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.

Roadmap: viewer on a domain, layer transitions, file size, earshot in doctor, 4K stills fix (#15)

Stanyslaus Hary4e521927d5e0
diff --git a/AGENTS.md b/AGENTS.md
index a42ce85..f571823 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -29,4 +29,4 @@ For viewer changes, start `motlab edit example`, check the change in a browser a
## Installing motlab for a user
-Follow [docs/install-for-agents.md](docs/install-for-agents.md).
+Follow [docs/install-for-agents.md](docs/install-for-agents.md). Its step 6 puts the viewer on the user's VPS behind a domain and a password, when they ask for that.
diff --git a/CHANGELOG.md b/CHANGELOG.md
index dcc60dd..81ff611 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -6,14 +6,25 @@ Changes are listed by release, newest first. The sections dated before 0.1.0 rec
### Added
+- `motlab help` prints the list of commands, like `motlab --help` and `-h`. Before, it stopped with "unknown mode". `test/cli.test.js` checks all three and that a wrong command still fails.
+- Steps for an agent that puts the viewer on the user's VPS (docs/install-for-agents.md, step 6): the domain and its DNS, a password the user writes into a file only they can read, Caddy, which ports to open and which not, a systemd user service (in docs/viewer.md) and how to check it. The skill and AGENTS.md point to them. Not run on a real VPS yet.
+- `motlab doctor` shows whether earshot is there, the optional tool the skill uses to listen to sound. It is `ok` when the CLI and its models are there, and `warn` with what to do when the CLI is missing or its models (about 1.1 GB) are not downloaded. It never makes the doctor fail, and motlab never installs it. The check runs `earshot doctor`, which took 0.9 s on the test laptop and loads no models. Checked with earshot 0.4.1 there, and `test/doctor.test.js` covers the missing, no-models and ready cases with faked output. Not tried: a machine where earshot is installed but its models are not downloaded.
+- `"qp"` and `"codec"` in `project.json`, and `--qp` and `--codec` on `motlab render`, set the file size against quality for a project, and the viewer's Export uses them too. Before, only `motlab video` took them. `"qp": 22` made an 8 s 4K render of a busy page 30% smaller (12.49 to 8.68 MB) with SSIM 0.9964 to 0.9960 and VMAF unchanged at 99.98. docs/rendering.md has a File size section with the measurements: HEVC, a second ffmpeg pass (NVENC HEVC, x264, SVT-AV1), keyframe spacing and a higher QP for P-frames were measured too, and none beat raising the QP at the same quality. The default stays QP 18. `test/render.test.js` checks that the QP reaches the encoder, that a wrong value is refused, and that a part made at another QP is not reused from the cache.
+- The viewer can run on a server and be opened at a domain of your own: `MOTLAB_VIEWER_PASSWORD=... motlab start --domain viewer.example.com`, behind a reverse proxy such as Caddy for HTTPS. It still listens only on `127.0.0.1`. Every request then needs a login, whatever Host header the proxy sends: a password of at least 12 characters, which gives a 30-day session cookie that is HttpOnly, Secure and SameSite=Strict. Writes must come from the viewer's own page on the domain, and after 5 wrong passwords in a minute the login waits. `motlab edit`, `stop` and `restart` on the server send a token the viewer writes to `~/.motlab/viewer-token` and removes when it stops. docs/viewer.md shows the Caddyfile and the Tailscale option. Checked: `test/access.test.js`, the real viewer with curl sending the domain's Host header, and Chrome on localhost (sign-in, a wrong password, saving a click, `motlab edit` and `stop` through the token). Not tried: a real VPS behind Caddy with a real certificate.
+- A transition can be a layer drawn over a hard cut: `"transition": { "layer": "assets/kits/acme/transitions/swish/transition.js", "duration": 0.6 }`, such as the asset skill's `transition.js`. The module's `draw(ctx, p, W, H)` covers the last half of the duration of the scene before and the first half of the next, in the page's own pixels. `p` reaches 0.5 at the cut, and the video keeps its length because nothing overlaps. Before, each of the two scene pages had to draw its half by hand. It is an option for when the user asks for one: the skill still designs each transition frame by frame in the scenes by default. The render draws it on the transition part and the viewer over the preview, and the module is part of the cache key. A note on a frame inside it records `transition: { layer, from, frame, frames }`. Checked: `test/render.test.js` renders a layer at `--scale 2` and checks the frame count and where it is drawn on both sides of the cut; `test/motion.test.js` checks how the frames are split; the asset skill's swish covered the whole frame at the cut and showed the same picture 0.2 s after it in the viewer and in a 1080p render. Not tried: a layer that loads its own images or fonts.
- `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.
- One recording can be split over several scenes by section, with captions from a transcript. `cuts.json` takes `"sections": [{ "name", "from" }]` in seconds of the recording (`cut_pauses.py --sections hook=0,demo=41.5` writes them and prints where each lands), and `cutList(cuts, clip, { section: 'demo' })` plays that section from time 0: it starts at the cut nearest its `from` and runs to the next section's cut, so the section scenes add up to the cut voice. `edit.captions(transcript)` takes Whisper's JSON with word times, or a list of `{ text, start, end }`, drops words that were cut out or lie outside the section, and returns caption lines in the scene's time, broken at pauses, sentence ends and a character limit. motlab does not transcribe. Checked: `test/cuts.test.js` (new) checks section starts and lengths with and without a dissolve and how captions are placed; `test/render.test.js` renders two section scenes of one grey-coded recording and checks all 24 frames; `cut_pauses.py --sections` on a made-up take matched `cutList`. Not tried: a real Whisper transcript and a real take split into sections.
- 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.
+### Fixed
+
+- `motlab stills` at 4K stopped with "TypeError: Failed to fetch" after 109 stills of a busy 1920x1080 page at `--scale 2` (4.6 MB PNGs, about 500 MB in all), every time. The page uploaded each still as a Blob, and Chrome frees a Blob only when garbage collection runs, which Blob memory does not trigger. Stills are now uploaded as an ArrayBuffer, and the raw bitstream path joins its chunks into one ArrayBuffer the same way. Checked on the Windows laptop: the same 200 stills at 4K all came out. Not covered by an automated test, because it needs about 500 MB of stills.
+
### Changed
+- docs/rendering.md no longer says WebCodecs probably skips NVENC. It encodes on the RTX 3060's NVENC: `nvidia-smi` showed the encoder at up to 51% during a 4K encode, on the same adapter that draws. The session count it showed as zero does not include Media Foundation sessions. The roadmap question is removed.
- The install docs now say a Chromium you already have works: set `CHROME` to it, for example the Chromium Playwright downloads, instead of installing Google Chrome. The README, the install docs and the roadmap also record that a real video has now been rendered on Linux: a 42 s, 1080x1920 project on Ubuntu 24.04 with no GPU in about 82 s (issue #8). An install from the npm registry on Linux and anything on macOS are still untested.
## 0.3.0 (2026-11-18)
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 79c9794..b0e23b2 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, two scenes from sections of one recording, 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, `cuts.test.js` how cut list sections and captions are placed, `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, two scenes from sections of one recording, 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, `cli.test.js` that `motlab help`, `--help` and `-h` print the commands, `doctor.test.js` the optional earshot check, `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, `access.test.js` the viewer's login on a domain, `install.test.js` what setup, `--update` and uninstall write and remove, `cuts.test.js` how cut list sections and captions are placed, `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/DESIGN.md b/DESIGN.md
index 7eb3398..267090e 100644
--- a/DESIGN.md
+++ b/DESIGN.md
@@ -54,6 +54,10 @@ This covers `src/editor.html`. The viewer is only for looking at a project and p
- The playhead is never animated, because it has to sit exactly on a frame. Nothing animates when the page first opens.
- All motion turns off under `prefers-reduced-motion`, including the export spinner.
+## Sign-in page
+
+- Only for a viewer started with `--domain` (src/access.js). One white card like the menus (12 px radius, the menu shadow) in the middle of the grey canvas `#ececec`: the title, the password field with its label above it in muted text, a full-width dark button like Export, and a wrong password in the red `#b8322a` under it as an alert. Indonesian when the browser asks for it first, English otherwise. The system font, because the page loads nothing from outside.
+
## Accessibility
- Every scene and audio row is a button, so Tab, Enter and Space reach it. The timeline is a focusable slider.
diff --git a/README.md b/README.md
index 1a53dee..ad30184 100644
--- a/README.md
+++ b/README.md
@@ -30,7 +30,9 @@ The ad above (19 seconds, 7 scenes) was made with motlab and its skill, reviewed
- The viewer plays the real pages with their audio, frame by frame, with a timeline you can zoom and step through.
- You point at what to change: click a frame, drag a box over a part of it, or mark a time range, and type a note on it. The agent reads every note from `selection.json` and works through them by number.
- Versions of a project sit side by side in the viewer, so a second cut does not overwrite the first.
-- Export renders 720p, 1080p, 1440p or 4K MP4, with the scenes' transitions, music and voice mixed in.
+- Export renders 720p, 1080p, 1440p or 4K MP4, with the scenes' transitions, music and voice mixed in. Scenes render three at a time (fewer on a small machine), which took a project of 12 short scenes from 93 to 53 s at 4K, and `"qp"` in `project.json` makes the file smaller (about 30% at `22`) when you need that.
+- The viewer can run on your own server behind a domain and a password, so you can review and export from your phone.
+- A long talking-head take is cut at its pauses and can be split into one scene per section, with captions placed from a transcript.
- Frames are encoded with WebCodecs inside the page, so they never leave Chrome as images. On a GPU that made it 2 to 4 times as fast as Remotion and HyperFrames on the [benchmark scene](#speed).
- A second skill, `motlab-assets`, builds reusable asset kits the same way: icons, illustrations, 2D characters with a rig, transitions, 3D objects and textures, rendered to transparent PNG plus SVG, or GLB, FBX and OBJ with PBR textures. Every video that uses the kit shares one look.
@@ -94,7 +96,7 @@ Later, `motlab update` tells you when a new version is out and how to get it (fr
3. The agent plans the shots, writes the scenes and starts the viewer. Click the frame you mean, or drag a box over the part and type a note right on it. Notes can be left all over the video and handed over at once, so "this one" or "all the notes" is enough.
4. When you are happy, press Export in the top right. The video goes to the project's `out/` folder.
-The viewer keeps running in the background for every project: `motlab stop` ends it, `motlab restart` starts it again, and `motlab start` starts it without opening a project. Its text is in English or Indonesian, following your browser, and the project menu switches it. You can also render from the command line:
+The viewer keeps running in the background for every project: `motlab stop` ends it, `motlab restart` starts it again, and `motlab start` starts it without opening a project. `motlab help` lists every command. Its text is in English or Indonesian, following your browser, and the project menu switches it. You can also render from the command line:
```bash
motlab render example --scale 1
@@ -121,13 +123,13 @@ This is one scene on one machine; macOS and Linux were not measured. The other s
1. A project is a `project.json` that lists scene pages and audio files.
2. A scene page is plain HTML with a `<canvas id="c">`, `window.renderAt(t)`, `window.TOTAL` and `window.ready`. Everything visible is a function of time, so the preview, the stills and the render draw the same frames.
3. The viewer (`motlab start`, or `motlab edit` to open a project in it) shows the real pages in iframes with their audio through WebAudio, and saves your clicks and notes to `selection.json`.
-4. `motlab render` opens headless Chrome per scene and encodes the frames with `VideoEncoder` inside the page. ffmpeg only copies streams, joins the parts, sets the colour tags and adds the audio.
+4. `motlab render` opens headless Chrome for each scene and transition, three at a time, and encodes the frames with `VideoEncoder` inside the page. ffmpeg only copies streams, joins the parts, sets the colour tags and adds the audio.
```text
project.json + scene pages (canvas, renderAt(t)) + audio files
|
+-- motlab edit viewer: the real pages in iframes, WebAudio audio, selection.json
- +-- motlab render headless Chrome per scene -> VideoEncoder in the page -> MP4 parts
+ +-- motlab render headless Chrome per part, 3 at a time -> VideoEncoder in the page -> MP4 parts
-> ffmpeg -c copy: join, colour tags, audio -> out/<name>.mp4
```
@@ -139,9 +141,9 @@ Footage is decoded inside the page with Mediabunny, so a scene can cut and trim
|---|---|
| Install, update, per-OS notes | [Install](docs/install.md), [Agent install](docs/install-for-agents.md) |
| Projects, scenes, audio and footage | [Projects](docs/projects.md) |
-| The viewer, keys and `selection.json` | [Viewer](docs/viewer.md) |
+| The viewer, keys, `selection.json`, the viewer on a VPS | [Viewer](docs/viewer.md) |
| Commands, options and the page contract | [Command line](docs/cli.md) |
-| How a render works, encoders, measurements, quirks | [Rendering](docs/rendering.md) |
+| How a render works, encoders, file size, measurements, quirks | [Rendering](docs/rendering.md) |
| What the skill does and its references | [SKILL.md](skills/motlab/SKILL.md), [skill references](skills/motlab/references/) |
| Asset kits: tokens, 2D, 3D | [motlab-assets SKILL.md](skills/motlab-assets/SKILL.md), [its references](skills/motlab-assets/references/) |
| The viewer's visual design | [DESIGN.md](DESIGN.md) |
@@ -182,6 +184,22 @@ Footage is decoded inside the page with Mediabunny, so a scene can cut and trim
</details>
+<details><summary><strong>Can I review on my phone?</strong></summary>
+
+<br>
+
+> Yes, with the viewer on a server of yours: `motlab start --domain viewer.example.com` behind a reverse proxy such as Caddy, with a password you set, as described in [the viewer docs](docs/viewer.md#on-a-vps-with-a-domain). An agent can set it up from [its install steps](docs/install-for-agents.md). On the same Wi-Fi without a server, there is no option yet. The login has been tested on the Windows laptop, not yet on a real VPS.
+
+</details>
+
+<details><summary><strong>Can the files be smaller?</strong></summary>
+
+<br>
+
+> Set `"qp": 22` in `project.json`: a busy 4K render came out 30% smaller with nearly the same quality (SSIM 0.9964 to 0.9960). HEVC, AV1 and a second encoding pass were measured too and did not do better at the same quality. The numbers are in [File size](docs/rendering.md#file-size).
+
+</details>
+
<details><summary><strong>Can I use it without an agent?</strong></summary>
<br>
diff --git a/ROADMAP.md b/ROADMAP.md
index 599ba0e..4266286 100644
--- a/ROADMAP.md
+++ b/ROADMAP.md
@@ -5,8 +5,7 @@ What is not built, what has not been tested, and ideas that came up while using
## Not built yet
- 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).
-- 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.
+- From the viewer on a VPS, sending a render to the personal laptop when it is on. The viewer itself runs on a domain behind a password now (`motlab start --domain`), and its Export renders on the server it runs on.
- 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.
## Not tested yet
@@ -15,6 +14,7 @@ What is not built, what has not been tested, and ideas that came up while using
- 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).
+- The viewer on a real VPS behind Caddy with a real certificate, its systemd user service, the agent's setup steps in docs/install-for-agents.md, and Tailscale Serve. The login was tested on the Windows laptop with curl and Chrome on localhost (docs/viewer.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.
@@ -34,5 +34,4 @@ What is not built, what has not been tested, and ideas that came up while using
## Questions about speed
-- Whether Chrome can be made to use NVENC on NVIDIA cards. On the test laptop `nvidia-smi` showed no encoder sessions during a hardware encode, so Chrome probably used the integrated GPU's encoder.
- Why the hardware encoder at 4K switches between about 34 and 17 fps from run to run.
diff --git a/SECURITY.md b/SECURITY.md
index 01e56f8..0abfae1 100644
--- a/SECURITY.md
+++ b/SECURITY.md
@@ -2,12 +2,13 @@
## Scope
-motlab runs local code: headless Chrome, ffmpeg and small HTTP servers on `127.0.0.1`. Scene pages are trusted code, like any script you run, so a page that does something harmful is not a motlab vulnerability. These are:
+motlab runs local code: headless Chrome, ffmpeg and small HTTP servers on `127.0.0.1`. The viewer can also be served on a domain through a reverse proxy, behind a password (`motlab start --domain`). Scene pages are trusted code, like any script you run, so a page that does something harmful is not a motlab vulnerability. These are:
- a way for a project file (`project.json`, a scene path, an audio entry) to run commands or write files outside the project folder
- path traversal in the render server or the viewer server, reading files outside the served folder
- command injection through a file name or option passed to ffmpeg, ffprobe or Chrome
- a server that listens on anything other than `127.0.0.1`, or accepts requests from other sites in a way that writes files
+- a viewer started with `--domain` that answers without the login or the local token, or lets another site write through a signed-in browser
- the installer deleting or overwriting files outside the paths it prints
Out of scope: bugs in Chrome or ffmpeg themselves, and someone who already has a shell on the machine.
diff --git a/docs/cli.md b/docs/cli.md
index 3043794..3577f29 100644
--- a/docs/cli.md
+++ b/docs/cli.md
@@ -1,22 +1,23 @@
# Command line
```text
-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 render <project> [out.mp4] [--scale 2] [--only 3] [--parallel 3] [--qp 22] [--codec hevc] all scenes and audio in project.json, as one MP4
+motlab start [--domain viewer.example.com] 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
motlab stills <page.html> <outDir> <t1> <t2> ... single frames as PNG or JPEG
motlab video <page.html> <out.mp4> [options] one page as an MP4
motlab events <page.html> <out.json> the page's EVENTS, for syncing sound
-motlab doctor check Node, Chrome, ffmpeg and the skill's Python packages
+motlab help this list and the engine folder (also motlab --help or -h)
+motlab doctor check Node, Chrome, ffmpeg, the skill's Python packages and earshot
motlab setup [--skill <target>] [--update] ... copy the skills to agent folders after npm install -g, and add the command if needed
motlab update [--dry-run] the newest motlab (from GitHub, or the npm commands that get it), and the skills copied again where they were installed
motlab uninstall [--dry-run] [--yes] remove the skills, ~/.motlab, the encoder cache and a clone's command
```
-The viewer commands are described in [the viewer](viewer.md), `motlab setup` in [From npm](install.md#from-npm), `motlab update` in [Updating](install.md#updating) and `motlab uninstall` in [Removing](install.md#removing).
+The viewer commands are described in [the viewer](viewer.md), `--domain` in [On a VPS with a domain](viewer.md#on-a-vps-with-a-domain), `motlab setup` in [From npm](install.md#from-npm), `motlab update` in [Updating](install.md#updating) and `motlab uninstall` in [Removing](install.md#removing).
-`<project>` is a folder with `project.json`, or a project file in it such as `video/project-tiktok.json` (a [version](projects.md#versions)). `motlab --help` prints the same list and the engine folder.
+`<project>` is a folder with `project.json`, or a project file in it such as `video/project-tiktok.json` (a [version](projects.md#versions)). `motlab help` (or `motlab --help`) prints the same list and the engine folder.
## Single pages
@@ -34,7 +35,7 @@ When the page throws while loading, the error names the file, line and column, f
## Options
-`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`).
+`render` takes `--scale`, `--only`, `--parallel`, `--qp` and `--codec` (the last two also from `project.json`); the rest are for `video` (and `--root`, `--chrome`, `--scale` and `--format` for `stills`, and `--root` and `--chrome` for `events`).
| Option | Meaning |
|---|---|
@@ -61,6 +62,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_VIEWER_PASSWORD` | The viewer's password with `motlab start --domain`, at least 12 characters. See [On a VPS with a domain](viewer.md#on-a-vps-with-a-domain) |
| `MOTLAB_CACHE_DIR` | Where the encoder timings and the cached scene parts are saved. Default `%LOCALAPPDATA%\motlab` on Windows, `~/.cache/motlab` elsewhere |
## Page contract
diff --git a/docs/install-for-agents.md b/docs/install-for-agents.md
index 7dc1dd0..36260fd 100644
--- a/docs/install-for-agents.md
+++ b/docs/install-for-agents.md
@@ -68,6 +68,24 @@ python -m pip install -r <folder>/skills/motlab/requirements.txt
Say in a few lines what was installed and where (the clone and the launcher, or the npm package, and the two skill folders), what `doctor` still reports, and how to start: `motlab edit <folder>/example` opens the example in the viewer (it starts the viewer in the background) and prints the address, `http://127.0.0.1:4173/p/example/`; `motlab stop` ends it. A new agent session may be needed before the skills show up.
+## 6. The viewer on a VPS, when the user asks for it
+
+Only when the user wants to open the viewer from anywhere, for example on their phone, with the viewer running on a server of theirs. Work on the server itself (a Linux VPS reached over SSH), after steps 1 to 4 there. [On a VPS with a domain](viewer.md#on-a-vps-with-a-domain) explains how it works; these are the steps. They have not been run end to end on a real VPS yet, so check each result and tell the user what you could not verify.
+
+1. **The domain.** Ask the user for the name to use, such as `viewer.example.com`, and to point its DNS (an A record, and AAAA for IPv6) at the server. Check with `getent hosts viewer.example.com` that it resolves to the server's address (`curl -s https://ifconfig.me` shows it) before going on.
+2. **The password.** The user picks it, at least 12 characters, and writes it themselves into an environment file that only they can read. Do not make it up, type it, repeat it in chat, or put it in a command, the shell history or any file in a repository. Create the file empty with the right permissions and let them fill it in:
+ ```bash
+ mkdir -p ~/.config/motlab && touch ~/.config/motlab/viewer.env && chmod 600 ~/.config/motlab/viewer.env
+ ```
+ It holds one line, `MOTLAB_VIEWER_PASSWORD=...`. Ask them to tell you when it is done.
+3. **Caddy for HTTPS.** Check `caddy version`. If it is missing, ask before installing it and use the install steps on [caddyserver.com/docs/install](https://caddyserver.com/docs/install) for their distribution. Add the site block from the viewer doc to `/etc/caddy/Caddyfile`. If that file already has sites, add the block, do not replace the file, and show the user the change before reloading with `sudo systemctl reload caddy`.
+4. **Ports.** 80 and 443 must be open for Caddy and its certificate. Do not open 4173: the viewer listens on `127.0.0.1` only and must stay behind Caddy. Ask before changing a firewall (`ufw`, a cloud provider's rules).
+5. **Keep it running.** Ask which folder holds their video projects; the viewer's menu lists the projects in it. Then set up the systemd user service from [Keep it running](viewer.md#keep-it-running), with the domain and that folder filled in. A user service only runs while they are logged in unless lingering is on (`loginctl enable-linger`); ask before turning it on.
+6. **Check it.** `curl -sI https://viewer.example.com/` must answer `302` with `location: /login`, and `systemctl --user status motlab-viewer` must be active. Then ask the user to open the address, sign in and press Export once, so a render on the server is known to work (`motlab doctor` must have found Chrome and ffmpeg there).
+7. **Tell the user** the address, where the password file is, that changing the password means editing that file and running `systemctl --user restart motlab-viewer`, and that signing in again is needed after every restart.
+
+Never run the viewer behind a public proxy without `--domain` (it would refuse saves and Export, and the wrong fix is to remove that check), never turn the login off, and never put the viewer's port on the internet directly. If the user has Tailscale and no domain, the viewer doc's Tailscale paragraph is the private alternative.
+
## Do not
- create video projects inside the clone, the npm package or the installed skill folder; a project lives in its own folder
diff --git a/docs/install.md b/docs/install.md
index 1383fed..7e9ad11 100644
--- a/docs/install.md
+++ b/docs/install.md
@@ -35,6 +35,8 @@ The skill's scripts need numpy, scipy and Pillow. From the engine folder (`motla
python -m pip install -r skills/motlab/requirements.txt
```
+[earshot](https://github.com/Leonxlnx/earshot) is optional. With it the agent can listen to sound: pick sound effects, find the best moment in a recording and check a mix. It needs Python with torch and about 1.1 GB of models, so motlab never installs it. `motlab doctor` shows it as `ok` with its models downloaded, or as `warn` with what to do, and it never makes the doctor fail. Install it from its own page, then `earshot doctor --fetch` downloads the models.
+
## From npm
```bash
diff --git a/docs/projects.md b/docs/projects.md
index da9ce9b..a72ad9f 100644
--- a/docs/projects.md
+++ b/docs/projects.md
@@ -20,6 +20,7 @@ A project is a folder with scene pages, audio files and a `project.json`:
- A mono file plays at the same level on both channels, in the viewer and in the render.
- An audio entry can also be a video file, whose sound is used. Any entry can take `from` (seconds into the file) and `duration` to use only part of it.
- Audio that runs past the end of the video is cut.
+- `qp` and `codec` trade file size against quality, for `motlab render` and the viewer's Export alike: `"qp": 22` makes a file about 30% smaller than the default 18 at nearly the same quality, and `"codec": "hevc"` asks for HEVC. `--qp` and `--codec` on `motlab render` override them. The measurements are in [File size](rendering.md#file-size).
Paths are relative to the folder that holds the project file. [`example/`](../example) is a sample with three scenes, music and three sound effects, all generated with ffmpeg (`sine` and `anoisesrc`).
@@ -91,6 +92,18 @@ 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 layer over the cut
+
+A transition can also be a layer of shapes drawn over a hard cut, such as a swish of brand-coloured bands, instead of a shader that mixes the two scenes. It is an option, not the default: the skill still designs each transition frame by frame in the scene pages, and uses a layer only when the user asks for one. Set `layer` to a JavaScript module in the project in place of `type`:
+
+```json
+{ "file": "scenes/02.html", "transition": { "layer": "assets/kits/acme/transitions/swish/transition.js", "duration": 0.6 } }
+```
+
+The module exports `draw(ctx, p, W, H)`, which draws the layer at progress `p` in the page's own pixels (`W` by `H`, before `?scale=`), and may be async. The asset skill's `templates/transition.js` is one. The scenes do not overlap and the video keeps its length: the layer covers the last half of `duration` of the scene before and the first half of the next, and `p` runs from 0 to 1 over those frames, reaching 0.5 at the cut. Of `n` frames, the scene before gives the last `floor(n / 2)` and the next scene the first `n - floor(n / 2)`, and frame `k` is drawn at `p = (k + 0.5) / n`. At `p = 0.5` the layer must cover the whole frame, or the cut shows through. The render draws it on the transition part like a shader transition, the viewer draws it over the preview, and the module's file is part of the cache key. `ease` and `params` do not apply: the layer eases itself.
+
+Tested: `test/render.test.js` renders two flat scenes with a layer that draws a red bar `p` of the width, at `--scale 2`, and checks the frame count (no frames lost) and where the bar is before and after the cut. The asset skill's swish between the example's first two scenes was fully covering at the cut and showed the same picture 0.2 s after it in the viewer and in a 1080p render, and the project stayed 9 s long. Not tried: a layer that loads its own images or fonts.
+
### A transition of your own
`type` can also be a path to a `.glsl` file in the project folder:
diff --git a/docs/rendering.md b/docs/rendering.md
index 705196b..b93b6e0 100644
--- a/docs/rendering.md
+++ b/docs/rendering.md
@@ -1,6 +1,6 @@
# Rendering
-How `motlab render`, `motlab video` and Export turn scene pages into an MP4, how the encoder is chosen, and what was measured. The screenshot pipeline in the tables captures each frame from Chrome as a JPEG and pipes it to ffmpeg libx264, the way DOM-based video tools capture frames. motlab was built to avoid that step.
+How `motlab render`, `motlab video` and Export turn scene pages into an MP4, how the encoder is chosen, what sets the file size, and what was measured. The screenshot pipeline in the tables captures each frame from Chrome as a JPEG and pipes it to ffmpeg libx264, the way DOM-based video tools capture frames. motlab was built to avoid that step.
## Steps
@@ -11,6 +11,8 @@ How `motlab render`, `motlab video` and Export turn scene pages into an MP4, how
5. ffmpeg copies the stream (`-c copy`) into the final file. This pass writes BT.709 tags with the encoder's range into the bitstream, joins the parts from parallel mode, adds audio and moves `moov` to the front. It always runs, even after a successful Mediabunny mux, because the encoders tag colour inconsistently (see quirks).
6. ffprobe counts the frames and duration of the final file. The render fails if they do not match.
+A project (`motlab render`, Export) runs these steps once for each scene and transition, three at a time after the first scene, and joins the parts with one more `-c copy` pass ([Rendering a project](projects.md#rendering-a-project)).
+
Temporary files go to the system temp folder and are removed afterwards. The output is written as `.part` and renamed at the end.
The code is plain JavaScript ESM with JSDoc and no TypeScript. Half of it runs inside Chrome and is served straight from disk, so TypeScript would mean two languages or a build step. CDP uses Node's built-in `WebSocket`.
@@ -155,11 +157,44 @@ At 4K:
Not measured: macOS, where HyperFrames turns on a capture through `drawElementImage` that its help calls about twice as fast; Linux; Remotion and HyperFrames with the browsers they download themselves; Remotion with PNG frames; scenes heavy on text layout, images or footage; and Remotion's cloud rendering.
+## File size
+
+The size of a render is set almost entirely by its QP: the encoder's step size, constant over the video. motlab's default is 18 for H.264 and 20 for HEVC, chosen so the 2D and 3D templates keep an SSIM near 0.999. A higher QP makes a smaller file. Set `"qp"` in `project.json` (Export uses it too) or pass `--qp` to `render` or `video`.
+
+Measured on the test laptop (Ryzen 7 5800H, RTX 3060 Laptop, Chrome 157): 8 s at 25 fps, against a lossless reference made from `motlab stills` of every frame. The busy page is 160 moving cards with shadows over a gradient, the hardest content here. VMAF stayed at 99.98 for every row on the busy page, so SSIM is the column that tells them apart.
+
+| Busy page, 4K | Size | SSIM | Time of the command |
+|---|---|---|---|
+| H.264 hardware, QP 18 (default) | 12.49 MB | 0.9964 | 8.2 s |
+| H.264 hardware, QP 22 | 8.68 MB | 0.9960 | 5.5 s |
+| HEVC hardware, QP 20 | 10.15 MB | 0.9963 | 7.9 s |
+| HEVC hardware, QP 22 | 8.67 MB | 0.9961 | 8.9 s |
+| HEVC hardware, QP 24 | 6.88 MB | 0.9958 | 8.7 s |
+| H.264 QP 18, then ffmpeg `hevc_nvenc` (CQ 24) | 9.82 MB | 0.9960 | 5.7 s more |
+| H.264 QP 18, then ffmpeg SVT-AV1 (preset 8, CRF 32) | 7.45 MB | 0.9927 | 7.5 s more |
+
+| Busy page, 1080p | Size | SSIM |
+|---|---|---|
+| H.264 QP 18 (default) | 6.93 MB | 0.9952 |
+| H.264 QP 20 | 5.57 MB | 0.9947 |
+| H.264 QP 22 | 4.71 MB | 0.9944 |
+| H.264 QP 26 | 3.12 MB | 0.9925 |
+| HEVC QP 20 | 5.10 MB | 0.9949 |
+| HEVC QP 22 | 4.32 MB | 0.9944 |
+| SVT-AV1 after it (CRF 32) | 2.80 MB | 0.9904 |
+
+What came out of it:
+
+- QP 22 is about 30% smaller than 18 at both sizes, and its SSIM drops by 0.0004 at 4K and 0.0008 at 1080p. On the 2D and 3D templates it was 26 to 29% smaller.
+- HEVC is 10 to 15% smaller than H.264 at the same SSIM at 1080p, and no smaller at 4K (QP 22: 8.67 against 8.68 MB). It was slower at 4K, and fewer players and browsers play it, so H.264 stays the default.
+- A second pass with ffmpeg was not worth it. `hevc_nvenc` was no smaller than raising the QP at the same SSIM. x264 (`-preset slow -crf 20 -tune animation`), measured on the templates only, came out about as large as QP 22 with a lower VMAF. SVT-AV1 was smaller only at a lower SSIM, and adds about one second for every second of 4K video.
+- A keyframe every 10 s instead of every 2 s saved 1 to 5%, and a QP for P-frames 2 above the keyframes' saved what raising the QP by 2 saves, at the same loss. Neither was worth a change.
+
## Quirks
- Headless Chrome uses the integrated Radeon GPU by default. `--force_high_performance_gpu` moves it to the RTX 3060. Check with `WEBGL_debug_renderer_info`.
- WebCodecs in headless Chrome supports hardware H.264 and HEVC, but not hardware AV1 or VP9, and not software HEVC.
-- WebCodecs does not seem to use NVENC: `nvidia-smi` shows zero encoder sessions during a hardware encode. Chrome probably uses the AMD encoder through Media Foundation, but that is not confirmed.
+- WebCodecs encodes on the RTX 3060's NVENC through Media Foundation, on the GPU it draws on. During a 4K hardware encode, `nvidia-smi --query-gpu=utilization.encoder` peaked at 51% and Windows' `GPU Engine(*engtype_VideoEncode)` counter showed encoding only on the adapter that also did the drawing. `nvidia-smi`'s encoder session count stays at zero, because it does not count Media Foundation sessions; that count was why earlier notes said NVENC was not used.
- The hardware encoder is not always faster. In one process, software is faster at 1080p (about 120 fps against 48) and at 4K (about 40 fps against 17 to 34).
- The hardware encoder has two throughput states. At 4K it runs at about 34 fps or about 17 fps and switches between runs with no code change. H.264 and HEVC are affected together. The cause is unknown, so measure several times before concluding anything about speed.
- The saved encoder probe keeps one machine, named by Chrome, GPU, CPU and platform. A render on another GPU, or on SwiftShader, probes again and replaces the saved results, so switching back and forth probes every time.
diff --git a/docs/viewer.md b/docs/viewer.md
index 16b1fcd..5122baa 100644
--- a/docs/viewer.md
+++ b/docs/viewer.md
@@ -96,7 +96,7 @@ Every click on a scene, an audio clip or a point on the timeline is saved to `se
| `scene`, `sceneIndex` | the scene page and its number, from 1 |
| `sceneTime` | seconds into that scene |
| `frame` | the frame of that scene the preview shows; `frame / fps` is its time on the render's frame grid |
-| `transition` | inside a transition: `{ type, from, frame, frames }`, the scene number it comes from and its frame `frame` of `frames`; else `null`. `scene` is then the scene it leads into |
+| `transition` | inside a transition: `{ type, from, frame, frames }`, the scene number it comes from and its frame `frame` of `frames`; else `null`. `scene` is then the scene it leads into. Inside a layer over a cut it is `{ layer, from, frame, frames }`, and `scene` is the one under the layer |
| `audio` | `{ file, start, index }` when the click was on an audio clip, else `null` |
| `range` | `{ start, end, scenes }` when a range is marked, else `null`: seconds from the start of the video, on the frame grid, and the scene numbers it covers |
| `marks` | the notes, see below |
@@ -147,10 +147,66 @@ Checked in headless Chrome over the DevTools protocol with a phone emulated (tou
## Export
-The Export button in the top right renders the project. Pick 720p, 1080p, 1440p or 4K and press the button under the list, which names the size it will make. The viewer's server runs the same render as `motlab render` and streams the log back to the page; the log also appears in the terminal. The file is written to `out/<folder>-<resolution>.mp4` in the project folder, for example `example/out/example-1080p.mp4`, or `out/<folder>-<version>-<resolution>.mp4` for another version, and the Open link opens it. The resolution in the name is the short side of the frame: 4K is written as `-2160p`. Only one export runs at a time.
+The Export button in the top right renders the project. Pick 720p, 1080p, 1440p or 4K and press the button under the list, which names the size it will make. The viewer's server runs the same render as `motlab render` and streams the log back to the page; the log also appears in the terminal. The file is written to `out/<folder>-<resolution>.mp4` in the project folder, for example `example/out/example-1080p.mp4`, or `out/<folder>-<version>-<resolution>.mp4` for another version, and the Open link opens it. The resolution in the name is the short side of the frame: 4K is written as `-2160p`. Only one export runs at a time. Export renders the scenes three at a time like `motlab render`, and uses `qp` and `codec` from the project file when it has them ([File size](rendering.md#file-size)).
While an export runs, the button is faded with a spinner and a red Cancel button appears under it. Pressing Cancel stops the render: the server closes its headless Chrome and any ffmpeg step, deletes the temp files, and the menu shows "Export cancelled". The file that was being written is never left half done in `out/`, because the render writes it as `.part` and renames it only when it is complete; an earlier export of the same size stays as it was. On the example project at 4K a cancel took 0.3 s. Reloading the page does not cancel an export; it keeps running in the terminal, and Export answers that another export is still running until it ends.
+## On a VPS with a domain
+
+The viewer can run on a server and be opened from anywhere at a domain of your own, behind a password. It still listens only on `127.0.0.1`; a reverse proxy on the same server gives it HTTPS and passes requests to it. With [Caddy](https://caddyserver.com), which gets the certificate by itself, the whole proxy is a Caddyfile:
+
+```text
+viewer.example.com {
+ reverse_proxy 127.0.0.1:4173
+}
+```
+
+Point the domain's DNS at the server, then start the viewer with the domain and a password of at least 12 characters in `MOTLAB_VIEWER_PASSWORD`:
+
+```bash
+MOTLAB_VIEWER_PASSWORD='a long password of your own' motlab start --domain viewer.example.com
+```
+
+Open `https://viewer.example.com` and sign in. Then:
+
+- Every request needs the login, whatever address it comes in on, so a proxy that rewrites the Host header to `127.0.0.1` does not skip it. Only the sign-in page answers without it.
+- The session is a cookie that is HttpOnly, Secure and SameSite=Strict, and lasts 30 days or until the viewer stops. A save, a new version or an Export must come from the viewer's own page on `https://viewer.example.com`; a request from another site is refused.
+- After 5 wrong passwords in a minute, the login waits until the minute is over.
+- `motlab edit`, `stop` and `restart` on the server still work: the viewer writes a random token to `~/.motlab/viewer-token` (readable only by you on Linux and macOS) and removes it when it stops, and the commands send it. `restart` keeps the domain.
+- Export renders on the server, so the server needs Chrome and ffmpeg (`motlab doctor`). The finished file opens from the Open link as it does on your own machine.
+
+The password is read from the environment so that it does not show up in the process list. Put it in your service manager's environment file rather than in a command line that the shell history keeps. A proxy other than Caddy works the same way: HTTPS in front, `127.0.0.1:4173` behind it.
+
+### Keep it running
+
+On a Linux server, a systemd user service starts the viewer again after a reboot or a crash. Put the password in `~/.config/motlab/viewer.env` as one line, `MOTLAB_VIEWER_PASSWORD=...`, readable only by you (`chmod 600`), and this in `~/.config/systemd/user/motlab-viewer.service`, with your domain, your projects folder and the path that `command -v motlab` prints:
+
+```ini
+[Unit]
+Description=motlab viewer
+
+[Service]
+EnvironmentFile=%h/.config/motlab/viewer.env
+WorkingDirectory=%h/videos
+ExecStart=/usr/local/bin/motlab start --foreground --domain viewer.example.com
+Restart=on-failure
+
+[Install]
+WantedBy=default.target
+```
+
+```bash
+systemctl --user daemon-reload
+systemctl --user enable --now motlab-viewer
+loginctl enable-linger "$USER"
+```
+
+The last line keeps it running when you are not logged in. `systemctl --user restart motlab-viewer` picks up a new password; everyone signs in again after a restart. This unit has not been run on a real server yet.
+
+Without a domain of your own, [Tailscale](https://tailscale.com) keeps the viewer private to your own devices: `tailscale serve 4173` on the server gives it an HTTPS name on your tailnet. Start the viewer with `--domain` set to that name and a password, because without `--domain` the viewer refuses saves and Export from any name but `127.0.0.1`.
+
+Tested on the Windows laptop: `test/access.test.js` checks the login, the cookie, refused writes from other sites and other Host headers, the token, the wait after wrong passwords and signing out. The real viewer was started with `--domain` and checked with curl sending the domain's Host header as a proxy does, and in Chrome on `localhost`: the sign-in page came first, a wrong password was refused, the right one opened the project, and a click saved `selection.json`. `motlab edit` and `motlab stop` worked through the token, and the token file was gone after the stop. Not tried yet: a real VPS behind Caddy with a real certificate, and Tailscale Serve.
+
## How the preview works
Nothing is rendered to a file for the preview. Each scene is its real page in a hidden iframe at `?scale=1`, and the preview copies its canvas, so you see exactly what the render draws, on the same frame grid.
@@ -159,7 +215,7 @@ When the viewer opens, it goes through the scenes one at a time for their length
What the viewer plays was recorded off its audio graph on the example project and compared with the render of the same project: the same events at the same times, the same loudness (-19.9 LUFS integrated, -7.2 dBTP) and level within 0.02 dB, with no dropouts or clipping (measured, and listened to with earshot).
-Scene transitions from `project.json` play in the preview: in the overlap the viewer draws both scenes and mixes them with `src/page/transitions.js`, the code the render uses. On the timeline the two tiles overlap, and the overlap is lighter with a bowtie on it. A transition frame in the viewer and in the 1080p MP4 differed by 1.37 levels of 255 on average (example project, desktop app's browser). A wrong transition type, or one too long for its scenes, shows a message instead of the project.
+Scene transitions from `project.json` play in the preview: in the overlap the viewer draws both scenes and mixes them with `src/page/transitions.js`, the code the render uses. On the timeline the two tiles overlap, and the overlap is lighter with a bowtie on it. A layer over a cut is drawn over the preview by its own module, and on the timeline the tiles meet at the cut with the bowtie on it and a lighter band over the frames the layer covers. A transition frame in the viewer and in the 1080p MP4 differed by 1.37 levels of 255 on average (example project, desktop app's browser). A wrong transition type, or one too long for its scenes, shows a message instead of the project.
A frame is drawn only when the playhead reaches a new one. The display refreshes many times per video frame, and drawing the same frame again took time from the next one.
diff --git a/skills/motlab-assets/SKILL.md b/skills/motlab-assets/SKILL.md
index 3644599..c6f13be 100644
--- a/skills/motlab-assets/SKILL.md
+++ b/skills/motlab-assets/SKILL.md
@@ -108,7 +108,8 @@ kits/<name>/
Copy (never move) the kit into the video's project: `<video>/assets/kits/<name>/`, because the viewer and the renderer
only serve the project folder. Read its `style.md` and `tokens.json` before building scenes, and load assets from
there: PNGs and SVGs as images, a character through `svgparts.js`, a GLB in the motlab skill's `template-three.html`,
-a transition by importing its `transition.js`. When the kit changes later, copy it again.
+a kit transition, when the user asks for one, as `"layer"` in `project.json` pointing at its `transition.js`. When the
+kit changes later, copy it again.
## Keep it above board
diff --git a/skills/motlab-assets/references/2d.md b/skills/motlab-assets/references/2d.md
index 498fc6d..34c69cc 100644
--- a/skills/motlab-assets/references/2d.md
+++ b/skills/motlab-assets/references/2d.md
@@ -79,21 +79,28 @@ Outputs for a character:
## Transitions: transition.js
A transition here is a layer over motlab's hard cut between scenes: shapes cover the frame, the cut happens under
-them, and they uncover the next scene. It needs nothing from the engine. `templates/transition.js` is a working example
-(three bands in brand colours sweeping across).
+them, and they uncover the next scene. `templates/transition.js` is a working example (three bands in brand colours
+sweeping across). Build one when the user asks for it; the video skill's default is still a transition designed frame
+by frame in the scenes. To use it, name it in `project.json` on the scene it leads into, and motlab draws it over the
+cut in the viewer and the render:
+
+```json
+{ "file": "scenes/02.html", "transition": { "layer": "assets/kits/acme/transitions/swish/transition.js", "duration": 0.6 } }
+```
- `DURATION` in seconds; half plays at the end of the scene before, half at the start of the scene after.
- `draw(ctx, p, W, H)` draws the layer at progress `p` from 0 to 1, in the page's own pixels. At `p = 0.5` it must
cover the frame completely, or the cut shows.
-- `atEnd(t, TOTAL)` and `atStart(t)` give `p` for the two scenes (or `null` outside the transition).
+- `atEnd(t, TOTAL)` and `atStart(t)` give `p` for the two scenes (or `null` outside the transition), for a scene that
+ has to draw it itself, such as one page that holds two shots. With `"layer"` in `project.json` neither scene draws it.
- Colours from `tokens.json`; motion from the motlab skill's easing rules (`craft.md`).
Check it with `templates/transition.html`: open it in a browser with `BEHIND = true` to see it over two cards, and
render `motlab stills transition.html frames 0 0.1 0.2 0.3 ...` with `BEHIND = false` for the PNG sequence with alpha.
Look at the still at exactly `DURATION / 2`: it must be fully covered. The PNG sequence is for editors outside motlab;
-motlab scenes import `transition.js` itself. In a two-scene render at 30 fps with a rigged `svgparts.js` character in
+motlab uses `transition.js` itself. In a two-scene render at 30 fps with a rigged `svgparts.js` character in
both, the frame was fully covered on the last frame before the cut and the first two after it, and the character gave
the same stills forward and in reverse.
-motlab's own shader transitions (`"transition"` in `project.json`) mix two scenes and are a different thing; they are
-listed in the motlab skill's `references/motion-and-libraries.md`.
+motlab's shader transitions (`"type"` in a `"transition"`) mix two scenes over an overlap and are a different thing;
+they are listed in the motlab skill's `references/motion-and-libraries.md`.
diff --git a/skills/motlab-assets/templates/transition.js b/skills/motlab-assets/templates/transition.js
index 330205e..77b8a0e 100644
--- a/skills/motlab-assets/templates/transition.js
+++ b/skills/motlab-assets/templates/transition.js
@@ -1,6 +1,7 @@
-// A transition as a layer over the cut: shapes that cover the frame at the cut and uncover the next scene. It works
-// with motlab's hard cut between scenes, so no engine support is needed: the scene before draws the first half on top
-// of its last frames, and the scene after draws the second half on top of its first frames.
+// A transition as a layer over the cut: shapes that cover the frame at the cut and uncover the next scene. In a video,
+// name it in project.json on the scene it leads into, and motlab draws it over the cut:
+// { "file": "scenes/02.html", "transition": { "layer": "assets/kits/acme/transitions/swish/transition.js", "duration": 0.6 } }
+// A scene that has to draw it itself (one page holding both shots) can use atEnd and atStart:
//
// import * as swish from '../assets/kits/acme/transitions/swish/transition.js';
// // last scene's renderAt, after everything else: const p = swish.atEnd(t, TOTAL); if (p !== null) swish.draw(ctx, p, W, H);
diff --git a/skills/motlab/SKILL.md b/skills/motlab/SKILL.md
index 29404c6..0efb9f1 100644
--- a/skills/motlab/SKILL.md
+++ b/skills/motlab/SKILL.md
@@ -137,6 +137,11 @@ promo/
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`,
with how to write a `.glsl` transition of your own into the project and how to match one from a reference video.
+ `"layer"` (a kit's `transition.js` drawn over a hard cut) is only for when the user asks for one; by default you
+ design each transition frame by frame in the scenes.
+- When the user wants a smaller file, set `"qp": 22` in `project.json` (about 30% smaller than the default 18, at
+ nearly the same quality); their Export then uses it. Higher saves more and shows more. Details in the engine's
+ docs/rendering.md, File size.
- `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,
@@ -153,6 +158,9 @@ promo/
it prints. `motlab restart` restarts the viewer (after `motlab update`), `motlab stop` ends it. The project name in the header switches between projects. It cannot edit; the
user reloads after changes. Space plays, arrows step frames on the timeline, Ctrl+scroll or `+`/`-` zooms the
timeline, Export renders 720p to 4K.
+- When the user wants to review from their phone or anywhere else, with the viewer on a server of theirs, follow
+ "The viewer on a VPS" in the engine's `docs/install-for-agents.md`. It runs behind a domain and a password the user
+ sets themselves; never handle, print or store the password, and never open the viewer's port to the internet.
- A click writes `<video>/selection.json`:
```json
@@ -164,7 +172,8 @@ promo/
(`floor(sceneTime * fps)`, the same grid as the render), so pass `frame / fps` to `motlab stills` to see exactly that
picture. Older selections have no `frame`; compute it the same way. Inside a scene transition, `transition` is
`{ type, from, frame, frames }` and the note is about the transition (`from` is the scene it comes from); `scene` is
- the one it leads into, and stills of either page alone will not show the mix, so check it in the viewer.
+ the one it leads into, and stills of either page alone will not show the mix, so check it in the viewer. Inside a
+ layer over the cut it is `{ layer, from, frame, frames }`, and `scene` is the one on screen under the layer.
- `range` is `{ start, end, scenes }` when the user marked a stretch of time on the timeline (the range button or `R`, Shift+drag, `X` for a scene, or `I` and
`O`): video seconds on the frame grid and the scene numbers it covers. A note like "ini terlalu lambat" with a range
is about that whole stretch, not the single `time`.
diff --git a/skills/motlab/references/motion-and-libraries.md b/skills/motlab/references/motion-and-libraries.md
index 93ca662..8a98699 100644
--- a/skills/motlab/references/motion-and-libraries.md
+++ b/skills/motlab/references/motion-and-libraries.md
@@ -55,6 +55,17 @@ 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 layer over the cut (only when asked)
+
+The default for every transition is still the one you design and draw frame by frame in the scene pages: a shape
+that carries across the cut (`craft.md` §9), checked with stills inside it. Do not reach for a layer to save that
+work. Use one only when the user asks for a ready-made sweep or wipe over the cut, or wants a kit's transition used
+the same way at many cuts:
+`"transition": { "layer": "assets/kits/<kit>/transitions/swish/transition.js", "duration": 0.6 }`. The module exports
+`draw(ctx, p, W, H)` in page pixels, `p` runs 0 to 1 and the frame must be fully covered at 0.5, where the cut is.
+The scenes keep their full length (nothing overlaps), so audio times do not move. The module comes from the asset
+skill (`templates/transition.js`); motlab then draws it over the cut, so neither scene page draws it.
+
### 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
diff --git a/skills/motlab/references/sound-and-music.md b/skills/motlab/references/sound-and-music.md
index 1f971fa..8366898 100644
--- a/skills/motlab/references/sound-and-music.md
+++ b/skills/motlab/references/sound-and-music.md
@@ -97,7 +97,8 @@ Save the WAV in `<video>/audio/` and list it in `project.json`. The viewer plays
[earshot](https://github.com/Leonxlnx/earshot) (MIT, CPU only) turns sound into words and numbers an agent can read.
motlab does not depend on it, so check once at the start of the sound work:
-- `earshot --help` runs: the CLI is there. If the session lists earshot MCP tools, use those instead of the CLI.
+- `motlab doctor` has an earshot line: `ok` means the CLI and its models are there, `warn` says which is missing.
+ `earshot --help` running is enough for the CLI. If the session lists earshot MCP tools, use those instead.
- Neither: carry on with the steps above. Mention earshot once only if the user asks how to pick sounds better.
- The analysis commands need about 1.1 GB of models (`earshot doctor --fetch`). Ask before fetching them.
diff --git a/src/access.js b/src/access.js
new file mode 100644
index 0000000..9722e29
--- /dev/null
+++ b/src/access.js
@@ -0,0 +1,121 @@
+// Access to the viewer from a domain, for a viewer on a VPS behind a reverse proxy such as Caddy (docs/viewer.md).
+// Off by default: then only 127.0.0.1 is served and nothing here runs. With a domain, every request needs a login
+// (a password from MOTLAB_VIEWER_PASSWORD, then a session cookie) or, from motlab commands on the same machine, the
+// token the viewer writes to ~/.motlab/viewer-token. That holds whatever Host header the proxy sends, so a proxy that
+// rewrites Host to 127.0.0.1 does not skip the login.
+import { createHash, randomBytes, timingSafeEqual } from 'node:crypto';
+import { mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { homedir } from 'node:os';
+import { dirname, join } from 'node:path';
+
+export const TOKEN_FILE = join(homedir(), '.motlab', 'viewer-token');
+export const MIN_PASSWORD = 12;
+const COOKIE = 'motlab_session', DAYS = 30, TRIES = 5; // 5 wrong passwords a minute, then wait
+
+// The token for motlab commands on this machine, or null when the viewer runs without a domain.
+export const readToken = () => { try { return readFileSync(TOKEN_FILE, 'utf8').trim() || null; } catch { return null; } };
+
+export function createAccess({ domain, password, tokenFile = TOKEN_FILE } = {}) {
+ if (!domain) return null;
+ if (!/^[a-z0-9.-]+(:\d+)?$/i.test(domain)) throw new Error(`--domain takes a host name such as viewer.example.com, not "${domain}"`);
+ if (!password || password.length < MIN_PASSWORD) throw new Error(`a viewer on a domain needs MOTLAB_VIEWER_PASSWORD set to a password of at least ${MIN_PASSWORD} characters`);
+ const digest = s => createHash('sha256').update(String(s)).digest();
+ const want = digest(password), token = randomBytes(32).toString('hex'), sessions = new Map(), failures = [];
+ mkdirSync(dirname(tokenFile), { recursive: true });
+ writeFileSync(tokenFile, token, { mode: 0o600 });
+ const same = (a, b) => a.length === b.length && timingSafeEqual(a, b);
+ const cookieOf = req => /(?:^|;\s*)motlab_session=([0-9a-f]{64})/.exec(req.headers.cookie || '')?.[1];
+ const signedIn = req => {
+ const id = cookieOf(req), until = id && sessions.get(id);
+ if (until && until > Date.now()) return true;
+ if (id) sessions.delete(id);
+ const t = req.headers['x-motlab-token'];
+ return typeof t === 'string' && same(digest(t), digest(token));
+ };
+ const local = host => /^(127\.0\.0\.1|localhost|\[::1\]):\d+$/.test(host);
+
+ return {
+ domain,
+ close() { try { if (readFileSync(tokenFile, 'utf8').trim() === token) rmSync(tokenFile, { force: true }); } catch {} },
+ // Whether a POST may write: from this host's own page (http:// on 127.0.0.1, https:// on the domain), or from a
+ // motlab command, which sends no Origin.
+ writeAllowed(req) {
+ const host = req.headers.host || '', origin = req.headers.origin;
+ if (host.toLowerCase() === domain.toLowerCase()) return !origin || origin === `https://${host}`;
+ return local(host) && (!origin || origin === `http://${host}`);
+ },
+ // Handles the login routes and turns away a request without a session. Returns true when it answered.
+ async guard(req, res, path, readBody) {
+ if (path === '/login' && req.method === 'GET') return page(res, req, 200);
+ if (path === '/login' && req.method === 'POST') {
+ const now = Date.now();
+ while (failures.length && failures[0] < now - 60000) failures.shift();
+ if (failures.length >= TRIES) return page(res, req, 429, 'wait');
+ const form = new URLSearchParams(await readBody(req)), next = safeNext(form.get('next'));
+ if (!same(digest(form.get('password') ?? ''), want)) {
+ failures.push(now);
+ await new Promise(r => setTimeout(r, 400));
+ return page(res, req, 401, 'wrong', next);
+ }
+ const id = randomBytes(32).toString('hex');
+ sessions.set(id, now + DAYS * 864e5);
+ res.writeHead(303, { Location: next, 'Set-Cookie': `${COOKIE}=${id}; Path=/; Max-Age=${DAYS * 86400}; HttpOnly; Secure; SameSite=Strict`, 'Cache-Control': 'no-store' });
+ res.end();
+ return true;
+ }
+ if (path === '/logout' && req.method === 'POST' && this.writeAllowed(req)) {
+ sessions.delete(cookieOf(req));
+ res.writeHead(303, { Location: '/login', 'Set-Cookie': `${COOKIE}=; Path=/; Max-Age=0; HttpOnly; Secure; SameSite=Strict` }).end();
+ return true;
+ }
+ if (signedIn(req)) return false;
+ // Just enough for `motlab edit` and `stop` to recognise a viewer they have no token for; no pid or folder.
+ if (path === '/__motlab/editor') { res.writeHead(200, { 'Content-Type': 'application/json' }).end(JSON.stringify({ motlab: 'editor', locked: true })); return true; }
+ if (req.method === 'GET' && (req.headers.accept || '').includes('text/html')) {
+ res.writeHead(302, { Location: `/login?next=${encodeURIComponent(path)}`, 'Cache-Control': 'no-store' }).end();
+ return true;
+ }
+ res.writeHead(401, { 'Content-Type': 'text/plain' }).end('sign in first');
+ return true;
+ },
+ };
+}
+
+// Only a path on this site, so the login cannot be used to send someone elsewhere.
+const safeNext = n => typeof n === 'string' && /^\/(?!\/)[^\s\\]*$/.test(n) ? n : '/';
+
+const TEXT = {
+ id: { title: 'Masuk ke motlab', password: 'Kata sandi', go: 'Masuk', wrong: 'Kata sandi salah.', wait: 'Terlalu banyak percobaan. Coba lagi sebentar lagi.' },
+ en: { title: 'Sign in to motlab', password: 'Password', go: 'Sign in', wrong: 'Wrong password.', wait: 'Too many tries. Try again in a minute.' },
+};
+const esc = s => String(s).replace(/[&<>"']/g, c => `&#${c.charCodeAt(0)};`);
+
+// The login page, in Indonesian when the browser asks for it first, else English. Colours and type follow DESIGN.md.
+function page(res, req, code, problem, next) {
+ const t = /^\s*id\b/i.test(req.headers['accept-language'] || '') ? TEXT.id : TEXT.en, lang = t === TEXT.id ? 'id' : 'en';
+ next ??= safeNext(new URL(req.url, 'http://x').searchParams.get('next'));
+ res.writeHead(code, { 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'no-store', 'X-Frame-Options': 'DENY', 'Content-Security-Policy': "default-src 'none'; style-src 'unsafe-inline'; form-action 'self'; frame-ancestors 'none'" });
+ res.end(`<!doctype html><html lang="${lang}"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>${t.title}</title>
+<style>
+ :root { --text: #1f1f1e; --muted: #666561; --edge: #dcdcda; --canvas: #ececec; --red: #b8322a; --blue: #2c6fe0; }
+ * { box-sizing: border-box; }
+ body { margin: 0; min-height: 100vh; display: grid; place-items: center; padding: 16px; background: var(--canvas); color: var(--text); font: 14px/1.4 ui-sans-serif, system-ui, "Segoe UI", sans-serif; }
+ main { width: min(340px, 100%); padding: 24px; border-radius: 12px; background: #fff; box-shadow: 0 8px 28px rgba(0,0,0,.12); }
+ h1 { margin: 0 0 16px; font-size: 16px; font-weight: 600; }
+ label { display: block; margin-bottom: 6px; color: var(--muted); }
+ input { width: 100%; height: 40px; padding: 0 10px; border: 1px solid var(--edge); border-radius: 8px; font: inherit; color: inherit; }
+ input:focus-visible, button:focus-visible { outline: 2px solid var(--blue); outline-offset: 2px; }
+ button { width: 100%; height: 40px; margin-top: 12px; border: 0; border-radius: 8px; background: var(--text); color: #fff; font: inherit; font-weight: 600; cursor: pointer; }
+ button:hover { background: #3a3a38; }
+ p { margin: 10px 0 0; color: var(--red); }
+</style></head><body><main>
+<h1>${t.title}</h1>
+<form method="post" action="/login">
+ <input type="hidden" name="next" value="${esc(next)}">
+ <label for="pw">${t.password}</label>
+ <input id="pw" name="password" type="password" autocomplete="current-password" required autofocus${problem ? ' aria-describedby="problem"' : ''}>
+ <button type="submit">${t.go}</button>
+ ${problem ? `<p id="problem" role="alert">${t[problem]}</p>` : ''}
+</form></main></body></html>`);
+ return true;
+}
diff --git a/src/cli.js b/src/cli.js
index afd0c45..ad8c276 100644
--- a/src/cli.js
+++ b/src/cli.js
@@ -11,10 +11,12 @@ 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] [--parallel 3]
+ motlab render <project> [out.mp4] [--scale 2] [--only 3] [--parallel 3] [--qp 22] [--codec hevc]
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
+ project; the menu lists the projects in this folder.
+ --domain viewer.example.com serves it behind a reverse proxy,
+ with the login password in MOTLAB_VIEWER_PASSWORD
motlab edit [project] open a project in the viewer (starting it if needed) and print its
address. [project] is a folder with project.json, or a project
file in it (video/storyboard.json). Clicks go to selection.json
@@ -22,7 +24,8 @@ const USAGE = `motlab: render a canvas page (canvas #c, renderAt(t), TOTAL, read
motlab stills <page.html> <outDir> <t1> <t2> ... [--scale 1] [--format png|jpg]
motlab video <page.html> <out.mp4> [--fps 24] [--scale 2] [--audio file] [--encoder auto|hw|sw] [--workers N]
motlab events <page.html> <out.json>
- motlab doctor check Node, Chrome, ffmpeg and the skill's Python packages
+ motlab help this list (also motlab --help or -h)
+ motlab doctor check Node, Chrome, ffmpeg, the skill's Python packages and earshot
motlab setup [--skill claude|agents|antigravity|hermes|...] [--skill-dir <dir>] [--link] [--update] [--dry-run]
copy the skills to agent folders (after npm install -g; default
Claude Code), and add the command when npm's folder is not on
@@ -81,25 +84,26 @@ 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' }, parallel: { type: 'string' },
+ only: { type: 'string' }, domain: { 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;
- if (v.help || !mode) { console.log(USAGE); return v.help ? 0 : 1; }
+ if (v.help || mode === 'help' || !mode) { console.log(USAGE); return v.help || mode ? 0 : 1; } // motlab help, --help or -h
if (mode === 'doctor') return doctor();
if (mode === 'update') return update({ dryRun: v['dry-run'] });
if (mode === 'uninstall') return uninstall({ dryRun: v['dry-run'], yes: v.yes });
// --foreground is the server itself (what start runs in the background); it runs until it is stopped.
- if (mode === 'start') return v.foreground ? (await startEditor(page) === 'joined' ? 0 : new Promise(() => {})) : (await startViewer(), 0);
+ if (mode === 'start') return v.foreground ? (await startEditor(page, undefined, { domain: v.domain }) === 'joined' ? 0 : new Promise(() => {})) : (await startViewer({ domain: v.domain }), 0);
if (mode === 'edit') { await openInViewer(page); return 0; }
if (mode === 'stop') { await stopViewer(); return 0; }
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), parallel: num('parallel', v.parallel, { min: 1, int: true }) });
+ 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 }),
+ qp: num('qp', v.qp, { min: 0, int: true }), codec: oneOf('codec', v.codec, ['auto', 'h264', 'hevc']) });
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)`);
+ if (!['stills', 'video', 'events'].includes(mode)) throw new Error(`unknown mode "${mode}" (render, start, edit, stop, restart, stills, video, events, doctor, setup, update, uninstall or help)`);
if (!page || !out) throw new Error(`${mode} needs a page and an output path`);
const common = { page, root: v.root, chrome: v.chrome };
diff --git a/src/doctor.js b/src/doctor.js
index 4973837..d10a883 100644
--- a/src/doctor.js
+++ b/src/doctor.js
@@ -47,9 +47,24 @@ export function checks() {
out.push({ name: 'Python packages (numpy, scipy, Pillow)', ok: !missing.length, optional: true, detail: missing.length ? `missing: ${missing.join(', ')}` : '',
fix: `${py.p} -m pip install -r "${fileURLToPath(new URL('../skills/motlab/requirements.txt', import.meta.url))}"` }); // the full path: an npm install is not the current folder
}
+ out.push(earshotCheck());
return out;
}
+// earshot (github.com/Leonxlnx/earshot, MIT) lets the agent listen: the skill uses it to pick sounds and check a mix
+// when it is there. Optional and never installed here: it needs Python with torch and about 1.1 GB of models.
+// `earshot doctor` answers in about a second without loading the models and says whether they are downloaded.
+export function earshotCheck(runCmd = (cmd, args) => spawnSync(cmd, args, { encoding: 'utf8', shell: false, timeout: 30000 })) {
+ const name = 'earshot (optional: lets the agent listen to sound)';
+ const r = runCmd('earshot', ['doctor']);
+ if (r.error || r.status !== 0) return { name, ok: false, optional: true, detail: 'not installed', fix: 'install it from https://github.com/Leonxlnx/earshot if you want the agent to listen (Python, about 1.1 GB of models)' };
+ let cached = null;
+ try { cached = Object.values(JSON.parse(/^models_cached:\s*(\{.*\})\s*$/m.exec(r.stdout)[1])); } catch {}
+ if (cached?.length && cached.every(Boolean)) return { name, ok: true, optional: true, detail: 'models downloaded' };
+ return { name, ok: false, optional: true, detail: cached ? 'installed, models not downloaded' : 'installed, its doctor output was not understood',
+ fix: 'earshot doctor --fetch (downloads about 1.1 GB of models)' };
+}
+
export function doctor(log = console.log) {
const list = checks();
for (const c of list) {
diff --git a/src/editor.html b/src/editor.html
index f3a8873..fd451af 100644
--- a/src/editor.html
+++ b/src/editor.html
@@ -643,7 +643,8 @@ try {
// 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.
// 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');
+ // A layer transition's module is loaded here too, so a missing file or a missing draw() shows on opening.
+ const { createMixer, isTransitionFile, layerFrames, layerProgress, loadLayer, loadTransition, transitionHead, transitionOverlap, transitionProgress, transitionTail } = 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) => {
@@ -652,6 +653,12 @@ try {
if (s.transition) {
if (!i) throw hint(L('firstTransition'));
try {
+ if (s.transition.layer !== undefined) {
+ if (s.transition.type !== undefined) throw new Error('a transition has "type" or "layer", not both');
+ const mod = await loadLayer(new URL(s.transition.layer, location.href).href, s.transition.layer);
+ s.transition = { ...s.transition, mod, n: Math.max(1, Math.round((Number(s.transition.duration) || 0) * fps)) };
+ return s;
+ }
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);
@@ -685,18 +692,27 @@ try {
const n = Math.min(12, Math.max(1, Math.round(s.dur / 2)));
for (let k = 0; k < n; k++) s.thumbs.push(await thumbAt(s, (k + 0.5) / n * s.dur));
}
- // With a transition, a scene starts that many frames before the one before it ends: the two overlap.
+ // With a shader transition, a scene starts that many frames before the one before it ends: the two overlap. A layer
+ // transition is drawn over a hard cut, so the scenes do not overlap.
let total = 0;
for (const [i, s] of scenes.entries()) {
- const n = s.transition?.n || 0, out = scenes[i + 1]?.transition?.n || 0; // the renderer's rule: a scene keeps at least one frame of its own
+ const n = transitionHead(s.transition), out = transitionTail(scenes[i + 1]?.transition); // the renderer's rule: a scene keeps at least one frame of its own
if (n + out >= Math.round(s.dur * fps)) throw hint(L('tooShort', i + 1, Math.round(s.dur * fps), n, out));
- s.start = total - n / fps; total = s.start + s.dur;
+ s.start = total - transitionOverlap(s.transition) / fps; total = s.start + s.dur;
}
const sceneAt = time => scenes.findLast(s => s.start <= time + 1e-9);
const pairAt = time => { // inside a transition: the scene it comes from, and the frame of the transition
- const s = sceneAt(time), n = s.transition?.n, k = frameIn(s, time);
+ const s = sceneAt(time), n = transitionOverlap(s.transition), k = frameIn(s, time);
return n && k < n ? { from: scenes[scenes.indexOf(s) - 1], k, n } : null;
};
+ // Inside a layer transition: the layer, its frame k of n and its progress, on either side of the cut.
+ const layerAt = (s, frame) => {
+ const i = scenes.indexOf(s), into = s.transition, out = scenes[i + 1]?.transition;
+ if (into?.layer && frame < layerFrames(into.n).after) { const k = layerFrames(into.n).before + frame; return { tr: into, from: i, k, n: into.n, p: layerProgress(k, into.n) }; }
+ const frames = Math.round(s.dur * fps), before = out?.layer ? layerFrames(out.n).before : 0;
+ if (before && frame >= frames - before) { const k = frame - (frames - before); return { tr: out, from: i + 1, k, n: out.n, p: layerProgress(k, out.n) }; }
+ return null;
+ };
const frameIn = (s, time) => Math.max(0, Math.min(Math.floor((time - s.start) * fps + 1e-6), Math.round(s.dur * fps) - 1)); // same frame grid as the render
const ac = new AudioContext();
@@ -771,16 +787,17 @@ try {
const at = (k + 0.5) * tw / pps, b = s.thumbs[Math.min(s.thumbs.length - 1, Math.floor(at / s.dur * s.thumbs.length))];
g.drawImage(b, x + k * tw, RULER, tw + 0.5, VH);
}
- const ow = s.transition ? s.transition.n / fps * pps : 0; // the overlap with the scene before, which holds the bowtie
+ const ow = transitionOverlap(s.transition) / fps * pps; // the overlap with the scene before, which holds the bowtie
const bx = Math.min(Math.max(x + ow, 0), x + cw - 24); // the scene number stays in view while the scene is
g.fillStyle = 'rgba(0,0,0,.55)'; g.beginPath(); g.roundRect(bx + 6, RULER + 6, 18, 16, 5); g.fill();
g.fillStyle = '#fff'; g.textAlign = 'center'; g.fillText(i + 1, bx + 15, RULER + 14.5); g.textAlign = 'left';
g.restore();
g.lineWidth = 2; g.strokeStyle = sel && !sel.audio && sel.sceneIndex === i + 1 ? BLUE : 'rgba(0,0,0,.08)';
g.beginPath(); g.roundRect(x + 1, RULER + 1, cw - 2, VH - 2, 7); g.stroke();
- if (s.transition) { // where the scene before turns into this one: a bowtie on the overlap, as in video editors
- const cx = x + ow / 2, cy = RULER + VH / 2, r = Math.max(5, Math.min(9, ow / 2));
- g.fillStyle = 'rgba(255,255,255,.35)'; g.fillRect(x, RULER + 2, ow, VH - 4);
+ if (s.transition) { // where the scene before turns into this one: a bowtie on the overlap (or on the cut, for a layer), as in video editors
+ const lw = s.transition.layer ? s.transition.n / fps * pps : ow, lx = s.transition.layer ? x - layerFrames(s.transition.n).before / fps * pps : x;
+ const cx = s.transition.layer ? x : x + ow / 2, cy = RULER + VH / 2, r = Math.max(5, Math.min(9, lw / 2));
+ g.fillStyle = 'rgba(255,255,255,.35)'; g.fillRect(lx, RULER + 2, lw, VH - 4);
g.fillStyle = 'rgba(0,0,0,.6)'; g.beginPath(); g.roundRect(cx - r - 4, cy - 9, 2 * r + 8, 18, 5); g.fill();
g.fillStyle = '#fff'; g.beginPath(); g.moveTo(cx - r, cy - 5); g.lineTo(cx + r, cy + 5); g.lineTo(cx + r, cy - 5); g.lineTo(cx - r, cy + 5); g.closePath(); g.fill();
}
@@ -931,6 +948,11 @@ try {
} else {
await s.win.renderAt(frame / fps);
c.drawImage(s.canvas, 0, 0, clean.width, clean.height);
+ const lay = layerAt(s, frame);
+ if (lay) { // the layer over the cut, in the page's own pixels, as the render draws it
+ c.save(); c.setTransform(clean.width / s.w, 0, 0, clean.height / s.h, 0, 0);
+ try { await lay.tr.mod.draw(c, lay.p, s.w, s.h); } finally { c.restore(); }
+ }
}
cur = { s, frame }; luma = null; paint();
} finally { busy = false; rendering = []; }
@@ -1060,9 +1082,10 @@ try {
drawTimeline();
}
const spot = time => { // where a time is: its scene, the frame the preview shows there, and the transition it is in
- const s = sceneAt(time), pair = pairAt(time);
+ const s = sceneAt(time), pair = pairAt(time), lay = pair ? null : layerAt(s, frameIn(s, time));
return { time: +time.toFixed(3), scene: s.file, sceneIndex: scenes.indexOf(s) + 1, sceneTime: +(time - s.start).toFixed(3), frame: frameIn(s, time),
- transition: pair ? { type: s.transition.type, from: scenes.indexOf(pair.from) + 1, frame: pair.k, frames: pair.n } : null };
+ transition: pair ? { type: s.transition.type, from: scenes.indexOf(pair.from) + 1, frame: pair.k, frames: pair.n }
+ : lay ? { layer: lay.tr.layer, from: lay.from, frame: lay.k, frames: lay.n } : null };
};
function select(time, audio) { // a new time, scene or clip
sel = { ...spot(time), audio: audio ? { file: audio.file, start: audio.start, index: tracks.indexOf(audio) } : null };
diff --git a/src/editor.js b/src/editor.js
index 21ff50e..b6fcd64 100644
--- a/src/editor.js
+++ b/src/editor.js
@@ -9,6 +9,7 @@ import { createServer } from 'node:http';
import { copyFileSync, existsSync, mkdirSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs';
import { homedir } from 'node:os';
import { basename, dirname, isAbsolute, join, relative, sep } from 'node:path';
+import { createAccess } from './access.js';
import { projectPaths, renderProject } from './project.js';
import { pageLib, sendFile } from './server.js';
@@ -60,7 +61,13 @@ export function mergeNotes(old, { marks = [], toggled = [], deleted = [] }, v) {
const json = (res, data, code = 200) => res.writeHead(code, { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' }).end(JSON.stringify(data));
const readBody = req => new Promise((ok, no) => { let body = ''; req.on('data', d => body += d).on('end', () => ok(body)).on('error', no); });
-export function startEditor(target, port = 4173) {
+// domain: serve the viewer to that host name through a reverse proxy, behind a login (src/access.js).
+export function startEditor(target, port = 4173, { domain, password = process.env.MOTLAB_VIEWER_PASSWORD } = {}) {
+ const access = createAccess({ domain, password }); // null without a domain
+ if (access) { // the token file goes with the viewer, also on Ctrl+C or a service manager's stop
+ process.on('exit', () => access.close());
+ for (const s of ['SIGINT', 'SIGTERM']) process.once(s, () => process.exit(0));
+ }
const workspace = process.cwd(), projects = new Map(); // slug -> { root, file }
const show = dir => { // a folder as the menu shows it: inside the workspace relative to it, else from ~
const r = relative(workspace, dir), h = relative(homedir(), dir), slash = p => p.split(sep).join('/');
@@ -85,14 +92,15 @@ export function startEditor(target, port = 4173) {
let exporting = false;
const server = createServer(async (req, res) => {
const url = new URL(req.url, 'http://x'), path = decodeURIComponent(url.pathname);
+ if (access && await access.guard(req, res, path, readBody)) return; // the login, when served on a domain
// Only the viewer's own page may write: another site open in the browser (or a DNS-rebound name) gets a 403,
// so it cannot write selection.json, add a project or start an export. `motlab edit` sends no Origin.
if (req.method === 'POST') {
const host = req.headers.host || '', origin = req.headers.origin;
const local = /^(127\.0\.0\.1|localhost|\[::1\]):\d+$/.test(host);
- if (!local || (origin && origin !== `http://${host}`)) return res.writeHead(403).end('forbidden');
+ if (access ? !access.writeAllowed(req) : !local || (origin && origin !== `http://${host}`)) return res.writeHead(403).end('forbidden');
}
- if (path === '/__motlab/editor') return json(res, { motlab: 'editor', pid: process.pid, workspace }); // how motlab edit/stop find this viewer
+ if (path === '/__motlab/editor') return json(res, { motlab: 'editor', pid: process.pid, workspace, domain: access?.domain }); // how motlab edit/stop find this viewer
if (req.method === 'POST' && path === '/__motlab/stop') { // motlab stop: end a running export (its Chrome closes), then exit
res.writeHead(204).end();
if (exporting) exporting.abort();
@@ -206,6 +214,7 @@ export function startEditor(target, port = 4173) {
server.on('listening', () => {
const n = list().length;
console.log(`Editor: http://127.0.0.1:${port}${opened ? `/p/${opened}/ (${projects.get(opened).file})` : ''}`);
+ if (access) console.log(` also on https://${access.domain}/ through the reverse proxy, behind the password in MOTLAB_VIEWER_PASSWORD`);
console.log(` ${n} project${n === 1 ? '' : 's'} in the menu: ${workspace}, and the ones opened before`);
});
server.listen(port, '127.0.0.1');
diff --git a/src/page/runtime.js b/src/page/runtime.js
index e776466..70d50df 100644
--- a/src/page/runtime.js
+++ b/src/page/runtime.js
@@ -55,7 +55,12 @@
async function openSink(o) {
if (o.mux === 'raw') {
let parts = [], size = 0;
- const flush = async () => { if (!size) return; const blob = new Blob(parts); parts = []; size = 0; await post(`${o.base}/append?id=${o.sink}`, blob); };
+ const flush = async () => { // one ArrayBuffer per upload, not a Blob, for the reason in still()
+ if (!size) return;
+ const all = new Uint8Array(size); let at = 0;
+ for (const p of parts) { all.set(p, at); at += p.length; }
+ parts = []; size = 0; await post(`${o.base}/append?id=${o.sink}`, all);
+ };
return {
async add(chunk) { const b = new Uint8Array(chunk.byteLength); chunk.copyTo(b); parts.push(b); size += b.length; if (size >= 4 << 20) await flush(); },
finish: flush,
@@ -174,8 +179,12 @@
await window.renderAt(o.t);
const blob = await new Promise(r => canvas().toBlob(r, o.type, o.quality));
if (!blob) throw new Error('canvas.toBlob returned nothing');
- await post(`${o.base}/append?id=${o.sink}`, blob);
- return blob.size;
+ // An ArrayBuffer, not the Blob: Chrome frees a Blob only when garbage collection runs, and Blob memory does not
+ // count towards the JavaScript heap, so nothing starts one. At 4K (4.6 MB PNGs) the uploads failed with "Failed to
+ // fetch" after 109 stills, about 500 MB.
+ const size = blob.size;
+ await post(`${o.base}/append?id=${o.sink}`, await blob.arrayBuffer());
+ return size;
}
window.__motlab = { info, gpu, encodeRange, probeEncoder, probeDone, still };
diff --git a/src/page/transition.html b/src/page/transition.html
index 4d7ae7c..1ced030 100644
--- a/src/page/transition.html
+++ b/src/page/transition.html
@@ -6,12 +6,14 @@
// 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 (a built-in name or
-// a .glsl path from the served root), ease, params (JSON), scale.
-import { createMixer, loadTransition, transitionProgress } from '/__motlab/transitions.js';
+// a .glsl path from the served root), ease, params (JSON), scale. With `layer` (a module's path) instead of `type`, the
+// scenes do not overlap: the first frames are the end of `from`, the rest the start of `to`, with the layer drawn on top.
+import { createMixer, layerFrames, layerProgress, loadLayer, 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, def;
+const layerPath = q.get('layer'), split = layerFrames(n);
+let A, B, mix, def, layer;
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})`);
@@ -33,14 +35,24 @@ const open = path => new Promise((ok, fail) => {
window.TOTAL = n / fps;
window.ready = (async () => {
- def = await loadTransition(type, readText); transitionProgress(0, n, easing); // a wrong name fails here, before any frame
+ if (layerPath) layer = await loadLayer('/' + layerPath.split('/').map(encodeURIComponent).join('/'), layerPath);
+ else { 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(); mix.check(def);
+ cv.width = A.c.width; cv.height = A.c.height;
+ if (!layer) { 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)));
+ if (layer) { // the scene on this side of the cut, then the layer over it in the page's own pixels
+ const side = k < split.before ? A : B;
+ await (side === A ? A.w.renderAt(offset + k / fps) : B.w.renderAt((k - split.before) / fps));
+ ctx.setTransform(1, 0, 0, 1, 0, 0); ctx.drawImage(side.c, 0, 0, cv.width, cv.height);
+ const s = Number(scale) || 1; ctx.save(); ctx.setTransform(s, 0, 0, s, 0, 0);
+ try { await layer.draw(ctx, layerProgress(k, n), cv.width / s, cv.height / s); } finally { ctx.restore(); }
+ return;
+ }
await A.w.renderAt(offset + k / fps); await B.w.renderAt(k / fps);
ctx.drawImage(mix.draw(def, A.c, B.c, transitionProgress(k, n, easing), params), 0, 0, cv.width, cv.height);
};
diff --git a/src/page/transitions.js b/src/page/transitions.js
index aa6c8ce..3c0b211 100644
--- a/src/page/transitions.js
+++ b/src/page/transitions.js
@@ -67,6 +67,26 @@ export async function loadTransition(type, readText) {
return isTransitionFile(type) ? parseTransition(await readText(type), type) : findTransition(type);
}
+// A layer transition is a module drawn over a hard cut: shapes that cover the frame and uncover the next scene, such
+// as the asset skill's transition.js. It is set as { "layer": "path/to/transition.js", "duration": 0.6 } and exports
+// draw(ctx, p, W, H), which draws in the page's own pixels (W x H, before ?scale=). The scenes do not overlap: the layer
+// covers the last `before` frames of the scene before and the first `after` frames of the next, and p runs from 0 to 1
+// over them, reaching 0.5 at the cut. A shader transition overlaps the two scenes for all n frames instead.
+export const layerFrames = n => ({ before: n >> 1, after: n - (n >> 1) });
+export const layerProgress = (k, n) => (k + 0.5) / n;
+// The frames a transition takes from the start of the scene it leads into, and from the end of the scene before it.
+export const transitionHead = tr => !tr ? 0 : tr.layer ? layerFrames(tr.n).after : tr.n;
+export const transitionTail = tr => !tr ? 0 : tr.layer ? layerFrames(tr.n).before : tr.n;
+// The frames the two scenes play at once: the length the video loses.
+export const transitionOverlap = tr => !tr || tr.layer ? 0 : tr.n;
+
+// A layer module, from a page: path is from the served root (the render) or relative to the viewer's page.
+export async function loadLayer(url, name = url) {
+ const m = await import(url);
+ if (typeof m.draw !== 'function') throw new Error(`layer ${name} has no draw(ctx, p, W, H) export`);
+ return m;
+}
+
// 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') {
diff --git a/src/project.js b/src/project.js
index 1eb387a..f04dcc6 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, isTransitionFile, parseTransition, transitionProgress } from './page/transitions.js';
+import { findTransition, isTransitionFile, parseTransition, transitionHead, transitionProgress, transitionTail } from './page/transitions.js';
import { cacheDir } from './probe.js';
import { renderVideo } from './render.js';
@@ -22,7 +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. root: the project folder, where a transition's .glsl file is checked.
+// at least 1. The viewer applies the same rule. root: the project folder, where a transition's .glsl file or layer
+// module is checked. A layer transition ({ layer, duration }) is drawn over a hard cut instead of mixing two scenes.
export function projectScenes(p, root) {
return p.scenes.map((s, i) => {
const scene = typeof s === 'string' ? { file: s } : { ...s };
@@ -32,7 +33,12 @@ export function projectScenes(p, root) {
if (tr) {
scene.transition = { ease: 'inOutCubic', params: {}, ...tr, n: Math.max(1, Math.round((Number(tr.duration) || 0) * p.fps)) };
try {
- if (!isTransitionFile(tr.type)) scene.transition.type = findTransition(tr.type).name;
+ if (tr.layer !== undefined) {
+ if (tr.type !== undefined) throw new Error('a transition has "type" (a shader that mixes the two scenes) or "layer" (a module drawn over the cut), not both');
+ if (!/\.m?js$/i.test(String(tr.layer))) throw new Error(`the layer ${tr.layer} must be a .js module that exports draw(ctx, p, W, H)`);
+ if (root && !existsSync(join(root, tr.layer))) throw new Error(`the layer file ${tr.layer} does not exist`);
+ }
+ else 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);
@@ -61,10 +67,16 @@ 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, parallel, log = console.log, signal }) { // signal: an AbortSignal that stops the render
+// qp and codec: the file size against quality (docs/rendering.md#file-size). They come from the options, else from
+// "qp" and "codec" in project.json, so the viewer's Export uses them too, else the encoder's defaults.
+export async function renderProject({ dir, out, scale, only, parallel, qp, codec, 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';
+ const p = JSON.parse(readFileSync(file, 'utf8'));
+ qp ??= p.qp; codec ??= p.codec;
+ if (qp !== undefined && !(Number.isInteger(qp) && qp >= 0 && qp <= 51)) throw new Error(`qp must be a whole number from 0 to 51, not ${JSON.stringify(qp)}`);
+ if (codec !== undefined && !['auto', 'h264', 'hevc'].includes(codec)) throw new Error(`codec must be auto, h264 or hevc, not ${JSON.stringify(codec)}`);
+ const tmp = mkdtempSync(join(tmpdir(), 'motlab-project-')), partial = out + '.part';
try {
// One MP4 per scene. The first scene picks the encoder and the rest are forced to the same one, so the parts
// can be joined without re-encoding.
@@ -114,9 +126,9 @@ export async function renderProject({ dir, out, scale, only, parallel, log = con
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 k = key({ kind: 'scene', file: scene.file, hash: hashes[i], fps: p.fps, scale, qp, codec, version: VERSION, head: transitionHead(into), tail: transitionTail(next) });
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() }));
+ out: join(cacheRoot, k + '.mp4'), fps: p.fps, scale, qp, codec, log, signal, progress, head: transitionHead(into), tail: transitionTail(next), ...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 });
@@ -124,12 +136,12 @@ 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, 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,
+ type: next.type, glsl: isTransitionFile(next.type) ? hash(next.type) : undefined, layer: next.layer, layerHash: next.layer ? hash(next.layer) : undefined, n: next.n, ease: next.ease, params: next.params, fps: p.fps, scale, qp, codec, version: VERSION });
+ const query = new URLSearchParams({ from: scene.file, to: scenes[i + 1].file, offset: (from.pageFrames - transitionTail(next)) / p.fps, frames: next.n,
+ fps: p.fps, ...(next.layer ? { layer: next.layer } : { 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.layer ? `layer ${next.layer}` : 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, progress, ...same() }));
+ fps: p.fps, scale, qp, codec, 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.
diff --git a/src/viewer.js b/src/viewer.js
index 2267700..1622678 100644
--- a/src/viewer.js
+++ b/src/viewer.js
@@ -9,18 +9,22 @@ import { homedir } from 'node:os';
import { join } from 'node:path';
import { fileURLToPath } from 'node:url';
import { setTimeout as sleep } from 'node:timers/promises';
+import { readToken } from './access.js';
import { projectPaths } from './project.js';
const FIRST_PORT = 4173, LAST_PORT = 4190;
const BIN = fileURLToPath(new URL('../bin/motlab.js', import.meta.url));
const LOG = join(homedir(), '.motlab', 'viewer.log');
+// A viewer started with --domain asks motlab commands for the token it wrote to ~/.motlab/viewer-token.
+const headers = () => { const t = readToken(); return t ? { 'x-motlab-token': t } : {}; };
// The motlab viewer on this machine: { port, url, pid, workspace }, or null. pid and workspace are missing for a
// viewer from before motlab start existed.
async function findViewer() {
for (let port = FIRST_PORT; port <= LAST_PORT; port++) {
- const r = await fetch(`http://127.0.0.1:${port}/__motlab/editor`, { signal: AbortSignal.timeout(800) }).then(r => r.json()).catch(() => null);
- if (r?.motlab === 'editor') return { port, url: `http://127.0.0.1:${port}`, pid: r.pid, workspace: r.workspace };
+ const r = await fetch(`http://127.0.0.1:${port}/__motlab/editor`, { headers: headers(), signal: AbortSignal.timeout(800) }).then(r => r.json()).catch(() => null);
+ if (r?.locked) throw new Error(`the viewer on port ${port} runs on a domain and did not accept the token in ~/.motlab/viewer-token. Run this as the user who started it`);
+ if (r?.motlab === 'editor') return { port, url: `http://127.0.0.1:${port}`, pid: r.pid, workspace: r.workspace, domain: r.domain };
}
return null;
}
@@ -28,19 +32,19 @@ async function findViewer() {
const logTail = () => { try { return readFileSync(LOG, 'utf8').trim().split('\n').slice(-15).join('\n'); } catch { return ''; } };
// Starts the server in the background in `cwd` (the folder whose projects the menu lists) and waits until it answers.
-export async function startViewer({ cwd = process.cwd(), say = true } = {}) {
+export async function startViewer({ cwd = process.cwd(), say = true, domain } = {}) {
const running = await findViewer();
if (running) { if (say) console.log(`Viewer: ${running.url} (already running)`); return running; }
mkdirSync(join(homedir(), '.motlab'), { recursive: true });
const log = openSync(LOG, 'w');
- const child = spawn(process.execPath, [BIN, 'start', '--foreground'], { cwd, detached: true, stdio: ['ignore', log, log], windowsHide: true });
+ const child = spawn(process.execPath, [BIN, 'start', '--foreground', ...(domain ? ['--domain', domain] : [])], { cwd, detached: true, stdio: ['ignore', log, log], windowsHide: true });
closeSync(log);
let exited = null;
child.once('exit', code => { exited = code; });
child.unref();
for (const until = Date.now() + 20000; Date.now() < until;) {
const v = await findViewer();
- if (v) { if (say) console.log(`Viewer: ${v.url} (in the background; log in ${LOG})`); return v; }
+ if (v) { if (say) console.log(`Viewer: ${v.url}${domain ? ` and https://${domain}/` : ''} (in the background; log in ${LOG})`); return v; }
if (exited !== null) break;
await sleep(250);
}
@@ -52,7 +56,7 @@ export async function stopViewer({ say = true } = {}) {
if (!v) { if (say) console.log('No viewer is running.'); return null; }
if (!v.pid) throw new Error(`the viewer on ${v.url} is from an older motlab and cannot be stopped from here. Stop it with Ctrl+C where it runs`);
// Asked first, so a running export closes its Chrome; killed if it does not go.
- await fetch(`${v.url}/__motlab/stop`, { method: 'POST', signal: AbortSignal.timeout(3000) }).catch(() => {});
+ await fetch(`${v.url}/__motlab/stop`, { method: 'POST', headers: headers(), signal: AbortSignal.timeout(3000) }).catch(() => {});
for (const until = Date.now() + 10000; Date.now() < until; await sleep(200)) {
const still = await findViewer();
if (!still || still.pid !== v.pid) { if (say) console.log(`Stopped the viewer on ${v.url}.`); return v; }
@@ -64,7 +68,7 @@ export async function stopViewer({ say = true } = {}) {
export async function restartViewer() {
const old = await stopViewer({ say: false });
if (old) console.log(`Stopped the viewer on ${old.url}.`);
- return startViewer({ cwd: old?.workspace || process.cwd() });
+ return startViewer({ cwd: old?.workspace || process.cwd(), domain: old?.domain });
}
// motlab edit [project]: the project in the running viewer, after starting one if needed. Ends once the address is printed.
@@ -72,7 +76,7 @@ export async function openInViewer(target) {
const file = target ? projectPaths(target).file : null; // fails here, before starting anything, if it is not a project
const v = await findViewer() || await startViewer({ say: false });
if (!file) { console.log(`Viewer: ${v.url}`); return; }
- const r = await fetch(`${v.url}/open`, { method: 'POST', body: JSON.stringify({ file }) });
+ const r = await fetch(`${v.url}/open`, { method: 'POST', headers: headers(), body: JSON.stringify({ file }) });
if (!r.ok) throw new Error(await r.text());
console.log(`Viewer: ${v.url}${(await r.json()).url} (${file})`);
}
diff --git a/test/access.test.js b/test/access.test.js
new file mode 100644
index 0000000..e0d2631
--- /dev/null
+++ b/test/access.test.js
@@ -0,0 +1,83 @@
+// The login for a viewer served on a domain (src/access.js), on a small server that uses it as the viewer does.
+import assert from 'node:assert/strict';
+import { existsSync, mkdtempSync, readFileSync, rmSync, statSync } from 'node:fs';
+import { createServer, request } from 'node:http';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { after, test } from 'node:test';
+import { createAccess } from '../src/access.js';
+
+const dir = mkdtempSync(join(tmpdir(), 'motlab-access-'));
+after(() => rmSync(dir, { recursive: true, force: true }));
+const readBody = req => new Promise(ok => { let b = ''; req.on('data', d => b += d).on('end', () => ok(b)); });
+const PASSWORD = 'correct horse battery', DOMAIN = 'viewer.example.com';
+
+// Requests go through node:http, which sends the Host header it is given, as a reverse proxy does.
+let base;
+const call = (path, { method = 'GET', headers = {}, body } = {}) => new Promise((ok, no) => {
+ const req = request(base + path, { method, headers: { host: DOMAIN, ...headers } }, res => {
+ let text = ''; res.on('data', d => text += d).on('end', () => ok({ status: res.statusCode, headers: res.headers, text }));
+ });
+ req.on('error', no); req.end(body);
+});
+const form = fields => ({ 'content-type': 'application/x-www-form-urlencoded', body: String(new URLSearchParams(fields)) });
+const login = (password, next = '/p/demo/') => { const { body, ...type } = form({ password, next }); return call('/login', { method: 'POST', body, headers: { origin: `https://${DOMAIN}`, ...type } }); };
+
+test('a viewer on a domain needs a real host name and a long password', () => {
+ assert.equal(createAccess({}), null);
+ assert.throws(() => createAccess({ domain: DOMAIN, password: 'short', tokenFile: join(dir, 't0') }), /at least 12 characters/);
+ assert.throws(() => createAccess({ domain: 'https://viewer.example.com/', password: PASSWORD, tokenFile: join(dir, 't0') }), /host name/);
+});
+
+test('every request needs the login or the local token, whatever Host the proxy sends', async () => {
+ const tokenFile = join(dir, 'viewer-token'), access = createAccess({ domain: DOMAIN, password: PASSWORD, tokenFile });
+ if (process.platform !== 'win32') assert.equal(statSync(tokenFile).mode & 0o777, 0o600);
+ const token = readFileSync(tokenFile, 'utf8');
+ const server = createServer(async (req, res) => {
+ const path = new URL(req.url, 'http://x').pathname;
+ if (await access.guard(req, res, path, readBody)) return;
+ if (req.method === 'POST' && !access.writeAllowed(req)) return res.writeHead(403).end('forbidden');
+ res.writeHead(200).end('inside');
+ });
+ await new Promise(r => server.listen(0, '127.0.0.1', r));
+ base = `http://127.0.0.1:${server.address().port}`;
+ try {
+ // signed out: a page goes to the login, anything else is refused, also with a local Host header
+ let r = await call('/p/demo/', { headers: { accept: 'text/html' } });
+ assert.equal(r.status, 302); assert.equal(r.headers.location, '/login?next=%2Fp%2Fdemo%2F');
+ assert.equal((await call('/p/demo/project.json')).status, 401);
+ assert.equal((await call('/p/demo/project.json', { headers: { host: `127.0.0.1:${server.address().port}` } })).status, 401);
+ assert.deepEqual(JSON.parse((await call('/__motlab/editor')).text), { motlab: 'editor', locked: true });
+ assert.match((await call('/login', { headers: { 'accept-language': 'id-ID,id;q=0.9' } })).text, /Kata sandi/);
+ // a wrong password, then the right one: a session cookie that is HttpOnly, Secure and SameSite=Strict
+ r = await login('nope nope nope');
+ assert.equal(r.status, 401); assert.match(r.text, /Wrong password/);
+ r = await login(PASSWORD);
+ assert.equal(r.status, 303); assert.equal(r.headers.location, '/p/demo/');
+ const cookie = r.headers['set-cookie'][0];
+ assert.match(cookie, /^motlab_session=[0-9a-f]{64}; Path=\/; Max-Age=2592000; HttpOnly; Secure; SameSite=Strict$/);
+ const session = { cookie: cookie.split(';')[0] };
+ assert.equal((await call('/p/demo/project.json', { headers: session })).text, 'inside');
+ // writes need the page's own origin on the domain
+ const post = origin => call('/p/demo/selection', { method: 'POST', body: '{}', headers: { ...session, origin } });
+ assert.equal((await post(`https://${DOMAIN}`)).status, 200);
+ assert.equal((await post('https://evil.example')).status, 403);
+ assert.equal((await post(`http://${DOMAIN}`)).status, 403);
+ // motlab commands on the machine use the token file instead
+ assert.equal((await call('/p/demo/project.json', { headers: { 'x-motlab-token': token } })).text, 'inside');
+ assert.equal((await call('/p/demo/project.json', { headers: { 'x-motlab-token': 'f'.repeat(64) } })).status, 401);
+ // the login cannot send you to another site
+ assert.equal((await login(PASSWORD, '//evil.example/')).headers.location, '/');
+ // five wrong passwords in a minute and the next try waits, even with the right password
+ for (let i = 0; i < 4; i++) await login('nope nope nope');
+ assert.equal((await login(PASSWORD)).status, 429);
+ // signing out ends the session
+ r = await call('/logout', { method: 'POST', headers: { ...session, origin: `https://${DOMAIN}` } });
+ assert.equal(r.status, 303);
+ assert.equal((await call('/p/demo/project.json', { headers: session })).status, 401);
+ } finally {
+ await new Promise(r => server.close(r));
+ access.close();
+ }
+ assert.ok(!existsSync(tokenFile), 'the token file is removed when the viewer ends');
+});
diff --git a/test/cli.test.js b/test/cli.test.js
new file mode 100644
index 0000000..29f7dea
--- /dev/null
+++ b/test/cli.test.js
@@ -0,0 +1,18 @@
+import assert from 'node:assert/strict';
+import { spawnSync } from 'node:child_process';
+import { test } from 'node:test';
+import { fileURLToPath } from 'node:url';
+
+const bin = fileURLToPath(new URL('../bin/motlab.js', import.meta.url));
+const run = (...args) => spawnSync(process.execPath, [bin, ...args], { encoding: 'utf8' });
+
+test('motlab help, --help and -h print the commands and succeed; no command prints them and fails', () => {
+ for (const args of [['help'], ['--help'], ['-h']]) {
+ const r = run(...args);
+ assert.equal(r.status, 0, args.join(' '));
+ assert.match(r.stdout, /motlab render <project>/);
+ assert.match(r.stdout, /Engine folder: /);
+ }
+ assert.equal(run().status, 1);
+ assert.match(run('nope').stderr + run('nope').stdout, /unknown mode "nope" .* or help/);
+});
diff --git a/test/doctor.test.js b/test/doctor.test.js
new file mode 100644
index 0000000..b04ccb1
--- /dev/null
+++ b/test/doctor.test.js
@@ -0,0 +1,18 @@
+import assert from 'node:assert/strict';
+import { test } from 'node:test';
+import { earshotCheck } from '../src/doctor.js';
+
+// earshot doctor prints lines of "key: value"; models_cached is JSON (from earshot 0.4.1 on the test laptop)
+const out = cached => ({ status: 0, stdout: `precision: bf16\nmodels_cached: ${JSON.stringify(cached)}\nproblems: []\n` });
+
+test('earshot is an optional check: missing, installed without models, or ready', () => {
+ const missing = earshotCheck(() => ({ error: new Error('spawnSync earshot ENOENT'), status: null }));
+ assert.deepEqual([missing.ok, missing.optional, missing.detail], [false, true, 'not installed']);
+ assert.match(missing.fix, /github\.com\/Leonxlnx\/earshot/);
+ const noModels = earshotCheck(() => out({ 'laion/larger_clap_general': true, 'MIT/ast-finetuned-audioset-10-10-0.4593': false }));
+ assert.deepEqual([noModels.ok, noModels.detail], [false, 'installed, models not downloaded']);
+ assert.match(noModels.fix, /earshot doctor --fetch/);
+ const ready = earshotCheck(() => out({ 'laion/larger_clap_general': true, 'MIT/ast-finetuned-audioset-10-10-0.4593': true }));
+ assert.deepEqual([ready.ok, ready.optional, ready.detail], [true, true, 'models downloaded']);
+ assert.equal(earshotCheck(() => ({ status: 0, stdout: 'something else' })).detail, 'installed, its doctor output was not understood');
+});
diff --git a/test/motion.test.js b/test/motion.test.js
index da9d259..b40a5e3 100644
--- a/test/motion.test.js
+++ b/test/motion.test.js
@@ -4,7 +4,7 @@ import { cubicBezier, ease, spring, stagger, tween } from '../src/page/motion.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 { findTransition, isTransitionFile, layerFrames, layerProgress, parseTransition, transitionHead, transitionNames, transitionOverlap, transitionProgress, transitionTail } 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}`);
@@ -91,3 +91,17 @@ vec4 transition(vec2 uv) { return mix(getFromColor(uv), getToColor(uv), progress
assert.throws(() => projectScenes(p, dir), /scene 2 .*t\/gone\.glsl does not exist/);
} finally { rmSync(dir, { recursive: true, force: true }); }
});
+
+test('a layer transition splits its frames around the cut and takes no time from the video', () => {
+ assert.deepEqual(layerFrames(15), { before: 7, after: 8 });
+ assert.deepEqual(layerFrames(1), { before: 0, after: 1 });
+ const layer = { layer: 'swish.js', n: 15 }, shader = { type: 'fade', n: 15 };
+ assert.deepEqual([transitionHead(layer), transitionTail(layer), transitionOverlap(layer)], [8, 7, 0]);
+ assert.deepEqual([transitionHead(shader), transitionTail(shader), transitionOverlap(shader)], [15, 15, 15]);
+ assert.equal(layerProgress(7, 14), 0.5357142857142857); // the first frame after the cut is just past 0.5
+ const p = { fps: 30, scenes: ['a.html', { file: 'b.html', transition: { layer: 'swish.js', duration: 0.5 } }] };
+ assert.equal(projectScenes(p)[1].transition.n, 15);
+ p.scenes[1].transition.type = 'fade';
+ assert.throws(() => projectScenes(p), /"type" .* or "layer" .*, not both/);
+ assert.throws(() => projectScenes({ fps: 30, scenes: ['a.html', { file: 'b.html', transition: { layer: 'swish.glsl', duration: 0.5 } }] }), /must be a \.js module/);
+});
diff --git a/test/render.test.js b/test/render.test.js
index 8e3ac47..6e3d03e 100644
--- a/test/render.test.js
+++ b/test/render.test.js
@@ -142,6 +142,30 @@ 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 layer transition is drawn over a hard cut, in the page pixels, without shortening the video', async () => {
+ const proj = join(dir, 'layer'), flat = (name, colour) => writeFileSync(join(proj, name), `<!doctype html><canvas id="c"></canvas><script>
+ const s = +(new URLSearchParams(location.search).get('scale') || 1), cv = document.getElementById('c'), c = cv.getContext('2d');
+ cv.width = 320 * s; cv.height = 180 * s; window.TOTAL = 1; window.ready = Promise.resolve(true);
+ window.renderAt = () => { c.fillStyle = '${colour}'; c.fillRect(0, 0, cv.width, cv.height); };</script>`);
+ mkdirSync(proj); flat('a.html', '#000'); flat('b.html', '#fff');
+ // a red bar from the left edge, p of the page's 320 px wide
+ writeFileSync(join(proj, 'bar.js'), 'export function draw(ctx, p, W, H) { ctx.fillStyle = "#f00"; ctx.fillRect(0, 0, p * W, H); }\n');
+ writeFileSync(join(proj, 'project.json'), JSON.stringify({ fps: 30, scenes: ['a.html', { file: 'b.html', transition: { layer: 'bar.js', duration: 0.5 } }] }));
+ const out = join(dir, 'layer.mp4');
+ await renderProject({ dir: proj, out, scale: 2, ...quiet }); // at scale 2 the bar must still be p of the width
+ const v = await probeVideo(out);
+ assert.equal(v.frames, 60); // two scenes of 30 frames, nothing shared
+ assert.deepEqual([v.width, v.height], [640, 360]);
+ const rgb = (f, x) => meanRgb(out, `16:16:${x}:172`, f);
+ // 15 frames: the last 7 of a (frames 23 to 29) and the first 8 of b (30 to 37); frame 26 is k = 3, p = 0.233
+ assert.ok(near(rgb(20, 600), [0, 0, 0], 8), `frame 20 is ${rgb(20, 600)}`);
+ assert.ok(near(rgb(26, 40), [255, 0, 0], 16), `frame 26 left is ${rgb(26, 40)}`);
+ assert.ok(near(rgb(26, 400), [0, 0, 0], 8), `frame 26 right is ${rgb(26, 400)}`);
+ assert.ok(near(rgb(33, 400), [255, 0, 0], 16), `frame 33 at 0.62 of the width is ${rgb(33, 400)}`); // k = 10, p = 0.7
+ assert.ok(near(rgb(33, 600), [255, 255, 255], 8), `frame 33 right is ${rgb(33, 600)}`);
+ assert.ok(near(rgb(40, 40), [255, 255, 255], 8), `frame 40 is ${rgb(40, 40)}`);
+});
+
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);
@@ -232,6 +256,29 @@ test('project: parts render several at a time in order, and a failing part is tr
assert.ok(!existsSync(join(dir, 'parallel2.mp4')));
});
+test('project: qp from project.json reaches the encoder, a wrong one is refused, and the cache keeps each qp apart', async () => {
+ const proj = join(dir, 'qp');
+ mkdirSync(proj);
+ writeFileSync(join(proj, 'a.html'), `<!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 = t => { c.fillStyle = '#123'; c.fillRect(0, 0, 320, 180); c.fillStyle = '#fc6'; c.fillRect(20 + t * 200, 40, 80, 80); };</script>`);
+ writeFileSync(join(proj, 'project.json'), JSON.stringify({ fps: 30, scenes: ['a.html'], qp: 60 }));
+ await assert.rejects(renderProject({ dir: proj, out: join(dir, 'qp0.mp4'), scale: 1, ...quiet }), /qp must be a whole number from 0 to 51, not 60/);
+ await assert.rejects(renderProject({ dir: proj, out: join(dir, 'qp0.mp4'), scale: 1, qp: 20, codec: 'av1', ...quiet }), /codec must be auto, h264 or hevc/);
+ writeFileSync(join(proj, 'b.html'), readFileSync(join(proj, 'a.html'), 'utf8'));
+ writeFileSync(join(proj, 'project.json'), JSON.stringify({ fps: 30, scenes: ['a.html', 'b.html'], qp: 30 }));
+ const logs = [];
+ await renderProject({ dir: proj, out: join(dir, 'qp30.mp4'), scale: 1, log: m => logs.push(m) });
+ const encoder = logs.find(l => l.startsWith('Encoder:'));
+ // only the hardware encoders take a QP; a runner without a GPU encodes in software at a bitrate instead
+ if (/constant QP/.test(encoder)) assert.match(encoder, /constant QP 30/);
+ // the option overrides project.json, and a part made at another qp is not reused
+ const again = [];
+ await renderProject({ dir: proj, out: join(dir, 'qp20.mp4'), scale: 1, qp: 20, only: [2], log: m => again.push(m) });
+ assert.ok(again.some(l => l.includes('Scene 1/2: a.html (no cached part, rendering it)')), again.join('\n'));
+ if (/constant QP/.test(encoder)) assert.ok(again.some(l => /constant QP 20/.test(l)), again.join('\n'));
+});
+
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);