fix(clips): deliver 1080x1920 instead of inheriting the source height

An audit of 45 real user clips pulled from R2 on 25-jul-2026 found 86% below
1080 wide, 80% of them exactly 406x720 — well under what TikTok, Reels and
Shorts expect, so the platforms re-encode an already soft image. Two causes,
one on top of the other:

- The download capped format selection at 720p whenever PROXY_URL was set. The
  cap exists to control paid-proxy bandwidth, but it was decided once from
  `_proxy` rather than per attempt, so it also capped the DIRECT attempt — the
  one that costs nothing and, with DIRECT_FIRST=1, serves most downloads. It is
  now chosen per attempt: direct pulls up to 1080p, proxied stays at 720p.
- The reframe set out_h = orig_h, so a 720p source could only ever produce a
  406x720 crop. `delivery_size()` now upscales to a 1080-wide floor and leaves
  anything already above it untouched — a 4K source still delivers 1216x2160,
  so no one loses resolution they supplied.

Applied to the v1 fallback too: an emergency render is still the clip the user
posts. Its frame loop already resizes to the target dims, so only the target
changed.

Crop geometry is unaffected — SmoothedCameraman derives the crop from the source
dimensions and never reads the output pair, which the call site now documents.

Verified end to end: a 1280x720 source that previously rendered 406x720 now
renders 1080x1920, correct aspect, no distortion.
This commit is contained in:
juancarlos.cavero 2026-07-25 17:09:03 +02:00
parent 5b5d3d2306
commit 98fd35130c
3 changed files with 99 additions and 27 deletions

41
main.py
View file

@ -564,12 +564,21 @@ def download_youtube_video(url, output_dir="."):
}
}
# Cap at 720p when using a paid proxy (bandwidth cost); direct keeps best.
if _proxy:
hd_fmt = ('bestvideo[vcodec^=avc1][height<=720][ext=mp4]+bestaudio[ext=m4a]/'
'bestvideo[vcodec^=avc1][height<=720]+bestaudio/best[height<=720][ext=mp4]/best[height<=720]/best')
else:
hd_fmt = 'bestvideo[vcodec^=avc1][ext=mp4]+bestaudio[ext=m4a]/bestvideo[vcodec^=avc1]+bestaudio/best[ext=mp4]/best'
# Cap at 720p ONLY when the bytes actually go through the paid proxy — that
# cap exists to control bandwidth cost, and the direct attempt has none.
#
# This is per-attempt on purpose. Deciding it once from `_proxy` capped the
# DIRECT attempt too, so with DIRECT_FIRST=1 (which serves most downloads)
# every YouTube source arrived at 720p and, since the reframe inherits the
# source height, 80% of delivered clips came out 406x720 (audited 25-jul-2026).
def _hd_fmt_for(proxy):
if proxy:
return ('bestvideo[vcodec^=avc1][height<=720][ext=mp4]+bestaudio[ext=m4a]/'
'bestvideo[vcodec^=avc1][height<=720]+bestaudio/'
'best[height<=720][ext=mp4]/best[height<=720]/best')
return ('bestvideo[vcodec^=avc1][height<=1080][ext=mp4]+bestaudio[ext=m4a]/'
'bestvideo[vcodec^=avc1][height<=1080]+bestaudio/'
'best[height<=1080][ext=mp4]/best[ext=mp4]/best')
fallback_fmt = 'best[ext=mp4]/best'
def _base_opts(extractor_args, proxy):
@ -623,8 +632,8 @@ def download_youtube_video(url, output_dir="."):
and _proxy and hd_args and cookies_path)
attempts = (
([('HD-direct', hd_args, hd_fmt, None)] if _direct_first else [])
+ ([('HD', hd_args, hd_fmt, _proxy)] if hd_args else [])
([('HD-direct', hd_args, _hd_fmt_for(None), None)] if _direct_first else [])
+ ([('HD', hd_args, _hd_fmt_for(_proxy), _proxy)] if hd_args else [])
+ [('fallback', fallback_args, fallback_fmt, _proxy)]
)
@ -827,16 +836,12 @@ def process_video_to_vertical(input_video, final_output_video, aspect_ratio=ASPE
print("\n 🧠 Step 2: Preparing Active Tracking...")
original_width, original_height = get_video_resolution(input_video)
OUTPUT_HEIGHT = original_height
OUTPUT_WIDTH = int(OUTPUT_HEIGHT * aspect_ratio)
# Never ask for a crop wider than the source; shrink height to fit instead.
if OUTPUT_WIDTH > original_width:
OUTPUT_WIDTH = original_width
OUTPUT_HEIGHT = int(OUTPUT_WIDTH / aspect_ratio)
if OUTPUT_WIDTH % 2 != 0:
OUTPUT_WIDTH += 1
if OUTPUT_HEIGHT % 2 != 0:
OUTPUT_HEIGHT += 1
# Same delivery floor as the v2 engine — a fallback render is still the clip
# the user posts, so it must not ship sub-HD. The frame loop below already
# resizes every cropped frame to these dims, so nothing else changes.
from reframe_v2 import delivery_size
OUTPUT_WIDTH, OUTPUT_HEIGHT = delivery_size(original_width, original_height,
aspect_ratio)
# Initialize Cameraman
cameraman = SmoothedCameraman(OUTPUT_WIDTH, OUTPUT_HEIGHT, original_width, original_height, aspect_ratio=aspect_ratio)

View file

@ -26,8 +26,37 @@ from ffmpeg_utils import video_encode_args, QUALITY_FAST, METADATA_SCRUB
ANALYSIS_MAX_WIDTH = 640
# Short-form platforms (TikTok / Reels / Shorts) expect a 1080-wide vertical
# upload; anything smaller is treated as low quality and re-encoded from the
# already-soft source. The crop region is whatever the source height allows, so
# a 720p input yields a 406x720 crop — we scale that up to the delivery floor
# rather than shipping sub-HD. Sources that already exceed it are left alone
# (never downscale quality the user supplied).
DELIVERY_MIN_WIDTH = 1080
# --- pure helpers (CI-testable) --------------------------------------------
def delivery_size(orig_w, orig_h, aspect_ratio):
"""Output (width, height) for a reframe of this source.
Picks the largest crop the source allows, then upscales to
``DELIVERY_MIN_WIDTH`` if that crop is narrower. Both dimensions come back
even (x264/NVENC reject odd ones).
"""
out_h = orig_h
out_w = int(out_h * aspect_ratio)
if out_w > orig_w:
out_w = orig_w
out_h = int(out_w / aspect_ratio)
if out_w < DELIVERY_MIN_WIDTH:
out_w = DELIVERY_MIN_WIDTH
out_h = int(round(out_w / aspect_ratio))
return out_w + (out_w % 2), out_h + (out_h % 2)
def dedupe_sendcmd_lines(xs, fps, target="crop@c"):
"""sendcmd lines setting crop x per frame, deduped to change-points.
@ -165,15 +194,7 @@ def render(input_video, final_output_video, aspect_ratio):
fps = float(fps) # PySceneDetect can hand back a Fraction
orig_w, orig_h = m.get_video_resolution(input_video)
out_h = orig_h
out_w = int(out_h * aspect_ratio)
if out_w > orig_w:
out_w = orig_w
out_h = int(out_w / aspect_ratio)
if out_w % 2:
out_w += 1
if out_h % 2:
out_h += 1
out_w, out_h = delivery_size(orig_w, orig_h, aspect_ratio)
if not scenes:
import cv2
@ -186,6 +207,10 @@ def render(input_video, final_output_video, aspect_ratio):
scene_boundaries = [(s.get_frames(), e.get_frames()) for s, e in scenes]
strategies = m.analyze_scenes_strategy(input_video, scenes)
# The crop geometry comes from the SOURCE dims only — SmoothedCameraman
# derives crop_width/crop_height from video_width/video_height and never
# reads the output pair. So out_w/out_h being the (possibly upscaled)
# delivery size doesn't move the camera; only the final scale= uses it.
cameraman = m.SmoothedCameraman(out_w, out_h, orig_w, orig_h, aspect_ratio=aspect_ratio)
tracker = m.SpeakerTracker(cooldown_frames=30)

View file

@ -1,10 +1,14 @@
from reframe_v2 import (
DELIVERY_MIN_WIDTH,
concat_list_content,
dedupe_sendcmd_lines,
delivery_size,
general_filtergraph,
scene_frame_ranges,
)
VERTICAL = 9 / 16
def test_sendcmd_lines_dedupe_to_change_points():
xs = [100, 100, 100, 104, 104, 110]
@ -40,6 +44,44 @@ def test_concat_list_format():
assert content == "file '/tmp/a/seg_000.mp4'\nfile '/tmp/a/seg_001.mp4'\n"
class TestDeliverySize:
"""A 720p source must not produce a 406x720 clip (prod audit, 25-jul-2026)."""
def test_720p_source_is_upscaled_to_the_delivery_floor(self):
assert delivery_size(1280, 720, VERTICAL) == (1080, 1920)
def test_1080p_source_lands_on_the_floor_exactly(self):
assert delivery_size(1920, 1080, VERTICAL) == (1080, 1920)
def test_tiny_source_still_reaches_the_floor(self):
# 360x640 sources were shipping as-is; platforms treat that as junk.
assert delivery_size(640, 360, VERTICAL) == (1080, 1920)
def test_high_res_source_is_never_downscaled(self):
# 4K source: the native crop is already well past the floor, so keep it.
assert delivery_size(3840, 2160, VERTICAL) == (1216, 2160)
def test_already_vertical_source_keeps_its_full_height(self):
assert delivery_size(1080, 1920, VERTICAL) == (1080, 1920)
def test_square_output_uses_the_same_floor(self):
assert delivery_size(1280, 720, 1.0) == (1080, 1080)
def test_dimensions_are_always_even(self):
for w, h in [(1280, 720), (1920, 1080), (854, 480), (3840, 2160), (641, 361)]:
out_w, out_h = delivery_size(w, h, VERTICAL)
assert out_w % 2 == 0 and out_h % 2 == 0, (w, h)
def test_never_returns_below_the_floor(self):
for w, h in [(320, 180), (640, 360), (1280, 720), (1920, 1080)]:
assert delivery_size(w, h, VERTICAL)[0] >= DELIVERY_MIN_WIDTH
def test_aspect_ratio_is_preserved(self):
for w, h in [(1280, 720), (640, 360), (3840, 2160)]:
out_w, out_h = delivery_size(w, h, VERTICAL)
assert abs(out_w / out_h - VERTICAL) < 0.01, (w, h)
def test_general_filtergraph_targets_output_geometry():
graph = general_filtergraph(608, 1080)
assert "gblur" in graph