Spaces:
Running
Running
Update: ≤3s WeChat-compatible live photos, sets 3 & 4 (fill-in-the-blank), in-browser maker tool
0daf81d verified Download source/frontend/src/lib/live/encode.ts from Ethscriptions/eths: direct link, hf CLI and curl.
- Browser
- Download file 5.72 kB
-
https://huggingface.co/spaces/Ethscriptions/eths/resolve/main/source/frontend/src/lib/live/encode.ts
- Command line
-
hf download hf://spaces/Ethscriptions/eths/source/frontend/src/lib/live/encode.ts
-
curl -L -o encode.ts https://huggingface.co/spaces/Ethscriptions/eths/resolve/main/source/frontend/src/lib/live/encode.ts
5.72 kB
| // Encode the rendered animation into an Apple Live Photo pair (JPG + MOV with audio), entirely in the browser. | |
| // Video: WebCodecs H.264 when available (fast, hardware), otherwise libx264 in ffmpeg.wasm. | |
| // Audio: AAC via ffmpeg.wasm. Container: QuickTime, then Live Photo metadata is written by livephoto.ts. | |
| import { FFmpeg } from '@ffmpeg/ffmpeg' | |
| import { CardRenderer, FPS, H, W } from './renderer' | |
| import { newIdentifier, writeLiveJpeg, writeLiveMov } from './livephoto' | |
| let ffPromise: Promise<FFmpeg> | null = null | |
| export function getFFmpeg(): Promise<FFmpeg> { | |
| if (ffPromise) return ffPromise | |
| ffPromise = (async () => { | |
| const base = new URL(`${import.meta.env.BASE_URL}ffmpeg/`, window.location.href).href | |
| const ff = new FFmpeg() | |
| await ff.load({ classWorkerURL: `${base}worker.js`, coreURL: `${base}ffmpeg-core.js`, wasmURL: `${base}ffmpeg-core.wasm` }) | |
| return ff | |
| })() | |
| ffPromise.catch(() => { | |
| ffPromise = null | |
| }) | |
| return ffPromise | |
| } | |
| export interface LiveResult { | |
| id: string | |
| jpg: Uint8Array | |
| mov: Uint8Array | |
| coverURL: string | |
| videoURL: string | |
| duration: number | |
| encoder: 'webcodecs' | 'x264' | |
| } | |
| type Progress = (stage: string, ratio: number) => void | |
| async function pickAvcConfig(): Promise<VideoEncoderConfig | null> { | |
| if (typeof window === 'undefined' || typeof window.VideoEncoder !== 'function') return null | |
| for (const codec of ['avc1.640028', 'avc1.4d0028', 'avc1.42e028', 'avc1.42001f']) { | |
| const cfg: VideoEncoderConfig = { | |
| codec, width: W, height: H, bitrate: 10_000_000, framerate: FPS, latencyMode: 'quality', | |
| avc: { format: 'annexb' } as AvcEncoderConfig, | |
| } | |
| try { | |
| const s = await VideoEncoder.isConfigSupported(cfg) | |
| if (s.supported) return cfg | |
| } catch { | |
| /* try next */ | |
| } | |
| } | |
| return null | |
| } | |
| function toBlob(c: HTMLCanvasElement, type: string, q?: number): Promise<Blob> { | |
| return new Promise((res, rej) => c.toBlob((b) => (b ? res(b) : rej(new Error('导出图片失败'))), type, q)) | |
| } | |
| export async function encodeLive(renderer: CardRenderer, wav: Uint8Array, onProgress: Progress, forceX264 = false): Promise<LiveResult> { | |
| const T = renderer.T | |
| const cv = document.createElement('canvas') | |
| cv.width = W | |
| cv.height = H | |
| const ctx = cv.getContext('2d', { alpha: false })! | |
| onProgress('加载编码器', 0) | |
| const ff = await getFFmpeg() | |
| let cover: Blob | null = null | |
| const cfg = forceX264 ? null : await pickAvcConfig() | |
| let encoder: LiveResult['encoder'] = 'x264' | |
| if (cfg) { | |
| encoder = 'webcodecs' | |
| const chunks: Uint8Array[] = [] | |
| let err: unknown = null | |
| const ve = new VideoEncoder({ | |
| output: (chunk) => { | |
| const b = new Uint8Array(chunk.byteLength) | |
| chunk.copyTo(b) | |
| chunks.push(b) | |
| }, | |
| error: (e) => { | |
| err = e | |
| }, | |
| }) | |
| ve.configure(cfg) | |
| for (let i = 0; i < T.nf; i++) { | |
| renderer.frame(ctx, i) | |
| if (i === T.coverFrame) cover = await toBlob(cv, 'image/jpeg', 0.95) | |
| const vf = new VideoFrame(cv, { timestamp: Math.round((i * 1e6) / FPS), duration: Math.round(1e6 / FPS) }) | |
| ve.encode(vf, { keyFrame: i % 60 === 0 }) | |
| vf.close() | |
| while (ve.encodeQueueSize > 4) await new Promise((r) => setTimeout(r, 4)) | |
| if (err) throw err | |
| if (i % 3 === 0) onProgress('渲染画面', i / T.nf) | |
| } | |
| await ve.flush() | |
| ve.close() | |
| if (err) throw err | |
| const total = chunks.reduce((a, c) => a + c.length, 0) | |
| const h264 = new Uint8Array(total) | |
| let o = 0 | |
| for (const c of chunks) { | |
| h264.set(c, o) | |
| o += c.length | |
| } | |
| await ff.writeFile('v.h264', h264) | |
| } else { | |
| for (let i = 0; i < T.nf; i++) { | |
| renderer.frame(ctx, i) | |
| const jpg = await toBlob(cv, 'image/jpeg', 0.92) | |
| if (i === T.coverFrame) cover = await toBlob(cv, 'image/jpeg', 0.95) | |
| await ff.writeFile(`f${String(i).padStart(4, '0')}.jpg`, new Uint8Array(await jpg.arrayBuffer())) | |
| if (i % 3 === 0) onProgress('渲染画面', (i / T.nf) * 0.5) | |
| } | |
| } | |
| await ff.writeFile('a.wav', wav) | |
| const onFF = ({ progress }: { progress: number }) => onProgress(encoder === 'webcodecs' ? '合成视频' : '编码视频', encoder === 'webcodecs' ? Math.min(1, progress) : 0.5 + 0.5 * Math.min(1, progress)) | |
| ff.on('progress', onFF) | |
| const common = ['-i', 'a.wav', '-map', '0:v:0', '-map', '1:a:0', '-c:a', 'aac', '-b:a', '128k', '-ar', '44100', '-ac', '1', | |
| '-shortest', '-map_metadata', '-1', '-movie_timescale', '60000', '-video_track_timescale', '30000', '-f', 'mov', 'out.mov'] | |
| const args = encoder === 'webcodecs' | |
| ? ['-fflags', '+genpts', '-framerate', String(FPS), '-i', 'v.h264', ...common.slice(0, 6), '-c:v', 'copy', ...common.slice(6)] | |
| : ['-framerate', String(FPS), '-i', 'f%04d.jpg', ...common.slice(0, 6), '-c:v', 'libx264', '-preset', 'veryfast', '-crf', '19', | |
| '-pix_fmt', 'yuv420p', '-profile:v', 'high', ...common.slice(6)] | |
| const code = await ff.exec(args) | |
| ff.off('progress', onFF) | |
| if (code !== 0) throw new Error('视频合成失败') | |
| const raw = (await ff.readFile('out.mov')) as Uint8Array | |
| // clean the virtual FS | |
| for (const f of await ff.listDir('/')) { | |
| if (!f.isDir && /^(f\d{4}\.jpg|v\.h264|a\.wav|out\.mov)$/.test(f.name)) await ff.deleteFile(f.name) | |
| } | |
| onProgress('写入实况标识', 1) | |
| const id = newIdentifier() | |
| const mov = writeLiveMov(raw, id, T.coverFrame / FPS, T.nf / FPS, FPS) | |
| const jpg = writeLiveJpeg(new Uint8Array(await cover!.arrayBuffer()), id, W, H) | |
| return { | |
| id, jpg, mov, duration: T.nf / FPS, encoder, | |
| coverURL: URL.createObjectURL(new Blob([jpg as BlobPart], { type: 'image/jpeg' })), | |
| videoURL: URL.createObjectURL(new Blob([mov as BlobPart], { type: 'video/mp4' })), | |
| } | |
| } | |