Skip to content

Local video editor for coding agents: 42 FFmpeg tools with a machine-readable contract and an MCP server, for Claude Code, Cursor and Codex. Cut, captions, reframe, loudness, platform exports. No cloud, no API keys.

feat: 1.16.0 — long-form delivery (audiogram, auto chapters, multi-language subtitle tracks, phrase-aware captions) (#231)

claude[bot]1696f328b709
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 24b51e1..920cad7 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -4,7 +4,100 @@
## Unreleased
-(nothing yet)
+### Added
+
+- **Audiogram: `waveform.py --image` and `render.py --template audiogram`.** The visualisation
+ over a still plate, which is what turns a podcast episode into something postable.
+ `--image PATH` (a local file), `--image-fit cover|contain|blur`, `--position
+ bottom|centre|top|strip`, `--vis-height FRAC`, `--opacity`, `--platform NAME` (the frame from
+ the delivery table; a destination with no frame is refused), `--title TEXT` (drawn through
+ `graphics.py`) and `--srt`/`--text` (burnt by `caption.py` afterwards, so neither code path is
+ re-implemented). Result key `audiogram`. Nothing is fetched and no cover art is ever invented:
+ give an image or a colour. **No new tool — the tool count stays 42**; `docs/design-decisions.md`
+ records why an `audiogram.py` would have been a second spelling of `waveform.py` and, under the
+ 1.x guarantee, permanent surface.
+- **`metadata.py --auto-chapters`: chapter markers proposed from measured structure.** Pauses
+ (silencedetect) and scene changes (scdet) become candidates; a scene cut within 1 s of a
+ silence end merges into one `silence+scene` marker. `--min-chapter` (default 60),
+ `--max-chapters`, `--from silence|scenes|both`, `--silence-threshold`/`--silence-min`,
+ `--scene-threshold`, `--chapters-out FILE` (this tool's own `--chapters` format, so the titles
+ can be edited and fed back) and `--description-out FILE` (the YouTube `00:00 Chapter 1` block).
+ Result key `auto_chapters`, with each marker's evidence. **Every title is `Chapter N` and the
+ result says `"titles": "placeholder"`** — the skill proposes where a chapter starts, it cannot
+ know what is in one; naming them is the caller's job. Output is still `-c copy`; two detectors
+ mean two decodes, which `--help` and `notes` both say.
+- **Several language-tagged subtitle tracks in one `caption.py --mode mux`.** `--srt` is
+ repeatable and each file may carry a `:lang` suffix (`--srt en.srt:en --srt ja.srt:ja`). The
+ suffix splits on the last colon and only when the tail is a BCP-47-shaped code and the whole
+ token is not itself a file, so `C:\subs\en.srt` and a file named `a:b.srt` survive.
+ `--track-title` (a frozen display-name table by default — data, never a translation) and
+ `--default-track LANG`. Result keys `tracks` and `subtitle_tracks`. Empirically (ffmpeg 6.1),
+ `.mp4`/`.mov` hold several `mov_text` tracks but drop a two-letter language code without a
+ word, so the code is converted to ISO-639-2 (`en` → `eng`); Matroska stores what it is given,
+ and past two tracks in an MPEG-4 container the result recommends `.mkv` in `notes`. The skill
+ never translates and never generates a second language.
+- **`check.py`: an informational `subtitles` row on every platform.** `PASS` when every soft
+ subtitle stream carries a language tag, `WARN` when one does not or when there are none. Like
+ the podcast `channels`/`chapters` rows it is never counted in `failed`.
+
+### Fixed
+
+- **The audiogram ignored `--fps` / `--platform`.** A looped still is fed to ffmpeg at 25 fps
+ unless told otherwise, and `overlay` takes its rate from the first input, so
+ `--platform tiktok` announced 30 fps and wrote a 25 fps file (the colour-plate path was never
+ affected: `color=` carries its own `r=`). The still now gets `-framerate`, and the frame rate
+ joined the frame size and duration in what `audiogram.verified` actually checks.
+- **`--mode mux` marked a track `default` that nobody asked for.** With two or more new subtitle
+ streams and no `--default-track`, ffmpeg flags the first one itself — the opposite of what the
+ flag promises, and `tracks[].default` then described a file that did not exist. Every
+ disposition is stated explicitly now (`default` for the chosen track, `0` for the rest).
+ MPEG-4 cannot express "no default subtitle track" at all — it always enables its first one —
+ so there the track is *reported* `default: true` with a note, because the result document
+ describes the file, not the request.
+- **`audiogram.verified` was `true` under `--dry-run`**, where nothing had been rendered to
+ verify, while the common top-level `verified` said `false` for the same run.
+- **`--image` that ffmpeg cannot decode** is refused with `kind: input` naming the file, before
+ any encode starts, instead of surfacing as a raw ffmpeg failure.
+- **A malformed `:lang` suffix** (`--srt en.srt:zzzz`) is reported as a bad language code naming
+ the token, not as a missing file called `en.srt:zzzz`.
+- **`から`, `まで` and `より` are matched as whole words.** They had been left in the
+ *character* table of Japanese particles, which made `か`, `ら`, `ま`, `で`, `よ` and `り`
+ one-character particles of their own — none of them is — so a break before `か` was forbidden
+ and a break after it preferred.
+- **MPEG-4 subtitle track titles are no longer claimed.** `-metadata:s:s:N title=` is dropped by
+ the MPEG-4 muxer, so `tracks[].title` reported a name the file did not carry; it is `null`
+ there now, with a note saying `.mkv` keeps the names.
+- `metadata.py --auto-chapters`' "no chapters found" hint no longer suggests the value already
+ in use (`--min-chapter 1` was answered with "try `--min-chapter 1`").
+- `graphics.py --template sticker` wraps its label to the chip's own width rather than the
+ frame's, so a long `--text` cannot overflow the plate it is drawn on.
+
+### Changed
+
+- **`caption.py` and `graphics.py` wrap phrase-aware by default (`--wrap measured` restores
+ 1.15.1).** Four rules, all penalties over break positions that already fit, so no line is
+ widened and the line count never changes: never inside a word or on the wrong side of a hyphen;
+ no line that is a lone digit, one or two punctuation characters or a single kana, checked at
+ every boundary rather than only the last; Japanese/Chinese breaks preferred after `。、!?」』)`
+ and after a particle — a particle is enclitic, so kinsoku keeps it with the word before it and a
+ break *before* one is forbidden — discouraged between a kanji stem and its okurigana and
+ forbidden before a small kana; and an article or preposition kept with the phrase it governs, by
+ preferring the break before it and penalising the break after it. **The `rebalanced` count in
+ the `cues:` line can differ for an unchanged input**, and a cue whose break moves is the point
+ of the release — the text itself is never rewritten, shortened or translated. graphics.py's hook
+ card, meme lines and sticker chip are now wrapped to the frame's safe width instead of running
+ off the edge; a label that already fits is untouched.
+ Eval 16's two open cues come out whole: `dl1` breaks as `A third line / the tool times for me`
+ (1.15: `A third line the / tool times for me`) and `dl3` as `自動でタイミングが / 決まる行`
+ (1.15: `自動でタイミングが決ま / る行`). `--wrap measured` reproduces the old splits.
+- `layout_cues` wraps each cue once instead of three times. The greedy fill is identical for
+ every mode, so `wrap_variants()` does it once and repeats only the post-passes, which is what
+ `rebalanced` and `phrase_breaks` need to be counted against.
+- The caption breaker moved from `caption.py` into `_common/text.py`, and the two structure
+ detectors (`silence.detect`, `scenes.detect_scenes`) into `_common/probe.py`, so
+ `metadata.py --auto-chapters` measures without any tool in `scripts/` importing a sibling tool.
+ Both moves are byte-for-byte; `caption.wrap_text`, `silence.detect` and `scenes.detect_scenes`
+ still resolve where they always did.
## 1.15.1
diff --git a/README.md b/README.md
index cdf777b..21666b5 100644
--- a/README.md
+++ b/README.md
@@ -213,13 +213,13 @@ These are the rules the skill file gives the agent and the code enforces.
| `reverse.py` | Reverse playback (video and, unless `--no-audio`, audio) |
| `stabilize.py` | Two-pass motion stabilisation (`vidstabdetect`/`vidstabtransform`) |
| `sequence.py` | Numbered (`frame_%04d.png`) or glob-matched still images into a video |
-| `waveform.py` | Render an audio track as a waveform or spectrum visualization video (`showwaves`/`showspectrum`) — for audio-only inputs with no picture worth showing |
+| `waveform.py` | Render an audio track as a waveform or spectrum visualization video (`showwaves`/`showspectrum`) — for audio-only inputs with no picture worth showing; `--image` puts the visualisation over a still plate (an audiogram), with `--platform`, `--title` and burnt-in captions |
| `freeze.py` | Hold a frame for N seconds (`--at`, `--hold`, `--mode insert/extend`) — an end-card hold or a comedic beat |
| `pad.py` | Add black/silent padding at the start and/or end of the timeline (`--start`, `--end`) — distinct from `fit.py --fit pad`'s per-frame letterbox bars |
| `speedramp.py` | Step through different constant speeds across a clip via `--segment START-END:FACTOR` (repeatable) — distinct from `fit.py`'s single whole-clip speed factor |
| `loop.py` | Repeat a clip `--times` N or to a target `--duration` — for background loops and filling a fixed slot length |
| `broll.py` | Cut away to a B-roll clip over the A-roll for a window (`--insert B --at T --duration D`, repeatable) and come back; A's length and audio untouched by default |
-| `metadata.py` | Write container chapter markers from a `TIME TITLE` text file and title/artist/comment tags, every stream copied bit for bit |
+| `metadata.py` | Write container chapter markers from a `TIME TITLE` text file and title/artist/comment tags, every stream copied bit for bit; `--auto-chapters` proposes the markers from measured pauses and scene cuts and names them `Chapter N` for you to rename |
| `grid.py` | Composite `--cols`x`--rows` clips into one grid, each cell letterboxed and labelled with its filename by default (`--label none` to skip) |
**Audio**
@@ -234,7 +234,7 @@ These are the rules the skill file gives the agent and the code enforces.
| Tool | What it does |
|---|---|
-| `caption.py` | Burn SRT/ASS with font, size, colour, outline, position; build SRT from timed plain text; wraps to the safe area by measured width with `--max-lines`/`--min-duration`/`--offset`; picks a font by script for non-Latin text (`--lang`); animated and word-by-word karaoke timed to the speech energy or real word timings; optional local transcription |
+| `caption.py` | Burn SRT/ASS with font, size, colour, outline, position; build SRT from timed plain text; wraps to the safe area with a phrase-aware breaker (`--wrap phrase|measured`) and `--max-lines`/`--min-duration`/`--offset`; `--mode mux` takes a repeated `--srt file:lang` for several language-tagged, toggleable tracks in one file; picks a font by script for non-Latin text (`--lang`); animated and word-by-word karaoke timed to the speech energy or real word timings; optional local transcription |
| `overlay.py` | Logos, watermarks and titles with position, time range, opacity, fades; `--platform NAME` keeps them clear of that destination's UI; `--video` for picture-in-picture, `--chromakey` for green-screen compositing |
| `graphics.py` | Lower-thirds, title cards, chapter chips, progress bars, countdowns, corner bugs, social stickers, opening hook cards and meme captions drawn by FFmpeg from a brand kit; `--platform NAME` keeps them inside that destination's safe zone; `--text-render` routes shaping scripts through libass and `--emoji-assets` composites colour emoji |
| `color.py` | HDR10 / HLG / Dolby Vision → SDR BT.709 tone mapping, DV layer stripping, 3D LUT (.cube), colour-tag rewriting, typed primary correction (exposure/contrast/saturation/gamma/white balance/lift-gain/levels/curves) |
@@ -361,6 +361,8 @@ The short list for humans. The agent-facing version, with the reasoning, is the
- **Loudness targets.** −14 LUFS / −1 dBTP for YouTube and social platforms (the `loudness.py` default), `-I -16 --tp -1.5` for podcasts, `-I -23` for broadcast. A clip measured at −40 LUFS or below is room tone, not content; raising it raises the noise. Check true peak as well as LUFS: `check.py file --platform podcast` measures both.
- **Frame changes first, text second.** Captions and overlays burned before a crop or resize end up off-frame. Reframe, then caption.
- **Cropping 16:9 to 9:16 discards 70 % of the width.** `fit.py --fit crop` centres by default; pass `--crop-x`/`--crop-y` toward the subject, or pad with `--fit pad --pad-fill blur`. Look at the contact sheet before deciding.
+- **Phrase-aware caption breaking (1.16).** `caption.py`/`graphics.py --wrap phrase` (the default) never breaks inside a word or on the wrong side of a hyphen, never leaves a lone digit, kana or punctuation pair on a line, prefers Japanese sentence ends and particles over a mid-word break, and never ends a line on an article or preposition. All four are penalties over break positions that already fit, so no line is widened and the line count never changes; `--wrap measured` restores 1.15's width-only wrap. The text itself is never rewritten or shortened.
+- **Audiogram (1.16).** `waveform.py --image cover.png` (or `render.py --template audiogram`) puts the waveform over a still plate for an episode that has no picture, with `--platform` for the frame, `--title` and burnt-in captions. The image is a local file you give: nothing is fetched and no cover art is ever invented.
- **Emoji in captions and titles (1.15).** `caption.py`/`graphics.py --emoji-assets DIR` composites a PNG per emoji (Twemoji/Noto naming, `1f389.png`) on top of the text, because drawtext cannot load a colour emoji font at all and an installed one does not prove libass will draw it in colour — `doctor --json`'s `fonts.emoji` answers that from a render probe. Without assets the run still succeeds and reports `mode: mono`. Nothing is ever downloaded.
- **Indic and Thai text shaped correctly in titles and lower-thirds (1.15).** `graphics.py` renders Devanagari, Bengali, Tamil, Thai and Lao through libass automatically (`text_renderer: "ass"`), because drawtext never reorders matras or re-clusters marks; Arabic and Hebrew were already correct on a fribidi build. `--text-render drawtext` with such a script is refused, never rendered wrongly.
- **Non-Latin text picks a font by script (1.12).** Japanese, Chinese, Korean, Arabic, Hebrew, Devanagari, Thai, Cyrillic and Greek cues, titles and overlays resolve a font file that covers them automatically, and a machine with no such font fails the job (`kind: input`) instead of rendering boxes. `doctor --json`'s `fonts.scripts` says which languages this machine can render; `--lang ja|ko` disambiguates Han-only text; an explicit `--font`/`--font-file` is always kept.
diff --git a/SKILL.md b/SKILL.md
index 8904312..28abe8c 100644
--- a/SKILL.md
+++ b/SKILL.md
@@ -7,13 +7,13 @@ description: 'Edit video and audio with local FFmpeg from natural-language reque
Scripts live in `scripts/` next to this file; run them with `python3 <skill-dir>/scripts/<name>.py`, and delivery templates in `templates/`. 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), `references/devices.md` (iPhone HDR, GoPro, DJI, screen recordings, Zoom), `references/gotchas.md` (the long form of the one-line rules at the end).
-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 — warned today, refused from 2.0); `--plan FILE` (the dry run as a plan document `render.py FILE` executes later, refusing if an input changed). 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).
+Shared flags, on every script: `--dry-run`; `--json` (output path, a probe of the output, the commands run); `--json-brief` (the same trimmed to status/output/verified plus a `summary` — prefer it on writing steps); `--fast` (preview quality); `--progress`; `--timeout SECONDS` (`kind: timeout`, default 1800); `--overwrite` (step 7); `--plan FILE` (the dry run as a plan `render.py FILE` runs later, refusing if an input changed). 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 — they just don't write their artifact (nor side files such as `--edl`, `--sheet` or a generated `.ass`); `verify` ignores the flag. Per-tool: `contract --json`'s `dry_run` field.
+Writing tools run nothing under `--dry-run`; the measuring tools (`probe`, `check`, `sync`, `multicam`, `scenes`, `cropdetect`, `report`, `silence`, `loudness`, `stabilize`) may still run ffmpeg/ffprobe — they just don't write their artifact, nor side files (`--edl`, `--sheet`, a generated `.ass`); `verify` ignores the flag. Per-tool: `contract --json`'s `dry_run` field.
## Workflow (always follow this order)
-0. **Environment, only on failure.** Never start a job with `doctor`: a broken machine fails on its own with `kind: missing_tool` or an ffmpeg error naming the filter/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`, and report the missing capability (usually `libass`, `zscale` or an encoder) rather than rediscovering it at runtime. `contract --json`'s tool schema is for a *planning* agent choosing a tool from an abstract goal, not for this workflow.
+0. **Environment, only on failure.** Never start a job with `doctor`: a broken machine fails on its own with `kind: missing_tool` or an ffmpeg error naming the filter/encoder (`No such filter: 'subtitles'`). Run `python3 <skill-dir>/scripts/_contract.py doctor` (also `npx ffmpeg-skill doctor`) after such a failure, or when the user asks what the machine can do: read `ok` and the tool's `usable`, and report the missing capability (usually `libass`, `zscale` or an encoder) rather than rediscovering it at runtime. `contract --json`'s 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 about a file. No separate probe before every edit: every writing tool's `--json` already carries its input and a probe of the output. 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; `--accurate` on `cut.py` only for frame-exact cuts.
3. **Plan with `--dry-run --json`, then execute.** Trust `--json`, not a dry run's summary line, for any number in the plan (dimensions there can be a placeholder — `docs/contract.md`). Use it 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.
@@ -57,7 +57,7 @@ If a request needs an FFmpeg feature none of the 42 scripts expose, say so and n
This 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 (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]`); 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 NLE cue sheet, so nothing is converted by hand.
+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 SMPTE `hh:mm:ss:ff` with `@fps` (`00:01:02:[email protected]`) — paste an NLE cue sheet as it is; length flags (`--min-silence`, `--margin`, `--fade`) are plain seconds.
| User says | Do |
|-----------|----|
@@ -87,16 +87,17 @@ 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; a `render.py` project spells it `"chapters"`) |
+| "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"`). `--auto-chapters` proposes them from measured pauses/scene cuts, titled `Chapter N` for you to rename |
| "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` |
| "caption it with these lines" (text with times) | `caption.py input.mp4 --text cues.txt` |
-| "keep the subtitles toggleable", "mux in an SRT" | `caption.py input.mp4 --srt subs.srt --mode mux` |
+| "keep the subtitles toggleable", "mux in an SRT" | `caption.py input.mp4 --srt subs.srt --mode mux`; repeat `--srt file:lang` for several languages, `.mkv` for more than two |
| "our logo top-right", "a watermark" | `overlay.py input.mp4 --image logo.png --position top-right --scale 200` |
| "a title for the first 4 seconds" | `overlay.py input.mp4 --text "Title" --position top --start 0 --end 4 --fade 0.4` |
| "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` |
+| "turn this podcast into a video", "audiogram" | `render.py --template audiogram ep.m4a --image cover.png` — waveform over a still or colour plate; give an image or a colour, nothing is fetched |
| "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; `--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`) |
@@ -149,7 +150,7 @@ Audio is a first-class input: `probe.py`, `cut.py`, `silence.py`, `loudness.py`,
## 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. Keep the field labels (`Done:`, `Steps:`, `Check:`, `Look:`, `Notes:`) in English: they read like log fields 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 are English, and never drift because the job was short or the report is a failure: a one-line "file does not exist" is in the request's language too. A mid-conversation switch follows the user's latest message. 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.
+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). Keep the field labels (`Done:`, `Steps:`, `Check:`, `Look:`, `Notes:`) in English: they read like log fields across languages. The *lines* they head are not: `Done:`, `Steps:` and `Check:` carry the user's language just as `Look:` and `Notes:` do — a Spanish prompt answered with English `Done:`/`Steps:` sentences is an English report. 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 are English, and never drift because the job was short or the report is a failure: a one-line "file does not exist" is in the request's language too. A mid-conversation switch follows the user's latest message.
Finish every job with this shape (numbers from `--json` or `probe.py`/`check.py`, not memory):
diff --git a/demos/build.py b/demos/build.py
index 22c5a51..aaea643 100644
--- a/demos/build.py
+++ b/demos/build.py
@@ -233,6 +233,9 @@ def build_fixtures(force=False):
"0:02-0:04 Nice work 👍 everyone",
"0:04-0:06 Ship it 🚀 now",
"0:06-0:08 Done ✅"],
+ # eval 16's dl1 and dl4 cues, the ones the 1.16 phrase breaker exists for
+ "cues_phrase.txt": ["0:00-0:03 Una tercera linea con tiempos automaticos",
+ "0:03-0:06 A third line the tool times for me"],
"cues_pop.txt": ["0:00-0:02 word by word",
"0:02-0:04 the karaoke highlight tracks the beat",
"0:04-0:06 pop scales each cue in",
@@ -1006,6 +1009,120 @@ def demo_waveform_render(ctx):
return before, after
+def demo_captions_phrase(ctx):
+ """The same cue rendered twice, at the same size, with one flag different -- the only demo in
+ the gallery whose two halves are the same tool. Left is 1.15's width-only wrap, right is the
+ phrase-aware one: no line ends on an article or a preposition."""
+ src = FIX / "motion.mp4"
+ before = ctx.path("before.mp4")
+ after = ctx.path("after.mp4")
+ for out, mode in ((before, "measured"), (after, "phrase")):
+ ctx.script("caption.py", src, "--text", FIX / "cues_phrase.txt", "--size", "34",
+ "--bold", "--position", "bottom", "--margin", "40", "--wrap", mode,
+ "--preset", "veryfast", "-o", out)
+ return before, after
+
+
+def demo_captions_multitrack(ctx):
+ """Nothing is burnt in and nothing is re-encoded: the video and audio are copied bit for bit
+ and three SRTs ride along as toggleable, language-tagged streams. The right half is the track
+ list ffprobe reads back, drawn the way the chapters demo draws its strip."""
+ before = FIX / "mandel.mp4"
+ srts = []
+ for lang, line in (("en", "Hello from the English track"),
+ ("ja", "\u65e5\u672c\u8a9e\u306e\u5b57\u5e55\u30c8\u30e9\u30c3\u30af"),
+ ("es", "Pista de subtitulos en espanol")):
+ path = ctx.path("track_%s.srt" % lang)
+ path.write_text("1\n00:00:00,000 --> 00:00:03,000\n%s\n" % line, encoding="utf-8")
+ srts.append("%s:%s" % (path, lang))
+ muxed = ctx.path("muxed.mkv")
+ ctx.script("caption.py", before, "--mode", "mux", "--srt", srts[0], "--srt", srts[1],
+ "--srt", srts[2], "--default-track", "en", "-o", muxed)
+ rows = []
+ if muxed.exists():
+ raw = run(["ffprobe", "-v", "error", "-print_format", "json", "-select_streams", "s",
+ "-show_streams", str(muxed)], capture=True)
+ for st in json.loads(raw).get("streams", []):
+ tags = st.get("tags") or {}
+ rows.append("%s %s %s" % (st.get("codec_name", "?"), tags.get("language", "-"),
+ tags.get("title", "-")))
+ ctx.note("%d subtitle tracks, video and audio stream-copied" % len(rows))
+ font = label_font()
+ draws = []
+ for i, text in enumerate(rows or ["no tracks"]):
+ draws.append("drawtext=fontfile='%s':text='%s':fontsize=24:fontcolor=white:x=40:y=%d"
+ % (esc(font), text.replace(":", "\\:"), 150 + i * 52))
+ draws.append("drawtext=fontfile='%s':text='ffprobe -select_streams s':fontsize=18:"
+ "fontcolor=0x39ff88:x=40:y=%d" % (esc(font), 150 + max(1, len(rows)) * 52 + 24))
+ card = ctx.path("tracks.png")
+ ffmpeg("-f", "lavfi", "-i", "color=c=0x101014:s=960x540", "-frames:v", "1",
+ "-vf", ",".join(draws), str(card))
+ after = ctx.path("after.mp4")
+ ffmpeg("-loop", "1", "-t", "3", "-i", str(card), "-vf", "format=yuv420p", "-r", "10",
+ "-c:v", "libx264", "-preset", "veryfast", "-crf", "24", str(after))
+ return before, after
+
+
+def demo_audiogram(ctx):
+ """The same track as the waveform demo, this time over a still plate with the episode title
+ and burnt-in captions -- one render.py --template audiogram call. The picture is generated by
+ background.py; nothing was downloaded and no cover art was invented."""
+ before = ctx.path("before.mp4")
+ ffmpeg("-f", "lavfi", "-i", "color=c=0x101014:s=640x360:rate=10", "-i", str(FIX / "music.m4a"),
+ "-shortest", "-t", "5", "-c:v", "libx264", "-preset", "veryfast", "-crf", "28",
+ "-pix_fmt", "yuv420p", "-c:a", "aac", str(before))
+ plate_clip = ctx.path("plate.mp4")
+ ctx.script("background.py", "--width", "960", "--height", "540",
+ "--gradient", "#101014:#2a1846", "--duration", "1", "-o", plate_clip)
+ plate = ctx.path("plate.png")
+ ffmpeg("-i", str(plate_clip), "-frames:v", "1", str(plate))
+ cues = ctx.path("cues.txt")
+ cues.write_text("0:00-0:02 The waveform rides over the plate\n"
+ "0:02-0:05 One render.py --template audiogram call\n", encoding="utf-8")
+ after = ctx.path("after.mp4")
+ ctx.script("waveform.py", FIX / "music.m4a", "--image", plate, "--width", "960",
+ "--height", "540", "--position", "strip", "--vis-height", "0.3",
+ "--color", "0x39ff88", "--title", "Episode 12", "--text", cues,
+ "--preset", "veryfast", "-o", after)
+ return before, after
+
+
+def demo_auto_chapters(ctx):
+ """The left strip is the file with no markers; the right is the same file after
+ --auto-chapters, whose timestamps come from the measured pauses and scene cuts and whose
+ titles are deliberately 'Chapter 1..N' -- the skill proposes where, the caller says what."""
+ before = FIX / "shots.mp4"
+ tagged = ctx.path("auto.mp4")
+ ctx.script("metadata.py", before, "--auto-chapters", "--min-chapter", "1",
+ "--from", "scenes", "-o", tagged)
+ marks = []
+ if tagged.exists():
+ raw = run(["ffprobe", "-v", "error", "-print_format", "json", "-show_chapters",
+ str(tagged)], capture=True)
+ total = duration(tagged) or 6.0
+ for chapter in json.loads(raw).get("chapters", []):
+ start = float(chapter["start_time"])
+ marks.append((start / total, "%d:%02d %s" % (int(start) // 60, int(start) % 60,
+ chapter.get("tags", {}).get("title", "?"))))
+ ctx.note("%d chapters proposed from measured structure, titles are placeholders" % len(marks))
+ font = label_font()
+ after = ctx.path("after.mp4")
+ strip = ctx.path("auto_strip.png")
+ draws = ["drawbox=x=0:y=70:w=960:h=8:[email protected]:t=fill"]
+ for idx, (frac, title) in enumerate(marks or [(0.0, "Chapter 1")]):
+ x = int(frac * 940)
+ draws.append("drawbox=x=%d:y=56:w=4:h=36:color=white:t=fill" % x)
+ draws.append("drawtext=fontfile='%s':text='%s':fontsize=20:fontcolor=white:"
+ "x=%d:y=%d" % (esc(font), title.replace(":", "\\:"), min(x + 10, 700),
+ 100 if idx % 2 else 20))
+ ffmpeg("-f", "lavfi", "-i", "color=c=0x101014:s=960x160", "-frames:v", "1",
+ "-vf", ",".join(draws), str(strip))
+ ffmpeg("-loop", "1", "-t", "3", "-i", str(strip), "-vf",
+ "pad=960:540:0:190:0x101014,format=yuv420p", "-r", "10", "-c:v", "libx264",
+ "-preset", "veryfast", "-crf", "24", str(after))
+ return before, after
+
+
def demo_proxy(ctx):
"""Both sides are shown at the same size, which is the only honest way to compare a proxy
with its master: the proxy is smaller on disk, not on screen."""
@@ -1086,6 +1203,12 @@ _ROWS = [
("captions_en", CAPTIONS, "Burned-in captions (English)",
"Plain-text cues become an SRT and are rendered by libass -- outline and margin come from the flags, not from a template.",
demo_captions_en, "video", "latin"),
+ ("captions_phrase", CAPTIONS, "Phrase-aware line breaks",
+ "The same cue at the same size, with one flag different. Left is 1.15's wrap, which only minimised the widest line and left `the` and `con` stranded at the end of a line; right is 1.16's default, which never breaks inside a word and never ends a line on an article or a preposition. The text itself is untouched -- the skill never rewrites a caption to make it fit.",
+ demo_captions_phrase, "video", "latin", ("GREEDY WRAP", "PHRASE WRAP")),
+ ("captions_multitrack", CAPTIONS, "Three subtitle tracks in one file",
+ "Nothing is burnt in and nothing is re-encoded: the video and audio are copied bit for bit and three SRTs ride along as toggleable, language-tagged streams. The right half is the track list ffprobe reads back.",
+ demo_captions_multitrack, "video", "latin", ("ONE FILE, NO SUBTITLES", "3 TAGGED TRACKS")),
("captions_ja", CAPTIONS, "Japanese captions",
"The font is chosen per script: Japanese cues get a CJK face automatically, so no box-glyph tofu appears.",
demo_captions_ja, "video", "ja"),
@@ -1241,6 +1364,9 @@ _ROWS = [
("waveform_render", AUDIO, "Audio rendered as a waveform video",
"An audio-only file has nothing to show; showwaves draws the amplitude as it plays, and the rendered clip carries the same audio it is drawing.",
demo_waveform_render, "video", None, ("AUDIO ONLY", "WAVEFORM")),
+ ("audiogram", AUDIO, "Audio episode as a shareable audiogram",
+ "The same track as the waveform demo, this time over a still plate with the episode title and burnt-in captions -- one waveform.py --image call (or render.py --template audiogram). The picture is generated by background.py: nothing was downloaded and no cover art was invented.",
+ demo_audiogram, "video", "latin", ("AUDIO ONLY", "AUDIOGRAM")),
("proxy", DELIVERY, "Proxy vs. master, shown at the same size",
"Both halves are scaled to the same cell, which is the honest comparison: the proxy is smaller on disk and cheaper to decode, not smaller on screen. The softness is the point of it.",
@@ -1252,6 +1378,9 @@ _ROWS = [
("metadata_chapters", PROJECTS, "Chapter marks written into the container",
"Nothing in the picture changes -- every stream is copied bit for bit. The right half is the chapter list read back out of the file with ffprobe and drawn as the timeline strip a player would show.",
demo_metadata_chapters, "video", "latin", ("NO CHAPTERS", "CHAPTER MARKS")),
+ ("metadata_auto_chapters", PROJECTS, "Chapters proposed from measured structure",
+ "The left strip is the file with no markers; the right is the same file after --auto-chapters, whose timestamps come from the measured pauses and scene cuts and whose titles are deliberately 'Chapter 1..N' -- the skill proposes where, the caller says what.",
+ demo_auto_chapters, "video", "latin", ("NO CHAPTERS", "PROPOSED CHAPTERS")),
]
DEMOS = [Demo(*row) for row in _ROWS]
diff --git a/docs/contract.md b/docs/contract.md
index 9861419..14a2315 100644
--- a/docs/contract.md
+++ b/docs/contract.md
@@ -423,6 +423,21 @@ including `input_lra`) and `targets` (the requested lufs / tp / lra).
`check.py --platform podcast` adds two informational rows to `checks`,
`channels` and `chapters`.
+Per-tool keys added in 1.16, all additive (no 1.15 key is removed, renamed or
+given a different type):
+
+| key | tool | what it holds |
+|---|---|---|
+| `caption` | `caption.py` | the cue-layout counts the run only printed before (`shifted`, `wrapped`, `rebalanced`, `split`, `extended`, `dropped`) plus `wrap` (`"phrase"` or `"measured"`) and `phrase_breaks`, the number of cues a phrase rule broke somewhere the 1.15 width rule would not |
+| `tracks`, `subtitle_tracks` | `caption.py --mode mux` | one entry per subtitle stream in the output — `{index, file, language, title, codec, default, cues, kept_from_input}`; a stream the input already carried has `file: null` and `kept_from_input: true`. `subtitle_tracks` is the total. Every field describes the file as written, not as asked for: an MPEG-4 output reports `title: null` (the muxer stores none) and `default: true` on its first track (the muxer always enables it), each with a `notes` line |
+| `auto_chapters` | `metadata.py --auto-chapters` | `{source, min_chapter, max_chapters, proposed, kept, titles, chapters, description_block, files}`. `titles` is always `"placeholder"`: the machine-readable form of "the skill did not name these". Each chapter carries its `evidence` (`start`, `silence`, `scene`, or `silence+scene` with the span, its length and the cut time) |
+| `audiogram` | `waveform.py` (every run) | `{style, background, image, position, vis_height, platform, captions, title, stages, verified}`. `background` is `"image"` or `"color"`; `verified` is true when the render probes at the asked-for frame size, frame rate and within 0.05 s of the source audio, and is `false` under `--dry-run`, where nothing was rendered to verify |
+
+`check.py` also gains an informational `subtitles` row on **every** platform:
+`PASS` when every soft subtitle stream carries a language tag, `WARN` when one
+does not (or when there are none). Like `channels` and `chapters` it is never
+counted in `failed` — no platform refuses a delivery over it.
+
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
diff --git a/docs/demos.md b/docs/demos.md
index 653f628..0e740a2 100644
--- a/docs/demos.md
+++ b/docs/demos.md
@@ -34,6 +34,27 @@ python3 scripts/caption.py demos/out/fixtures/motion.mp4 --text demos/out/fixtur
**Look for:** Plain-text cues become an SRT and are rendered by libass -- outline and margin come from the flags, not from a template.
+### Phrase-aware line breaks
+
+![Phrase-aware line breaks](demos/captions_phrase.gif)
+
+```bash
+python3 scripts/caption.py demos/out/fixtures/motion.mp4 --text demos/out/fixtures/cues_phrase.txt --size 34 --bold --position bottom --margin 40 --wrap measured --preset veryfast -o demos/out/captions_phrase_before.mp4
+python3 scripts/caption.py demos/out/fixtures/motion.mp4 --text demos/out/fixtures/cues_phrase.txt --size 34 --bold --position bottom --margin 40 --wrap phrase --preset veryfast -o demos/out/captions_phrase_after.mp4
+```
+
+**Look for:** The same cue at the same size, with one flag different. Left is 1.15's wrap, which only minimised the widest line and left `the` and `con` stranded at the end of a line; right is 1.16's default, which never breaks inside a word and never ends a line on an article or a preposition. The text itself is untouched -- the skill never rewrites a caption to make it fit.
+
+### Three subtitle tracks in one file
+
+![Three subtitle tracks in one file](demos/captions_multitrack.gif)
+
+```bash
+python3 scripts/caption.py demos/out/fixtures/mandel.mp4 --mode mux --srt demos/out/captions_multitrack_track_en.srt:en --srt demos/out/captions_multitrack_track_ja.srt:ja --srt demos/out/captions_multitrack_track_es.srt:es --default-track en -o demos/out/captions_multitrack_muxed.mkv
+```
+
+**Look for:** Nothing is burnt in and nothing is re-encoded: the video and audio are copied bit for bit and three SRTs ride along as toggleable, language-tagged streams. The right half is the track list ffprobe reads back.
+
### Japanese captions
![Japanese captions](demos/captions_ja.gif)
@@ -497,6 +518,17 @@ python3 scripts/waveform.py demos/out/fixtures/music.m4a --style waveform --widt
**Look for:** An audio-only file has nothing to show; showwaves draws the amplitude as it plays, and the rendered clip carries the same audio it is drawing.
+### Audio episode as a shareable audiogram
+
+![Audio episode as a shareable audiogram](demos/audiogram.gif)
+
+```bash
+python3 scripts/background.py --width 960 --height 540 --gradient #101014:#2a1846 --duration 1 -o demos/out/audiogram_plate.mp4
+python3 scripts/waveform.py demos/out/fixtures/music.m4a --image demos/out/audiogram_plate.png --width 960 --height 540 --position strip --vis-height 0.3 --color 0x39ff88 --title 'Episode 12' --text demos/out/audiogram_cues.txt --preset veryfast -o demos/out/audiogram_after.mp4
+```
+
+**Look for:** The same track as the waveform demo, this time over a still plate with the episode title and burnt-in captions -- one waveform.py --image call (or render.py --template audiogram). The picture is generated by background.py: nothing was downloaded and no cover art was invented.
+
## Delivery & checks
@@ -575,6 +607,16 @@ python3 scripts/metadata.py demos/out/fixtures/mandel.mp4 --chapters demos/out/f
**Look for:** Nothing in the picture changes -- every stream is copied bit for bit. The right half is the chapter list read back out of the file with ffprobe and drawn as the timeline strip a player would show.
+### Chapters proposed from measured structure
+
+![Chapters proposed from measured structure](demos/metadata_auto_chapters.gif)
+
+```bash
+python3 scripts/metadata.py demos/out/fixtures/shots.mp4 --auto-chapters --min-chapter 1 --from scenes -o demos/out/metadata_auto_chapters_auto.mp4
+```
+
+**Look for:** The left strip is the file with no markers; the right is the same file after --auto-chapters, whose timestamps come from the measured pauses and scene cuts and whose titles are deliberately 'Chapter 1..N' -- the skill proposes where, the caller says what.
+
## Inspection
diff --git a/docs/demos/audiogram.gif b/docs/demos/audiogram.gif
new file mode 100644
index 0000000..8e6caff
Binary files /dev/null and b/docs/demos/audiogram.gif differ
diff --git a/docs/demos/captions_multitrack.gif b/docs/demos/captions_multitrack.gif
new file mode 100644
index 0000000..9ded2dc
Binary files /dev/null and b/docs/demos/captions_multitrack.gif differ
diff --git a/docs/demos/captions_phrase.gif b/docs/demos/captions_phrase.gif
new file mode 100644
index 0000000..0dbe451
Binary files /dev/null and b/docs/demos/captions_phrase.gif differ
diff --git a/docs/demos/metadata_auto_chapters.gif b/docs/demos/metadata_auto_chapters.gif
new file mode 100644
index 0000000..fc0a869
Binary files /dev/null and b/docs/demos/metadata_auto_chapters.gif differ
diff --git a/docs/design-decisions.md b/docs/design-decisions.md
index f10ec1b..96b2436 100644
--- a/docs/design-decisions.md
+++ b/docs/design-decisions.md
@@ -247,3 +247,55 @@ Each item is recorded here so it is not re-proposed from scratch.
1.14.0, so the demos, the golden frames and every existing test do not move (the filter
string itself did change: the label moved from `text=` into `textfile=…:expansion=none`) —
and the new route carries no risk for the 95 % of jobs that never needed it.
+
+
+## 1.16.0 — long-form delivery
+
+**The audiogram extends `waveform.py`; there is no `audiogram.py`.** `waveform.py` already owns
+`showwaves`/`showspectrum`, `--width/--height/--fps/--color/--background`, `--split-channels`,
+`--audio-stream`, the one encoder line and the FFmpeg-5.x `-t` cap (#146). An `audiogram.py`
+would be that file plus a background image: a second spelling of one tool, which is exactly the
+mistake recorded for `audio.py --chapters`. The 1.x guarantee forbids *removing* a tool, so an
+`audiogram.py` would be permanent surface; `--image` is one additive argument. The composite job
+(visualisation over a plate, a title, captions burnt in, platform size, `check.py`) is a chain,
+and this repo already has one answer for a chain: a `render.py` template, as 1.14 established and
+`templates/podcast.json` precedes. The tool count therefore stays 42, which is asserted in five
+files by `test_docs_tool_count_matches_the_real_tool_list`. Do not re-propose it.
+
+**The title and the captions on an audiogram are second processes.** `waveform.py --title` runs
+`graphics.py --template sticker` and `--srt`/`--text` runs `caption.py` on the rendered file,
+rather than adding drawtext or an ASS path here. One code path per job is worth two process
+spawns; the alternative is a second subtitle renderer that drifts from the first.
+
+**`--auto-chapters` lives in `metadata.py`, and the detectors moved into `_common`.**
+`metadata.py` already owns the chapter format, the `-c copy` graph and the written-vs-asked-for
+count assertion; `scenes.py --chapters-out` would put chapter writing in a tool that cannot write
+chapters. No script in `scripts/` imports a sibling tool (only the `_`-prefixed modules are
+shared), so `silence.detect` and `scenes.detect_scenes` moved into `_common/probe.py` byte-for-byte
+and all three tools import them from there. The merge/keep/drop decision itself is
+`propose_chapters()` in `_common/decision.py`: pure, subprocess-free, unit-testable.
+
+**The skill proposes chapter timestamps; it never names them.** Every proposed title is
+`Chapter N` and the result says `"titles": "placeholder"`. Naming a chapter needs knowing what is
+said in it, which is content understanding — the boundary SKILL.md's "What this skill does and
+does not decide" holds. A request to title them is a refusal with the placeholder list offered.
+
+**Only the `--srt FILE:lang` suffix form.** The parallel-list alternative (`--srt a --srt b
+--lang en,ja`) was specified and dropped: it can get out of order, and two spellings of one
+argument is the thing the deprecation policy exists to avoid. A single `--srt` with no suffix
+still honours `--language`, so nothing that worked before changed.
+
+**The Japanese particle table is a preference, not grammar — and it is a "do not strand at the
+start of a line" table.** `は が を に で と の へ も や から まで より` come from the task brief
+plus the five a reader would add. A particle is enclitic: it attaches to the word *before* it and
+marks that word's role, so kinsoku practice keeps the two together. The rule is therefore "prefer
+the break after a particle, forbid the break before one", not the other way round. There is no
+upstream source for the list and no precedent in this repo; it is tunable data, applied among
+break positions that already fit, so it can never widen a line or change the line count.
+
+**R4 scores both directions, which is what makes it decide.** An article or preposition opens the
+noun phrase it governs, so the break *before* it is the good break (0.2) and the break *after* it
+the bad one (0.8). Penalising only the bad direction leaves the greedy width rule to choose among
+everything else, which is how the first cut of this release still split eval 16's `dl1` cue
+mid-phrase. With both directions scored, `"A third line the tool times for me"` comes out as
+`A third line / the tool times for me` — one whole phrase per line — and `dl4` is unchanged.
diff --git a/docs/roadmap.md b/docs/roadmap.md
index e4b778a..d4fe942 100644
--- a/docs/roadmap.md
+++ b/docs/roadmap.md
@@ -17,7 +17,7 @@ minor and `fix` PRs into a patch, so each block below is one or two `feat` PRs p
- **planned** — not released. Nothing below a *planned* heading exists in any published version;
the feature lines are the intent, not a description of the code.
-The released version today is **1.15.0**, shipped and evaluated: **eval 16**
+The released version today is **1.15.1**; **1.15.0** is the last one an eval graded: **eval 16**
(`evals/results/iteration-16.json`) graded it on the 82-prompt set, the 76 plus the six
emoji/shaping prompts. After it comes the behaviour-free refactor release below; everything
after that is planned.
@@ -33,7 +33,8 @@ after that is planned.
| 1.14.0 | shipped + evaluated | eval 15 at 1.14.0 (`iteration-15.json`) |
| 1.15.0 | shipped + evaluated | eval 16 at 1.15.0 (`iteration-16.json`) |
| refactor after 1.15.0 | shipped, eval pending | contract + MCP snapshots and every `--help` byte-identical; 323/323 cases |
-| 1.16.0 → 1.21.0, 2.0.0 | planned | — |
+| 1.16.0 | shipped, eval pending | contract and MCP snapshots additive only; tool count still 42; eval 17 is a separate PR |
+| 1.17.0 → 1.21.0, 2.0.0 | planned | — |
## 1.8.0 — one-call delivery, quieter checks, encoder flags (shipped + evaluated, eval 8)
@@ -262,19 +263,31 @@ came out byte-identical, as did `--help` for all 42 tools.
- No eval iteration of its own: the release is proved by the existing suite plus the two
snapshots, and the next themed eval runs on top of it.
-## 1.16.0 — long-form delivery (planned)
-
-- **Phrase-aware caption breaking** (eval 16 follow-up): the wrap never splits inside a word or
- between a determiner and its noun, and balances lines by measured width; the `dl1`/`dl3`/`dl4`
- cues become the regression lock. The label lines (`Done:`/`Steps:`/`Check:`) are stated in
- SKILL.md to be part of the user's-language report (`dl4`, `id1`).
-- **Audiogram**: a `waveform.py` / `render.py` template that turns an audio episode into a
- shareable video (waveform or spectrum over a still or brand background, captions burned in).
-- **Auto chapters**: chapter markers proposed from measured structure (silence spans and scene
- changes), written by `metadata.py` — the skill proposes the timestamps, the caller names them.
-- **Multi-language subtitle tracks**: `caption.py --mode mux` takes more than one subtitle file
- and tags each stream with its language, so one deliverable carries several tracks.
-- Eval 17 on long-form and podcast prompts.
+## 1.16.0 — long-form delivery (shipped, eval pending)
+
+- **Phrase-aware caption breaking** (eval 16 follow-up): `caption.py`/`graphics.py --wrap
+ phrase|measured`, default `phrase`. Four rules over the break positions that already fit, so
+ no line is widened and the line count never changes — never inside a word or on the wrong side
+ of a hyphen; no lone digit, punctuation pair or single kana on its own line, at every boundary
+ rather than only the last; Japanese/Chinese sentence ends preferred, a particle kept with the
+ word before it (kinsoku: a line may not open with one), never a break inside a word; an article
+ or preposition kept with the phrase it governs in six Latin-script languages. The
+ `dl1`/`dl3`/`dl4`/`th1` cues are the regression lock, and each now breaks as one whole phrase
+ per line. `--wrap measured` restores 1.15 exactly. The label lines (`Done:`/`Steps:`/`Check:`) are now stated in SKILL.md to carry the user's
+ language (`dl4`, `id1`).
+- **Audiogram**: `waveform.py --image` plus `templates/audiogram.json` and a `render.py`
+ `audiogram` stage — an audio episode over a still or brand plate, with a title and captions.
+ **No new tool** (`docs/design-decisions.md` records why), so the count stays 42, and a run with
+ none of the new flags builds the same command line 1.15 did.
+- **Auto chapters**: `metadata.py --auto-chapters` proposes markers from measured pauses and
+ scene changes, with `--chapters-out`/`--description-out`. Every title is `Chapter N` and the
+ result says `"titles": "placeholder"` — the skill proposes the timestamps, the caller names
+ them.
+- **Multi-language subtitle tracks**: `caption.py --mode mux --srt file:lang`, repeatable, with
+ `--track-title` and `--default-track`; the result lists every stream under `tracks` and
+ `check.py` gains an informational `subtitles` row.
+- Eval 17 on long-form and podcast prompts: **still pending**, a separate `docs:` PR as every
+ previous iteration was.
## 1.17.0 — throughput (planned)
diff --git a/evals/README.md b/evals/README.md
index 26eecd4..cf12038 100644
--- a/evals/README.md
+++ b/evals/README.md
@@ -2,16 +2,16 @@
Two kinds of eval live here:
-- **Trigger tests** (`trigger/`) — does a model pick this skill for a request, and leave it alone for a near miss? 38 prompts, see `trigger/README.md`.
+- **Trigger tests** (`trigger/`) — does a model pick this skill for a request, and leave it alone for a near miss? 45 prompts, see `trigger/README.md`.
- **Agent runs** (`agent_prompts_*.json` + `grade_runs_24.py`) — give an agent a real request with the skill available, then grade the transcript and the files it produced.
`tasks.json` + `run.py` are the older, simpler transcript-keyword harness; `contract/` checks the documented contract questions.
-## The 76-prompt agent set
+## The 90-prompt agent set
-`agent_prompts_24.json` (65 prompts) and `agent_prompts_exec.json` (11 prompts) together make the
-76-prompt set: the original 50 (39 + 11), plus 18 multilingual prompts in nine more languages and
-8 delivery/template prompts. Both use the same field shape:
+`agent_prompts_24.json` (79 prompts) and `agent_prompts_exec.json` (11 prompts) together make the
+90-prompt set: the original 50 (39 + 11), plus 18 multilingual prompts in nine more languages,
+8 delivery/template prompts, 6 emoji/shaping prompts and the 8 long-form prompts 1.16 added. Both use the same field shape:
| field | meaning |
|---|---|
@@ -75,6 +75,23 @@ captions, platform export, compliance check) and the agent has to infer it rathe
`expect` for the act ones is `["render|fit|export", "check"]`: they are runnable today as a manual
fit/caption/export/check chain, and from 1.14.0 in one step with `render.py --template`.
+### Long-form prompts (`cw1`/`cw2`, `ag1`/`ag2`, `ch1`/`ch2`, `ml1`/`ml2`), added for 1.16
+
+One act prompt and one refusal-shaped prompt per feature. The four refusals are deliberately in
+four different languages, so a single run re-measures the label rule (SKILL.md § Report format:
+`Done:`/`Steps:`/`Check:` carry the user's language) on es, ja, pt and de at once.
+
+| id | lang | request | graded on |
+|---|---|---|---|
+| `cw1` | en | caption for TikTok, "the lines have to break sensibly" | the phrase wrap is the default, so no flag is needed |
+| `cw2` | es | "rewrite the subtitles shorter so they fit" | refusal: the skill wraps and splits cues, it never rewrites the user's words |
+| `ag1` | en | turn a track into a postable video with this cover behind the waveform | `waveform.py --image` / `render.py --template audiogram` |
+| `ag2` | ja | make the podcast a video, "find a nice background image for it" | refusal: no network, no image search, no invented cover art |
+| `ch1` | en | propose chapter markers from the pauses, "don't rename anything yet" | `metadata.py --auto-chapters`, titles stay `Chapter N` |
+| `ch2` | pt | create the chapters and title each one by its subject | refusal: the skill proposes timestamps, it cannot know the subject |
+| `ml1` | en | put the English and Japanese SRTs in as switchable tracks | `caption.py --mode mux` with a repeated `--srt file:lang` |
+| `ml2` | de | "add the German subtitles — just translate the English ones" | refusal: no translation engine (r04's rule, in the mux context) |
+
### Fixtures
`c01`, `k01`, `a01`, `th1`, `he1`, `vi1` refer to a cue file in their own language (`cues_zh.txt`,
diff --git a/evals/agent_prompts_24.json b/evals/agent_prompts_24.json
index caa9520..b685483 100644
--- a/evals/agent_prompts_24.json
+++ b/evals/agent_prompts_24.json
@@ -723,5 +723,94 @@
"fixtures": {
"cues_th2.txt": "0:00-0:03 สวัสดีชาวโลก\n0:03-0:06 บรรทัดที่สองของคำบรรยาย\n"
}
+ },
+ {
+ "id": "cw1",
+ "lang": "en",
+ "prompt": "Caption /home/user/ffmpeg-skill/tests/out/source.mp4 with OUTDIR/cues_cw1.txt for TikTok — the lines have to break sensibly. Save the result in OUTDIR and show me a frame.",
+ "expect": [
+ "caption|render",
+ "look"
+ ],
+ "refuse": false,
+ "note": "the dl1 cue: the phrase-aware wrap is the default, so no flag is needed",
+ "fixtures": {
+ "cues_cw1.txt": "0:00-0:03 A third line the tool times for me\n0:03-0:06 Segunda linea de subtitulos\n"
+ }
+ },
+ {
+ "id": "cw2",
+ "lang": "es",
+ "prompt": "Los subtítulos de OUTDIR/cues_dl4.txt no caben en dos líneas — reescríbelos más cortos y ponlos en el vídeo /home/user/ffmpeg-skill/tests/out/source.mp4. Guarda todo en OUTDIR.",
+ "expect": [],
+ "refuse": true,
+ "note": "the skill wraps and splits cues, it never rewrites the user's words; the refusal offers --max-lines / a split and is written in Spanish, labels included",
+ "fixtures": {
+ "cues_dl4.txt": "0:00-0:03 Segunda línea de subtítulos\n0:03-0:06 Una tercera línea con tiempos automáticos\n"
+ }
+ },
+ {
+ "id": "ag1",
+ "lang": "en",
+ "prompt": "Turn OUTDIR/music.m4a into a video I can post, with OUTDIR/cover.png behind the waveform. Save it in OUTDIR and show me a frame.",
+ "expect": [
+ "waveform|render",
+ "check|export",
+ "look"
+ ],
+ "refuse": false,
+ "note": "the audiogram: waveform.py --image or render.py --template audiogram"
+ },
+ {
+ "id": "ag2",
+ "lang": "ja",
+ "prompt": "OUTDIR/music.m4a のポッドキャスト音声を動画にして。背景はいい感じの画像を探して付けておいて。OUTDIR に保存して。",
+ "expect": [],
+ "refuse": true,
+ "note": "no network, no image search, no invented cover art: the refusal asks for a local image or a colour, in Japanese, labels included"
+ },
+ {
+ "id": "ch1",
+ "lang": "en",
+ "prompt": "Propose chapter markers for OUTDIR/gappy.mp4 from where the pauses are — don't rename anything yet. Write them next to the file in OUTDIR.",
+ "expect": [
+ "metadata|silence|scenes"
+ ],
+ "refuse": false,
+ "note": "metadata.py --auto-chapters; the titles stay Chapter N"
+ },
+ {
+ "id": "ch2",
+ "lang": "pt",
+ "prompt": "Cria os capítulos do episódio OUTDIR/gappy.mp4 e dá um título a cada um conforme o assunto. Guarda em OUTDIR.",
+ "expect": [],
+ "refuse": true,
+ "note": "the skill proposes timestamps from measured structure; it cannot know the subject. Offers the Chapter N placeholders, in Portuguese, labels included"
+ },
+ {
+ "id": "ml1",
+ "lang": "en",
+ "prompt": "Put the English and Japanese SRTs (OUTDIR/en.srt, OUTDIR/ja.srt) into /home/user/ffmpeg-skill/tests/out/source.mp4 as switchable tracks. Save the result in OUTDIR.",
+ "expect": [
+ "caption",
+ "check|probe"
+ ],
+ "refuse": false,
+ "note": "caption.py --mode mux with a repeated --srt file:lang; .mkv is the honest container",
+ "fixtures": {
+ "en.srt": "1\n00:00:00,000 --> 00:00:03,000\nHello world\n",
+ "ja.srt": "1\n00:00:00,000 --> 00:00:03,000\nこんにちは世界\n"
+ }
+ },
+ {
+ "id": "ml2",
+ "lang": "de",
+ "prompt": "Häng die deutschen Untertitel mit dran — übersetz die englischen aus OUTDIR/en.srt einfach. Alles nach OUTDIR.",
+ "expect": [],
+ "refuse": true,
+ "note": "no translation engine (same rule as r04); the refusal is in German, labels included",
+ "fixtures": {
+ "en.srt": "1\n00:00:00,000 --> 00:00:03,000\nHello world\n"
+ }
}
]
diff --git a/evals/trigger/README.md b/evals/trigger/README.md
index 505f39d..07f2ef2 100644
--- a/evals/trigger/README.md
+++ b/evals/trigger/README.md
@@ -1,6 +1,6 @@
# Trigger tests: should / should-not
-`prompts.json` holds 23 requests the skill must trigger on (English, Japanese, Chinese, Korean, Spanish, Arabic, Thai, Hindi, Hebrew, Russian, Vietnamese and Turkish, some without a file extension or the word "edit") and 17 near-miss requests it must not (still images, installing ffmpeg — in English, Japanese, French and Greek, downloading from YouTube, writing a script in Japanese, Portuguese and Italian, an editor shortcut, thumbnail design, CSV to JSON, a codec explainer, AI video generation in English, German and Indonesian, meeting transcription, an emoji sticker pack as PNGs — image work, not video).
+`prompts.json` holds 26 requests the skill must trigger on (English, Japanese, Chinese, Korean, Spanish, Arabic, Thai, Hindi, Hebrew, Russian, Vietnamese and Turkish, some without a file extension or the word "edit") and 19 near-miss requests it must not (still images, installing ffmpeg — in English, Japanese, French and Greek, downloading from YouTube, writing a script in Japanese, Portuguese and Italian, an editor shortcut, thumbnail design, CSV to JSON, a codec explainer, AI video generation in English, German and Indonesian, meeting transcription, an emoji sticker pack as PNGs — image work, not video, chapter titles for a blog outline with no media, and designing a podcast cover, which is image design rather than an edit). 1.16 added three that must trigger: a podcast episode to post on YouTube, a Japanese request for chapter marks with no idea where to cut, and a Spanish request for switchable English and Spanish subtitle tracks.
Method: show an independent model a skill catalog made of this skill's `description` plus four decoy skills that own the neighbouring territory (image-tools, web-research, copywriter, meeting-notes), give it the raw request, and ask which one skill it would load or `none`. A run is correct when ffmpeg-skill is chosen exactly for the should-trigger prompts.
diff --git a/evals/trigger/prompts.json b/evals/trigger/prompts.json
index ba5c8cf..6ec9f3f 100644
--- a/evals/trigger/prompts.json
+++ b/evals/trigger/prompts.json
@@ -238,5 +238,35 @@
"lang": "en",
"prompt": "make me an emoji sticker pack as PNGs, 20 stickers with transparent backgrounds",
"should_trigger": false
+ },
+ {
+ "id": "t41",
+ "lang": "en",
+ "prompt": "can you make my podcast episode into something I can post on YouTube? it's just an mp3",
+ "should_trigger": true
+ },
+ {
+ "id": "t42",
+ "lang": "ja",
+ "prompt": "エピソードにチャプターを入れたいんだけど、どこで区切ればいいか分からない",
+ "should_trigger": true
+ },
+ {
+ "id": "t43",
+ "lang": "es",
+ "prompt": "necesito que el vídeo lleve subtítulos en inglés y en español, que se puedan cambiar",
+ "should_trigger": true
+ },
+ {
+ "id": "n18",
+ "lang": "en",
+ "prompt": "write the chapter titles for my blog post outline",
+ "should_trigger": false
+ },
+ {
+ "id": "n19",
+ "lang": "de",
+ "prompt": "entwirf ein Podcast-Cover für Spotify",
+ "should_trigger": false
}
]
diff --git a/references/scripts.md b/references/scripts.md
index 9494546..75ae26f 100644
--- a/references/scripts.md
+++ b/references/scripts.md
@@ -256,7 +256,11 @@ frame is refused here, not discovered from an opaque ffmpeg error).
### waveform.py — audio waveform/spectrum visualization video
```
waveform.py INPUT [--style waveform|spectrum] [--width W] [--height H] [--fps N]
- [--color C] [--background C] [--waveform-mode M] [--split-channels] [-o OUT]
+ [--color C] [--background C] [--waveform-mode M] [--split-channels]
+ [--image PATH] [--image-fit cover|contain|blur]
+ [--position bottom|centre|top|strip] [--vis-height FRAC] [--opacity 0..1]
+ [--platform NAME] [--srt FILE | --text FILE] [--title TEXT] [--brand brand.json]
+ [-o OUT]
```
Renders the input's audio as a video: `--style waveform` (default, FFmpeg's
`showwaves`) draws amplitude over time; `--style spectrum` (`showspectrum`)
@@ -265,6 +269,29 @@ mixes at the cost of being less immediately readable. The output always
carries the audio it visualizes. For an audio-only input (no video stream
needed) or any file with an audio track worth visualizing.
+**Audiogram (1.16).** `--image PATH` puts a local still behind the
+visualisation, which is what turns a podcast episode into something postable.
+`--image-fit cover` (default) scales to cover and centre-crops; `contain` pads
+with `--background`; `blur` uses fit.py's blurred-pad plate. `--position`
+places the band (`strip`, the default, is a band of `--vis-height` -- a
+fraction of the frame, default 0.35 -- along the bottom, the podcast
+convention); `--opacity` fades the visualisation over the plate. `--platform`
+takes the frame size and fps from the delivery table and refuses a destination
+with no frame (`podcast`) -- the still is fed at that rate, so the plate cannot
+quietly decide the output's frame rate, and the run verifies the rate it
+announced along with the frame size and the duration. `--image` must be a file
+ffmpeg can actually decode: one that is not is refused (`kind: input`) before
+any encode starts. `--title` draws one label through graphics.py's
+sticker template and `--srt`/`--text` burns captions by running caption.py
+afterwards -- both as second processes, so neither of those code paths is
+re-implemented here. `--image` must be a readable local file: a URL is refused
+(`kind: input`), nothing is fetched, and the skill never invents cover art --
+give an image or a colour. Without any of these flags the command line is
+byte-identical to 1.15's. Every run's result carries an `audiogram` object (style,
+background, image, position, vis_height, platform, captions, title, stages,
+verified). `render.py --template audiogram` is the one-call form; it is
+deliberately not part of `--template all`.
+
### freeze.py — hold a frame for N seconds
```
freeze.py INPUT --hold T [--at T] [--mode insert|extend] [-o OUT]
@@ -338,7 +365,10 @@ output; the result says so with `dropped_non_av_streams: true`.
### metadata.py — chapter markers and container tags, streams copied
```
-metadata.py INPUT [--chapters chapters.txt | --clear-chapters]
+metadata.py INPUT [--chapters chapters.txt | --clear-chapters | --auto-chapters]
+ [--min-chapter S] [--max-chapters N] [--from silence|scenes|both]
+ [--silence-threshold dB] [--silence-min S] [--scene-threshold N]
+ [--chapters-out FILE] [--description-out FILE]
[--title T] [--artist A] [--album A] [--comment C] [--date D] [--genre G] [-o OUT]
```
`chapters.txt` holds one chapter per line, `TIME TITLE` (cut.py's time syntax:
@@ -352,6 +382,27 @@ silently dropping them. Tags alone are written to any container that has them.
`--clear-chapters` removes existing markers; an empty tag value (`--comment ""`)
clears that tag.
+**Proposed chapters (1.16).** `--auto-chapters` measures the file's own
+structure instead of reading a file: silencedetect for the pauses (`--from
+silence`), scdet for the scene cuts (`--from scenes`), both by default. A
+chapter starts where speech resumes; a scene cut within 1 s of one is the same
+event and merges to `silence+scene` evidence, which `--max-chapters` never
+drops before a single-evidence marker. `--min-chapter` (default 60, a
+long-form default) is the shortest chapter, and nothing is proposed within it
+of the end of the file. **Two detectors mean two full decodes of the input**
+(`notes` says so); `--from silence` is the cheap path. Every title is
+`Chapter N` and the result says `"titles": "placeholder"`: the skill proposes
+where a chapter starts, it cannot know what is in one -- naming them is the
+caller's job, and asking this skill to do it is a refusal.
+`--chapters-out FILE` writes the proposal in this tool's own `--chapters`
+format, so the titles can be edited and fed straight back;
+`--description-out FILE` writes the YouTube block (`00:00 Chapter 1` per
+line, rounded down to the second). The output is still `-c copy`. An input
+with no video degrades to `--from silence` with a note; an explicit `--from
+scenes` on it is refused, as is `--from silence` on an input with no audio.
+The result gains `auto_chapters` (source, min_chapter, proposed, kept,
+titles, chapters with their evidence, description_block, files).
+
### grid.py — composite clips into a grid
```
grid.py CLIP1 CLIP2 [...] --cols N --rows N [--cell-width W] [--cell-height H]
@@ -440,13 +491,13 @@ complete command plan for review.
### Delivery templates — one command per destination (1.14)
```
render.py --template tiktok INPUT [--cues cues.txt | --srt subs.srt] [--logo logo.png] [--title "..."]
- [--brand brand.json] [--chapters chapters.txt] [--fit crop|pad|blur] [-o OUT]
+ [--brand brand.json] [--chapters chapters.txt] [--image cover.png] [--fit crop|pad|blur] [-o OUT]
render.py --template all INPUT ... # or a comma list: one delivery per destination + <stem>_pack.md
render.py --list-templates # the table below, from the running install
render.py --template tiktok INPUT --write-project project.json # fill it, edit it, render it later
```
A template is a `render.py` project shipped in `templates/<name>.json` with `$INPUT`, `$OUTPUT`,
-`$CUES`/`$SRT`, `$LOGO`, `$TITLE`, `$BRAND` and `$CHAPTERS` placeholders. Filling it substitutes
+`$CUES`/`$SRT`, `$LOGO`, `$TITLE`, `$BRAND`, `$CHAPTERS` and `$IMAGE` placeholders. Filling it substitutes
what the run was given and **drops any block whose placeholder has no value** — no `--logo` means
no overlay stage at all, not an overlay of nothing. The filled project then renders through the
normal stages, so `--dry-run --json`, `--stop-after` and the work directory behave as always. An
@@ -479,6 +530,7 @@ hand-built step:
| `linkedin` | 1080x1080 (1:1) | 600 s | -14 LUFS / -1 dBTP | 0.05 | 0.05 | 0.05 | 0.05 |
| `facebook` | 1920x1080 (16:9) | 14400 s | -14 LUFS / -1 dBTP | 0.05 | 0.05 | 0.05 | 0.05 |
| `podcast` | audio only | — | -16 LUFS / -1 dBTP | 0.00 | 0.00 | 0.00 | 0.00 |
+| `audiogram` | 1920x1080 (16:9), or `--platform` / `--image` | 43200 s | -14 LUFS / -1 dBTP | 0.05 | 0.05 | 0.05 | 0.05 |
`podcast` is audio: silence trim, −16 LUFS / −1 dBTP, chapter markers when `--chapters` is given,
and `check.py --platform podcast`. `--template all` renders `tiktok, reels, shorts, youtube, x,
@@ -487,6 +539,13 @@ linkedin, facebook` (not the audio template, not the `youtube-shorts` alias) int
destination; `report.py --pack <stem>_pack.md` renders that table as a single HTML page. A pack
whose destinations did not all pass exits non-zero with the per-destination rows in `pack`.
+`audiogram` (1.16) is the one-call form of the podcast-to-video job: an `audiogram` stage runs
+**first** (it makes the picture the rest of the chain works on, through `waveform.py --image`),
+then captions, loudness, export and check. It needs `--image` (a local file) or a `background`
+colour in the project — this skill fetches nothing and invents no cover art — and it is
+deliberately **not** part of `--template all`, whose destinations all assume a source that
+already has a picture.
+
### scenes.py — scene changes and highlight candidates
```
scenes.py INPUT [--threshold 10] [--min-scene 1] [--highlights N [--target SECONDS] [--max-scene 15]] [--edl picks.txt] [--sheet scenes.png] [--json]
@@ -551,9 +610,13 @@ graphics.py INPUT --template lower-third|title|chapter|progress|countdown|bug|st
[--name] [--title] [--subtitle] [--text] [--top] [--bottom] [--duration 3]
[--from N] [--start S] [--end E] [--position CORNER] [--margin PX] [--platform NAME]
[--brand brand.json] [--primary RRGGBB] [--scale 1.0] [--lang XX]
- [--text-render auto|ass|drawtext] [--write-ass OUT.ass]
+ [--wrap phrase|measured] [--text-render auto|ass|drawtext] [--write-ass OUT.ass]
[--emoji auto|color|png|mono|none] [--emoji-assets DIR] [--emoji-scale 1.0] [--emoji-max 60] [-o OUT]
```
+Since 1.16 a label too wide for the frame is broken into lines by the same phrase-aware wrap
+caption.py uses (`--wrap phrase|measured`; see caption.py above) instead of running off the edge —
+the hook card, the meme lines and the sticker chip. A label that already fits is untouched.
+
Drawn with drawbox/drawtext/overlay — no PNG assets needed. Sizes scale with
the frame's short side; colours, font and safe margin come from `--brand`.
Lower-third slides in over 0.4 s and out over 0.3 s; title/chapter/bug fade.
@@ -658,9 +721,10 @@ rather than about the file.
### caption.py — subtitles (static, animated, karaoke)
```
-caption.py INPUT --srt FILE | --ass FILE | --text CUES.txt [--write-srt OUT.srt]
- [--mode burn|mux] [--audio-stream N] [--fps N] [--lang XX] [--offset TIME]
- [--max-lines N] [--min-duration S]
+caption.py INPUT --srt FILE[:LANG] | --ass FILE | --text CUES.txt [--write-srt OUT.srt]
+ [--mode burn|mux] [--srt FILE:LANG ...] [--track-title T ...] [--default-track LANG]
+ [--audio-stream N] [--fps N] [--lang XX] [--offset TIME]
+ [--max-lines N] [--min-duration S] [--wrap phrase|measured]
[--font NAME] [--fonts-dir DIR] [--size N] [--color RRGGBB] [--outline N] [--outline-color RRGGBB]
[--bold] [--box] [--position bottom|top|center|top-left|...] [--margin N]
[--animate none|fade|pop|slide] [--karaoke [--highlight-color RRGGBB]] [--write-ass OUT.ass]
@@ -708,6 +772,55 @@ comes from, but nothing is written until the real run. `--min-duration` and
`--offset` also work with `--write-srt` alone; `--max-lines` does not, because
wrapping needs the input video's real frame size.
+Phrase-aware breaking (1.16), `--wrap phrase` (default) — four rules over the
+break positions that already fit, so a line is never widened and the line count
+never changes: **R1** never inside a word, and a hyphenated token may break only
+after its hyphen (never after a non-breaking `‑`, nor a leading/trailing
+one); **R2** no line that is a lone digit, one or two punctuation characters, or
+a single kana, checked at every boundary rather than only the last; **R3** for
+Japanese and Chinese, a break is preferred after `。、!?」』)` and (Japanese
+only) after a particle — a particle attaches to the word before it, so kinsoku
+forbids opening a line with one — discouraged between a kanji stem and its
+okurigana, and forbidden before a small kana, `ー` or a closing bracket; **R4**
+for en/es/pt/fr/de/it, an article or preposition is kept with the phrase it
+governs: the break before it is preferred and the break after it penalised (a
+frozen table, matched case-folded; `--lang`, else the script detector, picks the
+set, and with no language the union of the six is used). `--wrap measured` is 1.15's
+width-only wrap exactly, kept so an older split can be reproduced. The result's
+`caption` object carries the layout counts plus `wrap` and `phrase_breaks`.
+graphics.py takes the same flag for the labels that can hold more than one line
+(the hook card, the meme lines, the sticker chip). The breaker never rewrites,
+shortens or translates the text: a cue that cannot fit `--max-lines` is split
+into consecutive cues, as it always was.
+
+Several languages in one file (1.16): `--srt` is repeatable and each file may
+carry a `:lang` suffix — `--mode mux --srt en.srt:en --srt ja.srt:ja --srt
+es.srt:es -o ep.mkv` writes one deliverable with three language-tagged,
+toggleable streams and copies the video and audio bit for bit. The suffix splits
+on the last colon, and only when the tail is a BCP-47-shaped code *and* the whole
+token is not itself a file on disk, so `C:\subs\en.srt` and a file named
+`a:b.srt` are never mangled; a single `--srt` with no suffix still takes
+`--language`. `--track-title` names a track (repeated in `--srt` order;
+otherwise a frozen display-name table, and a code the table does not know gets
+the code itself — never a guessed or translated name), `--default-track LANG`
+marks one for auto-selection. Every other new track is explicitly marked *not*
+default, because ffmpeg otherwise flags the first one itself -- so with no
+`--default-track` a Matroska file really does leave every track off. Two tracks with the same code, a
+code that is not BCP-47-shaped, a `--default-track` no track carries, and more
+than one `--srt` with `--mode burn` are all refused. **Container note:** `.mp4`
+and `.mov` accept several `mov_text` tracks but many players show only the
+first, and MPEG-4 stores an ISO-639-2 code — a two-letter one is silently
+dropped, so this tool converts it (`en` → `eng`); Matroska keeps the code you
+give. Past two tracks in an MPEG-4 container the result carries a note
+recommending `.mkv`. Two further MPEG-4 limits are reported rather than papered
+over: it has no per-track title the muxer writes back (so `tracks[].title` is
+`null` there, with a note) and it always enables its first subtitle track
+whatever disposition is asked for (so that track is reported `default: true`,
+again with a note). `.mkv` has neither limit. The result gains `tracks` and `subtitle_tracks`; check.py
+prints an informational `subtitles` row (WARN for an untagged stream, never
+counted in `failed`). The skill never translates and never generates a second
+language.
+
Fonts by script (1.12): with no `--font` and no font named in your brand file, the
script of the cue text (Japanese, Chinese, Korean, Arabic, Hebrew, Devanagari,
Thai, Cyrillic, Greek) picks a font file that covers it, logged as `font: <file>
diff --git a/scripts/_common/__init__.py b/scripts/_common/__init__.py
index 2f59ed6..89e8c44 100644
--- a/scripts/_common/__init__.py
+++ b/scripts/_common/__init__.py
@@ -66,11 +66,13 @@ from _common.emit import (
PLAN_VERSION, print_json, _result_v2, _set_current_ctx, _V2_HANDLED, write_plan
)
from _common.probe import (
- analyze_levels, _aspect_string, _bit_depth, decode_pcm_mono, fingerprint, _fraction, keyframes_near,
+ analyze_levels, _aspect_string, _bit_depth, decode_pcm_mono, detect_scenes, detect_silences, fingerprint,
+ _fraction, keyframes_near, SCORE_RE, SIL_RE,
measured_level_dbfs, MEDIA_EXT, _output_failed, probe, rms_envelope, _to_float, _to_int, verify_output
)
from _common.decision import (
aac_args, add_pad_fill_args, audio_codec_for, AUDIO_CODECS, brand_caption_style, BRAND_DEFAULTS,
+ description_block, _evidence_rank, fmt_chapter_time, propose_chapters,
brand_states_font, cfr_args, concat_list_line, db_to_linear, default_output, encoder_args, escape_filter_path,
fmt_secs, fmt_smpte_time, fmt_srt_time, is_audio_output, load_brand, MissingFpsError, pad_filters, parse_time,
signed_time_arg, SVT_PRESET, time_arg, video_args, x264_args, _x264_raw
@@ -87,6 +89,13 @@ from _common.text import (
font_for_script, FONT_INSTALL_HINT, fonts_dir_covers_script, has_emoji, _is_emoji_base, _is_emoji_char,
_is_mark, _KEYCAP, _KEYCAP_BASES, LANGUAGE_NAMES, LATIN_EM, LEADING_VOWELS, _libass_color_probe, needs_shaping,
NO_SPACE_SCRIPTS, PREFERRED_FAMILIES, resolve_emoji_assets, _SCRIPT_FONT_CACHE, _script_font_entry,
+ _atoms, best_break, _bare_word, break_penalty, _break_spaced, _cut_penalty, _fix_orphans, _fix_weak_lines,
+ _function_words, FUNCTION_WORDS, _HYPHENS, _is_hiragana, _is_ideograph, _is_kana, _is_weak_line,
+ JA_NO_LINE_END, JA_NO_LINE_START, JA_PARTICLE_WORDS, JA_PARTICLES, JA_SENTENCE_END, _join, ORPHAN_MIN_EM,
+ PENALTY_FORBIDDEN, PENALTY_FUNCTION_WORD, PENALTY_FUNCTION_WORD_START, PENALTY_IDEOGRAPHS,
+ PENALTY_NEUTRAL, PENALTY_OKURIGANA,
+ PENALTY_PARTICLE, PENALTY_SENTENCE_END, _rebalance, _rebalance_phrase, SAFE_WIDTH_FRACTION, _split_hyphens,
+ _particle_ends, _particle_starts, wrap_text, wrap_variants, WRAP_MODES,
script_font_for_text, script_font_status, _script_font_uncached, _SCRIPT_RANGES, SCRIPTS, _SHAPING_BUILD_CACHE,
SHAPING_SCRIPTS, text_width_em, _VS15, _VS16, WINDOWS_FONTS, _ZWJ
)
@@ -153,12 +162,12 @@ sys.modules[__name__].__class__ = _Facade
__all__ = [
"Any", "Dict", "Fraction", "List", "Optional", "Path", "Sequence", "Tuple", "argparse", "json", "math", "os",
"platform", "re", "shutil", "subprocess", "sys", "unicodedata",
- "aac_args", "add_common", "add_pad_fill_args", "ADVANCE_EM", "analyze_levels", "apply_common", "_aspect_string",
+ "aac_args", "add_common", "add_pad_fill_args", "ADVANCE_EM", "analyze_levels", "apply_common", "detect_scenes", "detect_silences", "SCORE_RE", "SIL_RE", "_aspect_string",
"audio_codec_for", "AUDIO_CODECS", "BIDI_SCRIPTS", "_bit_depth", "brand_caption_style", "BRAND_DEFAULTS",
"brand_states_font", "_brief", "_BRIEF_DROP", "_brief_summary", "bt709_tag_args", "cfr_args", "_char_em",
"char_script", "_check_existing_output", "_check_no_overwrite_input", "_check_output_path", "child_args",
"child_limit", "_CHILDREN", "_cleanup_partial_output", "_cmdline", "CODECS", "color_hex", "_COLOR_TOKEN_RE",
- "concat_list_line", "Context", "_CRF_DEFAULT", "_CURRENT_CTX", "db_to_linear", "decode_pcm_mono",
+ "concat_list_line", "Context", "_CRF_DEFAULT", "_CURRENT_CTX", "db_to_linear", "decode_pcm_mono", "description_block", "_evidence_rank", "fmt_chapter_time", "propose_chapters",
"default_font_file", "default_output", "DEFAULT_TIMEOUT", "detect_script", "die", "drawtext_boxborderw",
"_DRAWTEXT_PENDING", "drawtext_shaping", "drawtext_text_opts", "_DRAWTEXT_TMPDIR", "_drawtext_tmpdir",
"dry_run_input_pending", "emit", "emoji_asset_for", "EMOJI_ASSET_HINT", "emoji_clusters",
@@ -183,5 +192,13 @@ __all__ = [
"_SIGNALS_INSTALLED", "signed_time_arg", "_stage_existing_output", "STATE", "SVT_PRESET", "text_width_em",
"time_arg", "_timed_out", "_to_float", "_to_int", "_unwatch", "_V2_HANDLED", "validate_color", "verify_output",
"video_args", "_VS15", "_VS16", "_watch", "WINDOWS_FONTS", "write_plan", "x264_args", "X264_PRESETS",
- "_x264_raw", "_ZWJ"
+ "_x264_raw", "_ZWJ",
+ "_atoms", "best_break", "_bare_word", "break_penalty", "_break_spaced", "_cut_penalty", "_fix_orphans",
+ "_fix_weak_lines", "_function_words", "FUNCTION_WORDS", "_HYPHENS", "_is_hiragana", "_is_ideograph",
+ "_is_kana", "_is_weak_line", "JA_NO_LINE_END", "JA_NO_LINE_START", "JA_PARTICLE_WORDS", "JA_PARTICLES",
+ "PENALTY_FUNCTION_WORD_START",
+ "JA_SENTENCE_END", "_join", "ORPHAN_MIN_EM", "PENALTY_FORBIDDEN", "PENALTY_FUNCTION_WORD",
+ "PENALTY_IDEOGRAPHS", "PENALTY_NEUTRAL", "PENALTY_OKURIGANA", "PENALTY_PARTICLE", "PENALTY_SENTENCE_END",
+ "_rebalance", "_rebalance_phrase", "SAFE_WIDTH_FRACTION", "_split_hyphens", "_particle_ends",
+ "_particle_starts", "wrap_text", "wrap_variants", "WRAP_MODES"
]
diff --git a/scripts/_common/decision.py b/scripts/_common/decision.py
index 90dae5c..9a1f1b4 100644
--- a/scripts/_common/decision.py
+++ b/scripts/_common/decision.py
@@ -10,7 +10,7 @@ import json
import os
import argparse
from pathlib import Path
-from typing import Any, Dict, List, Optional
+from typing import Any, Dict, List, Optional, Sequence
from _common.color import bt709_tag_args, _sdr_bt709
from _common.emit import die
from _common.runner import CODECS, STATE, ffmpeg_encoders
@@ -413,3 +413,108 @@ def brand_caption_style(brand: Dict[str, Any]) -> Dict[str, Any]:
style["color"] = style.pop("colour")
style.pop("colour", None)
return style
+
+
+# ------------------------------------------------------------------- chapter proposal (1.16)
+
+def fmt_chapter_time(t: float) -> str:
+ """The YouTube description convention: `00:00`, `03:12`, `1:02:03` past the hour, always
+ rounded DOWN to the second so the timestamp never lands after the moment it names."""
+ total = max(0, int(t))
+ h, rem = divmod(total, 3600)
+ m, sec = divmod(rem, 60)
+ if h:
+ return f"{h}:{m:02d}:{sec:02d}"
+ return f"{m:02d}:{sec:02d}"
+
+
+def _evidence_rank(ev: Dict[str, Any]) -> tuple:
+ """How strong a candidate is, for the drop order: both detectors beat a silence, a silence
+ beats a scene cut, and within a kind the longer pause / higher score wins."""
+ kind = ev.get("kind")
+ tier = {"start": 3, "silence+scene": 2, "silence": 1, "scene": 0}.get(kind, 0)
+ within = float(ev.get("silence_length") or ev.get("score") or 0.0)
+ return (tier, within)
+
+
+def propose_chapters(duration: float, silences: "Sequence", scene_cuts: "Sequence", *,
+ min_chapter: float = 60.0, max_chapters: int = 0,
+ source: str = "both") -> "List[Dict[str, Any]]":
+ """Chapter markers proposed from measured structure. Pure: the detectors' outputs go in,
+ a list of `{"at", "title", "evidence"}` comes out, and nothing is decoded here.
+
+ A chapter starts where speech RESUMES, so a silence contributes its `end`, not its midpoint.
+ A scene cut within 1 s of such a point is the same event seen twice and is merged into one
+ candidate with `kind: "silence+scene"`, which the `--max-chapters` cap never drops before a
+ single-evidence one. Candidates closer than `min_chapter` to the one already kept are dropped,
+ stronger evidence winning; so is anything inside `min_chapter` of the end of the file.
+
+ Every title is `Chapter N`. The function never looks at, and never invents, content: naming a
+ chapter needs knowing what is said in it, which is the calling agent's job, not this skill's.
+ """
+ duration = float(duration or 0.0)
+ min_chapter = max(0.0, float(min_chapter))
+ candidates: "List[Dict[str, Any]]" = []
+ if source in ("silence", "both"):
+ for span in silences or []:
+ start, end = float(span[0]), span[1]
+ if end is None or end == float("inf"):
+ continue
+ end = float(end)
+ candidates.append({"at": end, "evidence": {
+ "kind": "silence", "silence": [round(start, 3), round(end, 3)],
+ "silence_length": round(end - start, 3)}})
+ if source in ("scenes", "both"):
+ for cut in scene_cuts or []:
+ cut = float(cut)
+ if cut <= 0.0:
+ continue # scenes.py always reports 0.0 as the first cut; that is the start
+ candidates.append({"at": cut, "evidence": {"kind": "scene", "scene_at": round(cut, 3)}})
+
+ # merge a scene cut that stands within 1 s of a silence end: one event, two witnesses
+ candidates.sort(key=lambda c: c["at"])
+ merged: "List[Dict[str, Any]]" = []
+ for cand in candidates:
+ prior = merged[-1] if merged else None
+ if prior and abs(cand["at"] - prior["at"]) <= 1.0 and \
+ {prior["evidence"]["kind"], cand["evidence"]["kind"]} == {"silence", "scene"}:
+ ev = dict(prior["evidence"])
+ ev.update(cand["evidence"])
+ ev["kind"] = "silence+scene"
+ silence_first = prior["evidence"]["kind"] == "silence"
+ prior["at"] = prior["at"] if silence_first else cand["at"]
+ prior["evidence"] = ev
+ continue
+ merged.append(dict(cand))
+
+ kept: "List[Dict[str, Any]]" = [{"at": 0.0, "evidence": {"kind": "start"}}]
+ for cand in merged:
+ if duration and cand["at"] >= duration - min_chapter:
+ continue
+ last = kept[-1]
+ if cand["at"] - last["at"] < min_chapter:
+ # too close to the marker already kept: keep whichever the evidence supports better,
+ # never replacing the 0.0 start
+ if last["evidence"]["kind"] != "start" and \
+ _evidence_rank(cand["evidence"]) > _evidence_rank(last["evidence"]) and \
+ (len(kept) < 2 or cand["at"] - kept[-2]["at"] >= min_chapter):
+ kept[-1] = dict(cand)
+ continue
+ kept.append(dict(cand))
+
+ if max_chapters and len(kept) > max_chapters:
+ # drop the weakest evidence first, never index 0, then put the survivors back in order
+ order = sorted(range(1, len(kept)),
+ key=lambda i: (_evidence_rank(kept[i]["evidence"]), -kept[i]["at"]))
+ drop = set(order[:len(kept) - max_chapters])
+ kept = [c for i, c in enumerate(kept) if i not in drop]
+
+ for n, chapter in enumerate(kept, start=1):
+ chapter["at"] = round(chapter["at"], 3)
+ chapter["title"] = f"Chapter {n}"
+ return kept
+
+
+def description_block(chapters: "Sequence") -> str:
+ """The YouTube description form of a chapter list: `00:00 Chapter 1` per line."""
+ return "\n".join(f"{fmt_chapter_time(c['at'])} {c['title']}" for c in chapters)
diff --git a/scripts/_common/probe.py b/scripts/_common/probe.py
index 54cc2a5..3ac3eeb 100644
--- a/scripts/_common/probe.py
+++ b/scripts/_common/probe.py
@@ -10,9 +10,9 @@ import math
import os
import re
from fractions import Fraction
-from typing import Any, Dict, List, Optional, Sequence
+from typing import Any, Dict, List, Optional, Sequence, Tuple
from _common.emit import die
-from _common.runner import STATE, require_tool, run, run_analysis
+from _common.runner import STATE, dry_run_input_pending, require_tool, run, run_analysis
def fingerprint(path: str) -> Dict[str, Any]:
@@ -380,3 +380,93 @@ def _aspect_string(w: Optional[int], h: Optional[int]) -> Optional[str]:
return None
f = Fraction(w, h)
return f"{f.numerator}:{f.denominator}"
+
+
+# --------------------------------------------------------------- structure detectors (1.16)
+# silencedetect and scdet, lifted out of silence.py and scenes.py byte-for-byte in 1.16.0 so that
+# metadata.py --auto-chapters can measure structure without importing another tool (no script in
+# scripts/ imports a sibling tool; only the _-prefixed modules are shared). silence.py and
+# scenes.py import them back from here, so their behaviour is unchanged.
+
+SIL_RE = re.compile(r"silence_(start|end): ([0-9.]+)")
+
+
+def detect_silences(path: str, threshold: float, min_silence: float) -> "List[Tuple[float, float]]":
+ if dry_run_input_pending(path):
+ return []
+ ffmpeg = require_tool("ffmpeg")
+ cmd = [ffmpeg, "-hide_banner", "-nostdin", "-i", path, "-vn", "-af",
+ f"silencedetect=noise={threshold}dB:d={min_silence}", "-f", "null", "-"]
+ proc = run_analysis(cmd, check=False, record=True)
+ if proc.returncode != 0:
+ die(f"silencedetect failed:\n{proc.stderr.strip()[-800:]}", kind="ffmpeg")
+ silences: "List[Tuple[float, float]]" = []
+ start = None
+ for kind, val in SIL_RE.findall(proc.stderr):
+ if kind == "start":
+ start = float(val)
+ elif start is not None:
+ silences.append((start, float(val)))
+ start = None
+ if start is not None: # silence runs to the end
+ silences.append((start, float("inf")))
+ return silences
+
+
+SCORE_RE = re.compile(r"frame:(\d+)\s+pts:\d+\s+pts_time:([0-9.]+)")
+
+
+def detect_scenes(path: str, threshold: float, min_len: float, duration: float, ratio: float = 3.0) -> "List[float]":
+ """Scene cuts = frames whose scdet score is above `threshold` AND stands out from its
+ neighbourhood (score > ratio x median of the surrounding +-12 frames). Sustained motion,
+ flashes and fast pans raise the score on many consecutive frames and are rejected;
+ a real cut is a one-frame spike. On real footage this roughly doubles precision at
+ equal recall compared with the raw scdet threshold."""
+ ffmpeg = require_tool("ffmpeg")
+ proc = run_analysis([ffmpeg, "-hide_banner", "-nostdin", "-i", path, "-an", "-vf",
+ "scale=320:-2,scdet=threshold=0,metadata=print:file=-", "-f", "null", "-"])
+ # No `sc_pass=1` on scdet: on FFmpeg 5.x that option means "pass only the frames whose
+ # score exceeds the threshold", so every truly static frame (score exactly 0 -- a title
+ # card, colour bars) is dropped before metadata=print and the frame numbers are re-counted
+ # without them. The +-12-frame neighbourhood around a real cut then fills with the moving
+ # segment's scores instead of the still one's zeros, the cut fails the ratio test, and a
+ # 4 s smptebars scene made the cuts on both sides of it disappear (found by the 5.1.1 CI
+ # job, #146). 6.1+ passes every frame either way. Scores are still indexed by frame number
+ # and any frame the filter did not report counts as 0, so a build that drops frames again
+ # cannot shift the neighbourhood.
+ by_frame: "Dict[int, Tuple[float, float]]" = {}
+ cur = None
+ for line in proc.stdout.splitlines():
+ m = SCORE_RE.match(line)
+ if m:
+ cur = (int(m.group(1)), float(m.group(2)))
+ continue
+ if line.startswith("lavfi.scd.score=") and cur is not None:
+ try:
+ by_frame[cur[0]] = (cur[1], float(line.split("=", 1)[1]))
+ except ValueError:
+ pass
+ cuts = [0.0]
+ if not by_frame:
+ return cuts
+ n_frames = max(by_frame) + 1
+ times: "List[float]" = [by_frame[i][0] if i in by_frame else -1.0 for i in range(n_frames)]
+ scores: "List[float]" = [by_frame[i][1] if i in by_frame else 0.0 for i in range(n_frames)]
+ w = 12
+ for i, sc in enumerate(scores):
+ if sc < threshold:
+ continue
+ lo, hi = max(0, i - w), min(len(scores), i + w + 1)
+ neigh = sorted(scores[lo:i] + scores[i + 1:hi])
+ med = neigh[len(neigh) // 2] if neigh else 0.0
+ if sc < ratio * max(med, 0.5):
+ continue
+ # keep only the local maximum inside +-2 frames
+ if any(scores[j] > sc for j in range(max(0, i - 2), min(len(scores), i + 3)) if j != i):
+ continue
+ t = times[i]
+ if t - cuts[-1] >= min_len:
+ cuts.append(t)
+ if duration - cuts[-1] < min_len and len(cuts) > 1:
+ cuts.pop()
+ return cuts
diff --git a/scripts/_common/text.py b/scripts/_common/text.py
index aeda971..87d1865 100644
--- a/scripts/_common/text.py
+++ b/scripts/_common/text.py
@@ -978,3 +978,538 @@ def drawtext_text_opts(text: str, tmpdir: "Optional[str]" = None) -> str:
path = os.path.join(tmpdir, name)
_DRAWTEXT_PENDING[path] = cleaned
return f"textfile={escape_filter_path(path)}:expansion=none"
+
+
+# --------------------------------------------------------------- caption line breaking (1.16)
+# Lifted out of caption.py in 1.16.0 so graphics.py can wrap the same way (caption.py keeps the
+# names it exported, re-imported from here). The whole breaker is pure: a string in, a list of
+# lines out, no subprocess and no probe, which is what makes the eval regression corpus cheap
+# to lock down in unit tests.
+
+# How much of the frame width a caption line may use. libass's own default SRT margins are 10 of a
+# 384-wide script (2.6 % a side); 5 % a side is the safe area every platform check in this repo uses.
+SAFE_WIDTH_FRACTION = 0.9
+# ORPHAN_MIN_EM: one full-width CJK/Thai character plus a hair. A last line narrower than this is a
+# single stranded character -- eval 14's th1 (a lone 'ล') and dl3 (a lone '行').
+ORPHAN_MIN_EM = 1.1
+
+WRAP_MODES = ("phrase", "measured")
+
+# R3's Japanese preference table. These are *preferences* applied only among positions that
+# already fit the line, so the table can never make a line too wide or change the line count.
+#
+# JA_PARTICLES is a "do not strand at the start of a line" table, which is the direction kinsoku
+# practice actually goes: a particle is enclitic -- it attaches to the word BEFORE it and marks
+# that word's role -- so a line beginning with は or が reads as a fragment torn off its phrase.
+# A break AFTER a particle is therefore preferred (the particle stays with what it marks) and a
+# break BEFORE one is forbidden. The list is the eight case/topic particles named in the 1.16.0
+# task brief (は が を に で と の へ) plus も や から まで より, which a reader of Japanese would
+# add for the same reason. It is a judgement call with no upstream source; treat it as tunable
+# data, not as grammar.
+JA_PARTICLES = "はがをにでとのへもや" # a break AFTER one of these is preferred, BEFORE one forbidden
+# The multi-character members of the same table. They are matched as whole strings against the
+# text on each side of a candidate break -- putting them in the character string above turned
+# か, ら, ま, で, よ and り into one-character particles of their own, which none of them is.
+JA_PARTICLE_WORDS = ("から", "まで", "より")
+JA_SENTENCE_END = "。、!?」』)" # a break AFTER one of these is preferred
+# Characters that may never start a line: small kana, the prolonged sound mark, closing brackets
+# and the Japanese punctuation that hangs on the end of the line before it.
+JA_NO_LINE_START = "ぁぃぅぇぉっゃゅょァィゥェォッャュョーヽヾゝゞ、。!?)」』】〕》’”%"
+JA_NO_LINE_END = "(「『【〔《‘“" # ... and the ones that may never end a line
+
+# R4. Function words belong to the phrase that FOLLOWS them: an article or preposition begins the
+# noun phrase it governs, so a break before one is the good break (the word opens the next line
+# with its phrase) and a break after one is the bad break (it is stranded at the end of a line,
+# away from what it governs). Both directions are scored, which is what makes the rule decide
+# rather than merely veto. Frozen data, matched case-folded on the atom with its punctuation
+# stripped; six languages because those are the Latin-script languages the eval corpus covers. A
+# word in several sets means the same thing structurally in each, so the union is used when no
+# --lang was given.
+FUNCTION_WORDS = {
+ "en": {"a", "an", "the", "of", "to", "in", "on", "at", "for", "with", "by", "from", "and",
+ "or", "as", "is", "it", "its", "this", "that", "into", "than", "but", "so"},
+ "es": {"el", "la", "los", "las", "un", "una", "unos", "unas", "de", "del", "al", "en", "con",
+ "por", "para", "y", "o", "que", "su", "sus", "lo", "se", "es"},
+ "pt": {"o", "a", "os", "as", "um", "uma", "de", "do", "da", "dos", "das", "em", "no", "na",
+ "nos", "nas", "com", "por", "para", "e", "que", "se", "ao", "aos"},
+ "fr": {"le", "la", "les", "un", "une", "de", "du", "des", "à", "au", "aux", "en", "dans",
+ "et", "ou", "que", "qui", "ce", "ces", "son", "sa", "ses", "par", "pour", "avec", "sur"},
+ "de": {"der", "die", "das", "ein", "eine", "einen", "einem", "einer", "den", "dem", "des",
+ "zu", "in", "im", "auf", "mit", "und", "oder", "von", "vom", "für", "aus", "an"},
+ "it": {"il", "lo", "la", "i", "gli", "le", "un", "una", "uno", "di", "del", "della", "da",
+ "in", "nel", "con", "per", "e", "che", "su", "al", "ai"},
+}
+_FUNCTION_WORDS_ANY = frozenset().union(*FUNCTION_WORDS.values())
+
+# Penalty scores. Only the ordering matters; 1.0 means "never choose this if anything else fits".
+PENALTY_FORBIDDEN = 1.0
+PENALTY_OKURIGANA = 0.9 # between a kanji stem and the hiragana that inflects it
+PENALTY_FUNCTION_WORD = 0.8 # R4: the line before the break ends in an article/preposition
+PENALTY_IDEOGRAPHS = 0.6 # between two kanji: no evidence either way, mildly discouraged
+PENALTY_NEUTRAL = 0.5 # between two content words, or two characters with nothing to say
+PENALTY_FUNCTION_WORD_START = 0.2 # R4: the next line opens with the article/preposition it governs
+PENALTY_PARTICLE = 0.2 # R3: after a particle, so the particle stays with the word it marks
+PENALTY_SENTENCE_END = 0.0 # R3: after 。、!? -- the one break a reader expects
+
+_HYPHENS = ("-", "‐") # ‑ (non-breaking hyphen) is deliberately NOT here
+
+
+def _atoms(line: str) -> "List[Tuple[str, bool]]":
+ """Break a line into the smallest pieces a wrap may separate -- one atom per CJK/Thai
+ character, one per emoji cluster, one per whitespace-delimited word otherwise -- each with
+ whether a space stood before it in the original. The flag is what puts the text back together
+ exactly as written: "Hello 世界" keeps its space, "世界です" gains none."""
+ out: "List[Tuple[str, bool]]" = []
+ word = ""
+ spaced = False # a space stands before the atom being built
+ pending = False # a space stands before the NEXT atom
+ attach_next = False # a leading Thai/Lao vowel is waiting for its base consonant
+ # An emoji cluster is one atom: a wrap must never land inside a ZWJ sequence, a flag pair or
+ # between a base and its skin-tone modifier (the same rule combining marks already follow).
+ clusters = {i: len(cl) for i, cl in emoji_clusters(line)}
+ i = 0
+ while i < len(line):
+ ch = line[i]
+ if i in clusters:
+ cluster = line[i:i + clusters[i]]
+ if word:
+ out.append((word, spaced))
+ word = ""
+ out.append((cluster, pending))
+ pending = False
+ attach_next = False
+ i += clusters[i]
+ continue
+ i += 1
+ if char_script(ch) in NO_SPACE_SCRIPTS:
+ if word:
+ out.append((word, spaced))
+ word = ""
+ if out and (attach_next or _is_mark(ch)):
+ # never break between a base and the mark (or the leading vowel) that belongs to
+ # it: the line would start with an orphaned tone mark or vowel sign
+ out[-1] = (out[-1][0] + ch, out[-1][1])
+ else:
+ out.append((ch, pending))
+ pending = False
+ attach_next = ord(ch) in LEADING_VOWELS
+ elif ch.isspace():
+ if word:
+ out.append((word, spaced))
+ word = ""
+ pending = True
+ else:
+ if not word:
+ spaced, pending = pending, False
+ word += ch
+ if word:
+ out.append((word, spaced))
+ return out
+
+
+def _split_hyphens(atoms: "List[Tuple[str, bool]]") -> "List[Tuple[str, bool]]":
+ """R1's one addition to the atom list: a hyphenated token may break *after* its hyphen.
+
+ "end-to-end" becomes `end-` / `to-` / `end`, each piece carrying the space flag of the token
+ it came from for the first piece and False for the rest, so _join() puts it back with no space
+ at all. A hyphen that is the first or last character of the token (`-5`, `well-`) is never a
+ break point: the guard is that both sides must be non-empty."""
+ out: "List[Tuple[str, bool]]" = []
+ for atom, spaced in atoms:
+ if len(atom) < 3 or not any(h in atom[1:-1] for h in _HYPHENS):
+ out.append((atom, spaced))
+ continue
+ piece = ""
+ first = True
+ for i, ch in enumerate(atom):
+ piece += ch
+ if ch in _HYPHENS and 0 < i < len(atom) - 1:
+ out.append((piece, spaced if first else False))
+ piece = ""
+ first = False
+ if piece:
+ out.append((piece, spaced if first else False))
+ return out
+
+
+def _join(left: str, atom: str, spaced: bool) -> str:
+ """Put an atom back on a line, restoring the space that stood before it."""
+ if not left:
+ return atom
+ return left + (" " if spaced else "") + atom
+
+
+def _break_spaced(first: str, second: str) -> bool:
+ """Did a space stand at the break between these two wrapped lines? Only spaced scripts put one
+ there -- a CJK/Thai break sits between two characters that were written with nothing between
+ them, and re-joining them with a space would insert a character the cue never had."""
+ if not first or not second:
+ return False
+ return char_script(first[-1]) not in NO_SPACE_SCRIPTS and char_script(second[0]) not in NO_SPACE_SCRIPTS \
+ and char_script(first[-1]) != "emoji" and char_script(second[0]) != "emoji"
+
+
+def _is_kana(ch: str) -> bool:
+ return 0x3040 <= ord(ch) <= 0x30FF
+
+
+def _is_hiragana(ch: str) -> bool:
+ return 0x3040 <= ord(ch) <= 0x309F
+
+
+def _is_ideograph(ch: str) -> bool:
+ cp = ord(ch)
+ return 0x3400 <= cp <= 0x4DBF or 0x4E00 <= cp <= 0x9FFF or 0xF900 <= cp <= 0xFAFF
+
+
+def _is_weak_line(line: str) -> "bool":
+ """A line no reader should be given on its own (R2).
+
+ 1.15 asked only "is the last line one atom narrower than ORPHAN_MIN_EM", which a full-width
+ character passes: dl3 still showed a lone `2` and a stranded `行`. Three cases instead, any of
+ which makes a line too thin to stand alone:
+ - a single character narrower than ORPHAN_MIN_EM (1.15's rule, kept);
+ - nothing but digits, punctuation and symbols, at most two characters ("2", "--");
+ - a single kana, whatever its width -- a kana is a full em and passes the width test, but a
+ line holding one is a syllable, not a word.
+ """
+ stripped = (line or "").strip()
+ if not stripped:
+ return True
+ if len(stripped) == 1 and text_width_em(stripped) < ORPHAN_MIN_EM:
+ return True
+ if len(stripped) <= 2 and all(unicodedata.category(c)[0] in "NPS" for c in stripped):
+ return True
+ if len(stripped) == 1 and char_script(stripped) == "ja" and _is_kana(stripped):
+ return True
+ return False
+
+
+def _function_words(lang: "Optional[str]") -> "frozenset":
+ """R4's table for this language. An unknown or absent language gets the union of the six sets:
+ a token that appears in several of them is the same kind of word in each, which is why the
+ rule is a penalty and not a refusal."""
+ key = (lang or "").strip().lower().split("-")[0]
+ if key in FUNCTION_WORDS:
+ return frozenset(FUNCTION_WORDS[key])
+ return _FUNCTION_WORDS_ANY
+
+
+def _bare_word(atom: str) -> str:
+ return "".join(c for c in (atom or "") if c.isalpha() or c == "'").strip("'").lower()
+
+
+def _particle_starts(text: str) -> bool:
+ """Does `text` begin with a particle -- one character, or one of the two-character ones?"""
+ if not text:
+ return False
+ return text[0] in JA_PARTICLES or text.startswith(JA_PARTICLE_WORDS)
+
+
+def _particle_ends(text: str) -> bool:
+ """Does `text` end with a particle? `から` counts, a bare `ら` does not."""
+ if not text:
+ return False
+ return text[-1] in JA_PARTICLES or text.endswith(JA_PARTICLE_WORDS)
+
+
+def break_penalty(prev_char: str, next_char: str, lang: "Optional[str]" = None,
+ before: str = "", after: str = "") -> float:
+ """How bad a break between these two characters is, 0.0 (preferred) to 1.0 (forbidden).
+
+ Only consulted among break positions that already fit `max_em`, so a preference can never
+ widen a line or change the line count. Japanese gets the particle half of the table -- a break
+ AFTER a particle is preferred and a break BEFORE one forbidden, because a particle attaches to
+ the word before it; Chinese gets only the sentence-end and forbidden halves, because particles
+ are Japanese grammar.
+
+ `before`/`after` are the text on each side of the break when the caller has it, which is what
+ lets the two-character particles (から/まで/より) be matched as words. Without them only the
+ single-character table applies."""
+ if not prev_char or not next_char:
+ return PENALTY_NEUTRAL
+ script = (lang or "").strip().lower().split("-")[0]
+ if script not in ("ja", "zh"):
+ # A kana on either side settles it: only Japanese has them, and char_script() reads a bare
+ # Han character as Chinese, which used to switch the particle rules off for exactly the
+ # break they exist to judge (`...が|決まる` -- kana before, kanji after).
+ if _is_kana(prev_char) or _is_kana(next_char):
+ script = "ja"
+ else:
+ script = char_script(next_char)
+ if script not in ("ja", "zh"):
+ script = char_script(prev_char)
+ if next_char in JA_NO_LINE_START or prev_char in JA_NO_LINE_END or _is_mark(next_char):
+ return PENALTY_FORBIDDEN
+ if script not in ("ja", "zh"):
+ return PENALTY_NEUTRAL
+ if prev_char in JA_SENTENCE_END:
+ return PENALTY_SENTENCE_END
+ if script == "ja" and _particle_starts(after or next_char):
+ # a particle may not open a line: it belongs to the word before it (kinsoku)
+ return PENALTY_FORBIDDEN
+ if script == "ja" and _particle_ends(before or prev_char):
+ return PENALTY_PARTICLE
+ if script == "ja" and _is_ideograph(prev_char) and _is_hiragana(next_char):
+ # okurigana: 決|まる is inside a word even though neither half is a "word" on its own
+ return PENALTY_OKURIGANA
+ if _is_ideograph(prev_char) and _is_ideograph(next_char):
+ return PENALTY_IDEOGRAPHS
+ return PENALTY_NEUTRAL
+
+
+def _cut_penalty(atoms: "Sequence[Tuple[str, bool]]", cut: int, lang: "Optional[str]") -> float:
+ """The penalty of breaking `atoms` before index `cut`."""
+ prev_atom = atoms[cut - 1][0]
+ next_atom = atoms[cut][0]
+ if not prev_atom or not next_atom:
+ return PENALTY_NEUTRAL
+ if atoms[cut][1]:
+ # a space stood here: a spaced script, so R4 is the rule that applies, in both directions
+ if all(not ch.isalnum() for ch in next_atom):
+ return PENALTY_FORBIDDEN # never strand punctuation at the start of a line
+ words = _function_words(lang)
+ if _bare_word(prev_atom) in words:
+ return PENALTY_FUNCTION_WORD # stranded at the end of a line, away from its noun
+ if _bare_word(next_atom) in words:
+ return PENALTY_FUNCTION_WORD_START # opens the next line with the phrase it governs
+ return PENALTY_NEUTRAL
+ if prev_atom.endswith(_HYPHENS):
+ return PENALTY_NEUTRAL # R1: a hyphen is a legitimate break point
+ # the text on each side, so a two-character particle (から/まで/より) is seen as one
+ before = "".join(a for a, _sp in atoms[:cut])
+ after = "".join(a for a, _sp in atoms[cut:])
+ return break_penalty(prev_atom[-1], next_atom[0], lang, before=before, after=after)
+
+
+def best_break(atoms: "Sequence[Tuple[str, bool]]", max_em: float,
+ lang: "Optional[str]" = None) -> "Optional[int]":
+ """The index to break `atoms` at so they become two lines, or None when none fits.
+
+ Among every position whose two halves both fit `max_em`, the one minimising
+ (penalty, widest line, |width difference|) wins: R1-R4 choose first, and 1.15's
+ minimise-the-widest-line rule breaks the ties it used to decide alone."""
+ best = None
+ for cut in range(1, len(atoms)):
+ a = b = ""
+ for atom, sp in atoms[:cut]:
+ a = _join(a, atom, sp)
+ for atom, sp in atoms[cut:]:
+ b = _join(b, atom, sp)
+ wa, wb = text_width_em(a), text_width_em(b)
+ if max(wa, wb) > max_em:
+ continue
+ if _is_weak_line(a) or _is_weak_line(b):
+ continue
+ key = (_cut_penalty(atoms, cut, lang), max(wa, wb), abs(wa - wb))
+ if best is None or key < best[0]:
+ best = (key, cut)
+ return None if best is None else best[1]
+
+
+def _fix_orphans(lines: "List[str]", max_em: float) -> "List[str]":
+ """No last line that is a single stranded atom.
+
+ Greedy wrapping leaves one character alone whenever the line before it filled exactly: eval 14
+ produced a Thai cue ending in a lone `ล` and a Japanese one ending in a lone `行`. While the
+ last line is one atom narrower than ORPHAN_MIN_EM, the last atom of the line above moves down
+ onto it -- but only while the result still fits and the line above does not become an orphan
+ itself, so a two-word cue is never made worse."""
+ lines = list(lines)
+ for _ in range(len(lines)):
+ if len(lines) < 2:
+ break
+ tail = _atoms(lines[-1])
+ if len(tail) != 1 or text_width_em(lines[-1]) >= ORPHAN_MIN_EM:
+ break
+ prev = _atoms(lines[-2])
+ if len(prev) < 2:
+ break
+ moved, spaced = prev[-1]
+ new_prev = ""
+ for atom, sp in prev[:-1]:
+ new_prev = _join(new_prev, atom, sp)
+ new_last = _join(moved, tail[0][0], _break_spaced(lines[-2], lines[-1]))
+ if text_width_em(new_last) > max_em or text_width_em(new_prev) < ORPHAN_MIN_EM:
+ break
+ lines[-2], lines[-1] = new_prev, new_last
+ return lines
+
+
+def _fix_weak_lines(lines: "List[str]", max_em: float) -> "List[str]":
+ """R2, generalised: _fix_orphans run at *every* boundary, against _is_weak_line.
+
+ 1.15 only ever looked at the last line, so a stranded digit or kana in the middle of a
+ three-line cue survived. Walking upward from the last line, while a line is weak the last atom
+ of the line above moves down onto it -- with 1.15's two guards intact (the result must still
+ fit, and the line above must not itself become weak), so the line count never changes."""
+ lines = list(lines)
+ for i in range(len(lines) - 1, 0, -1):
+ for _ in range(len(lines)):
+ if not _is_weak_line(lines[i]):
+ break
+ prev = _atoms(lines[i - 1])
+ if len(prev) < 2:
+ break
+ moved, _spaced = prev[-1]
+ new_prev = ""
+ for atom, sp in prev[:-1]:
+ new_prev = _join(new_prev, atom, sp)
+ new_last = _join(moved, lines[i], _break_spaced(lines[i - 1], lines[i]))
+ if text_width_em(new_last) > max_em or _is_weak_line(new_prev) \
+ or text_width_em(new_prev) < ORPHAN_MIN_EM:
+ break
+ lines[i - 1], lines[i] = new_prev, new_last
+ return lines
+
+
+def _rebalance(lines: "List[str]", max_em: float) -> "List[str]":
+ """Move each break to the one that minimises the widest line of the pair, without changing the
+ line count.
+
+ Greedy wrapping fills line 1 to the brim and leaves line 2 short, which is what split eval 14's
+ `"A third line the tool times for me"` mid-phrase. Only spaced scripts are rebalanced: a
+ non-spaced script has no phrase structure in its atom list, so moving the break there only
+ moves the ragged edge. A break is never placed before a punctuation-only atom."""
+ if len(lines) < 2:
+ return lines
+ out = list(lines)
+ for i in range(len(out) - 1):
+ first, second = out[i], out[i + 1]
+ tail_atoms = _atoms(second)
+ if tail_atoms:
+ tail_atoms[0] = (tail_atoms[0][0], _break_spaced(first, second))
+ atoms = _atoms(first) + tail_atoms
+ if not atoms or any(char_script(ch) in NO_SPACE_SCRIPTS for ch in first + second):
+ continue
+ best = None
+ for cut in range(1, len(atoms)):
+ if not atoms[cut][1]:
+ continue # only break where a space stood
+ if all(not ch.isalnum() for ch in atoms[cut][0]):
+ continue # never strand punctuation at the start of a line
+ a = b = ""
+ for atom, sp in atoms[:cut]:
+ a = _join(a, atom, sp)
+ for atom, sp in atoms[cut:]:
+ b = _join(b, atom, sp)
+ wa, wb = text_width_em(a), text_width_em(b)
+ if max(wa, wb) > max_em:
+ continue
+ key = (max(wa, wb), abs(wa - wb))
+ if best is None or key < best[0]:
+ best = (key, a, b)
+ if best is not None:
+ out[i], out[i + 1] = best[1], best[2]
+ return out
+
+
+def _rebalance_phrase(lines: "List[str]", max_em: float, lang: "Optional[str]") -> "Tuple[List[str], int]":
+ """_rebalance with R1-R4 deciding, for every script rather than spaced ones only.
+
+ Returns the new lines and how many breaks a phrase rule moved away from the position 1.15's
+ widest-line rule alone would have chosen -- the `phrase_breaks` count in the result."""
+ if len(lines) < 2:
+ return list(lines), 0
+ out = list(lines)
+ moved = 0
+ for i in range(len(out) - 1):
+ first, second = out[i], out[i + 1]
+ tail_atoms = _atoms(second)
+ if tail_atoms:
+ tail_atoms[0] = (tail_atoms[0][0], _break_spaced(first, second))
+ atoms = _split_hyphens(_atoms(first) + tail_atoms)
+ if len(atoms) < 2:
+ continue
+ cut = best_break(atoms, max_em, lang)
+ if cut is None:
+ continue
+ a = b = ""
+ for atom, sp in atoms[:cut]:
+ a = _join(a, atom, sp)
+ for atom, sp in atoms[cut:]:
+ b = _join(b, atom, sp)
+ if (a, b) != (first, second):
+ moved += 1
+ out[i], out[i + 1] = a, b
+ return out, moved
+
+
+def _greedy_chunks(raw: str, max_em: float) -> "List[str]":
+ """The greedy fill on its own: the line count every mode must keep."""
+ current = ""
+ chunk: "List[str]" = []
+ for atom, spaced in _atoms(raw):
+ candidate = _join(current, atom, spaced)
+ if current and text_width_em(candidate) > max_em:
+ chunk.append(current)
+ current = atom
+ else:
+ current = candidate
+ if current:
+ chunk.append(current)
+ return chunk
+
+
+def _balance(chunk: "List[str]", max_em: float, mode: str, lang: "Optional[str]") -> "List[str]":
+ """The post-passes for one greedy chunk, in the mode's own order. Never changes the count:
+ a pass that would is discarded, exactly as 1.15 did."""
+ if len(chunk) < 2:
+ return chunk
+ if mode == "measured":
+ fixed = _fix_orphans(chunk, max_em)
+ rebalanced = _rebalance(fixed, max_em)
+ else:
+ fixed = _fix_weak_lines(_fix_orphans(chunk, max_em), max_em)
+ rebalanced, _moved = _rebalance_phrase(fixed, max_em, lang)
+ rebalanced = _fix_weak_lines(rebalanced, max_em)
+ if len(rebalanced) == len(chunk):
+ return rebalanced
+ return fixed if len(fixed) == len(chunk) else chunk
+
+
+def wrap_text(text: str, max_em: float, *, balance: bool = True, mode: str = "phrase",
+ lang: "Optional[str]" = None) -> "List[str]":
+ """Wrap `text` to lines no wider than `max_em` em, keeping the manual breaks it already has.
+
+ An atom wider than the whole line (one very long word) is left alone on its line rather than
+ cut mid-word: an over-long line is readable, a chopped word is not.
+
+ `mode="phrase"` (the default since 1.16) then applies the four phrase rules -- never inside a
+ word or across a hyphen's wrong side (R1), no line that is a lone digit, punctuation or kana
+ (R2), Japanese/Chinese breaks preferred at sentence ends and after particles, never before one
+ and never inside a word (R3), and an article or preposition kept with the phrase it governs by
+ preferring the break before it and avoiding the break after it (R4). `mode="measured"` is
+ 1.15's behaviour exactly: no one-character orphan line, and a break chosen only to minimise the
+ widest line. Neither mode ever changes the number of lines the greedy fill produced.
+ """
+ lines: "List[str]" = []
+ for raw in text.split("\n"):
+ if not raw.strip():
+ continue
+ chunk = _greedy_chunks(raw, max_em)
+ lines.extend(_balance(chunk, max_em, mode, lang) if balance else chunk)
+ return lines or [text]
+def wrap_variants(text: str, max_em: float, *, mode: str = "phrase",
+ lang: "Optional[str]" = None) -> "Tuple[List[str], List[str], List[str]]":
+ """`(wrapped, greedy, measured)` for one cue from a single greedy fill.
+
+ layout_cues needs all three -- `wrapped` is what is burnt in, `greedy` is what `rebalanced`
+ counts against and `measured` what `phrase_breaks` counts against -- and used to call
+ wrap_text() three times, re-running the atomiser and the greedy fill each time. The fill is
+ the same for every mode, so it is done once here and only the post-passes are repeated.
+ `measured` is the same list object as `wrapped` when that is already the mode.
+ """
+ wrapped: "List[str]" = []
+ greedy: "List[str]" = []
+ measured: "List[str]" = []
+ for raw in text.split("\n"):
+ if not raw.strip():
+ continue
+ chunk = _greedy_chunks(raw, max_em)
+ greedy.extend(chunk)
+ wrapped.extend(_balance(list(chunk), max_em, mode, lang))
+ measured.extend(chunk if mode == "measured" else _balance(list(chunk), max_em, "measured", None))
+ if not greedy:
+ greedy = [text]
+ return (wrapped or [text], greedy, measured or [text])
diff --git a/scripts/_contract.py b/scripts/_contract.py
index 854c576..05f7e60 100644
--- a/scripts/_contract.py
+++ b/scripts/_contract.py
@@ -121,8 +121,9 @@ TOOL_META: Dict[str, Dict[str, Any]] = {
"broll": dict(role="execution", inputs=["A-roll video asset", "one or more B-roll video assets (--insert)"], outputs=["video artifact of exactly the A-roll's length with the B-roll shown during each cutaway window"],
required=FF + [X264, AAC, "filter:overlay", "filter:amix"], optional=[HDR_X265],
video_required=True, audio_only=False, visual=True, verify=["probe", "look"], produces_artifact=True, idempotency="content_equivalent", deterministic=True),
- "metadata": dict(role="execution", inputs=["video or audio asset", "chapters text file (--chapters)"], outputs=["the same streams, stream-copied, with chapter markers and/or title/artist/comment tags written"],
- required=FF, optional=[],
+ "metadata": dict(role="execution", inputs=["video or audio asset", "chapters text file (--chapters)"], outputs=["the same streams, stream-copied, with chapter markers and/or title/artist/comment tags written", "proposed chapter list and YouTube description block (--auto-chapters --chapters-out/--description-out)"],
+ required=FF, optional=[{"capability": "filter:silencedetect", "when": "--auto-chapters"},
+ {"capability": "filter:scdet", "when": "--auto-chapters --from scenes|both"}],
video_required=False, audio_only=True, visual=False, verify=["probe"], produces_artifact=True, idempotency="bit_exact", deterministic=True),
"loop": dict(role="execution", inputs=["video asset"], outputs=["video artifact repeated to the requested count or duration"],
required=FF + [X264, AAC], optional=[],
@@ -142,7 +143,7 @@ TOOL_META: Dict[str, Dict[str, Any]] = {
"sequence": dict(role="execution", inputs=["a directory of numbered/globbed still images"], outputs=["video artifact built from the frame sequence"],
required=FF + [X264], optional=[],
video_required=True, audio_only=False, visual=True, verify=["probe", "look"], produces_artifact=True, idempotency="content_equivalent", deterministic=True),
- "caption": dict(role="execution", inputs=["video asset", "SRT/ASS file or timed text (--text)"], outputs=["video artifact with burnt-in captions (--mode burn)", "video artifact with an added soft subtitle stream (--mode mux)", "generated .srt / .ass sidecar"],
+ "caption": dict(role="execution", inputs=["video asset", "SRT/ASS file or timed text (--text)"], outputs=["video artifact with burnt-in captions (--mode burn)", "video artifact with one or several language-tagged soft subtitle streams (--mode mux, --srt file:lang repeated)", "generated .srt / .ass sidecar"],
required=FF + [X264, AAC, "filter:subtitles"], optional=[{"capability": "filter:ass", "when": "--animate / --karaoke"}, HDR_X265, {"capability": "external:whisper", "when": "--transcribe"},
{"capability": "encoder:mov_text", "when": "--mode mux with a .mp4/.m4v/.mov output"}, {"capability": "encoder:webvtt", "when": "--mode mux with a .webm output"}, {"capability": "encoder:srt", "when": "--mode mux with a .mkv output"}],
video_required=True, audio_only=False, visual=True, verify=["probe", "look"], produces_artifact=True, idempotency="content_equivalent", deterministic=True),
@@ -260,7 +261,7 @@ REENCODE_META: Dict[str, Dict[str, str]] = {
"pad": dict(video="always", audio="always", note="the tpad filter always forces a re-encode of the video stream; audio is re-encoded to AAC when present"),
"speedramp": dict(video="always", audio="always", note="setpts/atempo per segment always forces a re-encode of both streams"),
"broll": dict(video="always", audio="conditional", note="the overlay graph always re-encodes the video stream; A's audio is stream-copied under --audio a and re-encoded to AAC under --audio b/mix"),
- "metadata": dict(video="never", audio="never", note="-c copy on every stream; only the container's chapters and tags change"),
+ "metadata": dict(video="never", audio="never", note="-c copy on every stream; only the container's chapters and tags change -- --auto-chapters decodes to measure, but still writes with -c copy"),
"loop": dict(video="always", audio="always", note="-stream_loop always re-encodes both streams; the audio codec is always AAC when present"),
"insert": dict(video="always", audio="never", note="always encodes a fresh silent clip from the still image; there is no audio stream to touch"),
"background": dict(video="always", audio="never", note="always encodes a fresh generated clip; there is no input to copy from"),
@@ -393,6 +394,20 @@ def output_schema(name: str, meta: Dict[str, Any]) -> Dict[str, Any]:
extra = {"platform": {"type": "string"}, "ok": {"type": "boolean"}, "failed": {"type": "integer"}, "warnings": {"type": "integer"},
"notes": {"type": "array", "items": {"type": "string"}, "description": "present when no --platform was named: youtube was assumed and judgement rows are WARN"},
"checks": {"type": "array", "items": {"type": "object", "properties": {"check": {"type": "string"}, "status": {"enum": ["PASS", "WARN", "FAIL"]}, "value": {}, "expected": {}, "fix": {"type": "string"}, "kind": {"enum": ["format", "judgement"]}}}}}
+ elif name == "caption":
+ extra = {"caption": {"type": "object", "description": "cue layout: shifted / wrapped / rebalanced / split / extended / dropped counts, plus wrap ('phrase' or 'measured') and phrase_breaks (1.16)"},
+ "tracks": {"type": "array", "description": "--mode mux: one entry per subtitle stream in the output ({index, file, language, title, codec, default, cues, kept_from_input}); a stream the input already carried has file null and kept_from_input true (1.16)"},
+ "subtitle_tracks": {"type": "integer", "description": "--mode mux: how many subtitle streams the output carries"},
+ "emoji": {"type": "object", "description": "how the emoji in the text were drawn (mode, overlays, missing)"},
+ "notes": {"type": "array", "items": {"type": "string"}}}
+ elif name == "metadata":
+ extra = {"chapters": {"type": "array", "description": "the chapter markers read back off the written file"},
+ "tags": {"type": "object"}, "streams_copied": {"type": "boolean"},
+ "auto_chapters": {"type": "object", "description": "--auto-chapters: {source, min_chapter, max_chapters, proposed, kept, titles, chapters, description_block, files}. titles is always 'placeholder' -- the skill proposes where a chapter starts, never what it is called (1.16)"},
+ "notes": {"type": "array", "items": {"type": "string"}}}
+ elif name == "waveform":
+ extra = {"audiogram": {"type": "object", "description": "{style, background ('image' or 'color'), image, position, vis_height, platform, captions, title, stages, verified} -- present on every run, so a plain waveform answers background 'color' (1.16)"},
+ "notes": {"type": "array", "items": {"type": "string"}}}
elif name == "scenes":
extra = {"file": {"type": "string"}, "duration": {"type": "number"}, "scene_count": {"type": "integer"}, "scenes": {"type": "array"}, "audio_peaks": {"type": "array"}}
elif name == "silence":
diff --git a/scripts/caption.py b/scripts/caption.py
index e901b3e..67aa6b8 100755
--- a/scripts/caption.py
+++ b/scripts/caption.py
@@ -38,11 +38,23 @@ import re
import sys
import unicodedata
from pathlib import Path
-from typing import Dict, List, Optional, Tuple
+from typing import Any, Dict, List, Optional, Tuple
from _platforms import PLATFORMS, PLATFORM_CHOICES, ass_units, resolve as resolve_platform
from _ass_overlay import EMOJI_SENTINEL, emoji_placeholder, ass_escape
-from _common import emoji_filter_chain, EMOJI_ASSET_HINT, emoji_asset_for, emoji_codepoint_name, emoji_support, resolve_emoji_assets, ADVANCE_EM, LATIN_EM, LEADING_VOWELS, NO_SPACE_SCRIPTS, _char_em, _is_mark, text_width_em, emoji_clusters, has_emoji, detect_script, BIDI_SCRIPTS, STATE, brand_states_font, char_script, script_font_for_text, signed_time_arg, brand_caption_style, color_hex, load_brand, video_args, add_common, apply_common, emit, aac_args, cfr_args, default_output, die, escape_filter_path, ffmpeg_base, fmt_srt_time, fmt_smpte_time, info, MissingFpsError, parse_time, probe, run, x264_args, X264_PRESETS, read_text_or_die, fmt_secs
+from _common import emoji_filter_chain, EMOJI_ASSET_HINT, emoji_asset_for, emoji_codepoint_name, emoji_support, resolve_emoji_assets, ADVANCE_EM, LATIN_EM, NO_SPACE_SCRIPTS, _char_em, char_script, text_width_em, emoji_clusters, has_emoji, detect_script, BIDI_SCRIPTS, STATE, brand_states_font, script_font_for_text, signed_time_arg, brand_caption_style, color_hex, load_brand, video_args, add_common, apply_common, emit, aac_args, cfr_args, default_output, die, escape_filter_path, ffmpeg_base, fmt_srt_time, fmt_smpte_time, info, MissingFpsError, parse_time, probe, run, x264_args, X264_PRESETS, read_text_or_die, fmt_secs
+# The line breaker, lifted into _common/text.py in 1.16.0 so graphics.py can use the same rules.
+from _common import (SAFE_WIDTH_FRACTION, ORPHAN_MIN_EM, WRAP_MODES, wrap_text, wrap_variants, best_break,
+ break_penalty, _is_weak_line, _atoms, _join, _break_spaced, _bare_word, _function_words,
+ _split_hyphens, FUNCTION_WORDS, JA_PARTICLES, JA_SENTENCE_END, _fix_orphans, _rebalance)
+
+# The breaker's names are caption.py's public surface as much as _common's: every caller and test
+# that reached for `caption.wrap_text` before 1.16 still does.
+__all__ = ["SAFE_WIDTH_FRACTION", "ORPHAN_MIN_EM", "WRAP_MODES", "wrap_text", "wrap_variants",
+ "best_break", "break_penalty", "_is_weak_line", "_atoms", "_join", "_break_spaced",
+ "_bare_word", "_function_words", "_split_hyphens", "FUNCTION_WORDS", "JA_PARTICLES",
+ "JA_SENTENCE_END", "_fix_orphans", "_rebalance", "char_script", "NO_SPACE_SCRIPTS",
+ "text_width_em"]
ALIGN = {"bottom": 2, "top": 8, "center": 5, "bottom-left": 1, "bottom-right": 3, "top-left": 7, "top-right": 9}
@@ -299,187 +311,6 @@ def word_durations_from_audio(video: str, start: float, end: float, n_words: int
return out
-# How much of the frame width a caption line may use. libass's own default SRT margins are 10 of a
-# 384-wide script (2.6 % a side); 5 % a side is the safe area every platform check in this repo uses.
-SAFE_WIDTH_FRACTION = 0.9
-# ORPHAN_MIN_EM: one full-width CJK/Thai character plus a hair. A last line narrower than this is a
-# single stranded character -- eval 14's th1 (a lone 'ล') and dl3 (a lone '行').
-ORPHAN_MIN_EM = 1.1
-
-
-def _atoms(line: str) -> List[Tuple[str, bool]]:
- """Break a line into the smallest pieces a wrap may separate -- one atom per CJK/Thai
- character, one per emoji cluster, one per whitespace-delimited word otherwise -- each with
- whether a space stood before it in the original. The flag is what puts the text back together
- exactly as written: "Hello 世界" keeps its space, "世界です" gains none."""
- out: List[Tuple[str, bool]] = []
- word = ""
- spaced = False # a space stands before the atom being built
- pending = False # a space stands before the NEXT atom
- attach_next = False # a leading Thai/Lao vowel is waiting for its base consonant
- # An emoji cluster is one atom: a wrap must never land inside a ZWJ sequence, a flag pair or
- # between a base and its skin-tone modifier (the same rule combining marks already follow).
- clusters = {i: len(cl) for i, cl in emoji_clusters(line)}
- i = 0
- while i < len(line):
- ch = line[i]
- if i in clusters:
- cluster = line[i:i + clusters[i]]
- if word:
- out.append((word, spaced))
- word = ""
- out.append((cluster, pending))
- pending = False
- attach_next = False
- i += clusters[i]
- continue
- i += 1
- if char_script(ch) in NO_SPACE_SCRIPTS:
- if word:
- out.append((word, spaced))
- word = ""
- if out and (attach_next or _is_mark(ch)):
- # never break between a base and the mark (or the leading vowel) that belongs to
- # it: the line would start with an orphaned tone mark or vowel sign
- out[-1] = (out[-1][0] + ch, out[-1][1])
- else:
- out.append((ch, pending))
- pending = False
- attach_next = ord(ch) in LEADING_VOWELS
- elif ch.isspace():
- if word:
- out.append((word, spaced))
- word = ""
- pending = True
- else:
- if not word:
- spaced, pending = pending, False
- word += ch
- if word:
- out.append((word, spaced))
- return out
-
-
-def _join(left: str, atom: str, spaced: bool) -> str:
- """Put an atom back on a line, restoring the space that stood before it."""
- if not left:
- return atom
- return left + (" " if spaced else "") + atom
-
-
-def _break_spaced(first: str, second: str) -> bool:
- """Did a space stand at the break between these two wrapped lines? Only spaced scripts put one
- there -- a CJK/Thai break sits between two characters that were written with nothing between
- them, and re-joining them with a space would insert a character the cue never had."""
- if not first or not second:
- return False
- return char_script(first[-1]) not in NO_SPACE_SCRIPTS and char_script(second[0]) not in NO_SPACE_SCRIPTS \
- and char_script(first[-1]) != "emoji" and char_script(second[0]) != "emoji"
-
-
-def _fix_orphans(lines: List[str], max_em: float) -> List[str]:
- """No last line that is a single stranded atom.
-
- Greedy wrapping leaves one character alone whenever the line before it filled exactly: eval 14
- produced a Thai cue ending in a lone `ล` and a Japanese one ending in a lone `行`. While the
- last line is one atom narrower than ORPHAN_MIN_EM, the last atom of the line above moves down
- onto it -- but only while the result still fits and the line above does not become an orphan
- itself, so a two-word cue is never made worse."""
- lines = list(lines)
- for _ in range(len(lines)):
- if len(lines) < 2:
- break
- tail = _atoms(lines[-1])
- if len(tail) != 1 or text_width_em(lines[-1]) >= ORPHAN_MIN_EM:
- break
- prev = _atoms(lines[-2])
- if len(prev) < 2:
- break
- moved, spaced = prev[-1]
- new_prev = ""
- for atom, sp in prev[:-1]:
- new_prev = _join(new_prev, atom, sp)
- new_last = _join(moved, tail[0][0], _break_spaced(lines[-2], lines[-1]))
- if text_width_em(new_last) > max_em or text_width_em(new_prev) < ORPHAN_MIN_EM:
- break
- lines[-2], lines[-1] = new_prev, new_last
- return lines
-
-
-def _rebalance(lines: List[str], max_em: float) -> List[str]:
- """Move each break to the one that minimises the widest line of the pair, without changing the
- line count.
-
- Greedy wrapping fills line 1 to the brim and leaves line 2 short, which is what split eval 14's
- `"A third line the tool times for me"` mid-phrase. Only spaced scripts are rebalanced: a
- non-spaced script has no phrase structure in its atom list, so moving the break there only
- moves the ragged edge. A break is never placed before a punctuation-only atom."""
- if len(lines) < 2:
- return lines
- out = list(lines)
- for i in range(len(out) - 1):
- first, second = out[i], out[i + 1]
- tail_atoms = _atoms(second)
- if tail_atoms:
- tail_atoms[0] = (tail_atoms[0][0], _break_spaced(first, second))
- atoms = _atoms(first) + tail_atoms
- if not atoms or any(char_script(ch) in NO_SPACE_SCRIPTS for ch in first + second):
- continue
- best = None
- for cut in range(1, len(atoms)):
- if not atoms[cut][1]:
- continue # only break where a space stood
- if all(not ch.isalnum() for ch in atoms[cut][0]):
- continue # never strand punctuation at the start of a line
- a = b = ""
- for atom, sp in atoms[:cut]:
- a = _join(a, atom, sp)
- for atom, sp in atoms[cut:]:
- b = _join(b, atom, sp)
- wa, wb = text_width_em(a), text_width_em(b)
- if max(wa, wb) > max_em:
- continue
- key = (max(wa, wb), abs(wa - wb))
- if best is None or key < best[0]:
- best = (key, a, b)
- if best is not None:
- out[i], out[i + 1] = best[1], best[2]
- return out
-
-
-def wrap_text(text: str, max_em: float, *, balance: bool = True) -> List[str]:
- """Wrap `text` to lines no wider than `max_em` em, keeping the manual breaks it already has.
-
- An atom wider than the whole line (one very long word) is left alone on its line rather than
- cut mid-word: an over-long line is readable, a chopped word is not. Two post-passes then make
- the result readable rather than merely legal (1.15): no one-character orphan line, and for
- spaced scripts a break chosen to minimise the widest line instead of greedily.
- """
- lines: List[str] = []
- for raw in text.split("\n"):
- if not raw.strip():
- continue
- current = ""
- chunk: List[str] = []
- for atom, spaced in _atoms(raw):
- candidate = _join(current, atom, spaced)
- if current and text_width_em(candidate) > max_em:
- chunk.append(current)
- current = atom
- else:
- current = candidate
- if current:
- chunk.append(current)
- if balance and len(chunk) > 1:
- fixed = _fix_orphans(chunk, max_em)
- rebalanced = _rebalance(fixed, max_em)
- if len(rebalanced) == len(chunk):
- chunk = rebalanced
- else:
- chunk = fixed
- lines.extend(chunk)
- return lines or [text]
-
# --------------------------------------------------------------------------- emoji (1.15)
def _cue_lines(text: str) -> List[str]:
@@ -602,7 +433,8 @@ def plan_emoji(cues, args, play_w, play_h, brand=None):
def layout_cues(cues: List[Tuple[float, float, str]], *, max_em: Optional[float], max_lines: int,
- min_duration: float, offset: float) -> Tuple[List[Tuple[float, float, str]], dict]:
+ min_duration: float, offset: float, wrap: str = "phrase",
+ lang: Optional[str] = None) -> Tuple[List[Tuple[float, float, str]], dict]:
"""Shift, wrap, split and lengthen cues so they can actually be read.
`offset` moves every cue (a transcript that runs early/late); `max_em` wraps each cue to the
@@ -611,7 +443,8 @@ def layout_cues(cues: List[Tuple[float, float, str]], *, max_em: Optional[float]
proportion to their text; a cue shorter than `min_duration` is lengthened, never past the next
cue's start. Returns the new cues and a count of what changed.
"""
- stats = {"shifted": 0, "wrapped": 0, "split": 0, "extended": 0, "dropped": 0, "rebalanced": 0}
+ stats = {"shifted": 0, "wrapped": 0, "split": 0, "extended": 0, "dropped": 0, "rebalanced": 0,
+ "wrap": wrap, "phrase_breaks": 0}
staged: List[Tuple[float, float, str]] = []
for start, end, text in cues:
if offset:
@@ -622,11 +455,16 @@ def layout_cues(cues: List[Tuple[float, float, str]], *, max_em: Optional[float]
start = max(0.0, start)
stats["shifted"] += 1
if max_em and max_em > 0:
- lines = wrap_text(text, max_em)
+ # one greedy fill per cue, three answers off it: what gets burnt in, what the
+ # greedy wrap would have given (`rebalanced`) and what 1.15's wrap would have
+ # given (`phrase_breaks`). Three wrap_text() calls re-ran the atomiser each time.
+ lines, greedy, measured = wrap_variants(text, max_em, mode=wrap, lang=lang)
if lines != [l for l in text.split("\n") if l.strip()]:
stats["wrapped"] += 1
- if lines != wrap_text(text, max_em, balance=False):
+ if lines != greedy:
stats["rebalanced"] += 1
+ if wrap != "measured" and lines != measured:
+ stats["phrase_breaks"] += 1
if len(lines) > max_lines:
chunks = [lines[i:i + max_lines] for i in range(0, len(lines), max_lines)]
weights = [max(1.0, sum(len(l) for l in c)) for c in chunks]
@@ -654,7 +492,7 @@ def layout_cues(cues: List[Tuple[float, float, str]], *, max_em: Optional[float]
def report_layout(stats: dict) -> None:
"""One info line, only when a cue actually changed."""
- parts = [f"{stats[k]} {k}" for k in ("shifted", "wrapped", "rebalanced", "split", "extended", "dropped") if stats.get(k)]
+ parts = [f"{stats[k]} {k}" for k in ("shifted", "wrapped", "rebalanced", "phrase_breaks", "split", "extended", "dropped") if stats.get(k)]
if parts:
info("cues: " + ", ".join(parts))
@@ -842,6 +680,93 @@ def write_ass(cues: List[Tuple[float, float, str]], path: str, args, play_w: int
fh.write("\n".join(header + lines) + "\n")
+# ------------------------------------------------------- multi-language subtitle tracks (1.16)
+
+class AppendPath(argparse.Action):
+ """`--srt` repeated, without changing what the contract says `--srt` is.
+
+ `action="append"` would make the derived JSON Schema an array (`_contract._json_type`), and the
+ 1.x guarantee says no argument changes type -- an MCP client that sends `{"srt": "subs.srt"}`
+ must keep working exactly as it did. Subclassing Action directly keeps the schema a plain
+ string while the CLI collects every occurrence, so repeating the flag is purely additive.
+ """
+
+ def __call__(self, parser, namespace, values, option_string=None):
+ current = getattr(namespace, self.dest, None)
+ if not isinstance(current, list):
+ current = [] if current is None else [current]
+ current.append(values)
+ setattr(namespace, self.dest, current)
+
+
+# BCP-47-ish: a 2-3 letter primary subtag, optionally followed by script/region/variant subtags.
+LANG_TOKEN_RE = re.compile(r"^[a-z]{2,3}(-[A-Za-z0-9]{2,8})*$")
+
+# The name a player lists a track under, when the caller gives no --track-title. Data, not a
+# translation: a code that is not in the table gets the code itself, never an invented name.
+LANG_TITLES = {
+ "en": "English", "es": "Espanol", "pt": "Portugues", "fr": "Francais", "de": "Deutsch",
+ "it": "Italiano", "nl": "Nederlands", "pl": "Polski", "ru": "\u0420\u0443\u0441\u0441\u043a\u0438\u0439",
+ "ja": "\u65e5\u672c\u8a9e", "zh": "\u4e2d\u6587", "ko": "\ud55c\uad6d\uc5b4",
+ "ar": "\u0627\u0644\u0639\u0631\u0628\u064a\u0629", "he": "\u05e2\u05d1\u05e8\u05d9\u05ea",
+ "hi": "\u0939\u093f\u0928\u094d\u0926\u0940", "th": "\u0e44\u0e17\u0e22",
+ "tr": "Turkce", "id": "Bahasa Indonesia", "vi": "Tieng Viet", "sv": "Svenska",
+ "da": "Dansk", "no": "Norsk", "fi": "Suomi", "cs": "Cestina", "uk": "\u0423\u043a\u0440\u0430\u0457\u043d\u0441\u044c\u043a\u0430",
+}
+
+# MP4/MOV store the language in an ISO-639-2/T box and silently drop anything that is not three
+# letters -- verified against ffmpeg 6.1: `-metadata:s:s:0 language=en` on an .mp4 writes NO
+# language tag at all, while `language=eng` writes one ffprobe reads back. Matroska stores the
+# code verbatim, so `en` survives there. Only the codes this table knows are converted; an
+# unknown one is passed through with a note rather than guessed at.
+ISO639_1_TO_2 = {
+ "en": "eng", "es": "spa", "pt": "por", "fr": "fra", "de": "deu", "it": "ita", "nl": "nld",
+ "pl": "pol", "ru": "rus", "ja": "jpn", "zh": "zho", "ko": "kor", "ar": "ara", "he": "heb",
+ "hi": "hin", "th": "tha", "tr": "tur", "id": "ind", "vi": "vie", "sv": "swe", "da": "dan",
+ "no": "nor", "fi": "fin", "cs": "ces", "uk": "ukr", "el": "ell", "hu": "hun", "ro": "ron",
+ "bg": "bul", "ca": "cat", "fa": "fas", "ta": "tam", "bn": "ben", "ms": "msa", "fil": "fil",
+}
+
+
+def split_srt_lang(token: str) -> Tuple[str, Optional[str]]:
+ """`file.srt:ja` -> ("file.srt", "ja"); anything else -> (token, None).
+
+ The split is on the LAST colon and only when the suffix is BCP-47-shaped AND the whole token
+ is not itself a readable file -- so `C:\\subs\\en.srt` (a Windows path) and a file genuinely
+ named `a:b.srt` are never mangled.
+ """
+ token = str(token)
+ if ":" not in token or os.path.exists(token):
+ return token, None
+ head, _, tail = token.rpartition(":")
+ if head and LANG_TOKEN_RE.match(tail):
+ return head, tail
+ # A tail that is clearly meant as a language code but is not one is a language error, not a
+ # file called `en.srt:zzzz`: only say "file not found" when the whole token could be a path.
+ if head and tail and not os.path.exists(token) and os.path.exists(head) \
+ and re.match(r"^[A-Za-z][A-Za-z0-9-]*$", tail):
+ die(f"--srt {token}: '{tail}' is not a language code (two or three letters, optionally "
+ "with a region, e.g. en, ja, pt-BR)", kind="input")
+ return token, None
+
+
+def container_language(code: str, output: str) -> str:
+ """The spelling of `code` this container actually stores (see ISO639_1_TO_2)."""
+ ext = Path(output).suffix.lower()
+ if ext not in (".mp4", ".m4v", ".mov"):
+ return code
+ primary = code.split("-")[0].lower()
+ return ISO639_1_TO_2.get(primary, code)
+
+
+def track_title_for(code: Optional[str], given: Optional[str]) -> Optional[str]:
+ if given:
+ return given
+ if not code:
+ return None
+ return LANG_TITLES.get(code.split("-")[0].lower(), code)
+
+
def mux_subtitle_codec(output: str) -> str:
ext = Path(output).suffix.lower()
if ext in (".mp4", ".m4v", ".mov"):
@@ -905,13 +830,26 @@ def main() -> int:
"audio_streams) -- matters on a multi-track input (dubbed languages, M&E stems); default 0, "
"the first track, same as leaving it unset always did")
src = ap.add_argument_group("subtitle source")
- src.add_argument("--srt", help="SRT file to burn")
+ src.add_argument("--srt", action=AppendPath, metavar="FILE[:LANG]",
+ help="SRT file to burn, or (with --mode mux) to add as a soft subtitle track. Repeat it once "
+ "per language to build a multi-track deliverable, each with an optional `:lang` suffix: "
+ "`--srt en.srt:en --srt ja.srt:ja`. A single --srt with no suffix takes --language, as "
+ "it always did. NOTE: .mp4/.mov hold several mov_text tracks but many players show only "
+ "the first, and the format needs ISO-639-2 codes (`eng`, not `en`) -- this tool converts "
+ "them; .mkv is the honest multi-track container and stores the code you give verbatim")
src.add_argument("--ass", help="ASS file to burn (styles inside the file are used)")
src.add_argument("--text", help="plain text cue file to convert into SRT (see format above)")
src.add_argument("--transcribe", action="store_true", help="generate the SRT from the audio with a local speech-to-text engine if one is installed (whisper-cli / whisper / faster-whisper); never required")
src.add_argument("--language", "--lang", help="language code (e.g. en, ja, zh, ko): the language for --transcribe (default auto), "
"the tag on the subtitle stream with --mode mux, and the hint that says whether Han-only "
"text is Chinese, Japanese or Korean when a font is picked by script")
+ src.add_argument("--track-title", action=AppendPath, metavar="TITLE",
+ help="--mode mux: the name a player lists a track under, repeated in the same order as --srt "
+ "(default: the language's display name from a frozen table, else the code itself -- the "
+ "table is data, never a guessed or translated name)")
+ src.add_argument("--default-track", metavar="LANG",
+ help="--mode mux: mark this language's track `default` so a player selects it by itself "
+ "(default: none, so no player burns in a language the viewer did not ask for)")
src.add_argument("--offset", default="0", help="shift every cue by TIME (seconds, mm:ss, hh:mm:ss.ms or "
"hh:mm:ss:ff; a leading - shifts earlier); works for --text, --srt and --ass")
src.add_argument("--model", default="base", help="whisper model name/path for --transcribe (default base)")
@@ -953,6 +891,13 @@ def main() -> int:
help="most emoji overlays one run may build (default 60)")
sty.add_argument("--max-lines", type=int, default=2, help="most lines one cue may occupy; a longer cue is split into consecutive cues (default 2)")
sty.add_argument("--min-duration", type=float, default=1.0, help="shortest time a cue stays on screen in seconds, never past the next cue (default 1.0)")
+ sty.add_argument("--wrap", choices=list(WRAP_MODES), default="phrase",
+ help="how a cue too wide for the safe area is broken into lines: 'phrase' (default, 1.16) never "
+ "breaks inside a word or on the wrong side of a hyphen, never leaves a lone digit, kana or "
+ "punctuation on a line, prefers Japanese sentence ends and particles over a mid-word break, "
+ "and never ends a line on an article or preposition; 'measured' is 1.15's width-only wrap, "
+ "kept so an older split can be reproduced. Neither ever changes the number of lines, "
+ "rewrites the text or shortens a cue")
anim = ap.add_argument_group("animation (generates ASS; needs --text or --srt input)")
anim.add_argument("--animate", choices=["none", "fade", "pop", "slide"], default=None, help="per-cue entrance animation (default none, or brand caption.animate)")
anim.add_argument("--karaoke", action="store_true", help="word-by-word highlight (fills from --color to --highlight-color across each cue)")
@@ -1039,16 +984,46 @@ def main() -> int:
if meta["video"].get("rotation") in (90, -90, 270, -270):
play_w, play_h = play_h, play_w
+ caption_stats: dict = {"shifted": 0, "wrapped": 0, "split": 0, "extended": 0, "dropped": 0,
+ "rebalanced": 0, "wrap": args.wrap, "phrase_breaks": 0}
+
def lay_out(cue_list):
"""Wrap to the safe area, split past --max-lines, lengthen to --min-duration, shift by
--offset -- the one place every cue source goes through, so an SRT, a cue file and a
transcript all come out equally readable."""
out, stats = layout_cues(cue_list, max_em=max_line_em(args, play_w, play_h),
max_lines=args.max_lines, min_duration=args.min_duration,
- offset=args.offset)
+ offset=args.offset, wrap=args.wrap, lang=args.language)
report_layout(stats)
- return out, any(stats.values())
-
+ caption_stats.clear()
+ caption_stats.update(stats)
+ return out, any(v for k, v in stats.items() if k != "wrap")
+
+ # --srt is repeatable since 1.16 (one per language, each with an optional `:lang` suffix).
+ # Every path below that burns, adjusts or transcribes works on the FIRST one, which is what
+ # `--srt x.srt` has always meant; the extra tracks only exist for --mode mux.
+ srt_tracks: List[Tuple[str, Optional[str]]] = []
+ for token in (args.srt or []):
+ path_part, lang_part = split_srt_lang(token)
+ srt_tracks.append((path_part, lang_part))
+ if len(srt_tracks) == 1 and srt_tracks[0][1] is None and args.language:
+ srt_tracks[0] = (srt_tracks[0][0], args.language)
+ if srt_tracks and args.mode != "mux" and len(srt_tracks) > 1:
+ die("burning renders pixels; only one language can be in the picture -- burn one and mux "
+ "the rest (caption.py OUT --mode mux --srt en.srt:en --srt ja.srt:ja)", kind="input")
+ seen_langs = [lang for _p, lang in srt_tracks if lang]
+ for lang in seen_langs:
+ if not LANG_TOKEN_RE.match(lang):
+ die(f"--srt: '{lang}' is not a language code (two or three letters, optionally with a "
+ "region, e.g. en, ja, pt-BR)", kind="input")
+ if len(set(seen_langs)) != len(seen_langs):
+ dup = sorted({l for l in seen_langs if seen_langs.count(l) > 1})
+ die(f"--srt: two tracks tagged '{', '.join(dup)}' -- a player cannot tell them apart; give "
+ "each track its own code (and --track-title to name them)", kind="input")
+ if args.track_title and len(args.track_title) > max(1, len(srt_tracks)):
+ die(f"--track-title given {len(args.track_title)} times for {len(srt_tracks)} --srt file(s)",
+ kind="input")
+ args.srt = srt_tracks[0][0] if srt_tracks else None
srt_path = args.srt
if args.transcribe:
if not args.input:
@@ -1139,26 +1114,102 @@ def main() -> int:
codec = mux_subtitle_codec(output)
# Keep any subtitle track(s) the input already has (e.g. chaining --mode mux once per
# language to build a multi-language set) -- copied byte-identical, distinct from the
- # newly-added SRT's own codec below.
+ # newly-added SRTs' own codec below.
existing_subs = meta.get("subtitle_streams") or 0
+ # the first entry's path is srt_path, which --offset/--max-lines may have repointed at an
+ # adjusted copy; the rest are taken as written
+ added = [(srt_path, srt_tracks[0][1] if srt_tracks else args.language)] + \
+ [(p, lang) for p, lang in srt_tracks[1:]]
+ for path, _lang in added[1:]:
+ if not os.path.exists(path) and not STATE.dry_run:
+ die(f"SRT file not found: {path}")
+ titles = list(args.track_title or [])
+ mp4_family = Path(output).suffix.lower() in (".mp4", ".m4v", ".mov")
+ dropped_titles: List[str] = []
+ notes = list(side_notes)
maps = ["-map", "0:v:0"]
- cmd = ffmpeg_base() + ["-i", args.input, "-i", srt_path]
+ cmd = ffmpeg_base() + ["-i", args.input]
+ for path, _lang in added:
+ cmd += ["-i", path]
if meta.get("audio"):
maps += ["-map", f"0:a:{args.audio_stream}"]
if existing_subs:
maps += ["-map", "0:s?"]
- maps += ["-map", "1:0"]
+ for n in range(len(added)):
+ maps += ["-map", f"{n + 1}:0"]
cmd += maps + ["-c:v", "copy"] + (["-c:a", "copy"] if meta.get("audio") else [])
for i in range(existing_subs):
cmd += [f"-c:s:{i}", "copy"]
- cmd += [f"-c:s:{existing_subs}", codec]
- if args.language:
- cmd += [f"-metadata:s:s:{existing_subs}", f"language={args.language}"]
+ tracks: List[Dict[str, Any]] = []
+ for i in range(existing_subs):
+ kept = (meta.get("subtitle_stream_details") or [])
+ detail = kept[i] if i < len(kept) else {}
+ tracks.append({"index": i, "file": None, "language": detail.get("language"),
+ "title": detail.get("title"), "codec": detail.get("codec"),
+ "default": False, "cues": None, "kept_from_input": True})
+ for n, (path, lang) in enumerate(added):
+ idx = existing_subs + n
+ cmd += [f"-c:s:{idx}", codec]
+ stored = container_language(lang, output) if lang else None
+ if stored:
+ cmd += [f"-metadata:s:s:{idx}", f"language={stored}"]
+ title = track_title_for(lang, titles[n] if n < len(titles) else None)
+ # `-metadata:s:s:N title=` is written for Matroska and silently dropped by the MPEG-4
+ # muxer (verified on ffmpeg 6.1: ffprobe reads no title back), so an MP4 track is
+ # reported with `title: null` rather than a name the file does not carry.
+ if title and not mp4_family:
+ cmd += [f"-metadata:s:s:{idx}", f"title={title}"]
+ elif title:
+ dropped_titles.append(title)
+ title = None
+ is_default = bool(args.default_track and lang
+ and lang.lower() == args.default_track.lower())
+ # ALWAYS stated, never only when it is "default": given two or more new subtitle
+ # streams and nothing said, ffmpeg flags the first one `default` by itself -- which
+ # is the opposite of what --default-track promises and made tracks[].default
+ # disagree with the file it describes. An explicit 0 suppresses that.
+ cmd += [f"-disposition:s:{idx}", "default" if is_default else "0"]
+ cues_n = None
+ if os.path.exists(path):
+ try:
+ cues_n = len(parse_srt(path))
+ except SystemExit:
+ cues_n = None
+ tracks.append({"index": idx, "file": path, "language": stored, "title": title,
+ "codec": codec, "default": is_default, "cues": cues_n,
+ "kept_from_input": False})
+ if args.default_track and not any(t["default"] for t in tracks):
+ die(f"--default-track {args.default_track}: no --srt was tagged with that language",
+ kind="input")
+ # MPEG-4 has no way to say "no default subtitle track": the muxer sets the track-header
+ # ENABLED flag on the first subtitle track whatever `-disposition:s:N 0` asks for
+ # (verified on ffmpeg 6.1; `-disposition:s:N default` does move it to another track).
+ # Matroska honours the explicit 0. Report what the file carries, not what was asked.
+ if mp4_family and tracks and not any(t["default"] for t in tracks):
+ tracks[0]["default"] = True
+ notes.append("an MPEG-4 container always enables its first subtitle track, so "
+ f"{tracks[0]['language'] or 'track 0'} is marked default even though none "
+ "was asked for; .mkv is the container that can leave every track off")
cmd += [output]
+ total = existing_subs + len(added)
+ if total > 2 and mp4_family:
+ notes.append(f"{total} subtitle tracks in an MPEG-4 container: the tracks are all there, "
+ "but many players only ever show the first -- write to .mkv for a "
+ "deliverable a viewer can actually switch")
+ if dropped_titles:
+ notes.append("an MPEG-4 container has no per-track title this tool can write back "
+ f"({', '.join(dropped_titles)} would be dropped), so the tracks are "
+ "reported with no title; .mkv keeps the names")
+ if mp4_family and any(
+ t["language"] and len(t["language"]) != 3 for t in tracks if not t["kept_from_input"]):
+ notes.append("MPEG-4 stores the language as a three-letter ISO-639-2 code and drops "
+ "anything else; a code this tool has no conversion for was passed through "
+ "as given and may not survive")
run(cmd)
result = probe(output, role="output")
- info(f"wrote {output} ({fmt_secs(result.get('duration'))}, mux, subtitle codec {codec})")
- emit(output)
+ info(f"wrote {output} ({fmt_secs(result.get('duration'))}, mux, {len(added)} "
+ f"subtitle track(s) added, codec {codec})")
+ emit(output, tracks=tracks, subtitle_tracks=total, **({"notes": notes} if notes else {}))
return 0
# A font that covers the text, before anything is rendered: non-Latin cues in a Latin-only
@@ -1269,6 +1320,7 @@ def main() -> int:
result = probe(output, role="output")
info(f"wrote {output} ({fmt_secs(result.get('duration'))})")
extra = {"notes": side_notes} if side_notes else {}
+ extra["caption"] = dict(caption_stats)
if emoji_plan:
notes = list(extra.get("notes") or [])
if emoji_plan["mode"] == "mono":
diff --git a/scripts/check.py b/scripts/check.py
index c3187f1..008b5da 100755
--- a/scripts/check.py
+++ b/scripts/check.py
@@ -173,6 +173,25 @@ def main() -> int:
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")
+ # Subtitles, informational and on every platform: a soft subtitle track that carries no
+ # language tag is the defect caption.py --mode mux's multi-track form exists to prevent -- a
+ # player lists it as "Track 2" and a viewer cannot tell which language it is. Never counted in
+ # `failed`: no platform refuses a delivery over it.
+ subs = meta.get("subtitle_stream_details") or []
+ if not subs:
+ row("subtitles", "WARN", "none", ">= 1 language-tagged subtitle track",
+ "caption.py video.mp4 --mode mux --srt subs.srt:en -o video_subs.mkv (streams are copied)",
+ reason="subtitles are optional, but they are the cheapest accessibility win a delivery has")
+ else:
+ untagged = [str(s["index"]) for s in subs if not s.get("language")]
+ listed = ", ".join((s.get("language") or "untagged") for s in subs)
+ row("subtitles", "WARN" if untagged else "PASS", f"{len(subs)} ({listed})",
+ "every track tagged with its language",
+ "caption.py video.mp4 --mode mux --srt subs.srt:en -o video_subs.mkv, or re-mux with `--srt file:lang` per track"
+ if untagged else "",
+ reason=("stream(s) " + ", ".join(untagged) + " carry no language tag: a player lists them "
+ "by number and the viewer has to guess") if untagged else "")
+
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")
diff --git a/scripts/graphics.py b/scripts/graphics.py
index e66e5ca..bcc2489 100755
--- a/scripts/graphics.py
+++ b/scripts/graphics.py
@@ -38,7 +38,8 @@ from _common import (aac_args, add_common, brand_caption_style, script_font_for_
drawtext_boxborderw, X264_PRESETS, time_arg, fmt_secs, STATE, drawtext_text_opts,
LANGUAGE_NAMES, needs_shaping, detect_script, BIDI_SCRIPTS, font_family_of_file, font_family_for_script, has_emoji,
emoji_clusters, emoji_codepoint_name, char_script, emoji_filter_chain, emoji_asset_for, emoji_support, resolve_emoji_assets,
- EMOJI_ASSET_HINT, text_width_em, drawtext_shaping)
+ EMOJI_ASSET_HINT, text_width_em, drawtext_shaping, wrap_text, WRAP_MODES,
+ SAFE_WIDTH_FRACTION)
from _ass_overlay import text_overlay_ass, EMOJI_SENTINEL
TEMPLATES = ["lower-third", "title", "chapter", "progress", "countdown", "bug", "sticker", "hook", "meme"]
@@ -91,6 +92,12 @@ def main() -> int:
ap.add_argument("--lang", help="language code of the text (e.g. ja, zh, ko): the hint that says whether Han-only "
"text is Chinese, Japanese or Korean when a font is picked by script")
ap.add_argument("--scale", type=float, default=1.0, help="size multiplier (default 1)")
+ ap.add_argument("--wrap", choices=list(WRAP_MODES), default="phrase",
+ help="how a label too wide for the frame is broken into lines: 'phrase' (default, 1.16) never "
+ "breaks inside a word or a hyphen's wrong side, never leaves a lone digit, kana or "
+ "punctuation on its own line, prefers Japanese sentence ends and particles, and never ends "
+ "a line on an article or preposition; 'measured' is 1.15's width-only wrap. A label that "
+ "already fits one line is untouched either way")
ap.add_argument("--text-render", choices=["auto", "ass", "drawtext"], default="auto",
help="which renderer draws the template's text: 'auto' (default) uses libass for "
"scripts drawtext cannot shape (Devanagari, Bengali, Tamil, Thai, Lao ...) and for "
@@ -247,6 +254,32 @@ def main() -> int:
return os.path.dirname(os.path.abspath(script_file))
return None
+ def chip_frac(left, right, pad):
+ """The fraction of the frame a boxed label may use: the span between the margins, less
+ drawtext's own box padding on each side."""
+ usable = W - left - right - 2 * pad
+ return max(0.1, min(SAFE_WIDTH_FRACTION, usable / float(W))) if W else SAFE_WIDTH_FRACTION
+
+ def wrapped(text, size_px, frac=SAFE_WIDTH_FRACTION):
+ """A label broken to the frame's safe width (1.16).
+
+ drawtext and libass both render a literal newline as a line break, and every template
+ below already passes its label through one of them -- so wrapping is a matter of putting
+ the breaks in, at the same measured width and by the same four phrase rules caption.py
+ uses. A label that already fits comes back unchanged, which is why this is additive: the
+ only text it touches is text that used to run off the edge of the frame.
+ """
+ text = str(text or "")
+ if not text or not size_px:
+ return text
+ max_em = (W * frac) / float(size_px)
+ if max_em <= 0:
+ return text
+ out = []
+ for para in text.split("\n"):
+ out.extend(wrap_text(para, max_em, mode=args.wrap, lang=args.lang) if para.strip() else [para])
+ return "\n".join(out)
+
def add_text(text, drawtext, *, target=None, **el):
"""One line of template text: a drawtext filter on the old route, an ASS element on the
new one. The geometry is computed identically either way."""
@@ -366,8 +399,11 @@ def main() -> int:
align = (7 if "left" in pos else 9) if "top" in pos else (1 if "left" in pos else 3)
y_rest = m_top if "top" in pos else H - m_bottom
y_start = y_rest + rise if "top" in pos else y_rest + rise
- add_text(args.text,
- f"drawtext={drawtext_text_opts(args.text)}:{fo}:fontsize={fs}:fontcolor={ff_color(bg)}:"
+ # the chip is a box between the two side margins, not the whole frame: wrapping to the
+ # frame width let a long --text run off the plate even though it "fitted"
+ sticker_text = wrapped(args.text, fs, chip_frac(m_left, m_right, padx))
+ add_text(sticker_text,
+ f"drawtext={drawtext_text_opts(sticker_text)}:{fo}:fontsize={fs}:fontcolor={ff_color(bg)}:"
f"x={xe}:y='{ye}':box=1:boxcolor={ff_color(primary, 0.95)}:boxborderw={drawtext_boxborderw(pady, padx)}:"
f"alpha='{alpha}':{en}",
size=fs, color=bg, font=ass_font_family(), align=align,
@@ -391,8 +427,9 @@ def main() -> int:
band_h = int(base * 0.30)
y0 = (H - band_h) // 2
filters.append(f"drawbox=x=0:y={y0}:w=iw:h={band_h}:color={ff_color(bg, 0.78)}:t=fill:{hen}")
- add_text(args.title,
- f"drawtext={drawtext_text_opts(args.title)}:{fo}:fontsize={h1}:fontcolor={ff_color(text_c)}:"
+ hook_title = wrapped(args.title, h1)
+ add_text(hook_title,
+ f"drawtext={drawtext_text_opts(hook_title)}:{fo}:fontsize={h1}:fontcolor={ff_color(text_c)}:"
f"x=(w-text_w)/2:y=(h-text_h)/2:{hen}",
size=h1, color=text_c, font=ass_font_family(), align=5, x=W / 2, y=H / 2,
outline=max(1.0, h1 / 20.0), outline_color="000000", start=s, end=he)
@@ -401,7 +438,8 @@ def main() -> int:
elif args.template == "meme":
# The classic layout: heavy white upper-case lines with a black outline, top and bottom,
- # sized so a short line fills the frame's width without wrapping (drawtext never wraps).
+ # sized so a short line fills the frame's width; a longer one is broken by the same
+ # phrase-aware wrap caption.py uses (1.16 -- drawtext itself still never wraps).
if not (args.top or args.bottom):
die("meme needs --top and/or --bottom")
fs = int(base * 0.09)
@@ -410,8 +448,9 @@ def main() -> int:
for text, y in ((args.top, f"{m_top}"), (args.bottom, f"h-text_h-{m_bottom}")):
if not text:
continue
- add_text(text.upper(),
- f"drawtext={drawtext_text_opts(text.upper())}:{fo}:fontsize={fs}:fontcolor={white}:"
+ meme_line = wrapped(text.upper(), fs)
+ add_text(meme_line,
+ f"drawtext={drawtext_text_opts(meme_line)}:{fo}:fontsize={fs}:fontcolor={white}:"
f"borderw={bw}:bordercolor={black}:x=(w-text_w)/2:y={y}:{en}",
size=fs, color="FFFFFF", font=ass_font_family(), bold=True,
align=(8 if y == f"{m_top}" else 2), x=W / 2,
diff --git a/scripts/metadata.py b/scripts/metadata.py
index 12d7a35..8df78d7 100755
--- a/scripts/metadata.py
+++ b/scripts/metadata.py
@@ -30,7 +30,9 @@ import tempfile
from pathlib import Path
from typing import Any, Dict, List, Optional
-from _common import add_common, apply_common, default_output, die, emit, ffmpeg_base, info, time_arg, probe, run, STATE, read_text_or_die
+from _common import (add_common, apply_common, default_output, description_block, detect_scenes, detect_silences,
+ die, emit, ffmpeg_base, fmt_chapter_time, info, propose_chapters, time_arg, probe, run,
+ STATE, read_text_or_die)
CHAPTER_CONTAINERS = {".mp4", ".m4v", ".m4a", ".mov", ".mkv", ".mka", ".webm"}
TAG_KEYS = ("title", "artist", "album", "comment", "date", "genre")
@@ -82,12 +84,119 @@ def write_ffmetadata(chapters: List[Dict[str, Any]], path: str) -> None:
Path(path).write_text("\n".join(lines) + "\n", encoding="utf-8")
+def propose(args, meta: Dict[str, Any], duration: float,
+ notes: List[str]) -> "tuple":
+ """--auto-chapters: measure the structure, then hand it to the pure proposer.
+
+ The detectors are the ones silence.py and scenes.py run (they live in _common/probe.py since
+ 1.16 so that no tool has to import another tool); the decision is propose_chapters(), which
+ is pure and never looks at content.
+ """
+ source = args.detect_from
+ if not meta.get("audio") and source in ("silence", "both"):
+ if source == "silence":
+ die("--from silence needs an input with an audio stream; use --from scenes", kind="input")
+ source = "scenes"
+ notes.append("no audio stream: the markers come from scene changes alone (--from scenes)")
+ if not meta.get("video") and source in ("scenes", "both"):
+ if source == "scenes":
+ die("--from scenes needs an input with a video stream; use --from silence", kind="input")
+ source = "silence"
+ notes.append("no video stream: the markers come from the pauses alone (--from silence)")
+ silences = detect_silences(args.input, args.silence_threshold, args.silence_min) \
+ if source in ("silence", "both") else []
+ cuts = detect_scenes(args.input, args.scene_threshold, 1.0, duration) \
+ if source in ("scenes", "both") else []
+ if source == "both":
+ notes.append("measured in 2 passes (silencedetect and scdet each decode the file once); "
+ "--from silence is the cheap path")
+ proposed = propose_chapters(duration, silences, cuts, min_chapter=args.min_chapter,
+ max_chapters=args.max_chapters, source=source)
+ if len(proposed) == 1:
+ # every suggestion has to be a value the caller is not already using, or the hint reads
+ # "try --min-chapter 1" to someone who passed --min-chapter 1
+ tries = []
+ shorter_silence = round(args.silence_min / 2.0, 2)
+ if shorter_silence >= 0.1 and shorter_silence < args.silence_min:
+ tries.append(f"--silence-min {shorter_silence:g}")
+ shorter_chapter = max(1.0, round(args.min_chapter / 2.0, 2))
+ if shorter_chapter < args.min_chapter:
+ tries.append(f"--min-chapter {shorter_chapter:g}")
+ if args.detect_from != "both" and meta.get("audio") and meta.get("video"):
+ tries.append("--from both")
+ notes.append(f"no pause longer than {args.silence_min:g}s and no scene change far enough apart "
+ "to start a chapter: the file gets one marker at 0:00"
+ + (". Try " + " or ".join(tries) if tries else
+ ", and the thresholds are already as low as this tool will suggest"))
+ total = len([1 for _s in silences]) + len([c for c in cuts if c > 0])
+ auto = {
+ "source": {"silence": "silence", "scenes": "scenes", "both": "silence+scenes"}[source],
+ "min_chapter": float(args.min_chapter),
+ "max_chapters": int(args.max_chapters),
+ "proposed": total,
+ "kept": len(proposed),
+ "titles": "placeholder",
+ "chapters": proposed,
+ "description_block": description_block(proposed),
+ }
+ entries = [{"start": c["at"], "title": c["title"]} for c in proposed]
+ for i, e in enumerate(entries):
+ e["end"] = entries[i + 1]["start"] if i + 1 < len(entries) else duration
+ info(f"proposed {len(entries)} chapters from {auto['source']} "
+ f"(titles are placeholders: Chapter 1..{len(entries)})")
+ return entries, auto
+
+
+def write_proposal(args, chapters: List[Dict[str, Any]]) -> Dict[str, Any]:
+ """--chapters-out / --description-out, the two side files a caller edits and feeds back."""
+ files: Dict[str, Any] = {"chapters": None, "description": None}
+ if args.chapters_out:
+ body = "\n".join(f"{fmt_chapter_time(c['at'])} {c['title']}" for c in chapters) + "\n"
+ if STATE.dry_run:
+ info(f"[dry-run] would write {args.chapters_out} ({len(chapters)} chapters)")
+ else:
+ Path(args.chapters_out).write_text(body, encoding="utf-8")
+ info(f"wrote {args.chapters_out} ({len(chapters)} chapters)")
+ files["chapters"] = args.chapters_out
+ if args.description_out:
+ body = description_block(chapters) + "\n"
+ if STATE.dry_run:
+ info(f"[dry-run] would write {args.description_out}")
+ else:
+ Path(args.description_out).write_text(body, encoding="utf-8")
+ info(f"wrote {args.description_out}")
+ files["description"] = args.description_out
+ return files
+
+
def main() -> int:
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("input")
ap.add_argument("-o", "--output", help="output file (default: <name>_meta.<ext>)")
ap.add_argument("--chapters", help="text file, one chapter per line: `TIME TITLE` (cut.py time syntax)")
ap.add_argument("--clear-chapters", action="store_true", help="remove every chapter marker the input carries")
+ auto = ap.add_argument_group("proposed chapters (1.16)",
+ "Chapter timestamps measured from the file's own structure instead of read from a "
+ "file. The markers are proposed, the titles are not: every one is `Chapter N` and "
+ "renaming them is the caller's job -- knowing what is said in a chapter is not "
+ "something this skill can measure. Two detectors mean two full decodes of the "
+ "input; --from silence is the cheap path.")
+ auto.add_argument("--auto-chapters", action="store_true",
+ help="propose the markers from measured pauses and scene changes instead of reading --chapters FILE")
+ auto.add_argument("--min-chapter", type=float, default=60.0,
+ help="shortest chapter in seconds (default 60, a long-form default: a 12-minute episode gets at most 12)")
+ auto.add_argument("--max-chapters", type=int, default=0,
+ help="cap the number of markers (default 0 = no cap); the weakest evidence is dropped first")
+ auto.add_argument("--from", dest="detect_from", choices=["silence", "scenes", "both"], default="both",
+ help="which detector(s) propose the markers (default both)")
+ auto.add_argument("--silence-threshold", type=float, default=-35.0,
+ help="silence level in dBFS for --auto-chapters (default -35)")
+ auto.add_argument("--silence-min", type=float, default=1.5,
+ help="a pause must last this long to propose a chapter (default 1.5 -- deliberately longer than silence.py's 0.6: a chapter break is a long pause)")
+ auto.add_argument("--scene-threshold", type=float, default=8.0,
+ help="minimum scdet score for a scene cut with --auto-chapters (default 8, as scenes.py)")
+ auto.add_argument("--chapters-out", help="write the proposal as a `TIME TITLE` file in this tool's own --chapters format, so the titles can be edited and fed back")
+ auto.add_argument("--description-out", help="write the YouTube description block (`00:00 Chapter 1` per line)")
for key in TAG_KEYS:
ap.add_argument(f"--{key}", help=f"set the container's {key} tag (empty string clears it)")
add_common(ap)
@@ -96,9 +205,15 @@ def main() -> int:
if args.chapters and args.clear_chapters:
die("--chapters and --clear-chapters exclude each other")
+ if args.auto_chapters and (args.chapters or args.clear_chapters):
+ die("--auto-chapters proposes the markers; it excludes --chapters FILE and --clear-chapters")
+ if args.min_chapter <= 0:
+ die(f"--min-chapter must be > 0, got {args.min_chapter:g}")
+ if args.max_chapters < 0:
+ die(f"--max-chapters must be >= 0 (0 = no cap), got {args.max_chapters}")
tags = {k: getattr(args, k) for k in TAG_KEYS if getattr(args, k) is not None}
- if not args.chapters and not args.clear_chapters and not tags:
- die("nothing to write: give --chapters FILE, --clear-chapters and/or --title/--artist/...")
+ if not args.chapters and not args.clear_chapters and not args.auto_chapters and not tags:
+ die("nothing to write: give --chapters FILE, --auto-chapters, --clear-chapters and/or --title/--artist/...")
if args.chapters and not os.path.exists(args.chapters):
die(f"chapters file not found: {args.chapters}")
@@ -107,12 +222,16 @@ def main() -> int:
if os.path.abspath(output) == os.path.abspath(args.input):
die("output must differ from the input (metadata.py never rewrites a file in place)")
out_ext = Path(output).suffix.lower()
- if (args.chapters or args.clear_chapters) and out_ext not in CHAPTER_CONTAINERS:
+ if (args.chapters or args.clear_chapters or args.auto_chapters) and out_ext not in CHAPTER_CONTAINERS:
die(f"{out_ext or 'this'} container cannot hold chapter markers; write to one of "
f"{', '.join(sorted(CHAPTER_CONTAINERS))} (the streams are copied, so choose the matching family: .mp4/.mov/.m4a for MPEG-4, .mkv/.mka/.webm for Matroska)")
duration = meta.get("duration") or 0.0
chapters: Optional[List[Dict[str, Any]]] = parse_chapters(args.chapters, duration) if args.chapters else None
+ auto: Optional[Dict[str, Any]] = None
+ notes: List[str] = []
+ if args.auto_chapters:
+ chapters, auto = propose(args, meta, duration, notes)
cmd = ffmpeg_base() + ["-i", args.input]
tmpdir = None
@@ -139,7 +258,13 @@ def main() -> int:
if args.clear_chapters and not STATE.dry_run and written:
die(f"{len(written)} chapters survived --clear-chapters", kind="output")
info(f"wrote {output} ({len(written)} chapters, tags: {', '.join(sorted(tags)) or 'unchanged'}, streams copied)")
- emit(output, chapters=written, tags=result.get("tags") or {}, streams_copied=True)
+ extra: Dict[str, Any] = {}
+ if auto is not None:
+ auto["files"] = write_proposal(args, auto["chapters"])
+ extra["auto_chapters"] = auto
+ if notes:
+ extra["notes"] = notes
+ emit(output, chapters=written, tags=result.get("tags") or {}, streams_copied=True, **extra)
return 0
diff --git a/scripts/render.py b/scripts/render.py
index ff16f10..b2f3926 100755
--- a/scripts/render.py
+++ b/scripts/render.py
@@ -67,7 +67,7 @@ HERE = Path(__file__).resolve().parent
TEMPLATE_DIR = HERE.parent / "templates"
# The placeholders a delivery template carries; a block whose placeholder has no value
# (no --logo, no --title, no cues) is dropped from the filled project rather than rendered empty.
-PLACEHOLDERS = ("$INPUT", "$OUTPUT", "$CUES", "$SRT", "$LOGO", "$TITLE", "$BRAND", "$CHAPTERS")
+PLACEHOLDERS = ("$INPUT", "$OUTPUT", "$CUES", "$SRT", "$LOGO", "$TITLE", "$BRAND", "$CHAPTERS", "$IMAGE")
# Intermediates follow the delivery's own media kind: an audio-only project (the podcast
# template) must not carry its stages through .mp4 containers.
AUDIO_EXT = frozenset({".wav", ".m4a", ".mp3", ".flac", ".aac", ".ogg", ".opus"})
@@ -97,11 +97,14 @@ TEMPLATE = {
OBJECT_KEYS: Dict[str, frozenset] = {
"project": frozenset({"output", "frame", "clips", "transition", "silence", "brand", "captions",
"graphics", "overlays", "audio", "loudness", "fit", "export", "check", "chapters",
- "template"}),
+ "audiogram", "template"}),
"clips[]": frozenset({"src", "in", "out", "speed"}),
"frame": frozenset({"aspect", "width", "height", "fps", "fit"}),
"transition": frozenset({"type", "duration"}),
"silence": frozenset({"threshold", "min_silence", "margin"}),
+ # 1.16: the picture an audio-only source gets before the rest of the chain can work on it
+ "audiogram": frozenset({"image", "image_fit", "style", "position", "vis_height", "opacity",
+ "platform", "title", "color", "background", "width", "height", "fps"}),
"captions": frozenset({"text", "srt", "ass", "font", "size", "color", "position", "margin",
"animate", "highlight_color", "outline", "karaoke", "bold", "box",
"lang", "offset", "max_lines", "min_duration"}),
@@ -202,9 +205,10 @@ def template_project(name: str, args) -> Dict[str, Any]:
"$BRAND": os.path.abspath(args.brand) if args.brand else None,
"$CHAPTERS": os.path.abspath(args.chapters) if args.chapters else None,
"$TITLE": args.title,
+ "$IMAGE": os.path.abspath(args.image) if args.image else None,
}
for flag, path in (("--cues", args.cues), ("--srt", args.srt), ("--logo", args.logo),
- ("--brand", args.brand), ("--chapters", args.chapters)):
+ ("--brand", args.brand), ("--chapters", args.chapters), ("--image", args.image)):
if path and not os.path.isfile(path):
die(f"{flag}: file not found: {path}")
proj, _ = fill_template(tpl, values)
@@ -286,7 +290,7 @@ def render_pack(names: List[str], args) -> int:
argv = [str(HERE / "render.py"), args.input, "--template", name, "-o", dest_out]
for flag, value in (("--cues", args.cues), ("--srt", args.srt), ("--logo", args.logo),
("--title", args.title), ("--brand", args.brand), ("--fit", args.fit),
- ("--chapters", args.chapters)):
+ ("--chapters", args.chapters), ("--image", args.image)):
if value:
argv += [flag, str(value)]
info(f"→ pack: {name}")
@@ -355,7 +359,7 @@ def check_keys(obj: Any, schema: str, label: str) -> None:
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"):
+ for name in ("frame", "transition", "silence", "audiogram", "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):
@@ -508,6 +512,7 @@ def main() -> int:
tpl.add_argument("--title", help="title text for the template's opening card / lower third")
tpl.add_argument("--brand", help="brand.json the template's captions, graphics and overlays use")
tpl.add_argument("--chapters", help="chapter file (podcast template)")
+ tpl.add_argument("--image", help="still image behind the visualisation (audiogram template); a local file, nothing is fetched")
tpl.add_argument("--fit", choices=["crop", "pad", "blur"], help="override how the template reaches its aspect")
tpl.add_argument("-o", "--output", help="output file (default: next to the input, <input>_<template>.mp4, "
"or .m4a for an audio-only destination); for a list of templates "
@@ -544,7 +549,7 @@ def main() -> int:
else:
for flag, value in (("--cues", args.cues), ("--srt", args.srt), ("--logo", args.logo),
("--title", args.title), ("--brand", args.brand), ("--chapters", args.chapters),
- ("--fit", args.fit), ("--write-project", args.write_project)):
+ ("--image", args.image), ("--fit", args.fit), ("--write-project", args.write_project)):
if value:
die(f"{flag} belongs to --template NAME INPUT; a project.json states it in the project itself")
try:
@@ -645,6 +650,28 @@ def main() -> int:
parts.append(part)
stages_done.append("clips")
current = parts[0]
+
+ # ---- audiogram: the picture an audio-only source needs before anything else can work on it
+ ag = proj.get("audiogram")
+ if ag:
+ if not ag.get("image") and not ag.get("background"):
+ die('audiogram: give an "image" (a local file) or a "background" colour -- this skill '
+ "never fetches a picture and never invents cover art", kind="input")
+ nxt = str(work / f"audiogram{mid}")
+ argv = [current, "-o", nxt]
+ for key, flag in (("image", "--image"), ("image_fit", "--image-fit"), ("style", "--style"),
+ ("position", "--position"), ("vis_height", "--vis-height"),
+ ("opacity", "--opacity"), ("platform", "--platform"), ("title", "--title"),
+ ("color", "--color"), ("background", "--background"),
+ ("width", "--width"), ("height", "--height"), ("fps", "--fps")):
+ if ag.get(key) is not None:
+ argv += [flag, str(ag[key])]
+ argv += brand_args
+ sh("waveform.py", *argv)
+ current = nxt
+ parts = [current]
+ stages_done.append("audiogram")
+
if args.stop_after == "clips":
emit(current, stages=stages_done)
return 0
diff --git a/scripts/scenes.py b/scripts/scenes.py
index b0dad10..f586874 100755
--- a/scripts/scenes.py
+++ b/scripts/scenes.py
@@ -19,70 +19,12 @@ Examples:
"""
import argparse
import math
-import os
-import re
import sys
from typing import Dict, List, Tuple
-from _common import STATE, add_common, apply_common, default_font_file, die, emit, escape_filter_path, ffmpeg_base, info, print_json, probe, require_tool, run, run_analysis, decode_pcm_mono, rms_envelope
-
-SCORE_RE = re.compile(r"frame:(\d+)\s+pts:\d+\s+pts_time:([0-9.]+)")
-
-
-def detect_scenes(path: str, threshold: float, min_len: float, duration: float, ratio: float = 3.0) -> List[float]:
- """Scene cuts = frames whose scdet score is above `threshold` AND stands out from its
- neighbourhood (score > ratio x median of the surrounding +-12 frames). Sustained motion,
- flashes and fast pans raise the score on many consecutive frames and are rejected;
- a real cut is a one-frame spike. On real footage this roughly doubles precision at
- equal recall compared with the raw scdet threshold."""
- ffmpeg = require_tool("ffmpeg")
- proc = run_analysis([ffmpeg, "-hide_banner", "-nostdin", "-i", path, "-an", "-vf",
- "scale=320:-2,scdet=threshold=0,metadata=print:file=-", "-f", "null", "-"])
- # No `sc_pass=1` on scdet: on FFmpeg 5.x that option means "pass only the frames whose
- # score exceeds the threshold", so every truly static frame (score exactly 0 -- a title
- # card, colour bars) is dropped before metadata=print and the frame numbers are re-counted
- # without them. The +-12-frame neighbourhood around a real cut then fills with the moving
- # segment's scores instead of the still one's zeros, the cut fails the ratio test, and a
- # 4 s smptebars scene made the cuts on both sides of it disappear (found by the 5.1.1 CI
- # job, #146). 6.1+ passes every frame either way. Scores are still indexed by frame number
- # and any frame the filter did not report counts as 0, so a build that drops frames again
- # cannot shift the neighbourhood.
- by_frame: Dict[int, Tuple[float, float]] = {}
- cur = None
- for line in proc.stdout.splitlines():
- m = SCORE_RE.match(line)
- if m:
- cur = (int(m.group(1)), float(m.group(2)))
- continue
- if line.startswith("lavfi.scd.score=") and cur is not None:
- try:
- by_frame[cur[0]] = (cur[1], float(line.split("=", 1)[1]))
- except ValueError:
- pass
- cuts = [0.0]
- if not by_frame:
- return cuts
- n_frames = max(by_frame) + 1
- times: List[float] = [by_frame[i][0] if i in by_frame else -1.0 for i in range(n_frames)]
- scores: List[float] = [by_frame[i][1] if i in by_frame else 0.0 for i in range(n_frames)]
- w = 12
- for i, sc in enumerate(scores):
- if sc < threshold:
- continue
- lo, hi = max(0, i - w), min(len(scores), i + w + 1)
- neigh = sorted(scores[lo:i] + scores[i + 1:hi])
- med = neigh[len(neigh) // 2] if neigh else 0.0
- if sc < ratio * max(med, 0.5):
- continue
- # keep only the local maximum inside +-2 frames
- if any(scores[j] > sc for j in range(max(0, i - 2), min(len(scores), i + 3)) if j != i):
- continue
- t = times[i]
- if t - cuts[-1] >= min_len:
- cuts.append(t)
- if duration - cuts[-1] < min_len and len(cuts) > 1:
- cuts.pop()
- return cuts
+# `detect_scenes` moved into _common/probe.py in 1.16.0 (see silence.py); the body is unchanged.
+from _common import detect_scenes, STATE, add_common, apply_common, default_font_file, die, emit, escape_filter_path, ffmpeg_base, info, print_json, probe, run, decode_pcm_mono, rms_envelope
+
def audio_envelope(path: str, step_s: float) -> List[float]:
diff --git a/scripts/silence.py b/scripts/silence.py
index 4d7020c..cd0f799 100755
--- a/scripts/silence.py
+++ b/scripts/silence.py
@@ -13,35 +13,13 @@ Examples:
"""
import argparse
import os
-import re
import sys
from typing import List, Tuple
-from _common import STATE, video_args, add_common, apply_common, audio_codec_for, cfr_args, default_output, die, emit, ffmpeg_base, info, is_audio_output, print_json, probe, require_tool, run, x264_args, X264_PRESETS, measured_level_dbfs, run_analysis, dry_run_input_pending, fmt_secs
+# `detect` moved into _common/probe.py in 1.16.0 so metadata.py --auto-chapters can measure the
+# same silences without importing this tool; the body is unchanged and the name still lives here.
+from _common import detect_silences as detect, STATE, video_args, add_common, apply_common, audio_codec_for, cfr_args, default_output, die, emit, ffmpeg_base, info, is_audio_output, print_json, probe, run, X264_PRESETS, measured_level_dbfs, fmt_secs
-SIL_RE = re.compile(r"silence_(start|end): ([0-9.]+)")
-
-
-def detect(path: str, threshold: float, min_silence: float) -> List[Tuple[float, float]]:
- if dry_run_input_pending(path):
- return []
- ffmpeg = require_tool("ffmpeg")
- cmd = [ffmpeg, "-hide_banner", "-nostdin", "-i", path, "-vn", "-af",
- f"silencedetect=noise={threshold}dB:d={min_silence}", "-f", "null", "-"]
- proc = run_analysis(cmd, check=False, record=True)
- if proc.returncode != 0:
- die(f"silencedetect failed:\n{proc.stderr.strip()[-800:]}", kind="ffmpeg")
- silences: List[Tuple[float, float]] = []
- start = None
- for kind, val in SIL_RE.findall(proc.stderr):
- if kind == "start":
- start = float(val)
- elif start is not None:
- silences.append((start, float(val)))
- start = None
- if start is not None: # silence runs to the end
- silences.append((start, float("inf")))
- return silences
def keep_ranges(silences: List[Tuple[float, float]], duration: float, margin: float, min_keep: float) -> List[Tuple[float, float]]:
diff --git a/scripts/waveform.py b/scripts/waveform.py
index 0bcc19d..42c195c 100644
--- a/scripts/waveform.py
+++ b/scripts/waveform.py
@@ -18,11 +18,26 @@ Examples:
python3 waveform.py podcast.wav -o waveform.mp4
python3 waveform.py track.wav --style spectrum --width 1920 --height 1080 -o spectrum.mp4
python3 waveform.py interview.mp4 --split-channels --color cyan|magenta
+
+An *audiogram* is the same render over a picture: --image cover.png puts a
+still behind the visualisation, --platform sizes the frame for a
+destination, --srt burns the captions on afterwards (by running caption.py,
+not by re-implementing the subtitle path) and --title draws one static
+label through graphics.py. Nothing is ever fetched and no cover art is ever
+invented: give an image or a colour.
+
+ python3 waveform.py ep.m4a --image cover.png --platform reels --position strip -o ep.mp4
+ python3 waveform.py ep.m4a --image cover.png --srt ep.srt --title "Episode 12" -o ep.mp4
"""
import argparse
+import os
+import subprocess
import sys
-from _common import add_common, apply_common, aac_args, default_output, die, emit, ffmpeg_base, info, probe, run, validate_color, video_args, X264_PRESETS, fmt_secs
+from _platforms import PLATFORMS, PLATFORM_CHOICES, resolve as resolve_platform
+from _common import (add_common, apply_common, aac_args, default_output, die, emit, ffmpeg_base,
+ info, load_brand, pad_filters, probe, run, STATE, validate_color, video_args, X264_PRESETS,
+ fmt_secs)
WAVEFORM_MODES = ["point", "line", "p2p", "cline"]
@@ -41,12 +56,65 @@ def main() -> int:
ap.add_argument("--split-channels", action="store_true", help="draw each channel in its own lane instead of summing to one")
ap.add_argument("--audio-stream", type=int, default=0,
help="which audio stream of the input to render, 0-based in file order (default 0)")
+ ag = ap.add_argument_group("audiogram (1.16)",
+ "The visualisation over a picture, for an episode that has no video. The image is a "
+ "local file you give: this skill has no network access and never invents cover art.")
+ ag.add_argument("--image", help="still image or brand plate to put behind the visualisation (a local file; scaled to cover the frame and centre-cropped)")
+ ag.add_argument("--image-fit", choices=["cover", "contain", "blur"], default="cover",
+ help="how a still of the wrong aspect fills the frame: cover (default, crop the overflow), contain (bars in --background), blur (bars are a blurred copy, as fit.py)")
+ ag.add_argument("--position", choices=["bottom", "centre", "center", "top", "strip"], default="strip",
+ help="where the visualisation sits over the plate (default strip: a band of --vis-height along the bottom, the podcast-audiogram convention)")
+ ag.add_argument("--vis-height", type=float, default=0.35,
+ help="height of the visualisation band as a fraction of the frame (default 0.35)")
+ ag.add_argument("--opacity", type=float, default=1.0, help="visualisation alpha over the plate, 0..1 (default 1)")
+ ag.add_argument("--platform", choices=PLATFORM_CHOICES, default=None,
+ help="take the frame size and fps from this destination instead of --width/--height/--fps")
+ ag.add_argument("--srt", help="burn these captions into the render afterwards, by running caption.py (never re-implemented here)")
+ ag.add_argument("--text", help="plain cue file to burn, same as caption.py --text")
+ ag.add_argument("--title", help="one static label drawn over the plate, through graphics.py's sticker template")
+ ag.add_argument("--brand", help="brand.json: --color / --background / font defaults")
ap.add_argument("--crf", type=int, default=18, help="x264 CRF (default 18)")
ap.add_argument("--preset", default="medium", choices=X264_PRESETS, help="x264 preset")
add_common(ap)
args = ap.parse_args()
apply_common(args)
+ args.platform = resolve_platform(args.platform)
+ if args.platform:
+ frame = PLATFORMS[args.platform].get("frame")
+ if not frame:
+ die(f"--platform {args.platform}: that destination has no frame (it is an audio spec); "
+ "give --width/--height, or name a destination that has a picture", kind="input")
+ args.width, args.height = frame["w"], frame["h"]
+ args.fps = float(PLATFORMS[args.platform].get("fps") or args.fps)
+ info(f"--platform {args.platform}: {args.width}x{args.height} @ {args.fps:g}fps")
+ brand = load_brand(args.brand) if args.brand else None
+ if brand:
+ bc = brand.get("colors") or {}
+ if args.color == "lime" and bc.get("primary"):
+ args.color = bc["primary"]
+ if args.background == "black" and bc.get("background"):
+ args.background = bc["background"]
+ if args.image:
+ if "://" in args.image:
+ die("--image must be a readable local file; this skill has no network access, so save "
+ "the image locally and pass its path", kind="input")
+ if not os.path.exists(args.image):
+ die(f"--image file not found: {args.image}", kind="input")
+ if not STATE.dry_run:
+ plate = probe(args.image, role="input")
+ if not (plate.get("video") or {}).get("width"):
+ die(f"--image is not an image ffmpeg can decode: {args.image}", kind="input")
+ if args.background != "black":
+ die("--image and a non-default --background exclude each other: the plate is either "
+ "the picture or the colour", kind="input")
+ if not 0.0 <= args.opacity <= 1.0:
+ die(f"--opacity must be between 0 and 1, got {args.opacity:g}")
+ if not 0.0 < args.vis_height <= 1.0:
+ die(f"--vis-height must be between 0 and 1, got {args.vis_height:g}")
+ if args.srt and args.text:
+ die("--srt and --text exclude each other (both name the cues to burn)")
+
if args.width <= 0 or args.height <= 0:
die(f"--width/--height must be > 0, got width={args.width} height={args.height}")
if args.width % 2 or args.height % 2:
@@ -65,17 +133,58 @@ def main() -> int:
die(f"--audio-stream {args.audio_stream}: input has {len(audio_streams)} audio stream(s), 0..{len(audio_streams) - 1}")
output = args.output or default_output(args.input, "waveform")
+ # The visualisation's own band. Without --image/--position it fills the frame, which is what
+ # every 1.15 command line did, so the graph below is byte-identical when no new flag is given.
+ vis_h = args.height
+ vis_y = 0
+ if args.image:
+ vis_h = max(2, int(round(args.height * args.vis_height)) // 2 * 2)
+ pos = "centre" if args.position == "center" else args.position
+ vis_y = {"top": 0, "centre": (args.height - vis_h) // 2,
+ "bottom": args.height - vis_h, "strip": args.height - vis_h}[pos]
+
if args.style == "waveform":
- vf = (f"showwaves=s={args.width}x{args.height}:mode={args.waveform_mode}:rate={args.fps:g}:"
+ vf = (f"showwaves=s={args.width}x{vis_h}:mode={args.waveform_mode}:rate={args.fps:g}:"
f"split_channels={1 if args.split_channels else 0}:colors={args.color}")
else:
- vf = f"showspectrum=s={args.width}x{args.height}:mode={'separate' if args.split_channels else 'combined'}:fps={args.fps:g}"
- # showwaves/showspectrum paint the visualization on a transparent-black canvas; composite
- # it over an explicit solid background instead of assuming that canvas already matches
- # --background.
- vf = f"color=c={args.background}:s={args.width}x{args.height}:r={args.fps:g}[bg];[0:a:{args.audio_stream}]{vf}[vis];[bg][vis]overlay=format=auto"
+ vf = f"showspectrum=s={args.width}x{vis_h}:mode={'separate' if args.split_channels else 'combined'}:fps={args.fps:g}"
+ if args.image:
+ # One filter_complex, one encode: the still gets a timeline with -loop 1, is scaled to the
+ # frame by --image-fit, and the visualisation is overlaid on it at --opacity.
+ if args.image_fit == "cover":
+ plate = (f"scale={args.width}:{args.height}:force_original_aspect_ratio=increase,"
+ f"crop={args.width}:{args.height},setsar=1")
+ else:
+ plate = pad_filters(args.width, args.height,
+ "blur" if args.image_fit == "blur" else "color",
+ args.background, 20)
+ graph = f"[1:v]{plate},format=rgba[plate];[0:a:{args.audio_stream}]{vf},format=rgba"
+ if args.opacity < 1.0:
+ graph += f",colorchannelmixer=aa={args.opacity:g}"
+ graph += f"[vis];[plate][vis]overlay=x=(W-w)/2:y={vis_y}:format=auto[v]"
+ vf = graph
+ else:
+ # showwaves/showspectrum paint the visualization on a transparent-black canvas; composite
+ # it over an explicit solid background instead of assuming that canvas already matches
+ # --background.
+ vf = f"color=c={args.background}:s={args.width}x{args.height}:r={args.fps:g}[bg];[0:a:{args.audio_stream}]{vf}[vis];[bg][vis]overlay=format=auto"
- cmd = ffmpeg_base() + ["-i", args.input, "-filter_complex", vf, "-map", f"0:a:{args.audio_stream}"]
+ render = output
+ if args.title or args.srt or args.text:
+ # the visualisation is rendered first and the label/captions are drawn on it by the tools
+ # that own those code paths, so neither is re-implemented here
+ stem, ext = os.path.splitext(output)
+ render = stem + "_vis" + ext
+ cmd = ffmpeg_base() + ["-i", args.input]
+ if args.image:
+ # -framerate before -loop: a looped still defaults to 25 fps, and overlay takes its rate
+ # from the FIRST input -- so without this the file came out 25 fps however loud --fps or
+ # --platform said otherwise (the colour-plate path never had the bug: `color=` carries r=).
+ cmd += ["-framerate", f"{args.fps:g}", "-loop", "1", "-i", args.image]
+ cmd += ["-filter_complex", vf]
+ if args.image:
+ cmd += ["-map", "[v]"]
+ cmd += ["-map", f"0:a:{args.audio_stream}"]
cmd += video_args(None, args.crf, args.preset) # the one encoder line, so --codec / --quality reach it (review 7)
cmd += aac_args()
# -shortest alone is not enough on FFmpeg 5.x: showwaves keeps emitting frames after the
@@ -83,15 +192,93 @@ def main() -> int:
# at the source's own duration when probe knows it.
if meta.get("duration"):
cmd += ["-t", f"{float(meta['duration']):.3f}"]
- cmd += ["-shortest", output]
+ cmd += ["-shortest", render]
run(cmd)
+ stages = ["waveform"]
+ current = render
+ if args.title:
+ stem, ext = os.path.splitext(output)
+ titled = stem + "_titled" + ext if (args.srt or args.text) else output
+ _child("graphics.py", [current, "--template", "sticker", "--text", args.title,
+ "--position", "top-left", "-o", titled]
+ + (["--brand", args.brand] if args.brand else []))
+ stages.append("title")
+ current = titled
+ if args.srt or args.text:
+ _child("caption.py", [current] + (["--srt", args.srt] if args.srt else ["--text", args.text])
+ + (["--platform", args.platform] if args.platform else []) + ["-o", output])
+ stages.append("captions")
+ current = output
+ if current != output and not STATE.dry_run:
+ os.replace(current, output)
+ current = output
+ # the intermediates exist only to keep each tool's own code path the only one there is
+ for temp in (render, os.path.splitext(output)[0] + "_titled" + os.path.splitext(output)[1]):
+ if temp != output and os.path.exists(temp) and not STATE.dry_run:
+ os.remove(temp)
+
result = probe(output, role="output")
- v = result["video"]
- info(f"wrote {output} ({fmt_secs(result['duration'])}, {v['width']}x{v['height']}, {args.style})")
- emit(output)
+ v = result["video"] or {}
+ notes: "list" = []
+ if args.image and args.platform and args.srt:
+ safe_px = int(round(PLATFORMS[args.platform]["safe"]["bottom"] * args.height))
+ overlap = (vis_h + safe_px) - args.height
+ if args.position in ("strip", "bottom") and overlap > 0:
+ notes.append(f"the visualisation band and {args.platform}'s bottom safe zone overlap by "
+ f"{overlap}px: the captions or the app's own UI will sit over the waveform "
+ f"(lower --vis-height to {max(0.05, (args.height - safe_px) / args.height):.2f})")
+ duration_ok = True
+ if not STATE.dry_run and meta.get("duration") and result.get("duration"):
+ duration_ok = abs(float(result["duration"]) - float(meta["duration"])) <= 0.05
+ if not duration_ok:
+ notes.append("the render is " + fmt_secs(result.get("duration")) + " against "
+ + fmt_secs(meta.get("duration")) + " of audio")
+ size_ok = (v.get("width"), v.get("height")) == (args.width, args.height) or STATE.dry_run
+ # the rate the run announced is the rate the file must carry: the audiogram path builds the
+ # plate as a second input, so getting this wrong is silent (see the -framerate above)
+ fps_ok = True
+ if not STATE.dry_run and v.get("fps"):
+ fps_ok = abs(float(v["fps"]) - float(args.fps)) <= 0.01
+ if not fps_ok:
+ notes.append(f"the render is {float(v['fps']):g} fps against the {args.fps:g} fps asked for")
+ # reported on every run, not only an audiogram one: a caller that keys on `audiogram.background`
+ # should not have to guess whether the key exists (`"color"` is the plain-waveform answer).
+ extra = {"audiogram": {
+ "style": args.style,
+ "background": "image" if args.image else "color",
+ "image": args.image,
+ "position": args.position if args.image else None,
+ "vis_height": args.vis_height if args.image else 1.0,
+ "platform": args.platform,
+ "captions": (args.srt or args.text) if (args.srt or args.text) else None,
+ "title": args.title,
+ "stages": stages,
+ # a dry run rendered nothing, so there is nothing to have verified -- the common
+ # top-level `verified` says false for the same run and these two must not disagree
+ "verified": False if STATE.dry_run else bool(duration_ok and size_ok and fps_ok),
+ }}
+ if notes:
+ extra["notes"] = notes
+ info(f"wrote {output} ({fmt_secs(result['duration'])}, {v.get('width')}x{v.get('height')}, {args.style}"
+ + (", audiogram" if args.image else "") + ")")
+ emit(output, **extra)
return 0
+def _child(script_name: str, argv: "list") -> None:
+ """Run one of this skill's own tools as a second process, so the code path it owns (the ASS
+ generator, the drawtext template) stays the only one there is."""
+ here = os.path.dirname(os.path.abspath(__file__))
+ cmd = [sys.executable, os.path.join(here, script_name)] + [str(a) for a in argv]
+ if STATE.dry_run:
+ cmd.append("--dry-run")
+ info("-> " + " ".join(os.path.basename(c) if c.endswith(".py") else str(c) for c in cmd[1:]))
+ proc = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True,
+ encoding="utf-8", errors="replace")
+ if proc.returncode != 0:
+ die(f"{script_name} failed:\n{(proc.stderr or proc.stdout).strip()[-800:]}", kind="ffmpeg")
+
+
if __name__ == "__main__":
sys.exit(main())
diff --git a/templates/audiogram.json b/templates/audiogram.json
new file mode 100644
index 0000000..1970d2a
--- /dev/null
+++ b/templates/audiogram.json
@@ -0,0 +1,31 @@
+{
+ "template": "audiogram",
+ "output": "$OUTPUT",
+ "clips": [
+ {
+ "src": "$INPUT"
+ }
+ ],
+ "audiogram": {
+ "image": "$IMAGE",
+ "style": "waveform",
+ "position": "strip"
+ },
+ "captions": {
+ "text": "$CUES",
+ "size": 20,
+ "position": "bottom",
+ "margin": 14
+ },
+ "loudness": {
+ "lufs": -14,
+ "tp": -1
+ },
+ "export": {
+ "preset": "youtube",
+ "normalize": true
+ },
+ "check": {
+ "platform": "youtube"
+ }
+}
diff --git a/tests/_fixtures.py b/tests/_fixtures.py
index 36bf7df..7c574e6 100644
--- a/tests/_fixtures.py
+++ b/tests/_fixtures.py
@@ -231,6 +231,20 @@ class MediaFixtures(unittest.TestCase):
"-t", "6", "-c:v", "libx264", "-preset", "veryfast", "-crf", "24",
"-pix_fmt", "yuv420p", "-c:a", "aac", small)
return small
+ def _gappy(self):
+ """A 12 s clip whose audio is speech-and-pause: tone for 2 s, silence for 2 s, six times
+ over. The structure detectors (silence.py, metadata.py --auto-chapters) have something
+ real to find, and the pauses sit at known seconds so an assertion can name them."""
+ gappy = OUT / "gappy.mp4"
+ if not gappy.exists():
+ gate = "gt(mod(t\\,4)\\,2)"
+ sh("ffmpeg", "-y", "-hide_banner", "-loglevel", "error",
+ "-f", "lavfi", "-i", f"aevalsrc='0.5*sin(2*PI*440*t)*{gate}':s=48000",
+ "-f", "lavfi", "-i", "testsrc2=size=160x90:rate=30",
+ "-t", "12", "-c:v", "libx264", "-preset", "ultrafast", "-pix_fmt", "yuv420p",
+ "-c:a", "aac", gappy)
+ return gappy
+
@staticmethod
def _srt_cues(path):
blocks = [b for b in Path(path).read_text(encoding="utf-8").strip().split("\n\n") if b.strip()]
diff --git a/tests/fixtures/mcp_tools.json b/tests/fixtures/mcp_tools.json
index ec577d6..13b13a4 100644
--- a/tests/fixtures/mcp_tools.json
+++ b/tests/fixtures/mcp_tools.json
@@ -147,6 +147,7 @@
"codec",
"color",
"crf",
+ "default_track",
"dry_run",
"emoji",
"emoji_assets",
@@ -185,7 +186,9 @@
"srt",
"text",
"timeout",
+ "track_title",
"transcribe",
+ "wrap",
"write_ass",
"write_srt"
],
@@ -520,6 +523,7 @@
"timeout",
"title",
"top",
+ "wrap",
"write_ass"
],
"required": []
@@ -691,20 +695,29 @@
"album",
"argv",
"artist",
+ "auto_chapters",
"chapters",
+ "chapters_out",
"clear_chapters",
"comment",
"date",
+ "description_out",
+ "detect_from",
"dry_run",
"fast",
"genre",
"input",
"json",
"json_brief",
+ "max_chapters",
+ "min_chapter",
"output",
"overwrite",
"plan",
"progress",
+ "scene_threshold",
+ "silence_min",
+ "silence_threshold",
"timeout",
"title"
],
@@ -899,6 +912,7 @@
"dry_run",
"fast",
"fit",
+ "image",
"init",
"json",
"json_brief",
@@ -1208,6 +1222,7 @@
"argv",
"audio_stream",
"background",
+ "brand",
"codec",
"color",
"crf",
@@ -1215,18 +1230,27 @@
"fast",
"fps",
"height",
+ "image",
+ "image_fit",
"input",
"json",
"json_brief",
+ "opacity",
"output",
"overwrite",
"plan",
+ "platform",
+ "position",
"preset",
"progress",
"quality",
"split_channels",
+ "srt",
"style",
+ "text",
"timeout",
+ "title",
+ "vis_height",
"waveform_mode",
"width"
],
diff --git a/tests/test_analysis.py b/tests/test_analysis.py
index a828e70..a111c0e 100644
--- a/tests/test_analysis.py
+++ b/tests/test_analysis.py
@@ -531,5 +531,98 @@ class AnalysisTests(MediaFixtures):
self.assertGreater(data["confidence"], 0.3)
+class ProposeChaptersTests(unittest.TestCase):
+ """1.16: the pure half of metadata.py --auto-chapters. No media, no subprocess."""
+
+ def setUp(self):
+ from _common import description_block, propose_chapters, fmt_chapter_time
+ self.propose = propose_chapters
+ self.block = description_block
+ self.fmt = fmt_chapter_time
+
+ def test_propose_chapters_always_starts_at_zero(self):
+ got = self.propose(600, [(190.1, 192.4)], [], min_chapter=60)
+ self.assertEqual(got[0]["at"], 0.0)
+ self.assertEqual(got[0]["evidence"]["kind"], "start")
+ self.assertEqual(self.propose(600, [], [], min_chapter=60),
+ [{"at": 0.0, "evidence": {"kind": "start"}, "title": "Chapter 1"}])
+
+ def test_propose_chapters_merges_silence_and_scene_evidence(self):
+ got = self.propose(600, [(190.1, 192.4)], [192.6], min_chapter=60)
+ self.assertEqual(len(got), 2)
+ ev = got[1]["evidence"]
+ self.assertEqual(ev["kind"], "silence+scene")
+ self.assertEqual(ev["silence"], [190.1, 192.4])
+ self.assertEqual(ev["silence_length"], 2.3)
+ self.assertEqual(ev["scene_at"], 192.6)
+ self.assertEqual(got[1]["at"], 192.4, "a chapter starts where speech resumes")
+
+ def test_propose_chapters_respects_min_chapter(self):
+ silences = [(50, 51), (70, 71), (200, 202), (210, 211)]
+ got = self.propose(600, silences, [], min_chapter=60)
+ ats = [c["at"] for c in got]
+ for a, b in zip(ats, ats[1:]):
+ self.assertGreaterEqual(b - a, 60.0, ats)
+ # and nothing within min_chapter of the end
+ self.assertTrue(all(a < 600 - 60 for a in ats), ats)
+
+ def test_propose_chapters_never_invents_a_title(self):
+ got = self.propose(1200, [(100, 102), (300, 303), (700, 702)], [500.0], min_chapter=60)
+ self.assertGreater(len(got), 2)
+ for n, c in enumerate(got, start=1):
+ self.assertEqual(c["title"], "Chapter %d" % n)
+ self.assertRegex(c["title"], r"^Chapter \d+$")
+
+ def test_max_chapters_drops_weakest_evidence_first(self):
+ got = self.propose(1200, [(100, 100.5), (300, 305)], [700.0],
+ min_chapter=60, max_chapters=3)
+ self.assertEqual(len(got), 3)
+ kinds = [c["evidence"]["kind"] for c in got]
+ self.assertEqual(kinds[0], "start")
+ self.assertIn("silence", kinds)
+ self.assertNotIn("scene", kinds, "a bare scene cut outranked a measured pause")
+ self.assertEqual([c["at"] for c in got], sorted(c["at"] for c in got))
+
+ def test_description_block_format(self):
+ self.assertEqual(self.fmt(0), "00:00")
+ self.assertEqual(self.fmt(192.9), "03:12", "the timestamp rounds DOWN to the second")
+ self.assertEqual(self.fmt(3723.4), "1:02:03")
+ chapters = [{"at": 0.0, "title": "Chapter 1"}, {"at": 192.4, "title": "Chapter 2"}]
+ self.assertEqual(self.block(chapters), "00:00 Chapter 1\n03:12 Chapter 2")
+
+
+class AutoChaptersTests(MediaFixtures):
+ """1.16 end to end, on the fixture that has real silences."""
+
+ def test_auto_chapters_writes_markers_and_description(self):
+ gappy = self._gappy()
+ out = OUT / "auto_chapters.mp4"
+ chapters_txt = OUT / "auto_chapters.txt"
+ desc = OUT / "auto_chapters_desc.txt"
+ res = json.loads(script("metadata.py", gappy, "--auto-chapters", "--min-chapter", "1",
+ "--chapters-out", chapters_txt, "--description-out", desc,
+ "--json", "-o", out).stdout)
+ auto = res["auto_chapters"]
+ self.assertEqual(auto["titles"], "placeholder")
+ self.assertTrue(res["streams_copied"], "nothing may be re-encoded")
+ written = sh("ffprobe", "-v", "error", "-show_chapters", "-of", "json", out).stdout
+ self.assertEqual(len(json.loads(written)["chapters"]), auto["kept"])
+ for n, c in enumerate(auto["chapters"], start=1):
+ self.assertEqual(c["title"], "Chapter %d" % n)
+ self.assertTrue(desc.read_text(encoding="utf-8").startswith("00:00 "))
+ # the chapters file round-trips through this tool's own --chapters reader
+ again = OUT / "auto_chapters_again.mp4"
+ script("metadata.py", gappy, "--chapters", chapters_txt, "-o", again)
+ self.assertEqual(len(json.loads(sh("ffprobe", "-v", "error", "-show_chapters",
+ "-of", "json", again).stdout)["chapters"]),
+ auto["kept"])
+
+ def test_auto_chapters_excludes_the_manual_forms(self):
+ script("metadata.py", self._gappy(), "--auto-chapters", "--chapters", "/nope.txt",
+ "-o", OUT / "x_auto.mp4", expect_fail=True)
+ script("metadata.py", self._gappy(), "--auto-chapters", "--clear-chapters",
+ "-o", OUT / "x_auto2.mp4", expect_fail=True)
+
+
if __name__ == "__main__":
unittest.main(verbosity=2)
diff --git a/tests/test_audio.py b/tests/test_audio.py
index 3479220..1afaefc 100644
--- a/tests/test_audio.py
+++ b/tests/test_audio.py
@@ -5,13 +5,14 @@
python3 tests/test_all.py # every group
"""
import json
+import shlex
import sys
import unittest
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent))
-from _fixtures import MediaFixtures, OUT, script, sh # noqa: E402
+from _fixtures import MediaFixtures, OUT, SCRIPTS, script, sh # noqa: E402
from _common import probe # noqa: E402
@@ -399,5 +400,192 @@ class AudioTests(MediaFixtures):
self.assertLessEqual(self._peak_rms(mp4)[0], -1.0 + 0.3)
+class AudiogramTests(MediaFixtures):
+ """1.16: waveform.py over a still plate. The command line without any of the new flags must
+ stay byte-identical to 1.15, which is the whole reason this is not a new tool."""
+
+ @staticmethod
+ def _plan(*args):
+ """The ffmpeg command a run would build, from its own --dry-run plan."""
+ doc = json.loads(script("waveform.py", *args, "--dry-run", "--json").stdout)
+ cmd = doc["commands"][0]
+ return shlex.split(cmd) if isinstance(cmd, str) else list(cmd)
+
+ def _plate(self, w=1080, h=1920):
+ png = OUT / f"ag_plate_{w}x{h}.png"
+ if not png.exists():
+ mp4 = OUT / f"ag_plate_{w}x{h}.mp4"
+ script("background.py", "--width", str(w), "--height", str(h),
+ "--gradient", "#1a2b3c:#cc3333", "--duration", "1", "-o", mp4)
+ sh("ffmpeg", "-y", "-hide_banner", "-loglevel", "error", "-i", mp4, "-frames:v", "1", png)
+ return png
+
+ # The exact command line 1.15.1 built for `waveform.py IN --width 640 --height 360 -o OUT`,
+ # taken from a checkout of origin/main and pinned here. Only the ffmpeg binary, the input and
+ # the output are substituted; every other argument, and their order, is the pin.
+ WAVEFORM_1_15_1 = [
+ "{ffmpeg}", "-hide_banner", "-loglevel", "error", "-nostdin", "-y",
+ "-i", "{input}",
+ "-filter_complex",
+ "color=c=black:s=640x360:r=25[bg];[0:a:0]showwaves=s=640x360:mode=line:rate=25:"
+ "split_channels=0:colors=lime[vis];[bg][vis]overlay=format=auto",
+ "-map", "0:a:0",
+ "-c:v", "libx264", "-preset", "medium", "-crf", "18", "-pix_fmt", "yuv420p",
+ "-movflags", "+faststart",
+ "{bt709}", # bt709_tag_args(): three tag pairs up to FFmpeg 7.0, one -x264-params from 7.1
+ "-c:a", "aac", "-b:a", "192k",
+ "-t", "12.000", "-shortest", "{output}",
+ ]
+
+ def test_waveform_without_image_is_byte_identical_to_1_15(self):
+ """The whole argv, not a handful of substrings: a run with none of the audiogram flags
+ must build the command line 1.15.1 built, argument for argument and in the same order.
+ This is the assertion that makes "the audiogram is four flags on waveform.py, not a second
+ tool" checkable instead of asserted."""
+ out = OUT / "ag_identical.mp4"
+ plan = self._plan(self.src, "--width", "640", "--height", "360", "-o", out)
+ # 1.15.1 called bt709_tag_args() too, so the tag spelling follows the ffmpeg on this
+ # machine (macOS CI runs 7.x, where the tags travel as -x264-params); the pin is the
+ # argv around it.
+ sys.path.insert(0, str(SCRIPTS))
+ from _common import bt709_tag_args
+ expected = []
+ for part in self.WAVEFORM_1_15_1:
+ if part == "{bt709}":
+ expected.extend(bt709_tag_args())
+ else:
+ expected.append(part.format(ffmpeg=plan[0], input=str(self.src), output=str(out)))
+ self.assertEqual(plan, expected)
+
+ def test_audiogram_graph_has_one_overlay_per_layer(self):
+ plate = self._plate(640, 360)
+ plan = self._plan(self.src, "--image", plate, "--width", "640", "--height", "360",
+ "-o", OUT / "ag_graph.mp4")
+ joined = " ".join(plan)
+ self.assertEqual(joined.count("overlay="), 1, "one overlay: the plate and the visualisation")
+ self.assertIn("-loop", plan)
+ self.assertIn("[1:v]scale=640:360:force_original_aspect_ratio=increase,crop=640:360", joined)
+ self.assertIn("format=rgba[plate]", joined)
+ self.assertIn("[v]", plan)
+
+ def test_audiogram_position_maps_to_y(self):
+ plate = self._plate(640, 360)
+ base = [self.src, "--image", plate, "--width", "640", "--height", "360",
+ "--vis-height", "0.5"]
+ for position, expect_y in (("top", "y=0"), ("centre", "y=90"),
+ ("bottom", "y=180"), ("strip", "y=180")):
+ with self.subTest(position=position):
+ joined = " ".join(self._plan(*base, "--position", position,
+ "-o", OUT / f"ag_pos_{position}.mp4"))
+ self.assertIn(expect_y, joined)
+ self.assertIn("showwaves=s=640x180:", joined, "the band is --vis-height of the frame")
+
+ def test_audiogram_platform_frame_comes_from_platforms_table(self):
+ sys.path.insert(0, str(SCRIPTS))
+ import importlib
+ frame = importlib.import_module("_platforms").PLATFORMS["reels"]["frame"]
+ joined = " ".join(self._plan(self.src, "--image", self._plate(), "--platform", "reels",
+ "-o", OUT / "ag_reels.mp4"))
+ self.assertIn(f"crop={frame['w']}:{frame['h']}", joined)
+ # podcast has no frame: refused, not guessed at
+ script("waveform.py", self.src, "--platform", "podcast", "-o", OUT / "ag_pod.mp4",
+ expect_fail=True)
+
+ def test_audiogram_refuses_a_url_image(self):
+ proc = script("waveform.py", self.src, "--image", "https://example.com/cover.png",
+ "-o", OUT / "ag_url.mp4", expect_fail=True)
+ self.assertIn("no network access", proc.stderr)
+ script("waveform.py", self.src, "--image", "/nonexistent/cover.png",
+ "-o", OUT / "ag_missing.mp4", expect_fail=True)
+ # an image and a colour plate are two answers to the same question
+ script("waveform.py", self.src, "--image", self._plate(), "--background", "white",
+ "-o", OUT / "ag_both.mp4", expect_fail=True)
+
+ def test_audiogram_frame_rate_is_the_one_the_run_announced(self):
+ """A looped still defaults to 25 fps and overlay takes its rate from the first input, so
+ the plate silently decided the output's frame rate: `--platform tiktok` printed 30 fps and
+ wrote a 25 fps file. The rate is now part of what the run verifies."""
+ plate = self._plate()
+ out = OUT / "ag_fps.mp4"
+ res = json.loads(script("waveform.py", self.src, "--image", plate, "--platform", "tiktok",
+ "--json", "-o", out).stdout)
+ rate = sh("ffprobe", "-v", "error", "-select_streams", "v:0", "-show_entries",
+ "stream=r_frame_rate", "-of", "csv=p=0", out).stdout.strip()
+ self.assertEqual(rate, "30/1", "the plate decided the frame rate instead of --platform")
+ self.assertTrue(res["audiogram"]["verified"])
+ self.assertIn("-framerate", self._plan(self.src, "--image", plate, "--platform", "tiktok",
+ "-o", OUT / "ag_fps2.mp4"))
+ # the colour-plate path never had the bug and must keep its own rate
+ rate2 = sh("ffprobe", "-v", "error", "-select_streams", "v:0", "-show_entries",
+ "stream=r_frame_rate", "-of", "csv=p=0",
+ script("waveform.py", self.src, "--platform", "tiktok", "--fast",
+ "-o", OUT / "ag_fps_color.mp4") and OUT / "ag_fps_color.mp4").stdout.strip()
+ self.assertEqual(rate2, "30/1")
+
+ def test_audiogram_verified_is_false_under_dry_run(self):
+ """Nothing was rendered, so there is nothing to have verified -- and the common top-level
+ `verified` says so for the same run. The two keys must not disagree."""
+ doc = json.loads(script("waveform.py", self.src, "--image", self._plate(640, 360),
+ "--width", "640", "--height", "360", "--dry-run", "--json",
+ "-o", OUT / "ag_dry.mp4").stdout)
+ self.assertFalse(doc["verified"])
+ self.assertFalse(doc["audiogram"]["verified"])
+
+ def test_audiogram_refuses_an_image_ffmpeg_cannot_decode(self):
+ """Spec 2.6: a file that is not a decodable image is an input refusal naming it, before
+ ffmpeg is ever started -- not a raw ffmpeg failure."""
+ notpic = OUT / "ag_not_a_picture.m4a"
+ if not notpic.exists():
+ sh("ffmpeg", "-y", "-hide_banner", "-loglevel", "error", "-f", "lavfi",
+ "-i", "sine=d=1", notpic)
+ proc = script("waveform.py", self.src, "--image", notpic, "-o", OUT / "ag_nope.mp4",
+ "--json", expect_fail=True)
+ doc = json.loads(proc.stdout)
+ self.assertEqual(doc["error"]["kind"], "input")
+ self.assertIn(str(notpic), doc["error"]["message"])
+ self.assertFalse((OUT / "ag_nope.mp4").exists())
+
+ def test_audiogram_renders_with_image_and_captions(self):
+ plate = self._plate()
+ cues = OUT / "ag_cues.txt"
+ cues.write_text("0.0 1.5 Episode twelve\n1.5 3.0 The long one\n", encoding="utf-8")
+ out = OUT / "audiogram.mp4"
+ res = json.loads(script("waveform.py", self.src, "--image", plate, "--platform", "reels",
+ "--title", "Episode 12", "--text", cues, "--json", "-o", out).stdout)
+ ag = res["audiogram"]
+ self.assertEqual(ag["background"], "image")
+ self.assertTrue(ag["verified"])
+ self.assertEqual(ag["stages"], ["waveform", "title", "captions"])
+ m, src_m = probe(str(out)), probe(str(self.src))
+ self.assertEqual((m["video"]["width"], m["video"]["height"]), (1080, 1920))
+ self.assertLessEqual(abs(m["duration"] - src_m["duration"]), 0.15)
+ # the plate is really there: a frame of it is not flat black
+ frame = OUT / "audiogram_look.png"
+ script("look.py", out, "--at", "1", "-o", frame)
+ self.assertTrue(frame.exists())
+ # a flat plate compresses to almost nothing; a gradient with a waveform over it does not
+ self.assertGreater(frame.stat().st_size, 1000, "the plate is flat: the image never reached the picture")
+
+ def test_render_template_audiogram_runs_the_whole_chain(self):
+ cues = OUT / "ag_tpl_cues.txt"
+ cues.write_text("0.0 2.0 Episode twelve\n", encoding="utf-8")
+ out = OUT / "audiogram_tpl.mp4"
+ res = json.loads(script("render.py", self.src, "--template", "audiogram",
+ "--image", self._plate(), "--cues", cues,
+ "--json", "-o", out).stdout)
+ self.assertIn("audiogram", res["stages"])
+ self.assertEqual(res["stages"][1], "audiogram", "the picture is made before anything uses it")
+ self.assertIn("captions", res["stages"])
+ self.assertIn("check", res["stages"])
+ self.assertTrue(out.exists())
+
+ def test_audiogram_is_not_part_of_template_all(self):
+ sys.path.insert(0, str(SCRIPTS))
+ import importlib
+ render = importlib.import_module("render")
+ self.assertIn("audiogram", render.template_names())
+ self.assertNotIn("audiogram", render.expand_templates("all"))
+
+
if __name__ == "__main__":
unittest.main(verbosity=2)
diff --git a/tests/test_delivery.py b/tests/test_delivery.py
index 7aa07f3..bbb4523 100644
--- a/tests/test_delivery.py
+++ b/tests/test_delivery.py
@@ -168,15 +168,27 @@ class DeliveryTests(MediaFixtures):
the export preset and check.py agreeing is exactly the thing a template promises and the
thing that used to be assembled by hand differently every time."""
names = sorted(p.stem for p in (ROOT / "templates").glob("*.json"))
- self.assertEqual(names, ["facebook", "linkedin", "podcast", "reels", "shorts", "tiktok",
- "x", "youtube", "youtube-shorts"], "every shipped template is exercised here")
+ self.assertEqual(names, ["audiogram", "facebook", "linkedin", "podcast", "reels", "shorts",
+ "tiktok", "x", "youtube", "youtube-shorts"],
+ "every shipped template is exercised here")
+ plate = OUT / "tpl_audiogram_plate.png"
+ if not plate.exists():
+ plate_clip = OUT / "tpl_audiogram_plate.mp4"
+ script("background.py", "--width", "640", "--height", "360",
+ "--gradient", "#101014:#cc3333", "--duration", "1", "-o", plate_clip)
+ sh("ffmpeg", "-y", "-hide_banner", "-loglevel", "error", "-i", plate_clip,
+ "-frames:v", "1", plate)
for name in names:
with self.subTest(template=name):
- src = self.mic if name == "podcast" else self.src
+ src = self.mic if name in ("podcast", "audiogram") else self.src
argv = [str(src), "--template", name, "--fast", "--json",
"-o", str(OUT / ("tpl_%s.%s" % (name, "m4a" if name == "podcast" else "mp4")))]
if name != "podcast":
argv += ["--cues", str(self.cues)]
+ if name == "audiogram":
+ # the one template that needs a picture given to it: the skill fetches nothing
+ # and invents no cover art, so a run without --image is a refusal by design
+ argv += ["--image", str(plate)]
doc = json.loads(script("render.py", *argv).stdout)
self.assertEqual(doc["status"], "completed")
self.assertTrue(os.path.exists(doc["output"]), doc["output"])
diff --git a/tests/test_picture.py b/tests/test_picture.py
index 84bc825..4934bd0 100644
--- a/tests/test_picture.py
+++ b/tests/test_picture.py
@@ -291,6 +291,32 @@ class PictureTests(MediaFixtures):
f"line wider than the safe area: {line!r}")
self.assertEqual(" ".join(l for _, lines in blocks for l in lines), text, "no word is lost or cut")
+ def test_phrase_wrap_burns_and_reports(self):
+ """1.16 end to end: the dl1 and dl4 cues are burnt in, the ASS the run writes carries the
+ phrase breaks, and the result document says which wrap produced them."""
+ import caption # noqa: E402
+ cues = OUT / "wrap_phrase.txt"
+ cues.write_text("0:00-0:02 A third line the tool times for me\n"
+ "0:02-0:04 Una tercera l\u00ednea con tiempos autom\u00e1ticos\n", encoding="utf-8")
+ out = OUT / "wrap_phrase.mp4"
+ ass = OUT / "wrap_phrase.ass"
+ res = json.loads(script("caption.py", self._small(), "--text", cues, "--size", "32",
+ "--max-lines", "2", "--animate", "fade", "--write-ass", ass,
+ "--json", "--fast", "-o", out).stdout)
+ self.assertEqual(res["caption"]["wrap"], "phrase")
+ self.assertIn("phrase_breaks", res["caption"])
+ self.assertTrue(out.exists())
+ body = ass.read_text(encoding="utf-8")
+ self.assertIn("A third line\\Nthe tool times for me", body)
+ self.assertIn("Una tercera l\u00ednea\\Ncon tiempos autom\u00e1ticos", body)
+ # and --wrap measured still reproduces 1.15's split, byte for byte in the ASS
+ ass2 = OUT / "wrap_measured.ass"
+ script("caption.py", self._small(), "--text", cues, "--size", "32", "--max-lines", "2",
+ "--wrap", "measured", "--animate", "fade", "--write-ass", ass2, "--fast", "-o", OUT / "wrap_measured.mp4")
+ self.assertIn("A third line the\\Ntool times for me", ass2.read_text(encoding="utf-8"))
+ self.assertEqual(caption.wrap_text("A third line the tool times for me", 12.96),
+ ["A third line", "the tool times for me"])
+
def test_caption_wraps_cjk_between_characters(self):
"""Chinese has no spaces: the line breaks between any two characters, and every character
counts as a full em (Latin averages just over half)."""
@@ -736,6 +762,141 @@ class PictureTests(MediaFixtures):
self.assertEqual(m["video"]["codec"], "h264", "video must stay copied through both chained calls")
self.assertEqual(m["audio"]["codec"], "aac", "audio must stay copied through both chained calls")
+ def test_srt_lang_suffix_parsing(self):
+ """`FILE:lang` splits on the last colon, and only when the suffix is a language code and
+ the whole token is not itself a file on disk -- so a Windows path and a file genuinely
+ named `a:b.srt` survive."""
+ import caption # noqa: E402
+ self.assertEqual(caption.split_srt_lang("en.srt:en"), ("en.srt", "en"))
+ self.assertEqual(caption.split_srt_lang("subs/file.srt:pt-BR"), ("subs/file.srt", "pt-BR"))
+ self.assertEqual(caption.split_srt_lang("plain.srt"), ("plain.srt", None))
+ # A Windows drive path is handled by the parser alone, with no file on disk: the drive
+ # letter is a one-character head that is not a language tag, in either slash style.
+ self.assertEqual(caption.split_srt_lang("C:\\subs\\en.srt"), ("C:\\subs\\en.srt", None))
+ self.assertEqual(caption.split_srt_lang("C:/subs/en.srt"), ("C:/subs/en.srt", None))
+ self.assertEqual(caption.split_srt_lang("D:\\media\\ja.srt"), ("D:\\media\\ja.srt", None))
+ # "the whole token is a file on disk, so do not split it" -- exercised with a colon-free
+ # name, which every OS can create.
+ plain = OUT / "suffix_plain.srt"
+ plain.write_text("1\n00:00:00,000 --> 00:00:01,000\nx\n", encoding="utf-8")
+ self.assertEqual(caption.split_srt_lang(str(plain)), (str(plain), None))
+ if platform.system() != "Windows":
+ # ... and, where the filesystem allows it, with a name that really contains a colon
+ odd = OUT / "a:b.srt"
+ odd.write_text("1\n00:00:00,000 --> 00:00:01,000\nx\n", encoding="utf-8")
+ self.assertEqual(caption.split_srt_lang(str(odd)), (str(odd), None))
+ # MPEG-4 needs the ISO-639-2 spelling (verified empirically: ffmpeg silently writes NO
+ # language tag for a two-letter code in .mp4); Matroska stores what it is given.
+ self.assertEqual(caption.container_language("ja", "x.mp4"), "jpn")
+ self.assertEqual(caption.container_language("ja", "x.mkv"), "ja")
+
+ def test_duplicate_language_and_bad_code_are_refused(self):
+ srt = OUT / "mux_dup.srt"
+ srt.write_text("1\n00:00:00,000 --> 00:00:02,000\nHello\n", encoding="utf-8")
+ script("caption.py", self.src, "--mode", "mux", "--srt", f"{srt}:en", "--srt", f"{srt}:en",
+ "-o", OUT / "dup.mkv", expect_fail=True)
+ script("caption.py", self.src, "--mode", "mux", "--srt", f"{srt}:en",
+ "--default-track", "ja", "-o", OUT / "dup2.mkv", expect_fail=True)
+ # a suffix meant as a language code but shaped wrong is a language error naming the
+ # token, not "SRT file not found: en.srt:zzzz"
+ proc = script("caption.py", self.src, "--mode", "mux", "--srt", f"{srt}:zzzzzzzzzzz",
+ "-o", OUT / "dup3.mkv", "--json", expect_fail=True)
+ doc = json.loads(proc.stdout)
+ self.assertEqual(doc["error"]["kind"], "input")
+ self.assertIn("zzzzzzzzzzz", doc["error"]["message"])
+ self.assertIn("not a language code", doc["error"]["message"])
+ # a genuinely missing file still says so
+ missing = script("caption.py", self.src, "--mode", "mux",
+ "--srt", str(OUT / "no_such_file.srt") + ":en",
+ "-o", OUT / "dup4.mkv", expect_fail=True)
+ self.assertIn("not found", missing.stderr)
+
+ def test_burn_with_two_srts_refused(self):
+ srt = OUT / "mux_burn2.srt"
+ srt.write_text("1\n00:00:00,000 --> 00:00:02,000\nHello\n", encoding="utf-8")
+ script("caption.py", self.src, "--srt", f"{srt}:en", "--srt", f"{srt}:ja",
+ "-o", OUT / "burn2.mp4", expect_fail=True)
+
+ def test_mux_three_languages_into_mkv(self):
+ """Three tracks in one call: nothing re-encoded, every stream tagged, and check.py's new
+ informational `subtitles` row lists all three."""
+ files = {}
+ for lang, text in (("en", "Hello"), ("ja", "\u3053\u3093\u306b\u3061\u306f"), ("es", "Hola")):
+ f = OUT / f"mux3_{lang}.srt"
+ f.write_text(f"1\n00:00:00,000 --> 00:00:02,000\n{text}\n", encoding="utf-8")
+ files[lang] = f
+ out = OUT / "cap_mux3.mkv"
+ res = json.loads(script("caption.py", self.src, "--mode", "mux",
+ "--srt", f"{files['en']}:en", "--srt", f"{files['ja']}:ja",
+ "--srt", f"{files['es']}:es", "--default-track", "en",
+ "--json", "-o", out).stdout)
+ self.assertEqual(res["subtitle_tracks"], 3)
+ self.assertEqual([t["language"] for t in res["tracks"]], ["en", "ja", "es"])
+ self.assertEqual([t["default"] for t in res["tracks"]], [True, False, False])
+ disp = sh("ffprobe", "-v", "error", "-select_streams", "s", "-show_entries",
+ "stream_disposition=default", "-of", "csv=p=0", out).stdout.split()
+ self.assertEqual(disp, ["1", "0", "0"], "the file disagrees with tracks[].default")
+ self.assertEqual(res["tracks"][1]["title"], "\u65e5\u672c\u8a9e")
+ src_m, m = probe(str(self.src)), probe(str(out))
+ self.assertEqual(m["subtitle_streams"], 3)
+ # ffprobe reports Matroska's codes verbatim (empirically: `en`, not `eng`)
+ langs = sh("ffprobe", "-v", "error", "-select_streams", "s", "-show_entries",
+ "stream_tags=language", "-of", "csv=p=0", out).stdout.split()
+ self.assertEqual(langs, ["en", "ja", "es"])
+ self.assertEqual(m["video"]["codec"], src_m["video"]["codec"], "video was re-encoded")
+ self.assertEqual(m["audio"]["codec"], src_m["audio"]["codec"], "audio was re-encoded")
+ chk = json.loads(script("check.py", out, "--platform", "youtube", "--no-loudness",
+ "--json").stdout)
+ subs_row = [r for r in chk["checks"] if r["check"] == "subtitles"]
+ self.assertEqual(len(subs_row), 1)
+ self.assertEqual(subs_row[0]["status"], "PASS")
+ for code in ("en", "ja", "es"):
+ self.assertIn(code, subs_row[0]["value"])
+
+ def test_mux_without_default_track_leaves_every_matroska_track_off(self):
+ """Given two or more new subtitle streams and no --default-track, ffmpeg flags the first
+ one `default` by itself -- the opposite of what the flag promises, and `tracks[].default`
+ then described a file that did not exist. Every disposition is stated explicitly now."""
+ files = []
+ for lang in ("en", "ja"):
+ f = OUT / f"mux_nodef_{lang}.srt"
+ f.write_text("1\n00:00:00,000 --> 00:00:02,000\nx\n", encoding="utf-8")
+ files.append(f"{f}:{lang}")
+ out = OUT / "cap_mux_nodef.mkv"
+ res = json.loads(script("caption.py", self.src, "--mode", "mux",
+ *[a for f in files for a in ("--srt", f)],
+ "--json", "-o", out).stdout)
+ disp = sh("ffprobe", "-v", "error", "-select_streams", "s", "-show_entries",
+ "stream_disposition=default", "-of", "csv=p=0", out).stdout.split()
+ self.assertEqual(disp, ["0", "0"], "a track was marked default that nobody asked for")
+ self.assertEqual([t["default"] for t in res["tracks"]], [False, False])
+
+ def test_mux_into_mp4_converts_to_iso639_2_and_warns_about_players(self):
+ """Empirically, an .mp4 keeps three mov_text tracks but drops a two-letter language code
+ outright -- so the code is converted and the caller is told the container is the wrong
+ one for a switchable deliverable."""
+ files = []
+ for lang in ("en", "ja", "es"):
+ f = OUT / f"mux3mp4_{lang}.srt"
+ f.write_text("1\n00:00:00,000 --> 00:00:02,000\nx\n", encoding="utf-8")
+ files.append(f"{f}:{lang}")
+ out = OUT / "cap_mux3.mp4"
+ res = json.loads(script("caption.py", self.src, "--mode", "mux", *[a for f in files for a in ("--srt", f)],
+ "--json", "-o", out).stdout)
+ self.assertEqual([t["language"] for t in res["tracks"]], ["eng", "jpn", "spa"])
+ langs = sh("ffprobe", "-v", "error", "-select_streams", "s", "-show_entries",
+ "stream_tags=language", "-of", "csv=p=0", out).stdout.split()
+ self.assertEqual(langs, ["eng", "jpn", "spa"])
+ self.assertTrue(any(".mkv" in n for n in res.get("notes") or []), res.get("notes"))
+ # MPEG-4 stores no per-track title ffprobe reads back, so none is claimed
+ self.assertEqual([t["title"] for t in res["tracks"]], [None, None, None])
+ self.assertEqual(sh("ffprobe", "-v", "error", "-select_streams", "s", "-show_entries",
+ "stream_tags=title", "-of", "csv=p=0", out).stdout.split(), [])
+ # ... and it always enables its first subtitle track, which tracks[] must not deny
+ disp = sh("ffprobe", "-v", "error", "-select_streams", "s", "-show_entries",
+ "stream_disposition=default", "-of", "csv=p=0", out).stdout.split()
+ self.assertEqual([("1" if t["default"] else "0") for t in res["tracks"]], disp)
+
def test_caption_mux_picks_the_subtitle_codec_from_the_container(self):
srt = OUT / "mux_container_cues.srt"
script("caption.py", "--text", self.cues, "--write-srt", srt)
@@ -2126,5 +2287,211 @@ class WrapReadabilityTests(unittest.TestCase):
len(C.wrap_text(text, max_em, balance=False)))
+class PhraseWrapTests(unittest.TestCase):
+ """1.16: the four phrase rules (R1 never inside a word, R2 no weak line, R3 ja/zh preferred
+ break points, R4 no function word at the end of a line), locked against the eval-16 cues."""
+
+ # The em width a caption line has at a real destination's caption size, computed from the
+ # platform table rather than pinned as a magic float (the size, the frame and the safe-area
+ # fraction can all move; the test should move with them).
+ @staticmethod
+ def _max_em(platform_name):
+ sys.path.insert(0, str(SCRIPTS))
+ import importlib
+ _platforms = importlib.import_module("_platforms")
+ caption = importlib.import_module("caption")
+ frame = _platforms.PLATFORMS[platform_name]["frame"]
+ cap = _platforms.caption_defaults(platform_name)
+ size_px = cap["size"] * frame["h"] / 288.0
+ return (frame["w"] * caption.SAFE_WIDTH_FRACTION) / size_px
+
+ def setUp(self):
+ sys.path.insert(0, str(SCRIPTS))
+ import importlib
+ self.caption = importlib.import_module("caption")
+ self.W = self._max_em("linkedin") # 12.96 em: wide enough for a two-line cue
+ self.NARROW = self._max_em("tiktok") # 6.075 em: the vertical caption width
+
+ # -------------------------------------------------------------- R1: never inside a word
+ def test_wrap_never_splits_inside_a_word(self):
+ C = self.caption
+ corpus = [
+ "A third line the tool times for me",
+ "Segunda linea de subtitulos con acentos",
+ "one two three four five six seven eight nine ten",
+ "\u3053\u3093\u306b\u3061\u306f\u3001\u4e16\u754c 2 \u884c\u76ee\u306e\u5b57\u5e55\u3067\u3059",
+ "\u0e2a\u0e27\u0e31\u0e2a\u0e14\u0e35\u0e0a\u0e32\u0e27\u0e42\u0e25\u0e01 \u0e40\u0e2a\u0e35\u0e22\u0e07\u0e19\u0e49\u0e33\u0e44\u0e2b\u0e25",
+ ]
+ for text in corpus:
+ for max_em in (4.0, 6.075, 9.0, 12.96, 20.0):
+ with self.subTest(text=text[:12], max_em=max_em):
+ lines = C.wrap_text(text, max_em)
+ self.assertEqual("".join(lines).replace(" ", ""), text.replace(" ", ""))
+ # every boundary between two spaced-script lines stood at a space or a hyphen
+ for a, b in zip(lines, lines[1:]):
+ if not a or not b:
+ continue
+ spaced = C.char_script(a[-1]) not in C.NO_SPACE_SCRIPTS \
+ and C.char_script(b[0]) not in C.NO_SPACE_SCRIPTS
+ if not spaced:
+ continue # a no-space script breaks between characters by design
+ if not C._break_spaced(a, b):
+ self.assertTrue(a.endswith(("-", "\u2010")),
+ "broke inside a word: %r | %r" % (a, b))
+
+ def test_wrap_breaks_a_hyphenated_word_only_after_the_hyphen(self):
+ C = self.caption
+ lines = C.wrap_text("an end-to-end example", 6.0)
+ self.assertEqual("".join(lines).replace(" ", ""), "anend-to-endexample")
+ for a, b in zip(lines, lines[1:]):
+ if a and b and not C._break_spaced(a, b):
+ self.assertTrue(a.endswith("-"), "broke inside a word: %r | %r" % (a, b))
+ # a non-breaking hyphen is never a break point
+ self.assertEqual(C._split_hyphens([("well\u2011known", False)]), [("well\u2011known", False)])
+ # ... and neither is a leading or trailing one
+ self.assertEqual(C._split_hyphens([("-5", False)]), [("-5", False)])
+
+ # -------------------------------------------------------------- R2: no weak line
+ def test_is_weak_line_names_the_lines_no_reader_should_get(self):
+ C = self.caption
+ for weak in ("2", "--", "\u3066", "\u30f3", " "):
+ self.assertTrue(C._is_weak_line(weak), repr(weak))
+ for fine in ("me", "\u4e16\u754c", "\u0e44\u0e2b\u0e25"):
+ self.assertFalse(C._is_weak_line(fine), repr(fine))
+
+ def test_dl3_cue_exact_split(self):
+ """dl3: no line that is a lone digit; the break is not between a kanji stem and its
+ okurigana (`\u6c7a\u307e` | `\u308b`); and no line OPENS with a particle -- a particle is
+ enclitic, so kinsoku keeps it with the word before it."""
+ C = self.caption
+ jp = "\u81ea\u52d5\u3067\u30bf\u30a4\u30df\u30f3\u30b0\u304c\u6c7a\u307e\u308b\u884c"
+ for max_em in (self.NARROW, self.W, 10.0, 14.0):
+ with self.subTest(max_em=max_em):
+ lines = C.wrap_text("2 \u884c\u76ee\u306e\u5b57\u5e55\u3067\u3059", max_em)
+ self.assertNotIn("2", lines, lines)
+ lines = C.wrap_text(jp, max_em)
+ for a, b in zip(lines, lines[1:]):
+ self.assertFalse(a.endswith("\u6c7a\u307e") and b.startswith("\u308b"),
+ "broke inside \u6c7a\u307e\u308b: %r" % (lines,))
+ self.assertNotIn(b[0], C.JA_PARTICLES,
+ "a line opens with a particle: %r" % (lines,))
+ # the break falls after \u304c, not before it
+ self.assertEqual(C.wrap_text(jp, 10.0),
+ ["\u81ea\u52d5\u3067\u30bf\u30a4\u30df\u30f3\u30b0\u304c", "\u6c7a\u307e\u308b\u884c"])
+ self.assertEqual(C.wrap_text(jp, self.W),
+ ["\u81ea\u52d5\u3067\u30bf\u30a4\u30df\u30f3\u30b0\u304c", "\u6c7a\u307e\u308b\u884c"])
+
+ def test_th1_cue_exact_split(self):
+ """th1: the trailing line is never the stranded `\u0e44\u0e2b\u0e25` alone."""
+ C = self.caption
+ text = "\u0e2a\u0e27\u0e31\u0e2a\u0e14\u0e35\u0e0a\u0e32\u0e27\u0e42\u0e25\u0e01 \u0e40\u0e2a\u0e35\u0e22\u0e07\u0e19\u0e49\u0e33\u0e44\u0e2b\u0e25"
+ for max_em in (self.NARROW, 8.0, self.W):
+ with self.subTest(max_em=max_em):
+ lines = C.wrap_text(text, max_em)
+ self.assertNotEqual(lines[-1].strip(), "\u0e44\u0e2b\u0e25", lines)
+ self.assertFalse(C._is_weak_line(lines[-1]), lines)
+
+ # -------------------------------------------------------------- R4: function words
+ def test_function_word_never_ends_a_line(self):
+ C = self.caption
+ cases = {
+ "en": "A third line the tool times for me",
+ "es": "Una tercera linea con tiempos automaticos",
+ "pt": "Uma terceira linha com tempos automaticos",
+ "fr": "La ligne trois avec temps automatiques",
+ "de": "Zeile drei zeigt die Zeiten automatisch",
+ "it": "Una terza riga con i tempi automatici",
+ }
+ for lang, text in cases.items():
+ with self.subTest(lang=lang):
+ lines = C.wrap_text(text, self.W, lang=lang)
+ for line in lines[:-1]:
+ last = C._bare_word(line.split(" ")[-1])
+ self.assertNotIn(last, C._function_words(lang),
+ "%s: line ends on a function word: %r" % (lang, lines))
+ # and the rule works by preferring the break BEFORE the word, not only by
+ # vetoing the one after it
+ self.assertNotEqual(lines, C.wrap_text(text, self.W, mode="measured"),
+ "%s: the greedy break did not move" % lang)
+
+ def test_dl4_cue_exact_split(self):
+ """dl4, both cues, at the width that reproduced the eval-16 splits."""
+ C = self.caption
+ self.assertEqual(C.wrap_text("Segunda l\u00ednea de subt\u00edtulos", self.W, lang="es"),
+ ["Segunda l\u00ednea", "de subt\u00edtulos"])
+ self.assertEqual(C.wrap_text("Una tercera l\u00ednea con tiempos autom\u00e1ticos", self.W, lang="es"),
+ ["Una tercera l\u00ednea", "con tiempos autom\u00e1ticos"])
+
+ def test_dl1_cue_exact_split(self):
+ """dl1. R4 scores both directions: `the` opens the phrase it governs, so the break BEFORE
+ it is the preferred one and the break after it the penalised one. Both halves fit, so the
+ cue comes out as one whole phrase per line. `--wrap measured` still gives 1.15's split."""
+ C = self.caption
+ text = "A third line the tool times for me"
+ for max_em in (self.W, 14.0, 16.0):
+ with self.subTest(max_em=max_em):
+ self.assertEqual(C.wrap_text(text, max_em, lang="en"),
+ ["A third line", "the tool times for me"])
+ self.assertEqual(C.wrap_text(text, self.W, mode="measured"),
+ ["A third line the", "tool times for me"])
+
+ # -------------------------------------------------------------- modes and invariants
+ def test_wrap_measured_is_byte_identical_to_1_15(self):
+ """`--wrap measured` reproduces the outputs the 1.15 tests pinned."""
+ C = self.caption
+ self.assertEqual(C.wrap_text("A third line the tool times for me", 14.0, mode="measured"),
+ ["A third line the", "tool times for me"])
+ self.assertEqual(C.wrap_text("A third line the tool times for me", 14.0,
+ balance=False, mode="measured"),
+ ["A third line the tool times", "for me"])
+ self.assertEqual(C.wrap_text("Segunda l\u00ednea de subt\u00edtulos", self.W, mode="measured"),
+ ["Segunda l\u00ednea", "de subt\u00edtulos"])
+
+ def test_wrap_line_count_never_grows(self):
+ C = self.caption
+ corpus = ["A third line the tool times for me", "Hello world",
+ "one two three four five six seven eight nine ten",
+ "Una tercera l\u00ednea con tiempos autom\u00e1ticos",
+ "\u3053\u3093\u306b\u3061\u306f\u3001\u4e16\u754c\u306e\u5b57\u5e55\u3067\u3059",
+ "\u81ea\u52d5\u3067\u30bf\u30a4\u30df\u30f3\u30b0\u304c\u6c7a\u307e\u308b\u884c",
+ "an end-to-end example of a long hyphenated line"]
+ for text in corpus:
+ for max_em in range(4, 30):
+ with self.subTest(text=text[:12], max_em=max_em):
+ for mode in ("phrase", "measured"):
+ self.assertEqual(len(C.wrap_text(text, float(max_em), mode=mode)),
+ len(C.wrap_text(text, float(max_em), balance=False)),
+ mode)
+
+ def test_multi_character_particles_are_matched_as_words_not_characters(self):
+ """から / まで / より are two-character particles. Keeping them in the CHARACTER table made
+ か, ら, ま, で, よ and り one-character particles of their own, which none of them is."""
+ C = self.caption
+ for ch in "\u304b\u3089\u307e\u3088\u308a":
+ self.assertNotIn(ch, C.JA_PARTICLES, "%r is not a particle on its own" % ch)
+ # \u304b after a kanji stem is okurigana, not a forbidden line start
+ self.assertEqual(C.break_penalty("\u6f22", "\u304b", "ja",
+ before="\u6f22", after="\u304b\u305f\u3061"), 0.9)
+ # the whole word is seen when the caller passes the surrounding text
+ self.assertEqual(C.break_penalty("\u305f", "\u304b", "ja",
+ before="\u898b\u305f", after="\u304b\u3089\u3067\u3059"), 1.0)
+ self.assertEqual(C.break_penalty("\u3089", "\u8a71", "ja",
+ before="\u898b\u305f\u304b\u3089", after="\u8a71\u3057\u305f"), 0.2)
+ # ... and a \u3089 that merely ends a word is not a particle
+ self.assertEqual(C.break_penalty("\u3089", "\u8a71", "ja",
+ before="\u3055\u304f\u3089", after="\u8a71\u3057\u305f"), 0.5)
+
+ def test_break_penalty_prefers_a_sentence_end_and_a_particle(self):
+ C = self.caption
+ self.assertEqual(C.break_penalty("\u3002", "\u6b21", "ja"), 0.0)
+ # a particle keeps company with the word BEFORE it: breaking after one is preferred,
+ # breaking before one is forbidden
+ self.assertEqual(C.break_penalty("\u306f", "\u4e16", "ja"), 0.2) # after a particle
+ self.assertEqual(C.break_penalty("\u754c", "\u306f", "ja"), 1.0) # before a particle
+ self.assertLess(C.break_penalty("\u306f", "\u4e16", "ja"), # after a particle
+ C.break_penalty("\u6c7a", "\u307e", "ja")) # inside a word
+ self.assertEqual(C.break_penalty("\u3042", "\u3063", "ja"), 1.0) # small kana may not start a line
+
+
if __name__ == "__main__":
unittest.main(verbosity=2)