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.

Export: footage that seeks fast, a browser per page, the graphics chip's encoders (#15)

riverisbuilding12d34cdb89e1
diff --git a/.changeset/export-hardware.md b/.changeset/export-hardware.md
new file mode 100644
index 0000000..ee13f8a
--- /dev/null
+++ b/.changeset/export-hardware.md
@@ -0,0 +1,5 @@
+---
+"openfilm": patch
+---
+
+Faster exports that use more of the computer. A video whose key frames are far apart (most camera, phone and stock footage) gets a copy that seeks fast before a render, kept in the project's cache; the pages draw from the copy and the sound still comes from the original. A film with footage renders about three times as fast. Each of a render's pages gets a browser of its own, and a render uses a browser for every two threads with 3 GB of memory each, up to eight (it was up to four, sharing one browser). H.264 and HEVC below master go through the graphics chip's encoder when it has one that works: the Mac's for HEVC too, and on Windows NVIDIA's, Intel's, AMD's or Windows' own. Each one is tried on a moment of video first, and an export it fails partway is made again without it.
diff --git a/packages/openfilm/src/host.mjs b/packages/openfilm/src/host.mjs
index 2486afa..a31a9c3 100644
--- a/packages/openfilm/src/host.mjs
+++ b/packages/openfilm/src/host.mjs
@@ -56,9 +56,10 @@ const TYPES = {
* `headers` go on every response (a host adds its own policy); the film (film.html) is played by the built-in
* timeline, and gets `timelineInject` instead of `inject` (a host that drives it, like Studio, adds its bridge there). Returns false when the path is not inside
* `root`, or leads out of it through a link.
- * @param {string} root @param {{ inject?: string, timelineInject?: string, headers?: Record<string, string> }} [options]
+ * `swap(file)` may name another file to serve in a file's place (a render's fast-seeking copy of a video, seekable.mjs).
+ * @param {string} root @param {{ inject?: string, timelineInject?: string, headers?: Record<string, string>, swap?: (file: string) => string | null }} [options]
*/
-export function folderFiles(root, { inject = `<script>${HOST_FLAG}</script>`, timelineInject = inject, headers: extraHeaders = {} } = {}) {
+export function folderFiles(root, { inject = `<script>${HOST_FLAG}</script>`, timelineInject = inject, headers: extraHeaders = {}, swap } = {}) {
root = resolve(root);
return (req, res, path, query) => {
/* beside any film, wherever in the folder it is (its page asks for them relative to itself) */
@@ -76,14 +77,16 @@ export function folderFiles(root, { inject = `<script>${HOST_FLAG}</script>`, ti
/* an address speaks in `/`: a `\` in it (escaped as %5C) would be a separator on Windows, past every check */
if (rel.includes('\\') || rel.includes('\0')) { res.writeHead(400, extraHeaders).end('bad address'); return true; }
if (rel.endsWith('/')) rel += 'index.html';
- const file = normalize(join(root, rel));
- if (file !== root && !file.startsWith(root + sep)) return false;
- let stat;
- try { stat = statSync(file); } catch { res.writeHead(404, extraHeaders).end('not found'); return true; }
+ const asked = normalize(join(root, rel));
+ if (asked !== root && !asked.startsWith(root + sep)) return false;
+ try { statSync(asked); } catch { res.writeHead(404, extraHeaders).end('not found'); return true; }
// a link out of the folder is not followed: a film from elsewhere can bring one to any of the person's files
let inRoot = false;
- try { inRoot = within(realpathSync(root), realpathSync(file)); } catch { /* gone meanwhile */ }
+ try { inRoot = within(realpathSync(root), realpathSync(asked)); } catch { /* gone meanwhile */ }
if (!inRoot) return false;
+ const file = swap?.(asked) ?? asked;
+ let stat;
+ try { stat = statSync(file); } catch { res.writeHead(404, extraHeaders).end('not found'); return true; }
if (stat.isDirectory()) { res.writeHead(302, { ...extraHeaders, location: `${path}/` }).end(); return true; }
const type = TYPES[extname(file).toLowerCase()] ?? 'application/octet-stream';
const headers = { ...extraHeaders, 'content-type': type, 'cache-control': 'no-store', 'accept-ranges': 'bytes' };
@@ -119,8 +122,8 @@ const within = (folder, path) => path === folder || path.startsWith(folder.endsW
* Serve `root`. HTML gets the host flag injected before any page script;
* ?film-host=0 serves the page untouched, as a visitor would see it.
*/
-export function serve(root, { port = 0 } = {}) {
- const files = folderFiles(root);
+export function serve(root, { port = 0, swap } = {}) {
+ const files = folderFiles(root, { swap });
const server = createServer((req, res) => {
const url = new URL(req.url, 'http://x');
if (!files(req, res, url.pathname, url.searchParams)) res.writeHead(403).end();
diff --git a/packages/openfilm/src/render.mjs b/packages/openfilm/src/render.mjs
index c3ebb82..81b4fe9 100644
--- a/packages/openfilm/src/render.mjs
+++ b/packages/openfilm/src/render.mjs
@@ -1,10 +1,12 @@
// film render: the deliverable. Frames are rendered in parallel page instances, averaged
// over the shutter for motion blur, encoded with tagged BT.709 color, and muxed with the mix of the film's sounds.
-import { mkdirSync, rmSync, writeFileSync } from 'node:fs';
+import { mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { availableParallelism, totalmem } from 'node:os';
import { basename, dirname, extname, join, resolve } from 'node:path';
-import { FilmPage } from './host.mjs';
-import { ffmpeg, filmSound, fmt, kill, mix, open, outDir, parseTarget, shown, UsageError, write } from './shared.mjs';
+import { clipKind, kindOf, readFilmFile } from './film-doc.mjs';
+import { FilmPage, launch } from './host.mjs';
+import { seekableCopies } from './seekable.mjs';
+import { ffmpeg, fileOf, filmSound, fmt, kill, mix, open, outDir, parseTarget, shown, UsageError, write } from './shared.mjs';
const BT709 = ['-colorspace', 'bt709', '-color_primaries', 'bt709', '-color_trc', 'bt709', '-color_range', 'tv'];
const TAG_709 = ['-bsf:v', 'h264_metadata=colour_primaries=1:transfer_characteristics=1:matrix_coefficients=1:video_full_range_flag=0'];
@@ -20,9 +22,17 @@ export async function render(args, opts = {}) {
const started = Date.now();
const { film: target, at, range } = parseTarget(args);
if (at != null) throw new UsageError(`render takes a range (for example ${at}-${at + 2}), not one time; for one frame use openfilm look ${at}`);
- /* `root`: the folder to serve (a host rendering an edit kept elsewhere in a project serves the project) */
- const probe = await open(target, opts.root ? { root: opts.root } : {});
- const { entry, dir, name, site, browser, isFilm } = probe;
+ /* `root`: the folder to serve (a host rendering an edit kept elsewhere in a project serves the project). The videos
+ the pages ask for are noted, and served as their fast-seeking copies once there are some (seekable.mjs). */
+ const videos = new Set();
+ /** @type {Map<string, string>} */
+ let copies = new Map();
+ const swap = (/** @type {string} */ file) => {
+ if (clipKind(file) === 'video') videos.add(file);
+ return copies.get(file) ?? null;
+ };
+ const probe = await open(target, { ...(opts.root ? { root: opts.root } : {}), swap });
+ const { entry, dir, name, site, browser, isFilm, root } = probe;
const meta = probe.film.meta;
await probe.film.close();
@@ -51,6 +61,18 @@ export async function render(args, opts = {}) {
const format = { ...container, ...opts.format };
if (alpha && extname(out).toLowerCase() === '.mp4') { await probe.close(); throw new UsageError('mp4 has no transparency: write .webm or .mov with --alpha'); }
const workers = Math.max(1, Math.min(Number(opts.workers ?? defaultWorkers()), total));
+ /* a render of more than a moment: its videos seek fast (a film's video clips load only when their time comes, so
+ they are read from film.html; a page's own videos are the ones it asked for) */
+ if (total >= fps * 2 && opts.seekable !== false) {
+ if (isFilm) {
+ try {
+ const doc = readFilmFile(readFileSync(join(root, entry), 'utf8')).doc;
+ for (const track of doc?.tracks ?? []) for (const clip of track.clips) if (kindOf(clip) === 'video') videos.add(fileOf(root, entry, clip.src));
+ } catch { /* the pages ask for what they need */ }
+ }
+ /* only ever faster: a copy that could not be made leaves its video as it is */
+ if (videos.size) copies = await seekableCopies([...videos], dir, { signal: opts.signal }).catch(() => new Map());
+ }
if (!process.stderr.isTTY && !opts.onProgress) process.stderr.write(` rendering ${total} frames with ${workers} browser${workers > 1 ? 's' : ''}…\n`);
const work = join(outDir(dir, 'render'), `.parts-${process.pid}`);
@@ -77,10 +99,14 @@ export async function render(args, opts = {}) {
const cancelled = opts.signal?.aborted ? Promise.reject(new Error('cancelled'))
: new Promise((_, fail) => opts.signal?.addEventListener('abort', () => fail(new Error('cancelled')), { once: true }));
cancelled.catch(() => {});
+ /** @type {import('playwright-core').Browser[]} */
+ const browsers = [];
/* what is left of a step given up fails as the browsers close: that is no one's error */
const unlessCancelled = (/** @type {Promise<any>} */ step) => { step.catch(() => {}); return Promise.race([step, cancelled]); };
try {
- const pages = await unlessCancelled(Promise.all(Array.from({ length: workers }, () => FilmPage.open(browser, site.url, entry, { scale, transparent: alpha }))));
+ /* a browser each: pages sharing one browser share its GPU process, and stop getting faster after three or four */
+ const more = await unlessCancelled(Promise.all(Array.from({ length: workers - 1 }, () => launch().then((b) => { browsers.push(b); return b; }))));
+ const pages = await unlessCancelled(Promise.all([browser, ...more].map((b) => FilmPage.open(b, site.url, entry, { scale, transparent: alpha }))));
/* a film paints its stage behind its clips (black, or its own background): with alpha, only what the clips draw is kept */
if (alpha && isFilm) await Promise.all(pages.map((p) => p.page.addStyleTag({ content: 'html, body { background: transparent !important; }' })));
const per = Math.ceil(total / workers);
@@ -105,6 +131,7 @@ export async function render(args, opts = {}) {
} finally {
/* Windows lets go of a file a moment after ffmpeg exits */
rmSync(work, { recursive: true, force: true, maxRetries: 5 });
+ await Promise.allSettled(browsers.map((b) => b.close()));
await probe.close();
}
const seconds = (Date.now() - started) / 1000;
@@ -122,8 +149,9 @@ export async function render(args, opts = {}) {
* One browser per three cores, at most four, and memory to spare (a page with its media takes 1.5 GB or more, and the
* encoder and the person's own apps need theirs): a render leaves the computer usable while it runs.
*/
-function defaultWorkers() {
- return Math.max(1, Math.min(4, Math.floor(availableParallelism() / 3), Math.floor(totalmem() / (4 * 2 ** 30))));
+/** A browser for every two cores (a core's two threads), with 3 GB of memory each, up to 8. */
+export function defaultWorkers(threads = availableParallelism(), memory = totalmem()) {
+ return Math.max(1, Math.min(8, Math.floor(threads / 2), Math.floor(memory / (3 * 2 ** 30))));
}
/** Frames [a, b) of one page into one file; sub-frames are averaged by ffmpeg (tmix) and every n-th kept. */
diff --git a/packages/openfilm/src/render.test.mjs b/packages/openfilm/src/render.test.mjs
index db4f579..7df732f 100644
--- a/packages/openfilm/src/render.test.mjs
+++ b/packages/openfilm/src/render.test.mjs
@@ -4,7 +4,7 @@ import { execFileSync } from 'node:child_process';
import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
-import { render } from './render.mjs';
+import { defaultWorkers, render } from './render.mjs';
const hasFfmpeg = (() => { try { execFileSync('ffmpeg', ['-version'], { stdio: 'ignore' }); return true; } catch { return false; } })();
@@ -22,3 +22,11 @@ test('an encoder that fails to start fails the render with ffmpeg\'s error, inst
rmSync(dir, { recursive: true, force: true });
}
});
+
+test('a browser for every two threads, with 3 GB of memory each, at least one and at most eight', () => {
+ const GB = 2 ** 30;
+ assert.equal(defaultWorkers(10, 16 * GB), 5);
+ assert.equal(defaultWorkers(8, 8 * GB), 2, 'memory first');
+ assert.equal(defaultWorkers(32, 128 * GB), 8);
+ assert.equal(defaultWorkers(2, 4 * GB), 1);
+});
diff --git a/packages/openfilm/src/seekable.mjs b/packages/openfilm/src/seekable.mjs
new file mode 100644
index 0000000..8c0dd15
--- /dev/null
+++ b/packages/openfilm/src/seekable.mjs
@@ -0,0 +1,101 @@
+// Videos that seek fast, for a render. A render seeks each video to every frame, and a browser decodes from the key
+// frame before the one asked: footage from cameras, phones and stock sites has one every 1 to 4 s, so each frame costs
+// the decoding of up to a few hundred. Before rendering, such a video gets a copy with a key frame every quarter
+// second, all but lossless, made once and kept in the project's cache; the render's pages are served the copy, and
+// the sound is still mixed from the original.
+import { execFile } from 'node:child_process';
+import { existsSync, renameSync, rmSync, statSync } from 'node:fs';
+import { join } from 'node:path';
+import { ffmpeg, hash, outDir } from './shared.mjs';
+
+/** A key frame further apart than this is slow to seek to frame by frame. */
+const SLOW_GOP_S = 0.5;
+/** The copy's key frames: four a second. */
+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). */
+const MAX_SIDE = 4096;
+/** Changing how copies are made makes new ones. */
+const VERSION = 2;
+
+/** @param {string} file @returns {Promise<string>} */
+const probe = (file, args) => new Promise((done, fail) => {
+ execFile('ffprobe', ['-v', 'error', ...args, file], { maxBuffer: 16 << 20, windowsHide: true }, (error, stdout) => (error ? fail(error) : done(String(stdout))));
+});
+
+/**
+ * What a copy of `file` would be made from: its first video stream, when it is one worth copying (8-bit 4:2:0, no
+ * alpha, not too big or long, key frames far apart). Null when it is better left alone.
+ * @param {string} file
+ */
+export async function slowSeeking(file) {
+ let info;
+ try {
+ info = JSON.parse(await probe(file, ['-select_streams', 'v:0', '-show_entries', 'stream=width,height,pix_fmt,avg_frame_rate:format=duration', '-of', 'json']));
+ } catch { return null; }
+ const stream = info.streams?.[0];
+ const seconds = Number(info.format?.duration);
+ if (!stream || !['yuv420p', 'yuvj420p'].includes(stream.pix_fmt)) return null;
+ if (!(seconds > 0) || seconds > MAX_SECONDS || stream.width > MAX_SIDE || stream.height > MAX_SIDE) return null;
+ const [n, d] = String(stream.avg_frame_rate).split('/').map(Number);
+ const fps = n > 0 && d > 0 ? n / d : 30;
+ /* the key frames among the packets of its first 20 s (read, not decoded) */
+ let keys = 0, span = 0;
+ try {
+ const lines = (await probe(file, ['-select_streams', 'v:0', '-read_intervals', '%+20', '-show_entries', 'packet=pts_time,flags', '-of', 'csv=p=0'])).trim().split('\n');
+ let first = null, last = null;
+ for (const line of lines) {
+ const [pts, flags] = line.split(',');
+ const t = Number(pts);
+ if (!Number.isFinite(t)) continue;
+ first ??= t;
+ last = t;
+ if (flags?.startsWith('K')) keys++;
+ }
+ span = first == null || last == null ? 0 : last - first;
+ } catch { return null; }
+ if (keys === 0 || span <= 0) return null;
+ return span / keys > SLOW_GOP_S ? { fps, seconds } : null;
+}
+
+/**
+ * The fast-seeking copy of each of `files` that needs one, 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.
+ * @param {string[]} files @param {string} root @param {{ signal?: AbortSignal }} [options]
+ */
+export async function seekableCopies(files, root, { signal } = {}) {
+ const copies = new Map();
+ const dir = outDir(root, 'seek');
+ /* two at a time: each one already keeps several cores busy */
+ const queue = [...new Set(files)];
+ const worker = async () => {
+ for (let file = queue.shift(); file; file = queue.shift()) {
+ if (signal?.aborted) return;
+ let stat;
+ try { stat = statSync(file); } catch { continue; }
+ const out = join(dir, `${hash(Buffer.from(`${VERSION}\0${file}\0${stat.size}\0${stat.mtimeMs}`))}.mp4`);
+ if (existsSync(out)) { copies.set(file, out); continue; }
+ const slow = await slowSeeking(file);
+ if (!slow) continue;
+ const gop = String(Math.max(1, Math.round(slow.fps * COPY_GOP_S)));
+ const part = `${out}.part.mp4`;
+ /* the same frames at the same times (passthrough: no frame is added or dropped), the picture only */
+ const run = ffmpeg(['-i', file, '-map', '0:v:0', '-an', '-sn', '-dn', '-fps_mode', 'passthrough',
+ '-c:v', 'libx264', '-preset', 'superfast', '-crf', '16', '-g', gop, '-keyint_min', gop, '-pix_fmt', 'yuv420p', part]);
+ const stop = () => run.proc.kill('SIGKILL');
+ signal?.addEventListener('abort', stop, { once: true });
+ try {
+ await run.done;
+ renameSync(part, out);
+ copies.set(file, out);
+ } catch {
+ rmSync(part, { force: true });
+ } finally {
+ signal?.removeEventListener('abort', stop);
+ }
+ }
+ };
+ await Promise.all([worker(), worker()]);
+ return copies;
+}
diff --git a/packages/openfilm/src/seekable.test.mjs b/packages/openfilm/src/seekable.test.mjs
new file mode 100644
index 0000000..27b7587
--- /dev/null
+++ b/packages/openfilm/src/seekable.test.mjs
@@ -0,0 +1,51 @@
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+import { execFileSync } from 'node:child_process';
+import { existsSync, mkdtempSync, readdirSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { filmHtml } from './film-doc.mjs';
+import { render } from './render.mjs';
+import { seekableCopies, slowSeeking } from './seekable.mjs';
+
+const hasFfmpeg = (() => { try { execFileSync('ffmpeg', ['-version'], { stdio: 'ignore' }); return true; } catch { return false; } })();
+const ffmpeg = { skip: !hasFfmpeg && 'no ffmpeg', timeout: 120_000 };
+
+/** 4 s at 30 fps with a key frame every `gop` frames. */
+const clip = (file, gop) => execFileSync('ffmpeg', ['-v', 'error', '-y', '-f', 'lavfi', '-i', 'testsrc2=size=320x180:rate=30', '-t', '4',
+ '-c:v', 'libx264', '-preset', 'ultrafast', '-g', String(gop), '-keyint_min', String(gop), '-sc_threshold', '0', '-pix_fmt', 'yuv420p', file]);
+/** A video's frame times, as its packets give them. */
+const times = (file) => execFileSync('ffprobe', ['-v', 'error', '-select_streams', 'v:0', '-show_entries', 'packet=pts_time', '-of', 'csv=p=0', file]).toString().trim().split('\n').map(Number).sort((a, b) => a - b);
+
+test('a video with key frames far apart gets a copy with the same frames at the same times; one that seeks fast does not', ffmpeg, async () => {
+ const dir = mkdtempSync(join(tmpdir(), 'of-seekable-'));
+ try {
+ clip(join(dir, 'slow.mp4'), 120);
+ clip(join(dir, 'fast.mp4'), 5);
+ assert.ok(await slowSeeking(join(dir, 'slow.mp4')), 'a key frame every 4 s');
+ assert.equal(await slowSeeking(join(dir, 'fast.mp4')), null, 'six a second');
+ const copies = await seekableCopies([join(dir, 'slow.mp4'), join(dir, 'fast.mp4')], dir);
+ assert.deepEqual([...copies.keys()], [join(dir, 'slow.mp4')]);
+ const copy = /** @type {string} */ (copies.get(join(dir, 'slow.mp4')));
+ assert.deepEqual(times(copy), times(join(dir, 'slow.mp4')));
+ assert.equal(await slowSeeking(copy), null, 'the copy seeks fast');
+ /* kept: the next render finds it */
+ const again = await seekableCopies([join(dir, 'slow.mp4')], dir);
+ assert.equal(again.get(join(dir, 'slow.mp4')), copy);
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+});
+
+test('a render serves the film\'s slow-seeking videos as their copies', ffmpeg, async () => {
+ const dir = mkdtempSync(join(tmpdir(), 'of-seekable-render-'));
+ try {
+ clip(join(dir, 'a.mp4'), 120);
+ writeFileSync(join(dir, 'film.html'), filmHtml({ stage: { w: 320, h: 180 }, tracks: [{ clips: [{ id: 'v', src: 'a.mp4', at: 0, time: [0, 3] }] }] }));
+ const done = await render([dir], { out: join(dir, 'out.mp4'), workers: 2, silent: true, onProgress() {} });
+ assert.ok(existsSync(done.out));
+ assert.equal(readdirSync(join(dir, '.film/cache/seek')).filter((f) => f.endsWith('.mp4') && !f.includes('.part')).length, 1);
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+});
diff --git a/packages/openfilm/src/shared.mjs b/packages/openfilm/src/shared.mjs
index fc94151..4350f42 100644
--- a/packages/openfilm/src/shared.mjs
+++ b/packages/openfilm/src/shared.mjs
@@ -68,7 +68,7 @@ export async function open(target, opts = {}) {
const { problems } = readFilmFile(readFileSync(join(loc.dir, FILM_FILE), 'utf8'));
if (problems.length) throw new FrameError(problems.length === 1 ? problems[0] : `${FILM_FILE} has ${problems.length} problems:\n ${problems.join('\n ')}`);
}
- const site = await serve(loc.root);
+ const site = await serve(loc.root, { swap: opts.swap });
let browser;
try { browser = await launch(opts.launch); }
catch (e) { await site.close(); throw e; }
diff --git a/packages/openfilm/studio/server/exports.mjs b/packages/openfilm/studio/server/exports.mjs
index 7abfb38..dbb7631 100644
--- a/packages/openfilm/studio/server/exports.mjs
+++ b/packages/openfilm/studio/server/exports.mjs
@@ -525,26 +525,87 @@ const BPP = { standard: 0.07, high: 0.11, master: 0.2 };
const BT709 = ['-colorspace', 'bt709', '-color_primaries', 'bt709', '-color_trc', 'bt709', '-color_range', 'tv'];
const TO_709 = 'scale=out_color_matrix=bt709:out_range=tv';
+/**
+ * The graphics chip's encoders for H.264 and HEVC that this platform's ffmpeg may have, in the order they are tried:
+ * the Mac's own; on Windows NVIDIA's, Intel's, AMD's, then Windows' own (Media Foundation, through whichever chip
+ * there is); NVIDIA's on Linux.
+ */
+const HARDWARE = /** @type {Record<string, Record<'h264' | 'hevc', string[]>>} */ ({
+ darwin: { h264: ['h264_videotoolbox'], hevc: ['hevc_videotoolbox'] },
+ win32: { h264: ['h264_nvenc', 'h264_qsv', 'h264_amf', 'h264_mf'], hevc: ['hevc_nvenc', 'hevc_qsv', 'hevc_amf', 'hevc_mf'] },
+ linux: { h264: ['h264_nvenc'], hevc: ['hevc_nvenc'] },
+});
+
+/**
+ * A hardware encoder's options at a bitrate (they take no quality number that means the same on every chip): peaks
+ * allowed at half again, for cuts and screen text.
+ * @param {string} encoder @param {number} bits a second
+ */
+export function hardwareOptions(encoder, bits) {
+ const k = (/** @type {number} */ n) => `${Math.round(n / 1000)}k`;
+ const rate = ['-b:v', k(bits), '-maxrate', k(bits * 1.5), '-bufsize', k(bits * 2)];
+ const hevc = encoder.startsWith('hevc_');
+ const tag = hevc ? ['-tag:v', 'hvc1'] : [];
+ switch (encoder.slice(encoder.indexOf('_') + 1)) {
+ case 'videotoolbox': return ['-c:v', encoder, ...(hevc ? [] : ['-profile:v', 'high']), '-b:v', k(bits), ...tag];
+ case 'nvenc': return ['-c:v', encoder, '-preset', 'p5', '-rc', 'vbr', ...rate, ...tag];
+ case 'qsv': return ['-c:v', encoder, '-preset', 'medium', ...rate, ...tag];
+ case 'amf': return ['-c:v', encoder, '-quality', 'quality', '-rc', 'vbr_peak', ...rate, ...tag];
+ /* the chip's own encoder, never Windows' software one (x264 is better at that) */
+ case 'mf': return ['-c:v', encoder, '-hw_encoding', '1', '-rate_control', 'u_vbr', '-b:v', k(bits), ...tag];
+ default: return ['-c:v', encoder, '-b:v', k(bits), ...tag];
+ }
+}
+
+/** @type {Map<string, Promise<boolean>>} */
+const tried = new Map();
+/**
+ * Whether a hardware encoder works on this machine: one built into ffmpeg may have no chip or driver behind it, so a
+ * moment of video goes through it first (once a launch; `broken` remembers one that failed an export after that).
+ * @param {string} encoder
+ */
+function works(encoder) {
+ if (!tried.has(encoder)) {
+ tried.set(encoder, new Promise((done) => {
+ execFile('ffmpeg', ['-hide_banner', '-loglevel', 'error', '-f', 'lavfi', '-i', 'testsrc2=size=640x360:rate=30', '-frames:v', '10',
+ '-vf', 'format=yuv420p', ...hardwareOptions(encoder, 2e6), '-f', 'null', '-'], { timeout: 20_000, windowsHide: true }, (error) => done(!error));
+ }));
+ }
+ return /** @type {Promise<boolean>} */ (tried.get(encoder));
+}
+/** A hardware encoder that failed an export: the rest of this launch uses another. @param {string} encoder */
+const broken = (encoder) => { tried.set(encoder, Promise.resolve(false)); };
+
+/**
+ * The first hardware encoder for H.264 or HEVC that works here, or null.
+ * @param {'h264' | 'hevc'} codec @param {Set<string>} have @param {string} [platform]
+ */
+export async function hardwareEncoder(codec, have, platform = process.platform) {
+ for (const encoder of HARDWARE[platform]?.[codec] ?? []) if (have.has(encoder) && await works(encoder)) return encoder;
+ return null;
+}
+
/**
* How render should encode a codec: its encoder (for the person's list), and the container format render takes. H.264
- * below master is the Mac's own encoder when it has one (`hardware` not false), as editors do: far faster, and the
- * processor stays free for the person; master stays x264 at its slowest and best.
- * @param {VideoCodec} codec @param {Quality} quality @param {{ w: number, h: number }} size @param {number} fps @param {Set<string>} have @param {boolean} [hardware]
+ * and HEVC below master go through the graphics chip's encoder when it has one that works (`hw`, hardwareEncoder),
+ * as editors do: several times faster, and the processor stays free for drawing the frames and for the person; master
+ * stays x264 and x265 at their slowest and best.
+ * @param {VideoCodec} codec @param {Quality} quality @param {{ w: number, h: number }} size @param {number} fps @param {Set<string>} have @param {string | null} [hw]
*/
-function encoding(codec, quality, size, fps, have, hardware = true) {
- const bitrate = (/** @type {number} */ k) => `${Math.round(Math.min(120e6, Math.max(2e6, size.w * size.h * fps * BPP[quality] * k)) / 1000)}k`;
+function encoding(codec, quality, size, fps, have, hw = null) {
+ const bits = (/** @type {number} */ k) => Math.min(120e6, Math.max(2e6, size.w * size.h * fps * BPP[quality] * k));
+ const bitrate = (/** @type {number} */ k) => `${Math.round(bits(k) / 1000)}k`;
switch (codec) {
case 'h264':
- if (hardware && quality !== 'master' && have.has('h264_videotoolbox')) {
- /* a bitrate (it takes no quality number on every Mac), with room for screen text: half again the dialog's scale */
- return { encoder: 'h264_videotoolbox', format: { video: ['-c:v', 'h264_videotoolbox', '-profile:v', 'high', '-b:v', bitrate(1.5), ...BT709] } };
- }
+ /* with room for screen text: half again the dialog's scale */
+ if (hw && quality !== 'master') return { encoder: hw, format: { video: [...hardwareOptions(hw, bits(1.5)), ...BT709] } };
return { encoder: 'libx264', format: { video: ['-c:v', 'libx264', '-preset', quality === 'master' ? 'slow' : 'medium', '-crf', String(H264_CRF[quality]), ...BT709] } };
case 'hevc':
+ if (hw && quality !== 'master') return { encoder: hw, format: { video: [...hardwareOptions(hw, bits(0.8)), ...BT709], tag: ['-tag:v', 'hvc1'] } };
if (have.has('libx265')) {
return { encoder: 'libx265', format: { video: ['-c:v', 'libx265', '-preset', 'medium', '-crf', String(X265_CRF[quality]), '-x265-params', 'log-level=error', '-tag:v', 'hvc1', ...BT709], tag: ['-tag:v', 'hvc1'] } };
}
- if (have.has('hevc_videotoolbox')) return { encoder: 'hevc_videotoolbox', format: { video: ['-c:v', 'hevc_videotoolbox', '-b:v', bitrate(0.6), '-tag:v', 'hvc1', ...BT709], tag: ['-tag:v', 'hvc1'] } };
+ if (have.has('hevc_videotoolbox')) return { encoder: 'hevc_videotoolbox', format: { video: ['-c:v', 'hevc_videotoolbox', '-b:v', bitrate(0.8), '-tag:v', 'hvc1', ...BT709], tag: ['-tag:v', 'hvc1'] } };
throw new ExportError('this computer\'s ffmpeg has no HEVC encoder (libx265 or hevc_videotoolbox)');
case 'vp9':
return { encoder: 'libvpx-vp9', format: { video: ['-c:v', 'libvpx-vp9', '-b:v', '0', '-crf', String(VP9_CRF[quality]), '-row-mt', '1'] } };
@@ -736,15 +797,32 @@ export function createExports({ onChange = () => {}, captions = subtitlesForExpo
}
/* no fps asked: render's own (30) */
const fps = ask.fps;
- const { encoder, format } = encoding(codec, ask.quality ?? 'high', size, fps ?? 30, await encoders(), ask.hardware !== false);
- const container = /** @type {{ pix?: string }} */ (format).pix ?? (codec === 'h264' || codec === 'hevc' ? `${TO_709},format=yuv420p` : codec === 'vp9' ? 'format=yuva420p' : 'format=yuva444p10le');
- const opts = { fps, scale: place.scale, alpha, silent: ask.audio === false || codec === 'png', format: { ...format, pix: `${place.vf},${container}` }, ...(clip || burn ? { root } : {}) };
+ const quality = ask.quality ?? 'high';
+ const have = await encoders();
+ const hw = ask.hardware !== false && quality !== 'master' && (codec === 'h264' || codec === 'hevc') ? await hardwareEncoder(codec, have) : null;
+ /** @param {string | null} chip */
+ const how = (chip) => {
+ const { encoder, format } = encoding(codec, quality, size, fps ?? 30, have, chip);
+ const container = /** @type {{ pix?: string }} */ (format).pix ?? (codec === 'h264' || codec === 'hevc' ? `${TO_709},format=yuv420p` : codec === 'vp9' ? 'format=yuva420p' : 'format=yuva444p10le');
+ return { encoder, opts: { fps, scale: place.scale, alpha, silent: ask.audio === false || codec === 'png', format: { ...format, pix: `${place.vf},${container}` }, ...(clip || burn ? { root } : {}) } };
+ };
+ let { encoder, opts } = how(hw);
update(job, { encoder });
const target = clip ? clip.dir : burn ? burn.dir : root;
const out = freeFile(dir, baseName(job.name, ask), CODEC_EXT[codec]);
if (codec !== 'png') {
update(job, { out, outputs: [out] });
- await renderTo(job, target, out, opts, signal);
+ try {
+ await renderTo(job, target, out, opts, signal);
+ } catch (e) {
+ /* the graphics chip's encoder gave up partway (a driver, a size it does not take): the rest of this launch
+ encodes without it, starting with this export again */
+ if (!hw || signal.aborted || !/^ffmpeg: /.test(e instanceof Error ? e.message : '')) throw e;
+ broken(hw);
+ ({ encoder, opts } = how(null));
+ update(job, { encoder, framesDone: 0, progress: 0, etaMs: null });
+ await renderTo(job, target, out, opts, signal);
+ }
if (alpha) update(job, { alpha: await alphaOf(out, codec === 'vp9') });
/* the subtitles as a file beside it, timed to the part exported */
if (ask.sidecar) {
diff --git a/packages/openfilm/studio/server/exports.test.mjs b/packages/openfilm/studio/server/exports.test.mjs
index 4a39d8d..1df33bc 100644
--- a/packages/openfilm/studio/server/exports.test.mjs
+++ b/packages/openfilm/studio/server/exports.test.mjs
@@ -5,7 +5,7 @@ import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync,
import { homedir, tmpdir } from 'node:os';
import { join } from 'node:path';
import { fileURLToPath } from 'node:url';
-import { createExports, exportCapabilities, exportsRoot, ExportError, frameBox, dimsForShortEdge, projectFiles, projectSizes } from './exports.mjs';
+import { createExports, exportCapabilities, exportsRoot, ExportError, frameBox, dimsForShortEdge, hardwareEncoder, hardwareOptions, projectFiles, projectSizes } from './exports.mjs';
import { allocateLanes, containMotion, fadeKeyframes, frameSpan, nleRate, planNleTimeline, xmemlDocument } from './nle.mjs';
import { pptxParts } from './slides.mjs';
import { filmSubtitleSrt, parseFilmSubtitleStyle } from './film-subtitle.mjs';
@@ -663,3 +663,23 @@ test('an editing-software export of a film whose clip leads out of the project (
const made = readdirSync(exportsRoot()).filter((n) => n.startsWith('Outside'));
assert.deepEqual(made.flatMap((n) => readdirSync(join(exportsRoot(), n), { recursive: true })).filter((f) => /private/.test(String(f))), []);
});
+
+test('each graphics chip\'s encoder gets a bitrate it keeps to, with HEVC tagged for Apple players', () => {
+ for (const encoder of ['h264_videotoolbox', 'h264_nvenc', 'h264_qsv', 'h264_amf', 'h264_mf', 'hevc_videotoolbox', 'hevc_nvenc', 'hevc_qsv', 'hevc_amf', 'hevc_mf']) {
+ const options = hardwareOptions(encoder, 8e6);
+ assert.deepEqual(options.slice(0, 2), ['-c:v', encoder]);
+ assert.equal(options[options.indexOf('-b:v') + 1], '8000k', encoder);
+ assert.equal(options.includes('hvc1'), encoder.startsWith('hevc_'), encoder);
+ }
+ assert.ok(hardwareOptions('h264_mf', 8e6).join(' ').includes('-hw_encoding 1'), 'never Windows\' software encoder');
+});
+
+test('a hardware encoder is used only when this ffmpeg has it and it works', ffmpeg, async () => {
+ assert.equal(await hardwareEncoder('h264', new Set(['libx264']), 'win32'), null, 'none built in');
+ assert.equal(await hardwareEncoder('h264', new Set(['h264_nvenc']), 'darwin'), null, 'not one of this platform\'s');
+ const have = new Set(execFileSync('ffmpeg', ['-hide_banner', '-encoders']).toString().match(/^ V\S{5} (\S+)/gm)?.map((l) => l.trim().split(/\s+/)[1]) ?? []);
+ if (process.platform === 'darwin' && have.has('h264_videotoolbox')) {
+ assert.equal(await hardwareEncoder('h264', have), 'h264_videotoolbox');
+ assert.equal(await hardwareEncoder('hevc', have), have.has('hevc_videotoolbox') ? 'hevc_videotoolbox' : null);
+ }
+});