remotion-ffmpeg-skill 0.0.0-stage → 0.3.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/LICENSE +21 -0
- package/README.md +116 -2
- package/SKILL.md +66 -0
- package/bin/remotion-ffmpeg-skill.js +100 -0
- package/mcp/server.py +150 -0
- package/package.json +12 -4
- package/references/timeline.md +93 -0
- package/scripts/_captions.py +79 -0
- package/scripts/_common.py +538 -0
- package/scripts/_contract.py +202 -0
- package/scripts/analyze.py +240 -0
- package/scripts/deliver.py +79 -0
- package/scripts/doctor.py +83 -0
- package/scripts/init.py +62 -0
- package/scripts/pipeline.py +122 -0
- package/scripts/render.py +215 -0
- package/scripts/still.py +84 -0
- package/templates/remotion-project/package.json +20 -0
- package/templates/remotion-project/public/.gitkeep +0 -0
- package/templates/remotion-project/remotion.config.ts +6 -0
- package/templates/remotion-project/src/Root.tsx +32 -0
- package/templates/remotion-project/src/compositions/BeatMontage.tsx +60 -0
- package/templates/remotion-project/src/compositions/Captioned.tsx +95 -0
- package/templates/remotion-project/src/compositions/Highlights.tsx +98 -0
- package/templates/remotion-project/src/compositions/Jumpcut.tsx +52 -0
- package/templates/remotion-project/src/compositions/PeakPulse.tsx +73 -0
- package/templates/remotion-project/src/compositions/Titled.tsx +138 -0
- package/templates/remotion-project/src/index.ts +4 -0
- package/templates/remotion-project/src/lib/SourceVideo.tsx +84 -0
- package/templates/remotion-project/src/lib/useStagedFont.ts +25 -0
- package/templates/remotion-project/src/timeline.ts +214 -0
- package/templates/remotion-project/tsconfig.json +15 -0
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Caption file readers (internal module): SRT, WebVTT and a plain JSON cue list.
|
|
3
|
+
|
|
4
|
+
Cue text is kept exactly as written (line breaks included): this skill never rewrites,
|
|
5
|
+
shortens or paraphrases caption words -- the same rule as ffmpeg-skill.
|
|
6
|
+
"""
|
|
7
|
+
import json
|
|
8
|
+
import re
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
from typing import Dict, List
|
|
11
|
+
|
|
12
|
+
_TS = re.compile(r"(?:(\d+):)?(\d{1,2}):(\d{2})[.,](\d{1,3})")
|
|
13
|
+
_ARROW = re.compile(r"^\s*(\S+)\s+-->\s+(\S+)")
|
|
14
|
+
_TAG = re.compile(r"</?(?:[bius]|c(?:\.[\w.-]+)?|v(?:\s[^>]*)?|lang(?:\s[^>]*)?|ruby|rt)>")
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class CaptionError(ValueError):
|
|
18
|
+
pass
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def parse_timestamp(s: str) -> float:
|
|
22
|
+
m = _TS.fullmatch(s.strip())
|
|
23
|
+
if not m:
|
|
24
|
+
raise CaptionError(f"bad timestamp: {s!r}")
|
|
25
|
+
h, mi, se, ms = m.groups()
|
|
26
|
+
frac = int(ms) / (10 ** len(ms))
|
|
27
|
+
return int(h or 0) * 3600 + int(mi) * 60 + int(se) + frac
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def _blocks(text: str) -> List[List[str]]:
|
|
31
|
+
text = text.replace("", "").replace("\r\n", "\n").replace("\r", "\n")
|
|
32
|
+
return [b.split("\n") for b in re.split(r"\n\s*\n", text.strip()) if b.strip()]
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def parse_srt_or_vtt(text: str) -> List[Dict]:
|
|
36
|
+
cues: List[Dict] = []
|
|
37
|
+
for lines in _blocks(text):
|
|
38
|
+
if lines[0].strip().upper().startswith(("WEBVTT", "NOTE", "STYLE", "REGION")):
|
|
39
|
+
continue
|
|
40
|
+
idx = next((i for i, ln in enumerate(lines) if "-->" in ln), None)
|
|
41
|
+
if idx is None:
|
|
42
|
+
continue
|
|
43
|
+
m = _ARROW.match(lines[idx])
|
|
44
|
+
if not m:
|
|
45
|
+
raise CaptionError(f"bad cue timing line: {lines[idx]!r}")
|
|
46
|
+
start, end = parse_timestamp(m.group(1)), parse_timestamp(m.group(2))
|
|
47
|
+
body = "\n".join(_TAG.sub("", ln) for ln in lines[idx + 1:]).strip()
|
|
48
|
+
if end <= start:
|
|
49
|
+
raise CaptionError(f"cue ends before it starts: {lines[idx]!r}")
|
|
50
|
+
if body:
|
|
51
|
+
cues.append({"start": round(start, 3), "end": round(end, 3), "text": body})
|
|
52
|
+
return cues
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def parse_json_cues(text: str) -> List[Dict]:
|
|
56
|
+
data = json.loads(text)
|
|
57
|
+
if isinstance(data, dict):
|
|
58
|
+
data = data.get("cues") or data.get("captions")
|
|
59
|
+
if not isinstance(data, list):
|
|
60
|
+
raise CaptionError("JSON captions must be a list of {start, end, text} (or {\"cues\": [...]})")
|
|
61
|
+
cues = []
|
|
62
|
+
for i, c in enumerate(data):
|
|
63
|
+
try:
|
|
64
|
+
start, end, body = float(c["start"]), float(c["end"]), str(c["text"])
|
|
65
|
+
except (KeyError, TypeError, ValueError):
|
|
66
|
+
raise CaptionError(f"cue {i} needs numeric start/end and text")
|
|
67
|
+
if end <= start:
|
|
68
|
+
raise CaptionError(f"cue {i} ends before it starts")
|
|
69
|
+
cues.append({"start": round(start, 3), "end": round(end, 3), "text": body})
|
|
70
|
+
return cues
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def read_captions(path: Path) -> List[Dict]:
|
|
74
|
+
text = path.read_text(encoding="utf-8-sig")
|
|
75
|
+
if path.suffix.lower() == ".json":
|
|
76
|
+
cues = parse_json_cues(text)
|
|
77
|
+
else:
|
|
78
|
+
cues = parse_srt_or_vtt(text)
|
|
79
|
+
return sorted(cues, key=lambda c: c["start"])
|
|
@@ -0,0 +1,538 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Shared helpers for remotion-ffmpeg-skill (internal module, not a tool).
|
|
3
|
+
|
|
4
|
+
Three jobs live here so every public script behaves the same way:
|
|
5
|
+
|
|
6
|
+
* CLI conventions copied from ffmpeg-skill: --json, --dry-run, --overwrite, --timeout,
|
|
7
|
+
one JSON object on stdout, human lines on stderr, a typed error ("kind") on failure.
|
|
8
|
+
* Finding and calling ffmpeg-skill. This skill never runs a raw ffmpeg/ffprobe command of
|
|
9
|
+
its own: measuring (probe, scenes, silence), checking (check.py) and delivering
|
|
10
|
+
(render.py --template) all go through ffmpeg-skill's scripts and their --json output.
|
|
11
|
+
* Preparing a Remotion render: copying/linking the source into the project's public/
|
|
12
|
+
folder, writing the props file, finding the project-local `remotion` binary.
|
|
13
|
+
|
|
14
|
+
Python 3.10+ standard library only.
|
|
15
|
+
"""
|
|
16
|
+
import argparse
|
|
17
|
+
import hashlib
|
|
18
|
+
import json
|
|
19
|
+
import math
|
|
20
|
+
import os
|
|
21
|
+
import shutil
|
|
22
|
+
import subprocess
|
|
23
|
+
import sys
|
|
24
|
+
import time
|
|
25
|
+
from pathlib import Path
|
|
26
|
+
from typing import Any, Dict, List, Optional, Sequence, Tuple
|
|
27
|
+
|
|
28
|
+
HERE = Path(__file__).resolve().parent
|
|
29
|
+
ROOT = HERE.parent
|
|
30
|
+
SKILL_ID = "remotion-ffmpeg-skill"
|
|
31
|
+
TIMELINE_SCHEMA = "remotion-ffmpeg-skill/timeline@1"
|
|
32
|
+
|
|
33
|
+
# Exit codes follow ffmpeg-skill: 2 = bad input / refused, 3 = missing tool, 1 = the step ran and failed.
|
|
34
|
+
EXIT_FOR_KIND = {"input": 2, "missing_tool": 3, "timeout": 4, "failed": 1}
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
class State:
|
|
38
|
+
json = False
|
|
39
|
+
dry_run = False
|
|
40
|
+
overwrite = False
|
|
41
|
+
timeout = 1800.0
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
STATE = State()
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def version() -> str:
|
|
48
|
+
try:
|
|
49
|
+
return json.loads((ROOT / "package.json").read_text(encoding="utf-8"))["version"]
|
|
50
|
+
except (OSError, ValueError, KeyError):
|
|
51
|
+
return "0.0.0"
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
# ---------------------------------------------------------------- CLI conventions
|
|
55
|
+
|
|
56
|
+
def add_common(parser: argparse.ArgumentParser) -> None:
|
|
57
|
+
g = parser.add_argument_group("shared flags")
|
|
58
|
+
g.add_argument("--json", action="store_true", help="print one JSON object on stdout")
|
|
59
|
+
g.add_argument("--dry-run", action="store_true", help="plan only: print the commands, write nothing")
|
|
60
|
+
g.add_argument("--overwrite", action="store_true", help="allow replacing an existing output file")
|
|
61
|
+
g.add_argument("--timeout", type=float, default=1800.0, metavar="SECONDS",
|
|
62
|
+
help="wall-clock limit for each external step (default 1800)")
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def apply_common(args: argparse.Namespace) -> None:
|
|
66
|
+
STATE.json = bool(args.json)
|
|
67
|
+
STATE.dry_run = bool(args.dry_run)
|
|
68
|
+
STATE.overwrite = bool(args.overwrite)
|
|
69
|
+
STATE.timeout = float(args.timeout)
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def info(msg: str) -> None:
|
|
73
|
+
print(msg, file=sys.stderr, flush=True)
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def emit(result: Dict[str, Any], summary: str) -> None:
|
|
77
|
+
"""Print the result: JSON on stdout with --json, otherwise the one-line summary."""
|
|
78
|
+
result.setdefault("status", "completed")
|
|
79
|
+
result.setdefault("dry_run", STATE.dry_run)
|
|
80
|
+
if STATE.json:
|
|
81
|
+
print(json.dumps(result, ensure_ascii=False, indent=2))
|
|
82
|
+
else:
|
|
83
|
+
print(summary)
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def die(msg: str, kind: str = "input", **extra: Any) -> "NoReturn": # type: ignore[name-defined]
|
|
87
|
+
if STATE.json:
|
|
88
|
+
out = {"status": "failed", "error": msg, "kind": kind, "dry_run": STATE.dry_run}
|
|
89
|
+
out.update(extra)
|
|
90
|
+
print(json.dumps(out, ensure_ascii=False, indent=2))
|
|
91
|
+
else:
|
|
92
|
+
info(f"error ({kind}): {msg}")
|
|
93
|
+
sys.exit(EXIT_FOR_KIND.get(kind, 1))
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def refuse_existing(path: Path) -> None:
|
|
97
|
+
if path.exists() and not STATE.overwrite:
|
|
98
|
+
die(f"{path} already exists; pass --overwrite to replace it", "input")
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def default_output(src: Path, suffix: str, ext: Optional[str] = None) -> Path:
|
|
102
|
+
return src.with_name(f"{src.stem}{suffix}{ext if ext is not None else src.suffix}")
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def run(cmd: Sequence[str], cwd: Optional[Path] = None, capture: bool = True,
|
|
106
|
+
env: Optional[Dict[str, str]] = None) -> subprocess.CompletedProcess:
|
|
107
|
+
"""Run one external step with the shared timeout. Never called under --dry-run by writers."""
|
|
108
|
+
try:
|
|
109
|
+
return subprocess.run(list(cmd), cwd=str(cwd) if cwd else None, env=env,
|
|
110
|
+
stdout=subprocess.PIPE if capture else None,
|
|
111
|
+
stderr=subprocess.PIPE if capture else None,
|
|
112
|
+
text=True, encoding="utf-8", errors="replace",
|
|
113
|
+
timeout=STATE.timeout)
|
|
114
|
+
except subprocess.TimeoutExpired:
|
|
115
|
+
die(f"timed out after {STATE.timeout:.0f}s: {' '.join(cmd[:3])} ...", "timeout")
|
|
116
|
+
except FileNotFoundError:
|
|
117
|
+
die(f"not found: {cmd[0]}", "missing_tool")
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def shell_join(cmd: Sequence[str]) -> str:
|
|
121
|
+
import shlex
|
|
122
|
+
return " ".join(shlex.quote(str(c)) for c in cmd)
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
# ---------------------------------------------------------------- ffmpeg-skill
|
|
126
|
+
|
|
127
|
+
def _skill_candidates() -> List[Path]:
|
|
128
|
+
home = Path.home()
|
|
129
|
+
env = os.environ.get("FFMPEG_SKILL_DIR")
|
|
130
|
+
out: List[Path] = []
|
|
131
|
+
if env:
|
|
132
|
+
out.append(Path(env).expanduser())
|
|
133
|
+
out += [
|
|
134
|
+
ROOT.parent / "ffmpeg-skill", # installed side by side (~/.claude/skills/*)
|
|
135
|
+
Path.cwd() / ".claude" / "skills" / "ffmpeg-skill", # project install
|
|
136
|
+
home / ".claude" / "skills" / "ffmpeg-skill",
|
|
137
|
+
home / ".agents" / "skills" / "ffmpeg-skill",
|
|
138
|
+
home / ".cursor" / "skills" / "ffmpeg-skill",
|
|
139
|
+
]
|
|
140
|
+
return out
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def find_ffmpeg_skill() -> Optional[Path]:
|
|
144
|
+
for c in _skill_candidates():
|
|
145
|
+
if (c / "scripts" / "probe.py").is_file() and (c / "scripts" / "check.py").is_file():
|
|
146
|
+
return c.resolve()
|
|
147
|
+
return None
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def require_ffmpeg_skill() -> Path:
|
|
151
|
+
found = find_ffmpeg_skill()
|
|
152
|
+
if found is None:
|
|
153
|
+
die("ffmpeg-skill not found. Install it with `npx ffmpeg-skill` (it lands next to this skill), "
|
|
154
|
+
"or set FFMPEG_SKILL_DIR to its folder. Looked in: "
|
|
155
|
+
+ ", ".join(str(c) for c in _skill_candidates()), "missing_tool")
|
|
156
|
+
return found
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def ffmpeg_skill_version(skill_dir: Path) -> Optional[str]:
|
|
160
|
+
try:
|
|
161
|
+
return json.loads((skill_dir / "package.json").read_text(encoding="utf-8")).get("version")
|
|
162
|
+
except (OSError, ValueError):
|
|
163
|
+
return None
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def ffskill_cmd(script: str, args: Sequence[str]) -> List[str]:
|
|
167
|
+
skill = require_ffmpeg_skill()
|
|
168
|
+
return [sys.executable, str(skill / "scripts" / f"{script}.py"), *[str(a) for a in args], "--json"]
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def ffskill(script: str, args: Sequence[str], allow_fail: bool = False) -> Dict[str, Any]:
|
|
172
|
+
"""Run one ffmpeg-skill script with --json and return its parsed result.
|
|
173
|
+
|
|
174
|
+
ffmpeg-skill prints its JSON object on stdout and human progress on stderr; a non-zero exit
|
|
175
|
+
still carries a JSON error object (status/kind/error) that is passed through as ours.
|
|
176
|
+
"""
|
|
177
|
+
cmd = ffskill_cmd(script, args)
|
|
178
|
+
proc = run(cmd)
|
|
179
|
+
try:
|
|
180
|
+
data = json.loads(proc.stdout) if proc.stdout.strip() else {}
|
|
181
|
+
except ValueError:
|
|
182
|
+
data = {}
|
|
183
|
+
if proc.returncode != 0 or not data or data.get("status") == "failed":
|
|
184
|
+
if allow_fail:
|
|
185
|
+
data.setdefault("status", "failed")
|
|
186
|
+
data.setdefault("error", (proc.stderr or "").strip()[-600:])
|
|
187
|
+
return data
|
|
188
|
+
err = data.get("error") or (proc.stderr or "").strip()[-600:] or f"exit {proc.returncode}"
|
|
189
|
+
die(f"ffmpeg-skill {script}.py failed: {err}", data.get("kind") or "failed",
|
|
190
|
+
command=shell_join(cmd))
|
|
191
|
+
data["_command"] = shell_join(cmd)
|
|
192
|
+
return data
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
# ---------------------------------------------------------------- timeline
|
|
196
|
+
|
|
197
|
+
def load_timeline(path: Path) -> Dict[str, Any]:
|
|
198
|
+
if not path.is_file():
|
|
199
|
+
die(f"timeline not found: {path} (make one with analyze.py)", "input")
|
|
200
|
+
try:
|
|
201
|
+
t = json.loads(path.read_text(encoding="utf-8"))
|
|
202
|
+
except ValueError as e:
|
|
203
|
+
die(f"{path} is not valid JSON: {e}", "input")
|
|
204
|
+
problems = validate_timeline(t)
|
|
205
|
+
if problems:
|
|
206
|
+
die(f"{path} is not a {TIMELINE_SCHEMA} file: " + "; ".join(problems), "input")
|
|
207
|
+
return t
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
def validate_timeline(t: Any) -> List[str]:
|
|
211
|
+
p: List[str] = []
|
|
212
|
+
if not isinstance(t, dict):
|
|
213
|
+
return ["top level must be an object"]
|
|
214
|
+
if t.get("schema") != TIMELINE_SCHEMA:
|
|
215
|
+
p.append(f"schema must be {TIMELINE_SCHEMA!r} (got {t.get('schema')!r})")
|
|
216
|
+
src = t.get("source")
|
|
217
|
+
if not isinstance(src, dict):
|
|
218
|
+
p.append("source missing")
|
|
219
|
+
else:
|
|
220
|
+
for k in ("duration", "fps", "width", "height"):
|
|
221
|
+
v = src.get(k)
|
|
222
|
+
if not isinstance(v, (int, float)) or v <= 0:
|
|
223
|
+
p.append(f"source.{k} must be a positive number")
|
|
224
|
+
for k in ("scenes", "silences", "speech", "peaks", "captions", "highlights"):
|
|
225
|
+
if not isinstance(t.get(k, []), list):
|
|
226
|
+
p.append(f"{k} must be a list")
|
|
227
|
+
for i, c in enumerate(t.get("captions", []) or []):
|
|
228
|
+
if not (isinstance(c, dict) and isinstance(c.get("start"), (int, float))
|
|
229
|
+
and isinstance(c.get("end"), (int, float)) and isinstance(c.get("text"), str)
|
|
230
|
+
and c["end"] > c["start"]):
|
|
231
|
+
p.append(f"captions[{i}] needs start < end and text")
|
|
232
|
+
break
|
|
233
|
+
for i, r in enumerate(t.get("speech", []) or []):
|
|
234
|
+
if not (isinstance(r, list) and len(r) == 2 and r[1] > r[0]):
|
|
235
|
+
p.append(f"speech[{i}] must be [start, end] with start < end")
|
|
236
|
+
break
|
|
237
|
+
return p
|
|
238
|
+
|
|
239
|
+
|
|
240
|
+
def sec_to_frames(seconds: float, fps: float) -> int:
|
|
241
|
+
# JavaScript's Math.round (round half up), not Python's round() (half to even): the TypeScript
|
|
242
|
+
# compositions compute the same frame numbers and the two must agree to the frame (94.5 -> 95).
|
|
243
|
+
return int(math.floor(seconds * fps + 0.5))
|
|
244
|
+
|
|
245
|
+
|
|
246
|
+
def expected_frames(comp: str, t: Dict[str, Any]) -> Optional[int]:
|
|
247
|
+
"""Duration the built-in compositions compute in calculateMetadata (src/timeline.ts mirrors this).
|
|
248
|
+
|
|
249
|
+
Custom compositions return None: their length is whatever their own calculateMetadata says,
|
|
250
|
+
and render.py then only reports the measured numbers.
|
|
251
|
+
"""
|
|
252
|
+
fps = float(t["source"]["fps"])
|
|
253
|
+
if comp in ("Captioned", "PeakPulse", "Titled", "BeatMontage"):
|
|
254
|
+
return max(1, sec_to_frames(float(t["source"]["duration"]), fps))
|
|
255
|
+
if comp in ("Jumpcut", "Highlights"):
|
|
256
|
+
if comp == "Jumpcut":
|
|
257
|
+
ranges = t.get("speech") or [[0.0, float(t["source"]["duration"])]]
|
|
258
|
+
else:
|
|
259
|
+
ranges = [[h["start"], h["end"]] for h in (t.get("highlights") or [])] or [[0.0, float(t["source"]["duration"])]]
|
|
260
|
+
total = sum(max(1, sec_to_frames(e, fps) - sec_to_frames(s, fps)) for s, e in ranges)
|
|
261
|
+
return max(1, total)
|
|
262
|
+
return None
|
|
263
|
+
|
|
264
|
+
|
|
265
|
+
# ---------------------------------------------------------------- Remotion project
|
|
266
|
+
|
|
267
|
+
BUILTIN_COMPOSITIONS = ("Captioned", "Jumpcut", "PeakPulse", "Titled", "Highlights", "BeatMontage")
|
|
268
|
+
|
|
269
|
+
|
|
270
|
+
def remotion_bin(project: Path) -> Path:
|
|
271
|
+
name = "remotion.cmd" if os.name == "nt" else "remotion"
|
|
272
|
+
return project / "node_modules" / ".bin" / name
|
|
273
|
+
|
|
274
|
+
|
|
275
|
+
def require_project(project: Path, need_install: bool = True) -> Path:
|
|
276
|
+
project = project.resolve()
|
|
277
|
+
if not (project / "package.json").is_file() or not (project / "src" / "index.ts").is_file():
|
|
278
|
+
die(f"{project} is not a Remotion project made by init.py (needs package.json and src/index.ts)", "input")
|
|
279
|
+
if need_install and not remotion_bin(project).exists():
|
|
280
|
+
die(f"Remotion is not installed in {project}: run `npm install` there (or init.py --install)",
|
|
281
|
+
"missing_tool")
|
|
282
|
+
return project
|
|
283
|
+
|
|
284
|
+
|
|
285
|
+
_NOISE = ("Detected differing memory amounts", "Memory reported by", "inadvertently set the --memory",
|
|
286
|
+
"Using the lower amount of memory")
|
|
287
|
+
|
|
288
|
+
|
|
289
|
+
def remotion_error(text: str, limit: int = 15) -> str:
|
|
290
|
+
"""The useful part of a failed Remotion CLI run: what follows 'An error occurred:', else the tail
|
|
291
|
+
without container-memory chatter."""
|
|
292
|
+
lines = [ln for ln in (text or "").splitlines() if ln.strip() and not any(n in ln for n in _NOISE)]
|
|
293
|
+
for i, ln in enumerate(lines):
|
|
294
|
+
if "An error occurred" in ln:
|
|
295
|
+
return "\n".join(ln2.strip() for ln2 in lines[i + 1:i + 1 + limit])
|
|
296
|
+
return "\n".join(lines[-limit:])
|
|
297
|
+
|
|
298
|
+
|
|
299
|
+
def stage_source(project: Path, source_path: str) -> str:
|
|
300
|
+
"""Make the source reachable by staticFile(): public/media/<hash>_<name>. Returns the src string."""
|
|
301
|
+
src = Path(source_path).expanduser().resolve()
|
|
302
|
+
if not src.is_file():
|
|
303
|
+
die(f"source in the timeline does not exist any more: {src}", "input")
|
|
304
|
+
return _stage(project, src, "media")
|
|
305
|
+
|
|
306
|
+
|
|
307
|
+
def _stage(project: Path, src: Path, folder: str) -> str:
|
|
308
|
+
st = src.stat()
|
|
309
|
+
tag = hashlib.sha1(f"{src}|{st.st_size}|{int(st.st_mtime)}".encode()).hexdigest()[:8]
|
|
310
|
+
rel = f"{folder}/{tag}_{src.name}"
|
|
311
|
+
dst = project / "public" / rel
|
|
312
|
+
if STATE.dry_run:
|
|
313
|
+
return rel
|
|
314
|
+
if dst.is_symlink(): # left by an older version or by hand: Remotion cannot serve it
|
|
315
|
+
dst.unlink()
|
|
316
|
+
elif dst.exists():
|
|
317
|
+
return rel
|
|
318
|
+
dst.parent.mkdir(parents=True, exist_ok=True)
|
|
319
|
+
# A hard link (instant, no extra space), else a one-time copy. Never a symlink: Remotion's file
|
|
320
|
+
# server refuses a public/ symlink that points outside the project (404 at render time).
|
|
321
|
+
# Remotion's CLI itself links the whole public/ folder into its temporary bundle on macOS/Linux,
|
|
322
|
+
# so the source is not copied again per render; on Windows the CLI copies public/ each time.
|
|
323
|
+
try:
|
|
324
|
+
os.link(src, dst)
|
|
325
|
+
except OSError:
|
|
326
|
+
info(f"copying {src.name} into the project (hard link not possible across drives) ...")
|
|
327
|
+
shutil.copy2(src, dst)
|
|
328
|
+
return rel
|
|
329
|
+
|
|
330
|
+
|
|
331
|
+
# ---------------------------------------------------------------- output frame
|
|
332
|
+
|
|
333
|
+
ASPECTS = {"16:9": (16, 9), "9:16": (9, 16), "1:1": (1, 1), "4:5": (4, 5), "4:3": (4, 3)}
|
|
334
|
+
FITS = ("blur", "contain", "cover")
|
|
335
|
+
|
|
336
|
+
|
|
337
|
+
def even(n: float) -> int:
|
|
338
|
+
return max(2, int(round(n / 2.0)) * 2)
|
|
339
|
+
|
|
340
|
+
|
|
341
|
+
def output_frame(timeline: Dict[str, Any], aspect: Optional[str], width: Optional[int],
|
|
342
|
+
fit: Optional[str]) -> Optional[Dict[str, Any]]:
|
|
343
|
+
"""The output frame for --aspect/--width/--fit, or None for the source's own size.
|
|
344
|
+
|
|
345
|
+
Without --width the output keeps the source's short side (720p stays 720 wide when turned
|
|
346
|
+
portrait: 720x1280), so nothing is upscaled; sizes are rounded to even numbers for H.264.
|
|
347
|
+
"""
|
|
348
|
+
src = timeline["source"]
|
|
349
|
+
sw, sh = int(src["width"]), int(src["height"])
|
|
350
|
+
if (aspect in (None, "source")) and width is None:
|
|
351
|
+
return None if fit in (None, "contain") else {"width": sw, "height": sh, "fit": fit}
|
|
352
|
+
if aspect in (None, "source"):
|
|
353
|
+
aw, ah = sw, sh
|
|
354
|
+
else:
|
|
355
|
+
aw, ah = ASPECTS[aspect]
|
|
356
|
+
if width is not None:
|
|
357
|
+
w = even(width)
|
|
358
|
+
h = even(w * ah / aw)
|
|
359
|
+
else:
|
|
360
|
+
short = min(sw, sh)
|
|
361
|
+
if aw <= ah:
|
|
362
|
+
w = even(short)
|
|
363
|
+
h = even(w * ah / aw)
|
|
364
|
+
else:
|
|
365
|
+
h = even(short)
|
|
366
|
+
w = even(h * aw / ah)
|
|
367
|
+
return {"width": w, "height": h, "fit": fit or ("blur" if aspect not in (None, "source") else "contain")}
|
|
368
|
+
|
|
369
|
+
|
|
370
|
+
def frame_size(timeline: Dict[str, Any], frame: Optional[Dict[str, Any]]) -> Tuple[int, int]:
|
|
371
|
+
if frame:
|
|
372
|
+
return int(frame["width"]), int(frame["height"])
|
|
373
|
+
return int(timeline["source"]["width"]), int(timeline["source"]["height"])
|
|
374
|
+
|
|
375
|
+
|
|
376
|
+
def platform_aspect(platform: Optional[str]) -> Optional[str]:
|
|
377
|
+
"""The aspect ffmpeg-skill's delivery template for this platform produces (its frame.aspect)."""
|
|
378
|
+
if not platform:
|
|
379
|
+
return None
|
|
380
|
+
skill = find_ffmpeg_skill()
|
|
381
|
+
if skill is None:
|
|
382
|
+
return None
|
|
383
|
+
try:
|
|
384
|
+
tpl = json.loads((skill / "templates" / f"{platform}.json").read_text(encoding="utf-8"))
|
|
385
|
+
except (OSError, ValueError):
|
|
386
|
+
return None
|
|
387
|
+
aspect = (tpl.get("frame") or {}).get("aspect")
|
|
388
|
+
return aspect if aspect in ASPECTS else None
|
|
389
|
+
|
|
390
|
+
|
|
391
|
+
# ---------------------------------------------------------------- fonts
|
|
392
|
+
|
|
393
|
+
def caption_script(captions: List[Dict[str, Any]]) -> Optional[str]:
|
|
394
|
+
"""ja / ko / zh when the caption text needs a CJK font, else None (Latin etc. render with system fonts)."""
|
|
395
|
+
text = "".join(c.get("text", "") for c in captions)
|
|
396
|
+
if any("" <= ch <= "ヿ" for ch in text):
|
|
397
|
+
return "ja"
|
|
398
|
+
if any("가" <= ch <= "" or "ᄀ" <= ch <= "ᇿ" for ch in text):
|
|
399
|
+
return "ko"
|
|
400
|
+
if any("一" <= ch <= "鿿" or "㐀" <= ch <= "䶿" for ch in text):
|
|
401
|
+
return "ja" # Han only: Japanese glyph forms by default; --font-file picks another
|
|
402
|
+
return None
|
|
403
|
+
|
|
404
|
+
|
|
405
|
+
def cjk_font_file(script: str) -> Optional[Path]:
|
|
406
|
+
"""The font file ffmpeg-skill's doctor resolves for this script on this machine."""
|
|
407
|
+
skill = find_ffmpeg_skill()
|
|
408
|
+
if skill is None:
|
|
409
|
+
return None
|
|
410
|
+
proc = subprocess.run([sys.executable, str(skill / "scripts" / "_contract.py"), "doctor", "--json"],
|
|
411
|
+
capture_output=True, text=True, timeout=120)
|
|
412
|
+
try:
|
|
413
|
+
entry = json.loads(proc.stdout)["fonts"]["scripts"].get(script) or {}
|
|
414
|
+
except (ValueError, KeyError, TypeError):
|
|
415
|
+
return None
|
|
416
|
+
f = entry.get("file")
|
|
417
|
+
return Path(f) if entry.get("status") == "available" and f and Path(f).is_file() else None
|
|
418
|
+
|
|
419
|
+
|
|
420
|
+
def stage_font(project: Path, font_file: Path) -> Dict[str, str]:
|
|
421
|
+
if not font_file.is_file():
|
|
422
|
+
die(f"font file not found: {font_file}", "input")
|
|
423
|
+
if font_file.suffix.lower() not in (".ttf", ".otf", ".ttc", ".otc", ".woff", ".woff2"):
|
|
424
|
+
die(f"{font_file.name}: use a .ttf, .otf, .ttc, .woff or .woff2 font", "input")
|
|
425
|
+
rel = _stage(project, font_file.resolve(), "fonts")
|
|
426
|
+
return {"src": rel, "family": "RFS " + Path(rel).name.split("_", 1)[0]}
|
|
427
|
+
|
|
428
|
+
|
|
429
|
+
def resolve_font(project: Path, timeline: Dict[str, Any], font_file: Optional[str],
|
|
430
|
+
auto: bool) -> Tuple[Optional[Dict[str, str]], Optional[str]]:
|
|
431
|
+
"""(font asset for the props, a note for the report). A given --font-file always wins; otherwise
|
|
432
|
+
CJK captions get the CJK font ffmpeg-skill finds on this machine, so they never render as tofu."""
|
|
433
|
+
if font_file:
|
|
434
|
+
return stage_font(project, Path(font_file).expanduser()), f"font: {font_file}"
|
|
435
|
+
script = caption_script(timeline.get("captions") or [])
|
|
436
|
+
if not script or not auto:
|
|
437
|
+
return None, None
|
|
438
|
+
found = cjk_font_file(script)
|
|
439
|
+
if found is None:
|
|
440
|
+
return None, (f"captions need a {script} font and none was found on this machine: install one "
|
|
441
|
+
f"(e.g. Noto Sans CJK) or pass --font-file; the contact sheet will show tofu otherwise")
|
|
442
|
+
return stage_font(project, found), f"font: {found} (found by ffmpeg-skill for {script} captions)"
|
|
443
|
+
|
|
444
|
+
|
|
445
|
+
def write_props(project: Path, comp: str, timeline: Dict[str, Any], options: Dict[str, Any],
|
|
446
|
+
frame: Optional[Dict[str, Any]] = None, font: Optional[Dict[str, str]] = None,
|
|
447
|
+
overlay: bool = False) -> Tuple[Path, Dict[str, Any]]:
|
|
448
|
+
t = json.loads(json.dumps(timeline))
|
|
449
|
+
src = t["source"].get("path")
|
|
450
|
+
has_media = t["source"].get("has_video", True) or t["source"].get("has_audio", False)
|
|
451
|
+
t["source"]["src"] = stage_source(project, src) if src and has_media and not overlay else None
|
|
452
|
+
props = {"timeline": t, "options": options, "frame": frame, "font": font, "overlay": overlay}
|
|
453
|
+
# Named by content: two renders running at once (different sources, shapes or options) never
|
|
454
|
+
# overwrite each other's props, and identical props share one file harmlessly.
|
|
455
|
+
digest = hashlib.sha1(json.dumps(props, sort_keys=True, ensure_ascii=False).encode("utf-8")).hexdigest()[:10]
|
|
456
|
+
path = project / ".rfs" / f"props-{comp}-{digest}.json"
|
|
457
|
+
if not STATE.dry_run:
|
|
458
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
459
|
+
path.write_text(json.dumps(props, ensure_ascii=False, indent=2), encoding="utf-8")
|
|
460
|
+
return path, props
|
|
461
|
+
|
|
462
|
+
|
|
463
|
+
def add_frame_args(p: argparse.ArgumentParser) -> None:
|
|
464
|
+
g = p.add_argument_group("output frame and font")
|
|
465
|
+
g.add_argument("--aspect", choices=["source", *ASPECTS], default=None,
|
|
466
|
+
help="output shape (default: the source's own). 9:16 for Reels/TikTok/Shorts, 1:1, 4:5, 16:9")
|
|
467
|
+
g.add_argument("--width", type=int, help="output width in px (default: keep the source's short side)")
|
|
468
|
+
g.add_argument("--fit", choices=FITS, help="how the source fills another shape: blur (default when the shape "
|
|
469
|
+
"changes), contain (bars) or cover (crop)")
|
|
470
|
+
g.add_argument("--font-file", help="caption font file (.ttf/.otf/.ttc/.woff2), staged into the project")
|
|
471
|
+
g.add_argument("--no-auto-font", action="store_true",
|
|
472
|
+
help="don't stage the CJK font ffmpeg-skill finds for Japanese/Chinese/Korean captions")
|
|
473
|
+
|
|
474
|
+
|
|
475
|
+
def prepare_props(project: Path, comp: str, timeline: Dict[str, Any], options: Dict[str, Any],
|
|
476
|
+
a: argparse.Namespace) -> Tuple[Path, Optional[Dict[str, Any]], Optional[str]]:
|
|
477
|
+
"""Frame + font + props file for render.py / still.py. Returns (props path, frame, font note)."""
|
|
478
|
+
if a.width is not None and a.width < 16:
|
|
479
|
+
die("--width must be at least 16 px", "input")
|
|
480
|
+
frame = output_frame(timeline, a.aspect, a.width, a.fit)
|
|
481
|
+
font, note = resolve_font(project, timeline, a.font_file, not a.no_auto_font)
|
|
482
|
+
props_path, _ = write_props(project, comp, timeline, options, frame, font, bool(getattr(a, "overlay", False)))
|
|
483
|
+
return props_path, frame, note
|
|
484
|
+
|
|
485
|
+
|
|
486
|
+
def load_options(path: Optional[str]) -> Dict[str, Any]:
|
|
487
|
+
if not path:
|
|
488
|
+
return {}
|
|
489
|
+
p = Path(path)
|
|
490
|
+
if not p.is_file():
|
|
491
|
+
die(f"options file not found: {p}", "input")
|
|
492
|
+
try:
|
|
493
|
+
data = json.loads(p.read_text(encoding="utf-8"))
|
|
494
|
+
except ValueError as e:
|
|
495
|
+
die(f"{p} is not valid JSON: {e}", "input")
|
|
496
|
+
if not isinstance(data, dict):
|
|
497
|
+
die(f"{p} must hold a JSON object", "input")
|
|
498
|
+
problems = validate_options(data)
|
|
499
|
+
if problems:
|
|
500
|
+
die(f"{p}: " + "; ".join(problems) + " (see references/timeline.md, Options)", "input")
|
|
501
|
+
return data
|
|
502
|
+
|
|
503
|
+
|
|
504
|
+
# Mirrors Options in src/timeline.ts. A typo'd key would silently do nothing in the browser, so it is refused here.
|
|
505
|
+
_OPTION_TYPES: Dict[str, Any] = {
|
|
506
|
+
"accent": str, "textColor": str, "fontFamily": str, "captionSize": (int, float),
|
|
507
|
+
"captionMargin": (int, float, type(None)), "punchIn": (int, float), "pulse": (int, float),
|
|
508
|
+
"progressBar": bool, "driver": str, "lowerThirds": list, "sceneTitles": list,
|
|
509
|
+
"title": (str, type(None)), "beatsPerCut": int,
|
|
510
|
+
}
|
|
511
|
+
|
|
512
|
+
|
|
513
|
+
def validate_options(o: Dict[str, Any]) -> List[str]:
|
|
514
|
+
p: List[str] = []
|
|
515
|
+
for k, v in o.items():
|
|
516
|
+
if k not in _OPTION_TYPES:
|
|
517
|
+
p.append(f"unknown option {k!r} (known: {', '.join(sorted(_OPTION_TYPES))})")
|
|
518
|
+
elif isinstance(v, bool) and _OPTION_TYPES[k] is not bool and bool not in (
|
|
519
|
+
_OPTION_TYPES[k] if isinstance(_OPTION_TYPES[k], tuple) else (_OPTION_TYPES[k],)):
|
|
520
|
+
p.append(f"{k} must be {_OPTION_TYPES[k]}, got a boolean")
|
|
521
|
+
elif not isinstance(v, _OPTION_TYPES[k]):
|
|
522
|
+
p.append(f"{k} has the wrong type ({type(v).__name__})")
|
|
523
|
+
if "driver" in o and o["driver"] not in ("auto", "peaks", "beats"):
|
|
524
|
+
p.append("driver must be auto, peaks or beats")
|
|
525
|
+
if isinstance(o.get("beatsPerCut"), int) and o["beatsPerCut"] < 1:
|
|
526
|
+
p.append("beatsPerCut must be at least 1")
|
|
527
|
+
for i, lt in enumerate(o.get("lowerThirds") or []):
|
|
528
|
+
if not (isinstance(lt, dict) and isinstance(lt.get("text"), str) and lt.get("text")
|
|
529
|
+
and isinstance(lt.get("start"), (int, float)) and isinstance(lt.get("end"), (int, float))
|
|
530
|
+
and lt["end"] > lt["start"] and isinstance(lt.get("sub", ""), str)):
|
|
531
|
+
p.append(f"lowerThirds[{i}] needs text, start < end (seconds) and an optional sub")
|
|
532
|
+
if any(not isinstance(s, str) for s in (o.get("sceneTitles") or [])):
|
|
533
|
+
p.append("sceneTitles must be a list of strings")
|
|
534
|
+
return p
|
|
535
|
+
|
|
536
|
+
|
|
537
|
+
def now() -> float:
|
|
538
|
+
return time.monotonic()
|