"""视频片段编码。 浏览器(Chrome/Safari/Edge)不能解码 OpenCV 默认的 `mp4v`(MPEG-4 Part 2), 因此优先用 ffmpeg 输出 H.264/yuv420p + faststart;ffmpeg 不可用时回退到 cv2.VideoWriter,保证功能不中断(仅可下载、网页内可能无法直接播放)。 """ from __future__ import annotations import logging import shutil import subprocess from pathlib import Path import cv2 import numpy as np log = logging.getLogger("dccai.encoder") FFMPEG = shutil.which("ffmpeg") or "/opt/homebrew/bin/ffmpeg" _HAS_FFMPEG = bool(shutil.which("ffmpeg") or Path(FFMPEG).exists()) def ffmpeg_available() -> bool: return _HAS_FFMPEG def _ffmpeg_cmd(out_path: Path, size: tuple[int, int], fps: float) -> list[str]: w, h = size return [ FFMPEG, "-y", "-loglevel", "error", "-f", "rawvideo", "-pix_fmt", "bgr24", "-s", f"{w}x{h}", "-r", f"{fps:.6f}", "-i", "-", "-an", "-c:v", "libx264", "-profile:v", "high", "-level", "4.0", "-preset", "veryfast", "-crf", "24", "-pix_fmt", "yuv420p", "-tag:v", "avc1", "-movflags", "+faststart", str(out_path), ] class FfmpegVideoWriter: """把 BGR 帧通过管道喂给 ffmpeg 编码为浏览器可播放的 mp4。""" def __init__(self, out_path: Path, size: tuple[int, int], fps: float): self.out_path = Path(out_path) self.size = (max(2, int(size[0])), max(2, int(size[1]))) self.fps = max(1.0, float(fps)) self.frames = 0 self._proc: subprocess.Popen | None = None self._fallback: cv2.VideoWriter | None = None if _HAS_FFMPEG: self._proc = subprocess.Popen( _ffmpeg_cmd(self.out_path, self.size, self.fps), stdin=subprocess.PIPE, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE, ) else: log.warning("未找到 ffmpeg,回退到 cv2 mp4v(浏览器可能无法内嵌播放)") self._fallback = cv2.VideoWriter( str(self.out_path), cv2.VideoWriter_fourcc(*"mp4v"), self.fps, self.size ) def write(self, frame: np.ndarray) -> None: w, h = self.size if frame.shape[1] != w or frame.shape[0] != h: frame = cv2.resize(frame, (w, h)) if self._proc is not None and self._proc.stdin is not None: try: self._proc.stdin.write(np.ascontiguousarray(frame).tobytes()) self.frames += 1 except (BrokenPipeError, OSError): self._proc = None elif self._fallback is not None: self._fallback.write(frame) self.frames += 1 def release(self) -> tuple[bool, str]: """返回 (是否 H.264, 错误信息)。""" if self._proc is not None: err = "" try: # communicate() 会自行关闭 stdin 并等待进程退出 _, e = self._proc.communicate(timeout=180) err = (e or b"").decode("utf-8", "ignore").strip() except Exception as ex: # noqa: BLE001 self._proc.kill() err = str(ex) ok = self._proc.returncode == 0 and self.out_path.exists() if not ok: log.error("ffmpeg 编码失败:%s", err) return ok, err if self._fallback is not None: self._fallback.release() return False, "未使用 ffmpeg" def transcode_to_webm(src: Path, dst: Path, crf: int = 34, timeout: int = 900) -> tuple[bool, str]: """把 mp4(H.264) 转成 VP9/WebM。 用于「浏览器不带 H.264 解码器」的场景(部分 Chromium 发行版): VP9 是免版税编解码,所有 Chromium/Firefox 都内置支持。 """ if not _HAS_FFMPEG: return False, "未找到 ffmpeg,无法转码" if not src.exists(): return False, f"源片段不存在:{src}" tmp = dst.with_suffix(".webm.part") cmd = [ FFMPEG, "-y", "-loglevel", "error", "-i", str(src), "-an", "-c:v", "libvpx-vp9", "-b:v", "0", "-crf", str(crf), "-deadline", "good", "-cpu-used", "4", "-row-mt", "1", "-pix_fmt", "yuv420p", "-f", "webm", # .part 后缀无法推断容器,必须显式指定 str(tmp), ] try: r = subprocess.run(cmd, capture_output=True, timeout=timeout) except subprocess.TimeoutExpired: tmp.unlink(missing_ok=True) return False, "转码超时" if r.returncode != 0 or not tmp.exists(): tmp.unlink(missing_ok=True) return False, (r.stderr or b"").decode("utf-8", "ignore").strip()[:300] tmp.replace(dst) return True, ""