Skip to content

The open source AI video agent: turns any coding agent into a video agent, with an editor to change anything it makes.

Look: contact sheets of large high-bit-depth footage (#108)

taavie-z71922644da5d
diff --git a/.changeset/look-media-thumbnails.md b/.changeset/look-media-thumbnails.md
new file mode 100644
index 0000000..f7c3e94
--- /dev/null
+++ b/.changeset/look-media-thumbnails.md
@@ -0,0 +1,5 @@
+---
+"openfilm": patch
+---
+
+Resize media contact-sheet thumbnails before embedding them, preventing "Invalid string length" on high-resolution, high-bit-depth clips. Single-frame output keeps its original resolution. A transparent WebM (VP9 or VP8) keeps its alpha in the sheet and in a single frame.
diff --git a/packages/openfilm/src/look.mjs b/packages/openfilm/src/look.mjs
index 5f555a1..acbec86 100644
--- a/packages/openfilm/src/look.mjs
+++ b/packages/openfilm/src/look.mjs
@@ -7,6 +7,14 @@ import { FrameError, launch, SOFTWARE_GL } from './host.mjs';
import { blockDiff, checkSound, cutText, fileOf, ffmpeg, filmSound, fmt, hash, homeFor, mix, open, outDir, parseTarget, SAME_LIMIT, shown, shuffled, spread, UsageError } from './shared.mjs';
const MEDIA = /\.(mp4|mov|m4v|webm|mkv|avi|png|jpe?g|webp|gif|mp3|wav|m4a|aac|ogg|flac)$/i;
+const CELL_WIDTH = 480;
+/* VP9's and VP8's alpha is a side channel ffmpeg's own decoders drop: libvpx reads it, when this ffmpeg has it */
+const LIBVPX = { vp9: 'libvpx-vp9', vp8: 'libvpx' };
+let decoders;
+const hasDecoder = (name) => {
+ decoders ??= spawnSync('ffmpeg', ['-hide_banner', '-decoders'], { encoding: 'utf8', windowsHide: true }).stdout ?? '';
+ return new RegExp(`^\\s*\\S+\\s+${name}\\s`, 'm').test(decoders);
+};
export async function look(args, opts = {}) {
const { film: target, at, range } = parseTarget(args);
@@ -269,7 +277,7 @@ async function waveform(s, from, to) {
async function sheet(browser, shots, meta, from, to, wave, marks, label = 'sound mix') {
const cols = shots.length <= 4 ? shots.length : shots.length <= 9 ? 3 : 4;
- const cellW = 480;
+ const cellW = CELL_WIDTH;
const cellH = Math.round((cellW * meta.height) / meta.width);
/* a sound on its own has no frames: the sheet keeps the width of four, the waveform fills it */
const W = (cols || 4) * (cellW + 6) - 6;
@@ -312,7 +320,7 @@ async function lookMedia(target, at, range, opts) {
const file = resolve(target);
if (!existsSync(file) || !statSync(file).isFile()) throw new UsageError(`${target}: no such file`);
const dir = outDir(homeFor(dirname(file)), 'look');
- const probe = spawnSync('ffprobe', ['-v', 'error', '-show_entries', 'format=duration:stream=codec_type,width,height,avg_frame_rate,r_frame_rate', '-of', 'json', file], { encoding: 'utf8', windowsHide: true });
+ const probe = spawnSync('ffprobe', ['-v', 'error', '-show_entries', 'format=duration:stream=codec_type,codec_name,width,height,avg_frame_rate,r_frame_rate:stream_tags=alpha_mode', '-of', 'json', file], { encoding: 'utf8', windowsHide: true });
let info;
try { info = JSON.parse(probe.stdout); } catch { return { ok: false, lines: [`✗ ${target}: ffprobe cannot read it`], files: [] }; }
const video = (info.streams ?? []).find((x) => x.codec_type === 'video');
@@ -325,9 +333,13 @@ async function lookMedia(target, at, range, opts) {
const fps = video ? rate(video.avg_frame_rate) ?? rate(video.r_frame_rate) : null;
const name = basename(file, extname(file));
const head = `${basename(file)} ${video ? `${w}×${h}` : 'sound only'}${dur ? ` · ${fmt(dur)}` : ''}${fps && !still ? ` · ${Number(fps.toFixed(3))} fps` : ''}${audio ? ' · with sound' : ''}`;
- const grab = (t) => {
+ const libvpx = video?.tags?.alpha_mode === '1' && LIBVPX[video.codec_name];
+ const decode = libvpx && hasDecoder(libvpx) ? ['-c:v', libvpx] : [];
+ const grab = (t, thumbnail = false) => {
const out = join(dir, `.${name}-${fmt(t)}.png`);
- const r = spawnSync('ffmpeg', ['-v', 'error', '-y', ...(still ? [] : ['-ss', String(t)]), '-i', file, '-frames:v', '1', out], { windowsHide: true });
+ // Resize before base64 embedding: full-size high-bit-depth PNGs can exceed Node's string limit together. 8 bits, alpha kept.
+ const r = spawnSync('ffmpeg', ['-v', 'error', '-y', ...(still ? [] : ['-ss', String(t)]), ...decode, '-i', file,
+ ...(thumbnail ? ['-vf', `scale=${CELL_WIDTH}:-1,format=rgb24|rgba`] : []), '-frames:v', '1', out], { windowsHide: true });
if (r.status !== 0) throw new Error(`ffmpeg could not take a frame at ${fmt(t)}`);
const png = readFileSync(out); rmSync(out, { force: true }); return png;
};
@@ -349,7 +361,7 @@ async function lookMedia(target, at, range, opts) {
}
const browser = await launch(opts.launch);
try {
- const shots = times.map((t) => ({ t, png: grab(t) }));
+ const shots = times.map((t) => ({ t, png: grab(t, true) }));
const out = join(dir, `${name}-${Number(from.toFixed(3))}-${fmt(to)}.png`);
writeFileSync(out, await sheet(browser, shots, { width: w || 1920, height: h || 1080 }, from, to, wave, [], 'its sound'));
files.push(out);
diff --git a/packages/openfilm/src/look.test.mjs b/packages/openfilm/src/look.test.mjs
index c7088ab..0848b51 100644
--- a/packages/openfilm/src/look.test.mjs
+++ b/packages/openfilm/src/look.test.mjs
@@ -3,6 +3,82 @@ import assert from 'node:assert/strict';
import { fileURLToPath } from 'node:url';
import { look } from './look.mjs';
import { filmHtml } from './film-doc.mjs';
+import { chromium } from 'playwright-core';
+import { spawnSync } from 'node:child_process';
+import { mkdtempSync, readFileSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+
+/** The PNGs a media sheet embeds, as { width, height, depth, alpha }: look's browser is watched as it is given its page. */
+function sheetCells(t) {
+ const cells = [];
+ const launch = chromium.launch.bind(chromium);
+ t.mock.method(chromium, 'launch', async (opts) => {
+ const browser = await launch(opts);
+ const newPage = browser.newPage.bind(browser);
+ t.mock.method(browser, 'newPage', async (opts) => {
+ const page = await newPage(opts);
+ const setContent = page.setContent.bind(page);
+ t.mock.method(page, 'setContent', async (html, opts) => {
+ for (const [, data] of html.matchAll(/src="data:image\/png;base64,([^"]+)"/g)) {
+ const png = Buffer.from(data, 'base64');
+ cells.push({ width: png.readUInt32BE(16), height: png.readUInt32BE(20), depth: png[24], alpha: png[25] === 6 });
+ }
+ return setContent(html, opts);
+ });
+ return page;
+ });
+ return browser;
+ });
+ return cells;
+}
+
+const encode = (file, input, ...out) => {
+ const r = spawnSync('ffmpeg', ['-v', 'error', '-y', '-f', 'lavfi', '-i', input, ...out, file]);
+ assert.equal(r.status, 0, String(r.stderr));
+ return file;
+};
+
+test('high-bit-depth media sheets embed thumbnails; single frames keep their full resolution', { timeout: 60_000 }, async (t) => {
+ const dir = mkdtempSync(join(tmpdir(), 'of-look-media-'));
+ t.after(() => rmSync(dir, { recursive: true, force: true }));
+ const file = encode(join(dir, 'camera.mkv'), 'testsrc2=s=640x480:r=12:d=1', '-pix_fmt', 'yuv420p10le', '-c:v', 'ffv1');
+ const cells = sheetCells(t);
+ for (const opts of [{ count: 4 }, {}]) {
+ const r = await look([file], opts);
+ assert.equal(r.ok, true);
+ assert.ok(readFileSync(r.files[0]).length > 0);
+ }
+ assert.equal(cells.length, 16);
+ for (const cell of cells) assert.deepEqual(cell, { width: 480, height: 360, depth: 8, alpha: false });
+ const single = await look([file, '0']);
+ const png = readFileSync(single.files[0]);
+ assert.equal(png.readUInt32BE(16), 640);
+ assert.equal(png.readUInt32BE(20), 480);
+ assert.equal(png[24], 16);
+});
+
+test('a transparent clip keeps its alpha in a media sheet, so its cells show the checkerboard behind it', { timeout: 60_000 }, async (t) => {
+ const dir = mkdtempSync(join(tmpdir(), 'of-look-alpha-'));
+ t.after(() => rmSync(dir, { recursive: true, force: true }));
+ const file = encode(join(dir, 'layer.mov'), '[email protected]:s=64x64:r=12:d=1,format=rgba', '-c:v', 'prores_ks', '-profile:v', '4444');
+ const cells = sheetCells(t);
+ assert.equal((await look([file], { count: 4 })).ok, true);
+ assert.equal(cells.length, 4);
+ for (const cell of cells) assert.deepEqual(cell, { width: 480, height: 480, depth: 8, alpha: true });
+});
+
+const vp9 = /^\s*\S+\s+libvpx-vp9\s/m.test(spawnSync('ffmpeg', ['-hide_banner', '-encoders'], { encoding: 'utf8' }).stdout ?? '');
+
+test('a transparent WebM keeps its alpha in a media sheet', { timeout: 60_000, skip: !vp9 && 'this ffmpeg has no libvpx-vp9' }, async (t) => {
+ const dir = mkdtempSync(join(tmpdir(), 'of-look-webm-'));
+ t.after(() => rmSync(dir, { recursive: true, force: true }));
+ const file = encode(join(dir, 'layer.webm'), '[email protected]:s=64x64:r=12:d=1,format=yuva420p', '-c:v', 'libvpx-vp9', '-auto-alt-ref', '0');
+ const cells = sheetCells(t);
+ assert.equal((await look([file], { count: 4 })).ok, true);
+ assert.equal(cells.length, 4);
+ for (const cell of cells) assert.deepEqual(cell, { width: 480, height: 480, depth: 8, alpha: true });
+});
/* the pages under test/: each one a mistake an agent makes (or one that only looks like one), and what look says */
const page = (name) => fileURLToPath(new URL(`../test/${name}`, import.meta.url));