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: outer wall-clock ceiling on every sibling-script run; scenes and sync share one PCM decode and envelope (#178)

Shogo Kajiyama7b3020cf6724
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 8e6f605..e2b5f8a 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,8 @@
- `docs/design-decisions.md` lists behaviours that look like bugs but are decisions (timeout 0, dry-run measurements, BT.2020 handling, overwrite policy, `speed: 0`, packaging), each with its rationale and pinning test; `AGENTS.md`, CONTRIBUTING and the bug template point reviewers to it first.
- Docs: README no longer claims media ffmpeg calls have no timeout; tool counts read 42 everywhere (the count test now catches the "all N by" / "same N names" phrasings); `docs/contract.md` lists every dry-run exception; the error-kind list is identical in SKILL.md, README and the contract; SKILL.md states the dry-run exceptions once and moves the Windows drawtext story to `references/ci-platform-pitfalls.md`; CODE_OF_CONDUCT.md added.
- The npm package ships `references/scripts.md`, `devices.md` and `ci-platform-pitfalls.md` only; the maintainer diary `process-pitfalls.md` stays in the repository. Internal: the `Context` dict-style shims are gone, every call site uses attributes.
+- Every sibling-script run (`render.py`/`batch.py`/`report.py` stages and the MCP server's dispatch) has an outer wall-clock ceiling of 4x the per-ffmpeg `--timeout` plus 60 s, so a child hung for a reason other than ffmpeg is killed and reported as `kind: timeout`. The MCP caller's `timeout` argument sets both.
+- `scenes.py` and `sync.py` share one PCM decode and RMS-envelope implementation (`decode_pcm_mono`/`rms_envelope` in `_common.py`); results are unchanged.
## 1.4.5
diff --git a/mcp/server.py b/mcp/server.py
index 89a9c78..59b7d71 100755
--- a/mcp/server.py
+++ b/mcp/server.py
@@ -26,6 +26,7 @@ PROTOCOL_VERSION = "2024-11-05"
sys.path.insert(0, str(SCRIPTS))
import _contract # noqa: E402 (the contract is the only source of tool names, schemas and argument mapping)
+import _common # noqa: E402 (run_tool: the outer wall-clock ceiling on a dispatched tool)
_SPECS: Dict[str, Dict[str, Any]] = {}
@@ -91,7 +92,14 @@ def call_tool(name: str, args: Dict[str, Any]) -> Dict[str, Any]:
if name not in specs() or not script.exists():
return {"isError": True, "content": [{"type": "text", "text": f"unknown tool {name}"}]}
argv = build_argv(name, args or {})
- proc = subprocess.run([sys.executable, str(script)] + argv, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
+ # The child enforces --timeout on each ffmpeg call; this outer ceiling (4x that plus 60 s)
+ # is the only thing that ends a child hung for any other reason. The caller's own `timeout`
+ # argument sets both; otherwise FFMPEG_SKILL_TIMEOUT / the 1800 s default.
+ try:
+ per_call = float((args or {}).get("timeout", _common._env_timeout()))
+ except (TypeError, ValueError):
+ per_call = _common._env_timeout()
+ proc = _common.run_tool([str(script)] + argv, per_call=per_call)
stdout = proc.stdout.strip()
text = stdout
structured = None
diff --git a/scripts/_common.py b/scripts/_common.py
index 820dfd9..5bbeba3 100755
--- a/scripts/_common.py
+++ b/scripts/_common.py
@@ -479,6 +479,75 @@ def run_analysis(cmd: Sequence[str], *, check: bool = True, text: bool = True) -
return proc
+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
+ under its own --timeout, so the outer ceiling is a multiple of that plus a margin: it never
+ fires first on a healthy run, and it is the only thing that ends a child hung for a reason
+ that is not ffmpeg (a stuck import, a wedged pipe). None when the per-call limit is 0."""
+ limit = STATE.timeout if per_call is None else per_call
+ return (limit * 4 + 60) if limit else None
+
+
+def run_tool(argv: Sequence[str], *, per_call: Optional[float] = None) -> subprocess.CompletedProcess:
+ """Run a sibling script (`argv[0]` is the script path) under child_limit(). On overrun the
+ child is killed and a CompletedProcess is returned whose stdout is this skill's own failure
+ document (kind timeout, exit 124), so callers that parse the child's --json see a timeout
+ exactly as they would from the child itself."""
+ limit = child_limit(per_call)
+ try:
+ return subprocess.run([sys.executable] + list(argv), stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, timeout=limit)
+ except subprocess.TimeoutExpired as e:
+ name = os.path.basename(str(argv[0]))
+ msg = f"{name} did not finish within {limit:.0f} s (4x the per-ffmpeg --timeout plus 60 s) and was killed"
+ doc = {"status": "failed", "exit_code": 124,
+ "error": {"kind": "timeout", "message": msg, "code": ERROR_CODE["timeout"], "retryable": ERROR_RETRYABLE},
+ "commands": []}
+ partial = e.stderr.decode(errors="replace") if isinstance(e.stderr, bytes) else (e.stderr or "")
+ return subprocess.CompletedProcess(list(argv), 124, json.dumps(doc), partial + f"\nerror: {msg}\n")
+
+
+def decode_pcm_mono(path: str, sample_rate: int, seconds: Optional[float] = None, start: float = 0.0,
+ *, check: bool = True) -> List[float]:
+ """Decode (part of) a file's audio to mono float samples in [-1, 1) at `sample_rate` via a
+ single ffmpeg pass under --timeout. Shared by scenes.py (audio envelope for cut scoring) and
+ sync.py (cross-correlation); an undecodable input is kind ffmpeg when check=True, else []."""
+ ffmpeg = require_tool("ffmpeg")
+ cmd = [ffmpeg, "-hide_banner", "-loglevel", "error", "-nostdin"]
+ if start:
+ cmd += ["-ss", f"{start:.3f}"]
+ cmd += ["-i", path]
+ if seconds is not None:
+ cmd += ["-t", f"{seconds:.3f}"]
+ cmd += ["-vn", "-ac", "1", "-ar", str(sample_rate), "-f", "s16le", "-"]
+ proc = run_analysis(cmd, check=False, text=False)
+ if proc.returncode != 0 or not proc.stdout:
+ if check:
+ die(f"could not decode audio from {path}:\n{proc.stderr.decode(errors='replace').strip()}", kind="ffmpeg")
+ return []
+ n = len(proc.stdout) // 2
+ import struct
+ return [v / 32768.0 for v in struct.unpack(f"<{n}h", proc.stdout[: n * 2])]
+
+
+def rms_envelope(samples: Sequence[float], step: int, *, full_blocks_only: bool = False, remove_mean: bool = False) -> List[float]:
+ """RMS per block of `step` samples. full_blocks_only drops a short tail block (sync.py: every
+ block must be the same length for the correlation); remove_mean subtracts the envelope's mean
+ (sync.py: so silence does not correlate). scenes.py keeps the tail and the absolute level."""
+ import math
+ step = max(1, int(step))
+ n = len(samples)
+ stop = n - step + 1 if full_blocks_only else n
+ env: List[float] = []
+ for i in range(0, max(0, stop), step):
+ block = samples[i:i + step]
+ env.append(math.sqrt(sum(x * x for x in block) / len(block)))
+ if remove_mean and env:
+ mean = sum(env) / len(env)
+ env = [e - mean for e in env]
+ return env
+
+
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
diff --git a/scripts/batch.py b/scripts/batch.py
index de85924..d95b355 100755
--- a/scripts/batch.py
+++ b/scripts/batch.py
@@ -26,13 +26,12 @@ import argparse
import hashlib
import json
import os
-import subprocess
import sys
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
+from _common import STATE, add_common, apply_common, child_args, die, emit, info, run_tool
HERE = Path(__file__).resolve().parent
MEDIA_EXT = {".mp4", ".mov", ".m4v", ".mkv", ".webm", ".avi", ".mts", ".m2ts", ".mxf", ".wav", ".m4a", ".mp3", ".flac"}
@@ -78,9 +77,9 @@ 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:] + 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)
+ cmd = [str(HERE / script)] + argv[1:] + child_args()
+ info(" → " + " ".join(os.path.basename(c) if i < 1 else c for i, c in enumerate(cmd)))
+ proc = run_tool(cmd)
if proc.returncode != 0:
info(" " + "\n ".join(proc.stderr.strip().splitlines()[-4:]))
return False
diff --git a/scripts/render.py b/scripts/render.py
index b780a17..505d988 100755
--- a/scripts/render.py
+++ b/scripts/render.py
@@ -51,12 +51,11 @@ Examples:
import argparse
import json
import os
-import subprocess
import sys
from pathlib import Path
from typing import Any, Dict, List
-from _common import STATE, add_common, apply_common, child_args, die, emit, info, probe
+from _common import STATE, add_common, apply_common, child_args, die, emit, info, probe, run_tool
HERE = Path(__file__).resolve().parent
@@ -80,9 +79,9 @@ 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 []) + child_args() + ["--json"]
- info("→ " + " ".join(os.path.basename(c) if i < 2 else c for i, c in enumerate(cmd[:-1])))
- proc = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
+ cmd = [str(HERE / script)] + [str(a) for a in argv] + (extra or []) + child_args() + ["--json"]
+ info("→ " + " ".join(os.path.basename(c) if i < 1 else c for i, c in enumerate(cmd[:-1])))
+ proc = run_tool(cmd)
for line in proc.stderr.splitlines():
if line.startswith("$ ") or line.startswith("[dry-run]"):
STATE.commands.append(line[2:] if line.startswith("$ ") else line)
@@ -359,7 +358,7 @@ def main() -> int:
check_result = None
exit_code = 0
if ck and ck.get("platform") and not STATE.dry_run:
- proc = subprocess.run([sys.executable, str(HERE / "check.py"), output, "--platform", ck["platform"], "--json"], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
+ proc = run_tool([str(HERE / "check.py"), output, "--platform", ck["platform"], "--json"])
try:
check_result = json.loads(proc.stdout)
except ValueError:
diff --git a/scripts/report.py b/scripts/report.py
index 3d5279f..0bddac2 100755
--- a/scripts/report.py
+++ b/scripts/report.py
@@ -13,13 +13,12 @@ import base64
import html
import json
import os
-import subprocess
import sys
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
+from _common import STATE, add_common, apply_common, die, emit, info, probe, read_text_or_die, run_tool
HERE = Path(__file__).resolve().parent
@@ -27,15 +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 = subprocess.run([sys.executable, str(HERE / "look.py"), path, "--tiles", tiles, "--width", str(width), "-o", png],
- stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
+ proc = run_tool([str(HERE / "look.py"), path, "--tiles", tiles, "--width", str(width), "-o", png])
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 = subprocess.run([sys.executable, str(HERE / "loudness.py"), path, "--measure-only"], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
+ proc = run_tool([str(HERE / "loudness.py"), path, "--measure-only"])
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)}
@@ -44,7 +42,7 @@ def loudness(path: str) -> Dict[str, Any]:
def check(path: str, platform: str) -> Optional[Dict[str, Any]]:
- proc = subprocess.run([sys.executable, str(HERE / "check.py"), path, "--platform", platform, "--json"], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
+ proc = run_tool([str(HERE / "check.py"), path, "--platform", platform, "--json"])
try:
doc = json.loads(proc.stdout)
except ValueError:
diff --git a/scripts/scenes.py b/scripts/scenes.py
index a24acf0..6fb8caf 100755
--- a/scripts/scenes.py
+++ b/scripts/scenes.py
@@ -21,11 +21,10 @@ import argparse
import math
import os
import re
-import struct
import sys
from 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, run_analysis
+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_analysis, decode_pcm_mono, rms_envelope
SCORE_RE = re.compile(r"frame:(\d+)\s+pts:\d+\s+pts_time:([0-9.]+)")
@@ -87,19 +86,9 @@ 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 = 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) // 2
- if n == 0:
- return []
- samples = struct.unpack(f"<{n}h", proc.stdout[: n * 2])
- step = max(1, int(8000 * step_s))
- env = []
- for i in range(0, n, step):
- block = samples[i:i + step]
- env.append(math.sqrt(sum(x * x for x in block) / len(block)) / 32768.0)
- return env
+ """RMS level per step_s window at 8 kHz, absolute (a loud scene scores higher); [] when the
+ audio cannot be decoded (the cut scoring then runs on the picture alone)."""
+ return rms_envelope(decode_pcm_mono(path, 8000, check=False), int(8000 * step_s))
def main() -> int:
diff --git a/scripts/sync.py b/scripts/sync.py
index 1e20678..a73dd45 100755
--- a/scripts/sync.py
+++ b/scripts/sync.py
@@ -29,11 +29,10 @@ import cmath
import json
import math
import os
-import struct
import sys
from 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, run_analysis, 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_args, decode_pcm_mono, rms_envelope
SR = 8000 # decode sample rate
@@ -55,26 +54,12 @@ OVERLAP_WEIGHT_EXP = 0.5
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 = 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) // 2
- return [v / 32768.0 for v in struct.unpack(f"<{n}h", proc.stdout[: n * 2])]
+ return decode_pcm_mono(path, SR, seconds, start)
def envelope(samples: List[float], step: int) -> List[float]:
- """RMS energy per block, mean-removed so silence does not correlate."""
- env = []
- for i in range(0, len(samples) - step + 1, step):
- block = samples[i : i + step]
- env.append(math.sqrt(sum(x * x for x in block) / step))
- if not env:
- return env
- mean = sum(env) / len(env)
- return [e - mean for e in env]
+ """RMS energy per full block, mean-removed so silence does not correlate."""
+ return rms_envelope(samples, step, full_blocks_only=True, remove_mean=True)
def fft(a: List[complex]) -> List[complex]:
diff --git a/tests/test_contract.py b/tests/test_contract.py
index c795b7f..c38a180 100644
--- a/tests/test_contract.py
+++ b/tests/test_contract.py
@@ -1230,6 +1230,27 @@ class ContractTests(unittest.TestCase):
if preset and name != "export":
self.assertEqual(set(preset["enum"]), set(_common.X264_PRESETS), name)
+ def test_sibling_scripts_run_under_an_outer_ceiling(self):
+ """render/batch/report and the MCP server run sibling scripts as subprocesses. The child
+ limits each of its own ffmpeg calls with --timeout, but a child hung for any other reason
+ (a wedged pipe, a stuck import) was waited on forever: none of those outer subprocess.run
+ calls had a timeout. run_tool() applies child_limit() (4x the per-call limit + 60 s) and
+ returns this skill's own timeout failure document, so a caller parsing the child's --json
+ sees kind timeout exactly as it would from the child. Exercised with a script that sleeps
+ past a tiny limit (the ceiling is computed from the per-call limit, not fixed)."""
+ self.assertIsNone(_common.child_limit(0), "0 = no limit, as for --timeout")
+ self.assertEqual(_common.child_limit(10), 100)
+ sleeper = self.out("sleeper.py")
+ sleeper.write_text("import time\ntime.sleep(30)\n")
+ _common.STATE.reset()
+ _common.STATE.timeout = 0.01 # ceiling 60.04 s would be too slow; pass per_call explicitly instead
+ proc = _common.run_tool([str(sleeper)], per_call=-14.9) # -14.9*4+60 = 0.4 s
+ self.assertEqual(proc.returncode, 124)
+ doc = json.loads(proc.stdout)
+ self.assertEqual((doc["status"], doc["error"]["kind"], doc["error"]["code"]), ("failed", "timeout", "TIMEOUT"))
+ self.assertIn("sleeper.py", doc["error"]["message"])
+ _common.STATE.reset()
+
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