Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.
TypeScript ai-artartificial-intelligencegenerative-artimage-generationimg2imginpaintinglatent-diffusionlinuxmacosoutpaintingstable-diffusiontxt2imgwindows
fix(videos): pick gallery thumbnails from a scored seek ladder
Lincoln Stein438f1bb0c124
diff --git a/docs/src/content/docs/features/gallery.mdx b/docs/src/content/docs/features/gallery.mdxindex 5cb3694c92..941e5accc6 100644--- a/docs/src/content/docs/features/gallery.mdx+++ b/docs/src/content/docs/features/gallery.mdx@@ -146,7 +146,7 @@ A deletion removes the image's gallery record first and its files immediately af## Videos in the Gallery-Videos generated by InvokeAI (currently from the Wan 2.2 model family) appear alongside images in the same gallery view. Each video item displays a first-frame still as its thumbnail with a play badge in the corner; selecting it opens the video in the viewer where you can play it back inline.+Videos generated by InvokeAI (currently from the Wan 2.2 model family) appear alongside images in the same gallery view. Each video item displays a representative still as its thumbnail (a frame chosen to skip black lead-ins, fades and title cards) with a play badge in the corner; selecting it opens the video in the viewer where you can play it back inline.### Uploading Videos and Audiodiff --git a/invokeai/app/api/routers/videos.py b/invokeai/app/api/routers/videos.pyindex e41a049415..b830f396fa 100644--- a/invokeai/app/api/routers/videos.py+++ b/invokeai/app/api/routers/videos.py@@ -383,14 +383,14 @@ def _probe_decodable_video(path: Path) -> tuple[tuple[int, int, float, Optional["""Probes metadata and proves the video has a decodable frame.Returns the metadata plus the decoded frame so the save path can reuse it as the- thumbnail source instead of spawning another decode worker. The frame is taken ~1s into- the clip (see representative_thumbnail_frame_index) rather than at index 0 — first- frames are routinely unrepresentative (fade-ins, the synthesized waveform track's empty- first window) — with a frame-0 fallback inside the helper. Acceptance is thereby- slightly WIDER than before: a file whose frame 0 is corrupt but whose ~1s frame decodes- is now accepted rather than 415'd. A decode timeout is contention on a loaded server, not evidence the video is- bad — probe_video already succeeded — so it yields (metadata, None) and the upload- proceeds, with save-time thumbnail extraction as the backstop.+ thumbnail source instead of spawning another decode worker. The frame comes from the+ thumbnail seek ladder (see extract_representative_video_frame): the first informative+ frame found starting ~1s in, else the best-scoring one, with frame 0 as the last rung.+ Acceptance is thereby slightly WIDER than a frame-0 check: a file whose frame 0 is+ corrupt but whose later frame decodes is accepted rather than 415'd. A decode timeout+ is contention on a loaded server, not evidence the video is bad — probe_video already+ succeeded — so it yields (metadata, None) and the upload proceeds, with save-time+ thumbnail extraction as the backstop."""width, height, duration, fps, codec = probe_video_with_codec(path)if codec is None or codec.lower() not in {"h264", "avc", "avc1", "libx264"}:@@ -897,7 +897,7 @@ def get_video_thumbnail(current_user: CurrentMediaUserOrDefault,video_name: str = PathParam(description="The name of thumbnail file to get"),) -> Response:- """Returns the first-frame WebP thumbnail of an authorized video."""+ """Returns the WebP thumbnail of an authorized video."""_assert_video_read_access(video_name, current_user)try:path = ApiDependencies.invoker.services.videos.get_path(video_name, thumbnail=True)diff --git a/invokeai/app/services/urls/urls_base.py b/invokeai/app/services/urls/urls_base.pyindex c566f03f30..f91cedde8b 100644--- a/invokeai/app/services/urls/urls_base.py+++ b/invokeai/app/services/urls/urls_base.py@@ -11,7 +11,7 @@ class UrlServiceBase(ABC):@abstractmethoddef get_video_url(self, video_name: str, thumbnail: bool = False) -> str:- """Gets the URL for a video or its first-frame thumbnail."""+ """Gets the URL for a video or its thumbnail."""pass@abstractmethoddiff --git a/invokeai/app/services/video_files/video_files_base.py b/invokeai/app/services/video_files/video_files_base.pyindex 32100e7cc7..f9570aa267 100644--- a/invokeai/app/services/video_files/video_files_base.py+++ b/invokeai/app/services/video_files/video_files_base.py@@ -30,10 +30,10 @@ class VideoFileStorageBase(ABC):) -> None:"""Saves a video by moving the file at `source_path` into storage, then writes a siblingWEBP thumbnail, plus an optional sidecar JSON of metadata/workflow/graph.- The thumbnail is extracted from a representative frame (~1s in; see- ``representative_thumbnail_frame_index``), located using ``duration``/``fps`` when the- caller knows them. A caller that already decoded a representative frame can pass it as- `first_frame` to skip the extraction.+ The thumbnail is extracted from a representative frame (the first informative one on a+ seek ladder starting ~1s in; see ``extract_representative_video_frame``), located using+ ``duration``/``fps`` when the caller knows them. A caller that already decoded a+ representative frame can pass it as `first_frame` to skip the extraction.`source_path` is **consumed** by default: almost every caller hands over a temp file it justwrote, and moving it is both cheaper and the correct lifetime. A caller whose source is adiff --git a/invokeai/app/services/video_files/video_files_disk.py b/invokeai/app/services/video_files/video_files_disk.pyindex c4e36d9912..66b32b8644 100644--- a/invokeai/app/services/video_files/video_files_disk.py+++ b/invokeai/app/services/video_files/video_files_disk.py@@ -27,7 +27,7 @@ class _StagedDelete:class DiskVideoFileStorage(VideoFileStorageBase):- """Stores video files on disk under {outputs}/videos/, with first-frame WebP thumbnails under+ """Stores video files on disk under {outputs}/videos/, with representative-frame WebP thumbnails under{outputs}/videos/thumbnails/ and optional JSON sidecars for metadata/workflow/graph under{outputs}/videos/sidecars/."""@@ -83,8 +83,8 @@ class DiskVideoFileStorage(VideoFileStorageBase):# the video record + file in place and the invocation to complete. A missing# thumbnail leaves the gallery with a broken-image placeholder for that item, which# is annoying but not fatal. The upload path already decoded a representative frame- # to prove decodability and passes it in, saving a decode-worker subprocess per- # upload; this fallback picks the same ~1s-in frame for generated/derived videos.+ # to prove decodability and passes it in, saving the decode-worker spawns per+ # upload; this fallback runs the same seek ladder for generated/derived videos.frame = first_frameif frame is None:try:diff --git a/invokeai/app/services/videos/videos_base.py b/invokeai/app/services/videos/videos_base.pyindex 42f2f6ddea..f1cb64fb2c 100644--- a/invokeai/app/services/videos/videos_base.py+++ b/invokeai/app/services/videos/videos_base.py@@ -65,8 +65,8 @@ class VideoServiceABC(ABC):) -> VideoDTO:"""Creates a video by moving the file at `source_path` into storage and recording it.- ``first_frame``, when provided (e.g. the upload path already decoded frame 0 to- prove decodability), is used as the thumbnail source instead of spawning another+ ``first_frame``, when provided (e.g. the upload path already decoded a representative+ frame to prove decodability), is used as the thumbnail source instead of spawning anotherdecode worker.``source_path`` is consumed unless ``move_source=False``. Every caller that hands over adiff --git a/invokeai/app/util/video_thumbnails.py b/invokeai/app/util/video_thumbnails.pyindex b7e9e8fcb7..7cc13b9d58 100644--- a/invokeai/app/util/video_thumbnails.py+++ b/invokeai/app/util/video_thumbnails.py@@ -24,7 +24,7 @@ import tempfileimport threadingimport timefrom pathlib import Path-from typing import Any, Callable, Iterator, Optional+from typing import Any, Callable, Iterator, NamedTuple, Optionalimport numpy as npimport psutil@@ -401,7 +401,7 @@ def extract_video_frame(Path(tmp_name).unlink(missing_ok=True)-# Where in a clip the gallery thumbnail is taken from. Frame 0 is a poor representative:+# Where in a clip the gallery thumbnail search starts. Frame 0 is a poor representative:# generated videos commonly fade in from black or start on a conditioning frame, and an# audio-only upload wrapped in a synthesized waveform track (see video_ingest.py) renders its# first frame from a near-empty audio window — an all-black tile. About a second in, capped at@@ -411,20 +411,150 @@ THUMBNAIL_FRAME_TARGET_SECONDS = 1.0# synthesized waveform track's rate.THUMBNAIL_FRAME_FALLBACK_FPS = 24.0+# Where to look when the frame at the first rung decodes but is empty (see+# FrameScore.informative): the long fade-in or title-sequence case, which no fixed offset can+# cover because it scales with the runtime. Fractions of the duration; a candidate must land+# meaningfully *later* than the frame just rejected, which is what walks the ladder forward+# past a title sequence rather than back into it. More fractions than MAX_DEEPER_SEEK_ATTEMPTS+# on purpose: the early ones are unusable on a short clip and get skipped.+DEEPER_SEEK_FRACTIONS: tuple[float, ...] = (0.1, 0.35, 0.6)+MIN_DEEPER_SEEK_GAP_SECONDS = 1.0+# Ceiling on the deeper rungs. Each attempt costs a decode-worker spawn, and the upload+# path runs this inside the request. With the opening rung and the frame-0 walk-back the+# search is at most MAX_DEEPER_SEEK_ATTEMPTS + 2 decodes.+MAX_DEEPER_SEEK_ATTEMPTS = 2++# A candidate frame passes three gates read off one luma histogram: it is not flat, not+# dark, and not mostly one level. The first two thresholds are ported from PhotoMapAI, which+# calibrated them against a labelled corpus of synthetic-but-realistic frames and real+# encodes; the third was added after the first two let real title cards through (see+# FRAME_FLAT_FRACTION_CEILING). Erring towards rejection is deliberate throughout: a frame+# wrongly called empty only costs another decode, and the best-scoring frame is returned+# either way; a frame wrongly kept is the black thumbnail this whole search exists to avoid.+#+# Shannon entropy of the luma histogram, in bits, below which a frame is flat: a black+# screen, a solid slate, a fade. Junk in the calibration corpus measured 0.0-0.8 bits (pure+# black 0.0, dense end credits ~0.65); real content starts around 1.1 even when almost+# entirely dark — a night skyline, fireworks against black, an overcast snowfield — because+# a dark *scene* has tone everywhere while a slate is one level.+FRAME_ENTROPY_FLOOR = 0.75++# Entropy measures flatness, not darkness, and the two come apart at the bottom of the+# range. A photograph dimmed to a peak luma of 2/255 — black to any viewer — still measures+# ~1.45 bits, because the dither spread across a handful of levels carries information;+# black carrying nothing but sensor noise measures ~1.27 after an x264 round trip. Both+# clear the entropy floor, and the floor cannot be raised to catch them: the dimmest real+# content in the calibration corpus measures 1.07. So darkness is asked about separately,+# as a high quantile of the luma histogram: "are there any genuinely bright pixels", not+# "is the average bright", so fireworks on a night sky survive. A quantile rather than the+# maximum, so one stuck pixel, a timecode burn-in or a logo cannot vouch for an otherwise+# black frame.+FRAME_HIGHLIGHT_QUANTILE = 0.999+# Between the junk band (a 1% fade measures 2, a 2% fade 5, black with sensor noise 7) and+# the dimmest frame accepted from a real library (32). Low rather than high because a+# rejected frame falls through to the entropy ranking, where grain over black outranks+# genuinely dim content: a frame has to be darker than anything with recoverable content+# before it is put at that risk.+FRAME_LUMA_FLOOR = 10.0++# Fraction of pixels within FRAME_FLAT_BAND luma levels of the most common level above+# which a frame is a card: titles, a logo or a caption on a solid background. Synthetic+# title cards measure 0.2-0.3 bits and fail the entropy floor, but real encoded ones do+# not reliably: three title cards from a real library measured 0.74, 0.80 and 0.94 bits,+# straddling the floor, because x264 ringing around anti-aliased text spreads a few percent+# of pixels across most of the histogram. What they have in common is the background: 93-96%+# of their pixels sit on one level, while no accepted frame from the same library exceeded+# 0.68 (a portrait on white seamless, a pillarboxed clip) and ordinary content sits below+# 0.1. The band absorbs codec noise on the background; the ceiling sits in the middle of the+# gap. A product shot or a slide with a large plain background can fail this gate, at the+# cost of the extra decodes only: every rung of such a clip fails alike, and the+# highest-entropy one is returned.+FRAME_FLAT_BAND = 2+FRAME_FLAT_FRACTION_CEILING = 0.9+++class FrameScore(NamedTuple):+ """The three histogram measures of a thumbnail candidate. See the gate constants above."""++ entropy: float+ highlight_luma: float+ flat_fraction: float++ @classmethod+ def measure(cls, frame: Image.Image) -> "FrameScore":+ """Scores ``frame`` from one luma histogram; an empty frame measures as kept."""+ histogram = frame.convert("L").histogram()+ total = sum(histogram)+ if not total:+ return cls(math.inf, 255.0, 0.0)+ entropy = -sum((count / total) * math.log2(count / total) for count in histogram if count)+ # Whole pixels, floored at one: a float headroom makes the boundary arbitrary+ # (1000 * (1 - 0.999) is 1.0000000000000009), and the floor keeps a frame of very+ # few pixels measurable. Read from white downwards, so it costs 256 steps, not a sort.+ headroom = max(1, int(total * (1.0 - FRAME_HIGHLIGHT_QUANTILE)))+ seen = 0+ highlight = 0.0+ for level in range(255, -1, -1):+ seen += histogram[level]+ if seen >= headroom:+ highlight = float(level)+ break+ mode = max(range(256), key=histogram.__getitem__)+ flat = sum(histogram[max(0, mode - FRAME_FLAT_BAND) : mode + FRAME_FLAT_BAND + 1]) / total+ return cls(entropy, highlight, flat)++ @property+ def gates_passed(self) -> int:+ return (+ int(self.entropy >= FRAME_ENTROPY_FLOOR)+ + int(self.highlight_luma >= FRAME_LUMA_FLOOR)+ + int(self.flat_fraction < FRAME_FLAT_FRACTION_CEILING)+ )++ @property+ def informative(self) -> bool:+ """All three gates have to hold: flat frames are slates, dark ones fades, mostly-one-level ones cards."""+ return self.gates_passed == 3++ @property+ def rank(self) -> tuple[int, float]:+ """Ordering among frames that failed: fewest gates failed, then entropy.-def representative_thumbnail_frame_index(duration: Optional[float], fps: Optional[float]) -> int:- """The frame index a gallery thumbnail should be taken from.+ Gates first because entropy alone ranks grain over black (~1.3 bits, fails the luma+ gate) above a legible title card (~0.8 bits, fails only the flat gate); when nothing+ better is reachable the card is the thumbnail a person would pick.+ """+ return (self.gates_passed, self.entropy)- Roughly THUMBNAIL_FRAME_TARGET_SECONDS into the clip, capped at its midpoint. Returns 0- when the duration is unknown or degenerate — callers without metadata keep today's- first-frame behavior. Both inputs are untrusted container metadata, so a non-finite value- degrades to the safe answer rather than raising.++def thumbnail_frame_candidates(duration: Optional[float], fps: Optional[float]) -> list[int]:+ """The frame indices a gallery thumbnail is tried from, in order.++ The opening rung is roughly THUMBNAIL_FRAME_TARGET_SECONDS in, capped at the clip's+ midpoint; then up to MAX_DEEPER_SEEK_ATTEMPTS rungs at DEEPER_SEEK_FRACTIONS of the+ duration, each meaningfully later than the last; then frame 0 as the walk-back, which+ doubles as the fallback for containers whose metadata overstates the decodable range.+ Returns ``[0]`` when the duration is unknown or degenerate — callers without metadata+ keep first-frame behavior. Both inputs are untrusted container metadata, so a+ non-finite value degrades to the safe answer rather than raising."""if duration is None or not math.isfinite(duration) or duration <= 0:- return 0+ return [0]effective_fps = fps if fps is not None and math.isfinite(fps) and fps > 0 else THUMBNAIL_FRAME_FALLBACK_FPS- target_seconds = min(THUMBNAIL_FRAME_TARGET_SECONDS, duration / 2)- return max(0, int(target_seconds * effective_fps))+ seconds = [min(THUMBNAIL_FRAME_TARGET_SECONDS, duration / 2)]+ for fraction in DEEPER_SEEK_FRACTIONS:+ if len(seconds) > MAX_DEEPER_SEEK_ATTEMPTS:+ break+ candidate = duration * fraction+ if candidate >= seconds[-1] + MIN_DEEPER_SEEK_GAP_SECONDS:+ seconds.append(candidate)+ candidates: list[int] = []+ # Finite inputs can still multiply to infinity; such a rung cannot be decoded, so it is+ # dropped rather than raised on.+ for index in [*(int(offset * effective_fps) for offset in seconds if math.isfinite(offset * effective_fps)), 0]:+ if index not in candidates:+ candidates.append(index)+ return candidatesdef extract_representative_video_frame(@@ -434,29 +564,57 @@ def extract_representative_video_frame(timeout: float = VIDEO_DECODE_TIMEOUT_SECONDS,raise_on_timeout: bool = False,) -> Optional[Image.Image]:- """Extracts the representative thumbnail frame, falling back to frame 0.-- The fallback covers containers whose metadata overstates the decodable range (the- computed index then has no frame): such files still get a thumbnail rather than a- gallery placeholder. In the worst case — a slow decode *failure* at the representative- index — the fallback costs a second decode budget, bounding one call at two timeouts.-- A timeout is never retried, in either mode: it is contention or an adversarial file,- not evidence about the index, and a retry would hold a request worker for another full- budget. Timeouts are detected by always raising internally; with ``raise_on_timeout``- the VideoDecodeTimeoutError propagates, otherwise the call returns None as- ``extract_video_frame`` would.+ """Extracts the thumbnail frame: the first informative one on the seek ladder, else the best.++ Walks thumbnail_frame_candidates in order and returns the first frame FrameScore calls+ informative. If every reachable frame is empty — a clip that really is all dark, or the+ waveform track wrapping an audio upload — the best-ranked frame seen is returned, so the+ video still gets a thumbnail rather than a gallery placeholder; the waveform case thereby+ lands on the busiest window of the track.++ An opening rung with no decodable frame means the metadata overstates the range or the+ file is damaged there; the deeper rungs are later still, so the search goes straight to+ the frame-0 walk-back rather than spending the budget proving each one empty.++ The whole search shares one budget of two ``timeout``s, the same worst case the+ two-attempt version had (a slow decode *failure* followed by a full fallback decode).+ A timeout, or an exhausted budget, ends the search: it is contention or an adversarial+ file, not evidence about the index, and another rung would hold a request worker for+ another full budget. If a frame was already decoded it is returned — a dark thumbnail+ beats none — otherwise the VideoDecodeTimeoutError propagates with ``raise_on_timeout``+ and the call returns None without it, as ``extract_video_frame`` would."""- frame_index = representative_thumbnail_frame_index(duration, fps)+ queue = thumbnail_frame_candidates(duration, fps)+ opening = queue[0]+ best: Optional[tuple[tuple[int, float], Image.Image]] = None+ deadline = time.monotonic() + 2 * timeouttry:- frame = extract_video_frame(video_path, frame_index=frame_index, timeout=timeout, raise_on_timeout=True)- if frame is None and frame_index > 0:- frame = extract_video_frame(video_path, frame_index=0, timeout=timeout, raise_on_timeout=True)+ while queue:+ frame_index = queue.pop(0)+ remaining = deadline - time.monotonic()+ if remaining <= 0:+ raise VideoDecodeTimeoutError(f"Thumbnail search for {video_path} exhausted its {2 * timeout}s budget")+ frame = extract_video_frame(+ video_path, frame_index=frame_index, timeout=min(timeout, remaining), raise_on_timeout=True+ )+ if frame is None:+ if frame_index == opening and queue:+ queue = [queue[-1]]+ continue+ score = FrameScore.measure(frame)+ if score.informative:+ return frame+ if best is None or score.rank > best[0]:+ best = (score.rank, frame)+ # Frames can be up to MAX_VIDEO_FRAME_PIXELS; don't hold a rejected one across+ # the next decode.+ del frameexcept VideoDecodeTimeoutError:- if raise_on_timeout:- raise- return None- return frame+ if best is None:+ if raise_on_timeout:+ raise+ return None+ return best[1] if best is not None else Nonedef probe_video_with_codec(diff --git a/tests/app/services/video_files/test_video_files_disk.py b/tests/app/services/video_files/test_video_files_disk.pyindex d8c6a44dcc..e6b2cf54ec 100644--- a/tests/app/services/video_files/test_video_files_disk.py+++ b/tests/app/services/video_files/test_video_files_disk.py@@ -11,6 +11,7 @@ from pathlib import Pathfrom unittest.mock import MagicMockimport pytest+from PIL import Imagefrom invokeai.app.services.video_files.video_files_common import VideoFileSaveExceptionfrom invokeai.app.services.video_files.video_files_disk import DiskVideoFileStorage@@ -45,6 +46,25 @@ def test_save_writes_video_and_sidecar(storage: DiskVideoFileStorage, tmp_path:assert storage.get_workflow(VIDEO_NAME) is None # sidecar readable, workflow not set+def test_save_uses_a_passed_first_frame_instead_of_running_the_ladder(+ storage: DiskVideoFileStorage, tmp_path: Path, monkeypatch: pytest.MonkeyPatch+):+ """The upload path decodes a frame to prove decodability and hands it over; running the+ seek ladder again would cost up to four more decode-worker spawns inside the request."""+ source = _make_source(tmp_path)+ calls: list[Path] = []+ monkeypatch.setattr(+ "invokeai.app.services.video_files.video_files_disk.extract_representative_video_frame",+ lambda path, *args, **kwargs: calls.append(path),+ )++ storage.save(source_path=source, video_name=VIDEO_NAME, first_frame=Image.new("RGB", (48, 32), (200, 90, 40)))++ assert calls == []+ with Image.open(storage.get_path(VIDEO_NAME.replace(".mp4", ".webp"), thumbnail=True)) as thumbnail:+ assert thumbnail.size == (48, 32)++def test_save_with_move_source_false_leaves_the_source_intact(storage: DiskVideoFileStorage, tmp_path: Path):"""Copying a video the server already owns must not consume it.diff --git a/tests/app/util/test_video_thumbnails.py b/tests/app/util/test_video_thumbnails.pyindex 548b701e95..a11b603e52 100644--- a/tests/app/util/test_video_thumbnails.py+++ b/tests/app/util/test_video_thumbnails.py@@ -24,10 +24,17 @@ from unittest.mock import MagicMockimport imageio.v3 as iioimport numpy as npimport pytest+from PIL import Image, ImageDraw, ImageFontfrom invokeai.app.services.session_processor.session_processor_common import CanceledExceptionfrom invokeai.app.util import video_decode_worker, video_thumbnails-from invokeai.app.util.video_thumbnails import decoder_frame_count, extract_video_frame, iter_video_frames, probe_video+from invokeai.app.util.video_thumbnails import (+ FrameScore,+ decoder_frame_count,+ extract_video_frame,+ iter_video_frames,+ probe_video,+)FRAMES = 12FPS = 8.0@@ -707,122 +714,380 @@ class TestDecodedFrameValidation:video_decode_worker._validate_decoded_frame(frame)-class TestRepresentativeThumbnailFrame:- """The gallery thumbnail is taken ~1s in (capped at the clip midpoint), not at frame 0 —- first frames are routinely black (fade-ins, the waveform wrap's empty first window)."""+def _solid(color: tuple[int, int, int], size: tuple[int, int] = (320, 180)) -> Image.Image:+ return Image.new("RGB", size, color)+++def _textured(size: tuple[int, int] = (320, 180), brightness: float = 1.0) -> Image.Image:+ """A photograph stand-in: smooth colour gradients with a little grain, dimmable."""+ width, height = size+ y, x = np.mgrid[0:height, 0:width]+ rng = np.random.default_rng(7)+ base = np.stack([40 + x * 0.6, 60 + y, 250 - x * 0.5], axis=-1) + rng.normal(0, 3, (height, width, 3))+ return Image.fromarray(np.clip(base * brightness, 0, 255).astype(np.uint8))+++def _title_card(size: tuple[int, int] = (640, 360), noise: float = 1.2) -> Image.Image:+ """Three lines of anti-aliased text on black, over the kind of grain an x264 round trip+ leaves on a black background. Three real title cards measured 0.74-0.94 bits with 93-96%+ of pixels on the background level; at this noise the synthetic one measures ~1.1 bits."""+ rng = np.random.default_rng(3)+ background = np.clip(rng.normal(0, noise, (size[1], size[0])), 0, 255).astype(np.uint8)+ frame = Image.fromarray(np.repeat(background[:, :, None], 3, axis=2))+ draw = ImageDraw.Draw(frame)+ font = ImageFont.load_default(size=size[1] // 10)+ y = size[1] // 2 - 3 * size[1] // 16+ for line in ("Chocolate", "Covered", "Cherry"):+ draw.text(((size[0] - draw.textlength(line, font=font)) / 2, y), line, fill=(255, 255, 255), font=font)+ y += size[1] // 8+ return frame+++def _score(frame: Image.Image) -> FrameScore:+ return FrameScore.measure(frame)+++class TestFrameScoring:+ """The three gates a thumbnail candidate has to pass: not flat (entropy), not dark+ (highlight luma) and not a card (background occupancy)."""++ def test_solid_frames_carry_no_information(self) -> None:+ for color in ((0, 0, 0), (128, 128, 128), (40, 90, 200)):+ assert _score(_solid(color)).entropy == 0.0+ assert not _score(_solid(color)).informative++ def test_titles_over_black_score_below_the_entropy_floor(self) -> None:+ """Two levels carry almost nothing however sharp the text, and why the score is+ entropy rather than contrast (the standard deviation of this frame is enormous)."""+ assert _score(_title_card(noise=0.0)).entropy < video_thumbnails.FRAME_ENTROPY_FLOOR+ assert not _score(_title_card(noise=0.0)).informative++ def test_an_encoded_title_card_is_rejected_by_the_flat_gate(self) -> None:+ """Codec grain around anti-aliased text lifts a real title card over the entropy floor+ (three from a real library straddled it), and its text is bright, so the first two+ gates pass. What gives it away is that nearly every pixel sits on one level."""+ score = _score(_title_card())+ assert score.entropy > video_thumbnails.FRAME_ENTROPY_FLOOR, "the entropy gate alone would keep it"+ assert score.highlight_luma >= video_thumbnails.FRAME_LUMA_FLOOR, "the luma gate alone would keep it"+ assert score.flat_fraction >= video_thumbnails.FRAME_FLAT_FRACTION_CEILING+ assert not score.informative++ def test_a_dark_but_real_scene_is_kept(self) -> None:+ """A night scene is almost entirely dark, so a dark-pixel count would reject it; what+ separates it from a title card is tone everywhere rather than two levels."""+ frame = Image.new("RGB", (320, 180))+ frame.putdata([(v // 8, v // 8, max(0, v // 8 - 2)) for v in range(180) for _ in range(320)])+ assert _score(frame).entropy > video_thumbnails.FRAME_ENTROPY_FLOOR+ assert _score(frame).informative++ def test_ordinary_content_is_nowhere_near_the_gates(self) -> None:+ score = _score(_textured())+ assert score.entropy > 4 * video_thumbnails.FRAME_ENTROPY_FLOOR+ assert score.flat_fraction < 0.2+ assert score.informative++ def test_a_fade_to_black_is_rejected_though_its_entropy_passes(self) -> None:+ """A photograph dimmed to a peak luma of ~2/255 is black to any viewer, but the grain+ spread over a few levels clears the entropy floor. Only the highlight gate catches it."""+ score = _score(_textured(brightness=0.01))+ assert score.entropy > video_thumbnails.FRAME_ENTROPY_FLOOR+ assert score.highlight_luma < video_thumbnails.FRAME_LUMA_FLOOR+ assert not score.informative++ def test_black_carrying_only_sensor_noise_is_rejected(self) -> None:+ rng = np.random.default_rng(11)+ noise = np.clip(rng.normal(6, 0.5, (180, 320)), 0, 255).astype(np.uint8)+ score = _score(Image.fromarray(np.repeat(noise[:, :, None], 3, axis=2)))+ assert score.entropy > video_thumbnails.FRAME_ENTROPY_FLOOR+ assert not score.informative++ @pytest.mark.parametrize("brightness", [0.10, 0.15, 0.25])+ def test_a_dim_but_lit_scene_survives_the_luma_gate(self, brightness: float) -> None:+ """Dusk is not a fade. The gate must not cost real low-light footage."""+ assert _score(_textured(brightness=brightness)).informative++ def test_a_subject_on_a_plain_background_survives_the_flat_gate(self) -> None:+ """Fireworks on a night sky, a pillarboxed phone video, a portrait on white seamless:+ overwhelmingly one level, yet with a real subject filling a good part of the frame. A+ mean-luma test would throw the dark ones away, and a flat gate set too low would+ throw all of them away — real accepted frames reach 0.68 on this measure."""+ for background in ((2, 2, 4), (255, 255, 255)):+ frame = Image.new("RGB", (640, 360), background)+ frame.paste(_textured((200, 360)), (220, 0))+ score = _score(frame)+ assert 0.6 < score.flat_fraction < video_thumbnails.FRAME_FLAT_FRACTION_CEILING+ assert score.informative++ def test_a_sprinkle_of_hot_pixels_cannot_vouch_for_a_black_frame(self) -> None:+ """Why a quantile and not the maximum: a stuck pixel, a timecode burn-in or a logo is+ a handful of pixels. At 320x180 the 0.999 headroom is 57 pixels, so 40 must not+ count and 400 must."""+ frame = _textured(brightness=0.01)+ for i in range(40):+ frame.putpixel((i, 0), (255, 255, 255))+ assert np.asarray(frame.convert("L")).max() == 255+ assert _score(frame).highlight_luma < video_thumbnails.FRAME_LUMA_FLOOR+ for i in range(400):+ frame.putpixel((i % 320, 1 + i // 320), (255, 255, 255))+ assert _score(frame).highlight_luma == 255.0++ def test_a_pure_white_frame_is_not_scored_as_black(self) -> None:+ """The histogram walk starts at 255: off by one and an all-white frame falls through+ to 0.0 and fails the luma gate on top of the entropy one."""+ assert _score(_solid((255, 255, 255))).highlight_luma == 255.0++ def test_the_quantile_boundary_is_inclusive(self) -> None:+ """1000 px -> headroom int(1000 * 0.001) == 1, so a single bright pixel sits exactly+ on the boundary; a float headroom (1.0000000000000009) would miss it."""+ frame = Image.new("L", (1000, 1), 0)+ frame.putpixel((0, 0), 200)+ assert _score(frame.convert("RGB")).highlight_luma == 200.0++ @pytest.mark.parametrize("floor", [0, 253])+ def test_the_flat_band_absorbs_codec_noise_on_the_background(self, floor: int) -> None:+ """A background that decodes to three adjacent levels rather than exactly one still+ counts as one level, at both ends of the histogram; without the band the noisy title+ card would pass as 'many levels'."""+ rng = np.random.default_rng(5)+ background = rng.integers(floor, floor + 3, (180, 320)).astype(np.uint8)+ frame = Image.fromarray(np.repeat(background[:, :, None], 3, axis=2))+ assert _score(frame).flat_fraction == 1.0++ def test_an_empty_frame_is_kept(self) -> None:+ """An unmeasurable frame is never the reason to discard one."""+ assert _score(Image.new("RGB", (0, 0))).informative++ def test_a_legible_card_outranks_grain_over_black(self) -> None:+ """Among rejected frames, fewest failed gates wins before entropy: grain over black has+ more entropy than a title card, but the card is what a person would pick."""+ card = _score(_title_card())+ rng = np.random.default_rng(11)+ noise = np.clip(rng.normal(6, 0.5, (180, 320)), 0, 255).astype(np.uint8)+ grain = _score(Image.fromarray(np.repeat(noise[:, :, None], 3, axis=2)))+ assert grain.entropy > card.entropy, "the case only matters if entropy alone would pick the grain"+ assert card.rank > grain.rank > _score(_solid((0, 0, 0))).rank+++class TestThumbnailFrameCandidates:+ """The seek ladder: ~1s in (capped at the midpoint), deeper rungs at fractions of the+ duration that each move meaningfully later, then frame 0 as the walk-back."""@pytest.mark.parametrize(("duration", "fps", "expected"),[- (None, 24.0, 0), # unknown duration -> keep first-frame behavior- (0.0, 24.0, 0),- (-1.0, 24.0, 0),- (float("inf"), 24.0, 0), # untrusted metadata degrades safely- (float("nan"), 24.0, 0),- (10.0, 24.0, 24), # long clip: 1s in- (10.0, 8.0, 8),- (1.0, 24.0, 12), # short clip: capped at the midpoint- (10.0, None, 24), # unknown fps -> 24 fps assumption- (10.0, 0.0, 24),- (10.0, float("inf"), 24),- (0.01, 24.0, 0), # sub-frame midpoint resolves to frame 0+ (None, 24.0, [0]), # unknown duration -> first-frame behavior+ (0.0, 24.0, [0]),+ (-1.0, 24.0, [0]),+ (float("inf"), 24.0, [0]), # untrusted metadata degrades safely+ (float("nan"), 24.0, [0]),+ (10.0, 24.0, [24, 84, 144, 0]), # 1s, then 0.35 and 0.6 (0.1 is too close to 1s)+ (10.0, 8.0, [8, 28, 48, 0]),+ (5.0, 24.0, [24, 72, 0]), # a generated clip: only the 0.6 rung clears the gap+ (2.0, 24.0, [24, 0]), # every deeper rung is within a second of the opening one+ (1.0, 24.0, [12, 0]), # short clip: opening rung capped at the midpoint+ (10.0, None, [24, 84, 144, 0]), # unknown fps -> 24 fps assumption+ (10.0, 0.0, [24, 84, 144, 0]),+ (10.0, float("inf"), [24, 84, 144, 0]),+ (0.01, 24.0, [0]), # sub-frame midpoint resolves to frame 0 once+ (600.0, 24.0, [24, 1440, 5040, 0]), # long file: the 0.6 rung is over the cap],)- def test_index_selection(self, duration, fps, expected) -> None:- assert video_thumbnails.representative_thumbnail_frame_index(duration, fps) == expected-- def test_extracts_the_later_frame_through_the_worker(self, synthetic_mp4: Path) -> None:- """The synthetic clip brightens by 16 per frame, so the pixel value identifies the- frame: the representative extraction must not return frame 0."""- duration = FRAMES / FPS- expected_index = video_thumbnails.representative_thumbnail_frame_index(duration, FPS)- assert expected_index > 0- frame = video_thumbnails.extract_representative_video_frame(synthetic_mp4, duration, FPS)- assert frame is not None- value = np.asarray(frame)[0, 0, 0].astype(int)- assert abs(value - (32 + expected_index * 16)) <= 8- assert abs(value - 32) > 8 # decisively not frame 0+ def test_ladder(self, duration, fps, expected) -> None:+ assert video_thumbnails.thumbnail_frame_candidates(duration, fps) == expected++ @pytest.mark.parametrize("duration", [0.3, 1.2, 2.4, 3.0, 4.7, 30.0, 3600.0])+ def test_rungs_move_later_and_stay_inside_the_clip(self, duration: float) -> None:+ candidates = video_thumbnails.thumbnail_frame_candidates(duration, 24.0)+ rungs = candidates[:-1]+ assert candidates[-1] == 0+ assert rungs == sorted(set(rungs))+ assert len(rungs) <= 1 + video_thumbnails.MAX_DEEPER_SEEK_ATTEMPTS+ assert all(index / 24.0 <= 0.6 * duration for index in rungs)++ @pytest.mark.parametrize(("duration", "fps"), [(10.0, 1e308), (1.7e308, 24.0), (1e200, 1e200)])+ def test_finite_but_absurd_metadata_does_not_raise(self, duration: float, fps: float) -> None:+ """The inputs pass the finiteness guards but their product overflows; such a rung is+ dropped, never raised on (the callers would turn that into a 415 / a lost thumbnail)."""+ candidates = video_thumbnails.thumbnail_frame_candidates(duration, fps)+ assert candidates[-1] == 0+ assert all(isinstance(index, int) for index in candidates)- def test_falls_back_to_frame_zero_when_metadata_overstates(self, synthetic_mp4: Path) -> None:- """Container metadata is untrusted: fps/duration claiming frames that don't exist- (index 100 of a 12-frame clip) must still produce a thumbnail (frame 0), not a- gallery placeholder."""- frame = video_thumbnails.extract_representative_video_frame(synthetic_mp4, duration=10.0, fps=100.0)- assert frame is not None- value = np.asarray(frame)[0, 0, 0].astype(int)- assert abs(value - 32) <= 8 # frame 0- def test_fallback_calls_and_order(self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:+def ladder_mp4(tmp_path: Path) -> Path:+ """Six seconds at 8 fps: three seconds of black, then a textured scene. The ladder's+ opening rung (1s) and first deeper rung (2.1s) both land in the black lead-in."""+ path = tmp_path / "ladder.mp4"+ black = np.zeros((32, 48, 3), dtype=np.uint8)+ lit = np.asarray(_textured((48, 32)))+ frames = [black] * 24 + [lit] * 24+ iio.imwrite(path, frames, plugin="FFMPEG", codec="libx264", fps=FPS, macro_block_size=1)+ return path+++class TestRepresentativeThumbnailFrame:+ """The gallery thumbnail is the first informative frame on the seek ladder, else the best+ of the empty ones — never a black lead-in or title card when the clip has more to offer."""++ def _fake_extract(self, monkeypatch: pytest.MonkeyPatch, served: dict[int, object]) -> list[int]:calls: list[int] = []def fake_extract(path, frame_index=0, timeout=0.0, raise_on_timeout=False):calls.append(frame_index)- return None if frame_index > 0 else MagicMock()+ result = served[frame_index]+ if isinstance(result, Exception):+ raise result+ return resultmonkeypatch.setattr(video_thumbnails, "extract_video_frame", fake_extract)+ return calls++ def test_returns_the_first_informative_frame(self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:+ lit = _textured()+ calls = self._fake_extract(monkeypatch, {24: _solid((0, 0, 0)), 84: lit})frame = video_thumbnails.extract_representative_video_frame(tmp_path / "v.mp4", duration=10.0, fps=24.0)- assert frame is not None+ assert frame is lit+ assert calls == [24, 84]++ def test_returns_the_best_empty_frame_when_the_whole_ladder_is_empty(+ self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path+ ) -> None:+ """A clip that really is all dark still gets a thumbnail — the least empty one, which+ for the waveform track wrapping an audio upload is the busiest window."""+ fade = _textured(brightness=0.01)+ card = _title_card()+ calls = self._fake_extract(monkeypatch, {24: _solid((0, 0, 0)), 84: fade, 144: card, 0: _solid((0, 0, 0))})+ frame = video_thumbnails.extract_representative_video_frame(tmp_path / "v.mp4", duration=10.0, fps=24.0)+ assert frame is card+ assert calls == [24, 84, 144, 0]++ def test_an_opening_rung_with_no_frame_goes_straight_to_the_walk_back(+ self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path+ ) -> None:+ """No frame ~1s in means the metadata overstates the range or the file is damaged+ there; the deeper rungs are later still, so proving them empty would only spend+ worker spawns and budget that the frame-0 walk-back needs."""+ lit = _textured()+ calls = self._fake_extract(monkeypatch, {24: None, 0: lit})+ frame = video_thumbnails.extract_representative_video_frame(tmp_path / "v.mp4", duration=10.0, fps=24.0)+ assert frame is litassert calls == [24, 0]- def test_no_fallback_when_index_is_zero(self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:+ def test_a_deeper_rung_with_no_frame_is_skipped(self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:+ lit = _textured()+ calls = self._fake_extract(monkeypatch, {24: _solid((0, 0, 0)), 84: None, 144: lit})+ frame = video_thumbnails.extract_representative_video_frame(tmp_path / "v.mp4", duration=10.0, fps=24.0)+ assert frame is lit+ assert calls == [24, 84, 144]++ @pytest.mark.parametrize("raise_on_timeout", [True, False])+ def test_an_exhausted_budget_is_a_timeout_not_a_missing_frame(+ self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path, raise_on_timeout: bool+ ) -> None:+ """A rung that fails slowly without tripping its own timeout can leave no budget for+ the rest. That is inconclusive, like a timeout — the upload path must not 415 it as+ 'no decodable frame'."""+ clock = [0.0]calls: list[int] = []- def fake_extract(path, frame_index=0, timeout=0.0, raise_on_timeout=False):+ def slow_failure(path, frame_index=0, timeout=0.0, raise_on_timeout=False):calls.append(frame_index)+ clock[0] += 25.0return None- monkeypatch.setattr(video_thumbnails, "extract_video_frame", fake_extract)+ monkeypatch.setattr(video_thumbnails.time, "monotonic", lambda: clock[0])+ monkeypatch.setattr(video_thumbnails, "extract_video_frame", slow_failure)+ if raise_on_timeout:+ with pytest.raises(video_thumbnails.VideoDecodeTimeoutError):+ video_thumbnails.extract_representative_video_frame(+ tmp_path / "v.mp4", duration=10.0, fps=24.0, timeout=10.0, raise_on_timeout=True+ )+ else:+ assert (+ video_thumbnails.extract_representative_video_frame(+ tmp_path / "v.mp4", duration=10.0, fps=24.0, timeout=10.0, raise_on_timeout=False+ )+ is None+ )+ assert calls == [24]++ def test_single_attempt_when_the_duration_is_unknown(self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:+ calls = self._fake_extract(monkeypatch, {0: None})assert video_thumbnails.extract_representative_video_frame(tmp_path / "v.mp4", duration=None, fps=None) is Noneassert calls == [0]- def test_timeout_propagates_without_a_second_decode(self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:- """A timeout is contention, not evidence about the frame index — retrying at frame 0- would double the time an adversarial upload holds a request worker."""- calls: list[int] = []-- def fake_extract(path, frame_index=0, timeout=0.0, raise_on_timeout=False):- calls.append(frame_index)- raise video_thumbnails.VideoDecodeTimeoutError("busy")-- monkeypatch.setattr(video_thumbnails, "extract_video_frame", fake_extract)- with pytest.raises(video_thumbnails.VideoDecodeTimeoutError):- video_thumbnails.extract_representative_video_frame(- tmp_path / "v.mp4", duration=10.0, fps=24.0, raise_on_timeout=True+ @pytest.mark.parametrize("raise_on_timeout", [True, False])+ def test_timeout_before_any_frame_ends_the_search(+ self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path, raise_on_timeout: bool+ ) -> None:+ """A timeout is contention, not evidence about the frame index — another rung would+ hold a request worker for another full budget. Raise mode propagates; the disk+ store's non-raise mode gets None."""+ calls = self._fake_extract(monkeypatch, {24: video_thumbnails.VideoDecodeTimeoutError("busy")})+ if raise_on_timeout:+ with pytest.raises(video_thumbnails.VideoDecodeTimeoutError):+ video_thumbnails.extract_representative_video_frame(+ tmp_path / "v.mp4", duration=10.0, fps=24.0, raise_on_timeout=True+ )+ else:+ assert (+ video_thumbnails.extract_representative_video_frame(+ tmp_path / "v.mp4", duration=10.0, fps=24.0, raise_on_timeout=False+ )+ is None)assert calls == [24]- def test_timeout_in_non_raise_mode_returns_none_without_retry(- self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path+ @pytest.mark.parametrize("raise_on_timeout", [True, False])+ def test_timeout_after_a_decoded_frame_returns_that_frame(+ self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path, raise_on_timeout: bool) -> None:- """The no-retry-on-timeout rule must hold in non-raise mode too (the disk store's- mode): a timeout there must not trigger a second full-budget frame-0 decode."""- calls: list[int] = []-- def fake_extract(path, frame_index=0, timeout=0.0, raise_on_timeout=False):- calls.append(frame_index)- raise video_thumbnails.VideoDecodeTimeoutError("busy")-- monkeypatch.setattr(video_thumbnails, "extract_video_frame", fake_extract)- result = video_thumbnails.extract_representative_video_frame(- tmp_path / "v.mp4", duration=10.0, fps=24.0, raise_on_timeout=False+ """A dark thumbnail beats none, and the decoded frame still proves decodability."""+ dark = _solid((0, 0, 0))+ calls = self._fake_extract(monkeypatch, {24: dark, 84: video_thumbnails.VideoDecodeTimeoutError("busy")})+ frame = video_thumbnails.extract_representative_video_frame(+ tmp_path / "v.mp4", duration=10.0, fps=24.0, raise_on_timeout=raise_on_timeout)- assert result is None- assert calls == [24]+ assert frame is dark+ assert calls == [24, 84]- def test_timeout_during_fallback_is_not_swallowed_in_raise_mode(+ def test_the_whole_search_shares_one_budget_of_two_timeouts(self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:- calls: list[int] = []-- def fake_extract(path, frame_index=0, timeout=0.0, raise_on_timeout=False):- calls.append(frame_index)- if frame_index > 0:- return None- raise video_thumbnails.VideoDecodeTimeoutError("busy")+ """Each rung gets the remainder of the budget, not a fresh timeout, so a slow ladder+ is bounded at 2 * timeout like the two-attempt version was."""+ clock = [0.0]+ timeouts: list[float] = []+ dark = _solid((0, 0, 0))++ def slow_extract(path, frame_index=0, timeout=0.0, raise_on_timeout=False):+ timeouts.append(timeout)+ clock[0] += 15.0+ return dark++ monkeypatch.setattr(video_thumbnails.time, "monotonic", lambda: clock[0])+ monkeypatch.setattr(video_thumbnails, "extract_video_frame", slow_extract)+ frame = video_thumbnails.extract_representative_video_frame(+ tmp_path / "v.mp4", duration=10.0, fps=24.0, timeout=10.0+ )+ assert frame is dark+ assert timeouts == [10.0, 5.0]++ def test_walks_past_a_black_lead_in_through_the_worker(self, ladder_mp4: Path) -> None:+ """End to end: the opening rung and the first deeper rung both decode to black and are+ rejected; the search continues to the lit frame instead of settling."""+ duration = 48 / FPS+ assert video_thumbnails.thumbnail_frame_candidates(duration, FPS) == [8, 16, 28, 0]+ frame = video_thumbnails.extract_representative_video_frame(ladder_mp4, duration, FPS)+ assert frame is not None+ assert FrameScore.measure(frame).informative+ assert np.asarray(frame).mean() > 60- monkeypatch.setattr(video_thumbnails, "extract_video_frame", fake_extract)- with pytest.raises(video_thumbnails.VideoDecodeTimeoutError):- video_thumbnails.extract_representative_video_frame(- tmp_path / "v.mp4", duration=10.0, fps=24.0, raise_on_timeout=True- )- assert calls == [24, 0]+ def test_falls_back_to_frame_zero_when_metadata_overstates(self, synthetic_mp4: Path) -> None:+ """Container metadata is untrusted: fps/duration claiming frames that don't exist+ (indices 100+ of a 12-frame clip) must still produce a thumbnail (frame 0), not a+ gallery placeholder."""+ frame = video_thumbnails.extract_representative_video_frame(synthetic_mp4, duration=10.0, fps=100.0)+ assert frame is not None+ value = np.asarray(frame)[0, 0, 0].astype(int)+ assert abs(value - 32) <= 8 # frame 0