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.

caption.py: add --mode mux for a soft, toggleable subtitle stream (#51) (#58)

Shogo Kajiyama510f40046881
diff --git a/CHANGELOG.md b/CHANGELOG.md
index f4dd5d5..7470356 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -4,6 +4,7 @@
## Unreleased
+- **`caption.py --mode mux`: soft subtitle stream instead of burn-in.** Every caption call previously re-encoded both streams to render pixels (`reencodes_video`/`reencodes_audio`: `"always"`) even when the caller only wanted a subtitle track added, not the picture changed. `--mode mux` (new; `--mode burn` stays the default) copies video and audio untouched (`-c:v copy -c:a copy`) and adds the SRT as a separate, player-toggleable subtitle stream — `reencodes_video`/`reencodes_audio` are now `"conditional"` with a note explaining the split. Only takes a plain SRT (`--srt`/`--text`/`--transcribe`), not `--ass`, `--animate` or `--karaoke`: styling and animation render pixels, so they have no soft-subtitle equivalent and are refused with a pointer to `--mode burn`. The subtitle codec is picked from the output container (`mov_text` for `.mp4`/`.m4v`/`.mov`, `srt` for `.mkv`, `webvtt` for `.webm`); an unrecognized container is refused rather than guessed at. `contract --json` gains three new optional capabilities (`encoder:mov_text`/`encoder:webvtt`/`encoder:srt`, each `"when"`-gated to the matching output container) so `doctor` can report them honestly; the existing required capabilities (`encoder:libx264`, `encoder:aac`, `filter:subtitles`) are unchanged, since `--mode burn` is still the default and doctor's usability model doesn't vary by flag. Closes [#51](https://github.com/kajisho5/ffmpeg-skill/issues/51) — timecode-aware cue timing and explicit multi-audio-track selection were split out to [#54](https://github.com/kajisho5/ffmpeg-skill/issues/54) and [#55](https://github.com/kajisho5/ffmpeg-skill/issues/55) to keep this change reviewable.
- **Test: the prose tool count in README/`docs/contract.md`/`package.json` is now checked against the real tool list.** 0.11.0 was cut to fix exactly this drift (README said 28 twice and 22 once; `package.json` said 21) by hand, with nothing to stop it recurring. `tests/test_contract.py`'s `test_docs_tool_count_matches_the_real_tool_list` scans all three for `"<N> tools"` wording and fails if any number doesn't match `scripts/`'s actual public-tool count, so the next tool added/removed without updating every mention fails CI instead of drifting silently. `contract_version`/`skill.version` were already split (0.9.0) and already documented as "additive keeps `contract_version`, breaking bumps it" — `docs/contract.md` now also repeats the tagged-version pin guidance next to that table, since `capability_map` makes this the most cross-repo-facing part of the contract. Closes [#50](https://github.com/kajisho5/ffmpeg-skill/issues/50).
- **Tests: `overlay.py --image` on an audio-less video is now covered.** Every existing overlay test used a
source with audio; investigating a downstream report of `overlay.py` "hanging" on audio-less input (the
diff --git a/SKILL.md b/SKILL.md
index 5d54031..8591544 100644
--- a/SKILL.md
+++ b/SKILL.md
@@ -106,6 +106,7 @@ If a request needs an FFmpeg feature none of the 28 scripts expose, say so and n
| "turn these numbered frames into a video" | `sequence.py --dir frames --pattern "frame_%04d.png" --fps 24` |
| "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` |
| "put our logo top-right", "add a watermark" | `overlay.py input.mp4 --image logo.png --position top-right --scale 200` |
| "add a title for the first 4 seconds" | `overlay.py input.mp4 --text "Title" --position top --start 0 --end 4 --fade 0.4` |
| "put this webcam clip in the corner", "picture-in-picture" | `overlay.py input.mp4 --video webcam.mp4 --position bottom-right --scale 480` |
diff --git a/docs/contract.md b/docs/contract.md
index 3aab1de..9459d26 100644
--- a/docs/contract.md
+++ b/docs/contract.md
@@ -71,7 +71,7 @@ One entry per tool under `tools`, sorted by id. Tool ids are stable:
| `produces_artifact` | writes a file (media, PNG, HTML, EDL) |
| `verification` | `{required, tools}`: which tools to run on the output afterwards |
| `requires_visual_verification` | the picture changed; run `ffmpeg-skill/look` and inspect the PNG |
-| `reencodes_video`, `reencodes_audio` | `"always"` / `"never"` / `"conditional"`, meaning *when that stream is present in the input* — not whether the tool touches the file at all. `"conditional"` tools (`cut`, `export`, `render`, `batch`, `verify`) carry a `reencode_note` explaining what it depends on. Several visual tools (`fit`, `caption`, `overlay`, `graphics`, `color`, `join`, `multicam`, `silence`) are `"always"` on audio too: this codebase never mixes `-c:v` re-encode with `-c:a copy` in one call, so a caller cannot assume the original audio codec survives just because only the picture changed |
+| `reencodes_video`, `reencodes_audio` | `"always"` / `"never"` / `"conditional"`, meaning *when that stream is present in the input* — not whether the tool touches the file at all. `"conditional"` tools (`cut`, `export`, `render`, `batch`, `verify`, `caption`) carry a `reencode_note` explaining what it depends on — for `caption`, `--mode burn` (default) always re-encodes both streams, `--mode mux` copies both untouched. Several visual tools (`fit`, `overlay`, `graphics`, `color`, `join`, `multicam`, `silence`) are `"always"` on audio too: this codebase never mixes `-c:v` re-encode with `-c:a copy` in one call, so a caller cannot assume the original audio codec survives just because only the picture changed |
| `audio_only` | accepts an audio-only input (WAV, MP3, M4A, FLAC, OGG, Opus) |
| `video_required` | refuses an input without a video stream ("input has no video stream") |
| | `join` has `audio_only: true` and `video_required: false` since 0.9.1: audio-only inputs are joined as audio (no `look` needed then); mixing audio and video inputs is refused |
diff --git a/references/scripts.md b/references/scripts.md
index 2a15c41..2397c92 100644
--- a/references/scripts.md
+++ b/references/scripts.md
@@ -283,6 +283,7 @@ frame like an editor would. Use `--compare` to show before/after to the user.
### caption.py — subtitles (static, animated, karaoke)
```
caption.py INPUT --srt FILE | --ass FILE | --text CUES.txt [--write-srt OUT.srt]
+ [--mode burn|mux]
[--font NAME] [--fonts-dir DIR] [--size N] [--color RRGGBB] [--outline N] [--outline-color RRGGBB]
[--bold] [--box] [--position bottom|top|center|top-left|...] [--margin N]
[--animate none|fade|pop|slide] [--karaoke [--highlight-color RRGGBB]] [--write-ass OUT.ass] [-o OUT]
@@ -295,6 +296,13 @@ SRT/text cues: `pop` is the short-form "bouncy" entrance, `--karaoke` fills each
word from `--color` to `--highlight-color` evenly across the cue (word timing
is distributed, not transcribed). The ASS is kept next to the output so the
user can hand-tune timings and re-run with `--ass`.
+`--mode burn` (default) renders subtitles into the picture and always
+re-encodes both streams. `--mode mux` copies video and audio untouched and
+adds the SRT as a separate, player-toggleable subtitle stream instead —
+takes only a plain SRT (`--srt`/`--text`/`--transcribe`, not `--ass`, since
+styling has no soft-subtitle equivalent) and no `--animate`/`--karaoke`. The
+subtitle codec follows the output container: `mov_text` for `.mp4`/`.m4v`/`.mov`,
+`srt` for `.mkv`, `webvtt` for `.webm`.
### overlay.py — logo, image, title, video picture-in-picture, chroma key
```
diff --git a/scripts/_contract.py b/scripts/_contract.py
index a70d807..962a895 100644
--- a/scripts/_contract.py
+++ b/scripts/_contract.py
@@ -94,8 +94,9 @@ TOOL_META: Dict[str, Dict[str, Any]] = {
"sequence": dict(role="execution", inputs=["a directory of numbered/globbed still images"], outputs=["video artifact built from the frame sequence"],
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"}],
+ "caption": dict(role="execution", inputs=["video asset", "SRT/ASS file or timed text (--text)"], outputs=["video artifact with burnt-in captions (--mode burn)", "video artifact with an added soft subtitle stream (--mode mux)", "generated .srt / .ass sidecar"],
+ required=FF + [X264, AAC, "filter:subtitles"], optional=[{"capability": "filter:ass", "when": "--animate / --karaoke"}, HDR_X265, {"capability": "external:whisper", "when": "--transcribe"},
+ {"capability": "encoder:mov_text", "when": "--mode mux with a .mp4/.m4v/.mov output"}, {"capability": "encoder:webvtt", "when": "--mode mux with a .webm output"}, {"capability": "encoder:srt", "when": "--mode mux with a .mkv output"}],
video_required=True, audio_only=False, visual=True, verify=["probe", "look"], produces_artifact=True, idempotency="content_equivalent", deterministic=True),
"overlay": dict(role="execution", inputs=["video asset", "image (--image / --logo), text (--text), or a second video (--video) to composite"], outputs=["video artifact with the overlay composited"],
required=FF + [X264, AAC], optional=[{"capability": "filter:drawtext", "when": "--text"}, {"capability": "filter:chromakey", "when": "--chromakey"}, HDR_X265],
@@ -192,7 +193,7 @@ REENCODE_META: Dict[str, Dict[str, str]] = {
"reverse": dict(video="always", audio="conditional", note="video always re-encodes (reverse buffers and re-emits every frame); audio re-encodes to AAC when present and not dropped by --no-audio"),
"stabilize": dict(video="always", audio="conditional", note="video always re-encodes (two-pass vidstab); audio is re-encoded to AAC when present, never touched by the stabilization filters themselves"),
"sequence": dict(video="always", audio="never", note="always encodes a fresh clip from the frame sequence; there is no audio stream"),
- "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"),
+ "caption": dict(video="conditional", audio="conditional", note="--mode burn (default) always re-encodes both streams to render pixels; --mode mux copies video and audio untouched and only adds a subtitle stream"),
"overlay": dict(video="always", audio="always"),
"graphics": dict(video="always", audio="always"),
"sync": dict(video="never", audio="conditional", note="video is never touched; audio is copied or re-encoded depending on --trim-second / --replace-audio / --fix-drift"),
diff --git a/scripts/caption.py b/scripts/caption.py
index 52cf689..3ff7756 100755
--- a/scripts/caption.py
+++ b/scripts/caption.py
@@ -1,14 +1,20 @@
#!/usr/bin/env python3
-"""Burn SRT/ASS subtitles into a video, or generate an SRT from plain text.
+"""Burn SRT/ASS subtitles into a video, or mux one in as a soft (toggleable)
+subtitle stream, or generate an SRT from plain text.
Styling (font, size, colour, outline, position) applies to SRT input via
libass force_style. ASS files carry their own styles and are rendered as-is.
-
-This only burns subtitles into the picture. There is no soft-subtitle (mux a
-subtitle stream, toggleable by the player) path -- every call re-encodes the
-whole video and its audio (see contract --json: reencodes_video/reencodes_audio
-are both "always" for this tool), even for a source that only needed the
-subtitle track added.
+Styling and animation only apply to --mode burn (the default): they render
+pixels, so they have no meaning for a soft subtitle stream.
+
+--mode mux copies the video and audio streams untouched (see contract --json:
+reencodes_video/reencodes_audio are "never" for this mode) and adds the SRT
+as a separate subtitle stream a player can toggle -- the source is never
+touched. It takes only a plain SRT (from --srt, --text or --transcribe), not
+--ass: ASS styling has no equivalent soft-subtitle representation across
+containers, so --mode mux --ass is refused with a pointer to --mode burn.
+The subtitle codec is picked from the output container: mov_text for
+.mp4/.m4v/.mov, srt for .mkv, webvtt for .webm.
Text-to-SRT input format (one cue per line, blank lines ignored):
0:00-0:03 Hello and welcome
@@ -272,6 +278,18 @@ def write_ass(cues: List[Tuple[float, float, str]], path: str, args, play_w: int
fh.write("\n".join(header + lines) + "\n")
+def mux_subtitle_codec(output: str) -> str:
+ ext = Path(output).suffix.lower()
+ if ext in (".mp4", ".m4v", ".mov"):
+ return "mov_text"
+ if ext == ".mkv":
+ return "srt"
+ if ext == ".webm":
+ return "webvtt"
+ die(f"--mode mux: don't know a soft-subtitle codec for '{ext}' output "
+ "(know .mp4/.m4v/.mov, .mkv, .webm) -- use --mode burn, or pick one of those containers with -o")
+
+
def ass_color(hex_rgb: str, alpha: int = 0) -> str:
h = hex_rgb.lstrip("#")
if len(h) != 6:
@@ -284,12 +302,15 @@ def main() -> int:
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("input", nargs="?", help="video to burn captions into (omit with --write-srt to only generate)")
ap.add_argument("-o", "--output", help="output video (default: <name>_captioned.<ext>)")
+ ap.add_argument("--mode", choices=["burn", "mux"], default="burn",
+ help="'burn' renders subtitles into the picture (default); "
+ "'mux' copies video/audio untouched and adds the SRT as a soft, toggleable subtitle stream")
src = ap.add_argument_group("subtitle source")
src.add_argument("--srt", help="SRT file to burn")
src.add_argument("--ass", help="ASS file to burn (styles inside the file are used)")
src.add_argument("--text", help="plain text cue file to convert into SRT (see format above)")
src.add_argument("--transcribe", action="store_true", help="generate the SRT from the audio with a local speech-to-text engine if one is installed (whisper-cli / whisper / faster-whisper); never required")
- src.add_argument("--language", help="language code for --transcribe (e.g. en, ja); default auto")
+ src.add_argument("--language", help="language code for --transcribe (e.g. en, ja; default auto), also tagged on the subtitle stream with --mode mux")
src.add_argument("--model", default="base", help="whisper model name/path for --transcribe (default base)")
src.add_argument("--write-srt", help="where to save the generated SRT (default: <text>.srt)")
src.add_argument("--auto-seconds", type=float, default=3.0, help="duration for cues without timing (default 3)")
@@ -339,6 +360,12 @@ def main() -> int:
args.fonts_dir = str(Path(brand["font_file"]).parent)
if not (args.srt or args.ass or args.text or args.transcribe):
die("give one of --srt, --ass, --text or --transcribe")
+ if args.mode == "mux":
+ if args.ass:
+ die("--mode mux takes --srt (or --text/--transcribe), not --ass -- "
+ "ASS carries burn-only styling with no soft-subtitle equivalent; use --mode burn for an ASS file")
+ if args.animate != "none" or args.karaoke:
+ die("--animate/--karaoke render pixels into the picture and require --mode burn")
srt_path = args.srt
if args.transcribe:
@@ -372,6 +399,26 @@ def main() -> int:
die("input has no video stream")
output = args.output or default_output(args.input, "captioned")
+
+ if args.mode == "mux":
+ if not srt_path or (not os.path.exists(srt_path) and not (STATE.dry_run and args.text)):
+ die(f"SRT file not found: {srt_path}")
+ codec = mux_subtitle_codec(output)
+ maps = ["-map", "0:v:0"]
+ cmd = ffmpeg_base() + ["-i", args.input, "-i", srt_path]
+ if meta.get("audio"):
+ maps += ["-map", "0:a:0"]
+ maps += ["-map", "1:0"]
+ cmd += maps + ["-c:v", "copy"] + (["-c:a", "copy"] if meta.get("audio") else []) + ["-c:s", codec]
+ if args.language:
+ cmd += ["-metadata:s:s:0", f"language={args.language}"]
+ cmd += [output]
+ run(cmd)
+ result = probe(output, role="output")
+ info(f"wrote {output} ({result.get('duration'):.3f}s, mux, subtitle codec {codec})")
+ emit(output)
+ return 0
+
if (args.animate != "none" or args.karaoke) and not args.ass:
cues_for_ass = cues if args.text else parse_srt(srt_path)
ass_path = args.write_ass or os.path.splitext(output)[0] + ".ass"
diff --git a/tests/test_all.py b/tests/test_all.py
index 85b2014..b066812 100644
--- a/tests/test_all.py
+++ b/tests/test_all.py
@@ -510,6 +510,37 @@ class FFmpegSkillTests(unittest.TestCase):
self.assertTrue((sub / "cap_side.srt").exists(), "SRT written beside the output")
self.assertFalse((OUT / "source.srt").exists(), "no SRT dropped next to the source")
+ def test_caption_mux_copies_streams_and_adds_a_subtitle_track(self):
+ srt = OUT / "mux_cues.srt"
+ out = OUT / "cap_mux.mp4"
+ script("caption.py", self.src, "--text", self.cues, "--write-srt", srt, "--mode", "mux", "-o", out)
+ m = probe(str(out))
+ self.assertEqual(m["subtitle_streams"], 1)
+ self.assertEqual(m["video"]["codec"], "h264", "video must be copied, not re-encoded to a different codec")
+ self.assertEqual(m["audio"]["codec"], "aac", "audio must be copied untouched")
+ self.assertClose(m["duration"], 12.0, 0.15)
+
+ def test_caption_mux_picks_the_subtitle_codec_from_the_container(self):
+ srt = OUT / "mux_container_cues.srt"
+ script("caption.py", "--text", self.cues, "--write-srt", srt)
+ for ext, expect_codec in ((".mp4", "mov_text"), (".mkv", "subrip")):
+ out = OUT / f"cap_mux{ext}"
+ script("caption.py", self.src, "--srt", srt, "--mode", "mux", "-o", out)
+ streams = sh("ffprobe", "-v", "error", "-select_streams", "s", "-show_entries", "stream=codec_name",
+ "-of", "csv=p=0", out).stdout.strip()
+ self.assertEqual(streams, expect_codec, f"{ext} output")
+
+ def test_caption_mux_refuses_ass_and_animation(self):
+ script("caption.py", self.src, "--ass", "/nonexistent.ass", "--mode", "mux", "-o", OUT / "x.mp4", expect_fail=True)
+ srt = OUT / "mux_refuse_cues.srt"
+ script("caption.py", "--text", self.cues, "--write-srt", srt)
+ script("caption.py", self.src, "--srt", srt, "--mode", "mux", "--karaoke", "-o", OUT / "x2.mp4", expect_fail=True)
+
+ def test_caption_mux_refuses_an_unrecognized_container(self):
+ srt = OUT / "mux_avi_cues.srt"
+ script("caption.py", "--text", self.cues, "--write-srt", srt)
+ script("caption.py", self.src, "--srt", srt, "--mode", "mux", "-o", OUT / "x.avi", expect_fail=True)
+
# ---------------------------------------------------------------- overlay
def test_overlay_image_and_text(self):
out1 = OUT / "ov_img.mp4"
diff --git a/tests/test_contract.py b/tests/test_contract.py
index 2252426..09578db 100644
--- a/tests/test_contract.py
+++ b/tests/test_contract.py
@@ -318,7 +318,7 @@ class ContractTests(unittest.TestCase):
# a handful of the least intuitive ones, checked against what the scripts actually do
self.assertEqual((self.tools["cut"]["reencodes_video"], self.tools["cut"]["reencodes_audio"]), ("conditional", "conditional"))
self.assertEqual((self.tools["export"]["reencodes_video"], self.tools["export"]["reencodes_audio"]), ("conditional", "conditional"))
- self.assertEqual((self.tools["caption"]["reencodes_video"], self.tools["caption"]["reencodes_audio"]), ("always", "always"))
+ self.assertEqual((self.tools["caption"]["reencodes_video"], self.tools["caption"]["reencodes_audio"]), ("conditional", "conditional"))
self.assertEqual((self.tools["loudness"]["reencodes_video"], self.tools["loudness"]["reencodes_audio"]), ("never", "always"))
self.assertEqual((self.tools["probe"]["reencodes_video"], self.tools["probe"]["reencodes_audio"]), ("never", "never"))