Spaces:
Sleeping

Claude commited on
Commit
e059eb2
·
1 Parent(s): e363538

scenes: deterministic frame extraction to stabilise scene detection

Browse files

Users 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

2 files changed +85 -4
Files changed (2)
app/pipeline/scenes.py+30-4
tests/test_scenes.py+55