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: third audit's confirmed items — Windows concat lists, SMPTE round trip, ASR timeout, installer swap, HDR joins, argument checks, shipped docs (#181)

Shogo Kajiyamaafd46f16c38b
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 448f2f6..6385ed8 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -4,7 +4,13 @@
## Unreleased
-(nothing yet)
+- Multi-segment `cut.py` writes its concat list with forward slashes, so a Windows temp path (`C:\Users\...`) is not read as escape sequences by the concat demuxer; `sequence.py` shares the helper.
+- SMPTE `hh:mm:ss:ff` parsing counts frames per timecode-second like `fmt_smpte_time()` does, so the two agree at 29.97/59.94 over long files. `cut.py` passes the input's fps (so SMPTE works there) and refuses a bad time as `kind: input`; `freeze.py --at` accepts the shared time grammar.
+- `caption.py --transcribe`: faster-whisper runs under `--timeout` like the CLI engines; an old whisper.cpp binary named `main` is used when it lives in a whisper directory.
+- `bin/install.js` moves the old install aside and back on a failed swap, so an upgrade never leaves the target empty; the npm package and installer ship `docs/contract.md`.
+- `join.py` goes 10-bit HEVC when any input is HDR (not only the first); `broll.py` keeps a 10-bit cutaway over an HDR main clip; `grid.py` notes that an HDR input is composited into an 8-bit SDR grid.
+- `look.py -o` names the file for a single `--at` when it carries an image extension; `audio.py` refuses `--mono` with `--stereo` and an out-of-range `--denoise-strength`; `render.py` refuses a negative clip speed; `batch.py` also picks up `.ogg`/`.opus`/`.ts`/`.gif`/`.aac`/`.aiff`; `report.py` shows a 0 s duration as 0 s; `ffmpeg_version()` has a probe timeout.
+- Windows: `default_font_file()` looks for the requested family in `C:\Windows\Fonts` (and common CJK system fonts for a CJK request) before falling back to Arial.
## 1.4.7
diff --git a/bin/install.js b/bin/install.js
index a0304c2..cac8c14 100755
--- a/bin/install.js
+++ b/bin/install.js
@@ -27,7 +27,7 @@ const { spawnSync } = require('child_process');
const SKILL_NAME = 'ffmpeg-skill';
const ROOT = path.resolve(__dirname, '..');
-const PAYLOAD = ['SKILL.md', 'scripts', 'references', 'mcp', 'package.json'];
+const PAYLOAD = ['SKILL.md', 'scripts', 'references', 'docs', 'mcp', 'package.json'];
const args = process.argv.slice(2);
const has = (flag) => args.includes(flag);
@@ -131,8 +131,20 @@ for (const t of targets) {
if (!fs.existsSync(src)) { if (item !== 'SKILL.md' && item !== 'scripts') continue; throw new Error(`missing ${item} in package`); }
copyRecursive(src, path.join(tmpDir, item));
}
- fs.rmSync(t.dir, { recursive: true, force: true });
- fs.renameSync(tmpDir, t.dir);
+ // Swap: move the old install aside, move the new one in, then drop the old copy. If the
+ // second rename fails (a locked file on Windows, a permission error) the old install is put
+ // back, so an upgrade can fail but never leaves the target empty.
+ const bakDir = `${t.dir}.bak-${process.pid}`;
+ fs.rmSync(bakDir, { recursive: true, force: true });
+ const hadOld = fs.existsSync(t.dir);
+ if (hadOld) fs.renameSync(t.dir, bakDir);
+ try {
+ fs.renameSync(tmpDir, t.dir);
+ } catch (err) {
+ if (hadOld) { try { fs.renameSync(bakDir, t.dir); } catch (_) { /* the old copy stays at bakDir */ } }
+ throw err;
+ }
+ if (hadOld) fs.rmSync(bakDir, { recursive: true, force: true });
console.log(`installed ${t.label}: ${t.dir}`);
} catch (err) {
failed = true;
diff --git a/package.json b/package.json
index 634b7ff..f00419e 100644
--- a/package.json
+++ b/package.json
@@ -33,6 +33,7 @@
"references/scripts.md",
"references/devices.md",
"references/ci-platform-pitfalls.md",
+ "docs/contract.md",
"SKILL.md",
"README.md",
"LICENSE"
diff --git a/scripts/_common.py b/scripts/_common.py
index c1cb886..a2c89c2 100755
--- a/scripts/_common.py
+++ b/scripts/_common.py
@@ -107,11 +107,14 @@ def ffmpeg_version() -> "Tuple[int, int]":
if _FFMPEG_VERSION is None:
_FFMPEG_VERSION = (0, 0)
try:
- out = subprocess.run(["ffprobe", "-version"], stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True).stdout
+ out = subprocess.run(["ffprobe", "-version"], stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True,
+ timeout=PROBE_TIMEOUT).stdout
m = re.search(r"ffprobe version\s+n?(\d+)\.(\d+)", out)
if m:
_FFMPEG_VERSION = (int(m.group(1)), int(m.group(2)))
- except OSError:
+ except (OSError, subprocess.TimeoutExpired):
+ # (0, 0) = unknown: every version branch then takes the older, universally accepted
+ # spelling, the same "unknown is not missing" stance doctor takes.
pass
return _FFMPEG_VERSION
@@ -206,9 +209,9 @@ X264_PRESETS = ("ultrafast", "superfast", "veryfast", "faster", "fast", "medium"
class Context:
"""Per-process settings that the shared flags (--dry-run, --json, --progress, --fast) set once.
- Scripts read it as attributes (``STATE.dry_run``) or, for older call sites, like a dict
- (``STATE.dry_run``). Keeping it a single explicit object rather than module globals makes
- it obvious what run()/emit() depend on and lets tests reset it with ``STATE.reset()``.
+ Scripts read it as attributes (``STATE.dry_run``); the dict-style shims that once served
+ older call sites are gone. Keeping it a single explicit object rather than module globals
+ makes it obvious what run()/emit() depend on and lets tests reset it with ``STATE.reset()``.
"""
__slots__ = ("dry_run", "json", "progress", "fast", "duration_hint", "commands", "timeout", "overwrite", "written", "preexisting")
@@ -912,6 +915,15 @@ class MissingFpsError(ValueError):
silently swallowing a mistyped/missing --fps as an auto-timed line of digits."""
+def concat_list_line(path: str) -> str:
+ """One `file '...'` line for the concat demuxer. The demuxer reads backslash as an escape
+ inside the quoted form, so a Windows path (C:\\Users\\...\\part000.mp4) must be written
+ with forward slashes -- ffmpeg opens either spelling on Windows -- and a single quote in the
+ name is closed, escaped and reopened. Shared by cut.py (multi-segment) and sequence.py."""
+ escaped = str(path).replace("\\", "/").replace("'", "'\\''")
+ return f"file '{escaped}'"
+
+
def parse_time(value: str, fps: Optional[float] = None) -> float:
"""Accept seconds ('12.5'), mm:ss ('1:30'), hh:mm:ss(.ms) ('00:01:30.250'), SRT '00:01:30,250',
or -- when `fps` is given -- SMPTE non-drop-frame timecode 'hh:mm:ss:ff' ('00:01:30:15')."""
@@ -928,7 +940,12 @@ def parse_time(value: str, fps: Optional[float] = None) -> float:
frame, whole_fps = int(f), int(round(fps))
if not (0 <= frame < whole_fps):
raise ValueError(f"bad SMPTE timecode '{value}': frame {frame} is out of range for {fps:g} fps (0-{whole_fps - 1})")
- return int(h) * 3600 + int(m) * 60 + int(s) + frame / fps
+ # Non-drop-frame: the timecode counts whole_fps frames per timecode-second, so the real
+ # time is the total frame count over the true rate (at 29.97 an hour of timecode is
+ # 3596.4 s of video). This is exactly what fmt_smpte_time() inverts; before, the two
+ # disagreed by ~0.1 % on the fractional NTSC rates and drifted apart over long files.
+ total_frames = (int(h) * 3600 + int(m) * 60 + int(s)) * whole_fps + frame
+ return total_frames / fps
if len(parts) > 3:
raise ValueError(f"bad time: {value}")
total = 0.0
@@ -1002,7 +1019,26 @@ def default_font_file(font_name: str) -> Optional[str]:
"""
if platform.system() == "Windows":
windir = os.environ.get("WINDIR", "C:\\Windows")
- candidate = Path(windir) / "Fonts" / "arial.ttf"
+ fonts = Path(windir) / "Fonts"
+ # The requested family first: a file whose name starts with the family name with spaces
+ # removed (Noto Sans CJK JP -> NotoSansCJKjp-Regular.otf, Meiryo -> meiryo.ttc), then the
+ # common CJK system fonts when the request looks CJK (so Japanese text does not render as
+ # boxes in Arial), and Arial only as the last resort.
+ wanted = re.sub(r"[^a-z0-9]", "", (font_name or "").lower())
+ try:
+ files = sorted(fonts.iterdir()) if fonts.is_dir() else []
+ except OSError:
+ files = []
+ if wanted:
+ for f in files:
+ stem = re.sub(r"[^a-z0-9]", "", f.stem.lower())
+ if f.suffix.lower() in (".ttf", ".otf", ".ttc") and stem.startswith(wanted):
+ return str(f)
+ if any(k in wanted for k in ("cjk", "gothic", "mincho", "meiryo", "yugoth", "msgothic", "malgun", "simhei", "simsun", "jp", "kr", "sc", "tc")):
+ for name in ("NotoSansCJKjp-Regular.otf", "NotoSansCJK-Regular.ttc", "meiryo.ttc", "YuGothM.ttc", "msgothic.ttc", "malgun.ttf", "msyh.ttc"):
+ if (fonts / name).exists():
+ return str(fonts / name)
+ candidate = fonts / "arial.ttf"
return str(candidate) if candidate.exists() else None
exe = shutil.which("fc-match")
if not exe:
diff --git a/scripts/audio.py b/scripts/audio.py
index 87816de..ff808d8 100755
--- a/scripts/audio.py
+++ b/scripts/audio.py
@@ -91,8 +91,9 @@ def main() -> int:
fades.add_argument("--fade-in", type=float, default=0.0, help="seconds")
fades.add_argument("--fade-out", type=float, default=0.0, help="seconds; fades the whole final mix (voice included)")
music.add_argument("--music-fade-out", type=float, default=0.0, help="seconds; fades only the music bed at the end, voice untouched")
- fades.add_argument("--stereo", action="store_true", help="force 2-channel output (mono is duplicated to both sides)")
- fades.add_argument("--mono", action="store_true", help="force 1-channel output")
+ channels = fades.add_mutually_exclusive_group()
+ channels.add_argument("--stereo", action="store_true", help="force 2-channel output (mono is duplicated to both sides)")
+ channels.add_argument("--mono", action="store_true", help="force 1-channel output")
fades.add_argument("--downmix", action="store_true", help="downmix 5.1/7.1 to stereo using standard weights")
fades.add_argument("--replace", help="replace the audio with this file (trimmed/padded to the video)")
dyn = ap.add_argument_group("dynamics (typed; each flag is one option of ffmpeg's acompressor / alimiter / agate)")
@@ -151,6 +152,8 @@ def main() -> int:
if args.voice:
fx.append(VOICE_CHAIN)
elif args.denoise:
+ if not 10 <= args.denoise_strength <= 60:
+ die(f"--denoise-strength must be 10..60 (dB of noise floor to remove), got {args.denoise_strength:g}")
fx.append(f"afftdn=nf=-{args.denoise_strength:g}:tn=1")
if args.gain:
fx.append(f"volume={args.gain:g}dB")
diff --git a/scripts/batch.py b/scripts/batch.py
index 0834205..e2638c0 100755
--- a/scripts/batch.py
+++ b/scripts/batch.py
@@ -34,7 +34,8 @@ from typing import Any, Dict, List
from _common import STATE, add_common, apply_common, child_args, die, emit, info, run_tool, read_text_or_die
HERE = Path(__file__).resolve().parent
-MEDIA_EXT = {".mp4", ".mov", ".m4v", ".mkv", ".webm", ".avi", ".mts", ".m2ts", ".mxf", ".wav", ".m4a", ".mp3", ".flac"}
+MEDIA_EXT = {".mp4", ".mov", ".m4v", ".mkv", ".webm", ".avi", ".mts", ".m2ts", ".mxf", ".ts", ".gif",
+ ".wav", ".m4a", ".mp3", ".flac", ".aac", ".ogg", ".opus", ".aif", ".aiff"}
# recipe steps name the script to run as plain, untrusted JSON -- run_step() joins it onto HERE
# with the `/` operator, which silently ignores the left side when the right side is itself an
# absolute path (Path("/scripts") / "/tmp/evil.py" == Path("/tmp/evil.py")), and does nothing to
diff --git a/scripts/broll.py b/scripts/broll.py
index 4bfd1f1..e606e68 100755
--- a/scripts/broll.py
+++ b/scripts/broll.py
@@ -104,7 +104,7 @@ def main() -> int:
for i, c in enumerate(cutaways):
geo = f"scale={w}:{h}:force_original_aspect_ratio=decrease,pad={w}:{h}:(ow-iw)/2:(oh-ih)/2:color={args.pad_color}"
parts.append(f"[{i + 1}:v]trim=start={c['from']:.3f}:duration={c['length']:.3f},setpts=PTS-STARTPTS+{c['at']:.3f}/TB,"
- f"{geo},setsar=1,fps={fps:g},format=yuv420p[b{i}]")
+ f"{geo},setsar=1,fps={fps:g},format={'yuv420p10le' if (meta_a.get('video') or {}).get('hdr') else 'yuv420p'}[b{i}]")
parts.append(f"{cur}[b{i}]overlay=0:0:eof_action=pass:enable='between(t,{c['at']:.3f},{c['at'] + c['length']:.3f})'[v{i}]")
cur = f"[v{i}]"
vout = cur
diff --git a/scripts/caption.py b/scripts/caption.py
index fe069c5..ff1f6ea 100755
--- a/scripts/caption.py
+++ b/scripts/caption.py
@@ -109,7 +109,7 @@ def _asr_run(cmd: List[str], subprocess, name: str) -> "subprocess.CompletedProc
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_analysis
+ from _common import run_analysis, STATE, die
wav = os.path.join(tmpdir, "audio.wav")
# 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
@@ -117,8 +117,14 @@ def _transcribe_in(tmpdir: str, video: str, out_srt: str, language: Optional[str
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.cpp
- cli = 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")):
+ cli = shutil.which("whisper-cli") or shutil.which("whisper-cpp")
+ if not cli:
+ # older whisper.cpp builds ship the binary as plain `main`; accept it only when it lives
+ # in a directory that names whisper, so an unrelated /usr/bin/main is never run
+ main_bin = shutil.which("main")
+ if main_bin and "whisper" in os.path.dirname(os.path.realpath(main_bin)).lower():
+ cli = main_bin
+ if cli:
model_path = model
if not os.path.exists(model_path):
for cand in (os.path.expanduser(f"~/.cache/whisper.cpp/ggml-{model}.bin"), f"models/ggml-{model}.bin", f"/usr/local/share/whisper/ggml-{model}.bin"):
@@ -139,9 +145,21 @@ def _transcribe_in(tmpdir: str, video: str, out_srt: str, language: Optional[str
# 2. faster-whisper (python package)
try:
from faster_whisper import WhisperModel # type: ignore
- m = WhisperModel(model, device="cpu", compute_type="int8")
- segments, _ = m.transcribe(wav, language=language, word_timestamps=False)
- cues = [(seg.start, seg.end, seg.text.strip()) for seg in segments if seg.text.strip()]
+ import threading
+ result: list = []
+
+ def work() -> None:
+ m = WhisperModel(model, device="cpu", compute_type="int8")
+ segments, _ = m.transcribe(wav, language=language, word_timestamps=False)
+ result.extend((seg.start, seg.end, seg.text.strip()) for seg in segments if seg.text.strip())
+
+ # An in-process engine gets the same wall-clock limit as the CLI engines and ffmpeg.
+ t = threading.Thread(target=work, daemon=True)
+ t.start()
+ t.join(STATE.timeout or None)
+ if t.is_alive():
+ die(f"faster-whisper exceeded the {STATE.timeout:.0f} s time limit; raise --timeout for a long recording", code=124, kind="timeout")
+ cues = list(result)
if cues:
info("transcribed with faster-whisper")
write_srt(cues, out_srt)
diff --git a/scripts/cut.py b/scripts/cut.py
index 6f78218..137132f 100755
--- a/scripts/cut.py
+++ b/scripts/cut.py
@@ -30,14 +30,23 @@ import sys
import tempfile
from typing import List, Tuple
-from _common import video_args, STATE, add_common, apply_common, audio_codec_for, emit, aac_args, cfr_args, default_output, die, ffmpeg_base, info, is_audio_output, parse_time, probe, run, X264_PRESETS, keyframes_near
+from _common import video_args, STATE, add_common, apply_common, audio_codec_for, emit, aac_args, cfr_args, default_output, die, ffmpeg_base, info, is_audio_output, parse_time, probe, run, X264_PRESETS, keyframes_near, MissingFpsError, concat_list_line
# keyframe timestamps found next to a requested cut that the tolerance turned into a re-encode
# (reported so the caller can choose a lossless cut at one of them next time)
NEAREST_KEYFRAMES: list = []
-def parse_segments(spec: str) -> List[Tuple[float, float]]:
+def _t(value: str, fps) -> float:
+ """parse_time() with the input's fps (SMPTE hh:mm:ss:ff) and every failure as kind input."""
+ try:
+ return parse_time(value, fps)
+ except (ValueError, MissingFpsError) as e:
+ die(f"bad time {value!r}: {e}")
+ return 0.0 # unreachable
+
+
+def parse_segments(spec: str, fps=None) -> List[Tuple[float, float]]:
segs = []
for raw in spec.split(","):
raw = raw.strip()
@@ -46,7 +55,7 @@ def parse_segments(spec: str) -> List[Tuple[float, float]]:
if "-" not in raw:
die(f"segment '{raw}' must look like START-END (e.g. 0:05-0:12)")
a, b = raw.rsplit("-", 1)
- start, end = parse_time(a), parse_time(b)
+ start, end = _t(a, fps), _t(b, fps)
if end <= start:
die(f"segment '{raw}': end must be after start")
segs.append((start, end))
@@ -156,20 +165,21 @@ def main() -> int:
info("source looks variable-frame-rate; lossless cuts on VFR are unreliable, switching to --accurate")
args.accurate = True
+ fps = (meta.get("video") or {}).get("fps")
if args.segments:
- segments = parse_segments(args.segments)
+ segments = parse_segments(args.segments, fps)
else:
- start = parse_time(args.start)
+ start = _t(args.start, fps)
if start < 0:
die(f"--start must not be negative, got {args.start!r}")
if args.end and args.duration:
die("use --end or --duration, not both")
if args.end:
- end = parse_time(args.end)
+ end = _t(args.end, fps)
if end < 0:
die(f"--end must not be negative, got {args.end!r}")
elif args.duration:
- end = start + parse_time(args.duration)
+ end = start + _t(args.duration, fps)
else:
end = total
if end <= start:
@@ -197,7 +207,7 @@ def main() -> int:
listfile = os.path.join(tmp, "list.txt")
with open(listfile, "w", encoding="utf-8") as fh:
for p in parts:
- fh.write("file '" + p.replace("'", "'\\''") + "'\n")
+ fh.write(concat_list_line(p) + "\n")
cmd = ffmpeg_base() + ["-f", "concat", "-safe", "0", "-i", listfile, "-c", "copy", output]
proc = run(cmd, check=False)
if proc.returncode != 0:
diff --git a/scripts/freeze.py b/scripts/freeze.py
index c2e11d9..b9e85e7 100644
--- a/scripts/freeze.py
+++ b/scripts/freeze.py
@@ -19,14 +19,14 @@ Examples:
import argparse
import sys
-from _common import add_common, apply_common, aac_args, cfr_args, default_output, die, emit, ffmpeg_base, info, probe, run_keeping_subtitles, video_args, X264_PRESETS
+from _common import add_common, apply_common, aac_args, cfr_args, default_output, die, emit, ffmpeg_base, info, probe, run_keeping_subtitles, video_args, X264_PRESETS, MissingFpsError, parse_time
def main() -> int:
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("input")
ap.add_argument("-o", "--output", help="output file (default: <name>_freeze.<ext>)")
- ap.add_argument("--at", type=float, help="timestamp to freeze, in seconds (default: the last frame)")
+ ap.add_argument("--at", help="timestamp to freeze: seconds, mm:ss, hh:mm:ss.ms or SMPTE hh:mm:ss:ff (default: the last frame)")
ap.add_argument("--hold", type=float, required=True, help="how long the freeze lasts, in seconds")
ap.add_argument("--mode", choices=["insert", "extend"], default="insert",
help="insert (default): hold pushes the rest of the clip later; extend: only valid at/after the clip's end, makes the last frame last longer with nothing pushed")
@@ -44,7 +44,13 @@ def main() -> int:
die("input has no video stream")
dur = meta.get("duration") or 0.0
fps = meta["video"].get("fps") or 30.0
- at = args.at if args.at is not None else dur
+ if args.at is not None:
+ try:
+ at = parse_time(args.at, (meta.get("video") or {}).get("fps"))
+ except (ValueError, MissingFpsError) as e:
+ die(f"--at {args.at!r}: {e}")
+ else:
+ at = dur
if at < 0 or at > dur:
die(f"--at {at:g} is outside the clip (0..{dur:.3f})")
if args.mode == "extend" and at < dur - 0.01:
diff --git a/scripts/grid.py b/scripts/grid.py
index c49fe56..66b9cd5 100644
--- a/scripts/grid.py
+++ b/scripts/grid.py
@@ -121,6 +121,11 @@ def main() -> int:
if args.audio_from is not None:
audio_source = "[aout]" if (args.pad and durations[args.audio_from] < target_duration) else f"{args.audio_from}:a:0"
cmd += ["-map", audio_source]
+ # A grid is an 8-bit SDR composite by design (a comparison/contact artefact, not a
+ # deliverable); an HDR input is flattened like look.py's contact sheet flattens it. Say so
+ # once so the caller is not surprised by the 8-bit output.
+ if any((m.get("video") or {}).get("hdr") for m in metas):
+ info("note: an HDR input is composited into an 8-bit SDR grid (grid.py is a comparison artefact); use color.py --to-sdr first for a graded conversion")
cmd += video_args(None, args.crf, args.preset)
cmd += cfr_args(None, args.fps)
if args.audio_from is not None:
diff --git a/scripts/join.py b/scripts/join.py
index 8de4388..3d4b067 100755
--- a/scripts/join.py
+++ b/scripts/join.py
@@ -168,7 +168,10 @@ def main() -> int:
geo = f"scale={w}:{h}:force_original_aspect_ratio=increase,crop={w}:{h}"
else:
geo = f"scale={w}:{h}:force_original_aspect_ratio=decrease,pad={w}:{h}:(ow-iw)/2:(oh-ih)/2:color={args.pad_color}"
- pixfmt = "yuv420p10le" if (metas[0].get("video") or {}).get("hdr") else "yuv420p"
+ # Any HDR input makes the join HDR (10-bit, HEVC via video_args on that clip's tags): an SDR
+ # first clip used to drag an HDR second clip down to 8-bit without a tone map.
+ hdr_meta = next((m for m in metas if (m.get("video") or {}).get("hdr")), None)
+ pixfmt = "yuv420p10le" if hdr_meta else "yuv420p"
for i in range(n):
parts.append(f"[{i}:v]{geo},setsar=1,fps={fps:g},format={pixfmt},settb=AVTB[v{i}]")
parts.append(f"[{audio_src[i]}]aformat=sample_rates=48000:channel_layouts=stereo,asetpts=PTS-STARTPTS[a{i}]")
@@ -189,7 +192,7 @@ def main() -> int:
output = args.output or default_output(args.inputs[0], "joined", "mp4")
cmd += ["-filter_complex", ";".join(parts), "-map", "[vout]", "-map", "[aout]"]
- cmd += video_args(metas[0], args.crf, args.preset) + aac_args() + [output]
+ cmd += video_args(hdr_meta or metas[0], args.crf, args.preset) + aac_args() + [output]
run(cmd)
expected = sum(durs) - d * (n - 1)
r = probe(output, role="output")
diff --git a/scripts/look.py b/scripts/look.py
index be76586..6c18c73 100755
--- a/scripts/look.py
+++ b/scripts/look.py
@@ -85,7 +85,11 @@ def main() -> int:
sec = parse_time(t)
if dur and sec > dur:
die(f"--at {t} is beyond the duration ({dur:.2f}s)")
- out = os.path.join(outdir, f"{args.output and Path(args.output).stem or stem}_{sec:.3f}s.png")
+ if args.output and len(args.at) == 1 and Path(args.output).suffix.lower() in (".png", ".jpg", ".jpeg", ".webp"):
+ out = args.output # one frame, one named image file: the caller's -o is the contract
+ else:
+ # several frames, or -o given as a stem/prefix without an image extension
+ out = os.path.join(outdir, f"{args.output and Path(args.output).stem or stem}_{sec:.3f}s.png")
stamp = "" if args.no_timecode else f",drawtext=text='{escape_drawtext(fmt_hms(sec))}':{font_prefix}{FONT}"
cmd = ffmpeg_base() + ["-ss", f"{sec:.3f}", "-i", args.input, "-vf", f"scale={args.width}:-2{tc.replace(',' + timecode_filter(font_prefix), '')}{stamp}", "-frames:v", "1", out]
run(cmd)
diff --git a/scripts/render.py b/scripts/render.py
index ccd2c3e..d7fedd2 100755
--- a/scripts/render.py
+++ b/scripts/render.py
@@ -166,6 +166,8 @@ def main() -> int:
part = src
if c.get("speed"):
spd = float(c["speed"])
+ if not (spd > 0) or spd != spd or spd == float("inf"):
+ die(f"clip {i}: speed must be a positive number, got {c['speed']!r}")
dur = (probe(part).get("duration") or 0.0) if not STATE.dry_run else 10.0
fitted = str(work / f"clip{i:02d}_speed.mp4")
sh("fit.py", part, "--duration", f"{dur / spd:.3f}", "-o", fitted)
diff --git a/scripts/report.py b/scripts/report.py
index fe6f9b9..920e263 100755
--- a/scripts/report.py
+++ b/scripts/report.py
@@ -57,7 +57,7 @@ def check(path: str, platform: str) -> Optional[Dict[str, Any]]:
def fmt_dur(sec: Optional[float]) -> str:
- if not sec:
+ if sec is None:
return "?"
m, s = divmod(sec, 60)
h, m = divmod(int(m), 60)
diff --git a/scripts/sequence.py b/scripts/sequence.py
index 05dd7f8..fb5a048 100644
--- a/scripts/sequence.py
+++ b/scripts/sequence.py
@@ -19,7 +19,7 @@ import sys
import tempfile
from pathlib import Path
-from _common import add_common, apply_common, default_output, die, emit, ffmpeg_base, info, probe, run, video_args, X264_PRESETS
+from _common import add_common, apply_common, default_output, die, emit, ffmpeg_base, info, probe, run, video_args, X264_PRESETS, concat_list_line
def even(n: float) -> int:
@@ -28,9 +28,7 @@ def even(n: float) -> int:
def _concat_list_line(path: Path) -> str:
- # concat demuxer file paths: backslash and single-quote need escaping inside the quoted form.
- escaped = str(path).replace("\\", "/").replace("'", "'\\''")
- return f"file '{escaped}'"
+ return concat_list_line(str(path))
def main() -> int:
diff --git a/tests/test_contract.py b/tests/test_contract.py
index 9000446..8cbda17 100644
--- a/tests/test_contract.py
+++ b/tests/test_contract.py
@@ -1324,6 +1324,47 @@ class ContractTests(unittest.TestCase):
self.assertEqual((doc["status"], doc["error"]["kind"], doc["processed"], doc["total"]), ("failed", "verification", 0, 1))
self.assertFalse(doc["results"][0]["ok"])
+ def test_bug_report_2026_09_12_regressions(self):
+ """Pins from the third audit: concat list lines are Windows-safe; SMPTE parse and format
+ agree at 29.97; cut/freeze accept SMPTE with the input's fps and refuse bad times as kind
+ input; look.py honours -o for a single --at; audio refuses --mono with --stereo and an
+ out-of-range --denoise-strength; render refuses speed 0; batch lists .ogg/.opus/.ts;
+ report's 0 s is 0 s; ffmpeg_version has a probe timeout. (speed 0 was already "unset", not a
+ division by zero as reported; a negative speed did reach fit.py.)"""
+ self.assertEqual(_common.concat_list_line("C:\\Users\\t\\part000.mp4"), "file 'C:/Users/t/part000.mp4'")
+ self.assertEqual(_common.concat_list_line("/a/it's.mp4"), "file '/a/it'\\''s.mp4'")
+ for tc in ("00:00:00:29", "00:00:01:00", "01:00:00:00", "00:59:56:12"):
+ secs = _common.parse_time(tc, 29.97)
+ self.assertEqual(_common.fmt_smpte_time(secs, 29.97), tc, tc)
+ self.assertAlmostEqual(_common.parse_time("01:00:00:00", 29.97), 3600 * 30 / 29.97, places=3)
+ proc = tool("cut", self.src, "--start", "00:00:01:00", "--end", "00:00:02:15", "--json", "-o", self.out("smpte_cut.mp4"))
+ self.assertEqual(proc.returncode, 0, proc.stderr[-300:])
+ proc = tool("cut", self.src, "--start", "00:00:01:99", "--end", "2", "--json", "-o", self.out("smpte_bad.mp4"), check=False)
+ self.assertEqual((proc.returncode != 0, json.loads(proc.stdout)["error"]["kind"]), (True, "input"))
+ self.assertIn("out of range", json.loads(proc.stdout)["error"]["message"])
+ proc = tool("freeze", self.src, "--at", "0:01", "--hold", "0.5", "--json", "-o", self.out("freeze_mmss.mp4"))
+ self.assertEqual(proc.returncode, 0, proc.stderr[-300:])
+ one = self.out("one_frame.png")
+ doc = json.loads(tool("look", self.src, "--at", "1", "--json", "-o", one).stdout)
+ self.assertEqual(doc["output"], str(one))
+ self.assertTrue(one.exists())
+ proc = tool("audio", self.src, "--mono", "--stereo", "-o", self.out("ms.mp4"), check=False)
+ self.assertEqual(proc.returncode, 2, "argparse refuses --mono with --stereo")
+ proc = tool("audio", self.src, "--denoise", "--denoise-strength", "-25", "--json", "-o", self.out("dn.mp4"), check=False)
+ self.assertEqual(json.loads(proc.stdout)["error"]["kind"], "input")
+ proj = self.out("speed0.json")
+ proj.write_text(json.dumps({"output": str(self.out("speed0.mp4")), "clips": [{"src": str(self.src), "speed": -1}]}))
+ proc = tool("render", proj, "--dry-run", "--json", check=False)
+ self.assertNotEqual(proc.returncode, 0)
+ self.assertIn("speed must be a positive number", json.loads(proc.stdout)["error"]["message"])
+ import batch as batch_mod # noqa: E402
+ self.assertTrue({".ogg", ".opus", ".ts", ".aac"} <= batch_mod.MEDIA_EXT)
+ import report as report_mod # noqa: E402
+ self.assertNotEqual(report_mod.fmt_dur(0.0), "?")
+ self.assertEqual(report_mod.fmt_dur(None), "?")
+ self.assertEqual(json.loads((ROOT / "package.json").read_text())["files"].count("docs/contract.md"), 1)
+ self.assertIn("'docs'", (ROOT / "bin" / "install.js").read_text())
+
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