TL;DR(要点)
- npm に公式
@svga/cliやsvga-converterCLI は存在しません:類似名の非公式パッケージに注意してください。従来のコミュニティ CLIvideo-to-svgaは SVGA 1.x(ZIP +movie.spec)を出力するため、SVGAPlayer-Web-Lite(svga)やflutter_svgaでは再生できません。 - 約 60 行の純粋な Node.js で SVGA 2.0 を構築可能:
pako、protobufjs、公式svga.protoを使えば、C++ 画像ライブラリなしで自然順ソートと SHA-256 重複排除付き SVGA 2.0 パッカーを実装できます。 - CI/CD ゲートで肥大化と非互換を自動ブロック:デプロイ前にファイルサイズ上限、RGBA メモリ(
∑ w × h × 4)、1.x 禁止、未参照の孤立キーを検査できます。 - FFmpeg または CLI 不要のブラウザー変換:動画からの連番抽出には FFmpeg を利用でき、手元で今すぐ変換したい場合はブラウザー完結の SVGA フォーマット変換ハブ が使えます。
自動化手段の比較
| 用途 | 推奨ツール構成 | 出力バージョン | 向いている場面 |
|---|---|---|---|
| Node.js ビルド・CI/CD パイプライン | pako + protobufjs + svga.proto |
SVGA 2.0 | リポジトリの自動変換・容量チェック |
| Python・Blender 連携 | protobuf + Pillow + zlib |
SVGA 2.0 | Python SVGA 実践ガイド 参照 |
| 旧版 1.x の簡易検証 | npx video-to-svga(MP4 → SVGA) |
SVGA 1.x | 1.x 互換確認のみ(Web Lite 非対応) |
| CLI 不要のブラウザー変換 | SVGA フォーマット変換ハブ | SVGA 2.0 | 環境構築なしでローカル完結変換 |
ステップ 1:pako・protobufjs と svga.proto を用意する
Node.js 18 以降のプロジェクトに 2 つの依存関係を追加し、svga.proto を配置します。
npm install pako protobufjs
curl -fsSLO https://svga.dev/assets/svga/svga.proto
以下のスクリプトは .mjs 拡張子で保存するか、package.json に "type": "module" を設定して実行します。
ステップ 2:透過 PNG 連番から SVGA 2.0 を生成する Node.js スクリプト
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
ステップ 3:CI/CD リリース前チェックゲート
ci-gate-svga.mjs を CI に組み込むと、SVGA 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 を含む場合は SVGA フォーマット仕様 に沿ってヘッダー解析を追加するか、先に SVGA オンライン圧縮ツール で整理してください。
ステップ 4:FFmpeg で透過動画・デュアルチャンネル MP4 から連番を抽出
1. ProRes 4444 .mov / VP9 透過 .webm から RGBA 連番を抽出
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
ステップ 5:CLI 不要のブラウザー完結フロー
ローカル環境構築を行わずに変換したい場合は、ファイル送信なしでブラウザー内だけで完結する次のツールを利用できます。
- PNG 連番 / ZIP → SVGA 2.0:PNG 連番変換 で
__MACOSX除外、自然順ソート、重複排除、PNG-8 量子化を実行。 - MP4 / WebM → SVGA 2.0:動画変換 で FPS・最大幅・黒抜き・クロマキー・デュアルチャンネル Alpha 合成を設定。
- 品質と容量の仕上げ:オンラインプレーヤー で透明エッジを確認し、必要に応じて SVGA オンライン圧縮ツール で軽量化します。
