Canvix — Free & open-source graphic design tool. A community-built Canva alternative with a drag-and-drop editor, templates, shapes, text, images & one-click export. Works on desktop, tablet & mobile.
TypeScript canva-alternativecanvasdesigndesign-tooldrag-and-dropeditorgraphic-designkonvanextjsopen-sourcereactself-hostedtemplatestypescript
feat(v0.15): WebCodecs export pipeline — VideoEncoder + hand-rolled WebM muxer, deterministic frame pacing (R2)
Ashiq Hussain Mirf8b8d8e9e38b
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 8523610..da179e6 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -3,6 +3,54 @@All notable changes to Canvix will be documented in this file.The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).+## [0.15.1] — 2026-11-05++### Added++- **Rich content & export, part 2 — WebCodecs export pipeline (R2).**+ Silent designs export through `VideoEncoder` (VP9 with a VP8+ fallback, `latencyMode: 'quality'`, explicit bitrate) into a+ hand-rolled WebM muxer — zero new dependencies.+ - **`src/lib/webm-muxer.ts`** — an EBML writer with the ordering+ trap handled explicitly (small trees composed bottom-up;+ streamed Segment/Cluster elements get 8-byte placeholders that+ `finalize()` patches), 1 ms timecode scale, a cluster split+ policy (≤ 5 s age, keyframe splits at ≥ 1 s, int16 relative+ timecode ceiling, out-of-order re-base guard) and one CuePoint+ per cluster. 21 unit tests verify it through an INDEPENDENT+ mini EBML parser, plus an ffprobe cross-check that muxes real+ ffmpeg-encoded VP9 frames and reads the file back as+ matroska,webm.+ - **Deterministic frame pacing** — every frame carries its exact+ `frame / fps` microsecond stamp; there is no wall clock in the+ loop, so slow rendering can only make the export take longer,+ never drop or duplicate a frame. Backpressure rides+ `encodeQueueSize`.+ - **One render session, two engines** — the MediaRecorder loop+ and the WebCodecs loop share the same canvas, Konva stages and+ frame compositor (extracted in this release), so they draw+ identical pixels.+ - **Engine matrix** (`chooseVideoExportEngine`, pure and+ unit-tested): page-audio designs keep MediaRecorder when it can+ mux audio (WebCodecs is video-only for now — Opus-in-WebM via+ `AudioEncoder` is a documented post-R3 evaluation); silent+ designs get WebCodecs; WebCodecs-less browsers keep+ MediaRecorder; a browser with audio but no audio-muxing+ recorder now exports silent WebM instead of hard-failing.+ - The export dialog shows which engine will run before you click.+- **MP4 decision point, on the record**: MP4-everywhere needs a+ hand-rolled moov/mdat muxer (multi-week) or a ~30 KB muxing+ dependency — both rejected for R2; MP4 stays on the MediaRecorder+ path where the browser can encode H.264.++### Fixed++- A float-precision trap in the muxer's vint bounds check: at+ doubles ≥ 2^53 the guard `> 2**56 - 2` silently never fired+ because `2**56 - 2` rounds back to `2**56` (16-wide spacing); the+ guard is now `>= 2**56`. Found by the unit suite before any real+ file was written.+## [0.15.0] — 2026-11-05### Addeddiff --git a/README.md b/README.mdindex dc64053..6afc387 100644--- a/README.md+++ b/README.md@@ -1036,6 +1036,29 @@ tool descriptions so agents pick the right format.ignores spans in all three renderers, the splice ghost-copieseffect falls back to the flat path, and SVG exports render linksstyled but not as `<a>` anchors. *(v0.15.0)*+- [x] WebCodecs export pipeline (v0.15 R2) — a SECOND export engine+ for silent designs: `VideoEncoder` (VP9, VP8 fallback,+ `latencyMode: 'quality'`, explicit bitrate) feeding a hand-rolled+ **WebM muxer** (`src/lib/webm-muxer.ts` — EBML writer with patched+ segment/cluster sizes, 1 ms timecode scale, cluster split policy,+ per-cluster Cues; zero new dependencies). Frame pacing is+ **deterministic**: every frame carries its exact `frame/fps` µs+ stamp and there is no wall clock anywhere in the loop, so slow+ rendering can only make the export take longer — it can never+ drop or duplicate a frame (the MediaRecorder path paced against+ real time and dropped when behind). Both engines share ONE render+ session, so they draw identical pixels. **Engine matrix**+ (also in `chooseVideoExportEngine`, unit-tested): designs with+ autoplay page audio keep MediaRecorder when it can mux audio+ (the WebCodecs path is video-only — Opus-in-WebM via+ `AudioEncoder` is a documented post-R3 evaluation); silent+ designs get WebCodecs; browsers without WebCodecs keep+ MediaRecorder; browsers with neither still fail honestly.+ **MP4 decision point, on the record**: MP4-everywhere would need+ either a hand-rolled moov/mdat muxer (a multi-week project) or a+ ~30 KB muxing dependency (mux.js et al.) — rejected for now; MP4+ stays on the MediaRecorder path where the browser can encode+ H.264. *(v0.15.1)*- [ ] Mobile editor polish — touch-first selection handles, gesturezoom/pan without modifier keys, bottom-sheet property panels(the responsive groundwork from v0.11.3 makes this tractable)diff --git a/package.json b/package.jsonindex 990a658..29cb205 100644--- a/package.json+++ b/package.json@@ -1,6 +1,6 @@{"name": "canvix",- "version": "0.15.0",+ "version": "0.15.1","private": false,"description": "Canvix \u2014 free & open-source graphic design tool. A community-built Canva alternative.","scripts": {diff --git a/src/components/editor/ExportDialog.tsx b/src/components/editor/ExportDialog.tsxindex bdc976f..54b1416 100644--- a/src/components/editor/ExportDialog.tsx+++ b/src/components/editor/ExportDialog.tsx@@ -1,12 +1,22 @@'use client'-import { useState } from 'react'+import { useEffect, useState } from 'react'import { Download, Loader2, FileImage, FileType2, FileCode2, Film } from 'lucide-react'import { useEditorStore } from '@/store/editor-store'import { captureStage, canvasBridge } from './canvas/canvas-bridge'import { exportDesignToSVGs, downloadSVG } from '@/lib/svg-export'import { collectPluginElements, primePluginRenders } from '@/lib/plugins/renderer-cache'-import { detectVideoFormat, downloadVideo, estimateVideoDuration, exportVideo } from '@/lib/video-export'+import {+ chooseVideoExportEngine,+ computeExportSize,+ detectVideoFormat,+ detectWebCodecsVideoSupport,+ downloadVideo,+ estimateVideoDuration,+ exportVideo,+ pagesHaveAutoplayAudio,+ type VideoExportEngineDecision,+} from '@/lib/video-export'import { toast } from '@/hooks/use-toast'import { Progress } from '@/components/ui/progress'import { Button } from '@/components/ui/button'@@ -63,6 +73,31 @@ export function ExportDialog({ open, onOpenChange }: { open: boolean; onOpenChanconst [progressLabel, setProgressLabel] = useState('')const videoFormat = detectVideoFormat()const videoDuration = estimateVideoDuration(pages)+ // v0.15 R2: which engine will exportVideo use for THIS design?+ // (audio designs keep MediaRecorder; silent designs get WebCodecs)+ const [engine, setEngine] = useState<VideoExportEngineDecision | null>(null)+ useEffect(() => {+ let live = true+ void (async () => {+ const { width, height } = computeExportSize(+ canvasBridge.pageWidth || 1080,+ canvasBridge.pageHeight || 1080,+ scale === 3 ? 1920 : scale === 2 ? 1440 : 960,+ )+ const wc = await detectWebCodecsVideoSupport(width, height)+ const mr = detectVideoFormat()+ const decision = chooseVideoExportEngine({+ webcodecs: wc.supported,+ mediaRecorder: mr !== null,+ mediaRecorderAudio: mr?.audio ?? false,+ hasPageAudio: pagesHaveAutoplayAudio(pages),+ })+ if (live) setEngine(decision)+ })()+ return () => {+ live = false+ }+ }, [pages, scale])const base = sanitizeFilename(name)const pageCount = allPages ? pages.length : 1@@ -215,12 +250,23 @@ export function ExportDialog({ open, onOpenChange }: { open: boolean; onOpenChanRenders <strong>{videoDuration.toFixed(1)}s</strong> of animated playback ({pages.length} page{pages.length > 1 ? 's' : ''}) — element animations and page transitions included.</p><p>- {videoFormat ? (- <>Format: <strong>{videoFormat.label}</strong>{videoFormat.extension === 'webm' && <> — this browser can’t encode MP4, so Canvix produces WebM (plays everywhere)</>}</>+ {engine === null ? (+ <>Choosing the export engine…</>+ ) : engine.engine === 'webcodecs' ? (+ <>Engine: <strong>WebCodecs → WebM (VP9)</strong> — frame-exact timeline, explicit bitrate, rendered locally (no upload)</>+ ) : engine.engine === 'mediarecorder' && videoFormat ? (+ <>+ Engine: <strong>MediaRecorder → {videoFormat.label}</strong>+ {engine.reason.includes('page audio') ? (+ <> — renders the page audio</>+ ) : videoFormat.extension === 'webm' ? (+ <> — this browser can’t encode MP4, so Canvix produces WebM (plays everywhere)</>+ ) : null}+ {' '}· rendered locally (no upload)+ </>) : (- <span className="text-red-500">This browser cannot record video — try Chrome or Edge.</span>+ <span className="text-red-500">This browser cannot export video — try Chrome or Edge.</span>)}- · rendered locally (no upload)</p></div>) : (diff --git a/src/lib/video-export.test.ts b/src/lib/video-export.test.tsnew file mode 100644index 0000000..ff8a966--- /dev/null+++ b/src/lib/video-export.test.ts@@ -0,0 +1,133 @@+// ─────────────────────────────────────────────────────────────+// video-export engine tests (v0.15 R2)+//+// The engine matrix is a PURE function of three facts, so the+// whole decision surface is unit-testable without a browser:+//+// page audio + recorder-can-mux-audio → MediaRecorder+// WebCodecs available (silent design) → WebCodecs+// WebCodecs + audio but no audio-muxing+// recorder → WebCodecs (silent, honest)+// WebCodecs + audio + working recorder → MediaRecorder+// no WebCodecs + recorder → MediaRecorder+// neither → null (exportVideo throws)+//+// Plus computeExportSize (even-pixel rounding, upscale clamp)+// and pagesHaveAutoplayAudio (visibility + autoplay rules).+// ─────────────────────────────────────────────────────────────++import { describe, expect, it } from 'vitest'+import { chooseVideoExportEngine, computeExportSize, pagesHaveAutoplayAudio } from './video-export'+import type { PageData } from './types'++function page(elements: unknown[]): PageData {+ return {+ id: 'p1',+ background: { type: 'solid', color: '#FFFFFF' },+ elements: elements as PageData['elements'],+ }+}++describe('chooseVideoExportEngine — the fallback matrix', () => {+ it('page audio + an audio-muxing recorder rides MediaRecorder (audio wins)', () => {+ expect(+ chooseVideoExportEngine({ webcodecs: true, mediaRecorder: true, mediaRecorderAudio: true, hasPageAudio: true }),+ ).toEqual({ engine: 'mediarecorder', reason: expect.stringContaining('page audio') })+ })++ it('a silent design with WebCodecs takes the frame-exact path', () => {+ const d = chooseVideoExportEngine({ webcodecs: true, mediaRecorder: true, mediaRecorderAudio: true, hasPageAudio: false })+ expect(d.engine).toBe('webcodecs')+ expect(d.reason).toContain('frame-exact')+ })++ it('WebCodecs + page audio but NO audio-capable recorder → WebCodecs, honestly silent', () => {+ const d = chooseVideoExportEngine({ webcodecs: true, mediaRecorder: true, mediaRecorderAudio: false, hasPageAudio: true })+ expect(d.engine).toBe('webcodecs')+ expect(d.reason).toContain('silent')+ })++ it('WebCodecs + page audio + no recorder at all → WebCodecs (better than the old hard error)', () => {+ const d = chooseVideoExportEngine({ webcodecs: true, mediaRecorder: false, mediaRecorderAudio: false, hasPageAudio: true })+ expect(d.engine).toBe('webcodecs')+ expect(d.reason).toContain('only engine')+ })++ it('no WebCodecs + recorder → MediaRecorder', () => {+ expect(+ chooseVideoExportEngine({ webcodecs: false, mediaRecorder: true, mediaRecorderAudio: false, hasPageAudio: false }).engine,+ ).toBe('mediarecorder')+ })++ it('neither engine → null (exportVideo throws, same as before R2)', () => {+ const d = chooseVideoExportEngine({ webcodecs: false, mediaRecorder: false, mediaRecorderAudio: false, hasPageAudio: false })+ expect(d.engine).toBeNull()+ expect(d.reason).toContain('neither')+ })+})++describe('computeExportSize', () => {+ it('scales the longest edge down to the cap with even pixels', () => {+ expect(computeExportSize(1080, 720, 960)).toEqual({ width: 960, height: 640 })+ expect(computeExportSize(720, 1080, 960)).toEqual({ width: 640, height: 960 })+ })++ it('never upscales and never returns odd dimensions (VP8/VP9 chroma)', () => {+ expect(computeExportSize(800, 600, 1280)).toEqual({ width: 800, height: 600 })+ expect(computeExportSize(1001, 501, 2000)).toEqual({ width: 1002, height: 502 }) // half-up round to even+ const s = computeExportSize(1081, 719, 960)+ expect(s.width % 2).toBe(0)+ expect(s.height % 2).toBe(0)+ })++ it('clamps degenerate designs to the 2-pixel floor', () => {+ expect(computeExportSize(0, 0, 960)).toEqual({ width: 2, height: 2 })+ })+})++describe('pagesHaveAutoplayAudio — mirrors the recorder filter exactly', () => {+ it('no elements → false', () => {+ expect(pagesHaveAutoplayAudio([page([])])).toBe(false)+ })++ it('audio + autoplay + visible → true', () => {+ expect(+ pagesHaveAutoplayAudio([+ page([{ type: 'audio', autoplay: true, visible: true }]),+ ]),+ ).toBe(true)+ })++ it('autoplay audio that is hidden does not count (it never plays)', () => {+ expect(+ pagesHaveAutoplayAudio([+ page([{ type: 'audio', autoplay: true, visible: false }]),+ ]),+ ).toBe(false)+ })++ it('visible audio without autoplay does not count', () => {+ expect(+ pagesHaveAutoplayAudio([+ page([{ type: 'audio', autoplay: false, visible: true }]),+ ]),+ ).toBe(false)+ })++ it('any page carrying one counts', () => {+ expect(+ pagesHaveAutoplayAudio([+ page([]),+ page([{ type: 'audio', autoplay: true, visible: true }]),+ ]),+ ).toBe(true)+ })++ it('non-audio elements never count', () => {+ expect(+ pagesHaveAutoplayAudio([+ page([{ type: 'rect', autoplay: true, visible: true }]),+ ]),+ ).toBe(false)+ })+})diff --git a/src/lib/video-export.ts b/src/lib/video-export.tsindex 539a11c..5141538 100644--- a/src/lib/video-export.ts+++ b/src/lib/video-export.ts@@ -1,14 +1,15 @@// ─────────────────────────────────────────────────────────────-// Video export (v0.5) — REAL rendering pipeline, fully local+// Video export — REAL rendering pipeline, fully local//// Canvix document → animation timeline → frame renderer-// → MediaRecorder canvas capture → MP4 (H.264, where the-// browser can encode it) or WebM (VP9/VP8 fallback)+// → [v0.15 R2] WebCodecs VideoEncoder + WebM muxer (silent+// designs: deterministic µs-stamped frames, explicit bitrate,+// latencyMode 'quality') — or — MediaRecorder canvas capture+// → MP4 (H.264 where the browser can encode it) / WebM,+// which stays the path for page-audio designs (it muxes audio).//-// Fixed-timestep rendering: frames are pushed manually via-// captureStream(0) + requestFrame(), so output timing is exact-// even when rendering is slower than realtime. Static PNG/JPG/-// PDF/SVG exports are unaffected (animations are ignored there).+// Static PNG/JPG/PDF/SVG exports are unaffected (animations are+// ignored there). See chooseVideoExportEngine for the matrix.// ─────────────────────────────────────────────────────────────import Konva from 'konva'@@ -20,6 +21,7 @@ import { createCanvasMeasure, layoutRichLines, normalizeSpans } from '@/lib/richimport { animateElementAt, pageHoldDuration } from '@/lib/animations'import { beatEnvelopeAt, beatSourceOf } from '@/lib/media/beat-detect'import { awaitRender, renderKey } from '@/lib/plugins/renderer-cache'+import { WebMMuxer } from '@/lib/webm-muxer'export interface VideoExportOptions {designWidth: number@@ -741,121 +743,151 @@ function applyGradient(/*** Render the design timeline into a real video file (in-browser).*/-export async function exportVideo(opts: VideoExportOptions): Promise<VideoExportResult> {- const format = detectVideoFormat()- if (!format) throw new Error('This browser cannot record video (MediaRecorder unavailable).')-- const fps = opts.fps ?? 30- const scale = Math.min(1, (opts.maxWidth ?? 1280) / Math.max(opts.designWidth, opts.designHeight))- const width = Math.max(2, Math.round((opts.designWidth * scale) / 2) * 2)- const height = Math.max(2, Math.round((opts.designHeight * scale) / 2) * 2)+// ─────────────────────────────────────────────────────────────+// v0.15 (R2): two export engines behind one entry point.+//+// 'webcodecs' — silent designs: VideoEncoder (VP9, VP8+// fallback) + the hand-rolled WebM muxer.+// DETERMINISTIC frame pacing (every frame gets+// its exact timestamp — nothing is dropped+// when rendering is slow), explicit bitrate,+// latencyMode 'quality'. No wall clock.+// 'mediarecorder' — designs with page audio (it muxes the audio+// the WebCodecs path can't, yet) and browsers+// without WebCodecs. MP4/H.264 rides this path.+//+// The engine choice is a pure function of three facts (WebCodecs+// support at this size, MediaRecorder availability + audio muxing,+// whether the design has autoplay audio) — see+// chooseVideoExportEngine. Both paths share ONE render session+// (canvas + Konva stages + the frame compositor), so the WebCodecs+// path draws exactly what the MediaRecorder path draws.+// ─────────────────────────────────────────────────────────────- const { segments, total } = buildTimeline(opts.pages)- const totalFrames = Math.max(1, Math.round(total * fps))+/** Output pixel size for a design at a maxWidth cap (even numbers —+ * VP8/VP9 chroma subsampling demands it). */+export function computeExportSize(+ designWidth: number,+ designHeight: number,+ maxWidth: number,+): { width: number; height: number } {+ const scale = Math.min(1, maxWidth / Math.max(designWidth, designHeight))+ return {+ width: Math.max(2, Math.round((designWidth * scale) / 2) * 2),+ height: Math.max(2, Math.round((designHeight * scale) / 2) * 2),+ }+}- // preload every image source first (dataURLs resolve instantly)- opts.onProgress?.(0, 'Loading images…')- const images = await collectImages(opts.pages)+/** Does any page carry an autoplay audio element? (The same filter+ * the MediaRecorder path uses for its audio muxing.) */+export function pagesHaveAutoplayAudio(pages: PageData[]): boolean {+ return pages.some((p) =>+ (p.elements as AnyElement[]).some((e) => e.type === 'audio' && e.visible !== false && e.autoplay),+ )+}- // recorder canvas with manual frame pushing- const canvas = document.createElement('canvas')- canvas.width = width- canvas.height = height- const ctx = canvas.getContext('2d')- if (!ctx) throw new Error('Could not create the rendering canvas.')- const stream = canvas.captureStream(0)- const track = stream.getVideoTracks()[0] as MediaStreamTrack & { requestFrame?: () => void }+export interface WebCodecsVideoSupport {+ supported: boolean+ /** Matroska CodecID the muxer should declare. */+ codecId: 'V_VP9' | 'V_VP8' | null+ /** The WebCodecs codec string to configure. */+ codecString: string | null+}- // ── v0.11: page-audio muxing (best-effort) ──────────────────- // Each segment's autoplay audio elements play through a shared- // AudioContext MediaStreamDestination while their page is on the- // timeline; the wall-clock pacing of the frame loop keeps A/V aligned.- // Every step is individually guarded — a browser that refuses any of- // this (autoplay policy, codec) still produces a correct silent video.- const segmentAudio: HTMLAudioElement[][] = segments.map((s) =>- (s.page.elements as AnyElement[])- .filter((e): e is AudioElement => e.type === 'audio' && e.visible !== false && e.autoplay)- .map((el) => {- const a = new Audio(el.src)- a.volume = Math.min(1, Math.max(0, Number.isFinite(el.volume) ? el.volume : 0.8))- a.loop = el.loop- return a- }),- )- let audioCtx: AudioContext | null = null- let audioDest: MediaStreamAudioDestinationNode | null = null- if (format.audio && segmentAudio.some((els) => els.length)) {+/** Probe WebCodecs VP9→VP8 at the real export size (isConfigSupported+ * is size-sensitive; a 640×360 yes does not promise 1920×1080). */+export async function detectWebCodecsVideoSupport(width: number, height: number): Promise<WebCodecsVideoSupport> {+ const none: WebCodecsVideoSupport = { supported: false, codecId: null, codecString: null }+ if (typeof VideoEncoder === 'undefined' || typeof VideoFrame === 'undefined') return none+ const candidates: { codecId: 'V_VP9' | 'V_VP8'; codecString: string }[] = [+ { codecId: 'V_VP9', codecString: 'vp09.00.10.08' },+ { codecId: 'V_VP8', codecString: 'vp8' },+ ]+ for (const c of candidates) {try {- const Ctx: typeof AudioContext =- window.AudioContext ?? (window as unknown as { webkitAudioContext: typeof AudioContext }).webkitAudioContext- audioCtx = new Ctx()- // v0.11.1 fix: resume() is async — a context that is still suspended- // when the recorder starts records DIGITAL SILENCE for the whole- // export (racy in headless browsers, possible on real ones after a- // background-tab suspension). Wait (bounded) for it to run before- // any audio flows; on timeout we still proceed honestly — the- // guards below keep the export correct, just silent.- await Promise.race([audioCtx.resume(), new Promise<void>((r) => setTimeout(r, 750))]).catch(() => {- /* suspended → silent track */+ const probe = await VideoEncoder.isConfigSupported({+ codec: c.codecString,+ width,+ height,+ bitrate: 1_000_000,+ framerate: 30,})- audioDest = audioCtx.createMediaStreamDestination()- for (const els of segmentAudio) {- for (const a of els) audioCtx.createMediaElementSource(a).connect(audioDest)- }+ if (probe.supported) return { supported: true, codecId: c.codecId, codecString: c.codecString }} catch {- audioCtx = null- audioDest = null+ /* try the next candidate */}}- // v0.11.1 fix: WAIT for the audio to be buffered before recording starts.- // The render loop below yields via MessageChannel in a tight cycle, which- // starves the media element's resource-selection task — a not-yet-loaded- // element at recorder.start() never loads during the export (readyState- // stays 0, play() aborts in the finally) and the track records digital- // silence. Here the main thread is still idle: the fetch completes in- // milliseconds. Bounded at 1.5 s — a slow network still exports (silent,- // honestly) instead of hanging.- if (audioDest) {- const all = segmentAudio.flat()- await Promise.race([- Promise.all(- all.map(- (a) =>- new Promise<void>((resolve) => {- if (a.readyState >= 3) return resolve()- const done = () => {- a.removeEventListener('canplay', done)- a.removeEventListener('error', done)- resolve()- }- a.addEventListener('canplay', done)- a.addEventListener('error', done)- try {- a.load() // explicit resource selection — don't rely on the queued task- } catch {- resolve()- }- }),- ),- ),- new Promise<void>((resolve) => setTimeout(resolve, 1_500)),- ])- }+ return none+}- const recordStream = audioDest ? new MediaStream([track, ...audioDest.stream.getAudioTracks()]) : stream+export interface VideoEngineInputs {+ webcodecs: boolean+ mediaRecorder: boolean+ /** the recorder candidate can mux audio (mp4a/opus in its mime) */+ mediaRecorderAudio: boolean+ hasPageAudio: boolean+}- const recorder = new MediaRecorder(recordStream, {- mimeType: format.mimeType,- videoBitsPerSecond: Math.round(width * height * fps * 0.12),- })- const chunks: BlobPart[] = []- recorder.ondataavailable = (e) => {- if (e.data.size > 0) chunks.push(e.data)+export type VideoExportEngineDecision =+ | { engine: 'webcodecs'; reason: string }+ | { engine: 'mediarecorder'; reason: string }+ | { engine: null; reason: string }++/** The engine matrix, as one pure function (unit-tested):+ * - page audio + a recorder that can mux it → MediaRecorder+ * (the WebCodecs path is silent; Opus-in-WebM via AudioEncoder+ * is a documented post-R3 evaluation)+ * - WebCodecs available otherwise → WebCodecs (frame-exact)+ * - neither → null (exportVideo throws, as before) */+export function chooseVideoExportEngine(inputs: VideoEngineInputs): VideoExportEngineDecision {+ if (inputs.hasPageAudio && inputs.mediaRecorder && inputs.mediaRecorderAudio) {+ return { engine: 'mediarecorder', reason: 'page audio — MediaRecorder muxes it (the WebCodecs path is video-only for now)' }}- const done = new Promise<void>((resolve) => {- recorder.onstop = () => resolve()- })- recorder.start()+ if (inputs.webcodecs) {+ if (inputs.hasPageAudio) {+ return {+ engine: 'webcodecs',+ reason: inputs.mediaRecorder+ ? 'audio-preserving MediaRecorder unavailable here — exporting silent via WebCodecs'+ : 'MediaRecorder unavailable — WebCodecs is the only engine in this browser',+ }+ }+ return { engine: 'webcodecs', reason: 'frame-exact VP9/VP8 WebM at an explicit bitrate' }+ }+ if (inputs.mediaRecorder) {+ return { engine: 'mediarecorder', reason: 'WebCodecs unavailable in this browser' }+ }+ return { engine: null, reason: 'neither WebCodecs nor MediaRecorder can encode video here' }+}++/** Everything both engines share: the render canvas, the per-page+ * Konva stages, and the timeline compositor (renderFrameAt). */+interface RenderSession {+ readonly canvas: HTMLCanvasElement+ readonly ctx: CanvasRenderingContext2D+ readonly segments: TimelineSegment[]+ readonly segStarts: number[]+ readonly totalFrames: number+ renderFrameAt(frameNo: number, t: number): void+ destroy(): void+}++async function createRenderSession(+ opts: VideoExportOptions,+ width: number,+ height: number,+ segments: TimelineSegment[],+ totalFrames: number,+): Promise<RenderSession> {+ // preload every image source first (dataURLs resolve instantly)+ opts.onProgress?.(0, 'Loading images…')+ const images = await collectImages(opts.pages)++ const canvas = document.createElement('canvas')+ canvas.width = width+ canvas.height = height+ const ctx = canvas.getContext('2d')+ if (!ctx) throw new Error('Could not create the rendering canvas.')// hidden host for the Konva stagesconst host = document.createElement('div')@@ -1043,6 +1075,249 @@ export async function exportVideo(opts: VideoExportOptions): Promise<VideoExport}}++ /** tear down the Konva stages + hidden host (stream/audio teardown+ * belongs to the engine path that created them). */+ const destroy = (): void => {+ for (const stage of stageForPage.values()) stage.destroy()+ host.remove()+ }++ return { canvas, ctx, segments, segStarts, totalFrames, renderFrameAt, destroy }+}++export async function exportVideo(opts: VideoExportOptions): Promise<VideoExportResult> {+ const fps = opts.fps ?? 30+ const { width, height } = computeExportSize(opts.designWidth, opts.designHeight, opts.maxWidth ?? 1280)+ const { segments, total } = buildTimeline(opts.pages)+ const totalFrames = Math.max(1, Math.round(total * fps))++ const wc = await detectWebCodecsVideoSupport(width, height)+ const mr = detectVideoFormat()+ const decision = chooseVideoExportEngine({+ webcodecs: wc.supported,+ mediaRecorder: mr !== null,+ mediaRecorderAudio: mr?.audio ?? false,+ hasPageAudio: pagesHaveAutoplayAudio(opts.pages),+ })+ if (decision.engine === 'webcodecs' && wc.codecId && wc.codecString) {+ return exportViaWebCodecs(opts, wc, { fps, width, height, segments, total, totalFrames })+ }+ if (decision.engine === null) {+ throw new Error('This browser cannot record video (no WebCodecs encoder and no MediaRecorder).')+ }+ if (!mr) throw new Error('This browser cannot record video (MediaRecorder unavailable).')+ return exportViaMediaRecorder(opts, mr, { fps, width, height, segments, total, totalFrames })+}++interface SizedExport {+ fps: number+ width: number+ height: number+ segments: TimelineSegment[]+ total: number+ totalFrames: number+}++// ── engine A: WebCodecs → WebM (v0.15 R2) ─────────────────────++async function exportViaWebCodecs(+ opts: VideoExportOptions,+ wc: WebCodecsVideoSupport,+ sized: SizedExport,+): Promise<VideoExportResult> {+ const { fps, width, height, segments, total, totalFrames } = sized+ const session = await createRenderSession(opts, width, height, segments, totalFrames)+ const { canvas, ctx, renderFrameAt } = session++ const gopFrames = Math.max(1, Math.round(fps * 2))+ const bitrate = Math.min(20_000_000, Math.max(250_000, Math.round(width * height * fps * 0.14)))+ const mimeType = wc.codecId === 'V_VP9' ? 'video/webm;codecs=vp9' : 'video/webm;codecs=vp8'+ const muxer = new WebMMuxer({+ width,+ height,+ codec: wc.codecId ?? 'V_VP9',+ durationMs: Math.round((totalFrames / fps) * 1000),+ })++ let encodeError: DOMException | null = null+ const encoder = new VideoEncoder({+ output: (chunk) => {+ const data = new Uint8Array(chunk.byteLength)+ chunk.copyTo(data)+ muxer.addFrame({+ data,+ keyframe: chunk.type === 'key',+ timestampUs: chunk.timestamp,+ durationUs: chunk.duration !== null && chunk.duration > 0 ? chunk.duration : Math.round(1e6 / fps),+ })+ },+ error: (e) => {+ encodeError = e+ },+ })+ encoder.configure({+ codec: wc.codecString ?? 'vp09.00.10.08',+ width,+ height,+ bitrate,+ framerate: fps,+ // no realtime constraint — the file export prefers quality+ latencyMode: 'quality',+ alpha: 'discard',+ })++ /** tiny yield so the encoder queue and the UI can breathe */+ const breathe = (): Promise<void> => new Promise<void>((r) => setTimeout(r, 4))++ try {+ ctx.fillStyle = '#FFFFFF'+ ctx.fillRect(0, 0, width, height)++ // DETERMINISTIC PACING — every frame carries its exact µs stamp+ // (frame / fps). There is no wall clock anywhere in this loop:+ // slow rendering only makes the export take longer, never drops+ // or duplicates a frame. Backpressure rides encodeQueueSize.+ for (let frame = 0; frame < totalFrames; frame++) {+ if (encodeError) throw encodeError+ const t = frame / fps+ renderFrameAt(frame, t)+ while (encoder.encodeQueueSize > 4 && !encodeError) await breathe()+ const videoFrame = new VideoFrame(canvas, {+ timestamp: Math.round((frame * 1e6) / fps),+ duration: Math.round(1e6 / fps),+ })+ encoder.encode(videoFrame, { keyFrame: frame % gopFrames === 0 })+ videoFrame.close()+ if (frame % 10 === 0) {+ opts.onProgress?.(frame / totalFrames, `Encoding frame ${frame + 1} / ${totalFrames}`)+ await breathe()+ }+ }+ await encoder.flush()+ if (encodeError) throw encodeError++ opts.onProgress?.(1, 'Finalizing…')+ const bytes = muxer.finalize()+ if (muxer.frames === 0 || bytes.length === 0) {+ throw new Error('The video encoder produced an empty file — try fewer pages or a smaller resolution.')+ }+ return { blob: new Blob([bytes], { type: mimeType }), mimeType, extension: 'webm', durationSec: total, frames: muxer.frames }+ } finally {+ try {+ encoder.close()+ } catch {+ /* already closed on error */+ }+ session.destroy()+ }+}++// ── engine B: MediaRecorder (unchanged behaviour) ─────────────++async function exportViaMediaRecorder(+ opts: VideoExportOptions,+ format: { mimeType: string; extension: string; label: string; audio: boolean },+ sized: SizedExport,+): Promise<VideoExportResult> {+ const { fps, width, height, segments, total, totalFrames } = sized+ const session = await createRenderSession(opts, width, height, segments, totalFrames)+ const { canvas, ctx, renderFrameAt, segStarts } = session++ const stream = canvas.captureStream(0)+ const track = stream.getVideoTracks()[0] as MediaStreamTrack & { requestFrame?: () => void }++ // ── v0.11: page-audio muxing (best-effort) ──────────────────+ // Each segment's autoplay audio elements play through a shared+ // AudioContext MediaStreamDestination while their page is on the+ // timeline; the wall-clock pacing of the frame loop keeps A/V aligned.+ // Every step is individually guarded — a browser that refuses any of+ // this (autoplay policy, codec) still produces a correct silent video.+ const segmentAudio: HTMLAudioElement[][] = segments.map((s) =>+ (s.page.elements as AnyElement[])+ .filter((e): e is AudioElement => e.type === 'audio' && e.visible !== false && e.autoplay)+ .map((el) => {+ const a = new Audio(el.src)+ a.volume = Math.min(1, Math.max(0, Number.isFinite(el.volume) ? el.volume : 0.8))+ a.loop = el.loop+ return a+ }),+ )+ let audioCtx: AudioContext | null = null+ let audioDest: MediaStreamAudioDestinationNode | null = null+ if (format.audio && segmentAudio.some((els) => els.length)) {+ try {+ const Ctx: typeof AudioContext =+ window.AudioContext ?? (window as unknown as { webkitAudioContext: typeof AudioContext }).webkitAudioContext+ audioCtx = new Ctx()+ // v0.11.1 fix: resume() is async — a context that is still suspended+ // when the recorder starts records DIGITAL SILENCE for the whole+ // export (racy in headless browsers, possible on real ones after a+ // background-tab suspension). Wait (bounded) for it to run before+ // any audio flows; on timeout we still proceed honestly — the+ // guards below keep the export correct, just silent.+ await Promise.race([audioCtx.resume(), new Promise<void>((r) => setTimeout(r, 750))]).catch(() => {+ /* suspended → silent track */+ })+ audioDest = audioCtx.createMediaStreamDestination()+ for (const els of segmentAudio) {+ for (const a of els) audioCtx.createMediaElementSource(a).connect(audioDest)+ }+ } catch {+ audioCtx = null+ audioDest = null+ }+ }+ // v0.11.1 fix: WAIT for the audio to be buffered before recording starts.+ // The render loop below yields via MessageChannel in a tight cycle, which+ // starves the media element's resource-selection task — a not-yet-loaded+ // element at recorder.start() never loads during the export (readyState+ // stays 0, play() aborts in the finally) and the track records digital+ // silence. Here the main thread is still idle: the fetch completes in+ // milliseconds. Bounded at 1.5 s — a slow network still exports (silent,+ // honestly) instead of hanging.+ if (audioDest) {+ const all = segmentAudio.flat()+ await Promise.race([+ Promise.all(+ all.map(+ (a) =>+ new Promise<void>((resolve) => {+ if (a.readyState >= 3) return resolve()+ const done = () => {+ a.removeEventListener('canplay', done)+ a.removeEventListener('error', done)+ resolve()+ }+ a.addEventListener('canplay', done)+ a.addEventListener('error', done)+ try {+ a.load() // explicit resource selection — don't rely on the queued task+ } catch {+ resolve()+ }+ }),+ ),+ ),+ new Promise<void>((resolve) => setTimeout(resolve, 1_500)),+ ])+ }++ const recordStream = audioDest ? new MediaStream([track, ...audioDest.stream.getAudioTracks()]) : stream++ const recorder = new MediaRecorder(recordStream, {+ mimeType: format.mimeType,+ videoBitsPerSecond: Math.round(width * height * fps * 0.12),+ })+ const chunks: BlobPart[] = []+ recorder.ondataavailable = (e) => {+ if (e.data.size > 0) chunks.push(e.data)+ }+ const done = new Promise<void>((resolve) => {+ recorder.onstop = () => resolve()+ })+ recorder.start()+try {ctx.fillStyle = '#FFFFFF'ctx.fillRect(0, 0, width, height)@@ -1133,8 +1408,7 @@ export async function exportVideo(opts: VideoExportOptions): Promise<VideoExportawait doneopts.onProgress?.(1, 'Finalizing…')} finally {- for (const stage of stageForPage.values()) stage.destroy()- host.remove()+ session.destroy()stream.getTracks().forEach((tr) => tr.stop())for (const els of segmentAudio) {for (const a of els) {diff --git a/src/lib/webm-muxer.test.ts b/src/lib/webm-muxer.test.tsnew file mode 100644index 0000000..66a56d0--- /dev/null+++ b/src/lib/webm-muxer.test.ts@@ -0,0 +1,476 @@+// ─────────────────────────────────────────────────────────────+// webm-muxer tests (v0.15 R2)+//+// The muxer is verified with an INDEPENDENT mini EBML parser+// (written from the spec, not shared with the muxer code) so the+// tests can disagree with the writer about how to read a file —+// that's the whole point. On top of the parser:+//+// A. vint grammar — the reserved all-ones trap, marker bits,+// boundary values (127/16 383/…), oversized rejection+// B. header truth — DocType webm, MaxSizeLength 8+// C. Info — TimecodeScale 1 ms, Duration float patched, apps+// D. Tracks — one video track, codec id, dimensions, no lacing+// E. clusters — keyframe flags, relative timecodes, split+// policy (5 s cap, keyframe splits, int16 guard,+// out-of-order re-base), first-block-is-keyframe contract+// F. Cues — one point per cluster, positions point at real+// cluster element starts+// G. segment size patch — exactly file length − data start+// H. honesty — one-shot finalize, empty-payload refusal+// ─────────────────────────────────────────────────────────────++import { describe, expect, it } from 'vitest'+import { WebMMuxer, type MuxedVideoFrame, vintBytes, vintLength } from './webm-muxer'++// ── the independent parser ────────────────────────────────────++interface Node {+ id: number+ /** body byte range in the file */+ start: number+ end: number+ children: Node[]+}++function readVint(file: Uint8Array, at: number): { value: number; len: number } {+ const first = file[at]+ let markerBits = 0+ for (let i = 7; i >= 0; i--) {+ if ((first >> i) & 1) {+ markerBits = 8 - i+ break+ }+ }+ if (markerBits === 0) throw new Error(`parser: vint marker missing at ${at}`)+ let value = first & (0xff >> markerBits)+ for (let i = 1; i < markerBits; i++) {+ value = value * 256 + file[at + i]+ }+ if (value === 2 ** (7 * markerBits) - 1) {+ // all-ones payload = "unknown size" — the muxer must never emit it+ throw new Error(`parser: unknown-size vint at ${at}`)+ }+ return { value, len: markerBits }+}++function readId(file: Uint8Array, at: number): { id: number; len: number } {+ const first = file[at]+ if (first === 0) throw new Error(`parser: id leading zero at ${at}`)+ let len = 1+ for (let i = 7; i >= 0; i--) {+ if ((first >> i) & 1) {+ len = 8 - i+ break+ }+ }+ let id = 0+ for (let i = 0; i < len; i++) id = id * 256 + file[at + i]+ return { id, len }+}++function parseInto(file: Uint8Array, start: number, end: number, out: Node[]): void {+ let at = start+ while (at < end) {+ const { id, len: idLen } = readId(file, at)+ const { value: size, len: sizeLen } = readVint(file, at + idLen)+ const bodyStart = at + idLen + sizeLen+ const bodyEnd = bodyStart + size+ if (bodyEnd > end) throw new Error(`parser: element 0x${id.toString(16)} overruns parent (at ${at}, size ${size})`)+ out.push({ id, start: bodyStart, end: bodyEnd, children: [] })+ at = bodyEnd+ }+ if (at !== end) throw new Error('parser: trailing bytes in parent')+}++function parse(file: Uint8Array): Node[] {+ const out: Node[] = []+ parseInto(file, 0, file.length, out)+ return out+}++function childrenOf(file: Uint8Array, node: Node): Node[] {+ parseInto(file, node.start, node.end, node.children)+ return node.children+}++function find(nodes: Node[], id: number): Node | undefined {+ return nodes.find((n) => n.id === id)+}++function uintValue(file: Uint8Array, node: Node): number {+ let v = 0+ for (let i = node.start; i < node.end; i++) v = v * 256 + file[i]+ return v+}++function floatValue(file: Uint8Array, node: Node): number {+ const b = new Uint8Array(node.end - node.start)+ b.set(file.subarray(node.start, node.end))+ const be = new Uint8Array(8)+ for (let i = 0; i < 8; i++) be[i] = b[7 - i]+ return new Float64Array(be.buffer)[0]+}++function stringValue(file: Uint8Array, node: Node): string {+ return new TextDecoder().decode(file.subarray(node.start, node.end))+}++/** walk to a nested child by path of ids */+function dig(file: Uint8Array, node: Node, ...ids: number[]): Node {+ let cur = node+ for (const id of ids) {+ const next = find(childrenOf(file, cur), id)+ if (!next) throw new Error(`parser: child 0x${id.toString(16)} not found`)+ cur = next+ }+ return cur+}++// ── helpers ───────────────────────────────────────────────────++const FPS = 30+const DUR_MS = 10_000++function frameAt(i: number, keyframe: boolean, size = 64): MuxedVideoFrame {+ const data = new Uint8Array(size)+ data.fill(i & 0xff)+ return { data, keyframe, timestampUs: Math.round((i * 1e6) / FPS), durationUs: Math.round(1e6 / FPS) }+}++function muxFrames(frames: MuxedVideoFrame[], durationMs = DUR_MS): Uint8Array {+ const muxer = new WebMMuxer({ width: 960, height: 640, codec: 'V_VP9', durationMs })+ for (const f of frames) muxer.addFrame(f)+ return muxer.finalize()+}++function simpleBlocks(file: Uint8Array, cluster: Node): Node[] {+ return childrenOf(file, cluster).filter((n) => n.id === 0xa3)+}++/** decode a SimpleBlock body */+function blockInfo(file: Uint8Array, block: Node): { track: number; relTc: number; keyframe: boolean; dataStart: number } {+ const b = file+ const track = b[block.start] & 0x7f+ const relTc = (b[block.start + 1] << 8) | b[block.start + 2]+ const signed = relTc >= 0x8000 ? relTc - 0x10000 : relTc+ return { track, relTc: signed, keyframe: (b[block.start + 3] & 0x80) !== 0, dataStart: block.start + 4 }+}++// ── A. vint grammar ───────────────────────────────────────────++describe('webm-muxer: EBML vint grammar', () => {+ it('encodes single-byte values below the reserved boundary', () => {+ expect(vintBytes(0)).toEqual(new Uint8Array([0x80]))+ expect(vintBytes(1)).toEqual(new Uint8Array([0x81]))+ expect(vintBytes(126)).toEqual(new Uint8Array([0xfe]))+ })++ it('reserves all-ones — 127 jumps to two bytes', () => {+ expect(vintLength(127)).toBe(2)+ expect(vintBytes(127)).toEqual(new Uint8Array([0x40, 0x7f]))+ expect(vintLength(16_382)).toBe(2)+ expect(vintLength(16_383)).toBe(3)+ expect(vintLength(2 ** 21 - 2)).toBe(3)+ expect(vintLength(2 ** 21 - 1)).toBe(4)+ })++ it('round-trips through the independent parser at every boundary', () => {+ const values = [0, 1, 126, 127, 128, 16_382, 16_383, 2 ** 21 - 2, 2 ** 21 - 1, 2 ** 28 - 2, 999_999]+ for (const v of values) {+ const b = vintBytes(v)+ const back = readVint(b, 0)+ expect(back.value, `v=${v}`).toBe(v)+ expect(back.len, `v=${v}`).toBe(b.length)+ }+ })++ it('rejects negative, fractional and absurd values', () => {+ expect(() => vintLength(-1)).toThrow()+ expect(() => vintLength(1.5)).toThrow()+ expect(() => vintLength(2 ** 56)).toThrow()+ })+})++// ── B–D. header / info / tracks ───────────────────────────────++describe('webm-muxer: file skeleton', () => {+ const file = muxFrames([frameAt(0, true), frameAt(1, false), frameAt(2, false)])+ const top = parse(file)+ const ebml = find(top, 0x1a45dfa3)!+ const segment = find(top, 0x18538067)!++ it('writes exactly two top-level elements: EBML header + Segment', () => {+ expect(top.map((n) => n.id)).toEqual([0x1a45dfa3, 0x18538067])+ })++ it('declares the webm doctype with the size headroom it needs', () => {+ const kids = childrenOf(file, ebml)+ expect(stringValue(file, find(kids, 0x4282)!)).toBe('webm')+ expect(uintValue(file, find(kids, 0x4287)!)).toBe(2)+ expect(uintValue(file, find(kids, 0x42f3)!)).toBe(8) // MaxSizeLength — we patch 8-byte sizes+ })++ it('patches the segment size to exactly cover the file', () => {+ // the segment element starts after the EBML header element —+ // its body start (from the parser) is exactly 12 bytes after+ // its element start (4-byte id + 8-byte size placeholder).+ const segElementStart = segment.start - 12+ const { value, len } = readVint(file, segElementStart + 4)+ expect(len).toBe(8)+ expect(value).toBe(file.length - segment.start)+ })++ it('Info: 1 ms timecode scale, patched float duration, honest apps', () => {+ const info = find(childrenOf(file, segment), 0x1549a966)!+ const kids = childrenOf(file, info)+ expect(uintValue(file, find(kids, 0x2ad7b1)!)).toBe(1_000_000)+ expect(stringValue(file, find(kids, 0x4d80)!)).toBe('Canvix')+ expect(stringValue(file, find(kids, 0x5741)!)).toContain('Canvix')+ expect(floatValue(file, find(kids, 0x4489)!)).toBeCloseTo(DUR_MS, 6)+ })++ it('Tracks: one V_VP9 video track at the declared size, lacing off', () => {+ const trackEntry = dig(file, segment, 0x1654ae6b, 0xae)+ const kids = childrenOf(file, trackEntry)+ expect(uintValue(file, find(kids, 0xd7)!)).toBe(1) // TrackNumber+ expect(uintValue(file, find(kids, 0x83)!)).toBe(1) // TrackType video+ expect(uintValue(file, find(kids, 0x9c)!)).toBe(0) // FlagLacing+ expect(stringValue(file, find(kids, 0x86)!)).toBe('V_VP9')+ const video = find(kids, 0xe0)!+ const vk = childrenOf(file, video)+ expect(uintValue(file, find(vk, 0xb0)!)).toBe(960)+ expect(uintValue(file, find(vk, 0xba)!)).toBe(640)+ })+})++// ── E. clusters + blocks ──────────────────────────────────────++describe('webm-muxer: clusters and SimpleBlocks', () => {+ it('keeps frame data intact and flags keyframes', () => {+ const frames = [frameAt(0, true, 100), frameAt(1, false, 100), frameAt(2, false, 100)]+ const file = muxFrames(frames)+ const segment = find(parse(file), 0x18538067)!+ const clusters = childrenOf(file, segment).filter((n) => n.id === 0x1f43b675)+ const blocks = simpleBlocks(file, clusters[0])+ expect(blocks.length).toBe(3)+ const b0 = blockInfo(file, blocks[0])+ expect(b0.track).toBe(1)+ expect(b0.keyframe).toBe(true)+ expect(b0.relTc).toBe(0)+ expect(blockInfo(file, blocks[1]).keyframe).toBe(false)+ expect(blockInfo(file, blocks[1]).relTc).toBe(33)+ // data survived byte-for-byte+ const f0 = frames[0].data+ expect(Array.from(file.subarray(b0.dataStart, b0.dataStart + 8))).toEqual(Array.from(f0.subarray(0, 8)))+ })++ it('splits a new cluster per keyframe once the cluster is ≥ 1 s old', () => {+ // 5 s at 30 fps with a keyframe every 2 s → bases at 0, 2000, 4000+ const frames: MuxedVideoFrame[] = []+ for (let i = 0; i < 5 * FPS; i++) frames.push(frameAt(i, i % (2 * FPS) === 0))+ const file = muxFrames(frames)+ const segment = find(parse(file), 0x18538067)!+ const clusters = childrenOf(file, segment).filter((n) => n.id === 0x1f43b675)+ const bases = clusters.map((c) => uintValue(file, find(childrenOf(file, c), 0xe7)!))+ expect(bases).toEqual([0, 2_000, 4_000])+ // every cluster opens with a keyframe block+ for (const c of clusters) {+ expect(blockInfo(file, simpleBlocks(file, c)[0]).keyframe).toBe(true)+ }+ })++ it('caps cluster age at 5 s even without keyframes', () => {+ // 12 s of deltas only — the cap must still split+ const frames: MuxedVideoFrame[] = []+ for (let i = 0; i < 12 * FPS; i++) frames.push(frameAt(i, i === 0))+ const file = muxFrames(frames)+ const segment = find(parse(file), 0x18538067)!+ const clusters = childrenOf(file, segment).filter((n) => n.id === 0x1f43b675)+ expect(clusters.length).toBeGreaterThanOrEqual(3)+ for (const c of clusters) {+ const base = uintValue(file, find(childrenOf(file, c), 0xe7)!)+ expect(base % 5_000).toBe(0)+ // int16 safety: last block's relative timecode in range+ const blocks = simpleBlocks(file, c)+ expect(blockInfo(file, blocks[blocks.length - 1]).relTc).toBeLessThanOrEqual(32_767)+ }+ })++ it('re-bases when a stamp arrives out of order (guard, not corruption)', () => {+ // push the base to 2000 ms (keyframe split at ≥ 1 s), then a+ // rogue stamp at 1000 ms — BEFORE the open cluster's base+ const frames = [+ frameAt(0, true), // t = 0 ms → cluster 1 opens (base 0)+ frameAt(60, true), // t = 2000 ms → keyframe split (base 2000)+ { data: new Uint8Array(16).fill(0xab), keyframe: true, timestampUs: 1_000_000, durationUs: 33_333 }, // t = 1000 ms+ ]+ const file = muxFrames(frames)+ const segment = find(parse(file), 0x18538067)!+ const clusters = childrenOf(file, segment).filter((n) => n.id === 0x1f43b675)+ const allBlocks = clusters.flatMap((c) => simpleBlocks(file, c).map((b) => blockInfo(file, b)))+ for (const b of allBlocks) expect(b.relTc).toBeGreaterThanOrEqual(0)+ // bases: 0, 2000, then the rogue re-based to 1000+ const bases = clusters.map((c) => uintValue(file, find(childrenOf(file, c), 0xe7)!))+ expect(bases).toEqual([0, 2_000, 1_000])+ })++ it('the duration floor rises to the observed last-frame end', () => {+ // declared 10 s but frames claim 12 s → Duration must not lie short+ const frames: MuxedVideoFrame[] = []+ for (let i = 0; i < 12 * FPS; i++) frames.push(frameAt(i, i === 0))+ const file = muxFrames(frames, 10_000)+ const segment = find(parse(file), 0x18538067)!+ const info = find(childrenOf(file, segment), 0x1549a966)!+ const dur = floatValue(file, find(childrenOf(file, info), 0x4489)!)+ expect(dur).toBeGreaterThanOrEqual(12_000 - 1)+ })+})++// ── F. Cues ───────────────────────────────────────────────────++describe('webm-muxer: Cues', () => {+ it('emits one CuePoint per cluster whose position hits the cluster element exactly', () => {+ const frames: MuxedVideoFrame[] = []+ for (let i = 0; i < 5 * FPS; i++) frames.push(frameAt(i, i % (2 * FPS) === 0))+ const file = muxFrames(frames)+ const top = parse(file)+ const segment = find(top, 0x18538067)!+ // parse the segment DATA (the parser's node.start is exactly+ // where CueClusterPosition counts from)+ const segKids: Node[] = []+ parseInto(file, segment.start, file.length, segKids)+ const clusters = segKids.filter((n) => n.id === 0x1f43b675)+ const cues = segKids.find((n) => n.id === 0x1c53bb6b)!+ const points = childrenOf(file, cues)++ expect(points.length).toBe(clusters.length)+ points.forEach((point, i) => {+ const kids = childrenOf(file, point)+ const ctp = find(kids, 0xb7)!+ const pos = uintValue(file, find(childrenOf(file, ctp), 0xf1)!)+ // CueClusterPosition is relative to the segment DATA start —+ // the cluster element must REALLY start at that byte.+ const absolute = segment.start + pos+ const rid = readId(file, absolute)+ expect(rid.id, `cue ${i} → byte ${absolute}`).toBe(0x1f43b675)+ const cueTime = uintValue(file, find(kids, 0xb3)!)+ const base = uintValue(file, find(childrenOf(file, clusters[i]), 0xe7)!)+ expect(cueTime).toBe(base)+ })+ })+})++// ── G/H. honesty guards ───────────────────────────────────────++describe('webm-muxer: honesty guards', () => {+ it('finalize is one-shot — a half-patched file must never ship twice', () => {+ const muxer = new WebMMuxer({ width: 64, height: 64, codec: 'V_VP8', durationMs: 1_000 })+ muxer.addFrame(frameAt(0, true))+ muxer.finalize()+ expect(() => muxer.finalize()).toThrow(/already finalized/)+ expect(() => muxer.addFrame(frameAt(1, false))).toThrow(/finalized/)+ })++ it('refuses empty payloads (encoder bug, not a valid frame)', () => {+ const muxer = new WebMMuxer({ width: 64, height: 64, codec: 'V_VP9', durationMs: 1_000 })+ expect(() => muxer.addFrame({ data: new Uint8Array(0), keyframe: true, timestampUs: 0, durationUs: 33_333 })).toThrow(+ /empty/,+ )+ })++ it('rejects absurd dimensions and durations at construction', () => {+ expect(() => new WebMMuxer({ width: 1, height: 64, codec: 'V_VP9', durationMs: 100 })).toThrow(/dimensions/)+ expect(() => new WebMMuxer({ width: 64, height: 64, codec: 'V_VP9', durationMs: -1 })).toThrow(/duration/)+ })++ it('counts frames honestly', () => {+ const muxer = new WebMMuxer({ width: 64, height: 64, codec: 'V_VP9', durationMs: 1_000 })+ expect(muxer.frames).toBe(0)+ muxer.addFrame(frameAt(0, true))+ muxer.addFrame(frameAt(1, false))+ expect(muxer.frames).toBe(2)+ })++ it('a zero-frame file still has a complete skeleton (empty Cues)', () => {+ const muxer = new WebMMuxer({ width: 64, height: 64, codec: 'V_VP9', durationMs: 500 })+ const file = muxer.finalize()+ const segment = find(parse(file), 0x18538067)!+ const segKids: Node[] = []+ parseInto(file, segment.start, file.length, segKids)+ expect(segKids.map((n) => n.id)).toEqual([0x1549a966, 0x1654ae6b]) // Info + Tracks only+ })+})++// ── the ffprobe cross-check (local/CI machines with ffmpeg) ────++describe('webm-muxer: ffprobe agrees (when ffmpeg is installed)', () => {+ it('parses a muxed file as webm/vp9 with the declared duration', async () => {+ // ffprobe needs REAL vp9 payloads to be happy — synthetic+ // bytes fail the codec parse. Only run this when we can pull+ // a real keyframe from ffmpeg's own encoder.+ const { execFileSync } = await import('node:child_process')+ let haveFfmpeg = true+ try {+ execFileSync('ffprobe', ['-version'])+ } catch {+ haveFfmpeg = false+ }+ if (!haveFfmpeg) return++ // 3 s of tiny test video, raw vp9 in ivf → extract one packet set+ const tmp = await import('node:fs/promises')+ const os = await import('node:os')+ const path = await import('node:path')+ const dir = await tmp.mkdtemp(path.join(os.tmpdir(), 'canvix-webm-'))+ const ivf = path.join(dir, 'in.ivf')+ execFileSync(+ 'ffmpeg',+ ['-v', 'error', '-f', 'lavfi', '-i', 'testsrc2=duration=3:size=320x240:rate=10', '-c:v', 'libvpx-vp9', '-b:v', '0', ivf],+ { timeout: 30_000 },+ )+ // demux ivf into per-frame payloads: 32-byte file header then+ // per frame [4-byte LE size][8-byte LE pts][payload]+ // pts is in timebase units — ivf header carries rate/scale at+ // offsets 16/24, so usPerTick = 1e6 * scale / rate.+ const ivfBytes = await tmp.readFile(ivf)+ const rate = ivfBytes.readUInt32LE(16)+ const scale = ivfBytes.readUInt32LE(20)+ const usPerTick = (1e6 * scale) / rate+ const frames: MuxedVideoFrame[] = []+ let at = 32 // ivf file header+ let pts = 0+ while (at + 12 <= ivfBytes.length) {+ const sz = ivfBytes[at] | (ivfBytes[at + 1] << 8) | (ivfBytes[at + 2] << 16) | (ivfBytes[at + 3] << 24)+ pts = Number(ivfBytes.readBigUInt64LE(at + 4))+ const data = ivfBytes.subarray(at + 12, at + 12 + sz)+ frames.push({+ data: new Uint8Array(data),+ keyframe: frames.length === 0,+ timestampUs: Math.round(pts * usPerTick),+ durationUs: Math.round(usPerTick),+ })+ at += 12 + sz+ }+ expect(frames.length).toBe(30)+ expect(frames[1].timestampUs - frames[0].timestampUs).toBeGreaterThanOrEqual(99_999) // really 100 ms steps++ const muxer = new WebMMuxer({ width: 320, height: 240, codec: 'V_VP9', durationMs: 3_000 })+ for (const f of frames) muxer.addFrame(f)+ const out = path.join(dir, 'muxed.webm')+ await tmp.writeFile(out, muxer.finalize())++ const probe = JSON.parse(+ execFileSync('ffprobe', ['-v', 'error', '-show_entries', 'format=format_name,duration', '-show_entries', 'stream=codec_name,width,height,nb_frames', '-of', 'json', out]).toString(),+ ) as {+ format: { format_name: string; duration: string }+ streams: { codec_name: string; width: number; height: number; nb_frames?: string }[]+ }+ expect(probe.format.format_name).toBe('matroska,webm')+ expect(probe.streams[0].codec_name).toBe('vp9')+ expect(probe.streams[0].width).toBe(320)+ expect(probe.streams[0].height).toBe(240)+ expect(Number(probe.format.duration)).toBeCloseTo(3.0, 1)+ await tmp.rm(dir, { recursive: true, force: true })+ }, 60_000)+})diff --git a/src/lib/webm-muxer.ts b/src/lib/webm-muxer.tsnew file mode 100644index 0000000..3ca8f01--- /dev/null+++ b/src/lib/webm-muxer.ts@@ -0,0 +1,473 @@+// ─────────────────────────────────────────────────────────────+// WebM muxer (v0.15 R2) — hand-rolled EBML writer, zero deps.+//+// WHY THIS EXISTS+// WebCodecs gives you ENCODED CHUNKS, not a container. For MP4+// the only honest zero-dep path is a multi-week moov/mdat+// project (the documented R2 decision point: a muxing dependency+// like mux.js stays OFF the table until MP4-everywhere is a real+// requirement — MP4 exports keep riding MediaRecorder where the+// browser can encode H.264). WebM, by contrast, is tractable by+// hand: a flat EBML tree of clusters + SimpleBlocks.+//+// WHAT IT WRITES (webm DocType, single video track, VP9/VP8)+// EBML header → Segment [size placeholder, patched at finalize]+// Info (TimecodeScale 1 ms · apps · Duration, patched)+// Tracks (one V_VP9/V_VP8 track, PixelWidth/Height)+// Cluster* (Timecode absolute-ms + SimpleBlocks)+// Cues (one CuePoint per cluster — real seeking)+//+// HOW IT HANDLES THE EBML ORDERING TRAP+// An element is ID → size → body, so a size must be known+// before the body exists. Small static trees (header, Info,+// Tracks, Cues) are therefore composed BOTTOM-UP into byte+// arrays (el()), while streamed elements (Segment, Cluster) are+// appended directly and get an 8-byte placeholder that+// finalize()/closeOpenCluster() patches with the true size.+//+// INVARIANTS THIS MODULE OWNS+// 1. Every size field is a legal EBML vint (never all-ones).+// 2. SimpleBlock relative timecodes fit int16 (clusters split+// far below the 32 767 ceiling — see CLUSTER_MAX_MS).+// 3. A frame that arrives "before" the open cluster's base+// closes the cluster and re-bases (realtime encoders emit in+// order, but the guard is cheap and fail-safe).+// 4. The first block of the first cluster is a keyframe — the+// export loop forces frame 0; this module TRUSTS the caller+// for that (it only records what it is told).+// 5. finalize() is one-shot: it patches Segment size + Duration+// and appends Cues; a second call throws (a half-patched+// file must never ship).+//+// HONEST LIMITS+// - No SeekHead (players scan the cluster list; Chrome's own+// MediaRecorder output has the same shape) · no lacing (one+// block per frame — VP9 frames are big, lacing saves nothing).+// - TimecodeScale is fixed at 1 ms: sub-ms frame stamps round+// (at ≤ 120 fps the rounded stamps stay strictly monotonic).+// - Single track. Audio-in-WebM via AudioEncoder is a+// documented post-R3 evaluation; audio exports ride+// MediaRecorder today (see video-export.ts engine dispatch).+// ─────────────────────────────────────────────────────────────++/** Codec the muxed track declares (Matroska CodecID grammar). */+export type WebMVideoCodec = 'V_VP9' | 'V_VP8'++export interface WebMMuxerOptions {+ width: number+ height: number+ codec: WebMVideoCodec+ /** Declared container duration in ms (frames / fps × 1000) —+ * patched into Info/Duration at finalize (never below the+ * observed last-frame end). */+ durationMs: number+}++/** One encoded frame handed to the muxer. Timestamps use the+ * WebCodecs convention (µs, presentation time). */+export interface MuxedVideoFrame {+ data: Uint8Array+ keyframe: boolean+ timestampUs: number+ durationUs: number+}++/** Cluster-split policy (ms). 5 s keeps files seekable-granular+ * and int16 relative timecodes comfortably in range (32 767). */+const CLUSTER_MAX_MS = 5_000+/** A keyframe only SPLITS a cluster once the cluster is this old —+ * otherwise a 1-frame-GOP encoder would make one cluster per+ * frame (bloat + slow seeking). */+const CLUSTER_MIN_MS = 1_000+/** SimpleBlock relative timecode hard ceiling (int16, with slack). */+const REL_TC_MAX = 32_000++// ── EBML element IDs (webm subset) ────────────────────────────+const ID_EBML = 0x1a45dfa3+const ID_EBML_VERSION = 0x4286+const ID_EBML_READ_VERSION = 0x42f7+const ID_EBML_MAX_ID_LENGTH = 0x42f2+const ID_EBML_MAX_SIZE_LENGTH = 0x42f3+const ID_DOCTYPE = 0x4282+const ID_DOCTYPE_VERSION = 0x4287+const ID_DOCTYPE_READ_VERSION = 0x4285++const ID_SEGMENT = 0x18538067+const ID_INFO = 0x1549a966+const ID_TIMECODE_SCALE = 0x2ad7b1+const ID_MUXING_APP = 0x4d80+const ID_WRITING_APP = 0x5741+const ID_DURATION = 0x4489++const ID_TRACKS = 0x1654ae6b+const ID_TRACK_ENTRY = 0xae+const ID_TRACK_NUMBER = 0xd7+const ID_TRACK_UID = 0x73c5+const ID_TRACK_TYPE = 0x83+const ID_FLAG_LACING = 0x9c+const ID_CODEC_ID = 0x86+const ID_VIDEO = 0xe0+const ID_PIXEL_WIDTH = 0xb0+const ID_PIXEL_HEIGHT = 0xba++const ID_CLUSTER = 0x1f43b675+const ID_CLUSTER_TIMECODE = 0xe7+const ID_SIMPLE_BLOCK = 0xa3++const ID_CUES = 0x1c53bb6b+const ID_CUE_POINT = 0xbb+const ID_CUE_TIME = 0xb3+const ID_CUE_TRACK_POSITIONS = 0xb7+const ID_CUE_TRACK = 0xf7+const ID_CUE_CLUSTER_POSITION = 0xf1++// ── pure byte helpers ─────────────────────────────────────────++/** Byte length of the minimal unsigned EBML vint for `value`.+ * A vint's payload must be ≤ 2^(7n) − 2 (all-ones is reserved+ * for "unknown"), so 127 needs two bytes, 16 383 needs three. */+export function vintLength(value: number): number {+ if (!Number.isFinite(value) || value < 0 || !Number.isInteger(value)) {+ throw new Error(`webm-muxer: invalid vint ${value}`)+ }+ let n = 1+ while (n < 8 && value > 2 ** (7 * n) - 2) n+++ // NOTE: guard on >= 2**56, not > 2**56 - 2 — doubles above 2^53+ // have 16-wide spacing, so 2**56 - 2 ROUNDS BACK to 2**56 and a+ // subtractive bound silently never fires (found by the unit suite).+ if (value >= 2 ** 56) throw new Error(`webm-muxer: vint too large: ${value}`)+ return n+}++/** Encode `value` as a minimal unsigned EBML vint. */+export function vintBytes(value: number): Uint8Array {+ const n = vintLength(value)+ const out = new Uint8Array(n)+ out[0] = 0x80 >> (n - 1) // the length marker's 1 bit+ let v = value+ for (let i = n - 1; i >= 1; i--) {+ out[i] = v & 0xff+ v = Math.floor(v / 256)+ }+ out[0] |= v & 0x7f+ return out+}++/** An EBML element ID in minimal big-endian form (IDs carry+ * their own leading 1 bit — no length prefix). */+export function idBytes(id: number): Uint8Array {+ const bytes: number[] = []+ let v = id+ while (v > 0) {+ bytes.unshift(v & 0xff)+ v = Math.floor(v / 256)+ }+ if (bytes.length === 0 || bytes.length > 4) throw new Error(`webm-muxer: bad element id ${id}`)+ return new Uint8Array(bytes)+}++/** Minimal big-endian unsigned integer body. */+export function uintBE(value: number): Uint8Array {+ if (!Number.isInteger(value) || value < 0) throw new Error(`webm-muxer: bad uint ${value}`)+ const bytes: number[] = []+ let v = value+ do {+ bytes.unshift(v & 0xff)+ v = Math.floor(v / 256)+ } while (v > 0)+ return new Uint8Array(bytes)+}++/** Big-endian IEEE double body. */+export function float64BE(value: number): Uint8Array {+ const f = new Float64Array(1)+ f[0] = value+ const le = new Uint8Array(f.buffer)+ const be = new Uint8Array(8)+ for (let i = 0; i < 8; i++) be[i] = le[7 - i]+ return be+}++/** A complete element: ID + size-vint + body. */+export function el(id: number, body: Uint8Array): Uint8Array {+ const idB = idBytes(id)+ const sizeB = vintBytes(body.length)+ const out = new Uint8Array(idB.length + sizeB.length + body.length)+ out.set(idB, 0)+ out.set(sizeB, idB.length)+ out.set(body, idB.length + sizeB.length)+ return out+}++/** Minimal unsigned-integer child element. */+export function uintEl(id: number, value: number): Uint8Array {+ return el(id, uintBE(value))+}++/** UTF-8 string child element. */+export function stringEl(id: number, s: string): Uint8Array {+ return el(id, new TextEncoder().encode(s))+}++function concat(...parts: Uint8Array[]): Uint8Array {+ let n = 0+ for (const p of parts) n += p.length+ const out = new Uint8Array(n)+ let at = 0+ for (const p of parts) {+ out.set(p, at)+ at += p.length+ }+ return out+}++/** An 8-byte vint placeholder (marker 0x01 + seven 0x00 bytes)+ * for sizes that are only known later; `patchVint8` fills it. */+function vint8Placeholder(): Uint8Array {+ const out = new Uint8Array(8)+ out[0] = 0x01+ return out+}++/** Write the true size into an 8-byte vint placeholder. */+function patchVint8(target: Uint8Array, offset: number, size: number): void {+ if (size >= 2 ** 56) throw new Error('webm-muxer: size too large for an 8-byte vint')+ let v = size+ for (let i = 7; i >= 1; i--) {+ target[offset + i] = v & 0xff+ v = Math.floor(v / 256)+ }+ target[offset] = 0x01 | (v & 0x7f)+}++// ── append-only buffer with in-place patching ─────────────────+class ByteSink {+ private buf: Uint8Array+ private len = 0++ constructor(initial = 1 << 16) {+ this.buf = new Uint8Array(initial)+ }++ get length(): number {+ return this.len+ }++ private ensure(extra: number): void {+ if (this.len + extra <= this.buf.length) return+ let cap = this.buf.length+ while (cap < this.len + extra) cap *= 2+ const next = new Uint8Array(cap)+ next.set(this.buf.subarray(0, this.len))+ this.buf = next+ }++ bytes(b: Uint8Array): void {+ this.ensure(b.length)+ this.buf.set(b, this.len)+ this.len += b.length+ }++ patchAt(offset: number, b: Uint8Array): void {+ if (offset < 0 || offset + b.length > this.len) throw new Error('webm-muxer: patch out of range')+ this.buf.set(b, offset)+ }++ /** A stable, mutation-safe copy of everything written so far+ * (backed by a plain ArrayBuffer — BlobPart-friendly). */+ finish(): Uint8Array<ArrayBuffer> {+ return this.buf.slice(0, this.len)+ }+}++/** A closed cluster, remembered for the Cues element. */+interface FinishedCluster {+ /** Offset of the cluster element ID relative to the segment+ * DATA start — exactly what CueClusterPosition demands. */+ relOffset: number+ /** Absolute cluster base timecode (ms). */+ baseMs: number+}++export class WebMMuxer {+ private readonly sink = new ByteSink()+ private readonly opts: WebMMuxerOptions+ private readonly clusters: FinishedCluster[] = []+ private frameCount = 0+ /** End of the last frame (ms) — the observed duration floor. */+ private lastEndMs = 0++ /** Where the segment's 8-byte size placeholder lives. */+ private readonly segmentSizeAt: number+ /** Buffer offset just past the segment ID + size fields. */+ private readonly segmentDataStart: number+ /** Where the open cluster's 8-byte size placeholder lives. */+ private openSizeAt = -1+ /** Buffer offset just past the open cluster's ID + size fields. */+ private openBodyStart = -1+ /** Buffer offset of the open cluster's element ID. */+ private openIdAt = -1+ /** Base timecode (ms) of the open cluster. */+ private openBaseMs = 0++ /** Where Info/Duration's float body lives (patched at finalize). */+ private readonly durationAt: number+ private finalized = false++ constructor(opts: WebMMuxerOptions) {+ if (!Number.isInteger(opts.width) || !Number.isInteger(opts.height) || opts.width < 2 || opts.height < 2) {+ throw new Error(`webm-muxer: bad dimensions ${opts.width}x${opts.height}`)+ }+ if (!Number.isFinite(opts.durationMs) || opts.durationMs < 0) {+ throw new Error(`webm-muxer: bad duration ${opts.durationMs}`)+ }+ this.opts = opts++ // ── EBML header (composed bottom-up) ─────────────────────+ this.sink.bytes(+ el(+ ID_EBML,+ concat(+ uintEl(ID_EBML_VERSION, 1),+ uintEl(ID_EBML_READ_VERSION, 1),+ uintEl(ID_EBML_MAX_ID_LENGTH, 4),+ uintEl(ID_EBML_MAX_SIZE_LENGTH, 8),+ stringEl(ID_DOCTYPE, 'webm'),+ uintEl(ID_DOCTYPE_VERSION, 2),+ uintEl(ID_DOCTYPE_READ_VERSION, 2),+ ),+ ),+ )++ // ── Segment with an 8-byte size placeholder ──────────────+ this.sink.bytes(idBytes(ID_SEGMENT))+ this.segmentSizeAt = this.sink.length+ this.sink.bytes(vint8Placeholder())+ this.segmentDataStart = this.sink.length++ // ── Info (Duration is the LAST child → its float body is+ // the final 8 bytes of the blob; the offset is captured+ // for the finalize patch) ──────────────────────────────+ const info = el(+ ID_INFO,+ concat(+ uintEl(ID_TIMECODE_SCALE, 1_000_000), // 1 ms per timecode tick+ stringEl(ID_MUXING_APP, 'Canvix'),+ stringEl(ID_WRITING_APP, 'Canvix WebCodecs export'),+ el(ID_DURATION, float64BE(opts.durationMs)),+ ),+ )+ this.durationAt = this.sink.length + info.length - 8+ this.sink.bytes(info)++ // ── Tracks: one video track (composed bottom-up) ──────────+ this.sink.bytes(+ el(+ ID_TRACKS,+ el(+ ID_TRACK_ENTRY,+ concat(+ uintEl(ID_TRACK_NUMBER, 1),+ uintEl(ID_TRACK_UID, 1),+ uintEl(ID_TRACK_TYPE, 1), // 1 = video+ uintEl(ID_FLAG_LACING, 0), // we never lace+ stringEl(ID_CODEC_ID, opts.codec),+ el(ID_VIDEO, concat(uintEl(ID_PIXEL_WIDTH, opts.width), uintEl(ID_PIXEL_HEIGHT, opts.height))),+ ),+ ),+ ),+ )+ }++ /** Append one encoded frame (frames arrive in decode order; an+ * out-of-order stamp closes the cluster and re-bases). */+ addFrame(frame: MuxedVideoFrame): void {+ if (this.finalized) throw new Error('webm-muxer: finalized — addFrame after finalize')+ if (frame.data.length === 0) throw new Error('webm-muxer: empty frame payload')+ const tMs = Math.round(frame.timestampUs / 1000)+ this.frameCount += 1+ this.lastEndMs = Math.max(this.lastEndMs, tMs + Math.max(1, Math.round(frame.durationUs / 1000)))++ // split policy — evaluated BEFORE opening the next cluster+ if (this.openIdAt >= 0) {+ const rel = tMs - this.openBaseMs+ const age = tMs - this.openBaseMs+ if (rel < 0 || rel > REL_TC_MAX || age >= CLUSTER_MAX_MS || (frame.keyframe && age >= CLUSTER_MIN_MS)) {+ this.closeOpenCluster()+ }+ }++ if (this.openIdAt < 0) {+ this.openIdAt = this.sink.length+ this.sink.bytes(idBytes(ID_CLUSTER))+ this.openSizeAt = this.sink.length+ this.sink.bytes(vint8Placeholder())+ this.openBodyStart = this.sink.length+ this.openBaseMs = tMs+ this.sink.bytes(uintEl(ID_CLUSTER_TIMECODE, tMs))+ }++ // SimpleBlock: [track vint 0x81][int16 rel timecode][flags][payload]+ const rel = tMs - this.openBaseMs+ const rel16 = Math.max(-32768, Math.min(32767, rel))+ const blockBody = new Uint8Array(4 + frame.data.length)+ blockBody[0] = 0x81 // track number 1 as a vint+ blockBody[1] = (rel16 & 0xff00) >> 8+ blockBody[2] = rel16 & 0xff+ blockBody[3] = frame.keyframe ? 0x80 : 0x00+ blockBody.set(frame.data, 4)+ this.sink.bytes(el(ID_SIMPLE_BLOCK, blockBody))+ }++ /** Close the open cluster: patch its placeholder size and+ * remember it for the Cues element. */+ private closeOpenCluster(): void {+ if (this.openIdAt < 0) return+ const size = this.sink.length - this.openBodyStart+ const patch = vint8Placeholder()+ patchVint8(patch, 0, size)+ this.sink.patchAt(this.openSizeAt, patch)+ this.clusters.push({ relOffset: this.openIdAt - this.segmentDataStart, baseMs: this.openBaseMs })+ this.openIdAt = -1+ this.openSizeAt = -1+ this.openBodyStart = -1+ }++ /** Number of frames muxed so far. */+ get frames(): number {+ return this.frameCount+ }++ /** Patch the segment size + Duration, append Cues, return the+ * complete file (plain-ArrayBuffer-backed). One-shot. */+ finalize(): Uint8Array<ArrayBuffer> {+ if (this.finalized) throw new Error('webm-muxer: already finalized')+ this.finalized = true+ this.closeOpenCluster()++ // ── Cues: one CuePoint per cluster ───────────────────────+ if (this.clusters.length > 0) {+ const points = this.clusters.map((c) =>+ el(+ ID_CUE_POINT,+ concat(+ uintEl(ID_CUE_TIME, c.baseMs),+ el(ID_CUE_TRACK_POSITIONS, concat(uintEl(ID_CUE_TRACK, 1), uintEl(ID_CUE_CLUSTER_POSITION, c.relOffset))),+ ),+ ),+ )+ this.sink.bytes(el(ID_CUES, concat(...points)))+ }++ // ── patch the segment size with everything written ───────+ const segPatch = vint8Placeholder()+ patchVint8(segPatch, 0, this.sink.length - this.segmentDataStart)+ this.sink.patchAt(this.segmentSizeAt, segPatch)++ // ── patch Duration: never below the observed last-frame end ──+ const durationMs = Math.max(this.opts.durationMs, this.lastEndMs)+ this.sink.patchAt(this.durationAt, float64BE(durationMs))++ return this.sink.finish()+ }+}diff --git a/tests/e2e/webcodecs-export.spec.ts b/tests/e2e/webcodecs-export.spec.tsnew file mode 100644index 0000000..12fcfd9--- /dev/null+++ b/tests/e2e/webcodecs-export.spec.ts@@ -0,0 +1,159 @@+import { test, expect, type APIRequestContext, type Page } from '@playwright/test'+import { execFileSync } from 'node:child_process'++/**+ * v0.15 (R2): WebCodecs export — acceptance.+ *+ * 1. a SILENT animated design (2 pages, 60+ animated elements —+ * the acceptance bar from the roadmap) exports through the+ * WebCodecs engine: the dialog says so, and the downloaded+ * file is a WebM whose VIDEO stream is VP9 with NO audio+ * track (the engine matrix routes audio designs to+ * MediaRecorder — that path keeps its own coverage in+ * v0110-smoke).+ * 2. FRAME-EXACT: ffprobe counts every frame — nb_read_frames+ * must equal duration × fps. The old MediaRecorder loop+ * paced against the wall clock and dropped frames when+ * rendering fell behind; the WebCodecs loop has no clock and+ * cannot drop.+ * 3. dimensions follow the 1× quality cap (960 longest edge,+ * even pixels).+ *+ * Register budget: ZERO — one anonymous design, fresh context+ * (the PR #26/#30 lesson).+ */++const BASE = process.env.BASE_URL ?? 'http://localhost:3000'++/** the export pipeline's fixed fps */+const FPS = 30++interface RectElement {+ id: string+ type: 'rect'+ x: number+ y: number+ width: number+ height: number+ rotation: number+ opacity: number+ locked: boolean+ visible: boolean+ fill: string+ stroke: string+ strokeWidth: number+ cornerRadius: number+ animation: { kind: 'fade' | 'rise' | 'pan'; duration: number; delay: number; easing: 'easeOut'; direction?: 'up' | 'left' }+}++function animatedRect(i: number, page: number): RectElement {+ const col = i % 10+ const row = Math.floor(i / 10)+ return {+ id: `R${page}-${i}`,+ type: 'rect',+ x: 20 + col * 78,+ y: 20 + row * 58,+ width: 64,+ height: 44,+ rotation: 0,+ opacity: 1,+ locked: false,+ visible: true,+ fill: `hsl(${(i * 37) % 360} 70% 55%)`,+ stroke: '',+ strokeWidth: 0,+ cornerRadius: 6,+ animation: { kind: i % 3 === 0 ? 'rise' : i % 3 === 1 ? 'pan' : 'fade', duration: 0.6, delay: (i % 10) * 0.08, easing: 'easeOut', direction: i % 2 === 0 ? 'up' : 'left' },+ }+}++async function createSilentDesign(request: APIRequestContext): Promise<string> {+ const pages = [0, 1].map((p) => ({+ id: `p${p + 1}`,+ background: { type: 'solid' as const, color: '#ffffff' },+ // the transition INTO page 2 rides on page 2 (buildTimeline+ // reads pages[i+1].transition)+ transition: p === 1 ? { kind: 'fade' as const, duration: 0.7 } : undefined,+ elements: Array.from({ length: 32 }, (_, i) => animatedRect(i, p)),+ }))+ const res = await request.post(`${BASE}/api/designs`, {+ data: { name: 'r2 webcodecs acceptance', width: 1080, height: 720, pages },+ })+ expect(res.status(), `create design: ${await res.text()}`).toBeLessThan(300)+ return ((await res.json()) as { id: string }).id+}++async function openEditor(page: Page, designId: string): Promise<void> {+ await page.goto(`/design/${designId}`)+ await page.addStyleTag({ content: 'nextjs-portal { display: none !important; }' })+ await expect(page.getByLabel('Design canvas')).toBeVisible({ timeout: 60_000 })+}++test('silent animated design exports via WebCodecs — VP9 WebM, frame-exact, no audio', async ({ page, request }) => {+ test.setTimeout(240_000)++ const designId = await createSilentDesign(request)+ await openEditor(page, designId)++ // WebCodecs must exist in this browser for the assertion to be+ // meaningful (Chromium has it; skip honestly elsewhere)+ const webcodecs = await page.evaluate(async () => {+ if (typeof VideoEncoder === 'undefined' || typeof VideoFrame === 'undefined') return false+ try {+ const probe = await VideoEncoder.isConfigSupported({ codec: 'vp09.00.10.08', width: 960, height: 640, bitrate: 1_000_000, framerate: 30 })+ return probe.supported === true+ } catch {+ return false+ }+ })+ test.skip(!webcodecs, 'this browser has no WebCodecs VideoEncoder for VP9')++ await page.getByLabel('Download').click()+ const dlg = page.getByRole('dialog')+ await expect(dlg.getByText('Download your design')).toBeVisible()+ await dlg.getByRole('button', { name: /Video/ }).click()++ // the engine line is honest BEFORE the export starts+ await expect(dlg.getByText(/WebCodecs → WebM \(VP9\)/)).toBeVisible({ timeout: 30_000 })++ const [download] = await Promise.all([+ page.waitForEvent('download', { timeout: 200_000 }),+ dlg.getByRole('button', { name: /^Download/ }).click(),+ ])+ const path = (await download.path())!+ expect(download.suggestedFilename()).toMatch(/\.webm$/)++ // ── ffprobe: container, codec, dimensions, NO audio stream ──+ const probe = JSON.parse(+ execFileSync('ffprobe', ['-v', 'error', '-show_entries', 'format=format_name,duration', '-show_entries', 'stream=index,codec_type,codec_name,width,height', '-of', 'json', path]).toString(),+ ) as {+ format: { format_name: string; duration: string }+ streams: { codec_type: string; codec_name: string; width: number; height: number }[]+ }+ expect(probe.format.format_name).toContain('webm')+ expect(probe.streams.length, `streams: ${JSON.stringify(probe.streams)}`).toBe(1)+ const video = probe.streams[0]+ expect(video.codec_type).toBe('video')+ expect(video.codec_name).toBe('vp9')+ // the dialog's shared quality selector defaults to 2× → a 1440+ // cap on a 1080×720 design means NO downscale (min(1, 1440/1080))+ expect(video.width).toBe(1080)+ expect(video.height).toBe(720)++ // ── FRAME-EXACT: every frame the timeline promised is in the file ──+ const counted = JSON.parse(+ execFileSync('ffprobe', ['-v', 'error', '-count_frames', '-select_streams', 'v:0', '-show_entries', 'stream=nb_read_frames,avg_frame_rate', '-of', 'json', path]).toString(),+ ) as { streams: { nb_read_frames: string; avg_frame_rate: string }[] }+ const nbRead = Number(counted.streams[0].nb_read_frames)+ const duration = Number(probe.format.duration)+ expect(Number.isFinite(nbRead) && nbRead, `nb_read_frames: ${JSON.stringify(counted)}`).toBeGreaterThan(0)++ // duration sanity: 2 pages, each ≥ 2.2 s hold + 0.7 s transition+ expect(duration).toBeGreaterThanOrEqual(4.5)++ // the frame-exact contract: count === duration × fps (±1 for+ // rounding at the container boundary)+ const expected = Math.round(duration * FPS)+ expect(Math.abs(nbRead - expected), `frames ${nbRead} vs duration×fps ${expected}`).toBeLessThanOrEqual(1)+})