BLOG

How to parse, extract, and pack SVGA 2.0 files in Python (without svga-python)

How to parse, extract, and pack SVGA 2.0 files in Python (without svga-python)

TL;DR

  • There is no official svga-python package on PyPI: running pip install svga-python does not provide an official SVGA animation SDK. Avoid unverified placeholder packages under similar names.
  • Standard Python libraries + protobuf cover the full format: SVGA 2.x is a zlib-compressed Proto3 MovieEntity payload. Compile the official svga.proto into svga_pb2.py, then combine zlib, zipfile, protobuf, and Pillow to read, audit, extract, and build .svga files.
  • Handle all three container layouts: inspect leading magic bytes to distinguish 50 4B 03 04 (ZIP containing 1.x movie.spec or 2.x movie.binary) from 78 01 / 78 5E / 78 9C / 78 DA (raw 2.x zlib stream).
  • Measure true decoded RAM: summing width × height × 4 across all non-audio embedded images reproduces the uncompressed 32-bit RGBA texture footprint on mobile players.
  • Built for CI/CD and 3D render pipelines: pack transparent PNG sequences from Blender, Cinema 4D, or After Effects into deduplicated SVGA 2.0 binaries directly in Python.

Tooling choices at a glance

Task Recommended stack Notes
Read SVGA 1.x only (movie.spec) Built-in zipfile + json Zero third-party dependencies; see SVGA file structure
Read & write SVGA 2.x (MovieEntity) protobuf + svga.proto + built-in zlib Full support for ShapeEntity, matteKey, and AudioEntity
Compute RGBA RAM & inspect dimensions Above + Pillow (PIL) Decodes PNG, JPEG, and WebP headers accurately
Quick zero-install file check Browser SVGA Online Player Plays and inspects local files without uploads

Step 1: Download svga.proto and generate svga_pb2.py

Install protobuf and pillow, download svga.proto, and compile the Python bindings with protoc:

pip install protobuf pillow
curl -fsSLO https://svga.dev/assets/svga/svga.proto
protoc --python_out=. svga.proto

If protoc is not installed on your machine, grpcio-tools ships an embedded compiler:

pip install grpcio-tools pillow
python -m grpc_tools.protoc -I. --python_out=. svga.proto

This writes svga_pb2.py in your working directory. The primary message types (documented in the SVGA format specification) are:

  • MovieEntity: root message holding version, params (MovieParams), images (map<string, bytes>), sprites (repeated SpriteEntity), and audios (repeated AudioEntity).
  • MovieParams: canvas viewBoxWidth, viewBoxHeight, fps, and total frames.
  • SpriteEntity: binds an imageKey and optional matteKey to a per-frame array of FrameEntity records (alpha, layout, transform, clipPath, shapes).
  • AudioEntity: references an audioKey in images along with startFrame and endFrame.

Step 2: Sniff magic bytes, parse metadata, and calculate RGBA memory

Save the following script as inspect_svga.py. It detects the container header, parses SVGA 1.x ZIP (movie.spec), SVGA 2.x ZIP (movie.binary), or SVGA 2.x raw zlib, flags orphan/duplicate assets, and computes decoded RGBA memory (∑ width × height × 4).

import hashlib
import io
import json
import sys
import zipfile
import zlib
from pathlib import Path
from PIL import Image, UnidentifiedImageError

import svga_pb2


def sniff_container(raw: bytes) -> str:
    if raw.startswith(b"PK\x03\x04"):
        return "zip"
    if len(raw) >= 2 and raw[0] == 0x78 and raw[1] in (0x01, 0x5E, 0x9C, 0xDA):
        return "zlib"
    raise ValueError(f"Unsupported file header: {raw[:8].hex(' ')}")


def load_svga_assets(path: Path) -> dict:
    raw = path.read_bytes()
    kind = sniff_container(raw)

    if kind == "zip":
        with zipfile.ZipFile(io.BytesIO(raw)) as zf:
            names = set(zf.namelist())
            if "movie.binary" in names:
                movie = svga_pb2.MovieEntity()
                movie.ParseFromString(zf.read("movie.binary"))
                return parse_movie_entity("2.x (zip/movie.binary)", movie)
            if "movie.spec" in names:
                spec = json.loads(zf.read("movie.spec"))
                return parse_v1_spec(spec, zf, names)
            raise ValueError("ZIP archive contains neither movie.binary nor movie.spec")

    movie = svga_pb2.MovieEntity()
    movie.ParseFromString(zlib.decompress(raw))
    return parse_movie_entity("2.x (zlib)", movie)


def parse_v1_spec(spec: dict, zf: zipfile.ZipFile, names: set[str]) -> dict:
    movie = spec["movie"]
    view_box = movie.get("viewBox", {})
    sprites = spec.get("sprites", [])
    used_keys = {s.get("imageKey") for s in sprites if s.get("imageKey")}
    used_keys.update(s.get("matteKey") for s in sprites if s.get("matteKey"))

    blobs: dict[str, bytes] = {}
    for key, ref in spec.get("images", {}).items():
        candidate = next((c for c in (ref, f"{ref}.png", f"{key}.png") if c in names), None)
        if candidate:
            blobs[key] = zf.read(candidate)

    return summarize_assets(
        container="1.x (zip/movie.spec)",
        version=str(spec.get("ver", "1.x")),
        width=float(view_box.get("width", 0)),
        height=float(view_box.get("height", 0)),
        fps=int(movie.get("fps", 0)),
        frames=int(movie.get("frames", 0)),
        sprite_count=len(sprites),
        audio_count=0,
        audio_keys=set(),
        used_keys=used_keys,
        blobs=blobs,
    )


def parse_movie_entity(container: str, movie: svga_pb2.MovieEntity) -> dict:
    used_keys = {s.imageKey for s in movie.sprites if s.imageKey}
    used_keys.update(s.matteKey for s in movie.sprites if s.matteKey)
    audio_keys = {a.audioKey for a in movie.audios if a.audioKey}
    used_keys.update(audio_keys)

    return summarize_assets(
        container=container,
        version=movie.version or "2.0",
        width=movie.params.viewBoxWidth,
        height=movie.params.viewBoxHeight,
        fps=movie.params.fps,
        frames=movie.params.frames,
        sprite_count=len(movie.sprites),
        audio_count=len(movie.audios),
        audio_keys=audio_keys,
        used_keys=used_keys,
        blobs=dict(movie.images),
    )


def summarize_assets(
    *,
    container: str,
    version: str,
    width: float,
    height: float,
    fps: int,
    frames: int,
    sprite_count: int,
    audio_count: int,
    audio_keys: set[str],
    used_keys: set[str],
    blobs: dict[str, bytes],
) -> dict:
    rgba_bytes = 0
    hashes: dict[str, list[str]] = {}
    orphan_keys = sorted(k for k in blobs if k not in used_keys)

    for key, blob in blobs.items():
        if key in audio_keys or blob.startswith(b"ID3") or blob[:2] in (b"\xff\xfb", b"\xff\xf3", b"\xff\xf2"):
            continue
        digest = hashlib.sha256(blob).hexdigest()
        hashes.setdefault(digest, []).append(key)
        try:
            with Image.open(io.BytesIO(blob)) as im:
                rgba_bytes += im.width * im.height * 4
        except UnidentifiedImageError:
            pass

    duplicate_groups = [keys for keys in hashes.values() if len(keys) > 1]
    return {
        "container": container,
        "version": version,
        "canvas": f"{width:g}x{height:g}",
        "fps": fps,
        "frames": frames,
        "duration_sec": round(frames / fps, 3) if fps > 0 else 0.0,
        "sprites": sprite_count,
        "images": len(blobs) - len(audio_keys),
        "audios": audio_count,
        "orphan_keys": orphan_keys,
        "duplicate_groups": duplicate_groups,
        "decoded_rgba_bytes": rgba_bytes,
        "decoded_rgba_mib": round(rgba_bytes / (1024 * 1024), 2),
    }


if __name__ == "__main__":
    report = load_svga_assets(Path(sys.argv[1]))
    print(json.dumps(report, indent=2))

Test it against any download from the SVGA test samples library. When identifying orphan entries in automated cleanups, always preserve keys referenced by sprite.imageKey, sprite.matteKey, and audio.audioKey so mask layers and dynamic replacement slots are not stripped.


Step 3: Batch extract embedded images and MP3 audio tracks

To extract every embedded PNG, JPEG, WebP sprite and MP3 audio track to disk while sanitizing key names against path traversal:

import io
import json
import sys
import zipfile
import zlib
from pathlib import Path

import svga_pb2


def detect_extension(blob: bytes, is_audio: bool) -> str:
    if is_audio or blob.startswith(b"ID3") or blob[:2] in (b"\xff\xfb", b"\xff\xf3", b"\xff\xf2"):
        return ".mp3"
    if blob.startswith(b"\x89PNG\r\n\x1a\n"):
        return ".png"
    if blob.startswith(b"\xff\xd8\xff"):
        return ".jpg"
    if blob.startswith(b"RIFF") and blob[8:12] == b"WEBP":
        return ".webp"
    return ".bin"


def safe_stem(key: str, index: int) -> str:
    name = Path(key).name.strip(" .")
    return name if name else f"asset_{index:04d}"


def extract_assets(svga_path: Path, out_dir: Path) -> None:
    out_dir.mkdir(parents=True, exist_ok=True)
    raw = svga_path.read_bytes()

    if raw.startswith(b"PK\x03\x04"):
        with zipfile.ZipFile(io.BytesIO(raw)) as zf:
            names = set(zf.namelist())
            if "movie.binary" in names:
                movie = svga_pb2.MovieEntity()
                movie.ParseFromString(zf.read("movie.binary"))
            elif "movie.spec" in names:
                spec = json.loads(zf.read("movie.spec"))
                for idx, (key, ref) in enumerate(spec.get("images", {}).items()):
                    entry = next((c for c in (ref, f"{ref}.png", f"{key}.png") if c in names), None)
                    if entry:
                        blob = zf.read(entry)
                        ext = detect_extension(blob, False)
                        (out_dir / f"{safe_stem(key, idx)}{ext}").write_bytes(blob)
                return
            else:
                raise ValueError("Missing movie.binary or movie.spec")
    else:
        movie = svga_pb2.MovieEntity()
        movie.ParseFromString(zlib.decompress(raw))

    audio_keys = {a.audioKey for a in movie.audios if a.audioKey}
    for idx, (key, blob) in enumerate(movie.images.items()):
        ext = detect_extension(blob, key in audio_keys)
        stem = safe_stem(key, idx)
        filename = stem if stem.lower().endswith(ext) else f"{stem}{ext}"
        (out_dir / filename).write_bytes(blob)


if __name__ == "__main__":
    extract_assets(Path(sys.argv[1]), Path(sys.argv[2]))

Step 4: Pack a transparent PNG sequence into SVGA 2.0

If your team renders transparent PNG frames from Blender, Cinema 4D, or a headless pipeline, the script below sorts frames naturally (frame_2.png before frame_10.png), deduplicates identical frames via SHA-256, builds valid FrameEntity matrices, and compresses the MovieEntity binary with zlib level 9:

import hashlib
import re
import sys
import zlib
from pathlib import Path
from PIL import Image

import svga_pb2


def natural_key(path: Path) -> list[int | str]:
    return [int(part) if part.isdigit() else part.lower() for part in re.split(r"(\d+)", path.name)]


def pack_png_sequence(frames_dir: Path, out_file: Path, fps: int = 24) -> None:
    png_files = sorted(frames_dir.glob("*.png"), key=natural_key)
    if not png_files:
        raise FileNotFoundError(f"No PNG files found in {frames_dir}")

    with Image.open(png_files[0]) as first_img:
        canvas_w, canvas_h = first_img.size

    movie = svga_pb2.MovieEntity()
    movie.version = "2.0.0"
    movie.params.viewBoxWidth = float(canvas_w)
    movie.params.viewBoxHeight = float(canvas_h)
    movie.params.fps = fps
    movie.params.frames = len(png_files)

    digest_to_key: dict[str, str] = {}
    key_frames: dict[str, list[int]] = {}
    key_dims: dict[str, tuple[int, int]] = {}

    for frame_idx, png_path in enumerate(png_files):
        blob = png_path.read_bytes()
        with Image.open(png_path) as im:
            w, h = im.size
        digest = hashlib.sha256(blob).hexdigest()
        if digest not in digest_to_key:
            key = f"frame_{len(digest_to_key):04d}"
            digest_to_key[digest] = key
            movie.images[key] = blob
            key_frames[key] = []
            key_dims[key] = (w, h)
        key_frames[digest_to_key[digest]].append(frame_idx)

    total_frames = len(png_files)
    for key, active_indices in key_frames.items():
        active_set = set(active_indices)
        w, h = key_dims[key]
        sprite = movie.sprites.add()
        sprite.imageKey = key
        for idx in range(total_frames):
            frame = sprite.frames.add()
            if idx in active_set:
                frame.alpha = 1.0
                frame.layout.x = 0.0
                frame.layout.y = 0.0
                frame.layout.width = float(w)
                frame.layout.height = float(h)
                frame.transform.a = 1.0
                frame.transform.d = 1.0

    compressed = zlib.compress(movie.SerializeToString(), level=9)
    out_file.write_bytes(compressed)


if __name__ == "__main__":
    pack_png_sequence(Path(sys.argv[1]), Path(sys.argv[2]), fps=int(sys.argv[3]) if len(sys.argv) > 3 else 24)

Two implementation details matter in production:

  • Always initialize transform.a = 1.0 and transform.d = 1.0: in Proto3, unset float fields default to 0.0. Once frame.transform is accessed, leaving a and d at zero collapses the sprite to zero scale in native and Web players.
  • Keep len(sprite.frames) == movie.params.frames: inactive frames are empty FrameEntity records (alpha == 0), which take negligible space after zlib compression while guaranteeing consistent behavior across iOS, Android, Web Classic, Web Lite, and Flutter.

Step 5: Disambiguation and next steps

Searching for svga python frequently surfaces unrelated hardware and vector packages:

  1. ON Semiconductor PYTHON CMOS SVGA sensors: industrial 800 × 600 camera sensors branded as PYTHON SVGA — unrelated to .svga animation files.
  2. svglib: a Python library that renders static .svg graphics to ReportLab/PDF, not binary .svga animations.
  3. Super VGA (800 × 600 display standard): legacy monitor resolution sharing the SVGA acronym.

After generating or modifying an .svga file, drop it into the SVGA Online Player to verify alpha edges and playback timing, review the SVGA compression guide if RGBA memory or byte size is too high, or check the full schema in the SVGA format specification.