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.

Render: several scenes and transitions at once (#12)

Stanyslaus Haryae4de24e3b10
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 6a1b006..e5fbc0e 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -6,6 +6,7 @@ Changes are listed by release, newest first. The sections dated before 0.1.0 rec
### Added
+- `motlab render` and the viewer's Export render several scenes and transitions at once, each in its own Chrome, after the first scene has picked the encoder. `--parallel N` sets how many; the default is 3, but never more than one per 4 CPU threads or per 1 GB of free memory. If a part fails while several run, the finished parts are kept and the rest are rendered one at a time, so a machine that cannot run three still finishes. Each part's log is printed in one piece when it ends. On the test laptop (Ryzen 7 5800H, 16 threads, RTX 3060 Laptop), a project of 12 two-second scenes with 11 transitions went from 78 s to 45 s at 1080p and from 93 s to 53 s at 4K; four at a time was no faster than three. The example project went from 12.7 to 13.1 s to 8.9 to 9.6 s at 1080p, with an identical MP4. `test/render.test.js` renders a four-scene project three at a time and checks the frame count and the colours of every scene and transition, then breaks one scene and checks that it is tried again alone and its error is the one reported. Not tried: a machine with fewer threads or less memory, and a GPU that runs out of encoder sessions.
- With no system Chrome, motlab uses the newest Chromium that Playwright downloaded, from Playwright's folder (`~/.cache/ms-playwright` on Linux, `~/Library/Caches/ms-playwright` on macOS, `%LOCALAPPDATA%\ms-playwright` on Windows, or `PLAYWRIGHT_BROWSERS_PATH`), so `motlab doctor` passes without `CHROME` on a machine set up for Playwright (issue #8). The folder names come from Playwright's own code, and a test checks the lookup on folders made for it. Not tried: a real Playwright download found this way. The render in issue #8 used that Chromium with `CHROME` set.
- `motlab render --only 3` (or `--only 3,5`) re-renders only the scenes you name, plus the transitions touching them, and takes the rest from the cache in `~/.cache/motlab/parts` (`%LOCALAPPDATA%\motlab\parts` on Windows, or `MOTLAB_CACHE_DIR`), which a full render leaves behind. A scene with no cached part is rendered, so `--only` on a project that was never rendered works like a full render. A finished render removes the cached parts it did not use, so the cache holds the last render only and `--only` needs the same `--scale` as that render. The cache key holds the motlab version, so parts made by an older version are rendered again after an update. The cache keys on the scene page itself: a file the scene loads changing (a shared script, a font, a picture) is not noticed, so render the whole project again then. Checked on the example project (3 scenes, 9 s, 1080p) on Ubuntu 24.04 with no GPU, SwiftShader, while other builds were running on the same machine: a full render took 44 to 49 s, `--only 3` took 17 to 24 s. The --only output differs from a full render by the same amount two full renders differ from each other (average PSNR 68.9 dB in both cases, from the encoder's run-to-run variation). `test/render.test.js` renders a project, changes one scene, re-renders with `--only` and checks the frame count, the cached log line, the colours of the cached, transition and re-rendered frames, and that the old parts are gone.
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 9605f5f..dab7e34 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -47,7 +47,7 @@ The code is plain JavaScript ESM with JSDoc, no TypeScript and no build step, be
npm test
```
-`test/codecs.test.js` checks the frame maths. `test/render.test.js` renders `test/fixtures/basic.html` through every path (default encoder, software, raw mux, three workers, audio, stills, events) and checks the frame count, duration, colour tags and decoded colour values. It also renders a WebM footage clip, projects with a transition and with scenes of different sizes, and a project again with `--only`. It needs Chrome and ffmpeg. The others need neither: `motion.test.js` checks the easings, springs, keyframes and transition names, `chrome.test.js` the `--no-sandbox` flag and the lookup of Playwright's Chromium, `server.test.js` that a file stream closes when its request is aborted, `install.test.js` what setup, `--update` and uninstall write and remove, `notes.test.js` how the viewer's notes merge into `selection.json`, `skills.test.js` the skills' frontmatter, and `editor-text.test.js` the viewer's `TEXT` table.
+`test/codecs.test.js` checks the frame maths. `test/render.test.js` renders `test/fixtures/basic.html` through every path (default encoder, software, raw mux, three workers, audio, stills, events) and checks the frame count, duration, colour tags and decoded colour values. It also renders a WebM footage clip, projects with a transition and with scenes of different sizes, a project again with `--only`, and a project three parts at a time with one part failing. It needs Chrome and ffmpeg. The others need neither: `motion.test.js` checks the easings, springs, keyframes and transition names, `chrome.test.js` the `--no-sandbox` flag and the lookup of Playwright's Chromium, `server.test.js` that a file stream closes when its request is aborted, `install.test.js` what setup, `--update` and uninstall write and remove, `notes.test.js` how the viewer's notes merge into `selection.json`, `skills.test.js` the skills' frontmatter, and `editor-text.test.js` the viewer's `TEXT` table.
If you touch the renderer, include the render time of the sample project before and after: `motlab render example --scale 1`.
diff --git a/ROADMAP.md b/ROADMAP.md
index 88d29f9..2622712 100644
--- a/ROADMAP.md
+++ b/ROADMAP.md
@@ -5,7 +5,6 @@ What is not built, what has not been tested, and ideas that came up while using
## Not built yet
- Alpha output (ProRes 4444).
-- Rendering several scenes at once in an export. Scenes render one after another today, and Export uses one Chrome. Parallel workers need a safe default for machines with less memory or a hardware encoder session limit, and a fallback to fewer workers when one fails. A project of many short scenes pays a Chrome start per scene: 12 two-second scenes with 11 transitions took 57 s at 1080p.
- The viewer on a VPS with a domain. That needs security in front of it, or access only through Tailscale, which is also worth considering. From there, work could be run remotely on the personal laptop (when it is on) or on the VPS (when there is one).
- Custom GLSL transitions from a file in the project. A transition as a layer over the cut (a swish of shapes) already exists as the asset skill's `transition.js`, but each of the two scene pages has to draw its half by hand; `project.json` has no option for it.
- A cut list that splits one recording over several scenes by section, with captions placed from a transcript. `cuts.js` has the time map (`toOut`), but each section page still picks its part of the list by hand.
@@ -16,6 +15,7 @@ What is not built, what has not been tested, and ideas that came up while using
- The benchmark against Remotion and HyperFrames on macOS and Linux, with their own downloaded browsers, and on scenes heavy on text, images or footage. It was one scene on Windows, at 1080p and 4K.
- The npm package on macOS. It was installed on Windows, from the registry and with nvm for Windows 2.0 (where setup writes its own launcher), and on a Linux VPS from a packed tarball (docs/install.md).
- macOS, and Linux beyond the tests, including `motlab update` there. On Linux, CI renders the end-to-end tests on an Ubuntu runner, and a real video has been made there now: a 42 s, 1080x1920 project on Ubuntu 24.04 with no GPU, in about 82 s (issue #8). On macOS the Chrome paths and the Metal flag are in the code, but nothing has run.
+- `render --parallel` and Export on a machine with fewer than 16 CPU threads or little memory, and on a GPU whose hardware encoder runs out of sessions, where the fallback to one part at a time should take over. The parallel render was measured on the test laptop only (docs/projects.md).
- Renders longer than 10 minutes, and a 10-minute render on a machine that is doing nothing else.
- A machine without a GPU beyond the tests. CI runs the end-to-end tests on Linux and Windows runners without a GPU, and the benchmark ran with Chrome drawing on SwiftShader on the test laptop (1080p and 4K, in `docs/rendering.md`). A real video has been rendered on such a machine now: a 42 s, 1080x1920 project on Ubuntu 24.04 with no GPU, in about 82 s (issue #8). No 3D (WebGL) scene has been rendered on one yet.
- Footage filmed on a phone (variable frame rate and HEVC were tested with files made by ffmpeg), and HEVC on a Chrome that cannot decode it.
diff --git a/docs/cli.md b/docs/cli.md
index e68d1f8..3043794 100644
--- a/docs/cli.md
+++ b/docs/cli.md
@@ -1,7 +1,7 @@
# Command line
```text
-motlab render <project> [out.mp4] [--scale 2] [--only 3] all scenes and audio in project.json, as one MP4
+motlab render <project> [out.mp4] [--scale 2] [--only 3] [--parallel 3] all scenes and audio in project.json, as one MP4
motlab start the viewer in the background at http://127.0.0.1:4173, one for all projects
motlab edit [project] open a project in the viewer, starting it first if needed
motlab stop | restart end the viewer, or start it again from the same folder
@@ -34,7 +34,7 @@ When the page throws while loading, the error names the file, line and column, f
## Options
-`render` takes `--scale` and `--only`; the rest are for `video` (and `--root`, `--chrome`, `--scale` and `--format` for `stills`, and `--root` and `--chrome` for `events`).
+`render` takes `--scale`, `--only` and `--parallel`; the rest are for `video` (and `--root`, `--chrome`, `--scale` and `--format` for `stills`, and `--root` and `--chrome` for `events`).
| Option | Meaning |
|---|---|
@@ -49,6 +49,7 @@ When the page throws while loading, the error names the file, line and column, f
| `--mux` | `auto`, `mediabunny` or `raw`. Auto tries the in-page MP4 muxer, then a raw bitstream wrapped by ffmpeg |
| `--reprobe` | Time the encoders again instead of using the saved timings |
| `--only` | Re-render only these scenes (1-based, comma separated), for example `--only 3` or `--only 3,5`, and reuse the cached parts of the rest. The transitions touching a re-rendered scene are re-rendered too. The cache holds the last render's parts, so pass the same `--scale` as that render. Only for `render`, see [Rendering a project](projects.md#rendering-a-project) |
+| `--parallel` | How many scenes and transitions `render` renders at once, each in its own Chrome. Default 3, or fewer on a machine with under 12 CPU threads or 3 GB of free memory. 1 renders them one after another. See [Rendering a project](projects.md#rendering-a-project) |
| `--root` | Folder to serve. Default is the nearest folder above the page with a `project.json`, else the page's folder |
| `--chrome` | Path to Chrome. Default: found automatically, or the `CHROME` environment variable |
| `--format` | `png` or `jpg`, for `stills` |
diff --git a/docs/projects.md b/docs/projects.md
index 4e9b92c..db9652e 100644
--- a/docs/projects.md
+++ b/docs/projects.md
@@ -72,7 +72,9 @@ How it works:
- The first scene picks the encoder, and every later scene is forced to the same encoder and codec, because a stream copy join is only safe when codec, encoder and resolution match.
- Scenes are joined with hard cuts, unless a scene has a transition. A transition is rendered as a part of its own between the two scenes, and their own parts leave out those frames.
- ffmpeg mixes the audio into one WAV first (`adelay`, `volume`, `amix`), and the final pass muxes it in as AAC.
-- Every scene starts its own Chrome (about one second) and runs one ffmpeg pass, so a project with many short scenes pays that per scene. Scenes are rendered one after another.
+- Every scene and every transition is a part with its own Chrome (about one second to start) and one ffmpeg pass. The first scene renders alone, because it picks the encoder. The other parts then render several at a time, each in its own Chrome, and are joined in order. A transition waits for the scene before it, which tells it where that scene ends.
+- `--parallel` sets how many render at once. The default is 3, but never more than one per 4 CPU threads or per 1 GB of free memory, so a 4-thread machine renders one at a time. Each part's log is printed in one piece when it finishes. If a part fails while several run (too little memory, or more hardware encoder sessions than the GPU allows), the others stop, the finished parts are kept, and the parts still missing are rendered one at a time. A part that fails then too stops the render with its own error.
+- Measured on the test laptop (Ryzen 7 5800H with 16 threads, RTX 3060 Laptop) on a project of 12 two-second 1920x1080 scenes joined by 11 half-second transitions: 78 s one at a time, 49 s two at a time, 45 s three at a time and 41 to 47 s four at a time at 1080p; 93, 62, 53 and 51 s at 4K. With 160 shadowed shapes per frame, 4K took 94, 64, 53 and 52 s. Three at a time used about 2.5 GB of memory for the Chrome processes at 4K. The example project went from 12.7 to 13.1 s to 8.9 to 9.6 s at 1080p, and its MP4 came out identical. Not tried yet: a machine with fewer threads or less memory, and a GPU whose encoder sessions run out.
## Transitions
diff --git a/src/cli.js b/src/cli.js
index b4f16f8..afd0c45 100644
--- a/src/cli.js
+++ b/src/cli.js
@@ -11,7 +11,8 @@ import { openInViewer, restartViewer, startViewer, stopViewer } from './viewer.j
const USAGE = `motlab: render a canvas page (canvas #c, renderAt(t), TOTAL, ready, EVENTS) with headless Chrome and WebCodecs.
- motlab render <project> [out.mp4] [--scale 2] [--only 3] all scenes and audio in project.json, as one MP4
+ motlab render <project> [out.mp4] [--scale 2] [--only 3] [--parallel 3]
+ all scenes and audio in project.json, as one MP4
motlab start the viewer in the background at http://127.0.0.1:4173, for every
project; the menu lists the projects in this folder
motlab edit [project] open a project in the viewer (starting it if needed) and print its
@@ -45,6 +46,8 @@ const USAGE = `motlab: render a canvas page (canvas #c, renderAt(t), TOTAL, read
--mux auto | mediabunny | raw (auto tries Mediabunny, then raw bitstream + ffmpeg -c copy)
--reprobe time the encoders again instead of using the saved probe
--only re-render only these scenes (1-based, comma separated) and reuse the cached parts of the rest (render only)
+ --parallel render this many scenes and transitions at once, each in its own Chrome (render only; default 3, or
+ fewer with under 12 CPU threads or 3 GB of free memory)
--root folder to serve (default: the nearest folder above the page with a project.json, else the page's folder)
--chrome path to Chrome (default: autodetect, or the CHROME environment variable)
@@ -78,7 +81,7 @@ export async function main(argv) {
const { values: v, positionals } = parseArgs({ args: argv, allowPositionals: true, options: {
fps: { type: 'string' }, scale: { type: 'string' }, audio: { type: 'string' }, encoder: { type: 'string' }, codec: { type: 'string' },
workers: { type: 'string' }, bitrate: { type: 'string' }, qp: { type: 'string' }, mux: { type: 'string' }, root: { type: 'string' }, chrome: { type: 'string' },
- only: { type: 'string' },
+ only: { type: 'string' }, parallel: { type: 'string' },
format: { type: 'string' }, reprobe: { type: 'boolean' }, 'dry-run': { type: 'boolean' }, yes: { type: 'boolean', short: 'y' }, foreground: { type: 'boolean' }, gpu: { type: 'boolean' }, help: { type: 'boolean', short: 'h' },
} });
const [mode, page, out, ...rest] = positionals;
@@ -93,7 +96,7 @@ export async function main(argv) {
if (mode === 'restart') { await restartViewer(); return 0; }
if (mode === 'render') {
if (!page) throw new Error('render needs a project folder or project file');
- await renderProject({ dir: page, out, scale: num('scale', v.scale, { min: 0.01 }), only: only(v.only) });
+ await renderProject({ dir: page, out, scale: num('scale', v.scale, { min: 0.01 }), only: only(v.only), parallel: num('parallel', v.parallel, { min: 1, int: true }) });
return 0;
}
if (!['stills', 'video', 'events'].includes(mode)) throw new Error(`unknown mode "${mode}" (render, start, edit, stop, restart, stills, video, events, doctor, setup, update or uninstall)`);
diff --git a/src/project.js b/src/project.js
index 396e6c7..4238678 100644
--- a/src/project.js
+++ b/src/project.js
@@ -7,13 +7,18 @@
import { spawnSync } from 'node:child_process';
import { createHash } from 'node:crypto';
import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, renameSync, rmSync, writeFileSync } from 'node:fs';
-import { tmpdir } from 'node:os';
+import { freemem, availableParallelism, tmpdir } from 'node:os';
import { basename, dirname, join, resolve } from 'node:path';
import { finalize, probeVideo, run } from './ffmpeg.js';
import { findTransition, transitionProgress } from './page/transitions.js';
import { cacheDir } from './probe.js';
import { renderVideo } from './render.js';
+// How many parts render at once without --parallel: 3, fewer on a smaller machine. On the test laptop (16 threads) a
+// project of 12 short scenes got faster up to 3 at once and no faster at 4, and 3 Chrome processes rendering 4K used
+// about 2.5 GB together, so each part gets 4 threads and 1 GB of free memory. Each part is its own Chrome and encoder.
+export const defaultParallel = () => Math.max(1, Math.min(3, Math.floor(availableParallelism() / 4), Math.floor(freemem() / 1e9)));
+
const VERSION = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version;
// The scenes as { file, transition }, each transition with its length in frames (n): its duration on the frame grid,
@@ -49,7 +54,7 @@ export function projectPaths(target) {
// version are rendered again after an update, and a finished render removes the cached parts it did not use.
// The key is the scene page itself, so a file the scene loads (a shared script, a font, a picture) changing is
// not noticed: render the whole project again then, or delete the cache folder.
-export async function renderProject({ dir, out, scale, only, log = console.log, signal }) { // signal: an AbortSignal that stops the render
+export async function renderProject({ dir, out, scale, only, parallel, log = console.log, signal }) { // signal: an AbortSignal that stops the render
const { root, file, name } = projectPaths(dir);
dir = root; out = resolve(out || join(dir, 'out', name + '.mp4'));
const p = JSON.parse(readFileSync(file, 'utf8')), tmp = mkdtempSync(join(tmpdir(), 'motlab-project-')), partial = out + '.part';
@@ -68,7 +73,7 @@ export async function renderProject({ dir, out, scale, only, log = console.log,
const key = o => createHash('sha256').update(JSON.stringify(o)).digest('hex');
// A part is reused only when its cached file still probes as the manifest says, and its encoder and colour range
// match the first part, because a stream copy join is only safe when codec, encoder and resolution match.
- const getPart = async (k, forced, label, render) => {
+ const getPart = async (k, forced, label, log, render) => {
used.add(k);
let suffix = '';
if (!forced) {
@@ -93,24 +98,68 @@ export async function renderProject({ dir, out, scale, only, log = console.log,
} catch (e) { log(`(could not save the cached part: ${e.message})`); }
return summary;
};
- for (const [i, scene] of scenes.entries()) {
- const into = scene.transition, next = scenes[i + 1]?.transition;
- signal?.throwIfAborted();
- const k = key({ kind: 'scene', file: scene.file, hash: hashes[i], fps: p.fps, scale, version: VERSION, head: into?.n || 0, tail: next?.n || 0 });
- const part = await getPart(k, !only || only.includes(i + 1), `\nScene ${i + 1}/${scenes.length}: ${scene.file}`, () => renderVideo({ page: join(dir, scene.file), root: dir,
- out: join(cacheRoot, k + '.mp4'), fps: p.fps, scale, log, signal, head: into?.n, tail: next?.n, ...same() }));
- // a stream copy join of parts with different sizes makes an MP4 that changes resolution partway through
- if (parts[0] && (part.width !== parts[0].width || part.height !== parts[0].height))
- throw new Error(`${scene.file} is ${part.width}x${part.height} but ${scenes[0].file} is ${parts[0].width}x${parts[0].height}. All scenes in a project must have the same canvas size`);
- parts.push(part);
- if (!next) continue;
+ // The parts in order: each scene, and after it the transition into the next one. Scene 1 renders first and
+ // alone, because it picks the encoder (and times the encoders on a new machine). The rest render `parallel` at a
+ // time, each in its own Chrome; a transition waits for the scene before it, which tells it where that scene ends.
+ const jobs = scenes.flatMap((scene, i) => [{ kind: 'scene', i }, ...(scenes[i + 1]?.transition ? [{ kind: 'transition', i }] : [])]);
+ let progress = true; // the frame counter on the terminal, off while parts render in parallel
+ const renderJob = async (j, log, signal) => {
+ const { i } = jobs[j], scene = scenes[i], into = scene.transition, next = scenes[i + 1]?.transition;
+ signal.throwIfAborted();
+ if (jobs[j].kind === 'scene') {
+ const k = key({ kind: 'scene', file: scene.file, hash: hashes[i], fps: p.fps, scale, version: VERSION, head: into?.n || 0, tail: next?.n || 0 });
+ const part = await getPart(k, !only || only.includes(i + 1), `\nScene ${i + 1}/${scenes.length}: ${scene.file}`, log, () => renderVideo({ page: join(dir, scene.file), root: dir,
+ out: join(cacheRoot, k + '.mp4'), fps: p.fps, scale, log, signal, progress, head: into?.n, tail: next?.n, ...same() }));
+ // a stream copy join of parts with different sizes makes an MP4 that changes resolution partway through
+ if (parts[0] && (part.width !== parts[0].width || part.height !== parts[0].height))
+ throw Object.assign(new Error(`${scene.file} is ${part.width}x${part.height} but ${scenes[0].file} is ${parts[0].width}x${parts[0].height}. All scenes in a project must have the same canvas size`), { final: true });
+ return part;
+ }
+ const from = parts[j - 1];
const tk = key({ kind: 'transition', from: scene.file, to: scenes[i + 1].file, fromHash: hashes[i], toHash: hashes[i + 1],
type: next.type, n: next.n, ease: next.ease, params: next.params, fps: p.fps, scale, version: VERSION });
- const query = new URLSearchParams({ from: scene.file, to: scenes[i + 1].file, offset: (part.pageFrames - next.n) / p.fps, frames: next.n,
+ const query = new URLSearchParams({ from: scene.file, to: scenes[i + 1].file, offset: (from.pageFrames - next.n) / p.fps, frames: next.n,
fps: p.fps, type: next.type, ease: next.ease, params: JSON.stringify(next.params) });
- parts.push(await getPart(tk, !only || only.includes(i + 1) || only.includes(i + 2), `\nTransition ${i + 1} to ${i + 2}: ${next.type}, ${next.n} frames`,
+ return getPart(tk, !only || only.includes(i + 1) || only.includes(i + 2), `\nTransition ${i + 1} to ${i + 2}: ${next.type}, ${next.n} frames`, log,
() => renderVideo({ url: '__motlab/transition.html', query: String(query), root: dir, out: join(cacheRoot, tk + '.mp4'),
- fps: p.fps, scale, log, signal, ...same() })));
+ fps: p.fps, scale, log, signal, progress, ...same() }));
+ };
+ // Runs the parts that have no result yet, `width` at a time. When one fails the others are stopped, and the parts
+ // that finished are kept. A part's log is printed in one piece when it ends, so parallel logs do not interleave.
+ const runAll = async width => {
+ const ctrl = new AbortController(), stop = () => ctrl.abort(signal.reason);
+ signal?.addEventListener('abort', stop);
+ let free = width; const waiting = [];
+ const slot = () => free > 0 ? (free--, Promise.resolve()) : new Promise(r => waiting.push(r));
+ const release = () => waiting.length ? waiting.shift()() : free++;
+ const promises = [];
+ try {
+ for (let j = 0; j < jobs.length; j++) {
+ if (parts[j]) { promises.push(Promise.resolve(parts[j])); continue; }
+ const before = jobs[j].kind === 'transition' ? promises[j - 1] : null;
+ promises.push((async () => {
+ if (before) await before;
+ await slot();
+ const lines = [], out = width > 1 ? l => lines.push(l) : log;
+ try { return parts[j] = await renderJob(j, out, ctrl.signal); }
+ catch (e) { if (!ctrl.signal.aborted) ctrl.abort(e); throw e; }
+ finally { lines.forEach(l => log(l)); release(); }
+ })());
+ }
+ const failed = (await Promise.allSettled(promises)).find(r => r.status === 'rejected');
+ if (failed) throw ctrl.signal.reason ?? failed.reason; // the first failure, not the ones it caused by stopping the rest
+ } finally { signal?.removeEventListener('abort', stop); }
+ };
+ parts[0] = await renderJob(0, log, signal ?? new AbortController().signal);
+ const width = Math.max(1, Math.min(parallel ?? defaultParallel(), jobs.length - 1));
+ if (width > 1) { progress = false; log(`\nRendering ${jobs.length - 1} more parts, ${width} at a time`); }
+ try { await runAll(width); }
+ catch (e) {
+ // Too many Chrome processes for the memory, or more hardware encoder sessions than the GPU allows, show up as a
+ // failed part. The parts still missing are rendered one at a time; a part that fails then fails for real.
+ if (width === 1 || e.final || signal?.aborted) throw e;
+ log(`\nA part failed with ${width} at a time (${String(e?.message || e).split('\n')[0]}). Rendering the remaining parts one at a time.`);
+ progress = true; await runAll(1);
}
const duration = parts.reduce((sum, s) => sum + s.duration, 0);
diff --git a/src/render.js b/src/render.js
index 216fcb9..7f17766 100644
--- a/src/render.js
+++ b/src/render.js
@@ -95,7 +95,8 @@ export async function renderVideo(o) {
const done = ranges.map(() => 0); let lastLine = 0;
pages.forEach((p, i) => p.onEmit(m => {
if (m.type !== 'progress') return; done[i] = m.done;
- if (process.stdout.isTTY && Date.now() - lastLine > 200) { lastLine = Date.now(); process.stdout.write(`\r${done.reduce((a, b) => a + b, 0)}/${frames} frames`); }
+ // o.progress is false when project parts render in parallel, whose frame counts would overwrite each other
+ if (o.progress !== false && process.stdout.isTTY && Date.now() - lastLine > 200) { lastLine = Date.now(); process.stdout.write(`\r${done.reduce((a, b) => a + b, 0)}/${frames} frames`); }
}));
const ext = enc.codec === 'hevc' ? 'h265' : 'h264';
@@ -134,7 +135,7 @@ export async function renderVideo(o) {
log(`\nMediabunny path failed (${why}). Retrying with raw bitstream and ffmpeg.`);
res = await attempt('raw');
}
- if (process.stdout.isTTY) process.stdout.write('\r');
+ if (o.progress !== false && process.stdout.isTTY) process.stdout.write('\r');
rmSync(out, { force: true }); renameSync(part, out);
const v = await probeVideo(out), wantDur = frames / fps;
diff --git a/test/render.test.js b/test/render.test.js
index 29025f6..8d717d1 100644
--- a/test/render.test.js
+++ b/test/render.test.js
@@ -151,6 +151,33 @@ test('project: --only re-renders one scene and the transition touching it, reuse
assert.equal((await probeVideo(join(dir, 'only-cold.mp4'))).frames, 60);
});
+test('project: parts render several at a time in order, and a failing part is tried again one at a time', async () => {
+ const proj = join(dir, 'parallel'), 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);
+ window.renderAt = () => { c.fillStyle = '${colour}'; c.fillRect(0, 0, 320, 180); };</script>`);
+ mkdirSync(proj); flat('a.html', '#000'); flat('b.html', '#fff'); flat('c.html', '#f00'); flat('d.html', '#00f');
+ const fade = { type: 'fade', duration: 0.5, ease: 'linear' };
+ writeFileSync(join(proj, 'project.json'), JSON.stringify({ fps: 30, scenes: ['a.html', { file: 'b.html', transition: fade }, 'c.html', { file: 'd.html', transition: fade }] }));
+ const out = join(dir, 'parallel.mp4'), logs = [];
+ await renderProject({ dir: proj, out, scale: 1, parallel: 3, log: m => logs.push(m) });
+ assert.ok(logs.includes('\nRendering 5 more parts, 3 at a time'), logs.join('\n'));
+ const v = await probeVideo(out);
+ assert.equal(v.frames, 90); // four scenes of 30 frames, two transitions of 15 shared frames
+ const rgb = f => meanRgb(out, '100:100:110:40', f);
+ assert.ok(near(rgb(5), [0, 0, 0], 8), `frame 5 is ${rgb(5)}`);
+ assert.ok(near(rgb(22), [128, 128, 128], 10), `frame 22 is ${rgb(22)}`); // a to b at progress 0.5
+ assert.ok(near(rgb(40), [255, 255, 255], 8), `frame 40 is ${rgb(40)}`);
+ assert.ok(near(rgb(52), [255, 0, 0], 12), `frame 52 is ${rgb(52)}`);
+ assert.ok(near(rgb(67), [128, 0, 128], 12), `frame 67 is ${rgb(67)}`); // c to d at progress 0.5
+ assert.ok(near(rgb(85), [0, 0, 255], 12), `frame 85 is ${rgb(85)}`);
+ // A scene that fails fails again on its own, and that error is the one reported.
+ writeFileSync(join(proj, 'c.html'), '<!doctype html><canvas id="c" width="320" height="180"></canvas><script>window.TOTAL = 1; window.renderAt = () => {}; window.ready = Promise.reject(new Error("c is broken"));</script>');
+ const failLogs = [];
+ await assert.rejects(renderProject({ dir: proj, out: join(dir, 'parallel2.mp4'), scale: 1, parallel: 3, log: m => failLogs.push(m) }), /c is broken/);
+ assert.ok(failLogs.some(l => l.includes('Rendering the remaining parts one at a time')), failLogs.join('\n'));
+ assert.ok(!existsSync(join(dir, 'parallel2.mp4')));
+});
+
test('project: scenes of different sizes stop the render, and a mono file plays at full level on both channels', async () => {
const proj = join(dir, 'proj2'), flat = (name, w, h) => writeFileSync(join(proj, name), `<!doctype html><canvas id="c" width="${w}" height="${h}"></canvas><script>
const c = document.getElementById('c').getContext('2d'); window.TOTAL = 1; window.ready = Promise.resolve(true);