Skip to content

Generate clean 2D game sprites & animation atlases — component-row pipeline: state rows, alpha cleanup, frame extraction, runtime atlases. Codex/Claude skill.

feat(video): RIFE runs where the engine runs — the Apple GPU on a Mac, llvmpipe in a Linux container

Soohong Kimf0d14356e63d
diff --git a/docs/README.md b/docs/README.md
index 36010f4..9c4532e 100644
--- a/docs/README.md
+++ b/docs/README.md
@@ -77,6 +77,7 @@ grouping is derived from `sprite_gen/_modules.py`, the one taxonomy table.
| [video.md](video.md) | `sprite-gen video` / `video-extend` / `video-edit`: stills and clips to mp4 through Grok Imagine (image-to-video, last-frame pin, references, extension, editing) with the user's own credential |
| [video-pipeline.md](video-pipeline.md) | Pipeline B engine contract: state canvas, keyed frames, true-period and one-shot cycles, strip/GIF/WebP, the batch |
| [loop-review.md](loop-review.md) | Automatic loop decisions, ambiguous gait review, visual evidence and explicit cut/alignment overrides |
+| [loop-repair.md](loop-repair.md) | RIFE (where it runs, cost, licences), jump-frame repair, the jolt index and its gate, one cycle length per direction set |
| [frame-interpolation.md](frame-interpolation.md) | Generative in-betweens for sprite frames, recorded as a take |
| [seamless-video-loop.md](seamless-video-loop.md) | Making a non-looping ambient clip loop forever (RIFE seam bridge) — a different job from pipeline B |
diff --git a/docs/loop-repair.md b/docs/loop-repair.md
new file mode 100644
index 0000000..3fd3246
--- /dev/null
+++ b/docs/loop-repair.md
@@ -0,0 +1,102 @@
+# Loop repair — RIFE in-betweens for jump frames, the jolt index, one cycle per set
+
+> Owns: Where RIFE runs and what it costs, jump-frame repair in `video-loop`, the jolt index and its gate, cycle alignment across a direction set · Index: [docs/README.md](README.md)
+
+A walk loop cut from a generated clip can look right in every still and still hitch when it
+plays: the video model redraws thin hair a little differently every frame, and now and then
+a ponytail lands somewhere it was not one frame earlier. This doc owns the three repairs
+`video-loop` and `video-set` make for that, all built on one optical-flow interpolator.
+
+Not to be confused with [frame-interpolation.md](frame-interpolation.md) (a *generative*
+in-between drawn by an image model, where RIFE was retired because it smears a changed
+*appearance*) or [seamless-video-loop.md](seamless-video-loop.md) (RIFE bridging an ambient
+clip's seam). Here RIFE only ever makes a frame between two neighbours of the *same* walk,
+where the appearance does not change and only the motion does — the case optical flow is for.
+
+## 1. RIFE — what runs, where, and what it costs
+
+### What
+
+[rife-ncnn-vulkan](https://github.com/nihui/rife-ncnn-vulkan) release **20221029**, model
+**`rife-v4.6`** (shipped inside the release zip). The engine calls the binary as an external
+tool, like `ffmpeg` and `img2webp`; nothing is vendored into the package.
+
+| Release zip | SHA-256 (measured 2026-10-03) |
+|---|---|
+| `rife-ncnn-vulkan-20221029-ubuntu.zip` | `1e2c7ee7fa7daa326542d50622f0afedc80cf6f1858bda411d16385ffa5cdf68` |
+| `rife-ncnn-vulkan-20221029-macos.zip` | `4a63a1f3c9c715773c57d2ee51df1b315ed20cd6c63103e45c483ecc4400b595` |
+
+The engine finds it by `SPRITE_GEN_RIFE` (the binary's path) or `rife-ncnn-vulkan` on `PATH`,
+and the model by `SPRITE_GEN_RIFE_MODEL` or `rife-v4.6/` next to the binary. A loop that needs
+a repair and finds no RIFE stops with the install line; it is never cut unrepaired in silence
+(`--repair off` is the explicit way to skip it).
+
+RIFE reads three colour channels and no alpha. A frame is therefore interpolated as two
+images — its colour premultiplied over black, and its coverage as a grey image — and put back
+together unpremultiplied (`sprite_gen/video/rife.py`). Coverage below 2/255 is dropped, so no
+faint halo is invented around the body.
+
+### Where — measured 2026-10-03
+
+One real pair: two frames of a Lite side walk two apart (545 x 544, premultiplied), the frame
+between them as the truth. Time per RIFE call, wall clock, process start included.
+
+| Where | How | Time per call | Mean abs error vs the true middle frame |
+|---|---|---|---|
+| Local Mac, M4 Max | Apple GPU through MoltenVK (`-g` auto) | 0.33–0.41 s | 3.32 (the frame either side: 7.77) |
+| Local Mac, M4 Max | ncnn CPU path (`-g -1`) | 0.28–0.39 s | **39.3 — wrong output** |
+| Modal, Linux, default reservation (as `run_job`) | Mesa llvmpipe software Vulkan (`-g` auto) | 2.8–3.0 s (first call 6.9 s) | 3.32 |
+| Modal, Linux, `cpu=2` | llvmpipe | 1.6–3.0 s over two runs (first 4.3–7.4 s) | 3.32 |
+| Modal, Linux, `cpu=8` | llvmpipe | 2.7 s (first 6.6 s) | 3.32 |
+| Modal, Linux, `cpu=2` | ncnn CPU path (`-g -1`) | 0.72–0.85 s | **39.3 — wrong output** |
+| Modal, T4 GPU | — | not run: the workspace has no payment method for GPU functions | — |
+
+Read:
+
+- **llvmpipe gives the same frame as the Apple GPU**, to the third decimal of the error. It is
+ the CPU route on Linux. The binary's own CPU path (`-g -1`) is fast and wrong on both
+ platforms with this model; the engine never passes it.
+- The first call in a fresh container compiles llvmpipe's shaders (4–7 s); later calls in the
+ same container do not.
+- More cores barely help (8 cores: 2.7 s against 2.8–3.0 s), so the default reservation is
+ the right size.
+
+### Decision
+
+**RIFE runs where the engine runs.** On a Mac that is the Apple GPU. In the app it is the
+Modal job container itself, on CPU through llvmpipe — no GPU function and no second service:
+
+```
+apt_install("libvulkan1", "mesa-vulkan-drivers") # the Vulkan loader + llvmpipe
+curl -fsSL -o /tmp/rife.zip https://github.com/nihui/rife-ncnn-vulkan/releases/download/20221029/rife-ncnn-vulkan-20221029-ubuntu.zip
+echo '1e2c7ee7fa7daa326542d50622f0afedc80cf6f1858bda411d16385ffa5cdf68 /tmp/rife.zip' | sha256sum -c -
+unzip -q /tmp/rife.zip -d /opt && ln -s /opt/rife-ncnn-vulkan-20221029-ubuntu/rife-ncnn-vulkan /usr/local/bin/
+```
+
+Cost on Modal (prices read from modal.com/pricing on 2026-10-03: CPU $0.0000131 per core per
+second, memory $0.00000222 per GiB per second): one repaired frame is two calls, about 6 s; a
+loop repairs at most three frames, so at most about 20 s of one container — well under a cent.
+Aligning a set's cycles (section 4) makes more frames: about 6 s per frame RIFE makes, so a
+view that needs 20 made frames adds about two minutes on Modal and a few seconds on a Mac.
+That is the reason section 4 keeps every frame that lands on a source frame.
+
+A PyTorch RIFE was not chosen: it would add a framework of hundreds of megabytes to the image
+for the same model, and llvmpipe already gives the GPU's frame.
+
+### Licences
+
+| Part | Licence | Source (read 2026-10-03) |
+|---|---|---|
+| rife-ncnn-vulkan (code, release binaries) | MIT, © 2020 nihui | `LICENSE` in the repository and in the release zip |
+| RIFE (the network) | MIT | github.com/hzwer/ECCV2022-RIFE; the authors add that they "respect the commercial behavior of other developers" |
+| RIFE v4.x weights (Practical-RIFE) | MIT — "The content of these links is under the same MIT license as this project." | github.com/hzwer/Practical-RIFE |
+| ncnn | BSD 3-Clause | github.com/Tencent/ncnn |
+
+sprite-gen ships none of these. A deployment that bakes the release zip into an image ships
+the zip's `LICENSE` with it.
+
+## Related
+
+- [video-pipeline.md](video-pipeline.md) — the pipeline these repairs run inside
+- [loop-review.md](loop-review.md) — the decisions a loop records for review
+- [docs/README.md](README.md) — documentation index
diff --git a/sprite_gen/video/rife.py b/sprite_gen/video/rife.py
new file mode 100644
index 0000000..6bb1a30
--- /dev/null
+++ b/sprite_gen/video/rife.py
@@ -0,0 +1,113 @@
+# SPDX-License-Identifier: Apache-2.0
+"""RIFE in-betweens for RGBA sprite frames, through the external `rife-ncnn-vulkan` binary.
+
+Where it runs, what it costs and why this build: docs/loop-repair.md section 1. RIFE reads
+three colour channels and no alpha, so a frame is interpolated as two images — its colour
+premultiplied over black and its coverage as a grey image — and put back together
+unpremultiplied. Interpolating the straight colour instead would drag the key's black under
+alpha 0 into the edge; interpolating RGBA as RGB would lose the coverage outright.
+
+The binary's own CPU path (`-g -1`) returns a wrong frame with rife-v4.6 on both macOS and
+Linux (measured 2026-10-03: mean error 39 against 3.3 through Vulkan), so it is never passed;
+a machine without a GPU runs the Vulkan path on Mesa's llvmpipe, which gives the GPU's frame.
+
+The interpolator is a plain callable `(a, b, t) -> frame`, so a caller can be handed a stand-in
+(`Interpolate`), and a test needs no binary.
+"""
+
+from __future__ import annotations
+
+import os
+import shutil
+import subprocess
+import tempfile
+from pathlib import Path
+from typing import Callable
+
+from PIL import Image
+
+from sprite_gen._deps import np
+
+BINARY = "rife-ncnn-vulkan"
+MODEL = "rife-v4.6"
+RELEASE = "20221029"
+# Coverage RIFE leaves under this is its own blur, not body: dropped so no halo is invented.
+ALPHA_FLOOR = 2 / 255
+CALL_TIMEOUT_SECONDS = 120
+
+Interpolate = Callable[[Image.Image, Image.Image, float], Image.Image]
+
+INSTALL_HINT = (
+ f"install rife-ncnn-vulkan {RELEASE} (github.com/nihui/rife-ncnn-vulkan/releases/tag/{RELEASE}; "
+ f"on Linux without a GPU also `libvulkan1 mesa-vulkan-drivers`) and put it on PATH or set SPRITE_GEN_RIFE "
+ f"to the binary — the model {MODEL}/ ships beside it (SPRITE_GEN_RIFE_MODEL overrides); see docs/loop-repair.md"
+)
+
+
+class RifeUnavailable(RuntimeError):
+ """No usable RIFE binary or model. The message names what is missing and how to install it."""
+
+
+def locate() -> tuple[Path, Path]:
+ """(binary, model directory), from SPRITE_GEN_RIFE / PATH and SPRITE_GEN_RIFE_MODEL / beside the binary."""
+ named = os.environ.get("SPRITE_GEN_RIFE")
+ found = named or shutil.which(BINARY)
+ if not found:
+ raise RifeUnavailable(f"{BINARY} not found on PATH and SPRITE_GEN_RIFE is not set; {INSTALL_HINT}")
+ binary = Path(found).expanduser()
+ if not binary.is_file() or not os.access(binary, os.X_OK):
+ raise RifeUnavailable(f"{binary} is not an executable file; {INSTALL_HINT}")
+ binary = binary.resolve()
+ model = Path(os.environ.get("SPRITE_GEN_RIFE_MODEL") or binary.parent / MODEL).expanduser()
+ if not (model / "flownet.param").is_file() or not (model / "flownet.bin").is_file():
+ raise RifeUnavailable(f"RIFE model {model} has no flownet.param / flownet.bin; {INSTALL_HINT}")
+ return binary, model
+
+
+def _call(binary: Path, model: Path, a: Image.Image, b: Image.Image, t: float, tmp: Path) -> Image.Image:
+ a.save(tmp / "a.png")
+ b.save(tmp / "b.png")
+ out = tmp / "o.png"
+ out.unlink(missing_ok=True)
+ proc = subprocess.run(
+ [str(binary), "-0", str(tmp / "a.png"), "-1", str(tmp / "b.png"), "-o", str(out), "-s", f"{t:.4f}", "-m", str(model)],
+ capture_output=True, text=True, timeout=CALL_TIMEOUT_SECONDS,
+ )
+ if proc.returncode != 0 or not out.is_file():
+ raise RifeUnavailable(f"{binary.name} failed (exit {proc.returncode}): {(proc.stderr or proc.stdout).strip()[-300:]}")
+ with Image.open(out) as im:
+ return im.convert("RGB")
+
+
+def between(a: Image.Image, b: Image.Image, t: float, *, binary: Path, model: Path, tmp: Path) -> Image.Image:
+ """The RGBA frame at fraction `t` (0..1) of the way from `a` to `b`."""
+ if a.size != b.size:
+ raise ValueError(f"rife: frames differ in size ({a.size} vs {b.size})")
+ fa, fb = (np.asarray(f.convert("RGBA"), dtype=np.float32) / 255.0 for f in (a, b))
+ prem = [Image.fromarray(np.uint8(np.clip(x[..., :3] * x[..., 3:4], 0, 1) * 255 + 0.5), "RGB") for x in (fa, fb)]
+ cov = [Image.fromarray(np.uint8(x[..., 3] * 255 + 0.5), "L").convert("RGB") for x in (fa, fb)]
+ color = np.asarray(_call(binary, model, prem[0], prem[1], t, tmp), dtype=np.float32) / 255.0
+ alpha = np.asarray(_call(binary, model, cov[0], cov[1], t, tmp).convert("L"), dtype=np.float32) / 255.0
+ alpha = np.where(alpha < ALPHA_FLOOR, 0.0, alpha)
+ rgb = np.where(alpha[..., None] > 0, color / np.maximum(alpha[..., None], 1e-6), 0.0)
+ out = np.dstack([np.clip(rgb, 0, 1), alpha])
+ return Image.fromarray(np.uint8(out * 255 + 0.5), "RGBA")
+
+
+class Rife:
+ """A located RIFE as an `Interpolate` callable. Counts the frames it made (`made`)."""
+
+ def __init__(self, binary: Path | None = None, model: Path | None = None):
+ if binary is None or model is None:
+ binary, model = locate()
+ self.binary, self.model = binary, model
+ self.made = 0
+
+ def __call__(self, a: Image.Image, b: Image.Image, t: float) -> Image.Image:
+ with tempfile.TemporaryDirectory(prefix="sprite-gen-rife-") as td:
+ frame = between(a, b, t, binary=self.binary, model=self.model, tmp=Path(td))
+ self.made += 1
+ return frame
+
+ def describe(self) -> dict[str, str]:
+ return {"binary": str(self.binary), "model": self.model.name}
diff --git a/tests/video/test_rife.py b/tests/video/test_rife.py
new file mode 100644
index 0000000..99bc7bb
--- /dev/null
+++ b/tests/video/test_rife.py
@@ -0,0 +1,82 @@
+# SPDX-License-Identifier: Apache-2.0
+"""RIFE runner: it is found or refused by name, and a real binary (when one is installed)
+interpolates an RGBA frame that sits between its two neighbours, alpha included.
+
+The real-binary test runs only where `rife-ncnn-vulkan` is reachable (SPRITE_GEN_RIFE or PATH);
+the locating rules need no binary at all."""
+
+from __future__ import annotations
+
+import os
+import stat
+from pathlib import Path
+
+import numpy as np
+import pytest
+from PIL import Image
+
+from sprite_gen.video import rife
+
+
+def _fake_binary(tmp_path: Path, with_model: bool = True) -> Path:
+ binary = tmp_path / "bin" / rife.BINARY
+ binary.parent.mkdir()
+ binary.write_text("#!/bin/sh\nexit 0\n")
+ binary.chmod(binary.stat().st_mode | stat.S_IXUSR)
+ if with_model:
+ (binary.parent / rife.MODEL).mkdir()
+ for name in ("flownet.param", "flownet.bin"):
+ (binary.parent / rife.MODEL / name).write_bytes(b"x")
+ return binary
+
+
+def test_missing_binary_is_refused_with_the_install_line(monkeypatch, tmp_path):
+ monkeypatch.delenv("SPRITE_GEN_RIFE", raising=False)
+ monkeypatch.setenv("PATH", str(tmp_path))
+ with pytest.raises(rife.RifeUnavailable, match="install rife-ncnn-vulkan 20221029"):
+ rife.locate()
+
+
+def test_model_beside_the_binary_is_found(monkeypatch, tmp_path):
+ binary = _fake_binary(tmp_path)
+ monkeypatch.setenv("SPRITE_GEN_RIFE", str(binary))
+ monkeypatch.delenv("SPRITE_GEN_RIFE_MODEL", raising=False)
+ found, model = rife.locate()
+ assert found == binary.resolve() and model == binary.resolve().parent / rife.MODEL
+
+
+def test_missing_model_is_refused(monkeypatch, tmp_path):
+ binary = _fake_binary(tmp_path, with_model=False)
+ monkeypatch.setenv("SPRITE_GEN_RIFE", str(binary))
+ monkeypatch.delenv("SPRITE_GEN_RIFE_MODEL", raising=False)
+ with pytest.raises(rife.RifeUnavailable, match="flownet.param"):
+ rife.locate()
+
+
+def _disc(cx: int) -> Image.Image:
+ im = np.zeros((96, 128, 4), dtype=np.uint8)
+ yy, xx = np.mgrid[:96, :128]
+ inside = (yy - 48) ** 2 + (xx - cx) ** 2 <= 18 ** 2
+ im[inside] = (200, 60, 40, 255)
+ return Image.fromarray(im, "RGBA")
+
+
+def _real_rife_available() -> bool:
+ try:
+ rife.locate()
+ except rife.RifeUnavailable:
+ return False
+ return True
+
+
[email protected](not _real_rife_available(), reason="rife-ncnn-vulkan not installed (SPRITE_GEN_RIFE / PATH)")
+def test_real_rife_makes_the_frame_between_in_colour_and_alpha():
+ interpolate = rife.Rife()
+ mid = interpolate(_disc(40), _disc(72), 0.5)
+ a = np.asarray(mid)[..., 3] / 255.0
+ xs = np.nonzero(a > 0.5)[1]
+ assert abs(xs.mean() - 56) <= 3 # the disc moved half way, not cross-faded at both ends
+ assert a[:, :20].max() == 0 and a[:, -20:].max() == 0 # no coverage invented far from the body
+ rgb = np.asarray(mid)[..., :3][a > 0.9]
+ assert np.abs(rgb.mean(axis=0) - (200, 60, 40)).max() < 12 # unpremultiplied back to the body colour
+ assert interpolate.made == 1