diff --git a/main.py b/main.py index 474e044..791578a 100644 --- a/main.py +++ b/main.py @@ -5,6 +5,8 @@ import subprocess import argparse import re import sys +import threading +from concurrent.futures import ThreadPoolExecutor, as_completed from scenedetect import open_video, SceneManager from scenedetect.detectors import ContentDetector from ultralytics import YOLO @@ -282,13 +284,43 @@ class SpeakerTracker: return None +# Detectors never need full-resolution frames: MediaPipe returns relative +# coords and YOLO boxes are scaled back up. Running them on a ≤640px copy cuts +# per-frame preprocessing cost hard, which is what dominates CPU-only renders. +DETECT_MAX_WIDTH = 640 +# The global MediaPipe graph and YOLO model are NOT thread-safe; clips render +# in parallel, so every inference goes through this lock. Contention is small +# (a few ms per call) — the ffmpeg renders are where the parallel time goes. +DETECT_LOCK = threading.Lock() +# Detect every Nth frame; SmoothedCameraman interpolates between updates. +DETECT_STRIDE = max(int(os.environ.get("DETECT_STRIDE", "4")), 1) +# YOLO fallback (no face found) is far heavier than MediaPipe — extra throttle. +YOLO_FALLBACK_STRIDE = DETECT_STRIDE * 2 + + +def _detection_frame(frame): + """Downscaled copy for detectors. Returns (small_frame, scale) with + scale mapping small-frame pixel coords back to the original frame.""" + h, w = frame.shape[:2] + if w <= DETECT_MAX_WIDTH: + return frame, 1.0 + scale = w / DETECT_MAX_WIDTH + small = cv2.resize(frame, (DETECT_MAX_WIDTH, max(int(h / scale), 2)), + interpolation=cv2.INTER_AREA) + return small, scale + + def detect_face_candidates(frame): """ Returns list of all detected faces using lightweight FaceDetection. + Boxes are in ORIGINAL frame coordinates (detection runs downscaled; + MediaPipe's relative coords make the mapping exact). """ height, width, _ = frame.shape - rgb_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) - results = face_detection.process(rgb_frame) + small, _scale = _detection_frame(frame) + rgb_frame = cv2.cvtColor(small, cv2.COLOR_BGR2RGB) + with DETECT_LOCK: + results = face_detection.process(rgb_frame) candidates = [] @@ -312,21 +344,24 @@ def detect_face_candidates(frame): def detect_person_yolo(frame): """ Fallback: Detect largest person using YOLO when face detection fails. - Returns [x, y, w, h] of the person's 'upper body' approximation. + Returns [x, y, w, h] of the person's 'upper body' approximation, in + ORIGINAL frame coordinates (inference runs on a downscaled copy). """ + small, scale = _detection_frame(frame) # Use the globally loaded model - results = model(frame, verbose=False, classes=[0]) # class 0 is person - + with DETECT_LOCK: + results = model(small, verbose=False, classes=[0]) # class 0 is person + if not results: return None - + best_box = None max_area = 0 - + for result in results: boxes = result.boxes for box in boxes: - x1, y1, x2, y2 = [int(i) for i in box.xyxy[0]] + x1, y1, x2, y2 = [int(i * scale) for i in box.xyxy[0]] w = x2 - x1 h = y2 - y1 area = w * h @@ -352,22 +387,28 @@ def create_general_frame(frame, output_width, output_height): # Crop center to aspect ratio bg_scale = output_height / orig_h bg_w = int(orig_w * bg_scale) - bg_resized = cv2.resize(frame, (bg_w, output_height), interpolation=cv2.INTER_LANCZOS4) - + bg_resized = cv2.resize(frame, (bg_w, output_height), interpolation=cv2.INTER_LINEAR) + # Crop center of background start_x = (bg_w - output_width) // 2 if start_x < 0: start_x = 0 background = bg_resized[:, start_x:start_x+output_width] if background.shape[1] != output_width: - background = cv2.resize(background, (output_width, output_height), interpolation=cv2.INTER_LANCZOS4) - - # Blur background - background = cv2.GaussianBlur(background, (51, 51), 0) - + background = cv2.resize(background, (output_width, output_height), interpolation=cv2.INTER_LINEAR) + + # Blur background: blur at quarter resolution and scale back up — visually + # identical for a defocused backdrop, an order of magnitude cheaper than a + # 51px Gaussian at full size. + small_bg = cv2.resize(background, (max(output_width // 4, 2), max(output_height // 4, 2)), + interpolation=cv2.INTER_AREA) + small_bg = cv2.GaussianBlur(small_bg, (13, 13), 0) + background = cv2.resize(small_bg, (output_width, output_height), + interpolation=cv2.INTER_LINEAR) + # 2. Foreground (Fit Width) scale = output_width / orig_w fg_h = int(orig_h * scale) - foreground = cv2.resize(frame, (output_width, fg_h), interpolation=cv2.INTER_LANCZOS4) + foreground = cv2.resize(frame, (output_width, fg_h), interpolation=cv2.INTER_LINEAR) # 3. Overlay y_offset = (output_height - fg_h) // 2 @@ -589,15 +630,17 @@ Technical Details: {str(last_err)} return downloaded_file, sanitized_title def finalize_clip_passthrough(input_video, final_output_video): - """Keep the clip's native framing (for horizontal/16:9 output): just - re-encode with faststart, no reframing/cropping.""" + """Keep the clip's native framing (for horizontal/16:9 output). + + The input is the freshly encoded cut, so a stream-copy remux is enough to + add +faststart — re-encoding here would only cost time and quality. + """ if os.path.exists(final_output_video): os.remove(final_output_video) print(f"🎬 Passthrough (native framing): {input_video}") cmd = [ 'ffmpeg', '-y', '-i', input_video, - *video_encode_args(QUALITY), - '-c:a', 'aac', '-movflags', '+faststart', + '-c', 'copy', '-movflags', '+faststart', final_output_video, ] subprocess.run(cmd, check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=1800) @@ -622,6 +665,19 @@ def process_video_to_vertical(input_video, final_output_video, aspect_ratio=ASPE """ script_start_time = time.time() + # v2 engine: analyze downscaled, render natively in ffmpeg. Any failure + # falls back to the v1 frame loop below so a v2 edge case can't kill jobs. + if os.environ.get("REFRAME_ENGINE", "v2").strip().lower() != "v1": + try: + import reframe_v2 + t0 = time.time() + result = reframe_v2.render(input_video, final_output_video, aspect_ratio) + print(f" ⏱️ Reframe v2 total: {time.time() - t0:.1f}s") + return result + except Exception as e: + print(f" ⚠️ Reframe v2 failed ({type(e).__name__}: {e}) — " + f"falling back to v1 frame loop") + # Define temporary file paths based on the output name base_name = os.path.splitext(final_output_video)[0] temp_video_output = f"{base_name}_temp_video.mp4" @@ -694,6 +750,10 @@ def process_video_to_vertical(input_video, final_output_video, aspect_ratio=ASPE # Global tracker for single-person shots speaker_tracker = SpeakerTracker(cooldown_frames=30) + # Per-stage wall time (server-side diagnostics; hidden from cloud logs). + stage_seconds = {'detect': 0.0, 'write': 0.0} + loop_started = time.time() + with tqdm(total=total_frames, desc=" Processing", file=sys.stdout) as pbar: while cap.isOpened(): ret, frame = cap.read() @@ -720,34 +780,46 @@ def process_video_to_vertical(input_video, final_output_video, aspect_ratio=ASPE else: # "Single Speaker" -> Track & Crop - - # Detect every 2nd frame for performance - if frame_number % 2 == 0: + + # Detect every Nth frame for performance (cameraman smooths in + # between); the much heavier YOLO fallback gets its own stride. + if frame_number % DETECT_STRIDE == 0: + t_det = time.time() candidates = detect_face_candidates(frame) target_box = speaker_tracker.get_target(candidates, frame_number, original_width) if target_box: cameraman.update_target(target_box) - else: + elif frame_number % YOLO_FALLBACK_STRIDE == 0: person_box = detect_person_yolo(frame) if person_box: cameraman.update_target(person_box) + 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) - + # Crop if y2 > y1 and x2 > x1: cropped = frame[y1:y2, x1:x2] - output_frame = cv2.resize(cropped, (OUTPUT_WIDTH, OUTPUT_HEIGHT), interpolation=cv2.INTER_LANCZOS4) + output_frame = cv2.resize(cropped, (OUTPUT_WIDTH, OUTPUT_HEIGHT), interpolation=cv2.INTER_LINEAR) else: - output_frame = cv2.resize(frame, (OUTPUT_WIDTH, OUTPUT_HEIGHT), interpolation=cv2.INTER_LANCZOS4) + output_frame = cv2.resize(frame, (OUTPUT_WIDTH, OUTPUT_HEIGHT), interpolation=cv2.INTER_LINEAR) + t_wr = time.time() ffmpeg_process.stdin.write(output_frame.tobytes()) + stage_seconds['write'] += time.time() - t_wr frame_number += 1 pbar.update(1) + loop_total = time.time() - loop_started + other = loop_total - stage_seconds['detect'] - stage_seconds['write'] + print(f"\n ⏱️ Frame loop: {loop_total:.1f}s total — " + f"detect {stage_seconds['detect']:.1f}s, " + f"encode-wait {stage_seconds['write']:.1f}s, " + f"decode+render {other:.1f}s ({frame_number} frames)") + ffmpeg_process.stdin.close() stderr_output = ffmpeg_process.stderr.read().decode() ffmpeg_process.wait() @@ -1027,40 +1099,51 @@ if __name__ == '__main__': json.dump(clips_data, f, indent=2) print(f" Saved metadata to {metadata_file}") - # 5. Process each clip - for i, clip in enumerate(clips_data['shorts']): + # 5. Process clips in parallel: each worker cuts + renders one + # clip. Renders are mostly ffmpeg subprocesses (parallelize well); + # detector inference is serialized internally via DETECT_LOCK. + def _process_one_clip(i, clip): start = clip['start'] end = clip['end'] print(f"\n🎬 Processing Clip {i+1}: {start}s - {end}s") print(f" Title: {clip.get('video_title_for_youtube_short', 'No Title')}") - - # Cut clip + clip_filename = f"{video_title}_clip_{i+1}.mp4" clip_temp_path = os.path.join(output_dir, f"temp_{clip_filename}") clip_final_path = os.path.join(output_dir, clip_filename) - - # ffmpeg cut - # Using re-encoding for precision as requested by strict seconds - cut_command = [ - 'ffmpeg', '-y', - '-ss', str(start), - '-to', str(end), - '-i', input_video, - *video_encode_args(QUALITY_FAST), - '-c:a', 'aac', - clip_temp_path - ] - subprocess.run(cut_command, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE) - - # Process vertical - success = render_clip(clip_temp_path, clip_final_path, output_format) - - if success: - print(f" ✅ Clip {i+1} ready: {clip_final_path}") - - # Clean up temp cut - if os.path.exists(clip_temp_path): - os.remove(clip_temp_path) + + try: + # ffmpeg cut — re-encoding for precision on strict seconds + cut_command = [ + 'ffmpeg', '-y', + '-ss', str(start), + '-to', str(end), + '-i', input_video, + *video_encode_args(QUALITY_FAST), + '-c:a', 'aac', + clip_temp_path + ] + subprocess.run(cut_command, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE) + + success = render_clip(clip_temp_path, clip_final_path, output_format) + if success: + print(f" ✅ Clip {i+1} ready: {clip_final_path}") + return success + finally: + if os.path.exists(clip_temp_path): + os.remove(clip_temp_path) + + clip_workers = max(int(os.environ.get("CLIP_WORKERS", "3")), 1) + shorts = clips_data['shorts'] + with ThreadPoolExecutor(max_workers=min(clip_workers, len(shorts))) as pool: + futures = {pool.submit(_process_one_clip, i, clip): i + for i, clip in enumerate(shorts)} + for future in as_completed(futures): + i = futures[future] + try: + future.result() + except Exception as e: + print(f" ❌ Clip {i+1} failed: {type(e).__name__}: {e}") # Clean up original if requested if args.url and not args.keep_original and os.path.exists(input_video): diff --git a/reframe_v2.py b/reframe_v2.py new file mode 100644 index 0000000..ec1e61b --- /dev/null +++ b/reframe_v2.py @@ -0,0 +1,249 @@ +"""Reframe engine v2: analyze in Python, render natively in ffmpeg. + +v1 decodes every frame at full resolution in OpenCV, crops/resizes in numpy +and pipes raw frames back into ffmpeg. v2 splits that into: + + 1. ANALYSIS — one ffmpeg-decoded pass at <=640px feeding the same detectors + and the same SmoothedCameraman/SpeakerTracker state machines as v1, so + the resulting camera trajectory (crop x per frame) is equivalent. + 2. RENDER — one ffmpeg process per scene doing decode -> dynamic crop + (sendcmd) -> scale -> encode natively (TRACK scenes), or the blurred + background filtergraph (GENERAL scenes); segments are then concatenated + with stream copy and the audio mapped straight from the source clip. + +No raw-frame piping, no second full-res decode, one less intermediate encode. +Callers must treat any exception as "fall back to the v1 loop". + +Pure helpers (sendcmd/concat generation, scene slicing) have no heavy imports +so they stay unit-testable in CI. +""" +import os +import subprocess +import tempfile + +from ffmpeg_utils import video_encode_args, QUALITY_FAST + +ANALYSIS_MAX_WIDTH = 640 + + +# --- pure helpers (CI-testable) -------------------------------------------- + +def dedupe_sendcmd_lines(xs, fps, target="crop@c"): + """sendcmd lines setting crop x per frame, deduped to change-points. + + Timestamps are relative to the segment (the render seeks per scene). + """ + lines = [] + prev = None + for i, x in enumerate(xs): + if x != prev: + lines.append(f"{i / fps:.4f} {target} x {x};") + prev = x + return lines + + +def scene_frame_ranges(scene_boundaries, strategies, total_frames): + """Clamp scene (start, end) frame ranges to the decoded frame count, + dropping empty ranges. Each range keeps its strategy so later indices + can't misalign when a range is dropped.""" + ranges = [] + for i, (start_f, end_f) in enumerate(scene_boundaries): + strategy = strategies[i] if i < len(strategies) else 'TRACK' + start_f = max(0, min(start_f, total_frames)) + end_f = max(start_f, min(end_f, total_frames)) + if end_f > start_f: + ranges.append((start_f, end_f, strategy)) + return ranges + + +def concat_list_content(segment_paths): + # Single quotes per concat-demuxer spec; our paths are tempfile-generated + # (no quotes in them). + return "".join(f"file '{p}'\n" for p in segment_paths) + + +def general_filtergraph(out_w, out_h): + """Blurred-background 'general shot' layout, mirroring v1's + create_general_frame: bg fills height (center-cropped, blurred), fg fits + width, centered vertically.""" + return ( + f"[0:v]split=2[bga][fga];" + f"[bga]scale=-2:{out_h},crop=w=min(iw\\,{out_w}):h={out_h}," + f"scale={out_w}:{out_h},gblur=sigma=12[bg];" + f"[fga]scale={out_w}:-2[fg];" + f"[bg][fg]overlay=x=(W-w)/2:y=(H-h)/2,setsar=1[v]" + ) + + +# --- analysis --------------------------------------------------------------- + +def _analyze_trajectory(input_video, scenes_boundaries, scene_strategies, + fps, orig_w, orig_h, cameraman, tracker): + """Replays v1's per-frame decision loop on a downscaled ffmpeg-decoded + stream. Returns xs: crop x per frame (None on GENERAL frames).""" + import numpy as np + import main as m + + small_w = min(ANALYSIS_MAX_WIDTH, orig_w) + if small_w % 2: + small_w -= 1 + small_h = max(int(orig_h * small_w / orig_w), 2) + if small_h % 2: + small_h += 1 + scale = orig_w / small_w + frame_bytes = small_w * small_h * 3 + + proc = subprocess.Popen( + ["ffmpeg", "-loglevel", "error", "-i", input_video, + "-vf", f"scale={small_w}:{small_h}", + "-f", "rawvideo", "-pix_fmt", "bgr24", "-"], + stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, bufsize=frame_bytes * 4) + + xs = [] + frame_number = 0 + current_scene_index = 0 + try: + while True: + buf = proc.stdout.read(frame_bytes) + if len(buf) < frame_bytes: + break + frame = np.frombuffer(buf, dtype=np.uint8).reshape((small_h, small_w, 3)) + + if current_scene_index < len(scenes_boundaries): + start_f, end_f = scenes_boundaries[current_scene_index] + if frame_number >= end_f and current_scene_index < len(scenes_boundaries) - 1: + current_scene_index += 1 + + strategy = (scene_strategies[current_scene_index] + if current_scene_index < len(scene_strategies) else 'TRACK') + + if strategy == 'GENERAL': + cameraman.current_center_x = orig_w / 2 + cameraman.target_center_x = orig_w / 2 + xs.append(None) + else: + if frame_number % m.DETECT_STRIDE == 0: + candidates = m.detect_face_candidates(frame) + for cand in candidates: + cand['box'] = [int(v * scale) for v in cand['box']] + cand['score'] = cand['box'][2] * cand['box'][3] + target_box = tracker.get_target(candidates, frame_number, orig_w) + if target_box: + cameraman.update_target(target_box) + elif frame_number % m.YOLO_FALLBACK_STRIDE == 0: + person_box = m.detect_person_yolo(frame) + if 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) + xs.append(x1) + + frame_number += 1 + finally: + proc.stdout.close() + proc.wait() + + return xs + + +# --- render ----------------------------------------------------------------- + +def _run(cmd): + subprocess.run(cmd, check=True, stdout=subprocess.DEVNULL, + stderr=subprocess.PIPE, timeout=1800) + + +def render(input_video, final_output_video, aspect_ratio): + """Full v2 reframe of one clip. Raises on failure (caller falls back).""" + import main as m + + print(" 🚀 Reframe engine v2 (ffmpeg-native render)") + scenes, fps = m.detect_scenes(input_video) + 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 + + if not scenes: + import cv2 + cap = cv2.VideoCapture(input_video) + total = int(cap.get(cv2.CAP_PROP_FRAME_COUNT)) + cap.release() + from scenedetect import FrameTimecode + scenes = [(FrameTimecode(0, fps), FrameTimecode(total, fps))] + + scene_boundaries = [(s.get_frames(), e.get_frames()) for s, e in scenes] + strategies = m.analyze_scenes_strategy(input_video, scenes) + + cameraman = m.SmoothedCameraman(out_w, out_h, orig_w, orig_h, aspect_ratio=aspect_ratio) + tracker = m.SpeakerTracker(cooldown_frames=30) + + xs = _analyze_trajectory(input_video, scene_boundaries, strategies, fps, + orig_w, orig_h, cameraman, tracker) + if not xs: + raise RuntimeError("analysis produced no frames") + + ranges = scene_frame_ranges(scene_boundaries, strategies, len(xs)) + if not ranges: + raise RuntimeError("no usable scene ranges") + + crop_w, crop_h = cameraman.crop_width, cameraman.crop_height + workdir = tempfile.mkdtemp(prefix="reframe_v2_") + segments = [] + try: + for idx, (start_f, end_f, strategy) in enumerate(ranges): + seg_path = os.path.join(workdir, f"seg_{idx:03d}.mp4") + ss = start_f / fps + dur = (end_f - start_f) / fps + + if strategy == 'GENERAL': + graph = general_filtergraph(out_w, out_h) + else: + 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") + with open(cmd_path, "w") as f: + f.write("\n".join(dedupe_sendcmd_lines(seg_xs, fps)) + "\n") + graph = ( + f"[0:v]sendcmd=f='{cmd_path}'," + f"crop@c=w={crop_w}:h={crop_h}:x={seg_xs[0]}:y=0," + f"scale={out_w}:{out_h},setsar=1[v]" + ) + + _run([ + "ffmpeg", "-y", "-loglevel", "error", + "-ss", f"{ss:.4f}", "-t", f"{dur:.4f}", "-i", input_video, + "-filter_complex", graph, "-map", "[v]", + *video_encode_args(QUALITY_FAST), "-an", seg_path, + ]) + segments.append(seg_path) + + list_path = os.path.join(workdir, "concat.txt") + with open(list_path, "w") as f: + f.write(concat_list_content(segments)) + + # Concat video segments (stream copy) + audio straight from the clip. + _run([ + "ffmpeg", "-y", "-loglevel", "error", + "-f", "concat", "-safe", "0", "-i", list_path, + "-i", input_video, + "-map", "0:v:0", "-map", "1:a:0?", + "-c:v", "copy", "-c:a", "copy", + final_output_video, + ]) + finally: + import shutil + shutil.rmtree(workdir, ignore_errors=True) + + print(f" ✅ Clip saved to {final_output_video}") + return True diff --git a/tests/test_reframe_v2.py b/tests/test_reframe_v2.py new file mode 100644 index 0000000..0557a19 --- /dev/null +++ b/tests/test_reframe_v2.py @@ -0,0 +1,47 @@ +from reframe_v2 import ( + concat_list_content, + dedupe_sendcmd_lines, + general_filtergraph, + scene_frame_ranges, +) + + +def test_sendcmd_lines_dedupe_to_change_points(): + xs = [100, 100, 100, 104, 104, 110] + lines = dedupe_sendcmd_lines(xs, fps=30.0) + assert lines == [ + "0.0000 crop@c x 100;", + "0.1000 crop@c x 104;", + "0.1667 crop@c x 110;", + ] + + +def test_sendcmd_static_camera_is_single_command(): + assert len(dedupe_sendcmd_lines([250] * 300, fps=30.0)) == 1 + + +def test_scene_ranges_clamped_and_keep_strategy(): + ranges = scene_frame_ranges( + [(0, 100), (100, 250), (250, 400)], + ['TRACK', 'GENERAL', 'TRACK'], + total_frames=200, + ) + # Third scene starts past the decoded frame count -> dropped, and the + # GENERAL strategy stays attached to its own range. + assert ranges == [(0, 100, 'TRACK'), (100, 200, 'GENERAL')] + + +def test_scene_ranges_missing_strategy_defaults_to_track(): + assert scene_frame_ranges([(0, 10)], [], 10) == [(0, 10, 'TRACK')] + + +def test_concat_list_format(): + content = concat_list_content(["/tmp/a/seg_000.mp4", "/tmp/a/seg_001.mp4"]) + assert content == "file '/tmp/a/seg_000.mp4'\nfile '/tmp/a/seg_001.mp4'\n" + + +def test_general_filtergraph_targets_output_geometry(): + graph = general_filtergraph(608, 1080) + assert "gblur" in graph + assert "scale=608:-2" in graph + assert "overlay=x=(W-w)/2:y=(H-h)/2" in graph