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.
Python agent-skillsai-agentsaudio-processingcaptionsclaude-codecodexcoding-agentcursorffmpegloudness-normalizationmcpmcp-servermodel-context-protocolpythonsubtitlestranscodingvideovideo-editingvideo-processingwhisper
fix: failed check/render/batch/verify report status failed; analysis runs get --timeout; render/batch forward the shared flags (#174)
Shogo Kajiyama11c1811ede27
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 89856c9..1eb504c 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -4,7 +4,9 @@## Unreleased-(nothing yet)+- `check.py`, `render.py` (check stage), `batch.py` and `verify.py` report a failed result as `status: failed` with the new `kind: verification` (`VERIFICATION_FAILED`, exit 1) and keep their detail fields (`checks`, `check`, `results`, `files`); before, they printed `status: completed` next to a non-zero exit code.+- `scenes.py`, `cropdetect.py`, `sync.py`, `caption.py --transcribe` and the colour-level probe run their ffmpeg measurements under `--timeout` and report a decode failure as `kind: ffmpeg` instead of an empty result or a traceback; the transcribe temp directory is removed afterwards.+- `render.py` and `batch.py` forward `--timeout` and `--overwrite` to every stage, not only `--fast`/`--dry-run`.## 1.4.3diff --git a/README.md b/README.mdindex 1994f0b..0ff534c 100644--- a/README.md+++ b/README.md@@ -293,7 +293,7 @@ The contract is generated from the code that runs, not maintained beside it. For| `mutates_input` | always `false` || `idempotency_hint` | `bit_exact`, `content_equivalent`, `cached` or `environment_dependent` |-`contract_version` (1.0) is separate from the skill version, so a consumer can pin the shape and read the version for provenance. The document also states the invocation mapping (structured arguments → argv), the JSON shapes for success and failure (`{"status": "failed", "error": {"kind": "input | ffmpeg | missing_tool", "message": …}}`), and that no tool runs a shell or executes anything other than the named script, `ffmpeg` and `ffprobe`. Field-by-field reference: [docs/contract.md](docs/contract.md).+`contract_version` (1.0) is separate from the skill version, so a consumer can pin the shape and read the version for provenance. The document also states the invocation mapping (structured arguments → argv), the JSON shapes for success and failure (`{"status": "failed", "error": {"kind": "input | ffmpeg | output | missing_tool | timeout | verification", "message": …}}`), and that no tool runs a shell or executes anything other than the named script, `ffmpeg` and `ffprobe`. Field-by-field reference: [docs/contract.md](docs/contract.md).### MCPdiff --git a/SKILL.md b/SKILL.mdindex d142841..a8051b2 100644--- a/SKILL.md+++ b/SKILL.md@@ -265,7 +265,7 @@ Steps: probe -> color (failed); nothing writtenNotes: send a valid .cube, or say if you want the clip left as is```-Every script prints `{"status": "failed", "error": {"kind": input | ffmpeg | output | missing_tool, "message": ...}}` with `--json` and exits non-zero; quote the message, do not paraphrase it into a success.+Every script prints `{"status": "failed", "error": {"kind": input | ffmpeg | output | missing_tool | timeout | verification, "message": ...}}` with `--json` and exits non-zero; quote the message, do not paraphrase it into a success.## Things that look right but are wrongdiff --git a/docs/contract.md b/docs/contract.mdindex 9442ade..6dfed10 100644--- a/docs/contract.md+++ b/docs/contract.md@@ -305,8 +305,8 @@ before, and, when `--json` was given, on stdout:```json{"status": "failed", "exit_code": 1,- "error": {"kind": "input | ffmpeg | output | missing_tool | timeout", "message": "...",- "code": "INPUT_INVALID | DEPENDENCY_MISSING | FFMPEG_EXECUTION_FAILED | OUTPUT_INVALID | TIMEOUT | INTERNAL_ERROR",+ "error": {"kind": "input | ffmpeg | output | missing_tool | timeout | verification", "message": "...",+ "code": "INPUT_INVALID | DEPENDENCY_MISSING | FFMPEG_EXECUTION_FAILED | OUTPUT_INVALID | TIMEOUT | VERIFICATION_FAILED | INTERNAL_ERROR","retryable": false},"commands": ["ffmpeg ..."]}```@@ -316,7 +316,7 @@ stderr lines of ffmpeg, the verification that failed); `commands` lists what wasor run so the caller can retry or report without re-deriving the command. `code` is apurely additive, statically-mapped relabelling of `kind` (never a new distinction `kind`doesn't already make) for a caller that wants a stable enum instead of matching `kind`-strings. `retryable` is currently always `false`: none of the four kinds are distinguishable+strings. `retryable` is currently always `false`: none of the kinds are distinguishabletoday from a deterministic failure that would fail identically on a blind retry, so nothinghere claims otherwise until real exit-code/stderr sniffing exists to back that up.diff --git a/scripts/_common.py b/scripts/_common.pyindex 434593d..361c536 100755--- a/scripts/_common.py+++ b/scripts/_common.py@@ -63,6 +63,7 @@ ERROR_CODE = {"ffmpeg": "FFMPEG_EXECUTION_FAILED","output": "OUTPUT_INVALID","timeout": "TIMEOUT",+ "verification": "VERIFICATION_FAILED",}# Wall-clock ceiling for one ffmpeg/ffprobe invocation, in seconds. A hung ffmpeg (a build@@ -149,12 +150,18 @@ def add_pad_fill_args(parser: "argparse.ArgumentParser") -> None:parser.add_argument("--pad-blur", type=int, default=20, help="blur radius in pixels for --pad-fill blur (default 20)")-def die(msg: str, code: int = 1, kind: str = "input") -> "None":+def die(msg: str, code: int = 1, kind: str = "input", **extra: Any) -> "None":"""Exit with a message. Under --json also print a machine-readable failure document- (status: failed) on stdout so callers get the same shape as a success; exit codes are unchanged."""+ (status: failed) on stdout so callers get the same shape as a success; exit codes are unchanged.++ `extra` fields are added to the failure document: a tool whose *result* failed (check.py's+ platform rows, render.py's check stage, batch.py's per-item results, verify.py's steps) keeps+ reporting that detail while the top-level status says failed. Before 1.4.3 those four printed+ `status: "completed"` next to a non-zero exit code, so a caller keying on the status alone+ read a failed delivery as a success."""sys.stderr.write(f"error: {msg}\n")if STATE.json:- print_json({+ doc: Dict[str, Any] = {"status": "failed", "exit_code": code,"error": {"kind": kind, "message": msg,@@ -162,7 +169,9 @@ def die(msg: str, code: int = 1, kind: str = "input") -> "None":"retryable": ERROR_RETRYABLE,},"commands": list(STATE.commands),- })+ }+ doc.update(extra)+ print_json(doc)sys.exit(code)@@ -461,6 +470,39 @@ def run(cmd: Sequence[str], *, quiet: bool = False, check: bool = True) -> subprreturn 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."""+ limit = _limit_for(cmd)+ try:+ proc = subprocess.run(list(cmd), stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=text, timeout=limit)+ except subprocess.TimeoutExpired:+ _timed_out(cmd, limit or 0)+ if check and proc.returncode != 0:+ err = proc.stderr if text else proc.stderr.decode(errors="replace")+ _fail(cmd, proc.returncode, err)+ return proc+++def child_args() -> List[str]:+ """The shared flags a tool that runs sibling scripts (render.py, batch.py) forwards to them,+ so one `--timeout`/`--overwrite`/`--fast`/`--dry-run` on the outer command governs every+ stage. Before 1.4.3 only --fast and --dry-run were forwarded; a --timeout given to render.py+ stopped at render.py."""+ args: List[str] = []+ if STATE.fast:+ args.append("--fast")+ if STATE.dry_run:+ args.append("--dry-run")+ if STATE.overwrite:+ args.append("--overwrite")+ args += ["--timeout", f"{STATE.timeout:g}"]+ return args++def run_keeping_subtitles(cmd: List[str], output: str) -> bool:"""Run an ffmpeg command that already maps its video/audio, trying first to alsostream-copy any subtitle/data streams the source has (`-map 0:s?`/`0:d?` are no-ops when@@ -1045,7 +1087,7 @@ def analyze_levels(path: str, seconds: float = 20.0) -> Dict[str, Any]:ffmpeg = require_tool("ffmpeg")cmd = [ffmpeg, "-hide_banner", "-nostdin", "-t", f"{seconds:.1f}", "-i", path, "-an","-vf", "fps=2,signalstats,metadata=print:file=-", "-f", "null", "-"]- proc = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)+ proc = run_analysis(cmd, check=False)vals: Dict[str, List[float]] = {}for line in proc.stdout.splitlines():if "lavfi.signalstats." in line and "=" in line:diff --git a/scripts/_contract.py b/scripts/_contract.pyindex df42ab8..4fa1270 100644--- a/scripts/_contract.py+++ b/scripts/_contract.py@@ -1037,7 +1037,7 @@ def build(detect: bool = True) -> Dict[str, Any]:"json_output": {"success": {"status": "completed", "exit_code": 0, "stdout": "one JSON document (output_schema)"},"failure": {"status": "failed", "exit_code": "non-zero (127 when ffmpeg/ffprobe is missing)", "stdout": "{\"status\": \"failed\", \"exit_code\": N, \"error\": {\"kind\": ..., \"message\": ...}, \"commands\": [...]} when --json was given", "stderr": "human-readable message"},- "error_kinds": {"input": "missing or unsuitable input, bad arguments", "ffmpeg": "ffmpeg/ffprobe returned an error (message carries the last stderr lines)", "output": "ffmpeg exited 0 but the artifact is missing, empty or unreadable (an empty file is removed)", "missing_tool": "ffmpeg or ffprobe not on PATH", "timeout": "one ffmpeg/ffprobe run exceeded --timeout (default 1800 s, FFMPEG_SKILL_TIMEOUT) and was killed; partial output removed; exit 124"},+ "error_kinds": {"input": "missing or unsuitable input, bad arguments", "ffmpeg": "ffmpeg/ffprobe returned an error (message carries the last stderr lines)", "output": "ffmpeg exited 0 but the artifact is missing, empty or unreadable (an empty file is removed)", "missing_tool": "ffmpeg or ffprobe not on PATH", "timeout": "one ffmpeg/ffprobe run exceeded --timeout (default 1800 s, FFMPEG_SKILL_TIMEOUT) and was killed; partial output removed; exit 124", "verification": "the tool ran but its result failed the requested check: check.py platform rows (checks attached), render.py's check stage (output written, check attached), batch.py items (results attached), verify.py steps (files attached); exit 1"},"success_criterion": "exit 0 AND the output exists AND is non-empty AND ffprobe reads a stream from it; only then is status completed printed and the output probe attached",},"capabilities": caps,diff --git a/scripts/batch.py b/scripts/batch.pyindex 23f0e56..17db9a5 100755--- a/scripts/batch.py+++ b/scripts/batch.py@@ -32,7 +32,7 @@ import timefrom pathlib import Pathfrom typing import Any, Dict, List-from _common import STATE, add_common, apply_common, die, emit, info+from _common import STATE, add_common, apply_common, child_args, die, emit, infoHERE = Path(__file__).resolve().parentMEDIA_EXT = {".mp4", ".mov", ".m4v", ".mkv", ".webm", ".avi", ".mts", ".m2ts", ".mxf", ".wav", ".m4a", ".mp3", ".flac"}@@ -78,11 +78,7 @@ def run_step(argv: List[str]) -> bool:if script not in ALLOWED_STEP_SCRIPTS:die(f"recipe step names a script that isn't one of this skill's own tools: {script!r} "f"(must be a bare filename like 'silence.py', found in scripts/)")- cmd = [sys.executable, str(HERE / script)] + argv[1:]- if STATE["fast"]:- cmd.append("--fast")- if STATE["dry_run"]:- cmd.append("--dry-run")+ cmd = [sys.executable, str(HERE / script)] + argv[1:] + child_args()info(" → " + " ".join(os.path.basename(c) if i < 2 else c for i, c in enumerate(cmd)))proc = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)if proc.returncode != 0:@@ -219,11 +215,15 @@ def main() -> int:passdone = 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")- emit(None, results=results, processed=done, total=len(results))if not args.json:for r in results:print(f"{'OK ' if r['ok'] else 'FAIL'} {r['file']} -> {r['output']}" + (" (cached)" if r.get("cached") else ""))- return 0 if done == len(results) else 1+ if done != len(results):+ failed_files = [r["file"] for r in results if not r["ok"]]+ die(f"{len(results) - done} of {len(results)} items failed: {', '.join(failed_files[:5])}" + (" ..." if len(failed_files) > 5 else ""),+ kind="verification", output=None, dry_run=STATE.dry_run, results=results, processed=done, total=len(results))+ emit(None, results=results, processed=done, total=len(results))+ return 0if __name__ == "__main__":diff --git a/scripts/caption.py b/scripts/caption.pyindex 8b1760f..f8d57b8 100755--- a/scripts/caption.py+++ b/scripts/caption.py@@ -87,12 +87,36 @@ def transcribe(video: str, out_srt: str, language: Optional[str], model: str, auimport shutilimport subprocessimport tempfile- from _common import require_tool+ from _common import require_tool, run_analysis, STATEffmpeg = require_tool("ffmpeg")tmpdir = tempfile.mkdtemp(prefix="ffskill_asr_")+ try:+ return _transcribe_in(tmpdir, video, out_srt, language, model, audio_stream, ffmpeg, shutil, subprocess)+ finally:+ shutil.rmtree(tmpdir, ignore_errors=True)+++def _asr_run(cmd: List[str], subprocess, name: str) -> "subprocess.CompletedProcess":+ """Run a speech-to-text engine under the same wall-clock limit as an ffmpeg call."""+ from _common import STATE, die+ limit = STATE.timeout or None+ try:+ return subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, timeout=limit)+ except subprocess.TimeoutExpired:+ die(f"{name} exceeded the {limit:.0f} s time limit and was killed; raise --timeout for a long recording",+ code=124, kind="timeout")+ return None # unreachable+++def _transcribe_in(tmpdir: str, video: str, out_srt: str, language: Optional[str], model: str, audio_stream: int,+ ffmpeg: str, shutil, subprocess) -> List[Tuple[float, float, str]]:+ from _common import run_analysiswav = os.path.join(tmpdir, "audio.wav")- subprocess.run([ffmpeg, "-hide_banner", "-loglevel", "error", "-nostdin", "-y", "-i", video,- "-map", f"0:a:{audio_stream}", "-vn", "-ac", "1", "-ar", "16000", "-c:a", "pcm_s16le", wav], check=True)+ # A wav in our own temp dir: a measurement input for the engine, not a deliverable, so it+ # is not a run() call (no --dry-run gate, not recorded), but it keeps the time limit and+ # reports an unreadable input as kind ffmpeg instead of a CalledProcessError traceback.+ run_analysis([ffmpeg, "-hide_banner", "-loglevel", "error", "-nostdin", "-y", "-i", video,+ "-map", f"0:a:{audio_stream}", "-vn", "-ac", "1", "-ar", "16000", "-c:a", "pcm_s16le", wav])# 1. whisper.cppcli = shutil.which("whisper-cli") or shutil.which("whisper-cpp") or shutil.which("main")if cli and (shutil.which("whisper-cli") or shutil.which("whisper-cpp")):@@ -106,7 +130,7 @@ def transcribe(video: str, out_srt: str, language: Optional[str], model: str, aucmd = [cli, "-m", model_path, "-f", wav, "-osrt", "-of", base]if language:cmd += ["-l", language]- proc = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)+ proc = _asr_run(cmd, subprocess, "whisper.cpp")if proc.returncode == 0 and os.path.exists(base + ".srt"):info(f"transcribed with whisper.cpp ({os.path.basename(cli)}, model {os.path.basename(model_path)})")cues = parse_srt(base + ".srt")@@ -130,7 +154,7 @@ def transcribe(video: str, out_srt: str, language: Optional[str], model: str, aucmd = ["whisper", wav, "--model", model, "--output_format", "srt", "--output_dir", tmpdir]if language:cmd += ["--language", language]- proc = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)+ proc = _asr_run(cmd, subprocess, "openai-whisper")srt = os.path.join(tmpdir, "audio.srt")if proc.returncode == 0 and os.path.exists(srt):info("transcribed with openai-whisper")diff --git a/scripts/check.py b/scripts/check.pyindex 324bb70..f582745 100755--- a/scripts/check.py+++ b/scripts/check.py@@ -25,7 +25,7 @@ import sysfrom fractions import Fractionfrom typing import Any, Dict, List-from _common import 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, runSPECS: 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},@@ -190,8 +190,12 @@ def main() -> int:line += f" -> {r['fix']}"print(line)print(f" {len(rows)} checks, {len(failed)} failed, {len(warned)} warnings")- emit(None, platform=args.platform, checks=rows, failed=len(failed), warnings=len(warned), ok=not failed)- return 1 if failed else 0+ if failed:+ die(f"{len(failed)} of {len(rows)} {args.platform} checks failed: {', '.join(r['check'] for r in failed)}",+ kind="verification", output=None, dry_run=STATE.dry_run,+ platform=args.platform, checks=rows, failed=len(failed), warnings=len(warned), ok=False)+ emit(None, platform=args.platform, checks=rows, failed=len(failed), warnings=len(warned), ok=True)+ return 0if __name__ == "__main__":diff --git a/scripts/cropdetect.py b/scripts/cropdetect.pyindex 3d9c566..53ca2d1 100644--- a/scripts/cropdetect.py+++ b/scripts/cropdetect.py@@ -29,12 +29,11 @@ Examples:"""import argparseimport re-import subprocessimport sysfrom collections import Counterfrom typing import Dict, List, Tuple-from _common import add_common, apply_common, die, emit, info, print_json, probe, require_tool+from _common import add_common, apply_common, die, emit, info, print_json, probe, require_tool, run_analysisCROP_RE = re.compile(r"crop=(\d+):(\d+):(\d+):(\d+)")@@ -48,7 +47,7 @@ def detect(path: str, seconds: float, samples: int, limit: float, round_to: int,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 = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)+ proc = run_analysis(cmd)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))))return rectsdiff --git a/scripts/render.py b/scripts/render.pyindex 7202ebe..03722c8 100755--- a/scripts/render.py+++ b/scripts/render.py@@ -56,7 +56,7 @@ import sysfrom pathlib import Pathfrom typing import Any, Dict, List-from _common import STATE, add_common, apply_common, die, emit, info, probe+from _common import STATE, add_common, apply_common, child_args, die, emit, info, probeHERE = Path(__file__).resolve().parent@@ -80,11 +80,7 @@ TEMPLATE = {def sh(script: str, *argv: Any, extra: List[str] = None) -> str:"""Run a sibling script, forwarding --fast / --dry-run, returning its printed output path."""- cmd = [sys.executable, str(HERE / script)] + [str(a) for a in argv] + (extra or [])- if STATE["fast"]:- cmd.append("--fast")- if STATE["dry_run"]:- cmd.append("--dry-run")+ cmd = [sys.executable, str(HERE / script)] + [str(a) for a in argv] + (extra or []) + child_args()info("→ " + " ".join(os.path.basename(c) if i < 2 else c for i, c in enumerate(cmd)))proc = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)for line in proc.stderr.splitlines():@@ -360,12 +356,12 @@ def main() -> int:check_result = json.loads(proc.stdout)except ValueError:check_result = {"error": proc.stderr.strip()[-300:]}- if check_result.get("error"):- info(f"check: could not run check.py — {check_result['error']}")- exit_code = 1- elif check_result.get("failed"):+ if check_result.get("failed"):info(f"check: {check_result['failed']} FAIL — " + "; ".join(f"{r['check']}={r['value']} ({r['fix']})" for r in check_result["checks"] if r["status"] == "FAIL"))exit_code = 1+ elif check_result.get("error") or check_result.get("status") == "failed":+ info(f"check: could not run check.py — {check_result.get('error')}")+ exit_code = 1else:info(f"check: OK for {ck['platform']}")stages_done.append("check")@@ -378,9 +374,15 @@ def main() -> int:# to before the PID suffix was added.import shutilshutil.rmtree(work, ignore_errors=True)+ if exit_code:+ # The deliverable is written and verified, but it does not meet the requested platform+ # 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)info(f"rendered {output} via {' → '.join(stages_done)}")emit(output, stages=stages_done, check=check_result)- return exit_code+ return 0if __name__ == "__main__":diff --git a/scripts/scenes.py b/scripts/scenes.pyindex df4d637..a24acf0 100755--- a/scripts/scenes.py+++ b/scripts/scenes.py@@ -22,11 +22,10 @@ import mathimport osimport reimport struct-import subprocessimport sysfrom typing import Dict, List, Tuple-from _common import add_common, apply_common, default_font_file, die, emit, escape_filter_path, ffmpeg_base, info, print_json, probe, require_tool, run+from _common import add_common, apply_common, default_font_file, die, emit, escape_filter_path, ffmpeg_base, info, print_json, probe, require_tool, run, run_analysisSCORE_RE = re.compile(r"frame:(\d+)\s+pts:\d+\s+pts_time:([0-9.]+)")@@ -38,9 +37,8 @@ def detect_scenes(path: str, threshold: float, min_len: float, duration: float,a real cut is a one-frame spike. On real footage this roughly doubles precision atequal recall compared with the raw scdet threshold."""ffmpeg = require_tool("ffmpeg")- proc = subprocess.run([ffmpeg, "-hide_banner", "-nostdin", "-i", path, "-an", "-vf",- "scale=320:-2,scdet=threshold=0,metadata=print:file=-", "-f", "null", "-"],- stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)+ proc = run_analysis([ffmpeg, "-hide_banner", "-nostdin", "-i", path, "-an", "-vf",+ "scale=320:-2,scdet=threshold=0,metadata=print:file=-", "-f", "null", "-"])# No `sc_pass=1` on scdet: on FFmpeg 5.x that option means "pass only the frames whose# score exceeds the threshold", so every truly static frame (score exactly 0 -- a title# card, colour bars) is dropped before metadata=print and the frame numbers are re-counted@@ -90,8 +88,8 @@ def detect_scenes(path: str, threshold: float, min_len: float, duration: float,def audio_envelope(path: str, step_s: float) -> List[float]:ffmpeg = require_tool("ffmpeg")- proc = subprocess.run([ffmpeg, "-hide_banner", "-loglevel", "error", "-nostdin", "-i", path, "-vn", "-ac", "1", "-ar", "8000", "-f", "s16le", "-"],- stdout=subprocess.PIPE, stderr=subprocess.PIPE)+ proc = run_analysis([ffmpeg, "-hide_banner", "-loglevel", "error", "-nostdin", "-i", path, "-vn", "-ac", "1", "-ar", "8000", "-f", "s16le", "-"],+ check=False, text=False)n = len(proc.stdout) // 2if n == 0:return []diff --git a/scripts/sync.py b/scripts/sync.pyindex 40e1c8c..1e20678 100755--- a/scripts/sync.py+++ b/scripts/sync.py@@ -30,11 +30,10 @@ import jsonimport mathimport osimport struct-import subprocessimport sysfrom typing import List-from _common import video_args, add_common, apply_common, emit, aac_args, audio_codec_for, default_output, die, ffmpeg_base, info, probe, require_tool, run, x264_args+from _common import video_args, add_common, apply_common, emit, aac_args, audio_codec_for, default_output, die, ffmpeg_base, info, probe, require_tool, run, run_analysis, x264_argsSR = 8000 # decode sample rate@@ -59,7 +58,7 @@ def decode_mono(path: str, seconds: float, start: float = 0.0) -> List[float]:ffmpeg = require_tool("ffmpeg")cmd = [ffmpeg, "-hide_banner", "-loglevel", "error", "-nostdin", "-ss", f"{start:.3f}", "-i", path, "-t", f"{seconds:.3f}","-vn", "-ac", "1", "-ar", str(SR), "-f", "s16le", "-"]- proc = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)+ proc = run_analysis(cmd, check=False, text=False)if proc.returncode != 0 or not proc.stdout:die(f"could not decode audio from {path}:\n{proc.stderr.decode(errors='replace').strip()}", kind="ffmpeg")n = len(proc.stdout) // 2diff --git a/scripts/verify.py b/scripts/verify.pyindex 6ecd7dd..945193b 100755--- a/scripts/verify.py+++ b/scripts/verify.py@@ -24,7 +24,7 @@ import timefrom pathlib import Pathfrom typing import Dict, List-from _common import add_common, apply_common, die, emit, info, probe+from _common import STATE, add_common, apply_common, die, emit, info, probeHERE = Path(__file__).resolve().parentMEDIA_EXT = {".mp4", ".mov", ".m4v", ".mkv", ".webm", ".avi", ".mts", ".m2ts", ".mxf", ".wav", ".m4a", ".mp3", ".flac", ".aac"}@@ -176,13 +176,16 @@ def main() -> int:if args.report:Path(args.report).write_text(report, encoding="utf-8")info(f"wrote {args.report}")- if args.json:- emit(None, report=args.report, files=results, failed=failed, total=total)- else:+ if not args.json:print(report)if tmp and not args.keep:tmp.cleanup()- return 1 if failed else 0+ if failed:+ die(f"{failed} of {total} verification steps failed", kind="verification", output=None, dry_run=STATE.dry_run,+ report=args.report, files=results, failed=failed, total=total)+ if args.json:+ emit(None, report=args.report, files=results, failed=failed, total=total)+ return 0if __name__ == "__main__":diff --git a/tests/test_all.py b/tests/test_all.pyindex 21cd0b6..2990ae2 100644--- a/tests/test_all.py+++ b/tests/test_all.py@@ -1979,6 +1979,7 @@ class FFmpegSkillTests(unittest.TestCase):self.assertTrue((out / f"{Path(self.surround).stem}_st.mp4").exists())# a per-step timeout is reported per step, never raiseddata = json.loads(script("verify.py", self.src, "--quick", "--timeout", "0.01", "--json", expect_fail=True).stdout)+ self.assertEqual((data["status"], data["error"]["kind"]), ("failed", "verification"))timed_out = [s for f in data["files"] for s in f["steps"] if s["error"].startswith("timeout after")]self.assertTrue(timed_out, data)self.assertEqual(data["failed"], len(timed_out))@@ -2213,6 +2214,9 @@ class FFmpegSkillTests(unittest.TestCase):if not reels.exists():script("export.py", self.src, "--preset", "reels", "--fit", "crop", "-o", reels)data = json.loads(script("check.py", reels, "--platform", "reels", "--json", expect_fail=True).stdout)+ # a failed check is a failed run: status says so (before 1.4.3 it said "completed" next to exit 1)+ self.assertEqual((data["status"], data["error"]["kind"], data["error"]["code"]), ("failed", "verification", "VERIFICATION_FAILED"))+ self.assertFalse(data["ok"])names = {r["check"]: r["status"] for r in data["checks"]}kinds = {r["check"]: r["kind"] for r in data["checks"]}self.assertEqual(kinds["loudness"], "judgement")@@ -2475,7 +2479,13 @@ class FFmpegSkillTests(unittest.TestCase):proc = script("render.py", proj, "--fast", "--json", expect_fail=True)data = json.loads(proc.stdout)self.assertGreater(data["check"]["failed"], 0, data["check"])+ self.assertEqual((data["status"], data["error"]["kind"]), ("failed", "verification"))+ self.assertIn("aspect", data["error"]["message"])self.assertTrue(Path(data["output"]).exists(), "the deliverable is still written even though it fails delivery spec")+ # the outer --timeout reaches every stage: an impossible limit fails inside the first stage+ proc = script("render.py", proj, "--fast", "--timeout", "0.05", "--json", expect_fail=True)+ self.assertIn("time limit", proc.stderr)+ self.assertIn("--timeout 0.05", proc.stderr, "the flag must be forwarded to the child command line")def test_join_width_keeps_aspect(self):out = OUT / "join_w.mp4"diff --git a/tests/test_contract.py b/tests/test_contract.pyindex 2b805a1..73e0ad4 100644--- a/tests/test_contract.py+++ b/tests/test_contract.py@@ -1260,6 +1260,26 @@ class ContractTests(unittest.TestCase):self.assertEqual(json.loads(proc.stdout)["error"]["kind"], "timeout")self.assertLess(elapsed, 6, f"--progress waited {elapsed:.1f}s on a silent ffmpeg; the limit was 1 s")+ @unittest.skipIf(platform.system() == "Windows", "the failing ffmpeg is a #!/bin/sh shim on a POSIX-only PATH")+ def test_analysis_tools_report_an_ffmpeg_failure_instead_of_an_empty_result(self):+ """scenes.py and cropdetect.py ran their ffmpeg measurement with a bare subprocess.run and+ never looked at the return code: a file ffprobe accepts but ffmpeg cannot decode came back+ as "0 scenes" / "crop: none" with exit 0. The measurement now goes through run_analysis(),+ which applies --timeout and turns a non-zero exit into kind ffmpeg. An ffmpeg shim that+ fails on every call (ffprobe stays real, so probe() passes) reproduces the decode failure."""+ shim = self.out("fail_shim")+ shim.mkdir()+ (shim / "ffmpeg").write_text("#!/bin/sh\necho 'decode error' >&2\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"])+ for name, args in (("scenes", ()), ("cropdetect", ())):+ proc = tool(name, self.src, *args, "--json", env=env, check=False)+ self.assertNotEqual(proc.returncode, 0, f"{name} exited 0 over a failing ffmpeg")+ doc = json.loads(proc.stdout)+ self.assertEqual((doc["status"], doc["error"]["kind"]), ("failed", "ffmpeg"), name)+ self.assertIn("decode error", doc["error"]["message"], name)+def test_existing_output_warns_today_refuses_on_request_and_never_for_its_own_files(self):"""Every ffmpeg command carries -y (so a run never blocks on a y/N prompt), which meant anoutput path that already existed -- a previous deliverable, a mis-named source -- was