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.

Add grid.py: composite clips into a COLSxROWS video grid

Claude725acd8d56f5
diff --git a/CHANGELOG.md b/CHANGELOG.md
index b6008cf..299c81b 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -6,6 +6,25 @@
(nothing yet)
+## 0.16.0 — add grid.py
+
+New tool: composite `--cols`x`--rows` clips into one grid (e.g. a 4x2 wall
+of takes or angles), each cell letterboxed (not stretched) to a common
+`--cell-width`/`--cell-height` so mismatched aspect ratios and resolutions
+line up cleanly. `--label auto` (default) burns each clip's own filename,
+extension stripped, into its cell's bottom-right corner; `--label none`
+turns that off. No audio unless `--audio-from` picks one input's track --
+mixing every clip's audio together is rarely what a comparison grid needs,
+so this tool never does it silently. Runs only as long as the shortest
+clip by default; `--pad` instead holds each shorter clip's last frame (with
+silence) out to the longest.
+
+The per-cell label is filename-derived text reaching a `drawtext=text=...`
+option, the same injection class fixed in 0.15.3 -- wrapped with the
+existing `escape_drawtext()` helper from the start, with a regression test
+that builds a clip literally named to look like a filter-graph breakout
+payload and confirms it renders as inert literal text (not a new filter).
+
## 0.15.3 — fix a real filter-graph injection via --font fallback
Found by the same adversarial pass that produced 0.15.2, this time auditing
diff --git a/README.md b/README.md
index b90c782..1228e8e 100644
--- a/README.md
+++ b/README.md
@@ -25,7 +25,7 @@ npx ffmpeg-skill
![before / after demo](assets/demo.gif)
-`ffmpeg-skill` is an [Agent Skill](https://docs.anthropic.com/en/docs/agents-and-tools/agent-skills) for Claude Code, Cursor, Codex and any agent that reads `SKILL.md`. It teaches the agent a fixed workflow (probe → edit losslessly where possible → check → verify) and ships **39 tools** that do the actual work with `ffmpeg` / `ffprobe`: cut, join, silence removal, fit to duration and aspect, captions and karaoke, overlays and motion graphics, HDR → SDR and LUTs, audio clean-up and typed dynamics, sync with drift correction, multicam, loudness, delivery checks, whole-edit project rendering, batch folders. Every tool is also an MCP tool, and the whole set is described by a machine-readable contract.
+`ffmpeg-skill` is an [Agent Skill](https://docs.anthropic.com/en/docs/agents-and-tools/agent-skills) for Claude Code, Cursor, Codex and any agent that reads `SKILL.md`. It teaches the agent a fixed workflow (probe → edit losslessly where possible → check → verify) and ships **40 tools** that do the actual work with `ffmpeg` / `ffprobe`: cut, join, silence removal, fit to duration and aspect, captions and karaoke, overlays and motion graphics, HDR → SDR and LUTs, audio clean-up and typed dynamics, sync with drift correction, multicam, loudness, delivery checks, whole-edit project rendering, batch folders. Every tool is also an MCP tool, and the whole set is described by a machine-readable contract.
If `ffmpeg` and `python3` are on your PATH, it works: offline, on footage you would rather not upload.
@@ -139,7 +139,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.
-4. **Machine-readable contract.** `contract --json` describes all 39 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 39 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`.
+4. **Machine-readable contract.** `contract --json` describes all 40 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.
7. **Unknown is not missing.** When a listing cannot be read (a layout the parser does not know, ffmpeg exiting non-zero) the affected capabilities are `unknown`: never `missing`, never silently `available`. An installed filter is not reported absent; a failed detection is not a pass.
@@ -148,7 +148,7 @@ These are the rules the skill file gives the agent and the code enforces. Togeth
## Tools
-39 public tools, all Python 3.9 standard library, all with `--help`, `--dry-run`, `--json`, non-zero exit and a reason on stderr on failure.
+40 public tools, all Python 3.9 standard library, all with `--help`, `--dry-run`, `--json`, non-zero exit and a reason on stderr on failure.
**Analysis and inspection**
@@ -183,6 +183,7 @@ These are the rules the skill file gives the agent and the code enforces. Togeth
| `pad.py` | Add black/silent padding at the start and/or end of the timeline (`--start`, `--end`) — distinct from `fit.py --fit pad`'s per-frame letterbox bars |
| `speedramp.py` | Step through different constant speeds across a clip via `--segment START-END:FACTOR` (repeatable) — distinct from `fit.py`'s single whole-clip speed factor |
| `loop.py` | Repeat a clip `--times` N or to a target `--duration` — for background loops and filling a fixed slot length |
+| `grid.py` | Composite `--cols`x`--rows` clips into one grid, each cell letterboxed and labelled with its filename by default (`--label none` to skip) |
**Audio**
@@ -270,7 +271,7 @@ npx ffmpeg-skill contract --json # or: python3 scripts/_contract.py -
npx ffmpeg-skill contract --json --static # without environment detection
```
-The contract is generated from the code that runs, not maintained beside it. For each of the 39 tools (`ffmpeg-skill/<name>`) it states:
+The contract is generated from the code that runs, not maintained beside it. For each of the 40 tools (`ffmpeg-skill/<name>`) it states:
| Field | Meaning |
|---|---|
@@ -295,7 +296,7 @@ The contract is generated from the code that runs, not maintained beside it. For
On Windows, `python3` is only on PATH if Python was installed from the Microsoft Store; a python.org install exposes `python` (or the `py` launcher) instead — if your MCP client reports the server failed to start, change `"command"` above to `"python"` (or the full path from `where python`).
-`mcp/server.py` is a stdio JSON-RPC transport with no tool table of its own. `tools/list` is derived from the contract at start-up: the same 39 names, the same order, and `inputSchema` translated from each tool's `input_schema`. `tools/call` maps structured arguments to argv and runs the named script; a raw `argv` form is accepted for compatibility and marked non-canonical. `python3 mcp/server.py --list` prints the tools; `--call probe '{"inputs": ["a.mp4"]}'` runs one from the shell.
+`mcp/server.py` is a stdio JSON-RPC transport with no tool table of its own. `tools/list` is derived from the contract at start-up: the same 40 names, the same order, and `inputSchema` translated from each tool's `input_schema`. `tools/call` maps structured arguments to argv and runs the named script; a raw `argv` form is accepted for compatibility and marked non-canonical. `python3 mcp/server.py --list` prints the tools; `--call probe '{"inputs": ["a.mp4"]}'` runs one from the shell.
### Capability detection
diff --git a/SKILL.md b/SKILL.md
index 205bd71..5b55e5c 100644
--- a/SKILL.md
+++ b/SKILL.md
@@ -149,6 +149,7 @@ If a request needs an FFmpeg feature none of the 28 scripts expose, say so and n
| "add some black at the start before the title card" | `pad.py clip.mp4 --start 1.5` |
| "speed up here, slam into slow-mo there, then speed back up" (known segments) | `speedramp.py action.mp4 --segment 0-3:1.0 --segment 3-4:0.25 --segment 4-8:2.0` |
| "loop this background clip to fill 30 seconds" | `loop.py bg_loop.mp4 --duration 30` |
+| "put these videos in a 4x2 grid with the filename on each" | `grid.py t1.mp4 t2.mp4 t3.mp4 t4.mp4 t5.mp4 t6.mp4 t7.mp4 t8.mp4 --cols 4 --rows 2` |
| "add subtitles from this SRT", "burn in captions" | `caption.py input.mp4 --srt subs.srt` |
| "caption it with these lines" (plain text with times) | `caption.py input.mp4 --text cues.txt` |
| "add subtitles but keep them toggleable / editable", "mux in an SRT, don't burn it" | `caption.py input.mp4 --srt subs.srt --mode mux` |
diff --git a/docs/contract.md b/docs/contract.md
index 16d1972..4162f88 100644
--- a/docs/contract.md
+++ b/docs/contract.md
@@ -21,7 +21,7 @@ The contract is derived from the code that runs, not maintained beside it:
| Field | Meaning | Changes when |
|---|---|---|
| `contract_version` | shape of this document (`1.0`) | a key is renamed, removed or changes meaning |
-| `skill.version` | the npm / package.json version (`0.15.3`) | any release |
+| `skill.version` | the npm / package.json version (`0.16.0`) | any release |
A release that adds a tool or a flag keeps `contract_version`; a breaking change to the
ToolSpec shape bumps it. Consumers pin on `contract_version` and read `skill.version`
@@ -39,7 +39,7 @@ drifting silently.
```json
{
"contract_version": "1.0",
- "skill": {"id": "ffmpeg-skill", "version": "0.15.3", "execution_mode": "local", "kind": "execution",
+ "skill": {"id": "ffmpeg-skill", "version": "0.16.0", "execution_mode": "local", "kind": "execution",
"entrypoints": {"cli": "...", "mcp": "...", "contract": "...", "doctor": "..."},
"not_provided": ["AI reasoning", "decisions", "production plans", "project IR", "approvals", "network access", "transcription engine"]},
"requirements": {"python": ">=3.9 (standard library only)", "ffmpeg": ">=5.0", "ffprobe": ">=5.0"},
@@ -129,7 +129,7 @@ gives you:
## `provides`
-`provides` lists these 39 tools by a cross-repository Capability id, for
+`provides` lists these 40 tools by a cross-repository Capability id, for
`kajisho5/AI-video-production-OS`'s `CapabilityContract.provides`
(`docs/SPEC.md` there), matching the ids already assigned to this Skill in
that project's own `docs/CAPABILITY_MATRIX.md` section 9 ("ffmpeg-skill's
diff --git a/package.json b/package.json
index d8e90ac..dc67c13 100644
--- a/package.json
+++ b/package.json
@@ -1,7 +1,7 @@
{
"name": "ffmpeg-skill",
- "version": "0.15.3",
- "description": "Agent Skill that gives coding agents (Claude Code, Cursor, Codex) a local video editor: 39 FFmpeg tools with a machine-readable contract, contract-derived MCP server, FFmpeg capability detection, probe-first / verify-last workflow. Cut, join, silence removal, fit, captions and karaoke, overlays, motion graphics, HDR to SDR, LUTs, audio clean-up and typed dynamics, sync with drift correction, multicam, loudness, delivery checks, project rendering, batch. No API keys, no cloud, no dependencies.",
+ "version": "0.16.0",
+ "description": "Agent Skill that gives coding agents (Claude Code, Cursor, Codex) a local video editor: 40 FFmpeg tools with a machine-readable contract, contract-derived MCP server, FFmpeg capability detection, probe-first / verify-last workflow. Cut, join, silence removal, fit, captions and karaoke, overlays, motion graphics, HDR to SDR, LUTs, audio clean-up and typed dynamics, sync with drift correction, multicam, loudness, delivery checks, project rendering, batch. No API keys, no cloud, no dependencies.",
"keywords": [
"ffmpeg",
"video",
diff --git a/references/scripts.md b/references/scripts.md
index e00c6eb..b930cf3 100644
--- a/references/scripts.md
+++ b/references/scripts.md
@@ -283,6 +283,22 @@ loop point (no crossfade at the seam) -- a clip that doesn't already loop
cleanly will show a visible cut/pop at each repeat, which is a property of
the source material this tool cannot fix.
+### grid.py — composite clips into a grid
+```
+grid.py CLIP1 CLIP2 [...] --cols N --rows N [--cell-width W] [--cell-height H]
+ [--label auto|none] [--font NAME] [--audio-from I]
+ [--pad] [-o OUT]
+```
+Letterboxes every clip into a common `--cell-width`x`--cell-height` cell (no
+stretching) and tiles them `--cols`x`--rows`, filled left-to-right,
+top-to-bottom -- the input count must equal cols*rows exactly. `--label auto`
+(default) burns each clip's filename (extension stripped) into its cell's
+bottom-right corner; `--label none` skips it. No audio unless `--audio-from`
+picks one input's track by index -- mixing every clip's audio together is
+rarely useful for a comparison grid, so this tool never does that silently.
+Runs only as long as the shortest clip by default; `--pad` instead holds
+each shorter clip's last frame (with silence) out to the longest.
+
### silence.py — remove dead air / jump cuts
```
silence.py INPUT [--threshold -35] [--min-silence 0.6] [--margin 0.15] [--min-keep 0.2] [--list] [--edl keep.txt] [-o OUT]
diff --git a/scripts/_contract.py b/scripts/_contract.py
index 806d8d6..c749092 100644
--- a/scripts/_contract.py
+++ b/scripts/_contract.py
@@ -97,6 +97,9 @@ TOOL_META: Dict[str, Dict[str, Any]] = {
"sphere": dict(role="execution", inputs=["360/spherical video asset"], outputs=["flat rectilinear video artifact of the chosen viewport"],
required=FF + [X264, AAC, "filter:v360"], optional=[HDR_X265],
video_required=True, audio_only=False, visual=True, verify=["probe", "look"], produces_artifact=True, idempotency="content_equivalent", deterministic=True),
+ "grid": dict(role="execution", inputs=["cols*rows video assets, filled left-to-right top-to-bottom"], outputs=["composited grid video artifact"],
+ required=FF + [X264, "filter:xstack"], optional=[{"capability": "filter:drawtext", "when": "--label auto (the default)"}, {"capability": AAC, "when": "--audio-from"}],
+ video_required=True, audio_only=False, visual=True, verify=["probe", "look"], produces_artifact=True, idempotency="content_equivalent", deterministic=True),
"straighten": dict(role="execution", inputs=["video asset"], outputs=["video artifact rotated by the given angle (horizon correction)"],
required=FF + [X264, AAC, "filter:rotate"], optional=[HDR_X265],
video_required=True, audio_only=False, visual=True, verify=["probe", "look"], produces_artifact=True, idempotency="content_equivalent", deterministic=True),
@@ -230,6 +233,7 @@ REENCODE_META: Dict[str, Dict[str, str]] = {
"waveform": dict(video="always", audio="always", note="always encodes a fresh generated visualization clip; the source audio is always re-encoded to AAC"),
"sphere": dict(video="always", audio="always", note="the v360 filter always forces a re-encode of the video stream; audio is passed through to AAC unchanged"),
"straighten": dict(video="always", audio="always", note="the rotate filter always forces a re-encode of the video stream; audio is re-encoded to AAC when present"),
+ "grid": dict(video="always", audio="conditional", note="the xstack composite always forces a re-encode of the video stream; there is no audio at all unless --audio-from picks one input's track, which is then re-encoded to AAC"),
"freeze": dict(video="always", audio="always", note="the tpad/concat filter graph always forces a re-encode of the video stream; audio is re-encoded to AAC when present"),
"pad": dict(video="always", audio="always", note="the tpad filter always forces a re-encode of the video stream; audio is re-encoded to AAC when present"),
"speedramp": dict(video="always", audio="always", note="setpts/atempo per segment always forces a re-encode of both streams"),
diff --git a/scripts/grid.py b/scripts/grid.py
new file mode 100644
index 0000000..6a3216b
--- /dev/null
+++ b/scripts/grid.py
@@ -0,0 +1,137 @@
+#!/usr/bin/env python3
+"""Composite several video clips into one COLSxROWS grid, e.g. a 4x2 wall of
+takes, angles, or A/B renders side by side.
+
+Every cell is letterboxed (not stretched) to a common --cell-width/--cell-height
+so clips of different aspect ratios and resolutions line up cleanly. By default
+each cell gets its source filename (extension stripped) burnt into the bottom
+right corner -- --label none turns that off. The grid has no audio unless
+--audio-from picks one input's track to carry through; mixing every clip's
+audio together is rarely what a comparison grid is for, so this tool never
+does it silently.
+
+The grid runs only as long as its shortest clip (--shortest, the default) or
+is padded to the longest with black+silence (--pad); a mismatched frame rate
+across sources is conformed to --fps first so cells stay in sync.
+
+Examples:
+ python3 grid.py take1.mp4 take2.mp4 take3.mp4 take4.mp4 take5.mp4 take6.mp4 take7.mp4 take8.mp4 --cols 4 --rows 2
+ python3 grid.py a.mp4 b.mp4 c.mp4 d.mp4 --cols 2 --rows 2 --label none -o compare.mp4
+ python3 grid.py cam1.mp4 cam2.mp4 --cols 2 --rows 1 --audio-from 0 --pad
+"""
+import argparse
+import os
+import sys
+
+from _common import add_common, apply_common, aac_args, cfr_args, default_font_file, default_output, die, emit, \
+ escape_drawtext, escape_filter_path, ffmpeg_base, info, probe, run, validate_color, video_args
+
+LABEL_MARGIN = 10
+
+
+def main() -> int:
+ ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
+ ap.add_argument("inputs", nargs="+", help="video clips, filled into the grid left-to-right, top-to-bottom")
+ ap.add_argument("-o", "--output", help="output file (default: <first name>_grid.<ext>)")
+ ap.add_argument("--cols", type=int, required=True, help="grid columns")
+ ap.add_argument("--rows", type=int, required=True, help="grid rows")
+ ap.add_argument("--cell-width", type=int, default=480, help="each cell's width in px, must be even (default 480)")
+ ap.add_argument("--cell-height", type=int, default=270, help="each cell's height in px, must be even (default 270)")
+ ap.add_argument("--fps", type=float, default=30.0, help="output frame rate every cell is conformed to (default 30)")
+ ap.add_argument("--label", choices=["auto", "none"], default="auto",
+ help="auto (default): burn each cell's filename (extension stripped) into its bottom-right corner; none: no label")
+ ap.add_argument("--font", default="DejaVu Sans", help="label font (fontconfig family name, default DejaVu Sans)")
+ ap.add_argument("--font-size", type=int, default=16, help="label font size (default 16)")
+ ap.add_argument("--font-color", default="white", help="label text colour (default white)")
+ ap.add_argument("--pad", action="store_true", help="pad every cell to the longest clip's duration with black+silence instead of stopping at the shortest")
+ ap.add_argument("--audio-from", type=int, help="0-based index into inputs to take audio from (default: no audio)")
+ ap.add_argument("--gap", type=int, default=0, help="gap between cells in px, must be even (default 0, cells touch)")
+ ap.add_argument("--background", default="black", help="colour of the gap/pad borders (default black)")
+ ap.add_argument("--crf", type=int, default=18, help="x264 CRF (default 18)")
+ ap.add_argument("--preset", default="medium", help="x264 preset")
+ add_common(ap)
+ args = ap.parse_args()
+ apply_common(args)
+
+ n = args.cols * args.rows
+ if args.cols <= 0 or args.rows <= 0:
+ die(f"--cols/--rows must be > 0, got cols={args.cols} rows={args.rows}")
+ if len(args.inputs) != n:
+ die(f"--cols {args.cols} --rows {args.rows} needs exactly {n} inputs, got {len(args.inputs)}")
+ if args.cell_width <= 0 or args.cell_height <= 0:
+ die(f"--cell-width/--cell-height must be > 0, got width={args.cell_width} height={args.cell_height}")
+ if args.cell_width % 2 or args.cell_height % 2:
+ die(f"--cell-width/--cell-height must be even (4:2:0 chroma), got width={args.cell_width} height={args.cell_height}")
+ if args.fps <= 0:
+ die(f"--fps must be > 0, got {args.fps:g}")
+ if args.gap < 0 or args.gap % 2:
+ die(f"--gap must be >= 0 and even, got {args.gap}")
+ validate_color(args.background, "--background")
+ if args.font_color:
+ validate_color(args.font_color, "--font-color")
+ if args.audio_from is not None and not 0 <= args.audio_from < n:
+ die(f"--audio-from {args.audio_from}: must be an input index 0..{n - 1}")
+
+ metas = [probe(p) for p in args.inputs]
+ for p, m in zip(args.inputs, metas):
+ if not m.get("video"):
+ die(f"{p}: input has no video stream")
+ if args.audio_from is not None and not metas[args.audio_from].get("audio"):
+ die(f"--audio-from {args.audio_from}: {args.inputs[args.audio_from]} has no audio stream")
+
+ durations = [m.get("duration") or 0.0 for m in metas]
+ target_duration = max(durations) if args.pad else min(durations)
+
+ font_file = default_font_file(args.font)
+ output = args.output or default_output(args.inputs[0], "grid")
+
+ cmd = ffmpeg_base()
+ for p in args.inputs:
+ cmd += ["-i", p]
+
+ parts = []
+ for i, p in enumerate(args.inputs):
+ chain = [
+ f"fps={args.fps:g}",
+ f"scale={args.cell_width}:{args.cell_height}:force_original_aspect_ratio=decrease",
+ f"pad={args.cell_width}:{args.cell_height}:(ow-iw)/2:(oh-ih)/2:color={args.background}",
+ "setsar=1",
+ ]
+ if args.pad and durations[i] < target_duration:
+ chain.append(f"tpad=stop_mode=clone:stop_duration={target_duration - durations[i]:.3f}")
+ elif not args.pad:
+ chain.append(f"trim=duration={target_duration:.3f}")
+ if args.label == "auto":
+ stem = os.path.splitext(os.path.basename(p))[0]
+ font_opt = f"fontfile={escape_filter_path(font_file)}" if font_file else f"font='{escape_drawtext(args.font)}'"
+ chain.append(f"drawtext=text='{escape_drawtext(stem)}':{font_opt}:fontsize={args.font_size}:"
+ f"fontcolor={args.font_color}:x=w-tw-{LABEL_MARGIN}:y=h-th-{LABEL_MARGIN}:"
+ f"box=1:[email protected]:boxborderw=4")
+ parts.append(f"[{i}:v]{','.join(chain)}[v{i}]")
+
+ cw, ch = args.cell_width + args.gap, args.cell_height + args.gap
+ layout = "|".join(f"{c * cw}_{r * ch}" for r in range(args.rows) for c in range(args.cols))
+ parts.append("".join(f"[v{i}]" for i in range(n)) + f"xstack=inputs={n}:layout={layout}:fill={args.background}[out]")
+ cmd += ["-filter_complex", ";".join(parts), "-map", "[out]"]
+
+ if args.audio_from is not None:
+ cmd += ["-map", f"{args.audio_from}:a:0"]
+ cmd += video_args(None, args.crf, args.preset)
+ cmd += cfr_args(None, args.fps)
+ if args.audio_from is not None:
+ cmd += aac_args()
+ else:
+ cmd += ["-an"]
+ cmd += ["-t", f"{target_duration:.3f}", output]
+ run(cmd)
+
+ result = probe(output, role="output")
+ v = result["video"]
+ info(f"wrote {output} ({result['duration']:.3f}s, {v['width']}x{v['height']}, {args.cols}x{args.rows} grid, "
+ f"{n} clips, {'padded to longest' if args.pad else 'stopped at shortest'})")
+ emit(output, cols=args.cols, rows=args.rows, clips=n)
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/tests/test_all.py b/tests/test_all.py
index 5a17f6f..4bbc19a 100644
--- a/tests/test_all.py
+++ b/tests/test_all.py
@@ -505,6 +505,46 @@ class FFmpegSkillTests(unittest.TestCase):
def test_loop_duration_shorter_than_source_refused(self):
script("loop.py", self.src, "--duration", "3", expect_fail=True)
+ # ---------------------------------------------------------------- grid
+ def test_grid_composites_cols_rows_with_labels(self):
+ out = OUT / "grid1.mp4"
+ script("grid.py", self.src, self.rot, self.vfr, self.hdr, "--cols", "2", "--rows", "2",
+ "--cell-width", "320", "--cell-height", "180", "-o", out)
+ m = probe(str(out))
+ self.assertEqual((m["video"]["width"], m["video"]["height"]), (640, 360))
+
+ def test_grid_wrong_input_count_refused(self):
+ script("grid.py", self.src, self.rot, "--cols", "2", "--rows", "2", expect_fail=True)
+
+ def test_grid_label_none_skips_drawtext(self):
+ proc = script("grid.py", self.src, self.rot, "--cols", "2", "--rows", "1", "--label", "none", "-o", OUT / "grid2.mp4")
+ self.assertNotIn("drawtext", proc.stderr)
+
+ def test_grid_audio_from_selects_track(self):
+ out = OUT / "grid3.mp4"
+ script("grid.py", self.src, self.rot, "--cols", "2", "--rows", "1", "--audio-from", "1", "-o", out)
+ m = probe(str(out))
+ self.assertTrue(m.get("audio"))
+
+ def test_grid_pad_extends_shorter_clip_to_the_longest(self):
+ short = OUT / "grid_short.mp4"
+ sh("ffmpeg", "-y", "-hide_banner", "-loglevel", "error", "-i", self.src, "-t", "2", "-c", "copy", short)
+ out = OUT / "grid4.mp4"
+ script("grid.py", short, self.src, "--cols", "2", "--rows", "1", "--pad", "-o", out)
+ m = probe(str(out))
+ self.assertClose(m["duration"], probe(str(self.src))["duration"], 0.5)
+
+ def test_grid_filename_derived_label_refuses_filter_graph_injection(self):
+ """The per-cell label is the clip's own filename (extension stripped), which the caller
+ does not choose through a flag -- but on a filesystem where filenames can contain a comma
+ or colon, it still reaches a drawtext=text=... option the same way --font's fallback did
+ in the #108 finding. Confirm the escaping catches it: a filename shaped like a filter-graph
+ breakout payload must render literally, not start a sibling filter."""
+ evil = OUT / "evil,drawtext=text=OWNED.mp4"
+ sh("ffmpeg", "-y", "-hide_banner", "-loglevel", "error", "-i", self.src, "-t", "2", "-c", "copy", evil)
+ proc = script("grid.py", evil, self.rot, "--cols", "2", "--rows", "1", "-o", OUT / "grid5.mp4")
+ self.assertIn("\\,drawtext=text=OWNED", proc.stderr, "comma in the filename-derived label must be escaped")
+
# ---------------------------------------------------------------- insert
def test_insert_native_size_and_duration(self):
out = OUT / "insert1.mp4"
diff --git a/tests/test_contract.py b/tests/test_contract.py
index 92f7821..db68a1d 100644
--- a/tests/test_contract.py
+++ b/tests/test_contract.py
@@ -485,7 +485,7 @@ class ContractTests(unittest.TestCase):
def test_visual_verification_metadata(self):
picture = {"fit", "crop", "sphere", "insert", "background", "reverse", "stabilize", "sequence", "caption", "overlay", "graphics", "color", "join", "multicam", "render", "proxy",
- "deinterlace", "denoise", "redact", "waveform", "straighten", "freeze", "pad", "speedramp", "loop"}
+ "deinterlace", "denoise", "redact", "waveform", "straighten", "freeze", "pad", "speedramp", "loop", "grid"}
# join and waveform are the picture tools that also accept audio-only inputs (audio
# concat; audio-track visualization); look applies to their video output only, which
# SKILL.md states next to "Look: not needed"