Local video editor for coding agents: 42 FFmpeg tools with a machine-readable contract and an MCP server, for Claude Code, Cursor and Codex. Cut, captions, reframe, loudness, platform exports. No cloud, no API keys.
Python agent-skillsai-agentsaudio-processingcaptionsclaude-codecodexcoding-agentcursorffmpegloudness-normalizationmcpmcp-servermodel-context-protocolpythonsubtitlestranscodingvideovideo-editingvideo-processingwhisper
feat: delivery templates (render.py --template, safe zones, platform presets, blurred fit, social pack, sticker/hook/meme) (#224)
claude[bot]bdc7a4f07c54
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 92bedf5..e370b9c 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -4,7 +4,20 @@## Unreleased-(nothing yet)+### Added++- **One delivery table** (`scripts/_platforms.py`, internal — the public tool count is unchanged at 42). Every destination is described once: frame, fps, the compliance spec `check.py` reports (duration, aspects, minimum height, fps, codecs, size, LUFS, true peak, SDR-only), the fraction of the frame the app's own UI covers, caption defaults, the export preset and the check platform. `check.py`'s `SPECS` and `export.py`'s `PRESETS`/`PLATFORM_OF` are now built from it — each platform preset's frame and duration cap included — so the loudness `export.py --normalize` hits, the frame it writes, the cap it trims at and the spec `check.py` enforces are the same numbers by construction (two presets deliberately differ and say so in the code: `youtube4k` is YouTube at 2160p, and no `youtube*` preset trims at YouTube's 12-hour limit). The alias map (`youtube-shorts`/`yt-shorts` → `shorts`, `yt` → `youtube`, `instagram`/`ig` → `reels`, `twitter` → `x`, `fb` → `facebook`) is accepted by `check.py --platform`, `export.py --preset`, `caption.py`/`graphics.py`/`overlay.py --platform`, `look.py --safe` and `render.py --template` alike, and those tools now offer one platform vocabulary rather than three. Existing platform rows and preset command lines are byte-for-byte what they were.+- **Delivery templates**: `render.py --template tiktok INPUT [--cues cues.txt | --srt subs.srt] [--logo] [--title] [--brand] [--chapters] [--fit crop|pad|blur] [-o OUT]` fills a project shipped in `templates/` and renders it — frame and fit, captions sized and placed clear of the platform's UI, loudness, the platform export preset and that platform's `check.py` in one command. Templates ship for `tiktok`, `reels`, `shorts`, `youtube-shorts`, `youtube`, `x`, `linkedin`, `facebook` and `podcast` (audio: silence trim, −16 LUFS, chapters when given, the podcast check). `--list-templates` prints them with their frames, limits and safe zones; `--write-project FILE` writes the filled project for editing and renders nothing; an unknown name is refused (`kind: input`) with the list.+- **The social pack**: `render.py --template all INPUT` (or `--template tiktok,reels,x`) renders every named destination from the same edit into `<stem>_<platform>.mp4` next to the input (`.m4a` for an audio-only destination, and `--chapters` reaches it), runs each platform's own check, and writes `<stem>_pack.md` with one table row per destination (file, size, duration, check). Under `--dry-run` the pack prints every child's planned commands and its table reads `planned` with no size or duration, since nothing was encoded and nothing was verified. `report.py --pack <stem>_pack.md` renders that table as an HTML page.+- **Real presets per destination**: `export.py --preset tiktok|shorts|linkedin|facebook` are their own entries rather than aliases of `reels`/`youtube`, each with its platform's frame, duration limit and loudness spec. `--preset youtube-hdr` writes HEVC Main10 keeping the source's own HDR10/HLG tags and refuses an SDR source (`kind: input`, pointing at `--preset youtube`) instead of labelling SDR as HDR; `--preset youtube-av1` encodes AV1 with SVT-AV1 (libaom fallback) and refuses with `kind: missing_tool` on a build that has neither. `check.py --platform facebook` is new.+- **Text stays out of the app's UI**: `caption.py --platform NAME`, `graphics.py --platform NAME` and `overlay.py --platform NAME` (so a template's `--logo` clears TikTok's status bar instead of landing 24 px under it) take their margins from that destination's safe zone (TikTok covers the bottom 22 % with its description block and the right 14 % with the like column; Reels 20 %/12 %, Shorts 18 %/12 %; the feed destinations keep a 5 % title-safe border). An explicit `--margin` (new on `graphics.py`) or `--position` wins. `render.py` passes `--platform` only for projects filled from a template, so a hand-written project is unchanged. `look.py --safe NAME` shades those zones on the sheet or frame, so "is the caption readable" can be checked against the app and not just the file.+- `fit.py --fit blur`: reach an aspect with the whole picture centred on a blurred, darkened (`eq brightness=-0.15`) copy of itself — nothing cropped, no black bars. The darkening is SDR-only: an `eq` on PQ/HLG code values is not the same perceptual dim, so an HDR source keeps an undimmed (and un-tone-mapped) blurred background, with one `info` line saying so. Templates ask for it as `"frame": {"aspect": "9:16", "fit": "blur"}`, or `render.py --template tiktok clip.mp4 --fit blur`. `render.py` projects now accept `"frame": {"fit": ...}`.+- `graphics.py --template sticker|hook|meme`: a filled chip of `--text` that pops in at `--position` (the social sticker), the full-width opening card (`--title --duration 3`) with a thin progress bar along the top that empties as the card's time runs out, and the classic meme layout (`--top`/`--bottom`, upper-case white with a heavy black outline). All three work inside a `render.py` project's `graphics[]` — which now takes `text`, `top`, `bottom`, `duration`, `margin` and `platform` alongside the older keys — and honour `--platform`'s safe zone.+- `render.py` projects may carry `"template"` (the template they were filled from) and audio-only deliveries now carry their intermediates through the audio container instead of `.mp4`, which is what makes the podcast template render end to end from a `.wav`.++### Docs+- SKILL.md gains the delivery-template rows and the safe-zone gotcha, `references/scripts.md` a templates section with the safe-zone table, `docs/contract.md` the delivery-table shape, what is derived from it and the new arguments, `references/gotchas.md` a "Platform safe zones" section (the target of SKILL.md's safe-zone pointer), and the README a "Deliver to a platform" example. `demos/build.py` and `docs/demos.md` gain two demos: `fit_blur` and `template_tiktok`. `docs/roadmap.md` marks 1.14.0 done and renumbers the remaining themes.+- `tests/fixtures/mcp_tools.json` regenerated: `render` gains `template`, `list_templates`, `cues`, `srt`, `logo`, `title`, `brand`, `chapters`, `fit`, `output` and `write_project`; `caption`, `graphics` and `overlay` gain `platform` (and `graphics` also `margin`, `text`, `top`, `bottom`, `duration`); `look` gains `safe`; `report` gains `pack`. Nothing was removed, renamed or made required.## 1.13.0diff --git a/README.md b/README.mdindex 55d011f..f6aee8f 100644--- a/README.md+++ b/README.md@@ -107,6 +107,25 @@ Then talk to your agent:The agent runs `probe.py`, `cut.py --segments 0:45-3:10,5:00-6:30`, `fit.py --duration 60 --aspect 9:16 --fit crop`, `export.py --preset reels`, `check.py --platform reels` and `look.py`, then reports "final.mp4: 59.98 s, 1080×1920, 30 fps, AAC stereo" with the contact sheet it inspected.+### Deliver to a platform++One command per destination, with the app's own UI taken into account:++```bash+python3 $S/render.py talk.mp4 --template tiktok --cues cues.txt+```++That fills the shipped `templates/tiktok.json`: 9:16 crop, captions popped word by word *above*+TikTok's description bar and clear of its like column, −14 LUFS, the `tiktok` export preset, and+a `check.py --platform tiktok` on the file it wrote. Templates ship for `tiktok`, `reels`,+`shorts`, `youtube-shorts`, `youtube`, `x`, `linkedin`, `facebook` and `podcast`;+`--template all` (or a comma-separated list) renders every destination from the same edit and+writes a `<name>_pack.md` table of what each one produced. Files land next to the input unless+`-o` says otherwise, and `--dry-run` shows every planned command rather than a result.+`render.py --list-templates` prints them with their frames, limits and safe zones. Alias+spellings work everywhere a platform is named (`youtube-shorts` = `shorts`, `ig` = `reels`,+`twitter` = `x`, `fb` = `facebook`).+The tools also work on their own, from any shell:```bash@@ -172,7 +191,7 @@ These are the rules the skill file gives the agent and the code enforces.|---|---|| `probe.py` | Duration, fps (+ VFR detection), resolution, codecs, bit depth, HDR format incl. Dolby Vision (`hdr` for BT.2020 or PQ/HLG, `hdr_signal` for a real PQ/HLG/DV transfer only), colour space, rotation, every audio stream; `--analyze` flags Log footage || `scenes.py` | Scene changes, audio peaks, highlight proposals (`--rank-by audio` loudest, or `--rank-by duration` longest — both proxies, not "best") and a per-scene sheet; cut list for `cut.py --segments` |-| `look.py` | Contact sheet, single frames, side-by-side comparison as PNG so the agent can see what it made |+| `look.py` | Contact sheet, single frames, side-by-side comparison as PNG so the agent can see what it made; `--safe NAME` shades the zones a platform's own UI covers |**Editing**@@ -181,7 +200,7 @@ These are the rules the skill file gives the agent and the code enforces.| `cut.py` | In/out or multi-segment cuts, lossless `-c copy` first, re-encode fallback, `--accurate` for frame-exact video and sample-exact audio; reports `precision` || `join.py` | Concatenate clips with xfade transitions, normalising size, fps, sample rate and channel layout (the widest clip's, or `--channels`); audio-only inputs are joined as audio || `silence.py` | Detect and remove dead air (jump cuts) with a margin around speech; list or export the cut list |-| `fit.py` | Fit to a duration (pitch-preserving speed change or trim, smooth slow-mo) and/or aspect ratio (pad or crop, with `--crop-x`/`--crop-y` to keep an off-centre subject) and/or exact `--width`/`--height`; rotate 90/180/270, flip h/v; force constant fps |+| `fit.py` | Fit to a duration (pitch-preserving speed change or trim, smooth slow-mo) and/or aspect ratio (pad, crop or `--fit blur`'s blurred, darkened fill, with `--crop-x`/`--crop-y` to keep an off-centre subject) and/or exact `--width`/`--height`; rotate 90/180/270, flip h/v; force constant fps || `crop.py` | Crop to an exact pixel rectangle (`--x --y --width --height`) — distinct from `fit.py --fit crop`, which crops to an aspect ratio it computes itself || `cropdetect.py` | Measure existing black letterbox/pillarbox bars and report the `crop.py`-ready rectangle that removes them — analysis only, writes no file || `deinterlace.py` | Deinterlace interlaced source footage (`yadif`), `--mode frame`/`field`, `--parity` |@@ -216,24 +235,24 @@ 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 |-| `overlay.py` | Logos, watermarks and titles with position, time range, opacity, fades; `--video` for picture-in-picture, `--chromakey` for green-screen compositing |-| `graphics.py` | Lower-thirds, title cards, chapter chips, progress bars, countdowns, corner bugs drawn by FFmpeg from a brand kit |+| `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 || `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) |**Delivery**| Tool | What it does ||---|---|-| `export.py` | Presets `youtube`, `youtube4k`, `reels`, `x`, `prores`, `h265`, `gif`, all tagged BT.709; `--normalize` meets the platform's loudness in the same call (`render.py` turns it on by default for platform presets) |+| `export.py` | Presets `youtube`, `youtube4k`, `reels`, `tiktok`, `shorts`, `linkedin`, `facebook`, `x`, `youtube-hdr` (HEVC Main10, source HDR tags kept), `youtube-av1`, `prores`, `h265`, `gif`, `copy`, all tagged BT.709 unless they carry HDR; `--normalize` meets the platform's loudness in the same call (`render.py` turns it on by default for platform presets) || `proxy.py` | Small, low-bitrate proxy for downstream AI analysis/preview/editing decisions — resize by `--width`/`--scale`, proxy-grade `--crf` (deprecated alias of `--quality`), `--fps`, `--no-audio`; not a delivery preset |-| `check.py` | PASS / WARN / FAIL against YouTube, Shorts, Reels, TikTok, X, LinkedIn, broadcast and podcast specs (podcast also reports chapter markers and channel count), with the fix for each failure and a `format` / `judgement` kind per row |-| `report.py` | Single-file HTML delivery report: before/after sheets, media facts, loudness, compliance, the commands run |+| `check.py` | PASS / WARN / FAIL against YouTube, Shorts, Reels, TikTok, X, LinkedIn, Facebook, broadcast and podcast specs, from the same delivery table the export presets and templates read (podcast also reports chapter markers and channel count), with the fix for each failure and a `format` / `judgement` kind per row |+| `report.py` | Single-file HTML delivery report: before/after sheets, media facts, loudness, compliance, the commands run; `--pack` renders a social pack table |**Orchestration**| Tool | What it does ||---|---|-| `render.py` | Render a whole edit from a declarative `project.json` (clips, transitions, captions, overlays, music and stem levels, loudness, export, chapter markers, check); `--init`, `--dry-run`, `--stop-after` |+| `render.py` | Render a whole edit from a declarative `project.json` (clips, transitions, captions, overlays including the social sticker/hook/meme graphics, music and stem levels, loudness, export, chapter markers, check); `--init`, `--dry-run`, `--stop-after`; `--template NAME INPUT` renders a shipped delivery template (`--template all` writes the whole social pack plus its table) || `batch.py` | Apply a step recipe or a project to a folder with a content-hash cache; `--watch` || `multicam.py` | Align any number of cameras and recorders by audio (with drift correction) and cut between them from a switch list || `verify.py` | Run the toolchain on real device files and report PASS / FAIL per step |diff --git a/SKILL.md b/SKILL.mdindex 81a70f2..bb023ba 100644--- a/SKILL.md+++ b/SKILL.md@@ -5,59 +5,59 @@ description: 'Edit video and audio with local FFmpeg from natural-language reque# ffmpeg-skill-Scripts live in `scripts/` next to this file; run them with `python3 <skill-dir>/scripts/<name>.py`. This file is enough to do a job: the table below routes the request and `--help` on the one script you are about to run is the cheapest full flag list. The reference files cost as much to read as this file does, so open one only when it answers a question you actually have: `references/scripts.md` (every flag of all 42 scripts, for comparing tools), `references/devices.md` (iPhone HDR, GoPro, DJI, screen recordings, Zoom), `references/gotchas.md` (the long form of the one-line rules at the end of this file).+Scripts live in `scripts/` next to this file; run them with `python3 <skill-dir>/scripts/<name>.py`, 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 — without it the tool warns today, refuses from 2.0); `--plan FILE` (the dry run as a plan document `render.py FILE` executes later, refusing if an input changed: "plan → confirm → execute" in one round trip). Every re-encoding tool also takes `--codec h264|hevc|av1|prores` and `--quality N` (CRF scale, replaces the deprecated `--crf`): unset, SDR is x264 and HDR is x265 Main10; `prores` needs an explicit `-o NAME.mov`, `h264` refuses an HDR source (`color.py --to-sdr` first).+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).-Writing tools run nothing under `--dry-run`; `probe`, `check`, `sync`, `multicam`, `scenes`, `cropdetect`, `report`, `silence`, `loudness` and `stabilize` may still run ffmpeg/ffprobe to measure or analyse — they just don't write their final artifact (nor side files such as `--edl`, `--sheet` or a generated `.ass`); `verify` accepts the flag but ignores it. Exact per-tool semantics: `contract --json`'s `dry_run` field (or `docs/contract.md`).+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.## Workflow (always follow this order)-0. **Environment, only on failure.** Do not start a job with `doctor`: on a working machine it tells you nothing the job needs, and on a broken one the script fails on its own with `kind: missing_tool` (no ffmpeg) or an ffmpeg error naming the filter or encoder (`No such filter: 'subtitles'`). Run `python3 <skill-dir>/scripts/_contract.py doctor` (also `npx ffmpeg-skill doctor`; there is no doctor.py) after such a failure, or when the user asks what the machine can do. Read `ok` and the tool's `usable`; if `usable` isn't `yes`, report the missing capability (usually `libass`, `zscale` or an encoder) instead of discovering it through a runtime failure. `contract --json`'s full tool schema is for a *planning* agent choosing a tool from an abstract goal, not for this workflow.-1. **Probe what you must plan from.** Run `probe.py` on each input you plan the edit from — duration, fps, resolution, codecs, channels, `variable_frame_rate_suspected` — and whenever the user asks a question about a file. You do not need a separate probe before every edit: every writing tool's `--json` already carries its input and a probe of the output it wrote. Plan from real numbers, never assumptions.-2. **Prefer lossless.** If the request can be met without re-encoding (plain cuts on keyframes, remuxing, audio-only changes), do not re-encode. `cut.py` and `loudness.py` stream-copy video by default; pass `--accurate` to `cut.py` only for frame-exact cuts.-3. **Plan with `--dry-run --json`, then execute.** Trust `--json`, not a dry run's human-readable summary line, for any number after the plan (dimensions there can be a placeholder, not a computed preview — `docs/contract.md`). Use it to confirm a plan before long encodes and to report exact facts. `--fast` is preview quality (x264 veryfast), `--progress` prints percent/ETA on stderr. Never point `-o` at a file you did not create in this job unless the user asked for it to be replaced; pass `--overwrite` only then.-4. **Chain in a sensible order.** Colour (HDR→SDR / LUT) → cut → join → silence → fit → caption/overlay → sync → audio → loudness → export. Frame changes (fit/crop) before captions and overlays, so text is sized for the final frame. Re-encode as few times as possible: intermediates at CRF 18 (the default), `export.py` only for the last step. **Three or more steps: use `render.py` with a project.json** — one call, one JSON, one place for the user to change a number — rather than hand-chaining tools.-5. **Check the deliverable.** Before reporting, run `check.py OUTPUT --platform X` for the destination the user named. Each row is `format` or `judgement`. Format rows (codec, pixel format, size, true peak, colour tags, VFR) are safe to fix mechanically. Judgement rows change the content: duration (cut loses material), aspect (crop loses edges), fps (drops motion), loudness (ambience must not be boosted) — fix those only when the request already implies the answer, otherwise state the choice and its cost in one line. Mention WARNs; do not chase them.-6. **Verify the output.** Confirm duration, resolution, fps and audio match the request — from the writing tool's own `--json`/`--json-brief` probe, or `probe.py` — and report those numbers ("final.mp4: 59.98 s, 1080x1920, 30 fps, AAC stereo"). A step is done only when the script exited 0 and the output probes as expected: a non-zero exit, a missing or empty file, or a probe that contradicts the request is a failure, and the report says so with the script's error message.-7. **Keep the user's originals.** Never overwrite the source; write new files next to the input or where the user asked. Set `FFMPEG_SKILL_NO_OVERWRITE=1` in the environment you run these scripts in: an existing output path is then refused (`kind: input`) instead of warned about, and `--overwrite` stays the one way to say "yes, replace it". It is the recommended agent setting — an agent picking output names cannot see which files the user already cares about — and it is what 2.0 does by default.-8. **Look at the picture.** Whenever the picture changed (captions, overlays, graphics, crop/pad, resize, colour, transitions, a `join.py` that scaled or padded a clip to the first clip's frame, a `color.py --to-sdr` that tone-maps an HDR source) run `look.py OUTPUT --tiles 3x2` (or `--at T` for one frame) and view the PNG; the full 4x3 sheet is for a job about layout across the whole clip. The job is not finished until the report's `Look:` line names that PNG — a probe cannot see a caption sitting on someone's face. Audio-only jobs write `Look: not needed`; there is no picture. What to look for splits like `check.py`'s rows in step 5:- - **Mechanical (this skill's own job to verify and report):** the specified text/logo is present at the specified position, subtitles/text appear at the specified timestamps, dimensions are even. Letterboxing/pillarboxing from `fit.py --fit pad` is the *correct* result of that mode, never a defect to flag.- - **Judgement (report it, don't silently pass or fail):** whether a subject or face is cut off, whether text sits over a face, whether colours look washed out, whether a transition lands. These need deciding what the subject *is*, which belongs to the calling agent (see "What this skill does and does not decide") — say what you see in one line and let them judge it.+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.+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.+4. **Chain in a sensible order.** A delivery request with no other editing ("make this a TikTok") is one template run — `render.py --template NAME INPUT`, not a hand-built chain. Otherwise: colour (HDR→SDR / LUT) → cut → join → silence → fit → caption/overlay → sync → audio → loudness → export. Frame changes before captions and overlays, so text is sized for the final frame. Re-encode as few times as possible: intermediates at CRF 18, `export.py` only last. **Three or more steps: `render.py` with a project.json** — one call, one JSON, one place for the user to change a number.+5. **Check the deliverable.** Before reporting, run `check.py OUTPUT --platform X` for the destination the user named (a template run already does). Format rows (codec, pixel format, size, true peak, colour tags, VFR) are safe to fix mechanically. Judgement rows change the content: duration (cut loses material), aspect (crop loses edges), fps (drops motion), loudness (ambience must not be boosted) — fix those only when the request implies the answer, otherwise state the choice and its cost in one line. Mention WARNs; do not chase them.+6. **Verify the output.** Confirm duration, resolution, fps and audio match the request — from the writing tool's own `--json`/`--json-brief` probe, or `probe.py` — and report those numbers ("final.mp4: 59.98 s, 1080x1920, 30 fps, AAC stereo"). A step is done only when the script exited 0 and the output probes as expected: a non-zero exit, a missing or empty file, or a probe that contradicts the request is a failure reported with the script's error message.+7. **Keep the user's originals.** Never overwrite the source; write new files next to the input or where the user asked. Set `FFMPEG_SKILL_NO_OVERWRITE=1` in the environment you run these scripts in: an existing output path is then refused (`kind: input`) instead of warned about, with `--overwrite` the one way to say "yes, replace it". It is the recommended agent setting, and 2.0's default.+8. **Look at the picture.** Whenever the picture changed (captions, overlays, graphics, crop/pad, resize, colour, transitions, a `join.py` that scaled a clip to the first clip's frame, a `color.py --to-sdr`) run `look.py OUTPUT --tiles 3x2` (or `--at T` for one frame) and view the PNG; the full 4x3 sheet is for a job about layout across the whole clip. The job is not finished until the report's `Look:` line names that PNG — a probe cannot see a caption sitting on someone's face. Audio-only jobs write `Look: not needed`. What to look for splits like `check.py`'s rows in step 5:+ - **Mechanical (this skill's own job to verify and report):** the specified text/logo is at the specified position, subtitles appear at the specified timestamps, dimensions are even. Letterboxing from `fit.py --fit pad` is the *correct* result of that mode, never a defect to flag.+ - **Judgement (report it, don't silently pass or fail):** whether a subject or face is cut off, text sits over a face, colours look washed out, a transition lands. These need deciding what the subject *is*, which belongs to the calling agent — say what you see in one line and let them judge it.With no vision capability, write `Look: PATH (pixels not inspected; agent has no image view)` — never claim a picture was inspected when it wasn't, and don't stall waiting for a capability that isn't there.## Before you run anything: what to ask, what to assume-Ask one short question only when the answer changes the output materially and the request does not imply it. When several things are open at once (a vague "make it for social media" leaves destination, aspect, length and captions open), don't ask them one per turn: propose one bundle with your defaults and let the user change any part ("Reels: 9:16 with padding, trimmed to 60 s, -14 LUFS, no captions — OK, or change something?"). One question, one answer, then the run. Never ask for what `probe.py` can tell you.+Ask one short question only when the answer changes the output materially and the request does not imply it. When several things are open at once (a vague "make it for social media" leaves destination, aspect, length and captions open), don't ask them one per turn: propose one bundle with your defaults and let the user change any part ("Reels: 9:16 padded, 60 s, -14 LUFS, no captions — OK?"). One question, one answer, then the run. Never ask for what `probe.py` can tell you.-- **Destination** decides aspect, length limit, loudness and codec; "for Reels" answers all four. No destination named and a plain cut/caption: keep the source format and say so. If the user says "export", "post" or "deliver", ask where.-- **Duration** ("make it 60 s") without a method: speed up for ≤1.5× changes, trim otherwise, and say which you chose. Ask when the content is a talk (trimming loses words) and the change is large.+- **Destination** decides aspect, length limit, loudness and codec; "for Reels" answers all four and names a template. No destination named and a plain cut/caption: keep the source format and say so. If the user says "export", "post" or "deliver", ask where.+- **Duration** ("make it 60 s") without a method: speed up for ≤1.5× changes, trim otherwise, and say which. Ask when the content is a talk (trimming loses words) and the change is large.- **Captions** without a text source: `--transcribe` if a local whisper exists, otherwise ask for the text or a timed file; never invent dialogue.- **Fonts and brand**: if the user mentions a brand, colours or "our font", ask for or create `brand.json` once and reuse it.-- **CJK / non-Latin text**: let the tool pick the font by script (`--font` turns that off); `--lang ja|ko` for Han-only text. `doctor --json` `.fonts.scripts` says what renders here. Tofu is a failed job, not a style.-- **Crop position** for `--fit crop`: centre by default, but when the request or the source names an off-centre subject ("keep the product on the right", "don't cut off my hands", someone visibly off-centre in the sheet) use `--crop-x`/`--crop-y` (0=left/top, 1=right/bottom) instead of a silent centre guess. Ask which edge to keep when the sheet shows the subject near an edge and the request doesn't say.+- **CJK / non-Latin text**: let the tool pick the font by script (`--font` turns that off); `--lang ja|ko` for Han-only text. `doctor --json` `.fonts.scripts` says what renders here. Tofu is a failed job.+- **Crop position** for `--fit crop`: centre by default, but when the request or the source names an off-centre subject ("keep the product on the right", someone visibly off-centre in the sheet) use `--crop-x`/`--crop-y` (0=left/top, 1=right/bottom) instead of a silent centre guess, or ask which edge to keep.- Anything else (transition type, caption style): pick the conventional default, say what you picked, offer the alternative in one line.## What this skill does and does not decideThis skill cuts, joins, measures, syncs, exports and checks files — it executes an edit, it does not decide one. What belongs to the human, the calling agent or another skill:-- **Which cut is right, or whether a deliverable is approvable** — this skill measures and reports (`check.py`'s PASS/WARN/FAIL, `cut.py`'s measured duration error); the user or a production agent decides whether that ships.-- **What makes a highlight interesting** — `scenes.py --highlights` ranks by a measured proxy (audio energy, scene duration), never by understanding content: candidates, not a verdict.+- **Which cut is right, or whether a deliverable is approvable** — this skill measures and reports (`check.py`'s PASS/WARN/FAIL, `cut.py`'s duration error); the user or a production agent decides whether that ships.+- **What makes a highlight interesting** — `scenes.py --highlights` ranks by a measured proxy (audio energy, duration): candidates, not a verdict.- **Thumbnail or cover composition** — a design decision, not a measurement.-- **Understanding what a video is *about*** — there is no transcription or vision here beyond `look.py`'s contact sheets, which exist for the calling agent's eyes, not for this skill to interpret.-- **Judging what looks good** — "apply this LUT", "correct exposure by +0.3 stops" (`color.py`) is mechanical and belongs here; "grade this scene to look cinematic" belongs to a colour-grading skill ([`color-grading-skill`](https://github.com/kajisho5/color-grading-skill)) that decides the parameters and then calls `color.py`.-- **Picking a subject or region you were not given** — "crop to x=200,y=0" (`crop.py`/`fit.py --crop-x/-y`) is mechanical once the box is known; "crop to keep the speaker in frame" needs deciding *what* the speaker is — a judgement for the calling agent (from a `look.py` sheet) or a motion-graphics skill.+- **Understanding what a video is *about*** — there is no vision here beyond `look.py`'s contact sheets, which exist for the calling agent's eyes, not for this skill to interpret.+- **Judging what looks good** — "apply this LUT", "correct exposure by +0.3 stops" (`color.py`) is mechanical; "grade this scene to look cinematic" belongs to a colour-grading skill ([`color-grading-skill`](https://github.com/kajisho5/color-grading-skill)) that decides the parameters and then calls `color.py`.+- **Picking a subject or region you were not given** — "crop to x=200,y=0" is mechanical once the box is known; "crop to keep the speaker in frame" needs deciding *what* the speaker is — a judgement for the calling agent (from a `look.py` sheet).-The line: same input + same explicit parameters always producing the same verifiable output belongs here; anything that depends on taste, content understanding or what looks or sounds good belongs to whoever makes that judgement. This skill executes parameters it is given, never infers them from what something looks or sounds like.+The line: same input + same explicit parameters always producing the same verifiable output belongs here; anything depending on taste, content understanding or what looks or sounds good belongs to whoever makes that judgement.-If a request needs an FFmpeg feature none of the 42 scripts expose, say so and name the closest built-in option (`--dry-run` to show what would run, or a documented limitation) — never fall back to guessing a raw `ffmpeg`/`ffprobe` invocation or a hand-built filter graph outside `scripts/*.py`. A raw command bypasses every guarantee this skill makes (no shell, typed arguments, verification afterwards), so it is never the fallback when a script's flag doesn't cover something.+If a request needs an FFmpeg feature none of the 42 scripts expose, say so and name the closest built-in option — never guess a raw `ffmpeg`/`ffprobe` invocation or a hand-built filter graph outside `scripts/*.py`. A raw command bypasses every guarantee this skill makes (no shell, typed arguments, verification afterwards), so it is never the fallback when a script's flag doesn't cover something.## Request → script-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, never a plausible-sounding one (there is no `doctor.py`, no `trim.py`, no `subtitle.py`).+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]`); tolerance-style flags that are a length rather than a point in time (`--min-silence`, `--margin`, `--min-keep`, `--fade`) are plain seconds. Use the timecode forms when the user pastes an editor's or NLE cue sheet, so nothing is converted by hand.+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.| User says | Do ||-----------|----|@@ -100,7 +100,9 @@ Timestamp flags — `--start`, `--end`, `--at`, `--from`, `--duration`, `--offse| "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`) |-| "export for YouTube / Reels / X", "a ProRes master" | `export.py input.mp4 --preset youtube\|reels\|x\|prores\|h265` (`--normalize` hits the loudness spec in the same call) |+| "make this a TikTok / Reel / Short / YouTube / X / LinkedIn / podcast" | `render.py --template tiktok\|reels\|shorts\|youtube-shorts\|youtube\|x\|linkedin\|facebook\|podcast input.mp4 [--cues cues.txt\|--srt subs.srt] [--title "..."] [--logo logo.png] [--brand brand.json]` — frame, captions inside the safe area, loudness, export and that platform's check in one command (`--list-templates`, `--write-project` to edit first) |+| "post it everywhere", "one edit for every platform" | `render.py --template all input.mp4 --cues cues.txt` (or a comma list) → one file per destination plus `<name>_pack.md`; `report.py --pack <name>_pack.md` for the HTML |+| "export for YouTube / Reels / X", "a ProRes master" | `export.py input.mp4 --preset youtube\|reels\|tiktok\|shorts\|linkedin\|facebook\|x\|prores\|h265` (`--normalize` hits the loudness spec in the same call; `youtube-hdr` keeps HDR, `youtube-av1` writes AV1) || "make a GIF preview" | `export.py input.mp4 --preset gif` || "a small proxy / cheap preview file" | `proxy.py input.mp4 [--width 640 --no-audio]` — not a delivery preset (those are `export.py`) || "cut out the pauses", "jump cuts" | `silence.py input.mp4 [--threshold -40 --min-silence 0.8]` |@@ -112,6 +114,8 @@ Timestamp flags — `--start`, `--end`, `--at`, `--from`, `--duration`, `--offse| "a podcast episode with chapters" | `loudness.py ep.wav -I -16 --tp -1.5` → `metadata.py ep.m4a --chapters chapters.txt` → `check.py ep.m4a --platform podcast` (chapters and channels rows) || "several changes to the same edit", 3+ steps | `render.py --init project.json`, edit, `render.py project.json` || "a lower third with my name", "countdown intro", "progress bar" | `graphics.py input.mp4 --template lower-third --name "..." --title "..." --start 2 --end 8` |+| "a sticker", "a hook card for the first 3 s", "meme text" | `graphics.py input.mp4 --template sticker --text "NEW" --platform tiktok` / `--template hook --title "..." --duration 3` / `--template meme --top "..." --bottom "..."` |+| "blurred background instead of black bars" | `fit.py input.mp4 --aspect 9:16 --fit blur` (whole picture kept, borders are a blurred, darkened copy) || "use our brand fonts/colours/logo" | `--brand brand.json` on caption/overlay/graphics, or `"brand"` in project.json || "send me a summary of what you did" | `report.py --before raw.mov --after final.mp4 --platform youtube -o report.html` || "do this to every file in the folder" | `batch.py FOLDER --recipe batch.json` (steps or a render project; cached) |@@ -140,14 +144,14 @@ Timestamp flags — `--start`, `--end`, `--at`, `--from`, `--duration`, `--offse## Audio-only files-Audio is a first-class input: `probe.py`, `cut.py`, `silence.py`, `loudness.py`, `audio.py`, `sync.py` and `check.py --platform podcast` take WAV, FLAC, MP3, M4A/AAC, OGG and Opus, and the output extension picks the format. `Look: not needed` in the report; `Check:` still applies. Scripts that need a picture (`fit`, `caption`, `overlay`, `graphics`, `color`, `export`, `scenes`, `look`) refuse an audio file with "input has no video stream" — say so instead of forcing a video wrapper. The same commands work with `talk.wav` in place of `talk.mp4`; audio recipes, packet vs sample precision, joining and extracting one track: `references/gotchas.md#audio-only-files`.+Audio is a first-class input: `probe.py`, `cut.py`, `silence.py`, `loudness.py`, `audio.py`, `sync.py`, `check.py --platform podcast` and `render.py --template podcast` take WAV, FLAC, MP3, M4A/AAC, OGG and Opus, and the output extension picks the format. `Look: not needed` in the report; `Check:` still applies. Scripts that need a picture (`fit`, `caption`, `overlay`, `graphics`, `color`, `export`, `scenes`, `look`) refuse an audio file with "input has no video stream" — say so instead of forcing a video wrapper. Audio recipes, packet vs sample precision, joining and extracting one track: `references/gotchas.md#audio-only-files`.## Report format-Reply in the language the request itself is written in — the user's own sentences, not a language the request talks about (a request for subtitles in another language is still answered in the language it was written in) and not the language of a tool's error text or file names. Any language works the same way. Keep the field labels (`Done:`, `Steps:`, `Check:`, `Look:`, `Notes:`) in English: they read like log fields and stay recognisable across languages. Everything around them — the sentences, any question, any explanation of a judgement call — is in the user's language. Never default to English because the tool names and flags are English, and never drift because the job was short or the report is a failure: a one-line "file does not exist" is written in the request's language too. A mid-conversation switch follows the user's latest message. This holds for a one-command job: English `Done:`/`Steps:` sentences with one word of the user's language in `Notes:` is an English report — the descriptions are in the user's language even when the values are technical.+Reply in the language the request itself is written in — the user's own sentences, not a language the request talks about (a request for subtitles in another language is still answered in the language it was written in) and not the language of a tool's error text or file names. Any language works the same way. Keep the field labels (`Done:`, `Steps:`, `Check:`, `Look:`, `Notes:`) in English: they read like log fields 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.-Finish every job with this shape (numbers from a tool's `--json` or `probe.py`/`check.py`, not memory):+Finish every job with this shape (numbers from `--json` or `probe.py`/`check.py`, not memory):```Done: final.mp4 — 59.98 s, 1080x1920, 30 fps, H.264, AAC stereo, -14.1 LUFS@@ -169,7 +173,7 @@ Notes: 元は VFR だったので 30 fps に揃えた。音声はモノラルだSame shape in every other language, labels still English — zh: `Done: final.mp4 — 59.98 秒、1080x1920、30 fps、H.264` / `Steps: 0:12-1:12 剪切 -> 9:16 裁剪 -> 字幕 -> Reels 导出`; ko: `Done: final.mp4 — 59.98초, 1080x1920, 30 fps, H.264` / `Steps: 0:12-1:12 컷 -> 9:16 크롭 -> 자막 -> Reels 내보내기`.-Keep it to those five lines plus anything the user must decide. Attach the contact sheet when the edit touched the picture. Never report success without the output probe; never describe a fix you did not run.+Keep it to those five lines plus anything the user must decide. Never report success without the output probe; never describe a fix you did not run.When a step fails, replace `Done:` with `Failed:` and keep the rest honest:@@ -181,23 +185,24 @@ Look: not needed (nothing written)Notes: send a valid .cube, or say if you want the clip left as is```-A refusal (a judgement this skill does not make, or something outside its scope) uses the same shape: `Failed:` names what was refused and why, `Steps:` lists what did run (usually only probe), `Look: not needed`. Both keep the five labels so a failed report scans like a successful one — the shortest failure still gets all five lines, never prose headings. When a failure JSON carries `error.hint`, quote it in `Notes:`: it is the flag change that makes a retry meaningful.+A refusal (a judgement this skill does not make, or something outside its scope) uses the same shape: `Failed:` names what was refused and why, `Steps:` lists what did run, `Look: not needed`. The shortest failure still gets all five labels, never prose headings. When a failure JSON carries `error.hint`, quote it in `Notes:`: it is the flag change that makes a retry meaningful.-Every script prints `{"status": "failed", "error": {"kind": input | ffmpeg | output | missing_tool | timeout | verification | interrupted, "message": ...}}` with `--json` and exits non-zero; quote the message, never paraphrase it into a success.+Every script prints `{"status": "failed", "error": {"kind": input | ffmpeg | output | missing_tool | timeout | verification | interrupted, "message": ...}}` with `--json` and exits non-zero; quote the message, never paraphrase it.## Things that look right but are wrong-One line each, and each line is enough to act on; open the linked `references/gotchas.md` section only when the job is in that area and the line leaves you with a question.+One line each, each enough to act on; open the linked `references/gotchas.md` section only when the job is in that area and the line leaves a question.-- HDR (iPhone, HDR10) re-encoded through an SDR path goes flat; the scripts keep HDR, and `hdr: true` is wider than `hdr_signal: true` (a real PQ/HLG/Dolby Vision transfer). Details: [#hdr-and-colour](references/gotchas.md#hdr-and-colour)+- HDR (iPhone, HDR10) re-encoded through an SDR path goes flat; the scripts keep HDR, and `hdr: true` is wider than `hdr_signal: true` (a real PQ/HLG/DV transfer). Details: [#hdr-and-colour](references/gotchas.md#hdr-and-colour)- Log footage (S-Log/V-Log/C-Log) is tagged SDR and looks grey: `probe.py --analyze`, then `color.py --lut` before anything else. Details: [#log-footage](references/gotchas.md#log-footage)- A `-c copy` cut can start on a wrong or frozen frame; `cut.py` re-encodes past a 0.5 s snap — respect it. Details: [#keyframe-cuts](references/gotchas.md#keyframe-cuts)- VFR phone/screen recordings: re-encodes conform to CFR, `cut.py` switches to `--accurate`; pick the rate with `fit.py --fps` when the average is odd. Details: [#variable-frame-rate](references/gotchas.md#variable-frame-rate)-- Sync/multicam `confidence` under 0.3 (or a huge offset) is probably wrong — check every camera, and remember these align audio, never lip sync. Details: [#sync-multicam-and-drift](references/gotchas.md#sync-multicam-and-drift)+- Sync/multicam `confidence` under 0.3 (or a huge offset) is probably wrong — check every camera; these align audio, never lip sync. Details: [#sync-multicam-and-drift](references/gotchas.md#sync-multicam-and-drift)- "Normalised" audio can still clip (check true peak), and ambience at -40 LUFS or below must never be raised to a speech target. Details: [#loudness-and-ambience](references/gotchas.md#loudness-and-ambience)- Captions burned before a crop/resize land off-frame; burned small then upscaled by `export.py` they come out soft — fit to the delivery size first. Details: [#captions-fonts-and-text-order](references/gotchas.md#captions-fonts-and-text-order)-- Non-Latin text picks a font by script since 1.12; `doctor --json` `fonts.scripts` says which languages this machine renders; no font = failed job, not tofu. Details: [#fonts-by-script](references/gotchas.md#fonts-by-script)+- Non-Latin text picks a font by script since 1.12; `doctor --json` `fonts.scripts` says which languages this machine renders; no font = failed job. Details: [#fonts-by-script](references/gotchas.md#fonts-by-script)- `--fit crop` 16:9 → 9:16 throws away 70 % of the width, 60→30 fps halves the motion, and "60 seconds" by speed or by trim are different answers — say which and why. Details: [#reframing-fps-and-duration](references/gotchas.md#reframing-fps-and-duration)+- TikTok/Reels cover the bottom fifth and the right column with their own UI — templates keep text out of those zones; `look.py --safe tiktok` shows them. Details: [#platform-safe-zones](references/gotchas.md#platform-safe-zones)- `yuv420p` needs even dimensions and phone rotation tags are honoured, both automatically. Details: [#dimensions-and-rotation](references/gotchas.md#dimensions-and-rotation)- `scenes.py --highlights` ranks by loudness (or duration), never by meaning: check the sheet before treating picks as final. Details: [#highlights](references/gotchas.md#highlights)- Three hand-chained re-encodes should be one `render.py` project; re-encodes use x264 `medium`. Details: [#chaining-and-speed](references/gotchas.md#chaining-and-speed)diff --git a/bin/install.js b/bin/install.jsindex cac8c14..22927f3 100755--- a/bin/install.js+++ b/bin/install.js@@ -27,7 +27,7 @@ const { spawnSync } = require('child_process');const SKILL_NAME = 'ffmpeg-skill';const ROOT = path.resolve(__dirname, '..');-const PAYLOAD = ['SKILL.md', 'scripts', 'references', 'docs', 'mcp', 'package.json'];+const PAYLOAD = ['SKILL.md', 'scripts', 'templates', 'references', 'docs', 'mcp', 'package.json'];const args = process.argv.slice(2);const has = (flag) => args.includes(flag);diff --git a/demos/build.py b/demos/build.pyindex 39fc3b5..97e9ee0 100644--- a/demos/build.py+++ b/demos/build.py@@ -496,6 +496,27 @@ def demo_export_reels(ctx):return before, after+def demo_fit_blur(ctx):+ """16:9 to 9:16 with nothing cropped: the picture sits on a blurred, dimmed copy of itself."""+ before = FIX / "mandel.mp4"+ after = ctx.path("after.mp4")+ ctx.script("fit.py", before, "--aspect", "9:16", "--fit", "blur", "--width", "540",+ "--preset", "veryfast", "-o", after)+ return before, after+++def demo_template_tiktok(ctx):+ """One command per destination: the delivery template does the whole chain and checks it."""+ before = FIX / "motion.mp4"+ after = ctx.path("after.mp4")+ ctx.script("render.py", before, "--template", "tiktok", "--cues", FIX / "cues_en.txt",+ "--fast", "-o", after)+ if not after.exists():+ raise BuildError("render.py --template tiktok did not write %s" % after)+ ctx.note("1080x1920, captions clear of TikTok's description bar, check.py --platform tiktok passes")+ return before, after++def demo_render_project(ctx):before = FIX / "motion.mp4"after = ctx.path("after.mp4")@@ -590,6 +611,14 @@ DEMOS = ["One command produces the 1080x1920 deliverable; check.py then reports the spec row by row and exits non-zero on a FAIL.",demo_export_reels, "video", None),+ ("fit_blur", PICTURE, "16:9 to 9:16 on a blurred background",+ "Nothing is cropped and there are no black bars: the whole wide frame sits centred on a blurred, dimmed copy of itself.",+ demo_fit_blur, "video", None),++ ("template_tiktok", DELIVERY, "TikTok delivery template",+ "One command turns the master into the 1080x1920 deliverable: reframe, burned-in captions kept clear of TikTok's own UI, loudness to -14 LUFS, the tiktok export preset and check.py's platform rows.",+ demo_template_tiktok, "video", "latin"),+("render_project", PROJECTS, "Whole edit from one project file","Clips, a transition, captions and a title card described as JSON and rendered in one pass.",demo_render_project, "video", "latin"),diff --git a/docs/contract.md b/docs/contract.mdindex 2825d71..3b6f581 100644--- a/docs/contract.md+++ b/docs/contract.md@@ -264,6 +264,46 @@ downstream analysis/preview, distinct from `export.py`'s deliverypresets) resolves to `proxy` - itself a mechanical resize + re-encodewith no opinion on which asset should be proxied or what for.+## Delivery table and templates (1.14)++`scripts/_platforms.py` is the one table every delivery tool reads. Per destination+(`tiktok`, `reels`, `shorts`, `youtube`, `youtube-hdr`, `youtube-av1`, `x`, `linkedin`,+`facebook`, `podcast`, plus the `broadcast` / `custom` compliance targets):++| field | meaning |+|---|---|+| `frame` | `{w, h, aspect}` the destination is delivered at, or `null` for an audio-only one |+| `fps` | the frame rate a delivery is conformed to (`null`: leave the source's alone) |+| `spec` | `check.py`'s row values: `max_duration`, `aspects`, `min_height`, `fps_max`, `codecs`, `max_bytes`, `lufs`, `lufs_tol`, `tp`, `sdr_only` |+| `safe` | the fraction of the frame the app's own UI covers, per edge (`top`, `bottom`, `left`, `right`) |+| `caption` | caption defaults a template uses: `size` (fraction of frame height), `position`, `box`, `outline`, `animate` |+| `preset` | the `export.py` preset that writes this destination |+| `check` | the `check.py` platform a delivery is verified against |++It is an internal module (leading underscore), not a tool: the public tool count is unchanged.+`check.py`'s `SPECS`, `export.py`'s `PRESETS` (each platform preset's frame and duration cap)+and `export.py`'s `PLATFORM_OF` are all built from it, so the loudness `export.py --normalize`+targets, the frame it writes, the cap it trims at and the spec `check.py` enforces are one+value. Two presets deliberately differ from their destination's row and say so in the code:+`youtube4k` delivers to YouTube at 2160p, and no `youtube*` preset trims at YouTube's 12-hour+limit (`check.py` reports it instead). `_platforms.resolve()` is the one alias map --+`youtube-shorts`/`yt-shorts` = `shorts`, `yt` = `youtube`, `instagram`/`ig` = `reels`,+`twitter` = `x`, `fb` = `facebook` -- and `check.py --platform`, `export.py --preset`,+`caption.py`/`graphics.py`/`overlay.py --platform`, `look.py --safe` and+`render.py --template` all accept those spellings.++New in the same release, all additive: `export.py --preset tiktok|shorts|linkedin|facebook`+(real presets, not aliases of `reels`/`youtube`), `--preset youtube-hdr` (HEVC Main10 keeping+the source's HDR tags; `kind: input` on an SDR source) and `--preset youtube-av1`+(`kind: missing_tool` when the build has neither SVT-AV1 nor libaom); `caption.py --platform`+and `graphics.py --platform` / `--margin` and `overlay.py --platform` (margins from the safe+zone, an explicit `--margin`/`--position` wins); `look.py --safe NAME`; `fit.py --fit blur`; `report.py --pack`;+`graphics.py --template sticker|hook|meme`; and `render.py --template NAME INPUT`+(`--cues/--srt/--logo/--title/--brand/--chapters/--fit/-o/--write-project/--list-templates`),+which fills a `templates/<name>.json` project shipped with the skill. `--template all` or a+comma-separated list renders every named destination and writes a `<stem>_pack.md` table.+A project may now carry `"template"` (the name it was filled from) and `"frame": {"fit": ...}`.+## CapabilitiesNames: `ffmpeg`, `ffprobe`, `encoder:<name>`, `filter:<name>`, `bsf:<name>`,@@ -483,6 +523,8 @@ ffmpeg-skill contains no agent-specific code.## Where things live+- `scripts/_platforms.py`: the delivery table (destinations, specs, safe zones) read by check/export/render/caption/graphics/look+- `templates/*.json`: the shipped delivery templates `render.py --template NAME` fills- `scripts/_contract.py`: the generator (`--json`, `--static`, `doctor`)- `bin/install.js`: `ffmpeg-skill contract` and `ffmpeg-skill doctor`- `tests/test_contract.py`: schema, consistency (scripts = MCP = installer), MCP inputSchema derived from the contract (equality, determinism, drift, round trips), dry-run, JSON shapes, verification policy, real-media rundiff --git a/docs/demos.md b/docs/demos.mdindex 6ac00ea..2add2fe 100644--- a/docs/demos.md+++ b/docs/demos.md@@ -182,6 +182,16 @@ python3 scripts/join.py demos/out/fixtures/motion.mp4 demos/out/fixtures/mandel.**Look for:** The same join with fadeblack: the cut dips to black instead of blending the two pictures.+### 16:9 to 9:16 on a blurred background++++```bash+python3 scripts/fit.py demos/out/fixtures/mandel.mp4 --aspect 9:16 --fit blur --width 540 --preset veryfast -o demos/out/fit_blur_after.mp4+```++**Look for:** Nothing is cropped and there are no black bars: the whole wide frame sits centred on a blurred, dimmed copy of itself.+## Audio@@ -239,6 +249,16 @@ python3 scripts/check.py demos/out/export_reels_after.mp4 --platform reels --jso**Look for:** One command produces the 1080x1920 deliverable; check.py then reports the spec row by row and exits non-zero on a FAIL.+### TikTok delivery template++++```bash+python3 scripts/render.py demos/out/fixtures/motion.mp4 --template tiktok --cues demos/out/fixtures/cues_en.txt --fast -o demos/out/template_tiktok_after.mp4+```++**Look for:** One command turns the master into the 1080x1920 deliverable: reframe, burned-in captions kept clear of TikTok's own UI, loudness to -14 LUFS, the tiktok export preset and check.py's platform rows.+## Projects & inspectiondiff --git a/docs/demos/fit_blur.gif b/docs/demos/fit_blur.gifnew file mode 100644index 0000000..983417fBinary files /dev/null and b/docs/demos/fit_blur.gif differdiff --git a/docs/demos/template_tiktok.gif b/docs/demos/template_tiktok.gifnew file mode 100644index 0000000..5a15ea0Binary files /dev/null and b/docs/demos/template_tiktok.gif differdiff --git a/docs/roadmap.md b/docs/roadmap.mdindex b598235..0c3c53c 100644--- a/docs/roadmap.md+++ b/docs/roadmap.md@@ -17,8 +17,9 @@ 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.13.0**, evaluated by **eval 14** (`evals/results/iteration-14.json`,-76 prompts at 1.13.0). Everything from 1.14.0 down is planned.+The released version today is **1.14.0** (shipped, eval pending: eval 15 will grade it on the+76-prompt set plus the delivery prompts). The last evaluated version is **1.13.0**, closed by+**eval 14** (`evals/results/iteration-14.json`). Everything from 1.15.0 down is planned.| version | state | evidence ||---|---|---|@@ -28,7 +29,8 @@ The released version today is **1.13.0**, evaluated by **eval 14** (`evals/resul| 1.11.0 / 1.11.1 | shipped + evaluated | eval 11 at 1.11.0, eval 12 at 1.11.1 || 1.12.0 | shipped + evaluated | eval 13 at 1.12.0 (`iteration-13.json`) || 1.13.0 | shipped + evaluated | eval 14 at 1.13.0 (`iteration-14.json`) |-| 1.14.0 → 1.21.0, 2.0.0 | planned | — |+| 1.14.0 | shipped, eval pending | eval 15 (planned) |+| 1.15.0 → 1.21.0, 2.0.0 | planned | — |## 1.8.0 — one-call delivery, quieter checks, encoder flags (shipped + evaluated, eval 8)@@ -174,7 +176,7 @@ and the default MCP `tools/list` are unchanged except for additions.(drawtext) coming out wrong-shaped.-## 1.14.0 — delivery templates (planned)+## 1.14.0 — delivery templates (shipped, eval pending)Eval 14's delivery baseline: the destination is named ("make this a TikTok", 「リールにして」),the chain behind it is always the same, and four of seven producing runs paid a second fulldiff --git a/package.json b/package.jsonindex 163748a..4c79232 100644--- a/package.json+++ b/package.json@@ -29,6 +29,7 @@"files": ["bin/","scripts/",+ "templates/","mcp/","references/scripts.md","references/devices.md",diff --git a/references/gotchas.md b/references/gotchas.mdindex a08e5ce..6ec30f2 100644--- a/references/gotchas.md+++ b/references/gotchas.md@@ -158,6 +158,21 @@ visibly choppy for sports, gaming, drone pans. Keep 60 when the platform allows.trim it drops two thirds of the words. Ask which, or propose a highlight cut with`scenes.py`.+### Platform safe zones+Every vertical app draws its own UI over the delivery: TikTok covers roughly the+bottom 22 % (description and caption block), the right 14 % (like/comment/share+column) and the top 10 % (status bar and tabs); Reels 20/12/8 %; Shorts 18/12/6 %.+The feed destinations (YouTube, X, LinkedIn, Facebook) have no persistent overlay+and use the conventional 5 % title-safe border instead. A file can pass every+`check.py` row and still be unreadable because the caption sits under the+description.++The fractions live in one table (`scripts/_platforms.py`). `caption.py --platform+NAME`, `graphics.py --platform NAME` and `overlay.py --platform NAME` take their+margins from it, `render.py --template NAME` passes it to all three, and+`look.py --safe tiktok` shades the zones on a frame or contact sheet so you can+see what the app covers. An explicit `--margin` always wins.+### Dimensions and rotation`yuv420p` needs even width/height; `fit.py` and `export.py` round to even valuesautomatically. Phone footage often carries a `rotation` tag; `probe.py` reportsdiff --git a/references/scripts.md b/references/scripts.mdindex d7e5dc5..1034e48 100644--- a/references/scripts.md+++ b/references/scripts.md@@ -29,6 +29,7 @@ between tools.- silence.py — remove dead air / jump cuts- join.py — concatenate with transitions- render.py — the whole edit in one project.json+- delivery templates — one command per destination (`--template`)- scenes.py — scene changes and highlight candidates- check.py — pre-delivery compliance- batch.py — same recipe over a folder, cached@@ -76,7 +77,7 @@ re-encode, the result's `lossless_alternative` names the nearest keyframe### fit.py — target duration and/or aspect, rotate/flip```fit.py INPUT [--duration T --method speed|trim [--from-center] [--max-speed 4]]- [--aspect 16:9|9:16|1:1|4:5|W:H --fit pad|crop [--width W] [--height H] [--pad-color black] [--pad-fill color|blur [--pad-blur 20]]]+ [--aspect 16:9|9:16|1:1|4:5|W:H --fit pad|crop|blur [--width W] [--height H] [--pad-color black] [--pad-fill color|blur [--pad-blur 20]]][--rotate 90|180|270] [--flip h|v] [--fps N] [-o OUT]````speed` retimes video and audio together (pitch-preserving `atempo`); it@@ -94,7 +95,13 @@ automatically even without it.`--pad-fill blur` fills the letterbox/pillarbox bars with a blurred, scaled-to-cover copyof the frame (the look every phone editor gives landscape footage posted as a Short/Reel)instead of the solid `--pad-color`; `--pad-blur` is the blur radius. `export.py --fit pad`-takes the same two flags.+takes the same two flags. `--fit blur` (1.14) is the same fill named in one word and with the+background dimmed (`eq brightness=-0.15`) so the picture in front reads as the subject: the+whole frame is kept (nothing cropped), the borders are a blurred copy of it rather than black.+A delivery template asks for it as `"frame": {"aspect": "9:16", "fit": "blur"}`, or+`render.py --template tiktok clip.mp4 --fit blur`. The dimming is applied to SDR sources only:+an `eq` on PQ/HLG code values is not the −15 % perceptual dim it is on SDR, so an HDR source+keeps a blurred but undimmed background (and is never silently tone-mapped); `info` says so.### crop.py — crop to an exact pixel rectangle```@@ -430,6 +437,56 @@ more than two steps or the user is likely to ask for changes: edit the JSON,re-render, and the result is reproducible. `--dry-run --json` prints thecomplete 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]+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+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+unknown name is refused (`kind: input`) with the list. Output defaults to+`<input>_<template>.mp4` **next to the input** (`.m4a` for an audio-only destination such as+`podcast`) — the same rule for one template and for a pack, whose `-o` names the directory.+Alias spellings are accepted everywhere one name is: `youtube-shorts`/`yt-shorts` = `shorts`,+`yt` = `youtube`, `instagram`/`ig` = `reels`, `twitter` = `x`, `fb` = `facebook`+(`check.py --platform`, `export.py --preset`, `caption.py`/`graphics.py`/`overlay.py+--platform`, `look.py --safe`, `render.py --template`).++Under `--dry-run` a pack prints every child's planned commands and its table reads `planned`+with no size or duration: nothing was encoded, so nothing is reported as verified. `--chapters`+reaches a pack's audio destination like it does the single-template form.++Each template's frame, duration limit, loudness target and safe zones come from the one delivery+table (`scripts/_platforms.py`). Safe zones are the fraction of the frame the app's own UI covers;+the template places captions, graphics **and the `--logo` overlay** clear of them, and+`caption.py --platform`, `graphics.py --platform` and `overlay.py --platform` apply them to a+hand-built step:++| template | frame | max duration | loudness | safe top | safe bottom | safe left | safe right |+|---|---|---|---|---|---|---|---|+| `tiktok` | 1080x1920 (9:16) | 600 s | -14 LUFS / -1 dBTP | 0.10 | 0.22 | 0.05 | 0.14 |+| `reels` | 1080x1920 (9:16) | 90 s | -14 LUFS / -1 dBTP | 0.08 | 0.20 | 0.05 | 0.12 |+| `shorts` | 1080x1920 (9:16) | 180 s | -14 LUFS / -1 dBTP | 0.06 | 0.18 | 0.05 | 0.12 |+| `youtube-shorts` | 1080x1920 (9:16) | 180 s | -14 LUFS / -1 dBTP | 0.06 | 0.18 | 0.05 | 0.12 |+| `youtube` | 1920x1080 (16:9) | 43200 s | -14 LUFS / -1 dBTP | 0.05 | 0.05 | 0.05 | 0.05 |+| `x` | 1280x720 (16:9) | 140 s | -14 LUFS / -1 dBTP | 0.05 | 0.05 | 0.05 | 0.05 |+| `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 |++`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,+linkedin, facebook` (not the audio template, not the `youtube-shorts` alias) into+`<stem>_<platform>.mp4`, runs each platform's check and writes `<stem>_pack.md` with one row per+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`.+### 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]@@ -446,7 +503,7 @@ and why (energy, scene length).### check.py — pre-delivery compliance```-check.py INPUT --platform youtube|shorts|reels|tiktok|x|linkedin|broadcast|podcast|custom [--no-loudness] [--json]+check.py INPUT --platform youtube|shorts|reels|tiktok|x|linkedin|facebook|broadcast|podcast|custom [--no-loudness] [--json][--max-duration S] [--aspect 9:16] [--lufs -14] [--tp -1] [--max-mb N]```PASS/WARN/FAIL per check with the script that fixes it. Run it as the final@@ -458,7 +515,11 @@ line, not FAIL: name the platform when the file is a delivery for it.stereo, WARN above — podcast players downmix 5.1 unpredictably) and `chapters`(PASS when the container carries at least one marker, WARN `none` otherwise —write them with `metadata.py --chapters`). Neither can FAIL a delivery, and-neither appears for another platform.+neither appears for another platform. Since 1.14 the per-platform numbers (duration, aspects,+minimum height, fps, codecs, size, LUFS, true peak, SDR-only) come from the one delivery table+in `scripts/_platforms.py`, which `export.py` and the `render.py` templates read too -- so the+loudness a preset normalises to and the loudness this tool checks are the same value by+construction, not by two lists agreeing.### batch.py — same recipe over a folder, cached```@@ -486,8 +547,10 @@ Inside this skill, call the scripts directly; the server is for other hosts.### graphics.py — motion-graphics templates```-graphics.py INPUT --template lower-third|title|chapter|progress|countdown|bug [--name] [--title] [--subtitle]- [--from N] [--start S] [--end E] [--position CORNER] [--brand brand.json] [--primary RRGGBB] [--scale 1.0] [--lang XX] [-o OUT]+graphics.py INPUT --template lower-third|title|chapter|progress|countdown|bug|sticker|hook|meme+ [--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] [-o OUT]```Drawn with drawbox/drawtext/overlay — no PNG assets needed. Sizes scale withthe frame's short side; colours, font and safe margin come from `--brand`.@@ -499,6 +562,15 @@ the script fails the job). RTL shaping in drawtext depends on the ffmpeg buildthem does not); `caption.py` always shapes, because it renders through libass:`references/gotchas.md#fonts-by-script`.+All three are usable from a `render.py` project too: a `graphics[]` entry takes `text`, `top`,+`bottom`, `duration`, `margin` and `platform` alongside the older keys.+1.14 adds three social templates: `sticker` (`--text`, a filled chip that pops in at+`--position`), `hook` (`--title --duration 3`, the full-width opening card with a thin progress+bar along the top that empties as the card's time runs out) and `meme` (`--top` / `--bottom`,+upper-case white with a heavy black outline). `--platform NAME` takes each edge's margin from+that destination's safe zone (see "Delivery templates" above), so a sticker stays off TikTok's+like column; `--margin PX` sets all four edges and wins over `--platform`.+### brand.json — one file for fonts, colours, logo, margins```json{"font": "Noto Sans CJK JP", "font_file": "fonts/NotoSansCJK-Bold.ttc",@@ -555,9 +627,13 @@ seen before, and fix or report what fails.look.py INPUT [--tiles 4x3] [--width 1280] [-o sheet.png] # contact sheet with timecodeslook.py INPUT --at 2.5 [--at 7] [-o basename] # single frames -> basename_2.500s.pnglook.py BEFORE --compare AFTER --at 4 [-o cmp.png] # side-by-side frame+look.py INPUT --safe tiktok [--at 3] # shade what the app's UI covers```Outputs PNG. View it with the Read tool (or any image viewer) and judge the-frame like an editor would. Use `--compare` to show before/after to the user.+frame like an editor would. Use `--compare` to show before/after to the user. `--safe NAME` (1.14) shades the zones that+destination's own UI covers -- TikTok's description block and like column, the Reels/Shorts+chrome -- on the sheet or the frame, so "is the caption readable" can be answered about the app+rather than about the file.### caption.py — subtitles (static, animated, karaoke)```@@ -635,8 +711,11 @@ stream selection would have picked.```overlay.py INPUT --image PNG [--scale W | --scale-percent P] | --text "..." [--font-file F.ttf] [--font-size N] [--box]| --video CLIP [--chromakey COLOR [--chromakey-similarity 0-1] [--chromakey-blend 0-1]]- [--position top-right|bottom-left|center|X,Y] [--margin N] [--start T] [--end T] [--fade S] [--opacity 0-1] [-o OUT]+ [--position top-right|bottom-left|center|X,Y] [--margin N] [--platform NAME] [--start T] [--end T] [--fade S] [--opacity 0-1] [-o OUT]```+`--platform NAME` (1.14) takes each edge's margin from that destination's safe zone+(`scripts/_platforms.py`), so a template's top-left logo clears TikTok's status bar instead of+sitting 24 px into it; an explicit `--margin` (or a brand `safe_margin`) wins.Alpha in PNGs is respected. Fades apply to the overlay only; the video keepsplaying. `--video` composites a second video as a picture-in-picture layer(same position/scale/opacity/time-range knobs as `--image`); only the main@@ -772,7 +851,8 @@ integrated loudness ended more than 1 LU from the target because of it.### export.py — delivery presets```-export.py INPUT --preset youtube|youtube4k|reels|x|prores|h265|gif [--fit pad|crop] [--no-scale] [--allow-long] [--crf N] [--normalize] [-o OUT]+export.py INPUT --preset youtube|youtube4k|reels|tiktok|shorts|linkedin|facebook|x|youtube-hdr|youtube-av1|prores|h265|gif|copy+ [--fit pad|crop] [--no-scale] [--allow-long] [--crf N] [--normalize] [-o OUT]export.py --list```Scales into the preset frame (pad by default), tags BT.709, sets `+faststart`,@@ -784,6 +864,15 @@ that fixes it -- or pass `--normalize`, which runs that call on the writtenfile itself (audio re-encoded, video copied; `loudness.normalized: true`) so aplatform export is one command instead of export, loudness, export again.+Since 1.14 each social destination is its own preset rather than an alias: `tiktok`+(1080x1920, max 600 s), `shorts` (1080x1920, max 180 s), `reels` (1080x1920, max 90 s),+`linkedin` (1080x1080), `facebook` (1920x1080), each with its platform's loudness spec from the+same table `check.py` reads, so `--normalize` and the check agree. `youtube-hdr` writes HEVC+Main10 keeping the source's own HDR10/HLG tags and refuses an SDR source (`kind: input`, hinting+at `--preset youtube`) rather than labelling SDR as HDR; `youtube-av1` encodes AV1 with+SVT-AV1 (libaom fallback) and refuses with `kind: missing_tool` on an ffmpeg built with+neither.+### proxy.py — low-bitrate proxy for analysis/preview```proxy.py INPUT [--width W | --scale F] [--crf N] [--fps N] [--no-audio] [-o OUT]diff --git a/scripts/_common.py b/scripts/_common.pyindex 8e5b867..9302509 100755--- a/scripts/_common.py+++ b/scripts/_common.py@@ -140,7 +140,7 @@ def drawtext_boxborderw(vertical: int, horizontal: int) -> str:return str(max(vertical, horizontal))-def pad_filters(out_w: int, out_h: int, fill: str, color: str, blur: int) -> str:+def pad_filters(out_w: int, out_h: int, fill: str, color: str, blur: int, darken: float = 0.0) -> str:"""The letterbox/pillarbox step shared by fit.py and export.py, as one -vf segment.fill="color": scale to fit, then pad with a solid colour (the historical behaviour).@@ -148,14 +148,17 @@ def pad_filters(out_w: int, out_h: int, fill: str, color: str, blur: int) -> strphone editor's "make it vertical" does with landscape footage (#139). Built as a smallgraph inside the -vf chain: split, one branch scaled to cover and cropped to the framethen boxblur'ed, the other scaled to fit, overlaid centred. Only `filter:boxblur` is- needed beyond the usual scale/pad set, and that is already required by redact.py."""+ needed beyond the usual scale/pad set, and that is already required by redact.py.+ `darken` > 0 also dims that background copy by that much brightness (eq), so the picture in+ front reads as the subject instead of competing with a bright blurred copy of itself --+ what `fit.py --fit blur` uses (1.14)."""if fill == "blur":# boxblur rejects a radius larger than half the smaller dimension ("radius 20, must be# <= 8" on a 16 px target); clamp instead of failing an otherwise valid requestradius = max(1, min(int(blur), max(1, min(out_w, out_h) // 2 - 1)))return (f"split[__fitfg][__fitbg];"f"[__fitbg]scale={out_w}:{out_h}:force_original_aspect_ratio=increase,crop={out_w}:{out_h},"- f"boxblur={radius}:2[__fitbgb];"+ f"boxblur={radius}:2" + (f",eq=brightness=-{darken:g}" if darken else "") + "[__fitbgb];"f"[__fitfg]scale={out_w}:{out_h}:force_original_aspect_ratio=decrease[__fitfgs];"f"[__fitbgb][__fitfgs]overlay=(W-w)/2:(H-h)/2:format=auto")return f"scale={out_w}:{out_h}:force_original_aspect_ratio=decrease,pad={out_w}:{out_h}:(ow-iw)/2:(oh-ih)/2:color={color}"diff --git a/scripts/_contract.py b/scripts/_contract.pyindex 3e0f871..3b51150 100644--- a/scripts/_contract.py+++ b/scripts/_contract.py@@ -79,7 +79,8 @@ TOOL_META: Dict[str, Dict[str, Any]] = {video_required=False, audio_only=True, visual=False, verify=["probe"], produces_artifact=True, idempotency="content_equivalent", deterministic=True),"fit": dict(role="execution", inputs=["video asset"], outputs=["video artifact at the requested duration / aspect / fps"],required=FF + [X264, AAC], optional=[HDR_X265, {"capability": "filter:minterpolate", "when": "--smooth interpolate"},- {"capability": "filter:boxblur", "when": "--pad-fill blur"}],+ {"capability": "filter:boxblur", "when": "--pad-fill blur or --fit blur"},+ {"capability": "filter:eq", "when": "--fit blur (the background copy is dimmed)"}],video_required=True, audio_only=False, visual=True, verify=["probe", "look"], produces_artifact=True, idempotency="content_equivalent", deterministic=True),"crop": dict(role="execution", inputs=["video asset"], outputs=["video artifact cropped to the given pixel rectangle"],required=FF + [X264, AAC], optional=[HDR_X265],@@ -187,7 +188,8 @@ TOOL_META: Dict[str, Dict[str, Any]] = {"export": dict(role="execution", inputs=["video asset"], outputs=["delivery artifact in the preset's format"],required=FF, optional=[{"capability": X264, "when": "preset youtube / youtube4k / reels / x"}, {"capability": AAC, "when": "preset youtube / youtube4k / reels / x / h265 (prores uses pcm_s16le, copy stream-copies, gif has no audio)"},{"capability": X265, "when": "preset h265"}, {"capability": "encoder:prores_ks", "when": "preset prores"},- {"capability": "filter:palettegen", "when": "preset gif"}, {"capability": "encoder:gif", "when": "preset gif"}, {"capability": "filter:boxblur", "when": "--pad-fill blur"},+ {"capability": "filter:palettegen", "when": "preset gif"}, {"capability": "encoder:gif", "when": "preset gif"}, {"capability": "filter:boxblur", "when": "--pad-fill blur or --fit blur"},+ {"capability": "filter:eq", "when": "--fit blur (the background copy is dimmed)"},{"capability": "filter:loudnorm", "when": "preset youtube / youtube4k / reels / x with audio: the written file is measured against the platform's loudness target (result `loudness`)"}],video_required=True, audio_only=False, visual=False, verify=["probe", "check"], produces_artifact=True, idempotency="content_equivalent", deterministic=True),"check": dict(role="verification", inputs=["media artifact"], outputs=["compliance rows JSON on stdout (no file)"],@@ -197,10 +199,11 @@ TOOL_META: Dict[str, Dict[str, Any]] = {required=FF + ["filter:scdet"], optional=[{"capability": "filter:drawtext", "when": "--sheet"}, {"capability": "filter:tile", "when": "--sheet"}],video_required=True, audio_only=False, visual=False, verify=[], produces_artifact=True, idempotency="bit_exact", deterministic=True),"look": dict(role="verification", inputs=["video artifact"], outputs=["PNG contact sheet / frames / side-by-side"],- required=FF + ["filter:tile"], optional=[{"capability": "filter:drawtext", "when": "timecode stamps (default; --no-timecode to skip)"}, {"capability": "filter:zscale", "when": "HDR source"}, {"capability": "filter:tonemap", "when": "HDR source"}],+ required=FF + ["filter:tile"], optional=[{"capability": "filter:drawtext", "when": "timecode stamps (default; --no-timecode to skip)"},+ {"capability": "filter:drawbox", "when": "--safe NAME (the platform's occluded zones)"}, {"capability": "filter:zscale", "when": "HDR source"}, {"capability": "filter:tonemap", "when": "HDR source"}],video_required=True, audio_only=False, visual=False, verify=[], produces_artifact=True, idempotency="bit_exact", deterministic=True),- "render": dict(role="execution", inputs=["project.json (clips, transitions, captions, overlays, audio, loudness, export, check)"], outputs=["final video artifact", "work directory of stage outputs (--keep / --work)"],- required=FF, optional=[{"capability": "delegated", "when": "each stage runs cut / join / fit / caption / overlay / audio / loudness / export / check with their capabilities"}],+ "render": dict(role="execution", inputs=["project.json (clips, transitions, captions, overlays, audio, loudness, export, check)", "media asset plus --template NAME (a shipped delivery template)"], outputs=["final video artifact", "one artifact per destination plus a pack table (--template all)", "work directory of stage outputs (--keep / --work)"],+ required=FF, optional=[{"capability": "delegated", "when": "each stage (and each destination of --template) runs cut / join / fit / caption / graphics / overlay / audio / loudness / export / check with their capabilities"}],video_required=True, audio_only=False, visual=True, verify=["probe", "check", "look"], produces_artifact=True, idempotency="content_equivalent", deterministic=True),"batch": dict(role="execution", inputs=["folder of media", "batch.json recipe (steps or a render project)"], outputs=["one artifact per input file in the recipe's output_dir", "content-hash cache"],required=FF, optional=[{"capability": "delegated", "when": "each recipe step runs the named script with its capabilities"}],diff --git a/scripts/_platforms.py b/scripts/_platforms.pynew file mode 100644index 0000000..dc15c9d--- /dev/null+++ b/scripts/_platforms.py@@ -0,0 +1,251 @@+#!/usr/bin/env python3+"""One table per delivery destination (internal module, not a tool).++Before 1.14 the same destination was described three times: check.py held the+compliance spec (duration, aspect, codecs, loudness), export.py held the frame and+encoder settings, and nothing at all held the part of the frame the app's own UI+covers. A TikTok export therefore passed every check while its captions sat under+the description bar. This module is the single table the delivery tools read:++ PLATFORMS[name] = {+ "frame": {"w", "h", "aspect"} or None (audio-only destinations),+ "fps": the frame rate a delivery is conformed to (None = leave alone),+ "spec": check.py's compliance row values (max_duration, aspects,+ min_height, fps_max, codecs, max_bytes, lufs, lufs_tol, tp,+ sdr_only) -- the keys check.py's SPECS has always had,+ "safe": the fraction of the frame each edge's UI covers+ (top/bottom/left/right, 0..1) -- nothing readable goes there,+ "caption": the caption defaults a template uses (size as a fraction of the+ frame height, position, box, outline, animate),+ "preset": the export.py preset that writes this destination's file,+ "check": the check.py platform name a delivery is verified against.+ }++Read by check.py (SPECS), export.py (PRESETS/PLATFORM_OF), render.py (templates),+caption.py and graphics.py (--platform margins) and look.py (--safe).++Safe zones are the app's own overlay, measured from each platform's published+design guidance: TikTok's caption/description block and the like/comment column,+Instagram's Reels UI, the Shorts player. They are deliberately generous -- a+caption 2 % too high is readable, a caption under the share button is not. The+feed destinations (YouTube, X, LinkedIn, Facebook) have no persistent overlay, so+they carry the conventional 5 % title-safe border instead.++ASS note: caption.py's --size and --margin are in the 288-line ASS script grid, so+a fraction of the frame height is that fraction * 288 (ass_units() below); the+burn scales it back to the real frame. graphics.py and look.py work in pixels.+"""+from typing import Any, Dict, List, Optional++ASS_SCRIPT_HEIGHT = 288 # caption.py's --size/--margin reference grid+++def ass_units(fraction: float) -> int:+ """A fraction of the frame height as a caption.py --size / --margin value."""+ return int(round(fraction * ASS_SCRIPT_HEIGHT))+++# The edges a feed destination reserves: no app chrome, just the conventional title-safe border.+_SAFE_5 = {"top": 0.05, "bottom": 0.05, "left": 0.05, "right": 0.05}+_NO_SAFE = {"top": 0.0, "bottom": 0.0, "left": 0.0, "right": 0.0}++# caption defaults: size is a fraction of the frame height (0.0833 = the 24 that every+# vertical job in this repo has used since 1.2), position/box/outline/animate as the+# caption.py flags of the same name.+_CAP_VERTICAL = {"size": 0.0833, "position": "bottom", "box": False, "outline": 2, "animate": "pop"}+_CAP_WIDE = {"size": 0.0694, "position": "bottom", "box": False, "outline": 2, "animate": "none"}++PLATFORMS: Dict[str, Dict[str, Any]] = {+ "tiktok": {+ "title": "TikTok",+ "frame": {"w": 1080, "h": 1920, "aspect": "9:16"},+ "fps": 30,+ "spec": {"max_duration": 600, "aspects": ["9:16", "1:1"], "min_height": 1080, "fps_max": 60,+ "codecs": ["h264", "hevc"], "max_bytes": 4 * 1024 ** 3,+ "lufs": -14, "lufs_tol": 2.0, "tp": -1.0, "sdr_only": True},+ # the description/caption block along the bottom, the like/comment/share column on the+ # right, the status bar and the "Following | For You" tabs at the top+ "safe": {"top": 0.10, "bottom": 0.22, "left": 0.05, "right": 0.14},+ "caption": _CAP_VERTICAL,+ "preset": "tiktok", "check": "tiktok",+ },+ "reels": {+ "title": "Instagram Reels",+ "frame": {"w": 1080, "h": 1920, "aspect": "9:16"},+ "fps": 30,+ "spec": {"max_duration": 90, "aspects": ["9:16", "4:5", "1:1"], "min_height": 1080, "fps_max": 60,+ "codecs": ["h264", "hevc"], "max_bytes": 4 * 1024 ** 3,+ "lufs": -14, "lufs_tol": 2.0, "tp": -1.0, "sdr_only": True},+ "safe": {"top": 0.08, "bottom": 0.20, "left": 0.05, "right": 0.12},+ "caption": _CAP_VERTICAL,+ "preset": "reels", "check": "reels",+ },+ "shorts": {+ "title": "YouTube Shorts",+ "frame": {"w": 1080, "h": 1920, "aspect": "9:16"},+ "fps": 30,+ "spec": {"max_duration": 180, "aspects": ["9:16", "1:1"], "min_height": 1080, "fps_max": 60,+ "codecs": ["h264", "hevc"], "max_bytes": 256 * 1024 ** 3,+ "lufs": -14, "lufs_tol": 2.0, "tp": -1.0, "sdr_only": False},+ "safe": {"top": 0.06, "bottom": 0.18, "left": 0.05, "right": 0.12},+ "caption": _CAP_VERTICAL,+ "preset": "shorts", "check": "shorts",+ },+ "youtube": {+ "title": "YouTube",+ "frame": {"w": 1920, "h": 1080, "aspect": "16:9"},+ "fps": None,+ "spec": {"max_duration": 12 * 3600, "aspects": ["16:9", "9:16", "1:1", "4:3"], "min_height": 720, "fps_max": 60,+ "codecs": ["h264", "hevc", "prores", "av1", "vp9"], "max_bytes": 256 * 1024 ** 3,+ "lufs": -14, "lufs_tol": 2.0, "tp": -1.0, "sdr_only": False},+ "safe": _SAFE_5,+ "caption": _CAP_WIDE,+ "preset": "youtube", "check": "youtube",+ },+ "youtube-hdr": {+ "title": "YouTube (HDR10)",+ "frame": {"w": 1920, "h": 1080, "aspect": "16:9"},+ "fps": None,+ "spec": dict({"max_duration": 12 * 3600, "aspects": ["16:9", "9:16", "1:1", "4:3"], "min_height": 720, "fps_max": 60,+ "codecs": ["h264", "hevc", "prores", "av1", "vp9"], "max_bytes": 256 * 1024 ** 3,+ "lufs": -14, "lufs_tol": 2.0, "tp": -1.0, "sdr_only": False}),+ "safe": _SAFE_5,+ "caption": _CAP_WIDE,+ "preset": "youtube-hdr", "check": "youtube",+ },+ "youtube-av1": {+ "title": "YouTube (AV1)",+ "frame": {"w": 1920, "h": 1080, "aspect": "16:9"},+ "fps": None,+ "spec": dict({"max_duration": 12 * 3600, "aspects": ["16:9", "9:16", "1:1", "4:3"], "min_height": 720, "fps_max": 60,+ "codecs": ["h264", "hevc", "prores", "av1", "vp9"], "max_bytes": 256 * 1024 ** 3,+ "lufs": -14, "lufs_tol": 2.0, "tp": -1.0, "sdr_only": False}),+ "safe": _SAFE_5,+ "caption": _CAP_WIDE,+ "preset": "youtube-av1", "check": "youtube",+ },+ "x": {+ "title": "X (Twitter)",+ "frame": {"w": 1280, "h": 720, "aspect": "16:9"},+ "fps": 30,+ "spec": {"max_duration": 140, "aspects": ["16:9", "1:1", "9:16"], "min_height": 720, "fps_max": 60,+ "codecs": ["h264"], "max_bytes": 512 * 1024 ** 2,+ "lufs": -14, "lufs_tol": 3.0, "tp": -1.0, "sdr_only": True},+ "safe": _SAFE_5,+ "caption": _CAP_WIDE,+ "preset": "x", "check": "x",+ },+ "linkedin": {+ "title": "LinkedIn",+ "frame": {"w": 1080, "h": 1080, "aspect": "1:1"},+ "fps": 30,+ "spec": {"max_duration": 600, "aspects": ["16:9", "1:1", "9:16", "4:5"], "min_height": 720, "fps_max": 60,+ "codecs": ["h264"], "max_bytes": 5 * 1024 ** 3,+ "lufs": -14, "lufs_tol": 3.0, "tp": -1.0, "sdr_only": True},+ "safe": _SAFE_5,+ "caption": _CAP_WIDE,+ "preset": "linkedin", "check": "linkedin",+ },+ "facebook": {+ "title": "Facebook",+ "frame": {"w": 1920, "h": 1080, "aspect": "16:9"},+ "fps": 30,+ "spec": {"max_duration": 240 * 60, "aspects": ["16:9", "1:1", "9:16", "4:5"], "min_height": 720, "fps_max": 60,+ "codecs": ["h264", "hevc"], "max_bytes": 4 * 1024 ** 3,+ "lufs": -14, "lufs_tol": 3.0, "tp": -1.0, "sdr_only": True},+ "safe": _SAFE_5,+ "caption": _CAP_WIDE,+ "preset": "facebook", "check": "facebook",+ },+ "podcast": {+ "title": "Podcast (audio)",+ "frame": None,+ "fps": None,+ "spec": {"max_duration": None, "aspects": None, "min_height": 0, "fps_max": None,+ "codecs": None, "max_bytes": None,+ "lufs": -16, "lufs_tol": 1.0, "tp": -1.0, "sdr_only": False},+ "safe": _NO_SAFE,+ "caption": _CAP_WIDE,+ "preset": None, "check": "podcast",+ },+ # Not destinations an app owns, but compliance targets check.py has always had.+ "broadcast": {+ "title": "Broadcast (EBU R128)",+ "frame": {"w": 1920, "h": 1080, "aspect": "16:9"},+ "fps": None,+ "spec": {"max_duration": None, "aspects": ["16:9"], "min_height": 1080, "fps_max": 60,+ "codecs": ["prores", "dnxhd", "h264", "hevc", "mpeg2video"], "max_bytes": None,+ "lufs": -23, "lufs_tol": 1.0, "tp": -1.0, "sdr_only": False},+ "safe": _SAFE_5,+ "caption": _CAP_WIDE,+ "preset": "prores", "check": "broadcast",+ },+ "custom": {+ "title": "Custom",+ "frame": None,+ "fps": None,+ "spec": {"max_duration": None, "aspects": None, "min_height": 0, "fps_max": None,+ "codecs": None, "max_bytes": None,+ "lufs": None, "lufs_tol": 2.0, "tp": -1.0, "sdr_only": False},+ "safe": _NO_SAFE,+ "caption": _CAP_WIDE,+ "preset": None, "check": "custom",+ },+}++# The canonical destination names.+PLATFORM_NAMES: List[str] = sorted(PLATFORMS)+# The spellings people actually write for those destinations. resolve() maps them onto the+# canonical name, and every tool's --platform/--safe/--preset accepts both, so+# `--platform youtube-shorts` and `--platform shorts` are the same request everywhere.+ALIASES: Dict[str, str] = {"youtube-shorts": "shorts", "yt-shorts": "shorts", "yt": "youtube",+ "instagram": "reels", "ig": "reels", "twitter": "x", "fb": "facebook"}+# One vocabulary for the word "platform": check.py, caption.py, graphics.py and look.py all+# offer this list (review 12 found three different ones). It is the compliance targets -- the+# destinations a delivery is checked against -- plus every alias; youtube-hdr and youtube-av1+# are export presets of the youtube target, not separate destinations, so they are not in it.+PLATFORM_CHOICES: List[str] = sorted({n for n in PLATFORMS if PLATFORMS[n]["check"] == n} | set(ALIASES))+++def has_frame(name: str) -> bool:+ """True when this destination has a frame, and therefore a safe zone to place text inside."""+ return bool(PLATFORMS.get(resolve(name) or "", {}).get("frame"))+++def spec_of(name: str) -> Dict[str, Any]:+ """check.py's compliance row values for a destination."""+ return dict(PLATFORMS[name]["spec"])+++def safe_of(name: str) -> Dict[str, float]:+ return dict(PLATFORMS[name]["safe"])+++def loudness_of(name: str) -> Dict[str, float]:+ s = PLATFORMS[name]["spec"]+ return {"lufs": s["lufs"], "lufs_tol": s["lufs_tol"], "tp": s["tp"]}+++def safe_margins_px(name: str, width: int, height: int) -> Dict[str, int]:+ """The safe zone in pixels for a frame of this size, as whole pixels per edge."""+ s = PLATFORMS[name]["safe"]+ return {"top": int(round(s["top"] * height)), "bottom": int(round(s["bottom"] * height)),+ "left": int(round(s["left"] * width)), "right": int(round(s["right"] * width))}+++def caption_defaults(name: str) -> Dict[str, Any]:+ """caption.py flag values for this destination: --size/--margin in ASS units."""+ cap = dict(PLATFORMS[name]["caption"])+ safe = PLATFORMS[name]["safe"]+ edge = safe["top"] if cap["position"].startswith("top") else safe["bottom"]+ cap["size"] = ass_units(cap["size"])+ cap["margin"] = ass_units(edge)+ return cap+++def resolve(name: Optional[str]) -> Optional[str]:+ """Accept the spellings people write for a destination ('youtube-shorts', 'ig')."""+ if not name:+ return None+ key = str(name).strip().lower()+ return ALIASES.get(key, key)diff --git a/scripts/caption.py b/scripts/caption.pyindex a071f36..0179767 100755--- a/scripts/caption.py+++ b/scripts/caption.py@@ -40,6 +40,7 @@ import unicodedatafrom pathlib import Pathfrom typing import List, Optional, Tuple+from _platforms import PLATFORMS, PLATFORM_CHOICES, ass_units, resolve as resolve_platformfrom _common import 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_secsALIGN = {"bottom": 2, "top": 8, "center": 5, "bottom-left": 1, "bottom-right": 3, "top-left": 7, "top-right": 9}@@ -759,7 +760,10 @@ def main() -> int:sty.add_argument("--shadow", type=float, default=0.0, help="shadow depth (default 0)")sty.add_argument("--bold", action="store_true")sty.add_argument("--position", choices=sorted(ALIGN), default=None, help="on-screen placement (default bottom)")- sty.add_argument("--margin", type=int, default=30, help="vertical margin from the edge (default 30)")+ sty.add_argument("--margin", type=int, default=None, help="vertical margin from the edge in ASS units (default 30, or the --platform safe zone)")+ sty.add_argument("--platform", choices=PLATFORM_CHOICES, default=None,+ help="keep the captions out of this destination's UI: the margin becomes the platform's safe "+ "zone (TikTok's description bar, the Reels/Shorts chrome). An explicit --margin/--position wins")sty.add_argument("--box", action="store_true", help="draw an opaque box behind text instead of an outline")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)")@@ -792,6 +796,18 @@ def main() -> int:args.outline_color = color_hex(args.outline_color or bc.get("outline", "000000"))args.outline = args.outline if args.outline is not None else (float(bcap.get("outline", 2)) if args.brand else 2.0)args.position = args.position or (bcap.get("position", "bottom") if args.brand else "bottom")+ # --platform: the margin is the fraction of the frame that platform's own UI covers+ # (scripts/_platforms.py). An explicit --margin is the more specific statement and wins;+ # without either, the historical default 30 is unchanged.+ # every tool resolves the spellings people write ('youtube-shorts' is 'shorts') in one place+ args.platform = resolve_platform(args.platform)+ if args.margin is None and args.platform and PLATFORMS[args.platform].get("frame"):+ edge = PLATFORMS[args.platform]["safe"]["top" if args.position.startswith("top") else "bottom"]+ args.margin = ass_units(edge)+ info(f"--platform {args.platform}: caption margin {args.margin} ASS units ({edge * 100:.0f}% of the frame height, "+ f"clear of the app's own UI)")+ if args.margin is None:+ args.margin = 30# a brand's caption.animate is a burn-in default; over --mode mux (soft subtitles) it used# to be applied anyway and then refused as "animation is burn only" -- ignore it thereargs.animate = args.animate or (bcap.get("animate", "none") if args.brand and args.mode != "mux" else "none")diff --git a/scripts/check.py b/scripts/check.pyindex 008a8b0..c3187f1 100755--- a/scripts/check.py+++ b/scripts/check.py@@ -10,7 +10,8 @@ row's `fix` is the command that resolves it; a few of the less obvious FAILsnot a restatement of the spec value -- for a caller reporting this to someonewho doesn't already know why the spec says what it says.-Platforms: youtube, shorts, reels, tiktok, x, linkedin, broadcast (EBU R128), podcast, custom+Platforms: youtube, shorts, reels, tiktok, x, linkedin, facebook, broadcast (EBU R128),+podcast, custom -- one table, shared with export.py and the render.py templatesExamples:python3 check.py final.mp4 --platform youtube@@ -25,19 +26,15 @@ import sysfrom fractions import Fractionfrom typing import Any, Dict, List+from _platforms import PLATFORMS, PLATFORM_CHOICES, spec_of, resolve as resolve_platformfrom _common import STATE, add_common, apply_common, die, emit, info, probe, require_tool, run, run_analysis, dry_run_input_pending-SPECS: Dict[str, Dict[str, Any]] = {- "youtube": {"max_duration": 12 * 3600, "aspects": ["16:9", "9:16", "1:1", "4:3"], "min_height": 720, "fps_max": 60, "codecs": ["h264", "hevc", "prores", "av1", "vp9"], "max_bytes": 256 * 1024 ** 3, "lufs": -14, "lufs_tol": 2.0, "tp": -1.0, "sdr_only": False},- "shorts": {"max_duration": 180, "aspects": ["9:16", "1:1"], "min_height": 1080, "fps_max": 60, "codecs": ["h264", "hevc"], "max_bytes": 256 * 1024 ** 3, "lufs": -14, "lufs_tol": 2.0, "tp": -1.0, "sdr_only": False},- "reels": {"max_duration": 90, "aspects": ["9:16", "4:5", "1:1"], "min_height": 1080, "fps_max": 60, "codecs": ["h264", "hevc"], "max_bytes": 4 * 1024 ** 3, "lufs": -14, "lufs_tol": 2.0, "tp": -1.0, "sdr_only": True},- "tiktok": {"max_duration": 600, "aspects": ["9:16", "1:1"], "min_height": 1080, "fps_max": 60, "codecs": ["h264", "hevc"], "max_bytes": 4 * 1024 ** 3, "lufs": -14, "lufs_tol": 2.0, "tp": -1.0, "sdr_only": True},- "x": {"max_duration": 140, "aspects": ["16:9", "1:1", "9:16"], "min_height": 720, "fps_max": 60, "codecs": ["h264"], "max_bytes": 512 * 1024 ** 2, "lufs": -14, "lufs_tol": 3.0, "tp": -1.0, "sdr_only": True},- "linkedin": {"max_duration": 600, "aspects": ["16:9", "1:1", "9:16", "4:5"], "min_height": 720, "fps_max": 60, "codecs": ["h264"], "max_bytes": 5 * 1024 ** 3, "lufs": -14, "lufs_tol": 3.0, "tp": -1.0, "sdr_only": True},- "broadcast": {"max_duration": None, "aspects": ["16:9"], "min_height": 1080, "fps_max": 60, "codecs": ["prores", "dnxhd", "h264", "hevc", "mpeg2video"], "max_bytes": None, "lufs": -23, "lufs_tol": 1.0, "tp": -1.0, "sdr_only": False},- "podcast": {"max_duration": None, "aspects": None, "min_height": 0, "fps_max": None, "codecs": None, "max_bytes": None, "lufs": -16, "lufs_tol": 1.0, "tp": -1.0, "sdr_only": False},- "custom": {"max_duration": None, "aspects": None, "min_height": 0, "fps_max": None, "codecs": None, "max_bytes": None, "lufs": None, "lufs_tol": 2.0, "tp": -1.0, "sdr_only": False},-}+# The one delivery table (scripts/_platforms.py): check.py's rows, export.py's presets and the+# render.py templates all read it, so a platform's loudness spec is stated once. Only the+# destinations that are compliance targets appear here; youtube-hdr / youtube-av1 are export+# presets of the youtube target, not separate specs.+SPECS: Dict[str, Dict[str, Any]] = {name: spec_of(name) for name in sorted(PLATFORMS)+ if PLATFORMS[name]["check"] == name}def measure_loudness(path: str) -> Dict[str, float]:@@ -66,7 +63,7 @@ def aspect_name(w: int, h: int) -> str:def main() -> int:ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)ap.add_argument("input")- ap.add_argument("--platform", choices=sorted(SPECS), default=None, help="delivery spec to check against (default: youtube, with judgement rows reported as WARN because no platform was named)")+ ap.add_argument("--platform", choices=PLATFORM_CHOICES, default=None, help="delivery spec to check against (default: youtube, with judgement rows reported as WARN because no platform was named)")ap.add_argument("--max-duration", type=float, help="override max duration in seconds")ap.add_argument("--aspect", help="override allowed aspect (e.g. 9:16 or 16:9,1:1)")ap.add_argument("--lufs", type=float, help="override loudness target")@@ -81,7 +78,7 @@ def main() -> int:# spent a paragraph explaining why they left them alone. Without a named platform the# judgement rows are advisory: WARN, not FAIL, and not counted as failed.named = args.platform is not None- args.platform = args.platform or "youtube"+ args.platform = resolve_platform(args.platform) or "youtube"spec = dict(SPECS[args.platform])if args.max_duration is not None:spec["max_duration"] = args.max_duration@@ -134,10 +131,10 @@ def main() -> int:row("fps", "PASS" if fps <= spec["fps_max"] + 0.01 else "FAIL", f"{fps:g}", f"<= {spec['fps_max']}", "fit.py --fps 30 (drops half the frames of 60 fps motion; fine for talking heads, visible on sports/gaming)")row("vfr", "PASS" if not v.get("variable_frame_rate_suspected") else "WARN", "variable" if v.get("variable_frame_rate_suspected") else "constant", "constant", "fit.py --fps N (any re-encode conforms it)")if spec["codecs"]:- row("video codec", "PASS" if v.get("codec") in spec["codecs"] else "FAIL", v.get("codec"), "/".join(spec["codecs"]), "export.py --preset " + args.platform.replace("shorts", "reels").replace("tiktok", "reels").replace("linkedin", "youtube").replace("broadcast", "prores"),+ row("video codec", "PASS" if v.get("codec") in spec["codecs"] else "FAIL", v.get("codec"), "/".join(spec["codecs"]), "export.py --preset " + (PLATFORMS[args.platform].get("preset") or "youtube"),reason="the platform's player may refuse to decode this codec at all, not just look worse")pf = v.get("pix_fmt") or ""- if args.platform in ("reels", "tiktok", "x", "linkedin"):+ if args.platform in ("reels", "tiktok", "x", "linkedin", "facebook"):row("pixel format", "PASS" if pf == "yuv420p" else "FAIL", pf, "yuv420p (8-bit 4:2:0)", "export.py preset re-encodes to yuv420p",reason="QuickTime and iOS commonly reject video that isn't 8-bit 4:2:0")if spec["sdr_only"] and v.get("hdr"):diff --git a/scripts/export.py b/scripts/export.pyindex 53edab6..12bb744 100755--- a/scripts/export.py+++ b/scripts/export.py@@ -6,7 +6,13 @@ sets BT.709 tags, and picks sensible codecs/bitrates.Presets:youtube 1920x1080 H.264 CRF 18 high profile, AAC 192k, 48 kHz, faststartyoutube4k 3840x2160 H.264 CRF 18, AAC 192k- reels 1080x1920 9:16 H.264 CRF 20, AAC 128k, max 90 s (also Shorts/TikTok)+ reels 1080x1920 9:16 H.264 CRF 20, AAC 128k, max 90 s (Instagram Reels)+ tiktok 1080x1920 9:16 H.264 CRF 20, AAC 128k, max 600 s+ shorts 1080x1920 9:16 H.264 CRF 20, AAC 128k, max 180 s (YouTube Shorts)+ linkedin 1080x1080 1:1 H.264 CRF 20, AAC 128k, max 600 s+ facebook 1920x1080 16:9 H.264 CRF 21, AAC 128k+ youtube-hdr HEVC Main10 keeping the source's HDR10/HLG tags (refuses an SDR source)+ youtube-av1 1080p AV1 (libsvtav1, libaom fallback); missing_tool when neither is builtx 1280x720 H.264 CRF 22, AAC 128k, max 140 s (Twitter/X)prores ProRes 422 HQ .mov, PCM 16-bit audio (editing master)h265 HEVC CRF 24 (libx265) with hvc1 tag for Apple compatibility@@ -29,31 +35,82 @@ import sysfrom pathlib import Pathfrom typing import Dict, List-from _common import STATE, add_common, apply_common, bt709_tag_args, child_args, emit, cfr_args, default_output, die, ffmpeg_base, info, probe, run, run_tool, validate_color, pad_filters, add_pad_fill_args, fmt_secs+from _common import STATE, add_common, apply_common, bt709_tag_args, child_args, emit, cfr_args, default_output, die, encoder_args, ffmpeg_base, info, probe, run, run_tool, validate_color, pad_filters, add_pad_fill_args, fmt_secsfrom check import SPECS as PLATFORMS, measure_loudness+from _platforms import ALIASES as _ALIASES, PLATFORMS as PLATFORM_TABLE, resolve as resolve_platform+# Frame and duration limit come from the one platform table (scripts/_platforms.py) rather than+# from a literal restated here: before 1.14 they were typed twice and the facebook preset had+# already drifted (no duration cap against the table's 14400 s).+def _from_table(dest: str, **over) -> Dict:+ """A preset's w/h/max read from PLATFORMS[dest], with the encoder settings given here.++ `over` is for the two presets that are deliberately not the destination's own frame or cap:+ `youtube4k` delivers to YouTube at 2160p, and neither youtube preset trims at YouTube's+ 12-hour limit (check.py reports it; export.py has never cut a long upload and does not start).+ """+ frame = PLATFORM_TABLE[dest]["frame"] or {}+ spec = PLATFORM_TABLE[dest]["spec"]+ max_duration = spec.get("max_duration")+ out = {"w": frame.get("w"), "h": frame.get("h"),+ "max": float(max_duration) if max_duration is not None else None}+ out.update(over)+ return out+++_H264_HIGH = ["-c:v", "libx264", "-preset", "slow", "-crf", "18", "-profile:v", "high", "-pix_fmt", "yuv420p"]+_AAC_192 = ["-c:a", "aac", "-b:a", "192k", "-ar", "48000"]+_AAC_128 = ["-c:a", "aac", "-b:a", "128k", "-ar", "48000"]+++def _social(crf: str = "20") -> List[str]:+ return ["-c:v", "libx264", "-preset", "medium", "-crf", crf, "-profile:v", "high", "-pix_fmt", "yuv420p", "-r", "30"]++PRESETS: Dict[str, Dict] = {- "youtube": {"w": 1920, "h": 1080, "ext": "mp4", "video": ["-c:v", "libx264", "-preset", "slow", "-crf", "18", "-profile:v", "high", "-pix_fmt", "yuv420p"], "audio": ["-c:a", "aac", "-b:a", "192k", "-ar", "48000"], "max": None, "desc": "1080p H.264, AAC 192k"},- "youtube4k": {"w": 3840, "h": 2160, "ext": "mp4", "video": ["-c:v", "libx264", "-preset", "slow", "-crf", "18", "-profile:v", "high", "-pix_fmt", "yuv420p"], "audio": ["-c:a", "aac", "-b:a", "192k", "-ar", "48000"], "max": None, "desc": "2160p H.264, AAC 192k"},- "reels": {"w": 1080, "h": 1920, "ext": "mp4", "video": ["-c:v", "libx264", "-preset", "medium", "-crf", "20", "-profile:v", "high", "-pix_fmt", "yuv420p", "-r", "30"], "audio": ["-c:a", "aac", "-b:a", "128k", "-ar", "48000"], "max": 90.0, "desc": "9:16 1080x1920, 30fps, max 90s (Reels/Shorts/TikTok)"},- "x": {"w": 1280, "h": 720, "ext": "mp4", "video": ["-c:v", "libx264", "-preset", "medium", "-crf", "22", "-profile:v", "high", "-pix_fmt", "yuv420p", "-r", "30"], "audio": ["-c:a", "aac", "-b:a", "128k", "-ar", "44100"], "max": 140.0, "desc": "720p H.264, max 140s (Twitter/X)"},+ "youtube": dict(_from_table("youtube", max=None), ext="mp4", video=_H264_HIGH, audio=_AAC_192, desc="1080p H.264, AAC 192k"),+ "youtube4k": dict(_from_table("youtube", w=3840, h=2160, max=None), ext="mp4", video=_H264_HIGH, audio=_AAC_192, desc="2160p H.264, AAC 192k"),+ "reels": dict(_from_table("reels"), ext="mp4", video=_social(), audio=_AAC_128, desc="9:16 1080x1920, 30fps, max 90s (Instagram Reels)"),+ "x": dict(_from_table("x"), ext="mp4", video=_social("22"), audio=["-c:a", "aac", "-b:a", "128k", "-ar", "44100"], desc="720p H.264, max 140s (Twitter/X)"),"prores": {"w": None, "h": None, "ext": "mov", "video": ["-c:v", "prores_ks", "-profile:v", "3", "-vendor", "apl0", "-pix_fmt", "yuv422p10le"], "audio": ["-c:a", "pcm_s16le"], "max": None, "desc": "ProRes 422 HQ master, PCM audio, source resolution"},"h265": {"w": None, "h": None, "ext": "mp4", "video": ["-c:v", "libx265", "-preset", "medium", "-crf", "24", "-pix_fmt", "yuv420p", "-tag:v", "hvc1"], "audio": ["-c:a", "aac", "-b:a", "160k"], "max": None, "desc": "HEVC CRF 24, hvc1 tag, source resolution"},"gif": {"w": 480, "h": None, "ext": "gif", "video": [], "audio": [], "max": None, "desc": "480px palette GIF, 12fps"},"copy": {"w": None, "h": None, "ext": None, "video": ["-c:v", "copy"], "audio": ["-c:a", "copy"], "max": None, "desc": "stream copy, no re-encode (source codecs/container/colour tags unchanged)"},+ # 1.14: the destinations that used to be aliases of reels/youtube are their own presets, each+ # sized and length-limited from the one platform table (scripts/_platforms.py) rather than from+ # a comment. `reels` keeps its historical settings byte-for-byte so existing calls are unchanged.+ "tiktok": dict(_from_table("tiktok"), ext="mp4", video=_social(), audio=_AAC_128, desc="9:16 1080x1920, 30fps, max 600s (TikTok)"),+ "shorts": dict(_from_table("shorts"), ext="mp4", video=_social(), audio=_AAC_128, desc="9:16 1080x1920, 30fps, max 180s (YouTube Shorts)"),+ "linkedin": dict(_from_table("linkedin"), ext="mp4", video=_social(), audio=_AAC_128, desc="1:1 1080x1080, 30fps, max 600s (LinkedIn)"),+ "facebook": dict(_from_table("facebook"), ext="mp4", video=_social("21"), audio=_AAC_128, desc="16:9 1920x1080, 30fps, max 14400s (Facebook feed)"),+ # HDR and AV1 deliveries: the encoder line comes from encoder_args() so the source's own+ # HDR tags survive (hevc) and the AV1 encoder is chosen/refused in one place.+ "youtube-hdr": {"w": None, "h": None, "ext": "mp4", "codec": "hevc", "video": [], "audio": _AAC_192, "max": None, "hdr_only": True, "desc": "HEVC Main10, source HDR10/HLG tags kept, AAC 192k (refuses an SDR source)"},+ "youtube-av1": dict(_from_table("youtube", max=None), ext="mp4", codec="av1", video=[], audio=_AAC_192, desc="1080p AV1 (libsvtav1, libaom fallback), AAC 192k"),}# which check.py platform a preset targets (its loudness spec is measured after the write)HERE = Path(__file__).resolve().parent-PLATFORM_OF = {"youtube": "youtube", "youtube4k": "youtube", "reels": "reels", "x": "x"}+# broadcast's "preset" is prores, an editing master rather than a delivery: nothing is measured+# against a loudness spec after writing it, exactly as before 1.14.+_NOT_A_DELIVERY = frozenset({"broadcast"})+# Derived from the same table: a destination whose "preset" is this one is the compliance target+# its loudness is measured against (youtube4k and the two youtube variants deliver to youtube).+PLATFORM_OF: Dict[str, str] = {PLATFORM_TABLE[n]["preset"]: PLATFORM_TABLE[n]["check"]+ for n in sorted(PLATFORM_TABLE)+ if PLATFORM_TABLE[n].get("preset") in PRESETS and PLATFORM_TABLE[n]["frame"]+ and n not in _NOT_A_DELIVERY}+PLATFORM_OF["youtube4k"] = PLATFORM_TABLE["youtube"]["check"]+# Aliases people write for a destination ('youtube-shorts', 'ig', 'twitter') name the same preset.+PRESET_CHOICES: List[str] = sorted(set(PRESETS) | {a for a in _ALIASES if resolve_platform(a) in PRESETS})def main() -> int:ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)ap.add_argument("input", nargs="?")ap.add_argument("-o", "--output", help="output file (default: <name>_<preset>.<ext>)")- ap.add_argument("--preset", choices=sorted(PRESETS), help="delivery preset")+ ap.add_argument("--preset", choices=PRESET_CHOICES, help="delivery preset (aliases: " + ", ".join(a for a in _ALIASES if resolve_platform(a) in PRESETS) + ")")ap.add_argument("--fit", choices=["pad", "crop"], default="pad", help="how to reach the preset frame when aspect differs (default pad)")ap.add_argument("--pad-color", default="black")add_pad_fill_args(ap)@@ -65,6 +122,8 @@ def main() -> int:add_common(ap, codec=False) # the preset decides the codec; --codec would only be refusedargs = ap.parse_args()apply_common(args)+ if args.preset and args.preset not in PRESETS:+ args.preset = resolve_platform(args.preset)if args.list:for name, p in PRESETS.items():@@ -82,7 +141,13 @@ def main() -> int:if not meta.get("video"):die("input has no video stream")notes: List[str] = []- if meta["video"].get("hdr") and args.preset not in ("prores", "copy"):+ if p.get("hdr_only") and not meta["video"].get("hdr"):+ # The point of this preset is that the delivery stays HDR. Running it on an SDR source+ # would write a 10-bit HEVC file labelled with SDR tags and call it an HDR delivery.+ die(f"--preset {args.preset} delivers HDR and this source is SDR ({meta['video'].get('codec')}, "+ f"{meta['video'].get('color_transfer') or 'untagged'})",+ hint="use --preset youtube for an SDR delivery; there is no way to invent HDR range from an SDR master")+ if meta["video"].get("hdr") and args.preset not in ("prores", "copy", "youtube-hdr"):notes.append("source is HDR (%s). This preset outputs SDR BT.709 tags without tone mapping; run color.py --to-sdr first for correct colours." % meta["video"].get("hdr_format"))info("warning: " + notes[-1])has_audio = bool(meta.get("audio"))@@ -113,9 +178,20 @@ def main() -> int:if vf:cmd += ["-vf", ",".join(vf)]video = list(p["video"])+ if p.get("codec"):+ # encoder_args() is the one place that turns a codec name into encoder options: it keeps+ # the source's HDR tags for hevc and refuses (kind: missing_tool) when no AV1 encoder is+ # built, which is exactly what these two presets promise.+ video = encoder_args(p["codec"], args.crf if args.crf is not None else (20 if p["codec"] == "hevc" else 32),+ "veryfast" if STATE.fast else "medium", meta)+ # encoder_args() already applied --fast (its own preset scale per encoder: SVT-AV1 counts+ # 1..12, not x264's names) and appends +faststart, which this tool adds again for mp4+ while "-movflags" in video:+ i = video.index("-movflags")+ del video[i:i + 2]if args.crf is not None and "-crf" in video:video[video.index("-crf") + 1] = str(args.crf)- if STATE.fast and "-preset" in video:+ if STATE.fast and "-preset" in video and not p.get("codec"):video[video.index("-preset") + 1] = "veryfast"cmd += videoif args.preset != "copy":@@ -123,7 +199,7 @@ def main() -> int:# no longer be a copy, and would silently mislabel colour the agent never actually looked atif "-r" not in video:cmd += cfr_args(meta)- if args.preset not in ("prores",):+ if args.preset not in ("prores",) and not p.get("codec"):cmd += bt709_tag_args(video[video.index("-c:v") + 1])if out_ext == "mp4":cmd += ["-movflags", "+faststart"]diff --git a/scripts/fit.py b/scripts/fit.pyindex d50a973..d982e97 100755--- a/scripts/fit.py+++ b/scripts/fit.py@@ -4,7 +4,7 @@Duration: --duration N with --method speed (retime video+audio, pitch-preservingvia atempo chaining) or --method trim (keep the first N seconds, or a centredwindow with --from-center). Aspect: --aspect 16:9|9:16|1:1|4:5|W:H with---fit pad (letterbox/pillarbox with --pad-color, default black, or --pad-fill blur\nfor a blurred copy of the frame behind the picture) or --fit crop.+--fit pad (letterbox/pillarbox with --pad-color, default black, or --pad-fill blur\nfor a blurred copy of the frame behind the picture), --fit crop, or --fit blur\n(the whole picture centred on a blurred, darkened copy of itself -- nothing\ncropped, no black bars).--width and/or --height set the output size: give one and the other followsthe aspect (source aspect if --aspect is not also given); give both for anexact frame. --rotate 90|180|270 (clockwise) and --flip h|v apply a new@@ -25,6 +25,7 @@ Examples:python3 fit.py input.mp4 --duration 30 --method trimpython3 fit.py input.mp4 --aspect 9:16 --fit pad --width 1080python3 fit.py input.mp4 --aspect 9:16 --fit pad --pad-fill blur # the phone-editor look: blurred frame behind the bars+ python3 fit.py input.mp4 --aspect 9:16 --fit blur # same look in one word (blurred + darkened fill)python3 fit.py input.mp4 --aspect 1:1 --fit crop --duration 15python3 fit.py input.mp4 --aspect 9:16 --fit crop --crop-x 1 # keep the right edge (e.g. product held stage-right)python3 fit.py input.mp4 --height 1080 # width follows the source aspect@@ -39,6 +40,7 @@ from fractions import Fractionfrom typing import Listfrom _common import video_args, STATE, add_common, apply_common, emit, aac_args, cfr_args, default_output, die, ffmpeg_base, info, parse_time, probe, run, run_keeping_subtitles, validate_color, x264_args, pad_filters, add_pad_fill_args, X264_PRESETS, time_arg, fmt_secs+BLUR_DARKEN = 0.15 # how much --fit blur dims the blurred background copy (eq brightness)ASPECT_PRESETS = {"16:9": Fraction(16, 9), "9:16": Fraction(9, 16), "1:1": Fraction(1, 1), "4:5": Fraction(4, 5), "4:3": Fraction(4, 3), "21:9": Fraction(21, 9)}@@ -89,7 +91,11 @@ def main() -> int:help="slow-motion quality: blend (frame blending) or interpolate (motion-compensated, slow but fluid). default none = duplicate frames")a = ap.add_argument_group("aspect")a.add_argument("--aspect", help="target aspect ratio, e.g. 16:9, 9:16, 1:1, 4:5")- a.add_argument("--fit", choices=["pad", "crop"], default="pad", help="pad (letterbox) or crop to reach the aspect (default pad)")+ a.add_argument("--fit", choices=["pad", "crop", "blur"], default="pad",+ help="how to reach the aspect: pad (letterbox), crop, or blur -- the whole picture centred on a "+ "blurred, darkened copy of itself filling the rest (the phone-editor vertical, 1.14). "+ "The darkening is applied to SDR sources only: on an HDR source the background is blurred "+ "but left at its own levels, since an eq on PQ/HLG code values is not a -15%% perceptual dim")a.add_argument("--width", type=int, help="output width in px (default: keep source width or the width implied by the aspect); with --height also given, both are used directly")a.add_argument("--height", type=int, help="output height in px (default: keep source height or the height implied by the aspect); with --width also given, both are used directly")a.add_argument("--pad-color", default="black", help="pad colour, e.g. black, white, 0x101010 (default black)")@@ -214,6 +220,19 @@ def main() -> int:if args.fit == "crop":vf.append(f"scale={out_w}:{out_h}:force_original_aspect_ratio=increase")vf.append(f"crop={out_w}:{out_h}:(in_w-out_w)*{args.crop_x:g}:(in_h-out_h)*{args.crop_y:g}")+ elif args.fit == "blur":+ # nothing is cropped and nothing is a black bar: the picture keeps its own aspect in+ # the middle of a blurred, dimmed copy of itself (BLUR_DARKEN) filling the frame.+ # The dimming is an eq on the code values, which is a -15 % perceptual dim on an SDR+ # (gamma-encoded) signal and something else entirely on a PQ/HLG one -- so an HDR+ # source keeps its blurred background undimmed rather than being silently altered+ # (review 12). The blur itself is neutral either way, and no tone mapping happens.+ darken = 0.0 if meta["video"].get("hdr") else BLUR_DARKEN+ if not darken:+ info("--fit blur: HDR source, so the blurred background is not dimmed "+ "(an eq on PQ/HLG code values is not the -15%% dim it is on SDR); "+ "run color.py --to-sdr first for the SDR look")+ vf.append(pad_filters(out_w, out_h, "blur", args.pad_color, args.pad_blur, darken))else:vf.append(pad_filters(out_w, out_h, args.pad_fill, args.pad_color, args.pad_blur))vf.append("setsar=1")diff --git a/scripts/graphics.py b/scripts/graphics.pyindex 0f8f0cc..f5761c5 100755--- a/scripts/graphics.py+++ b/scripts/graphics.py@@ -9,6 +9,10 @@ Templates:progress thin progress bar along the bottom that fills over the clip (or --start/--end)countdown big numbers counting down from --from to 0 (--start/--end define the window)bug persistent text bug (--title) in a corner, e.g. "@handle" or "LIVE"+ sticker rounded filled chip of --text that pops in at --position (the social sticker)+ hook full-width opening title card (--title) for --duration seconds with a thin+ progress bar along the top -- the TikTok/Shorts opener+ meme white upper-case --top / --bottom lines with a heavy black outlineExamples:python3 graphics.py talk.mp4 --template lower-third --name "Ada Lovelace" --title "Analyst" --start 2 --end 8@@ -17,14 +21,18 @@ Examples:python3 graphics.py intro.mp4 --template countdown --from 5 --start 1 --end 6python3 graphics.py talk.mp4 --template lower-third --name "김민준" --title "감독" --lang kopython3 graphics.py clip.mp4 --template chapter --title "Part 2 — Setup" --position top-left --start 0 --end 5+ python3 graphics.py reel.mp4 --template sticker --text "NEW" --position top-right --platform tiktok+ python3 graphics.py reel.mp4 --template hook --title "How I cut this in one command" --duration 3+ python3 graphics.py clip.mp4 --template meme --top "when the render" --bottom "finally finishes""""import argparseimport sysfrom typing import List, Optional+from _platforms import PLATFORMS, PLATFORM_CHOICES, safe_margins_px, resolve as resolve_platformfrom _common import aac_args, add_common, brand_caption_style, script_font_for_text, apply_common, cfr_args, color_hex, default_font_file, default_output, die, emit, escape_drawtext, escape_filter_path, ffmpeg_base, info, load_brand, parse_time, probe, run, run_keeping_subtitles, video_args, drawtext_boxborderw, X264_PRESETS, time_arg, fmt_secs-TEMPLATES = ["lower-third", "title", "chapter", "progress", "countdown", "bug"]+TEMPLATES = ["lower-third", "title", "chapter", "progress", "countdown", "bug", "sticker", "hook", "meme"]def ff_color(hex_rgb: str, alpha: float = 1.0) -> str:@@ -53,12 +61,20 @@ def main() -> int:ap.add_argument("--template", choices=TEMPLATES, required=True)ap.add_argument("--brand", help="brand.json for colours, font, safe margin")ap.add_argument("--name", help="lower-third: name line")- ap.add_argument("--title", help="title / chapter / bug text, or lower-third second line")+ ap.add_argument("--title", help="title / chapter / bug / hook text, or lower-third second line")+ ap.add_argument("--text", help="sticker: the chip's text")+ ap.add_argument("--top", help="meme: upper line")+ ap.add_argument("--bottom", help="meme: lower line")+ ap.add_argument("--duration", type=float, default=3.0, help="hook: seconds the opening card stays up (default 3)")ap.add_argument("--subtitle", help="title: smaller second line")ap.add_argument("--from", dest="count_from", type=int, default=5, help="countdown start number (default 5)")ap.add_argument("--start", help="show from (default 0)")ap.add_argument("--end", help="hide after (default end of clip)")- ap.add_argument("--position", choices=["top-left", "top-right", "bottom-left", "bottom-right"], default=None, help="corner for chapter/bug (default bottom-left / top-right)")+ ap.add_argument("--position", choices=["top-left", "top-right", "bottom-left", "bottom-right"], default=None, help="corner for chapter/bug/sticker (default bottom-left / top-right / top-right)")+ ap.add_argument("--margin", type=int, default=None, help="distance from the frame edge in px (default: brand safe_margin, or the --platform safe zone)")+ ap.add_argument("--platform", choices=PLATFORM_CHOICES, default=None,+ help="keep the graphic out of this destination's UI: margins become the platform's safe zone "+ "(TikTok's description bar and like column, the Reels/Shorts chrome). An explicit --margin wins")ap.add_argument("--primary", help="override brand primary colour RRGGBB")ap.add_argument("--text-color", help="override text colour RRGGBB")ap.add_argument("--font")@@ -72,6 +88,10 @@ def main() -> int:args = ap.parse_args()apply_common(args)+ args.platform = resolve_platform(args.platform)+ if args.platform and not PLATFORMS[args.platform].get("frame"):+ info(f"--platform {args.platform}: this destination has no frame and no app chrome; margins unchanged")+ args.platform = Nonebrand = load_brand(args.brand)primary = color_hex(args.primary or brand["colors"]["primary"])text_c = color_hex(args.text_color or brand["colors"]["text"])@@ -85,7 +105,7 @@ def main() -> int:args.lang = args.lang or (brand.get("lang") if args.brand else None)# a font that covers the text before drawtext renders boxes instead of glyphs (1.12)_script, script_file, _family = script_font_for_text(- " ".join(t for t in (args.name, args.title, args.subtitle) if t),+ " ".join(t for t in (args.name, args.title, args.subtitle, args.text, args.top, args.bottom) if t),lang=args.lang, font=args.font, font_explicit=bool(args.font), font_file=args.font_file or brand.get("font_file"))fo = font_opts(brand, args.font, args.font_file, script_file)@@ -101,6 +121,19 @@ def main() -> int:if meta["video"].get("rotation") in (90, -90, 270, -270):W, H = H, Wdur = meta.get("duration") or 0.0+ # Per-edge margins. Without --margin/--platform every edge is the brand safe margin, exactly+ # as before; --margin sets all four; --platform takes each edge from the destination's safe+ # zone (scripts/_platforms.py), which is what keeps a sticker off TikTok's like column.+ m_top = m_bottom = m_left = m_right = margin+ if args.margin is not None:+ if args.margin < 0:+ die(f"--margin must be >= 0, got {args.margin}")+ m_top = m_bottom = m_left = m_right = margin = args.margin+ elif args.platform:+ px = safe_margins_px(args.platform, W, H)+ m_top, m_bottom, m_left, m_right = px["top"], px["bottom"], px["left"], px["right"]+ margin = m_left+ info(f"--platform {args.platform}: safe margins top {m_top} / bottom {m_bottom} / left {m_left} / right {m_right} px")fps = meta["video"].get("fps")s = time_arg(args.start, "--start", fps) if args.start else 0.0e = time_arg(args.end, "--end", fps) if args.end else dur@@ -123,9 +156,9 @@ def main() -> int:pad = int(base * 0.02)bar_h = h1 + (h2 + pad if args.title else 0) + pad * 2bar_w = int(base * 0.62)- y0 = H - margin - bar_h+ y0 = H - m_bottom - bar_h# slide in from the left over 0.4 s, slide out over 0.3 s (overlay evaluates x per frame)- x_expr = f"if(lt(t,{s:.3f}+0.4),-{bar_w}+({bar_w}+{margin})*((t-{s:.3f})/0.4),if(gt(t,{e:.3f}-0.3),{margin}-({bar_w}+{margin})*(1-({e:.3f}-t)/0.3),{margin}))"+ x_expr = f"if(lt(t,{s:.3f}+0.4),-{bar_w}+({bar_w}+{m_left})*((t-{s:.3f})/0.4),if(gt(t,{e:.3f}-0.3),{m_left}-({bar_w}+{m_left})*(1-({e:.3f}-t)/0.3),{m_left}))"fc.append(f"color=c=0x{bg}@0.85:s={bar_w}x{bar_h}:r={meta['video'].get('fps') or 30:g},format=rgba[bar]")fc.append(f"color=c=0x{primary}:s={int(base * 0.012)}x{bar_h}:r={meta['video'].get('fps') or 30:g},format=rgba[acc]")fc.append(f"[0:v][bar]overlay=x='{x_expr}':y={y0}:{en}:eof_action=pass[v1]")@@ -153,8 +186,8 @@ def main() -> int:pos = args.position or ("bottom-left" if args.template == "chapter" else "top-right")fs = int(base * (0.04 if args.template == "chapter" else 0.032))padx, pady = int(fs * 0.6), int(fs * 0.35)- xe = f"{margin}" if "left" in pos else f"w-text_w-{margin}"- ye = f"{margin}" if "top" in pos else f"h-text_h-{margin}"+ xe = f"{m_left}" if "left" in pos else f"w-text_w-{m_right}"+ ye = f"{m_top}" if "top" in pos else f"h-text_h-{m_bottom}"box_color = ff_color(primary if args.template == "chapter" else bg, 0.9 if args.template == "chapter" else 0.7)txt_color = ff_color(bg if args.template == "chapter" else text_c)filters.append(f"drawtext=text='{escape_drawtext(args.title)}':{fo}:fontsize={fs}:fontcolor={txt_color}:x={xe}:y={ye}:box=1:boxcolor={box_color}:boxborderw={drawtext_boxborderw(pady, padx)}:alpha='{fade_a}':{en}")@@ -166,6 +199,58 @@ def main() -> int:fc.append(f"[0:v]drawbox=x=0:y=ih-{h}:w=iw:h={h}:color={ff_color(bg, 0.5)}:t=fill:{en}[v1]")fc.append(f"[v1][pb]overlay=x='-w+w*min(1,max(0,(t-{s:.3f})/{e - s:.3f}))':y={H - h}:{en}:eof_action=pass[vout]")+ elif args.template == "sticker":+ # A social sticker: a filled chip of text that pops in. drawtext's box gives the chip+ # (its corners are square -- drawtext has no rounded box), and the pop is the two things+ # drawtext *can* animate per frame: alpha and position, so the chip fades up while+ # rising the last few pixels into place over 0.25 s.+ if not args.text:+ die("sticker needs --text")+ pos = args.position or "top-right"+ fs = int(base * 0.05)+ padx, pady = int(fs * 0.7), int(fs * 0.45)+ rise = int(fs * 0.5)+ pop = f"min(1,(t-{s:.3f})/0.25)"+ xe = f"{m_left}" if "left" in pos else f"w-text_w-{m_right}"+ ye = (f"{m_top}+{rise}*(1-{pop})" if "top" in pos else f"h-text_h-{m_bottom}-{rise}*(1-{pop})")+ alpha = f"min({pop},{fade_a})"+ filters.append(f"drawtext=text='{escape_drawtext(args.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}")++ elif args.template == "hook":+ # The opener: a full-width card over the first --duration seconds with a thin bar along+ # the top that empties as the card's time runs out, so the viewer sees how long it lasts.+ if not args.title:+ die("hook needs --title")+ if args.duration <= 0:+ die(f"--duration must be > 0, got {args.duration:g}")+ he = min(e, s + args.duration)+ hen = f"enable='between(t,{s:.3f},{he:.3f})'"+ h1 = int(base * 0.085)+ bar_h = max(3, int(base * 0.01))+ 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}")+ filters.append(f"drawtext=text='{escape_drawtext(args.title)}':{fo}:fontsize={h1}:fontcolor={ff_color(text_c)}:"+ f"x=(w-text_w)/2:y=(h-text_h)/2:{hen}")+ filters.append(f"drawbox=x=0:y=0:w='iw*max(0,1-(t-{s:.3f})/{max(0.001, he - s):.3f})':h={bar_h}:"+ f"color={ff_color(primary)}:t=fill:{hen}")++ 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).+ if not (args.top or args.bottom):+ die("meme needs --top and/or --bottom")+ fs = int(base * 0.09)+ bw = max(2, int(fs / 12))+ white, black = ff_color("FFFFFF"), ff_color("000000")+ for text, y in ((args.top, f"{m_top}"), (args.bottom, f"h-text_h-{m_bottom}")):+ if not text:+ continue+ filters.append(f"drawtext=text='{escape_drawtext(text.upper())}':{fo}:fontsize={fs}:fontcolor={white}:"+ f"borderw={bw}:bordercolor={black}:x=(w-text_w)/2:y={y}:{en}")+elif args.template == "countdown":n = args.count_fromseg = (e - s) / (n + 1)diff --git a/scripts/look.py b/scripts/look.pyindex 84a65be..5029610 100755--- a/scripts/look.py+++ b/scripts/look.py@@ -7,6 +7,7 @@ Examples:python3 look.py final.mp4 --tiles 4x5 --width 1600python3 look.py final.mp4 --at 2.5 --at 7 # single frames -> final_2.500s.png, final_7.000s.pngpython3 look.py before.mp4 --compare after.mp4 --at 4 # side-by-side frame+ python3 look.py reel.mp4 --safe tiktok --at 3 # shade what TikTok's own UI coversThen view the PNG (Read tool / image viewer) and verify before reporting."""import argparse@@ -15,6 +16,7 @@ import sysfrom pathlib import Pathfrom typing import List+from _platforms import PLATFORMS, PLATFORM_CHOICES, resolve as resolve_platformfrom _common import STATE, add_common, apply_common, default_font_file, die, emit, escape_drawtext, escape_filter_path, ffmpeg_base, info, parse_time, probe, run, time_argFONT = "fontcolor=white:fontsize=h/18:box=1:[email protected]:boxborderw=6:x=8:y=8"@@ -39,6 +41,8 @@ def main() -> int:ap.add_argument("--width", type=int, default=1280, help="total width of the sheet / compare image (default 1280)")ap.add_argument("--compare", help="second video: place its frame next to the first (needs --at)")ap.add_argument("--no-timecode", action="store_true")+ ap.add_argument("--safe", choices=PLATFORM_CHOICES, help="shade the zones this platform's UI covers (its description bar, "+ "like column, status bar) so you can see whether anything readable is under them")add_common(ap)args = ap.parse_args()apply_common(args)@@ -55,6 +59,37 @@ def main() -> int:default_font = default_font_file("DejaVu Sans")font_prefix = f"fontfile={escape_filter_path(default_font)}:" if default_font else ""tc = "" if args.no_timecode else "," + timecode_filter(font_prefix)+ # --safe: the platform's occluded zones, drawn as shaded boxes in fractions of the frame so+ # the same filter is right at any scale (a tile of a contact sheet as much as a full frame).+ safe_filter = ""+ args.safe = resolve_platform(args.safe)+ if args.safe and not PLATFORMS[args.safe].get("frame"):+ info(f"--safe {args.safe}: this destination has no frame and no app chrome; nothing to shade")+ args.safe = None+ if args.safe:+ z = PLATFORMS[args.safe]["safe"]+ frame = PLATFORMS[args.safe]["frame"]+ src = meta["video"]+ if src.get("width") and src.get("height") and abs(src["width"] / src["height"] - frame["w"] / frame["h"]) > 0.02:+ info(f"--safe {args.safe}: this source is {src['width']}x{src['height']}, not {args.safe}'s "+ f"{frame['w']}x{frame['h']} -- the zones are drawn as fractions of the frame you gave, "+ f"so reframe first (fit.py --aspect) to see what the app really covers")+ boxes = []+ for edge, frac in (("top", z["top"]), ("bottom", z["bottom"]), ("left", z["left"]), ("right", z["right"])):+ if frac <= 0:+ continue+ if edge == "top":+ boxes.append(f"drawbox=x=0:y=0:w=iw:h=ih*{frac:g}:[email protected]:t=fill")+ elif edge == "bottom":+ boxes.append(f"drawbox=x=0:y=ih*(1-{frac:g}):w=iw:h=ih*{frac:g}:[email protected]:t=fill")+ elif edge == "left":+ boxes.append(f"drawbox=x=0:y=0:w=iw*{frac:g}:h=ih:[email protected]:t=fill")+ else:+ boxes.append(f"drawbox=x=iw*(1-{frac:g}):y=0:w=iw*{frac:g}:h=ih:[email protected]:t=fill")+ safe_filter = "," + ",".join(boxes) if boxes else ""+ info(f"--safe {args.safe}: shaded top {z['top'] * 100:.0f}% / bottom {z['bottom'] * 100:.0f}% / "+ f"left {z['left'] * 100:.0f}% / right {z['right'] * 100:.0f}% of the frame -- keep text out of those")+ tc = safe_filter + tc# HDR sources: tone-map for the PNG so the agent judges representative colours, not raw HLG/PQif meta["video"].get("hdr"):v = meta["video"]diff --git a/scripts/overlay.py b/scripts/overlay.pyindex 24818ca..013bdfd 100755--- a/scripts/overlay.py+++ b/scripts/overlay.py@@ -24,24 +24,30 @@ import argparseimport sysfrom typing import List, Optional+from _platforms import PLATFORMS, PLATFORM_CHOICES, safe_margins_px, resolve as resolve_platformfrom _common import STATE, script_font_for_text, load_brand, video_args, add_common, apply_common, default_font_file, emit, aac_args, cfr_args, default_output, die, escape_drawtext, escape_filter_path, ffmpeg_base, info, parse_time, probe, run, run_keeping_subtitles, validate_color, x264_args, X264_PRESETS, time_arg, fmt_secs+# Per-edge margins: a platform's UI does not cover the same fraction of every edge (TikTok's+# like column is 14 % of the width, its description block 22 % of the height), so a position+# names the edges it is measured from rather than one --margin for all four.POS = {- "top-left": ("{m}", "{m}"),- "top": ("(W-w)/2", "{m}"),- "top-right": ("W-w-{m}", "{m}"),- "left": ("{m}", "(H-h)/2"),+ "top-left": ("{left}", "{top}"),+ "top": ("(W-w)/2", "{top}"),+ "top-right": ("W-w-{right}", "{top}"),+ "left": ("{left}", "(H-h)/2"),"center": ("(W-w)/2", "(H-h)/2"),- "right": ("W-w-{m}", "(H-h)/2"),- "bottom-left": ("{m}", "H-h-{m}"),- "bottom": ("(W-w)/2", "H-h-{m}"),- "bottom-right": ("W-w-{m}", "H-h-{m}"),+ "right": ("W-w-{right}", "(H-h)/2"),+ "bottom-left": ("{left}", "H-h-{bottom}"),+ "bottom": ("(W-w)/2", "H-h-{bottom}"),+ "bottom-right": ("W-w-{right}", "H-h-{bottom}"),}-def position_exprs(pos: str, margin: int, text_mode: bool):+def position_exprs(pos: str, margin: int, text_mode: bool, margins: Optional[dict] = None):+ edges = margins or {}+ m = {edge: int(edges.get(edge, margin)) for edge in ("top", "bottom", "left", "right")}if pos in POS:- x, y = (e.format(m=margin) for e in POS[pos])+ x, y = (e.format(**m) for e in POS[pos])else:try:xs, ys = pos.split(",")@@ -101,6 +107,10 @@ def main() -> int:ap.add_argument("--brand", help="brand.json (logo, font, colours, safe margin)")ap.add_argument("--position", default="top-right", help="named position or X,Y (default top-right)")ap.add_argument("--margin", type=int, default=24, help="margin from the edges in px (default 24)")+ ap.add_argument("--platform", choices=PLATFORM_CHOICES, default=None,+ help="keep the overlay out of this destination's UI: each edge's margin becomes that "+ "platform's safe zone (scripts/_platforms.py), so a top-left logo clears TikTok's "+ "status bar and a right-hand one clears the like column. An explicit --margin wins")ap.add_argument("--start", help="show from this time (default: whole video)")ap.add_argument("--end", help="hide after this time")ap.add_argument("--fade", type=float, default=0.0, help="fade-in duration in seconds (at --start or 0); the fade-out happens only at --end")@@ -163,6 +173,20 @@ def main() -> int:if args.audio_stream and not audio_streams:die("--audio-stream needs an input with audio streams")vw = meta["video"]["width"]+ # --platform: the edges this destination's own UI covers, in pixels of this frame. An+ # explicit --margin (or a brand safe_margin, applied above) is the more specific statement+ # and wins; without either, the historical 24 px default is unchanged.+ safe_margins = None+ args.platform = resolve_platform(args.platform)+ if args.platform and args.margin == ap.get_default("margin") and PLATFORMS[args.platform].get("frame"):+ # a dry run has no real frame to measure (the probe is stubbed rather than guessed), so+ # fall back to the destination's own delivery frame -- which is what the fitted+ # intermediate this stage runs on will be anyway+ frame = PLATFORMS[args.platform]["frame"]+ pw, ph = vw or frame["w"], meta["video"].get("height") or frame["h"]+ safe_margins = safe_margins_px(args.platform, pw, ph)+ info(f"--platform {args.platform}: safe margins top {safe_margins['top']} / bottom {safe_margins['bottom']} / "+ f"left {safe_margins['left']} / right {safe_margins['right']} px (clear of the app's own UI)")fps = meta["video"].get("fps")start = time_arg(args.start, "--start", fps) if args.start else Noneend = time_arg(args.end, "--end", fps) if args.end else None@@ -203,7 +227,7 @@ def main() -> int:chain.append(f"fade=t=in:st={s:.3f}:d={args.fade:g}:alpha=1")if end is not None and end > args.fade:chain.append(f"fade=t=out:st={end - args.fade:.3f}:d={args.fade:g}:alpha=1")- x, y = position_exprs(args.position, args.margin, text_mode=False)+ x, y = position_exprs(args.position, args.margin, text_mode=False, margins=safe_margins)ov = f"overlay={x}:{y}:format=auto"if enable:ov += f":enable='{enable}'"@@ -237,7 +261,7 @@ def main() -> int:chain.append(f"chromakey={args.chromakey}:{args.chromakey_similarity:g}:{args.chromakey_blend:g}")if args.opacity < 1:chain.append(f"colorchannelmixer=aa={args.opacity:g}")- x, y = position_exprs(args.position, args.margin, text_mode=False)+ x, y = position_exprs(args.position, args.margin, text_mode=False, margins=safe_margins)ov = f"overlay={x}:{y}:format=auto"if enable:ov += f":enable='{enable}'"@@ -251,7 +275,7 @@ def main() -> int:else:cmd += ["-shortest"]else:- x, y = position_exprs(args.position, args.margin, text_mode=True)+ x, y = position_exprs(args.position, args.margin, text_mode=True, margins=safe_margins)opts = [f"text='{escape_drawtext(args.text)}'", f"fontsize={args.font_size}", f"x={x}", f"y={y}",f"borderw={args.border}", f"bordercolor={args.border_color}"]if args.font_file:diff --git a/scripts/render.py b/scripts/render.pyindex 04ed04a..ff16f10 100755--- a/scripts/render.py+++ b/scripts/render.py@@ -60,9 +60,17 @@ from pathlib import Pathfrom typing import Any, Dict, Listfrom export import PRESETS, PLATFORM_OF+from _platforms import PLATFORMS, caption_defaults, resolve as resolve_platformfrom _common import STATE, add_common, apply_common, child_args, die, emit, info, probe, run_tool, place_output, refuse_output_is_input, fingerprint, PLAN_VERSIONHERE = 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")+# 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"})TEMPLATE = {"output": "final.mp4",@@ -88,18 +96,23 @@ TEMPLATE = {# untrimmed, and a mistyped stage name dropped the stage -- both reported as a success (review 9).OBJECT_KEYS: Dict[str, frozenset] = {"project": frozenset({"output", "frame", "clips", "transition", "silence", "brand", "captions",- "graphics", "overlays", "audio", "loudness", "fit", "export", "check", "chapters"}),+ "graphics", "overlays", "audio", "loudness", "fit", "export", "check", "chapters",+ "template"}),"clips[]": frozenset({"src", "in", "out", "speed"}),- "frame": frozenset({"aspect", "width", "height", "fps"}),+ "frame": frozenset({"aspect", "width", "height", "fps", "fit"}),"transition": frozenset({"type", "duration"}),"silence": frozenset({"threshold", "min_silence", "margin"}),"captions": frozenset({"text", "srt", "ass", "font", "size", "color", "position", "margin","animate", "highlight_color", "outline", "karaoke", "bold", "box","lang", "offset", "max_lines", "min_duration"}),+ # the 1.14 social templates (sticker/hook/meme) take their own text and timing, so a+ # graphics[] entry can carry them too -- a template that only works from the CLI is not+ # "usable inside a render.py graphics[] entry" (review 12)"graphics[]": frozenset({"template", "name", "title", "subtitle", "start", "end", "position",- "from", "scale", "primary", "text_color", "lang"}),+ "from", "scale", "primary", "text_color", "lang",+ "text", "top", "bottom", "duration", "margin", "platform"}),"overlays[]": frozenset({"logo", "image", "text", "position", "start", "end", "fade", "opacity",- "scale", "font_size", "font", "font_file", "margin", "box"}),+ "scale", "font_size", "font", "font_file", "margin", "box", "platform"}),"audio": frozenset({"music", "replace", "music_volume", "fade_in", "fade_out", "music_fade_out","gain", "duck_amount", "duck_threshold", "duck_attack", "duck_release","voice", "denoise", "duck", "music_loop", "stereo", "mono", "downmix",@@ -117,6 +130,216 @@ NEAR_KEYS: Dict[str, Dict[str, str]] = {"clips[]": {"start": "in", "end": "out","chapters[]": {"start": "at", "time": "at", "name": "title"}}+def template_names() -> List[str]:+ """Every templates/<name>.json that ships with the skill."""+ return sorted(p.stem for p in TEMPLATE_DIR.glob("*.json"))+++def load_template(name: str) -> Dict[str, Any]:+ path = TEMPLATE_DIR / f"{name}.json"+ if not path.is_file():+ die(f"unknown template {name!r}", hint="templates: " + ", ".join(template_names()) + " (or 'all')")+ try:+ return json.loads(path.read_text(encoding="utf-8"))+ except (OSError, ValueError) as exc:+ die(f"cannot read template {path}: {exc}")+ return {}+++def fill_template(node: Any, values: Dict[str, Any]) -> "tuple":+ """Substitute the $PLACEHOLDERS a template carries; return (filled, complete).++ complete=False means a placeholder in this node had no value, and the caller drops the+ whole block: a template's overlay entry is `{"image": "$LOGO"}`, so a run without --logo+ must lose the overlay entirely rather than render an overlay of nothing."""+ if isinstance(node, str):+ if node in PLACEHOLDERS:+ value = values.get(node)+ return value, value is not None+ return node, True+ if isinstance(node, list):+ kept = []+ for item in node:+ filled, ok = fill_template(item, values)+ if ok:+ kept.append(filled)+ return kept, True+ if isinstance(node, dict):+ out: Dict[str, Any] = {}+ complete = True+ for key, value in node.items():+ filled, ok = fill_template(value, values)+ if not ok:+ complete = False+ continue+ out[key] = filled+ return out, complete+ return node, True+++def template_project(name: str, args) -> Dict[str, Any]:+ """One template plus the run's arguments as a ready-to-render project."""+ tpl = load_template(name)+ dest = str((tpl.get("check") or {}).get("platform") or name)+ if args.srt and isinstance(tpl.get("captions"), dict) and "text" in tpl["captions"]:+ cap = {("srt" if k == "text" else k): ("$SRT" if k == "text" else v) for k, v in tpl["captions"].items()}+ tpl["captions"] = cap+ # The caption block's size and margin are the table's, not a literal restated in the JSON:+ # change a destination's safe zone in scripts/_platforms.py and every template follows.+ if isinstance(tpl.get("captions"), dict) and dest in PLATFORMS and PLATFORMS[dest].get("frame"):+ defaults = caption_defaults(dest)+ tpl["captions"]["size"] = defaults["size"]+ tpl["captions"]["margin"] = defaults["margin"]+ for key in ("position", "animate", "outline"):+ tpl["captions"].setdefault(key, defaults[key])+ output = args.output or str(template_output(args.input, name, dest))+ values = {+ "$INPUT": os.path.abspath(args.input),+ "$OUTPUT": os.path.abspath(output),+ "$CUES": os.path.abspath(args.cues) if args.cues else None,+ "$SRT": os.path.abspath(args.srt) if args.srt else None,+ "$LOGO": os.path.abspath(args.logo) if args.logo else None,+ "$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,+ }+ for flag, path in (("--cues", args.cues), ("--srt", args.srt), ("--logo", args.logo),+ ("--brand", args.brand), ("--chapters", args.chapters)):+ if path and not os.path.isfile(path):+ die(f"{flag}: file not found: {path}")+ proj, _ = fill_template(tpl, values)+ if args.fit:+ proj.setdefault("frame", {})["fit"] = args.fit+ return proj+++def template_ext(dest: str) -> str:+ """A destination with no frame delivers audio: the podcast template writes .m4a, not .mp4."""+ return ".mp4" if (PLATFORMS.get(dest) or {}).get("frame") else ".m4a"+++def template_output(input_path: str, name: str, dest: str) -> Path:+ """Where a template writes when no -o was given: next to the input, named after it and the+ template. One rule for a single template and for a pack, so `--template tiktok` and+ `--template tiktok,x` put their files in the same place (review 12)."""+ stem = Path(input_path).with_suffix("").name+ return Path(input_path).resolve().parent / f"{stem}_{name}{template_ext(dest)}"+++def list_templates() -> None:+ """The templates, the destination each delivers to, and the zones its UI covers."""+ print("%-15s %-11s %-5s %7s %-10s %s" % ("template", "frame", "fit", "max", "loudness", "safe zones (fraction of the frame)"))+ for name in template_names():+ tpl = load_template(name)+ dest = str((tpl.get("check") or {}).get("platform") or name)+ plat = PLATFORMS.get(dest) or {}+ frame = plat.get("frame")+ spec = plat.get("spec") or {}+ safe = plat.get("safe") or {}+ dur = spec.get("max_duration")+ zones = ", ".join("%s %.2f" % (edge, safe.get(edge, 0)) for edge in ("top", "bottom", "left", "right") if safe.get(edge))+ size = "%dx%d" % (frame["w"], frame["h"]) if frame else "audio"+ fit = str((tpl.get("frame") or {}).get("fit") or "-")+ loud = ("%g LUFS" % spec["lufs"]) if spec.get("lufs") is not None else "-"+ print("%-15s %-11s %-5s %7s %-10s %s" % (name, size, fit, ("%gs" % dur) if dur else "-", loud, zones or "none"))+++# `--template all`: every destination a single edit is normally posted to. The podcast template+# is audio-only and youtube-shorts is an alias of shorts, so neither belongs in a video pack.+PACK_DEFAULT = ["tiktok", "reels", "shorts", "youtube", "x", "linkedin", "facebook"]+++def expand_templates(value: str) -> List[str]:+ if value.strip() == "all":+ return list(PACK_DEFAULT)+ names = [n.strip() for n in value.split(",") if n.strip()]+ if not names:+ die("--template needs a name, a comma-separated list, or 'all'")+ known = template_names()+ seen: List[str] = []+ for name in names:+ # the spellings people write resolve to the destination they mean, the same way+ # check.py --platform and export.py --preset take them (scripts/_platforms.py)+ if name not in known:+ name = resolve_platform(name) or name+ if name not in known:+ die(f"unknown template {name!r}", hint="templates: " + ", ".join(known) + " (or 'all')")+ if name not in seen:+ seen.append(name)+ return seen+++def render_pack(names: List[str], args) -> int:+ """The social pack: one edit delivered to every named destination, plus a table of what+ was written. Each destination is a full render (its own frame, captions, loudness, export+ and platform check), so the pack reports per-platform results rather than one verdict."""+ stem = Path(args.input).with_suffix("").name+ outdir = Path(args.output).parent if args.output else Path(args.input).resolve().parent+ dests = {name: str((load_template(name).get("check") or {}).get("platform") or name) for name in names}+ rows: List[Dict[str, Any]] = []+ outputs: List[str] = []+ failed: List[str] = []+ for name in names:+ # the destination decides the container: an audio-only destination in a pack must not be+ # handed a .mp4 name the single-template form would never have written (review 12)+ dest_out = str(outdir / (stem + "_" + name + template_ext(dests[name])))+ 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)):+ if value:+ argv += [flag, str(value)]+ info(f"→ pack: {name}")+ proc = run_tool(argv + child_args() + ["--json"])+ try:+ doc = json.loads(proc.stdout.strip() or "{}")+ except ValueError:+ doc = {}+ # the child ran with --json, so its planned commands come back in the document: the pack+ # is the one path that writes seven files, and --dry-run has to show all of them+ for line in proc.stderr.splitlines():+ if line.startswith("$ ") or line.startswith("[dry-run]"):+ STATE.commands.append(line[2:] if line.startswith("$ ") else line)+ STATE.commands.extend(str(c) for c in (doc.get("commands") or []))+ out = doc.get("output") or dest_out+ chk = doc.get("check") or {}+ ok = proc.returncode == 0 and doc.get("status") == "completed"+ probe_doc = doc.get("probe") or {}+ if STATE.dry_run:+ # A dry run encoded nothing and verified nothing. Reading a size off a file left over+ # from an earlier real run, or calling an unrun check "pass", reports a verification+ # result for a run that never happened (review 12).+ rows.append({"platform": name, "file": os.path.basename(out), "path": out,+ "size_bytes": None, "duration": None, "check": "planned", "ok": bool(ok)})+ continue+ size = os.path.getsize(out) if os.path.exists(out) else 0+ rows.append({"platform": name, "file": os.path.basename(out), "path": out,+ "size_bytes": size, "duration": probe_doc.get("duration"),+ "check": ("pass" if chk.get("ok") else ("%d FAIL" % chk["failed"]) if chk.get("failed") else ("pass" if ok else "failed")),+ "ok": bool(ok)})+ outputs.append(out)+ if not ok:+ failed.append(name)+ pack = str(outdir / f"{stem}_pack.md")+ lines = [f"# Social pack — {stem}", "",+ "| platform | file | size | duration | check |", "|---|---|---|---|---|"]+ for r in rows:+ dur = f"{r['duration']:.2f} s" if r.get("duration") else "-"+ mb = f"{r['size_bytes'] / 1024 / 1024:.1f} MB" if r.get("size_bytes") else "-"+ lines.append(f"| {r['platform']} | {r['file']} | {mb} | {dur} | {r['check']} |")+ lines += ["", f"{len(rows)} destinations from one edit ({os.path.basename(args.input)}).",+ "Rendered by ffmpeg-skill; `report.py --pack` turns this table into an HTML report."]+ if not STATE.dry_run:+ Path(pack).write_text("\n".join(lines) + "\n", encoding="utf-8")+ info(("[dry-run] would write " if STATE.dry_run else "wrote ") + pack)+ if failed:+ die(f"pack: {len(failed)} of {len(rows)} destinations failed: {', '.join(failed)}",+ kind="verification", output=pack, dry_run=STATE.dry_run, pack=rows, outputs=outputs)+ emit(pack, pack=rows, outputs=outputs, stages=["pack"],+ verification=[{"step": "check", "ok": r["ok"], "platform": r["platform"]} for r in rows])+ return 0++def check_keys(obj: Any, schema: str, label: str) -> None:"""Refuse an unrecognised key, naming the object, the key and the nearest valid one."""if not isinstance(obj, dict):@@ -275,29 +498,74 @@ def main() -> int:ap.add_argument("--work", help="work directory for intermediates (default: <output>_work)")ap.add_argument("--keep", action="store_true", help="keep intermediates (default: kept only when --work is given)")ap.add_argument("--stop-after", choices=["clips", "join", "silence", "fit", "captions", "graphics", "overlays", "audio", "loudness", "export"], help="stop after this stage (for iterating)")+ tpl = ap.add_argument_group("delivery templates (one command per destination)")+ tpl.add_argument("--template", metavar="NAME", help="render INPUT with a shipped template: " + ", ".join(template_names())+ + ", a comma-separated list, or 'all' (the social pack)")+ tpl.add_argument("--list-templates", action="store_true", help="print the templates with their frames, limits and safe zones, and exit")+ tpl.add_argument("--cues", help="cue file for the template's captions (caption.py --text format)")+ tpl.add_argument("--srt", help="SRT file for the template's captions instead of --cues")+ tpl.add_argument("--logo", help="logo image the template overlays")+ 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("--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 "+ "or 'all' its directory is where the pack is written")+ tpl.add_argument("--write-project", metavar="FILE", help="write the filled project.json for editing and stop (no render)")add_common(ap)args = ap.parse_args()apply_common(args)+ if args.list_templates:+ list_templates()+ return 0if args.init:Path(args.init).write_text(json.dumps(TEMPLATE, indent=2) + "\n", encoding="utf-8")info(f"wrote {args.init}; edit clips/src and run: render.py {args.init}")print(args.init)return 0if not args.project:- die("give a project.json (or --init FILE)")+ die("give a project.json (or --init FILE, or --template NAME INPUT)")if STATE.plan:die("render.py has no --plan: the project file is the plan (use --dry-run to preview it)")- try:- proj: Dict[str, Any] = json.loads(Path(args.project).read_text(encoding="utf-8"))- except (OSError, ValueError) as exc:- die(f"cannot read project: {exc}")- if not isinstance(proj, dict):- die(f"{args.project}: not a project or plan object (top level is {type(proj).__name__})")- if "plan_version" in proj:- return execute_plan(proj, os.path.abspath(args.project))+ if args.template:+ # `render.py --template tiktok talk.mp4 ...`: the positional is the footage, not a project.+ args.input = args.project+ if not os.path.isfile(args.input):+ die(f"input not found: {args.input}")+ names = expand_templates(args.template)+ if len(names) > 1:+ if args.write_project:+ die("--write-project writes one project; name a single template")+ return render_pack(names, args)+ proj: Dict[str, Any] = template_project(names[0], args)+ base = Path.cwd()+ 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)):+ if value:+ die(f"{flag} belongs to --template NAME INPUT; a project.json states it in the project itself")+ try:+ proj = json.loads(Path(args.project).read_text(encoding="utf-8"))+ except (OSError, ValueError) as exc:+ die(f"cannot read project: {exc}")+ if not isinstance(proj, dict):+ die(f"{args.project}: not a project or plan object (top level is {type(proj).__name__})")+ if "plan_version" in proj:+ return execute_plan(proj, os.path.abspath(args.project))+ base = Path(args.project).resolve().parentvalidate_project(proj)- base = Path(args.project).resolve().parent+ if args.write_project:+ # Only the filled project: the point is to edit it before rendering, so nothing runs.+ try:+ Path(args.write_project).write_text(json.dumps(proj, indent=2) + "\n", encoding="utf-8")+ except OSError as exc:+ die(f"cannot write {args.write_project}: {exc}", kind="output")+ info(f"wrote {args.write_project}; edit it and run: render.py {args.write_project}")+ emit(args.write_project, template=args.template, stages=[], check=None)+ return 0def rel(p: Any) -> str:p = str(p)@@ -330,10 +598,20 @@ def main() -> int:import atexitimport shutilatexit.register(lambda: shutil.rmtree(work, ignore_errors=True))+ # Intermediates keep the delivery's media kind: a .mp4 project is unchanged (every stage file+ # is still clipNN.mp4 / fit.mp4 / loudnorm.mp4), while an audio-only delivery (the podcast+ # template) carries its stages through the audio container instead of a video one.+ mid = Path(output).suffix.lower() if Path(output).suffix.lower() in AUDIO_EXT else ".mp4"frame = dict(proj.get("frame") or {})trans = proj.get("transition") or {}frame_from_preset(frame, proj.get("export") or {})brand_args: List[str] = ["--brand", rel(proj["brand"])] if proj.get("brand") else []+ # A project written from a delivery template names its destination, so the caption and+ # graphics stages are told which zones that app's UI covers; the template's own explicit+ # margin/size still win inside those tools. A hand-written project (no "template" key) is+ # unchanged -- it never gets a --platform it did not ask for.+ dest = str(((proj.get("check") or {}).get("platform") or "")) if proj.get("template") else ""+ platform_args: List[str] = ["--platform", dest] if dest in PLATFORMS and PLATFORMS[dest].get("frame") else []stages_done: List[str] = []# ---- clips@@ -345,7 +623,7 @@ def main() -> int:if not STATE.dry_run:probe(src)needs_cut = c.get("in") is not None or c.get("out") is not None- part = str(work / f"clip{i:02d}.mp4")+ part = str(work / f"clip{i:02d}{mid}")if needs_cut:argv: List[Any] = [src, "-o", part, "--accurate"]if c.get("in") is not None:@@ -361,7 +639,7 @@ def main() -> int:die(f"clip {i}: speed must be a positive number, got {c['speed']!r}")if abs(spd - 1.0) > 1e-6: # speed 1.0 used to cost a full re-encode for nothingdur = (probe(part).get("duration") or 0.0) if not STATE.dry_run else 10.0- fitted = str(work / f"clip{i:02d}_speed.mp4")+ fitted = str(work / f"clip{i:02d}_speed{mid}")sh("fit.py", part, "--duration", f"{dur / spd:.3f}", "-o", fitted)part = fittedparts.append(part)@@ -373,7 +651,7 @@ def main() -> int:# ---- joinif len(parts) > 1:- current = str(work / "joined.mp4")+ current = str(work / f"joined{mid}")argv = list(parts) + ["-o", current, "--transition", trans.get("type", "fade"), "--duration", str(trans.get("duration", 0.5))]if frame.get("width"):argv += ["--width", str(frame["width"])]@@ -390,7 +668,7 @@ def main() -> int:# ---- silencesil = proj.get("silence")if sil:- nxt = str(work / "tight.mp4")+ nxt = str(work / f"tight{mid}")argv = [current, "-o", nxt]for k, flag in (("threshold", "--threshold"), ("min_silence", "--min-silence"), ("margin", "--margin")):if sil.get(k) is not None:@@ -406,6 +684,8 @@ def main() -> int:fit = dict(proj.get("fit") or {})if frame.get("aspect"):fit.setdefault("aspect", frame["aspect"])+ if frame.get("fit"):+ fit.setdefault("fit", frame["fit"])if frame.get("width") and len(parts) == 1:fit.setdefault("width", frame["width"])if frame.get("height") and len(parts) == 1:@@ -413,7 +693,7 @@ def main() -> int:if frame.get("fps") and len(parts) == 1:fit.setdefault("fps", frame["fps"])if fit:- nxt = str(work / "fit.mp4")+ nxt = str(work / f"fit{mid}")argv = [current, "-o", nxt]for k, flag in (("duration", "--duration"), ("method", "--method"), ("aspect", "--aspect"), ("fit", "--fit"), ("width", "--width"), ("height", "--height"), ("fps", "--fps"), ("smooth", "--smooth")):if fit.get(k) is not None:@@ -428,7 +708,7 @@ def main() -> int:# ---- captionscap = proj.get("captions")if cap:- nxt = str(work / "captioned.mp4")+ nxt = str(work / f"captioned{mid}")argv = [current, "-o", nxt]if cap.get("text"):argv += ["--text", rel(cap["text"])]@@ -444,7 +724,7 @@ def main() -> int:for k, flag in (("karaoke", "--karaoke"), ("bold", "--bold"), ("box", "--box")):if cap.get(k):argv.append(flag)- sh("caption.py", *(argv + brand_args))+ sh("caption.py", *(argv + brand_args + platform_args))current = nxtstages_done.append("captions")if args.stop_after == "captions":@@ -453,14 +733,16 @@ def main() -> int:# ---- graphicsfor i, g in enumerate(proj.get("graphics") or []):- nxt = str(work / f"graphics{i:02d}.mp4")+ nxt = str(work / f"graphics{i:02d}{mid}")if not g.get("template"):die(f"graphics[{i}] needs a template")argv = [current, "-o", nxt, "--template", g["template"]]- for k, flag in (("name", "--name"), ("title", "--title"), ("subtitle", "--subtitle"), ("start", "--start"), ("end", "--end"), ("position", "--position"), ("from", "--from"), ("scale", "--scale"), ("primary", "--primary"), ("text_color", "--text-color"), ("lang", "--lang")):+ for k, flag in (("name", "--name"), ("title", "--title"), ("subtitle", "--subtitle"), ("start", "--start"), ("end", "--end"), ("position", "--position"), ("from", "--from"), ("scale", "--scale"), ("primary", "--primary"), ("text_color", "--text-color"), ("lang", "--lang"),+ ("text", "--text"), ("top", "--top"), ("bottom", "--bottom"), ("duration", "--duration"), ("margin", "--margin"), ("platform", "--platform")):if g.get(k) is not None:argv += [flag, str(g[k])]- sh("graphics.py", *(argv + brand_args))+ # the entry's own "platform" is the more specific statement than the template's destination+ sh("graphics.py", *(argv + brand_args + ([] if g.get("platform") else platform_args)))current = nxtif "graphics" not in stages_done:stages_done.append("graphics")@@ -470,7 +752,7 @@ def main() -> int:# ---- overlaysfor i, ov in enumerate(proj.get("overlays") or []):- nxt = str(work / f"overlay{i:02d}.mp4")+ nxt = str(work / f"overlay{i:02d}{mid}")argv = [current, "-o", nxt]if ov.get("logo"):argv.append("--logo")@@ -480,12 +762,14 @@ def main() -> int:argv += ["--text", ov["text"]]else:die(f"overlays[{i}] needs image or text")- for k, flag in (("position", "--position"), ("start", "--start"), ("end", "--end"), ("fade", "--fade"), ("opacity", "--opacity"), ("scale", "--scale"), ("font_size", "--font-size"), ("font", "--font"), ("font_file", "--font-file"), ("margin", "--margin")):+ for k, flag in (("position", "--position"), ("start", "--start"), ("end", "--end"), ("fade", "--fade"), ("opacity", "--opacity"), ("scale", "--scale"), ("font_size", "--font-size"), ("font", "--font"), ("font_file", "--font-file"), ("margin", "--margin"), ("platform", "--platform")):if ov.get(k) is not None:argv += [flag, str(ov[k])]if ov.get("box"):argv.append("--box")- sh("overlay.py", *(argv + brand_args))+ # review 12: the overlay stage was the one stage that never heard which destination this+ # is, so a template's top-left logo landed 24 px in -- under TikTok's own status bar.+ sh("overlay.py", *(argv + brand_args + ([] if ov.get("platform") else platform_args)))current = nxtif "overlays" not in stages_done:stages_done.append("overlays")@@ -509,7 +793,7 @@ def main() -> int:for stem, key in (("dialogue", "gain"), ("music", "music_volume"), ("effects", "effects_volume")):if stems.get(stem) is not None:au.setdefault(key, stems[stem])- nxt = str(work / "audio.mp4")+ nxt = str(work / f"audio{mid}")argv = [current, "-o", nxt]for k, flag in (("music", "--music"), ("replace", "--replace"), ("effects", "--effects")):if au.get(k):@@ -533,7 +817,7 @@ def main() -> int:# ---- loudnessld = proj.get("loudness")if ld:- nxt = str(work / "loudnorm.mp4")+ nxt = str(work / f"loudnorm{mid}")argv = [current, "-o", nxt]if ld.get("lufs") is not None:argv += ["-I", str(ld["lufs"])]diff --git a/scripts/report.py b/scripts/report.pyindex 0ae8e3b..051d0d9 100755--- a/scripts/report.py+++ b/scripts/report.py@@ -7,6 +7,7 @@ Examples:python3 report.py --before raw.mov --after final.mp4 -o report.htmlpython3 report.py --after final.mp4 --platform reels --title "Episode 12 — Reels cut" -o report.htmlpython3 report.py --before raw.mov --after final.mp4 --commands commands.txt --notes notes.md+ python3 report.py --pack talk_pack.md -o pack.html # the social pack table as HTML"""import argparseimport base64@@ -79,9 +80,76 @@ def media_rows(meta: Dict[str, Any], ld: Dict[str, Any]) -> List[List[str]]:return rows+PACK_CSS = """+ :root{--bg:#F4F6F8;--paper:#fff;--ink:#161B21;--ink2:#4B5661;--line:#D8DEE4;--ok:#2C8A5B;--bad:#B4362F}+ @media (prefers-color-scheme:dark){:root{--bg:#111518;--paper:#191E23;--ink:#E8ECEF;--ink2:#AEB6BE;--line:#2A3138;--ok:#5CC38C;--bad:#F07A73}}+ body{margin:0;background:var(--bg);color:var(--ink);font:15px/1.6 system-ui,-apple-system,"Segoe UI",Roboto,"Noto Sans JP",sans-serif}+ .wrap{max-width:900px;margin:0 auto;padding:32px 20px 60px}+ h1{font-size:24px;margin:0 0 16px}+ table{border-collapse:collapse;width:100%;font-size:14px;background:var(--paper);border:1px solid var(--line);border-radius:6px;overflow:hidden}+ th,td{text-align:left;padding:7px 10px;border-bottom:1px solid var(--line)}th{color:var(--ink2);font-weight:500}+ td.pass{color:var(--ok);font-weight:600}td.bad{color:var(--bad);font-weight:600}+ p.note{color:var(--ink2);font-size:13px}+ .foot{color:var(--ink2);font-size:12px;margin-top:30px;border-top:1px solid var(--line);padding-top:10px}+"""+++def pack_report(args) -> int:+ """render.py --template all writes <stem>_pack.md: one row per destination. This renders the+ same rows as HTML, so a pack can be handed over the way a single delivery report is -- no+ re-measurement, because the pack table is what the renders actually produced."""+ text = read_text_or_die(args.pack, "--pack")+ rows: List[List[str]] = []+ header: List[str] = []+ for line in text.splitlines():+ line = line.strip()+ if not line.startswith("|"):+ continue+ cells = [c.strip() for c in line.strip("|").split("|")]+ if all(set(c) <= set("-: ") for c in cells):+ continue+ if not header:+ header = cells+ else:+ rows.append(cells)+ if not rows:+ die(f"{args.pack}: no pack table found (expected the Markdown table render.py --template all writes)")+ title = args.title or f"Social pack — {Path(args.pack).stem.replace('_pack', '')}"+ output = args.output or str(Path(args.pack).with_suffix(".html"))+ head = "".join(f"<th>{html.escape(h)}</th>" for h in header)+ body = ""+ for r in rows:+ cells = ""+ for i, c in enumerate(r):+ cls = ""+ if header[i:i + 1] == ["check"]:+ cls = " class='pass'" if c.lower() == "pass" else " class='bad'"+ cells += f"<td{cls}>{html.escape(c)}</td>"+ body += f"<tr>{cells}</tr>"+ doc = ("<!doctype html><html><head><meta charset='utf-8'><meta name='viewport' content='width=device-width,initial-scale=1'>"+ f"<title>{html.escape(title)}</title><style>{PACK_CSS}</style></head><body><div class='wrap'>"+ f"<h1>{html.escape(title)}</h1><table><tr>{head}</tr>{body}</table>"+ f"<p class='note'>{len(rows)} destination(s) from one edit.</p>"+ "<p class='foot'>Generated by ffmpeg-skill · local FFmpeg, no cloud.</p></div></body></html>")+ if STATE.dry_run:+ info(f"wrote {output}")+ else:+ try:+ Path(output).write_text(doc, encoding="utf-8")+ except OSError as e:+ die(f"cannot write {output}: {e}", kind="output")+ info(f"wrote {output} ({os.path.getsize(output) / 1024:.0f} KB)")+ emit(None, report=output, pack=[dict(zip(header, r)) for r in rows], check=None,+ verification=([{"step": "exists", "ok": True}] if not STATE.dry_run else []))+ if not args.json:+ print(output)+ return 0++def main() -> int:ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)- ap.add_argument("--after", required=True, help="the deliverable")+ ap.add_argument("--after", help="the deliverable (required unless --pack is given)")+ ap.add_argument("--pack", metavar="FILE", help="a social pack table written by render.py --template all (<stem>_pack.md): render it as HTML")ap.add_argument("--before", help="the source (optional)")ap.add_argument("-o", "--output", help="report path (default: <after>_report.html)")ap.add_argument("--title", help="report title")@@ -93,6 +161,10 @@ def main() -> int:args = ap.parse_args()apply_common(args)+ if args.pack:+ return pack_report(args)+ if not args.after:+ die("--after is required (or --pack FILE for a social pack table)")after = probe(args.after)before = probe(args.before) if args.before else Noneld_after = loudness(args.after) if after.get("audio") else {}diff --git a/templates/facebook.json b/templates/facebook.jsonnew file mode 100644index 0000000..557322f--- /dev/null+++ b/templates/facebook.json@@ -0,0 +1,47 @@+{+ "template": "facebook",+ "output": "$OUTPUT",+ "clips": [+ {+ "src": "$INPUT"+ }+ ],+ "frame": {+ "aspect": "16:9",+ "fit": "pad"+ },+ "brand": "$BRAND",+ "captions": {+ "text": "$CUES",+ "animate": "none",+ "karaoke": false,+ "size": 20,+ "position": "bottom",+ "margin": 14+ },+ "graphics": [+ {+ "template": "lower-third",+ "name": "$TITLE",+ "start": 1,+ "end": 6+ }+ ],+ "overlays": [+ {+ "image": "$LOGO",+ "position": "top-left"+ }+ ],+ "loudness": {+ "lufs": -14,+ "tp": -1.0+ },+ "export": {+ "preset": "facebook",+ "normalize": true+ },+ "check": {+ "platform": "facebook"+ }+}diff --git a/templates/linkedin.json b/templates/linkedin.jsonnew file mode 100644index 0000000..73486e3--- /dev/null+++ b/templates/linkedin.json@@ -0,0 +1,47 @@+{+ "template": "linkedin",+ "output": "$OUTPUT",+ "clips": [+ {+ "src": "$INPUT"+ }+ ],+ "frame": {+ "aspect": "1:1",+ "fit": "crop"+ },+ "brand": "$BRAND",+ "captions": {+ "text": "$CUES",+ "animate": "none",+ "karaoke": false,+ "size": 20,+ "position": "bottom",+ "margin": 14+ },+ "graphics": [+ {+ "template": "lower-third",+ "name": "$TITLE",+ "start": 1,+ "end": 6+ }+ ],+ "overlays": [+ {+ "image": "$LOGO",+ "position": "top-left"+ }+ ],+ "loudness": {+ "lufs": -14,+ "tp": -1.0+ },+ "export": {+ "preset": "linkedin",+ "normalize": true+ },+ "check": {+ "platform": "linkedin"+ }+}diff --git a/templates/podcast.json b/templates/podcast.jsonnew file mode 100644index 0000000..e0ed100--- /dev/null+++ b/templates/podcast.json@@ -0,0 +1,22 @@+{+ "template": "podcast",+ "output": "$OUTPUT",+ "clips": [+ {+ "src": "$INPUT"+ }+ ],+ "silence": {+ "threshold": -40,+ "min_silence": 1.0,+ "margin": 0.15+ },+ "loudness": {+ "lufs": -16,+ "tp": -1+ },+ "chapters": "$CHAPTERS",+ "check": {+ "platform": "podcast"+ }+}diff --git a/templates/reels.json b/templates/reels.jsonnew file mode 100644index 0000000..01d03d4--- /dev/null+++ b/templates/reels.json@@ -0,0 +1,47 @@+{+ "template": "reels",+ "output": "$OUTPUT",+ "clips": [+ {+ "src": "$INPUT"+ }+ ],+ "frame": {+ "aspect": "9:16",+ "fit": "crop"+ },+ "brand": "$BRAND",+ "captions": {+ "text": "$CUES",+ "animate": "pop",+ "karaoke": true,+ "size": 24,+ "position": "bottom",+ "margin": 58+ },+ "graphics": [+ {+ "template": "hook",+ "title": "$TITLE",+ "start": 0,+ "end": 3+ }+ ],+ "overlays": [+ {+ "image": "$LOGO",+ "position": "top-left"+ }+ ],+ "loudness": {+ "lufs": -14,+ "tp": -1.0+ },+ "export": {+ "preset": "reels",+ "normalize": true+ },+ "check": {+ "platform": "reels"+ }+}diff --git a/templates/shorts.json b/templates/shorts.jsonnew file mode 100644index 0000000..65fba1b--- /dev/null+++ b/templates/shorts.json@@ -0,0 +1,47 @@+{+ "template": "shorts",+ "output": "$OUTPUT",+ "clips": [+ {+ "src": "$INPUT"+ }+ ],+ "frame": {+ "aspect": "9:16",+ "fit": "crop"+ },+ "brand": "$BRAND",+ "captions": {+ "text": "$CUES",+ "animate": "pop",+ "karaoke": true,+ "size": 24,+ "position": "bottom",+ "margin": 52+ },+ "graphics": [+ {+ "template": "hook",+ "title": "$TITLE",+ "start": 0,+ "end": 3+ }+ ],+ "overlays": [+ {+ "image": "$LOGO",+ "position": "top-left"+ }+ ],+ "loudness": {+ "lufs": -14,+ "tp": -1.0+ },+ "export": {+ "preset": "shorts",+ "normalize": true+ },+ "check": {+ "platform": "shorts"+ }+}diff --git a/templates/tiktok.json b/templates/tiktok.jsonnew file mode 100644index 0000000..845973f--- /dev/null+++ b/templates/tiktok.json@@ -0,0 +1,47 @@+{+ "template": "tiktok",+ "output": "$OUTPUT",+ "clips": [+ {+ "src": "$INPUT"+ }+ ],+ "frame": {+ "aspect": "9:16",+ "fit": "crop"+ },+ "brand": "$BRAND",+ "captions": {+ "text": "$CUES",+ "animate": "pop",+ "karaoke": true,+ "size": 24,+ "position": "bottom",+ "margin": 63+ },+ "graphics": [+ {+ "template": "hook",+ "title": "$TITLE",+ "start": 0,+ "end": 3+ }+ ],+ "overlays": [+ {+ "image": "$LOGO",+ "position": "top-left"+ }+ ],+ "loudness": {+ "lufs": -14,+ "tp": -1.0+ },+ "export": {+ "preset": "tiktok",+ "normalize": true+ },+ "check": {+ "platform": "tiktok"+ }+}diff --git a/templates/x.json b/templates/x.jsonnew file mode 100644index 0000000..62276b4--- /dev/null+++ b/templates/x.json@@ -0,0 +1,47 @@+{+ "template": "x",+ "output": "$OUTPUT",+ "clips": [+ {+ "src": "$INPUT"+ }+ ],+ "frame": {+ "aspect": "16:9",+ "fit": "pad"+ },+ "brand": "$BRAND",+ "captions": {+ "text": "$CUES",+ "animate": "none",+ "karaoke": false,+ "size": 20,+ "position": "bottom",+ "margin": 14+ },+ "graphics": [+ {+ "template": "lower-third",+ "name": "$TITLE",+ "start": 1,+ "end": 6+ }+ ],+ "overlays": [+ {+ "image": "$LOGO",+ "position": "top-left"+ }+ ],+ "loudness": {+ "lufs": -14,+ "tp": -1.0+ },+ "export": {+ "preset": "x",+ "normalize": true+ },+ "check": {+ "platform": "x"+ }+}diff --git a/templates/youtube-shorts.json b/templates/youtube-shorts.jsonnew file mode 100644index 0000000..a6740fc--- /dev/null+++ b/templates/youtube-shorts.json@@ -0,0 +1,47 @@+{+ "template": "youtube-shorts",+ "output": "$OUTPUT",+ "clips": [+ {+ "src": "$INPUT"+ }+ ],+ "frame": {+ "aspect": "9:16",+ "fit": "crop"+ },+ "brand": "$BRAND",+ "captions": {+ "text": "$CUES",+ "animate": "pop",+ "karaoke": true,+ "size": 24,+ "position": "bottom",+ "margin": 52+ },+ "graphics": [+ {+ "template": "hook",+ "title": "$TITLE",+ "start": 0,+ "end": 3+ }+ ],+ "overlays": [+ {+ "image": "$LOGO",+ "position": "top-left"+ }+ ],+ "loudness": {+ "lufs": -14,+ "tp": -1.0+ },+ "export": {+ "preset": "shorts",+ "normalize": true+ },+ "check": {+ "platform": "shorts"+ }+}diff --git a/templates/youtube.json b/templates/youtube.jsonnew file mode 100644index 0000000..90d6f6d--- /dev/null+++ b/templates/youtube.json@@ -0,0 +1,47 @@+{+ "template": "youtube",+ "output": "$OUTPUT",+ "clips": [+ {+ "src": "$INPUT"+ }+ ],+ "frame": {+ "aspect": "16:9",+ "fit": "pad"+ },+ "brand": "$BRAND",+ "captions": {+ "text": "$CUES",+ "animate": "none",+ "karaoke": false,+ "size": 20,+ "position": "bottom",+ "margin": 14+ },+ "graphics": [+ {+ "template": "lower-third",+ "name": "$TITLE",+ "start": 1,+ "end": 6+ }+ ],+ "overlays": [+ {+ "image": "$LOGO",+ "position": "top-left"+ }+ ],+ "loudness": {+ "lufs": -14,+ "tp": -1.0+ },+ "export": {+ "preset": "youtube",+ "normalize": true+ },+ "check": {+ "platform": "youtube"+ }+}diff --git a/tests/fixtures/mcp_tools.json b/tests/fixtures/mcp_tools.jsonindex b798447..4bc35d5 100644--- a/tests/fixtures/mcp_tools.json+++ b/tests/fixtures/mcp_tools.json@@ -171,6 +171,7 @@"output","overwrite","plan",+ "platform","position","preset","progress",@@ -475,11 +476,13 @@"properties": ["argv","audio_stream",+ "bottom","brand","codec","count_from","crf","dry_run",+ "duration","end","fast","font",@@ -488,10 +491,12 @@"json","json_brief","lang",+ "margin","name","output","overwrite","plan",+ "platform","position","preset","primary",@@ -501,9 +506,11 @@"start","subtitle","template",+ "text","text_color","timeout",- "title"+ "title",+ "top"],"required": []},@@ -615,6 +622,7 @@"overwrite","plan","progress",+ "safe","tiles","timeout","width"@@ -756,6 +764,7 @@"output","overwrite","plan",+ "platform","position","preset","progress",@@ -870,19 +879,30 @@"name": "render","properties": ["argv",+ "brand",+ "chapters",+ "cues","dry_run","fast",+ "fit","init","json","json_brief","keep",+ "list_templates",+ "logo",+ "output","overwrite","plan","progress","project",+ "srt","stop_after",+ "template","timeout",- "work"+ "title",+ "work",+ "write_project"],"required": []},@@ -901,6 +921,7 @@"notes","output","overwrite",+ "pack","plan","platform","progress",diff --git a/tests/test_all.py b/tests/test_all.pyindex 8d7b5e9..6502518 100644--- a/tests/test_all.py+++ b/tests/test_all.py@@ -3608,6 +3608,427 @@ class FFmpegSkillTests(unittest.TestCase):self.assertNotEqual(a[200:4000], b[200:4000])script("graphics.py", self.src, "--template", "lower-third", expect_fail=True)+ # ------------------------------------------------------- delivery templates (1.14)+ def _region_stats(self, path, crop, at=1.0):+ """Mean luma and spread of one region of a frame, as signalstats reports them."""+ proc = sh("ffmpeg", "-hide_banner", "-loglevel", "error", "-ss", str(at), "-i", str(path), "-frames:v", "1",+ "-vf", f"crop={crop},signalstats,metadata=print:file=-", "-f", "null", "-")+ vals = {k: float(v) for k, v in re.findall(r"lavfi\.signalstats\.(YAVG|YMIN|YMAX)=([0-9.]+)", proc.stdout)}+ return vals["YAVG"], vals["YMAX"] - vals["YMIN"]++ def test_every_delivery_template_renders_and_passes_its_own_check(self):+ """1.14: `render.py --template NAME INPUT` is the one command a delivery request becomes,+ so every shipped template has to survive its own pipeline on real footage and come back+ with its own platform's check passing -- the frame, the caption burn, the loudness pass,+ 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")+ for name in names:+ with self.subTest(template=name):+ src = self.mic if name == "podcast" 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)]+ doc = json.loads(script("render.py", *argv).stdout)+ self.assertEqual(doc["status"], "completed")+ self.assertTrue(os.path.exists(doc["output"]), doc["output"])+ self.assertTrue(doc["check"]["ok"],+ f"{name}: {[r for r in doc['check']['checks'] if r['status'] == 'FAIL']}")+ platform = json.loads((ROOT / "templates" / f"{name}.json").read_text())["check"]["platform"]+ self.assertEqual(doc["check"]["platform"], platform)++ def test_template_keeps_caption_and_graphic_out_of_the_platform_safe_zone(self):+ """The whole point of the table's safe zones: TikTok draws its description block over the+ bottom 22 % of the frame and its like/comment column over the right 14 %. A caption burned+ at the historical margin sits under the description; a right-hand graphic sits under the+ buttons. Asserted on the planned commands (--dry-run --json), which is where the ASS+ MarginV and the drawtext x actually are."""+ sys.path.insert(0, str(SCRIPTS))+ from _platforms import PLATFORMS, ass_units+ safe = PLATFORMS["tiktok"]["safe"]+ proj = OUT / "safe_project.json"+ script("render.py", self.src, "--template", "tiktok", "--cues", self.cues,+ "--write-project", proj, "-o", str(OUT / "safe_out.mp4"))+ cap = json.loads(proj.read_text())["captions"]+ self.assertEqual(cap["margin"], ass_units(safe["bottom"]), "the template's caption margin is the safe zone")+ # the burn itself: the generated .ass carries MarginV in the same 288-unit grid, scaled+ plan = json.loads(script("render.py", proj, "--dry-run", "--json").stdout)+ ass_lines = [c for c in plan["commands"] if "captioned.ass" in c]+ self.assertTrue(ass_lines, plan["commands"])+ # the ASS grid is 288 lines, so a fraction of the frame lands on the nearest of ~6.7 px+ margin_px = round(cap["margin"] * 1920 / 288)+ self.assertGreaterEqual(margin_px, round(safe["bottom"] * 1920) - 1920 / 288,+ "the caption's baseline margin must clear TikTok's description bar")+ # a right-positioned graphic: drawtext's x must leave the like column free+ gfx = json.loads(script("graphics.py", self.src, "--template", "bug", "--title", "@handle",+ "--position", "top-right", "--platform", "tiktok", "--dry-run", "--json",+ "-o", str(OUT / "safe_bug.mp4")).stdout)+ W, H = 1280, 720 # the fixture's own frame: the margins are fractions of it+ drawtext = [c for c in gfx["commands"] if "drawtext" in c][0]+ m = re.search(r"x=w-text_w-(\d+)", drawtext)+ self.assertTrue(m, drawtext)+ self.assertGreaterEqual(int(m.group(1)), round(safe["right"] * W) - 1,+ "a right-hand graphic must sit left of TikTok's like column")+ m = re.search(r"y=(\d+):box", drawtext)+ self.assertGreaterEqual(int(m.group(1)), round(safe["top"] * H) - 1)++ def test_list_templates_names_every_template_with_its_safe_zones(self):+ out = script("render.py", "--list-templates").stdout+ sys.path.insert(0, str(SCRIPTS))+ from _platforms import PLATFORMS+ for path in sorted((ROOT / "templates").glob("*.json")):+ self.assertIn(path.stem, out)+ for edge, frac in PLATFORMS["tiktok"]["safe"].items():+ self.assertIn(f"{edge} {frac:.2f}", out, f"--list-templates must state tiktok's {edge} safe zone")+ self.assertIn("1080x1920", out)+ script("render.py", self.src, "--template", "myspace", expect_fail=True)++ def test_write_project_writes_a_project_render_accepts(self):+ """--write-project is the "let me edit it first" path: it must write a project the real+ renderer takes without a single further change, and render nothing itself."""+ proj = OUT / "wp_project.json"+ out = OUT / "wp_out.mp4"+ out.unlink(missing_ok=True)+ doc = json.loads(script("render.py", self.src, "--template", "reels", "--cues", self.cues,+ "--write-project", proj, "-o", out, "--json").stdout)+ self.assertEqual(doc["output"], str(proj))+ self.assertFalse(out.exists(), "--write-project renders nothing")+ loaded = json.loads(proj.read_text())+ self.assertEqual(loaded["template"], "reels")+ self.assertEqual(loaded["clips"][0]["src"], str(self.src.resolve()))+ plan = json.loads(script("render.py", proj, "--dry-run", "--json").stdout)+ self.assertEqual(plan["status"], "completed")+ self.assertIn("export", plan["stages"])++ def test_social_pack_writes_one_file_per_destination_and_a_table(self):+ """--template all / a comma list: one edit, N deliveries, one table. The table is what the+ user is handed, so it must have exactly one row per destination and name the real files."""+ doc = json.loads(script("render.py", self.src, "--template", "tiktok,x,linkedin",+ "--cues", self.cues, "--fast", "--json").stdout)+ self.assertEqual([r["platform"] for r in doc["pack"]], ["tiktok", "x", "linkedin"])+ for row in doc["pack"]:+ self.assertTrue(os.path.exists(row["path"]), row)+ self.assertEqual(row["check"], "pass", row)+ pack = Path(doc["output"])+ self.assertTrue(pack.exists())+ body = pack.read_text(encoding="utf-8")+ rows = [l for l in body.splitlines() if l.startswith("|") and not set(l.strip("| ")) <= set("-: |")]+ self.assertEqual(len(rows), 4, "one header row plus one row per destination")+ html_out = OUT / "pack.html"+ script("report.py", "--pack", pack, "-o", html_out)+ html_text = html_out.read_text(encoding="utf-8")+ for name in ("tiktok", "x", "linkedin"):+ self.assertIn(name, html_text)++ def test_export_presets_per_destination_are_distinct_and_hdr_av1_refuse_honestly(self):+ """1.14: tiktok/shorts/linkedin/facebook stop being aliases of reels/youtube -- each is its+ own frame and duration limit. youtube-hdr must keep a real HDR source's tags (the point of+ the preset) and refuse an SDR one instead of labelling SDR as HDR; youtube-av1 must refuse+ with kind: missing_tool on a build with no AV1 encoder rather than failing inside ffmpeg."""+ sys.path.insert(0, str(SCRIPTS))+ import export as export_mod+ frames = {name: (p["w"], p["h"], p["max"]) for name, p in export_mod.PRESETS.items()+ if name in ("reels", "tiktok", "shorts", "linkedin", "facebook")}+ self.assertEqual(len(set(frames.values())), 5, f"presets must be distinct entries: {frames}")+ for preset, size in (("tiktok", (1080, 1920)), ("linkedin", (1080, 1080))):+ out = OUT / f"export_{preset}.mp4"+ script("export.py", self.src, "--preset", preset, "--fast", "-o", out)+ m = probe(str(out))+ self.assertEqual((m["video"]["width"], m["video"]["height"]), size)+ hdr_out = OUT / "export_yt_hdr.mp4"+ script("export.py", self.hdr, "--preset", "youtube-hdr", "--fast", "-o", hdr_out)+ m = probe(str(hdr_out))+ self.assertTrue(m["video"]["hdr"], "youtube-hdr must keep the source's HDR")+ self.assertNotEqual(m["video"]["color_space"], "bt709")+ doc = json.loads(script("export.py", self.src, "--preset", "youtube-hdr", "--json",+ "-o", str(OUT / "never.mp4"), expect_fail=True).stdout)+ self.assertEqual(doc["error"]["kind"], "input")+ self.assertIn("SDR", doc["error"]["message"])+ from _common import ffmpeg_encoders+ av1_out = OUT / "export_yt_av1.mp4"+ if {"libsvtav1", "libaom-av1"} & ffmpeg_encoders():+ script("export.py", self.src, "--preset", "youtube-av1", "--fast", "-o", av1_out)+ self.assertEqual(probe(str(av1_out))["video"]["codec"], "av1")+ else:+ doc = json.loads(script("export.py", self.src, "--preset", "youtube-av1", "--json",+ "-o", str(av1_out), expect_fail=True).stdout)+ self.assertEqual(doc["error"]["kind"], "missing_tool")++ def test_check_and_export_read_one_loudness_spec_per_platform(self):+ """The 1.14 table exists so `export.py --normalize` and `check.py` cannot drift: the+ loudness a preset normalises to is read from the same entry the check enforces."""+ sys.path.insert(0, str(SCRIPTS))+ import export as export_mod+ from check import SPECS+ from _platforms import loudness_of+ for preset, platform in export_mod.PLATFORM_OF.items():+ with self.subTest(preset=preset):+ spec = SPECS[platform]+ table = loudness_of(platform)+ self.assertEqual((spec["lufs"], spec["lufs_tol"], spec["tp"]),+ (table["lufs"], table["lufs_tol"], table["tp"]))++ def test_fit_blur_keeps_the_whole_picture_on_a_blurred_border(self):+ """--fit blur: the target aspect, nothing cropped, borders that carry a dimmed copy of the+ picture rather than black, and a centre band that is still the scaled source."""+ out = OUT / "fit_blur.mp4"+ script("fit.py", self.src, "--duration", "3", "--aspect", "9:16", "--fit", "blur",+ "--width", "360", "--fast", "-o", out)+ m = probe(str(out))+ self.assertEqual((m["video"]["width"], m["video"]["height"]), (360, 640))+ top_avg, top_spread = self._region_stats(out, "iw:80:0:0")+ self.assertGreater(top_avg, 10, f"blurred border is black: {top_avg}")+ self.assertGreater(top_spread, 8, f"blurred border is flat: {top_spread}")+ # the centre band is the fitted source: 360x202 sits at y=(640-202)/2+ ref = OUT / "fit_blur_ref.mp4"+ script("fit.py", self.src, "--duration", "3", "--width", "360", "--fast", "-o", ref)+ mid_avg, _ = self._region_stats(out, "iw:180:0:230")+ ref_avg, _ = self._region_stats(ref, "iw:180:0:10")+ self.assertClose(mid_avg, ref_avg, 12, "the centre of a blur fit is the scaled source")+ # the darkening is an eq on code values: a -15 % perceptual dim on SDR, something else on+ # PQ/HLG, so an HDR source keeps its background at its own levels (review 12)+ sdr_plan = json.loads(script("fit.py", self.src, "--aspect", "9:16", "--fit", "blur",+ "--dry-run", "--json", "-o", str(OUT / "blur_sdr.mp4")).stdout)+ hdr_plan = json.loads(script("fit.py", self.hdr, "--aspect", "9:16", "--fit", "blur",+ "--dry-run", "--json", "-o", str(OUT / "blur_hdr.mp4")).stdout)+ self.assertTrue(any("eq=brightness" in c for c in sdr_plan["commands"]))+ self.assertTrue(any("boxblur" in c for c in hdr_plan["commands"]))+ self.assertFalse(any("eq=brightness" in c for c in hdr_plan["commands"]),+ "an HDR source must not be dimmed by an SDR-shaped eq")++ def test_look_safe_shades_only_the_platforms_occluded_zones(self):+ """`look.py --safe tiktok` is how "is the caption readable" gets answered about the app and+ not just the file: the bottom fifth and the right column come back visibly marked, the+ middle of the frame untouched."""+ plain, marked = OUT / "safe_plain.png", OUT / "safe_marked.png"+ script("look.py", self.src, "--at", "2", "--no-timecode", "-o", plain)+ doc = json.loads(script("look.py", self.src, "--at", "2", "--no-timecode", "--safe", "tiktok",+ "-o", marked, "--json").stdout)+ self.assertTrue(os.path.exists(doc["output"]))+ self.assertEqual(png_size(plain), png_size(marked))+ self.assertNotEqual(plain.read_bytes(), marked.read_bytes(), "--safe must mark the frame")+ cmd = [c for c in doc["commands"] if "drawbox" in c]+ self.assertTrue(cmd, doc["commands"])+ self.assertIn("y=ih*(1-0.22)", cmd[0])+ self.assertIn("x=iw*(1-0.14)", cmd[0])++ def test_sticker_hook_and_meme_draw_ink_where_they_promise(self):+ """The three social graphics templates: each must render, put ink where the layout says it+ goes (top band for the hook's progress bar, the two edges for a meme), and -- for the+ sticker -- stay inside the platform's safe zone when --platform names one."""+ sys.path.insert(0, str(SCRIPTS))+ from _platforms import PLATFORMS+ vertical = OUT / "safe_vertical.mp4"+ script("fit.py", self.src, "--duration", "4", "--aspect", "9:16", "--fit", "crop",+ "--width", "540", "--fast", "-o", vertical)+ base = self._region_stats(vertical, "iw:60:0:0", at=1.0)++ sticker = OUT / "gfx_sticker.mp4"+ doc = json.loads(script("graphics.py", vertical, "--template", "sticker", "--text", "NEW",+ "--position", "top-right", "--platform", "tiktok", "--fast",+ "-o", sticker, "--json").stdout)+ self.assertTrue(os.path.exists(sticker))+ drawtext = [c for c in doc["commands"] if "drawtext" in c][0]+ safe = PLATFORMS["tiktok"]["safe"]+ W, H = 540, 960+ right = int(re.search(r"x=w-text_w-(\d+)", drawtext).group(1))+ top = int(re.search(r"y=[^0-9]*(\d+)\+", drawtext).group(1)) # the shell quoting around the expression varies+ self.assertGreaterEqual(right, round(safe["right"] * W) - 1, "the sticker must clear the like column")+ self.assertGreaterEqual(top, round(safe["top"] * H) - 1, "the sticker must clear the status bar")++ hook = OUT / "gfx_hook.mp4"+ script("graphics.py", vertical, "--template", "hook", "--title", "How I cut this",+ "--duration", "3", "--fast", "-o", hook)+ band_avg, _ = self._region_stats(hook, "iw:12:0:0", at=0.5)+ late_avg, _ = self._region_stats(hook, "iw:12:0:0", at=3.5)+ self.assertGreater(abs(band_avg - late_avg), 4,+ "the hook's progress bar must be drawn while the card is up and gone after it")+ mid_card, _ = self._region_stats(hook, "iw:200:0:380", at=0.5)+ mid_after, _ = self._region_stats(hook, "iw:200:0:380", at=3.5)+ self.assertNotAlmostEqual(mid_card, mid_after, delta=1.0,+ msg="the hook card must darken the middle of the frame while it is up")++ meme = OUT / "gfx_meme.mp4"+ script("graphics.py", vertical, "--template", "meme", "--top", "when the render",+ "--bottom", "finally finishes", "--fast", "-o", meme)+ plain_top, _ = self._region_stats(vertical, "iw:120:0:40", at=1.0)+ meme_top, _ = self._region_stats(meme, "iw:120:0:40", at=1.0)+ plain_bottom, _ = self._region_stats(vertical, "iw:120:0:820", at=1.0)+ meme_bottom, _ = self._region_stats(meme, "iw:120:0:820", at=1.0)+ self.assertNotAlmostEqual(meme_top, plain_top, delta=0.5, msg="meme --top draws nothing")+ self.assertNotAlmostEqual(meme_bottom, plain_bottom, delta=0.5, msg="meme --bottom draws nothing")+ script("graphics.py", vertical, "--template", "sticker", expect_fail=True)+ script("graphics.py", vertical, "--template", "meme", expect_fail=True)++ def test_project_graphics_entry_renders_a_sticker_and_a_meme(self):+ """The three social graphics templates are advertised as usable inside a render.py+ graphics[] entry, and until review 12 the project validator refused their own keys+ (text/top/bottom/duration), so sticker and meme could only be run from the CLI."""+ out = OUT / "gproj_out.mp4"+ proj = OUT / "gproj.json"+ proj.write_text(json.dumps({+ "output": str(out),+ "clips": [{"src": str(self.src.resolve()), "in": 0, "out": 4}],+ "graphics": [+ {"template": "sticker", "text": "NEW", "position": "top-right", "platform": "tiktok"},+ {"template": "meme", "top": "when the render", "bottom": "finally finishes"},+ {"template": "hook", "title": "How I cut this", "duration": 2},+ ]}), encoding="utf-8")+ doc = json.loads(script("render.py", proj, "--fast", "--json").stdout)+ self.assertEqual(doc["status"], "completed")+ self.assertIn("graphics", doc["stages"])+ self.assertTrue(out.exists())+ # ink where the meme layout puts it: the two edges of the frame change, and the sticker+ # corner does too -- a validator that accepted the keys but dropped them would not show here+ for crop, y in (("iw:100:0:20", "top"), ("iw:100:0:600", "bottom")):+ before, _ = self._region_stats(self.src, crop, at=1.0)+ after, _ = self._region_stats(out, crop, at=1.0)+ self.assertNotAlmostEqual(before, after, delta=0.5, msg=f"nothing was drawn at the {y}")+ # an unknown key is still a refusal, with the valid ones named+ proj.write_text(json.dumps({"output": str(out), "clips": [{"src": str(self.src.resolve())}],+ "graphics": [{"template": "sticker", "caption": "NEW"}]}), encoding="utf-8")+ proc = script("render.py", proj, "--dry-run", "--json", expect_fail=True)+ self.assertIn("unknown key", proc.stderr)++ def test_template_logo_lands_inside_the_platform_safe_zone(self):+ """A template's --logo used to be drawn 24 px from the corner -- i.e. under TikTok's own+ status bar and next to its tab row. The overlay stage now hears the destination like the+ caption and graphics stages do, so the planned overlay sits inside the safe zone."""+ sys.path.insert(0, str(SCRIPTS))+ from _platforms import PLATFORMS+ safe = PLATFORMS["tiktok"]["safe"]+ W, H = PLATFORMS["tiktok"]["frame"]["w"], PLATFORMS["tiktok"]["frame"]["h"]+ doc = json.loads(script("render.py", self.src, "--template", "tiktok", "--cues", self.cues,+ "--logo", self.logo, "--dry-run", "--json",+ "-o", str(OUT / "logo_safe.mp4")).stdout)+ cmd = [c for c in doc["commands"] if "logo.png" in c and "overlay=" in c]+ self.assertTrue(cmd, doc["commands"])+ x, y = re.search(r"overlay=(-?\d+):(-?\d+)", cmd[0]).groups()+ self.assertGreaterEqual(int(x), round(safe["left"] * W) - 1,+ "the logo must clear the left safe margin")+ self.assertGreaterEqual(int(y), round(safe["top"] * H) - 1,+ "the logo must clear TikTok's status bar and tab row")+ self.assertLess(int(y), H - round(safe["bottom"] * H))++ def test_pack_dry_run_plans_every_command_and_reports_no_result(self):+ """A pack is the one path that writes seven files, so --dry-run has to show all of them --+ and must never report a check result or a file size for a run that encoded nothing (the+ sizes used to be read off files left behind by an earlier real run)."""+ packdir = OUT / "packdry"+ packdir.mkdir(exist_ok=True)+ stale = packdir / "source_tiktok.mp4"+ stale.write_bytes(b"0" * 4096) # a leftover from an earlier real run+ doc = json.loads(script("render.py", self.src, "--template", "tiktok,podcast",+ "--cues", self.cues, "--dry-run", "--json",+ "-o", str(packdir / "ignored.mp4")).stdout)+ self.assertTrue(any("ffmpeg" in c for c in doc["commands"]),+ "the pack's planned commands are the plan; --dry-run must show them")+ self.assertTrue(any("loudnorm" in c or "libx264" in c for c in doc["commands"]))+ for row in doc["pack"]:+ self.assertEqual(row["check"], "planned", row)+ self.assertIsNone(row["size_bytes"], row)+ self.assertIsNone(row["duration"], row)+ self.assertEqual(stale.stat().st_size, 4096, "a dry run must not touch the files it plans")+ # the audio-only destination of a pack is named like the single-template form: .m4a+ self.assertEqual([Path(r["file"]).suffix for r in doc["pack"]], [".mp4", ".m4a"])+ self.assertFalse((packdir / "source_pack.md").exists(), "a dry run writes no table either")++ def test_export_presets_are_the_platform_tables_frame_and_duration(self):+ """docs/contract.md says export.py's PRESETS/PLATFORM_OF come from scripts/_platforms.py.+ Until review 12 only check.py's SPECS did, and the facebook preset had already drifted+ (no duration cap against the table's 14400 s). Every platform preset is the table now,+ except the two deliberate, documented exceptions."""+ sys.path.insert(0, str(SCRIPTS))+ import export as export_mod+ from _platforms import PLATFORMS, loudness_of+ from check import SPECS+ # youtube4k delivers to youtube at 2160p; neither youtube preset trims at the 12-hour cap+ exceptions = {"youtube": {"max"}, "youtube4k": {"w", "h", "max"},+ "youtube-hdr": {"w", "h", "max"}, "youtube-av1": {"max"}}+ for preset, platform in sorted(export_mod.PLATFORM_OF.items()):+ with self.subTest(preset=preset):+ p = export_mod.PRESETS[preset]+ frame = PLATFORMS[platform]["frame"]+ spec = PLATFORMS[platform]["spec"]+ skip = exceptions.get(preset, set())+ if "w" not in skip:+ self.assertEqual((p["w"], p["h"]), (frame["w"], frame["h"]),+ f"{preset} frame must be {platform}'s frame")+ if "max" not in skip:+ self.assertEqual(p["max"], float(spec["max_duration"]) if spec["max_duration"] else None,+ f"{preset} duration cap must be {platform}'s")+ table = loudness_of(platform)+ self.assertEqual((SPECS[platform]["lufs"], SPECS[platform]["lufs_tol"], SPECS[platform]["tp"]),+ (table["lufs"], table["lufs_tol"], table["tp"]))+ self.assertEqual(export_mod.PRESETS["facebook"]["max"], 14400.0,+ "the drift review 12 found: facebook had no duration cap at all")++ def test_every_template_caption_block_is_the_tables_safe_zone(self):+ """The templates must not restate the numbers the table exists to own: change a+ destination's safe zone and every shipped template follows, rather than keeping an old+ margin silently."""+ sys.path.insert(0, str(SCRIPTS))+ from _platforms import PLATFORMS, caption_defaults+ import render as render_mod+ for path in sorted((ROOT / "templates").glob("*.json")):+ tpl = json.loads(path.read_text(encoding="utf-8"))+ cap = tpl.get("captions")+ if not cap:+ continue+ dest = tpl["check"]["platform"]+ with self.subTest(template=path.stem):+ want = caption_defaults(dest)+ self.assertEqual((cap["size"], cap["margin"]), (want["size"], want["margin"]),+ f"{path.name} restates {dest}'s caption size/margin")+ self.assertTrue(PLATFORMS[dest]["frame"])+ # and the filled project takes them from the table, not from the file's literals+ proj = OUT / "tplcap_project.json"+ script("render.py", self.src, "--template", "reels", "--cues", self.cues,+ "--write-project", proj, "-o", str(OUT / "tplcap.mp4"))+ filled = json.loads(proj.read_text())["captions"]+ want = caption_defaults("reels")+ self.assertEqual((filled["size"], filled["margin"]), (want["size"], want["margin"]))++ def test_platform_aliases_resolve_the_same_on_every_tool(self):+ """One resolve(): 'youtube-shorts' is 'shorts' for check, export, caption, graphics, look+ and render alike. Before review 12 the alias map was written, advertised in the docs and+ called from nowhere, so no tool accepted a single one of them."""+ sys.path.insert(0, str(SCRIPTS))+ import render as render_mod+ self.assertEqual(render_mod.expand_templates("ig"), ["reels"])+ self.assertEqual(render_mod.expand_templates("twitter,yt"), ["x", "youtube"])+ self.assertEqual(render_mod.expand_templates("youtube-shorts"), ["youtube-shorts"],+ "a template that ships under its own name stays itself")+ target = OUT / "alias_src.mp4"+ script("fit.py", self.src, "--duration", "3", "--aspect", "9:16", "--fit", "crop",+ "--width", "360", "--fast", "-o", target)++ def commands(tool, *argv):+ doc = json.loads(script(tool, target, *argv, "--dry-run", "--json").stdout)+ return [c for c in doc["commands"] if "ffmpeg" in c or "drawtext" in c]++ # the alias is the point here, not compliance: a 3 s crop can miss the fps row on some+ # ffmpeg builds (7.1 reports the speed-changed rate differently), and check.py names+ # the resolved platform in its JSON on failure as well as on success+ proc_a = subprocess.run([sys.executable, str(SCRIPTS / "check.py"), str(target), "--platform",+ "youtube-shorts", "--no-loudness", "--json"],+ stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, encoding="utf-8")+ doc_a = json.loads(proc_a.stdout)+ self.assertEqual(doc_a["platform"], "shorts")+ self.assertTrue(doc_a["checks"], "check.py must have run the shorts rows under the alias")+ for tool, argv in (+ ("export.py", ("--preset", "youtube-shorts", "-o", str(OUT / "alias_exp.mp4"))),+ ("caption.py", ("--text", self.cues, "-o", str(OUT / "alias_cap.mp4"), "--platform", "youtube-shorts")),+ ("graphics.py", ("--template", "bug", "--title", "@x", "-o", str(OUT / "alias_gfx.mp4"), "--platform", "youtube-shorts")),+ ("look.py", ("--at", "1", "-o", str(OUT / "alias_look.png"), "--safe", "youtube-shorts"))):+ with self.subTest(tool=tool):+ canonical = tuple("shorts" if a == "youtube-shorts" else a for a in argv)+ self.assertEqual(commands(tool, *argv), commands(tool, *canonical),+ f"{tool} must treat youtube-shorts and shorts as one destination")+def test_graphics_audio_stream_selects_the_requested_track_not_always_the_first(self):two = OUT / "gfx_two_streams.mkv"sh("ffmpeg", "-y", "-hide_banner", "-loglevel", "error", "-f", "lavfi", "-i", "testsrc2=size=320x180:rate=30",