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

Centralize encoder defaults at medium preset and CRF 23

apoogdka77cbbd6c0d7
diff --git a/docs/content/developer-guide/documentation.md b/docs/content/developer-guide/documentation.md
index 771db6b4..aa76e61d 100644
--- a/docs/content/developer-guide/documentation.md
+++ b/docs/content/developer-guide/documentation.md
@@ -237,8 +237,7 @@ audio and words are committed with it.
[`tests/docs/test_examples.py`](https://github.com/academa-labs/manimgx/blob/main/tests/docs/test_examples.py)
fails until they are.
-A film is encoded for the web (x264's `slow` preset at CRF 28): a tenth of the size of a
-render's default (`ultrafast`, 18), alike to the eye, made in the same time.
+A film is encoded for the web with x264's `slow` preset at CRF 28. Normal renders use `medium` at CRF 23.
## The Gallery
diff --git a/rust/engine/src/python.rs b/rust/engine/src/python.rs
index 6c51ecda..d6b8e9bc 100644
--- a/rust/engine/src/python.rs
+++ b/rust/engine/src/python.rs
@@ -12,6 +12,10 @@ use pyo3::types::PyBytes;
use crate::render::{COUNT_BYTES, Player, count, with_gpu};
use crate::{CameraView, take};
+// One source for the native binding and every Python export entry point.
+const DEFAULT_ENCODER_PRESET: &str = "medium";
+const DEFAULT_ENCODER_CRF: f32 = 23.0;
+
#[cfg(feature = "typeset")]
pyo3::create_exception!(_engine, TypstError, pyo3::exceptions::PyException);
@@ -140,9 +144,9 @@ impl Player {
#[cfg(feature = "export")]
/// Start an MP4 at `path`; frames follow with `push`, and `end_export` writes the file. x264
- /// runs at `preset` and `crf` (by default ultrafast, 18), with `options` — its own settings
+ /// runs at `preset` and `crf` (the module's defaults), with `options` — its own settings
/// over those (as `-x264-params`, e.g. `[("keyint", "600")]`).
- #[pyo3(signature = (path, fps = 60, preset = "ultrafast".to_string(), crf = 18.0, options = Vec::new()))]
+ #[pyo3(signature = (path, fps = 60, preset = DEFAULT_ENCODER_PRESET.to_string(), crf = DEFAULT_ENCODER_CRF, options = Vec::new()))]
fn begin_export(&mut self, py: Python<'_>, path: String, fps: u32, preset: String, crf: f32, options: Vec<(String, String)>) -> PyResult<()> {
if self.export.is_some() {
return Err(PyRuntimeError::new_err("an export is already open"));
@@ -526,6 +530,8 @@ fn window(py: Python<'_>, title: String, time: f64, fonts: Vec<String>) -> PyRes
#[pymodule]
fn _engine(m: &Bound<'_, PyModule>) -> PyResult<()> {
+ m.add("DEFAULT_ENCODER_PRESET", DEFAULT_ENCODER_PRESET)?;
+ m.add("DEFAULT_ENCODER_CRF", DEFAULT_ENCODER_CRF)?;
m.add("TAKE_VERSION", take::VERSION)?;
#[cfg(feature = "render")]
{
diff --git a/src/manimgx/_engine.pyi b/src/manimgx/_engine.pyi
index 9cb6762f..e030db3a 100644
--- a/src/manimgx/_engine.pyi
+++ b/src/manimgx/_engine.pyi
@@ -10,6 +10,9 @@ its layout read off Typst's frames (see `manimgx.drawing.typesetting`).
from collections.abc import Sequence
from pathlib import Path
+DEFAULT_ENCODER_PRESET: str
+DEFAULT_ENCODER_CRF: float
+
TAKE_VERSION: int
"""The take format written by Recorder and supported by Replay and the native/browser player."""
@@ -76,8 +79,8 @@ class Player:
self,
path: str,
fps: int = 60,
- preset: str = "ultrafast",
- crf: float = 18.0,
+ preset: str = ...,
+ crf: float = ...,
options: Sequence[tuple[str, str]] = ...,
) -> None:
"""Start an MP4 at `path` (x264 at `preset` and `crf`, `options` its own settings)."""
diff --git a/src/manimgx/cli/export.py b/src/manimgx/cli/export.py
index d3d5e8fc..6e71beba 100644
--- a/src/manimgx/cli/export.py
+++ b/src/manimgx/cli/export.py
@@ -30,7 +30,15 @@ from manimgx.cli.scenes import (
)
from manimgx.cli.storyboard import Sheets, Watch, line
from manimgx.config import config
-from manimgx.rendering.film import Cut, Film, Frame, Play, X264Preset
+from manimgx.rendering.film import (
+ DEFAULT_ENCODER_CRF,
+ DEFAULT_ENCODER_PRESET,
+ Cut,
+ Film,
+ Frame,
+ Play,
+ X264Preset,
+)
from manimgx.scene import Scene
if TYPE_CHECKING:
@@ -56,10 +64,10 @@ def render(
typer.Option(
help="x264 encoding preset; faster presets render faster while making larger files."
),
- ] = "ultrafast",
+ ] = DEFAULT_ENCODER_PRESET,
crf: Annotated[
float, typer.Option(min=0, max=51, help="x264 CRF (0 to 51); lower is better.")
- ] = 18.0,
+ ] = DEFAULT_ENCODER_CRF,
) -> None:
"""Render a scene to an MP4 video, with its sound.
diff --git a/src/manimgx/cli/scenes.py b/src/manimgx/cli/scenes.py
index 4f1fec2f..1cda639d 100644
--- a/src/manimgx/cli/scenes.py
+++ b/src/manimgx/cli/scenes.py
@@ -21,7 +21,14 @@ from rich.console import Console
import manimgx
from manimgx.animation.timeline import Animation
from manimgx.config import Config, config
-from manimgx.rendering.film import Film, FrameSink, Play, X264Preset
+from manimgx.rendering.film import (
+ DEFAULT_ENCODER_CRF,
+ DEFAULT_ENCODER_PRESET,
+ Film,
+ FrameSink,
+ Play,
+ X264Preset,
+)
from manimgx.scene import Scene
@@ -297,8 +304,8 @@ def take(
video: str | os.PathLike[str] | None = None,
frames: FrameSink | None = None,
plays: Watch | None = None,
- preset: X264Preset = "ultrafast",
- crf: float = 18.0,
+ preset: X264Preset = DEFAULT_ENCODER_PRESET,
+ crf: float = DEFAULT_ENCODER_CRF,
) -> tuple[Scene, Film]:
"""Run the scene at `look`, making its film (and video, frames and plays, as asked). On a
terminal, a status line on stderr follows the plays as they end."""
diff --git a/src/manimgx/rendering/film.py b/src/manimgx/rendering/film.py
index 8ed56c6c..5a18e512 100644
--- a/src/manimgx/rendering/film.py
+++ b/src/manimgx/rendering/film.py
@@ -11,7 +11,7 @@ import os
from collections.abc import Callable
from dataclasses import asdict, dataclass
from fractions import Fraction
-from typing import TYPE_CHECKING, Literal, get_args
+from typing import TYPE_CHECKING, Final, Literal, cast, get_args
from warnings import deprecated
from manimgx import _engine
@@ -44,6 +44,13 @@ X264Preset = Literal[
]
"""The x264 presets, from fastest to slowest."""
+DEFAULT_ENCODER_PRESET: Final[X264Preset] = cast(
+ X264Preset, _engine.DEFAULT_ENCODER_PRESET
+)
+"""The native encoder's default preset, shared by Python and the command line."""
+DEFAULT_ENCODER_CRF: Final[float] = _engine.DEFAULT_ENCODER_CRF
+"""The native encoder's default constant rate factor."""
+
class Frame:
"""A frame of a film, as the film sends it: shown as frames `index` to
@@ -242,8 +249,8 @@ class Film:
frames: FrameSink | None = None,
plays: PlayHook | None = None,
take: Take | None = None,
- preset: X264Preset = "ultrafast",
- crf: float = 18.0,
+ preset: X264Preset = DEFAULT_ENCODER_PRESET,
+ crf: float = DEFAULT_ENCODER_CRF,
) -> None:
if preset not in get_args(X264Preset):
raise ValueError(f"unknown x264 preset {preset!r}")
diff --git a/src/manimgx/scene.py b/src/manimgx/scene.py
index 505ac6f9..1140bf9f 100644
--- a/src/manimgx/scene.py
+++ b/src/manimgx/scene.py
@@ -49,6 +49,8 @@ from manimgx.mobject import (
simulated,
)
from manimgx.rendering.film import (
+ DEFAULT_ENCODER_CRF,
+ DEFAULT_ENCODER_PRESET,
Caption,
Cut,
Film,
@@ -616,8 +618,8 @@ class Scene:
self,
video: str | os.PathLike[str] | None = None,
*,
- preset: X264Preset = "ultrafast",
- crf: float = 18.0,
+ preset: X264Preset = DEFAULT_ENCODER_PRESET,
+ crf: float = DEFAULT_ENCODER_CRF,
frames: FrameSink | None = None,
plays: PlayHook | None = None,
take: Take | None = None,
diff --git a/tests/unit/rendering/test_encoding.py b/tests/unit/rendering/test_encoding.py
new file mode 100644
index 00000000..b5c02312
--- /dev/null
+++ b/tests/unit/rendering/test_encoding.py
@@ -0,0 +1,68 @@
+"""All export entry points pass shared defaults and explicit overrides to the encoder."""
+
+from pathlib import Path
+from typing import TypedDict
+
+import pytest
+from typer import Exit
+from typer.testing import CliRunner
+
+import manimgx as m
+from manimgx import _engine
+from manimgx.cli import app
+from manimgx.cli.scenes import Format, take
+from manimgx.rendering import feed
+from manimgx.rendering.film import X264Preset
+
+
+class Options(TypedDict, total=False):
+ preset: X264Preset
+ crf: float
+
+
+class EncoderReached(Exception):
+ """Stop before the native encoder or GPU does any work."""
+
+
[email protected]("entry", ["film", "scene", "take", "cli"])
[email protected]("override", [False, True])
+def test_export_settings_reach_the_encoder(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, entry: str, override: bool
+) -> None:
+ received: list[tuple[str, float]] = []
+
+ class Player:
+ def __init__(self, width: int, height: int) -> None:
+ pass
+
+ def begin_export(self, path: str, *, fps: int, preset: str, crf: float) -> None:
+ received.append((preset, crf))
+ raise EncoderReached
+
+ monkeypatch.setattr(feed, "Player", Player)
+ monkeypatch.setattr(_engine, "start_gpu", lambda: None)
+ options: Options = {"preset": "slow", "crf": 31.0} if override else {}
+ video = tmp_path / "out.mp4"
+ if entry == "cli":
+ source = tmp_path / "encoding_scene.py"
+ source.write_text(
+ "import manimgx as m\nclass EncodingScene(m.Scene):\n"
+ " def construct(self):\n pass\n",
+ encoding="utf-8",
+ )
+ flags = ["--preset", "slow", "--crf", "31"] if override else []
+ result = CliRunner().invoke(
+ app, ["render", str(source), "-o", str(video), *flags]
+ )
+ assert result.exit_code == 1
+ elif entry == "film":
+ with pytest.raises(EncoderReached):
+ m.Film(video, **options)
+ elif entry == "scene":
+ with pytest.raises(EncoderReached):
+ m.Scene().render(video, **options)
+ else:
+ with pytest.raises(Exit):
+ take(m.Scene, Format.own(None, None), video=video, **options)
+ assert received == [("slow", 31.0) if override else ("medium", 23.0)]
+ assert not video.exists()