diff --git a/app.py b/app.py index 78902ab..8b9d5b2 100644 --- a/app.py +++ b/app.py @@ -20,7 +20,7 @@ from pathlib import Path from src.job import JobQueue from src.model_registry import scan_models, scan_model_groups, ModelConfig -from src.preview import extract_thumbnail, extract_sample_frames, probe_video +from src.preview import extract_thumbnail, extract_sample_frames, probe_video, resize_video_to_max_height from src.zone_config import load_zone_config, list_zone_presets, build_static_roi, get_active_zone load_dotenv() @@ -118,6 +118,11 @@ def upload(): return "Invalid video file type", 400 model_configs, class_filters = _parse_model_configs(request.form) + + # For upload reuse, only transcode if video is taller than 720p + meta = probe_video(video_path) + if meta["height"] > 720: + video_path = resize_video_to_max_height(video_path, max_height=720) if not model_configs: return "No models selected", 400 @@ -129,6 +134,9 @@ def upload(): n += 1 video.save(video_path) + # Transcode to 720p max height to save storage and speed up processing + video_path = resize_video_to_max_height(video_path, max_height=720) + output_height = request.form.get("output_height", "") zone_mode = request.form.get("zone_mode", "dynamic") fixed_zone = None @@ -165,6 +173,11 @@ def upload_reuse(): return "Video not found", 400 model_configs, class_filters = _parse_model_configs(request.form) + + # For upload reuse, only transcode if video is taller than 720p + meta = probe_video(video_path) + if meta["height"] > 720: + video_path = resize_video_to_max_height(video_path, max_height=720) if not model_configs: return "No models selected", 400 diff --git a/src/preview.py b/src/preview.py index 9f4508d..1dbafe7 100644 --- a/src/preview.py +++ b/src/preview.py @@ -1,9 +1,10 @@ # src/preview.py -"""Video preview utilities — probe, thumbnails, sample frames.""" +"""Video preview utilities — probe, thumbnails, sample frames, transcoding.""" from __future__ import annotations import os +import subprocess import cv2 @@ -30,6 +31,77 @@ def probe_video(video_path: str) -> dict: cap.release() +def resize_video_to_max_height( + input_path: str, + max_height: int = 720, + output_path: str | None = None, + preset: str = "veryfast", + crf: int = 23, +) -> str: + """ + Transcode video to max height, preserving aspect ratio. + + Args: + input_path: Path to input video + max_height: Maximum height in pixels (width scales proportionally) + output_path: Optional output path; if None, overwrites input atomically + preset: ffmpeg preset (veryfast, fast, medium, slow) + crf: Constant Rate Factor (lower = better quality, 18-28 typical) + + Returns: + Path to the resized video (same as output_path or input_path) + """ + meta = probe_video(input_path) + src_h = meta["height"] + src_w = meta["width"] + + if src_h <= max_height: + # Already at or below target height, no transcode needed + return input_path + + # Calculate new dimensions (even numbers for encoder compatibility) + scale = max_height / src_h + new_h = max_height + new_w = int(round(src_w * scale / 2) * 2) # round to even + + if output_path is None: + # Atomic overwrite: write to temp, then rename + output_path = input_path + ".resized.mp4" + atomic = True + else: + atomic = False + + # Try hardware encoder first (Jetson), fallback to libx264 + encoders = [ + ["-c:v", "h264_nvenc", "-preset", preset], + ["-c:v", "h264_v4l2m2m", "-preset", preset], + ["-c:v", "libx264", "-preset", preset, "-crf", str(crf)], + ] + + last_err = None + for enc_args in encoders: + cmd = [ + "ffmpeg", "-y", "-i", input_path, + "-vf", f"scale={new_w}:{new_h}", + *enc_args, + "-c:a", "copy", # copy audio stream + output_path, + ] + try: + result = subprocess.run(cmd, capture_output=True, timeout=300) + if result.returncode == 0 and os.path.exists(output_path): + if atomic: + os.replace(output_path, input_path) + return input_path + return output_path + last_err = result.stderr.decode() if result.stderr else "Unknown error" + except (subprocess.TimeoutExpired, FileNotFoundError) as e: + last_err = str(e) + continue + + raise RuntimeError(f"Failed to transcode video: {last_err}") + + def extract_thumbnail( video_path: str, output_path: str, time_sec: float = 1.0 ) -> str: diff --git a/templates/index.html b/templates/index.html index 7243171..3e50999 100644 --- a/templates/index.html +++ b/templates/index.html @@ -493,7 +493,7 @@ {# --- Output Options --- #}