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.

Transitions: a .glsl file in the project as a scene transition (#13)

Stanyslaus Hary5ae457c68e5b
diff --git a/CHANGELOG.md b/CHANGELOG.md
index e5fbc0e..1aec8e3 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
- `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.
+- A scene transition can come from a `.glsl` file in the project, as `"type": "transitions/swipe.glsl"`. The file is a gl-transitions shader: `vec4 transition(vec2 uv)` with `getFromColor`, `getToColor`, `progress` and `ratio`. Its uniforms (float, int, bool, vec2 to vec4, ivec2 to ivec4) take their defaults from the comment after them, as gl-transitions writes them, and `params` sets them. The viewer and the render compile the file before the first frame and report a mistake with its line in the file. The file's contents are in the cache key, so `--only` renders an edited transition again. The skill's motion reference says how to write one, and how to match a transition from a reference video by laying frames from both on contact sheets. Checked: the 11 built-in shaders parse back to the uniforms and defaults listed with them; `test/render.test.js` renders a project with a shader file at its defaults and with `params`, and checks that a mistake on line 3 is reported on line 3; the wipe from the docs looked the same in the viewer and in a 1080p render, and the viewer showed a compile error with its line. Not tried: shaders copied from gl-transitions beyond the 11 built in, and matching a real reference video.
- 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 dab7e34..0e273f4 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, 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.
+`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, with a transition from a `.glsl` file 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, transition names and how a `.glsl` transition's uniforms are read, `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 2622712..11269eb 100644
--- a/ROADMAP.md
+++ b/ROADMAP.md
@@ -6,7 +6,7 @@ What is not built, what has not been tested, and ideas that came up while using
- Alpha output (ProRes 4444).
- 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 transition as a layer over the cut (a swish of shapes) in `project.json`. It exists as the asset skill's `transition.js`, but each of the two scene pages has to draw its half by hand. Shader transitions from a `.glsl` file in the project are built.
- 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.
- A dark mode for the viewer. Its colours are written into the CSS and the timeline's canvas code, so they need to become tokens with dark values checked for contrast first.
@@ -21,6 +21,7 @@ What is not built, what has not been tested, and ideas that came up while using
- 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.
- Scene transitions between scenes of different sizes in the viewer, and in a normal Chrome window. The render refuses scenes of different sizes.
- The cut voice from `cut_pauses.py` on a real person's take. The whole-take test used Windows text to speech.
+- A `.glsl` transition copied from gl-transitions beyond the 11 built in, and one matched to a real reference video by the skill.
- Rive, Lottie text layers exported with glyphs, Theatre.js state exported from its studio, and the studio inside the viewer.
- p5.js `loadFont` and p5 add-on libraries.
- The asset skill (`motlab-assets`) on a real brief and a kit used in a real video. Its scripts were run on a test kit: an SVG character with a rig, a transition, a mug on both 3D paths and a Rigify figure.
diff --git a/docs/projects.md b/docs/projects.md
index db9652e..ad4aed2 100644
--- a/docs/projects.md
+++ b/docs/projects.md
@@ -91,6 +91,30 @@ Frame `k` of an `n`-frame transition shows frame `TOTAL * fps - n + k` of the sc
`type` is one of 11 shaders from [gl-transitions](https://github.com/gl-transitions/gl-transitions) 1.43.0, all MIT, copied into `src/page/transitions.js` with their authors: `fade`, `fadecolor`, `Directional`, `directionalwipe`, `directionalwarp`, `circleopen`, `CrossZoom`, `crosswarp`, `SimpleZoom`, `LinearBlur` and `cube`. `params` overrides their uniforms (for example `{ "direction": [1, 0] }`), and `ease` is a name from `motion.js`. An unknown type or ease stops the render and the viewer with the list of valid names.
+### A transition of your own
+
+`type` can also be a path to a `.glsl` file in the project folder:
+
+```json
+{ "file": "scenes/02.html", "transition": { "type": "transitions/swipe.glsl", "duration": 0.6, "params": { "softness": 0.1 } } }
+```
+
+The file is written like a gl-transitions shader. It defines `vec4 transition(vec2 uv)`, reads the two scenes with `getFromColor(uv)` and `getToColor(uv)`, and may use `progress` (0 to 1, after `ease`) and `ratio` (width divided by height), which motlab sets:
+
+```glsl
+// a soft-edged wipe from left to right
+uniform float softness; // = 0.05
+
+vec4 transition(vec2 uv) {
+ float edge = progress * (1.0 + softness);
+ return mix(getToColor(uv), getFromColor(uv), smoothstep(edge - softness, edge, uv.x));
+}
+```
+
+Each uniform the file declares can be set from `params`. A float, int, bool, vec2 to vec4 or ivec2 to ivec4 works; a texture (`sampler2D`) does not. A comment right after the declaration gives the default, as gl-transitions writes it: `// = 0.05`, `// = vec2(1.0, 0.0)`, `// = true` or `/* = 0.4 */` before the semicolon. A uniform with no default and no param is 0. Do not declare `progress` or `ratio`. A shader from gl-transitions that uses no texture can be copied in unchanged; keep its author and licence lines at the top.
+
+The viewer and the render compile the file before the first frame, so a mistake stops both with the compiler's message, for example `transition transitions/swipe.glsl: ERROR: 0:6: 'edg' : undeclared identifier`, where 6 is the line in the file. The file's contents are part of the cache key, so after editing it, `--only` renders that transition again.
+
The render draws a transition with `__motlab/transition.html`, a page that loads both scene pages in iframes and mixes their canvases with WebGL2. The viewer mixes the same two canvases with the same code. On the example project with a `crosswarp` and a `cube` transition, a transition frame in the viewer and in the 1080p MP4 differed by 1.37 levels of 255 on average, with 0.2% of values more than 8 apart, at the edges, from the H.264 compression.
Tested: the example's scenes with two transitions (7.6 s, 228 frames, the frame count and length expected), a 1080x1920 project of two footage scenes joined by `directionalwarp`, and `test/render.test.js`, which checks that a 15-frame linear fade from black to white is at mid grey on its eighth frame. A 12-scene project with all 11 types, one into each scene, gave 555 frames and 18.5 s as expected, and every scene showed its own colour and clock in the middle of its plain stretch. It took 57 s at 1080p, mostly from starting Chrome for 23 parts. Not tested: a transition between scenes of different sizes in the viewer, where the new scene is stretched to the size of the one before (the render refuses such a project).
diff --git a/skills/motlab/SKILL.md b/skills/motlab/SKILL.md
index e8e1b8e..dacd4c7 100644
--- a/skills/motlab/SKILL.md
+++ b/skills/motlab/SKILL.md
@@ -135,7 +135,8 @@ promo/
- A scene can instead be `{ "file": "scenes/02.html", "transition": { "type": "crosswarp", "duration": 0.5 } }`: the
scene before turns into it through a shader, and the two overlap for that long, so it starts that much earlier and
the video is that much shorter. Use these for edits, explainers and talking heads; in an ad, a shape that carries
- across the cut (`craft.md`) is still better. The types and options are in `references/motion-and-libraries.md`.
+ across the cut (`craft.md`) is still better. The types and options are in `references/motion-and-libraries.md`,
+ with how to write a `.glsl` transition of your own into the project and how to match one from a reference video.
- `audio` is mixed by ffmpeg. `start` is seconds from the start of the whole video, `volume` a multiplier, `from` and
`duration` pick a part of the file. A video file listed here contributes its sound.
- `window.EVENTS` times are per scene. To place a sound on a beat, add the scene's start (the `TOTAL`s before it,
diff --git a/skills/motlab/references/motion-and-libraries.md b/skills/motlab/references/motion-and-libraries.md
index 2607173..93ca662 100644
--- a/skills/motlab/references/motion-and-libraries.md
+++ b/skills/motlab/references/motion-and-libraries.md
@@ -55,6 +55,39 @@ transitions in `craft.md` that carry a shape across the cut; these are for edits
a designed morph is not worth building for every cut. A shader transition between two scenes that already morph into
each other only blurs the morph.
+### A transition of your own, or one from a reference
+
+When none of the 11 fits, write the shader into the project, for example `transitions/swipe.glsl`, and set
+`"type": "transitions/swipe.glsl"`. It is a gl-transitions shader: define `vec4 transition(vec2 uv)`, read the scenes
+with `getFromColor(uv)` and `getToColor(uv)`, use `progress` (0 to 1, eased) and `ratio` (width / height), and give
+each uniform its default in a comment so `params` can change it:
+
+```glsl
+uniform float softness; // = 0.05
+vec4 transition(vec2 uv) {
+ float edge = progress * (1.0 + softness);
+ return mix(getToColor(uv), getFromColor(uv), smoothstep(edge - softness, edge, uv.x));
+}
+```
+
+Uniforms can be float, int, bool, vec2 to vec4 or ivec2 to ivec4, not textures; do not declare `progress` or
+`ratio`. A shader from gl-transitions (github.com/gl-transitions/gl-transitions, all MIT) that uses no texture can be
+copied in unchanged: keep its author and licence lines. The viewer shows a compile error with the line in the file when the project opens.
+
+When the user shows a transition they like in another video, do not guess it from a description. Take frames across
+it, about ten over the transition, named by their time so `contact_sheet.py` can lay them out:
+
+```bash
+for t in 3.20 3.25 3.30 3.35 3.40 3.45 3.50 3.55 3.60 3.65; do ffmpeg -v error -y -ss $t -i reference.mp4 -frames:v 1 ref/$t.png; done
+python3 scripts/contact_sheet.py ref ref-sheet.jpg
+```
+
+Look at the sheet and write down what happens frame by frame: where the new scene first appears, the shape and
+softness of the edge, its direction and speed (constant, or fast in the middle, which is the `ease`), and anything on
+top such as blur, zoom, a colour flash or light. Build the shader from that, render the project, take frames from the
+same stretch of your MP4 the same way, and compare the two sheets side by side. Change the shader or `ease` until the
+moments match, then tell the user what still differs. Copy the movement, not the other video's pictures.
+
## Animation libraries
These were each checked with a box moving from x 100 to 1700 over 2 s: stills at 0.5, 1 and 1.5 s were identical
diff --git a/src/editor.html b/src/editor.html
index 0fe400d..f3a8873 100644
--- a/src/editor.html
+++ b/src/editor.html
@@ -642,18 +642,25 @@ try {
let shown = null, rendering = [];
// A scene is a path, or { file, transition } where the transition turns the scene before into this one. Its length
// in frames (n) follows the renderer's rule in src/project.js.
- const { createMixer, findTransition, transitionProgress } = await import('/__motlab/transitions.js');
- const scenes = project.scenes.map((x, i) => {
+ // A transition from a .glsl file in the project is read and compiled here, so a mistake in it shows on opening.
+ const { createMixer, isTransitionFile, loadTransition, transitionProgress } = await import('/__motlab/transitions.js');
+ const readText = async path => { const r = await fetch(path); if (!r.ok) throw new Error(`${path} did not load (HTTP ${r.status})`); return r.text(); };
+ let mixer = null;
+ const scenes = await Promise.all(project.scenes.map(async (x, i) => {
const s = typeof x === 'string' ? { file: x } : { file: x.file, transition: x.transition };
if (!s.file) throw hint(L('noFile', i + 1));
if (s.transition) {
if (!i) throw hint(L('firstTransition'));
- try { s.transition = { ease: 'inOutCubic', params: {}, ...s.transition, type: findTransition(s.transition.type).name, n: Math.max(1, Math.round((Number(s.transition.duration) || 0) * fps)) }; transitionProgress(0, 1, s.transition.ease); }
+ try {
+ const def = await loadTransition(s.transition.type, readText);
+ s.transition = { ease: 'inOutCubic', params: {}, ...s.transition, type: def.name, def, n: Math.max(1, Math.round((Number(s.transition.duration) || 0) * fps)) };
+ transitionProgress(0, 1, s.transition.ease);
+ if (isTransitionFile(def.name)) (mixer ??= createMixer()).check(def);
+ }
catch (e) { throw hint(L('badTransition', i + 1, e.message)); }
}
return s;
- });
- let mixer = null;
+ }));
function unload(s) { s.frame.remove(); s.frame = s.win = s.canvas = s.warm = null; live.splice(live.indexOf(s), 1); }
function load(s) {
if (s.win) { live.push(...live.splice(live.indexOf(s), 1)); return s; }
@@ -920,7 +927,7 @@ try {
const tr = s.transition, a = pair.from;
await a.win.renderAt(frameIn(a, at) / fps); await s.win.renderAt(frame / fps);
mixer ??= createMixer();
- c.drawImage(mixer.draw(tr.type, a.canvas, s.canvas, transitionProgress(pair.k, pair.n, tr.ease), tr.params), 0, 0, clean.width, clean.height);
+ c.drawImage(mixer.draw(tr.def, a.canvas, s.canvas, transitionProgress(pair.k, pair.n, tr.ease), tr.params), 0, 0, clean.width, clean.height);
} else {
await s.win.renderAt(frame / fps);
c.drawImage(s.canvas, 0, 0, clean.width, clean.height);
diff --git a/src/page/transition.html b/src/page/transition.html
index 7276165..4d7ae7c 100644
--- a/src/page/transition.html
+++ b/src/page/transition.html
@@ -5,12 +5,18 @@
// The frames where one scene turns into the next, rendered like any scene page (served at /__motlab/transition.html).
// Both scene pages are loaded in iframes. Frame k shows frame (offset * fps + k) of `from` and frame k of `to`,
// mixed by src/page/transitions.js, the same code the viewer uses.
-// Query: from, to (page paths from the served root), offset (seconds into `from`), frames, fps, type, ease, params (JSON), scale.
-import { createMixer, findTransition, transitionProgress } from '/__motlab/transitions.js';
+// Query: from, to (page paths from the served root), offset (seconds into `from`), frames, fps, type (a built-in name or
+// a .glsl path from the served root), ease, params (JSON), scale.
+import { createMixer, loadTransition, transitionProgress } from '/__motlab/transitions.js';
const q = new URLSearchParams(location.search), fps = +q.get('fps'), n = +q.get('frames'), offset = +q.get('offset');
const type = q.get('type'), easing = q.get('ease') || 'inOutCubic', params = JSON.parse(q.get('params') || '{}'), scale = q.get('scale') || '1';
const cv = document.getElementById('c'), ctx = cv.getContext('2d');
-let A, B, mix;
+let A, B, mix, def;
+const readText = async path => {
+ const r = await fetch('/' + path.split('/').map(encodeURIComponent).join('/'));
+ if (!r.ok) throw new Error(`transition ${path} did not load (HTTP ${r.status})`);
+ return r.text();
+};
const open = path => new Promise((ok, fail) => {
const f = document.createElement('iframe'); f.src = `/${path}?scale=${scale}`;
@@ -27,15 +33,15 @@ const open = path => new Promise((ok, fail) => {
window.TOTAL = n / fps;
window.ready = (async () => {
- findTransition(type); transitionProgress(0, n, easing); // a wrong name fails here, before any frame
+ def = await loadTransition(type, readText); transitionProgress(0, n, easing); // a wrong name fails here, before any frame
[A, B] = await Promise.all([open(q.get('from')), open(q.get('to'))]);
- cv.width = A.c.width; cv.height = A.c.height; mix = createMixer();
+ cv.width = A.c.width; cv.height = A.c.height; mix = createMixer(); mix.check(def);
return true;
})();
window.renderAt = async t => {
await window.ready;
const k = Math.min(n - 1, Math.max(0, Math.round(t * fps)));
await A.w.renderAt(offset + k / fps); await B.w.renderAt(k / fps);
- ctx.drawImage(mix.draw(type, A.c, B.c, transitionProgress(k, n, easing), params), 0, 0, cv.width, cv.height);
+ ctx.drawImage(mix.draw(def, A.c, B.c, transitionProgress(k, n, easing), params), 0, 0, cv.width, cv.height);
};
</script></body></html>
diff --git a/src/page/transitions.js b/src/page/transitions.js
index e79adf3..aa6c8ce 100644
--- a/src/page/transitions.js
+++ b/src/page/transitions.js
@@ -34,10 +34,39 @@ export const TRANSITIONS = {
export const transitionNames = Object.keys(TRANSITIONS);
export const findTransition = name => {
const key = transitionNames.find(k => k.toLowerCase() === String(name).toLowerCase());
- if (!key) throw new Error(`unknown transition "${name}"; use one of: ${transitionNames.join(', ')}`);
+ if (!key) throw new Error(`unknown transition "${name}"; use one of: ${transitionNames.join(', ')}, or a path to a .glsl file in the project`);
return { name: key, ...TRANSITIONS[key] };
};
+// A transition of the project's own: a .glsl file in the project folder, written like a gl-transitions shader. It
+// defines vec4 transition(vec2 uv) and may call getFromColor(uv), getToColor(uv) and read progress (0 to 1) and ratio
+// (width / height). Each uniform it declares can be set from "params", and a comment after it gives its default, as
+// in gl-transitions: uniform float amount; // = 0.5 or uniform vec2 direction; // = vec2(1.0, 0.0)
+export const isTransitionFile = type => /\.glsl$/i.test(String(type));
+const UNIFORM = /uniform\s+(\w+)\s+(\w+)\s*(?:\/\*\s*=\s*(.*?)\s*\*\/)?\s*;(?:[ \t]*\/\/\s*=\s*([^\n]*))?/g;
+const SIZES = { float: 1, int: 1, bool: 1, vec2: 2, vec3: 3, vec4: 4, ivec2: 2, ivec3: 3, ivec4: 4 };
+export function parseTransition(glsl, name) {
+ const types = {}, defaults = {};
+ if (!/vec4\s+transition\s*\(/.test(glsl)) throw new Error(`transition ${name} has no vec4 transition(vec2 uv) function`);
+ for (const [, type, key, inline, comment] of String(glsl).replace(/^\s*\/\/.*$/gm, '').matchAll(UNIFORM)) {
+ if (key === 'progress' || key === 'ratio') throw new Error(`transition ${name} declares the uniform ${key}, which motlab sets itself; remove that line`);
+ if (!SIZES[type]) throw new Error(`transition ${name}: the uniform ${key} is a ${type}; a project transition can use float, int, bool, vec2 to vec4 and ivec2 to ivec4`);
+ types[key] = type;
+ const v = (inline ?? comment ?? '').match(/^(true|false|[-+.\d][-+.\deE]*|\w+\s*\([^)]*\))/)?.[1];
+ if (v === undefined) continue;
+ if (type === 'bool') { defaults[key] = v === 'true'; continue; }
+ const nums = (/\(([^)]*)\)/.exec(v)?.[1] ?? v).split(',').map(Number);
+ if (nums.some(n => Number.isNaN(n))) continue;
+ defaults[key] = SIZES[type] === 1 ? nums[0] : nums.length === 1 ? Array(SIZES[type]).fill(nums[0]) : nums;
+ }
+ return { name, glsl, types, defaults, file: true };
+}
+
+// A built-in name, or a .glsl path read with readText(path) (fetch in a page, readFileSync in Node).
+export async function loadTransition(type, readText) {
+ return isTransitionFile(type) ? parseTransition(await readText(type), type) : findTransition(type);
+}
+
// Frame k of a transition that lasts n frames. The middle of each frame, so neither the first nor the last frame is
// a plain copy of one scene. Easing names are the ones in motion.js (default inOutCubic).
export function transitionProgress(k, n, easing = 'inOutCubic') {
@@ -51,6 +80,7 @@ const frag = glsl => `precision highp float;
varying vec2 vUv; uniform sampler2D uFrom, uTo; uniform float progress, ratio;
vec4 getFromColor(vec2 uv) { return texture2D(uFrom, uv); }
vec4 getToColor(vec2 uv) { return texture2D(uTo, uv); }
+#line 1
${glsl}
void main() { gl_FragColor = transition(vUv); }`;
@@ -76,9 +106,12 @@ export function createMixer() {
}
init();
- function program(name) {
- if (programs.has(name)) return programs.get(name);
- const t = findTransition(name), p = gl.createProgram();
+ // t: a built-in name, or what loadTransition() returned
+ function program(t) {
+ const id = typeof t === 'string' ? t.toLowerCase() : t.name;
+ if (programs.has(id)) return programs.get(id);
+ if (typeof t === 'string') t = findTransition(t);
+ const p = gl.createProgram();
for (const [type, src] of [[gl.VERTEX_SHADER, VERT], [gl.FRAGMENT_SHADER, frag(t.glsl)]]) {
const s = gl.createShader(type); gl.shaderSource(s, src); gl.compileShader(s);
if (!gl.getShaderParameter(s, gl.COMPILE_STATUS)) throw new Error(`transition ${t.name}: ${gl.getShaderInfoLog(s)}`);
@@ -87,7 +120,7 @@ export function createMixer() {
gl.bindAttribLocation(p, 0, 'p'); gl.linkProgram(p);
if (!gl.getProgramParameter(p, gl.LINK_STATUS)) throw new Error(`transition ${t.name}: ${gl.getProgramInfoLog(p)}`);
const entry = { p, t, u: n => gl.getUniformLocation(p, n) };
- programs.set(name, entry); return entry;
+ programs.set(id, entry); return entry;
}
function drawOnce(name, from, to, progress, params) {
@@ -102,6 +135,7 @@ export function createMixer() {
if (loc === null || v === undefined) continue;
if (type === 'float') gl.uniform1f(loc, v);
else if (type === 'bool' || type === 'int') gl.uniform1i(loc, Number(v));
+ else if (type.startsWith('ivec')) gl[`uniform${type.slice(4)}iv`](loc, v.map(Math.round)); // ivec2, ivec3, ivec4
else gl[`uniform${type.slice(3)}fv`](loc, v); // vec2, vec3, vec4
}
gl.enableVertexAttribArray(0); gl.vertexAttribPointer(0, 2, gl.FLOAT, false, 0, 0);
@@ -111,7 +145,10 @@ export function createMixer() {
return {
get canvas() { return cv; },
- // A context lost mid-frame throws from a compile or draws nothing, so both are checked; a second loss is reported.
+ // Compiles a transition without drawing, so a mistake in a project's .glsl file shows before the first frame.
+ check(t) { program(t); },
+ // name: a built-in name or a loaded transition. A context lost mid-frame throws from a compile or draws nothing,
+ // so both are checked; a second loss is reported.
draw(name, from, to, progress, params = {}) {
for (let tries = 0; tries < 2; tries++) {
try { const out = drawOnce(name, from, to, progress, params); if (!gl.isContextLost()) return out; }
diff --git a/src/project.js b/src/project.js
index 4238678..1eb387a 100644
--- a/src/project.js
+++ b/src/project.js
@@ -10,7 +10,7 @@ import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, renameSy
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 { findTransition, isTransitionFile, parseTransition, transitionProgress } from './page/transitions.js';
import { cacheDir } from './probe.js';
import { renderVideo } from './render.js';
@@ -22,8 +22,8 @@ export const defaultParallel = () => Math.max(1, Math.min(3, Math.floor(availabl
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) {
+// at least 1. The viewer applies the same rule. root: the project folder, where a transition's .glsl file is checked.
+export function projectScenes(p, root) {
return p.scenes.map((s, i) => {
const scene = typeof s === 'string' ? { file: s } : { ...s };
if (!scene.file) throw new Error(`scene ${i + 1} has no "file"`);
@@ -31,7 +31,14 @@ export function projectScenes(p) {
if (tr && i === 0) throw new Error(`scene 1 (${scene.file}) has a transition, but there is no scene before it`);
if (tr) {
scene.transition = { ease: 'inOutCubic', params: {}, ...tr, n: Math.max(1, Math.round((Number(tr.duration) || 0) * p.fps)) };
- try { scene.transition.type = findTransition(tr.type).name; transitionProgress(0, 1, scene.transition.ease); }
+ try {
+ if (!isTransitionFile(tr.type)) scene.transition.type = findTransition(tr.type).name;
+ else if (root) { // its uniforms are read here; a GLSL mistake shows when Chrome compiles it, before the first frame
+ if (!existsSync(join(root, tr.type))) throw new Error(`the transition file ${tr.type} does not exist`);
+ parseTransition(readFileSync(join(root, tr.type), 'utf8'), tr.type);
+ }
+ transitionProgress(0, 1, scene.transition.ease);
+ }
catch (e) { throw new Error(`scene ${i + 1} (${scene.file}): ${e.message}`); }
}
return scene;
@@ -63,7 +70,7 @@ export async function renderProject({ dir, out, scale, only, parallel, log = con
// can be joined without re-encoding.
// 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 parts = [], scenes = projectScenes(p, dir), 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}`);
@@ -117,7 +124,7 @@ export async function renderProject({ dir, out, scale, only, parallel, log = con
}
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 });
+ type: next.type, glsl: isTransitionFile(next.type) ? hash(next.type) : undefined, 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: (from.pageFrames - next.n) / p.fps, frames: next.n,
fps: p.fps, type: next.type, ease: next.ease, params: JSON.stringify(next.params) });
return getPart(tk, !only || only.includes(i + 1) || only.includes(i + 2), `\nTransition ${i + 1} to ${i + 2}: ${next.type}, ${next.n} frames`, log,
diff --git a/test/motion.test.js b/test/motion.test.js
index 0d197db..da9d259 100644
--- a/test/motion.test.js
+++ b/test/motion.test.js
@@ -1,7 +1,10 @@
import assert from 'node:assert/strict';
import { test } from 'node:test';
import { cubicBezier, ease, spring, stagger, tween } from '../src/page/motion.js';
-import { findTransition, transitionNames, transitionProgress } from '../src/page/transitions.js';
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { findTransition, isTransitionFile, parseTransition, transitionNames, transitionProgress } from '../src/page/transitions.js';
import { projectScenes } from '../src/project.js';
const near = (a, b, d = 1e-3) => assert.ok(Math.abs(a - b) <= d, `${a} is not within ${d} of ${b}`);
@@ -56,3 +59,35 @@ test('project scenes accept paths and objects with transitions', () => {
assert.throws(() => projectScenes({ fps: 30, scenes: [{ file: 'a.html', transition: { type: 'fade', duration: 1 } }] }), /no scene before it/);
assert.throws(() => projectScenes({ fps: 30, scenes: ['a.html', { file: 'b.html', transition: { type: 'zap', duration: 1 } }] }), /scene 2 .*unknown transition/);
});
+
+test('a .glsl transition file: its uniforms and their defaults are read as gl-transitions writes them', () => {
+ // the built-in shaders come back with the types and defaults listed next to them
+ for (const name of transitionNames) {
+ const t = findTransition(name), parsed = parseTransition(t.glsl, name);
+ assert.deepEqual([parsed.types, parsed.defaults], [t.types, t.defaults], name);
+ }
+ const t = parseTransition(`uniform float amount; // = 0.25
+uniform vec3 tint;// = vec3(1.0)
+uniform float soft/* = 0.4 */; // a note after the default
+uniform bool flip; // = true
+uniform int steps; // = 6
+uniform vec2 dir;
+uniform ivec2 grid; // = ivec2(4)
+// uniform float old; // = 9.0
+vec4 transition(vec2 uv) { return mix(getFromColor(uv), getToColor(uv), progress * amount); }`, 'mine.glsl');
+ assert.deepEqual(t.types, { amount: 'float', tint: 'vec3', soft: 'float', flip: 'bool', steps: 'int', dir: 'vec2', grid: 'ivec2' });
+ assert.deepEqual(t.defaults, { amount: 0.25, tint: [1, 1, 1], soft: 0.4, flip: true, steps: 6, grid: [4, 4] });
+ assert.throws(() => parseTransition('vec4 main2(vec2 uv) { return vec4(1.0); }', 'x.glsl'), /no vec4 transition/);
+ assert.throws(() => parseTransition('uniform sampler2D map;\nvec4 transition(vec2 uv) { return vec4(1.0); }', 'x.glsl'), /map is a sampler2D/);
+ assert.throws(() => parseTransition('uniform float progress;\nvec4 transition(vec2 uv) { return vec4(1.0); }', 'x.glsl'), /progress, which motlab sets/);
+ assert.ok(isTransitionFile('transitions/Swirl.GLSL') && !isTransitionFile('fade'));
+ // projectScenes keeps the path as the type and checks the file when it knows the project folder
+ const dir = mkdtempSync(join(tmpdir(), 'motlab-glsl-'));
+ try {
+ mkdirSync(join(dir, 't')); writeFileSync(join(dir, 't', 'mine.glsl'), 'vec4 transition(vec2 uv) { return getToColor(uv); }');
+ const p = { fps: 30, scenes: ['a.html', { file: 'b.html', transition: { type: 't/mine.glsl', duration: 0.5 } }] };
+ assert.equal(projectScenes(p, dir)[1].transition.type, 't/mine.glsl');
+ p.scenes[1].transition.type = 't/gone.glsl';
+ assert.throws(() => projectScenes(p, dir), /scene 2 .*t\/gone\.glsl does not exist/);
+ } finally { rmSync(dir, { recursive: true, force: true }); }
+});
diff --git a/test/render.test.js b/test/render.test.js
index 8d717d1..b35f8fa 100644
--- a/test/render.test.js
+++ b/test/render.test.js
@@ -114,6 +114,32 @@ test('project: a transition overlaps two scenes and mixes them on the frame grid
assert.ok(grey(30) > 248, `frame 30 is ${grey(30)}`);
});
+test('project: a transition from a .glsl file in the project, with params over its defaults, and its compile errors', async () => {
+ const proj = join(dir, 'glsl'), 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(join(proj, 'transitions'), { recursive: true }); flat('a.html', '#000'); flat('b.html', '#fff');
+ // a fixed mix of the two scenes, the same on every frame, so the level shows which value the shader got
+ writeFileSync(join(proj, 'transitions', 'hold.glsl'), `// a test transition
+uniform float level; // = 0.25
+uniform ivec2 grid; // = ivec2(2, 3)
+vec4 transition(vec2 uv) { return mix(getFromColor(uv), getToColor(uv), grid.x == 2 && grid.y == 3 ? level : 0.0); }
+`);
+ const write = transition => writeFileSync(join(proj, 'project.json'), JSON.stringify({ fps: 30, scenes: ['a.html', { file: 'b.html', transition }] }));
+ const grey = (file, f) => meanRgb(file, '100:100:110:40', f)[0];
+ write({ type: 'transitions/hold.glsl', duration: 0.5 });
+ await renderProject({ dir: proj, out: join(dir, 'glsl1.mp4'), scale: 1, ...quiet });
+ assert.equal((await probeVideo(join(dir, 'glsl1.mp4'))).frames, 45);
+ assert.ok(Math.abs(grey(join(dir, 'glsl1.mp4'), 18) - 64) < 8, `the default 0.25 gave ${grey(join(dir, 'glsl1.mp4'), 18)}`);
+ write({ type: 'transitions/hold.glsl', duration: 0.5, params: { level: 0.75 } });
+ await renderProject({ dir: proj, out: join(dir, 'glsl2.mp4'), scale: 1, ...quiet });
+ assert.ok(Math.abs(grey(join(dir, 'glsl2.mp4'), 18) - 191) < 8, `params 0.75 gave ${grey(join(dir, 'glsl2.mp4'), 18)}`);
+ // a mistake on line 3 of the file is reported on line 3, with the file's name
+ writeFileSync(join(proj, 'transitions', 'bad.glsl'), 'uniform float level; // = 0.5\nvec4 transition(vec2 uv) {\n return mix(getFromColor(uv), getToColor(uv), lvl);\n}\n');
+ write({ type: 'transitions/bad.glsl', duration: 0.5 });
+ await assert.rejects(renderProject({ dir: proj, out: join(dir, 'glsl3.mp4'), scale: 1, ...quiet }), /transitions\/bad\.glsl: ERROR: 0:3: 'lvl'/);
+});
+
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);