fix(reframe): cut instead of pan when the source changes shot

At every scene boundary the tracker kept the previous shot's speaker (sticky
bonus + 30-frame cooldown returning None) and the cameraman's jump damping
held the new face for JUMP_CONFIRM_FRAMES detections, so the frame started
on the old subject and slid across at pan speed. Seen on a two-camera
podcast as a headless torso for 1.5s after each cut.

Reset both at the cut, force a detection on the cut frame, and snap the
camera to the first target accepted in the new shot. SCENE_CUT_RESET=0
restores the old behaviour.

Measured on the 45-clip corpus plus the reported clip (123 TRACK scenes):
first-frame framing error 97 -> 34 px, frames to settle 18.9 -> 3.8,
in-scene reversals unchanged (0.02/s), camera travel 12 -> 7 px/s.
This commit is contained in:
juancarlos.cavero 2026-08-24 20:35:07 +02:00
parent b4bf211b7b
commit 11d4bc76d2
3 changed files with 148 additions and 10 deletions

64
main.py
View file

@ -93,6 +93,12 @@ face_detection = mp_face_detection.FaceDetection(model_selection=1, min_detectio
# damping can be dialled back without a deploy; 1 restores the old behaviour. # damping can be dialled back without a deploy; 1 restores the old behaviour.
JUMP_CONFIRM_FRAMES = max(int(os.environ.get("JUMP_CONFIRM_FRAMES", "3")), 1) JUMP_CONFIRM_FRAMES = max(int(os.environ.get("JUMP_CONFIRM_FRAMES", "3")), 1)
# Reset the tracker and the cameraman's damping at every scene cut, so the
# first face found in the new shot is framed instantly instead of being treated
# as a suspicious "jump" from the previous shot's subject (see
# SmoothedCameraman.begin_scene). 0 restores the old behaviour.
SCENE_CUT_RESET = os.environ.get("SCENE_CUT_RESET", "1") != "0"
class SmoothedCameraman: class SmoothedCameraman:
""" """
@ -146,6 +152,26 @@ class SmoothedCameraman:
self.jump_confirm_frames = JUMP_CONFIRM_FRAMES self.jump_confirm_frames = JUMP_CONFIRM_FRAMES
self._pending_target = None self._pending_target = None
self._pending_count = 0 self._pending_count = 0
self._snap_pending = False
def begin_scene(self):
"""Forget the previous shot's subject at a scene cut.
The jump damping above exists to reject detector noise INSIDE a shot.
Across a cut it does the opposite of what is wanted: the new shot's face
is (by construction) far from the old target, so it was held back for
JUMP_CONFIRM_FRAMES detections and the camera then panned towards it at
pan speed. On a real two-camera podcast (24-aug-2026) that showed up as
a headless torso for 1.5s after every cut while the frame slid over to
the speaker. The snap at the scene's first frame did not help: the
target it snapped to was still the previous shot's.
So: drop any pending jump, and cut (rather than pan) to the first target
accepted in the new shot.
"""
self._pending_target = None
self._pending_count = 0
self._snap_pending = True
def update_target(self, face_box): def update_target(self, face_box):
"""Update the target centre from a detection, ignoring lone big jumps.""" """Update the target centre from a detection, ignoring lone big jumps."""
@ -154,6 +180,14 @@ class SmoothedCameraman:
x, y, w, h = face_box x, y, w, h = face_box
new_center = x + w / 2 new_center = x + w / 2
if self._snap_pending:
self._snap_pending = False
self._pending_target = None
self._pending_count = 0
self.target_center_x = new_center
self.current_center_x = new_center
return
if abs(new_center - self.target_center_x) > self.safe_zone_radius: if abs(new_center - self.target_center_x) > self.safe_zone_radius:
# Same big move as last time? Count it. Otherwise start counting # Same big move as last time? Count it. Otherwise start counting
# afresh — two contradictory outliers must not confirm each other. # afresh — two contradictory outliers must not confirm each other.
@ -240,6 +274,21 @@ class SpeakerTracker:
self.next_id = 0 self.next_id = 0
self.known_faces = [] # [{'id': 0, 'center': x, 'last_frame': 123}] self.known_faces = [] # [{'id': 0, 'center': x, 'last_frame': 123}]
def reset(self):
"""Forget every speaker at a scene cut.
Identity, hysteresis and the switch cooldown are all about continuity
within a shot. After a cut none of it applies: the sticky x3 bonus and
the cooldown were holding the previous shot's speaker (returning None)
for up to 30 frames while a new face sat unframed.
"""
self.active_speaker_id = None
self.speaker_scores = {}
self.last_seen = {}
self.locked_counter = 0
self.last_switch_frame = -1000
self.known_faces = []
def get_target(self, face_candidates, frame_number, width): def get_target(self, face_candidates, frame_number, width):
""" """
Decides which face to focus on. Decides which face to focus on.
@ -1190,21 +1239,26 @@ def process_video_to_vertical(input_video, final_output_video, aspect_ratio=ASPE
# Detect every Nth frame for performance (cameraman smooths in # Detect every Nth frame for performance (cameraman smooths in
# between); the much heavier YOLO fallback gets its own stride. # between); the much heavier YOLO fallback gets its own stride.
if frame_number % DETECT_STRIDE == 0: # Snap camera on scene change to avoid panning from previous scene position
is_scene_start = (frame_number == scene_boundaries[current_scene_index][0])
if is_scene_start and SCENE_CUT_RESET:
speaker_tracker.reset()
cameraman.begin_scene()
# Always detect on a cut, whatever the stride: the new shot's
# subject has to be found before the first frame is framed.
if frame_number % DETECT_STRIDE == 0 or (is_scene_start and SCENE_CUT_RESET):
t_det = time.time() t_det = time.time()
candidates = detect_face_candidates(frame) candidates = detect_face_candidates(frame)
target_box = speaker_tracker.get_target(candidates, frame_number, original_width) target_box = speaker_tracker.get_target(candidates, frame_number, original_width)
if target_box: if target_box:
cameraman.update_target(target_box) cameraman.update_target(target_box)
elif frame_number % YOLO_FALLBACK_STRIDE == 0: elif frame_number % YOLO_FALLBACK_STRIDE == 0 or (is_scene_start and SCENE_CUT_RESET):
person_box = detect_person_yolo(frame) person_box = detect_person_yolo(frame)
if person_box: if person_box:
cameraman.update_target(person_box) cameraman.update_target(person_box)
stage_seconds['detect'] += time.time() - t_det stage_seconds['detect'] += time.time() - t_det
# Snap camera on scene change to avoid panning from previous scene position
is_scene_start = (frame_number == scene_boundaries[current_scene_index][0])
x1, y1, x2, y2 = cameraman.get_crop_box(force_snap=is_scene_start) x1, y1, x2, y2 = cameraman.get_crop_box(force_snap=is_scene_start)
# Crop # Crop

View file

@ -279,7 +279,17 @@ def _analyze_trajectory(input_video, scenes_boundaries, scene_strategies,
cameraman.target_center_x = orig_w / 2 cameraman.target_center_x = orig_w / 2
xs.append(None) xs.append(None)
else: else:
if frame_number % m.DETECT_STRIDE == 0: is_scene_start = (
current_scene_index < len(scenes_boundaries)
and frame_number == scenes_boundaries[current_scene_index][0])
cut = is_scene_start and m.SCENE_CUT_RESET
if cut:
# New shot: forget the old subject and cut to the new one
# (see SmoothedCameraman.begin_scene).
tracker.reset()
cameraman.begin_scene()
if frame_number % m.DETECT_STRIDE == 0 or cut:
candidates = m.detect_face_candidates(frame) candidates = m.detect_face_candidates(frame)
for cand in candidates: for cand in candidates:
cand['box'] = [int(v * scale) for v in cand['box']] cand['box'] = [int(v * scale) for v in cand['box']]
@ -287,14 +297,11 @@ def _analyze_trajectory(input_video, scenes_boundaries, scene_strategies,
target_box = tracker.get_target(candidates, frame_number, orig_w) target_box = tracker.get_target(candidates, frame_number, orig_w)
if target_box: if target_box:
cameraman.update_target(target_box) cameraman.update_target(target_box)
elif frame_number % m.YOLO_FALLBACK_STRIDE == 0: elif frame_number % m.YOLO_FALLBACK_STRIDE == 0 or cut:
person_box = m.detect_person_yolo(frame) person_box = m.detect_person_yolo(frame)
if person_box: if person_box:
cameraman.update_target([int(v * scale) for v in person_box]) cameraman.update_target([int(v * scale) for v in person_box])
is_scene_start = (
current_scene_index < len(scenes_boundaries)
and frame_number == scenes_boundaries[current_scene_index][0])
x1, _y1, _x2, _y2 = cameraman.get_crop_box(force_snap=is_scene_start) x1, _y1, _x2, _y2 = cameraman.get_crop_box(force_snap=is_scene_start)
xs.append(x1) xs.append(x1)

View file

@ -0,0 +1,77 @@
"""Camera behaviour across a scene cut.
Regression cover for the slow pan after every shot change (24-aug-2026, a
two-camera podcast): the jump damping in SmoothedCameraman and the hysteresis
in SpeakerTracker both exist to reject noise INSIDE a shot, and across a cut
they held the previous shot's subject while the new face sat unframed, then
panned over to it. A cut must cut.
"""
import pytest
main = pytest.importorskip("main") # needs cv2/mediapipe, absent in minimal CI
W, H = 1920, 1080
def _cam():
cam = main.SmoothedCameraman(1080, 1920, W, H, aspect_ratio=9 / 16)
cam.jump_confirm_frames = 3
return cam
def _box(cx, size=200):
return [cx - size / 2, 200, size, size]
def _settle(cam, cx, n=6):
for _ in range(n):
cam.update_target(_box(cx))
cam.get_crop_box(force_snap=True)
assert abs(cam.current_center_x - cx) < 1
class TestCameramanBeginScene:
def test_first_target_after_a_cut_is_framed_at_once(self):
cam = _cam()
_settle(cam, 400)
cam.begin_scene()
cam.update_target(_box(1500)) # one detection, far away
x1, _, x2, _ = cam.get_crop_box()
assert abs((x1 + x2) / 2 - 1500) <= 1, "must cut to the new face, not pan"
def test_without_a_cut_a_lone_big_jump_is_still_ignored(self):
# The in-shot damping is untouched.
cam = _cam()
_settle(cam, 400)
cam.update_target(_box(1500))
assert cam.target_center_x == 400
def test_a_pending_jump_from_the_old_shot_is_dropped(self):
cam = _cam()
_settle(cam, 400)
cam.update_target(_box(1500)) # 1 of 3 confirmations
cam.update_target(_box(1500)) # 2 of 3
cam.begin_scene()
cam.update_target(_box(900)) # new shot, different place
assert cam.target_center_x == 900
assert cam.current_center_x == 900
def test_snap_is_consumed_once(self):
cam = _cam()
cam.begin_scene()
cam.update_target(_box(900))
cam.update_target(_box(1600)) # a lone jump inside the new shot
assert cam.target_center_x == 900
class TestTrackerReset:
def test_reset_releases_the_cooldown_hold(self):
t = main.SpeakerTracker(cooldown_frames=30)
for f in range(5):
t.get_target([{"box": _box(300), "score": 1}], f, W)
t.get_target([{"box": _box(1500), "score": 1}], 40, W) # switch -> cooldown
assert t.get_target([{"box": _box(300), "score": 1}], 42, W) is None, "held (sanity)"
t.reset()
assert t.get_target([{"box": _box(300), "score": 1}], 43, W) is not None
assert t.active_speaker_id is not None