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.

render --subtitles: burn the project's subtitles in (#183)

WEBGRS28206c376e0d
diff --git a/.changeset/render-subtitles.md b/.changeset/render-subtitles.md
new file mode 100644
index 0000000..167189d
--- /dev/null
+++ b/.changeset/render-subtitles.md
@@ -0,0 +1,5 @@
+---
+"openfilm": minor
+---
+
+CLI: `openfilm render --subtitles` burns the project's subtitles into the rendered video, in their own style, through the same code Studio's export uses.
diff --git a/packages/openfilm/bin/openfilm.mjs b/packages/openfilm/bin/openfilm.mjs
index 41b39c4..e2a5624 100755
--- a/packages/openfilm/bin/openfilm.mjs
+++ b/packages/openfilm/bin/openfilm.mjs
@@ -81,7 +81,8 @@ openfilm skill remove <name>
--fps <n> frame rate, including decimals such as 29.97 (30)
--4k 3840 px wide --scale <n> any device pixel ratio
--blur motion blur (8 samples) --samples <n> --shutter <0..1>
- --alpha transparent background --workers <n> parallel browsers`,
+ --alpha transparent background --workers <n> parallel browsers
+ --subtitles burn the project's subtitles in, in their own style`,
};
/* `openfilm` alone: the manual, the whole of what an agent needs to know. `get` takes any options its verb has,
@@ -127,7 +128,7 @@ try {
allowPositionals: true,
options: {
count: { type: 'string' }, out: { type: 'string', short: 'o' }, '4k': { type: 'boolean' }, scale: { type: 'string' },
- blur: { type: 'boolean' }, samples: { type: 'string' }, shutter: { type: 'string' }, alpha: { type: 'boolean' },
+ blur: { type: 'boolean' }, samples: { type: 'string' }, shutter: { type: 'string' }, alpha: { type: 'boolean' }, subtitles: { type: 'boolean' },
fps: { type: 'string' }, workers: { type: 'string' }, help: { type: 'boolean', short: 'h' },
},
});
diff --git a/packages/openfilm/src/burn.mjs b/packages/openfilm/src/burn.mjs
new file mode 100644
index 0000000..29cf7f9
--- /dev/null
+++ b/packages/openfilm/src/burn.mjs
@@ -0,0 +1,131 @@
+/* The film with its subtitles burned in: a page drawn around the film, the subtitles over it (Studio's export and
+ render --subtitles). */
+import { randomBytes } from 'node:crypto';
+import { existsSync, readFileSync } from 'node:fs';
+import { copyFile, mkdir, rm, writeFile } from 'node:fs/promises';
+import { join } from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { FILM_FILE, readFilmFile } from './film-doc.mjs';
+import { open } from './shared.mjs';
+import { filmSubtitleShown } from '../studio/server/film-subtitle.mjs';
+
+const tidy = (path) => rm(path, { recursive: true, force: true, maxRetries: 5, retryDelay: 200 }).catch(() => {});
+export const even = (/** @type {number} */ n) => Math.max(2, Math.round(n / 2) * 2);
+
+/** A frame written `W:H` ("16:9", "2.39:1"), from 1:4 to 4:1: its width ÷ height, or null. @param {unknown} frame */
+export function frameRatio(frame) {
+ const m = typeof frame === 'string' ? /^(\d{1,4}(?:\.\d{1,3})?):(\d{1,4}(?:\.\d{1,3})?)$/.exec(frame) : null;
+ if (!m) return null;
+ const ratio = Number(m[1]) / Number(m[2]);
+ return Number.isFinite(ratio) && ratio >= 1 / 4 && ratio <= 4 ? ratio : null;
+}
+
+/**
+ * The film (`stage`) fitted into a delivery frame: the frame's size (its long side follows the film's), its exact
+ * shape (`ratio`: the frame's own, not its even-rounded pixels'), and the film's scale inside it (`contain`: whole,
+ * with bars; `cover`: filling it, the overflow cut).
+ * @param {{ w: number, h: number, ratio?: number }} stage @param {string} frame @param {'contain' | 'cover'} fill
+ */
+export function frameBox(stage, frame, fill) {
+ const ratio = frame === 'native' ? null : frameRatio(frame);
+ /* native: the stage's own shape (a frame drawn as a page, with subtitles over it, keeps the frame's exact one) */
+ if (ratio == null) return { w: even(stage.w), h: even(stage.h), ratio: stage.ratio ?? stage.w / Math.max(1, stage.h), scale: 1 };
+ const box = stage.w / ratio >= stage.h ? { w: stage.w, h: stage.w / ratio } : { w: stage.h * ratio, h: stage.h };
+ const w = even(box.w), h = even(box.h);
+ return { w, h, ratio, scale: fill === 'cover' ? Math.max(w / stage.w, h / stage.h) : Math.min(w / stage.w, h / stage.h) };
+}
+
+/**
+ * The film inside its delivery frame with its subtitles drawn over it: a web page (SPEC.md: `window.film`) in the
+ * project's .film showing the film (film.html's timeline, or the project's page) fitted into the frame, with bars or
+ * cropped as asked, and over the whole frame each moment's subtitle line as the editor draws it (film-subtitle.mjs
+ * `filmSubtitleFrameHtml`). It is rendered like the film itself, and its sound is the film's. `box` is the frame in the
+ * film's pixels; `remove()` when done.
+ * @param {string} root @param {{ w: number, h: number }} stage @param {string} frame @param {'contain' | 'cover'} fill
+ * @param {Cue[]} cues @param {SubtitleStyle} style @param {boolean} [transparent] nothing behind the film (an alpha export)
+ */
+export async function burnFilm(root, stage, frame, fill, cues, style, transparent = false) {
+ const box = frameBox(stage, frame, fill);
+ const dir = join(root, '.film', 'cache', 'export', `burn-${process.pid}-${randomBytes(4).toString('hex')}`);
+ await mkdir(dir, { recursive: true });
+ try {
+ await copyFile(fileURLToPath(new URL('../studio/server/film-subtitle.mjs', import.meta.url)), join(dir, 'film-subtitle.mjs'));
+ const entry = existsSync(join(root, FILM_FILE)) ? `/${FILM_FILE}` : '/index.html';
+ const x = (box.w - stage.w * box.scale) / 2, y = (box.h - stage.h * box.scale) / 2;
+ const json = (/** @type {unknown} */ v) => JSON.stringify(v).replace(/</g, '\\u003c');
+ await writeFile(join(dir, 'index.html'), `<!doctype html>
+<html><head><meta charset="utf-8"><style>
+html,body{margin:0;width:${box.w}px;height:${box.h}px;overflow:hidden;background:${transparent ? 'transparent' : '#000'}}
+#film{position:absolute;left:${x}px;top:${y}px;width:${stage.w}px;height:${stage.h}px;border:0;transform:scale(${box.scale});transform-origin:0 0}
+#subs{position:absolute;left:0;top:0;width:${box.w}px;height:${box.h}px}
+</style></head><body><div id="subs"></div><script type="module">
+import { filmSubtitleFrameHtml } from './film-subtitle.mjs';
+const cues = ${json(cues)};
+const style = ${json({ ...style, on: true })};
+const size = { w: ${box.w}, h: ${box.h} };
+const subs = document.getElementById('subs');
+const el = document.createElement('iframe');
+el.id = 'film';
+let inner = null;
+const loaded = new Promise((ok) => el.addEventListener('load', ok, { once: true }));
+el.src = ${json(entry)};
+document.body.prepend(el);
+const ready = loaded.then(async () => {
+ const win = el.contentWindow;
+ const t0 = performance.now();
+ while (!(win.film && typeof win.film.frame === 'function')) {
+ if (performance.now() - t0 > 10000) throw new Error('the film did not set window.film');
+ await new Promise((r) => setTimeout(r, 20));
+ }
+ await (typeof win.film.ready === 'function' ? win.film.ready() : win.film.ready);
+ ${transparent ? "const clear = win.document.createElement('style'); clear.textContent = 'html, body { background: transparent !important; }'; win.document.head.append(clear);" : ''}
+ inner = win;
+});
+window.film = {
+ get duration() { return inner ? inner.film.duration : 0.001; },
+ width: size.w, height: size.h,
+ ready,
+ async frame(t) {
+ inner.filmHost?.time?.(t);
+ await inner.film.frame(t);
+ inner.filmHost?.settle?.(t);
+ subs.innerHTML = filmSubtitleFrameHtml(cues, style, size, t * 1000);
+ await document.fonts?.ready;
+ },
+};
+window.__filmCuts = () => inner?.__filmCuts?.() ?? null;
+window.__filmSounds = () => inner?.__filmSounds?.() ?? [];
+</script></body></html>
+`);
+ } catch (e) {
+ await tidy(dir);
+ throw e;
+ }
+ return { dir, box, remove: () => tidy(dir) };
+}
+
+/** The film's stage, from film.html (or, for a single page, from the page). @param {string} root */
+export async function stageOf(root) {
+ const file = join(root, FILM_FILE);
+ if (existsSync(file)) {
+ const { doc } = readFilmFile(readFileSync(file, 'utf8'));
+ if (doc) return doc.stage;
+ }
+ const probe = await open(root);
+ try { return { w: probe.film.meta.width, h: probe.film.meta.height }; } finally { await probe.close(); }
+}
+
+/**
+ * The film with its subtitles burned in, when the ask wants them and the film has some (else null): what to render
+ * instead of the project (see burnFilm). `captions(root)`: the film's cues and the person's style (captions.mjs).
+ * @param {string} root @param {{ burnSubtitles?: boolean, frame?: string, fill?: 'contain' | 'cover' }} ask
+ * @param {(root: string) => Promise<{ cues: Cue[], style: SubtitleStyle }>} captions @param {boolean} [transparent]
+ */
+export async function burned(root, ask, captions, transparent = false) {
+ if (!ask.burnSubtitles) return null;
+ /* the cues as stored: the page picks the shown language itself (filmSubtitleFrameHtml), and picking it twice
+ puts a bilingual line's translation under it twice */
+ const { cues, style } = await captions(root);
+ if (!filmSubtitleShown(cues, style).some((c) => c.durMs > 0 && c.text.trim())) return null;
+ return burnFilm(root, await stageOf(root), ask.frame ?? 'native', ask.fill ?? 'contain', cues, style, transparent);
+}
diff --git a/packages/openfilm/src/render.mjs b/packages/openfilm/src/render.mjs
index 5ca68bd..5014980 100644
--- a/packages/openfilm/src/render.mjs
+++ b/packages/openfilm/src/render.mjs
@@ -1,7 +1,7 @@
// 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 { spawn, spawnSync } from 'node:child_process';
-import { mkdirSync, renameSync, rmSync, writeFileSync } from 'node:fs';
+import { existsSync, mkdirSync, renameSync, rmSync, writeFileSync } from 'node:fs';
import { availableParallelism, freemem, totalmem } from 'node:os';
import { basename, dirname, extname, join, resolve } from 'node:path';
import { clipKind, FILM_FILE } from './film-doc.mjs';
@@ -9,7 +9,8 @@ import { broken, encoders, FRAMES_709, hardwareEncoder, hardwareOptions, prores7
import { FilmPage, launch } from './host.mjs';
import { exactRate, ffmpegRate } from './rate.mjs';
import { browserCopies, filmVideos } from './seekable.mjs';
-import { ffmpeg, filmSound, fmt, kill, mix, open, outDir, parseTarget, shown, UsageError, write } from './shared.mjs';
+import { ffmpeg, filmSound, fmt, kill, locate, mix, open, outDir, parseTarget, shown, UsageError, write } from './shared.mjs';
+import { burned } from './burn.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'];
@@ -77,6 +78,22 @@ 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}`);
+ /* --subtitles: the project's film drawn around by a page that burns its subtitles in (the export's own, burn.mjs),
+ rendered in its place, from the project's folder, named as the film's own render is. Studio burns only the
+ project's film, so a page of it is refused */
+ if (opts.subtitles) {
+ const loc = locate(target);
+ const own = existsSync(join(loc.root, FILM_FILE)) ? FILM_FILE : 'index.html';
+ if (decodeURI(loc.entry) !== own) throw new UsageError(`--subtitles burns the subtitles into the project's film: render the project's folder, not ${decodeURI(loc.entry)}`);
+ const { subtitlesForExport } = await import('../studio/server/captions.mjs');
+ const burn = await burned(loc.root, { burnSubtitles: true }, subtitlesForExport, !!opts.alpha);
+ if (!burn) throw new UsageError('--subtitles: the film has no subtitles to burn in');
+ try {
+ return await render([burn.dir, ...(range ? [`${range[0]}-${range[1]}`] : [])], { ...opts, subtitles: false, root: loc.root, nameAs: { dir: loc.dir, name: loc.name } });
+ } finally {
+ await burn.remove();
+ }
+ }
/* `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();
@@ -98,7 +115,10 @@ export async function render(args, opts = {}) {
await pool?.give(lent, { retire: true });
throw e;
}
- const { entry, dir, name, site, browser, isFilm, root } = probe;
+ const { entry, site, browser, isFilm, root } = probe;
+ /* a burned-in render names the project it is for, not the page drawn for it */
+ const dir = opts.nameAs?.dir ?? probe.dir;
+ const name = opts.nameAs?.name ?? probe.name;
const meta = probe.film.meta;
await probe.film.close();
diff --git a/packages/openfilm/src/render.test.mjs b/packages/openfilm/src/render.test.mjs
index 68073e0..44fa101 100644
--- a/packages/openfilm/src/render.test.mjs
+++ b/packages/openfilm/src/render.test.mjs
@@ -1,9 +1,9 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { execFileSync, spawn, spawnSync } from 'node:child_process';
-import { chmodSync, existsSync, mkdirSync, mkdtempSync, rmSync, statSync, writeFileSync } from 'node:fs';
+import { chmodSync, existsSync, mkdirSync, mkdtempSync, readdirSync, rmSync, statSync, writeFileSync } from 'node:fs';
import { getPriority, tmpdir, totalmem } from 'node:os';
-import { join } from 'node:path';
+import { basename, join } from 'node:path';
import { fileURLToPath } from 'node:url';
import { BrowserPool } from './browser-pool.mjs';
import { encoders, hardwareEncoder } from './encoders.mjs';
@@ -237,3 +237,32 @@ document.body.style.background=${clearAt === null ? 'false' : `Math.abs(t-${clea
rmSync(dir, { recursive: true, force: true });
}
});
+
+test('--subtitles burns the project\'s subtitles into its film, named as its render is; a page of it, or a film with none, is refused', { skip: !hasFfmpeg && 'no ffmpeg', timeout: 180_000 }, async () => {
+ const dir = mkdtempSync(join(tmpdir(), 'of-render-subs-'));
+ try {
+ mkdirSync(join(dir, 'assets'));
+ writeFileSync(join(dir, 'page.html'), '<!doctype html><body style="margin:0;background:#204080"><script>window.film = { duration: 2, width: 640, height: 360, frame() {} };</script>');
+ writeFileSync(join(dir, 'film.html'), '<!doctype html><html><head><meta charset="utf-8"><meta name="viewport" content="width=640, height=360"></head>'
+ + '<body><section><iframe src="page.html"></iframe></section><section><audio src="assets/vo.wav"></audio></section></body></html>');
+ execFileSync('ffmpeg', ['-v', 'error', '-y', '-f', 'lavfi', '-i', 'sine=frequency=440:duration=2', '-ac', '1', '-ar', '48000', join(dir, 'assets', 'vo.wav')]);
+ writeFileSync(join(dir, 'assets', 'vo.vtt'), 'WEBVTT\n\n00:00:00.500 --> 00:00:01.800\nBurned in\n');
+ const quiet = { workers: 1, silent: true, onProgress() {}, fps: 10 };
+ /* the bottom third of frame n, in grey, and how many of its pixels differ from another's */
+ const bottom = (file, n) => execFileSync('ffmpeg', ['-v', 'error', '-i', file, '-vf', `select=eq(n\\,${n}),crop=iw:ih/3:0:ih*2/3,format=gray`, '-frames:v', '1', '-f', 'rawvideo', '-']);
+ const changed = (a, b) => a.reduce((n, v, i) => n + (Math.abs(v - b[i]) > 48 ? 1 : 0), 0);
+ const plain = await render([dir], { ...quiet, out: join(dir, 'plain.mp4') });
+ const burned = await render([dir], { ...quiet, subtitles: true, out: join(dir, 'burned.mp4') });
+ assert.equal(changed(bottom(plain.out, 2), bottom(plain.out, 10)), 0, 'without it, the bottom of the picture stays the same');
+ assert.equal(changed(bottom(burned.out, 2), bottom(plain.out, 2)), 0, 'before the line, the picture is the film\'s');
+ assert.ok(changed(bottom(burned.out, 10), bottom(burned.out, 2)) > 200, 'during the line, it is drawn at the bottom');
+ assert.deepEqual(readdirSync(join(dir, '.film', 'cache', 'export')).filter((n) => n.startsWith('burn-')), [], 'the burn page is removed');
+ const past = await render([dir, '1-5'], { ...quiet, subtitles: true });
+ assert.equal(basename(past.out), `${basename(dir)}-1-2.mp4`, 'a range past the end is named as it was rendered, as a plain render names it');
+ await assert.rejects(render([join(dir, 'page.html')], { ...quiet, subtitles: true }), /into the project's film: render the project's folder, not page\.html/);
+ rmSync(join(dir, 'assets', 'vo.vtt'));
+ await assert.rejects(render([dir], { ...quiet, subtitles: true, out: join(dir, 'none.mp4') }), /no subtitles to burn in/);
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+});
diff --git a/packages/openfilm/studio/server/exports.mjs b/packages/openfilm/studio/server/exports.mjs
index 676e150..34a4336 100644
--- a/packages/openfilm/studio/server/exports.mjs
+++ b/packages/openfilm/studio/server/exports.mjs
@@ -75,6 +75,8 @@ import { NLE_FPS, nleFps, planNleTimeline, probeSource, soundStem, xmemlDocument
import { draftsRoot, jianyingDraft } from './jianying.mjs';
import { slidesPdf, writePptx } from './slides.mjs';
import { subtitlesForExport } from './captions.mjs';
+import { burned, even, frameBox, frameRatio, stageOf } from '../../src/burn.mjs';
+export { frameBox, frameRatio };
import { filmSubtitleCuesInRange, filmSubtitleShown, filmSubtitleSrt, filmSubtitleTranscript, filmSubtitleVtt } from './film-subtitle.mjs';
import { zipFiles } from './zip.mjs';
import { inProject } from './files.mjs';
@@ -147,30 +149,8 @@ export const draftApps = () => ({ jianying: Boolean(defaultDrafts('jianying')),
/* ── delivery frames (the same arithmetic as the editor's lib/film-frame.ts) ── */
-/** A frame written `W:H` ("16:9", "2.39:1"), from 1:4 to 4:1: its width ÷ height, or null. @param {unknown} frame */
-export function frameRatio(frame) {
- const m = typeof frame === 'string' ? /^(\d{1,4}(?:\.\d{1,3})?):(\d{1,4}(?:\.\d{1,3})?)$/.exec(frame) : null;
- if (!m) return null;
- const ratio = Number(m[1]) / Number(m[2]);
- return Number.isFinite(ratio) && ratio >= 1 / 4 && ratio <= 4 ? ratio : null;
-}
const MAX_DIM = 4096;
-const even = (/** @type {number} */ n) => Math.max(2, Math.round(n / 2) * 2);
-/**
- * The film (`stage`) fitted into a delivery frame: the frame's size (its long side follows the film's), its exact
- * shape (`ratio`: the frame's own, not its even-rounded pixels'), and the film's scale inside it (`contain`: whole,
- * with bars; `cover`: filling it, the overflow cut).
- * @param {{ w: number, h: number, ratio?: number }} stage @param {string} frame @param {'contain' | 'cover'} fill
- */
-export function frameBox(stage, frame, fill) {
- const ratio = frame === 'native' ? null : frameRatio(frame);
- /* native: the stage's own shape (a frame drawn as a page, with subtitles over it, keeps the frame's exact one) */
- if (ratio == null) return { w: even(stage.w), h: even(stage.h), ratio: stage.ratio ?? stage.w / Math.max(1, stage.h), scale: 1 };
- const box = stage.w / ratio >= stage.h ? { w: stage.w, h: stage.w / ratio } : { w: stage.h * ratio, h: stage.h };
- const w = even(box.w), h = even(box.h);
- return { w, h, ratio, scale: fill === 'cover' ? Math.max(w / stage.w, h / stage.h) : Math.min(w / stage.w, h / stage.h) };
-}
/**
* A box's size with its short side at `shortEdge` (even, no side over 4096), in the box's exact shape: a 16:9 frame
@@ -494,17 +474,6 @@ function run(args, signal, input) {
});
}
-/** The film's stage, from film.html (or, for a single page, from the page). @param {string} root */
-async function stageOf(root) {
- const file = join(root, FILM_FILE);
- if (existsSync(file)) {
- const { doc } = readFilmFile(readFileSync(file, 'utf8'));
- if (doc) return doc.stage;
- }
- const probe = await open(root);
- try { return { w: probe.film.meta.width, h: probe.film.meta.height }; } finally { await probe.close(); }
-}
-
/** The project's film.html, read. @param {string} root */
function filmDoc(root) {
const file = join(root, FILM_FILE);
@@ -559,69 +528,6 @@ async function clipFilm(root, clipId, { change = {}, doc = filmDoc(root) } = {})
return { dir, stage: doc.stage, remove: () => tidy(dir) };
}
-/**
- * The film inside its delivery frame with its subtitles drawn over it: a web page (SPEC.md: `window.film`) in the
- * project's .film showing the film (film.html's timeline, or the project's page) fitted into the frame, with bars or
- * cropped as asked, and over the whole frame each moment's subtitle line as the editor draws it (film-subtitle.mjs
- * `filmSubtitleFrameHtml`). It is rendered like the film itself, and its sound is the film's. `box` is the frame in the
- * film's pixels; `remove()` when done.
- * @param {string} root @param {{ w: number, h: number }} stage @param {string} frame @param {'contain' | 'cover'} fill
- * @param {Cue[]} cues @param {SubtitleStyle} style @param {boolean} [transparent] nothing behind the film (an alpha export)
- */
-async function burnFilm(root, stage, frame, fill, cues, style, transparent = false) {
- const box = frameBox(stage, frame, fill);
- const dir = join(root, '.film', 'cache', 'export', `burn-${process.pid}-${randomBytes(4).toString('hex')}`);
- await mkdir(dir, { recursive: true });
- await copyFile(fileURLToPath(new URL('./film-subtitle.mjs', import.meta.url)), join(dir, 'film-subtitle.mjs'));
- const entry = existsSync(join(root, FILM_FILE)) ? `/${FILM_FILE}` : '/index.html';
- const x = (box.w - stage.w * box.scale) / 2, y = (box.h - stage.h * box.scale) / 2;
- const json = (/** @type {unknown} */ v) => JSON.stringify(v).replace(/</g, '\\u003c');
- await writeFile(join(dir, 'index.html'), `<!doctype html>
-<html><head><meta charset="utf-8"><style>
-html,body{margin:0;width:${box.w}px;height:${box.h}px;overflow:hidden;background:${transparent ? 'transparent' : '#000'}}
-#film{position:absolute;left:${x}px;top:${y}px;width:${stage.w}px;height:${stage.h}px;border:0;transform:scale(${box.scale});transform-origin:0 0}
-#subs{position:absolute;left:0;top:0;width:${box.w}px;height:${box.h}px}
-</style></head><body><div id="subs"></div><script type="module">
-import { filmSubtitleFrameHtml } from './film-subtitle.mjs';
-const cues = ${json(cues)};
-const style = ${json({ ...style, on: true })};
-const size = { w: ${box.w}, h: ${box.h} };
-const subs = document.getElementById('subs');
-const el = document.createElement('iframe');
-el.id = 'film';
-let inner = null;
-const loaded = new Promise((ok) => el.addEventListener('load', ok, { once: true }));
-el.src = ${json(entry)};
-document.body.prepend(el);
-const ready = loaded.then(async () => {
- const win = el.contentWindow;
- const t0 = performance.now();
- while (!(win.film && typeof win.film.frame === 'function')) {
- if (performance.now() - t0 > 10000) throw new Error('the film did not set window.film');
- await new Promise((r) => setTimeout(r, 20));
- }
- await (typeof win.film.ready === 'function' ? win.film.ready() : win.film.ready);
- ${transparent ? "const clear = win.document.createElement('style'); clear.textContent = 'html, body { background: transparent !important; }'; win.document.head.append(clear);" : ''}
- inner = win;
-});
-window.film = {
- get duration() { return inner ? inner.film.duration : 0.001; },
- width: size.w, height: size.h,
- ready,
- async frame(t) {
- inner.filmHost?.time?.(t);
- await inner.film.frame(t);
- inner.filmHost?.settle?.(t);
- subs.innerHTML = filmSubtitleFrameHtml(cues, style, size, t * 1000);
- await document.fonts?.ready;
- },
-};
-window.__filmCuts = () => inner?.__filmCuts?.() ?? null;
-window.__filmSounds = () => inner?.__filmSounds?.() ?? [];
-</script></body></html>
-`);
- return { dir, box, remove: () => tidy(dir) };
-}
const H264_CRF = { standard: 23, high: 18, master: 14 };
const X265_CRF = { standard: 28, high: 23, master: 19 };
@@ -872,19 +778,8 @@ export function createExports({ onChange = () => {}, captions = subtitlesForExpo
const { cues, style } = await captions(root);
return { cues: filmSubtitleShown(cues, style).filter((c) => c.durMs > 0 && c.text.trim()), style };
};
- /**
- * The film with its subtitles burned in, when the ask wants them and the film has some (else null): what to render
- * instead of the project (see burnFilm).
- * @param {string} root @param {Framing} ask @param {boolean} [transparent]
- */
- const burned = async (root, ask, transparent = false) => {
- if (!ask.burnSubtitles) return null;
- if (!(await subtitlesOf(root)).cues.length) return null;
- /* the cues as stored: the page picks the shown language itself (filmSubtitleFrameHtml), and picking it twice
- puts a bilingual line's translation under it twice */
- const { cues, style } = await captions(root);
- return burnFilm(root, await stageOf(root), ask.frame ?? 'native', ask.fill ?? 'contain', cues, style, transparent);
- };
+ /** The film with its subtitles burned in, or null (burn.mjs). @param {string} root @param {Framing} ask @param {boolean} [transparent] */
+ const burnedOf = (root, ask, transparent = false) => burned(root, ask, captions, transparent);
/**
* render's frame count as the job's progress, its rate and what is left: `share` is the part of the whole job the
@@ -921,7 +816,7 @@ export function createExports({ onChange = () => {}, captions = subtitlesForExpo
const codec = ask.codec ?? 'h264';
const alpha = ALPHA_CODECS.has(codec);
const clip = ask.clip ? await clipFilm(root, ask.clip) : null;
- const burn = clip ? null : await burned(root, ask, alpha);
+ const burn = clip ? null : await burnedOf(root, ask, alpha);
const scratch = codec === 'png' || codec === 'hevc_alpha' ? await mkdtemp(join(tmpdir(), 'openfilm-export-')) : null;
try {
const stage = clip?.stage ?? await stageOf(root);
@@ -1019,7 +914,7 @@ export function createExports({ onChange = () => {}, captions = subtitlesForExpo
async function exportGif(job, root, dir, signal) {
const ask = /** @type {GifAsk} */ (job.ask);
const scratch = await mkdtemp(join(tmpdir(), 'openfilm-export-'));
- const burn = await burned(root, ask);
+ const burn = await burnedOf(root, ask);
try {
/* with subtitles, the frame is the page drawn */
const stage = burn ? burn.box : await stageOf(root);
@@ -1095,7 +990,7 @@ export function createExports({ onChange = () => {}, captions = subtitlesForExpo
* @param {string} scratch @param {AbortSignal} signal
*/
async function stillFrames(job, root, ask, ext, scratch, signal) {
- const burn = await burned(root, ask);
+ const burn = await burnedOf(root, ask);
/* footage the browser does not decode (ProRes; HEVC without a chip for it) drawn through a copy it plays: the film's
video clips, the project's when the film is drawn inside a frame with its subtitles */
const probe = await open(burn ? burn.dir : root, burn ? { root, playable: filmVideos(root, FILM_FILE) } : { playable: true }).catch(async (e) => { await burn?.remove(); throw e; });