Computer Vision

Active-Speaker Reframing: Turning 16:9 Talks Into 9:16 Clips

How we turn 16:9 talks into 9:16 clips: face tracks, mouth activity and diarization drive a virtual camera with hysteresis, dead zones and hard cuts.

Weaveward computer vision editorial illustration

A 9:16 crop of a 1920x1080 frame is 607.5 pixels wide: under a third of the picture. Put two people on a sofa and the crop can hold one of them, not both. Centre-cropping loses the speaker half the time, and naive face following produces a camera that twitches on every nod, pans across an empty room when the conversation changes hands and slices slides in half.

Our position is that reframing is a control problem, not a detection problem. Detectors give you noisy measurements; the hard part is the controller that turns them into a calm, deliberate virtual camera, plus a metric that tells you whether it worked. This article walks through how we built that in the AI Video Clipper, a prototype that cuts long talks and interviews into short clips: the signals, the decision rules with their real parameter names and defaults, the layouts, the render path and the QA checks that run after the pixels exist.

You will get a runnable virtual-camera controller with a dead zone, smoothing, a speed limit and hold hysteresis, a synthetic run that shows what each rule buys, and the failure modes we designed around.

The shape of the problem

The planner works on one clip and one output aspect at a time, and it works offline. That matters more than any model choice. A live operator has to decide now; a planner holding the whole clip can look ahead, so hysteresis costs no latency. When speaker B takes over at 8.0 seconds, the cut can land at 8.0 seconds, not after a confirmation delay.

The output is a FramingPlan: contiguous layout segments, each with one or two panels, each panel carrying crop keyframes (t, cx, cy, zoom) in normalised source coordinates. Paths are simplified with Ramer-Douglas-Peucker at a tolerance of 0.002 and interpolated linearly at render time. Planner and compositor import the same geometry functions (window_size, clamp_center, visible_windows), so what the planner measures is exactly what the renderer shows.

One piece of arithmetic calibrates everything below: for a 1920x1080 source and a 1080x1920 output, the crop window is 0.316 of the source width. Two speakers seated 0.45 apart can never share one crop.

Signals: whose face, and who is talking

Face tracks

Faces come from YuNet (the OpenCV Zoo 2023 model) run through ONNX Runtime on a 640 pixel analysis frame, with min_face_score 0.6. The repository notes about 24 ms per frame this way on the development machine against about 45 ms for OpenCV 5's FaceDetectorYN, with identical boxes, so the post-processing mirrors OpenCV's decoder. A small deterministic tracker associates detections greedily on IoU, size-normalised centre distance and size similarity against a constant-velocity prediction. Tracks survive gaps up to max_gap 1.0 seconds and split at scene cuts unless the new detection overlaps the old position strongly, which handles false cuts on a static camera.

Mouth activity from jawOpen

To choose between visible faces we use the MediaPipe Face Landmarker's jawOpen blendshape, computed on a square crop 1.8 times the face box resized to 256 pixels, because blendshapes from a 50 pixel face are mostly noise. It only runs when at least two faces are visible near speech; with one face there is nothing to choose.

The signal is activity, not openness: the mean absolute successive difference of jawOpen within plus or minus 0.5 seconds, widened to at least four samples per side at sparse rates. We deliberately avoid the window's standard deviation: a smiling listener's slow expression change has a larger spread than a quiet talker's articulation. Switching faces has its own hysteresis in SpeakerParams: a challenger must beat the incumbent by switch_ratio 1.3 for challenge_s 0.5 seconds after a min_hold of 1.0 seconds, and if no face exceeds min_activity 0.015 for quiet_hold 2.0 seconds during speech, the voice is treated as off-screen.

On a public NASA interview (two astronauts on camera, an off-screen interviewer), the repository records that at 2 fps 88% of in-speech samples during answers got a face, 94% of those on the answer's dominant face, and 62% of question samples were correctly marked as having no visible speaker. That is one sample video: a sanity check, not a benchmark.

Diarization label to face track

Mouth activity is a visual guess; diarization knows who is talking but not where they are. The planner joins them by co-occurrence, voting for the pair (speaker label, active track) at each sample inside a word. A label maps to a track when it has at least two votes, the pair covers at least 30% of that label's speech samples and half of its votes, and the mapping is one-to-one. A mapped label beats the mouth cue; unmapped speech falls back to mouth activity.

Decisions: whom to frame, and when to cut

Whom to frame

The planner builds subject runs per shot. Silence keeps the previous subject. Speech with no on-screen speaker becomes a group shot only when it lasts at least GROUP_MIN_S 2.5 seconds; a short off-camera question keeps the current face. Runs shorter than the minimum length are absorbed by the longer neighbour: that is the hold hysteresis that stops a half-second "mm-hmm" causing two cuts. One honest detail: TrackingConfig exposes hold_s (default 1.2 seconds), but the current planner merges runs using MIN_SEGMENT_S, 1.5 seconds, so 1.5 seconds is the effective hold.

When to cut

Every speaker switch is a hard cut, never a pan. Two faces 0.46 apart at a max_speed of 0.35 per second is a 1.3 second whip pan with neither face properly framed. The cut lands 0.1 seconds before the new speaker's first word, clamped so both neighbouring segments stay at least 1.5 seconds long; without a mapped label, the planner uses the word after the largest pause of at least 0.25 seconds nearby.

Scene changes are free cuts, since shot spans come from detected scene boundaries. Inside a shot, if the subject sits further than max(0.2, 0.5 * window_width) from the camera for 0.4 seconds (JUMP_PERSIST_S), the planner cuts there when both resulting segments are at least 1.5 seconds, and otherwise pans at the speed limit.

How the camera moves

Within a run, four TrackingConfig rules apply: a dead_zone of 0.06 with release at a quarter of that (so it does not chatter at the boundary), exponential smoothing with smoothing_s 0.6, a max_speed of 0.35 normalised units per second, and containment that keeps the face box inside the window with a 0.01 margin. Containment overrides the speed limit: a slightly fast move beats a cropped forehead. Vertically, the eye line (40% down the face box) is offset by headroom 0.12 of the window height. Here is a condensed one-axis version:

import math
from dataclasses import dataclass


@dataclass(frozen=True)
class Tracking:
    dead_zone: float = 0.06  # normalised drift tolerated before the camera moves
    smoothing_s: float = 0.6  # time constant of the exponential follow
    max_speed: float = 0.35  # max normalised pan per second
    hold_s: float = 1.2  # shortest subject run allowed to cause a switch
    margin: float = 0.01  # kept between the face box and the window edge


def follow(cx, moving, target, box, dt, ww, tc):
    """One step on the x axis: dead zone, smoothing, speed limit, then containment."""
    d = target - cx
    if abs(d) > tc.dead_zone:
        moving = True
    elif abs(d) < 0.25 * tc.dead_zone:  # release well inside the zone: no chatter
        moving = False
    if moving:
        alpha = 1.0 - math.exp(-dt / tc.smoothing_s)
        limit = tc.max_speed * dt
        cx += max(-limit, min(limit, d * alpha))
    x0, x1 = box  # keeping the face inside the window overrides the speed limit
    if x0 - tc.margin < cx - ww / 2:
        cx = x0 - tc.margin + ww / 2
    elif x1 + tc.margin > cx + ww / 2:
        cx = x1 + tc.margin - ww / 2
    return min(max(cx, ww / 2), 1 - ww / 2), moving

A synthetic run

We drive it with a synthetic 12 second exchange at 8 fps: speaker A drifts slowly right with plus or minus 0.02 of detection jitter, speaker B interjects for half a second at 5.0 seconds and takes over at 8.0 seconds.

def subject_runs(ts, active, hold_s):
    """Offline hysteresis: a run shorter than hold_s is absorbed by the run before it."""
    runs = []
    for t, who in zip(ts, active):
        if runs and runs[-1][2] == who:
            runs[-1][1] = t
        else:
            runs.append([t, t, who])
    kept = [runs[0]]
    for r in runs[1:]:
        if r[1] - r[0] < hold_s or r[2] == kept[-1][2]:
            kept[-1][1] = r[1]
        else:
            kept.append(r)
    return kept  # every later run starts on the new speaker's first sample


FPS, WW, FACE_W = 8.0, (1080 * 9 / 16) / 1920, 0.08  # 9:16 window: 0.316 of the width
tc, ts = Tracking(), [i / 8.0 for i in range(96)]  # 12 s at the dense rate
jitter = lambda t: 0.02 if int(t * FPS) % 2 else -0.02
face_x = lambda who, t: 0.30 + 0.01 * t + jitter(t) if who == "A" else 0.74
speaker = lambda t: "B" if 5.0 <= t < 5.5 or t >= 8.0 else "A"

runs = subject_runs(ts, [speaker(t) for t in ts], tc.hold_s)
cx, moving, prev_t, seen, inside, moves = 0.5, False, 0.0, None, 0, 0
for t in ts:
    who = next(r[2] for r in reversed(runs) if r[0] <= t)
    x = face_x(who, t)
    if who != seen:  # subject switch: hard cut, never a pan across the room
        cx, moving, seen = min(max(x, WW / 2), 1 - WW / 2), False, who
        print(f"cut at {t:.3f} s to {who}")
    else:
        old = cx
        cx, moving = follow(cx, moving, x, (x - FACE_W / 2, x + FACE_W / 2), t - prev_t, WW, tc)
        moves += cx != old
    prev_t = t
    sx = face_x(speaker(t), t)  # whoever is really talking right now
    inside += cx - WW / 2 <= sx - FACE_W / 2 and sx + FACE_W / 2 <= cx + WW / 2
print(f"camera moved on {moves} of {len(ts)} samples")
print(f"talking face fully inside the window: {inside / len(ts):.1%}")

With the defaults it prints two cuts (0.0 and 8.0 seconds), the camera moves on 6 of 96 samples, and the talking face is fully in frame for 95.8% of samples. With dead_zone and hold_s set to zero it reaches 100%, but with four cuts, two of them half a second apart, and a camera moving on 58 of 96 samples. The 4.2 points we give up are exactly the interjection, and in exchange the clip stops looking like a security camera. A metric that preferred the jittery version would be the wrong metric, which is why the QA threshold sits well below 100%.

Layouts: crop, split, fit and full

Some shots should not be cropped at all. In the default auto portrait policy, the planner picks per shot:

Layout Chosen when What it costs
full Source and target aspects agree within 3% Nothing; a plain scale
fit Screen or slide shots, faces in under 30% of samples, a group of three or more wider than any crop, or a wide shot with no identifiable speaker Small subjects; the whole frame sits over a blurred, darkened background
split Two primary faces both visible in at least 60% of samples, too far apart for one crop, and alternating (at least two switches) Each face gets half the height; captions move to the seam
crop Everything else: follow the active speaker Anyone outside the window is gone

Split panels put the left face on top, each zoomed so the face fills about 38% of the panel height (capped at 2x), with a 6 pixel dark separator. The fit background is cheap by design: a cover crop downscaled to an eighth of the output, blurred, darkened by about 45%, then upscaled. Every layout segment lasts at least 1.5 seconds, because layout flicker reads as a bug even when each decision was locally right. A human review override per clip and aspect wins over all of this.

Screen content is detected per scene by screen_score, which looks for large perfectly flat blocks plus line-shaped edge clusters (text). A scene is screen when that score is at least 0.5 and there is no face or the typical face is under 15% of the frame height. Camera footage has sensor noise almost everywhere; slides do not.

subject_coverage and the QA that enforces it

subject_coverage is the share of on-screen speech time during which the speaker's face box is fully inside a visible window of the output. It walks the analysis samples, takes the active track from the planner's own timeline, asks visible_windows for the exact rectangles the compositor will render and checks containment with a 0.002 margin. Speech with no on-screen speaker is excluded rather than counted as a pass. Because it is computed from the plan, before any encoding, a planner change can be judged across many clips in milliseconds.

After rendering, two checks run. subject_framing fails when coverage is below min_subject_coverage 0.75, or when YuNet, run on five frames sampled across the crop and split segments of the rendered video, finds a panel's largest face touching that panel's edge. visual_info_outside fails when a crop or split segment overlaps a screen shot by more than 0.5 seconds, because slides cut to a third of their width lose what the speaker is pointing at. Failures trigger repair on that clip only: the offending segments switch to fit and the clip re-renders, within a max_repairs budget of 2.

Sparse everywhere, dense where it matters

Face analysis is one of the pipeline's three big compute costs, so it runs at two rates. The source-level visual stage samples the whole video at sample_fps 2.0; the framing stage re-analyses only the selected clips at dense_fps 8.0, decoding at up to 1280 pixels wide for the landmarker crops. If dense analysis fails, the planner falls back to the sparse samples and says so in the plan notes.

The rate matters for the controller too. The per-step smoothing factor, 1 minus e to the power of minus dt over 0.6, is about 0.19 at 8 fps and 0.57 at 2 fps, and the per-step speed limit goes from 0.044 to 0.175. At 2 fps the camera moves in large jumps between measurements: fine for choosing clips, not for rendering them. In the project's measured run on a 21.4 minute 720p interview, the 2 fps pass took 153 seconds and the 8 fps pass inside the six selected clips took 185 seconds.

The render path: one decode, one composite, one encode

Arbitrary crop paths, split screens and blurred fits are awkward as FFmpeg filter graphs and easy in numpy. So the renderer decodes once to raw BGR frames on a pipe, composites in Python with OpenCV and encodes once. The shape of the two processes, with illustrative values and the subtitle and loudness filters omitted:

# decode: exact output frame rate, raw BGR frames on stdout
ffmpeg -nostdin -ss 754.2 -i talk.mp4 -t 38.5 -map 0:v:0 -an -sn -dn \
  -vf "fps=60000/1001,scale=in_color_matrix=bt709:flags=bicubic,format=bgr24" \
  -f rawvideo -pix_fmt bgr24 pipe:1
# the Python compositor reads W*H*3 bytes per frame and writes 1080x1920 frames
# encode: composited frames on stdin, audio from the source, exact frame count
ffmpeg -nostdin -y -f rawvideo -pix_fmt bgr24 -s 1080x1920 -framerate 60000/1001 \
  -i pipe:0 -ss 754.2 -t 38.0 -i talk.mp4 \
  -filter_complex "[1:a:0]apad=whole_dur=37.5,atrim=end=37.5,asetpts=PTS-STARTPTS[aout]" \
  -map 0:v -map "[aout]" -c:v libx264 -preset medium -frames:v 2248 clip.mp4

Three details carry A/V sync. The frame count is computed, not discovered: round(duration * fps), so a 37.5 second clip at 60000/1001 fps is 2,248 frames. The audio is padded and trimmed to exactly the clip duration. If the decoder ends early, the last frame is repeated and the shortfall logged. Between the pipes, a reader thread fills a bounded queue and three compositor workers run ahead (OpenCV releases the GIL) while the main thread writes frames in order. A static window uses an integer crop and resize; a moving one uses a sub-pixel affine warp, because slow pans otherwise step by whole source pixels and judder. In the measured run, renders ran at 0.43 to 0.56 times real time with libx264 medium at 60 fps, the largest cost in the pipeline.

FAQ

Why not use AutoFlip directly?

AutoFlip established the right ideas: shot-aware processing, a smoothed camera path rather than raw boxes, and a padded fallback when required content cannot fit. It is a C++ MediaPipe graph, which the project found impractical as a Python dependency on Windows, and it frames salient objects rather than whoever is speaking.

Why not an audio-visual active speaker model?

Diarization plus jawOpen activity gave a usable signal without another heavy model, and the planner's hysteresis absorbs much of the remaining noise. A dedicated model is a reasonable upgrade if coverage on real footage stays low.

Checklist

  • Plan offline over the whole clip so hysteresis costs no latency and cuts can land on the first word
  • Treat speaker changes and far jumps as hard cuts; pan only for small drift, under a speed limit
  • Use a dead zone with a smaller release threshold, and let face containment override smoothing
  • Fall back to fit for slides and wide groups instead of cropping information away
  • Enforce a minimum segment length so layouts never flicker
  • Measure subject_coverage from the plan with the renderer's own geometry, and expect 100% to mean a jittery camera
  • Analyse sparsely for selection and densely only inside the clips you will render
  • Fix the output frame count and pad or trim audio to the exact duration

Primary references

The full pipeline behind this article is written up in the AI Video Clipper case study, and our computer vision service covers this kind of video work.

Let’s connect the dots

What would this look like for your business?

Let's turn the right ideas into a clear next step.

Discuss your project