Skip to content

Local video editor for coding agents: 42 FFmpeg tools with a machine-readable contract and an MCP server, for Claude Code, Cursor and Codex. Cut, captions, reframe, loudness, platform exports. No cloud, no API keys.

Fix a silent false-PASS in check.py, an infinite loop in multicam.py, and a silent output collision in batch.py (#117)

Shogo Kajiyamab37ee2d7869d
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 7610974..3f80998 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -6,6 +6,36 @@
(nothing yet)
+## 0.16.4 — fix a silent false-PASS in check.py, an infinite loop in multicam.py, and a silent output collision in batch.py
+
+Three unrelated bugs found in a wider audit past `caption.py`:
+
+- `check.py`: `measure_loudness()` returns `{}` when ffmpeg's `loudnorm` JSON
+ doesn't parse out of stderr (unexpected/garbled output). `main()` only
+ appended the `loudness`/`true peak` rows when that measurement succeeded,
+ so a failed measurement made those rows vanish entirely -- not FAIL, not
+ WARN, just absent -- while `check.py` still reported an overall PASS for
+ a platform with a loudness requirement it never actually verified. Fixed
+ by reporting `WARN` (could not measure) instead of dropping the rows: a
+ silent false PASS is worse than visible noise on a compliance tool.
+- `multicam.py`: `--auto` alternates cameras with
+ `while t < ref_dur: ... t += args.auto`, gated by `elif args.auto:` --
+ which is only false for exactly `0`, so a negative value passed the
+ check and entered the loop with `t` decreasing every iteration, hanging
+ forever instead of erroring on invalid input. Fixed by refusing
+ `--auto <= 0` up front.
+- `batch.py`: a recipe's default output extension falls back to each
+ source's own extension, so files that only differ by extension don't
+ collide -- but a recipe with a fixed `"ext"` (e.g. converting a folder
+ of mixed `.mp4`/`.mov` masters to one format) makes two sources with the
+ same stem (`clip.mp4` and `clip.mov`) resolve to the identical final
+ path (`clip_out.mp4`). `process()` had no collision detection, so the
+ file processed later in sorted order silently overwrote the earlier
+ one's finished output, with the cache still recording both entries as
+ `"ok": true`. Fixed with a pre-flight collision check across the whole
+ batch, refusing before any file is processed rather than after data is
+ already lost.
+
## 0.16.3 — fix two more caption.py delimiter bugs: ASS override injection, SRT blank-line split
Following on from 0.16.2's `--font` fix, a closer look at `caption.py` found
diff --git a/docs/contract.md b/docs/contract.md
index 9d96577..3cc8f1c 100644
--- a/docs/contract.md
+++ b/docs/contract.md
@@ -21,7 +21,7 @@ The contract is derived from the code that runs, not maintained beside it:
| Field | Meaning | Changes when |
|---|---|---|
| `contract_version` | shape of this document (`1.0`) | a key is renamed, removed or changes meaning |
-| `skill.version` | the npm / package.json version (`0.16.3`) | any release |
+| `skill.version` | the npm / package.json version (`0.16.4`) | any release |
A release that adds a tool or a flag keeps `contract_version`; a breaking change to the
ToolSpec shape bumps it. Consumers pin on `contract_version` and read `skill.version`
@@ -39,7 +39,7 @@ drifting silently.
```json
{
"contract_version": "1.0",
- "skill": {"id": "ffmpeg-skill", "version": "0.16.3", "execution_mode": "local", "kind": "execution",
+ "skill": {"id": "ffmpeg-skill", "version": "0.16.4", "execution_mode": "local", "kind": "execution",
"entrypoints": {"cli": "...", "mcp": "...", "contract": "...", "doctor": "..."},
"not_provided": ["AI reasoning", "decisions", "production plans", "project IR", "approvals", "network access", "transcription engine"]},
"requirements": {"python": ">=3.9 (standard library only)", "ffmpeg": ">=5.0", "ffprobe": ">=5.0"},
diff --git a/package.json b/package.json
index fbf6379..cc72e69 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "ffmpeg-skill",
- "version": "0.16.3",
+ "version": "0.16.4",
"description": "Agent Skill that gives coding agents (Claude Code, Cursor, Codex) a local video editor: 40 FFmpeg tools with a machine-readable contract, contract-derived MCP server, FFmpeg capability detection, probe-first / verify-last workflow. Cut, join, silence removal, fit, captions and karaoke, overlays, motion graphics, HDR to SDR, LUTs, audio clean-up and typed dynamics, sync with drift correction, multicam, loudness, delivery checks, project rendering, batch. No API keys, no cloud, no dependencies.",
"keywords": [
"ffmpeg",
diff --git a/scripts/batch.py b/scripts/batch.py
index b196ce7..a8432a2 100755
--- a/scripts/batch.py
+++ b/scripts/batch.py
@@ -68,10 +68,20 @@ def run_step(argv: List[str]) -> bool:
return True
-def process(src: Path, recipe: Dict[str, Any], outdir: Path, work: Path) -> Dict[str, Any]:
+def final_path(src: Path, recipe: Dict[str, Any], outdir: Path) -> Path:
suffix = recipe.get("suffix", "_out")
+ # By default final_ext falls back to each source's OWN extension, so files that only differ
+ # by extension don't collide -- but a recipe that fixes "ext" (e.g. converting a folder of
+ # mixed .mp4/.mov masters to one format) makes every source with the same stem land on the
+ # same final path, e.g. clip.mp4 and clip.mov both -> clip_out.mp4. process() has no collision
+ # detection of its own; see one_pass()'s pre-flight check, which uses this same computation
+ # to catch that before any file is actually processed (and the earlier one silently clobbered).
final_ext = recipe.get("ext") or src.suffix.lstrip(".") or "mp4"
- final = outdir / f"{src.stem}{suffix}.{final_ext}"
+ return outdir / f"{src.stem}{suffix}.{final_ext}"
+
+
+def process(src: Path, recipe: Dict[str, Any], outdir: Path, work: Path) -> Dict[str, Any]:
+ final = final_path(src, recipe, outdir)
t0 = time.time()
if recipe.get("project"):
proj = json.loads(Path(recipe["project"]).read_text(encoding="utf-8"))
@@ -140,6 +150,18 @@ def main() -> int:
def one_pass() -> List[Dict[str, Any]]:
results = []
files = sorted(p for p in folder.glob(glob) if p.is_file() and p.suffix.lower() in MEDIA_EXT and outdir not in p.parents)
+ # Two different sources can compute the same final path (most often a fixed recipe "ext"
+ # collapsing e.g. clip.mp4 and clip.mov to the same clip_out.mp4) -- catch that before
+ # processing anything, rather than letting the later one silently overwrite the earlier
+ # one's finished output with the cache still recording both as "ok".
+ by_final: Dict[Path, List[Path]] = {}
+ for src in files:
+ by_final.setdefault(final_path(src, recipe, outdir), []).append(src)
+ collisions = {dst: srcs for dst, srcs in by_final.items() if len(srcs) > 1}
+ if collisions:
+ detail = "; ".join(f"{dst.name} <- {', '.join(s.name for s in srcs)}" for dst, srcs in collisions.items())
+ die(f"{len(collisions)} output filename collision(s) in this batch -- rename the sources, "
+ f"or add a distinguishing \"suffix\"/\"ext\" per run, or split into separate globs: {detail}")
for src in files:
key = f"{file_key(src)}:{rkey}"
hit = cache.get(key)
diff --git a/scripts/check.py b/scripts/check.py
index 7c5bf6a..324bb70 100755
--- a/scripts/check.py
+++ b/scripts/check.py
@@ -162,6 +162,14 @@ def main() -> int:
row("loudness", "PASS" if diff <= spec["lufs_tol"] else "FAIL", f"{lm['lufs']:.1f} LUFS", f"{spec['lufs']:g} ± {spec['lufs_tol']:g} LUFS", f"loudness.py -I {spec['lufs']:g} for speech or music; leave ambience/near-silence (<= -40 LUFS) alone and say so",
reason="the platform will auto-normalise it to its own target anyway, which can pump or duck the mix in ways you did not choose")
row("true peak", "PASS" if lm["tp"] <= spec["tp"] + 0.05 else "FAIL", f"{lm['tp']:.1f} dBTP", f"<= {spec['tp']:g} dBTP", f"loudness.py --tp {spec['tp']:g}")
+ else:
+ # ffmpeg's loudnorm JSON didn't parse out of stderr (unexpected/garbled output).
+ # Dropping the loudness/true-peak rows silently here would report an overall PASS
+ # for a platform that has a loudness requirement, without ever having checked it --
+ # a false PASS is worse than noise. WARN so the gap is visible in the report.
+ row("loudness", "WARN", "could not measure", f"{spec['lufs']:g} ± {spec['lufs_tol']:g} LUFS", "re-run check.py, or verify loudness manually",
+ reason="ffmpeg's loudness measurement didn't produce a readable result -- this was not actually checked")
+ row("true peak", "WARN", "could not measure", f"<= {spec['tp']:g} dBTP", "re-run check.py, or verify true peak manually")
elif args.platform in ("podcast",):
row("audio", "FAIL", "none", "audio stream", "audio.py --replace")
else:
diff --git a/scripts/multicam.py b/scripts/multicam.py
index 9080009..fd471a6 100755
--- a/scripts/multicam.py
+++ b/scripts/multicam.py
@@ -134,6 +134,8 @@ def main() -> int:
if args.switch:
cuts = parse_switch(args.switch, n)
elif args.auto:
+ if args.auto <= 0:
+ die(f"--auto must be a positive number of seconds, got {args.auto:g}")
cams = [i for i, m in enumerate(metas) if m.get("video")]
cuts, t, k = [], 0.0, 0
while t < ref_dur:
diff --git a/tests/test_all.py b/tests/test_all.py
index e17dd4f..eab3d3b 100644
--- a/tests/test_all.py
+++ b/tests/test_all.py
@@ -1577,6 +1577,13 @@ class FFmpegSkillTests(unittest.TestCase):
self.assertClose(probe(str(auto))["duration"], 12.0, 0.2)
script("multicam.py", self.src, camB, "--switch", "0-3:5", expect_fail=True)
+ def test_multicam_negative_auto_interval_refused_not_infinite_loop(self):
+ """--auto builds cuts with `while t < ref_dur: ... t += args.auto` -- `elif args.auto:` is
+ only false for exactly 0, so a negative value used to pass that check and enter the loop
+ with t decreasing every iteration, meaning t < ref_dur never becomes false: the process
+ hangs forever instead of erroring on invalid input. Must be refused up front instead."""
+ script("multicam.py", self.src, self.src, "--auto", "-1", "--fast", "-o", OUT / "mc_auto_neg.mp4", expect_fail=True)
+
def test_multicam_warns_on_a_camera_with_no_shared_audio_event(self):
"""A camera whose audio has nothing in common with the reference must not align silently."""
unrelated = OUT / "camC_unrelated.mp4"
@@ -1841,6 +1848,30 @@ class FFmpegSkillTests(unittest.TestCase):
data = json.loads(script("check.py", self.src, "--platform", "custom", "--max-duration", "5", "--no-loudness", "--json", expect_fail=True).stdout)
self.assertEqual({r["check"]: r["status"] for r in data["checks"]}["duration"], "FAIL")
+ def test_check_unmeasurable_loudness_warns_instead_of_silently_passing(self):
+ """measure_loudness() returns {} when ffmpeg's loudnorm JSON doesn't parse out of stderr
+ (malformed/unexpected output). main() used to gate the loudness/true-peak rows entirely on
+ `if lm:`, so a measurement failure meant those rows were never appended at all -- not FAIL,
+ not WARN, just absent -- and check.py would still report an overall PASS for a platform
+ with a loudness requirement it never actually verified. A silent false PASS is worse than a
+ crash for a compliance tool. Verify a forced measurement failure surfaces as WARN rows,
+ not a vanished check."""
+ from unittest.mock import patch
+ sys.path.insert(0, str(SCRIPTS))
+ import check
+ with patch.object(check, "measure_loudness", return_value={}):
+ buf = __import__("io").StringIO()
+ import contextlib
+ with contextlib.redirect_stdout(buf):
+ sys.argv = ["check.py", str(self.src), "--platform", "youtube", "--json"]
+ check.main()
+ data = json.loads(buf.getvalue())
+ statuses = {r["check"]: r["status"] for r in data["checks"]}
+ self.assertIn("loudness", statuses, "an unmeasurable loudness check must still appear in the report")
+ self.assertIn("true peak", statuses)
+ self.assertEqual(statuses["loudness"], "WARN")
+ self.assertEqual(statuses["true peak"], "WARN")
+
def test_scenes_and_highlights(self):
src = OUT / "scenes_src.mp4"
sh("ffmpeg", "-y", "-hide_banner", "-loglevel", "error",
@@ -2066,6 +2097,27 @@ class FFmpegSkillTests(unittest.TestCase):
self.assertEqual(data["processed"], 1)
self.assertClose(probe(data["results"][0]["output"])["duration"], 3.0, 0.3)
+ def test_batch_refuses_a_fixed_ext_recipe_that_collapses_two_sources_to_one_output(self):
+ """final_path() falls back to each source's OWN extension by default, so files that only
+ differ by extension don't collide -- but a recipe with a fixed "ext" (e.g. converting a
+ folder of mixed .mp4/.mov masters to one format) makes two sources with the same stem
+ (clip.mp4 and clip.mov) resolve to the identical final path (clip_out.mp4). process() had
+ no collision detection: the file processed later in sorted() order used to silently
+ overwrite the earlier one's finished output, with the cache still recording both entries
+ as ok. Verify this is now refused up front, before either file is processed, rather than
+ one silently clobbering the other."""
+ folder = OUT / "batch_collision_in"
+ folder.mkdir(exist_ok=True)
+ for name in ("clip.mp4", "clip.mov"):
+ (folder / name).write_bytes(Path(self.src).read_bytes())
+ recipe = folder / "collide.json"
+ recipe.write_text(json.dumps({"ext": "mp4", "steps": [["export.py", "{in}", "--preset", "x", "-o", "{out}"]]}))
+ proc = script("batch.py", folder, "--recipe", recipe, "--fast", expect_fail=True)
+ self.assertIn("collision", proc.stderr)
+ self.assertIn("clip.mp4", proc.stderr)
+ self.assertIn("clip.mov", proc.stderr)
+ self.assertFalse((folder / "out" / "clip_out.mp4").exists(), "nothing should be written once a collision is detected")
+
def test_transcribe_without_engine_explains(self):
import shutil
if shutil.which("whisper-cli") or shutil.which("whisper"):