fix(reframe): a source already shot vertical is passed through untouched

The scene classifier sends every face-less shot to GENERAL, and GENERAL scales
the content to 42% of the frame height. That ratio buys presence on a LANDSCAPE
source by overflowing the sides; on a 1080x1920 upload the same number is a
shrink, leaving a 453px sliver floating over a blurred copy of itself. A user's
already-vertical video came back with its screen-recording scenes rendered that
way while its talking-head scenes (TRACK, whose crop is the whole frame) looked
right, so a single clip alternated between correct and ruined.

source_already_fits() gates the whole thing: a source at or past the target
aspect has no width to buy back, so the classifier, the SPLIT detection and the
screencast/inset upgrades are all skipped and every scene renders TRACK. The
layout picker is skipped too, saving a Gemini call per upload that the render
would have ignored anyway.

general_filtergraph() additionally floors the foreground at the height where the
source fills the output width, so the editor's explicit GENERAL override on a
portrait clip cannot reproduce the shrink. A 16:9 source keeps the 0.42 ratio
untouched.

Two siblings of the same bug, both only reachable on a source TALLER than the
target: the TRACK crop pinned y=0 and threw away the bottom of the frame instead
of trimming both ends, and v1's create_general_frame indexed the output with a
negative offset, which raises rather than renders.

Claude-Session: https://claude.ai/code/session_01KeQYCfUX2E9Q2fDgZMKEaJ
This commit is contained in:
juancarlos.cavero 2026-08-29 00:06:15 +02:00
parent 5807217f00
commit b4be92cb63
4 changed files with 124 additions and 8 deletions

View file

@ -147,6 +147,20 @@ the dashboard offers them as the person reference so the thumbnail shows the
creator instead of a stranger; an uploaded face photo still wins. creator instead of a stranger; an uploaded face photo still wins.
### Video Reframing Modes ### Video Reframing Modes
**A source already shot vertical is passed through untouched.**
`reframe_v2.source_already_fits()` gates it: every layout below reorganises the
frame to buy back width the crop threw away, and on a 9:16 upload there is none
to buy. GENERAL was the visible failure — its 0.42 height ratio, which buys
presence on a landscape source by overflowing the sides, scaled a 1080x1920
source down to a 453px sliver floating over a blurred copy of itself, and the
scene classifier routes every face-less shot (a slide, a screen recording) there.
So the picker is skipped (one Gemini call saved per upload), the classifier is
skipped, and every scene renders TRACK, whose crop is the whole frame.
`general_filtergraph` additionally floors the foreground at the height where the
source fills the output width, so the editor's explicit GENERAL override on a
portrait clip cannot reproduce the shrink either.
- **TRACK Mode** (single subject): MediaPipe face detection + YOLOv8 fallback with "Heavy Tripod" stabilization - **TRACK Mode** (single subject): MediaPipe face detection + YOLOv8 fallback with "Heavy Tripod" stabilization
- **GENERAL Mode** (groups/landscapes): Blurred background layout preserving full width - **GENERAL Mode** (groups/landscapes): Blurred background layout preserving full width
- **SPLIT Mode** (two-shot conversation, `split_layout.py`): both speakers stacked - **SPLIT Mode** (two-shot conversation, `split_layout.py`): both speakers stacked

23
main.py
View file

@ -522,10 +522,18 @@ def create_general_frame(frame, output_width, output_height):
scale = output_width / orig_w scale = output_width / orig_w
fg_h = int(orig_h * scale) fg_h = int(orig_h * scale)
foreground = cv2.resize(frame, (output_width, fg_h), interpolation=cv2.INTER_LINEAR) foreground = cv2.resize(frame, (output_width, fg_h), interpolation=cv2.INTER_LINEAR)
# A source taller than the output fills the width at a height that does not
# fit: centre-crop it instead of indexing the frame with a negative offset,
# which raises rather than renders.
if fg_h > output_height:
top = (fg_h - output_height) // 2
foreground = foreground[top:top + output_height, :]
fg_h = output_height
# 3. Overlay # 3. Overlay
y_offset = (output_height - fg_h) // 2 y_offset = (output_height - fg_h) // 2
# Clone background to avoid modifying it # Clone background to avoid modifying it
final_frame = background.copy() final_frame = background.copy()
final_frame[y_offset:y_offset+fg_h, :] = foreground final_frame[y_offset:y_offset+fg_h, :] = foreground
@ -1788,8 +1796,17 @@ if __name__ == '__main__':
_cap = cv2.VideoCapture(input_video) _cap = cv2.VideoCapture(input_video)
_fps = _cap.get(cv2.CAP_PROP_FPS) or 30.0 _fps = _cap.get(cv2.CAP_PROP_FPS) or 30.0
_duration = int(_cap.get(cv2.CAP_PROP_FRAME_COUNT)) / _fps _duration = int(_cap.get(cv2.CAP_PROP_FRAME_COUNT)) / _fps
_w = int(_cap.get(cv2.CAP_PROP_FRAME_WIDTH))
_h = int(_cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
_cap.release() _cap.release()
layout_picker.pick_and_apply(input_video, _duration) from reframe_v2 import source_already_fits # imports main back
# A source already shot vertical has no width to reorganise, and
# the render passes it through whatever the model says. Asking
# anyway costs a Gemini call per upload to be ignored.
if _w and _h and source_already_fits(_w, _h, ASPECT_RATIO):
print(f" ↕️ Source is {_w}x{_h} — already vertical, no layout to pick.")
else:
layout_picker.pick_and_apply(input_video, _duration)
except Exception as e: except Exception as e:
print(f"⚠️ Layout choice skipped ({e}) — using the default layout.") print(f"⚠️ Layout choice skipped ({e}) — using the default layout.")

View file

@ -64,6 +64,18 @@ def delivery_size(orig_w, orig_h, aspect_ratio):
return out_w + (out_w % 2), out_h + (out_h % 2) return out_w + (out_w % 2), out_h + (out_h % 2)
def source_already_fits(orig_w, orig_h, aspect_ratio, tol=0.01):
"""True when the source is already at (or past) the target aspect.
Such a source has no width to throw away, so every layout that rearranges
the frame is a downgrade: GENERAL puts it in a blurred bed, SPLIT stacks
two crops of an already-narrow frame, SCREENCAST/INSET carve panels out of
it. TRACK is the only one that leaves it alone — its crop is the whole
frame — so a vertical upload should pass straight through.
"""
return orig_w / float(orig_h) <= aspect_ratio * (1 + tol)
def dedupe_sendcmd_lines(xs, fps, target="crop@c"): def dedupe_sendcmd_lines(xs, fps, target="crop@c"):
"""sendcmd lines setting crop x per frame, deduped to change-points. """sendcmd lines setting crop x per frame, deduped to change-points.
@ -123,7 +135,7 @@ def full_width_content_height(orig_w, orig_h, out_w):
return fg_h + (fg_h % 2) return fg_h + (fg_h % 2)
def general_filtergraph(out_w, out_h, content_h=None): def general_filtergraph(out_w, out_h, content_h=None, orig_w=None, orig_h=None):
"""Blurred-background 'general shot' layout: bg fills the frame (centre- """Blurred-background 'general shot' layout: bg fills the frame (centre-
cropped, blurred), fg is scaled to a readable share of the height and cropped, blurred), fg is scaled to a readable share of the height and
centred, overflowing the sides rather than floating small in the middle. centred, overflowing the sides rather than floating small in the middle.
@ -132,8 +144,16 @@ def general_filtergraph(out_w, out_h, content_h=None):
turns the side-cropping off entirely, which is what a scene full of charts turns the side-cropping off entirely, which is what a scene full of charts
or spreadsheets needs: the default 0.42 ratio buys presence by throwing away or spreadsheets needs: the default 0.42 ratio buys presence by throwing away
~24% of the width, and on that material the discarded columns are the point. ~24% of the width, and on that material the discarded columns are the point.
``orig_w``/``orig_h`` floor the foreground at the height where the source
fills the output width. The 0.42 ratio buys presence on a LANDSCAPE source
by overflowing the sides; on a portrait one the same number is a shrink —
an already-9:16 upload came back as a 453px sliver floating over a blurred
copy of itself. Filling the width is the floor, never the target.
""" """
fg_h = content_h if content_h else int(out_h * GENERAL_CONTENT_HEIGHT_RATIO) fg_h = content_h if content_h else int(out_h * GENERAL_CONTENT_HEIGHT_RATIO)
if orig_w and orig_h:
fg_h = max(fg_h, full_width_content_height(orig_w, orig_h, out_w))
fg_h += fg_h % 2 fg_h += fg_h % 2
return ( return (
f"[0:v]split=2[bga][fga];" f"[0:v]split=2[bga][fga];"
@ -358,10 +378,21 @@ def render(input_video, final_output_video, aspect_ratio, content_ranges=None,
scenes = [(FrameTimecode(0, fps), FrameTimecode(total, fps))] scenes = [(FrameTimecode(0, fps), FrameTimecode(total, fps))]
scene_boundaries = [(s.get_frames(), e.get_frames()) for s, e in scenes] scene_boundaries = [(s.get_frames(), e.get_frames()) for s, e in scenes]
# A source shot vertical is already the output: nothing to reframe. The
# scene classifier still sends its face-less shots (a slide, a chart, a
# screen recording) to GENERAL, and GENERAL on such a source shrank the
# whole frame into the middle of a blurred copy of itself. Skip the
# classifier and every layout upgrade instead of trying to survive them.
passthrough = source_already_fits(orig_w, orig_h, aspect_ratio)
if force_strategy: if force_strategy:
strategies = [force_strategy] * len(scenes) strategies = [force_strategy] * len(scenes)
content_ranges = [] # no screencast/inset upgrades over an explicit choice content_ranges = [] # no screencast/inset upgrades over an explicit choice
print(f" 🎯 Framing override: every scene -> {force_strategy}") print(f" 🎯 Framing override: every scene -> {force_strategy}")
elif passthrough:
strategies = ['TRACK'] * len(scenes)
content_ranges = []
print(f" ↕️ Source is already {orig_w}x{orig_h} vertical — "
f"passing it through, no reframe")
else: else:
strategies = m.analyze_scenes_strategy(input_video, scenes) strategies = m.analyze_scenes_strategy(input_video, scenes)
@ -372,8 +403,9 @@ def render(input_video, final_output_video, aspect_ratio, content_ranges=None,
# that begin past the last decoded frame, and those get dropped). # that begin past the last decoded frame, and those get dropped).
splits = {} splits = {}
split_scene_of = {} split_scene_of = {}
for scene_idx, centres in split_layout.detect_split_scenes( detected_splits = {} if passthrough else split_layout.detect_split_scenes(
input_video, scenes, strategies).items(): input_video, scenes, strategies)
for scene_idx, centres in detected_splits.items():
strategies[scene_idx] = 'SPLIT' strategies[scene_idx] = 'SPLIT'
start_f = scene_boundaries[scene_idx][0] start_f = scene_boundaries[scene_idx][0]
splits[start_f] = centres splits[start_f] = centres
@ -513,7 +545,8 @@ def render(input_video, final_output_video, aspect_ratio, content_ranges=None,
graph = split_layout.split_filtergraph( graph = split_layout.split_filtergraph(
orig_w, orig_h, out_w, out_h, left, right) orig_w, orig_h, out_w, out_h, left, right)
elif strategy == 'GENERAL': elif strategy == 'GENERAL':
graph = general_filtergraph(out_w, out_h) graph = general_filtergraph(out_w, out_h,
orig_w=orig_w, orig_h=orig_h)
else: else:
seg_xs = [x if x is not None else 0 for x in xs[start_f:end_f]] seg_xs = [x if x is not None else 0 for x in xs[start_f:end_f]]
cmd_path = os.path.join(workdir, f"cmd_{idx:03d}.txt") cmd_path = os.path.join(workdir, f"cmd_{idx:03d}.txt")
@ -527,7 +560,13 @@ def render(input_video, final_output_video, aspect_ratio, content_ranges=None,
init = f"w={first[0]}:h={first[1]}:x={first[2]}:y={first[3]}" init = f"w={first[0]}:h={first[1]}:x={first[2]}:y={first[3]}"
else: else:
lines = dedupe_sendcmd_lines(seg_xs, fps) lines = dedupe_sendcmd_lines(seg_xs, fps)
init = f"w={crop_w}:h={crop_h}:x={seg_xs[0]}:y=0" # sendcmd only ever moves x, so y is whatever it starts as.
# crop_h equals the source height on any landscape input,
# making this 0; it only bites on a source TALLER than the
# target, where y=0 threw away the bottom of the frame
# instead of trimming both ends.
crop_y = max(0, (orig_h - crop_h) // 2)
init = f"w={crop_w}:h={crop_h}:x={seg_xs[0]}:y={crop_y}"
with open(cmd_path, "w") as f: with open(cmd_path, "w") as f:
f.write("\n".join(lines) + "\n") f.write("\n".join(lines) + "\n")
graph = ( graph = (

View file

@ -5,6 +5,7 @@ from reframe_v2 import (
delivery_size, delivery_size,
general_filtergraph, general_filtergraph,
scene_frame_ranges, scene_frame_ranges,
source_already_fits,
) )
VERTICAL = 9 / 16 VERTICAL = 9 / 16
@ -125,3 +126,48 @@ class TestGeneralLayout:
from reframe_v2 import GENERAL_CONTENT_HEIGHT_RATIO from reframe_v2 import GENERAL_CONTENT_HEIGHT_RATIO
scaled_w = 1920 * GENERAL_CONTENT_HEIGHT_RATIO * (16 / 9) scaled_w = 1920 * GENERAL_CONTENT_HEIGHT_RATIO * (16 / 9)
assert 1080 / scaled_w > 0.70, "keeps less than 70% of the source width" assert 1080 / scaled_w > 0.70, "keeps less than 70% of the source width"
class TestVerticalSource:
"""An already-vertical upload used to come back shrunk into a blurred bed.
The scene classifier sends face-less shots (a slide, a screen recording) to
GENERAL, and GENERAL scaled the content to 42% of the frame height — on a
9:16 source that is 453px of 1080, floating over a blurred copy of itself.
"""
def test_vertical_source_needs_no_reframe(self):
assert source_already_fits(1080, 1920, VERTICAL)
assert source_already_fits(720, 1280, VERTICAL)
assert source_already_fits(1080, 2400, VERTICAL) # taller than 9:16
def test_landscape_and_squarish_sources_still_reframe(self):
assert not source_already_fits(1920, 1080, VERTICAL)
assert not source_already_fits(1080, 1080, VERTICAL)
assert not source_already_fits(1080, 1350, VERTICAL) # 4:5 has width to cut
def test_general_never_renders_the_source_narrower_than_the_frame(self):
# 1080x1920 in a 1080x1920 frame: the foreground must fill it, not sit
# at 0.42 * 1920 = 806 (453px wide).
graph = general_filtergraph(1080, 1920, orig_w=1080, orig_h=1920)
assert "[fga]scale=-2:1920," in graph
def test_portrait_source_fills_the_width(self):
# 4:5 source: full width is reached at 1350, well above the 806 default.
graph = general_filtergraph(1080, 1920, orig_w=1080, orig_h=1350)
assert "[fga]scale=-2:1350," in graph
def test_landscape_keeps_the_presence_ratio(self):
# The floor must not disturb the case the ratio was tuned for: a 16:9
# source fills the width at 608, below the 806 the ratio asks for.
from reframe_v2 import GENERAL_CONTENT_HEIGHT_RATIO
expected = int(1920 * GENERAL_CONTENT_HEIGHT_RATIO)
expected += expected % 2
graph = general_filtergraph(1080, 1920, orig_w=1920, orig_h=1080)
assert f"[fga]scale=-2:{expected}," in graph
def test_floor_keeps_the_height_even(self):
for orig_h in (1919, 1351, 1233):
graph = general_filtergraph(1080, 1920, orig_w=1080, orig_h=orig_h)
h = int(graph.split("[fga]scale=-2:")[1].split(",")[0])
assert h % 2 == 0, (orig_h, h)