Skip to content

The animation engine for agents: blazingly fast math and 3D videos with Manim's Python API, on a Rust GPU core.

Python

Add live scene preview

apoogdk206f300f1c05
diff --git a/src/manimgx/cli/export.py b/src/manimgx/cli/export.py
index 1076eb57..df873e19 100644
--- a/src/manimgx/cli/export.py
+++ b/src/manimgx/cli/export.py
@@ -26,7 +26,7 @@ from manimgx.cli.scenes import (
)
from manimgx.cli.storyboard import PER_SHEET, Sheets, Watch, caption, tile
from manimgx.config import config
-from manimgx.rendering.film import Cut, Film, Frame, Play
+from manimgx.rendering.film import Cut, Film, Frame, Play, X264Preset
from manimgx.scene import Scene
@@ -43,6 +43,15 @@ def render(
] = None,
resolution: Resolution = None,
fps: Fps = None,
+ preset: Annotated[
+ X264Preset,
+ typer.Option(
+ help="x264 encoding preset; faster presets render faster while making larger files."
+ ),
+ ] = "ultrafast",
+ crf: Annotated[
+ float, typer.Option(min=0, max=51, help="x264 CRF (0 to 51); lower is better.")
+ ] = 18.0,
) -> None:
"""Render a scene to an MP4 video, with its sound.
@@ -56,7 +65,7 @@ def render(
look = Format.own(resolution, fps)
watch = Watch(Sheets(video.with_name(f"{video.stem}.storyboard.png")))
started = time.perf_counter()
- made, _ = take(kind, look, video=video, plays=watch)
+ made, _ = take(kind, look, video=video, plays=watch, preset=preset, crf=crf)
sheets = watch.close()
took = time.perf_counter() - started
megabytes = video.stat().st_size / 1e6
@@ -258,8 +267,8 @@ def present(
Renders the video, writes a page that plays it (it stops at the end of each section,
until you go on), and opens it. Keys: → or Space next, ← back, F full screen, B black,
- P presenter view (notes, the next slide, a clock), C captions, ? help. A clicker works:
- it sends the same keys. Begin a section with `self.next_section(...)` in the scene.
+ Shift+P presenter view (notes, the next slide, a timer), C captions, ? help. A clicker
+ works: it sends the same keys. Begin a section with `self.next_section(...)` in the scene.
"""
kind = scene(file, name)
video = output or file.with_name(f"{kind.__name__}.mp4")
diff --git a/src/manimgx/cli/present.html b/src/manimgx/cli/present.html
new file mode 100644
index 00000000..f14a1980
--- /dev/null
+++ b/src/manimgx/cli/present.html
@@ -0,0 +1,125 @@
+<!doctype html>
+<!-- A manimgx film presented: its sections are its slides. manimgx fills in DECK. -->
+<meta charset="utf-8" />
+<meta name="viewport" content="width=device-width, initial-scale=1" />
+<title>DECK_TITLE</title>
+<style>
+ html, body { margin: 0; height: 100%; background: #000; overflow: hidden; }
+ video { width: 100vw; height: 100vh; object-fit: contain; display: block; }
+ #black { position: fixed; inset: 0; background: #000; display: none; }
+ #help { position: fixed; right: 1em; bottom: 1em; color: #aaa; font: 14px system-ui;
+ background: #111d; padding: .8em 1em; border-radius: 8px; display: none; white-space: pre; }
+</style>
+<video id="film" src="DECK_VIDEO" preload="auto" playsinline></video>
+<div id="black"></div>
+<div id="help">→ Space PageDown: next ← PageUp: back
+Home End: first, last 1–9 then Enter: go to slide
+F: full screen B: black P: presenter view C: captions ?: this help</div>
+<script>
+"use strict";
+const deck = DECK_JSON; // {fps, frames, sections: [{name, frame, type, notes}], captions: [[start, end, text]]}
+const film = document.getElementById("film");
+const s = deck.sections;
+const last = deck.frames - 1;
+const at = (frame) => (Math.min(frame, last) + 0.5) / deck.fps; // a frame's middle: seeking lands on it
+const first = (k) => (k < s.length ? s[k].frame : deck.frames); // where section k starts (k = s.length: the end)
+// two states: ready at section k's start (the picture the section before left), or playing it
+let k = 0, playing = false, leaving = false, typed = "";
+
+const track = film.addTextTrack("captions", "Captions");
+for (const [a, b, text] of deck.captions) track.addCue(new VTTCue(a, b, text));
+track.mode = "hidden";
+
+function ready(section) {
+ k = Math.max(0, Math.min(section, s.length));
+ playing = leaving = false;
+ film.pause();
+ film.currentTime = at(first(k));
+ sync();
+}
+function play(section) {
+ if (section >= s.length) return ready(s.length);
+ k = section; playing = true; leaving = false;
+ if (Math.abs(film.currentTime - at(first(k))) > 0.5 / deck.fps) film.currentTime = at(first(k));
+ film.play(); sync(); watch();
+}
+// each frame: at a section's end, by its type, stop there, go on, or play it again
+function watch() {
+ film.requestVideoFrameCallback((_, meta) => {
+ if (!playing) return;
+ if (meta.mediaTime * deck.fps >= first(k + 1) - 1.5 || film.ended) {
+ const type = s[k].type;
+ if (type.endsWith("loop") && !leaving) film.currentTime = at(first(k));
+ else if (type === "presentation.skip" || leaving) return play(k + 1);
+ else return ready(k + 1);
+ }
+ watch();
+ });
+}
+function next() {
+ if (!playing) return play(k);
+ const type = s[k].type;
+ if (type === "presentation.loop") return play(k + 1);
+ if (type === "presentation.complete_loop") return void (leaving = true);
+ ready(k + 1); // the section, finished at once
+}
+function back() { ready(playing ? k : k - 1); }
+
+// ── presenter view: a window this page writes and drives (so it works from a file too)
+let presenter = null;
+function openPresenter() {
+ presenter = window.open("", "presenter", "width=900,height=600");
+ if (!presenter) return;
+ presenter.document.write(`<!doctype html><meta charset="utf-8"><title>Presenter</title>
+ <style>body{margin:0;background:#111;color:#eee;font:18px system-ui;display:grid;
+ grid-template:"now next" 55% "notes notes" 1fr/60% 40%;height:100vh;gap:8px;padding:8px;box-sizing:border-box}
+ video{width:100%;height:100%;object-fit:contain;background:#000}#notes{grid-area:notes;overflow:auto;white-space:pre-wrap}
+ #bar{position:fixed;top:8px;right:16px;color:#8cf}</style>
+ <video id="now" muted></video><video id="next" muted style="grid-area:next"></video>
+ <div id="notes"></div><div id="bar"></div>`);
+ presenter.document.close();
+ for (const id of ["now", "next"]) presenter.document.getElementById(id).src = film.currentSrc || film.src;
+ presenter.document.addEventListener("keydown", key);
+ sync();
+}
+const t0 = Date.now();
+function sync() {
+ if (!presenter || presenter.closed) return;
+ const d = presenter.document, j = Math.min(k, s.length - 1);
+ for (const [id, t] of [["now", at(first(k))], ["next", at(first(k + 1))]]) {
+ const v = d.getElementById(id);
+ if (Math.abs(v.currentTime - t) > 1e-3) v.currentTime = t; // seek only on a change
+ }
+ d.getElementById("notes").textContent = s[j].notes || "";
+ const m = Math.floor((Date.now() - t0) / 60000), sec = Math.floor((Date.now() - t0) / 1000) % 60;
+ d.getElementById("bar").textContent = `${j + 1} / ${s.length} ${s[j].name} ${m}:${String(sec).padStart(2, "0")}`;
+}
+setInterval(sync, 1000);
+
+function key(e) {
+ const black = document.getElementById("black"), help = document.getElementById("help");
+ if (/^[0-9]$/.test(e.key)) { typed += e.key; return; }
+ if (e.key === "Enter" && typed) { ready(Number(typed) - 1); typed = ""; return; }
+ typed = "";
+ switch (e.key) {
+ case "ArrowRight": case "ArrowDown": case " ": case "PageDown": case "Enter": case "n": next(); break;
+ case "ArrowLeft": case "ArrowUp": case "PageUp": case "Backspace": case "p": back(); break;
+ case "Home": ready(0); break;
+ case "End": ready(s.length); break;
+ case "f": case "F": document.fullscreenElement ? document.exitFullscreen() : document.documentElement.requestFullscreen(); break;
+ case "b": case "B": case ".": black.style.display = black.style.display === "block" ? "none" : "block"; break;
+ case "P": openPresenter(); break;
+ case "c": case "C": track.mode = track.mode === "showing" ? "hidden" : "showing"; break;
+ case "?": case "h": help.style.display = help.style.display === "block" ? "none" : "block"; break;
+ default: return;
+ }
+ e.preventDefault();
+}
+document.addEventListener("keydown", key);
+film.addEventListener("click", next);
+// the film's own end, which the frames' watch may not see
+film.addEventListener("ended", () => {
+ if (playing) s[k].type.endsWith("loop") && !leaving ? play(k) : ready(s.length);
+});
+film.addEventListener("loadeddata", () => ready(0), { once: true });
+</script>
diff --git a/src/manimgx/cli/preview.py b/src/manimgx/cli/preview.py
new file mode 100644
index 00000000..bef41fde
--- /dev/null
+++ b/src/manimgx/cli/preview.py
@@ -0,0 +1,171 @@
+"""`manimgx preview`: a scene in manimgx's player, in a window of its own, made again each time
+its code is saved.
+
+The scene runs here, as `manimgx render` runs it, but its film is recorded as a take (see
+[`Film`][manimgx.Film]) and sent to a [`Window`][manimgx.Window], which plays it as it is made.
+On a save the scene runs again — at once: a run a save has made out of date is cut — and its new
+take replaces the old at the same moment, once it gets there: an edit never loses the place. An
+error is shown over the last good take.
+"""
+
+import sys
+import time
+import traceback
+from pathlib import Path
+from typing import Annotated
+
+import typer
+
+from manimgx.cli.scenes import (
+ File,
+ Format,
+ Fps,
+ Mistake,
+ Resolution,
+ SceneName,
+ Size,
+ fail,
+ load,
+ pick,
+ report_error,
+ scenes,
+)
+from manimgx.config import config
+from manimgx.rendering.film import Cut
+from manimgx.rendering.window import Window
+
+POLL = 0.02 # seconds between looks at the files
+
+
+def preview(
+ file: File,
+ name: SceneName = None,
+ time_: Annotated[
+ float,
+ typer.Option(
+ "--time", "-t", min=0, help="Where the playhead starts, in seconds."
+ ),
+ ] = 0.0,
+ resolution: Resolution = None,
+ fps: Fps = None,
+) -> None:
+ """Preview a scene live: in a window, made again each time its code is saved.
+
+ The window plays the scene as it is made. Saving the file, or a module it imports from
+ beside it, runs the scene again, and the window keeps its place; an error shows over the
+ last good picture. A file of several scenes plays the one named, or its first; N and P go
+ to the others. Keys: Space play/pause, ← → 5 s, , . a frame, Option (or Ctrl) with ← → a
+ play, ? all of them. Closing the window, or Ctrl+C, stops."""
+ if not file.is_file():
+ raise fail(f"error: {file}: no such file")
+ with Window(f"{file.name} — manimgx", time=time_) as window:
+ try:
+ files = [file]
+ while window.open:
+ news = News(files, window) # the files as this run reads them
+ files = run(file, name, resolution, fps, window, news)
+ news.watch(files)
+ while window.open and not news():
+ time.sleep(POLL)
+ if news.asked is not None:
+ name = news.asked
+ else:
+ time.sleep(POLL) # an editor saving in steps: let it finish
+ except KeyboardInterrupt:
+ pass
+ if window.failure is not None:
+ raise fail(f"error: the window: {window.failure}", 1)
+
+
+class News:
+ """What makes a run out of date: a file it reads saved again, or another scene asked for
+ in the window. Called, whether there is any (it looks every `POLL` seconds)."""
+
+ def __init__(self, files: list[Path], window: Window) -> None:
+ self.seen = dict(zip(files, stamps(files), strict=True))
+ self.window = window
+ self.asked: str | None = None
+ self.any = False # there was some
+ self.looked = time.monotonic()
+
+ def watch(self, files: list[Path]) -> None:
+ """Watch `files` too: those not watched yet as they are now."""
+ new = [f for f in files if f not in self.seen]
+ self.seen.update(zip(new, stamps(new), strict=True))
+
+ def __call__(self) -> bool:
+ now = time.monotonic()
+ if now - self.looked < POLL:
+ return False
+ self.looked = now
+ self.asked = self.window.asked() or self.asked
+ files = list(self.seen)
+ self.any = self.asked is not None or stamps(files) != list(self.seen.values())
+ return self.any
+
+
+def run(
+ file: Path,
+ name: str | None,
+ resolution: Size | None,
+ fps: int | None,
+ window: Window,
+ news: News,
+) -> list[Path]:
+ """Run the scene once, its take (or its error) into `window`, and cut it once `news`
+ makes it out of date. Returns the files to watch: the scene's, and the modules it imported
+ from beside it."""
+ root = file.resolve().parent
+ for key in [key for key, path in _own(root) if key != "__main__"]:
+ del sys.modules[key] # the file's own modules are imported afresh: they change
+ started = time.perf_counter()
+
+ def take(data: bytes) -> None:
+ if news():
+ raise Cut # out of date: run again
+ window(data)
+
+ try:
+ module = load(file)
+ found = [s.__name__ for s in scenes(module)]
+ # unnamed, the file's first scene: its viewer goes to the others in the window (N, P)
+ kind = pick(file, module, found[0] if name is None and len(found) > 1 else name)
+ window.scenes(found, kind.__name__)
+ look = Format.own(resolution, fps)
+ config.pixel_width, config.pixel_height = look.width, look.height
+ config.frame_rate = look.fps
+ film = kind().render(take=take)
+ cut = "cut: " if news.any or not window.open else ""
+ typer.echo(
+ f"{kind.__name__}: {cut}{film.frame_count} frames in"
+ f" {time.perf_counter() - started:.2f} s",
+ err=True,
+ )
+ except Exception as error:
+ text = str(error) if isinstance(error, Mistake) else report_error(error)
+ typer.echo(text, err=True)
+ own = [
+ f
+ for f in traceback.extract_tb(error.__traceback__)
+ if Path(f.filename).resolve().is_relative_to(root)
+ ]
+ window.failed(
+ error, text, own[-1].lineno if own else getattr(error, "lineno", None)
+ )
+ return [file, *(path for _, path in _own(root) if path != file.resolve())]
+
+
+def _own(root: Path) -> list[tuple[str, Path]]:
+ """The modules imported from under `root` (the scene's directory), and their files."""
+ return [
+ (key, path)
+ for key, module in list(sys.modules.items())
+ if (where := getattr(module, "__file__", None))
+ and (path := Path(where).resolve()).is_relative_to(root)
+ and path.suffix == ".py"
+ ]
+
+
+def stamps(paths: list[Path]) -> list[float]:
+ """The files' modification times (0 for one that is gone, for now)."""
+ return [p.stat().st_mtime if p.exists() else 0.0 for p in paths]