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: fifth review -- render self-overwrite, fit trim subtitles, caption transcribe under dry-run, and nine smaller items (#194)

claude[bot]42b29dad3bf0
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 3f87d17..45c3066 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -4,7 +4,7 @@
## Unreleased
-(nothing yet)
+- Fifth review. `render.py` refused nothing when `output` named one of its own clip sources and overwrote the source (now `kind: input`); `fit.py --method trim` stream-copied a subtitle track through the `-ss` cut, so the file came out at twice the requested length with cues from the wrong part (dropped and reported like `pad --start`); `caption.py --transcribe` ran the speech engine and wrote the `.srt` under `--dry-run`, and put that sidecar next to the *input*, silently replacing a hand-written one (now planned only, written next to the output, with a warning before replacing); `color.py --correct --dry-run` ran two real signalstats passes; `multicam.py --audio N` out of range was a traceback; `check.py`'s fix for a broadcast codec failure named a preset that does not exist (`prores` now); `sequence.py` had `import re` above its shebang, so its docstring never reached `--help` or the contract; `batch.py --watch` could not be stopped with Ctrl-C without an "interrupted, nothing written" exit; `render.py --dry-run` said "copied"; `join.py`'s audio path probed its output as an input; `references/scripts.md` described karaoke timing as even when the default follows speech energy (`--karaoke-timing`).
## 1.5.0
diff --git a/references/scripts.md b/references/scripts.md
index c631d54..8a67d81 100644
--- a/references/scripts.md
+++ b/references/scripts.md
@@ -504,8 +504,9 @@ not — a timecode-shaped cue with no fps available is refused rather than misre
Lines without a time run for `--auto-seconds` (3 s) after the previous cue. `|` is a line break.
`--animate`/`--karaoke` generate a styled ASS (PlayRes = video size) from the
SRT/text cues: `pop` is the short-form "bouncy" entrance, `--karaoke` fills each
-word from `--color` to `--highlight-color` evenly across the cue (word timing
-is distributed, not transcribed). The ASS is kept next to the output so the
+word from `--color` to `--highlight-color` across the cue; `--karaoke-timing
+energy` (default) follows the speech loudness in the audio, `even` splits the
+cue equally (word timing is derived, not transcribed). The ASS is kept next to the
user can hand-tune timings and re-run with `--ass`.
`--mode burn` (default) renders subtitles into the picture and always
re-encodes both streams. `--mode mux` copies video and audio untouched and
diff --git a/scripts/batch.py b/scripts/batch.py
index d037def..2233d9e 100755
--- a/scripts/batch.py
+++ b/scripts/batch.py
@@ -224,12 +224,20 @@ def main() -> int:
results = one_pass()
if args.watch:
info(f"watching {folder} every {args.watch:g}s (Ctrl-C to stop)")
+ # the shared SIGINT handler (install_signal_handlers) exits 130 with "nothing was written",
+ # which is wrong for a watch that already processed files: while idle between passes,
+ # let Ctrl-C be a plain KeyboardInterrupt so the summary below prints (review 5)
+ import signal
try:
while True:
- time.sleep(args.watch)
+ previous = signal.signal(signal.SIGINT, signal.default_int_handler)
+ try:
+ time.sleep(args.watch)
+ finally:
+ signal.signal(signal.SIGINT, previous)
results = one_pass()
except KeyboardInterrupt:
- pass
+ info("watch stopped")
done = sum(1 for r in results if r["ok"])
info(f"{done}/{len(results)} processed, {sum(1 for r in results if r.get('cached'))} from cache")
if not args.json:
diff --git a/scripts/caption.py b/scripts/caption.py
index af28996..cac1b23 100755
--- a/scripts/caption.py
+++ b/scripts/caption.py
@@ -487,9 +487,17 @@ def main() -> int:
if args.transcribe:
if not args.input:
die("--transcribe needs the input video")
- srt_path = args.write_srt or os.path.splitext(args.input)[0] + ".srt"
- cues = transcribe(args.input, srt_path, args.language, args.model, args.audio_stream)
- info(f"wrote {srt_path} ({len(cues)} cues)")
+ # the sidecar goes next to the output like the --text one, not into the source folder
+ # where it silently replaced a hand-written <input>.srt (review 5)
+ srt_path = args.write_srt or os.path.splitext(args.output or default_output(args.input, "captioned"))[0] + ".srt"
+ if STATE.dry_run:
+ cues = []
+ info(f"[dry-run] would transcribe {args.input} and write {srt_path}")
+ else:
+ if os.path.exists(srt_path) and not getattr(args, "overwrite", False):
+ info(f"warning: {srt_path} already exists and will be replaced by the transcript (pass --overwrite to confirm)")
+ cues = transcribe(args.input, srt_path, args.language, args.model, args.audio_stream)
+ info(f"wrote {srt_path} ({len(cues)} cues)")
args.text = None
if args.text:
cues = parse_text_cues(args.text, args.auto_seconds, args.gap, fps_for_tc)
@@ -515,7 +523,7 @@ def main() -> int:
output = args.output or default_output(args.input, "captioned")
if args.mode == "mux":
- if not srt_path or (not os.path.exists(srt_path) and not (STATE.dry_run and args.text)):
+ if not srt_path or (not os.path.exists(srt_path) and not (STATE.dry_run and (args.text or args.transcribe))):
die(f"SRT file not found: {srt_path}")
codec = mux_subtitle_codec(output)
# Keep any subtitle track(s) the input already has (e.g. chaining --mode mux once per
@@ -543,7 +551,7 @@ def main() -> int:
return 0
if (args.animate != "none" or args.karaoke) and not args.ass:
- cues_for_ass = cues if args.text else parse_srt(srt_path)
+ cues_for_ass = cues if (args.text or args.transcribe) else parse_srt(srt_path)
ass_path = args.write_ass or os.path.splitext(output)[0] + ".ass"
w, h = meta["video"]["width"], meta["video"]["height"]
if meta["video"].get("rotation") in (90, -90, 270, -270):
@@ -563,7 +571,7 @@ def main() -> int:
if args.fonts_dir:
vf += f":fontsdir={escape_filter_path(args.fonts_dir)}"
else:
- if not srt_path or (not os.path.exists(srt_path) and not (STATE.dry_run and args.text)):
+ if not srt_path or (not os.path.exists(srt_path) and not (STATE.dry_run and (args.text or args.transcribe))):
die(f"SRT file not found: {srt_path}")
style = [
f"FontName={ass_font_name(args.font)}",
diff --git a/scripts/check.py b/scripts/check.py
index 891a487..8c435b7 100755
--- a/scripts/check.py
+++ b/scripts/check.py
@@ -127,7 +127,7 @@ def main() -> int:
row("fps", "PASS" if fps <= spec["fps_max"] + 0.01 else "FAIL", f"{fps:g}", f"<= {spec['fps_max']}", "fit.py --fps 30 (drops half the frames of 60 fps motion; fine for talking heads, visible on sports/gaming)")
row("vfr", "PASS" if not v.get("variable_frame_rate_suspected") else "WARN", "variable" if v.get("variable_frame_rate_suspected") else "constant", "constant", "fit.py --fps N (any re-encode conforms it)")
if spec["codecs"]:
- row("video codec", "PASS" if v.get("codec") in spec["codecs"] else "FAIL", v.get("codec"), "/".join(spec["codecs"]), "export.py --preset " + args.platform.replace("shorts", "reels").replace("tiktok", "reels").replace("linkedin", "youtube"),
+ row("video codec", "PASS" if v.get("codec") in spec["codecs"] else "FAIL", v.get("codec"), "/".join(spec["codecs"]), "export.py --preset " + args.platform.replace("shorts", "reels").replace("tiktok", "reels").replace("linkedin", "youtube").replace("broadcast", "prores"),
reason="the platform's player may refuse to decode this codec at all, not just look worse")
pf = v.get("pix_fmt") or ""
if args.platform in ("reels", "tiktok", "x", "linkedin"):
diff --git a/scripts/color.py b/scripts/color.py
index 39226a4..8bce9e0 100755
--- a/scripts/color.py
+++ b/scripts/color.py
@@ -22,7 +22,7 @@ import os
import sys
from typing import List
-from _common import add_common, analyze_levels, apply_common, emit, aac_args, cfr_args, default_output, die, escape_filter_path, ffmpeg_base, info, probe, run, run_keeping_subtitles, x264_args, X264_PRESETS, fmt_secs
+from _common import STATE, add_common, analyze_levels, apply_common, emit, aac_args, cfr_args, default_output, die, escape_filter_path, ffmpeg_base, info, probe, run, run_keeping_subtitles, x264_args, X264_PRESETS, fmt_secs
TONEMAPS = ["hable", "mobius", "reinhard", "bt2390", "clip", "linear", "gamma"]
@@ -293,7 +293,7 @@ def main() -> int:
tag = "correct"
# OBSERVED technical measurements (signalstats: luma / saturation distribution), never a
# "looks better" judgement -- the same primitive probe.py --analyze uses for Log detection.
- measurements = {"input": analyze_levels(args.input)}
+ measurements = None if STATE.dry_run else {"input": analyze_levels(args.input)}
else:
if v.get("hdr") and not args.force:
die(f"{args.input} is HDR ({v.get('hdr_format')}); a LUT made for SDR applied to PQ/HLG pixels gives a wrong picture "
diff --git a/scripts/fit.py b/scripts/fit.py
index bcaf92b..d50a973 100755
--- a/scripts/fit.py
+++ b/scripts/fit.py
@@ -239,12 +239,13 @@ def main() -> int:
else:
cmd += ["-an"]
cmd += post
- if abs(factor - 1.0) > 1e-4:
+ if abs(factor - 1.0) > 1e-4 or "-ss" in pre_input:
# A subtitle/data stream stream-copied by run_keeping_subtitles keeps the source's
# original timestamps; --method speed retimes video (setpts) and audio (atempo) but has
# no equivalent way to retime a copied subtitle track, so it would desync from the
# now-faster/slower picture. Drop them here rather than ship a captions track that lies
- # about when a line is spoken.
+ # about when a line is spoken. --method trim's -ss moves the timeline the same way: a copied
+ # track kept its cues at the source's times and doubled the output's length (review 5).
run(cmd + [output])
dropped_streams = bool(meta.get("subtitle_streams") or meta.get("data_streams"))
else:
diff --git a/scripts/join.py b/scripts/join.py
index af92d6f..635f445 100755
--- a/scripts/join.py
+++ b/scripts/join.py
@@ -68,7 +68,7 @@ def join_audio(args: argparse.Namespace, metas: List[dict]) -> int:
cmd += ["-filter_complex", ";".join(parts), "-map", "[aout]", "-vn"] + audio_codec_for(output) + [output]
run(cmd)
expected = sum(durs) - d * (n - 1)
- r = probe(output)
+ r = probe(output, role="output")
a = r.get("audio") or {}
if not STATE.dry_run:
if r.get("video"):
diff --git a/scripts/multicam.py b/scripts/multicam.py
index a89b0f2..4f8cbb6 100755
--- a/scripts/multicam.py
+++ b/scripts/multicam.py
@@ -77,6 +77,8 @@ def main() -> int:
die(f"--analyze-seconds {args.analyze_seconds:g}: the window is decoded into memory; 900 s is the ceiling")
if args.fps is not None and args.fps <= 0:
die(f"--fps must be positive, got {args.fps:g}")
+ if not 0 <= args.audio < len(args.inputs):
+ die(f"--audio {args.audio}: inputs are numbered 0..{len(args.inputs) - 1}")
n = len(args.inputs)
if n < 2:
diff --git a/scripts/render.py b/scripts/render.py
index f804595..5b9114a 100755
--- a/scripts/render.py
+++ b/scripts/render.py
@@ -55,7 +55,7 @@ import sys
from pathlib import Path
from typing import Any, Dict, List
-from _common import STATE, add_common, apply_common, child_args, die, emit, info, probe, run_tool, place_output
+from _common import STATE, add_common, apply_common, child_args, die, emit, info, probe, run_tool, place_output, refuse_output_is_input
HERE = Path(__file__).resolve().parent
@@ -133,6 +133,8 @@ def main() -> int:
if not clips:
die("project.clips is empty")
output = rel(proj.get("output") or "final.mp4")
+ # the final stage is a copy from the work dir, so run()'s own guard never sees the sources (review 5)
+ refuse_output_is_input(output, *[rel(c.get("src")) for c in clips if c.get("src")])
# The default work dir name comes only from the output path, with no PID or timestamp --
# two concurrent render.py runs targeting the same output (a batch.py "project" recipe
# processing several files in parallel, or simply running render.py twice by mistake) shared
@@ -363,7 +365,7 @@ def main() -> int:
else:
if not STATE.dry_run:
place_output(current, output)
- info(f"copied final stage to {output}")
+ info(("[dry-run] would copy" if STATE.dry_run else "copied") + f" final stage to {output}")
current = output
# ---- check
diff --git a/scripts/sequence.py b/scripts/sequence.py
index 66a5956..98fb36c 100644
--- a/scripts/sequence.py
+++ b/scripts/sequence.py
@@ -1,4 +1,3 @@
-import re
#!/usr/bin/env python3
"""Turn a numbered image sequence into a video.
@@ -16,6 +15,7 @@ Examples:
python3 sequence.py --dir frames --pattern "*.png" --fps 30 --start-number 1
"""
import argparse
+import re
import sys
import tempfile
from pathlib import Path
diff --git a/tests/test_contract.py b/tests/test_contract.py
index b697ba6..874ac5e 100644
--- a/tests/test_contract.py
+++ b/tests/test_contract.py
@@ -1118,6 +1118,9 @@ class ContractTests(unittest.TestCase):
"silence": [self.src, "-o", outdir / "sil.mp4"],
"join": [self.src, self.camb, "-o", outdir / "join.mp4"],
"color": [self.hdr, "--to-sdr", "-o", outdir / "col.mp4"],
+ # review 5: --correct measured with two real signalstats passes and --transcribe ran the engine
+ "color#correct": [self.src, "--correct", "--exposure", "0.2", "-o", outdir / "colc.mp4"],
+ "caption#transcribe": [self.src, "--transcribe", "-o", outdir / "capt.mp4"],
"export": [self.src, "--preset", "x", "-o", outdir / "exp.mp4"],
"scenes": [self.src, "--sheet", outdir / "sc.png", "--edl", outdir / "sc.txt"],
"look": [self.src, "-o", outdir / "look.png"],
@@ -1125,6 +1128,7 @@ class ContractTests(unittest.TestCase):
"cropdetect": [self.src, "--seconds", "1", "--samples", "1"],
}
for name, args in cases.items():
+ name = name.split("#")[0]
spec = self.tools[name]
self.assertTrue(spec["supports_dry_run"], name)
strict = spec["dry_run"]["ffmpeg_execution"] == "none"
@@ -1716,6 +1720,34 @@ class ContractTests(unittest.TestCase):
doc = json.loads(tool("fit", self.src, "--aspect", "1:1", "--dry-run", "-o", self.out("v2_dry.mp4"), "--json", env=env).stdout)
self.assertEqual((doc["result_v2"]["probe"], doc["result_v2"]["output"]), (None, doc["output"]))
+ def test_fifth_review_regressions(self):
+ """Review 5 (2026-09-12): render refuses an output that is one of its clip sources (it
+ overwrote the source and said completed); fit --method trim drops a subtitle track whose
+ cues would sit at the source's times (the output came out double length); multicam
+ --audio out of range is kind input, not an IndexError; check's fix for a broadcast codec
+ failure names a preset that exists; sequence.py has its docstring back."""
+ import shutil
+ src_copy = self.out("r5_src.mp4"); shutil.copy(self.src, src_copy)
+ proj = self.out("r5_proj.json")
+ proj.write_text(json.dumps({"output": str(src_copy), "clips": [{"src": str(src_copy), "in": 0, "out": 1}]}))
+ before = src_copy.stat().st_size
+ proc = tool("render", proj, "--json", "--fast", check=False)
+ self.assertEqual(json.loads(proc.stdout)["error"]["kind"], "input")
+ self.assertEqual(src_copy.stat().st_size, before, "render must not touch its own source")
+ doc = json.loads(tool("fit", self.subbed, "--duration", "2", "--method", "trim", "--from-center", "--fast", "--json", "-o", self.out("r5_trim.mkv")).stdout)
+ self.assertTrue(doc["dropped_non_av_streams"])
+ self.assertAlmostEqual(doc["probe"]["duration"], 2.0, delta=0.15)
+ proc = tool("multicam", self.src, self.camb, "--audio", "5", "--switch", "0-1:0", "--dry-run", "--json", "-o", self.out("r5_mc.mp4"), check=False)
+ self.assertEqual(json.loads(proc.stdout)["error"]["kind"], "input")
+ m4 = self.out("r5_mpeg4.mp4")
+ ffmpeg("-i", self.src, "-t", "1", "-c:v", "mpeg4", "-c:a", "copy", m4)
+ doc = json.loads(tool("check", m4, "--platform", "broadcast", "--no-loudness", "--json", check=False).stdout)
+ fix = next(c["fix"] for c in doc["checks"] if c["check"] == "video codec")
+ self.assertIn("--preset prores", fix)
+ self.assertTrue(self.tools["sequence"]["description"], "sequence.py's docstring must reach the contract")
+ with open(ROOT / "scripts" / "sequence.py", encoding="utf-8") as f:
+ self.assertTrue(f.readline().startswith("#!"))
+
def test_settled_policies_exit_code_and_subtitle_tracks(self):
"""docs/design-decisions.md: an ffmpeg failure exits 1 whatever ffmpeg returned (the raw code
travels as ffmpeg_returncode); tools that leave the timeline alone keep a subtitle track