Skip to content

Video as code: canvas scenes rendered with WebCodecs in headless Chrome, a review viewer, and agent skills that build the video from your references.

Tag the colour range the encoder used; WebGL without a GPU

StaryOne11176ba02f33
diff --git a/docs/cli.md b/docs/cli.md
index 4c3ca6a..a385300 100644
--- a/docs/cli.md
+++ b/docs/cli.md
@@ -51,7 +51,7 @@ When the page throws while loading, the error names the file, line and column, f
| `--chrome` | Path to Chrome. Default: found automatically, or the `CHROME` environment variable |
| `--format` | `png` or `jpg`, for `stills` |
-`--gpu` is accepted and ignored, so older commands that pass it keep working. Chrome always runs with `--enable-gpu --force_high_performance_gpu`.
+`--gpu` is accepted and ignored, so older commands that pass it keep working. Chrome always runs with `--enable-gpu --force_high_performance_gpu --enable-unsafe-swiftshader`; the last lets WebGL fall back to software where there is no GPU.
## Environment
diff --git a/docs/rendering.md b/docs/rendering.md
index 28ca2ad..1998d2f 100644
--- a/docs/rendering.md
+++ b/docs/rendering.md
@@ -5,10 +5,10 @@ How `motlab render`, `motlab video` and Export turn scene pages into an MP4, how
## Steps
1. A small static server serves the project folder (the nearest folder above the page with a `project.json`, else the page's folder, or `--root`) on `127.0.0.1`.
-2. Chrome starts with `--headless=new --enable-gpu --force_high_performance_gpu`. The GPU actually in use is read from `WEBGL_debug_renderer_info` and printed at the start.
+2. Chrome starts with `--headless=new --enable-gpu --force_high_performance_gpu --enable-unsafe-swiftshader`. The GPU actually in use is read from `WEBGL_debug_renderer_info` and printed at the start.
3. `src/page/runtime.js` is injected into the page. For each frame it calls `renderAt`, makes a `VideoFrame` from the canvas and feeds it to a `VideoEncoder`.
4. Mediabunny muxes the encoded chunks into an MP4 inside the page, which is POSTed to Node. If that fails, the engine retries with a raw Annex B bitstream.
-5. ffmpeg copies the stream (`-c copy`) into the final file. This pass writes BT.709 limited range tags into the bitstream, joins the parts from parallel mode, adds audio and moves `moov` to the front. It always runs, even after a successful Mediabunny mux, because the encoders tag colour inconsistently (see quirks).
+5. ffmpeg copies the stream (`-c copy`) into the final file. This pass writes BT.709 tags with the encoder's range into the bitstream, joins the parts from parallel mode, adds audio and moves `moov` to the front. It always runs, even after a successful Mediabunny mux, because the encoders tag colour inconsistently (see quirks).
6. ffprobe counts the frames and duration of the final file. The render fails if they do not match.
Temporary files go to the system temp folder and are removed afterwards. The output is written as `.part` and renamed at the end.
@@ -119,14 +119,14 @@ To compare on the same GPU, motlab ran again on the Radeon (`IGPU=1 node run.mjs
### Without a GPU
-The same benchmark with Chrome drawing in software (`CPU=1 node run.mjs`, and `CPU=1 SCALE=2` for 4K), on the same laptop with nothing else running. All three use ANGLE on SwiftShader (`--use-gl=angle --use-angle=swiftshader --enable-unsafe-swiftshader`): HyperFrames through `--no-browser-gpu`, Remotion through `--gl=swangle`, and motlab through [bench/motlab-cpu.mjs](../bench/motlab-cpu.mjs), which swaps motlab's GPU flags for these (motlab has no option for it). motlab encodes with `--encoder sw`; Remotion and HyperFrames encode with ffmpeg on the CPU by default. motlab's `GPU:` line named SwiftShader, and in one 1080p run each of motlab, Remotion's canvas and HyperFrames' canvas, the Windows GPU counters showed no GPU work from their Chrome. The GPUs were still in the laptop, so this is software drawing on a laptop CPU, not a measured machine without a GPU. SSIM is against the same stills as above, drawn on the GPU.
+The same benchmark with Chrome drawing in software (`CPU=1 node run.mjs`, and `CPU=1 SCALE=2` for 4K), on the same laptop with nothing else running. All three use ANGLE on SwiftShader (`--use-gl=angle --use-angle=swiftshader --enable-unsafe-swiftshader`): HyperFrames through `--no-browser-gpu`, Remotion through `--gl=swangle`, and motlab through [bench/motlab-cpu.mjs](../bench/motlab-cpu.mjs), which swaps motlab's GPU flags for these (motlab has no option for it). motlab encodes with `--encoder sw`; Remotion and HyperFrames encode with ffmpeg on the CPU by default. motlab's `GPU:` line named SwiftShader, and in one 1080p run each of motlab, Remotion's canvas and HyperFrames' canvas, the Windows GPU counters showed no GPU work from their Chrome. The GPUs were still in the laptop, so this is software drawing on a laptop CPU, not a measured machine without a GPU. SSIM is against the same stills as above, drawn on the GPU. motlab's SSIM was measured again after the colour range fix below (one run each); the times are from before it, and the fix changes only the tags ffmpeg writes.
At 1080p:
| Tool and setting | Time | fps overall | SSIM | File | With a GPU |
|---|---|---|---|---|---|
-| motlab, `--encoder sw --workers 4` | 19.2 s | 15.6 | 0.980 | 30.0 MB | |
-| motlab, `--encoder sw` | 27.0 s | 11.1 | 0.980 | 29.9 MB | 9.5 s |
+| motlab, `--encoder sw --workers 4` | 19.2 s | 15.6 | 0.982 | 30.0 MB | |
+| motlab, `--encoder sw` | 27.0 s | 11.1 | 0.983 | 29.9 MB | 9.5 s |
| HyperFrames, canvas, default | 28.3 s | 10.6 | 0.987 | 20.4 MB | 27.6 s |
| HyperFrames, HTML, default (6 workers) | 29.4 s | 10.2 | 0.965 | 20.5 MB | 30.9 s |
| HyperFrames, HTML, `--workers 1` | 30.5 s | 9.8 | 0.965 | 20.5 MB | 27.2 s |
@@ -140,9 +140,9 @@ At 4K:
|---|---|---|---|---|---|
| HyperFrames, canvas, default | 43.4 s | 6.9 | 0.985 | 36.5 MB | 50.9 s |
| HyperFrames, HTML, default (6 workers) | 50.7 s | 5.9 | 0.972 | 49.0 MB | 54.3 s |
-| motlab, `--encoder sw --workers 4` | 60.7 s | 4.9 | 0.988 | 83.9 MB | |
+| motlab, `--encoder sw --workers 4` | 60.7 s | 4.9 | 0.991 | 83.9 MB | |
| HyperFrames, HTML, `--workers 1` | 63.2 s | 4.8 | 0.972 | 49.0 MB | 71.8 s |
-| motlab, `--encoder sw` | 67.3 s | 4.5 | 0.988 | 84.5 MB | 14.8 s |
+| motlab, `--encoder sw` | 67.3 s | 4.5 | 0.992 | 84.5 MB | 14.8 s |
| Remotion, canvas, default | 72.4 s | 4.1 | 0.977 | 35.7 MB | 48.9 s |
| Remotion, HTML, `--concurrency=1` | 130.6 s | 2.3 | 0.964 | 42.9 MB | 53.8 s |
| Remotion, HTML, default | 154.2 s | 1.9 | 0.964 | 42.9 MB | 61.1 s |
@@ -166,7 +166,9 @@ Not measured: macOS, where HyperFrames turns on a capture through `drawElementIm
- The hardware encoder hangs after a mid-stream `flush()`: the next `encode()` never finishes. Flush only once, at the end.
- Software H.264 ignores bitrate. Targets of 2, 22, 60 or 200 Mbit/s give nearly the same file. `quantizer` mode is not supported for software H.264. `contentHint: 'detail'` raises quality slightly but is slower.
- Hardware H.264 and HEVC support `bitrateMode: 'quantizer'`. QP is passed per frame with `encode(frame, { avc: { quantizer } })`.
-- Colour tags in the bitstream are inconsistent: hardware H.264 writes none, hardware HEVC writes `colour_primaries=0`, and software H.264 writes an sRGB transfer. ffmpeg always overwrites the VUI with BT.709 limited range through `h264_metadata` or `hevc_metadata`.
+- Colour tags in the bitstream are inconsistent: hardware H.264 writes none, hardware HEVC writes `colour_primaries=0`, and software H.264 writes an sRGB transfer. ffmpeg always overwrites the VUI with BT.709 and the encoder's range through `h264_metadata` or `hevc_metadata`.
+- The range depends on how Chrome draws. On a GPU, a canvas frame becomes limited range YUV; when Chrome draws in software (SwiftShader, or a CI runner without a GPU) it becomes full range, with both the hardware and the software encoder. The encoder's `decoderConfig.colorSpace.fullRange` says which, and motlab tags the file from it. Before that, software-drawn renders were tagged limited and decoded with shifted colours: `#30E2A8` came back as (41, 243, 179) instead of (48, 226, 168). Found by the CI runs; reproduced on the test laptop with SwiftShader, where the fixed render decodes as (49, 226, 169).
+- WebGL needs `--enable-unsafe-swiftshader` to fall back to software where there is no usable GPU: without it a Linux CI runner has no WebGL2, so scene transitions fail. motlab always passes it; with a GPU it changes nothing.
- The encoder config needs a sensible `framerate`. 240 is rejected.
- `shadowBlur` on a 2D canvas is expensive: 160 shadow blurs cap every pipeline at about 32 fps at 1080p.
- `willReadFrequently: true` makes the canvas CPU-backed and nearly halves WebCodecs speed. Do not use it on a render canvas.
diff --git a/src/chrome.js b/src/chrome.js
index a58e1d5..9ad8c50 100644
--- a/src/chrome.js
+++ b/src/chrome.js
@@ -19,7 +19,10 @@ export function findChrome(explicit) {
}
// --force_high_performance_gpu matters on dual-GPU laptops: without it headless Chrome draws on the integrated GPU.
-export const GPU_FLAGS = ['--enable-gpu', '--force_high_performance_gpu', ...(process.platform === 'darwin' ? ['--use-angle=metal'] : [])];
+// --enable-unsafe-swiftshader lets WebGL fall back to software on a machine without a usable GPU (a Linux CI runner
+// has no WebGL2 otherwise); with a GPU it changes nothing. It is "unsafe" for browsing untrusted sites, and motlab
+// only opens the user's own pages.
+export const GPU_FLAGS = ['--enable-gpu', '--force_high_performance_gpu', '--enable-unsafe-swiftshader', ...(process.platform === 'darwin' ? ['--use-angle=metal'] : [])];
const live = new Set();
process.on('exit', () => { for (const c of live) c.killSync(); });
diff --git a/src/cli.js b/src/cli.js
index cbb7a40..2590d69 100644
--- a/src/cli.js
+++ b/src/cli.js
@@ -40,7 +40,7 @@ const USAGE = `motlab: render a canvas page (canvas #c, renderAt(t), TOTAL, read
--root folder to serve (default: the nearest folder above the page with a project.json, else the page's folder)
--chrome path to Chrome (default: autodetect, or the CHROME environment variable)
-Chrome always runs with --enable-gpu --force_high_performance_gpu (--gpu is accepted and ignored, so older commands
+Chrome always runs with --enable-gpu --force_high_performance_gpu --enable-unsafe-swiftshader (--gpu is accepted and ignored, so older commands
that pass it keep working). Needs ffmpeg and ffprobe on PATH.
Engine folder: ${fileURLToPath(new URL('..', import.meta.url))} (README.md, example/, src/page/footage.js)`;
diff --git a/src/ffmpeg.js b/src/ffmpeg.js
index 427ac73..6dcbfff 100644
--- a/src/ffmpeg.js
+++ b/src/ffmpeg.js
@@ -13,11 +13,12 @@ export function run(cmd, args, signal) { // signal: an AbortSignal that kills
});
}
-// BT.709, limited range, written into the bitstream itself (VUI) so the tag survives any later remux.
-const VUI = 'colour_primaries=1:transfer_characteristics=1:matrix_coefficients=1:video_full_range_flag=0';
+// BT.709 with the range the encoder used (limited when Chrome drew on a GPU, full when it drew in software), written
+// into the bitstream itself (VUI) so the tag survives any later remux.
+const vui = full => `colour_primaries=1:transfer_characteristics=1:matrix_coefficients=1:video_full_range_flag=${full ? 1 : 0}`;
// inputs: MP4 segments (one or more) or one raw Annex B file. Output: a fast-start MP4, optionally with audio.
-export async function finalize({ inputs, raw, codec, fps, audio, out, duration, tmp, signal }) {
+export async function finalize({ inputs, raw, codec, fps, audio, out, duration, tmp, signal, fullRange = false }) {
const args = ['-y', '-loglevel', 'error'];
if (raw) args.push('-f', codec === 'hevc' ? 'hevc' : 'h264', '-framerate', String(fps), '-i', inputs[0]);
else if (inputs.length === 1) args.push('-i', inputs[0]);
@@ -28,8 +29,8 @@ export async function finalize({ inputs, raw, codec, fps, audio, out, duration,
}
if (audio) args.push('-i', audio, '-map', '0:v:0', '-map', '1:a:0', '-c:a', 'aac', '-b:a', '320k', '-t', duration.toFixed(6));
else args.push('-map', '0:v:0');
- args.push('-c:v', 'copy', '-bsf:v', `${codec === 'hevc' ? 'hevc' : 'h264'}_metadata=${VUI}`,
- '-color_primaries', 'bt709', '-color_trc', 'bt709', '-colorspace', 'bt709', '-color_range', 'tv',
+ args.push('-c:v', 'copy', '-bsf:v', `${codec === 'hevc' ? 'hevc' : 'h264'}_metadata=${vui(fullRange)}`,
+ '-color_primaries', 'bt709', '-color_trc', 'bt709', '-colorspace', 'bt709', '-color_range', fullRange ? 'pc' : 'tv',
...(codec === 'hevc' ? ['-tag:v', 'hvc1'] : []), '-movflags', '+faststart', '-f', 'mp4', out);
await run('ffmpeg', args, signal);
}
diff --git a/src/page/runtime.js b/src/page/runtime.js
index 3275d6b..e776466 100644
--- a/src/page/runtime.js
+++ b/src/page/runtime.js
@@ -6,6 +6,9 @@
if (window.__motlab) return;
const BT709 = { primaries: 'bt709', transfer: 'bt709', matrix: 'bt709', fullRange: false };
+ // Chrome turns the canvas into limited range YUV when it draws on a GPU, but into full range when it draws in
+ // software (SwiftShader, or a machine without a GPU), and the encoder's decoderConfig says which.
+ const fullRange = meta => meta?.decoderConfig?.colorSpace?.fullRange === true;
const emit = (type, data = {}) => { try { window.__motlabEmit(JSON.stringify({ type, ...data })); } catch {} };
const post = async (url, body) => { const r = await fetch(url, { method: 'POST', body }); if (!r.ok) throw new Error(`upload failed (${r.status})`); };
const sleep = ms => new Promise(r => setTimeout(r, ms));
@@ -68,10 +71,10 @@
output.addVideoTrack(source, { frameRate: o.fps });
await output.start();
return {
- // Encoders tag colour inconsistently (hardware H.264 not at all) although the pixels are BT.709 limited range,
- // so the container tag is set here for every encoder. ffmpeg later writes the same into the bitstream.
+ // Encoders tag colour inconsistently in the bitstream (hardware H.264 not at all), so the container tag is set
+ // here: BT.709 with the range the encoder reports. ffmpeg later writes the same into the bitstream.
add: (chunk, meta) => source.add(MB.EncodedPacket.fromEncodedChunk(chunk),
- meta && meta.decoderConfig ? { ...meta, decoderConfig: { ...meta.decoderConfig, colorSpace: BT709 } } : meta),
+ meta && meta.decoderConfig ? { ...meta, decoderConfig: { ...meta.decoderConfig, colorSpace: { ...BT709, fullRange: fullRange(meta) } } } : meta),
finish: () => output.finalize(),
};
}
@@ -83,10 +86,11 @@
if (!(await VideoEncoder.isConfigSupported(cfg)).supported) throw new Error(`encoder config not supported: ${cfg.codec} ${cfg.hardwareAcceleration} ${cv.width}x${cv.height}`);
const sink = await openSink(o);
- let chain = Promise.resolve(), queued = 0, failure = null, bytes = 0;
+ let chain = Promise.resolve(), queued = 0, failure = null, bytes = 0, full = false;
const enc = new VideoEncoder({
output(chunk, meta) {
bytes += chunk.byteLength; queued++;
+ if (meta?.decoderConfig) full = fullRange(meta);
chain = chain.then(() => failure || sink.add(chunk, meta)).then(() => { queued--; }, e => { failure ??= e; queued--; });
},
error(e) { failure ??= e; },
@@ -111,7 +115,7 @@
await chain;
if (failure) throw new Error(`encode failed: ${failure.message || failure}`);
await sink.finish();
- return { frames, bytes, ms: performance.now() - t0, renderMs };
+ return { frames, bytes, ms: performance.now() - t0, renderMs, fullRange: full };
}
// ---- encoder probe: how fast is one encoder config at this size, with drawing kept cheap? ----
diff --git a/src/project.js b/src/project.js
index 76047b6..5e8f275 100644
--- a/src/project.js
+++ b/src/project.js
@@ -82,7 +82,8 @@ export async function renderProject({ dir, out, scale, log = console.log, signal
// Written beside the output first and renamed when complete, so a stopped or failed render leaves no half file.
signal?.throwIfAborted();
mkdirSync(dirname(out), { recursive: true });
- await finalize({ inputs: parts.map(s => s.out), codec: parts[0].codec, fps: p.fps, audio, out: partial, duration, tmp, signal });
+ if (parts.some(s => s.fullRange !== parts[0].fullRange)) throw new Error('the scenes were encoded with different colour ranges');
+ await finalize({ inputs: parts.map(s => s.out), codec: parts[0].codec, fps: p.fps, audio, out: partial, duration, tmp, signal, fullRange: parts[0].fullRange });
rmSync(out, { force: true }); renameSync(partial, out);
log(`\nSAVED ${out} (${scenes.length} scenes${parts.length > scenes.length ? `, ${parts.length - scenes.length} transitions` : ''}, ${duration.toFixed(3)} s${audio ? `, ${p.audio.length} audio files` : ''})`);
} finally { rmSync(partial, { force: true }); rmSync(tmp, { recursive: true, force: true }); }
diff --git a/src/render.js b/src/render.js
index be0004b..2bc02af 100644
--- a/src/render.js
+++ b/src/render.js
@@ -116,8 +116,10 @@ export async function renderVideo(o) {
for (const p of inputs) await pipeline(createReadStream(p), w, { end: false });
await new Promise(r => w.end(r)); inputs = [all];
}
- await finalize({ inputs, raw: mux === 'raw', codec: enc.codec, fps, audio: o.audio && resolve(o.audio), out: part, duration: frames / fps, tmp, signal: o.signal });
- return { mux, encodeMs, stats };
+ const fullRange = stats[0].fullRange;
+ if (stats.some(s => s.fullRange !== fullRange)) throw new Error('the workers encoded different colour ranges');
+ await finalize({ inputs, raw: mux === 'raw', codec: enc.codec, fps, audio: o.audio && resolve(o.audio), out: part, duration: frames / fps, tmp, signal: o.signal, fullRange });
+ return { mux, encodeMs, stats, fullRange };
};
mkdirSync(dirname(out), { recursive: true });
@@ -134,7 +136,7 @@ export async function renderVideo(o) {
const v = await probeVideo(out), wantDur = frames / fps;
const muxLabel = `${res.mux === 'raw' ? 'raw bitstream' : 'Mediabunny in the page'}, then ffmpeg -c copy${ranges.length > 1 ? ` (concat of ${ranges.length} parts)` : ''}${o.audio ? ' with audio' : ''}`;
const summary = { out, frames: v.frames, expectedFrames: frames, pageFrames, duration: v.duration, width, height, fps, gpu: info.gpu.renderer, encoder: label(enc), codec: enc.codec, hw: enc.hw,
- rate: rate(enc), mux: muxLabel, workers: ranges.length, encodeSeconds: res.encodeMs / 1000, totalSeconds: (Date.now() - started) / 1000, size: v.size,
+ rate: rate(enc), mux: muxLabel, fullRange: res.fullRange, workers: ranges.length, encodeSeconds: res.encodeMs / 1000, totalSeconds: (Date.now() - started) / 1000, size: v.size,
color: { range: v.color_range, space: v.color_space, transfer: v.color_transfer, primaries: v.color_primaries } };
log(`Mux: ${muxLabel}`);
log(`Colour tags: ${v.color_space || 'none'} / ${v.color_range || 'none'} (primaries ${v.color_primaries || 'none'}, transfer ${v.color_transfer || 'none'})`);
diff --git a/test/install.test.js b/test/install.test.js
index f89e956..d52650b 100644
--- a/test/install.test.js
+++ b/test/install.test.js
@@ -34,11 +34,12 @@ test('motlab uninstall removes what the installer wrote and nothing else', () =>
put(join(home, '.claude', 'skills', 'motlab-assets', 'SKILL.md'));
put(join(home, '.claude', 'skills', 'someone-else', 'SKILL.md'));
put(join(home, '.motlab', 'install.json'), JSON.stringify({ skillDirs: [join(home, 'custom')], bin: join(home, 'bin') }));
- put(join(home, 'local', 'motlab', 'encoder-probe.json'), '{}');
+ const cache = process.platform === 'win32' ? join(home, 'local', 'motlab') : join(home, '.cache', 'motlab'); // where probe.js keeps it
+ put(join(cache, 'encoder-probe.json'), '{}');
const env = { ...process.env, HOME: home, USERPROFILE: home, LOCALAPPDATA: join(home, 'local'), MOTLAB_KEEP_VIEWER: '1', MOTLAB_CACHE_DIR: '' };
delete env.MOTLAB_CACHE_DIR;
const run = (...args) => spawnSync(process.execPath, ['bin/motlab.js', 'uninstall', ...args], { encoding: 'utf8', env, input: '' });
- const gone = [join(home, 'bin', 'motlab.cmd'), join(home, 'custom', 'motlab'), join(home, '.claude', 'skills', 'motlab-assets'), join(home, '.motlab'), join(home, 'local', 'motlab')];
+ const gone = [join(home, 'bin', 'motlab.cmd'), join(home, 'custom', 'motlab'), join(home, '.claude', 'skills', 'motlab-assets'), join(home, '.motlab'), cache];
const asked = run();
assert.equal(asked.status, 1, asked.stdout);
for (const f of gone) { assert.ok(asked.stdout.includes(f), `${f} is listed`); assert.ok(existsSync(f), `${f} is kept without --yes`); }
diff --git a/test/render.test.js b/test/render.test.js
index c542b00..f125eaa 100644
--- a/test/render.test.js
+++ b/test/render.test.js
@@ -30,7 +30,8 @@ async function checkVideo(name, opts, frames) {
assert.equal(v.frames, frames); assert.equal(Number(v.nb_frames), frames);
assert.ok(Math.abs(v.duration - frames / 30) < 1e-3, `duration ${v.duration}`);
assert.deepEqual([v.width, v.height], [640, 360]);
- assert.deepEqual([v.color_range, v.color_space, v.color_transfer, v.color_primaries], ['tv', 'bt709', 'bt709', 'bt709']);
+ // limited range when Chrome draws on a GPU, full range when it draws in software (CI runners have no GPU)
+ assert.deepEqual([v.color_range, v.color_space, v.color_transfer, v.color_primaries], [s.fullRange ? 'pc' : 'tv', 'bt709', 'bt709', 'bt709']);
const left = meanRgb(out, '200:200:60:80'), right = meanRgb(out, '100:60:340:20');
assert.ok(near(left, [0x30, 0xE2, 0xA8], 4), `left field decoded as ${left}`);
assert.ok(near(right, [0xF5, 0xD0, 0x4E], 4), `right field decoded as ${right}`);