"""Reframing helpers for the video pipeline.""" from typing import Any from typing import Dict from typing import List from typing import Optional from pathlib import Path from typing import Tuple import cv2 import numpy as np import re import shutil import subprocess import tempfile from .common import ( FACE_PRESENCE_MIN_AREA, FACE_PRESENCE_RATE, FACE_RATE_WINDOW, KENBURNS_FOCUS_Y, FIT_DETAIL_MARGIN_FRAC, FIT_MAX_FOREGROUND_H, FIT_MAX_ZOOM_LEVELS, FIT_VISIBLE_LEVELS, FIT_ZOOM_HOLD_SECONDS, KENBURNS_MIN_SECONDS, KENBURNS_SUPERSAMPLE_H, KENBURNS_SUPERSAMPLE_W, KENBURNS_ZOOM_DELTA, LAYOUT_SNAP_WINDOW, MIN_LAYOUT_SECONDS, OUTPUT_FPS, UPSCALE_SHARPEN_FILTER, VERTICAL_SCALE_CHAIN, logger, ) from .face_detection import open_haar_cascade, open_yunet_detector from .scene_context import ( ContextAnalyzer, SceneEvidence, build_context_layout_plan, context_scene_cuts, ) from .ffmpeg import ( build_audio_output_args, build_final_video_encode_args, clamp_even, ffmpeg_escape_filter_path, ffprobe_duration, ffprobe_has_audio, ffprobe_video_size, round_to_even, run_ffmpeg_command, subtitles_filter_fragment, ) from .broll_overlay import ( broll_input_args, broll_overlay_graph, normalize_broll_overlays, ) from .source_limits import ( FPS_EPSILON, MAX_OUTPUT_FPS, fit_within_1080p, output_rate_token, probe_video_geometry, ) def detect_optimal_crop_region( video_path: Path, start_time: float, end_time: float, target_ratio: float = 9 / 16, ) -> Tuple[int, int, int, int]: """Detect optimal crop region using improved face detection.""" try: original_width, original_height = ffprobe_video_size(video_path) # Calculate target dimensions and ensure they're even if original_width / original_height > target_ratio: new_width = round_to_even(int(original_height * target_ratio)) new_height = round_to_even(original_height) else: new_width = round_to_even(original_width) new_height = round_to_even(int(original_width / target_ratio)) # Try improved face detection face_centers = detect_faces_in_clip(video_path, start_time, end_time) # Calculate crop position if face_centers: # Use weighted average of face centers with temporal consistency total_weight = sum( area * confidence for _, _, area, confidence in face_centers ) if total_weight > 0: weighted_x = ( sum( x * area * confidence for x, y, area, confidence in face_centers ) / total_weight ) weighted_y = ( sum( y * area * confidence for x, y, area, confidence in face_centers ) / total_weight ) # Add slight bias towards upper portion for better face framing weighted_y = max(0, weighted_y - new_height * 0.1) x_offset = max( 0, min(int(weighted_x - new_width // 2), original_width - new_width) ) y_offset = max( 0, min( int(weighted_y - new_height // 2), original_height - new_height ), ) logger.info( f"Face-centered crop: {len(face_centers)} faces detected with improved algorithm" ) else: # Center crop x_offset = ( (original_width - new_width) // 2 if original_width > new_width else 0 ) y_offset = ( (original_height - new_height) // 2 if original_height > new_height else 0 ) else: # Center crop x_offset = ( (original_width - new_width) // 2 if original_width > new_width else 0 ) y_offset = ( (original_height - new_height) // 2 if original_height > new_height else 0 ) logger.info("Using center crop (no faces detected)") # Ensure offsets are even too x_offset = round_to_even(x_offset) y_offset = round_to_even(y_offset) logger.info( f"Crop dimensions: {new_width}x{new_height} at offset ({x_offset}, {y_offset})" ) return (x_offset, y_offset, new_width, new_height) except Exception as e: logger.error(f"Error in crop detection: {e}") # Fallback to center crop original_width, original_height = ffprobe_video_size(video_path) if original_width / original_height > target_ratio: new_width = round_to_even(int(original_height * target_ratio)) new_height = round_to_even(original_height) else: new_width = round_to_even(original_width) new_height = round_to_even(int(original_width / target_ratio)) x_offset = ( round_to_even((original_width - new_width) // 2) if original_width > new_width else 0 ) y_offset = ( round_to_even((original_height - new_height) // 2) if original_height > new_height else 0 ) return (x_offset, y_offset, new_width, new_height) def detect_faces_in_clip( video_path: Path, start_time: float, end_time: float ) -> List[Tuple[int, int, int, float]]: """ Improved face detection using multiple methods and temporal consistency. Returns list of (x, y, area, confidence) tuples. """ face_centers = [] try: # YuNet (most accurate) with Haar as the last-resort fallback yunet, haar_cascade = _open_face_detectors() # Try to load DNN face detector (more accurate than Haar) dnn_net = None try: # Load OpenCV's DNN face detector prototxt_path = cv2.data.haarcascades.replace( "haarcascades", "opencv_face_detector.pbtxt" ) model_path = cv2.data.haarcascades.replace( "haarcascades", "opencv_face_detector_uint8.pb" ) # If DNN model files don't exist, we'll fall back to Haar cascade import os if os.path.exists(prototxt_path) and os.path.exists(model_path): dnn_net = cv2.dnn.readNetFromTensorflow(model_path, prototxt_path) logger.info("OpenCV DNN face detector loaded as backup") else: logger.info("OpenCV DNN face detector not available") except Exception: logger.info("OpenCV DNN face detector failed to load") # Sample more frames for better face detection (every 0.5 seconds) duration = end_time - start_time sample_interval = min(0.5, duration / 10) # At least 10 samples, max every 0.5s sample_times = [] current_time = start_time while current_time < end_time: sample_times.append(current_time) current_time += sample_interval # Ensure we always sample the middle and end if duration > 1.0: middle_time = start_time + duration / 2 if middle_time not in sample_times: sample_times.append(middle_time) sample_times = [t for t in sample_times if t < end_time] logger.info(f"Sampling {len(sample_times)} frames for face detection") capture = cv2.VideoCapture(str(video_path)) if not capture.isOpened(): logger.warning("Unable to open video for face detection: %s", video_path) return [] for sample_time in sample_times: try: capture.set(cv2.CAP_PROP_POS_MSEC, max(0.0, sample_time) * 1000.0) ok, frame_bgr = capture.read() if not ok or frame_bgr is None: continue height, width = frame_bgr.shape[:2] detected_faces = [] # Try YuNet first (most accurate) if yunet is not None: try: for fx, fy, fw, fh, confidence in yunet.detect(frame_bgr): x, y, w, h = int(fx), int(fy), int(fw), int(fh) if w > 30 and h > 30: # Minimum face size detected_faces.append((x, y, w, h, confidence)) except Exception as e: logger.warning( f"YuNet detection failed for frame at {sample_time}s: {e}" ) # If YuNet didn't find faces, try DNN detector if not detected_faces and dnn_net is not None: try: blob = cv2.dnn.blobFromImage( frame_bgr, 1.0, (300, 300), [104, 117, 123] ) dnn_net.setInput(blob) detections = dnn_net.forward() for i in range(detections.shape[2]): confidence = detections[0, 0, i, 2] if confidence > 0.5: # Confidence threshold x1 = int(detections[0, 0, i, 3] * width) y1 = int(detections[0, 0, i, 4] * height) x2 = int(detections[0, 0, i, 5] * width) y2 = int(detections[0, 0, i, 6] * height) w = x2 - x1 h = y2 - y1 if w > 30 and h > 30: # Minimum face size detected_faces.append((x1, y1, w, h, confidence)) except Exception as e: logger.warning( f"DNN detection failed for frame at {sample_time}s: {e}" ) # If still no faces found, use Haar cascade if not detected_faces: try: gray = cv2.cvtColor(frame_bgr, cv2.COLOR_BGR2GRAY) faces = haar_cascade.detectMultiScale( gray, scaleFactor=1.05, # More sensitive minNeighbors=3, # Less strict minSize=(40, 40), # Smaller minimum size maxSize=( int(width * 0.7), int(height * 0.7), ), # Maximum size limit ) for x, y, w, h in faces: # Estimate confidence based on face size and position face_area = w * h relative_size = face_area / (width * height) confidence = min( 0.9, 0.3 + relative_size * 2 ) # Rough confidence estimate detected_faces.append((x, y, w, h, confidence)) except Exception as e: logger.warning( f"Haar cascade detection failed for frame at {sample_time}s: {e}" ) # Process detected faces for x, y, w, h, confidence in detected_faces: face_center_x = x + w // 2 face_center_y = y + h // 2 face_area = w * h # Filter out very small or very large faces frame_area = width * height relative_area = face_area / frame_area if ( 0.005 < relative_area < 0.3 ): # Face should be 0.5% to 30% of frame face_centers.append( (face_center_x, face_center_y, face_area, confidence) ) except Exception as e: logger.warning(f"Error detecting faces in frame at {sample_time}s: {e}") continue capture.release() # Remove outliers (faces that are very far from the median position) if len(face_centers) > 2: face_centers = filter_face_outliers(face_centers) logger.info(f"Detected {len(face_centers)} reliable face centers") return face_centers except Exception as e: logger.error(f"Error in face detection: {e}") return [] def filter_face_outliers( face_centers: List[Tuple[int, int, int, float]], ) -> List[Tuple[int, int, int, float]]: """Remove face detections that are outliers (likely false positives).""" if len(face_centers) < 3: return face_centers try: # Calculate median position x_positions = [x for x, y, area, conf in face_centers] y_positions = [y for x, y, area, conf in face_centers] median_x = np.median(x_positions) median_y = np.median(y_positions) # Calculate standard deviation std_x = np.std(x_positions) std_y = np.std(y_positions) # Filter out faces that are more than 2 standard deviations away filtered_faces = [] for face in face_centers: x, y, area, conf = face if abs(x - median_x) <= 2 * std_x and abs(y - median_y) <= 2 * std_y: filtered_faces.append(face) logger.info( f"Filtered {len(face_centers)} -> {len(filtered_faces)} faces (removed outliers)" ) return ( filtered_faces if filtered_faces else face_centers ) # Return original if all filtered except Exception as e: logger.warning(f"Error filtering face outliers: {e}") return face_centers def count_scene_cuts(video_path: Path, threshold: float = 0.35) -> int: """Count likely scene cuts in a clip using ffmpeg's scene score.""" result = run_ffmpeg_command( [ "ffmpeg", "-i", str(video_path), "-filter:v", f"select='gt(scene,{threshold})',showinfo", "-f", "null", "-", ], timeout=300, ) if result.returncode != 0: return 0 return len(re.findall(r"pts_time:", result.stderr)) def parse_motion_metadata(path: Path) -> Tuple[List[float], List[float]]: times: List[float] = [] values: List[float] = [] current_time: Optional[float] = None for line in path.read_text(errors="ignore").splitlines(): time_match = re.search(r"pts_time:([0-9.]+)", line) if time_match: current_time = float(time_match.group(1)) continue value_match = re.search(r"lavfi\.signalstats\.YAVG=([0-9.]+)", line) if value_match and current_time is not None: times.append(current_time) values.append(float(value_match.group(1))) current_time = None return times, values def smooth_values(values: List[float], window: int = 15) -> List[float]: if not values: return [] smoothed: List[float] = [] half = window // 2 for idx in range(len(values)): start = max(0, idx - half) end = min(len(values), idx + half + 1) smoothed.append(sum(values[start:end]) / (end - start)) return smoothed def build_speaker_timeline_from_motion( times: List[float], left_values: List[float], right_values: List[float], min_duration: float = 1.0, ) -> List[Dict[str, Any]]: if not times or len(left_values) != len(right_values): return [] def normalize(values: List[float]) -> List[float]: mean_value = sum(values) / max(len(values), 1) return [value / mean_value if mean_value > 0 else 0.0 for value in values] left = smooth_values(normalize(left_values)) right = smooth_values(normalize(right_values)) if not left or not right: return [] margin = 1.15 current = 0 if left[0] >= right[0] else 1 speakers: List[int] = [] for left_value, right_value in zip(left, right): if current == 0 and right_value > left_value * margin: current = 1 elif current == 1 and left_value > right_value * margin: current = 0 speakers.append(current) segments: List[Dict[str, Any]] = [] idx = 0 while idx < len(speakers): end_idx = idx while end_idx + 1 < len(speakers) and speakers[end_idx + 1] == speakers[idx]: end_idx += 1 seg_start = times[idx] seg_end = times[min(end_idx + 1, len(times) - 1)] if seg_end <= seg_start: seg_end = seg_start + 0.05 segments.append( { "start": seg_start, "end": seg_end, "speaker": "left" if speakers[idx] == 0 else "right", } ) idx = end_idx + 1 merged: List[Dict[str, Any]] = [] for segment in segments: if merged and segment["end"] - segment["start"] < min_duration: merged[-1]["end"] = segment["end"] continue if merged and merged[-1]["speaker"] == segment["speaker"]: merged[-1]["end"] = segment["end"] continue merged.append(segment) return merged def cluster_two_face_regions( face_centers: List[Tuple[int, int, int, float]], width: int, height: int, ) -> Optional[Dict[str, Dict[str, int]]]: """Approximate left/right face regions from sampled face centers.""" if len(face_centers) < 2: return None median_x = float(np.median([face[0] for face in face_centers])) left_faces = [face for face in face_centers if face[0] <= median_x] right_faces = [face for face in face_centers if face[0] > median_x] if not left_faces or not right_faces: return None def region(faces: List[Tuple[int, int, int, float]]) -> Dict[str, int]: center_x = int(np.median([face[0] for face in faces])) center_y = int(np.median([face[1] for face in faces])) face_size = int(np.sqrt(max(1, float(np.median([face[2] for face in faces]))))) roi_w = max(80, int(face_size * 1.4)) roi_h = max(70, int(face_size * 0.9)) roi_x = clamp_even(center_x - roi_w // 2, 0, max(0, width - roi_w)) roi_y = clamp_even(center_y, 0, max(0, height - roi_h)) tile_w = min(width, max(160, int(face_size * 2.8))) tile_h = min(height, max(160, int(face_size * 2.4))) tile_x = clamp_even(center_x - tile_w // 2, 0, max(0, width - tile_w)) tile_y = clamp_even(center_y - int(tile_h * 0.42), 0, max(0, height - tile_h)) return { "center_x": center_x, "center_y": center_y, "roi_x": roi_x, "roi_y": roi_y, "roi_w": round_to_even(min(roi_w, width - roi_x)), "roi_h": round_to_even(min(roi_h, height - roi_y)), "tile_x": tile_x, "tile_y": tile_y, "tile_w": round_to_even(min(tile_w, width - tile_x)), "tile_h": round_to_even(min(tile_h, height - tile_y)), } left = region(left_faces) right = region(right_faces) if abs(right["center_x"] - left["center_x"]) < width * 0.15: return None return {"left": left, "right": right} def build_pan_expression( timeline: List[Dict[str, Any]], left_x: int, right_x: int, ramp: float = 0.45 ) -> str: """Eased crop-x expression that glides between two speaker framings. Instead of snapping the crop instantly at each speaker change, this ramps smoothly over ``ramp`` seconds, giving a natural camera-pan feel. """ if not timeline: return str(left_x) def x_for(speaker: str) -> int: return left_x if speaker == "left" else right_x keys: List[Tuple[float, float]] = [(0.0, float(x_for(timeline[0]["speaker"])))] for segment in timeline: switch_t = max(0.0, float(segment["start"])) target = float(x_for(segment["speaker"])) if abs(target - keys[-1][1]) < 1.0: continue keys.append((switch_t, keys[-1][1])) # hold previous framing until switch keys.append((switch_t + ramp, target)) # then ease into the new framing cleaned: List[Tuple[float, int]] = [] for t, x in keys: if cleaned and t <= cleaned[-1][0]: t = cleaned[-1][0] + 0.01 cleaned.append((t, int(round(x)))) if len(cleaned) < 2: return str(int(cleaned[0][1]) if cleaned else left_x) return build_smooth_pan_expression(cleaned) def detect_speaker_reframe_plan( clip_path: Path, output_format: str, ) -> Optional[Dict[str, Any]]: """Build a speaker-aware pan or split-screen plan for a trimmed clip.""" try: width, height = ffprobe_video_size(clip_path) if width / max(height, 1) <= 1.2: return None scene_cuts = count_scene_cuts(clip_path) if scene_cuts > 2: logger.info("Skipping speaker reframe: %d scene cuts detected", scene_cuts) return None duration = ffprobe_duration(clip_path) face_centers = detect_faces_in_clip(clip_path, 0, min(duration, 12.0)) regions = cluster_two_face_regions(face_centers, width, height) if not regions: return None crop_w = round_to_even(min(width, int(height * 9 / 16))) left_x = clamp_even( regions["left"]["center_x"] - crop_w // 2, 0, max(0, width - crop_w), ) right_x = clamp_even( regions["right"]["center_x"] - crop_w // 2, 0, max(0, width - crop_w), ) if output_format == "vertical_split": return { "mode": "split", "width": width, "height": height, "regions": regions, } with tempfile.TemporaryDirectory(prefix="supoclip_motion_") as motion_dir: left_motion = Path(motion_dir) / "left.txt" right_motion = Path(motion_dir) / "right.txt" left = regions["left"] right = regions["right"] filter_complex = ( f"[0:v]split=2[l][r];" f"[l]crop={left['roi_w']}:{left['roi_h']}:{left['roi_x']}:{left['roi_y']}," f"format=gray,tblend=all_mode=difference,signalstats," f"metadata=mode=print:key=lavfi.signalstats.YAVG:file={ffmpeg_escape_filter_path(left_motion)}[lo];" f"[r]crop={right['roi_w']}:{right['roi_h']}:{right['roi_x']}:{right['roi_y']}," f"format=gray,tblend=all_mode=difference,signalstats," f"metadata=mode=print:key=lavfi.signalstats.YAVG:file={ffmpeg_escape_filter_path(right_motion)}[ro]" ) result = run_ffmpeg_command( [ "ffmpeg", "-y", "-i", str(clip_path), "-filter_complex", filter_complex, "-map", "[lo]", "-f", "null", "-", "-map", "[ro]", "-f", "null", "-", ], timeout=300, ) if result.returncode != 0: return None times, left_values = parse_motion_metadata(left_motion) _, right_values = parse_motion_metadata(right_motion) timeline = build_speaker_timeline_from_motion( times, left_values, right_values, ) if len(timeline) < 2: return None return { "mode": "pan", "width": width, "height": height, "crop_w": crop_w, "crop_h": height, "x_expression": build_pan_expression(timeline, left_x, right_x), "timeline": timeline, } except Exception as exc: logger.warning("Speaker reframe planning failed: %s", exc) return None def compute_vertical_crop_dims( width: int, height: int, target_ratio: float = 9 / 16 ) -> Tuple[int, int]: """Even-dimensioned 9:16 crop box that fits inside a source frame.""" if width <= 0 or height <= 0: return width, height if width / height > target_ratio: crop_w = round_to_even(int(height * target_ratio)) crop_h = round_to_even(height) else: crop_w = round_to_even(width) crop_h = round_to_even(int(width / target_ratio)) return ( max(2, min(crop_w, round_to_even(width))), max(2, min(crop_h, round_to_even(height))), ) def _open_face_detectors(): """Initialise the YuNet (preferred) + Haar (fallback) face detectors. Returns (face_detector_or_None, haar). The YuNet wrapper also exposes a MediaPipe-style ``process``/``close`` so older call sites keep working. """ return open_yunet_detector(), open_haar_cascade() def _detect_face_boxes(frame_bgr, face_detector, haar) -> List[Tuple[float, float, float, float]]: """All face boxes (x, y, w, h) in a frame, largest first. Frame-pixel coordinates.""" h, w = frame_bgr.shape[:2] frame_area = float(max(1, w * h)) boxes: List[Tuple[float, float, float, float, float]] = [] if face_detector is not None: try: for fx, fy, fw, fh, conf in face_detector.detect(frame_bgr): if fw > 10 and fh > 10: boxes.append((float(fw * fh * conf), float(fx), float(fy), float(fw), float(fh))) except Exception as exc: logger.debug("YuNet detection failed on frame: %s", exc) if not boxes: try: gray = cv2.cvtColor(frame_bgr, cv2.COLOR_BGR2GRAY) min_side = max(14, int(w * 0.04)) for (fx, fy, fw, fh) in haar.detectMultiScale( gray, scaleFactor=1.2, # coarser scale steps -> ~2x faster minNeighbors=3, minSize=(min_side, min_side), maxSize=(int(w * 0.7), int(h * 0.7)), ): boxes.append((float(fw * fh), float(fx), float(fy), float(fw), float(fh))) except Exception: pass boxes.sort(key=lambda item: item[0], reverse=True) kept: List[Tuple[float, float, float, float]] = [] for _, fx, fy, fw, fh in boxes: if (fw * fh) / frame_area < FACE_PRESENCE_MIN_AREA: continue cx, cy = fx + fw / 2, fy + fh / 2 if any(k[0] <= cx <= k[0] + k[2] and k[1] <= cy <= k[1] + k[3] for k in kept): continue kept.append((fx, fy, fw, fh)) if len(kept) >= 6: break return kept def _detect_dominant_face(frame_bgr, face_detector, haar) -> Optional[Tuple[float, float]]: """Return (center_x_fraction, area_fraction) of the dominant face, or None.""" h, w = frame_bgr.shape[:2] frame_area = float(max(1, w * h)) boxes = _detect_face_boxes(frame_bgr, face_detector, haar) if not boxes: return None fx, fy, fw, fh = max(boxes, key=lambda box: box[2] * box[3]) return (fx + fw / 2.0) / w, (fw * fh) / frame_area def _scene_cuts_from_diffs(diffs: List[Tuple[float, float]]) -> List[float]: """Derive scene-cut timestamps from per-frame difference spikes.""" if len(diffs) < 3: return [] vals = [d for _, d in diffs] mean = sum(vals) / len(vals) std = (sum((v - mean) ** 2 for v in vals) / len(vals)) ** 0.5 threshold = max(14.0, mean + 3.5 * std) cuts: List[float] = [] for i, (t, d) in enumerate(diffs): if d <= threshold: continue if (i == 0 or d >= diffs[i - 1][1]) and ( i == len(diffs) - 1 or d >= diffs[i + 1][1] ): cuts.append(t) return cuts def analyze_vertical_clip( input_path: Path, *, sample_fps: float = 3.0, proc_width: int = 480, analyze_context: bool = True, ) -> Tuple[ List[Tuple[float, Optional[float], float]], List[float], List[Tuple[float, List[Tuple[float, float, float, float]]]], List[SceneEvidence], ]: """Fast single-pass clip analysis: face track + scene cuts in one decode. Replaces slow per-sample random seeks (and a separate scene-detect pass) with a single sequential ffmpeg decode at low fps/resolution, piped straight into lightweight face detection. Scene cuts come from frame differences computed in the same pass. Returns (track, scene_cuts, face_samples, context) where track entries are (t, center_x_in_source_px or None, area_frac) and face_samples are (t, [(x, y, w, h), ...]) in source pixels. ``analyze_context=False`` skips optical flow, text components, and histograms and returns an empty context list. The reaction detail pass only needs the finer face boxes, so it uses that mode. """ if not np.isfinite(sample_fps) or sample_fps <= 0 or proc_width < 2: raise ValueError("Analysis requires positive sample_fps and proc_width >= 2") width, height = ffprobe_video_size(input_path) if width <= 0 or height <= 0: return [], [], [], [] proc_w = round_to_even(min(proc_width, width)) proc_h = round_to_even(max(2, int(round(proc_w * height / width)))) frame_bytes = proc_w * proc_h * 3 command = [ "ffmpeg", "-v", "error", "-an", "-sn", "-i", str(input_path), "-vf", f"fps={sample_fps:.3f},scale={proc_w}:{proc_h}", "-pix_fmt", "bgr24", "-f", "rawvideo", "-threads", "0", "-", ] try: proc = subprocess.Popen( command, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL ) except Exception as exc: logger.warning("analyze_vertical_clip: ffmpeg spawn failed (%s)", exc) return [], [], [], [] face_detector = None track: List[Tuple[float, Optional[float], float]] = [] face_samples: List[Tuple[float, List[Tuple[float, float, float, float]]]] = [] diffs: List[Tuple[float, float]] = [] context_analyzer = ContextAnalyzer() if analyze_context else None context: List[SceneEvidence] = [] prev_small = None idx = 0 scale_x = width / proc_w scale_y = height / proc_h try: face_detector, haar = _open_face_detectors() while True: raw = proc.stdout.read(frame_bytes) if not raw: break if len(raw) < frame_bytes: raise RuntimeError("Video analysis decoder returned an incomplete frame") frame = np.frombuffer(raw, dtype=np.uint8).reshape(proc_h, proc_w, 3) t = idx / sample_fps boxes = _detect_face_boxes(frame, face_detector, haar) if context_analyzer is not None: context.append(context_analyzer.measure(frame, boxes, t)) if not boxes: track.append((t, None, 0.0)) face_samples.append((t, [])) else: fx, fy, fw, fh = max(boxes, key=lambda box: box[2] * box[3]) area = (fw * fh) / float(proc_w * proc_h) track.append((t, (fx + fw / 2.0) * scale_x, area)) face_samples.append( (t, [(bx * scale_x, by * scale_y, bw * scale_x, bh * scale_y) for bx, by, bw, bh in boxes]) ) small = cv2.resize(frame, (32, 18)).astype(np.int16) if prev_small is not None: diffs.append((t, float(np.mean(np.abs(small - prev_small))))) prev_small = small idx += 1 finally: try: proc.stdout.close() except Exception: pass proc.wait() if face_detector is not None: face_detector.close() if proc.returncode != 0: raise RuntimeError("Video analysis decoder failed; partial analysis discarded") cuts = sorted(set(_scene_cuts_from_diffs(diffs)) | set(context_scene_cuts(context))) return track, cuts, face_samples, context def _median_filter(values: List[float], window: int = 3) -> List[float]: """Small median filter to remove single-frame detection spikes.""" if window <= 1 or len(values) < window: return list(values) half = window // 2 out: List[float] = [] for i in range(len(values)): lo = max(0, i - half) hi = min(len(values), i + half + 1) seg = sorted(values[lo:hi]) out.append(seg[len(seg) // 2]) return out def build_crop_trajectory( track: List[Tuple[float, Optional[float], float]], width: int, crop_w: int, *, deadzone_frac: float = 0.05, smooth_time: float = 0.9, max_pan_speed_frac: float = 0.4, ) -> List[Tuple[float, int]]: """Turn a raw face-centre track into a smooth, eased crop-x trajectory. Returns keyframes [(t, x)] for the crop's left edge. The motion is produced by a critically-damped spring (Unity-style SmoothDamp) easing toward a comfort-zone target, which gives natural ease-in/ease-out with no overshoot and no mechanical ramp-then-stop feel. A deadzone keeps the frame still for small head movements; a median pre-filter removes detection spikes. Returns [] when there isn't enough signal to track. """ if not track: return [] max_x = max(0, width - crop_w) if max_x <= 0: return [] centers: List[Optional[float]] = [c for _, c, _ in track] times = [t for t, _, _ in track] detected = sum(1 for c in centers if c is not None) if detected < max(3, len(centers) // 5): return [] # too sparse to trust — caller falls back to a static crop # Gap-fill missing detections: forward fill, then back fill. last: Optional[float] = None for i in range(len(centers)): if centers[i] is None: centers[i] = last else: last = centers[i] last = None for i in range(len(centers) - 1, -1, -1): if centers[i] is None: centers[i] = last else: last = centers[i] if any(c is None for c in centers): return [] desired = [min(max(c - crop_w / 2.0, 0.0), float(max_x)) for c in centers] desired = _median_filter(desired, window=3) deadzone = max(2.0, crop_w * deadzone_frac) max_speed = max(1.0, width * max_pan_speed_frac) smooth_time = max(0.05, smooth_time) omega = 2.0 / smooth_time # Comfort-zone target: a stable goal that only moves once the subject drifts # past the deadzone, so the spring isn't chasing sub-deadzone jitter. targets: List[float] = [] anchor = desired[0] for d in desired: if d - anchor > deadzone: anchor = d - deadzone elif anchor - d > deadzone: anchor = d + deadzone targets.append(anchor) # Critically-damped spring toward the comfort-zone target. eased: List[float] = [] cur = float(targets[0]) vel = 0.0 for i, tgt in enumerate(targets): dt = (times[i] - times[i - 1]) if i > 0 else 0.0 if dt <= 0: eased.append(cur) continue x = omega * dt exp_factor = 1.0 / (1.0 + x + 0.48 * x * x + 0.235 * x * x * x) change = cur - tgt max_change = max_speed * smooth_time change = max(-max_change, min(change, max_change)) adj_target = cur - change temp = (vel + omega * change) * dt vel = (vel - omega * temp) * exp_factor out = adj_target + (change + temp) * exp_factor # Prevent overshoot past the target. if (tgt - cur > 0) == (out > tgt): out = tgt vel = (out - tgt) / dt cur = min(max(out, 0.0), float(max_x)) eased.append(cur) # Final low-pass pass: removes residual velocity steps so the piecewise- # linear keyframes read as continuous, fluid motion. eased = smooth_values(eased, window=5) # Keep keyframes fine enough that linear interpolation tracks the smooth # curve without visible faceting. def simplify(tol: float) -> List[Tuple[float, int]]: keys: List[Tuple[float, int]] = [(0.0, int(round(eased[0])))] for i in range(1, len(eased)): if abs(eased[i] - keys[-1][1]) >= tol: keys.append((times[i], int(round(eased[i])))) if keys[-1][0] < times[-1]: keys.append((times[-1], int(round(eased[-1])))) return keys tol = max(1.5, crop_w * 0.006) keys = simplify(tol) while len(keys) > 90: tol *= 1.5 keys = simplify(tol) if keys and keys[0][0] > 0.0: keys[0] = (0.0, keys[0][1]) return keys def trajectory_has_movement(keys: List[Tuple[float, int]], crop_w: int) -> bool: """Whether a trajectory pans enough to be worth a moving crop.""" if len(keys) < 2: return False xs = [x for _, x in keys] return (max(xs) - min(xs)) >= max(8, crop_w * 0.04) def build_smooth_pan_expression(keys: List[Tuple[float, int]]) -> str: """Piecewise-linear ffmpeg crop-x expression interpolating the keyframes. Commas are escaped for use inside a quoted filtergraph expression. The result is rounded to an even integer for clean chroma subsampling. """ if not keys: return "0" if len(keys) == 1: return str(int(keys[0][1])) expr = str(int(keys[-1][1])) for i in range(len(keys) - 2, -1, -1): t0, x0 = keys[i] t1, x1 = keys[i + 1] span = max(1e-3, t1 - t0) lerp = f"({int(x0)}+({int(x1) - int(x0)})*(t-{t0:.3f})/{span:.3f})" expr = f"if(lt(t\\,{t1:.3f})\\,{lerp}\\,{expr})" return f"trunc(({expr})/2)*2" def build_layout_plan( track: List[Tuple[float, Optional[float], float]], scene_cuts: List[float], duration: float, ) -> List[Dict[str, Any]]: """Classify a clip into 'face' (tracked crop) and 'fit' (full-frame) shots. Talking-head shots become a tracked crop; content shots (tweets, graphs, code — no real face) become a full-frame blurred-background fit so nothing is cropped off. Boundaries are debounced and snapped to scene cuts. """ if duration <= 0 or not track: return [{"start": 0.0, "end": max(0.0, duration), "kind": "fit"}] times = [t for t, _, _ in track] present = [ 1 if (c is not None and a >= FACE_PRESENCE_MIN_AREA) else 0 for _, c, a in track ] # Classify by face-presence RATE over a window: a real talking shot has a # face in many frames (even if small/spotty); a content shot has ~none. diffs = [times[i] - times[i - 1] for i in range(1, len(times))] dt = sorted(diffs)[len(diffs) // 2] if diffs else 0.25 half = max(1, int(round(FACE_RATE_WINDOW / 2.0 / max(dt, 0.05)))) smoothed: List[int] = [] for i in range(len(present)): seg = present[max(0, i - half) : min(len(present), i + half + 1)] rate = sum(seg) / len(seg) smoothed.append(1 if rate >= FACE_PRESENCE_RATE else 0) # Build runs of constant layout value. runs: List[List[float]] = [] run_start, run_val = 0.0, smoothed[0] for i in range(1, len(times)): if smoothed[i] != run_val: runs.append([run_start, times[i], run_val]) run_start, run_val = times[i], smoothed[i] runs.append([run_start, duration, run_val]) def coalesce(rs: List[List[float]]) -> List[List[float]]: out = [rs[0][:]] for r in rs[1:]: if r[2] == out[-1][2]: out[-1][1] = r[1] else: out.append(r[:]) return out # Merge any run shorter than the minimum layout duration (flip + coalesce). runs = coalesce(runs) changed = True while changed and len(runs) > 1: changed = False for r in runs: if r[1] - r[0] < MIN_LAYOUT_SECONDS: r[2] = 1 - r[2] changed = True break if changed: runs = coalesce(runs) # Snap internal boundaries to nearby scene cuts for clean switches. cuts = sorted(c for c in (scene_cuts or []) if 0.05 < c < duration - 0.05) for i in range(len(runs) - 1): boundary = runs[i][1] near = [c for c in cuts if abs(c - boundary) <= LAYOUT_SNAP_WINDOW] if not near: continue snapped = min(near, key=lambda c: abs(c - boundary)) if runs[i][0] + 0.1 < snapped < runs[i + 1][1] - 0.1: runs[i][1] = snapped runs[i + 1][0] = snapped return [ {"start": r[0], "end": r[1], "kind": "face" if r[2] == 1 else "fit"} for r in runs ] def build_scene_crop_expression( track: List[Tuple[float, Optional[float], float]], scene_cuts: List[float], duration: float, width: int, crop_w: int, ) -> str: """Track each camera shot independently, with a hard reset at every cut.""" boundaries = [0.0, *sorted({c for c in scene_cuts if 0 < c < duration}), duration] shots = [] for start, end in zip(boundaries, boundaries[1:]): shot_track = [(t, x, area) for t, x, area in track if start <= t < end] keys = build_crop_trajectory(shot_track, width, crop_w) if keys: # Hold the first/last detected positions to the shot boundaries; # never extrapolate an initial movement backwards over a cut. keys = [(start, keys[0][1]), *[(t, x) for t, x in keys if start < t < end], (end, keys[-1][1])] expression = build_smooth_pan_expression(keys) else: centers = [x for _, x, _ in shot_track if x is not None] center = float(np.median(centers)) if centers else width / 2 expression = str(clamp_even(int(center - crop_w / 2), 0, width - crop_w)) shots.append((end, expression)) result = shots[-1][1] for end, expression in reversed(shots[:-1]): result = f"if(lt(t\\,{end:.3f})\\,{expression}\\,{result})" return result def kenburns_zoom_fragment(duration: float) -> Optional[str]: """Slow linear punch-in fragment producing a 1080x1920 [setsar-ed] stream. Zooms through a 1.5x supersampled frame so zoompan's integer crop offsets stay sub-pixel in the output (no visible stepping). The frame rate is normalised to OUTPUT_FPS *before* zoompan and re-declared on it, because zoompan re-times its output at its own fps — matching the two keeps the video duration identical and the audio in sync. """ if duration < KENBURNS_MIN_SECONDS: return None z_expr = ( f"if(isnan(it)\\,1\\,1+{KENBURNS_ZOOM_DELTA}*min(it/{duration:.3f}\\,1))" ) return ( f"scale={KENBURNS_SUPERSAMPLE_W}:{KENBURNS_SUPERSAMPLE_H}:flags=lanczos," f"fps={OUTPUT_FPS}," f"zoompan=z='{z_expr}':x='(iw-iw/zoom)/2':y='(ih-ih/zoom)*{KENBURNS_FOCUS_Y}'" f":d=1:s=1080x1920:fps={OUTPUT_FPS},{UPSCALE_SHARPEN_FILTER},setsar=1" ) FIT_CHAIN = ( "scale=1080:1920:force_original_aspect_ratio=decrease:flags=lanczos," "scale=trunc(iw/2)*2:trunc(ih/2)*2,setsar=1" ) FitWindow = Tuple[float, float, Optional[int], int] def plan_fit_windows( plan: List[Dict[str, Any]], samples: List[SceneEvidence], width: int, height: int, ) -> List[FitWindow]: """Readable crops for the fitted (full-frame) shots of a layout plan. Returns [(start, end, crop_w, x)], with crop_w None where the whole frame stays visible, or [] when nothing zooms. Each window contains all detail measured during it (for text cut by a face crop: the faces and the text lines), so text is never pushed off the edge. Zoom sizes come from FIT_VISIBLE_LEVELS. A zoom shorter than FIT_ZOOM_HOLD_SECONDS joins a neighbour that already shows its detail, otherwise it shows the full frame; a fitted shot with no fitted neighbour keeps its zoom. """ if width <= 0 or height <= 0: return [] min_visible = height * 1080 / FIT_MAX_FOREGROUND_H / width levels = [level for level in FIT_VISIBLE_LEVELS if level >= min_visible] def needed(left: float, right: float) -> float: return next((level for level in levels if right - left <= level), 1.0) runs: List[Dict[str, Any]] = [] def add(start: float, end: float, left: float, right: float) -> None: if end <= start: return if right <= left: left = right = (left + right) / 2 left = max(0.0, left - FIT_DETAIL_MARGIN_FRAC) right = min(1.0, right + FIT_DETAIL_MARGIN_FRAC) if runs and runs[-1]["end"] == start: run = runs[-1] union = (min(run["left"], left), max(run["right"], right)) if needed(left, right) == run["level"] and needed(*union) == run["level"]: run.update(end=end, left=union[0], right=union[1]) return runs.append({"start": start, "end": end, "left": left, "right": right, "level": needed(left, right), "settled": False}) for shot in plan: if shot["kind"] != "fit": continue cut_text = shot.get("reason") == "text_cut_by_crop" inside = [s for s in samples if shot["start"] <= s.time < shot["end"]] if not inside: add(shot["start"], shot["end"], 0.0, 1.0) continue for index, sample in enumerate(inside): start = shot["start"] if index == 0 else sample.time end = inside[index + 1].time if index + 1 < len(inside) else shot["end"] if cut_text: add(start, end, sample.protect_left, sample.protect_right) else: add(start, end, sample.detail_left, sample.detail_right) def touching(a: Dict[str, Any], b: Dict[str, Any]) -> bool: return abs(a["end"] - b["start"]) < 1e-6 or abs(b["end"] - a["start"]) < 1e-6 while True: short = [r for r in runs if not r["settled"] and r["end"] - r["start"] < FIT_ZOOM_HOLD_SECONDS] if not short: break run = min(short, key=lambda r: r["end"] - r["start"]) index = runs.index(run) neighbours = [ runs[j] for j in (index - 1, index + 1) if 0 <= j < len(runs) and touching(runs[j], run) ] neighbours.sort(key=lambda r: r["end"] - r["start"], reverse=True) host = next(( n for n in neighbours if max(n["right"], run["right"]) - min(n["left"], run["left"]) <= n["level"] ), None) if not neighbours: # A whole fitted shot between crops (or the whole clip) changes # layout at its edges anyway, so its zoom causes no extra jump. run["settled"] = True elif host is not None: host.update( start=min(host["start"], run["start"]), end=max(host["end"], run["end"]), left=min(host["left"], run["left"]), right=max(host["right"], run["right"]), ) runs.remove(run) elif run["level"] < 1.0: run["level"] = 1.0 else: run["settled"] = True # Each size is its own filter branch, so cap how many a clip may use. while len({r["level"] for r in runs}) > FIT_MAX_ZOOM_LEVELS: smallest, next_size = sorted({r["level"] for r in runs})[:2] for run in runs: if run["level"] == smallest: run["level"] = next_size if all(r["level"] >= 1.0 for r in runs): return [] merged: List[Dict[str, Any]] = [] for run in runs: last = merged[-1] if merged else None if ( last is not None and touching(last, run) and last["level"] == run["level"] and max(last["right"], run["right"]) - min(last["left"], run["left"]) <= run["level"] ): last.update(end=run["end"], left=min(last["left"], run["left"]), right=max(last["right"], run["right"])) else: merged.append(dict(run)) windows: List[FitWindow] = [] for run in merged: if run["level"] >= 1.0: windows.append((run["start"], run["end"], None, 0)) continue crop_w = round_to_even(int(width * run["level"])) centre = (run["left"] + run["right"]) / 2 * width x = clamp_even(int(centre - crop_w / 2), 0, width - crop_w) windows.append((run["start"], run["end"], crop_w, x)) return windows def build_fit_layers( fit_intervals: List[Tuple[float, float]], windows: Optional[List[FitWindow]] = None, ) -> List[Tuple[str, List[Tuple[float, float]]]]: """Fitted foreground layers as (filter chain, intervals), one per crop size.""" if not windows: return [(FIT_CHAIN, fit_intervals)] layers = [] for crop_w in sorted({w for _, _, w, _ in windows}, key=lambda w: w or 0): mine = [window for window in windows if window[2] == crop_w] intervals = [(start, end) for start, end, _, _ in mine] if crop_w is None: layers.append((FIT_CHAIN, intervals)) continue x_expr = str(mine[-1][3]) for _, end, _, x in reversed(mine[:-1]): x_expr = f"if(lt(t\\,{end:.3f})\\,{x}\\,{x_expr})" sharpen = f"{UPSCALE_SHARPEN_FILTER}," if crop_w < 1080 else "" layers.append(( f"crop={crop_w}:ih:x='{x_expr}':y=0,scale=1080:-2:flags=lanczos,{sharpen}setsar=1", intervals, )) return layers def _enable_expr(intervals: List[Tuple[float, float]]) -> str: if not intervals: return "0" return "+".join(f"between(t\\,{a:.3f}\\,{b:.3f})" for a, b in intervals) def _fit_overlays(base: str, layers: List[Tuple[str, List[Tuple[float, float]]]], gated: bool) -> str: """Chain [ft0].. into [fit0].. and overlay them on ``base`` into [vout].""" parts = [f"[ft{i}]{chain}[fit{i}]" for i, (chain, _) in enumerate(layers)] current = base for i, (_, intervals) in enumerate(layers): out = "[vout]" if i == len(layers) - 1 else f"[f{i}]" enable = f":enable='{_enable_expr(intervals)}'" if gated else "" parts.append(f"{current}[fit{i}]overlay=(W-w)/2:(H-h)/2{enable}{out}") current = out return ";".join(parts) def build_full_frame_filter( blur_sigma: int = 14, fit_windows: Optional[List[FitWindow]] = None ) -> str: """Preserve the complete source on a vertical canvas, without a crop branch. ``fit_windows`` (see ``plan_fit_windows``) enlarges content whose detail leaves empty margins; without them the whole frame is letterboxed. """ background = ( "[bgsrc]scale=540:960:force_original_aspect_ratio=increase,crop=540:960," f"gblur=sigma={blur_sigma}:steps=2,scale=1080:1920:flags=bilinear,setsar=1[bg];" ) if not fit_windows: return ( "[0:v]split=2[bgsrc][ftsrc];" f"{background}" f"[ftsrc]{FIT_CHAIN}[fit];" "[bg][fit]overlay=(W-w)/2:(H-h)/2[vout]" ) # Nothing but the fit is shown here, so the last window stays on to the # final frame even if the stream runs past the probed duration. last = max(range(len(fit_windows)), key=lambda i: fit_windows[i][1]) fit_windows = [ (start, max(end, 1e6) if i == last else end, crop_w, x) for i, (start, end, crop_w, x) in enumerate(fit_windows) ] layers = build_fit_layers([(0.0, fit_windows[last][1])], fit_windows) sources = "".join(f"[ft{i}]" for i in range(len(layers))) return ( f"[0:v]split={1 + len(layers)}[bgsrc]{sources};" f"{background}" + _fit_overlays("[bg]", layers, gated=len(layers) > 1) ) def build_vertical_compositor_filter( crop_chain: str, face_intervals: List[Tuple[float, float]], fit_intervals: List[Tuple[float, float]], blur_sigma: int = 14, fit_windows: Optional[List[FitWindow]] = None, ) -> str: """filter_complex switching between a tracked face crop and a blurred- background full-frame fit over time. Produces a labelled [vout] stream. Layers: a blurred fill background (always), the face crop on top during face shots (covers the frame), and the centred full-frame fit during content shots (background shows around it). ``fit_windows`` splits the fit into readable zoomed crops (see ``plan_fit_windows``). """ face_en = _enable_expr(face_intervals) # Smooth Gaussian background: blur at half resolution (plenty of detail for a # heavy blur) with multiple passes for a true Gaussian falloff, then upscale # 2x with bilinear so there's no lanczos ringing/blockiness — a creamy blur. head = ( "[bgsrc]scale=540:960:force_original_aspect_ratio=increase,crop=540:960," f"gblur=sigma={blur_sigma}:steps=2,scale=1080:1920:flags=bilinear,setsar=1[bg];" f"[crsrc]{crop_chain}[face];" ) if not fit_windows: fit_en = _enable_expr(fit_intervals) return ( "[0:v]split=3[bgsrc][crsrc][ftsrc];" f"{head}" f"[ftsrc]{FIT_CHAIN}[fit];" f"[bg][face]overlay=0:0:enable='{face_en}'[t1];" f"[t1][fit]overlay=(W-w)/2:(H-h)/2:enable='{fit_en}'[vout]" ) layers = build_fit_layers(fit_intervals, fit_windows) sources = "".join(f"[ft{i}]" for i in range(len(layers))) return ( f"[0:v]split={2 + len(layers)}[bgsrc][crsrc]{sources};" f"{head}" f"[bg][face]overlay=0:0:enable='{face_en}'[t1];" + _fit_overlays("[t1]", layers, gated=True) ) def _described( kind: str, video_filter: str, mode: str, caption_y: Optional[float] ) -> Dict[str, Any]: return { "kind": kind, "video_filter": video_filter, "mode": mode, "caption_y": caption_y, } def build_vertical_filter_plan( input_path: Path, width: int, height: int, speaker_turns: Optional[List[Dict[str, Any]]] = None, speaker_words: Optional[List[Dict[str, Any]]] = None, ) -> Tuple[str, str, Optional[float]]: """Build the 9:16 reframing filter for the default vertical mode. Returns (filter, mode, caption_y). mode 'vf' is a simple crop chain; mode 'complex' is a filter_complex producing [vout]. caption_y is a 0-1 output fraction that keeps captions off the detected face, or None to keep the template default. """ described = describe_vertical_layout( input_path, width, height, speaker_turns, speaker_words ) return described["video_filter"], described["mode"], described["caption_y"] def describe_vertical_layout( input_path: Path, width: int, height: int, speaker_turns: Optional[List[Dict[str, Any]]] = None, speaker_words: Optional[List[Dict[str, Any]]] = None, ) -> Dict[str, Any]: """Same plan as ``build_vertical_filter_plan``, plus a layout ``kind``. Kinds the editor keeps whole are ``reaction`` (reactor above the source), ``stack`` (side-by-side call tiles) and ``overlap`` (two speakers at once). ``crop``, ``speaker``, ``stage``, ``fit`` and ``compositor`` stay on the editor's vertical or original crop. All-face clips use a face-aware layout when the subject would otherwise sit low in a full-height crop (stacked call tiles, a wider stage for one webcam, or the whole gallery). Well-framed closeups keep the tracked crop. Clips containing content shots use the scene-aware compositor so tweets / graphs / slides are shown in full. With diarized speaker turns, multi-person wide shots that are not a video-call grid cut to whoever is talking. """ from .talking_head_layout import ( caption_y_below_subject, choose_talking_head_layout, dominant_face_bottom, ) crop_w, crop_h = compute_vertical_crop_dims(width, height) duration = ffprobe_duration(input_path) def bleed_caption(samples) -> Optional[float]: bottom = dominant_face_bottom(samples, height) if bottom is None: return None adjusted = caption_y_below_subject(bottom) return adjusted if adjusted > 0.805 else None # Narrow/portrait source: no horizontal room to crop — static fit, with a # slow punch-in so the frame still breathes. if crop_w >= width: sx, sy, sw, sh = detect_optimal_crop_region(input_path, 0, min(duration, 12.0)) tail = kenburns_zoom_fragment(duration) or VERTICAL_SCALE_CHAIN return _described("crop", f"crop={sw}:{sh}:{sx}:{sy},{tail}", "vf", None) # One fast decode pass yields the face track, face boxes, and scene cuts. try: analyzed = analyze_vertical_clip(input_path) except Exception as exc: logger.warning("Clip analysis failed (%s); preserving full frame", exc) analyzed = ([], [], []) track, scene_cuts = analyzed[0], analyzed[1] face_samples = analyzed[2] if len(analyzed) > 2 else [] context = analyzed[3] if len(analyzed) > 3 else [] plan = ( build_context_layout_plan(context, scene_cuts, duration, crop_w / width) if context else build_layout_plan(track, scene_cuts, duration) ) logger.info("Vertical scene layout: %s", plan) try: fit_windows = plan_fit_windows(plan, context, width, height) if context else [] except Exception as exc: logger.warning("Readable fit planning failed (%s); keeping the plain fit", exc) fit_windows = [] if fit_windows: logger.info("Readable fit windows (start, end, crop_w, x): %s", fit_windows) fit_intervals = [(s["start"], s["end"]) for s in plan if s["kind"] == "fit"] # Two people who cannot share a 9:16 crop are not slide or sports content. # Call/stage layouts and speaker framing still apply; if both decline, that # shot keeps the full frame instead of a dominant-face crop. content_fits = [ shot for shot in plan if shot["kind"] == "fit" and shot.get("reason") != "interaction_exceeds_crop" ] # A persistent reaction inset is independent of fit intervals, camera cuts, # and speaker labels. Separate it before dominant-face tracking can confuse # the inset with the source, or a full-frame fallback discards it. from .reaction_layout import choose_reaction_layout, find_reactor_face if find_reactor_face(width, height, face_samples): # Tiny faces in the source wide shot need more detail than the normal # 480px tracking pass. Keep its detections too: a profile/occluded face # can be visible to only one of the two scales. The pass only reads # face boxes, so skip optical flow, text, and histograms. try: detailed = analyze_vertical_clip( input_path, proc_width=960, analyze_context=False )[2] combined = [] for (t, coarse), (_, fine) in zip(face_samples, detailed): boxes = [] for box in sorted(list(coarse) + list(fine), key=lambda f: f[2]*f[3], reverse=True): cx, cy = box[0]+box[2]/2, box[1]+box[3]/2 if not any(x <= cx <= x+w and y <= cy <= y+h for x, y, w, h in boxes): boxes.append(box) combined.append((t, boxes)) if len(combined) == len(face_samples): face_samples = combined except Exception as exc: logger.debug("Reaction detail analysis unavailable: %s", exc) reaction = choose_reaction_layout( input_path, width, height, duration, face_samples, scene_cuts ) if reaction: logger.info("Reaction layout: inset %s, %d source sections", reaction['inset'], len(reaction['source_runs'])) return _described("reaction", reaction["video_filter"], "complex", reaction["caption_y"]) if all(s["kind"] == "fit" for s in plan) and content_fits: return _described("fit", build_full_frame_filter(fit_windows=fit_windows), "complex", 0.80) # choose_talking_head_layout already refuses cut-heavy clips (more than # four cuts). One jump cut must not drop stage, stack, or gallery layouts. talking = ( choose_talking_head_layout(width, height, face_samples, scene_cuts) if not content_fits else None ) if not content_fits and speaker_words and (not talking or talking["kind"] == "stack"): # Diarized speakers: cut to whoever is talking on multi-person wide # shots, including a pair that does not fit in one 9:16 crop. Slides # and other content shots keep the compositor below. from .speaker_framing import build_speaker_filter_plan try: speaker_plan = build_speaker_filter_plan( input_path, width, height, crop_w, crop_h, duration, speaker_turns or [], speaker_words, ) except Exception as exc: logger.warning("Speaker framing failed (%s); tracking dominant face", exc) speaker_plan = None if speaker_plan: speaker_filter, speaker_mode = speaker_plan if not talking or speaker_mode == "complex": # Overlap gets full-bleed panels even if the wide shot looks # like a call. Put captions between the two faces. caption_y = 0.5 if speaker_mode == "complex" else bleed_caption(face_samples) kind = "overlap" if speaker_mode == "complex" else "speaker" return _described(kind, speaker_filter, speaker_mode, caption_y) if talking: logger.info( "Face-aware vertical layout: %s (upscale %.2fx, caption_y %.2f)", talking["kind"], talking["upscale"], talking["caption_y"], ) return _described( talking["kind"], talking["video_filter"], "complex", talking["caption_y"] ) if all(s["kind"] == "fit" for s in plan): return _described("fit", build_full_frame_filter(fit_windows=fit_windows), "complex", 0.80) keys = build_crop_trajectory(track, width, crop_w) if track else [] # A cut by itself is not camera motion. Ken Burns stays available unless # the face trajectory actually pans. Real pans still reset at each cut. moving = bool(keys and trajectory_has_movement(keys, crop_w)) static_x = 0 if moving: x_expr = ( build_scene_crop_expression(track, scene_cuts, duration, width, crop_w) if scene_cuts else build_smooth_pan_expression(keys) ) crop_chain = f"crop={crop_w}:{crop_h}:x='{x_expr}':y=0,{VERTICAL_SCALE_CHAIN}" else: if keys: static_x = clamp_even( int(np.median([x for _, x in keys])), 0, max(0, width - crop_w) ) else: sx, _, _, _ = detect_optimal_crop_region(input_path, 0, min(duration, 12.0)) static_x = clamp_even(sx, 0, max(0, width - crop_w)) crop_chain = f"crop={crop_w}:{crop_h}:{static_x}:0,{VERTICAL_SCALE_CHAIN}" if not fit_intervals: # Static, all-face clip: add the slow Ken Burns punch-in. (The moving # tracked crop and the compositor path keep the plain chain — they # already have motion, and zoompan's re-timing would fight overlays.) if not moving: zoom = kenburns_zoom_fragment(duration) if zoom: return _described( "crop", f"crop={crop_w}:{crop_h}:{static_x}:0,{zoom}", "vf", bleed_caption(face_samples), ) return _described("crop", crop_chain, "vf", bleed_caption(face_samples)) face_intervals = [(s["start"], s["end"]) for s in plan if s["kind"] == "face"] logger.info( "Scene-aware vertical layout: %d face shot(s), %d content shot(s)", len(face_intervals), len(fit_intervals), ) return _described( "compositor", build_vertical_compositor_filter( crop_chain, face_intervals, fit_intervals, fit_windows=fit_windows ), "complex", bleed_caption(face_samples), ) def render_reframed_clip_ffmpeg( input_path: Path, output_path: Path, output_format: str, subtitle_ass_path: Optional[Path] = None, fonts_dir: Optional[Path] = None, speaker_turns: Optional[List[Dict[str, Any]]] = None, speaker_words: Optional[List[Dict[str, Any]]] = None, vertical_plan: Optional[Tuple[str, str]] = None, speaker_plan: Optional[Dict[str, Any]] = None, broll_overlays: Optional[List[Dict[str, Any]]] = None, ) -> Tuple[bool, int, int]: """Render the final framed clip and (optionally) burn subtitles in one pass. Collapsing reframing + subtitle burn into a single encode avoids a whole generation of re-encode loss. The pass uses the high-quality profile, CFR output and loudness-normalised audio. ``broll_overlays`` (path, start and duration on the clip timeline) are composited over the framed picture and under the captions. """ width, height = ffprobe_video_size(input_path) has_audio = ffprobe_has_audio(input_path) subs = ( subtitles_filter_fragment(subtitle_ass_path, fonts_dir) if subtitle_ass_path else None ) audio_args = build_audio_output_args(has_audio) overlays = ( normalize_broll_overlays(broll_overlays, ffprobe_duration(input_path)) if broll_overlays else [] ) def composited(head: str, head_label: str, out_w: int, out_h: int, tail: str = "", **encode) -> bool: graph, label = broll_overlay_graph(head_label, overlays, out_w, out_h) post = ",".join(part for part in (subs, tail) if part) if post: graph = f"{graph};{label}{post}[v]" label = "[v]" command = [ "ffmpeg", "-y", "-i", str(input_path), *broll_input_args(overlays), "-filter_complex", f"{head};{graph}", "-map", label, "-map", "0:a?", *build_final_video_encode_args(**encode), *audio_args, "-movflags", "+faststart", str(output_path), ] return run_ffmpeg_command(command).returncode == 0 if output_format == "original": geometry = probe_video_geometry(input_path) display_width = geometry.display_width if geometry else width display_height = geometry.display_height if geometry else height source_fps = geometry.fps if geometry else None capped_width, capped_height = fit_within_1080p(display_width, display_height) needs_scale = (capped_width, capped_height) != (display_width, display_height) needs_fps = source_fps is not None and source_fps > MAX_OUTPUT_FPS + FPS_EPSILON out_w, out_h = round_to_even(capped_width), round_to_even(capped_height) if overlays: # Always scale to the display size: on a non-square-pixel source # the coded frame is not the size the overlay is built for. ok = composited( f"[0:v]scale={out_w}:{out_h}:flags=lanczos,setsar=1[base]", "[base]", out_w, out_h, tail="setsar=1", ) return ok, out_w, out_h # A source already within 1080p/60 can be copied. Anything above that is # re-encoded so original-format output cannot exceed the cap. if not subs and not needs_scale and not needs_fps: shutil.copyfile(input_path, output_path) return True, round_to_even(display_width), round_to_even(display_height) filters: List[str] = [] if needs_scale: filters.append(f"scale={out_w}:{out_h}:flags=lanczos,setsar=1") if needs_fps and not subs: filters.append(f"fps={MAX_OUTPUT_FPS}") if subs: filters.append(subs) if not needs_scale: filters.append("setsar=1") if subs: encode_fps: int | str = OUTPUT_FPS encode_level = "4.1" elif needs_fps or source_fps is None: encode_fps = MAX_OUTPUT_FPS if needs_fps else OUTPUT_FPS encode_level = "4.2" if needs_fps else "4.1" else: # 59.94 stays 60000/1001. Rounding it to 60 would drop or duplicate # frames on an NTSC master that is already inside the cap. encode_fps = output_rate_token(source_fps) encode_level = "4.2" if source_fps > 30 + FPS_EPSILON else "4.1" command = [ "ffmpeg", "-y", "-i", str(input_path), "-vf", ",".join(filters), *build_final_video_encode_args(fps=encode_fps, level=encode_level), *audio_args, "-movflags", "+faststart", str(output_path), ] return run_ffmpeg_command(command).returncode == 0, out_w, out_h # A caller that already built the split or pan plan (the editor) skips a # second face pass and renders that exact layout. if speaker_plan is not None: plan = speaker_plan else: plan = ( detect_speaker_reframe_plan(input_path, output_format) if output_format in {"vertical_pan", "vertical_split"} else None ) if plan and plan["mode"] == "split": left = plan["regions"]["left"] right = plan["regions"]["right"] vstack_tail = f",{subs}" if subs else "" stacked = ( f"[0:v]split=2[l][r];" f"[l]crop={left['tile_w']}:{left['tile_h']}:{left['tile_x']}:{left['tile_y']}," f"scale=1080:960:flags=lanczos,{UPSCALE_SHARPEN_FILTER},setsar=1[lv];" f"[r]crop={right['tile_w']}:{right['tile_h']}:{right['tile_x']}:{right['tile_y']}," f"scale=1080:960:flags=lanczos,{UPSCALE_SHARPEN_FILTER},setsar=1[rv];" f"[lv][rv]vstack,setsar=1" ) if overlays: return composited(f"{stacked}[base]", "[base]", 1080, 1920), 1080, 1920 video_filter = f"{stacked}{vstack_tail}[v]" command = [ "ffmpeg", "-y", "-i", str(input_path), "-filter_complex", video_filter, "-map", "[v]", "-map", "0:a?", *build_final_video_encode_args(), *audio_args, "-movflags", "+faststart", str(output_path), ] return run_ffmpeg_command(command).returncode == 0, 1080, 1920 if plan and plan["mode"] == "pan": video_filter = ( f"crop={plan['crop_w']}:{plan['crop_h']}:x='{plan['x_expression']}':y=0," f"{VERTICAL_SCALE_CHAIN}" ) if overlays: return composited(f"[0:v]{video_filter}[base]", "[base]", 1080, 1920), 1080, 1920 if subs: video_filter = f"{video_filter},{subs}" command = [ "ffmpeg", "-y", "-i", str(input_path), "-vf", video_filter, *build_final_video_encode_args(), *audio_args, "-movflags", "+faststart", str(output_path), ] return run_ffmpeg_command(command).returncode == 0, 1080, 1920 # Default "vertical": face-aware for low webcams and calls, tracked crop # for a well-framed closeup, blurred full-frame fit for content shots. if output_format == "vertical_fit": video_filter, mode = build_full_frame_filter(), "complex" elif vertical_plan is not None: video_filter, mode = vertical_plan else: video_filter, mode, _caption_y = build_vertical_filter_plan( input_path, width, height, speaker_turns, speaker_words ) if overlays: if mode == "complex": return composited(video_filter, "[vout]", 1080, 1920), 1080, 1920 return composited(f"[0:v]{video_filter}[base]", "[base]", 1080, 1920), 1080, 1920 if mode == "complex": if subs: graph = f"{video_filter};[vout]{subs}[v]" map_label = "[v]" else: graph = video_filter map_label = "[vout]" command = [ "ffmpeg", "-y", "-i", str(input_path), "-filter_complex", graph, "-map", map_label, "-map", "0:a?", *build_final_video_encode_args(), *audio_args, "-movflags", "+faststart", str(output_path), ] return run_ffmpeg_command(command).returncode == 0, 1080, 1920 if subs: video_filter = f"{video_filter},{subs}" command = [ "ffmpeg", "-y", "-i", str(input_path), "-vf", video_filter, *build_final_video_encode_args(), *audio_args, "-movflags", "+faststart", str(output_path), ] return run_ffmpeg_command(command).returncode == 0, 1080, 1920 def caption_probe_plan(input_path: Path, output_format: str, vertical_plan=None) -> Tuple[str, str]: """The same composition as the final render, without subtitles or stock footage.""" if output_format == "vertical_fit": return build_full_frame_filter(), "complex" if output_format in {"vertical_split", "vertical_pan"}: plan = detect_speaker_reframe_plan(input_path, output_format) if plan and plan["mode"] == "split": left, right = plan["regions"]["left"], plan["regions"]["right"] return (f"[0:v]split=2[a][b];[a]crop={left['tile_w']}:{left['tile_h']}:{left['tile_x']}:{left['tile_y']},scale=1080:960:flags=lanczos,{UPSCALE_SHARPEN_FILTER},setsar=1[top];[b]crop={right['tile_w']}:{right['tile_h']}:{right['tile_x']}:{right['tile_y']},scale=1080:960:flags=lanczos,{UPSCALE_SHARPEN_FILTER},setsar=1[bottom];[top][bottom]vstack,setsar=1[vout]", "complex") if plan and plan["mode"] == "pan": return f"crop={plan['crop_w']}:{plan['crop_h']}:x='{plan['x_expression']}':y=0,{VERTICAL_SCALE_CHAIN}", "vf" if vertical_plan is not None: return vertical_plan width, height = ffprobe_video_size(input_path) video_filter, mode, _ = build_vertical_filter_plan(input_path, width, height) return video_filter, mode