The open creative studio on ComfyUI: images, video, 3D and audio on open weights, on your own GPU or the cloud. Camera motions, effects, apps, Cinema, Layers, Image to 3D and an AI agent.
TypeScript ai-videocomfyuicreative-toolsgenerative-aiideogramimage-generationimage-to-3dimage-to-videoltx-videominimax-h3nextjsopen-sourceopen-weightsqwen-imagetext-to-imagevideo-generationwan
Blockout to film: an MP4 writer for the browser's renders, and the video encoders in one module
Claude81ac119c87ab
diff --git a/src/components/cinema/scene-engine.ts b/src/components/cinema/scene-engine.tsindex 31b9bf06..bb2b6f1f 100644--- a/src/components/cinema/scene-engine.ts+++ b/src/components/cinema/scene-engine.ts@@ -4,7 +4,6 @@ import * as THREE from "three";import { GLTFLoader } from "three/examples/jsm/loaders/GLTFLoader.js";import { FullScreenQuad } from "three/examples/jsm/postprocessing/Pass.js";import { flyPoseOf, type FramePoses } from "@/lib/camera-path";-import { muxWebM, type EncodedFrame } from "@/lib/webm";import {LENS,blurScale,@@ -27,6 +26,7 @@ import {type Rect,} from "@/lib/scene3d";import type { SceneSource } from "./scene-actions";+import { encodeVp8, pathVideoType, recordWithMediaRecorder, vp8Supported } from "./video-encode";/*** The 3D scene viewer's renderer (three.js, loaded only when a scene opens): a MoGe mesh (GLB) or a point cloud@@ -203,100 +203,6 @@ function sampleVertices(root: THREE.Object3D, max = 80_000): Float32Array {return Float32Array.from(out);}-/** The type MediaRecorder records a path in when WebCodecs can't: MP4 (H.264) where it writes it, else WebM. Null: none. */-export function pathVideoType(): string | null {- if (typeof MediaRecorder === "undefined") return null;- return ["video/mp4;codecs=avc1.42E01E", "video/mp4", "video/webm;codecs=vp9", "video/webm;codecs=vp8", "video/webm"].find((t) => MediaRecorder.isTypeSupported(t)) ?? null;-}--const VP8 = (width: number, height: number, fps: number): VideoEncoderConfig => ({ codec: "vp8", width, height, bitrate: 8_000_000, framerate: fps });--/** WebCodecs can encode VP8 at this size here. */-async function vp8Supported(width: number, height: number, fps: number): Promise<boolean> {- if (typeof VideoEncoder === "undefined" || typeof VideoFrame === "undefined") return false;- try {- return !!(await VideoEncoder.isConfigSupported(VP8(width, height, fps))).supported;- } catch {- return false;- }-}--/**- * `count` frames of two streams (`draw(i)` gives frame i of each) encoded with WebCodecs and written as two WebM files:- * every frame kept, frame i at i / fps, a keyframe each second.- */-async function encodeVp8(count: number, width: number, height: number, fps: number, outputs: number, draw: (i: number) => ImageData[]): Promise<Uint8Array[]> {- const chunks: EncodedFrame[][] = Array.from({ length: outputs }, () => []);- let failure: unknown;- const encoders = chunks.map((_, k) => {- const e = new VideoEncoder({- output: (chunk) => {- const data = new Uint8Array(chunk.byteLength);- chunk.copyTo(data);- chunks[k].push({ data, key: chunk.type === "key" });- },- error: (err) => (failure = err),- });- e.configure(VP8(width, height, fps));- return e;- });- try {- const step = 1e6 / fps;- for (let i = 0; i < count; i++) {- const images = draw(i);- images.forEach((img, k) => {- const f = new VideoFrame(img.data, { format: "RGBA", codedWidth: width, codedHeight: height, timestamp: Math.round(i * step), duration: Math.round(step) });- encoders[k].encode(f, { keyFrame: i % Math.max(1, Math.round(fps)) === 0 });- f.close();- });- if (failure) throw failure;- // Let the encoders and the page breathe (the progress label repaints).- while (encoders.some((e) => e.encodeQueueSize > 4)) await new Promise((r) => setTimeout(r, 5));- if (i % 4 === 3) await new Promise((r) => setTimeout(r, 0));- }- await Promise.all(encoders.map((e) => e.flush()));- if (failure) throw failure;- } finally {- encoders.forEach((e) => e.state !== "closed" && e.close());- }- if (chunks.some((c) => c.length !== count)) throw new Error(`The path render lost frames (${chunks[0].length} of ${count})`);- const track = { codec: "V_VP8" as const, width, height, fps };- return chunks.map((c) => muxWebM(track, c));-}--/** The fallback: a canvas per stream recorded with MediaRecorder, each frame handed over 1/fps apart. */-async function recordWithMediaRecorder(type: string, count: number, width: number, height: number, fps: number, outputs: number, draw: (i: number) => ImageData[]): Promise<Blob[]> {- const canvases = Array.from({ length: outputs }, () => Object.assign(document.createElement("canvas"), { width, height }));- const ctxs = canvases.map((c) => c.getContext("2d")!);- const streams = canvases.map((c) => c.captureStream(0));- const tracks = streams.map((s) => s.getVideoTracks()[0] as MediaStreamTrack & { requestFrame?: () => void });- const recorders = streams.map((s) => new MediaRecorder(s, { mimeType: type, videoBitsPerSecond: 8_000_000 }));- const chunks: Blob[][] = recorders.map(() => []);- const stopped = recorders.map((r, i) => {- r.ondataavailable = (e) => e.data.size && chunks[i].push(e.data);- return new Promise<void>((resolve) => (r.onstop = () => resolve()));- });- const wait = (ms: number) => new Promise((r) => setTimeout(r, ms));- const step = 1000 / Math.max(1, fps);- try {- recorders.forEach((r) => r.start());- await wait(step);- const t0 = performance.now();- for (let i = 0; i < count; i++) {- draw(i).forEach((img, k) => ctxs[k].putImageData(img, 0, 0));- tracks.forEach((t) => t.requestFrame?.());- await wait(Math.max(0, t0 + (i + 1) * step - performance.now()));- }- await wait(step);- } finally {- recorders.forEach((r) => r.state !== "inactive" && r.stop());- await Promise.all(stopped);- streams.forEach((s) => s.getTracks().forEach((t) => t.stop()));- }- const base = type.split(";")[0];- return chunks.map((c) => new Blob(c, { type: base }));-}-export class SceneEngine {info: SceneInfo | null = null;/** Called when the autofocus distance changes (scene units ≈ m). */diff --git a/src/components/cinema/video-encode.ts b/src/components/cinema/video-encode.tsnew file mode 100644index 00000000..59f2a6ba--- /dev/null+++ b/src/components/cinema/video-encode.ts@@ -0,0 +1,173 @@+"use client";++import { muxMp4 } from "@/lib/mp4";+import { muxWebM, type EncodedFrame } from "@/lib/webm";++/**+ * Frame-exact video from frames drawn in the browser (Cinema's fly path render, N7-5, and the blockout builder): WebCodecs+ * VP8 into WebM (what ComfyUI reads), WebCodecs H.264 into MP4 (what the cloud models read: Seedance 2.5 takes MP4 or+ * MOV), and MediaRecorder as the fallback where WebCodecs can't, which may drop a frame.+ */++/** The type MediaRecorder records a path in when WebCodecs can't: MP4 (H.264) where it writes it, else WebM. Null: none. */+export function pathVideoType(): string | null {+ if (typeof MediaRecorder === "undefined") return null;+ return ["video/mp4;codecs=avc1.42E01E", "video/mp4", "video/webm;codecs=vp9", "video/webm;codecs=vp8", "video/webm"].find((t) => MediaRecorder.isTypeSupported(t)) ?? null;+}++const VP8 = (width: number, height: number, fps: number): VideoEncoderConfig => ({ codec: "vp8", width, height, bitrate: 8_000_000, framerate: fps });++/** WebCodecs can encode VP8 at this size here. */+export async function vp8Supported(width: number, height: number, fps: number): Promise<boolean> {+ if (typeof VideoEncoder === "undefined" || typeof VideoFrame === "undefined") return false;+ try {+ return !!(await VideoEncoder.isConfigSupported(VP8(width, height, fps))).supported;+ } catch {+ return false;+ }+}++/**+ * `count` frames of two streams (`draw(i)` gives frame i of each) encoded with WebCodecs and written as two WebM files:+ * every frame kept, frame i at i / fps, a keyframe each second.+ */+export async function encodeVp8(count: number, width: number, height: number, fps: number, outputs: number, draw: (i: number) => ImageData[]): Promise<Uint8Array[]> {+ const chunks: EncodedFrame[][] = Array.from({ length: outputs }, () => []);+ let failure: unknown;+ const encoders = chunks.map((_, k) => {+ const e = new VideoEncoder({+ output: (chunk) => {+ const data = new Uint8Array(chunk.byteLength);+ chunk.copyTo(data);+ chunks[k].push({ data, key: chunk.type === "key" });+ },+ error: (err) => (failure = err),+ });+ e.configure(VP8(width, height, fps));+ return e;+ });+ try {+ const step = 1e6 / fps;+ for (let i = 0; i < count; i++) {+ const images = draw(i);+ images.forEach((img, k) => {+ const f = new VideoFrame(img.data, { format: "RGBA", codedWidth: width, codedHeight: height, timestamp: Math.round(i * step), duration: Math.round(step) });+ encoders[k].encode(f, { keyFrame: i % Math.max(1, Math.round(fps)) === 0 });+ f.close();+ });+ if (failure) throw failure;+ // Let the encoders and the page breathe (the progress label repaints).+ while (encoders.some((e) => e.encodeQueueSize > 4)) await new Promise((r) => setTimeout(r, 5));+ if (i % 4 === 3) await new Promise((r) => setTimeout(r, 0));+ }+ await Promise.all(encoders.map((e) => e.flush()));+ if (failure) throw failure;+ } finally {+ encoders.forEach((e) => e.state !== "closed" && e.close());+ }+ if (chunks.some((c) => c.length !== count)) throw new Error(`The path render lost frames (${chunks[0].length} of ${count})`);+ const track = { codec: "V_VP8" as const, width, height, fps };+ return chunks.map((c) => muxWebM(track, c));+}++/** The fallback: a canvas per stream recorded with MediaRecorder, each frame handed over 1/fps apart. */+export async function recordWithMediaRecorder(type: string, count: number, width: number, height: number, fps: number, outputs: number, draw: (i: number) => ImageData[]): Promise<Blob[]> {+ const canvases = Array.from({ length: outputs }, () => Object.assign(document.createElement("canvas"), { width, height }));+ const ctxs = canvases.map((c) => c.getContext("2d")!);+ const streams = canvases.map((c) => c.captureStream(0));+ const tracks = streams.map((s) => s.getVideoTracks()[0] as MediaStreamTrack & { requestFrame?: () => void });+ const recorders = streams.map((s) => new MediaRecorder(s, { mimeType: type, videoBitsPerSecond: 8_000_000 }));+ const chunks: Blob[][] = recorders.map(() => []);+ const stopped = recorders.map((r, i) => {+ r.ondataavailable = (e) => e.data.size && chunks[i].push(e.data);+ return new Promise<void>((resolve) => (r.onstop = () => resolve()));+ });+ const wait = (ms: number) => new Promise((r) => setTimeout(r, ms));+ const step = 1000 / Math.max(1, fps);+ try {+ recorders.forEach((r) => r.start());+ await wait(step);+ const t0 = performance.now();+ for (let i = 0; i < count; i++) {+ draw(i).forEach((img, k) => ctxs[k].putImageData(img, 0, 0));+ tracks.forEach((t) => t.requestFrame?.());+ await wait(Math.max(0, t0 + (i + 1) * step - performance.now()));+ }+ await wait(step);+ } finally {+ recorders.forEach((r) => r.state !== "inactive" && r.stop());+ await Promise.all(stopped);+ streams.forEach((s) => s.getTracks().forEach((t) => t.stop()));+ }+ const base = type.split(";")[0];+ return chunks.map((c) => new Blob(c, { type: base }));+}++/** The H.264 profiles tried in order (baseline 3.1 holds 1280 × 720 at 30 fps; main and high 4.0 more). */+const AVC_CODECS = ["avc1.42001f", "avc1.4d0028", "avc1.640028"];+const AVC = (codec: string, width: number, height: number, fps: number): VideoEncoderConfig => ({ codec, width, height, bitrate: 8_000_000, framerate: fps, avc: { format: "avc" } });++/** The H.264 profile WebCodecs encodes at this size here, or null (Chromium without proprietary codecs, Firefox). */+export async function avcCodec(width: number, height: number, fps: number): Promise<string | null> {+ if (typeof VideoEncoder === "undefined" || typeof VideoFrame === "undefined") return null;+ for (const c of AVC_CODECS) {+ try {+ if ((await VideoEncoder.isConfigSupported(AVC(c, width, height, fps))).supported) return c;+ } catch {}+ }+ return null;+}++/** `count` frames (`draw(i)` gives frame i) encoded with WebCodecs H.264 and written as one MP4: every frame kept. */+export async function encodeMp4(codec: string, count: number, width: number, height: number, fps: number, draw: (i: number) => ImageData): Promise<Uint8Array> {+ const frames: EncodedFrame[] = [];+ let avcC: Uint8Array | null = null;+ let failure: unknown;+ const e = new VideoEncoder({+ output: (chunk, meta) => {+ const d = meta?.decoderConfig?.description;+ if (d && !avcC) avcC = d instanceof ArrayBuffer ? new Uint8Array(d.slice(0)) : new Uint8Array((d as ArrayBufferView).buffer.slice((d as ArrayBufferView).byteOffset, (d as ArrayBufferView).byteOffset + (d as ArrayBufferView).byteLength));+ const data = new Uint8Array(chunk.byteLength);+ chunk.copyTo(data);+ frames.push({ data, key: chunk.type === "key" });+ },+ error: (err) => (failure = err),+ });+ e.configure(AVC(codec, width, height, fps));+ try {+ const step = 1e6 / fps;+ for (let i = 0; i < count; i++) {+ const img = draw(i);+ const f = new VideoFrame(img.data, { format: "RGBA", codedWidth: width, codedHeight: height, timestamp: Math.round(i * step), duration: Math.round(step) });+ e.encode(f, { keyFrame: i % Math.max(1, Math.round(fps)) === 0 });+ f.close();+ if (failure) throw failure;+ while (e.encodeQueueSize > 4) await new Promise((r) => setTimeout(r, 5));+ if (i % 4 === 3) await new Promise((r) => setTimeout(r, 0));+ }+ await e.flush();+ if (failure) throw failure;+ } finally {+ if (e.state !== "closed") e.close();+ }+ if (frames.length !== count) throw new Error(`The render lost frames (${frames.length} of ${count})`);+ if (!avcC) throw new Error("The H.264 encoder gave no decoder description");+ return muxMp4({ width, height, fps, avcC }, frames);+}++/**+ * One stream of `count` frames as the best video this browser makes: MP4 (H.264) when `preferMp4` and WebCodecs can,+ * else WebM (VP8), else MediaRecorder's own type. Frame-exact except on the MediaRecorder fallback.+ */+export async function encodeFrames(count: number, width: number, height: number, fps: number, draw: (i: number) => ImageData, preferMp4 = false): Promise<{ blob: Blob; type: string; exact: boolean }> {+ const avc = preferMp4 ? await avcCodec(width, height, fps) : null;+ if (avc) return { blob: new Blob([(await encodeMp4(avc, count, width, height, fps, draw)) as BlobPart], { type: "video/mp4" }), type: "video/mp4", exact: true };+ if (await vp8Supported(width, height, fps)) {+ const [a] = await encodeVp8(count, width, height, fps, 1, (i) => [draw(i)]);+ return { blob: new Blob([a as BlobPart], { type: "video/webm" }), type: "video/webm", exact: true };+ }+ const type = pathVideoType();+ if (!type) throw new Error("This browser can't record video — try Chrome or Edge, or upload a render from your 3D app");+ const [b] = await recordWithMediaRecorder(type, count, width, height, fps, 1, (i) => [draw(i)]);+ return { blob: b, type: type.split(";")[0], exact: false };+}diff --git a/src/lib/mp4.ts b/src/lib/mp4.tsnew file mode 100644index 00000000..340e9ccd--- /dev/null+++ b/src/lib/mp4.ts@@ -0,0 +1,111 @@+/**+ * A minimal MP4 writer for one H.264 video track of already-encoded frames (WebCodecs AVC chunks in "avc" format, with+ * the encoder's avcC as the decoder description). Blockout to film renders its grey box in the browser, and the cloud+ * models that read it (Seedance 2.5's reference clips: MP4 or MOV) don't take WebM. ISO base media file layout: ftyp,+ * then moov first (so a player or a provider can start before the end), then one mdat holding every frame in one chunk.+ * Frames are in decode order with no reordering (WebCodecs' H.264 encoder makes no B-frames), so no composition offsets.+ * Pure: no DOM.+ */++import type { EncodedFrame } from "./webm";++export interface Mp4Track {+ width: number;+ height: number;+ fps: number;+ /** The avcC record (VideoDecoderConfig.description from the encoder's first chunk). */+ avcC: Uint8Array;+}++/** Ticks a second: 90 kHz divides 16, 24, 25, 30 and 60 fps exactly. */+const TIMESCALE = 90_000;++const enc = new TextEncoder();++function u32(n: number): Uint8Array {+ const b = new Uint8Array(4);+ new DataView(b.buffer).setUint32(0, Math.max(0, Math.round(n)) >>> 0);+ return b;+}+function u16(n: number): Uint8Array {+ const b = new Uint8Array(2);+ new DataView(b.buffer).setUint16(0, Math.max(0, Math.round(n)) & 0xffff);+ return b;+}+const zeros = (n: number) => new Uint8Array(n);++function concat(parts: Uint8Array[]): Uint8Array {+ const out = new Uint8Array(parts.reduce((n, p) => n + p.length, 0));+ let at = 0;+ for (const p of parts) {+ out.set(p, at);+ at += p.length;+ }+ return out;+}++/** A box: size, four-character type, body. */+function box(type: string, ...body: Uint8Array[]): Uint8Array {+ const data = concat(body);+ return concat([u32(data.length + 8), enc.encode(type), data]);+}+/** A full box: a box whose body starts with version (1 byte) and flags (3 bytes). */+const full = (type: string, version: number, flags: number, ...body: Uint8Array[]) => box(type, new Uint8Array([version, (flags >> 16) & 255, (flags >> 8) & 255, flags & 255]), ...body);++/** The identity transform every track header and the movie header carry. */+const MATRIX = concat([u32(0x00010000), u32(0), u32(0), u32(0), u32(0x00010000), u32(0), u32(0), u32(0), u32(0x40000000)]);++function moov(track: Mp4Track, frames: readonly EncodedFrame[], dataOffset: number): Uint8Array {+ const delta = Math.round(TIMESCALE / Math.max(1, track.fps));+ const mediaDuration = delta * frames.length;+ const movieMs = Math.round((frames.length * 1000) / Math.max(1, track.fps));+ const mvhd = full("mvhd", 0, 0, u32(0), u32(0), u32(1000), u32(movieMs), u32(0x00010000), u16(0x0100), zeros(10), MATRIX, zeros(24), u32(2));+ const tkhd = full("tkhd", 0, 3, u32(0), u32(0), u32(1), u32(0), u32(movieMs), zeros(8), u16(0), u16(0), u16(0), u16(0), MATRIX, u32(track.width * 65536), u32(track.height * 65536));+ const mdhd = full("mdhd", 0, 0, u32(0), u32(0), u32(TIMESCALE), u32(mediaDuration), u16(0x55c4), u16(0));+ const hdlr = full("hdlr", 0, 0, u32(0), enc.encode("vide"), zeros(12), enc.encode("VideoHandler\0"));+ const vmhd = full("vmhd", 0, 1, u16(0), zeros(6));+ const dinf = box("dinf", full("dref", 0, 0, u32(1), full("url ", 0, 1)));+ const avc1 = box(+ "avc1",+ zeros(6),+ u16(1),+ zeros(16),+ u16(track.width),+ u16(track.height),+ u32(0x00480000),+ u32(0x00480000),+ u32(0),+ u16(1),+ zeros(32),+ u16(0x0018),+ u16(0xffff),+ box("avcC", track.avcC),+ );+ const stsd = full("stsd", 0, 0, u32(1), avc1);+ const stts = full("stts", 0, 0, u32(1), u32(frames.length), u32(delta));+ const keys = frames.flatMap((f, i) => (f.key ? [u32(i + 1)] : []));+ const stss = full("stss", 0, 0, u32(keys.length), ...keys);+ const stsc = full("stsc", 0, 0, u32(1), u32(1), u32(frames.length), u32(1));+ const stsz = full("stsz", 0, 0, u32(0), u32(frames.length), ...frames.map((f) => u32(f.data.length)));+ const stco = full("stco", 0, 0, u32(1), u32(dataOffset));+ const stbl = box("stbl", stsd, stts, stss, stsc, stsz, stco);+ const minf = box("minf", vmhd, dinf, stbl);+ const mdia = box("mdia", mdhd, hdlr, minf);+ const trak = box("trak", tkhd, mdia);+ return box("moov", mvhd, trak);+}++/**+ * One MP4 file of `frames` (H.264, AVCC length-prefixed NAL units as WebCodecs gives them in "avc" format) at+ * `track.fps`: frame i is shown at i / fps and lasts 1 / fps, so a reader counts exactly frames.length frames.+ */+export function muxMp4(track: Mp4Track, frames: readonly EncodedFrame[]): Uint8Array {+ if (!frames.length) throw new Error("No frames to write");+ if (!frames[0].key) throw new Error("The first frame must be a keyframe");+ const ftyp = box("ftyp", enc.encode("isom"), u32(512), enc.encode("isomiso2avc1mp41"));+ // moov's size doesn't depend on the offset it records, so measure it once, then write it with the real offset.+ const size = moov(track, frames, 0).length;+ const offset = ftyp.length + size + 8;+ const mdat = box("mdat", ...frames.map((f) => f.data));+ return concat([ftyp, moov(track, frames, offset), mdat]);+}diff --git a/tests/mp4.test.ts b/tests/mp4.test.tsnew file mode 100644index 00000000..6e149789--- /dev/null+++ b/tests/mp4.test.ts@@ -0,0 +1,115 @@+import { execFileSync, spawnSync } from "node:child_process";+import fs from "node:fs";+import os from "node:os";+import path from "node:path";+import { describe, expect, it } from "vitest";+import { muxMp4 } from "@/lib/mp4";++/** The browser's MP4 writer (Blockout to film's grey-box render for the cloud): its boxes, and a real decoder reading it. */++const hasFfmpeg = spawnSync("ffmpeg", ["-version"]).status === 0 && spawnSync("ffprobe", ["-version"]).status === 0;++/** Boxes at the top level, or inside one: [type, start, size]. */+function boxes(b: Uint8Array, from = 0, to = b.length): [string, number, number][] {+ const out: [string, number, number][] = [];+ const v = new DataView(b.buffer, b.byteOffset, b.byteLength);+ for (let at = from; at + 8 <= to; ) {+ const size = v.getUint32(at);+ out.push([new TextDecoder().decode(b.subarray(at + 4, at + 8)), at, size]);+ if (size < 8) break;+ at += size;+ }+ return out;+}+function find(b: Uint8Array, pathTypes: string[]): [number, number] {+ let from = 0;+ let to = b.length;+ for (const t of pathTypes) {+ const hit = boxes(b, from, to).find(([x]) => x === t);+ if (!hit) throw new Error(`no ${t}`);+ from = hit[1] + 8;+ to = hit[1] + hit[2];+ }+ return [from, to];+}++describe("muxMp4", () => {+ const frames = [+ { data: Uint8Array.from([0, 0, 0, 2, 0x65, 1]), key: true },+ { data: Uint8Array.from([0, 0, 0, 3, 0x41, 2, 3]), key: false },+ { data: Uint8Array.from([0, 0, 0, 2, 0x41, 4]), key: false },+ ];+ const avcC = Uint8Array.from([1, 0x42, 0, 0x1f, 0xff, 0xe0, 0]);++ it("writes ftyp, moov, then mdat, with the sample table pointing at each frame", () => {+ const out = muxMp4({ width: 64, height: 48, fps: 24, avcC }, frames);+ expect(boxes(out).map(([t]) => t)).toEqual(["ftyp", "moov", "mdat"]);+ const v = new DataView(out.buffer);+ const [stco] = find(out, ["moov", "trak", "mdia", "minf", "stbl", "stco"]);+ const offset = v.getUint32(stco + 8);+ expect([...out.subarray(offset, offset + 6)]).toEqual([...frames[0].data]);+ const [stsz] = find(out, ["moov", "trak", "mdia", "minf", "stbl", "stsz"]);+ expect([v.getUint32(stsz + 8), v.getUint32(stsz + 12), v.getUint32(stsz + 16)]).toEqual([3, 6, 7]);+ const [stts] = find(out, ["moov", "trak", "mdia", "minf", "stbl", "stts"]);+ expect([v.getUint32(stts + 4), v.getUint32(stts + 8), v.getUint32(stts + 12)]).toEqual([1, 3, 3750]);+ const [stss] = find(out, ["moov", "trak", "mdia", "minf", "stbl", "stss"]);+ expect([v.getUint32(stss + 4), v.getUint32(stss + 8)]).toEqual([1, 1]);+ const [avc1] = find(out, ["moov", "trak", "mdia", "minf", "stbl", "stsd"]);+ expect(boxes(out, avc1 + 8)[0][0]).toBe("avc1");+ });++ it("refuses an empty list and a first frame that isn't a keyframe", () => {+ expect(() => muxMp4({ width: 64, height: 48, fps: 24, avcC }, [])).toThrow(/No frames/);+ expect(() => muxMp4({ width: 64, height: 48, fps: 24, avcC }, frames.slice(1))).toThrow(/keyframe/);+ });++ it.skipIf(!hasFfmpeg)("makes a file ffmpeg decodes frame for frame", () => {+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-mp4-"));+ try {+ const raw = path.join(dir, "in.h264");+ execFileSync("ffmpeg", ["-v", "error", "-f", "lavfi", "-i", "testsrc=size=64x48:rate=24", "-frames:v", "30", "-c:v", "libx264", "-bf", "0", "-g", "24", "-pix_fmt", "yuv420p", "-x264-params", "aud=1", "-f", "h264", raw]);+ const bytes = new Uint8Array(fs.readFileSync(raw));+ // Annex B → NAL units (3- or 4-byte start codes).+ const nals: Uint8Array[] = [];+ let start = -1;+ for (let i = 0; i + 3 <= bytes.length; i++) {+ if (bytes[i] === 0 && bytes[i + 1] === 0 && bytes[i + 2] === 1) {+ if (start >= 0) nals.push(bytes.subarray(start, i > 0 && bytes[i - 1] === 0 ? i - 1 : i));+ start = i + 3;+ i += 2;+ }+ }+ nals.push(bytes.subarray(start));+ const sps = nals.find((n) => (n[0] & 31) === 7)!;+ const pps = nals.find((n) => (n[0] & 31) === 8)!;+ const avc = Uint8Array.from([1, sps[1], sps[2], sps[3], 0xff, 0xe1, sps.length >> 8, sps.length & 255, ...sps, 1, pps.length >> 8, pps.length & 255, ...pps]);+ // Access units start at each delimiter (type 9); a frame is its NAL units, length-prefixed.+ const units: Uint8Array[][] = [];+ for (const n of nals) {+ const type = n[0] & 31;+ if (type === 9) units.push([]);+ else if (type !== 7 && type !== 8) units[units.length - 1].push(n);+ }+ const frames = units.map((u) => {+ const parts = u.flatMap((n) => [Uint8Array.from([n.length >>> 24, (n.length >> 16) & 255, (n.length >> 8) & 255, n.length & 255]), n]);+ const data = new Uint8Array(parts.reduce((s, p) => s + p.length, 0));+ let at = 0;+ for (const p of parts) {+ data.set(p, at);+ at += p.length;+ }+ return { data, key: u.some((n) => (n[0] & 31) === 5) };+ });+ expect(frames).toHaveLength(30);+ const file = path.join(dir, "out.mp4");+ fs.writeFileSync(file, muxMp4({ width: 64, height: 48, fps: 24, avcC: avc }, frames));+ const probe = JSON.parse(execFileSync("ffprobe", ["-v", "error", "-count_frames", "-select_streams", "v:0", "-show_entries", "stream=codec_name,width,height,nb_read_frames,r_frame_rate", "-of", "json", file]).toString());+ expect(probe.streams[0]).toMatchObject({ codec_name: "h264", width: 64, height: 48, nb_read_frames: "30", r_frame_rate: "24/1" });+ const decode = spawnSync("ffmpeg", ["-v", "error", "-i", file, "-f", "null", "-"]);+ expect(decode.status).toBe(0);+ expect(decode.stderr.toString()).toBe("");+ } finally {+ fs.rmSync(dir, { recursive: true, force: true });+ }+ });+});