video-compressor / app /engine.py
Transfer Bot
Moved to Hugging Face automatically
60fd361
Raw History Blame Contribute Delete
61.5 kB
"""Compression engine. Pipeline for every video: 1. probe – streams, colour, HDR, rotation, audio, subtitles 2. plan – codec settings, filters, audio handling, sample windows 3. search – encode short samples at a few CRF values and score each with VMAF (Netflix's perceptual quality metric) until the highest CRF (= smallest file) that still meets the quality target is found. This is per-video ("per-title") optimisation. 4. encode – encode the whole video once with that CRF 5. verify – score the finished file against the original with VMAF 6. previews – matching frames for the before/after slider The result is never bigger than the original: when it would be, the job ends as "already optimal" instead of returning a worse file. """ from __future__ import annotations import asyncio import json import math import os import re import signal import time from collections import deque from dataclasses import dataclass, field from pathlib import Path from typing import Callable, Optional from . import settings FFMPEG = settings.FFMPEG FFPROBE = settings.FFPROBE THREADS = settings.JOB_THREADS MAX_JOB_SECONDS = max(300, int(os.environ.get("MAX_JOB_MINUTES", "45") or 45) * 60) _ENV = dict(os.environ, SVT_LOG="1", AV_LOG_FORCE_NOCOLOR="1") # =========================================================================== # # errors # =========================================================================== # class EngineError(Exception): """Failure with a code that the API turns into a Persian message.""" def __init__(self, code: str, detail: str = ""): super().__init__(f"{code}: {detail}") self.code = code self.detail = detail class Cancelled(Exception): pass # =========================================================================== # # subprocess helpers # =========================================================================== # def _nice(cmd: list[str]) -> list[str]: # encoders run at lower priority so the web server always stays responsive for path in ("/usr/bin/nice", "/bin/nice"): if os.path.exists(path): return [path, "-n", "10", *cmd] return cmd async def run_capture(cmd: list[str], timeout: float = 120) -> tuple[int, str, str]: proc = await asyncio.create_subprocess_exec( *cmd, stdin=asyncio.subprocess.DEVNULL, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE, env=_ENV, ) try: out, err = await asyncio.wait_for(proc.communicate(), timeout) except asyncio.TimeoutError: proc.kill() await proc.wait() raise EngineError("timeout", " ".join(cmd[:2])) return proc.returncode, out.decode("utf-8", "replace"), err.decode("utf-8", "replace") async def _terminate(proc: asyncio.subprocess.Process) -> None: if proc.returncode is not None: return try: os.killpg(proc.pid, signal.SIGTERM) except Exception: try: proc.terminate() except Exception: return try: await asyncio.wait_for(proc.wait(), 4) except asyncio.TimeoutError: try: os.killpg(proc.pid, signal.SIGKILL) except Exception: try: proc.kill() except Exception: pass await proc.wait() async def run_ffmpeg( args: list[str], *, cancel: Optional[asyncio.Event] = None, total_us: Optional[float] = None, on_progress: Optional[Callable[[float, dict], None]] = None, ) -> list[str]: """Run ffmpeg; progress arrives through -progress on stdout. Returns the last stderr lines. Raises Cancelled or EngineError.""" cmd = [FFMPEG, "-hide_banner", "-nostdin", "-loglevel", "error", "-y"] if on_progress is not None: cmd += ["-progress", "pipe:1", "-stats_period", "0.5"] cmd = _nice(cmd + args) proc = await asyncio.create_subprocess_exec( *cmd, stdin=asyncio.subprocess.DEVNULL, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE, env=_ENV, start_new_session=True, limit=1 << 20, ) tail: deque[str] = deque(maxlen=40) async def read_err(): while True: line = await proc.stderr.readline() if not line: return text = line.decode("utf-8", "replace").rstrip() if text: tail.append(text) async def read_out(): state: dict[str, str] = {} while True: line = await proc.stdout.readline() if not line: return text = line.decode("utf-8", "replace").strip() key, sep, value = text.partition("=") if not sep: continue state[key] = value if key == "progress" and on_progress is not None: frac = 0.0 try: us = float(state.get("out_time_us") or 0) if total_us and total_us > 0 and us > 0: frac = min(1.0, us / total_us) except ValueError: pass try: on_progress(frac, state) except Exception: pass readers = [asyncio.create_task(read_err()), asyncio.create_task(read_out())] waiter = asyncio.create_task(proc.wait()) cancel_task = asyncio.create_task(cancel.wait()) if cancel is not None else None try: await asyncio.wait([t for t in (waiter, cancel_task) if t], return_when=asyncio.FIRST_COMPLETED) if not waiter.done(): await _terminate(proc) raise Cancelled() except asyncio.CancelledError: await _terminate(proc) raise finally: if cancel_task: cancel_task.cancel() for r in readers: try: await asyncio.wait_for(r, 5) except Exception: r.cancel() if proc.returncode != 0: if cancel is not None and cancel.is_set(): raise Cancelled() raise EngineError("ffmpeg_failed", "\n".join(tail)[-2000:]) return list(tail) # =========================================================================== # # capabilities of the installed FFmpeg # =========================================================================== # CAPS: dict = {"av1": False, "hevc": False, "h264": False, "vmaf": False, "zscale": False, "dovi_av1": False, "dovi_hevc": False, "av1_tuned": True, "version": ""} AV1_TUNING = ["tune=1", "enable-variance-boost=1", "scd=1", "keyint=10s"] async def detect_capabilities() -> dict: """What the installed FFmpeg can do – checked with real (tiny) runs, so a newer or older build never breaks the app; it only switches features off.""" try: _, enc, _ = await run_capture([FFMPEG, "-hide_banner", "-encoders"], 30) _, flt, _ = await run_capture([FFMPEG, "-hide_banner", "-filters"], 30) _, ver, _ = await run_capture([FFMPEG, "-hide_banner", "-version"], 30) except Exception: return CAPS CAPS.update( av1=bool(re.search(r"\blibsvtav1\b", enc)), hevc=bool(re.search(r"\blibx265\b", enc)), h264=bool(re.search(r"\blibx264\b", enc)), vmaf=bool(re.search(r"\blibvmaf\b", flt)), zscale=bool(re.search(r"\bzscale\b", flt)), version=(ver.splitlines() or [""])[0], ) test_src = ["-f", "lavfi", "-i", "testsrc2=size=128x72:rate=10"] if CAPS["av1"]: _, h, _ = await run_capture([FFMPEG, "-hide_banner", "-h", "encoder=libsvtav1"], 30) CAPS["dovi_av1"] = "dolbyvision" in h rc, _, err = await run_capture([FFMPEG, "-hide_banner", "-loglevel", "warning", *test_src, "-frames:v", "3", "-c:v", "libsvtav1", "-preset", "10", "-svtav1-params", ":".join(["crf=35", *AV1_TUNING, "lp=1"]), "-f", "null", "-"], 60) CAPS["av1_tuned"] = rc == 0 and "Error parsing option" not in err if not CAPS["av1_tuned"]: rc, _, _ = await run_capture([FFMPEG, "-hide_banner", "-loglevel", "error", *test_src, "-frames:v", "3", "-c:v", "libsvtav1", "-preset", "10", "-crf", "35", "-f", "null", "-"], 60) CAPS["av1"] = rc == 0 if CAPS["hevc"]: _, h, _ = await run_capture([FFMPEG, "-hide_banner", "-h", "encoder=libx265"], 30) CAPS["dovi_hevc"] = "dolbyvision" in h if CAPS["vmaf"]: rc, _, _ = await run_capture([FFMPEG, "-hide_banner", "-loglevel", "error", *test_src, *test_src, "-frames:v", "2", "-lavfi", "[0:v][1:v]libvmaf=model=version=vmaf_v0.6.1", "-f", "null", "-"], 60) CAPS["vmaf"] = rc == 0 return CAPS # =========================================================================== # # probing # =========================================================================== # TEXT_SUBS = {"subrip", "srt", "ass", "ssa", "webvtt", "mov_text", "text", "microdvd", "subviewer"} @dataclass class AudioInfo: index: int codec: str channels: int sample_rate: int bitrate: int # bits/s, 0 = unknown @dataclass class MediaInfo: path: str size: int duration: float container: str bitrate: int v_index: int v_codec: str width: int # display size (after rotation) height: int rotation: int fps: float frames: int pix_fmt: str bit_depth: int color_range: str # "tv" | "pc" | "" color_space: str color_transfer: str color_primaries: str hdr: str # "" | "pq" | "hlg" dovi_profile: int interlaced: bool v_offset: float = 0.0 # video start relative to the file start (A/V sync when remuxing) audio: list[AudioInfo] = field(default_factory=list) subs_text: list[int] = field(default_factory=list) subs_dropped: int = 0 def public(self) -> dict: return { "size": self.size, "duration": round(self.duration, 3), "width": self.width, "height": self.height, "fps": round(self.fps, 3), "codec": self.v_codec, "bitrate": self.bitrate, "hdr": self.hdr, "bit_depth": self.bit_depth, "audio_tracks": len(self.audio), } def _ratio(text) -> float: try: text = str(text) if "/" in text: a, b = text.split("/", 1) return float(a) / float(b) if float(b) else 0.0 return float(text) except (TypeError, ValueError, ZeroDivisionError): return 0.0 def _int0(value) -> int: try: return int(float(value)) except (TypeError, ValueError): return 0 def _bit_depth(pix_fmt: str, raw) -> int: m = re.search(r"p(9|10|12|14|16)", pix_fmt or "") if m: return int(m.group(1)) return _int0(raw) if _int0(raw) > 8 else 8 async def probe(path: str) -> MediaInfo: rc, out, err = await run_capture( [FFPROBE, "-v", "error", "-print_format", "json", "-show_format", "-show_streams", path], 180) if rc != 0 or not out.strip(): raise EngineError("not_video", err[-500:]) try: data = json.loads(out) except json.JSONDecodeError: raise EngineError("not_video", "bad json") fmt = data.get("format") or {} streams = data.get("streams") or [] videos = [s for s in streams if s.get("codec_type") == "video" and not (s.get("disposition") or {}).get("attached_pic")] # a single still picture is not a video videos = [s for s in videos if not (_int0(s.get("nb_frames")) == 1 and s.get("codec_name") in ("mjpeg", "png", "bmp", "webp"))] if not videos: raise EngineError("no_video") v = max(videos, key=lambda s: _int0(s.get("width")) * _int0(s.get("height"))) cw, ch = _int0(v.get("width")), _int0(v.get("height")) if cw < 16 or ch < 16: raise EngineError("too_small") rotation = 0 dovi = 0 for sd in v.get("side_data_list") or []: if "rotation" in sd: rotation = _int0(sd.get("rotation")) if "dv_profile" in sd: dovi = _int0(sd.get("dv_profile")) if not rotation: rotation = _int0((v.get("tags") or {}).get("rotate")) rotation = rotation % 360 width, height = (ch, cw) if rotation in (90, 270) else (cw, ch) fps = _ratio(v.get("avg_frame_rate", "0")) rfps = _ratio(v.get("r_frame_rate", "0")) if not (1 <= fps <= 300): fps = rfps if 1 <= rfps <= 300 else 30.0 duration = _ratio(fmt.get("duration", "0")) or _ratio(v.get("duration", "0")) if duration <= 0: duration = await _measure_duration(path) if duration <= 0.2: raise EngineError("too_short") frames = _int0(v.get("nb_frames")) if frames <= 1 or abs(frames - duration * fps) > duration * fps * 0.5: frames = int(round(duration * fps)) pix_fmt = v.get("pix_fmt") or "yuv420p" crange = v.get("color_range") or "" if pix_fmt.startswith("yuvj"): crange = "pc" transfer = v.get("color_transfer") or "" hdr = "pq" if transfer == "smpte2084" else "hlg" if transfer == "arib-std-b67" else "" interlaced = (v.get("field_order") or "").lower() in ("tt", "bb", "tb", "bt") audio: list[AudioInfo] = [] subs_text: list[int] = [] subs_dropped = 0 for s in streams: kind = s.get("codec_type") if kind == "audio" and _int0(s.get("channels")) > 0: br = _int0(s.get("bit_rate")) if not br: for k, val in (s.get("tags") or {}).items(): if k.upper().startswith("BPS"): br = _int0(val) break audio.append(AudioInfo(int(s["index"]), s.get("codec_name") or "", _int0(s.get("channels")) or 2, _int0(s.get("sample_rate")) or 48000, br)) elif kind == "subtitle": if (s.get("codec_name") or "") in TEXT_SUBS: subs_text.append(int(s["index"])) else: subs_dropped += 1 size = _int0(fmt.get("size")) or os.path.getsize(path) bitrate = _int0(fmt.get("bit_rate")) or int(size * 8 / max(duration, 0.001)) v_offset = max(0.0, _ratio(v.get("start_time", "0")) - _ratio(fmt.get("start_time", "0"))) if v_offset > 5: v_offset = 0.0 return MediaInfo( path=path, size=size, duration=duration, container=fmt.get("format_name") or "", bitrate=bitrate, v_index=int(v["index"]), v_codec=v.get("codec_name") or "", width=width, height=height, rotation=rotation, fps=fps, frames=max(1, frames), pix_fmt=pix_fmt, bit_depth=_bit_depth(pix_fmt, v.get("bits_per_raw_sample")), color_range=crange, color_space=v.get("color_space") or "", color_transfer=transfer, color_primaries=v.get("color_primaries") or "", hdr=hdr, dovi_profile=dovi, interlaced=interlaced, v_offset=v_offset, audio=audio, subs_text=subs_text, subs_dropped=subs_dropped, ) async def _measure_duration(path: str) -> float: """Demux-only pass for files whose header carries no duration (some WebM/MKV).""" rc, out, err = await run_capture( [FFMPEG, "-hide_banner", "-nostdin", "-i", path, "-map", "0:v:0", "-c", "copy", "-f", "null", "-"], 600) times = re.findall(r"time=(\d+):(\d+):(\d+(?:\.\d+)?)", err) if not times: return 0.0 h, m, s = times[-1] return int(h) * 3600 + int(m) * 60 + float(s) # =========================================================================== # # planning # =========================================================================== # CODECS = ("av1", "hevc", "h264") QUALITY_TARGETS = {"high": 97.0, "standard": 95.0, "compact": 93.0} SPEEDS = ("fast", "balanced", "best") RESOLUTIONS = {"original": 0, "2160": 2160, "1440": 1440, "1080": 1080, "720": 720, "540": 540, "480": 480, "360": 360} # "smaller" mode: the user accepts some loss for a much smaller file # level -> (short side cap, VMAF target, fps cap) LEVELS = { "light": (0, 91.0, 0), # same size picture, a little less detail "medium": (720, 91.0, 0), # 720p "strong": (480, 88.0, 30), # 480p, at most 30 fps } MIN_BPP = {"av1": 0.018, "hevc": 0.026, "h264": 0.045} # bits per pixel per frame, size mode # encoder presets per speed mode, slowest first – the planner steps to a faster # one when the video is long and the CPU small PRESETS = { "av1": {"best": [4, 5, 6], "balanced": [6, 7], "fast": [8]}, "hevc": {"best": ["slow", "medium"], "balanced": ["medium", "fast"], "fast": ["fast"]}, "h264": {"best": ["slower", "slow"], "balanced": ["slow", "medium"], "fast": ["medium"]}, } # frames/s measured at 1920x1080 on 2 vCPU SPEED_TABLE = { "av1": {4: 7.1, 5: 8.9, 6: 12.8, 7: 15.8, 8: 17.8}, "hevc": {"slow": 5.2, "medium": 12.6, "fast": 17.0}, "h264": {"slower": 5.5, "slow": 10.3, "medium": 13.0}, } CRF_RANGE = {"av1": (8.0, 58.0, 1.0), "hevc": (10.0, 38.0, 0.5), "h264": (10.0, 36.0, 0.5)} CRF_START = {"av1": 36.0, "hevc": 23.0, "h264": 21.0} SLOPE = {"av1": 0.35, "hevc": 0.7, "h264": 0.8} # VMAF points lost per CRF step (typical) SAFETY = 0.15 # VMAF margin between samples and full video PLATEAU = {"av1": 0.09, "hevc": 0.12, "h264": 0.12} # VMAF/CRF below which quality has saturated FALLBACK_CRF = { # only when FFmpeg lacks libvmaf "av1": {97.0: 26.0, 95.0: 31.0, 93.0: 35.0}, "hevc": {97.0: 19.0, 95.0: 22.0, 93.0: 25.0}, "h264": {97.0: 17.0, 95.0: 20.0, 93.0: 23.0}, } @dataclass class Options: mode: str = "keep" # keep = no visible loss | smaller = user accepts loss level: str = "medium" # smaller mode: light | medium | strong | size target_mb: float = 0.0 # level "size": wanted file size codec: str = "av1" quality: str = "standard" speed: str = "" # "" = automatic for this machine resolution: str = "original" # smaller mode only fps: str = "original" # smaller mode only: original | 30 | 24 audio: str = "auto" # auto | remove @classmethod def from_dict(cls, d: dict) -> "Options": o = cls() if d.get("mode") in ("keep", "smaller"): o.mode = d["mode"] if d.get("level") in (*LEVELS, "size"): o.level = d["level"] try: o.target_mb = max(0.0, float(d.get("target_mb") or 0)) except (TypeError, ValueError): o.target_mb = 0.0 if d.get("codec") in CODECS: o.codec = d["codec"] if d.get("quality") in QUALITY_TARGETS: o.quality = d["quality"] if d.get("speed") in SPEEDS: o.speed = d["speed"] if str(d.get("resolution")) in RESOLUTIONS: o.resolution = str(d["resolution"]) if str(d.get("fps")) in ("original", "30", "24"): o.fps = str(d["fps"]) if d.get("audio") in ("auto", "remove"): o.audio = d["audio"] if not o.speed: # big machines can afford the most efficient settings by default o.speed = "best" if settings.JOB_THREADS >= 6 else "balanced" return o @property def by_size(self) -> bool: return self.mode == "smaller" and self.level == "size" def effective(self) -> tuple[float, int, int]: """(VMAF target, short-side cap, fps cap) for these options.""" if self.mode != "smaller": return QUALITY_TARGETS[self.quality], 0, 0 # "size": picture size follows from the wanted file size (see size_mode_short_side) short, target, fps_cap = LEVELS[self.level] if self.level in LEVELS else (0, 91.0, 0) if self.resolution != "original": short = RESOLUTIONS[self.resolution] if self.fps != "original": fps_cap = int(self.fps) return target, short, fps_cap @dataclass class Plan: codec: str preset: object pix_fmt: str chain: list[str] out_w: int out_h: int target: float crf_min: float crf_max: float crf_step: float crf_start: float slope: float audio: list[tuple[int, str, int, int]] # (input index, "copy"|"aac", kbps, channels) audio_bytes: int subs: list[int] color_args: list[str] vmaf_model: str vmaf_scale: Optional[tuple[int, int]] samples: list[tuple[float, float]] max_iter: int tolerance: float search_subsample: int est_fps: float tonemap: bool fps_out: float = 30.0 search_preset: object = None whole: bool = False # samples == the whole clip: the best test encode IS the result fps: float = 30.0 notes: list[str] = field(default_factory=list) def _even(x: float) -> int: return max(2, int(round(x / 2.0)) * 2) def est_fps(codec: str, preset, pixels: int, threads: int) -> float: base = SPEED_TABLE[codec].get(preset) or 8.0 scale_px = (1920 * 1080 / max(pixels, 1)) ** 0.95 scale_cpu = (max(threads, 1) / 2.0) ** 0.85 return max(0.2, base * 0.75 * scale_px * scale_cpu) TONEMAP = ("zscale=t=linear:npl=100,format=gbrpf32le,zscale=p=bt709," "tonemap=tonemap=hable:desat=0,zscale=t=bt709:m=bt709:r=tv") def build_plan(info: MediaInfo, opts: Options) -> Plan: notes: list[str] = [] codec = opts.codec if not CAPS.get(codec): codec = next((c for c in ("av1", "hevc", "h264") if CAPS.get(c)), "") if not codec: raise EngineError("no_encoder") notes.append("codec_fallback") # ---- output size ------------------------------------------------------- target, target_short, fps_cap = opts.effective() w, h = info.width, info.height if opts.by_size: target_short = size_mode_short_side(info, opts, codec, target_short) scaled = bool(target_short and min(w, h) > target_short) if scaled: k = target_short / min(w, h) w, h = _even(w * k), _even(h * k) else: w, h = (w // 2) * 2, (h // 2) * 2 # ---- HDR / pixel format --------------------------------------------------- tonemap = False if codec == "h264" and info.hdr: if CAPS.get("zscale"): tonemap = True notes.append("hdr_tonemapped") elif CAPS.get("hevc"): codec = "hevc" notes.append("hdr_needs_hevc") if codec == "av1": pix_fmt = "yuv420p10le" elif codec == "hevc": pix_fmt = "yuv420p10le" if (info.bit_depth > 8 or info.hdr) else "yuv420p" else: pix_fmt = "yuv420p" if info.dovi_profile: notes.append("dovi_base_layer") # ---- filters: the SAME chain feeds samples, final encode and verification chain: list[str] = [] if info.interlaced: chain.append("bwdif=mode=send_frame:parity=auto:deint=all") notes.append("deinterlaced") if scaled: chain.append(f"scale={w}:{h}:flags=lanczos") elif (info.width % 2) or (info.height % 2): chain.append(f"crop={w}:{h}:0:0") if tonemap: chain.append(TONEMAP) elif info.color_range == "pc": chain.append("scale=in_range=full:out_range=limited") fps_out = info.fps if fps_cap and info.fps > fps_cap + 1: chain.append(f"fps={fps_cap}") fps_out = float(fps_cap) notes.append("fps_reduced") if scaled: notes.append("resized") chain.append(f"format={pix_fmt}") # ---- colour tags (unknown tags get what players would have assumed) ------- color_args = ["-color_range", "tv"] if tonemap: color_args += ["-color_primaries", "bt709", "-color_trc", "bt709", "-colorspace", "bt709"] else: hd = max(info.width, info.height) >= 1000 or min(info.width, info.height) >= 700 dflt = "bt709" if hd else "smpte170m" bad = ("", "unknown", "reserved") prim = info.color_primaries if info.color_primaries not in bad else dflt trc = info.color_transfer if info.color_transfer not in bad else dflt mat = info.color_space if info.color_space not in bad + ("gbr", "rgb") else dflt color_args += ["-color_primaries", prim, "-color_trc", trc, "-colorspace", mat] # ---- preset inside the time budget ------------------------------------------ pixels = w * h options = PRESETS[codec][opts.speed] preset = options[-1] for p in options: if info.frames / est_fps(codec, p, pixels, settings.JOB_THREADS) * 1.5 <= MAX_JOB_SECONDS: preset = p break if preset != options[0]: notes.append("faster_preset") # ---- CRF search space --------------------------------------------------------- lo, hi, step = CRF_RANGE[codec] k = 1.0 if codec == "av1" else 0.6 start = CRF_START[codec] + (95.0 - target) * 1.5 * k short = min(w, h) if short < 600: start -= 3.0 * k elif short < 900: start -= 1.5 * k elif short >= 2000: start += 2.0 * k start = min(max(start, lo), hi) # ---- VMAF ------------------------------------------------------------------------ vmaf_model, vmaf_scale = "vmaf_v0.6.1", None if short >= 2000: vmaf_model = "vmaf_4k_v0.6.1" elif max(w, h) < 1728 and short < 972: f = 1080.0 / short # small videos are judged as if watched full-screen vmaf_scale = (_even(w * f), _even(h * f)) # ---- audio: copy when already efficient, otherwise transparent AAC --------------- audio: list[tuple[int, str, int, int]] = [] audio_bytes = 0 if opts.audio == "remove": notes.append("audio_removed") else: # already-compressed audio is copied untouched unless its bitrate is far above # transparent; uncompressed/lossless audio becomes transparent AAC if target >= 96.5: per_ch, aac_ch = 160_000, 128 elif target >= 94.5: per_ch, aac_ch = 112_000, 96 elif target >= 90.5: per_ch, aac_ch = 96_000, 80 else: per_ch, aac_ch = 64_000, 56 for a in info.audio: ch = max(1, min(a.channels, 8)) limit = per_ch * max(2, ch) # mono gets the stereo allowance copyable = a.codec in ("aac", "mp3", "ac3", "eac3") or (a.codec == "opus" and codec == "av1") if copyable and (a.bitrate == 0 or a.bitrate <= limit): audio.append((a.index, "copy", 0, a.channels)) audio_bytes += int((a.bitrate or 128_000) * info.duration / 8) else: kbps = aac_ch * ch if ch > 1 else max(96, aac_ch) audio.append((a.index, "aac", kbps, ch)) audio_bytes += int(kbps * 1000 * info.duration / 8) if opts.by_size and audio: per_track = size_bitrates(info, opts)[1] audio = [(idx, mode, kb, ch) if (mode == "copy" and 0 < next( (a.bitrate for a in info.audio if a.index == idx), 0) <= per_track) else (idx, "aac", max(24, per_track // 1000), min(ch, 2)) for idx, mode, kb, ch in audio] audio_bytes = int(per_track * len(audio) * info.duration / 8) if info.subs_dropped: notes.append("bitmap_subs_dropped") # ---- samples ---------------------------------------------------------------------- budget = {"fast": 90, "balanced": 150, "best": 240}[opts.speed] budget = budget * (1920 * 1080 / max(pixels, 1)) ** 0.5 budget *= min(2.0, max(1.0, settings.JOB_THREADS / 2.0) ** 0.5) # testing must not cost much more than encoding the video itself budget = min(budget, max(48.0, info.frames * 0.3)) budget = int(min(360, max(48, budget))) samples = pick_samples(info.duration, info.fps, budget) whole = len(samples) == 1 and samples[0][0] == 0.0 search_preset = preset if opts.speed == "best" and not whole: # test at the next faster preset – the slower final encode only gets better faster = {"av1": {4: 6, 5: 7, 6: 7}, "hevc": {"slow": "medium"}, "h264": {"slower": "slow"}} search_preset = faster[codec].get(preset, preset) return Plan( codec=codec, preset=preset, pix_fmt=pix_fmt, chain=chain, out_w=w, out_h=h, target=target, crf_min=lo, crf_max=hi, crf_step=step, crf_start=start, slope=SLOPE[codec], audio=audio, audio_bytes=audio_bytes, subs=list(info.subs_text), color_args=color_args, vmaf_model=vmaf_model, vmaf_scale=vmaf_scale, samples=samples, max_iter={"fast": 4, "balanced": 5, "best": 7}[opts.speed], tolerance={"fast": 1.2, "balanced": 0.8, "best": 0.5}[opts.speed], search_subsample=1 if opts.speed == "best" else 2, est_fps=est_fps(codec, preset, pixels, settings.JOB_THREADS) * (info.fps / max(fps_out, 1)), tonemap=tonemap, fps_out=fps_out, search_preset=search_preset, whole=whole, fps=fps_out, notes=notes, ) def size_mode_short_side(info: MediaInfo, opts: Options, codec: str, forced: int) -> int: """Largest picture that still gets enough bits per pixel at the wanted size.""" if forced: return forced fps = min(info.fps, float(opts.fps)) if opts.fps != "original" else info.fps video_bps = size_bitrates(info, opts)[0] short0 = min(info.width, info.height) ratio = max(info.width, info.height) / max(1, short0) for short in (short0, 1080, 720, 540, 480, 360, 240): if short > short0: continue pixels = short * short * ratio if video_bps / (pixels * max(fps, 1)) >= MIN_BPP[codec]: return 0 if short == short0 else short return 240 def size_bitrates(info: MediaInfo, opts: Options) -> tuple[int, int]: """(video bits/s, audio bits/s per track) that land on the wanted file size.""" total = opts.target_mb * 1024 * 1024 * 8 * 0.975 / max(info.duration, 0.1) tracks = 0 if opts.audio == "remove" else len(info.audio) per_track = 0 if tracks: per_track = int(min(128_000, max(24_000, total * 0.1 / tracks))) return int(total - per_track * tracks), per_track def pick_samples(duration: float, fps: float, budget_frames: int) -> list[tuple[float, float]]: """Evenly spread short windows – or the whole clip when it is short anyway.""" # short clips are tested whole: exact quality, and the winning test becomes the result if duration * fps <= max(budget_frames * 1.25, 200) or duration <= 6.0: return [(0.0, round(duration, 3))] n = 2 if duration <= 15 else 3 if duration <= 60 else 4 if duration <= 300 else 5 length = max(1.0, budget_frames / n / max(fps, 1.0)) if n * length >= duration * 0.7: return [(0.0, round(duration, 3))] out = [] for i in range(n): start = duration * (i + 0.5) / n - length / 2 start = min(max(0.0, start), max(0.0, duration - length - 0.05)) out.append((round(start, 3), round(length, 3))) return out def video_args(plan: Plan, crf: float, preset=None, mp4: bool = True, bitrate: int = 0) -> list[str]: t = settings.JOB_THREADS preset = plan.preset if preset is None else preset rate = [f"crf={crf:g}"] if not bitrate else [] if plan.codec == "av1": params = [*rate, *(AV1_TUNING if CAPS.get("av1_tuned", True) else []), f"lp={t}"] if not CAPS.get("av1_tuned", True): params = [f"crf={int(round(crf))}"] if not bitrate else [f"lp={t}"] args = ["-c:v", "libsvtav1", "-preset", str(preset), "-pix_fmt", plan.pix_fmt, "-svtav1-params", ":".join(params)] if bitrate: args += ["-b:v", str(bitrate)] if CAPS.get("dovi_av1"): args += ["-dolbyvision", "0"] elif plan.codec == "hevc": args = ["-c:v", "libx265", "-preset", str(preset), *(["-b:v", str(bitrate)] if bitrate else ["-crf", f"{crf:g}"]), "-pix_fmt", plan.pix_fmt, "-profile:v", "main10" if "10" in plan.pix_fmt else "main", "-x265-params", f"log-level=error:aq-mode=3:pools={t}"] if mp4: args += ["-tag:v", "hvc1"] # Apple players need this tag in MP4 if CAPS.get("dovi_hevc"): args += ["-dolbyvision", "0"] else: args = ["-c:v", "libx264", "-preset", str(preset), *(["-b:v", str(bitrate), "-maxrate", str(int(bitrate * 1.6)), "-bufsize", str(bitrate * 3)] if bitrate else ["-crf", f"{crf:g}"]), "-pix_fmt", "yuv420p", "-profile:v", "high", "-x264-params", "aq-mode=3", "-threads", str(t)] return args + plan.color_args # =========================================================================== # # progress reporting # =========================================================================== # STAGES = ("analyze", "search", "encode", "verify", "finish") class Reporter: """Turns stage progress into overall progress + ETA (never moves backwards).""" def __init__(self, push: Callable[[dict], None], estimates: dict[str, float]): self.push = push self.est = dict(estimates) self.t0 = time.monotonic() self.stage = STAGES[0] self.stage_t0 = self.t0 self.stage_frac = 0.0 self.last = 0.0 def enter(self, stage: str, **extra) -> None: self.stage, self.stage_frac, self.stage_t0 = stage, 0.0, time.monotonic() self.emit(**extra) def remaining(self) -> float: now = time.monotonic() spent = now - self.stage_t0 cur = self.est.get(self.stage, 1.0) if self.stage_frac > 0.04 and spent > 2: cur = 0.5 * cur + 0.5 * (spent / self.stage_frac) if self.stage_frac < 0.15 else spent / self.stage_frac rem = max(0.0, cur - spent) later = STAGES[STAGES.index(self.stage) + 1:] return rem + sum(self.est.get(s, 0.0) for s in later) def emit(self, stage_frac: Optional[float] = None, **extra) -> None: if stage_frac is not None: self.stage_frac = max(self.stage_frac, min(1.0, stage_frac)) elapsed = time.monotonic() - self.t0 rem = self.remaining() overall = elapsed / (elapsed + rem) if (elapsed + rem) > 0 else 0.0 self.last = max(self.last, min(0.995, overall)) self.push({ "stage": self.stage, "stage_progress": round(self.stage_frac, 4), "progress": round(self.last, 4), "eta": int(rem), **extra, }) # =========================================================================== # # quality measurement # =========================================================================== # @dataclass class Score: crf: float vmaf: float # decision value mean: float p5: float minimum: float bytes: int enc_seconds: float path: Optional[Path] = None # kept only in whole-clip mode def _search_stride(plan: Plan, sample_seconds: float) -> int: frames = sample_seconds * plan.fps if plan.whole: # this measurement is the final verdict return odd_stride(frames, 240) return 1 if plan.search_subsample == 1 else odd_stride(frames, 75) def summarise_vmaf(path: Path) -> tuple[float, float, float, float]: data = json.loads(path.read_text()) vals = sorted(f["metrics"]["vmaf"] for f in data.get("frames", []) if "vmaf" in f.get("metrics", {})) if not vals: pooled = (data.get("pooled_metrics") or {}).get("vmaf") or {} m = float(pooled.get("mean", 0.0)) return m, m, m, float(pooled.get("min", m)) mean = sum(vals) / len(vals) p5 = vals[min(len(vals) - 1, int(len(vals) * 0.05))] # the average decides – but a run of clearly worse frames pulls it down return min(mean, p5 + 3.0), mean, p5, vals[0] def vmaf_graph(plan: Plan, log: Path, subsample: int, dist: str, ref: str, ref_chain: str = "", by_index: bool = True) -> str: sp = "setpts=N" if by_index else "setpts=PTS-STARTPTS,settb=1/1000" scale = f",scale={plan.vmaf_scale[0]}:{plan.vmaf_scale[1]}:flags=bicubic" if plan.vmaf_scale else "" fmt = ",format=yuv420p10le" if "10" in plan.pix_fmt else ",format=yuv420p" rc = f"{ref_chain}," if ref_chain else "" return (f"[{dist}]{sp}{scale}{fmt}[d];" f"[{ref}]{rc}{sp}{scale}{fmt}[r];" f"[d][r]libvmaf=model=version={plan.vmaf_model}:n_threads={settings.JOB_THREADS}" f":n_subsample={max(1, subsample)}:log_fmt=json:log_path={log}") # =========================================================================== # # pipeline # =========================================================================== # def stage_estimates(info: MediaInfo, plan: Plan) -> dict[str, float]: """Seconds each stage is expected to take on this machine.""" has_vmaf = bool(CAPS.get("vmaf")) vpix = (plan.vmaf_scale[0] * plan.vmaf_scale[1]) if plan.vmaf_scale else plan.out_w * plan.out_h vmaf_fps = 15.0 * (settings.JOB_THREADS / 2.0) ** 0.8 * (2_073_600 / max(1, vpix)) sample_frames = sum(l for _, l in plan.samples) * info.fps verify_sub = _verify_subsample(info) iters = min(4, plan.max_iter) search_fps = plan.est_fps * (1.6 if plan.search_preset != plan.preset else 1.0) whole = plan.whole and has_vmaf return { "analyze": (2 + sample_frames / 45.0) if has_vmaf else 1, "search": (iters * (4 + sample_frames * (1.25 / search_fps + 1 / (vmaf_fps * plan.search_subsample)))) if has_vmaf else 0, "encode": 3 if whole else info.frames / plan.est_fps, "verify": 0 if (whole or not has_vmaf) else (info.frames / 110.0 + info.frames / verify_sub / vmaf_fps), "finish": 5, } def odd_stride(frames: float, keep: int) -> int: """Score every n-th frame, n odd, so that roughly `keep` frames are scored. Even strides skip whole temporal layers of a hierarchical GOP (biased high).""" n = max(1, math.ceil(frames / max(1, keep))) return n if n % 2 else n + 1 def _verify_subsample(info: MediaInfo) -> int: return odd_stride(info.frames, 240) def estimate_seconds(info: MediaInfo, opts: Options) -> int: try: return int(sum(stage_estimates(info, build_plan(info, opts)).values())) except EngineError: return 0 async def compress(src: Path, work: Path, info: MediaInfo, opts: Options, push: Callable[[dict], None], cancel: asyncio.Event) -> dict: if opts.by_size: return await compress_to_size(src, work, info, opts, push, cancel) t_start = time.monotonic() plan = build_plan(info, opts) has_vmaf = bool(CAPS.get("vmaf")) sample_seconds = sum(l for _, l in plan.samples) sample_frames = sample_seconds * info.fps verify_sub = _verify_subsample(info) rep = Reporter(push, stage_estimates(info, plan)) rep.enter("analyze", plan={ "codec": plan.codec, "preset": str(plan.preset), "width": plan.out_w, "height": plan.out_h, "target": plan.target, "notes": plan.notes, }) log: list[dict] = [] best: Optional[Score] = None if has_vmaf: samples = work / "samples.nut" await extract_samples(src, info, plan, samples, cancel, lambda f: rep.emit(stage_frac=f)) rep.enter("search", search=log) best, optimal = await crf_search(info, plan, samples, sample_seconds, work, rep, log, cancel) _rm(samples) if optimal: if best.path: _rm(best.path) return _optimal(info, plan, log, t_start) crf = best.crf fps = sample_frames / max(best.enc_seconds, 0.05) if plan.search_preset != plan.preset: fps /= 1.6 rep.est["encode"] = 3 if best.path else info.frames / max(fps, 0.1) else: crf = _fallback_crf(plan) plan.notes.append("no_vmaf") out = work / "output.mp4" verified = None attempt = 0 while True: attempt += 1 rep.enter("encode", crf=crf) if best is not None and best.path and best.path.exists(): # short clip: the winning test encode already is the whole video await mux_final(src, info, plan, best.path, out, cancel) _rm(best.path) verified = (best.vmaf, best.mean, best.p5, best.minimum) if out.stat().st_size >= info.size * 0.985: _rm(out) return _optimal(info, plan, log, t_start, crf) break await final_encode(src, info, plan, crf, out, cancel, rep) if out.stat().st_size >= info.size * 0.985: _rm(out) return _optimal(info, plan, log, t_start, crf) if not has_vmaf: break rep.enter("verify") verified = await verify(src, info, plan, out, work, verify_sub, cancel, rep) # one corrective pass when the whole video missed the target noticeably if (verified[0] < plan.target - 0.6 and attempt == 1 and crf > plan.crf_min and "target_unreached" not in plan.notes and (time.monotonic() - t_start) < MAX_JOB_SECONDS * 0.45): slope = _log_slope(log, crf, plan.slope) drop = max(2 * plan.crf_step, (plan.target + SAFETY - verified[0]) / slope * 1.2) crf = max(plan.crf_min, _round_step(crf - drop, plan.crf_step)) plan.notes.append("corrected") continue break rep.enter("finish") previews = await make_previews(src, info, plan, out, work, cancel) rep.emit(stage_frac=0.7) out_info = await probe(str(out)) size = out.stat().st_size result = { "status": "done", "original": info.public(), "output": { "size": size, "codec": plan.codec, "width": out_info.width, "height": out_info.height, "duration": round(out_info.duration, 3), "bitrate": out_info.bitrate, "crf": crf, "preset": str(plan.preset), "bit_depth": out_info.bit_depth, "hdr": out_info.hdr, }, "reduction": round(1 - size / max(1, info.size), 4), "target": plan.target, "quality": None, "search": log, "previews": previews, "notes": plan.notes, "elapsed": round(time.monotonic() - t_start, 1), } if verified: result["quality"] = {"vmaf": round(verified[1], 2), "p5": round(verified[2], 2), "min": round(verified[3], 2), "verified": True} elif best: result["quality"] = {"vmaf": round(best.mean, 2), "p5": round(best.p5, 2), "min": round(best.minimum, 2), "verified": False} return result async def compress_to_size(src: Path, work: Path, info: MediaInfo, opts: Options, push: Callable[[dict], None], cancel: asyncio.Event) -> dict: """'Make it N MB': bitrate-driven encode, re-tried until it fits.""" t_start = time.monotonic() target_bytes = opts.target_mb * 1024 * 1024 if target_bytes >= info.size * 0.97: raise EngineError("target_too_big") video_bps, _ = size_bitrates(info, opts) if video_bps < 40_000: raise EngineError("target_too_small") plan = build_plan(info, opts) plan.notes.append("size_mode") est = stage_estimates(info, plan) rep = Reporter(push, {"analyze": 1, "search": 0, "encode": est["encode"] * 1.2, "verify": est["verify"], "finish": 5}) rep.enter("analyze", plan={"codec": plan.codec, "preset": str(plan.preset), "width": plan.out_w, "height": plan.out_h, "target": plan.target, "notes": plan.notes}) out = work / "output.mp4" rate = video_bps for attempt in range(3): rep.enter("encode", crf=None) await final_encode(src, info, plan, 0, out, cancel, rep, bitrate=rate) size = out.stat().st_size if size <= target_bytes * 1.02: break rate = int(rate * (target_bytes / size) * 0.95) if rate < 30_000: break verified = None if CAPS.get("vmaf"): rep.enter("verify") verified = await verify(src, info, plan, out, work, _verify_subsample(info), cancel, rep) rep.enter("finish") previews = await make_previews(src, info, plan, out, work, cancel) out_info = await probe(str(out)) size = out.stat().st_size return { "status": "done", "original": info.public(), "output": {"size": size, "codec": plan.codec, "width": out_info.width, "height": out_info.height, "duration": round(out_info.duration, 3), "bitrate": out_info.bitrate, "crf": None, "preset": str(plan.preset), "bit_depth": out_info.bit_depth, "hdr": out_info.hdr}, "reduction": round(1 - size / max(1, info.size), 4), "target": plan.target, "target_mb": opts.target_mb, "quality": ({"vmaf": round(verified[1], 2), "p5": round(verified[2], 2), "min": round(verified[3], 2), "verified": True} if verified else None), "search": [], "previews": previews, "notes": plan.notes, "elapsed": round(time.monotonic() - t_start, 1), } def _fallback_crf(plan: Plan) -> float: base = FALLBACK_CRF[plan.codec][95.0] return _round_step(min(plan.crf_max, base + (95.0 - plan.target) * 1.4), plan.crf_step) def _log_slope(log: list[dict], crf: float, default: float) -> float: """VMAF lost per CRF unit around `crf`, from the search measurements.""" pts = sorted((e["crf"], e["vmaf"]) for e in log) below = [p for p in pts if p[0] < crf] if below: c1, v1 = below[-1] v2 = next((v for c, v in pts if c == crf), None) if v2 is not None and crf > c1: s = (v1 - v2) / (crf - c1) if 0.1 <= s <= 4.0: return s return default def _rm(p: Path) -> None: try: p.unlink() except FileNotFoundError: pass def _optimal(info: MediaInfo, plan: Plan, log: list[dict], t_start: float, crf=None) -> dict: return {"status": "optimal", "original": info.public(), "codec": plan.codec, "target": plan.target, "search": log, "crf": crf, "notes": plan.notes, "elapsed": round(time.monotonic() - t_start, 1)} def _round_step(x: float, step: float) -> float: return round(round(x / step) * step, 2) async def extract_samples(src: Path, info: MediaInfo, plan: Plan, dest: Path, cancel: asyncio.Event, progress: Callable[[float], None]) -> None: """Cut the sample windows once, through the final filter chain, losslessly.""" chain = ",".join(plan.chain) t = str(settings.JOB_THREADS) total = sum(l for _, l in plan.samples) args: list[str] = [] if len(plan.samples) == 1: args += ["-threads", t, "-i", str(src), "-map", f"0:{info.v_index}", "-vf", chain] if plan.samples[0][1] < info.duration - 0.01: args += ["-t", f"{plan.samples[0][1]:.3f}"] else: for start, length in plan.samples: args += ["-threads", t, "-ss", f"{start:.3f}", "-t", f"{length:.3f}", "-i", str(src)] parts = [f"[{i}:{info.v_index}]{chain},setpts=PTS-STARTPTS[s{i}]" for i in range(len(plan.samples))] labels = "".join(f"[s{i}]" for i in range(len(plan.samples))) graph = ";".join(parts) + f";{labels}concat=n={len(plan.samples)}:v=1:a=0[out]" args += ["-filter_complex", graph, "-map", "[out]"] args += ["-an", "-sn", "-dn", "-c:v", "ffv1", "-level", "3", "-g", "1", "-slices", "4", "-threads", t, "-fps_mode", "passthrough", "-f", "nut", str(dest)] await run_ffmpeg(args, cancel=cancel, total_us=total * 1e6, on_progress=lambda f, _s: progress(f)) if not dest.exists() or dest.stat().st_size < 500: raise EngineError("sample_failed") async def evaluate(plan: Plan, samples: Path, crf: float, work: Path, sample_seconds: float, cancel: asyncio.Event, progress: Callable[[float], None]) -> Score: cand = work / f"cand_{crf:g}.nut" log = work / f"vmaf_{crf:g}.json" t = str(settings.JOB_THREADS) t0 = time.monotonic() await run_ffmpeg(["-threads", t, "-i", str(samples), "-map", "0:v:0", *video_args(plan, crf, plan.search_preset, mp4=False), "-an", "-f", "nut", str(cand)], cancel=cancel, total_us=sample_seconds * 1e6, on_progress=lambda f, _s: progress(f * 0.72)) enc_seconds = time.monotonic() - t0 size = cand.stat().st_size await run_ffmpeg(["-threads", t, "-i", str(cand), "-threads", t, "-i", str(samples), "-lavfi", vmaf_graph(plan, log, _search_stride(plan, sample_seconds), "0:v", "1:v"), "-f", "null", "-"], cancel=cancel, total_us=sample_seconds * 1e6, on_progress=lambda f, _s: progress(0.72 + f * 0.28)) score, mean, p5, mn = summarise_vmaf(log) _rm(log) if not plan.whole: _rm(cand) return Score(crf, score, mean, p5, mn, size, enc_seconds, cand if plan.whole else None) async def crf_search(info: MediaInfo, plan: Plan, samples: Path, sample_seconds: float, work: Path, rep: Reporter, log: list[dict], cancel: asyncio.Event) -> tuple[Score, bool]: """Highest CRF whose samples still score >= target. Returns (score, already_optimal).""" tested: dict[float, Score] = {} step = plan.crf_step crf = _round_step(plan.crf_start, step) target = plan.target + SAFETY # samples must beat the target by a hair passing: Optional[float] = None # highest crf meeting the target failing: Optional[float] = None # lowest crf missing it def predict(sc: Score) -> int: return int(sc.bytes / max(sample_seconds, 0.01) * info.duration * 0.97 + plan.audio_bytes) for it in range(plan.max_iter): sc = await evaluate(plan, samples, crf, work, sample_seconds, cancel, lambda f, _i=it: rep.emit(stage_frac=(_i + f) / plan.max_iter)) tested[crf] = sc ok = sc.vmaf >= target log.append({"crf": crf, "vmaf": round(sc.vmaf, 2), "mean": round(sc.mean, 2), "p5": round(sc.p5, 2), "predicted": predict(sc), "pass": ok}) rep.emit(stage_frac=(it + 1) / plan.max_iter, search=log) if ok: passing = crf if passing is None else max(passing, crf) else: failing = crf if failing is None else min(failing, crf) # even this lower-quality setting is not smaller than the original, so # every setting that passes would be bigger still – stop right here if predict(sc) >= info.size * 0.97: return sc, True if passing is not None and failing is not None: # one untested step between pass and fail is worth only ~3% of size if failing - passing <= 2 * step + 1e-6: break if tested[passing].vmaf - target <= plan.tolerance * 0.35: break s_hi, s_lo = tested[passing].vmaf, tested[failing].vmaf guess = passing + (s_hi - target) * (failing - passing) / max(s_hi - s_lo, 1e-6) guess = math.floor(guess / step + 1e-6) * step # lean to the passing side guess = min(max(round(guess, 2), passing + step), failing - step) elif passing is not None: if passing >= plan.crf_max: break margin = tested[passing].vmaf - target if len(tested) >= 2: # measured slope: stop when less than one step of headroom is left headroom = margin / _slope(tested, plan.slope, measured_only=True) if headroom < step * 1.0 + 1e-6 or (margin <= plan.tolerance * 0.35): break delta = headroom else: # one point only – the slope is unknown, so always probe once more delta = max(3.0 if plan.codec == "av1" else 2 * step, margin / plan.slope) guess = _round_step(passing + min(max(delta, step), 10.0), step) else: if failing <= plan.crf_min: break if len(tested) >= 2 and _slope(tested, plan.slope, measured_only=True) < PLATEAU[plan.codec]: break # quality has stopped rising – lower CRF only adds size # overshoot a little towards quality: landing on the passing side ends the search delta = (target - tested[failing].vmaf) / _slope(tested, plan.slope) * 1.25 + step / 2 guess = _round_step(failing - min(max(delta, step), 14.0), step) guess = min(max(guess, plan.crf_min), plan.crf_max) if guess in tested: break crf = guess if cancel.is_set(): raise Cancelled() rep.emit(stage_frac=1.0, search=log) if passing is None: plan.notes.append("target_unreached") top = max(sc.vmaf for sc in tested.values()) best = tested[max(c for c, sc in tested.items() if sc.vmaf >= top - 0.2)] else: best = tested[passing] for sc in tested.values(): # whole-clip mode keeps only the winner if sc is not best and sc.path: _rm(sc.path) return best, predict(best) >= info.size * 0.985 def _slope(tested: dict[float, Score], default: float, measured_only: bool = False) -> float: """VMAF points lost per CRF unit, from the two closest-to-target points.""" if len(tested) >= 2: pts = sorted(tested.items()) (c1, s1), (c2, s2) = pts[-2], pts[-1] if c2 > c1: s = (s1.vmaf - s2.vmaf) / (c2 - c1) if measured_only: return min(max(s, 0.04), 4.0) if 0.15 <= s <= 4.0: return s return default async def final_encode(src: Path, info: MediaInfo, plan: Plan, crf: float, out: Path, cancel: asyncio.Event, rep: Reporter, _retry: int = 0, bitrate: int = 0) -> None: t = str(settings.JOB_THREADS) args = ["-threads", t, "-i", str(src), "-map", f"0:{info.v_index}"] for idx, *_ in plan.audio: args += ["-map", f"0:{idx}"] for idx in plan.subs: args += ["-map", f"0:{idx}"] args += ["-filter:v", ",".join(plan.chain), *video_args(plan, crf, bitrate=bitrate), "-fps_mode:v", "vfr"] if not plan.audio: args += ["-an"] args += _audio_sub_args(plan, info) args += ["-dn", "-map_metadata", "0", "-map_chapters", "0", "-movflags", "+faststart+use_metadata_tags", "-max_muxing_queue_size", "4096", str(out)] try: await run_ffmpeg(args, cancel=cancel, total_us=info.duration * 1e6, on_progress=lambda f, s: rep.emit(stage_frac=f, speed=s.get("speed", ""))) except EngineError: # rare muxing problems: retry without subtitles, then with all audio as AAC if _retry == 0 and plan.subs: plan.subs = [] plan.notes.append("subs_dropped") elif _retry <= 1 and any(m == "copy" for _, m, _, _ in plan.audio): plan.audio = [(i, "aac", {1: 96, 2: 192}.get(min(c, 8), 64 * min(c, 8)), min(c, 8)) for i, _m, _k, c in plan.audio] plan.notes.append("audio_reencoded") else: raise _rm(out) await final_encode(src, info, plan, crf, out, cancel, rep, _retry + 1, bitrate) return if not out.exists() or out.stat().st_size < 500: raise EngineError("encode_failed") def _audio_sub_args(plan: Plan, info: MediaInfo) -> list[str]: args: list[str] = [] for n, (idx, mode, kbps, ch) in enumerate(plan.audio): if mode == "copy": args += [f"-c:a:{n}", "copy"] else: args += [f"-c:a:{n}", "aac", f"-b:a:{n}", f"{kbps}k", f"-ac:a:{n}", str(ch)] rate = next((a.sample_rate for a in info.audio if a.index == idx), 48000) if rate > 48000 or rate < 8000: args += [f"-ar:a:{n}", "48000"] args += ["-c:s", "mov_text"] if plan.subs else ["-sn"] return args async def mux_final(src: Path, info: MediaInfo, plan: Plan, video: Path, out: Path, cancel: asyncio.Event, _retry: int = 0) -> None: """Short clips: put the winning test encode together with the original audio, subtitles and metadata – no second encode needed.""" t = str(settings.JOB_THREADS) args = ["-threads", t] if info.v_offset > 0.001: args += ["-itsoffset", f"{info.v_offset:.6f}"] args += ["-i", str(video), "-i", str(src), "-map", "0:v:0"] for idx, *_ in plan.audio: args += ["-map", f"1:{idx}"] for idx in plan.subs: args += ["-map", f"1:{idx}"] args += ["-c:v", "copy"] if plan.codec == "hevc": args += ["-tag:v", "hvc1"] if not plan.audio: args += ["-an"] args += _audio_sub_args(plan, info) args += ["-dn", "-map_metadata", "1", "-map_chapters", "1", "-movflags", "+faststart+use_metadata_tags", "-max_muxing_queue_size", "4096", str(out)] try: await run_ffmpeg(args, cancel=cancel) except EngineError: if _retry == 0 and plan.subs: plan.subs = [] plan.notes.append("subs_dropped") elif _retry <= 1 and any(m == "copy" for _, m, _, _ in plan.audio): plan.audio = [(i, "aac", {1: 96, 2: 192}.get(min(c, 8), 64 * min(c, 8)), min(c, 8)) for i, _m, _k, c in plan.audio] plan.notes.append("audio_reencoded") else: raise _rm(out) await mux_final(src, info, plan, video, out, cancel, _retry + 1) return if not out.exists() or out.stat().st_size < 500: raise EngineError("encode_failed") async def verify(src: Path, info: MediaInfo, plan: Plan, out: Path, work: Path, subsample: int, cancel: asyncio.Event, rep: Reporter) -> tuple[float, float, float, float]: log = work / "vmaf_final.json" t = str(settings.JOB_THREADS) graph = vmaf_graph(plan, log, subsample, "0:v:0", f"1:{info.v_index}", ref_chain=",".join(plan.chain), by_index=False) await run_ffmpeg(["-threads", t, "-i", str(out), "-threads", t, "-i", str(src), "-lavfi", graph, "-f", "null", "-"], cancel=cancel, total_us=info.duration * 1e6, on_progress=lambda f, _s: rep.emit(stage_frac=f)) res = summarise_vmaf(log) _rm(log) return res async def make_poster(src: Path, info: MediaInfo, dest: Path) -> bool: """A display frame for the page – browsers cannot show every source format.""" view = "scale='min(1280,iw)':-2:flags=bicubic" if info.hdr and CAPS.get("zscale"): view = TONEMAP + "," + view ts = max(0.0, min(info.duration - 0.15, info.duration * 0.2, 4.0)) try: await run_ffmpeg(["-ss", f"{ts:.3f}", "-i", str(src), "-map", f"0:{info.v_index}", "-frames:v", "1", "-vf", view, "-q:v", "3", str(dest)]) except EngineError: return False return dest.exists() and dest.stat().st_size > 0 async def make_previews(src: Path, info: MediaInfo, plan: Plan, out: Path, work: Path, cancel: asyncio.Event) -> list[dict]: """The same moment from the original and from the result, for the slider.""" k = min(1.0, 1920.0 / max(plan.out_w, plan.out_h)) pw, ph = _even(plan.out_w * k), _even(plan.out_h * k) fit = f"scale={pw}:{ph}:flags=lanczos" show_hdr = bool(info.hdr) and CAPS.get("zscale") src_view = [c for c in plan.chain if not c.startswith(("format=", "zscale=t=linear"))] if show_hdr: src_view.append(TONEMAP) # display only – a JPEG cannot hold HDR src_view.append(fit) out_view = ([TONEMAP] if show_hdr and not plan.tonemap else []) + [fit] shots = [] for n, frac in enumerate((0.2, 0.5, 0.8)): ts = max(0.0, min(info.duration - 0.15, info.duration * frac)) a, b = work / f"prev_{n}_a.jpg", work / f"prev_{n}_b.jpg" try: await run_ffmpeg(["-ss", f"{ts:.3f}", "-i", str(src), "-map", f"0:{info.v_index}", "-frames:v", "1", "-vf", ",".join(src_view), "-q:v", "2", str(a)], cancel=cancel) await run_ffmpeg(["-ss", f"{ts:.3f}", "-i", str(out), "-map", "0:v:0", "-frames:v", "1", "-vf", ",".join(out_view), "-q:v", "2", str(b)], cancel=cancel) if a.exists() and b.exists(): shots.append({"n": n, "t": round(ts, 2), "w": pw, "h": ph}) except Cancelled: raise except Exception: continue return shots
"""Compression engine.
Pipeline for every video:
1. probe – streams, colour, HDR, rotation, audio, subtitles
2. plan – codec settings, filters, audio handling, sample windows
3. search – encode short samples at a few CRF values and score each with
VMAF (Netflix's perceptual quality metric) until the highest
CRF (= smallest file) that still meets the quality target is
found. This is per-video ("per-title") optimisation.
4. encode – encode the whole video once with that CRF
5. verify – score the finished file against the original with VMAF
6. previews – matching frames for the before/after slider
The result is never bigger than the original: when it would be, the job ends
as "already optimal" instead of returning a worse file.
"""
from __future__ import annotations
import asyncio
import json
import math
import os
import re
import signal
import time
from collections import deque
from dataclasses import dataclass, field
from pathlib import Path
from typing import Callable, Optional
from . import settings
FFMPEG = settings.FFMPEG
FFPROBE = settings.FFPROBE
THREADS = settings.JOB_THREADS
MAX_JOB_SECONDS = max(300, int(os.environ.get("MAX_JOB_MINUTES", "45") or 45) * 60)
_ENV = dict(os.environ, SVT_LOG="1", AV_LOG_FORCE_NOCOLOR="1")
# =========================================================================== #
# errors
# =========================================================================== #
class EngineError(Exception):
"""Failure with a code that the API turns into a Persian message."""
def __init__(self, code: str, detail: str = ""):
super().__init__(f"{code}: {detail}")
self.code = code
self.detail = detail
class Cancelled(Exception):
pass
# =========================================================================== #
# subprocess helpers
# =========================================================================== #
def _nice(cmd: list[str]) -> list[str]:
# encoders run at lower priority so the web server always stays responsive
for path in ("/usr/bin/nice", "/bin/nice"):
if os.path.exists(path):
return [path, "-n", "10", *cmd]
return cmd
async def run_capture(cmd: list[str], timeout: float = 120) -> tuple[int, str, str]:
proc = await asyncio.create_subprocess_exec(
*cmd,
stdin=asyncio.subprocess.DEVNULL,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE,
env=_ENV,
)
try:
out, err = await asyncio.wait_for(proc.communicate(), timeout)
except asyncio.TimeoutError:
proc.kill()
await proc.wait()
raise EngineError("timeout", " ".join(cmd[:2]))
return proc.returncode, out.decode("utf-8", "replace"), err.decode("utf-8", "replace")
async def _terminate(proc: asyncio.subprocess.Process) -> None:
if proc.returncode is not None:
return
try:
os.killpg(proc.pid, signal.SIGTERM)
except Exception:
try:
proc.terminate()
except Exception:
return
try:
await asyncio.wait_for(proc.wait(), 4)
except asyncio.TimeoutError:
try:
os.killpg(proc.pid, signal.SIGKILL)
except Exception: