BLOG

Node.js CLI and CI automation for SVGA 2.0 pipelines

Node.js CLI and CI automation for SVGA 2.0 pipelines

TL;DR

  • There is no official @svga/cli or svga-converter CLI package on npm: avoid unverified packages claiming those names. Meanwhile, the community video-to-svga CLI outputs SVGA 1.x (ZIP + movie.spec), which SVGAPlayer-Web-Lite (svga) and flutter_svga do not support.
  • ~60 lines of Node.js produce compliant SVGA 2.0: using pako, protobufjs, and the official svga.proto, you can naturally sort PNG sequences, deduplicate identical frames via SHA-256, and deflate directly to SVGA 2.0 without native C++ image bindings.
  • Automate asset budgets in CI/CD: check maximum wire bytes, decoded RGBA texture memory (∑ w × h × 4), container version (rejecting 1.x ZIPs for Web Lite), and unreferenced orphan keys before merge.
  • Use FFmpeg for video frames or skip CLI completely: extract transparent or dual-channel MP4 frames with FFmpeg, or run zero-install local browser packing in the SVGA Format Converter Hub.

Automation options compared

Use case Recommended tooling Output format Best fit
Node.js build scripts & CI/CD pipelines pako + protobufjs + svga.proto SVGA 2.0 Headless asset pipelines & repository gates
Python / Blender headless rendering protobuf + Pillow + zlib SVGA 2.0 See SVGA Python guide
Legacy quick 1.x testing npx video-to-svga (see MP4 to SVGA) SVGA 1.x Legacy players only; rejected by Web Lite
Zero-CLI browser conversion SVGA Format Converter Hub SVGA 2.0 Designers & ad-hoc tasks with zero setup

Step 1: Install pako and protobufjs with svga.proto

In any Node.js 18+ project, install the two pure-JS dependencies and download svga.proto:

npm install pako protobufjs
curl -fsSLO https://svga.dev/assets/svga/svga.proto

Save the scripts below with an .mjs extension (or set "type": "module" in package.json).


Step 2: Pack transparent PNG sequences to SVGA 2.0 in ~60 lines

pack-svga2.mjs reads exact dimensions from each PNG’s IHDR chunk, uses Intl.Collator natural sorting so frame_2.png precedes frame_10.png, merges duplicate frames by SHA-256 digest, and compresses MovieEntity with pako.deflate(..., { level: 9 }):

import { createHash } from 'node:crypto'
import { readdirSync, readFileSync, writeFileSync } from 'node:fs'
import { join } from 'node:path'
import { deflate } from 'pako'
import protobuf from 'protobufjs'

const collator = new Intl.Collator(undefined, { numeric: true, sensitivity: 'base' })
const PNG_SIG = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])

function readPngSize(buf) {
  if (buf.length < 24 || !buf.subarray(0, 8).equals(PNG_SIG)) {
    throw new Error('Invalid PNG header')
  }
  return { width: buf.readUInt32BE(16), height: buf.readUInt32BE(20) }
}

export function packPngDirToSvga2(framesDir, outFile, fps = 24) {
  const files = readdirSync(framesDir)
    .filter((name) => name.toLowerCase().endsWith('.png') && !name.startsWith('.'))
    .sort(collator.compare)
  if (!files.length) throw new Error(`No PNG files found in ${framesDir}`)

  const root = protobuf.parse(readFileSync('svga.proto', 'utf8')).root
  const MovieEntity = root.lookupType('com.opensource.svga.MovieEntity')
  const images = {}
  const keyFrames = new Map()
  const digestToKey = new Map()
  let viewBoxWidth = 0
  let viewBoxHeight = 0

  files.forEach((name, index) => {
    const buf = readFileSync(join(framesDir, name))
    const size = readPngSize(buf)
    if (index === 0) ({ width: viewBoxWidth, height: viewBoxHeight } = size)
    const digest = createHash('sha256').update(buf).digest('hex')
    let key = digestToKey.get(digest)
    if (!key) {
      key = `frame_${String(digestToKey.size).padStart(4, '0')}`
      digestToKey.set(digest, key)
      images[key] = new Uint8Array(buf)
      keyFrames.set(key, { ...size, indices: new Set() })
    }
    keyFrames.get(key).indices.add(index)
  })

  const sprites = [...keyFrames.entries()].map(([imageKey, meta]) => ({
    imageKey,
    frames: Array.from({ length: files.length }, (_, idx) =>
      meta.indices.has(idx)
        ? {
            alpha: 1,
            layout: { x: 0, y: 0, width: meta.width, height: meta.height },
            transform: { a: 1, b: 0, c: 0, d: 1, tx: 0, ty: 0 }
          }
        : { alpha: 0 }
    )
  }))

  const payload = MovieEntity.encode(
    MovieEntity.create({
      version: '2.0.0',
      params: { viewBoxWidth, viewBoxHeight, fps, frames: files.length },
      images,
      sprites
    })
  ).finish()

  writeFileSync(outFile, deflate(payload, { level: 9 }))
  return { frames: files.length, uniqueImages: Object.keys(images).length, fps }
}

const [, , dir, out, fpsArg] = process.argv
if (dir && out) console.log(packPngDirToSvga2(dir, out, fpsArg ? Number(fpsArg) : 24))

Run it from your terminal:

node pack-svga2.mjs ./frames ./dist/effect.svga 24

Step 3: CI/CD pre-release budget gate script

Add ci-gate-svga.mjs to GitHub Actions or your asset build step to block SVGA 1.x ZIP files, oversized payloads, high RGBA memory footprints, and unreferenced orphan images while respecting imageKey, matteKey, and audioKey:

import { readdirSync, readFileSync } from 'node:fs'
import { join } from 'node:path'
import { inflate } from 'pako'
import protobuf from 'protobufjs'

const MAX_FILE_BYTES = 512 * 1024
const MAX_RGBA_BYTES = 32 * 1024 * 1024
const PNG_SIG = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])

const root = protobuf.parse(readFileSync('svga.proto', 'utf8')).root
const MovieEntity = root.lookupType('com.opensource.svga.MovieEntity')

function auditFile(filePath) {
  const raw = readFileSync(filePath)
  const issues = []

  if (raw.subarray(0, 4).equals(Buffer.from('PK\x03\x04'))) {
    return [`${filePath}: ZIP container (1.x or movie.binary) rejected when targeting Web Lite`]
  }
  if (raw.length > MAX_FILE_BYTES) {
    issues.push(`${filePath}: file size ${raw.length} B exceeds limit ${MAX_FILE_BYTES} B`)
  }

  const entity = MovieEntity.decode(inflate(raw))
  const usedKeys = new Set()
  for (const sprite of entity.sprites || []) {
    if (sprite.imageKey) usedKeys.add(sprite.imageKey)
    if (sprite.matteKey) usedKeys.add(sprite.matteKey)
  }
  const audioKeys = new Set((entity.audios || []).map((a) => a.audioKey).filter(Boolean))
  for (const key of audioKeys) usedKeys.add(key)

  let rgbaBytes = 0
  for (const [key, blob] of Object.entries(entity.images || {})) {
    if (!usedKeys.has(key)) issues.push(`${filePath}: orphan asset key "${key}"`)
    if (audioKeys.has(key)) continue
    const buf = Buffer.from(blob)
    if (buf.length >= 24 && buf.subarray(0, 8).equals(PNG_SIG)) {
      rgbaBytes += buf.readUInt32BE(16) * buf.readUInt32BE(20) * 4
    }
  }

  if (rgbaBytes > MAX_RGBA_BYTES) {
    issues.push(`${filePath}: decoded RGBA ${rgbaBytes} B exceeds limit ${MAX_RGBA_BYTES} B`)
  }
  return issues
}

const targetDir = process.argv[2] || './assets/svga'
const failures = readdirSync(targetDir)
  .filter((name) => name.endsWith('.svga'))
  .flatMap((name) => auditFile(join(targetDir, name)))

if (failures.length) {
  console.error(failures.join('\n'))
  process.exitCode = 1
} else {
  console.log('All SVGA assets passed CI budget gates.')
}

If your assets include JPEG or WebP images, extend the dimension check per the SVGA format specification or optimize them first with the SVGA Online Compressor.


Step 4: Extract transparent or dual-channel video frames with FFmpeg

1. ProRes 4444 .mov or VP9 alpha .webm to RGBA PNG sequence

mkdir -p frames
ffmpeg -i input.mov -vf "fps=24,scale='min(750,iw)':-1:flags=lanczos" -pix_fmt rgba frames/frame_%04d.png
node pack-svga2.mjs ./frames ./output.svga 24

2. Dual-channel MP4 (left RGB + right grayscale alpha) to transparent SVGA 2.0

mkdir -p frames
ffmpeg -i dual_channel.mp4 \
  -filter_complex "[0:v]crop=iw/2:ih:0:0,format=rgba[rgb];[0:v]crop=iw/2:ih:iw/2:0,format=gray[alpha];[rgb][alpha]alphamerge,fps=24" \
  -pix_fmt rgba frames/frame_%04d.png
node pack-svga2.mjs ./frames ./output-transparent.svga 24

Step 5: Zero-CLI browser workflow

When you do not want to install Node.js or FFmpeg locally, run the same conversion locally in your browser with zero file uploads:

  • PNG sequences or ZIPs → SVGA 2.0: open PNG Sequence to SVGA 2.0 to filter __MACOSX, sort frames naturally, deduplicate identical frames, and apply optional PNG-8 quantization.
  • MP4 / WebM → SVGA 2.0: open Video to SVGA 2.0 with configurable FPS, max resolution, black-luma keying, chroma-green keying, and dual-channel RGB+Alpha compositing.
  • Verify and shrink output: inspect your build in the SVGA Online Player or trim its footprint in the SVGA Online Compressor.