clipwright/frame_sampler.py
victormanuel.caverogracia a4c92cac2c perf(pipeline): halve a job's CPU with byte-identical clips
Reverts 1d3d20c (NVDEC decode + quarter-size blur): it changed the
delivered pixels (SSIM 0.998-0.9997, not identical), and clips must not
change. Replaces it with two fixes that leave every clip byte-identical.

- Parakeet's onnxruntime pool threads no longer spin
  (transcribe_backends.parakeet_session_options). While the GPU did the
  work they burned ~160 CPU-s per 9 min of audio, the biggest CPU cost of
  a job. The VAD keeps load_vad's defaults: any options there make
  onnx_asr drop its default providers and a word changes.
- analyze_scenes_strategy and split_layout read their sampled frames in
  one forward pass (frame_sampler.read_at) instead of a seek per sample,
  which re-decoded the GOP every time: 89 -> 6 CPU-s for one clip's
  samples, same frames.

Bench on balrog, 3 Carlos Gracia videos (2.5/9/17 min, 15 clips), Gemini
decisions recorded once and replayed: every clip identical to the old
code (decoded-frame MD5s + audio). Serial stage profile of the 9 min
video: 629 -> 273 CPU-s per job; Python side 332 -> 57 CPU-s.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-25 15:40:22 +02:00

48 lines
1.8 KiB
Python

"""Read sampled frames without a seek per sample.
The scene classifiers sample a handful of frames per scene with
``cap.set(CAP_PROP_POS_FRAMES, i); cap.read()``. On H.264 every such seek
decodes again from the previous keyframe, so a clip's ~100 samples decoded
the same GOPs over and over: 89 CPU-s for one 20 s clip, against 6 CPU-s for
a single forward pass that keeps the frames asked for (prod bench,
25-sep-2026). The frames are byte-identical either way (checked on 217
samples of NVENC-cut clips), so every downstream decision stays the same.
"""
import cv2
# Past this many frames ahead, one seek is cheaper than decoding forward to
# the target (an NVENC cut's GOP is ~250 frames).
MAX_FORWARD = 300
def read_at(cap, indices, max_forward=MAX_FORWARD):
"""Yield ``cap.read()``'s frame for each index in ``indices``, in order,
or None where a seek + read would have failed (past the last frame).
``cap`` must be freshly opened (positioned at frame 0). Indices should be
non-decreasing to get the forward-pass saving; a step backwards or a jump
past ``max_forward`` seeks exactly like the callers used to. A repeated
index yields the same frame object again: treat frames as read-only.
"""
pos = 0 # index of the frame the next grab() decodes
last = (None, None)
for idx in indices:
idx = int(idx)
if idx == last[0]:
yield last[1]
continue
if idx < pos or idx - pos > max_forward:
cap.set(cv2.CAP_PROP_POS_FRAMES, idx)
pos = idx
frame = None
while pos < idx:
if not cap.grab():
break
pos += 1
if pos == idx:
ok, frame = cap.read()
pos += 1
if not ok:
frame = None
last = (idx, frame)
yield frame