Video as code: canvas scenes rendered with WebCodecs in headless Chrome, a review viewer, and agent skills that build the video from your references.
motlab: video as code, a review viewer and two agent skills
StaryOne87a9a050deef
diff --git a/.claude/launch.json b/.claude/launch.jsonnew file mode 100644index 0000000..6c4c758--- /dev/null+++ b/.claude/launch.json@@ -0,0 +1,11 @@+{+ "version": "0.0.1",+ "configurations": [+ {+ "name": "editor-example",+ "runtimeExecutable": "node",+ "runtimeArgs": ["bin/motlab.js", "edit", "example"],+ "port": 4173+ }+ ]+}diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.mdnew file mode 100644index 0000000..9ae2105--- /dev/null+++ b/.github/ISSUE_TEMPLATE/bug_report.md@@ -0,0 +1,28 @@+---+name: Bug report+about: A render, the viewer, the installer or the skill did something it should not+labels: bug+---++**What you ran**++```text+the exact command, or what you asked the agent and which agent it was+```++**What happened**++Paste the full output, including the error.++**What you expected**++**Machine**++- `motlab doctor` output:+- The `GPU:` line printed at the start of a render, if it was a render:+- Operating system:+- Commit (`git rev-parse --short HEAD` in the motlab folder):++**Smallest page or project that shows it**++Attach it without `out/`, or describe the scene. Remove anything private first.diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.ymlnew file mode 100644index 0000000..c85618a--- /dev/null+++ b/.github/ISSUE_TEMPLATE/config.yml@@ -0,0 +1,5 @@+blank_issues_enabled: true+contact_links:+ - name: Security vulnerability+ url: https://github.com/staryone/motlab/security/advisories/new+ about: Report it privately, not in a public issue. See SECURITY.md.diff --git a/.github/ISSUE_TEMPLATE/feature_request.md b/.github/ISSUE_TEMPLATE/feature_request.mdnew file mode 100644index 0000000..6d2324f--- /dev/null+++ b/.github/ISSUE_TEMPLATE/feature_request.md@@ -0,0 +1,13 @@+---+name: Feature request+about: Something a video needed that motlab could not do+labels: enhancement+---++**The video you were making**++What it was for, and the moment where motlab got in the way.++**What you would want**++**What you do now instead**diff --git a/.github/pull_request_template.md b/.github/pull_request_template.mdnew file mode 100644index 0000000..0f4e339--- /dev/null+++ b/.github/pull_request_template.md@@ -0,0 +1,14 @@+## What changed++One concern per pull request.++## Measured or checked++Render time before and after, what you looked at in the viewer, or the case that now works. Say what you could not check.++## Checklist++- [ ] `npm test` passes+- [ ] Docs updated in the same commit: the doc in `docs/` that owns this, README if its claims change, `SKILL.md` if the agent uses it, `CHANGELOG.md`+- [ ] `ROADMAP.md` updated if this builds or tests something listed there+- [ ] No generated output or private files committeddiff --git a/.gitignore b/.gitignorenew file mode 100644index 0000000..1d2e89e--- /dev/null+++ b/.gitignore@@ -0,0 +1,9 @@+node_modules/+out/+*.part+selection.json+selection.png+refs/+__pycache__/+selection/+example_mesh/diff --git a/.npmrc b/.npmrcnew file mode 100644index 0000000..145d3fa--- /dev/null+++ b/.npmrc@@ -0,0 +1,2 @@+save-exact=true+engine-strict=truediff --git a/.nvmrc b/.nvmrcnew file mode 100644index 0000000..b7179ae--- /dev/null+++ b/.nvmrc@@ -0,0 +1 @@+24.20.0diff --git a/AGENTS.md b/AGENTS.mdnew file mode 100644index 0000000..a42ce85--- /dev/null+++ b/AGENTS.md@@ -0,0 +1,32 @@+# AGENTS.md++Instructions for a coding agent working on this repository. If you are making a video for a user, you want the skill in [skills/motlab/SKILL.md](skills/motlab/SKILL.md), and for assets [skills/motlab-assets/SKILL.md](skills/motlab-assets/SKILL.md), not this file.++## Read first++- [README.md](README.md): what motlab is+- [docs/rendering.md](docs/rendering.md): how a render works and the measured quirks that shaped it+- [CONTRIBUTING.md](CONTRIBUTING.md): what a change must include++## Rules++1. Keep it small. Build the smallest thing that works. No new dependency, cache, validator or abstraction unless a real video needs it or the maintainer asks for it.+2. Docs move with the change, in the same commit: the doc in `docs/` that owns the behaviour, the README if its claims change, `SKILL.md` if the agent uses it, and `CHANGELOG.md`. Grep for the old claim before committing.+3. Numbers carry their measurement: what was rendered, at what size, on what machine.+4. Say what was not tested, and keep [ROADMAP.md](ROADMAP.md) honest.+5. Do not break the page contract or `project.json` for existing projects without saying so in the changelog.+6. Do not commit generated output (`out/`, renders, `selection.json`, `selection/`) or files from a user's project.+7. The viewer follows [DESIGN.md](DESIGN.md). Its UI text is in Indonesian and English: a new string goes into `TEXT` in `src/editor.html` in both.++## Checks before you finish++```bash+npm test+motlab doctor+```++For viewer changes, start `motlab edit example`, check the change in a browser and read the console. For renderer changes, time `motlab render example --scale 1` before and after.++## Installing motlab for a user++Follow [docs/install-for-agents.md](docs/install-for-agents.md).diff --git a/CHANGELOG.md b/CHANGELOG.mdnew file mode 100644index 0000000..38cc8ad--- /dev/null+++ b/CHANGELOG.md@@ -0,0 +1,103 @@+# Changelog++There are no releases yet. Changes are listed by date, newest first.++## Unreleased++### Added++- The viewer runs as a background server. `motlab start` starts it on 4173 (the next free port up to 4190 when something else has 4173) and returns, `motlab stop` ends it (asking it to exit, so a running export closes its Chrome), and `motlab restart` starts it again from the folder it ran in. `motlab edit <project>` now opens the project in the running viewer and ends, starting the viewer first when none runs, instead of staying in the terminal until Ctrl+C; `motlab start --foreground` is the old way. The server's output goes to `~/.motlab/viewer.log`. A stop request from another site's page gets a 403, like the viewer's other writes. Tried on Windows: start in 0.5 s, a second start says it is running, edit, restart from another folder (the menu kept the first folder), stop, edit with no viewer running, and a viewer on 4174 while another server held 4173.+- `motlab uninstall` removes the launchers that run motlab, the two skill folders in every agent folder from `~/.motlab/install.json` (or the agent folders the installer knows), `~/.motlab` and the encoder timings, after listing them and asking. `--yes` skips the question, `--dry-run` only lists, and without a terminal it needs `--yes`. A linked skill is removed as a link. The clone is left. A test runs it in a made-up home folder; a junction made like `--link` does was also removed without touching its target.+- `THIRD_PARTY_NOTICES.md`: the MIT licence of gl-transitions, whose shaders are copied into `src/page/transitions.js` (the MIT licence asks for its text to go with copies), and the licences of what motlab installs or loads from a CDN.+- The README shows the 19-second motlab ad (made with motlab and its skill) as a silent animated WebP, `assets/demo.webp`: 960x540, 24 fps, 4.6 MB. A GIF of the same ad was 7.3 MB at 720 px and 12 fps.+- `bench/run.mjs` takes `IGPU=1` to run only motlab's settings on Chrome's default GPU (the new `bench/motlab-igpu.mjs` leaves out `--force_high_performance_gpu`), which on the test laptop is the integrated Radeon that Remotion and HyperFrames drew on. On the Radeon motlab took 8.0 to 12.0 s at 1080p and 13.2 to 22.5 s at 4K, no slower than on the RTX 3060 except the 4K default (22.5 s against 19.4 s), so the gap to the other two stays about the same.+- `bench/run.mjs` takes `CPU=1` to run the benchmark with Chrome drawing in software (ANGLE on SwiftShader) and CPU encoders only: Remotion `--gl=swangle`, HyperFrames `--no-browser-gpu`, and motlab through the new `bench/motlab-cpu.mjs` with `--encoder sw`. On the test laptop motlab was the fastest at 1080p (19.2 s with 4 workers, HyperFrames 28.3 s, Remotion 46.7 s), but at 4K HyperFrames was faster (43.4 s against motlab's 60.7 s). The GPUs were still in the laptop; a machine without one was not tested. `docs/rendering.md` also notes that Remotion and HyperFrames drew on the integrated Radeon in the GPU benchmark, and that the saved encoder probe keeps one machine.+- `bench/run.mjs` takes `SCALE=2` to render every setting at 4K (motlab `--scale 2`, Remotion `--scale=2`, HyperFrames `--resolution landscape-4k`), with 4K reference stills, into `results-4k.json`.+- `bench/`: one scene (a turning gradient, 160 moving cards with numbers, text) rendered by motlab, Remotion 4.0.543 and HyperFrames 0.9.52 with the same Chrome, timed three times per setting, with SSIM against lossless stills. On the test laptop at 1080p and 300 frames, motlab took 9.5 to 12.6 s, HyperFrames 27.2 s and Remotion 30.7 s at their fastest settings. The table and what was not measured are in `docs/rendering.md`, and the README now shows its results as a table instead of the earlier synthetic benchmark. Not run at 4K or outside Windows.+- `motlab update`. In the clone the command runs from, it fetches the branch from `origin`, lists the new commits, fast-forwards to them and runs the new `install.js --update`, which runs `npm ci`, writes the launcher and copies the skills again to every folder they were installed in. It stops when the clone has changes to tracked files, is not on a branch, or has commits of its own. The installer now keeps where it put the skills, the launcher and `--link` in `~/.motlab/install.json`; for an install from before that file, `--update` finds the skill in the agent folders it knows. `--dry-run` prints the steps. A test runs `install.js --update --dry-run` against a made-up home folder. Tried on Windows in a test clone one commit behind a local bare repository, with a made-up home that had old skills in `~/.claude/skills` and `~/.gemini/config/skills`: the dry run, the update (both skill folders replaced, the record written, doctor Ready) and a second run that said it was up to date. The skill runs it when the user asks for an update.+- The viewer in English as well as Indonesian. It follows the browser (Indonesian when one of its languages is Indonesian, English otherwise), and the last row of the project menu switches to the other language and remembers it. All its text is one table, `TEXT`, and a test checks that every key the page uses is in it in both languages. The server's few error messages are now in English; the page shows its own text for them. Tried in the desktop app's browser on the example project: every label, tooltip, menu, the note card, the range bar and the timeline's key list read in each language, and the version name check worked. The pane was hidden, so the layout was checked through the page's text, not by eye.+- The installer puts the skills where more agents look. `--skill agents` writes to `~/.agents/skills/`, the shared folder that Codex, Cursor, OpenCode, GitHub Copilot, Gemini CLI, Amp and Windsurf read; `--skill antigravity` writes to `~/.gemini/config/skills/`, the one folder both the Antigravity App and its CLI read (the CLI's own `~/.gemini/antigravity-cli/skills/` and `~/.gemini/skills/` are not read by the App); `--skill copilot` to `~/.copilot/skills/`. Targets can be joined with commas (`--skill claude,agents,antigravity` covers all of them), and `--skill-dir <dir>` takes any other agent's folder. The folders come from each agent's docs as of November 2026. A test checks that each skill's name matches its folder and its description is at most 500 bytes.+- A second skill, `skills/motlab-assets`: reusable asset kits built as code, without AI image, video or 3D models. A kit is a folder with `tokens.json`, `style.md`, `kit.json` and each asset's source and outputs, and a video copies it into `assets/kits/`. 2D assets are SVG rendered to transparent PNG at any scale through `templates/asset.html` and `motlab stills` (a 400x600 character to 1600x2400 in 2.6 s). 2D characters are one `parts.svg` plus a `rig.json` of pivots and parents, posed in a scene with `templates/svgparts.js`. A transition is a `transition.js` layer drawn over motlab's hard cut, half in each scene, with a preview page that also writes a PNG sequence with alpha. `scripts/palette.py` reads the main colours of references and measures assets against the kit's colours; `scripts/sheet.py` tiles any images on a checker for review.+- 3D in the asset skill has two paths, and the skill asks which one. The light path needs no Blender: `scripts/mesh_export.py` writes distance-function meshes as GLB and OBJ + MTL with flat PBR colours (a two-part test mug of 194,646 vertices in 2.9 s), and `templates/model.html` renders turntable stills of a GLB through three.js (four 1024 px views in 2.6 s). The main path uses Blender: `scripts/blender/asset3d.py` bakes base colour, roughness, normal and AO maps, exports GLB, FBX and OBJ, renders a Cycles turntable with transparent background, and re-imports the files to check them. On the same mug with Blender 5.2 and an RTX 3060 Laptop: bake 7.5 s, export 1.2 to 2.3 s, four 1024 px views at 32 samples 16.8 s; the GLB, FBX and OBJ came back with the same meshes, materials and 6 texture images. `scripts/blender/check_blender.py` prints the Blender version, the Cycles device, and whether MPFB, a Blender MCP add-on and Rigify are installed.+- `install.js` installs both skills.+- Done notes. Tandai selesai in an open note, or `"done": true` written by the agent in `selection.json`, takes the note off the preview and the timeline and folds it under Selesai at the end of the Catatan list; Buka lagi opens it again. The viewer keeps the file's `done` for notes it did not change, and reads it again on focus, so the agent can mark notes while the page is open. The skill skips done notes and marks each note done once it is applied. Tried on a copy of the example in the desktop app's browser: done and reopened in the card, `done` written into the file while the page was open (picked up on the next click and on a focus event, and not overwritten), and a note in a second version left alone.+- Tooltips in the viewer's style instead of the browser's: a dark label with the shortcut in a key cap, and a list of the timeline's keys when the pointer rests on it.+- Notes in the viewer. A drag on the preview draws a box and a click marks a point, and a card opens under it to type what is wrong there; a range can get a note too. Notes stay until they are deleted, numbered across all versions of the folder, and are listed under Catatan in the side panel and as numbered tags on the timeline. A box or point shows only on the frame it was drawn on. `selection.json` gets `marks`, and each box or point note gets `selection/<n>.png`. The skill reads them and works through them by number. Tried on a copy of the example in the desktop app's browser: a box, a point, a range note and a note in a second version, reloading, opening from the list and deleting (its picture went with it).+- A time range on the viewer's timeline, marked the way video editors do it: a range tool (the button in the play toolbar, or `R`, as in Final Cut Pro) and a drag on the timeline, Shift+drag, `I` and `O` at the playhead (Premiere, Resolve, Final Cut, Frame.io), or `X` for the scene under the playhead (their Mark Clip). Its edges have blue heads like the playhead and can be dragged. It is a light blue band, a range bar next to the play toolbar shows it with Catatan and ×, Play loops inside it, and `selection.json` gets `range: { start, end, scenes }` on the frame grid. Tried on the example project in the desktop app's browser, also at 375 px wide.+- Versions in the viewer. Every `.json` file in a project folder with a `scenes` list is a version, and the second name in the header is a menu of them (`project.json` is "Utama"). "Versi baru dari ini" copies the open version to `project-<name>.json` and opens it. Export renders the open version, and `selection.json` names it as `project`. Tried on a copy of the example with a version that left out the last scene: the viewer showed 2 scenes (6.50 s) and a 720p export wrote `out/iklan-b-tiktok-720p.mp4` in 7 s.+- One viewer for many projects. Each project is at `/p/<folder>/`, and the project name in the header is a menu of the projects the viewer knows: folders with a `project.json` up to four levels under the folder it was started from, and every project opened before (`~/.motlab/recent.json`). A second `motlab edit` adds its project to the running viewer instead of starting one on the next port, and `motlab edit` works without a project. Tried with the example and a copy of it on another drive, next to two older viewers on 4173 and 4174.+- The viewer's export can be cancelled. While an export runs, the Export button is faded with a spinner and a red "Batalkan" button appears under it; pressing it closes the render's Chrome and stops ffmpeg, and the menu says "Export dibatalkan". On the example project at 4K it stopped in 0.3 s during the second scene, with no Chrome process, temp folder or output file left behind. The server route is `POST /export/cancel`, and `renderProject` and `renderVideo` take an `AbortSignal` as `signal`.++- MIT licence, and an install guide, agent install guide and docs for projects, the viewer, the command line and rendering under `docs/`.+- `install.js`: one installer for Windows, macOS and Linux. It runs `npm ci`, writes a `motlab` launcher to `~/.local/bin`, copies or links the skills to the agent skill folders you pick (see `--skill` in `docs/install.md`), and checks the machine.+- `motlab doctor`: checks Node, Chrome, ffmpeg, ffprobe, the npm packages and the skill's Python packages, and prints how to get what is missing.+- `skills/motlab/requirements.txt` for the skill's Python scripts.+- CONTRIBUTING, SECURITY, CODE_OF_CONDUCT, AGENTS.md, ROADMAP and GitHub issue and pull request templates.+- Skill: `get_sfx.py` searches Openverse for openly licensed sound effects (CC0 by default, or any licence that allows commercial use), downloads the chosen ones and keeps a `CREDITS.md` with a credit line for each. Without a key Openverse allows 20 requests a minute and 200 a day (its rate-limit headers on 2026-11-13). It retries with `certifi` when the Windows certificate store rejects a valid chain, as it did for `cdn.freesound.org` on the test laptop.+- `mix.py`: a cue can name a `role` (`hit`, `whoosh`, `riser`, `click`, `ui`, `pop`, `tap`, `key`, `tick`, `ambience`) that sets its level and anchor. The levels follow the [Clipwing real-sfx skill](https://clipwing.pro/skills/real-sfx) (hit −4, whoosh −9, riser −12, click −14, ambience −24 dBFS peak).+- `mix.py --voice <file> [--duck 9]` turns the effects down while the voice speaks. On a test mix with two seconds of synthetic speech, a whoosh under speech came out 9.0 dB lower and a click 0.6 s after it about 0.5 dB lower.+- `mix.py` warns about one recording 5 or more times in a row and about `tick`, `key` and `pop` runs closer than 66, 87 and 114 ms (the spacings in earshot's launch kit), and ends with up to five "listen by ear" moments for the user.+- Skill: when earshot is installed (its CLI or MCP tools), the agent uses it to shortlist sounds from a library by what they are, measure the mix (LUFS, true peak) and render a missing sound from code. It asks before fetching earshot's 1.1 GB of models. Without earshot nothing changes. Not tested with earshot installed: the laptop used for this change does not have it.+- Skill: `template-three.html` for real 3D with three.js 0.186.1 (a GLB or glTF model, or a placeholder box, on a shadow floor with a 2D title over it; model animations through `mixer.setTime(t)`), and `template-p5.html` for generative graphics with p5.js 2.3.4, with `references/engine-p5.md` on keeping p5 frames independent of each other. Both load the library from jsDelivr, so rendering them needs the network. Stills rendered forwards and in reverse were identical byte for byte, and a 3-scene project with both rendered at 1080p and 4K and played in the viewer, on the test laptop (RTX 3060 Laptop). Not tested with a real product model or in p5's WebGL mode.+- Transitions between scenes. A scene in `project.json` can be `{ "file": ..., "transition": { "type", "duration", "ease", "params" } }`, and the scene before turns into it through one of 11 shaders from gl-transitions 1.43.0 (MIT): `fade`, `fadecolor`, `Directional`, `directionalwipe`, `directionalwarp`, `circleopen`, `CrossZoom`, `crosswarp`, `SimpleZoom`, `LinearBlur`, `cube`. The two scenes overlap for the transition, so the video is that much shorter. The render draws it as a part of its own (`__motlab/transition.html`), the viewer mixes the same two canvases with the same code (`src/page/transitions.js`), and the timeline marks the overlap with a bowtie. On the example project, a transition frame in the viewer and in the 1080p MP4 differed by 1.37 levels of 255 on average. `selection.json` gets a `transition` field inside one.+- `/__motlab/motion.js` for scene pages: easings, CSS `cubicBezier`, exact springs (`spring({ stiffness, damping, mass, velocity })`, solved in closed form so frame order does not matter), keyframes (`tween`), `stagger` and `motionBlur`. `test/motion.test.js` checks them.+- Cut lists for talking heads: `skills/motlab/scripts/cut_pauses.py` cuts the pauses out of a recording with ffmpeg `silencedetect` into `cuts.json`, and writes the voice with the same cuts. `/__motlab/cuts.js` plays the list in a scene with alternating punch-in zoom, an eased glide between framings, a slow drift and optional dissolves. On 40 s of a talking-head take: 10 parts, 38.64 s to 33.47 s, and the cut voice was the length of the list to within 10 ms, with and without a dissolve.+- Skill: `references/motion-and-libraries.md`, with tested ways to drive GSAP 3.15.0, Anime.js 4.5.0, Lottie (lottie-web 5.13.0) and Theatre.js core 0.7.2 from `renderAt(t)`. Each moved a test box to the expected position in forward and reverse order, in stills and in the viewer.+- A banner at the top of the README (`assets/banner.svg`). Its text is outlined to paths from Syne, Instrument Sans and IBM Plex Mono (all OFL), so it looks the same on GitHub without loading fonts.++### Changed++- The git history starts again from one commit that holds the files as they are now; this changelog keeps the dated record of what changed. The repository on GitHub was created again for it, still private, and the old one is archived as a private repository under another name. An existing clone has to be cloned again. `THIRD_PARTY_NOTICES.md` now says the example project's sounds were made for this repository and are under its MIT licence.+- The README starts with the motlab ad instead of the banner, as an animated AVIF, `assets/demo.avif`: 1920x1080, 30 fps, 19.9 s, 2.1 MB, made from the 4K render with SVT-AV1 at CRF 30 (SSIM 0.994 on frame 300 against the 4K frame scaled to 1080p). The old WebP was 960x540 at 24 fps and 4.6 MB, which looked soft at the README's width. `assets/banner.svg` and `assets/demo.webp` are gone. Checked in Chrome that the AVIF plays and loops; Safari before 16.4 does not play animated AVIF.+- The README follows a shorter layout: a centered title with the install command and links, what motlab does, numbered quick start and how-it-works steps, and a FAQ in folded sections. The speed table and the docs table are unchanged. A "Watch the demo" section plays the 2-minute English walkthrough, and the ad's paragraph links to the ad with sound; both are 1080p H.264 under GitHub's 10 MB video limit, uploaded as GitHub attachments through the public `staryone/motlab-media` repository, so they play inline and stay viewable while this repository is private.+- The skill's helper scripts, the 2D and 3D templates and seven references were written again from scratch, so all of `skills/motlab` is motlab's own work under its MIT licence. The scripts keep their command lines and function names (`Puppet.create`, `GL3D.create`, the `kit`, `tracks` and `mesh_from_sdf` functions, `mix.py`'s cue format). What behaves differently: `kit.render` puts frame f at (f - 1) / fps seconds instead of spreading the frames over 0 to the end, and keys with linear interpolation through a preference, which also works in Blender 5's layered actions; `kit.load_model` also reads FBX; `mesh_from_sdf.nets` places each vertex at the average of the cell's edge crossings (classic surface nets) and returns the vertices and quads; `example_scene.py` is now a speaker with a dark band; `synth_sfx.py` makes nine sounds with lower-case names (`synth whoosh short`, `synth pop`, ...); `contact_sheet.py` keeps the stills' aspect ratio and takes `--width`; `key.py` takes `--tol`; `grid.py` shows transparent areas on magenta; `compose_into_clip.py` uses Pillow instead of OpenCV, so the skill and `motlab doctor` no longer ask for OpenCV. Checked on the test laptop: the mesher's sphere, ellipsoid, bar, union, cut and revolved shapes came out closed with outward normals (sphere volume within 0.2% of 4/3 pi); the new `mix.py` on the old cue file and sound kit printed the same placements and warnings as the old one, with samples at most 0.001 apart; `puppet.js` and `gl3d.js` (depth order, fog, depth of field, floor reflection, light band, `project`) were looked at through `motlab stills`, and the puppet's stills were identical in forward and reverse order; the four templates rendered stills; the Blender example rendered 100 frames at 1280 px and 24 samples in 402 s on Blender 5.2 (OptiX), the flat look rendered, and a frame-player page turned the frames into an MP4 with every frame closest to its own PNG (mean difference 0.22 of 255); the asset skill's `asset3d.py` baked, exported and re-imported the new example's body, and `mesh_export.py` wrote it as GLB and OBJ.+- Tested the ROADMAP items that could be tested on the Windows test laptop without downloading anything new, and moved the results into the docs that own them: footage (a 20-minute recording, variable frame rate, HEVC 8 and 10-bit, every frame checked by a number drawn into it), a 12-scene project with all 11 transitions, `cut_pauses.py` on a whole 10-minute take, three.js with a 15 MB GLB with 4K textures and with a Rigify rig, a heavy p5.js sketch and p5.js in WebGL mode, GSAP's SplitText, MorphSVG and DrawSVG, dotLottie, Lottie image and text layers, `puppet.js`, `svgparts.js` and `transition.js` through the renderer, brand fonts in all four templates, a whole Blender sequence played by a scene page, Rigify export, a Blender MCP running the asset skill's scripts, the viewer with 20 WebGL scenes and an hour of audio, the viewer's sound against the render, full screen and notes in full screen in a windowed Chrome, notes drawn with emulated touch, the project menu's walk of a home folder (0.77 s, 0.33 s the second time), `motlab update` pulling three commits from GitHub into a fake home, a 10-minute render at 4K (1,126 s, 3.16 GB, with other tests running), and the benchmark at 4K, where motlab took 13.1 to 19.4 s and the fastest of Remotion and HyperFrames 48.9 s. Two viewer tabs on one project were confirmed to lose a note, which is fixed (see Fixed). The dotLottie, GSAP plugin and Blender sequence patterns are in the skill's references. Not tested, as each needs a download or another account: Linux and macOS, a machine without a GPU, Rive, MPFB, and agents other than Claude Code.+- The skill has been used from start to finish on two real briefs: a 2-minute demo video of motlab (10 scenes) and a 19-second ad for motlab (7 scenes), both rendered to 4K MP4. Making them used the viewer's notes and ranges with a real mouse and keyboard, the agent marking notes done, and scene transitions, so ROADMAP no longer lists those or the skill itself as untested. Its longest render is now that 2-minute video instead of 480 frames. Render times for them were not recorded. ROADMAP also says that a transition as a layer over the cut already exists in the asset skill, and that `motlab update` has only fetched from GitHub, not pulled new commits from it.+- `--skill codex` now installs to `~/.agents/skills/`, the only user folder Codex's docs list. A copy in `~/.codex/skills/` from an older install can be deleted.+- Both skill descriptions are under 500 characters. The motlab one was 1,067, over the Agent Skills limit of 1,024, and Codex skips a skill whose description is too long. The skills also say "the agent" or "you" instead of "Claude", so they read right in any agent.++- `selection.json` no longer has `box` and `point`, and the viewer no longer writes `selection.png`: a box or point is now a note in `marks`, with its picture in `selection/<n>.png`. A box no longer follows the playhead to other frames, and Escape no longer removes it (Hapus in the note does). An old `selection.png` is removed on the next save.+- A project file named `project-<name>.json` now renders to `<folder>-<name>.mp4`, without the `project-` (`promo-v2.mp4`, not `promo-project-v2.mp4`). Other file names are named as before.+- `renderProject` writes the final MP4 as `<name>.mp4.part` and renames it when it is complete, as `renderVideo` already did, so a failed or cancelled export no longer leaves a half-written file in `out/`.+- `renderVideo` takes `head` and `tail` (frames to leave out at the start and the end of a page), `url` (a page the server provides) and `query`, which project transitions use.++- `mix.py`: a cue without `align` is now placed by `auto` instead of `peak`: the role's anchor, or for a cue without a role, `start` when the peak is within 60 ms of the audible start, `arrive` (first at −3 dB of the peak) when the sound is nearly full 100 ms or more before its peak, and `peak` otherwise. Struck sounds now start on the beat instead of their lead-in coming before it. Old cue files that relied on the `peak` default sound different; add `"align": "peak"` to keep the old placement. A cue needs `db` or `role`.+- The README is now a short overview. The engine reference moved to `docs/`.+- The `refs/` folder of UI screenshots is no longer in the repository or its history.++### Fixed++- Two viewer tabs on one project lost notes. Each tab saved its whole list, so a note made in one tab was dropped when the other saved, and both gave their new note the same number, the second overwriting the first one's picture. A save now names the notes the tab deleted, the server keeps the rest (`mergeNotes` in `src/editor.js`, tested in `test/notes.test.js`) and moves a new note to the next free number when its number was taken, and the page takes in the file's notes after every save and on focus. Notes get an `id`; notes from before ids are matched by number. Tried with two tabs in a windowed Chrome: notes 1 and 2 from the two tabs, each listed in both after a focus change, and a delete in one tab that the other did not undo. A running viewer keeps the old code until it is started again.+- A project whose scenes had different canvas sizes rendered without a word and made an MP4 that changed resolution partway through (1920x1080, then 1280x720, then 1920x1080 in the test). `motlab render` and Export now stop with an error that names the scene and both sizes. `test/render.test.js` checks it.+- The render put mono audio files 3 dB lower than the viewer plays them. ffmpeg's up-mix to stereo lowers a mono channel by 3 dB on each side, while WebAudio copies it to both at full level. Mono files now go to both channels at full level in the render too. On the example project (all three files are mono) the viewer, recorded off its audio graph, and the render now differ by 0.02 dB instead of 3.0 dB. Renders of existing projects with mono files get 3 dB louder. `test/render.test.js` checks the level.+- A page whose `window.ready` never resolves made `motlab render`, `video` and `stills` wait forever in silence. They still wait, since a heavy page can take long, but print "Still waiting for window.ready after 30 s" with the page and its errors.+- `template-three.html` asked for `PCFSoftShadowMap`, which three.js 0.186 has removed; it fell back to `PCFShadowMap` with a console warning for every scene. It now asks for `PCFShadowMap`, so the shadows are as before without the warning.+- `puppet.js`'s header left out the last two arguments of `draw` (`cw`, `ch`, the target canvas size).+- The viewer's Cancel button did nothing. The page asked for `export/cancel` relative to `/p/<project>/`, the server only answers `/export/cancel`, and the 404 was swallowed, so the render ran on and the button stayed on "Cancelling…". The page now asks for `/export/cancel`. Tried in the desktop app's browser on the example project at 720p: cancelled 4 s in, during scene 1, it stopped in 0.8 s with "Export cancelled" and no file left in `out/`.+- `get_sfx.py search` failed with HTTP 401 whenever `--max` was given or `--n` was above 20: without a key Openverse refuses a `page_size` above 20 ("page_size may not exceed 20 for anonymous requests"), and the script asked for 40. It now asks for pages of 20, reads up to 3 of them with `--max`, lists at most 20 sounds, and prints the API's message instead of a traceback when a request fails. Tried on 2026-11-15 with `search whoosh --max 2` and `--n 30`.+- Docs and help text that no longer matched the code. `motlab --help` said `--root` defaults to the page's folder; it is the nearest folder with a `project.json`. The viewer's message for a folder with no project is in English, like its other server messages. `motlab doctor` says `npm ci`, not `npm install`. The docs now say that stills are named with two decimals (`0.50.png`), that a 4K export is named `-2160p`, that a scene must be longer than its transitions together, that removing motlab includes `~/.motlab/`, and the viewer's export controls by their English names. The skill no longer says `compose_into_clip.py` takes an export: it takes transparent PNG frames from Blender. It changes no render or viewer behaviour beyond the one message; `npm test` passed and the message was checked on an empty folder.+- The motlab skill's Blender `kit.py` saved frames to the drive root when the output folder was relative (`frames` became `C:rames` on Windows). It now resolves the folder against the working folder.+- The 2D and 3D templates kept their preview loop (`requestAnimationFrame`) running inside the viewer, because the viewer loads scenes without `?t=`. Each loaded scene drew frames in the background while nothing played: with the old check, the three.js template drew 900 frames in 3 seconds in the desktop app's browser, and none with the new one. A template now loops only when it is opened by hand, not in an iframe.+- Viewer playback stuttered on busy scenes. It drew a frame on every display refresh, so a 30 fps video was drawn about 213 times a second in the test browser, and the first frame after a cut into a footage scene waited 161 to 221 ms for the footage to seek. The viewer now draws only when the frame changes (29 to 30 draws a second on the same project), and draws the next scene's first frame while it loads ahead, so that first frame takes 10 to 17 ms. Measured on a 16-scene 1080x1920 project with 1440x1440 footage, on the test laptop's AMD integrated GPU; see `docs/viewer.md`.++- The viewer ran out of file handles (`EMFILE: too many open files`) after many reloads of a project with large footage. The browser aborts many Range requests while it seeks, and the server left the file open for each one. Files are now sent with `stream.pipeline`, which closes the file when the request is aborted. `test/server.test.js` aborts 20 requests on a 32 MB file and checks that every file stream closes; before the fix all 20 stayed open.+- `motlab stills`, `events` and `video` now serve the nearest folder above the page with a `project.json` when `--root` is not given. Before, a scene that loaded `../` files needed `--root`, and without it `events` could write an empty list.+- A script error while the page loads now names the file, line and column. A `SyntaxError` used to come without them.+- `mix.py` reads `.ogg`, `.opus` and `.m4a` files from the library (they were skipped without a word) and prints a `WARNING` for each cue outside `0` to `--len`, which was cut off or silent before.+- `contact_sheet.py` reads `.png` stills, the default of `motlab stills`, as well as `.jpg`, and says so when the folder has none. It used to fail with "cannot write empty image" on a folder of PNGs.++### Security++- The viewer's server only accepts writes (every POST: `/selection`, `/versions`, `/export`, `/export/cancel`, `/open`) from its own page or from `motlab edit` (no Origin). A request from another origin, or with a host name other than `127.0.0.1`, `localhost` or `[::1]`, gets a 403, so another site open in the browser cannot write `selection.json` or start an export.++## 2026-11-12++- Viewer: drag a box or click a point on the preview. `selection.json` gets `box`, `point` and `frame`, and `selection.png` shows that frame with the box. The box stays when the time changes, and a click on the empty space around the preview removes it.+- Viewer: the box and point are a thin outline in the style of the Claude canvas selection box, and the + cursor turns white over dark parts of the frame.+- Viewer: the timeline zooms up to 24 px per frame, scrolls sideways and follows the playhead, and it can be hidden.+- Viewer: only three scene pages stay loaded, so long projects open and play lighter. A 45-scene project opened in about 4 seconds.+- Skill: moved to `skills/motlab`, reads the exact frame and audio point from `selection.json`, and picks a Google Font when no brand font is given.++## 2026-11-11++- First version: canvas scene pages rendered in headless Chrome with WebCodecs, a project format with audio, the web viewer with Export, the footage layer with Range requests, and the motlab skill.diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.mdnew file mode 100644index 0000000..addf650--- /dev/null+++ b/CODE_OF_CONDUCT.md@@ -0,0 +1,7 @@+# Code of conduct++motlab follows the [Contributor Covenant, version 2.1](https://www.contributor-covenant.org/version/2/1/code_of_conduct/).++In short: be respectful, assume good intent, criticise work and not people, and keep discussions on topic. Harassment, insults and personal attacks are not accepted in issues, pull requests or any other project space.++To report a problem, open a private report through [GitHub Security Advisories](https://github.com/staryone/motlab/security/advisories/new) and mark it as a conduct report, or contact the maintainer through their GitHub profile. Reports are kept confidential. The maintainer may remove comments, close threads or block accounts that break these rules.diff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdnew file mode 100644index 0000000..4c87fa1--- /dev/null+++ b/CONTRIBUTING.md@@ -0,0 +1,66 @@+# Contributing++Thanks for looking. motlab stays small on purpose: build the smallest thing that works, and add a feature when a real video needs it.++## Setup++```bash+git clone https://github.com/staryone/motlab.git+cd motlab+node install.js --link # the skills link to this checkout, so edits apply at once+motlab doctor+npm test+```++## Repository shape++```text+bin/motlab.js the command+src/ engine: CLI, Chrome over CDP, render, encoder probe, ffmpeg, project, viewer server+src/page/ code that runs inside Chrome: the render runtime, footage, cut lists, motion and transitions+src/editor.html the viewer, one file (its design is in DESIGN.md)+skills/motlab/ the video skill: SKILL.md, references, templates, helper scripts+skills/motlab-assets/ the asset skill: kits of 2D and 3D assets built as code+example/ a sample project+test/ node:test, including an end-to-end render+docs/ install, projects, viewer, command line, rendering+bench/ one scene timed in motlab, Remotion and HyperFrames+install.js the installer+assets/ the demo preview at the top of the README+```++The code is plain JavaScript ESM with JSDoc, no TypeScript and no build step, because half of it runs inside Chrome straight from disk. The only npm dependency is `mediabunny`, pinned to an exact version (`.npmrc` has `save-exact`). Think twice before adding another.++## Rules for a change++1. Docs move with the code in the same commit. A new flag, field or behaviour updates the README or the doc in `docs/` that describes it, `SKILL.md` if the agent uses it, and `CHANGELOG.md`. A doc that describes something the code does not do is a bug.+2. Numbers come with what produced them. "Faster" is not a change note; "1080p, 200 frames, 2.9 s to 2.1 s on an RTX 3060 laptop" is.+3. Say what you did not test. The [roadmap](ROADMAP.md) keeps the list of what has not been tried, and a change that tests one of those items removes it.+4. Do not commit generated output: `out/`, renders, `selection.json`, `selection/`.+5. The viewer follows [DESIGN.md](DESIGN.md). Its text is in Indonesian and English, in the `TEXT` table at the top of its script; a new string needs both, short and in the same voice. `test/editor-text.test.js` checks that every key the page uses is there in both.+6. A change to the page contract or `project.json` must keep existing projects working, or say clearly in the changelog what breaks.+7. A skill's `name` matches its folder and its `description` stays at 500 characters or less, or Codex and other agents skip it without a word. `test/skills.test.js` checks both.++## Tests++```bash+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, and renders a project with a transition. It needs Chrome and ffmpeg. The others need neither: `motion.test.js` checks the easings, springs, keyframes and transition names, `server.test.js` that a file stream closes when its request is aborted, `install.test.js` that `install.js --update --dry-run` finds where the skills went, `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`.++For viewer changes, run `motlab edit example`, check the change in a browser, and look at the console for errors.++## Pull requests++One concern per pull request. Describe what changed, what you measured, and what you could not check. Commit subjects are short and imperative, for example `Viewer: keep the box when the time changes`.++## Reporting bugs++Open an issue with the command you ran, the full output, `motlab doctor` output, your OS, and the smallest page or project that shows the problem. Security problems go through [SECURITY.md](SECURITY.md) instead.++## Code of conduct++Be kind and specific. See [CODE_OF_CONDUCT.md](CODE_OF_CONDUCT.md).diff --git a/DESIGN.md b/DESIGN.mdnew file mode 100644index 0000000..d0ceb18--- /dev/null+++ b/DESIGN.md@@ -0,0 +1,59 @@+# Viewer design++This covers `src/editor.html`. The viewer is only for looking at a project and pointing at "this one" to talk about in chat, so it stays quiet and does not compete with the preview. The UI text is in Indonesian and English, from one table (`TEXT` at the top of the script). The examples here are the Indonesian text.++## Direction++- Dials: ENERGY 1, RHYTHM 1, MOTION 2.+- The style follows the Claude desktop app: its artboard for the grey canvas and floating pills, its header, and the plain lists of the Claude and ChatGPT sidebars. Parts of those apps that the viewer has no use for are not built. The reference screenshots are kept outside the repository.+- Short, direct text with no middle dots. For example, the selection box reads "Scene 2: 02-grafik", then "Detik 1.09, video 00:04.09".+- As few lines as possible. The header has one bottom line, half a pixel in `#ececeb`. The selection box at the bottom of the sidebar has none.++## Layout++- One header across both panes, after the Claude app header: the panel toggle on the left, `project / scene` in the middle (project name grey, current scene black), Export on the right. The project name and the version after it are buttons with a small chevron. Each opens a menu centred under it: projects with the folder name and its path in muted text, versions with the name and file name. The project menu ends with the other language, named in that language ("English" or "Bahasa Indonesia", with EN or ID in muted text), so someone who cannot read the current one still finds it. The open one has the selected-row grey. The version menu ends with "Versi baru dari ini", which turns into a name field and a small dark "Buat" button like Export.+- Two panes under the header, because the scene list and the preview need to be visible together. The grey canvas `#ececec` holds the preview, the play toolbar, the full-screen pill in the top right and the timeline card at the bottom.+- The play toolbar ends with two magnifier buttons that zoom the timeline, and a button that hides or shows the timeline (a frame with a bottom bar, like the panel icon with a side bar). Hidden, the preview fills the canvas up to the sidebar, and the zoom buttons are hidden too. It shows and hides at once, without a slide, and the browser remembers it. Zoomed in, the timeline scrolls sideways with a native scrollbar, and its canvas stays put (sticky) and draws only what is in view.+- The timeline is at most 35% of the window height and scrolls, so a project with many audio files does not push the preview out. The preview area is at least 150 px including padding.+- The timeline's final height is set as soon as `project.json` is read, so it does not jump when the scenes finish loading.+- Below 720 px the sidebar floats over the canvas instead of squeezing it, and it closes when the window becomes that narrow. On touch screens buttons grow to 44 px.+- Spacing is in steps of roughly 2 px (6, 8, 10, 12). Radius follows element size, from 3 px on the preview to 12 px on the timeline card.++## Colour++- White and neutral greys, so the colours in the scene preview are the only strong colours on screen.+- Blue `#2c6fe0` appears only on the timeline (the selected clip, the selection line, and a range as a 10% band with a 1 px edge on each side and an 8 by 14 px head at the top of each edge, like the playhead's), on the range button while it waits for a drag, on the bracket icon of the range bar, on the play button while the video is playing, and on the notes drawn on the preview. A note's box follows the selection box of the Claude canvas: a 1 px blue line, a light blue fill at 14% (22% for the open note), square corners. A point is a 16 px circle in the same style with a 5 px blue dot in the middle. Each has its number in a 16 px blue tag with white text above its top left corner (top right for a point). They sit over the preview as outline elements, so the line stays 1 px and sharp at any preview size. `selection/<n>.png` draws them the same, scaled to the frame. On the timeline the note numbers are tags in a row under the time labels: light blue `#dfe9fb` with blue text, solid blue with white text for the open note. A range note draws a 2 px line to the end of its range with a short end cap. All lines are drawn first and every tag over them with a 2 px margin in the colour behind it, so no line runs through a number.+- A range gets a second pill next to the play toolbar, in the same style: the bracket icon, "00:03.00", an arrow icon, "00:06.50" (the same everywhere a range is written, with "sampai" for screen readers), a thin divider and the length in muted text, a "Catatan" button and ×. The two wrap onto two rows when they do not fit. Below 480 px the toolbars drop the total length, the range length and the zoom buttons, so they fit a phone.+- The open note is a card like the menus (white, 12 px radius, the menu shadow) under its box, or above the timeline for a range note, with the number tag and where it is, a text field, a quiet "Hapus" and a small dark "Simpan" like Export. In the side panel the notes are rows like the audio rows, with the number in the grey tile; an empty note reads "Tanpa catatan" in muted text. The card's footer has a quiet "Tandai selesai" with a check icon between them ("Buka lagi" with a rotate icon on a done note, whose head then ends with a muted check and "Selesai"). Done notes fold under a muted "Selesai N" row with a chevron at the end of the list; unfolded, their number and text are muted and the text struck through. They are not drawn on the preview or the timeline unless one is open.+- Selected rows in the sidebar and in the Export menu use a grey background `#ebebea` and a bold name, like the active item in the Claude sidebar. No borders or accent bars. The Export button names the resolution it will export, so the menu needs no check mark. While an export runs, that button is disabled and faded like any disabled control, with a spinner and "Mengekspor 4K…". A full-width "Batalkan" button appears under it, tinted like the blue play button: red text `#b8322a` on `#fbe4e2` (4.90:1; hover `#f8d9d6`, 4.50:1). The resolution list cannot be changed meanwhile. Red is used for nothing else.+- Muted text `#666561` stays above 4.5:1 on every background it sits on (white, hover, selected row, canvas). The lowest is 4.78:1 on the selected row. The waveform `#85847f` is 3.31:1 against its clip, and the selected waveform in blue is 3.86:1.++## Tooltips++- Not the browser's `title`: a small dark label (`#1f1f1e`, white 12 px text, 8 px radius) after 0.5 s of hover, at once when moving between controls, and on keyboard focus. It sits above the control, or below it near the top of the window, and fades in with a 2 px move.+- Short names in the imperative, with the shortcut in a key cap next to it: "Tandai rentang [R]", "Putar [Spasi]". The explanation goes elsewhere: the range tool says what to do in the toast when it is picked.+- The timeline's tooltip is a two-column list of its keys (key caps left, what they do right in 70% white). It waits 1 s with the pointer still and goes away when the pointer moves on.++## Type++- Plus Jakarta Sans (400, 500, 600) from Google Fonts. The timeline canvas uses the same font and waits for it to load before drawing. Offline, the page falls back to the system font.+- Times use `tabular-nums` so they do not jitter during playback.++## Icons++- 1.5 px rounded strokes in a 16 px box, matching the references. Each icon shows its function directly: panel, export, full screen, play and pause, previous and next scene, waveform, zoom out and in, timeline, range, note, close, the arrow between a range's start and end, and a check and a rotate arrow for marking a note done and opening it again (Lucide's arrow-right, check and rotate-ccw, ISC, redrawn in the same box).++## Motion++- Motion only answers an interaction. The sidebar slides in 0.26 s when it opens or closes. The grid column is animated, so the list keeps its width and does not reflow; on narrow screens the floating sidebar slides with `transform`.+- The Export menu and the full-screen message fade in with a 4 px move over 0.14 s, using `@starting-style`. Hover and press colours change smoothly, and icon buttons shrink slightly when pressed.+- The cursor on the preview is a + (a drag there draws a box). It is dark `#1f1f1e` over light parts of the frame and white over dark parts, picked by the relative luminance of the frame under the pointer (below 0.179 white has the higher contrast). Each has a faint halo in the other colour for edges between light and dark. The brightness comes from a 64-cell-wide copy of the frame, read on the first pointer move after the frame changes, so playback costs nothing extra.+- 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.++## Accessibility++- Every scene and audio row is a button, so Tab, Enter and Space reach it. The timeline is a focusable slider.+- Icon buttons have `aria-label`, SVGs are `aria-hidden`, the play button's label switches to "Jeda" while playing, and the Export button has `aria-expanded`. The export status and the selection box are live regions.+- One `h1` (the project name in the header), plus `header` and `nav`.+- Empty and broken projects show a message that says what to do next.diff --git a/LICENSE b/LICENSEnew file mode 100644index 0000000..3ce81c7--- /dev/null+++ b/LICENSE@@ -0,0 +1,21 @@+MIT License++Copyright (c) 2026 motlab contributors++Permission is hereby granted, free of charge, to any person obtaining a copy+of this software and associated documentation files (the "Software"), to deal+in the Software without restriction, including without limitation the rights+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the Software is+furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in all+copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE+SOFTWARE.diff --git a/README.md b/README.mdnew file mode 100644index 0000000..2fa24be--- /dev/null+++ b/README.md@@ -0,0 +1,202 @@+<p align="center">+ <img src="assets/demo.avif" width="100%" alt="The motlab ad: a prompt asks the agent for a coffee shop promo, the agent builds the scenes, notes are marked on frames in the viewer, the fixes appear, and the video is exported at 4K">+</p>++<div align="center">++# motlab++A video engine where every scene is code, and an agent skill that writes the scenes for you.++<code>git clone https://github.com/staryone/motlab.git && cd motlab && node install.js</code>++[Demo](#watch-the-demo) · [Install](#install) · [Quick start](#quick-start) · [Speed](#speed) · [How it works](#how-it-works) · [Docs](#documentation) · [FAQ](#faq) · [Roadmap](ROADMAP.md)++[](LICENSE)+[](package.json)++</div>++---++Every scene is a canvas page with one function, `renderAt(t)`, that draws the frame at time `t`. motlab plays the pages in a web viewer where you step through them frame by frame, and renders them to MP4 in headless Chrome. You hand your agent a folder of references (logos, screenshots, footage, fonts, music, voice) and a direction, and it builds every scene, opens the viewer and revises from your notes. No AI image or video model is involved.++The ad above (19 seconds, 7 scenes) was made with motlab and its skill, reviewed in the viewer and exported at 4K. The preview is silent; [watch it with sound](https://github.com/user-attachments/assets/5e2ff219-697c-459f-a273-f36cb11db1d1).++## What it does++- Your agent writes each scene as a canvas page, from your references and a short brief.+- 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.+- 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.++## Watch the demo++Two minutes in English, made with motlab too: the install, the brief to the agent, the build, playing it in the viewer, notes on frames, versions, the revision and the export.++https://github.com/user-attachments/assets/522d1db2-a0bd-43bd-84b7-9f071f224854++## Install++You need Node 24 or newer, Google Chrome or Chromium, and ffmpeg with ffprobe on PATH. Python 3 is optional and only used by the skills' helper scripts. Blender is optional too, for the asset skill's main 3D path.++```bash+git clone https://github.com/staryone/motlab.git+cd motlab+node install.js+motlab doctor+```++The installer runs `npm ci`, puts a `motlab` command in `~/.local/bin`, copies both skills to `~/.claude/skills/`, and checks the machine. `motlab doctor` checks it again at any time.++<details><summary>Skills for other agents, and the other installer options</summary>++<br>++- `--skill agents` for Codex, Cursor, OpenCode, Copilot, Gemini CLI, Amp and Windsurf+- `--skill antigravity` for the Antigravity App and CLI+- several at once with commas: `--skill claude,agents,antigravity`+- `--skill-dir <dir>` for any other agent's skill folder, or `--skill none` for no skills+- `--link` to link the skills instead of copying them+- `--dry-run` to see every step first++</details>++Later, `motlab update` gets the newest version from GitHub and copies the skills again to every agent folder they were installed in, and `motlab uninstall` removes the command, the skills and motlab's own files again.++[Install guide and per-OS notes](docs/install.md) · [Instructions for an agent doing the install](docs/install-for-agents.md)++## Quick start++1. Run `motlab edit example`. It starts the viewer in the background, opens the sample project and prints its address, `http://127.0.0.1:4173/p/example/`. Space plays, the arrow keys on the timeline step one frame, Ctrl+scroll zooms the timeline, and a drag on the preview marks a box.+2. To make your own video, put your references in a folder and ask your agent, for example:++ ```text+ Make a 20 second portrait promo for my app with motlab. The references are in ./promo-refs.+ ```++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:++```bash+motlab render example --scale 1+```++## Speed++The same scene (a moving gradient, 160 animated cards with numbers, text) at 1080p, 300 frames, rendered by three tools on one laptop (Ryzen 7 5800H, RTX 3060 Laptop, Windows 11) with the same Chrome:++| Tool | Render time | Frames per second | Compared with motlab |+|---|---|---|---|+| **motlab** | 9.5 s (`--encoder sw`), 12.6 s (default) | 31.5, 23.7 | |+| HyperFrames 0.9.52, fastest setting (1 worker) | 27.2 s | 11.0 | 2.2 to 2.9 times as long |+| Remotion 4.0.543, fastest setting (concurrency 1) | 30.7 s | 9.8 | 2.4 to 3.2 times as long |++Time is the whole command, the median of three runs. At 4K the same scene took motlab 13.1 to 19.4 s and the fastest of the other two 48.9 s.++Remotion and HyperFrames drew on the laptop's integrated Radeon. motlab on the same Radeon took 8.0 to 12.0 s at 1080p and 13.2 to 22.5 s at 4K. With Chrome drawing in software instead of on a GPU, motlab was still the fastest at 1080p (19.2 s against 28.3 s for HyperFrames), but at 4K HyperFrames was faster (43.4 s against 60.7 s).++This is one scene on one machine; macOS and Linux were not measured. The other settings, quality (SSIM) and file sizes are in [the benchmark](docs/rendering.md#against-remotion-and-hyperframes), and [bench/](bench/README.md) runs it again.++## How it works++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.++```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+ -> ffmpeg -c copy: join, colour tags, audio -> out/<name>.mp4+```++Footage is decoded inside the page with Mediabunny, so a scene can cut and trim video files and draw over them. DOM-based engines take a screenshot of every frame and pipe the images to ffmpeg; encoding inside the page skips that, which is where the gap in [Speed](#speed) comes from. The encoder rules and the measured quirks are in [rendering](docs/rendering.md).++## Documentation++| Need | Read |+|---|---|+| 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) |+| Commands, options and the page contract | [Command line](docs/cli.md) |+| How a render works, encoders, 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) |+| What is not built or not tested yet | [Roadmap](ROADMAP.md) |+| Changes | [Changelog](CHANGELOG.md) |++## FAQ++<details><summary><strong>Does motlab use AI image or video models?</strong></summary>++<br>++> No. Your agent writes every scene as code, and motlab draws it frame by frame in Chrome. The pictures come from your references and from what the code draws.++</details>++<details><summary><strong>Which agents does the skill work with?</strong></summary>++<br>++> The installer copies it for Claude Code by default. `--skill agents` covers Codex, Cursor, OpenCode, GitHub Copilot, Gemini CLI, Amp and Windsurf, and `--skill antigravity` the Antigravity App and CLI. `--skill-dir` takes any other agent's skill folder.++</details>++<details><summary><strong>Do I need a GPU?</strong></summary>++<br>++> It renders faster with one, and every render prints the GPU it got on its first line. On the test laptop, with Chrome drawing in software instead, renders took 2.8 to 4.5 times as long. A machine that has no GPU at all, such as a cloud server, has not been tested, and neither has a 3D scene without a GPU.++</details>++<details><summary><strong>Does it run on macOS and Linux?</strong></summary>++<br>++> The Chrome paths and the Metal flag are in the code, but no render has run there yet. Everything so far was built and measured on one Windows laptop.++</details>++<details><summary><strong>Can I use it without an agent?</strong></summary>++<br>++> Yes. A scene is a plain HTML page you can write by hand, `motlab edit` opens the viewer, and `motlab render` exports from the command line. The page contract is in [the command line docs](docs/cli.md).++</details>++<details><summary><strong>Where do my notes go?</strong></summary>++<br>++> Into `selection.json` in the project folder, with a picture of each box or point in `selection/`. The agent reads that file, so you do not have to describe the frame in chat.++</details>++## Status++motlab is young and has been built and measured on one Windows laptop with an RTX 3060. The skill has made two real videos from start to finish, a 2-minute demo of motlab in 10 scenes and a 19-second ad in 7, both rendered at 4K, and the viewer has been tried with a 45-scene project. Alpha output is not built. The Blender path has rendered a whole test sequence on Blender 5.2, played by a scene page into an MP4, and the asset skill has baked, exported and re-imported test assets, a Rigify rig among them. The [roadmap](ROADMAP.md) lists what is open.++## Contributing++Read [CONTRIBUTING.md](CONTRIBUTING.md) first. Agents working in this repository follow [AGENTS.md](AGENTS.md). Report security issues privately, as described in [SECURITY.md](SECURITY.md).++```bash+npm test+```++## License++[MIT](LICENSE). The scene transitions come from gl-transitions (MIT); [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md) has their licence and the libraries motlab installs or loads. Fonts, footage, music and other files you bring into a project keep their own licences.diff --git a/ROADMAP.md b/ROADMAP.mdnew file mode 100644index 0000000..d8e7179--- /dev/null+++ b/ROADMAP.md@@ -0,0 +1,38 @@+# Roadmap++What is not built, what has not been tested, and ideas that came up while using motlab. Nothing here is promised.++## Not built yet++- Alpha output (ProRes 4444).+- Rendering only the scenes that changed. Scenes are already separate MP4 parts joined with `-c copy`, so re-rendering one scene and joining again would be cheap. It needs an explicit option such as `--only 7`.+- Rendering several scenes at once in an export. Scenes render one after another today, and Export uses one Chrome. Parallel workers need a safe default for machines with less memory or a hardware encoder session limit, and a fallback to fewer workers when one fails. A project of many short scenes pays a Chrome start per scene: 12 two-second scenes with 11 transitions took 57 s at 1080p.+- The viewer on a VPS with a domain. That needs security in front of it, or access only through Tailscale, which is also worth considering. From there, work could be run remotely on the personal laptop (when it is on) or on the VPS (when there is one).+- Custom GLSL transitions from a file in the project. A transition as a layer over the cut (a swish of shapes) already exists as the asset skill's `transition.js`, but each of the two scene pages has to draw its half by hand; `project.json` has no option for it.+- A cut list that splits one recording over several scenes by section, with captions placed from a transcript. `cuts.js` has the time map (`toOut`), but each section page still picks its part of the list by hand.+- Continuous integration. The end-to-end test needs Chrome, ffmpeg and ideally a GPU.+- Moving or resizing a note's box after it is drawn. Today the note has to be deleted and drawn again.+- Clearing done notes in one go. They fold under Done, but `selection.json` keeps every one until it is deleted by hand.++## Not tested yet++- The benchmark against Remotion and HyperFrames on macOS and Linux, with their own downloaded browsers, and on scenes heavy on text, images or footage. It was one scene on Windows, at 1080p and 4K.+- macOS and Linux, including `motlab update` there. The Chrome paths and the Metal flag are in the code, but no render has run there.+- Renders longer than 10 minutes, and a 10-minute render on a machine that is doing nothing else.+- A machine without a GPU. The benchmark ran with Chrome drawing on SwiftShader on the test laptop (1080p and 4K, in `docs/rendering.md`), but not on a machine that has no GPU, such as a cloud server, and not with a 3D (WebGL) scene.+- Footage filmed on a phone (variable frame rate and HEVC were tested with files made by ffmpeg), and HEVC on a Chrome that cannot decode it.+- Scene transitions between scenes of different sizes in the viewer, and in a normal Chrome window. The render refuses scenes of different sizes.+- The cut voice from `cut_pauses.py` on a real person's take. The whole-take test used Windows text to speech.+- Rive, Lottie text layers exported with glyphs, Theatre.js state exported from its studio, and the studio inside the viewer.+- p5.js `loadFont` and p5 add-on libraries.+- The asset skill (`motlab-assets`) on a real brief and a kit used in a real video. Its scripts were run on a test kit: an SVG character with a rig, a transition, a mug on both 3D paths and a Rigify figure.+- MPFB, which was not installed on the test laptop.+- The asset skill's FBX and OBJ files in programs other than Blender (Unity, Unreal, Maya, Cinema 4D).+- `svgparts.js` and `transition.js` in the viewer. They were checked with stills and a video render.+- Notes on a real touch screen. Touch was emulated in Chrome over the DevTools protocol.+- The skills in agents other than Claude Code. The installer was run with `--dry-run` for every target, and the folders come from each agent's docs, but no other agent has loaded the skills or made a video with them yet.++## 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.mdnew file mode 100644index 0000000..01e56f8--- /dev/null+++ b/SECURITY.md@@ -0,0 +1,29 @@+# Security policy++## 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:++- 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+- 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.++## Reporting++Report privately through GitHub Security Advisories:++<https://github.com/staryone/motlab/security/advisories/new>++Please do not open a public issue for a vulnerability. Include the version or commit, the command that triggers it, and the smallest project that reproduces it. You will get an answer within a week, and a fix and disclosure date will be agreed with you before anything is published.++## Supported versions++Only the latest commit on `main` is supported.++## What motlab never asks for++motlab needs no account, password, token or API key. If an issue or pull request asks you for one, treat it as hostile.diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.mdnew file mode 100644index 0000000..5d69041--- /dev/null+++ b/THIRD_PARTY_NOTICES.md@@ -0,0 +1,39 @@+# Third-party notices++motlab's own code is under the [MIT licence](LICENSE). This file lists code from other projects that is copied into the repository, with the licence it came under. The example project's sounds in `example/audio/` were made by the maintainer for this repository and are under the same MIT licence.++## gl-transitions++The 11 scene transition shaders in `src/page/transitions.js` are copied from [gl-transitions](https://github.com/gl-transitions/gl-transitions) 1.43.0. Each shader's author is named next to it in that file. `SimpleZoom` is changed so it compiles in WebGL.++```text+MIT License++Copyright (c) 2017-present gl-transitions contributors++Permission is hereby granted, free of charge, to any person obtaining a copy+of this software and associated documentation files (the "Software"), to deal+in the Software without restriction, including without limitation the rights+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the Software is+furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in all+copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE+SOFTWARE.+```++## Installed, not copied++These are downloaded when you install or run motlab, under their own licences, and are not part of this repository:++- [Mediabunny](https://github.com/Vanilagy/mediabunny) (MPL-2.0), installed by `npm ci`. It writes MP4 files and decodes footage inside scene pages.+- The libraries that scene pages load from jsDelivr at a pinned version, when a scene uses them: three.js (MIT), p5.js (LGPL-2.1), GSAP (its own no-charge licence from Webflow), Anime.js (MIT), lottie-web (MIT), dotLottie (MIT) and Theatre.js core (Apache-2.0).+- Remotion, HyperFrames and GSAP in `bench/`, installed only when you run the benchmark. See [bench/README.md](bench/README.md).diff --git a/assets/demo.avif b/assets/demo.avifnew file mode 100644index 0000000..ba6c4e2Binary files /dev/null and b/assets/demo.avif differdiff --git a/bench/.gitignore b/bench/.gitignorenew file mode 100644index 0000000..1aa3194--- /dev/null+++ b/bench/.gitignore@@ -0,0 +1,11 @@+hyperframes/*/shared.js+hyperframes/*/gsap.min.js+results.json+results-4k.json+ref/+ref-*/+.hyperframes/+results-cpu.json+results-cpu-4k.json+results-igpu.json+results-igpu-4k.jsondiff --git a/bench/README.md b/bench/README.mdnew file mode 100644index 0000000..9a4c7dd--- /dev/null+++ b/bench/README.md@@ -0,0 +1,27 @@+# Benchmark++One scene rendered by motlab, Remotion and HyperFrames on the same machine. The results and what they leave out are in [docs/rendering.md](../docs/rendering.md#against-remotion-and-hyperframes).++The scene is in `shared.js`: a turning gradient, 160 cards that move, turn, scale and fade with a number on each, a title, a frame counter and a progress bar, at 1920x1080, 30 fps, 10 seconds. Every value is a function of time. `drawCanvas` draws it on a 2D canvas, and `dom` with `applyDom` build and move the same thing as HTML elements.++| Folder | What renders it |+|---|---|+| `motlab/canvas.html` | motlab, the canvas |+| `remotion/src/Root.jsx` | Remotion, composition `Dom` (HTML elements) and `Canvas` (the canvas code) |+| `hyperframes/dom`, `hyperframes/canvas` | HyperFrames, HTML elements and the canvas code, each moved from a GSAP timeline |++## Running it++You need what motlab needs (Node 24, Chrome, ffmpeg). Remotion and HyperFrames are installed in this folder only, at the versions that were measured:++```bash+cd bench+npm ci+node run.mjs+```++It runs every setting three times, one after another, and prints a table and `results.json`: the median wall time of the whole command, frames per second over that time, the file size, and SSIM of 10 frames against lossless PNG stills of the canvas page. All three tools use the Chrome that motlab finds (or `CHROME`), and Remotion's and HyperFrames' telemetry is turned off. `RUNS=1` runs each once, `ONLY=motlab-sw,hf-dom` picks settings by name, and `SCALE=2` renders at 4K into `results-4k.json`. `CPU=1` runs the settings with Chrome drawing in software (SwiftShader) and CPU encoders only, into `results-cpu.json` (or `results-cpu-4k.json` with `SCALE=2`); motlab runs through `motlab-cpu.mjs` for that, which gives it the same Chrome flags as HyperFrames' `--no-browser-gpu`. `IGPU=1` runs only the motlab settings, through `motlab-igpu.mjs` without `--force_high_performance_gpu`, so that on a laptop with two GPUs it draws on the integrated one, as Remotion and HyperFrames do (`results-igpu.json`, `results-igpu-4k.json`).++`npm ci` downloads these tools under their own licences, which motlab's MIT licence does not cover. Remotion's is not an open source licence: it is free for individuals, companies of up to 3 employees, non-profits and for evaluating it, and other companies need a paid company licence ([its licence](https://github.com/remotion-dev/remotion/blob/main/LICENSE.md)). HyperFrames is Apache-2.0, and GSAP has its own free licence from Webflow. If you run it on behalf of a company, check Remotion's terms first.++Close other programs first, and run motlab once before timing so its encoder probe is saved. The first run with a new `--workers` count probes again and is slower.diff --git a/bench/hyperframes/canvas/hyperframes.json b/bench/hyperframes/canvas/hyperframes.jsonnew file mode 100644index 0000000..dc9ec2e--- /dev/null+++ b/bench/hyperframes/canvas/hyperframes.json@@ -0,0 +1,12 @@+{+ "$schema": "https://hyperframes.heygen.com/schema/hyperframes.json",+ "registry": "https://raw.githubusercontent.com/heygen-com/hyperframes/main/registry",+ "paths": {+ "blocks": "compositions",+ "components": "compositions/components",+ "assets": "assets"+ },+ "media": {+ "autoProxy": true+ }+}diff --git a/bench/hyperframes/canvas/index.html b/bench/hyperframes/canvas/index.htmlnew file mode 100644index 0000000..3d12d58--- /dev/null+++ b/bench/hyperframes/canvas/index.html@@ -0,0 +1,17 @@+<!doctype html>+<html lang="en"><head><meta charset="UTF-8" /><meta name="viewport" content="width=1920, height=1080" />+<script src="gsap.min.js"></script><script src="shared.js"></script>+<style>* { margin: 0; padding: 0; box-sizing: border-box; } html, body { width: 1920px; height: 1080px; overflow: hidden; background: #000; }</style>+</head><body>+<div id="root" data-composition-id="main" data-start="0" data-duration="10" data-width="1920" data-height="1080">+ <canvas id="c" class="clip" width="1920" height="1080" data-start="0" data-duration="10" data-track-index="0"></canvas>+</div>+<script>+ // The same scene drawn on a canvas with the code motlab uses.+ const ctx = document.getElementById('c').getContext('2d');+ const tl = gsap.timeline({ paused: true });+ tl.to({}, { duration: 10, ease: 'none', onUpdate: () => BENCH.drawCanvas(ctx, tl.time()) }, 0);+ window.__timelines["main"] = tl;+ tl.seek(0); BENCH.drawCanvas(ctx, 0);+</script>+</body></html>diff --git a/bench/hyperframes/dom/hyperframes.json b/bench/hyperframes/dom/hyperframes.jsonnew file mode 100644index 0000000..dc9ec2e--- /dev/null+++ b/bench/hyperframes/dom/hyperframes.json@@ -0,0 +1,12 @@+{+ "$schema": "https://hyperframes.heygen.com/schema/hyperframes.json",+ "registry": "https://raw.githubusercontent.com/heygen-com/hyperframes/main/registry",+ "paths": {+ "blocks": "compositions",+ "components": "compositions/components",+ "assets": "assets"+ },+ "media": {+ "autoProxy": true+ }+}diff --git a/bench/hyperframes/dom/index.html b/bench/hyperframes/dom/index.htmlnew file mode 100644index 0000000..a313679--- /dev/null+++ b/bench/hyperframes/dom/index.html@@ -0,0 +1,17 @@+<!doctype html>+<html lang="en"><head><meta charset="UTF-8" /><meta name="viewport" content="width=1920, height=1080" />+<script src="gsap.min.js"></script><script src="shared.js"></script>+<style>* { margin: 0; padding: 0; box-sizing: border-box; } html, body { width: 1920px; height: 1080px; overflow: hidden; background: #000; }</style>+</head><body>+<div id="root" data-composition-id="main" data-start="0" data-duration="10" data-width="1920" data-height="1080">+ <div id="scene" class="clip" data-start="0" data-duration="10" data-track-index="0"></div>+</div>+<script>+ // The same scene as HTML elements, each moved from the timeline's time.+ const els = BENCH.dom(document.getElementById('scene'));+ const tl = gsap.timeline({ paused: true });+ tl.to({}, { duration: 10, ease: 'none', onUpdate: () => BENCH.applyDom(els, tl.time()) }, 0);+ window.__timelines["main"] = tl;+ tl.seek(0); BENCH.applyDom(els, 0);+</script>+</body></html>diff --git a/bench/motlab-cpu.mjs b/bench/motlab-cpu.mjsnew file mode 100644index 0000000..a9cd508--- /dev/null+++ b/bench/motlab-cpu.mjs@@ -0,0 +1,7 @@+// motlab with Chrome drawing in software (SwiftShader through ANGLE), the flags HyperFrames' --no-browser-gpu passes.+// motlab itself has no CPU option; this swaps its GPU flags for the run.mjs CPU=1 benchmark. Same arguments as motlab.+import { GPU_FLAGS } from '../src/chrome.js';+import { main } from '../src/cli.js';++GPU_FLAGS.splice(0, GPU_FLAGS.length, '--use-gl=angle', '--use-angle=swiftshader', '--enable-unsafe-swiftshader');+main(process.argv.slice(2)).then(code => process.exit(code), e => { console.error(`FAILED: ${e.message}`); process.exit(1); });diff --git a/bench/motlab-igpu.mjs b/bench/motlab-igpu.mjsnew file mode 100644index 0000000..717024f--- /dev/null+++ b/bench/motlab-igpu.mjs@@ -0,0 +1,7 @@+// motlab with Chrome left on its default GPU: without --force_high_performance_gpu, headless Chrome on a dual-GPU+// laptop draws on the integrated GPU, as it does for Remotion and HyperFrames. For the run.mjs IGPU=1 benchmark.+import { GPU_FLAGS } from '../src/chrome.js';+import { main } from '../src/cli.js';++GPU_FLAGS.splice(0, GPU_FLAGS.length, ...GPU_FLAGS.filter(f => f !== '--force_high_performance_gpu'));+main(process.argv.slice(2)).then(code => process.exit(code), e => { console.error(`FAILED: ${e.message}`); process.exit(1); });diff --git a/bench/motlab/canvas.html b/bench/motlab/canvas.htmlnew file mode 100644index 0000000..10fd54d--- /dev/null+++ b/bench/motlab/canvas.html@@ -0,0 +1,10 @@+<!doctype html><html><head><meta charset="utf-8"></head><body style="margin:0"><canvas id="c"></canvas>+<script src="../shared.js"></script>+<script>+const S = parseFloat(new URLSearchParams(location.search).get('scale') || '1');+const cv = document.getElementById('c'); cv.width = BENCH.W * S; cv.height = BENCH.H * S;+const ctx = cv.getContext('2d');+window.TOTAL = BENCH.TOTAL;+window.renderAt = t => { ctx.setTransform(S, 0, 0, S, 0, 0); BENCH.drawCanvas(ctx, t); };+window.ready = document.fonts.ready.then(() => window.renderAt(0));+</script></body></html>diff --git a/bench/package-lock.json b/bench/package-lock.jsonnew file mode 100644index 0000000..006ca6c--- /dev/null+++ b/bench/package-lock.json@@ -0,0 +1,5618 @@+{+ "name": "motlab-bench",+ "lockfileVersion": 3,+ "requires": true,+ "packages": {+ "": {+ "name": "motlab-bench",+ "dependencies": {+ "@remotion/bundler": "4.0.543",+ "@remotion/cli": "4.0.543",+ "@remotion/renderer": "4.0.543",+ "gsap": "3.15.0",+ "hyperframes": "0.9.52",+ "react": "19.2.0",+ "react-dom": "19.2.0",+ "remotion": "4.0.543"+ }+ },+ "node_modules/@babel/code-frame": {+ "version": "7.29.7",+ "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.29.7.tgz",+ "integrity": "sha512-Aup7aUOfpbAUg2ROOJN6Iw5f9DMBlzu0mIkm/malLQFN/YQgO48wCj0Kxa3sEHJvPVFg7siR+qRInwXd2qhQKw==",+ "license": "MIT",+ "dependencies": {+ "@babel/helper-validator-identifier": "^7.29.7",+ "js-tokens": "^4.0.0",+ "picocolors": "^1.1.1"+ },+ "engines": {+ "node": ">=6.9.0"+ }+ },+ "node_modules/@babel/compat-data": {+ "version": "7.29.7",+ "resolved": "https://registry.npmjs.org/@babel/compat-data/-/compat-data-7.29.7.tgz",+ "integrity": "sha512-locTkQyKvwIEgBzVrn8693ebc97F2U8ZHjbXwDXJ5Fn2TCpNwTlKcaKLkdHop5c/icOFE7qt7Q9JC5hnKNa6Gg==",+ "license": "MIT",+ "engines": {+ "node": ">=6.9.0"+ }+ },+ "node_modules/@babel/core": {+ "version": "7.29.13",+ "resolved": "https://registry.npmjs.org/@babel/core/-/core-7.29.13.tgz",+ "integrity": "sha512-j1nvOQCZYSgp7HLmisnCXFTpVvFODiijQ9QHkORfGKWH6YDtskTEeCJS7eV545GZ9UBzrq0e2xsOd5QQ5PjIqw==",+ "license": "MIT",+ "dependencies": {+ "@babel/code-frame": "^7.29.7",+ "@babel/generator": "^7.29.13",+ "@babel/helper-compilation-targets": "^7.29.13",+ "@babel/helper-module-transforms": "^7.29.13",+ "@babel/helpers": "^7.29.13",+ "@babel/parser": "^7.29.13",+ "@babel/template": "^7.29.7",+ "@babel/traverse": "^7.29.13",+ "@babel/types": "^7.29.11",+ "@jridgewell/remapping": "^2.3.5",+ "convert-source-map": "^2.0.0",+ "debug": "^4.1.0",+ "gensync": "^1.0.0-beta.2",+ "json5": "^2.2.3",+ "semver": "^6.3.1"+ },+ "engines": {+ "node": ">=6.9.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/babel"+ }+ },+ "node_modules/@babel/core/node_modules/@babel/parser": {+ "version": "7.29.14",+ "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.29.14.tgz",+ "integrity": "sha512-VL220vXuyO2z3rNIQwY7ftj9UwpqOt+33sH+sBWkOekbsSR2g7EEMnOx24ZlCH0xOA3DM/33SifVFGbnJD8r/w==",+ "license": "MIT",+ "dependencies": {+ "@babel/types": "^7.29.14"+ },+ "bin": {+ "parser": "bin/babel-parser.js"+ },+ "engines": {+ "node": ">=6.0.0"+ }+ },+ "node_modules/@babel/core/node_modules/@babel/types": {+ "version": "7.29.14",+ "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.29.14.tgz",+ "integrity": "sha512-UjI/dKmwJwT9pOszJitq2G6EObZPnsZUfdCr92z2TlF3EZK9J3EdfOKUrCzHl6wFthbzwhzl1Soc/UIwxRiq6w==",+ "license": "MIT",+ "dependencies": {+ "@babel/helper-string-parser": "^7.29.14",+ "@babel/helper-validator-identifier": "^7.29.7"+ },+ "engines": {+ "node": ">=6.9.0"+ }+ },+ "node_modules/@babel/core/node_modules/semver": {+ "version": "6.3.2",+ "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.2.tgz",+ "integrity": "sha512-GYrCADwpu6yV5OAvchkQ27Z5wwMxWAEMg5NNWjyHh/5DboFFqbdbvYNIvZouQpxXyeMPoTOh0vdPYKlf0ZswdQ==",+ "license": "ISC",+ "bin": {+ "semver": "bin/semver.js"+ }+ },+ "node_modules/@babel/generator": {+ "version": "7.29.14",+ "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-7.29.14.tgz",+ "integrity": "sha512-qSY56jgW5JnSXzuekLVil6zaOQxOCtOHidr65KkaMBw772IuAY28Qx4ZykAcDn8+FRF15qk80XzKwgSc/RYW6g==",+ "license": "MIT",+ "dependencies": {+ "@babel/parser": "^7.29.14",+ "@babel/types": "^7.29.14",+ "@jridgewell/gen-mapping": "^0.3.12",+ "@jridgewell/trace-mapping": "^0.3.28",+ "jsesc": "^3.0.2"+ },+ "engines": {+ "node": ">=6.9.0"+ }+ },+ "node_modules/@babel/generator/node_modules/@babel/parser": {+ "version": "7.29.14",+ "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.29.14.tgz",+ "integrity": "sha512-VL220vXuyO2z3rNIQwY7ftj9UwpqOt+33sH+sBWkOekbsSR2g7EEMnOx24ZlCH0xOA3DM/33SifVFGbnJD8r/w==",+ "license": "MIT",+ "dependencies": {+ "@babel/types": "^7.29.14"+ },+ "bin": {+ "parser": "bin/babel-parser.js"+ },+ "engines": {+ "node": ">=6.0.0"+ }+ },+ "node_modules/@babel/generator/node_modules/@babel/types": {+ "version": "7.29.14",+ "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.29.14.tgz",+ "integrity": "sha512-UjI/dKmwJwT9pOszJitq2G6EObZPnsZUfdCr92z2TlF3EZK9J3EdfOKUrCzHl6wFthbzwhzl1Soc/UIwxRiq6w==",+ "license": "MIT",+ "dependencies": {+ "@babel/helper-string-parser": "^7.29.14",+ "@babel/helper-validator-identifier": "^7.29.7"+ },+ "engines": {+ "node": ">=6.9.0"+ }+ },+ "node_modules/@babel/helper-compilation-targets": {+ "version": "7.29.13",+ "resolved": "https://registry.npmjs.org/@babel/helper-compilation-targets/-/helper-compilation-targets-7.29.13.tgz",+ "integrity": "sha512-8WxJ4/Vmes3ghacj8VOJy3NW8eyHiFY/4thU/LSBuBE470+igjR/j1ZTNn8fV5VdNrLx6iXUwig526UdOvfP0w==",+ "license": "MIT",+ "dependencies": {+ "@babel/compat-data": "^7.29.7",+ "@babel/helper-validator-option": "^7.29.7",+ "browserslist": "^4.24.0",+ "lru-cache": "^5.1.1",+ "semver": "^6.3.1"+ },+ "engines": {+ "node": ">=6.9.0"+ }+ },+ "node_modules/@babel/helper-compilation-targets/node_modules/semver": {+ "version": "6.3.2",+ "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.2.tgz",+ "integrity": "sha512-GYrCADwpu6yV5OAvchkQ27Z5wwMxWAEMg5NNWjyHh/5DboFFqbdbvYNIvZouQpxXyeMPoTOh0vdPYKlf0ZswdQ==",+ "license": "ISC",+ "bin": {+ "semver": "bin/semver.js"+ }+ },+ "node_modules/@babel/helper-globals": {+ "version": "7.29.7",+ "resolved": "https://registry.npmjs.org/@babel/helper-globals/-/helper-globals-7.29.7.tgz",+ "integrity": "sha512-3nQVUAtvkKH9zahfWgw96Jc/uFOmjACE1kQz82E2lqWmHBgjzbNlsC22nuQTfahmWeQtTq5nQ/4Nnd2A1wj4zA==",+ "license": "MIT",+ "engines": {+ "node": ">=6.9.0"+ }+ },+ "node_modules/@babel/helper-module-imports": {+ "version": "7.29.7",+ "resolved": "https://registry.npmjs.org/@babel/helper-module-imports/-/helper-module-imports-7.29.7.tgz",+ "integrity": "sha512-ejHwrQQYcm9xnTivShn2IDOlIzInN34AXskvq9QicvCtEzq1Vzclu/tKF8Jq1Cg8JG2GL6/EmjgsCT7lXepE3g==",+ "license": "MIT",+ "dependencies": {+ "@babel/traverse": "^7.29.7",+ "@babel/types": "^7.29.7"+ },+ "engines": {+ "node": ">=6.9.0"+ }+ },+ "node_modules/@babel/helper-module-imports/node_modules/@babel/types": {+ "version": "7.29.14",+ "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.29.14.tgz",+ "integrity": "sha512-UjI/dKmwJwT9pOszJitq2G6EObZPnsZUfdCr92z2TlF3EZK9J3EdfOKUrCzHl6wFthbzwhzl1Soc/UIwxRiq6w==",+ "license": "MIT",+ "dependencies": {+ "@babel/helper-string-parser": "^7.29.14",+ "@babel/helper-validator-identifier": "^7.29.7"+ },+ "engines": {+ "node": ">=6.9.0"+ }+ },+ "node_modules/@babel/helper-module-transforms": {+ "version": "7.29.14",+ "resolved": "https://registry.npmjs.org/@babel/helper-module-transforms/-/helper-module-transforms-7.29.14.tgz",+ "integrity": "sha512-2XDvQVd9JESaOgGc4jT2/jquTAO7ppA5noTZQqH+MmZ89yjCzScLwtCPbWtkPZylL+TLWR49IwWmk+QkRR4GsA==",+ "license": "MIT",+ "dependencies": {+ "@babel/helper-module-imports": "^7.29.7",+ "@babel/helper-validator-identifier": "^7.29.7",+ "@babel/traverse": "^7.29.14"+ },+ "engines": {+ "node": ">=6.9.0"+ },+ "peerDependencies": {+ "@babel/core": "^7.0.0"+ }+ },+ "node_modules/@babel/helper-string-parser": {+ "version": "7.29.14",+ "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.29.14.tgz",+ "integrity": "sha512-CXvKMFvM80ihI7Vox9jb+kQjnyjESQNPM+vB7U0Zz6TWuZA+Z/FL0QPMH300h33qJtIx+REeBhXqWOPW48TcAQ==",+ "license": "MIT",+ "engines": {+ "node": ">=6.9.0"+ }+ },+ "node_modules/@babel/helper-validator-identifier": {+ "version": "7.29.7",+ "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.29.7.tgz",+ "integrity": "sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg==",+ "license": "MIT",+ "engines": {+ "node": ">=6.9.0"+ }+ },+ "node_modules/@babel/helper-validator-option": {+ "version": "7.29.7",+ "resolved": "https://registry.npmjs.org/@babel/helper-validator-option/-/helper-validator-option-7.29.7.tgz",+ "integrity": "sha512-N9ZErrD+yW5geCDtBqnOoxmR8+tNKiGuxKlDpuJxfsqpa2dFcexaziGAE/qoHLiDDreVNMupxGmSoNlyvsA3gw==",+ "license": "MIT",+ "engines": {+ "node": ">=6.9.0"+ }+ },+ "node_modules/@babel/helpers": {+ "version": "7.29.14",+ "resolved": "https://registry.npmjs.org/@babel/helpers/-/helpers-7.29.14.tgz",+ "integrity": "sha512-6E3Mi1r0B0umq6vmZa4/78q+64fqO2YY0THUdjDPKUCKhNb0yQy5NQIaPHCSD3ryTgiTss//P4JsWS80AsZ6LQ==",+ "license": "MIT",+ "dependencies": {+ "@babel/template": "^7.29.7",+ "@babel/types": "^7.29.14"+ },+ "engines": {+ "node": ">=6.9.0"+ }+ },+ "node_modules/@babel/helpers/node_modules/@babel/types": {+ "version": "7.29.14",+ "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.29.14.tgz",+ "integrity": "sha512-UjI/dKmwJwT9pOszJitq2G6EObZPnsZUfdCr92z2TlF3EZK9J3EdfOKUrCzHl6wFthbzwhzl1Soc/UIwxRiq6w==",+ "license": "MIT",+ "dependencies": {+ "@babel/helper-string-parser": "^7.29.14",+ "@babel/helper-validator-identifier": "^7.29.7"+ },+ "engines": {+ "node": ">=6.9.0"+ }+ },+ "node_modules/@babel/parser": {+ "version": "7.24.1",+ "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.24.1.tgz",+ "integrity": "sha512-Zo9c7N3xdOIQrNip7Lc9wvRPzlRtovHVE4lkz8WEDr7uYh/GMQhSiIgFxGIArRHYdJE5kxtZjAf8rT0xhdLCzg==",+ "license": "MIT",+ "bin": {+ "parser": "bin/babel-parser.js"+ },+ "engines": {+ "node": ">=6.0.0"+ }+ },+ "node_modules/@babel/template": {+ "version": "7.29.7",+ "resolved": "https://registry.npmjs.org/@babel/template/-/template-7.29.7.tgz",+ "integrity": "sha512-puq+Gf35oI24FeN11LkoUQFqv9uwNeWpxXZi/Ji3rRIoKAzKnxRaZ+Gkj0vKS9ZCiTESfng1N9LyOyXvo+m+Gg==",+ "license": "MIT",+ "dependencies": {+ "@babel/code-frame": "^7.29.7",+ "@babel/parser": "^7.29.7",+ "@babel/types": "^7.29.7"+ },+ "engines": {+ "node": ">=6.9.0"+ }+ },+ "node_modules/@babel/template/node_modules/@babel/parser": {+ "version": "7.29.14",+ "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.29.14.tgz",+ "integrity": "sha512-VL220vXuyO2z3rNIQwY7ftj9UwpqOt+33sH+sBWkOekbsSR2g7EEMnOx24ZlCH0xOA3DM/33SifVFGbnJD8r/w==",+ "license": "MIT",+ "dependencies": {+ "@babel/types": "^7.29.14"+ },+ "bin": {+ "parser": "bin/babel-parser.js"+ },+ "engines": {+ "node": ">=6.0.0"+ }+ },+ "node_modules/@babel/template/node_modules/@babel/types": {+ "version": "7.29.14",+ "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.29.14.tgz",+ "integrity": "sha512-UjI/dKmwJwT9pOszJitq2G6EObZPnsZUfdCr92z2TlF3EZK9J3EdfOKUrCzHl6wFthbzwhzl1Soc/UIwxRiq6w==",+ "license": "MIT",+ "dependencies": {+ "@babel/helper-string-parser": "^7.29.14",+ "@babel/helper-validator-identifier": "^7.29.7"+ },+ "engines": {+ "node": ">=6.9.0"+ }+ },+ "node_modules/@babel/traverse": {+ "version": "7.29.14",+ "resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-7.29.14.tgz",+ "integrity": "sha512-RAdQJrBgmIH1FWvN0X+1hoDxzMzlP4cv/1Zi4dn4tG1H0cTb+rw7CzUxQJhp1f4ANd8j5vH3fy8BAWFGkBDEsA==",+ "license": "MIT",+ "dependencies": {+ "@babel/code-frame": "^7.29.7",+ "@babel/generator": "^7.29.14",+ "@babel/helper-globals": "^7.29.7",+ "@babel/parser": "^7.29.14",+ "@babel/template": "^7.29.7",+ "@babel/types": "^7.29.14",+ "debug": "^4.3.1"+ },+ "engines": {+ "node": ">=6.9.0"+ }+ },+ "node_modules/@babel/traverse/node_modules/@babel/parser": {+ "version": "7.29.14",+ "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.29.14.tgz",+ "integrity": "sha512-VL220vXuyO2z3rNIQwY7ftj9UwpqOt+33sH+sBWkOekbsSR2g7EEMnOx24ZlCH0xOA3DM/33SifVFGbnJD8r/w==",+ "license": "MIT",+ "dependencies": {+ "@babel/types": "^7.29.14"+ },+ "bin": {+ "parser": "bin/babel-parser.js"+ },+ "engines": {+ "node": ">=6.0.0"+ }+ },+ "node_modules/@babel/traverse/node_modules/@babel/types": {+ "version": "7.29.14",+ "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.29.14.tgz",+ "integrity": "sha512-UjI/dKmwJwT9pOszJitq2G6EObZPnsZUfdCr92z2TlF3EZK9J3EdfOKUrCzHl6wFthbzwhzl1Soc/UIwxRiq6w==",+ "license": "MIT",+ "dependencies": {+ "@babel/helper-string-parser": "^7.29.14",+ "@babel/helper-validator-identifier": "^7.29.7"+ },+ "engines": {+ "node": ">=6.9.0"+ }+ },+ "node_modules/@babel/types": {+ "version": "7.24.0",+ "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.24.0.tgz",+ "integrity": "sha512-+j7a5c253RfKh8iABBhywc8NSfP5LURe7Uh4qpsh6jc+aLJguvmIUBdjSdEMQv2bENrCR5MfRdjGo7vzS/ob7w==",+ "license": "MIT",+ "dependencies": {+ "@babel/helper-string-parser": "^7.23.4",+ "@babel/helper-validator-identifier": "^7.22.20",+ "to-fast-properties": "^2.0.0"+ },+ "engines": {+ "node": ">=6.9.0"+ }+ },+ "node_modules/@emnapi/core": {+ "version": "1.11.3",+ "resolved": "https://registry.npmjs.org/@emnapi/core/-/core-1.11.3.tgz",+ "integrity": "sha512-zLpS5asjEb7lq8jYLq37N6XKaE41DIexlY1rF/z4/tIl3wo13Sqm28fRyfIsKZD+NZ8mM5RoKkpW/rBcuoSZSg==",+ "license": "MIT",+ "optional": true,+ "dependencies": {+ "@emnapi/wasi-threads": "1.2.3",+ "tslib": "^2.4.0"+ }+ },+ "node_modules/@emnapi/runtime": {+ "version": "1.11.3",+ "resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-1.11.3.tgz",+ "integrity": "sha512-Xz4Tpyki7XyrpbUK1jR1AhdAdaXyhhY4lZ3neLodmhpuWfy2PAQN5B46sAiU4liOXGLkHypn/qU+jvfWSCYYLA==",+ "license": "MIT",+ "optional": true,+ "dependencies": {+ "tslib": "^2.4.0"+ }+ },+ "node_modules/@emnapi/wasi-threads": {+ "version": "1.2.3",+ "resolved": "https://registry.npmjs.org/@emnapi/wasi-threads/-/wasi-threads-1.2.3.tgz",+ "integrity": "sha512-ELEBe8PsLvvJ6QMr0zLt8ffvOHW/dc1m3CEzNMg7aJUv3bMaoDtw2TXyDAwkYBuroxxuHEwhRTLJSe5sya547g==",+ "license": "MIT",+ "optional": true,+ "dependencies": {+ "tslib": "^2.4.0"+ }+ },+ "node_modules/@esbuild/aix-ppc64": {+ "version": "0.28.1",+ "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.28.1.tgz",+ "integrity": "sha512-Svl7tq8k/08+p6CXPpRjQ1fKX+1odH/BQbb48fV6fj3CWHhsoIOoY87w1oHXm0qEpkIK3ZfVgp0hed3XBXzXMQ==",+ "cpu": [+ "ppc64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "aix"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/android-arm": {+ "version": "0.28.1",+ "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.28.1.tgz",+ "integrity": "sha512-0k2F129Xdio1TdJfzJ8sy1Q47vUD2NnwdhiAf7drUN1EBTfPf4hsFCtmMgu/6m8JSzsBrlmVjudMBQqOfG8usQ==",+ "cpu": [+ "arm"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "android"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/android-arm64": {+ "version": "0.28.1",+ "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.28.1.tgz",+ "integrity": "sha512-34EGEbCIAgosYz6goLcopX6Mo7NyGv9tfwEM2/7Ce2VcVRk568iSvniGWcUXIy7wEDR1wzolcxcriFVrWYcwBg==",+ "cpu": [+ "arm64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "android"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/android-x64": {+ "version": "0.28.1",+ "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.28.1.tgz",+ "integrity": "sha512-dbwY7ltSMDWsRatcRpCnES4F+im88OCUgGZjy52shC7GqHRE/cYlxNbB4Z4UpJswpcc4Qxd2oE/ufM0p61IKng==",+ "cpu": [+ "x64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "android"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/darwin-arm64": {+ "version": "0.28.1",+ "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.28.1.tgz",+ "integrity": "sha512-TZbWkQY7kvTAXbXUT7uVACR5cMHsDiSz9z7ZKAX/RTq/WJEk3QyRr0wZpNhBDX+/0CtdqUIJlOiodQcta6tY3Q==",+ "cpu": [+ "arm64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "darwin"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/darwin-x64": {+ "version": "0.28.1",+ "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.28.1.tgz",+ "integrity": "sha512-zfdzgK9ACBNZLI/CyHTOx81SyNbM6YXn7rxSgX97VjyiPl9W1i4Ka4fgKECEoFCKGpvBj5qArWIGgQjOwkgskQ==",+ "cpu": [+ "x64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "darwin"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/freebsd-arm64": {+ "version": "0.28.1",+ "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.28.1.tgz",+ "integrity": "sha512-wG2EA8ENdEI0qhkSZMjfqrdY+ziCYCPMmtZjjIwOmXFjmyzEHn+UUxk5of+SYsjtfs3VpnlC7QLzSI5hY/rOAw==",+ "cpu": [+ "arm64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "freebsd"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/freebsd-x64": {+ "version": "0.28.1",+ "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.28.1.tgz",+ "integrity": "sha512-i7dZ9vQgnvSCzi/rYCXNgtF/U+eKZNJBzu3eTQbRgHnM7tNSizLOkRFAl3qzVc/Op/u5YkHHa4pf/3DOYHthLQ==",+ "cpu": [+ "x64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "freebsd"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-arm": {+ "version": "0.28.1",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.28.1.tgz",+ "integrity": "sha512-qVXBOHQS+d5Y722GwJzJUtOLlX7km3CraOaGormF1pDtPd2C/l1SHRPgjLunLGe51Sh5YYWKMFDyV4SxgMQYTQ==",+ "cpu": [+ "arm"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-arm64": {+ "version": "0.28.1",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.28.1.tgz",+ "integrity": "sha512-yHs+0uc8+nvEAfAfxrWQKK5peSNzBc4PegcMO0EJ2hT71uA7vB8Ihg2e77R2P7SG5uYjPbHlLLmve4LLLRCf0g==",+ "cpu": [+ "arm64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-ia32": {+ "version": "0.28.1",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.28.1.tgz",+ "integrity": "sha512-d1z4ZuP0ajrfz/FhGT4vv278rX8KnPPJx8i5+AtK7TYbx9Le9F1hyzurZpkEyjkGa9dUGhQow4C1NmeGvqxN2w==",+ "cpu": [+ "ia32"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-loong64": {+ "version": "0.28.1",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.28.1.tgz",+ "integrity": "sha512-M5sRjUVZrkm1OAPR3dlOYzNmN+loZKGVi1VUQGrwuqLcbR6qeAz+famMhjASeH3YVKvZz+zT1jlh/keC3Rj/lg==",+ "cpu": [+ "loong64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-mips64el": {+ "version": "0.28.1",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.28.1.tgz",+ "integrity": "sha512-mRObBZeHh2OxcBFPWE/FjylkRgZdYuiTR3vaTozquCGOH14iP9oN4x4Ge81CoIDYQrXmIxpFumJBu5MtZpnQJQ==",+ "cpu": [+ "mips64el"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-ppc64": {+ "version": "0.28.1",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.28.1.tgz",+ "integrity": "sha512-slScBsMAb3GFDcdrCgLwZtPYRoH2H/youv10QiZyRjmsP48fznoveWytSgCI/R0ZcUgpc0ZhIUEx6LHts8yrfQ==",+ "cpu": [+ "ppc64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-riscv64": {+ "version": "0.28.1",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.28.1.tgz",+ "integrity": "sha512-kw0owk1o0GFETUJyW0jc0G4Yzs0BHZn0JDZ8JRT088vjJYX777BAs1fDGxAC+q831qOs2DTC96mNsG2opdfyyQ==",+ "cpu": [+ "riscv64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-s390x": {+ "version": "0.28.1",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.28.1.tgz",+ "integrity": "sha512-/lAIjX8aYFRByhh6L5rYtPEDRqa9de/4V/juOXcta5frjvzXO4/sqEtyytse0g3zZFuWu5cDN0MkLz2qRDD2Ag==",+ "cpu": [+ "s390x"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-x64": {+ "version": "0.28.1",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.28.1.tgz",+ "integrity": "sha512-u/anNYF2mmVOEDwLtnQ1wOr3EZ9sTNGLWrsYGYwHWzGA3Si84IOkHXlbWTD1NB+9/1lcnweYKO54uhxZydNzfA==",+ "cpu": [+ "x64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/netbsd-arm64": {+ "version": "0.28.1",+ "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.28.1.tgz",+ "integrity": "sha512-oks0DYbLwWMmaakTsCb+zL4E+aHRVLom9IJZOAthMQEPiQmydXHkziYEsGYRx0uNV/IjEKGAV941JzH02pflqw==",+ "cpu": [+ "arm64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "netbsd"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/netbsd-x64": {+ "version": "0.28.1",+ "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.28.1.tgz",+ "integrity": "sha512-aeL6lAnN89Hz43Mlh1G8ARasbuoYvSITDEx0tHh5b7jJnHcssqgjy9Yx430GDpmCa6OyrKoS0aNRjKundRizGg==",+ "cpu": [+ "x64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "netbsd"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/openbsd-arm64": {+ "version": "0.28.1",+ "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.28.1.tgz",+ "integrity": "sha512-MEFJe5C3R8pwXdZ5Y21oo6m7ePiS0d9pWucn99O/wvyJZChoIQKrQDxKrGeW8F5+T0okTHesAmDeiHDTIq0V/Q==",+ "cpu": [+ "arm64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "openbsd"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/openbsd-x64": {+ "version": "0.28.1",+ "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.28.1.tgz",+ "integrity": "sha512-i/ZLIOafE0Z8cI/XANJAixoJL/uRAoS2xOA3rb0xN+KK0K177cMAsQYkzHtBrtMXAKuAc7HGgcWiZ/sRC1Nxgw==",+ "cpu": [+ "x64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "openbsd"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/openharmony-arm64": {+ "version": "0.28.1",+ "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.28.1.tgz",+ "integrity": "sha512-ge+Z7EXFNt2BO1oAMsVpiQ8EwndV9i1xXerAeTIK7AtPs3bKFXQM7nlRxDSIUIMeueR1CNXxqztLzdNeReKBJg==",+ "cpu": [+ "arm64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "openharmony"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/sunos-x64": {+ "version": "0.28.1",+ "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.28.1.tgz",+ "integrity": "sha512-BEjgtECkL3vY+SaSQ6nzVfiALUeFxpawyp8Jmf5PtYhf1Ug40N1h/hxlhts+f1FvSvarEigdxS3BlSMI2PJLcQ==",+ "cpu": [+ "x64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "sunos"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/win32-arm64": {+ "version": "0.28.1",+ "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.28.1.tgz",+ "integrity": "sha512-lCv9eK/H6ZJWbE7bh2nw54CZ9M2nupBxJcTsdk/QQnWkdSjKGuxmmH8/GWrlT1eMmZfn4dGcCjRte397WqfQXA==",+ "cpu": [+ "arm64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "win32"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/win32-ia32": {+ "version": "0.28.1",+ "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.28.1.tgz",+ "integrity": "sha512-zvb/mB2bSCoJOpoCBgYKKpX6YM6mJBlBUVUtVj41DlZJVEB6/0CKlRYxP5wWl1C1ILiCoAU5wZZ4q1P3qeS6Eg==",+ "cpu": [+ "ia32"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "win32"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/win32-x64": {+ "version": "0.28.1",+ "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.28.1.tgz",+ "integrity": "sha512-bm4Mowrv+GXMlpWX++EcXw/iLyd1o3+bJkC2DkWXYVvgZCqD/bSj9ctZeAMC3cIxgjRVR2Dufaiu4YPxr5gW1A==",+ "cpu": [+ "x64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "win32"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@hono/node-server": {+ "version": "2.1.8",+ "resolved": "https://registry.npmjs.org/@hono/node-server/-/node-server-2.1.8.tgz",+ "integrity": "sha512-jdf7FHh6A1lzjpHHQUgxsg2GeER2vMetnAOfeActzcoli6jamlK+NAwL6Dsr5Fl3BS3tYUQzCdtZjU8Qxv7bEA==",+ "license": "MIT",+ "engines": {+ "node": ">=20"+ },+ "peerDependencies": {+ "hono": "^4 || ^5.0.0-0"+ }+ },+ "node_modules/@img/colour": {+ "version": "1.1.0",+ "resolved": "https://registry.npmjs.org/@img/colour/-/colour-1.1.0.tgz",+ "integrity": "sha512-Td76q7j57o/tLVdgS746cYARfSyxk8iEfRxewL9h4OMzYhbW4TAcppl0mT4eyqXddh6L/jwoM75mo7ixa/pCeQ==",+ "license": "MIT",+ "optional": true,+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@img/sharp-darwin-arm64": {+ "version": "0.35.5",+ "resolved": "https://registry.npmjs.org/@img/sharp-darwin-arm64/-/sharp-darwin-arm64-0.35.5.tgz",+ "integrity": "sha512-QRUlFQ0WxvdWyqqG/WtI3iupfD5rBzmCHXSdPsY91sAtVtTo7Q4cb6zOccZ3gqEqkr0f1As1ehLqmEpDsRf+lg==",+ "cpu": [+ "arm64"+ ],+ "license": "Apache-2.0",+ "optional": true,+ "os": [+ "darwin"+ ],+ "engines": {+ "node": ">=20.9.0"+ },+ "funding": {+ "url": "https://opencollective.com/libvips"+ },+ "optionalDependencies": {+ "@img/sharp-libvips-darwin-arm64": "1.3.4"+ }+ },+ "node_modules/@img/sharp-darwin-x64": {+ "version": "0.35.5",+ "resolved": "https://registry.npmjs.org/@img/sharp-darwin-x64/-/sharp-darwin-x64-0.35.5.tgz",+ "integrity": "sha512-+BR255RhDlpygUpOc/Jdt1nT6DQ3XG/ERo5wbcdOf5Q320dKtPCKPLR1LJs9VGXRaMa8l1uUa0tkCNOXiAxZUw==",+ "cpu": [+ "x64"+ ],+ "license": "Apache-2.0",+ "optional": true,+ "os": [+ "darwin"+ ],+ "engines": {+ "node": ">=20.9.0"+ },+ "funding": {+ "url": "https://opencollective.com/libvips"+ },+ "optionalDependencies": {+ "@img/sharp-libvips-darwin-x64": "1.3.4"+ }+ },+ "node_modules/@img/sharp-freebsd-wasm32": {+ "version": "0.35.5",+ "resolved": "https://registry.npmjs.org/@img/sharp-freebsd-wasm32/-/sharp-freebsd-wasm32-0.35.5.tgz",+ "integrity": "sha512-Y/z91nEZ4uIBX5X3nfTovjU9lHNKFYbL2lpHCLVNmXQK03VIZvXBBt0KxbPGp2SdGSF+2mQU4e+hQaWOt86iAw==",+ "license": "Apache-2.0",+ "optional": true,+ "os": [+ "freebsd"+ ],+ "dependencies": {+ "@img/sharp-wasm32": "0.35.5"+ },+ "engines": {+ "node": ">=20.9.0"+ },+ "funding": {+ "url": "https://opencollective.com/libvips"+ }+ },+ "node_modules/@img/sharp-libvips-darwin-arm64": {+ "version": "1.3.4",+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-arm64/-/sharp-libvips-darwin-arm64-1.3.4.tgz",+ "integrity": "sha512-5R89nBYiRdUlSWJxPhO+GVtaXzXSxKnRu/xqMn3KTA3L9EB9Oy/P+Nn2f2vlhPuUdy/Zusb2DarbyTpGCfEDuw==",+ "cpu": [+ "arm64"+ ],+ "license": "LGPL-3.0-or-later",+ "optional": true,+ "os": [+ "darwin"+ ],+ "funding": {+ "url": "https://opencollective.com/libvips"+ }+ },+ "node_modules/@img/sharp-libvips-darwin-x64": {+ "version": "1.3.4",+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-x64/-/sharp-libvips-darwin-x64-1.3.4.tgz",+ "integrity": "sha512-iR2OKH80yi0U+dUplyh3/xdpFvps6YkCwsXenIJxqxR1v9o+xtKTGbS9H7cps+2Vxjc8B1j96p75NmTGjIhtpQ==",+ "cpu": [+ "x64"+ ],+ "license": "LGPL-3.0-or-later",+ "optional": true,+ "os": [+ "darwin"+ ],+ "funding": {+ "url": "https://opencollective.com/libvips"+ }+ },+ "node_modules/@img/sharp-libvips-linux-arm": {+ "version": "1.3.4",+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm/-/sharp-libvips-linux-arm-1.3.4.tgz",+ "integrity": "sha512-LmRtTsOHuvM2+wlO2Db37dx5MiZhB0FvSunciw48YjdOkZz9KAiRbm8ujeMOA1INqmei5NapFxYEK1D1ZSidmw==",+ "cpu": [+ "arm"+ ],+ "libc": [+ "glibc"+ ],+ "license": "LGPL-3.0-or-later",+ "optional": true,+ "os": [+ "linux"+ ],+ "funding": {+ "url": "https://opencollective.com/libvips"+ }+ },+ "node_modules/@img/sharp-libvips-linux-arm64": {+ "version": "1.3.4",+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm64/-/sharp-libvips-linux-arm64-1.3.4.tgz",+ "integrity": "sha512-Y3dgX/6lE2QhQb+Gxy0WZxfg9MEm/JBjamZpS2IklP7xIQoKN4hzAm7KcMVGtaVDt3neE9OKBC7vAfonA/Lr1A==",+ "cpu": [+ "arm64"+ ],+ "libc": [+ "glibc"+ ],+ "license": "LGPL-3.0-or-later",+ "optional": true,+ "os": [+ "linux"+ ],+ "funding": {+ "url": "https://opencollective.com/libvips"+ }+ },+ "node_modules/@img/sharp-libvips-linux-ppc64": {+ "version": "1.3.4",+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-ppc64/-/sharp-libvips-linux-ppc64-1.3.4.tgz",+ "integrity": "sha512-Le6boB8Tai0Nis+gIxIpKx68UDVVIqdR8Tin5Yf1z2LJJQLDJvCDRqRu+jC2qCoD+eIomonmOwB4smBRxfVpYQ==",+ "cpu": [+ "ppc64"+ ],+ "libc": [+ "glibc"+ ],+ "license": "LGPL-3.0-or-later",+ "optional": true,+ "os": [+ "linux"+ ],+ "funding": {+ "url": "https://opencollective.com/libvips"+ }+ },+ "node_modules/@img/sharp-libvips-linux-riscv64": {+ "version": "1.3.4",+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-riscv64/-/sharp-libvips-linux-riscv64-1.3.4.tgz",+ "integrity": "sha512-aHkkIEHPRdQEegJN20MLmGtxYD9R2wQr3Cwpddnu5+YKMt6Uzax7S9h5gpZTo8wyrGuZSlfQ63OevL5mTyOC7Q==",+ "cpu": [+ "riscv64"+ ],+ "libc": [+ "glibc"+ ],+ "license": "LGPL-3.0-or-later",+ "optional": true,+ "os": [+ "linux"+ ],+ "funding": {+ "url": "https://opencollective.com/libvips"+ }+ },+ "node_modules/@img/sharp-libvips-linux-s390x": {+ "version": "1.3.4",+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-s390x/-/sharp-libvips-linux-s390x-1.3.4.tgz",+ "integrity": "sha512-ra/mB6MikESDUO7Yg+Mi95bFBb9GsObURuhnOv3OqknjGe9sZrG8tCe9q0xSIGrtLgvgw0gKnFWcK4blSgQOuQ==",+ "cpu": [+ "s390x"+ ],+ "libc": [+ "glibc"+ ],+ "license": "LGPL-3.0-or-later",+ "optional": true,+ "os": [+ "linux"+ ],+ "funding": {+ "url": "https://opencollective.com/libvips"+ }+ },+ "node_modules/@img/sharp-libvips-linux-x64": {+ "version": "1.3.4",+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-x64/-/sharp-libvips-linux-x64-1.3.4.tgz",+ "integrity": "sha512-GJ//SSXbnwSDes02umB3nDJLFcQzw8a18V8fyhqr6tV515tOEMdImjjxj1AoafMRz56F3PHgftnj1QEKSU1zkw==",+ "cpu": [+ "x64"+ ],+ "libc": [+ "glibc"+ ],+ "license": "LGPL-3.0-or-later",+ "optional": true,+ "os": [+ "linux"+ ],+ "funding": {+ "url": "https://opencollective.com/libvips"+ }+ },+ "node_modules/@img/sharp-libvips-linuxmusl-arm64": {+ "version": "1.3.4",+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linuxmusl-arm64/-/sharp-libvips-linuxmusl-arm64-1.3.4.tgz",+ "integrity": "sha512-hvulFwtjUcagsis6BBxHwGFwWoNZjgYmULGVrZcyfNbjA8hKILbRxGg15/7w5HDyXHXUos/j6baAWqnCyQ2DWA==",+ "cpu": [+ "arm64"+ ],+ "libc": [+ "musl"+ ],+ "license": "LGPL-3.0-or-later",+ "optional": true,+ "os": [+ "linux"+ ],+ "funding": {+ "url": "https://opencollective.com/libvips"+ }+ },+ "node_modules/@img/sharp-libvips-linuxmusl-x64": {+ "version": "1.3.4",+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linuxmusl-x64/-/sharp-libvips-linuxmusl-x64-1.3.4.tgz",+ "integrity": "sha512-6zXKeE/p39I1AmA3cJG35eyBGNqNddLnUXjhwBnsGjFPWqf5VKkDBEqaEkPDoTEtkxwi2vv8Tcr2mDyP4So7Fg==",+ "cpu": [+ "x64"+ ],+ "libc": [+ "musl"+ ],+ "license": "LGPL-3.0-or-later",+ "optional": true,+ "os": [+ "linux"+ ],+ "funding": {+ "url": "https://opencollective.com/libvips"+ }+ },+ "node_modules/@img/sharp-linux-arm": {+ "version": "0.35.5",+ "resolved": "https://registry.npmjs.org/@img/sharp-linux-arm/-/sharp-linux-arm-0.35.5.tgz",+ "integrity": "sha512-LEaXK2WdXVK5ykcw0buWyPMsmLLL2vpHLD6yrNSW+JGEL3BZPA4tpKN6iaMc4AxTTAoaX/sU1rOL51lcIz48ZQ==",+ "cpu": [+ "arm"+ ],+ "libc": [+ "glibc"+ ],+ "license": "Apache-2.0",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=20.9.0"+ },+ "funding": {+ "url": "https://opencollective.com/libvips"+ },+ "optionalDependencies": {+ "@img/sharp-libvips-linux-arm": "1.3.4"+ }+ },+ "node_modules/@img/sharp-linux-arm64": {+ "version": "0.35.5",+ "resolved": "https://registry.npmjs.org/@img/sharp-linux-arm64/-/sharp-linux-arm64-0.35.5.tgz",+ "integrity": "sha512-LYVx5JTsOM2CBzmxreh+nl64/3H6Xb09iSLknqH47z2T2DFFxDeFLP5y4dJwe6H7uGQlHPyEEtIqyo3DYsRwdQ==",+ "cpu": [+ "arm64"+ ],+ "libc": [+ "glibc"+ ],+ "license": "Apache-2.0",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=20.9.0"+ },+ "funding": {+ "url": "https://opencollective.com/libvips"+ },+ "optionalDependencies": {+ "@img/sharp-libvips-linux-arm64": "1.3.4"+ }+ },+ "node_modules/@img/sharp-linux-ppc64": {+ "version": "0.35.5",+ "resolved": "https://registry.npmjs.org/@img/sharp-linux-ppc64/-/sharp-linux-ppc64-0.35.5.tgz",+ "integrity": "sha512-QVxAAq8evVRI9ia2vqgwrmWucn5Dfv+JdWzj75pD8omHLPSP7f8p20O8jxzjCcuCEQEOtYOZUmX1hkiZ0kdevA==",+ "cpu": [+ "ppc64"+ ],+ "libc": [+ "glibc"+ ],+ "license": "Apache-2.0",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=20.9.0"+ },+ "funding": {+ "url": "https://opencollective.com/libvips"+ },+ "optionalDependencies": {+ "@img/sharp-libvips-linux-ppc64": "1.3.4"+ }+ },+ "node_modules/@img/sharp-linux-riscv64": {+ "version": "0.35.5",+ "resolved": "https://registry.npmjs.org/@img/sharp-linux-riscv64/-/sharp-linux-riscv64-0.35.5.tgz",+ "integrity": "sha512-LtdreXguaavKODPIfzJ4kffx7UNt1omwtK0rch4EBbbSTXPnxWmYSayXdLJw0fJzQ97kHt1gL/yh4tvU+nCyRQ==",+ "cpu": [+ "riscv64"+ ],+ "libc": [+ "glibc"+ ],+ "license": "Apache-2.0",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=20.9.0"+ },+ "funding": {+ "url": "https://opencollective.com/libvips"+ },+ "optionalDependencies": {+ "@img/sharp-libvips-linux-riscv64": "1.3.4"+ }+ },+ "node_modules/@img/sharp-linux-s390x": {+ "version": "0.35.5",+ "resolved": "https://registry.npmjs.org/@img/sharp-linux-s390x/-/sharp-linux-s390x-0.35.5.tgz",+ "integrity": "sha512-UZasTOFiYzotTsGOCu42BfUzP6Tu6Do/947iRm1RsLKvlllxwGcn4RN27LibGWceix4Y+Pmw3jsnTcCQIgWjqA==",+ "cpu": [+ "s390x"+ ],+ "libc": [+ "glibc"+ ],+ "license": "Apache-2.0",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=20.9.0"+ },+ "funding": {+ "url": "https://opencollective.com/libvips"+ },+ "optionalDependencies": {+ "@img/sharp-libvips-linux-s390x": "1.3.4"+ }+ },+ "node_modules/@img/sharp-linux-x64": {+ "version": "0.35.5",+ "resolved": "https://registry.npmjs.org/@img/sharp-linux-x64/-/sharp-linux-x64-0.35.5.tgz",+ "integrity": "sha512-SxFtLTeJInhAA9Q836kux2vZNeOBQEx658qvbboZScr0wIARym3IcGmW7KpVD5sbVg0Ojy+udFQdayYIZyoNog==",+ "cpu": [+ "x64"+ ],+ "libc": [+ "glibc"+ ],+ "license": "Apache-2.0",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=20.9.0"+ },+ "funding": {+ "url": "https://opencollective.com/libvips"+ },+ "optionalDependencies": {+ "@img/sharp-libvips-linux-x64": "1.3.4"+ }+ },+ "node_modules/@img/sharp-linuxmusl-arm64": {+ "version": "0.35.5",+ "resolved": "https://registry.npmjs.org/@img/sharp-linuxmusl-arm64/-/sharp-linuxmusl-arm64-0.35.5.tgz",+ "integrity": "sha512-9HbMclmI1zlNkFRs3z9/eBtDjfD0sGlrX1z6b1qwmiFY5ElDLh4BC0LPBdVp7z1DXFiKlIcznf+ZlsuZzLxQqg==",+ "cpu": [+ "arm64"+ ],+ "libc": [+ "musl"+ ],+ "license": "Apache-2.0",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=20.9.0"+ },+ "funding": {+ "url": "https://opencollective.com/libvips"+ },+ "optionalDependencies": {+ "@img/sharp-libvips-linuxmusl-arm64": "1.3.4"+ }+ },+ "node_modules/@img/sharp-linuxmusl-x64": {+ "version": "0.35.5",+ "resolved": "https://registry.npmjs.org/@img/sharp-linuxmusl-x64/-/sharp-linuxmusl-x64-0.35.5.tgz",+ "integrity": "sha512-4KOphqB035HrVdqLZfCgMzzERrQkkzOwRhl4OAkRO1YCldbaFjySXMaK534Mo0V+LndnlJk+sbUyLeU0ULyD1A==",+ "cpu": [+ "x64"+ ],+ "libc": [+ "musl"+ ],+ "license": "Apache-2.0",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=20.9.0"+ },+ "funding": {+ "url": "https://opencollective.com/libvips"+ },+ "optionalDependencies": {+ "@img/sharp-libvips-linuxmusl-x64": "1.3.4"+ }+ },+ "node_modules/@img/sharp-wasm32": {+ "version": "0.35.5",+ "resolved": "https://registry.npmjs.org/@img/sharp-wasm32/-/sharp-wasm32-0.35.5.tgz",+ "integrity": "sha512-Ptsga1su4tQx+LLF1ECS9U6nz5kmrXKo6XVbtR48Ke3ZRxxgaWBu7IDtEe1quo8hiupwm6WFqxVlXaSf7IINGQ==",+ "license": "Apache-2.0 AND LGPL-3.0-or-later AND MIT",+ "optional": true,+ "dependencies": {+ "@emnapi/runtime": "^1.11.3"+ },+ "engines": {+ "node": ">=20.9.0"+ },+ "funding": {+ "url": "https://opencollective.com/libvips"+ }+ },+ "node_modules/@img/sharp-webcontainers-wasm32": {+ "version": "0.35.5",+ "resolved": "https://registry.npmjs.org/@img/sharp-webcontainers-wasm32/-/sharp-webcontainers-wasm32-0.35.5.tgz",+ "integrity": "sha512-hfhF/FmoQyTUkA0bIKFOtw536BQSeBMe6BF6QyWlrPxT754+TFLaZ7sKKTfvvM0yJgKgaYTwnFCIZ/GuDw5SUA==",+ "cpu": [+ "wasm32"+ ],+ "license": "Apache-2.0",+ "optional": true,+ "dependencies": {+ "@img/sharp-wasm32": "0.35.5"+ },+ "engines": {+ "node": ">=20.9.0"+ },+ "funding": {+ "url": "https://opencollective.com/libvips"+ }+ },+ "node_modules/@img/sharp-win32-arm64": {+ "version": "0.35.5",+ "resolved": "https://registry.npmjs.org/@img/sharp-win32-arm64/-/sharp-win32-arm64-0.35.5.tgz",+ "integrity": "sha512-X4t7g+7ZA5DKblCBEXGjUqqemj4vczING/5viFwAL8h4N3qYeyjwdCvRLHi4EdOUI+2Z7UFlp1VM+p/AuEtm6Q==",+ "cpu": [+ "arm64"+ ],+ "license": "Apache-2.0 AND LGPL-3.0-or-later",+ "optional": true,+ "os": [+ "win32"+ ],+ "engines": {+ "node": ">=20.9.0"+ },+ "funding": {+ "url": "https://opencollective.com/libvips"+ }+ },+ "node_modules/@img/sharp-win32-ia32": {+ "version": "0.35.5",+ "resolved": "https://registry.npmjs.org/@img/sharp-win32-ia32/-/sharp-win32-ia32-0.35.5.tgz",+ "integrity": "sha512-5Zm82LoBc43nhwNybZlG7Y1KO//Zhsn306fQl29ZOuStHLGTo3BWL83q3cznX0poxSAMuYL1On/BHBxkBeKr6A==",+ "cpu": [+ "ia32"+ ],+ "license": "Apache-2.0 AND LGPL-3.0-or-later",+ "optional": true,+ "os": [+ "win32"+ ],+ "engines": {+ "node": "^20.9.0"+ },+ "funding": {+ "url": "https://opencollective.com/libvips"+ }+ },+ "node_modules/@img/sharp-win32-x64": {+ "version": "0.35.5",+ "resolved": "https://registry.npmjs.org/@img/sharp-win32-x64/-/sharp-win32-x64-0.35.5.tgz",+ "integrity": "sha512-x76eH0vEiHlcMQu8Y8IenntaACtddpT6W0wmXtWrnKcnKI7ME5DdgqhAD6SEWOEl1v2zDvkZDhFA9KnURwpfqg==",+ "cpu": [+ "x64"+ ],+ "license": "Apache-2.0 AND LGPL-3.0-or-later",+ "optional": true,+ "os": [+ "win32"+ ],+ "engines": {+ "node": ">=20.9.0"+ },+ "funding": {+ "url": "https://opencollective.com/libvips"+ }+ },+ "node_modules/@jridgewell/gen-mapping": {+ "version": "0.3.13",+ "resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz",+ "integrity": "sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA==",+ "license": "MIT",+ "dependencies": {+ "@jridgewell/sourcemap-codec": "^1.5.0",+ "@jridgewell/trace-mapping": "^0.3.24"+ }+ },+ "node_modules/@jridgewell/remapping": {+ "version": "2.3.5",+ "resolved": "https://registry.npmjs.org/@jridgewell/remapping/-/remapping-2.3.5.tgz",+ "integrity": "sha512-LI9u/+laYG4Ds1TDKSJW2YPrIlcVYOwi2fUC6xB43lueCjgxV4lffOCZCtYFiH6TNOX+tQKXx97T4IKHbhyHEQ==",+ "license": "MIT",+ "dependencies": {+ "@jridgewell/gen-mapping": "^0.3.5",+ "@jridgewell/trace-mapping": "^0.3.24"+ }+ },+ "node_modules/@jridgewell/resolve-uri": {+ "version": "3.1.3",+ "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.3.tgz",+ "integrity": "sha512-lhTtjtoEArWBjismtfS761S9Hlyn+nIZqOZVYoZ1Xn82PMNMVnk+jj/NhC4fAXGTs7ydONcJiR5vyQBTMDu27g==",+ "license": "MIT",+ "engines": {+ "node": ">=6.0.0"+ }+ },+ "node_modules/@jridgewell/source-map": {+ "version": "0.3.11",+ "resolved": "https://registry.npmjs.org/@jridgewell/source-map/-/source-map-0.3.11.tgz",+ "integrity": "sha512-ZMp1V8ZFcPG5dIWnQLr3NSI1MiCU7UETdS/A0G8V/XWHvJv3ZsFqutJn1Y5RPmAPX6F3BiE397OqveU/9NCuIA==",+ "license": "MIT",+ "dependencies": {+ "@jridgewell/gen-mapping": "^0.3.5",+ "@jridgewell/trace-mapping": "^0.3.25"+ }+ },+ "node_modules/@jridgewell/sourcemap-codec": {+ "version": "1.6.0",+ "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.6.0.tgz",+ "integrity": "sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw==",+ "license": "MIT"+ },+ "node_modules/@jridgewell/trace-mapping": {+ "version": "0.3.31",+ "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.31.tgz",+ "integrity": "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==",+ "license": "MIT",+ "dependencies": {+ "@jridgewell/resolve-uri": "^3.1.0",+ "@jridgewell/sourcemap-codec": "^1.4.14"+ }+ },+ "node_modules/@mediabunny/aac-encoder": {+ "version": "1.64.0",+ "resolved": "https://registry.npmjs.org/@mediabunny/aac-encoder/-/aac-encoder-1.64.0.tgz",+ "integrity": "sha512-u9BnYGgDsPw4xjD7YRt285wsz+QR5Cp0Lzi/aZTrZ1FHBqYW4c7uyIFD1NhU+jKOO5IZgXhMOw9Y2IEjyr2k5Q==",+ "license": "MPL-2.0",+ "funding": {+ "type": "individual",+ "url": "https://github.com/sponsors/Vanilagy"+ },+ "peerDependencies": {+ "mediabunny": "^1.0.0"+ }+ },+ "node_modules/@mediabunny/flac-encoder": {+ "version": "1.64.0",+ "resolved": "https://registry.npmjs.org/@mediabunny/flac-encoder/-/flac-encoder-1.64.0.tgz",+ "integrity": "sha512-PN0B2rwLT6Ovkk88ayaaamYduHj35r7EVM1yu5mjxPrbeO2VoCZSD2aTONzYQGg1PnSJmc9jwtRrK/EMe6pwsg==",+ "license": "MPL-2.0",+ "funding": {+ "type": "individual",+ "url": "https://github.com/sponsors/Vanilagy"+ },+ "peerDependencies": {+ "mediabunny": "^1.0.0"+ }+ },+ "node_modules/@mediabunny/mp3-encoder": {+ "version": "1.64.0",+ "resolved": "https://registry.npmjs.org/@mediabunny/mp3-encoder/-/mp3-encoder-1.64.0.tgz",+ "integrity": "sha512-agJx3Vv2NsrJDwMBF4l5a0SEA6cszmFS4LVyLaHCQNAY0BKm55HEo+vbD51CJIxuHSYtvFdaurJqHh/S6kF7XQ==",+ "license": "MPL-2.0",+ "funding": {+ "type": "individual",+ "url": "https://github.com/sponsors/Vanilagy"+ },+ "peerDependencies": {+ "mediabunny": "^1.0.0"+ }+ },+ "node_modules/@napi-rs/wasm-runtime": {+ "version": "1.1.6",+ "resolved": "https://registry.npmjs.org/@napi-rs/wasm-runtime/-/wasm-runtime-1.1.6.tgz",+ "integrity": "sha512-ZLv/JdUfkvOy9eCnnBaGfiO+XimbjebAeO+MRQqD/B+FR1tnRN0tpKSJHRbE8sFfS6aqsXZ67TQjfwfsxULVbg==",+ "license": "MIT",+ "optional": true,+ "dependencies": {+ "@tybys/wasm-util": "^0.10.3"+ },+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/Brooooooklyn"+ },+ "peerDependencies": {+ "@emnapi/core": "^1.7.1",+ "@emnapi/runtime": "^1.7.1"+ }+ },+ "node_modules/@puppeteer/browsers": {+ "version": "3.2.7",+ "resolved": "https://registry.npmjs.org/@puppeteer/browsers/-/browsers-3.2.7.tgz",+ "integrity": "sha512-B3C/v8OEEaJYcN1IzzgbPmt+GbFANr4Mf/NrqNuGk/dIchrv6quNqxgT+A6qE0Ge0MN95NjKUddcR1JMpYRMWA==",+ "license": "Apache-2.0",+ "dependencies": {+ "modern-tar": "^0.8.6",+ "yargs": "^18.0.0"+ },+ "bin": {+ "browsers": "lib/main-cli.js"+ },+ "engines": {+ "node": ">=22.12.0"+ },+ "peerDependencies": {+ "proxy-agent": ">=8.0.1",+ "yauzl": "^2.10.0 || ^3.4.0"+ },+ "peerDependenciesMeta": {+ "proxy-agent": {+ "optional": true+ },+ "yauzl": {+ "optional": true+ }+ }+ },+ "node_modules/@remotion/bundler": {+ "version": "4.0.543",+ "resolved": "https://registry.npmjs.org/@remotion/bundler/-/bundler-4.0.543.tgz",+ "integrity": "sha512-D8NjdhQa4X4KXVnQ4hbsjH36MnL0CFTyV0wNJfVdnhKYXmbCZtzv3LnpijGZArxY1q+wh7CXT9eE3WgnnKqaYg==",+ "license": "SEE LICENSE IN LICENSE.md",+ "dependencies": {+ "@remotion/studio": "4.0.543",+ "@remotion/studio-shared": "4.0.543",+ "@remotion/timeline-utils": "4.0.543",+ "@rspack/core": "2.3.0",+ "@rspack/plugin-react-refresh": "2.0.2",+ "css-loader": "7.1.4",+ "esbuild": "0.28.1",+ "react-refresh": "0.18.0",+ "remotion": "4.0.543",+ "style-loader": "4.0.0",+ "webpack": "5.105.0"+ },+ "peerDependencies": {+ "react": ">=16.8.0",+ "react-dom": ">=16.8.0"+ }+ },+ "node_modules/@remotion/captions": {+ "version": "4.0.543",+ "resolved": "https://registry.npmjs.org/@remotion/captions/-/captions-4.0.543.tgz",+ "integrity": "sha512-qlMHi2jWnQrF1TrHbP/Es3i+XaIJuVMXbvOC/LXNYYg7r0tOl6j3auXVYUW5V6okZCR+gMjl9An0fSmbXCtduA==",+ "license": "MIT"+ },+ "node_modules/@remotion/cli": {+ "version": "4.0.543",+ "resolved": "https://registry.npmjs.org/@remotion/cli/-/cli-4.0.543.tgz",+ "integrity": "sha512-pDc+pUIAuhoaQN8hqAalxfCgBAjoyU96Q5xbDdJia3xkF9Eq8U5QBAXnc/dVppgqur7f0w+1OY0bBjca/0LB+Q==",+ "license": "SEE LICENSE IN LICENSE.md",+ "dependencies": {+ "@babel/parser": "7.24.1",+ "@remotion/bundler": "4.0.543",+ "@remotion/codemods": "4.0.543",+ "@remotion/licensing": "4.0.543",+ "@remotion/media-utils": "4.0.543",+ "@remotion/player": "4.0.543",+ "@remotion/renderer": "4.0.543",+ "@remotion/studio": "4.0.543",+ "@remotion/studio-protocol": "4.0.543",+ "@remotion/studio-server": "4.0.543",+ "@remotion/studio-shared": "4.0.543",+ "dotenv": "17.3.1",+ "mediabunny": "1.64.0",+ "minimist": "1.2.6",+ "prompts": "2.4.2",+ "remotion": "4.0.543",+ "semver": "7.5.3"+ },+ "bin": {+ "remotion": "remotion-cli.js",+ "remotionb": "remotionb-cli.js",+ "remotiond": "remotiond-cli.js"+ },+ "peerDependencies": {+ "react": ">=16.8.0",+ "react-dom": ">=16.8.0"+ }+ },+ "node_modules/@remotion/codemods": {+ "version": "4.0.543",+ "resolved": "https://registry.npmjs.org/@remotion/codemods/-/codemods-4.0.543.tgz",+ "integrity": "sha512-/0KVSJMa6p2TqcsV1ImaHd8R/lKGJ1J/LWOsZi0yDK+dIietdjZO7jXYXyBppy9BuEES9IWLzGG0jFpEmBMA5g==",+ "license": "MIT",+ "dependencies": {+ "@babel/parser": "7.24.1",+ "@babel/types": "7.24.0",+ "@remotion/studio-protocol": "4.0.543",+ "@remotion/studio-shared": "4.0.543",+ "ast-types": "0.16.1",+ "recast": "0.23.21",+ "remotion": "4.0.543"+ }+ },+ "node_modules/@remotion/compositor-darwin-arm64": {+ "version": "4.0.543",+ "resolved": "https://registry.npmjs.org/@remotion/compositor-darwin-arm64/-/compositor-darwin-arm64-4.0.543.tgz",+ "integrity": "sha512-vQbuZB/foOzEgw6zy2R6LF82v0nSQX2A5pBWiNtBXlm7z5DstBgKeJZLVquxnhN7GHXVwOWZcVQqeOegM+acGg==",+ "cpu": [+ "arm64"+ ],+ "optional": true,+ "os": [+ "darwin"+ ]+ },+ "node_modules/@remotion/compositor-darwin-x64": {+ "version": "4.0.543",+ "resolved": "https://registry.npmjs.org/@remotion/compositor-darwin-x64/-/compositor-darwin-x64-4.0.543.tgz",+ "integrity": "sha512-gZH/uXHIxokz7DD0Fenhv1KQwe2RX/QkZpw8fkD4CPx0dhzQTgBJTqptbguIG1tPVpLuDHv4WQkY4rH78SLBTg==",+ "cpu": [+ "x64"+ ],+ "optional": true,+ "os": [+ "darwin"+ ]+ },+ "node_modules/@remotion/compositor-linux-arm64-gnu": {+ "version": "4.0.543",+ "resolved": "https://registry.npmjs.org/@remotion/compositor-linux-arm64-gnu/-/compositor-linux-arm64-gnu-4.0.543.tgz",+ "integrity": "sha512-v3tnneapzP2bcammFlcRNPejELM+p/qZXMrxgIoAsVo/zgRpLjkD7uZmidapX2fDr4X022VNwnKA5PG0zmXnog==",+ "cpu": [+ "arm64"+ ],+ "libc": [+ "glibc"+ ],+ "optional": true,+ "os": [+ "linux"+ ]+ },+ "node_modules/@remotion/compositor-linux-arm64-musl": {+ "version": "4.0.543",+ "resolved": "https://registry.npmjs.org/@remotion/compositor-linux-arm64-musl/-/compositor-linux-arm64-musl-4.0.543.tgz",+ "integrity": "sha512-U6PPG7sVcpQEHqTkyNQFHFPiYRQ+I2d+HTlQ3egB2+hr3jSlLRN6+9hJCjiu3gbwwt7A9wKqM6s7uW8mUlXDDg==",+ "cpu": [+ "arm64"+ ],+ "libc": [+ "musl"+ ],+ "optional": true,+ "os": [+ "linux"+ ]+ },+ "node_modules/@remotion/compositor-linux-x64-gnu": {+ "version": "4.0.543",+ "resolved": "https://registry.npmjs.org/@remotion/compositor-linux-x64-gnu/-/compositor-linux-x64-gnu-4.0.543.tgz",+ "integrity": "sha512-NJu4x01+iXH4ojnr3X3eV8z3nUTQLJdHSAZG4tcrRqvudghc3T4/jxi2yJZDEit5z2mGIpv+ArzjSi9HtA/YqQ==",+ "cpu": [+ "x64"+ ],+ "libc": [+ "glibc"+ ],+ "optional": true,+ "os": [+ "linux"+ ]+ },+ "node_modules/@remotion/compositor-linux-x64-musl": {+ "version": "4.0.543",+ "resolved": "https://registry.npmjs.org/@remotion/compositor-linux-x64-musl/-/compositor-linux-x64-musl-4.0.543.tgz",+ "integrity": "sha512-uWqy9MsKZo+CGiZLlEULjKaIYhReYzKDoSt0kRLBoO5CmpqCK9W5pstM9R43+5Eg9T3Om6Ib0Rnv8c8S0z21ZQ==",+ "cpu": [+ "x64"+ ],+ "libc": [+ "musl"+ ],+ "optional": true,+ "os": [+ "linux"+ ]+ },+ "node_modules/@remotion/compositor-win32-x64-msvc": {+ "version": "4.0.543",+ "resolved": "https://registry.npmjs.org/@remotion/compositor-win32-x64-msvc/-/compositor-win32-x64-msvc-4.0.543.tgz",+ "integrity": "sha512-sdObydvUpSAjOlc9Mz/oJUNFwR9gCL+Gub4Wq0tu5Y1qEv/P4YslO0kuYhknCGIzq2yTKhK5s4MpVD3FVvr35w==",+ "cpu": [+ "x64"+ ],+ "optional": true,+ "os": [+ "win32"+ ]+ },+ "node_modules/@remotion/effects": {+ "version": "4.0.543",+ "resolved": "https://registry.npmjs.org/@remotion/effects/-/effects-4.0.543.tgz",+ "integrity": "sha512-dX8adEAJbrBUwyDBu76XUe6yQtMbOJiavi002SggeeBksqCvEY6QJiI10fo3E2WdwGP1/U34DMx22orQMnxPYQ==",+ "license": "UNLICENSED",+ "dependencies": {+ "remotion": "4.0.543"+ }+ },+ "node_modules/@remotion/elevenlabs": {+ "version": "4.0.543",+ "resolved": "https://registry.npmjs.org/@remotion/elevenlabs/-/elevenlabs-4.0.543.tgz",+ "integrity": "sha512-ZN+V7k/AcS76AVLqT1O9fW+PyZt8Oa5wQ6Xzsf3wpuLK1ojrheg9HP0s7aHMfuo5os6v125QTATZj+I3U3CRCw==",+ "license": "MIT",+ "dependencies": {+ "@remotion/captions": "4.0.543",+ "zod": "4.6.7"+ }+ },+ "node_modules/@remotion/licensing": {+ "version": "4.0.543",+ "resolved": "https://registry.npmjs.org/@remotion/licensing/-/licensing-4.0.543.tgz",+ "integrity": "sha512-igTuOmTo6JYdn1JYwxN27ipkzXr65vlhcm6K4eyrELg+S/Cn9wpP7+V5FpJR30Kh2RTTcADtAua68ZNWXS/stw==",+ "license": "MIT"+ },+ "node_modules/@remotion/media": {+ "version": "4.0.543",+ "resolved": "https://registry.npmjs.org/@remotion/media/-/media-4.0.543.tgz",+ "integrity": "sha512-IV+jpXFDKksm/JZQJTssk9XMx28DaDI+By3v7uyGZEFv5DWj+aVjHKTKo0gNdTWVuGcQ5j6NKXjYczvLhcdgyA==",+ "dependencies": {+ "mediabunny": "1.64.0",+ "remotion": "4.0.543",+ "zod": "4.6.7"+ },+ "peerDependencies": {+ "react": ">=16.8.0",+ "react-dom": ">=16.8.0"+ }+ },+ "node_modules/@remotion/media-utils": {+ "version": "4.0.543",+ "resolved": "https://registry.npmjs.org/@remotion/media-utils/-/media-utils-4.0.543.tgz",+ "integrity": "sha512-qH5J3FHhxw+9tr315L0+8J23I4ebtaQyPLBBki0tUay1dpoRpU3qWLu/LTxaIBK3KHHmYguomMT2967IFxiHYA==",+ "license": "MIT",+ "dependencies": {+ "mediabunny": "1.64.0",+ "remotion": "4.0.543"+ },+ "peerDependencies": {+ "react": ">=16.8.0",+ "react-dom": ">=16.8.0"+ }+ },+ "node_modules/@remotion/openai-whisper": {+ "version": "4.0.543",+ "resolved": "https://registry.npmjs.org/@remotion/openai-whisper/-/openai-whisper-4.0.543.tgz",+ "integrity": "sha512-xutdQsAl4NJw9+8QnsyhmncPauJNHWGMzGu4TNJp9OGPh+eVKJgtPDuVNSfTJgKLcKzCDDOShzpE8LatS8vsug==",+ "license": "MIT",+ "dependencies": {+ "@remotion/captions": "4.0.543",+ "zod": "4.6.7"+ }+ },+ "node_modules/@remotion/paths": {+ "version": "4.0.543",+ "resolved": "https://registry.npmjs.org/@remotion/paths/-/paths-4.0.543.tgz",+ "integrity": "sha512-+++2ZHZBv56e5bsDxoOGQgqky+l29pTEbHVfXt/N41M2wZ8Z8LX1DIJIeZiwyQODHEMJl3hh+weXZmAbH2uF4w==",+ "license": "MIT",+ "dependencies": {+ "remotion": "4.0.543"+ }+ },+ "node_modules/@remotion/player": {+ "version": "4.0.543",+ "resolved": "https://registry.npmjs.org/@remotion/player/-/player-4.0.543.tgz",+ "integrity": "sha512-XokTrZDF/8L8nSLB7rWDmIXX/LFcnJcpP/7aSdl5mD6Epr1HuWsYlQlxbqZQC2ZkuZZA0b/mCUJGbam5npIhgA==",+ "license": "SEE LICENSE IN LICENSE.md",+ "dependencies": {+ "remotion": "4.0.543"+ },+ "peerDependencies": {+ "react": ">=16.8.0",+ "react-dom": ">=16.8.0"+ }+ },+ "node_modules/@remotion/renderer": {+ "version": "4.0.543",+ "resolved": "https://registry.npmjs.org/@remotion/renderer/-/renderer-4.0.543.tgz",+ "integrity": "sha512-/Q0O0X5Tu9Vycka1iK0YeG7WwszHtErCcMdEp2LYKCn7JONoXmh5MG+WD91RI3NIwkM+OdXsqPY04e27bAYhLw==",+ "license": "SEE LICENSE IN LICENSE.md",+ "dependencies": {+ "@remotion/licensing": "4.0.543",+ "@remotion/streaming": "4.0.543",+ "execa": "5.1.1",+ "remotion": "4.0.543",+ "source-map": "0.8.0",+ "ws": "8.21.0"+ },+ "optionalDependencies": {+ "@remotion/compositor-darwin-arm64": "4.0.543",+ "@remotion/compositor-darwin-x64": "4.0.543",+ "@remotion/compositor-linux-arm64-gnu": "4.0.543",+ "@remotion/compositor-linux-arm64-musl": "4.0.543",+ "@remotion/compositor-linux-x64-gnu": "4.0.543",+ "@remotion/compositor-linux-x64-musl": "4.0.543",+ "@remotion/compositor-win32-x64-msvc": "4.0.543"+ },+ "peerDependencies": {+ "react": ">=16.8.0",+ "react-dom": ">=16.8.0"+ }+ },+ "node_modules/@remotion/sdk": {+ "version": "4.0.543",+ "resolved": "https://registry.npmjs.org/@remotion/sdk/-/sdk-4.0.543.tgz",+ "integrity": "sha512-vCqqUC81rs825RN05hjw9Bcax5HfeCRiydLIxGd9Cc3gWjiike7qM5oYv3HUaCX9yByMy2HIm1nIUWCl3aUcbg==",+ "license": "Remotion License",+ "dependencies": {+ "@remotion/player": "4.0.543",+ "@remotion/studio-shared": "4.0.543",+ "remotion": "4.0.543"+ },+ "peerDependencies": {+ "react": ">=16.8.0",+ "react-dom": ">=16.8.0"+ }+ },+ "node_modules/@remotion/streaming": {+ "version": "4.0.543",+ "resolved": "https://registry.npmjs.org/@remotion/streaming/-/streaming-4.0.543.tgz",+ "integrity": "sha512-inKIcnywMc7+cCIRnmymFBPE5FccvLqis+Ja0zWRmHQfMdoj8RjCmPk1WGxkLb7aVEe+nA9L8lYAlYXMbv7Frg==",+ "license": "MIT"+ },+ "node_modules/@remotion/studio": {+ "version": "4.0.543",+ "resolved": "https://registry.npmjs.org/@remotion/studio/-/studio-4.0.543.tgz",+ "integrity": "sha512-hqEqgvihvo75avceijaD18H53srlq7m0Ge0LEA+4u/N71syubC+tOb3N3BWX2oocg/BRJq7IH0VTHWpmYuZwJQ==",+ "license": "MIT",+ "dependencies": {+ "@jridgewell/trace-mapping": "0.3.31",+ "@remotion/captions": "4.0.543",+ "@remotion/codemods": "4.0.543",+ "@remotion/effects": "4.0.543",+ "@remotion/elevenlabs": "4.0.543",+ "@remotion/media": "4.0.543",+ "@remotion/media-utils": "4.0.543",+ "@remotion/openai-whisper": "4.0.543",+ "@remotion/paths": "4.0.543",+ "@remotion/player": "4.0.543",+ "@remotion/renderer": "4.0.543",+ "@remotion/sdk": "4.0.543",+ "@remotion/studio-protocol": "4.0.543",+ "@remotion/studio-shared": "4.0.543",+ "@remotion/timeline-utils": "4.0.543",+ "@remotion/web-renderer": "4.0.543",+ "@remotion/zod-types": "4.0.543",+ "@tanstack/react-virtual": "3.14.9",+ "client-zip": "2.5.1",+ "mediabunny": "1.64.0",+ "memfs": "3.4.3",+ "open": "8.4.2",+ "prismjs": "1.30.0",+ "remotion": "4.0.543",+ "semver": "7.5.3",+ "zod": "4.6.7"+ },+ "peerDependencies": {+ "@remotion/video-matting": "4.0.543",+ "@remotion/whisper-webgpu": "4.0.543",+ "react": ">=16.8.0",+ "react-dom": ">=16.8.0"+ },+ "peerDependenciesMeta": {+ "@remotion/video-matting": {+ "optional": true+ },+ "@remotion/whisper-webgpu": {+ "optional": true+ }+ }+ },+ "node_modules/@remotion/studio-protocol": {+ "version": "4.0.543",+ "resolved": "https://registry.npmjs.org/@remotion/studio-protocol/-/studio-protocol-4.0.543.tgz",+ "integrity": "sha512-MIV4wNox+tUKKCp89f8qLq4k9nB0SgFK9Bn+9LRSZ/Wb18WZT9gvXxHn/Y/6sY2whjgr24okzgQA8wz17++ApA==",+ "license": "Remotion License",+ "dependencies": {+ "zod": "4.6.7"+ }+ },+ "node_modules/@remotion/studio-server": {+ "version": "4.0.543",+ "resolved": "https://registry.npmjs.org/@remotion/studio-server/-/studio-server-4.0.543.tgz",+ "integrity": "sha512-dAWnTniiRPMlJOqvrvWWf90RmY9adivcHsC38wZNcn2StcWHslGgEh6eVqZgK31ZrJu/k6yNUJ8AzsfSjRPrPA==",+ "license": "MIT",+ "dependencies": {+ "@babel/parser": "7.24.1",+ "@babel/types": "7.24.0",+ "@remotion/bundler": "4.0.543",+ "@remotion/codemods": "4.0.543",+ "@remotion/renderer": "4.0.543",+ "@remotion/studio-protocol": "4.0.543",+ "@remotion/studio-shared": "4.0.543",+ "@svgr/core": "8.1.0",+ "@svgr/plugin-jsx": "8.1.0",+ "kiwi-schema": "0.5.0",+ "memfs": "3.4.3",+ "open": "8.4.2",+ "recast": "0.23.21",+ "remotion": "4.0.543",+ "semver": "7.5.3",+ "zod": "4.6.7"+ }+ },+ "node_modules/@remotion/studio-shared": {+ "version": "4.0.543",+ "resolved": "https://registry.npmjs.org/@remotion/studio-shared/-/studio-shared-4.0.543.tgz",+ "integrity": "sha512-SktHr/GQSs5K03R5QFuJRUsIZMNL0cox/6oVczSdm2frkQd/o1R4Pwe4Ikix1/pxuXG23s1OLaXJ5+gI+NxiUg==",+ "license": "MIT",+ "dependencies": {+ "remotion": "4.0.543"+ }+ },+ "node_modules/@remotion/timeline-utils": {+ "version": "4.0.543",+ "resolved": "https://registry.npmjs.org/@remotion/timeline-utils/-/timeline-utils-4.0.543.tgz",+ "integrity": "sha512-M0d72K18chlRRpftmke8Ll/xsFS69dOEOvRPfshYWvJ7Nk8IGmXiCHp+9ZYddkuolseOP5rwy11CxiZsabEZkQ==",+ "license": "MIT",+ "dependencies": {+ "mediabunny": "1.64.0",+ "remotion": "4.0.543"+ }+ },+ "node_modules/@remotion/web-renderer": {+ "version": "4.0.543",+ "resolved": "https://registry.npmjs.org/@remotion/web-renderer/-/web-renderer-4.0.543.tgz",+ "integrity": "sha512-UqJXVw170/Kn2Fcw2WZ0cwuae5M+dgx/NqkCgvV9wP8+VUaaM0UHXIAVa5BH0wC9ybTR3ZkVjIB8T6it4ZokHA==",+ "license": "SEE LICENSE IN LICENSE.md",+ "dependencies": {+ "@mediabunny/aac-encoder": "1.64.0",+ "@mediabunny/flac-encoder": "1.64.0",+ "@mediabunny/mp3-encoder": "1.64.0",+ "@remotion/licensing": "4.0.543",+ "mediabunny": "1.64.0",+ "remotion": "4.0.543"+ },+ "peerDependencies": {+ "react": ">=18.0.0",+ "react-dom": ">=18.0.0"+ }+ },+ "node_modules/@remotion/zod-types": {+ "version": "4.0.543",+ "resolved": "https://registry.npmjs.org/@remotion/zod-types/-/zod-types-4.0.543.tgz",+ "integrity": "sha512-i1WhDdXdH7W8EqeG6lL4Ra/TlHQL9uVF+6wG6k0O4EZ8ZnTzXp+mNuVf2j9nXMVEGaJ+JVc7ya4EeqRPJ03/cw==",+ "license": "MIT",+ "dependencies": {+ "remotion": "4.0.543"+ }+ },+ "node_modules/@rspack/binding": {+ "version": "2.3.0",+ "resolved": "https://registry.npmjs.org/@rspack/binding/-/binding-2.3.0.tgz",+ "integrity": "sha512-rh9S5xvGVs73gdqMDMYXi3SHUfCWIChlL7a8zaYF8+1HLtIgdMyxa100f1ifAKlr8VoyFUv3xrfGLBaoxwjU5g==",+ "license": "MIT",+ "optionalDependencies": {+ "@rspack/binding-darwin-arm64": "2.3.0",+ "@rspack/binding-darwin-x64": "2.3.0",+ "@rspack/binding-linux-arm64-gnu": "2.3.0",+ "@rspack/binding-linux-arm64-musl": "2.3.0",+ "@rspack/binding-linux-ppc64-gnu": "2.3.0",+ "@rspack/binding-linux-riscv64-gnu": "2.3.0",+ "@rspack/binding-linux-riscv64-musl": "2.3.0",+ "@rspack/binding-linux-s390x-gnu": "2.3.0",+ "@rspack/binding-linux-x64-gnu": "2.3.0",+ "@rspack/binding-linux-x64-musl": "2.3.0",+ "@rspack/binding-wasm32-wasi": "2.3.0",+ "@rspack/binding-win32-arm64-msvc": "2.3.0",+ "@rspack/binding-win32-ia32-msvc": "2.3.0",+ "@rspack/binding-win32-x64-msvc": "2.3.0"+ }+ },+ "node_modules/@rspack/binding-darwin-arm64": {+ "version": "2.3.0",+ "resolved": "https://registry.npmjs.org/@rspack/binding-darwin-arm64/-/binding-darwin-arm64-2.3.0.tgz",+ "integrity": "sha512-raUm1V29xRm1fPaS2R2qK4Yw5PGo3xooK6Fz2rt74pjJ+UhEUT4ED/8A9Qyf/YW16aMUl58eS5prtth8+UaJSQ==",+ "cpu": [+ "arm64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "darwin"+ ]+ },+ "node_modules/@rspack/binding-darwin-x64": {+ "version": "2.3.0",+ "resolved": "https://registry.npmjs.org/@rspack/binding-darwin-x64/-/binding-darwin-x64-2.3.0.tgz",+ "integrity": "sha512-Mi7WUDMvYL14607lzOMkFYiu/NmXIeazVKJd/HmCsPu9H8aUpyf71RcbIY0otCfmpvjX2ZFJ5GrXM1VbYCAxKg==",+ "cpu": [+ "x64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "darwin"+ ]+ },+ "node_modules/@rspack/binding-linux-arm64-gnu": {+ "version": "2.3.0",+ "resolved": "https://registry.npmjs.org/@rspack/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-2.3.0.tgz",+ "integrity": "sha512-4qHSxhLkjz6Y2r8nW72IyW0sVC1TglNz5198YFEvokQ/O356mwVk3bCS/yz3IdwPu6v4sXylLDB8cEudRoeKwg==",+ "cpu": [+ "arm64"+ ],+ "libc": [+ "glibc"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ]+ },+ "node_modules/@rspack/binding-linux-arm64-musl": {+ "version": "2.3.0",+ "resolved": "https://registry.npmjs.org/@rspack/binding-linux-arm64-musl/-/binding-linux-arm64-musl-2.3.0.tgz",+ "integrity": "sha512-YKbmMCK7RS9YOUKYx2j6hretwv0mPHOQnD2UStDITMAnhsidn63teEyUt5404U53u+tEvyK8toQqqHFbtA/aZQ==",+ "cpu": [+ "arm64"+ ],+ "libc": [+ "musl"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ]+ },+ "node_modules/@rspack/binding-linux-ppc64-gnu": {+ "version": "2.3.0",+ "resolved": "https://registry.npmjs.org/@rspack/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-2.3.0.tgz",+ "integrity": "sha512-8hI1CiQTQiBxfFevf1jsFoP2PL4jv9Vc4oUG9Q4ryF+xBwqmKSOLgb0MTgiHz0lQ0jg4hbVcb5fR3ZgK0f3lDg==",+ "cpu": [+ "ppc64"+ ],+ "libc": [+ "glibc"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ]+ },+ "node_modules/@rspack/binding-linux-riscv64-gnu": {+ "version": "2.3.0",+ "resolved": "https://registry.npmjs.org/@rspack/binding-linux-riscv64-gnu/-/binding-linux-riscv64-gnu-2.3.0.tgz",+ "integrity": "sha512-kzXFRjvfQkFd14/zyVG+xNnEurVZPQA1aKL/OcKeIW4niqU13RdIGMbGQ2M8SBfPBbL92ze//CZIiBlz8kZIbg==",+ "cpu": [+ "riscv64"+ ],+ "libc": [+ "glibc"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ]+ },+ "node_modules/@rspack/binding-linux-riscv64-musl": {+ "version": "2.3.0",+ "resolved": "https://registry.npmjs.org/@rspack/binding-linux-riscv64-musl/-/binding-linux-riscv64-musl-2.3.0.tgz",+ "integrity": "sha512-ATJC0MwQmkC+wFyoUtpklemROUaW1IRpf7M6depLaiZXuVN8bx0IMFr/iCL1YBLf5+38NBAXsGwO3/bqYxmdQQ==",+ "cpu": [+ "riscv64"+ ],+ "libc": [+ "musl"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ]+ },+ "node_modules/@rspack/binding-linux-s390x-gnu": {+ "version": "2.3.0",+ "resolved": "https://registry.npmjs.org/@rspack/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-2.3.0.tgz",+ "integrity": "sha512-MWGDa/JKwXNwJiZM/A7Iy4Js7IrEmWExjPefGDFhWmozGJ5BsKdnvD4q3Kb/YfQ+X++LJR5q1o9MkACpdOu/Bw==",+ "cpu": [+ "s390x"+ ],+ "libc": [+ "glibc"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ]+ },+ "node_modules/@rspack/binding-linux-x64-gnu": {+ "version": "2.3.0",+ "resolved": "https://registry.npmjs.org/@rspack/binding-linux-x64-gnu/-/binding-linux-x64-gnu-2.3.0.tgz",+ "integrity": "sha512-XxyrjQXvIjxWIct9ceKUBZdeBbNfZ6OkyAKU62xKuyLCyKiwg7M9LhXvKKfvVyFkK7n10a6t/KeIV8+k+kREoQ==",+ "cpu": [+ "x64"+ ],+ "libc": [+ "glibc"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ]+ },+ "node_modules/@rspack/binding-linux-x64-musl": {+ "version": "2.3.0",+ "resolved": "https://registry.npmjs.org/@rspack/binding-linux-x64-musl/-/binding-linux-x64-musl-2.3.0.tgz",+ "integrity": "sha512-XFY3Ayqpb/j9J9npTtOOa8woswCBDZxWfVUkirxxkvHTEk9eAP3/ABd4wxwRuGQuBFf91Emew/g0K/KpFbyH3Q==",+ "cpu": [+ "x64"+ ],+ "libc": [+ "musl"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ]+ },+ "node_modules/@rspack/binding-wasm32-wasi": {+ "version": "2.3.0",+ "resolved": "https://registry.npmjs.org/@rspack/binding-wasm32-wasi/-/binding-wasm32-wasi-2.3.0.tgz",+ "integrity": "sha512-d24u2ShgaRE2DipdiuVvZMZKjSse1LpLeHqs5wqm1q8S9MW6sjE2GwlIErXSKuNymSqf0YlaN/11jjxLb2x2qA==",+ "cpu": [+ "wasm32"+ ],+ "license": "MIT",+ "optional": true,+ "dependencies": {+ "@emnapi/core": "1.11.3",+ "@emnapi/runtime": "1.11.3",+ "@napi-rs/wasm-runtime": "1.1.6"+ }+ },+ "node_modules/@rspack/binding-win32-arm64-msvc": {+ "version": "2.3.0",+ "resolved": "https://registry.npmjs.org/@rspack/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-2.3.0.tgz",+ "integrity": "sha512-foalqSBgpsAPCOLd4zxALB7s06uu1YEa7p74rknv2OciF/kd9bGN4tPIpkTTgYPd2Q6KFpae/Vq8zxPSQFDHRA==",+ "cpu": [+ "arm64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "win32"+ ]+ },+ "node_modules/@rspack/binding-win32-ia32-msvc": {+ "version": "2.3.0",+ "resolved": "https://registry.npmjs.org/@rspack/binding-win32-ia32-msvc/-/binding-win32-ia32-msvc-2.3.0.tgz",+ "integrity": "sha512-RVoGgdW0GsWa0fsrqRYQ4JkCLViS/RGqd8gzqgMDmtdyrhHV/bvGiTPYIRYMJPWk9zBhaxA6RAAip3fjKdga8g==",+ "cpu": [+ "ia32"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "win32"+ ]+ },+ "node_modules/@rspack/binding-win32-x64-msvc": {+ "version": "2.3.0",+ "resolved": "https://registry.npmjs.org/@rspack/binding-win32-x64-msvc/-/binding-win32-x64-msvc-2.3.0.tgz",+ "integrity": "sha512-gZyb4zPz8WfGbPLMscY7TX8Y1SDBvQdhHF/Gq1nzt3JEHqYFeZJrQHl0C8atH+PrDK5l7d+lY/qRwfuE+qeJ5A==",+ "cpu": [+ "x64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "win32"+ ]+ },+ "node_modules/@rspack/core": {+ "version": "2.3.0",+ "resolved": "https://registry.npmjs.org/@rspack/core/-/core-2.3.0.tgz",+ "integrity": "sha512-1zylQSMl3xo1f57ZqJMHAoVddRv1BSvpQQVIgWjP51AGhLyeHTAfEf0mphb0wb0bOUf5EujpvvO592X9GMf2qQ==",+ "license": "MIT",+ "dependencies": {+ "@rspack/binding": "2.3.0"+ },+ "engines": {+ "node": "^20.19.0 || >=22.12.0"+ },+ "peerDependencies": {+ "@module-federation/runtime-tools": "^0.24.1 || ^2.0.0",+ "@swc/helpers": "^0.5.23"+ },+ "peerDependenciesMeta": {+ "@module-federation/runtime-tools": {+ "optional": true+ },+ "@swc/helpers": {+ "optional": true+ }+ }+ },+ "node_modules/@rspack/plugin-react-refresh": {+ "version": "2.0.2",+ "resolved": "https://registry.npmjs.org/@rspack/plugin-react-refresh/-/plugin-react-refresh-2.0.2.tgz",+ "integrity": "sha512-dGNZiCxQxgAUI9sah7gd8u+O7OJZRCmqtEJNDOd8xW5RqcieC86F7p5qcShyw6onH5pKf57evpr2VjGbaFGkZg==",+ "license": "MIT",+ "peerDependencies": {+ "@rspack/core": "^2.0.0",+ "react-refresh": ">=0.10.0 <1.0.0"+ },+ "peerDependenciesMeta": {+ "@rspack/core": {+ "optional": true+ }+ }+ },+ "node_modules/@svgr/babel-plugin-add-jsx-attribute": {+ "version": "8.0.0",+ "resolved": "https://registry.npmjs.org/@svgr/babel-plugin-add-jsx-attribute/-/babel-plugin-add-jsx-attribute-8.0.0.tgz",+ "integrity": "sha512-b9MIk7yhdS1pMCZM8VeNfUlSKVRhsHZNMl5O9SfaX0l0t5wjdgu4IDzGB8bpnGBBOjGST3rRFVsaaEtI4W6f7g==",+ "license": "MIT",+ "engines": {+ "node": ">=14"+ },+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/gregberge"+ },+ "peerDependencies": {+ "@babel/core": "^7.0.0-0"+ }+ },+ "node_modules/@svgr/babel-plugin-remove-jsx-attribute": {+ "version": "8.0.0",+ "resolved": "https://registry.npmjs.org/@svgr/babel-plugin-remove-jsx-attribute/-/babel-plugin-remove-jsx-attribute-8.0.0.tgz",+ "integrity": "sha512-BcCkm/STipKvbCl6b7QFrMh/vx00vIP63k2eM66MfHJzPr6O2U0jYEViXkHJWqXqQYjdeA9cuCl5KWmlwjDvbA==",+ "license": "MIT",+ "engines": {+ "node": ">=14"+ },+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/gregberge"+ },+ "peerDependencies": {+ "@babel/core": "^7.0.0-0"+ }+ },+ "node_modules/@svgr/babel-plugin-remove-jsx-empty-expression": {+ "version": "8.0.0",+ "resolved": "https://registry.npmjs.org/@svgr/babel-plugin-remove-jsx-empty-expression/-/babel-plugin-remove-jsx-empty-expression-8.0.0.tgz",+ "integrity": "sha512-5BcGCBfBxB5+XSDSWnhTThfI9jcO5f0Ai2V24gZpG+wXF14BzwxxdDb4g6trdOux0rhibGs385BeFMSmxtS3uA==",+ "license": "MIT",+ "engines": {+ "node": ">=14"+ },+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/gregberge"+ },+ "peerDependencies": {+ "@babel/core": "^7.0.0-0"+ }+ },+ "node_modules/@svgr/babel-plugin-replace-jsx-attribute-value": {+ "version": "8.0.0",+ "resolved": "https://registry.npmjs.org/@svgr/babel-plugin-replace-jsx-attribute-value/-/babel-plugin-replace-jsx-attribute-value-8.0.0.tgz",+ "integrity": "sha512-KVQ+PtIjb1BuYT3ht8M5KbzWBhdAjjUPdlMtpuw/VjT8coTrItWX6Qafl9+ji831JaJcu6PJNKCV0bp01lBNzQ==",+ "license": "MIT",+ "engines": {+ "node": ">=14"+ },+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/gregberge"+ },+ "peerDependencies": {+ "@babel/core": "^7.0.0-0"+ }+ },+ "node_modules/@svgr/babel-plugin-svg-dynamic-title": {+ "version": "8.0.0",+ "resolved": "https://registry.npmjs.org/@svgr/babel-plugin-svg-dynamic-title/-/babel-plugin-svg-dynamic-title-8.0.0.tgz",+ "integrity": "sha512-omNiKqwjNmOQJ2v6ge4SErBbkooV2aAWwaPFs2vUY7p7GhVkzRkJ00kILXQvRhA6miHnNpXv7MRnnSjdRjK8og==",+ "license": "MIT",+ "engines": {+ "node": ">=14"+ },+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/gregberge"+ },+ "peerDependencies": {+ "@babel/core": "^7.0.0-0"+ }+ },+ "node_modules/@svgr/babel-plugin-svg-em-dimensions": {+ "version": "8.0.0",+ "resolved": "https://registry.npmjs.org/@svgr/babel-plugin-svg-em-dimensions/-/babel-plugin-svg-em-dimensions-8.0.0.tgz",+ "integrity": "sha512-mURHYnu6Iw3UBTbhGwE/vsngtCIbHE43xCRK7kCw4t01xyGqb2Pd+WXekRRoFOBIY29ZoOhUCTEweDMdrjfi9g==",+ "license": "MIT",+ "engines": {+ "node": ">=14"+ },+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/gregberge"+ },+ "peerDependencies": {+ "@babel/core": "^7.0.0-0"+ }+ },+ "node_modules/@svgr/babel-plugin-transform-react-native-svg": {+ "version": "8.1.0",+ "resolved": "https://registry.npmjs.org/@svgr/babel-plugin-transform-react-native-svg/-/babel-plugin-transform-react-native-svg-8.1.0.tgz",+ "integrity": "sha512-Tx8T58CHo+7nwJ+EhUwx3LfdNSG9R2OKfaIXXs5soiy5HtgoAEkDay9LIimLOcG8dJQH1wPZp/cnAv6S9CrR1Q==",+ "license": "MIT",+ "engines": {+ "node": ">=14"+ },+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/gregberge"+ },+ "peerDependencies": {+ "@babel/core": "^7.0.0-0"+ }+ },+ "node_modules/@svgr/babel-plugin-transform-svg-component": {+ "version": "8.0.0",+ "resolved": "https://registry.npmjs.org/@svgr/babel-plugin-transform-svg-component/-/babel-plugin-transform-svg-component-8.0.0.tgz",+ "integrity": "sha512-DFx8xa3cZXTdb/k3kfPeaixecQLgKh5NVBMwD0AQxOzcZawK4oo1Jh9LbrcACUivsCA7TLG8eeWgrDXjTMhRmw==",+ "license": "MIT",+ "engines": {+ "node": ">=12"+ },+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/gregberge"+ },+ "peerDependencies": {+ "@babel/core": "^7.0.0-0"+ }+ },+ "node_modules/@svgr/babel-preset": {+ "version": "8.1.0",+ "resolved": "https://registry.npmjs.org/@svgr/babel-preset/-/babel-preset-8.1.0.tgz",+ "integrity": "sha512-7EYDbHE7MxHpv4sxvnVPngw5fuR6pw79SkcrILHJ/iMpuKySNCl5W1qcwPEpU+LgyRXOaAFgH0KhwD18wwg6ug==",+ "license": "MIT",+ "dependencies": {+ "@svgr/babel-plugin-add-jsx-attribute": "8.0.0",+ "@svgr/babel-plugin-remove-jsx-attribute": "8.0.0",+ "@svgr/babel-plugin-remove-jsx-empty-expression": "8.0.0",+ "@svgr/babel-plugin-replace-jsx-attribute-value": "8.0.0",+ "@svgr/babel-plugin-svg-dynamic-title": "8.0.0",+ "@svgr/babel-plugin-svg-em-dimensions": "8.0.0",+ "@svgr/babel-plugin-transform-react-native-svg": "8.1.0",+ "@svgr/babel-plugin-transform-svg-component": "8.0.0"+ },+ "engines": {+ "node": ">=14"+ },+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/gregberge"+ },+ "peerDependencies": {+ "@babel/core": "^7.0.0-0"+ }+ },+ "node_modules/@svgr/core": {+ "version": "8.1.0",+ "resolved": "https://registry.npmjs.org/@svgr/core/-/core-8.1.0.tgz",+ "integrity": "sha512-8QqtOQT5ACVlmsvKOJNEaWmRPmcojMOzCz4Hs2BGG/toAp/K38LcsMRyLp349glq5AzJbCEeimEoxaX6v/fLrA==",+ "license": "MIT",+ "dependencies": {+ "@babel/core": "^7.21.3",+ "@svgr/babel-preset": "8.1.0",+ "camelcase": "^6.2.0",+ "cosmiconfig": "^8.1.3",+ "snake-case": "^3.0.4"+ },+ "engines": {+ "node": ">=14"+ },+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/gregberge"+ }+ },+ "node_modules/@svgr/hast-util-to-babel-ast": {+ "version": "8.0.0",+ "resolved": "https://registry.npmjs.org/@svgr/hast-util-to-babel-ast/-/hast-util-to-babel-ast-8.0.0.tgz",+ "integrity": "sha512-EbDKwO9GpfWP4jN9sGdYwPBU0kdomaPIL2Eu4YwmgP+sJeXT+L7bMwJUBnhzfH8Q2qMBqZ4fJwpCyYsAN3mt2Q==",+ "license": "MIT",+ "dependencies": {+ "@babel/types": "^7.21.3",+ "entities": "^4.4.0"+ },+ "engines": {+ "node": ">=14"+ },+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/gregberge"+ }+ },+ "node_modules/@svgr/plugin-jsx": {+ "version": "8.1.0",+ "resolved": "https://registry.npmjs.org/@svgr/plugin-jsx/-/plugin-jsx-8.1.0.tgz",+ "integrity": "sha512-0xiIyBsLlr8quN+WyuxooNW9RJ0Dpr8uOnH/xrCVO8GLUcwHISwj1AG0k+LFzteTkAA0GbX0kj9q6Dk70PTiPA==",+ "license": "MIT",+ "dependencies": {+ "@babel/core": "^7.21.3",+ "@svgr/babel-preset": "8.1.0",+ "@svgr/hast-util-to-babel-ast": "8.0.0",+ "svg-parser": "^2.0.4"+ },+ "engines": {+ "node": ">=14"+ },+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/gregberge"+ },+ "peerDependencies": {+ "@svgr/core": "*"+ }+ },+ "node_modules/@swc/helpers": {+ "version": "0.5.24",+ "resolved": "https://registry.npmjs.org/@swc/helpers/-/helpers-0.5.24.tgz",+ "integrity": "sha512-6tcXo4kA8HgGO7AVmawB57RYi/piBPYVHVcO6dXjX+SZw8GoHmi262sp4v2Ha2kNP9Cx84qei27yT+fjS1lxgg==",+ "license": "Apache-2.0"+ },+ "node_modules/@tanstack/react-virtual": {+ "version": "3.14.9",+ "resolved": "https://registry.npmjs.org/@tanstack/react-virtual/-/react-virtual-3.14.9.tgz",+ "integrity": "sha512-qZyr0FZDP8rDC4WBhsryIZmAd9bveJvFGUJJtskWaew6/0dTRS6wZxnR6VQ5bY2KwL3LjerrHqQLk3a0GKcPXQ==",+ "license": "MIT",+ "dependencies": {+ "@tanstack/virtual-core": "3.17.7"+ },+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/tannerlinsley"+ },+ "peerDependencies": {+ "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0",+ "react-dom": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0"+ }+ },+ "node_modules/@tanstack/virtual-core": {+ "version": "3.17.7",+ "resolved": "https://registry.npmjs.org/@tanstack/virtual-core/-/virtual-core-3.17.7.tgz",+ "integrity": "sha512-bp+v10y65sp2H7WpWfIMyxTNfl8ZVfxFTLRjPIFRryi6FV/J33z4IS53WO4pTk36KlvJ4iLiQz+oaydDC1xbcA==",+ "license": "MIT",+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/tannerlinsley"+ }+ },+ "node_modules/@tybys/wasm-util": {+ "version": "0.10.4",+ "resolved": "https://registry.npmjs.org/@tybys/wasm-util/-/wasm-util-0.10.4.tgz",+ "integrity": "sha512-W3c4gRigFS0T/Ma4qIYF3GDAc5AQdHb1yL5znJT1Zv1YaD9Kitx656wBjvr19qbiosmZT8lWDM5BEMynUqX65A==",+ "license": "MIT",+ "optional": true,+ "dependencies": {+ "tslib": "^2.4.0"+ }+ },+ "node_modules/@types/dom-mediacapture-transform": {+ "version": "0.1.12",+ "resolved": "https://registry.npmjs.org/@types/dom-mediacapture-transform/-/dom-mediacapture-transform-0.1.12.tgz",+ "integrity": "sha512-d7/QsLRwF864A5mgIM/YrfiglHoYn7zgCcAoJgW404r+2DwnNr7EBbLnCWpmOMgH8y0te73L1AV6H1bmauaWFw==",+ "license": "MIT",+ "dependencies": {+ "@types/dom-webcodecs": "*"+ }+ },+ "node_modules/@types/dom-webcodecs": {+ "version": "0.1.13",+ "resolved": "https://registry.npmjs.org/@types/dom-webcodecs/-/dom-webcodecs-0.1.13.tgz",+ "integrity": "sha512-O5hkiFIcjjszPIYyUSyvScyvrBoV3NOEEZx/pMlsu44TKzWNkLVBBxnxJz42in5n3QIolYOcBYFCPZZ0h8SkwQ==",+ "license": "MIT"+ },+ "node_modules/@types/eslint": {+ "version": "9.6.1",+ "resolved": "https://registry.npmjs.org/@types/eslint/-/eslint-9.6.1.tgz",+ "integrity": "sha512-FXx2pKgId/WyYo2jXw63kk7/+TY7u7AziEJxJAnSFzHlqTAS3Ync6SvgYAN/k4/PQpnnVuzoMuVnByKK2qp0ag==",+ "license": "MIT",+ "dependencies": {+ "@types/estree": "*",+ "@types/json-schema": "*"+ }+ },+ "node_modules/@types/eslint-scope": {+ "version": "3.7.7",+ "resolved": "https://registry.npmjs.org/@types/eslint-scope/-/eslint-scope-3.7.7.tgz",+ "integrity": "sha512-MzMFlSLBqNF2gcHWO0G1vP/YQyfvrxZ0bF+u7mzUdZ1/xK4A4sru+nraZz5i3iEIk1l1uyicaDVTB4QbbEkAYg==",+ "license": "MIT",+ "dependencies": {+ "@types/eslint": "*",+ "@types/estree": "*"+ }+ },+ "node_modules/@types/estree": {+ "version": "1.0.10",+ "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.10.tgz",+ "integrity": "sha512-lTyOMnOcmRBzdCv6/4zUZCrEhV0xrqQiUZBZtVcbmLHBXKLnN8q89v/wKRF/Q0HbwVsqbIG3o5HDoFl9sduM+g==",+ "license": "MIT"+ },+ "node_modules/@types/json-schema": {+ "version": "7.0.15",+ "resolved": "https://registry.npmjs.org/@types/json-schema/-/json-schema-7.0.15.tgz",+ "integrity": "sha512-5+fP8P8MFNC+AyZCDxrB2pkZFPGzqQWUzpSeuuVLvm8VMcorNYavBqoFcxK8bQz4Qsbn4oUEEem4wDLfcysGHA==",+ "license": "MIT"+ },+ "node_modules/@types/node": {+ "version": "26.6.6",+ "resolved": "https://registry.npmjs.org/@types/node/-/node-26.6.6.tgz",+ "integrity": "sha512-MzQj+8Kx3XI40OmUAE6Qoh58ZMNstNNMwn2nfd3qWsfe7nDNSqJNzes4njhz6AHwrSHOffSLwXU6yb474Q4aog==",+ "license": "MIT",+ "dependencies": {+ "undici-types": "~8.9.0"+ }+ },+ "node_modules/@webassemblyjs/ast": {+ "version": "1.14.1",+ "resolved": "https://registry.npmjs.org/@webassemblyjs/ast/-/ast-1.14.1.tgz",+ "integrity": "sha512-nuBEDgQfm1ccRp/8bCQrx1frohyufl4JlbMMZ4P1wpeOfDhF6FQkxZJ1b/e+PLwr6X1Nhw6OLme5usuBWYBvuQ==",+ "license": "MIT",+ "dependencies": {+ "@webassemblyjs/helper-numbers": "1.13.2",+ "@webassemblyjs/helper-wasm-bytecode": "1.13.2"+ }+ },+ "node_modules/@webassemblyjs/floating-point-hex-parser": {+ "version": "1.13.2",+ "resolved": "https://registry.npmjs.org/@webassemblyjs/floating-point-hex-parser/-/floating-point-hex-parser-1.13.2.tgz",+ "integrity": "sha512-6oXyTOzbKxGH4steLbLNOu71Oj+C8Lg34n6CqRvqfS2O71BxY6ByfMDRhBytzknj9yGUPVJ1qIKhRlAwO1AovA==",+ "license": "MIT"+ },+ "node_modules/@webassemblyjs/helper-api-error": {+ "version": "1.13.2",+ "resolved": "https://registry.npmjs.org/@webassemblyjs/helper-api-error/-/helper-api-error-1.13.2.tgz",+ "integrity": "sha512-U56GMYxy4ZQCbDZd6JuvvNV/WFildOjsaWD3Tzzvmw/mas3cXzRJPMjP83JqEsgSbyrmaGjBfDtV7KDXV9UzFQ==",+ "license": "MIT"+ },+ "node_modules/@webassemblyjs/helper-buffer": {+ "version": "1.14.1",+ "resolved": "https://registry.npmjs.org/@webassemblyjs/helper-buffer/-/helper-buffer-1.14.1.tgz",+ "integrity": "sha512-jyH7wtcHiKssDtFPRB+iQdxlDf96m0E39yb0k5uJVhFGleZFoNw1c4aeIcVUPPbXUVJ94wwnMOAqUHyzoEPVMA==",+ "license": "MIT"+ },+ "node_modules/@webassemblyjs/helper-numbers": {+ "version": "1.13.2",+ "resolved": "https://registry.npmjs.org/@webassemblyjs/helper-numbers/-/helper-numbers-1.13.2.tgz",+ "integrity": "sha512-FE8aCmS5Q6eQYcV3gI35O4J789wlQA+7JrqTTpJqn5emA4U2hvwJmvFRC0HODS+3Ye6WioDklgd6scJ3+PLnEA==",+ "license": "MIT",+ "dependencies": {+ "@webassemblyjs/floating-point-hex-parser": "1.13.2",+ "@webassemblyjs/helper-api-error": "1.13.2",+ "@xtuc/long": "4.2.2"+ }+ },+ "node_modules/@webassemblyjs/helper-wasm-bytecode": {+ "version": "1.13.2",+ "resolved": "https://registry.npmjs.org/@webassemblyjs/helper-wasm-bytecode/-/helper-wasm-bytecode-1.13.2.tgz",+ "integrity": "sha512-3QbLKy93F0EAIXLh0ogEVR6rOubA9AoZ+WRYhNbFyuB70j3dRdwH9g+qXhLAO0kiYGlg3TxDV+I4rQTr/YNXkA==",+ "license": "MIT"+ },+ "node_modules/@webassemblyjs/helper-wasm-section": {+ "version": "1.14.1",+ "resolved": "https://registry.npmjs.org/@webassemblyjs/helper-wasm-section/-/helper-wasm-section-1.14.1.tgz",+ "integrity": "sha512-ds5mXEqTJ6oxRoqjhWDU83OgzAYjwsCV8Lo/N+oRsNDmx/ZDpqalmrtgOMkHwxsG0iI//3BwWAErYRHtgn0dZw==",+ "license": "MIT",+ "dependencies": {+ "@webassemblyjs/ast": "1.14.1",+ "@webassemblyjs/helper-buffer": "1.14.1",+ "@webassemblyjs/helper-wasm-bytecode": "1.13.2",+ "@webassemblyjs/wasm-gen": "1.14.1"+ }+ },+ "node_modules/@webassemblyjs/ieee754": {+ "version": "1.13.2",+ "resolved": "https://registry.npmjs.org/@webassemblyjs/ieee754/-/ieee754-1.13.2.tgz",+ "integrity": "sha512-4LtOzh58S/5lX4ITKxnAK2USuNEvpdVV9AlgGQb8rJDHaLeHciwG4zlGr0j/SNWlr7x3vO1lDEsuePvtcDNCkw==",+ "license": "MIT",+ "dependencies": {+ "@xtuc/ieee754": "^1.2.0"+ }+ },+ "node_modules/@webassemblyjs/leb128": {+ "version": "1.13.2",+ "resolved": "https://registry.npmjs.org/@webassemblyjs/leb128/-/leb128-1.13.2.tgz",+ "integrity": "sha512-Lde1oNoIdzVzdkNEAWZ1dZ5orIbff80YPdHx20mrHwHrVNNTjNr8E3xz9BdpcGqRQbAEa+fkrCb+fRFTl/6sQw==",+ "license": "Apache-2.0",+ "dependencies": {+ "@xtuc/long": "4.2.2"+ }+ },+ "node_modules/@webassemblyjs/utf8": {+ "version": "1.13.2",+ "resolved": "https://registry.npmjs.org/@webassemblyjs/utf8/-/utf8-1.13.2.tgz",+ "integrity": "sha512-3NQWGjKTASY1xV5m7Hr0iPeXD9+RDobLll3T9d2AO+g3my8xy5peVyjSag4I50mR1bBSN/Ct12lo+R9tJk0NZQ==",+ "license": "MIT"+ },+ "node_modules/@webassemblyjs/wasm-edit": {+ "version": "1.14.1",+ "resolved": "https://registry.npmjs.org/@webassemblyjs/wasm-edit/-/wasm-edit-1.14.1.tgz",+ "integrity": "sha512-RNJUIQH/J8iA/1NzlE4N7KtyZNHi3w7at7hDjvRNm5rcUXa00z1vRz3glZoULfJ5mpvYhLybmVcwcjGrC1pRrQ==",+ "license": "MIT",+ "dependencies": {+ "@webassemblyjs/ast": "1.14.1",+ "@webassemblyjs/helper-buffer": "1.14.1",+ "@webassemblyjs/helper-wasm-bytecode": "1.13.2",+ "@webassemblyjs/helper-wasm-section": "1.14.1",+ "@webassemblyjs/wasm-gen": "1.14.1",+ "@webassemblyjs/wasm-opt": "1.14.1",+ "@webassemblyjs/wasm-parser": "1.14.1",+ "@webassemblyjs/wast-printer": "1.14.1"+ }+ },+ "node_modules/@webassemblyjs/wasm-gen": {+ "version": "1.14.1",+ "resolved": "https://registry.npmjs.org/@webassemblyjs/wasm-gen/-/wasm-gen-1.14.1.tgz",+ "integrity": "sha512-AmomSIjP8ZbfGQhumkNvgC33AY7qtMCXnN6bL2u2Js4gVCg8fp735aEiMSBbDR7UQIj90n4wKAFUSEd0QN2Ukg==",+ "license": "MIT",+ "dependencies": {+ "@webassemblyjs/ast": "1.14.1",+ "@webassemblyjs/helper-wasm-bytecode": "1.13.2",+ "@webassemblyjs/ieee754": "1.13.2",+ "@webassemblyjs/leb128": "1.13.2",+ "@webassemblyjs/utf8": "1.13.2"+ }+ },+ "node_modules/@webassemblyjs/wasm-opt": {+ "version": "1.14.1",+ "resolved": "https://registry.npmjs.org/@webassemblyjs/wasm-opt/-/wasm-opt-1.14.1.tgz",+ "integrity": "sha512-PTcKLUNvBqnY2U6E5bdOQcSM+oVP/PmrDY9NzowJjislEjwP/C4an2303MCVS2Mg9d3AJpIGdUFIQQWbPds0Sw==",+ "license": "MIT",+ "dependencies": {+ "@webassemblyjs/ast": "1.14.1",+ "@webassemblyjs/helper-buffer": "1.14.1",+ "@webassemblyjs/wasm-gen": "1.14.1",+ "@webassemblyjs/wasm-parser": "1.14.1"+ }+ },+ "node_modules/@webassemblyjs/wasm-parser": {+ "version": "1.14.1",+ "resolved": "https://registry.npmjs.org/@webassemblyjs/wasm-parser/-/wasm-parser-1.14.1.tgz",+ "integrity": "sha512-JLBl+KZ0R5qB7mCnud/yyX08jWFw5MsoalJ1pQ4EdFlgj9VdXKGuENGsiCIjegI1W7p91rUlcB/LB5yRJKNTcQ==",+ "license": "MIT",+ "dependencies": {+ "@webassemblyjs/ast": "1.14.1",+ "@webassemblyjs/helper-api-error": "1.13.2",+ "@webassemblyjs/helper-wasm-bytecode": "1.13.2",+ "@webassemblyjs/ieee754": "1.13.2",+ "@webassemblyjs/leb128": "1.13.2",+ "@webassemblyjs/utf8": "1.13.2"+ }+ },+ "node_modules/@webassemblyjs/wast-printer": {+ "version": "1.14.1",+ "resolved": "https://registry.npmjs.org/@webassemblyjs/wast-printer/-/wast-printer-1.14.1.tgz",+ "integrity": "sha512-kPSSXE6De1XOR820C90RIo2ogvZG+c3KiHzqUoO/F34Y2shGzesfqv7o57xrxovZJH/MetF5UjroJ/R/3isoiw==",+ "license": "MIT",+ "dependencies": {+ "@webassemblyjs/ast": "1.14.1",+ "@xtuc/long": "4.2.2"+ }+ },+ "node_modules/@xtuc/ieee754": {+ "version": "1.2.0",+ "resolved": "https://registry.npmjs.org/@xtuc/ieee754/-/ieee754-1.2.0.tgz",+ "integrity": "sha512-DX8nKgqcGwsc0eJSqYt5lwP4DH5FlHnmuWWBRy7X0NcaGR0ZtuyeESgMwTYVEtxmsNGY+qit4QYT/MIYTOTPeA==",+ "license": "BSD-3-Clause"+ },+ "node_modules/@xtuc/long": {+ "version": "4.2.2",+ "resolved": "https://registry.npmjs.org/@xtuc/long/-/long-4.2.2.tgz",+ "integrity": "sha512-NuHqBY1PB/D8xU6s/thBgOAiAP7HOYDQ32+BFZILJ8ivkUkAHQnWfn6WhL79Owj1qmUnoN/YPhktdIoucipkAQ==",+ "license": "Apache-2.0"+ },+ "node_modules/acorn": {+ "version": "8.19.0",+ "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.19.0.tgz",+ "integrity": "sha512-oJlA3XiRm7Cyk6qFD2Jn8ak9B7jSy0qy00ADO3+8dpT0LSjFihQYv4C02LFCSYJV3Q37xYwwRy5m+IpIiUzqWw==",+ "license": "MIT",+ "bin": {+ "acorn": "bin/acorn"+ },+ "engines": {+ "node": ">=0.4.0"+ }+ },+ "node_modules/acorn-import-phases": {+ "version": "1.0.4",+ "resolved": "https://registry.npmjs.org/acorn-import-phases/-/acorn-import-phases-1.0.4.tgz",+ "integrity": "sha512-wKmbr/DDiIXzEOiWrTTUcDm24kQ2vGfZQvM2fwg2vXqR5uW6aapr7ObPtj1th32b9u90/Pf4AItvdTh42fBmVQ==",+ "license": "MIT",+ "engines": {+ "node": ">=10.13.0"+ },+ "peerDependencies": {+ "acorn": "^8.14.0"+ }+ },+ "node_modules/adm-zip": {+ "version": "0.6.1",+ "resolved": "https://registry.npmjs.org/adm-zip/-/adm-zip-0.6.1.tgz",+ "integrity": "sha512-Xwrja8nx9e5o2N1my4DsKCeKpdrnACyr1wtbPxBDgGzKzKyE9kRtBFA8mWldI+RVlD7CBZNWY/wQ2+ydwOR6kQ==",+ "license": "MIT",+ "engines": {+ "node": ">=14.0"+ }+ },+ "node_modules/ajv": {+ "version": "8.20.0",+ "resolved": "https://registry.npmjs.org/ajv/-/ajv-8.20.0.tgz",+ "integrity": "sha512-Thbli+OlOj+iMPYFBVBfJ3OmCAnaSyNn4M1vz9T6Gka5Jt9ba/HIR56joy65tY6kx/FCF5VXNB819Y7/GUrBGA==",+ "license": "MIT",+ "dependencies": {+ "fast-deep-equal": "^3.1.3",+ "fast-uri": "^3.0.1",+ "json-schema-traverse": "^1.0.0",+ "require-from-string": "^2.0.2"+ },+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/epoberezkin"+ }+ },+ "node_modules/ajv-formats": {+ "version": "3.0.1",+ "resolved": "https://registry.npmjs.org/ajv-formats/-/ajv-formats-3.0.1.tgz",+ "integrity": "sha512-8iUql50EUR+uUcdRQ3HDqa6EVyo3docL8g5WJ3FNcWmu62IbkGUue/pEyLBW8VGKKucTPgqeks4fIU1DA4yowQ==",+ "license": "MIT",+ "dependencies": {+ "ajv": "^8.0.0"+ },+ "peerDependencies": {+ "ajv": "^8.0.0"+ },+ "peerDependenciesMeta": {+ "ajv": {+ "optional": true+ }+ }+ },+ "node_modules/ajv-keywords": {+ "version": "5.1.0",+ "resolved": "https://registry.npmjs.org/ajv-keywords/-/ajv-keywords-5.1.0.tgz",+ "integrity": "sha512-YCS/JNFAUyr5vAuhk1DWm1CBxRHW9LbJ2ozWeemrIqpbsqKjHVxYPyi5GC0rjZIT5JxJ3virVTS8wk4i/Z+krw==",+ "license": "MIT",+ "dependencies": {+ "fast-deep-equal": "^3.1.3"+ },+ "peerDependencies": {+ "ajv": "^8.8.2"+ }+ },+ "node_modules/ansi-regex": {+ "version": "6.6.0",+ "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-6.6.0.tgz",+ "integrity": "sha512-XZ5apbzreCbXSKwPjJstu8R0zOi247w3XYwWxtwBXgpZrCyc1Ka7p9/xY0A9/diMewmHbEKz+FIraWaEWjlN5g==",+ "license": "MIT",+ "engines": {+ "node": ">=12"+ },+ "funding": {+ "url": "https://github.com/chalk/ansi-regex?sponsor=1"+ }+ },+ "node_modules/ansi-styles": {+ "version": "6.2.3",+ "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-6.2.3.tgz",+ "integrity": "sha512-4Dj6M28JB+oAH8kFkTLUo+a2jwOFkuqb3yucU0CANcRRUbxS0cP0nZYCGjcc3BNXwRIsUVmDGgzawme7zvJHvg==",+ "license": "MIT",+ "engines": {+ "node": ">=12"+ },+ "funding": {+ "url": "https://github.com/chalk/ansi-styles?sponsor=1"+ }+ },+ "node_modules/argparse": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/argparse/-/argparse-2.0.1.tgz",+ "integrity": "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==",+ "license": "Python-2.0"+ },+ "node_modules/ast-types": {+ "version": "0.16.1",+ "resolved": "https://registry.npmjs.org/ast-types/-/ast-types-0.16.1.tgz",+ "integrity": "sha512-6t10qk83GOG8p0vKmaCr8eiilZwO171AvbROMtvvNiwrTly62t+7XkA8RdIIVbpMhCASAsxgAzdRSwh6nw/5Dg==",+ "license": "MIT",+ "dependencies": {+ "tslib": "^2.0.1"+ },+ "engines": {+ "node": ">=4"+ }+ },+ "node_modules/base64-js": {+ "version": "1.5.1",+ "resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz",+ "integrity": "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==",+ "funding": [+ {+ "type": "github",+ "url": "https://github.com/sponsors/feross"+ },+ {+ "type": "patreon",+ "url": "https://www.patreon.com/feross"+ },+ {+ "type": "consulting",+ "url": "https://feross.org/support"+ }+ ],+ "license": "MIT"+ },+ "node_modules/baseline-browser-mapping": {+ "version": "2.11.37",+ "resolved": "https://registry.npmjs.org/baseline-browser-mapping/-/baseline-browser-mapping-2.11.37.tgz",+ "integrity": "sha512-QYph+vfurmaxhNwi9FprfmtkT5cx2Keg8FzZ0vnjO8ukscIybVyZGMFwdllKGlTI6qyU8ck43OM9UXh+IFJihQ==",+ "license": "Apache-2.0",+ "bin": {+ "baseline-browser-mapping": "dist/cli.cjs"+ },+ "engines": {+ "node": ">=6.0.0"+ }+ },+ "node_modules/brotli": {+ "version": "1.3.3",+ "resolved": "https://registry.npmjs.org/brotli/-/brotli-1.3.3.tgz",+ "integrity": "sha512-oTKjJdShmDuGW94SyyaoQvAjf30dZaHnjJ8uAF+u2/vGJkJbJPJAT1gDiOJP5v1Zb6f9KEyW/1HpuaWIXtGHPg==",+ "license": "MIT",+ "dependencies": {+ "base64-js": "^1.1.2"+ }+ },+ "node_modules/browserslist": {+ "version": "4.29.5",+ "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.29.5.tgz",+ "integrity": "sha512-khTmKu5NGYTotqcYo8Bew2k4RAE9PuXRSFRXG2lQBrCEQHyeQ/vX6gKMxfokwywBsLiXZMnHsmWMG1pnO8J7uQ==",+ "funding": [+ {+ "type": "opencollective",+ "url": "https://opencollective.com/browserslist"+ },+ {+ "type": "tidelift",+ "url": "https://tidelift.com/funding/github/npm/browserslist"+ },+ {+ "type": "github",+ "url": "https://github.com/sponsors/ai"+ }+ ],+ "license": "MIT",+ "dependencies": {+ "baseline-browser-mapping": "^2.11.33",+ "caniuse-lite": "^1.0.30001819",+ "electron-to-chromium": "^1.5.464",+ "node-releases": "^2.0.60",+ "update-browserslist-db": "^1.3.4"+ },+ "bin": {+ "browserslist": "cli.js"+ },+ "engines": {+ "node": "^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7"+ }+ },+ "node_modules/buffer-from": {+ "version": "1.1.2",+ "resolved": "https://registry.npmjs.org/buffer-from/-/buffer-from-1.1.2.tgz",+ "integrity": "sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ==",+ "license": "MIT"+ },+ "node_modules/bundle-name": {+ "version": "4.1.1",+ "resolved": "https://registry.npmjs.org/bundle-name/-/bundle-name-4.1.1.tgz",+ "integrity": "sha512-DdH81/zPLVS11EUgWq3tEu/xn+EzljlMYooDNdzWEnFha3R3NBMpMV1UqYIpjYHV/SgpFKMIX1Oh7o06SjM/oA==",+ "license": "MIT",+ "dependencies": {+ "run-applescript": "^7.0.0"+ },+ "engines": {+ "node": ">=18"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/callsites": {+ "version": "3.1.0",+ "resolved": "https://registry.npmjs.org/callsites/-/callsites-3.1.0.tgz",+ "integrity": "sha512-P8BjAsXvZS+VIDUI11hHCQEv74YT67YUi5JJFNWIqL235sBmjX4+qx9Muvls5ivyNENctx46xQLQ3aTuE7ssaQ==",+ "license": "MIT",+ "engines": {+ "node": ">=6"+ }+ },+ "node_modules/camelcase": {+ "version": "6.3.0",+ "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-6.3.0.tgz",+ "integrity": "sha512-Gmy6FhYlCY7uOElZUSbxo2UCDH8owEk996gkbrpsgGtrJLM3J7jGxl9Ic7Qwwj4ivOE5AWZWRMecDdF7hqGjFA==",+ "license": "MIT",+ "engines": {+ "node": ">=10"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/caniuse-lite": {+ "version": "1.0.30001826",+ "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001826.tgz",+ "integrity": "sha512-wTB+9tIbLro/BCXwLuNV1meHE4L9dS6dArMDwgYfNBPMYScqClHyGunhkCSDtHhe/69Xl0sHlKgBVZ+fNsYtWA==",+ "funding": [+ {+ "type": "opencollective",+ "url": "https://opencollective.com/browserslist"+ },+ {+ "type": "tidelift",+ "url": "https://tidelift.com/funding/github/npm/caniuse-lite"+ },+ {+ "type": "github",+ "url": "https://github.com/sponsors/ai"+ }+ ],+ "license": "CC-BY-4.0"+ },+ "node_modules/chrome-trace-event": {+ "version": "1.0.4",+ "resolved": "https://registry.npmjs.org/chrome-trace-event/-/chrome-trace-event-1.0.4.tgz",+ "integrity": "sha512-rNjApaLzuwaOTjCiT8lSDdGN1APCiqkChLMJxJPWLunPAt5fy8xgU9/jNOchV84wfIxrA0lRQB7oCT8jrn/wrQ==",+ "license": "MIT",+ "engines": {+ "node": ">=6.0"+ }+ },+ "node_modules/chromium-bidi": {+ "version": "157.0.8090-0",+ "resolved": "https://registry.npmjs.org/chromium-bidi/-/chromium-bidi-157.0.8090-0.tgz",+ "integrity": "sha512-KJw7IQgqXwxpJgJlEIPg5mr2ZoqA+jkTRtc5EABI7sUJ3bu3cpI7NuEBoj4Gn1AsF78CaT9So5WQWspK3/wYag==",+ "license": "Apache-2.0",+ "dependencies": {+ "mitt": "^3.0.1",+ "zod": "^4.6.5"+ },+ "engines": {+ "node": ">=20.19.0 <22.0.0 || >=22.12.0"+ },+ "peerDependencies": {+ "devtools-protocol": "*"+ }+ },+ "node_modules/citty": {+ "version": "0.2.2",+ "resolved": "https://registry.npmjs.org/citty/-/citty-0.2.2.tgz",+ "integrity": "sha512-+6vJA3L98yv+IdfKGZHBNiGW5KHn22e/JwID0Strsz8h4S/csAu/OuICwxrg44k5MRiZHWIo8XXuJgQTriRP4w==",+ "license": "MIT"+ },+ "node_modules/client-zip": {+ "version": "2.5.1",+ "resolved": "https://registry.npmjs.org/client-zip/-/client-zip-2.5.1.tgz",+ "integrity": "sha512-yOvNSBsQX1B7wtdvIVXJEIIShrlPiX+adhli7sWvQhsx3nX1DjvpSt+AwOxaX+3DCsT/Yx0nRy5hIjRLIYfebw==",+ "license": "MIT"+ },+ "node_modules/cliui": {+ "version": "9.0.1",+ "resolved": "https://registry.npmjs.org/cliui/-/cliui-9.0.1.tgz",+ "integrity": "sha512-k7ndgKhwoQveBL+/1tqGJYNz097I7WOvwbmmU2AR5+magtbjPWQTS1C5vzGkBC8Ym8UWRzfKUzUUqFLypY4Q+w==",+ "license": "ISC",+ "dependencies": {+ "string-width": "^7.2.0",+ "strip-ansi": "^7.1.0",+ "wrap-ansi": "^9.0.0"+ },+ "engines": {+ "node": ">=20"+ }+ },+ "node_modules/cliui/node_modules/string-width": {+ "version": "7.2.0",+ "resolved": "https://registry.npmjs.org/string-width/-/string-width-7.2.0.tgz",+ "integrity": "sha512-tsaTIkKW9b4N+AEj+SVA+WhJzV7/zMhcSu78mLKWSk7cXMOSHsBKFWUs0fWwq8QyK3MgJBQRX6Gbi4kYbdvGkQ==",+ "license": "MIT",+ "dependencies": {+ "emoji-regex": "^10.3.0",+ "get-east-asian-width": "^1.0.0",+ "strip-ansi": "^7.1.0"+ },+ "engines": {+ "node": ">=18"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/clone": {+ "version": "2.1.2",+ "resolved": "https://registry.npmjs.org/clone/-/clone-2.1.2.tgz",+ "integrity": "sha512-3Pe/CF1Nn94hyhIYpjtiLhdCoEoz0DqQ+988E9gmeEdQZlojxnOb74wctFyuwWQHzqyf9X7C7MG8juUpqBJT8w==",+ "license": "MIT",+ "engines": {+ "node": ">=0.8"+ }+ },+ "node_modules/commander": {+ "version": "2.20.3",+ "resolved": "https://registry.npmjs.org/commander/-/commander-2.20.3.tgz",+ "integrity": "sha512-GpVkmM8vF2vQUkj2LvZmD35JxeJOLCwJ9cUkugyk2nuhbv3+mJvpLYYt+0+USMxE+oj+ey/lJEnhZw75x/OMcQ==",+ "license": "MIT"+ },+ "node_modules/compare-versions": {+ "version": "6.1.1",+ "resolved": "https://registry.npmjs.org/compare-versions/-/compare-versions-6.1.1.tgz",+ "integrity": "sha512-4hm4VPpIecmlg59CHXnRDnqGplJFrbLG4aFEl5vl6cK1u76ws3LLvX7ikFnTDl5vo39sjWD6AaDPYodJp/NNHg==",+ "license": "MIT"+ },+ "node_modules/convert-source-map": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-2.0.0.tgz",+ "integrity": "sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg==",+ "license": "MIT"+ },+ "node_modules/cosmiconfig": {+ "version": "8.3.6",+ "resolved": "https://registry.npmjs.org/cosmiconfig/-/cosmiconfig-8.3.6.tgz",+ "integrity": "sha512-kcZ6+W5QzcJ3P1Mt+83OUv/oHFqZHIx8DuxG6eZ5RGMERoLqp4BuGjhHLYGK+Kf5XVkQvqBSmAy/nGWN3qDgEA==",+ "license": "MIT",+ "dependencies": {+ "import-fresh": "^3.3.0",+ "js-yaml": "^4.1.0",+ "parse-json": "^5.2.0",+ "path-type": "^4.0.0"+ },+ "engines": {+ "node": ">=14"+ },+ "funding": {+ "url": "https://github.com/sponsors/d-fischer"+ },+ "peerDependencies": {+ "typescript": ">=4.9.5"+ },+ "peerDependenciesMeta": {+ "typescript": {+ "optional": true+ }+ }+ },+ "node_modules/cross-spawn": {+ "version": "7.0.6",+ "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz",+ "integrity": "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==",+ "license": "MIT",+ "dependencies": {+ "path-key": "^3.1.0",+ "shebang-command": "^2.0.0",+ "which": "^2.0.1"+ },+ "engines": {+ "node": ">= 8"+ }+ },+ "node_modules/css-loader": {+ "version": "7.1.4",+ "resolved": "https://registry.npmjs.org/css-loader/-/css-loader-7.1.4.tgz",+ "integrity": "sha512-vv3J9tlOl04WjiMvHQI/9tmIrCxVrj6PFbHemBB1iihpeRbi/I4h033eoFIhwxBBqLhI0KYFS7yvynBFhIZfTw==",+ "license": "MIT",+ "dependencies": {+ "icss-utils": "^5.1.0",+ "postcss": "^8.4.40",+ "postcss-modules-extract-imports": "^3.1.0",+ "postcss-modules-local-by-default": "^4.0.5",+ "postcss-modules-scope": "^3.2.0",+ "postcss-modules-values": "^4.0.0",+ "postcss-value-parser": "^4.2.0",+ "semver": "^7.6.3"+ },+ "engines": {+ "node": ">= 18.12.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/webpack"+ },+ "peerDependencies": {+ "@rspack/core": "0.x || ^1.0.0 || ^2.0.0-0",+ "webpack": "^5.27.0"+ },+ "peerDependenciesMeta": {+ "@rspack/core": {+ "optional": true+ },+ "webpack": {+ "optional": true+ }+ }+ },+ "node_modules/css-loader/node_modules/semver": {+ "version": "7.8.6",+ "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.6.tgz",+ "integrity": "sha512-9lpSSU4Mly3mrtruwLs1eLK6+gzbzqeBFwRNjIjE+9LuDpWdYctrQlQ3ej1Ilgi7gknpsTRnPoLP8DpCHqHIJw==",+ "license": "ISC",+ "bin": {+ "semver": "bin/semver.js"+ },+ "engines": {+ "node": ">=10"+ }+ },+ "node_modules/css-tree": {+ "version": "3.2.1",+ "resolved": "https://registry.npmjs.org/css-tree/-/css-tree-3.2.1.tgz",+ "integrity": "sha512-X7sjQzceUhu1u7Y/ylrRZFU2FS6LRiFVp6rKLPg23y3x3c3DOKAwuXGDp+PAGjh6CSnCjYeAul8pcT8bAl+lSA==",+ "license": "MIT",+ "dependencies": {+ "mdn-data": "2.27.1",+ "source-map-js": "^1.2.1"+ },+ "engines": {+ "node": "^10 || ^12.20.0 || ^14.13.0 || >=15.0.0"+ }+ },+ "node_modules/debug": {+ "version": "4.4.3",+ "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz",+ "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==",+ "license": "MIT",+ "dependencies": {+ "ms": "^2.1.3"+ },+ "engines": {+ "node": ">=6.0"+ },+ "peerDependenciesMeta": {+ "supports-color": {+ "optional": true+ }+ }+ },+ "node_modules/default-browser": {+ "version": "5.5.1",+ "resolved": "https://registry.npmjs.org/default-browser/-/default-browser-5.5.1.tgz",+ "integrity": "sha512-m1pAzaJgZ/gssEqlOhJkPJp8Xly7QyW6xcrkUa2KKcDeDSEMP7X8xipU3snUcfisTQx0w1AGae+9UtJSfVnXGw==",+ "license": "MIT",+ "dependencies": {+ "bundle-name": "^4.1.0",+ "default-browser-id": "^5.0.0"+ },+ "engines": {+ "node": ">=18"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/default-browser-id": {+ "version": "5.0.1",+ "resolved": "https://registry.npmjs.org/default-browser-id/-/default-browser-id-5.0.1.tgz",+ "integrity": "sha512-x1VCxdX4t+8wVfd1so/9w+vQ4vx7lKd2Qp5tDRutErwmR85OgmfX7RlLRMWafRMY7hbEiXIbudNrjOAPa/hL8Q==",+ "license": "MIT",+ "engines": {+ "node": ">=18"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/define-lazy-prop": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/define-lazy-prop/-/define-lazy-prop-2.0.0.tgz",+ "integrity": "sha512-Ds09qNh8yw3khSjiJjiUInaGX9xlqZDY7JVryGxdxV7NPeuqQfplOpQ66yJFZut3jLa5zOwkXw1g9EI2uKh4Og==",+ "license": "MIT",+ "engines": {+ "node": ">=8"+ }+ },+ "node_modules/detect-libc": {+ "version": "2.1.2",+ "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz",+ "integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==",+ "license": "Apache-2.0",+ "optional": true,+ "engines": {+ "node": ">=8"+ }+ },+ "node_modules/devtools-protocol": {+ "version": "0.0.1717327",+ "resolved": "https://registry.npmjs.org/devtools-protocol/-/devtools-protocol-0.0.1717327.tgz",+ "integrity": "sha512-3RDLDzyvv8XAYf1L+TL1og0EEk0eOW1Jn0yi88uG6Bj8fUKO1ZKfgNtwbJkqf5SWdPDS4VGEPxwdUWz78V6Xcg==",+ "license": "BSD-3-Clause"+ },+ "node_modules/dfa": {+ "version": "1.2.0",+ "resolved": "https://registry.npmjs.org/dfa/-/dfa-1.2.0.tgz",+ "integrity": "sha512-ED3jP8saaweFTjeGX8HQPjeC1YYyZs98jGNZx6IiBvxW7JG5v492kamAQB3m2wop07CvU/RQmzcKr6bgcC5D/Q==",+ "license": "MIT"+ },+ "node_modules/dot-case": {+ "version": "3.0.4",+ "resolved": "https://registry.npmjs.org/dot-case/-/dot-case-3.0.4.tgz",+ "integrity": "sha512-Kv5nKlh6yRrdrGvxeJ2e5y2eRUpkUosIW4A2AS38zwSz27zu7ufDwQPi5Jhs3XAlGNetl3bmnGhQsMtkKJnj3w==",+ "license": "MIT",+ "dependencies": {+ "no-case": "^3.0.4",+ "tslib": "^2.0.3"+ }+ },+ "node_modules/dotenv": {+ "version": "17.3.1",+ "resolved": "https://registry.npmjs.org/dotenv/-/dotenv-17.3.1.tgz",+ "integrity": "sha512-IO8C/dzEb6O3F9/twg6ZLXz164a2fhTnEWb95H23Dm4OuN+92NmEAlTrupP9VW6Jm3sO26tQlqyvyi4CsnY9GA==",+ "license": "BSD-2-Clause",+ "engines": {+ "node": ">=12"+ },+ "funding": {+ "url": "https://dotenvx.com"+ }+ },+ "node_modules/electron-to-chromium": {+ "version": "1.5.486",+ "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.486.tgz",+ "integrity": "sha512-rpybw4Ac4ak/An6G1Me2+61xzwobowDGyuJe71QHHOVpkZv4fPVobsLl7WH6zHSKusAMpaHxGKTpOvpy7+r3dQ==",+ "license": "ISC"+ },+ "node_modules/emoji-regex": {+ "version": "10.6.0",+ "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-10.6.0.tgz",+ "integrity": "sha512-toUI84YS5YmxW219erniWD0CIVOo46xGKColeNQRgOzDorgBi1v4D71/OFzgD9GO2UGKIv1C3Sp8DAn0+j5w7A==",+ "license": "MIT"+ },+ "node_modules/enhanced-resolve": {+ "version": "5.27.0",+ "resolved": "https://registry.npmjs.org/enhanced-resolve/-/enhanced-resolve-5.27.0.tgz",+ "integrity": "sha512-Do6BB2xzlcc/odFg+XEYyneAx4T/WfywO71yw9ePS2tVfRsf7JVR4mUeELadIeHzixkzbG5DpluiEFPi2WGfYQ==",+ "license": "MIT",+ "dependencies": {+ "graceful-fs": "^4.2.4",+ "tapable": "^2.3.3"+ },+ "engines": {+ "node": ">=10.13.0"+ }+ },+ "node_modules/entities": {+ "version": "4.5.0",+ "resolved": "https://registry.npmjs.org/entities/-/entities-4.5.0.tgz",+ "integrity": "sha512-V0hjH4dGPh9Ao5p0MoRY6BVqtwCjhz6vI5LT8AJ55H+4g9/4vbHx1I54fS0XuclLhDHArPQCiMjDxjaL8fPxhw==",+ "license": "BSD-2-Clause",+ "engines": {+ "node": ">=0.12"+ },+ "funding": {+ "url": "https://github.com/fb55/entities?sponsor=1"+ }+ },+ "node_modules/error-ex": {+ "version": "1.3.4",+ "resolved": "https://registry.npmjs.org/error-ex/-/error-ex-1.3.4.tgz",+ "integrity": "sha512-sqQamAnR14VgCr1A618A3sGrygcpK+HEbenA/HiEAkkUwcZIIB/tgWqHFxWgOyDh4nB4JCRimh79dR5Ywc9MDQ==",+ "license": "MIT",+ "dependencies": {+ "is-arrayish": "^0.2.1"+ }+ },+ "node_modules/es-module-lexer": {+ "version": "2.3.2",+ "resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-2.3.2.tgz",+ "integrity": "sha512-poHGpORABojJJucnV9KbOavETW8lBVnphkW77ER5/BQ5Fz7oXSoCNek7IH3vR5nRjdsEz926ibFYX8KtLQmdyw==",+ "license": "MIT"+ },+ "node_modules/esbuild": {+ "version": "0.28.1",+ "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.28.1.tgz",+ "integrity": "sha512-HrJrvZv5ayxBzPfwphOoNzkzOIIlifzk0KJrGK2c8R4+LKpMtpYLQeUdjnwjWv/LZlkH2laZk+4w78pi99D4Vw==",+ "hasInstallScript": true,+ "license": "MIT",+ "bin": {+ "esbuild": "bin/esbuild"+ },+ "engines": {+ "node": ">=18"+ },+ "optionalDependencies": {+ "@esbuild/aix-ppc64": "0.28.1",+ "@esbuild/android-arm": "0.28.1",+ "@esbuild/android-arm64": "0.28.1",+ "@esbuild/android-x64": "0.28.1",+ "@esbuild/darwin-arm64": "0.28.1",+ "@esbuild/darwin-x64": "0.28.1",+ "@esbuild/freebsd-arm64": "0.28.1",+ "@esbuild/freebsd-x64": "0.28.1",+ "@esbuild/linux-arm": "0.28.1",+ "@esbuild/linux-arm64": "0.28.1",+ "@esbuild/linux-ia32": "0.28.1",+ "@esbuild/linux-loong64": "0.28.1",+ "@esbuild/linux-mips64el": "0.28.1",+ "@esbuild/linux-ppc64": "0.28.1",+ "@esbuild/linux-riscv64": "0.28.1",+ "@esbuild/linux-s390x": "0.28.1",+ "@esbuild/linux-x64": "0.28.1",+ "@esbuild/netbsd-arm64": "0.28.1",+ "@esbuild/netbsd-x64": "0.28.1",+ "@esbuild/openbsd-arm64": "0.28.1",+ "@esbuild/openbsd-x64": "0.28.1",+ "@esbuild/openharmony-arm64": "0.28.1",+ "@esbuild/sunos-x64": "0.28.1",+ "@esbuild/win32-arm64": "0.28.1",+ "@esbuild/win32-ia32": "0.28.1",+ "@esbuild/win32-x64": "0.28.1"+ }+ },+ "node_modules/escalade": {+ "version": "3.2.0",+ "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.2.0.tgz",+ "integrity": "sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==",+ "license": "MIT",+ "engines": {+ "node": ">=6"+ }+ },+ "node_modules/eslint-scope": {+ "version": "5.1.1",+ "resolved": "https://registry.npmjs.org/eslint-scope/-/eslint-scope-5.1.1.tgz",+ "integrity": "sha512-2NxwbF/hZ0KpepYN0cNbo+FN6XoK7GaHlQhgx/hIZl6Va0bF45RQOOwhLIy8lQDbuCiadSLCBnH2CFYquit5bw==",+ "license": "BSD-2-Clause",+ "dependencies": {+ "esrecurse": "^4.3.0",+ "estraverse": "^4.1.1"+ },+ "engines": {+ "node": ">=8.0.0"+ }+ },+ "node_modules/esprima": {+ "version": "4.0.1",+ "resolved": "https://registry.npmjs.org/esprima/-/esprima-4.0.1.tgz",+ "integrity": "sha512-eGuFFw7Upda+g4p+QHvnW0RyTX/SVeJBDM/gCtMARO0cLuT2HcEKnTPvhjV6aGeqrCB/sbNop0Kszm0jsaWU4A==",+ "license": "BSD-2-Clause",+ "bin": {+ "esparse": "bin/esparse.js",+ "esvalidate": "bin/esvalidate.js"+ },+ "engines": {+ "node": ">=4"+ }+ },+ "node_modules/esrecurse": {+ "version": "4.3.0",+ "resolved": "https://registry.npmjs.org/esrecurse/-/esrecurse-4.3.0.tgz",+ "integrity": "sha512-KmfKL3b6G+RXvP8N1vr3Tq1kL/oCFgn2NYXEtqP8/L3pKapUA4G8cFVaoF3SU323CD4XypR/ffioHmkti6/Tag==",+ "license": "BSD-2-Clause",+ "dependencies": {+ "estraverse": "^5.2.0"+ },+ "engines": {+ "node": ">=4.0"+ }+ },+ "node_modules/esrecurse/node_modules/estraverse": {+ "version": "5.3.0",+ "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-5.3.0.tgz",+ "integrity": "sha512-MMdARuVEQziNTeJD8DgMqmhwR11BRQ/cBP+pLtYdSTnf3MIO8fFeiINEbX36ZdNlfU/7A9f3gUw49B3oQsvwBA==",+ "license": "BSD-2-Clause",+ "engines": {+ "node": ">=4.0"+ }+ },+ "node_modules/estraverse": {+ "version": "4.3.0",+ "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-4.3.0.tgz",+ "integrity": "sha512-39nnKffWz8xN1BU/2c79n9nB9HDzo0niYUqx6xyqUnyoAnQyyWpOTdZEeiCch8BBu515t4wp9ZmgVfVhn9EBpw==",+ "license": "BSD-2-Clause",+ "engines": {+ "node": ">=4.0"+ }+ },+ "node_modules/events": {+ "version": "3.3.0",+ "resolved": "https://registry.npmjs.org/events/-/events-3.3.0.tgz",+ "integrity": "sha512-mQw+2fkQbALzQ7V0MY0IqdnXNOeTtP4r0lN9z7AAawCXgqea7bDii20AYrIBrFd/Hx0M2Ocz6S111CaFkUcb0Q==",+ "license": "MIT",+ "engines": {+ "node": ">=0.8.x"+ }+ },+ "node_modules/execa": {+ "version": "5.1.1",+ "resolved": "https://registry.npmjs.org/execa/-/execa-5.1.1.tgz",+ "integrity": "sha512-8uSpZZocAZRBAPIEINJj3Lo9HyGitllczc27Eh5YYojjMFMn8yHMDMaUHE2Jqfq05D/wucwI4JGURyXt1vchyg==",+ "license": "MIT",+ "dependencies": {+ "cross-spawn": "^7.0.3",+ "get-stream": "^6.0.0",+ "human-signals": "^2.1.0",+ "is-stream": "^2.0.0",+ "merge-stream": "^2.0.0",+ "npm-run-path": "^4.0.1",+ "onetime": "^5.1.2",+ "signal-exit": "^3.0.3",+ "strip-final-newline": "^2.0.0"+ },+ "engines": {+ "node": ">=10"+ },+ "funding": {+ "url": "https://github.com/sindresorhus/execa?sponsor=1"+ }+ },+ "node_modules/fast-deep-equal": {+ "version": "3.1.3",+ "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz",+ "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==",+ "license": "MIT"+ },+ "node_modules/fast-uri": {+ "version": "3.1.9",+ "resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.9.tgz",+ "integrity": "sha512-hS/0Wt3Ya043oKXs0sIxrMpKQITXhMLIrVAKKXi4gozGC9v7YRWVnXIZzjNPTO02M9BdxLCWqK1yRXgNziVyJQ==",+ "funding": [+ {+ "type": "github",+ "url": "https://github.com/sponsors/fastify"+ },+ {+ "type": "opencollective",+ "url": "https://opencollective.com/fastify"+ }+ ],+ "license": "BSD-3-Clause"+ },+ "node_modules/fontkit": {+ "version": "2.0.4",+ "resolved": "https://registry.npmjs.org/fontkit/-/fontkit-2.0.4.tgz",+ "integrity": "sha512-syetQadaUEDNdxdugga9CpEYVaQIxOwk7GlwZWWZ19//qW4zE5bknOKeMBDYAASwnpaSHKJITRLMF9m1fp3s6g==",+ "license": "MIT",+ "dependencies": {+ "@swc/helpers": "^0.5.12",+ "brotli": "^1.3.2",+ "clone": "^2.1.2",+ "dfa": "^1.2.0",+ "fast-deep-equal": "^3.1.3",+ "restructure": "^3.0.0",+ "tiny-inflate": "^1.0.3",+ "unicode-properties": "^1.4.0",+ "unicode-trie": "^2.0.0"+ }+ },+ "node_modules/fs-monkey": {+ "version": "1.0.3",+ "resolved": "https://registry.npmjs.org/fs-monkey/-/fs-monkey-1.0.3.tgz",+ "integrity": "sha512-cybjIfiiE+pTWicSCLFHSrXZ6EilF30oh91FDP9S2B051prEa7QWfrVTQm10/dDpswBDXZugPa1Ogu8Yh+HV0Q==",+ "license": "Unlicense"+ },+ "node_modules/gensync": {+ "version": "1.0.0-beta.2",+ "resolved": "https://registry.npmjs.org/gensync/-/gensync-1.0.0-beta.2.tgz",+ "integrity": "sha512-3hN7NaskYvMDLQY55gnW3NQ+mesEAepTqlg+VEbj7zzqEMBVNhzcGYYeqFo/TlYz6eQiFcp1HcsCZO+nGgS8zg==",+ "license": "MIT",+ "engines": {+ "node": ">=6.9.0"+ }+ },+ "node_modules/get-caller-file": {+ "version": "2.0.5",+ "resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz",+ "integrity": "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==",+ "license": "ISC",+ "engines": {+ "node": "6.* || 8.* || >= 10.*"+ }+ },+ "node_modules/get-east-asian-width": {+ "version": "1.7.0",+ "resolved": "https://registry.npmjs.org/get-east-asian-width/-/get-east-asian-width-1.7.0.tgz",+ "integrity": "sha512-XjH1AECxf0giL2V1aU8vKyRR2ppRUb5c0EvT7zuJTokQ74bNo52zOtghqdWIqrhUD79fo3x0WfKZdOqxF6LG1Q==",+ "license": "MIT",+ "engines": {+ "node": ">=18"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/get-stream": {+ "version": "6.0.1",+ "resolved": "https://registry.npmjs.org/get-stream/-/get-stream-6.0.1.tgz",+ "integrity": "sha512-ts6Wi+2j3jQjqi70w5AlN8DFnkSwC+MqmxEzdEALB2qXZYV3X/b1CTfgPLGJNMeAWxdPfU8FO1ms3NUfaHCPYg==",+ "license": "MIT",+ "engines": {+ "node": ">=10"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/giget": {+ "version": "3.3.1",+ "resolved": "https://registry.npmjs.org/giget/-/giget-3.3.1.tgz",+ "integrity": "sha512-r+mvuDjrjMpsdw46Kmeydb8bdHm7wOKw8wNBtTndkjbPjgAp5oUJUxRE76wZFknxIPokfWvep2qSXK37aXE6zg==",+ "license": "MIT",+ "bin": {+ "giget": "dist/cli.mjs"+ }+ },+ "node_modules/glob-to-regexp": {+ "version": "0.4.1",+ "resolved": "https://registry.npmjs.org/glob-to-regexp/-/glob-to-regexp-0.4.1.tgz",+ "integrity": "sha512-lkX1HJXwyMcprw/5YUZc2s7DrpAiHB21/V+E1rHUrVNokkvB6bqMzT0VfV6/86ZNabt1k14YOIaT7nDvOX3Iiw==",+ "license": "BSD-2-Clause"+ },+ "node_modules/graceful-fs": {+ "version": "4.2.12",+ "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.12.tgz",+ "integrity": "sha512-iuyGF2E4oafQfPsRrG2wtY2ILupMhvtdrhzrxB+0VcjsPpSPttpfYdjnGFGsTi5MaJFjI1jOKHPQ6UTbTj9TAw==",+ "license": "BlueOak-1.0.0"+ },+ "node_modules/gsap": {+ "version": "3.15.0",+ "resolved": "https://registry.npmjs.org/gsap/-/gsap-3.15.0.tgz",+ "integrity": "sha512-dMW4CWBTUK1AEEDeZc1g4xpPGIrSf9fJF960qbTZmN/QwZIWY5wgliS6JWl9/25fpTGJrMRtSjGtOmPnfjZB+A==",+ "license": "Standard 'no charge' license: https://gsap.com/standard-license."+ },+ "node_modules/has-flag": {+ "version": "4.0.0",+ "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz",+ "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==",+ "license": "MIT",+ "engines": {+ "node": ">=8"+ }+ },+ "node_modules/hono": {+ "version": "4.13.18",+ "resolved": "https://registry.npmjs.org/hono/-/hono-4.13.18.tgz",+ "integrity": "sha512-H9q/E1XizaWstJxUW881dmLxEj+t/TrGGnyxINkm4+sK0qUwsMtFdo2BWI9Vs3cIS19MU6b6iCijoUoEf4f3DA==",+ "license": "MIT",+ "engines": {+ "node": ">=16.9.0"+ }+ },+ "node_modules/human-signals": {+ "version": "2.1.0",+ "resolved": "https://registry.npmjs.org/human-signals/-/human-signals-2.1.0.tgz",+ "integrity": "sha512-B4FFZ6q/T2jhhksgkbEW3HBvWIfDW85snkQgawt07S7J5QXTk6BkNV+0yAeZrM5QpMAdYlocGoljn0sJ/WQkFw==",+ "license": "Apache-2.0",+ "engines": {+ "node": ">=10.17.0"+ }+ },+ "node_modules/hyperframes": {+ "version": "0.9.52",+ "resolved": "https://registry.npmjs.org/hyperframes/-/hyperframes-0.9.52.tgz",+ "integrity": "sha512-TGfCsrgUhsKQj7kVXBBi1t4mO2pK9niU6Cu3UHO5HLhuUCQzTWElSSUmu38Z2FXaMt7tllOw/lBX12w/1OdOuw==",+ "license": "Apache-2.0",+ "dependencies": {+ "@hono/node-server": "^2.1.6",+ "@puppeteer/browsers": "^3.2.2",+ "acorn": "^8.17.0",+ "adm-zip": "^0.6.1",+ "citty": "^0.2.1",+ "compare-versions": "^6.1.1",+ "css-tree": "^3.2.1",+ "debug": "^4.4.0",+ "esbuild": "^0.28.2",+ "fontkit": "^2.0.4",+ "giget": "^3.2.0",+ "hono": "^4.13.16",+ "ignore": "^5.3.2",+ "open": "^10.0.0",+ "postcss": "^8.5.8",+ "puppeteer-core": "^25.10.0",+ "undici": "7.30.1",+ "yauzl": "^3.4.0"+ },+ "bin": {+ "hyperframes": "bin/hyperframes.mjs",+ "hyperframes-localize-fonts": "bin/hyperframes-localize-fonts.mjs"+ },+ "engines": {+ "node": ">=22"+ },+ "optionalDependencies": {+ "sharp": "^0.35.5"+ }+ },+ "node_modules/hyperframes/node_modules/@esbuild/aix-ppc64": {+ "version": "0.28.2",+ "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.28.2.tgz",+ "integrity": "sha512-XExcO+dvLKvVtNTibSTBej1NCAbaGhWn9Ww1ZPx80qsahhPFe/8jgWP0IchNe0F3HwkU7n8ejhH8bjonqht8mQ==",+ "cpu": [+ "ppc64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "aix"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/hyperframes/node_modules/@esbuild/android-arm": {+ "version": "0.28.2",+ "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.28.2.tgz",+ "integrity": "sha512-kXXoiPVVGQcnIYGOeaovwOURpniDBpSq4A03qkQ+BMQqtGG6HYap3xne9C1O1yo4TR3qxlCX5IqqmX6fFo2Lqg==",+ "cpu": [+ "arm"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "android"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/hyperframes/node_modules/@esbuild/android-arm64": {+ "version": "0.28.2",+ "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.28.2.tgz",+ "integrity": "sha512-5YfKeeI8qWfBZIX+u2xZC3Zlb3Os/gLS2sbEKM+I4ZOcsWmHS2WLysCcQZDAFRslDUU5Oiq44gf6PYN1vGwG5A==",+ "cpu": [+ "arm64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "android"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/hyperframes/node_modules/@esbuild/android-x64": {+ "version": "0.28.2",+ "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.28.2.tgz",+ "integrity": "sha512-O387ite7SzUyCcy3JQX4P4bLtEA7bLLkx+esve5JHnyYfNTxcVpXZo9jhdB0lTKN44gztELTdU7nS8Nr16Fs1Q==",+ "cpu": [+ "x64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "android"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/hyperframes/node_modules/@esbuild/darwin-arm64": {+ "version": "0.28.2",+ "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.28.2.tgz",+ "integrity": "sha512-n4KqkOQrraxHJcgjM1RvwbigfQKIKJVpM7xp+KsxiyUSrRdIXnt73VhrPAx0fV44hgfmIVKjxMN9J1t5jySVkw==",+ "cpu": [+ "arm64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "darwin"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/hyperframes/node_modules/@esbuild/darwin-x64": {+ "version": "0.28.2",+ "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.28.2.tgz",+ "integrity": "sha512-uq6suIWYP37qzGddBKPw5QEQPi6HiLGsO7UmkpfyaYNQ3D+rN6w6WfwH+nuqcGXWvawGwxOEroO4YGnFh95azw==",+ "cpu": [+ "x64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "darwin"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/hyperframes/node_modules/@esbuild/freebsd-arm64": {+ "version": "0.28.2",+ "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.28.2.tgz",+ "integrity": "sha512-n+I0BTSRIoy+d6RPKnEVwql5UwBJolytvY4mAOIEJorKlqgPII8ix6slVVrfZ5Tnj7glIZvloylbB/EJPMWEXw==",+ "cpu": [+ "arm64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "freebsd"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/hyperframes/node_modules/@esbuild/freebsd-x64": {+ "version": "0.28.2",+ "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.28.2.tgz",+ "integrity": "sha512-78XJTJkvPs0kz2w61301PJjXl4g7q3JqiYMZ/M/yVI73EHBrCRTgkhu9oqG7vPqq+a/yadEW8aD+agKlk5xrmg==",+ "cpu": [+ "x64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "freebsd"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/hyperframes/node_modules/@esbuild/linux-arm": {+ "version": "0.28.2",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.28.2.tgz",+ "integrity": "sha512-XlDnu2q5yoqems+xay6wSAcg9DDD7K9RLKZEBOMZm3ckNpJBvOX20tSfby8KfrrhINDyv9V2YVZKY/SpoGJI8w==",+ "cpu": [+ "arm"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/hyperframes/node_modules/@esbuild/linux-arm64": {+ "version": "0.28.2",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.28.2.tgz",+ "integrity": "sha512-pW4AC0P3it8c7do9MVM4p51FzHzdM/TZrerurgRcHJ2WTa1VQ1CIq18xncfpBJw4ojkiZZrKW2yIBWBP92j6Ug==",+ "cpu": [+ "arm64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/hyperframes/node_modules/@esbuild/linux-ia32": {+ "version": "0.28.2",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.28.2.tgz",+ "integrity": "sha512-CYbnj78HsIeA+DhgUKgFCfvNsTHFhMMrinUrMZpDXJXKN8T3XViTZ/+wtHeVxEWY8ewSzTFN+nRmSwO2tZaLUQ==",+ "cpu": [+ "ia32"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/hyperframes/node_modules/@esbuild/linux-loong64": {+ "version": "0.28.2",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.28.2.tgz",+ "integrity": "sha512-buwkd8nsph4R+ajRvw0qM5Hja/TXQow3ptzWO2EbG/cqcIkHloRrdlBtQlshyYGTNFvfkfJ5tpPLVkY4DtsPfQ==",+ "cpu": [+ "loong64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/hyperframes/node_modules/@esbuild/linux-mips64el": {+ "version": "0.28.2",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.28.2.tgz",+ "integrity": "sha512-ZVykbDyk7519VwiNb9Lcj9m8XM6v5V9uKPvrEMkkEedVewf+0itkhahp4HDpgERXhwLRpWFypsGbG/J8s0QjJA==",+ "cpu": [+ "mips64el"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/hyperframes/node_modules/@esbuild/linux-ppc64": {+ "version": "0.28.2",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.28.2.tgz",+ "integrity": "sha512-CAXl+Dtd9UUuJd8pKKdwh6MLm3MUMiqMPmhZ3tTSXPqfyQ3vDl6R5hZdZ/kYojK4ofXtdfSv1tFq8XzWx3heNQ==",+ "cpu": [+ "ppc64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/hyperframes/node_modules/@esbuild/linux-riscv64": {+ "version": "0.28.2",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.28.2.tgz",+ "integrity": "sha512-GeXCej4IQtU1B+QlDV8W/RRvbzI3O/Stss+/bCXv4lZls5WGRtu2a+3JkA3i4qIUlMXpcHebWpF8AkJhATowuA==",+ "cpu": [+ "riscv64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/hyperframes/node_modules/@esbuild/linux-s390x": {+ "version": "0.28.2",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.28.2.tgz",+ "integrity": "sha512-3H1weTYZPxt/WOhByszQZybS9w5lKzUn1FDMsgEChbHWQwHYQQRfBxgCcZvPhjHfKyJjIievvMmEUawJrdY9Dg==",+ "cpu": [+ "s390x"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/hyperframes/node_modules/@esbuild/linux-x64": {+ "version": "0.28.2",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.28.2.tgz",+ "integrity": "sha512-4xTZr1FUmSoQW4XIWmit3tzQrUTZM+N3P0XV8xROKYF50XfI7xeO90+1bZvNwxIufQ9hDQVRJH5YhgPVF8A/HQ==",+ "cpu": [+ "x64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/hyperframes/node_modules/@esbuild/netbsd-arm64": {+ "version": "0.28.2",+ "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.28.2.tgz",+ "integrity": "sha512-sSATRjPeDBg3pdgHoQfoYBob11Kk1FGa9lui5RIHZCoCkJa9QKlvl3/vKz2usCmYYjs7ymJR/2Nnsqe+Hjt5nw==",+ "cpu": [+ "arm64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "netbsd"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/hyperframes/node_modules/@esbuild/netbsd-x64": {+ "version": "0.28.2",+ "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.28.2.tgz",+ "integrity": "sha512-lqnzCV+mM0gIADaKihiCg6ifgfU2L3h5E33rNQBN1Y4MaVGnzryzmvvf7UHxprpQdE8hpqLolJ9Rl+SkIRDpyw==",+ "cpu": [+ "x64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "netbsd"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/hyperframes/node_modules/@esbuild/openbsd-arm64": {+ "version": "0.28.2",+ "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.28.2.tgz",+ "integrity": "sha512-AL2qJILH7lNjrDmCQDvdxMfAUIv8KMNZOvrwAQ8i8//ntL9FflhOyMJ8OZSMBb8/AWXe3/5v5S20y3zCoZWKoQ==",+ "cpu": [+ "arm64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "openbsd"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/hyperframes/node_modules/@esbuild/openbsd-x64": {+ "version": "0.28.2",+ "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.28.2.tgz",+ "integrity": "sha512-QtiuPytchRyC4rwUKhexJdQKvDuZ6hWloi3igqPQNUJCS1/v9EiO3UTOXR6A3FoMo4fnAKbWJdqaIwhOzh8qEw==",+ "cpu": [+ "x64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "openbsd"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/hyperframes/node_modules/@esbuild/openharmony-arm64": {+ "version": "0.28.2",+ "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.28.2.tgz",+ "integrity": "sha512-WkhYDmpTjLvGlScA1rwjRUmhl4k8oXR3cIbtqWmELgU/dFeHHlEllxDvdWcNJV9rbzCexB5vz8gtNewWLgCT7Q==",+ "cpu": [+ "arm64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "openharmony"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/hyperframes/node_modules/@esbuild/sunos-x64": {+ "version": "0.28.2",+ "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.28.2.tgz",+ "integrity": "sha512-GPMSkTOtMnv2U2F8gxe4Io6qmVs+YKyp832Etqqxr0hFngmXQ3rzwytelm3GIn7T4VviRUlf3sOgBOiTdvaf7g==",+ "cpu": [+ "x64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "sunos"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/hyperframes/node_modules/@esbuild/win32-arm64": {+ "version": "0.28.2",+ "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.28.2.tgz",+ "integrity": "sha512-PIhhEkE9uPBleRBrQEJpUn7MBnibZzbGzYWPmY3x+YoVg/95zbjB4CxPPOQ8l5tYYM4mMaCthF8/1DIfBQQyWQ==",+ "cpu": [+ "arm64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "win32"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/hyperframes/node_modules/@esbuild/win32-ia32": {+ "version": "0.28.2",+ "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.28.2.tgz",+ "integrity": "sha512-YmJbfTlvU7Sdn9BB+4PRES4oB6pxgS37MAONj+hBr/cpXS1aBPKXxNnDbu+QCWPj0o9dgyxeq79g6c5P8KeuYA==",+ "cpu": [+ "ia32"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "win32"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/hyperframes/node_modules/@esbuild/win32-x64": {+ "version": "0.28.2",+ "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.28.2.tgz",+ "integrity": "sha512-5ebpxr3nWMzrL/rnUI755Jkuee0bHL/Gq0WTF9lvcpv73wAp5eu8MfBUgWK9bhWvZjj7yX8etf/8tI8Ney695g==",+ "cpu": [+ "x64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "win32"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/hyperframes/node_modules/define-lazy-prop": {+ "version": "3.0.0",+ "resolved": "https://registry.npmjs.org/define-lazy-prop/-/define-lazy-prop-3.0.0.tgz",+ "integrity": "sha512-N+MeXYoqr3pOgn8xfyRPREN7gHakLYjhsHhWGT3fWAiL4IkAt0iDw14QiiEm2bE30c5XX5q0FtAA3CK5f9/BUg==",+ "license": "MIT",+ "engines": {+ "node": ">=12"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/hyperframes/node_modules/esbuild": {+ "version": "0.28.2",+ "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.28.2.tgz",+ "integrity": "sha512-HKVLS8dvII+xoKW9kmqxbRKrnWEXfJJr/FZhhJmiqIB0e053QNYFqOBouTMO/k5sID4MvCiUCvv8b9M4h32wIA==",+ "hasInstallScript": true,+ "license": "MIT",+ "bin": {+ "esbuild": "bin/esbuild"+ },+ "engines": {+ "node": ">=18"+ },+ "optionalDependencies": {+ "@esbuild/aix-ppc64": "0.28.2",+ "@esbuild/android-arm": "0.28.2",+ "@esbuild/android-arm64": "0.28.2",+ "@esbuild/android-x64": "0.28.2",+ "@esbuild/darwin-arm64": "0.28.2",+ "@esbuild/darwin-x64": "0.28.2",+ "@esbuild/freebsd-arm64": "0.28.2",+ "@esbuild/freebsd-x64": "0.28.2",+ "@esbuild/linux-arm": "0.28.2",+ "@esbuild/linux-arm64": "0.28.2",+ "@esbuild/linux-ia32": "0.28.2",+ "@esbuild/linux-loong64": "0.28.2",+ "@esbuild/linux-mips64el": "0.28.2",+ "@esbuild/linux-ppc64": "0.28.2",+ "@esbuild/linux-riscv64": "0.28.2",+ "@esbuild/linux-s390x": "0.28.2",+ "@esbuild/linux-x64": "0.28.2",+ "@esbuild/netbsd-arm64": "0.28.2",+ "@esbuild/netbsd-x64": "0.28.2",+ "@esbuild/openbsd-arm64": "0.28.2",+ "@esbuild/openbsd-x64": "0.28.2",+ "@esbuild/openharmony-arm64": "0.28.2",+ "@esbuild/sunos-x64": "0.28.2",+ "@esbuild/win32-arm64": "0.28.2",+ "@esbuild/win32-ia32": "0.28.2",+ "@esbuild/win32-x64": "0.28.2"+ }+ },+ "node_modules/hyperframes/node_modules/open": {+ "version": "10.2.0",+ "resolved": "https://registry.npmjs.org/open/-/open-10.2.0.tgz",+ "integrity": "sha512-YgBpdJHPyQ2UE5x+hlSXcnejzAvD0b22U2OuAP+8OnlJT+PjWPxtgmGqKKc+RgTM63U9gN0YzrYc71R2WT/hTA==",+ "license": "MIT",+ "dependencies": {+ "default-browser": "^5.2.1",+ "define-lazy-prop": "^3.0.0",+ "is-inside-container": "^1.0.0",+ "wsl-utils": "^0.1.0"+ },+ "engines": {+ "node": ">=18"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/icss-utils": {+ "version": "5.1.0",+ "resolved": "https://registry.npmjs.org/icss-utils/-/icss-utils-5.1.0.tgz",+ "integrity": "sha512-soFhflCVWLfRNOPU3iv5Z9VUdT44xFRbzjLsEzSr5AQmgqPMTHdU3PMT1Cf1ssx8fLNJDA1juftYl+PUcv3MqA==",+ "license": "ISC",+ "engines": {+ "node": "^10 || ^12 || >= 14"+ },+ "peerDependencies": {+ "postcss": "^8.1.0"+ }+ },+ "node_modules/ignore": {+ "version": "5.3.2",+ "resolved": "https://registry.npmjs.org/ignore/-/ignore-5.3.2.tgz",+ "integrity": "sha512-hsBTNUqQTDwkWtcdYI2i06Y/nUBEsNEDJKjWdigLvegy8kDuJAS8uRlpkkcQpyEXL0Z/pjDy5HBmMjRCJ2gq+g==",+ "license": "MIT",+ "engines": {+ "node": ">= 4"+ }+ },+ "node_modules/import-fresh": {+ "version": "3.3.1",+ "resolved": "https://registry.npmjs.org/import-fresh/-/import-fresh-3.3.1.tgz",+ "integrity": "sha512-TR3KfrTZTYLPB6jUjfx6MF9WcWrHL9su5TObK4ZkYgBdWKPOFoSoQIdEuTuR82pmtxH2spWG9h6etwfr1pLBqQ==",+ "license": "MIT",+ "dependencies": {+ "parent-module": "^1.0.0",+ "resolve-from": "^4.0.0"+ },+ "engines": {+ "node": ">=6"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/is-arrayish": {+ "version": "0.2.1",+ "resolved": "https://registry.npmjs.org/is-arrayish/-/is-arrayish-0.2.1.tgz",+ "integrity": "sha512-zz06S8t0ozoDXMG+ube26zeCTNXcKIPJZJi8hBrF4idCLms4CG9QtK7qBl1boi5ODzFpjswb5JPmHCbMpjaYzg==",+ "license": "MIT"+ },+ "node_modules/is-docker": {+ "version": "2.2.1",+ "resolved": "https://registry.npmjs.org/is-docker/-/is-docker-2.2.1.tgz",+ "integrity": "sha512-F+i2BKsFrH66iaUFc0woD8sLy8getkwTwtOBjvs56Cx4CgJDeKQeqfz8wAYiSb8JOprWhHH5p77PbmYCvvUuXQ==",+ "license": "MIT",+ "bin": {+ "is-docker": "cli.js"+ },+ "engines": {+ "node": ">=8"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/is-inside-container": {+ "version": "1.0.0",+ "resolved": "https://registry.npmjs.org/is-inside-container/-/is-inside-container-1.0.0.tgz",+ "integrity": "sha512-KIYLCCJghfHZxqjYBE7rEy0OBuTd5xCHS7tHVgvCLkx7StIoaxwNW3hCALgEUjFfeRk+MG/Qxmp/vtETEF3tRA==",+ "license": "MIT",+ "dependencies": {+ "is-docker": "^3.0.0"+ },+ "bin": {+ "is-inside-container": "cli.js"+ },+ "engines": {+ "node": ">=14.16"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/is-inside-container/node_modules/is-docker": {+ "version": "3.0.0",+ "resolved": "https://registry.npmjs.org/is-docker/-/is-docker-3.0.0.tgz",+ "integrity": "sha512-eljcgEDlEns/7AXFosB5K/2nCM4P7FQPkGc/DWLy5rmFEWvZayGrik1d9/QIY5nJ4f9YsVvBkA6kJpHn9rISdQ==",+ "license": "MIT",+ "bin": {+ "is-docker": "cli.js"+ },+ "engines": {+ "node": "^12.20.0 || ^14.13.1 || >=16.0.0"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/is-stream": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/is-stream/-/is-stream-2.0.1.tgz",+ "integrity": "sha512-hFoiJiTl63nn+kstHGBtewWSKnQLpyb155KHheA1l39uvtO9nWIop1p3udqPcUd/xbF1VLMO4n7OI6p7RbngDg==",+ "license": "MIT",+ "engines": {+ "node": ">=8"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/is-wsl": {+ "version": "2.2.0",+ "resolved": "https://registry.npmjs.org/is-wsl/-/is-wsl-2.2.0.tgz",+ "integrity": "sha512-fKzAra0rGJUUBwGBgNkHZuToZcn+TtXHpeCgmkMJMMYx1sQDYaCSyjJBSCa2nH1DGm7s3n1oBnohoVTBaN7Lww==",+ "license": "MIT",+ "dependencies": {+ "is-docker": "^2.0.0"+ },+ "engines": {+ "node": ">=8"+ }+ },+ "node_modules/isexe": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz",+ "integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==",+ "license": "ISC"+ },+ "node_modules/jest-worker": {+ "version": "27.5.1",+ "resolved": "https://registry.npmjs.org/jest-worker/-/jest-worker-27.5.1.tgz",+ "integrity": "sha512-7vuh85V5cdDofPyxn58nrPjBktZo0u9x1g8WtjQol+jZDaE+fhN+cIvTj11GndBnMnyfrUOG1sZQxCdjKh+DKg==",+ "license": "MIT",+ "dependencies": {+ "@types/node": "*",+ "merge-stream": "^2.0.0",+ "supports-color": "^8.0.0"+ },+ "engines": {+ "node": ">= 10.13.0"+ }+ },+ "node_modules/js-tokens": {+ "version": "4.0.0",+ "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz",+ "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==",+ "license": "MIT"+ },+ "node_modules/js-yaml": {+ "version": "4.3.2",+ "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.3.2.tgz",+ "integrity": "sha512-SFNOvSJ+Dgf/9An904Yx+CgSlIPCkIpao4qo51lpee25TIRejdH3rhR4EZMGoNx3/TP3O+wzWuiTFl4sqbltzA==",+ "funding": [+ {+ "type": "github",+ "url": "https://github.com/sponsors/puzrin"+ },+ {+ "type": "github",+ "url": "https://github.com/sponsors/nodeca"+ }+ ],+ "license": "MIT",+ "dependencies": {+ "argparse": "^2.0.1"+ },+ "bin": {+ "js-yaml": "bin/js-yaml.js"+ }+ },+ "node_modules/jsesc": {+ "version": "3.1.0",+ "resolved": "https://registry.npmjs.org/jsesc/-/jsesc-3.1.0.tgz",+ "integrity": "sha512-/sM3dO2FOzXjKQhJuo0Q173wf2KOo8t4I8vHy6lF9poUp7bKT0/NHE8fPX23PwfhnykfqnC2xRxOnVw5XuGIaA==",+ "license": "MIT",+ "bin": {+ "jsesc": "bin/jsesc"+ },+ "engines": {+ "node": ">=6"+ }+ },+ "node_modules/json-parse-even-better-errors": {+ "version": "2.3.1",+ "resolved": "https://registry.npmjs.org/json-parse-even-better-errors/-/json-parse-even-better-errors-2.3.1.tgz",+ "integrity": "sha512-xyFwyhro/JEof6Ghe2iz2NcXoj2sloNsWr/XsERDK/oiPCfaNhl5ONfp+jQdAZRQQ0IJWNzH9zIZF7li91kh2w==",+ "license": "MIT"+ },+ "node_modules/json-schema-traverse": {+ "version": "1.0.0",+ "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz",+ "integrity": "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==",+ "license": "MIT"+ },+ "node_modules/json5": {+ "version": "2.2.3",+ "resolved": "https://registry.npmjs.org/json5/-/json5-2.2.3.tgz",+ "integrity": "sha512-XmOWe7eyHYH14cLdVPoyg+GOH3rYX++KpzrylJwSW98t3Nk+U8XOl8FWKOgwtzdb8lXGf6zYwDUzeHMWfxasyg==",+ "license": "MIT",+ "bin": {+ "json5": "lib/cli.js"+ },+ "engines": {+ "node": ">=6"+ }+ },+ "node_modules/kiwi-schema": {+ "version": "0.5.0",+ "resolved": "https://registry.npmjs.org/kiwi-schema/-/kiwi-schema-0.5.0.tgz",+ "integrity": "sha512-X+FpfU0yTEtc6aTHS7VwbOpvQwRt70+pXXWRI5fd6CvWhe7pSVC854TVo4Zo0x5/wwcWj+/9KUlXpdcP0dY9AA==",+ "license": "MIT",+ "bin": {+ "kiwic": "cli.js"+ }+ },+ "node_modules/kleur": {+ "version": "3.0.3",+ "resolved": "https://registry.npmjs.org/kleur/-/kleur-3.0.3.tgz",+ "integrity": "sha512-eTIzlVOSUR+JxdDFepEYcBMtZ9Qqdef+rnzWdRZuMbOywu5tO2w2N7rqjoANZ5k9vywhL6Br1VRjUIgTQx4E8w==",+ "license": "MIT",+ "engines": {+ "node": ">=6"+ }+ },+ "node_modules/lines-and-columns": {+ "version": "1.2.4",+ "resolved": "https://registry.npmjs.org/lines-and-columns/-/lines-and-columns-1.2.4.tgz",+ "integrity": "sha512-7ylylesZQ/PV29jhEDl3Ufjo6ZX7gCqJr5F7PKrqc93v7fzSymt1BpwEU8nAUXs8qzzvqhbjhK5QZg6Mt/HkBg==",+ "license": "MIT"+ },+ "node_modules/loader-runner": {+ "version": "4.3.2",+ "resolved": "https://registry.npmjs.org/loader-runner/-/loader-runner-4.3.2.tgz",+ "integrity": "sha512-DFEqQ3ihfS9blba08cLfYf1NRAIEm+dDjic073DRDc3/JspI/8wYmtDsHwd3+4hwvdxSK7PGaElfTmm0awWJ4w==",+ "license": "MIT",+ "engines": {+ "node": ">=6.11.5"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/webpack"+ }+ },+ "node_modules/lower-case": {+ "version": "2.0.2",+ "resolved": "https://registry.npmjs.org/lower-case/-/lower-case-2.0.2.tgz",+ "integrity": "sha512-7fm3l3NAF9WfN6W3JOmf5drwpVqX78JtoGJ3A6W0a6ZnldM41w2fV5D490psKFTpMds8TJse/eHLFFsNHHjHgg==",+ "license": "MIT",+ "dependencies": {+ "tslib": "^2.0.3"+ }+ },+ "node_modules/lru-cache": {+ "version": "5.1.1",+ "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-5.1.1.tgz",+ "integrity": "sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w==",+ "license": "ISC",+ "dependencies": {+ "yallist": "^3.0.2"+ }+ },+ "node_modules/mdn-data": {+ "version": "2.27.1",+ "resolved": "https://registry.npmjs.org/mdn-data/-/mdn-data-2.27.1.tgz",+ "integrity": "sha512-9Yubnt3e8A0OKwxYSXyhLymGW4sCufcLG6VdiDdUGVkPhpqLxlvP5vl1983gQjJl3tqbrM731mjaZaP68AgosQ==",+ "license": "CC0-1.0"+ },+ "node_modules/mediabunny": {+ "version": "1.64.0",+ "resolved": "https://registry.npmjs.org/mediabunny/-/mediabunny-1.64.0.tgz",+ "integrity": "sha512-ILat5qSwfmZjnYhk7Dc8uEvEQNtzXNxUVyfxR9Fp6JRa8Axsg5xE1EXwCTOzXJHhH/a2eyk6sZ1ffivCk4rIXg==",+ "license": "MPL-2.0",+ "workspaces": [+ ".",+ "packages/*"+ ],+ "dependencies": {+ "@types/dom-mediacapture-transform": "^0.1.11",+ "@types/dom-webcodecs": "0.1.13"+ },+ "funding": {+ "type": "individual",+ "url": "https://github.com/sponsors/Vanilagy"+ }+ },+ "node_modules/memfs": {+ "version": "3.4.3",+ "resolved": "https://registry.npmjs.org/memfs/-/memfs-3.4.3.tgz",+ "integrity": "sha512-eivjfi7Ahr6eQTn44nvTnR60e4a1Fs1Via2kCR5lHo/kyNoiMWaXCNJ/GpSd0ilXas2JSOl9B5FTIhflXu0hlg==",+ "license": "Unlicense",+ "dependencies": {+ "fs-monkey": "1.0.3"+ },+ "engines": {+ "node": ">= 4.0.0"+ }+ },+ "node_modules/merge-stream": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/merge-stream/-/merge-stream-2.0.0.tgz",+ "integrity": "sha512-abv/qOcuPfk3URPfDzmZU1LKmuw8kT+0nIHvKrKgFrwifol/doWcdA4ZqsWQ8ENrFKkd67Mfpo/LovbIUsbt3w==",+ "license": "MIT"+ },+ "node_modules/mime-db": {+ "version": "1.52.0",+ "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz",+ "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.6"+ }+ },+ "node_modules/mime-types": {+ "version": "2.1.35",+ "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz",+ "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==",+ "license": "MIT",+ "dependencies": {+ "mime-db": "1.52.0"+ },+ "engines": {+ "node": ">= 0.6"+ }+ },+ "node_modules/mimic-fn": {+ "version": "2.1.0",+ "resolved": "https://registry.npmjs.org/mimic-fn/-/mimic-fn-2.1.0.tgz",+ "integrity": "sha512-OqbOk5oEQeAZ8WXWydlu9HJjz9WVdEIvamMCcXmuqUYjTknH/sqsWvhQ3vgwKFRR1HpjvNBKQ37nbJgYzGqGcg==",+ "license": "MIT",+ "engines": {+ "node": ">=6"+ }+ },+ "node_modules/minimist": {+ "version": "1.2.6",+ "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.6.tgz",+ "integrity": "sha512-Jsjnk4bw3YJqYzbdyBiNsPWHPfO++UGG749Cxs6peCu5Xg4nrena6OVxOYxrQTqww0Jmwt+Ref8rggumkTLz9Q==",+ "license": "MIT"+ },+ "node_modules/mitt": {+ "version": "3.0.1",+ "resolved": "https://registry.npmjs.org/mitt/-/mitt-3.0.1.tgz",+ "integrity": "sha512-vKivATfr97l2/QBCYAkXYDbrIWPM2IIKEl7YPhjCvKlG3kE2gm+uBo6nEXK3M5/Ffh/FLpKExzOQ3JJoJGFKBw==",+ "license": "MIT"+ },+ "node_modules/modern-tar": {+ "version": "0.8.6",+ "resolved": "https://registry.npmjs.org/modern-tar/-/modern-tar-0.8.6.tgz",+ "integrity": "sha512-LYSks0tNVqbtez/9OB0YFP6qLRSqkdAxJWOQpVaR67lNTbj2zNLyYpowkRMia5lXLCZKzxwoxkxH2MbbBR2aEg==",+ "license": "MIT",+ "engines": {+ "node": ">=18.0.0"+ }+ },+ "node_modules/ms": {+ "version": "2.1.3",+ "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",+ "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",+ "license": "MIT"+ },+ "node_modules/nanoid": {+ "version": "3.3.20",+ "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.20.tgz",+ "integrity": "sha512-uKdg2G3GNCKQn9byYOpxbGqrT2fGO5KRt5J/8b3pok8rT6qxGWF6hxMyJiEYtAf+FVyYuD9hRaDqX5uPFYJ4ZQ==",+ "funding": [+ {+ "type": "github",+ "url": "https://github.com/sponsors/ai"+ }+ ],+ "license": "MIT",+ "bin": {+ "nanoid": "bin/nanoid.cjs"+ },+ "engines": {+ "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1"+ }+ },+ "node_modules/neo-async": {+ "version": "2.6.2",+ "resolved": "https://registry.npmjs.org/neo-async/-/neo-async-2.6.2.tgz",+ "integrity": "sha512-Yd3UES5mWCSqR+qNT93S3UoYUkqAZ9lLg8a7g9rimsWmYGK8cVToA4/sF3RrshdyV3sAGMXVUmpMYOw+dLpOuw==",+ "license": "MIT"+ },+ "node_modules/no-case": {+ "version": "3.0.4",+ "resolved": "https://registry.npmjs.org/no-case/-/no-case-3.0.4.tgz",+ "integrity": "sha512-fgAN3jGAh+RoxUGZHTSOLJIqUc2wmoBwGR4tbpNAKmmovFoWq0OdRkb0VkldReO2a2iBT/OEulG9XSUc10r3zg==",+ "license": "MIT",+ "dependencies": {+ "lower-case": "^2.0.2",+ "tslib": "^2.0.3"+ }+ },+ "node_modules/node-releases": {+ "version": "2.0.64",+ "resolved": "https://registry.npmjs.org/node-releases/-/node-releases-2.0.64.tgz",+ "integrity": "sha512-zAPCKqMcnqs2nGy6nlkm7JduFseiBJy3EXHGLh+8pFR+TxGCBxxiEN21+UROU5CKwX/f4TlUcYjiM+vs/tsyxw==",+ "license": "MIT",+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/npm-run-path": {+ "version": "4.0.1",+ "resolved": "https://registry.npmjs.org/npm-run-path/-/npm-run-path-4.0.1.tgz",+ "integrity": "sha512-S48WzZW777zhNIrn7gxOlISNAqi9ZC/uQFnRdbeIHhZhCA6UqpkOT8T1G7BvfdgP4Er8gF4sUbaS0i7QvIfCWw==",+ "license": "MIT",+ "dependencies": {+ "path-key": "^3.0.0"+ },+ "engines": {+ "node": ">=8"+ }+ },+ "node_modules/onetime": {+ "version": "5.1.2",+ "resolved": "https://registry.npmjs.org/onetime/-/onetime-5.1.2.tgz",+ "integrity": "sha512-kbpaSSGJTWdAY5KPVeMOKXSrPtr8C8C7wodJbcsd51jRnmD+GZu8Y0VoU6Dm5Z4vWr0Ig/1NKuWRKf7j5aaYSg==",+ "license": "MIT",+ "dependencies": {+ "mimic-fn": "^2.1.0"+ },+ "engines": {+ "node": ">=6"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/open": {+ "version": "8.4.2",+ "resolved": "https://registry.npmjs.org/open/-/open-8.4.2.tgz",+ "integrity": "sha512-7x81NCL719oNbsq/3mh+hVrAWmFuEYUqrq/Iw3kUzH8ReypT9QQ0BLoJS7/G9k6N81XjW4qHWtjWwe/9eLy1EQ==",+ "license": "MIT",+ "dependencies": {+ "define-lazy-prop": "^2.0.0",+ "is-docker": "^2.1.1",+ "is-wsl": "^2.2.0"+ },+ "engines": {+ "node": ">=12"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/pako": {+ "version": "0.2.9",+ "resolved": "https://registry.npmjs.org/pako/-/pako-0.2.9.tgz",+ "integrity": "sha512-NUcwaKxUxWrZLpDG+z/xZaCgQITkA/Dv4V/T6bw7VON6l1Xz/VnrBqrYjZQ12TamKHzITTfOEIYUj48y2KXImA==",+ "license": "MIT"+ },+ "node_modules/parent-module": {+ "version": "1.0.1",+ "resolved": "https://registry.npmjs.org/parent-module/-/parent-module-1.0.1.tgz",+ "integrity": "sha512-GQ2EWRpQV8/o+Aw8YqtfZZPfNRWZYkbidE9k5rpl/hC3vtHHBfGm2Ifi6qWV+coDGkrUKZAxE3Lot5kcsRlh+g==",+ "license": "MIT",+ "dependencies": {+ "callsites": "^3.0.0"+ },+ "engines": {+ "node": ">=6"+ }+ },+ "node_modules/parse-json": {+ "version": "5.2.0",+ "resolved": "https://registry.npmjs.org/parse-json/-/parse-json-5.2.0.tgz",+ "integrity": "sha512-ayCKvm/phCGxOkYRSCM82iDwct8/EonSEgCSxWxD7ve6jHggsFl4fZVQBPRNgQoKiuV/odhFrGzQXZwbifC8Rg==",+ "license": "MIT",+ "dependencies": {+ "@babel/code-frame": "^7.0.0",+ "error-ex": "^1.3.1",+ "json-parse-even-better-errors": "^2.3.0",+ "lines-and-columns": "^1.1.6"+ },+ "engines": {+ "node": ">=8"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/path-key": {+ "version": "3.1.1",+ "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz",+ "integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==",+ "license": "MIT",+ "engines": {+ "node": ">=8"+ }+ },+ "node_modules/path-type": {+ "version": "4.0.0",+ "resolved": "https://registry.npmjs.org/path-type/-/path-type-4.0.0.tgz",+ "integrity": "sha512-gDKb8aZMDeD/tZWs9P6+q0J9Mwkdl6xMV8TjnGP3qJVJ06bdMgkbBlLU8IdfOsIsFz2BW1rNVT3XuNEl8zPAvw==",+ "license": "MIT",+ "engines": {+ "node": ">=8"+ }+ },+ "node_modules/pend": {+ "version": "1.2.0",+ "resolved": "https://registry.npmjs.org/pend/-/pend-1.2.0.tgz",+ "integrity": "sha512-F3asv42UuXchdzt+xXqfW1OGlVBe+mxa2mqI0pg5yAHZPvFmY3Y6drSf/GQ1A86WgWEN9Kzh/WrgKa6iGcHXLg==",+ "license": "MIT"+ },+ "node_modules/picocolors": {+ "version": "1.1.1",+ "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz",+ "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==",+ "license": "ISC"+ },+ "node_modules/postcss": {+ "version": "8.5.33",+ "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.33.tgz",+ "integrity": "sha512-RVHEU9/Pp1Fnjr/MpAJsZoADukCKhfIi15OunEYiGktIkYLkPVvC1sioWolGDS7XByMTx9m/IGbro0Js13zhnQ==",+ "funding": [+ {+ "type": "opencollective",+ "url": "https://opencollective.com/postcss/"+ },+ {+ "type": "tidelift",+ "url": "https://tidelift.com/funding/github/npm/postcss"+ },+ {+ "type": "github",+ "url": "https://github.com/sponsors/ai"+ }+ ],+ "license": "MIT",+ "dependencies": {+ "nanoid": "^3.3.20",+ "picocolors": "^1.1.1",+ "source-map-js": "^1.2.2"+ },+ "engines": {+ "node": "^10 || ^12 || >=14"+ }+ },+ "node_modules/postcss-modules-extract-imports": {+ "version": "3.1.0",+ "resolved": "https://registry.npmjs.org/postcss-modules-extract-imports/-/postcss-modules-extract-imports-3.1.0.tgz",+ "integrity": "sha512-k3kNe0aNFQDAZGbin48pL2VNidTF0w4/eASDsxlyspobzU3wZQLOGj7L9gfRe0Jo9/4uud09DsjFNH7winGv8Q==",+ "license": "ISC",+ "engines": {+ "node": "^10 || ^12 || >= 14"+ },+ "peerDependencies": {+ "postcss": "^8.1.0"+ }+ },+ "node_modules/postcss-modules-local-by-default": {+ "version": "4.2.0",+ "resolved": "https://registry.npmjs.org/postcss-modules-local-by-default/-/postcss-modules-local-by-default-4.2.0.tgz",+ "integrity": "sha512-5kcJm/zk+GJDSfw+V/42fJ5fhjL5YbFDl8nVdXkJPLLW+Vf9mTD5Xe0wqIaDnLuL2U6cDNpTr+UQ+v2HWIBhzw==",+ "license": "MIT",+ "dependencies": {+ "icss-utils": "^5.0.0",+ "postcss-selector-parser": "^7.0.0",+ "postcss-value-parser": "^4.1.0"+ },+ "engines": {+ "node": "^10 || ^12 || >= 14"+ },+ "peerDependencies": {+ "postcss": "^8.1.0"+ }+ },+ "node_modules/postcss-modules-scope": {+ "version": "3.2.1",+ "resolved": "https://registry.npmjs.org/postcss-modules-scope/-/postcss-modules-scope-3.2.1.tgz",+ "integrity": "sha512-m9jZstCVaqGjTAuny8MdgE88scJnCiQSlSrOWcTQgM2t32UBe+MUmFSO5t7VMSfAf/FJKImAxBav8ooCHJXCJA==",+ "license": "ISC",+ "dependencies": {+ "postcss-selector-parser": "^7.0.0"+ },+ "engines": {+ "node": "^10 || ^12 || >= 14"+ },+ "peerDependencies": {+ "postcss": "^8.1.0"+ }+ },+ "node_modules/postcss-modules-values": {+ "version": "4.0.0",+ "resolved": "https://registry.npmjs.org/postcss-modules-values/-/postcss-modules-values-4.0.0.tgz",+ "integrity": "sha512-RDxHkAiEGI78gS2ofyvCsu7iycRv7oqw5xMWn9iMoR0N/7mf9D50ecQqUo5BZ9Zh2vH4bCUR/ktCqbB9m8vJjQ==",+ "license": "ISC",+ "dependencies": {+ "icss-utils": "^5.0.0"+ },+ "engines": {+ "node": "^10 || ^12 || >= 14"+ },+ "peerDependencies": {+ "postcss": "^8.1.0"+ }+ },+ "node_modules/postcss-selector-parser": {+ "version": "7.2.1",+ "resolved": "https://registry.npmjs.org/postcss-selector-parser/-/postcss-selector-parser-7.2.1.tgz",+ "integrity": "sha512-GwxlMgTTXwIom+ebC7an3k6RaJDwklRQQnfiXsLPGicu8FYV/k/+1/9YY2OU2+r938H2t4X0TDxoif+HP2rjzQ==",+ "license": "MIT",+ "dependencies": {+ "util-deprecate": "^1.0.2"+ },+ "engines": {+ "node": ">=4"+ }+ },+ "node_modules/postcss-value-parser": {+ "version": "4.2.0",+ "resolved": "https://registry.npmjs.org/postcss-value-parser/-/postcss-value-parser-4.2.0.tgz",+ "integrity": "sha512-1NNCs6uurfkVbeXG4S8JFT9t19m45ICnif8zWLd5oPSZ50QnwMfK+H3jv408d4jw/7Bttv5axS5IiHoLaVNHeQ==",+ "license": "MIT"+ },+ "node_modules/prismjs": {+ "version": "1.30.0",+ "resolved": "https://registry.npmjs.org/prismjs/-/prismjs-1.30.0.tgz",+ "integrity": "sha512-DEvV2ZF2r2/63V+tK8hQvrR2ZGn10srHbXviTlcv7Kpzw8jWiNTqbVgjO3IY8RxrrOUF8VPMQQFysYYYv0YZxw==",+ "license": "MIT",+ "engines": {+ "node": ">=6"+ }+ },+ "node_modules/prompts": {+ "version": "2.4.2",+ "resolved": "https://registry.npmjs.org/prompts/-/prompts-2.4.2.tgz",+ "integrity": "sha512-NxNv/kLguCA7p3jE8oL2aEBsrJWgAakBpgmgK6lpPWV+WuOmY6r2/zbAVnP+T8bQlA0nzHXSJSJW0Hq7ylaD2Q==",+ "license": "MIT",+ "dependencies": {+ "kleur": "^3.0.3",+ "sisteransi": "^1.0.5"+ },+ "engines": {+ "node": ">= 6"+ }+ },+ "node_modules/puppeteer-core": {+ "version": "25.17.0",+ "resolved": "https://registry.npmjs.org/puppeteer-core/-/puppeteer-core-25.17.0.tgz",+ "integrity": "sha512-YAgBitkd+K9gxRt+wzBAFTTkGjkC8aC2o4OxofsU8JUy2nnK/RflTCJ9bRCvCMNbq9TPhqFk4Phz98otN9FrGg==",+ "license": "Apache-2.0",+ "dependencies": {+ "@puppeteer/browsers": "3.2.7",+ "chromium-bidi": "157.0.8090-0",+ "devtools-protocol": "0.0.1717327",+ "typed-query-selector": "^2.12.3",+ "webdriver-bidi-protocol": "1.0.2",+ "ws": "^8.22.1"+ },+ "engines": {+ "node": ">=22.12.0"+ }+ },+ "node_modules/puppeteer-core/node_modules/ws": {+ "version": "8.23.0",+ "resolved": "https://registry.npmjs.org/ws/-/ws-8.23.0.tgz",+ "integrity": "sha512-wCkmX8QMOrKjgO8HW2WyDbTSGeqkocxgDzS9iR79rEAexty6/2qzilx3Ag8Tqf9ykop3irLKle0MtVn5qjVnoQ==",+ "license": "MIT",+ "engines": {+ "node": ">=10.0.0"+ },+ "peerDependencies": {+ "bufferutil": "^4.0.1",+ "utf-8-validate": ">=5.0.2"+ },+ "peerDependenciesMeta": {+ "bufferutil": {+ "optional": true+ },+ "utf-8-validate": {+ "optional": true+ }+ }+ },+ "node_modules/react": {+ "version": "19.2.0",+ "resolved": "https://registry.npmjs.org/react/-/react-19.2.0.tgz",+ "integrity": "sha512-tmbWg6W31tQLeB5cdIBOicJDJRR2KzXsV7uSK9iNfLWQ5bIZfxuPEHp7M8wiHyHnn0DD1i7w3Zmin0FtkrwoCQ==",+ "license": "MIT",+ "engines": {+ "node": ">=0.10.0"+ }+ },+ "node_modules/react-dom": {+ "version": "19.2.0",+ "resolved": "https://registry.npmjs.org/react-dom/-/react-dom-19.2.0.tgz",+ "integrity": "sha512-UlbRu4cAiGaIewkPyiRGJk0imDN2T3JjieT6spoL2UeSf5od4n5LB/mQ4ejmxhCFT1tYe8IvaFulzynWovsEFQ==",+ "license": "MIT",+ "dependencies": {+ "scheduler": "^0.27.0"+ },+ "peerDependencies": {+ "react": "^19.2.0"+ }+ },+ "node_modules/react-refresh": {+ "version": "0.18.0",+ "resolved": "https://registry.npmjs.org/react-refresh/-/react-refresh-0.18.0.tgz",+ "integrity": "sha512-QgT5//D3jfjJb6Gsjxv0Slpj23ip+HtOpnNgnb2S5zU3CB26G/IDPGoy4RJB42wzFE46DRsstbW6tKHoKbhAxw==",+ "license": "MIT",+ "engines": {+ "node": ">=0.10.0"+ }+ },+ "node_modules/recast": {+ "version": "0.23.21",+ "resolved": "https://registry.npmjs.org/recast/-/recast-0.23.21.tgz",+ "integrity": "sha512-mFAyJq9vUbSTARLZUvAEf1z3YxlvAwswbmxMx2mPA/MSm4KmpwvwvhsH/NIrZhyOuwD60Lzyw2qh83uCbgTPYw==",+ "license": "MIT",+ "dependencies": {+ "ast-types": "^0.16.1",+ "esprima": "~4.0.0",+ "source-map": "~0.6.1",+ "tiny-invariant": "^1.3.3",+ "tslib": "^2.0.1"+ },+ "engines": {+ "node": ">= 4"+ }+ },+ "node_modules/recast/node_modules/source-map": {+ "version": "0.6.1",+ "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz",+ "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==",+ "license": "BSD-3-Clause",+ "engines": {+ "node": ">=0.10.0"+ }+ },+ "node_modules/remotion": {+ "version": "4.0.543",+ "resolved": "https://registry.npmjs.org/remotion/-/remotion-4.0.543.tgz",+ "integrity": "sha512-p3PS2+ZsaFBp1KiyiTsMDyLM9x7csvkCaFQN3DLSwuye+BFht+eLT7hvp2R3rvhQ7pa0SHPZwcYdOEKS1XbqIA==",+ "license": "SEE LICENSE IN LICENSE.md",+ "peerDependencies": {+ "react": ">=16.8.0",+ "react-dom": ">=16.8.0"+ }+ },+ "node_modules/require-from-string": {+ "version": "2.0.2",+ "resolved": "https://registry.npmjs.org/require-from-string/-/require-from-string-2.0.2.tgz",+ "integrity": "sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==",+ "license": "MIT",+ "engines": {+ "node": ">=0.10.0"+ }+ },+ "node_modules/resolve-from": {+ "version": "4.0.0",+ "resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-4.0.0.tgz",+ "integrity": "sha512-pb/MYmXstAkysRFx8piNI1tGFNQIFA3vkE3Gq4EuA1dF6gHp/+vgZqsCGJapvy8N3Q+4o7FwvquPJcnZ7RYy4g==",+ "license": "MIT",+ "engines": {+ "node": ">=4"+ }+ },+ "node_modules/restructure": {+ "version": "3.0.2",+ "resolved": "https://registry.npmjs.org/restructure/-/restructure-3.0.2.tgz",+ "integrity": "sha512-gSfoiOEA0VPE6Tukkrr7I0RBdE0s7H1eFCDBk05l1KIQT1UIKNc5JZy6jdyW6eYH3aR3g5b3PuL77rq0hvwtAw==",+ "license": "MIT"+ },+ "node_modules/run-applescript": {+ "version": "7.1.0",+ "resolved": "https://registry.npmjs.org/run-applescript/-/run-applescript-7.1.0.tgz",+ "integrity": "sha512-DPe5pVFaAsinSaV6QjQ6gdiedWDcRCbUuiQfQa2wmWV7+xC9bGulGI8+TdRmoFkAPaBXk8CrAbnlY2ISniJ47Q==",+ "license": "MIT",+ "engines": {+ "node": ">=18"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/scheduler": {+ "version": "0.27.0",+ "resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.27.0.tgz",+ "integrity": "sha512-eNv+WrVbKu1f3vbYJT/xtiF5syA5HPIMtf9IgY/nKg0sWqzAUEvqY/xm7OcZc/qafLx/iO9FgOmeSAp4v5ti/Q==",+ "license": "MIT"+ },+ "node_modules/schema-utils": {+ "version": "4.8.3",+ "resolved": "https://registry.npmjs.org/schema-utils/-/schema-utils-4.8.3.tgz",+ "integrity": "sha512-qIfo3f+lRNqnMPgpXSKvUhsT3pY5U+ppmgGr4j8LanFP3W/Ze+xj8DY/dPb5qVu3m6qFIMyMWKVRLNKxrNhxWg==",+ "license": "MIT",+ "dependencies": {+ "@types/json-schema": "^7.0.15",+ "ajv": "^8.20.0",+ "ajv-formats": "^3.0.1",+ "ajv-keywords": "^5.1.0"+ },+ "bin": {+ "schema-utils": "bin/schema-utils.js"+ },+ "engines": {+ "node": ">= 10.13.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/webpack"+ },+ "peerDependencies": {+ "webpack": "^5.0.0"+ },+ "peerDependenciesMeta": {+ "webpack": {+ "optional": true+ }+ }+ },+ "node_modules/semver": {+ "version": "7.5.3",+ "resolved": "https://registry.npmjs.org/semver/-/semver-7.5.3.tgz",+ "integrity": "sha512-QBlUtyVk/5EeHbi7X0fw6liDZc7BBmEaSYn01fMU1OUYbf6GPsbTtd8WmnqbI20SeycoHSeiybkE/q1Q+qlThQ==",+ "license": "ISC",+ "dependencies": {+ "lru-cache": "^6.0.0"+ },+ "bin": {+ "semver": "bin/semver.js"+ },+ "engines": {+ "node": ">=10"+ }+ },+ "node_modules/semver/node_modules/lru-cache": {+ "version": "6.0.0",+ "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-6.0.0.tgz",+ "integrity": "sha512-Jo6dJ04CmSjuznwJSS3pUeWmd/H0ffTlkXXgwZi+eq1UCmqQwCh+eLsYOYCwY991i2Fah4h1BEMCx4qThGbsiA==",+ "license": "ISC",+ "dependencies": {+ "yallist": "^4.0.0"+ },+ "engines": {+ "node": ">=10"+ }+ },+ "node_modules/semver/node_modules/yallist": {+ "version": "4.0.0",+ "resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz",+ "integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==",+ "license": "ISC"+ },+ "node_modules/sharp": {+ "version": "0.35.5",+ "resolved": "https://registry.npmjs.org/sharp/-/sharp-0.35.5.tgz",+ "integrity": "sha512-Ywn4OnzGukp7CDMrp08RQ50YKmuwG47brZgIVPTvBaaAfQlRlygrRqSrxdCiL9M+LlzLBiJ68IR1QqvzHyjC7g==",+ "license": "Apache-2.0",+ "optional": true,+ "dependencies": {+ "@img/colour": "^1.1.0",+ "detect-libc": "^2.1.2",+ "semver": "^7.8.5"+ },+ "engines": {+ "node": ">=20.9.0"+ },+ "funding": {+ "url": "https://opencollective.com/libvips"+ },+ "optionalDependencies": {+ "@img/sharp-darwin-arm64": "0.35.5",+ "@img/sharp-darwin-x64": "0.35.5",+ "@img/sharp-freebsd-wasm32": "0.35.5",+ "@img/sharp-libvips-darwin-arm64": "1.3.4",+ "@img/sharp-libvips-darwin-x64": "1.3.4",+ "@img/sharp-libvips-linux-arm": "1.3.4",+ "@img/sharp-libvips-linux-arm64": "1.3.4",+ "@img/sharp-libvips-linux-ppc64": "1.3.4",+ "@img/sharp-libvips-linux-riscv64": "1.3.4",+ "@img/sharp-libvips-linux-s390x": "1.3.4",+ "@img/sharp-libvips-linux-x64": "1.3.4",+ "@img/sharp-libvips-linuxmusl-arm64": "1.3.4",+ "@img/sharp-libvips-linuxmusl-x64": "1.3.4",+ "@img/sharp-linux-arm": "0.35.5",+ "@img/sharp-linux-arm64": "0.35.5",+ "@img/sharp-linux-ppc64": "0.35.5",+ "@img/sharp-linux-riscv64": "0.35.5",+ "@img/sharp-linux-s390x": "0.35.5",+ "@img/sharp-linux-x64": "0.35.5",+ "@img/sharp-linuxmusl-arm64": "0.35.5",+ "@img/sharp-linuxmusl-x64": "0.35.5",+ "@img/sharp-webcontainers-wasm32": "0.35.5",+ "@img/sharp-win32-arm64": "0.35.5",+ "@img/sharp-win32-ia32": "0.35.5",+ "@img/sharp-win32-x64": "0.35.5"+ },+ "peerDependenciesMeta": {+ "@types/node": {+ "optional": true+ }+ }+ },+ "node_modules/sharp/node_modules/semver": {+ "version": "7.8.6",+ "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.6.tgz",+ "integrity": "sha512-9lpSSU4Mly3mrtruwLs1eLK6+gzbzqeBFwRNjIjE+9LuDpWdYctrQlQ3ej1Ilgi7gknpsTRnPoLP8DpCHqHIJw==",+ "license": "ISC",+ "optional": true,+ "bin": {+ "semver": "bin/semver.js"+ },+ "engines": {+ "node": ">=10"+ }+ },+ "node_modules/shebang-command": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz",+ "integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==",+ "license": "MIT",+ "dependencies": {+ "shebang-regex": "^3.0.0"+ },+ "engines": {+ "node": ">=8"+ }+ },+ "node_modules/shebang-regex": {+ "version": "3.0.0",+ "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz",+ "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==",+ "license": "MIT",+ "engines": {+ "node": ">=8"+ }+ },+ "node_modules/signal-exit": {+ "version": "3.0.7",+ "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.7.tgz",+ "integrity": "sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ==",+ "license": "ISC"+ },+ "node_modules/sisteransi": {+ "version": "1.0.5",+ "resolved": "https://registry.npmjs.org/sisteransi/-/sisteransi-1.0.5.tgz",+ "integrity": "sha512-bLGGlR1QxBcynn2d5YmDX4MGjlZvy2MRBDRNHLJ8VI6l6+9FUiyTFNJ0IveOSP0bcXgVDPRcfGqA0pjaqUpfVg==",+ "license": "MIT"+ },+ "node_modules/snake-case": {+ "version": "3.0.4",+ "resolved": "https://registry.npmjs.org/snake-case/-/snake-case-3.0.4.tgz",+ "integrity": "sha512-LAOh4z89bGQvl9pFfNF8V146i7o7/CqFPbqzYgP+yYzDIDeS9HaNFtXABamRW+AQzEVODcvE79ljJ+8a9YSdMg==",+ "license": "MIT",+ "dependencies": {+ "dot-case": "^3.0.4",+ "tslib": "^2.0.3"+ }+ },+ "node_modules/source-map": {+ "version": "0.8.0",+ "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.8.0.tgz",+ "integrity": "sha512-d8EqvL+k/SOXCreS/SUzg2ciyHqBBLcN/yuRjFsbvVhHTE2pgei7oAhmPM7kWFbkX6OSMQfUq4KbkF3au9lhYQ==",+ "license": "BSD-3-Clause",+ "engines": {+ "node": ">= 12"+ }+ },+ "node_modules/source-map-js": {+ "version": "1.2.2",+ "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.2.tgz",+ "integrity": "sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw==",+ "license": "BSD-3-Clause",+ "engines": {+ "node": ">=0.10.0"+ }+ },+ "node_modules/source-map-support": {+ "version": "0.5.21",+ "resolved": "https://registry.npmjs.org/source-map-support/-/source-map-support-0.5.21.tgz",+ "integrity": "sha512-uBHU3L3czsIyYXKX88fdrGovxdSCoTGDRZ6SYXtSRxLZUzHg5P/66Ht6uoUlHu9EZod+inXhKo3qQgwXUT/y1w==",+ "license": "MIT",+ "dependencies": {+ "buffer-from": "^1.0.0",+ "source-map": "^0.6.0"+ }+ },+ "node_modules/source-map-support/node_modules/source-map": {+ "version": "0.6.1",+ "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz",+ "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==",+ "license": "BSD-3-Clause",+ "engines": {+ "node": ">=0.10.0"+ }+ },+ "node_modules/string-width": {+ "version": "8.3.0",+ "resolved": "https://registry.npmjs.org/string-width/-/string-width-8.3.0.tgz",+ "integrity": "sha512-ZbmZM0JCihQN91dWnxoipT2KOEyHqEyfRXUyjuRhW8b/xnqPDoq4gWEVApTVa9db2wN8mmoikgFBbjh71+cGeQ==",+ "license": "MIT",+ "dependencies": {+ "get-east-asian-width": "^1.5.0",+ "strip-ansi": "^7.1.2"+ },+ "engines": {+ "node": ">=20"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/strip-ansi": {+ "version": "7.2.0",+ "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-7.2.0.tgz",+ "integrity": "sha512-yDPMNjp4WyfYBkHnjIRLfca1i6KMyGCtsVgoKe/z1+6vukgaENdgGBZt+ZmKPc4gavvEZ5OgHfHdrazhgNyG7w==",+ "license": "MIT",+ "dependencies": {+ "ansi-regex": "^6.2.2"+ },+ "engines": {+ "node": ">=12"+ },+ "funding": {+ "url": "https://github.com/chalk/strip-ansi?sponsor=1"+ }+ },+ "node_modules/strip-final-newline": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/strip-final-newline/-/strip-final-newline-2.0.0.tgz",+ "integrity": "sha512-BrpvfNAE3dcvq7ll3xVumzjKjZQ5tI1sEUIKr3Uoks0XUl45St3FlatVqef9prk4jRDzhW6WZg+3bk93y6pLjA==",+ "license": "MIT",+ "engines": {+ "node": ">=6"+ }+ },+ "node_modules/style-loader": {+ "version": "4.0.0",+ "resolved": "https://registry.npmjs.org/style-loader/-/style-loader-4.0.0.tgz",+ "integrity": "sha512-1V4WqhhZZgjVAVJyt7TdDPZoPBPNHbekX4fWnCJL1yQukhCeZhJySUL+gL9y6sNdN95uEOS83Y55SqHcP7MzLA==",+ "license": "MIT",+ "engines": {+ "node": ">= 18.12.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/webpack"+ },+ "peerDependencies": {+ "webpack": "^5.27.0"+ }+ },+ "node_modules/supports-color": {+ "version": "8.1.1",+ "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-8.1.1.tgz",+ "integrity": "sha512-MpUEN2OodtUzxvKQl72cUF7RQ5EiHsGvSsVG0ia9c5RbWGL2CI4C7EpPS8UTBIplnlzZiNuV56w+FuNxy3ty2Q==",+ "license": "MIT",+ "dependencies": {+ "has-flag": "^4.0.0"+ },+ "engines": {+ "node": ">=10"+ },+ "funding": {+ "url": "https://github.com/chalk/supports-color?sponsor=1"+ }+ },+ "node_modules/svg-parser": {+ "version": "2.1.0",+ "resolved": "https://registry.npmjs.org/svg-parser/-/svg-parser-2.1.0.tgz",+ "integrity": "sha512-bwLf38YmY+TDYHJw1Ex0Co8c4yeXuJAo8YnXGZrscxrvYoVVIvLeniEkV1Ks/54VteMnL4FtyN1+P+TZJdUPmQ==",+ "license": "MIT",+ "engines": {+ "node": ">=8"+ }+ },+ "node_modules/tapable": {+ "version": "2.3.4",+ "resolved": "https://registry.npmjs.org/tapable/-/tapable-2.3.4.tgz",+ "integrity": "sha512-NHFiWnAbMJxNNpBwiO7jJVGDuqMxT9/oV8v57RR+fgBQShkJil5inGD8/xWy0hjLyHQyX1tu27QANhlz3KBqCg==",+ "license": "MIT",+ "engines": {+ "node": ">=6"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/webpack"+ }+ },+ "node_modules/terser": {+ "version": "5.51.2",+ "resolved": "https://registry.npmjs.org/terser/-/terser-5.51.2.tgz",+ "integrity": "sha512-bWnjSNscmuI+GJze6ZupnHP8G/cTcsJF+bXCeQknk2SHQsgbNJnLrqiH9jZ2W4STPVXH2mDKKRX3iwPhc9Cn/Q==",+ "license": "BSD-2-Clause",+ "dependencies": {+ "@jridgewell/source-map": "^0.3.3",+ "acorn": "^8.15.0",+ "commander": "^2.20.0",+ "source-map-support": "~0.5.20"+ },+ "bin": {+ "terser": "bin/terser"+ },+ "engines": {+ "node": ">=10"+ }+ },+ "node_modules/terser-webpack-plugin": {+ "version": "5.6.1",+ "resolved": "https://registry.npmjs.org/terser-webpack-plugin/-/terser-webpack-plugin-5.6.1.tgz",+ "integrity": "sha512-201R5j+sJpK8nFWwKVyNfZot8FaJbLZDq5evriVzbV1wDtSXDjRUDRfJzHpAaxFDMEhsZL1QkeqM61wgsS3KaQ==",+ "license": "MIT",+ "dependencies": {+ "@jridgewell/trace-mapping": "^0.3.25",+ "jest-worker": "^27.4.5",+ "schema-utils": "^4.3.0",+ "terser": "^5.31.1"+ },+ "engines": {+ "node": ">= 10.13.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/webpack"+ },+ "peerDependencies": {+ "webpack": "^5.1.0"+ },+ "peerDependenciesMeta": {+ "@minify-html/node": {+ "optional": true+ },+ "@swc/core": {+ "optional": true+ },+ "@swc/css": {+ "optional": true+ },+ "@swc/html": {+ "optional": true+ },+ "clean-css": {+ "optional": true+ },+ "cssnano": {+ "optional": true+ },+ "csso": {+ "optional": true+ },+ "esbuild": {+ "optional": true+ },+ "html-minifier-terser": {+ "optional": true+ },+ "lightningcss": {+ "optional": true+ },+ "postcss": {+ "optional": true+ },+ "uglify-js": {+ "optional": true+ }+ }+ },+ "node_modules/tiny-inflate": {+ "version": "1.0.3",+ "resolved": "https://registry.npmjs.org/tiny-inflate/-/tiny-inflate-1.0.3.tgz",+ "integrity": "sha512-pkY1fj1cKHb2seWDy0B16HeWyczlJA9/WW3u3c4z/NiWDsO3DOU5D7nhTLE9CF0yXv/QZFY7sEJmj24dK+Rrqw==",+ "license": "MIT"+ },+ "node_modules/tiny-invariant": {+ "version": "1.3.3",+ "resolved": "https://registry.npmjs.org/tiny-invariant/-/tiny-invariant-1.3.3.tgz",+ "integrity": "sha512-+FbBPE1o9QAYvviau/qC5SE3caw21q3xkvWKBtja5vgqOWIHHJ3ioaq1VPfn/Szqctz2bU/oYeKd9/z5BL+PVg==",+ "license": "MIT"+ },+ "node_modules/to-fast-properties": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/to-fast-properties/-/to-fast-properties-2.0.0.tgz",+ "integrity": "sha512-/OaKK0xYrs3DmxRYqL/yDc+FxFUVYhDlXMhRmv3z915w2HF1tnN1omB354j8VUGO/hbRzyD6Y3sA7v7GS/ceog==",+ "license": "MIT",+ "engines": {+ "node": ">=4"+ }+ },+ "node_modules/tslib": {+ "version": "2.9.1",+ "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.9.1.tgz",+ "integrity": "sha512-a4Ux9VKuIMHsOS7ENbEq6hK2ZGYIT27Rtl0E4eD9KqwxhKiQeMZE/9xb3IdYwWaSOyIBQLExhQgXDTYoiCxnWA==",+ "license": "0BSD"+ },+ "node_modules/typed-query-selector": {+ "version": "2.12.3",+ "resolved": "https://registry.npmjs.org/typed-query-selector/-/typed-query-selector-2.12.3.tgz",+ "integrity": "sha512-/dtuMZyutHLlrxWhhC1uib00ELUr2dZ8C9B8YzZYsJmeE3V56OxRblrSM2UaF142pcMtak7ehZ6+poWGeehNIg==",+ "license": "MIT"+ },+ "node_modules/undici": {+ "version": "7.30.1",+ "resolved": "https://registry.npmjs.org/undici/-/undici-7.30.1.tgz",+ "integrity": "sha512-03KrMbjIFDWQR5RNPrSw3bd1r12JpyFQl9/yxjUbJtqkjmllqC5lFjZh6ujeuJCKr8EOQvRW872Oy/az+nLYxg==",+ "license": "MIT",+ "engines": {+ "node": ">=20.18.1"+ }+ },+ "node_modules/undici-types": {+ "version": "8.9.0",+ "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-8.9.0.tgz",+ "integrity": "sha512-KTDyRTYX8sWmKXAikPHHSyc63CRPETMctyjKFupcC6OBLXT3xsN0e9aF7m+mIXutFWpUXuedtowG7iLOzp0kQg==",+ "license": "MIT"+ },+ "node_modules/unicode-properties": {+ "version": "1.4.1",+ "resolved": "https://registry.npmjs.org/unicode-properties/-/unicode-properties-1.4.1.tgz",+ "integrity": "sha512-CLjCCLQ6UuMxWnbIylkisbRj31qxHPAurvena/0iwSVbQ2G1VY5/HjV0IRabOEbDHlzZlRdCrD4NhB0JtU40Pg==",+ "license": "MIT",+ "dependencies": {+ "base64-js": "^1.3.0",+ "unicode-trie": "^2.0.0"+ }+ },+ "node_modules/unicode-trie": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/unicode-trie/-/unicode-trie-2.0.0.tgz",+ "integrity": "sha512-x7bc76x0bm4prf1VLg79uhAzKw8DVboClSN5VxJuQ+LKDOVEW9CdH+VY7SP+vX7xCYQqzzgQpFqz15zeLvAtZQ==",+ "license": "MIT",+ "dependencies": {+ "pako": "^0.2.5",+ "tiny-inflate": "^1.0.0"+ }+ },+ "node_modules/update-browserslist-db": {+ "version": "1.3.4",+ "resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.3.4.tgz",+ "integrity": "sha512-t8wonIOdQyOjtPd2VktlBu6QjTVTks6v8bSi7kd0r2Vll8TK1JYDZtRRdbmCHOAMphkZgrzK+L+vXK4pyZ8t4A==",+ "funding": [+ {+ "type": "opencollective",+ "url": "https://opencollective.com/browserslist"+ },+ {+ "type": "tidelift",+ "url": "https://tidelift.com/funding/github/npm/browserslist"+ },+ {+ "type": "github",+ "url": "https://github.com/sponsors/ai"+ }+ ],+ "license": "MIT",+ "dependencies": {+ "escalade": "^3.2.0",+ "picocolors": "^1.1.1"+ },+ "bin": {+ "update-browserslist-db": "cli.js"+ },+ "peerDependencies": {+ "browserslist": ">= 4.21.0"+ }+ },+ "node_modules/util-deprecate": {+ "version": "1.0.2",+ "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz",+ "integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==",+ "license": "MIT"+ },+ "node_modules/watchpack": {+ "version": "2.6.4",+ "resolved": "https://registry.npmjs.org/watchpack/-/watchpack-2.6.4.tgz",+ "integrity": "sha512-5H3Tce2GfzWbcr9VnSqyak2whFaONw4BdmI5BDnMXold4qSlCFd64XaMQESRh2vkDKmdUkv6rUo17UvZ9f9nXw==",+ "license": "MIT",+ "dependencies": {+ "graceful-fs": "^4.1.2"+ },+ "engines": {+ "node": ">=10.13.0"+ }+ },+ "node_modules/webdriver-bidi-protocol": {+ "version": "1.0.2",+ "resolved": "https://registry.npmjs.org/webdriver-bidi-protocol/-/webdriver-bidi-protocol-1.0.2.tgz",+ "integrity": "sha512-nghazPI+J5RrLZ+qb6vMjC6l1/tnwqr2muVEax4Ufd6eIdcjeqNnhLsAxTG9s+7Zf4umgf0DrEwDC8CoU91nAA==",+ "license": "Apache-2.0"+ },+ "node_modules/webpack": {+ "version": "5.105.0",+ "resolved": "https://registry.npmjs.org/webpack/-/webpack-5.105.0.tgz",+ "integrity": "sha512-gX/dMkRQc7QOMzgTe6KsYFM7DxeIONQSui1s0n/0xht36HvrgbxtM1xBlgx596NbpHuQU8P7QpKwrZYwUX48nw==",+ "license": "MIT",+ "dependencies": {+ "@types/eslint-scope": "^3.7.7",+ "@types/estree": "^1.0.8",+ "@types/json-schema": "^7.0.15",+ "@webassemblyjs/ast": "^1.14.1",+ "@webassemblyjs/wasm-edit": "^1.14.1",+ "@webassemblyjs/wasm-parser": "^1.14.1",+ "acorn": "^8.15.0",+ "acorn-import-phases": "^1.0.3",+ "browserslist": "^4.28.1",+ "chrome-trace-event": "^1.0.2",+ "enhanced-resolve": "^5.19.0",+ "es-module-lexer": "^2.0.0",+ "eslint-scope": "5.1.1",+ "events": "^3.2.0",+ "glob-to-regexp": "^0.4.1",+ "graceful-fs": "^4.2.11",+ "json-parse-even-better-errors": "^2.3.1",+ "loader-runner": "^4.3.1",+ "mime-types": "^2.1.27",+ "neo-async": "^2.6.2",+ "schema-utils": "^4.3.3",+ "tapable": "^2.3.0",+ "terser-webpack-plugin": "^5.3.16",+ "watchpack": "^2.5.1",+ "webpack-sources": "^3.3.3"+ },+ "bin": {+ "webpack": "bin/webpack.js"+ },+ "engines": {+ "node": ">=10.13.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/webpack"+ },+ "peerDependenciesMeta": {+ "webpack-cli": {+ "optional": true+ }+ }+ },+ "node_modules/webpack-sources": {+ "version": "3.7.0",+ "resolved": "https://registry.npmjs.org/webpack-sources/-/webpack-sources-3.7.0.tgz",+ "integrity": "sha512-PdUhbCycwEgiS1hB/FBDksWKg/ashAIuJKqwdbPn8/dFVgU5LxQiBvG0js6VRRIzPujMrStYCczywp82P0KWng==",+ "license": "MIT",+ "engines": {+ "node": ">=10.13.0"+ }+ },+ "node_modules/which": {+ "version": "2.0.2",+ "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz",+ "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==",+ "license": "ISC",+ "dependencies": {+ "isexe": "^2.0.0"+ },+ "bin": {+ "node-which": "bin/node-which"+ },+ "engines": {+ "node": ">= 8"+ }+ },+ "node_modules/wrap-ansi": {+ "version": "9.0.2",+ "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-9.0.2.tgz",+ "integrity": "sha512-42AtmgqjV+X1VpdOfyTGOYRi0/zsoLqtXQckTmqTeybT+BDIbM/Guxo7x3pE2vtpr1ok6xRqM9OpBe+Jyoqyww==",+ "license": "MIT",+ "dependencies": {+ "ansi-styles": "^6.2.1",+ "string-width": "^7.0.0",+ "strip-ansi": "^7.1.0"+ },+ "engines": {+ "node": ">=18"+ },+ "funding": {+ "url": "https://github.com/chalk/wrap-ansi?sponsor=1"+ }+ },+ "node_modules/wrap-ansi/node_modules/string-width": {+ "version": "7.2.0",+ "resolved": "https://registry.npmjs.org/string-width/-/string-width-7.2.0.tgz",+ "integrity": "sha512-tsaTIkKW9b4N+AEj+SVA+WhJzV7/zMhcSu78mLKWSk7cXMOSHsBKFWUs0fWwq8QyK3MgJBQRX6Gbi4kYbdvGkQ==",+ "license": "MIT",+ "dependencies": {+ "emoji-regex": "^10.3.0",+ "get-east-asian-width": "^1.0.0",+ "strip-ansi": "^7.1.0"+ },+ "engines": {+ "node": ">=18"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/ws": {+ "version": "8.21.0",+ "resolved": "https://registry.npmjs.org/ws/-/ws-8.21.0.tgz",+ "integrity": "sha512-Vsp28b7DRcimFQvrqu2Wek3z1iYxDCWqHYB8Qsnk/S4RfaCQzPGPyBNuVjJV3cd6UiKtUtp6sNM77gWvzcCH+g==",+ "license": "MIT",+ "engines": {+ "node": ">=10.0.0"+ },+ "peerDependencies": {+ "bufferutil": "^4.0.1",+ "utf-8-validate": ">=5.0.2"+ },+ "peerDependenciesMeta": {+ "bufferutil": {+ "optional": true+ },+ "utf-8-validate": {+ "optional": true+ }+ }+ },+ "node_modules/wsl-utils": {+ "version": "0.1.0",+ "resolved": "https://registry.npmjs.org/wsl-utils/-/wsl-utils-0.1.0.tgz",+ "integrity": "sha512-h3Fbisa2nKGPxCpm89Hk33lBLsnaGBvctQopaBSOW/uIs6FTe1ATyAnKFJrzVs9vpGdsTe73WF3V4lIsk4Gacw==",+ "license": "MIT",+ "dependencies": {+ "is-wsl": "^3.1.0"+ },+ "engines": {+ "node": ">=18"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/wsl-utils/node_modules/is-wsl": {+ "version": "3.1.1",+ "resolved": "https://registry.npmjs.org/is-wsl/-/is-wsl-3.1.1.tgz",+ "integrity": "sha512-e6rvdUCiQCAuumZslxRJWR/Doq4VpPR82kqclvcS0efgt430SlGIk05vdCN58+VrzgtIcfNODjozVielycD4Sw==",+ "license": "MIT",+ "dependencies": {+ "is-inside-container": "^1.0.0"+ },+ "engines": {+ "node": ">=16"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/y18n": {+ "version": "5.0.8",+ "resolved": "https://registry.npmjs.org/y18n/-/y18n-5.0.8.tgz",+ "integrity": "sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA==",+ "license": "ISC",+ "engines": {+ "node": ">=10"+ }+ },+ "node_modules/yallist": {+ "version": "3.1.1",+ "resolved": "https://registry.npmjs.org/yallist/-/yallist-3.1.1.tgz",+ "integrity": "sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g==",+ "license": "ISC"+ },+ "node_modules/yargs": {+ "version": "18.2.0",+ "resolved": "https://registry.npmjs.org/yargs/-/yargs-18.2.0.tgz",+ "integrity": "sha512-9OpKOLeaoNFecEp7P6iYbzze/5CqWoH7N3SMs/6y1XF4nMvFMspEGZzJ6uFi9MmQwXhyzqYoSEKO3tvA3Z/o2w==",+ "license": "MIT",+ "dependencies": {+ "cliui": "^9.0.1",+ "escalade": "^3.1.1",+ "get-caller-file": "^2.0.5",+ "string-width": "^8.2.1",+ "y18n": "^5.0.5",+ "yargs-parser": "^22.0.0"+ },+ "engines": {+ "node": "^20.19.0 || ^22.12.0 || >=23"+ }+ },+ "node_modules/yargs-parser": {+ "version": "22.0.0",+ "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-22.0.0.tgz",+ "integrity": "sha512-rwu/ClNdSMpkSrUb+d6BRsSkLUq1fmfsY6TOpYzTwvwkg1/NRG85KBy3kq++A8LKQwX6lsu+aWad+2khvuXrqw==",+ "license": "ISC",+ "engines": {+ "node": "^20.19.0 || ^22.12.0 || >=23"+ }+ },+ "node_modules/yauzl": {+ "version": "3.4.0",+ "resolved": "https://registry.npmjs.org/yauzl/-/yauzl-3.4.0.tgz",+ "integrity": "sha512-jIH9yLR9wqr0wOS0TpBvo/g/2UgZH5qePVbjgRliiF0BYvOZyaBknKsF+x9Iht0O6sqgnB93rCICdOZFecJuDw==",+ "license": "MIT",+ "dependencies": {+ "pend": "~1.2.0"+ },+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/zod": {+ "version": "4.6.7",+ "resolved": "https://registry.npmjs.org/zod/-/zod-4.6.7.tgz",+ "integrity": "sha512-g8W2D2kU6a8untc053fX1uVBKzM7yqAxW/3zwk83+6RyF2+SKOuV+c0wBDhUwzV1PaGapmZH+rmcUzPf+3CGwg==",+ "license": "MIT",+ "funding": {+ "url": "https://github.com/sponsors/colinhacks"+ }+ }+ }+}diff --git a/bench/package.json b/bench/package.jsonnew file mode 100644index 0000000..973a816--- /dev/null+++ b/bench/package.json@@ -0,0 +1,15 @@+{+ "name": "motlab-bench",+ "private": true,+ "description": "The same scene rendered by motlab, Remotion and HyperFrames. See README.md.",+ "dependencies": {+ "@remotion/bundler": "4.0.543",+ "@remotion/cli": "4.0.543",+ "@remotion/renderer": "4.0.543",+ "gsap": "3.15.0",+ "hyperframes": "0.9.52",+ "react": "19.2.0",+ "react-dom": "19.2.0",+ "remotion": "4.0.543"+ }+}diff --git a/bench/remotion/src/Root.jsx b/bench/remotion/src/Root.jsxnew file mode 100644index 0000000..c9da342--- /dev/null+++ b/bench/remotion/src/Root.jsx@@ -0,0 +1,24 @@+import React, { useLayoutEffect, useRef } from 'react';+import { AbsoluteFill, Composition, useCurrentFrame, useVideoConfig } from 'remotion';+import BENCH from '../../shared.js';++// The same scene as HTML elements, each moved from the frame's time.+const Dom = () => {+ const frame = useCurrentFrame(), { fps } = useVideoConfig(), ref = useRef(null), els = useRef(null);+ useLayoutEffect(() => { if (!els.current) els.current = BENCH.dom(ref.current); BENCH.applyDom(els.current, frame / fps); }, [frame, fps]);+ return <AbsoluteFill><div ref={ref} /></AbsoluteFill>;+};++// The same scene drawn on a canvas with the code motlab uses.+const Canvas = () => {+ const frame = useCurrentFrame(), { fps } = useVideoConfig(), ref = useRef(null);+ useLayoutEffect(() => { BENCH.drawCanvas(ref.current.getContext('2d'), frame / fps); }, [frame, fps]);+ return <canvas ref={ref} width={BENCH.W} height={BENCH.H} />;+};++export const Root = () => (+ <>+ <Composition id="Dom" component={Dom} durationInFrames={BENCH.TOTAL * 30} fps={30} width={BENCH.W} height={BENCH.H} />+ <Composition id="Canvas" component={Canvas} durationInFrames={BENCH.TOTAL * 30} fps={30} width={BENCH.W} height={BENCH.H} />+ </>+);diff --git a/bench/remotion/src/index.jsx b/bench/remotion/src/index.jsxnew file mode 100644index 0000000..4672e05--- /dev/null+++ b/bench/remotion/src/index.jsx@@ -0,0 +1,3 @@+import { registerRoot } from 'remotion';+import { Root } from './Root.jsx';+registerRoot(Root);diff --git a/bench/run.mjs b/bench/run.mjsnew file mode 100644index 0000000..64d291e--- /dev/null+++ b/bench/run.mjs@@ -0,0 +1,83 @@+// Renders the scene in shared.js with motlab, Remotion and HyperFrames, RUNS times per setting, one after another,+// and writes results.json: wall time of the whole command as a user sees it (Chrome start-up, Remotion's bundling,+// muxing), plus SSIM of 10 frames against lossless PNG stills of the canvas page. Run `npm ci` in this folder first.+// node run.mjs every setting, 3 runs each+// RUNS=1 ONLY=motlab-sw node run.mjs+// SCALE=2 node run.mjs at 4K (results-4k.json)+// CPU=1 node run.mjs Chrome drawing in software (SwiftShader) and CPU encoders only (results-cpu.json)+// IGPU=1 node run.mjs motlab only, on Chrome's default (integrated) GPU like the other two (results-igpu.json)+import { spawnSync } from 'node:child_process';+import { copyFileSync, existsSync, statSync, writeFileSync } from 'node:fs';+import { join } from 'node:path';+import { findChrome } from '../src/chrome.js';++const B = import.meta.dirname, OUT = join(B, 'out'), REF = join(B, 'ref'), RUNS = Number(process.env.RUNS || 3);+const SCALE = Number(process.env.SCALE || 1), CPU = process.env.CPU === '1', IGPU = process.env.IGPU === '1', SIZE = SCALE === 1 ? '' : `-${1080 * SCALE}p`;+const MODE = CPU ? '-cpu' : IGPU ? '-igpu' : '', TAG = MODE + SIZE, RESULTS = join(B, `results${MODE}${SCALE === 1 ? '' : '-4k'}.json`);+const MOTLAB = join(B, '..', 'bin', 'motlab.js'), MOTLAB_CPU = join(B, 'motlab-cpu.mjs'), MOTLAB_IGPU = join(B, 'motlab-igpu.mjs'), CHROME = findChrome(process.env.CHROME);+// Both other tools are pointed at the same Chrome as motlab, and their telemetry is off.+const env = { ...process.env, REMOTION_DISABLE_TELEMETRY: '1', HYPERFRAMES_NO_TELEMETRY: '1', DO_NOT_TRACK: '1', HYPERFRAMES_SKIP_SKILLS: '1', HYPERFRAMES_BROWSER_PATH: CHROME };+for (const d of ['dom', 'canvas']) { // HyperFrames serves the composition folder only+ copyFileSync(join(B, 'shared.js'), join(B, 'hyperframes', d, 'shared.js'));+ copyFileSync(join(B, 'node_modules', 'gsap', 'dist', 'gsap.min.js'), join(B, 'hyperframes', d, 'gsap.min.js'));+}++const motlab = (name, extra) => ({ name, cwd: join(B, 'motlab'), args: [CPU ? MOTLAB_CPU : IGPU ? MOTLAB_IGPU : MOTLAB, 'video', 'canvas.html', join(OUT, name + TAG + '.mp4'), '--fps', '30', '--scale', String(SCALE), '--chrome', CHROME, '--root', B, ...extra] });+const remotion = (name, comp, extra) => ({ name, cwd: join(B, 'remotion'), args: [join(B, 'node_modules', '@remotion', 'cli', 'remotion-cli.js'), 'render', 'src/index.jsx', comp, join(OUT, name + TAG + '.mp4'), `--browser-executable=${CHROME}`, `--scale=${SCALE}`, '--chrome-mode=chrome-for-testing', '--log=error', ...extra] });+const hf = (name, dir, extra) => ({ name, cwd: join(B, 'hyperframes'), args: [join(B, 'node_modules', 'hyperframes', 'bin', 'hyperframes.mjs'), 'render', dir, '-o', join(OUT, name + TAG + '.mp4'), '--quiet', ...(SCALE === 2 ? ['--resolution', 'landscape-4k'] : []), ...extra] });+// CPU=1: Remotion's --gl=swangle and HyperFrames' --no-browser-gpu (both ANGLE on SwiftShader), motlab-cpu.mjs gives+// motlab the same flags. Remotion and HyperFrames encode with ffmpeg libx264 by default; motlab gets --encoder sw.+const configs = CPU ? [+ motlab('motlab-sw', ['--encoder', 'sw']),+ motlab('motlab-sw-w4', ['--encoder', 'sw', '--workers', '4']),+ remotion('remotion-dom', 'Dom', ['--gl=swangle']),+ remotion('remotion-dom-c1', 'Dom', ['--gl=swangle', '--concurrency=1']),+ remotion('remotion-canvas', 'Canvas', ['--gl=swangle']),+ hf('hf-dom', 'dom', ['--no-browser-gpu']),+ hf('hf-dom-w1', 'dom', ['--no-browser-gpu', '--workers', '1']),+ hf('hf-canvas', 'canvas', ['--no-browser-gpu']),+] : IGPU ? [+ motlab('motlab-auto', []),+ motlab('motlab-sw', ['--encoder', 'sw']),+ motlab('motlab-auto-w4', ['--workers', '4']),+] : [+ motlab('motlab-auto', []),+ motlab('motlab-sw', ['--encoder', 'sw']),+ motlab('motlab-auto-w4', ['--workers', '4']),+ remotion('remotion-dom', 'Dom', []),+ remotion('remotion-dom-c1', 'Dom', ['--concurrency=1']),+ remotion('remotion-canvas', 'Canvas', []),+ hf('hf-dom', 'dom', []),+ hf('hf-dom-w1', 'dom', ['--workers', '1']),+ hf('hf-canvas', 'canvas', []),+];++const ts = Array.from({ length: 10 }, (_, i) => i + 0.5);+const ref = join(REF + SIZE); // the GPU stills: what the frames should look like+const ssim = file => {+ if (!existsSync(join(ref, '9.50.png')))+ spawnSync(process.execPath, [MOTLAB, 'stills', 'canvas.html', ref, ...ts.map(String), '--scale', String(SCALE), '--chrome', CHROME, '--root', B], { cwd: join(B, 'motlab'), stdio: 'inherit' });+ const vals = ts.map(t => {+ const p = spawnSync('ffmpeg', ['-v', 'info', '-i', file, '-i', join(ref, t.toFixed(2) + '.png'), '-filter_complex',+ `[0:v]select=eq(n\\,${Math.round(t * 30)}),setpts=PTS-STARTPTS,format=yuv444p[a];[1:v]format=yuv444p[b];[a][b]ssim`, '-frames:v', '1', '-f', 'null', '-'], { encoding: 'utf8' });+ return Number(/All:([\d.]+)/.exec(p.stderr)?.[1]);+ });+ return +(vals.reduce((a, b) => a + b, 0) / vals.length).toFixed(4);+};++const only = process.env.ONLY?.split(','), results = [];+for (const c of configs.filter(c => !only || only.includes(c.name))) {+ const times = [], file = join(OUT, c.name + TAG + '.mp4');+ for (let i = 0; i < RUNS; i++) {+ const t0 = performance.now();+ const r = spawnSync(process.execPath, c.args, { cwd: c.cwd, env, encoding: 'utf8', maxBuffer: 1 << 26 });+ const s = (performance.now() - t0) / 1000;+ if (r.status !== 0) { console.log(`${c.name} run ${i + 1} FAILED\n${(r.stdout || '').slice(-1500)}\n${(r.stderr || '').slice(-1500)}`); break; }+ times.push(+s.toFixed(2)); console.log(`${c.name} run ${i + 1}: ${s.toFixed(2)} s`);+ }+ if (!times.length) continue;+ const median = [...times].sort((a, b) => a - b)[(times.length - 1) >> 1];+ results.push({ name: c.name, times, median, fps: +(300 / median).toFixed(1), mb: +(statSync(file).size / 1e6).toFixed(1), ssim: ssim(file) });+ writeFileSync(RESULTS, JSON.stringify(results, null, 2));+}+console.table(results);diff --git a/bench/shared.js b/bench/shared.jsnew file mode 100644index 0000000..72199be--- /dev/null+++ b/bench/shared.js@@ -0,0 +1,89 @@+// One benchmark scene, shared by motlab, Remotion and HyperFrames. Everything visible is a function of t (seconds):+// a gradient that turns, 160 cards that move, turn, scale and fade, each with a number, a title, a frame counter and+// a progress bar. drawCanvas draws it on a 2D canvas; dom/applyDom build and move the same thing as HTML elements.+(function (g) {+ const W = 1920, H = 1080, TOTAL = 10, N = 160, COLS = 16, CW = 96, CH = 64, FONT = '"Segoe UI", system-ui, sans-serif';++ function state(t) {+ const cards = [];+ for (let i = 0; i < N; i++) {+ const col = i % COLS, row = (i / COLS) | 0, ph = i * 0.37;+ cards.push({+ x: 64 + col * 114 + Math.sin(t * 1.3 + ph) * 18,+ y: 170 + row * 82 + Math.cos(t * 1.1 + ph) * 14,+ r: Math.sin(t * 0.9 + ph) * 0.6,+ s: 0.85 + 0.15 * Math.sin(t * 2 + ph),+ a: 0.55 + 0.45 * (0.5 + 0.5 * Math.sin(t * 1.7 + ph)),+ hue: (i * 7 + t * 40) % 360,+ label: String((i + Math.floor(t * 10)) % 100),+ });+ }+ return {+ angle: (t * 20) % 360, // CSS degrees: 0 = to top, clockwise+ bg1: `hsl(${(220 + t * 15) % 360}, 60%, 18%)`, bg2: `hsl(${(300 + t * 15) % 360}, 55%, 30%)`,+ titleY: 70 + Math.sin(t * 2.4) * 10,+ counter: `frame ${Math.round(t * 30)}`,+ progress: t / TOTAL,+ cards,+ };+ }++ function drawCanvas(ctx, t) {+ const st = state(t), a = st.angle * Math.PI / 180;+ const dx = Math.sin(a), dy = -Math.cos(a), half = (Math.abs(W * dx) + Math.abs(H * dy)) / 2;+ const gr = ctx.createLinearGradient(W / 2 - dx * half, H / 2 - dy * half, W / 2 + dx * half, H / 2 + dy * half);+ gr.addColorStop(0, st.bg1); gr.addColorStop(1, st.bg2);+ ctx.globalAlpha = 1; ctx.fillStyle = gr; ctx.fillRect(0, 0, W, H);++ ctx.textAlign = 'center'; ctx.textBaseline = 'middle';+ ctx.font = `600 24px ${FONT}`;+ for (const c of st.cards) {+ ctx.save();+ ctx.translate(c.x + CW / 2, c.y + CH / 2); ctx.rotate(c.r); ctx.scale(c.s, c.s);+ ctx.globalAlpha = c.a;+ ctx.fillStyle = `hsl(${c.hue}, 70%, 60%)`;+ ctx.beginPath(); ctx.roundRect(-CW / 2, -CH / 2, CW, CH, 12); ctx.fill();+ ctx.fillStyle = '#ffffff'; ctx.fillText(c.label, 0, 1);+ ctx.restore();+ }+ ctx.globalAlpha = 1; ctx.fillStyle = '#ffffff';+ ctx.font = `700 72px ${FONT}`; ctx.textAlign = 'left'; ctx.textBaseline = 'alphabetic';+ ctx.fillText('Benchmark', 64, st.titleY + 60);+ ctx.font = `400 32px ${FONT}`; ctx.textAlign = 'right';+ ctx.fillText(st.counter, W - 64, st.titleY + 50);+ ctx.fillStyle = 'rgba(255,255,255,0.25)'; ctx.fillRect(64, H - 60, W - 128, 12);+ ctx.fillStyle = '#ffffff'; ctx.fillRect(64, H - 60, (W - 128) * st.progress, 12);+ }++ // DOM: build once into a W x H container, then applyDom(els, t) per frame.+ function dom(root, doc) {+ doc = doc || document;+ const mk = (css, text) => { const e = doc.createElement('div'); e.style.cssText = 'position:absolute;' + css; if (text != null) e.textContent = text; root.appendChild(e); return e; };+ root.style.cssText += `;position:relative;width:${W}px;height:${H}px;overflow:hidden;font-family:${FONT};color:#fff`;+ const els = { bg: mk(`left:0;top:0;width:${W}px;height:${H}px`), cards: [] };+ for (let i = 0; i < N; i++) els.cards.push(mk(`left:0;top:0;width:${CW}px;height:${CH}px;border-radius:12px;display:flex;align-items:center;justify-content:center;font-weight:600;font-size:24px;line-height:1`, ''));+ els.title = mk('left:64px;top:0;font-weight:700;font-size:72px;line-height:1;white-space:nowrap', 'Benchmark');+ els.counter = mk('right:64px;top:0;font-size:32px;line-height:1;white-space:nowrap', '');+ mk(`left:64px;top:${H - 60}px;width:${W - 128}px;height:12px;background:rgba(255,255,255,0.25)`);+ els.bar = mk(`left:64px;top:${H - 60}px;width:0;height:12px;background:#fff`);+ return els;+ }+ function applyDom(els, t) {+ const st = state(t);+ els.bg.style.background = `linear-gradient(${st.angle}deg, ${st.bg1}, ${st.bg2})`;+ st.cards.forEach((c, i) => {+ const e = els.cards[i];+ e.style.transform = `translate(${c.x}px, ${c.y}px) rotate(${c.r}rad) scale(${c.s})`;+ e.style.opacity = c.a; e.style.background = `hsl(${c.hue}, 70%, 60%)`;+ if (e.textContent !== c.label) e.textContent = c.label;+ });+ els.title.style.transform = `translateY(${st.titleY}px)`;+ els.counter.style.transform = `translateY(${st.titleY + 22}px)`;+ els.counter.textContent = st.counter;+ els.bar.style.width = `${(W - 128) * st.progress}px`;+ }++ const BENCH = { W, H, TOTAL, state, drawCanvas, dom, applyDom };+ g.BENCH = BENCH;+ if (typeof module !== 'undefined' && module.exports) module.exports = BENCH;+})(typeof window !== 'undefined' ? window : globalThis);diff --git a/bin/motlab.js b/bin/motlab.jsnew file mode 100644index 0000000..ab15c87--- /dev/null+++ b/bin/motlab.js@@ -0,0 +1,4 @@+#!/usr/bin/env node+import { main } from '../src/cli.js';++main(process.argv.slice(2)).then(code => process.exit(code), e => { console.error(`FAILED: ${e.message}`); process.exit(1); });diff --git a/docs/cli.md b/docs/cli.mdnew file mode 100644index 0000000..4c3ca6a--- /dev/null+++ b/docs/cli.md@@ -0,0 +1,77 @@+# Command line++```text+motlab render <project> [out.mp4] [--scale 2] all scenes and audio in project.json, as one MP4+motlab start the viewer in the background at http://127.0.0.1:4173, one for all projects+motlab edit [project] open a project in the viewer, starting it first if needed+motlab stop | restart end the viewer, or start it again from the same folder+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 update [--dry-run] the newest motlab from GitHub, and the skills copied again where they were installed+motlab uninstall [--dry-run] [--yes] remove the command, the skills, ~/.motlab and the encoder cache+```++The viewer commands are described in [the viewer](viewer.md), `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.++## Single pages++```bash+motlab stills page.html outDir 0.5 2 4.25+motlab video page.html out.mp4 --fps 25 --scale 2+motlab events page.html events.json+```++`stills` writes files named after the time with two decimals, for example `0.50.png`, `2.00.png` and `4.25.png`, or JPEG with `--format jpg`. Its default scale is 1.++`stills`, `events` and `video` serve the nearest folder above the page that has a `project.json`, the same folder the viewer serves, so a scene can load `../` files. A page outside a project is served from its own folder. Pass `--root` to serve another folder.++When the page throws while loading, the error names the file, line and column, for example `SyntaxError: Illegal return statement (/scenes/bad.html:4:1)`.++## Options++`render` takes only `--scale`; the rest are for `video` (and `--root`, `--chrome`, `--scale` and `--format` for `stills`, and `--root` and `--chrome` for `events`).++| Option | Meaning |+|---|---|+| `--fps` | Frames per second, default 24 (`render` takes it from `project.json`) |+| `--scale` | Passed to the page as `?scale=`. 2 turns a 1920x1080 page into 4K. Default 2 for video and render, 1 for stills |+| `--audio` | Audio file to mux in (AAC 320k), cut to the video length |+| `--encoder` | `auto`, `hw` or `sw`, see [encoder choice](rendering.md#encoder-choice) |+| `--codec` | `auto`, `h264` or `hevc`. H.264 is kept unless HEVC is clearly faster |+| `--workers` | Split the frames over this many Chrome processes and join the parts with ffmpeg concat (default 1) |+| `--qp` | Constant QP for encoders that support it (default 18 for H.264, 20 for HEVC; lower is better and larger) |+| `--bitrate` | Use variable bitrate at this many Mbit/s instead of constant QP |+| `--mux` | `auto`, `mediabunny` or `raw`. Auto tries the in-page MP4 muxer, then a raw bitstream wrapped by ffmpeg |+| `--reprobe` | Time the encoders again instead of using the saved timings |+| `--root` | Folder to serve. Default is the nearest folder above the page with a `project.json`, else the page's folder |+| `--chrome` | Path to Chrome. Default: found automatically, or the `CHROME` environment variable |+| `--format` | `png` or `jpg`, for `stills` |++`--gpu` is accepted and ignored, so older commands that pass it keep working. Chrome always runs with `--enable-gpu --force_high_performance_gpu`.++## Environment++| Variable | Meaning |+|---|---|+| `CHROME` | Path to Chrome or Chromium |+| `MOTLAB_CACHE_DIR` | Where the encoder timings are saved. Default `%LOCALAPPDATA%\motlab` on Windows, `~/.cache/motlab` elsewhere |++## Page contract++A scene page must have:++- `<canvas id="c">` with even width and height (H.264 and HEVC need them)+- `window.renderAt(t)`, which draws the frame at `t` seconds and may be async+- `window.TOTAL`, the length in seconds+- `window.ready`, a promise that resolves when fonts and assets are loaded++And may have:++- `window.EVENTS`, a list of `{ name, t }` for placing sound effects on beats+- support for `?t=` (show one frame, for opening the page by hand) and `?scale=` (the resolution multiplier)++The frame count is `round(TOTAL * fps)`, and frame `f` is drawn at `t = f / fps`. The page itself is never edited by the renderer: `src/page/runtime.js` is injected and drives it.diff --git a/docs/install-for-agents.md b/docs/install-for-agents.mdnew file mode 100644index 0000000..abcc413--- /dev/null+++ b/docs/install-for-agents.md@@ -0,0 +1,61 @@+# Installing motlab (for an agent)++Follow these steps when a user asks you to install or update motlab. Ask before running any command that installs system software, and never install anything the user did not agree to.++## 1. Check what the machine has++```bash+node --version+ffmpeg -version+ffprobe -version+```++Node must be 24 or newer. If Node is missing or older, tell the user and give them the command from the table in [install.md](install.md#requirements) for their OS. Do the same for Chrome and ffmpeg. Do not continue until Node 24 is there; Chrome and ffmpeg can be fixed after the install, because `motlab doctor` reports them again.++## 2. Get the repository++If the user has no clone yet, ask where it should live (a folder they keep, not a temporary one, because the `motlab` command runs from it):++```bash+git clone https://github.com/staryone/motlab.git <folder>+```++If they already have a clone and only want the newest version, run `motlab update` and skip to step 4: it pulls, runs `npm ci` and copies the skills again to every agent folder they were installed in. If it stops because the clone has local changes or commits of its own, show the user its message and ask what to do; do not stash, reset or discard anything yourself.++## 3. Run the installer++Pick the skill target for the agent you are, from the table in [install.md](install.md#with-the-installer): `claude` for Claude Code, `agents` for Codex, Cursor, OpenCode, GitHub Copilot, Gemini CLI, Amp and Windsurf, `antigravity` for the Antigravity App and CLI. If the user also works in other agents, ask which, and join the targets with commas. For an agent not in the table, look up its user skill folder in its own docs and pass `--skill-dir <folder>` instead. Run a dry run first and show the user where files will go:++```bash+node install.js --skill <target> --dry-run+node install.js --skill <target>+```++Use `--link` only when the user works on the skill itself. If the installer refuses because a folder without `SKILL.md` is at a skill path, ask the user what to do with it; pass `--force` only when they say so.++If the installer prints that `~/.local/bin` is not on PATH, show the user the line it printed and ask before changing their shell profile or Windows user PATH. Until it is on PATH, call the engine as `node <folder>/bin/motlab.js`.++## 4. Verify++```bash+motlab doctor+motlab --help+```++`doctor` must end with `Ready.` (warnings about Python are fine if the user does not need the skill's scripts). `motlab --help` prints the engine folder; it must be the clone from step 2. If it is another folder, an older launcher comes first on PATH; tell the user which one.++Python packages for the skill's scripts, if the user wants them:++```bash+python -m pip install -r <folder>/skills/motlab/requirements.txt+```++## 5. Tell the user++Say in a few lines what was installed and where (the clone, the launcher, 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.++## Do not++- create video projects inside the clone or the installed skill folder; a project lives in its own folder+- delete or overwrite a folder you did not create+- render a user's project unless they ask for it; the user exports from the viewerdiff --git a/docs/install.md b/docs/install.mdnew file mode 100644index 0000000..e59f054--- /dev/null+++ b/docs/install.md@@ -0,0 +1,142 @@+# Installing motlab++motlab has two parts: the engine (the `motlab` command, the viewer and the renderer) and two agent skills: `skills/motlab/` makes videos, and `skills/motlab-assets/` makes reusable asset kits for them. The installer sets up both parts. If an agent is doing the install for you, point it at [install-for-agents.md](install-for-agents.md).++## Requirements++| Tool | Why | Check |+|---|---|---|+| Node.js 24 or newer | runs the engine | `node --version` |+| Google Chrome or Chromium | draws and encodes the frames | found on its default path, or set `CHROME` |+| ffmpeg and ffprobe | join the parts, add audio, check the output | `ffmpeg -version` |+| Python 3, optional | the skills' helper scripts | `python --version` |+| Blender 4.2 or newer, optional | the main 3D path of `motlab-assets` (FBX, baked textures, Cycles stills) | `blender --version` |++How to get them:++| | Windows | macOS | Debian or Ubuntu |+|---|---|---|---|+| Node 24 | `winget install OpenJS.NodeJS` | `brew install node` | [nodejs.org](https://nodejs.org) or nvm |+| Chrome | `winget install Google.Chrome` | `brew install --cask google-chrome` | Google's `.deb`, or `sudo apt install chromium` |+| ffmpeg | `winget install Gyan.FFmpeg` | `brew install ffmpeg` | `sudo apt install ffmpeg` |+| Python 3 | `winget install Python.Python.3.12` | `brew install python` | `sudo apt install python3 python3-pip` |++The skill's scripts need numpy, scipy and Pillow:++```bash+python -m pip install -r skills/motlab/requirements.txt+```++## With the installer++```bash+git clone https://github.com/staryone/motlab.git+cd motlab+node install.js+```++It does four things and prints each one:++1. `npm ci` in the engine folder. The only dependency is `mediabunny`, pinned to an exact version.+2. Writes a `motlab` launcher to `~/.local/bin` (on Windows `motlab.cmd` for cmd and PowerShell, and `motlab` for Git Bash). The launcher runs `bin/motlab.js` from the folder you cloned, so keep that folder where it is. If `~/.local/bin` is not on PATH, the installer prints the line that adds it.+3. Copies both skills to each agent skill folder you pick.+4. Runs `motlab doctor` and lists anything still missing.++It keeps where the skills, the launcher and `--link` went in `~/.motlab/install.json`, so `motlab update` can put them back there.++Options:++| Option | Meaning |+|---|---|+| `--skill <target>` | where the two skills go, from the table below. Several at once with commas: `--skill claude,agents,antigravity`. The default is `claude` |+| `--skill none` | engine and command only |+| `--skill-dir <dir>` | the skills in any other folder, for an agent not in the table. Can be given more than once, and together with `--skill` |+| `--link` | link the skill folders to this checkout instead of copying them, so edits under `skills/` apply at once (a junction on Windows) |+| `--bin <dir>` | put the launcher somewhere else |+| `--update` | the skills again in every folder from `~/.motlab/install.json`, and in any folder from the table below that already has the motlab skill (an install from before that file). `--skill` and `--skill-dir` add folders. `motlab update` runs this |+| `--force` | replace a folder at a skill path that has no `SKILL.md` |+| `--dry-run` | print every step and change nothing |++Skill targets. Each one is the agent's user skill folder, as its docs gave it in November 2026:++| Target | Folder | Read by |+|---|---|---|+| `claude` | `~/.claude/skills/` | Claude Code. Cursor, OpenCode and Amp read it too |+| `agents` (or `codex`) | `~/.agents/skills/` | Codex, Cursor, OpenCode, GitHub Copilot, Gemini CLI, Amp, Windsurf |+| `antigravity` | `~/.gemini/config/skills/` | Antigravity, the App and the CLI |+| `opencode` | `~/.config/opencode/skills/` | OpenCode |+| `cursor` | `~/.cursor/skills/` | Cursor |+| `copilot` | `~/.copilot/skills/` | GitHub Copilot |++`claude,agents,antigravity` covers every agent in the table. An agent that reads two of these folders finds the skill in both; OpenCode and Amp keep one, and the others may list it twice. For any other agent, find its user skill folder in its docs and pass it with `--skill-dir`, for example Windsurf's own `~/.config/devin/skills`. The Antigravity CLI also reads `~/.gemini/antigravity-cli/skills/` and `~/.gemini/skills/`, and the App reads neither, so the installer uses the folder they share. A copy in one of the CLI's own folders wins over it in the CLI, so delete an old one there. Codex used `~/.codex/skills/` before; a copy left there by an older installer can be deleted.++The installer never installs Chrome, ffmpeg or Python. An existing link at a skill path is removed as a link, so the folder it pointed at is not touched. A folder there that has no `SKILL.md` is left alone unless you pass `--force`.++## Without the installer++```bash+git clone https://github.com/staryone/motlab.git+cd motlab+npm ci+node bin/motlab.js doctor+```++Then either run `node /path/to/motlab/bin/motlab.js` directly, or make a launcher yourself. On Windows, `motlab.cmd` containing `@node "C:\path\to\motlab\bin\motlab.js" %*` in a folder on PATH. On macOS and Linux, a `motlab` file containing `exec node "/path/to/motlab/bin/motlab.js" "$@"`, marked executable.++`npm link` and `npm install -g .` also work where npm's global folder is on PATH. They do not with nvm for Windows in its default setup, which is why the installer writes its own launcher.++To install the skills by hand, copy or link `skills/motlab/` and `skills/motlab-assets/` to your agent's skill folder (see the table above), side by side. Both call `motlab` and find the engine folder through `motlab --help`; `motlab-assets` also uses scripts from the motlab skill there.++## Updating++```bash+motlab update+```++It works in the clone the `motlab` command runs from:++1. Stops if the clone has changes to tracked files, is not on a branch, or has commits that GitHub does not. It says what to do about each.+2. Fetches the branch from `origin` and lists the new commits. With none it says so and stops.+3. Fast-forwards to them (`git merge --ff-only`), so it never makes a merge commit.+4. Runs the new `install.js --update`: `npm ci`, the launcher, and the skills copied again to every folder they were installed in, then `motlab doctor`.++`motlab update --dry-run` fetches and lists the new commits, then prints the other steps without doing them. A viewer that is already running keeps the old code until `motlab restart`, and an agent picks up the new skills in a new session.++By hand, the same is:++```bash+cd motlab+git pull+node install.js --update+```++With `--link`, the skills update with `git pull` alone, but run the installer anyway in case the npm packages changed.++## Removing++```bash+motlab uninstall+```++It stops the viewer and removes the launcher (`~/.local/bin/motlab`, and `motlab.cmd` on Windows), the two skill folders in every agent folder they were installed in, `~/.motlab/` (where the installer put things, the viewer's recent projects and its log) and the encoder timings (`%LOCALAPPDATA%\motlab` on Windows, `~/.cache/motlab` elsewhere; with `MOTLAB_CACHE_DIR` only the timings file). It lists everything and asks first; `--yes` skips the question and `--dry-run` only lists. A skill installed with `--link` is removed as a link, and what it points to stays. It leaves the clone, because it runs from there: delete that folder afterwards.++## Check the machine++```bash+motlab doctor+```++It checks Node, Chrome, ffmpeg, ffprobe, the npm packages, and (as warnings) Python and its packages. For each missing tool it prints a command for your OS. The exit code is 1 when a required check fails. The GPU in use is not checked here: every render prints it on its first line.++## Notes per OS++Windows++- Chrome is found in `Program Files` and `Program Files (x86)`. Set `CHROME` for any other path.+- On a laptop with two GPUs, headless Chrome draws on the integrated one unless told otherwise. motlab always passes `--force_high_performance_gpu`, and each render prints the GPU it got.+- Python is usually `python`, not `python3`.++macOS and Linux++- The code has the macOS and Linux Chrome paths and uses ANGLE on Metal on macOS, but neither system has been tested yet. Reports are welcome.+- A machine without a GPU should still render through Chrome's software drawing and software H.264 encoder, only slower. On the Windows test laptop with Chrome drawing on SwiftShader, the benchmark scene took 2.8 times as long at 1080p and 4.5 times at 4K ([rendering](rendering.md#without-a-gpu)). A machine with no GPU at all has not been tested.diff --git a/docs/projects.md b/docs/projects.mdnew file mode 100644index 0000000..f3d6f40--- /dev/null+++ b/docs/projects.md@@ -0,0 +1,144 @@+# Projects++A project is a folder with scene pages, audio files and a `project.json`:++```json+{+ "fps": 30,+ "scenes": ["scenes/01-judul.html", "scenes/02-grafik.html"],+ "audio": [+ { "file": "audio/musik.wav", "start": 0, "volume": 0.6 },+ { "file": "audio/whoosh.wav", "start": 2.2, "volume": 0.8 }+ ]+}+```++- Scenes play in list order, and each lasts as long as its page's `TOTAL`, rounded to the frame grid.+- A scene can be an object with a `transition` from the scene before it (see [Transitions](#transitions)). A plain path is a hard cut.+- All scenes must have the same canvas size, and the render stops with an error that names the scene that differs. That size sets the orientation: landscape, portrait and square all work.+- `start` is seconds from the start of the video, and `volume` is a multiplier (1 leaves it as is).+- 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.++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`).++## Versions++A folder can hold more than one cut of the same video: every `.json` file in it with a `scenes` list is a version, for example `project-tiktok.json` next to `project.json`. One video often goes to several places, and one place keeps a part (an affiliate link, say) that another wants removed. Each version lists its own scenes and audio and shares the folder's assets, so a version that drops a scene just leaves it out. A version that needs a different scene gets its own copy, such as `scenes/05-cta-tiktok.html`, listed only in that version.++In the viewer the second name in the header is the version menu. "New version from this one" ("Versi baru dari ini" in Indonesian) copies the open version to `project-<name>.json` and opens it. On the command line, pass the file instead of the folder:++```bash+motlab edit promo/project-tiktok.json+motlab render promo/project-tiktok.json+```++The output is named `<folder>-<version>.mp4`, with a leading `project-` left out: `promo-tiktok.mp4`. `project.json` is shown as "Main" ("Utama") and renders to `promo.mp4`.++## Scene pages++A scene is an HTML page that keeps the [page contract](cli.md#page-contract): a `<canvas id="c">`, `window.renderAt(t)`, `window.TOTAL` and `window.ready`. Everything on screen must be a function of `t`. No timers, `requestAnimationFrame` loops or unseeded randomness, because the renderer calls `renderAt` for frames in any order and as fast as it can.++The skill's [templates](../skills/motlab/templates) are starting points for scenes: 2D canvas, UI panels in 3D (`gl3d.js`), three.js and p5.js. The three.js and p5.js ones draw into their own canvas and copy it onto `#c`, and they load the library from a CDN with an exact version, so rendering them needs the network.++The renderer and the viewer serve a few files for scene pages at fixed paths, so a page imports them the same way in both:++| Path | What it is |+|---|---|+| `/__motlab/footage.js` | decodes video files inside the page ([Footage](#footage)) |+| `/__motlab/cuts.js` | plays a cut list over one recording ([Cut lists](#cut-lists)) |+| `/__motlab/motion.js` | easings, CSS `cubic-bezier`, exact springs, keyframes, stagger and motion blur, all pure functions of time |+| `/__motlab/transitions.js` | the scene transitions, also usable inside a page to mix two canvases |++The skill's `references/motion-and-libraries.md` lists what is in `motion.js` and how GSAP, Anime.js, Lottie and Theatre.js are driven from `renderAt`.++Opened by hand, a template plays on a loop. Inside the viewer (an iframe) or with `?t=`, it draws only when `renderAt` is called. A scene of your own that loops with `requestAnimationFrame` should do the same: in the viewer, a three.js scene that kept its loop running drew 900 frames in 3 seconds while nothing played, against none with the check.++## Rendering a project++```bash+motlab render example+motlab render example out/promo.mp4 --scale 1+```++This renders every scene, joins them and adds the audio. The result is `example/out/example.mp4` unless you give a path. The default `--scale 2` turns 1920x1080 pages into 4K; `--scale 1` gives 1080p. The viewer's Export button does the same thing at a resolution you pick.++How it works:++- Each scene is rendered to its own MP4, and ffmpeg joins them with `-c copy`.+- The first scene picks the encoder, and every later scene is forced to the same encoder and codec, because a stream copy join is only safe when codec, encoder and resolution match.+- Scenes are joined with hard cuts, unless a scene has a transition. A transition is rendered as a part of its own between the two scenes, and their own parts leave out those frames.+- ffmpeg mixes the audio into one WAV first (`adelay`, `volume`, `amix`), and the final pass muxes it in as AAC.+- Every scene starts its own Chrome (about one second) and runs one ffmpeg pass, so a project with many short scenes pays that per scene. Scenes are rendered one after another.++## Transitions++```json+"scenes": [+ "scenes/01-hook.html",+ { "file": "scenes/02-demo.html", "transition": { "type": "crosswarp", "duration": 0.5, "ease": "inOutCubic", "params": {} } }+]+```++The transition is set on the scene it leads into. For `duration` (rounded to whole frames, at least one), the two scenes overlap: the scene before keeps playing its last frames while the new one plays its first, and the two are mixed. Scene 2 therefore starts 0.5 s before scene 1 ends, and the video is 0.5 s shorter than the sum of the scenes. Audio `start` times are times in the finished video and do not move by themselves.++Frame `k` of an `n`-frame transition shows frame `TOTAL * fps - n + k` of the scene before and frame `k` of the new one, mixed at progress `ease((k + 0.5) / n)`, so neither end of the transition repeats a plain frame. A scene must be longer than its transitions together: a scene with one leading into it and one leading out needs more frames than the two have between them.++`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.++The render draws a transition with `__motlab/transition.html`, a page that loads both scene pages in iframes and mixes their canvases with WebGL2. The viewer mixes the same two canvases with the same code. On the example project with a `crosswarp` and a `cube` transition, a transition frame in the viewer and in the 1080p MP4 differed by 1.37 levels of 255 on average, with 0.2% of values more than 8 apart, at the edges, from the H.264 compression.++Tested: the example's scenes with two transitions (7.6 s, 228 frames, the frame count and length expected), a 1080x1920 project of two footage scenes joined by `directionalwarp`, and `test/render.test.js`, which checks that a 15-frame linear fade from black to white is at mid grey on its eighth frame. A 12-scene project with all 11 types, one into each scene, gave 555 frames and 18.5 s as expected, and every scene showed its own colour and clock in the middle of its plain stretch. It took 57 s at 1080p, mostly from starting Chrome for 23 parts. Not tested: a transition between scenes of different sizes in the viewer, where the new scene is stretched to the size of the one before (the render refuses such a project).++## Footage++Scene pages can draw video files. The renderer and the viewer both serve `/__motlab/footage.js`, which decodes a file inside the page with Mediabunny (WebCodecs):++```js+let clip;+window.ready = (async () => {+ const { openFootage } = await import('/__motlab/footage.js');+ clip = await openFootage('../footage/demo.mp4'); // relative to the page, like an <img src>+})();+window.renderAt = async t => { await window.ready; (await clip.frame(12.5 + t)).draw(ctx, 0, 0, W, H); };+```++- `clip.frame(t)` returns the frame shown at `t` seconds into the file. It is a Mediabunny `VideoSample` and stays valid until the next call.+- Sequential calls decode each frame once. A jump backwards or far ahead seeks from a keyframe.+- Rotation metadata (phone footage) is applied by `draw`. For a WebGL texture, use `toCanvasImageSource()`.+- Both servers answer Range requests, so long files are read in pieces.+- The footage's sound goes in `project.json` as an audio entry with `from` and `duration`.++Tested: a 60 fps clip trimmed from 1.5 s into a 30 fps scene renders the exact source frame for every output frame, also with three workers starting partway through; a portrait 1080x1920 project with a portrait clip; playback in the viewer. Each frame of the test clips carried its own number in a strip of black and white squares, so every output frame could be checked against the frame the file shows at that time:++- A 20-minute 1280x720 recording (1.1 GB, a keyframe every second): stills at 0.5, 600.2, 1199.9, 30, 1100.1, 2 and 2.03 s, in that order, all showed the right frame, in 1.7 s for the whole command. Ten seconds from 19:40 rendered at 94 fps, every frame right.+- Variable frame rate (portrait 1080x1920, 30 fps with uneven gaps for 5 s, then 60 fps): 435 frames at 30 fps, every one the frame shown at that time.+- HEVC 8-bit (Main) and 10-bit (Main 10) at 1080p: 300 frames each, every one right, at 53 fps. Colour matched an H.264 source of the same picture.++These were made with ffmpeg, not filmed on a phone, and played by a Chrome that could decode HEVC on this laptop. Chrome on a machine without HEVC decoding stops at `openFootage` with "this browser cannot decode".++## Cut lists++For a talking head with many jump cuts, cut the pauses out of the recording instead of making one scene per cut. The skill's `cut_pauses.py` finds the pauses in the sound with ffmpeg `silencedetect` and writes the parts to keep, and with `--audio-out` also the voice with the same cuts:++```bash+python skills/motlab/scripts/cut_pauses.py footage/talk.mp4 cuts.json --start 1.4 --audio-out audio/voice-cut.wav+```++A scene then plays the cut list with `/__motlab/cuts.js`:++```js+const { cutList } = await import('/__motlab/cuts.js');+const edit = cutList(await (await fetch('../cuts.json')).json(), clip, { punch: [1, 1.12], glide: 0.25, drift: 0.008, x: 0.5, y: 0.42 });+window.renderAt = async t => { await window.ready; await edit.draw(ctx, t, 0, 0, W, H); };+```++- Each part is framed to cover the scene, zoomed by `punch` in turn (wide, then closer, then wide) around the point `x`, `y` (fractions of the recording), so the jump cuts read as deliberate. A segment in the JSON can set its own `zoom`, `x` and `y`.+- `glide` eases the zoom from the previous part over that many seconds instead of jumping, and `drift` pushes in slowly, per second.+- `--dissolve 0.12` in `cut_pauses.py` overlaps the parts and fades between them, in the picture and the sound. A dissolve draws two parts at once, so `cutList` needs a second `openFootage()` of the same file as `clip2`.+- `edit.parts[k].at` is where part `k` starts in the edit, for sound effects on the cuts, and `edit.toOut(seconds)` maps a time in the recording (a word from a transcript) to the edit.++Tested on the first 40 s of a 1440x1440 talking-head recording: 10 parts, 38.64 s of take to 33.47 s, and the cut voice WAV was the same length as the cut list, with and without a 0.12 s dissolve. A 1080x1920 render of two 12 s scenes from it encoded at 55 to 72 fps on the test laptop (RTX 3060 Laptop). A whole 10-minute take (Windows text to speech with pauses of 0.4 to 2.5 s, over a pink noise room tone) went from 619.4 s to 384.4 s in 240 parts in 60 s. No part starts or ends inside a word: the clean voice is at least 38 dB below its speech level in the first and last 20 ms of every part. None of the 239 joins in the cut voice WAV clicks. Listened to with earshot: no clipping, the same loudness through the take (-20 LUFS), and 0.3 s gaps where sentences meet. A synthetic voice says little about how natural a real person sounds with these settings, so listen to the first real take.++The skill's [footage reference](../skills/motlab/references/footage.md) covers editing footage into a video.diff --git a/docs/rendering.md b/docs/rendering.mdnew file mode 100644index 0000000..28ca2ad--- /dev/null+++ b/docs/rendering.md@@ -0,0 +1,174 @@+# 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.++## Steps++1. A small static server serves the project folder (the nearest folder above the page with a `project.json`, else the page's folder, or `--root`) on `127.0.0.1`.+2. Chrome starts with `--headless=new --enable-gpu --force_high_performance_gpu`. The GPU actually in use is read from `WEBGL_debug_renderer_info` and printed at the start.+3. `src/page/runtime.js` is injected into the page. For each frame it calls `renderAt`, makes a `VideoFrame` from the canvas and feeds it to a `VideoEncoder`.+4. Mediabunny muxes the encoded chunks into an MP4 inside the page, which is POSTed to Node. If that fails, the engine retries with a raw Annex B bitstream.+5. ffmpeg copies the stream (`-c copy`) into the final file. This pass writes BT.709 limited range tags 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.++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`.++## Encoder choice++The first time a resolution is rendered, the engine times four candidates (H.264 and HEVC, hardware and software) for a few seconds. The result is saved per machine, resolution, fps and worker count in `%LOCALAPPDATA%\motlab\encoder-probe.json` (`~/.cache/motlab` outside Windows, or the folder in `MOTLAB_CACHE_DIR`).++- `auto` picks the fastest encoder that supports constant QP. In current Chrome only the hardware encoders do. If none does, it picks the fastest.+- `hw` picks the fastest hardware encoder.+- `sw` picks a software encoder. It is the fastest option, but Chrome's software H.264 encoder ignores bitrate above a certain quality ceiling, so fine line art at 1080p comes out slightly below a JPEG screenshot pipeline.++H.264 is kept unless HEVC is at least 25% faster.++Why hardware with constant QP is the default and not simply the fastest encoder: on the 2D template at 1080p, software H.264 reached SSIM 0.9945 against 0.9983 for the screenshot pipeline, while hardware at QP 18 (H.264) or 20 (HEVC) was always above it. At 4K the software encoder matches the screenshot pipeline and its timing is steadier, while hardware is sometimes twice as slow. That is the reason to revisit this default later.++## Why canvas and WebCodecs++DOM pages have to be screenshotted before they can be encoded. A canvas can go straight into the encoder. These options were compared and not chosen:++| Option | How it works | Why not |+|---|---|---|+| Remotion | React DOM, screenshot per frame | Heavy, and a paid license for companies of four or more |+| HyperFrames (Apache 2.0) | HTML with data attributes, Puppeteer and FFmpeg | Closest in concept, but capture is still a screenshot |+| Motion Canvas / Revideo (MIT) | Canvas and TypeScript | Its own API, so existing canvas scenes would need rewriting |+| Native (Rust/wgpu, Skia) | No browser | The web preview would no longer match the render, and three.js is lost |++The engine is neutral about style. It only fixes technical things: the page contract, tracks, resolution, fps and encoder. Style and content come from each project's reference folder and the user's direction.++## Measurements++Measured on one Windows laptop (Ryzen 7 5800H, RTX 3060 Laptop, Chrome 157). The 2D and 3D scene templates, 8 seconds at 25 fps (200 frames), total time of one CLI command including Chrome start-up, with the encoder probe already saved. The first probe for a new resolution adds about 5 seconds. SSIM is against 200 lossless PNG frames.++| Case | Screenshot pipeline (JPEG to libx264, GPU drawing) | `auto` (H.264 hardware, QP 18) | `--encoder sw` |+|---|---|---|---|+| 2D 1080p | 6.3 s, SSIM 0.9983 | 5.9 s, SSIM 0.9987 | 2.9 s, SSIM 0.9945 |+| 3D 1080p | 8.3 s, SSIM 0.9984 | 5.6 s, SSIM 0.9992 | 3.3 s, SSIM 0.9989 |+| 2D 4K | 17.5 s, SSIM 0.9989 | 6.9 s or 13.4 s, SSIM 0.9992 | 6.7 s, SSIM 0.9985 |+| 3D 4K | 25.6 s, SSIM 0.9984 | 6.9 s or 13.1 s, SSIM 0.9994 | 6.3 s, SSIM 0.9992 |++An earlier synthetic benchmark (a 2D canvas with a gradient, 160 moving cards and text, frames per second in one Chrome process) shows where the gain comes from. Piping JPEG frames to ffmpeg libx264, as screenshot renderers do, ran at 26 fps at 1080p and 7.9 at 4K. WebCodecs ran at 70 and 17 with `prefer-hardware`, and 105 and 27 with `prefer-software`. The screenshot path is limited by reading frames out of Chrome, not by encoding.++The two 4K `auto` numbers are the two throughput states of the hardware encoder (see quirks). The sample project renders at 4K in about 21 seconds including the first probe, and a 720p export from the viewer takes about 13 seconds.++A 10-minute render at 4K (the benchmark scene below looped for 600 s, 18,000 frames, hardware H.264 at QP 18) took 1,126 s in all, 17.0 fps while encoding, and made a 3.16 GB MP4. Its last seconds decoded cleanly and a frame at 595 s matched a still of the page (SSIM 0.994). Other tests ran on the laptop at the same time, so a quiet machine should be faster. At this QP a busy 4K scene comes to about 5 MB a second. `motlab video --bitrate` makes smaller files; `render` and Export have no such option.++`--workers` only helps when `renderAt` is expensive. It did nothing for the two templates, where drawing is cheap and the encoder is the limit. A test page with 160 shadowed cards went from 14 fps (one process) to 35 fps (two) at 4K. The hardware encoder tops out around 35 fps in total at 4K, however many processes run.++## Against Remotion and HyperFrames++The same scene rendered by three tools on one laptop (Ryzen 7 5800H, RTX 3060 Laptop, Windows 11, on mains power), all three with the same Chrome 157.0.8103.51. The scene is a turning gradient, 160 cards that move, turn, scale and fade with a number on each, a title, a frame counter and a progress bar, at 1920x1080, 30 fps, 10 seconds (300 frames). motlab draws it on a canvas. Remotion 4.0.543 and HyperFrames 0.9.52 render it twice: as HTML elements, which is how they are normally used, and on a canvas with motlab's own drawing code, to tell the drawing apart from the capture.++Time is the whole command as a user runs it (Chrome start-up, Remotion's bundling, muxing), the median of three runs, with motlab's encoder probe already saved. SSIM is the mean over 10 frames against lossless PNG stills of the canvas page. For the HTML versions it also counts the small differences between how HTML and a canvas draw the same shapes, so compare those among themselves. The code is in [bench/](../bench/README.md).++| Tool and setting | Time | fps overall | SSIM | File |+|---|---|---|---|---|+| motlab, `--encoder sw` | 9.5 s | 31.5 | 0.986 | 29.9 MB |+| motlab, default (hardware H.264, QP 18) | 12.6 s | 23.7 | 0.988 | 25.4 MB |+| motlab, `--workers 4` | 12.3 s | 24.4 | 0.989 | 25.7 MB |+| HyperFrames, HTML, `--workers 1` | 27.2 s | 11.0 | 0.966 | 20.5 MB |+| HyperFrames, canvas, default | 27.6 s | 10.9 | 0.987 | 20.3 MB |+| HyperFrames, HTML, default (6 workers) | 30.9 s | 9.7 | 0.965 | 19.6 MB |+| Remotion, HTML, `--concurrency=1` | 30.7 s | 9.8 | 0.948 | 18.5 MB |+| Remotion, canvas, default | 38.7 s | 7.8 | 0.967 | 19.8 MB |+| Remotion, HTML, default | 39.0 s | 7.7 | 0.948 | 18.5 MB |++What it shows, for this scene on this laptop:++- motlab took 9.5 to 12.6 s. The fastest HyperFrames setting took 27.2 s and the fastest Remotion setting 30.7 s, so motlab was 2.2 to 2.9 times faster than HyperFrames and 2.4 to 3.2 times faster than Remotion.+- Giving the other two motlab's canvas drawing did not make them faster (HyperFrames 27.6 s against 27.2 s, Remotion 38.7 s against 39.0 s). The gap comes from taking a screenshot of every frame, not from HTML drawing.+- More parallel workers did not help any of the three. HyperFrames' default of 6 workers was slower than one, and Remotion's default concurrency slower than one. motlab with 4 workers matched one; its first run took 24.9 s because the encoder probe ran again for the new worker count.+- Remotion's lower SSIM comes from its default JPEG frames. Its PNG option was not tried. motlab's files are larger, 25 to 30 MB against 18.5 to 20.5 MB.++At 4K (`SCALE=2 node run.mjs`: motlab `--scale 2`, Remotion `--scale=2`, HyperFrames `--resolution landscape-4k`; all nine files 3840x2160 with 300 frames), on the same laptop with nothing else running:++| Tool and setting | Time | fps overall | SSIM | File |+|---|---|---|---|---|+| motlab, `--workers 4` | 13.1 s | 22.9 | 0.994 | 53.1 MB |+| motlab, `--encoder sw` | 14.8 s | 20.3 | 0.993 | 84.4 MB |+| motlab, default (hardware H.264, QP 18) | 19.4 s | 15.4 | 0.994 | 52.6 MB |+| Remotion, canvas, default | 48.9 s | 6.1 | 0.977 | 33.6 MB |+| HyperFrames, canvas, default | 50.9 s | 5.9 | 0.984 | 38.3 MB |+| Remotion, HTML, `--concurrency=1` | 53.8 s | 5.6 | 0.964 | 42.8 MB |+| HyperFrames, HTML, default (6 workers) | 54.3 s | 5.5 | 0.972 | 46.9 MB |+| Remotion, HTML, default | 61.1 s | 4.9 | 0.964 | 42.8 MB |+| HyperFrames, HTML, `--workers 1` | 71.8 s | 4.2 | 0.972 | 46.9 MB |++- motlab took 13.1 to 19.4 s, and the fastest of the others 48.9 s (Remotion on a canvas) and 53.8 s (Remotion with HTML), so motlab was 2.5 to 3.7 times faster than the fastest of them, and 2.8 to 4.1 times faster with HTML scenes.+- At 4K more workers helped: HyperFrames' 6 workers beat one (54.3 s against 71.8 s), the reverse of 1080p, and motlab's 4 workers beat one. motlab's default runs were 15.3, 20.2 and 19.4 s, the hardware encoder's two speeds again (see quirks); its first run with 4 workers took 23.8 s because the encoder probe ran again.+- Drawing on a canvas made the other two faster at 4K (Remotion 48.9 s against 53.8 s), unlike at 1080p.+- motlab drew on the RTX 3060. Remotion and HyperFrames do not pass `--force_high_performance_gpu`, so their Chrome drew on the integrated Radeon: in one more 1080p run of each canvas setting, the Windows GPU counters showed their Chrome on the Radeon's 3D engine and not on the RTX 3060.++### motlab on the integrated GPU++To compare on the same GPU, motlab ran again on the Radeon (`IGPU=1 node run.mjs`, and `IGPU=1 SCALE=2` for 4K) through [bench/motlab-igpu.mjs](../bench/motlab-igpu.mjs), which leaves out `--force_high_performance_gpu`. motlab's `GPU:` line named the Radeon (ANGLE on Direct3D 11), and in one 1080p run the Windows GPU counters showed its Chrome on the Radeon's 3D engine only. Only motlab was run again; the Remotion and HyperFrames times are the ones above.++| motlab setting | 1080p on the Radeon | 1080p on the RTX 3060 | 4K on the Radeon | 4K on the RTX 3060 |+|---|---|---|---|---|+| `--encoder sw` | 8.0 s (SSIM 0.986, 29.9 MB) | 9.5 s | 13.2 s (0.993, 84.4 MB) | 14.8 s |+| default | 10.3 s (0.988, 25.4 MB) | 12.6 s | 22.5 s (0.993, 40.7 MB) | 19.4 s |+| `--workers 4` | 12.0 s (0.989, 25.6 MB) | 12.3 s | 14.0 s (0.994, 53.1 MB) | 13.1 s |++- On the Radeon motlab took 8.0 to 12.0 s at 1080p, against 27.2 s for HyperFrames and 30.7 s for Remotion at their fastest settings (2.3 to 3.4 and 2.6 to 3.8 times as long). At 4K it took 13.2 to 22.5 s, against 48.9 s for the fastest of the other two (2.2 to 3.7 times as long). The gap is about the same as with motlab on the RTX 3060.+- motlab was not slower on the Radeon. At 1080p every setting was a little faster, and at 4K software encoding was faster (13.2 s against 14.8 s). Why was not measured; one guess is that the frames stay on the GPU that also holds the hardware encoder.+- At 4K the default picked HEVC on the Radeon (the saved probe found it clearly faster there), so that file is HEVC and smaller (40.7 MB). On the RTX 3060 it picked H.264.++### Without a GPU++The same benchmark with Chrome drawing in software (`CPU=1 node run.mjs`, and `CPU=1 SCALE=2` for 4K), on the same laptop with nothing else running. All three use ANGLE on SwiftShader (`--use-gl=angle --use-angle=swiftshader --enable-unsafe-swiftshader`): HyperFrames through `--no-browser-gpu`, Remotion through `--gl=swangle`, and motlab through [bench/motlab-cpu.mjs](../bench/motlab-cpu.mjs), which swaps motlab's GPU flags for these (motlab has no option for it). motlab encodes with `--encoder sw`; Remotion and HyperFrames encode with ffmpeg on the CPU by default. motlab's `GPU:` line named SwiftShader, and in one 1080p run each of motlab, Remotion's canvas and HyperFrames' canvas, the Windows GPU counters showed no GPU work from their Chrome. The GPUs were still in the laptop, so this is software drawing on a laptop CPU, not a measured machine without a GPU. SSIM is against the same stills as above, drawn on the GPU.++At 1080p:++| Tool and setting | Time | fps overall | SSIM | File | With a GPU |+|---|---|---|---|---|---|+| motlab, `--encoder sw --workers 4` | 19.2 s | 15.6 | 0.980 | 30.0 MB | |+| motlab, `--encoder sw` | 27.0 s | 11.1 | 0.980 | 29.9 MB | 9.5 s |+| HyperFrames, canvas, default | 28.3 s | 10.6 | 0.987 | 20.4 MB | 27.6 s |+| HyperFrames, HTML, default (6 workers) | 29.4 s | 10.2 | 0.965 | 20.5 MB | 30.9 s |+| HyperFrames, HTML, `--workers 1` | 30.5 s | 9.8 | 0.965 | 20.5 MB | 27.2 s |+| Remotion, canvas, default | 46.7 s | 6.4 | 0.967 | 21.2 MB | 38.7 s |+| Remotion, HTML, `--concurrency=1` | 50.7 s | 5.9 | 0.948 | 18.6 MB | 30.7 s |+| Remotion, HTML, default | 60.1 s | 5.0 | 0.948 | 18.6 MB | 39.0 s |++At 4K:++| Tool and setting | Time | fps overall | SSIM | File | With a GPU |+|---|---|---|---|---|---|+| HyperFrames, canvas, default | 43.4 s | 6.9 | 0.985 | 36.5 MB | 50.9 s |+| HyperFrames, HTML, default (6 workers) | 50.7 s | 5.9 | 0.972 | 49.0 MB | 54.3 s |+| motlab, `--encoder sw --workers 4` | 60.7 s | 4.9 | 0.988 | 83.9 MB | |+| HyperFrames, HTML, `--workers 1` | 63.2 s | 4.8 | 0.972 | 49.0 MB | 71.8 s |+| motlab, `--encoder sw` | 67.3 s | 4.5 | 0.988 | 84.5 MB | 14.8 s |+| Remotion, canvas, default | 72.4 s | 4.1 | 0.977 | 35.7 MB | 48.9 s |+| Remotion, HTML, `--concurrency=1` | 130.6 s | 2.3 | 0.964 | 42.9 MB | 53.8 s |+| Remotion, HTML, default | 154.2 s | 1.9 | 0.964 | 42.9 MB | 61.1 s |++- motlab lost the most without a GPU. With `--encoder sw` it took 2.8 times as long at 1080p (27.0 s against 9.5 s) and 4.5 times as long at 4K (67.3 s against 14.8 s). Which part slowed down, the drawing in SwiftShader or the software encoder at 4K, was not measured.+- At 1080p motlab was still the fastest: 19.2 s with 4 workers, against 28.3 s for HyperFrames and 46.7 s for Remotion at their fastest settings (1.5 and 2.4 times as long). With one worker it was about as fast as HyperFrames (27.0 s against 28.3 s).+- At 4K HyperFrames was the fastest. Its canvas setting took 43.4 s and its default HTML setting 50.7 s, against motlab's 60.7 s with 4 workers. motlab was still faster than Remotion (72.4 s at its fastest).+- HyperFrames barely changed: 1080p within 1 to 3 s of its GPU times, and at 4K it was faster on SwiftShader than on the integrated Radeon (43.4 s against 50.9 s on a canvas). Remotion took 1.2 to 2.5 times as long, most of all with HTML at 4K.+- The first motlab run of three settings took longer (46.3 s, 88.6 s and 131.5 s) because the encoder probe ran again (see quirks); the medians leave those runs out.++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.++## 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.+- 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.+- The hardware encoder hangs after a mid-stream `flush()`: the next `encode()` never finishes. Flush only once, at the end.+- Software H.264 ignores bitrate. Targets of 2, 22, 60 or 200 Mbit/s give nearly the same file. `quantizer` mode is not supported for software H.264. `contentHint: 'detail'` raises quality slightly but is slower.+- Hardware H.264 and HEVC support `bitrateMode: 'quantizer'`. QP is passed per frame with `encode(frame, { avc: { quantizer } })`.+- Colour tags in the bitstream are inconsistent: hardware H.264 writes none, hardware HEVC writes `colour_primaries=0`, and software H.264 writes an sRGB transfer. ffmpeg always overwrites the VUI with BT.709 limited range through `h264_metadata` or `hevc_metadata`.+- The encoder config needs a sensible `framerate`. 240 is rejected.+- `shadowBlur` on a 2D canvas is expensive: 160 shadow blurs cap every pipeline at about 32 fps at 1080p.+- `willReadFrequently: true` makes the canvas CPU-backed and nearly halves WebCodecs speed. Do not use it on a render canvas.+- ffmpeg's `sine` source is very quiet (amplitude 1/8). Check synthetic audio with `volumedetect`.+- The ffmpeg build used for these measurements does not support `-pattern_type glob`. Use numbered patterns or make contact sheets from the video.diff --git a/docs/viewer.md b/docs/viewer.mdnew file mode 100644index 0000000..9f59f97--- /dev/null+++ b/docs/viewer.md@@ -0,0 +1,159 @@+# The viewer++```bash+motlab edit <project>+```++This opens the project in the viewer at `http://127.0.0.1:4173/p/<folder>/`, prints the address and ends. When no viewer is running yet, it starts one first. The viewer is a server that runs in the background until it is stopped, and it only listens on `127.0.0.1`:++```bash+motlab start # the viewer, without opening a project+motlab stop # end it (an export that is running is cancelled)+motlab restart # stop it and start it again from the same folder, for example after motlab update+```++`motlab start` prints the address; a second `start` says it is already running. The server's output goes to `~/.motlab/viewer.log`. `motlab start --foreground` runs the server in the terminal instead, until Ctrl+C.++One viewer holds many projects. The project name in the header is a menu of the motlab projects it knows: the folders with a `project.json` up to four levels under the folder `motlab edit` was started from (without `node_modules`, `out`, `backup` and hidden folders), and every project opened with `motlab edit` before, which is remembered in `~/.motlab/recent.json`. A project on another drive shows up in the menu after it has been opened once. The folder the menu scans is the one the viewer was started from, by `motlab start` or by the `motlab edit` that started it. `motlab edit` without a project prints the viewer's address, which opens the first project it finds. If port 4173 belongs to something else, the viewer takes the next free port up to 4190, and `motlab edit`, `stop` and `restart` find it there. The left panel lists the scenes and audio files, the middle shows the preview with the play controls, and the bottom has a timeline of scenes and audio with waveforms.++The viewer is for looking and pointing, not editing. It does not watch files, so reload the page after the project changes.++## Language++The viewer's text is in English or Indonesian. It follows the browser: Indonesian when one of the browser's languages is Indonesian, English otherwise. The last row of the project menu switches to the other language ("Bahasa Indonesia" or "English") and reloads the page, and the browser remembers the choice. This page names the controls in English. In Indonesian, Notes and Note are Catatan, Save is Simpan, Delete is Hapus, Mark done is Tandai selesai, Reopen is Buka lagi, Done is Selesai, Open is Buka, Cancel is Batalkan, "New version from this one" is "Versi baru dari ini" and Main is Utama.++## Versions++The name after the project in the header is the version menu. It lists every project file in the folder (see [Versions](projects.md#versions)), with `project.json` as "Main". "New version from this one" asks for a name and copies the open version to `project-<name>.json`, then opens it; the agent changes what is in it. The open version is in the address as `?v=project-tiktok.json`, and Export renders that version to `out/<folder>-<version>-<resolution>.mp4`. `selection.json` names the version a click was made in as `project`.++## Keys and controls++| Action | How |+|---|---|+| Play and pause | Space (on a focused button, Space presses that button instead) |+| Step one frame, one second | Left and Right arrows on the focused timeline, with Shift for one second |+| Jump to start or end | Home and End on the focused timeline |+| Previous or next scene | the buttons next to play |+| Zoom the timeline | Ctrl+scroll or a trackpad pinch, the magnifier buttons, or `+`, `-` and `0` on the focused timeline |+| Scroll a zoomed timeline | its scrollbar, Shift+scroll, or plain scroll when there is no vertical scroll |+| Mark a range | the range button in the play toolbar (or `R`), then drag on the timeline; or Shift+drag on the timeline; or `I` and `O` at the playhead for its start and end; drag an edge or its blue head to change it |+| Make the scene a range | `X`, for the scene under the playhead |+| Remove the range | the × in the range bar, or Escape when no note is open |+| A note with a box | drag on the preview, then type |+| A note on one spot | click on the preview without dragging, then type |+| A note on a range | mark the range, then Note in the range bar |+| Save and close a note | Enter, Save, Escape, or a click on the empty grey space around the preview (Shift+Enter is a new line) |+| Open a note | its row under Notes, its number on the timeline, or a click on its box |+| Delete a note | Delete in the open note |+| Mark a note done | Mark done in the open note; Reopen opens it again |+| See the done notes | Done at the end of the Notes list |+| Hide the timeline | the last button in the play toolbar |+| Hide the side panel | the button in the top left |+| Full screen | the button in the top right of the preview |++Every button in the toolbars has a tooltip with its shortcut, and resting the pointer on the timeline for a second lists the timeline's keys.++The timeline zooms up to 24 px per frame, and close in the ruler gets a tick per frame. While it plays zoomed in, the view follows the playhead. Hiding the timeline gives the preview the whole canvas, up to the side panel, or the full width with the panel closed. The browser remembers that choice and the last export resolution.++Over the preview the cursor is a +. It is dark over light parts of the frame and white over dark ones.++## selection.json++Every click on a scene, an audio clip or a point on the timeline is saved to `selection.json` in the project folder, so you can tell an agent "this one" in chat. The range and every note are saved with it:++```json+{+ "project": "project.json",+ "time": 0.947,+ "scene": "scenes/01-judul.html",+ "sceneIndex": 1,+ "sceneTime": 0.947,+ "frame": 28,+ "transition": null,+ "audio": null,+ "range": { "start": 2.2, "end": 6.133, "scenes": [1, 2] },+ "marks": [+ {+ "n": 1,+ "note": "Batang ketiga harusnya lebih tinggi",+ "time": 6.42, "scene": "scenes/02-grafik.html", "sceneIndex": 2, "sceneTime": 3.42, "frame": 102, "transition": null,+ "box": { "x": 531, "y": 577, "w": 964, "h": 437 },+ "point": null,+ "range": null,+ "image": "selection/1.png",+ "project": "project.json"+ }+ ]+}+```++| Field | Meaning |+|---|---|+| `project` | the project file in use, so a click in one cut is not taken for another |+| `time` | seconds from the start of the video, where the click landed |+| `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 |+| `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 |++Each note in `marks` has its number `n`, an `id` the page gives it (notes from before ids have none), the text `note`, where it was made (the same fields as a click), and one of:++| Field | Meaning |+|---|---|+| `box` | `{ x, y, w, h }` in the scene's own pixels at `?scale=1`, the units the scene code uses |+| `point` | `{ x, y }` in the same units |+| `range` | `{ start, end, scenes }`, as above |++`image` is `selection/<n>.png` for a box or point: that frame with the note's box or point and number drawn on it, as on screen. `project` is the version the note was made in. `done: true` marks a note as done; an open note has no `done`.++A range marks a stretch of time, for a note such as "seconds 3 to 5 are too slow". The range button in the play toolbar turns blue and the page says to drag on the timeline; the drag marks the range and the button turns off again, so the next drag scrubs as usual. The range is a light blue band over the whole timeline with a blue head at the top of each edge, like the playhead's, to drag it by, and a range bar appears next to the play toolbar with its start, end and length, Note to write a note about it, and × to remove it. While there is a range, Play starts at its start and goes round inside it; a click elsewhere while playing plays on from there. A click on the timeline moves the playhead and keeps the range.++## Notes++A note says what is wrong at one spot, so a whole review can be written down while watching and handed to the agent at once ("kerjakan semua catatan"). Drag a box over the part, or click one spot, and a card opens under it to type in. A box or point belongs to the frame it was drawn on and shows only on that frame, with its number in a small blue tag. Several notes can sit on one frame. A note on a range is about a stretch of time instead.++Notes stay until they are deleted. They are numbered in the order they were made and listed under Notes in the side panel, and their numbers sit in a row on the timeline under the time labels; a range note draws a line to the end of its range. A click on either goes to the note's frame (and its range) and opens it. A click on the preview while a note is open only closes it, so a stray click does not make a new note.++A note that has been dealt with can be marked done, by the user with Mark done in the open note or by the agent with `"done": true` in `selection.json`. A done note leaves the preview and the timeline and moves under Done at the end of the list, folded, so the list holds what is left for the next round. The number next to Notes counts the open notes only. A done note opened from the list shows on its frame again, says Done in its head, and Reopen makes it an open note again when the fix was not right.++The agent writes `done` into the file while the page is open. So the viewer keeps the file's `done` for every note it did not change itself, and the server sends back which notes are done after each save. The page also reads the file again when it gets focus back, so a note the agent marked done moves under Done without a reload. A note the agent deletes from the file is gone from the page then too.++Notes work in full screen too: the card opens over the full-screen preview and takes typing, and Save writes the note. On a touch screen a finger drag draws a box like the mouse does, and a tap on Save saves it (tried in a windowed Chrome over the DevTools protocol, with touch emulated).++Two tabs on the same project can both take notes. A save names the notes the tab deleted instead of leaving them out, so notes made in the other tab are kept, and a new note whose number the other tab took first moves to the next free number, with its picture drawn again. After every save, and when a tab gets focus back, the page takes in the file's notes: the other tab's new ones, the ones it deleted, and done marks. Tried in a windowed Chrome over the DevTools protocol with two tabs: tab B's first note became 2 next to tab A's 1, each tab listed the other's notes after a focus change, a note deleted in B stayed deleted when A saved again, and every picture showed its own number. Two tabs editing the text of the same note still keep whichever saved last.++Each version has its own notes. The numbers run across all versions of the folder, so "catatan 3" means one note. The selection is written about 0.15 s after the last change, so scrubbing and typing do not write a file per pointer move or key. The last selection and the notes are loaded again when the page opens.++`selection.json`, `selection.png` (from before notes) and `selection/` are in `.gitignore`.++## 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.++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.++## 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.++When the viewer opens, it goes through the scenes one at a time for their length and a few thumbnails (one per 2 seconds, at most 12 per scene). After that only three scene pages stay loaded: the one on screen and its neighbours. The next scene is loaded ahead while playing, and its first frame is drawn once, so footage in it has already sought to its start when playback reaches the cut. A test project with 45 scenes (2:15) opened in about 4 seconds. A project of 20 WebGL scenes (ten three.js scenes with a rigged GLB, ten p5.js WebGL scenes) and a 60-minute AAC file opened, played across scene cuts and jumped to scene 19 without a lost WebGL context, since no more than three pages are loaded at once. Audio plays through WebAudio, and the audio clock drives the playhead, so picture and sound cannot drift apart.++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.++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.++Measured on a 16-scene, 30 fps, 1080x1920 talking-head project with 1440x1440 footage, in the desktop app's browser on the AMD integrated GPU of the test laptop:++| | Before | After |+|---|---|---|+| `renderAt` calls per second while playing | about 213 (one per display refresh) | 29 to 30 |+| First frame after a cut into a footage scene | 161 to 221 ms | 10 to 17 ms |++One frame of those scenes took 4.7 to 6.6 ms to draw, and the same at `?scale=0.5`, so a lower preview resolution would not help them. Not yet measured in a normal Chrome window at 60 or 144 Hz.++The page loads Plus Jakarta Sans from Google Fonts and falls back to the system font offline. Its visual design is described in [DESIGN.md](../DESIGN.md).diff --git a/example/audio/musik.wav b/example/audio/musik.wavnew file mode 100644index 0000000..6c92bd7Binary files /dev/null and b/example/audio/musik.wav differdiff --git a/example/audio/tik.wav b/example/audio/tik.wavnew file mode 100644index 0000000..6d68c4bBinary files /dev/null and b/example/audio/tik.wav differdiff --git a/example/audio/whoosh.wav b/example/audio/whoosh.wavnew file mode 100644index 0000000..938dd35Binary files /dev/null and b/example/audio/whoosh.wav differdiff --git a/example/project.json b/example/project.jsonnew file mode 100644index 0000000..0d84cb3--- /dev/null+++ b/example/project.json@@ -0,0 +1,14 @@+{+ "fps": 30,+ "scenes": [+ "scenes/01-judul.html",+ "scenes/02-grafik.html",+ "scenes/03-selesai.html"+ ],+ "audio": [+ { "file": "audio/musik.wav", "start": 0, "volume": 0.6 },+ { "file": "audio/whoosh.wav", "start": 2.2, "volume": 0.8 },+ { "file": "audio/whoosh.wav", "start": 5.7, "volume": 0.8 },+ { "file": "audio/tik.wav", "start": 7.3, "volume": 0.9 }+ ]+}diff --git a/example/scenes/01-judul.html b/example/scenes/01-judul.htmlnew file mode 100644index 0000000..692bffa--- /dev/null+++ b/example/scenes/01-judul.html@@ -0,0 +1,26 @@+<!doctype html><html><head><meta charset="utf-8"><title>01 judul</title></head><body style="margin:0"><canvas id="c"></canvas>+<script src="lib.js"></script>+<script>+// Title on cream. The orange dot grows until it fills the frame, which is where scene 2 starts.+const WIPE = 2.2;+scene(3, t => {+ ctx.fillStyle = CREAM; ctx.fillRect(0, 0, W, H);+ const push = 1 + 0.03 * t / 3; // slow push in, so nothing is ever still+ ctx.translate(W / 2, H / 2); ctx.scale(push, push); ctx.translate(-W / 2, -H / 2);++ ctx.textBaseline = 'alphabetic'; ctx.font = `700 220px ${FONT}`;+ const word = 'motlab', width = ctx.measureText(word).width; let x = (W - width) / 2;+ for (const [i, ch] of [...word].entries()) { // letters rise and fade in one after another+ const p = ease(prog(t, 0.2 + i * 0.07, 0.9 + i * 0.07));+ ctx.globalAlpha = p; ctx.fillStyle = INK; ctx.fillText(ch, x, 560 + (1 - p) * 40);+ x += ctx.measureText(ch).width;+ }+ const p = ease(prog(t, 0.9, 1.6));+ ctx.globalAlpha = p; ctx.font = `400 46px ${FONT}`; ctx.textAlign = 'center';+ ctx.fillText('video dari kode, dirender di Chrome', W / 2, 660 + (1 - p) * 20); ctx.textAlign = 'left';++ const grow = prog(t, WIPE, 3), r = 22 * ease(prog(t, 0.6, 1.1)) + 2300 * grow * grow;+ ctx.globalAlpha = 1; ctx.fillStyle = ORANGE;+ ctx.beginPath(); ctx.arc((W + width) / 2 + 44, 540, r, 0, Math.PI * 2); ctx.fill();+});+</script></body></html>diff --git a/example/scenes/02-grafik.html b/example/scenes/02-grafik.htmlnew file mode 100644index 0000000..bb29513--- /dev/null+++ b/example/scenes/02-grafik.html@@ -0,0 +1,23 @@+<!doctype html><html><head><meta charset="utf-8"><title>02 grafik</title></head><body style="margin:0"><canvas id="c"></canvas>+<script src="lib.js"></script>+<script>+// Bars on orange. The last bar turns dark and grows until it fills the frame, which is where scene 3 starts.+const BARS = [0.35, 0.5, 0.42, 0.68, 0.9], WIPE = 2.7;+scene(3.5, t => {+ ctx.fillStyle = ORANGE; ctx.fillRect(0, 0, W, H);+ const head = ease(prog(t, 0.1, 0.8));+ ctx.globalAlpha = head * (1 - prog(t, WIPE, WIPE + 0.3)); ctx.fillStyle = '#fff'; ctx.textAlign = 'center';+ ctx.font = `700 84px ${FONT}`; ctx.fillText('Satu folder, satu perintah', W / 2, 230 + (1 - head) * 30); ctx.textAlign = 'left';++ const bw = 150, gap = 70, x0 = (W - (BARS.length * bw + (BARS.length - 1) * gap)) / 2, base = 900;+ for (const [i, v] of BARS.entries()) {+ const h = 560 * v * ease(prog(t, 0.5 + i * 0.12, 1.4 + i * 0.12)), last = i === BARS.length - 1, g = last ? prog(t, WIPE, 3.5) : 0;+ const k = g * g, x = x0 + i * (bw + gap);+ ctx.globalAlpha = last ? 1 : 1 - prog(t, WIPE, WIPE + 0.3);+ ctx.fillStyle = last && t > WIPE - 0.3 ? `rgb(${[255, 255, 255].map(c => Math.round(c + (22 - c) * prog(t, WIPE - 0.3, WIPE))).join(',')})` : '#fff';+ ctx.beginPath(); // the last bar spreads to every edge of the frame+ ctx.roundRect(x - x * k, base - h - (base - h) * k, bw + (W - bw) * k, h + (H - h) * k, 18 * (1 - k));+ ctx.fill();+ }+});+</script></body></html>diff --git a/example/scenes/03-selesai.html b/example/scenes/03-selesai.htmlnew file mode 100644index 0000000..362049b--- /dev/null+++ b/example/scenes/03-selesai.html@@ -0,0 +1,27 @@+<!doctype html><html><head><meta charset="utf-8"><title>03 selesai</title></head><body style="margin:0"><canvas id="c"></canvas>+<script src="lib.js"></script>+<script>+// Dark end card: a ring draws itself, then the tick, then the line of text.+scene(2.5, t => {+ ctx.fillStyle = INK; ctx.fillRect(0, 0, W, H);+ const push = 1 + 0.04 * t / 2.5;+ ctx.translate(W / 2, H / 2); ctx.scale(push, push); ctx.translate(-W / 2, -H / 2);++ ctx.lineWidth = 16; ctx.lineCap = 'round'; ctx.lineJoin = 'round'; ctx.strokeStyle = ORANGE;+ const ring = ease(prog(t, 0.2, 1.1));+ ctx.beginPath(); ctx.arc(W / 2, 440, 120, -Math.PI / 2, -Math.PI / 2 + Math.PI * 2 * ring); ctx.stroke();++ const tick = ease(prog(t, 0.9, 1.4)), pts = [[W / 2 - 52, 444], [W / 2 - 12, 484], [W / 2 + 58, 400]];+ if (tick > 0) { // two segments, drawn in order+ const a = Math.min(1, tick * 2), b = Math.max(0, tick * 2 - 1);+ ctx.strokeStyle = CREAM; ctx.beginPath(); ctx.moveTo(...pts[0]);+ ctx.lineTo(pts[0][0] + (pts[1][0] - pts[0][0]) * a, pts[0][1] + (pts[1][1] - pts[0][1]) * a);+ if (b > 0) ctx.lineTo(pts[1][0] + (pts[2][0] - pts[1][0]) * b, pts[1][1] + (pts[2][1] - pts[1][1]) * b);+ ctx.stroke();+ }++ const p = ease(prog(t, 1.1, 1.8));+ ctx.globalAlpha = p; ctx.fillStyle = CREAM; ctx.textAlign = 'center'; ctx.font = `700 72px ${FONT}`;+ ctx.fillText('Selesai. MP4 siap.', W / 2, 720 + (1 - p) * 24); ctx.textAlign = 'left';+});+</script></body></html>diff --git a/example/scenes/lib.js b/example/scenes/lib.jsnew file mode 100644index 0000000..282384a--- /dev/null+++ b/example/scenes/lib.js@@ -0,0 +1,14 @@+// Shared by the example scenes: a 1920x1080 canvas (times ?scale=) and the page contract.+const q = new URLSearchParams(location.search), S = parseFloat(q.get('scale') || '1'), W = 1920, H = 1080;+const cv = document.getElementById('c'); cv.width = W * S; cv.height = H * S;+const ctx = cv.getContext('2d');+const CREAM = '#F4F1EA', INK = '#161616', ORANGE = '#FF5B2E', FONT = '"Segoe UI", system-ui, sans-serif';+const clamp = (x, a = 0, b = 1) => Math.min(b, Math.max(a, x));+const ease = x => 1 - Math.pow(1 - clamp(x), 3); // fast, then slow+const prog = (t, a, b) => clamp((t - a) / (b - a)); // 0..1 between seconds a and b++function scene(total, draw) {+ window.TOTAL = total;+ window.renderAt = t => { ctx.setTransform(S, 0, 0, S, 0, 0); ctx.globalAlpha = 1; draw(t); };+ window.ready = document.fonts.ready.then(() => window.renderAt(parseFloat(q.get('t') || '0')));+}diff --git a/install.js b/install.jsnew file mode 100644index 0000000..4dcf646--- /dev/null+++ b/install.js@@ -0,0 +1,105 @@+#!/usr/bin/env node+// Installs motlab from this folder: npm packages, a `motlab` command on PATH and the agent skills (motlab, motlab-assets).+//+// node install.js engine, command and the skills for Claude Code+// node install.js --skill agents the skills in ~/.agents/skills (Codex, Cursor, OpenCode, Copilot, Gemini CLI, Amp, Windsurf)+// node install.js --skill claude,antigravity several agents at once (see SKILL_DIRS; none for no skills)+// node install.js --skill-dir <dir> the skills in any other agent's skill folder+// node install.js --link link the skills to this folder instead of copying them (for working on a skill)+// node install.js --bin <dir> where the `motlab` command goes (default ~/.local/bin)+// node install.js --dry-run print what would happen and change nothing+// node install.js --update the skills again where they went last time (what `motlab update` runs)+//+// Where the skills, the launcher and --link went is kept in ~/.motlab/install.json for --update. It never installs+// Chrome, ffmpeg or Python; it says how to get them.+import { spawnSync } from 'node:child_process';+import { chmodSync, cpSync, existsSync, lstatSync, mkdirSync, readFileSync, readlinkSync, realpathSync, rmSync, symlinkSync, writeFileSync } from 'node:fs';+import { homedir } from 'node:os';+import { delimiter, dirname, join, resolve } from 'node:path';+import { fileURLToPath } from 'node:url';+import { parseArgs } from 'node:util';++const HERE = dirname(fileURLToPath(import.meta.url)), WIN = process.platform === 'win32', HOME = homedir();+// Each agent's user skill folder, from its docs (November 2026). ~/.agents/skills is the shared one: Codex reads only that,+// and Cursor, OpenCode, Copilot, Gemini CLI, Amp and Windsurf read it too. Claude Code and Antigravity do not.+const AGENTS = join(HOME, '.agents', 'skills');+const SKILL_DIRS = {+ claude: join(HOME, '.claude', 'skills'),+ agents: AGENTS,+ codex: AGENTS,+ antigravity: join(HOME, '.gemini', 'config', 'skills'), // the one folder both the Antigravity App and the CLI (agy) read+ opencode: join(HOME, '.config', 'opencode', 'skills'),+ cursor: join(HOME, '.cursor', 'skills'),+ copilot: join(HOME, '.copilot', 'skills'),+};++const { values: o } = parseArgs({ options: {+ skill: { type: 'string' }, 'skill-dir': { type: 'string', multiple: true }, link: { type: 'boolean' }, bin: { type: 'string' },+ update: { type: 'boolean' }, 'dry-run': { type: 'boolean' }, force: { type: 'boolean' }, help: { type: 'boolean', short: 'h' },+} });+if (o.help) { console.log(`usage: node install.js [--skill ${Object.keys(SKILL_DIRS).join('|')}|none[,...]] [--skill-dir <dir>] [--link] [--bin <dir>] [--update] [--force] [--dry-run]`); process.exit(0); }+// --update puts the skills where they went before: the folders in the record, and any agent folder above that already+// has the motlab skill (an install from before there was a record). --skill and --skill-dir add to them.+const RECORD = join(HOME, '.motlab', 'install.json');+let last = {}; if (o.update) try { last = JSON.parse(readFileSync(RECORD, 'utf8')); } catch {}+const found = o.update ? Object.values(SKILL_DIRS).filter(d => existsSync(join(d, 'motlab', 'SKILL.md'))) : [];+const targets = (o.skill ?? (o.update ? 'none' : 'claude')).split(',').map(t => t.trim()).filter(t => t && t !== 'none');+const bad = targets.filter(t => !SKILL_DIRS[t]);+if (bad.length) { console.error(`unknown --skill ${bad.join(', ')}; use ${Object.keys(SKILL_DIRS).join(', ')}, none, or --skill-dir <dir>`); process.exit(1); }+const skillDirs = [...new Set([...targets.map(t => SKILL_DIRS[t]), // codex and agents are one folder+ ...(o['skill-dir'] || []).map(d => resolve(d.replace(/^~(?=$|[\\/])/, HOME))), ...(last.skillDirs || []), ...found])];+const link = o.link ?? !!last.link;+const dry = o['dry-run'], say = s => console.log(dry ? `[dry run] ${s}` : s);++if (Number(process.versions.node.split('.')[0]) < 24) { console.error(`motlab needs Node 24 or newer; this is ${process.version}.`); process.exit(1); }++// 1. npm packages+say(`npm ci in ${HERE}`);+if (!dry) {+ const r = spawnSync('npm ci --no-audit --no-fund', { cwd: HERE, stdio: 'inherit', shell: true }); // one string: npm is npm.cmd on Windows+ if (r.status !== 0) { console.error('npm ci failed. Fix the error above and run the installer again.'); process.exit(1); }+}++// 2. the `motlab` command: small launchers that run this folder's bin/motlab.js+const bin = resolve(o.bin || last.bin || join(HOME, '.local', 'bin')), entry = join(HERE, 'bin', 'motlab.js');+const launchers = WIN+ ? [['motlab.cmd', `@node "${entry}" %*\r\n`], ['motlab', `#!/bin/sh\nexec node "${entry.replaceAll('\\', '/')}" "$@"\n`]] // cmd/PowerShell, Git Bash+ : [['motlab', `#!/bin/sh\nexec node "${entry}" "$@"\n`]];+for (const [name, body] of launchers) {+ say(`write ${join(bin, name)}`);+ if (!dry) { mkdirSync(bin, { recursive: true }); writeFileSync(join(bin, name), body); if (!WIN) chmodSync(join(bin, name), 0o755); }+}+const onPath = (process.env.PATH || '').split(delimiter).some(p => p && resolve(p).toLowerCase() === bin.toLowerCase());+if (!onPath) console.log(`\n${bin} is not on PATH yet. Add it, then open a new terminal:\n ${WIN+ ? `[Environment]::SetEnvironmentVariable('Path', [Environment]::GetEnvironmentVariable('Path', 'User') + ';${bin}', 'User') (PowerShell)`+ : `echo 'export PATH="${bin}:$PATH"' >> ~/.profile`}\n`);++// 3. the skills+if (o.update && !skillDirs.length) say('no skill folders from an earlier install; pass --skill to add the skills');+for (const dir of skillDirs) for (const name of ['motlab', 'motlab-assets']) {+ const src = join(HERE, 'skills', name), dest = join(dir, name);+ let stat = null; try { stat = lstatSync(dest); } catch {}+ const isLink = stat?.isSymbolicLink();+ if (isLink && realpathSync(dest) === realpathSync(src)) say(`skill already linked to this folder: ${dest}`);+ else {+ if (stat) {+ // A link is removed as a link (never through it); a directory that is not ours needs --force.+ if (isLink) say(`remove the old link ${dest} -> ${readlinkSync(dest)}`);+ else if (!existsSync(join(dest, 'SKILL.md')) && !o.force) { console.error(`${dest} exists and is not a skill. Move it away or pass --force.`); process.exit(1); }+ else say(`replace ${dest}`);+ if (!dry) rmSync(dest, isLink ? {} : { recursive: true, force: true });+ }+ say(link ? `link ${dest} -> ${src}` : `copy ${src} -> ${dest}`);+ if (!dry) { mkdirSync(dirname(dest), { recursive: true }); link ? symlinkSync(src, dest, WIN ? 'junction' : 'dir') : cpSync(src, dest, { recursive: true }); }+ }+}++if (!dry) { mkdirSync(dirname(RECORD), { recursive: true }); writeFileSync(RECORD, JSON.stringify({ skillDirs, link, bin }, null, 2) + '\n'); }++// 4. what is still missing on this machine+if (!dry) {+ console.log('\nChecking the machine:');+ const { doctor } = await import('./src/doctor.js');+ const code = doctor();+ console.log(code ? '\nInstall what is marked FAIL, then run `motlab doctor` again.' : `\nDone. Try: motlab edit "${join(HERE, 'example')}"`);+}diff --git a/package-lock.json b/package-lock.jsonnew file mode 100644index 0000000..d2035eb--- /dev/null+++ b/package-lock.json@@ -0,0 +1,55 @@+{+ "name": "motlab",+ "version": "0.1.0",+ "lockfileVersion": 3,+ "requires": true,+ "packages": {+ "": {+ "name": "motlab",+ "version": "0.1.0",+ "license": "MIT",+ "dependencies": {+ "mediabunny": "1.65.2"+ },+ "bin": {+ "motlab": "bin/motlab.js"+ },+ "engines": {+ "node": ">=24"+ }+ },+ "node_modules/@types/dom-mediacapture-transform": {+ "version": "0.1.12",+ "resolved": "https://registry.npmjs.org/@types/dom-mediacapture-transform/-/dom-mediacapture-transform-0.1.12.tgz",+ "integrity": "sha512-d7/QsLRwF864A5mgIM/YrfiglHoYn7zgCcAoJgW404r+2DwnNr7EBbLnCWpmOMgH8y0te73L1AV6H1bmauaWFw==",+ "license": "MIT",+ "dependencies": {+ "@types/dom-webcodecs": "*"+ }+ },+ "node_modules/@types/dom-webcodecs": {+ "version": "0.1.13",+ "resolved": "https://registry.npmjs.org/@types/dom-webcodecs/-/dom-webcodecs-0.1.13.tgz",+ "integrity": "sha512-O5hkiFIcjjszPIYyUSyvScyvrBoV3NOEEZx/pMlsu44TKzWNkLVBBxnxJz42in5n3QIolYOcBYFCPZZ0h8SkwQ==",+ "license": "MIT"+ },+ "node_modules/mediabunny": {+ "version": "1.65.2",+ "resolved": "https://registry.npmjs.org/mediabunny/-/mediabunny-1.65.2.tgz",+ "integrity": "sha512-goZpibvo/5hkc/56WVNm93Ini+o7K4y8aXA20c/BN1B+m3L5aHQa8MTvO+S1APg/YI8kMILtrX6QCqUtxLW7bA==",+ "license": "MPL-2.0",+ "workspaces": [+ ".",+ "packages/*"+ ],+ "dependencies": {+ "@types/dom-mediacapture-transform": "^0.1.11",+ "@types/dom-webcodecs": "0.1.13"+ },+ "funding": {+ "type": "individual",+ "url": "https://github.com/sponsors/Vanilagy"+ }+ }+ }+}diff --git a/package.json b/package.jsonnew file mode 100644index 0000000..dd2c49f--- /dev/null+++ b/package.json@@ -0,0 +1,38 @@+{+ "name": "motlab",+ "version": "0.1.0",+ "private": true,+ "description": "Video as code: canvas scene pages rendered frame by frame in headless Chrome with WebCodecs, a project format with audio, a web viewer, and an agent skill that builds the scenes.",+ "license": "MIT",+ "repository": {+ "type": "git",+ "url": "git+https://github.com/staryone/motlab.git"+ },+ "homepage": "https://github.com/staryone/motlab#readme",+ "bugs": {+ "url": "https://github.com/staryone/motlab/issues"+ },+ "keywords": [+ "video",+ "motion-graphics",+ "canvas",+ "webcodecs",+ "headless-chrome",+ "agent-skills",+ "claude-code"+ ],+ "type": "module",+ "engines": {+ "node": ">=24"+ },+ "bin": {+ "motlab": "bin/motlab.js"+ },+ "scripts": {+ "test": "node --test",+ "doctor": "node bin/motlab.js doctor"+ },+ "dependencies": {+ "mediabunny": "1.65.2"+ }+}diff --git a/skills/motlab-assets/SKILL.md b/skills/motlab-assets/SKILL.mdnew file mode 100644index 0000000..3644599--- /dev/null+++ b/skills/motlab-assets/SKILL.md@@ -0,0 +1,141 @@+---+name: motlab-assets+description: Make reusable assets as code for motlab videos, without any AI image, video or 3D generator: icons, illustrations, vector logos, rigged 2D characters, 3D objects, transitions, textures and backgrounds, kept in one kit so every video looks the same. Outputs transparent PNG plus SVG, or GLB, FBX and OBJ with PBR textures. Use whenever someone asks for assets, an asset kit, a mascot, an icon set, a 3D model or textures, even if they never say motlab.+---++# motlab-assets++Build assets as code and keep them in a **kit**: one folder with the style rules, the source of every asset and its+rendered files. A motlab video copies the kit into its project and draws from it, so the tenth video looks like the+first. Nothing here uses an AI image, video or 3D model: you write SVG, canvas, three.js and Blender code, and+ordinary renderers (Chrome, Blender) draw the pixels.++**The source is the asset.** Every asset has a source file you wrote (`source.svg`, `parts.svg` + `rig.json`,+`build.py`, `transition.js`). PNG, GLB, FBX, OBJ and texture maps are outputs of that source. A change is made in the+source and the outputs are rendered again; never edit an output by hand. That is what keeps variations consistent.++**Good references in, good assets out.** Work from the user's references: brand guidelines, logos, product photos,+sketches, screenshots, a 3D viewer recording, style examples. If a reference is too small or missing, ask for a better+one. Don't draw a logo or a real product from memory.++## Tools++- This skill's folder: `scripts/` and `templates/` below.+- The motlab engine: run `motlab --help` once; it prints the engine folder. The motlab skill's scripts are in+ `<engine>/skills/motlab/scripts/`: `blender/kit.py` and `blender/mesh_from_sdf.py` (3D), `grid.py` (read coordinates+ off a reference), `get_font.py` (Google Fonts). `motlab stills` renders every PNG on the 2D and light 3D paths.+- Python 3 with numpy, scipy and Pillow (the motlab skill's `requirements.txt`). Commands say `python`; on macOS and+ Linux it may be `python3`.+- Blender, only for the main 3D path (below).++## The workflow++1. **Brief.** Ask what the assets are for (which videos, which brand or series), what is needed now, the sizes and+ orientation they will be used at, and which files the user wants besides PNG (SVG, GLB, FBX, OBJ, textures). Ask+ where the kit lives; the default is `kits/<name>/` in the user's workspace, outside any one video.+2. **Read the kit, if there is one.** Read `kit.json`, `style.md` and `tokens.json` first. New assets follow them. If a+ new asset needs a rule the kit does not have yet, add it to `style.md` and say so.+3. **References.** List and measure everything (size, format). Run `python scripts/palette.py <refs>` for the main+ colours. Write down what you can measure: line weight, corner radius, proportions, light direction, materials.+4. **Lock the style before building many assets.** For a new kit, write `tokens.json` and `style.md`+ (`references/kit.md`), build one hero asset, render it, and show the user a sheet with it next to the references.+ Wait for their OK here: a wrong style copied into twenty assets is twenty fixes. After that, build the rest without+ stopping.+5. **Build each asset** from its reference file:+ - 2D (icons, illustrations, logos, backgrounds, patterns, 2D characters, transitions): `references/2d.md`.+ - 3D (objects, products, simple characters, textures): `references/3d.md`. **Offer the two 3D paths first** (below).+6. **Render and export.** Each asset's folder gets its outputs (`references/kit.md` has the names). PNGs are transparent+ and at least 2x the largest size the asset will be shown at.+7. **Check it yourself.** `python scripts/sheet.py <sheet.jpg> <asset outputs> <refs>` and look at it: shapes against the+ references, edges on the checker (halos, missing alpha), sharpness at full size. `python scripts/palette.py check+ tokens.json <pngs>` for colour drift. For 3D, re-import every exported file (`asset3d.py check`) and look at the GLB+ through `templates/model.html`, which is how a motlab scene will show it.+8. **Hand over.** Update `kit.json`, rebuild the kit's `sheet.jpg`, and show the user the sheet and the list of files.+ Say what you could not check (an FBX opened in another program, a rig in motion, a texture at close range).+9. **Revisions.** The user names the asset and the change. Edit its source, render again, check again, and report what+ changed. Before a change that touches many assets, copy the kit to `backup/<n>/` inside it.++## The two 3D paths++When the user wants a 3D asset, say what each path gives and let them choose:++| | Light path | Main path |+|---|---|---|+| Needs | Python + Chrome only | Blender (4.2 or newer; tested on 5.2) |+| Model from | distance functions (`mesh_from_sdf.py`) | distance functions, Blender modelling, a GLB/OBJ the user owns, MPFB humans |+| Files | GLB, OBJ + MTL, PNG | GLB, FBX, OBJ + MTL, baked PBR textures (base colour, roughness, normal, AO), PNG |+| Materials | one flat colour, roughness and metalness per part | any Blender material, baked into textures |+| Rig | none | Rigify or MPFB armatures in FBX and GLB |+| PNG | three.js turntable (`templates/model.html`) | Cycles turntable, path traced |+| Time | seconds | about 30 s for the test mug: bake 7.5 s, export 2.3 s, four 1024 px views 16.5 s (RTX 3060 Laptop) |++For the main path, check the machine before promising anything, and tell the user what you found:++1. **Blender.** Find it: `blender` on PATH, `C:\Program Files\Blender Foundation\Blender <version>\blender.exe`,+ `/Applications/Blender.app/Contents/MacOS/Blender`, `/opt/homebrew/bin/blender`. If it is missing, say so and how to+ get it (blender.org, or `winget install BlenderFoundation.Blender` on Windows), and offer the light path meanwhile.+2. **Add-ons.** Run `blender -b -P scripts/blender/check_blender.py`. It prints the version, the GPU Cycles will use,+ and whether MPFB (human characters), a Blender MCP add-on and Rigify are installed and on. MPFB is needed only for+ human characters; without it, build characters from shapes.+3. **Blender MCP.** Also look for Blender MCP tools in this session (tool names with `blender` in them). If they are+ there, use them to show the user the model live in their own Blender window while it is built. If not, say it is+ not installed and carry on: every export and render goes through `blender -b -P build.py` either way, because+ `build.py` is the asset's source, a background run gives the same result every time, and MCP export calls can time+ out on large files. Point the user to the MCP's install guide only if they want the live view. Through the MCP,+ `kit.py` and `asset3d.py` import and run in the user's Blender (bake and export of a small mug took 2.3 s), but+ operators that need an active object, such as `bpy.ops.mesh.primitive_cylinder_add`, fail there: build meshes with+ `bmesh` and the data API instead.++## Kit layout++```+kits/<name>/+ kit.json what is in the kit: assets, their sources and outputs, licences+ style.md the style rules, in numbers where possible+ tokens.json colours, fonts, line weight, radii, shadow, light and lens+ refs/ copies of the references the kit was built from+ 2d/<asset>/ source.svg, asset.html, <asset>@4x.png+ chars/<name>/ parts.svg, rig.json, turnaround.svg, <name>@4x.png, poses.png+ 3d/<asset>/ build.py, mesh/, <asset>.glb, <asset>.fbx, <asset>.obj + .mtl, textures/, turntable/+ transitions/<name>/ transition.js, transition.html, frames/ (PNG sequence with alpha)+ sheet.jpg every asset on one sheet+```++`references/kit.md` has the formats of `kit.json`, `tokens.json` and `style.md`.++## Using a kit in a motlab video++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.++## Keep it above board++- Only build from references the user owns or may use, and only rebuild brands and products they own or have+ permission for. Record each reference's source in `kit.json`.+- Downloaded CC0 material (Poly Haven HDRIs and textures) and MPFB's CC0 assets still go in `kit.json` with where they+ came from.+- Fonts keep their licences; note them in `tokens.json`.+- No real people's likenesses without their consent.++## Scripts and templates++- `scripts/palette.py`: main colours of references; `check` measures assets against `tokens.json`.+- `scripts/sheet.py`: labelled review sheet of any images, transparency on a checker.+- `scripts/mesh_export.py`: light path, `.npz` meshes to GLB and OBJ + MTL with flat PBR colours.+- `scripts/blender/asset3d.py`: main path, `bake()`, `export()`, `turntable()`, and `check` to re-import files.+- `scripts/blender/check_blender.py`: Blender version, GPU and add-ons.+- `templates/asset.html`: SVG files to transparent PNG at any `--scale`.+- `templates/svgparts.js`: a rigged 2D character from `parts.svg` + `rig.json`, posed in a scene.+- `templates/transition.js` and `transition.html`: a transition as a layer over a hard cut, and its preview.+- `templates/model.html`: turntable stills of a GLB through three.js, transparent.++## Where to read more++| When you are… | Read |+|---|---|+| starting a kit, writing tokens and style rules, naming files | `references/kit.md` |+| making icons, illustrations, logos, backgrounds, 2D characters or transitions | `references/2d.md` |+| making 3D objects, characters or textures | `references/3d.md` |+| modelling a product from reference in Blender | the motlab skill's `references/blender.md` |diff --git a/skills/motlab-assets/references/2d.md b/skills/motlab-assets/references/2d.mdnew file mode 100644index 0000000..498fc6d--- /dev/null+++ b/skills/motlab-assets/references/2d.md@@ -0,0 +1,99 @@+# 2D assets: SVG, characters, transitions++Every 2D asset is an SVG you write by hand (or a canvas module, for transitions), rendered to PNG by Chrome+through `templates/asset.html`. Measured on the test laptop: a 400x600 SVG character to a 1600x2400 PNG in 2.6 s,+most of it Chrome starting.++## Writing the SVG++- A `viewBox` in the asset's size at 1080p (`0 0 400 600` for a figure 600 px tall in a 1080p frame), so the tokens'+ `px@1080` values are the SVG's own units.+- Colours, stroke width, joins and radii from `tokens.json`. Fills flat unless `style.md` says otherwise.+- Text outlined to paths, or the font loaded by the page that draws it. An SVG drawn as an image cannot load fonts by+ itself, so a live `<text>` falls back to a system font in the PNG.+- No `<image>` that points at another file and no external CSS: an SVG drawn as an image cannot fetch them. Embed a+ raster as a `data:` URL only when it truly is a photo.+- Group what moves or might be recoloured: `<g id="...">`, named as in `kit.md`.+- Redraw from the reference in its own pixel space: put the reference image under the SVG at the same size while+ drawing (`grid.py` from the motlab skill prints coordinates), then remove it. Check the result over the reference on+ `sheet.py`, not from memory.++## Rendering: templates/asset.html++Copy it next to the SVG, set `SRC`, `W`, `H` (the box at 1x) and `PAD`, then:++```+motlab stills asset.html out 0 --scale 4 # out/0.00.png at 4x+motlab stills asset.html out 0 1 2 --scale 4 # one PNG per file in SRC+```++Rename the outputs to `<asset>@4x.png`. Chrome rasterises the SVG at the drawn size, so 4x is as sharp as 1x. For an+icon set, put all icons in `SRC` and render them in one call.++## Icons, illustrations, backgrounds, patterns++- **Icon sets:** one grid for the whole set (for example 24 units with 2 units of padding), one stroke weight, the same+ corner radius and cap style. Build them in one session from the same rules, then put them side by side on one sheet:+ an odd one out shows at once.+- **Logos:** rebuild the user's logo as clean paths only from a good reference (a vector file, or a large PNG). Put the+ rebuild over the original at the same size on a sheet and check every curve. The user confirms it before it goes in+ the kit.+- **Backgrounds and patterns:** a pattern is an SVG `<pattern>` or a tile whose edges meet; check it by tiling the PNG+ 3x3 on a sheet. Grain or noise comes from a seeded function, so it is the same every render.++## 2D characters: parts.svg + rig.json++A character the scenes can pose is one SVG with every moving part as a top-level `<g id>` in the root `<svg>`,+back to front, and a `rig.json`:++```json+{ "parts": [+ { "id": "arm_l", "pivot": [102, 252], "parent": "torso" },+ { "id": "leg_l", "pivot": [165, 450] },+ { "id": "torso", "pivot": [200, 460] },+ { "id": "head", "pivot": [200, 230], "parent": "torso" },+ { "id": "arm_r", "pivot": [298, 252], "parent": "torso" } ] }+```++- `pivot` is in SVG units: a shoulder for an arm, the neck for the head, the hips for the torso. A part with a+ `parent` moves with it; a hand is a child of its forearm.+- Draw each part a little past its joint and cover the joint with the part in front (the sleeve over the top of the+ arm), so rotating it never opens a gap. Check the extreme poses, not just the rest pose.+- Things that change shape rather than turn (mouths, eyes, hands) are alternative groups: `mouth_smile`,+ `mouth_open`. The scene draws one of them; give each the same pivot.+- `templates/svgparts.js` draws it in a scene: `loadRig(svg, rig, res)` then `draw(ctx, x, y, pose, size)` with+ `pose = { head: { rot: -0.1 }, arm_r: { rot: 0.6, dx: 0, dy: 0, s: 1 } }`. Copy it into the video's project next to+ the kit. A pose is a plain object, so poses can live in the kit as JSON and be tweened in the scene.+- For a character drawn in one piece with detail too fine for parts (a painted illustration), use the motlab skill's+ puppet pins (`puppet.js`, `references/engine-2d-puppet.md`) on its PNG instead.++Outputs for a character:++- `<name>@4x.png`: the rest pose, through `asset.html`.+- `turnaround.svg`: front, three-quarter and side, drawn on one row at the same height with guide lines for eyes,+ shoulders, hips and feet. It is the reference for later poses and for a 3D version.+- `poses.png`: a few poses through a page that uses `svgparts.js` (copy `asset.html` and draw with the rig), which+ also proves the rig bends well.+- Expressions: one sheet with each mouth and eye group.++## 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).++- `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).+- 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+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`.diff --git a/skills/motlab-assets/references/3d.md b/skills/motlab-assets/references/3d.mdnew file mode 100644index 0000000..7869135--- /dev/null+++ b/skills/motlab-assets/references/3d.md@@ -0,0 +1,108 @@+# 3D assets: objects, characters, textures++Offer the two paths first (the table in `SKILL.md`), then build. Both start the same way: get the shape right against+the references before any material or render, as the motlab skill's `references/blender.md` describes (real model if+there is one, otherwise distance functions, check shots next to the reference from several angles).++All numbers below are from the test laptop (RTX 3060 Laptop, Blender 5.2, Chrome with ANGLE on Direct3D 11), on a+test mug of two parts with 194,646 vertices.++## Light path: Python and Chrome++1. Write the shape as distance functions with the motlab skill's `mesh_from_sdf.py` (copy the pattern of its+ `example_scene.py mesh`): one `.npz` per part that has its own colour.+2. Export: `python scripts/mesh_export.py <asset dir> <asset> body.npz:#E8743B:0.3 base.npz:#8C735F:0.8` writes+ `<asset>.glb` and `<asset>.obj` + `.mtl`. Each part is `file:#colour[:roughness[:metalness]]`. `--smooth 20` (the+ default) relaxes the surface like the Blender path's smooth modifier; use 0 for small sharp parts. 2.9 s for the mug,+ 9.3 MB GLB.+3. PNGs: copy `templates/model.html` next to the GLB, set `MODEL`, and run+ `motlab stills model.html turntable 0 1 2 3 4 5 6 7 --scale 2`. View `i` is at `t = i`, eight views round the+ object, lit from the upper left of the camera in every view. Four 1024 px views took 2.6 s.++Limits: no textures, no FBX, no rig, one flat material per part. Anything more is the main path.++## Main path: Blender++A `build.py` per asset, run with no window: `blender -b -P build.py -- <asset dir>`. It puts the motlab skill's+`scripts/blender` and this skill's `scripts/blender` on `sys.path`, builds the objects with `kit.py`, and calls+`asset3d.py`:++```python+import sys, os+HERE = os.path.dirname(os.path.abspath(__file__)); SKILLS = r'<engine>/skills' # from `motlab --help`+sys.path[:0] = [HERE, os.path.join(SKILLS, 'motlab', 'scripts', 'blender'), os.path.join(SKILLS, 'motlab-assets', 'scripts', 'blender')]+import bpy, math, kit, asset3d as A+from mathutils import Euler+OUT = os.path.abspath(sys.argv[sys.argv.index('--') + 1])+kit.fresh()+glaze = kit.mat('glaze', (0.9, 0.35, 0.15), 0.25, coat=0.5) # any node tree works: noise, bump, layered paint+root = kit.empty('mug'); root.rotation_quaternion = Euler((math.pi / 2, 0, 0)).to_quaternion() # SDF meshes are y-up+body = kit.load_npz(os.path.join(HERE, 'mesh', 'body.npz'), glaze, root)+A.bake(body, os.path.join(OUT, 'textures'), size=2048) # body_basecolor.png, body_roughness.png, body_normal.png+A.export([root], OUT, 'mug') # mug.glb, mug.fbx, mug.obj + mug.mtl+A.turntable([body], os.path.join(OUT, 'turntable'), views=8, width=2048, samples=64)+```++- **`bake(obj, out, size, maps)`** applies the modifiers, unwraps with Smart UV Project if the mesh has no UVs, bakes+ each map from all of the object's materials, saves `<object>_<map>.png`, and gives the object one new material that+ uses the maps. Maps: `basecolor`, `roughness`, `normal`, `ao`, `emission`. Cycles cannot bake metalness, so the+ highest metalness of the old materials is kept as one value. Two objects, three 1024 px maps each: 7.5 s.+ A normal map only carries detail the material adds (bump, noise); a smooth mesh bakes a flat normal map.+- **`export(objs, out, name)`** writes GLB and FBX with the textures inside, and OBJ + MTL pointing at the texture+ files where they are. Children of the given objects come along. 1.2 to 2.3 s over two runs; the mug was 11.6 MB GLB, 7.5 MB FBX and+ 26.1 MB OBJ.+- **`turntable(objs, out, views, width, samples, lens, elevation, light, world)`**: square, transparent PNGs from the+ front round the object; the key light turns with the camera. Use the kit's `light` and `camera` tokens. Four 1024 px+ views at 32 samples: 16.5 s.+- **Check the exports** in a clean Blender, then through three.js:++ ```+ blender -b --factory-startup -P scripts/blender/asset3d.py -- check mug.glb mug.fbx mug.obj+ motlab stills model.html check 0 2 --scale 1 (MODEL = 'mug.glb')+ ```++ `check` prints meshes, vertices, materials, images and size per file; all three should agree (the GLB counts a few+ more vertices because glTF splits vertices at UV seams). On the mug, all three came back with 2 meshes, 2 materials+ and 6 images.++### Size and detail++Distance-function meshes are dense. For a GLB that loads fast in a scene, add a Decimate modifier (`ratio` 0.2 to 0.5)+before `bake` and compare the turntable before and after. If the user wants smaller files still, glTF Transform+(`npx @gltf-transform/cli optimize in.glb out.glb`, MIT) compresses geometry and textures; it downloads from npm, so+ask first, and check the result in `model.html`, as a compressed GLB needs the matching decoder.++### Characters++- **Stylised characters** (a mascot, a toy-like figure): distance functions per body part, joined smoothly where they+ should read as one surface and kept separate where they move. Start from the 2D character's `turnaround.svg` so both+ versions match.+- **Human characters**: MPFB 2 (the MakeHuman plugin for Blender; code GPL, its assets CC0) if `check_blender.py`+ finds it. It builds a human with a skeleton. Not tested in this skill yet; read its documentation and render check+ poses before promising a result.+- **Rigs**: an armature parented to the mesh exports to FBX and GLB. Rigify ships with Blender but is off by default+ (`check_blender.py` shows it). Turn it on inside `build.py` with `addon_utils.enable('rigify', default_set=True)` and+ run Blender with `--factory-startup`, so the user's saved preferences stay as they were; without `default_set=True`+ its generate step fails on missing parameters. Export only the deform bones:+ `export_scene.gltf(..., export_def_bones=True, export_animations=True)` and+ `export_scene.fbx(..., use_armature_deform_only=True, bake_anim=True, add_leaf_bones=False)`. On a test figure (the+ human metarig, 706 bones of which 160 deform, a mesh bound with automatic weights, a 48-frame wave): 13 s, a 1.8 MB+ GLB and a 2.4 MB FBX. Re-imported in a clean Blender, both played the animation and followed a posed upper arm, and+ the GLB played through `mixer.setTime(t)` in `template-three.html` with the same stills both ways. Re-import and pose a+ bone like this before handing a rig over.++### Textures on their own++A material for the kit (a brand plastic, a paper, a fabric) is a `build.py` that makes the node tree on a plane or a+sphere, bakes it with `bake(..., maps=('basecolor', 'roughness', 'normal'))` at 2048 or 4096 px, and renders one+turntable view as the preview. For a tileable texture, bake on a plane with a 0 to 1 UV square and check the edges by+tiling the base colour 3x3 on `sheet.py`. HDRIs for lighting can come from Poly Haven (CC0); credit them in `kit.json`.++## Formats++- **GLB**: the one to use in motlab (`template-three.html`) and on the web. Metres, y-up, PBR materials and textures+ inside one file.+- **FBX**: for other 3D programs and game engines. Textures embedded. Scale written with `FBX_SCALE_ALL`, so it opens+ at the right size in Blender; check another program's import scale if the user names one.+- **OBJ + MTL**: the widest support, but no rig or animation, and PBR only through the `Pr`/`Pm` extension that Blender+ writes and reads. Keep the texture files next to it when copying.diff --git a/skills/motlab-assets/references/kit.md b/skills/motlab-assets/references/kit.mdnew file mode 100644index 0000000..ec3092b--- /dev/null+++ b/skills/motlab-assets/references/kit.md@@ -0,0 +1,95 @@+# The kit: tokens, style rules, names++A kit is only as consistent as its rules are measurable. "Friendly and bold" can't be checked; "6 px ink outlines at+1080p, 24 px corner radius, light from the upper left, no gradients on figures" can.++## tokens.json++The numbers every asset uses. Read them in code instead of typing values into each asset.++```json+{+ "color": {+ "ink": "#111111", "paper": "#FFF8EE",+ "brand": { "primary": "#FF5A1F", "secondary": "#FFC23D" },+ "skin": ["#F2B48C"]+ },+ "font": { "display": { "family": "Syne", "weight": 700, "licence": "OFL" }, "body": { "family": "Inter", "weight": 500, "licence": "OFL" } },+ "stroke": { "px@1080": 6, "join": "round", "cap": "round" },+ "radius": { "px@1080": 24 },+ "shadow": { "type": "flat", "offset@1080": [16, 18], "opacity": 0.25 },+ "light": { "from": "upper left", "blender": [-1, -1, 1.1] },+ "camera": { "lens_mm": 70, "elevation_deg": 12 }+}+```++- Colours are `#RRGGBB`. `palette.py check` reads every such string under `color`, in objects and lists alike.+- Sizes are given at 1080p (a 1920x1080 or 1080x1920 frame). An asset drawn at another size scales them.+- `light.blender` is the `light` argument of `asset3d.turntable()`; keep every 3D asset in a kit on the same one.++## style.md++Short and specific, one rule per line, in this order:++```markdown+# <kit name> style++## Shape+- Outlines: ink, 6 px at 1080p, round joins. Inner detail lines 4 px.+- Corners: 24 px radius on cards and panels; characters have no sharp corners.+- Proportions: characters are 3.5 heads tall; heads are circles.++## Colour+- Fills are flat. Gradients only on backgrounds, never on figures.+- Brand primary is for the hero object in a frame, at most one per frame.++## Light and depth+- Light from the upper left. Flat shadows 16/18 px down right, ink at 25%.+- 3D: one soft key light, upper left; 70 mm lens; 12 degree elevation.++## Don't+- No drop shadows with blur. No outlines on text. No pure white backgrounds (use paper).+```++When the user corrects an asset ("too thick", "warmer orange"), change the rule here first, then the asset, then any+other asset the rule touches.++## kit.json++```json+{+ "name": "acme",+ "version": 3,+ "refs": [ { "file": "refs/brand-guide.pdf", "from": "the user, Acme brand team" } ],+ "assets": [+ { "id": "kiko", "type": "char2d", "source": ["chars/kiko/parts.svg", "chars/kiko/rig.json"],+ "outputs": ["chars/kiko/[email protected]", "chars/kiko/poses.png"], "size@1080": [400, 600] },+ { "id": "mug", "type": "model", "path": "main", "source": ["3d/mug/build.py"],+ "outputs": ["3d/mug/mug.glb", "3d/mug/mug.fbx", "3d/mug/mug.obj", "3d/mug/textures/", "3d/mug/turntable/"] },+ { "id": "swish", "type": "transition", "source": ["transitions/swish/transition.js"], "outputs": ["transitions/swish/frames/"], "duration": 0.6 }+ ],+ "credits": [ { "what": "studio_small_09 HDRI", "from": "Poly Haven", "licence": "CC0" } ]+}+```++Types: `svg` (icons, illustrations, logos, backgrounds, patterns), `char2d`, `model`, `char3d`, `texture`,+`transition`. Raise `version` when a change alters assets that videos already use, and say in the hand-over which ones+changed, so the user knows which videos to copy the kit into again.++## Names++- Folder and file names in lowercase with hyphens: `2d/icon-upload/`, `3d/coffee-mug/`.+- PNG outputs are `<asset>@<scale>x.png`, where the scale is relative to `size@1080`.+- SVG groups and rig parts use `snake_case` with `_l` / `_r` for the character's own left and right: `arm_l`,+ `eye_r`. Draw order in the SVG is back to front.+- A variant is its own asset with the base id and a suffix (`kiko-winter`), built from the same source with a+ parameter, not copied and edited.++## Consistency checks for every hand-over++- `sheet.py` with the new assets next to the hero asset and the references.+- `palette.py check tokens.json` on every new PNG. A flat 2D asset should be under about 3% off palette (edges and+ anti-aliasing); much more means a colour outside the tokens. Shaded 3D renders are mostly off palette by nature, so+ compare their base colour texture instead.+- Line weight: measure an outline in the 4x PNG (it should be 4x the token).+- The same light and lens on every 3D turntable.diff --git a/skills/motlab-assets/scripts/blender/asset3d.py b/skills/motlab-assets/scripts/blender/asset3d.pynew file mode 100644index 0000000..66ea79b--- /dev/null+++ b/skills/motlab-assets/scripts/blender/asset3d.py@@ -0,0 +1,106 @@+# Blender helpers for a 3D asset: UVs, baked PBR textures, export to GLB + FBX + OBJ, a re-import check and a turntable.+# Your build.py puts this folder and the motlab skill's scripts/blender folder (kit.py, mesh_from_sdf.py) on sys.path, builds+# the objects with kit.py, then calls these. Run it with no window: blender -b -P build.py -- <out dir>+# Check exported files in a clean Blender: blender -b --factory-startup -P asset3d.py -- check model.glb model.fbx model.obj+import bpy, os, sys, math+from mathutils import Vector++def meshes(objs=None): return [o for o in (objs or bpy.context.scene.objects) if o.type == 'MESH']++def select(objs):+ bpy.ops.object.select_all(action='DESELECT')+ for o in objs: o.hide_set(False); o.select_set(True)+ bpy.context.view_layer.objects.active = objs[0]++def apply_modifiers(o): # bake and UVs work on the final shape+ select([o])+ for m in list(o.modifiers): bpy.ops.object.modifier_apply(modifier=m.name)++def unwrap(o, margin=0.02): # Smart UV Project when the mesh has no UVs. Hand-made seams are better for characters+ if o.data.uv_layers: return+ select([o]); bpy.ops.object.mode_set(mode='EDIT'); bpy.ops.mesh.select_all(action='SELECT')+ bpy.ops.uv.smart_project(angle_limit=math.radians(66), island_margin=margin); bpy.ops.object.mode_set(mode='OBJECT')++def _image_node(mat, img):+ n = mat.node_tree.nodes.new('ShaderNodeTexImage'); n.image = img; mat.node_tree.nodes.active = n; return n++def bake(o, out, size=2048, maps=('basecolor', 'roughness', 'normal'), samples=16):+ # Bakes the object's materials into PNG maps <name>_<map>.png in `out`, then gives the object one new material that+ # uses them, so every exporter carries the look. Procedural nodes, several materials and bump all end up in the maps.+ sc = bpy.context.scene; sc.render.engine = 'CYCLES'; sc.cycles.samples = samples+ apply_modifiers(o); unwrap(o); os.makedirs(out, exist_ok=True); name = o.name; files = {}+ kinds = {'basecolor': ('DIFFUSE', {'COLOR'}, 'sRGB'), 'roughness': ('ROUGHNESS', set(), 'Non-Color'), 'normal': ('NORMAL', set(), 'Non-Color'),+ 'ao': ('AO', set(), 'Non-Color'), 'emission': ('EMIT', set(), 'sRGB')}+ for m in maps:+ kind, passes, space = kinds[m]+ img = bpy.data.images.new(f'{name}_{m}', size, size, alpha=False, float_buffer=False); img.colorspace_settings.name = space+ tmp = [(mat, _image_node(mat, img)) for mat in o.data.materials if mat and mat.use_nodes]+ select([o]); sc.render.bake.margin = 8+ bpy.ops.object.bake(type=kind, pass_filter=passes, use_clear=True, margin=8)+ p = os.path.join(out, f'{name}_{m}.png'); img.filepath_raw = p; img.file_format = 'PNG'; img.save(); files[m] = p+ for mat, n in tmp: mat.node_tree.nodes.remove(n)+ print('BAKED', p, flush=True)+ mat = bpy.data.materials.new(f'{name}_baked'); mat.use_nodes = True; nt = mat.node_tree; P = nt.nodes['Principled BSDF']+ def tex(m, space):+ n = nt.nodes.new('ShaderNodeTexImage'); n.image = bpy.data.images.load(files[m]); n.image.colorspace_settings.name = space; return n+ if 'basecolor' in files: nt.links.new(tex('basecolor', 'sRGB').outputs['Color'], P.inputs['Base Color'])+ if 'roughness' in files: nt.links.new(tex('roughness', 'Non-Color').outputs['Color'], P.inputs['Roughness'])+ if 'normal' in files:+ nm = nt.nodes.new('ShaderNodeNormalMap'); nt.links.new(tex('normal', 'Non-Color').outputs['Color'], nm.inputs['Color']); nt.links.new(nm.outputs['Normal'], P.inputs['Normal'])+ metal = [mt.node_tree.nodes['Principled BSDF'].inputs['Metallic'].default_value for mt in o.data.materials if mt and mt.use_nodes and 'Principled BSDF' in mt.node_tree.nodes]+ P.inputs['Metallic'].default_value = max(metal) if metal else 0.0 # Cycles cannot bake metalness; one value is kept+ o.data.materials.clear(); o.data.materials.append(mat)+ return files++def export(objs, out, name, formats=('glb', 'fbx', 'obj')):+ # Writes <name>.glb and <name>.fbx with the textures inside, and <name>.obj + .mtl pointing at the texture files where they are. Modifiers are applied in the files.+ os.makedirs(out, exist_ok=True); objs = list(objs)+ for o in list(objs): # take parents and children along, so empties that place the parts are kept+ objs += [c for c in o.children_recursive if c not in objs]+ select(objs); done = []+ if 'glb' in formats:+ p = os.path.join(out, name + '.glb'); bpy.ops.export_scene.gltf(filepath=p, export_format='GLB', use_selection=True, export_apply=True); done.append(p)+ if 'fbx' in formats:+ p = os.path.join(out, name + '.fbx'); bpy.ops.export_scene.fbx(filepath=p, use_selection=True, apply_scale_options='FBX_SCALE_ALL', path_mode='COPY', embed_textures=True, use_mesh_modifiers=True); done.append(p)+ if 'obj' in formats:+ p = os.path.join(out, name + '.obj'); bpy.ops.wm.obj_export(filepath=p, export_selected_objects=True, export_materials=True, export_pbr_extensions=True, path_mode='RELATIVE', apply_modifiers=True); done.append(p)+ for p in done: print('EXPORTED', p, f'{os.path.getsize(p) / 1e6:.1f} MB', flush=True)+ return done++def bounds(objs):+ pts = [o.matrix_world @ Vector(c) for o in meshes(objs) for c in o.bound_box]+ lo = Vector((min(p.x for p in pts), min(p.y for p in pts), min(p.z for p in pts))); hi = Vector((max(p.x for p in pts), max(p.y for p in pts), max(p.z for p in pts)))+ return lo, hi++def turntable(objs, out, views=8, width=2048, samples=64, lens=70, elevation=12, light=(-1, -1, 1.1), world=0.04):+ # Renders `views` angles round the object, square, transparent PNG: <out>/view_00.png ... The camera and the key light+ # turn together, so every view is lit the same way. `light` is the light's direction seen from the front view (x right, y towards the object, z up).+ import kit+ from mathutils import Matrix+ sc = kit.setup(width, samples, 24, world=world); sc.render.resolution_y = width; sc.render.use_motion_blur = False+ lo, hi = bounds(objs); c = (lo + hi) / 2; r = (hi - lo).length / 2+ cam = kit.camera(); cam.data.lens = lens; d = r / math.tan(cam.data.angle / 2) * 1.08+ key = kit.key_light(tuple(c + Vector(light).normalized() * r * 6), size=(r * 4, r * 5), power=900 * r * r, target=tuple(c))+ os.makedirs(out, exist_ok=True); files = []+ for i in range(views):+ a = 2 * math.pi * i / views - math.pi / 2; e = math.radians(elevation)+ kit.look_at(cam, tuple(c + Vector((d * math.cos(e) * math.cos(a), d * math.cos(e) * math.sin(a), d * math.sin(e)))), tuple(c))+ lp = c + Matrix.Rotation(a + math.pi / 2, 3, 'Z') @ Vector(light).normalized() * r * 6+ key.location = lp; key.rotation_quaternion = (c - lp).to_track_quat('-Z', 'Y')+ p = os.path.join(out, f'view_{i:02d}.png'); sc.render.filepath = p; bpy.ops.render.render(write_still=True); files.append(p); print('VIEW', p, flush=True)+ return files++def check(paths): # imports each file into an empty scene and reports what came back+ for p in paths:+ bpy.ops.wm.read_factory_settings(use_empty=True); e = p.lower().rsplit('.', 1)[-1]+ if e in ('glb', 'gltf'): bpy.ops.import_scene.gltf(filepath=p)+ elif e == 'fbx': bpy.ops.import_scene.fbx(filepath=p)+ elif e == 'obj': bpy.ops.wm.obj_import(filepath=p)+ ms = meshes(); imgs = [i for i in bpy.data.images if i.type == 'IMAGE']+ verts = sum(len(o.data.vertices) for o in ms); mats = {m.name for o in ms for m in o.data.materials if m}+ lo, hi = bounds(ms) if ms else (Vector(), Vector())+ print(f'CHECK {os.path.basename(p)}: {len(ms)} meshes, {verts} vertices, {len(mats)} materials, {len(imgs)} images, size {tuple(round(v, 3) for v in (hi - lo))}', flush=True)++if __name__ == '__main__' and '--' in sys.argv:+ a = sys.argv[sys.argv.index('--') + 1:]+ if a and a[0] == 'check': check([os.path.abspath(p) for p in a[1:]])diff --git a/skills/motlab-assets/scripts/blender/check_blender.py b/skills/motlab-assets/scripts/blender/check_blender.pynew file mode 100644index 0000000..e7a06d3--- /dev/null+++ b/skills/motlab-assets/scripts/blender/check_blender.py@@ -0,0 +1,19 @@+# Reports what the Blender path can use on this machine: version, render device, and the add-ons that matter for assets.+# Run it with the user's own settings (no --factory-startup), so their add-ons and extensions are loaded:+# blender -b -P check_blender.py+import bpy, addon_utils+print('BLENDER', bpy.app.version_string, flush=True)+pr = bpy.context.preferences.addons['cycles'].preferences; device = 'CPU'+for kind in ('OPTIX', 'CUDA', 'METAL', 'HIP', 'ONEAPI'):+ try:+ pr.compute_device_type = kind; pr.get_devices()+ ds = [d.name for d in pr.devices if d.type == kind]+ if ds: device = f'{kind}: {", ".join(ds)}'; break+ except Exception: pass+print('DEVICE', device, flush=True)+enabled = {a.module for a in bpy.context.preferences.addons}+installed = {m.__name__ for m in addon_utils.modules()}+def find(*words): return sorted(m for m in installed | enabled if any(w in m.lower() for w in words))+for label, words in (('MPFB (human characters)', ('mpfb',)), ('Blender MCP add-on', ('mcp',)), ('Rigify', ('rigify',))):+ hits = find(*words)+ print('ADDON', label + ':', ', '.join(f'{h} ({"on" if h in enabled else "off"})' for h in hits) if hits else 'not installed', flush=True)diff --git a/skills/motlab-assets/scripts/mesh_export.py b/skills/motlab-assets/scripts/mesh_export.pynew file mode 100644index 0000000..e9edef1--- /dev/null+++ b/skills/motlab-assets/scripts/mesh_export.py@@ -0,0 +1,81 @@+# The light 3D path, without Blender: writes meshes made with mesh_from_sdf.py (.npz) as one GLB and one OBJ + MTL.+# Each part gets one flat PBR material (colour, roughness, metalness). No textures, no rig, no FBX: that is the Blender path.+# Usage: python mesh_export.py <out_dir> <name> <part.npz>:<#hex>[:<roughness>[:<metalness>]] ... [--smooth 20]+# --smooth N Laplacian smoothing passes (0.6 each), like the Blender path's smooth modifier. Default 20; 0 for small sharp parts+# The meshes are y-up, like glTF. Units are whatever the distance functions used.+import sys, os, json, struct+import numpy as np+from scipy import sparse++def load(path):+ d = np.load(path); v = d['v'].astype(np.float64); f = d['f'].astype(np.int64)+ if f.shape[1] == 4: f = np.concatenate([f[:, [0, 1, 2]], f[:, [0, 2, 3]]]) # quads to triangles+ return v, f++def smooth(v, f, n, k=0.6):+ if not n: return v+ e = np.concatenate([f[:, [0, 1]], f[:, [1, 2]], f[:, [2, 0]]]); e = np.concatenate([e, e[:, ::-1]])+ A = sparse.coo_matrix((np.ones(len(e)), (e[:, 0], e[:, 1])), shape=(len(v), len(v))).tocsr(); A.data[:] = 1+ deg = np.asarray(A.sum(1)).ravel(); deg[deg == 0] = 1+ for _ in range(n): v = v + k * (A @ v / deg[:, None] - v)+ return v++def normals(v, f):+ fn = np.cross(v[f[:, 1]] - v[f[:, 0]], v[f[:, 2]] - v[f[:, 0]]) # area-weighted+ n = np.zeros_like(v)+ for i in range(3): np.add.at(n, f[:, i], fn)+ return n / (np.linalg.norm(n, axis=1, keepdims=True) + 1e-12)++def srgb_to_linear(c): c = np.asarray(c); return np.where(c <= 0.04045, c / 12.92, ((c + 0.055) / 1.055) ** 2.4)++def parse(spec):+ p = spec.split(':'); path = p[0]+ if len(p) > 1 and len(p[0]) == 1: path = p[0] + ':' + p[1]; p = [path] + p[2:] # a Windows drive letter+ hx = (p[1] if len(p) > 1 else '#cccccc').lstrip('#'); rgb = [int(hx[i:i + 2], 16) / 255 for i in (0, 2, 4)]+ return path, rgb, float(p[2]) if len(p) > 2 else 0.5, float(p[3]) if len(p) > 3 else 0.0++def main():+ a = sys.argv[1:]; n = 20+ if '--smooth' in a: i = a.index('--smooth'); n = int(a[i + 1]); del a[i:i + 2]+ out, name, specs = a[0], a[1], a[2:]+ if not specs: sys.exit('usage: mesh_export.py <out_dir> <name> <part.npz>:<#hex>[:rough[:metal]] ... [--smooth 20]')+ os.makedirs(out, exist_ok=True)+ parts = []+ for s in specs:+ path, rgb, rough, metal = parse(s); v, f = load(path); v = smooth(v, f, n); parts.append((os.path.splitext(os.path.basename(path))[0], v.astype(np.float32), normals(v, f).astype(np.float32), f.astype(np.uint32), rgb, rough, metal))++ # GLB: one buffer, one mesh and node per part, all under one root node+ blob = bytearray(); views = []; acc = []; meshes = []; mats = []; nodes = []+ def add_view(arr, target):+ while len(blob) % 4: blob.append(0)+ views.append({'buffer': 0, 'byteOffset': len(blob), 'byteLength': arr.nbytes, 'target': target}); blob.extend(arr.tobytes()); return len(views) - 1+ for i, (pn, v, nr, f, rgb, rough, metal) in enumerate(parts):+ acc.append({'bufferView': add_view(v, 34962), 'componentType': 5126, 'count': len(v), 'type': 'VEC3', 'min': v.min(0).tolist(), 'max': v.max(0).tolist()})+ acc.append({'bufferView': add_view(nr, 34962), 'componentType': 5126, 'count': len(nr), 'type': 'VEC3'})+ acc.append({'bufferView': add_view(f.ravel(), 34963), 'componentType': 5125, 'count': f.size, 'type': 'SCALAR'})+ mats.append({'name': pn, 'pbrMetallicRoughness': {'baseColorFactor': [*srgb_to_linear(rgb).tolist(), 1], 'metallicFactor': metal, 'roughnessFactor': rough}})+ meshes.append({'name': pn, 'primitives': [{'attributes': {'POSITION': 3 * i, 'NORMAL': 3 * i + 1}, 'indices': 3 * i + 2, 'material': i}]})+ nodes.append({'name': pn, 'mesh': i})+ nodes.append({'name': name, 'children': list(range(len(parts)))})+ while len(blob) % 4: blob.append(0)+ doc = {'asset': {'version': '2.0', 'generator': 'motlab-assets mesh_export.py'}, 'scene': 0, 'scenes': [{'nodes': [len(parts)]}], 'nodes': nodes, 'meshes': meshes,+ 'materials': mats, 'accessors': acc, 'bufferViews': views, 'buffers': [{'byteLength': len(blob)}]}+ js = json.dumps(doc, separators=(',', ':')).encode(); js += b' ' * (-len(js) % 4)+ glb = os.path.join(out, name + '.glb')+ with open(glb, 'wb') as fh:+ fh.write(struct.pack('<III', 0x46546C67, 2, 12 + 8 + len(js) + 8 + len(blob)))+ fh.write(struct.pack('<II', len(js), 0x4E4F534A)); fh.write(js); fh.write(struct.pack('<II', len(blob), 0x004E4942)); fh.write(blob)++ # OBJ + MTL (Kd in sRGB, as most importers expect; Pr/Pm are the PBR extension Blender reads)+ with open(os.path.join(out, name + '.mtl'), 'w', newline='\n') as m:+ for pn, _, _, _, rgb, rough, metal in parts: m.write(f'newmtl {pn}\nKd {rgb[0]:.4f} {rgb[1]:.4f} {rgb[2]:.4f}\nPr {rough:.3f}\nPm {metal:.3f}\n\n')+ with open(os.path.join(out, name + '.obj'), 'w', newline='\n') as o:+ o.write(f'mtllib {name}.mtl\n'); base = 1+ for pn, v, nr, f, *_ in parts:+ o.write(f'o {pn}\nusemtl {pn}\n')+ o.write(''.join(f'v {x:.5f} {y:.5f} {z:.5f}\n' for x, y, z in v)); o.write(''.join(f'vn {x:.4f} {y:.4f} {z:.4f}\n' for x, y, z in nr))+ o.write(''.join(f'f {a}//{a} {b}//{b} {c}//{c}\n' for a, b, c in (f + base))); base += len(v)+ tris = sum(len(p[3]) for p in parts)+ print(f'{glb} ({os.path.getsize(glb) / 1e6:.1f} MB), {name}.obj, {name}.mtl: {len(parts)} parts, {tris} triangles')++if __name__ == '__main__': main()diff --git a/skills/motlab-assets/scripts/palette.py b/skills/motlab-assets/scripts/palette.pynew file mode 100644index 0000000..5e48e65--- /dev/null+++ b/skills/motlab-assets/scripts/palette.py@@ -0,0 +1,49 @@+# Colours of a kit. Reads the main colours out of references, and checks rendered assets against the kit's tokens.json.+# python palette.py <image> ... [--k 8] main colours of the references, with their share of the opaque pixels+# python palette.py check <tokens.json> <image> ... share of each asset's opaque pixels that is off the palette+# Colour distance is CIE76 delta E in Lab: under 2.3 is about the smallest visible step, over 10 is a different colour.+# Anti-aliased edges, shading and gradients are off-palette by nature, so read `check` as a trend across assets, not a pass mark.+import sys, json, os, glob+import numpy as np+from PIL import Image+from scipy.cluster.vq import kmeans2++def lab(rgb): # sRGB 0..255 -> CIE Lab (D65)+ c = rgb / 255.0; c = np.where(c <= 0.04045, c / 12.92, ((c + 0.055) / 1.055) ** 2.4)+ xyz = c @ np.array([[0.4124, 0.2126, 0.0193], [0.3576, 0.7152, 0.1192], [0.1805, 0.0722, 0.9505]]) / np.array([0.95047, 1.0, 1.08883])+ f = np.where(xyz > 216 / 24389, np.cbrt(xyz), (24389 / 27 * xyz + 16) / 116)+ return np.stack([116 * f[:, 1] - 16, 500 * (f[:, 0] - f[:, 1]), 200 * (f[:, 1] - f[:, 2])], 1)++def pixels(path, n=200000):+ im = Image.open(path).convert('RGBA'); im.thumbnail((800, 800)); a = np.asarray(im).reshape(-1, 4)+ a = a[a[:, 3] > 200][:, :3].astype(np.float64) # opaque pixels only+ if len(a) > n: a = a[np.random.default_rng(0).choice(len(a), n, replace=False)]+ return a++def files(args): return [f for s in args for f in (sorted(glob.glob(os.path.join(s, '*.png')) + glob.glob(os.path.join(s, '*.jpg'))) if os.path.isdir(s) else [s])]++def hexes(tokens): # every "#rrggbb" string anywhere under "color"+ out = {}+ def walk(v, k):+ if isinstance(v, dict): [walk(x, f'{k}.{n}' if k else n) for n, x in v.items()]+ elif isinstance(v, list): [walk(x, f'{k}.{i}') for i, x in enumerate(v)]+ elif isinstance(v, str) and v.startswith('#') and len(v) == 7: out[k] = v+ walk(tokens.get('color', tokens), ''); return out++a = sys.argv[1:]+if a and a[0] == 'check':+ toks = hexes(json.load(open(a[1], encoding='utf-8'))); names = list(toks)+ if not toks: sys.exit('no "#rrggbb" colours under "color" in ' + a[1])+ T = lab(np.array([[int(h[i:i + 2], 16) for i in (1, 3, 5)] for h in toks.values()], np.float64))+ for f in files(a[2:]):+ L = lab(pixels(f)); d = np.sqrt(((L[:, None] - T[None]) ** 2).sum(-1)); near = d.argmin(1); dm = d.min(1)+ used = ', '.join(f'{names[i]} {np.mean(near == i) * 100:.0f}%' for i in np.argsort(-np.bincount(near, minlength=len(names)))[:4] if np.any(near == i))+ print(f'{os.path.basename(f)}: {np.mean(dm > 10) * 100:.1f}% off palette (dE > 10), median dE {np.median(dm):.1f}; nearest: {used}')+else:+ k = int(a[a.index('--k') + 1]) if '--k' in a else 8+ if '--k' in a: i = a.index('--k'); del a[i:i + 2]+ px = np.concatenate([pixels(f) for f in files(a)])+ cent, lbl = kmeans2(px, k, minit='++', seed=0); share = np.bincount(lbl, minlength=k) / len(lbl)+ for i in np.argsort(-share):+ if share[i] < 0.005: continue+ r, g, b = np.clip(cent[i], 0, 255).round().astype(int); print(f'#{r:02X}{g:02X}{b:02X} {share[i] * 100:5.1f}%')diff --git a/skills/motlab-assets/scripts/sheet.py b/skills/motlab-assets/scripts/sheet.pynew file mode 100644index 0000000..de84240--- /dev/null+++ b/skills/motlab-assets/scripts/sheet.py@@ -0,0 +1,25 @@+# Tile images into one labelled review sheet. Transparent PNGs sit on a grey checker, so a halo or a missing alpha shows.+# Put the user's references in the same call to see the assets next to them.+# Usage: python sheet.py <out.jpg> <image or folder> ... [--cols 4] [--cell 512]+import sys, os, glob+from PIL import Image, ImageDraw+a = sys.argv[1:]; opt = lambda k, d: int(a[a.index(k) + 1]) if k in a else d+cols, cell = opt('--cols', 4), opt('--cell', 512)+for k in ('--cols', '--cell'):+ if k in a: i = a.index(k); del a[i:i + 2]+out, srcs = a[0], a[1:]+fs = []+for s in srcs: fs += sorted(f for e in ('png', 'jpg', 'jpeg', 'webp') for f in glob.glob(os.path.join(s, f'*.{e}'))) if os.path.isdir(s) else [s]+if not fs: sys.exit('no images found')+def checker(n, sq=16):+ im = Image.new('RGB', (n, n), (200, 200, 200)); d = ImageDraw.Draw(im)+ for y in range(0, n, sq):+ for x in range((y // sq) % 2 * sq, n, sq * 2): d.rectangle([x, y, x + sq - 1, y + sq - 1], fill=(170, 170, 170))+ return im+lab = 28; sheet = Image.new('RGB', (cell * cols, (cell + lab) * ((len(fs) + cols - 1) // cols)), (24, 24, 24)); bg = checker(cell)+for i, f in enumerate(fs):+ im = Image.open(f).convert('RGBA'); w, h = im.size; k = min(cell / w, cell / h); im = im.resize((max(1, round(w * k)), max(1, round(h * k))), Image.LANCZOS)+ tile = bg.copy(); tile.paste(im, ((cell - im.width) // 2, (cell - im.height) // 2), im)+ x, y = (i % cols) * cell, (i // cols) * (cell + lab); sheet.paste(tile, (x, y + lab))+ ImageDraw.Draw(sheet).text((x + 8, y + 8), f'{os.path.basename(f)} {w}x{h}', fill='white')+sheet.save(out, quality=88); print(out, len(fs), 'images')diff --git a/skills/motlab-assets/templates/asset.html b/skills/motlab-assets/templates/asset.htmlnew file mode 100644index 0000000..de84588--- /dev/null+++ b/skills/motlab-assets/templates/asset.html@@ -0,0 +1,35 @@+<!doctype html>+<html lang="en"><head><meta charset="utf-8"><title>Asset still</title>+<style>html,body{margin:0;height:100%;background:repeating-conic-gradient(#c8c8c8 0 25%,#aaa 0 50%) 0 0/32px 32px} body{display:flex;align-items:center;justify-content:center} canvas{max-width:100vw;max-height:100vh;display:block}</style>+</head><body><canvas id="c"></canvas>+<script type="module">+// Draws SVG files to a transparent PNG at any size: one file per time, so t = 0 is SRC[0], t = 1 is SRC[1] ...+// motlab stills asset.html <out> 0 1 2 --scale 4 -> 0.00.png, 1.00.png, 2.00.png at W*4 x H*4+// Chrome rasterises the SVG at the drawn size, so the PNG is sharp at any scale. Fonts used in the SVG must be outlined+// to paths, or be loaded by this page (@font-face) and named the same way, or Chrome falls back to a system font.+// Page contract: renderAt(t), TOTAL, ready, ?t=, ?scale=.+const SRC = ['source.svg']; // paths from this page+const W = 1024, H = 1024; // the box at scale 1; each SVG is fitted inside it, keeping its aspect ratio+const PAD = 0; // empty margin inside the box, in scale-1 pixels+const q = new URLSearchParams(location.search), SCALE = parseFloat(q.get('scale') || '1');+const cv = document.getElementById('c'); cv.width = Math.round(W * SCALE / 2) * 2; cv.height = Math.round(H * SCALE / 2) * 2;+const ctx = cv.getContext('2d');++async function svgImage(url, w, h) { // an <img> sized up front so Chrome rasterises the vector at that size+ const text = await (await fetch(url)).text(), doc = new DOMParser().parseFromString(text, 'image/svg+xml'), svg = doc.documentElement;+ const vb = (svg.getAttribute('viewBox') || `0 0 ${parseFloat(svg.getAttribute('width'))} ${parseFloat(svg.getAttribute('height'))}`).split(/[\s,]+/).map(Number);+ const k = Math.min(w / vb[2], h / vb[3]); svg.setAttribute('width', vb[2] * k); svg.setAttribute('height', vb[3] * k);+ const img = new Image(); img.src = URL.createObjectURL(new Blob([new XMLSerializer().serializeToString(svg)], { type: 'image/svg+xml' }));+ await img.decode(); return img;+}++let imgs = [];+function render(t) {+ ctx.clearRect(0, 0, cv.width, cv.height);+ const img = imgs[Math.min(imgs.length - 1, Math.max(0, Math.floor(t)))];+ ctx.drawImage(img, (cv.width - img.width) / 2, (cv.height - img.height) / 2);+}++window.TOTAL = SRC.length; window.renderAt = t => render(t);+window.ready = Promise.all(SRC.map(s => svgImage(s, (cv.width - 2 * PAD * SCALE), (cv.height - 2 * PAD * SCALE)))).then(r => { imgs = r; render(parseFloat(q.get('t') || '0')); return true; });+</script></body></html>diff --git a/skills/motlab-assets/templates/model.html b/skills/motlab-assets/templates/model.htmlnew file mode 100644index 0000000..954f985--- /dev/null+++ b/skills/motlab-assets/templates/model.html@@ -0,0 +1,49 @@+<!doctype html>+<html lang="en"><head><meta charset="utf-8"><title>Model turntable</title>+<style>html,body{margin:0;height:100%;background:repeating-conic-gradient(#c8c8c8 0 25%,#aaa 0 50%) 0 0/32px 32px} body{display:flex;align-items:center;justify-content:center} canvas{max-width:100vw;max-height:100vh;display:block}</style>+<script type="importmap">{ "imports": {+ "three": "https://cdn.jsdelivr.net/npm/[email protected]/build/three.module.min.js",+ "three/addons/": "https://cdn.jsdelivr.net/npm/[email protected]/examples/jsm/"+} }</script>+</head><body><canvas id="c"></canvas>+<script type="module">+// Turntable stills of a GLB on a transparent background, for the light 3D path and to check any GLB the way three.js+// (and so a motlab scene) will show it. View i is at t = i: motlab stills model.html <out> 0 1 2 3 4 5 6 7 --scale 2+// Page contract: renderAt(t), TOTAL, ready, ?t=, ?scale=. three.js comes from the CDN, so it needs the network.+import * as THREE from 'three';+import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';+import { RoomEnvironment } from 'three/addons/environments/RoomEnvironment.js';++const MODEL = 'model.glb'; // path from this page+const W = 1024, H = 1024, VIEWS = 8, ELEVATION = 12, LENS = 70; // LENS in mm on a 36 mm film back, like Blender+const q = new URLSearchParams(location.search), SCALE = parseFloat(q.get('scale') || '1');+const cv = document.querySelector('#c'), ctx = cv.getContext('2d');+cv.width = Math.round(W * SCALE); cv.height = Math.round(H * SCALE);++const gl = new THREE.WebGLRenderer({ antialias: true, alpha: true, preserveDrawingBuffer: true });+gl.setPixelRatio(1); gl.setSize(cv.width, cv.height, false); gl.setClearColor(0x000000, 0);+gl.toneMapping = THREE.AgXToneMapping; gl.outputColorSpace = THREE.SRGBColorSpace;+const scene = new THREE.Scene();+scene.environment = new THREE.PMREMGenerator(gl).fromScene(new RoomEnvironment(), 0.04).texture; scene.environmentIntensity = 0.35;+const cam = new THREE.PerspectiveCamera(2 * Math.atan(18 / LENS) * 180 / Math.PI, W / H, 0.01, 1000);+const key = new THREE.DirectionalLight('#ffffff', 3); scene.add(key, key.target);+let c = new THREE.Vector3(), d = 1, r = 1;++async function load() {+ const gltf = await new GLTFLoader().loadAsync(MODEL); scene.add(gltf.scene);+ const box = new THREE.Box3().setFromObject(gltf.scene); c = box.getCenter(new THREE.Vector3()); r = box.getSize(new THREE.Vector3()).length() / 2;+ d = r / Math.tan(cam.fov * Math.PI / 360) * 1.08; cam.near = d / 100; cam.far = d * 10; cam.updateProjectionMatrix();+ key.target.position.copy(c);+}++function render(t) {+ const a = (Math.floor(t) % VIEWS) / VIEWS * Math.PI * 2, e = ELEVATION * Math.PI / 180; // view 0 looks at the model's front (+z)+ cam.position.set(c.x + d * Math.cos(e) * Math.sin(a), c.y + d * Math.sin(e), c.z + d * Math.cos(e) * Math.cos(a)); cam.lookAt(c);+ const l = new THREE.Vector3(-1, 1.1, 1).normalize().applyAxisAngle(new THREE.Vector3(0, 1, 0), a); // upper left of the camera, turning with it+ key.position.copy(c).addScaledVector(l, r * 6);+ gl.render(scene, cam); ctx.clearRect(0, 0, cv.width, cv.height); ctx.drawImage(gl.domElement, 0, 0);+}++window.TOTAL = VIEWS; window.renderAt = t => render(t);+window.ready = load().then(() => { render(parseFloat(q.get('t') || '0')); return true; });+</script></body></html>diff --git a/skills/motlab-assets/templates/svgparts.js b/skills/motlab-assets/templates/svgparts.jsnew file mode 100644index 0000000..3a19618--- /dev/null+++ b/skills/motlab-assets/templates/svgparts.js@@ -0,0 +1,53 @@+// A 2D character (or any object with moving parts) from one SVG and its rig.json, for motlab scene pages.+// The SVG keeps each part as a top-level <g id="..."> in the root <svg>; rig.json names the parts back to front, each+// with a pivot in the SVG's own units and an optional parent, so a hand follows the forearm it hangs from.+//+// rig.json: { "parts": [ { "id": "arm_r", "pivot": [412, 380] }, { "id": "torso", "pivot": [360, 520] },+// { "id": "head", "pivot": [360, 300], "parent": "torso" }, ... ] }+//+// import { loadRig } from './svgparts.js';+// const kiko = await loadRig('assets/kits/acme/chars/kiko/parts.svg', 'assets/kits/acme/chars/kiko/rig.json', 2 * SCALE);+// kiko.draw(ctx, x, y, { head: { rot: -0.1 }, arm_r: { rot: 0.6 } }, 0.5); // x, y: where the SVG's origin goes; 0.5: drawn size+//+// A pose entry is { rot, dx, dy, s } (radians, SVG units, scale), all optional and relative to the drawn SVG. Parts are+// rasterised once at `res` pixels per SVG unit, so pass at least the largest size the part is drawn at. Parts the+// rig does not name are drawn as they are, behind the named ones.+export async function loadRig(svgUrl, rigUrl, res = 1) {+ const [text, rig] = await Promise.all([fetch(svgUrl).then(r => r.text()), fetch(rigUrl).then(r => r.json())]);+ const doc = new DOMParser().parseFromString(text, 'image/svg+xml'), root = doc.documentElement;+ const vb = (root.getAttribute('viewBox') || `0 0 ${parseFloat(root.getAttribute('width'))} ${parseFloat(root.getAttribute('height'))}`).split(/[\s,]+/).map(Number);+ const named = new Set(rig.parts.map(p => p.id)), groups = [...root.children].filter(e => e.tagName === 'g' && e.id);+ for (const id of named) if (!groups.some(g => g.id === id)) throw new Error(`rig.json names "${id}", but ${svgUrl} has no top-level <g id="${id}">`);+ const w = Math.ceil(vb[2] * res), h = Math.ceil(vb[3] * res);+ async function only(keep) { // the SVG with only these top-level groups visible, as an image of the whole viewBox+ const s = root.cloneNode(true); s.setAttribute('width', w); s.setAttribute('height', h);+ for (const g of [...s.children]) if (g.tagName === 'g' && g.id && !keep(g.id)) g.setAttribute('display', 'none');+ const img = new Image(); img.src = URL.createObjectURL(new Blob([new XMLSerializer().serializeToString(s)], { type: 'image/svg+xml' }));+ await img.decode(); return img;+ }+ const rest = groups.some(g => !named.has(g.id)) ? await only(id => !named.has(id)) : null;+ const imgs = Object.fromEntries(await Promise.all(rig.parts.map(async p => [p.id, await only(id => id === p.id)])));+ const byId = Object.fromEntries(rig.parts.map(p => [p.id, p]));++ function matrix(id, pose, memo) { // the part's transform in SVG units, after its parents'+ if (memo[id]) return memo[id];+ const p = byId[id], m = p.parent ? DOMMatrix.fromMatrix(matrix(p.parent, pose, memo)) : new DOMMatrix(), o = pose[id] || {};+ const [px, py] = p.pivot || [0, 0];+ m.translateSelf((o.dx || 0) + px, (o.dy || 0) + py).rotateSelf((o.rot || 0) * 180 / Math.PI).scaleSelf(o.s ?? 1).translateSelf(-px, -py);+ return (memo[id] = m);+ }+ return {+ viewBox: vb, parts: rig.parts.map(p => p.id),+ draw(ctx, x, y, pose = {}, size = 1) {+ const base = ctx.getTransform(), memo = {};+ ctx.save(); ctx.translate(x, y); ctx.scale(size, size); ctx.translate(-vb[0], -vb[1]);+ const at = ctx.getTransform();+ if (rest) { ctx.setTransform(at.multiply(new DOMMatrix([1 / res, 0, 0, 1 / res, vb[0], vb[1]]))); ctx.drawImage(rest, 0, 0); }+ for (const p of rig.parts) {+ ctx.setTransform(at.multiply(matrix(p.id, pose, memo)).multiply(new DOMMatrix([1 / res, 0, 0, 1 / res, vb[0], vb[1]])));+ ctx.drawImage(imgs[p.id], 0, 0);+ }+ ctx.restore(); ctx.setTransform(base);+ },+ };+}diff --git a/skills/motlab-assets/templates/transition.html b/skills/motlab-assets/templates/transition.htmlnew file mode 100644index 0000000..b04b3ff--- /dev/null+++ b/skills/motlab-assets/templates/transition.html@@ -0,0 +1,26 @@+<!doctype html>+<html lang="en"><head><meta charset="utf-8"><title>Transition preview</title>+<style>html,body{margin:0;height:100%;background:repeating-conic-gradient(#c8c8c8 0 25%,#aaa 0 50%) 0 0/32px 32px} body{display:flex;align-items:center;justify-content:center} canvas{max-width:100vw;max-height:100vh;display:block}</style>+</head><body><canvas id="c"></canvas>+<script type="module">+// Plays a transition.js over a transparent frame, from p = 0 to 1 over its DURATION. Check it at the cut (t = DURATION / 2+// must be fully covered) and write the frames as a PNG sequence with alpha:+// motlab stills transition.html <out> 0 0.1 0.2 0.3 0.4 0.5 0.6 --scale 1+// With BEHIND on, scene A and scene B are drawn behind it as two flat cards, to judge the motion; turn it off for the PNGs.+import { draw, DURATION } from './transition.js';+const W = 1920, H = 1080, BEHIND = false;+const q = new URLSearchParams(location.search), SCALE = parseFloat(q.get('scale') || '1');+const cv = document.querySelector('#c'), ctx = cv.getContext('2d');+cv.width = Math.round(W * SCALE); cv.height = Math.round(H * SCALE);+function render(t) {+ const p = Math.max(0, Math.min(1, t / DURATION));+ ctx.setTransform(1, 0, 0, 1, 0, 0); ctx.clearRect(0, 0, cv.width, cv.height); ctx.setTransform(SCALE, 0, 0, SCALE, 0, 0);+ if (BEHIND) { ctx.fillStyle = p < 0.5 ? '#2b3a55' : '#e9e4d8'; ctx.fillRect(0, 0, W, H); ctx.fillStyle = p < 0.5 ? '#fff' : '#111'; ctx.font = '700 160px system-ui'; ctx.textAlign = 'center'; ctx.textBaseline = 'middle'; ctx.fillText(p < 0.5 ? 'A' : 'B', W / 2, H / 2); }+ draw(ctx, p, W, H);+}+window.TOTAL = DURATION; window.renderAt = t => render(t);+window.ready = Promise.resolve().then(() => {+ if (q.has('t') || window.top !== window) render(parseFloat(q.get('t') || '0')); else (function tick(n) { render((n / 1000) % (DURATION + 0.4)); requestAnimationFrame(tick); })(0);+ return true;+});+</script></body></html>diff --git a/skills/motlab-assets/templates/transition.js b/skills/motlab-assets/templates/transition.jsnew file mode 100644index 0000000..330205e--- /dev/null+++ b/skills/motlab-assets/templates/transition.js@@ -0,0 +1,32 @@+// 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.+//+// 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);+// // next scene's renderAt, after everything else: const p = swish.atStart(t); if (p !== null) swish.draw(ctx, p, W, H);+//+// draw() works in the page's own pixels (call it under ctx.setTransform(SCALE, 0, 0, SCALE, 0, 0)). At p = 0.5 the+// frame must be fully covered, so the cut does not show. Colours come from the kit's tokens.json.+export const DURATION = 0.6; // seconds, half on each side of the cut+const COLORS = ['#FF5A1F', '#FFC23D', '#111111']; // back to front; the last one covers the cut+const ANGLE = -0.35; // radians the bands lean++const clamp01 = v => Math.max(0, Math.min(1, v));+const inOut = k => (k = clamp01(k)) < 0.5 ? 4 * k * k * k : 1 - Math.pow(-2 * k + 2, 3) / 2;++export function draw(ctx, p, W, H) {+ const reach = Math.hypot(W, H), lag = 0.08; // each band trails the one in front of it+ ctx.save(); ctx.translate(W / 2, H / 2); ctx.rotate(ANGLE);+ const n = COLORS.length, span = 0.5 - (n - 1) * lag; // each band covers in `span`; the last one is done exactly at the cut+ COLORS.forEach((col, i) => { // back bands lead in, and the front band leaves first+ const a = inOut((p - i * lag) / span); // 0 -> 1 while covering+ const b = inOut((p - 0.5 - (n - 1 - i) * lag) / span); // 0 -> 1 while uncovering+ const x0 = -reach / 2 + reach * b, x1 = -reach / 2 + reach * a;+ if (x1 > x0) { ctx.fillStyle = col; ctx.fillRect(x0, -reach / 2, x1 - x0, reach); }+ });+ ctx.restore();+}++export const atEnd = (t, total) => { const s = total - DURATION / 2; return t >= s ? 0.5 * (t - s) / (DURATION / 2) : null; }; // 0 -> 0.5+export const atStart = t => t < DURATION / 2 ? 0.5 + 0.5 * t / (DURATION / 2) : null; // 0.5 -> 1diff --git a/skills/motlab/SKILL.md b/skills/motlab/SKILL.mdnew file mode 100644index 0000000..f6f0a85--- /dev/null+++ b/skills/motlab/SKILL.md@@ -0,0 +1,287 @@+---+name: motlab+description: Make and edit videos as code with the motlab engine, with no AI video or image generation: product and app ads, logo animations, explainers, tutorials, screen-recording and footage edits, social clips. The agent builds every scene from the user's references and opens the motlab viewer; the user leaves notes there and exports the video. Use whenever someone asks for a video, animation, motion ad, promo, explainer, reel or short, mentions motlab, or gives notes on one.+---++# motlab++Build a video as code and put it in the motlab viewer, where the user plays it, steps through it frame by frame and+points at what to change. Everything is code, so a note such as "slower here" means changing a number and reloading.+No AI model makes any picture or video.++**The split of work.** The user gives a folder of high-quality references (pictures, logos, screenshots, footage,+fonts, music, voiceover, sound effects) and their direction. You do everything up to the render: it redraws and+animates what is in the references, edits the footage, plans the shots, builds every scene, places the sound and+revises from the user's notes. The user reviews in the viewer and renders. Good references in, good video out. If a+reference is too small, blurry or missing, ask for a better one rather than inventing it.++**The first thing the user sees is the real video.** No rough storyboard, animatic or approval step before building.+Plan the shots, build all of them properly, and open the viewer. The review happens on the real scenes.++**You never render the video.** Don't run `motlab render` or `motlab video` on the project, and don't offer to.+When the user is happy, they press Export in the viewer and pick a resolution. `motlab stills` (single frames to check+your own work) and `motlab events` are fine. Render only if the user asks for it in chat in so many words.++## The engine++`motlab` is a command on PATH. Run `motlab --help` once at the start: it lists the commands and prints the engine+folder (its README, the `example/` project and `src/page/footage.js`).++If `motlab` is not found, ask the user where their motlab clone is (the folder with `install.js` and `bin/motlab.js`)+and run `node install.js --skill none` there; it puts the command on PATH. If they have no clone, follow+`docs/install-for-agents.md` from https://github.com/staryone/motlab. Until the command is on PATH, call+`node <engine>/bin/motlab.js`. Never hard-code the engine path anywhere else. If a render or still fails because Chrome+or ffmpeg is missing, run `motlab doctor` and show the user what it reports. When the user asks to update motlab or+its skills, run `motlab update`. If it stops because the engine folder has local changes or commits of its own, show+the user its message and ask; never stash, reset or discard their changes. The new skills load in a new session.++## The workflow++1. **Brief and references.** Ask what the video is for, where it will be seen, how long it should be, whether it+ needs a voiceover, and the **orientation**: landscape 16:9 (1920x1080 pages), portrait 9:16 (1080x1920) or square+ 1:1 (1080x1080). Then go through the user's folder:+ - List everything. Measure images (`python3 -c "from PIL import Image; ..."` or `ffprobe`), probe footage and audio+ with `ffprobe` (size, frame rate, rotation, length, audio track), and note the music's length and tempo.+ - Check resolution against how close the camera will get. Ask for better files or rebuild as vector shapes. Get logos+ as real files: one cut from a screenshot or redrawn from memory is only acceptable if the user says so and checks it.+ - If the user has an asset kit (made with the motlab-assets skill: a folder with `kit.json`, `style.md` and+ `tokens.json`), copy it into `<video>/assets/kits/<name>/`, read its `style.md` and `tokens.json` before planning, and+ use its assets and colours rather than drawing new ones. New assets the video needs belong in the kit, through that+ skill.+ - Read any brand guidelines. Use the brand's fonts if they are there; otherwise pick any Google Font that fits the+ video's vibe (`references/fonts.md`).+ - Decide the style: the ad preset (`references/style-rules.md`) for product, app and brand ads, or when the user asks+ for it; otherwise the references set the look, and `references/craft.md` applies to everything.+2. **Know where it ends.** Find out what the viewer is meant to do afterwards (download, visit, sign up) or which shot+ the video hands over to, and plan the end from there.+3. **Plan the shots.** Number them (5 to 10 for a short piece, more for longer edits) and give each a duration (on the+ music's phrases, if the music is there already), what is on screen, what moves, and how it turns into the next shot. If you cannot say how a+ shot becomes the next one, the transition is a plain cut and the shot needs rethinking (`craft.md` §9). Post the list+ in chat in a few lines so the user knows what is coming, then go straight on to building. Don't wait for approval.+4. **Build every scene.** Write the real scenes in `<video>/scenes/` and list them in `<video>/project.json`. Keep the page contract (below). Keep all of a page's beat times together in one+ constant near the top, so changing the timing means editing one place. Footage goes in as a layer (`references/footage.md`). Copy templates and scripts from this skill's+ folder next to the scenes as needed. Every scene is finished work, built to `craft.md` (and the preset, if on): no+ placeholder frames, rough sketches or shots left for later.+5. **Sound, now or later.** Music and effects can come after the picture. The first build may be silent, or carry+ only the music if the user already gave it. When music arrives later, re-time the shots to its phrases if the user+ wants that. Build the effects mix with `mix.py` from the pages' `EVENTS` (`references/sound-and-music.md`), save it+ in `<video>/audio/`, and list it in `project.json` with the music, voiceover and any footage sound, so the viewer+ plays it and Export includes it.+6. **Check stills yourself.** `motlab stills <page> <outDir> 0.5 1.2 …` (it serves the folder with `project.json`, so+ the page can load files from the whole project), then `python3 scripts/contact_sheet.py <outDir> sheet.jpg` and look at it. Look+ inside every transition at three or four moments as well as at the still parts, and put the references next to the+ stills: a wrong shape, a flipped layout or parts that pass through each other are easy to miss otherwise. Fix what `craft.md` would flag+ before the user sees it.+7. **Open the viewer.** Run `motlab edit <video>`; it ends at once and prints the address. Give it to the user. Say in+ a few lines what is in it and what you could not check: you saw stills, not playback, and you cannot hear the sound. Give the+ user the "listen by ear" moments `mix.py` printed.+8. **Revision rounds.** The user plays the video, steps through it frame by frame, clicks the spot and comments, or+ leaves notes in the viewer and says "kerjakan semua catatan". When they say "this one", "here", "yang ini" or "di+ sini", or mention notes, read `<video>/selection.json` first (and look at `<video>/selection/<n>.png` for each note+ with a box or point), then grab that frame with+ `motlab stills <scene> <dir> <frame time>` (see below) so you see what they see. Apply every open note, check stills+ around the change, re-run `mix.py` if beats moved, and tell the user to reload. Report what changed in plain words.+ Before a round that changes a lot, copy `scenes/` to `backup/<n>/`. Never delete or edit the user's reference files.+ Many rounds are normal; keep going until the user is happy.+9. **The render is the user's.** They press Export in the viewer and pick 720p, 1080p, 1440p or 4K. The file lands in+ `<video>/out/<folder>-<resolution>.mp4` (4K as `-2160p`). To look at an export they ask about, tile one frame a+ second into a single image: `ffmpeg -i out.mp4 -vf "fps=1,scale=480:-1,tile=6x10" -frames:v 1 sheet.jpg`.++**Paid tools:** generating a voice, music or anything else on a paid service (ElevenLabs, Suno and the like) spends the+user's credits. Do it only when they ask.++## Project layout++One folder per video. The user's references can stay where they are if they are inside this folder; anything used from+outside it is copied into `assets/` (copy, never move), because the viewer and renderer only serve the project folder.++```+promo/+ refs/ the user's references, untouched+ assets/ copies, cut-outs, rebuilt vectors, fonts+ footage/ video clips used in scenes+ audio/ music, voiceover, the effects mix+ project.json the video+ scenes/ one page per scene+ backup/ copies of scenes/ before big revision rounds+ out/ the user's exports+```++`project.json`:++```json+{+ "fps": 30,+ "scenes": ["scenes/01-hook.html", "scenes/02-feature.html"],+ "audio": [+ { "file": "audio/music.wav", "start": 0, "volume": 0.6 },+ { "file": "audio/sfx.wav", "start": 0, "volume": 1 },+ { "file": "footage/demo.mp4", "start": 4.0, "from": 12.5, "duration": 6 }+ ]+}+```++- Scenes play in list order and each lasts its page's `TOTAL`. All scenes need the same canvas size, which sets the+ orientation of the whole video. The join between scenes is a hard cut, exact to the frame. For a move that carries+ across it, the next scene's `t = 0` must show what the previous scene would show at its `TOTAL`, one frame after its+ last frame. Repeating the same picture holds for a frame and stutters. Use one scene per shot or beat, so the viewer+ and `selection.json` point at it; keep a long continuous move (one camera, shapes morphing through several beats)+ inside a single page.+- A scene can instead be `{ "file": "scenes/02.html", "transition": { "type": "crosswarp", "duration": 0.5 } }`: the+ scene before turns into it through a shader, and the two overlap for that long, so it starts that much earlier and+ the video is that much shorter. Use these for edits, explainers and talking heads; in an ad, a shape that carries+ across the cut (`craft.md`) is still better. The types and options are in `references/motion-and-libraries.md`.+- `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,+ minus the transition durations up to and including this scene's own).+- Another `.json` file in the folder with a `scenes` list is a version with the same assets, for example+ `project-tiktok.json` for a cut without the affiliate part. The viewer's header has a version menu, and the user can+ make a version there ("New version from this one", in Indonesian "Versi baru dari ini", copies the open one to `project-<name>.json`). When the user asks for a+ version or a revision ("revisi 2"), copy the current project file to `project-<name>.json` and change the copy. A+ scene that has to differ in one version gets its own copy (`scenes/05-cta-tiktok.html`) listed only there; never+ change a shared scene for one version. `selection.json` says which version a note is about (`project`), so edit that+ file. Export writes `out/<folder>-<name>-<resolution>.mp4`.+- `motlab edit <video>` (or a project file) opens the project in the viewer at `http://127.0.0.1:4173/p/<folder>/`,+ starting the viewer in the background when none is running, prints the address and ends. Give the user the address+ 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.+- A click writes `<video>/selection.json`:++ ```json+ { "project": "project.json", "time": 4.094, "scene": "scenes/02-feature.html", "sceneIndex": 2, "sceneTime": 1.094,+ "frame": 32, "audio": null, "range": null, "marks": [] }+ ```++ The times are where the click landed, not snapped to a frame. `frame` is the frame of that scene the preview shows+ (`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.+- `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`.+- `marks` are the user's notes, numbered `n` across all versions of the folder: `{ n, id, note, time, scene, sceneIndex,+ sceneTime, frame, transition, box, point, range, image, project }`. Each is a box or a point drawn on one frame, or+ a range, with the text `note` saying what is wrong there (it can be empty: then the spot is the note). `box` and+ `point` are in the scene's own pixels at `?scale=1`, the same units as the scene code. `image` is+ `<video>/selection/<n>.png`: that frame with the note's box or point and number drawn on it. Look at it first, then+ find what the scene draws inside the box. It is the preview, not a clean still, so use `motlab stills` for a clean+ frame. Work only on the notes whose `project` is the version you are editing, and when the user says "catatan 3",+ that is `n: 3`. Skip notes with `"done": true`; they were dealt with in an earlier round. Report per note number+ what you changed, and once a note is applied and checked in stills, set `"done": true` on that mark in+ `selection.json`. Change nothing else in that file: the viewer writes it, and it keeps your `done` while it is open.+ The user opens a note again in the viewer when the fix was not right. `time` is on the same clock as `start` in `project.json`, so a sound effect for that moment+ gets `"start": <time>` (or the frame's time, for a hit on the frame). `audio` holds `{ file, start, index }` for a+ click on an audio clip; the point inside that file is `time - start + from` (`from` from the entry in+ `project.json`). When the user says "this one", "here", "yang ini" or "di sini", read this file first and act on that project,+ scene and time.++The engine folder's `example/` is a small working project (three scenes, music, three sound effects) to copy from.++## Page contract++- `<canvas id="c">` sized `W * scale` by `H * scale` with even dimensions, where `scale` comes from `?scale=`+ (1 in the viewer, 2 for a 4K render of a 1920x1080 page)+- `window.renderAt(t)` draws the frame at `t` seconds and may be async+- `window.TOTAL` is the length in seconds+- `window.ready` is a promise that resolves when fonts and assets are loaded. Set it before any `await` in a module+- `window.EVENTS` (optional) is `[{ name, t }]` for syncing sound+- `?t=` draws a still++Frame `f` is rendered at `t = f / fps`. The same page runs in the viewer, so what the user plays is what renders.++## Choosing how to build it++| Approach | Use it for | Tools |+|---|---|---|+| 2D canvas | Flat brand animation, kinetic type, explainers, captions, edits | `templates/template-2d.html`; illustrations: `references/engine-2d-puppet.md` |+| UI in 3D space | Apps and software: real screenshots as panels with a camera and depth of field | `templates/template-3d.html`, `scripts/gl3d.js`, `references/engine-3d.md` |+| three.js | Real 3D objects that turn: a product, character or logo from a GLB or glTF file, or built from shapes | `templates/template-three.html`, `references/engine-3d.md` |+| p5.js | Generative graphics: noise fields, particles, patterns, data drawn as shapes | `templates/template-p5.html`, `references/engine-p5.md` |+| Footage | Screen recordings, camera clips, tutorials, reels made from real video | `references/footage.md`; jump cuts in a talking head: `scripts/cut_pauses.py` and `/__motlab/cuts.js` |+| Blender | Photoreal products or a filmed studio look. Slower, and Blender must be installed | `scripts/blender/`, `references/blender.md` |++Mix them freely: footage with 2D captions, a 3D UI shot that ends on a recording, a Blender product over a canvas end card.++## Kinds of video++- **Product, app and brand ads (8 to 20 s).** Turn on the ad preset. One journey in 5 to 10 beats, every shot morphs+ into the next, a clear call to action.+- **Animated pieces and logo animations.** The references set the style. `craft.md` still applies: shapes that carry+ across transitions, one-way camera moves, nothing dead still.+- **Explainers.** One scene per idea. Write the voiceover or on-screen text first and time the scenes to it.+- **Tutorials and screen-recording edits.** Cut the recording into shots, zoom into the part being explained, highlight+ the control being used, add short captions. Slower pacing: text stays up long enough to read twice, and legibility+ beats "always moving" or "keep it centred".+- **Edits of camera footage.** Trim, order and time clips to the music, add titles and overlays, use the clips' own+ sound where it matters. Hard cuts are fine here; match cuts and motion-led cuts are better.+- **Portrait and square social clips.** Same workflow on a 1080x1920 or 1080x1080 canvas. Keep text and faces clear of+ the top and bottom of the frame, where the app's own interface sits. Hook in the first second.+- **Long videos.** A 10-minute test render at 4K took about 19 minutes on the test laptop and made a 3.2 GB file, and+ a real 2-minute video has been exported at 4K. Suggest a 1080p export first for a long video, and say how long 4K will take.++Transparent (alpha) output is not available yet.++## Keep it above board++Before the video is shared, settle these with the user:++- **Brands.** The brand has to be the user's, or one they have permission to promote. For any other brand the video is+ a spec piece, for practice or a portfolio: it ends on a small "Spec ad. Not affiliated with <brand>." line, does not+ copy the brand's actual campaigns or pose as official, and is never bought as ad space.+- **Assets.** Every file in the video (footage, images, fonts, sounds, music, 3D models) is either the user's own or+ covered by a licence that allows this use.+- **Claims.** What the video shows or says has to be true, and the user has to be able to back it up. Nothing that+ promises earnings or results, and no made-up numbers, reviews, ratings or awards.+- **Privacy.** Personal details in screenshots and footage are blurred or swapped out, and anyone recognisable has+ agreed to appear.++## Where to read more++| When you are… | Read |+|---|---|+| making anything look polished: transitions, camera, easing, text, assets | `references/craft.md` |+| making a product, app or brand ad (the ad preset) | `references/style-rules.md` |+| editing screen recordings or camera footage | `references/footage.md` |+| screens and cards floating in 3D, or real models with three.js | `references/engine-3d.md` |+| making generative graphics with p5.js | `references/engine-p5.md` |+| cutting out, splitting or puppeting flat illustrations | `references/engine-2d-puppet.md` |+| choosing, downloading and loading fonts | `references/fonts.md` |+| rendering a product in Blender, shaded or in the flat look | `references/blender.md` |+| ending an animation on real footage | `references/into-footage.md` |+| sound effects, a voiceover or music | `references/sound-and-music.md` |+| easing, springs, motion blur, transitions between scenes, GSAP, Anime.js, Lottie or Theatre.js | `references/motion-and-libraries.md` |+| a frame looks wrong or a render misbehaves | `references/pitfalls.md` |++## Setup++Needs the motlab engine (see "The engine"), Node 24 or newer, Python 3 with Pillow, numpy and scipy,+ffmpeg and ffprobe on PATH, and Google Chrome (set `CHROME` if it isn't found). Blender only for the Blender approach.+Commands in this skill say `python3`; on Windows use `python`. Check these first, and tell the user what is missing+and how to install it before you start.++## Scripts and templates++- The engine: `motlab stills` to check frames, `motlab events` to dump the beat list, `motlab edit` for the viewer.+ `motlab render` and `motlab video` are the user's (see the top). Chrome always runs on the GPU.+- `templates/template-2d.html`, `template-3d.html` (gl3d.js), `template-three.html` and `template-p5.html`: starting+ points for scenes. The three.js and p5.js templates load their library from a CDN, so they need the network.+- `contact_sheet.py`: puts the stills from `motlab stills` on one sheet, labelled with their times.+- `key.py` removes a flat background, `split.py` cuts a cut-out into layers, `grid.py` overlays pixel coordinates.+- `gl3d.js` places 2D-canvas panels in 3D; `puppet.js` bends a cut-out with pins.+- `get_font.py`: searches the Google Fonts catalog and downloads a family into the project. `templates/font-specimen.html`+ shows the downloaded fonts side by side for `motlab stills`.+- In every scene page: `/__motlab/motion.js` (easings, `cubicBezier`, `spring`, `tween`, `stagger`, `motionBlur`),+ `/__motlab/footage.js` (video files) and `/__motlab/cuts.js` (a cut list over one recording).+- `cut_pauses.py`: cuts the pauses out of a talking-head recording into `cuts.json`, and with `--audio-out` writes the+ voice with the same cuts.+- `mix.py`: puts library sounds on the page's events at a level set by their role, lowers them under a voiceover,+ reports how close each landed and which moments to listen to. `synth_sfx.py`: builds a free sound kit. `get_sfx.py`: finds openly licensed sounds on+ Openverse and downloads them with a `CREDITS.md`. If the user has earshot (`earshot --help` runs, or its MCP tools+ are listed), use it to pick sounds and measure the mix (`references/sound-and-music.md`).+- `blender/`: `kit.py` (scene, light, camera and render helpers), `tracks.py` (move curves), `mesh_from_sdf.py`+ (meshes from distance functions) and `example_scene.py`, a complete scene to start from.+- `compose_into_clip.py`: joins transparent PNG frames from a Blender render to a real clip, so the render hands over+ to the footage (`references/into-footage.md`).diff --git a/skills/motlab/references/blender.md b/skills/motlab/references/blender.mdnew file mode 100644index 0000000..dc7cbdf--- /dev/null+++ b/skills/motlab/references/blender.md@@ -0,0 +1,118 @@+# Level 3: Blender++Blender is for a product that should look photographed: real materials, soft light, a shallow lens. The user installs+Blender from blender.org but never has to open it. You run it with no window (`blender -b -P scene.py -- ...`), it+writes a numbered PNG sequence, and a scene page plays that sequence like any other scene, so the user still reviews in+the viewer and exports from there. Expect the build to take longer than a canvas scene.++Look for Blender before planning on it: `blender` on the PATH, `C:\Program Files\Blender Foundation\Blender <version>\+blender.exe` on Windows, `/Applications/Blender.app/Contents/MacOS/Blender` on a Mac.++## The scripts++All in `scripts/blender/`, plain Python files to copy next to the project's assets:++- `kit.py` runs inside Blender: an empty scene, Cycles on whatever GPU the machine has, materials, one area light, a+ camera, importing meshes and models, the flat look, and the render loop that keys every frame and skips frames+ already on disk.+- `tracks.py`: smooth curves for moves (`mono`, `tracks`) that never overshoot, so a move cannot wobble back.+- `mesh_from_sdf.py` runs in plain Python (numpy and scipy): describe a shape as a distance function and get a smooth+ quad mesh as `.npz`, which `kit.load_npz()` reads.+- `example_scene.py`: a complete small scene that uses all three.++Run the example once before building anything, so you know the machine works:++```+python3 example_scene.py mesh+blender -b -P example_scene.py -- frames 1280 24 0.5 2 3.5+```++The first line writes the meshes to `example_mesh/`. The arguments after `--`, in order: where to write the frames,+the image width in pixels, the Cycles sample count, the word `flat` for the flat look (optional), and any number of+times in seconds to render only those frames (none renders the whole animation). Frame f is the scene at (f - 1) / fps seconds, saved as `<folder>/<f:04d>.png` with a transparent+background. Frames already on disk are skipped, so after a crash the same command carries on. A relative output folder+is taken from the folder Blender runs in.++Measured on Blender 5.2 with an RTX 3060 Laptop (Cycles on OptiX): three 640 px stills at 8 samples took 8.9 s+including Blender's start-up, and all 100 frames (4 s at 25 fps) at 1280 px and 24 samples took 402 s.++## Playing the frames in a scene++A scene page loads each PNG only when it is asked for, so a long sequence never sits in memory at once:++```html+<canvas id="c"></canvas><script>+const q = new URLSearchParams(location.search), S = parseFloat(q.get('scale') || '1'), W = 1280, H = 720, FPS = 25, N = 100;+const c = document.getElementById('c'); c.width = W * S; c.height = H * S; const ctx = c.getContext('2d');+window.TOTAL = N / FPS; const cache = new Map();+function frame(k) { // frame k of the scene is frames/<k + 1>.png+ k = Math.max(0, Math.min(N - 1, k));+ if (!cache.has(k)) { const img = new Image(); img.src = `frames/${String(k + 1).padStart(4, '0')}.png`; cache.set(k, img.decode().then(() => img));+ if (cache.size > 8) cache.delete(cache.keys().next().value); }+ return cache.get(k);+}+window.ready = frame(0).then(() => true);+window.renderAt = async t => { const k = Math.round(t * FPS), img = await frame(k); frame(k + 1); frame(k + 2); // load ahead+ ctx.fillStyle = '#000'; ctx.fillRect(0, 0, c.width, c.height); ctx.drawImage(img, 0, 0, c.width, c.height); };+</script>+```++Render the project at the frames' fps. The example's 100 frames played this way and rendered with `motlab video` at+25 fps came out one PNG per video frame: every frame was closest to its own PNG (mean difference 0.22 of 255), none to+a neighbour.++## Getting the shape right++People notice a wrong shape before anything else, and it is easy to miss without a side-by-side comparison.++- If a model exists, use it: `kit.load_model(path, parent)` imports GLB, glTF, FBX and OBJ and returns the new+ objects. Check its licence when the video will be published.+- If not, build it in `mesh_from_sdf.py`. A body is usually a few `ellipsoid`s or `pill`s joined with `smin`; anything+ round (a bottle, a cap, a knob) is a `revolve` of an outline, rounded first with `chaikin`; a recess is `smax` with a+ `rounded_pocket`. Shapes are y-up; the example turns them upright with a parent rotated 90 degrees about x.+- Collect references from several angles. A screen recording of the product turning in a 3D viewer is ideal; pull+ frames from it with ffmpeg and measure proportions on them.+- Before animating, render a few still poses on a grey world and put them next to the references. Fix the shape until+ they agree. Each check takes seconds.++Things that go wrong with distance-function meshes:++- Heavy smoothing (`smooth=` in `load_npz`, 20 iterations by default) rounds off small parts and closes small holes.+ Use fewer iterations on small or detailed parts, as the example does for its band.+- A detail placed as a flat disc on a curved surface sticks out at its edges. Sink a flattened ellipsoid into the+ surface instead.+- Seams and grooves look heavier once lit than they do in a reference photo. Keep them shallow.+- A mirrored copy made with a negative scale can end up on the wrong side. Check left and right against the reference.+- Parts that move out of a closed object can pass through its walls. Move them straight out before they turn, and hide+ what is inside until it opens.++## Light and camera++- One light: `kit.key_light(position, size, power, target)` is a large soft area light, and `kit.setup` gives a world+ that is almost black. One source with a dark surround is most of the photographed look.+- Long focal lengths (70 to 90 mm) keep proportions calm and let the camera move in close for details.+- Give each move a single curve from `tracks.py` from start to end. Two curves joined in the middle leave a jolt in+ speed even when the positions match; render the frames around a join to check.+- Choose the camera path for the moment that matters: by then the side people recognise the product by should face+ the lens.+- The render keys every object passed to `kit.render` on every frame, with motion blur over half a frame.++## Render time++- Quick looks: a few times at 640 px and 8 samples. Final frames: 1280 or 1920 px at 24 samples, scaled up in the+ scene page if the export is larger. Close-ups and glass take longer.+- Cycles keeps the GPU busy and the machine sluggish. Tell the user before a long render and do not start other heavy+ work alongside it.+- After a change that affects only some frames, delete those PNGs and run the same command; the others are kept.++## The flat look++Pure white shapes with black only where the product is black, no shading and no lines. It reads as a bold graphic and+sits naturally next to footage shot in silhouette.++Pass `flat` on the command line to a scene that calls `kit.flat_mode(black_materials=('dark',))` when it sees it, as+the example does. Every mesh becomes flat white except those whose material is named in `black_materials`, which become+flat black; text objects are hidden. With no lighting to compute, 8 samples or so are plenty.++Keep black only for what is black on the real product, and leave out small details such as lettering, lights and+seams. Lines along the seams turn the look into a drawing, so add them only if the shape is unclear without them.diff --git a/skills/motlab/references/craft.md b/skills/motlab/references/craft.mdnew file mode 100644index 0000000..f867a74--- /dev/null+++ b/skills/motlab/references/craft.md@@ -0,0 +1,96 @@+# Craft: what makes a motlab video look expensive++These techniques come from a 12-second Spotify spec ad built with this workflow from nothing but eight phone+screenshots and two logo files. No generated images or video went into it. It looked good for the reasons below, and they apply to any video, not only ads.++## 1. Real assets, measured to the pixel++- Every picture on screen is the user's real material: screenshots, logos, photos, footage. Nothing is invented when+ a real version exists.+- Measure before you draw. The ad kept the logo's visible bounding box (`{ x: 13, y: 14, w: 913, h: 912 }`), the+ album cover's rectangle inside the screenshot (`[128, 267, 823, 823]`), and each tile's crop rectangle as constants.+ Centring and morphs then land exactly, and the end logo is centred by what you see, not by the file's canvas.+- Crop pieces out of screenshots and move them separately (tiles, a header, track rows), so a flat screenshot becomes+ a layered scene. Cover personal details (a profile photo became a grey circle).+- Rebuild anything the camera gets close to as vector shapes (the play button, the pause disc), so it stays sharp at+ 4K while the screenshot around it would blur.++## 2. One block of beat times++```js+const B = { morph1: 1.05, tilesIn: 1.5, tap: 3.0, flood2: 3.15, artist: 3.7, press: 5.9, END: 12 };+window.EVENTS = [{ name: 'tap', t: B.tap }, { name: 'press_play', t: B.press }];+```++Every animation reads its times from `B`, and `EVENTS` is built from the same constants. Re-timing a note ("slower+here") is one number, and the sound effects follow automatically because the cues point at event names.++## 3. Shots become each other++There is not one cut or cross dissolve in the ad. Each shot hands its key shape to the next one:++| From | Becomes |+|---|---|+| the logo disc | the phone screen (circle to rounded rectangle, green to dark) |+| a round photo on a tile | the orange background of the artist page (it grows past the frame edges) |+| the mini player bar | the full-screen now-playing background |+| the album cover in the bar | the big cover in the centre, on one curve |+| the white pause disc | the green logo, then the wordmark slides out from behind it |++Two small tricks sell each handover. First, an anticipation: the source shape squashes about 8% one pose before it+grows (`1 - 0.08 * bump(prog(t, start - 0.14, start + 0.02))`). Second, the shape is painted in the next shot's+background colour as it grows, and the next shot appears inside it a beat later, scaling up from 93% to 100%.++## 4. A camera that only goes one way++Each "world" has one camera that keeps pushing in and never reverses. Distance is eased in log space, so the push feels+even from far to near:++```js+const D = Math.exp(lerp(Math.log(2500), Math.log(1700), outCubic(prog(t, 1.1, 3.75))));+```++Something is always moving: a 3 to 5% push on holds, a drift, rings pulsing behind the cover. A still frame reads as+a mistake.++## 5. Easing with intent++- Entrances: `outExpo` or `outCubic` (fast, then a long settle). First drafts are nearly always too fast.+- Shape morphs: `inOutCubic`. Fades: a sine, never an ease that ends abruptly.+- Staggers of 0.08 to 0.1 s between items in a cascade (tiles, list rows, words).++## 6. Depth and a filmed look++- UI panels sit in real 3D (`gl3d.js`) with a perspective camera and shallow depth of field, so the background goes soft.+- Motion blur: every frame averages 12 renders spread over half a frame's time. Fast moves smear like film instead of+ stepping.+- One soft light source, a gentle glow behind the hero, a single light sweep across the final logo. Nothing else.++## 7. Text that arrives softly++Words come in one at a time, 0.08 s apart: each rises 20 px while it goes from blurred to sharp, and they go out the+same way. Sentence+case, tight tracking (about -3%), a short line ending in a full stop, a gradient only on the lower half of the letters+on dark backgrounds. No bounces, no letter-by-letter typing, no hard wipe edge.++## 8. Sound mapped to meaning++`cues.json` lists every sound against an event name with an offset, a level, a pitch and a pan. Repeated ticks rise in+pitch (0.90, 1.00, 1.10, 1.20) and alternate pan. Whooshes only under movement, pops and soft hits on morphs and+landings, a riser that ends on the logo. The song comes in on the play press (`"event": "press_play"`), with a quiet air+bed underneath the whole ad. See `sound-and-music.md`.++## 9. A shot plan that says how shots connect++The Spotify ad was planned as six numbered shots, each with a time range, one line on what we see, one on what moves,+and one on how the shot becomes the next. That last line is the design: if you cannot write one, the transition is a+cut, and the shot needs rethinking.++## Checklist before opening the viewer++- [ ] Every transition has a shape that carries across it+- [ ] Nothing reverses direction, and nothing is ever fully still+- [ ] Subject centred by its visible bounds, end card dead still and centred+- [ ] Assets crisp at 4K where the camera gets close+- [ ] Stills checked at three or four points inside every transition, not only on the holds+- [ ] Beat times in one block, events derived from themdiff --git a/skills/motlab/references/engine-2d-puppet.md b/skills/motlab/references/engine-2d-puppet.mdnew file mode 100644index 0000000..72a3ce9--- /dev/null+++ b/skills/motlab/references/engine-2d-puppet.md@@ -0,0 +1,86 @@+# 2D: cut-outs, puppets and layers++For flat, illustrated scenes start from `templates/template-2d.html`. It is a working example of the pieces below:+shots on flat colour fields, a shot change that grows a shape from the outgoing shot, headlines that rise word by word,+a slow push on each shot, and optional held poses, jitter and flat shadows. Replace its `SHOTS` with the real ones.++Most illustrated briefs come with art as flat PNGs. The scripts here turn that art into parts that can move.++## From a flat image to a cut-out++`python3 scripts/key.py art.png figure.png` removes a flat background. It reads the background colour from the image's+border and removes only what is connected to the border, so a white shirt on a white background keeps its inside.++- `--tol 45` is how far a colour may be from the background and still count as background. Lower it if edges of the+ figure disappear, raise it if a halo is left.+- Patches of background colour enclosed by the figure (between an arm and the body) are removed too. When such a patch+ is part of the drawing (a yellow folder on a yellow field), add `--keep-pockets`.+- `--no-bottom` stops the removal from starting at the bottom edge, for a figure the frame cuts off at the legs.+- Check the result on a loud colour before using it: `python3 scripts/grid.py figure.png check.jpg` shows it on+ magenta with a numbered grid.++Art on a gradient or a paper texture will not key cleanly. Use the whole image as one layer, or redraw the scene.++## Finding coordinates++`python3 scripts/grid.py figure.png grid.jpg [--step 50]` draws a grid labelled in the image's own pixels. Read pin+positions, split polygons and transition shapes off it.++## Splitting into layers++`python3 scripts/split.py figure.png regions.json` writes one PNG per named polygon, each the size of the original and+in the same place, so they stack back exactly. Whatever no polygon covers goes to `figure-base.png`.++```json+{ "badge": [[620, 80], [760, 80], [760, 200], [620, 200]], "cloud": [[40, 30], [300, 30], [300, 180], [40, 180]] }+```++This suits parts that stand apart (a badge, a cloud, motion lines). Where objects overlap, the cut leaves a hole in+whatever was behind, which then shows when the front part moves. Redraw those as shapes instead (below).++## Puppet pins: `scripts/puppet.js`++A grid mesh over a cut-out, bent by pins. Each pin gets a move (shift, turn, scale about a pivot) and the art between+pins follows a blend of the nearby moves, so a figure can lean, wave or nod without being cut apart.++```js+const P = Puppet.create(img, [{ x: 200, y: 90 }, { x: 60, y: 198 }, ...], { cols: 64 }); // pins in image pixels+P.draw(ctx, moves, x * SCALE, y * SCALE, s * SCALE, cv.width, cv.height);+// moves[i] = { dx, dy, rot, s, ox, oy }: (ox, oy) is the pivot, for example the shoulder for an arm+```++- Pin every part that moves, and add pins that hold still (an empty `{}`) wherever the art must stay put, usually the+ feet. Without them the whole figure slides.+- An arm turns about its shoulder, the head about the neck. Give each its own pin with the pivot set.+- A pin's `r` (default 1) widens its reach; `power` in the options (default 3) sets how quickly a pin's pull fades.+- Life comes from small overlapping motions: a main gesture on the beat, a smaller follow-through after it, the head+ arriving a pose later than the body, a slow breathing bob.+- Puppet people and animals. Objects usually look better moved whole, as layers.+- `P.draw` copies the bent art onto `ctx` with `drawImage`, so whatever shadow `ctx` has set (offsets in device+ pixels) falls under the figure.+- It needs WebGL2, which motlab's Chrome has. A six-pin test figure rendered through `motlab stills` at 0, 0.5, 1 and+ 1.5 s gave the same pixels in forward and reverse order.++## Redrawing as shapes++Overlapping objects (papers in a tray, a phone in a hand, coins in a pile) are better drawn again as canvas paths.+Use the original image's pixel coordinates so the new shapes line up with the rest. Then every object is its own layer and+nothing has holes. Match the art's style: if it uses dark outlines and flat fills, so do the shapes. Typical motions that+become easy: a paper sliding out from behind the tray's front, a coin spinning (scale its width by `|cos|`), a line+drawing itself with a dash offset, a speech bubble popping in with a slight overshoot.++## Held poses, jitter and flat shadows++Flat art often looks better moving like hand-drawn animation than perfectly smooth:++- Hold poses: `tp = Math.floor(t * POSES) / POSES` feeds every animation, with `POSES` at 12 (smoother) or 8 (rougher).+ At 24 fps that is a new pose every 2 or 3 frames, always the same number.+- Jitter: move each layer by a pixel or two per pose, from a hash of the pose number, so it is the same in every+ render.+- Flat shadows: a hard shadow with no blur, offset down and to the right, about a quarter opaque. Shadow offsets are+ in device pixels, so multiply them by `SCALE`.++## The last shot++End on a still frame: no push or drift, the logo centred by what is visible in it (not by the image file's size, which+may include empty margins), then the tagline and what to do next (a URL, a store badge the brand really uses).diff --git a/skills/motlab/references/engine-3d.md b/skills/motlab/references/engine-3d.mdnew file mode 100644index 0000000..a6d69ba--- /dev/null+++ b/skills/motlab/references/engine-3d.md@@ -0,0 +1,84 @@+# 3D: UI panels in space (gl3d.js) and real models (three.js)++There are two 3D paths. For screens, cards and text floating in space, use `scripts/gl3d.js` with+`templates/template-3d.html`. For real models (a product, a character, a room), use three.js with+`templates/template-three.html`. Both draw onto the page's 2D canvas, so 2D titles and overlays work the same way on+top. motlab runs Chrome on the GPU, so WebGL2 works without extra flags.++## Panels with gl3d.js++Every element is a flat rectangle. Its picture is an ordinary 2D canvas, drawn with the same code as any 2D scene, so+text and icons stay sharp; gl3d.js places the rectangle in 3D and looks at it through a perspective camera.++```js+const stage = GL3D.create(cv.width, cv.height);+const tex = stage.texture(canvas2d); // tex.update() after drawing on canvas2d again+ctx.drawImage(stage.render(panels, view), 0, 0);+const [px, py] = stage.project([x, y, z], view); // where a 3D point lands on screen+```++A panel is `{ tex, w, h, pos, rot, scale, alpha, light, blur, bias, reflect, sheen, sheenPos }` and the view is+`{ eye, target, up, fov, focus, aperture, fog: { near, far, color }, floorY, ground }`. The comment at the top of+`gl3d.js` explains each field.++- Scale: with `fov` 34 to 38 and the camera about 1600 units away, a unit is about a pixel at 1080p, so a 540 x 760+ panel looks like a 540 x 760 card. y points up.+- Draw order: panels are drawn far to near, by depth along the view direction. Things stacked almost on top of each+ other (a play button on a cover, a title on a card) can swap places as the camera moves; `bias` pulls a panel+ forward in the order without moving it. A few units is enough for art on a card; text that must always win can take+ hundreds.+- Depth of field: `focus` is the distance kept sharp and `aperture` how fast the rest softens. It works by reading+ smaller mip levels, which looks like a soft lens blur. `blur` softens one panel on its own.+- `fog` fades far panels into a colour, usually the background's. `floorY` adds a faint mirrored copy of every panel+ below that height, like a glossy floor; `reflect: false` leaves a panel out. `ground` panels (a floor texture,+ contact shadows) are drawn first, flat and sharp.+- `sheen` and `sheenPos` slide a diagonal band of light across a panel, for glass and glossy cards.+- `rot` is in radians and applied z first, then x, then y. A panel at `pos` faces a camera at `eye` with+ `ry = atan2(dx, dz)` and `rx = -asin(dy / distance)`, where `d = eye - pos`.++### How the template is put together++- Each element is a `panel(w, h, pad, paint)`. `pad` leaves room round it for a drop shadow. `panel.update(args)`+ redraws the picture only when its arguments changed, so animating a panel's content is cheap. Pictures are drawn at+ `TEX` (2) times their size, so they hold up when the camera comes close.+- One camera function `camera(t)` drives the whole scene, and `panels(t)` returns where everything is at time `t`.+- Motion blur renders `SUBFRAMES` (12) moments across half a frame and averages them. With only a handful, a fast move+ shows separate copies instead of a smear.++### Ideas that work with panels++- A glow behind the subject: `project()` its position and draw a soft radial gradient there on the 2D canvas before+ drawing the 3D layer.+- A circle that becomes a card: redraw the panel's picture step by step (circle, rounded square, the card's content)+ and move the panel to the card's place at the same time.+- A wall of tiles that seems endless: draw a small repeating set of tiles around the camera and skip the ones behind+ it or off screen (check with `project()`).+- A phone: a screen panel drawn at twice the screenshot's pixels, a dark glass body behind it, and a stack of thin+ slices behind that for the edge. To fly into one icon, fade the phone out gently and put the icon on its own sharp+ panel so it does not pixelate.+- Swapping what is on a card unseen: turn the camera round it and change the content on the frame where the card is+ edge-on to the camera.++## Real models with three.js++gl3d.js has no meshes. For models start from `templates/template-three.html`. It loads three.js 0.186.1 from jsDelivr+through an import map, so a render needs the network. Set `MODEL` to a `.glb` or `.gltf` next to the page; left empty,+it shows a placeholder box. The model is scaled to 1.6 units and stood on a shadow floor, lit by `RoomEnvironment` and+one key light, with a one-way camera and a 2D title over it.++- three.js draws into its own WebGL canvas, which `render()` copies onto `#c`. So `#c` stays a 2D canvas and titles,+ captions and glows are drawn with the same code as in the 2D template, after the copy.+- Everything comes from `t`. Model animations play through `AnimationMixer` with `mixer.setTime(t)`, never a+ `THREE.Clock` or `mixer.update(delta)`. Stills rendered in the order 0.5, 1.5, 3, 5.9 s and again in reverse were+ identical byte for byte, for the box and for an animated glTF.+- `SUB` above 1 averages that many renders across a half-frame shutter into motion blur, at that many times the cost.+- Measured on the test laptop (RTX 3060 Laptop) for the template's 6 s at 30 fps: 52 fps to encode at 1080p and 23+ fps at 4K for the box, 39 and 22 fps for the glTF. In the viewer `renderAt` took under 1 ms of script time, because+ the GPU work runs after it returns, so that number says nothing about the GPU.+- Ask where a model comes from: the user's own work or a licence that allows this use. GLB or glTF with textures is+ easiest; three.js also has `FBXLoader`+ and `OBJLoader` under `three/addons/loaders/`.+- Keep the light simple (the environment and one key light) and the camera on one continuous move. Flat UI goes on top+ as 2D overlays or as textured planes in the scene.+- A detailed character cannot be modelled from scratch here to a professional standard. Ask for the model files.+ A flat picture of a 3D render can still float in space as a gl3d.js panel, but it cannot turn.diff --git a/skills/motlab/references/engine-p5.md b/skills/motlab/references/engine-p5.mdnew file mode 100644index 0000000..6e3f651--- /dev/null+++ b/skills/motlab/references/engine-p5.md@@ -0,0 +1,35 @@+# p5.js: generative graphics++Start from `templates/template-p5.html`. It loads p5.js 2.3.4 from jsDelivr, so a render needs the network. p5 runs in+instance mode with `noLoop()`. `renderAt(t)` sets `T`, calls `redraw()` and copies the p5 canvas onto `#c`. The sketch+is drawn in 1920x1080 units, and `?scale=` is applied once with `p.scale(SCALE)`.++Use it for things p5 is good at: noise fields, flow lines, particles, grids and patterns, data drawn as shapes. For+type-led brand animation the 2D template is shorter, and for objects in 3D use three.js (`references/engine-3d.md`).++## Rules that keep frames right++The renderer asks for frames in any order and splits them over several Chrome processes, so a frame must not depend on+the one before it.++- Draw from `T` only. Never `frameCount`, `millis()`, `deltaTime` or `Date.now()`.+- No state carried between frames. A particle that moves "a little each frame" breaks. Compute where it is at `T`+ (`x = x0 + vx * T`, or from `noise(id, T * speed)`), or, for a real simulation, run it from 0 to `T` inside the draw+ with a fixed step and cache the steps you have computed.+- Call `noiseSeed()` and `randomSeed()` at the top of every draw. For values that change per frame, seed with the+ frame number (`Math.round(T * fps)`).+- Do not name a global function `draw`, `setup` or `preload`. p5 2.x then starts a second sketch in global mode, which+ calls it with no arguments. The template names its draw function `paint`.+- Keep `pixelDensity(1)`. The canvas size already includes `?scale=`.++## Checked++Stills at 0.5, 1.5, 3 and 5.9 s, rendered in that order and in reverse, were identical byte for byte. The template's+field of about 1,200 strokes took a median of 11.2 ms a frame in the viewer and encoded at 28 to 34 fps at 1080p (two runs) and+21 fps at 4K on the test laptop (RTX 3060 Laptop). Drawing is on the CPU, so a sketch with many more shapes gets slower in+proportion; at 30 fps a frame has 33 ms. A heavy sketch (6,000 particles traced 40 steps through the noise field from 0 to `T`, 240,000 vertices a frame) gave+identical stills both ways and encoded at 6.1 fps at 1080p.++WebGL mode works the same way: `p.createCanvas(cv.width, cv.height, p.WEBGL)` in `setup`, with the origin at the centre.+A test of 40 lit boxes and a torus gave identical stills forward and in reverse. Not tested: p5's own font loading+with `loadFont`, and p5 add-on libraries.diff --git a/skills/motlab/references/fonts.md b/skills/motlab/references/fonts.mdnew file mode 100644index 0000000..db4a6de--- /dev/null+++ b/skills/motlab/references/fonts.md@@ -0,0 +1,78 @@+# Fonts++The user's own fonts come first. If the reference folder has brand fonts or brand guidelines that name a typeface,+use those. Otherwise the choice is free: any of the roughly 1,950 families on Google Fonts, picked to fit the video's+vibe. The examples below are starting points, not a list to stay inside.++Google Fonts families are released under open licences (mostly the SIL Open Font License), which allow use in+commercial videos. Downloading needs the internet; rendering does not, because the files live in the project.++## Picking one++1. **Name the vibe in a few words** from the brief and the references: the era, the energy, the audience, how serious+ it is. "Calm premium skincare", "loud street football promo", "friendly fintech for students".+2. **Shortlist 4 to 8 families.** Search the catalog with `python3 scripts/get_font.py list <words> [--cat Serif]`+ (categories: Sans Serif, Serif, Display, Handwriting, Monospace; most popular first) and add what you know fits.+ Don't fall back on Inter, Poppins, Roboto, Montserrat or Open Sans unless the brand uses them or the brief asks for+ something neutral.+3. **Look before choosing.** Download the shortlist into `<video>/assets/fonts-try/`, copy+ `templates/font-specimen.html` next to `fonts.css`, and run+ `motlab stills <video>/assets/fonts-try/font-specimen.html <outDir> 0`. Put the video's real words in the copy's+ `text` line first. Read the image and compare against the references.+4. **Pick one family, two at most** (a display face for big words and a text face for small ones). One family across+ several weights is often the strongest choice for motion. Download the winner into `<video>/assets/fonts/` and+ delete `fonts-try/`.+5. Name the font and the reason in one line when you post the shot list. The user can change it during review.++## Where to start, by vibe++| Vibe | Direction | Try |+|---|---|---|+| Clean tech, SaaS, fintech | Geometric or grotesk sans | Manrope, Plus Jakarta Sans, DM Sans, Sora, Outfit |+| Loud, sport, street, sale | Condensed and heavy | Anton, Bebas Neue, Oswald, Barlow Condensed, Archivo (width axis) |+| Luxury, fashion, beauty, editorial | High-contrast serif | Instrument Serif, Playfair Display, DM Serif Display, Cormorant Garamond, Gloock |+| Warm, friendly, food, kids | Rounded or soft | Fredoka, Nunito, Baloo 2, Fraunces (SOFT axis), Young Serif |+| Creative, music, youth culture | Characterful display | Bricolage Grotesque, Syne, Unbounded, Space Grotesk, Shrikhand |+| Retro, 70s and 80s | Fat, rounded display | Righteous, Bagel Fat One, Shrikhand, Rubik Mono One |+| Developer tools, data, terminal | Monospace | JetBrains Mono, Space Mono, IBM Plex Mono; pixel: VT323, Press Start 2P |+| Handmade notes, annotations | Handwriting, a few words only | Caveat, Kalam, Gochi Hand, Permanent Marker |+| Documentary, history, literary | Classic book serif | EB Garamond, Newsreader, Lora, Libre Caslon Text |++## Type that survives motion and compression++- Weights under 300 break up at small sizes and in the encoder. Keep hairlines for big words.+- Handwriting and script faces for one to three words, never for a sentence.+- Small text on a 1080p frame stays above about 28 px at `?scale=1`; on portrait clips keep it clear of the top and+ bottom where the app's interface sits.+- Variable fonts let weight and width animate. Download the range (`get_font.py get "Archivo" "wdth,[email protected],100..900"`),+ then set the weight as a number in `ctx.font` and the width with `ctx.fontStretch` (keywords such as `'condensed'`).+- Check the font covers the script of every line. Indonesian and English only need Latin.++## Download and use++```bash+python3 scripts/get_font.py get "Bricolage Grotesque" "[email protected]" --out <video>/assets/fonts+python3 scripts/get_font.py get "Instrument Serif" "ital@0;1" --out <video>/assets/fonts+```++Axes follow the Google Fonts css2 syntax: `wght@400;700` for two weights, `[email protected]` for a variable range,+`ital,wght@0,400;1,400` for regular and italic. A static font only has the weights `list` prints. Each call writes+`<slug>.css` and the woff2 files, and rebuilds `fonts.css` from every family in the folder.++In a scene page, link `fonts.css` and wait for every face the page uses. Fail loudly if one is missing, so a render+never ships in a fallback font:++```html+<link rel="stylesheet" href="../assets/fonts/fonts.css">+<script>+const FONTS = ['800 120px "Bricolage Grotesque"', 'italic 400 64px "Instrument Serif"'];+window.ready = Promise.all(FONTS.map(f => document.fonts.load(f).then(faces => {+ if (!faces.length) throw new Error(`font not loaded: ${f}`);+})));+</script>+```++`document.fonts.load` resolves to an empty list when no `@font-face` matches, and rejects when a file is missing.+Don't use `document.fonts.check` for this: it returns true for a family that was never declared.++Then draw with the same strings, for example `ctx.font = '800 120px "Bricolage Grotesque"'`.diff --git a/skills/motlab/references/footage.md b/skills/motlab/references/footage.mdnew file mode 100644index 0000000..6bf8b50--- /dev/null+++ b/skills/motlab/references/footage.md@@ -0,0 +1,112 @@+# Footage: screen recordings, camera clips and edits++A scene page can decode a video file and draw any frame of it, so footage is just another layer on the canvas. Cuts,+trims, speed changes, zooms, captions and animated overlays are all code, rendered on the same frame grid as everything+else.++## Open a clip++```html+<canvas id="c"></canvas>+<script type="module">+const S = +(new URLSearchParams(location.search).get('scale') || 1), W = 1920, H = 1080;+const c = document.getElementById('c'); c.width = W * S; c.height = H * S; const ctx = c.getContext('2d');+let clip;+window.TOTAL = 4;+window.ready = (async () => { // set window.ready before any await+ const { openFootage } = await import('/__motlab/footage.js');+ clip = await openFootage('../footage/demo.mp4'); // relative to this page, inside the project folder+})();+window.renderAt = async t => {+ await window.ready;+ ctx.setTransform(S, 0, 0, S, 0, 0);+ const f = await clip.frame(12.5 + t); // 12.5 s into the file: the in-point of this shot+ f.draw(ctx, 0, 0, W, H); // rotation metadata from phones is applied here+};+</script>+```++- `clip.width`, `clip.height`, `clip.duration` describe the file. `clip.frame(t)` returns the frame shown at `t` seconds+ into the file. It stays valid until the next `frame()` call, so draw it straight away. For a WebGL texture use+ `f.toCanvasImageSource()`.+- `/__motlab/footage.js` is served by the renderer and by the viewer, so the page works in both. It does not work from+ `file://`; open pages through `motlab edit`.+- Sequential frames decode once each. Jumping backwards or far ahead seeks from the previous keyframe, which is fine.+- Footage must be inside the project folder, like every other asset.++## Probe before you plan++```bash+ffprobe -v error -show_entries stream=codec_type,codec_name,width,height,r_frame_rate,duration:stream_side_data=rotation -of compact footage/demo.mp4+```++Note the frame rate (screen recordings are often 60 fps or variable), the size, any rotation, and whether there is an+audio track. Pull a contact sheet to see what is in it: `ffmpeg -i demo.mp4 -vf "fps=1,scale=320:-1,tile=6x6" -frames:v 1 sheet.jpg`.++## Editing moves++- **Trim and cut.** One scene per shot, each with its own in-point. A hard cut between scenes is a real cut now, which+ is right for edits even though ads avoid it.+- **Speed.** `clip.frame(in + t * 2)` plays at double speed. A speed ramp uses an eased time map:+ `in + 3 * outCubic(t / 3)`. Keep the audio in step or drop it under music.+- **Freeze frame.** `clip.frame(in)` for every `t`, with a slow push so it is not dead.+- **Zoom and pan on a screen recording.** Draw the frame scaled around the point of interest:+ `f.draw(ctx, sx, sy, sw, sh, 0, 0, W, H)`. Ease into the zoom before the action and out after it. Keep text on the+ recording readable: at 1080p output, UI text should stay at least as large as in the original.+- **Highlights.** A rounded rectangle outline, a dimmed surround (draw a dark layer with the target cut out), or a soft+ spotlight. Animate it in with the same easing as everything else.+- **Captions and labels.** Use the text rules of the chosen style. Burned-in subtitles: short lines, bottom third, a+ soft dark band behind for contrast.+- **Picture in picture, split screens, device frames.** Draw the frame into a clipped rounded rectangle, a phone body or+ a laptop shape.+- **Animation over footage.** Draw canvas or 3D elements on top of the frame. When footage has to meet an animation,+ see `into-footage.md`.++## Talking heads: cut the pauses++One scene per jump cut makes dozens of pages, each with its own decoder. Cut the pauses into a list instead and play+it in one scene (or one scene per section, each with its part of the list):++```bash+python3 scripts/cut_pauses.py footage/talk.mp4 cuts.json --start 1.4 --audio-out audio/voice-cut.wav+```++```js+const { cutList } = await import('/__motlab/cuts.js');+const edit = cutList(await (await fetch('../cuts.json')).json(), clip, { punch: [1, 1.12], glide: 0.25, drift: 0.008, x: 0.5, y: 0.42 });+window.renderAt = async t => { await window.ready; await edit.draw(ctx, t, 0, 0, W, H); /* captions, overlays */ };+```++- Put `audio/voice-cut.wav` in `project.json` at the scene's start, not the recording itself: it has the same cuts.+- `punch` alternates the framing at every cut (wide, closer, wide), which makes jump cuts look meant. `glide` eases the+ zoom over that many seconds after a cut; 0 is a hard punch-in, 0.2 to 0.3 a quick settle. Keep `drift` at 0.005 to+ 0.01: it adds up over a long part (0.012 is 14% closer after 12 s).+- `x`, `y` is the point that stays put (fractions of the recording, the face for a talking head). A segment in+ `cuts.json` can set its own `zoom`, `x` and `y`, for a closer shot on a key line.+- A dissolve (`--dissolve 0.12`) softens cuts in the picture and the sound but blurs the mouth for a moment; most+ talking heads look better with plain punch-ins. It needs `clip2`, a second `openFootage()` of the same file.+- `edit.parts[k].at` are the cut times, for a pop or swish on a cut. `edit.toOut(t)` maps a word time from a transcript+ of the recording to the edit. Whisper word times were about 0.23 s early in one take, so check captions by ear.+- Listen to the cut voice before building on it. Raise `--min-pause` if a deliberate pause was cut, and raise+ `--keep-tail` or `--keep-lead` if a cut clips the end or start of a word.++## Footage sound++List the video file in `project.json` like any audio file, with `from` (seconds into the file) and `duration`:++```json+{ "file": "footage/demo.mp4", "start": 4.0, "from": 12.5, "duration": 6, "volume": 1 }+```++`start` is where it begins in the finished video, `from` must match the in-point you pass to `clip.frame`. For a J or L+cut (sound starting before or running after its picture), give the audio entry an earlier `start` or a longer+`duration` than the scene. Duck music under speech by giving the music a lower `volume`, or split the music into two+entries around the speech.++## Limits++- Decoding uses WebCodecs, so the codec must be one Chrome decodes (H.264, HEVC, VP9, AV1, ProRes is not). Convert+ anything else first: `ffmpeg -i in.mov -c:v libx264 -crf 16 -c:a aac out.mp4`.+- The viewer decodes the whole audio of a video file to draw its waveform, so very long recordings load slowly there.+ Trim long recordings to the parts you use before listing them.+- No alpha output yet, so the result is always a flat MP4.diff --git a/skills/motlab/references/into-footage.md b/skills/motlab/references/into-footage.mdnew file mode 100644index 0000000..306be91--- /dev/null+++ b/skills/motlab/references/into-footage.md@@ -0,0 +1,53 @@+# Ending an animation inside real footage++Sometimes the animation has to hand over to a real clip: the rendered product lands exactly where the real one sits in+the first frame of the next shot, and the clip plays on. The clip has to be the user's own or licensed for this.++There are two ways to build it:++- **In motlab (the usual way).** The clip is a layer in the same scene (see `footage.md`). The animation ends on the+ clip's first frame and the clip plays on in the same page, so the user reviews and exports it like any other scene.+- **Outside motlab.** `scripts/compose_into_clip.py` joins a folder of transparent PNG frames to a clip with ffmpeg. The+ frames have to come from a transparent Blender render (`blender.md`), because motlab cannot export alpha.++```+python3 scripts/compose_into_clip.py frames/ clip.mp4 out.mp4 --start 2.0 --end 8 --fade 6.2 7.5 --melt 7.45 7.95 --sfx ad.wav+```++The rendered frames play over black. During `--fade` the black gives way to the clip's frame at `--start`, held still;+during `--melt` the rendered object fades out over the real one; at `--end` the clip itself runs on from `--start`.+`--sfx` is the animation's sound from 0 s, and the clip's own sound follows from `--end`. Output is 4K at 25 fps unless+`--w`, `--h` and `--fps` say otherwise.++## Work backwards from the target frame++Ask early which clip comes next and where in it the hand-over happens, then design the ending from that frame.++1. Export the frame: `ffmpeg -ss <seconds> -i clip.mp4 -frames:v 1 target.png`.+2. Measure the object in it: position, size, angle, which side faces the camera. Keep these numbers together in the+ scene so the last pose uses them.+3. Overlay the render's last frame on `target.png` and adjust until they line up.+4. Check the clip's frame rate with ffprobe; it is often not what the file name suggests.++## Hiding the join++- **Fade the black away** when the object is already in place: it settles on its target over black, the held frame+ fades in behind it, and the render dissolves into the real object over about half a second. This is what+ `compose_into_clip.py` does.+- **Pull back out of a dark shape** when the next shot has one (a hand, a silhouette): start with the held frame scaled+ up so far that a dark area fills the screen, then shrink it and the rendered object together so they move as one, and+ bring the object along a natural path to where it ends up. Mask with the footage's dark shapes so fingers pass in+ front of the render.+- **Match the look** of the footage by the end. Shaded 3D does not melt into flat, silhouetted footage; render the flat+ look instead (`blender.md`).+- If the real object has to be painted out of the held frame while the render moves, grow the fill a few pixels beyond+ the object's edge, or a faint outline stays.+- A white object on a white background disappears. Give it a thin dark edge if the footage shows one.++## Checking it++- Compare neighbouring frames around the join (mean difference per frame). A spike is a visible jump.+- The held frame is still, and the clip starts moving at once. If the footage moves fast, the start can feel abrupt;+ ask the user to watch it at full speed.+- Text must not end up on a background of its own colour after the hand-over.+- Let the sound carry across the join instead of stopping with the animation.diff --git a/skills/motlab/references/motion-and-libraries.md b/skills/motlab/references/motion-and-libraries.mdnew file mode 100644index 0000000..2607173--- /dev/null+++ b/skills/motlab/references/motion-and-libraries.md@@ -0,0 +1,154 @@+# Motion helpers and animation libraries++Every frame must come from `t` alone, because the renderer asks for frames in any order and the viewer jumps around.+That rules out anything that runs on its own clock. The tools below all work by being told the time.++## motion.js: easing, springs, keyframes, motion blur++Served by the renderer and the viewer, so a scene imports it the same way in both:++```js+const { ease, cubicBezier, spring, tween, stagger, prog, lerp, clamp, motionBlur } = await import('/__motlab/motion.js');+```++| Helper | What it does |+|---|---|+| `ease.outCubic(k)` and the rest | the usual curves: `linear`, `in/out/inOut` + `Sine`, `Quad`, `Cubic`, `Quart`, `Expo`, `Back`, plus `outBounce` and the CSS presets `css`, `cssIn`, `cssOut`, `cssInOut` |+| `cubicBezier(x1, y1, x2, y2)` | a CSS `cubic-bezier()` as an easing, e.g. one copied from a design tool or an After Effects graph |+| `spring({ stiffness, damping, mass, velocity })` | a spring from 0 to 1 solved exactly, so frame order does not matter. `spring(...).duration` is when it has settled within 0.1%. `damping` 10 at `stiffness` 100 overshoots by 16%; 20 is critically damped (no overshoot) |+| `tween(t, [[0, 0], [0.4, 120, ease.outBack], [1.2, [10, 20]]])` | keyframes of numbers or arrays, each with the easing into it |+| `stagger(i, 0.06, 0.3, { n, from: 'center' })` | the start time of item `i` in a staggered group |+| `prog(t, a, b)` | 0 to 1 between seconds `a` and `b` |+| `await motionBlur(canvas, t, async time => drawFrame(time), { samples: 8, shutter: 0.5 / fps })` | draws the frame across the shutter and averages it on `canvas`. Use it only on fast moves; it costs `samples` times the drawing |++A spring for an element that pops in after a beat: `const s = spring({ stiffness: 180, damping: 12 }); scale = s(t - beat)`.++## Transitions between scenes++Set in `project.json` on the scene a transition leads into. The viewer and the render draw it with the same shader:++```json+{ "file": "scenes/02.html", "transition": { "type": "crosswarp", "duration": 0.5, "ease": "inOutCubic", "params": {} } }+```++The two scenes overlap for `duration`, so the video gets that much shorter and every later scene starts that much+earlier. Audio `start` times are times in the finished video, so move them when you add a transition before them.+Both scenes need content for the whole overlap: the outgoing scene keeps playing under it and the incoming one has+already started, so do not end a scene on its last frame of motion. The types, from gl-transitions (MIT):++| Type | Look | Params (default) |+|---|---|---|+| `fade` | crossfade | |+| `fadecolor` | dip through a colour | `color` ([0, 0, 0]), `colorPhase` (0.4) |+| `Directional` | push: the new scene slides in and pushes the old one out | `direction` ([0, 1]) |+| `directionalwipe` | soft-edged wipe | `direction` ([1, -1]), `smoothness` (0.5) |+| `directionalwarp` | wipe that stretches both scenes | `direction` ([-1, 1]) |+| `circleopen` | iris | `smoothness` (0.3), `opening` (true) |+| `CrossZoom` | zoom blur through the cut | `strength` (0.4) |+| `crosswarp` | warp from one side | |+| `SimpleZoom` | zoom into the old scene, then fade | `zoom_quickness` (0.8) |+| `LinearBlur` | blur dissolve | `intensity` (0.1) |+| `cube` | 3D cube turn | `persp` (0.7), `unzoom` (0.3), `reflection` (0.4), `floating` (3) |++Names are not case sensitive. `ease` is any name from `motion.js` (default `inOutCubic`). In an ad, prefer the+transitions in `craft.md` that carry a shape across the cut; these are for edits, explainers and talking heads, where+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.++## Animation libraries++These were each checked with a box moving from x 100 to 1700 over 2 s: stills at 0.5, 1 and 1.5 s were identical+in forward and reverse order, the box was at 500, 900 and 1300, and the viewer showed it at 900 at 1 s. Pin the exact+version, as below. They load from jsDelivr, so a render needs the network.++**GSAP 3.15.0** (free, its own licence from Webflow, not MIT: it may not be used in a no-code visual animation+builder that competes with Webflow, and Webflow can change the terms). A paused timeline only moves when sought:++```html+<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/gsap.min.js"></script>+<script>+const state = { x: 100 };+const tl = gsap.timeline({ paused: true }).to(state, { x: 1700, duration: 2, ease: 'power3.out' });+window.renderAt = t => { tl.seek(t, false); draw(state); };+</script>+```++**Anime.js 4.5.0** (MIT). Times are in milliseconds:++```js+const { createTimeline } = await import('https://cdn.jsdelivr.net/npm/[email protected]/dist/bundles/anime.esm.min.js');+const tl = createTimeline({ autoplay: false }).add(state, { x: 1700, duration: 2000, ease: 'outExpo' });+window.renderAt = t => { tl.seek(t * 1000); draw(state); };+```++**Lottie (lottie-web 5.13.0, MIT)** plays After Effects animations exported with Bodymovin as JSON. Use the canvas+build. It draws into a canvas it makes inside the container (it ignores `rendererSettings.context`), so size the+container to the frame and copy that canvas:++```html+<div id="lot" style="position:fixed;left:-99999px;top:0"></div>+<script src="https://cdn.jsdelivr.net/npm/[email protected]/build/player/lottie_canvas.min.js"></script>+<script>+Object.assign(lot.style, { width: c.width / devicePixelRatio + 'px', height: c.height / devicePixelRatio + 'px' });+let anim;+window.ready = fetch('anim.json').then(r => r.json()).then(data => new Promise(ok => {+ anim = lottie.loadAnimation({ container: lot, renderer: 'canvas', loop: false, autoplay: false, animationData: data });+ anim.addEventListener('DOMLoaded', () => ok(true));+}));+window.renderAt = async t => {+ await window.ready; anim.goToAndStop(t * anim.frameRate, true); // in frames; fractions draw in-between frames+ ctx.drawImage(anim.renderer.canvasContext.canvas, 0, 0, c.width, c.height);+};+</script>+```++**Theatre.js core 0.7.2** (Apache-2.0) plays keyframes made in Theatre's visual editor (the studio, AGPL-3.0, used only+while editing and not shipped in the page). Export the project state from the studio as JSON and load it:++```js+const { getProject } = await import('https://cdn.jsdelivr.net/npm/@theatre/[email protected]/+esm');+const project = getProject('motlab', { state: await (await fetch('theatre-state.json')).json() });+await project.ready;+const sheet = project.sheet('Scene'), box = sheet.object('Box', { x: 0 });+window.renderAt = t => { sheet.sequence.position = t; draw(box.value); }; // seconds+```++The test used a state file written by hand, not one exported from the studio. Running the studio inside the motlab+viewer has not been tried.++Lottie files with image layers work, also with the image inside the JSON as a data URL. **Text layers need their+glyphs**: lottie-web's canvas build throws on a text layer exported without them (Bodymovin's "Glyphs" option), and it+swallows the error, so the whole animation stays on its first frame. Export with glyphs, or play the file with dotLottie.++**GSAP plugins** (SplitText, MorphSVGPlugin and DrawSVGPlugin ship in `[email protected]/dist/`). They change DOM and SVG+elements, so keep those elements hidden in the page and draw what they hold onto the canvas:++```js+gsap.registerPlugin(SplitText, MorphSVGPlugin, DrawSVGPlugin);+const split = SplitText.create('#title', { type: 'chars' }); // #title: visibility:hidden, same font as the canvas+const tl = gsap.timeline({ paused: true })+ .to('#shape', { morphSVG: '#target', duration: 2 }, 0) // read back: new Path2D(shape.getAttribute('d'))+ .fromTo('#line', { drawSVG: '0%' }, { drawSVG: '100%', duration: 2 }, 0) // read back: line.style.strokeDasharray and strokeDashoffset+ .from(split.chars, { y: 160, opacity: 0, stagger: 0.1, duration: 0.5 }, 0);+window.renderAt = t => { tl.seek(t, false);+ for (const ch of split.chars) { ctx.globalAlpha = +gsap.getProperty(ch, 'opacity'); ctx.fillText(ch.textContent, x0 + ch.offsetLeft, y0 + gsap.getProperty(ch, 'y')); } };+```++Wait for `document.fonts.ready` before `SplitText.create`, or the letters are measured in the fallback font. All three+gave the same stills forward and in reverse order.++**dotLottie (`@lottiefiles/dotlottie-web` 0.82.0, MIT)** plays `.lottie` and Lottie JSON with its own renderer (ThorVG,+WebAssembly) and handles text layers without glyphs, in its own font when the file has none:++```js+const { DotLottie } = await import('https://cdn.jsdelivr.net/npm/@lottiefiles/[email protected]/+esm');+const player = new DotLottie({ canvas: off, src: 'anim.lottie', autoplay: false, loop: false, renderConfig: { autoResize: false, devicePixelRatio: 1 } });+window.ready = new Promise((ok, no) => { player.addEventListener('load', () => ok(true)); player.addEventListener('loadError', no); });+window.renderAt = async t => { await window.ready; player.setFrame(Math.min(t * FPS, player.totalFrames - 1)); ctx.drawImage(off, 0, 0, c.width, c.height); };+```++`off` is a second canvas the size of `#c`, kept off screen. A `.lottie` file it cannot read fires neither `load` nor+`loadError`, so the page never becomes ready; the render then says it is still waiting after 30 s. Stills were the+same forward and in reverse.++Not tested: Rive.diff --git a/skills/motlab/references/pitfalls.md b/skills/motlab/references/pitfalls.mdnew file mode 100644index 0000000..370fe32--- /dev/null+++ b/skills/motlab/references/pitfalls.md@@ -0,0 +1,50 @@+# Pitfalls++Problems that are easy to hit with motlab's scenes and scripts, what causes them and what to do.++## Rendering++| What you see | Why | What to do |+|---|---|---|+| A 3D scene renders black or empty | WebGL2 has no GPU to run on | motlab starts Chrome on the GPU and prints a `GPU:` line; if it names no GPU, fix the driver or Chrome first |+| Fast moves show separate copies instead of a blur | too few motion-blur sub-frames | 12 sub-frames over half a frame; fewer than 8 shows steps |+| Two renders at once fail or freeze the machine | GPU memory and encoder sessions run out | one or two renders at a time |+| A long Blender render stopped part way | a crash or a sleep | run the same command again; finished frames are skipped |+| A contact sheet made with ffmpeg's `tile` comes out empty | `-frames:v` counts output sheets, not input frames | trim with `-t` first, then `tile`, then `-frames:v 1`, or use `contact_sheet.py` on `motlab stills` |++## Drawing++| What you see | Why | What to do |+|---|---|---|+| Canvas shadows are the wrong size at 4K | shadow offsets and blur ignore the canvas transform | multiply them by `SCALE` |+| A thin grid flickers while the shot pushes in | lines of 1 to 2 px are resampled differently each frame | lines of about 3.5 px, low opacity, moved in whole pixels |+| Text slips behind a card in 3D | panels are ordered by depth | give the text panel a `bias` |+| An end logo sits off centre | the image file has empty margins, or the camera still drifts | centre it by its visible bounds and keep the last shot still |+| A gradient headline is hard to read on a colour field | low contrast between the gradient and the field | solid text on colour fields; gradients on dark backgrounds |+| Code after a `//` comment stopped running | the comment was put in the middle of a long one-line statement | put comments at the end of a line; check stills after editing |++## Motion++| What you see | Why | What to do |+|---|---|---|+| Held poses look uneven | 25 fps does not divide by 8 or 12 poses a second | render posed animation at 24 fps |+| A move has a bump in the middle | two curves joined at a hand-over | one `tracks.py` curve, or one easing, for the whole move |+| A fade ends with a snap | an easing that is still fast at its end | an ease that slows at both ends |+| A shape flips inside out while it morphs | it is interpolated towards a curve that bends the other way | change its curvature first, then move it |+| Morphing pieces collide | each piece moves at its own speed | drive them from one shared value with even spacing |++## Cut-outs and 3D shapes++| What you see | Why | What to do |+|---|---|---|+| A cut-out lost a part that shares the background colour | enclosed patches of that colour are removed, or the removal leaked in from the bottom edge | `key.py --keep-pockets` or `--no-bottom` |+| A moved layer leaves a hole behind it | the art was cut where objects overlap | redraw the scene as shapes |+| A small hole in a mesh closed up | too much smoothing | lower `smooth=` for that part |+| A white product disappears on a white background | nothing separates their edges | a thin dark outline where they meet |+| A fill in a frame shows a hard line round it | the fill stops at the anti-aliased edge | grow the fill mask by a few pixels |++## Files++| What you see | Why | What to do |+|---|---|---|+| A screen recording cannot be opened | it is still in the temporary folder the screenshot tool saves to | ask the user to save it to a normal folder |diff --git a/skills/motlab/references/sound-and-music.md b/skills/motlab/references/sound-and-music.mdnew file mode 100644index 0000000..1f971fa--- /dev/null+++ b/skills/motlab/references/sound-and-music.md@@ -0,0 +1,144 @@+# Sound effects, voiceover and music++Sound can be built with the first version or added later, once the user has music and effects. Any revision that moves+a beat moves the sound with it, so run the mix again after timing changes.++## Effects: `scripts/mix.py`++### 1. Take the beats from the page++Never type beat times into the mix by hand. Give each scene a `window.EVENTS` list made from the same constants that+drive its animation, for example `[{ name: 'card.open', t: T.cardOpen }, ...]`, and include beats that are computed+(every step of a sequence, every landing, every word of a headline). Export it with+`motlab events page.html events.json`. A cue that names `"event": "card.open"` then follows the animation when it is+re-timed. `EVENTS` times are per scene: for cues across several scenes, add each scene's start time (the `TOTAL`s of+the scenes before it).++When the animation holds poses (8 or 12 a second), pass the same number as `--quant`: each event moves to the start of+the pose in which its change is first visible.++### 2. Find the sounds++- Ask whether the user has a sound library, or look for folders of WAV files on the machine. List them by name and+ folder before choosing, and with earshot (below) by what they actually sound like. Copy the ones this video uses+ into its folder. Recorded libraries sound richest, but read their licence for this kind of use.+- With no library, `python3 scripts/synth_sfx.py sounds/` writes a small set made from noise and sine waves (whooshes,+ a pop, a tick, a thud, a shutter, a riser, an air bed). Plainer than recordings, but free and offline. Add a function+ to the script when a video needs a sound it lacks.+- For recorded sounds, `python3 scripts/get_sfx.py search "soft whoosh" --max 2` searches Openverse (CC0 by default;+ `--license commercial` adds CC BY and BY-SA, which need a credit), and+ `python3 scripts/get_sfx.py get <id> ... --out <video>/audio/sfx` downloads them and writes `CREDITS.md` with a credit+ line for each. Without a key Openverse allows 20 requests a minute and 200 a day. Most results are Freesound's MP3+ previews, which are fine for UI sounds and whooshes. Ask before downloading, and tell the user which sounds need a+ credit.++### 3. Write the cues++`cues.json` has one entry per beat, for example `{"event": "card.open", "file": "pop", "role": "pop"}`. The header of+`mix.py` lists every field.++- `role` sets the level and how the sound sits on the beat, so most cues need nothing else. Levels are the cue's peak+ in dBFS, from the [Clipwing real-sfx skill](https://clipwing.pro/skills/real-sfx): `hit` -4, `whoosh` -9, `riser` -12,+ `click`, `ui`, `pop`, `tap`, `key` and `tick` -14, `ambience` -24. A quiet layer under another sound takes its own+ `"db"`, for example -28.+- The anchor is the point of the sound placed on the beat. Struck sounds use the moment they become audible, past any+ silence at the start of the file, so they never come before the motion. A whoosh uses its loudest point, in the middle+ of the move. A riser uses its end, on the reveal. Library files often start with 30 to 150 ms of near silence, so a+ file placed by its first sample sounds late; measuring where it becomes audible avoids that.+- Without a role, `align` is `auto` and measured from the sound: `start` if it peaks within 60 ms of becoming audible,+ `arrive` (first within 3 dB of the peak) if it is nearly full at least 100 ms before its peak, `peak` otherwise. Set+ `"align"` to `start`, `arrive`, `peak` or `end` to choose. The printout marks automatic choices with `*`. Cue files+ from before 2026-11-13 without `align` used `peak`; add `"align": "peak"` to keep that.+- `pitch` varies a repeated sound (a run of clicks climbing from 0.9 to 1.3), `lp` and `hp` soften it, `dur` cuts a long+ tail, `pan` places it left or right.+- Beds (`"type": "bed"`) are long layers: looped if short, faded in and out, with an `env` of level changes over time.++### 4. Mix++```+python3 scripts/mix.py cues.json "<video>/audio/sfx.wav" --lib sounds/ --events events.json [--gain -2]+```++It reads WAV, AIFF, MP3, FLAC, OGG, Opus and M4A. For each cue it prints how far the anchor landed from its beat+(0 ms is right; more than a frame is a bug), then the peak level. With a voiceover, add `--voice <video>/audio/voice.wav`+(the voice as it plays in the video, from 0 s): effects drop 9 dB while it speaks (`--duck 6` for less). On a test mix+that measured -9.0 dB under speech and less than 1 dB of reduction half a second after the speech stopped.++It warns about:++- a cue outside 0 to `--len`, which is cut off or silent (often a per-scene event time missing its scene's start);+- one file five or more times in a row (except ticks and keys): use another file or vary `pitch`;+- `tick`, `key` and `pop` cues closer than 66, 87 and 114 ms, where they start to blur (from earshot's launch kit).++Last, it lists up to five moments to **listen to by ear**: the first sound, the loudest cue, the busiest second, any+gap of more than 2.5 s, and with `--voice` the loudest cue under speech. You cannot hear the result, so pass these+moments on to the user when you open the viewer.++A full sound bed usually has three layers: two to four quiet beds (a soft tonal pad, a high airy layer, a faint+texture) that lift towards the reveal; soft whooshes (-26 to -33 dB) under camera and object moves; and the hits, pops+and clicks on top, with a riser and a low hit under the final reveal. Measure the loudness with+`ffmpeg -i sfx.wav -af loudnorm=print_format=summary -f null -` and look at a waveform (`showwavespic`) for silent+stretches. An effects-only track around -20 LUFS with peaks below -2 dBFS leaves room for music.++### 5. Add it to the project++Save the WAV in `<video>/audio/` and list it in `project.json`. The viewer plays it and Export mixes it in.++### Taste++- Aim for clean, light sounds: soft pops, tonal clicks, wooden or glassy taps, airy whooshes.+- Save whooshes for things that travel: the camera, a sliding panel. A cut or a shape change sounds better as a pop,+ a tick or a soft hit.+- Leave out bells and dings, typing sounds and hums, and never play one file identically several times in a row.+- Let the sound say what happens: pieces locking together click, a panel opening slides, a reveal rises and lands.++## earshot, when the user has it++[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.+- 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.++With earshot, use it at three points, and read `earshot <command> --help` for the arguments rather than guessing them:++1. **Choosing sounds** (step 2). `earshot find` and `match` search a library by what the sounds are, not their names,+ and `describe` says what one sound is. Use them to shortlist from a big library, then still check onset and length+ with `mix.py`'s printout. Each call loads the models again (20 to 40 s), so batch questions into few calls.+2. **Checking the mix** (step 4). `earshot measure` gives LUFS, true peak and loudness range without loading models.+ Measure the effects track and a full mix with voice and music. `critique` and `timeline` on the full mix can point+ at silent stretches or a cue that covers a word.+3. **Filling a gap** with no fitting sound in the library: `earshot sfx list --kind whoosh`, then+ `earshot sfx render <id> -o <video>/audio/sfx/<name>.wav --dur 0.8` renders one from code, nothing downloaded.++Its words are hints, not taste: it cannot judge whether a sound fits the brand, knows nothing of licences, and hears+nothing above 14 kHz. Say in the hand-off which checks came from earshot, and keep the "listen by ear" moments for the user.++## Voiceover++If the user has ElevenLabs connected to the agent (a connector or MCP server), the agent can write the script to the+exact timing of the scenes and generate the voice in the same session. Each take costs the user ElevenLabs+credits, so make one only on request. Without the connection, the user pastes your script into ElevenLabs themselves.++- Budget roughly 2.2 words per second so the delivery is not rushed. A 10-second video holds 18 to 22 words, and the+ end card's last two seconds stay quiet.+- Write a line for each shot in the way the brand talks, and finish on its slogan.+- Only claims the user can back up; no promised results.+- Add delivery notes (pace, mood, pauses, which word carries the stress) and offer a second version aimed at another+ audience. When the real take arrives, re-time the scene constants to it.++## Music++Write a prompt for a music generator such as Suno with the exact length the video needs. The user generates the track and+sends the file, which goes into `project.json` at a level below the effects and the voice. Check whether the user has+a connector for the service before assuming they work in its website, and point out that commercial use can depend on+their plan.++- Match the tempo to anything rhythmic on screen: pulses every 0.62 s are 97 BPM.+- Offer two or three directions. For each, give a style line and a structure (intro, build, drop, outro, instrumental)+ with the lift landing on the reveal. For example: "warm minimal house, 97 BPM, instrumental, soft round kick, muted+ plucks, gentle chords, bright and calm", or "playful indie electronic, 97 BPM, instrumental, hand claps, bouncy bass,+ toy-piano melody, cheerful".+- Cut the track so its biggest change lands on the reveal, and keep the music 8 to 10 dB under the effects so the+ details still come through.diff --git a/skills/motlab/references/style-rules.md b/skills/motlab/references/style-rules.mdnew file mode 100644index 0000000..02478e7--- /dev/null+++ b/skills/motlab/references/style-rules.md@@ -0,0 +1,70 @@+# The ad preset++A house style for short product, app and brand ads (about 8 to 20 seconds). Turn it on when the brief is that kind of+ad, when the user asks for it, or when their references look like it. Otherwise the references decide the look and only+`craft.md` applies. When the preset is on, apply all of it to every scene, not only to the scene a note was about.++## Structure++- Pick one path through the product and show it as 5 to 10 beats, one per line of voiceover: for an app, opening it,+ finding something, choosing, using it, then the brand. Each beat is a shot.+- Open on something that grabs the eye within a second: a flood of the brand colour, the logo flying in, a character+ caught mid-move.+- Leave time. Viewers need longer than a first draft gives them, especially for anything with text or a quick flip;+ when in doubt, slow a fast moment by half again.+- When the user wants several versions, make them differ in camera and look, not just in copy.++## Camera++- In 3D, one camera for the whole ad. Moves start quickly and settle slowly (an exponential ease out), with no sudden+ bursts of speed in the middle of a move.+- A move keeps its direction. Do not push in and then pull back on the same subject, and do not let an orbit swing back.+ If a card has to end facing the camera, let the move arrive there.+- Something is always moving, even if only a slow drift, so no frame looks frozen between two big moves.+- On a long scroll or pan, change the angle as it goes so the screen does not sit flat and still.++## Shot changes++- Each shot hands over to the next through a shape: an object in the outgoing shot (a button, a card, a logo, an+ avatar) grows until it fills the frame and becomes the next shot's background. Circles, rounded squares and cards+ turn into each other.+- Fill the growing shape with the next shot's colour first and let the next shot's content settle in a moment later,+ from slightly smaller to full size. Cutting straight to the next shot inside the shape looks abrupt by comparison.+- A small squash just before the shape grows gives it a push.+- Pieces that move together should share one speed and one spacing, and things meant to happen at once should happen at+ once.+- Curves keep bending the same way while they morph; one that flattens and flips looks broken.++## Framing and text++- Centre the subject, and keep the last shot perfectly still and centred, using the logo's visible bounds.+- Leave space for headlines, usually at the top, and keep them away from where things will move.+- Headlines in the brand's font, sentence case, short, with tight letter spacing (about -3%). Reveal them word by word,+ each word rising and sharpening with a short stagger (0.06 to 0.09 s), and take them away the same way. Avoid letters+ fading one by one, bouncing text and pops in scale.+- A gradient on text only on dark backgrounds. On a colour field use solid ink.+- On the end card, the tagline or URL is much smaller than the wordmark and sits below it. Typing the URL into a search+ field with a blinking caret is a clear call to action.++## Interfaces and assets++- Use the product's real screens, from the user's screenshots, cleaned up: personal names and photos replaced with+ neutral placeholders, notifications and unrelated apps removed, and every state correct (a playing track shows pause).+- Icons, wordmarks and buttons that the camera moves close to are drawn again as vector paths; a screenshot blurs at+ that size in 4K.+- A phone is built, not photographed: dark glass, a thin bezel, a frame with some depth. Side buttons only if their+ exact position is known.+- Characters from a brand's illustrations are cut out and puppeted; objects are redrawn as shapes (`engine-2d-puppet.md`).+- For a spec ad (made without the brand's involvement), add a small note at the end saying so, and do not borrow the+ brand's campaign lines.++## Finish++- Flat 2D work can hold poses (8 to 12 a second, rendered at 24 fps), with a pixel or two of jitter per pose and hard+ flat shadows, which gives it a hand-made feel.+- Reward the payoff beats with something small: a burst of short lines, a check mark stamping in, a little confetti+ in the brand colours, a quick flash as the logo lands, a light sweeping across the wordmark.+- In 3D, a shallow depth of field keeps the subject sharp and the rest soft, which makes it feel filmed. A physical+ product gets a single soft light (`blender.md`).+- Leave out soft drop shadows everywhere, lens flares, light leaks, wobbly text and glow on everything.+- End with what the viewer should do: download it, visit the URL, sign up.diff --git a/skills/motlab/requirements.txt b/skills/motlab/requirements.txtnew file mode 100644index 0000000..9e7e585--- /dev/null+++ b/skills/motlab/requirements.txt@@ -0,0 +1,5 @@+# Python packages for the skill's helper scripts (contact sheets, sound effects, mixing, keying, splitting).+# The engine itself does not need Python.+numpy+scipy+pillowdiff --git a/skills/motlab/scripts/blender/example_scene.py b/skills/motlab/scripts/blender/example_scene.pynew file mode 100644index 0000000..0f23332--- /dev/null+++ b/skills/motlab/scripts/blender/example_scene.py@@ -0,0 +1,72 @@+"""A small complete Blender scene: a white speaker with a dark band rises, turns and settles under one light while the+camera eases in. Copy it next to your assets and replace the object.++Build the meshes first (plain Python), then render (Blender with no window):++ python3 example_scene.py mesh+ blender -b -P example_scene.py -- frames 1280 24 [flat] [times...]+"""+import math+import os+import sys++HERE = os.path.dirname(os.path.abspath(__file__))+sys.path.insert(0, HERE)+MESH = os.path.join(HERE, 'example_mesh')+END, FPS = 4.0, 25++if len(sys.argv) > 1 and sys.argv[1] == 'mesh':+ import numpy as np+ import mesh_from_sdf as sdf++ # The outline of half the speaker as (radius, height), spun round its upright axis. The shapes are y-up.+ outline = sdf.chaikin(np.array([(0, -0.62), (0.5, -0.62), (0.6, -0.5), (0.63, 0.25), (0.5, 0.58), (0.2, 0.66), (0, 0.66)]), 4)+ spun = sdf.revolve(outline, rmax=0.8, zmin=-0.8, zmax=0.8, res=500)++ def body(x, y, z):+ return spun(x, z, y)++ def band(x, y, z):+ surface = body(x, y, z)+ shell = np.maximum(surface - 0.008, -(surface + 0.02)) # a thin skin just over the body+ return np.maximum(shell, np.abs(y + 0.12) - 0.16) # only round the lower middle++ sdf.nets(body, (-0.75, -0.75, -0.75), (0.75, 0.8, 0.75), 0.01, 'body', MESH)+ sdf.nets(band, (-0.75, -0.35, -0.75), (0.75, 0.1, 0.75), 0.008, 'band', MESH)+ sys.exit()++import kit+import tracks+from mathutils import Euler++OUT, WIDTH, SAMPLES, FLAT, TIMES = kit.args()+kit.fresh()+kit.setup(WIDTH, SAMPLES, FPS)++white = kit.mat('white', (0.85, 0.85, 0.84), rough=0.25, coat=0.5, sss=0.1)+dark = kit.mat('dark', (0.015, 0.015, 0.018), rough=0.7)+upright = kit.empty('upright')+upright.rotation_quaternion = Euler((math.pi / 2, 0, 0)).to_quaternion() # y-up meshes into Blender's z-up+speaker = kit.empty('speaker', upright)+kit.load_npz(os.path.join(MESH, 'body.npz'), white, speaker)+kit.load_npz(os.path.join(MESH, 'band.npz'), dark, speaker, smooth=4)++cam = kit.camera()+cam.data.lens = 80+kit.key_light((-9, -8, 10), size=(6, 8), power=3800)+if FLAT:+ kit.flat_mode(black_materials=('dark',))++# Every curve only moves one way, so nothing turns back on itself.+lift = tracks.mono([(0, -0.5), (1.6, 0.05), (END, 0.1)])+spin = tracks.mono([(0, -1.4), (2.4, 0.15), (END, 0.35)])+eye = tracks.tracks([(0, (1.2, -9.5, 1.6)), (2.0, (0.5, -6.6, 1.0)), (END, (0.2, -5.8, 0.8))])+++def pose(t):+ speaker.location = (0, lift(t), 0) # in the upright parent, y is up+ speaker.rotation_quaternion = Euler((0, spin(t), 0), 'XYZ').to_quaternion()+ kit.look_at(cam, eye(t), (0, 0, 0.05))+++kit.render(pose, [speaker, cam], END, FPS, OUT, TIMES)diff --git a/skills/motlab/scripts/blender/kit.py b/skills/motlab/scripts/blender/kit.pynew file mode 100644index 0000000..da72801--- /dev/null+++ b/skills/motlab/scripts/blender/kit.py@@ -0,0 +1,248 @@+"""Helpers for rendering a product shot with Blender and Cycles, with no window open.++A scene script puts this folder on sys.path, imports kit, builds its objects and calls kit.render():++ blender -b -P scene.py -- <out dir> <width> <samples> [flat] [times...]++Frame f (from 1) shows the scene at (f - 1) / fps seconds and is saved as <out dir>/<f:04d>.png with a transparent+background. Frames that already exist are skipped, so running the same command again after a crash carries on.+Given times (in seconds), only the frames nearest those times are rendered, for quick checks.+"""+import os+import sys++import bpy+import numpy as np+from mathutils import Quaternion, Vector+++def args():+ """The arguments after `--`: (out dir, width, samples, flat, times)."""+ rest = sys.argv[sys.argv.index('--') + 1:] if '--' in sys.argv else []+ flat = 'flat' in rest+ rest = [a for a in rest if a != 'flat']+ if len(rest) < 3:+ sys.exit('usage: blender -b -P scene.py -- <out dir> <width> <samples> [flat] [times...]')+ return os.path.abspath(rest[0]), int(rest[1]), int(rest[2]), flat, [float(a) for a in rest[3:]]+++def fresh():+ """An empty scene, with no default cube, light or camera."""+ bpy.ops.wm.read_factory_settings(use_empty=True)+ return bpy.context.scene+++def _link(obj, parent=None):+ bpy.context.scene.collection.objects.link(obj)+ obj.parent = parent+ obj.rotation_mode = 'QUATERNION'+ return obj+++def empty(name, parent=None):+ """A null object to group and move other objects."""+ return _link(bpy.data.objects.new(name, None), parent)+++def mat(name, base, rough=0.3, coat=0.0, metal=0.0, sss=0.0):+ """A Principled BSDF material. base is linear RGB in 0..1."""+ m = bpy.data.materials.new(name)+ m.use_nodes = True+ bsdf = next(n for n in m.node_tree.nodes if n.type == 'BSDF_PRINCIPLED')+ values = {'Base Color': (*base, 1.0), 'Roughness': rough, 'Metallic': metal,+ 'Coat Weight': coat, 'Subsurface Weight': sss}+ for socket, value in values.items():+ if socket in bsdf.inputs:+ bsdf.inputs[socket].default_value = value+ return m+++def load_npz(path, material, parent=None, smooth=20):+ """A mesh written by mesh_from_sdf.nets(), shaded smooth, with a Smooth modifier of `smooth` iterations."""+ data = np.load(path)+ name = os.path.splitext(os.path.basename(path))[0]+ mesh = bpy.data.meshes.new(name)+ mesh.from_pydata(data['v'].astype(float).tolist(), [], data['f'].tolist())+ mesh.validate()+ mesh.polygons.foreach_set('use_smooth', [True] * len(mesh.polygons))+ mesh.update()+ mesh.materials.append(material)+ obj = _link(bpy.data.objects.new(name, mesh), parent)+ if smooth:+ mod = obj.modifiers.new('smooth', 'SMOOTH')+ mod.factor = 0.6+ mod.iterations = smooth+ return obj+++def load_model(path, parent=None):+ """Import a .glb, .gltf, .fbx or .obj file and return the objects it added."""+ before = set(bpy.data.objects)+ ext = os.path.splitext(path)[1].lower()+ if ext in ('.glb', '.gltf'):+ bpy.ops.import_scene.gltf(filepath=path)+ elif ext == '.fbx':+ bpy.ops.import_scene.fbx(filepath=path)+ elif ext == '.obj':+ bpy.ops.wm.obj_import(filepath=path)+ else:+ raise ValueError(f'cannot import {ext} files')+ added = [o for o in bpy.data.objects if o not in before]+ if parent is not None:+ for o in added:+ if o.parent is None:+ o.parent = parent+ return added+++def _aim(obj, eye, target, roll=0.0):+ obj.location = eye+ obj.rotation_quaternion = (Vector(target) - Vector(eye)).to_track_quat('-Z', 'Y') @ Quaternion((0, 0, 1), roll)+++def key_light(loc, size=(7, 9), power=4200, target=(0, 0, 0)):+ """One large, soft rectangular area light aimed at target. A single source is what makes the shot look lit."""+ light = bpy.data.lights.new('key', 'AREA')+ light.shape = 'RECTANGLE'+ light.size, light.size_y = size+ light.energy = power+ obj = _link(bpy.data.objects.new('key', light))+ _aim(obj, loc, target)+ return obj+++def camera():+ """A camera that becomes the scene's camera. Aim it with look_at()."""+ obj = _link(bpy.data.objects.new('cam', bpy.data.cameras.new('cam')))+ bpy.context.scene.camera = obj+ return obj+++def look_at(cam, eye, target, roll=0.0):+ _aim(cam, eye, target, roll)+++def _use_gpu(scene):+ prefs = bpy.context.preferences.addons['cycles'].preferences+ for backend in ('OPTIX', 'CUDA', 'HIP', 'METAL', 'ONEAPI'):+ try:+ prefs.compute_device_type = backend+ prefs.get_devices()+ except Exception:+ continue+ found = [d for d in prefs.devices if d.type == backend]+ if found:+ for d in prefs.devices:+ d.use = d.type == backend+ scene.cycles.device = 'GPU'+ return backend+ scene.cycles.device = 'CPU'+ return 'CPU'+++def setup(width, samples, fps, world=0.002):+ """Cycles on the GPU when there is one, a 16:9 frame `width` wide, a transparent film, a near-black world,+ motion blur over half a frame, and the AgX view transform."""+ scene = bpy.context.scene+ scene.world = bpy.data.worlds.new('world')+ scene.world.use_nodes = True+ background = next(n for n in scene.world.node_tree.nodes if n.type == 'BACKGROUND')+ background.inputs['Color'].default_value = (world, world, world, 1)++ scene.render.engine = 'CYCLES'+ print('Cycles device:', _use_gpu(scene), flush=True)+ c = scene.cycles+ c.samples = samples+ c.use_adaptive_sampling = True+ c.adaptive_threshold = 0.04+ c.use_denoising = True+ c.max_bounces = 4++ r = scene.render+ r.resolution_x, r.resolution_y, r.resolution_percentage = width, width * 9 // 16, 100+ r.fps = fps+ r.film_transparent = True+ r.use_motion_blur = True+ r.motion_blur_shutter = 0.5+ r.use_persistent_data = True+ r.image_settings.file_format = 'PNG'+ r.image_settings.color_mode = 'RGBA'++ scene.view_settings.view_transform = 'AgX'+ for look in ('AgX - Medium High Contrast', 'Medium High Contrast'):+ try:+ scene.view_settings.look = look+ break+ except TypeError:+ pass+ return scene+++def flat_mode(black_materials=()):+ """The silhouette look: every mesh flat white, except meshes whose first material is named in black_materials,+ which go flat black. Text objects are hidden. No shading, no denoising, no tone mapping."""+ def emission(name, level):+ m = bpy.data.materials.new(name)+ m.use_nodes = True+ nodes = m.node_tree.nodes+ nodes.clear()+ glow = nodes.new('ShaderNodeEmission')+ glow.inputs['Color'].default_value = (level, level, level, 1)+ m.node_tree.links.new(glow.outputs[0], nodes.new('ShaderNodeOutputMaterial').inputs['Surface'])+ return m++ white, black = emission('flat white', 1.0), emission('flat black', 0.0)+ for obj in bpy.data.objects:+ if obj.type == 'FONT':+ obj.hide_render = True+ elif obj.type == 'MESH' and obj.data.materials:+ base = obj.data.materials[0].name.split('.')[0]+ obj.data.materials[0] = black if base in black_materials else white+ scene = bpy.context.scene+ scene.view_settings.view_transform = 'Standard'+ scene.view_settings.look = 'None'+ scene.cycles.use_denoising = False+ scene.cycles.use_adaptive_sampling = False+ scene.cycles.filter_width = 1.5+ scene.render.dither_intensity = 0+++def keyframe(objects, frame):+ """Key location, rotation and scale. A quaternion that flipped sign since the last key is flipped back, so the+ rotation between keys takes the short way round."""+ for obj in objects:+ q = obj.rotation_quaternion.copy()+ last = obj.get('_last_q')+ if last is not None and Quaternion(last).dot(q) < 0:+ obj.rotation_quaternion = Quaternion((-q.w, -q.x, -q.y, -q.z))+ obj['_last_q'] = list(obj.rotation_quaternion)+ for path in ('location', 'rotation_quaternion', 'scale'):+ obj.keyframe_insert(path, frame=frame)+++def render(setf, animated, end, fps, out, times=()):+ """Call setf(t) for every frame of `end` seconds, key the animated objects, then render the frames.++ setf poses the scene for time t. animated lists every object setf moves, the camera included.+ """+ scene = bpy.context.scene+ count = max(1, round(end * fps))+ prefs = bpy.context.preferences.edit+ old = prefs.keyframe_new_interpolation_type+ prefs.keyframe_new_interpolation_type = 'LINEAR' # keys on every frame; straight lines between them+ for f in range(1, count + 2): # one extra key so the last frame has motion blur+ setf((f - 1) / fps)+ keyframe(animated, f)+ prefs.keyframe_new_interpolation_type = old+ scene.frame_start, scene.frame_end = 1, count++ wanted = sorted({min(count, max(1, round(t * fps) + 1)) for t in times}) if times else range(1, count + 1)+ os.makedirs(out, exist_ok=True)+ for f in wanted:+ path = os.path.join(out, f'{f:04d}.png')+ if os.path.isfile(path) and os.path.getsize(path):+ continue+ scene.frame_set(f)+ scene.render.filepath = path+ bpy.ops.render.render(write_still=True)+ print('FRAME', f, flush=True)diff --git a/skills/motlab/scripts/blender/mesh_from_sdf.py b/skills/motlab/scripts/blender/mesh_from_sdf.pynew file mode 100644index 0000000..be2ef5d--- /dev/null+++ b/skills/motlab/scripts/blender/mesh_from_sdf.py@@ -0,0 +1,178 @@+"""Turn a signed distance function into a smooth quad mesh, for products that have no 3D model.++Plain Python with numpy and scipy; it does not run inside Blender. Describe the shape as f(x, y, z) -> distance,+negative inside, using numpy arrays, then call++ nets(f, lo=(x0, y0, z0), hi=(x1, y1, z1), step=0.01, name='body', out='mesh')++which writes mesh/body.npz with `v` (vertices, float32, n x 3) and `f` (quads, int32, m x 4, counter-clockwise seen+from outside). kit.load_npz() reads it in Blender and the asset skill's mesh_export.py writes it as GLB and OBJ.++The mesher is surface nets: one vertex per grid cell the surface passes through, placed at the average of the points+where the surface crosses that cell's edges, and one quad around every grid edge the surface crosses.++Shapes are y-up. The helpers below build the usual parts: smooth unions and cuts, ellipsoids, rounded bars,+superellipsoid recesses, and outlines spun round an axis.+"""+import os++import numpy as np+from scipy.ndimage import map_coordinates+++# ---- combining shapes ---------------------------------------------------------------------------------------------++def smin(a, b, k):+ """Union of two shapes with a fillet about k wide where they meet."""+ h = np.maximum(k - np.abs(a - b), 0) / k+ return np.minimum(a, b) - h * h * k * 0.25+++def smax(a, b, k):+ """Intersection with a fillet. smax(shape, -hole, k) cuts hole out of shape with a soft edge."""+ return -smin(-a, -b, k)+++# ---- parts --------------------------------------------------------------------------------------------------------++def ellipsoid(x, y, z, rx, ry, rz):+ """An ellipsoid centred on the origin (a close approximation of the true distance near the surface)."""+ scaled = np.sqrt((x / rx) ** 2 + (y / ry) ** 2 + (z / rz) ** 2)+ grad = np.sqrt((x / rx ** 2) ** 2 + (y / ry ** 2) ** 2 + (z / rz ** 2) ** 2) + 1e-9+ return scaled * (scaled - 1) / grad+++def extrude(d2, along, start, end):+ """Extend a 2D distance d2 (computed across the other two axes) between start and end on one axis."""+ half = (end - start) / 2+ out_of_range = np.abs(along - (start + end) / 2) - half+ return np.minimum(np.maximum(d2, out_of_range), 0) + np.hypot(np.maximum(d2, 0), np.maximum(out_of_range, 0))+++def pill(x, y, z, y0, y1, a, b):+ """An upright bar from y0 to y1: across x it is 2a wide, across z 2b deep, with round sides of radius b."""+ across = np.hypot(np.maximum(np.abs(x) - (a - b), 0), z) - b+ return extrude(across, y, y0, y1)+++def rounded_pocket(x, y, z, a, b, ry, p=3.2):+ """A squarish scoop: a superellipse a x b across x and z (higher p is boxier), rounded to depth ry along y."""+ ring = (np.abs(x / a) ** p + np.abs(z / b) ** p) ** (1 / p)+ return (np.sqrt(ring ** 2 + (y / ry) ** 2) - 1) * 0.8 * min(a, b, ry)+++def polygon_2d(u, v, points):+ """Signed distance from (u, v) to a closed polygon, negative inside."""+ pts = np.asarray(points, float)+ u, v = np.broadcast_arrays(np.asarray(u, float), np.asarray(v, float))+ nearest = np.full(u.shape, np.inf)+ crossings = np.zeros(u.shape, bool)+ for (ax, ay), (bx, by) in zip(pts, np.roll(pts, -1, axis=0)):+ ex, ey = bx - ax, by - ay+ px, py = u - ax, v - ay+ s = np.clip((px * ex + py * ey) / (ex * ex + ey * ey + 1e-18), 0, 1)+ nearest = np.minimum(nearest, (px - s * ex) ** 2 + (py - s * ey) ** 2)+ straddles = (ay > v) != (by > v) # a ray towards +u crosses this edge+ with np.errstate(divide='ignore', invalid='ignore'):+ hit_u = ax + (v - ay) * ex / (ey if ey else 1e-18)+ crossings ^= straddles & (u < hit_u)+ return np.sqrt(nearest) * np.where(crossings, -1.0, 1.0)+++def chaikin(points, n=4):+ """Round a profile's corners by cutting each one n times. The first two and last two points stay put."""+ pts = np.asarray(points, float)+ for _ in range(n):+ middle = []+ for p, q in zip(pts[1:-2], pts[2:-1]):+ middle += [0.75 * p + 0.25 * q, 0.25 * p + 0.75 * q]+ pts = np.array([pts[0], pts[1], *middle, pts[-2], pts[-1]])+ return pts+++def revolve(profile, rmax=1.5, zmin=-1.5, zmax=1.5, res=600):+ """Spin a closed (radius, height) outline round the z axis: bottles, caps, bells, buttons.++ Returns f(x, y, z). The outline's distance is tabulated once on a res x res grid covering radius 0..rmax and+ height zmin..zmax, then read back with bilinear interpolation.+ """+ r = np.linspace(0, rmax, res)+ h = np.linspace(zmin, zmax, res)+ table = polygon_2d(*np.meshgrid(r, h, indexing='ij'), profile)++ def f(x, y, z):+ radius, height = np.broadcast_arrays(np.hypot(x, y), z)+ coords = [(radius / rmax * (res - 1)).ravel(), ((height - zmin) / (zmax - zmin) * (res - 1)).ravel()]+ return map_coordinates(table, coords, order=1, mode='nearest').reshape(radius.shape).astype(np.float32)++ return f+++# ---- the mesher ---------------------------------------------------------------------------------------------------++def _cell_ids(shape, index):+ return np.ravel_multi_index(index, shape)+++def nets(fn, lo, hi, step, name, out='mesh'):+ axes = [np.arange(lo[n], hi[n] + step * 0.5, step, dtype=np.float32) for n in range(3)]+ field = np.asarray(fn(*np.meshgrid(*axes, indexing='ij', sparse=True)), np.float32)+ field = np.broadcast_to(field, tuple(len(a) for a in axes))+ inside = field < 0+ cells = tuple(n - 1 for n in field.shape)+ total = np.zeros((int(np.prod(cells)), 3))+ count = np.zeros(int(np.prod(cells)))+ edges = []++ for axis in range(3):+ lead = [slice(None)] * 3+ lead[axis] = slice(0, -1)+ tail = [slice(None)] * 3+ tail[axis] = slice(1, None)+ a, b = field[tuple(lead)], field[tuple(tail)]+ flips = np.argwhere(inside[tuple(lead)] != inside[tuple(tail)])+ if not len(flips):+ continue+ fa, fb = a[tuple(flips.T)], b[tuple(flips.T)]+ frac = np.clip(fa / (fa - fb), 0, 1)+ point = np.stack([axes[n][flips[:, n]] for n in range(3)], axis=1).astype(np.float64)+ point[:, axis] += frac * step++ others = [(axis + 1) % 3, (axis + 2) % 3] # cyclic, so the corner order below winds round +axis+ for d1 in (0, -1):+ for d2 in (0, -1):+ idx = flips.copy()+ idx[:, others[0]] += d1+ idx[:, others[1]] += d2+ ok = np.all((idx >= 0) & (idx < np.array(cells)), axis=1)+ ids = _cell_ids(cells, tuple(idx[ok].T))+ np.add.at(total, ids, point[ok])+ np.add.at(count, ids, 1)+ edges.append((axis, others, flips, inside[tuple(flips.T)]))++ used = count > 0+ vertex_of = np.full(len(count), -1, np.int64)+ vertex_of[used] = np.arange(used.sum())+ verts = (total[used] / count[used, None]).astype(np.float32)++ quads = []+ for axis, (b, c), flips, starts_inside in edges:+ corners = []+ for db, dc in ((-1, -1), (0, -1), (0, 0), (-1, 0)): # counter-clockwise round +axis+ idx = flips.copy()+ idx[:, b] += db+ idx[:, c] += dc+ corners.append(idx)+ ok = np.ones(len(flips), bool)+ for idx in corners:+ ok &= np.all((idx >= 0) & (idx < np.array(cells)), axis=1)+ ring = np.stack([vertex_of[_cell_ids(cells, tuple(idx[ok].T))] for idx in corners], axis=1)+ # The surface faces away from the inside: +axis when the edge starts inside, -axis when it ends inside.+ ring[~starts_inside[ok]] = ring[~starts_inside[ok]][:, ::-1]+ quads.append(ring)++ faces = np.concatenate(quads).astype(np.int32) if quads else np.zeros((0, 4), np.int32)+ os.makedirs(out, exist_ok=True)+ np.savez(os.path.join(out, name + '.npz'), v=verts, f=faces)+ print(f'{name}: {len(verts)} vertices, {len(faces)} quads')+ return verts, facesdiff --git a/skills/motlab/scripts/blender/tracks.py b/skills/motlab/scripts/blender/tracks.pynew file mode 100644index 0000000..452dbdf--- /dev/null+++ b/skills/motlab/scripts/blender/tracks.py@@ -0,0 +1,59 @@+"""Animation curves for Blender scenes, in plain Python.++mono(keys) passes through every key and never overshoots between two of them (monotone cubic interpolation), so a+move cannot drift backwards and come back. Use one curve for a whole move: joining two curves at a handover leaves a+kink in the speed.++ turn = mono([(0, -1.2), (2.0, 0.2), (4.0, 0.5)]) # (seconds, value)+ path = tracks([(0, (0, -5, 1)), (4.0, (0, -12, 1))]) # several values per key, each with its own curve+ turn(1.0); path(1.0)+"""+from bisect import bisect_right+++def _tangents(times, values):+ slopes = [(values[i + 1] - values[i]) / (times[i + 1] - times[i]) for i in range(len(times) - 1)]+ if not slopes:+ return [0.0]+ out = [slopes[0]]+ for left, right in zip(slopes, slopes[1:]):+ # Flat where the curve turns round, otherwise the harmonic mean of the two slopes (Fritsch and Carlson).+ out.append(0.0 if left * right <= 0 else 2 * left * right / (left + right))+ out.append(slopes[-1])+ return out+++def mono(keys):+ keys = sorted(keys)+ times = [float(k[0]) for k in keys]+ values = [float(k[1]) for k in keys]+ tangents = _tangents(times, values)++ def at(t):+ if t <= times[0]:+ return values[0]+ if t >= times[-1]:+ return values[-1]+ i = bisect_right(times, t) - 1+ span = times[i + 1] - times[i]+ u = (t - times[i]) / span+ u2, u3 = u * u, u * u * u+ return ((2 * u3 - 3 * u2 + 1) * values[i] + (u3 - 2 * u2 + u) * span * tangents[i]+ + (3 * u2 - 2 * u3) * values[i + 1] + (u3 - u2) * span * tangents[i + 1])++ return at+++def tracks(keys):+ width = len(keys[0][1])+ curves = [mono([(t, v[n]) for t, v in keys]) for n in range(width)]+ return lambda t: [curve(t) for curve in curves]+++def smooth(x):+ """0 to 1 with an eased start and end, clamped outside 0..1."""+ x = min(1.0, max(0.0, x))+ return x * x * (3 - 2 * x)+++sm = smooth # older scenes call it smdiff --git a/skills/motlab/scripts/compose_into_clip.py b/skills/motlab/scripts/compose_into_clip.pynew file mode 100644index 0000000..49e4a08--- /dev/null+++ b/skills/motlab/scripts/compose_into_clip.py@@ -0,0 +1,101 @@+"""Run a transparent rendered sequence straight into a real clip, as one MP4.++The ad plays over black. During --fade the black gives way to the clip's frame at --start, held still. During --melt+the rendered object fades out over the real one in that frame, so there is no jump at the cut. At --end the clip+itself starts playing from --start.++ python3 compose_into_clip.py <frames dir> <clip> <out.mp4> [--start 0] [--end 8]+ [--fade 6.2 7.5] [--melt 7.45 7.95] [--sfx ad.wav] [--fps 25] [--w 3840] [--h 2160]++<frames dir> holds RGBA PNGs (a Blender render with a transparent film); they are spread evenly over 0 to --end.+--sfx is the ad's own sound, from 0 s; the clip's sound, if it has any, follows from --end.+"""+import argparse+import glob+import os+import subprocess++import numpy as np+from PIL import Image+++def ease(x):+ x = min(1.0, max(0.0, x))+ return x * x * (3 - 2 * x)+++def window(t, span):+ a, b = span+ return ease((t - a) / (b - a)) if b > a else float(t >= b)+++def grab_frame(clip, at, w, h):+ raw = subprocess.run(+ ['ffmpeg', '-v', 'error', '-ss', str(at), '-i', clip, '-frames:v', '1',+ '-vf', f'scale={w}:{h}:flags=lanczos', '-f', 'rawvideo', '-pix_fmt', 'rgb24', '-'],+ capture_output=True, check=True).stdout+ return np.frombuffer(raw, np.uint8).reshape(h, w, 3).astype(np.float32)+++def has_audio(path):+ out = subprocess.run(['ffprobe', '-v', 'error', '-select_streams', 'a', '-show_entries', 'stream=index',+ '-of', 'csv=p=0', path], capture_output=True, text=True).stdout+ return bool(out.strip())+++def main():+ ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])+ ap.add_argument('frames')+ ap.add_argument('clip')+ ap.add_argument('out')+ ap.add_argument('--start', type=float, default=0.0, help='where in the clip the ad lands, in seconds')+ ap.add_argument('--end', type=float, default=8.0, help='length of the ad part, in seconds')+ ap.add_argument('--fade', type=float, nargs=2, default=[6.2, 7.5], metavar=('FROM', 'TO'))+ ap.add_argument('--melt', type=float, nargs=2, default=[7.45, 7.95], metavar=('FROM', 'TO'))+ ap.add_argument('--sfx')+ ap.add_argument('--fps', type=int, default=25)+ ap.add_argument('--w', type=int, default=3840)+ ap.add_argument('--h', type=int, default=2160)+ o = ap.parse_args()++ frames = sorted(glob.glob(os.path.join(o.frames, '*.png')))+ if len(frames) < 2:+ raise SystemExit(f'need at least two PNG frames in {o.frames}')+ held = grab_frame(o.clip, o.start, o.w, o.h)++ graph = (f'[0:v]format=yuv420p,setsar=1[ad];'+ f'[1:v]fps={o.fps},scale={o.w}:{o.h}:flags=lanczos,format=yuv420p,setsar=1[rest];'+ f'[ad][rest]concat=n=2:v=1:a=0[v]')+ inputs = ['-f', 'rawvideo', '-pix_fmt', 'rgb24', '-s', f'{o.w}x{o.h}', '-r', str(o.fps), '-i', '-',+ '-ss', str(o.start), '-i', o.clip]+ audio = []+ clip_sound = has_audio(o.clip)+ ms = round(o.end * 1000)+ if o.sfx:+ inputs += ['-i', o.sfx]+ graph += (f';[1:a]adelay={ms}:all=1[late];[2:a][late]amix=inputs=2:normalize=0:duration=longest[a]'+ if clip_sound else ';[2:a]anull[a]')+ elif clip_sound:+ graph += f';[1:a]adelay={ms}:all=1[a]'+ if o.sfx or clip_sound:+ audio = ['-map', '[a]', '-c:a', 'aac', '-b:a', '320k']++ enc = subprocess.Popen(['ffmpeg', '-y', '-v', 'error', *inputs, '-filter_complex', graph, '-map', '[v]', *audio,+ '-c:v', 'libx264', '-preset', 'medium', '-crf', '15', '-pix_fmt', 'yuv420p', o.out],+ stdin=subprocess.PIPE)+ last = len(frames) - 1+ for n, path in enumerate(frames):+ t = n / last * o.end+ rgba = np.asarray(Image.open(path).convert('RGBA').resize((o.w, o.h), Image.LANCZOS), dtype=np.float32)+ cover = rgba[..., 3:] / 255 * (1 - window(t, o.melt))+ under = held * window(t, o.fade)+ frame = rgba[..., :3] * cover + under * (1 - cover)+ enc.stdin.write(np.clip(frame + 0.5, 0, 255).astype(np.uint8).tobytes())+ enc.stdin.close()+ if enc.wait():+ raise SystemExit('ffmpeg failed')+ print(f'{o.out}: {len(frames)} rendered frames, then the clip from {o.start:g} s')+++if __name__ == '__main__':+ main()diff --git a/skills/motlab/scripts/contact_sheet.py b/skills/motlab/scripts/contact_sheet.pynew file mode 100644index 0000000..02760de--- /dev/null+++ b/skills/motlab/scripts/contact_sheet.py@@ -0,0 +1,53 @@+"""Put a folder of stills on one labelled sheet, in time order, for reviewing a video frame by frame.++The stills are the files `motlab stills` writes: <seconds>.png or <seconds>.jpg.++ python3 contact_sheet.py <stills dir> <out.jpg> [--cols 4] [--width 640]+"""+import argparse+import math+import os+import re++from PIL import Image, ImageDraw++NAME = re.compile(r'^(\d+(?:\.\d+)?)\.(png|jpe?g)$', re.I)+++def main():+ ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])+ ap.add_argument('folder')+ ap.add_argument('out')+ ap.add_argument('--cols', type=int, default=4)+ ap.add_argument('--width', type=int, default=640, help='width of one tile in pixels')+ args = ap.parse_args()++ stills = []+ for name in os.listdir(args.folder):+ m = NAME.match(name)+ if m:+ stills.append((float(m.group(1)), m.group(1), os.path.join(args.folder, name)))+ if not stills:+ raise SystemExit(f'no stills named <seconds>.png or <seconds>.jpg in {args.folder}')+ stills.sort()++ first = Image.open(stills[0][2])+ tw = args.width+ th = round(tw * first.height / first.width)+ rows = math.ceil(len(stills) / args.cols)+ gap = 4+ sheet = Image.new('RGB', (args.cols * (tw + gap) + gap, rows * (th + gap) + gap), (24, 24, 24))+ pen = ImageDraw.Draw(sheet)++ for n, (_, label, path) in enumerate(stills):+ x = gap + (n % args.cols) * (tw + gap)+ y = gap + (n // args.cols) * (th + gap)+ sheet.paste(Image.open(path).convert('RGB').resize((tw, th), Image.LANCZOS), (x, y))+ pen.text((x + 8, y + 6), f'{label} s', fill='white', stroke_width=2, stroke_fill='black')++ sheet.save(args.out, quality=88)+ print(f'{args.out}: {len(stills)} stills, {args.cols} per row')+++if __name__ == '__main__':+ main()diff --git a/skills/motlab/scripts/cut_pauses.py b/skills/motlab/scripts/cut_pauses.pynew file mode 100644index 0000000..99ea7d8--- /dev/null+++ b/skills/motlab/scripts/cut_pauses.py@@ -0,0 +1,72 @@+# Cuts the pauses out of a talking-head recording: finds them in its sound with ffmpeg silencedetect, keeps a little+# breath on each side, and writes the parts to keep as a cut list for /__motlab/cuts.js. Optionally writes the voice+# with the same cuts, so picture and sound stay in step.+#+# python3 cut_pauses.py footage/talk.mp4 cuts.json [--audio-out audio/voice-cut.wav]+# [--start 1.4] [--end 158.2] the part of the take to use (seconds in the file)+# [--noise -38] [--min-pause 0.35] quieter than this many dB for at least this long is a pause+# [--keep-tail 0.12] [--keep-lead 0.08] seconds kept after speech stops and before it starts again+# [--drop 61.2-63.0,90-91.5] more parts of the file to leave out (a fluffed line)+# [--dissolve 0.12] parts overlap and fade by this long instead of cutting hard+#+# Run it from the project folder; the paths in cuts.json are relative to it. Listen to the result: a pause that was a+# deliberate beat may need --min-pause raised, and a cut that clips a word needs more --keep-tail or --keep-lead.+import json, os, re, subprocess, sys, tempfile++def opt(name, default, cast=float):+ return cast(sys.argv[sys.argv.index(name) + 1]) if name in sys.argv else default++def duration(path): # the shortest stream: a recording's sound often ends a few frames before its picture+ out = subprocess.run(['ffprobe', '-v', 'error', '-show_entries', 'stream=duration:format=duration', '-of', 'csv=p=0', path], capture_output=True, text=True)+ return min(float(x) for x in out.stdout.split() if re.fullmatch(r'[\d.]+', x.strip(',')))++def pauses(path, noise, min_pause):+ err = subprocess.run(['ffmpeg', '-hide_banner', '-i', path, '-map', '0:a:0', '-af', f'highpass=f=80,silencedetect=noise={noise}dB:d={min_pause}',+ '-f', 'null', '-'], capture_output=True, text=True).stderr+ if 'silence' not in err and 'Stream #0' not in err: sys.exit(f'ffmpeg could not read the sound of {path}')+ starts = [float(x) for x in re.findall(r'silence_start: (-?[\d.]+)', err)]+ ends = [float(x) for x in re.findall(r'silence_end: ([\d.]+)', err)]+ return list(zip(starts, ends + [float('inf')] * (len(starts) - len(ends))))++def main():+ if len(sys.argv) < 3 or sys.argv[1].startswith('-'): sys.exit(__doc__ or open(__file__, encoding='utf-8').read().split('\nimport')[0])+ src, out = sys.argv[1], sys.argv[2]+ total = duration(src)+ start, end = opt('--start', 0.0), min(opt('--end', total), total)+ tail, lead, D = opt('--keep-tail', 0.12), opt('--keep-lead', 0.08), opt('--dissolve', 0.0)+ drops = [tuple(map(float, r.split('-'))) for r in opt('--drop', '', str).split(',') if r]+ gaps = [(a + tail, b - lead) for a, b in pauses(src, opt('--noise', -38.0), opt('--min-pause', 0.35))] + drops+ keep, cur = [], start+ for a, b in sorted(gaps):+ a, b = max(a, cur), min(b, end)+ if b - a < 0.12: continue # too short to be worth a cut+ if a - cur > max(0.12, D): keep.append([cur, a])+ cur = max(cur, b)+ if cur >= end: break+ if end - cur > max(0.12, D): keep.append([cur, end])+ if not keep: sys.exit('nothing left to keep: check --start, --end and --noise')+ segs = [{'from': round(a, 3), 'to': round(b, 3)} for a, b in keep]+ length = sum(s['to'] - s['from'] for s in segs) - D * (len(segs) - 1)+ data = {'source': src.replace('\\', '/'), 'dissolve': D, 'duration': round(length, 3), 'segments': segs}+ os.makedirs(os.path.dirname(os.path.abspath(out)), exist_ok=True)+ with open(out, 'w', encoding='utf-8') as f: json.dump(data, f, indent=1)+ print(f'{len(segs)} parts kept, {end - start:.2f} s of the take became {length:.2f} s -> {out}')++ audio = opt('--audio-out', None, str)+ if audio: # the same cuts on the sound: 5 ms fades at each cut so it does not click, or crossfades for a dissolve+ parts = [f'[0:a]atrim={s["from"]}:{s["to"]},asetpts=PTS-STARTPTS' + ('' if D else f',afade=t=in:d=0.005,afade=t=out:st={s["to"] - s["from"] - 0.005:.3f}:d=0.005') + f'[p{i}]'+ for i, s in enumerate(segs)]+ if D and len(segs) > 1:+ chain, last = [], 'p0'+ for i in range(1, len(segs)): chain.append(f'[{last}][p{i}]acrossfade=d={D}:c1=tri:c2=tri[x{i}]'); last = f'x{i}'+ graph = ';'.join(parts + chain) + f';[{last}]anull[out]'+ else:+ graph = ';'.join(parts) + ';' + ''.join(f'[p{i}]' for i in range(len(segs))) + f'concat=n={len(segs)}:v=0:a=1[out]'+ with tempfile.NamedTemporaryFile('w', suffix='.txt', delete=False, encoding='utf-8') as g: g.write(graph)+ try:+ os.makedirs(os.path.dirname(os.path.abspath(audio)), exist_ok=True)+ subprocess.run(['ffmpeg', '-y', '-loglevel', 'error', '-i', src, '-/filter_complex', g.name, '-map', '[out]', '-ar', '48000', '-ac', '2', audio], check=True)+ finally: os.unlink(g.name)+ print(f'voice with the same cuts -> {audio} ({duration(audio):.2f} s)')++main()diff --git a/skills/motlab/scripts/get_font.py b/skills/motlab/scripts/get_font.pynew file mode 100644index 0000000..951a2ae--- /dev/null+++ b/skills/motlab/scripts/get_font.py@@ -0,0 +1,82 @@+"""Find and download Google Fonts for a motlab project.++ python get_font.py list [words...] [--cat "Sans Serif"|Serif|Display|Handwriting|Monospace] [--n 40]+ Searches the whole Google Fonts catalog (about 1,950 families), most popular first.+ Words match the family name, category, stroke or classification.++ python get_font.py get "Family Name" [axes] [--out assets/fonts]+ Downloads the family's woff2 files and writes <slug>.css next to them, then rebuilds fonts.css+ from every <slug>.css in the folder. Link fonts.css from scenes. axes is the css2 axis spec:+ "wght@400;700" two weights+ "[email protected]" the variable weight range (animate weight)+ "ital,wght@0,400;1,400" regular and italic+ Without axes you get the family's default style.+"""+import json, re, sys, urllib.parse, urllib.request+from pathlib import Path++UA = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0 Safari/537.36'+++def fetch(url):+ return urllib.request.urlopen(urllib.request.Request(url, headers={'User-Agent': UA}), timeout=60).read()+++def opt(args, name, default):+ if name in args:+ i = args.index(name); v = args[i + 1]; del args[i:i + 2]; return v+ return default+++def catalog():+ text = fetch('https://fonts.google.com/metadata/fonts').decode('utf-8')+ return json.loads(text[text.index('{'):])['familyMetadataList']+++def list_fonts(args):+ cat, n = opt(args, '--cat', None), int(opt(args, '--n', '40'))+ words = [w.lower() for w in args]+ rows = []+ for f in catalog():+ if cat and f['category'].lower() != cat.lower():+ continue+ hay = ' '.join([f['family'], f['category'], f.get('stroke') or '', *(f.get('classifications') or [])]).lower()+ if all(w in hay for w in words):+ rows.append(f)+ rows.sort(key=lambda f: f['popularity'])+ for f in rows[:n]:+ axes = ','.join(f"{a['tag']} {a['min']:g}-{a['max']:g}" for a in f['axes']) or 'static ' + ' '.join(f['fonts'])+ print(f"{f['family']:<32} {f['category']:<12} {f.get('stroke') or '':<11} {axes}")+ print(f'{len(rows)} match, {min(n, len(rows))} shown')+++def get_font(args):+ out = Path(opt(args, '--out', 'assets/fonts'))+ family, axes = args[0], (args[1] if len(args) > 1 else '')+ q = urllib.parse.quote_plus(family) + (':' + axes if axes else '')+ try:+ css = fetch(f'https://fonts.googleapis.com/css2?family={q}&display=block').decode('utf-8')+ except urllib.error.HTTPError as e:+ sys.exit(f'Google Fonts refused "{family}" {axes} (HTTP {e.code}). Check the name with "list" and the axes '+ 'against what it prints, e.g. a static font only has the weights listed.')+ out.mkdir(parents=True, exist_ok=True)+ slug = re.sub(r'[^a-z0-9]+', '-', family.lower()).strip('-')+ for old in out.glob(f'{slug}-*.woff2'):+ old.unlink()+ urls = list(dict.fromkeys(re.findall(r'url\((https://[^)]+)\)', css)))+ for i, url in enumerate(urls):+ name = f'{slug}-{i}.woff2'+ (out / name).write_bytes(fetch(url))+ css = css.replace(url, name)+ (out / f'{slug}.css').write_text(css, encoding='utf-8')+ parts = [p.read_text(encoding='utf-8') for p in sorted(out.glob('*.css')) if p.name != 'fonts.css']+ (out / 'fonts.css').write_text('\n'.join(parts), encoding='utf-8')+ weights = sorted(set(re.findall(r'font-weight: ([^;]+);', css)))+ print(f'{family}: {len(urls)} files, weights {", ".join(weights)} -> {out / (slug + ".css")}, fonts.css updated')+++if __name__ == '__main__':+ a = sys.argv[1:]+ if not a or a[0] not in ('list', 'get') or (a[0] == 'get' and len(a) < 2):+ sys.exit(__doc__)+ (list_fonts if a[0] == 'list' else get_font)(a[1:])diff --git a/skills/motlab/scripts/get_sfx.py b/skills/motlab/scripts/get_sfx.pynew file mode 100644index 0000000..b6fc4d2--- /dev/null+++ b/skills/motlab/scripts/get_sfx.py@@ -0,0 +1,80 @@+"""Find and download openly licensed sound effects from Openverse (api.openverse.org) into a project.++ python get_sfx.py search "whoosh" [--license cc0|commercial] [--max 5] [--n 20]+ Lists matches: id, length, licence, creator and title (at most 20). --max drops sounds longer than that many seconds.+ --license cc0 (default) needs no credit; commercial also allows CC BY and BY-SA, which must be credited.++ python get_sfx.py get <id> [<id> ...] [--out audio/sfx]+ Downloads each sound as <title>-<id>.<ext> and adds its credit line to CREDITS.md in the same folder.++Without a key Openverse allows 20 requests a minute and 200 a day (its rate-limit headers, measured 2026-11-13).+A page is at most 20 results without a key (a larger page_size is a 401). Search is one request (up to 3 with --max),+and get is one per sound. Most sounds come from Freesound as its high-quality MP3 previews.+A licence on Openverse is what the source states; check the landing page in CREDITS.md before a paid use.+"""+import json, re, ssl, sys, urllib.error, urllib.parse, urllib.request+from pathlib import Path++API = 'https://api.openverse.org/v1/audio/'+UA = 'motlab-get-sfx'+++def fetch(url):+ req = urllib.request.Request(url, headers={'User-Agent': UA})+ try: return urllib.request.urlopen(req, timeout=60).read()+ except urllib.error.HTTPError as e: sys.exit(f'{url}: HTTP {e.code} {e.read().decode("utf-8", "replace")[:300]}')+ except urllib.error.URLError as e:+ # A Windows certificate store can hold an expired intermediate that breaks a valid chain (seen with+ # cdn.freesound.org on 2026-11-13). certifi's bundle, when installed, verifies it.+ if not isinstance(e.reason, ssl.SSLCertVerificationError): raise+ try: import certifi+ except ImportError: sys.exit(f'{url}: {e.reason}. pip install certifi, then try again')+ return urllib.request.urlopen(req, timeout=60, context=ssl.create_default_context(cafile=certifi.where())).read()+++def opt(args, name, default):+ if name in args:+ i = args.index(name); v = args[i + 1]; del args[i:i + 2]; return v+ return default+++def search(args):+ lic, mx, n = opt(args, '--license', 'cc0'), float(opt(args, '--max', '0')), int(opt(args, '--n', '20'))+ if lic not in ('cc0', 'commercial'): sys.exit('--license is cc0 or commercial')+ if not args: sys.exit('search needs words, e.g. search "soft whoosh"')+ # Without a key Openverse answers a page_size above 20 with a 401, so --max reads up to 3 pages of 20 instead.+ q = {'q': ' '.join(args)[:200], 'page_size': 20 if mx else min(n, 20)}+ q.update({'license': 'cc0'} if lic == 'cc0' else {'license_type': 'commercial'})+ rows = []+ for page in range(1, 4 if mx else 2):+ d = json.loads(fetch(API + '?' + urllib.parse.urlencode({**q, 'page': page})))+ rows += [r for r in d['results'] if not mx or (r.get('duration') or 0) <= mx * 1000]+ if len(rows) >= n or page >= d.get('page_count', 1): break+ rows = rows[:n]+ if not rows: print('no matches'); return+ for r in rows:+ credit = '' if r['license'] in ('cc0', 'pdm') else ' (credit needed)'+ print(f"{r['id']} {(r.get('duration') or 0) / 1000:5.1f} s {r['license']:6s} {r['filetype'] or '?':4s} {r['creator'][:20]:20s} {r['title'][:50]}{credit}")+ print(f"{len(rows)} of {d['result_count']} matches. Get with: python get_sfx.py get <id> ... --out audio/sfx")+++def get(args):+ out = Path(opt(args, '--out', 'audio/sfx')); out.mkdir(parents=True, exist_ok=True)+ if not args: sys.exit('get needs one or more ids from search')+ credits = out / 'CREDITS.md'+ text = credits.read_text(encoding='utf-8') if credits.exists() else '# Sound credits\n\nSounds found through Openverse. Keep this file with the project.\n\n'+ for id in args:+ r = json.loads(fetch(API + urllib.parse.quote(id) + '/'))+ slug = re.sub(r'[^a-z0-9]+', '-', r['title'].lower()).strip('-')[:40] or 'sound'+ ext = r.get('filetype') or Path(urllib.parse.urlparse(r['url']).path).suffix.lstrip('.') or 'mp3'+ f = out / f'{slug}-{id[:8]}.{ext}'+ if not f.exists(): f.write_bytes(fetch(r['url']))+ if id not in text: text += f"- `{f.name}`: {r['attribution']} Source: {r['foreign_landing_url']} (id {id})\n"+ print(f"{f} {(r.get('duration') or 0) / 1000:.1f} s {r['license']} {r.get('license_version') or ''}")+ credits.write_text(text, encoding='utf-8'); print(f'credits -> {credits}')+++if __name__ == '__main__':+ a = sys.argv[1:]+ if not a or a[0] not in ('search', 'get'): sys.exit(__doc__)+ (search if a[0] == 'search' else get)(a[1:])diff --git a/skills/motlab/scripts/gl3d.js b/skills/motlab/scripts/gl3d.jsnew file mode 100644index 0000000..e8dfcf7--- /dev/null+++ b/skills/motlab/scripts/gl3d.js@@ -0,0 +1,190 @@+// A small WebGL2 stage for flat panels in 3D: each panel is a rectangle whose texture is a 2D canvas (so UI drawn+// with canvas code stays sharp), placed in space and seen through a perspective camera. It adds fog, depth of field+// (sharper or softer mip levels), a soft reflection on a glossy floor and an optional light band across a panel.+//+// const stage = GL3D.create(width, height);+// const tex = stage.texture(canvas2d); // call tex.update() after drawing on canvas2d again+// const out = stage.render(panels, view); // returns the stage's canvas; draw it onto the page's canvas+// const [px, py] = stage.project([x, y, z], view); // a world point in the stage's pixels+//+// panels: [{ tex, w, h, pos: [x, y, z], rot: [rx, ry, rz] (radians, applied z, then x, then y), scale, alpha,+// light (brightness multiplier), blur (extra softness), bias (draw-order nudge: higher draws later, on top),+// reflect (false: no floor reflection), sheen (0..1 strength of a light band), sheenPos (0..1 across) }]+// view: { eye, target, up = [0, 1, 0], fov (degrees, vertical), focus (distance kept sharp),+// aperture (softness per unit of relative defocus), fog: { near, far, color: [r, g, b] in 0..1 },+// floorY (reflect panels in the plane y = floorY), ground: [panels drawn first, sharp and unsorted] }+// Units: with fov 38 and the camera about 1600 from a panel, one unit is about one pixel at 1080p. y is up.+window.GL3D = (() => {+ // ---- 4x4 matrices, column-major as WebGL expects ----+ const mul = (a, b) => {+ const o = new Float32Array(16);+ for (let col = 0; col < 4; col++) {+ for (let row = 0; row < 4; row++) {+ o[col * 4 + row] = a[row] * b[col * 4] + a[4 + row] * b[col * 4 + 1] + a[8 + row] * b[col * 4 + 2] + a[12 + row] * b[col * 4 + 3];+ }+ }+ return o;+ };+ const chain = (...ms) => ms.reduce((acc, m) => mul(acc, m));+ const translate = ([x, y, z]) => [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, x, y, z, 1];+ const scaling = s => [s, 0, 0, 0, 0, s, 0, 0, 0, 0, s, 0, 0, 0, 0, 1];+ const turnX = a => { const c = Math.cos(a), s = Math.sin(a); return [1, 0, 0, 0, 0, c, s, 0, 0, -s, c, 0, 0, 0, 0, 1]; };+ const turnY = a => { const c = Math.cos(a), s = Math.sin(a); return [c, 0, -s, 0, 0, 1, 0, 0, s, 0, c, 0, 0, 0, 0, 1]; };+ const turnZ = a => { const c = Math.cos(a), s = Math.sin(a); return [c, s, 0, 0, -s, c, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]; };++ const minus = (a, b) => [a[0] - b[0], a[1] - b[1], a[2] - b[2]];+ const dot = (a, b) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2];+ const crossP = (a, b) => [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]];+ const unit = a => { const n = Math.hypot(a[0], a[1], a[2]) || 1; return [a[0] / n, a[1] / n, a[2] / n]; };++ const NEAR = 10, FAR = 40000;+ function viewProjection(view, aspect) {+ const f = 1 / Math.tan(view.fov * Math.PI / 360);+ const proj = [f / aspect, 0, 0, 0, 0, f, 0, 0, 0, 0, (FAR + NEAR) / (NEAR - FAR), -1, 0, 0, 2 * FAR * NEAR / (NEAR - FAR), 0];+ const back = unit(minus(view.eye, view.target)), side = unit(crossP(view.up || [0, 1, 0], back)), up = crossP(back, side);+ const cam = [side[0], up[0], back[0], 0, side[1], up[1], back[1], 0, side[2], up[2], back[2], 0,+ -dot(side, view.eye), -dot(up, view.eye), -dot(back, view.eye), 1];+ return mul(proj, cam);+ }++ const VERTEX = `#version 300 es+ layout(location = 0) in vec2 corner; // 0..1 across the panel, (0, 0) at its top left+ uniform mat4 viewProj, model;+ uniform vec2 size;+ out vec2 uv;+ out vec3 world;+ void main() {+ vec4 p = model * vec4((corner.x - 0.5) * size.x, (0.5 - corner.y) * size.y, 0.0, 1.0);+ world = p.xyz;+ uv = corner;+ gl_Position = viewProj * p;+ }`;+ const FRAGMENT = `#version 300 es+ precision highp float;+ in vec2 uv;+ in vec3 world;+ uniform sampler2D image;+ uniform float opacity, softness, brightness, band, bandAt, mirrored, floorY, fogNear, fogFar;+ uniform vec3 eye, fogColour;+ out vec4 colour;+ void main() {+ vec4 c = texture(image, uv, softness); // premultiplied+ c.rgb *= brightness;+ float across = uv.x * 0.65 + uv.y * 0.35; // a diagonal band of light+ c.rgb += band * max(0.0, 1.0 - abs(across - bandAt) * 5.0) * c.a;+ float haze = clamp((distance(world, eye) - fogNear) / (fogFar - fogNear), 0.0, 1.0) * 0.9;+ c.rgb = mix(c.rgb, fogColour * c.a, haze);+ float a = opacity;+ if (mirrored > 0.5) a *= 0.2 * exp(-max(0.0, floorY - world.y) / 160.0); // fades with depth below the floor+ colour = c * a;+ }`;++ function create(width, height) {+ const canvas = document.createElement('canvas');+ canvas.width = width; canvas.height = height;+ const gl = canvas.getContext('webgl2', { alpha: true, premultipliedAlpha: true, antialias: true, preserveDrawingBuffer: true });+ if (!gl) throw new Error('gl3d.js needs WebGL2');+ const shader = (type, src) => {+ const s = gl.createShader(type);+ gl.shaderSource(s, src);+ gl.compileShader(s);+ if (!gl.getShaderParameter(s, gl.COMPILE_STATUS)) throw new Error(gl.getShaderInfoLog(s));+ return s;+ };+ const program = gl.createProgram();+ gl.attachShader(program, shader(gl.VERTEX_SHADER, VERTEX));+ gl.attachShader(program, shader(gl.FRAGMENT_SHADER, FRAGMENT));+ gl.linkProgram(program);+ if (!gl.getProgramParameter(program, gl.LINK_STATUS)) throw new Error(gl.getProgramInfoLog(program));+ gl.useProgram(program);+ const u = {};+ for (const name of ['viewProj', 'model', 'size', 'image', 'opacity', 'softness', 'brightness', 'band', 'bandAt',+ 'mirrored', 'floorY', 'fogNear', 'fogFar', 'eye', 'fogColour']) u[name] = gl.getUniformLocation(program, name);++ gl.bindBuffer(gl.ARRAY_BUFFER, gl.createBuffer());+ gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([0, 0, 1, 0, 0, 1, 1, 1]), gl.STATIC_DRAW);+ gl.enableVertexAttribArray(0);+ gl.vertexAttribPointer(0, 2, gl.FLOAT, false, 0, 0);+ gl.disable(gl.DEPTH_TEST);+ gl.disable(gl.CULL_FACE);+ gl.enable(gl.BLEND);+ gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);+ const anisotropy = gl.getExtension('EXT_texture_filter_anisotropic');++ function texture(src) {+ const handle = { t: gl.createTexture(), src };+ handle.update = () => {+ gl.bindTexture(gl.TEXTURE_2D, handle.t);+ gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, true);+ gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, src);+ gl.generateMipmap(gl.TEXTURE_2D);+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR_MIPMAP_LINEAR);+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);+ if (anisotropy) gl.texParameterf(gl.TEXTURE_2D, anisotropy.TEXTURE_MAX_ANISOTROPY_EXT, 8);+ return handle;+ };+ return handle.update();+ }++ const visible = p => p && p.tex && (p.alpha ?? 1) > 0.002;++ function drawPanel(p, view, softness, mirror) {+ let model = chain(translate(p.pos), turnY((p.rot || [])[1] || 0), turnX((p.rot || [])[0] || 0), turnZ((p.rot || [])[2] || 0), scaling(p.scale ?? 1));+ if (mirror) model = mul([1, 0, 0, 0, 0, -1, 0, 0, 0, 0, 1, 0, 0, 2 * view.floorY, 0, 1], model);+ gl.uniformMatrix4fv(u.model, false, model);+ gl.uniform2f(u.size, p.w, p.h);+ gl.uniform1f(u.opacity, p.alpha ?? 1);+ gl.uniform1f(u.softness, softness + (mirror ? 1.5 : 0));+ gl.uniform1f(u.brightness, p.light ?? 1);+ gl.uniform1f(u.band, mirror ? 0 : (p.sheen || 0));+ gl.uniform1f(u.bandAt, p.sheenPos ?? 0.5);+ gl.uniform1f(u.mirrored, mirror ? 1 : 0);+ gl.bindTexture(gl.TEXTURE_2D, p.tex.t);+ gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);+ }++ function render(panels, view) {+ gl.viewport(0, 0, canvas.width, canvas.height);+ gl.clearColor(0, 0, 0, 0);+ gl.clear(gl.COLOR_BUFFER_BIT);+ const fog = view.fog || { near: 1e5, far: 2e5, color: [0, 0, 0] };+ gl.uniformMatrix4fv(u.viewProj, false, viewProjection(view, canvas.width / canvas.height));+ gl.uniform3fv(u.eye, view.eye);+ gl.uniform1f(u.fogNear, fog.near);+ gl.uniform1f(u.fogFar, fog.far);+ gl.uniform3fv(u.fogColour, fog.color);+ gl.uniform1f(u.floorY, view.floorY ?? -1e6);+ gl.activeTexture(gl.TEXTURE0);+ gl.uniform1i(u.image, 0);++ // Depth is measured along the view direction, not as straight distance, so stacked panels keep their order.+ const ahead = unit(minus(view.target, view.eye));+ const focus = view.focus;+ const items = panels.filter(visible).map(p => ({ p, depth: dot(minus(p.pos, view.eye), ahead) }))+ .sort((a, b) => (b.depth - (b.p.bias || 0)) - (a.depth - (a.p.bias || 0)));+ const softness = ({ p, depth }) => {+ const sharpAt = focus || depth;+ return Math.min(7, (p.blur ?? 0) + (view.aperture || 0) * Math.abs(depth - sharpAt) / Math.max(1, sharpAt));+ };++ for (const p of (view.ground || []).filter(visible)) drawPanel(p, view, p.blur ?? 0, false);+ if (view.floorY != null) for (const item of items) if (item.p.reflect !== false) drawPanel(item.p, view, softness(item), true);+ for (const item of items) drawPanel(item.p, view, softness(item), false);+ return canvas;+ }++ function project(point, view) {+ const m = viewProjection(view, canvas.width / canvas.height), [x, y, z] = point;+ const cx = m[0] * x + m[4] * y + m[8] * z + m[12];+ const cy = m[1] * x + m[5] * y + m[9] * z + m[13];+ const cw = m[3] * x + m[7] * y + m[11] * z + m[15];+ return [(cx / cw + 1) / 2 * canvas.width, (1 - cy / cw) / 2 * canvas.height];+ }++ return { gl, canvas, texture, render, project };+ }++ return { create };+})();diff --git a/skills/motlab/scripts/grid.py b/skills/motlab/scripts/grid.pynew file mode 100644index 0000000..8462852--- /dev/null+++ b/skills/motlab/scripts/grid.py@@ -0,0 +1,39 @@+"""Lay a numbered pixel grid over an image so coordinates can be read off it.++Used to find puppet pin positions, split polygons and transition shapes in a cut-out. Transparent areas are shown+on solid magenta, so the edge of the art is easy to see.++ python3 grid.py <image> <out.jpg> [--step 100]+"""+import argparse++from PIL import Image, ImageDraw+++def main():+ ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])+ ap.add_argument('image')+ ap.add_argument('out')+ ap.add_argument('--step', type=int, default=100, help='grid spacing in image pixels')+ args = ap.parse_args()++ art = Image.open(args.image).convert('RGBA')+ sheet = Image.new('RGBA', art.size, (230, 0, 160, 255))+ sheet.alpha_composite(art)+ pen = ImageDraw.Draw(sheet)+ w, h = art.size+ line, label = (0, 255, 255, 255), (255, 255, 255, 255)++ for x in range(0, w, args.step):+ pen.line([(x, 0), (x, h - 1)], fill=line, width=1)+ pen.text((x + 3, 3), str(x), fill=label, stroke_width=2, stroke_fill=(0, 0, 0, 255))+ for y in range(args.step, h, args.step):+ pen.line([(0, y), (w - 1, y)], fill=line, width=1)+ pen.text((3, y + 3), str(y), fill=label, stroke_width=2, stroke_fill=(0, 0, 0, 255))++ sheet.convert('RGB').save(args.out, quality=90)+ print(f'{args.out}: {w}x{h}, grid every {args.step} px')+++if __name__ == '__main__':+ main()diff --git a/skills/motlab/scripts/key.py b/skills/motlab/scripts/key.pynew file mode 100644index 0000000..f8520bd--- /dev/null+++ b/skills/motlab/scripts/key.py@@ -0,0 +1,73 @@+"""Remove the flat background around an illustration and save the subject as a transparent, cropped PNG.++The background colour is read from the image's border. Pixels close to it count as background only when they are+connected to the border, so details inside the figure that share the background colour stay. Larger enclosed patches+of background colour (the gap between an arm and the body) are removed too, unless --keep-pockets is given.++ python3 key.py <in.png> <out.png> [--tol 45] [--keep-pockets] [--no-bottom]++--tol colour distance (0 to 441) that still counts as background+--keep-pockets keep enclosed patches of background colour (a yellow folder drawn on a yellow field)+--no-bottom do not start from the bottom edge (a figure cut off by the frame, light trousers)+"""+import argparse++import numpy as np+from PIL import Image, ImageFilter+from scipy import ndimage++POCKET_MIN = 400 # enclosed background patches smaller than this many pixels are kept as part of the drawing+SPECK_MAX = 300 # foreground islands smaller than this are dropped+PAD = 12 # transparent margin left around the subject after cropping+++def border_colour(rgb, depth=4):+ edges = [rgb[:depth], rgb[-depth:], rgb[:, :depth], rgb[:, -depth:]]+ return np.median(np.concatenate([e.reshape(-1, 3) for e in edges]), axis=0)+++def main():+ ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])+ ap.add_argument('src')+ ap.add_argument('out')+ ap.add_argument('--tol', type=float, default=45)+ ap.add_argument('--keep-pockets', action='store_true')+ ap.add_argument('--no-bottom', action='store_true')+ args = ap.parse_args()++ img = Image.open(args.src).convert('RGB')+ rgb = np.asarray(img, dtype=np.float32)+ bg = border_colour(rgb)+ like_bg = np.linalg.norm(rgb - bg, axis=2) < args.tol++ regions, count = ndimage.label(like_bg)+ sides = [regions[0], regions[:, 0], regions[:, -1]]+ if not args.no_bottom:+ sides.append(regions[-1])+ outside = np.setdiff1d(np.unique(np.concatenate(sides)), [0])+ background = np.isin(regions, outside)++ if not args.keep_pockets:+ area = np.bincount(regions.ravel(), minlength=count + 1)+ background |= like_bg & (area[regions] > POCKET_MIN)++ subject = ~background+ islands, n = ndimage.label(subject)+ area = np.bincount(islands.ravel(), minlength=n + 1)+ area[0] = 0+ subject = area[islands] > SPECK_MAX++ alpha = Image.fromarray(subject.astype(np.uint8) * 255).filter(ImageFilter.GaussianBlur(0.8))+ out = img.convert('RGBA')+ out.putalpha(alpha)+ box = out.getbbox()+ if box is None:+ raise SystemExit('nothing left after removing the background; try a lower --tol')+ l, t, r, b = box+ out = out.crop((max(0, l - PAD), max(0, t - PAD), min(img.width, r + PAD), min(img.height, b + PAD)))+ out.save(args.out)+ print(f'{args.out}: {out.width}x{out.height}, background rgb {tuple(int(v) for v in bg)}')+++if __name__ == '__main__':+ main()diff --git a/skills/motlab/scripts/mix.py b/skills/motlab/scripts/mix.pynew file mode 100644index 0000000..3fcb3a3--- /dev/null+++ b/skills/motlab/scripts/mix.py@@ -0,0 +1,337 @@+"""Place sound effects from a local library on an animation's beats, write one WAV and report how well they sync.++ python3 mix.py cues.json <out.wav> --lib <folder> [--lib <folder> ...] [--events events.json] [--len 20.2]+ [--gain 0] [--quant 12] [--voice voice.wav [--duck 9]]++--events the page's window.EVENTS as JSON ([{name, t}], from `motlab events page.html events.json`). Cues that name+ an event move with it when the animation is re-timed.+--len length of the mix in seconds (default: the event called "end", else 20).+--quant N round event times up to the next 1/N s, for posterised animation that shows N poses a second: the sound+ lands on the pose where the change first shows.+--voice the voiceover as it plays in the video, from 0 s. Effects are lowered by --duck dB while it speaks.++cues.json is a list. A one-shot cue:+ {"event": "card.open" or "at": 3.15, "offset": 0, "file": "part of a file name", "pick": 0,+ "role": "click", "db": -14, "align": "auto", "pitch": 1.0, "lp": 6000, "hp": 200, "dur": 2.0, "pan": 0}+ file the first library file (or the pick-th) whose name contains this text, ignoring case+ role hit, tap, click, ui, pop, key, tick, whoosh, riser or ambience: sets the level and where the sound sits+ on the beat. "db" (peak level in dBFS, before --gain) and "align" override it.+ align which point of the sound lands on the beat: start (where it becomes audible), arrive (where it first+ gets within 3 dB of its peak), peak, or end (where its tail drops away). auto uses the role's point, or+ without a role measures the sound: start when it peaks within 60 ms, arrive when it is nearly full well+ before its peak, peak otherwise.+ pitch playback speed (1.2 is higher and shorter). lp / hp: low-pass and high-pass in Hz. dur: cut to this+ many seconds with a short fade. pan: -1 left to 1 right.+A bed, looped if the file is shorter than the span:+ {"type": "bed", "file": ..., "event"/"at": start, "to_event"/"to": end, "db": -26, "from": 0,+ "fade_in": 0.5, "fade_out": 1.0, "lp", "hp", "env": [["event name or seconds", dB], ...]}+ from where to start reading the file, in seconds. env: level changes over time, relative to db.+"""+import argparse+import json+import os+import subprocess+import sys++import numpy as np+from scipy.signal import butter, sosfilt++RATE = 48000+AUDIO = ('.wav', '.aif', '.aiff', '.mp3', '.flac', '.ogg', '.opus', '.m4a')++# Role -> (peak level in dBFS, the point that lands on the beat). The levels follow the Clipwing real-sfx skill+# (https://clipwing.pro/skills/real-sfx). Struck sounds start on the beat so they never come before the motion; a+# whoosh peaks on it, in the middle of the move; a riser ends on it, on the reveal.+ROLES = {+ 'hit': (-4, 'start'), 'tap': (-14, 'start'), 'click': (-14, 'start'), 'ui': (-14, 'start'),+ 'pop': (-14, 'start'), 'key': (-14, 'start'), 'tick': (-14, 'start'),+ 'whoosh': (-9, 'peak'), 'riser': (-12, 'end'), 'ambience': (-24, 'start'),+}+# Closest spacing in ms between two cues of one role before they blur together, from earshot's launch kit.+CLOSEST = {'tick': 66, 'key': 87, 'pop': 114}+CEILING = -1.0 # dBFS peak of the finished mix+++def db(x):+ return 10 ** (x / 20)+++def fail(msg):+ sys.exit(f'mix.py: {msg}')+++# ---- reading and shaping sounds -----------------------------------------------------------------------------------++def decode(path):+ pcm = subprocess.run(['ffmpeg', '-v', 'error', '-i', path, '-ac', '2', '-ar', str(RATE), '-f', 'f32le', '-'],+ capture_output=True, check=True).stdout+ return np.frombuffer(pcm, np.float32).reshape(-1, 2).astype(np.float64)+++def library(folders):+ found = []+ for folder in folders:+ for root, _, names in os.walk(folder):+ found += [os.path.join(root, n) for n in names if n.lower().endswith(AUDIO) and not n.startswith('._')]+ return sorted(found)+++def pick_file(files, text, index=0):+ matches = [f for f in files if text.lower() in os.path.basename(f).lower()]+ if not matches:+ fail(f'no file in the library has "{text}" in its name')+ return matches[min(index, len(matches) - 1)]+++def speed(x, factor):+ if abs(factor - 1) < 1e-3:+ return x+ where = np.arange(0, len(x) - 1, factor)+ return np.stack([np.interp(where, np.arange(len(x)), x[:, ch]) for ch in (0, 1)], axis=1)+++def filtered(x, hz, kind):+ return sosfilt(butter(2, hz / (RATE / 2), kind, output='sos'), x, axis=0)+++def envelope(x):+ """Peak level across both channels, smoothed over 10 ms."""+ width = int(0.01 * RATE)+ return np.convolve(np.abs(x).max(axis=1), np.ones(width) / width, mode='same')+++def landmarks(x):+ """Sample positions of a sound's start (-22 dB of its peak), arrival (-3 dB), peak and end (-26 dB)."""+ e = envelope(x)+ top = e.max() or 1.0+ above = lambda level: np.flatnonzero(e > top * level)+ tail = above(0.05)+ return {+ 'start': int(above(0.08)[0]) if len(above(0.08)) else 0,+ 'arrive': int(above(0.71)[0]) if len(above(0.71)) else 0,+ 'peak': int(np.argmax(e)),+ 'end': int(tail[-1]) if len(tail) else len(x),+ }+++def guess_align(marks):+ if marks['peak'] - marks['start'] <= 0.06 * RATE:+ return 'start'+ if marks['peak'] - marks['arrive'] >= 0.10 * RATE and marks['arrive'] - marks['start'] < 0.45 * RATE:+ return 'arrive'+ return 'peak'+++def ducking(voice, length, depth, attack=0.03, release=0.25):+ """A gain curve that is 1 while the voice is silent and -depth dB while it speaks, plus the speaking mask+ (one value per 10 ms)."""+ hop = RATE // 100+ level = np.abs(voice).max(axis=1)+ blocks = len(level) // hop+ if not blocks:+ return np.ones(length), np.zeros(1, bool)+ rms = np.sqrt((level[:blocks * hop].reshape(blocks, hop) ** 2).mean(axis=1))+ speaking = rms > np.percentile(rms, 95) * db(-30)+ target = np.where(speaking, db(-depth), 1.0)+ fall, rise = np.exp(-1 / (attack * 100)), np.exp(-1 / (release * 100))+ gain, now = np.empty_like(target), 1.0+ for n, want in enumerate(target):+ k = fall if want < now else rise+ now = want + (now - want) * k+ gain[n] = now+ return np.interp(np.arange(length), np.arange(blocks) * hop, gain, right=1.0), speaking+++# ---- the mix ------------------------------------------------------------------------------------------------------++class Timeline:+ def __init__(self, events, quant):+ self.events = events+ self.quant = quant++ def snap(self, t):+ return np.ceil(t * self.quant - 1e-6) / self.quant if self.quant else t++ def event(self, name):+ if name not in self.events:+ fail(f'unknown event "{name}"')+ return self.snap(self.events[name])++ def time(self, value):+ return self.event(value) if isinstance(value, str) else float(value)++ def cue_time(self, cue, name_key='event', time_key='at'):+ base = self.event(cue[name_key]) if name_key in cue else float(cue[time_key])+ return base + cue.get('offset', 0)+++def add_bed(out, cue, sound, level, when, length):+ start = when.cue_time(cue)+ stop = when.time(cue['to_event']) if 'to_event' in cue else float(cue.get('to', length))+ n = int((stop - start) * RATE)+ if n <= 0:+ fail(f'bed {cue["file"]} ends before it starts')+ skip = int(cue.get('from', 0) * RATE)+ source = sound[skip:] if skip < len(sound) else sound+ body = np.tile(source, (n // max(1, len(source)) + 1, 1))[:n]+ gain = np.full(n, db(level))+ if cue.get('env'):+ points = sorted((when.time(t), d) for t, d in cue['env'])+ times = start + np.arange(n) / RATE+ gain *= db(np.interp(times, [p[0] for p in points], [p[1] for p in points]))+ fade_in, fade_out = int(cue.get('fade_in', 0.5) * RATE), int(cue.get('fade_out', 1.0) * RATE)+ if fade_in:+ gain[:fade_in] *= np.linspace(0, 1, fade_in) ** 2+ if fade_out:+ gain[-fade_out:] *= np.linspace(1, 0, fade_out) ** 2+ at = int(start * RATE)+ fit = min(n, len(out) - at)+ out[at:at + fit] += body[:fit] * gain[:fit, None]+ print(f'BED {start:6.2f}-{stop:5.2f} {level:+5.1f} dB {os.path.basename(cue["file"])[:60]}')+++def main():+ ap = argparse.ArgumentParser(description=__doc__.splitlines()[0], formatter_class=argparse.RawDescriptionHelpFormatter)+ ap.add_argument('cues')+ ap.add_argument('out')+ ap.add_argument('--lib', action='append', required=True)+ ap.add_argument('--events')+ ap.add_argument('--len', type=float)+ ap.add_argument('--gain', type=float, default=0.0)+ ap.add_argument('--quant', type=float, default=0.0)+ ap.add_argument('--voice')+ ap.add_argument('--duck', type=float, default=9.0)+ opt = ap.parse_args()++ files = library(opt.lib)+ events = {e['name']: e['t'] for e in json.load(open(opt.events, encoding='utf8'))} if opt.events else {}+ when = Timeline(events, opt.quant)+ length = opt.len or events.get('end') or 20.0+ total = int(length * RATE)+ out = np.zeros((total + 4 * RATE, 2))+ decoded, placed, outside = {}, [], []++ for cue in json.load(open(opt.cues, encoding='utf8')):+ role = cue.get('role')+ if role is not None and role not in ROLES:+ fail(f'unknown role "{role}"; use one of {", ".join(ROLES)}')+ level = cue.get('db', ROLES[role][0] if role else None)+ if level is None:+ fail(f'cue {json.dumps(cue)} needs "db" or "role"')+ path = pick_file(files, cue['file'], cue.get('pick', 0))+ if path not in decoded:+ raw = decode(path)+ decoded[path] = raw / (np.abs(raw).max() + 1e-9)+ sound = speed(decoded[path], cue.get('pitch', 1.0))+ if cue.get('lp'):+ sound = filtered(sound, cue['lp'], 'lowpass')+ if cue.get('hp'):+ sound = filtered(sound, cue['hp'], 'highpass')++ if cue.get('type') == 'bed':+ add_bed(out, dict(cue, file=path), sound, level, when, length)+ continue++ if cue.get('dur'):+ sound = sound[:int(cue['dur'] * RATE)].copy()+ fade = min(len(sound), int(0.08 * RATE))+ sound[len(sound) - fade:] *= np.linspace(1, 0, fade)[:, None]+ pan = cue.get('pan', 0)+ sound = sound * db(level) * np.sqrt(2) * np.array([np.sqrt((1 - pan) / 2), np.sqrt((1 + pan) / 2)])++ align = cue.get('align', 'auto')+ chosen = align == 'auto'+ marks = landmarks(sound)+ if chosen:+ align = ROLES[role][1] if role else guess_align(marks)+ if align not in marks:+ fail(f'unknown align "{align}"; use auto, start, arrive, peak or end')+ anchor = marks[align]++ beat = when.cue_time(cue)+ if not 0 <= beat < length:+ outside.append((beat, cue.get('event', ''), os.path.basename(path)))+ first = int(beat * RATE) - anchor+ if first < 0: # the sound would start before 0 s: drop its head so the anchor still lands on the beat+ sound, anchor, first = sound[-first:], anchor + first, 0+ fit = max(0, min(len(sound), len(out) - first))+ out[first:first + fit] += sound[:fit]+ placed.append({'t': beat, 'align': align, 'auto': chosen, 'event': cue.get('event', ''), 'name': os.path.basename(path),+ 'role': role, 'db': level, 'actual': (first + anchor) / RATE})++ out = out[:total] * db(opt.gain)+ speaking = None+ if opt.voice:+ gain, speaking = ducking(decode(opt.voice), total, opt.duck)+ out *= gain[:, None]+ tail = min(total, int(0.6 * RATE))+ out[total - tail:] *= np.linspace(1, 0, tail)[:, None]+ peak = np.abs(out).max()+ if peak > db(CEILING):+ out *= db(CEILING) / peak+ subprocess.run(['ffmpeg', '-v', 'error', '-y', '-f', 'f32le', '-ar', str(RATE), '-ac', '2', '-i', '-',+ '-c:a', 'pcm_s24le', opt.out], input=out.astype(np.float32).tobytes(), check=True)++ report(placed, outside, out, length, speaking, opt)+++def report(placed, outside, out, length, speaking, opt):+ placed.sort(key=lambda p: p['t'])+ worst = 0.0+ for p in placed:+ off = (p['actual'] - p['t']) * 1000+ worst = max(worst, abs(off))+ print(f"{p['t']:6.3f}s {p['event'][:14]:14s} {p['align'] + ('*' if p['auto'] else ''):7s} {off:+6.1f} ms {p['name'][:58]}")+ peak = 20 * np.log10(np.abs(out).max() + 1e-9)+ print(f'sync: {len(placed)} cues, worst offset {worst:.1f} ms (one frame at 24 fps is 41.7 ms), '+ f'peak {peak:.1f} dBFS (* = align chosen automatically)')+ if speaking is not None:+ print(f'voice: effects lowered {opt.duck:g} dB while it speaks ({speaking.mean() * 100:.0f}% of the voice file)')++ for t, event, name in outside:+ print(f'WARNING: cue at {t:.3f} s ({event or "at"}, {name[:40]}) is outside 0-{length:.3f} s, so it is cut or silent')+ start = 0+ for n in range(1, len(placed) + 1): # one recording five or more times in a row sounds mechanical+ if n < len(placed) and placed[n]['name'] == placed[start]['name']:+ continue+ if n - start >= 5 and placed[start]['role'] not in ('tick', 'key'):+ print(f"WARNING: {placed[start]['name'][:40]} plays {n - start} times in a row from {placed[start]['t']:.2f} s; "+ 'vary the file or its pitch')+ start = n+ for role, gap in CLOSEST.items():+ times = [p['t'] for p in placed if p['role'] == role]+ close = [(a, b) for a, b in zip(times, times[1:]) if (b - a) * 1000 < gap]+ if close:+ a, b = close[0]+ print(f'WARNING: {len(close)} pairs of {role} cues are closer than {gap} ms and blur together '+ f'(first at {a:.3f} s, {(b - a) * 1000:.0f} ms apart)')++ if not placed:+ return+ # Numbers cannot judge taste, so name the few moments most worth listening to.+ times = np.array([p['t'] for p in placed])+ moments = [(placed[0]['t'], 'the first sound')]+ loud = max(placed, key=lambda p: p['db'])+ moments.append((loud['t'], f"the loudest cue ({loud['name'][:30]}, {loud['db']:+.0f} dB)"))+ per_second = [((times >= t) & (times < t + 1)).sum() for t in times]+ busy = int(np.argmax(per_second))+ moments.append((times[busy], f'the busiest second ({per_second[busy]} cues)'))+ edges = np.concatenate([[0.0], times, [length]])+ gap = int(np.argmax(np.diff(edges)))+ if edges[gap + 1] - edges[gap] > 2.5:+ moments.append((edges[gap], f'{edges[gap + 1] - edges[gap]:.1f} s with no sound (finished SFX reels rarely leave more than 2.5 s)'))+ if speaking is not None:+ over = [p for p in placed if speaking[min(len(speaking) - 1, int(p['t'] * 100))]]+ if over:+ top = max(over, key=lambda p: p['db'])+ moments.append((top['t'], f"the loudest cue over the voice ({top['name'][:30]}): is the word still clear?"))+ grouped = {}+ for t, why in moments:+ grouped.setdefault(round(float(t), 2), []).append(why)+ print('listen by ear:')+ for t, why in list(grouped.items())[:5]:+ print(f' {t:6.2f}s {"; ".join(why)}')+++if __name__ == '__main__':+ main()diff --git a/skills/motlab/scripts/puppet.js b/skills/motlab/scripts/puppet.jsnew file mode 100644index 0000000..ef42d98--- /dev/null+++ b/skills/motlab/scripts/puppet.js@@ -0,0 +1,179 @@+// Puppet pins for flat illustrations: a grid mesh laid over a cut-out PNG and bent by a few pins.+//+// const P = Puppet.create(img, pins, { cols: 64, power: 3 });+// P.draw(ctx, moves, x, y, scale, canvasWidth, canvasHeight);+//+// pins: [{ x, y, r }] in the image's pixels. r (default 1) widens a pin's reach.+// moves: one per pin, { dx, dy, rot, s, ox, oy }: move by (dx, dy) image pixels, turn by rot radians and scale by s+// about the pivot (ox, oy), which defaults to the pin itself. An empty {} holds that part still.+// draw: puts image pixel (0, 0) at (x, y) on ctx, scaled by scale; canvasWidth x canvasHeight is ctx's canvas size+// in device pixels. ctx's shadow settings apply, so a flat shadow can be set before drawing.+//+// Every mesh vertex follows a weighted blend of the pins' moves; a pin's weight falls off with distance (higher power+// keeps each pin's influence more local). Cells of the grid that hold no visible pixel are left out of the mesh.+// The mesh is drawn with WebGL2 on one hidden canvas shared by all puppets, then copied onto ctx.+window.Puppet = (() => {+ let shared = null;++ function context() {+ if (shared) return shared;+ const canvas = document.createElement('canvas');+ const gl = canvas.getContext('webgl2', { premultipliedAlpha: true, antialias: true, preserveDrawingBuffer: true });+ if (!gl) throw new Error('puppet.js needs WebGL2');+ const compile = (type, src) => {+ const s = gl.createShader(type);+ gl.shaderSource(s, src);+ gl.compileShader(s);+ if (!gl.getShaderParameter(s, gl.COMPILE_STATUS)) throw new Error(gl.getShaderInfoLog(s));+ return s;+ };+ const program = gl.createProgram();+ gl.attachShader(program, compile(gl.VERTEX_SHADER, `#version 300 es+ layout(location = 0) in vec2 clip;+ layout(location = 1) in vec2 uv;+ out vec2 texUV;+ void main() { texUV = uv; gl_Position = vec4(clip, 0.0, 1.0); }`));+ gl.attachShader(program, compile(gl.FRAGMENT_SHADER, `#version 300 es+ precision highp float;+ in vec2 texUV;+ uniform sampler2D art;+ out vec4 colour;+ void main() { colour = texture(art, texUV); }`));+ gl.linkProgram(program);+ if (!gl.getProgramParameter(program, gl.LINK_STATUS)) throw new Error(gl.getProgramInfoLog(program));+ shared = { canvas, gl, program, art: gl.getUniformLocation(program, 'art') };+ return shared;+ }++ // Which grid cells show any of the art: the image is shrunk to 3 x 3 samples per cell and checked for alpha.+ function coverage(img, cols, rows) {+ const probe = document.createElement('canvas');+ probe.width = cols * 3; probe.height = rows * 3;+ const pc = probe.getContext('2d', { willReadFrequently: true });+ pc.drawImage(img, 0, 0, probe.width, probe.height);+ const alpha = pc.getImageData(0, 0, probe.width, probe.height).data;+ const covered = new Uint8Array(cols * rows);+ for (let py = 0; py < probe.height; py++) {+ for (let px = 0; px < probe.width; px++) {+ if (alpha[(py * probe.width + px) * 4 + 3] > 8) covered[Math.floor(py / 3) * cols + Math.floor(px / 3)] = 1;+ }+ }+ return covered;+ }++ function create(img, pins, opts = {}) {+ const W = img.naturalWidth || img.width, H = img.naturalHeight || img.height;+ const cols = opts.cols || 64, rows = Math.max(1, Math.round(cols * H / W)), power = opts.power || 3;+ const across = cols + 1, count = across * (rows + 1);++ const rest = new Float32Array(count * 2), uv = new Float32Array(count * 2);+ for (let j = 0; j <= rows; j++) {+ for (let i = 0; i <= cols; i++) {+ const v = j * across + i;+ uv[v * 2] = i / cols; uv[v * 2 + 1] = j / rows;+ rest[v * 2] = uv[v * 2] * W; rest[v * 2 + 1] = uv[v * 2 + 1] * H;+ }+ }+ const covered = coverage(img, cols, rows), tris = [];+ for (let j = 0; j < rows; j++) {+ for (let i = 0; i < cols; i++) {+ if (!covered[j * cols + i]) continue;+ const a = j * across + i, b = a + 1, c = a + across, d = c + 1;+ tris.push(a, c, b, b, c, d);+ }+ }++ // Weights: one row of pins.length values per vertex, summing to 1.+ const weights = new Float32Array(count * pins.length);+ for (let v = 0; v < count; v++) {+ let sum = 0;+ pins.forEach((pin, p) => {+ const reach = pin.r || 1, dx = (rest[v * 2] - pin.x) / reach, dy = (rest[v * 2 + 1] - pin.y) / reach;+ const w = Math.pow(dx * dx + dy * dy + 36, -power / 2);+ weights[v * pins.length + p] = w; sum += w;+ });+ for (let p = 0; p < pins.length; p++) weights[v * pins.length + p] /= sum;+ }++ const clip = new Float32Array(count * 2);+ let gpu = null;++ function upload() {+ const { gl } = context();+ const texture = gl.createTexture();+ gl.bindTexture(gl.TEXTURE_2D, texture);+ gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, true);+ gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, img);+ gl.generateMipmap(gl.TEXTURE_2D);+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR_MIPMAP_LINEAR);+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);+ const vao = gl.createVertexArray();+ gl.bindVertexArray(vao);+ const clipBuffer = gl.createBuffer();+ gl.bindBuffer(gl.ARRAY_BUFFER, clipBuffer);+ gl.bufferData(gl.ARRAY_BUFFER, clip.byteLength, gl.DYNAMIC_DRAW);+ gl.enableVertexAttribArray(0);+ gl.vertexAttribPointer(0, 2, gl.FLOAT, false, 0, 0);+ gl.bindBuffer(gl.ARRAY_BUFFER, gl.createBuffer());+ gl.bufferData(gl.ARRAY_BUFFER, uv, gl.STATIC_DRAW);+ gl.enableVertexAttribArray(1);+ gl.vertexAttribPointer(1, 2, gl.FLOAT, false, 0, 0);+ gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, gl.createBuffer());+ gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new Uint32Array(tris), gl.STATIC_DRAW);+ gl.bindVertexArray(null);+ gpu = { texture, vao, clipBuffer };+ }++ // Bend the mesh, then place it on the target canvas in clip space.+ function pose(moves, x, y, scale, cw, ch) {+ const xf = pins.map((pin, p) => {+ const m = moves[p] || {}, s = m.s ?? 1, turn = m.rot || 0;+ return { cos: Math.cos(turn) * s, sin: Math.sin(turn) * s, ox: m.ox ?? pin.x, oy: m.oy ?? pin.y, dx: m.dx || 0, dy: m.dy || 0 };+ });+ for (let v = 0; v < count; v++) {+ const rx = rest[v * 2], ry = rest[v * 2 + 1];+ let bx = 0, by = 0;+ for (let p = 0; p < xf.length; p++) {+ const w = weights[v * xf.length + p];+ if (w < 1e-5) continue;+ const t = xf[p], lx = rx - t.ox, ly = ry - t.oy;+ bx += w * (t.ox + t.cos * lx - t.sin * ly + t.dx);+ by += w * (t.oy + t.sin * lx + t.cos * ly + t.dy);+ }+ clip[v * 2] = (x + bx * scale) / cw * 2 - 1;+ clip[v * 2 + 1] = 1 - (y + by * scale) / ch * 2;+ }+ }++ function draw(ctx, moves, x, y, scale, cw, ch) {+ const g = context(), gl = g.gl;+ if (!gpu) upload();+ if (g.canvas.width !== cw || g.canvas.height !== ch) { g.canvas.width = cw; g.canvas.height = ch; }+ pose(moves, x, y, scale, cw, ch);+ gl.viewport(0, 0, cw, ch);+ gl.clearColor(0, 0, 0, 0);+ gl.clear(gl.COLOR_BUFFER_BIT);+ gl.useProgram(g.program);+ gl.bindVertexArray(gpu.vao);+ gl.bindBuffer(gl.ARRAY_BUFFER, gpu.clipBuffer);+ gl.bufferSubData(gl.ARRAY_BUFFER, 0, clip);+ gl.activeTexture(gl.TEXTURE0);+ gl.bindTexture(gl.TEXTURE_2D, gpu.texture);+ gl.uniform1i(g.art, 0);+ gl.enable(gl.BLEND);+ gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);+ gl.drawElements(gl.TRIANGLES, tris.length, gl.UNSIGNED_INT, 0);+ gl.bindVertexArray(null);+ ctx.save();+ ctx.setTransform(1, 0, 0, 1, 0, 0);+ ctx.drawImage(g.canvas, 0, 0);+ ctx.restore();+ }++ return { draw, pins, W, H, tris: tris.length / 3 };+ }++ return { create };+})();diff --git a/skills/motlab/scripts/split.py b/skills/motlab/scripts/split.pynew file mode 100644index 0000000..9c7285d--- /dev/null+++ b/skills/motlab/scripts/split.py@@ -0,0 +1,49 @@+"""Cut one transparent PNG into layer PNGs of the same size, one per named polygon.++Each layer keeps only the pixels inside its polygon, at their original position, so the layers stack back into the+original image and each part can move on its own. Pixels no polygon covers go to <stem>-base.png.++ python3 split.py <cutout.png> <regions>++<regions> is JSON, inline or a path to a .json file: {"card": [[x, y], [x, y], ...], "ticks": [...]}, with points in+the image's pixels (read them off with grid.py).+"""+import json+import os+import sys++from PIL import Image, ImageChops, ImageDraw+++def polygon_mask(size, points):+ mask = Image.new('L', size, 0)+ ImageDraw.Draw(mask).polygon([(float(x), float(y)) for x, y in points], fill=255)+ return mask+++def main():+ if len(sys.argv) != 3:+ sys.exit(__doc__)+ path, spec = sys.argv[1], sys.argv[2]+ regions = json.load(open(spec, encoding='utf8')) if os.path.isfile(spec) else json.loads(spec)++ art = Image.open(path).convert('RGBA')+ stem = os.path.splitext(path)[0]+ claimed = Image.new('L', art.size, 0)+ alpha = art.getchannel('A')++ for name, points in regions.items():+ mask = polygon_mask(art.size, points)+ layer = art.copy()+ layer.putalpha(ImageChops.multiply(alpha, mask))+ layer.save(f'{stem}-{name}.png')+ claimed = ImageChops.lighter(claimed, mask)++ rest = art.copy()+ rest.putalpha(ImageChops.multiply(alpha, ImageChops.invert(claimed)))+ rest.save(f'{stem}-base.png')+ print('wrote', ', '.join(f'{os.path.basename(stem)}-{n}.png' for n in [*regions, 'base']))+++if __name__ == '__main__':+ main()diff --git a/skills/motlab/scripts/synth_sfx.py b/skills/motlab/scripts/synth_sfx.pynew file mode 100644index 0000000..da16d70--- /dev/null+++ b/skills/motlab/scripts/synth_sfx.py@@ -0,0 +1,100 @@+"""Make a small set of sound effects from noise and sine waves, for when there is no sound library.++Writes 48 kHz stereo WAVs: three whooshes, a pop, a tick, a thud, a shutter, a riser and an air bed. They are plainer+than recorded sounds, but nothing is downloaded and nothing costs anything. Pass the folder to mix.py with --lib, and+add your own functions here when an ad needs a sound the set does not have.++ python3 synth_sfx.py <folder>+"""+import os+import sys+import wave++import numpy as np+from scipy.signal import butter, sosfilt++RATE = 48000+rng = np.random.default_rng(7)+++def seconds(n):+ return np.arange(int(n * RATE)) / RATE+++def bandpass(x, low, high, order=2):+ nyq = RATE / 2+ return sosfilt(butter(order, [low / nyq, min(high, nyq * 0.95) / nyq], 'bandpass', output='sos'), x)+++def sweep(f0, f1, dur):+ """A sine whose frequency glides exponentially from f0 to f1."""+ t = seconds(dur)+ freq = f0 * (f1 / f0) ** (t / dur)+ return np.sin(2 * np.pi * np.cumsum(freq) / RATE)+++def decay(dur, attack, half_life):+ t = seconds(dur)+ return np.clip(t / attack, 0, 1) * 0.5 ** (t / half_life)+++def whoosh(dur, centre_lo, centre_hi):+ """Noise through a band that rises to centre_hi in the middle and falls back, swelling and fading with it."""+ t = seconds(dur)+ noise = rng.standard_normal(len(t))+ shape = np.sin(np.pi * t / dur)+ out = np.zeros_like(noise)+ hop = 512+ window = np.hanning(hop * 2)+ for start in range(0, len(t) - hop * 2, hop):+ centre = centre_lo + (centre_hi - centre_lo) * shape[start + hop]+ chunk = bandpass(noise[start:start + hop * 2], max(40, centre * 0.5), centre * 1.6)+ out[start:start + hop * 2] += chunk * window+ return out * shape ** 1.5+++def write(folder, name, mono):+ mono = mono / (np.max(np.abs(mono)) + 1e-12) * 0.89+ delay = 9 # a few samples between left and right gives a little width+ stereo = np.stack([mono, np.concatenate([np.zeros(delay), mono[:-delay]])], axis=1)+ with wave.open(os.path.join(folder, name + '.wav'), 'wb') as f:+ f.setnchannels(2)+ f.setsampwidth(2)+ f.setframerate(RATE)+ f.writeframes((stereo * 32767).astype('<i2').tobytes())+ return name+++def main():+ if len(sys.argv) != 2:+ sys.exit(__doc__)+ folder = sys.argv[1]+ os.makedirs(folder, exist_ok=True)+ made = []++ for label, dur, lo, hi in [('short', 0.4, 600, 5200), ('medium', 0.7, 350, 3800), ('long', 1.1, 220, 2600)]:+ made.append(write(folder, f'synth whoosh {label}', whoosh(dur, lo, hi)))++ made.append(write(folder, 'synth pop', sweep(700, 170, 0.16) * decay(0.16, 0.002, 0.025)))++ click = bandpass(rng.standard_normal(int(0.05 * RATE)), 2800, 9500) * decay(0.05, 0.0004, 0.004)+ made.append(write(folder, 'synth tick', click + 0.4 * sweep(1900, 1700, 0.05) * decay(0.05, 0.0004, 0.007)))++ body = sweep(110, 45, 0.8) * decay(0.8, 0.003, 0.12)+ made.append(write(folder, 'synth thud', body + 0.15 * bandpass(rng.standard_normal(len(body)), 200, 1500) * decay(0.8, 0.001, 0.02)))++ made.append(write(folder, 'synth shutter', bandpass(rng.standard_normal(int(0.09 * RATE)), 1400, 8500) * decay(0.09, 0.0008, 0.012)))++ t = seconds(2.4)+ build = (t / t[-1]) ** 2.2+ made.append(write(folder, 'synth riser', (0.6 * bandpass(rng.standard_normal(len(t)), 900, 7500) + 0.4 * sweep(120, 480, 2.4)) * build))++ t = seconds(4.0)+ edges = np.clip(np.minimum(t, t[-1] - t) / 0.6, 0, 1)+ made.append(write(folder, 'synth air bed', bandpass(rng.standard_normal(len(t)), 1100, 8000) * edges))++ print(f'{len(made)} sounds in {folder}: ' + ', '.join(made))+++if __name__ == '__main__':+ main()diff --git a/skills/motlab/templates/font-specimen.html b/skills/motlab/templates/font-specimen.htmlnew file mode 100644index 0000000..8c87cce--- /dev/null+++ b/skills/motlab/templates/font-specimen.html@@ -0,0 +1,38 @@+<!doctype html>+<!-- Copy next to fonts.css (made by get_font.py) and look at it with:+ motlab stills font-specimen.html <outDir> 0+ Put the video's real words in `text` and its colours in `bg` and `fg`. -->+<meta charset="utf-8">+<link rel="stylesheet" href="fonts.css">+<body style="margin:0"><canvas id="c"></canvas>+<script>+const text = 'The quick brown fox, 0123456789', bg = '#f4f3ef', fg = '#111';+const S = parseFloat(new URLSearchParams(location.search).get('scale') || '1');+const cv = document.getElementById('c'), ctx = cv.getContext('2d');+window.TOTAL = 1;+window.ready = (async () => {+ const faces = [...document.fonts];+ await Promise.all(faces.map(f => f.load().catch(() => {})));+ // one row per family, style and weight; a variable range shows its two ends and the middle+ const rows = new Map();+ for (const f of faces) {+ const fam = f.family.replace(/^["']|["']$/g, ''), w = String(f.weight).split(' ').map(Number);+ const ws = w.length > 1 ? [w[0], Math.round((w[0] + w[1]) / 200) * 100, w[1]] : w;+ for (const x of ws) rows.set(`${fam}|${f.style}|${x}`, { fam, style: f.style, w: x, failed: f.status === 'error' });+ }+ window.rows = [...rows.values()];+ cv.width = 1920 * S; cv.height = Math.max(2, Math.ceil((80 + window.rows.length * 150) * S / 2) * 2);+ render(0);+})();+function render() {+ ctx.setTransform(S, 0, 0, S, 0, 0); ctx.fillStyle = bg; ctx.fillRect(0, 0, 1920, cv.height / S);+ window.rows.forEach((r, i) => {+ const y = 60 + i * 150;+ ctx.fillStyle = r.failed ? '#d22' : '#888'; ctx.font = '500 22px system-ui, sans-serif';+ ctx.fillText(`${r.fam} ${r.w}${r.style === 'normal' ? '' : ' ' + r.style}${r.failed ? ' FAILED TO LOAD' : ''}`, 60, y + 20);+ ctx.fillStyle = fg; ctx.font = `${r.style} ${r.w} 76px "${r.fam}"`;+ ctx.fillText(text, 60, y + 110);+ });+}+window.renderAt = render;+</script>diff --git a/skills/motlab/templates/template-2d.html b/skills/motlab/templates/template-2d.htmlnew file mode 100644index 0000000..4449e3b--- /dev/null+++ b/skills/motlab/templates/template-2d.html@@ -0,0 +1,146 @@+<!doctype html>+<html lang="en"><head><meta charset="utf-8"><title>Scene (2D)</title>+<style>+ /* The brand's font files go next to the page; point Head at them (Poppins SemiBold as an example). */+ @font-face { font-family: Head; src: url("fonts/Poppins-SemiBold.ttf") format("truetype"); }+ html, body { margin: 0; height: 100%; background: #000; display: grid; place-items: center; }+ canvas { display: block; width: min(100vw, 100vh * 16 / 9); aspect-ratio: 16 / 9; }+</style></head><body><canvas id="c"></canvas>+<!-- puppet.js bends cut-out characters with pins; copy it next to the page when a shot uses it. -->+<script src="puppet.js"></script>+<script>+// A 2D starter for flat, illustrated scenes. Each shot is a flat colour field with its own drawing. A shot ends by+// growing one of its shapes (a circle or a rounded box) until it fills the frame: the shape fills with the next+// shot's colour, and the next shot settles in inside it. Headlines rise word by word from behind a mask.+// Optional feel: time held in poses (POSES per second), a pixel or two of jitter per pose, hard flat shadows.+// Copy the page, rename it and replace SHOTS. Page contract: renderAt(t), TOTAL, ready, ?t=, ?scale=.+const W = 1920, H = 1080, END = 8, POSES = 12; // POSES 0 = smooth time; 12 or 8 held poses a second, render at 24 fps+const params = new URLSearchParams(location.search), SCALE = parseFloat(params.get('scale') || '1');+const cv = document.querySelector('#c'), ctx = cv.getContext('2d');+cv.width = Math.round(W * SCALE); cv.height = Math.round(H * SCALE);+const INK = '#141414', TAU = Math.PI * 2;++// ---- timing helpers ----+const clamp = (v, lo = 0, hi = 1) => Math.min(hi, Math.max(lo, v));+const mix = (a, b, k) => a + (b - a) * k;+const span = (t, from, to) => clamp((t - from) / (to - from));+const easeOut = k => 1 - (1 - clamp(k)) ** 3;+const easeInOut = k => (k = clamp(k), k < 0.5 ? 4 * k ** 3 : 1 - (2 - 2 * k) ** 3 / 2);+const overshoot = (k, amount = 1.6) => (k = clamp(k) - 1, 1 + k * k * ((amount + 1) * k + amount));++// ---- hand-made feel ----+let pose = 0;+const hash = n => { const s = Math.sin(n * 91.345 + pose * 47.853) * 24634.6345; return s - Math.floor(s); };+const jitter = (id, px = 1.5) => [(hash(id) - 0.5) * 2 * px, (hash(id + 0.5) - 0.5) * 2 * px]; // same offset for a whole pose+function flatShadow(g, on = true) { // shadow offsets are in device pixels, so they are scaled here+ g.shadowColor = on ? 'rgba(20, 20, 20, 0.25)' : 'transparent';+ g.shadowBlur = 0; g.shadowOffsetX = 14 * SCALE; g.shadowOffsetY = 16 * SCALE;+}++function backdrop(g, colour, lt) { // flat colour, a faint grid sliding slowly, light rising from the bottom+ g.fillStyle = colour; g.fillRect(0, 0, W, H);+ if (colour === '#000') return;+ const cell = 120, shift = Math.round(lt * 20) % cell; // whole-pixel steps and 3.5 px lines stay steady when scaled+ g.save(); g.strokeStyle = 'rgba(255, 255, 255, 0.1)'; g.lineWidth = 3.5; g.beginPath();+ for (let x = shift - cell; x < W + cell; x += cell) { g.moveTo(x, 0); g.lineTo(x, H); }+ for (let y = Math.round(shift / 2) - cell; y < H + cell; y += cell) { g.moveTo(0, y); g.lineTo(W, y); }+ g.stroke();+ const glow = g.createRadialGradient(W / 2, H * 1.1, 0, W / 2, H * 1.1, H * 0.9);+ glow.addColorStop(0, 'rgba(255, 255, 255, 0.22)'); glow.addColorStop(1, 'rgba(255, 255, 255, 0)');+ g.fillStyle = glow; g.fillRect(0, 0, W, H); g.restore();+}++function headline(g, text, lt, { at = 0.2, y = 170, size = 76, colour = INK, gap = 0.08, rise = 0.3 } = {}) {+ g.save();+ g.font = `600 ${size}px Head, system-ui, sans-serif`; g.letterSpacing = `${-0.03 * size}px`; g.textBaseline = 'alphabetic';+ const words = text.split(' '), widths = words.map(w => g.measureText(w).width), space = g.measureText(' ').width;+ let x = (W - widths.reduce((a, b) => a + b, 0) - space * (words.length - 1)) / 2;+ words.forEach((word, n) => {+ const k = easeOut(span(lt, at + n * gap, at + n * gap + rise));+ if (k > 0) {+ g.save(); g.beginPath(); g.rect(x - 10, y - size * 1.1, widths[n] + 20, size * 1.45); g.clip(); // the mask+ g.fillStyle = colour; g.fillText(word, x, y + (1 - k) * size * 1.25); g.restore();+ }+ x += widths[n] + space;+ });+ g.restore();+}++// ---- shots: when each starts, its colour, what it draws (lt = seconds into the shot), and the shape it leaves+// through (in the shot's own 1920x1080 space). A change takes CHANGE seconds from the next shot's start. ----+const CHANGE = 0.5;+const SHOTS = [+ { at: 0, colour: '#2FD9A0',+ draw(g, lt) {+ backdrop(g, this.colour, lt); headline(g, 'Your first headline.', lt);+ const [jx, jy] = jitter(1);+ flatShadow(g); g.beginPath(); g.roundRect(770 + jx, 390 + jy, 380, 300, 30); g.fillStyle = '#fff'; g.fill();+ flatShadow(g, false); g.lineWidth = 6; g.strokeStyle = INK; g.stroke();+ },+ exit: { box: [770, 390, 380, 300], radius: 30 } },+ { at: 2.5, colour: '#F4CF4F',+ draw(g, lt) {+ backdrop(g, this.colour, lt); headline(g, 'The second beat.', lt);+ const r = 140 * overshoot(span(lt, 0.3, 0.65));+ if (r > 0) { g.beginPath(); g.arc(960, 560, r, 0, TAU); g.fillStyle = '#2AB5F7'; g.fill(); g.lineWidth = 6; g.strokeStyle = INK; g.stroke(); }+ },+ exit: { circle: [960, 560, 140] } },+ { at: 5, colour: '#000',+ draw(g, lt) { backdrop(g, this.colour, lt); headline(g, 'Brand. Tagline.', lt, { at: 0.3, y: 560, size: 90, colour: '#fff' }); } },+];++// The camera on each shot: a slow push in and a drift. The last shot holds still so the end card stays centred.+const zoom = (n, lt) => n === SHOTS.length - 1 ? 1 : 1 + 0.045 * lt;+const drift = (n, lt) => n === SHOTS.length - 1 ? 0 : -16 * lt;+const layers = SHOTS.map(() => Object.assign(document.createElement('canvas'), { width: cv.width, height: cv.height }));++function shotImage(n, lt) {+ const g = layers[n].getContext('2d');+ g.setTransform(1, 0, 0, 1, 0, 0); g.clearRect(0, 0, cv.width, cv.height); g.setTransform(SCALE, 0, 0, SCALE, 0, 0);+ SHOTS[n].draw(g, lt);+ return layers[n];+}+function place(g, image, z, dx) { // draw a shot layer with its camera, in device pixels+ g.save(); g.setTransform(z, 0, 0, z, (cv.width / 2) * (1 - z) + dx * SCALE, (cv.height / 2) * (1 - z));+ g.drawImage(image, 0, 0); g.restore();+}+const onScreen = (n, lt, x, y) => [W / 2 + drift(n, lt) + (x - W / 2) * zoom(n, lt), H / 2 + (y - H / 2) * zoom(n, lt)];++function render(t) {+ const time = POSES ? Math.floor(t * POSES + 1e-6) / POSES : t;+ pose = Math.round(time * (POSES || 60));+ let n = 0;+ SHOTS.forEach((s, i) => { if (time >= s.at) n = i; });+ const changing = n > 0 && time < SHOTS[n].at + CHANGE, shot = changing ? n - 1 : n, lt = time - SHOTS[shot].at;++ ctx.setTransform(1, 0, 0, 1, 0, 0); ctx.fillStyle = '#000'; ctx.fillRect(0, 0, cv.width, cv.height);+ place(ctx, shotImage(shot, lt), zoom(shot, lt), drift(shot, lt));+ if (!changing) return;++ const next = shot + 1, nlt = time - SHOTS[next].at, k = easeInOut(span(time, SHOTS[next].at, SHOTS[next].at + CHANGE));+ const exit = SHOTS[shot].exit, z = zoom(shot, lt);+ ctx.save(); ctx.setTransform(SCALE, 0, 0, SCALE, 0, 0); ctx.beginPath();+ if (exit.circle) {+ const [cx, cy, r] = exit.circle, [sx, sy] = onScreen(shot, lt, cx, cy);+ ctx.arc(mix(sx, W / 2, k), mix(sy, H / 2, k), mix(r * z, Math.hypot(W, H) * 0.62, k), 0, TAU);+ } else {+ const [bx, by, bw, bh] = exit.box, [sx, sy] = onScreen(shot, lt, bx, by);+ ctx.roundRect(mix(sx, -30, k), mix(sy, -30, k), mix(bw * z, W + 60, k), mix(bh * z, H + 60, k), mix(exit.radius * z, 0, k));+ }+ ctx.save(); ctx.clip();+ ctx.fillStyle = SHOTS[next].colour; ctx.fillRect(0, 0, W, H);+ if (k > 0.12) place(ctx, shotImage(next, nlt), zoom(next, nlt) * mix(0.93, 1, span(k, 0.12, 1)), drift(next, nlt));+ ctx.restore();+ ctx.globalAlpha = 1 - k; ctx.lineWidth = 6; ctx.strokeStyle = INK; ctx.stroke();+ ctx.restore();+}++window.TOTAL = END;+window.renderAt = render;+window.ready = document.fonts.load('600 76px Head').catch(() => {}).then(() => {+ // Opened on its own, the page loops. In a render or in the viewer (an iframe), only renderAt draws.+ if (params.has('t') || window.top !== window) render(parseFloat(params.get('t') || '0'));+ else requestAnimationFrame(function loop(ms) { render((ms / 1000) % END); requestAnimationFrame(loop); });+ return true;+});+</script></body></html>diff --git a/skills/motlab/templates/template-3d.html b/skills/motlab/templates/template-3d.htmlnew file mode 100644index 0000000..df4b7a3--- /dev/null+++ b/skills/motlab/templates/template-3d.html@@ -0,0 +1,95 @@+<!doctype html>+<html lang="en"><head><meta charset="utf-8"><title>Scene (UI in 3D)</title>+<style>+ /* The UI font files go next to the page; point UI at them (Inter as an example). */+ @font-face { font-family: UI; src: url("fonts/Inter-Variable.ttf") format("truetype"); font-weight: 100 900; }+ html, body { margin: 0; height: 100%; background: #000; display: grid; place-items: center; }+ canvas { display: block; width: min(100vw, 100vh * 16 / 9); aspect-ratio: 16 / 9; }+</style></head><body><canvas id="c"></canvas>+<script src="gl3d.js"></script>+<script>+// A starter for UI in 3D space with gl3d.js. Every element is a flat panel: its picture is drawn with ordinary 2D+// canvas code (at TEX times its size, so it stays sharp up close) and gl3d.js places it in 3D. One camera moves+// through the whole scene. Motion blur averages SUBFRAMES renders across half a frame.+// Page contract: renderAt(t), TOTAL, ready, ?t=, ?scale=. motlab renders with Chrome on the GPU, which WebGL needs.+const W = 1920, H = 1080, END = 8, TEX = 2, SUBFRAMES = 12, SHUTTER = 0.5 / 60;+const params = new URLSearchParams(location.search), SCALE = parseFloat(params.get('scale') || '1');+const cv = document.querySelector('#c'), out = cv.getContext('2d');+cv.width = Math.round(W * SCALE); cv.height = Math.round(H * SCALE);+const blank = () => Object.assign(document.createElement('canvas'), { width: cv.width, height: cv.height });+const stage = GL3D.create(cv.width, cv.height), frame = blank(), sum = blank();++const clamp = (v, lo = 0, hi = 1) => Math.min(hi, Math.max(lo, v));+const mix = (a, b, k) => a + (b - a) * k;+const span = (t, from, to) => clamp((t - from) / (to - from));+const expoOut = k => (k = clamp(k), k === 1 ? 1 : 1 - 2 ** (-10 * k));+const sineInOut = k => (1 - Math.cos(Math.PI * clamp(k))) / 2;++// A panel: its picture is drawn by paint(g, ...args) in panel units, with `pad` spare room round it for shadows.+// panel.update(...args) redraws it, and does nothing when the arguments are the same as last time.+function panel(w, h, pad, paint) {+ const c = Object.assign(document.createElement('canvas'), { width: (w + 2 * pad) * TEX, height: (h + 2 * pad) * TEX });+ const p = { w: w + 2 * pad, h: h + 2 * pad, tex: null, last: null };+ p.update = (...args) => {+ const key = JSON.stringify(args);+ if (p.tex && key === p.last) return p;+ p.last = key;+ const g = c.getContext('2d');+ g.setTransform(1, 0, 0, 1, 0, 0); g.clearRect(0, 0, c.width, c.height);+ g.setTransform(TEX, 0, 0, TEX, pad * TEX, pad * TEX);+ paint(g, ...args);+ p.tex = p.tex ? p.tex.update() : stage.texture(c);+ return p;+ };+ return p.update();+}++const card = panel(540, 760, 60, g => {+ g.save(); g.shadowColor = 'rgba(0, 0, 0, 0.5)'; g.shadowBlur = 60 * TEX; g.shadowOffsetY = 24 * TEX; // shadow sizes are device pixels+ g.beginPath(); g.roundRect(0, 0, 540, 760, 32); g.fillStyle = '#131416'; g.fill(); g.restore();+ g.font = '700 52px UI, system-ui, sans-serif'; g.textAlign = 'center'; g.fillStyle = '#fff';+ g.fillText('Your product', 270, 650);+});+const art = panel(460, 460, 0, g => {+ const fill = g.createLinearGradient(0, 0, 460, 460);+ fill.addColorStop(0, '#22DFA0'); fill.addColorStop(1, '#5040F5');+ g.beginPath(); g.roundRect(0, 0, 460, 460, 22); g.fillStyle = fill; g.fill();+});++// One camera for the whole scene: it pulls back fast and then slowly, then circles one way only.+function camera(t) {+ const distance = Math.exp(mix(Math.log(220), Math.log(1500), expoOut(span(t, 0, 1.8))));+ const angle = 0.35 * sineInOut(span(t, 1.5, END)), target = [0, 0, 0];+ return {+ eye: [distance * Math.sin(angle), 110 * Math.sin(angle), distance * Math.cos(angle)], target,+ fov: 34, focus: distance, aperture: 0.3, fog: { near: 2400, far: 6500, color: [0.025, 0.03, 0.035] },+ };+}+// The panels at time t. bias lifts a panel in the draw order, for things stacked close together.+const panels = t => [+ { tex: card.tex, w: card.w, h: card.h, pos: [0, 0, 0] },+ { tex: art.tex, w: art.w, h: art.h, pos: [0, 90, 30], bias: 8 },+];++function render(t) {+ const acc = sum.getContext('2d'), f = frame.getContext('2d');+ acc.setTransform(1, 0, 0, 1, 0, 0); acc.globalAlpha = 1; acc.clearRect(0, 0, sum.width, sum.height);+ for (let i = 0; i < SUBFRAMES; i++) {+ const ts = clamp(t + (SUBFRAMES > 1 ? i / (SUBFRAMES - 1) - 0.5 : 0) * SHUTTER, 0, END), view = camera(ts);+ f.globalAlpha = 1; f.fillStyle = '#07080a'; f.fillRect(0, 0, frame.width, frame.height);+ f.drawImage(stage.render(panels(ts), view), 0, 0);+ acc.globalAlpha = 1 / (i + 1); // a running average: each new sub-frame weighs 1/(i+1)+ acc.drawImage(frame, 0, 0);+ }+ out.setTransform(1, 0, 0, 1, 0, 0); out.globalAlpha = 1; out.drawImage(sum, 0, 0);+}++window.TOTAL = END;+window.renderAt = render;+window.ready = document.fonts.load('700 52px UI').catch(() => {}).then(() => {+ card.last = null; card.update(); // draw the card again now that its font is in+ if (params.has('t') || window.top !== window) render(parseFloat(params.get('t') || '0'));+ else requestAnimationFrame(function loop(ms) { render((ms / 1000) % END); requestAnimationFrame(loop); });+ return true;+});+</script></body></html>diff --git a/skills/motlab/templates/template-p5.html b/skills/motlab/templates/template-p5.htmlnew file mode 100644index 0000000..bbe7651--- /dev/null+++ b/skills/motlab/templates/template-p5.html@@ -0,0 +1,58 @@+<!doctype html>+<html lang="en"><head><meta charset="utf-8"><title>Ad (p5.js)</title>+<style>+ /* The brand's font files go next to the page; point Head at them (Poppins SemiBold as an example). */+ @font-face { font-family: Head; src: url("fonts/Poppins-SemiBold.ttf") format("truetype"); }+ html, body { margin: 0; height: 100%; background: #000; display: grid; place-items: center; }+ canvas { display: block; width: min(100vw, 100vh * 16 / 9); aspect-ratio: 16 / 9; }+</style></head><body><canvas id="c"></canvas>+<script src="https://cdn.jsdelivr.net/npm/[email protected]/lib/p5.min.js"></script>+<script>+// p5.js starter for generative graphics: a field of strokes that follow drifting noise, and a title. p5 runs in+// instance mode with noLoop(); renderAt(t) sets T and calls redraw(), then the p5 canvas is copied onto canvas #c.+// The renderer asks for frames in any order, so draw() must be a function of T alone:+// - never frameCount, millis(), deltaTime, or state carried over from the previous frame (particles that move+// a little each frame); compute positions from T, or simulate from 0 to T inside draw+// - noise() and random() only after noiseSeed() and randomSeed() at the top of draw+// Page contract: renderAt(t), TOTAL, ready, ?t=, ?scale=. p5 comes from the CDN, so a render needs the network.+const W = 1920, H = 1080, END = 6, q = new URLSearchParams(location.search), SCALE = parseFloat(q.get('scale') || '1');+const cv = document.querySelector('#c'), ctx = cv.getContext('2d');+cv.width = Math.round(W * SCALE); cv.height = Math.round(H * SCALE);+const clamp01 = v => Math.max(0, Math.min(1, v)), prog = (t, a, b) => clamp01((t - a) / (b - a)), outCubic = k => 1 - Math.pow(1 - clamp01(k), 3);+let T = 0, P = null;++function paint(p, t) { // in 1920x1080 units; SCALE is applied once here. Not named draw or setup: p5 would start a second, global sketch+ p.noiseSeed(7); p.randomSeed(7);+ p.push(); p.scale(SCALE);+ p.background('#0e0f12');+ const A = p.color('#1FE39A'), B = p.color('#4E3BFF'), G = 40;+ p.strokeCap(p.ROUND); p.strokeWeight(4);+ for (let y = G; y < H; y += G) for (let x = G; x < W; x += G) {+ const k = outCubic(prog(t, 0.1 + 0.9 * x / W, 0.9 + 0.9 * x / W)); // a wave of strokes growing in from the left+ if (k <= 0) continue;+ const a = p.noise(x * 0.0025, y * 0.0025, t * 0.18) * p.TWO_PI * 2, len = 22 * k;+ p.stroke(p.lerpColor(A, B, p.noise(x * 0.001, y * 0.001, 5 + t * 0.1)));+ p.line(x, y, x + Math.cos(a) * len, y + Math.sin(a) * len);+ }+ const e = outCubic(prog(t, 1.2, 1.9));+ p.noStroke(); p.fill(255, 255 * e); p.textFont('Head, system-ui, sans-serif'); p.textSize(110); p.textAlign(p.CENTER, p.CENTER);+ p.text('Your idea, as a system.', W / 2, H / 2 + (1 - e) * 40);+ p.pop();+}++async function render(t) {+ T = t; await P.redraw();+ ctx.setTransform(1, 0, 0, 1, 0, 0); ctx.drawImage(P.drawingContext.canvas, 0, 0);+}++window.TOTAL = END;+window.renderAt = render;+window.ready = new Promise(res => new p5(p => {+ p.setup = () => { p.pixelDensity(1); p.createCanvas(cv.width, cv.height); p.drawingContext.canvas.style.display = 'none'; p.noLoop(); P = p; res(); };+ p.draw = () => { if (P) paint(p, T); };+})).then(() => document.fonts.load('600 110px Head').catch(() => {})).then(async () => {+ // Opened by hand, the page plays on a loop. In the render and inside the viewer (an iframe), only renderAt draws.+ if (q.has('t') || window.top !== window) await render(parseFloat(q.get('t') || '0')); else (function tick(n) { render((n / 1000) % END).then(() => requestAnimationFrame(tick)); })(0);+ return true;+});+</script></body></html>diff --git a/skills/motlab/templates/template-three.html b/skills/motlab/templates/template-three.htmlnew file mode 100644index 0000000..d749a03--- /dev/null+++ b/skills/motlab/templates/template-three.html@@ -0,0 +1,112 @@+<!doctype html>+<html lang="en"><head><meta charset="utf-8"><title>Ad (three.js)</title>+<style>+ /* The brand's font files go next to the page; point Head at them (Poppins SemiBold as an example). */+ @font-face { font-family: Head; src: url("fonts/Poppins-SemiBold.ttf") format("truetype"); }+ html, body { margin: 0; height: 100%; background: #000; display: grid; place-items: center; }+ canvas { display: block; width: min(100vw, 100vh * 16 / 9); aspect-ratio: 16 / 9; }+</style>+<script type="importmap">{ "imports": {+ "three": "https://cdn.jsdelivr.net/npm/[email protected]/build/three.module.min.js",+ "three/addons/": "https://cdn.jsdelivr.net/npm/[email protected]/examples/jsm/"+} }</script>+</head><body><canvas id="c"></canvas>+<script type="module">+// three.js starter for real 3D: a model (GLB/glTF) or a placeholder box on a shadow floor, one continuous camera,+// and a 2D title drawn over it. three.js draws into its own WebGL canvas, which is copied onto canvas #c, so #c is+// an ordinary 2D canvas like in every other scene and 2D overlays use the same code as the 2D template.+// Everything is a function of t: model animations go through mixer.setTime(t), never a THREE.Clock.+// Page contract: renderAt(t), TOTAL, ready, ?t=, ?scale=. three.js comes from the CDN, so a render needs the network.+import * as THREE from 'three';+import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';+import { RoomEnvironment } from 'three/addons/environments/RoomEnvironment.js';+import { RoundedBoxGeometry } from 'three/addons/geometries/RoundedBoxGeometry.js';++const W = 1920, H = 1080, END = 6, q = new URLSearchParams(location.search), SCALE = parseFloat(q.get('scale') || '1');+const MODEL = ''; // a .glb or .gltf next to the page, e.g. 'models/product.glb'; empty = the placeholder box+const SUB = 1, SHUTTER = 0.5 / 30; // sub-frames per frame; 8 to 12 average into motion blur on fast moves (costs SUB renders)+const cv = document.querySelector('#c'), ctx = cv.getContext('2d');+cv.width = Math.round(W * SCALE); cv.height = Math.round(H * SCALE);+const clamp01 = v => Math.min(1, Math.max(0, v));+const lerp = (a, b, k) => a + (b - a) * k;+const prog = (t, from, to) => clamp01((t - from) / (to - from));+const outExpo = k => (k = clamp01(k)) >= 1 ? 1 : 1 - Math.pow(2, -10 * k), outCubic = k => 1 - Math.pow(1 - clamp01(k), 3);+const sine = k => 0.5 - 0.5 * Math.cos(Math.PI * clamp01(k));++// ---- the 3D world ----+const gl = new THREE.WebGLRenderer({ antialias: true });+gl.setPixelRatio(1); gl.setSize(cv.width, cv.height, false);+gl.toneMapping = THREE.ACESFilmicToneMapping; gl.outputColorSpace = THREE.SRGBColorSpace;+gl.shadowMap.enabled = true; gl.shadowMap.type = THREE.PCFShadowMap; // three 0.186 removed PCFSoftShadowMap and falls back to this with a warning+const scene = new THREE.Scene(); scene.background = new THREE.Color('#0b0d10');+scene.environment = new THREE.PMREMGenerator(gl).fromScene(new RoomEnvironment(), 0.04).texture; // soft studio light+const key = new THREE.DirectionalLight('#ffffff', 2.4); key.position.set(3, 6, 4); key.castShadow = true;+key.shadow.mapSize.set(2048, 2048); Object.assign(key.shadow.camera, { left: -3, right: 3, top: 3, bottom: -3, near: 1, far: 20 }); key.shadow.radius = 6;+scene.add(key);+const floor = new THREE.Mesh(new THREE.PlaneGeometry(40, 40), new THREE.ShadowMaterial({ opacity: 0.32 }));+floor.rotation.x = -Math.PI / 2; floor.receiveShadow = true; scene.add(floor);+const cam = new THREE.PerspectiveCamera(30, W / H, 0.1, 100);+const rig = new THREE.Group(); scene.add(rig); // the hero turns and rises inside this; the model itself stays as loaded+let mixer = null;++async function load() {+ let hero;+ if (!MODEL) {+ hero = new THREE.Mesh(new RoundedBoxGeometry(1.1, 1.6, 0.45, 6, 0.12), new THREE.MeshPhysicalMaterial({ color: '#4E3BFF', roughness: 0.28, clearcoat: 1, clearcoatRoughness: 0.15 }));+ } else {+ const gltf = await new GLTFLoader().loadAsync(MODEL);+ hero = gltf.scene;+ if (gltf.animations.length) { mixer = new THREE.AnimationMixer(hero); for (const clip of gltf.animations) mixer.clipAction(clip).play(); }+ }+ hero.traverse(o => { if (o.isMesh) o.castShadow = true; });+ if (mixer) mixer.setTime(0); // measure the model in its first pose+ const box = new THREE.Box3().setFromObject(hero), size = box.getSize(new THREE.Vector3()); // fit to 1.6 units, standing on the floor+ hero.scale.multiplyScalar(1.6 / Math.max(size.x, size.y, size.z)); box.setFromObject(hero);+ hero.position.sub(new THREE.Vector3((box.min.x + box.max.x) / 2, box.min.y, (box.min.z + box.max.z) / 2));+ rig.add(hero);+}++function pose(t) { // ONE continuous camera: a push in that slows down, while the orbit only ever turns one way+ rig.rotation.y = lerp(-0.7, 0.45, sine(prog(t, 0, END)));+ rig.position.y = lerp(-0.25, 0, outExpo(prog(t, 0, 1.4)));+ if (mixer) mixer.setTime(t);+ const d = lerp(7.5, 5.2, outExpo(prog(t, 0, 2.2))), th = lerp(0.35, -0.15, sine(prog(t, 0, END)));+ cam.position.set(d * Math.sin(th), lerp(1.9, 1.25, sine(prog(t, 0, END))), d * Math.cos(th));+ cam.lookAt(0, 0.55, 0); // below the hero's middle, so it sits high and leaves room for the title+}++// ---- 2D over the 3D, in frame pixels ----+function swipeWords(text, t, at = 0.6, { y = 990, size = 84, colour = '#fff', gap = 0.08, rise = 0.34 } = {}) { // words rise from behind a mask+ ctx.save();+ ctx.font = `600 ${size}px Head, system-ui, sans-serif`; ctx.letterSpacing = `${-0.03 * size}px`;+ const words = text.split(' '), widths = words.map(w => ctx.measureText(w).width), space = ctx.measureText(' ').width;+ let x = (W - widths.reduce((a, b) => a + b, 0) - space * (words.length - 1)) / 2;+ words.forEach((word, n) => {+ const k = outCubic(prog(t, at + n * gap, at + n * gap + rise));+ if (k > 0) {+ ctx.save(); ctx.beginPath(); ctx.rect(x - 10, y - size * 1.1, widths[n] + 20, size * 1.45); ctx.clip();+ ctx.fillStyle = colour; ctx.fillText(word, x, y + (1 - k) * size * 1.25); ctx.restore();+ }+ x += widths[n] + space;+ });+ ctx.restore();+}++function render(t) {+ ctx.setTransform(1, 0, 0, 1, 0, 0);+ for (let i = 0; i < SUB; i++) { // with SUB 1 this is one plain render; more sub-frames are averaged with alpha 1/(i+1)+ pose(SUB > 1 ? Math.max(0, Math.min(END, t + (i / (SUB - 1) - 0.5) * SHUTTER)) : t);+ gl.render(scene, cam); ctx.globalAlpha = 1 / (i + 1); ctx.drawImage(gl.domElement, 0, 0);+ }+ ctx.globalAlpha = 1; ctx.setTransform(SCALE, 0, 0, SCALE, 0, 0);+ swipeWords('Your product, in 3D.', t);+}++window.TOTAL = END;+window.renderAt = render;+window.ready = Promise.all([load(), document.fonts.load('600 84px Head').catch(() => {})]).then(() => {+ // Opened by hand, the page plays on a loop. In the render and inside the viewer (an iframe), only renderAt draws.+ if (q.has('t') || window.top !== window) render(parseFloat(q.get('t') || '0')); else (function tick(n) { render((n / 1000) % END); requestAnimationFrame(tick); })(0);+ return true;+});+</script></body></html>diff --git a/src/chrome.js b/src/chrome.jsnew file mode 100644index 0000000..a58e1d5--- /dev/null+++ b/src/chrome.js@@ -0,0 +1,116 @@+// Launches headless Chrome on the real GPU and talks to it over the DevTools protocol (no dependency: Node's WebSocket).+import { spawn } from 'node:child_process';+import { existsSync, mkdtempSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';++const CANDIDATES = [+ 'C:/Program Files/Google/Chrome/Application/chrome.exe',+ 'C:/Program Files (x86)/Google/Chrome/Application/chrome.exe',+ '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',+ '/Applications/Chromium.app/Contents/MacOS/Chromium',+ '/usr/bin/google-chrome', '/usr/bin/chromium', '/usr/bin/chromium-browser',+];++export function findChrome(explicit) {+ const path = explicit || process.env.CHROME || CANDIDATES.find(p => existsSync(p));+ if (!path || !existsSync(path)) throw new Error('Chrome not found. Pass --chrome <path> or set CHROME=/path/to/chrome');+ return path;+}++// --force_high_performance_gpu matters on dual-GPU laptops: without it headless Chrome draws on the integrated GPU.+export const GPU_FLAGS = ['--enable-gpu', '--force_high_performance_gpu', ...(process.platform === 'darwin' ? ['--use-angle=metal'] : [])];++const live = new Set();+process.on('exit', () => { for (const c of live) c.killSync(); });++export async function launchChrome({ chromePath, extraArgs = [] }) {+ const profile = mkdtempSync(join(tmpdir(), 'motlab-chrome-'));+ const proc = spawn(chromePath, [+ '--headless=new', ...GPU_FLAGS,+ '--remote-debugging-port=0', `--user-data-dir=${profile}`,+ '--no-first-run', '--no-default-browser-check', '--hide-scrollbars', '--mute-audio',+ '--disable-background-timer-throttling', '--disable-renderer-backgrounding', '--disable-backgrounding-occluded-windows',+ '--window-size=1920,1080', ...extraArgs, 'about:blank',+ ], { stdio: ['ignore', 'ignore', 'pipe'] });++ const wsUrl = await new Promise((ok, no) => {+ let err = '';+ const timer = setTimeout(() => no(new Error('Chrome did not open a DevTools port within 30 s')), 30000);+ proc.stderr.on('data', d => { // keep draining stderr for the whole run so the pipe never fills+ if (err.length < 20000) err += d;+ const m = /DevTools listening on (ws:\/\/\S+)/.exec(err);+ if (m) { clearTimeout(timer); ok(m[1]); }+ });+ proc.once('exit', code => { clearTimeout(timer); no(new Error(`Chrome exited early (code ${code}): ${err.slice(0, 400)}`)); });+ proc.once('error', e => { clearTimeout(timer); no(e); });+ });++ const ws = new WebSocket(wsUrl);+ await new Promise((ok, no) => { ws.onopen = ok; ws.onerror = () => no(new Error('could not connect to Chrome DevTools')); });++ let nextId = 0, closed = false;+ const pending = new Map(), listeners = new Map();+ ws.onmessage = e => {+ const m = JSON.parse(e.data);+ if (m.id !== undefined) {+ const p = pending.get(m.id); if (!p) return; pending.delete(m.id);+ if (m.error) p.no(new Error(`${p.method}: ${m.error.message}`)); else p.ok(m.result);+ } else for (const fn of listeners.get(m.method) || []) fn(m.params, m.sessionId);+ };+ ws.onclose = () => { closed = true; for (const p of pending.values()) p.no(new Error('Chrome connection closed')); pending.clear(); };++ const send = (method, params = {}, sessionId) => new Promise((ok, no) => {+ if (closed) return no(new Error('Chrome connection closed'));+ const id = ++nextId; pending.set(id, { ok, no, method });+ ws.send(JSON.stringify({ id, method, params, ...(sessionId ? { sessionId } : {}) }));+ });+ const on = (event, fn) => { if (!listeners.has(event)) listeners.set(event, []); listeners.get(event).push(fn); };++ const chrome = {+ send, on,+ killSync() { try { proc.kill(); } catch {} try { rmSync(profile, { recursive: true, force: true, maxRetries: 5, retryDelay: 200 }); } catch {} },+ async close() {+ live.delete(chrome);+ if (proc.exitCode !== null || proc.signalCode !== null) return chrome.killSync();+ const gone = new Promise(r => proc.once('exit', r));+ try { await Promise.race([send('Browser.close'), new Promise(r => setTimeout(r, 2000))]); } catch {}+ await Promise.race([gone, new Promise(r => setTimeout(r, 3000))]);+ chrome.killSync();+ },+ };+ live.add(chrome);+ chrome.version = (await send('Browser.getVersion')).product;+ return chrome;+}++// One page (tab) in a Chrome process: evaluate code in it and receive the messages the in-page runtime emits.+export async function attachPage(chrome) {+ const { targetInfos } = await chrome.send('Target.getTargets');+ const target = targetInfos.find(t => t.type === 'page');+ if (!target) throw new Error('Chrome has no page target');+ const { sessionId } = await chrome.send('Target.attachToTarget', { targetId: target.targetId, flatten: true });+ const send = (method, params) => chrome.send(method, params, sessionId);++ const errors = [], emitHandlers = [];+ // A SyntaxError's description names no file, so the file and line are added from the exception details.+ const where = d => d.url ? ` (${decodeURIComponent(new URL(d.url).pathname)}:${d.lineNumber + 1}:${d.columnNumber + 1})` : '';+ chrome.on('Runtime.exceptionThrown', (p, sid) => {+ if (sid !== sessionId) return;+ const d = p.exceptionDetails, text = d.exception?.description || d.text, place = where(d);+ errors.push(place && !text.includes(place.slice(2, -1)) ? text + place : text);+ });+ chrome.on('Runtime.bindingCalled', (p, sid) => {+ if (sid !== sessionId || p.name !== '__motlabEmit') return;+ let msg; try { msg = JSON.parse(p.payload); } catch { return; }+ for (const fn of emitHandlers) fn(msg);+ });+ await send('Page.enable'); await send('Runtime.enable'); await send('Runtime.addBinding', { name: '__motlabEmit' });++ const evaluate = async expression => {+ const r = await send('Runtime.evaluate', { expression, awaitPromise: true, returnByValue: true });+ if (r.exceptionDetails) throw new Error(r.exceptionDetails.exception?.description || r.exceptionDetails.text || 'page error');+ return r.result.value;+ };+ return { send, evaluate, errors, onEmit: fn => emitHandlers.push(fn), navigate: url => send('Page.navigate', { url }) };+}diff --git a/src/cli.js b/src/cli.jsnew file mode 100644index 0000000..cbb7a40--- /dev/null+++ b/src/cli.js@@ -0,0 +1,94 @@+import { fileURLToPath } from 'node:url';+import { parseArgs } from 'node:util';+import { doctor } from './doctor.js';+import { startEditor } from './editor.js';+import { renderProject } from './project.js';+import { dumpEvents, renderStills, renderVideo } from './render.js';+import { uninstall } from './uninstall.js';+import { update } from './update.js';+import { openInViewer, restartViewer, startViewer, stopViewer } from './viewer.js';++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] all scenes and audio in project.json, as one MP4+ motlab start the viewer in the background at http://127.0.0.1:4173, for every+ project; the menu lists the projects in this folder+ motlab edit [project] open a project in the viewer (starting it if needed) and print its+ address. [project] is a folder with project.json, or a project+ file in it (video/storyboard.json). Clicks go to selection.json+ motlab stop | restart end the viewer, or start it again from the same folder+ 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 update [--dry-run] the newest motlab from GitHub, its npm packages, and the skills+ copied again to every agent folder they were installed in+ motlab uninstall [--dry-run] [--yes] remove the command, the skills, ~/.motlab and the encoder cache+ (it lists them and asks first; the clone folder is left)++ --fps frames per second (default 24)+ --scale passed to the page as ?scale=; 2 turns a 1920x1080 page into 4K (default 2 for video, 1 for stills)+ --audio audio file to mux in (AAC 320k); the result is cut to the video length+ --encoder auto = fastest encoder with constant quality in the saved probe for this machine and size,+ hw = fastest hardware encoder, sw = software (fastest at 1080p, but its quality has a ceiling)+ --codec auto | h264 | hevc (default auto; H.264 is kept unless HEVC is clearly faster)+ --workers split the frames over N Chrome processes and join the parts with ffmpeg concat (default 1)+ --qp constant QP for encoders that support it (default 18 for H.264, 20 for HEVC; lower = better, larger)+ --bitrate use variable bitrate at this many Mbit/s instead of constant QP+ --mux auto | mediabunny | raw (auto tries Mediabunny, then raw bitstream + ffmpeg -c copy)+ --reprobe time the encoders again instead of using the saved probe+ --root folder to serve (default: the nearest folder above the page with a project.json, else the page's folder)+ --chrome path to Chrome (default: autodetect, or the CHROME environment variable)++Chrome always runs with --enable-gpu --force_high_performance_gpu (--gpu is accepted and ignored, so older commands+that pass it keep working). Needs ffmpeg and ffprobe on PATH.++Engine folder: ${fileURLToPath(new URL('..', import.meta.url))} (README.md, example/, src/page/footage.js)`;++const oneOf = (name, v, list) => { if (v !== undefined && !list.includes(v)) throw new Error(`--${name} must be one of: ${list.join(', ')}`); return v; };+const num = (name, v, { min = 0, int = false } = {}) => {+ if (v === undefined) return undefined;+ const n = Number(v);+ if (!Number.isFinite(n) || n < min || (int && !Number.isInteger(n))) throw new Error(`--${name}: "${v}" is not a valid value`);+ return n;+};++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' },+ 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 (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 === '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 }) });+ return 0;+ }+ if (!['stills', 'video', 'events'].includes(mode)) throw new Error(`unknown mode "${mode}" (render, start, edit, stop, restart, stills, video, events, doctor, update or uninstall)`);+ if (!page || !out) throw new Error(`${mode} needs a page and an output path`);+ const common = { page, root: v.root, chrome: v.chrome };++ if (mode === 'events') { await dumpEvents({ ...common, out }); return 0; }+ if (mode === 'stills') {+ const times = rest.map(t => num('time', t));+ if (!times.length) throw new Error('stills needs at least one time in seconds');+ await renderStills({ ...common, outDir: out, times, scale: num('scale', v.scale, { min: 0.01 }), format: oneOf('format', v.format, ['png', 'jpg']) });+ return 0;+ }+ if (rest.length) throw new Error(`unexpected arguments: ${rest.join(' ')}`);+ const bitrate = num('bitrate', v.bitrate, { min: 0.1 });+ await renderVideo({ ...common, out, audio: v.audio, fps: num('fps', v.fps, { min: 1 }), scale: num('scale', v.scale, { min: 0.01 }),+ workers: num('workers', v.workers, { min: 1, int: true }), bitrate: bitrate && bitrate * 1e6, qp: num('qp', v.qp, { min: 0, int: true }), reprobe: v.reprobe,+ encoder: oneOf('encoder', v.encoder, ['auto', 'hw', 'sw']), codec: oneOf('codec', v.codec, ['auto', 'h264', 'hevc']), mux: oneOf('mux', v.mux, ['auto', 'mediabunny', 'raw']) });+ return 0;+}diff --git a/src/codecs.js b/src/codecs.jsnew file mode 100644index 0000000..1556541--- /dev/null+++ b/src/codecs.js@@ -0,0 +1,47 @@+// Codec strings, default bitrates and frame splitting. Pure functions, shared by the probe and the renderer.++// [level_idc, max frame size in macroblocks, max macroblocks per second, max bitrate in kbit/s for High profile]+const AVC_LEVELS = [+ [40, 8192, 245760, 25000], [41, 8192, 245760, 62500], [42, 8704, 522240, 62500],+ [50, 22080, 589824, 168750], [51, 36864, 983040, 300000], [52, 36864, 2073600, 300000],+ [60, 139264, 4177920, 300000], [61, 139264, 8355840, 600000], [62, 139264, 16711680, 1000000],+];+// [level_idc, max luma picture size, max luma sample rate, max bitrate in kbit/s for Main tier, same for High tier]+const HEVC_LEVELS = [+ [120, 2228224, 66846720, 12000, 30000], [123, 2228224, 133693440, 20000, 50000],+ [150, 8912896, 267386880, 25000, 100000], [153, 8912896, 534773760, 40000, 160000], [156, 8912896, 1069547520, 60000, 240000],+ [180, 35651584, 1069547520, 60000, 240000], [183, 35651584, 2139095040, 120000, 480000], [186, 35651584, 4278190080, 240000, 800000],+];++export function codecString(codec, width, height, fps, bitrate) {+ const kbps = bitrate / 1000;+ if (codec === 'h264') {+ const mbs = Math.ceil(width / 16) * Math.ceil(height / 16);+ const level = AVC_LEVELS.find(([, fs, mbps, br]) => mbs <= fs && mbs * fps <= mbps && kbps <= br) || AVC_LEVELS.at(-1);+ return 'avc1.6400' + level[0].toString(16).padStart(2, '0'); // High profile+ }+ if (codec === 'hevc') {+ const px = width * height;+ const level = HEVC_LEVELS.find(([, ps, sr, , high]) => px <= ps && px * fps <= sr && kbps <= high) || HEVC_LEVELS.at(-1);+ return `hvc1.1.6.${kbps <= level[3] ? 'L' : 'H'}${level[0]}.B0`; // Main profile, Main or High tier+ }+ throw new Error(`unknown codec ${codec}`);+}++// Default variable-bitrate target, for encoders without a constant QP mode. It also decides the level in the codec+// string. Chrome's software H.264 encoder stops spending bits well below this on flat motion graphics, so in+// practice it is a ceiling.+export function defaultBitrate(codec, width, height, fps) {+ const base = codec === 'hevc' ? 14e6 : 24e6; // at 1920x1080, 30 fps+ const bps = base * Math.pow((width * height) / (1920 * 1080), 0.75) * Math.sqrt(fps / 30);+ return Math.round(bps / 1e5) * 1e5;+}++// Split frames [0, n) into contiguous ranges, one per worker.+export function splitFrames(n, workers) {+ const w = Math.max(1, Math.min(workers, n)), out = [];+ for (let i = 0; i < w; i++) out.push({ start: Math.floor((i * n) / w), end: Math.floor(((i + 1) * n) / w) });+ return out;+}++export const frameCount = (total, fps) => Math.round(total * fps);diff --git a/src/doctor.js b/src/doctor.jsnew file mode 100644index 0000000..6351618--- /dev/null+++ b/src/doctor.js@@ -0,0 +1,54 @@+// `motlab doctor`: checks what the engine and the skill need on this machine and says how to get what is missing.+// It never installs anything. The installer (install.js) runs the same checks.+import { spawnSync } from 'node:child_process';+import { existsSync } from 'node:fs';+import { findChrome } from './chrome.js';++const run = (cmd, args) => {+ const r = spawnSync(cmd, args, { encoding: 'utf8', shell: false });+ return r.status === 0 ? (r.stdout || r.stderr).trim() : null;+};+const firstLine = s => s && s.split('\n')[0].trim();++const HINTS = {+ win32: { ffmpeg: 'winget install Gyan.FFmpeg', chrome: 'winget install Google.Chrome', python: 'winget install Python.Python.3.12' },+ darwin: { ffmpeg: 'brew install ffmpeg', chrome: 'brew install --cask google-chrome', python: 'brew install python' },+ linux: { ffmpeg: 'sudo apt install ffmpeg', chrome: 'install Google Chrome or Chromium from your distribution', python: 'sudo apt install python3 python3-pip' },+};++// Each check: { name, ok, detail, fix, optional }. Required checks decide the exit code.+export function checks() {+ const hint = HINTS[process.platform] || HINTS.linux, out = [];+ const major = Number(process.versions.node.split('.')[0]);+ out.push({ name: 'Node.js 24 or newer', ok: major >= 24, detail: process.version, fix: 'install Node 24 from https://nodejs.org or with nvm' });++ let chrome = null; try { chrome = findChrome(); } catch {}+ out.push({ name: 'Google Chrome or Chromium', ok: !!chrome, detail: chrome || 'not found', fix: `${hint.chrome}, or set CHROME=/path/to/chrome` });++ for (const tool of ['ffmpeg', 'ffprobe']) {+ const v = firstLine(run(tool, ['-version']));+ out.push({ name: tool, ok: !!v, detail: v ? v.replace(/ Copyright.*/, '') : 'not on PATH', fix: hint.ffmpeg });+ }+ out.push({ name: 'npm packages (mediabunny)', ok: existsSync(new URL('../node_modules/mediabunny/package.json', import.meta.url)), detail: '', fix: 'run npm ci in the engine folder' });++ // Python is only for the skill's helper scripts (contact sheets, sound effects, mixing, fonts).+ const py = ['python3', 'python'].map(p => ({ p, v: firstLine(run(p, ['--version'])) })).find(x => x.v && /Python 3/.test(x.v));+ out.push({ name: 'Python 3 (skill scripts)', ok: !!py, optional: true, detail: py ? `${py.p}: ${py.v}` : 'not found', fix: hint.python });+ if (py) {+ const missing = ['numpy', 'scipy', 'PIL'].filter(m => run(py.p, ['-c', `import ${m}`]) === null);+ 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 skills/motlab/requirements.txt` });+ }+ return out;+}++export function doctor(log = console.log) {+ const list = checks();+ for (const c of list) {+ log(`${c.ok ? 'ok ' : c.optional ? 'warn' : 'FAIL'} ${c.name}${c.detail ? ` (${c.detail})` : ''}`);+ if (!c.ok) log(` fix: ${c.fix}`);+ }+ const failed = list.filter(c => !c.ok && !c.optional);+ log(failed.length ? `\n${failed.length} required check(s) failed.` : '\nReady. The GPU in use is printed at the start of every render.');+ return failed.length ? 1 : 0;+}diff --git a/src/editor.html b/src/editor.htmlnew file mode 100644index 0000000..eb46ea9--- /dev/null+++ b/src/editor.html@@ -0,0 +1,1264 @@+<!doctype html>+<html lang="id"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>{{name}} / {{version}} · motlab</title>+<link rel="preconnect" href="https://fonts.googleapis.com"><link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>+<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;500;600&display=swap">+<style>+ /* Design notes are in DESIGN.md. Muted text and waveform colours were picked with the contrast checker against every background they sit on. */+ :root { --line: #e6e6e4; --edge: #dcdcda; --canvas: #ececec; --text: #1f1f1e; --muted: #666561; --hover: #f4f4f3; --press: #e4e4e2; --sel: #ebebea; --blue: #2c6fe0; --blue-bg: #dfe9fb; --red: #b8322a; --red-bg: #fbe4e2;+ --font: "Plus Jakarta Sans", ui-sans-serif, system-ui, "Segoe UI", sans-serif; --side: clamp(260px, 24.5vw, 468px);+ --ease: cubic-bezier(.2, .8, .2, 1); --fast: .14s; --slide: .26s; }+ * { box-sizing: border-box; margin: 0; }+ [hidden]:not(.menu, .toast, #tip) { display: none !important; }+ html, body { height: 100%; }+ body { display: grid; grid-template: 44px minmax(0, 1fr) / var(--side) minmax(0, 1fr); transition: grid-template-columns var(--slide) var(--ease); font: 14px/1.4 var(--font); color: var(--text); background: #fff; -webkit-font-smoothing: antialiased; user-select: none; }+ body.closed { grid-template-columns: 0 minmax(0, 1fr); }+ body.still, body.still * { transition: none !important; } /* no animation for the state the page opens in */+ button { font: inherit; color: inherit; border: 0; background: none; cursor: pointer; }+ button:disabled { cursor: not-allowed; opacity: .45; }+ svg { display: block; flex: none; }+ .muted { color: var(--muted); }+ .num { font-variant-numeric: tabular-nums; }++ /* one header across both panes, like the Claude app header: panel toggle, project / scene in the middle, Export */+ header { grid-column: 1 / -1; display: grid; grid-template-columns: 1fr minmax(0, auto) 1fr; align-items: center; gap: 12px; padding: 0 10px; border-bottom: .5px solid #ececeb; white-space: nowrap; }+ .crumb { display: flex; align-items: center; gap: 4px; min-width: 0; font-size: 14px; }+ .crumb h1 { font: inherit; min-width: 0; }+ .crumb .wrap { min-width: 0; }+ /* a crumb that opens a menu: the project, and later its version */+ .pick { display: flex; align-items: center; gap: 2px; max-width: 100%; height: 28px; padding: 0 4px 0 8px; border-radius: 6px; color: var(--muted); }+ .pick .nm { overflow: hidden; text-overflow: ellipsis; }+ .pick:hover, .pick.open { background: var(--hover); color: var(--text); }+ .crumb .sep { color: #c9c9c7; }+ #crumb { overflow: hidden; text-overflow: ellipsis; }+ .sep:has(+ #crumb:empty) { display: none; }+ header .wrap { justify-self: end; }+ .icon { display: grid; place-items: center; width: 28px; height: 28px; border-radius: 6px; }+ .btn { display: flex; align-items: center; gap: 6px; height: 30px; padding: 0 10px; border-radius: 8px; font-weight: 500; }+ .icon:hover, .btn:hover, .btn.open, #panel[aria-expanded="true"] { background: var(--hover); }+ .wrap { position: relative; }++ /* left pane */+ /* the panel keeps its width and the column around it slides, so the list does not reflow while it opens or closes */+ aside { display: flex; flex-direction: column; min-width: 0; min-height: 0; overflow: hidden; box-shadow: inset -1px 0 var(--line); background: #fff; transition: visibility 0s, opacity var(--slide) var(--ease); }+ aside > * { width: var(--side); flex-shrink: 0; }+ aside > nav { flex-shrink: 1; }+ body.closed aside { visibility: hidden; opacity: 0; transition: visibility 0s var(--slide), opacity var(--slide) var(--ease); }+ #lists { flex: 1; min-height: 0; overflow-y: auto; padding: 6px 10px 12px; }+ h2 { font-size: 12px; font-weight: 500; color: var(--muted); padding: 14px 10px 6px; }+ ol, ul { list-style: none; padding: 0; }+ .row { display: flex; align-items: center; gap: 10px; width: 100%; padding: 6px 10px; border-radius: 8px; text-align: left; }+ .row:hover { background: var(--hover); }+ .row[aria-current] { background: var(--sel); }+ .row[aria-current] .name { font-weight: 500; }+ .row canvas, .row .ic { flex: none; height: 34px; border-radius: 5px; background: #f0f0ee; box-shadow: 0 0 0 1px rgba(0,0,0,.06); }+ .row .ic { display: grid; place-items: center; width: 34px; color: var(--muted); }+ .row .name { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }+ .row small { display: block; font-size: 12px; font-weight: 400; color: var(--muted); }+ .row .d { font-size: 12px; color: var(--muted); }+ .empty { padding: 6px 10px; font-size: 13px; color: var(--muted); }+ #sel { padding: 12px 20px 14px; }+ #sel b { display: block; font-weight: 500; }+ #sel small { display: block; font-size: 12px; color: var(--muted); }++ /* canvas pane */+ main { grid-area: 2 / 2; display: flex; flex-direction: column; min-width: 0; min-height: 0; }+ aside { grid-area: 2 / 1; }+ #canvas { position: relative; flex: 1; min-height: 0; display: flex; flex-direction: column; background: var(--canvas); overflow-y: auto; }+ .pill { display: flex; align-items: center; gap: 2px; height: 36px; padding: 0 4px; background: #fff; border: 1px solid var(--edge); border-radius: 10px; box-shadow: 0 1px 2px rgba(0,0,0,.04); }+ .pill button { display: flex; align-items: center; gap: 4px; height: 28px; padding: 0 8px; border-radius: 6px; }+ .pill button:hover { background: var(--hover); }+ .pill .sq { width: 30px; padding: 0; justify-content: center; }+ .pill .hot { background: var(--blue-bg); color: var(--blue); }+ .pill .hot:hover { background: #d3e1fa; }+ #pillFull { position: absolute; top: 12px; right: 12px; z-index: 2; }+ #stage { flex: 1; min-height: 150px; display: grid; grid-template: minmax(0, 1fr) / minmax(0, 1fr); place-items: center; padding: 60px 24px 14px; font-size: 13px; color: var(--muted); }+ #msg { max-width: 46ch; text-align: center; user-select: text; }+ #stage { position: relative; }+ #stage:fullscreen { padding: 0; background: #111; }+ /* notes on the preview, after the Claude canvas selection box: a 1 px blue line and a light blue fill, square+ corners, and the note's number in a small blue tag above the top left corner */+ #marks { position: absolute; inset: 0; pointer-events: none; }+ .mk { position: absolute; border: 1px solid var(--blue); background: rgba(44,111,224,.14); }+ .mk.on { background: rgba(44,111,224,.22); }+ .mk.point { border-radius: 50%; }+ .mk.point::after { content: ""; position: absolute; inset: 0; margin: auto; width: 5px; height: 5px; border-radius: 50%; background: var(--blue); }+ .mk i, .tag { min-width: 16px; height: 16px; padding: 0 5px; border-radius: 4px; background: var(--blue); color: #fff; font: 600 11px/16px var(--font); font-style: normal; text-align: center; font-variant-numeric: tabular-nums; }+ .mk i { position: absolute; left: -1px; bottom: calc(100% + 2px); }+ .mk.point i { left: calc(100% + 1px); bottom: calc(100% + 1px); }+ /* the note being written: a card like the menus, under the box (above it when there is no room) */+ .pop { position: fixed; z-index: 20; width: 288px; max-width: calc(100vw - 24px); padding: 8px; background: #fff; border: 1px solid var(--edge); border-radius: 12px; box-shadow: 0 8px 28px rgba(0,0,0,.12); color: var(--text); font-size: 13px; }+ .pop .head { display: flex; align-items: center; gap: 8px; padding: 2px 2px 8px; font-size: 12px; color: var(--muted); }+ #popText { display: block; width: 100%; min-height: 60px; max-height: 160px; padding: 8px 10px; border: 1px solid var(--edge); border-radius: 8px; font: inherit; font-size: 13px; line-height: 1.45; color: var(--text); background: #fff; resize: none; user-select: text; }+ #popText::placeholder { color: var(--muted); }+ #popText:focus-visible { outline: 2px solid var(--blue); outline-offset: -1px; }+ .pop .foot2 { display: flex; justify-content: space-between; gap: 6px; margin-top: 8px; }+ #popDel, #popOk { height: 30px; padding: 0 12px; border-radius: 8px; font-size: 13px; font-weight: 500; }+ #popDel { color: var(--muted); }+ #popDel:hover { background: var(--hover); color: var(--text); }+ #popOk { background: var(--text); color: #fff; }+ #popOk:active { background: #000; }+ .row .ic.n { font-size: 13px; font-weight: 600; color: var(--text); }+ .row .none { color: var(--muted); }+ /* done notes: folded under "Selesai" (Done) at the end of the list, muted and struck through, and off the preview and the+ timeline unless one is open */+ #doneBtn { color: var(--muted); font-size: 13px; }+ #doneBtn .ic { background: none; box-shadow: none; }+ #doneBtn svg { transition: rotate var(--fast) var(--ease); }+ #doneBtn[aria-expanded="true"] svg { rotate: 180deg; }+ .row.done .ic.n, .row.done .name > span { color: var(--muted); }+ .row.done .name > span { text-decoration: line-through; text-decoration-color: rgba(0,0,0,.3); }+ #popState { display: flex; align-items: center; gap: 4px; margin-left: auto; }+ #popState svg { width: 14px; height: 14px; }+ .pop .foot2 span { flex: none; display: flex; gap: 6px; }+ #popDone { display: flex; align-items: center; gap: 6px; height: 30px; padding: 0 10px; white-space: nowrap; border-radius: 8px; font-size: 13px; font-weight: 500; color: var(--text); }+ #popDone:hover { background: var(--hover); }+ #popDone svg { width: 14px; height: 14px; }+ /* the + cursor is dark over light parts of the frame and light over dark parts (.on-dark, set from the frame's pixels),+ with a faint halo in the other colour for edges between the two */+ #view { cursor: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24'%3E%3Cpath d='M12 3v18M3 12h18' stroke='%23fff' stroke-opacity='.4' stroke-width='3.5'/%3E%3Cpath d='M12 3v18M3 12h18' stroke='%231f1f1e' stroke-width='1.5'/%3E%3C/svg%3E") 12 12, crosshair; }+ #view.on-dark { cursor: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24'%3E%3Cpath d='M12 3v18M3 12h18' stroke='%23000' stroke-opacity='.4' stroke-width='3.5'/%3E%3Cpath d='M12 3v18M3 12h18' stroke='%23fff' stroke-width='1.5'/%3E%3C/svg%3E") 12 12, crosshair; }+ #view { max-width: 100%; max-height: 100%; touch-action: none; background: #fff; border-radius: 3px; box-shadow: 0 0 0 1px rgba(0,0,0,.06), 0 2px 10px rgba(0,0,0,.06); }+ #stage:fullscreen #view { border-radius: 0; box-shadow: none; }+ #bar { flex: none; display: flex; flex-wrap: wrap; justify-content: center; gap: 8px; padding: 0 12px; margin-bottom: 10px; }+ #tools, #rangeBar { height: 40px; padding: 0 6px; border-radius: 12px; }+ /* with a range: what it covers and what can be done with it, next to the play toolbar */+ #rangeBar { gap: 4px; padding-left: 10px; font-size: 13px; }+ #rangeBar .ri { color: var(--blue); }+ #rangeText { display: flex; align-items: center; gap: 8px; padding: 0 6px 0 4px; white-space: nowrap; }+ #rangeText .dv { width: 1px; height: 16px; background: var(--line); }+ /* a range as "00:03.00 [arrow] 00:06.50"; screen readers hear "sampai" or "to" */+ .rg { display: inline-flex; align-items: center; gap: 4px; height: 1lh; vertical-align: top; } /* one line high, so the icon sits on the text's middle */+ .rg svg { width: 12px; height: 12px; color: var(--muted); }+ /* inside a line of small text the digits' middle sits 0.9 px above the line's middle (Plus Jakarta Sans 12 px, measured) */+ small .rg svg, #popWhere .rg svg { translate: 0 -.075em; }+ .sr { position: absolute; width: 1px; height: 1px; overflow: hidden; clip-path: inset(50%); white-space: nowrap; }+ /* phones: the toolbars keep to the essentials so they fit; the timeline fits the width there anyway */+ @media (max-width: 479px) { #time .muted, #rangeText .muted, #rangeText .dv, #zin, #zout { display: none; } }+ /* tooltips: a small dark label after a short hover, with the shortcut in a key cap; the timeline's lists its keys */+ #tip { position: fixed; z-index: 40; max-width: 280px; padding: 6px 8px; border-radius: 8px; background: var(--text); color: #fff; font-size: 12px; line-height: 1.4; box-shadow: 0 4px 14px rgba(0,0,0,.18); pointer-events: none; transition: opacity var(--fast) var(--ease), translate var(--fast) var(--ease), display var(--fast) allow-discrete; }+ #tip[hidden] { display: none; opacity: 0; }+ @starting-style { #tip:not([hidden]) { opacity: 0; translate: 0 2px; } }+ #tip .line { display: flex; align-items: center; gap: 8px; }+ #tip kbd { display: inline-block; min-width: 18px; height: 18px; padding: 0 5px; border-radius: 4px; background: rgba(255,255,255,.16); font: 500 11px/18px var(--font); text-align: center; }+ #tip .keys { display: grid; grid-template-columns: auto 1fr; gap: 5px 12px; align-items: center; }+ #tip .keys span:first-child, #tip .keys .k { white-space: nowrap; }+ #tip .dim { color: rgba(255,255,255,.7); }+ #time { padding: 0 10px 0 12px; font-size: 13px; }+ #lane { max-height: 35vh; margin: 0 12px 12px; background: #fff; border: 1px solid var(--edge); border-radius: 12px; box-shadow: 0 1px 2px rgba(0,0,0,.04); overflow: auto; }+ #laneIn { position: relative; }+ #tl { position: sticky; left: 0; display: block; width: 100%; height: 144px; cursor: pointer; }+ #tl:focus-visible { outline: 2px solid var(--blue); outline-offset: -2px; border-radius: 12px; }+ .mark { position: absolute; top: 4px; bottom: 6px; left: 20px; width: 2px; margin-left: -1px; background: var(--text); pointer-events: none; }+ .mark::before { content: ""; position: absolute; top: 0; left: -4px; width: 10px; height: 12px; border-radius: 3px 3px 5px 5px; background: inherit; }+ #pick { background: var(--blue); width: 1px; margin-left: 0; }+ #pick::before { display: none; }+ .toast { position: absolute; top: 56px; left: 50%; transform: translate(-50%, 0); transition: opacity var(--fast) var(--ease), transform var(--fast) var(--ease), display var(--fast) allow-discrete; z-index: 5; max-width: calc(100% - 24px); padding: 8px 12px; border-radius: 8px; background: var(--text); color: #fff; font-size: 13px; }++ /* menus */+ .menu { position: absolute; top: calc(100% + 6px); z-index: 10; min-width: 220px; padding: 6px; background: #fff; border: 1px solid var(--edge); border-radius: 12px; box-shadow: 0 8px 28px rgba(0,0,0,.12); font-weight: 400; }+ .menu { transform-origin: top right; transition: opacity var(--fast) var(--ease), transform var(--fast) var(--ease), display var(--fast) allow-discrete; }+ .menu[hidden], .toast[hidden] { display: none; opacity: 0; }+ .menu[hidden] { transform: translateY(-4px) scale(.98); }+ .toast[hidden] { transform: translate(-50%, -4px); }+ @starting-style { .menu:not([hidden]) { opacity: 0; transform: translateY(-4px) scale(.98); } .toast:not([hidden]) { opacity: 0; transform: translate(-50%, -4px); } }+ .menu.r { right: 0; }+ .menu.c { left: 50%; translate: -50% 0; transform-origin: top center; }+ #projMenu { width: 300px; max-width: calc(100vw - 24px); }+ #projList { max-height: min(60vh, 420px); overflow-y: auto; }+ .menu a.opt { color: inherit; text-decoration: none; }+ .menu .opt.two { flex-direction: column; align-items: flex-start; justify-content: center; gap: 1px; height: auto; min-height: 44px; padding: 6px 10px; }+ .opt.two span { max-width: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }+ .menu .foot { padding: 8px 10px 4px; font-size: 12px; color: var(--muted); white-space: normal; }+ .menu .foot:empty { display: none; }+ .menu .div { height: 1px; margin: 6px 4px; background: var(--line); }+ #verMenu { width: 260px; max-width: calc(100vw - 24px); }+ #verList { max-height: min(50vh, 320px); overflow-y: auto; }+ #verForm { display: flex; gap: 6px; padding: 4px; }+ #verName { flex: 1; min-width: 0; height: 32px; padding: 0 10px; border: 1px solid var(--edge); border-radius: 8px; font: inherit; font-size: 13px; color: var(--text); background: #fff; user-select: text; }+ #verName::placeholder { color: var(--muted); }+ #verName:focus-visible { outline: 2px solid var(--blue); outline-offset: -1px; }+ #verGo { height: 32px; padding: 0 12px; border-radius: 8px; font-size: 13px; font-weight: 500; background: var(--text); color: #fff; }+ #verGo:active:not(:disabled) { background: #000; }+ .menu h3 { font-size: 12px; font-weight: 500; color: var(--muted); padding: 6px 10px; }+ #exportMenu { width: 232px; }+ .menu .opt { display: flex; align-items: center; justify-content: space-between; width: 100%; height: 32px; padding: 0 10px; border-radius: 8px; font-size: 13px; text-align: left; }+ .menu .opt:hover { background: var(--hover); }+ .menu .opt.on { background: var(--sel); font-weight: 500; }+ .opt .dim { font-size: 12px; font-weight: 400; color: var(--muted); }+ .acts { display: flex; flex-direction: column; gap: 6px; margin-top: 6px; }+ #go, #stop { height: 34px; border-radius: 8px; font-size: 13px; font-weight: 500; }+ #go { display: flex; align-items: center; justify-content: center; gap: 8px; background: var(--text); color: #fff; }+ #go .spin { border-color: rgba(255,255,255,.3); border-top-color: #fff; } /* the button is faded like any disabled one while it loads */+ #stop { background: var(--red-bg); color: var(--red); } /* tinted like the blue pill button, not a solid fill */+ #stop:hover:not(:disabled) { background: #f8d9d6; }+ #xs { padding: 10px 10px 4px; font-size: 12px; color: var(--muted); user-select: text; }+ #xs .line { display: flex; justify-content: space-between; gap: 8px; color: var(--text); }+ #xs .sub { display: block; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }+ #xs .wrap { white-space: normal; }+ #xs a { color: var(--blue); text-decoration: none; font-weight: 500; }+ #xs a:hover { text-decoration: underline; }+ .spin { width: 14px; height: 14px; border: 1.5px solid var(--edge); border-top-color: var(--text); border-radius: 50%; animation: spin .8s linear infinite; }+ @keyframes spin { to { transform: rotate(360deg); } }+ #frames { position: fixed; left: -99999px; top: 0; visibility: hidden; }++ /* pressed state, after hover so it wins */+ .icon, .btn, .pick, .pill button, .row, .menu .opt, #go, #stop, #popDel, #popDone, #popOk { transition: background-color var(--fast) var(--ease), opacity var(--fast) var(--ease), transform var(--fast) var(--ease); }+ .icon:active, .pill .sq:active { transform: scale(.94); }+ .icon:active, .btn:active, .pick:active, #popDel:active, #popDone:active, .pill button:active, .row:active, .menu .opt:active { background: var(--press); }+ .pill .hot:active { background: #c7d8f8; }+ #go:active:not(:disabled) { background: #000; }+ #stop:active:not(:disabled) { background: #f4cdc9; }++ @media (prefers-reduced-motion: reduce) {+ *, *::before { transition-duration: 0s !important; transition-delay: 0s !important; }+ .spin { animation: none; border-color: var(--text); }+ }+ /* narrow windows: the panel floats over the canvas instead of squeezing it */+ @media (max-width: 719px) {+ body, body.closed { grid-template-columns: 0 minmax(0, 1fr); }+ aside { position: fixed; top: 44px; left: 0; bottom: 0; z-index: 30; width: min(320px, 85vw); box-shadow: 0 8px 28px rgba(0,0,0,.16); transition: visibility 0s, transform var(--slide) var(--ease); }+ aside > * { width: auto; }+ body.closed aside { opacity: 1; transform: translateX(-100%); transition: visibility 0s var(--slide), transform var(--slide) var(--ease); }+ }+ @media (pointer: coarse) {+ .icon, .btn, .pick, .pill button, .row, .menu .opt, #go, #stop, #verGo, #verName, #popDel, #popDone, #popOk { min-height: 44px; }+ .icon, .pill .sq { min-width: 44px; }+ .pill { height: auto; }+ }+</style></head>+<body class="still">+<header>+ <div><button class="icon" id="panel" data-i="panel" data-label="hidePanel" aria-expanded="true"></button></div>+ <div class="crumb">+ <div class="wrap"><h1><button class="pick" id="proj" data-i="down" aria-expanded="false" aria-controls="projMenu" data-t="data-tip=switchProject"><span class="nm">{{name}}</span></button></h1>+ <div class="menu c" id="projMenu" hidden><h3 data-t="projects"></h3><div id="projList"><p class="foot" data-t="loading"></p></div><p class="foot" id="projFoot"></p>+ <div class="div"></div><button class="opt" id="lang"><span></span><span class="dim"></span></button></div></div>+ <span class="sep" aria-hidden="true">/</span>+ <div class="wrap"><button class="pick" id="ver" data-i="down" aria-expanded="false" aria-controls="verMenu" data-t="data-tip=switchVersion"><span class="nm">{{version}}</span></button>+ <div class="menu c" id="verMenu" hidden>+ <h3 data-t="versions"></h3><div id="verList"><p class="foot" data-t="loading"></p></div>+ <div class="div"></div>+ <button class="opt" id="verNew"><span data-t="newVersion"></span><span class="dim" aria-hidden="true">+</span></button>+ <form id="verForm" hidden><input id="verName" autocomplete="off" spellcheck="false" maxlength="40" data-t="placeholder=versionHint aria-label=versionName"><button id="verGo" data-t="create"></button></form>+ <p class="foot" id="verFoot"></p>+ </div></div>+ <span class="sep" aria-hidden="true">/</span><span id="crumb"></span>+ </div>+ <div class="wrap">+ <button class="btn" id="export" data-i="export" aria-expanded="false" aria-controls="exportMenu"><span id="exportLabel">Export</span></button>+ <div class="menu r" id="exportMenu" hidden>+ <h3 data-t="resolution"></h3>+ <div id="res" role="group" data-t="aria-label=resolution"></div>+ <div class="acts"><button id="go">Export</button><button id="stop" data-t="cancel" hidden></button></div>+ <div id="xs" role="status" hidden></div>+ </div>+ </div>+</header>+<aside>+ <nav id="lists" data-t="aria-label=lists">+ <h2 data-t="scenes"></h2><ol id="scenes"></ol>+ <h2>Audio</h2><ul id="audio"></ul>+ <h2><span data-t="notes"></span> <span id="noteCount" class="num"></span></h2><ol id="notes"></ol>+ </nav>+ <section id="sel" aria-live="polite" data-t="aria-label=selection"><b id="selText" class="muted" data-t="nothing"></b><small id="selSub" data-t="how"></small><small id="selRange" class="num" hidden></small><small data-t="saved"></small></section>+</aside>+<main>+ <div id="canvas">+ <div class="pill" id="pillFull"><button class="sq" id="full" data-i="full" data-label="full"></button></div>+ <div class="toast" id="note" role="status" hidden></div>+ <div id="stage"><span id="msg" data-t="loadingProject"></span><canvas id="view" hidden></canvas><div id="marks"></div>+ <div class="pop" id="pop" role="dialog" aria-labelledby="popWhere" hidden>+ <div class="head"><span class="tag" id="popN"></span><span id="popWhere" class="num"></span><span id="popState" hidden></span></div>+ <textarea id="popText" rows="2" data-t="placeholder=noteHint aria-label=note"></textarea>+ <div class="foot2"><button id="popDel" data-t="del"></button><span><button id="popDone"></button><button id="popOk" data-t="save"></button></span></div>+ </div></div>+ <div id="bar">+ <div class="pill" id="tools">+ <button class="sq" id="prev" data-i="prev" data-label="prevScene"></button>+ <button class="sq" id="play" data-i="play" data-label="play" data-key="Space"></button>+ <button class="sq" id="next" data-i="next" data-label="nextScene"></button>+ <span id="time" class="num"><span id="now">00:00.00</span> <span class="muted">/ <span id="len">00:00.00</span></span></span>+ <button class="sq" id="rangeBtn" data-i="range" data-label="markRange" data-key="R" aria-pressed="false"></button>+ <button class="sq" id="zout" data-i="zout" data-label="zoomOut" data-key="−"></button>+ <button class="sq" id="zin" data-i="zin" data-label="zoomIn" data-key="+"></button>+ <button class="sq" id="laneBtn" data-i="lane" data-label="hideTimeline" aria-expanded="true" aria-controls="lane"></button>+ </div>+ <div class="pill" id="rangeBar" role="group" data-t="aria-label=range" hidden>+ <span class="ri" data-i="range"></span><span id="rangeText" class="num"></span>+ <button id="rangeNote" data-i="note" data-t="note"></button>+ <button class="sq" id="rangeOff" data-i="x" data-label="removeRange" data-key="Esc"></button>+ </div>+ </div>+ <div id="lane"><div id="laneIn">+ <canvas id="tl" data-tip="#tlKeys" tabindex="0" role="slider" aria-label="Timeline" aria-valuemin="0" aria-valuenow="0"></canvas>+ <div class="mark" id="pick" hidden></div><div class="mark" id="head"></div>+ </div></div>+ </div>+</main>+<div id="frames"></div>+<div id="tip" aria-hidden="true" hidden></div>+<template id="tlKeys"><div class="keys">+ <span data-t="clickDrag"></span><span class="dim" data-t="moveTime"></span>+ <span class="k"><kbd>←</kbd> <kbd>→</kbd></span><span class="dim" data-t="step"></span>+ <span class="k"><kbd>Shift</kbd> + <span data-t="drag"></span></span><span class="dim" data-t="markRangeKey"></span>+ <span class="k"><kbd>I</kbd> <kbd>O</kbd></span><span class="dim" data-t="rangeEnds"></span>+ <span class="k"><kbd>X</kbd></span><span class="dim" data-t="sceneRange"></span>+ <span class="k"><kbd>Ctrl</kbd> + scroll</span><span class="dim">zoom</span>+</div></template>+<script type="module">+const $ = id => document.getElementById(id);+// ---- UI text, in Indonesian and English. The language is the one picked in the project menu, else the browser's:+// Indonesian when one of its languages is, English otherwise. Picking one reloads the page, so text is set once.+const TEXT = {+ hidePanel: ['Sembunyikan panel', 'Hide panel'],+ showPanel: ['Tampilkan panel', 'Show panel'],+ switchProject: ['Ganti project', 'Switch project'],+ projects: ['Project', 'Projects'],+ loading: ['Memuat…', 'Loading…'],+ projectsHint: ['Project yang pernah dibuka akan muncul di sini.', 'Projects you have opened show up here.'],+ projectsFailed: ['Daftar project tidak bisa dimuat.', 'The project list could not be loaded.'],+ otherLang: ['English', 'Bahasa Indonesia'],+ switchVersion: ['Ganti versi', 'Switch version'],+ versions: ['Versi', 'Versions'],+ main: ['Utama', 'Main'],+ versionsFailed: ['Daftar versi tidak bisa dimuat.', 'The version list could not be loaded.'],+ newVersion: ['Versi baru dari ini', 'New version from this one'],+ versionName: ['Nama versi baru', 'New version name'],+ versionHint: ['Nama, misal tiktok', 'Name, for example tiktok'],+ create: ['Buat', 'Create'],+ copyOf: [v => `Salinan dari ${v}. Minta agent mengubah isinya.`, v => `A copy of ${v}. Ask the agent to change it.`],+ badName: ['Nama versi pakai huruf atau angka.', 'Use letters or numbers in the name.'],+ nameTaken: ['Sudah ada versi dengan nama itu.', 'A version with that name already exists.'],+ resolution: ['Resolusi', 'Resolution'],+ cancel: ['Batalkan', 'Cancel'],+ lists: ['Scene dan audio', 'Scenes and audio'],+ scenes: ['Scene', 'Scenes'],+ notes: ['Catatan', 'Notes'],+ note: ['Catatan', 'Note'],+ selection: ['Seleksi', 'Selection'],+ nothing: ['Belum ada pilihan', 'Nothing selected'],+ how: ['Klik scene, audio, atau timeline. Tarik kotak atau klik di preview untuk memberi catatan.', 'Click a scene, an audio file or the timeline. Drag a box or click on the preview to leave a note.'],+ saved: ['Tersimpan di selection.json', 'Saved in selection.json'],+ full: ['Layar penuh', 'Full screen'],+ fullExit: ['Keluar dari layar penuh', 'Exit full screen'],+ fullNone: ['Layar penuh tidak tersedia di browser ini', 'Full screen is not available in this browser'],+ fullRefused: ['Layar penuh ditolak browser', 'The browser refused full screen'],+ fullStuck: ['Layar penuh tidak terbuka. Coba di Chrome biasa.', 'Full screen did not open. Try it in regular Chrome.'],+ loadingProject: ['Memuat project…', 'Loading project…'],+ noteHint: ['Tulis masalahnya. Enter untuk simpan.', 'Say what is wrong. Enter to save.'],+ del: ['Hapus', 'Delete'],+ save: ['Simpan', 'Save'],+ prevScene: ['Scene sebelumnya', 'Previous scene'],+ nextScene: ['Scene berikutnya', 'Next scene'],+ play: ['Putar', 'Play'],+ pause: ['Jeda', 'Pause'],+ space: ['Spasi', 'Space'],+ markRange: ['Tandai rentang', 'Mark a range'],+ zoomOut: ['Perkecil timeline', 'Zoom out the timeline'],+ zoomIn: ['Perbesar timeline', 'Zoom in the timeline'],+ hideTimeline: ['Sembunyikan timeline', 'Hide timeline'],+ showTimeline: ['Tampilkan timeline', 'Show timeline'],+ range: ['Rentang', 'Range'],+ removeRange: ['Hapus rentang', 'Remove range'],+ to: ['sampai', 'to'],+ clickDrag: ['Klik atau tarik', 'Click or drag'],+ moveTime: ['pindah waktu', 'move in time'],+ step: ['1 frame, dengan Shift 1 detik', '1 frame, 1 second with Shift'],+ drag: ['tarik', 'drag'],+ markRangeKey: ['tandai rentang', 'mark a range'],+ rangeEnds: ['awal dan akhir rentang', 'start and end of a range'],+ sceneRange: ['rentang satu scene', 'one scene as a range'],+ noScenes: ['Belum ada scene. Tambahkan ke "scenes" di project.json, lalu muat ulang.', 'No scenes yet. Add them to "scenes" in project.json, then reload.'],+ noFile: [n => `Scene ${n} di project.json tidak punya "file".`, n => `Scene ${n} in project.json has no "file".`],+ firstTransition: ['Scene 1 punya transisi, padahal tidak ada scene sebelumnya. Hapus "transition" dari scene 1.', 'Scene 1 has a transition, but there is no scene before it. Remove "transition" from scene 1.'],+ badTransition: [(n, e) => `Transisi di scene ${n}: ${e}`, (n, e) => `Transition in scene ${n}: ${e}`],+ noCanvas: [f => `${f} tidak ada atau tanpa <canvas id="c">. Periksa project.json, lalu muat ulang.`, f => `${f} is missing or has no <canvas id="c">. Check project.json, then reload.`],+ loadingScene: [(i, n) => `Memuat scene ${i} dari ${n}…`, (i, n) => `Loading scene ${i} of ${n}…`],+ tooShort: [(i, f, a, b) => `Scene ${i} (${f} frame) terlalu pendek untuk transisinya (${a} + ${b} frame). Perpendek "duration" transisinya, lalu muat ulang.`,+ (i, f, a, b) => `Scene ${i} (${f} frames) is too short for its transitions (${a} + ${b} frames). Shorten the transition's "duration", then reload.`],+ loadFailed: [e => `Gagal memuat project: ${e}. Periksa project.json, lalu muat ulang.`, e => `The project did not load: ${e}. Check project.json, then reload.`],+ noScenesYet: ['Belum ada scene', 'No scenes yet'],+ noAudio: ['Belum ada audio', 'No audio yet'],+ starts: [s => `mulai ${s} s`, s => `starts at ${s} s`],+ inScene: [(time, n) => `${time}, di scene ${n}`, (time, n) => `${time}, in scene ${n}`],+ atSecond: [(s, time) => `Detik ${s}, video ${time}`, (s, time) => `At ${s} s, video ${time}`],+ sceneSecond: [(n, s) => `Scene ${n}, detik ${s}`, (n, s) => `Scene ${n}, at ${s} s`],+ done: ['Selesai', 'Done'],+ reopen: ['Buka lagi', 'Reopen'],+ markDone: ['Tandai selesai', 'Mark done'],+ empty: ['Tanpa catatan', 'Empty note'],+ noteLabel: [(n, done, text, where) => `Catatan ${n}${done ? ', selesai' : ''}: ${text || 'tanpa catatan'}, ${where}`, (n, done, text, where) => `Note ${n}${done ? ', done' : ''}: ${text || 'empty note'}, ${where}`],+ noNotes: ['Belum ada catatan. Tarik kotak atau klik di preview.', 'No notes yet. Drag a box or click on the preview.'],+ allDone: ['Semua catatan sudah selesai.', 'All notes are done.'],+ rangeHow: ['Tarik di timeline dari awal sampai akhir. Esc untuk batal.', 'Drag on the timeline from start to end. Esc to cancel.'],+ open: ['Buka', 'Open'],+ cancelling: ['Membatalkan…', 'Cancelling…'],+ exporting: [r => `Mengekspor ${r}`, r => `Exporting ${r}`],+ preparing: ['Menyiapkan…', 'Preparing…'],+ sceneOf: [(i, n) => `Scene ${i} dari ${n}`, (i, n) => `Scene ${i} of ${n}`],+ cancelled: ['Export dibatalkan', 'Export cancelled'],+ noResult: ['render berhenti tanpa hasil', 'the render stopped without a result'],+ doneIn: [s => `Selesai, ${s} detik`, s => `Done in ${s} s`],+ failed: ['Export gagal', 'Export failed'],+ seeLog: [e => `${e}. Log ada di terminal.`, e => `${e}. The log is in the terminal.`],+ busy: ['Export lain masih berjalan', 'Another export is still running'],+};+const LANG = (() => {+ let pick; try { pick = localStorage.motlabLang; } catch {}+ return pick === 'id' || pick === 'en' ? pick : navigator.languages.some(l => /^id(-|$)/i.test(l)) ? 'id' : 'en';+})();+const L = (key, ...a) => { const v = TEXT[key][LANG === 'id' ? 0 : 1]; return typeof v === 'function' ? v(...a) : v; };+document.documentElement.lang = LANG;+// data-t="key" is the element's text, data-t="attribute=key" an attribute; several are separated by spaces+for (const el of [document, $('tlKeys').content].flatMap(root => [...root.querySelectorAll('[data-t]')]))+ for (const part of el.dataset.t.split(' ')) { const [attr, key] = part.includes('=') ? part.split('=') : [null, part]; attr ? el.setAttribute(attr, L(key)) : el.textContent = L(key); }+const VERSION = '{{project}}' === 'project.json' ? L('main') : '{{version}}'; // the server names project.json "Utama"+$('ver').firstElementChild.textContent = VERSION; document.title = `${$('proj').textContent} / ${VERSION} · motlab`;+$('lang').firstChild.textContent = L('otherLang'); $('lang').lastChild.textContent = LANG === 'id' ? 'EN' : 'ID'; $('lang').firstChild.lang = LANG === 'id' ? 'en' : 'id';+$('lang').onclick = () => { try { localStorage.motlabLang = LANG === 'id' ? 'en' : 'id'; } catch {} location.reload(); };+const PAD = 20, RULER = 44, MK_Y = 30, VH = 54, AH = 40, GAP = 8, AY = RULER + VH + GAP, PEAKS = 200;+const BLUE = '#2c6fe0', MUTED = '#666561', WAVE = '#85847f'; // waveform is 3.3:1 on its clip, 3.9:1 in blue when selected+const FONT = getComputedStyle(document.documentElement).getPropertyValue('--font').trim(); // the timeline canvas uses the page font too+const laneHeight = n => AY + n * (AH + GAP) + 6;+const svg = (d, fill) => `<svg aria-hidden="true" width="16" height="16" viewBox="0 0 16 16" fill="${fill ? 'currentColor' : 'none'}" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round">${d}</svg>`;+const ICON = {+ panel: svg('<rect x="2" y="3" width="12" height="10" rx="2"/><path d="M6.5 3v10"/>'),+ export: svg('<path d="M8 2.5v7.5m0 0L5 7m3 3 3-3M3 11v1a1.5 1.5 0 0 0 1.5 1.5h7A1.5 1.5 0 0 0 13 12v-1"/>'),+ full: svg('<path d="M9.5 2.5h4v4M6.5 13.5h-4v-4M13.5 2.5 9.5 6.5M2.5 13.5l4-4"/>'),+ prev: svg('<path d="M4 3.5v9"/><path d="M12 4v8L6.5 8z" fill="currentColor"/>'),+ next: svg('<path d="M12 3.5v9"/><path d="M4 4v8l5.5-4z" fill="currentColor"/>'),+ play: svg('<path d="M5 3.5v9L12.5 8z"/>', true),+ pause: svg('<path d="M5 3.5v9M11 3.5v9" stroke-width="2.5"/>'),+ wave: svg('<path d="M3 6.5v3M5.5 4v8M8 5.5v5M10.5 3v10M13 6.5v3"/>'),+ range: svg('<path d="M5 3H3v10h2M11 3h2v10h-2M6.5 8h3"/>'),+ note: svg('<path d="M3 3.5h10v7H8.5L5.5 13v-2.5H3z"/>'),+ x: svg('<path d="m4.5 4.5 7 7m0-7-7 7"/>'),+ arrow: svg('<path d="M3.5 8h9M8.5 4l4 4-4 4"/>'), // Lucide arrow-right (ISC), in the 16 px box+ check: svg('<path d="M13 4.5 6.5 11 3 7.5"/>'), // Lucide check (ISC), in the 16 px box+ undo: svg('<path d="M3 3v4h4"/><path d="M3.5 7A5 5 0 1 1 5 11.5"/>'), // Lucide rotate-ccw (ISC), in the 16 px box+ zout: svg('<circle cx="7" cy="7" r="4.5"/><path d="m10.5 10.5 3 3M5 7h4"/>'),+ zin: svg('<circle cx="7" cy="7" r="4.5"/><path d="m10.5 10.5 3 3M5 7h4M7 5v4"/>'),+ lane: svg('<rect x="2" y="3" width="12" height="10" rx="2"/><path d="M2 9.5h12"/>'),+ down: svg('<path d="m5 6.5 3 3 3-3"/>'),+};+const label = (b, text, key = b.dataset.key) => { // the accessible name and the tooltip; `key` is shown in a key cap+ b.setAttribute('aria-label', text); b.dataset.tip = text;+ if (key) { b.dataset.key = key; b.setAttribute('aria-keyshortcuts', key === '−' ? '-' : key); }+};+document.querySelectorAll('[data-i]').forEach(e => e.insertAdjacentHTML(e.id === 'export' || e.id === 'rangeNote' ? 'afterbegin' : 'beforeend', ICON[e.dataset.i]));+document.querySelectorAll('[data-label]').forEach(b => label(b, L(b.dataset.label)));+// Tooltips: shown after 0.5 s of hover (at once while moving between controls, or on keyboard focus), above the control+// or below it near the top of the window. The timeline's list of keys waits 1 s and goes away when the pointer moves on,+// so it does not sit over the timeline while you work.+{+ const tip = $('tip'); let at = null, timer = 0, warm = 0, from = null;+ const fill = el => {+ const t = el.dataset.tip;+ if (t.startsWith('#')) return tip.replaceChildren($(t.slice(1)).content.cloneNode(true));+ tip.innerHTML = '<span class="line"><span></span></span>'; tip.firstChild.firstChild.textContent = t;+ if (el.dataset.key) tip.firstChild.append(Object.assign(document.createElement('kbd'), { textContent: el.dataset.key === 'Space' ? L('space') : el.dataset.key }));+ };+ const place = (el, x) => {+ const r = el.getBoundingClientRect(), w = tip.offsetWidth, h = tip.offsetHeight, M = 8;+ const left = x ?? r.left + r.width / 2 - w / 2, top = r.top - h - 6 >= M ? r.top - h - 6 : r.bottom + 6;+ tip.style.left = Math.min(innerWidth - w - M, Math.max(M, left)) + 'px'; tip.style.top = top + 'px';+ };+ const show = (el, x) => { at = el; fill(el); tip.hidden = false; place(el, x); };+ const hide = () => { clearTimeout(timer); if (!tip.hidden) warm = performance.now(); tip.hidden = true; at = null; };+ addEventListener('pointerover', e => {+ const el = e.target.closest?.('[data-tip]');+ if (el === at || e.pointerType === 'touch') return;+ hide(); if (!el) return;+ const big = el.dataset.tip.startsWith('#'), x = e.clientX;+ from = { x: e.clientX, y: e.clientY };+ timer = setTimeout(() => show(el, big ? x - 20 : undefined), big ? 1000 : performance.now() - warm < 400 ? 0 : 500);+ });+ addEventListener('pointermove', e => { // the timeline's list: still pointer only+ const el = e.target.closest?.('[data-tip^="#"]');+ if (!el || e.buttons || !from || Math.hypot(e.clientX - from.x, e.clientY - from.y) < 6) return;+ hide(); from = { x: e.clientX, y: e.clientY };+ timer = setTimeout(() => show(el, from.x - 20), 1000);+ });+ addEventListener('pointerout', e => { const el = e.target.closest?.('[data-tip]'); if (el && !el.contains(e.relatedTarget)) hide(); });+ for (const ev of ['pointerdown', 'wheel', 'keydown', 'scroll']) addEventListener(ev, hide, { capture: true, passive: true });+ addEventListener('focusin', e => { const el = e.target.closest?.('[data-tip]'); if (el && e.target.matches(':focus-visible') && !el.dataset.tip.startsWith('#')) { hide(); show(el); } });+ addEventListener('focusout', e => { if (at?.contains(e.target)) hide(); });+}+const fmt = t => `${String(Math.floor(t / 60)).padStart(2, '0')}:${(t % 60).toFixed(2).padStart(5, '0')}`;+const name = f => f.split('/').pop().replace(/\.\w+$/, '');+const hint = text => Object.assign(new Error(text), { hint: true }); // a message that already says what to do next+let noteTimer;+const note = text => { $('note').textContent = text; $('note').hidden = false; clearTimeout(noteTimer); noteTimer = setTimeout(() => $('note').hidden = true, 5000); };++// ---- menus, the side panel and full screen work before the project has loaded+const menus = [[$('export'), $('exportMenu')], [$('proj'), $('projMenu')], [$('ver'), $('verMenu')]];+const setMenu = (btn, menu, open) => { menu.hidden = !open; btn.classList.toggle('open', open); btn.setAttribute('aria-expanded', open); if (open) btn.onopen?.(); };+for (const [btn, menu] of menus) btn.onclick = () => setMenu(btn, menu, menu.hidden);+// The project menu lists the motlab projects the server finds, read again each time it opens, so a new one shows up.+$('proj').onopen = async () => {+ try {+ const { projects } = await (await fetch('/projects')).json();+ $('projList').replaceChildren(...projects.map(p => {+ const a = document.createElement('a'); a.className = 'opt two'; a.href = `/p/${p.slug}/`;+ a.innerHTML = '<span class="nm"></span><span class="dim"></span>'; a.firstChild.textContent = p.name; a.lastChild.textContent = p.path;+ if (p.slug === '{{slug}}') { a.classList.add('on'); a.setAttribute('aria-current', 'page'); }+ return a;+ }));+ $('projFoot').textContent = L('projectsHint');+ } catch { $('projList').innerHTML = `<p class="foot">${L('projectsFailed')}</p>`; }+};+// Versions are the project files in this folder (project.json, project-tiktok.json). A new one is a copy of the open+// version, which the agent then changes; the page opens it right away.+$('ver').onopen = async () => {+ $('verForm').hidden = true; $('verNew').hidden = false; $('verFoot').textContent = '';+ try {+ const list = await (await fetch('versions')).json();+ $('verList').replaceChildren(...list.map(v => {+ const a = document.createElement('a'); a.className = 'opt'; a.href = '?v=' + encodeURIComponent(v.file);+ a.innerHTML = '<span></span><span class="dim"></span>'; a.firstChild.textContent = v.file === 'project.json' ? L('main') : v.label; a.lastChild.textContent = v.file;+ if (v.file === '{{project}}') { a.classList.add('on'); a.setAttribute('aria-current', 'page'); }+ return a;+ }));+ } catch { $('verList').innerHTML = `<p class="foot">${L('versionsFailed')}</p>`; }+};+$('verNew').onclick = () => { $('verNew').hidden = true; $('verForm').hidden = false; $('verFoot').textContent = L('copyOf', VERSION); $('verName').focus(); };+$('verForm').onsubmit = async e => {+ e.preventDefault();+ if (!/[a-z0-9]/i.test($('verName').value)) { $('verFoot').textContent = L('badName'); return $('verName').focus(); } // the server keeps only a to z and 0 to 9+ $('verGo').disabled = true;+ try {+ const r = await fetch('versions', { method: 'POST', body: JSON.stringify({ from: '{{project}}', name: $('verName').value }) });+ if (!r.ok) throw new Error(r.status === 409 ? L('nameTaken') : await r.text());+ location.search = '?v=' + encodeURIComponent((await r.json()).file);+ } catch (err) { $('verFoot').textContent = err.message; $('verGo').disabled = false; $('verName').focus(); }+};+addEventListener('pointerdown', e => { for (const [btn, menu] of menus) if (!menu.parentElement.contains(e.target)) setMenu(btn, menu, false); });+addEventListener('keydown', e => {+ if (e.key === 'Escape') for (const [btn, menu] of menus) if (!menu.hidden) { setMenu(btn, menu, false); btn.focus(); e.preventDefault(); }+});+const setPanel = open => {+ document.body.classList.toggle('closed', !open); $('panel').setAttribute('aria-expanded', open);+ label($('panel'), L(open ? 'hidePanel' : 'showPanel'));+};+$('panel').onclick = () => setPanel(document.body.classList.contains('closed'));+const narrow = matchMedia('(max-width: 719px)'); // a narrow window hides the panel, also when the window is made narrow later+if (narrow.matches) setPanel(false);+narrow.addEventListener('change', e => { if (e.matches) setPanel(false); });+requestAnimationFrame(() => requestAnimationFrame(() => document.body.classList.remove('still'))); // animate from here on+if (!document.fullscreenEnabled) { $('full').disabled = true; label($('full'), L('fullNone')); }+$('full').onclick = () => { // some embedded browsers neither open full screen nor reject, so a silent wait also gets a message+ if (document.fullscreenElement) return document.exitFullscreen();+ let settled = false;+ $('stage').requestFullscreen().then(() => settled = true, e => { settled = true; note(L('fullRefused')); });+ setTimeout(() => { if (!settled) note(L('fullStuck')); }, 1500);+};+document.onfullscreenchange = () => label($('full'), L(document.fullscreenElement ? 'fullExit' : 'full'));++try {+ const project = await (await fetch(encodeURIComponent('{{project}}'))).json(), fps = project.fps, files = project.audio || [];+ if (!project.scenes?.length) throw hint(L('noScenes'));+ $('tl').style.height = laneHeight(files.length) + 'px'; // hold the timeline's final height while the scenes load+ try { if (localStorage.motlabTimeline === '0') $('lane').hidden = true; } catch {} // hidden last time: stays hidden from the start++ // Every scene is the real page in a hidden iframe, so the preview draws exactly what the render draws. Only a few+ // pages stay loaded (the one on screen and its neighbours); the rest are unloaded, so a long project stays light.+ const KEEP = 3, live = []; // loaded scenes, least recently used first+ let shown = null, rendering = [];+ // A scene is a path, or { file, transition } where the transition turns the scene before into this one. Its length+ // in frames (n) follows the renderer's rule in src/project.js.+ const { createMixer, findTransition, transitionProgress } = await import('/__motlab/transitions.js');+ const scenes = project.scenes.map((x, i) => {+ const s = typeof x === 'string' ? { file: x } : { file: x.file, transition: x.transition };+ if (!s.file) throw hint(L('noFile', i + 1));+ if (s.transition) {+ if (!i) throw hint(L('firstTransition'));+ try { s.transition = { ease: 'inOutCubic', params: {}, ...s.transition, type: findTransition(s.transition.type).name, n: Math.max(1, Math.round((Number(s.transition.duration) || 0) * fps)) }; transitionProgress(0, 1, s.transition.ease); }+ catch (e) { throw hint(L('badTransition', i + 1, e.message)); }+ }+ return s;+ });+ let mixer = null;+ function unload(s) { s.frame.remove(); s.frame = s.win = s.canvas = s.warm = null; live.splice(live.indexOf(s), 1); }+ function load(s) {+ if (s.win) { live.push(...live.splice(live.indexOf(s), 1)); return s; }+ return s.loading ??= (async () => {+ const frame = document.createElement('iframe'); frame.src = `${s.file}?scale=1`; $('frames').append(frame);+ await new Promise(r => frame.onload = r);+ const win = frame.contentWindow, canvas = win.document.getElementById('c');+ if (!canvas) { frame.remove(); throw hint(L('noCanvas', s.file)); }+ await win.ready;+ Object.assign(s, { frame, win, canvas }); live.push(s);+ for (const old of live.filter(x => x !== s && x !== shown && !rendering.includes(x)).slice(0, Math.max(0, live.length - KEEP))) unload(old);+ return s;+ })().finally(() => s.loading = null);+ }++ // One pass through the scenes for their length and a few thumbnails (one per 2 s, at most 12).+ const thumbAt = async (s, time) => { await s.win.renderAt(time); return createImageBitmap(s.canvas, { resizeHeight: VH * 2, resizeQuality: 'high' }); };+ for (const [i, s] of scenes.entries()) {+ $('msg').textContent = L('loadingScene', i + 1, scenes.length);+ await load(s);+ Object.assign(s, { dur: Math.round(s.win.TOTAL * fps) / fps, w: s.canvas.width, h: s.canvas.height, thumbs: [] });+ 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.+ 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+ 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;+ }+ 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);+ return n && k < n ? { from: scenes[scenes.indexOf(s) - 1], k, n } : 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();+ const tracks = await Promise.all(files.map(async a => {+ const buf = await ac.decodeAudioData(await (await fetch(a.file)).arrayBuffer()), data = buf.getChannelData(0);+ const peaks = new Float32Array(Math.ceil(buf.duration * PEAKS));+ for (let i = 0; i < data.length; i++) { const k = Math.floor(i / buf.sampleRate * PEAKS), v = Math.abs(data[i]); if (v > peaks[k]) peaks[k] = v; }+ const from = a.from || 0, len = Math.max(0, Math.min(a.duration ?? Infinity, buf.duration - from)); // the part of the file that is used+ return { file: a.file, start: a.start || 0, volume: a.volume ?? 1, from, len, buf, peaks };+ }));++ const view = $('view'), tl = $('tl'), lane = $('lane'), g = tl.getContext('2d'), clean = document.createElement('canvas');+ view.width = clean.width = scenes[0].w; view.height = clean.height = scenes[0].h;+ $('msg').hidden = true; view.hidden = false;+ tl.setAttribute('aria-valuemax', total.toFixed(2));+ let notes = [], others = [], active = null, opening = null, draft = null, hits = []; // this version's notes, other versions', the open one, one to open, a box being drawn, tags on the timeline+ const openNotes = () => notes.filter(m => !m.done || m === active); // what the preview and the timeline show: done notes only while open+ const images = new Map(); // note number -> PNG data URL, sent with the next save+ let t = 0, sel = null, range = null, looping = false, playing = false, t0 = 0, ac0 = 0, sources = [], busy = false, pps = 1, zoom = 1, cur = null, luma = null;++ // ---- side panel; every row is a button so Tab, Enter and Space reach it+ $('len').textContent = fmt(total);+ const item = (list, html, click) => {+ const li = document.createElement('li'), b = document.createElement('button');+ b.className = 'row'; b.innerHTML = html; b.onclick = click; li.append(b); $(list).append(li); return b;+ };+ const current = (el, on) => on ? el.setAttribute('aria-current', 'true') : el.removeAttribute('aria-current');+ scenes.forEach((s, i) => {+ s.li = item('scenes', `<canvas aria-hidden="true"></canvas><span class="name">${name(s.file)}<small>Scene ${i + 1}</small></span><span class="d num">${s.dur.toFixed(2)} s</span>`, () => seek(s.start));+ const th = s.li.firstElementChild, b = s.thumbs[s.thumbs.length >> 1]; th.width = b.width; th.height = b.height; th.getContext('2d').drawImage(b, 0, 0);+ });+ tracks.forEach(a => a.li = item('audio', `<span class="ic">${ICON.wave}</span><span class="name">${name(a.file)}<small class="num">${L('starts', a.start.toFixed(2))}</small></span><span class="d num">vol ${a.volume}</span>`, () => seek(a.start, a)));+ if (!tracks.length) $('audio').innerHTML = `<li class="empty">${L('noAudio')}</li>`;++ // ---- timeline: ruler, one row of scenes, one row per audio file. Zoomed in, #laneIn gets the full width so the+ // lane scrolls natively, and the canvas (sticky) draws only the part in view.+ const fitPps = () => (lane.clientWidth - PAD * 2) / total, maxZoom = () => Math.max(1, 24 * fps / fitPps()); // up to 24 px per frame+ function layout() { // hidden, the timeline has no width, so it keeps its zoom and is laid out again when it is shown+ if (lane.hidden) return;+ zoom = Math.min(zoom, maxZoom()); pps = fitPps() * zoom;+ $('laneIn').style.width = zoom > 1 ? total * pps + PAD * 2 + 'px' : '';+ $('zout').disabled = zoom <= 1; $('zin').disabled = zoom >= maxZoom();+ }+ function setZoom(z, at = t, x = PAD + t * pps - lane.scrollLeft) { // keeps time `at` under canvas x `x`+ zoom = Math.max(1, z); layout(); lane.scrollLeft = PAD + at * pps - x; drawTimeline();+ }+ function drawTimeline() {+ if (lane.hidden) return;+ const w = lane.clientWidth, h = laneHeight(tracks.length), dpr = devicePixelRatio, sx = lane.scrollLeft;+ tl.style.width = w + 'px'; tl.width = w * dpr; tl.height = h * dpr; tl.style.height = h + 'px'; g.setTransform(dpr, 0, 0, dpr, 0, 0);+ const X = time => PAD + time * pps - sx, from = Math.max(0, (sx - PAD) / pps), to = (sx + w) / pps; // visible seconds++ g.font = `11px ${FONT}`; g.textBaseline = 'middle';+ if (pps / fps >= 6) { // close in, a small tick per frame+ g.fillStyle = '#dcdcda';+ for (let f = Math.floor(from * fps); f <= Math.min(to, total) * fps; f++) g.fillRect(X(f / fps), 21, 1, 4);+ }+ const step = [0.1, 0.2, 0.5, 1, 2, 5, 10, 15, 30, 60, 120, 300].find(s => s * pps >= 70) || 600;+ for (let k = Math.floor(from / step); k * step <= Math.min(to, total) + 1e-6; k++) {+ const s = k * step, text = step < 1 ? fmt(s) : fmt(s).slice(0, 5);+ g.fillStyle = '#dcdcda'; g.fillRect(X(s), 8, 1, 10);+ g.fillStyle = MUTED; if (X(s) + 40 < w) g.fillText(text, X(s) + 6, 13);+ }++ for (const [i, s] of scenes.entries()) {+ const x = X(s.start), cw = s.dur * pps - 2;+ if (x > w || x + cw < 0) continue;+ const tw = VH * s.w / s.h; // thumbnails keep their shape; a tile shows the thumbnail nearest its middle+ g.save(); g.beginPath(); g.roundRect(x, RULER, cw, VH, 8); g.clip();+ for (let k = Math.max(0, Math.floor(-x / tw)); k * tw < cw && x + k * tw < w; k++) {+ 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 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);+ 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();+ }+ }++ for (const [i, a] of tracks.entries()) {+ const x = X(a.start), y = AY + i * (AH + GAP), cw = Math.max(4, Math.min(a.len, total - a.start) * pps), on = sel?.audio && tracks[sel.audio.index] === a;+ if (x > w || x + cw < 0) continue;+ g.fillStyle = on ? '#dfe9fb' : '#f1f1ef'; g.beginPath(); g.roundRect(x, y, cw, AH, 8); g.fill();+ g.save(); g.clip(); g.fillStyle = on ? BLUE : WAVE;+ for (let px = Math.max(0, Math.floor(-x)); px < cw && x + px < w; px++) { // waveform at the volume it is mixed at+ let v = 0; for (let k = Math.floor((a.from + px / pps) * PEAKS), e = Math.max(k + 1, Math.floor((a.from + (px + 1) / pps) * PEAKS)); k < e; k++) v = Math.max(v, a.peaks[k] || 0);+ const bar = Math.max(1, Math.min(1, v * a.volume) * (AH - 8)); g.fillRect(x + px, y + (AH - bar) / 2, 1, bar);+ }+ g.restore();+ if (on) { g.lineWidth = 2; g.strokeStyle = BLUE; g.beginPath(); g.roundRect(x + 1, y + 1, cw - 2, AH - 2, 7); g.stroke(); }+ const label = name(a.file), lw = g.measureText(label).width, inside = cw > lw + 16, lx = Math.max(x, 0);+ g.fillStyle = inside ? '#3d3d3a' : MUTED; g.fillText(label, inside ? Math.min(lx, x + cw - lw - 16) + 8 : x + cw + 8, inside ? y + 10 : y + AH / 2);+ }+ if (range) { // a light blue band over every row, with a 1 px edge on each side and a bar in the ruler+ const a = X(range.start), b = X(range.end);+ g.fillStyle = 'rgba(44,111,224,.10)'; g.fillRect(a, 4, b - a, h - 10);+ g.fillStyle = BLUE;+ for (const x of [a, b]) { // the edges can be dragged; each has a head at the top, like the playhead+ g.fillRect(x - 0.5, 4, 1, h - 10);+ g.beginPath(); g.roundRect(x - 4, 4, 8, 14, [3, 3, 4, 4]); g.fill();+ }+ }+ // Notes in a row under the time labels: a numbered tag at their time, light blue, solid blue for the open one. A+ // range note draws a line to the end of its range. All lines go first and every tag over them, with a 2 px white+ // margin, so a line or a range edge never runs through a number.+ g.font = `600 11px ${FONT}`; g.textAlign = 'center'; hits = [];+ const vis = openNotes();+ for (const m of vis) if (m.range) {+ const a = X(m.range.start), b = X(m.range.end);+ g.fillStyle = m === active ? BLUE : '#a9c3f1'; g.fillRect(a, MK_Y - 1, b - a, 2); g.fillRect(b - 1, MK_Y - 4, 2, 8); // with a short end cap+ }+ for (const m of [...vis.filter(m => m !== active), ...vis.filter(m => m === active)]) { // the open one on top+ const a = X(m.range ? m.range.start : m.time), on = m === active, tw = Math.max(18, g.measureText(m.n).width + 10);+ const x0 = m.range ? a : a - tw / 2;+ if (x0 > w || x0 + tw < 0) continue;+ const inBand = range && x0 + tw / 2 > X(range.start) && x0 + tw / 2 < X(range.end); // the margin takes the colour under it+ g.fillStyle = inBand ? '#eaf0fc' : '#fff'; g.beginPath(); g.roundRect(x0 - 2, MK_Y - 10, tw + 4, 20, 6); g.fill();+ g.fillStyle = on ? BLUE : '#dfe9fb'; g.beginPath(); g.roundRect(x0, MK_Y - 8, tw, 16, 4); g.fill();+ g.fillStyle = on ? '#fff' : BLUE; g.fillText(m.n, x0 + tw / 2, MK_Y + 0.5);+ hits.push({ m, x0, x1: x0 + tw });+ }+ g.textAlign = 'left';+ if (active?.range) place();+ marks();+ }+ function marks() { // the marks live in #laneIn, so they scroll with it+ $('head').style.left = PAD + t * pps + 'px';+ $('pick').hidden = !sel; if (sel) $('pick').style.left = PAD + sel.time * pps + 'px';+ tl.setAttribute('aria-valuenow', t.toFixed(2)); tl.setAttribute('aria-valuetext', `${fmt(t)}, ${name(sceneAt(t).file)}`);+ }+ function reveal() { // zoomed in, playing or stepping brings the playhead back into view, near the left edge+ if (lane.hidden) return;+ const x = PAD + t * pps - lane.scrollLeft;+ if (x < PAD || x > lane.clientWidth - PAD) lane.scrollLeft = t * pps;+ }+ let drawQueued = false;+ lane.onscroll = () => { if (!drawQueued) { drawQueued = true; requestAnimationFrame(() => { drawQueued = false; drawTimeline(); }); } };+ lane.addEventListener('wheel', e => { // Ctrl+scroll (and a trackpad pinch) zooms around the pointer+ const r = tl.getBoundingClientRect(), x = e.clientX - r.left;+ if (e.ctrlKey || e.metaKey) { e.preventDefault(); setZoom(zoom * Math.exp(-e.deltaY * 0.002), (x + lane.scrollLeft - PAD) / pps, x); }+ else if (zoom > 1 && lane.scrollHeight <= lane.clientHeight && Math.abs(e.deltaY) > Math.abs(e.deltaX)) { e.preventDefault(); lane.scrollLeft += e.deltaY; }+ }, { passive: false });+ $('zin').onclick = () => setZoom(zoom * 2);+ $('zout').onclick = () => setZoom(zoom / 2);+ // The timeline can be hidden, so the preview gets the whole canvas (and more with the sidebar closed). The zoom+ // buttons go with it, and the choice is remembered in this browser.+ function setLane(open) {+ lane.hidden = $('zin').hidden = $('zout').hidden = !open;+ $('laneBtn').setAttribute('aria-expanded', open); label($('laneBtn'), L(open ? 'hideTimeline' : 'showTimeline'));+ try { localStorage.motlabTimeline = open ? '1' : '0'; } catch {}+ if (open) { layout(); drawTimeline(); reveal(); }+ }+ $('laneBtn').onclick = () => setLane(lane.hidden);++ // ---- preview: the scene's canvas is copied to `clean` and the view. Notes with a box or point are thin outlines+ // over the preview (#marks, after the selection box in the Claude canvas), so they stay sharp at any size. A note+ // belongs to the frame it was drawn on and shows only there.+ const PT = 16; // point marker diameter in CSS px+ const onFrame = m => !!cur && !!(m.box || m.point) && m.sceneIndex === scenes.indexOf(cur.s) + 1 && m.frame === cur.frame;+ function paint() {+ view.getContext('2d').drawImage(clean, 0, 0);+ if (opening && onFrame(opening)) { const m = opening; opening = null; return openNote(m); }+ if ((active?.box || active?.point) && !onFrame(active)) return closeNote(); // moved to another frame+ const vis = openNotes().filter(onFrame); if (draft) vis.push(draft);+ const vr = view.getBoundingClientRect(), sr = $('stage').getBoundingClientRect(), k = vr.width / view.width;+ $('marks').replaceChildren(...vis.map(m => {+ const d = document.createElement('div'), b = m.box || { x: m.point.x - PT / 2 / k, y: m.point.y - PT / 2 / k, w: PT / k, h: PT / k };+ d.className = 'mk' + (m.point ? ' point' : '') + (m === active ? ' on' : '');+ Object.assign(d.style, { left: vr.left - sr.left + b.x * k + 'px', top: vr.top - sr.top + b.y * k + 'px', width: b.w * k + 'px', height: b.h * k + 'px' });+ if (m.n) d.append(Object.assign(document.createElement('i'), { textContent: m.n }));+ return d;+ }));+ if (active?.box || active?.point) place();+ }+ function snapshot(m) { // selection/<n>.png: the frame with this note's box or point and number, as on screen, scaled to the frame+ const c = document.createElement('canvas'), v = c.getContext('2d'), k = view.width / view.getBoundingClientRect().width;+ c.width = view.width; c.height = view.height; v.drawImage(clean, 0, 0);+ v.fillStyle = 'rgba(44,111,224,.14)'; v.strokeStyle = BLUE; v.lineWidth = k;+ let lx, ly;+ if (m.box) { const { x, y, w, h } = m.box; v.fillRect(x, y, w, h); v.strokeRect(x + k / 2, y + k / 2, w - k, h - k); lx = x; ly = y - 2 * k; }+ else {+ const { x, y } = m.point;+ v.beginPath(); v.arc(x, y, (PT / 2 - 0.5) * k, 0, Math.PI * 2); v.fill(); v.stroke();+ v.fillStyle = BLUE; v.beginPath(); v.arc(x, y, 2.5 * k, 0, Math.PI * 2); v.fill();+ lx = x + (PT / 2 + 1) * k; ly = y - (PT / 2 + 1) * k;+ }+ v.font = `600 ${11 * k}px ${FONT}`;+ const tw = Math.max(16 * k, v.measureText(m.n).width + 10 * k), th = 16 * k, tx = Math.min(c.width - tw, Math.max(0, lx)), ty = Math.max(0, ly - th);+ v.fillStyle = BLUE; v.beginPath(); v.roundRect(tx, ty, tw, th, 4 * k); v.fill();+ v.fillStyle = '#fff'; v.textAlign = 'center'; v.textBaseline = 'middle'; v.fillText(m.n, tx + tw / 2, ty + th / 2 + 0.5 * k);+ return c.toDataURL('image/png');+ }+ new ResizeObserver(paint).observe(view);+ async function show() {+ marks(); $('now').textContent = fmt(t);+ const s = sceneAt(t);+ if (s !== shown) { if (shown) shown.warm = null; shown = s; $('crumb').textContent = name(s.file); } // played, it needs warming again+ if (busy) return;+ const at = t, frame = frameIn(s, at);+ // The display refreshes at 60 to 240 Hz and the video has 24 or 30 frames a second, so most ticks land on the frame+ // already shown. Drawing it again only took time from the next frame.+ if (cur && cur.s === s && cur.frame === frame && s.win) return;+ busy = true;+ try {+ const pair = pairAt(at);+ rendering = pair ? [s, pair.from] : [s];+ if (pair) await load(pair.from);+ await load(s); await s.warm;+ const next = scenes[scenes.indexOf(s) + 1];+ // Load the next scene before playback reaches it, and draw its first frame, so its footage has already sought to+ // the start and the cut does not stall (161 to 221 ms down to 10 to 17 ms on a scene with two clips, measured).+ if (next) Promise.resolve(load(next)).then(n => { if (n !== shown && !n.warm) n.warm = n.win.renderAt(0).catch(() => {}); }).catch(() => {});+ const c = clean.getContext('2d');+ if (pair) { // the frames of both scenes, mixed by the same code as the render (src/page/transitions.js)+ const tr = s.transition, a = pair.from;+ await a.win.renderAt(frameIn(a, at) / fps); await s.win.renderAt(frame / fps);+ mixer ??= createMixer();+ c.drawImage(mixer.draw(tr.type, a.canvas, s.canvas, transitionProgress(pair.k, pair.n, tr.ease), tr.params), 0, 0, clean.width, clean.height);+ } else {+ await s.win.renderAt(frame / fps);+ c.drawImage(s.canvas, 0, 0, clean.width, clean.height);+ }+ cur = { s, frame }; luma = null; paint();+ } finally { busy = false; rendering = []; }+ if (at !== t) show();+ }++ // ---- playback: the audio clock drives the playhead; the button is blue only while it plays+ const setPlay = on => { $('play').innerHTML = on ? ICON.pause : ICON.play; $('play').classList.toggle('hot', on); label($('play'), L(on ? 'pause' : 'play')); };+ function play(jump = true) { // with a range, Play starts at its start and goes round inside it+ const inside = range && t >= range.start && t < range.end - 1e-6;+ looping = !!range && (jump || inside); // a click elsewhere while playing plays on from there+ if (looping && !inside) t = range.start;+ if (t >= total) t = 0;+ ac.resume(); playing = true; t0 = t; ac0 = ac.currentTime; setPlay(true);+ sources = tracks.filter(a => a.start + a.len > t).map(a => {+ const src = ac.createBufferSource(), gain = ac.createGain();+ src.buffer = a.buf; gain.gain.value = a.volume; src.connect(gain).connect(ac.destination);+ const into = Math.max(0, t - a.start); src.start(ac0 + Math.max(0, a.start - t), a.from + into, a.len - into);+ return src;+ });+ requestAnimationFrame(tick);+ }+ function pause() { playing = false; sources.forEach(s => s.stop()); sources = []; setPlay(false); }+ function tick() {+ if (!playing) return;+ t = t0 + ac.currentTime - ac0;+ if (looping && range && t >= range.end) { pause(); t = range.start; play(); return; }+ if (t >= total) { t = total; pause(); }+ reveal(); show(); requestAnimationFrame(tick);+ }++ // ---- selection: every click on a scene, an audio file or a point in time is written to selection.json, with the+ // range and the notes.+ function showSelection() {+ scenes.forEach((s, i) => current(s.li, !!sel && !sel.audio && sel.sceneIndex === i + 1));+ tracks.forEach((a, i) => current(a.li, sel?.audio?.index === i));+ if (sel) { // e.g. "Scene 2: 02-grafik" / "Detik 1.09, video 00:04.09"+ $('selText').className = '';+ $('selText').textContent = sel.audio ? `Audio: ${name(sel.audio.file)}` : `Scene ${sel.sceneIndex}: ${name(sel.scene)}`;+ $('selSub').textContent = sel.audio+ ? L('inScene', fmt(sel.time), sel.sceneIndex)+ : L('atSecond', sel.sceneTime.toFixed(2), fmt(sel.time));+ }+ $('selRange').hidden = $('rangeBar').hidden = !range; // e.g. "Rentang 00:03.00 sampai 00:05.00, 2.00 s"+ if (range) {+ const len = (range.end - range.start).toFixed(2);+ $('selRange').innerHTML = `${L('range')} ${spanOf(range)} (${len} s)`;+ $('rangeText').innerHTML = `${spanOf(range)}<span class="dv"></span><span class="muted">${len} s</span>`;+ }+ 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);+ 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 };+ };+ 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 };+ }+ const spanOf = r => `<span class="rg"><span>${fmt(r.start)}</span>${ICON.arrow}<span class="sr">${L('to')}</span><span>${fmt(r.end)}</span></span>`;+ const rangeOut = r => r && { start: r.start, end: r.end, scenes: scenes.flatMap((s, i) => s.start < r.end - 1e-9 && s.start + s.dur > r.start + 1e-9 ? [i + 1] : []) };+ // Written shortly after the last change, so scrubbing or typing does not write a file per pointer move or key. The+ // server keeps the notes of the folder's other versions and writes the new note pictures.+ // A note's done state is the file's unless it was changed here (`toggled`), because the agent marks notes done in+ // selection.json while this page is open. The reply, and a read when the page gets focus back, bring those in.+ // Another tab of the viewer can save notes of the same project too, so the page names the notes it deleted instead of+ // leaving them out, and takes in the file's notes after every save and on focus (sync).+ let saveTimer = 0;+ const toggled = new Set(), deleted = new Set(); // done changed here (by number), and notes deleted here (by key)+ const key = m => m.id || `#${m.n}`, uid = () => crypto.randomUUID?.() || Math.random().toString(36).slice(2) + Date.now().toString(36);+ let known = new Set(); // keys of this version's notes in the file at the last sync+ function save() {+ clearTimeout(saveTimer);+ saveTimer = setTimeout(async () => {+ const png = Object.fromEntries(images), sent = [...toggled], gone = [...deleted]; images.clear(); toggled.clear(); deleted.clear();+ try {+ const r = await fetch('selection', { method: 'POST', body: JSON.stringify({ ...sel, range: rangeOut(range), project: '{{project}}', marks: notes, toggled: sent, deleted: gone, images: png }) });+ if (!r.ok) throw new Error(r.status);+ const res = await r.json();+ for (const [id, n] of res.renumbered) { // another tab took this number first: the note moves to the next free one+ const m = notes.find(x => x.id === id); if (!m) continue;+ m.n = n; if (m.image) { m.image = `selection/${n}.png`; images.set(n, snapshot(m)); }+ if (m === active) $('popN').textContent = n;+ save();+ }+ sync(res.marks, res.others);+ } catch { sent.forEach(n => toggled.add(n)); gone.forEach(k => deleted.add(k)); }+ }, 150);+ }+ function sync(file, other) { // this version's notes in the file, and the other versions'+ const inFile = new Map(file.map(m => [key(m), m]));+ let changed = false;+ notes = notes.filter(m => { // in the file at the last sync and gone now: deleted in another tab+ const gone = known.has(key(m)) && !inFile.has(key(m));+ if (gone) { changed = true; if (m === active) { active = null; pop.hidden = true; } }+ return !gone;+ });+ for (const f of file) {+ const m = notes.find(x => key(x) === key(f));+ if (!m) { if (!deleted.has(key(f))) { const { project, ...n } = f; notes.push({ note: '', ...n }); changed = true; } continue; } // made in another tab+ if (!toggled.has(m.n) && !!m.done !== !!f.done) { changed = true; if (m.done) delete m.done; else m.done = true; } // done marked by the agent+ }+ known = new Set(inFile.keys()); others = other;+ if (!changed) return;+ notes.sort((a, b) => a.n - b.n); paint(); listNotes(); drawTimeline(); if (active) doneUI(active);+ }+ const reread = () => document.visibilityState === 'visible' && fetch('selection.json', { cache: 'no-store' }).then(r => r.ok ? r.json() : null)+ .then(s => s && sync((s.marks || []).filter(m => m.project === '{{project}}'), (s.marks || []).filter(m => m.project !== '{{project}}'))).catch(() => {});+ addEventListener('focus', reread); document.addEventListener('visibilitychange', reread);++ // ---- notes: a box or point drawn on the preview, or a range, with a line about what is wrong there. They stay in+ // selection.json (`marks`) until they are deleted, numbered in the order they were made, across all versions.+ const pop = $('pop'), popText = $('popText');+ const where = m => m.range ? `${L('range')} ${fmt(m.range.start)} ${L('to')} ${fmt(m.range.end)}` : L('sceneSecond', m.sceneIndex, m.sceneTime.toFixed(2)); // read out+ const whereHTML = m => m.range ? `${L('range')} ${spanOf(m.range)}` : where(m); // shown+ function place() { // under the box or point, or above the range's tag on the timeline; kept inside the window+ const el = $('marks').querySelector('.mk.on'), M = 12;+ let r;+ if (el) r = el.getBoundingClientRect();+ else if (active?.range && !lane.hidden) {+ const lr = tl.getBoundingClientRect(), x = lr.left + PAD + active.range.start * pps - lane.scrollLeft;+ r = { left: x, top: lr.top + MK_Y - 8, bottom: lr.top + MK_Y + 8 };+ } else { const sr = $('stage').getBoundingClientRect(); r = { left: sr.left + sr.width / 2 - 144, top: sr.bottom - 24, bottom: sr.bottom - 24 }; }+ const w = pop.offsetWidth, h = pop.offsetHeight, below = r.bottom + 8, above = r.top - 8 - h;+ pop.style.left = Math.min(innerWidth - w - M, Math.max(M, r.left)) + 'px';+ // a range note sits above the timeline, so the range stays in view+ pop.style.top = (el ? (below + h <= innerHeight - M ? below : Math.max(M, above)) : (above >= M ? above : below)) + 'px';+ }+ const grow = () => { popText.style.height = 'auto'; popText.style.height = Math.min(160, popText.scrollHeight + 2) + 'px'; };+ function openNote(m) {+ active = m; opening = null;+ $('popN').textContent = m.n; $('popWhere').innerHTML = whereHTML(m); popText.value = m.note; doneUI(m);+ pop.hidden = false; grow(); paint(); place(); listNotes(); drawTimeline();+ popText.focus({ preventScroll: true });+ }+ function doneUI(m) { // a done note says so in the card's head, and its button opens it again+ $('popState').hidden = !m.done; $('popState').innerHTML = ICON.check + L('done');+ $('popDone').innerHTML = m.done ? ICON.undo + L('reopen') : ICON.check + L('markDone');+ }+ function setDone(m, on) { // done: the card closes and the note leaves the preview and the timeline; opened again, it stays open+ if (on) m.done = true; else delete m.done;+ toggled.add(m.n);+ if (on) closeNote(); else { doneUI(m); paint(); listNotes(); drawTimeline(); save(); popText.focus({ preventScroll: true }); }+ }+ function closeNote() {+ if (!active) return;+ active = null; pop.hidden = true; paint(); listNotes(); drawTimeline(); save();+ }+ function deleteNote(m) {+ notes = notes.filter(x => x !== m); images.delete(m.n); deleted.add(key(m));+ if (m === active) { active = null; pop.hidden = true; }+ paint(); listNotes(); drawTimeline(); save();+ }+ const nextN = () => Math.max(0, ...notes.map(m => m.n), ...others.map(m => m.n)) + 1;+ function addNote(extra, time = t) {+ const m = { id: uid(), n: nextN(), note: '', ...spot(time), box: null, point: null, range: null, image: null, ...extra };+ if (m.box || m.point) { m.image = `selection/${m.n}.png`; images.set(m.n, snapshot(m)); }+ notes.push(m); openNote(m); save();+ }+ function goTo(m) { // to the note's frame (and its range), then open it once that frame is on screen+ if (m.range) range = { start: m.range.start, end: m.range.end };+ const here = onFrame(m) || (m.range && !(m.box || m.point));+ seek(m.time);+ if (here) openNote(m); else opening = m;+ }+ // The open notes, then the done ones folded under "Selesai N" (unfolded or not is remembered in this browser), so the+ // list after a round of revisions holds what is left to do.+ let doneOpen = false; try { doneOpen = localStorage.motlabDone === '1'; } catch {}+ function listNotes() {+ const open = notes.filter(m => !m.done), done = notes.filter(m => m.done);+ $('noteCount').textContent = open.length || '';+ const row = m => {+ const li = document.createElement('li'), b = document.createElement('button');+ b.className = 'row' + (m.done ? ' done' : ''); b.innerHTML = '<span class="ic n num" aria-hidden="true"></span><span class="name"><span></span><small class="num"></small></span>';+ b.firstChild.textContent = m.n;+ const text = b.querySelector('.name > span'); text.textContent = m.note.trim() || L('empty'); text.classList.toggle('none', !m.note.trim());+ b.querySelector('small').innerHTML = whereHTML(m);+ b.setAttribute('aria-label', L('noteLabel', m.n, m.done, m.note.trim(), where(m)));+ b.onclick = () => goTo(m); current(b, m === active);+ li.append(b); return li;+ };+ const items = open.map(row);+ if (!notes.length) items.push(Object.assign(document.createElement('li'), { className: 'empty', textContent: L('noNotes') }));+ else if (!open.length) items.push(Object.assign(document.createElement('li'), { className: 'empty', textContent: L('allDone') }));+ if (done.length) {+ const li = document.createElement('li'), b = document.createElement('button');+ b.className = 'row'; b.id = 'doneBtn'; b.setAttribute('aria-expanded', doneOpen);+ b.innerHTML = `<span class="ic" aria-hidden="true">${ICON.down}</span><span class="name">${L('done')} <span class="num"></span></span>`;+ b.querySelector('.num').textContent = done.length;+ b.onclick = () => { doneOpen = !doneOpen; try { localStorage.motlabDone = doneOpen ? '1' : '0'; } catch {} listNotes(); $('doneBtn').focus(); };+ li.append(b); items.push(li);+ if (doneOpen) items.push(...done.map(row));+ }+ $('notes').replaceChildren(...items);+ }+ popText.oninput = () => { active.note = popText.value; grow(); place(); listNotes(); save(); };+ popText.onkeydown = e => {+ if (e.key === 'Enter' && !e.shiftKey && !e.isComposing) { e.preventDefault(); closeNote(); }+ if (e.key === 'Escape') { e.preventDefault(); closeNote(); } // Escape in the note only closes it, the range stays+ };+ $('popOk').onclick = closeNote;+ $('popDel').onclick = () => deleteNote(active);+ $('popDone').onclick = () => setDone(active, !active.done);+ $('rangeNote').onclick = () => { addNote({ range: rangeOut(range) }, range.start); showSelection(); };+ $('rangeOff').onclick = () => unrange();+ function seek(time, audio) {+ t = Math.min(total, Math.max(0, time));+ select(t, audio); save();+ if (playing) { pause(); play(false); }+ reveal(); showSelection(); show();+ }++ const scrub = e => {+ const r = tl.getBoundingClientRect(), y = e.clientY - r.top;+ seek((e.clientX - r.left + lane.scrollLeft - PAD) / pps, y >= AY ? tracks[Math.floor((y - AY) / (AH + GAP))] : null);+ };+ // A range: Shift+drag on the timeline, or I and O at the playhead. Its edges can be dragged, and Escape takes it off.+ // Its ends sit on the frame grid.+ const snap = time => Math.min(total, Math.max(0, Math.round(time * fps) / fps));+ const timeAt = e => snap((e.clientX - tl.getBoundingClientRect().left + lane.scrollLeft - PAD) / pps);+ const edgeAt = e => {+ if (!range) return null;+ const x = e.clientX - tl.getBoundingClientRect().left + lane.scrollLeft - PAD;+ return Math.abs(x - range.start * pps) <= 5 ? 'start' : Math.abs(x - range.end * pps) <= 5 ? 'end' : null;+ };+ function setRange(a, b, done) {+ range = { start: +Math.min(a, b).toFixed(3), end: +Math.max(a, b).toFixed(3) };+ if (done) { if (range.end - range.start < 0.5 / fps) range = null; if (!sel) select(t, null); save(); showSelection(); } else drawTimeline();+ }+ let rangeDrag = null, rangeMode = false;+ function setRangeMode(on) {+ rangeMode = on; $('rangeBtn').classList.toggle('hot', on); $('rangeBtn').setAttribute('aria-pressed', on);+ if (on && lane.hidden) setLane(true);+ if (on) note(L('rangeHow')); else $('note').hidden = true;+ }+ $('rangeBtn').onclick = () => setRangeMode(!rangeMode);+ const tagAt = e => { // the note tag under the pointer, if any+ const r = tl.getBoundingClientRect(), x = e.clientX - r.left, y = e.clientY - r.top;+ return Math.abs(y - MK_Y) <= 9 ? hits.findLast(h => x >= h.x0 - 2 && x <= h.x1 + 2)?.m : null;+ };+ tl.onpointerdown = e => {+ if (e.button !== 0) return;+ const tag = tagAt(e);+ if (tag) return goTo(tag);+ const edge = edgeAt(e);+ if (!e.shiftKey && !edge && !rangeMode) return scrub(e);+ tl.setPointerCapture(e.pointerId);+ rangeDrag = edge ? (edge === 'start' ? range.end : range.start) : timeAt(e);+ setRange(rangeDrag, timeAt(e), false);+ };+ tl.onpointermove = e => {+ if (rangeDrag !== null) return setRange(rangeDrag, timeAt(e), false);+ if (!e.buttons) { tl.style.cursor = edgeAt(e) ? 'ew-resize' : tagAt(e) ? 'default' : rangeMode ? 'col-resize' : ''; return; }+ scrub(e);+ };+ tl.onpointerup = tl.onpointercancel = () => { if (rangeDrag === null) return; rangeDrag = null; setRange(range.start, range.end, true); if (rangeMode) setRangeMode(false); };+ addEventListener('keydown', e => { // I and O mark the start and the end of the range at the playhead+ if (e.ctrlKey || e.metaKey || e.altKey || e.target.closest?.('input, textarea')) return;+ const k = e.key.toLowerCase(), at = snap(t);+ if (k === 'r') setRangeMode(!rangeMode); // R picks the range tool, as in Final Cut Pro+ if (k === 'x') { const s = sceneAt(t); setRange(snap(s.start), snap(s.start + s.dur), true); } // X: the scene under the playhead, as Mark Clip+ if (k === 'i') setRange(at, range && range.end > at ? range.end : total, true);+ else if (k === 'o') setRange(range && range.start < at ? range.start : 0, at, true);+ });+ tl.onkeydown = e => { // arrows move one frame, Shift+arrows one second; the selected row stays selected; + and - zoom+ if (e.key === '+' || e.key === '=') return setZoom(zoom * 2);+ if (e.key === '-') return setZoom(zoom / 2);+ if (e.key === '0') return setZoom(1);+ const step = e.shiftKey ? 1 : 1 / fps, to = { ArrowLeft: t - step, ArrowRight: t + step, Home: 0, End: total }[e.key];+ if (to === undefined) return;+ e.preventDefault(); seek(to, sel?.audio ? tracks[sel.audio.index] : null);+ };++ let drag = null;+ // The cursor follows the brightness of the frame under it: a 64-cell-wide copy of the frame is read once per frame,+ // on the first pointer move after the frame changed, so playback costs nothing extra.+ const LW = 64, LH = Math.max(1, Math.round(LW * view.height / view.width)), lumaCanvas = Object.assign(document.createElement('canvas'), { width: LW, height: LH });+ const lumaCtx = lumaCanvas.getContext('2d', { willReadFrequently: true });+ const tone = e => {+ if (!luma) { lumaCtx.drawImage(clean, 0, 0, LW, LH); luma = lumaCtx.getImageData(0, 0, LW, LH).data; }+ const r = view.getBoundingClientRect(), x = Math.min(LW - 1, Math.max(0, Math.floor((e.clientX - r.left) / r.width * LW))), y = Math.min(LH - 1, Math.max(0, Math.floor((e.clientY - r.top) / r.height * LH)));+ const i = (y * LW + x) * 4;+ const lin = c => (c /= 255) <= 0.04045 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4; // relative luminance, as in WCAG contrast+ // below 0.179 white has more contrast than the dark cursor, above it the dark one does+ view.classList.toggle('on-dark', 0.2126 * lin(luma[i]) + 0.7152 * lin(luma[i + 1]) + 0.0722 * lin(luma[i + 2]) < 0.179);+ };+ view.addEventListener('pointerenter', tone); view.addEventListener('pointermove', tone);+ const onView = e => { // pointer position in the scene's own pixels (the page at ?scale=1)+ const r = view.getBoundingClientRect();+ return { x: Math.min(view.width, Math.max(0, (e.clientX - r.left) * view.width / r.width)), y: Math.min(view.height, Math.max(0, (e.clientY - r.top) * view.height / r.height)) };+ };+ const hit = p => { // the note on this frame under the pointer, the last made first+ const k = view.getBoundingClientRect().width / view.width;+ return openNotes().filter(onFrame).findLast(m => m.box ? p.x >= m.box.x && p.x <= m.box.x + m.box.w && p.y >= m.box.y && p.y <= m.box.y + m.box.h+ : Math.hypot(p.x - m.point.x, p.y - m.point.y) <= (PT / 2 + 2) / k);+ };+ // A drag on the preview draws a box and a click marks a point; either one is a new note, opened for typing. A click+ // on a note opens it, and a click while a note is open only closes it.+ view.onpointerdown = e => {+ if (e.button !== 0 || !cur) return;+ if (playing) pause();+ view.setPointerCapture(e.pointerId);+ drag = { a: onView(e), x: e.clientX, y: e.clientY, moved: false, open: !!active };+ };+ view.onpointermove = e => {+ if (!drag || (!drag.moved && Math.hypot(e.clientX - drag.x, e.clientY - drag.y) < 4)) return;+ if (!drag.moved) closeNote();+ const a = drag.a, b = onView(e); drag.moved = true;+ draft = { box: { x: Math.round(Math.min(a.x, b.x)), y: Math.round(Math.min(a.y, b.y)), w: Math.round(Math.abs(b.x - a.x)), h: Math.round(Math.abs(b.y - a.y)) } };+ paint();+ };+ view.onpointerup = () => {+ if (!drag) return;+ const d = drag; drag = null;+ if (d.moved) {+ const { box } = draft; draft = null;+ if (box.w < 2 || box.h < 2) return paint();+ select(t, null); addNote({ box }); return showSelection();+ }+ const m = hit(d.a);+ if (m) return m === active ? undefined : openNote(m);+ if (d.open) return closeNote();+ select(t, null); addNote({ point: { x: Math.round(d.a.x), y: Math.round(d.a.y) } }); showSelection();+ };+ view.onpointercancel = () => { drag = draft = null; paint(); };+ // Escape (unless it just closed a menu) closes the open note, else leaves range marking, else takes the range off. A click on the empty grey+ // space around the preview closes the note. Notes are only deleted with Hapus.+ const unrange = () => { if (!range) return; range = null; save(); showSelection(); };+ addEventListener('keydown', e => { if (e.key === 'Escape' && !e.defaultPrevented) active ? closeNote() : rangeMode ? setRangeMode(false) : unrange(); });+ $('canvas').addEventListener('pointerdown', e => { if (e.button === 0 && (e.target === $('stage') || e.target === $('canvas'))) closeNote(); });++ $('play').onclick = () => playing ? pause() : play();+ $('prev').onclick = () => { const s = sceneAt(t), i = scenes.indexOf(s); seek(t - s.start > 0.5 || !i ? s.start : scenes[i - 1].start); };+ $('next').onclick = () => { const n = scenes[scenes.indexOf(sceneAt(t)) + 1]; if (n) seek(n.start); };+ addEventListener('keydown', e => { // Space plays, except on a button or link, where Space presses that control+ if (e.code !== 'Space' || e.target.closest?.('button, a, input, textarea, select')) return;+ e.preventDefault(); $('play').click();+ });++ // ---- export: the server renders the project at the chosen size and streams its log back+ const short = Math.min(view.width, view.height), RES = [[720, '720p'], [1080, '1080p'], [1440, '1440p'], [2160, '4K']];+ let pick = 2160; try { pick = +localStorage.motlabRes || 2160; } catch {}+ if (!RES.some(r => r[0] === pick)) pick = 2160;+ for (const [p, text] of RES) {+ const b = document.createElement('button'); b.className = 'opt';+ b.innerHTML = `<span>${text}</span><span class="dim num">${Math.round(view.width * p / short)}×${Math.round(view.height * p / short)}</span>`;+ b.onclick = () => choose(p);+ $('res').append(b);+ }+ function choose(p) { // the button names the size it will export, so the choice is visible without the menu+ pick = p; try { localStorage.motlabRes = p; } catch {}+ [...$('res').children].forEach((o, i) => { o.classList.toggle('on', RES[i][0] === p); o.setAttribute('aria-pressed', RES[i][0] === p); });+ $('go').textContent = `Export ${RES.find(r => r[0] === p)[1]}`;+ }+ choose(pick);+ const status = (main, sub, link) => { // one line, an optional muted second line, an optional link at the end of the first+ $('xs').hidden = false; $('xs').replaceChildren();+ const line = document.createElement('span'); line.className = 'line'; line.append(main);+ if (link) { const a = document.createElement('a'); a.href = encodeURI(link); a.target = '_blank'; a.textContent = L('open'); line.append(a); }+ $('xs').append(line);+ if (sub) { const s = document.createElement('span'); s.className = link ? 'sub' : 'sub wrap'; s.textContent = sub; s.dataset.tip = sub; $('xs').append(s); }+ };+ $('stop').onclick = () => { // the running export's own response then ends with CANCELLED+ $('stop').disabled = true; $('stop').textContent = L('cancelling'); status(L('cancelling'));+ fetch('/export/cancel', { method: 'POST' }).catch(() => {}); // the server's route, not one under /p/<project>/: there is one export at a time+ };+ $('go').onclick = async () => {+ const [p, text] = RES.find(r => r[0] === pick), icon = $('export').firstElementChild;+ $('res').inert = true; $('go').disabled = true; $('go').setAttribute('aria-busy', 'true');+ $('go').innerHTML = `<span class="spin" aria-hidden="true"></span><span>${L('exporting', text)}…</span>`;+ $('stop').hidden = false; $('stop').disabled = false; $('stop').textContent = L('cancel');+ $('exportLabel').textContent = L('exporting', text);+ icon.outerHTML = '<span class="spin" aria-hidden="true"></span>'; status(L('preparing'));+ try {+ const res = await fetch('export', { method: 'POST', body: JSON.stringify({ project: '{{project}}', scale: p / short, tag: p + 'p' }) });+ if (!res.ok) throw new Error(res.status === 409 ? L('busy') : await res.text());+ const reader = res.body.pipeThrough(new TextDecoderStream()).getReader(); let log = '';+ for (;;) {+ const { done, value } = await reader.read(); if (done) break;+ log += value;+ const m = [...log.matchAll(/Scene (\d+)\/(\d+)/g)].at(-1);+ if (m && !$('stop').disabled) status(L('sceneOf', m[1], m[2]));+ }+ const end = log.trim().split('\n').at(-1);+ if (end === 'CANCELLED') status(L('cancelled'));+ else {+ if (!end.startsWith('DONE ')) throw new Error(end.replace(/^ERROR /, '') || L('noResult'));+ const [, file, secs] = end.match(/^DONE (.+) (\d+)$/);+ status(L('doneIn', secs), file, file);+ }+ } catch (e) { status(L('failed'), L('seeLog', e.message)); }+ $('res').inert = false; $('stop').hidden = true;+ $('go').disabled = false; $('go').removeAttribute('aria-busy'); choose(pick); $('exportLabel').textContent = 'Export';+ $('export').firstElementChild.outerHTML = ICON.export;+ setMenu($('export'), $('exportMenu'), true);+ };++ // ---- first paint: the last saved selection if there is one+ sel = await fetch('selection.json').then(r => r.ok ? r.json() : null).catch(() => null);+ const saved = Array.isArray(sel?.marks) ? sel.marks : []; // notes of every version in this folder+ others = saved.filter(m => m.project !== '{{project}}');+ notes = saved.filter(m => m.project === '{{project}}').map(({ project, ...m }) => ({ note: '', ...m }));+ known = new Set(notes.map(key));+ if (sel) { delete sel.marks; delete sel.box; delete sel.point; } // box and point are from before notes+ if (sel?.project && sel.project !== '{{project}}') sel = null; // the last click was in another project file of this folder+ if (sel) t = Math.min(total, sel.time);+ if (sel?.range && sel.range.end > sel.range.start && sel.range.start < total) range = { start: sel.range.start, end: Math.min(total, sel.range.end) };+ await document.fonts.load(`11px ${FONT}`).catch(() => {}); // the canvas cannot redraw itself when the web font arrives+ setLane(!lane.hidden); setPlay(false); listNotes(); showSelection(); show();+ new ResizeObserver(() => { layout(); drawTimeline(); }).observe(lane);+} catch (e) {+ $('view').hidden = $('lane').hidden = $('bar').hidden = true; $('msg').hidden = false;+ $('msg').textContent = e.hint ? e.message : L('loadFailed', e.message);+ if (!$('scenes').children.length) $('scenes').innerHTML = `<li class="empty">${L('noScenesYet')}</li>`;+ if (!e.hint) throw e;+}+</script>+</body></html>diff --git a/src/editor.js b/src/editor.jsnew file mode 100644index 0000000..6486692--- /dev/null+++ b/src/editor.js@@ -0,0 +1,213 @@+// Viewer for projects: serves the editor page and the projects' files, saves the last click to selection.json, and+// renders a project when the page's Export button asks for it.+// One server holds many projects, each under /p/<slug>/: the one it was started with, the project folders in the+// folder it was started from (the workspace), and the projects opened before (~/.motlab/recent.json). A second+// `motlab edit` adds its project to a viewer that is already running instead of starting another one.+// A project is a folder with project.json, or a project file in it (video/storyboard.json), so a storyboard and the+// finished video can share one folder and its assets.+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, resolve, sep } from 'node:path';+import { projectPaths, renderProject } from './project.js';+import { pageLib, sendFile } from './server.js';++const RECENT = join(homedir(), '.motlab', 'recent.json');+const SKIP = new Set(['node_modules', 'out', 'backup']);+const readRecent = () => { try { return JSON.parse(readFileSync(RECENT, 'utf8')).filter(f => typeof f === 'string'); } catch { return []; } };+function remember(file) { // newest first; a missing or unwritable file only means the list is not remembered+ try { mkdirSync(dirname(RECENT), { recursive: true }); writeFileSync(RECENT, JSON.stringify([file, ...readRecent().filter(f => f !== file)].slice(0, 30), null, 2)); } catch {}+}+// project.json files under `dir`, a few levels down. A project's own folders are not searched, and the walk stops after+// a few thousand folders, so starting it in a home folder stays quick.+function scan(dir, depth = 4, found = [], budget = { n: 3000 }) {+ let list; try { list = readdirSync(dir, { withFileTypes: true }); } catch { return found; }+ if (list.some(e => e.isFile() && e.name === 'project.json')) { found.push(join(dir, 'project.json')); return found; }+ if (depth) for (const e of list) if (e.isDirectory() && !e.name.startsWith('.') && !SKIP.has(e.name) && budget.n-- > 0) scan(join(dir, e.name), depth - 1, found, budget);+ return found;+}+// The versions of a project: the .json files in its folder with a list of scenes. project.json is "Utama", and+// project-tiktok.json is "tiktok".+const label = file => file === 'project.json' ? 'Utama' : file.replace(/\.json$/i, '').replace(/^project-/, '');+function versions(root) {+ const out = [];+ for (const f of readdirSync(root)) {+ if (!/\.json$/i.test(f) || f === 'selection.json') continue;+ try { if (Array.isArray(JSON.parse(readFileSync(join(root, f), 'utf8')).scenes)) out.push({ file: f, label: label(f) }); } catch {}+ }+ return out.sort((a, b) => (b.file === 'project.json') - (a.file === 'project.json') || a.label.localeCompare(b.label));+}+// One page's save of version v's notes, merged into the notes in selection.json (`old`). A page sends the notes it holds+// and names the ones it deleted, so a note it has not seen (made in another tab of the viewer) is kept rather than+// dropped. A note is known by its `id` (notes from before ids, by `n`). A new note whose number another tab took meanwhile+// gets the next free one: `renumbered` lists [id, old n, new n]. `done` is the file's unless the page changed it+// (`toggled`), because the agent marks notes done in the file while the page is open.+export function mergeNotes(old, { marks = [], toggled = [], deleted = [] }, v) {+ const key = m => m.id || `#${m.n}`, sent = new Set(marks.map(key)), gone = new Set(deleted);+ const was = new Map(old.filter(m => m.project === v).map(m => [key(m), m]));+ const kept = old.filter(m => m.project !== v || (!sent.has(key(m)) && !gone.has(key(m))));+ const taken = new Set(kept.map(m => m.n)), renumbered = [];+ let next = Math.max(0, ...old.map(m => m.n), ...marks.map(m => m.n)) + 1;+ const mine = marks.map(({ done, ...m }) => {+ const d = toggled.includes(m.n) || !was.has(key(m)) ? done : was.get(key(m)).done;+ if (taken.has(m.n)) { renumbered.push([m.id, m.n, next]); m = { ...m, n: next, ...(m.image ? { image: `selection/${next}.png` } : {}) }; next++; }+ taken.add(m.n);+ return { ...m, ...(d ? { done: true } : {}), project: v };+ });+ return { all: [...kept, ...mine].sort((a, b) => a.n - b.n), renumbered };+}++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) {+ 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('/');+ return r && !r.startsWith('..') && !isAbsolute(r) ? slash(r) : h && !h.startsWith('..') && !isAbsolute(h) ? '~/' + slash(h) : slash(dir);+ };+ function register(target) { // the slug of a project, added if it is new; throws if there is no project file+ const { root, file } = projectPaths(target);+ for (const [slug, p] of projects) if (p.root.toLowerCase() === root.toLowerCase()) return slug;+ const base = basename(root).toLowerCase().replace(/[^a-z0-9._-]+/g, '-') || 'project';+ let slug = base; for (let i = 2; projects.has(slug); i++) slug = `${base}-${i}`;+ projects.set(slug, { root, file });+ return slug;+ }+ function list() { // looked up again on every request, so a project made while the viewer runs shows up+ for (const f of [...scan(workspace), ...readRecent()]) try { register(f); } catch {}+ return [...projects].filter(([, p]) => existsSync(p.file)).map(([slug, p]) => ({ slug, name: basename(p.root), path: show(p.root) }))+ .sort((a, b) => a.name.localeCompare(b.name) || a.path.localeCompare(b.path));+ }+ const opened = target ? register(target) : null;+ if (opened) remember(projects.get(opened).file);++ let exporting = false;+ const server = createServer(async (req, res) => {+ const url = new URL(req.url, 'http://x'), path = decodeURIComponent(url.pathname);+ // 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 (path === '/__motlab/editor') return json(res, { motlab: 'editor', pid: process.pid, workspace }); // 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();+ setTimeout(() => process.exit(0), exporting ? 1500 : 100);+ return;+ }+ if (path === '/') {+ const first = opened || list()[0]?.slug;+ if (first) return res.writeHead(302, { Location: `/p/${first}/` }).end();+ return res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8' }).end(`No motlab project in ${workspace} yet. Run motlab edit <project folder>.`);+ }+ if (path === '/projects') return json(res, { workspace: show(workspace), projects: list() });+ if (req.method === 'POST' && path === '/open') { // body: { file }, from a second `motlab edit`+ try { const { file } = JSON.parse(await readBody(req)), slug = register(file); remember(projects.get(slug).file); return json(res, { url: `/p/${slug}/` }); }+ catch (e) { return res.writeHead(400).end(e.message); }+ }+ if (req.method === 'POST' && path === '/export/cancel') { // stops the running export; its /export response then ends with CANCELLED+ if (exporting) exporting.abort();+ return res.writeHead(204).end();+ }+ const lib = pageLib(path);+ if (lib) return sendFile(req, res, lib);+ const m = /^\/p\/([^/]+)(\/.*)?$/.exec(path);+ if (!m) return res.writeHead(404).end();+ if (!projects.has(m[1])) list(); // the viewer was restarted and the page reloaded+ const p = projects.get(m[1]);+ if (!p) return res.writeHead(404).end();+ if (!m[2]) return res.writeHead(301, { Location: `/p/${m[1]}/` }).end(); // the page loads everything relative to this+ // The version comes as ?v= for the page and as `project` in the body of a write; anything that is not one of the+ // project's versions falls back to the file the project was opened with.+ const { root } = p, sub = m[2], all = versions(root);+ const version = f => all.some(v => v.file === f) ? f : basename(p.file);++ if (sub === '/versions' && req.method === 'GET') return json(res, all);+ if (sub === '/versions' && req.method === 'POST') { // body: { from, name }; a copy of `from` as project-<name>.json+ try {+ const { from, name } = JSON.parse(await readBody(req)), slug = String(name || '').toLowerCase().trim().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '');+ if (!slug) return res.writeHead(400).end('A version name needs letters or numbers.');+ const to = `project-${slug}.json`;+ if (existsSync(join(root, to))) return res.writeHead(409).end(`${to} already exists.`);+ copyFileSync(join(root, version(from)), join(root, to));+ return json(res, { file: to, label: label(to) });+ } catch (e) { return res.writeHead(400).end(e.message); }+ }+ if (req.method === 'POST' && sub === '/selection') { // the last click, the range and this version's notes+ try {+ // `images` holds a PNG (data URL) per new note with a box or point: that frame with the note drawn on it, saved+ // as selection/<n>.png. Pictures of deleted notes are removed. The notes are merged by mergeNotes, and the reply+ // gives the page the file's notes, so it picks up notes from other tabs and done marks from the agent.+ const { images = {}, project, marks = [], toggled = [], deleted = [], png, ...sel } = JSON.parse(await readBody(req)), v = version(project), file = join(root, 'selection.json');+ let old = []; try { old = JSON.parse(readFileSync(file, 'utf8')).marks || []; } catch {}+ const { all, renumbered } = mergeNotes(old, { marks, toggled, deleted }, v), moved = new Set(renumbered.map(([, from]) => String(from)));+ writeFileSync(file, JSON.stringify({ project: v, ...sel, marks: all }, null, 2));+ const dir = join(root, 'selection'), keep = new Set(all.filter(m => m.image).map(m => `${m.n}.png`));+ for (const [n, data] of Object.entries(images)) {+ if (!keep.has(`${n}.png`) || moved.has(n)) continue; // a renumbered note's picture shows its old number; the page sends a new one+ mkdirSync(dir, { recursive: true }); writeFileSync(join(dir, `${n}.png`), Buffer.from(data.slice(data.indexOf(',') + 1), 'base64'));+ }+ if (existsSync(dir)) for (const f of readdirSync(dir)) if (/^\d+\.png$/.test(f) && !keep.has(f)) rmSync(join(dir, f), { force: true });+ rmSync(join(root, 'selection.png'), { force: true }); // the single picture from before notes+ return json(res, { renumbered: renumbered.map(([id, , n]) => [id, n]), marks: all.filter(m => m.project === v), others: all.filter(m => m.project !== v) });+ } catch (e) { return res.writeHead(400).end(e.message); }+ }+ if (req.method === 'POST' && sub === '/export') { // body: { project, scale, tag }; the render log is streamed back, last line DONE, CANCELLED or ERROR+ if (exporting) return res.writeHead(409).end('another export is still running');+ exporting = new AbortController();+ const started = Date.now(), { signal } = exporting, body = await readBody(req);+ res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8', 'Cache-Control': 'no-store' });+ try {+ const { project, scale, tag } = JSON.parse(body), file = join(root, version(project));+ const rel = `out/${projectPaths(file).name}-${String(tag).replace(/\W/g, '')}.mp4`; // out/example-tiktok-1080p.mp4+ await renderProject({ dir: file, out: join(root, rel), scale: Number(scale) || 2, signal, log: line => { console.log(line); res.write(line + '\n'); } });+ res.end(`DONE ${rel} ${Math.round((Date.now() - started) / 1000)}\n`);+ } catch (e) {+ if (signal.aborted) { console.log('\nExport cancelled'); res.end('CANCELLED\n'); }+ else { console.error(e); res.end(`ERROR ${e.message.split('\n')[0]}\n`); }+ }+ exporting = false;+ return;+ }+ if (sub === '/') { // read on every request, so a reload picks up edits to the editor itself+ res.writeHead(200, { 'Content-Type': 'text/html', 'Cache-Control': 'no-store' });+ const file = version(url.searchParams.get('v'));+ const fill = { name: basename(root), project: file, version: label(file), slug: m[1] };+ return res.end(readFileSync(new URL('./editor.html', import.meta.url), 'utf8').replace(/\{\{(\w+)\}\}/g, (all, k) => fill[k] ?? all));+ }+ const asset = join(root, sub);+ if (!asset.startsWith(root + sep) || !existsSync(asset) || statSync(asset).isDirectory()) return res.writeHead(404).end();+ sendFile(req, res, asset);+ });++ // A viewer already on the port takes this project and the command ends; something else on the port, or an older+ // viewer, means the next free port.+ const handOver = async at => {+ const r = await fetch(`http://127.0.0.1:${at}/__motlab/editor`, { signal: AbortSignal.timeout(1500) }).then(r => r.json()).catch(() => null);+ if (r?.motlab !== 'editor') return null;+ if (!opened) return `http://127.0.0.1:${at}`;+ const o = await fetch(`http://127.0.0.1:${at}/open`, { method: 'POST', body: JSON.stringify({ file: projects.get(opened).file }) });+ if (!o.ok) throw new Error(await o.text());+ return `http://127.0.0.1:${at}${(await o.json()).url}`;+ };+ return new Promise((ok, no) => {+ server.on('error', async e => {+ if (e.code !== 'EADDRINUSE' || port > 4190) return no(e);+ try {+ const there = await handOver(port);+ if (there) { console.log(`Editor: ${there} (in the viewer that is already running)`); return ok('joined'); }+ } catch (err) { return no(err); }+ server.listen(++port, '127.0.0.1');+ });+ server.on('listening', () => {+ const n = list().length;+ console.log(`Editor: http://127.0.0.1:${port}${opened ? `/p/${opened}/ (${projects.get(opened).file})` : ''}`);+ 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/ffmpeg.js b/src/ffmpeg.jsnew file mode 100644index 0000000..427ac73--- /dev/null+++ b/src/ffmpeg.js@@ -0,0 +1,43 @@+// ffmpeg is only used to stream-copy: join parallel segments, add audio, wrap a raw bitstream. It never re-encodes video.+import { spawn } from 'node:child_process';+import { writeFileSync } from 'node:fs';+import { join } from 'node:path';++export function run(cmd, args, signal) { // signal: an AbortSignal that kills the process+ return new Promise((ok, no) => {+ const p = spawn(cmd, args, { stdio: ['ignore', 'pipe', 'pipe'], signal });+ let out = '', err = '';+ p.stdout.on('data', d => out += d); p.stderr.on('data', d => err += d);+ p.on('error', e => no(e.name === 'AbortError' ? signal.reason : new Error(`${cmd} could not start: ${e.message}`)));+ p.on('close', code => code === 0 ? ok(out) : no(new Error(`${cmd} exited with ${code}: ${err.trim().split('\n').slice(-6).join('\n')}`)));+ });+}++// BT.709, limited range, written into the bitstream itself (VUI) so the tag survives any later remux.+const VUI = 'colour_primaries=1:transfer_characteristics=1:matrix_coefficients=1:video_full_range_flag=0';++// inputs: MP4 segments (one or more) or one raw Annex B file. Output: a fast-start MP4, optionally with audio.+export async function finalize({ inputs, raw, codec, fps, audio, out, duration, tmp, signal }) {+ const args = ['-y', '-loglevel', 'error'];+ if (raw) args.push('-f', codec === 'hevc' ? 'hevc' : 'h264', '-framerate', String(fps), '-i', inputs[0]);+ else if (inputs.length === 1) args.push('-i', inputs[0]);+ else {+ const list = join(tmp, 'concat.txt');+ writeFileSync(list, inputs.map(p => `file '${p.replaceAll('\\', '/').replaceAll("'", "'\\''")}'`).join('\n') + '\n');+ args.push('-f', 'concat', '-safe', '0', '-i', list);+ }+ if (audio) args.push('-i', audio, '-map', '0:v:0', '-map', '1:a:0', '-c:a', 'aac', '-b:a', '320k', '-t', duration.toFixed(6));+ else args.push('-map', '0:v:0');+ args.push('-c:v', 'copy', '-bsf:v', `${codec === 'hevc' ? 'hevc' : 'h264'}_metadata=${VUI}`,+ '-color_primaries', 'bt709', '-color_trc', 'bt709', '-colorspace', 'bt709', '-color_range', 'tv',+ ...(codec === 'hevc' ? ['-tag:v', 'hvc1'] : []), '-movflags', '+faststart', '-f', 'mp4', out);+ await run('ffmpeg', args, signal);+}++export async function probeVideo(file) {+ const out = await run('ffprobe', ['-v', 'error', '-select_streams', 'v:0', '-count_packets', '-show_entries',+ 'stream=codec_name,profile,width,height,pix_fmt,color_range,color_space,color_transfer,color_primaries,r_frame_rate,avg_frame_rate,nb_frames,nb_read_packets,duration:format=duration,size',+ '-of', 'json', file]);+ const j = JSON.parse(out), s = j.streams[0];+ return { ...s, frames: Number(s.nb_read_packets), duration: Number(s.duration), formatDuration: Number(j.format.duration), size: Number(j.format.size) };+}diff --git a/src/page/cuts.js b/src/page/cuts.jsnew file mode 100644index 0000000..7521e04--- /dev/null+++ b/src/page/cuts.js@@ -0,0 +1,59 @@+// Cut lists for footage, served at /__motlab/cuts.js. Pure code: it draws frames it gets from openFootage().+import { clamp, ease, lerp } from './motion.js';++// A cut list over one recording: the parts to keep, played back to back. Made for talking heads with many jump+// cuts (skills/motlab/scripts/cut_pauses.py writes the list from the pauses in the voice).+//+// const { cutList } = await import('/__motlab/cuts.js');+// const cuts = await (await fetch('../cuts.json')).json(); // { segments: [{ from, to }, ...], dissolve }+// const edit = cutList(cuts, clip, { punch: [1, 1.12], glide: 0.2, drift: 0.01, x: 0.5, y: 0.4 });+// await edit.draw(ctx, t, 0, 0, W, H); // the frame at t seconds into the edit+//+// Each part is framed by its zoom (from the segment, else the next value of `punch`, so jump cuts alternate between+// a wide and a closer framing) around the point x, y (fractions of the frame; a segment may set its own). `glide` eases+// from the previous part's zoom over that many seconds after a cut instead of jumping, and `drift` pushes in slowly+// (per second) so a part is never still. With `dissolve` (seconds, from the cut list or the options) parts overlap and+// fade into each other; that needs a second decoder of the same file as `clip2`, because both parts are drawn at once.+// edit.toOut(seconds in the file) gives the time in the edit, for words from a transcript of the recording.+export function cutList(cuts, clip, { clip2 = null, punch = [1], glide = 0, drift = 0, x = 0.5, y = 0.5, dissolve, ease: easing = 'inOutCubic' } = {}) {+ const list = Array.isArray(cuts) ? cuts : cuts.segments, D = dissolve ?? cuts.dissolve ?? 0;+ if (!list?.length) throw new Error('cutList: no segments');+ if (D > 0 && !clip2) throw new Error('cutList: a dissolve needs clip2, a second openFootage() of the same file');+ let at = 0;+ const parts = list.map((s, i) => {+ const len = s.to - s.from;+ if (!(len > D)) throw new Error(`cutList: segment ${i + 1} (${s.from} to ${s.to}) is not longer than the dissolve`);+ const p = { from: s.from, to: s.to, len, at, zoom: s.zoom ?? punch[i % punch.length], x: s.x ?? x, y: s.y ?? y };+ at += len - D; return p;+ });+ const duration = at + D, E = ease[easing];+ const index = t => { let k = 0; while (k + 1 < parts.length && parts[k + 1].at <= t + 1e-9) k++; return k; };+ const zoomAt = (k, t) => { // the zoom of part k at edit time t+ const p = parts[k], into = t - p.at, z = k && glide > 0 ? lerp(parts[k - 1].zoom, p.zoom, E(clamp(into / glide))) : p.zoom;+ return z * (1 + drift * into);+ };+ async function drawPart(ctx, k, t, alpha, dx, dy, dw, dh) {+ const p = parts[k], c = D > 0 ? [clip, clip2][k % 2] : clip, f = await c.frame(p.from + (t - p.at));+ const s = Math.max(dw / c.width, dh / c.height) * zoomAt(k, t), w = c.width * s, h = c.height * s;+ const ox = clamp(dx + dw / 2 - p.x * w, dx + dw - w, dx), oy = clamp(dy + dh / 2 - p.y * h, dy + dh - h, dy); // never shows an edge+ ctx.save(); ctx.beginPath(); ctx.rect(dx, dy, dw, dh); ctx.clip(); ctx.globalAlpha = alpha;+ f.draw(ctx, ox, oy, w, h); ctx.restore();+ }+ return {+ duration, parts,+ at(t) { const k = index(t), p = parts[k]; return { index: k, src: p.from + (t - p.at), zoom: zoomAt(k, t) }; },+ toOut(src) {+ for (const p of parts) { if (src < p.from) return p.at; if (src <= p.to) return p.at + (src - p.from); }+ return duration;+ },+ async draw(ctx, t, dx, dy, dw, dh) {+ t = clamp(t, 0, duration - 1e-6);+ const k = index(t), into = t - parts[k].at;+ if (k && D > 0 && into < D) { // the end of the part before, then this part fading in over it+ await drawPart(ctx, k - 1, t, 1, dx, dy, dw, dh);+ return drawPart(ctx, k, t, E(into / D), dx, dy, dw, dh);+ }+ return drawPart(ctx, k, t, 1, dx, dy, dw, dh);+ },+ };+}diff --git a/src/page/footage.js b/src/page/footage.jsnew file mode 100644index 0000000..92475f2--- /dev/null+++ b/src/page/footage.js@@ -0,0 +1,38 @@+// Footage for scene pages: decodes a video file inside the page with Mediabunny (WebCodecs), one frame per renderAt.+// Served by the render server and the viewer at /__motlab/footage.js, so a scene page imports it the same way in both:+//+// const { openFootage } = await import('/__motlab/footage.js');+// const clip = await openFootage('clips/demo.mp4'); // path relative to the page, like an <img src>+// const f = await clip.frame(t); // the frame shown at t seconds into the file+// f.draw(ctx, 0, 0, W, H); // or f.toCanvasImageSource() for a WebGL texture+//+// A frame stays valid until the next clip.frame() call. Rotation metadata (phone footage) is applied by f.draw.+// Sequential calls (render, playback) decode each frame once; a jump backwards or far ahead seeks from a keyframe.+import * as MB from './mediabunny.mjs';++export async function openFootage(path) {+ const url = new URL(path, document.baseURI);+ const input = new MB.Input({ source: new MB.UrlSource(url), formats: MB.ALL_FORMATS });+ const track = await input.getPrimaryVideoTrack();+ if (!track) throw new Error(`${path} has no video track`);+ if (!(await track.canDecode())) throw new Error(`${path}: this browser cannot decode ${track.codec}`);+ const sink = new MB.VideoSampleSink(track), first = await track.getFirstTimestamp(), duration = await track.computeDuration() - first;++ let it = null, cur = null, next = null;+ const pull = async () => { const r = await it.next(); return r.done ? null : r.value; };+ async function seek(at) {+ await it?.return(); cur?.close(); next?.close();+ it = sink.samples(at); cur = await pull(); next = cur && await pull();+ }+ return {+ width: track.displayWidth, height: track.displayHeight, duration,+ async frame(t) {+ const at = first + Math.min(Math.max(0, t), Math.max(0, duration - 1e-6));+ if (!cur || at < cur.timestamp || (next && at > next.timestamp + 1)) await seek(at);+ while (next && next.timestamp <= at + 1e-6) { cur.close(); cur = next; next = await pull(); }+ if (!cur) throw new Error(`${path}: no frame at ${t.toFixed(3)} s`);+ return cur;+ },+ close() { it?.return(); cur?.close(); next?.close(); input.dispose(); },+ };+}diff --git a/src/page/motion.js b/src/page/motion.jsnew file mode 100644index 0000000..4932b39--- /dev/null+++ b/src/page/motion.js@@ -0,0 +1,106 @@+// Motion helpers for scene pages. Everything is a pure function of time, so frames can be drawn in any order.+// Served by the render server and the viewer at /__motlab/motion.js:+//+// const { ease, cubicBezier, spring, tween, stagger, prog, motionBlur } = await import('/__motlab/motion.js');+//+// Times are in seconds. An easing takes 0..1 and returns 0..1 (a spring or "back" ease may pass 1 on the way).++export const clamp = (x, a = 0, b = 1) => Math.min(b, Math.max(a, x));+export const lerp = (a, b, k) => a + (b - a) * k;+export const prog = (t, a, b) => clamp((t - a) / (b - a)); // 0..1 between seconds a and b++const { PI, cos, sin, pow, sqrt, exp } = Math;+const outBounce = k => {+ const n = 7.5625, d = 2.75;+ if (k < 1 / d) return n * k * k;+ if (k < 2 / d) return n * (k -= 1.5 / d) * k + 0.75;+ if (k < 2.5 / d) return n * (k -= 2.25 / d) * k + 0.9375;+ return n * (k -= 2.625 / d) * k + 0.984375;+};+const B = 1.70158, B2 = B * 1.525;+export const ease = {+ linear: k => k,+ inSine: k => 1 - cos(k * PI / 2), outSine: k => sin(k * PI / 2), inOutSine: k => 0.5 - 0.5 * cos(PI * k),+ inQuad: k => k * k, outQuad: k => 1 - (1 - k) * (1 - k), inOutQuad: k => k < 0.5 ? 2 * k * k : 1 - pow(-2 * k + 2, 2) / 2,+ inCubic: k => k * k * k, outCubic: k => 1 - pow(1 - k, 3), inOutCubic: k => k < 0.5 ? 4 * k * k * k : 1 - pow(-2 * k + 2, 3) / 2,+ inQuart: k => k ** 4, outQuart: k => 1 - pow(1 - k, 4), inOutQuart: k => k < 0.5 ? 8 * k ** 4 : 1 - pow(-2 * k + 2, 4) / 2,+ inExpo: k => k <= 0 ? 0 : pow(2, 10 * k - 10), outExpo: k => k >= 1 ? 1 : 1 - pow(2, -10 * k),+ inOutExpo: k => k <= 0 ? 0 : k >= 1 ? 1 : k < 0.5 ? pow(2, 20 * k - 10) / 2 : (2 - pow(2, -20 * k + 10)) / 2,+ inBack: k => (B + 1) * k ** 3 - B * k * k, outBack: k => 1 + (B + 1) * pow(k - 1, 3) + B * pow(k - 1, 2),+ inOutBack: k => k < 0.5 ? (pow(2 * k, 2) * ((B2 + 1) * 2 * k - B2)) / 2 : (pow(2 * k - 2, 2) * ((B2 + 1) * (k * 2 - 2) + B2) + 2) / 2,+ outBounce,+};++// A CSS cubic-bezier(x1, y1, x2, y2) as an easing function, e.g. cubicBezier(0.2, 0.8, 0.2, 1).+export function cubicBezier(x1, y1, x2, y2) {+ const cx = 3 * x1, bx = 3 * (x2 - x1) - cx, ax = 1 - cx - bx, cy = 3 * y1, by = 3 * (y2 - y1) - cy, ay = 1 - cy - by;+ const X = s => ((ax * s + bx) * s + cx) * s, Y = s => ((ay * s + by) * s + cy) * s, dX = s => (3 * ax * s + 2 * bx) * s + cx;+ return k => {+ if (k <= 0) return 0; if (k >= 1) return 1;+ let s = k;+ for (let i = 0; i < 8; i++) { const e = X(s) - k, d = dX(s); if (Math.abs(e) < 1e-7) return Y(s); if (Math.abs(d) < 1e-6) break; s -= e / d; }+ let lo = 0, hi = 1; s = k; // Newton did not settle: bisect+ for (let i = 0; i < 40; i++) { const x = X(s); if (Math.abs(x - k) < 1e-7) break; if (x < k) lo = s; else hi = s; s = (lo + hi) / 2; }+ return Y(s);+ };+}+Object.assign(ease, { css: cubicBezier(0.25, 0.1, 0.25, 1), cssIn: cubicBezier(0.42, 0, 1, 1), cssOut: cubicBezier(0, 0, 0.58, 1), cssInOut: cubicBezier(0.42, 0, 0.58, 1) });++// A damped spring from 0 to 1, solved exactly (no stepping), so spring(cfg)(t) is the same in any frame order.+// stiffness, damping and mass as in Remotion and Framer Motion; velocity in units per second at t = 0.+// spring(cfg).duration is when it stays within 0.1% of 1 for good.+export function spring({ stiffness = 100, damping = 10, mass = 1, velocity = 0 } = {}) {+ const w0 = sqrt(stiffness / mass), zeta = damping / (2 * sqrt(stiffness * mass)), v0 = velocity, x0 = -1;+ let f; // the offset from 1 is x(t), with x(0) = -1 and x'(0) = velocity+ if (Math.abs(zeta - 1) < 1e-9) {+ f = t => 1 + exp(-w0 * t) * (x0 + (v0 + w0 * x0) * t);+ } else if (zeta < 1) {+ const wd = w0 * sqrt(1 - zeta * zeta), A = x0, Bc = (v0 + zeta * w0 * x0) / wd;+ f = t => 1 + exp(-zeta * w0 * t) * (A * cos(wd * t) + Bc * sin(wd * t));+ } else {+ const r = sqrt(zeta * zeta - 1), s1 = -w0 * (zeta - r), s2 = -w0 * (zeta + r), c2 = (v0 - s1 * x0) / (s2 - s1), c1 = x0 - c2;+ f = t => 1 + c1 * exp(s1 * t) + c2 * exp(s2 * t);+ }+ const fn = t => t <= 0 ? 0 : f(t);+ let settle = 0; for (let t = 0; t < 30; t += 1 / 240) if (Math.abs(f(t) - 1) > 1e-3) settle = t; // last time it was off by more than 0.1%+ fn.duration = settle + 1 / 240;+ return fn;+}++// Keyframes: tween(t, [[0, 0], [0.5, 100, ease.outCubic], [2, [1, 2]]]). Each key is [time, value, easing into it].+// Values are numbers or arrays of numbers (a position, a colour as [r, g, b]). Before the first key and after the last,+// the value holds.+export function tween(t, keys) {+ if (t <= keys[0][0]) return keys[0][1];+ for (let i = 1; i < keys.length; i++) {+ const [t1, v1, e = ease.inOutCubic] = keys[i];+ if (t < t1) {+ const [t0, v0] = keys[i - 1], k = e((t - t0) / (t1 - t0));+ return Array.isArray(v0) ? v0.map((a, j) => lerp(a, v1[j], k)) : lerp(v0, v1, k);+ }+ }+ return keys[keys.length - 1][1];+}++// Start time of item i in a staggered group: stagger(i, 0.06, 0.4). from 'end' or 'center' reorders the wave.+export function stagger(i, each, start = 0, { n = 0, from = 'start' } = {}) {+ const k = from === 'end' ? n - 1 - i : from === 'center' ? Math.abs(i - (n - 1) / 2) : i;+ return start + k * each;+}++// Motion blur: draws the frame `samples` times across the shutter and averages them on `canvas`.+// draw(time) must draw a whole frame onto `canvas` (opaque), and may be async. shutter is in seconds: half a frame+// (0.5 / fps) is the film look, and 8 to 12 samples hide the steps on fast moves (5 shows ghost copies).+let acc = null;+export async function motionBlur(canvas, t, draw, { samples = 8, shutter = 0.5 / 30, from = 0, to = Infinity } = {}) {+ if (samples <= 1) return draw(t);+ if (!acc || acc.width !== canvas.width || acc.height !== canvas.height) acc = Object.assign(document.createElement('canvas'), { width: canvas.width, height: canvas.height });+ const a = acc.getContext('2d'), c = canvas.getContext('2d');+ a.setTransform(1, 0, 0, 1, 0, 0);+ for (let i = 0; i < samples; i++) {+ await draw(clamp(t + (i / (samples - 1) - 0.5) * shutter, from, to));+ a.globalAlpha = 1 / (i + 1); a.drawImage(canvas, 0, 0);+ }+ a.globalAlpha = 1;+ c.save(); c.setTransform(1, 0, 0, 1, 0, 0); c.globalAlpha = 1; c.globalCompositeOperation = 'copy'; c.drawImage(acc, 0, 0); c.restore();+}diff --git a/src/page/runtime.js b/src/page/runtime.jsnew file mode 100644index 0000000..3275d6b--- /dev/null+++ b/src/page/runtime.js@@ -0,0 +1,178 @@+// Runs inside the page (injected by the renderer, the page itself is never edited). Drives the page contract+// (canvas #c, renderAt, TOTAL, ready, EVENTS) and encodes with WebCodecs, so frames never leave Chrome as images:+// only encoded video bytes are posted back to Node.+(() => {+ 'use strict';+ if (window.__motlab) return;++ const BT709 = { primaries: 'bt709', transfer: 'bt709', matrix: 'bt709', fullRange: false };+ const emit = (type, data = {}) => { try { window.__motlabEmit(JSON.stringify({ type, ...data })); } catch {} };+ const post = async (url, body) => { const r = await fetch(url, { method: 'POST', body }); if (!r.ok) throw new Error(`upload failed (${r.status})`); };+ const sleep = ms => new Promise(r => setTimeout(r, ms));++ function canvas() {+ const c = document.getElementById('c');+ if (!(c instanceof HTMLCanvasElement)) throw new Error('page has no <canvas id="c">');+ return c;+ }++ function gpu() { // the GPU Chrome really draws on+ try {+ const gl = document.createElement('canvas').getContext('webgl2') || document.createElement('canvas').getContext('webgl');+ if (!gl) return { renderer: null, vendor: null };+ const e = gl.getExtension('WEBGL_debug_renderer_info');+ const out = { renderer: gl.getParameter(e ? e.UNMASKED_RENDERER_WEBGL : gl.RENDERER), vendor: gl.getParameter(e ? e.UNMASKED_VENDOR_WEBGL : gl.VENDOR) };+ gl.getExtension('WEBGL_lose_context')?.loseContext();+ return out;+ } catch (e) { return { renderer: null, vendor: null, error: String(e && e.message) }; }+ }++ function info() {+ const c = canvas();+ return { width: c.width, height: c.height, total: Number(window.TOTAL), events: Array.isArray(window.EVENTS) ? window.EVENTS : [], gpu: gpu() };+ }++ // rc 'quantizer' = constant QP (quality stays fixed, size follows content); otherwise variable bitrate.+ function encoderConfig(o, width, height, annexb) {+ const hevc = o.codec === 'hevc';+ return {+ codec: o.codecString, width, height, framerate: o.fps,+ hardwareAcceleration: o.hw ? 'prefer-hardware' : 'prefer-software', latencyMode: 'quality',+ ...(o.rc === 'quantizer' ? { bitrateMode: 'quantizer' } : { bitrateMode: 'variable', bitrate: o.bitrate }),+ [hevc ? 'hevc' : 'avc']: { format: annexb ? 'annexb' : (hevc ? 'hevc' : 'avc') },+ };+ }+ const frameOptions = (o, keyFrame) => o.rc === 'quantizer' ? { keyFrame, [o.codec === 'hevc' ? 'hevc' : 'avc']: { quantizer: o.qp } } : { keyFrame };++ // Wait until the encoder has room. The timeout keeps a dead encoder from hanging the loop.+ const drained = enc => Promise.race([new Promise(r => enc.addEventListener('dequeue', r, { once: true })), sleep(2000)]);++ // Where encoded chunks go. 'mediabunny' muxes the MP4 inside the page and streams it out with positional writes.+ // 'raw' appends the Annex B bitstream for ffmpeg to wrap.+ 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); };+ 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,+ };+ }+ const MB = await import(`${o.base}/mediabunny.mjs`);+ const writable = new WritableStream({ write: c => post(`${o.base}/write?id=${o.sink}&pos=${c.position}`, c.data) });+ const output = new MB.Output({+ format: new MB.Mp4OutputFormat({ fastStart: false }), // ffmpeg writes the final fast-start file+ target: new MB.StreamTarget(writable, { chunked: true, chunkSize: 8 << 20 }),+ });+ const source = new MB.EncodedVideoPacketSource(o.codec === 'hevc' ? 'hevc' : 'avc');+ output.addVideoTrack(source, { frameRate: o.fps });+ await output.start();+ return {+ // Encoders tag colour inconsistently (hardware H.264 not at all) although the pixels are BT.709 limited range,+ // so the container tag is set here for every encoder. ffmpeg later writes the same into the bitstream.+ add: (chunk, meta) => source.add(MB.EncodedPacket.fromEncodedChunk(chunk),+ meta && meta.decoderConfig ? { ...meta, decoderConfig: { ...meta.decoderConfig, colorSpace: BT709 } } : meta),+ finish: () => output.finalize(),+ };+ }++ // Render frames [start, end) with renderAt(frame / fps) and encode them. Timestamps start at 0 for each range.+ async function encodeRange(o) {+ const cv = canvas(), frames = o.end - o.start;+ const cfg = encoderConfig(o, cv.width, cv.height, o.mux === 'raw');+ if (!(await VideoEncoder.isConfigSupported(cfg)).supported) throw new Error(`encoder config not supported: ${cfg.codec} ${cfg.hardwareAcceleration} ${cv.width}x${cv.height}`);+ const sink = await openSink(o);++ let chain = Promise.resolve(), queued = 0, failure = null, bytes = 0;+ const enc = new VideoEncoder({+ output(chunk, meta) {+ bytes += chunk.byteLength; queued++;+ chain = chain.then(() => failure || sink.add(chunk, meta)).then(() => { queued--; }, e => { failure ??= e; queued--; });+ },+ error(e) { failure ??= e; },+ });+ enc.configure(cfg);++ const t0 = performance.now(), frameUs = 1e6 / o.fps; let renderMs = 0, lastEmit = t0;+ for (let i = 0; i < frames && !failure; i++) {+ const r0 = performance.now();+ await window.renderAt((o.start + i) / o.fps);+ renderMs += performance.now() - r0;+ const vf = new VideoFrame(cv, { timestamp: Math.round(i * frameUs), duration: Math.round(frameUs) });+ enc.encode(vf, frameOptions(o, i % o.keyInterval === 0));+ vf.close();+ while (enc.encodeQueueSize > 2 && !failure) await drained(enc);+ if (queued > 32) await chain;+ const now = performance.now();+ if (now - lastEmit > 250 || i === frames - 1) { lastEmit = now; emit('progress', { done: i + 1 }); }+ }+ if (!failure) await enc.flush();+ try { enc.close(); } catch {}+ await chain;+ if (failure) throw new Error(`encode failed: ${failure.message || failure}`);+ await sink.finish();+ return { frames, bytes, ms: performance.now() - t0, renderMs };+ }++ // ---- encoder probe: how fast is one encoder config at this size, with drawing kept cheap? ----+ let scene = null;+ function probeScene(width, height) {+ if (scene && scene.cv.width === width && scene.cv.height === height) return scene;+ const cv = document.createElement('canvas'); cv.width = width; cv.height = height;+ const ctx = cv.getContext('2d'), S = width / 1920;+ const g = ctx.createLinearGradient(0, 0, width, height); g.addColorStop(0, '#1b2a4a'); g.addColorStop(1, '#0c3b2e');+ ctx.fillStyle = g; ctx.fillRect(0, 0, width, height);+ for (let k = 0; k < 90; k++) { // static detail, kept as a bitmap so per-frame drawing stays cheap+ ctx.fillStyle = `hsl(${(k * 37) % 360},65%,${45 + (k % 5) * 6}%)`;+ ctx.beginPath(); ctx.roundRect(((k * 211) % 1800) * S, ((k * 127) % 1000) * S, (60 + (k % 6) * 30) * S, (40 + (k % 4) * 24) * S, 10 * S); ctx.fill();+ }+ ctx.fillStyle = '#fff'; ctx.font = `600 ${64 * S}px system-ui, sans-serif`; ctx.fillText('motlab encoder probe', 80 * S, 120 * S);+ const bg = document.createElement('canvas'); bg.width = width; bg.height = height; bg.getContext('2d').drawImage(cv, 0, 0);+ const draw = i => {+ ctx.drawImage(bg, 0, 0);+ for (let k = 0; k < 24; k++) {+ const a = k * 0.7 + i * 0.03 * (1 + (k % 5) * 0.2);+ ctx.fillStyle = `hsl(${(k * 23 + 180) % 360},80%,62%)`;+ ctx.beginPath(); ctx.roundRect((960 + Math.cos(a) * (200 + k * 28) - 60) * S, (540 + Math.sin(a * 1.3) * (120 + k * 14) - 40) * S, 120 * S, 80 * S, 14 * S); ctx.fill();+ }+ ctx.fillStyle = '#fff'; ctx.fillText(String(i), 960 * S, 560 * S);+ };+ return (scene = { cv, draw });+ }++ async function probeEncoder(o) {+ const cfg = encoderConfig(o, o.width, o.height, true);+ try { if (!(await VideoEncoder.isConfigSupported(cfg)).supported) return { supported: false }; } catch (e) { return { supported: false, error: String(e && e.message) }; }+ const { cv, draw } = probeScene(o.width, o.height), frameUs = 1e6 / o.fps;+ // The clock starts at the WARM-th output chunk, so encoder start-up is not counted. There is no flush in the+ // middle: a hardware encoder that is flushed and then fed again stalls in headless Chrome.+ const WARM = 6; let failure = null, bytes = 0, outs = 0, t0 = 0;+ const enc = new VideoEncoder({ output(c) { if (++outs === WARM) { t0 = performance.now(); bytes = 0; } else bytes += c.byteLength; }, error(e) { failure ??= e; } });+ try {+ enc.configure(cfg);+ for (let i = 0; i < WARM + o.frames && !failure; i++) {+ draw(i);+ const vf = new VideoFrame(cv, { timestamp: Math.round(i * frameUs), duration: Math.round(frameUs) });+ enc.encode(vf, frameOptions(o, i === 0)); vf.close();+ while (enc.encodeQueueSize > 2 && !failure) await drained(enc);+ }+ if (!failure) await enc.flush();+ const ms = performance.now() - t0, timed = outs - WARM;+ if (failure) return { supported: false, error: String(failure.message || failure) };+ if (timed < 1) return { supported: false, error: `encoder returned ${outs} of ${WARM + o.frames} frames` };+ return { supported: true, fps: timed / (ms / 1000), mbps: (bytes * 8 * o.fps) / timed / 1e6 };+ } catch (e) { return { supported: false, error: String(e && e.message) }; } finally { try { enc.close(); } catch {} }+ }++ const probeDone = () => { if (scene) { scene.cv.width = scene.cv.height = 0; scene = null; } };++ async function still(o) {+ 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;+ }++ window.__motlab = { info, gpu, encodeRange, probeEncoder, probeDone, still };+})();diff --git a/src/page/transition.html b/src/page/transition.htmlnew file mode 100644index 0000000..7276165--- /dev/null+++ b/src/page/transition.html@@ -0,0 +1,41 @@+<!doctype html><html><head><meta charset="utf-8"><title>motlab transition</title>+<style>html,body{margin:0;background:#000} iframe{position:fixed;left:-99999px;top:0;border:0;visibility:hidden}</style></head>+<body><canvas id="c"></canvas>+<script type="module">+// The frames where one scene turns into the next, rendered like any scene page (served at /__motlab/transition.html).+// Both scene pages are loaded in iframes. Frame k shows frame (offset * fps + k) of `from` and frame k of `to`,+// mixed by src/page/transitions.js, the same code the viewer uses.+// Query: from, to (page paths from the served root), offset (seconds into `from`), frames, fps, type, ease, params (JSON), scale.+import { createMixer, findTransition, transitionProgress } from '/__motlab/transitions.js';+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;++const open = path => new Promise((ok, fail) => {+ const f = document.createElement('iframe'); f.src = `/${path}?scale=${scale}`;+ f.onload = async () => {+ try {+ const w = f.contentWindow, c = w.document.getElementById('c');+ if (!c || typeof w.renderAt !== 'function') throw new Error(`${path} does not keep the page contract`);+ await w.ready; ok({ w, c });+ } catch (e) { fail(e); }+ };+ f.onerror = () => fail(new Error(`${path} did not load`));+ document.body.append(f);+});++window.TOTAL = n / fps;+window.ready = (async () => {+ findTransition(type); 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();+ return true;+})();+window.renderAt = async t => {+ await window.ready;+ const k = Math.min(n - 1, Math.max(0, Math.round(t * fps)));+ await A.w.renderAt(offset + k / fps); await B.w.renderAt(k / fps);+ ctx.drawImage(mix.draw(type, A.c, B.c, transitionProgress(k, n, easing), params), 0, 0, cv.width, cv.height);+};+</script></body></html>diff --git a/src/page/transitions.js b/src/page/transitions.jsnew file mode 100644index 0000000..dac25d8--- /dev/null+++ b/src/page/transitions.js@@ -0,0 +1,107 @@+// Scene transitions: two frames and a progress go in, one frame comes out. The viewer and the renderer both use this+// file, so a transition looks the same in the preview and in the MP4. Served at /__motlab/transitions.js.+//+// The shaders are from gl-transitions 1.43.0 (https://github.com/gl-transitions/gl-transitions), each under the+// licence and by the author named next to it (all MIT). SimpleZoom is changed so it compiles in WebGL: its+// nQuick is computed inside transition() instead of at the top level.+import { ease } from './motion.js';++export const TRANSITIONS = {+ "fade": { author: "gre", license: "MIT", defaults: {}, types: {},+ glsl: "// author: gre\n// license: MIT\n\nvec4 transition (vec2 uv) {\n return mix(\n getFromColor(uv),\n getToColor(uv),\n progress\n );\n}\n" },+ "fadecolor": { author: "gre", license: "MIT", defaults: {"color": [0, 0, 0], "colorPhase": 0.4}, types: {"color": "vec3", "colorPhase": "float"},+ glsl: "// author: gre\n// License: MIT\nuniform vec3 color;// = vec3(0.0)\nuniform float colorPhase/* = 0.4 */; // if 0.0, there is no black phase, if 0.9, the black phase is very important\nvec4 transition (vec2 uv) {\n return mix(\n mix(vec4(color, 1.0), getFromColor(uv), smoothstep(1.0-colorPhase, 0.0, progress)),\n mix(vec4(color, 1.0), getToColor(uv), smoothstep( colorPhase, 1.0, progress)),\n progress);\n}\n" },+ "Directional": { author: "Gaëtan Renaudeau", license: "MIT", defaults: {"direction": [0, 1]}, types: {"direction": "vec2"},+ glsl: "// Author: Gaëtan Renaudeau\n// License: MIT\n\nuniform vec2 direction; // = vec2(0.0, 1.0)\n\nvec4 transition (vec2 uv) {\n vec2 p = uv + progress * sign(direction);\n vec2 f = fract(p);\n return mix(\n getToColor(f),\n getFromColor(f),\n step(0.0, p.y) * step(p.y, 1.0) * step(0.0, p.x) * step(p.x, 1.0)\n );\n}\n" },+ "directionalwipe": { author: "gre", license: "MIT", defaults: {"direction": [1, -1], "smoothness": 0.5}, types: {"direction": "vec2", "smoothness": "float"},+ glsl: "// Author: gre\n// License: MIT\n\nuniform vec2 direction; // = vec2(1.0, -1.0)\nuniform float smoothness; // = 0.5\n \nconst vec2 center = vec2(0.5, 0.5);\n \nvec4 transition (vec2 uv) {\n vec2 v = normalize(direction);\n v /= abs(v.x)+abs(v.y);\n float d = v.x * center.x + v.y * center.y;\n float m =\n (1.0-step(progress, 0.0)) * // there is something wrong with our formula that makes m not equals 0.0 with progress is 0.0\n (1.0 - smoothstep(-smoothness, 0.0, v.x * uv.x + v.y * uv.y - (d-0.5+progress*(1.+smoothness))));\n return mix(getFromColor(uv), getToColor(uv), m);\n}\n" },+ "directionalwarp": { author: "pschroen", license: "MIT", defaults: {"direction": [-1, 1]}, types: {"direction": "vec2"},+ glsl: "// Author: pschroen\n// License: MIT\n\nuniform vec2 direction; // = vec2(-1.0, 1.0)\n\nconst float smoothness = 0.5;\nconst vec2 center = vec2(0.5, 0.5);\n\nvec4 transition (vec2 uv) {\n vec2 v = normalize(direction);\n v /= abs(v.x) + abs(v.y);\n float d = v.x * center.x + v.y * center.y;\n float m = 1.0 - smoothstep(-smoothness, 0.0, v.x * uv.x + v.y * uv.y - (d - 0.5 + progress * (1.0 + smoothness)));\n return mix(getFromColor((uv - 0.5) * (1.0 - m) + 0.5), getToColor((uv - 0.5) * m + 0.5), m);\n}\n" },+ "circleopen": { author: "gre", license: "MIT", defaults: {"smoothness": 0.3, "opening": true}, types: {"smoothness": "float", "opening": "bool"},+ glsl: "// author: gre\n// License: MIT\nuniform float smoothness; // = 0.3\nuniform bool opening; // = true\n\nconst vec2 center = vec2(0.5, 0.5);\nconst float SQRT_2 = 1.414213562373;\n\nvec4 transition (vec2 uv) {\n float x = opening ? progress : 1.-progress;\n float m = smoothstep(-smoothness, 0.0, SQRT_2*distance(center, uv) - x*(1.+smoothness));\n return mix(getFromColor(uv), getToColor(uv), opening ? 1.-m : m);\n}\n" },+ "CrossZoom": { author: "rectalogic", license: "MIT", defaults: {"strength": 0.4}, types: {"strength": "float"},+ glsl: "// License: MIT\n// Author: rectalogic\n// ported by gre from https://gist.github.com/rectalogic/b86b90161503a0023231\n\n// Converted from https://github.com/rectalogic/rendermix-basic-effects/blob/master/assets/com/rendermix/CrossZoom/CrossZoom.frag\n// Which is based on https://github.com/evanw/glfx.js/blob/master/src/filters/blur/zoomblur.js\n// With additional easing functions from https://github.com/rectalogic/rendermix-basic-effects/blob/master/assets/com/rendermix/Easing/Easing.glsllib\n\nuniform float strength; // = 0.4\n\nconst float PI = 3.141592653589793;\n\nfloat Linear_ease(in float begin, in float change, in float duration, in float time) {\n return change * time / duration + begin;\n}\n\nfloat Exponential_easeInOut(in float begin, in float change, in float duration, in float time) {\n if (time == 0.0)\n return begin;\n else if (time == duration)\n return begin + change;\n time = time / (duration / 2.0);\n if (time < 1.0)\n return change / 2.0 * pow(2.0, 10.0 * (time - 1.0)) + begin;\n return change / 2.0 * (-pow(2.0, -10.0 * (time - 1.0)) + 2.0) + begin;\n}\n\nfloat Sinusoidal_easeInOut(in float begin, in float change, in float duration, in float time) {\n return -change / 2.0 * (cos(PI * time / duration) - 1.0) + begin;\n}\n\nfloat rand (vec2 co) {\n return fract(sin(dot(co.xy ,vec2(12.9898,78.233))) * 43758.5453);\n}\n\nvec3 crossFade(in vec2 uv, in float dissolve) {\n return mix(getFromColor(uv).rgb, getToColor(uv).rgb, dissolve);\n}\n\nvec4 transition(vec2 uv) {\n vec2 texCoord = uv.xy / vec2(1.0).xy;\n\n // Linear interpolate center across center half of the image\n vec2 center = vec2(Linear_ease(0.25, 0.5, 1.0, progress), 0.5);\n float dissolve = Exponential_easeInOut(0.0, 1.0, 1.0, progress);\n\n // Mirrored sinusoidal loop. 0->strength then strength->0\n float strength = Sinusoidal_easeInOut(0.0, strength, 0.5, progress);\n\n vec3 color = vec3(0.0);\n float total = 0.0;\n vec2 toCenter = center - texCoord;\n\n /* randomize the lookup values to hide the fixed number of samples */\n float offset = rand(uv);\n\n for (float t = 0.0; t <= 40.0; t++) {\n float percent = (t + offset) / 40.0;\n float weight = 4.0 * (percent - percent * percent);\n color += crossFade(texCoord + toCenter * percent * strength, dissolve) * weight;\n total += weight;\n }\n return vec4(color / total, 1.0);\n}\n" },+ "crosswarp": { author: "Eke Péter <[email protected]>", license: "MIT", defaults: {}, types: {},+ glsl: "// Author: Eke Péter <[email protected]>\n// License: MIT\nvec4 transition(vec2 p) {\n float x = progress;\n x=smoothstep(.0,1.0,(x*2.0+p.x-1.0));\n return mix(getFromColor((p-.5)*(1.-x)+.5), getToColor((p-.5)*x+.5), x);\n}\n" },+ "SimpleZoom": { author: "0gust1", license: "MIT", defaults: {"zoom_quickness": 0.8}, types: {"zoom_quickness": "float"},+ glsl: "// Author: 0gust1\n// License: MIT\n\nuniform float zoom_quickness; // = 0.8\n\nvec2 zoom(vec2 uv, float amount) {\n return 0.5 + ((uv - 0.5) * (1.0-amount));\t\n}\n\nvec4 transition (vec2 uv) {\n float nQuick = clamp(zoom_quickness,0.2,1.0);\n return mix(\n getFromColor(zoom(uv, smoothstep(0.0, nQuick, progress))),\n getToColor(uv),\n smoothstep(nQuick-0.2, 1.0, progress)\n );\n}" },+ "LinearBlur": { author: "gre", license: "MIT", defaults: {"intensity": 0.1}, types: {"intensity": "float"},+ glsl: "// author: gre\n// license: MIT\nuniform float intensity; // = 0.1\nconst int passes = 6;\n\nvec4 transition(vec2 uv) {\n vec4 c1 = vec4(0.0);\n vec4 c2 = vec4(0.0);\n\n float disp = intensity*(0.5-distance(0.5, progress));\n for (int xi=0; xi<passes; xi++)\n {\n float x = float(xi) / float(passes) - 0.5;\n for (int yi=0; yi<passes; yi++)\n {\n float y = float(yi) / float(passes) - 0.5;\n vec2 v = vec2(x,y);\n float d = disp;\n c1 += getFromColor( uv + d*v);\n c2 += getToColor( uv + d*v);\n }\n }\n c1 /= float(passes*passes);\n c2 /= float(passes*passes);\n return mix(c1, c2, progress);\n}\n" },+ "cube": { author: "gre", license: "MIT", defaults: {"persp": 0.7, "unzoom": 0.3, "reflection": 0.4, "floating": 3}, types: {"persp": "float", "unzoom": "float", "reflection": "float", "floating": "float"},+ glsl: "// Author: gre\n// License: MIT\nuniform float persp; // = 0.7\nuniform float unzoom; // = 0.3\nuniform float reflection; // = 0.4\nuniform float floating; // = 3.0\n\nvec2 project (vec2 p) {\n return p * vec2(1.0, -1.2) + vec2(0.0, -floating/100.);\n}\n\nbool inBounds (vec2 p) {\n return all(lessThan(vec2(0.0), p)) && all(lessThan(p, vec2(1.0)));\n}\n\nvec4 bgColor (vec2 p, vec2 pfr, vec2 pto) {\n vec4 c = vec4(0.0, 0.0, 0.0, 1.0);\n pfr = project(pfr);\n // FIXME avoid branching might help perf!\n if (inBounds(pfr)) {\n c += mix(vec4(0.0), getFromColor(pfr), reflection * mix(1.0, 0.0, pfr.y));\n }\n pto = project(pto);\n if (inBounds(pto)) {\n c += mix(vec4(0.0), getToColor(pto), reflection * mix(1.0, 0.0, pto.y));\n }\n return c;\n}\n\n// p : the position\n// persp : the perspective in [ 0, 1 ]\n// center : the xcenter in [0, 1] \\ 0.5 excluded\nvec2 xskew (vec2 p, float persp, float center) {\n float x = mix(p.x, 1.0-p.x, center);\n return (\n (\n vec2( x, (p.y - 0.5*(1.0-persp) * x) / (1.0+(persp-1.0)*x) )\n - vec2(0.5-distance(center, 0.5), 0.0)\n )\n * vec2(0.5 / distance(center, 0.5) * (center<0.5 ? 1.0 : -1.0), 1.0)\n + vec2(center<0.5 ? 0.0 : 1.0, 0.0)\n );\n}\n\nvec4 transition(vec2 op) {\n float uz = unzoom * 2.0*(0.5-distance(0.5, progress));\n vec2 p = -uz*0.5+(1.0+uz) * op;\n vec2 fromP = xskew(\n (p - vec2(progress, 0.0)) / vec2(1.0-progress, 1.0),\n 1.0-mix(progress, 0.0, persp),\n 0.0\n );\n vec2 toP = xskew(\n p / vec2(progress, 1.0),\n mix(pow(progress, 2.0), 1.0, persp),\n 1.0\n );\n // FIXME avoid branching might help perf!\n if (inBounds(fromP)) {\n return getFromColor(fromP);\n }\n else if (inBounds(toP)) {\n return getToColor(toP);\n }\n return bgColor(op, fromP, toP);\n}\n" },+};++export const transitionNames = Object.keys(TRANSITIONS);+export const findTransition = name => {+ const key = transitionNames.find(k => k.toLowerCase() === String(name).toLowerCase());+ if (!key) throw new Error(`unknown transition "${name}"; use one of: ${transitionNames.join(', ')}`);+ return { name: key, ...TRANSITIONS[key] };+};++// 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') {+ const e = ease[easing];+ if (!e) throw new Error(`unknown ease "${easing}"; use one of: ${Object.keys(ease).join(', ')}`);+ return e((k + 0.5) / n);+}++const VERT = 'attribute vec2 p; varying vec2 vUv; void main() { vUv = p * 0.5 + 0.5; gl_Position = vec4(p, 0.0, 1.0); }';+const frag = glsl => `precision highp float;+varying vec2 vUv; uniform sampler2D uFrom, uTo; uniform float progress, ratio;+vec4 getFromColor(vec2 uv) { return texture2D(uFrom, uv); }+vec4 getToColor(vec2 uv) { return texture2D(uTo, uv); }+${glsl}+void main() { gl_FragColor = transition(vUv); }`;++// One WebGL canvas that mixes two canvases (or images, or video frames). draw() returns that canvas; copy it onto+// the frame with drawImage right away.+export function createMixer() {+ const cv = document.createElement('canvas');+ const gl = cv.getContext('webgl2', { premultipliedAlpha: false, preserveDrawingBuffer: true, antialias: false });+ if (!gl) throw new Error('scene transitions need WebGL2');+ const programs = new Map(), textures = [gl.createTexture(), gl.createTexture()];+ for (const t of textures) {+ gl.bindTexture(gl.TEXTURE_2D, t);+ for (const [k, v] of [[gl.TEXTURE_MIN_FILTER, gl.LINEAR], [gl.TEXTURE_MAG_FILTER, gl.LINEAR], [gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE], [gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE]]) gl.texParameteri(gl.TEXTURE_2D, k, v);+ }+ gl.bindBuffer(gl.ARRAY_BUFFER, gl.createBuffer());+ gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([-1, -1, 3, -1, -1, 3]), gl.STATIC_DRAW); // one triangle over the frame+ gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, true);++ function program(name) {+ if (programs.has(name)) return programs.get(name);+ const t = findTransition(name), p = gl.createProgram();+ for (const [type, src] of [[gl.VERTEX_SHADER, VERT], [gl.FRAGMENT_SHADER, frag(t.glsl)]]) {+ const s = gl.createShader(type); gl.shaderSource(s, src); gl.compileShader(s);+ if (!gl.getShaderParameter(s, gl.COMPILE_STATUS)) throw new Error(`transition ${t.name}: ${gl.getShaderInfoLog(s)}`);+ gl.attachShader(p, s);+ }+ gl.bindAttribLocation(p, 0, 'p'); gl.linkProgram(p);+ if (!gl.getProgramParameter(p, gl.LINK_STATUS)) throw new Error(`transition ${t.name}: ${gl.getProgramInfoLog(p)}`);+ const entry = { p, t, u: n => gl.getUniformLocation(p, n) };+ programs.set(name, entry); return entry;+ }++ return {+ canvas: cv,+ draw(name, from, to, progress, params = {}) {+ const w = from.width, h = from.height;+ if (cv.width !== w || cv.height !== h) { cv.width = w; cv.height = h; }+ const { p, t, u } = program(name);+ gl.viewport(0, 0, w, h); gl.useProgram(p);+ [from, to].forEach((img, i) => { gl.activeTexture(gl.TEXTURE0 + i); gl.bindTexture(gl.TEXTURE_2D, textures[i]); gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, img); });+ gl.uniform1i(u('uFrom'), 0); gl.uniform1i(u('uTo'), 1); gl.uniform1f(u('progress'), progress); gl.uniform1f(u('ratio'), w / h);+ for (const [k, type] of Object.entries(t.types)) {+ const v = params[k] ?? t.defaults[k], loc = u(k);+ if (loc === null || v === undefined) continue;+ if (type === 'float') gl.uniform1f(loc, v);+ else if (type === 'bool' || type === 'int') gl.uniform1i(loc, Number(v));+ else gl[`uniform${type.slice(3)}fv`](loc, v); // vec2, vec3, vec4+ }+ gl.enableVertexAttribArray(0); gl.vertexAttribPointer(0, 2, gl.FLOAT, false, 0, 0);+ gl.drawArrays(gl.TRIANGLES, 0, 3);+ return cv;+ },+ };+}diff --git a/src/probe.js b/src/probe.jsnew file mode 100644index 0000000..8069583--- /dev/null+++ b/src/probe.js@@ -0,0 +1,69 @@+// Picks the encoder for this machine and resolution by timing each candidate once, then remembers the answer.+// Nothing is assumed: on the reference laptop the software encoder is the fastest, and the hardware one is the only+// one that can hold a constant QP.+import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';+import { cpus, homedir } from 'node:os';+import { join } from 'node:path';+import { codecString, defaultBitrate } from './codecs.js';++const CANDIDATES = [{ codec: 'h264', hw: true }, { codec: 'h264', hw: false }, { codec: 'hevc', hw: true }, { codec: 'hevc', hw: false }];+// Constant QP values that keep SSIM against a lossless reference near 0.999 on the skill's 2D and 3D templates.+export const DEFAULT_QP = { h264: 18, hevc: 20 };+export const label = c => `${c.codec === 'hevc' ? 'HEVC' : 'H.264'} ${c.hw ? 'hardware' : 'software'}`;+export const rate = c => c.rc === 'quantizer' ? `constant QP ${c.qp}` : `${(c.bitrate / 1e6).toFixed(1)} Mbit/s VBR`;++export function cacheFile() {+ const dir = process.env.MOTLAB_CACHE_DIR || (process.platform === 'win32' && process.env.LOCALAPPDATA ? join(process.env.LOCALAPPDATA, 'motlab') : join(homedir(), '.cache', 'motlab'));+ return join(dir, 'encoder-probe.json');+}+const load = () => { try { return JSON.parse(readFileSync(cacheFile(), 'utf8')); } catch { return {}; } };++// auto: the fastest encoder that can hold a constant QP, because Chrome's software H.264 encoder ignores the bitrate+// above a quality ceiling (SSIM about 0.994 on fine 1080p line art). Without such an encoder: the fastest overall.+// hw / sw: the fastest of that kind. H.264 is kept unless HEVC is at least 25% faster: it plays everywhere, and a+// smaller margin would let probe noise flip the codec between runs.+export function pick(results, { mode = 'auto', codec = 'auto' } = {}) {+ let ok = results.filter(r => r.supported && (mode === 'auto' || r.hw === (mode === 'hw')) && (codec === 'auto' || r.codec === codec)).sort((a, b) => b.fps - a.fps);+ if (mode === 'auto' && ok.some(r => r.rc === 'quantizer')) ok = ok.filter(r => r.rc === 'quantizer');+ if (!ok.length) return null;+ const h264 = ok.find(r => r.codec === 'h264');+ return h264 && h264.fps >= ok[0].fps * 0.8 ? h264 : ok[0];+}++// pages: the already open render pages, one per worker. Probing on all of them at once measures what a parallel+// render will really get (encoders share the CPU and the GPU).+export async function selectEncoder({ pages, machine, width, height, fps, mode, codec, bitrate, qp, reprobe, log }) {+ const machineKey = ['v2', machine.chrome, machine.gpu, cpus()[0]?.model, process.platform].join(' | ');+ const key = `${width}x${height}@${Math.round(fps)} x${pages.length}`;+ const cache = load();+ let entry = !reprobe && cache.machine === machineKey ? cache.entries?.[key] : null, source = 'cache';++ if (!entry) {+ source = 'probed now';+ const frames = Math.max(24, Math.min(90, Math.round((90 * 1920 * 1080) / (width * height) * 2)));+ const results = [];+ for (const c of CANDIDATES) {+ const br = defaultBitrate(c.codec, width, height, fps);+ const base = { ...c, width, height, fps, frames, bitrate: br, qp: DEFAULT_QP[c.codec], codecString: codecString(c.codec, width, height, fps, br) };+ let rc, per;+ for (rc of ['quantizer', 'variable']) { // constant QP first; variable bitrate when the encoder has no QP mode+ per = await Promise.all(pages.map(p => p.evaluate(`window.__motlab.probeEncoder(${JSON.stringify({ ...base, rc })})`)));+ if (per.every(r => r.supported)) break;+ }+ const supported = per.every(r => r.supported);+ results.push({ ...c, supported, ...(supported ? { rc, fps: +per.reduce((s, r) => s + r.fps, 0).toFixed(1) } : { fps: 0, error: per.find(r => r.error)?.error }) });+ log(` probe ${label(c).padEnd(16)} ${supported ? `${String(results.at(-1).fps).padStart(6)} fps ${rc === 'quantizer' ? 'constant QP' : 'variable bitrate'}` : 'not supported'}`);+ }+ await Promise.all(pages.map(p => p.evaluate('window.__motlab.probeDone()')));+ entry = { at: new Date().toISOString(), results };+ const next = cache.machine === machineKey ? cache : { machine: machineKey, entries: {} };+ next.entries[key] = entry;+ try { mkdirSync(join(cacheFile(), '..'), { recursive: true }); writeFileSync(cacheFile(), JSON.stringify(next, null, 2)); } catch (e) { log(` (could not save probe cache: ${e.message})`); }+ }++ const best = pick(entry.results, { mode, codec });+ if (!best) throw new Error(`no usable encoder for ${width}x${height} with --encoder ${mode} --codec ${codec}`);+ const br = bitrate || defaultBitrate(best.codec, width, height, fps);+ const rc = bitrate ? 'variable' : best.rc; // an explicit --bitrate asks for variable bitrate+ return { codec: best.codec, hw: best.hw, rc, qp: qp ?? DEFAULT_QP[best.codec], bitrate: br, codecString: codecString(best.codec, width, height, fps, br), probedFps: best.fps, source, results: entry.results };+}diff --git a/src/project.js b/src/project.jsnew file mode 100644index 0000000..76047b6--- /dev/null+++ b/src/project.js@@ -0,0 +1,89 @@+// A project is a folder of scene pages plus a project.json:+// { "fps": 30, "scenes": ["scenes/01.html", ...], "audio": [{ "file": "audio/music.wav", "start": 0, "volume": 0.8 }] }+// Scenes play back to back in list order. A scene may be { "file": ..., "transition": { "type": "crosswarp",+// "duration": 0.6, "ease": "inOutCubic", "params": {} } }: the previous scene turns into it over that time, so the two+// overlap and the video is that much shorter. Audio files are mixed at their start time (seconds) and volume (1 = as is).+// An audio entry may also be a video file (its sound is used), with optional "from" (seconds into the file) and "duration".+import { spawnSync } from 'node:child_process';+import { existsSync, mkdirSync, mkdtempSync, readFileSync, renameSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { basename, dirname, join, resolve } from 'node:path';+import { finalize, run } from './ffmpeg.js';+import { findTransition, transitionProgress } from './page/transitions.js';+import { renderVideo } from './render.js';++// The scenes as { file, transition }, each transition with its length in frames (n): its duration on the frame grid,+// at least 1. The viewer applies the same rule.+export function projectScenes(p) {+ return p.scenes.map((s, i) => {+ const scene = typeof s === 'string' ? { file: s } : { ...s };+ if (!scene.file) throw new Error(`scene ${i + 1} has no "file"`);+ const tr = scene.transition;+ if (tr && i === 0) throw new Error(`scene 1 (${scene.file}) has a transition, but there is no scene before it`);+ if (tr) {+ scene.transition = { ease: 'inOutCubic', params: {}, ...tr, n: Math.max(1, Math.round((Number(tr.duration) || 0) * p.fps)) };+ try { scene.transition.type = findTransition(tr.type).name; transitionProgress(0, 1, scene.transition.ease); }+ catch (e) { throw new Error(`scene ${i + 1} (${scene.file}): ${e.message}`); }+ }+ return scene;+ });+}++// A project is named by its folder (which holds project.json) or by a .json file in it, such as storyboard.json.+// Paths inside the file are relative to that folder, and `name` is used for output files.+export function projectPaths(target) {+ const t = resolve(target), isFile = t.toLowerCase().endsWith('.json'), root = isFile ? dirname(t) : t;+ const file = isFile ? t : join(root, 'project.json'), stem = basename(file).replace(/\.json$/i, '');+ if (!existsSync(file)) throw new Error(`no project file at ${file}`);+ return { root, file, name: stem === 'project' ? basename(root) : `${basename(root)}-${stem.replace(/^project-/, '')}` }; // project-tiktok.json: <folder>-tiktok+}++export async function renderProject({ dir, out, scale, log = console.log, signal }) { // signal: an AbortSignal that stops the render+ 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';+ 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.+ // A transition is a part of its own between the two scenes: their overlapping frames, mixed by+ // __motlab/transition.html, and left out of the scenes' own parts.+ const parts = [], scenes = projectScenes(p), same = () => parts[0] && { encoder: parts[0].hw ? 'hw' : 'sw', codec: parts[0].codec };+ for (const [i, scene] of scenes.entries()) {+ const into = scene.transition, next = scenes[i + 1]?.transition;+ signal?.throwIfAborted();+ log(`\nScene ${i + 1}/${scenes.length}: ${scene.file}`);+ const part = await renderVideo({ page: join(dir, scene.file), root: dir, out: join(tmp, `${parts.length}.mp4`), fps: p.fps, scale, log, signal,+ head: into?.n, tail: next?.n, ...same() });+ // a stream copy join of parts with different sizes makes an MP4 that changes resolution partway through+ if (parts[0] && (part.width !== parts[0].width || part.height !== parts[0].height))+ throw new Error(`${scene.file} is ${part.width}x${part.height} but ${scenes[0].file} is ${parts[0].width}x${parts[0].height}. All scenes in a project must have the same canvas size`);+ parts.push(part);+ if (!next) continue;+ log(`\nTransition ${i + 1} to ${i + 2}: ${next.type}, ${next.n} frames`);+ const query = new URLSearchParams({ from: scene.file, to: scenes[i + 1].file, offset: (part.pageFrames - next.n) / p.fps, frames: next.n,+ fps: p.fps, type: next.type, ease: next.ease, params: JSON.stringify(next.params) });+ parts.push(await renderVideo({ url: '__motlab/transition.html', query: String(query), root: dir, out: join(tmp, `${parts.length}.mp4`),+ fps: p.fps, scale, log, signal, ...same() }));+ }+ const duration = parts.reduce((sum, s) => sum + s.duration, 0);++ let audio;+ if (p.audio?.length) {+ audio = join(tmp, 'mix.wav');+ // A mono file goes to both channels at full level, as the viewer (WebAudio) plays it. ffmpeg's own up-mix to+ // stereo would put it 3 dB lower.+ const mono = a => spawnSync('ffprobe', ['-v', 'error', '-select_streams', 'a:0', '-show_entries', 'stream=channels', '-of', 'csv=p=0', join(dir, a.file)], { encoding: 'utf8' }).stdout.trim() === '1';+ const chains = p.audio.map((a, i) => `[${i}:a]${mono(a) ? 'pan=stereo|c0=c0|c1=c0,' : ''}adelay=${Math.round((a.start || 0) * 1000)}:all=1,volume=${a.volume ?? 1}[a${i}]`);+ await run('ffmpeg', ['-y', '-loglevel', 'error', ...p.audio.flatMap(a => [...(a.from ? ['-ss', String(a.from)] : []), ...(a.duration ? ['-t', String(a.duration)] : []), '-i', join(dir, a.file)]), '-filter_complex',+ `${chains.join(';')};${p.audio.map((_, i) => `[a${i}]`).join('')}amix=inputs=${p.audio.length}:normalize=0[mix]`,+ '-map', '[mix]', '-ar', '48000', '-ac', '2', '-t', duration.toFixed(6), audio], signal);+ }++ // Written beside the output first and renamed when complete, so a stopped or failed render leaves no half file.+ signal?.throwIfAborted();+ mkdirSync(dirname(out), { recursive: true });+ await finalize({ inputs: parts.map(s => s.out), codec: parts[0].codec, fps: p.fps, audio, out: partial, duration, tmp, signal });+ rmSync(out, { force: true }); renameSync(partial, out);+ log(`\nSAVED ${out} (${scenes.length} scenes${parts.length > scenes.length ? `, ${parts.length - scenes.length} transitions` : ''}, ${duration.toFixed(3)} s${audio ? `, ${p.audio.length} audio files` : ''})`);+ } finally { rmSync(partial, { force: true }); rmSync(tmp, { recursive: true, force: true }); }+}diff --git a/src/render.js b/src/render.jsnew file mode 100644index 0000000..be0004b--- /dev/null+++ b/src/render.js@@ -0,0 +1,181 @@+// The three render modes. A page is opened in headless Chrome, checked against the contract, then driven by the+// in-page runtime (src/page/runtime.js).+import { createReadStream, createWriteStream, existsSync, mkdirSync, mkdtempSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { dirname, join, relative, resolve, sep } from 'node:path';+import { pipeline } from 'node:stream/promises';+import { setTimeout as sleep } from 'node:timers/promises';+import { attachPage, findChrome, launchChrome } from './chrome.js';+import { frameCount, splitFrames } from './codecs.js';+import { finalize, probeVideo } from './ffmpeg.js';+import { label, rate, selectEncoder } from './probe.js';+import { startServer } from './server.js';++const RUNTIME = readFileSync(new URL('./page/runtime.js', import.meta.url), 'utf8');++// Without --root, a page is served from the nearest folder above it that holds a project.json, the folder the viewer+// serves, so a scene can load ../ files; a page outside a project is served from its own folder.+function projectRoot(page) {+ for (let dir = dirname(page); ; dir = dirname(dir)) {+ if (existsSync(join(dir, 'project.json'))) return dir;+ if (dirname(dir) === dir) return dirname(page);+ }+}++function locate(o) {+ if (o.url) return { root: resolve(o.root), url: o.url }; // a page the server provides itself, e.g. __motlab/transition.html+ const page = resolve(o.page), root = resolve(o.root || projectRoot(page)), rel = relative(root, page);+ if (rel.startsWith('..')) throw new Error(`page ${page} is outside the served folder ${root}; pass --root`);+ return { root, url: rel.split(sep).map(encodeURIComponent).join('/') };+}++async function openPage({ server, chromePath, url, scale, query }) {+ const chrome = await launchChrome({ chromePath });+ try {+ const page = await attachPage(chrome);+ await page.navigate(`${server.origin}/${url}?t=0&scale=${scale}${query ? '&' + query : ''}`);+ // Wait for the contract. Give up 8 s after the document has finished loading (or 5 s after a script error).+ const t0 = Date.now(); let loadedAt = 0;+ for (;;) {+ const state = await page.evaluate('typeof window.renderAt === "function" && typeof window.ready !== "undefined" ? "ok" : document.readyState').catch(() => 'loading');+ if (state === 'ok') break;+ const now = Date.now(), errs = page.errors.length ? ` Page errors: ${page.errors.slice(0, 3).join(' | ')}` : '';+ if (state === 'complete' && !loadedAt) loadedAt = now;+ if (now - t0 > 60000 || (loadedAt && now - loadedAt > 8000) || (errs && now - t0 > 5000)) throw new Error(`the page did not expose window.renderAt and window.ready.${errs}`);+ await sleep(50);+ }+ // ready has no time limit (a heavy page can take long), but a page whose ready never resolves should not wait in silence+ const waiting = setTimeout(() => console.warn(`Still waiting for window.ready after 30 s (${url}).${page.errors.length ? ` Page errors: ${page.errors.slice(0, 3).join(' | ')}` : ''}`), 30000);+ try { await page.evaluate('Promise.resolve(window.ready).then(() => true)'); } finally { clearTimeout(waiting); }+ await page.evaluate(RUNTIME);+ return { ...page, chrome };+ } catch (e) { await chrome.close(); throw e; }+}++async function openPages(count, args) {+ const settled = await Promise.allSettled(Array.from({ length: count }, () => openPage(args)));+ const failed = settled.find(s => s.status === 'rejected');+ if (failed) { await Promise.all(settled.filter(s => s.status === 'fulfilled').map(s => s.value.chrome.close())); throw failed.reason; }+ return settled.map(s => s.value);+}++async function readInfo(page, log) {+ const info = await page.evaluate('window.__motlab.info()');+ log(`GPU: ${info.gpu.renderer || 'none (no WebGL: Chrome is not using a GPU)'}`);+ return info;+}++export async function renderVideo(o) {+ const log = o.log || console.log, fps = o.fps ?? 24, scale = o.scale ?? 2, workers = Math.max(1, o.workers ?? 1), started = Date.now();+ const { root, url } = locate(o), out = resolve(o.out), part = out + '.part'; // written here first, renamed when complete+ const server = await startServer({ root }), tmp = mkdtempSync(join(tmpdir(), 'motlab-render-'));+ let pages = [];+ // o.signal (an AbortSignal) stops the render: closing Chrome rejects whatever the render is waiting on.+ const stop = () => pages.forEach(p => p.chrome.close());+ o.signal?.addEventListener('abort', stop);+ try {+ pages = await openPages(workers, { server, chromePath: findChrome(o.chrome), url, scale, query: o.query });+ o.signal?.throwIfAborted();+ const info = await readInfo(pages[0], log), { width, height } = info;+ if (!(info.total > 0)) throw new Error('window.TOTAL must be a positive number of seconds');+ if (width % 2 || height % 2) throw new Error(`canvas is ${width}x${height}; H.264 and HEVC need even dimensions`);+ // head and tail leave out frames at the start and the end, which a scene transition draws instead.+ const pageFrames = frameCount(info.total, fps), head = o.head || 0, tail = o.tail || 0, frames = pageFrames - head - tail;+ if (frames < 1) throw new Error(`the page has ${pageFrames} frames, too few for transitions of ${head} and ${tail} frames at its start and end`);+ const ranges = splitFrames(frames, workers).map(r => ({ start: r.start + head, end: r.end + head }));+ for (const extra of pages.splice(ranges.length)) await extra.chrome.close();+ log(`Page: ${width}x${height}, ${info.total} s, ${frames} frames at ${fps} fps${head || tail ? ` (frames ${head} to ${pageFrames - tail} of ${pageFrames})` : ''}${ranges.length > 1 ? `, ${ranges.length} Chrome processes` : ''}`);++ const enc = await selectEncoder({ pages, machine: { chrome: pages[0].chrome.version, gpu: info.gpu.renderer }, width, height, fps,+ mode: o.encoder || 'auto', codec: o.codec || 'auto', bitrate: o.bitrate, qp: o.qp, reprobe: o.reprobe, log });+ log(`Encoder: ${label(enc)}, ${rate(enc)}, ${enc.codecString} (${enc.source})`);++ const done = ranges.map(() => 0); let lastLine = 0;+ pages.forEach((p, i) => p.onEmit(m => {+ if (m.type !== 'progress') return; done[i] = m.done;+ if (process.stdout.isTTY && Date.now() - lastLine > 200) { lastLine = Date.now(); process.stdout.write(`\r${done.reduce((a, b) => a + b, 0)}/${frames} frames`); }+ }));++ const ext = enc.codec === 'hevc' ? 'h265' : 'h264';+ // Each worker writes its own part into the temp folder: an MP4 muxed in the page by Mediabunny, or a raw Annex B+ // stream. ffmpeg then stream-copies the parts into the final file, which is where the colour tags are written+ // into the bitstream, parallel parts are joined and audio is added.+ const attempt = async mux => {+ const jobs = [];+ for (let i = 0; i < ranges.length; i++) jobs.push(await server.createSink(join(tmp, `${mux}-${i}.${mux === 'raw' ? ext : 'mp4'}`)));+ const t0 = Date.now(); let stats;+ try {+ stats = await Promise.all(ranges.map((r, i) => pages[i].evaluate(`window.__motlab.encodeRange(${JSON.stringify({+ ...r, fps, codec: enc.codec, codecString: enc.codecString, hw: enc.hw, rc: enc.rc, qp: enc.qp, bitrate: enc.bitrate, mux, base: server.base, sink: jobs[i].id,+ keyInterval: Math.max(1, Math.round(fps * 2)) })})`)));+ } catch (e) { o.signal?.throwIfAborted(); throw e; } finally { await Promise.all(jobs.map(j => j.close())); }+ const encodeMs = Date.now() - t0;+ let inputs = jobs.map(j => j.path);+ if (mux === 'raw' && inputs.length > 1) { // Annex B streams join by plain concatenation+ const all = join(tmp, `all.${ext}`), w = createWriteStream(all);+ for (const p of inputs) await pipeline(createReadStream(p), w, { end: false });+ await new Promise(r => w.end(r)); inputs = [all];+ }+ await finalize({ inputs, raw: mux === 'raw', codec: enc.codec, fps, audio: o.audio && resolve(o.audio), out: part, duration: frames / fps, tmp, signal: o.signal });+ return { mux, encodeMs, stats };+ };++ mkdirSync(dirname(out), { recursive: true });+ let res; const want = o.mux || 'auto';+ try { res = await attempt(want === 'raw' ? 'raw' : 'mediabunny'); }+ catch (e) {+ if (want !== 'auto' || o.signal?.aborted) throw e;+ log(`\nMediabunny path failed (${e.message.split('\n')[0]}). Retrying with raw bitstream and ffmpeg.`);+ res = await attempt('raw');+ }+ if (process.stdout.isTTY) process.stdout.write('\r');+ rmSync(out, { force: true }); renameSync(part, out);++ const v = await probeVideo(out), wantDur = frames / fps;+ const muxLabel = `${res.mux === 'raw' ? 'raw bitstream' : 'Mediabunny in the page'}, then ffmpeg -c copy${ranges.length > 1 ? ` (concat of ${ranges.length} parts)` : ''}${o.audio ? ' with audio' : ''}`;+ const summary = { out, frames: v.frames, expectedFrames: frames, pageFrames, duration: v.duration, width, height, fps, gpu: info.gpu.renderer, encoder: label(enc), codec: enc.codec, hw: enc.hw,+ rate: rate(enc), mux: muxLabel, workers: ranges.length, encodeSeconds: res.encodeMs / 1000, totalSeconds: (Date.now() - started) / 1000, size: v.size,+ color: { range: v.color_range, space: v.color_space, transfer: v.color_transfer, primaries: v.color_primaries } };+ log(`Mux: ${muxLabel}`);+ log(`Colour tags: ${v.color_space || 'none'} / ${v.color_range || 'none'} (primaries ${v.color_primaries || 'none'}, transfer ${v.color_transfer || 'none'})`);+ if (v.frames !== frames || Math.abs(v.duration - wantDur) > 0.5 / fps) throw new Error(`output check failed: ${v.frames} frames, ${v.duration} s; expected ${frames} frames, ${wantDur} s (${out})`);+ log(`SAVED ${out} (${v.frames} frames, ${v.duration.toFixed(3)} s, ${(v.size / 1e6).toFixed(1)} MB; encode ${summary.encodeSeconds.toFixed(1)} s = ${(frames / summary.encodeSeconds).toFixed(1)} fps, total ${summary.totalSeconds.toFixed(1)} s)`);+ return summary;+ } finally {+ o.signal?.removeEventListener('abort', stop);+ await Promise.all(pages.map(p => p.chrome.close()));+ await server.close();+ rmSync(part, { force: true }); rmSync(tmp, { recursive: true, force: true });+ }+}++export async function renderStills(o) {+ const log = o.log || console.log, { root, url } = locate(o), outDir = resolve(o.outDir);+ const jpg = (o.format || 'png') !== 'png', server = await startServer({ root });+ let page;+ try {+ page = await openPage({ server, chromePath: findChrome(o.chrome), url, scale: o.scale ?? 1 });+ await readInfo(page, log);+ mkdirSync(outDir, { recursive: true });+ const files = [];+ for (const t of o.times) {+ const sink = await server.createSink(join(outDir, `${t.toFixed(2)}.${jpg ? 'jpg' : 'png'}`));+ try { await page.evaluate(`window.__motlab.still(${JSON.stringify({ t, type: jpg ? 'image/jpeg' : 'image/png', quality: o.quality ?? 0.92, base: server.base, sink: sink.id })})`); } finally { await sink.close(); }+ files.push(sink.path);+ }+ log(`stills -> ${outDir} (${files.length})`);+ return files;+ } finally { if (page) await page.chrome.close(); await server.close(); }+}++export async function dumpEvents(o) {+ const log = o.log || console.log, { root, url } = locate(o), out = resolve(o.out), server = await startServer({ root });+ let page;+ try {+ page = await openPage({ server, chromePath: findChrome(o.chrome), url, scale: 1 });+ const info = await page.evaluate('window.__motlab.info()');+ mkdirSync(dirname(out), { recursive: true }); writeFileSync(out, JSON.stringify(info.events));+ log(`${info.events.length} events -> ${out}`);+ return info.events;+ } finally { if (page) await page.chrome.close(); await server.close(); }+}diff --git a/src/server.js b/src/server.jsnew file mode 100644index 0000000..fd2b4de--- /dev/null+++ b/src/server.js@@ -0,0 +1,91 @@+// Static server for the served folder (the project folder, see locate() in render.js), plus private endpoints the in-page runtime uses to hand encoded bytes to Node.+import { createServer } from 'node:http';+import { createReadStream, existsSync, statSync } from 'node:fs';+import { open } from 'node:fs/promises';+import { randomBytes } from 'node:crypto';+import { pipeline } from 'node:stream';+import { createRequire } from 'node:module';+import { dirname, extname, join, resolve, sep } from 'node:path';++export const TYPES = {+ '.html': 'text/html', '.js': 'text/javascript', '.mjs': 'text/javascript', '.css': 'text/css', '.json': 'application/json',+ '.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.webp': 'image/webp', '.avif': 'image/avif', '.gif': 'image/gif', '.svg': 'image/svg+xml',+ '.ttf': 'font/ttf', '.otf': 'font/otf', '.woff': 'font/woff', '.woff2': 'font/woff2',+ '.mp4': 'video/mp4', '.webm': 'video/webm', '.mov': 'video/quicktime', '.wav': 'audio/wav', '.mp3': 'audio/mpeg', '.ogg': 'audio/ogg', '.m4a': 'audio/mp4',+ '.glb': 'model/gltf-binary', '.gltf': 'model/gltf+json', '.wasm': 'application/wasm', '.txt': 'text/plain',+};++function mediabunnyBundle() { // the ESM browser bundle that ships inside the pinned npm package+ let dir = dirname(createRequire(import.meta.url).resolve('mediabunny'));+ while (!existsSync(join(dir, 'dist', 'bundles', 'mediabunny.min.mjs'))) { const up = dirname(dir); if (up === dir) throw new Error('mediabunny bundle not found'); dir = up; }+ return join(dir, 'dist', 'bundles', 'mediabunny.min.mjs');+}++// Files for scene pages at fixed paths, so a page loads them the same way from the renderer and from the viewer.+const pageFile = file => () => new URL(`./page/${file}`, import.meta.url);+const PAGE_LIBS = {+ '/__motlab/footage.js': pageFile('footage.js'), '/__motlab/motion.js': pageFile('motion.js'), '/__motlab/transitions.js': pageFile('transitions.js'),+ '/__motlab/cuts.js': pageFile('cuts.js'), '/__motlab/transition.html': pageFile('transition.html'), '/__motlab/mediabunny.mjs': mediabunnyBundle,+};+export const pageLib = pathname => PAGE_LIBS[pathname]?.();++// Sends a file, honouring a single Range request so footage can be read in pieces and MP4s can be seeked.+// pipeline, not pipe: the browser aborts many range requests while it seeks, and pipe would leave the file open.+const stream = (res, path, range) => pipeline(createReadStream(path, range), res, () => {});+export function sendFile(req, res, path) {+ const size = statSync(path).size, type = TYPES[extname(String(path)).toLowerCase()] || 'application/octet-stream';+ const m = /^bytes=(\d*)-(\d*)$/.exec(req.headers.range || '');+ const head = { 'Content-Type': type, 'Cache-Control': 'no-store', 'Accept-Ranges': 'bytes' };+ if (m && (m[1] || m[2])) {+ const start = m[1] ? +m[1] : Math.max(0, size - +m[2]), end = m[1] && m[2] ? Math.min(+m[2], size - 1) : size - 1;+ if (start >= size || start > end) { res.writeHead(416, { 'Content-Range': `bytes */${size}` }); return res.end(); }+ res.writeHead(206, { ...head, 'Content-Range': `bytes ${start}-${end}/${size}`, 'Content-Length': end - start + 1 });+ return stream(res, path, { start, end });+ }+ res.writeHead(200, { ...head, 'Content-Length': size });+ stream(res, path);+}++const readBody = req => new Promise((ok, no) => { const parts = []; req.on('data', d => parts.push(d)); req.on('end', () => ok(Buffer.concat(parts))); req.on('error', no); });++export async function startServer({ root }) {+ const ROOT = resolve(root), prefix = `/__motlab/${randomBytes(8).toString('hex')}`;+ const sinks = new Map(); let nextSink = 0;++ const server = createServer(async (req, res) => {+ try {+ const u = new URL(req.url, 'http://x');+ if (u.pathname.startsWith(prefix + '/')) {+ const route = u.pathname.slice(prefix.length + 1);+ if (req.method === 'GET' && route === 'mediabunny.mjs') return sendFile(req, res, mediabunnyBundle());+ if (req.method === 'GET' && route === 'blank.html') { res.writeHead(200, { 'Content-Type': 'text/html' }); return res.end('<!doctype html><meta charset="utf-8"><title>motlab</title>'); }+ const sink = sinks.get(u.searchParams.get('id'));+ if (req.method === 'POST' && sink && (route === 'write' || route === 'append')) {+ const body = await readBody(req);+ if (route === 'write') await sink.fh.write(body, 0, body.length, Number(u.searchParams.get('pos')));+ else await (sink.tail = sink.tail.then(async () => { await sink.fh.write(body, 0, body.length, sink.size); sink.size += body.length; }));+ res.writeHead(204); return res.end();+ }+ res.writeHead(404); return res.end();+ }+ const lib = pageLib(u.pathname);+ if (lib) return sendFile(req, res, lib);+ const path = join(ROOT, decodeURIComponent(u.pathname));+ if ((path !== ROOT && !path.startsWith(ROOT + sep)) || !existsSync(path) || statSync(path).isDirectory()) { res.writeHead(404); return res.end(); }+ sendFile(req, res, path);+ } catch (e) { res.writeHead(500); res.end(String(e && e.message)); }+ });+ await new Promise(r => server.listen(0, '127.0.0.1', r));+ const origin = `http://127.0.0.1:${server.address().port}`;++ return {+ origin, base: origin + prefix,+ // A sink is a file the page may write to: positional writes (MP4 muxer) or appends (raw bitstream, stills).+ async createSink(path) {+ const id = String(++nextSink), sink = { fh: await open(path, 'w'), size: 0, tail: Promise.resolve() };+ sinks.set(id, sink);+ return { id, path, close: async () => { sinks.delete(id); await sink.tail.catch(() => {}); await sink.fh.close(); } };+ },+ close: () => new Promise(r => { server.closeAllConnections(); server.close(r); }),+ };+}diff --git a/src/uninstall.js b/src/uninstall.jsnew file mode 100644index 0000000..02d4638--- /dev/null+++ b/src/uninstall.js@@ -0,0 +1,61 @@+// motlab uninstall: removes what install.js put on this machine. It stops the viewer, then deletes the `motlab`+// launchers, the two skill folders in every agent folder from ~/.motlab/install.json (or, without that record, in+// the agent folders install.js knows), ~/.motlab and the encoder cache. It lists everything and asks first. The+// clone is left, because this command runs from it.+import { existsSync, lstatSync, readFileSync, rmSync } from 'node:fs';+import { homedir } from 'node:os';+import { dirname, join } from 'node:path';+import { createInterface } from 'node:readline/promises';+import { fileURLToPath } from 'node:url';+import { cacheFile } from './probe.js';+import { stopViewer } from './viewer.js';++const HOME = homedir(), STATE = join(HOME, '.motlab'), ROOT = fileURLToPath(new URL('..', import.meta.url)).replace(/[\\/]$/, '');+// The agent skill folders install.js writes to, for an install from before ~/.motlab/install.json existed.+const KNOWN = ['.claude/skills', '.agents/skills', '.gemini/config/skills', '.config/opencode/skills', '.cursor/skills', '.copilot/skills'].map(d => join(HOME, d));++function targets() {+ let record = {}; try { record = JSON.parse(readFileSync(join(STATE, 'install.json'), 'utf8')); } catch {}+ const out = [];+ const bin = record.bin || join(HOME, '.local', 'bin');+ for (const name of ['motlab', 'motlab.cmd']) { // only launchers that run this clone+ const f = join(bin, name);+ try { if (readFileSync(f, 'utf8').includes('motlab.js')) out.push({ path: f, what: 'launcher' }); } catch {}+ }+ for (const dir of new Set([...(record.skillDirs || []), ...KNOWN])) for (const name of ['motlab', 'motlab-assets']) {+ const d = join(dir, name);+ let stat = null; try { stat = lstatSync(d); } catch {}+ if (stat?.isSymbolicLink()) out.push({ path: d, what: 'skill link', link: true }); // removed as a link, never through it+ else if (stat && existsSync(join(d, 'SKILL.md'))) out.push({ path: d, what: 'skill' });+ }+ if (existsSync(STATE)) out.push({ path: STATE, what: 'install record, recent projects, viewer log' });+ const cache = cacheFile(), cacheDir = dirname(cache);+ // The default cache folder is motlab's own; a folder from MOTLAB_CACHE_DIR may hold other things, so only the file goes.+ if (!process.env.MOTLAB_CACHE_DIR && existsSync(cacheDir)) out.push({ path: cacheDir, what: 'encoder timings' });+ else if (existsSync(cache)) out.push({ path: cache, what: 'encoder timings' });+ return out;+}++export async function uninstall({ dryRun = false, yes = false } = {}) {+ const list = targets();+ if (!list.length) { console.log('Nothing from motlab is installed here.'); return 0; }+ console.log('motlab uninstall removes:');+ for (const t of list) console.log(` ${t.path} (${t.what})`);+ console.log(`It leaves the clone in ${ROOT}; delete that folder yourself afterwards.`);+ if (dryRun) return 0;+ if (!yes) {+ if (!process.stdin.isTTY) { console.log('Run it again with --yes to remove them.'); return 1; }+ const rl = createInterface({ input: process.stdin, output: process.stdout });+ const answer = (await rl.question('Remove these? [y/N] ')).trim().toLowerCase();+ rl.close();+ if (answer !== 'y' && answer !== 'yes') { console.log('Nothing removed.'); return 1; }+ }+ // The viewer holds ~/.motlab/viewer.log open. MOTLAB_KEEP_VIEWER is for the tests, which must not stop a real one.+ if (!process.env.MOTLAB_KEEP_VIEWER) try { await stopViewer({ say: true }); } catch (e) { console.log(`Could not stop the viewer: ${e.message}`); }+ for (const t of list) {+ try { rmSync(t.path, t.link ? {} : { recursive: true, force: true, maxRetries: 5, retryDelay: 200 }); console.log(`removed ${t.path}`); }+ catch (e) { console.log(`could not remove ${t.path}: ${e.message}`); }+ }+ console.log(`\nDone. To remove the rest, delete ${ROOT}.`);+ return 0;+}diff --git a/src/update.js b/src/update.jsnew file mode 100644index 0000000..aae4c02--- /dev/null+++ b/src/update.js@@ -0,0 +1,42 @@+import { spawnSync } from 'node:child_process';+import { existsSync } from 'node:fs';+import { join } from 'node:path';+import { fileURLToPath } from 'node:url';++// motlab update: the engine folder is a git clone. It fetches its branch from origin, fast-forwards to it, and runs the+// new install.js with --update, which runs npm ci and copies the skills again to every folder they were installed in.+const ROOT = fileURLToPath(new URL('..', import.meta.url)).replace(/[\\/]$/, '');+const git = (...args) => {+ const r = spawnSync('git', args, { cwd: ROOT, encoding: 'utf8' });+ if (r.error) throw new Error('git was not found. Install git, or update by hand as in docs/install.md#updating');+ return { ok: r.status === 0, out: (r.stdout || '').trimEnd(), err: (r.stderr || '').trim() };+};++export function update({ dryRun = false } = {}) {+ if (!existsSync(join(ROOT, '.git'))) throw new Error(`${ROOT} is not a git clone, so it cannot update itself. Clone motlab again (docs/install.md) and run node install.js there`);+ const branch = git('rev-parse', '--abbrev-ref', 'HEAD').out;+ if (branch === 'HEAD') throw new Error(`${ROOT} is not on a branch. Check out main, then run motlab update again`);+ const changed = git('status', '--porcelain', '--untracked-files=no').out;+ if (changed) throw new Error(`${ROOT} has local changes:\n${changed}\nCommit or stash them, then run motlab update again`);++ console.log(`Checking ${branch} on origin...`);+ const f = git('fetch', 'origin', branch);+ if (!f.ok) throw new Error(`git fetch failed: ${f.err}`);+ const from = git('rev-parse', '--short', 'HEAD').out, count = range => Number(git('rev-list', '--count', range).out);+ const behind = count(`HEAD..origin/${branch}`), ahead = count(`origin/${branch}..HEAD`);+ if (!behind) { console.log(`motlab is up to date (${from}).`); return 0; }+ console.log(`${behind} new commit${behind > 1 ? 's' : ''}:\n${git('log', '--oneline', `HEAD..origin/${branch}`).out}\n`);+ if (ahead) throw new Error(`this clone also has ${ahead} commit${ahead > 1 ? 's' : ''} that origin does not, so it cannot fast-forward. Push or rebase them, then run motlab update again`);++ if (dryRun) console.log(`[dry run] git merge --ff-only origin/${branch}`);+ else {+ const m = git('merge', '--ff-only', `origin/${branch}`);+ if (!m.ok) throw new Error(`git merge failed: ${m.err}`);+ console.log(`Updated ${from} to ${git('rev-parse', '--short', 'HEAD').out}.\n`);+ }+ // the installer that just arrived, so a change to it applies to this update+ const r = spawnSync(process.execPath, ['install.js', '--update', ...(dryRun ? ['--dry-run'] : [])], { cwd: ROOT, stdio: 'inherit' });+ if (r.status) return r.status;+ if (!dryRun) console.log('\nA viewer that is already running keeps the old code: run motlab restart. Start a new agent session to load the new skills.');+ return 0;+}diff --git a/src/viewer.js b/src/viewer.jsnew file mode 100644index 0000000..1b35918--- /dev/null+++ b/src/viewer.js@@ -0,0 +1,78 @@+// The viewer as a background server. `motlab start` runs it on 4173 (the next free port when something else has+// 4173), `motlab edit <project>` opens a project in it and starts it first when none is running, `motlab stop` ends+// it and `motlab restart` starts it again from the same folder. The server is `motlab start --foreground` in a+// detached process, writing to ~/.motlab/viewer.log. A running viewer is found by asking each port for+// /__motlab/editor, so there is no pid file to go stale.+import { spawn } from 'node:child_process';+import { closeSync, mkdirSync, openSync, readFileSync } from 'node:fs';+import { homedir } from 'node:os';+import { join } from 'node:path';+import { fileURLToPath } from 'node:url';+import { setTimeout as sleep } from 'node:timers/promises';+import { projectPaths } from './project.js';++export const FIRST_PORT = 4173, LAST_PORT = 4190;+const BIN = fileURLToPath(new URL('../bin/motlab.js', import.meta.url));+export const LOG = join(homedir(), '.motlab', 'viewer.log');++// 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.+export 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 };+ }+ return null;+}++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 } = {}) {+ 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 });+ 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 (exited !== null) break;+ await sleep(250);+ }+ throw new Error(`the viewer did not start${exited !== null ? ` (it exited with code ${exited})` : ' within 20 s'}. ${LOG}:\n${logTail()}`);+}++export async function stopViewer({ say = true } = {}) {+ const v = await findViewer();+ 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(() => {});+ 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; }+ if (Date.now() > until - 5000) try { process.kill(v.pid); } catch {}+ }+ throw new Error(`the viewer on ${v.url} (process ${v.pid}) did not stop within 10 s`);+}++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() });+}++// motlab edit [project]: the project in the running viewer, after starting one if needed. Ends once the address is printed.+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 }) });+ if (!r.ok) throw new Error(await r.text());+ console.log(`Viewer: ${v.url}${(await r.json()).url} (${file})`);+}diff --git a/test/codecs.test.js b/test/codecs.test.jsnew file mode 100644index 0000000..b56cebc--- /dev/null+++ b/test/codecs.test.js@@ -0,0 +1,42 @@+import assert from 'node:assert/strict';+import { test } from 'node:test';+import { codecString, defaultBitrate, frameCount, splitFrames } from '../src/codecs.js';+import { pick } from '../src/probe.js';++test('splitFrames covers every frame once, in order', () => {+ for (const [n, w] of [[200, 1], [200, 3], [7, 4], [3, 8], [1, 1]]) {+ const r = splitFrames(n, w);+ assert.equal(r[0].start, 0); assert.equal(r.at(-1).end, n);+ r.forEach((x, i) => { assert.ok(x.end > x.start); if (i) assert.equal(x.start, r[i - 1].end); });+ assert.ok(r.length <= Math.min(n, w));+ }+});++test('frameCount rounds TOTAL * fps to the nearest frame', () => {+ assert.equal(frameCount(8, 25), 200); assert.equal(frameCount(8, 29.97), 240); assert.equal(frameCount(2.5, 24), 60);+});++test('codec strings pick a level that fits size, rate and bitrate', () => {+ assert.equal(codecString('h264', 1920, 1080, 25, 20e6), 'avc1.640028');+ assert.equal(codecString('h264', 1920, 1080, 60, 20e6), 'avc1.64002a');+ assert.equal(codecString('h264', 3840, 2160, 25, 60e6), 'avc1.640033');+ assert.equal(codecString('h264', 3840, 2160, 60, 60e6), 'avc1.640034');+ assert.equal(codecString('hevc', 1920, 1080, 25, 10e6), 'hvc1.1.6.L120.B0');+ assert.equal(codecString('hevc', 3840, 2160, 25, 36e6), 'hvc1.1.6.H150.B0');+ assert.ok(defaultBitrate('h264', 3840, 2160, 25) > defaultBitrate('h264', 1920, 1080, 25));+});++test('pick prefers constant QP in auto, speed in hw and sw, and keeps H.264 unless HEVC is clearly faster', () => {+ const results = [+ { codec: 'h264', hw: true, supported: true, rc: 'quantizer', fps: 70 },+ { codec: 'h264', hw: false, supported: true, rc: 'variable', fps: 150 },+ { codec: 'hevc', hw: true, supported: true, rc: 'quantizer', fps: 75 },+ { codec: 'hevc', hw: false, supported: false, fps: 0 },+ ];+ assert.deepEqual(pick(results), results[0]);+ assert.deepEqual(pick(results, { mode: 'sw' }), results[1]);+ assert.deepEqual(pick(results, { codec: 'hevc' }), results[2]);+ assert.equal(pick(results, { mode: 'sw', codec: 'hevc' }), null);+ assert.deepEqual(pick([results[1], results[3]]), results[1]); // no constant-QP encoder: fastest overall+ assert.deepEqual(pick([{ ...results[0], fps: 40 }, results[2]]), results[2]); // HEVC far ahead+});diff --git a/test/editor-text.test.js b/test/editor-text.test.jsnew file mode 100644index 0000000..19d91e8--- /dev/null+++ b/test/editor-text.test.js@@ -0,0 +1,26 @@+import assert from 'node:assert/strict';+import { readFileSync } from 'node:fs';+import { test } from 'node:test';++// The viewer's text is one table, TEXT, with the Indonesian and the English side by side. A key the page asks for that+// is not in it stops the page, so every key used in the markup and the script has to be there, in both languages.+test('every viewer text is in TEXT, in Indonesian and English', () => {+ const html = readFileSync('src/editor.html', 'utf8');+ const src = html.slice(html.indexOf('const TEXT = {') + 13, html.indexOf('\n};', html.indexOf('const TEXT = {')) + 2);+ const TEXT = new Function(`return ${src}`)();+ for (const [k, v] of Object.entries(TEXT)) {+ assert.ok(Array.isArray(v) && v.length === 2, `${k}: needs [Indonesian, English]`);+ assert.equal(typeof v[0], typeof v[1], `${k}: both or neither are functions`);+ if (typeof v[0] === 'function') assert.equal(v[0].length, v[1].length, `${k}: both take the same arguments`);+ else assert.ok(v[0] && v[1], `${k}: empty text`);+ }+ const code = html.split('\n').filter(l => !l.trim().startsWith('//')).join('\n');+ const used = new Set([+ ...[...code.matchAll(/\bL\('(\w+)'/g)].map(m => m[1]),+ ...[...code.matchAll(/\bL\([\w.]+ \? '(\w+)' : '(\w+)'\)/g)].flatMap(m => [m[1], m[2]]),+ ...[...code.matchAll(/data-label="(\w+)"/g)].map(m => m[1]),+ ...[...code.matchAll(/data-t="([^"]+)"/g)].flatMap(m => m[1].split(' ').map(p => p.split('=').at(-1))),+ ]);+ assert.ok(used.size > 50);+ for (const k of used) assert.ok(k in TEXT, `"${k}" is used but not in TEXT`);+});diff --git a/test/fixtures/basic.html b/test/fixtures/basic.htmlnew file mode 100644index 0000000..5c0925b--- /dev/null+++ b/test/fixtures/basic.html@@ -0,0 +1,15 @@+<!doctype html><html><head><meta charset="utf-8"><title>fixture</title></head><body style="margin:0"><canvas id="c"></canvas>+<script>+// Smallest page that follows the contract: canvas #c, renderAt(t), TOTAL, ready, EVENTS, ?t=, ?scale=.+// Two flat fields of known colour let the tests check that encoding does not shift colour.+const q = new URLSearchParams(location.search), SCALE = parseFloat(q.get('scale') || '1'), W = 640 * SCALE, H = 360 * SCALE;+const cv = document.getElementById('c'); cv.width = W; cv.height = H; const ctx = cv.getContext('2d');+function render(t) {+ ctx.fillStyle = '#30E2A8'; ctx.fillRect(0, 0, W / 2, H);+ ctx.fillStyle = '#F5D04E'; ctx.fillRect(W / 2, 0, W / 2, H);+ ctx.fillStyle = '#111'; ctx.fillRect(W * 0.6 + t * W * 0.2, H * 0.4, W * 0.1, H * 0.2);+}+window.TOTAL = 1; window.EVENTS = [{ name: 'hit', t: 0.5 }];+window.renderAt = async t => { await null; render(t); }; // async on purpose: the contract allows it+window.ready = Promise.resolve().then(() => { render(parseFloat(q.get('t') || '0')); return true; });+</script></body></html>diff --git a/test/install.test.js b/test/install.test.jsnew file mode 100644index 0000000..f89e956--- /dev/null+++ b/test/install.test.js@@ -0,0 +1,50 @@+import assert from 'node:assert/strict';+import { spawnSync } from 'node:child_process';+import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { test } from 'node:test';++// `motlab update` runs `install.js --update`, which has to find every folder the skills went to: the ones in+// ~/.motlab/install.json and agent folders that already hold the skill from an install before that file existed.+test('install.js --update puts the skills back where they were', () => {+ const home = mkdtempSync(join(tmpdir(), 'motlab-home-'));+ try {+ mkdirSync(join(home, '.agents', 'skills', 'motlab'), { recursive: true });+ writeFileSync(join(home, '.agents', 'skills', 'motlab', 'SKILL.md'), 'old');+ mkdirSync(join(home, '.motlab'));+ writeFileSync(join(home, '.motlab', 'install.json'), JSON.stringify({ skillDirs: [join(home, 'custom')], link: false }));+ const r = spawnSync(process.execPath, ['install.js', '--update', '--dry-run'], { encoding: 'utf8', env: { ...process.env, HOME: home, USERPROFILE: home } });+ assert.equal(r.status, 0, r.stderr);+ assert.ok(r.stdout.includes(`replace ${join(home, '.agents', 'skills', 'motlab')}`), r.stdout);+ assert.ok(r.stdout.includes(`-> ${join(home, 'custom', 'motlab-assets')}`), r.stdout);+ assert.ok(!r.stdout.includes(join(home, '.claude')), 'an agent folder without the skill stays untouched');+ } finally { rmSync(home, { recursive: true, force: true }); }+});++// `motlab uninstall` removes only what install.js wrote: launchers that run motlab, skill folders that hold a+// SKILL.md, ~/.motlab and the encoder cache, and asks first. Without a terminal and without --yes it removes nothing.+test('motlab uninstall removes what the installer wrote and nothing else', () => {+ const home = mkdtempSync(join(tmpdir(), 'motlab-home-'));+ const put = (f, text = 'x') => { mkdirSync(join(f, '..'), { recursive: true }); writeFileSync(f, text); };+ try {+ put(join(home, 'bin', 'motlab.cmd'), '@node "C:/clone/bin/motlab.js" %*');+ put(join(home, 'bin', 'other.cmd'), 'echo other');+ put(join(home, 'custom', 'motlab', 'SKILL.md'));+ put(join(home, '.claude', 'skills', 'motlab-assets', 'SKILL.md'));+ put(join(home, '.claude', 'skills', 'someone-else', 'SKILL.md'));+ put(join(home, '.motlab', 'install.json'), JSON.stringify({ skillDirs: [join(home, 'custom')], bin: join(home, 'bin') }));+ put(join(home, 'local', 'motlab', 'encoder-probe.json'), '{}');+ const env = { ...process.env, HOME: home, USERPROFILE: home, LOCALAPPDATA: join(home, 'local'), MOTLAB_KEEP_VIEWER: '1', MOTLAB_CACHE_DIR: '' };+ delete env.MOTLAB_CACHE_DIR;+ const run = (...args) => spawnSync(process.execPath, ['bin/motlab.js', 'uninstall', ...args], { encoding: 'utf8', env, input: '' });+ const gone = [join(home, 'bin', 'motlab.cmd'), join(home, 'custom', 'motlab'), join(home, '.claude', 'skills', 'motlab-assets'), join(home, '.motlab'), join(home, 'local', 'motlab')];+ const asked = run();+ assert.equal(asked.status, 1, asked.stdout);+ for (const f of gone) { assert.ok(asked.stdout.includes(f), `${f} is listed`); assert.ok(existsSync(f), `${f} is kept without --yes`); }+ const r = run('--yes');+ assert.equal(r.status, 0, r.stdout + r.stderr);+ for (const f of gone) assert.ok(!existsSync(f), `${f} is removed`);+ assert.ok(existsSync(join(home, 'bin', 'other.cmd')) && existsSync(join(home, '.claude', 'skills', 'someone-else')), 'other files stay');+ } finally { rmSync(home, { recursive: true, force: true }); }+});diff --git a/test/motion.test.js b/test/motion.test.jsnew file mode 100644index 0000000..0d197db--- /dev/null+++ b/test/motion.test.js@@ -0,0 +1,58 @@+import assert from 'node:assert/strict';+import { test } from 'node:test';+import { cubicBezier, ease, spring, stagger, tween } from '../src/page/motion.js';+import { findTransition, transitionNames, transitionProgress } from '../src/page/transitions.js';+import { 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}`);++test('every easing starts at 0 and ends at 1', () => {+ for (const [name, e] of Object.entries(ease)) { near(e(0), 0, 1e-6); near(e(1), 1, 1e-6); assert.ok(Number.isFinite(e(0.5)), name); }+});++test('cubicBezier matches CSS ease and is the identity on a straight line', () => {+ near(cubicBezier(0.25, 0.1, 0.25, 1)(0.5), 0.8024, 2e-4); // CSS "ease" at half time+ const line = cubicBezier(0.3, 0.3, 0.7, 0.7);+ for (const k of [0.1, 0.37, 0.9]) near(line(k), k, 1e-5);+});++test('spring starts at 0 with the given velocity and settles at 1', () => {+ for (const cfg of [{ damping: 10 }, { damping: 20 }, { damping: 40 }, { damping: 12, velocity: 5 }]) { // under, critical, over damped+ const s = spring({ stiffness: 100, mass: 1, ...cfg }), h = 1e-5;+ near(s(h) / h, cfg.velocity || 0, 0.01);+ near(s(s.duration), 1, 1e-3); near(s(s.duration + 3), 1, 1e-3);+ assert.ok(s.duration > 0 && s.duration < 30);+ }+ const bouncy = spring({ stiffness: 100, damping: 10 });+ assert.ok(Math.max(...Array.from({ length: 200 }, (_, i) => bouncy(i / 100))) > 1.15, 'damping ratio 0.5 overshoots by 16%');+ const critical = spring({ stiffness: 100, damping: 20 }); let last = 0;+ for (let t = 0; t < 2; t += 0.01) { assert.ok(critical(t) >= last - 1e-9); last = critical(t); }+});++test('tween holds outside its keys and blends numbers and arrays', () => {+ const keys = [[1, 0], [2, 10, ease.linear], [3, 10]];+ assert.equal(tween(0, keys), 0); assert.equal(tween(1.5, keys), 5); assert.equal(tween(9, keys), 10);+ assert.deepEqual(tween(0.5, [[0, [0, 0]], [1, [10, 20], ease.linear]]), [5, 10]);+});++test('stagger spaces items from the start, the end or the centre', () => {+ assert.equal(stagger(2, 0.1, 1), 1.2);+ near(stagger(0, 0.1, 0, { n: 5, from: 'end' }), 0.4, 1e-12);+ assert.equal(stagger(2, 0.1, 0, { n: 5, from: 'center' }), 0);+});++test('transitions are found by any case and their progress covers the frame middles', () => {+ assert.equal(findTransition('CROSSWARP').name, 'crosswarp');+ assert.throws(() => findTransition('nope'), /use one of/);+ near(transitionProgress(0, 2, 'linear'), 0.25, 1e-12); near(transitionProgress(1, 2, 'linear'), 0.75, 1e-12);+ assert.throws(() => transitionProgress(0, 2, 'wobble'), /unknown ease/);+ for (const name of transitionNames) assert.match(findTransition(name).glsl, /vec4 transition\s*\(/);+});++test('project scenes accept paths and objects with transitions', () => {+ const s = projectScenes({ fps: 30, scenes: ['a.html', { file: 'b.html', transition: { type: 'fade', duration: 0.5 } }] });+ assert.deepEqual(s[0], { file: 'a.html' });+ assert.equal(s[1].transition.n, 15); assert.equal(s[1].transition.ease, 'inOutCubic');+ assert.throws(() => projectScenes({ fps: 30, scenes: [{ file: 'a.html', transition: { type: 'fade', duration: 1 } }] }), /no scene before it/);+ assert.throws(() => projectScenes({ fps: 30, scenes: ['a.html', { file: 'b.html', transition: { type: 'zap', duration: 1 } }] }), /scene 2 .*unknown transition/);+});diff --git a/test/notes.test.js b/test/notes.test.jsnew file mode 100644index 0000000..26a5deb--- /dev/null+++ b/test/notes.test.js@@ -0,0 +1,36 @@+// How one page's save of notes is merged into selection.json, when another tab or the agent changed the file meanwhile.+import assert from 'node:assert/strict';+import { test } from 'node:test';+import { mergeNotes } from '../src/editor.js';++const v = 'project.json', note = (n, id, extra = {}) => ({ n, ...(id ? { id } : {}), note: `note ${n}`, image: `selection/${n}.png`, project: v, ...extra });+const ns = list => list.map(m => `${m.n}:${m.id || '-'}`);++test('notes made in another tab are kept, and a taken number moves to the next free one', () => {+ const old = [note(1, 'a1')]; // tab A saved note 1+ const { all, renumbered } = mergeNotes(old, { marks: [note(1, 'b1')] }, v); // tab B, which has not seen it, saves its own note 1+ assert.deepEqual(ns(all), ['1:a1', '2:b1']);+ assert.deepEqual(renumbered, [['b1', 1, 2]]);+ assert.equal(all[1].image, 'selection/2.png');+});++test('a deleted note goes only when the page names it', () => {+ const old = [note(1, 'a1'), note(2, 'b1')];+ assert.deepEqual(ns(mergeNotes(old, { marks: [note(2, 'b1')] }, v).all), ['1:a1', '2:b1']); // left out: kept+ assert.deepEqual(ns(mergeNotes(old, { marks: [note(2, 'b1')], deleted: ['a1'] }, v).all), ['2:b1']);+});++test('notes from before ids are matched by number', () => {+ const old = [note(1), note(2)];+ const { all, renumbered } = mergeNotes(old, { marks: [{ ...note(1), note: 'edited' }, note(2)], deleted: [] }, v);+ assert.deepEqual(ns(all), ['1:-', '2:-']); assert.equal(all[0].note, 'edited'); assert.deepEqual(renumbered, []);+ assert.deepEqual(ns(mergeNotes(old, { marks: [note(2)], deleted: ['#1'] }, v).all), ['2:-']);+});++test('done stays the file\'s unless the page toggled it, and other versions are untouched', () => {+ const old = [note(1, 'a1', { done: true }), { ...note(2, 'x2'), project: 'project-tiktok.json' }];+ const { all } = mergeNotes(old, { marks: [note(1, 'a1'), note(3, 'c3')] }, v);+ assert.equal(all.find(m => m.id === 'a1').done, true); // the agent marked it done in the file+ assert.ok(all.some(m => m.id === 'x2' && m.project === 'project-tiktok.json'));+ assert.equal(mergeNotes(old, { marks: [note(1, 'a1')], toggled: [1] }, v).all.find(m => m.id === 'a1').done, undefined);+});diff --git a/test/render.test.js b/test/render.test.jsnew file mode 100644index 0000000..c542b00--- /dev/null+++ b/test/render.test.js@@ -0,0 +1,110 @@+// End to end: needs Chrome, ffmpeg and ffprobe. Renders the fixture page and checks what came out.+import assert from 'node:assert/strict';+import { spawnSync } from 'node:child_process';+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { after, test } from 'node:test';+import { fileURLToPath } from 'node:url';+import { probeVideo } from '../src/ffmpeg.js';+import { renderProject } from '../src/project.js';+import { dumpEvents, renderStills, renderVideo } from '../src/render.js';++const page = fileURLToPath(new URL('./fixtures/basic.html', import.meta.url));+const dir = mkdtempSync(join(tmpdir(), 'motlab-test-'));+process.env.MOTLAB_CACHE_DIR = join(dir, 'cache'); // keep test probes out of the real cache+after(() => rmSync(dir, { recursive: true, force: true }));+const quiet = { log: () => {} };++// Mean RGB of a region of a decoded frame (the first one by default).+function meanRgb(file, crop, frame = 0) {+ const r = spawnSync('ffmpeg', ['-v', 'error', '-i', file, '-vf', `select=eq(n\\,${frame}),crop=${crop},scale=1:1:flags=area,format=rgb24`, '-frames:v', '1', '-f', 'rawvideo', '-']);+ return [...r.stdout.subarray(0, 3)];+}+const near = (got, want, tol) => got.length === 3 && got.every((v, i) => Math.abs(v - want[i]) <= tol);++async function checkVideo(name, opts, frames) {+ const out = join(dir, name);+ const s = await renderVideo({ page, out, fps: 30, scale: 1, ...quiet, ...opts });+ const v = await probeVideo(out);+ assert.equal(v.frames, frames); assert.equal(Number(v.nb_frames), frames);+ assert.ok(Math.abs(v.duration - frames / 30) < 1e-3, `duration ${v.duration}`);+ assert.deepEqual([v.width, v.height], [640, 360]);+ assert.deepEqual([v.color_range, v.color_space, v.color_transfer, v.color_primaries], ['tv', 'bt709', 'bt709', 'bt709']);+ const left = meanRgb(out, '200:200:60:80'), right = meanRgb(out, '100:60:340:20');+ assert.ok(near(left, [0x30, 0xE2, 0xA8], 4), `left field decoded as ${left}`);+ assert.ok(near(right, [0xF5, 0xD0, 0x4E], 4), `right field decoded as ${right}`);+ assert.ok(!existsSync(out + '.part'));+ return s;+}++test('video: default encoder, Mediabunny mux', async () => {+ const s = await checkVideo('auto.mp4', {}, 30);+ assert.match(s.mux, /^Mediabunny/);+});+test('video: software encoder', () => checkVideo('sw.mp4', { encoder: 'sw' }, 30));+test('video: raw bitstream mux', async () => {+ const s = await checkVideo('raw.mp4', { mux: 'raw', encoder: 'sw' }, 30);+ assert.match(s.mux, /^raw bitstream/);+});+test('video: three workers joined with concat', async () => {+ const s = await checkVideo('workers.mp4', { workers: 3, encoder: 'sw' }, 30);+ assert.equal(s.workers, 3);+});+test('video: audio is muxed and never extends the video', async () => {+ const wav = join(dir, 'tone.wav');+ spawnSync('ffmpeg', ['-v', 'error', '-f', 'lavfi', '-i', 'sine=frequency=440:duration=3', wav]);+ await checkVideo('audio.mp4', { audio: wav, encoder: 'sw' }, 30);+ const a = JSON.parse(spawnSync('ffprobe', ['-v', 'error', '-select_streams', 'a:0', '-show_entries', 'stream=codec_name,duration', '-of', 'json', join(dir, 'audio.mp4')], { encoding: 'utf8' }).stdout).streams[0];+ assert.equal(a.codec_name, 'aac'); assert.ok(Math.abs(Number(a.duration) - 1) < 0.05, `audio duration ${a.duration}`);+});+test('stills: PNG at the scaled page size, exact colour', async () => {+ const files = await renderStills({ page, outDir: join(dir, 'stills'), times: [0, 0.5], scale: 2, ...quiet });+ assert.equal(files.length, 2); assert.match(files[1], /0\.50\.png$/);+ const p = JSON.parse(spawnSync('ffprobe', ['-v', 'error', '-show_entries', 'stream=width,height', '-of', 'json', files[1]], { encoding: 'utf8' }).stdout).streams[0];+ assert.deepEqual([p.width, p.height], [1280, 720]);+ assert.deepEqual(meanRgb(files[1], '200:200:60:80'), [0x30, 0xE2, 0xA8]);+});+test('events: window.EVENTS is written as JSON', async () => {+ const out = join(dir, 'events.json');+ await dumpEvents({ page, out, ...quiet });+ assert.deepEqual(JSON.parse(readFileSync(out, 'utf8')), [{ name: 'hit', t: 0.5 }]);+});+test('a page without the contract fails with a clear message', async () => {+ await assert.rejects(renderVideo({ page: fileURLToPath(new URL('../package.json', import.meta.url)), out: join(dir, 'x.mp4'), ...quiet }), /renderAt/);+});++test('project: a transition overlaps two scenes and mixes them on the frame grid', async () => {+ const proj = join(dir, 'proj'), flat = (name, colour) => writeFileSync(join(proj, name), `<!doctype html><canvas id="c" width="320" height="180"></canvas><script>+ const c = document.getElementById('c').getContext('2d'); window.TOTAL = 1; window.ready = Promise.resolve(true);+ window.renderAt = () => { c.fillStyle = '${colour}'; c.fillRect(0, 0, 320, 180); };</script>`);+ mkdirSync(proj); flat('a.html', '#000'); flat('b.html', '#fff');+ writeFileSync(join(proj, 'project.json'), JSON.stringify({ fps: 30, scenes: ['a.html', { file: 'b.html', transition: { type: 'fade', duration: 0.5, ease: 'linear' } }] }));+ const out = join(dir, 'proj.mp4');+ await renderProject({ dir: proj, out, scale: 1, ...quiet });+ const v = await probeVideo(out);+ assert.equal(v.frames, 45); // 30 + 30 frames, 15 of them shared+ const grey = f => meanRgb(out, '100:100:110:40', f)[0];+ // frames 0 to 14: scene a; 15 to 29: the transition; 30 to 44: the rest of scene b+ assert.ok(grey(14) < 8, `frame 14 is ${grey(14)}`);+ assert.ok(Math.abs(grey(22) - 128) < 8, `frame 22 is ${grey(22)}`); // k = 7 of 15: progress 0.5+ assert.ok(grey(30) > 248, `frame 30 is ${grey(30)}`);+});++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);+ window.renderAt = () => { c.fillStyle = '#000'; c.fillRect(0, 0, ${w}, ${h}); };</script>`);+ mkdirSync(proj); flat('a.html', 320, 180); flat('b.html', 180, 320);+ // a mono sine at 0.5: RMS -9.03 dBFS, which both channels of the result should keep (ffmpeg's own up-mix gives -12.04)+ spawnSync('ffmpeg', ['-v', 'error', '-y', '-f', 'lavfi', '-i', 'sine=f=440:d=1:sample_rate=48000', '-af', 'volume=4', '-ac', '1', join(proj, 'tone.wav')]);+ writeFileSync(join(proj, 'project.json'), JSON.stringify({ fps: 30, scenes: ['a.html', 'b.html'] }));+ await assert.rejects(renderProject({ dir: proj, out: join(dir, 'proj2.mp4'), scale: 1, ...quiet }), /b\.html is 180x320 but a\.html is 320x180/);+ writeFileSync(join(proj, 'project.json'), JSON.stringify({ fps: 30, scenes: ['a.html'], audio: [{ file: 'tone.wav', start: 0 }] }));+ const out = join(dir, 'proj3.mp4');+ await renderProject({ dir: proj, out, scale: 1, ...quiet });+ const level = file => spawnSync('ffmpeg', ['-hide_banner', '-i', file, '-af', 'astats=measure_perchannel=RMS_level:measure_overall=none', '-f', 'null', '-'], { encoding: 'utf8' })+ .stderr.match(/RMS level dB: -?[\d.]+/g).map(s => parseFloat(s.split(': ')[1]));+ const [src] = level(join(proj, 'tone.wav')), [l, r] = level(out);+ assert.ok(Math.abs(l - src) < 0.5 && Math.abs(r - src) < 0.5, `source ${src} dB, render ${l} / ${r} dB`);+});diff --git a/test/server.test.js b/test/server.test.jsnew file mode 100644index 0000000..38de1a8--- /dev/null+++ b/test/server.test.js@@ -0,0 +1,31 @@+import assert from 'node:assert/strict';+import fs from 'node:fs';+import { syncBuiltinESMExports } from 'node:module';+import { request } from 'node:http';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { test } from 'node:test';+import { setTimeout as sleep } from 'node:timers/promises';++// Footage is read with Range requests, and the browser aborts many of them while seeking. Every file stream the+// server opens must close when its request is aborted, or the viewer runs out of file handles (EMFILE).+test('a file stream closes when its request is aborted', async () => {+ const open = new Set(), real = fs.createReadStream;+ fs.createReadStream = (...args) => { const s = real(...args); open.add(s); s.on('close', () => open.delete(s)); return s; };+ syncBuiltinESMExports();+ const dir = fs.mkdtempSync(join(tmpdir(), 'motlab-server-')), file = join(dir, 'big.bin');+ fs.writeFileSync(file, Buffer.alloc(32 * 1024 * 1024));+ const { startServer } = await import(`../src/server.js?abort=${Date.now()}`);+ const server = await startServer({ root: dir });+ try {+ const abortAfterFirstChunk = range => new Promise(ok => {+ const req = request(`${server.origin}/big.bin`, { headers: range ? { Range: range } : {} }, res => res.once('data', () => { req.destroy(); ok(); }));+ req.on('error', ok); req.end();+ });+ for (let i = 0; i < 20; i++) await abortAfterFirstChunk(i % 2 ? 'bytes=0-' : null);+ for (let i = 0; i < 50 && open.size; i++) await sleep(20);+ assert.equal(open.size, 0, `${open.size} file streams still open after 20 aborted requests`);+ } finally {+ await server.close(); fs.createReadStream = real; syncBuiltinESMExports(); fs.rmSync(dir, { recursive: true, force: true });+ }+});diff --git a/test/skills.test.js b/test/skills.test.jsnew file mode 100644index 0000000..8edfda5--- /dev/null+++ b/test/skills.test.js@@ -0,0 +1,18 @@+import assert from 'node:assert/strict';+import { readdirSync, readFileSync } from 'node:fs';+import { join } from 'node:path';+import { test } from 'node:test';++// Other agents check a skill's frontmatter and skip it without a word when it is off: the Agent Skills spec wants a+// lowercase name that matches the folder and a description of at most 1024 characters, and Codex's docs say 500.+test('every skill has frontmatter that Codex, Cursor and the others accept', () => {+ for (const dir of readdirSync('skills')) {+ const head = readFileSync(join('skills', dir, 'SKILL.md'), 'utf8').match(/^---\r?\n([\s\S]*?)\r?\n---/)?.[1];+ assert.ok(head, `${dir}: no frontmatter`);+ const field = k => head.match(new RegExp(`^${k}: (.*)$`, 'm'))?.[1];+ assert.equal(field('name'), dir, `${dir}: name must match the folder`);+ assert.match(dir, /^[a-z0-9]+(-[a-z0-9]+)*$/);+ const d = field('description') || '';+ assert.ok(d.length > 0 && Buffer.byteLength(d) <= 500, `${dir}: description is ${Buffer.byteLength(d)} bytes, keep it at 500 or less`);+ }+});