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.

Exports: a video the browser can't decode is copied scaled down, or fails the export by its clip (#258)

riverisbuildingaa29fc82945e
diff --git a/.changeset/undecodable-video-fails.md b/.changeset/undecodable-video-fails.md
new file mode 100644
index 0000000..c28231d
--- /dev/null
+++ b/.changeset/undecodable-video-fails.md
@@ -0,0 +1,5 @@
+---
+"openfilm": patch
+---
+
+Exports no longer come out black where a video can't be played. A video larger than 4096 on a side that the export's browser does not decode (ProRes from a camera larger than 4K, say) gets a copy scaled down to fit, as smaller ones get a copy at their size. A copy that could not be made is said in the render's log, and a video the browser still can't decode now fails the export, naming its clip and file, instead of drawing black frames and saying it is done. Studio's preview is unchanged.
diff --git a/packages/openfilm/src/render.mjs b/packages/openfilm/src/render.mjs
index 5014980..ab6a711 100644
--- a/packages/openfilm/src/render.mjs
+++ b/packages/openfilm/src/render.mjs
@@ -160,6 +160,8 @@ export async function render(args, opts = {}) {
let format = chip ? { ...own, ...chip.format } : own;
let encoder = chip?.encoder ?? encoderOf(own.video);
const workers = Math.max(1, Math.min(pool ? lent.length : Number(opts.workers ?? defaultWorkers(machine(), total)), total));
+ /** @type {string[]} videos whose copy could not be made: drawn as they are, said as it happens and in the result */
+ const uncopied = [];
/* the videos get copies this browser plays: those it does not decode here (ProRes; HEVC without a chip for it), and
for a render of more than a moment those that seek slowly (seekable.mjs). A film's video clips load only when
their time comes, so they are read from film.html (a page drawn around the project's film, as a burned-in
@@ -167,8 +169,13 @@ export async function render(args, opts = {}) {
if (opts.seekable !== false) {
const film = isFilm ? entry : opts.root ? FILM_FILE : null;
const files = [...new Set([...videos, ...(film ? filmVideos(root, film) : [])])];
+ /* one the browser does not decode then fails its first frame, by its clip (timeline.mjs): never drawn black */
+ const failed = (/** @type {string} */ file) => {
+ uncopied.push(file);
+ console.error(`openfilm render: ${shown(file)}: a copy this browser plays could not be made, so it is drawn as it is`);
+ };
try {
- copies = await browserCopies(browser, site.url, root, files, { signal: opts.signal, slow: total >= fps * 2 });
+ copies = await browserCopies(browser, site.url, root, files, { signal: opts.signal, slow: total >= fps * 2, failed });
} catch (e) {
await probe.close();
await pool?.give(lent, { retire: true });
@@ -315,6 +322,7 @@ export async function render(args, opts = {}) {
lines: [
`→ ${shown(out)}`,
` ${total} frames · ${fmt(to - from)} at ${Number(fps.toFixed(3))} fps · ${Math.round(meta.width * scale)}×${Math.round(meta.height * scale)}${samples > 1 ? ` · ${samples} samples/frame` : ''}${alpha ? ' · alpha' : ''} · ${workers} worker${workers > 1 ? 's' : ''} · ${encoder} · ${seconds.toFixed(1)} s`,
+ ...uncopied.map((file) => `✗ copy: ${shown(file)}: could not be made, drawn as it is`),
...problems.map((p) => `✗ ${p.kind === 'request' ? 'request' : 'page'}: ${p.message}`),
],
};
diff --git a/packages/openfilm/src/seekable.mjs b/packages/openfilm/src/seekable.mjs
index 322ef19..9a6d49d 100644
--- a/packages/openfilm/src/seekable.mjs
+++ b/packages/openfilm/src/seekable.mjs
@@ -18,7 +18,8 @@ const SLOW_GOP_S = 0.5;
const COPY_GOP_S = 0.25;
/** A longer video is left as it is: copying it all could take longer than the render it would speed up. */
const MAX_SECONDS = 10 * 60;
-/** Bigger than this is left as it is (H.264 stops at 4096 on a side in most decoders). */
+/** Bigger than this is not copied at its size (H.264 stops at 4096 on a side in most decoders): left as it is when it
+ plays, else copied scaled down to fit. */
const MAX_SIDE = 4096;
/** Changing how copies are made makes new ones. */
const VERSION = 2;
@@ -71,9 +72,9 @@ const decodedAnywhere = (/** @type {{ codec_name?: string, pix_fmt?: string }} *
* What a render needs of a video: a copy because its browser does not decode it here (`unplayable`: ProRes in any
* browser, HEVC without a chip for it, 10-bit H.264…, asked of the browser itself with `plays`; `alpha` when its
* picture has one to keep), or because it seeks slowly (`slow`, slowSeeking, only when `slow` is asked for); null for
- * neither.
+ * neither. `w` and `h` are the copy's size: `scaled` when that is smaller than the video's.
* @param {string} file @param {{ plays?: (file: string) => Promise<boolean>, slow?: boolean }} [options]
- * @returns {Promise<{ why: 'unplayable' | 'slow', fps: number, w: number, h: number, alpha: boolean } | null>}
+ * @returns {Promise<{ why: 'unplayable' | 'slow', fps: number, w: number, h: number, alpha: boolean, scaled?: true } | null>}
*/
export async function copyNeed(file, { plays, slow = true } = {}) {
let info;
@@ -81,12 +82,20 @@ export async function copyNeed(file, { plays, slow = true } = {}) {
info = JSON.parse(await probe(file, ['-select_streams', 'v:0', '-show_entries', 'stream=codec_name,width,height,pix_fmt,avg_frame_rate:stream_tags=alpha_mode', '-of', 'json']));
} catch { return null; }
const stream = info.streams?.[0];
- if (!stream || stream.width > MAX_SIDE || stream.height > MAX_SIDE) return null;
+ if (!stream) return null;
+ const w = Number(stream.width), h = Number(stream.height);
if (plays && !decodedAnywhere(stream) && !(await plays(file))) {
const [n, d] = String(stream.avg_frame_rate).split('/').map(Number);
const alpha = /^(yuva|rgba|bgra|argb|abgr|gbrap|ya)/.test(String(stream.pix_fmt)) || stream.tags?.alpha_mode === '1';
- return { why: 'unplayable', fps: n > 0 && d > 0 ? n / d : 30, w: Number(stream.width), h: Number(stream.height), alpha };
+ const need = { why: /** @type {const} */ ('unplayable'), fps: n > 0 && d > 0 ? n / d : 30, w, h, alpha };
+ /* too big to copy at its size: scaled down to fit, its sides even. The film draws a video scaled to its clip's box,
+ which the original's size sets, so it is placed the same; left out, it would draw nothing at all */
+ const fit = MAX_SIDE / Math.max(w, h);
+ if (fit >= 1) return need;
+ const even = (/** @type {number} */ side) => Math.max(2, Math.round((side * fit) / 2) * 2);
+ return { ...need, w: even(w), h: even(h), scaled: /** @type {const} */ (true) };
}
+ if (w > MAX_SIDE || h > MAX_SIDE) return null;
const slowly = slow ? await slowSeeking(file) : null;
return slowly ? { why: 'slow', fps: slowly.fps, w: slowly.w, h: slowly.h, alpha: false } : null;
}
@@ -151,11 +160,12 @@ const firstFrame = (url) => new Promise((done) => {
/**
* The copies `browser` needs of `files` to show them (seekableCopies, kept in `root`'s cache), each file asked of the
* browser itself through a page that loads it from the site at `origin`, which serves `root`. `slow`: slow-seeking
- * ones too. A map from a file to its copy; it never fails: a video that can't be copied stays as it is.
+ * ones too. A map from a file to its copy; it never fails: a video that can't be copied stays as it is, and is told
+ * to `failed`.
* @param {import('playwright-core').Browser} browser @param {string} origin @param {string} root @param {string[]} files
- * @param {{ signal?: AbortSignal, slow?: boolean }} [options]
+ * @param {{ signal?: AbortSignal, slow?: boolean, failed?: (file: string) => void }} [options]
*/
-export async function browserCopies(browser, origin, root, files, { signal, slow = false } = {}) {
+export async function browserCopies(browser, origin, root, files, { signal, slow = false, failed } = {}) {
if (!files.length) return new Map();
/** @type {Promise<import('playwright-core').Page> | null} */
let tester = null;
@@ -165,7 +175,7 @@ export async function browserCopies(browser, origin, root, files, { signal, slow
return (await tester).evaluate(firstFrame, url).catch(() => false);
};
try {
- return await seekableCopies(files, root, { signal, plays, slow });
+ return await seekableCopies(files, root, { signal, plays, slow, failed });
} catch {
return new Map();
} finally {
@@ -175,12 +185,13 @@ export async function browserCopies(browser, origin, root, files, { signal, slow
/**
* The copy of each of `files` that needs one (copyNeed), made in `root`'s cache (or found there from before): a map
- * from a file to its copy. A file that is fine as it is, or whose copy fails, is not in it. `plays`: whether the
- * render's browser decodes a file; `slow`: whether slow-seeking ones get a copy too (a render of more than a moment).
+ * from a file to its copy. A file that is fine as it is, or whose copy fails, is not in it; one whose copy fails is
+ * told to `failed`. `plays`: whether the render's browser decodes a file; `slow`: whether slow-seeking ones get a copy
+ * too (a render of more than a moment).
* @param {string[]} files @param {string} root
- * @param {{ signal?: AbortSignal, plays?: (file: string) => Promise<boolean>, slow?: boolean }} [options]
+ * @param {{ signal?: AbortSignal, plays?: (file: string) => Promise<boolean>, slow?: boolean, failed?: (file: string) => void }} [options]
*/
-export async function seekableCopies(files, root, { signal, plays, slow = true } = {}) {
+export async function seekableCopies(files, root, { signal, plays, slow = true, failed } = {}) {
const copies = new Map();
outDir(root, 'seek');
/* two at a time: on the processor each one keeps several cores busy; on the graphics chip it leaves them free */
@@ -212,6 +223,7 @@ export async function seekableCopies(files, root, { signal, plays, slow = true }
let result = await shared();
if (result === 'cancelled' && !signal?.aborted) result = await shared();
if (result === 'made') known(out);
+ else if (result === 'failed') failed?.(file);
}
};
await Promise.all([worker(), worker()]);
@@ -225,7 +237,7 @@ const making = new Map();
* `file`'s copy written to `out`, under a name of its own until it is whole: another process making the same copy
* never writes the same file, and the one renamed last is kept (the same picture). One that cannot replace a copy
* already there (Windows, while a browser reads it) uses that copy.
- * @param {string} file @param {string} out @param {{ fps: number, w: number, h: number, alpha: boolean }} need @param {AbortSignal} [signal]
+ * @param {string} file @param {string} out @param {{ fps: number, w: number, h: number, alpha: boolean, scaled?: true }} need @param {AbortSignal} [signal]
* @returns {Promise<'made' | 'failed' | 'cancelled'>}
*/
async function makeCopy(file, out, need, signal) {
@@ -239,6 +251,7 @@ async function makeCopy(file, out, need, signal) {
const make = async (/** @type {string | null} */ encoder, /** @type {string[]} */ decoding) => {
/* the same frames at the same times (passthrough: no frame is added or dropped), the picture only */
const run = ffmpeg([...decoding, '-i', file, '-map', '0:v:0', '-an', '-sn', '-dn', '-fps_mode', 'passthrough',
+ ...(need.scaled ? ['-vf', `scale=${need.w}:${need.h}`] : []),
...(need.alpha ? ['-c:v', 'libvpx-vp9', '-pix_fmt', 'yuva420p', '-b:v', '0', '-crf', '18', '-row-mt', '1', '-deadline', 'realtime', '-cpu-used', '8',
'-g', String(gop), '-keyint_min', String(gop), '-auto-alt-ref', '0']
: encoder ? ['-pix_fmt', 'nv12', ...hardwareOptions(encoder, bits, { gop }), ...h264ColorTags(await colorTagsOf(file))]
diff --git a/packages/openfilm/src/seekable.test.mjs b/packages/openfilm/src/seekable.test.mjs
index 6461740..5a8121d 100644
--- a/packages/openfilm/src/seekable.test.mjs
+++ b/packages/openfilm/src/seekable.test.mjs
@@ -1,7 +1,7 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { execFile, execFileSync } from 'node:child_process';
-import { existsSync, mkdtempSync, readdirSync, rmSync, writeFileSync } from 'node:fs';
+import { chmodSync, existsSync, mkdirSync, mkdtempSync, readdirSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { filmHtml } from './film-doc.mjs';
@@ -94,6 +94,48 @@ test('a render shows ProRes footage, which no browser decodes, through its copy'
}
});
+test('footage too big for H.264 that the browser does not decode gets a copy scaled down to fit, and a render shows it', ffmpeg, async () => {
+ const dir = mkdtempSync(join(tmpdir(), 'of-seekable-big-'));
+ try {
+ execFileSync('ffmpeg', ['-v', 'error', '-y', '-f', 'lavfi', '-i', 'color=c=0x2060c0:size=4400x2400:rate=10', '-t', '1', '-c:v', 'prores_ks', '-profile:v', '0', join(dir, 'a.mov')]);
+ assert.deepEqual(await copyNeed(join(dir, 'a.mov'), { plays: async () => false }), { why: 'unplayable', fps: 10, w: 4096, h: 2234, alpha: false, scaled: true });
+ writeFileSync(join(dir, 'film.html'), filmHtml({ stage: { w: 320, h: 180 }, tracks: [{ clips: [{ id: 'v', src: 'a.mov', at: 0, time: [0, 1] }] }] }));
+ const done = await render([dir, '0-0.5'], { out: join(dir, 'out.mp4'), workers: 1, silent: true, onProgress() {} });
+ const copy = readdirSync(join(dir, '.film/cache/seek')).filter((f) => f.endsWith('.mp4'));
+ assert.equal(copy.length, 1);
+ const size = execFileSync('ffprobe', ['-v', 'error', '-select_streams', 'v:0', '-show_entries', 'stream=width,height', '-of', 'csv=p=0', join(dir, '.film/cache/seek', copy[0])]).toString().trim();
+ assert.equal(size, '4096,2234');
+ const [r, g, b] = execFileSync('ffmpeg', ['-v', 'error', '-ss', '0.2', '-i', done.out, '-frames:v', '1', '-vf', 'crop=4:4:160:90,format=rgb24', '-f', 'rawvideo', '-']);
+ assert.ok(Math.abs(r - 0x20) < 16 && Math.abs(g - 0x60) < 16 && Math.abs(b - 0xc0) < 16, `the footage's colour: ${r},${g},${b}`);
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+});
+
+test('a copy that could not be made is said, and footage the browser does not decode then fails the render by its clip', {
+ ...ffmpeg, skip: ffmpeg.skip || ((process.platform === 'win32' || process.getuid?.() === 0) && 'a folder it can\'t write to'),
+}, async () => {
+ const dir = mkdtempSync(join(tmpdir(), 'of-seekable-uncopied-'));
+ const seek = join(dir, '.film', 'cache', 'seek');
+ const error = console.error;
+ try {
+ execFileSync('ffmpeg', ['-v', 'error', '-y', '-f', 'lavfi', '-i', 'color=c=0x2060c0:size=320x180:rate=30', '-t', '1', '-c:v', 'prores_ks', '-profile:v', '3', join(dir, 'a.mov')]);
+ writeFileSync(join(dir, 'film.html'), filmHtml({ stage: { w: 320, h: 180 }, tracks: [{ clips: [{ id: 'v', src: 'a.mov', at: 0, time: [0, 1] }] }] }));
+ /* the copy can't be written */
+ mkdirSync(seek, { recursive: true });
+ chmodSync(seek, 0o555);
+ const said = [];
+ console.error = (...args) => { said.push(args.join(' ')); };
+ await assert.rejects(render([dir, '0-0.5'], { out: join(dir, 'out.mp4'), workers: 1, silent: true, onProgress() {} }),
+ /clip "v" \(a\.mov\): this browser can't play its video/);
+ assert.ok(said.some((line) => line.includes('a.mov') && line.includes('could not be made')), said.join('\n'));
+ } finally {
+ console.error = error;
+ chmodSync(seek, 0o755);
+ rmSync(dir, { recursive: true, force: true });
+ }
+});
+
test('a copy once made is found for each request after it, and none before', ffmpeg, async () => {
const dir = mkdtempSync(join(tmpdir(), 'of-seekable-made-'));
try {
diff --git a/packages/openfilm/src/timeline.mjs b/packages/openfilm/src/timeline.mjs
index 150026d..102748a 100644
--- a/packages/openfilm/src/timeline.mjs
+++ b/packages/openfilm/src/timeline.mjs
@@ -757,13 +757,18 @@ function frameOf(c) {
return frameLengths.get(src.pathname);
}
-/** Wait for a video's file for an exact frame: too long is the film's error, said by the clip. */
-function loaded(c) {
+/**
+ * Wait for a video's file for an exact frame: too long, or a file this browser does not decode (one a render could
+ * not copy, see seekable.mjs), is the film's error, said by the clip. Drawn, it would show nothing: a black frame.
+ */
+async function loaded(c) {
let timer;
const late = new Promise((_, fail) => {
timer = setTimeout(() => fail(new Error(`clip "${c.id}" (${c.src}): its video did not load within ${LOAD_MS / 1000} s`)), LOAD_MS);
});
- return Promise.race([wake(c), late]).finally(() => clearTimeout(timer));
+ await Promise.race([wake(c), late]).finally(() => clearTimeout(timer));
+ const error = c.el.error;
+ if (error) throw new Error(`clip "${c.id}" (${c.src}): this browser can't play its video${error.message ? ` (${error.message})` : ''}`);
}
/**
diff --git a/packages/openfilm/src/timeline.test.mjs b/packages/openfilm/src/timeline.test.mjs
index 9263c4f..390e81b 100644
--- a/packages/openfilm/src/timeline.test.mjs
+++ b/packages/openfilm/src/timeline.test.mjs
@@ -5,7 +5,7 @@ import { cpSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
import { createServer } from 'node:http';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
-import { FilmPage, launch, serve, VideoNotShown } from './host.mjs';
+import { FilmPage, FrameError, launch, serve, VideoNotShown } from './host.mjs';
import { open } from './shared.mjs';
import { filmHead, filmHtml } from './film-doc.mjs';
@@ -224,6 +224,20 @@ test('a missing file stops a film, said by its name; an editor\'s preview (film-
}
});
+test('a video the browser can\'t decode fails an exact frame, said by its clip and file; watched, the film draws on', { timeout: 60_000 }, async () => {
+ const dir = mkdtempSync(join(tmpdir(), 'of-undecodable-'));
+ writeFileSync(join(dir, 'bad.mp4'), Buffer.alloc(20_000, 'not a video '));
+ writeFileSync(join(dir, 'film.html'), filmHtml({ stage: { w: 320, h: 180 }, tracks: [{ clips: [{ id: 'v', src: 'bad.mp4', time: [0, 2] }] }] }));
+ const s = await open(dir);
+ try {
+ await assert.rejects(s.film.seek(0.5), (e) => e instanceof FrameError && /^clip "v" \(bad\.mp4\): this browser can't play its video/.test(e.message));
+ await s.film.page.evaluate(() => window.__filmEditor.watch(1));
+ } finally {
+ await s.close();
+ rmSync(dir, { recursive: true, force: true });
+ }
+});
+
test('an editor\'s preview is up without opening a page whose time is its length: it opens at its moment, its own length and size told then', { timeout: 60_000 }, async () => {
const dir = mkdtempSync(join(tmpdir(), 'of-unread-'));
writeFileSync(join(dir, 'a.html'), page('a', 2));