Spaces:
Sleeping
scenes: deterministic frame extraction to stabilise scene detection
Browse filesUsers reported the "Preview scenes" step returning a different set of
scenes on every run of the same video. Root cause: representative-frame
extraction used cap.set(CAP_PROP_POS_MSEC, …), OpenCV's approximate
millisecond seek. That seek lands on the nearest keyframe and decodes
forward, and FFmpeg's multithreaded decoder can return a slightly
different frame for the same timestamp across runs.
The jitter didn't just change thumbnails — it changed the scene COUNT.
_merge_duplicate_adjacent compares each scene's extracted frame against
its neighbour with a fixed mean-abs-diff threshold (5.0); when a seek
returned a marginally different frame, the MAE crossed the threshold and
flipped a merge decision, so scenes that collapsed one run stayed split
the next.
Fix: add _read_frame_at(cap, time_seconds, fps) which converts the
timestamp to an integer frame index and seeks via CAP_PROP_POS_FRAMES —
a specific decode target that maps far more reproducibly than a
millisecond value. Both extraction sites (_save_top_candidate_frames
and _save_frame_at) now route through it. A zero/broken FPS header falls
back to the old millisecond seek so it degrades rather than hard-fails.
This removes the FFmpeg-thread-jitter class of variation, which is what
was flipping the merge decisions. (Long-GOP codecs with B-frames can
still have minor residual seek imprecision; a keyframe-grab-forward
decode would be fully frame-accurate but adds decode cost — not needed
to fix the reported instability.)
Tests use a fake capture to assert the frame-index seek path is taken
when FPS is known, that it clamps to the last frame, and that it falls
back to millisecond seeking without FPS.
https://claude.ai/code/session_01EM8jiYxdVFy1w3LeJ9GBJg
Files changed (2)
23 unmodified lines242526272829303132333473 unmodified lines10810911011111211311411511611711823 unmodified linescap.release()def _save_frame_at(video_path: Path, time_seconds: float, dest: Path) -> bool:cap = cv2.VideoCapture(str(video_path))try:cap.set(cv2.CAP_PROP_POS_MSEC, max(time_seconds, 0) * 1000.0)ok, frame = cap.read()if not ok or frame is None:return Falsedest.parent.mkdir(parents=True, exist_ok=True)73 unmodified linestimestamps = [t_start + (t_end - t_start) * (i / (n - 1)) for i in range(n)]cap = cv2.VideoCapture(str(video_path))scored: list[tuple[float, float, "np.ndarray"]] = []try:for t in timestamps:cap.set(cv2.CAP_PROP_POS_MSEC, max(t, 0) * 1000.0)ok, frame = cap.read()if not ok or frame is None:continue# Normalize first so a dark-themed slide isn't outranked by a23 unmodified lines2425262728293031323334353637383940414243444546474849505152535455565758596073 unmodified lines13413513613713813914014114214314423 unmodified linescap.release()def _read_frame_at(cap: "cv2.VideoCapture", time_seconds: float, fps: float):"""Deterministically read the frame at `time_seconds`.OpenCV's `cap.set(CAP_PROP_POS_MSEC, …)` seek is approximate — it landson the nearest keyframe and decodes forward, and FFmpeg's multithreadeddecoder can return a slightly different frame for the same timestampacross runs. That jitter propagates into `_merge_duplicate_adjacent`(which compares extracted frames against a fixed diff threshold), sothe *scene count itself* wobbles run-to-run.We instead convert the timestamp to an integer frame index and seek byframe position (`CAP_PROP_POS_FRAMES`), which maps to a specific decodetarget far more reproducibly. Returns (ok, frame). `fps <= 0` falls backto the old millisecond seek so a broken FPS header doesn't hard-fail."""if fps and fps > 0:frame_no = int(round(max(time_seconds, 0.0) * fps))total = cap.get(cv2.CAP_PROP_FRAME_COUNT)if total and total > 0:frame_no = min(frame_no, int(total) - 1)cap.set(cv2.CAP_PROP_POS_FRAMES, float(max(frame_no, 0)))else:cap.set(cv2.CAP_PROP_POS_MSEC, max(time_seconds, 0.0) * 1000.0)return cap.read()def _save_frame_at(video_path: Path, time_seconds: float, dest: Path) -> bool:cap = cv2.VideoCapture(str(video_path))try:fps = cap.get(cv2.CAP_PROP_FPS) or 0.0ok, frame = _read_frame_at(cap, time_seconds, fps)if not ok or frame is None:return Falsedest.parent.mkdir(parents=True, exist_ok=True)73 unmodified linestimestamps = [t_start + (t_end - t_start) * (i / (n - 1)) for i in range(n)]cap = cv2.VideoCapture(str(video_path))fps = cap.get(cv2.CAP_PROP_FPS) or 0.0scored: list[tuple[float, float, "np.ndarray"]] = []try:for t in timestamps:ok, frame = _read_frame_at(cap, t, fps)if not ok or frame is None:continue# Normalize first so a dark-themed slide isn't outranked by a
123451 unmodified line7891011121314151617from pathlib import Pathimport numpy as npfrom PIL import Image1 unmodified line_cap_max_frames,_enforce_min_gap,_merge_duplicate_adjacent,_save_top_candidate_frames,)from app.pipeline.types import SceneFramedef _save(path: Path, color) -> None:path.parent.mkdir(parents=True, exist_ok=True)Image.new("RGB", (64, 36), color).save(path, "JPEG")1234561 unmodified line89101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172from pathlib import Pathimport cv2import numpy as npfrom PIL import Image1 unmodified line_cap_max_frames,_enforce_min_gap,_merge_duplicate_adjacent,_read_frame_at,_save_top_candidate_frames,)from app.pipeline.types import SceneFrameclass _FakeCapture:"""Records the last seek property/value so we can assert which seekmode _read_frame_at chose without decoding a real video."""def __init__(self, frame_count=1000):self.frame_count = frame_countself.last_prop = Noneself.last_value = Nonedef get(self, prop):if prop == cv2.CAP_PROP_FRAME_COUNT:return float(self.frame_count)return 0.0def set(self, prop, value):self.last_prop = propself.last_value = valuereturn Truedef read(self):return True, np.zeros((36, 64, 3), dtype=np.uint8)def test_read_frame_at_seeks_by_frame_index_when_fps_known():"""Deterministic path: with a valid FPS, the timestamp is converted toan integer frame index and seeked via CAP_PROP_POS_FRAMES. This is whatmakes representative-frame extraction reproducible run-to-run (and, inturn, stabilises the merge step's scene count)."""cap = _FakeCapture()ok, _ = _read_frame_at(cap, time_seconds=2.0, fps=30.0)assert okassert cap.last_prop == cv2.CAP_PROP_POS_FRAMESassert cap.last_value == 60.0 # 2.0s * 30fpsdef test_read_frame_at_clamps_to_last_frame():"""A timestamp past the end clamps to the final frame index rather thanseeking out of range."""cap = _FakeCapture(frame_count=100)_read_frame_at(cap, time_seconds=999.0, fps=30.0)assert cap.last_prop == cv2.CAP_PROP_POS_FRAMESassert cap.last_value == 99.0 # frame_count - 1def test_read_frame_at_falls_back_to_msec_without_fps():"""A broken/zero FPS header falls back to millisecond seeking so theframe still extracts (just non-deterministically) instead of hard-failing."""cap = _FakeCapture()_read_frame_at(cap, time_seconds=2.0, fps=0.0)assert cap.last_prop == cv2.CAP_PROP_POS_MSECassert cap.last_value == 2000.0 # 2.0s * 1000def _save(path: Path, color) -> None:path.parent.mkdir(parents=True, exist_ok=True)Image.new("RGB", (64, 36), color).save(path, "JPEG")