from __future__ import annotations import json import math import subprocess import tempfile from dataclasses import dataclass from fractions import Fraction from pathlib import Path from typing import Any, Iterator import numpy as np PIXEL_FORMATS = ("yuv420p", "yuv444p") @dataclass(frozen=True) class VideoConfig: codec: str = "libx265" preset: str = "medium" crf: int = 18 pixel_format: str = "yuv420p" gop: int = 30 encoder_pools: int = 6 def encoder_command(ffmpeg: str, output: Path | str, width: int, height: int, fps: float, config: VideoConfig = VideoConfig()) -> list[str]: return [ ffmpeg, "-y", "-loglevel", "error", "-f", "rawvideo", "-pix_fmt", "rgb24", "-s:v", f"{width}x{height}", "-r", f"{fps:.9f}", "-i", "-", "-an", "-c:v", config.codec, "-preset", config.preset, "-crf", str(config.crf), "-pix_fmt", config.pixel_format, "-g", str(config.gop), "-x265-params", f"pools={config.encoder_pools}:keyint={config.gop}:min-keyint={config.gop}:scenecut=0", "-tag:v", "hvc1", "-movflags", "+faststart", "-f", "mp4", str(output), ] class VideoEncoder: def __init__(self, ffmpeg: str, destination: Path, width: int, height: int, fps: float, config: VideoConfig = VideoConfig()) -> None: if width <= 0 or height <= 0 or width % 2 or height % 2: raise ValueError("HEVC yuv420p requires positive even width and height") if not math.isfinite(fps) or fps <= 0: raise ValueError("fps must be positive and finite") if config.codec != "libx265" or config.pixel_format not in PIXEL_FORMATS: raise ValueError(f"video contract requires libx265 with a pixel format in {PIXEL_FORMATS}") self.destination = Path(destination) self.destination.parent.mkdir(parents=True, exist_ok=True) self.temporary = self.destination.with_name(self.destination.name + ".partial") self.frame_bytes = width * height * 3 self.frames_written = 0 self.closed = False self.log = tempfile.TemporaryFile() command = encoder_command(ffmpeg, self.temporary, width, height, fps, config) try: self.process = subprocess.Popen(command, stdin=subprocess.PIPE, stderr=self.log) except OSError: self.log.close() raise def write(self, frame: bytes | np.ndarray) -> None: if isinstance(frame, np.ndarray): if frame.dtype != np.uint8: raise ValueError("encoder requires uint8 RGB") frame = np.ascontiguousarray(frame).tobytes() if len(frame) != self.frame_bytes: raise ValueError("encoder frame has wrong byte count") if self.closed or self.process.stdin is None: raise RuntimeError("encoder stdin is closed") self.process.stdin.write(frame) self.frames_written += 1 def finish(self) -> None: if self.closed: raise RuntimeError("encoder is already closed") try: if self.process.stdin is not None: self.process.stdin.close() code = self.process.wait() self.log.seek(0) error = self.log.read().decode(errors="replace") if code != 0 or not self.frames_written or not self.temporary.is_file(): raise RuntimeError(f"ffmpeg failed with exit code {code}: {error.strip()}") self.temporary.replace(self.destination) except BaseException: self.abort() raise finally: self.closed = True self.log.close() def abort(self) -> None: if self.process.poll() is None: self.process.kill() self.process.wait() if self.process.stdin is not None: try: self.process.stdin.close() except BrokenPipeError: pass self.temporary.unlink(missing_ok=True) self.log.close() self.closed = True def __enter__(self) -> VideoEncoder: return self def __exit__(self, exc_type: object, exc: object, traceback: object) -> None: if exc_type is None: self.finish() else: self.abort() def validate_video(path: Path, *, width: int, height: int, count: int, fps: float, ffprobe: str = "ffprobe", pixel_format: str = "yuv420p") -> dict[str, Any]: result = subprocess.run( [ffprobe, "-v", "error", "-select_streams", "v:0", "-count_frames", "-show_streams", "-of", "json", str(path)], text=True, capture_output=True, check=False, ) if result.returncode or result.stderr.strip(): raise ValueError(f"video decode/probe failed: {path.name}: {result.stderr.strip()}") streams = json.loads(result.stdout).get("streams", []) if len(streams) != 1: raise ValueError("video must contain one readable video stream") stream = streams[0] if (stream.get("codec_name"), stream.get("pix_fmt"), stream.get("width"), stream.get("height")) != ("hevc", pixel_format, width, height): raise ValueError("video codec, pixel format or resolution mismatch") if int(stream.get("nb_read_frames", -1)) != count: raise ValueError("video frame count mismatch") rate = float(Fraction(stream["avg_frame_rate"])) if not math.isclose(rate, fps, rel_tol=1e-5, abs_tol=1e-6): raise ValueError("video frame rate mismatch") if abs(float(stream.get("start_time", 0))) > 1 / fps: raise ValueError("video time origin mismatch") if abs(float(stream["duration"]) - count / fps) > 1 / fps: raise ValueError("video duration mismatch") return {"codec": "hevc", "pixel_format": pixel_format, "frame_count": count, "resolution": [width, height], "fps": rate} def decode_frames(path: Path | str, *, thread_count: int = 2, thread_type: str | None = None, expected_frames: int | None = None) -> Iterator[np.ndarray]: import av with av.open(str(path)) as container: stream = container.streams.video[0] pts = sorted(int(p.pts) for p in container.demux(stream) if p.pts is not None) if len(set(pts)) != len(pts) or not pts: raise ValueError(f"{path}: empty or duplicate packet pts") if expected_frames is not None and len(pts) != expected_frames: raise ValueError(f"{path}: {len(pts)} packets, expected {expected_frames} frames") with av.open(str(path)) as container: stream = container.streams.video[0] if thread_type: stream.thread_type = thread_type if thread_count: stream.thread_count = thread_count index = 0 for frame in container.decode(stream): if frame.pts is None: continue if index >= len(pts) or int(frame.pts) != pts[index]: raise ValueError(f"{path}: decoded pts {frame.pts} is not frame {index} of the packet index") yield frame.to_ndarray(format="rgb24") index += 1 if index != len(pts): raise ValueError(f"{path}: decoded {index} of {len(pts)} frames")