Skip to content
This repository was archived by the owner on Nov 15, 2026. It is now read-only.
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 10 additions & 4 deletions claude/skills/visual/motion-reel/references/pipeline.md
Original file line number Diff line number Diff line change
Expand Up @@ -64,14 +64,20 @@ renders. Delete `frames/` after encoding when space is tight.
alone sample eight frames a scene, and an error between two samples passes them.
- `render.py` exits non-zero on any page error or console error (a missing
`fonts.css` is a 404, not a warning) and on any missing frame.
- `render.py frames` renders one sample frame, then refuses before it deletes or writes
any frame when the filesystem cannot hold every frame (the larger of 1.25 bytes a
pixel and twice the sample) with 1 GiB to spare; the message names the size it needs.
- `encode.py` writes each video to `NAME-master.part.mp4` and `NAME.part.mp4`, and
renames both over the final names only after ffmpeg exits 0 and the frame counts
pass; a failed encode removes the partial files and keeps the previous videos.
- `encode.py` decodes both outputs and compares their frame counts with `cues.json`,
and fails when even the last CRF cannot bring the share copy under `--max-mb`.
- `synth.py` exits non-zero when a registered silence window is louder than −100 dB.
- No script writes through a symbolic link or out of the project. A generated file is
written beside its destination and renamed over it (`scripts/project_files.py`); the
videos are removed and written anew, and the frames go into a `frames/` made fresh for
the run. A destination that is a link is refused, and so is an output directory
outside the project unless it is named with `review --out`. `synth.py` loads
written beside its destination and renamed over it (`scripts/project_files.py`), the
videos included, and the frames go into a `frames/` made fresh for the run. A
destination that is a link is refused, and so is an output directory outside the
project unless it is named with `review --out`. `synth.py` loads
`score.py` without writing its bytecode.

## Encoding
Expand Down
75 changes: 50 additions & 25 deletions claude/skills/visual/motion-reel/scripts/encode.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,12 @@
with --at, one full-size frame of it instead, to read small type 1:1

Both outputs are decoded again and their frame count is compared with cues.json;
a mismatch exits non-zero. ffmpeg is imageio-ffmpeg's own build, never one from
PATH: an older system ffmpeg lacks options this script uses.
a mismatch exits non-zero. Each output is encoded to NAME*.part.mp4 and renamed
over its final name only after ffmpeg and the frame counts pass for both. A failed
encode or a mismatch keeps the previous videos and leaves no partial file under a
final name. When the share copy stays over --max-mb, both videos are complete:
they replace the previous ones, and the run then exits non-zero. ffmpeg is imageio-ffmpeg's own build, never
one from PATH: an older system ffmpeg lacks options this script uses.
"""

import argparse
Expand Down Expand Up @@ -46,6 +50,12 @@ def run(args):
)


def part_of(out):
"""The partial file beside `out`: x.mp4 -> x.part.mp4. The suffix stays last, so
ffmpeg still picks the format from the name."""
return out.with_name(out.stem + ".part" + out.suffix)


def fresh(out, args, hint=""):
"""ffmpeg into a new file, which then replaces `out`. ffmpeg can exit 0 having
written nothing (a seek past the end), and an old image must never pass for one of
Expand All @@ -55,7 +65,7 @@ def fresh(out, args, hint=""):
raise SystemExit(
f"{out} is a symbolic link: remove it, outputs are written as files"
)
part = out.with_name(out.stem + ".part" + out.suffix)
part = part_of(out)
part.unlink(missing_ok=True)
try:
run([*args, "-update", "1", str(part)])
Expand Down Expand Up @@ -135,28 +145,43 @@ def one(out, crf, abr):
]
)

# new files, never written in place through a hard link to one elsewhere; only now,
# after the name, link and frame-count checks, so an encode refused there keeps the
# old videos (an input ffmpeg itself rejects, such as a broken audio.wav, does not)
for out in (master, share):
out.unlink(missing_ok=True)
one(master, 14, "320k")
for crf in CRF_LADDER:
if crf == 14:
shutil.copyfile(master, share)
else:
one(share, crf, "256k")
size = share.stat().st_size / 2**20
print(f" crf {crf}: {size:.1f} MiB")
if size <= max_mb:
break
for out in (master, share):
n = decoded_frames(out)
print(
f"{out.name}: {out.stat().st_size / 2**20:.1f} MiB, {n} frames decoded | {probe(out)}"
)
if n != expected:
raise SystemExit(f"{out.name} decodes to {n} frames, expected {expected}")
# Both videos are encoded to NAME-master.part.mp4 and NAME.part.mp4, new files
# beside the final names, never written in place through a hard link. They are
# decoded and checked there, and renamed over the final names only when both pass.
# A failed encode (a broken audio.wav, a full disk) removes the partial files and
# leaves the previous videos as they were.
parts = {out: part_of(out) for out in (master, share)}
try:
for part in parts.values():
part.unlink(missing_ok=True)
one(parts[master], 14, "320k")
for crf in CRF_LADDER:
if crf == 14:
shutil.copyfile(parts[master], parts[share])
else:
one(parts[share], crf, "256k")
size = parts[share].stat().st_size / 2**20
print(f" crf {crf}: {size:.1f} MiB")
if size <= max_mb:
break
for out, part in parts.items():
n = decoded_frames(part)
print(
f"{out.name}: {part.stat().st_size / 2**20:.1f} MiB, {n} frames decoded | {probe(part)}"
)
if n != expected:
raise SystemExit(
f"{out.name} decodes to {n} frames, expected {expected}: previous videos kept"
)
for out, part in parts.items():
os.replace(part, out)
except subprocess.CalledProcessError as e:
raise SystemExit(
f"ffmpeg exited {e.returncode}: no video written, previous videos kept"
) from e
finally:
for part in parts.values():
part.unlink(missing_ok=True)
if (
size > max_mb
): # the capped copy is the promise of this step: missing it is a failure
Expand Down
45 changes: 44 additions & 1 deletion claude/skills/visual/motion-reel/scripts/render.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@
from this skill, so a project never carries a copy of it. Chrome comes from
$MOTION_REEL_CHROME, a system install, or Playwright's own Chromium (installed on
first use). Exits non-zero when the page reports an error or a frame is missing.
`frames` renders one sample frame first and refuses, before it writes any frame,
when the filesystem cannot hold every frame with 1 GiB to spare.
"""

import argparse
Expand All @@ -41,6 +43,12 @@
"/Applications/Chromium.app/Contents/MacOS/Chromium",
]
SHEET_FRACTIONS = [0.06, 0.18, 0.31, 0.44, 0.57, 0.7, 0.83, 0.96]
# Disk budget for `frames`. Measured PNG frames run 1.3-2.3 MB at 1920x1080, at most
# 1.1 bytes a pixel, so the floor is 1.25 bytes a pixel. A sample frame often
# compresses better than a busy one, so its size counts twice.
BYTES_PER_PIXEL_FLOOR = 1.25
SAMPLE_FACTOR = 2
FREE_MARGIN = 2**30 # leave 1 GiB free after the frames are written


class Handler(SimpleHTTPRequestHandler):
Expand Down Expand Up @@ -207,14 +215,49 @@ def run(page):
print("wrote", path)


def gib(n):
return f"{n / 2**30:.1f} GiB"


def frames_bytes(info, sample_bytes):
"""The bytes all frames need: the larger of the pixel floor and the sample frame
times SAMPLE_FACTOR, for every frame."""
per_frame = max(
BYTES_PER_PIXEL_FLOOR * info["w"] * info["h"], SAMPLE_FACTOR * sample_bytes
)
return int(per_frame * info["frames"])


def check_space(out, project, need):
"""Refuse a render the filesystem under `out` cannot hold with FREE_MARGIN left.
It runs before the old frames are deleted, so a refused run keeps them. Their
bytes count as free, because the render deletes them first."""
old = out.is_dir()
free = shutil.disk_usage(out if old else project).free
if old:
free += sum(p.stat().st_size for p in out.iterdir() if p.is_file())
if need + FREE_MARGIN > free:
raise SystemExit(
f"frames need about {gib(need)} plus a {gib(FREE_MARGIN)} margin, "
f"but {out} has {gib(free)} free: free space or render elsewhere"
)


def cmd_frames(project, a):
info = with_page(project, lambda page: page.evaluate("window.INFO"))
def sample(page):
info = page.evaluate("window.INFO")
mid = info["frames"] // 2 # frame 0 is often black and compresses to nothing
data = page.evaluate("([f, s]) => renderFrame(f, s)", [mid, a.sub])
return info, len(png(data))

info, sample_bytes = with_page(project, sample)
frames = list(range(info["frames"]))
out = project / "frames"
if out.is_symlink():
raise SystemExit(
f"{out} is a symbolic link: frames render into the project itself"
)
check_space(out, project, frames_bytes(info, sample_bytes))
if out.exists(): # every frame from this reel.js, never a mix of two versions
shutil.rmtree(out)
out.mkdir()
Expand Down
137 changes: 137 additions & 0 deletions claude/skills/visual/motion-reel/scripts/test_motion_reel.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,137 @@
"""Offline tests for the disk guards in render.py and encode.py (TOM-1222).
No Chrome and no real ffmpeg: the page and ffmpeg are stubbed.
Run: python -m pytest test_motion_reel.py"""

import argparse
import json
import sys
from collections import namedtuple
from pathlib import Path

import pytest

sys.path.insert(0, str(Path(__file__).resolve().parent))

import encode
import render

Usage = namedtuple("Usage", "total used free")

INFO = {"w": 1920, "h": 1080, "fps": 60, "dur": 56.25, "frames": 3375, "scenes": []}


class Reached(Exception):
"""The render went past the disk check."""


def frames_args(project):
return argparse.Namespace(sub=8, workers=2, project=project)


def stub_render(monkeypatch, free):
monkeypatch.setattr(render, "with_page", lambda project, fn: (INFO, 2_000_000))
monkeypatch.setattr(render.shutil, "disk_usage", lambda p: Usage(0, 0, free))

def serve(project):
raise Reached

monkeypatch.setattr(render, "serve", serve)


def test_frames_refuses_when_disk_too_small(tmp_path, monkeypatch):
stub_render(monkeypatch, free=2**30)
old = tmp_path / "frames" / "f_00000.png"
old.parent.mkdir()
old.write_bytes(b"old frame")
with pytest.raises(SystemExit) as e:
render.cmd_frames(tmp_path, frames_args(tmp_path))
msg = str(e.value)
# 2 x 2.0 MB sample > 1.25 B/px floor: 4,000,000 x 3,375 frames = 12.6 GiB
assert "12.6 GiB" in msg, msg
assert "1.0 GiB free" in msg, msg
# refused before the render started, and before the old frames were deleted
assert [p.name for p in old.parent.iterdir()] == ["f_00000.png"]


def test_frames_proceeds_when_disk_holds_them(tmp_path, monkeypatch):
stub_render(monkeypatch, free=20 * 2**30)
with pytest.raises(Reached):
render.cmd_frames(tmp_path, frames_args(tmp_path))


def test_frames_bytes_uses_pixel_floor_for_a_blank_sample():
assert render.frames_bytes(INFO, 1000) == int(1.25 * 1920 * 1080 * 3375)


STUB = """#!/usr/bin/env python3
import os, sys
args = sys.argv[1:]
if "null" in args:
sys.stderr.write("frame= %s fps=0\\n" % os.environ.get("STUB_FRAMES", "3"))
sys.exit(0)
if args[-2] == "-i": # probe: input only, no output
sys.stderr.write("Duration: 00:00:00.05\\n")
sys.exit(1)
with open(args[-1], "wb") as f:
f.write(b"NEW" * 100)
sys.exit(1 if os.environ.get("STUB_FAIL") else 0)
"""


@pytest.fixture
def project(tmp_path, monkeypatch):
stub = tmp_path / "ffmpeg"
stub.write_text(STUB)
stub.chmod(0o755)
monkeypatch.setattr(encode, "ffmpeg", lambda: str(stub))
proj = tmp_path / "reel-project"
(proj / "frames").mkdir(parents=True)
for f in range(3):
(proj / "frames" / f"f_{f:05d}.png").write_bytes(b"png")
(proj / "cues.json").write_text(json.dumps({"fps": 60, "frames": 3}))
return proj.resolve()


def test_failed_encode_keeps_previous_videos(project, monkeypatch):
(project / "reel-master.mp4").write_bytes(b"OLD-MASTER")
(project / "reel.mp4").write_bytes(b"OLD-SHARE")
monkeypatch.setenv("STUB_FAIL", "1")
with pytest.raises(SystemExit) as e:
encode.encode(project, "reel", 29.0)
assert "ffmpeg exited 1" in str(e.value)
assert (project / "reel-master.mp4").read_bytes() == b"OLD-MASTER"
assert (project / "reel.mp4").read_bytes() == b"OLD-SHARE"
assert list(project.glob("*.part.*")) == []


def test_frame_count_mismatch_keeps_previous_videos(project, monkeypatch):
(project / "reel-master.mp4").write_bytes(b"OLD-MASTER")
(project / "reel.mp4").write_bytes(b"OLD-SHARE")
monkeypatch.delenv("STUB_FAIL", raising=False)
monkeypatch.setenv("STUB_FRAMES", "2")
with pytest.raises(SystemExit) as e:
encode.encode(project, "reel", 29.0)
assert "decodes to 2 frames, expected 3" in str(e.value)
assert (project / "reel-master.mp4").read_bytes() == b"OLD-MASTER"
assert (project / "reel.mp4").read_bytes() == b"OLD-SHARE"
assert list(project.glob("*.part.*")) == []


def test_failed_first_encode_leaves_no_final_file(project, monkeypatch):
monkeypatch.setenv("STUB_FAIL", "1")
with pytest.raises(SystemExit):
encode.encode(project, "reel", 29.0)
assert sorted(p.name for p in project.iterdir()) == ["cues.json", "frames"]


def test_normal_encode_writes_the_same_final_names(project, monkeypatch):
monkeypatch.delenv("STUB_FAIL", raising=False)
(project / "reel-master.mp4").write_bytes(b"OLD-MASTER")
encode.encode(project, "reel", 29.0)
assert (project / "reel-master.mp4").read_bytes() == b"NEW" * 100
assert (project / "reel.mp4").read_bytes() == b"NEW" * 100
assert list(project.glob("*.part.*")) == []


if __name__ == "__main__":
sys.exit(pytest.main([__file__, "-v"]))
Loading