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를 조합하면 별도 네이티브 이미지 모듈 없이 자연 숫자 정렬과 SHA-256 중복 제거를 포함한 SVGA 2.0 패커를 구현할 수 있습니다. - CI/CD 게이트로 과대 파일 및 호환성 오류 차단: 병합 전 단계에서 최대 파일 바이트, 디코딩 RGBA 메모리(
∑ w × h × 4), 1.x 차단, 미참조 리소스를 자동 검사합니다. - FFmpeg 또는 무설치 브라우저 도구 병행: 서버 파이프라인에서는 FFmpeg로 투명/듀얼 채널 프레임을 추출하고, 단건 작업은 SVGA 포맷 변환 허브에서 CLI 없이 바로 처리할 수 있습니다.
자동화 도구 비교
| 사용 시나리오 | 권장 도구 | 출력 포맷 | 적합한 환경 |
|---|---|---|---|
| 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 플레이어 호환 확인 전용 |
| CLI 설치 없는 브라우저 변환 | SVGA 포맷 변환 허브 | SVGA 2.0 | 파일 업로드 없이 로컬 브라우저 실행 |
1단계: pako, protobufjs 설치 및 svga.proto 준비
Node.js 18+ 프로젝트에 두 패키지를 설치하고 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으로 패킹하는 60줄 스크립트
아래 pack-svga2.mjs는 PNG IHDR 청크에서 직접 해상도를 읽고 Intl.Collator 자연 정렬(frame_2.png < frame_10.png)과 SHA-256 중복 제거를 적용한 뒤 zlib 압축 레벨 9로 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 단계에 연결하면 Web Lite용 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로 투명·듀얼 채널 영상에서 시퀀스 추출하기
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 + 우 흑백 알파)를 투명 PNG 시퀀스로 합성
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 온라인 압축기로 용량을 줄이세요.
