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 fit.py --height, crop.py, and insert.py (#44)

Shogo Kajiyama0ec4ce8fb86b
diff --git a/CHANGELOG.md b/CHANGELOG.md
index ea2e13f..240608b 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -4,6 +4,24 @@
## Unreleased
+- **`fit.py --height`.** Only `--width` existed ("output width ... height follows the aspect").
+ Added a symmetric `--height` that mirrors `join.py`'s existing width/height resolution: give
+ one and the other follows the aspect (the source aspect, or `--aspect` if also given); give
+ both for an exact frame. `--width` alone still behaves exactly as before.
+- **`crop.py`: crop to an exact pixel rectangle.** `fit.py --fit crop` crops to a target *aspect
+ ratio*, computing the rectangle itself; there was no way to crop to a rectangle the caller
+ already knows (a face-detection box, a saved crop, a hand-picked region). New tool takes
+ `--x --y --width --height` in source pixels, validated before ffmpeg runs: refuses negative
+ offsets, non-positive or odd width/height (4:2:0 chroma, this codebase's even-size convention
+ — refused rather than silently rounded, since a caller-specified rectangle should do exactly
+ what was asked or fail loudly), and a rectangle that doesn't fit inside the source frame
+ (accounting for display rotation).
+- **`insert.py`: still image to a timed silent video clip.** Given one image, a duration, and
+ optional target frame size / fps, produces a silent, constant-frame-rate clip of exactly that
+ duration and size — for title cards, end slates, or placeholders alongside real footage in
+ `join.py`. `--width`/`--height` resolve the same way `fit.py`'s do (one given -> the other
+ follows the image's aspect; both given -> exact frame, scaled to fill and centre-cropped, never
+ distorted). Refuses non-positive `--duration`/`--fps`.
- **`join.py`: joining two or more audio-less clips together failed.** Each clip missing an audio
track gets a synthetic silent input (`-f lavfi -i anullsrc=...`) appended to the ffmpeg command;
the filtergraph index for that input was computed as `n + len(extra_inputs)`, but
diff --git a/README.md b/README.md
index b0c1b26..11646d4 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 **21 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 **23 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.
@@ -127,7 +127,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 21 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 21 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 23 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 23 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.
@@ -153,7 +153,9 @@ These are the rules the skill file gives the agent and the code enforces. Togeth
| `cut.py` | In/out or multi-segment cuts, lossless `-c copy` first, re-encode fallback, `--accurate` for frame-exact video and sample-exact audio; reports `precision` |
| `join.py` | Concatenate clips with xfade transitions, normalising size, fps and audio; audio-only inputs are joined as audio |
| `silence.py` | Detect and remove dead air (jump cuts) with a margin around speech; list or export the cut list |
-| `fit.py` | Fit to a duration (pitch-preserving speed change or trim, smooth slow-mo) and/or aspect ratio (pad or crop, with `--crop-x`/`--crop-y` to keep an off-centre subject); force constant fps |
+| `fit.py` | Fit to a duration (pitch-preserving speed change or trim, smooth slow-mo) and/or aspect ratio (pad or crop, with `--crop-x`/`--crop-y` to keep an off-centre subject) and/or exact `--width`/`--height`; force constant fps |
+| `crop.py` | Crop to an exact pixel rectangle (`--x --y --width --height`) — distinct from `fit.py --fit crop`, which crops to an aspect ratio it computes itself |
+| `insert.py` | Turn a still image into a silent, fixed-duration video clip (title card, end slate) at an exact frame size / fps |
**Audio**
@@ -212,7 +214,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 21 tools (`ffmpeg-skill/<name>`) it states:
+The contract is generated from the code that runs, not maintained beside it. For each of the 23 tools (`ffmpeg-skill/<name>`) it states:
| Field | Meaning |
|---|---|
diff --git a/SKILL.md b/SKILL.md
index 4e656dc..fa2c380 100644
--- a/SKILL.md
+++ b/SKILL.md
@@ -76,7 +76,7 @@ This skill cuts, joins, measures, syncs, exports and checks files — it execute
- **Thumbnail or cover-image composition** — that's a design decision, not a measurement; a thumbnail-generation skill or the user makes it.
- **Understanding what a video is *about*** — this skill has no transcription or vision beyond `look.py`'s contact sheets, which exist for the calling agent's own eyes, not for this skill to interpret on its own.
-If a request needs an FFmpeg feature none of the 21 scripts expose, say so and name the closest built-in option (`--dry-run` to show what would run, or a documented limitation) — never fall back to guessing a raw `ffmpeg`/`ffprobe` invocation or a hand-built filter graph outside `scripts/*.py`. A raw command bypasses every guarantee this skill makes (no shell, typed arguments, verification afterwards); it is exactly the failure mode this skill exists to prevent, so it is never the fallback when a script's flag doesn't cover something.
+If a request needs an FFmpeg feature none of the 23 scripts expose, say so and name the closest built-in option (`--dry-run` to show what would run, or a documented limitation) — never fall back to guessing a raw `ffmpeg`/`ffprobe` invocation or a hand-built filter graph outside `scripts/*.py`. A raw command bypasses every guarantee this skill makes (no shell, typed arguments, verification afterwards); it is exactly the failure mode this skill exists to prevent, so it is never the fallback when a script's flag doesn't cover something.
## Request → script
@@ -87,6 +87,9 @@ If a request needs an FFmpeg feature none of the 21 scripts expose, say so and n
| "keep only these parts", "remove the middle" | `cut.py input.mp4 --segments 0-1:00,1:30-2:00` |
| "make it exactly 60 seconds", "fit it in 30s" | `fit.py input.mp4 --duration 60` (speed) or `--method trim` |
| "make it vertical / for TikTok / 9:16", "square for Instagram" | `fit.py input.mp4 --aspect 9:16 --fit pad` (or `--fit crop`) |
+| "resize to a specific height, width follows" | `fit.py input.mp4 --height 1080` (or `--width`, or both for an exact frame) |
+| "crop to this exact box/rectangle" (known x/y/width/height, not an aspect ratio) | `crop.py input.mp4 --x 100 --y 0 --width 1080 --height 1920` |
+| "turn this image into a N-second clip", "title card / end slate" | `insert.py title.png --duration 3` |
| "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` |
| "put our logo top-right", "add a watermark" | `overlay.py input.mp4 --image logo.png --position top-right --scale 200` |
diff --git a/docs/contract.md b/docs/contract.md
index 7cc0b5d..be29de0 100644
--- a/docs/contract.md
+++ b/docs/contract.md
@@ -122,7 +122,7 @@ gives you:
## `provides`
-`provides` lists these 21 tools by a cross-repository Capability id, for
+`provides` lists these 23 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/references/scripts.md b/references/scripts.md
index ac7e851..ad14328 100644
--- a/references/scripts.md
+++ b/references/scripts.md
@@ -6,6 +6,7 @@ Every script prints the same information with `--help`; this file exists so the
- probe.py — inspect
- cut.py — cut / join segments
- fit.py — target duration and/or aspect
+- crop.py — crop to an exact pixel rectangle
- silence.py — remove dead air / jump cuts
- join.py — concatenate with transitions
- render.py — the whole edit in one project.json
@@ -51,15 +52,29 @@ the result was "lossless stream copy" or "re-encoded".
### fit.py — target duration and/or aspect
```
fit.py INPUT [--duration T --method speed|trim [--from-center] [--max-speed 4]]
- [--aspect 16:9|9:16|1:1|4:5|W:H --fit pad|crop [--width W] [--pad-color black]]
+ [--aspect 16:9|9:16|1:1|4:5|W:H --fit pad|crop [--width W] [--height H] [--pad-color black]]
[--fps N] [-o OUT]
```
`speed` retimes video and audio together (pitch-preserving `atempo`); it
refuses factors beyond `--max-speed`. For slow motion add `--smooth blend`
(frame blending, fast) or `--smooth interpolate` (motion-compensated
`minterpolate`, fluid but roughly 10-20x slower than realtime). `trim` keeps
-the head (or the middle with `--from-center`). `--fps` forces a constant frame
-rate; VFR sources are conformed automatically even without it.
+the head (or the middle with `--from-center`). `--width`/`--height` set the
+output size: give one and the other follows the aspect (source aspect if
+`--aspect` isn't also given); give both for an exact frame. `--fps` forces a
+constant frame rate; VFR sources are conformed automatically even without it.
+
+### crop.py — crop to an exact pixel rectangle
+```
+crop.py INPUT --x X --y Y --width W --height H [-o OUT]
+```
+Crops to a literal `{x, y, width, height}` rectangle in source pixels —
+distinct from `fit.py --fit crop`, which crops to an *aspect ratio* and picks
+the rectangle for you. Use this when the rectangle is already known (a
+face-detection box, a saved crop, a hand-picked region). The rectangle must
+lie entirely inside the source frame (after accounting for display rotation);
+`--width`/`--height` must be even (4:2:0 chroma) and are refused, never
+rounded, if they aren't.
### silence.py — remove dead air / jump cuts
```
diff --git a/scripts/_contract.py b/scripts/_contract.py
index 2e6f8fc..da5662b 100644
--- a/scripts/_contract.py
+++ b/scripts/_contract.py
@@ -70,6 +70,12 @@ TOOL_META: Dict[str, Dict[str, Any]] = {
"fit": dict(role="execution", inputs=["video asset"], outputs=["video artifact at the requested duration / aspect / fps"],
required=FF + [X264, AAC], optional=[HDR_X265, {"capability": "filter:minterpolate", "when": "--smooth interpolate"}],
video_required=True, audio_only=False, visual=True, verify=["probe", "look"], produces_artifact=True, idempotency="content_equivalent", deterministic=True),
+ "crop": dict(role="execution", inputs=["video asset"], outputs=["video artifact cropped to the given pixel rectangle"],
+ required=FF + [X264, AAC], optional=[HDR_X265],
+ video_required=True, audio_only=False, visual=True, verify=["probe", "look"], produces_artifact=True, idempotency="content_equivalent", deterministic=True),
+ "insert": dict(role="execution", inputs=["still image"], outputs=["silent video artifact of the requested duration / frame size / fps"],
+ required=FF + [X264], optional=[],
+ video_required=True, audio_only=False, visual=True, verify=["probe", "look"], produces_artifact=True, idempotency="content_equivalent", deterministic=True),
"caption": dict(role="execution", inputs=["video asset", "SRT/ASS file or timed text (--text)"], outputs=["video artifact with burnt-in captions", "generated .srt / .ass sidecar"],
required=FF + [X264, AAC, "filter:subtitles"], optional=[{"capability": "filter:ass", "when": "--animate / --karaoke"}, HDR_X265, {"capability": "external:whisper", "when": "--transcribe"}],
video_required=True, audio_only=False, visual=True, verify=["probe", "look"], produces_artifact=True, idempotency="content_equivalent", deterministic=True),
@@ -159,6 +165,8 @@ REENCODE_META: Dict[str, Dict[str, str]] = {
"probe": dict(video="never", audio="never", note="analysis only, no artifact"),
"cut": dict(video="conditional", audio="conditional", note="lossless -c copy preferred; re-encodes on --accurate, a VFR source, or a keyframe snap past --tolerance (see cut.py --json: mode, keyframe_snapped)"),
"fit": dict(video="always", audio="always", note="always re-encodes to AAC when audio is present, even if only --fps or --aspect was asked for"),
+ "crop": dict(video="always", audio="always", note="the crop filter always forces a re-encode of both streams"),
+ "insert": dict(video="always", audio="never", note="always encodes a fresh silent clip from the still image; there is no audio stream to touch"),
"caption": dict(video="always", audio="always", note="burn-in only: no soft-subtitle mux path exists, so captions always cost a full re-encode of both streams"),
"overlay": dict(video="always", audio="always"),
"graphics": dict(video="always", audio="always"),
diff --git a/scripts/crop.py b/scripts/crop.py
new file mode 100644
index 0000000..da5f636
--- /dev/null
+++ b/scripts/crop.py
@@ -0,0 +1,79 @@
+#!/usr/bin/env python3
+"""Crop a video to an exact pixel rectangle.
+
+{x, y, width, height} are literal pixel offsets and dimensions in the SOURCE
+frame, not aspect-ratio-relative -- for cropping to a target aspect ratio
+(e.g. 16:9 -> 9:16) use fit.py --fit crop instead, which computes the
+rectangle for you and lets you steer it with --crop-x/--crop-y. This tool is
+for when the caller already knows the exact rectangle (a face-detection box,
+a saved crop from a previous edit, a hand-picked region).
+
+The rectangle must lie entirely inside the source frame after accounting for
+any display rotation, and --width/--height must be even (required for 4:2:0
+chroma subsampling, the pixel format every encoder here uses) -- given values
+are validated and refused, never silently rounded, since a caller-specified
+rectangle should do exactly what was asked or fail loudly.
+
+Examples:
+ python3 crop.py input.mp4 --x 100 --y 0 --width 1080 --height 1920
+ python3 crop.py input.mp4 --x 0 --y 140 --width 1920 --height 800 -o cropped.mp4
+"""
+import argparse
+import sys
+
+from _common import add_common, apply_common, aac_args, cfr_args, default_output, die, emit, ffmpeg_base, info, probe, run, video_args
+
+
+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>_crop.<ext>)")
+ ap.add_argument("--x", type=int, required=True, help="left edge of the crop rectangle, in source pixels")
+ ap.add_argument("--y", type=int, required=True, help="top edge of the crop rectangle, in source pixels")
+ ap.add_argument("--width", type=int, required=True, help="crop width in px (must be even)")
+ ap.add_argument("--height", type=int, required=True, help="crop height in px (must be even)")
+ ap.add_argument("--crf", type=int, default=18, help="x264 CRF (default 18)")
+ ap.add_argument("--preset", default="medium", help="x264 preset")
+ ap.add_argument("--fps", type=float, help="force a constant output frame rate (recommended for VFR sources)")
+ add_common(ap)
+ args = ap.parse_args()
+ apply_common(args)
+
+ if args.x < 0 or args.y < 0:
+ die(f"--x/--y must be >= 0, got x={args.x} y={args.y}")
+ if args.width <= 0 or args.height <= 0:
+ die(f"--width/--height must be > 0, got width={args.width} height={args.height}")
+ if args.width % 2 or args.height % 2:
+ die(f"--width/--height must be even (4:2:0 chroma), got width={args.width} height={args.height}")
+
+ meta = probe(args.input)
+ if not meta.get("video"):
+ die("input has no video stream")
+ sw, sh = meta["video"]["width"], meta["video"]["height"]
+ if meta["video"].get("rotation") in (90, -90, 270, -270):
+ sw, sh = sh, sw
+ if args.x + args.width > sw or args.y + args.height > sh:
+ die(f"crop rectangle ({args.x},{args.y},{args.width}x{args.height}) exceeds the source frame ({sw}x{sh})")
+ has_audio = bool(meta.get("audio"))
+
+ output = args.output or default_output(args.input, "crop")
+ vf = [f"crop={args.width}:{args.height}:{args.x}:{args.y}", "setsar=1"]
+ cmd = ffmpeg_base() + ["-i", args.input, "-vf", ",".join(vf)]
+ cmd += video_args(meta, args.crf, args.preset)
+ cmd += cfr_args(meta, args.fps)
+ if has_audio:
+ cmd += aac_args()
+ else:
+ cmd += ["-an"]
+ cmd.append(output)
+ run(cmd)
+
+ result = probe(output)
+ v = result["video"]
+ info(f"wrote {output} ({result['duration']:.3f}s, {v['width']}x{v['height']})")
+ emit(output)
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/scripts/fit.py b/scripts/fit.py
index 8a1d8e7..505f10b 100755
--- a/scripts/fit.py
+++ b/scripts/fit.py
@@ -5,7 +5,9 @@ Duration: --duration N with --method speed (retime video+audio, pitch-preserving
via atempo chaining) or --method trim (keep the first N seconds, or a centred
window with --from-center). Aspect: --aspect 16:9|9:16|1:1|4:5|W:H with
--fit pad (letterbox/pillarbox with --pad-color, default black) or --fit crop.
---width sets the output width; height follows the aspect.
+--width and/or --height set the output size: give one and the other follows
+the aspect (source aspect if --aspect is not also given); give both for an
+exact frame.
Crop keeps the centre of the frame by default, which is a guess: going from
16:9 to 9:16 throws away most of the width, and whatever isn't in the middle
@@ -20,6 +22,8 @@ Examples:
python3 fit.py input.mp4 --aspect 9:16 --fit pad --width 1080
python3 fit.py input.mp4 --aspect 1:1 --fit crop --duration 15
python3 fit.py input.mp4 --aspect 9:16 --fit crop --crop-x 1 # keep the right edge (e.g. product held stage-right)
+ python3 fit.py input.mp4 --height 1080 # width follows the source aspect
+ python3 fit.py input.mp4 --width 1920 --height 1080 # exact frame, no aspect needed
"""
import argparse
import math
@@ -76,7 +80,8 @@ def main() -> int:
a = ap.add_argument_group("aspect")
a.add_argument("--aspect", help="target aspect ratio, e.g. 16:9, 9:16, 1:1, 4:5")
a.add_argument("--fit", choices=["pad", "crop"], default="pad", help="pad (letterbox) or crop to reach the aspect (default pad)")
- a.add_argument("--width", type=int, help="output width in px (default: keep source width or the width implied by the aspect)")
+ a.add_argument("--width", type=int, help="output width in px (default: keep source width or the width implied by the aspect); with --height also given, both are used directly")
+ a.add_argument("--height", type=int, help="output height in px (default: keep source height or the height implied by the aspect); with --width also given, both are used directly")
a.add_argument("--pad-color", default="black", help="pad colour, e.g. black, white, 0x101010 (default black)")
a.add_argument("--crop-x", type=float, default=0.5, help="with --fit crop, horizontal anchor 0=left, 0.5=centre (default), 1=right")
a.add_argument("--crop-y", type=float, default=0.5, help="with --fit crop, vertical anchor 0=top, 0.5=centre (default), 1=bottom")
@@ -88,8 +93,8 @@ def main() -> int:
args = ap.parse_args()
apply_common(args)
- if not args.duration and not args.aspect and not args.width and not args.fps:
- die("nothing to do: give --duration, --aspect, --width and/or --fps")
+ if not args.duration and not args.aspect and not args.width and not args.height and not args.fps:
+ die("nothing to do: give --duration, --aspect, --width/--height and/or --fps")
if not 0.0 <= args.crop_x <= 1.0:
die(f"--crop-x must be 0..1, got {args.crop_x}")
if not 0.0 <= args.crop_y <= 1.0:
@@ -142,14 +147,20 @@ def main() -> int:
info(f"source ({src_dur:.2f}s) is already shorter than {target:.2f}s; trim does nothing")
# ---- aspect / size
- if args.aspect or args.width:
+ if args.aspect or args.width or args.height:
src_ratio = Fraction(sw, sh)
ratio = parse_aspect(args.aspect) if args.aspect else src_ratio
- if args.width:
+ if args.width and args.height:
+ out_w, out_h = even(args.width), even(args.height)
+ elif args.width:
out_w = even(args.width)
+ out_h = even(out_w / ratio)
+ elif args.height:
+ out_h = even(args.height)
+ out_w = even(out_h * ratio)
else:
out_w = even(sw if ratio <= src_ratio else sh * ratio)
- out_h = even(out_w / ratio)
+ out_h = even(out_w / ratio)
if args.fit == "crop":
vf.append(f"scale={out_w}:{out_h}:force_original_aspect_ratio=increase")
vf.append(f"crop={out_w}:{out_h}:(in_w-out_w)*{args.crop_x:g}:(in_h-out_h)*{args.crop_y:g}")
diff --git a/scripts/insert.py b/scripts/insert.py
new file mode 100644
index 0000000..da44dae
--- /dev/null
+++ b/scripts/insert.py
@@ -0,0 +1,88 @@
+#!/usr/bin/env python3
+"""Turn a still image into a silent, timed video clip.
+
+Produces a fixed-duration, constant-frame-rate video from one image -- for
+example a title card, an end slate, or a placeholder to slot into join.py
+alongside real footage. The output has no audio track: pair it with audio.py
+or export.py's own audio handling if the surrounding edit needs sound under
+the still.
+
+--width/--height set the output frame size the same way fit.py does: give
+one and the other follows the image's own aspect; give both for an exact
+frame (the image is scaled to fill it, centre-cropping any excess -- never
+distorted). Omit both to keep the image's native size (evened for 4:2:0).
+
+Examples:
+ python3 insert.py title.png --duration 3
+ python3 insert.py slate.jpg --duration 5 --width 1920 --height 1080 --fps 30 -o slate.mp4
+"""
+import argparse
+import sys
+
+from _common import add_common, apply_common, default_output, die, emit, ffmpeg_base, info, parse_time, probe, run, video_args
+
+
+def even(n: float) -> int:
+ v = int(round(n))
+ return v if v % 2 == 0 else v + 1
+
+
+def main() -> int:
+ ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
+ ap.add_argument("input", help="still image (PNG/JPG/...)")
+ ap.add_argument("-o", "--output", help="output file (default: <name>_insert.mp4)")
+ ap.add_argument("--duration", required=True, help="clip duration (seconds or mm:ss)")
+ ap.add_argument("--width", type=int, help="output width in px; with --height also given, both are used directly")
+ ap.add_argument("--height", type=int, help="output height in px; with --width also given, both are used directly")
+ ap.add_argument("--fps", type=float, default=30.0, help="output frame rate (default 30)")
+ 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)
+
+ target = parse_time(args.duration)
+ if target <= 0:
+ die("--duration must be > 0")
+ if args.fps <= 0:
+ die("--fps must be > 0")
+
+ meta = probe(args.input)
+ if not meta.get("video"):
+ die("input has no image/video stream")
+ sw, sh = meta["video"]["width"], meta["video"]["height"]
+ ratio = sw / sh
+
+ if args.width and args.height:
+ out_w, out_h = even(args.width), even(args.height)
+ elif args.width:
+ out_w = even(args.width)
+ out_h = even(out_w / ratio)
+ elif args.height:
+ out_h = even(args.height)
+ out_w = even(out_h * ratio)
+ else:
+ out_w, out_h = even(sw), even(sh)
+
+ vf = [
+ f"scale={out_w}:{out_h}:force_original_aspect_ratio=increase",
+ f"crop={out_w}:{out_h}",
+ "setsar=1",
+ f"fps={args.fps:g}",
+ ]
+
+ output = args.output or default_output(args.input, "insert", "mp4")
+ cmd = ffmpeg_base() + ["-loop", "1", "-i", args.input, "-t", f"{target:.3f}", "-vf", ",".join(vf)]
+ cmd += video_args(None, args.crf, args.preset)
+ cmd += ["-an", output]
+ run(cmd)
+
+ result = probe(output)
+ v = result["video"]
+ info(f"wrote {output} ({result['duration']:.3f}s, {v['width']}x{v['height']}, {v['fps']:g}fps)")
+ emit(output)
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/tests/test_all.py b/tests/test_all.py
index 5bee81c..96db7f3 100644
--- a/tests/test_all.py
+++ b/tests/test_all.py
@@ -203,6 +203,62 @@ class FFmpegSkillTests(unittest.TestCase):
script("fit.py", self.src, "--aspect", "9:16", "--fit", "crop", "--crop-x", "1.5", expect_fail=True)
script("fit.py", self.src, "--aspect", "9:16", "--fit", "crop", "--crop-y", "-0.1", expect_fail=True)
+ def test_fit_height_alone_follows_source_aspect(self):
+ out = OUT / "fit_h.mp4"
+ script("fit.py", self.src, "--height", "480", "-o", out)
+ m = probe(str(out))
+ # source is 1280x720 (16:9); height 480 -> width 853.33 rounds to even 854
+ self.assertEqual((m["video"]["width"], m["video"]["height"]), (854, 480))
+
+ def test_fit_width_and_height_both_given_is_exact(self):
+ out = OUT / "fit_wh.mp4"
+ script("fit.py", self.src, "--width", "500", "--height", "500", "-o", out)
+ m = probe(str(out))
+ self.assertEqual((m["video"]["width"], m["video"]["height"]), (500, 500))
+
+ def test_fit_width_alone_still_works(self):
+ out = OUT / "fit_w.mp4"
+ script("fit.py", self.src, "--width", "640", "-o", out)
+ m = probe(str(out))
+ self.assertEqual((m["video"]["width"], m["video"]["height"]), (640, 360))
+
+ # ---------------------------------------------------------------- crop
+ def test_crop_exact_rectangle(self):
+ out = OUT / "crop1.mp4"
+ script("crop.py", self.src, "--x", "100", "--y", "0", "--width", "1080", "--height", "720", "-o", out)
+ m = probe(str(out))
+ self.assertEqual((m["video"]["width"], m["video"]["height"]), (1080, 720))
+ self.assertClose(m["duration"], 12.0, 0.2)
+
+ def test_crop_out_of_bounds_is_refused(self):
+ script("crop.py", self.src, "--x", "1200", "--y", "0", "--width", "200", "--height", "200", expect_fail=True)
+
+ def test_crop_odd_dimensions_refused(self):
+ script("crop.py", self.src, "--x", "0", "--y", "0", "--width", "101", "--height", "100", expect_fail=True)
+
+ def test_crop_negative_offset_refused(self):
+ script("crop.py", self.src, "--x", "-5", "--y", "0", "--width", "100", "--height", "100", expect_fail=True)
+
+ # ---------------------------------------------------------------- insert
+ def test_insert_native_size_and_duration(self):
+ out = OUT / "insert1.mp4"
+ script("insert.py", self.logo, "--duration", "3", "-o", out)
+ m = probe(str(out))
+ self.assertClose(m["duration"], 3.0, 0.15)
+ self.assertEqual((m["video"]["width"], m["video"]["height"]), (240, 90))
+ self.assertIsNone(m["audio"])
+
+ def test_insert_exact_frame_size_and_fps(self):
+ out = OUT / "insert2.mp4"
+ script("insert.py", self.logo, "--duration", "2", "--width", "500", "--height", "500", "--fps", "24", "-o", out)
+ m = probe(str(out))
+ self.assertClose(m["duration"], 2.0, 0.15)
+ self.assertEqual((m["video"]["width"], m["video"]["height"]), (500, 500))
+ self.assertClose(m["video"]["fps"], 24.0, 0.01)
+
+ def test_insert_refuses_zero_duration(self):
+ script("insert.py", self.logo, "--duration", "0", expect_fail=True)
+
# ---------------------------------------------------------------- caption
def test_caption_text_to_srt_and_burn(self):
srt = OUT / "cues.srt"
diff --git a/tests/test_contract.py b/tests/test_contract.py
index 2bbd05b..e857761 100644
--- a/tests/test_contract.py
+++ b/tests/test_contract.py
@@ -244,7 +244,7 @@ class ContractTests(unittest.TestCase):
self.assertEqual(self.tools["cut"]["verification"]["tools"], ["ffmpeg-skill/probe"])
def test_visual_verification_metadata(self):
- picture = {"fit", "caption", "overlay", "graphics", "color", "join", "multicam", "render"}
+ picture = {"fit", "crop", "insert", "caption", "overlay", "graphics", "color", "join", "multicam", "render"}
# join is the one picture tool that also accepts audio-only inputs (audio concat); look applies
# to its video output only, which SKILL.md states next to "Look: not needed"
both = {"join"}