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.
Python agent-skillsai-agentsaudio-processingcaptionsclaude-codecodexcoding-agentcursorffmpegloudness-normalizationmcpmcp-servermodel-context-protocolpythonsubtitlestranscodingvideovideo-editingvideo-processingwhisper
overlay.py/graphics.py/color.py: --audio-stream for multi-track consistency; fit.py: explicit audio mapping (#72)
Shogo Kajiyama84236f53f1e4
diff --git a/scripts/color.py b/scripts/color.pyindex ba29e84..19c658e 100755--- a/scripts/color.py+++ b/scripts/color.py@@ -105,6 +105,12 @@ def main() -> int:ap.add_argument("--saturation", type=float, default=CORRECTION["saturation"][0], help="--correct: saturation, 0..2, 1=unchanged (default 1)")ap.add_argument("--temperature", type=float, default=CORRECTION["temperature"][0], help="--correct: white-balance temperature in Kelvin, 2000..12000, 6500=unchanged (default 6500)")ap.add_argument("--tint", type=float, default=CORRECTION["tint"][0], help="--correct: green(-1)/magenta(+1) tint, 0=unchanged (default 0)")+ ap.add_argument("--audio-stream", type=int, default=0,+ help="which audio stream of the input to keep, 0-based in file order (probe.py lists them under "+ "audio_streams) -- matters on a multi-track input (dubbed languages, M&E stems); default 0, "+ "the first track, same as leaving it unset always did. Only affects modes that re-encode "+ "audio (--to-sdr, --lut, --correct, and --retag's re-encode fallback) -- --strip-dovi and "+ "a successful --retag stream-copy all streams untouched, so the flag has nothing to select there.")ap.add_argument("--crf", type=int, default=18)ap.add_argument("--preset", default="medium")add_common(ap)@@ -116,6 +122,11 @@ def main() -> int:die("input has no video stream")v = meta["video"]has_audio = bool(meta.get("audio"))+ audio_streams = meta.get("audio_streams") or []+ if audio_streams and not (0 <= args.audio_stream < len(audio_streams)):+ die(f"--audio-stream {args.audio_stream}: input has {len(audio_streams)} audio stream(s), 0..{len(audio_streams) - 1}")+ if args.audio_stream and not audio_streams:+ die("--audio-stream needs an input with audio streams")if args.strip_dovi:output = args.output or default_output(args.input, "nodv")@@ -151,7 +162,7 @@ def main() -> int:if proc.returncode != 0:# some codecs cannot carry retagged colour info without a bitstream filter; fall back to re-encodeinfo("stream copy could not rewrite tags, re-encoding")- cmd = ffmpeg_base() + ["-i", args.input, "-map", "0:v:0", "-map", "0:a:0?"] + x264_args(args.crf, args.preset, keep_bt709=False)+ cmd = ffmpeg_base() + ["-i", args.input, "-map", "0:v:0", "-map", f"0:a:{args.audio_stream}?"] + x264_args(args.crf, args.preset, keep_bt709=False)cmd += ["-colorspace", tags[0], "-color_primaries", tags[1], "-color_trc", tags[2]] + (aac_args() if has_audio else []) + [output]run(cmd)info(f"wrote {output} (tags -> {args.retag})")@@ -184,7 +195,7 @@ def main() -> int:output = args.output or default_output(args.input, "lut")tag = "lut"- cmd = ffmpeg_base() + ["-i", args.input, "-vf", vf, "-map", "0:v:0", "-map", "0:a:0?"]+ cmd = ffmpeg_base() + ["-i", args.input, "-vf", vf, "-map", "0:v:0", "-map", f"0:a:{args.audio_stream}?"]cmd += x264_args(args.crf, args.preset) + cfr_args(meta) + (aac_args() if has_audio else []) + [output]run(cmd)r = probe(output, role="output")diff --git a/scripts/fit.py b/scripts/fit.pyindex 23aaa5e..b238f25 100755--- a/scripts/fit.py+++ b/scripts/fit.py@@ -76,6 +76,10 @@ 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>_fit.<ext>)")+ ap.add_argument("--audio-stream", type=int, default=0,+ help="which audio stream of the input to keep, 0-based in file order (probe.py lists them under "+ "audio_streams) -- matters on a multi-track input (dubbed languages, M&E stems); default 0, "+ "the first track, same as leaving it unset always did")d = ap.add_argument_group("duration")d.add_argument("--duration", help="target duration (seconds or mm:ss)")d.add_argument("--method", choices=["speed", "trim"], default="speed", help="how to reach the duration (default speed)")@@ -114,6 +118,11 @@ def main() -> int:meta = probe(args.input)if not meta.get("video"):die("input has no video stream")+ audio_streams = meta.get("audio_streams") or []+ if audio_streams and not (0 <= args.audio_stream < len(audio_streams)):+ die(f"--audio-stream {args.audio_stream}: input has {len(audio_streams)} audio stream(s), 0..{len(audio_streams) - 1}")+ if args.audio_stream and not audio_streams:+ die("--audio-stream needs an input with audio streams")src_dur = meta["duration"] or 0.0sw, sh = meta["video"]["width"], meta["video"]["height"]if meta["video"].get("rotation") in (90, -90, 270, -270):@@ -205,6 +214,9 @@ def main() -> int:cmd += ["-vf", ",".join(vf)]if af:cmd += ["-af", ",".join(af)]+ cmd += ["-map", "0:v:0"]+ if has_audio:+ cmd += ["-map", f"0:a:{args.audio_stream}"]cmd += video_args(meta, args.crf, args.preset)cmd += cfr_args(meta, args.fps) if not args.fps else []if has_audio:diff --git a/scripts/graphics.py b/scripts/graphics.pyindex 8eaa5c3..24eab9b 100755--- a/scripts/graphics.py+++ b/scripts/graphics.py@@ -40,6 +40,10 @@ 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>_gfx.<ext>)")+ ap.add_argument("--audio-stream", type=int, default=0,+ help="which audio stream of the input to keep, 0-based in file order (probe.py lists them under "+ "audio_streams) -- matters on a multi-track input (dubbed languages, M&E stems); default 0, "+ "the first track, same as leaving it unset always did")ap.add_argument("--template", choices=TEMPLATES, required=True)ap.add_argument("--brand", help="brand.json for colours, font, safe margin")ap.add_argument("--name", help="lower-third: name line")@@ -70,6 +74,11 @@ def main() -> int:meta = probe(args.input)if not meta.get("video"):die("input has no video stream")+ audio_streams = meta.get("audio_streams") or []+ if audio_streams and not (0 <= args.audio_stream < len(audio_streams)):+ die(f"--audio-stream {args.audio_stream}: input has {len(audio_streams)} audio stream(s), 0..{len(audio_streams) - 1}")+ if args.audio_stream and not audio_streams:+ die("--audio-stream needs an input with audio streams")W, H = meta["video"]["width"], meta["video"]["height"]if meta["video"].get("rotation") in (90, -90, 270, -270):W, H = H, W@@ -149,9 +158,9 @@ def main() -> int:output = args.output or default_output(args.input, "gfx")cmd = ffmpeg_base() + ["-i", args.input]if fc:- cmd += ["-filter_complex", ";".join(fc), "-map", "[vout]", "-map", "0:a:0?"]+ cmd += ["-filter_complex", ";".join(fc), "-map", "[vout]", "-map", f"0:a:{args.audio_stream}?"]else:- cmd += ["-vf", ",".join(filters), "-map", "0:v:0", "-map", "0:a:0?"]+ cmd += ["-vf", ",".join(filters), "-map", "0:v:0", "-map", f"0:a:{args.audio_stream}?"]cmd += video_args(meta, args.crf, args.preset) + cfr_args(meta)cmd += aac_args() if meta.get("audio") else ["-an"]cmd.append(output)diff --git a/scripts/overlay.py b/scripts/overlay.pyindex c69e532..a94e666 100755--- a/scripts/overlay.py+++ b/scripts/overlay.py@@ -85,6 +85,10 @@ 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>_overlay.<ext>)")+ ap.add_argument("--audio-stream", type=int, default=0,+ help="which audio stream of the input to keep, 0-based in file order (probe.py lists them under "+ "audio_streams) -- matters on a multi-track input (dubbed languages, M&E stems); default 0, "+ "the first track, same as leaving it unset always did")src = ap.add_mutually_exclusive_group()src.add_argument("--image", help="PNG/JPG (alpha respected) to composite")src.add_argument("--text", help="text to draw (drawtext)")@@ -143,6 +147,11 @@ def main() -> int:meta = probe(args.input)if not meta.get("video"):die("input has no video stream")+ audio_streams = meta.get("audio_streams") or []+ if audio_streams and not (0 <= args.audio_stream < len(audio_streams)):+ die(f"--audio-stream {args.audio_stream}: input has {len(audio_streams)} audio stream(s), 0..{len(audio_streams) - 1}")+ if args.audio_stream and not audio_streams:+ die("--audio-stream needs an input with audio streams")vw = meta["video"]["width"]start = parse_time(args.start) if args.start else Noneend = parse_time(args.end) if args.end else None@@ -184,7 +193,7 @@ def main() -> int:# -loop 1 turns the still into a timed stream so fade/enable expressions see real timestampscmd = ffmpeg_base() + ["-i", args.input, "-loop", "1", "-i", args.image]fc = f"[1:v]{','.join(chain)},setpts=PTS-STARTPTS[ov];[0:v][ov]{ov}[out]"- cmd += ["-filter_complex", fc, "-map", "[out]", "-map", "0:a:0?", "-shortest"]+ cmd += ["-filter_complex", fc, "-map", "[out]", "-map", f"0:a:{args.audio_stream}?", "-shortest"]# -shortest alone is not exact on FFmpeg 7+: the muxer keeps up to shortest_buf_duration (10 s)# of the looped still after the video ended, and the file came out 2 s long on 8.1 / 9.0.# The output must be as long as the main input, so say so explicitly.@@ -210,7 +219,7 @@ def main() -> int:ov += f":enable='{enable}'"cmd = ffmpeg_base() + ["-i", args.input, "-i", args.video]fc = f"[1:v]{','.join(chain)}[ov];[0:v][ov]{ov}[out]"- cmd += ["-filter_complex", fc, "-map", "[out]", "-map", "0:a:0?", "-shortest"]+ cmd += ["-filter_complex", fc, "-map", "[out]", "-map", f"0:a:{args.audio_stream}?", "-shortest"]if meta.get("duration"):cmd += ["-t", f"{meta['duration']:.3f}"]else:@@ -230,7 +239,9 @@ def main() -> int:opts += ["box=1", f"boxcolor={args.box_color}", "boxborderw=12"]if enable:opts.append(f"enable='{enable}'")- cmd += ["-vf", "drawtext=" + ":".join(opts)]+ cmd += ["-vf", "drawtext=" + ":".join(opts), "-map", "0:v:0"]+ if meta.get("audio"):+ cmd += ["-map", f"0:a:{args.audio_stream}"]cmd += video_args(meta, args.crf, args.preset) + cfr_args(meta)cmd += aac_args() if meta.get("audio") else ["-an"]diff --git a/tests/test_all.py b/tests/test_all.pyindex b7a1173..502e3bf 100644--- a/tests/test_all.py+++ b/tests/test_all.py@@ -271,6 +271,19 @@ class FFmpegSkillTests(unittest.TestCase):def test_fit_nothing_to_do_is_refused(self):script("fit.py", self.src, expect_fail=True)+ def test_fit_audio_stream_selects_the_requested_track_not_always_the_first(self):+ two = OUT / "fit_two_streams.mkv"+ sh("ffmpeg", "-y", "-hide_banner", "-loglevel", "error", "-f", "lavfi", "-i", "testsrc2=size=320x180:rate=30",+ "-f", "lavfi", "-i", "sine=frequency=440:sample_rate=48000", "-f", "lavfi", "-i", "sine=frequency=880:sample_rate=44100",+ "-t", "4", "-map", "0:v", "-map", "1:a", "-map", "2:a", "-c:v", "libx264", "-preset", "ultrafast", "-pix_fmt", "yuv420p", "-c:a", "aac", two)+ self.assertEqual(len(probe(str(two))["audio_streams"]), 2)+ out1 = OUT / "fit_two_s1.mp4"+ script("fit.py", two, "--audio-stream", "1", "--width", "160", "-o", out1, "--preset", "veryfast")+ self.assertIsNotNone(probe(str(out1))["audio"], "default fit.py now explicitly maps audio too, not just the automatic 'best stream' pick")+ proc = script("fit.py", two, "--audio-stream", "5", "--width", "160", "-o", OUT / "fit_nope.mp4", "--json", expect_fail=True)+ self.assertEqual(json.loads(proc.stdout)["error"]["kind"], "input")+ self.assertIn("audio-stream", proc.stderr)+# ---------------------------------------------------------------- cropdef test_crop_exact_rectangle(self):out = OUT / "crop1.mp4"@@ -793,6 +806,19 @@ class FFmpegSkillTests(unittest.TestCase):self.assertIn("-c copy", proc.stderr)self.assertEqual(probe(str(out))["video"]["color_transfer"], "smpte170m")+ def test_color_audio_stream_selects_the_requested_track_not_always_the_first(self):+ two = OUT / "color_two_streams.mkv"+ sh("ffmpeg", "-y", "-hide_banner", "-loglevel", "error", "-f", "lavfi", "-i", "testsrc2=size=320x180:rate=30",+ "-f", "lavfi", "-i", "sine=frequency=440:sample_rate=48000", "-f", "lavfi", "-i", "sine=frequency=880:sample_rate=44100",+ "-t", "4", "-map", "0:v", "-map", "1:a", "-map", "2:a", "-c:v", "libx264", "-preset", "ultrafast", "-pix_fmt", "yuv420p", "-c:a", "aac", two)+ self.assertEqual(len(probe(str(two))["audio_streams"]), 2)+ out1 = OUT / "color_two_correct1.mp4"+ script("color.py", two, "--correct", "--exposure", "0.2", "--audio-stream", "1", "-o", out1, "--preset", "veryfast")+ self.assertIsNotNone(probe(str(out1))["audio"])+ proc = script("color.py", two, "--correct", "--audio-stream", "5", "-o", OUT / "color_nope.mp4", "--json", expect_fail=True)+ self.assertEqual(json.loads(proc.stdout)["error"]["kind"], "input")+ self.assertIn("audio-stream", proc.stderr)+def test_color_lut(self):lut = OUT / "invert.cube"lines = ["LUT_3D_SIZE 2"]@@ -1297,6 +1323,22 @@ class FFmpegSkillTests(unittest.TestCase):self.assertNotEqual(a[200:4000], b[200:4000])script("graphics.py", self.src, "--template", "lower-third", expect_fail=True)+ def test_graphics_audio_stream_selects_the_requested_track_not_always_the_first(self):+ two = OUT / "gfx_two_streams.mkv"+ sh("ffmpeg", "-y", "-hide_banner", "-loglevel", "error", "-f", "lavfi", "-i", "testsrc2=size=320x180:rate=30",+ "-f", "lavfi", "-i", "sine=frequency=440:sample_rate=48000", "-f", "lavfi", "-i", "sine=frequency=880:sample_rate=44100",+ "-t", "4", "-map", "0:v", "-map", "1:a", "-map", "2:a", "-c:v", "libx264", "-preset", "ultrafast", "-pix_fmt", "yuv420p", "-c:a", "aac", two)+ self.assertEqual(len(probe(str(two))["audio_streams"]), 2)+ out1 = OUT / "gfx_two_s1.mp4"+ script("graphics.py", two, "--template", "bug", "--title", "@handle", "--audio-stream", "1", "-o", out1, "--fast")+ self.assertIsNotNone(probe(str(out1))["audio"])+ out_prog = OUT / "gfx_two_progress.mp4"+ script("graphics.py", two, "--template", "progress", "--audio-stream", "1", "-o", out_prog, "--fast")+ self.assertIsNotNone(probe(str(out_prog))["audio"])+ proc = script("graphics.py", two, "--template", "bug", "--title", "x", "--audio-stream", "5", "-o", OUT / "gfx_nope.mp4", "--json", expect_fail=True)+ self.assertEqual(json.loads(proc.stdout)["error"]["kind"], "input")+ self.assertIn("audio-stream", proc.stderr)+def test_brand_defaults_apply_to_caption_and_logo(self):brand = OUT / "brand.json"if not brand.exists():@@ -1737,6 +1779,23 @@ class FFmpegSkillTests(unittest.TestCase):stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, encoding="utf-8", errors="replace", timeout=60)self.assertEqual(proc.returncode, 0, f"STDOUT:\n{proc.stdout}\nSTDERR:\n{proc.stderr}")self.assertClose(probe(str(out))["duration"], probe(str(noaudio))["duration"], 0.15)++ def test_overlay_audio_stream_selects_the_requested_track_not_always_the_first(self):+ two = OUT / "ov_two_streams.mkv"+ sh("ffmpeg", "-y", "-hide_banner", "-loglevel", "error", "-f", "lavfi", "-i", "testsrc2=size=320x180:rate=30",+ "-f", "lavfi", "-i", "sine=frequency=440:sample_rate=48000", "-f", "lavfi", "-i", "sine=frequency=880:sample_rate=44100",+ "-t", "4", "-map", "0:v", "-map", "1:a", "-map", "2:a", "-c:v", "libx264", "-preset", "ultrafast", "-pix_fmt", "yuv420p", "-c:a", "aac", two)+ self.assertEqual(len(probe(str(two))["audio_streams"]), 2)+ out_text = OUT / "ov_two_text.mp4"+ script("overlay.py", two, "--text", "hi", "--audio-stream", "1", "-o", out_text, "--preset", "veryfast")+ self.assertIsNotNone(probe(str(out_text))["audio"])+ out_img = OUT / "ov_two_img.mp4"+ script("overlay.py", two, "--image", self.logo, "--audio-stream", "1", "-o", out_img, "--preset", "veryfast")+ self.assertIsNotNone(probe(str(out_img))["audio"])+ proc = script("overlay.py", two, "--text", "hi", "--audio-stream", "5", "-o", OUT / "ov_nope.mp4", "--json", expect_fail=True)+ self.assertEqual(json.loads(proc.stdout)["error"]["kind"], "input")+ self.assertIn("audio-stream", proc.stderr)+def test_overlay_video_pip_composites_at_the_right_position(self):red_bg = OUT / "red_bg.mp4"blue_quad = OUT / "blue_quad.mp4"