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: dry-run plans rest on real measurements; shared flags reach every child; guarded cue reads; cropdetect skips an undecodable window (#179)

Shogo Kajiyama8d79f2558bf9
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 5878e2f..ce74473 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -4,7 +4,10 @@
## Unreleased
-(nothing yet)
+- `--dry-run` plans rest on real measurements: `silence.py`, `loudness.py`, `check.py` and `stabilize.py` run their measurement passes (silencedetect, loudnorm pass 1, vidstabdetect) under `--dry-run` and skip only the write. Before, a dry run reported 0 silences, a made-up -20 LUFS, an unmeasured loudness row and no stabilisation pass. The contract lists them as `analysis_only`.
+- `render.py`'s check stage and `report.py`'s look/loudness/check children receive the shared flags (`--timeout`, `--overwrite`, `--fast`, `--dry-run`); `render.py`'s failure document carries the output probe.
+- `cropdetect.py` skips a sampled window ffmpeg cannot decode and measures the rest; only when every window fails is it `kind: ffmpeg`.
+- `caption.py --text`/`--srt` and `batch.py`'s `recipe.project` read through the guarded reader: a missing, directory or non-UTF-8 file is a `kind: input` refusal naming the flag.
## 1.4.6
diff --git a/references/scripts.md b/references/scripts.md
index cc585c9..e3feb09 100644
--- a/references/scripts.md
+++ b/references/scripts.md
@@ -1,6 +1,6 @@
# Script reference
-Every script prints the same information with `--help`; this file exists so the agent can read several at once. All scripts accept `--dry-run`, `--json`, `--fast`, `--progress`, `--timeout SECONDS`, `--overwrite`, `-o OUT` -- but `--dry-run` only guarantees nothing is written for writing tools: `probe` (read-only, `--dry-run` changes nothing) and `check` (skips only the loudness-measurement pass) still run ffprobe/ffmpeg, `sync`/`multicam`/`scenes`/`cropdetect`/`report` still run ffmpeg/ffprobe to measure or analyse (they just don't write the final artifact), and `verify` accepts the flag but ignores it entirely. Exact per-tool semantics: `contract --json`'s `dry_run` field (or `docs/contract.md`).
+Every script prints the same information with `--help`; this file exists so the agent can read several at once. All scripts accept `--dry-run`, `--json`, `--fast`, `--progress`, `--timeout SECONDS`, `--overwrite`, `-o OUT` -- but `--dry-run` only guarantees nothing is written for writing tools: `probe` (read-only, `--dry-run` changes nothing) still runs ffprobe, `check`/`sync`/`multicam`/`scenes`/`cropdetect`/`report`/`silence`/`loudness`/`stabilize` still run their ffmpeg/ffprobe measurements (a dry-run plan rests on real numbers; they just don't write the final artifact), and `verify` accepts the flag but ignores it entirely. Exact per-tool semantics: `contract --json`'s `dry_run` field (or `docs/contract.md`).
## Contents
- probe.py — inspect
diff --git a/scripts/_common.py b/scripts/_common.py
index 5bbeba3..c1cb886 100755
--- a/scripts/_common.py
+++ b/scripts/_common.py
@@ -462,12 +462,17 @@ def run(cmd: Sequence[str], *, quiet: bool = False, check: bool = True) -> subpr
return proc
-def run_analysis(cmd: Sequence[str], *, check: bool = True, text: bool = True) -> subprocess.CompletedProcess:
- """Run an ffmpeg *measurement* (scene scores, crop rectangles, decoded PCM, signal stats):
- output to `-f null` or a pipe, nothing written. These are not run() calls -- they run under
- --dry-run too, since the analysis is the tool's whole job -- but they get the same wall-clock
- limit as any other ffmpeg invocation and, with check=True, the same `kind: ffmpeg` failure
- instead of an exit-0 "0 scenes found" over a file ffmpeg could not read."""
+def run_analysis(cmd: Sequence[str], *, check: bool = True, text: bool = True, record: bool = False) -> subprocess.CompletedProcess:
+ """Run an ffmpeg *measurement* (scene scores, crop rectangles, decoded PCM, signal stats,
+ silence detection, loudness, stabilisation pass 1): output to `-f null`, a pipe or a temp
+ file, no deliverable written. These are not run() calls -- they run under --dry-run too,
+ since a plan built on a fake measurement is not a plan (silence.py used to report "0
+ silences" and loudness.py a made-up -20 LUFS under --dry-run) -- but they get the same
+ wall-clock limit as any other ffmpeg invocation and, with check=True, the same `kind: ffmpeg`
+ failure instead of an exit-0 "0 scenes found" over a file ffmpeg could not read. record=True
+ lists the command in the --json `commands` like run() does."""
+ if record:
+ STATE.commands.append(_cmdline(cmd))
limit = _limit_for(cmd)
try:
proc = subprocess.run(list(cmd), stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=text, timeout=limit)
@@ -479,6 +484,17 @@ def run_analysis(cmd: Sequence[str], *, check: bool = True, text: bool = True) -
return proc
+def dry_run_input_pending(path: str) -> bool:
+ """True when a measurement cannot run because its input does not exist yet under --dry-run:
+ in a render.py/batch.py plan each stage's input is the previous stage's output, which a dry
+ run never wrote. The measurement is then skipped (with a note) rather than failing the plan;
+ on a real file the measurement runs even under --dry-run."""
+ if STATE.dry_run and not os.path.exists(path):
+ info(f"[dry-run] {path} does not exist yet (an earlier dry-run stage would write it); measurement skipped")
+ return True
+ return False
+
+
def child_limit(per_call: Optional[float] = None) -> Optional[float]:
"""Wall-clock ceiling for running one sibling script as a subprocess (render/batch/report
stages, the MCP server's dispatch). A tool runs a handful of ffmpeg/ffprobe calls, each
@@ -1142,6 +1158,9 @@ def db_to_linear(db: float) -> float:
def read_text_or_die(path: str, flag: str) -> str:
"""Read a caller-supplied UTF-8 text file (a cue list, chapters, notes) or fail as kind input
with the flag named, instead of a FileNotFoundError / UnicodeDecodeError traceback."""
+ if os.path.isdir(path):
+ # checked first: Windows raises PermissionError, not IsADirectoryError, for a directory
+ die(f"{flag}: {path} is a directory, not a text file")
try:
with open(path, "r", encoding="utf-8") as fh:
return fh.read()
diff --git a/scripts/_contract.py b/scripts/_contract.py
index 4fa1270..f437a38 100644
--- a/scripts/_contract.py
+++ b/scripts/_contract.py
@@ -215,10 +215,13 @@ DRY_RUN_ANALYSIS = {
"scenes": "scene and audio-peak measurement runs; --sheet and --edl are not written",
"report": "probe, loudness and contact-sheet measurements run; the HTML is not written",
"cropdetect": "the cropdetect filter runs over the sampled windows to measure bars; this tool never writes a file regardless of --dry-run",
+ "silence": "silencedetect runs so the reported silences and keep ranges are real; the cut output is not written",
+ "loudness": "the loudnorm measurement pass runs so input_i and the planned pass-2 command are real; the normalised output is not written",
+ "check": "read-only tool; the loudness measurement runs under --dry-run too, so every row is present",
+ "stabilize": "vidstabdetect (pass 1, into a temp file) runs; the stabilised output (pass 2) is not written",
}
DRY_RUN_NOTES = {
"probe": "read-only tool; --dry-run changes nothing (ffprobe still runs)",
- "check": "read-only tool; --dry-run skips the ffmpeg loudness measurement, so loudness rows are absent",
"verify": "not supported: the flag is accepted but the steps run and outputs are written",
}
diff --git a/scripts/batch.py b/scripts/batch.py
index d95b355..0834205 100755
--- a/scripts/batch.py
+++ b/scripts/batch.py
@@ -31,7 +31,7 @@ import time
from pathlib import Path
from typing import Any, Dict, List
-from _common import STATE, add_common, apply_common, child_args, die, emit, info, run_tool
+from _common import STATE, add_common, apply_common, child_args, die, emit, info, run_tool, read_text_or_die
HERE = Path(__file__).resolve().parent
MEDIA_EXT = {".mp4", ".mov", ".m4v", ".mkv", ".webm", ".avi", ".mts", ".m2ts", ".mxf", ".wav", ".m4a", ".mp3", ".flac"}
@@ -102,7 +102,10 @@ def process(src: Path, recipe: Dict[str, Any], outdir: Path, work: Path) -> Dict
final = final_path(src, recipe, outdir)
t0 = time.time()
if recipe.get("project"):
- proj = json.loads(Path(recipe["project"]).read_text(encoding="utf-8"))
+ try:
+ proj = json.loads(read_text_or_die(str(recipe["project"]), "recipe.project"))
+ except ValueError as e:
+ die(f"recipe.project: {recipe['project']} is not valid JSON: {e}")
idx = int(recipe.get("clip_key", 0))
proj.setdefault("clips", [{}])
while len(proj["clips"]) <= idx:
diff --git a/scripts/caption.py b/scripts/caption.py
index 45c64a4..fe069c5 100755
--- a/scripts/caption.py
+++ b/scripts/caption.py
@@ -36,7 +36,7 @@ import sys
from pathlib import Path
from typing import List, Optional, Tuple
-from _common import STATE, color_hex, load_brand, video_args, add_common, apply_common, emit, aac_args, cfr_args, default_output, die, escape_filter_path, ffmpeg_base, fmt_srt_time, fmt_smpte_time, info, MissingFpsError, parse_time, probe, run, x264_args, X264_PRESETS
+from _common import STATE, color_hex, load_brand, video_args, add_common, apply_common, emit, aac_args, cfr_args, default_output, die, escape_filter_path, ffmpeg_base, fmt_srt_time, fmt_smpte_time, info, MissingFpsError, parse_time, probe, run, x264_args, X264_PRESETS, read_text_or_die
ALIGN = {"bottom": 2, "top": 8, "center": 5, "bottom-left": 1, "bottom-right": 3, "top-left": 7, "top-right": 9}
@@ -48,33 +48,32 @@ TIME_RE = re.compile(
def parse_text_cues(path: str, auto_seconds: float, gap: float, fps: Optional[float] = None) -> List[Tuple[float, float, str]]:
cues: List[Tuple[float, float, str]] = []
cursor = 0.0
- with open(path, encoding="utf-8") as fh:
- for raw in fh:
- line = raw.rstrip("\n")
- if not line.strip():
- continue
- m = TIME_RE.match(line)
- if m:
- try:
- start, end = parse_time(m.group("a"), fps), parse_time(m.group("b"), fps)
- except MissingFpsError as e:
- die(f"cue '{line}': {e} -- pass --fps, or --input's own fps is used automatically when given")
- except ValueError:
- # TIME_RE matched (so m.group("text") is the real cue text, not the broken
- # timestamp), but one of the two timestamps itself failed to parse (e.g. a
- # malformed "00:00:03.15.999") -- falling back to `line.strip()` here used to
- # burn the whole raw line, broken timestamp included, into the caption instead
- # of just the text after it.
- start, end, text = cursor, cursor + auto_seconds, m.group("text").strip()
- else:
- text = m.group("text").strip()
+ for raw in read_text_or_die(path, "--text").lstrip("\ufeff").splitlines(True):
+ line = raw.rstrip("\n")
+ if not line.strip():
+ continue
+ m = TIME_RE.match(line)
+ if m:
+ try:
+ start, end = parse_time(m.group("a"), fps), parse_time(m.group("b"), fps)
+ except MissingFpsError as e:
+ die(f"cue '{line}': {e} -- pass --fps, or --input's own fps is used automatically when given")
+ except ValueError:
+ # TIME_RE matched (so m.group("text") is the real cue text, not the broken
+ # timestamp), but one of the two timestamps itself failed to parse (e.g. a
+ # malformed "00:00:03.15.999") -- falling back to `line.strip()` here used to
+ # burn the whole raw line, broken timestamp included, into the caption instead
+ # of just the text after it.
+ start, end, text = cursor, cursor + auto_seconds, m.group("text").strip()
else:
- start, end, text = cursor, cursor + auto_seconds, line.strip()
- if end <= start:
- die(f"cue '{line}': end must be after start")
- text = text.replace(" | ", "\n").replace("|", "\n")
- cues.append((start, end, text))
- cursor = end + gap
+ text = m.group("text").strip()
+ else:
+ start, end, text = cursor, cursor + auto_seconds, line.strip()
+ if end <= start:
+ die(f"cue '{line}': end must be after start")
+ text = text.replace(" | ", "\n").replace("|", "\n")
+ cues.append((start, end, text))
+ cursor = end + gap
if not cues:
die(f"no cues found in {path}")
return cues
@@ -173,8 +172,7 @@ def _transcribe_in(tmpdir: str, video: str, out_srt: str, language: Optional[str
def parse_srt(path: str) -> List[Tuple[float, float, str]]:
cues: List[Tuple[float, float, str]] = []
block: List[str] = []
- with open(path, encoding="utf-8-sig") as fh:
- content = fh.read().replace("\r\n", "\n") + "\n\n"
+ content = read_text_or_die(path, "--srt").lstrip("\ufeff").replace("\r\n", "\n") + "\n\n"
for line in content.split("\n"):
if line.strip():
block.append(line)
diff --git a/scripts/check.py b/scripts/check.py
index f582745..891a487 100755
--- a/scripts/check.py
+++ b/scripts/check.py
@@ -25,7 +25,7 @@ import sys
from fractions import Fraction
from typing import Any, Dict, List
-from _common import STATE, add_common, apply_common, die, emit, info, probe, require_tool, run
+from _common import STATE, add_common, apply_common, die, emit, info, probe, require_tool, run, run_analysis, dry_run_input_pending
SPECS: Dict[str, Dict[str, Any]] = {
"youtube": {"max_duration": 12 * 3600, "aspects": ["16:9", "9:16", "1:1", "4:3"], "min_height": 720, "fps_max": 60, "codecs": ["h264", "hevc", "prores", "av1", "vp9"], "max_bytes": 256 * 1024 ** 3, "lufs": -14, "lufs_tol": 2.0, "tp": -1.0, "sdr_only": False},
@@ -41,8 +41,10 @@ SPECS: Dict[str, Dict[str, Any]] = {
def measure_loudness(path: str) -> Dict[str, float]:
+ if dry_run_input_pending(path):
+ return {}
ffmpeg = require_tool("ffmpeg")
- proc = run([ffmpeg, "-hide_banner", "-nostdin", "-i", path, "-vn", "-af", "loudnorm=I=-14:TP=-1:LRA=11:print_format=json", "-f", "null", "-"], quiet=True, check=False)
+ proc = run_analysis([ffmpeg, "-hide_banner", "-nostdin", "-i", path, "-vn", "-af", "loudnorm=I=-14:TP=-1:LRA=11:print_format=json", "-f", "null", "-"], check=False, record=True)
m = re.search(r"\{[^{}]*\"input_i\"[^{}]*\}", proc.stderr, re.S)
if not m:
return {}
diff --git a/scripts/cropdetect.py b/scripts/cropdetect.py
index 53ca2d1..0cf8e2a 100644
--- a/scripts/cropdetect.py
+++ b/scripts/cropdetect.py
@@ -42,14 +42,22 @@ def detect(path: str, seconds: float, samples: int, limit: float, round_to: int,
ffmpeg = require_tool("ffmpeg")
per_window = max(0.5, seconds / max(1, samples))
rects: List[Tuple[int, int, int, int]] = []
+ failures: List[List[str]] = []
for i in range(samples):
start = 0.0 if duration <= 0 else (duration - per_window) * i / max(1, samples - 1) if samples > 1 else 0.0
start = max(0.0, start)
cmd = [ffmpeg, "-hide_banner", "-nostdin", "-ss", f"{start:.3f}", "-i", path, "-t", f"{per_window:.3f}",
"-vf", f"cropdetect=limit={limit:g}:round={round_to}:reset=1", "-f", "null", "-"]
- proc = run_analysis(cmd)
+ proc = run_analysis(cmd, check=False)
+ if proc.returncode != 0:
+ # One window ffmpeg cannot decode (a damaged stretch) is skipped; the other windows
+ # still measure. Only when every window fails is there nothing to report.
+ failures.append(proc.stderr.strip().splitlines()[-1:] or ["?"])
+ continue
for m in CROP_RE.finditer(proc.stderr):
rects.append((int(m.group(1)), int(m.group(2)), int(m.group(3)), int(m.group(4))))
+ if failures and len(failures) == samples:
+ die(f"cropdetect could not decode any of the {samples} sampled windows: {failures[-1][0][:300]}", kind="ffmpeg")
return rects
diff --git a/scripts/loudness.py b/scripts/loudness.py
index 94ff866..e1dcb14 100755
--- a/scripts/loudness.py
+++ b/scripts/loudness.py
@@ -18,16 +18,18 @@ import os
import re
import sys
-from _common import STATE, add_common, apply_common, emit, AUDIO_CODECS, audio_codec_for, default_output, die, ffmpeg_base, info, probe, require_tool, run
+from _common import STATE, add_common, apply_common, emit, AUDIO_CODECS, audio_codec_for, default_output, die, ffmpeg_base, info, probe, require_tool, run, run_analysis, dry_run_input_pending
def measure(path: str, I: float, tp: float, lra: float) -> dict:
- if STATE.dry_run:
- return {"input_i": "-20.0", "input_tp": "-3.0", "input_lra": "8.0", "input_thresh": "-30.0", "target_offset": "0.0", "silent": False}
+ if dry_run_input_pending(path):
+ return {"input_i": "-20.0", "input_tp": "-3.0", "input_lra": "8.0", "input_thresh": "-30.0", "target_offset": "0.0", "silent": False, "placeholder": True}
ffmpeg = require_tool("ffmpeg")
cmd = [ffmpeg, "-hide_banner", "-nostdin", "-i", path, "-vn", "-af", f"loudnorm=I={I}:TP={tp}:LRA={lra}:print_format=json", "-f", "null", "-"]
- proc = run(cmd, check=False)
+ # Pass 1 is a measurement: it runs under --dry-run too, so the planned pass-2 command and
+ # the reported input_i are real (before 1.4.6 a dry run returned a made-up -20 LUFS).
+ proc = run_analysis(cmd, check=False, record=True)
m = re.search(r"\{[^{}]*\"input_i\"[^{}]*\}", proc.stderr, re.S)
if proc.returncode != 0 or not m:
die(f"loudness measurement failed:\n{proc.stderr.strip()[-1500:]}", kind="ffmpeg")
@@ -86,6 +88,10 @@ def main() -> int:
cmd.append(output)
run(cmd)
+ if STATE.dry_run:
+ # pass 1 measured the input for real; there is no output to measure
+ emit(output, measured={k: stats[k] for k in ("input_i", "input_tp", "input_lra", "input_thresh", "target_offset", "silent")})
+ return 0
after = measure(output, args.lufs, args.tp, args.lra)
if not after.get("silent"):
info(f"result: {float(after['input_i']):.1f} LUFS, TP {float(after['input_tp']):.1f} dBTP (target {args.lufs} LUFS)")
diff --git a/scripts/render.py b/scripts/render.py
index 505d988..ccd2c3e 100755
--- a/scripts/render.py
+++ b/scripts/render.py
@@ -358,7 +358,7 @@ def main() -> int:
check_result = None
exit_code = 0
if ck and ck.get("platform") and not STATE.dry_run:
- proc = run_tool([str(HERE / "check.py"), output, "--platform", ck["platform"], "--json"])
+ proc = run_tool([str(HERE / "check.py"), output, "--platform", ck["platform"], "--json"] + child_args())
try:
check_result = json.loads(proc.stdout)
except ValueError:
@@ -386,7 +386,8 @@ def main() -> int:
# spec (or the check itself could not run): a failed delivery, reported as one.
failed_rows = [r["check"] for r in (check_result or {}).get("checks", []) if r.get("status") == "FAIL"]
die(f"rendered {output} but the {ck['platform']} check failed" + (f": {', '.join(failed_rows)}" if failed_rows else ""),
- kind="verification", output=output, dry_run=STATE.dry_run, stages=stages_done, check=check_result)
+ kind="verification", output=output, dry_run=STATE.dry_run, stages=stages_done, check=check_result,
+ probe=probe(output, role="output"))
info(f"rendered {output} via {' → '.join(stages_done)}")
emit(output, stages=stages_done, check=check_result)
return 0
diff --git a/scripts/report.py b/scripts/report.py
index 0bddac2..fe6f9b9 100755
--- a/scripts/report.py
+++ b/scripts/report.py
@@ -18,7 +18,7 @@ import tempfile
from pathlib import Path
from typing import Any, Dict, List, Optional
-from _common import STATE, add_common, apply_common, die, emit, info, probe, read_text_or_die, run_tool
+from _common import STATE, add_common, apply_common, child_args, die, emit, info, probe, read_text_or_die, run_tool
HERE = Path(__file__).resolve().parent
@@ -26,14 +26,14 @@ HERE = Path(__file__).resolve().parent
def sheet_b64(path: str, tiles: str = "4x2", width: int = 1200) -> Optional[str]:
with tempfile.TemporaryDirectory(prefix="ffskill_report_") as tmp:
png = os.path.join(tmp, "sheet.png")
- proc = run_tool([str(HERE / "look.py"), path, "--tiles", tiles, "--width", str(width), "-o", png])
+ proc = run_tool([str(HERE / "look.py"), path, "--tiles", tiles, "--width", str(width), "-o", png] + child_args())
if proc.returncode != 0 or not os.path.exists(png):
return None
return base64.b64encode(Path(png).read_bytes()).decode("ascii")
def loudness(path: str) -> Dict[str, Any]:
- proc = run_tool([str(HERE / "loudness.py"), path, "--measure-only"])
+ proc = run_tool([str(HERE / "loudness.py"), path, "--measure-only"] + child_args())
try:
d = json.loads(proc.stdout)
return {"lufs": round(float(d["input_i"]), 1), "tp": round(float(d["input_tp"]), 1), "lra": round(float(d["input_lra"]), 1)}
@@ -42,7 +42,7 @@ def loudness(path: str) -> Dict[str, Any]:
def check(path: str, platform: str) -> Optional[Dict[str, Any]]:
- proc = run_tool([str(HERE / "check.py"), path, "--platform", platform, "--json"])
+ proc = run_tool([str(HERE / "check.py"), path, "--platform", platform, "--json"] + child_args())
try:
doc = json.loads(proc.stdout)
except ValueError:
diff --git a/scripts/silence.py b/scripts/silence.py
index 572aa17..c6ab7a7 100755
--- a/scripts/silence.py
+++ b/scripts/silence.py
@@ -12,20 +12,23 @@ Examples:
python3 silence.py talk.mp4 --edl keep.txt # also save the kept ranges (START-END per line, cut.py --segments format)
"""
import argparse
+import os
import re
import sys
from typing import List, Tuple
-from _common import STATE, video_args, add_common, apply_common, audio_codec_for, cfr_args, default_output, die, emit, ffmpeg_base, info, is_audio_output, print_json, probe, require_tool, run, x264_args, X264_PRESETS, measured_level_dbfs
+from _common import STATE, video_args, add_common, apply_common, audio_codec_for, cfr_args, default_output, die, emit, ffmpeg_base, info, is_audio_output, print_json, probe, require_tool, run, x264_args, X264_PRESETS, measured_level_dbfs, run_analysis, dry_run_input_pending
SIL_RE = re.compile(r"silence_(start|end): ([0-9.]+)")
def detect(path: str, threshold: float, min_silence: float) -> List[Tuple[float, float]]:
+ if dry_run_input_pending(path):
+ return []
ffmpeg = require_tool("ffmpeg")
cmd = [ffmpeg, "-hide_banner", "-nostdin", "-i", path, "-vn", "-af",
f"silencedetect=noise={threshold}dB:d={min_silence}", "-f", "null", "-"]
- proc = run(cmd, quiet=True, check=False)
+ proc = run_analysis(cmd, check=False, record=True)
if proc.returncode != 0:
die(f"silencedetect failed:\n{proc.stderr.strip()[-800:]}", kind="ffmpeg")
silences: List[Tuple[float, float]] = []
@@ -86,7 +89,7 @@ def main() -> int:
"removed_seconds": round(removed, 3),
}
info(f"{len(silences)} silences, keeping {len(keeps)} ranges: {kept:.2f}s of {duration:.2f}s (removing {removed:.2f}s)")
- if not silences and not STATE.dry_run:
+ if not silences and not (STATE.dry_run and not os.path.exists(args.input)):
# Nothing under the threshold is a valid result, not a failure -- but an agent that only
# sees "0 silences" tends to reach for raw ffmpeg next. Say what the floor actually is and
# what threshold would bite, so the retry is a flag change, not a workaround.
diff --git a/scripts/stabilize.py b/scripts/stabilize.py
index 03b2596..3c56a67 100644
--- a/scripts/stabilize.py
+++ b/scripts/stabilize.py
@@ -27,7 +27,7 @@ import sys
import tempfile
from pathlib import Path
-from _common import STATE, add_common, apply_common, aac_args, cfr_args, default_output, die, emit, escape_filter_path, ffmpeg_base, info, probe, require_tool, run, video_args, X264_PRESETS
+from _common import STATE, add_common, apply_common, aac_args, cfr_args, default_output, die, emit, escape_filter_path, ffmpeg_base, info, probe, require_tool, run, video_args, X264_PRESETS, run_analysis, dry_run_input_pending
def main() -> int:
@@ -62,18 +62,20 @@ def main() -> int:
trf = str(Path(tmp) / "transforms.trf")
trf_arg = escape_filter_path(trf)
- if not STATE.dry_run:
- ffmpeg = require_tool("ffmpeg")
- detect_vf = f"vidstabdetect=shakiness={args.shakiness}:result={trf_arg}"
- if args.tripod:
- # A frame number, not a boolean: frame 1 is the standard reference for "lock to
- # this fixed frame" (mirrors vidstabtransform's own tripod=1 below).
- detect_vf += ":tripod=1"
- detect_cmd = [ffmpeg, "-hide_banner", "-loglevel", "error", "-nostdin", "-y", "-i", args.input,
- "-vf", detect_vf, "-f", "null", "-"]
- proc = run(detect_cmd, check=False)
+ ffmpeg = require_tool("ffmpeg")
+ detect_vf = f"vidstabdetect=shakiness={args.shakiness}:result={trf_arg}"
+ if args.tripod:
+ # A frame number, not a boolean: frame 1 is the standard reference for "lock to
+ # this fixed frame" (mirrors vidstabtransform's own tripod=1 below).
+ detect_vf += ":tripod=1"
+ detect_cmd = [ffmpeg, "-hide_banner", "-loglevel", "error", "-nostdin", "-y", "-i", args.input,
+ "-vf", detect_vf, "-f", "null", "-"]
+ # Pass 1 is a measurement into a temp file (the transforms), so it runs under --dry-run
+ # as well; only pass 2, the write, is skipped there.
+ if not dry_run_input_pending(args.input):
+ proc = run_analysis(detect_cmd, check=False, record=True)
if proc.returncode != 0:
- die(f"stabilization analysis (pass 1) failed:\n{proc.stderr.strip()[-1500:]}")
+ die(f"stabilization analysis (pass 1) failed:\n{proc.stderr.strip()[-1500:]}", kind="ffmpeg")
crop_mode = {"keep": 0, "black": 1}[args.crop]
transform_vf = f"vidstabtransform=input={trf_arg}:smoothing={args.smoothing}:crop={crop_mode}:zoom={args.zoom:g}:optzoom=1"
diff --git a/tests/test_contract.py b/tests/test_contract.py
index c38a180..9000446 100644
--- a/tests/test_contract.py
+++ b/tests/test_contract.py
@@ -504,7 +504,7 @@ class ContractTests(unittest.TestCase):
tool gaining/losing an analysis-only dry-run mode is caught here instead of the docs
silently drifting out of sync with _contract.py again (issue #82)."""
analysis_tools = set(_contract.DRY_RUN_ANALYSIS.keys())
- self.assertEqual(analysis_tools, {"sync", "multicam", "scenes", "report", "cropdetect"},
+ self.assertEqual(analysis_tools, {"sync", "multicam", "scenes", "report", "cropdetect", "silence", "loudness", "check", "stabilize"},
"the analysis-only dry-run tool set changed -- update SKILL.md/references/scripts.md's exception list to match")
skill = (ROOT / "SKILL.md").read_text(encoding="utf-8")
scripts_ref = (ROOT / "references" / "scripts.md").read_text(encoding="utf-8")
@@ -1126,7 +1126,8 @@ class ContractTests(unittest.TestCase):
self.assertEqual(sorted(p.name for p in outdir.iterdir()), [], f"{name} --dry-run wrote files")
if strict:
self.assertFalse(marker.exists(), f"{name} --dry-run invoked ffmpeg")
- self.assertEqual({n for n, s in self.tools.items() if s["dry_run"]["ffmpeg_execution"] == "analysis_only"}, {"sync", "multicam", "scenes", "report", "cropdetect"})
+ self.assertEqual({n for n, s in self.tools.items() if s["dry_run"]["ffmpeg_execution"] == "analysis_only"},
+ {"sync", "multicam", "scenes", "report", "cropdetect", "silence", "loudness", "check", "stabilize"})
# the read-only tools keep working under --dry-run (ffprobe still runs)
self.assertEqual(tool("probe", self.src, "--dry-run", env=env).returncode, 0)
self.assertEqual(tool("check", self.src, "--platform", "x", "--no-loudness", "--dry-run", env=env).returncode, 0)
@@ -1251,6 +1252,78 @@ class ContractTests(unittest.TestCase):
self.assertIn("sleeper.py", doc["error"]["message"])
_common.STATE.reset()
+ def test_dry_run_plans_rest_on_real_measurements(self):
+ """silence.py, loudness.py, check.py and stabilize.py ran their measurement through run(),
+ which --dry-run replaces with a fake empty result: a dry run always reported "0 silences",
+ a made-up -20 LUFS, a loudness row that could not be measured, and no stabilisation pass.
+ A plan built on a fake measurement is not a plan. The measurement passes now go through
+ run_analysis() (real under --dry-run, still under --timeout); only the write is skipped."""
+ gappy = self.out("gappy.mp4")
+ ffmpeg("-f", "lavfi", "-i", "aevalsrc='0.5*sin(2*PI*440*t)*gt(sin(2*PI*0.25*t)\\,0)':s=48000",
+ "-f", "lavfi", "-i", "testsrc2=size=160x90:rate=30", "-t", "8", "-c:v", "libx264", "-preset", "ultrafast", "-c:a", "aac", gappy)
+ doc = json.loads(tool("silence", gappy, "--dry-run", "--list", "--json").stdout)
+ self.assertTrue(doc["dry_run"])
+ self.assertTrue(doc["silences"], "a dry run must detect the fixture's real silences")
+ self.assertTrue(any("silencedetect" in c for c in doc["commands"]))
+ doc = json.loads(tool("loudness", self.src, "--dry-run", "--json", "-o", self.out("dry_loud.mp4")).stdout)
+ self.assertTrue(doc["dry_run"])
+ self.assertNotEqual(doc["measured"]["input_i"], "-20.0", "the pass-1 measurement must be real, not the old placeholder")
+ self.assertFalse(self.out("dry_loud.mp4").exists())
+ doc = json.loads(tool("check", self.src, "--platform", "youtube", "--dry-run", "--json", check=False).stdout)
+ rows = {r["check"]: r for r in doc["checks"]}
+ self.assertNotIn("could not be measured", rows["loudness"].get("reason", ""), rows["loudness"])
+
+ def test_run_analysis_is_killed_by_timeout(self):
+ """A measurement (scenes.py's scdet pass) that hangs is killed under the same --timeout
+ as any other ffmpeg call and reported as kind timeout, not waited on forever."""
+ if platform.system() == "Windows":
+ self.skipTest("the hung ffmpeg is a #!/bin/sh shim on a POSIX-only PATH")
+ shim = self.out("hang_analysis_shim")
+ shim.mkdir()
+ (shim / "ffmpeg").write_text("#!/bin/sh\nsleep 8\nexit 1\n")
+ (shim / "ffmpeg").chmod(0o755)
+ (shim / "ffprobe").symlink_to(shutil.which("ffprobe"))
+ env = dict(os.environ, PATH=str(shim) + os.pathsep + os.environ["PATH"])
+ t0 = time.time()
+ proc = tool("scenes", self.src, "--timeout", "1", "--json", env=env, check=False)
+ self.assertEqual(proc.returncode, 124, proc.stderr[-300:])
+ self.assertEqual(json.loads(proc.stdout)["error"]["kind"], "timeout")
+ self.assertLess(time.time() - t0, 6)
+
+ def test_caller_supplied_text_files_fail_as_kind_input(self):
+ """--text/--srt/--chapters/--commands/--notes files that are missing, a directory or not
+ UTF-8 used to surface as FileNotFoundError / IsADirectoryError / UnicodeDecodeError
+ tracebacks. read_text_or_die() names the flag and fails as kind input."""
+ bad = self.out("latin1.txt")
+ bad.write_bytes(b"0:00-0:01 caf\xe9\n")
+ adir = self.out("a_directory")
+ adir.mkdir()
+ for args, needle in ((["--text", str(self.out("nope.txt"))], "does not exist"),
+ (["--text", str(adir)], "is a directory"),
+ (["--text", str(bad)], "not UTF-8")):
+ proc = tool("caption", self.src, *args, "--json", "-o", self.out("cap_bad.mp4"), check=False)
+ self.assertNotEqual(proc.returncode, 0)
+ doc = json.loads(proc.stdout)
+ self.assertEqual((doc["status"], doc["error"]["kind"]), ("failed", "input"), args)
+ self.assertIn("--text", doc["error"]["message"])
+ self.assertIn(needle, doc["error"]["message"])
+ self.assertEqual(doc["commands"], [], "refused before ffmpeg ran")
+
+ def test_batch_reports_failed_items_as_a_failed_run(self):
+ """batch.py printed status completed next to exit 1 when an item failed; it now fails
+ with kind verification and keeps the per-item results so the caller sees which."""
+ folder = self.out("batch_fail")
+ folder.mkdir()
+ shutil.copy(self.src, folder / "a.mp4")
+ recipe = folder / "batch.json"
+ recipe.write_text(json.dumps({"glob": "*.mp4", "output_dir": "out", "suffix": "_x",
+ "steps": [["cut.py", "{in}", "--start", "0", "--end", "1", "--crf", "99", "-o", "{out}"]]}))
+ proc = tool("batch", folder, "--recipe", recipe, "--json", check=False)
+ self.assertEqual(proc.returncode, 1)
+ doc = json.loads(proc.stdout)
+ self.assertEqual((doc["status"], doc["error"]["kind"], doc["processed"], doc["total"]), ("failed", "verification", 0, 1))
+ self.assertFalse(doc["results"][0]["ok"])
+
def test_failed_run_never_deletes_an_output_that_predates_it(self):
"""The partial-output cleanup (#78) removed the output path after every failed ffmpeg run
without asking whether the file had been there before: a bad filter argument aimed at an