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.

Footage: WebM and MKV frames no longer come a frame late (#3)

Stanyslaus Hary2a935f8da603
diff --git a/CHANGELOG.md b/CHANGELOG.md
index efc628f..b605c34 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,7 @@ Changes are listed by release, newest first. The sections dated before 0.1.0 rec
### Fixed
- Running motlab as root, as in a container or on a VPS logged in as root, failed at the first scene with "Chrome exited early (code 1): Running as root without --no-sandbox is not supported", because Chrome refuses to start as root and motlab passed no such flag. Chrome now gets `--no-sandbox` when motlab runs as root, and only then; motlab only opens the user's own pages. Checked on Ubuntu 24.04 as root, no GPU, Google Chrome 157: `motlab render example --scale 1` went from failing at once to a 9 s, 1080p render in 13.6 s (8.5 s on a repeat run, with the encoder probe cached), and `npm test` passed 34/34. Not tried: a non-root user in a container where Chrome's sandbox still fails.
+- Footage in WebM or MKV showed some frames one frame late: at 30 fps every third frame (2, 5, 8 and so on) was the one before. These containers store timestamps in whole milliseconds, so a frame due at 0.0667 s is stored at 0.067 s, and `clip.frame(t)` did not count it as shown yet. `footage.js` now rounds the time it is asked for to the millisecond for these two containers, and MP4 and MOV work as before. Checked on the Windows laptop with clips made by ffmpeg in which every frame is a different grey: VP9 in WebM and MP4, H.264 in MKV, MP4 and MOV, at 24, 25, 29.97, 30 and 60 fps, rendered at 30 fps and at the clip's own rate, 40 cases, every output frame the source frame due at that time (12 of the 40, all WebM or MKV, were wrong before). Stills in a jumbled order and stepping frame by frame in the viewer showed the right frames too. `test/render.test.js` renders a VP9 WebM and checks every frame. Not tried: footage filmed on a phone in these containers.
### Changed
diff --git a/docs/projects.md b/docs/projects.md
index f3d6f40..e5dbf31 100644
--- a/docs/projects.md
+++ b/docs/projects.md
@@ -115,6 +115,7 @@ Tested: a 60 fps clip trimmed from 1.5 s into a 30 fps scene renders the exact s
- A 20-minute 1280x720 recording (1.1 GB, a keyframe every second): stills at 0.5, 600.2, 1199.9, 30, 1100.1, 2 and 2.03 s, in that order, all showed the right frame, in 1.7 s for the whole command. Ten seconds from 19:40 rendered at 94 fps, every frame right.
- Variable frame rate (portrait 1080x1920, 30 fps with uneven gaps for 5 s, then 60 fps): 435 frames at 30 fps, every one the frame shown at that time.
- HEVC 8-bit (Main) and 10-bit (Main 10) at 1080p: 300 frames each, every one right, at 53 fps. Colour matched an H.264 source of the same picture.
+- VP9 in WebM and MP4, and H.264 in MKV, MP4 and MOV, at 24, 25, 29.97, 30 and 60 fps, rendered at 30 fps and at the clip's own rate: every frame right, in 64x64 test clips where each frame is a different grey. WebM and MKV store timestamps in whole milliseconds, so for them `clip.frame(t)` rounds `t` to the millisecond.
These were made with ffmpeg, not filmed on a phone, and played by a Chrome that could decode HEVC on this laptop. Chrome on a machine without HEVC decoding stops at `openFootage` with "this browser cannot decode".
diff --git a/skills/motlab/references/footage.md b/skills/motlab/references/footage.md
index 6bf8b50..5d44c9a 100644
--- a/skills/motlab/references/footage.md
+++ b/skills/motlab/references/footage.md
@@ -105,8 +105,8 @@ entries around the speech.
## Limits
-- Decoding uses WebCodecs, so the codec must be one Chrome decodes (H.264, HEVC, VP9, AV1, ProRes is not). Convert
- anything else first: `ffmpeg -i in.mov -c:v libx264 -crf 16 -c:a aac out.mp4`.
+- Decoding uses WebCodecs, so the codec must be one Chrome decodes: H.264, HEVC, VP9 or AV1, in MP4, MOV, WebM or MKV.
+ ProRes is not. Convert anything else first: `ffmpeg -i in.mov -c:v libx264 -crf 16 -c:a aac out.mp4`.
- The viewer decodes the whole audio of a video file to draw its waveform, so very long recordings load slowly there.
Trim long recordings to the parts you use before listing them.
- No alpha output yet, so the result is always a flat MP4.
diff --git a/src/page/footage.js b/src/page/footage.js
index 92475f2..5886e1b 100644
--- a/src/page/footage.js
+++ b/src/page/footage.js
@@ -17,6 +17,9 @@ export async function openFootage(path) {
if (!track) throw new Error(`${path} has no video track`);
if (!(await track.canDecode())) throw new Error(`${path}: this browser cannot decode ${track.codec}`);
const sink = new MB.VideoSampleSink(track), first = await track.getFirstTimestamp(), duration = await track.computeDuration() - first;
+ // WebM and MKV store timestamps in whole milliseconds, so a 30 fps frame due at 0.0667 s is stored at 0.067 s. The time
+ // asked for is rounded the same way; without it every third frame of a 30 fps WebM came a frame late.
+ const ms = (await input.getFormat()) instanceof MB.MatroskaInputFormat;
let it = null, cur = null, next = null;
const pull = async () => { const r = await it.next(); return r.done ? null : r.value; };
@@ -27,7 +30,8 @@ export async function openFootage(path) {
return {
width: track.displayWidth, height: track.displayHeight, duration,
async frame(t) {
- const at = first + Math.min(Math.max(0, t), Math.max(0, duration - 1e-6));
+ let at = first + Math.min(Math.max(0, t), Math.max(0, duration - 1e-6));
+ if (ms) at = Math.round(at * 1000) / 1000;
if (!cur || at < cur.timestamp || (next && at > next.timestamp + 1)) await seek(at);
while (next && next.timestamp <= at + 1e-6) { cur.close(); cur = next; next = await pull(); }
if (!cur) throw new Error(`${path}: no frame at ${t.toFixed(3)} s`);
diff --git a/test/render.test.js b/test/render.test.js
index 9f18952..906101d 100644
--- a/test/render.test.js
+++ b/test/render.test.js
@@ -76,6 +76,26 @@ test('a page without the contract fails with a clear message', async () => {
await assert.rejects(renderVideo({ page: fileURLToPath(new URL('../package.json', import.meta.url)), out: join(dir, 'x.mp4'), ...quiet }), /renderAt/);
});
+test('footage: a WebM clip shows the right frame at every time, though Matroska rounds timestamps to the millisecond', async () => {
+ const proj = join(dir, 'footage'), clip = join(proj, 'clip.webm');
+ mkdirSync(proj);
+ // VP9 at 30 fps, each frame a flat grey 6 levels lighter than the one before, so a frame tells which one it is
+ spawnSync('ffmpeg', ['-v', 'error', '-f', 'lavfi', '-i', 'nullsrc=s=64x64:r=30:d=1,geq=lum=16+N*6:cb=128:cr=128', '-c:v', 'libvpx-vp9', '-b:v', '2M', '-pix_fmt', 'yuv420p', clip]);
+ writeFileSync(join(proj, 'scene.html'), `<!doctype html><canvas id="c" width="64" height="64"></canvas><script>
+ const ctx = document.getElementById('c').getContext('2d'); let clip; window.TOTAL = 1;
+ window.ready = (async () => { clip = await (await import('/__motlab/footage.js')).openFootage('clip.webm'); return true; })();
+ window.renderAt = async t => { await window.ready; (await clip.frame(t)).draw(ctx, 0, 0, 64, 64); };</script>`);
+ const out = join(dir, 'footage.mp4');
+ await renderVideo({ page: join(proj, 'scene.html'), out, fps: 30, scale: 1, encoder: 'sw', ...quiet });
+ const grey = (file, f) => meanRgb(file, '32:32:16:16', f)[1];
+ const src = Array.from({ length: 30 }, (_, f) => grey(clip, f)), wrong = [];
+ for (let f = 0; f < 30; f++) {
+ const g = grey(out, f), shown = src.reduce((b, v, i) => Math.abs(v - g) < Math.abs(src[b] - g) ? i : b, 0);
+ if (shown !== f) wrong.push(`frame ${f} showed source frame ${shown}`);
+ }
+ assert.deepEqual(wrong, [], `source greys ${src}`);
+});
+
test('project: a transition overlaps two scenes and mixes them on the frame grid', async () => {
const proj = join(dir, 'proj'), flat = (name, colour) => writeFileSync(join(proj, name), `<!doctype html><canvas id="c" width="320" height="180"></canvas><script>
const c = document.getElementById('c').getContext('2d'); window.TOTAL = 1; window.ready = Promise.resolve(true);