from __future__ import annotations import io import unittest from PIL import Image from scene_search.frame_source import FrameSource from scene_search.jellyfin import TrickplaySelection class FakeJellyfinClient: def __init__(self) -> None: self.selection = TrickplaySelection( media_source_id="source-1", width=2, height=1, interval_ms=10000, thumbnail_count=4, tile_columns=2, tile_rows=2, ) sheet = Image.new("RGB", (4, 2)) sheet.putpixel((0, 0), (255, 0, 0)) sheet.putpixel((2, 0), (0, 255, 0)) sheet.putpixel((0, 1), (0, 0, 255)) sheet.putpixel((2, 1), (255, 255, 0)) out = io.BytesIO() sheet.save(out, "JPEG", quality=100, subsampling=0) sheet.close() self.sheet_bytes = out.getvalue() self.sheet_requests = 0 def item(self, item_id: str) -> dict: return {"Id": item_id} def select_trickplay( self, item: dict, preferred_width: int = 320, preferred_media_source_id: str | None = None, ) -> TrickplaySelection: self.assertions = ( preferred_width, preferred_media_source_id, ) return self.selection def trickplay_sheet_bytes( self, item_id: str, selection: TrickplaySelection, sheet_index: int, ) -> bytes: self.sheet_requests += 1 if sheet_index != 0: raise AssertionError(sheet_index) return self.sheet_bytes class FrameSourceTests(unittest.TestCase): def test_jellyfin_row_uses_trickplay_even_with_legacy_thumb_path(self) -> None: client = FakeJellyfinClient() row = { "source_kind": "jellyfin", "jellyfin_item_id": "item-1", "jellyfin_media_source_id": "source-1", "trickplay_width": 2, "frame_number": 2, "thumb_path": "/definitely/not/a/real/legacy/frame.jpg", } with FrameSource(client, sheet_cache_size=1) as source: image = source.image(row) try: pixel = image.getpixel((0, 0)) finally: image.close() self.assertEqual(client.assertions, (2, "source-1")) self.assertEqual(client.sheet_requests, 1) # JPEG round-trip is lossy, so verify the third tile is predominantly blue. self.assertGreater(pixel[2], pixel[0]) self.assertGreater(pixel[2], pixel[1]) def test_multiple_frames_reuse_one_trickplay_sheet(self) -> None: client = FakeJellyfinClient() base = { "source_kind": "jellyfin", "jellyfin_item_id": "item-1", "jellyfin_media_source_id": "source-1", "trickplay_width": 2, "thumb_path": "jellyfin://item-1/trickplay/2", } with FrameSource(client, sheet_cache_size=1) as source: for frame_number in (0, 1, 2, 3): row = {**base, "frame_number": frame_number} image = source.image(row) image.close() self.assertEqual(client.sheet_requests, 1) if __name__ == "__main__": unittest.main()