remotion-ffmpeg-skill 0.5.0 → 0.7.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
@@ -116,10 +116,12 @@ This skill is MIT. **Remotion itself has its own licence**: free for individuals
116
116
 
117
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.
118
118
 
119
+ **`--sparse`** (Captioned, Karaoke, Titled): only the frames that show a caption, lower third or scene title are drawn; ffmpeg-skill places each stretch back at its time over the untouched source. Same picture frame for frame (checked by an integration test), and the render time follows the captioned share of the footage: 60 s with 7 s of captions took 46 s instead of 152 s; 40 s with two scene titles and a lower third, 39 s instead of 104 s. Needs an ffmpeg-skill whose `overlay.py` has `--place`; otherwise it draws the full layer and says why.
120
+
119
121
  ## Agent evals
120
122
 
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)).
123
+ 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)). A third run with a neutral prompt (both skills installed, no hint) went to ffmpeg-skill alone for three requests it can finish by itself — 6 / 9 by the original checks, 9 / 9 once that route is accepted ([run 3](evals/results/2026-10-24c.md)).
122
124
 
123
125
  ## Status
124
126
 
125
- 0.4.0. CI renders every composition on Linux, macOS and Windows (Node 22, Remotion 4.0.538, ffmpeg-skill main).
127
+ 0.5. CI renders every composition on Linux, macOS and Windows (Node 22, Remotion 4.0.538, ffmpeg-skill main).
package/SKILL.md CHANGED
@@ -20,6 +20,7 @@ Shared flags (every script): `--json` (one JSON object on stdout; prefer it), `-
20
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
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
+ - **Long footage with gaps between captions:** `--sparse` (Captioned / Karaoke / Titled) draws only the frames where a caption, lower third or scene title shows and places each stretch back at its time with ffmpeg-skill `overlay.py --place` — same picture, frame for frame. It needs an ffmpeg-skill with `--place`; without it (or when the source does not start at 0) it draws the full layer and says why in `sparse.reason`.
23
24
  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
25
  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
26
 
@@ -29,6 +30,16 @@ MCP: `mcp/server.py` exposes the same tools (schemas from `scripts/_contract.py`
29
30
 
30
31
  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
 
33
+ ## This skill or ffmpeg-skill alone?
34
+
35
+ ffmpeg-skill by itself already does silence cuts, burned-in (also pop / karaoke) captions, title and lower-third templates, joins and platform templates, without a browser render. For a request that fits those, ffmpeg-skill alone is a valid and faster answer. Choose this skill when the request needs something ffmpeg-skill does not draw:
36
+
37
+ - motion tied to measurements: punch-in zooms on jump cuts, pulses on peaks or beats, picture cuts on a beat grid, a highlight counter;
38
+ - the graphics as a separate transparent layer for an editor (`--overlay --keep-graphics`);
39
+ - a custom React composition, or the user asks for Remotion.
40
+
41
+ Changing the shape alone is not a reason: ffmpeg-skill's Reels / TikTok / Shorts templates centre-crop by default, but ffmpeg-skill can also keep the whole frame on a blurred fill. Whichever you choose, say which one and the trade-off that matters (for example "centre-cropped: the left and right edges are gone").
42
+
32
43
  ## Request → script / composition
33
44
 
34
45
  | Request | Run |
@@ -44,6 +55,7 @@ Everything in one go: `pipeline.py SOURCE --project ./motion --comp NAME [--capt
44
55
  | "vertical / 9:16 / square" | `render.py --aspect 9:16` (or `1:1`, `4:5`) |
45
56
  | "Japanese captions" / a specific font | nothing extra for CJK (auto font); `--font-file` for a chosen font |
46
57
  | "give me the graphics as a separate layer" | `render.py --overlay --keep-graphics` |
58
+ | captions or name titles on long footage (a talk, a lecture) | `render.py --comp Captioned --sparse` (or `Karaoke`, `Titled`): only the stretches where something shows are drawn |
47
59
  | "change colour / font / caption size / zoom" | an `--options` JSON (`references/timeline.md`), re-render |
48
60
  | 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 |
49
61
  | "preview" / "show me a frame" | `still.py` |
@@ -62,6 +74,6 @@ Everything in one go: `pipeline.py SOURCE --project ./motion --comp NAME [--capt
62
74
  - 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.
63
75
  - Keep the user's originals: sources are linked into `public/media/` of the project, never modified; outputs never overwrite an existing file without `--overwrite`.
64
76
  - 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.
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.
77
+ - 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. `--sparse` cuts that to the share that shows graphics: 60 s with 7 s of captions went from 152 s to 46 s; 40 s with two scene titles and one lower third from 104 s to 39 s. `--concurrency` above the core count is refused by Remotion.
66
78
  - Remotion packages in a project must all be the same version; the template pins them. Don't mix in a different `remotion` version.
67
79
  - A render that fails verification is a failure: report the failed rows from `--json`, don't ship it.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "remotion-ffmpeg-skill",
3
- "version": "0.5.0",
3
+ "version": "0.7.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
5
  "keywords": [
6
6
  "remotion",
@@ -38,7 +38,8 @@
38
38
  "references",
39
39
  "mcp",
40
40
  "LICENSE",
41
- "README.md"
41
+ "README.md",
42
+ "!**/__pycache__"
42
43
  ],
43
44
  "engines": {
44
45
  "node": ">=18"
@@ -94,7 +94,7 @@ Render a composition from a timeline, verify it (frames, fps, size, audio) and w
94
94
  - Role: execution — writes a new media artifact; inputs are never modified
95
95
  - Writes: video file (+ contact sheet PNG)
96
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)
97
+ - ffmpeg-skill: probe, look, overlay (--overlay; --place with --sparse), _contract doctor (CJK font lookup)
98
98
  - `--dry-run`: plans without writing
99
99
 
100
100
  | Argument | Type | Default | Meaning |
@@ -112,15 +112,17 @@ Render a composition from a timeline, verify it (frames, fps, size, audio) and w
112
112
  | `--no-look` | boolean | | skip the contact sheet |
113
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
114
  | `--keep-graphics` | boolean | | with --overlay: keep the transparent graphics .mov |
115
+ | `--sparse` | boolean | | overlay mode that draws only the frames where something shows (Captioned / Karaoke / Titled) and places each stretch at its time with ffmpeg-skill overlay.py --place: much faster on long footage with gaps between captions. Falls back to the full-length layer (and says why) when this ffmpeg-skill has no --place or the source does not start at 0 |
116
+ | `--merge-gap` | number | `2.0` | with --sparse: graphics closer than this many seconds are drawn as one stretch (default 2) |
115
117
  | `--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
118
  | `--width` | integer | | output width in px (default: keep the source's short side) |
117
119
  | `--fit` | string: blur / contain / cover | | how the source fills another shape: blur (default when the shape changes), contain (bars) or cover (crop) |
118
120
  | `--font-file` | string | | caption font file (.ttf/.otf/.ttc/.woff2), staged into the project |
119
121
  | `--no-auto-font` | boolean | | don't stage the CJK font ffmpeg-skill finds for Japanese/Chinese/Korean captions |
120
122
 
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))
123
+ --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)), `sparse` (null|{used, reason, stretches, drawn_frames, source_frames} (--sparse)), `kind` (null|failed), `error` (null|str (which verification rows failed))
122
124
 
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)
125
+ --dry-run --json result (besides `status`, `dry_run`, `output`): `commands` (list[str]), `props` (str), `expected_frames` (int|null), `frame` (object|null), `font` (str|null), `sparse` (null|object (--sparse))
124
126
 
125
127
  ## deliver.py
126
128
 
@@ -62,7 +62,7 @@ TOOL_META: Dict[str, Dict[str, Any]] = {
62
62
  "summary": "Render a composition from a timeline, verify it (frames, fps, size, audio) and write a contact sheet.",
63
63
  "writes": "video file (+ contact sheet PNG)",
64
64
  "verification": "exact frame count / fps / size / audio against the timeline; non-zero exit on mismatch",
65
- "ffmpeg_skill": ["probe", "look", "overlay (--overlay)", "_contract doctor (CJK font lookup)"],
65
+ "ffmpeg_skill": ["probe", "look", "overlay (--overlay; --place with --sparse)", "_contract doctor (CJK font lookup)"],
66
66
  "dry_run": True,
67
67
  },
68
68
  "deliver": {
@@ -114,10 +114,12 @@ OUTPUTS: Dict[str, Dict[str, Dict[str, str]]] = {
114
114
  "result": {"verified": "bool", "verification": "list[{check, status, value, expected}]",
115
115
  "commands": "list[str]", "look": "str|null (contact sheet PNG)", "look_error": "str|null",
116
116
  "summary": "str", "frame": "object|null", "font": "str|null", "mode": "full|overlay",
117
- "graphics": "str|null (kept ProRes 4444 layer)", "kind": "null|failed",
117
+ "graphics": "str|null (kept ProRes 4444 layer)",
118
+ "sparse": "null|{used, reason, stretches, drawn_frames, source_frames} (--sparse)",
119
+ "kind": "null|failed",
118
120
  "error": "null|str (which verification rows failed)"},
119
121
  "dry_run": {"commands": "list[str]", "props": "str", "expected_frames": "int|null", "frame": "object|null",
120
- "font": "str|null"},
122
+ "font": "str|null", "sparse": "null|object (--sparse)"},
121
123
  },
122
124
  "deliver": {
123
125
  "result": {"checked": "str", "platform": "str|null", "verified": "bool",
@@ -0,0 +1,142 @@
1
+ """Sparse overlay rendering: draw only the frames where something shows, then lay each drawn stretch
2
+ back at its own time with ffmpeg-skill `overlay.py --place`.
3
+
4
+ Remotion renders every frame in a browser, so a 30-minute talk with captions on a third of it spends
5
+ two thirds of the render on empty transparent frames. Here the shown intervals (caption cues, or
6
+ Titled's lower thirds and scene cards) are grouped into stretches (intervals closer than `merge_gap`
7
+ seconds share one), the stretches are packed back to back in a short timeline, Remotion draws that,
8
+ and overlay.py places each stretch over the untouched source. Everything moves by whole frames, so
9
+ the result matches the full-length overlay frame for frame.
10
+ """
11
+ import copy
12
+ from typing import Any, Dict, List, Optional, Tuple
13
+
14
+ from _common import sec_to_frames
15
+
16
+ SPARSE_COMPOSITIONS = ("Captioned", "Karaoke", "Titled")
17
+ # One overlay filter per stretch: past this many, the filter chain costs more than it saves.
18
+ MAX_STRETCHES = 400
19
+ # Titled.tsx: a scene card lasts until the scene ends, at most this long.
20
+ SCENE_CARD_SECONDS = 2.5
21
+
22
+ Layout = List[Tuple[int, int, int]] # (packed_first_frame, length_frames, source_first_frame)
23
+
24
+
25
+ def _scene_card(sc: Dict[str, Any], fps: float) -> Tuple[int, int]:
26
+ """[from, end) frames of a scene card, as Titled.tsx computes them."""
27
+ s = sec_to_frames(sc["start"], fps)
28
+ return s, s + max(1, min(sec_to_frames(sc["end"], fps), s + sec_to_frames(SCENE_CARD_SECONDS, fps)) - s)
29
+
30
+
31
+ def drawn_intervals(comp: str, timeline: Dict[str, Any], options: Optional[Dict[str, Any]] = None) -> List[Tuple[int, int]]:
32
+ """[from, end) frames in which the composition draws anything (its Sequences)."""
33
+ fps = float(timeline["source"]["fps"])
34
+ o = options or {}
35
+ out: List[Tuple[int, int]] = []
36
+ if comp in ("Captioned", "Karaoke"):
37
+ for c in timeline.get("captions") or []:
38
+ s = sec_to_frames(c["start"], fps)
39
+ out.append((s, s + max(1, sec_to_frames(c["end"], fps) - s)))
40
+ elif comp == "Titled":
41
+ titles = o.get("sceneTitles") or []
42
+ for i, sc in enumerate(timeline.get("scenes") or []):
43
+ if i < len(titles) and titles[i]:
44
+ out.append(_scene_card(sc, fps))
45
+ for lt in o.get("lowerThirds") or []:
46
+ s = sec_to_frames(lt["start"], fps)
47
+ out.append((s, s + max(1, sec_to_frames(lt["end"], fps) - s)))
48
+ return out
49
+
50
+
51
+ def stretches(intervals: List[Tuple[int, int]], total: int, merge_gap_frames: int) -> List[Tuple[int, int]]:
52
+ """Sorted, merged [from, end) stretches inside [0, total); intervals closer than the gap merge."""
53
+ out: List[List[int]] = []
54
+ for s, e in sorted(intervals):
55
+ s = max(0, min(s, total - 1))
56
+ e = min(total, max(e, s + 1))
57
+ if out and s <= out[-1][1] + merge_gap_frames:
58
+ out[-1][1] = max(out[-1][1], e)
59
+ else:
60
+ out.append([s, e])
61
+ return [(s, e) for s, e in out]
62
+
63
+
64
+ def plan_stretches(comp: str, timeline: Dict[str, Any], options: Optional[Dict[str, Any]], merge_gap: float) -> List[Tuple[int, int]]:
65
+ fps = float(timeline["source"]["fps"])
66
+ total = sec_to_frames(float(timeline["source"]["duration"]), fps)
67
+ return stretches(drawn_intervals(comp, timeline, options), total, sec_to_frames(merge_gap, fps))
68
+
69
+
70
+ def caption_stretches(timeline: Dict[str, Any], merge_gap: float) -> List[Tuple[int, int]]:
71
+ return plan_stretches("Captioned", timeline, None, merge_gap)
72
+
73
+
74
+ def pack(timeline: Dict[str, Any], spans: List[Tuple[int, int]],
75
+ options: Optional[Dict[str, Any]] = None) -> Tuple[Dict[str, Any], Dict[str, Any], Layout]:
76
+ """The timeline and options with the stretches back to back (one blank frame between them), and
77
+ the layout that puts each stretch back."""
78
+ fps = float(timeline["source"]["fps"])
79
+ layout: Layout = []
80
+ p = 0
81
+ for s, e in spans:
82
+ layout.append((p, e - s, s))
83
+ p += (e - s) + 1
84
+
85
+ def offset(t: float) -> Optional[int]:
86
+ """Whole frames to move a time by: its stretch's source start minus its packed start. Only
87
+ whole frames, so a word timed between two frames keeps exactly where it falls in its frame."""
88
+ f = sec_to_frames(t, fps)
89
+ for pp, n, s in layout:
90
+ if s <= f <= s + n:
91
+ return s - pp
92
+ return None
93
+
94
+ def moved(items: List[Dict[str, Any]], anchor) -> List[Dict[str, Any]]:
95
+ out = []
96
+ for c in items:
97
+ k = offset(anchor(c))
98
+ if k is not None:
99
+ out.append({**c, "start": c["start"] - k / fps, "end": c["end"] - k / fps})
100
+ return out
101
+
102
+ tl = copy.deepcopy(timeline)
103
+ tl["source"]["duration"] = packed_frames(layout) / fps
104
+ tl["captions"] = moved(timeline.get("captions") or [], lambda c: c["start"])
105
+ # a word belongs where Karaoke puts it: by its midpoint
106
+ tl["words"] = moved(timeline.get("words") or [], lambda w: (w["start"] + w["end"]) / 2)
107
+ opts = copy.deepcopy(options or {})
108
+ if opts.get("lowerThirds"):
109
+ opts["lowerThirds"] = moved(opts["lowerThirds"], lambda lt: lt["start"])
110
+ # Scene cards are matched to sceneTitles by index, so every scene keeps its place in the list:
111
+ # a titled one moves with its stretch and keeps its card length; the rest draw nothing anyway.
112
+ titles = opts.get("sceneTitles") or []
113
+ scenes = []
114
+ for i, sc in enumerate(timeline.get("scenes") or []):
115
+ if i < len(titles) and titles[i]:
116
+ s, e = _scene_card(sc, fps)
117
+ k = offset(sc["start"])
118
+ if k is not None:
119
+ scenes.append({"start": (s - k) / fps, "end": (e - k) / fps})
120
+ continue
121
+ scenes.append({"start": 0.0, "end": 1.0 / fps})
122
+ tl["scenes"] = scenes if any(titles) else []
123
+ # nothing else is drawn; measurements on the source clock would only mislead
124
+ for key in ("silences", "speech", "peaks", "highlights", "clips"):
125
+ tl[key] = []
126
+ tl["beats"] = None
127
+ return tl, opts, layout
128
+
129
+
130
+ def place_args(layout: Layout, fps: float) -> List[str]:
131
+ """overlay.py --place arguments. Range edges sit half a frame inside the stretch, so the blank
132
+ frame between stretches is never picked up whatever the float rounding of a timestamp."""
133
+ args: List[str] = []
134
+ for pp, n, s in layout:
135
+ a = max(0.0, (pp - 0.5) / fps)
136
+ b = (pp + n - 0.5) / fps
137
+ args += ["--place", f"{a:.6f}-{b:.6f}@{s / fps:.6f}"]
138
+ return args
139
+
140
+
141
+ def packed_frames(layout: Layout) -> int:
142
+ return max(1, sum(n for _, n, _ in layout) + len(layout) - 1)
package/scripts/render.py CHANGED
@@ -15,6 +15,7 @@ from pathlib import Path
15
15
  from typing import Any, Dict, List, Optional, Tuple
16
16
 
17
17
  sys.path.insert(0, str(Path(__file__).resolve().parent))
18
+ import _sparse
18
19
  from _common import (BUILTIN_COMPOSITIONS, STATE, add_common, add_frame_args, apply_common, die, emit, expected_frames,
19
20
  ffskill, ffskill_cmd, frame_size, info, load_options, load_timeline, prepare_props, refuse_existing,
20
21
  remotion_bin, require_ffmpeg_skill, require_project, remotion_error, run, shell_join)
@@ -43,6 +44,14 @@ def build_parser() -> argparse.ArgumentParser:
43
44
  "untouched source with ffmpeg-skill overlay.py (Captioned / PeakPulse, source frame only); "
44
45
  "with --keep-graphics the layer is kept for an editing app (Premiere, Resolve, Final Cut)")
45
46
  p.add_argument("--keep-graphics", action="store_true", help="with --overlay: keep the transparent graphics .mov")
47
+ p.add_argument("--sparse", action="store_true",
48
+ help="overlay mode that draws only the frames where something shows (Captioned / Karaoke / "
49
+ "Titled) and "
50
+ "places each stretch at its time with ffmpeg-skill overlay.py --place: much faster on long "
51
+ "footage with gaps between captions. Falls back to the full-length layer (and says why) "
52
+ "when this ffmpeg-skill has no --place or the source does not start at 0")
53
+ p.add_argument("--merge-gap", type=float, default=2.0,
54
+ help="with --sparse: graphics closer than this many seconds are drawn as one stretch (default 2)")
46
55
  add_frame_args(p)
47
56
  add_common(p)
48
57
  return p
@@ -126,6 +135,52 @@ def verify(out_probe: Dict[str, Any], timeline: Dict[str, Any], comp: str,
126
135
  return all(r["status"] != "FAIL" for r in rows), rows
127
136
 
128
137
 
138
+ def ffskill_can_place() -> bool:
139
+ """Whether this ffmpeg-skill's overlay.py has --place (ffmpeg-skill PR #353)."""
140
+ import subprocess
141
+ try:
142
+ proc = subprocess.run(ffskill_cmd("overlay", ["--help"]), capture_output=True, text=True, timeout=60)
143
+ except (OSError, subprocess.TimeoutExpired):
144
+ return False
145
+ return "--place" in (proc.stdout or "")
146
+
147
+
148
+ def sparse_plan(timeline: Dict[str, Any], options: Dict[str, Any], a: argparse.Namespace) -> Dict[str, Any]:
149
+ """What --sparse will draw, or why it falls back to the full-length layer."""
150
+ src = timeline["source"]
151
+ fps = float(src["fps"])
152
+ total = expected_frames(a.comp, timeline) or 1
153
+ plan: Dict[str, Any] = {"used": False, "reason": None, "stretches": 0, "drawn_frames": total,
154
+ "source_frames": total, "timeline": None, "options": None, "place": []}
155
+ stretches = _sparse.plan_stretches(a.comp, timeline, options, a.merge_gap)
156
+ start = None
157
+ if stretches and src.get("path") and not STATE.dry_run:
158
+ # the source as it is now (older timelines do not record where its first picture sits)
159
+ start = (ffskill("probe", [str(src["path"])], allow_fail=True).get("video") or {}).get("start_time")
160
+ if not stretches:
161
+ plan["reason"] = "nothing to draw (no captions, lower thirds or scene titles)"
162
+ elif len(stretches) > _sparse.MAX_STRETCHES:
163
+ plan["reason"] = (f"{len(stretches)} stretches (over {_sparse.MAX_STRETCHES}); raise --merge-gap")
164
+ elif isinstance(start, (int, float)) and abs(start) > 0.5 / fps:
165
+ plan["reason"] = (f"the source's first picture is at {start:.3f} s, not 0: placed stretches would be "
166
+ "shifted by that much")
167
+ elif not ffskill_can_place():
168
+ plan["reason"] = "this ffmpeg-skill's overlay.py has no --place yet (update ffmpeg-skill)"
169
+ else:
170
+ packed, packed_options, layout = _sparse.pack(timeline, stretches, options)
171
+ drawn = _sparse.packed_frames(layout)
172
+ if drawn >= total:
173
+ plan["reason"] = "the graphics cover the whole source: nothing to skip"
174
+ else:
175
+ plan.update(used=True, stretches=len(layout), drawn_frames=drawn, timeline=packed, options=packed_options,
176
+ place=_sparse.place_args(layout, fps))
177
+ if plan["reason"]:
178
+ info(f"--sparse: drawing the full length instead ({plan['reason']})")
179
+ else:
180
+ info(f"--sparse: drawing {plan['drawn_frames']} of {total} frames in {plan['stretches']} stretch(es)")
181
+ return plan
182
+
183
+
129
184
  def main() -> None:
130
185
  a = build_parser().parse_args()
131
186
  apply_common(a)
@@ -147,6 +202,13 @@ def main() -> None:
147
202
  output = output.resolve()
148
203
  refuse_existing(output)
149
204
 
205
+ if a.sparse:
206
+ if a.comp not in _sparse.SPARSE_COMPOSITIONS:
207
+ die(f"--sparse draws only the stretches where graphics show: {a.comp} is not one of "
208
+ f"{', '.join(_sparse.SPARSE_COMPOSITIONS)} (use --overlay for the full-length layer)", "input")
209
+ if a.merge_gap < 0:
210
+ die("--merge-gap cannot be negative", "input")
211
+ a.overlay = True
150
212
  if a.overlay:
151
213
  if a.comp in ("Jumpcut", "Highlights", "BeatMontage"):
152
214
  die(f"--overlay cannot do {a.comp}: its cuts move the picture itself (overlay works for "
@@ -158,18 +220,25 @@ def main() -> None:
158
220
  if not timeline["source"].get("has_video"):
159
221
  die("--overlay needs a video source to composite onto", "input")
160
222
 
161
- props_path, frame, font_note = prepare_props(project, a.comp, timeline, options, a)
223
+ sparse = sparse_plan(timeline, options, a) if a.sparse else None
224
+ used = bool(sparse and sparse["used"])
225
+ props_path, frame, font_note = prepare_props(project, a.comp, sparse["timeline"] if used else timeline,
226
+ sparse["options"] if used else options, a)
162
227
  if font_note:
163
228
  info(font_note)
164
229
  graphics = output.with_name(output.stem + ".graphics.mov") if a.overlay else output
165
230
  cmd = remotion_render_cmd(project, a.comp, graphics, props_path, a)
166
231
  ov_args = [timeline["source"]["path"], "--video", str(graphics), "--position", "0,0", "--margin", "0",
167
232
  "-o", str(output)] + (["--overwrite"] if STATE.overwrite else [])
233
+ if sparse and sparse["used"]:
234
+ ov_args += sparse["place"]
235
+ sparse_note = None if not sparse else {k: sparse[k] for k in ("used", "reason", "stretches", "drawn_frames",
236
+ "source_frames")}
168
237
  if STATE.dry_run:
169
238
  plan = [shell_join(cmd)] + ([shell_join(ffskill_cmd("overlay", ov_args))] if a.overlay else [])
170
239
  emit({"output": str(output), "commands": plan, "props": str(props_path),
171
240
  "expected_frames": (frames[1] - frames[0] + 1) if frames else expected_frames(a.comp, timeline),
172
- "frame": frame, "font": font_note},
241
+ "frame": frame, "font": font_note, "sparse": sparse_note},
173
242
  f"would render {a.comp} -> {output}")
174
243
  return
175
244
 
@@ -182,6 +251,13 @@ def main() -> None:
182
251
  tail = remotion_error((proc.stderr or "") + "\n" + (proc.stdout or ""))
183
252
  die(f"Remotion render failed (exit {proc.returncode}):\n{tail}", "failed", command=shell_join(cmd))
184
253
  commands = [shell_join(cmd)]
254
+ if sparse and sparse["used"]:
255
+ # the packed layer must hold exactly the frames the placements read
256
+ gp = ffskill("probe", [str(graphics)])
257
+ nb = (gp.get("video") or {}).get("nb_frames")
258
+ if isinstance(nb, int) and nb != sparse["drawn_frames"]:
259
+ die(f"--sparse: the drawn layer has {nb} frames, the placements expect {sparse['drawn_frames']}",
260
+ "failed", command=shell_join(cmd))
185
261
  if a.overlay:
186
262
  info(f"compositing the graphics over the source with ffmpeg-skill overlay.py -> {output}")
187
263
  ov = ffskill("overlay", ov_args)
@@ -213,7 +289,7 @@ def main() -> None:
213
289
  result = {"status": "completed" if ok else "failed", "output": str(output), "verified": ok,
214
290
  "verification": rows, "commands": commands, "look": look, "summary": summary,
215
291
  "frame": frame, "font": font_note, "mode": "overlay" if a.overlay else "full", "look_error": look_error,
216
- "graphics": str(graphics) if a.overlay and a.keep_graphics else None,
292
+ "graphics": str(graphics) if a.overlay and a.keep_graphics else None, "sparse": sparse_note,
217
293
  "kind": None if ok else "failed",
218
294
  "error": None if ok else "verification failed: " + ", ".join(r["check"] for r in rows if r["status"] == "FAIL")}
219
295
  table = "\n".join(f" {r['check']:<9} {r['status']:<4} {r['value']} (expected {r['expected']})" for r in rows)
@@ -48,7 +48,9 @@ const KaraokeCue: React.FC<{ cue: Caption; words: Caption[]; len: number; o: Opt
48
48
  const fade = Math.min(6, Math.floor(len / 3));
49
49
  const exit = fade > 0 ? interpolate(frame, [len - fade, len], [1, 0], { extrapolateLeft: "clamp", extrapolateRight: "clamp" }) : 1;
50
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
51
+ // Source time at this frame. The microsecond nudge settles a word boundary that falls exactly on a
52
+ // frame (5.2 + 21/30 vs 5.9) the same way whatever float rounding produced the two numbers.
53
+ const now = cue.start + frame / fps + 1e-6;
52
54
  const lang = /[぀-ヿ]/.test(cue.text) ? "ja" : /[가-힯]/.test(cue.text) ? "ko" : undefined;
53
55
  return (
54
56
  <AbsoluteFill style={{ justifyContent: "flex-end", alignItems: "center", paddingBottom: captionMarginPx(o, width, height) }}>