Skip to content

Saving animations#

Render a clip once and derive every other format from the written file.

Drawing frames costs far more than encoding them, so save_animation encodes the animation to a video and — when a GIF is also wanted — reads the frames back off that file rather than redrawing them. It also raises the intermediate video to full chroma in that case, because a subsampled source permanently caps how much colour detail can survive the GIF palette.

Reachable as Map.save_animation and TexturedGlobe.save_animation, or directly as the function below.

digitalearth.static.render.animation.save_animation(anim, path, *, fps=None, gif=None, gif_options=None, **kwargs) #

Save anim to path, optionally deriving a GIF from the written file without re-rendering.

Parameters:

Name Type Description Default
anim Any

The matplotlib FuncAnimation to save.

required
path str | PathLike[str]

Output path. The extension picks the format — gif, mp4, mov, avi or webp.

required
fps float | None

Frames per second. Defaults to :data:FALLBACK_SAVE_FPS; callers that know the scene's own rate (Map.animate(fps=...)) pass it through so the file matches what was previewed.

None
gif str | PathLike[str] | None

When given, a second output path to derive a GIF at, by reading the frames back off path instead of re-rendering them. path must be one of :data:VIDEO_SUFFIXES — the ffmpeg-written containers. GIF and WebP are excluded because cleopatra writes them with Pillow, which ignores pix_fmt, so the full-chroma intermediate below cannot be delivered for them.

None
gif_options dict | None

Extra keyword arguments for gif_from_video (width, max_colors, loop, optimize, quantize_method). fps defaults to the same rate as the video.

None
**kwargs Any

Forwarded to cleopatra's save_animation (crf, bitrate, codec, preset, pix_fmt, dpi, optimize, loop, quantize_method, extra_args).

{}

Returns:

Type Description
str | tuple[str, str]

The written path as a str, or a (video, gif) pair when gif was requested.

Raises:

Type Description
ValueError

if gif is given but path is itself a GIF, if gif does not end in .gif, or if fps is not a finite number or rounds to less than one frame per second.

Warns:

Type Description
RuntimeWarning

If gif_options["fps"] differs from the video's rate, so the two files of the one animation would play at different speeds.

Note

The rate is rounded to a whole number once, and the same value is used for the video and for the derived GIF, so the two files play at the same speed unless gif_options deliberately overrides it.

Examples:

  • Rendering once and delivering two formats, without drawing the frames twice:
    >>> from digitalearth.static.render.animation import save_animation
    >>> video, gif = save_animation(anim, "clip.mp4", fps=12, gif="clip.gif")  # doctest: +SKIP
    
Source code in src/digitalearth/static/render/animation.py
def save_animation(
    anim: Any,
    path: str | os.PathLike[str],
    *,
    fps: float | None = None,
    gif: str | os.PathLike[str] | None = None,
    gif_options: dict | None = None,
    **kwargs: Any,
) -> str | tuple[str, str]:
    """Save ``anim`` to ``path``, optionally deriving a GIF from the written file without re-rendering.

    Args:
        anim: The matplotlib ``FuncAnimation`` to save.
        path: Output path. The extension picks the format — ``gif``, ``mp4``, ``mov``, ``avi`` or ``webp``.
        fps: Frames per second. Defaults to :data:`FALLBACK_SAVE_FPS`; callers that know the scene's own
            rate
            (``Map.animate(fps=...)``) pass it through so the file matches what was previewed.
        gif: When given, a second output path to derive a GIF at, by reading the frames back off ``path``
            instead of re-rendering them. ``path`` must be one of :data:`VIDEO_SUFFIXES` — the ffmpeg-written
            containers. GIF and WebP are excluded because cleopatra writes them with Pillow, which ignores
            ``pix_fmt``, so the full-chroma intermediate below cannot be delivered for them.
        gif_options: Extra keyword arguments for ``gif_from_video`` (``width``, ``max_colors``, ``loop``,
            ``optimize``, ``quantize_method``). ``fps`` defaults to the same rate as the video.
        **kwargs: Forwarded to cleopatra's ``save_animation`` (``crf``, ``bitrate``, ``codec``, ``preset``,
            ``pix_fmt``, ``dpi``, ``optimize``, ``loop``, ``quantize_method``, ``extra_args``).

    Returns:
        The written path as a ``str``, or a ``(video, gif)`` pair when ``gif`` was requested.

    Raises:
        ValueError: if ``gif`` is given but ``path`` is itself a GIF, if ``gif`` does not end in ``.gif``, or
            if ``fps`` is not a finite number or rounds to less than one frame per second.

    Warns:
        RuntimeWarning: If ``gif_options["fps"]`` differs from the video's rate, so the two files of the one
            animation would play at different speeds.

    Note:
        The rate is rounded to a whole number **once**, and the same value is used for the video and for the
        derived GIF, so the two files play at the same speed unless ``gif_options`` deliberately overrides it.

    Examples:
        - Rendering once and delivering two formats, without drawing the frames twice:
            ```python
            >>> from digitalearth.static.render.animation import save_animation
            >>> video, gif = save_animation(anim, "clip.mp4", fps=12, gif="clip.gif")  # doctest: +SKIP

            ```
    """
    rate = _encoder_fps(FALLBACK_SAVE_FPS if fps is None else fps)
    video_path = os.fspath(path)
    if gif is None:
        _cleopatra_save_animation(anim, video_path, fps=rate, **kwargs)
        return video_path

    gif_path = os.fspath(gif)
    if video_path.lower().endswith(".gif"):
        raise ValueError(
            "gif= derives a GIF from a video; path is already a GIF. Save to a video (e.g. .mp4) and let "
            "gif= produce the GIF, or drop gif= to write the GIF directly."
        )
    if not video_path.lower().endswith(VIDEO_SUFFIXES):
        raise ValueError(
            f"gif= reads the frames back off a video, so path must be one of {', '.join(VIDEO_SUFFIXES)}; "
            f"got {video_path!r}."
        )
    if not gif_path.lower().endswith(".gif"):
        raise ValueError(f"gif must end in '.gif', got {gif_path!r}")

    # Full chroma in the intermediate so the GIF palette is not built from subsampled colour.
    kwargs.setdefault("pix_fmt", FULL_CHROMA_PIX_FMT)
    _cleopatra_save_animation(anim, video_path, fps=rate, **kwargs)
    gif_kwargs = dict(gif_options or {})
    if "fps" in gif_kwargs and float(gif_kwargs["fps"]) != rate:
        # gif_from_video types fps as a float and samples the source at that rate, so a fractional value is
        # meaningful here even though the video's own rate had to be a whole number. Only warn when the two
        # genuinely differ, which is the case that produces two files playing at different speeds.
        warnings.warn(
            f"gif_options['fps']={gif_kwargs['fps']!r} differs from the video's {rate} fps, so the GIF and "
            "the video will play at different speeds. Drop it to inherit the video's rate.",
            RuntimeWarning,
            stacklevel=2,
        )
    gif_from_video(video_path, gif_path, **{"fps": rate, **gif_kwargs})
    return video_path, gif_path