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.
- package/LICENSE +21 -0
- package/README.md +112 -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,122 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""The whole loop in one command: measure (analyze.py) -> draw (render.py) -> deliver and
|
|
3
|
+
check (deliver.py), each step verified before the next runs. Stops at the first failure
|
|
4
|
+
and says which step failed.
|
|
5
|
+
|
|
6
|
+
Examples:
|
|
7
|
+
python3 pipeline.py talk.mp4 --project ./motion --comp Jumpcut --captions talk.srt --platform youtube
|
|
8
|
+
python3 pipeline.py clip.mp4 --project ./motion --comp PeakPulse --platform reels --out-dir out/
|
|
9
|
+
python3 pipeline.py talk.mp4 --project ./motion --comp Captioned --captions talk.srt # no delivery step
|
|
10
|
+
"""
|
|
11
|
+
import argparse
|
|
12
|
+
import json
|
|
13
|
+
import subprocess
|
|
14
|
+
import sys
|
|
15
|
+
from pathlib import Path
|
|
16
|
+
from typing import Any, Dict, List
|
|
17
|
+
|
|
18
|
+
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
|
19
|
+
from _common import (ASPECTS, BUILTIN_COMPOSITIONS, FITS, HERE, STATE, add_common, apply_common, die, emit, info,
|
|
20
|
+
platform_aspect, shell_join)
|
|
21
|
+
from deliver import PLATFORMS
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
25
|
+
p = argparse.ArgumentParser(description=__doc__.split("\n\n")[0],
|
|
26
|
+
formatter_class=argparse.RawDescriptionHelpFormatter, epilog=__doc__)
|
|
27
|
+
p.add_argument("input", nargs="+", help="source video; several are joined in order (ffmpeg-skill join.py) first")
|
|
28
|
+
p.add_argument("--project", required=True, help="Remotion project folder made by init.py")
|
|
29
|
+
p.add_argument("--comp", required=True, help=f"composition id ({', '.join(BUILTIN_COMPOSITIONS)}, or yours)")
|
|
30
|
+
p.add_argument("--captions", help="SRT / WebVTT / JSON cues for the timeline")
|
|
31
|
+
p.add_argument("--options", help="JSON options file passed to the composition")
|
|
32
|
+
p.add_argument("--platform", choices=PLATFORMS, help="deliver with this ffmpeg-skill template and check it")
|
|
33
|
+
p.add_argument("--out-dir", help="where the timeline, render and deliverable go (default: next to the input)")
|
|
34
|
+
p.add_argument("--beats", action="store_true", help="measure the beat grid too")
|
|
35
|
+
p.add_argument("--fast", action="store_true", help="preview-quality render")
|
|
36
|
+
p.add_argument("--aspect", choices=["source", *ASPECTS],
|
|
37
|
+
help="output shape (default: the shape the --platform template delivers, else the source's)")
|
|
38
|
+
p.add_argument("--width", type=int, help="output width in px")
|
|
39
|
+
p.add_argument("--fit", choices=FITS, help="blur (default when the shape changes), contain or cover")
|
|
40
|
+
p.add_argument("--font-file", help="caption font file")
|
|
41
|
+
add_common(p)
|
|
42
|
+
return p
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def step(name: str, script: str, args: List[str], steps: List[Dict[str, Any]]) -> Dict[str, Any]:
|
|
46
|
+
cmd = [sys.executable, str(HERE / f"{script}.py"), *args, "--json", "--timeout", str(STATE.timeout)]
|
|
47
|
+
if STATE.overwrite:
|
|
48
|
+
cmd.append("--overwrite")
|
|
49
|
+
if STATE.dry_run:
|
|
50
|
+
cmd.append("--dry-run")
|
|
51
|
+
info(f"[{name}] {script}.py")
|
|
52
|
+
proc = subprocess.run(cmd, capture_output=True, text=True, encoding="utf-8", errors="replace")
|
|
53
|
+
try:
|
|
54
|
+
data = json.loads(proc.stdout)
|
|
55
|
+
except ValueError:
|
|
56
|
+
data = {"status": "failed", "error": (proc.stderr or proc.stdout).strip()[-800:], "kind": "failed"}
|
|
57
|
+
data["_command"] = shell_join(cmd)
|
|
58
|
+
steps.append({"step": name, "status": data.get("status"), "output": data.get("output"), "command": data["_command"]})
|
|
59
|
+
if proc.returncode != 0 or data.get("status") == "failed":
|
|
60
|
+
die(f"step '{name}' failed: {data.get('error') or 'verification failed'}", data.get("kind") or "failed",
|
|
61
|
+
steps=steps, failed_step=data)
|
|
62
|
+
return data
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def main() -> None:
|
|
66
|
+
a = build_parser().parse_args()
|
|
67
|
+
apply_common(a)
|
|
68
|
+
inputs = [Path(i).expanduser() for i in a.input]
|
|
69
|
+
missing = [str(i) for i in inputs if not i.is_file()]
|
|
70
|
+
if missing:
|
|
71
|
+
die(f"input not found: {', '.join(missing)}", "input")
|
|
72
|
+
src = inputs[0]
|
|
73
|
+
out_dir = Path(a.out_dir).expanduser() if a.out_dir else src.parent
|
|
74
|
+
if not STATE.dry_run:
|
|
75
|
+
out_dir.mkdir(parents=True, exist_ok=True)
|
|
76
|
+
stem = src.stem + ("_joined" if len(inputs) > 1 else "")
|
|
77
|
+
tl = out_dir / f"{stem}.timeline.json"
|
|
78
|
+
render_out = out_dir / f"{stem}_{a.comp}.mp4"
|
|
79
|
+
steps: List[Dict[str, Any]] = []
|
|
80
|
+
|
|
81
|
+
an_args = [*map(str, inputs), "-o", str(tl)] + (["--joined", str(out_dir / f"{stem}.mp4")] if len(inputs) > 1 else [])
|
|
82
|
+
an_args += (["--captions", a.captions] if a.captions else []) + (["--beats"] if a.beats else [])
|
|
83
|
+
analysis = step("measure", "analyze", an_args, steps)
|
|
84
|
+
if STATE.dry_run and not tl.exists():
|
|
85
|
+
emit({"output": None, "steps": steps,
|
|
86
|
+
"note": "dry run stops after planning the measurement: render needs the timeline it would write"},
|
|
87
|
+
"planned: " + " -> ".join(s["step"] for s in steps))
|
|
88
|
+
return
|
|
89
|
+
|
|
90
|
+
r_args = ["--project", a.project, "--comp", a.comp, "--timeline", str(tl), "-o", str(render_out)]
|
|
91
|
+
if a.options:
|
|
92
|
+
r_args += ["--options", a.options]
|
|
93
|
+
if a.fast:
|
|
94
|
+
r_args.append("--fast")
|
|
95
|
+
# Draw in the shape the delivery template will produce: a 16:9 render pushed through the Reels
|
|
96
|
+
# template would be centre-cropped to 9:16 and lose the edges of every caption.
|
|
97
|
+
aspect = a.aspect or platform_aspect(a.platform)
|
|
98
|
+
if aspect:
|
|
99
|
+
r_args += ["--aspect", aspect]
|
|
100
|
+
for flag, val in (("--width", a.width), ("--fit", a.fit), ("--font-file", a.font_file)):
|
|
101
|
+
if val is not None:
|
|
102
|
+
r_args += [flag, str(val)]
|
|
103
|
+
rendered = step("draw", "render", r_args, steps)
|
|
104
|
+
|
|
105
|
+
delivered = None
|
|
106
|
+
if a.platform:
|
|
107
|
+
delivered = step("deliver", "deliver", [str(render_out), "--platform", a.platform], steps)
|
|
108
|
+
|
|
109
|
+
final = (delivered or {}).get("output") or rendered.get("output")
|
|
110
|
+
look = rendered.get("look")
|
|
111
|
+
lines = [f"measure: {analysis.get('summary')}", f"draw: {rendered.get('summary')}"]
|
|
112
|
+
if delivered:
|
|
113
|
+
lines.append(f"deliver: {Path(delivered.get('checked') or '').name} "
|
|
114
|
+
f"({'PASS' if delivered.get('verified') else 'FAIL'}, warnings: {', '.join(delivered.get('warnings') or []) or 'none'})")
|
|
115
|
+
lines.append(f"Look: {look}" if look else "Look: not generated")
|
|
116
|
+
emit({"output": final, "timeline": str(tl), "render": rendered.get("output"),
|
|
117
|
+
"deliverable": (delivered or {}).get("output"), "look": look, "verified": True,
|
|
118
|
+
"warnings": analysis.get("warnings", []), "steps": steps}, "\n".join(lines))
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
if __name__ == "__main__":
|
|
122
|
+
main()
|
|
@@ -0,0 +1,215 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Render a composition from a measured timeline with Remotion, then verify the result with
|
|
3
|
+
ffmpeg-skill: probe the output against the frame count, fps and size the timeline implies,
|
|
4
|
+
and pull a contact sheet (look.py) so the picture can be checked before anything ships.
|
|
5
|
+
|
|
6
|
+
Examples:
|
|
7
|
+
python3 render.py --project ./motion --comp Captioned --timeline talk.timeline.json -o captioned.mp4
|
|
8
|
+
python3 render.py --project ./motion --comp Jumpcut --timeline talk.timeline.json --options look.json
|
|
9
|
+
python3 render.py --project ./motion --comp PeakPulse --timeline tl.json --frames 0-89 --fast
|
|
10
|
+
python3 render.py --project ./motion --comp Captioned --timeline tl.json --codec prores -o master.mov
|
|
11
|
+
"""
|
|
12
|
+
import argparse
|
|
13
|
+
import sys
|
|
14
|
+
from pathlib import Path
|
|
15
|
+
from typing import Any, Dict, List, Optional, Tuple
|
|
16
|
+
|
|
17
|
+
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
|
18
|
+
from _common import (BUILTIN_COMPOSITIONS, STATE, add_common, add_frame_args, apply_common, die, emit, expected_frames,
|
|
19
|
+
ffskill, ffskill_cmd, frame_size, info, load_options, load_timeline, prepare_props, refuse_existing,
|
|
20
|
+
remotion_bin, require_ffmpeg_skill, require_project, remotion_error, run, shell_join)
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
24
|
+
p = argparse.ArgumentParser(description=__doc__.split("\n\n")[0],
|
|
25
|
+
formatter_class=argparse.RawDescriptionHelpFormatter, epilog=__doc__)
|
|
26
|
+
p.add_argument("--project", required=True, help="Remotion project folder made by init.py")
|
|
27
|
+
p.add_argument("--comp", required=True,
|
|
28
|
+
help=f"composition id ({', '.join(BUILTIN_COMPOSITIONS)}, or one you added)")
|
|
29
|
+
p.add_argument("--timeline", required=True, help="timeline.json written by analyze.py")
|
|
30
|
+
p.add_argument("--options", help="JSON object of look-and-feel options (see references/timeline.md)")
|
|
31
|
+
p.add_argument("-o", "--output", help="output file (default: <source>_<comp>.mp4, .mov for prores)")
|
|
32
|
+
p.add_argument("--codec", choices=["h264", "prores"], default="h264",
|
|
33
|
+
help="h264 (default) or prores (ProRes 422 HQ master, .mov)")
|
|
34
|
+
p.add_argument("--crf", type=int, help="h264 quality (Remotion default 18; lower = better)")
|
|
35
|
+
p.add_argument("--frames", help="render only this frame range, e.g. 0-89 (inclusive)")
|
|
36
|
+
p.add_argument("--fast", action="store_true", help="preview quality: half resolution, quicker encode")
|
|
37
|
+
p.add_argument("--concurrency", help="Remotion --concurrency (number or percentage)")
|
|
38
|
+
p.add_argument("--no-look", action="store_true", help="skip the contact sheet")
|
|
39
|
+
p.add_argument("--overlay", action="store_true",
|
|
40
|
+
help="draw the graphics only as a transparent ProRes 4444 layer and composite it over the "
|
|
41
|
+
"untouched source with ffmpeg-skill overlay.py (Captioned / PeakPulse, source frame only); "
|
|
42
|
+
"with --keep-graphics the layer is kept for an editing app (Premiere, Resolve, Final Cut)")
|
|
43
|
+
p.add_argument("--keep-graphics", action="store_true", help="with --overlay: keep the transparent graphics .mov")
|
|
44
|
+
add_frame_args(p)
|
|
45
|
+
add_common(p)
|
|
46
|
+
return p
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def parse_frames(spec: Optional[str]) -> Optional[Tuple[int, int]]:
|
|
50
|
+
if not spec:
|
|
51
|
+
return None
|
|
52
|
+
try:
|
|
53
|
+
a, b = (int(x) for x in spec.split("-", 1))
|
|
54
|
+
except ValueError:
|
|
55
|
+
die(f"--frames must look like 0-89, got {spec!r}", "input")
|
|
56
|
+
if a < 0 or b < a:
|
|
57
|
+
die(f"--frames range is empty or negative: {spec!r}", "input")
|
|
58
|
+
return a, b
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def remotion_render_cmd(project: Path, comp: str, output: Path, props: Path, a: argparse.Namespace) -> List[str]:
|
|
62
|
+
if getattr(a, "overlay", False):
|
|
63
|
+
# Transparent graphics layer: PNG frames keep the alpha, ProRes 4444 carries it.
|
|
64
|
+
cmd = [str(remotion_bin(project)), "render", "src/index.ts", comp, str(output), f"--props={props}",
|
|
65
|
+
"--codec=prores", "--prores-profile=4444", "--image-format=png", "--pixel-format=yuva444p10le",
|
|
66
|
+
"--log=warn"]
|
|
67
|
+
if a.frames:
|
|
68
|
+
cmd.append(f"--frames={a.frames}")
|
|
69
|
+
if a.concurrency:
|
|
70
|
+
cmd.append(f"--concurrency={a.concurrency}")
|
|
71
|
+
return cmd
|
|
72
|
+
cmd = [str(remotion_bin(project)), "render", "src/index.ts", comp, str(output), f"--props={props}",
|
|
73
|
+
f"--codec={a.codec}", "--log=warn"]
|
|
74
|
+
if a.codec == "prores":
|
|
75
|
+
cmd.append("--prores-profile=hq")
|
|
76
|
+
if a.crf is not None and a.codec == "h264":
|
|
77
|
+
cmd.append(f"--crf={a.crf}")
|
|
78
|
+
if a.frames:
|
|
79
|
+
cmd.append(f"--frames={a.frames}")
|
|
80
|
+
if a.fast:
|
|
81
|
+
cmd += ["--scale=0.5"]
|
|
82
|
+
if a.codec == "h264" and a.crf is None:
|
|
83
|
+
cmd.append("--crf=28")
|
|
84
|
+
if a.concurrency:
|
|
85
|
+
cmd.append(f"--concurrency={a.concurrency}")
|
|
86
|
+
return cmd
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def verify(out_probe: Dict[str, Any], timeline: Dict[str, Any], comp: str,
|
|
90
|
+
frames: Optional[Tuple[int, int]], fast: bool,
|
|
91
|
+
frame: Optional[Dict[str, Any]] = None) -> Tuple[bool, List[Dict[str, Any]]]:
|
|
92
|
+
src = timeline["source"]
|
|
93
|
+
fps = float(src["fps"])
|
|
94
|
+
v = out_probe.get("video") or {}
|
|
95
|
+
rows: List[Dict[str, Any]] = []
|
|
96
|
+
|
|
97
|
+
def row(name: str, ok: bool, value: Any, expected: Any) -> None:
|
|
98
|
+
rows.append({"check": name, "status": "PASS" if ok else "FAIL", "value": value, "expected": expected})
|
|
99
|
+
|
|
100
|
+
scale = 0.5 if fast else 1.0
|
|
101
|
+
fw, fh = frame_size(timeline, frame)
|
|
102
|
+
ew, eh = int(round(fw * scale)), int(round(fh * scale))
|
|
103
|
+
# Remotion rounds odd scaled sizes to even numbers for H.264.
|
|
104
|
+
row("size", abs(int(v.get("width") or 0) - ew) <= 1 and abs(int(v.get("height") or 0) - eh) <= 1,
|
|
105
|
+
f"{v.get('width')}x{v.get('height')}", f"{ew}x{eh}")
|
|
106
|
+
out_fps = float(v.get("fps") or 0)
|
|
107
|
+
row("fps", abs(out_fps - fps) < 0.01, out_fps, fps)
|
|
108
|
+
|
|
109
|
+
want = (frames[1] - frames[0] + 1) if frames else expected_frames(comp, timeline)
|
|
110
|
+
duration = float(out_probe.get("duration") or v.get("duration") or 0)
|
|
111
|
+
nb = v.get("nb_frames")
|
|
112
|
+
if want is not None and isinstance(nb, int) and nb > 0:
|
|
113
|
+
# The video stream's own frame count: exact, unaffected by audio padding.
|
|
114
|
+
row("frames", nb == want, nb, want)
|
|
115
|
+
elif want is not None:
|
|
116
|
+
want_s = want / fps
|
|
117
|
+
# No frame count in the container: one frame of slack plus AAC priming/padding (~1024 samples).
|
|
118
|
+
row("duration", abs(duration - want_s) <= (1.0 / fps) + 0.05, round(duration, 3), round(want_s, 3))
|
|
119
|
+
else:
|
|
120
|
+
rows.append({"check": "duration", "status": "INFO", "value": round(duration, 3),
|
|
121
|
+
"expected": "custom composition: no built-in expectation"})
|
|
122
|
+
if src.get("has_audio") and comp in BUILTIN_COMPOSITIONS:
|
|
123
|
+
row("audio", bool(out_probe.get("audio")), "present" if out_probe.get("audio") else "missing", "present")
|
|
124
|
+
return all(r["status"] != "FAIL" for r in rows), rows
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def main() -> None:
|
|
128
|
+
a = build_parser().parse_args()
|
|
129
|
+
apply_common(a)
|
|
130
|
+
timeline_path = Path(a.timeline).expanduser()
|
|
131
|
+
timeline = load_timeline(timeline_path)
|
|
132
|
+
project = require_project(Path(a.project).expanduser(), need_install=not STATE.dry_run)
|
|
133
|
+
options = load_options(a.options)
|
|
134
|
+
frames = parse_frames(a.frames)
|
|
135
|
+
require_ffmpeg_skill()
|
|
136
|
+
|
|
137
|
+
ext = ".mov" if a.codec == "prores" else ".mp4"
|
|
138
|
+
if a.output:
|
|
139
|
+
output = Path(a.output).expanduser()
|
|
140
|
+
if a.codec == "prores" and output.suffix.lower() != ".mov":
|
|
141
|
+
die("--codec prores needs a .mov output", "input")
|
|
142
|
+
else:
|
|
143
|
+
stem = Path(timeline["source"].get("name") or "render").stem
|
|
144
|
+
output = timeline_path.with_name(f"{stem}_{a.comp}{ext}")
|
|
145
|
+
output = output.resolve()
|
|
146
|
+
refuse_existing(output)
|
|
147
|
+
|
|
148
|
+
if a.overlay:
|
|
149
|
+
if a.comp in ("Jumpcut", "Highlights", "BeatMontage"):
|
|
150
|
+
die(f"--overlay cannot do {a.comp}: its cuts move the picture itself (overlay works for "
|
|
151
|
+
"Captioned, PeakPulse, Titled)", "input")
|
|
152
|
+
if a.aspect not in (None, "source") or a.width is not None or a.fit not in (None, "contain"):
|
|
153
|
+
die("--overlay draws on the source's own frame: drop --aspect / --width / --fit", "input")
|
|
154
|
+
if a.fast or a.codec != "h264" or frames:
|
|
155
|
+
die("--overlay renders the full length at full size to H.264: drop --fast / --codec / --frames", "input")
|
|
156
|
+
if not timeline["source"].get("has_video"):
|
|
157
|
+
die("--overlay needs a video source to composite onto", "input")
|
|
158
|
+
|
|
159
|
+
props_path, frame, font_note = prepare_props(project, a.comp, timeline, options, a)
|
|
160
|
+
if font_note:
|
|
161
|
+
info(font_note)
|
|
162
|
+
graphics = output.with_name(output.stem + ".graphics.mov") if a.overlay else output
|
|
163
|
+
cmd = remotion_render_cmd(project, a.comp, graphics, props_path, a)
|
|
164
|
+
ov_args = [timeline["source"]["path"], "--video", str(graphics), "--position", "0,0", "--margin", "0",
|
|
165
|
+
"-o", str(output)] + (["--overwrite"] if STATE.overwrite else [])
|
|
166
|
+
if STATE.dry_run:
|
|
167
|
+
plan = [shell_join(cmd)] + ([shell_join(ffskill_cmd("overlay", ov_args))] if a.overlay else [])
|
|
168
|
+
emit({"output": str(output), "commands": plan, "props": str(props_path),
|
|
169
|
+
"expected_frames": (frames[1] - frames[0] + 1) if frames else expected_frames(a.comp, timeline),
|
|
170
|
+
"frame": frame, "font": font_note},
|
|
171
|
+
f"would render {a.comp} -> {output}")
|
|
172
|
+
return
|
|
173
|
+
|
|
174
|
+
output.parent.mkdir(parents=True, exist_ok=True)
|
|
175
|
+
if a.overlay and graphics.exists():
|
|
176
|
+
graphics.unlink()
|
|
177
|
+
info(f"rendering {a.comp} with Remotion -> {graphics}")
|
|
178
|
+
proc = run(cmd, cwd=project)
|
|
179
|
+
if proc.returncode != 0 or not graphics.is_file() or graphics.stat().st_size == 0:
|
|
180
|
+
tail = remotion_error((proc.stderr or "") + "\n" + (proc.stdout or ""))
|
|
181
|
+
die(f"Remotion render failed (exit {proc.returncode}):\n{tail}", "failed", command=shell_join(cmd))
|
|
182
|
+
commands = [shell_join(cmd)]
|
|
183
|
+
if a.overlay:
|
|
184
|
+
info(f"compositing the graphics over the source with ffmpeg-skill overlay.py -> {output}")
|
|
185
|
+
ov = ffskill("overlay", ov_args)
|
|
186
|
+
commands.append(ov["_command"])
|
|
187
|
+
if not a.keep_graphics:
|
|
188
|
+
graphics.unlink(missing_ok=True)
|
|
189
|
+
|
|
190
|
+
probe = ffskill("probe", [str(output)])
|
|
191
|
+
ok, rows = verify(probe, timeline, a.comp, frames, a.fast, frame)
|
|
192
|
+
look: Optional[str] = None
|
|
193
|
+
commands.append(probe["_command"])
|
|
194
|
+
if not a.no_look:
|
|
195
|
+
lk = ffskill("look", [str(output), "--tiles", "3x2"], allow_fail=True)
|
|
196
|
+
if lk.get("status") == "completed":
|
|
197
|
+
look = lk.get("output")
|
|
198
|
+
commands.append(lk.get("_command", ""))
|
|
199
|
+
v = probe.get("video") or {}
|
|
200
|
+
summary = (f"{output.name}: {float(probe.get('duration') or 0):.2f} s, {v.get('width')}x{v.get('height')}, "
|
|
201
|
+
f"{v.get('fps')} fps, {'audio' if probe.get('audio') else 'no audio'}")
|
|
202
|
+
result = {"status": "completed" if ok else "failed", "output": str(output), "verified": ok,
|
|
203
|
+
"verification": rows, "commands": commands, "look": look, "summary": summary,
|
|
204
|
+
"frame": frame, "font": font_note, "mode": "overlay" if a.overlay else "full",
|
|
205
|
+
"graphics": str(graphics) if a.overlay and a.keep_graphics else None,
|
|
206
|
+
"kind": None if ok else "failed"}
|
|
207
|
+
table = "\n".join(f" {r['check']:<9} {r['status']:<4} {r['value']} (expected {r['expected']})" for r in rows)
|
|
208
|
+
emit(result, summary + "\n" + table + (f"\nLook: {look}" if look else "") +
|
|
209
|
+
("" if ok else "\nverification FAILED: " + ", ".join(r["check"] for r in rows if r["status"] == "FAIL")))
|
|
210
|
+
if not ok:
|
|
211
|
+
sys.exit(1)
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
if __name__ == "__main__":
|
|
215
|
+
main()
|
package/scripts/still.py
ADDED
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Render single frames of a composition as PNG -- the cheap check before a full render.
|
|
3
|
+
Pick frames by time (--at, seconds on the composition timeline) or by frame number.
|
|
4
|
+
|
|
5
|
+
Examples:
|
|
6
|
+
python3 still.py --project ./motion --comp Captioned --timeline tl.json --at 1.2 --at 5.5
|
|
7
|
+
python3 still.py --project ./motion --comp Jumpcut --timeline tl.json --frame 0 --frame 120
|
|
8
|
+
python3 still.py --project ./motion --comp PeakPulse --timeline tl.json # first, middle, last
|
|
9
|
+
"""
|
|
10
|
+
import argparse
|
|
11
|
+
import sys
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
from typing import List
|
|
14
|
+
|
|
15
|
+
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
|
16
|
+
from _common import (BUILTIN_COMPOSITIONS, STATE, add_common, add_frame_args, apply_common, die, emit,
|
|
17
|
+
expected_frames, info, load_options, load_timeline, prepare_props, refuse_existing, remotion_bin,
|
|
18
|
+
require_project, remotion_error, run, sec_to_frames, shell_join)
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
22
|
+
p = argparse.ArgumentParser(description=__doc__.split("\n\n")[0],
|
|
23
|
+
formatter_class=argparse.RawDescriptionHelpFormatter, epilog=__doc__)
|
|
24
|
+
p.add_argument("--project", required=True, help="Remotion project folder made by init.py")
|
|
25
|
+
p.add_argument("--comp", required=True, help=f"composition id ({', '.join(BUILTIN_COMPOSITIONS)}, or yours)")
|
|
26
|
+
p.add_argument("--timeline", required=True, help="timeline.json written by analyze.py")
|
|
27
|
+
p.add_argument("--options", help="JSON object of look-and-feel options")
|
|
28
|
+
p.add_argument("--at", type=float, action="append", default=[], help="time in seconds (repeatable)")
|
|
29
|
+
p.add_argument("--frame", type=int, action="append", default=[], help="frame number (repeatable)")
|
|
30
|
+
p.add_argument("--out-dir", help="folder for the PNGs (default: next to the timeline)")
|
|
31
|
+
add_frame_args(p)
|
|
32
|
+
add_common(p)
|
|
33
|
+
return p
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def main() -> None:
|
|
37
|
+
a = build_parser().parse_args()
|
|
38
|
+
apply_common(a)
|
|
39
|
+
tl_path = Path(a.timeline).expanduser()
|
|
40
|
+
timeline = load_timeline(tl_path)
|
|
41
|
+
project = require_project(Path(a.project).expanduser(), need_install=not STATE.dry_run)
|
|
42
|
+
options = load_options(a.options)
|
|
43
|
+
fps = float(timeline["source"]["fps"])
|
|
44
|
+
|
|
45
|
+
frames: List[int] = list(a.frame) + [sec_to_frames(t, fps) for t in a.at]
|
|
46
|
+
total = expected_frames(a.comp, timeline)
|
|
47
|
+
if not frames:
|
|
48
|
+
if total is None:
|
|
49
|
+
die("custom composition: pass --frame or --at", "input")
|
|
50
|
+
frames = sorted({0, total // 2, max(0, total - 1)})
|
|
51
|
+
if total is not None:
|
|
52
|
+
bad = [f for f in frames if f < 0 or f >= total]
|
|
53
|
+
if bad:
|
|
54
|
+
die(f"frame(s) {bad} outside the composition (0..{total - 1})", "input")
|
|
55
|
+
|
|
56
|
+
out_dir = Path(a.out_dir).expanduser() if a.out_dir else tl_path.parent
|
|
57
|
+
stem = Path(timeline["source"].get("name") or "still").stem
|
|
58
|
+
props_path, frame, font_note = prepare_props(project, a.comp, timeline, options, a)
|
|
59
|
+
if font_note:
|
|
60
|
+
info(font_note)
|
|
61
|
+
outputs, commands = [], []
|
|
62
|
+
for f in frames:
|
|
63
|
+
out = (out_dir / f"{stem}_{a.comp}_f{f:05d}.png").resolve()
|
|
64
|
+
refuse_existing(out)
|
|
65
|
+
cmd = [str(remotion_bin(project)), "still", "src/index.ts", a.comp, str(out),
|
|
66
|
+
f"--props={props_path}", f"--frame={f}", "--log=warn"]
|
|
67
|
+
commands.append(shell_join(cmd))
|
|
68
|
+
if STATE.dry_run:
|
|
69
|
+
outputs.append(str(out))
|
|
70
|
+
continue
|
|
71
|
+
out_dir.mkdir(parents=True, exist_ok=True)
|
|
72
|
+
info(f"still frame {f} ({f / fps:.3f}s) -> {out}")
|
|
73
|
+
proc = run(cmd, cwd=project)
|
|
74
|
+
if proc.returncode != 0 or not out.is_file():
|
|
75
|
+
tail = remotion_error((proc.stderr or "") + "\n" + (proc.stdout or ""))
|
|
76
|
+
die(f"Remotion still failed for frame {f}:\n{tail}", "failed", command=shell_join(cmd))
|
|
77
|
+
outputs.append(str(out))
|
|
78
|
+
emit({"output": outputs[0] if outputs else None, "outputs": outputs, "frames": frames,
|
|
79
|
+
"commands": commands, "verified": not STATE.dry_run, "frame": frame, "font": font_note},
|
|
80
|
+
("would write " if STATE.dry_run else "Look: ") + ", ".join(outputs))
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
if __name__ == "__main__":
|
|
84
|
+
main()
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "remotion-ffmpeg-project",
|
|
3
|
+
"private": true,
|
|
4
|
+
"version": "1.0.0",
|
|
5
|
+
"description": "Remotion project scaffolded by remotion-ffmpeg-skill (init.py). Compositions read a timeline.json measured by ffmpeg-skill.",
|
|
6
|
+
"scripts": {
|
|
7
|
+
"studio": "remotion studio src/index.ts",
|
|
8
|
+
"typecheck": "tsc --noEmit"
|
|
9
|
+
},
|
|
10
|
+
"dependencies": {
|
|
11
|
+
"@remotion/cli": "4.0.538",
|
|
12
|
+
"remotion": "4.0.538",
|
|
13
|
+
"react": "19.3.1",
|
|
14
|
+
"react-dom": "19.3.1"
|
|
15
|
+
},
|
|
16
|
+
"devDependencies": {
|
|
17
|
+
"@types/react": "^19.0.0",
|
|
18
|
+
"typescript": "^5.6.0"
|
|
19
|
+
}
|
|
20
|
+
}
|
|
File without changes
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
// Remotion CLI settings for projects made by remotion-ffmpeg-skill.
|
|
2
|
+
// render.py passes codec, props and output on the command line; only defaults live here.
|
|
3
|
+
import { Config } from "@remotion/cli/config";
|
|
4
|
+
|
|
5
|
+
Config.setVideoImageFormat("jpeg");
|
|
6
|
+
Config.setOverwriteOutput(true);
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import React from "react";
|
|
2
|
+
import { Composition, type CalculateMetadataFunction } from "remotion";
|
|
3
|
+
import { Captioned } from "./compositions/Captioned";
|
|
4
|
+
import { Jumpcut } from "./compositions/Jumpcut";
|
|
5
|
+
import { PeakPulse } from "./compositions/PeakPulse";
|
|
6
|
+
import { Titled } from "./compositions/Titled";
|
|
7
|
+
import { Highlights } from "./compositions/Highlights";
|
|
8
|
+
import { BeatMontage } from "./compositions/BeatMontage";
|
|
9
|
+
import { SAMPLE_TIMELINE, fullLengthFrames, highlightFrames, jumpcutFrames, outputFrame, type Props, type Timeline } from "./timeline";
|
|
10
|
+
|
|
11
|
+
// Length and fps come from the measured timeline, never from constants; the frame is the
|
|
12
|
+
// source's probed size unless render.py was given another shape (--aspect).
|
|
13
|
+
const metadataFrom =
|
|
14
|
+
(frames: (t: Timeline) => number): CalculateMetadataFunction<Props> =>
|
|
15
|
+
({ props }) => {
|
|
16
|
+
const f = outputFrame(props);
|
|
17
|
+
return { durationInFrames: frames(props.timeline), fps: props.timeline.source.fps, width: f.width, height: f.height };
|
|
18
|
+
};
|
|
19
|
+
|
|
20
|
+
const defaultProps: Props = { timeline: SAMPLE_TIMELINE, options: {}, frame: null, font: null };
|
|
21
|
+
const base = { durationInFrames: 240, fps: 30, width: 1280, height: 720, defaultProps };
|
|
22
|
+
|
|
23
|
+
export const RemotionRoot: React.FC = () => (
|
|
24
|
+
<>
|
|
25
|
+
<Composition id="Captioned" component={Captioned} {...base} calculateMetadata={metadataFrom(fullLengthFrames)} />
|
|
26
|
+
<Composition id="Jumpcut" component={Jumpcut} {...base} calculateMetadata={metadataFrom(jumpcutFrames)} />
|
|
27
|
+
<Composition id="PeakPulse" component={PeakPulse} {...base} calculateMetadata={metadataFrom(fullLengthFrames)} />
|
|
28
|
+
<Composition id="Titled" component={Titled} {...base} calculateMetadata={metadataFrom(fullLengthFrames)} />
|
|
29
|
+
<Composition id="Highlights" component={Highlights} {...base} calculateMetadata={metadataFrom(highlightFrames)} />
|
|
30
|
+
<Composition id="BeatMontage" component={BeatMontage} {...base} calculateMetadata={metadataFrom(fullLengthFrames)} />
|
|
31
|
+
</>
|
|
32
|
+
);
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import React from "react";
|
|
2
|
+
import { AbsoluteFill, Audio, Sequence, interpolate, staticFile, useCurrentFrame, useVideoConfig } from "remotion";
|
|
3
|
+
import { SourceVideo } from "../lib/SourceVideo";
|
|
4
|
+
import { Props, beatTimes, highlightRanges, outputFrame, resolveOptions, secToFrames } from "../timeline";
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* BeatMontage: the source's audio plays straight through, unbroken, while the picture cuts on the
|
|
8
|
+
* beat grid ffmpeg-skill measured (every options.beatsPerCut beats), cycling through the measured
|
|
9
|
+
* scenes -- or the highlights, when analyze.py ranked some. No beat grid (or not confident): it cuts
|
|
10
|
+
* on scene changes only, never on invented beats.
|
|
11
|
+
*/
|
|
12
|
+
export const BeatMontage: React.FC<Props> = (props) => {
|
|
13
|
+
const { timeline, options } = props;
|
|
14
|
+
const o = resolveOptions(options);
|
|
15
|
+
const fit = outputFrame(props).fit;
|
|
16
|
+
const { fps, durationInFrames } = useVideoConfig();
|
|
17
|
+
const beats = beatTimes(timeline);
|
|
18
|
+
const step = Math.max(1, Math.round(o.beatsPerCut));
|
|
19
|
+
// Cut points (output frames): every Nth measured beat, else the measured scene starts.
|
|
20
|
+
const cutTimes = beats.length > 0 ? beats.filter((_, i) => i % step === 0) : timeline.scenes.map((s) => s.start);
|
|
21
|
+
const cuts = Array.from(new Set([0, ...cutTimes.map((t) => secToFrames(t, fps))]))
|
|
22
|
+
.filter((f) => f >= 0 && f < durationInFrames)
|
|
23
|
+
.sort((a, b) => a - b);
|
|
24
|
+
// Picture pool: highlights if ranked, else scenes (each a [start, end] range of the source).
|
|
25
|
+
const pool =
|
|
26
|
+
timeline.highlights && timeline.highlights.length > 0
|
|
27
|
+
? highlightRanges(timeline)
|
|
28
|
+
: timeline.scenes.map((s) => [s.start, s.end] as [number, number]);
|
|
29
|
+
return (
|
|
30
|
+
<AbsoluteFill style={{ backgroundColor: "black" }}>
|
|
31
|
+
{cuts.map((from, i) => {
|
|
32
|
+
const to = i + 1 < cuts.length ? cuts[i + 1] : durationInFrames;
|
|
33
|
+
const len = Math.max(1, to - from);
|
|
34
|
+
const [ps, pe] = pool[i % pool.length];
|
|
35
|
+
const poolLen = Math.max(1, secToFrames(pe, fps) - secToFrames(ps, fps));
|
|
36
|
+
// Each visit to a range moves further into it; the shot stays inside the range when it fits
|
|
37
|
+
// (a range shorter than the shot starts at its own beginning).
|
|
38
|
+
const room = poolLen - len;
|
|
39
|
+
const start = secToFrames(ps, fps) + (room > 0 ? (Math.floor(i / pool.length) * len) % (room + 1) : 0);
|
|
40
|
+
const src = { ...timeline.source, has_audio: false };
|
|
41
|
+
return (
|
|
42
|
+
<Sequence key={i} from={from} durationInFrames={len} name={`shot ${i + 1}`}>
|
|
43
|
+
<SourceVideo source={src} fit={fit} trimBefore={start} trimAfter={start + len} />
|
|
44
|
+
{i > 0 ? <BeatFlash accent={o.accent} /> : null}
|
|
45
|
+
</Sequence>
|
|
46
|
+
);
|
|
47
|
+
})}
|
|
48
|
+
{timeline.source.src && timeline.source.has_audio ? <Audio src={staticFile(timeline.source.src)} /> : null}
|
|
49
|
+
</AbsoluteFill>
|
|
50
|
+
);
|
|
51
|
+
};
|
|
52
|
+
|
|
53
|
+
const BeatFlash: React.FC<{ accent: string }> = ({ accent }) => {
|
|
54
|
+
const frame = useCurrentFrame();
|
|
55
|
+
const { fps, width, height } = useVideoConfig();
|
|
56
|
+
const a = interpolate(frame, [0, fps * 0.15], [1, 0], { extrapolateRight: "clamp" });
|
|
57
|
+
if (a <= 0) return null;
|
|
58
|
+
const glow = Math.round(Math.min(width, height) * 0.05 * a);
|
|
59
|
+
return <AbsoluteFill style={{ boxShadow: `inset 0 0 ${glow * 2}px ${glow}px ${accent}`, opacity: a }} />;
|
|
60
|
+
};
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
import React from "react";
|
|
2
|
+
import { AbsoluteFill, Sequence, interpolate, spring, useCurrentFrame, useVideoConfig } from "remotion";
|
|
3
|
+
import { SourceVideo } from "../lib/SourceVideo";
|
|
4
|
+
import { useStagedFont } from "../lib/useStagedFont";
|
|
5
|
+
import { Props, fontStack, outputFrame, resolveOptions, secToFrames, type Options } from "../timeline";
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Captioned: the source, full length, with each measured caption cue popping in on its own
|
|
9
|
+
* timing. Cue text is drawn exactly as written in the caption file.
|
|
10
|
+
*/
|
|
11
|
+
export const Captioned: React.FC<Props> = (props) => {
|
|
12
|
+
const { timeline, options, font, overlay } = props;
|
|
13
|
+
useStagedFont(font);
|
|
14
|
+
const o = resolveOptions(options);
|
|
15
|
+
const family = fontStack(o, font);
|
|
16
|
+
const { fps } = useVideoConfig();
|
|
17
|
+
return (
|
|
18
|
+
<AbsoluteFill style={{ backgroundColor: overlay ? "transparent" : "black" }}>
|
|
19
|
+
{overlay ? null : <SourceVideo source={timeline.source} fit={outputFrame(props).fit} />}
|
|
20
|
+
{timeline.captions.map((c, i) => {
|
|
21
|
+
const from = secToFrames(c.start, fps);
|
|
22
|
+
const dur = Math.max(1, secToFrames(c.end, fps) - from);
|
|
23
|
+
return (
|
|
24
|
+
<Sequence key={i} from={from} durationInFrames={dur} name={`cue ${i + 1}`} layout="none">
|
|
25
|
+
<CaptionCard text={c.text} durationInFrames={dur} o={o} fontFamily={family} />
|
|
26
|
+
</Sequence>
|
|
27
|
+
);
|
|
28
|
+
})}
|
|
29
|
+
</AbsoluteFill>
|
|
30
|
+
);
|
|
31
|
+
};
|
|
32
|
+
|
|
33
|
+
/** Bottom margin: the option if set, else clear of Reels/TikTok UI on portrait frames. */
|
|
34
|
+
export const captionMarginPx = (o: Options, width: number, height: number): number =>
|
|
35
|
+
height * (o.captionMargin ?? (height > width ? 0.2 : 0.08));
|
|
36
|
+
|
|
37
|
+
export const CaptionCard: React.FC<{ text: string; durationInFrames: number; o: Options; fontFamily: string }> = ({
|
|
38
|
+
text,
|
|
39
|
+
durationInFrames,
|
|
40
|
+
o,
|
|
41
|
+
fontFamily,
|
|
42
|
+
}) => {
|
|
43
|
+
const frame = useCurrentFrame();
|
|
44
|
+
const { fps, height, width } = useVideoConfig();
|
|
45
|
+
const enter = spring({ frame, fps, config: { damping: 14, stiffness: 180, mass: 0.6 } });
|
|
46
|
+
const fadeFrames = Math.min(6, Math.floor(durationInFrames / 3));
|
|
47
|
+
const exit =
|
|
48
|
+
fadeFrames > 0
|
|
49
|
+
? interpolate(frame, [durationInFrames - fadeFrames, durationInFrames], [1, 0], {
|
|
50
|
+
extrapolateLeft: "clamp",
|
|
51
|
+
extrapolateRight: "clamp",
|
|
52
|
+
})
|
|
53
|
+
: 1;
|
|
54
|
+
const size = Math.round(Math.min(width, height) * o.captionSize);
|
|
55
|
+
const lang = /[\u3040-\u30ff]/.test(text)
|
|
56
|
+
? "ja"
|
|
57
|
+
: /[\uac00-\ud7af]/.test(text)
|
|
58
|
+
? "ko"
|
|
59
|
+
: /[\u3400-\u9fff]/.test(text)
|
|
60
|
+
? "ja"
|
|
61
|
+
: undefined;
|
|
62
|
+
const cjk = lang !== undefined;
|
|
63
|
+
return (
|
|
64
|
+
<AbsoluteFill
|
|
65
|
+
style={{ justifyContent: "flex-end", alignItems: "center", paddingBottom: captionMarginPx(o, width, height) }}
|
|
66
|
+
>
|
|
67
|
+
<div
|
|
68
|
+
lang={lang}
|
|
69
|
+
style={{
|
|
70
|
+
maxWidth: width * 0.86,
|
|
71
|
+
padding: `${size * 0.28}px ${size * 0.6}px`,
|
|
72
|
+
borderRadius: size * 0.35,
|
|
73
|
+
background: "rgba(0,0,0,0.62)",
|
|
74
|
+
borderBottom: `${Math.max(2, Math.round(size * 0.08))}px solid ${o.accent}`,
|
|
75
|
+
color: o.textColor,
|
|
76
|
+
fontFamily,
|
|
77
|
+
fontWeight: 700,
|
|
78
|
+
fontSize: size,
|
|
79
|
+
lineHeight: 1.3,
|
|
80
|
+
textAlign: "center",
|
|
81
|
+
whiteSpace: "pre-wrap",
|
|
82
|
+
// Japanese: break between phrases (文節), not inside a word; balance the lines so a
|
|
83
|
+
// cue never ends with one orphaned character. Latin: normal word breaks.
|
|
84
|
+
wordBreak: (cjk ? "auto-phrase" : "normal") as React.CSSProperties["wordBreak"],
|
|
85
|
+
textWrap: "balance",
|
|
86
|
+
overflowWrap: "break-word",
|
|
87
|
+
opacity: Math.min(enter, exit),
|
|
88
|
+
transform: `translateY(${(1 - enter) * size * 0.6}px) scale(${0.92 + 0.08 * enter})`,
|
|
89
|
+
}}
|
|
90
|
+
>
|
|
91
|
+
{text}
|
|
92
|
+
</div>
|
|
93
|
+
</AbsoluteFill>
|
|
94
|
+
);
|
|
95
|
+
};
|