encoder.py 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130
  1. """视频片段编码。
  2. 浏览器(Chrome/Safari/Edge)不能解码 OpenCV 默认的 `mp4v`(MPEG-4 Part 2),
  3. 因此优先用 ffmpeg 输出 H.264/yuv420p + faststart;ffmpeg 不可用时回退到
  4. cv2.VideoWriter,保证功能不中断(仅可下载、网页内可能无法直接播放)。
  5. """
  6. from __future__ import annotations
  7. import logging
  8. import shutil
  9. import subprocess
  10. from pathlib import Path
  11. import cv2
  12. import numpy as np
  13. log = logging.getLogger("dccai.encoder")
  14. FFMPEG = shutil.which("ffmpeg") or "/opt/homebrew/bin/ffmpeg"
  15. _HAS_FFMPEG = bool(shutil.which("ffmpeg") or Path(FFMPEG).exists())
  16. def ffmpeg_available() -> bool:
  17. return _HAS_FFMPEG
  18. def _ffmpeg_cmd(out_path: Path, size: tuple[int, int], fps: float) -> list[str]:
  19. w, h = size
  20. return [
  21. FFMPEG, "-y", "-loglevel", "error",
  22. "-f", "rawvideo", "-pix_fmt", "bgr24",
  23. "-s", f"{w}x{h}", "-r", f"{fps:.6f}",
  24. "-i", "-",
  25. "-an",
  26. "-c:v", "libx264",
  27. "-profile:v", "high", "-level", "4.0",
  28. "-preset", "veryfast", "-crf", "24",
  29. "-pix_fmt", "yuv420p",
  30. "-tag:v", "avc1",
  31. "-movflags", "+faststart",
  32. str(out_path),
  33. ]
  34. class FfmpegVideoWriter:
  35. """把 BGR 帧通过管道喂给 ffmpeg 编码为浏览器可播放的 mp4。"""
  36. def __init__(self, out_path: Path, size: tuple[int, int], fps: float):
  37. self.out_path = Path(out_path)
  38. self.size = (max(2, int(size[0])), max(2, int(size[1])))
  39. self.fps = max(1.0, float(fps))
  40. self.frames = 0
  41. self._proc: subprocess.Popen | None = None
  42. self._fallback: cv2.VideoWriter | None = None
  43. if _HAS_FFMPEG:
  44. self._proc = subprocess.Popen(
  45. _ffmpeg_cmd(self.out_path, self.size, self.fps),
  46. stdin=subprocess.PIPE, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE,
  47. )
  48. else:
  49. log.warning("未找到 ffmpeg,回退到 cv2 mp4v(浏览器可能无法内嵌播放)")
  50. self._fallback = cv2.VideoWriter(
  51. str(self.out_path), cv2.VideoWriter_fourcc(*"mp4v"), self.fps, self.size
  52. )
  53. def write(self, frame: np.ndarray) -> None:
  54. w, h = self.size
  55. if frame.shape[1] != w or frame.shape[0] != h:
  56. frame = cv2.resize(frame, (w, h))
  57. if self._proc is not None and self._proc.stdin is not None:
  58. try:
  59. self._proc.stdin.write(np.ascontiguousarray(frame).tobytes())
  60. self.frames += 1
  61. except (BrokenPipeError, OSError):
  62. self._proc = None
  63. elif self._fallback is not None:
  64. self._fallback.write(frame)
  65. self.frames += 1
  66. def release(self) -> tuple[bool, str]:
  67. """返回 (是否 H.264, 错误信息)。"""
  68. if self._proc is not None:
  69. err = ""
  70. try:
  71. # communicate() 会自行关闭 stdin 并等待进程退出
  72. _, e = self._proc.communicate(timeout=180)
  73. err = (e or b"").decode("utf-8", "ignore").strip()
  74. except Exception as ex: # noqa: BLE001
  75. self._proc.kill()
  76. err = str(ex)
  77. ok = self._proc.returncode == 0 and self.out_path.exists()
  78. if not ok:
  79. log.error("ffmpeg 编码失败:%s", err)
  80. return ok, err
  81. if self._fallback is not None:
  82. self._fallback.release()
  83. return False, "未使用 ffmpeg"
  84. def transcode_to_webm(src: Path, dst: Path, crf: int = 34, timeout: int = 900) -> tuple[bool, str]:
  85. """把 mp4(H.264) 转成 VP9/WebM。
  86. 用于「浏览器不带 H.264 解码器」的场景(部分 Chromium 发行版):
  87. VP9 是免版税编解码,所有 Chromium/Firefox 都内置支持。
  88. """
  89. if not _HAS_FFMPEG:
  90. return False, "未找到 ffmpeg,无法转码"
  91. if not src.exists():
  92. return False, f"源片段不存在:{src}"
  93. tmp = dst.with_suffix(".webm.part")
  94. cmd = [
  95. FFMPEG, "-y", "-loglevel", "error",
  96. "-i", str(src),
  97. "-an",
  98. "-c:v", "libvpx-vp9", "-b:v", "0", "-crf", str(crf),
  99. "-deadline", "good", "-cpu-used", "4", "-row-mt", "1",
  100. "-pix_fmt", "yuv420p",
  101. "-f", "webm", # .part 后缀无法推断容器,必须显式指定
  102. str(tmp),
  103. ]
  104. try:
  105. r = subprocess.run(cmd, capture_output=True, timeout=timeout)
  106. except subprocess.TimeoutExpired:
  107. tmp.unlink(missing_ok=True)
  108. return False, "转码超时"
  109. if r.returncode != 0 or not tmp.exists():
  110. tmp.unlink(missing_ok=True)
  111. return False, (r.stderr or b"").decode("utf-8", "ignore").strip()[:300]
  112. tmp.replace(dst)
  113. return True, ""