TL;DR(核心结论)
- npm 上没有官方
@svga/cli或svga-converter命令行工具:安装同名占位包无法获得官方打包器;早期社区工具video-to-svga默认输出 SVGA 1.x(ZIP +movie.spec),在SVGAPlayer-Web-Lite(svga)与flutter_svga中无法直接播放。 - 约 60 行纯 Node.js 代码即可稳定输出 SVGA 2.0:利用
pako、protobufjs与官方svga.proto,结合 SHA-256 去重与Intl.Collator自然数字排序,无需原生 C++ 图形库即可直接从透明 PNG 序列帧构建 SVGA 2.0。 - CI/CD 门禁可在合入前拦截超标资产:在构建脚本中校验单文件字节上限、解码后 RGBA 内存(
∑ w × h × 4)、禁用 1.x 格式并告警未引用的孤儿位图。 - FFmpeg + 浏览器零命令行双路径:服务端批处理用 FFmpeg 提取透明或双通道视频帧;个人或设计师日常转换可直接使用免安装的浏览器端 SVGA 格式转换中心。
自动化方案选型对照
| 使用场景 | 推荐工具链 | 输出版本 | 适用环境 |
|---|---|---|---|
| Node.js 服务 / GitHub Actions 批处理打包 | pako + protobufjs + svga.proto |
SVGA 2.0 | 服务端批处理、CI 构建、前端工程化脚本 |
| 已有 Python / Blender 渲染管线 | protobuf + Pillow + zlib |
SVGA 2.0 | 见 Python 解析与生成 SVGA 2.0 指南 |
| 旧版快速验证(仅兼容 1.x 播放器) | npx video-to-svga(参见 MP4 转 SVGA) |
SVGA 1.x | 仅限历史兼容测试,Web Lite 不支持 |
| 零命令行、免安装单次转换 | SVGA 格式转换中心 | SVGA 2.0 | 浏览器本地运行,不上传服务器 |
第一步:安装依赖并下载 svga.proto
在 Node.js 18+ ESM 项目中安装两个纯 JS 依赖,并拉取官方 svga.proto 协议文件:
npm install pako protobufjs
curl -fsSLO https://svga.dev/assets/svga/svga.proto
确认 package.json 已设置 "type": "module"(或将脚本保存为 .mjs 后缀)。
第二步:约 60 行 Node.js 脚本打包透明 PNG 序列帧为 SVGA 2.0
下面的 pack-svga2.mjs 直接解析 PNG 文件的 IHDR 块获取宽高,使用 Intl.Collator 确保 frame_2.png 排在 frame_10.png 之前,并通过 SHA-256 合并完全相同的静止帧,最终以 zlib 最高压缩等级写出标准 SVGA 2.0 文件:
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))
执行打包:
node pack-svga2.mjs ./frames ./dist/effect.svga 24
第三步:CI/CD 上线前自动门禁脚本
将下面的 ci-gate-svga.mjs 接入 GitHub Actions 或打包流程,自动拦截 1.x 文件、超大体积、高解码 RGBA 内存以及未引用的孤儿资源:
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.')
}
如果资产中包含 JPEG 或 WebP 位图,可参考 格式规范页 补充 SOF/VP8 尺寸头解析,或先通过 SVGA 在线压缩工作台 执行结构去重与 PNG-8 量化。
第四步:用 FFmpeg 抽取透明或双通道视频序列帧
1. 从透明通道视频(ProRes 4444 .mov / VP9 .webm)抽帧
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. 从左右双通道 MP4(左 RGB + 右灰度 Alpha)合成透明帧
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
第五步:零命令行浏览器替代工作流
如果团队成员不方便在本地配置 Node.js 或 FFmpeg,可以直接在浏览器本地完成相同流程(全部数据留在本机内存中计算):
- PNG 序列帧或 ZIP 直接打包为 SVGA 2.0:打开 SVGA 格式转换中心 — PNG 序列帧模式,支持过滤
__MACOSX、自然排序、去重与 PNG-8 压缩。 - MP4 / WebM 直接转 SVGA 2.0:打开 SVGA 格式转换中心 — 视频模式,支持设置帧率、尺寸上限、黑底抠图、绿幕去背及左右双通道 Alpha 合成。
- 打包后体积检查:转入 在线播放器 核对透明度与兼容标签,或打开 SVGA 在线压缩工作台 进一步瘦身。
