Files
jellyfin-scene-search/scene_search/frame_source.py
T

170 lines
5.5 KiB
Python

from __future__ import annotations
import io
import threading
from collections import OrderedDict
from pathlib import Path
from typing import Any
from PIL import Image
from .config import settings
from .jellyfin import JellyfinClient, TrickplaySelection
from .paths import resolve_thumb_path
class FrameSource:
"""Loads frame imagery from Jellyfin Trickplay or local fallback thumbnails.
Jellyfin-backed rows use Jellyfin as the source of truth. Existing rows that
still contain old local thumb_path values are intentionally ignored when
Trickplay metadata is available, so no reindex is needed after this change.
"""
def __init__(
self,
client: JellyfinClient | None = None,
*,
sheet_cache_size: int = 4,
) -> None:
self._client = client
self.sheet_cache_size = max(1, sheet_cache_size)
self._selection_cache: dict[str, TrickplaySelection] = {}
self._sheet_cache: OrderedDict[
tuple[str, int, int, str | None], Image.Image
] = OrderedDict()
self._lock = threading.Lock()
@property
def client(self) -> JellyfinClient:
if self._client is None:
self._client = JellyfinClient(
settings.jellyfin_url,
settings.jellyfin_api_key,
settings.jellyfin_timeout_seconds,
)
return self._client
@staticmethod
def is_jellyfin_trickplay(row: Any) -> bool:
return (
str(row["source_kind"] or "") == "jellyfin"
and bool(row["jellyfin_item_id"])
and row["trickplay_width"] is not None
)
def _selection(self, row: Any) -> TrickplaySelection:
item_id = str(row["jellyfin_item_id"])
cached = self._selection_cache.get(item_id)
if cached is not None:
return cached
detail = self.client.item(item_id)
preferred_width = int(row["trickplay_width"])
selection = self.client.select_trickplay(
detail,
preferred_width,
str(row["jellyfin_media_source_id"] or "") or None,
)
if selection is None:
raise RuntimeError(
f"Jellyfin item {item_id} no longer exposes Trickplay data"
)
self._selection_cache[item_id] = selection
return selection
def _sheet(
self,
item_id: str,
selection: TrickplaySelection,
sheet_index: int,
) -> Image.Image:
key = (
item_id,
selection.width,
sheet_index,
selection.media_source_id,
)
cached = self._sheet_cache.get(key)
if cached is not None:
self._sheet_cache.move_to_end(key)
return cached
raw = self.client.trickplay_sheet_bytes(
item_id,
selection,
sheet_index,
)
with Image.open(io.BytesIO(raw)) as opened:
sheet = opened.convert("RGB")
self._sheet_cache[key] = sheet
self._sheet_cache.move_to_end(key)
while len(self._sheet_cache) > self.sheet_cache_size:
_, old = self._sheet_cache.popitem(last=False)
old.close()
return sheet
def image(self, row: Any) -> Image.Image:
with self._lock:
if not self.is_jellyfin_trickplay(row):
path = resolve_thumb_path(str(row["thumb_path"]))
if not path.is_file():
raise FileNotFoundError(path)
with Image.open(path) as image:
return image.convert("RGB")
item_id = str(row["jellyfin_item_id"])
try:
selection = self._selection(row)
frame_number = int(row["frame_number"])
capacity = selection.thumbnails_per_sheet
sheet_index = frame_number // capacity
local_index = frame_number % capacity
sheet = self._sheet(item_id, selection, sheet_index)
column = local_index % selection.tile_columns
tile_row = local_index // selection.tile_columns
left = column * selection.width
top = tile_row * selection.height
return sheet.crop(
(
left,
top,
left + selection.width,
top + selection.height,
)
)
except Exception:
# Migration safety: old canonical rows may still point at
# duplicated local JPEGs. Use those only as a fallback if
# Jellyfin cannot currently serve the matching Trickplay tile.
legacy = resolve_thumb_path(str(row["thumb_path"]))
if legacy.is_file():
with Image.open(legacy) as image:
return image.convert("RGB")
raise
def jpeg_bytes(self, row: Any, *, quality: int = 90) -> bytes:
image = self.image(row)
try:
out = io.BytesIO()
image.save(out, "JPEG", quality=quality)
return out.getvalue()
finally:
image.close()
def close(self) -> None:
with self._lock:
for sheet in self._sheet_cache.values():
sheet.close()
self._sheet_cache.clear()
def __enter__(self) -> "FrameSource":
return self
def __exit__(self, *_: object) -> None:
self.close()