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
Fix a contract/reality mismatch on AAC, three batch.py/render.py reliability bugs, and a non-atomic installer (#125)
Shogo Kajiyama25e4171ef855
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex c97b35e..9f4e600 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -6,6 +6,48 @@(nothing yet)+## 0.16.11 — fix a contract/reality mismatch on AAC, three batch.py/render.py reliability bugs, and a non-atomic installer++Continuing the same external audit report's architecture/data-integrity/reliability findings:++- `_contract.py` declared `encoder:aac` unconditionally `required` for `audio.py`,+ `loudness.py` and `join.py`, but all three pick their audio codec from the output+ extension via `audio_codec_for()` (falling back to AAC only when the extension+ isn't otherwise covered) -- so `doctor` reported these tools entirely unusable+ on an ffmpeg build without an AAC encoder, even though they can still produce+ e.g. a `.flac` output with no AAC involved at all. Moved to `optional` with a+ `when`, matching the pattern `cut.py`/`silence.py` already used; `join.py`'s+ `libx264` requirement was similarly conditioned on joining video inputs.+ `export.py`'s AAC `when` also named "any preset except gif", though `prores`+ (`pcm_s16le`) and `copy` (stream copy) don't use AAC either -- corrected.+- `batch.py`'s `--recipe` project mode (`{"project": "p.json", "clip_key": N}`)+ computed its cache key by hashing only that small outer dict, never the+ referenced project file's own content -- so editing `p.json` (an export preset+ swapped from `copy` to a real re-encode, captions text, anything) without+ touching the recipe file itself left the cache key unchanged, and the stale+ cached output was silently served for the new settings. Fixed by folding the+ referenced file's content into the key.+- `batch.py`'s cache file was written with a plain `write_text()`, not atomic --+ a process killed mid-write left a truncated file that the next run's+ `json.loads()` treats as corrupt and silently discards, losing every prior+ cache entry, not just the interrupted one. Fixed via a sibling temp file ++ `os.replace()`.+- `render.py`'s default work directory name came only from the output path (e.g.+ `final_work`), with no PID or timestamp -- two concurrent `render.py` runs+ targeting the same output (a `batch.py` "project" recipe processing several+ files in parallel, or simply two runs by mistake) shared the same work+ directory and clobbered each other's same-named intermediates mid-run. Fixed+ by suffixing the auto-derived default with this process's PID (an explicit+ `--work` is left as given, since the caller asked for that exact path).+- `bin/install.js` deleted an existing install (`rmSync`) before copying the new+ one in -- normal install, not just `--uninstall`. A process killed partway+ through the copy (Ctrl-C, disk full, a permission error) left the target+ either empty or half-populated, destroying a working previous install for+ nothing worse than an interrupted upgrade. Confirmed live: a simulated crash+ mid-copy left the target directory completely empty, an existing marker file+ gone. Fixed by copying into a scratch directory next to the real target first,+ then swapping it into place with a single rename.+## 0.16.10 — fix batch.py arbitrary script execution, and four fit/background/caption/freeze correctness bugs- **Security:** `batch.py`'s recipe `steps` named the script to run for eachdiff --git a/bin/install.js b/bin/install.jsindex 7e72de4..7944afb 100755--- a/bin/install.js+++ b/bin/install.js@@ -108,13 +108,22 @@ for (const t of targets) {console.log(`removed ${t.label}: ${t.dir}`);continue;}- fs.rmSync(t.dir, { recursive: true, force: true });- fs.mkdirSync(t.dir, { recursive: true });+ // Copy into a scratch directory next to the real target first, then swap it into place+ // with a single rename -- not delete-then-copy-into-the-gap. A process killed mid-copy+ // (Ctrl-C, disk full, a permission error partway through) used to leave the target either+ // empty or half-populated; now it leaves the previous install untouched (first run: no+ // previous install to preserve, so an interruption here still leaves nothing, same as+ // before -- the guarantee is specifically for an upgrade of an existing install).+ const tmpDir = `${t.dir}.tmp-${process.pid}`;+ fs.rmSync(tmpDir, { recursive: true, force: true });+ fs.mkdirSync(tmpDir, { recursive: true });for (const item of PAYLOAD) {const src = path.join(ROOT, item);if (!fs.existsSync(src)) { if (item !== 'SKILL.md' && item !== 'scripts') continue; throw new Error(`missing ${item} in package`); }- copyRecursive(src, path.join(t.dir, item));+ copyRecursive(src, path.join(tmpDir, item));}+ fs.rmSync(t.dir, { recursive: true, force: true });+ fs.renameSync(tmpDir, t.dir);console.log(`installed ${t.label}: ${t.dir}`);} catch (err) {failed = true;diff --git a/docs/contract.md b/docs/contract.mdindex 3084b1f..fc99b35 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.16.10`) | any release |+| `skill.version` | the npm / package.json version (`0.16.11`) | any release |A release that adds a tool or a flag keeps `contract_version`; a breaking change to theToolSpec 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.16.10", "execution_mode": "local", "kind": "execution",+ "skill": {"id": "ffmpeg-skill", "version": "0.16.11", "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"},diff --git a/package.json b/package.jsonindex 91aeb00..5128c55 100644--- a/package.json+++ b/package.json@@ -1,6 +1,6 @@{"name": "ffmpeg-skill",- "version": "0.16.10",+ "version": "0.16.11","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",diff --git a/scripts/_contract.py b/scripts/_contract.pyindex c749092..27ad716 100644--- a/scripts/_contract.py+++ b/scripts/_contract.py@@ -147,17 +147,19 @@ TOOL_META: Dict[str, Dict[str, Any]] = {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),"audio": dict(role="execution", inputs=["video or audio asset", "music bed (--music) or replacement track (--replace)"], outputs=["artifact with the processed audio (video stream-copied, or dropped when -o has an audio extension)"],- required=FF + [AAC], optional=[{"capability": "filter:afftdn", "when": "--denoise / --voice"}, {"capability": "filter:sidechaincompress", "when": "--duck"},- {"capability": "filter:acompressor", "when": "--compress / --voice"}, {"capability": "filter:alimiter", "when": "--limit"}, {"capability": "filter:agate", "when": "--gate"}] + AUDIO_OUT,+ required=FF, optional=[{"capability": "filter:afftdn", "when": "--denoise / --voice"}, {"capability": "filter:sidechaincompress", "when": "--duck"},+ {"capability": "filter:acompressor", "when": "--compress / --voice"}, {"capability": "filter:alimiter", "when": "--limit"}, {"capability": "filter:agate", "when": "--gate"},+ {"capability": AAC, "when": "output extension isn't .mp3/.opus/.ogg/.flac (audio_codec_for()'s default)"}] + AUDIO_OUT,video_required=False, audio_only=True, visual=False, verify=["probe"], produces_artifact=True, idempotency="content_equivalent", deterministic=True),"loudness": dict(role="analysis_and_execution", inputs=["video or audio asset"], outputs=["loudness measurement JSON (--measure-only)", "normalised artifact (video stream-copied)"],- required=FF + ["filter:loudnorm", AAC], optional=AUDIO_OUT,+ required=FF + ["filter:loudnorm"], optional=[{"capability": AAC, "when": "output extension isn't .mp3/.opus/.ogg/.flac (audio_codec_for()'s default)"}] + AUDIO_OUT,video_required=False, audio_only=True, visual=False, verify=["probe", "check"], produces_artifact=True, idempotency="content_equivalent", deterministic=True),"silence": dict(role="analysis_and_execution", inputs=["video or audio asset"], outputs=["silence list JSON (--list)", "artifact with silences removed", "EDL text (--edl)"],required=FF + ["filter:silencedetect"], optional=[{"capability": X264, "when": "removing silences from a video"}, HDR_X265, {"capability": AAC, "when": "removing silences from a video"}] + AUDIO_OUT,video_required=False, audio_only=True, visual=False, verify=["probe"], produces_artifact=True, idempotency="content_equivalent", deterministic=True),"join": dict(role="execution", inputs=["two or more video assets, or two or more audio-only assets"], outputs=["concatenated video artifact", "concatenated audio artifact (audio-only inputs, audio output extension)"],- required=FF + [X264, AAC, "filter:xfade", "filter:acrossfade"], optional=[HDR_X265] + AUDIO_OUT,+ required=FF + ["filter:xfade", "filter:acrossfade"],+ optional=[{"capability": X264, "when": "joining video inputs"}, {"capability": AAC, "when": "joining video inputs, or an audio-only join whose output extension isn't .mp3/.opus/.ogg/.flac"}, HDR_X265] + AUDIO_OUT,video_required=False, audio_only=True, visual=True, verify=["probe", "look"], produces_artifact=True, idempotency="content_equivalent", deterministic=True),"color": dict(role="execution", inputs=["video asset", ".cube LUT (--lut)"], outputs=["video artifact with converted colour"],required=FF, optional=[{"capability": X264, "when": "--to-sdr / --lut / --correct"}, {"capability": "filter:zscale", "when": "--to-sdr"}, {"capability": "filter:tonemap", "when": "--to-sdr"},@@ -170,7 +172,7 @@ TOOL_META: Dict[str, Dict[str, Any]] = {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),"export": dict(role="execution", inputs=["video asset"], outputs=["delivery artifact in the preset's format"],- required=FF, optional=[{"capability": X264, "when": "preset youtube / youtube4k / reels / x"}, {"capability": AAC, "when": "any preset except gif"},+ required=FF, optional=[{"capability": X264, "when": "preset youtube / youtube4k / reels / x"}, {"capability": AAC, "when": "preset youtube / youtube4k / reels / x / h265 (prores uses pcm_s16le, copy stream-copies, gif has no audio)"},{"capability": X265, "when": "preset h265"}, {"capability": "encoder:prores_ks", "when": "preset prores"},{"capability": "filter:palettegen", "when": "preset gif"}, {"capability": "encoder:gif", "when": "preset gif"}],video_required=True, audio_only=False, visual=False, verify=["probe", "check"], produces_artifact=True, idempotency="content_equivalent", deterministic=True),diff --git a/scripts/batch.py b/scripts/batch.pyindex 5c0b294..23f0e56 100755--- a/scripts/batch.py+++ b/scripts/batch.py@@ -58,7 +58,19 @@ def file_key(path: Path) -> str:def recipe_key(recipe: Dict[str, Any]) -> str:- return hashlib.sha1(json.dumps(recipe, sort_keys=True).encode()).hexdigest()[:12]+ # A "project" recipe is just {"project": "<path>", "clip_key": N} -- the actual settings+ # (export preset, captions, everything) live in the file at that path, not in this dict.+ # Hashing only `recipe` meant editing project.json's content (without touching batch.json+ # itself) left the key, and so every cache hit, unchanged: a preset swapped from "copy" to+ # "x" (a real re-encode) still served the old cached output. Fold the referenced file's own+ # content into the key so a content change invalidates the cache like any other edit would.+ project_content = ""+ if recipe.get("project"):+ try:+ project_content = Path(recipe["project"]).read_text(encoding="utf-8")+ except OSError:+ pass+ return hashlib.sha1((json.dumps(recipe, sort_keys=True) + "\0" + project_content).encode()).hexdigest()[:12]def run_step(argv: List[str]) -> bool:@@ -185,7 +197,15 @@ def main() -> int:results.append(r)if r["ok"] and not STATE["dry_run"]:cache[key] = r- cache_path.write_text(json.dumps(cache, indent=2), encoding="utf-8")+ # write_text isn't atomic -- a process killed mid-write (or a --watch loop racing+ # a concurrent manual run) could leave a truncated file that json.loads() above+ # then silently treats as "no cache" (a ValueError -> {}), discarding every prior+ # entry. Write to a sibling temp file and rename into place: same-directory+ # renames are atomic on POSIX and os.replace() is atomic on Windows too, so a+ # reader only ever sees the old complete file or the new complete file.+ tmp = cache_path.parent / f"{cache_path.name}.tmp{os.getpid()}"+ tmp.write_text(json.dumps(cache, indent=2), encoding="utf-8")+ os.replace(tmp, cache_path)return resultsresults = one_pass()diff --git a/scripts/render.py b/scripts/render.pyindex ceacbf7..7202ebe 100755--- a/scripts/render.py+++ b/scripts/render.py@@ -130,7 +130,14 @@ def main() -> int:if not clips:die("project.clips is empty")output = rel(proj.get("output") or "final.mp4")- work = Path(args.work) if args.work else Path(str(Path(output).with_suffix("")) + "_work")+ # The default work dir name comes only from the output path, with no PID or timestamp --+ # two concurrent render.py runs targeting the same output (a batch.py "project" recipe+ # processing several files in parallel, or simply running render.py twice by mistake) shared+ # the same work directory and clobbered each other's same-named intermediates (clip00.mp4,+ # fit.mp4, ...) mid-run. An explicit --work is left as given (the caller asked for that exact,+ # shared path, e.g. to inspect intermediates across runs); only the auto-derived default is+ # made unique per process, since it's the one that's also auto-deleted at the end.+ work = Path(args.work) if args.work else Path(f"{Path(output).with_suffix('')}_work_{os.getpid()}")work.mkdir(parents=True, exist_ok=True)frame = proj.get("frame") or {}trans = proj.get("transition") or {}@@ -363,7 +370,12 @@ def main() -> int:info(f"check: OK for {ck['platform']}")stages_done.append("check")- if not args.keep and not args.work and not STATE["dry_run"]:+ if not args.keep and not args.work:+ # Also clean up on --dry-run: a dry run still creates this directory (and some steps,+ # e.g. caption.py's .ass sidecar, write into it even under --dry-run), and now that the+ # default name carries this process's PID, nothing else will ever reuse -- and so+ # implicitly clean up -- a leftover dry-run directory the way a same-named real run used+ # to before the PID suffix was added.import shutilshutil.rmtree(work, ignore_errors=True)info(f"rendered {output} via {' → '.join(stages_done)}")diff --git a/tests/fixtures/ffmpeg_encoders_6.1_no_aac.txt b/tests/fixtures/ffmpeg_encoders_6.1_no_aac.txtnew file mode 100644index 0000000..2310e30--- /dev/null+++ b/tests/fixtures/ffmpeg_encoders_6.1_no_aac.txt@@ -0,0 +1,232 @@+Encoders:+ V..... = Video+ A..... = Audio+ S..... = Subtitle+ .F.... = Frame-level multithreading+ ..S... = Slice-level multithreading+ ...X.. = Codec is experimental+ ....B. = Supports draw_horiz_band+ .....D = Supports direct rendering method 1+ ------+ V....D a64multi Multicolor charset for Commodore 64 (codec a64_multi)+ V....D a64multi5 Multicolor charset for Commodore 64, extended with 5th color (colram) (codec a64_multi5)+ V....D alias_pix Alias/Wavefront PIX image+ V..... amv AMV Video+ V....D apng APNG (Animated Portable Network Graphics) image+ V....D asv1 ASUS V1+ V....D asv2 ASUS V2+ V....D libaom-av1 libaom AV1 (codec av1)+ V....D librav1e librav1e AV1 (codec av1)+ V..... libsvtav1 SVT-AV1(Scalable Video Technology for AV1) encoder (codec av1)+ V....D av1_nvenc NVIDIA NVENC av1 encoder (codec av1)+ V..... av1_qsv AV1 (Intel Quick Sync Video acceleration) (codec av1)+ V....D av1_vaapi AV1 (VAAPI) (codec av1)+ V....D avrp Avid 1:1 10-bit RGB Packer+ V..X.D avui Avid Meridien Uncompressed+ V....D ayuv Uncompressed packed MS 4:4:4:4+ VF...D bitpacked Bitpacked+ V....D bmp BMP (Windows and OS/2 bitmap)+ VF...D cfhd GoPro CineForm HD+ V....D cinepak Cinepak+ V....D cljr Cirrus Logic AccuPak+ V.S..D vc2 SMPTE VC-2 (codec dirac)+ VFS..D dnxhd VC3/DNxHD+ V....D dpx DPX (Digital Picture Exchange) image+ VFS..D dvvideo DV (Digital Video)+ VF...D exr OpenEXR image+ V.S..D ffv1 FFmpeg video codec #1+ VF...D ffvhuff Huffyuv FFmpeg variant+ V....D fits Flexible Image Transport System+ V....D flashsv Flash Screen Video+ V....D flashsv2 Flash Screen Video Version 2+ V..... flv FLV / Sorenson Spark / Sorenson H.263 (Flash Video) (codec flv1)+ V....D gif GIF (Graphics Interchange Format)+ V..... h261 H.261+ V..... h263 H.263 / H.263-1996+ V..... h263_v4l2m2m V4L2 mem2mem H.263 encoder wrapper (codec h263)+ V.S... h263p H.263+ / H.263-1998 / H.263 version 2+ V....D libx264 libx264 H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10 (codec h264)+ V....D libx264rgb libx264 H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10 RGB (codec h264)+ V....D h264_nvenc NVIDIA NVENC H.264 encoder (codec h264)+ V..... h264_qsv H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10 (Intel Quick Sync Video acceleration) (codec h264)+ V..... h264_v4l2m2m V4L2 mem2mem H.264 encoder wrapper (codec h264)+ V....D h264_vaapi H.264/AVC (VAAPI) (codec h264)+ V.S..D hap Vidvox Hap+ VF...D hdr HDR (Radiance RGBE format) image+ V....D libx265 libx265 H.265 / HEVC (codec hevc)+ V....D hevc_nvenc NVIDIA NVENC hevc encoder (codec hevc)+ V..... hevc_qsv HEVC (Intel Quick Sync Video acceleration) (codec hevc)+ V..... hevc_v4l2m2m V4L2 mem2mem HEVC encoder wrapper (codec hevc)+ V....D hevc_vaapi H.265/HEVC (VAAPI) (codec hevc)+ VF...D huffyuv Huffyuv / HuffYUV+ VF...D jpeg2000 JPEG 2000+ VF.... libopenjpeg OpenJPEG JPEG 2000 (codec jpeg2000)+ VF...D jpegls JPEG-LS+ V..... libjxl libjxl JPEG XL (codec jpegxl)+ VF...D ljpeg Lossless JPEG+ VFS..D magicyuv MagicYUV video+ VFS... mjpeg MJPEG (Motion JPEG)+ V..... mjpeg_qsv MJPEG (Intel Quick Sync Video acceleration) (codec mjpeg)+ V....D mjpeg_vaapi MJPEG (VAAPI) (codec mjpeg)+ V.S... mpeg1video MPEG-1 video+ V.S... mpeg2video MPEG-2 video+ V..... mpeg2_qsv MPEG-2 video (Intel Quick Sync Video acceleration) (codec mpeg2video)+ V....D mpeg2_vaapi MPEG-2 (VAAPI) (codec mpeg2video)+ V.S... mpeg4 MPEG-4 part 2+ V....D libxvid libxvidcore MPEG-4 part 2 (codec mpeg4)+ V..... mpeg4_v4l2m2m V4L2 mem2mem MPEG4 encoder wrapper (codec mpeg4)+ V..... msmpeg4v2 MPEG-4 part 2 Microsoft variant version 2+ V..... msmpeg4 MPEG-4 part 2 Microsoft variant version 3 (codec msmpeg4v3)+ V....D msrle Microsoft RLE+ V..... msvideo1 Microsoft Video-1+ V....D pam PAM (Portable AnyMap) image+ V....D pbm PBM (Portable BitMap) image+ V....D pcx PC Paintbrush PCX image+ V....D pfm PFM (Portable FloatMap) image+ V....D pgm PGM (Portable GrayMap) image+ V....D pgmyuv PGMYUV (Portable GrayMap YUV) image+ V....D phm PHM (Portable HalfFloatMap) image+ VF...D png PNG (Portable Network Graphics) image+ V....D ppm PPM (Portable PixelMap) image+ VF...D prores Apple ProRes+ VF...D prores_aw Apple ProRes (codec prores)+ VFS... prores_ks Apple ProRes (iCodec Pro) (codec prores)+ VF...D qoi QOI (Quite OK Image format) image+ V....D qtrle QuickTime Animation (RLE) video+ V....D r10k AJA Kona 10-bit RGB Codec+ V....D r210 Uncompressed RGB 10-bit+ VF...D rawvideo raw video+ V....D roqvideo id RoQ video (codec roq)+ V....D rpza QuickTime video (RPZA)+ V..... rv10 RealVideo 1.0+ V..... rv20 RealVideo 2.0+ V....D sgi SGI image+ V....D smc QuickTime Graphics (SMC)+ V....D snow Snow+ V..... speedhq NewTek SpeedHQ+ V....D sunrast Sun Rasterfile image+ V....D svq1 Sorenson Vector Quantizer 1 / Sorenson Video 1 / SVQ1+ V....D targa Truevision Targa image+ V....D libtheora libtheora Theora (codec theora)+ VF...D tiff TIFF image+ VF...D utvideo Ut Video+ VF...D v210 Uncompressed 4:2:2 10-bit+ V....D v308 Uncompressed packed 4:4:4+ V....D v408 Uncompressed packed QT 4:4:4:4+ V....D v410 Uncompressed 4:4:4 10-bit+ V.S..D vbn Vizrt Binary Image+ V..... vnull null video+ V....D libvpx libvpx VP8 (codec vp8)+ V..... vp8_v4l2m2m V4L2 mem2mem VP8 encoder wrapper (codec vp8)+ V....D vp8_vaapi VP8 (VAAPI) (codec vp8)+ V....D libvpx-vp9 libvpx VP9 (codec vp9)+ V....D vp9_vaapi VP9 (VAAPI) (codec vp9)+ V..... vp9_qsv VP9 video (Intel Quick Sync Video acceleration) (codec vp9)+ VF...D wbmp WBMP (Wireless Application Protocol Bitmap) image+ V....D libwebp_anim libwebp WebP image (codec webp)+ V....D libwebp libwebp WebP image (codec webp)+ V..... wmv1 Windows Media Video 7+ V..... wmv2 Windows Media Video 8+ V..... wrapped_avframe AVFrame to AVPacket passthrough+ V....D xbm XBM (X BitMap) image+ V....D xface X-face image+ V....D xwd XWD (X Window Dump) image+ V....D y41p Uncompressed YUV 4:1:1 12-bit+ V....D yuv4 Uncompressed packed 4:2:0+ VF...D zlib LCL (LossLess Codec Library) ZLIB+ V....D zmbv Zip Motion Blocks Video+ A....D ac3 ATSC A/52A (AC-3)+ A....D ac3_fixed ATSC A/52A (AC-3) (codec ac3)+ A....D adpcm_adx SEGA CRI ADX ADPCM+ A....D adpcm_argo ADPCM Argonaut Games+ A....D g722 G.722 ADPCM (codec adpcm_g722)+ A....D g726 G.726 ADPCM (codec adpcm_g726)+ A....D g726le G.726 little endian ADPCM ("right-justified") (codec adpcm_g726le)+ A....D adpcm_ima_alp ADPCM IMA High Voltage Software ALP+ A....D adpcm_ima_amv ADPCM IMA AMV+ A....D adpcm_ima_apm ADPCM IMA Ubisoft APM+ A....D adpcm_ima_qt ADPCM IMA QuickTime+ A....D adpcm_ima_ssi ADPCM IMA Simon & Schuster Interactive+ A....D adpcm_ima_wav ADPCM IMA WAV+ A....D adpcm_ima_ws ADPCM IMA Westwood+ A....D adpcm_ms ADPCM Microsoft+ A....D adpcm_swf ADPCM Shockwave Flash+ A....D adpcm_yamaha ADPCM Yamaha+ A....D alac ALAC (Apple Lossless Audio Codec)+ A..... anull null audio+ A....D aptx aptX (Audio Processing Technology for Bluetooth)+ A....D aptx_hd aptX HD (Audio Processing Technology for Bluetooth)+ A....D libcodec2 codec2 encoder using libcodec2 (codec codec2)+ A....D comfortnoise RFC 3389 comfort noise generator+ A....D dfpwm DFPWM1a audio+ A..X.D dca DCA (DTS Coherent Acoustics) (codec dts)+ A....D eac3 ATSC A/52 E-AC-3+ A....D flac FLAC (Free Lossless Audio Codec)+ A....D g723_1 G.723.1+ A....D libgsm libgsm GSM (codec gsm)+ A....D libgsm_ms libgsm GSM Microsoft variant (codec gsm_ms)+ A..X.D mlp MLP (Meridian Lossless Packing)+ A....D mp2 MP2 (MPEG audio layer 2)+ A....D mp2fixed MP2 fixed point (MPEG audio layer 2) (codec mp2)+ A....D libtwolame libtwolame MP2 (MPEG audio layer 2) (codec mp2)+ A....D libmp3lame libmp3lame MP3 (MPEG audio layer 3) (codec mp3)+ A....D libshine libshine MP3 (MPEG audio layer 3) (codec mp3)+ A....D nellymoser Nellymoser Asao+ A..X.D opus Opus+ A....D libopus libopus Opus (codec opus)+ A....D pcm_alaw PCM A-law / G.711 A-law+ A....D pcm_bluray PCM signed 16|20|24-bit big-endian for Blu-ray media+ A....D pcm_dvd PCM signed 16|20|24-bit big-endian for DVD media+ A....D pcm_f32be PCM 32-bit floating point big-endian+ A....D pcm_f32le PCM 32-bit floating point little-endian+ A....D pcm_f64be PCM 64-bit floating point big-endian+ A....D pcm_f64le PCM 64-bit floating point little-endian+ A....D pcm_mulaw PCM mu-law / G.711 mu-law+ A....D pcm_s16be PCM signed 16-bit big-endian+ A....D pcm_s16be_planar PCM signed 16-bit big-endian planar+ A....D pcm_s16le PCM signed 16-bit little-endian+ A....D pcm_s16le_planar PCM signed 16-bit little-endian planar+ A....D pcm_s24be PCM signed 24-bit big-endian+ A....D pcm_s24daud PCM D-Cinema audio signed 24-bit+ A....D pcm_s24le PCM signed 24-bit little-endian+ A....D pcm_s24le_planar PCM signed 24-bit little-endian planar+ A....D pcm_s32be PCM signed 32-bit big-endian+ A....D pcm_s32le PCM signed 32-bit little-endian+ A....D pcm_s32le_planar PCM signed 32-bit little-endian planar+ A....D pcm_s64be PCM signed 64-bit big-endian+ A....D pcm_s64le PCM signed 64-bit little-endian+ A....D pcm_s8 PCM signed 8-bit+ A....D pcm_s8_planar PCM signed 8-bit planar+ A....D pcm_u16be PCM unsigned 16-bit big-endian+ A....D pcm_u16le PCM unsigned 16-bit little-endian+ A....D pcm_u24be PCM unsigned 24-bit big-endian+ A....D pcm_u24le PCM unsigned 24-bit little-endian+ A....D pcm_u32be PCM unsigned 32-bit big-endian+ A....D pcm_u32le PCM unsigned 32-bit little-endian+ A....D pcm_u8 PCM unsigned 8-bit+ A....D pcm_vidc PCM Archimedes VIDC+ A....D real_144 RealAudio 1.0 (14.4K) (codec ra_144)+ A....D roq_dpcm id RoQ DPCM+ A..X.D s302m SMPTE 302M+ A....D sbc SBC (low-complexity subband codec)+ A..X.D sonic Sonic+ A..X.D sonicls Sonic lossless+ A....D libspeex libspeex Speex (codec speex)+ A..X.D truehd TrueHD+ A....D tta TTA (True Audio)+ A..X.D vorbis Vorbis+ A....D libvorbis libvorbis (codec vorbis)+ A....D wavpack WavPack+ A....D wmav1 Windows Media Audio 1+ A....D wmav2 Windows Media Audio 2+ S..... ssa ASS (Advanced SubStation Alpha) subtitle (codec ass)+ S..... ass ASS (Advanced SubStation Alpha) subtitle+ S..... dvbsub DVB subtitles (codec dvb_subtitle)+ S..... dvdsub DVD subtitles (codec dvd_subtitle)+ S..... mov_text 3GPP Timed Text subtitle+ S..... srt SubRip subtitle (codec subrip)+ S..... subrip SubRip subtitle+ S..... text Raw text subtitle+ S..... ttml TTML subtitle+ S..... webvtt WebVTT subtitle+ S..... xsub DivX subtitles (XSUB)diff --git a/tests/test_all.py b/tests/test_all.pyindex efeba8c..07b1394 100644--- a/tests/test_all.py+++ b/tests/test_all.py@@ -2124,7 +2124,7 @@ class FFmpegSkillTests(unittest.TestCase):m = probe(str(OUT / "render_final.mp4"))self.assertEqual((m["video"]["width"], m["video"]["height"]), (1080, 1920))self.assertClose(m["duration"], 4 + 3.2 - 0.5, 0.4)- self.assertFalse((OUT / "render_final_work").exists(), "work dir removed when not kept")+ self.assertEqual(list(OUT.glob("render_final_work*")), [], "work dir removed when not kept")init = OUT / "init.json"script("render.py", "--init", init)self.assertIn("clips", json.loads(init.read_text()))@@ -2133,6 +2133,21 @@ class FFmpegSkillTests(unittest.TestCase):self.assertEqual(out["stages"], ["clips", "join"])self.assertTrue(Path(out["output"]).exists())+ def test_render_default_work_dir_is_unique_per_process(self):+ """The default work dir name came only from the output path (e.g. "out_work"), no PID or+ timestamp -- two concurrent render.py runs targeting the same output (a batch.py "project"+ recipe processing files in parallel, or simply two runs by mistake) shared the same work+ directory and clobbered each other's same-named intermediates (clip00.mp4, fit.mp4, ...)+ mid-run. Verify the auto-derived work dir name includes this process's own PID."""+ proj = OUT / "project_workdir.json"+ proj.write_text(json.dumps({"output": "render_workdir_check.mp4", "clips": [{"src": "source.mp4", "in": 0, "out": 2}]}), encoding="utf-8")+ out = json.loads(script("render.py", proj, "--fast", "--stop-after", "clips", "--keep", "--json").stdout)+ self.assertEqual(out["stages"], ["clips"])+ work_dirs = [p for p in OUT.glob("render_workdir_check_work*") if p.is_dir()]+ self.assertEqual(len(work_dirs), 1)+ self.assertRegex(work_dirs[0].name, r"^render_workdir_check_work_\d+$",+ "the default work dir name must carry a PID suffix, not just the bare output stem")+def test_render_single_clip_fit_height_is_not_silently_dropped(self):"""The single-clip fit path only ever inherited width/fps from project.frame, and theflag-forwarding list that turns project.fit's own keys into fit.py argv omitted height@@ -2317,6 +2332,45 @@ class FFmpegSkillTests(unittest.TestCase):self.assertEqual(data["processed"], 1)self.assertClose(probe(data["results"][0]["output"])["duration"], 3.0, 0.3)+ def test_batch_project_recipe_cache_invalidates_on_project_json_content_change(self):+ """A "project" recipe is just {"project": "<path>", "clip_key": N} -- the real settings+ (export preset, captions, everything) live in the file at that path. The cache key used+ to hash only this outer recipe dict, so editing project.json's content (export preset+ swapped from "copy" to "x", a real re-encode) without touching batch.json itself left the+ key unchanged, and the stale cached output was served for the new settings with no error+ or warning. Verify a content-only change to project.json invalidates the cache."""+ folder = OUT / "batch_project_cache"+ folder.mkdir(exist_ok=True)+ (folder / "clip.mp4").write_bytes(Path(self.src).read_bytes())+ proj = folder / "p.json"+ proj.write_text(json.dumps({"clips": [{}], "export": {"preset": "copy"}}))+ recipe = folder / "batch.json"+ recipe.write_text(json.dumps({"glob": "clip.mp4", "output_dir": "out", "project": "p.json"}))+ data = json.loads(script("batch.py", folder, "--recipe", recipe, "--fast", "--json").stdout)+ self.assertFalse(data["results"][0].get("cached"))+ proj.write_text(json.dumps({"clips": [{}], "export": {"preset": "x"}}))+ data = json.loads(script("batch.py", folder, "--recipe", recipe, "--fast", "--json").stdout)+ self.assertFalse(data["results"][0].get("cached"), "a content-only project.json change must not be served from a stale cache")++ def test_batch_cache_write_is_atomic_no_leftover_temp_file(self):+ """The cache file used to be written with a plain write_text(), which is not atomic -- a+ process killed mid-write leaves a truncated file that the next run's json.loads() treats+ as corrupt and silently discards (every prior cache entry lost, not just the interrupted+ one). Now written via a sibling temp file + os.replace(). Verify a normal run leaves the+ cache file valid and no stray .tmp<pid> file behind."""+ folder = OUT / "batch_cache_atomic"+ folder.mkdir(exist_ok=True)+ (folder / "clip.mp4").write_bytes(Path(self.src).read_bytes())+ recipe = folder / "batch.json"+ recipe.write_text(json.dumps({"glob": "clip.mp4", "output_dir": "out", "steps": [["export.py", "{in}", "--preset", "copy", "-o", "{out}"]]}))+ script("batch.py", folder, "--recipe", recipe, "--fast")+ outdir = folder / "out"+ cache_path = outdir / ".ffskill_cache.json"+ self.assertTrue(cache_path.exists())+ json.loads(cache_path.read_text(encoding="utf-8")) # must not be truncated/corrupt+ leftover = list(outdir.glob(".ffskill_cache.json.tmp*"))+ self.assertEqual(leftover, [], f"temp cache file(s) left behind: {leftover}")+def test_batch_refuses_a_recipe_step_naming_a_script_outside_scripts_dir(self):"""run_step() built its command as `HERE / argv[0]`, where argv[0] came straight from anuntrusted recipe JSON step. Path's / operator silently ignores the left side when thediff --git a/tests/test_contract.py b/tests/test_contract.pyindex 4b40495..30cb7e2 100644--- a/tests/test_contract.py+++ b/tests/test_contract.py@@ -789,6 +789,36 @@ class ContractTests(unittest.TestCase):for t in doc["tools"]:self.assertTrue((installed / t["executable"]).is_file())+ def test_installer_upgrade_survives_an_interruption_mid_copy(self):+ """install.js used to `rmSync(t.dir)` then `mkdirSync` + copy straight into the now-empty+ target -- a process killed partway through that copy (Ctrl-C, disk full, a permission+ error) left the target either empty or half-populated, destroying a working previous+ install for nothing worse than an interrupted upgrade. Verify a copy that dies partway+ through (simulated: a marker item throws right after it's copied) leaves an existing+ install's own file untouched, instead of gone."""+ with tempfile.TemporaryDirectory() as tmp:+ env = dict(os.environ, HOME=tmp, USERPROFILE=tmp)+ installed = Path(tmp) / ".claude" / "skills" / "ffmpeg-skill"+ installed.mkdir(parents=True)+ marker = installed / "PREVIOUS_INSTALL_MARKER.txt"+ marker.write_text("preserve me", encoding="utf-8")++ js = (ROOT / "bin" / "install.js").read_text(encoding="utf-8")+ crashing_js = js.replace(+ "copyRecursive(src, path.join(tmpDir, item));",+ "copyRecursive(src, path.join(tmpDir, item)); "+ "if (item === 'SKILL.md') throw new Error('SIMULATED_CRASH_MID_COPY');",+ 1,+ )+ self.assertNotEqual(crashing_js, js, "expected to find and patch the per-item copy call")+ crashing_installer = Path(tmp) / "install_crash_test.js"+ crashing_installer.write_text(crashing_js, encoding="utf-8")++ proc = sh("node", crashing_installer, "--claude", env=env, check=False)+ self.assertNotEqual(proc.returncode, 0, "the simulated crash should make the installer report failure")+ self.assertTrue(marker.exists(), "an install interrupted mid-copy must not destroy the previous install")+ self.assertEqual(marker.read_text(encoding="utf-8"), "preserve me")+# ------------------------------------------------------------------ integration: claims hold at run time@unittest.skipIf(platform.system() == "Windows", "fake ffmpeg is a #!/bin/sh script on a POSIX-only PATH shim; not portable to Windows. The claim itself (run() never invokes ffmpeg under --dry-run) is still exercised on Windows by every --dry-run case in tests/test_all.py, just without a shim proving no *other* ffmpeg-shaped binary would have run.")def test_dry_run_never_runs_ffmpeg_and_writes_nothing(self):@@ -1308,6 +1338,21 @@ class DoctorDetectionTests(unittest.TestCase):self.assertFalse(d["ok"])self.assertEqual(code, 2)+ def test_audio_loudness_join_stay_usable_without_aac(self):+ """audio.py/loudness.py/join.py all pick their audio codec from the output extension via+ audio_codec_for() (falling back to AAC only when the extension isn't otherwise covered),+ yet the contract declared AAC unconditionally `required` for all three -- so an ffmpeg+ build without an AAC encoder made `doctor` report these tools entirely unusable, even+ though they can still produce e.g. a .flac or .wav output with no AAC involved at all."""+ d, _ = self._doctor("ffmpeg_filters_8.1.2_macos.txt", encoders="ffmpeg_encoders_6.1_no_aac.txt")+ for name in ("audio", "loudness", "join"):+ self.assertEqual(d["tools"][name]["usable"], "yes", f"{name} must stay usable without AAC")+ self.assertNotIn("missing", d["tools"][name])+ # encoder:aac is still globally `missing` (other tools, e.g. multicam, still require it+ # unconditionally) -- the point of this test is that audio/loudness/join specifically+ # don't let that sink their own usability.+ self.assertIn("encoder:aac", d["missing"])+def test_tool_usability_answers_can_i_run_this_today(self):"""`doctor`'s tools map answers "usable on this machine now", not just "what capabilities exist" --a caller should not have to cross-reference each tool's own required-capability list by hand."""