Browser-Side MP4 Export with WebCodecs: Frames, Timestamps, and Backpressure
canvas.captureStream(30) plus MediaRecorder is the easiest way to turn a canvas animation into a video. It is also the least repeatable one. Recording happens in wall-clock time, so a slow tab or a backgrounded window quietly drops frames, and the same input can produce two different files.
WebCodecs fixes that: you hand the encoder explicit frames and explicit timestamps. The tradeoff is that you now own the container. Here is the pipeline that survived real use, including the three bugs that only show up after a few hundred frames.
1. Separate rendering from encoding
The renderer should know nothing about video. It takes a frame index and a scene, and draws one image:
const FPS = 30;
const FRAME_COUNT = FPS * 6;
function renderFrame(ctx, frame, scene) {
const t = frame / (FRAME_COUNT - 1);
ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
drawSeries(ctx, scene.series, t);
}
const canvas = new OffscreenCanvas(1920, 1080);
const ctx = canvas.getContext('2d');
The same function feeds the live preview, the PNG thumbnail, the GIF encoder, and the MP4 encoder. If you write a second renderer for export, the two will drift apart within a week.
2. Configure the encoder for a muxable stream
const encoder = new VideoEncoder({
output: (chunk, meta) => handleChunk(chunk, meta),
error: e => console.error('VideoEncoder', e),
});
encoder.configure({
codec: 'avc1.42001f',
width: 1920,
height: 1080,
bitrate: 8_000_000,
framerate: FPS,
latencyMode: 'quality',
avc: { format: 'avc' },
});
avc: { format: 'avc' } is the detail people miss. It gives you length-prefixed NAL units and a description on the metadata object — exactly what an MP4 avcC box needs. With the default annexb format you have to convert the NAL starts yourself, and every muxer will ask you for that description anyway.
3. Timestamps come from the frame index, not the clock
WebCodecs timestamps are microseconds. Derive them from the index:
for (let frame = 0; frame < FRAME_COUNT; frame++) {
renderFrame(ctx, frame, scene);
const videoFrame = new VideoFrame(canvas, {
timestamp: Math.round(frame * 1_000_000 / FPS),
duration: Math.round(1_000_000 / FPS),
});
encoder.encode(videoFrame, { keyFrame: frame % (FPS * 2) === 0 });
videoFrame.close();
}
await encoder.flush();
Do not use performance.now() here. It makes the output depend on machine speed, and it makes seeking and thumbnail extraction a guessing game. A two-second keyframe interval is a reasonable default: it keeps scrubbing responsive without bloating the file.
VideoFrame.close() matters. In a 180-frame export each frame holds a GPU-backed image; forgetting to close them is an easy way to exhaust memory halfway through.
4. Output order is not input order
With B frames enabled, output callbacks can arrive out of order. The muxer needs samples sorted by timestamp:
const pending = [];
function handleChunk(chunk, meta) {
pending.push({
data: new Uint8Array(chunk.byteLength),
timestamp: chunk.timestamp,
duration: chunk.duration,
type: chunk.type,
description: meta?.decoderConfig?.description,
});
chunk.copyTo(pending[pending.length - 1].data);
}
// after flush()
pending.sort((a, b) => a.timestamp - b.timestamp);
If you want the simple path, disable B frames in the encoder config and the callback order will match input order. I keep them enabled for the bitrate saving and sort explicitly — the sort costs microseconds.
5. Backpressure is not optional
encoder.encode() returns immediately. A 4K, six-second clip pushes 180 frames into the queue faster than the hardware can consume them, and encodeQueueSize climbs until the browser kills the tab.
async function encodeWhenReady(frame) {
while (encoder.encodeQueueSize > 4) {
await new Promise(resolve => {
encoder.addEventListener('dequeue', resolve, { once: true });
});
}
encoder.encode(frame);
}
A queue depth of four keeps the hardware busy without buffering a second of video in memory. The dequeue event is the only reliable signal — setTimeout guesses will fail on slower devices.
6. Mux into MP4
Use a small muxer library rather than writing ISO BMFF boxes by hand. The shape of the call is always the same:
const muxer = new Muxer({
target: new ArrayBufferTarget(),
video: { codec: 'avc', width: 1920, height: 1080 },
fastStart: 'in-memory',
});
for (const s of pending) {
muxer.addVideoChunk({
type: s.type,
timestamp: s.timestamp,
duration: s.duration,
data: s.data,
// from the encoder metadata, only on the first chunk
decoderConfig: s.description ? { description: s.description } : undefined,
});
}
const blob = new Blob([muxer.finalize().buffer], { type: 'video/mp4' });
fastStart: 'in-memory' moves the moov atom to the front. Without it the file plays locally but stalls on first load in a browser or a chat app, which reads as "the export is broken."
7. The silent-audio trap
A video track alone is valid MP4, but some players report the duration as zero or refuse to scrub. Adding a silent AAC track fixes it:
const audioEncoder = new AudioEncoder({
output: (chunk, meta) => muxer.addAudioChunk(chunk, meta.decoderConfig),
error: console.error,
});
audioEncoder.configure({
codec: 'mp4a.40.2',
sampleRate: 48000,
numberOfChannels: 2,
bitrate: 128000,
});
const samples = new Float32Array(1024 * 2); // 1024 frames per channel
const audio = new AudioData({
format: 'f32-planar',
sampleRate: 48000,
numberOfFrames: 1024,
numberOfChannels: 2,
timestamp: frame * 1_000_000 / FPS,
data: samples,
});
audioEncoder.encode(audio);
audio.close();
Keep the audio timestamps on the same microsecond base as the video. Give the muxer one audio sample per video frame and the duration will line up exactly.
8. Where this came from
These constraints come from LivelyChart, which I help build. It turns a spreadsheet into animated charts: you describe the scene — board deck, product launch, QBR, social clip — and it generates the templates, maps labels and values, then exports MP4, WebM, GIF, or PNG up to 4K. The same renderFrame drives the preview and every export path, and the spreadsheet data stays in the browser unless you ask the AI to edit it.
If you are building this yourself, start with a six-second clip, sort your chunks, add the silent track, and check the file in a browser that is not your dev server. That catches most of it.
Disclosure: I am one of the builders of LivelyChart, linked above.

Top comments (0)