From 90b10c190236a6ddd8f206f4df396e6c02ced184 Mon Sep 17 00:00:00 2001 From: "victormanuel.caverogracia" <> Date: Fri, 25 Sep 2026 19:47:34 +0200 Subject: [PATCH] perf(render): burn the watermark in the reframe encode; read AV1 sources - The free-plan watermark (~97% of jobs) rode a pass of its own: decode the finished clip, overlay, encode it all again. It now goes into each reframe segment's own encode (reframe_v2.render(watermark=True), same geometry via main.watermark_filter). One NVENC encode less per clip; the v1 fallback and horizontal clips still use apply_watermark. The editor's paths (recut.py) are untouched. - layout_picker.sample_frames falls back to the ffmpeg CLI when OpenCV reads no frame: OpenCV's bundled FFmpeg has no AV1 software decoder, so AV1 YouTube sources always got the default layout. H.264 sources return byte-identical frames (same JPEG MD5). Bench on balrog, 3 videos, old and new run side by side: job CPU -27 to -43%, wall -6 to -12%; clips SSIM 0.990-0.999 vs before (one generation fewer), audio identical, watermark position checked by eye. Co-Authored-By: Claude Opus 5.5 --- layout_picker.py | 72 +++++++++++++++++++++++++++++-------- main.py | 63 ++++++++++++++++++++------------ reframe_v2.py | 20 +++++++++-- tests/test_layout_picker.py | 15 ++++++++ 4 files changed, 131 insertions(+), 39 deletions(-) diff --git a/layout_picker.py b/layout_picker.py index a6568e8..9fa6ef2 100644 --- a/layout_picker.py +++ b/layout_picker.py @@ -99,6 +99,53 @@ def apply(decision): return touched +def _encode_frame(frame, width): + import cv2 + + h, w = frame.shape[:2] + scaled = cv2.resize(frame, (width, max(2, int(h * width / w))), + interpolation=cv2.INTER_AREA) + ok, buf = cv2.imencode(".jpg", scaled, [cv2.IMWRITE_JPEG_QUALITY, 80]) + return buf.tobytes() if ok else None + + +def _ffmpeg_frames(video_path, n): + """The same evenly spread frames, decoded by the ffmpeg CLI. + + OpenCV's bundled FFmpeg has no software AV1 decoder, so on the AV1 sources + YouTube often serves every read failed ("Failed to get pixel format") and + the picker fell back to the default layout for the whole video (prod, + 25-sep-2026). The system ffmpeg decodes AV1 with libdav1d. + """ + import subprocess + + import cv2 + import numpy as np + + try: + probe = subprocess.run( + ["ffprobe", "-v", "error", "-show_entries", "format=duration", + "-of", "default=nw=1:nk=1", video_path], + capture_output=True, text=True, timeout=60) + duration = float(probe.stdout.strip()) + except (OSError, ValueError, subprocess.SubprocessError): + return [] + frames = [] + for i in range(n): + try: + r = subprocess.run( + ["ffmpeg", "-v", "error", "-ss", f"{i * duration / n:.3f}", + "-i", video_path, "-frames:v", "1", "-c:v", "png", + "-f", "image2pipe", "-"], + capture_output=True, timeout=120) + except (OSError, subprocess.SubprocessError): + continue + frame = cv2.imdecode(np.frombuffer(r.stdout, np.uint8), cv2.IMREAD_COLOR) + if frame is not None: + frames.append(frame) + return frames + + def sample_frames(video_path, n=None, width=None): """JPEG bytes for ``n`` frames spread evenly across the video.""" import cv2 @@ -109,22 +156,19 @@ def sample_frames(video_path, n=None, width=None): total = int(cap.get(cv2.CAP_PROP_FRAME_COUNT)) out = [] try: - if total <= 0: - return out - for i in range(n): - cap.set(cv2.CAP_PROP_POS_FRAMES, int(i * total / n)) - ok, frame = cap.read() - if not ok: - continue - h, w = frame.shape[:2] - scaled = cv2.resize(frame, (width, max(2, int(h * width / w))), - interpolation=cv2.INTER_AREA) - ok, buf = cv2.imencode(".jpg", scaled, - [cv2.IMWRITE_JPEG_QUALITY, 80]) - if ok: - out.append(buf.tobytes()) + if total > 0: + for i in range(n): + cap.set(cv2.CAP_PROP_POS_FRAMES, int(i * total / n)) + ok, frame = cap.read() + if not ok: + continue + jpg = _encode_frame(frame, width) + if jpg: + out.append(jpg) finally: cap.release() + if not out and os.path.exists(video_path): + out = [j for j in (_encode_frame(f, width) for f in _ffmpeg_frames(video_path, n)) if j] return out diff --git a/main.py b/main.py index 2432a9e..445a950 100644 --- a/main.py +++ b/main.py @@ -1196,19 +1196,25 @@ def auto_hook_clip(clip_path, clip): def render_clip(input_video, final_output_video, output_format="auto", - force_strategy=None, crop_overrides=None): + force_strategy=None, crop_overrides=None, watermark=False): """Route a cut clip through the right renderer for the chosen output format. vertical/auto -> 9:16 reframe, square -> 1:1 reframe, horizontal -> keep. ``force_strategy`` (e.g. 'WIDE'/'TRACK') pins every scene's layout — the clip editor's whole-clip framing override. ``crop_overrides`` positions individual scenes by hand (the per-scene reframing editor) and wins over - ``force_strategy`` for the scenes it names.""" + ``force_strategy`` for the scenes it names. + ``watermark`` burns the free-plan mark into the result: inside the reframe + encode on the v2 path, as a separate pass (apply_watermark) otherwise.""" if output_format == "horizontal": - return finalize_clip_passthrough(input_video, final_output_video) + ok = finalize_clip_passthrough(input_video, final_output_video) + if ok and watermark: + apply_watermark(final_output_video) + return ok aspect = 1.0 if output_format == "square" else ASPECT_RATIO return process_video_to_vertical(input_video, final_output_video, aspect_ratio=aspect, force_strategy=force_strategy, - crop_overrides=crop_overrides) + crop_overrides=crop_overrides, + watermark=watermark) # Watermark geometry, as fractions of the clip width/height. @@ -1225,6 +1231,23 @@ WATERMARK_Y_RATIO = 0.40 WATERMARK_OPACITY = 0.85 +def watermark_logo_path(): + return os.path.join(os.path.dirname(os.path.abspath(__file__)), + "assets", "watermark.png") + + +def watermark_filter(vw, vh, video="[0:v]", logo="[1:v]", out=""): + """filter_complex chain overlaying the logo input on a vw x vh video.""" + wm_w = max(80, int(vw * WATERMARK_WIDTH_RATIO)) + x = int(vw * WATERMARK_MARGIN_RATIO) + y = int(vh * WATERMARK_Y_RATIO) + return ( + f"{logo}scale={wm_w}:-1,format=rgba," + f"colorchannelmixer=aa={WATERMARK_OPACITY}[wm];" + f"{video}[wm]overlay=x={x}:y={y}{out}" + ) + + def apply_watermark(video_path): """Burn the OpenShorts watermark into a finished clip (free plan). @@ -1232,8 +1255,7 @@ def apply_watermark(video_path): GENERAL, horizontal passthrough) gets the mark, and later subtitle/hook re-encodes keep it — they re-encode the already-marked pixels. """ - logo_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), - "assets", "watermark.png") + logo_path = watermark_logo_path() if not os.path.exists(logo_path): print(f" ⚠️ Watermark asset missing ({logo_path}); clip kept unmarked.") return False @@ -1251,14 +1273,7 @@ def apply_watermark(video_path): print(f" ⚠️ Could not probe clip for watermark ({e}); clip kept unmarked.") return False - wm_w = max(80, int(vw * WATERMARK_WIDTH_RATIO)) - x = int(vw * WATERMARK_MARGIN_RATIO) - y = int(vh * WATERMARK_Y_RATIO) - filt = ( - f"[1:v]scale={wm_w}:-1,format=rgba," - f"colorchannelmixer=aa={WATERMARK_OPACITY}[wm];" - f"[0:v][wm]overlay=x={x}:y={y}" - ) + filt = watermark_filter(vw, vh) tmp_path = video_path + ".wm.mp4" cmd = ["ffmpeg", "-y", "-i", video_path, "-i", logo_path, "-filter_complex", filt, @@ -1277,7 +1292,7 @@ def apply_watermark(video_path): def process_video_to_vertical(input_video, final_output_video, aspect_ratio=ASPECT_RATIO, - force_strategy=None, crop_overrides=None): + force_strategy=None, crop_overrides=None, watermark=False): """ Core logic to reframe a horizontal video to a target aspect ratio using scene detection and Active Speaker Tracking (MediaPipe). @@ -1294,7 +1309,8 @@ def process_video_to_vertical(input_video, final_output_video, aspect_ratio=ASPE t0 = time.time() result = reframe_v2.render(input_video, final_output_video, aspect_ratio, force_strategy=force_strategy, - crop_overrides=crop_overrides) + crop_overrides=crop_overrides, + watermark=watermark) print(f" ⏱️ Reframe v2 total: {time.time() - t0:.1f}s") return result except Exception as e: @@ -1489,6 +1505,8 @@ def process_video_to_vertical(input_video, final_output_video, aspect_ratio=ASPE if os.path.exists(leftover): os.remove(leftover) + if watermark: + apply_watermark(final_output_video) return True # --- Transcript checkpoint (survive a redeploy without paying twice) --------- @@ -2176,15 +2194,16 @@ if __name__ == '__main__': # ffmpeg cut — re-encoding for precision on strict seconds cut_clip(input_video, clip_temp_path, start, end, i + 1) - success = render_clip(clip_temp_path, clip_final_path, output_format) # Layer order: watermark burns into the canonical (so any # later hook replacement, which re-derives from it, keeps # the branding), the hook is a derived hooked_ file, and - # captions go last on top of whichever is current. Each - # worker writes only its own clip dict, so the re-dump - # after the pool is race-free. - if success and os.environ.get("WATERMARK") == "1": - apply_watermark(clip_final_path) + # captions go last on top of whichever is current. The + # watermark rides the reframe's own encode instead of a + # pass of its own: one encode less per clip on ~97% of + # jobs (free plan). Each worker writes only its own clip + # dict, so the re-dump after the pool is race-free. + success = render_clip(clip_temp_path, clip_final_path, output_format, + watermark=os.environ.get("WATERMARK") == "1") deliver_path = clip_final_path # Which stretches were stacked (SPLIT): captions go on the # seam there, and /api/subtitle needs it again later. diff --git a/reframe_v2.py b/reframe_v2.py index 396b840..1ad0144 100644 --- a/reframe_v2.py +++ b/reframe_v2.py @@ -342,7 +342,7 @@ def _run(cmd): def render(input_video, final_output_video, aspect_ratio, content_ranges=None, - force_strategy=None, crop_overrides=None): + force_strategy=None, crop_overrides=None, watermark=False): """Full v2 reframe of one clip. Raises on failure (caller falls back). ``content_ranges`` comes from screencast_layout.detect_content_ranges() on @@ -358,6 +358,10 @@ def render(input_video, final_output_video, aspect_ratio, content_ranges=None, listed keep the automatic camera, so correcting one bad shot never disturbs the ones the tracker got right. Applied AFTER force_strategy: a per-scene hand position always beats the whole-clip choice for the scenes it names. + + ``watermark`` overlays the free-plan mark (main.watermark_filter) in every + segment's own encode, instead of main.apply_watermark re-encoding the + finished clip once more. """ import main as m content_ranges = content_ranges or [] @@ -522,6 +526,11 @@ def render(input_video, final_output_video, aspect_ratio, content_ranges=None, ranges = scene_frame_ranges(scene_boundaries, strategies, len(xs)) if not ranges: raise RuntimeError("no usable scene ranges") + logo = m.watermark_logo_path() if watermark else None + if logo and not os.path.exists(logo): + print(f" ⚠️ Watermark asset missing ({logo}); clip kept unmarked.") + logo = None + workdir = tempfile.mkdtemp(prefix="reframe_v2_") segments = [] try: @@ -575,10 +584,15 @@ def render(input_video, final_output_video, aspect_ratio, content_ranges=None, f"scale={out_w}:{out_h},setsar=1[v]" ) + inputs, out_label = ["-i", input_video], "[v]" + if logo: + inputs += ["-i", logo] + graph += ";" + m.watermark_filter(out_w, out_h, video="[v]", out="[vw]") + out_label = "[vw]" _run([ "ffmpeg", "-y", "-loglevel", "error", - "-ss", f"{ss:.4f}", "-t", f"{dur:.4f}", "-i", input_video, - "-filter_complex", graph, "-map", "[v]", + "-ss", f"{ss:.4f}", "-t", f"{dur:.4f}", *inputs, + "-filter_complex", graph, "-map", out_label, *video_encode_args(QUALITY_FAST), "-an", seg_path, ]) segments.append(seg_path) diff --git a/tests/test_layout_picker.py b/tests/test_layout_picker.py index d6df4f2..845b224 100644 --- a/tests/test_layout_picker.py +++ b/tests/test_layout_picker.py @@ -146,3 +146,18 @@ class TestShadowMode: assert "[layout-shadow]" in out assert "decision=split" in out assert "would_enable=split_layout,active_speaker" in out + + +def test_sample_frames_falls_back_to_ffmpeg_when_opencv_reads_nothing(tmp_path, monkeypatch): + """AV1 sources: OpenCV's bundled FFmpeg reads no frame, the CLI does.""" + import numpy as np + + src = tmp_path / "av1.mp4" + src.write_bytes(b"not a video OpenCV can open") + frame = np.full((360, 640, 3), 120, dtype=np.uint8) + monkeypatch.setattr(layout_picker, "_ffmpeg_frames", lambda path, n: [frame] * n) + + out = layout_picker.sample_frames(str(src), n=3, width=320) + + assert len(out) == 3 + assert all(j[:2] == b"\xff\xd8" for j in out) # JPEG