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: address review feedback on --only (#10)
Arya Afendicb9874b91ace
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex c42be2b..cd07a54 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,7 @@ Changes are listed by release, newest first. The sections dated before 0.1.0 rec### Added- 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, and 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.### Changeddiff --git a/ROADMAP.md b/ROADMAP.mdindex f9a7baf..88d29f9 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 only the scenes that changed. Scenes are already separate MP4 parts joined with `-c copy`, so re-rendering one scene and joining again would be cheap. It needs an explicit option such as `--only 7`.- 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.diff --git a/docs/cli.md b/docs/cli.mdindex dd52da2..53ef87d 100644--- a/docs/cli.md+++ b/docs/cli.md@@ -1,7 +1,7 @@# Command line```text-motlab render <project> [out.mp4] [--scale 2] all scenes and audio in project.json, as one MP4+motlab render <project> [out.mp4] [--scale 2] [--only 3] all scenes and audio in project.json, as one MP4motlab start the viewer in the background at http://127.0.0.1:4173, one for all projectsmotlab edit [project] open a project in the viewer, starting it first if neededmotlab 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 only `--scale`; the rest are for `video` (and `--root`, `--chrome`, `--scale` and `--format` for `stills`, and `--root` and `--chrome` for `events`).+`render` takes `--scale` and `--only`; the rest are for `video` (and `--root`, `--chrome`, `--scale` and `--format` for `stills`, and `--root` and `--chrome` for `events`).| Option | Meaning ||---|---|@@ -48,6 +48,7 @@ When the page throws while loading, the error names the file, line and column, f| `--bitrate` | Use variable bitrate at this many Mbit/s instead of constant QP || `--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. Only for `render`, 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` |@@ -59,7 +60,7 @@ When the page throws while loading, the error names the file, line and column, f| Variable | Meaning ||---|---|| `CHROME` | Path to Chrome or Chromium |-| `MOTLAB_CACHE_DIR` | Where the encoder timings are saved. Default `%LOCALAPPDATA%\motlab` on Windows, `~/.cache/motlab` elsewhere |+| `MOTLAB_CACHE_DIR` | Where the encoder timings and the cached scene parts are saved. Default `%LOCALAPPDATA%\motlab` on Windows, `~/.cache/motlab` elsewhere |## Page contractdiff --git a/docs/install.md b/docs/install.mdindex 5fab0c7..1383fed 100644--- a/docs/install.md+++ b/docs/install.md@@ -158,7 +158,7 @@ With `--link`, the skills update with `git pull` alone, but run the installer anmotlab uninstall```-It stops the viewer and removes the launcher (`~/.local/bin/motlab`, and `motlab.cmd` on Windows), the two skill folders in every agent folder they were installed in, `~/.motlab/` (where the installer put things, the viewer's recent projects and its log) and the encoder timings (`%LOCALAPPDATA%\motlab` on Windows, `~/.cache/motlab` elsewhere; with `MOTLAB_CACHE_DIR` only the timings file). It lists everything and asks first; `--yes` skips the question and `--dry-run` only lists. A skill installed with `--link` is removed as a link, and what it points to stays. It leaves the clone, because it runs from there: delete that folder afterwards. From npm there is no launcher to remove, and `npm uninstall -g @motlab/cli` removes the engine and the command afterwards.+It stops the viewer and removes the launcher (`~/.local/bin/motlab`, and `motlab.cmd` on Windows), the two skill folders in every agent folder they were installed in, `~/.motlab/` (where the installer put things, the viewer's recent projects and its log) and the encoder timings and cached scene parts (`%LOCALAPPDATA%\motlab` on Windows, `~/.cache/motlab` elsewhere; with `MOTLAB_CACHE_DIR` only the timings file). It lists everything and asks first; `--yes` skips the question and `--dry-run` only lists. A skill installed with `--link` is removed as a link, and what it points to stays. It leaves the clone, because it runs from there: delete that folder afterwards. From npm there is no launcher to remove, and `npm uninstall -g @motlab/cli` removes the engine and the command afterwards.## Check the machinediff --git a/docs/projects.md b/docs/projects.mdindex e5dbf31..2e099e8 100644--- a/docs/projects.md+++ b/docs/projects.md@@ -64,9 +64,11 @@ motlab render example out/promo.mp4 --scale 1This renders every scene, joins them and adds the audio. The result is `example/out/example.mp4` unless you give a path. The default `--scale 2` turns 1920x1080 pages into 4K; `--scale 1` gives 1080p. The viewer's Export button does the same thing at a resolution you pick.+To change one scene without rendering the rest again, pass `--only` with its number: `motlab render example --only 3`. The scenes you name are rendered again, the transitions touching them too, and every other scene comes from the cache in `~/.cache/motlab/parts` (`%LOCALAPPDATA%\motlab\parts` on Windows, or `MOTLAB_CACHE_DIR`), where a full render leaves each scene's part. A finished render removes the cached parts it did not use. A scene with no cached part is rendered, so `--only` on a project that was never rendered works like a full render. The cache key holds the motlab version and the scene page itself, so if a file the scene loads changes (a shared script, a font, a picture), render the whole project again, or delete the cache folder.+How it works:-- Each scene is rendered to its own MP4, and ffmpeg joins them with `-c copy`.+- Each scene is rendered to its own MP4, and ffmpeg joins them with `-c copy`. A full render also leaves each part in the cache, so `--only` can reuse it later.- 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.diff --git a/skills/motlab/SKILL.md b/skills/motlab/SKILL.mdindex 65d33a8..5205ed7 100644--- a/skills/motlab/SKILL.md+++ b/skills/motlab/SKILL.md@@ -86,7 +86,9 @@ ask; never stash, reset or discard their changes. The new skills load in a new sBefore a round that changes a lot, copy `scenes/` to `backup/<n>/`. Never delete or edit the user's reference files.Many rounds are normal; keep going until the user is happy.9. **The render is the user's.** They press Export in the viewer and pick 720p, 1080p, 1440p or 4K. The file lands in- `<video>/out/<folder>-<resolution>.mp4` (4K as `-2160p`). To look at an export they ask about, tile one frame a+ `<video>/out/<folder>-<resolution>.mp4` (4K as `-2160p`). After fixing one scene, they can re-render just that scene+ from the command line instead of a full export: `motlab render <project> --only N`, where N is the scene's number+ in `project.json`; the rest comes from the cache. To look at an export they ask about, tile one frame asecond into a single image: `ffmpeg -i out.mp4 -vf "fps=1,scale=480:-1,tile=6x10" -frames:v 1 sheet.jpg`.**Paid tools:** generating a voice, music or anything else on a paid service (ElevenLabs, Suno and the like) spends thediff --git a/src/cli.js b/src/cli.jsindex 9157eb8..b4f16f8 100644--- a/src/cli.js+++ b/src/cli.js@@ -11,7 +11,7 @@ import { openInViewer, restartViewer, startViewer, stopViewer } from './viewer.jconst 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] all scenes and audio in project.json, as one MP4+ motlab render <project> [out.mp4] [--scale 2] [--only 3] all scenes and audio in project.json, as one MP4motlab start the viewer in the background at http://127.0.0.1:4173, for everyproject; the menu lists the projects in this foldermotlab edit [project] open a project in the viewer (starting it if needed) and print its@@ -44,6 +44,7 @@ const USAGE = `motlab: render a canvas page (canvas #c, renderAt(t), TOTAL, read--bitrate use variable bitrate at this many Mbit/s instead of constant QP--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)--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)@@ -53,6 +54,14 @@ that pass it keep working). Needs ffmpeg and ffprobe on PATH.Engine folder: ${fileURLToPath(new URL('..', import.meta.url))} (README.md, example/, src/page/footage.js)`;const oneOf = (name, v, list) => { if (v !== undefined && !list.includes(v)) throw new Error(`--${name} must be one of: ${list.join(', ')}`); return v; };+const only = v => {+ if (v === undefined) return undefined;+ return v.split(',').map(s => {+ const n = Number(s.trim());+ if (!Number.isInteger(n) || n < 1) throw new Error(`--only: "${s.trim()}" is not a scene number`);+ return n;+ });+};const num = (name, v, { min = 0, int = false } = {}) => {if (v === undefined) return undefined;const n = Number(v);@@ -69,6 +78,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' },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;@@ -83,7 +93,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 }) });+ await renderProject({ dir: page, out, scale: num('scale', v.scale, { min: 0.01 }), only: only(v.only) });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/probe.js b/src/probe.jsindex cb979f8..15dd4ab 100644--- a/src/probe.js+++ b/src/probe.js@@ -12,9 +12,12 @@ const DEFAULT_QP = { h264: 18, hevc: 20 };export const label = c => `${c.codec === 'hevc' ? 'HEVC' : 'H.264'} ${c.hw ? 'hardware' : 'software'}`;export const rate = c => c.rc === 'quantizer' ? `constant QP ${c.qp}` : `${(c.bitrate / 1e6).toFixed(1)} Mbit/s VBR`;+export function cacheDir() {+ return process.env.MOTLAB_CACHE_DIR || (process.platform === 'win32' && process.env.LOCALAPPDATA ? join(process.env.LOCALAPPDATA, 'motlab') : join(homedir(), '.cache', 'motlab'));+}+export function cacheFile() {- const dir = process.env.MOTLAB_CACHE_DIR || (process.platform === 'win32' && process.env.LOCALAPPDATA ? join(process.env.LOCALAPPDATA, 'motlab') : join(homedir(), '.cache', 'motlab'));- return join(dir, 'encoder-probe.json');+ return join(cacheDir(), 'encoder-probe.json');}const load = () => { try { return JSON.parse(readFileSync(cacheFile(), 'utf8')); } catch { return {}; } };diff --git a/src/project.js b/src/project.jsindex 5e8f275..396e6c7 100644--- a/src/project.js+++ b/src/project.js@@ -5,13 +5,17 @@// overlap and the video is that much shorter. Audio files are mixed at their start time (seconds) and volume (1 = as is).// An audio entry may also be a video file (its sound is used), with optional "from" (seconds into the file) and "duration".import { spawnSync } from 'node:child_process';-import { existsSync, mkdirSync, mkdtempSync, readFileSync, renameSync, rmSync } from 'node:fs';+import { createHash } from 'node:crypto';+import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, renameSync, rmSync, writeFileSync } from 'node:fs';import { tmpdir } from 'node:os';import { basename, dirname, join, resolve } from 'node:path';-import { finalize, run } from './ffmpeg.js';+import { finalize, probeVideo, run } from './ffmpeg.js';import { findTransition, transitionProgress } from './page/transitions.js';+import { cacheDir } from './probe.js';import { renderVideo } from './render.js';+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,// at least 1. The viewer applies the same rule.export function projectScenes(p) {@@ -38,7 +42,14 @@ export function projectPaths(target) {return { root, file, name: stem === 'project' ? basename(root) : `${basename(root)}-${stem.replace(/^project-/, '')}` }; // project-tiktok.json: <folder>-tiktok}-export async function renderProject({ dir, out, scale, log = console.log, signal }) { // signal: an AbortSignal that stops the render+// only: the 1-based scenes to re-render (for example [3], or [3, 5]). The rest come from the cache of scene parts+// in ~/.cache/motlab/parts on macOS and Linux, %LOCALAPPDATA%\motlab\parts on Windows (or MOTLAB_CACHE_DIR),+// which a full render leaves behind; a scene with no cached part is rendered, and the transitions touching a+// re-rendered scene are re-rendered too. The cache key holds the motlab version too, so parts made by an older+// 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 renderconst { 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';@@ -48,22 +59,58 @@ export async function renderProject({ dir, out, scale, log = console.log, signal// A transition is a part of its own between the two scenes: their overlapping frames, mixed by// __motlab/transition.html, and left out of the scenes' own parts.const parts = [], scenes = projectScenes(p), same = () => parts[0] && { encoder: parts[0].hw ? 'hw' : 'sw', codec: parts[0].codec };+ const used = new Set(); // the cache keys this render used, for pruning the ones it did not+ if (only && only.some(n => !Number.isInteger(n) || n < 1 || n > scenes.length))+ throw new Error(`--only takes scene numbers from 1 to ${scenes.length}`);+ const cacheRoot = join(cacheDir(), 'parts', createHash('sha256').update(file).digest('hex').slice(0, 16));+ const hash = f => createHash('sha256').update(readFileSync(join(dir, f))).digest('hex');+ const hashes = scenes.map(s => hash(s.file));+ 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) => {+ used.add(k);+ let suffix = '';+ if (!forced) {+ let m = null;+ try { m = JSON.parse(readFileSync(join(cacheRoot, k + '.json'), 'utf8')); } catch {}+ if (m?.key === k && existsSync(join(cacheRoot, k + '.mp4'))) {+ const v = await probeVideo(join(cacheRoot, k + '.mp4')).catch(() => null);+ if (v && v.frames === m.frames && Math.abs(v.duration - m.duration) <= 0.5 / p.fps && v.width === m.width && v.height === m.height+ && (!parts[0] || (m.hw === parts[0].hw && m.codec === parts[0].codec && m.fullRange === parts[0].fullRange))) {+ log(`${label} (cached)`);+ return { out: join(cacheRoot, k + '.mp4'), width: m.width, height: m.height, duration: m.duration, frames: m.frames, pageFrames: m.pageFrames, fullRange: m.fullRange, codec: m.codec, hw: m.hw };+ }+ }+ suffix = ' (no cached part, rendering it)';+ }+ log(label + suffix);+ const summary = await render();+ try {+ mkdirSync(cacheRoot, { recursive: true });+ writeFileSync(join(cacheRoot, k + '.json'), JSON.stringify({ key: k, codec: summary.codec, hw: summary.hw, fullRange: summary.fullRange,+ width: summary.width, height: summary.height, frames: summary.frames, pageFrames: summary.pageFrames, duration: summary.duration }));+ } 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();- log(`\nScene ${i + 1}/${scenes.length}: ${scene.file}`);- const part = await renderVideo({ page: join(dir, scene.file), root: dir, out: join(tmp, `${parts.length}.mp4`), fps: p.fps, scale, log, signal,- head: into?.n, tail: next?.n, ...same() });+ 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 throughif (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;- log(`\nTransition ${i + 1} to ${i + 2}: ${next.type}, ${next.n} frames`);+ 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,fps: p.fps, type: next.type, ease: next.ease, params: JSON.stringify(next.params) });- parts.push(await renderVideo({ url: '__motlab/transition.html', query: String(query), root: dir, out: join(tmp, `${parts.length}.mp4`),- fps: p.fps, scale, log, signal, ...same() }));+ 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`,+ () => renderVideo({ url: '__motlab/transition.html', query: String(query), root: dir, out: join(cacheRoot, tk + '.mp4'),+ fps: p.fps, scale, log, signal, ...same() })));}const duration = parts.reduce((sum, s) => sum + s.duration, 0);@@ -85,6 +132,14 @@ export async function renderProject({ dir, out, scale, log = console.log, signalif (parts.some(s => s.fullRange !== parts[0].fullRange)) throw new Error('the scenes were encoded with different colour ranges');await finalize({ inputs: parts.map(s => s.out), codec: parts[0].codec, fps: p.fps, audio, out: partial, duration, tmp, signal, fullRange: parts[0].fullRange });rmSync(out, { force: true }); renameSync(partial, out);+ // Parts from earlier edits that this render did not use would pile up: one scene edited three times leaves+ // three versions of its part. A finished render clears out the ones it did not use.+ let pruned = 0;+ try {+ const stale = [...new Set(readdirSync(cacheRoot).map(f => f.match(/^([0-9a-f]{64})\.(mp4|json)$/)?.[1]).filter(Boolean))].filter(k => !used.has(k));+ for (const k of stale) { rmSync(join(cacheRoot, k + '.mp4'), { force: true }); rmSync(join(cacheRoot, k + '.json'), { force: true }); pruned++; }+ } catch {}+ if (pruned) log(`(removed ${pruned} unused cached part${pruned === 1 ? '' : 's'})`);log(`\nSAVED ${out} (${scenes.length} scenes${parts.length > scenes.length ? `, ${parts.length - scenes.length} transitions` : ''}, ${duration.toFixed(3)} s${audio ? `, ${p.audio.length} audio files` : ''})`);} finally { rmSync(partial, { force: true }); rmSync(tmp, { recursive: true, force: true }); }}diff --git a/src/uninstall.js b/src/uninstall.jsindex 905faa9..1dbd594 100644--- a/src/uninstall.js+++ b/src/uninstall.js@@ -33,7 +33,7 @@ function targets() {if (existsSync(STATE)) out.push({ path: STATE, what: 'install record, recent projects, viewer log' });const cache = cacheFile(), cacheDir = dirname(cache);// The default cache folder is motlab's own; a folder from MOTLAB_CACHE_DIR may hold other things, so only the file goes.- if (!process.env.MOTLAB_CACHE_DIR && existsSync(cacheDir)) out.push({ path: cacheDir, what: 'encoder timings' });+ if (!process.env.MOTLAB_CACHE_DIR && existsSync(cacheDir)) out.push({ path: cacheDir, what: 'encoder timings and cached scene parts' });else if (existsSync(cache)) out.push({ path: cache, what: 'encoder timings' });return out;}diff --git a/test/render.test.js b/test/render.test.jsindex 906101d..29025f6 100644--- a/test/render.test.js+++ b/test/render.test.js@@ -1,7 +1,8 @@// End to end: needs Chrome, ffmpeg and ffprobe. Renders the fixture page and checks what came out.import assert from 'node:assert/strict';import { spawnSync } from 'node:child_process';-import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { createHash } from 'node:crypto';+import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from 'node:fs';import { tmpdir } from 'node:os';import { join } from 'node:path';import { after, test } from 'node:test';@@ -113,6 +114,43 @@ test('project: a transition overlaps two scenes and mixes them on the frame gridassert.ok(grey(30) > 248, `frame 30 is ${grey(30)}`);});+test('project: --only re-renders one scene and the transition touching it, reuses the cached rest and prunes the parts it did not use', async () => {+ const proj = join(dir, 'only'), 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');+ writeFileSync(join(proj, 'project.json'), JSON.stringify({ fps: 30, scenes: ['a.html', { file: 'b.html', transition: { type: 'fade', duration: 0.5, ease: 'linear' } }] }));+ await renderProject({ dir: proj, out: join(dir, 'only1.mp4'), scale: 1, ...quiet });+ flat('b.html', '#f00');+ const logs = [];+ await renderProject({ dir: proj, out: join(dir, 'only2.mp4'), scale: 1, only: [2], log: m => logs.push(m) });+ const v = await probeVideo(join(dir, 'only2.mp4'));+ assert.equal(v.frames, 45); // 30 + 30 frames, 15 of them shared+ const seen = logs.join('\n');+ assert.ok(seen.includes('Scene 1/2: a.html (cached)'), seen);+ assert.ok(!seen.includes('Transition 1 to 2: fade, 15 frames (cached)'), seen); // scene 2 changed, so the transition is rendered again+ const red = f => meanRgb(join(dir, 'only2.mp4'), '100:100:110:40', f)[0];+ assert.ok(red(0) < 8, `frame 0 is ${red(0)}`); // scene a, from the cache+ assert.ok(Math.abs(red(22) - 128) < 8, `frame 22 is ${red(22)}`); // the transition, black to red at progress 0.5+ assert.ok(red(40) > 200, `frame 40 is ${red(40)}`); // scene b, re-rendered red+ // the old scene b and transition parts are gone, not left behind+ const partsDir = join(dir, 'cache', 'parts', createHash('sha256').update(join(proj, 'project.json')).digest('hex').slice(0, 16));+ assert.equal(readdirSync(partsDir).filter(f => f.endsWith('.mp4')).length, 3); // scene a, scene b, the transition+ // --only on a project with no cached parts renders everything, and a scene number outside the project stops it+ await assert.rejects(renderProject({ dir: proj, out: join(dir, 'only3.mp4'), scale: 1, only: [3], ...quiet }), /--only takes scene numbers from 1 to 2/);+ const cold = join(dir, 'only-cold');+ mkdirSync(cold);+ const cflat = (name, colour) => writeFileSync(join(cold, 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>`);+ cflat('a.html', '#000'); cflat('b.html', '#fff');+ writeFileSync(join(cold, 'project.json'), JSON.stringify({ fps: 30, scenes: ['a.html', 'b.html'] }));+ const coldLogs = [];+ await renderProject({ dir: cold, out: join(dir, 'only-cold.mp4'), scale: 1, only: [2], log: m => coldLogs.push(m) });+ assert.ok(coldLogs.join('\n').includes('Scene 1/2: a.html (no cached part, rendering it)'), coldLogs.join('\n'));+ assert.equal((await probeVideo(join(dir, 'only-cold.mp4'))).frames, 60);+});+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);