remotion-ffmpeg-skill 0.0.0-stage → 0.2.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.
Files changed (32) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +112 -2
  3. package/SKILL.md +66 -0
  4. package/bin/remotion-ffmpeg-skill.js +100 -0
  5. package/mcp/server.py +150 -0
  6. package/package.json +12 -4
  7. package/references/timeline.md +93 -0
  8. package/scripts/_captions.py +79 -0
  9. package/scripts/_common.py +538 -0
  10. package/scripts/_contract.py +202 -0
  11. package/scripts/analyze.py +240 -0
  12. package/scripts/deliver.py +79 -0
  13. package/scripts/doctor.py +83 -0
  14. package/scripts/init.py +62 -0
  15. package/scripts/pipeline.py +122 -0
  16. package/scripts/render.py +215 -0
  17. package/scripts/still.py +84 -0
  18. package/templates/remotion-project/package.json +20 -0
  19. package/templates/remotion-project/public/.gitkeep +0 -0
  20. package/templates/remotion-project/remotion.config.ts +6 -0
  21. package/templates/remotion-project/src/Root.tsx +32 -0
  22. package/templates/remotion-project/src/compositions/BeatMontage.tsx +60 -0
  23. package/templates/remotion-project/src/compositions/Captioned.tsx +95 -0
  24. package/templates/remotion-project/src/compositions/Highlights.tsx +98 -0
  25. package/templates/remotion-project/src/compositions/Jumpcut.tsx +52 -0
  26. package/templates/remotion-project/src/compositions/PeakPulse.tsx +73 -0
  27. package/templates/remotion-project/src/compositions/Titled.tsx +138 -0
  28. package/templates/remotion-project/src/index.ts +4 -0
  29. package/templates/remotion-project/src/lib/SourceVideo.tsx +84 -0
  30. package/templates/remotion-project/src/lib/useStagedFont.ts +25 -0
  31. package/templates/remotion-project/src/timeline.ts +214 -0
  32. package/templates/remotion-project/tsconfig.json +15 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 kajisho5
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,113 @@
1
- # Temporary Holding Version
1
+ # remotion-ffmpeg-skill
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ **ffmpeg-skill measures the footage. Remotion draws from those measurements. ffmpeg-skill checks and delivers the result.**
4
+
5
+ An [Agent Skill](https://docs.claude.com/en/docs/agents-and-tools/agent-skills/overview) for Claude Code, Cursor and Codex that puts Remotion motion graphics on *real recordings* — and never guesses a number. Composition length, fps and frame size come from the probe; cuts come from measured silences; pulses hit on measured audio peaks; captions keep the timing of your SRT. Every render is verified frame-for-frame against its timeline and inspected with a contact sheet before it ships.
6
+
7
+ Built on [**ffmpeg-skill**](https://github.com/kajisho5/ffmpeg-skill). Unofficial — not affiliated with Remotion.
8
+
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
+
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>
12
+
13
+ ## Why this and not just Remotion's own skills?
14
+
15
+ [Remotion's official Agent Skills](https://www.remotion.dev/docs/ai/skills) teach an agent to *write* good Remotion code. This skill closes the loop around it:
16
+
17
+ | | Remotion skills | remotion-ffmpeg-skill |
18
+ |---|---|---|
19
+ | Writes Remotion compositions | ✅ | ✅ (three ready-made, timeline-driven) |
20
+ | Knows the source's real duration / fps / size / silences / scene cuts / audio peaks | — | ✅ measured by ffmpeg-skill |
21
+ | Warns before drawing on VFR or HDR footage | — | ✅ |
22
+ | Verifies the render (exact frame count, fps, size, audio) | — | ✅ non-zero exit on mismatch |
23
+ | Looks at the result (contact sheet) | — | ✅ |
24
+ | Delivers for YouTube / Reels / TikTok / Shorts / X with loudness and compliance checks | — | ✅ ffmpeg-skill templates + `check.py` |
25
+
26
+ They work well together: install both if you write custom compositions.
27
+
28
+ ## Install
29
+
30
+ ```bash
31
+ npx ffmpeg-skill # the measuring/delivery half (required)
32
+ npx remotion-ffmpeg-skill # this skill, next to it in ~/.claude/skills
33
+ ```
34
+
35
+ `--cursor`, `--codex`, `--all`, `--project` work for both. Requirements: Python 3.10+, Node.js 18+, FFmpeg (ffmpeg-skill's `doctor` tells you what's missing). Remotion's headless browser downloads itself on the first render.
36
+
37
+ ## What you can ask for
38
+
39
+ - "Put animated captions from `talk.srt` on `talk.mp4` and make it a YouTube upload."
40
+ - "Cut the silences out of this recording, jump-cut style, and keep the subtitles in sync."
41
+ - "Make graphics that hit on the loud moments of `clip.mp4`, as a Reel."
42
+ - "Japanese captions, vertical, for TikTok." — renders 9:16 with a blurred fill, stages a CJK font automatically, breaks lines between phrases.
43
+
44
+ ## Under the hood
45
+
46
+ ```bash
47
+ S=~/.claude/skills/remotion-ffmpeg-skill/scripts
48
+
49
+ python3 $S/init.py ./motion --install # Remotion project (pinned versions)
50
+ python3 $S/analyze.py talk.mp4 --captions talk.srt # -> talk.timeline.json (all measured)
51
+ python3 $S/still.py --project ./motion --comp Jumpcut --timeline talk.timeline.json --at 2
52
+ python3 $S/render.py --project ./motion --comp Jumpcut --timeline talk.timeline.json -o jumpcut.mp4
53
+ python3 $S/deliver.py jumpcut.mp4 --platform youtube # template + compliance table
54
+
55
+ # or all of it, each step verified before the next:
56
+ python3 $S/pipeline.py talk.mp4 --project ./motion --comp Jumpcut --captions talk.srt --platform youtube
57
+ ```
58
+
59
+ Every script takes `--json`, `--dry-run`, `--overwrite`, `--timeout`, like ffmpeg-skill.
60
+
61
+ ### MCP
62
+
63
+ ```bash
64
+ claude mcp add remotion-ffmpeg-skill -- python3 ~/.claude/skills/remotion-ffmpeg-skill/mcp/server.py
65
+ ```
66
+
67
+ Tool names and input schemas come from the machine-readable contract (`npx remotion-ffmpeg-skill contract --json`), generated from the scripts' own argument parsers.
68
+
69
+ ### Compositions
70
+
71
+ | Id | Length | What it draws |
72
+ |---|---|---|
73
+ | `Captioned` | source duration | caption cards that spring in on each cue (text exactly as written) |
74
+ | `Jumpcut` | sum of measured speech ranges | silences removed, punch-in on every other cut, captions re-timed |
75
+ | `PeakPulse` | source duration | edge glow + zoom on measured audio peaks or beats, flash on scene cuts, progress bar |
76
+ | `Titled` | source duration | your lower thirds + a title card at each measured scene change |
77
+ | `Highlights` | sum of ranked highlights | ffmpeg-skill's audio-energy highlights back to back, counter, title |
78
+ | `BeatMontage` | source duration | audio unbroken, picture cuts on the measured beat grid |
79
+
80
+ **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
+
82
+ <img src="assets/portrait-ja-still.png" width="270" alt="9:16 still with a Japanese caption, blurred fill behind the 16:9 source">
83
+
84
+ **Fonts:** Japanese / Chinese / Korean captions get the CJK font ffmpeg-skill finds on the machine, loaded before the first frame — no tofu. `--font-file` for your own.
85
+
86
+ **A layer for your editor:** `--overlay --keep-graphics` renders the graphics alone as transparent ProRes 4444 and composites it over the untouched source with ffmpeg-skill — keep the `.mov` for Premiere, Resolve or Final Cut.
87
+
88
+ Colours, font, caption size, zoom and pulse strength are options (`--options look.json`); the timeline format and every option are in [`references/timeline.md`](references/timeline.md). Add your own composition to the generated project and render it with `--comp YourId`.
89
+
90
+ ### What render.py verifies
91
+
92
+ ```text
93
+ jumpcut.mp4: 6.32 s, 1280x720, 30.0 fps, audio
94
+ size PASS 1280x720 (expected 1280x720)
95
+ fps PASS 30.0 (expected 30.0)
96
+ frames PASS 189 (expected 189)
97
+ audio PASS present (expected present)
98
+ Look: jumpcut_sheet.png
99
+ ```
100
+
101
+ Frame numbers are `Math.round(seconds × fps)` on both sides (TypeScript and Python), so the expected count is exact, not "close enough".
102
+
103
+ ## Licence
104
+
105
+ This skill is MIT. **Remotion itself has its own 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). Using this skill does not change that.
106
+
107
+ ## Speed
108
+
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`).
110
+
111
+ ## Status
112
+
113
+ 0.2.0. Tested on Linux (Node 22, Remotion 4.0.538, ffmpeg-skill 2.12.0); macOS and Windows not yet. Planned: agent evals, multi-clip sources, rendering only the captioned ranges for long footage.
package/SKILL.md ADDED
@@ -0,0 +1,66 @@
1
+ ---
2
+ name: remotion-ffmpeg-skill
3
+ description: 'Make motion graphics on real footage with Remotion, driven by measurements from ffmpeg-skill: animated captions timed from an SRT/VTT file, automatic jump cuts that drop the silences ffmpeg-skill measured (with punch-in zooms and captions re-timed), and motion that hits on measured audio peaks and scene cuts. Every composition takes its length, fps and frame size from the probed source; every render is verified (frame count, fps, size, audio) and inspected with a contact sheet, then delivered through ffmpeg-skill templates (YouTube, Reels, TikTok, Shorts, X) and its compliance check. Use this skill when the user wants Remotion, React video, motion graphics, animated captions or titles over a video, jump cuts / silence removal with motion, audio-reactive or beat-synced graphics, or a programmatic video built from a real recording -- even when they do not say "Remotion". Needs Node.js and ffmpeg-skill; local, no API keys.'
4
+ ---
5
+
6
+ # remotion-ffmpeg-skill
7
+
8
+ **ffmpeg-skill measures → Remotion draws → ffmpeg-skill checks and delivers.** Scripts live in `scripts/` next to this file; run them with `python3 <skill-dir>/scripts/<name>.py`. `--help` on a script is the full flag list; `references/timeline.md` is the timeline format and the options every composition takes.
9
+
10
+ This skill depends on [ffmpeg-skill](https://github.com/kajisho5/ffmpeg-skill) (found next to this skill, in `~/.claude/skills/ffmpeg-skill`, or via `FFMPEG_SKILL_DIR`). It never runs a raw `ffmpeg`/`ffprobe` command itself: measuring, checking and delivering go through ffmpeg-skill's scripts, so their guarantees carry over.
11
+
12
+ Shared flags (every script): `--json` (one JSON object on stdout; prefer it), `--dry-run` (plan, write nothing), `--overwrite` (the one way to replace an existing output), `--timeout SECONDS`.
13
+
14
+ ## Workflow (in this order)
15
+
16
+ 1. **Project once.** No Remotion project yet: `init.py ./motion --install` (copies the template, runs `npm install`; Remotion's headless browser downloads on the first render). An existing project from this skill: reuse it.
17
+ 2. **Measure.** `analyze.py SOURCE [--captions FILE.srt] [--beats] -o SOURCE.timeline.json`. Read the summary and the `warnings`: a VFR or HDR source must be fixed with ffmpeg-skill *before* drawing (`color.py --to-sdr`, a constant-frame-rate export) — Remotion renders SDR on a fixed frame grid. Never write or edit timeline numbers by hand; re-measure instead (`--threshold`, `--min-silence` for a quiet room).
18
+ 3. **Preview stills.** `still.py --project ./motion --comp NAME --timeline TL --at 1.5 --at 6` and view the PNGs: caption placement, punch-in, colours. Cheap; do it before a full render.
19
+ 4. **Render.** `render.py --project ./motion --comp NAME --timeline TL [--options look.json] -o OUT.mp4` (`--fast` = half-size preview, `--frames 0-89` = a range, `--codec prores -o master.mov` = a master). It verifies the output against the timeline (frame count, fps, size, audio) and exits non-zero on a mismatch.
20
+ - **Shape:** draw in the shape it will be delivered in. `--aspect 9:16` for Reels / TikTok / Shorts (`1:1`, `4:5`, `16:9` too); `--fit blur` (default when the shape changes: contained over a blurred copy), `contain` (bars) or `cover` (crop — check the subject in the still first). Never render 16:9 and let a 9:16 template crop it: captions lose their edges. `pipeline.py --platform` picks the aspect from ffmpeg-skill's template for you.
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
+ - **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
+ 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.
25
+
26
+ Options files are checked before rendering: an unknown key or a wrong type is refused (`kind: input`) instead of silently doing nothing.
27
+
28
+ MCP: `mcp/server.py` exposes the same tools (schemas from `scripts/_contract.py`, `contract --json` prints them).
29
+
30
+ Everything in one go: `pipeline.py SOURCE --project ./motion --comp NAME [--captions F] [--platform P]` runs 2→4→5 with the same checks and stops at the first failed step.
31
+
32
+ ## Request → script / composition
33
+
34
+ | Request | Run |
35
+ |---|---|
36
+ | "animated captions / subtitles on this video" | `analyze.py --captions` → `render.py --comp Captioned` |
37
+ | "cut the silences / jump cut / tighten this talk" (with motion) | `analyze.py` → `render.py --comp Jumpcut` (captions re-timed if given) |
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
+ | "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
+ | "highlight reel / best moments" | `analyze.py --highlights N [--target S]` → `render.py --comp Highlights` (audio-energy ranking: candidates, say so) |
41
+ | "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) |
42
+ | "for YouTube / Reels / TikTok ..." | `pipeline.py --platform` (renders in the template's aspect, then delivers and checks), or `render.py --aspect` + `deliver.py --platform` |
43
+ | "vertical / 9:16 / square" | `render.py --aspect 9:16` (or `1:1`, `4:5`) |
44
+ | "Japanese captions" / a specific font | nothing extra for CJK (auto font); `--font-file` for a chosen font |
45
+ | "give me the graphics as a separate layer" | `render.py --overlay --keep-graphics` |
46
+ | "change colour / font / caption size / zoom" | an `--options` JSON (`references/timeline.md`), re-render |
47
+ | several clips ("intro + talk + outro") | `analyze.py A.mp4 B.mov C.mp4` (or `pipeline.py` with several inputs): ffmpeg-skill join.py normalises and joins them, then everything is measured on the joined file |
48
+ | "preview" / "show me a frame" | `still.py` |
49
+ | a new kind of graphic | add a composition to `src/` of the project that reads `Props` from `src/timeline.ts`; render with `--comp YourId` (render.py then reports measured numbers without a built-in expectation) |
50
+ | plain cut / trim / resize / loudness with no graphics | not this skill: use ffmpeg-skill directly |
51
+ | something broke | `doctor.py [--project DIR]` |
52
+
53
+ ## What this skill decides and what it does not
54
+
55
+ - **Decides (mechanical):** composition length, fps and size (from the probe); where cuts fall (from measured silences); when cues show (from the caption file); when pulses hit (from measured peaks); whether a render matches its timeline.
56
+ - **Does not decide:** names, titles and chapter names (lower thirds and scene titles are the user's text — ask), which words a caption says — cue text is drawn exactly as written, never shortened or paraphrased, even to "make it fit" (offer a smaller `captionSize` instead); what counts as a highlight; whether a look is good. Those belong to the user or the calling agent.
57
+ - **Never invents data.** No captions without a timed caption file from the user or a local speech-to-text engine; no beat grid that `--beats` did not measure.
58
+
59
+ ## Rules that keep jobs from failing
60
+
61
+ - 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
+ - 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
+ - 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
+ - Remotion packages in a project must all be the same version; the template pins them. Don't mix in a different `remotion` version.
66
+ - A render that fails verification is a failure: report the failed rows from `--json`, don't ship it.
@@ -0,0 +1,100 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * remotion-ffmpeg-skill installer.
4
+ *
5
+ * Copies SKILL.md, scripts/, templates/ and references/ into the skills directory of one or
6
+ * more coding agents. Default target is Claude Code (~/.claude/skills/remotion-ffmpeg-skill).
7
+ *
8
+ * npx remotion-ffmpeg-skill # Claude Code
9
+ * npx remotion-ffmpeg-skill --cursor # Cursor (~/.cursor/skills/remotion-ffmpeg-skill)
10
+ * npx remotion-ffmpeg-skill --codex # Codex (~/.agents/skills/remotion-ffmpeg-skill)
11
+ * npx remotion-ffmpeg-skill --all # all of the above
12
+ * npx remotion-ffmpeg-skill --dir ./skills # custom parent directory
13
+ * npx remotion-ffmpeg-skill --project # ./.claude/skills/remotion-ffmpeg-skill
14
+ * npx remotion-ffmpeg-skill --uninstall # remove from the selected targets
15
+ * npx remotion-ffmpeg-skill doctor # what this machine can do
16
+ * npx remotion-ffmpeg-skill contract --json # machine-readable contract (tools, schemas, verification)
17
+ *
18
+ * This skill needs ffmpeg-skill next to it: `npx ffmpeg-skill` with the same target flags.
19
+ */
20
+ 'use strict';
21
+
22
+ const fs = require('fs');
23
+ const os = require('os');
24
+ const path = require('path');
25
+ const { spawnSync } = require('child_process');
26
+
27
+ const SKILL_NAME = 'remotion-ffmpeg-skill';
28
+ const ROOT = path.resolve(__dirname, '..');
29
+ const PAYLOAD = ['SKILL.md', 'scripts', 'templates', 'references', 'mcp', 'package.json', 'LICENSE'];
30
+
31
+ const args = process.argv.slice(2);
32
+ const has = (flag) => args.includes(flag);
33
+ const optValue = (flag) => {
34
+ const i = args.indexOf(flag);
35
+ return i !== -1 && args[i + 1] ? args[i + 1] : null;
36
+ };
37
+
38
+ if (has('--help') || has('-h')) {
39
+ console.log(fs.readFileSync(__filename, 'utf8').split('*/')[0].replace(/^\/\*\*?\s?|^\s\*\s?/gm, ''));
40
+ process.exit(0);
41
+ }
42
+
43
+ function python() {
44
+ const candidates = process.platform === 'win32' ? ['python3', 'python', 'py'] : ['python3'];
45
+ for (const c of candidates) {
46
+ const r = spawnSync(c, ['-c', 'import sys; raise SystemExit(0 if sys.version_info >= (3, 10) else 1)']);
47
+ if (!r.error && r.status === 0) return c;
48
+ }
49
+ return null;
50
+ }
51
+
52
+ if (args[0] === 'doctor' || args[0] === 'contract') {
53
+ const py = python();
54
+ if (!py) {
55
+ console.error('Python 3.10+ not found on PATH.');
56
+ process.exit(3);
57
+ }
58
+ const script = args[0] === 'doctor' ? 'doctor.py' : '_contract.py';
59
+ const r = spawnSync(py, [path.join(ROOT, 'scripts', script), ...args.slice(1)], { stdio: 'inherit' });
60
+ process.exit(r.status === null ? 1 : r.status);
61
+ }
62
+
63
+ const home = os.homedir();
64
+ const targets = [];
65
+ if (optValue('--dir')) targets.push(path.resolve(optValue('--dir')));
66
+ if (has('--project')) targets.push(path.resolve('.claude', 'skills'));
67
+ if (has('--cursor') || has('--all')) targets.push(path.join(home, '.cursor', 'skills'));
68
+ if (has('--codex') || has('--all')) targets.push(path.join(home, '.agents', 'skills'));
69
+ if (has('--all') || targets.length === 0) targets.unshift(path.join(home, '.claude', 'skills'));
70
+
71
+ function copy(src, dst) {
72
+ const st = fs.statSync(src);
73
+ if (st.isDirectory()) {
74
+ if (['node_modules', '__pycache__', '.rfs'].includes(path.basename(src))) return;
75
+ fs.mkdirSync(dst, { recursive: true });
76
+ for (const e of fs.readdirSync(src)) copy(path.join(src, e), path.join(dst, e));
77
+ } else {
78
+ fs.copyFileSync(src, dst);
79
+ }
80
+ }
81
+
82
+ for (const parent of [...new Set(targets)]) {
83
+ const dest = path.join(parent, SKILL_NAME);
84
+ if (has('--uninstall')) {
85
+ fs.rmSync(dest, { recursive: true, force: true });
86
+ console.log(`removed ${dest}`);
87
+ continue;
88
+ }
89
+ fs.rmSync(dest, { recursive: true, force: true });
90
+ fs.mkdirSync(dest, { recursive: true });
91
+ for (const item of PAYLOAD) {
92
+ const src = path.join(ROOT, item);
93
+ if (fs.existsSync(src)) copy(src, path.join(dest, item));
94
+ }
95
+ console.log(`installed ${SKILL_NAME} -> ${dest}`);
96
+ if (!fs.existsSync(path.join(parent, 'ffmpeg-skill', 'scripts', 'probe.py')) && !process.env.FFMPEG_SKILL_DIR) {
97
+ console.log(` note: ffmpeg-skill is not next to it yet. Install it too: npx ffmpeg-skill${parent.includes('.cursor') ? ' --cursor' : parent.includes('.agents') ? ' --codex' : ''}`);
98
+ }
99
+ }
100
+ if (!python()) console.log('warning: Python 3.10+ not found on PATH; the scripts need it.');
package/mcp/server.py ADDED
@@ -0,0 +1,150 @@
1
+ #!/usr/bin/env python3
2
+ """remotion-ffmpeg-skill as an MCP server (stdio, JSON-RPC 2.0) -- standard library only.
3
+
4
+ Every public script becomes a tool; names, order and input schemas come from the contract
5
+ (scripts/_contract.py), so this file is only the transport. Arguments are a flat object whose
6
+ keys are the CLI's argument names (positional ones included), or {"argv": [...]} for raw CLI
7
+ arguments. Results are the script's --json output, as text and as structuredContent; a failed
8
+ step comes back with isError: true and its typed error (kind: input / missing_tool / timeout / failed).
9
+
10
+ Run:
11
+ python3 mcp/server.py
12
+ Claude Code:
13
+ claude mcp add remotion-ffmpeg-skill -- python3 /path/to/remotion-ffmpeg-skill/mcp/server.py
14
+ Claude Desktop (claude_desktop_config.json):
15
+ {"mcpServers": {"remotion-ffmpeg-skill": {"command": "python3",
16
+ "args": ["/path/to/remotion-ffmpeg-skill/mcp/server.py"]}}}
17
+ ffmpeg-skill must be installed next to it or pointed to with FFMPEG_SKILL_DIR (set it in "env").
18
+ """
19
+ import json
20
+ import subprocess
21
+ import sys
22
+ from pathlib import Path
23
+ from typing import Any, Dict, List, Optional
24
+
25
+ HERE = Path(__file__).resolve().parent
26
+ SCRIPTS = HERE.parent / "scripts"
27
+ PROTOCOL_VERSION = "2024-11-05"
28
+
29
+ sys.path.insert(0, str(SCRIPTS))
30
+ import _contract # noqa: E402
31
+
32
+ _CONTRACT: Dict[str, Any] = {}
33
+
34
+
35
+ def contract() -> Dict[str, Any]:
36
+ if not _CONTRACT:
37
+ _CONTRACT.update(_contract.build())
38
+ return _CONTRACT
39
+
40
+
41
+ def spec(name: str) -> Optional[Dict[str, Any]]:
42
+ return next((t for t in contract()["tools"] if t["name"] == name), None)
43
+
44
+
45
+ def build_argv(name: str, args: Dict[str, Any]) -> List[str]:
46
+ if isinstance(args.get("argv"), list):
47
+ argv = [str(a) for a in args["argv"]]
48
+ return argv if "--json" in argv else argv + ["--json"]
49
+ s = spec(name)
50
+ if s is None:
51
+ raise ValueError(f"unknown tool {name!r}")
52
+ schema = s["inputSchema"]
53
+ unknown = sorted(set(args) - set(schema["properties"]))
54
+ if unknown:
55
+ raise ValueError(f"{name}: unknown argument(s) {unknown}; see tools/list for the schema")
56
+ missing = [k for k in schema["required"] if args.get(k) in (None, "")]
57
+ if missing:
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]
60
+ flags = dict(s["flags"], dry_run="--dry-run", overwrite="--overwrite", timeout="--timeout")
61
+ for key, val in args.items():
62
+ if key in schema["x-positional"] or val is None or val is False:
63
+ continue
64
+ flag = flags[key]
65
+ if val is True:
66
+ argv.append(flag)
67
+ elif isinstance(val, list):
68
+ for v in val:
69
+ argv += [flag, str(v)]
70
+ else:
71
+ argv += [flag, str(val)]
72
+ return argv + ["--json"]
73
+
74
+
75
+ def call_tool(name: str, args: Dict[str, Any]) -> Dict[str, Any]:
76
+ try:
77
+ argv = build_argv(name, args or {})
78
+ except ValueError as e:
79
+ return {"content": [{"type": "text", "text": json.dumps({"status": "failed", "kind": "input", "error": str(e)})}],
80
+ "isError": True}
81
+ proc = subprocess.run([sys.executable, str(SCRIPTS / f"{name}.py"), *argv],
82
+ capture_output=True, text=True, encoding="utf-8", errors="replace")
83
+ try:
84
+ data = json.loads(proc.stdout)
85
+ except ValueError:
86
+ data = {"status": "failed", "kind": "failed", "error": (proc.stderr or proc.stdout).strip()[-1500:]}
87
+ failed = proc.returncode != 0 or data.get("status") == "failed"
88
+ return {"content": [{"type": "text", "text": json.dumps(data, ensure_ascii=False)}],
89
+ "structuredContent": data, "isError": failed}
90
+
91
+
92
+ def tools_list() -> Dict[str, Any]:
93
+ out = []
94
+ for t in contract()["tools"]:
95
+ schema = {k: v for k, v in t["inputSchema"].items() if not k.startswith("x-")}
96
+ desc = f"{t['summary']} Writes: {t['writes'] or 'nothing'}. Verifies: {t['verification']}."
97
+ out.append({"name": t["name"], "description": desc, "inputSchema": schema})
98
+ return {"tools": out}
99
+
100
+
101
+ def handle(msg: Dict[str, Any]) -> Optional[Dict[str, Any]]:
102
+ method, mid = msg.get("method"), msg.get("id")
103
+ if mid is None: # notification (e.g. notifications/initialized): no reply
104
+ return None
105
+ try:
106
+ if method == "initialize":
107
+ result: Any = {
108
+ "protocolVersion": PROTOCOL_VERSION,
109
+ "capabilities": {"tools": {}},
110
+ "serverInfo": {"name": "remotion-ffmpeg-skill", "version": contract()["version"]},
111
+ "instructions": "Workflow: analyze (measure) -> still (preview) -> render (verified) -> deliver "
112
+ "(template + check). pipeline does all of it. Read the 'look' contact sheet "
113
+ "path a render returns before reporting.",
114
+ }
115
+ elif method == "tools/list":
116
+ result = tools_list()
117
+ elif method == "tools/call":
118
+ p = msg.get("params") or {}
119
+ if spec(p.get("name", "")) is None:
120
+ return {"jsonrpc": "2.0", "id": mid, "error": {"code": -32602, "message": f"unknown tool {p.get('name')!r}"}}
121
+ result = call_tool(p["name"], p.get("arguments") or {})
122
+ elif method == "ping":
123
+ result = {}
124
+ else:
125
+ return {"jsonrpc": "2.0", "id": mid, "error": {"code": -32601, "message": f"method not found: {method}"}}
126
+ except Exception as e: # keep the server alive; report the failure to the client
127
+ return {"jsonrpc": "2.0", "id": mid, "error": {"code": -32603, "message": str(e)}}
128
+ return {"jsonrpc": "2.0", "id": mid, "result": result}
129
+
130
+
131
+ def main() -> None:
132
+ for line in sys.stdin:
133
+ line = line.strip()
134
+ if not line:
135
+ continue
136
+ try:
137
+ msg = json.loads(line)
138
+ except ValueError:
139
+ sys.stdout.write(json.dumps({"jsonrpc": "2.0", "id": None,
140
+ "error": {"code": -32700, "message": "parse error"}}) + "\n")
141
+ sys.stdout.flush()
142
+ continue
143
+ reply = handle(msg)
144
+ if reply is not None:
145
+ sys.stdout.write(json.dumps(reply, ensure_ascii=False) + "\n")
146
+ sys.stdout.flush()
147
+
148
+
149
+ if __name__ == "__main__":
150
+ main()
package/package.json CHANGED
@@ -1,6 +1,14 @@
1
1
  {
2
2
  "name": "remotion-ffmpeg-skill",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.0",
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"],
6
+ "license": "MIT",
7
+ "author": "kajisho5",
8
+ "repository": {"type": "git", "url": "git+https://github.com/kajisho5/remotion-ffmpeg-skill.git"},
9
+ "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"}
14
+ }
@@ -0,0 +1,93 @@
1
+ # timeline.json and composition options
2
+
3
+ `analyze.py` writes one `timeline.json` per source. The Remotion compositions receive it as
4
+ props (`{ "timeline": ..., "options": ..., "frame": ..., "font": ..., "overlay": ... }`, written by `render.py` / `still.py` to
5
+ `<project>/.rfs/props-<comp>-<hash>.json`, one file per distinct set of props so parallel renders never collide). The TypeScript type is `Timeline` in
6
+ `templates/remotion-project/src/timeline.ts`.
7
+
8
+ ## Timeline (schema `remotion-ffmpeg-skill/timeline@1`)
9
+
10
+ | Key | Type | From | Meaning |
11
+ |---|---|---|---|
12
+ | `schema` | string | — | always `remotion-ffmpeg-skill/timeline@1` |
13
+ | `generator` | object | — | this skill's version and the ffmpeg-skill version that measured |
14
+ | `source.path` | string | analyze.py | absolute path of the measured file |
15
+ | `source.src` | string \| null | render.py | `staticFile()` path inside `public/` (added at render time) |
16
+ | `source.duration` | seconds | probe.py | container duration |
17
+ | `source.fps` | number | probe.py | composition fps = source fps |
18
+ | `source.width` / `height` | px | probe.py | composition size = source size |
19
+ | `source.has_video` / `has_audio` | bool | probe.py | |
20
+ | `scenes` | `[{start, end}]` | scenes.py | shot boundaries (one scene = whole file when skipped) |
21
+ | `silences` | `[[start, end]]` | silence.py `--list` | measured silent gaps |
22
+ | `speech` | `[[start, end]]` | silence.py `--list` | ranges kept between silences (with margin) |
23
+ | `peaks` | `[{time, rms}]` | scenes.py | audio energy peaks |
24
+ | `beats` | object \| null | scenes.py `--beats` | `{times, tempo_bpm, confidence, usable}`; compositions use the times only when `usable` |
25
+ | `highlights` | `[{start, end}]` | scenes.py `--highlights` | ranked by audio energy, stored in source order (analyze.py `--highlights N [--target S]`) |
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 |
28
+ | `warnings` | `[string]` | analyze.py | VFR, HDR, rotation, odd frame rate |
29
+
30
+ All times are seconds on the source timeline. Frames are `Math.round(seconds * fps)` (round
31
+ half up) in both TypeScript and Python, so render.py's expected frame count matches the
32
+ composition exactly.
33
+
34
+ ## Built-in compositions
35
+
36
+ | Id | Length | What it draws |
37
+ |---|---|---|
38
+ | `Captioned` | source duration | source + caption cards that spring in on each cue and fade out |
39
+ | `Jumpcut` | sum of `speech` ranges | speech ranges back to back, punch-in zoom on every other cut, captions re-timed (parts inside removed silences dropped) |
40
+ | `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
+ | `Titled` | source duration | source + the user's lower thirds (`lowerThirds`) + a title card at the start of each measured scene (`sceneTitles`, in order) |
42
+ | `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 |
43
+ | `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
+
45
+ ## Options (`--options look.json`)
46
+
47
+ Every key is optional.
48
+
49
+ | Key | Default | Meaning |
50
+ |---|---|---|
51
+ | `accent` | `#ffcc00` | accent colour (caption underline, glow, progress bar) |
52
+ | `textColor` | `#ffffff` | caption text colour |
53
+ | `fontFamily` | Noto Sans JP, Hiragino Sans, Yu Gothic, … | CSS font stack; the font must exist on the rendering machine |
54
+ | `captionSize` | `0.055` | caption font size as a fraction of the frame's short side |
55
+ | `captionMargin` | `null` | caption bottom margin as a fraction of frame height; `null` = 0.08 landscape, 0.2 portrait (clear of Reels / TikTok UI) |
56
+ | `punchIn` | `1.12` | Jumpcut zoom on every other cut (`1` turns it off) |
57
+ | `pulse` | `0.6` | PeakPulse strength, 0..1 |
58
+ | `progressBar` | `true` | PeakPulse progress bar |
59
+ | `driver` | `"auto"` | PeakPulse: `peaks`, `beats`, or `auto` (beats when a usable grid was measured) |
60
+ | `lowerThirds` | `[]` | Titled: `[{"text", "sub"?, "start", "end"}]`, seconds on the source timeline |
61
+ | `sceneTitles` | `[]` | Titled: one title per measured scene, in order |
62
+ | `title` | `null` | Highlights: title over the first highlight |
63
+ | `beatsPerCut` | `4` | BeatMontage: measured beats per shot |
64
+
65
+ Unknown keys and wrong types are refused by render.py / still.py before anything renders.
66
+
67
+ Example:
68
+
69
+ ```json
70
+ { "accent": "#38bdf8", "captionSize": 0.065, "punchIn": 1.08 }
71
+ ```
72
+
73
+ ## Render-time props (set by render.py, not measured)
74
+
75
+ | Prop | From | Meaning |
76
+ |---|---|---|
77
+ | `frame` | `--aspect`, `--width`, `--fit` | `{width, height, fit}` of the output; `null` = the source's own size. Without `--width` the short side of the source is kept (720p → 720×1280 portrait), sizes rounded to even numbers |
78
+ | `font` | `--font-file`, or automatic for CJK captions | `{src, family}`: a font staged into `public/fonts/` and loaded before the first frame |
79
+ | `overlay` | `--overlay` | `true` = graphics only on a transparent background; render.py composites them over the source with ffmpeg-skill `overlay.py` |
80
+
81
+ `fit`: `blur` (contained over a blurred, cropped copy — default when the shape changes), `contain` (bars), `cover` (crop).
82
+
83
+ ## Caption files
84
+
85
+ - **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
+ - **JSON**: `[{"start": 1.0, "end": 3.5, "text": "..."}]` or `{"cues": [...]}`.
87
+
88
+ ## Adding your own composition
89
+
90
+ 1. Write a component in `src/compositions/` that takes `Props` (`{ timeline, options }`).
91
+ 2. Register it in `src/Root.tsx` with a `calculateMetadata` that derives length from the timeline.
92
+ 3. `render.py --comp YourId ...` — the output is still probed and contact-sheeted; the frame
93
+ count check is replaced by an INFO row because the skill cannot know your length rule.