Branchwell

Jotley / website / scripts / video-refresh / render-delivery.py

1#!/usr/bin/env python3
2"""Export the isolated website/social refresh; never upload or modify production."""
3import argparse
4import datetime
5import hashlib
6import json
7import os
8from pathlib import Path
9import shutil
10import subprocess
11import time
12
13ROOT = Path(__file__).resolve().parents[2]
14BASE = ROOT / "output/video-refresh-20261023/workspace"
15OUT = Path(os.environ.get("JOTLEY_DELIVERY_ROOT", str(BASE / "delivery")))
16ARCHIVE = Path("/Volumes/Music/Jotley/Jotley-2.0-App-Store-Videos/refresh-website-social-20261023")
17
18
19def main():
20 parser = argparse.ArgumentParser(description=__doc__)
21 parser.add_argument("group", choices=["remotion", "hyperframes", "portrait"])
22 args = parser.parse_args()
23 if not Path("/Volumes/Music").is_mount() or not ARCHIVE.is_dir():
24 parser.error("Music must be mounted; render temporaries are kept off the internal disk")
25 logdir = OUT / "render-jobs"
26 logdir.mkdir(parents=True, exist_ok=True)
27 env = dict(os.environ)
28 temporary = ARCHIVE / "render-tmp" / args.group
29 temporary.mkdir(parents=True, exist_ok=True)
30 env["TMPDIR"] = str(temporary) + "/"
31 jobs = []
32
33 def save():
34 (logdir / f"{args.group}.json").write_text(json.dumps(jobs, indent=2) + "\n")
35
36 def run(name, command, cwd=BASE):
37 log = logdir / (name + ".log")
38 entry = {"name": name, "command": command, "cwd": str(cwd), "log": str(log),
39 "state": "running", "started": datetime.datetime.now(datetime.timezone.utc).isoformat()}
40 jobs.append(entry)
41 save()
42 print(json.dumps({"started": name, "log": str(log)}), flush=True)
43 start = time.monotonic()
44 with log.open("w") as handle:
45 result = subprocess.run(command, cwd=cwd, env=env, stdout=handle, stderr=subprocess.STDOUT)
46 entry.update(state="complete" if result.returncode == 0 else "failed", exit_code=result.returncode,
47 elapsed_seconds=round(time.monotonic() - start, 2))
48 save()
49 print(json.dumps({"finished": name, "state": entry["state"], "seconds": entry["elapsed_seconds"]}), flush=True)
50 if result.returncode:
51 raise SystemExit(result.returncode)
52
53 def verify(path, width, height, duration):
54 probe = json.loads(subprocess.check_output(["ffprobe", "-v", "error", "-show_streams", "-show_format", "-of", "json", str(path)]))
55 video = next(s for s in probe["streams"] if s["codec_type"] == "video")
56 assert (video["width"], video["height"]) == (width, height), path
57 assert video["avg_frame_rate"] == "60/1", (path, video["avg_frame_rate"])
58 assert abs(float(probe["format"]["duration"]) - duration) < .15, path
59 assert any(s["codec_type"] == "audio" for s in probe["streams"]), path
60 run(path.stem + "-decode", ["ffmpeg", "-v", "error", "-i", str(path), "-f", "null", "-"])
61 checksum = hashlib.file_digest(path.open("rb"), "sha256").hexdigest()
62 probe.update(full_decode=True, sha256=checksum)
63 path.with_suffix(".verification.json").write_text(json.dumps(probe, indent=2) + "\n")
64
65 def renditions(master, prefix, folder, duration):
66 for label, width, height, crf, rate in [("1080p", 1920, 1080, 16, "16M"), ("720p", 1280, 720, 18, "6M")]:
67 dest = folder / f"{prefix}-{label}.mp4"
68 run(dest.stem, ["ffmpeg", "-v", "error", "-y", "-i", str(master), "-map", "0:v:0", "-map", "0:a:0",
69 "-vf", f"scale={width}:{height}:flags=lanczos,setsar=1,format=yuv420p", "-r", "60",
70 "-c:v", "libx264", "-preset", "medium", "-crf", str(crf), "-maxrate", rate,
71 "-bufsize", "32M" if label == "1080p" else "12M", "-g", "120", "-c:a", "copy",
72 "-movflags", "+faststart", str(dest)])
73 verify(dest, width, height, duration)
74
75 films = OUT / "website/films"
76 social = OUT / "social"
77 films.mkdir(parents=True, exist_ok=True)
78 social.mkdir(parents=True, exist_ok=True)
79 if args.group == "remotion":
80 version = os.environ.get("JOTLEY_MARKETING_VERSION", "v9")
81 assert version in {"v9", "v10", "v11"}
82 master = films / f"jotley-marketing-{version}-2160p.mp4"
83 run(master.stem, ["npx", "remotion", "render", f"Jotley-Website-Marketing-{version}-4K", str(master),
84 "--codec=h264", "--crf=14", "--x264-preset=medium", "--concurrency=3", "--image-format=png"], BASE / "remotion")
85 verify(master, 3840, 2160, 5554 / 60)
86 renditions(master, f"jotley-marketing-{version}", films, 5554 / 60)
87 portrait = social / f"jotley-marketing-{version}-portrait-1080p.mp4"
88 run(portrait.stem, ["npx", "remotion", "render", f"Jotley-Social-Marketing-{version}-Portrait", str(portrait),
89 "--codec=h264", "--crf=14", "--x264-preset=medium", "--concurrency=3", "--image-format=png"], BASE / "remotion")
90 verify(portrait, 1080, 1920, 5554 / 60)
91 elif args.group == "hyperframes":
92 items = [("tutorial-iphone-16x9", "jotley-tutorial-iphone-v4", 84.333),
93 ("tutorial-ipad-16x9", "jotley-tutorial-ipad-v5", 71.528),
94 ("tutorial-mac-16x9", "jotley-tutorial-mac-v4", 120.182),
95 ("social-16x9", "jotley-social-ui-20261023", 32.25),
96 ("social-9x16", "jotley-social-ui-20261023-portrait", 32.25)]
97 for project, prefix, duration in items:
98 vertical = project == "social-9x16"
99 folder = social if project.startswith("social") else films
100 master = folder / f"{prefix}-{'1080p' if vertical else '2160p'}.mp4"
101 command = ["npx", "hyperframes", "render", "--output", str(master), "--quality", "delivery", "--crf", "14",
102 "--fps", "60", "--workers", "2", "--video-frame-format", "png", "--strict", "--no-best-effort", "--sdr",
103 "--frames-cache-dir", str(ARCHIVE / "render-source-cache")]
104 if not vertical:
105 command += ["--resolution", "4k"]
106 run(master.stem, command, BASE / "composition" / project)
107 verify(master, 1080 if vertical else 3840, 1920 if vertical else 2160, duration)
108 if not vertical:
109 renditions(master, prefix, folder, duration)
110 else:
111 run("portrait-iphone-ipad", ["python3", str(BASE / "portrait/build_portrait_jotley.py"), "iphone", "ipad"])
112 run("portrait-mac", ["python3", str(BASE / "portrait/build_portrait_jotley_mac.py")])
113 destination = social / "portrait-tutorials"
114 shutil.copytree(BASE / "final-SOCIAL-portrait", destination, dirs_exist_ok=True)
115 for device, duration in [("iPhone", 84.333), ("iPad", 71.528), ("Mac", 120.182)]:
116 verify(destination / f"Jotley-{device}-Portrait-Tutorial-1080x1920-60fps.mp4", 1080, 1920, duration)
117 print(json.dumps({"group": args.group, "state": "complete"}), flush=True)
118
119
120if __name__ == "__main__":
121 main()