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
feat: the audio bed — voice levels, stereo widen, duck parameters, effects stem, loudness --dialogue, podcast rows, project chapters (#221)
claude[bot]71a956d34d63
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 43b93d0..49cdffc 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -4,7 +4,21 @@## Unreleased-(nothing yet)+### Added++- **`audio.py --voice` takes a strength**: `--voice light|medium|strong`, with a bare `--voice` meaning `medium` — byte for byte the chain it has always produced, so existing calls and MCP requests are unchanged. `light` is `highpass=f=80,acompressor=threshold=-18dB:ratio=2:attack=5:release=80:makeup=1` (rumble and level only, for a good room); `medium` is `highpass=f=80,deesser=i=0.4,afftdn=nf=-25:tn=1,acompressor=threshold=-18dB:ratio=3:attack=5:release=80:makeup=2`; `strong` is `medium` followed by `deesser=i=0.6,acompressor=threshold=-24dB:ratio=4:attack=5:release=120:makeup=3,alimiter=limit=0.891251:level=disabled`, for phone and laptop audio.+- **The ducking parameters are sayable**: `--duck-threshold DB` (default −26.02 dBFS, the 0.05 linear the bed has used since 1.4, so the default filter string is unchanged), `--duck-attack MS` (20) and `--duck-release MS` (400) next to the existing `--duck-amount`. `--json` gains an `audio` block reporting the voice level, the stereo width, the effects bed and the duck settings the run actually used.+- `audio.py --stereo-widen 0..1` widens the stereo image (`extrastereo=m=1+2*amount`), applied after the channel layout is settled. It needs a real stereo source and says so: widening scales the side signal (L−R), which is exactly zero once a mono track has been duplicated to two identical channels, so a 1-channel input is refused (`kind: input`) whether or not `--stereo` is given, and more than two channels are refused unless `--downmix` folds them to stereo first — in which case the widening runs on the fold-down. Nothing is downmixed implicitly.+- `audio.py --effects FILE` / `--effects-volume DB` mixes a third track (sound effects, atmos) into the bed. It is never ducked: effects are cut to the picture, so dipping them under speech would move them off their own frames.+- `loudness.py --json` now reports the loudness range on both sides (`measured.input_lra` for the input, `result.input_lra` for the written file) and echoes the requested `targets` (lufs, tp, lra); `--lra N` is documented in `references/scripts.md` and the README.+- `check.py --platform podcast` gains two informational rows: `chapters` (PASS when the container carries at least one marker, WARN `none` otherwise, with `metadata.py --chapters` as the fix) and `channels` (PASS for mono or stereo, WARN above — podcast players downmix 5.1 unpredictably). Neither can FAIL a delivery and neither appears for another platform.+- **`render.py` project keys**: `"audio": {"stems": {"dialogue": DB, "music": DB, "effects": DB}}` names one level per element of the mix, mapping to `--gain`, `--music-volume` and `--effects-volume` (an explicit flag next to a stem wins; a stems `effects` level with no `"audio": {"effects": "sfx.wav"}` file is refused), and `"chapters"` — a chapters file path or an inline list of `{"at": TIME, "title": STR}` — runs `metadata.py` on the delivered file as the last stage before `check`, so the markers are in the file that ships. The stage plans like every other one: `--dry-run`/`--plan` prints the `metadata.py` command and lists `chapters` in `stages`, so the plan the user approves is the run. `"audio": {"voice": "light"|"medium"|"strong"}` picks the voice strength; `true` still means `medium`. Both new objects are validated against the project schema, so a misspelled stem or chapter key is refused by name.+- **The audio guards say what is missing** instead of ignoring it: a duck parameter (`--duck-threshold`, `--duck-attack`, `--duck-release`, `--duck-amount`) without `--duck`, and `--duck` without `--music`, are refused (`kind: input`) the way a typed dynamics parameter without its switch already was. In a `render.py` project, an `audio.stems.music` level with no `"music"` file is refused like `stems.effects` without an `"effects"` file, and `chapters` entries (a missing `at` or `title`, a chapters file that does not exist) are validated before the first ffmpeg call rather than after the render has already delivered an unchaptered file.+- `tests/fixtures/mcp_tools.json` regenerated: `audio` gains `duck_threshold`, `duck_attack`, `duck_release`, `stereo_widen`, `effects` and `effects_volume` and `voice` becomes a `light|medium|strong` enum. A client still sending the 1.12 boolean `{"voice": true}` keeps working: `true` is the bare flag, which is `medium`; `docs/contract.md` and `audio.py --help` say so.++### Docs+- **Not shipped: a `loudness.py --dialogue` speech gate.** `loudnorm`'s EBU R128 integrated measurement already applies the −70 LUFS absolute and −10 LU relative gates, so gating the measurement on speech spans moved the result by at most 0.6 LU on every fixture (including one that is half digital silence) — inside `check.py`'s own ±1 LU tolerance — for the cost of a second decode pass. `references/gotchas.md#loudness-and-ambience` records it.+- `docs/roadmap.md` marks 1.13.0 done and records the decision **not** to add `audio.py --chapters`: `metadata.py episode.mp4 --chapters chapters.txt` already writes chapter markers with every stream copied, and a second spelling inside a tool that re-encodes the audio would be the worse one. `render.py`'s `chapters` key is the project-level answer instead.## 1.12.0@@ -24,6 +38,7 @@ _Automated release: version and notes generated from pull requests merged since- `doctor`'s plain `fonts:` line carries the default font's `detail` in brackets when the status is not `available` and the detail is short enough to keep the line to one screen width; longer detail stays `--json` only.- `references/gotchas.md` on RTL: `caption.py` shapes and reorders Arabic and Hebrew by construction (everything it draws goes through libass); `drawtext` (`overlay.py --text`, `graphics.py`) does too on a build with `--enable-libfribidi`/`--enable-libharfbuzz`, and only an older build draws unjoined logical order.+- **The audio guards say what is missing** instead of ignoring it: a duck parameter (`--duck-threshold`, `--duck-attack`, `--duck-release`, `--duck-amount`) without `--duck`, and `--duck` without `--music`, are refused (`kind: input`) the way a typed dynamics parameter without its switch already was. In a `render.py` project, an `audio.stems.music` level with no `"music"` file is refused like `stems.effects` without an `"effects"` file, and `chapters` entries (a missing `at` or `title`, a chapters file that does not exist) are validated before the first ffmpeg call rather than after the render has already delivered an unchaptered file.- `tests/fixtures/mcp_tools.json` regenerated: `caption` gains `language` (spelled `--lang` too), `offset`, `max_lines`, `min_duration`; `graphics` gains `lang`.### Docsdiff --git a/README.md b/README.mdindex 7e7081d..4d9ee5e 100644--- a/README.md+++ b/README.md@@ -196,9 +196,9 @@ These are the rules the skill file gives the agent and the code enforces. Togeth| Tool | What it does ||---|---|-| `audio.py` | Voice clean-up chain, FFT denoise, typed compressor / limiter / gate, music bed with sidechain ducking, fades, 5.1 → stereo, track replacement, extraction (`-o out.wav`), `--audio-stream N` |+| `audio.py` | Voice clean-up chain at three strengths (`--voice light\|medium\|strong`), FFT denoise, typed compressor / limiter / gate, music bed with sidechain ducking (`--duck-amount/-threshold/-attack/-release`), a never-ducked effects bed (`--effects`), `--stereo-widen`, fades, 5.1 → stereo, track replacement, extraction (`-o out.wav`), `--audio-stream N` || `sync.py` | Offset between two recordings by audio cross-correlation (1 ms, pure Python), clock-drift correction; aligned video or audio out (audio-to-audio only — no lip-sync/face detection) |-| `loudness.py` | Two-pass EBU R128 `loudnorm` to −14 LUFS / −1 dBTP or any target, video stream-copied; the written file is measured again and re-encoded until it meets `--tp` (lossy encoders overshoot); `--measure-only` |+| `loudness.py` | Two-pass EBU R128 `loudnorm` to −14 LUFS / −1 dBTP or any target (`--lra` for the range), video stream-copied; the written file is measured again and re-encoded until it meets `--tp` (lossy encoders overshoot); `--measure-only` |**Picture**@@ -215,14 +215,14 @@ These are the rules the skill file gives the agent and the code enforces. Togeth|---|---|| `export.py` | Presets `youtube`, `youtube4k`, `reels`, `x`, `prores`, `h265`, `gif`, all tagged BT.709; `--normalize` meets the platform's loudness in the same call (`render.py` turns it on by default for platform presets) || `proxy.py` | Small, low-bitrate proxy for downstream AI analysis/preview/editing decisions — resize by `--width`/`--scale`, proxy-grade `--crf` (deprecated alias of `--quality`), `--fps`, `--no-audio`; not a delivery preset |-| `check.py` | PASS / WARN / FAIL against YouTube, Shorts, Reels, TikTok, X, LinkedIn, broadcast and podcast specs, with the fix for each failure and a `format` / `judgement` kind per row |+| `check.py` | PASS / WARN / FAIL against YouTube, Shorts, Reels, TikTok, X, LinkedIn, broadcast and podcast specs (podcast also reports chapter markers and channel count), with the fix for each failure and a `format` / `judgement` kind per row || `report.py` | Single-file HTML delivery report: before/after sheets, media facts, loudness, compliance, the commands run |**Orchestration**| Tool | What it does ||---|---|-| `render.py` | Render a whole edit from a declarative `project.json` (clips, transitions, captions, overlays, music, loudness, export, check); `--init`, `--dry-run`, `--stop-after` |+| `render.py` | Render a whole edit from a declarative `project.json` (clips, transitions, captions, overlays, music and stem levels, loudness, export, chapter markers, check); `--init`, `--dry-run`, `--stop-after` || `batch.py` | Apply a step recipe or a project to a folder with a content-hash cache; `--watch` || `multicam.py` | Align any number of cameras and recorders by audio (with drift correction) and cut between them from a switch list || `verify.py` | Run the toolchain on real device files and report PASS / FAIL per step |@@ -237,7 +237,7 @@ WAV, FLAC, MP3, M4A/AAC, OGG and Opus go through `probe`, `cut`, `join`, `silenc- **Join.** `join.py intro.wav episode.m4a outro.wav -o full.flac` resamples every clip to one rate and channel layout and crossfades them (`--transition none` for a butt join). Audio and video inputs cannot be mixed in one join.- **Sample-accurate trims.** `cut.py talk.wav --start 1.2345 --end 2.3456 --accurate` trims at the sample; the JSON reports `precision` (`packet` for a stream copy, `sample` for PCM / FLAC, `codec_frame` when a lossy encoder frames the audio again, `frame` for video) and the measured `duration_error_ms`. A `.wav` never receives compressed packets.- **Typed dynamics.** `audio.py --compress --comp-threshold -20 --comp-ratio 4`, `--limit --limit-ceiling -1`, `--gate --gate-threshold -45`. Each flag is one documented option of FFmpeg's `acompressor`, `alimiter` or `agate`, range-checked before ffmpeg runs; no filter string is accepted from the caller.-- **Loudness.** `loudness.py talk.wav -I -16 --tp -1.5 -o talk.m4a` for podcast levels; `check.py talk.m4a --platform podcast` measures LUFS and true peak.+- **Loudness.** `loudness.py talk.wav -I -16 --tp -1.5 -o talk.m4a` for podcast levels; `check.py talk.m4a --platform podcast` measures LUFS and true peak and reports the chapter markers and channel count.Picture tools (`fit`, `caption`, `overlay`, `graphics`, `color`, `export`, `scenes`, `look`) refuse an audio file with "input has no video stream" instead of inventing a picture.diff --git a/SKILL.md b/SKILL.mdindex 34c67c7..81a70f2 100644--- a/SKILL.md+++ b/SKILL.md@@ -5,30 +5,30 @@ description: 'Edit video and audio with local FFmpeg from natural-language reque# ffmpeg-skill-Scripts live in `scripts/` next to this file; run them with `python3 <skill-dir>/scripts/<name>.py`. This file is enough to do a job: the table below routes the request, the recipes give the flags, and `--help` on the one script you are about to run is the cheapest full flag list. The reference files cost as much to read as this file does, so open one only when it answers a question you actually have: `references/scripts.md` (every flag of all 42 scripts, for comparing tools), `references/devices.md` (iPhone HDR, GoPro, DJI, screen recordings, Zoom), `references/gotchas.md` (the long form of the one-line rules at the end of this file).+Scripts live in `scripts/` next to this file; run them with `python3 <skill-dir>/scripts/<name>.py`. This file is enough to do a job: the table below routes the request and `--help` on the one script you are about to run is the cheapest full flag list. The reference files cost as much to read as this file does, so open one only when it answers a question you actually have: `references/scripts.md` (every flag of all 42 scripts, for comparing tools), `references/devices.md` (iPhone HDR, GoPro, DJI, screen recordings, Zoom), `references/gotchas.md` (the long form of the one-line rules at the end of this file).-Shared flags, on every script: `--dry-run`; `--json` (output path, a probe of the output, the commands run); `--json-brief` (that document trimmed to status/output/verified, a compact `summary` and the command count — prefer it on every writing step, `--json` when you need the full probe); `--fast` (preview quality); `--progress`; `--timeout SECONDS` (`kind: timeout`, default 1800); `--overwrite` (consent to replace an existing output — without it the tool warns today, refuses from 2.0); `--plan FILE` (the dry run as a plan document `render.py FILE` executes later, refusing if an input changed: "plan → confirm → execute" in one round trip). Every re-encoding tool also takes `--codec h264|hevc|av1|prores` and `--quality N` (CRF scale, replaces the deprecated `--crf`): unset, SDR is x264 and HDR is x265 Main10; `prores` needs an explicit `-o NAME.mov` (or `.mkv`), `h264` refuses an HDR source (run `color.py --to-sdr` first).+Shared flags, on every script: `--dry-run`; `--json` (output path, a probe of the output, the commands run); `--json-brief` (that document trimmed to status/output/verified, a compact `summary` and the command count — prefer it on every writing step); `--fast` (preview quality); `--progress`; `--timeout SECONDS` (`kind: timeout`, default 1800); `--overwrite` (consent to replace an existing output — without it the tool warns today, refuses from 2.0); `--plan FILE` (the dry run as a plan document `render.py FILE` executes later, refusing if an input changed: "plan → confirm → execute" in one round trip). Every re-encoding tool also takes `--codec h264|hevc|av1|prores` and `--quality N` (CRF scale, replaces the deprecated `--crf`): unset, SDR is x264 and HDR is x265 Main10; `prores` needs an explicit `-o NAME.mov`, `h264` refuses an HDR source (`color.py --to-sdr` first).Writing tools run nothing under `--dry-run`; `probe`, `check`, `sync`, `multicam`, `scenes`, `cropdetect`, `report`, `silence`, `loudness` and `stabilize` may still run ffmpeg/ffprobe to measure or analyse — they just don't write their final artifact (nor side files such as `--edl`, `--sheet` or a generated `.ass`); `verify` accepts the flag but ignores it. Exact per-tool semantics: `contract --json`'s `dry_run` field (or `docs/contract.md`).## Workflow (always follow this order)-0. **Environment, only on failure.** Do not start a job with `doctor`: on a working machine it is a call that tells you nothing the job needs, and on a broken one the script fails on its own with `kind: missing_tool` (no ffmpeg) or an ffmpeg error naming the filter or encoder (`No such filter: 'subtitles'`). Run `python3 <skill-dir>/scripts/_contract.py doctor` (also `npx ffmpeg-skill doctor`; there is no doctor.py) after such a failure, or when the user asks what the machine can do. Read `ok` and the tool's `usable`; if `usable` isn't `yes`, report the missing capability (a missing `libass`, `zscale` or encoder is the common case, e.g. `caption.py`) instead of discovering it through a runtime failure. `contract --json`'s full tool schema is for a *planning* agent choosing a tool from an abstract goal, not for this per-job workflow.+0. **Environment, only on failure.** Do not start a job with `doctor`: on a working machine it tells you nothing the job needs, and on a broken one the script fails on its own with `kind: missing_tool` (no ffmpeg) or an ffmpeg error naming the filter or encoder (`No such filter: 'subtitles'`). Run `python3 <skill-dir>/scripts/_contract.py doctor` (also `npx ffmpeg-skill doctor`; there is no doctor.py) after such a failure, or when the user asks what the machine can do. Read `ok` and the tool's `usable`; if `usable` isn't `yes`, report the missing capability (usually `libass`, `zscale` or an encoder) instead of discovering it through a runtime failure. `contract --json`'s full tool schema is for a *planning* agent choosing a tool from an abstract goal, not for this workflow.1. **Probe what you must plan from.** Run `probe.py` on each input you plan the edit from — duration, fps, resolution, codecs, channels, `variable_frame_rate_suspected` — and whenever the user asks a question about a file. You do not need a separate probe before every edit: every writing tool's `--json` already carries its input and a probe of the output it wrote. Plan from real numbers, never assumptions.2. **Prefer lossless.** If the request can be met without re-encoding (plain cuts on keyframes, remuxing, audio-only changes), do not re-encode. `cut.py` and `loudness.py` stream-copy video by default; pass `--accurate` to `cut.py` only for frame-exact cuts.3. **Plan with `--dry-run --json`, then execute.** Trust `--json`, not a dry run's human-readable summary line, for any number after the plan (dimensions there can be a placeholder, not a computed preview — `docs/contract.md`). Use it to confirm a plan before long encodes and to report exact facts. `--fast` is preview quality (x264 veryfast), `--progress` prints percent/ETA on stderr. Never point `-o` at a file you did not create in this job unless the user asked for it to be replaced; pass `--overwrite` only then.4. **Chain in a sensible order.** Colour (HDR→SDR / LUT) → cut → join → silence → fit → caption/overlay → sync → audio → loudness → export. Frame changes (fit/crop) before captions and overlays, so text is sized for the final frame. Re-encode as few times as possible: intermediates at CRF 18 (the default), `export.py` only for the last step. **Three or more steps: use `render.py` with a project.json** — one call, one JSON, one place for the user to change a number — rather than hand-chaining tools.-5. **Check the deliverable.** Before reporting, run `check.py OUTPUT --platform X` for the destination the user named. Each row is `format` or `judgement`. Format rows (codec, pixel format, size, true peak, colour tags, VFR) are safe to fix mechanically. Judgement rows change the content: duration (cut loses material, speed changes motion), aspect (crop loses edges), fps (drops motion), loudness (ambience must not be boosted) — fix those only when the request already implies the answer, otherwise state the choice and its cost in one line. Mention WARNs; do not chase them.-6. **Verify the output.** Confirm duration, resolution, fps and audio match the request — from the writing tool's own `--json`/`--json-brief` probe, or `probe.py` when you have none — and report those numbers ("final.mp4: 59.98 s, 1080x1920, 30 fps, AAC stereo"). A step is done only when the script exited 0 and the output probes as expected. Writing the command is not doing the job: a non-zero exit, a missing or empty file, or a probe that contradicts the request is a failure, and the report says so with the script's error message.+5. **Check the deliverable.** Before reporting, run `check.py OUTPUT --platform X` for the destination the user named. Each row is `format` or `judgement`. Format rows (codec, pixel format, size, true peak, colour tags, VFR) are safe to fix mechanically. Judgement rows change the content: duration (cut loses material), aspect (crop loses edges), fps (drops motion), loudness (ambience must not be boosted) — fix those only when the request already implies the answer, otherwise state the choice and its cost in one line. Mention WARNs; do not chase them.+6. **Verify the output.** Confirm duration, resolution, fps and audio match the request — from the writing tool's own `--json`/`--json-brief` probe, or `probe.py` — and report those numbers ("final.mp4: 59.98 s, 1080x1920, 30 fps, AAC stereo"). A step is done only when the script exited 0 and the output probes as expected: a non-zero exit, a missing or empty file, or a probe that contradicts the request is a failure, and the report says so with the script's error message.7. **Keep the user's originals.** Never overwrite the source; write new files next to the input or where the user asked. Set `FFMPEG_SKILL_NO_OVERWRITE=1` in the environment you run these scripts in: an existing output path is then refused (`kind: input`) instead of warned about, and `--overwrite` stays the one way to say "yes, replace it". It is the recommended agent setting — an agent picking output names cannot see which files the user already cares about — and it is what 2.0 does by default.-8. **Look at the picture.** Whenever the picture changed (captions, overlays, graphics, crop/pad, resize, colour, transitions, a `join.py` that scaled or padded a clip to the first clip's frame, a `color.py --to-sdr` that tone-maps an HDR source) run `look.py OUTPUT --tiles 3x2` (or `--at T` for one frame) and view the PNG; the full 4x3 sheet is for a job about layout across the whole clip. The job is not finished until the report's `Look:` line names that PNG — a probe cannot see a caption sitting on someone's face. Audio-only jobs (sync, loudness, silence, or any job whose input is an audio file) write `Look: not needed`; there is no picture. What to look for splits like `check.py`'s rows in step 5:+8. **Look at the picture.** Whenever the picture changed (captions, overlays, graphics, crop/pad, resize, colour, transitions, a `join.py` that scaled or padded a clip to the first clip's frame, a `color.py --to-sdr` that tone-maps an HDR source) run `look.py OUTPUT --tiles 3x2` (or `--at T` for one frame) and view the PNG; the full 4x3 sheet is for a job about layout across the whole clip. The job is not finished until the report's `Look:` line names that PNG — a probe cannot see a caption sitting on someone's face. Audio-only jobs write `Look: not needed`; there is no picture. What to look for splits like `check.py`'s rows in step 5:- **Mechanical (this skill's own job to verify and report):** the specified text/logo is present at the specified position, subtitles/text appear at the specified timestamps, dimensions are even. Letterboxing/pillarboxing from `fit.py --fit pad` is the *correct* result of that mode, never a defect to flag.- **Judgement (report it, don't silently pass or fail):** whether a subject or face is cut off, whether text sits over a face, whether colours look washed out, whether a transition lands. These need deciding what the subject *is*, which belongs to the calling agent (see "What this skill does and does not decide") — say what you see in one line and let them judge it.With no vision capability, write `Look: PATH (pixels not inspected; agent has no image view)` — never claim a picture was inspected when it wasn't, and don't stall waiting for a capability that isn't there.## Before you run anything: what to ask, what to assume-Ask one short question only when the answer changes the output materially and the request does not imply it. When several things are open at once (a vague "make it for social media" leaves destination, aspect method, length and captions unresolved), don't ask them one per turn: propose one bundle with your defaults and let the user change any part ("Reels: 9:16 with padding, trimmed to 60 s, -14 LUFS, no captions — OK, or change something?"). One question, one answer, then the run. Never ask for what `probe.py` can tell you.+Ask one short question only when the answer changes the output materially and the request does not imply it. When several things are open at once (a vague "make it for social media" leaves destination, aspect, length and captions open), don't ask them one per turn: propose one bundle with your defaults and let the user change any part ("Reels: 9:16 with padding, trimmed to 60 s, -14 LUFS, no captions — OK, or change something?"). One question, one answer, then the run. Never ask for what `probe.py` can tell you.- **Destination** decides aspect, length limit, loudness and codec; "for Reels" answers all four. No destination named and a plain cut/caption: keep the source format and say so. If the user says "export", "post" or "deliver", ask where.- **Duration** ("make it 60 s") without a method: speed up for ≤1.5× changes, trim otherwise, and say which you chose. Ask when the content is a talk (trimming loses words) and the change is large.@@ -51,13 +51,13 @@ This skill cuts, joins, measures, syncs, exports and checks files — it executeThe line: same input + same explicit parameters always producing the same verifiable output belongs here; anything that depends on taste, content understanding or what looks or sounds good belongs to whoever makes that judgement. This skill executes parameters it is given, never infers them from what something looks or sounds like.-If a request needs an FFmpeg feature none of the 42 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 42 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), so it is never the fallback when a script's flag doesn't cover something.## Request → scriptThis table and `doctor --json`'s `tools` list are the source of truth for what exists: name only a script you have seen in one of them, never a plausible-sounding one (there is no `doctor.py`, no `trim.py`, no `subtitle.py`).-Timestamp flags — `--start`, `--end`, `--at`, `--from`, `--duration`, `--offset`, and the times in cue and chapter files — take seconds, `mm:ss(.fff)`, `hh:mm:ss(.fff)` or four-part SMPTE `hh:mm:ss:ff`, with `@fps` naming the rate (`00:01:02:[email protected]`); tolerance-style flags that are a length rather than a point in time (`--min-silence`, `--margin`, `--min-keep`, `--fade`) are plain seconds. Use the timecode forms when the user pastes an editor's timecode list or an NLE cue sheet, so nothing is converted by hand on the way in.+Timestamp flags — `--start`, `--end`, `--at`, `--from`, `--duration`, `--offset`, and the times in cue and chapter files — take seconds, `mm:ss(.fff)`, `hh:mm:ss(.fff)` or four-part SMPTE `hh:mm:ss:ff`, with `@fps` naming the rate (`00:01:02:[email protected]`); tolerance-style flags that are a length rather than a point in time (`--min-silence`, `--margin`, `--min-keep`, `--fade`) are plain seconds. Use the timecode forms when the user pastes an editor's or NLE cue sheet, so nothing is converted by hand.| User says | Do ||-----------|----|@@ -87,7 +87,7 @@ Timestamp flags — `--start`, `--end`, `--at`, `--from`, `--duration`, `--offse| "speed up here, slow-mo there" (known segments) | `speedramp.py action.mp4 --segment 0-3:1.0 --segment 3-4:0.25 --segment 4-8:2.0` || "loop this clip to fill 30 seconds" | `loop.py bg_loop.mp4 --duration 30` || "cut to the product shot 0:12-0:16", "B-roll over this bit" | `broll.py talk.mp4 --insert product.mp4 --at 12 --end 16` (repeat `--insert/--at`; `--audio b\|mix`) |-| "add chapters", "chapter markers for YouTube" | `metadata.py episode.mp4 --chapters chapters.txt` (`TIME TITLE` per line; streams copied) |+| "add chapters", "chapter markers for YouTube" | `metadata.py episode.mp4 --chapters chapters.txt` (`TIME TITLE` per line; streams copied; a `render.py` project spells it `"chapters"`) || "set the title / artist / comment" | `metadata.py episode.mp4 --title "Episode 12" --artist "Studio"` || "put these videos in a 4x2 grid" | `grid.py t1.mp4 ... t8.mp4 --cols 4 --rows 2` || "add subtitles from this SRT", "burn in captions" | `caption.py input.mp4 --srt subs.srt` |@@ -98,7 +98,7 @@ Timestamp flags — `--start`, `--end`, `--at`, `--from`, `--duration`, `--offse| "webcam clip in the corner", "picture-in-picture" | `overlay.py input.mp4 --video webcam.mp4 --position bottom-right --scale 480` || "remove the green screen" | `overlay.py bg.mp4 --video greenscreen.mp4 --chromakey 0x00ff00` || "sync the lav mic", "line up two cameras" | `sync.py camera.mp4 mic.wav --replace-audio` / `sync.py camA.mp4 camB.mp4 --trim-second` |-| "fix the audio levels", "normalise to -14 LUFS" | `loudness.py input.mp4` (`-I -16 --tp -1.5` podcast, `-I -23` broadcast) |+| "fix the audio levels", "normalise to -14 LUFS" | `loudness.py input.mp4` (`-I -16 --tp -1.5` podcast, `-I -23` broadcast; `--lra N` for the range) || "cut this and make it HEVC / AV1 / ProRes" (output codec named) | `cut.py input.mp4 --start 0:10 --end 0:40 --codec hevc` (`--codec`/`--quality` on any re-encoding tool; ProRes needs `-o NAME.mov`) || "export for YouTube / Reels / X", "a ProRes master" | `export.py input.mp4 --preset youtube\|reels\|x\|prores\|h265` (`--normalize` hits the loudness spec in the same call) || "make a GIF preview" | `export.py input.mp4 --preset gif` |@@ -109,6 +109,7 @@ Timestamp flags — `--start`, `--end`, `--at`, `--from`, `--duration`, `--offse| "what would you run?", "don't render yet" | any script with `--dry-run` || "a 60 s highlight from this hour" | `scenes.py long.mp4 --highlights 6 --target 60 --edl picks.txt` → `cut.py --segments` || "is this OK to upload?" | `check.py final.mp4 --platform reels` |+| "a podcast episode with chapters" | `loudness.py ep.wav -I -16 --tp -1.5` → `metadata.py ep.m4a --chapters chapters.txt` → `check.py ep.m4a --platform podcast` (chapters and channels rows) || "several changes to the same edit", 3+ steps | `render.py --init project.json`, edit, `render.py project.json` || "a lower third with my name", "countdown intro", "progress bar" | `graphics.py input.mp4 --template lower-third --name "..." --title "..." --start 2 --end 8` || "use our brand fonts/colours/logo" | `--brand brand.json` on caption/overlay/graphics, or `"brand"` in project.json |@@ -124,8 +125,10 @@ Timestamp flags — `--start`, `--end`, `--at`, `--from`, `--duration`, `--offse| "apply this LUT", "convert the S-Log footage" | `color.py input.mp4 --lut grade.cube [--lut-strength 0.7]` || "the colours are tagged wrong" | `color.py input.mp4 --retag bt709` (stream copy; re-encodes only if the copy can't carry it — see `reencoded`) || "brighten it / punch up contrast / fix white balance" | `color.py input.mp4 --correct --exposure 0.3 --contrast 1.1 --saturation 1.05 --temperature 5600 --tint -0.05` |-| "clean up the audio", "remove the hiss" | `audio.py input.mp4 --voice` (speech) or `--denoise` |-| "add background music under the talking" | `audio.py input.mp4 --music bed.mp3 --duck --fade-out 3` |+| "clean up the audio", "remove the hiss" | `audio.py input.mp4 --voice` (speech; `--voice light\|medium\|strong`) or `--denoise` |+| "add background music under the talking" | `audio.py input.mp4 --music bed.mp3 --duck --fade-out 3` (`--effects sfx.wav` adds a third bed, never ducked; project levels: `audio.stems`) |+| "make the music duck harder / come back faster" | add `--duck-amount 18 --duck-threshold -30 --duck-release 250` (`--duck-attack` too) |+| "the mix sounds narrow", "wider stereo" | `audio.py band.wav --stereo-widen 0.5` (needs a real stereo source; 5.1 needs `--downmix`) || "convert the 5.1 to stereo" | `audio.py input.mov --downmix` || "swap in the narration track" | `audio.py input.mp4 --replace narration.wav` || "pull the audio out", "give me the sound as WAV" | `audio.py input.mp4 -o input.wav` (an audio extension drops the picture; `--audio-stream 1` picks a track) |@@ -137,12 +140,12 @@ Timestamp flags — `--start`, `--end`, `--at`, `--from`, `--duration`, `--offse## Audio-only files-Audio is a first-class input: `probe.py`, `cut.py`, `silence.py`, `loudness.py`, `audio.py`, `sync.py` and `check.py --platform podcast` take WAV, FLAC, MP3, M4A/AAC, OGG and Opus, and the output extension picks the format. `Look: not needed` in the report; `Check:` still applies (`check.py file.wav --platform podcast`). Scripts that need a picture (`fit`, `caption`, `overlay`, `graphics`, `color`, `export`, `scenes`, `look`) refuse an audio file with "input has no video stream" — say so instead of forcing a video wrapper. The same commands work with `talk.wav` in place of `talk.mp4`; audio-specific recipes, packet vs sample precision, joining and extracting one track: `references/gotchas.md#audio-only-files`.+Audio is a first-class input: `probe.py`, `cut.py`, `silence.py`, `loudness.py`, `audio.py`, `sync.py` and `check.py --platform podcast` take WAV, FLAC, MP3, M4A/AAC, OGG and Opus, and the output extension picks the format. `Look: not needed` in the report; `Check:` still applies. Scripts that need a picture (`fit`, `caption`, `overlay`, `graphics`, `color`, `export`, `scenes`, `look`) refuse an audio file with "input has no video stream" — say so instead of forcing a video wrapper. The same commands work with `talk.wav` in place of `talk.mp4`; audio recipes, packet vs sample precision, joining and extracting one track: `references/gotchas.md#audio-only-files`.## Report format-Reply in the language the request itself is written in — the user's own sentences, not a language the request talks about (a request for subtitles in another language is still answered in the language it was written in) and not the language of a tool's error text or file names. Chinese, Korean, Spanish, Portuguese, French, German, Arabic or any other language works exactly the same way. Keep the field labels (`Done:`, `Steps:`, `Check:`, `Look:`, `Notes:`) in English: they read like log fields and stay recognisable across languages. Everything around them — the sentences, any question, any explanation of a judgement call — is in the user's language. Never default to English because the tool names and flags are English, and never drift into another language because the job was short or the report is a failure: a one-line "file does not exist" is written in the request's language too. A mid-conversation switch follows the user's latest message, not the first one. This holds for a one-command job: a three-second audio trim with English `Done:`/`Steps:` sentences and one word of the user's language in `Notes:` is an English report — the descriptions (what was cut, from where) are in the user's language even when the values are technical.+Reply in the language the request itself is written in — the user's own sentences, not a language the request talks about (a request for subtitles in another language is still answered in the language it was written in) and not the language of a tool's error text or file names. Any language works the same way. Keep the field labels (`Done:`, `Steps:`, `Check:`, `Look:`, `Notes:`) in English: they read like log fields and stay recognisable across languages. Everything around them — the sentences, any question, any explanation of a judgement call — is in the user's language. Never default to English because the tool names and flags are English, and never drift because the job was short or the report is a failure: a one-line "file does not exist" is written in the request's language too. A mid-conversation switch follows the user's latest message. This holds for a one-command job: English `Done:`/`Steps:` sentences with one word of the user's language in `Notes:` is an English report — the descriptions are in the user's language even when the values are technical.Finish every job with this shape (numbers from a tool's `--json` or `probe.py`/`check.py`, not memory):@@ -178,7 +181,7 @@ Look: not needed (nothing written)Notes: send a valid .cube, or say if you want the clip left as is```-A refusal (a judgement this skill does not make, or something outside its scope) uses the same shape: `Failed:` names what was refused and why, `Steps:` lists what did run (usually only probe), `Look: not needed`. Both keep the five labels so a failed report scans like a successful one — the shortest failure (a missing input, an invalid LUT) still gets all five lines, never prose headings in their place. When a failure JSON carries `error.hint`, quote it in `Notes:`: it is the flag change that makes a retry meaningful.+A refusal (a judgement this skill does not make, or something outside its scope) uses the same shape: `Failed:` names what was refused and why, `Steps:` lists what did run (usually only probe), `Look: not needed`. Both keep the five labels so a failed report scans like a successful one — the shortest failure still gets all five lines, never prose headings. When a failure JSON carries `error.hint`, quote it in `Notes:`: it is the flag change that makes a retry meaningful.Every script prints `{"status": "failed", "error": {"kind": input | ffmpeg | output | missing_tool | timeout | verification | interrupted, "message": ...}}` with `--json` and exits non-zero; quote the message, never paraphrase it into a success.diff --git a/docs/contract.md b/docs/contract.mdindex 8d02423..9ca8903 100644--- a/docs/contract.md+++ b/docs/contract.md@@ -354,6 +354,21 @@ runs a shell, evaluates strings, or executes anything other than the named scrip## JSON output+Per-tool keys added in 1.13: `audio` (`audio.py`) reports the mix it built — the+`--voice` level, `stereo_widen`, whether an `--effects` bed was mixed, and with+`--music` the `music_volume` plus a `duck` object naming the threshold (dB and+linear), ratio, attack and release actually used, or `null` when `--duck` was not+given. `loudness.py` reports `measured` (the input's loudnorm measurement,+including `input_lra`) and `targets` (the requested lufs / tp / lra).+`check.py --platform podcast` adds two informational rows to `checks`,+`channels` and `chapters`.++The MCP `audio` tool publishes `voice` as `{"type": "string", "enum": ["light",+"medium", "strong"]}`. A client that still sends the 1.12 boolean `{"voice":+true}` keeps working: `true` emits the bare `--voice`, which is `medium` — the+chain the flag has always produced. Send the string when you can; the boolean+is accepted at runtime and means `medium`.+Success (`exit 0`): one document matching `output_schema`, always with`status: "completed"`, `output`, `dry_run`, `commands`, and `probe` of the output when afile was written. `probe` prints its measurement document directly.diff --git a/docs/roadmap.md b/docs/roadmap.mdindex 8a4f833..fb9d535 100644--- a/docs/roadmap.md+++ b/docs/roadmap.md@@ -109,16 +109,36 @@ and the default MCP `tools/list` are unchanged except for additions.- Eval 11: the 8 caption prompts (JA/EN, CJK wrap, karaoke, SRT offset) run 3 times, plus theper-language act/refuse prompts added for zh, ko, es, pt, fr, de and ar (pending).-## 1.13.0 — the audio bed--- `audio.py`: `--voice` strength levels (`light|medium|strong`), `--stereo-widen`, stem- levels for dialogue / music / effects in a `render.py` project (`audio.stems`), sidechain- ducking parameters exposed (`--duck-threshold`, `--duck-release`).-- `loudness.py --lra N` targets loudness range, `--dialogue` gates the measurement on speech- (ffmpeg `speechnorm` / `silencedetect` energy) so ambience-heavy edits are not over-boosted.-- `check.py --platform podcast` gains chapters and mono/stereo rows; `audio.py --chapters- chapters.txt` writes MP4/M4A chapter markers.-- Eval 12 on audio-only and mixed prompts.+## 1.13.0 — the audio bed (done)++- `audio.py` (done): `--voice [light|medium|strong]` (bare `--voice` is `medium`, the chain it+ always produced), `--stereo-widen 0..1` (refused on a mono input, and on more than two+ channels unless `--downmix` folds them to stereo first), the sidechain ducking parameters exposed (`--duck-threshold`, `--duck-attack`,+ `--duck-release`, next to the existing `--duck-amount`), and `--effects FILE` /+ `--effects-volume`: a third bed that is deliberately never ducked. `--json` gains an `audio`+ block naming the duck settings the run used. `render.py` spells the levels as+ `audio.stems: {dialogue, music, effects}`, mapping to `--gain` / `--music-volume` /+ `--effects-volume`.+- `loudness.py` (done): `--lra N` documented and the measured input/output ranges reported in+ `--json` (`measured.input_lra`, `result.input_lra`, `targets`).+- `loudness.py --dialogue` was **not** shipped. It was built (silencedetect → aselect → a gated+ loudnorm measurement) and then measured against the whole-file measurement it was meant to+ correct: `loudnorm`'s EBU R128 integrated loudness already applies the −70 LUFS absolute and+ −10 LU relative gates, which drop the same blocks the speech gate dropped. On every fixture in+ the repo — including one that is half digital silence — the gated result moved by at most+ 0.6 LU, inside `check.py`'s own ±1 LU tolerance, and cost a second full decode of the input.+ A flag that cannot change the delivered file by more than the tolerance it is checked against+ is not worth the pass; `references/gotchas.md#loudness-and-ambience` records it so it is not+ re-proposed.+- `check.py --platform podcast` (done) gains `chapters` (PASS with ≥ 1 marker, WARN `none`) and+ `channels` (PASS mono/stereo, WARN above — players downmix 5.1 unpredictably); both are+ informational and absent for other platforms.+- `audio.py --chapters` was **not** added: `metadata.py episode.mp4 --chapters chapters.txt`+ already writes them, losslessly, and a second spelling in a tool that re-encodes the audio+ would be the worse one. Instead `render.py` gained a `chapters` project key (a file path or+ an inline list of `{"at", "title"}`) that runs `metadata.py` on the delivered file as the+ last stage before `check`.+- Eval 12 on audio-only and mixed prompts (pending).## 1.14.0 — sync and multicam at scalediff --git a/references/gotchas.md b/references/gotchas.mdindex 1a16383..a08e5ce 100644--- a/references/gotchas.md+++ b/references/gotchas.md@@ -74,6 +74,14 @@ clip measured at -40 LUFS or below is room tone, wind or nothing; raising it25 dB raises the noise, not the content. Leave the level, say so, and offer musicor narration.+Do not add a speech gate in front of the measurement either: `loudnorm`'s EBU+R128 integrated loudness already applies the −70 LUFS absolute and −10 LU+relative gates, which drop the same quiet blocks a `silencedetect` pass would.+A speech-span gate was measured against the whole-file measurement on every+fixture in the repo, including one that is half digital silence, and moved the+result by at most 0.6 LU — inside `check.py`'s own ±1 LU tolerance — for the+cost of a second full decode. That is why `loudness.py` has no speech-gate flag.+## Text and framing### Captions, fonts and text orderdiff --git a/references/scripts.md b/references/scripts.mdindex 94eea57..d7e5dc5 100644--- a/references/scripts.md+++ b/references/scripts.md@@ -404,8 +404,25 @@ so the rendered file meets the platform's loudness without a separate pass. Sinc1.9.0 it is on by default when the preset is a platform (`youtube|youtube4k|reels|x`)and the project has no `loudness` stage; `"normalize": false` opts out.+`"audio": {"stems": {"dialogue": -2, "music": -18, "effects": -24}}` names one+level per element of the mix: `dialogue` is the main track's gain, `music` the+bed's level, `effects` the level of the third file `"audio": {"effects":+"sfx.wav"}` adds (never ducked). Each maps to the flag of the same meaning+(`--gain`, `--music-volume`, `--effects-volume`); an explicit flag next to a+stem wins, and a stems level with no file to apply it to (`effects` without+`"effects"`, `music` without `"music"`) is refused, `kind: input`.+`"audio": {"voice": "light"|"medium"|"strong"}` picks the voice strength+(`true` is `medium`).++`"chapters"` is a chapters file path, or an inline list of `{"at": TIME,+"title": STR}`; it runs `metadata.py` on the delivered file as the last stage+before `check`, so the markers are in the file that ships (streams copied). The+entries and the file path are validated before the first stage runs, and the+stage plans its `metadata.py` command under `--dry-run`/`--plan` like every+other stage, so the plan lists `chapters` and the run does the same work.+Stages: clips (cut, optional speed) → join (transition) → silence → fit →-captions → graphics → overlays → audio → loudness → export → check. Keys mirror the+captions → graphics → overlays → audio → loudness → export → chapters → check. Keys mirror theCLI flags of each script (see the docstring); a key `render.py` does not read -- atthe top level or in any stage/clip object -- is refused (`kind: input`) naming thekey and the nearest valid one, never silently ignored. Use it whenever an edit has@@ -437,6 +454,11 @@ step before reporting a deliverable; fix FAILs, mention WARNs. Without`--platform` the youtube spec is assumed and the judgement rows (duration,aspect, fps, resolution, loudness, true peak) come back as WARN with a `notes`line, not FAIL: name the platform when the file is a delivery for it.+`--platform podcast` adds two informational rows: `channels` (PASS for mono or+stereo, WARN above — podcast players downmix 5.1 unpredictably) and `chapters`+(PASS when the container carries at least one marker, WARN `none` otherwise —+write them with `metadata.py --chapters`). Neither can FAIL a delivery, and+neither appears for another platform.### batch.py — same recipe over a folder, cached```@@ -684,13 +706,42 @@ first on HDR or Log sources.### audio.py — clean-up, music, ducking, layout```-audio.py INPUT [--voice | --denoise [--denoise-strength 25]] [--gain dB]- [--music FILE [--music-volume -14] [--duck [--duck-amount 12]] [--music-loop]]+audio.py INPUT [--voice [light|medium|strong] | --denoise [--denoise-strength 25]] [--gain dB]+ [--music FILE [--music-volume -14] [--duck [--duck-amount 12] [--duck-threshold -26.02]+ [--duck-attack 20] [--duck-release 400]] [--music-loop]]+ [--effects FILE [--effects-volume -14]] [--stereo-widen 0..1][--fade-in S] [--fade-out S] [--stereo | --mono | --downmix] [--replace FILE] [-o OUT]```-`--voice` = highpass 80 Hz → de-esser → FFT denoise → gentle compressor, the-standard talking-head chain. `--duck` uses a sidechain compressor keyed by the-speech so music dips under dialogue and swells in pauses. `--downmix` uses the+`--voice` takes a strength; a bare `--voice` is `medium`, the chain it has always+produced. The exact filter chains:++| level | chain |+| --- | --- |+| `light` | `highpass=f=80,acompressor=threshold=-18dB:ratio=2:attack=5:release=80:makeup=1` |+| `medium` | `highpass=f=80,deesser=i=0.4,afftdn=nf=-25:tn=1,acompressor=threshold=-18dB:ratio=3:attack=5:release=80:makeup=2` |+| `strong` | the `medium` chain, then `deesser=i=0.6,acompressor=threshold=-24dB:ratio=4:attack=5:release=120:makeup=3,alimiter=limit=0.891251:level=disabled` |++`light` for a good room (rumble and level only, noise floor and sibilance left+alone), `medium` for a normal talking head, `strong` for phone/laptop audio.+`strong` is the only level with a limiter, so it is the only one whose peaks+stop at −1 dBFS: `medium` (the default, and the chain a bare `--voice` gets) can+clip a hot source, since its make-up gain has nothing above it — normalise+afterwards with `loudness.py`, or use `strong`, which measures quieter and safer.+`--duck` uses a sidechain compressor keyed by the speech so music dips under+dialogue and swells in pauses:+`sidechaincompress=threshold=0.05:ratio=<amount/3, min 2>:attack=20:release=400:makeup=1`+by default. `--duck-threshold DB` (default −26.02 dBFS, i.e. the 0.05 linear),+`--duck-attack MS` (20) and `--duck-release MS` (400) move each one; a lower+threshold ducks on quieter speech, a shorter release brings the bed back faster.+`--json`'s `audio` block reports the settings the run actually used.+`--effects FILE` mixes a third track (sound effects, atmos) at+`--effects-volume` and is never ducked — effects are cut to the picture.+`--stereo-widen 0..1` widens the stereo image (`extrastereo=m=1+2*amount`) and+needs a real stereo source: it scales the side signal (L−R), so a mono track+duplicated to two channels has nothing to scale. A 1-channel input is refused+(`kind: input`) — `--stereo` duplicates it but does not widen it — and more than+two channels are refused unless `--downmix` is given too, in which case the+widening runs on the stereo fold-down. `--downmix` uses theITU centre/LFE weights for 5.1/7.1 → stereo. `--mono` averages a stereo pair,leaves a 1-channel input untouched and downmixes >2 channels throughswresample. Video is always stream-copied, and so is a subtitle/data track@@ -701,6 +752,12 @@ Run `loudness.py` after this for final levels.```loudness.py INPUT [-I -14] [--tp -1] [--lra 11] [--measure-only] [-o OUT]```+`--lra N` is the loudness-range target in LU (default 11): lower it to squeeze a+wide-dynamic mix into a phone speaker, raise it to leave a film mix alone.+`--json` reports the measured range on both sides — `measured.input_lra` for the+input, `result.input_lra` for the written file, with `targets` echoing the+requested lufs / tp / lra.+Two-pass `loudnorm`: measure, then apply with measured values (linear mode whenthe true-peak ceiling allows). Video and any subtitle/data track arestream-copied (`dropped_non_av_streams` reports a track the container refused); audio becomes AAC indiff --git a/scripts/_contract.py b/scripts/_contract.pyindex 06ac9a4..3e0f871 100644--- a/scripts/_contract.py+++ b/scripts/_contract.py@@ -157,9 +157,11 @@ TOOL_META: Dict[str, Dict[str, Any]] = {"multicam": dict(role="execution", inputs=["reference camera", "other cameras / recorders"], outputs=["switched multicam video artifact"],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)"],+ "audio": dict(role="execution", inputs=["video or audio asset", "music bed (--music) or replacement track (--replace)", "effects/atmos track (--effects)"], outputs=["artifact with the processed audio (video stream-copied, or dropped when -o has an audio extension)"],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": "filter:acompressor", "when": "--compress / --voice"}, {"capability": "filter:alimiter", "when": "--limit / --voice strong"}, {"capability": "filter:agate", "when": "--gate"},+ {"capability": "filter:deesser", "when": "--voice medium (the default) / --voice strong"},+ {"capability": "filter:extrastereo", "when": "--stereo-widen"},{"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)"],@@ -411,7 +413,9 @@ def output_schema(name: str, meta: Dict[str, Any]) -> Dict[str, Any]:extra = {"loudness": {"type": "object", "description": "platform presets with audio: the written file's lufs/tp against the platform's target_lufs/target_tp, ok true when inside the spec; normalized true when --normalize ran loudness.py on the file"},"notes": {"type": "array", "items": {"type": "string"}}}elif name == "loudness":- extra = {"measured": {"type": "object", "description": "--measure-only prints the loudnorm measurement instead (input_i, input_tp, input_lra, input_thresh, target_offset)"}}+ extra = {"measured": {"type": "object", "description": "the loudnorm measurement of the input (input_i, input_tp, input_lra, input_thresh, target_offset); with --measure-only it is the whole result"},+ "targets": {"type": "object", "description": "the requested lufs / tp / lra"},+ "result": {"type": "object", "description": "the written file measured again (input_i, input_tp, input_lra, ...), plus tp_ceiling_used, audio_bitrate_used and encodes"}}elif name == "cut":extra = {"expected_duration": {"type": "number", "description": "seconds requested"},"duration_error_ms": {"type": ["number", "null"], "description": "written minus requested, measured by ffprobe (null under --dry-run)"},@@ -426,7 +430,8 @@ def output_schema(name: str, meta: Dict[str, Any]) -> Dict[str, Any]:elif name == "audio":extra = {"video": {"type": "boolean", "description": "true when the input's video stream was copied; false for an audio output extension (extraction)"},"audio_stream": {"type": "integer", "description": "which input audio stream was processed (--audio-stream)"},- "dynamics": {"type": "array", "items": {"enum": ["agate", "acompressor", "alimiter"]}, "description": "typed dynamics filters applied, in graph order"}}+ "dynamics": {"type": "array", "items": {"enum": ["agate", "acompressor", "alimiter"]}, "description": "typed dynamics filters applied, in graph order"},+ "audio": {"type": "object", "description": "what the mix was built from: voice (null | light | medium | strong), stereo_widen, effects/effects_volume, and with --music the music_volume plus duck (null when --duck was not given, else the threshold in dB and linear, ratio, attack_ms, release_ms, amount_db actually used)"}}props = dict(base)props.update(extra)required = ["status", "output", "dry_run", "commands"]diff --git a/scripts/audio.py b/scripts/audio.pyindex a832cfb..e4505d6 100755--- a/scripts/audio.py+++ b/scripts/audio.py@@ -7,9 +7,12 @@ drops the picture, so `audio.py talk.mp4 -o talk.wav` is an extraction.Examples:python3 audio.py interview.mp4 --denoise # FFT noise reductionpython3 audio.py interview.mp4 --voice # highpass + de-esser + compressor + denoise+ python3 audio.py interview.mp4 --voice light # highpass + gentle compression only (light|medium|strong)python3 audio.py talk.mp4 --music bed.mp3 --duck # music under speech, auto-duckedpython3 audio.py talk.mp4 --music bed.mp3 --music-volume -18 --music-fade-out 3 # bed fades, voice does notpython3 audio.py clip.mp4 --fade-in 0.5 --fade-out 1 --stereo+ python3 audio.py talk.mp4 --music bed.mp3 --duck --duck-threshold -30 --duck-release 250 # ducks earlier and recovers faster+ python3 audio.py band.wav --stereo-widen 0.5 -o wide.wav # wider stereo image (a real stereo source; mono is refused)python3 audio.py surround.mov --downmix # 5.1 -> stereo with proper centre/LFE weightspython3 audio.py clip.mp4 --replace narration.wav # swap the audio track entirelypython3 audio.py interview.mp4 -o interview.wav # extract the audio (no video in the output)@@ -18,12 +21,29 @@ Examples:"""import argparseimport sys-from typing import List+from typing import Any, Dict, Listfrom _common import STATE, add_common, apply_common, audio_codec_for, db_to_linear, default_output, die, emit, ffmpeg_base, info, is_audio_output, probe, run, run_keeping_subtitles, fmt_secsVOICE_CHAIN = "highpass=f=80,deesser=i=0.4,afftdn=nf=-25:tn=1,acompressor=threshold=-18dB:ratio=3:attack=5:release=80:makeup=2"+# --voice [light|medium|strong] (1.13). "medium" is the chain --voice has always produced, so a+# bare --voice (and every existing call and MCP request) is byte-identical to before. "light"+# leaves the noise floor and the sibilance alone -- it only removes rumble and evens the level,+# which is what a good room recording needs; "strong" is for phone/laptop audio: a harder+# de-esser, a second compression stage and a soft limiter at -1 dBFS so the peaks stop there+# instead of at whatever the make-up gain produced.+VOICE_LEVELS = {+ "light": "highpass=f=80,acompressor=threshold=-18dB:ratio=2:attack=5:release=80:makeup=1",+ "medium": VOICE_CHAIN,+ "strong": VOICE_CHAIN + ",deesser=i=0.6,acompressor=threshold=-24dB:ratio=4:attack=5:release=120:makeup=3,alimiter=limit=0.891251:level=disabled",+}++# The sidechain threshold the music bed has used since 1.4 is the linear 0.05 that ffmpeg's+# sidechaincompress takes; -26.0206 dBFS is that same number in the unit the flag speaks, so the+# default command line is unchanged to the byte while the value is now sayable.+DUCK_THRESHOLD_DB = -26.0206+# Typed dynamics: every flag maps to one real option of one ffmpeg filter, validated against the# range that filter documents (ffmpeg -h filter=acompressor / alimiter / agate). dB flags are# converted to the linear value the filter takes, so no string reaches the graph unchecked.@@ -79,13 +99,23 @@ def main() -> int:clean = ap.add_argument_group("clean-up")clean.add_argument("--denoise", action="store_true", help="FFT noise reduction (afftdn, adaptive)")clean.add_argument("--denoise-strength", type=float, default=25.0, help="noise floor in dB to remove, 10..60 (default 25)")- clean.add_argument("--voice", action="store_true", help="speech preset: highpass 80 Hz, de-esser, denoise, gentle compression")+ clean.add_argument("--voice", nargs="?", const="medium", choices=["light", "medium", "strong"], default=None,+ help="speech preset (default medium when the flag is given bare): light = highpass 80 Hz + gentle compression; "+ "medium = highpass, de-esser, denoise, gentle compression; strong = medium plus a harder de-esser, a second "+ "compressor and a soft limiter at -1 dBFS. MCP/JSON callers may still send the 1.12 boolean true, "+ "which is the bare flag and so means medium")clean.add_argument("--gain", type=float, help="gain in dB applied to the main track")music = ap.add_argument_group("music")music.add_argument("--music", help="music file to mix underneath")music.add_argument("--music-volume", type=float, default=-14.0, help="music level in dB relative to full scale (default -14)")music.add_argument("--duck", action="store_true", help="auto-duck the music when the main track has speech (sidechain compressor)")music.add_argument("--duck-amount", type=float, default=12.0, help="how many dB to duck (default 12)")+ music.add_argument("--duck-threshold", type=float, default=DUCK_THRESHOLD_DB,+ help="sidechain threshold in dBFS: the main track is heard as speech above this (default -26.02, the 0.05 linear used since 1.4)")+ music.add_argument("--duck-attack", type=float, default=20.0, help="ms the bed takes to duck once speech starts (default 20)")+ music.add_argument("--duck-release", type=float, default=400.0, help="ms the bed takes to come back up after speech (default 400)")+ music.add_argument("--effects", help="a third track (sound effects/atmos) mixed in at --effects-volume; never ducked")+ music.add_argument("--effects-volume", type=float, default=-14.0, help="effects level in dB relative to full scale (default -14)")music.add_argument("--music-loop", action="store_true", help="loop the music if shorter than the video")fades = ap.add_argument_group("fades / layout")fades.add_argument("--fade-in", type=float, default=0.0, help="seconds")@@ -94,6 +124,10 @@ def main() -> int:channels = fades.add_mutually_exclusive_group()channels.add_argument("--stereo", action="store_true", help="force 2-channel output (mono is duplicated to both sides)")channels.add_argument("--mono", action="store_true", help="force 1-channel output")+ fades.add_argument("--stereo-widen", type=float, default=None, metavar="AMOUNT",+ help="widen the stereo image, 0..1 (0 = untouched, 1 = maximum); needs a real stereo source: a mono input is "+ "refused (duplicating it leaves both channels identical, so there is nothing to widen) and more than two "+ "channels are refused unless --downmix folds them to stereo first")fades.add_argument("--downmix", action="store_true", help="downmix 5.1/7.1 to stereo using standard weights")fades.add_argument("--replace", help="replace the audio with this file (trimmed/padded to the video)")dyn = ap.add_argument_group("dynamics (typed; each flag is one option of ffmpeg's acompressor / alimiter / agate)")@@ -124,6 +158,26 @@ def main() -> int:if not getattr(args, switch) and any(getattr(args, f) is not None for f in DYNAMICS[flag_group]):die(f"--{switch} is off but one of its parameters was given; add --{switch}")+ # Same rule as the typed dynamics above, for the ducking knobs: a parameter for a switch that+ # is off does nothing, and a caller who says --duck-release 250 and gets the default 400 ms has+ # no way to notice. --duck itself needs a bed to duck.+ duck_params = [f"--duck-{name}" for name in ("threshold", "attack", "release")+ if getattr(args, f"duck_{name}") != ap.get_default(f"duck_{name}")] + \+ (["--duck-amount"] if args.duck_amount != ap.get_default("duck_amount") else [])+ if not args.duck and duck_params:+ die(f"--duck is off but {duck_params[0]} was given; add --duck")+ if args.duck and not args.music:+ die("--duck ducks the music bed under the main track, but no --music was given; add --music FILE")++ for flag, value, lo, hi in (("--duck-amount", args.duck_amount, 0.0, 60.0),+ ("--duck-threshold", args.duck_threshold, -60.0, 0.0),+ ("--duck-attack", args.duck_attack, 0.01, 2000.0),+ ("--duck-release", args.duck_release, 0.01, 9000.0)):+ if not (lo <= value <= hi):+ die(f"{flag} {value:g} is outside {lo:g}..{hi:g} (the range ffmpeg's sidechaincompress accepts)")+ if args.stereo_widen is not None and not (0.0 <= args.stereo_widen <= 1.0):+ die(f"--stereo-widen must be 0..1 (0 = untouched, 1 = maximum), got {args.stereo_widen:g}")+meta = probe(args.input)dur = meta.get("duration") or 0.0has_video = bool(meta.get("video"))@@ -136,6 +190,19 @@ def main() -> int:die(f"--audio-stream {args.audio_stream}: input has {len(streams)} audio stream(s), 0..{len(streams) - 1}")if args.audio_stream and not streams and not STATE.dry_run:die("--audio-stream needs an input with audio streams")+ in_channels = (meta.get("audio") or {}).get("channels") or 0+ if args.stereo_widen is not None:+ if args.mono:+ die("--stereo-widen and --mono contradict each other: there is no stereo image in a 1-channel output")+ # Widening scales the side signal (L-R). Duplicating a mono track to two channels leaves+ # L == R, so the side signal is exactly zero and scaling it changes nothing: --stereo is+ # not a way in, it is a way to a file that measures mono no matter the amount asked for.+ if in_channels == 1:+ die("--stereo-widen needs a real stereo source: mono has no stereo image to widen; keep it mono or "+ "use --stereo to duplicate it, but widening needs a real stereo source")+ if in_channels > 2 and not args.downmix:+ die(f"--stereo-widen needs a stereo track; this input has {in_channels} channels. Add --downmix to fold it "+ "to stereo first (the widening then happens after the downmix), or leave the channels alone.")inputs: List[str] = ["-i", args.input]main_src = f"0:a:{args.audio_stream}"@@ -150,7 +217,7 @@ def main() -> int:if args.downmix:fx.append("pan=stereo|FL=0.707*FC+FL+0.5*BL+0.5*SL+0.5*LFE|FR=0.707*FC+FR+0.5*BR+0.5*SR+0.5*LFE")if args.voice:- fx.append(VOICE_CHAIN)+ fx.append(VOICE_LEVELS[args.voice])elif args.denoise:if not 10 <= args.denoise_strength <= 60:die(f"--denoise-strength must be 10..60 (dB of noise floor to remove), got {args.denoise_strength:g}")@@ -172,6 +239,11 @@ def main() -> int:# 1 channel: already mono; the stereo pan used to halve it (-6 dB) because c1 was silenceelif args.stereo:fx.append("aformat=channel_layouts=stereo")+ if args.stereo_widen is not None:+ # extrastereo widens by scaling the side (L-R) signal: m=1 is the input, m=3 is as wide+ # as it goes before the centre collapses. It runs after the channel layout is settled, so+ # a --downmix 5.1 source is widened on the stereo fold-down rather than on six channels.+ fx.append(f"extrastereo=m={1 + 2 * args.stereo_widen:g}")graph: List[str] = []graph.append(f"[{main_src}]{','.join(fx) if fx else 'anull'}[main]")@@ -192,13 +264,26 @@ def main() -> int:if args.duck:graph.append("[main]asplit=2[mainA][sc]")graph.append(- f"[music][sc]sidechaincompress=threshold=0.05:ratio={max(2.0, args.duck_amount / 3):.1f}:attack=20:release=400:makeup=1[ducked]"+ f"[music][sc]sidechaincompress=threshold={db_to_linear(args.duck_threshold):.6g}"+ f":ratio={max(2.0, args.duck_amount / 3):.1f}:attack={args.duck_attack:g}:release={args.duck_release:g}:makeup=1[ducked]")graph.append("[mainA][ducked]amix=inputs=2:duration=first:dropout_transition=2:normalize=0[mix]")else:graph.append("[main][music]amix=inputs=2:duration=first:dropout_transition=2:normalize=0[mix]")last = "mix"+ if args.effects:+ # A third bed, mixed in at its own level and deliberately never ducked: effects are cut+ # to the picture, so dipping them under speech would move them off their own frames.+ probe(args.effects)+ inputs += ["-i", args.effects]+ e = f"{idx}:a:0"+ idx += 1+ efx = [f"volume={args.effects_volume:g}dB", f"atrim=0:{dur:.3f}" if dur else "anull"]+ graph.append(f"[{e}]{','.join(efx)}[effects]")+ graph.append(f"[{last}][effects]amix=inputs=2:duration=first:dropout_transition=2:normalize=0[mixfx]")+ last = "mixfx"+post: List[str] = []if args.fade_in:post.append(f"afade=t=in:st=0:d={args.fade_in:g}")@@ -237,7 +322,16 @@ def main() -> int:die(f"{output} unexpectedly contains a video stream")info(f"wrote {output} ({fmt_secs(r['duration'])}, audio {a['codec']} {a['channels']}ch {a['sample_rate']}Hz"+ (", video stream-copied" if has_video and not audio_out else ", video dropped" if has_video else "") + ")")- emit(output, video=bool(has_video and not audio_out), audio_stream=args.audio_stream,+ audio_block: Dict[str, Any] = {"voice": args.voice, "stereo_widen": args.stereo_widen,+ "effects": bool(args.effects), "effects_volume": args.effects_volume if args.effects else None}+ if args.music:+ audio_block["music_volume"] = args.music_volume+ audio_block["duck"] = ({"amount_db": args.duck_amount, "threshold_db": round(args.duck_threshold, 4),+ "threshold_linear": float(f"{db_to_linear(args.duck_threshold):.6g}"),+ "ratio": round(max(2.0, args.duck_amount / 3), 1),+ "attack_ms": args.duck_attack, "release_ms": args.duck_release}+ if args.duck else None)+ emit(output, audio=audio_block, video=bool(has_video and not audio_out), audio_stream=args.audio_stream,dynamics=[f for f in (args.gate and "agate", args.compress and "acompressor", args.limit and "alimiter") if f],dropped_non_av_streams=dropped_streams)return 0diff --git a/scripts/check.py b/scripts/check.pyindex 6e0de05..008a8b0 100755--- a/scripts/check.py+++ b/scripts/check.py@@ -162,6 +162,21 @@ def main() -> int:if a:row("audio", "PASS", f"{a.get('codec')} {a.get('channels')}ch {a.get('sample_rate')}Hz", "present")+ if args.platform == "podcast":+ # Podcast rows, informational: neither can fail a delivery, both are things a+ # publisher notices after the fact. A 5.1 podcast master is the common one -- every+ # player downmixes it, none of them the same way, and the centre-heavy dialogue+ # comes back at a level nobody checked.+ ch = a.get("channels") or 0+ row("channels", "PASS" if ch in (1, 2) else "WARN", f"{ch}ch", "1 (mono) or 2 (stereo)",+ "audio.py --downmix (5.1/7.1 to stereo with the standard weights) or audio.py --mono",+ reason="podcast players downmix 5.1 unpredictably")+ if args.platform == "podcast":+ chapters = meta.get("chapters") or []+ row("chapters", "PASS" if chapters else "WARN", f"{len(chapters)}" if chapters else "none", ">= 1 chapter marker",+ "metadata.py episode.m4a --chapters chapters.txt (`TIME TITLE` per line; streams copied)",+ reason="chapter markers are optional, but a podcast app shows them as the episode's seekable table of contents")+ if a:if a.get("sample_rate") and a["sample_rate"] not in (44100, 48000):row("sample rate", "WARN", a["sample_rate"], "44100 or 48000", "loudness.py --sample-rate 48000")if not args.no_loudness and spec["lufs"] is not None:diff --git a/scripts/loudness.py b/scripts/loudness.pyindex 948c9d8..67dcbf3 100755--- a/scripts/loudness.py+++ b/scripts/loudness.py@@ -11,6 +11,7 @@ Examples:python3 loudness.py input.mp4 # -14 LUFS, -1 dBTPpython3 loudness.py podcast.wav -I -16 --tp -1.5 -o podcast_norm.wavpython3 loudness.py input.mp4 --measure-only+ python3 loudness.py music.wav --lra 7 # tighter loudness range target"""import argparseimport json@@ -155,6 +156,8 @@ def main() -> int:kind="verification", output=output, result=result,hint="raise --audio-bitrate (e.g. 256k) or deliver a lossless format (wav/flac) and let the platform encode")emit(output, result=result, dropped_non_av_streams=dropped_streams,+ measured={k: stats[k] for k in ("input_i", "input_tp", "input_lra", "input_thresh", "target_offset", "silent")},+ targets={"lufs": args.lufs, "tp": args.tp, "lra": args.lra},verification=[{"step": "loudness","ok": bool(after.get("silent")) or (abs(float(after["input_i"]) - args.lufs) <= 1.0 and float(after["input_tp"]) <= args.tp + 0.1),"lufs": float(after["input_i"]), "tp": float(after["input_tp"]), "target_lufs": args.lufs, "target_tp": args.tp}])diff --git a/scripts/render.py b/scripts/render.pyindex 78c0890..04ed04a 100755--- a/scripts/render.py+++ b/scripts/render.py@@ -24,15 +24,17 @@ Project format (all keys optional except clips):{"logo": true},{"text": "Episode 12", "position": "bottom", "start": 1, "end": 5, "fade": 0.3, "box": true}],- "audio": {"voice": true, "music": "bed.mp3", "music_volume": -16, "duck": true, "music_fade_out": 2},+ "audio": {"voice": "medium", "music": "bed.mp3", "music_volume": -16, "duck": true, "music_fade_out": 2,+ "effects": "sfx.wav", "stems": {"dialogue": 0, "music": -18, "effects": -22}},"loudness": {"lufs": -14, "tp": -1},"fit": {"duration": 60},"export": {"preset": "reels", "normalize": true}, (default for platform presets; false opts out)- "check": {"platform": "reels"}+ "check": {"platform": "reels"},+ "chapters": "chapters.txt" (or [{"at": "0:00", "title": "Intro"}, ...])}Stages run in this order: clips (cut) → join → silence → fit → captions →-graphics → overlays → audio → loudness → export → check. Missing stages are+graphics → overlays → audio → loudness → export → chapters → check. Missing stages areskipped. "brand" points caption/graphics/overlay at a brand.json (fonts,colours, logo, safe margin); {"logo": true} in overlays places the brand logo.@@ -76,6 +78,7 @@ TEMPLATE = {"loudness": {"lufs": -14, "tp": -1},"fit": None,"export": {"preset": "youtube", "normalize": True},+ "chapters": None,"check": {"platform": "youtube"},}@@ -85,7 +88,7 @@ TEMPLATE = {# untrimmed, and a mistyped stage name dropped the stage -- both reported as a success (review 9).OBJECT_KEYS: Dict[str, frozenset] = {"project": frozenset({"output", "frame", "clips", "transition", "silence", "brand", "captions",- "graphics", "overlays", "audio", "loudness", "fit", "export", "check"}),+ "graphics", "overlays", "audio", "loudness", "fit", "export", "check", "chapters"}),"clips[]": frozenset({"src", "in", "out", "speed"}),"frame": frozenset({"aspect", "width", "height", "fps"}),"transition": frozenset({"type", "duration"}),@@ -98,15 +101,20 @@ OBJECT_KEYS: Dict[str, frozenset] = {"overlays[]": frozenset({"logo", "image", "text", "position", "start", "end", "fade", "opacity","scale", "font_size", "font", "font_file", "margin", "box"}),"audio": frozenset({"music", "replace", "music_volume", "fade_in", "fade_out", "music_fade_out",- "gain", "duck_amount", "voice", "denoise", "duck", "music_loop", "stereo",- "mono", "downmix"}),+ "gain", "duck_amount", "duck_threshold", "duck_attack", "duck_release",+ "voice", "denoise", "duck", "music_loop", "stereo", "mono", "downmix",+ "stereo_widen", "effects", "effects_volume", "stems"}),+ "audio.stems": frozenset({"dialogue", "music", "effects"}),+ "chapters[]": frozenset({"at", "title"}),"loudness": frozenset({"lufs", "tp"}),"fit": frozenset({"duration", "method", "aspect", "fit", "width", "height", "fps", "smooth"}),"export": frozenset({"preset", "fit", "crf", "normalize"}),"check": frozenset({"platform"}),}# Typos difflib cannot see: a clip is trimmed with in/out, not the start/end that time a title.-NEAR_KEYS: Dict[str, Dict[str, str]] = {"clips[]": {"start": "in", "end": "out", "from": "in", "to": "out"}}+NEAR_KEYS: Dict[str, Dict[str, str]] = {"clips[]": {"start": "in", "end": "out", "from": "in", "to": "out"},+ "audio.stems": {"voice": "dialogue", "speech": "dialogue", "sfx": "effects", "bed": "music"},+ "chapters[]": {"start": "at", "time": "at", "name": "title"}}def check_keys(obj: Any, schema: str, label: str) -> None:@@ -126,6 +134,14 @@ def validate_project(proj: Dict[str, Any]) -> None:check_keys(proj, "project", "project")for name in ("frame", "transition", "silence", "captions", "audio", "loudness", "fit", "export", "check"):check_keys(proj.get(name), name, name)+ check_keys((proj.get("audio") or {}).get("stems"), "audio.stems", "audio.stems")+ if isinstance(proj.get("chapters"), list):+ # Every other project error is raised here, before the first ffmpeg call; a chapter typo+ # found inside the last stage costs a whole render and leaves an unchaptered file behind.+ for i, item in enumerate(proj["chapters"]):+ check_keys(item, "chapters[]", f"chapters[{i}]")+ if not isinstance(item, dict) or item.get("at") is None or not str(item.get("title") or "").strip():+ die(f'chapters[{i}]: needs {{"at": TIME, "title": STR}}')for name in ("clips", "graphics", "overlays"):items = proj.get(name)if isinstance(items, list):@@ -287,6 +303,9 @@ def main() -> int:p = str(p)return p if os.path.isabs(p) else str(base / p)+ if isinstance(proj.get("chapters"), str) and not os.path.exists(rel(proj["chapters"])):+ die(f"chapters file not found: {rel(proj['chapters'])}")+clips = proj.get("clips") or []if not clips:die("project.clips is empty")@@ -475,17 +494,33 @@ def main() -> int:return 0# ---- audio- au = proj.get("audio")+ au = dict(proj.get("audio") or {})if au:+ # "stems": one level per element of the mix, the way a mixing desk names them. Each maps+ # to the flag that already exists (dialogue = the main track's gain, music = the bed's+ # level, effects = the third file's level), so a stems block is a vocabulary, not a+ # second code path -- and an explicit flag next to it wins, since it is the more specific+ # statement of the same thing.+ stems = au.pop("stems", None) or {}+ if stems.get("effects") is not None and not au.get("effects"):+ die('audio.stems.effects sets the level of "audio": {"effects": "sfx.wav"}, which this project does not have')+ if stems.get("music") is not None and not au.get("music"):+ die('audio.stems.music sets the level of "audio": {"music": "bed.mp3"}, which this project does not have')+ for stem, key in (("dialogue", "gain"), ("music", "music_volume"), ("effects", "effects_volume")):+ if stems.get(stem) is not None:+ au.setdefault(key, stems[stem])nxt = str(work / "audio.mp4")argv = [current, "-o", nxt]- for k, flag in (("music", "--music"), ("replace", "--replace")):+ for k, flag in (("music", "--music"), ("replace", "--replace"), ("effects", "--effects")):if au.get(k):argv += [flag, rel(au[k])]- for k, flag in (("music_volume", "--music-volume"), ("fade_in", "--fade-in"), ("fade_out", "--fade-out"), ("music_fade_out", "--music-fade-out"), ("gain", "--gain"), ("duck_amount", "--duck-amount")):+ for k, flag in (("music_volume", "--music-volume"), ("effects_volume", "--effects-volume"), ("fade_in", "--fade-in"), ("fade_out", "--fade-out"), ("music_fade_out", "--music-fade-out"), ("gain", "--gain"), ("duck_amount", "--duck-amount"), ("duck_threshold", "--duck-threshold"), ("duck_attack", "--duck-attack"), ("duck_release", "--duck-release"), ("stereo_widen", "--stereo-widen")):if au.get(k) is not None:argv += [flag, str(au[k])]- for k, flag in (("voice", "--voice"), ("denoise", "--denoise"), ("duck", "--duck"), ("music_loop", "--music-loop"), ("stereo", "--stereo"), ("mono", "--mono"), ("downmix", "--downmix")):+ # "voice": true is the medium chain; "voice": "light"|"medium"|"strong" names one+ if au.get("voice") is not None and au.get("voice") is not False:+ argv += ["--voice"] + ([] if au["voice"] is True else [str(au["voice"])])+ for k, flag in (("denoise", "--denoise"), ("duck", "--duck"), ("music_loop", "--music-loop"), ("stereo", "--stereo"), ("mono", "--mono"), ("downmix", "--downmix")):if au.get(k):argv.append(flag)sh("audio.py", *argv)@@ -536,6 +571,24 @@ def main() -> int:info(("[dry-run] would copy" if STATE.dry_run else "copied") + f" final stage to {output}")current = output+ # ---- chapters (metadata.py on the delivered file: streams copied, markers written)+ ch = proj.get("chapters")+ if ch:+ # Planned exactly like the audio stage: the metadata.py command names the export's output,+ # which a dry run has not written either. The plan is the run, so --dry-run shows the+ # command and lists the stage (the child's own --dry-run prints rather than writes).+ if isinstance(ch, list):+ chapter_file = str(work / "chapters.txt")+ lines = [f"{entry['at']} {entry['title']}" for entry in ch]+ Path(chapter_file).write_text("\n".join(lines) + "\n", encoding="utf-8")+ else:+ chapter_file = rel(ch)+ tagged = str(work / ("chapters" + Path(output).suffix))+ sh("metadata.py", output, "--chapters", chapter_file, "-o", tagged)+ if not STATE.dry_run:+ place_output(tagged, output)+ stages_done.append("chapters")+# ---- checkck = proj.get("check")check_result = Nonediff --git a/tests/fixtures/mcp_tools.json b/tests/fixtures/mcp_tools.jsonindex cd5d436..b798447 100644--- a/tests/fixtures/mcp_tools.json+++ b/tests/fixtures/mcp_tools.json@@ -18,6 +18,11 @@"dry_run","duck","duck_amount",+ "duck_attack",+ "duck_release",+ "duck_threshold",+ "effects",+ "effects_volume","fade_in","fade_out","fast",@@ -47,6 +52,7 @@"progress","replace","stereo",+ "stereo_widen","timeout","voice"],diff --git a/tests/test_all.py b/tests/test_all.pyindex 01d9617..cfbe8f0 100644--- a/tests/test_all.py+++ b/tests/test_all.py@@ -2155,6 +2155,287 @@ class FFmpegSkillTests(unittest.TestCase):self.assertEqual(m3["audio"]["channels"], 2)self.assertClose(m3["duration"], 12.0, 0.2)+ # ------------------------------------------------------------------ 1.13: the audio bed+ def _audio_filters(self, *args):+ """The filter graph audio.py plans, from --dry-run --json (no encode)."""+ data = json.loads(script("audio.py", *args, "--dry-run", "--json").stdout)+ cmd = next(c for c in data["commands"] if "-filter_complex" in c)+ return cmd.split("-filter_complex ", 1)[1].split(" -map", 1)[0].strip("'"), data++ def test_audio_voice_levels_are_three_different_chains(self):+ """1.13: --voice takes a strength. A bare --voice must stay byte-identical to the chain+ it produced before the flag took a value (every existing call and MCP request sends it+ bare), and each named level must actually be a different chain -- a preset that is only+ a different word in the help is worse than no preset."""+ out = OUT / "voice_level.mp4"+ bare, _ = self._audio_filters(self.src, "--voice", "-o", out)+ self.assertEqual(bare, "[0:a:0]highpass=f=80,deesser=i=0.4,afftdn=nf=-25:tn=1,"+ "acompressor=threshold=-18dB:ratio=3:attack=5:release=80:makeup=2[main];"+ "[main]apad,atrim=0:12.000[out]",+ "a bare --voice is the 1.12 chain, unchanged")+ chains = {}+ for level in ("light", "medium", "strong"):+ chains[level], data = self._audio_filters(self.src, "--voice", level, "-o", out)+ self.assertEqual(data["audio"]["voice"], level)+ self.assertEqual(chains["medium"], bare, "bare --voice == --voice medium")+ self.assertEqual(len(set(chains.values())), 3, "each level is a different filter chain")+ self.assertNotIn("deesser", chains["light"])+ self.assertNotIn("afftdn", chains["light"], "light leaves the noise floor alone")+ self.assertIn("acompressor=threshold=-18dB:ratio=2", chains["light"])+ self.assertIn("deesser=i=0.6", chains["strong"])+ self.assertIn("alimiter=limit=0.891251:level=disabled", chains["strong"], "strong ends in a soft limiter")+ self.assertTrue(chains["strong"].count("acompressor") == 2, "strong compresses twice")+ # and each one really encodes+ for level in ("light", "strong"):+ real = OUT / f"voice_{level}.m4a"+ script("audio.py", self.mic, "--voice", level, "-o", real)+ self.assertGreater(probe(str(real))["duration"], 1.0)++ def test_audio_duck_parameters_reach_the_sidechain_filter(self):+ """1.13: the ducking knobs are sayable. The default command line must not move (the+ threshold flag speaks dBFS, the filter takes the same 0.05 linear it always did), and+ every flag must land in the filter string and in --json's audio block."""+ out = OUT / "duck_params.mp4"+ default, data = self._audio_filters(self.src, "--music", self.long_ref, "--duck", "-o", out)+ self.assertIn("sidechaincompress=threshold=0.05:ratio=4.0:attack=20:release=400:makeup=1", default,+ "the default duck filter is unchanged")+ self.assertEqual(data["audio"]["duck"]["threshold_linear"], 0.05)+ tuned, data = self._audio_filters(self.src, "--music", self.long_ref, "--duck", "--duck-amount", "18",+ "--duck-threshold", "-30", "--duck-attack", "5", "--duck-release", "250", "-o", out)+ self.assertIn("sidechaincompress=threshold=0.0316228:ratio=6.0:attack=5:release=250:makeup=1", tuned)+ self.assertEqual(data["audio"]["duck"], {"amount_db": 18.0, "threshold_db": -30.0, "threshold_linear": 0.0316228,+ "ratio": 6.0, "attack_ms": 5.0, "release_ms": 250.0})+ # no --duck: the block says so rather than describing settings nothing used+ _, data = self._audio_filters(self.src, "--music", self.long_ref, "-o", out)+ self.assertIsNone(data["audio"]["duck"])+ # out of range is refused before ffmpeg sees it+ doc = json.loads(script("audio.py", self.src, "--music", self.long_ref, "--duck", "--duck-release", "99999",+ "-o", out, "--json", expect_fail=True).stdout)+ self.assertEqual(doc["error"]["kind"], "input")+ self.assertIn("--duck-release", doc["error"]["message"])++ def _side_peak_db(self, path):+ """Peak level of the side signal (L-R) in dBFS; -inf (returned as -120) means the two+ channels are identical, i.e. the file has no stereo image at all."""+ proc = sh("ffmpeg", "-hide_banner", "-nostdin", "-i", str(path), "-af",+ "pan=mono|c0=c0-c1,astats=measure_overall=Peak_level:measure_perchannel=none", "-f", "null", "-")+ peak = re.search(r"Peak level dB: (-?[0-9.]+|-inf)", proc.stderr)+ self.assertIsNotNone(peak, proc.stderr[-400:])+ return -120.0 if peak.group(1) == "-inf" else float(peak.group(1))++ def test_audio_stereo_widen_needs_a_real_stereo_source(self):+ """1.13: widening scales the side signal (L-R). Duplicating a mono track to two channels+ leaves L == R, so the side signal is exactly zero and scaling it changes nothing -- the+ file comes out bit-identical and still mono. Mono is refused outright, --stereo included,+ rather than pointed at a workaround that cannot work."""+ mono = OUT / "widen_mono.wav"+ sh("ffmpeg", "-y", "-hide_banner", "-loglevel", "error", "-i", str(self.mic), "-ac", "1", str(mono))+ out = OUT / "widened.wav"+ for extra in ([], ["--stereo"]):+ doc = json.loads(script("audio.py", mono, "--stereo-widen", "0.5", *extra, "-o", out,+ "--json", expect_fail=True).stdout)+ self.assertEqual(doc["error"]["kind"], "input", extra)+ self.assertIn("real stereo source", doc["error"]["message"], extra)+ # a real stereo source -- different content per channel -- is widened, and the widening+ # is audible in the only place it can be: the side signal+ stereo = OUT / "widen_stereo.wav"+ sh("ffmpeg", "-y", "-hide_banner", "-loglevel", "error", "-f", "lavfi", "-i",+ "aevalsrc='0.15*sin(2*PI*300*t)|0.1*sin(2*PI*900*t)':s=48000:c=stereo", "-t", "4", str(stereo))+ before = self._side_peak_db(stereo)+ graph, data = self._audio_filters(stereo, "--stereo-widen", "1", "-o", out)+ self.assertIn("extrastereo=m=3", graph)+ self.assertEqual(data["audio"]["stereo_widen"], 1.0)+ script("audio.py", stereo, "--stereo-widen", "1", "-o", out)+ after = self._side_peak_db(out)+ self.assertEqual(probe(str(out))["audio"]["channels"], 2)+ self.assertGreater(after, -60.0, "L-R must not be silent after widening: that is the whole effect")+ self.assertGreater(after, before + 3.0, "the side signal is louder than it was")+ doc = json.loads(script("audio.py", stereo, "--stereo-widen", "4", "-o", out, "--json", expect_fail=True).stdout)+ self.assertEqual(doc["error"]["kind"], "input")++ def test_audio_stereo_widen_refuses_more_than_two_channels_without_downmix(self):+ """1.13: extrastereo is a stereo-only filter, so libavfilter would auto-insert a downmix+ and throw four channels of a 5.1 master away with no flag and no warning. Losing channels+ is the caller's decision (--downmix), and with it the widening runs on the fold-down."""+ out = OUT / "widen_surround.m4a"+ doc = json.loads(script("audio.py", self.surround, "--stereo-widen", "0.5", "-o", out,+ "--json", expect_fail=True).stdout)+ self.assertEqual(doc["error"]["kind"], "input")+ self.assertIn("--downmix", doc["error"]["message"])+ self.assertIn("6 channels", doc["error"]["message"])+ graph, _ = self._audio_filters(self.surround, "--stereo-widen", "0.5", "--downmix", "-o", out)+ self.assertLess(graph.index("pan=stereo"), graph.index("extrastereo="), "widen runs after the downmix")+ data = json.loads(script("audio.py", self.surround, "--stereo-widen", "0.5", "--downmix",+ "-o", out, "--json").stdout)+ self.assertEqual(data["probe"]["audio"]["channels"], 2)+ self.assertEqual(data["probe"]["audio"]["channel_layout"], "stereo")++ def test_audio_duck_parameters_need_their_switch_and_a_bed(self):+ """1.13: --duck-release 250 that silently delivers the default 400 ms is invisible to the+ caller, and --duck with no --music has nothing to duck. Both are refusals naming the+ missing flag, the same rule the typed dynamics parameters already follow."""+ out = OUT / "duck_guard.mp4"+ for flag, value in (("--duck-threshold", "-40"), ("--duck-attack", "5"), ("--duck-release", "250"), ("--duck-amount", "18")):+ doc = json.loads(script("audio.py", self.src, "--music", self.long_ref, flag, value, "-o", out,+ "--json", expect_fail=True).stdout)+ self.assertEqual(doc["error"]["kind"], "input", flag)+ self.assertIn(flag, doc["error"]["message"])+ self.assertIn("--duck", doc["error"]["message"])+ doc = json.loads(script("audio.py", self.src, "--duck", "--duck-release", "250", "-o", out,+ "--json", expect_fail=True).stdout)+ self.assertEqual(doc["error"]["kind"], "input")+ self.assertIn("--music", doc["error"]["message"])+ # the combination that means something still runs+ graph, _ = self._audio_filters(self.src, "--music", self.long_ref, "--duck", "--duck-release", "250", "-o", out)+ self.assertIn("release=250", graph)++ def test_audio_effects_bed_is_mixed_and_never_ducked(self):+ """1.13: --effects is a third bed at its own level. It is mixed after the ducked music,+ outside the sidechain, because effects are cut to the picture."""+ out = OUT / "effects.mp4"+ graph, data = self._audio_filters(self.src, "--music", self.long_ref, "--duck",+ "--effects", self.mic, "--effects-volume", "-20", "-o", out)+ self.assertIn("volume=-20dB", graph)+ self.assertIn("[effects]", graph)+ self.assertGreater(graph.index("[effects]"), graph.index("sidechaincompress"),+ "the effects bed is mixed after the duck, so the sidechain never sees it")+ self.assertTrue(data["audio"]["effects"])+ script("audio.py", self.src, "--effects", self.mic, "--effects-volume", "-20", "-o", out)+ self.assertClose(probe(str(out))["duration"], 12.0, 0.2)++ def test_loudness_json_reports_the_measurement_and_the_targets(self):+ """1.13: --json carries the input's own loudnorm measurement (including its loudness+ range) and the targets that were asked for, next to the result measured off the written+ file -- so a caller can see what it started from without a second --measure-only run.++ There is deliberately no speech gate here: loudnorm's EBU R128 integrated measurement+ already applies the -70 LUFS absolute and -10 LU relative gates, so gating on+ silencedetect spans moves the result by a fraction of check.py's own tolerance (see+ references/gotchas.md#loudness-and-ambience)."""+ out = OUT / "loud_targets.m4a"+ data = json.loads(script("loudness.py", self.mic, "-I", "-16", "--tp", "-1.5", "--lra", "9",+ "-o", out, "--json").stdout)+ self.assertEqual(data["targets"], {"lufs": -16.0, "tp": -1.5, "lra": 9.0})+ for key in ("input_i", "input_tp", "input_lra", "input_thresh", "target_offset"):+ self.assertIn(key, data["measured"], key)+ self.assertIn(key, data["result"], key)+ measured_only = json.loads(script("loudness.py", self.mic, "--measure-only", "--json").stdout)["measured"]+ self.assertEqual(data["measured"]["input_i"], measured_only["input_i"],+ "the reported measurement is the same pass-1 measurement --measure-only prints")+ self.assertClose(float(data["result"]["input_i"]), -16.0, 1.0)+ self.assertNotIn("dialogue", script("loudness.py", "--help").stdout,+ "the speech gate was withdrawn; the flag must not come back without the evidence")++ def test_check_podcast_reports_chapters_and_channel_count(self):+ """1.13: two informational podcast rows. Neither may FAIL a delivery, and neither may+ appear for a platform that does not care."""+ data = json.loads(script("check.py", self.mic, "--platform", "podcast", "--no-loudness", "--json").stdout)+ rows = {r["check"]: r for r in data["checks"]}+ self.assertEqual(rows["chapters"]["status"], "WARN")+ self.assertEqual(rows["chapters"]["value"], "none")+ self.assertIn("metadata.py", rows["chapters"]["fix"])+ self.assertEqual(rows["channels"]["status"], "PASS", "mono is fine for a podcast")+ self.assertTrue(data["ok"], "informational rows never fail the delivery")+ # after metadata.py the chapters row passes+ chapters = OUT / "podcast_chapters.txt"+ chapters.write_text("0:00 Intro\n0:04 Body\n", encoding="utf-8")+ tagged = OUT / "podcast_tagged.m4a"+ script("audio.py", self.mic, "-o", OUT / "podcast.m4a")+ script("metadata.py", OUT / "podcast.m4a", "--chapters", chapters, "-o", tagged)+ rows = {r["check"]: r for r in json.loads(script("check.py", tagged, "--platform", "podcast", "--no-loudness", "--json").stdout)["checks"]}+ self.assertEqual(rows["chapters"]["status"], "PASS")+ self.assertEqual(rows["chapters"]["value"], "2")+ # 5.1 warns, with the reason a publisher needs+ rows = {r["check"]: r for r in json.loads(script("check.py", self.surround, "--platform", "podcast", "--no-loudness", "--json").stdout)["checks"]}+ self.assertEqual(rows["channels"]["status"], "WARN")+ self.assertIn("downmix", rows["channels"]["reason"])+ # absent for every other platform+ for platform in ("youtube", "reels"):+ proc = subprocess.run([sys.executable, str(SCRIPTS / "check.py"), str(self.src), "--platform", platform,+ "--no-loudness", "--json"], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)+ names = {r["check"] for r in json.loads(proc.stdout)["checks"]}+ self.assertNotIn("chapters", names, platform)+ self.assertNotIn("channels", names, platform)++ def test_render_audio_stems_and_chapters_stage(self):+ """1.13: stems are a vocabulary over the flags that already exist, and the chapters stage+ puts the markers in the file that ships (metadata.py, streams copied)."""+ proj = OUT / "project_stems.json"+ proj.write_text(json.dumps({+ "output": "render_stems.mp4",+ "clips": [{"src": "source.mp4"}],+ "audio": {"music": "lavmic.wav", "effects": "lavmic.wav", "duck": True, "voice": "light",+ "stems": {"dialogue": -2, "music": -18, "effects": -24}},+ "export": {"preset": "youtube", "normalize": False},+ "chapters": [{"at": "0:00", "title": "Intro"}, {"at": 3, "title": "Body"}],+ }), encoding="utf-8")+ data = json.loads(script("render.py", proj, "--dry-run", "--json").stdout)+ graph = next(c for c in data["commands"] if "sidechaincompress" in c)+ self.assertIn("volume=-2dB", graph, "stems.dialogue is the main track's gain")+ self.assertIn("volume=-18dB", graph, "stems.music is the bed's level")+ self.assertIn("volume=-24dB", graph, "stems.effects is the effects bed's level")+ self.assertIn("highpass=f=80,acompressor=threshold=-18dB:ratio=2", graph, '"voice": "light" picks the light chain')+ # the chapters stage is planned like every other stage: the dry run names the same+ # metadata.py command against the same delivered file, and lists the stage. A plan that+ # hides a stage is a plan the user cannot approve.+ planned = json.loads(script("render.py", proj, "--dry-run", "--json").stdout)+ real = json.loads(script("render.py", proj, "--fast", "--json").stdout)+ self.assertIn("chapters", planned["stages"])+ self.assertEqual(planned["stages"], real["stages"], "the plan lists the stages the run does")+ for doc in (planned, real):+ chapter_cmds = [c for c in doc["commands"] if "-map_chapters 1" in c]+ self.assertEqual(len(chapter_cmds), 1, doc["stages"])+ self.assertIn(str(OUT / "render_stems.mp4"), chapter_cmds[0], "planned against the delivered file")+ data = real+ written = probe(str(OUT / "render_stems.mp4")).get("chapters") or []+ self.assertEqual([c["title"] for c in written], ["Intro", "Body"])+ self.assertClose(written[1]["start"], 3.0, 0.05)+ # a chapters file path works the same way+ proj2 = OUT / "project_chapters_file.json"+ (OUT / "render_chapters.txt").write_text("0:00 One\n0:05 Two\n", encoding="utf-8")+ proj2.write_text(json.dumps({+ "output": "render_chapters.mp4", "clips": [{"src": "source.mp4"}],+ "export": {"preset": "youtube", "normalize": False}, "chapters": "render_chapters.txt",+ }), encoding="utf-8")+ script("render.py", proj2, "--fast", "--json")+ self.assertEqual(len(probe(str(OUT / "render_chapters.mp4")).get("chapters") or []), 2)+ # a stems level with no effects file, and a misspelled stem, are refusals by name+ proj3 = OUT / "project_stems_bad.json"+ proj3.write_text(json.dumps({"output": "render_stems_bad.mp4", "clips": [{"src": "source.mp4"}],+ "audio": {"stems": {"effects": -20}}}), encoding="utf-8")+ doc = json.loads(script("render.py", proj3, "--dry-run", "--json", expect_fail=True).stdout)+ self.assertEqual(doc["error"]["kind"], "input")+ self.assertIn("effects", doc["error"]["message"])+ proj3.write_text(json.dumps({"output": "render_stems_bad.mp4", "clips": [{"src": "source.mp4"}],+ "audio": {"stems": {"voice": -20}}}), encoding="utf-8")+ doc = json.loads(script("render.py", proj3, "--dry-run", "--json", expect_fail=True).stdout)+ self.assertIn("dialogue", doc["error"]["message"], "the nearest valid stem is named")+ # a music level with no music file is refused the same way an effects level is+ proj3.write_text(json.dumps({"output": "render_stems_bad.mp4", "clips": [{"src": "source.mp4"}],+ "audio": {"stems": {"music": -18}}}), encoding="utf-8")+ doc = json.loads(script("render.py", proj3, "--dry-run", "--json", expect_fail=True).stdout)+ self.assertEqual(doc["error"]["kind"], "input")+ self.assertIn("music", doc["error"]["message"])++ def test_render_chapters_are_validated_before_any_stage_runs(self):+ """1.13: every other project error is raised before the first ffmpeg call. A bad chapter+ entry used to surface inside the last stage, after place_output had already delivered an+ unchaptered file and reported the render as done."""+ out = OUT / "render_bad_chapters.mp4"+ proj = OUT / "project_bad_chapters.json"+ for chapters, needle in (([{"title": "A"}], "at"), ([{"at": "0:00"}], "title"),+ ("no_such_chapters.txt", "not found")):+ if out.exists():+ out.unlink()+ proj.write_text(json.dumps({"output": "render_bad_chapters.mp4", "clips": [{"src": "source.mp4"}],+ "export": {"preset": "youtube", "normalize": False},+ "chapters": chapters}), encoding="utf-8")+ doc = json.loads(script("render.py", proj, "--fast", "--json", expect_fail=True).stdout)+ self.assertEqual(doc["error"]["kind"], "input", chapters)+ self.assertIn(needle, doc["error"]["message"], chapters)+ self.assertEqual(doc.get("commands") or [], [], "refused before the first ffmpeg call")+ self.assertFalse(out.exists(), "no half-done delivery is left behind")+def test_sync_fine_resolution_and_drift(self):data = json.loads(script("sync.py", self.long_ref, self.long_drift, "--fix-drift", "--json").stdout)self.assertClose(data["offset_seconds"], 1.2, 0.01, "offset extrapolated to t=0 at 1 ms resolution")