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: release-check catalogue, overlay scale, sync wording, MCP timeout (#343)

Shogo Kajiyama79799a7f66bb
diff --git a/CHANGELOG.md b/CHANGELOG.md
index cf86aa8..fab487f 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -17,6 +17,13 @@ _Automated release: version and notes generated from pull requests merged since
### Fixed
+- **`npm run release-check` lists the full MCP catalogue.** Since the default `tools/list` became the core 12, step 4 required at least 15 names and step 6 required every contract tool, both against the default list. Both steps now set `FFMPEG_SKILL_MCP_FULL=1`. The same script refuses a tarball that contains `references/process-pitfalls.md`.
+- **A text overlay no longer ignores `scale`.** `--scale` / `--scale-percent` size an image, logo or video layer. On text they were accepted and the draw stayed at the default font size, including a render project that forwarded `overlays[].scale` for a text entry. That combination is now refused (`kind: input`); text size is `--font-size` / `font_size`.
+- **`sync.py` says two files that start together start together.** A measured offset of 0 used to read "second starts 0.000s earlier than reference".
+- **MCP `--timeout 0` in a raw `argv` list clears the outer ceiling.** The structured `timeout` key already did. The argv form left the dispatch ceiling at 4×1800 s while the child ran with no limit.
+- **`fit.py --fit blur` on HDR prints `-15%`, not `-15%%`.**
+- **`speedramp.py` cuts the last segment where it was asked to** when that end is more than 50 ms before the file. The end bound used to be omitted for every last segment, so an end inside the 0.5 s coverage slack played the tail at that segment's speed. An end that is the file's end still runs to the last packet.
+- **`npx ffmpeg-skill doctor` on Windows tries the next Python when `python3` is the Store alias.** That alias spawns and exits non-zero, which the installer used to treat as a found interpreter.
- **`cut.py --accurate` starts the picture at 0 (#336).** The re-encode passed `-avoid_negative_ts make_zero`, which shifts every stream so the earliest timestamp is 0. That timestamp is the AAC encoder's priming (21.3 ms at 48 kHz) or a negative B-frame decode time, so the picture started after 0 and the sound at 0. `fit.py --fps` then changed the frame count. The video re-encode no longer passes the flag. When `--start` lands on a frame, that frame is at 0. A start between frames begins on the next source frame and may keep up to one frame of its timestamp. An MP4/MOV edit list hides the priming, and a source whose audio starts late keeps that offset. A stream copy still uses `make_zero` (or `--edit-list`). An audio-only `--accurate` cut still uses it, which is the priming `precision: codec_frame` counts in the length.
- **Windows 11 resolves Nirmala UI for Hindi, Bengali and Tamil (#339).** The font ships as `C:\Windows\Fonts\Nirmala.ttc`. `WINDOWS_FONTS` only named `Nirmala.ttf` and `NirmalaB.ttf`, so `doctor` reported no font for `hi`, `bn` and `ta`. The collection is now in those three lists, after the `.ttf` names, so a machine that still has Mangal or `Nirmala.ttf` keeps that file.
- fix(cut): start an accurate re-encode's picture at 0 (#342)
diff --git a/bin/install.js b/bin/install.js
index e416c27..81a3de7 100755
--- a/bin/install.js
+++ b/bin/install.js
@@ -41,21 +41,39 @@ if (has('--help') || has('-h')) {
process.exit(0);
}
-// `contract` / `doctor` are answered by scripts/_contract.py; everything else installs.
-if (args[0] === 'contract' || args[0] === 'doctor') {
- // Windows Python installers commonly expose `python`/`py`, not `python3` (only the
- // Microsoft Store package does); try python3 first (macOS/Linux convention), then fall
- // back so `npx ffmpeg-skill doctor` doesn't silently fail with ENOENT on Windows.
- const candidates = process.platform === 'win32' ? ['python3', 'python', 'py'] : ['python3'];
- let py;
+// Windows Python installers commonly expose `python`/`py`, not `python3`. The Microsoft Store
+// app-execution alias is a real python3.exe that spawns (no ENOENT) and exits non-zero, so a
+// missing `error` is not proof an interpreter ran. Probe with a version check, then fall through.
+const PYTHON_PROBE = ['-c', 'import sys; raise SystemExit(0 if sys.version_info >= (3, 9) else 1)'];
+
+function pythonCandidates(platform) {
+ return platform === 'win32' ? ['python3', 'python', 'py'] : ['python3'];
+}
+
+function runWithPython(scriptArgs, platform, spawn) {
+ const candidates = pythonCandidates(platform);
+ const run = spawn || spawnSync;
+ let last = null;
for (const cmd of candidates) {
- py = spawnSync(cmd, [path.join(ROOT, 'scripts', '_contract.py'), ...args], { stdio: 'inherit' });
- if (!py.error) break;
+ const probe = run(cmd, PYTHON_PROBE, { stdio: 'ignore', timeout: 15000 });
+ if (probe.error || probe.status !== 0) {
+ last = probe;
+ continue;
+ }
+ return run(cmd, scriptArgs, { stdio: 'inherit' });
}
- if (py.error) {
- console.error(`error: could not find a Python interpreter (tried: ${candidates.join(', ')}). Install Python 3.9+ and ensure it is on PATH.`);
+ return { missing: true, error: last && last.error, status: last && last.status, candidates };
+}
+
+function main() {
+// `contract` / `doctor` are answered by scripts/_contract.py; everything else installs.
+if (args[0] === 'contract' || args[0] === 'doctor') {
+ const py = runWithPython([path.join(ROOT, 'scripts', '_contract.py'), ...args], process.platform, spawnSync);
+ if (py.missing) {
+ console.error(`error: could not find a Python 3.9+ interpreter (tried: ${py.candidates.join(', ')}). Install Python 3.9+ and ensure it is on PATH.`);
+ process.exit(127);
}
- process.exit(py.error ? 127 : py.status);
+ process.exit(py.error ? 127 : (py.status == null ? 1 : py.status));
}
const home = os.homedir();
@@ -159,3 +177,10 @@ if (!has('--uninstall')) {
console.log('\nDone. Ask your agent things like "make this video 60 seconds and add captions".');
}
process.exit(failed ? 1 : 0);
+}
+
+if (require.main === module) {
+ main();
+}
+
+module.exports = { pythonCandidates, runWithPython };
diff --git a/docs/design-decisions.md b/docs/design-decisions.md
index 0fbc0bd..2dd57f1 100644
--- a/docs/design-decisions.md
+++ b/docs/design-decisions.md
@@ -14,7 +14,10 @@ exists. When a decision changes, edit the entry in the same PR.
- **`FFMPEG_SKILL_TIMEOUT=0` (or `--timeout 0`) means no limit anywhere**, including the outer
ceiling on sibling-script runs and the MCP dispatch. 0 is the documented "off" value, chosen so
a genuinely multi-hour job can opt out; the default (1800 s) is what protects an unattended
- agent. Code: `_common.child_limit()`, `_common._limit_for()`. Test: `test_timeout_kills_a_hung_ffmpeg_and_reports_kind_timeout` (the `--timeout 0` case).
+ agent. Code: `_common.child_limit()`, `_common._limit_for()`, `mcp/server.py` `timeout_from_call()`
+ (a raw `argv` list's `--timeout` sets the same ceiling as the structured `timeout` key). Test:
+ `test_timeout_kills_a_hung_ffmpeg_and_reports_kind_timeout` (the `--timeout 0` case) and
+ `test_mcp_argv_timeout_zero_clears_the_outer_ceiling`.
- **The outer ceiling is 4x the per-call limit plus 60 s, not the per-call limit itself.** A tool
runs several ffmpeg/ffprobe calls (two-pass loudness, copy-then-re-encode fallbacks), each under
its own limit; the outer ceiling only exists to end a child hung for a non-ffmpeg reason. Code:
@@ -284,7 +287,10 @@ exists. When a decision changes, edit the entry in the same PR.
- **`references/process-pitfalls.md` is a maintainer diary and is not in the npm package**;
`scripts.md`, `devices.md`, `ci-platform-pitfalls.md` and `docs/contract.md` are. Code:
- `package.json` `files`, `bin/install.js` `PAYLOAD`. Test: `tests/release_check.sh`.
+ `package.json` `files`, `bin/install.js` `PAYLOAD`. Test: `tests/release_check.sh` (the packed
+ tarball and the install made from it must not contain the file; that script needs npm) and
+ `test_npm_package_omits_the_maintainer_diary` (pins the `files` allow-list, which is what CI
+ runs — Windows cannot spawn `npm`, and the debian-trixie job has nodejs without npm).
- **`npm test` calls `python3`**; the Windows CI job gets it from `actions/setup-python`. A
Windows machine with only `py` should run the test files directly.
- **The release bump commit carries the skip-CI marker in its message**; it is pushed by the
diff --git a/mcp/server.py b/mcp/server.py
index 0320625..d01fddd 100755
--- a/mcp/server.py
+++ b/mcp/server.py
@@ -21,7 +21,7 @@ import os
import subprocess
import sys
from pathlib import Path
-from typing import Any, Dict, List
+from typing import Any, Dict, List, Optional
HERE = Path(__file__).resolve().parent
SCRIPTS = HERE.parent / "scripts"
@@ -90,18 +90,66 @@ def build_argv(name: str, args: Dict[str, Any]) -> List[str]:
return argv
+def _timeout_in_argv(argv: List[str]) -> Optional[float]:
+ """The last `--timeout` / `--timeout=N` value in a raw argv list.
+
+ None when the flag is absent or its value is not a number (the child argparse then fails,
+ and the outer ceiling stays the environment default)."""
+ found: Optional[float] = None
+ seen = False
+ i = 0
+ n = len(argv)
+ while i < n:
+ token = argv[i]
+ if token == "--":
+ break
+ if token == "--timeout":
+ if i + 1 >= n:
+ return None
+ raw = argv[i + 1]
+ i += 2
+ elif token.startswith("--timeout="):
+ raw = token.split("=", 1)[1]
+ i += 1
+ else:
+ i += 1
+ continue
+ seen = True
+ try:
+ found = float(raw)
+ except ValueError:
+ return None
+ return found if seen else None
+
+
+def timeout_from_call(args: Dict[str, Any]) -> float:
+ """Per-call seconds for the MCP outer ceiling.
+
+ Structured `timeout` is the canonical key. A raw `argv` list ignores every other key, so
+ `--timeout` has to be read from that list: `--timeout 0` otherwise left the ceiling at 4x
+ the 1800 s default while the child itself ran with no limit. A negative value is 0, matching
+ apply_common (0 means no limit)."""
+ if isinstance(args.get("argv"), list):
+ parsed = _timeout_in_argv([str(a) for a in args["argv"]])
+ if parsed is None:
+ return _common._env_timeout()
+ return max(0.0, parsed)
+ try:
+ return max(0.0, float(args.get("timeout", _common._env_timeout())))
+ except (TypeError, ValueError):
+ return _common._env_timeout()
+
+
def call_tool(name: str, args: Dict[str, Any]) -> Dict[str, Any]:
script = SCRIPTS / f"{name}.py"
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 {})
# 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()
+ # is the only thing that ends a child hung for any other reason. Structured `timeout` or
+ # `--timeout` inside a raw argv list sets both (0 = no limit); otherwise
+ # FFMPEG_SKILL_TIMEOUT / the 1800 s default.
+ per_call = timeout_from_call(args or {})
proc = _common.run_tool([str(script)] + argv, per_call=per_call)
stdout = proc.stdout.strip()
text = stdout
diff --git a/references/scripts.md b/references/scripts.md
index 77b1ac1..08ddc74 100644
--- a/references/scripts.md
+++ b/references/scripts.md
@@ -755,10 +755,13 @@ An `overlays[]` entry draws one of `"logo": true`, `"image"`, `"text"` or
`"video"` (#326: a picture-in-picture or green-screen layer, `overlay.py
--video`), with `position`, `scale`, `opacity`, `start`, `end`, `margin`,
`platform` (and `fade`, `box`, `font*` for the still/text kinds) mapping to
-overlay.py's flags. `"chromakey": "0x00ff00"`, `"chromakey_similarity"` and
-`"chromakey_blend"` key a colour out of the video layer. The stage runs after
-`fit`, so `"scale": 480` is 480 px of the delivered frame, and a template's
-safe margins apply as they do to a logo. Refused (`kind: input`) before the
+overlay.py's flags. `scale` is the layer width in px for a logo, image or
+video (`"scale": 480` is 480 px of the delivered frame, because the stage
+runs after `fit`). A text entry's size is `font_size`; `scale` on a text-only
+entry is refused (`kind: input`) rather than drawn at the default font size.
+`"chromakey": "0x00ff00"`, `"chromakey_similarity"` and
+`"chromakey_blend"` key a colour out of the video layer. A template's
+safe margins apply as they do to a logo. Also refused before the
first stage: `video` together with `logo`/`image`/`text` in one entry (a
logo, image and text together still draw the first of them, as before), a
`chromakey*` key without `video`, `chromakey_similarity`/`_blend` without
@@ -1464,7 +1467,9 @@ overlay.py INPUT --image PNG [--scale W | --scale-percent P] | --text "..." [--f
(`scripts/_platforms.py`), so a template's top-left logo clears TikTok's status bar instead of
sitting 24 px into it; an explicit `--margin` (or a brand `safe_margin`) wins.
Alpha in PNGs is respected. Fades apply to the overlay only; the video keeps
-playing. `--video` composites a second video as a picture-in-picture layer
+playing. `--scale` / `--scale-percent` set the width of an image, logo or
+`--video` layer. They are refused with `--text`: text size is `--font-size`.
+`--video` composites a second video as a picture-in-picture layer
(same position/scale/opacity/time-range knobs as `--image`); only the main
input's audio is kept, the PiP layer's own audio is dropped. `--chromakey`
(with `--video`) keys out that colour first for green-screen compositing.
diff --git a/scripts/fit.py b/scripts/fit.py
index f8e9bff..10f8dea 100755
--- a/scripts/fit.py
+++ b/scripts/fit.py
@@ -198,7 +198,7 @@ def main() -> int:
darken = 0.0 if meta["video"].get("bt2020_or_hdr") else BLUR_DARKEN
if not darken:
info("--fit blur: HDR source, so the blurred background is not dimmed "
- "(an eq on PQ/HLG code values is not the -15%% dim it is on SDR); "
+ "(an eq on PQ/HLG code values is not the -15% dim it is on SDR); "
"run color.py --to-sdr first for the SDR look")
vf.append(pad_filters(out_w, out_h, "blur", args.pad_color, args.pad_blur, darken))
else:
diff --git a/scripts/overlay.py b/scripts/overlay.py
index 591e025..5fbb074 100755
--- a/scripts/overlay.py
+++ b/scripts/overlay.py
@@ -116,8 +116,8 @@ def main() -> int:
ap.add_argument("--fade", type=float, default=0.0, help="fade-in duration in seconds (at --start or 0); the fade-out happens only at --end")
ap.add_argument("--opacity", type=float, default=1.0, help="0..1 (default 1)")
img = ap.add_argument_group("image options")
- img.add_argument("--scale", type=int, help="scale the image to this width in px (keeps aspect)")
- img.add_argument("--scale-percent", type=float, help="scale the image to this %% of the video width")
+ img.add_argument("--scale", type=int, help="width in px for an image, logo or video layer (keeps aspect); text size is --font-size")
+ img.add_argument("--scale-percent", type=float, help="width as a %% of the video for an image, logo or video layer (keeps aspect); text size is --font-size")
txt = ap.add_argument_group("text options")
txt.add_argument("--font", default="DejaVu Sans", help="fontconfig font name")
txt.add_argument("--font-file", help="explicit .ttf/.otf/.ttc path (use this for CJK fonts)")
@@ -158,6 +158,10 @@ def main() -> int:
die("--text is blank -- give the words to draw", kind="input")
if not (args.image or args.text or args.video):
die("give --image, --text, --logo or --video")
+ # --scale is a layer width. On a text draw it used to be accepted and ignored (fontsize stayed
+ # at --font-size), so a project that asked for 200 px text completed with the 42 px default.
+ if args.text and not (args.image or args.video) and (args.scale is not None or args.scale_percent is not None):
+ die("--scale and --scale-percent size an image, logo or video layer; text size is --font-size", kind="input")
if args.brand:
if args.margin == ap.get_default("margin"):
args.margin = int(brand.get("safe_margin", args.margin))
diff --git a/scripts/render.py b/scripts/render.py
index 169e4e8..ea9733a 100755
--- a/scripts/render.py
+++ b/scripts/render.py
@@ -40,7 +40,9 @@ skipped. "brand" points caption/graphics/overlay at a brand.json (fonts,
colours, logo, safe margin); {"logo": true} in overlays places the brand logo.
An overlay entry draws one of logo, image, text or video (a picture-in-picture
layer, overlay.py --video; "chromakey", "chromakey_similarity" and
-"chromakey_blend" key a colour out of that video and need "video").
+"chromakey_blend" key a colour out of that video and need "video"). "scale"
+is that layer's width in px for a logo, image or video; a text entry's size
+is "font_size", and "scale" on a text entry is refused.
"check" mirrors check.py's own exit code: a delivery-spec FAIL (or check.py
itself failing to run) exits 1, same as running check.py directly would --
@@ -436,6 +438,10 @@ def check_overlay(ov: Any, label: str) -> None:
tuned = [k for k in ("chromakey_similarity", "chromakey_blend") if ov.get(k) is not None]
if tuned:
die(f"{label}: {tuned[0]} tunes \"chromakey\", which this entry does not set")
+ # scale is a layer width (overlay.py --scale). A text entry that carries it used to complete
+ # with the default font size, because the text branch never reads the flag.
+ if ov.get("text") and not any(ov.get(k) for k in ("logo", "image", "video")) and ov.get("scale") is not None:
+ die(f"{label}: scale sizes an image, logo or video layer; text size is font_size", kind="input")
def require_object(obj: Any, label: str) -> None:
diff --git a/scripts/speedramp.py b/scripts/speedramp.py
index a05898f..7c5e57a 100644
--- a/scripts/speedramp.py
+++ b/scripts/speedramp.py
@@ -84,9 +84,14 @@ def main() -> int:
output = args.output or default_output(args.input, "ramp")
vparts, aparts, labels = [], [], []
+ # The coverage check above allows the last end to sit up to 0.5 s off the probed duration.
+ # That slack is for a caller who rounded the duration, not a reason to redraw the tail at
+ # the last factor. The end bound is omitted only when the stated end is the file's end
+ # (within 50 ms): a trim a few milliseconds short of the last packet drops that packet.
+ last_runs_to_eof = abs(segments[-1][1] - dur) <= 0.05
for i, (start, end, factor) in enumerate(segments):
vlabel, alabel = f"v{i}", f"a{i}"
- end_expr = f"{end:.3f}" if i < len(segments) - 1 else None
+ end_expr = f"{end:.3f}" if not (i == len(segments) - 1 and last_runs_to_eof) else None
trim = f"trim=start={start:.3f}" + (f":end={end_expr}" if end_expr else "")
vparts.append(f"[0:v]{trim},setpts=(PTS-STARTPTS)/{factor:.6f}[{vlabel}]")
labels.append(f"[{vlabel}]")
diff --git a/scripts/sync.py b/scripts/sync.py
index 484793d..aee74f5 100755
--- a/scripts/sync.py
+++ b/scripts/sync.py
@@ -36,6 +36,17 @@ from _common import video_args, add_common, apply_common, emit, aac_args, audio_
SR = 8000 # decode sample rate
+
+def sync_meaning(offset: float) -> str:
+ """The sentence a caller reads next to offset_seconds.
+
+ A zero offset used to take the else branch of `later if offset > 0` and say the second
+ file starts earlier. Values that print as 0.000 s (under half a millisecond) say the two
+ recordings start together; anything larger keeps later/earlier."""
+ if abs(offset) < 5e-4:
+ return "second starts together with the reference"
+ return "second starts %.3fs %s than reference" % (abs(offset), "later" if offset > 0 else "earlier")
+
# Scoring constants for coarse alignment. Both come from tests/bench_sync.py on real dialogue and
# music with +/-30 s offsets, gain, noise and EQ (see evals/results and CHANGELOG 0.8.0):
#
@@ -307,7 +318,7 @@ def main() -> int:
"second": args.second,
"offset_seconds": offset,
"confidence": score,
- "meaning": ("second starts %.3fs %s than reference" % (abs(offset), "later" if offset > 0 else "earlier")),
+ "meaning": sync_meaning(offset),
"sources": sources_block,
}
if drift_info:
diff --git a/tests/release_check.sh b/tests/release_check.sh
index e538a2a..cf4a9ac 100755
--- a/tests/release_check.sh
+++ b/tests/release_check.sh
@@ -21,6 +21,12 @@ LIST="$(tar -tzf "$TGZ")"
for need in package/SKILL.md package/scripts/_common/__init__.py package/scripts/_contract.py package/scripts/probe.py package/references/scripts.md package/references/devices.md package/mcp/server.py package/bin/install.js; do
echo "$LIST" | grep -qx "$need" || { echo "FAIL: $need missing from the package"; exit 1; }
done
+# docs/design-decisions.md: the maintainer diary stays in git and out of the tarball.
+# scripts.md, devices.md, ci-platform-pitfalls.md and docs/contract.md are the ones that ship.
+if echo "$LIST" | grep -qx "package/references/process-pitfalls.md"; then
+ echo "FAIL: references/process-pitfalls.md must not be in the npm package"
+ exit 1
+fi
echo " ok ($(echo "$LIST" | wc -l | tr -d ' ') files)"
echo "== 2. install from the tarball into a temp HOME"
@@ -30,6 +36,10 @@ HOME="$TMP/home" node "$TMP/pkg/package/bin/install.js" >/dev/null
for d in SKILL.md scripts references mcp package.json; do
[ -e "$TMP/home/.claude/skills/ffmpeg-skill/$d" ] || { echo "FAIL: $d not installed"; exit 1; }
done
+if [ -e "$TMP/home/.claude/skills/ffmpeg-skill/references/process-pitfalls.md" ]; then
+ echo "FAIL: references/process-pitfalls.md was installed from the package"
+ exit 1
+fi
echo " ok"
echo "== 3. every script answers --help"
@@ -41,7 +51,10 @@ done
echo " ok"
echo "== 4. MCP server lists tools"
-n="$(python3 "$TMP/home/.claude/skills/ffmpeg-skill/mcp/server.py" --list | wc -l | tr -d ' ')"
+# Default tools/list is the core 12 (1.18.3). This step checks the full catalogue, which is
+# what step 6 compares to the contract. FFMPEG_SKILL_MCP_FULL=1 is that catalogue; without it
+# --list prints 12 and the >= 15 floor below fails, and step 6's names == contract fails too.
+n="$(FFMPEG_SKILL_MCP_FULL=1 python3 "$TMP/home/.claude/skills/ffmpeg-skill/mcp/server.py" --list | wc -l | tr -d ' ')"
[ "$n" -ge 15 ] || { echo "FAIL: MCP server lists only $n tools"; exit 1; }
echo " ok ($n tools)"
@@ -63,9 +76,10 @@ PY
echo "== 6. MCP tools == contract tools; doctor"
python3 - "$TMP/contract_inst.json" "$INST" <<'PY'
-import json, subprocess, sys
+import json, os, subprocess, sys
doc = json.load(open(sys.argv[1]))
-listed = subprocess.run([sys.executable, sys.argv[2] + "/mcp/server.py", "--list"], stdout=subprocess.PIPE, text=True, check=True).stdout
+env = dict(os.environ, FFMPEG_SKILL_MCP_FULL="1")
+listed = subprocess.run([sys.executable, sys.argv[2] + "/mcp/server.py", "--list"], stdout=subprocess.PIPE, text=True, check=True, env=env).stdout
names = {l.split()[0] for l in listed.splitlines() if l.strip()}
want = {t["name"] for t in doc["tools"]}
assert names == want, f"MCP {sorted(names ^ want)} differs from contract"
@@ -73,7 +87,7 @@ assert names == want, f"MCP {sorted(names ^ want)} differs from contract"
sys.path.insert(0, sys.argv[2] + "/scripts")
import _contract
req = json.dumps({"jsonrpc": "2.0", "id": 1, "method": "tools/list"}) + "\n"
-resp = json.loads(subprocess.run([sys.executable, sys.argv[2] + "/mcp/server.py"], input=req, stdout=subprocess.PIPE, text=True, check=True).stdout.splitlines()[0])
+resp = json.loads(subprocess.run([sys.executable, sys.argv[2] + "/mcp/server.py"], input=req, stdout=subprocess.PIPE, text=True, check=True, env=env).stdout.splitlines()[0])
mcp_tools = resp["result"]["tools"]
assert [t["name"] for t in mcp_tools] == [t["name"] for t in doc["tools"]], "MCP order differs from contract"
for entry, spec in zip(mcp_tools, doc["tools"]):
diff --git a/tests/test_analysis.py b/tests/test_analysis.py
index 5192ae6..da3afe7 100644
--- a/tests/test_analysis.py
+++ b/tests/test_analysis.py
@@ -137,12 +137,22 @@ class AnalysisTests(MediaFixtures):
proc = script("sync.py", self.src, self.mic, "--json")
data = json.loads(proc.stdout)
self.assertClose(data["offset_seconds"], 2.5, 0.05, "lav mic started 2.5 s later")
+ self.assertIn("later than reference", data["meaning"])
self.assertGreater(data["confidence"], 0.5)
out = OUT / "synced.mp4"
script("sync.py", self.src, self.mic, "--replace-audio", "-o", out)
again = json.loads(script("sync.py", self.src, out, "--json").stdout)
self.assertClose(again["offset_seconds"], 0.0, 0.05, "aligned output has no residual offset")
+ def test_sync_zero_offset_says_the_files_start_together(self):
+ """A measured offset of 0 used to take the else of `later if offset > 0` and say the
+ second file starts earlier. Identical inputs start together."""
+ same = OUT / "sync_identical.mp4"
+ shutil.copy(self.src, same)
+ data = json.loads(script("sync.py", self.src, same, "--json").stdout)
+ self.assertAlmostEqual(data["offset_seconds"], 0.0, delta=5e-4)
+ self.assertEqual(data["meaning"], "second starts together with the reference")
+
def test_sync_replace_audio_stream_copy_writes_faststart_mp4(self):
"""Same shape as #275/#277: --replace-audio stream-copies the reference's video with
-c:v copy while only the audio is rebuilt, and must write -movflags +faststart on the
diff --git a/tests/test_contract.py b/tests/test_contract.py
index 4458a14..1ba11c1 100644
--- a/tests/test_contract.py
+++ b/tests/test_contract.py
@@ -1646,6 +1646,80 @@ class ContractTests(unittest.TestCase):
self.assertEqual([t["id"] for t in doc["tools"]], [t["id"] for t in self.contract["tools"]])
self.assertEqual(sh("node", ROOT / "bin" / "install.js", "doctor", "--json").returncode, 0)
+ def test_windows_store_python_stub_is_not_treated_as_an_interpreter(self):
+ """The Microsoft Store python3 alias is a real executable: spawn succeeds (no ENOENT) and
+ the process exits non-zero. install.js used to stop there. A probe that fails falls
+ through to python, then py; a probe that succeeds does not, even when the script itself
+ exits non-zero. Linux still tries python3 only."""
+ probe = self.out("python_probe.js")
+ probe.write_text(
+ "const inst = require(process.argv[2]);\n"
+ "function callsOf(fn) { return fn.calls.map(c => c[0] + ' ' + c[1]).join('|'); }\n"
+ "function stub(cmd, args) {\n"
+ " stub.calls.push([cmd, args[0]]);\n"
+ " if (cmd === 'python3') return { status: 9009, error: null };\n"
+ " if (cmd === 'python' && args[0] === '-c') return { status: 0, error: null };\n"
+ " if (cmd === 'python') return { status: 7, error: null };\n"
+ " return { error: Object.assign(new Error('spawn ENOENT'), { code: 'ENOENT' }), status: null };\n"
+ "}\n"
+ "stub.calls = [];\n"
+ "const fallen = inst.runWithPython(['doctor'], 'win32', stub);\n"
+ "if (fallen.missing || fallen.status !== 7) process.exit(2);\n"
+ "if (callsOf(stub) !== 'python3 -c|python -c|python doctor') process.exit(3);\n"
+ "function kept(cmd, args) {\n"
+ " kept.calls.push([cmd, args[0]]);\n"
+ " if (args[0] === '-c') return { status: 0, error: null };\n"
+ " return { status: 2, error: null };\n"
+ "}\n"
+ "kept.calls = [];\n"
+ "const scriptFailed = inst.runWithPython(['doctor'], 'win32', kept);\n"
+ "if (scriptFailed.missing || scriptFailed.status !== 2) process.exit(4);\n"
+ "if (kept.calls.some(c => c[0] !== 'python3')) process.exit(5);\n"
+ "function missing(cmd, args) {\n"
+ " missing.calls.push(cmd);\n"
+ " return { error: Object.assign(new Error('spawn ENOENT'), { code: 'ENOENT' }), status: null };\n"
+ "}\n"
+ "missing.calls = [];\n"
+ "const none = inst.runWithPython(['doctor'], 'linux', missing);\n"
+ "if (!none.missing || missing.calls.join() !== 'python3') process.exit(6);\n"
+ "if (inst.pythonCandidates('linux').join() !== 'python3') process.exit(7);\n"
+ "if (inst.pythonCandidates('win32').join() !== 'python3,python,py') process.exit(8);\n",
+ encoding="utf-8")
+ proc = subprocess.run(["node", str(probe), str(ROOT / "bin" / "install.js")],
+ stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
+ self.assertEqual(proc.returncode, 0, proc.stderr or proc.stdout)
+
+ def test_npm_package_omits_the_maintainer_diary(self):
+ """docs/design-decisions.md: references/process-pitfalls.md stays out of the npm package.
+
+ release_check.sh is the live `npm pack`. This is the check CI actually runs, and it
+ does not spawn npm: Windows Python cannot CreateProcess `npm` (the runner ships
+ npm.cmd), and the debian-trixie job installs nodejs without the npm package. When
+ `files` is set, `npm pack` includes that allow-list and nothing else, so a directory
+ entry or a glob under references/ is what would pull the diary in.
+ """
+ pkg = json.loads((ROOT / "package.json").read_text(encoding="utf-8"))
+ files = pkg["files"]
+ self.assertIsInstance(files, list)
+ shipped = {
+ "references/scripts.md",
+ "references/devices.md",
+ "references/ci-platform-pitfalls.md",
+ "references/gotchas.md",
+ "docs/contract.md",
+ }
+ self.assertTrue(shipped <= set(files))
+ for entry in files:
+ norm = entry.replace("\\", "/").strip()
+ self.assertNotIn("process-pitfalls", norm, entry)
+ base = norm.rstrip("/")
+ self.assertNotEqual(base, "references", entry)
+ if base.startswith("references/") and any(ch in base for ch in "*?["):
+ self.fail(f"{entry} would pack every file under references/, including the diary")
+ script = (ROOT / "tests" / "release_check.sh").read_text(encoding="utf-8")
+ self.assertIn("package/references/process-pitfalls.md", script)
+ self.assertGreaterEqual(script.count("FFMPEG_SKILL_MCP_FULL"), 2)
+
def test_installer_agent_targets_are_the_directories_those_agents_actually_read(self):
"""`--codex` installed into ~/.codex/skills for weeks -- a location Codex's own docs never
list (they name $HOME/.agents/skills, .agents/skills up the repo tree, /etc/codex/skills).
@@ -2146,6 +2220,43 @@ class ContractTests(unittest.TestCase):
self.assertIn("sleeper.py", doc["error"]["message"])
_common.STATE.reset()
+ def test_mcp_argv_timeout_zero_clears_the_outer_ceiling(self):
+ """docs/design-decisions.md: --timeout 0 means no limit, including MCP dispatch. The
+ structured `timeout` key already did. A raw argv list ignores every other key, so
+ `--timeout 0` inside it left the outer ceiling at 4x the 1800 s default while the child
+ ran with no limit. A negative value matches apply_common and is also no limit."""
+ captured = {}
+
+ def fake_run_tool(argv, per_call=None):
+ captured["per_call"] = per_call
+ captured["ceiling"] = _common.child_limit(per_call)
+ return subprocess.CompletedProcess(argv, 0, "{}", "")
+
+ saved = mcp_server._common.run_tool
+ mcp_server._common.run_tool = fake_run_tool
+ try:
+ mcp_server.call_tool("probe", {"argv": [str(self.wav), "--timeout", "0"]})
+ self.assertEqual(captured["per_call"], 0.0)
+ self.assertIsNone(captured["ceiling"])
+ self.assertEqual(mcp_server.build_argv("probe", {"argv": [str(self.wav), "--timeout", "0"]}),
+ [str(self.wav), "--timeout", "0"])
+ mcp_server.call_tool("probe", {"argv": [str(self.wav), "--timeout=0"]})
+ self.assertIsNone(captured["ceiling"])
+ mcp_server.call_tool("probe", {"input": str(self.wav), "timeout": 0})
+ self.assertEqual(captured["per_call"], 0.0)
+ self.assertIsNone(captured["ceiling"])
+ mcp_server.call_tool("probe", {"argv": [str(self.wav), "--timeout", "30"]})
+ self.assertEqual(captured["per_call"], 30.0)
+ self.assertEqual(captured["ceiling"], 180.0)
+ mcp_server.call_tool("probe", {"argv": [str(self.wav), "--timeout", "-5"]})
+ self.assertEqual(captured["per_call"], 0.0)
+ self.assertIsNone(captured["ceiling"])
+ mcp_server.call_tool("probe", {"argv": [str(self.wav)]})
+ self.assertEqual(captured["per_call"], _common._env_timeout())
+ self.assertEqual(captured["ceiling"], _common.child_limit(_common._env_timeout()))
+ finally:
+ mcp_server._common.run_tool = saved
+
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",
diff --git a/tests/test_editing.py b/tests/test_editing.py
index a9c8c8e..5bd8275 100644
--- a/tests/test_editing.py
+++ b/tests/test_editing.py
@@ -627,6 +627,31 @@ class EditingTests(MediaFixtures):
def test_speedramp_must_start_at_zero_refused(self):
script("speedramp.py", self.src, "--segment", "1-12:1.0", expect_fail=True)
+ def test_speedramp_last_segment_inside_the_coverage_slack_keeps_its_end(self):
+ """The last segment omitted its end bound, and the coverage check allows that end to sit
+ up to 0.5 s before the file. A last segment ending 0.4 s early therefore played the tail
+ at that segment's speed (1.5 s out of a 2 s source, instead of 1.3 s). The bound is
+ omitted only when the stated end is the file's end."""
+ src = OUT / "ramp_slack.mp4"
+ sh("ffmpeg", "-y", "-hide_banner", "-loglevel", "error",
+ "-f", "lavfi", "-i", "testsrc2=size=64x64:rate=30",
+ "-f", "lavfi", "-i", "sine=frequency=440:sample_rate=48000",
+ "-t", "2", "-c:v", "libx264", "-preset", "ultrafast", "-c:a", "aac", src)
+ out = OUT / "ramp_slack_out.mp4"
+ doc = json.loads(script("speedramp.py", src, "--segment", "0-1:1", "--segment", "1-1.6:2",
+ "--preset", "ultrafast", "--json", "-o", out).stdout)
+ graph = " ".join(doc["commands"])
+ self.assertIn("trim=start=1.000:end=1.600", graph)
+ self.assertIn("atrim=start=1.000:end=1.600", graph)
+ self.assertClose(probe(str(out))["duration"], 1.3, 0.15)
+ # an end that is the file's end still runs to the last packet (no end bound to clip it)
+ plan = json.loads(script("speedramp.py", src, "--segment", "0-2:1", "--dry-run", "--json",
+ "-o", OUT / "ramp_slack_eof.mp4").stdout)
+ joined = " ".join(plan["commands"])
+ self.assertIn("trim=start=0.000", joined)
+ self.assertNotIn("trim=start=0.000:end=", joined)
+ self.assertNotIn("atrim=start=0.000:end=", joined)
+
# ---------------------------------------------------------------- loop
def test_loop_times_multiplies_duration(self):
out = OUT / "loop1.mp4"
@@ -1297,12 +1322,15 @@ class EditingTests(MediaFixtures):
# PQ/HLG, so an HDR source keeps its background at its own levels (review 12)
sdr_plan = json.loads(script("fit.py", self.src, "--aspect", "9:16", "--fit", "blur",
"--dry-run", "--json", "-o", str(OUT / "blur_sdr.mp4")).stdout)
- hdr_plan = json.loads(script("fit.py", self.hdr, "--aspect", "9:16", "--fit", "blur",
- "--dry-run", "--json", "-o", str(OUT / "blur_hdr.mp4")).stdout)
+ hdr_proc = script("fit.py", self.hdr, "--aspect", "9:16", "--fit", "blur",
+ "--dry-run", "--json", "-o", str(OUT / "blur_hdr.mp4"))
+ hdr_plan = json.loads(hdr_proc.stdout)
self.assertTrue(any("eq=brightness" in c for c in sdr_plan["commands"]))
self.assertTrue(any("boxblur" in c for c in hdr_plan["commands"]))
self.assertFalse(any("eq=brightness" in c for c in hdr_plan["commands"]),
"an HDR source must not be dimmed by an SDR-shaped eq")
+ self.assertIn("not the -15% dim it is on SDR", hdr_proc.stderr)
+ self.assertNotIn("-15%%", hdr_proc.stderr)
def test_join_list_checks_every_segment_before_joining(self):
"""Reported by a user generating shorts on a VPS: TTS writes one audio file per line,
diff --git a/tests/test_orchestration.py b/tests/test_orchestration.py
index 62eede8..0cc52e1 100644
--- a/tests/test_orchestration.py
+++ b/tests/test_orchestration.py
@@ -753,6 +753,7 @@ class OrchestrationTests(MediaFixtures):
"key_without_video": ({"image": "logo.png", "chromakey": "green"}, 'chromakey keys a colour out of a video layer and needs "video"'),
"tune_without_key": ({"video": pip.name, "chromakey_blend": 0.1}, 'chromakey_blend tunes "chromakey"'),
"missing_layer": ({"video": "pip326_gone.mp4"}, "overlays[0].video: file not found"),
+ "text_scale": ({"text": "Hello", "scale": 200}, "scale sizes an image, logo or video layer"),
}
for name, (overlay, message) in cases.items():
proc = script("render.py", self._proj(f"render_pip326_{name}.json", {"clips": clips, "overlays": [overlay]}),
diff --git a/tests/test_picture.py b/tests/test_picture.py
index 35c6495..d1060b0 100644
--- a/tests/test_picture.py
+++ b/tests/test_picture.py
@@ -1078,6 +1078,22 @@ class PictureTests(MediaFixtures):
script("overlay.py", self.src, "--text", "Episode 12", "--position", "bottom", "--box", "--start", "1", "--end", "5", "--fade", "0.3", "-o", out2)
self.assertClose(probe(str(out2))["duration"], 12.0, 0.15)
+ def test_overlay_text_scale_is_refused(self):
+ """--scale is a layer width. On --text it used to be accepted and ignored, so the draw
+ stayed at fontsize 42 while the result said completed."""
+ for flag in ("--scale", "--scale-percent"):
+ value = "200" if flag == "--scale" else "40"
+ proc = script("overlay.py", self.src, "--text", "Hello", flag, value, "--dry-run", "--json",
+ "-o", OUT / "ov_text_scale.mp4", expect_fail=True)
+ doc = json.loads(proc.stdout)
+ self.assertEqual(doc["error"]["kind"], "input", flag)
+ self.assertIn("--font-size", doc["error"]["message"])
+ self.assertEqual(doc["commands"], [])
+ # an image layer still takes the width
+ plan = json.loads(script("overlay.py", self.src, "--image", self.logo, "--scale", "80",
+ "--dry-run", "--json", "-o", OUT / "ov_img_scale.mp4").stdout)
+ self.assertTrue(any("scale=80:" in c for c in plan["commands"]))
+
def test_hdr_to_sdr_tonemap(self):
out = OUT / "sdr.mp4"
script("color.py", self.hdr, "--to-sdr", "--preset", "veryfast", "-o", out)