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: --timeout kills a hung ffmpeg and reports it; --overwrite guards existing outputs (#163)

Shogo Kajiyama69fd093aceaa
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 5927738..363cbd2 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -4,7 +4,8 @@
## Unreleased
-(nothing yet)
+- Every tool takes `--timeout SECONDS` (default 1800, `FFMPEG_SKILL_TIMEOUT`): a single ffmpeg run past the limit is killed, its partial output removed, and the failure reported as `kind: timeout` (exit 124) instead of hanging the caller.
+- Every tool takes `--overwrite`. An output path that already exists (and was not written by this run) now prints a warning; `FFMPEG_SKILL_NO_OVERWRITE=1` makes it a refusal today, and 2.0 will refuse by default.
## 1.4.0
diff --git a/README.md b/README.md
index 3f3da70..1994f0b 100644
--- a/README.md
+++ b/README.md
@@ -143,7 +143,7 @@ These are the rules the skill file gives the agent and the code enforces. Togeth
1. **Probe first.** No tool decides from the file name. `probe.py` measures duration, fps (with variable-frame-rate detection), resolution, rotation, bit depth, HDR format including Dolby Vision, colour tags and every audio stream before anything is cut.
2. **Lossless when possible.** `cut.py`, `join.py` and `loudness.py` stream-copy what they do not need to touch. Re-encoding happens only when it must: frame-accurate cuts, filters, format changes, or a keyframe farther than the tolerance.
-3. **Plan before render.** Every tool takes `--dry-run` (print the ffmpeg command lines, write nothing), `--json` (structured result with a probe of the output), `--fast` (preview quality) and `--progress` (percent and ETA). A test runs every tool under `--dry-run` behind a fake ffmpeg and asserts that no ffmpeg call happened and no file appeared.
+3. **Plan before render.** Every tool takes `--dry-run` (print the ffmpeg command lines, write nothing), `--json` (structured result with a probe of the output), `--fast` (preview quality), `--progress` (percent and ETA), `--timeout` (a hung ffmpeg is killed and reported, never waited on forever) and `--overwrite` (explicit consent before an existing output is replaced). A test runs every tool under `--dry-run` behind a fake ffmpeg and asserts that no ffmpeg call happened and no file appeared.
4. **Machine-readable contract.** `contract --json` describes all 42 tools: input schema generated from the parser, output schema, role, required and conditional FFmpeg capabilities, dry-run support, the verification tools to run afterwards, whether a visual check is required, `mutates_input: false`. `provides` lists all 40 by a cross-repository Capability id (`ffmpeg-skill.cut`, `ffmpeg-skill.loudness`, ...) for [`kajisho5/AI-video-production-OS`](https://github.com/kajisho5/AI-video-production-OS)'s `CapabilityContract.provides` — see `docs/contract.md`.
5. **Contract-derived MCP.** `mcp/server.py` builds its `tools/list` from the contract. Tool names, order and `inputSchema` cannot drift from the scripts; a test keeps the two byte-identical.
6. **Capability detection.** `doctor` reads `ffmpeg -encoders / -filters / -bsfs` and reports which of the components the tools need are present on this build (libx264, libass, zscale, loudnorm, xfade, …), before a job fails inside ffmpeg.
diff --git a/SKILL.md b/SKILL.md
index 43a4376..d142841 100644
--- a/SKILL.md
+++ b/SKILL.md
@@ -5,7 +5,7 @@ description: 'Edit video and audio with local FFmpeg from natural-language reque
# ffmpeg-skill
-Scripts live in `scripts/` next to this file; run them with `python3 <skill-dir>/scripts/<name>.py`. Every script has `--help`, and all of them accept `--dry-run`, `--json` (structured result with a probe of the output), `--fast` (preview quality) and `--progress`. Writing tools run nothing under `--dry-run`; `probe`/`check`/`sync`/`multicam`/`scenes`/`cropdetect`/`report` may still run ffmpeg/ffprobe to measure or analyse — they just don't write their final artifact; `verify` accepts the flag but ignores it. Exact per-tool semantics: `contract --json`'s `dry_run` field (or `docs/contract.md`). Details for every flag: `references/scripts.md`. Device-specific behaviour (iPhone HDR, GoPro, DJI, screen recordings, Zoom): `references/devices.md`.
+Scripts live in `scripts/` next to this file; run them with `python3 <skill-dir>/scripts/<name>.py`. Every script has `--help`, and all of them accept `--dry-run`, `--json` (structured result with a probe of the output), `--fast` (preview quality), `--progress`, `--timeout SECONDS` (a single ffmpeg run is killed past this and reported as `kind: timeout`; default 1800) and `--overwrite` (consent to replace an output that already exists; without it the tool warns today and refuses from 2.0). Writing tools run nothing under `--dry-run`; `probe`/`check`/`sync`/`multicam`/`scenes`/`cropdetect`/`report` may still run ffmpeg/ffprobe to measure or analyse — they just don't write their final artifact; `verify` accepts the flag but ignores it. Exact per-tool semantics: `contract --json`'s `dry_run` field (or `docs/contract.md`). Details for every flag: `references/scripts.md`. Device-specific behaviour (iPhone HDR, GoPro, DJI, screen recordings, Zoom): `references/devices.md`.
## Workflow (always follow this order)
@@ -41,7 +41,9 @@ Scripts live in `scripts/` next to this file; run them with `python3 <skill-dir>
be a placeholder, not a computed preview — see `docs/contract.md`). Use
them to confirm a plan before long encodes and to report exact facts.
`--fast` gives a quick preview-quality render (x264 veryfast), `--progress`
- prints percent and ETA on stderr for long encodes.
+ prints percent and ETA on stderr for long encodes. Never point `-o` at a file
+ you did not create in this job unless the user asked for it to be replaced;
+ pass `--overwrite` only then.
4. **Chain operations in a sensible order.** Colour (HDR→SDR / LUT) → cut →
join → silence → fit → caption/overlay → sync → audio → loudness → export.
Do frame changes (fit/crop) before captions and overlays so text is sized
diff --git a/docs/contract.md b/docs/contract.md
index 0b3bd50..7408d76 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", "message": "...",
- "code": "INPUT_INVALID | DEPENDENCY_MISSING | FFMPEG_EXECUTION_FAILED | OUTPUT_INVALID | INTERNAL_ERROR",
+ "error": {"kind": "input | ffmpeg | output | missing_tool | timeout", "message": "...",
+ "code": "INPUT_INVALID | DEPENDENCY_MISSING | FFMPEG_EXECUTION_FAILED | OUTPUT_INVALID | TIMEOUT | INTERNAL_ERROR",
"retryable": false},
"commands": ["ffmpeg ..."]}
```
diff --git a/references/scripts.md b/references/scripts.md
index 910bf58..cc585c9 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`, `-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) 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`).
## Contents
- probe.py — inspect
diff --git a/scripts/_common.py b/scripts/_common.py
index 71aea99..6c64b09 100755
--- a/scripts/_common.py
+++ b/scripts/_common.py
@@ -62,8 +62,25 @@ ERROR_CODE = {
"missing_tool": "DEPENDENCY_MISSING",
"ffmpeg": "FFMPEG_EXECUTION_FAILED",
"output": "OUTPUT_INVALID",
+ "timeout": "TIMEOUT",
}
+# Wall-clock ceiling for one ffmpeg/ffprobe invocation, in seconds. A hung ffmpeg (a build
+# that deadlocks on a filter combination, a stalled network mount, an input that never ends)
+# used to hang the calling agent with it, with no error document and no way out short of
+# killing the process by hand. The ceiling is generous on purpose: it exists to turn a hang
+# into a reported failure, not to police slow encodes. --timeout and FFMPEG_SKILL_TIMEOUT
+# override it; 0 disables it.
+DEFAULT_TIMEOUT = 1800.0
+PROBE_TIMEOUT = 120.0
+
+
+def _env_timeout() -> float:
+ try:
+ return max(0.0, float(os.environ.get("FFMPEG_SKILL_TIMEOUT", DEFAULT_TIMEOUT)))
+ except ValueError:
+ return DEFAULT_TIMEOUT
+
# None of the four kinds above are retryable in practice: an "input"/"missing_tool" failure is
# always deterministic (the same bad path or absent binary fails identically every time), and a
# "ffmpeg"/"output" failure -- while it COULD in principle be caused by a transient environment
@@ -182,8 +199,8 @@ class Context:
it obvious what run()/emit() depend on and lets tests reset it with ``STATE.reset()``.
"""
- __slots__ = ("dry_run", "json", "progress", "fast", "duration_hint", "commands")
- _KEYS = ("dry_run", "json", "progress", "fast", "duration_hint", "commands")
+ __slots__ = ("dry_run", "json", "progress", "fast", "duration_hint", "commands", "timeout", "overwrite", "written")
+ _KEYS = ("dry_run", "json", "progress", "fast", "duration_hint", "commands", "timeout", "overwrite", "written")
def __init__(self) -> None:
self.reset()
@@ -195,6 +212,9 @@ class Context:
self.fast = False # x264 preset forced to veryfast
self.duration_hint: Optional[float] = None # expected output length, for the progress percent
self.commands: List[str] = [] # every ffmpeg command line, for --json and --dry-run
+ self.timeout: float = _env_timeout() # seconds per ffmpeg invocation, 0 = none
+ self.overwrite = False # --overwrite: an existing output may be replaced
+ self.written: set = set() # output paths this process has written itself
# mapping-style access kept for backwards compatibility
def __getitem__(self, key: str) -> Any:
@@ -221,6 +241,11 @@ def add_common(ap: "argparse.ArgumentParser") -> None:
g.add_argument("--json", action="store_true", help="print a JSON result (output, probe, commands) on stdout instead of the path")
g.add_argument("--progress", action="store_true", help="show percent / ETA on stderr while ffmpeg encodes")
g.add_argument("--fast", action="store_true", help="preview quality: x264 preset veryfast (overrides --preset) for quick iterations")
+ if "--timeout" not in ap._option_string_actions: # verify.py defines its own per-step --timeout; apply_common reads either
+ g.add_argument("--timeout", type=float, default=None, metavar="SECONDS",
+ help=f"kill any single ffmpeg run that exceeds this many seconds and report kind=timeout (default {DEFAULT_TIMEOUT:.0f}, or FFMPEG_SKILL_TIMEOUT; 0 = no limit)")
+ g.add_argument("--overwrite", action="store_true",
+ help="allow replacing an output file that already exists (without it a warning is printed today; from 2.0 an existing output is refused, and FFMPEG_SKILL_NO_OVERWRITE=1 opts into that now)")
def apply_common(args: "argparse.Namespace") -> None:
@@ -228,6 +253,9 @@ def apply_common(args: "argparse.Namespace") -> None:
STATE.json = bool(getattr(args, "json", False))
STATE.progress = bool(getattr(args, "progress", False))
STATE.fast = bool(getattr(args, "fast", False))
+ STATE.overwrite = bool(getattr(args, "overwrite", False))
+ if getattr(args, "timeout", None) is not None:
+ STATE.timeout = max(0.0, float(args.timeout))
if STATE.fast and getattr(args, "preset", None) in X264_PRESETS:
args.preset = "veryfast"
@@ -312,6 +340,46 @@ def _check_no_overwrite_input(cmd: Sequence[str]) -> None:
continue
+def _check_existing_output(cmd: Sequence[str]) -> None:
+ """An output path that already exists is someone's file: a previous result, a source the
+ agent mis-named, a deliverable from another run. ffmpeg's -y (which every command carries so
+ a run never blocks on a y/N prompt) would replace it without a word. Until 2.0 this only
+ warns, per docs/contract.md's deprecation policy; FFMPEG_SKILL_NO_OVERWRITE=1 opts into the
+ 2.0 behaviour (refuse) today, and --overwrite is the explicit consent either way. Paths this
+ process wrote itself (a two-pass tool, a copy-then-re-encode fallback) are never in question."""
+ output = cmd[-1]
+ if STATE.overwrite or output in ("-",) or output.startswith("pipe:") or output.startswith("-"):
+ return
+ try:
+ exists = os.path.isfile(output)
+ real = os.path.realpath(output)
+ except OSError:
+ return
+ if not exists or real in STATE.written:
+ return
+ if os.environ.get("FFMPEG_SKILL_NO_OVERWRITE", "") not in ("", "0"):
+ die(f"refusing to overwrite existing output {output!r}: pass --overwrite to replace it, or choose another -o path", kind="input")
+ info(f"warning: {output} already exists and will be overwritten (pass --overwrite to confirm; "
+ f"from 2.0 an existing output is refused without it, FFMPEG_SKILL_NO_OVERWRITE=1 enables that now)")
+
+
+def _remember_output(cmd: Sequence[str]) -> None:
+ output = cmd[-1]
+ if output == "-" or output.startswith("pipe:") or output.startswith("-"):
+ return
+ try:
+ STATE.written.add(os.path.realpath(output))
+ except OSError:
+ pass
+
+
+def _timed_out(cmd: Sequence[str], seconds: float) -> "None":
+ _cleanup_partial_output(cmd)
+ die(f"{os.path.basename(cmd[0])} exceeded the {seconds:.0f} s time limit and was killed; nothing was written. "
+ f"Raise --timeout (or FFMPEG_SKILL_TIMEOUT) if the job is genuinely that long, or check the input for a stall",
+ code=124, kind="timeout")
+
+
def run(cmd: Sequence[str], *, quiet: bool = False, check: bool = True) -> subprocess.CompletedProcess:
"""Run a command, echoing it to stderr unless quiet. Exits on failure when check=True.
@@ -322,6 +390,7 @@ def run(cmd: Sequence[str], *, quiet: bool = False, check: bool = True) -> subpr
is_ffmpeg = _is_ffmpeg(cmd)
if is_ffmpeg:
_check_no_overwrite_input(cmd)
+ _check_existing_output(cmd)
STATE.commands.append(_cmdline(cmd))
if not quiet:
info(("[dry-run] $ " if STATE.dry_run and is_ffmpeg else "$ ") + _cmdline(cmd))
@@ -346,9 +415,23 @@ def run_keeping_subtitles(cmd: List[str], output: str) -> bool:
return True
+def _limit_for(cmd: Sequence[str]) -> Optional[float]:
+ """The wall-clock ceiling for this command: ffprobe (and other read-only probes) get a fixed
+ short one, ffmpeg the configured one; None means unlimited."""
+ if not _is_ffmpeg(cmd):
+ return PROBE_TIMEOUT if STATE.timeout else None
+ return STATE.timeout or None
+
+
def _run_captured(cmd: List[str], check: bool) -> subprocess.CompletedProcess:
"""Plain run with stdout/stderr captured."""
- proc = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
+ limit = _limit_for(cmd)
+ try:
+ proc = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, timeout=limit)
+ except subprocess.TimeoutExpired:
+ _timed_out(cmd, limit or 0)
+ if proc.returncode == 0 and _is_ffmpeg(cmd):
+ _remember_output(cmd)
if proc.returncode != 0:
# Cleanup happens for every failed ffmpeg invocation, not just the check=True/_fail()
# path: a handful of scripts (cut.py, loudness.py, silence.py, sync.py) call run() with
@@ -377,10 +460,17 @@ def _run_with_progress(cmd: List[str], check: bool) -> subprocess.CompletedProce
total = STATE.duration_hint or 0.0
full = cmd[:1] + ["-progress", "pipe:1", "-nostats"] + cmd[1:]
t0 = time.time()
+ limit = _limit_for(cmd)
proc = subprocess.Popen(full, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
last = ""
assert proc.stdout is not None
for line in proc.stdout:
+ if limit and time.time() - t0 > limit:
+ proc.kill()
+ proc.communicate()
+ if last:
+ sys.stderr.write("\r" + " " * len(last) + "\r")
+ _timed_out(cmd, limit)
if line.startswith("out_time_us=") or line.startswith("out_time_ms="):
try:
done = int(line.split("=")[1]) / 1_000_000
@@ -391,9 +481,16 @@ def _run_with_progress(cmd: List[str], check: bool) -> subprocess.CompletedProce
sys.stderr.write(msg)
sys.stderr.flush()
last = msg
- _, err = proc.communicate()
+ try:
+ _, err = proc.communicate(timeout=(max(5.0, limit - (time.time() - t0)) if limit else None))
+ except subprocess.TimeoutExpired:
+ proc.kill()
+ proc.communicate()
+ _timed_out(cmd, limit or 0)
if last:
sys.stderr.write("\r" + " " * len(last) + "\r")
+ if proc.returncode == 0:
+ _remember_output(cmd)
if proc.returncode != 0:
_cleanup_partial_output(cmd)
if check:
diff --git a/scripts/_contract.py b/scripts/_contract.py
index 5347e38..df42ab8 100644
--- a/scripts/_contract.py
+++ b/scripts/_contract.py
@@ -329,7 +329,7 @@ def input_schema(parser: argparse.ArgumentParser) -> Dict[str, Any]:
props: Dict[str, Any] = {}
required: List[str] = []
positional: List[str] = []
- common = {"dry_run", "json", "progress", "fast"}
+ common = {"dry_run", "json", "progress", "fast", "timeout", "overwrite"}
for action in parser._actions:
if isinstance(action, argparse._HelpAction):
continue
@@ -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"},
+ "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"},
"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/tests/fixtures/mcp_tools.json b/tests/fixtures/mcp_tools.json
index 065c9e9..51b88db 100644
--- a/tests/fixtures/mcp_tools.json
+++ b/tests/fixtures/mcp_tools.json
@@ -41,9 +41,11 @@
"music_loop",
"music_volume",
"output",
+ "overwrite",
"progress",
"replace",
"stereo",
+ "timeout",
"voice"
],
"required": []
@@ -63,8 +65,10 @@
"height",
"json",
"output",
+ "overwrite",
"preset",
"progress",
+ "timeout",
"width"
],
"required": []
@@ -78,8 +82,10 @@
"folder",
"force",
"json",
+ "overwrite",
"progress",
"recipe",
+ "timeout",
"watch",
"work"
],
@@ -101,9 +107,11 @@
"insert",
"json",
"output",
+ "overwrite",
"pad_color",
"preset",
- "progress"
+ "progress",
+ "timeout"
],
"required": []
},
@@ -138,6 +146,7 @@
"outline",
"outline_color",
"output",
+ "overwrite",
"position",
"preset",
"progress",
@@ -145,6 +154,7 @@
"size",
"srt",
"text",
+ "timeout",
"transcribe",
"write_ass",
"write_srt"
@@ -164,8 +174,10 @@
"max_duration",
"max_mb",
"no_loudness",
+ "overwrite",
"platform",
"progress",
+ "timeout",
"tp"
],
"required": []
@@ -196,6 +208,7 @@
"lut",
"lut_strength",
"output",
+ "overwrite",
"peak",
"preset",
"progress",
@@ -203,6 +216,7 @@
"saturation",
"strip_dovi",
"temperature",
+ "timeout",
"tint",
"to_sdr",
"tonemap"
@@ -221,8 +235,10 @@
"input",
"json",
"output",
+ "overwrite",
"preset",
"progress",
+ "timeout",
"width",
"x",
"y"
@@ -238,10 +254,12 @@
"input",
"json",
"limit",
+ "overwrite",
"progress",
"round_to",
"samples",
- "seconds"
+ "seconds",
+ "timeout"
],
"required": []
},
@@ -258,10 +276,12 @@
"input",
"json",
"output",
+ "overwrite",
"preset",
"progress",
"segments",
"start",
+ "timeout",
"tolerance"
],
"required": []
@@ -279,9 +299,11 @@
"mode",
"only_interlaced",
"output",
+ "overwrite",
"parity",
"preset",
- "progress"
+ "progress",
+ "timeout"
],
"required": []
},
@@ -301,9 +323,11 @@
"luma_spatial",
"luma_temporal",
"output",
+ "overwrite",
"preset",
"progress",
- "strength"
+ "strength",
+ "timeout"
],
"required": []
},
@@ -321,11 +345,13 @@
"list",
"no_scale",
"output",
+ "overwrite",
"pad_blur",
"pad_color",
"pad_fill",
"preset",
- "progress"
+ "progress",
+ "timeout"
],
"required": []
},
@@ -351,6 +377,7 @@
"max_speed",
"method",
"output",
+ "overwrite",
"pad_blur",
"pad_color",
"pad_fill",
@@ -358,6 +385,7 @@
"progress",
"rotate",
"smooth",
+ "timeout",
"width"
],
"required": []
@@ -375,8 +403,10 @@
"json",
"mode",
"output",
+ "overwrite",
"preset",
- "progress"
+ "progress",
+ "timeout"
],
"required": []
},
@@ -397,6 +427,7 @@
"json",
"name",
"output",
+ "overwrite",
"position",
"preset",
"primary",
@@ -406,6 +437,7 @@
"subtitle",
"template",
"text_color",
+ "timeout",
"title"
],
"required": []
@@ -431,10 +463,12 @@
"json",
"label",
"output",
+ "overwrite",
"pad",
"preset",
"progress",
- "rows"
+ "rows",
+ "timeout"
],
"required": []
},
@@ -451,9 +485,11 @@
"input",
"json",
"output",
+ "overwrite",
"pan",
"preset",
"progress",
+ "timeout",
"width",
"zoom",
"zoom_amount"
@@ -475,10 +511,12 @@
"inputs",
"json",
"output",
+ "overwrite",
"pad_color",
"preset",
"progress",
"sample_rate",
+ "timeout",
"transition",
"width"
],
@@ -496,8 +534,10 @@
"json",
"no_timecode",
"output",
+ "overwrite",
"progress",
"tiles",
+ "timeout",
"width"
],
"required": []
@@ -513,8 +553,10 @@
"input",
"json",
"output",
+ "overwrite",
"preset",
"progress",
+ "timeout",
"times"
],
"required": []
@@ -532,8 +574,10 @@
"lufs",
"measure_only",
"output",
+ "overwrite",
"progress",
"sample_rate",
+ "timeout",
"tp"
],
"required": []
@@ -554,7 +598,9 @@
"input",
"json",
"output",
+ "overwrite",
"progress",
+ "timeout",
"title"
],
"required": []
@@ -577,9 +623,11 @@
"max_offset",
"offsets_only",
"output",
+ "overwrite",
"preset",
"progress",
"switch",
+ "timeout",
"width"
],
"required": []
@@ -613,6 +661,7 @@
"margin",
"opacity",
"output",
+ "overwrite",
"position",
"preset",
"progress",
@@ -620,6 +669,7 @@
"scale_percent",
"start",
"text",
+ "timeout",
"video"
],
"required": []
@@ -636,9 +686,11 @@
"input",
"json",
"output",
+ "overwrite",
"preset",
"progress",
- "start"
+ "start",
+ "timeout"
],
"required": []
},
@@ -653,7 +705,9 @@
"field",
"inputs",
"json",
- "progress"
+ "overwrite",
+ "progress",
+ "timeout"
],
"required": []
},
@@ -669,8 +723,10 @@
"json",
"no_audio",
"output",
+ "overwrite",
"progress",
"scale",
+ "timeout",
"width"
],
"required": []
@@ -691,8 +747,10 @@
"json",
"mode",
"output",
+ "overwrite",
"preset",
"progress",
+ "timeout",
"width",
"x",
"y"
@@ -708,9 +766,11 @@
"init",
"json",
"keep",
+ "overwrite",
"progress",
"project",
"stop_after",
+ "timeout",
"work"
],
"required": []
@@ -728,8 +788,10 @@
"no_sheets",
"notes",
"output",
+ "overwrite",
"platform",
"progress",
+ "timeout",
"title"
],
"required": []
@@ -745,8 +807,10 @@
"json",
"no_audio",
"output",
+ "overwrite",
"preset",
- "progress"
+ "progress",
+ "timeout"
],
"required": []
},
@@ -763,12 +827,14 @@
"max_scene",
"min_scene",
"no_timecode",
+ "overwrite",
"progress",
"rank_by",
"ratio",
"sheet",
"target",
- "threshold"
+ "threshold",
+ "timeout"
],
"required": []
},
@@ -784,10 +850,12 @@
"height",
"json",
"output",
+ "overwrite",
"pattern",
"preset",
"progress",
"start_number",
+ "timeout",
"width"
],
"required": []
@@ -807,9 +875,11 @@
"min_keep",
"min_silence",
"output",
+ "overwrite",
"preset",
"progress",
- "threshold"
+ "threshold",
+ "timeout"
],
"required": []
},
@@ -823,9 +893,11 @@
"input",
"json",
"output",
+ "overwrite",
"preset",
"progress",
- "segments"
+ "segments",
+ "timeout"
],
"required": []
},
@@ -845,11 +917,13 @@
"interp",
"json",
"output",
+ "overwrite",
"pitch",
"preset",
"progress",
"roll",
"stereo",
+ "timeout",
"v_fov",
"width",
"yaw"
@@ -867,10 +941,12 @@
"input",
"json",
"output",
+ "overwrite",
"preset",
"progress",
"shakiness",
"smoothing",
+ "timeout",
"tripod",
"zoom"
],
@@ -891,8 +967,10 @@
"input",
"json",
"output",
+ "overwrite",
"preset",
- "progress"
+ "progress",
+ "timeout"
],
"required": []
},
@@ -910,11 +988,13 @@
"json",
"max_offset",
"output",
+ "overwrite",
"progress",
"reference",
"replace_audio",
"second",
"step_ms",
+ "timeout",
"trim_second"
],
"required": []
@@ -928,6 +1008,7 @@
"json",
"keep",
"out",
+ "overwrite",
"paths",
"progress",
"quick",
@@ -952,10 +1033,12 @@
"input",
"json",
"output",
+ "overwrite",
"preset",
"progress",
"split_channels",
"style",
+ "timeout",
"waveform_mode",
"width"
],
diff --git a/tests/test_contract.py b/tests/test_contract.py
index 5ec3f53..5e367ca 100644
--- a/tests/test_contract.py
+++ b/tests/test_contract.py
@@ -1183,6 +1183,66 @@ class ContractTests(unittest.TestCase):
self.assertAlmostEqual(reprobed2["duration"], 2.0, delta=0.6)
# ------------------------------------------------------------------ fail loudly
+ def test_timeout_kills_a_hung_ffmpeg_and_reports_kind_timeout(self):
+ """A build that deadlocks on a filter combination (conda-forge's 7.1.1 on tpad+adelay,
+ seen while chasing #156) used to hang the calling agent with it: no error document, no
+ partial-output cleanup, nothing short of a manual kill. --timeout (default 1800 s,
+ FFMPEG_SKILL_TIMEOUT) turns that into a failure the agent can read: kind timeout, code
+ TIMEOUT, exit 124, the partial output removed, the command still recorded. A limit far
+ below what any encode of the 6 s fixture can meet is the cheapest reliable reproduction;
+ verify.py keeps its own per-step --timeout, which applies the same way."""
+ out = self.out("timeout.mp4")
+ proc = tool("fit", self.src, "--aspect", "9:16", "--timeout", "0.05", "--json", "-o", out, check=False)
+ self.assertEqual(proc.returncode, 124, proc.stderr[-300:])
+ doc = json.loads(proc.stdout)
+ self.assertEqual((doc["status"], doc["error"]["kind"], doc["error"]["code"], doc["exit_code"]), ("failed", "timeout", "TIMEOUT", 124))
+ self.assertIn("--timeout", doc["error"]["message"])
+ self.assertTrue(doc["commands"] and "ffmpeg" in doc["commands"][0])
+ self.assertFalse(out.exists(), "a killed encode must not leave a partial file behind")
+ # 0 disables the limit; a generous limit does not interfere with a normal short run
+ self.assertEqual(tool("cut", self.src, "--start", "0", "--end", "1", "--timeout", "0", "-o", self.out("timeout_off.mp4")).returncode, 0)
+ env = dict(os.environ, FFMPEG_SKILL_TIMEOUT="0.05")
+ proc = tool("fit", self.src, "--aspect", "9:16", "--json", "-o", self.out("timeout_env.mp4"), env=env, check=False)
+ self.assertEqual(json.loads(proc.stdout)["error"]["kind"], "timeout", "the env default applies without the flag")
+ self.assertIn("timeout", self.contract["json_output"]["error_kinds"])
+
+ 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 an
+ output path that already existed -- a previous deliverable, a mis-named source -- was
+ replaced without a word. Per the 1.x deprecation policy the default stays but warns;
+ FFMPEG_SKILL_NO_OVERWRITE=1 opts into the 2.0 refusal now; --overwrite is the explicit
+ consent in both modes; a path this same run wrote (two-pass tools, copy-then-re-encode
+ fallbacks) is never treated as someone else's file."""
+ out = self.out("exists.mp4")
+ first = tool("cut", self.src, "--start", "0", "--end", "1", "-o", out)
+ self.assertNotIn("already exists", first.stderr, "a fresh path must not warn")
+ again = tool("cut", self.src, "--start", "0", "--end", "1", "-o", out)
+ self.assertEqual(again.returncode, 0)
+ self.assertIn("already exists and will be overwritten", again.stderr)
+ self.assertIn("--overwrite", again.stderr)
+ quiet = tool("cut", self.src, "--start", "0", "--end", "1", "--overwrite", "-o", out)
+ self.assertNotIn("already exists", quiet.stderr, "--overwrite is the consent; no warning")
+ env = dict(os.environ, FFMPEG_SKILL_NO_OVERWRITE="1")
+ proc = tool("cut", self.src, "--start", "0", "--end", "1", "--json", "-o", out, env=env, check=False)
+ self.assertNotEqual(proc.returncode, 0)
+ doc = json.loads(proc.stdout)
+ self.assertEqual((doc["status"], doc["error"]["kind"]), ("failed", "input"))
+ self.assertIn("refusing to overwrite", doc["error"]["message"])
+ self.assertEqual(doc["commands"], [], "refused before any ffmpeg ran")
+ size_before = out.stat().st_size
+ self.assertEqual(tool("cut", self.src, "--start", "0", "--end", "2", "--overwrite", "-o", out, env=env).returncode, 0)
+ self.assertNotEqual(out.stat().st_size, size_before, "--overwrite replaced the file under the strict mode")
+ # a tool that writes its own output twice in one run (color --retag's copy-then-re-encode
+ # fallback path is exercised elsewhere); the guard keys on paths written by this process
+ fresh = self.out("own.mp4")
+ proc = tool("cut", self.src, "--start", "0", "--end", "1", "-o", fresh, env=env)
+ self.assertEqual(proc.returncode, 0)
+ self.assertNotIn("refusing", proc.stderr)
+ # dry-run never touches the file but still says what it would do
+ dry = tool("cut", self.src, "--start", "0", "--end", "1", "--dry-run", "-o", out)
+ self.assertIn("already exists", dry.stderr)
+ self.assertEqual(out.stat().st_size, os.path.getsize(out))
+
def _fails(self, name, *args, kind=None, code=None):
proc = tool(name, *args, "--json", check=False)
self.assertNotEqual(proc.returncode, 0, f"{name} {args}: exit 0 on a failure")