Skip to content

Open-source AI podcast clipper. Generate vertical clips with face tracking and burned-in captions. CLI, MCP server, web app.

backend: extract ffmpeg probe helpers into services/media_probe

Nika Siradze25bed0d879fa
diff --git a/backend/services/media_probe.py b/backend/services/media_probe.py
new file mode 100644
index 0000000..b84de00
--- /dev/null
+++ b/backend/services/media_probe.py
@@ -0,0 +1,151 @@
+"""FFmpeg / ffprobe utility helpers.
+
+Extracted from video_processor.py so small probing functions can be
+reused (and unit-tested) without pulling in the 3600+ lines of the
+rendering pipeline. The rendering module re-exports these to keep the
+historical import surface stable.
+
+All functions here route subprocess calls through utils.proc.run so
+they inherit the mandatory timeout + structured logging.
+"""
+
+from __future__ import annotations
+
+import json
+import math
+import os
+import sys
+from typing import Optional
+
+from services.encoder import get_video_encode_flags
+from utils.proc import run as proc_run
+
+# Max time for any single FFmpeg/ffprobe call (seconds).
+# Prevents the rendering pipeline from hanging on a stuck process.
+FFMPEG_TIMEOUT = 300
+
+# Quality presets: name → (crf, preset) for libx264.
+# Lower CRF = higher quality = larger file. 18 is visually lossless.
+QUALITY_PRESETS = {
+ "low": {"crf": "28", "preset": "fast"}, # ~2-4 MB/min, fast encode
+ "medium": {"crf": "23", "preset": "medium"}, # ~4-8 MB/min, balanced
+ "high": {"crf": "18", "preset": "slow"}, # ~8-15 MB/min, great quality
+ "max": {"crf": "14", "preset": "slower"}, # ~15-30 MB/min, near-lossless
+}
+
+_quality = os.environ.get("PODCLI_QUALITY", "high")
+_qp = QUALITY_PRESETS.get(_quality, QUALITY_PRESETS["high"])
+CPU_FLAGS = [
+ "-c:v", "libx264",
+ "-crf", _qp["crf"],
+ "-preset", _qp["preset"],
+ "-profile:v", "high",
+]
+
+
+def run_ffmpeg_with_fallback(
+ cmd_parts_before_enc: list,
+ cmd_parts_after_enc: list,
+ output_path: str,
+ label: str = "encode",
+) -> str:
+ """Run an FFmpeg command with the best encoder; retry libx264 on failure.
+
+ Final command shape:
+ cmd_parts_before_enc + <encoder_flags> + cmd_parts_after_enc + [output_path]
+
+ If the preferred hardware encoder fails, the function automatically
+ retries with libx264 before raising.
+ """
+ enc_flags = get_video_encode_flags()
+ cmd = cmd_parts_before_enc + enc_flags + cmd_parts_after_enc + [output_path]
+
+ result = proc_run(cmd, timeout=FFMPEG_TIMEOUT, check=False)
+ if result.returncode == 0:
+ return output_path
+
+ if enc_flags != CPU_FLAGS:
+ print(
+ f"Warning: HW encoder failed for {label}, falling back to libx264",
+ file=sys.stderr,
+ )
+ cmd_fallback = cmd_parts_before_enc + CPU_FLAGS + cmd_parts_after_enc + [output_path]
+ result2 = proc_run(cmd_fallback, timeout=FFMPEG_TIMEOUT, check=False)
+ if result2.returncode == 0:
+ return output_path
+ raise RuntimeError(
+ f"FFmpeg {label} failed (both HW and CPU): {result2.stderr[-500:]}"
+ )
+
+ raise RuntimeError(f"FFmpeg {label} failed: {result.stderr[-500:]}")
+
+
+def get_video_info(video_path: str) -> dict:
+ """Probe a media file and return the full ffprobe JSON payload."""
+ cmd = [
+ "ffprobe",
+ "-v", "quiet",
+ "-print_format", "json",
+ "-show_format",
+ "-show_streams",
+ video_path,
+ ]
+ result = proc_run(cmd, timeout=FFMPEG_TIMEOUT, check=False)
+ if result.returncode != 0:
+ raise RuntimeError(f"ffprobe failed: {result.stderr}")
+ return json.loads(result.stdout)
+
+
+def has_audio_stream(video_path: str) -> bool:
+ """Return True if the file has any audio stream (best-effort)."""
+ try:
+ info = get_video_info(video_path)
+ return any(s.get("codec_type") == "audio" for s in info.get("streams", []))
+ except Exception:
+ # Assume yes if we can't check — missing audio is reasonably rare
+ # and downstream concat filters will surface the real error.
+ return True
+
+
+def parse_duration_seconds(value: object) -> Optional[float]:
+ """Parse a duration-like value, rejecting non-finite / non-positive numbers."""
+ try:
+ parsed = float(str(value).strip())
+ except Exception:
+ return None
+ if not math.isfinite(parsed) or parsed <= 0:
+ return None
+ return parsed
+
+
+def get_media_duration_seconds(video_path: str, default: float = 0.0) -> float:
+ """Best-effort media duration in seconds.
+
+ Prefers the max valid duration from the format block and per-stream
+ durations; falls back to `default` if nothing parseable is found.
+ """
+ try:
+ info = get_video_info(video_path)
+ except Exception:
+ return default
+
+ candidates: list[float] = []
+ fmt_duration = parse_duration_seconds(info.get("format", {}).get("duration"))
+ if fmt_duration is not None:
+ candidates.append(fmt_duration)
+
+ for stream in info.get("streams", []):
+ stream_duration = parse_duration_seconds(stream.get("duration"))
+ if stream_duration is not None:
+ candidates.append(stream_duration)
+
+ return max(candidates) if candidates else default
+
+
+def get_dimensions(video_path: str) -> tuple[int, int]:
+ """Return the (width, height) of the first video stream."""
+ info = get_video_info(video_path)
+ for stream in info.get("streams", []):
+ if stream.get("codec_type") == "video":
+ return int(stream["width"]), int(stream["height"])
+ raise ValueError(f"No video stream found in {video_path}")
diff --git a/backend/services/video_processor.py b/backend/services/video_processor.py
index 878ee2b..95d512e 100644
--- a/backend/services/video_processor.py
+++ b/backend/services/video_processor.py
@@ -13,117 +13,20 @@ from typing import Optional
from services.encoder import get_video_encode_flags
from utils.proc import run as proc_run, ProcError
+from services import media_probe
+from services.media_probe import (
+ CPU_FLAGS,
+ FFMPEG_TIMEOUT as _FFMPEG_TIMEOUT,
+ QUALITY_PRESETS,
+ get_dimensions,
+ get_video_info,
+ get_media_duration_seconds as _get_media_duration_seconds,
+ has_audio_stream as _has_audio_stream,
+ parse_duration_seconds as _parse_duration_seconds,
+ run_ffmpeg_with_fallback as _run_ffmpeg_with_fallback,
+)
import sys
-# Max time for any single FFmpeg call (seconds). Prevents infinite hangs.
-_FFMPEG_TIMEOUT = 300
-
-# Quality presets: name → (crf, preset)
-# Lower CRF = higher quality = larger file. 18 is visually lossless.
-QUALITY_PRESETS = {
- "low": {"crf": "28", "preset": "fast"}, # ~2-4 MB/min, fast encode
- "medium": {"crf": "23", "preset": "medium"}, # ~4-8 MB/min, balanced
- "high": {"crf": "18", "preset": "slow"}, # ~8-15 MB/min, great quality
- "max": {"crf": "14", "preset": "slower"}, # ~15-30 MB/min, near-lossless
-}
-
-_quality = os.environ.get("PODCLI_QUALITY", "high")
-_qp = QUALITY_PRESETS.get(_quality, QUALITY_PRESETS["high"])
-CPU_FLAGS = ["-c:v", "libx264", "-crf", _qp["crf"], "-preset", _qp["preset"], "-profile:v", "high"]
-
-
-def _run_ffmpeg_with_fallback(cmd_parts_before_enc: list, cmd_parts_after_enc: list, output_path: str, label: str = "encode") -> str:
- """
- Run an FFmpeg command with the best encoder. If it fails, retry with libx264.
- cmd = cmd_parts_before_enc + enc_flags + cmd_parts_after_enc + [output_path]
- """
- enc_flags = get_video_encode_flags()
- cmd = cmd_parts_before_enc + enc_flags + cmd_parts_after_enc + [output_path]
-
- result = proc_run(cmd, timeout=_FFMPEG_TIMEOUT, check=False)
- if result.returncode == 0:
- return output_path
-
- # If not already CPU, retry with libx264
- if enc_flags != CPU_FLAGS:
- print(f"Warning: HW encoder failed for {label}, falling back to libx264", file=sys.stderr)
- cmd_fallback = cmd_parts_before_enc + CPU_FLAGS + cmd_parts_after_enc + [output_path]
- result2 = proc_run(cmd_fallback, timeout=_FFMPEG_TIMEOUT, check=False)
- if result2.returncode == 0:
- return output_path
- raise RuntimeError(f"FFmpeg {label} failed (both HW and CPU): {result2.stderr[-500:]}")
-
- raise RuntimeError(f"FFmpeg {label} failed: {result.stderr[-500:]}")
-
-
-def _has_audio_stream(video_path: str) -> bool:
- """Check if a video file contains an audio stream."""
- try:
- info = get_video_info(video_path)
- return any(s.get("codec_type") == "audio" for s in info.get("streams", []))
- except Exception:
- return True # Assume yes if we can't check
-
-
-def get_video_info(video_path: str) -> dict:
- """Get video metadata via ffprobe."""
- cmd = [
- "ffprobe",
- "-v", "quiet",
- "-print_format", "json",
- "-show_format",
- "-show_streams",
- video_path,
- ]
- result = proc_run(cmd, timeout=_FFMPEG_TIMEOUT, check=False)
- if result.returncode != 0:
- raise RuntimeError(f"ffprobe failed: {result.stderr}")
- return json.loads(result.stdout)
-
-
-def _parse_duration_seconds(value: object) -> Optional[float]:
- """Parse a duration value and reject invalid/non-finite numbers."""
- try:
- parsed = float(str(value).strip())
- except Exception:
- return None
- if not math.isfinite(parsed) or parsed <= 0:
- return None
- return parsed
-
-
-def _get_media_duration_seconds(video_path: str, default: float = 0.0) -> float:
- """
- Best-effort media duration in seconds.
- Prefers max valid duration from format/streams, else returns default.
- """
- try:
- info = get_video_info(video_path)
- except Exception:
- return default
-
- candidates: list[float] = []
- fmt = info.get("format", {})
- fmt_duration = _parse_duration_seconds(fmt.get("duration"))
- if fmt_duration is not None:
- candidates.append(fmt_duration)
-
- for stream in info.get("streams", []):
- stream_duration = _parse_duration_seconds(stream.get("duration"))
- if stream_duration is not None:
- candidates.append(stream_duration)
-
- return max(candidates) if candidates else default
-
-
-def get_dimensions(video_path: str) -> tuple[int, int]:
- """Get video width and height."""
- info = get_video_info(video_path)
- for stream in info.get("streams", []):
- if stream.get("codec_type") == "video":
- return int(stream["width"]), int(stream["height"])
- raise ValueError(f"No video stream found in {video_path}")
-
def cut_segment(
input_path: str,
diff --git a/tests/test_media_probe.py b/tests/test_media_probe.py
new file mode 100644
index 0000000..0549291
--- /dev/null
+++ b/tests/test_media_probe.py
@@ -0,0 +1,149 @@
+"""Tests for backend.services.media_probe — extracted ffmpeg helpers."""
+
+import os
+import sys
+import unittest
+from unittest import mock
+
+ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
+BACKEND_ROOT = os.path.join(ROOT, "backend")
+if BACKEND_ROOT not in sys.path:
+ sys.path.insert(0, BACKEND_ROOT)
+
+from services import media_probe
+
+
+class ParseDurationSecondsTests(unittest.TestCase):
+ def test_valid_numeric_string(self):
+ self.assertEqual(media_probe.parse_duration_seconds("12.5"), 12.5)
+
+ def test_valid_float(self):
+ self.assertEqual(media_probe.parse_duration_seconds(30.0), 30.0)
+
+ def test_rejects_nan(self):
+ self.assertIsNone(media_probe.parse_duration_seconds("nan"))
+ self.assertIsNone(media_probe.parse_duration_seconds(float("nan")))
+
+ def test_rejects_infinity(self):
+ self.assertIsNone(media_probe.parse_duration_seconds(float("inf")))
+ self.assertIsNone(media_probe.parse_duration_seconds("inf"))
+
+ def test_rejects_zero_and_negative(self):
+ self.assertIsNone(media_probe.parse_duration_seconds(0))
+ self.assertIsNone(media_probe.parse_duration_seconds(-5))
+
+ def test_rejects_non_parsable(self):
+ self.assertIsNone(media_probe.parse_duration_seconds("N/A"))
+ self.assertIsNone(media_probe.parse_duration_seconds(None))
+ self.assertIsNone(media_probe.parse_duration_seconds(""))
+
+
+class GetMediaDurationSecondsTests(unittest.TestCase):
+ def test_uses_format_duration_when_valid(self):
+ fake_info = {"format": {"duration": "42.5"}, "streams": []}
+ with mock.patch.object(media_probe, "get_video_info", return_value=fake_info):
+ self.assertEqual(
+ media_probe.get_media_duration_seconds("/fake.mp4"), 42.5
+ )
+
+ def test_prefers_max_of_format_and_streams(self):
+ fake_info = {
+ "format": {"duration": "30.0"},
+ "streams": [
+ {"duration": "29.5"},
+ {"duration": "31.0"}, # slightly longer stream
+ ],
+ }
+ with mock.patch.object(media_probe, "get_video_info", return_value=fake_info):
+ self.assertEqual(
+ media_probe.get_media_duration_seconds("/fake.mp4"), 31.0
+ )
+
+ def test_falls_back_to_default_when_all_invalid(self):
+ fake_info = {
+ "format": {"duration": "N/A"},
+ "streams": [{"duration": "N/A"}],
+ }
+ with mock.patch.object(media_probe, "get_video_info", return_value=fake_info):
+ self.assertEqual(
+ media_probe.get_media_duration_seconds("/fake.mp4", default=99.0),
+ 99.0,
+ )
+
+ def test_falls_back_when_probe_raises(self):
+ with mock.patch.object(
+ media_probe, "get_video_info", side_effect=RuntimeError("ffprobe failed")
+ ):
+ self.assertEqual(
+ media_probe.get_media_duration_seconds("/fake.mp4", default=7.0),
+ 7.0,
+ )
+
+
+class HasAudioStreamTests(unittest.TestCase):
+ def test_detects_audio(self):
+ info = {"streams": [{"codec_type": "video"}, {"codec_type": "audio"}]}
+ with mock.patch.object(media_probe, "get_video_info", return_value=info):
+ self.assertTrue(media_probe.has_audio_stream("/fake.mp4"))
+
+ def test_detects_no_audio(self):
+ info = {"streams": [{"codec_type": "video"}]}
+ with mock.patch.object(media_probe, "get_video_info", return_value=info):
+ self.assertFalse(media_probe.has_audio_stream("/fake.mp4"))
+
+ def test_assumes_yes_on_probe_failure(self):
+ # Defensive default — pipeline should still try audio filters
+ with mock.patch.object(
+ media_probe, "get_video_info", side_effect=RuntimeError("boom")
+ ):
+ self.assertTrue(media_probe.has_audio_stream("/fake.mp4"))
+
+
+class GetDimensionsTests(unittest.TestCase):
+ def test_returns_first_video_stream_dimensions(self):
+ info = {
+ "streams": [
+ {"codec_type": "audio"},
+ {"codec_type": "video", "width": 1920, "height": 1080},
+ ]
+ }
+ with mock.patch.object(media_probe, "get_video_info", return_value=info):
+ self.assertEqual(
+ media_probe.get_dimensions("/fake.mp4"), (1920, 1080)
+ )
+
+ def test_raises_when_no_video_stream(self):
+ info = {"streams": [{"codec_type": "audio"}]}
+ with mock.patch.object(media_probe, "get_video_info", return_value=info):
+ with self.assertRaises(ValueError):
+ media_probe.get_dimensions("/fake.mp4")
+
+
+class VideoProcessorReExportsTests(unittest.TestCase):
+ """Regression guard: video_processor must continue to expose the
+ helpers under their original names so older imports and test mocks
+ don't break."""
+
+ def test_video_processor_reexports_helpers(self):
+ from services import video_processor as vp
+ self.assertIs(vp.get_video_info, media_probe.get_video_info)
+ self.assertIs(vp.get_dimensions, media_probe.get_dimensions)
+ self.assertIs(vp._has_audio_stream, media_probe.has_audio_stream)
+ self.assertIs(
+ vp._parse_duration_seconds, media_probe.parse_duration_seconds
+ )
+ self.assertIs(
+ vp._get_media_duration_seconds, media_probe.get_media_duration_seconds
+ )
+ self.assertIs(
+ vp._run_ffmpeg_with_fallback, media_probe.run_ffmpeg_with_fallback
+ )
+
+ def test_video_processor_still_exposes_cpu_flags_and_timeout(self):
+ from services import video_processor as vp
+ self.assertEqual(vp.CPU_FLAGS, media_probe.CPU_FLAGS)
+ self.assertEqual(vp._FFMPEG_TIMEOUT, media_probe.FFMPEG_TIMEOUT)
+
+
+if __name__ == "__main__":
+ unittest.main()