remotion-ffmpeg-skill 0.3.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -8,7 +8,14 @@ Built on [**ffmpeg-skill**](https://github.com/kajisho5/ffmpeg-skill). Unofficia
8
8
 
9
9
  ![Jumpcut: the silences ffmpeg-skill measured are gone, every other cut punches in, captions re-timed to the new cut](assets/demo-jumpcut.gif)
10
10
 
11
- <sub>Fictional demo footage. Left to right in time: ffmpeg-skill measured two silences and a scene cut; Remotion played only the speech ranges with punch-in zooms and re-timed captions; render.py verified 201 of 201 frames.</sub>
11
+ <sub>Fictional demo footage. ffmpeg-skill measured two silences and a scene cut; Remotion played only the speech ranges with punch-in zooms and re-timed captions; render.py verified 201 of 201 frames.</sub>
12
+
13
+ <table>
14
+ <tr>
15
+ <td width="62%"><img src="assets/demo-karaoke.gif" alt="Karaoke: each word lights up at the time a speech engine measured"><br><sub><b>Karaoke</b> — words light up at their measured times (250 / 250 frames verified)</sub></td>
16
+ <td width="38%"><img src="assets/demo-portrait-ja.gif" alt="9:16 jump cut with Japanese captions on a blurred fill"><br><sub><b>9:16 + Japanese</b> — silences cut, CJK font staged automatically, phrase-based line breaks</sub></td>
17
+ </tr>
18
+ </table>
12
19
 
13
20
  ## Why this and not just Remotion's own skills?
14
21
 
@@ -76,6 +83,7 @@ Tool names and input schemas come from the machine-readable contract (`npx remot
76
83
  | `Titled` | source duration | your lower thirds + a title card at each measured scene change |
77
84
  | `Highlights` | sum of ranked highlights | ffmpeg-skill's audio-energy highlights back to back, counter, title |
78
85
  | `BeatMontage` | source duration | audio unbroken, picture cuts on the measured beat grid |
86
+ | `Karaoke` | source duration | words light up at the times a local speech engine measured |
79
87
 
80
88
  **Any shape:** `--aspect 9:16 | 1:1 | 4:5 | 16:9` with `--fit blur | contain | cover`; `pipeline.py --platform reels` picks 9:16 from ffmpeg-skill's own template so nothing gets cropped on delivery.
81
89
 
@@ -106,12 +114,12 @@ This skill is MIT. **Remotion itself has its own licence**: free for individuals
106
114
 
107
115
  ## Speed
108
116
 
109
- Remotion renders in a headless browser. Measured on a 2-core Linux machine: a 30 s 1080p30 render takes about 170 s (≈ 5–6× the clip length). Check with `still.py` and `--fast` before a full render of long footage; more CPU cores help (`--concurrency`).
117
+ Remotion renders in a headless browser. Measured on a 2-core Linux machine: a 30 s 1080p30 render takes about 80 s (≈ 2.6× the clip length) with render.py's default of all CPU cores — Remotion's own default (half the cores) took 170 s. More cores scale it further. Check with `still.py` and `--fast` before a full render of long footage.
110
118
 
111
119
  ## Agent evals
112
120
 
113
- Six plain requests ("captions for YouTube", a Japanese Reels jump cut, "cut to the beat", a lower third without a name, a plain trim that is *not* this skill's job, a square highlight reel), run by an agent that only has the skill files, graded on what it leaves behind: **6 / 6** on the first run ([results](evals/results/2026-10-24.md), [how to run](evals/README.md)).
121
+ Plain requests ("captions for YouTube", a Japanese Reels jump cut, "cut to the beat", a lower third without a name, a plain trim that is *not* this skill's job, a square highlight reel), run by an agent that only has the skill files, graded on what it leaves behind — plus a transparent layer for an editor, joining clips with titles, and karaoke from word timings: **9 / 9** ([run 1](evals/results/2026-10-24.md), [run 2](evals/results/2026-10-24b.md), [how to run](evals/README.md)).
114
122
 
115
123
  ## Status
116
124
 
117
- 0.3.0. Tested on Linux (Node 22, Remotion 4.0.538, ffmpeg-skill 2.12.0); macOS and Windows not yet. Next: rendering only the captioned ranges for long footage, macOS/Windows CI, word-level karaoke captions ([roadmap](ROADMAP.md)).
125
+ 0.4.0. CI renders every composition on Linux, macOS and Windows (Node 22, Remotion 4.0.538, ffmpeg-skill main).
package/SKILL.md CHANGED
@@ -21,7 +21,7 @@ Shared flags (every script): `--json` (one JSON object on stdout; prefer it), `-
21
21
  - **Fonts:** Japanese / Chinese / Korean captions get the CJK font ffmpeg-skill finds on the machine automatically (staged into the project, so no tofu); `--font-file F.ttf` uses a specific font; the report line `font:` says which was used, or that none was found.
22
22
  - **Editing-app layer:** `--overlay --keep-graphics` (Captioned / PeakPulse, source shape) draws the graphics alone as a transparent ProRes 4444 `.graphics.mov` and composites it over the untouched source with ffmpeg-skill `overlay.py`; hand the `.mov` to someone finishing in Premiere / Resolve / Final Cut. It is not faster than a normal render.
23
23
  5. **Deliver.** `deliver.py OUT.mp4 --platform youtube|reels|tiktok|shorts|x|...` runs ffmpeg-skill's delivery template and its `check.py` table. Format rows are safe to fix; judgement rows (duration, aspect) change content — ask. Mention WARNs, don't chase them. No destination named: skip this step and say so.
24
- 6. **Look.** Not finished until the reply names the contact sheet render.py wrote (`Look: PATH`) and says what it shows. Mechanical (check and report): text is where it was asked, cues appear at their times, nothing is cut off by the frame. Judgement (say what you see, the user decides): text over a face, a jump that lands badly. No image view: `Look: PATH (pixels not inspected)` — never claim you looked.
24
+ 6. **Look.** Not finished until the reply names the contact sheet render.py wrote (`Look: PATH`) and says what it shows. Mechanical (check and report): text is where it was asked, cues appear at their times, nothing is cut off by the frame. Judgement (say what you see, the user decides): text over a face, a jump that lands badly. No image view: `Look: PATH (pixels not inspected)` — never claim you looked. No contact sheet (`look_error` in the result, e.g. an FFmpeg without `drawtext`): look at `still.py` frames instead and pass on the fix the error names.
25
25
 
26
26
  Options files are checked before rendering: an unknown key or a wrong type is refused (`kind: input`) instead of silently doing nothing.
27
27
 
@@ -36,6 +36,7 @@ Everything in one go: `pipeline.py SOURCE --project ./motion --comp NAME [--capt
36
36
  | "animated captions / subtitles on this video" | `analyze.py --captions` → `render.py --comp Captioned` |
37
37
  | "cut the silences / jump cut / tighten this talk" (with motion) | `analyze.py` → `render.py --comp Jumpcut` (captions re-timed if given) |
38
38
  | "graphics that react to the audio / hit on the beat / on cuts" | `analyze.py [--beats]` → `render.py --comp PeakPulse` (pulses on beats when the grid was measured) |
39
+ | "karaoke captions / words light up as they're spoken" | `analyze.py --words WORDS.json [--captions F.srt]` → `render.py --comp Karaoke` (word timings from a local speech engine, whisper JSON; without an SRT the cues are grouped from the words) |
39
40
  | "lower thirds / name titles / chapter titles" | `render.py --comp Titled --options` with `lowerThirds` / `sceneTitles` — the text comes from the user; ask for it, never invent names |
40
41
  | "highlight reel / best moments" | `analyze.py --highlights N [--target S]` → `render.py --comp Highlights` (audio-energy ranking: candidates, say so) |
41
42
  | "cut to the beat / music montage" | `analyze.py --beats [--highlights N]` → `render.py --comp BeatMontage` (audio unbroken, picture cuts every `beatsPerCut` measured beats; scene cuts if no confident grid) |
@@ -61,6 +62,6 @@ Everything in one go: `pipeline.py SOURCE --project ./motion --comp NAME [--capt
61
62
  - Remotion licence: free for individuals and for-profit organisations with up to 3 employees; larger companies need a Remotion company licence (https://www.remotion.dev/license). If the user is plainly a larger company, say so once.
62
63
  - Keep the user's originals: sources are linked into `public/media/` of the project, never modified; outputs never overwrite an existing file without `--overwrite`.
63
64
  - CJK captions: the auto font comes from ffmpeg-skill's font detection; when the report says no font was found, install one (Noto Sans CJK) or pass `--font-file` — tofu in the contact sheet is a failed job. Japanese lines break between phrases, not inside words.
64
- - Speed (measured on a 2-core Linux machine): about 5–6× the clip length for a 1080p30 render (30 s took 170 s). Preview with `still.py` and `--fast` before a full render of long footage; warn the user before starting a render of a long clip.
65
+ - Speed (measured on a 2-core Linux machine, all cores — render.py's default): about 2.6× the clip length for 1080p30 (30 s took 80 s). Preview with `still.py` and `--fast` before a full render of long footage; tell the user the expected time before starting a long render. `--concurrency` above the core count is refused by Remotion.
65
66
  - Remotion packages in a project must all be the same version; the template pins them. Don't mix in a different `remotion` version.
66
67
  - A render that fails verification is a failure: report the failed rows from `--json`, don't ship it.
package/mcp/server.py CHANGED
@@ -56,7 +56,13 @@ def build_argv(name: str, args: Dict[str, Any]) -> List[str]:
56
56
  missing = [k for k in schema["required"] if args.get(k) in (None, "")]
57
57
  if missing:
58
58
  raise ValueError(f"{name}: missing required argument(s) {missing}")
59
- argv: List[str] = [str(args[k]) for k in schema["x-positional"] if args.get(k) is not None]
59
+ argv: List[str] = []
60
+ for k in schema["x-positional"]:
61
+ v = args.get(k)
62
+ if isinstance(v, list):
63
+ argv += [str(x) for x in v]
64
+ elif v is not None:
65
+ argv.append(str(v))
60
66
  flags = dict(s["flags"], dry_run="--dry-run", overwrite="--overwrite", timeout="--timeout")
61
67
  for key, val in args.items():
62
68
  if key in schema["x-positional"] or val is None or val is False:
package/package.json CHANGED
@@ -1,14 +1,46 @@
1
1
  {
2
2
  "name": "remotion-ffmpeg-skill",
3
- "version": "0.3.0",
3
+ "version": "0.5.0",
4
4
  "description": "Agent Skill: ffmpeg-skill measures the footage, Remotion draws the motion graphics from those measurements, ffmpeg-skill checks and delivers the result. Timeline-driven captions, silence jump cuts and audio-peak motion with probe-first / verify-last rendering. Local, no API keys.",
5
- "keywords": ["remotion", "ffmpeg", "ffmpeg-skill", "video", "motion-graphics", "captions", "agent-skill", "agent-skills", "claude-code", "claude-skill", "cursor", "codex", "ai-agents"],
5
+ "keywords": [
6
+ "remotion",
7
+ "ffmpeg",
8
+ "ffmpeg-skill",
9
+ "video",
10
+ "motion-graphics",
11
+ "captions",
12
+ "agent-skill",
13
+ "agent-skills",
14
+ "claude-code",
15
+ "claude-skill",
16
+ "cursor",
17
+ "codex",
18
+ "ai-agents"
19
+ ],
6
20
  "license": "MIT",
7
21
  "author": "kajisho5",
8
- "repository": {"type": "git", "url": "git+https://github.com/kajisho5/remotion-ffmpeg-skill.git"},
22
+ "repository": {
23
+ "type": "git",
24
+ "url": "git+https://github.com/kajisho5/remotion-ffmpeg-skill.git"
25
+ },
9
26
  "homepage": "https://github.com/kajisho5/remotion-ffmpeg-skill#readme",
10
- "bugs": {"url": "https://github.com/kajisho5/remotion-ffmpeg-skill/issues"},
11
- "bin": {"remotion-ffmpeg-skill": "bin/remotion-ffmpeg-skill.js"},
12
- "files": ["bin", "SKILL.md", "scripts", "templates", "references", "mcp", "LICENSE", "README.md"],
13
- "engines": {"node": ">=18"}
27
+ "bugs": {
28
+ "url": "https://github.com/kajisho5/remotion-ffmpeg-skill/issues"
29
+ },
30
+ "bin": {
31
+ "remotion-ffmpeg-skill": "bin/remotion-ffmpeg-skill.js"
32
+ },
33
+ "files": [
34
+ "bin",
35
+ "SKILL.md",
36
+ "scripts",
37
+ "templates",
38
+ "references",
39
+ "mcp",
40
+ "LICENSE",
41
+ "README.md"
42
+ ],
43
+ "engines": {
44
+ "node": ">=18"
45
+ }
14
46
  }
@@ -0,0 +1,30 @@
1
+ # Gotchas
2
+
3
+ Things that went wrong while building and running this skill, and what the scripts now do about them.
4
+ Read the one you need; SKILL.md has the one-line versions.
5
+
6
+ ## Frames and timing
7
+ - **Python `round()` is not JavaScript `Math.round()`.** 3.15 s × 30 fps = 94.5: Python gives 94 (half to even), the composition gives 95. render.py's expected frame count was off by one frame per half-frame boundary. Both sides now use round-half-up (`sec_to_frames`, `secToFrames`); a test pins it.
8
+ - **Count frames, not seconds.** AAC priming/padding makes a container 20–50 ms longer than its picture. render.py compares the video stream's `nb_frames` with the expected count exactly and only falls back to a duration tolerance when the container has no frame count.
9
+ - **Variable frame rate sources drift.** Remotion renders on a fixed grid; analyze.py warns on suspected VFR. Make a constant-frame-rate copy with ffmpeg-skill first.
10
+
11
+ ## Files Remotion can and cannot read
12
+ - **Symlinks in `public/` 404.** Remotion's file server refuses a symlink that points outside the project. Sources and fonts are hard-linked (instant, no extra space) or copied once.
13
+ - **Remotion's CLI does not copy `public/` per render on macOS/Linux** (it links the folder into its temporary bundle); **on Windows it copies it every time.** Big sources make Windows renders slower to start.
14
+ - **Props files are named by content** (`.rfs/props-<comp>-<hash>.json`): one name per composition used to let two parallel renders overwrite each other's props.
15
+
16
+ ## Picture
17
+ - **HDR / BT.2020 looks washed out.** Chrome composites in SDR. analyze.py warns; convert with ffmpeg-skill `color.py --to-sdr` first.
18
+ - **Delivery templates crop.** ffmpeg-skill's Reels / TikTok / Shorts templates fit to 9:16 by cropping, so a 16:9 render loses the edges of every caption. Render in the delivery shape (`--aspect 9:16`, or `pipeline.py --platform`, which reads the template's aspect).
19
+ - **Remotion's default concurrency is half the CPU cores.** render.py passes `--concurrency 100%`: 30 s of 1080p30 on 2 cores went from 170 s to 80 s. A number above the core count is an error.
20
+ - **`--overlay` is not faster.** Transparent PNG frames plus ProRes 4444 cost about what decoding the source saves (170 s vs 174 s for 30 s of 1080p30 on 2 cores). It exists for handing a graphics layer to an editing app.
21
+
22
+ ## Text
23
+ - **CJK captions need a CJK font on the rendering machine**, or they render as tofu. render.py stages the font ffmpeg-skill's doctor resolves for the caption's script and loads it before the first frame; `cancelRender` stops the render if it cannot load.
24
+ - **Japanese line breaks** use `word-break: auto-phrase` (phrase boundaries) with `text-wrap: balance`; Korean gets `lang="ko"` so it is not treated as Japanese.
25
+ - **An options typo used to do nothing.** Unknown keys and wrong types are refused before rendering.
26
+
27
+ ## Containers and CI
28
+ - **Homebrew's `ffmpeg` has no `drawtext`.** ffmpeg-skill's contact sheets fail on it (the render itself still verifies). `brew install ffmpeg-full` (keg-only: put its `bin` on PATH). render.py says so in `look_error`.
29
+ - **`remotion` packages must share one version.** The template pins them; Dependabot groups them.
30
+ - **Container memory warnings** ("Detected differing memory amounts") are noise in Docker; error extraction drops them and keeps what follows "An error occurred".
@@ -0,0 +1,194 @@
1
+ # Script reference
2
+
3
+ <!-- Generated by scripts/_docs.py from scripts/_contract.py. Do not edit by hand. -->
4
+
5
+ Contract 1.0 · timeline schema `remotion-ffmpeg-skill/timeline@1`.
6
+ Every script also takes `--json`, `--dry-run`, `--overwrite` and `--timeout SECONDS`.
7
+ Exit codes: input = 2, missing_tool = 3, timeout = 4, failed = 1.
8
+
9
+ ## analyze.py
10
+
11
+ Measure a source with ffmpeg-skill and write timeline.json (+ captions from a file).
12
+
13
+ - Role: analysis — measures media and writes a data file (no media)
14
+ - Writes: timeline.json
15
+ - Verifies: every number comes from ffmpeg-skill probe/scenes/silence; warnings for VFR/HDR/rotation
16
+ - ffmpeg-skill: probe, scenes, silence
17
+ - `--dry-run`: plans without writing
18
+
19
+ | Argument | Type | Default | Meaning |
20
+ |---|---|---|---|
21
+ | `input` | string, repeatable | | source video (or audio) file; several are joined in order first |
22
+ | `--joined` | string | | with several inputs: where the joined source goes (default: <first>_joined.mp4) |
23
+ | `--join-transition` | string | `none` | with several inputs: ffmpeg-skill join.py --transition (default none = straight cuts) |
24
+ | `--join-duration` | number | `0.5` | transition length in seconds (default 0.5) |
25
+ | `--output` | string | | timeline file (default: <name>.timeline.json) |
26
+ | `--captions` | string | | SRT, WebVTT or JSON cue list to carry into the timeline (text kept as written) |
27
+ | `--words` | string | | word timings from a speech engine (whisper JSON with word timestamps) for the Karaoke composition; without --captions the cues are grouped from these words |
28
+ | `--beats` | boolean | | also measure the beat grid (scenes.py --beats) |
29
+ | `--highlights` | integer | | also rank N highlight ranges (scenes.py --highlights; audio energy) for the Highlights composition |
30
+ | `--target` | number | | with --highlights: total length the picks add up to |
31
+ | `--no-scenes` | boolean | | skip scene-cut detection |
32
+ | `--no-silence` | boolean | | skip silence detection (speech = whole file) |
33
+ | `--threshold` | number | | silence level in dBFS for silence.py (default -35) |
34
+ | `--min-silence` | number | | shortest gap in seconds that counts as silence (default 0.6) |
35
+ | `--margin` | number | | seconds of silence kept around speech (default 0.15) |
36
+ | `--scene-threshold` | number | | scenes.py --threshold (default 8) |
37
+
38
+ --json result (besides `status`, `dry_run`, `output`): `commands` (list[str]), `verified` (bool), `summary` (object: duration, fps, size, scenes, silences, speech_seconds, peaks, captions, beats, tempo_bpm, highlights, clips, words), `warnings` (list[str])
39
+
40
+ --dry-run --json result (besides `status`, `dry_run`, `output`): `commands` (list[str])
41
+
42
+ ## init.py
43
+
44
+ Create a Remotion project with the built-in compositions (optionally npm install).
45
+
46
+ - Role: setup — creates a project folder
47
+ - Writes: project folder
48
+ - Verifies: refuses a non-empty folder; npm install exit status
49
+ - ffmpeg-skill: —
50
+ - `--dry-run`: plans without writing
51
+
52
+ | Argument | Type | Default | Meaning |
53
+ |---|---|---|---|
54
+ | `directory` | string | | new project folder (must not exist, or be empty) |
55
+ | `--install` | boolean | | run npm install after copying |
56
+
57
+ --json result (besides `status`, `dry_run`, `output`): `commands` (list[str]), `installed` (bool), `entry` (str), `compositions` (list[str])
58
+
59
+ --dry-run --json result (besides `status`, `dry_run`, `output`): `commands` (list[str])
60
+
61
+ ## still.py
62
+
63
+ Render single frames as PNG to check the look before a full render.
64
+
65
+ - Role: execution — writes a new media artifact; inputs are never modified
66
+ - Writes: PNG files
67
+ - Verifies: frames must lie inside the composition; view the PNGs
68
+ - ffmpeg-skill: _contract doctor (CJK font lookup)
69
+ - `--dry-run`: plans without writing
70
+
71
+ | Argument | Type | Default | Meaning |
72
+ |---|---|---|---|
73
+ | `--project (required)` | string | | Remotion project folder made by init.py |
74
+ | `--comp (required)` | string | | composition id (Captioned, Jumpcut, PeakPulse, Titled, Highlights, BeatMontage, Karaoke, or yours) |
75
+ | `--timeline (required)` | string | | timeline.json written by analyze.py |
76
+ | `--options` | string | | JSON object of look-and-feel options |
77
+ | `--at` | number, repeatable | | time in seconds (repeatable) |
78
+ | `--frame` | integer, repeatable | | frame number (repeatable) |
79
+ | `--out-dir` | string | | folder for the PNGs (default: next to the timeline) |
80
+ | `--aspect` | string: source / 16:9 / 9:16 / 1:1 / 4:5 / 4:3 | | output shape (default: the source's own). 9:16 for Reels/TikTok/Shorts, 1:1, 4:5, 16:9 |
81
+ | `--width` | integer | | output width in px (default: keep the source's short side) |
82
+ | `--fit` | string: blur / contain / cover | | how the source fills another shape: blur (default when the shape changes), contain (bars) or cover (crop) |
83
+ | `--font-file` | string | | caption font file (.ttf/.otf/.ttc/.woff2), staged into the project |
84
+ | `--no-auto-font` | boolean | | don't stage the CJK font ffmpeg-skill finds for Japanese/Chinese/Korean captions |
85
+
86
+ --json result (besides `status`, `dry_run`, `output`): `outputs` (list[str] (PNG paths)), `frames` (list[int]), `commands` (list[str]), `verified` (bool), `frame` (object|null {width, height, fit}), `font` (str|null)
87
+
88
+ --dry-run --json result (besides `status`, `dry_run`, `output`): `outputs` (list[str]), `frames` (list[int]), `commands` (list[str])
89
+
90
+ ## render.py
91
+
92
+ Render a composition from a timeline, verify it (frames, fps, size, audio) and write a contact sheet.
93
+
94
+ - Role: execution — writes a new media artifact; inputs are never modified
95
+ - Writes: video file (+ contact sheet PNG)
96
+ - Verifies: exact frame count / fps / size / audio against the timeline; non-zero exit on mismatch
97
+ - ffmpeg-skill: probe, look, overlay (--overlay), _contract doctor (CJK font lookup)
98
+ - `--dry-run`: plans without writing
99
+
100
+ | Argument | Type | Default | Meaning |
101
+ |---|---|---|---|
102
+ | `--project (required)` | string | | Remotion project folder made by init.py |
103
+ | `--comp (required)` | string | | composition id (Captioned, Jumpcut, PeakPulse, Titled, Highlights, BeatMontage, Karaoke, or one you added) |
104
+ | `--timeline (required)` | string | | timeline.json written by analyze.py |
105
+ | `--options` | string | | JSON object of look-and-feel options (see references/timeline.md) |
106
+ | `--output` | string | | output file (default: <source>_<comp>.mp4, .mov for prores) |
107
+ | `--codec` | string: h264 / prores | `h264` | h264 (default) or prores (ProRes 422 HQ master, .mov) |
108
+ | `--crf` | integer | | h264 quality (Remotion default 18; lower = better) |
109
+ | `--frames` | string | | render only this frame range, e.g. 0-89 (inclusive) |
110
+ | `--fast` | boolean | | preview quality: half resolution, quicker encode |
111
+ | `--concurrency` | string | `100%` | parallel browser tabs: a number up to the CPU cores, or a percentage (default 100%: all cores -- about twice as fast as Remotion's own default of half the cores) |
112
+ | `--no-look` | boolean | | skip the contact sheet |
113
+ | `--overlay` | boolean | | draw the graphics only as a transparent ProRes 4444 layer and composite it over the untouched source with ffmpeg-skill overlay.py (Captioned / PeakPulse, source frame only); with --keep-graphics the layer is kept for an editing app (Premiere, Resolve, Final Cut) |
114
+ | `--keep-graphics` | boolean | | with --overlay: keep the transparent graphics .mov |
115
+ | `--aspect` | string: source / 16:9 / 9:16 / 1:1 / 4:5 / 4:3 | | output shape (default: the source's own). 9:16 for Reels/TikTok/Shorts, 1:1, 4:5, 16:9 |
116
+ | `--width` | integer | | output width in px (default: keep the source's short side) |
117
+ | `--fit` | string: blur / contain / cover | | how the source fills another shape: blur (default when the shape changes), contain (bars) or cover (crop) |
118
+ | `--font-file` | string | | caption font file (.ttf/.otf/.ttc/.woff2), staged into the project |
119
+ | `--no-auto-font` | boolean | | don't stage the CJK font ffmpeg-skill finds for Japanese/Chinese/Korean captions |
120
+
121
+ --json result (besides `status`, `dry_run`, `output`): `verified` (bool), `verification` (list[{check, status, value, expected}]), `commands` (list[str]), `look` (str|null (contact sheet PNG)), `look_error` (str|null), `summary` (str), `frame` (object|null), `font` (str|null), `mode` (full|overlay), `graphics` (str|null (kept ProRes 4444 layer)), `kind` (null|failed), `error` (null|str (which verification rows failed))
122
+
123
+ --dry-run --json result (besides `status`, `dry_run`, `output`): `commands` (list[str]), `props` (str), `expected_frames` (int|null), `frame` (object|null), `font` (str|null)
124
+
125
+ ## deliver.py
126
+
127
+ Run an ffmpeg-skill delivery template (YouTube, Reels, ...) and its compliance check.
128
+
129
+ - Role: execution — writes a new media artifact; inputs are never modified
130
+ - Writes: deliverable video
131
+ - Verifies: ffmpeg-skill check.py table; non-zero exit on any FAIL row
132
+ - ffmpeg-skill: render --template, check
133
+ - `--dry-run`: plans without writing
134
+
135
+ | Argument | Type | Default | Meaning |
136
+ |---|---|---|---|
137
+ | `input` | string | | rendered video |
138
+ | `--platform` | string: youtube / youtube-shorts / shorts / reels / tiktok / x / facebook / linkedin / podcast / audiogram | | ffmpeg-skill delivery template to run |
139
+ | `--output` | string | | deliverable path (default: <name>_<platform>.mp4) |
140
+ | `--check-only` | boolean | | run check.py only, write nothing |
141
+
142
+ --json result (besides `status`, `dry_run`, `output`): `checked` (str), `platform` (str|null), `verified` (bool), `checks` (list[{check, status, value, expected, ...}] (ffmpeg-skill check.py rows)), `failed` (list[str]), `warnings` (list[str]), `commands` (list[str]), `kind` (null|failed), `error` (null|str)
143
+
144
+ --dry-run --json result (besides `status`, `dry_run`, `output`): `commands` (list[str])
145
+
146
+ ## pipeline.py
147
+
148
+ analyze -> render -> deliver in one call, stopping at the first failed step.
149
+
150
+ - Role: orchestration — runs other tools in order, each verified before the next
151
+ - Writes: timeline.json, render, deliverable
152
+ - Verifies: each step's own verification
153
+ - ffmpeg-skill: probe, scenes, silence, look, render --template, check
154
+ - `--dry-run`: plans without writing
155
+
156
+ | Argument | Type | Default | Meaning |
157
+ |---|---|---|---|
158
+ | `input` | string, repeatable | | source video; several are joined in order (ffmpeg-skill join.py) first |
159
+ | `--project (required)` | string | | Remotion project folder made by init.py |
160
+ | `--comp (required)` | string | | composition id (Captioned, Jumpcut, PeakPulse, Titled, Highlights, BeatMontage, Karaoke, or yours) |
161
+ | `--captions` | string | | SRT / WebVTT / JSON cues for the timeline |
162
+ | `--options` | string | | JSON options file passed to the composition |
163
+ | `--platform` | string: youtube / youtube-shorts / shorts / reels / tiktok / x / facebook / linkedin / podcast / audiogram | | deliver with this ffmpeg-skill template and check it |
164
+ | `--out-dir` | string | | where the timeline, render and deliverable go (default: next to the input) |
165
+ | `--beats` | boolean | | measure the beat grid too |
166
+ | `--fast` | boolean | | preview-quality render |
167
+ | `--aspect` | string: source / 16:9 / 9:16 / 1:1 / 4:5 / 4:3 | | output shape (default: the shape the --platform template delivers, else the source's) |
168
+ | `--width` | integer | | output width in px |
169
+ | `--fit` | string: blur / contain / cover | | blur (default when the shape changes), contain or cover |
170
+ | `--font-file` | string | | caption font file |
171
+
172
+ --json result (besides `status`, `dry_run`, `output`): `timeline` (str), `render` (str), `deliverable` (str|null), `look` (str|null), `verified` (bool), `warnings` (list[str]), `steps` (list[{step, status, output, command}])
173
+
174
+ --dry-run --json result (besides `status`, `dry_run`, `output`): `steps` (list[{step, status, output, command}])
175
+
176
+ ## doctor.py
177
+
178
+ What this machine can do: Python, Node/npm, ffmpeg-skill, ffmpeg, a project's Remotion install.
179
+
180
+ - Role: verification — checks an artifact or the environment; writes no media
181
+ - Writes: nothing
182
+ - Verifies: reports only
183
+ - ffmpeg-skill: _contract doctor
184
+ - `--dry-run`: not applicable (reports only)
185
+
186
+ | Argument | Type | Default | Meaning |
187
+ |---|---|---|---|
188
+ | `--project` | string | | Remotion project folder to inspect |
189
+
190
+ --json result (besides `status`, `dry_run`, `output`): `ok` (bool), `version` (str), `checks` (list[{check, ok, value, fix}]), `ffmpeg_skill_doctor` (object|null)
191
+
192
+ ## Failures
193
+
194
+ Every failure is one JSON object: `status` (failed), `error` (str), `kind` (input|missing_tool|timeout|failed), `dry_run` (bool).
@@ -24,7 +24,8 @@ props (`{ "timeline": ..., "options": ..., "frame": ..., "font": ..., "overlay":
24
24
  | `beats` | object \| null | scenes.py `--beats` | `{times, tempo_bpm, confidence, usable}`; compositions use the times only when `usable` |
25
25
  | `highlights` | `[{start, end}]` | scenes.py `--highlights` | ranked by audio energy, stored in source order (analyze.py `--highlights N [--target S]`) |
26
26
  | `clips` | `[{name, path, start, end}]` | analyze.py with several inputs | where each input sits after ffmpeg-skill join.py joined them (empty for one input) |
27
- | `captions` | `[{start, end, text}]` | your SRT / VTT / JSON | text exactly as written, timed on the (joined) source |
27
+ | `captions` | `[{start, end, text}]` | your SRT / VTT / JSON, or grouped from `words` | text exactly as written, timed on the (joined) source |
28
+ | `words` | `[{start, end, text}]` | `--words` (whisper JSON with word timestamps, `{"words": [...]}` or a list) | per-word timings with the engine's own spacing; Karaoke lights them up |
28
29
  | `warnings` | `[string]` | analyze.py | VFR, HDR, rotation, odd frame rate |
29
30
 
30
31
  All times are seconds on the source timeline. Frames are `Math.round(seconds * fps)` (round
@@ -40,6 +41,7 @@ composition exactly.
40
41
  | `PeakPulse` | source duration | source + edge glow and slight zoom on each audio peak (scaled by its rms) or on each measured beat (`driver`), flash on scene cuts, progress bar with cut ticks |
41
42
  | `Titled` | source duration | source + the user's lower thirds (`lowerThirds`) + a title card at the start of each measured scene (`sceneTitles`, in order) |
42
43
  | `Highlights` | sum of `highlights` (whole file if none) | ranked ranges back to back in source order, flash on cuts, "2 / 5" counter, `title` over the first |
44
+ | `Karaoke` | source duration | caption cues whose words light up at their measured times (current word accent + lift, spoken white, upcoming dimmed); cues without timed words show plain |
43
45
  | `BeatMontage` | source duration | audio unbroken; the picture cuts every `beatsPerCut` measured beats, cycling through highlights (or scenes); no usable grid → cuts on scene changes |
44
46
 
45
47
  ## Options (`--options look.json`)
@@ -84,6 +86,7 @@ Example:
84
86
 
85
87
  - **SRT** and **WebVTT**: timing lines `00:00:01,000 --> 00:00:03,500` (comma or dot), multi-line cue text kept; simple formatting tags (`<i>`, `<b>`, `<c>`, `<v ...>`) are stripped.
86
88
  - **JSON**: `[{"start": 1.0, "end": 3.5, "text": "..."}]` or `{"cues": [...]}`.
89
+ - **Word timings** (`--words`): whisper / faster-whisper JSON made with word timestamps (`segments[].words[]` with `word`, `start`, `end`), `{"words": [...]}` or a plain list. With no `--captions`, cues are grouped mechanically: a new cue after a pause over 0.7 s, past 32 characters or 4 s. Words are never added, dropped or reworded.
87
90
 
88
91
  ## Adding your own composition
89
92
 
@@ -77,3 +77,65 @@ def read_captions(path: Path) -> List[Dict]:
77
77
  else:
78
78
  cues = parse_srt_or_vtt(text)
79
79
  return sorted(cues, key=lambda c: c["start"])
80
+
81
+
82
+ # ---------------------------------------------------------------- word timings (karaoke)
83
+
84
+ def parse_words(text: str) -> List[Dict]:
85
+ """Word timings from a speech engine's JSON, as [{start, end, text}] in time order.
86
+
87
+ Accepts the whisper / faster-whisper layout ({"segments": [{"words": [{"word", "start", "end"}]}]}),
88
+ a top-level {"words": [...]} and a plain list. `text` keeps the engine's own spacing (English words
89
+ carry a leading space, Japanese tokens none), so joining them reproduces the transcript exactly.
90
+ """
91
+ data = json.loads(text)
92
+ raw: List[Dict] = []
93
+ if isinstance(data, dict) and isinstance(data.get("segments"), list):
94
+ for seg in data["segments"]:
95
+ raw += list(seg.get("words") or [])
96
+ elif isinstance(data, dict) and isinstance(data.get("words"), list):
97
+ raw = data["words"]
98
+ elif isinstance(data, list):
99
+ raw = data
100
+ else:
101
+ raise CaptionError("word timings must be whisper JSON (segments[].words[]) or a list of {word, start, end}")
102
+ words: List[Dict] = []
103
+ for i, w in enumerate(raw):
104
+ try:
105
+ body = str(w.get("word", w.get("text")))
106
+ start, end = float(w["start"]), float(w["end"])
107
+ except (AttributeError, KeyError, TypeError, ValueError):
108
+ raise CaptionError(f"word {i} needs word/text, start and end")
109
+ if body in ("", "None") or end < start:
110
+ continue
111
+ words.append({"start": round(start, 3), "end": round(max(end, start + 0.01), 3), "text": body})
112
+ if not words:
113
+ raise CaptionError("no timed words found (was the transcript made with word timestamps?)")
114
+ return sorted(words, key=lambda w: w["start"])
115
+
116
+
117
+ def read_words(path: Path) -> List[Dict]:
118
+ return parse_words(path.read_text(encoding="utf-8-sig"))
119
+
120
+
121
+ def cues_from_words(words: List[Dict], max_chars: int = 32, max_gap: float = 0.7, max_len: float = 4.0) -> List[Dict]:
122
+ """Group timed words into caption cues mechanically: a new cue after a pause longer than max_gap,
123
+ when the cue would pass max_chars characters, or last longer than max_len seconds. The words and
124
+ their order are the engine's; nothing is added, dropped or reworded."""
125
+ cues: List[Dict] = []
126
+ cur: List[Dict] = []
127
+ for w in words:
128
+ if cur:
129
+ text_len = len("".join(x["text"] for x in cur + [w]).strip())
130
+ if (w["start"] - cur[-1]["end"] > max_gap or text_len > max_chars
131
+ or w["end"] - cur[0]["start"] > max_len):
132
+ cues.append(_cue(cur))
133
+ cur = []
134
+ cur.append(w)
135
+ if cur:
136
+ cues.append(_cue(cur))
137
+ return cues
138
+
139
+
140
+ def _cue(ws: List[Dict]) -> Dict:
141
+ return {"start": ws[0]["start"], "end": ws[-1]["end"], "text": "".join(w["text"] for w in ws).strip()}
@@ -221,7 +221,7 @@ def validate_timeline(t: Any) -> List[str]:
221
221
  v = src.get(k)
222
222
  if not isinstance(v, (int, float)) or v <= 0:
223
223
  p.append(f"source.{k} must be a positive number")
224
- for k in ("scenes", "silences", "speech", "peaks", "captions", "highlights"):
224
+ for k in ("scenes", "silences", "speech", "peaks", "captions", "highlights", "words"):
225
225
  if not isinstance(t.get(k, []), list):
226
226
  p.append(f"{k} must be a list")
227
227
  for i, c in enumerate(t.get("captions", []) or []):
@@ -250,7 +250,7 @@ def expected_frames(comp: str, t: Dict[str, Any]) -> Optional[int]:
250
250
  and render.py then only reports the measured numbers.
251
251
  """
252
252
  fps = float(t["source"]["fps"])
253
- if comp in ("Captioned", "PeakPulse", "Titled", "BeatMontage"):
253
+ if comp in ("Captioned", "PeakPulse", "Titled", "BeatMontage", "Karaoke"):
254
254
  return max(1, sec_to_frames(float(t["source"]["duration"]), fps))
255
255
  if comp in ("Jumpcut", "Highlights"):
256
256
  if comp == "Jumpcut":
@@ -264,7 +264,7 @@ def expected_frames(comp: str, t: Dict[str, Any]) -> Optional[int]:
264
264
 
265
265
  # ---------------------------------------------------------------- Remotion project
266
266
 
267
- BUILTIN_COMPOSITIONS = ("Captioned", "Jumpcut", "PeakPulse", "Titled", "Highlights", "BeatMontage")
267
+ BUILTIN_COMPOSITIONS = ("Captioned", "Jumpcut", "PeakPulse", "Titled", "Highlights", "BeatMontage", "Karaoke")
268
268
 
269
269
 
270
270
  def remotion_bin(project: Path) -> Path:
@@ -293,7 +293,11 @@ def remotion_error(text: str, limit: int = 15) -> str:
293
293
  for i, ln in enumerate(lines):
294
294
  if "An error occurred" in ln:
295
295
  return "\n".join(ln2.strip() for ln2 in lines[i + 1:i + 1 + limit])
296
- return "\n".join(lines[-limit:])
296
+ # No marker: the Error lines themselves, without the JavaScript stack frames under them.
297
+ errors = [ln.strip() for ln in lines if "Error" in ln and not ln.lstrip().startswith("at ")]
298
+ if errors:
299
+ return "\n".join(errors[-limit:])
300
+ return "\n".join(ln for ln in lines if not ln.lstrip().startswith("at "))[-4000:] or "\n".join(lines[-limit:])
297
301
 
298
302
 
299
303
  def stage_source(project: Path, source_path: str) -> str:
@@ -91,6 +91,65 @@ TOOL_META: Dict[str, Dict[str, Any]] = {
91
91
  },
92
92
  }
93
93
 
94
+ # What each tool's --json result carries (beyond the shared status / dry_run / output), as
95
+ # key -> short type. "result" is a completed run, "dry_run" a --dry-run plan. tests check real
96
+ # outputs against these, so the contract cannot promise a key a script stopped writing.
97
+ OUTPUTS: Dict[str, Dict[str, Dict[str, str]]] = {
98
+ "analyze": {
99
+ "result": {"commands": "list[str]", "verified": "bool", "summary": "object: duration, fps, size, scenes, "
100
+ "silences, speech_seconds, peaks, captions, beats, tempo_bpm, highlights, clips, words",
101
+ "warnings": "list[str]"},
102
+ "dry_run": {"commands": "list[str]"},
103
+ },
104
+ "init": {
105
+ "result": {"commands": "list[str]", "installed": "bool", "entry": "str", "compositions": "list[str]"},
106
+ "dry_run": {"commands": "list[str]"},
107
+ },
108
+ "still": {
109
+ "result": {"outputs": "list[str] (PNG paths)", "frames": "list[int]", "commands": "list[str]",
110
+ "verified": "bool", "frame": "object|null {width, height, fit}", "font": "str|null"},
111
+ "dry_run": {"outputs": "list[str]", "frames": "list[int]", "commands": "list[str]"},
112
+ },
113
+ "render": {
114
+ "result": {"verified": "bool", "verification": "list[{check, status, value, expected}]",
115
+ "commands": "list[str]", "look": "str|null (contact sheet PNG)", "look_error": "str|null",
116
+ "summary": "str", "frame": "object|null", "font": "str|null", "mode": "full|overlay",
117
+ "graphics": "str|null (kept ProRes 4444 layer)", "kind": "null|failed",
118
+ "error": "null|str (which verification rows failed)"},
119
+ "dry_run": {"commands": "list[str]", "props": "str", "expected_frames": "int|null", "frame": "object|null",
120
+ "font": "str|null"},
121
+ },
122
+ "deliver": {
123
+ "result": {"checked": "str", "platform": "str|null", "verified": "bool",
124
+ "checks": "list[{check, status, value, expected, ...}] (ffmpeg-skill check.py rows)",
125
+ "failed": "list[str]", "warnings": "list[str]", "commands": "list[str]",
126
+ "kind": "null|failed", "error": "null|str"},
127
+ "dry_run": {"commands": "list[str]"},
128
+ },
129
+ "pipeline": {
130
+ "result": {"timeline": "str", "render": "str", "deliverable": "str|null", "look": "str|null",
131
+ "verified": "bool", "warnings": "list[str]", "steps": "list[{step, status, output, command}]"},
132
+ "dry_run": {"steps": "list[{step, status, output, command}]"},
133
+ },
134
+ "doctor": {
135
+ "result": {"ok": "bool", "version": "str", "checks": "list[{check, ok, value, fix}]",
136
+ "ffmpeg_skill_doctor": "object|null"},
137
+ "dry_run": {},
138
+ },
139
+ }
140
+ SHARED_OUTPUT = {"status": "completed|failed", "dry_run": "bool", "output": "str|null (main artifact)"}
141
+ FAILURE_OUTPUT = {"status": "failed", "error": "str", "kind": "input|missing_tool|timeout|failed", "dry_run": "bool"}
142
+
143
+
144
+ def missing_output_keys(tool: str, doc: Dict[str, Any]) -> List[str]:
145
+ """Keys the contract promises for this result that `doc` lacks (empty = conforms)."""
146
+ if doc.get("status") == "failed":
147
+ return [k for k in FAILURE_OUTPUT if k not in doc]
148
+ which = "dry_run" if doc.get("dry_run") else "result"
149
+ want = list(OUTPUTS[tool][which]) + [k for k in SHARED_OUTPUT if not (tool == "doctor" and k == "output")]
150
+ return [k for k in want if k not in doc]
151
+
152
+
94
153
  # Flags every tool takes; the MCP server adds --json itself.
95
154
  SHARED = {"json", "dry_run", "overwrite", "timeout", "help"}
96
155
 
@@ -111,8 +170,10 @@ def _json_type(action: argparse.Action) -> Dict[str, Any]:
111
170
  t = {"type": "string"}
112
171
  if action.choices:
113
172
  t["enum"] = list(action.choices)
114
- if isinstance(action, argparse._AppendAction):
173
+ if isinstance(action, argparse._AppendAction) or action.nargs in ("+", "*"):
115
174
  t = {"type": "array", "items": t}
175
+ if action.nargs == "+":
176
+ t["minItems"] = 1
116
177
  return t
117
178
 
118
179
 
@@ -168,6 +229,7 @@ def tool_spec(name: str) -> Dict[str, Any]:
168
229
  "dry_run": meta["dry_run"],
169
230
  "inputSchema": input_schema(parser),
170
231
  "flags": flag_for(parser),
232
+ "output": OUTPUTS[name],
171
233
  }
172
234
 
173
235
 
@@ -180,6 +242,8 @@ def build() -> Dict[str, Any]:
180
242
  "depends_on": {"ffmpeg-skill": "https://github.com/kajisho5/ffmpeg-skill", "node": ">=18",
181
243
  "python": ">=3.10"},
182
244
  "roles": ROLES,
245
+ "output_shared": SHARED_OUTPUT,
246
+ "output_failure": FAILURE_OUTPUT,
183
247
  "conventions": {
184
248
  "output": "one JSON object on stdout with --json; human lines on stderr",
185
249
  "errors": {"input": 2, "missing_tool": 3, "timeout": 4, "failed": 1},
@@ -0,0 +1,81 @@
1
+ #!/usr/bin/env python3
2
+ """Generate references/scripts.md from the contract (internal; not a tool).
3
+
4
+ python3 scripts/_docs.py # rewrite references/scripts.md
5
+ python3 scripts/_docs.py --check # exit 1 if it is out of date (tests run this)
6
+
7
+ The reference is generated, never edited by hand, so it cannot drift from the scripts' own parsers.
8
+ """
9
+ import sys
10
+ from pathlib import Path
11
+
12
+ HERE = Path(__file__).resolve().parent
13
+ sys.path.insert(0, str(HERE))
14
+ import _contract # noqa: E402
15
+
16
+ OUT = HERE.parent / "references" / "scripts.md"
17
+
18
+
19
+ def render() -> str:
20
+ c = _contract.build()
21
+ lines = [
22
+ "# Script reference",
23
+ "",
24
+ "<!-- Generated by scripts/_docs.py from scripts/_contract.py. Do not edit by hand. -->",
25
+ "",
26
+ # No package version here: a version bump must not make the generated reference stale.
27
+ f"Contract {c['contract_version']} · timeline schema `{c['timeline_schema']}`.",
28
+ "Every script also takes `--json`, `--dry-run`, `--overwrite` and `--timeout SECONDS`.",
29
+ "Exit codes: " + ", ".join(f"{k} = {v}" for k, v in c["conventions"]["errors"].items()) + ".",
30
+ "",
31
+ ]
32
+ for t in c["tools"]:
33
+ s = t["inputSchema"]
34
+ lines += [f"## {t['name']}.py", "", t["summary"], "",
35
+ f"- Role: {t['role']} — {c['roles'][t['role']]}",
36
+ f"- Writes: {t['writes'] or 'nothing'}",
37
+ f"- Verifies: {t['verification']}",
38
+ f"- ffmpeg-skill: {', '.join(t['ffmpeg_skill']) or '—'}",
39
+ f"- `--dry-run`: {'plans without writing' if t['dry_run'] else 'not applicable (reports only)'}",
40
+ "", "| Argument | Type | Default | Meaning |", "|---|---|---|---|"]
41
+ for name, p in s["properties"].items():
42
+ if name in ("dry_run", "overwrite", "timeout"):
43
+ continue
44
+ arg = name if name in s["x-positional"] else t["flags"].get(name, "--" + name.replace("_", "-"))
45
+ if name in s["required"] and name not in s["x-positional"]:
46
+ arg += " (required)"
47
+ typ = p.get("type", "")
48
+ if typ == "array":
49
+ typ = f"{p['items'].get('type', '')}, repeatable"
50
+ if "enum" in p or ("items" in p and "enum" in p["items"]):
51
+ typ += ": " + " / ".join(map(str, p.get("enum") or p["items"]["enum"]))
52
+ default = f"`{p['default']}`" if "default" in p else ""
53
+ desc = (p.get("description") or "").replace("|", "\\|").replace("\n", " ")
54
+ lines.append(f"| `{arg}` | {typ} | {default} | {desc} |")
55
+ lines.append("")
56
+ for which, title in (("result", "--json result"), ("dry_run", "--dry-run --json result")):
57
+ keys = t["output"][which]
58
+ if keys:
59
+ lines.append(f"{title} (besides `status`, `dry_run`, `output`): " +
60
+ ", ".join(f"`{k}` ({v})" for k, v in keys.items()))
61
+ lines.append("")
62
+ lines += ["## Failures", "",
63
+ "Every failure is one JSON object: " + ", ".join(f"`{k}` ({v})" for k, v in c["output_failure"].items()) + ".", ""]
64
+ return "\n".join(lines)
65
+
66
+
67
+ def main() -> None:
68
+ text = render()
69
+ if "--check" in sys.argv:
70
+ current = OUT.read_text(encoding="utf-8") if OUT.exists() else ""
71
+ if current != text:
72
+ print("references/scripts.md is out of date: run python3 scripts/_docs.py", file=sys.stderr)
73
+ sys.exit(1)
74
+ print("references/scripts.md is up to date")
75
+ return
76
+ OUT.write_text(text, encoding="utf-8")
77
+ print(f"wrote {OUT}")
78
+
79
+
80
+ if __name__ == "__main__":
81
+ main()
@@ -24,7 +24,7 @@ sys.path.insert(0, str(Path(__file__).resolve().parent))
24
24
  from _common import (STATE, TIMELINE_SCHEMA, SKILL_ID, add_common, apply_common, default_output, die,
25
25
  emit, ffmpeg_skill_version, ffskill, ffskill_cmd, info, refuse_existing,
26
26
  require_ffmpeg_skill, shell_join, version)
27
- from _captions import CaptionError, read_captions
27
+ from _captions import CaptionError, cues_from_words, read_captions, read_words
28
28
 
29
29
 
30
30
  def build_parser() -> argparse.ArgumentParser:
@@ -37,6 +37,8 @@ def build_parser() -> argparse.ArgumentParser:
37
37
  p.add_argument("--join-duration", type=float, default=0.5, help="transition length in seconds (default 0.5)")
38
38
  p.add_argument("-o", "--output", help="timeline file (default: <name>.timeline.json)")
39
39
  p.add_argument("--captions", help="SRT, WebVTT or JSON cue list to carry into the timeline (text kept as written)")
40
+ p.add_argument("--words", help="word timings from a speech engine (whisper JSON with word timestamps) for the "
41
+ "Karaoke composition; without --captions the cues are grouped from these words")
40
42
  p.add_argument("--beats", action="store_true", help="also measure the beat grid (scenes.py --beats)")
41
43
  p.add_argument("--highlights", type=int, metavar="N",
42
44
  help="also rank N highlight ranges (scenes.py --highlights; audio energy) for the Highlights composition")
@@ -112,6 +114,18 @@ def main() -> None:
112
114
  except (CaptionError, ValueError) as e:
113
115
  die(f"cannot read {cpath}: {e}", "input")
114
116
 
117
+ words: List[Dict[str, Any]] = []
118
+ if a.words:
119
+ wpath = Path(a.words).expanduser()
120
+ if not wpath.is_file():
121
+ die(f"word timings file not found: {wpath}", "input")
122
+ try:
123
+ words = read_words(wpath)
124
+ except (CaptionError, ValueError) as e:
125
+ die(f"cannot read {wpath}: {e}", "input")
126
+ if not captions:
127
+ captions = cues_from_words(words)
128
+
115
129
  join_args = [*map(str, inputs), "-o", str(joined), "--transition", a.join_transition,
116
130
  "--duration", str(a.join_duration)] + (["--overwrite"] if STATE.overwrite else [])
117
131
  plan = ([shell_join(ffskill_cmd("join", join_args))] if len(inputs) > 1 else []) + \
@@ -211,6 +225,7 @@ def main() -> None:
211
225
  "highlights": highlights,
212
226
  "clips": clips,
213
227
  "captions": captions,
228
+ "words": words,
214
229
  "warnings": warnings_for(probe),
215
230
  }
216
231
  if not video:
@@ -230,7 +245,7 @@ def main() -> None:
230
245
  "speech_seconds": round(speech_total, 3), "peaks": len(peaks),
231
246
  "captions": len(captions), "beats": bool(beats and beats.get("usable")),
232
247
  "tempo_bpm": (beats or {}).get("tempo_bpm"), "highlights": len(highlights),
233
- "clips": len(clips) or 1},
248
+ "clips": len(clips) or 1, "words": len(words)},
234
249
  "warnings": timeline["warnings"]},
235
250
  f"wrote {out}: {timeline['source']['duration']}s, {len(scenes)} scenes, {len(silences)} silences "
236
251
  f"(speech {speech_total:.2f}s), {len(peaks)} peaks, {len(captions)} captions")
@@ -69,7 +69,10 @@ def main() -> None:
69
69
  lines = [f"{c['status']:4} {c['check']}: {c.get('value')} (expected {c.get('expected')})" for c in checks]
70
70
  emit({"status": "completed" if ok else "failed", "output": str(target) if target != src else None,
71
71
  "checked": str(target), "platform": a.platform, "verified": ok, "checks": checks,
72
- "failed": [c["check"] for c in failed], "warnings": [c["check"] for c in warns], "commands": commands},
72
+ "failed": [c["check"] for c in failed], "warnings": [c["check"] for c in warns], "commands": commands,
73
+ "kind": None if ok else "failed",
74
+ "error": None if ok else ("compliance check failed: " + ", ".join(c["check"] for c in failed)
75
+ if failed else (ck.get("error") or "check.py returned no rows"))},
73
76
  "\n".join([f"{target.name}: {'PASS' if ok else 'FAIL'} ({len(failed)} fail, {len(warns)} warn)"] + lines))
74
77
  if not ok:
75
78
  sys.exit(1)
package/scripts/render.py CHANGED
@@ -34,7 +34,9 @@ def build_parser() -> argparse.ArgumentParser:
34
34
  p.add_argument("--crf", type=int, help="h264 quality (Remotion default 18; lower = better)")
35
35
  p.add_argument("--frames", help="render only this frame range, e.g. 0-89 (inclusive)")
36
36
  p.add_argument("--fast", action="store_true", help="preview quality: half resolution, quicker encode")
37
- p.add_argument("--concurrency", help="Remotion --concurrency (number or percentage)")
37
+ p.add_argument("--concurrency", default="100%",
38
+ help="parallel browser tabs: a number up to the CPU cores, or a percentage (default 100%%: all "
39
+ "cores -- about twice as fast as Remotion's own default of half the cores)")
38
40
  p.add_argument("--no-look", action="store_true", help="skip the contact sheet")
39
41
  p.add_argument("--overlay", action="store_true",
40
42
  help="draw the graphics only as a transparent ProRes 4444 layer and composite it over the "
@@ -148,7 +150,7 @@ def main() -> None:
148
150
  if a.overlay:
149
151
  if a.comp in ("Jumpcut", "Highlights", "BeatMontage"):
150
152
  die(f"--overlay cannot do {a.comp}: its cuts move the picture itself (overlay works for "
151
- "Captioned, PeakPulse, Titled)", "input")
153
+ "Captioned, PeakPulse, Titled, Karaoke)", "input")
152
154
  if a.aspect not in (None, "source") or a.width is not None or a.fit not in (None, "contain"):
153
155
  die("--overlay draws on the source's own frame: drop --aspect / --width / --fit", "input")
154
156
  if a.fast or a.codec != "h264" or frames:
@@ -190,20 +192,30 @@ def main() -> None:
190
192
  probe = ffskill("probe", [str(output)])
191
193
  ok, rows = verify(probe, timeline, a.comp, frames, a.fast, frame)
192
194
  look: Optional[str] = None
195
+ look_error: Optional[str] = None
193
196
  commands.append(probe["_command"])
194
197
  if not a.no_look:
195
198
  lk = ffskill("look", [str(output), "--tiles", "3x2"], allow_fail=True)
196
199
  if lk.get("status") == "completed":
197
200
  look = lk.get("output")
201
+ if look and not Path(look).is_absolute():
202
+ look = str((Path.cwd() / look).resolve())
198
203
  commands.append(lk.get("_command", ""))
204
+ else:
205
+ look_error = f"{lk.get('kind') or 'failed'}: {str(lk.get('error') or '')[-400:]}"
206
+ if "drawtext" in look_error:
207
+ look_error += (" -- this FFmpeg build has no drawtext filter. macOS Homebrew: `brew install ffmpeg-full` "
208
+ "(the plain ffmpeg formula dropped it); use still.py frames to look meanwhile")
209
+ info(f"warning: contact sheet failed ({look_error}); view the render itself")
199
210
  v = probe.get("video") or {}
200
211
  summary = (f"{output.name}: {float(probe.get('duration') or 0):.2f} s, {v.get('width')}x{v.get('height')}, "
201
212
  f"{v.get('fps')} fps, {'audio' if probe.get('audio') else 'no audio'}")
202
213
  result = {"status": "completed" if ok else "failed", "output": str(output), "verified": ok,
203
214
  "verification": rows, "commands": commands, "look": look, "summary": summary,
204
- "frame": frame, "font": font_note, "mode": "overlay" if a.overlay else "full",
215
+ "frame": frame, "font": font_note, "mode": "overlay" if a.overlay else "full", "look_error": look_error,
205
216
  "graphics": str(graphics) if a.overlay and a.keep_graphics else None,
206
- "kind": None if ok else "failed"}
217
+ "kind": None if ok else "failed",
218
+ "error": None if ok else "verification failed: " + ", ".join(r["check"] for r in rows if r["status"] == "FAIL")}
207
219
  table = "\n".join(f" {r['check']:<9} {r['status']:<4} {r['value']} (expected {r['expected']})" for r in rows)
208
220
  emit(result, summary + "\n" + table + (f"\nLook: {look}" if look else "") +
209
221
  ("" if ok else "\nverification FAILED: " + ", ".join(r["check"] for r in rows if r["status"] == "FAIL")))
@@ -6,6 +6,7 @@ import { PeakPulse } from "./compositions/PeakPulse";
6
6
  import { Titled } from "./compositions/Titled";
7
7
  import { Highlights } from "./compositions/Highlights";
8
8
  import { BeatMontage } from "./compositions/BeatMontage";
9
+ import { Karaoke } from "./compositions/Karaoke";
9
10
  import { SAMPLE_TIMELINE, fullLengthFrames, highlightFrames, jumpcutFrames, outputFrame, type Props, type Timeline } from "./timeline";
10
11
 
11
12
  // Length and fps come from the measured timeline, never from constants; the frame is the
@@ -28,5 +29,6 @@ export const RemotionRoot: React.FC = () => (
28
29
  <Composition id="Titled" component={Titled} {...base} calculateMetadata={metadataFrom(fullLengthFrames)} />
29
30
  <Composition id="Highlights" component={Highlights} {...base} calculateMetadata={metadataFrom(highlightFrames)} />
30
31
  <Composition id="BeatMontage" component={BeatMontage} {...base} calculateMetadata={metadataFrom(fullLengthFrames)} />
32
+ <Composition id="Karaoke" component={Karaoke} {...base} calculateMetadata={metadataFrom(fullLengthFrames)} />
31
33
  </>
32
34
  );
@@ -0,0 +1,104 @@
1
+ import React from "react";
2
+ import { AbsoluteFill, Sequence, interpolate, spring, useCurrentFrame, useVideoConfig } from "remotion";
3
+ import { SourceVideo } from "../lib/SourceVideo";
4
+ import { useStagedFont } from "../lib/useStagedFont";
5
+ import { captionMarginPx } from "./Captioned";
6
+ import { Props, fontStack, outputFrame, resolveOptions, secToFrames, type Caption, type Options } from "../timeline";
7
+
8
+ /**
9
+ * Karaoke: each caption cue with its words lit one by one at the times the speech engine measured
10
+ * (analyze.py --words). The current word takes the accent colour and lifts, spoken words stay white,
11
+ * words still to come are dimmed. Cues without timed words fall back to a plain caption.
12
+ */
13
+ export const Karaoke: React.FC<Props> = (props) => {
14
+ const { timeline, options, font, overlay } = props;
15
+ useStagedFont(font);
16
+ const o = resolveOptions(options);
17
+ const family = fontStack(o, font);
18
+ const { fps } = useVideoConfig();
19
+ const words = timeline.words ?? [];
20
+ return (
21
+ <AbsoluteFill style={{ backgroundColor: overlay ? "transparent" : "black" }}>
22
+ {overlay ? null : <SourceVideo source={timeline.source} fit={outputFrame(props).fit} />}
23
+ {timeline.captions.map((c, i) => {
24
+ const from = secToFrames(c.start, fps);
25
+ const dur = Math.max(1, secToFrames(c.end, fps) - from);
26
+ // Words that belong to this cue: their midpoint falls inside it.
27
+ const own = words.filter((w) => (w.start + w.end) / 2 >= c.start && (w.start + w.end) / 2 <= c.end);
28
+ return (
29
+ <Sequence key={i} from={from} durationInFrames={dur} name={`cue ${i + 1}`} layout="none">
30
+ <KaraokeCue cue={c} words={own} len={dur} o={o} fontFamily={family} />
31
+ </Sequence>
32
+ );
33
+ })}
34
+ </AbsoluteFill>
35
+ );
36
+ };
37
+
38
+ const KaraokeCue: React.FC<{ cue: Caption; words: Caption[]; len: number; o: Options; fontFamily: string }> = ({
39
+ cue,
40
+ words,
41
+ len,
42
+ o,
43
+ fontFamily,
44
+ }) => {
45
+ const frame = useCurrentFrame();
46
+ const { fps, width, height } = useVideoConfig();
47
+ const enter = spring({ frame, fps, config: { damping: 14, stiffness: 180, mass: 0.6 } });
48
+ const fade = Math.min(6, Math.floor(len / 3));
49
+ const exit = fade > 0 ? interpolate(frame, [len - fade, len], [1, 0], { extrapolateLeft: "clamp", extrapolateRight: "clamp" }) : 1;
50
+ const size = Math.round(Math.min(width, height) * o.captionSize * 1.1);
51
+ const now = cue.start + frame / fps; // source time at this frame
52
+ const lang = /[぀-ヿ]/.test(cue.text) ? "ja" : /[가-힯]/.test(cue.text) ? "ko" : undefined;
53
+ return (
54
+ <AbsoluteFill style={{ justifyContent: "flex-end", alignItems: "center", paddingBottom: captionMarginPx(o, width, height) }}>
55
+ <div
56
+ lang={lang}
57
+ style={{
58
+ maxWidth: width * 0.88,
59
+ padding: `${size * 0.25}px ${size * 0.55}px`,
60
+ borderRadius: size * 0.3,
61
+ background: "rgba(0,0,0,0.6)",
62
+ fontFamily,
63
+ fontWeight: 800,
64
+ fontSize: size,
65
+ lineHeight: 1.35,
66
+ textAlign: "center",
67
+ whiteSpace: "pre-wrap",
68
+ textWrap: "balance",
69
+ opacity: Math.min(enter, exit),
70
+ transform: `translateY(${(1 - enter) * size * 0.5}px)`,
71
+ }}
72
+ >
73
+ {words.length === 0 ? (
74
+ <span style={{ color: o.textColor }}>{cue.text}</span>
75
+ ) : (
76
+ words.map((w, i) => {
77
+ const spoken = now >= w.end;
78
+ const active = now >= w.start && now < w.end;
79
+ // A lift, not a scale: scaling a word would grow it over the spaces beside it.
80
+ const lift = active ? interpolate(now, [w.start, Math.min(w.end, w.start + 0.12)], [-0.12, -0.05], { extrapolateRight: "clamp" }) : 0;
81
+ // The engine's leading space stays a plain text node between words: inside an
82
+ // inline-block it would collapse and glue the words together.
83
+ const lead = w.text.match(/^\s*/)?.[0] ?? "";
84
+ return (
85
+ <React.Fragment key={i}>
86
+ {lead}
87
+ <span
88
+ style={{
89
+ color: active ? o.accent : spoken ? o.textColor : "rgba(255,255,255,0.45)",
90
+ display: "inline-block",
91
+ transform: `translateY(${lift}em)`,
92
+ textShadow: active ? `0 0 0.35em ${o.accent}` : "none",
93
+ }}
94
+ >
95
+ {w.text.slice(lead.length)}
96
+ </span>
97
+ </React.Fragment>
98
+ );
99
+ })
100
+ )}
101
+ </div>
102
+ </AbsoluteFill>
103
+ );
104
+ };
@@ -37,6 +37,8 @@ export type Timeline = {
37
37
  /** Several inputs joined by ffmpeg-skill: where each clip sits on the joined timeline. */
38
38
  clips?: { name: string; start: number; end: number }[];
39
39
  captions: Caption[];
40
+ /** Word timings from a speech engine (analyze.py --words), text with the engine's own spacing. */
41
+ words?: Caption[];
40
42
  warnings?: string[];
41
43
  };
42
44