Skip to content

armgit / 67.js

Public Imported from GitHub
0

3D engine that AI agents drive

Add a recipe timeline, job audio and an encoder choice

Nguyen Xuan An391f0d92c50a
diff --git a/CHANGELOG.md b/CHANGELOG.md
index d757d5d6..9c8e4b00 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -2,6 +2,8 @@
## Unreleased
+- Add a recipe timeline, job audio and an encoder choice (part of issue #60, first slice). A recipe `timeline` lists named shots played in order over the motion clock, each with a `duration`, an optional `motionStart`, a partial `camera` on top of the sampled one and a `dip` through black; `set-timeline` edits it. `settings.timeline: { start }` renders it as an image, stills or video: one clock drives the shot, the motion and the renderer, so a seek to any time gives the same frame as inside a video. `settings.audio: { file, offset }` mixes one `.wav`, `.mp3`, `.ogg` or `.flac` from the new `--audio <folder>` option into a video, checks that it covers the video, decodes both streams afterwards and reports `metrics.sync` (a gap over 50 ms fails the job); `settings.encoder` is `cpu` or `nvenc`. File names are plain names without paths, drives or protocols, files must be regular and at most 32 MiB, and ffmpeg gets `-protocol_whitelist file`; nothing else comes from the agent. Video jobs can last 60 s (was 30), still capped at 900 frames, so a 60 s video runs at 15 fps. Measured through MCP on SwiftShader (`npm run smoke:film-timeline`): 9 PNG seeks across three shots and a dip match 8 stills byte for byte, and a 60 s, 900 frame video with sound rendered in 58 s (84 s on a loaded machine) at 128 x 128 with the click in the decoded audio on the decoded cut frame (offset 0.1 ms, streams 20 ms apart). Tool schemas stay inside their budgets (the timeline is a record reference; fields are in `scene_capabilities` `filmTimeline`). Left out: resumable long renders, several audio tracks, gain, markers inside a shot, animation events, crossfades and timelines for imported assets. The video sequence editor stays a non-goal.
+
- Add recipe cloth (part of issue #62, no new tool). A `cloth` section records sheets with a position-based solver (`src/cloth.js`, loaded on demand with the new `cloth` module, no peer dependency): pinned edges, gravity, steady wind, ball and box colliders, thickness and friction, 60 frames a second, bounded by particle, frame and solver-operation limits. A seek blends two recorded frames, so the same time gives the same positions and a seek backwards repeats them (`npm run smoke:agent-cloth` repeats the PNG bytes through the MCP preview). New `grid` geometry (a flat sheet, 1 to 64 segments), `set-cloth` operation and a `cloth` report in `scene_inspect`. The tool schemas stay within the total budget: `set-physics` now takes the same record reference as `set-motion`, and the physics descriptions are shorter. A hanging sheet matches a Blender cloth bake (`scripts/blender-cloth.py`) to 0.08 percent of its height; a sheet dropped on a ball does not match, and no parity is claimed. No self collision and no soft bodies yet.
- Edit the topology of imported GLB parts (part of issue #48, no new tool). `mesh_edit` and `mesh_inspect` take a part ID such as `mesh-10` of an imported asset: the part becomes a welded polygon mesh with axis tags and a `material-<n>` tag, the edit log is kept in the asset recipe as `meshEdits` (checkpoints, export and replay work), and every result passes `validateTopology`. New vertices take skin weights, morph deltas and vertex colours from the nearest original surface point and faces left without UVs read the nearest UV island; on a skinned or morphed part an edit more than a quarter of the part's bounds diagonal from the original surface is rejected with the next action. `mesh_inspect` reports `localToWorldScale` and `localAxesInWorld`. Measured on RobotExpressive through MCP (`npm run smoke:imported-topology`): a through hole in the closed left leg (98 to 210 triangles, still one closed part), a cut in the skinned right hand (124 to 109) and the morphed head (154 to 134), a 3 m extrude on the head rejected, GLB export and checkpoint restore intact. Suite task `robot-leg-hole`.
- Make room in the npm package (part of issue #36). The MCP preview page, `build/mcp/preview.js`, is now an entry of the library build and imports the engine chunks that the package entries already ship, instead of bundling its own copy of the engine. The archive drops from 904,975 to 666,214 bytes. `build/mcp/manifest.json` lists those chunks under `previewChunks` with their hashes, the MCP runtime serves them next to `preview.js`, and `bench/size/budgets.json` gains `archiveBytes`, which `npm run smoke:package` checks.
diff --git a/ROADMAP.md b/ROADMAP.md
index 230127c9..41c4fb5f 100644
--- a/ROADMAP.md
+++ b/ROADMAP.md
@@ -39,7 +39,7 @@ The npm package includes the prebuilt `67js-mcp` command with lazy browser start
1. Extend imported asset sessions with deformed geometry diagnostics and merging several parts into one editable mesh (part topology edits are in the next release).
2. Extend visual review with posed geometry bounds, automatic framing and compact rendered diagnostics.
-3. Extend render jobs with hardware encoder selection, audio, longer sequences and measured adaptive output quality.
+3. Extend render jobs with resumable long renders, several audio tracks, markers and events, and measured adaptive output quality. Timeline shots, one audio file with measured sync, an NVENC choice and 60 s videos are in place.
4. Geometry, rig and asset diagnostics that help agents correct intersections, invalid transforms and unsupported materials.
5. Agent workflows for imported assets, sculpting, surface fitting, lighting and animation, verified against rendered reference scenes.
6. GPU timing and adaptive quality based on measured frame time, with stable resolution changes and explicit minimum quality.
diff --git a/bench/size/budgets.json b/bench/size/budgets.json
index 2f3ac69a..7a1d0661 100644
--- a/bench/size/budgets.json
+++ b/bench/size/budgets.json
@@ -1,5 +1,5 @@
{
- "archiveBytes": 721300,
+ "archiveBytes": 729000,
"goals": {
"lit-box": 50000,
"gltf-box": 80000,
@@ -30,15 +30,15 @@
"entry:clutter": 5300,
"entry:texture-set": 900,
"entry:agent-scene": 61800,
- "entry:agent-scene+lazy": 194600,
+ "entry:agent-scene+lazy": 196100,
"entry:agent-asset": 92800,
- "entry:agent-asset+lazy": 205000,
+ "entry:agent-asset+lazy": 206500,
"entry:hdri": 3300,
"entry:camera-effects": 8600,
"entry:render-passes": 1700,
"scene:lit-box": 60200,
"scene:gltf-box": 79700,
"scene:agent-scene": 91700,
- "scene:agent-scene+lazy": 223850
+ "scene:agent-scene+lazy": 225300
}
}
diff --git a/bench/tool-cost-budgets.json b/bench/tool-cost-budgets.json
index 0575c20c..78c10944 100644
--- a/bench/tool-cost-budgets.json
+++ b/bench/tool-cost-budgets.json
@@ -1,16 +1,16 @@
{
- "measured": "2026-10-31, from scripts/measure-tool-cost.mjs; raised by 800 total and 150 for scene_apply for branch and labels fields (no new tool); raised by 650 total and 80 for scene_apply for clip layers, bone masks and retargeting through MCP; raised by 20 for scene_create and 20 for the scene_capabilities result after merging the expression language with the material graph; was 373388 schema bytes before shared IDs and recipe references; trimmed after the render-passes merge: material graph, depth of field, motion blur and passes details moved to scene_capabilities, budgets set to the measured value plus 0.5% (total 188267, scene_capabilities result 5167); raised by 95 for scene_apply and 690 for the scene_capabilities result for node relations; curve and text geometry entries shortened to a pointer at scene_capabilities curveText, budgets set to the measured value plus 0.5% (total 189468, scene_capabilities result 6399); then six modifier ops (weld, triangulate, edge_split, smooth, simple_deform, cast) added as one compact schema entry with details in scene_capabilities meshModifiers, entry and mesh_stack description shortened: total 190382 (budget unchanged at 190420), mesh_edit 34216 (budget 34220), scene_capabilities result 7042 (budget 7050); mesh_stack 11682 (budget 11690); after merging imported mesh topology with the modifier ops: raised the total to 190480 (measured 190471), mesh_edit to 34300 (measured 34293) and the scene_capabilities result to 7520 (measured 7512) for imported mesh edits; then cloth (recipe cloth, set-cloth, grid geometry) added with the total unchanged at 190480 (measured 189159): physics descriptions shortened and set-physics now takes the same record reference as set-motion, scene_create raised to 62150 and scene_apply lowered to 44130, scene_capabilities result raised to 8190 (measured 8176) for the cloth details",
+ "measured": "2026-10-31, from scripts/measure-tool-cost.mjs; raised by 800 total and 150 for scene_apply for branch and labels fields (no new tool); raised by 650 total and 80 for scene_apply for clip layers, bone masks and retargeting through MCP; raised by 20 for scene_create and 20 for the scene_capabilities result after merging the expression language with the material graph; was 373388 schema bytes before shared IDs and recipe references; trimmed after the render-passes merge: material graph, depth of field, motion blur and passes details moved to scene_capabilities, budgets set to the measured value plus 0.5% (total 188267, scene_capabilities result 5167); raised by 95 for scene_apply and 690 for the scene_capabilities result for node relations; curve and text geometry entries shortened to a pointer at scene_capabilities curveText, budgets set to the measured value plus 0.5% (total 189468, scene_capabilities result 6399); then six modifier ops (weld, triangulate, edge_split, smooth, simple_deform, cast) added as one compact schema entry with details in scene_capabilities meshModifiers, entry and mesh_stack description shortened: total 190382 (budget unchanged at 190420), mesh_edit 34216 (budget 34220), scene_capabilities result 7042 (budget 7050); mesh_stack 11682 (budget 11690); after merging imported mesh topology with the modifier ops: raised the total to 190480 (measured 190471), mesh_edit to 34300 (measured 34293) and the scene_capabilities result to 7520 (measured 7512) for imported mesh edits; then cloth (recipe cloth, set-cloth, grid geometry) added with the total unchanged at 190480 (measured 189159): physics descriptions shortened and set-physics now takes the same record reference as set-motion, scene_create raised to 62150 and scene_apply lowered to 44130, scene_capabilities result raised to 8190 (measured 8176) for the cloth details; then the recipe timeline (record reference, set-timeline, settings.timeline, audio and encoder on render jobs) with the total unchanged at 190480 (measured 190236) after trimming the field expression and recipe descriptions: scene_create raised to 62250 (measured 62242), scene_apply to 44370 (measured 44359) and the scene_capabilities result to 8560 (measured 8555) for the filmTimeline fields",
"schemaTotalBytes": 190480,
"schemaToolBytes": {
- "scene_create": 62150,
- "scene_apply": 44130,
+ "scene_create": 62250,
+ "scene_apply": 44370,
"mesh_edit": 34300,
"scene_create_asset": 19310,
"mesh_stack": 11690
},
"schemaOtherToolBytes": 4000,
"resultBytes": {
- "scene_capabilities": 8190,
+ "scene_capabilities": 8560,
"scene_create": 1400,
"scene_inspect": 1400,
"mesh_inspect": 1200,
diff --git a/docs/agent-render-jobs.md b/docs/agent-render-jobs.md
index a1a9fb5e..dca5721a 100644
--- a/docs/agent-render-jobs.md
+++ b/docs/agent-render-jobs.md
@@ -35,9 +35,9 @@ Preview rendering and edits pause during a job. Inspection and recipe export rem
The source revision, pose and checkpoints survive completion or cancellation.
Cancellation becomes terminal after the owned encoder and job page stop and the preview recovers.
-Video uses CPU H.264 encoding, even dimensions and one streamed frame at a time.
+Video uses H.264 (CPU by default, see `settings.encoder`), even dimensions and one streamed frame at a time.
The render backend can use GPU or CPU. Memory limits can reduce the actual output dimensions.
-Results report actual dimensions and measured timings. They do not embed video bytes or include audio.
+Results report actual dimensions and measured timings. They do not embed video bytes.
Release `0.8.0` also samples imported character tracks and can layer them over an independently sampled imported clip.
@@ -49,6 +49,46 @@ Creation and edits author tracks through scene recipes and `set-motion`, before
Static recipes remain static unless a shader uses renderer time.
Imported clips retain separate absolute sampling through `settings.animation`.
+## Timeline, audio and encoder
+
+A recipe `timeline` plays shots one after another over the recipe's motion clock. It is small on purpose: the video sequence
+editor is a non-goal of the engine (issue #23), so there are no layers, overlaps, trimming or crossfades. Shots cut, or dip through black.
+
+```json
+{ "timeline": { "shots": [
+ { "name": "wide", "duration": 20, "camera": { "eye": [0, 3, 14], "target": [0, 0, 0] } },
+ { "name": "close", "duration": 20, "motionStart": 1, "camera": { "eye": [0, 0.6, 2.4], "fov": 50 } },
+ { "name": "dusk", "duration": 20, "dip": 1 }
+] } }
+```
+
+| Shot field | Meaning |
+| --- | --- |
+| `name` | 1 to 24 letters, digits, `-` or `_`, unique. Job metrics list shots by name with their start second. |
+| `duration` | 0.1 to 30 s. The timeline holds up to 64 shots and 60 s. |
+| `motionStart` | Second of the motion clock the shot starts at. Omitted, the shot reads the motion at its place on the timeline, so a non-looping motion must cover it. Only for recipes with motion, physics or cloth. |
+| `camera` | A partial camera (`eye`, `target`, `up`, `fov`, `near`, `far`) on top of the sampled camera. Omitted, the shot keeps the camera of the motion tracks. |
+| `dip` | 0.05 to 4 s. The previous shot fades to black over the first half and this one fades up over the second half. |
+
+`set-timeline` edits the section and `null` removes it. A job renders it with `settings.timeline: { start }` (default 0) for kind `image`, `stills` or `video`.
+`duration` defaults to the rest of the timeline. The timeline owns the motion clock, so `motion` and `animation` settings are rejected, and the renderer clock reads timeline time.
+Imported assets have no timeline.
+
+A frame depends only on its timeline time and keeps no state, so a seek to any time gives the same pixels as that frame inside a video or stills run.
+Videos are capped at 60 s and 900 frames, so a 60 s video needs 15 fps or less.
+
+**Audio.** Start the server with `--audio <absolute folder>` and pass `settings.audio: { file, offset }` on a video job.
+`file` is a plain name in that folder ending in `.wav`, `.mp3`, `.ogg` or `.flac` (no path, drive or protocol syntax); the file must be a regular file of up to 32 MiB without links.
+`offset` starts the sound that many seconds into the file. The sound is resampled to 48 kHz and encoded as AAC.
+A job whose file is shorter than the video after its offset fails before rendering. After encoding, the job decodes both streams of the MP4 and reports `metrics.sync`
+(`videoSeconds`, `audioSeconds`, `differenceSeconds`); a difference over 50 ms fails the job.
+ffmpeg only receives the resolved path with `-protocol_whitelist file`; no URL, argument or output path comes from the agent.
+
+**Encoder.** `settings.encoder` is `cpu` (libx264, default) or `nvenc` (h264_nvenc). A machine without NVENC fails the job with the ffmpeg error and never falls back.
+
+`npm run smoke:film-timeline` proves it through MCP on SwiftShader (`cpu` backend): 9 PNG seeks over 8 stills across three shots and a dip are identical to the byte,
+and a click placed on a cut in a WAV lands on the decoded cut frame within a frame. `FILM_SECONDS=60` renders the 60 s case.
+
## Render passes
`image` and `stills` jobs accept `settings.passes`, a list of `albedo`, `normal`, `emission`, `depth` and `objectId`.
@@ -218,7 +258,7 @@ This conservative repair step prevents two recovery processes from deleting a ne
| Asset bytes | 16 MiB |
| Dimensions | 64 to 1024 pixels each |
| Video frame rate | 1 to 30 fps |
-| Duration | 0.1 to 30 seconds |
+| Duration | 0.1 to 60 seconds |
| Maximum video frames | 900 |
| Still frames | 8 |
| Job elapsed deadline | Five minutes |
diff --git a/docs/parity.md b/docs/parity.md
index 0a54b2c1..ddabf8b7 100644
--- a/docs/parity.md
+++ b/docs/parity.md
@@ -169,7 +169,7 @@ To move to a new Blender release, run `node scripts/parity-manual-snapshot.mjs`.
| Animation & Rigging > Constraints > Relationship > Shrinkwrap Constraint | partial | `addons/surface-attachment` binds points to a surface in code. | [surface-attachment](../tests/surface-attachment.test.js) | |
| Animation & Rigging > Actions | partial | Clips, weights and crossfades in code. An asset through MCP plays several clips as masked layers at motion time; there are no crossfades or state machines there. | [animation-mixer](../tests/animation-mixer.test.js), [agent-asset-layers](../tests/agent-asset-layers.test.js) | #59 |
| Animation & Rigging > Drivers | partial | `motion.drivers`: a node component or material property from a bounded expression over time and other nodes. No custom properties, shape keys or variables. | [agent-motion-constraints](../tests/agent-motion-constraints.test.js) | #58 |
-| Animation & Rigging > Markers | missing | No markers or events. | | #60 |
+| Animation & Rigging > Markers | partial | Recipe timeline shots are named, listed with their start second in job metrics, and cut with their own camera, motion start and an optional dip through black (no strips, layers or crossfades; the video sequence editor is a non-goal). No markers inside a shot and no events. | [film-timeline](../tests/film-timeline.test.js) | #60 |
| Animation & Rigging > Shape Keys | partial | Morph targets import, render and animate, and clip layers drive imported morph weights (`createAssetPose`, MCP `motion.layers`). Recipes can not author them. | [morph](../tests/morph.test.js), [agent-asset-layers](../tests/agent-asset-layers.test.js) | #59 |
| Animation & Rigging > Motion Paths | out of scope | Viewport display for hand work. `scene_inspect` reports motion as numbers. | | |
| Animation & Rigging > In-Betweens | out of scope | Pose tools for a hand. Agents write keyframes and IK targets. | | |
@@ -210,8 +210,8 @@ To move to a new Blender release, run `node scripts/parity-manual-snapshot.mjs`.
| Rendering > Color Management | partial | ACES tone mapping and grading. There is no choice of color space or display. | [effects](../tests/effects.test.js) | |
| Rendering > Freestyle | missing | No line rendering. | | |
| Rendering > View Layers & Passes | partial | Render jobs write albedo, normal, emission, depth and object ID passes as PNG files. There are no view layers, no cryptomatte and no lighting passes (diffuse, glossy, shadow). | [render-passes](../tests/render-passes.test.js) | #54 |
-| Rendering > Render Output > Output Properties | partial | PNG and MP4, frame rate, duration and size. There is no stereo or metadata. | [agent-render-jobs](../tests/agent-render-jobs.test.js) | #60 |
-| Rendering > Render Output > Audio Rendering | missing | Render jobs have no audio. | | #60 |
+| Rendering > Render Output > Output Properties | partial | PNG and MP4, frame rate, duration (to 60 s) and size, and a CPU or NVENC encoder. There is no stereo or metadata. | [agent-render-jobs](../tests/agent-render-jobs.test.js) | #60 |
+| Rendering > Render Output > Audio Rendering | partial | A video job mixes one local WAV, MP3, OGG or FLAC file with an offset and reports measured sync. No several tracks, mixing, gain or generated sound. | [film-timeline](../tests/film-timeline.test.js), `npm run smoke:film-timeline` | #60 |
| Rendering > Render Output > Rendering Animations | done | Snapshot render jobs with progress, cancel and verified output. | [agent-render-jobs](../tests/agent-render-jobs.test.js) | |
| Rendering > Render Output > Animation Player | out of scope | Interface for a person. | | |
| Compositing | partial | A fixed chain of bloom, grading and FXAA. There is no graph. | [effects](../tests/effects.test.js) | #54 |
diff --git a/package.json b/package.json
index 079da078..617979de 100644
--- a/package.json
+++ b/package.json
@@ -102,6 +102,7 @@
"smoke:agent-assets": "node scripts/smoke-agent-assets.mjs",
"smoke:agent-render-jobs": "node scripts/smoke-agent-render-jobs.mjs",
"smoke:render-passes": "node scripts/smoke-render-passes.mjs",
+ "smoke:film-timeline": "node scripts/smoke-film-timeline.mjs",
"smoke:agent-motion": "node scripts/smoke-agent-motion.mjs",
"smoke:agent-physics": "node scripts/smoke-agent-physics.mjs",
"smoke:agent-cloth": "node scripts/smoke-agent-cloth.mjs",
diff --git a/scripts/agent-preview-browser.js b/scripts/agent-preview-browser.js
index 7a57d134..de20ff85 100644
--- a/scripts/agent-preview-browser.js
+++ b/scripts/agent-preview-browser.js
@@ -181,6 +181,14 @@ function initializeRenderer(scene, { memoryBudgetMiB, backend }) {
})));
}
+// Camera fields from a timeline shot on top of the sampled camera, checked with the scene's own camera rules.
+function withCameraOverrides(camera, overrides) {
+ const merged = createAgentScene({ format: '67js.scene', schemaVersion: 1,
+ geometries: [], materials: [], nodes: [], camera: { ...camera, ...overrides } }).camera;
+ validatePreviewCamera(merged);
+ return merged;
+}
+
// The camera at the start of the shutter interval, sampled from time so the same seek always gives the same blur.
function previousCameraFor(record, motionTime) {
const shutter = record.scene.effects.motionBlur.shutter;
@@ -427,8 +435,10 @@ window.__agentPreview = {
}
},
// `pass` draws one render pass instead of the lit image. Object ID frames also list the part behind each ID.
- frame({ sessionId, animation, motionTime, rendererTime = 0, pass, passDepthRange }) {
+ // `camera` overrides camera fields (a timeline shot) and `brightness` scales exposure for a dip through black.
+ frame({ sessionId, animation, motionTime, rendererTime = 0, pass, passDepthRange, camera: cameraOverrides, brightness = 1 }) {
const record = requireSession(sessionId);
+ if (!Number.isFinite(brightness) || brightness < 0 || brightness > 1) throw new RangeError('Invalid frame brightness.');
if (!Number.isFinite(rendererTime) || rendererTime < 0 || rendererTime > 3600) throw new RangeError('Invalid render time.');
if (record.asset && (animation !== undefined || motionTime !== undefined)) {
record.scene.sampleFrame({ ...(animation === undefined ? {} : { animation }),
@@ -436,8 +446,11 @@ window.__agentPreview = {
} else if (motionTime !== undefined) {
record.scene.sampleMotion(motionTime);
}
- const previousCamera = pass ? undefined : previousCameraFor(record, motionTime);
- draw(record, rendererTime, undefined, { pass, passDepthRange, previousCamera });
+ const shotCamera = cameraOverrides ? withCameraOverrides(record.scene.camera, cameraOverrides) : undefined;
+ const sampledPreviousCamera = pass ? undefined : previousCameraFor(record, motionTime);
+ const previousCamera = sampledPreviousCamera && cameraOverrides ? withCameraOverrides(sampledPreviousCamera, cameraOverrides) : sampledPreviousCamera;
+ const exposure = record.scene.effects.exposure * brightness;
+ draw(record, rendererTime, shotCamera, { pass, passDepthRange, previousCamera, ...(brightness === 1 ? {} : { exposure }) });
const info = renderInfo(record.renderer);
return pass === 'objectId' ? { ...info, objectNames: record.renderer.passSupport.objectNames() } : info;
},
diff --git a/scripts/agent-render-jobs.mjs b/scripts/agent-render-jobs.mjs
index 6a0b89c4..1e90ae65 100644
--- a/scripts/agent-render-jobs.mjs
+++ b/scripts/agent-render-jobs.mjs
@@ -2,7 +2,8 @@ import { mkdir, open, readFile, writeFile, rename, unlink, rmdir, readdir, lstat
import { randomUUID, createHash } from 'node:crypto';
import { isAbsolute, join, resolve } from 'node:path';
-import { RENDER_PASS_NAMES } from '../src/agent-scene-capabilities.js';
+import { RENDER_PASS_NAMES, VIDEO_ENCODERS, AUDIO_FILE_PATTERN, MAXIMUM_VIDEO_SECONDS } from '../src/agent-scene-capabilities.js';
+import { normalizeFilmTimeline, filmTimelineDuration } from '../src/film-timeline.js';
const UUID =/^[a-f0-9]{8}-[a-f0-9]{4}-[1-8][a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/;
const STATES = ['queued', 'running', 'finalizing', 'completed', 'cancelling', 'cancelled', 'failed', 'interrupted'];
@@ -57,18 +58,31 @@ function jsonCopy(value, maximum = MAXIMUM_JSON_BYTES) {
}
function settingsFrom(input, clips, recipe) {
- objectKeys(input, ['kind', 'width', 'height', 'fps', 'duration', 'animation', 'motion', 'rendererTime', 'passes'], 'settings');
+ objectKeys(input, ['kind', 'width', 'height', 'fps', 'duration', 'animation', 'motion', 'rendererTime', 'passes', 'timeline', 'audio', 'encoder'], 'settings');
if (!['image', 'stills', 'video'].includes(input.kind)) throw new TypeError('kind must be image, stills or video.');
const width = boundedNumber(input.width, 64, 1024, 'width', true);
const height = boundedNumber(input.height, 64, 1024, 'height', true);
if (input.kind === 'video' && (width % 2 || height % 2)) throw new RangeError('Video dimensions must be even.');
const fps = boundedNumber(input.fps ?? 24, 1, 30, 'fps', true);
- const duration = boundedNumber(input.duration ?? 1, 0.1, 30, 'duration');
+ const timelineStart = timelineStartFrom(input, recipe);
+ const defaultDuration = timelineStart === undefined || input.kind === 'image' ? 1 : filmTimelineDuration(recipe.timeline) - timelineStart;
+ const duration = boundedNumber(input.duration ?? defaultDuration, 0.1, MAXIMUM_VIDEO_SECONDS, 'duration');
const frameCount = input.kind === 'image' ? 1 : input.kind === 'stills' ? 8 : Math.ceil(fps * duration);
if (frameCount > 900) throw new RangeError('Job exceeds 900 frames.');
const result = { kind: input.kind, width, height, fps, duration, frameCount };
if (input.passes !== undefined) result.passes = passesFrom(input.passes, input.kind);
const lastSampleTime = input.kind === 'image' ? 0 : input.kind === 'stills' ? duration : (frameCount - 1) / fps;
+ if (timelineStart !== undefined) {
+ if (input.motion !== undefined || input.animation !== undefined) throw new TypeError('A timeline owns the motion clock; leave motion and animation out.');
+ if (timelineStart + lastSampleTime > filmTimelineDuration(recipe.timeline)) throw new RangeError('Timeline range exceeds the timeline duration.');
+ result.timeline = { start: timelineStart };
+ }
+ if (input.encoder !== undefined) {
+ if (input.kind !== 'video') throw new TypeError('encoder needs kind video.');
+ if (!VIDEO_ENCODERS.includes(input.encoder)) throw new TypeError(`encoder must be one of ${VIDEO_ENCODERS.join(', ')}.`);
+ result.encoder = input.encoder;
+ }
+ if (input.audio !== undefined) result.audio = audioFrom(input.audio, input.kind);
if (input.motion !== undefined) {
objectKeys(input.motion, ['start'], 'motion');
if (!['67js.scene', '67js.asset'].includes(recipe?.format) || !recipe.motion) {
@@ -102,6 +116,23 @@ function settingsFrom(input, clips, recipe) {
return result;
}
+function timelineStartFrom(input, recipe) {
+ if (input.timeline === undefined) return undefined;
+ objectKeys(input.timeline, ['start'], 'timeline');
+ if (recipe?.format !== '67js.scene' || !recipe.timeline) throw new RangeError('Timeline settings require a recipe with a timeline.');
+ normalizeFilmTimeline(recipe.timeline, recipe);
+ return boundedNumber(input.timeline.start ?? 0, 0, MAXIMUM_VIDEO_SECONDS, 'timeline start');
+}
+
+function audioFrom(audio, kind) {
+ if (kind !== 'video') throw new TypeError('audio needs kind video.');
+ objectKeys(audio, ['file', 'offset'], 'audio');
+ if (typeof audio.file !== 'string' || !AUDIO_FILE_PATTERN.test(audio.file)) {
+ throw new TypeError('audio.file must be a file name in the configured audio folder ending in .wav, .mp3, .ogg or .flac.');
+ }
+ return { file: audio.file, offset: boundedNumber(audio.offset ?? 0, 0, 3600, 'audio offset') };
+}
+
function passesFrom(passes, kind) {
if (kind === 'video') throw new RangeError('Render passes need kind image or stills; a video holds the lit image only.');
if (!Array.isArray(passes) || passes.length < 1 || passes.length > RENDER_PASS_NAMES.length) throw new TypeError(`passes must list 1 to ${RENDER_PASS_NAMES.length} pass names.`);
diff --git a/scripts/agent-runtime.mjs b/scripts/agent-runtime.mjs
index f4b82d59..6c85b80a 100644
--- a/scripts/agent-runtime.mjs
+++ b/scripts/agent-runtime.mjs
@@ -6,10 +6,12 @@ import { dirname, isAbsolute, join } from 'node:path';
import { createRequire } from 'node:module';
import { fileURLToPath } from 'node:url';
import packageMetadata from '../package.json' with { type: 'json' };
-import { AGENT_SCENE_CAPABILITIES, AGENT_SCENE_DEFAULT_LIMITS, RENDER_PASS_NAMES, RENDER_PASS_DEPTH_RANGE } from '../src/agent-scene-capabilities.js';
+import { AGENT_SCENE_CAPABILITIES, AGENT_SCENE_DEFAULT_LIMITS, RENDER_PASS_NAMES, RENDER_PASS_DEPTH_RANGE, VIDEO_ENCODERS, MAXIMUM_VIDEO_SECONDS } from '../src/agent-scene-capabilities.js';
import { createAgentAssetCatalog } from './agent-asset-catalog.mjs';
import { createAgentRenderJobs, EXPORT_DIRECTORY_NAME } from './agent-render-jobs.mjs';
import { createFrameEncoder } from './frame-encoder.mjs';
+import { audioInputArguments, createAudioLibrary, measureStreamSeconds } from './job-audio.mjs';
+import { filmTimelineDuration, filmTimelineShotStarts, sampleFilmTimeline } from '../src/film-timeline.js';
import { isPreviewHost } from './preview-host.mjs';
import { normalizeReview, REVIEW_LIMITS } from './agent-review.mjs';
import { BRANCH_LIMITS, validateBranchName } from '../src/agent-branches.js';
@@ -23,6 +25,8 @@ const MAXIMUM_QUEUED_CALLS = 16;
const MAXIMUM_GLB_BYTES = 32 * 1024 * 1024;
const MAXIMUM_KEPT_GLBS = 8;
const EVALUATION_TIMEOUT_MS = 30000;
+// Decoded audio and video lengths of a finished file may differ by the encoder delay; more than this fails the job.
+const SYNC_TOLERANCE_SECONDS = 0.05;
// The preview page imports engine chunks that sit beside the package entries, one folder above preview.js.
const ENGINE_CHUNK_URL = /^\/[\w.-]+\.js$/;
const html = '<!doctype html><html><head><meta charset="utf-8"><style>html,body{margin:0;height:100%;background:#182126}canvas{display:block;width:100vw;height:100vh}</style></head><body><canvas></canvas><script type="module" src="/preview.js"></script></body></html>';
@@ -36,7 +40,7 @@ const VENDOR_FILES = Object.freeze({
});
export function createAgentRuntime({ backend = 'gpu', browser: browserPath, memory = 192, assets: assetRoot,
- jobs: jobRoot, ffmpeg = 'ffmpeg',
+ jobs: jobRoot, ffmpeg = 'ffmpeg', audio: audioRoot,
previewUrl = new URL(/* @vite-ignore */ '../build/mcp/preview.js', import.meta.url) } = {}) {
if (!['gpu', 'cpu'].includes(backend)) {
throw new RangeError('backend must be gpu or cpu.');
@@ -53,6 +57,7 @@ export function createAgentRuntime({ backend = 'gpu', browser: browserPath, memo
if (jobRoot !== undefined && (typeof jobRoot !== 'string' || !isAbsolute(jobRoot))) {
throw new TypeError('Job root must be an explicit absolute directory path.');
}
+ const audioLibrary = audioRoot === undefined ? undefined : createAudioLibrary(audioRoot);
if (typeof ffmpeg !== 'string' || !ffmpeg || (ffmpeg !== 'ffmpeg' && (!isAbsolute(ffmpeg) || !existsSync(ffmpeg)))) {
throw new TypeError('FFmpeg must be on PATH or configured with an existing absolute executable path.');
}
@@ -313,17 +318,28 @@ export function createAgentRuntime({ backend = 'gpu', browser: browserPath, memo
await jobPage.setViewportSize({ width, height });
const session = await jobPage.context().newCDPSession(jobPage);
const artifacts = [];
+ const timeline = settings.timeline ? snapshot.recipe.timeline : undefined;
+ const audio = settings.audio ? await prepareAudio(settings) : undefined;
if (settings.kind === 'video') {
encoder = createFrameEncoder({ executable: ffmpeg, output: join(directory, 'render.mp4.partial'),
- fps: settings.fps, format: 'jpeg', signal });
+ fps: settings.fps, format: 'jpeg', signal, backend: settings.encoder === 'nvenc' ? 'gpu' : 'cpu',
+ audioArguments: settings.audio ? audioInputArguments(audio.path, settings.audio.offset) : [] });
+ metrics.videoEncoder = settings.encoder === 'nvenc' ? 'h264_nvenc' : 'libx264';
}
+ if (timeline) metrics.shots = filmTimelineShotStarts(timeline);
for (let frame = 0; frame < settings.frameCount; frame++) {
signal.throwIfAborted();
const elapsed = settings.kind === 'video' ? frame / settings.fps
: settings.kind === 'stills' ? settings.duration * frame / (settings.frameCount - 1) : 0;
+ // A timeline job reads one clock for the shot, the motion and the renderer, so a seek matches the frame in a video.
+ const timelineTime = timeline ? Math.min(filmTimelineDuration(timeline), settings.timeline.start + elapsed) : undefined;
+ const shotSample = timeline ? sampleFilmTimeline(timeline, snapshot.recipe, timelineTime) : undefined;
const frameInput = { sessionId: jobId,
- rendererTime: (settings.rendererTime?.start ?? 0) + elapsed * (settings.rendererTime?.rate ?? 1),
+ rendererTime: (settings.rendererTime?.start ?? 0) + (timelineTime ?? elapsed) * (settings.rendererTime?.rate ?? 1),
...(settings.motion ? { motionTime: settings.motion.start + elapsed } : {}),
+ ...(shotSample?.motionTime == null ? {} : { motionTime: shotSample.motionTime }),
+ ...(shotSample?.camera ? { camera: shotSample.camera } : {}),
+ ...(shotSample && shotSample.brightness < 1 ? { brightness: shotSample.brightness } : {}),
...(settings.animation ? { animation: { clip: settings.animation.clip, time: settings.animation.start + elapsed } } : {}) };
const renderStarted = performance.now();
const rendered = await jobPage.evaluate(input => window.__agentPreview.frame(input), frameInput);
@@ -375,6 +391,7 @@ export function createAgentRuntime({ backend = 'gpu', browser: browserPath, memo
}
if (encoder) {
metrics.encoder = await encoder.finish();
+ if (audio) metrics.sync = await measureSync(join(directory, 'render.mp4.partial'));
artifacts.push({ temporary: 'render.mp4.partial', filename: 'render.mp4', mimeType: 'video/mp4' });
}
metrics.elapsedSeconds = (performance.now() - started) / 1000;
@@ -404,6 +421,30 @@ export function createAgentRuntime({ backend = 'gpu', browser: browserPath, memo
}
}
+ // The audio must cover the video from its offset, or ffmpeg would cut the picture short at the end of the sound.
+ async function prepareAudio(settings) {
+ if (!audioLibrary) throw new Error('Configure --audio with an absolute folder before rendering audio.');
+ const path = await audioLibrary.resolve(settings.audio.file);
+ const fileSeconds = await measureStreamSeconds(ffmpeg, path, 'audio');
+ const videoSeconds = settings.frameCount / settings.fps;
+ const availableSeconds = fileSeconds - settings.audio.offset;
+ if (availableSeconds + SYNC_TOLERANCE_SECONDS < videoSeconds) {
+ throw new RangeError(`Audio has ${availableSeconds.toFixed(2)} s after its offset but the video lasts ${videoSeconds.toFixed(2)} s.`);
+ }
+ return { path, availableSeconds };
+ }
+
+ // Decodes both streams of the finished file; a gap beyond the encoder delay means picture and sound drifted apart.
+ async function measureSync(path) {
+ const videoSeconds = await measureStreamSeconds(ffmpeg, path, 'video', { format: 'mp4' });
+ const audioSeconds = await measureStreamSeconds(ffmpeg, path, 'audio', { format: 'mp4' });
+ const differenceSeconds = audioSeconds - videoSeconds;
+ if (Math.abs(differenceSeconds) > SYNC_TOLERANCE_SECONDS) {
+ throw new Error(`Audio and video lengths differ by ${(differenceSeconds * 1000).toFixed(0)} ms.`);
+ }
+ return { videoSeconds, audioSeconds, differenceSeconds, toleranceSeconds: SYNC_TOLERANCE_SECONDS };
+ }
+
return Object.freeze({
async capabilities() {
return {
@@ -422,12 +463,12 @@ export function createAgentRuntime({ backend = 'gpu', browser: browserPath, memo
commands: ['set-root', 'set-asset-node', 'set-motion', 'set-animation', 'set-material', 'set-camera', 'set-environment', 'set-effects', 'set-shadow'],
},
jobs: { configured: Boolean(jobRoot), kinds: ['image', 'stills', 'video'], passes: RENDER_PASS_NAMES, maximumActiveJobs: 1,
- maximumDuration: 30, maximumFps: 30, maximumFrames: 900, maximumStills: 8,
- encoder: 'CPU H.264', audio: false, previewSuspendedDuringJob: true,
+ maximumDuration: MAXIMUM_VIDEO_SECONDS, maximumFps: 30, maximumFrames: 900, maximumStills: 8,
+ encoder: 'H.264', encoders: VIDEO_ENCODERS, audio: Boolean(audioRoot), timeline: true, previewSuspendedDuringJob: true,
glbExport: { maximumBytes: MAXIMUM_GLB_BYTES, maximumKept: MAXIMUM_KEPT_GLBS, maximumTextureSize: 4096 },
records: jobRoot ? (await jobs()).list().map(record => ({ jobId: record.jobId, state: record.state,
sourceRevision: record.sourceRevision, progress: record.progress })) : [] },
- unsupported: ['remote asset providers', 'arbitrary code execution', 'imported morph track authoring', 'job audio'],
+ unsupported: ['remote asset providers', 'arbitrary code execution', 'imported morph track authoring'],
};
},
create({ recipe }) {
@@ -684,6 +725,10 @@ export function createAgentRuntime({ backend = 'gpu', browser: browserPath, memo
return enqueue(async () => {
await requirePreviewRenderer();
const controller = await jobs();
+ if (settings?.audio) {
+ if (!audioLibrary) throw new Error('Configure --audio with an absolute folder before submitting a job with audio.');
+ await audioLibrary.resolve(settings.audio.file);
+ }
const snapshot = await invoke('snapshot', { sessionId, expectedRevision });
const assetBytes = snapshot.recipe.format === '67js.asset' ? await (await catalog()).read(snapshot.recipe.assetId) : undefined;
phase = 'rendering';
diff --git a/scripts/job-audio.mjs b/scripts/job-audio.mjs
new file mode 100644
index 00000000..09c51cd0
--- /dev/null
+++ b/scripts/job-audio.mjs
@@ -0,0 +1,59 @@
+import { spawn } from 'node:child_process';
+import { lstat, realpath } from 'node:fs/promises';
+import { isAbsolute, join, sep } from 'node:path';
+import { AUDIO_FILE_PATTERN } from '../src/agent-scene-capabilities.js';
+
+// Audio for render jobs: local files in one configured folder, chosen by plain file name. The agent never supplies a
+// path, URL or ffmpeg argument; ffmpeg only receives the resolved path and a fixed protocol whitelist.
+
+export const MAXIMUM_AUDIO_BYTES = 32 * 1024 ** 2;
+const PROBE_TIMEOUT_MS = 30000;
+// Every file is resampled to this rate: AAC adds one 1024-sample frame of delay, 21 ms here but 64 ms at 16 kHz.
+const OUTPUT_SAMPLE_RATE = 48000;
+
+/** Looks files up in `root`, refusing links and anything that resolves outside it. */
+export function createAudioLibrary(root) {
+ if (typeof root !== 'string' || !isAbsolute(root)) throw new TypeError('Audio root must be an explicit absolute directory path.');
+ return Object.freeze({
+ async resolve(file) {
+ if (typeof file !== 'string' || !AUDIO_FILE_PATTERN.test(file)) throw new TypeError('Audio file name is not allowed.');
+ const path = join(root, file);
+ const information = await lstat(path).catch(() => { throw new RangeError(`Audio file ${file} is not in the audio folder.`); });
+ if (!information.isFile() || information.isSymbolicLink() || information.nlink > 1) throw new RangeError(`Audio file ${file} must be a regular file without links.`);
+ if (information.size < 1 || information.size > MAXIMUM_AUDIO_BYTES) throw new RangeError(`Audio file ${file} must be 1 byte to ${MAXIMUM_AUDIO_BYTES} bytes.`);
+ const rootReal = await realpath(root);
+ if (!(await realpath(path)).startsWith(rootReal + sep)) throw new RangeError('Audio file resolves outside the audio folder.');
+ return path;
+ },
+ });
+}
+
+/** Input arguments for the encoder: the file is read at `offset` seconds and may only be opened as a plain file. */
+export function audioInputArguments(path, offsetSeconds) {
+ return ['-protocol_whitelist', 'file', '-ss', String(offsetSeconds), '-i', path, '-ar', String(OUTPUT_SAMPLE_RATE)];
+}
+
+function parseSeconds(text) {
+ const matches = [...text.matchAll(/time=(\d+):(\d+):(\d+(?:\.\d+)?)/g)];
+ const last = matches.at(-1);
+ if (!last) throw new Error('ffmpeg reported no decoded duration.');
+ return Number(last[1]) * 3600 + Number(last[2]) * 60 + Number(last[3]);
+}
+
+/** Decodes one stream to nowhere and reads how long it ran: `audio` or `video`. Decoded length, not container metadata. */
+export function measureStreamSeconds(executable, path, stream, { format } = {}) {
+ const map = stream === 'audio' ? ['-map', '0:a:0', '-vn'] : ['-map', '0:v:0', '-an'];
+ const argumentsValue = ['-hide_banner', '-nostdin', '-protocol_whitelist', 'file', ...(format ? ['-f', format] : []), '-i', path, ...map, '-f', 'null', '-'];
+ return new Promise((resolve, reject) => {
+ const child = spawn(executable, argumentsValue, { windowsHide: true, stdio: ['ignore', 'ignore', 'pipe'] });
+ let diagnostics = '';
+ child.stderr.on('data', bytes => { diagnostics = (diagnostics + bytes).slice(-16384); });
+ const timer = setTimeout(() => child.kill(), PROBE_TIMEOUT_MS);
+ child.once('error', reject);
+ child.once('close', code => {
+ clearTimeout(timer);
+ if (code !== 0) return reject(new Error(`ffmpeg could not decode the ${stream} stream: ${diagnostics.slice(-300)}`));
+ try { resolve(parseSeconds(diagnostics)); } catch (error) { reject(error); }
+ });
+ });
+}
diff --git a/scripts/mcp-server.mjs b/scripts/mcp-server.mjs
index 4786ef80..a1c0e374 100644
--- a/scripts/mcp-server.mjs
+++ b/scripts/mcp-server.mjs
@@ -7,7 +7,7 @@ import { resolve } from 'node:path';
import { pathToFileURL } from 'node:url';
import packageMetadata from '../package.json' with { type: 'json' };
import { MODIFIER_OPERATIONS } from '../src/mesh-operations.js';
-import { MATERIAL_PATTERN_TYPES, MATERIAL_MAPPINGS, LIGHTING_SETUP_NAMES, RENDER_PASS_NAMES } from '../src/agent-scene-capabilities.js';
+import { MATERIAL_PATTERN_TYPES, MATERIAL_MAPPINGS, LIGHTING_SETUP_NAMES, RENDER_PASS_NAMES, VIDEO_ENCODERS } from '../src/agent-scene-capabilities.js';
import { MATERIAL_LAYER_SCALAR_RANGES, MATERIAL_LAYER_COLOR_RANGES } from '../src/material-layers.js';
const finite = z.number().min(-3.4028234663852886e38).max(3.4028234663852886e38);
@@ -37,7 +37,7 @@ const nodeFields = {
rotation: quaternion.optional().describe('Nonzero local XYZW quaternion. The backend normalizes it.'),
scale: z.tuple([positive, positive, positive]).optional().describe('Positive local XYZ scale.'),
};
-const fieldExpression = z.union([finite, z.boolean(), vector3, z.record(z.string(), z.unknown())]).describe('Field expression, plain JSON and never code; driver expressions use the same language. A number, a boolean or [x,y,z] is a constant; an object holds one operator: math add mul sub div mod pow atan2 min max clamp saturate mix smoothstep neg abs sqrt sin cos floor ceil round fract sign; comparison lt lte gt gte eq; logic and or not if [cond,a,b]; vectors vec [x,y,z] dot cross distance length normalize x y z; sources {"attr":"position"|"normal"|"index"|"tag","component":"x"|"y"|"z","name":tag}, {"noise":{"scale":3,"seed":7,"octaves":1}} in 0..1, {"random":{"seed":1}} per element in 0..1. Example: {"mul":[{"attr":"position","component":"y"},0.5]}. At most 64 nodes, depth 12, 250000 elements.');
+const fieldExpression = z.union([finite, z.boolean(), vector3, z.record(z.string(), z.unknown())]).describe('Field expression, plain JSON and never code; driver expressions use the same language. A number, a boolean or [x,y,z] is a constant; an object holds one operator: math add mul sub div mod pow atan2 min max clamp saturate mix smoothstep neg abs sqrt sin cos floor ceil round fract sign; comparison lt lte gt gte eq; logic and or not if [cond,a,b]; vectors vec [x,y,z] dot cross distance length normalize x y z; sources {"attr":"position"|"normal"|"index"|"tag","component":"x"|"y"|"z","name":tag}, {"noise":{"scale":3,"seed":7,"octaves":1}} in 0..1, {"random":{"seed":1}} per element in 0..1. Limits in scene_capabilities fieldExpressions.');
const instanceCount = z.number().int().min(1).max(2048);
const instanceSpec = z.strictObject({
grid: z.strictObject({ counts: z.tuple([instanceCount, instanceCount, instanceCount]), spacing: vector3 }).optional().describe('Grid of counts[0] x counts[1] x counts[2] points centred on the group.'),
@@ -498,6 +498,7 @@ const armature = z.strictObject({
bones: z.array(boneRecord).min(1).max(128).optional().describe('Explicit bones, instead of a preset.'),
}).describe('A skeleton. Each bone becomes a recipe node named after it (parented like the bones, rotating about its head), so motion tracks, motion.ik and set-node address bones by name. Mesh nodes bind with skin. scene_inspect rig lists unweighted vertices, bones with no vertices and joint axis problems.');
const armaturesReference = z.array(z.record(z.string(), z.unknown())).max(16).describe('The same array as recipe.armatures in scene_create: id, parent, preset, fit, bones. Read that tool for the fields.');
+const timelineReference = z.record(z.string(), z.unknown()).describe('Shots in order, up to 60 s; fields in scene_capabilities filmTimeline.');
const recipe = z.strictObject({
format: z.literal('67js.scene'),
schemaVersion: z.literal(1),
@@ -512,7 +513,8 @@ const recipe = z.strictObject({
motion: motion.nullable().optional(),
physics: physics.nullable().optional(),
cloth: cloth.nullable().optional(),
-}).describe('Bounded scene recipe. Backend validates references, mesh resource pairs, hierarchy, geometry budgets and camera consistency.');
+ timeline: timelineReference.nullable().optional(),
+}).describe('Bounded scene recipe; the backend validates it.');
const assetRecipe = z.strictObject({
format: z.literal('67js.asset'),
schemaVersion: z.literal(1),
@@ -538,6 +540,7 @@ const operation = z.discriminatedUnion('type', [
z.strictObject({ type: z.literal('set-armatures'), armatures: armaturesReference.nullable() }),
z.strictObject({ type: z.literal('set-physics'), physics: z.record(z.string(), z.unknown()).nullable().describe('Same object as recipe.physics in scene_create.') }),
z.strictObject({ type: z.literal('set-cloth'), cloth: z.record(z.string(), z.unknown()).nullable() }),
+ z.strictObject({ type: z.literal('set-timeline'), timeline: z.record(z.string(), z.unknown()).nullable() }),
z.strictObject({ type: z.literal('set-environment'), environment }),
z.strictObject({ type: z.literal('set-effects'), effects }),
z.strictObject({ type: z.literal('set-shadow'), shadow }),
@@ -562,10 +565,13 @@ const renderSettings = z.strictObject({
width: z.number().int().min(64).max(1024),
height: z.number().int().min(64).max(1024),
fps: z.number().int().min(1).max(30).optional(),
- duration: z.number().min(0.1).max(30).optional(),
+ duration: z.number().min(0.1).max(60).optional(),
animation: z.strictObject({ clip: z.number().int().min(0), start: z.number().min(0).max(3600).optional() }).optional(),
motion: z.strictObject({ start: z.number().min(0).max(3600).optional() }).optional(),
rendererTime: z.strictObject({ start: z.number().min(0).max(3600).optional(), rate: z.number().min(-16).max(16).optional() }).optional(),
+ timeline: z.strictObject({ start: z.number().min(0).max(60).optional() }).optional().describe('Play the recipe timeline from start (default 0); duration defaults to the rest of it. It owns the motion clock, so leave motion and animation out.'),
+ audio: z.strictObject({ file: z.string().max(68), offset: z.number().min(0).max(3600).optional() }).optional().describe('Video only: a file name in the --audio folder (.wav, .mp3, .ogg, .flac) mixed in from offset seconds.'),
+ encoder: z.enum(VIDEO_ENCODERS).optional().describe('Video only: cpu (default) or nvenc.'),
passes: z.array(z.enum(RENDER_PASS_NAMES)).min(1).max(RENDER_PASS_NAMES.length).optional().describe('image and stills only: also write raw PNGs per frame for these passes; opaque geometry only.'),
}).describe('Immutable snapshot render: one PNG, eight evenly spaced PNGs, or CPU H.264 MP4. Video dimensions must be even. Defaults: 24 fps, one second. Use motion.start for authored recipe tracks, animation for an imported clip, or both to layer them. Omitted motion holds time zero. Nonlooping samples must fit the authored duration.');
const readOnly = { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false };
@@ -653,8 +659,8 @@ export async function runMcpCli({ argumentsValue = process.argv.slice(2),
for (let index = 0; index < argumentsValue.length; index += 2) {
const name = argumentsValue[index];
const value = argumentsValue[index + 1];
- if (!['--backend', '--browser', '--memory', '--assets', '--jobs', '--ffmpeg'].includes(name) || value === undefined) {
- throw new Error('Use --backend cpu|gpu, --browser <local executable path>, --memory <32..256 MiB>, --assets <absolute GLB directory>, --jobs <absolute private output directory>, and --ffmpeg <absolute executable>.');
+ if (!['--backend', '--browser', '--memory', '--assets', '--jobs', '--ffmpeg', '--audio'].includes(name) || value === undefined) {
+ throw new Error('Use --backend cpu|gpu, --browser <local executable path>, --memory <32..256 MiB>, --assets <absolute GLB directory>, --jobs <absolute private output directory>, --ffmpeg <absolute executable>, and --audio <absolute folder of .wav, .mp3, .ogg or .flac files for video jobs>.');
}
options[name.slice(2)] = name === '--memory' ? Number(value) : value;
}
diff --git a/scripts/smoke-film-timeline.mjs b/scripts/smoke-film-timeline.mjs
new file mode 100644
index 00000000..0956eb37
--- /dev/null
+++ b/scripts/smoke-film-timeline.mjs
@@ -0,0 +1,199 @@
+// Proves the timeline through the real MCP runtime: a seek to any time gives the same PNG bytes as that frame inside a
+// sequence, across shots and in any order of seeks; and a video with sound keeps picture and sound in sync, measured
+// by finding the cut in the decoded frames and the click in the decoded audio.
+// Usage: node scripts/smoke-film-timeline.mjs [cli] [cpu|gpu]. FILM_SECONDS=60 renders the long case (15 fps, 900 frames).
+import assert from 'node:assert/strict';
+import { spawnSync } from 'node:child_process';
+import { createHash } from 'node:crypto';
+import { mkdir, mkdtemp, readFile, writeFile } from 'node:fs/promises';
+import { tmpdir, constants, setPriority } from 'node:os';
+import { join, resolve } from 'node:path';
+import { setTimeout as delay } from 'node:timers/promises';
+import { Client } from '@modelcontextprotocol/client';
+import { StdioClientTransport } from '@modelcontextprotocol/client/stdio';
+
+setPriority(0, constants.priority.PRIORITY_BELOW_NORMAL);
+const directory = await mkdtemp(join(tmpdir(), '67js-mcp-timeline-'));
+const jobs = join(directory, 'jobs');
+const audioFolder = join(directory, 'audio');
+await mkdir(audioFolder);
+const cli = resolve(process.argv[2] ?? 'bin/67js-mcp.mjs');
+const backend = process.argv[3] ?? 'cpu';
+const transport = new StdioClientTransport({ command: process.execPath,
+ args: [cli, '--backend', backend, '--memory', '128', '--jobs', jobs, '--audio', audioFolder], cwd: directory, stderr: 'pipe' });
+let diagnostics = '';
+transport.stderr.on('data', bytes => { diagnostics = (diagnostics + bytes).slice(-8192); });
+const client = new Client({ name: '67js-timeline-proof', version: '1' });
+const SIZE = 128;
+const FILM_SECONDS = Number(process.env.FILM_SECONDS ?? 6);
+const FRAMES_PER_SECOND = FILM_SECONDS > 30 ? 15 : 10;
+const SAMPLE_RATE = 16000;
+
+async function call(name, argumentsValue = {}, timeout = 60000) {
+ const result = await client.callTool({ name, arguments: argumentsValue }, { timeout });
+ assert.equal(result.isError, undefined, result.content?.find(item => item.type === 'text')?.text);
+ return result;
+}
+
+async function expectError(name, argumentsValue, pattern) {
+ const result = await client.callTool({ name, arguments: argumentsValue }, { timeout: 60000 });
+ assert.equal(result.isError, true, `${name} should have been rejected.`);
+ assert.match(result.content.find(item => item.type === 'text').text, pattern);
+}
+
+async function finished(jobId, seconds = 900) {
+ const deadline = Date.now() + seconds * 1000;
+ while (Date.now() < deadline) {
+ const record = (await call('scene_render_status', { jobId })).structuredContent;
+ if (['completed', 'cancelled', 'failed'].includes(record.state)) return record;
+ await delay(200);
+ }
+ throw new Error('Job did not finish in time.');
+}
+
+async function runJob(sessionId, settings) {
+ const submitted = (await call('scene_render_submit', { sessionId, expectedRevision: 0, settings })).structuredContent;
+ const record = await finished(submitted.jobId);
+ assert.equal(record.state, 'completed', record.reason);
+ const result = (await call('scene_render_result', { jobId: submitted.jobId })).structuredContent;
+ const files = new Map();
+ for (const artifact of result.artifacts) {
+ const bytes = await readFile(artifact.path);
+ assert.equal(createHash('sha256').update(bytes).digest('hex'), artifact.sha256);
+ files.set(artifact.path.split(/[\\/]/).pop(), { bytes, path: artifact.path });
+ }
+ return { files, metrics: result.metrics ?? record.metrics, jobId: submitted.jobId, elapsedSeconds: record.metrics?.elapsedSeconds };
+}
+
+// Three shots over a moving sphere: a wide shot, a close shot that fills the frame with light, and a shot that dips in.
+function recipe() {
+ const shotSeconds = FILM_SECONDS / 3;
+ return {
+ format: '67js.scene', schemaVersion: 1,
+ geometries: [{ id: 'box', type: 'box' }, { id: 'sphere', type: 'sphere', segments: 24, rings: 16 }],
+ materials: [{ id: 'floor', color: [0.05, 0.05, 0.06], roughness: 0.9 }, { id: 'glow', color: [1, 1, 1], emission: 3 }],
+ nodes: [
+ { id: 'floor', geometry: 'box', material: 'floor', translation: [0, -0.1, 0], scale: [12, 0.2, 12] },
+ { id: 'lamp', geometry: 'sphere', material: 'glow', translation: [0, 0.6, 0] },
+ ],
+ camera: { eye: [0, 1.6, 7], target: [0, 0.5, 0], fov: 40 },
+ effects: { motionBlur: { shutter: 0.25 } },
+ motion: { duration: 4, loop: true, tracks: [{ kind: 'node', id: 'lamp', property: 'translation', keyframes: [
+ { time: 0, value: [-1.5, 0.6, 0] }, { time: 4, value: [1.5, 0.6, 0] },
+ ] }] },
+ timeline: { shots: [
+ { name: 'wide', duration: shotSeconds, camera: { eye: [0, 3, 14], target: [0, -2, 0] } },
+ { name: 'close', duration: shotSeconds, motionStart: 1, camera: { eye: [0, 0.6, 2.4], target: [0, 0.6, 0], fov: 50 } },
+ { name: 'dusk', duration: shotSeconds, dip: 1, camera: { eye: [4, 1.2, 5], target: [0, 0.5, 0] } },
+ ] },
+ };
+}
+
+// A short click at `clickSeconds` in a silent mono file, so the decoded audio shows where the sound lands.
+function clickWav(totalSeconds, clickSeconds) {
+ const samples = Math.ceil(totalSeconds * SAMPLE_RATE);
+ const pcm = Buffer.alloc(samples * 2);
+ const clickStart = Math.round(clickSeconds * SAMPLE_RATE);
+ for (let index = 0; index < SAMPLE_RATE * 0.03; index++) {
+ pcm.writeInt16LE(Math.round(20000 * Math.sin(2 * Math.PI * 1000 * index / SAMPLE_RATE)), (clickStart + index) * 2);
+ }
+ const header = Buffer.alloc(44);
+ header.write('RIFF', 0); header.writeUInt32LE(36 + pcm.length, 4); header.write('WAVEfmt ', 8);
+ header.writeUInt32LE(16, 16); header.writeUInt16LE(1, 20); header.writeUInt16LE(1, 22);
+ header.writeUInt32LE(SAMPLE_RATE, 24); header.writeUInt32LE(SAMPLE_RATE * 2, 28); header.writeUInt16LE(2, 32); header.writeUInt16LE(16, 34);
+ header.write('data', 36); header.writeUInt32LE(pcm.length, 40);
+ return Buffer.concat([header, pcm]);
+}
+
+function decode(path, outputArguments) {
+ const result = spawnSync('ffmpeg', ['-hide_banner', '-loglevel', 'error', '-i', path, ...outputArguments, 'pipe:1'], { maxBuffer: 512 * 1024 ** 2 });
+ assert.equal(result.status, 0, String(result.stderr));
+ return result.stdout;
+}
+
+// Finds the first cut as the frame whose picture changes most from the one before it (before any dip), and the click as
+// the first decoded audio sample above a threshold, both in seconds from the start of the file.
+function measureSync(videoPath, fps, searchEndSeconds) {
+ const frameSize = 8 * 8;
+ const raw = decode(videoPath, ['-map', '0:v:0', '-vf', 'scale=8:8,format=gray', '-f', 'rawvideo']);
+ const frames = [];
+ for (let offset = 0; offset + frameSize <= raw.length; offset += frameSize) frames.push(raw.subarray(offset, offset + frameSize));
+ const means = frames.map(frame => frame.reduce((sum, value) => sum + value, 0) / frameSize);
+ let cutFrame = 1;
+ let largestChange = -1;
+ for (let frame = 1; frame < Math.min(frames.length, Math.floor(searchEndSeconds * fps)); frame++) {
+ let change = 0;
+ for (let index = 0; index < frameSize; index++) change += Math.abs(frames[frame][index] - frames[frame - 1][index]);
+ if (change > largestChange) {
+ largestChange = change;
+ cutFrame = frame;
+ }
+ }
+ const audio = decode(videoPath, ['-map', '0:a:0', '-ac', '1', '-ar', String(SAMPLE_RATE), '-f', 's16le']);
+ let onset = 0;
+ while (onset < audio.length / 2 && Math.abs(audio.readInt16LE(onset * 2)) < 3000) onset++;
+ const cutAt = cutFrame / fps;
+ const clickAt = onset / SAMPLE_RATE;
+ return { frames: frames.length, cutAt, clickAt, offsetMilliseconds: (clickAt - cutAt) * 1000, means };
+}
+
+try {
+ await client.connect(transport);
+ const created = (await call('scene_create', { recipe: recipe() }, 180000)).structuredContent;
+ const sessionId = created.sessionId;
+ const shotSeconds = FILM_SECONDS / 3;
+ const timeline = { start: 0 };
+
+ // Seek determinism across shots: eight stills over the whole timeline, then each frame again as a single image,
+ // in a shuffled order and twice for one of them. The frames fall in all three shots and on the dip.
+ const stills = await runJob(sessionId, { kind: 'stills', width: SIZE, height: SIZE, timeline });
+ assert.equal(stills.files.size, 8);
+ const distinct = new Set([...stills.files.values()].map(file => createHash('sha256').update(file.bytes).digest('hex')));
+ assert.ok(distinct.size >= 7, 'The stills across three shots should almost all differ.');
+ const frameTimes = Array.from({ length: 8 }, (unused, frame) => FILM_SECONDS * frame / 7);
+ const seekOrder = [5, 0, 3, 7, 3, 1, 6, 2, 4];
+ for (const frame of seekOrder) {
+ const seek = await runJob(sessionId, { kind: 'image', width: SIZE, height: SIZE, timeline: { start: frameTimes[frame] } });
+ assert.deepEqual(seek.files.get('render.png').bytes, stills.files.get(`frame-${frame}.png`).bytes, `Frame ${frame} differs after a seek.`);
+ }
+ console.log(`seek: ${seekOrder.length} PNG seeks over ${frameTimes.length} stills identical to the byte (${backend}, ${stills.metrics.graphics})`);
+
+ // Hostile settings through the real tool schema.
+ await expectError('scene_render_submit', { sessionId, expectedRevision: 0, settings: { kind: 'video', width: SIZE, height: SIZE, encoder: 'libx264 -f lavfi' } }, /encoder|Invalid/i);
+ await expectError('scene_render_submit', { sessionId, expectedRevision: 0, settings: { kind: 'video', width: SIZE, height: SIZE, audio: { file: 'http://example.com/a.wav' } } }, /audio|string|Invalid/i);
+ await expectError('scene_render_submit', { sessionId, expectedRevision: 0, settings: { kind: 'video', width: SIZE, height: SIZE, audio: { file: '../outside.wav' } } }, /audio/i);
+ await expectError('scene_render_submit', { sessionId, expectedRevision: 0, settings: { kind: 'video', width: SIZE, height: SIZE, audio: { file: 'missing.wav' } } }, /not in the audio folder/);
+ await expectError('scene_render_submit', { sessionId, expectedRevision: 0, settings: { kind: 'video', width: SIZE, height: SIZE, audio: { file: 'score.wav' }, ffmpegArguments: ['-i', 'x'] } }, /Unrecognized|ffmpegArguments|Invalid/i);
+
+ // Sync: a click placed on the first cut of the timeline, rendered into a video with sound. The audio file is longer
+ // than the film, so the click sits at the cut when the offset is zero.
+ await writeFile(join(audioFolder, 'score.wav'), clickWav(FILM_SECONDS + 1, shotSeconds));
+ await writeFile(join(audioFolder, 'short.wav'), clickWav(1, 0.5));
+ const submittedShort = (await call('scene_render_submit', { sessionId, expectedRevision: 0, settings: { kind: 'video', width: SIZE, height: SIZE, fps: FRAMES_PER_SECOND, timeline, audio: { file: 'short.wav' } } })).structuredContent;
+ const shortRecord = await finished(submittedShort.jobId);
+ assert.equal(shortRecord.state, 'failed');
+ assert.match(shortRecord.reason ?? '', /Audio has .* s after its offset/);
+
+ const film = await runJob(sessionId, { kind: 'video', width: SIZE, height: SIZE, fps: FRAMES_PER_SECOND, timeline, audio: { file: 'score.wav' } });
+ assert.ok(film.metrics.sync, 'The job must report its sync measurement.');
+ assert.deepEqual(film.metrics.shots.map(shot => shot.name), ['wide', 'close', 'dusk']);
+ const measured = measureSync(film.files.get('render.mp4').path, FRAMES_PER_SECOND, 2 * shotSeconds - 0.5);
+ console.log(`film: ${FILM_SECONDS} s at ${FRAMES_PER_SECOND} fps, ${measured.frames} frames decoded, encoder ${film.metrics.videoEncoder}, ${film.metrics.elapsedSeconds.toFixed(1)} s to render`);
+ console.log(JSON.stringify(film.metrics.sync)); console.log(`sync: decoded streams differ by ${(film.metrics.sync.differenceSeconds * 1000).toFixed(1)} ms; cut at ${measured.cutAt.toFixed(3)} s, click at ${measured.clickAt.toFixed(3)} s, offset ${measured.offsetMilliseconds.toFixed(1)} ms`);
+ assert.equal(measured.frames, FILM_SECONDS * FRAMES_PER_SECOND);
+ assert.ok(Math.abs(measured.offsetMilliseconds) <= 1000 / FRAMES_PER_SECOND + 25, 'Sound lands more than a frame and an encoder delay from the cut.');
+ const middleOfDip = Math.round((2 * shotSeconds) * FRAMES_PER_SECOND);
+ assert.ok(measured.means[middleOfDip] < measured.means[middleOfDip - 3] / 2, 'The dip should darken the frame at the cut into the last shot.');
+
+ // An offset moves the sound earlier: the click now lands half a second before the cut.
+ const windowStart = shotSeconds - 1.5;
+ const early = await runJob(sessionId, { kind: 'video', width: SIZE, height: SIZE, fps: FRAMES_PER_SECOND, timeline: { start: windowStart }, duration: 3, audio: { file: 'score.wav', offset: windowStart + 0.5 } });
+ const earlyMeasured = measureSync(early.files.get('render.mp4').path, FRAMES_PER_SECOND, 3);
+ assert.ok(Math.abs(earlyMeasured.offsetMilliseconds + 500) <= 1000 / FRAMES_PER_SECOND + 25, `An audio offset of 0.5 s should move the click 500 ms earlier, got ${earlyMeasured.offsetMilliseconds.toFixed(1)} ms.`);
+ console.log(`timeline smoke passed on ${backend}`);
+} catch (error) {
+ console.error(diagnostics);
+ throw error;
+} finally {
+ await client.close();
+}
diff --git a/skills/render-67js-media/SKILL.md b/skills/render-67js-media/SKILL.md
index 47ee5420..1702b896 100644
--- a/skills/render-67js-media/SKILL.md
+++ b/skills/render-67js-media/SKILL.md
@@ -12,6 +12,7 @@ Use the repository pipeline rather than constructing a parallel exporter.
For MCP snapshot jobs, read the checkout's `docs/agent-render-jobs.md` and verify source versus published support.
Configure a private job store. Poll status after cancellation before resuming preview edits.
+For a video with cuts, sound or an encoder choice, use the recipe `timeline`, `settings.timeline`, `settings.audio` (a file in the server's `--audio` folder) and `settings.encoder` described in the same document; the job reports measured sync.
For procedural motion, read `docs/agent-motion.md` and select `settings.motion.start`. Preview seeks preserve revisions and authored recipes.
For imported character motion from `0.8.0`, read `docs/agent-character-motion.md`. Use independent `settings.animation` and `settings.motion` clocks.
diff --git a/src/agent-scene-capabilities.js b/src/agent-scene-capabilities.js
index 4333c2e9..2f632b82 100644
--- a/src/agent-scene-capabilities.js
+++ b/src/agent-scene-capabilities.js
@@ -62,6 +62,12 @@ export const DEFAULT_AMBIENT_OCCLUSION = 0;
// Render passes a render job can write next to the lit image (see RENDER_PASS_MODES in renderer.js, which must list the same names).
export const RENDER_PASS_NAMES = Object.freeze(['albedo', 'normal', 'emission', 'depth', 'objectId']);
+// Video encoders a render job can choose (nvenc is h264_nvenc and fails the job when the GPU or ffmpeg lacks it), the
+// longest video, and the audio file names a job may mix in from the --audio folder: one path segment with a known
+// extension, no drive or protocol syntax.
+export const VIDEO_ENCODERS = Object.freeze(['cpu', 'nvenc']);
+export const MAXIMUM_VIDEO_SECONDS = 60;
+export const AUDIO_FILE_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}\.(wav|mp3|ogg|flac)$/;
// Metres that depth pass values 0 to 65535 span, measured from the camera.
export const RENDER_PASS_DEPTH_RANGE = 100;
@@ -89,13 +95,19 @@ export const AGENT_SCENE_CAPABILITIES = Object.freeze({
operations: Object.freeze([
'set-node', 'set-material', 'set-camera', 'add-node', 'remove-node',
'add-geometry', 'remove-geometry', 'add-material', 'remove-material',
- 'set-environment', 'set-effects', 'set-shadow', 'set-motion', 'set-armatures', 'set-physics', 'set-cloth', 'edit-mesh', 'set-mesh-stack',
+ 'set-environment', 'set-effects', 'set-shadow', 'set-motion', 'set-armatures', 'set-physics', 'set-cloth', 'set-timeline', 'edit-mesh', 'set-mesh-stack',
]),
materialTags: Object.freeze(['surface', 'unlit', 'liquid', 'foam']),
alphaModes: RECIPE_ALPHA_MODES,
materialPatterns: MATERIAL_PATTERN_TYPES, maxMaterialPatterns: MAX_MATERIAL_PATTERNS,
materialMappings: MATERIAL_MAPPINGS,
renderPasses: Object.freeze({ names: RENDER_PASS_NAMES, files: 'render-<pass>.png or frame-N-<pass>.png, raw and unantialiased; opaque and cutout geometry only', depth: `16 bits in red and green over ${RENDER_PASS_DEPTH_RANGE} m`, objectId: '24 bits in RGB; the job result lists the part names' }),
+ // Recipe timeline (src/film-timeline.js), rendered with settings.timeline; the rest is in docs/agent-render-jobs.md.
+ filmTimeline: Object.freeze({
+ maxShots: 64, maxTotalSeconds: 60, maxShotSeconds: 30,
+ shot: 'name (unique), duration, motionStart (default: the shot start, so non-looping motion must cover it), camera (partial: eye target up fov near far), dip (s; fades through black at the cut into this shot).',
+ notSupported: 'layers, overlaps, crossfades, markers, events, imported assets',
+ }),
curveText: Object.freeze({
maxCurvePoints: CURVE_TEXT_LIMITS.maxCurvePoints, maxProfilePoints: CURVE_TEXT_LIMITS.maxProfilePoints,
maxTextCharacters: CURVE_TEXT_LIMITS.maxTextCharacters, maxTextLines: CURVE_TEXT_LIMITS.maxTextLines,
diff --git a/src/agent-scene-modules.js b/src/agent-scene-modules.js
index 1cf6d690..e71954e5 100644
--- a/src/agent-scene-modules.js
+++ b/src/agent-scene-modules.js
@@ -12,6 +12,7 @@ const MODULE_LOADERS = {
cloth: () => import('./agent-cloth.js'),
patterns: () => import('./material-patterns.js'),
relations: () => import('./agent-relations.js'),
+ timeline: () => import('./film-timeline.js'),
};
const loadedModules = {};
@@ -29,6 +30,7 @@ const MODULE_MARKERS = {
cloth: ['"cloth":{'],
patterns: ['"pattern"'],
relations: ['"relations":'],
+ timeline: ['"timeline":{'],
};
/** Whether a recipe, operation list or edit list contains a boolean edit, which needs loadMeshBooleans() first. */
diff --git a/src/agent-scene.js b/src/agent-scene.js
index a86cc44d..5f46a015 100644
--- a/src/agent-scene.js
+++ b/src/agent-scene.js
@@ -579,7 +579,7 @@ function addArmatures(recipe, limits) {
function normalizeRecipe(input, limits) {
let recipe = copiedJson(input, limits.maxRecipeBytes);
- knownKeys(recipe, ['format', 'schemaVersion', 'geometries', 'materials', 'nodes', 'armatures', 'camera', 'environment', 'effects', 'shadow', 'motion', 'physics', 'cloth'], 'recipe');
+ knownKeys(recipe, ['format', 'schemaVersion', 'geometries', 'materials', 'nodes', 'armatures', 'camera', 'environment', 'effects', 'shadow', 'motion', 'physics', 'cloth', 'timeline'], 'recipe');
if (recipe.format !== '67js.scene' || recipe.schemaVersion !== 1) {
throw new RangeError('Expected 67js.scene schemaVersion 1.');
}
@@ -629,10 +629,23 @@ function normalizeRecipe(input, limits) {
if (Object.hasOwn(recipe, 'cloth')) {
recipe.cloth = agentSceneModule('cloth').normalizeAgentCloth(recipe.cloth, recipe);
}
+ if (Object.hasOwn(recipe, 'timeline')) {
+ if (recipe.timeline === null) {
+ delete recipe.timeline;
+ } else {
+ recipe.timeline = agentSceneModule('timeline').normalizeFilmTimeline(recipe.timeline, recipe, { checkCamera: shotCameraOverrides => cameraOverridesFrom(recipe.camera, shotCameraOverrides) });
+ }
+ }
recipe = copiedJson(recipe, limits.maxRecipeBytes);
return recipe;
}
+// A shot camera is a partial camera: it must be valid on top of the recipe camera, and only its own fields are kept.
+function cameraOverridesFrom(baseCamera, overrides) {
+ cameraFrom({ ...baseCamera, ...overrides });
+ return structuredClone(overrides);
+}
+
function geometryStats(records) {
let vertices = 0;
let geometryBytes = 0;
@@ -1089,6 +1102,14 @@ export function createAgentScene(input, inputLimits = {}) {
candidate.physics = operation.physics;
continue;
}
+ if (operation.type === 'set-timeline') {
+ knownKeys(operation, ['type', 'timeline'], 'operation');
+ if (!Object.hasOwn(operation, 'timeline')) {
+ throw new TypeError('set-timeline requires timeline; use null to clear it.');
+ }
+ candidate.timeline = operation.timeline;
+ continue;
+ }
if (operation.type === 'set-cloth') {
knownKeys(operation, ['type', 'cloth'], 'operation');
if (!Object.hasOwn(operation, 'cloth')) {
@@ -1206,7 +1227,7 @@ export function createAgentScene(input, inputLimits = {}) {
fields = CAMERA_FIELDS;
target = candidate.camera;
} else {
- throw new TypeError(`Unsupported operation type: ${operation.type}. Use one of set-node, set-material, set-camera, set-motion, set-physics, set-cloth, set-environment, set-effects, set-shadow, add-node, add-geometry, add-material, remove-node, remove-geometry, remove-material, edit-mesh, set-mesh-stack.`);
+ throw new TypeError(`Unsupported operation type: ${operation.type}. Use one of set-node, set-material, set-camera, set-motion, set-physics, set-cloth, set-timeline, set-environment, set-effects, set-shadow, add-node, add-geometry, add-material, remove-node, remove-geometry, remove-material, edit-mesh, set-mesh-stack.`);
}
knownKeys(operation, ['type', ...(operation.type === 'set-camera' ? [] : ['id']), ...fields], 'operation');
if (!target) {
diff --git a/src/film-timeline.js b/src/film-timeline.js
new file mode 100644
index 00000000..293a9a95
--- /dev/null
+++ b/src/film-timeline.js
@@ -0,0 +1,141 @@
+// A recipe timeline: shots played one after another over the recipe's motion clock. Plain data and plain functions with
+// no engine imports, so the MCP server (render jobs) and the scene (recipe validation) share one definition.
+// Not a video sequence editor: no layers, no overlaps and no clip trimming. Shots cut, or dip through black.
+
+export const FILM_TIMELINE_LIMITS = Object.freeze({
+ maxShots: 64, maxTotalSeconds: 60, minShotSeconds: 0.1, maxShotSeconds: 30, maxDipSeconds: 4, maxMotionStart: 3600,
+});
+
+const SHOT_NAME_PATTERN = /^[A-Za-z0-9_-]{1,24}$/;
+const SHOT_FIELDS = ['name', 'duration', 'motionStart', 'camera', 'dip'];
+
+function plainObject(value, label) {
+ if (!value || typeof value !== 'object' || Array.isArray(value) || Object.getPrototypeOf(value) !== Object.prototype) {
+ throw new TypeError(`${label} must be a plain object.`);
+ }
+}
+
+function rejectUnknownKeys(value, allowed, label) {
+ for (const key of Object.keys(value)) {
+ if (!allowed.includes(key)) throw new TypeError(`${label} has unsupported field ${JSON.stringify(key.slice(0, 48))}.`);
+ }
+}
+
+function numberBetween(value, minimum, maximum, label) {
+ if (typeof value !== 'number' || !Number.isFinite(value) || value < minimum || value > maximum) {
+ throw new RangeError(`${label} must be a number from ${minimum} to ${maximum}.`);
+ }
+ return value;
+}
+
+function hasAnimatedScene(recipe) {
+ return Boolean(recipe?.motion || recipe?.physics || recipe?.cloth);
+}
+
+/**
+ * Validates and copies a timeline against its recipe. `checkCamera(cameraOverrides)` lets the caller reject camera
+ * fields with the engine's own rules and return the cleaned copy; without it the camera is only checked for shape.
+ */
+export function normalizeFilmTimeline(timeline, recipe, { checkCamera } = {}) {
+ plainObject(timeline, 'timeline');
+ rejectUnknownKeys(timeline, ['shots'], 'timeline');
+ const { shots } = timeline;
+ if (!Array.isArray(shots) || shots.length < 1 || shots.length > FILM_TIMELINE_LIMITS.maxShots) {
+ throw new RangeError(`timeline.shots must list 1 to ${FILM_TIMELINE_LIMITS.maxShots} shots.`);
+ }
+ const animated = hasAnimatedScene(recipe);
+ const seenNames = new Set();
+ let startSeconds = 0;
+ const normalized = shots.map((shot, index) => {
+ plainObject(shot, `Shot ${index}`);
+ rejectUnknownKeys(shot, SHOT_FIELDS, `Shot ${index}`);
+ if (typeof shot.name !== 'string' || !SHOT_NAME_PATTERN.test(shot.name)) {
+ throw new TypeError(`Shot ${index} name must be 1 to 24 letters, digits, - or _.`);
+ }
+ if (seenNames.has(shot.name)) throw new RangeError(`Shot name ${shot.name} is used twice.`);
+ seenNames.add(shot.name);
+ const duration = numberBetween(shot.duration, FILM_TIMELINE_LIMITS.minShotSeconds, FILM_TIMELINE_LIMITS.maxShotSeconds, `Shot ${shot.name} duration`);
+ const result = { name: shot.name, duration };
+ if (shot.motionStart !== undefined) {
+ if (!animated) throw new RangeError(`Shot ${shot.name} sets motionStart but the recipe has no motion, physics or cloth.`);
+ result.motionStart = numberBetween(shot.motionStart, 0, FILM_TIMELINE_LIMITS.maxMotionStart, `Shot ${shot.name} motionStart`);
+ }
+ if (animated && recipe.motion && !recipe.motion.loop) {
+ const motionStart = result.motionStart ?? startSeconds;
+ if (motionStart + duration > recipe.motion.duration) {
+ throw new RangeError(`Shot ${shot.name} reads motion up to ${motionStart + duration} s but the motion lasts ${recipe.motion.duration} s. Set motionStart, or make the motion loop.`);
+ }
+ }
+ if (shot.dip !== undefined) {
+ result.dip = numberBetween(shot.dip, 0.05, FILM_TIMELINE_LIMITS.maxDipSeconds, `Shot ${shot.name} dip`);
+ const previousDuration = index === 0 ? Infinity : shots[index - 1].duration;
+ if (result.dip / 2 > duration || result.dip / 2 > previousDuration) {
+ throw new RangeError(`Shot ${shot.name} dip is longer than twice the shots on either side of the cut.`);
+ }
+ }
+ if (shot.camera !== undefined) {
+ plainObject(shot.camera, `Shot ${shot.name} camera`);
+ result.camera = checkCamera ? checkCamera(shot.camera) : { ...shot.camera };
+ }
+ startSeconds += duration;
+ return result;
+ });
+ if (startSeconds > FILM_TIMELINE_LIMITS.maxTotalSeconds) {
+ throw new RangeError(`The timeline lasts ${startSeconds} s; the most is ${FILM_TIMELINE_LIMITS.maxTotalSeconds} s.`);
+ }
+ return { shots: normalized };
+}
+
+export function filmTimelineDuration(timeline) {
+ let total = 0;
+ for (const shot of timeline.shots) total += shot.duration;
+ return total;
+}
+
+/** Shots with their start times, summed in order so the same time always lands in the same shot. */
+export function filmTimelineShotStarts(timeline) {
+ let startSeconds = 0;
+ return timeline.shots.map(shot => {
+ const entry = { name: shot.name, start: startSeconds, duration: shot.duration };
+ startSeconds += shot.duration;
+ return entry;
+ });
+}
+
+function brightnessAt(timeline, starts, index, shotTime) {
+ let brightness = 1;
+ const shot = timeline.shots[index];
+ if (shot.dip !== undefined) brightness = Math.min(brightness, shotTime / (shot.dip / 2));
+ const next = timeline.shots[index + 1];
+ if (next?.dip !== undefined) {
+ const remaining = starts[index].duration - shotTime;
+ brightness = Math.min(brightness, remaining / (next.dip / 2));
+ }
+ return Math.max(0, Math.min(1, brightness));
+}
+
+/**
+ * Everything one frame needs at timeline time `time`: the shot, the motion clock (null for a static recipe), the
+ * camera overrides and the brightness of a dip through black. It keeps no state, so any seek gives the same answer.
+ */
+export function sampleFilmTimeline(timeline, recipe, time) {
+ const starts = filmTimelineShotStarts(timeline);
+ const total = filmTimelineDuration(timeline);
+ if (!Number.isFinite(time) || time < 0 || time > total) {
+ throw new RangeError(`Timeline time ${time} is outside 0 to ${total} s.`);
+ }
+ let index = starts.length - 1;
+ for (let candidate = 0; candidate < starts.length; candidate++) {
+ if (time < starts[candidate].start + starts[candidate].duration) {
+ index = candidate;
+ break;
+ }
+ }
+ const shot = timeline.shots[index];
+ const shotTime = time - starts[index].start;
+ const motionTime = hasAnimatedScene(recipe) ? (shot.motionStart ?? starts[index].start) + shotTime : null;
+ return {
+ shotIndex: index, shotName: shot.name, shotTime, motionTime,
+ camera: shot.camera ?? null, brightness: brightnessAt(timeline, starts, index, shotTime),
+ };
+}
diff --git a/tests/agent-render-jobs.test.js b/tests/agent-render-jobs.test.js
index a050f274..f518711f 100644
--- a/tests/agent-render-jobs.test.js
+++ b/tests/agent-render-jobs.test.js
@@ -178,7 +178,7 @@ test('validation enforces range, geometry-independent storage limits and one pen
{ kind: 'video', width: 65, height: 64 },
{ kind: 'image', width: 1025, height: 64 },
{ kind: 'video', width: 64, height: 64, fps: 31 },
- { kind: 'video', width: 64, height: 64, duration: 31 },
+ { kind: 'video', width: 64, height: 64, duration: 61 },
]) await assert.rejects(controller.submit({ ...request(), settings }));
await assert.rejects(controller.submit({ ...request(), snapshot: { recipe: {}, clips: [{ duration: 1 }] }, settings: { kind: 'video', width: 64, height: 64, duration: 1, animation: { clip: 0, start: 0.1 } } }), /clip duration/);
await assert.rejects(controller.submit({ ...request(), snapshot: { recipe: { sparse: Array(2) } } }), /dense/);
diff --git a/tests/agent-runtime.test.js b/tests/agent-runtime.test.js
index dedf2fa6..04b1ff50 100644
--- a/tests/agent-runtime.test.js
+++ b/tests/agent-runtime.test.js
@@ -6,7 +6,9 @@ import { readFile } from 'node:fs/promises';
import { createServer } from 'node:http';
import { randomUUID } from 'node:crypto';
import { createContext, Script } from 'node:vm';
-import { AGENT_SCENE_CAPABILITIES, AGENT_SCENE_DEFAULT_LIMITS, RENDER_PASS_NAMES, RENDER_PASS_DEPTH_RANGE } from '../src/agent-scene-capabilities.js';
+import { AGENT_SCENE_CAPABILITIES, AGENT_SCENE_DEFAULT_LIMITS, RENDER_PASS_NAMES, RENDER_PASS_DEPTH_RANGE, VIDEO_ENCODERS, MAXIMUM_VIDEO_SECONDS } from '../src/agent-scene-capabilities.js';
+import { audioInputArguments, createAudioLibrary, measureStreamSeconds } from '../scripts/job-audio.mjs';
+import { filmTimelineDuration, filmTimelineShotStarts, sampleFilmTimeline } from '../src/film-timeline.js';
import { normalizeReview, REVIEW_LIMITS } from '../scripts/agent-review.mjs';
import { BRANCH_LIMITS, validateBranchName } from '../src/agent-branches.js';
@@ -97,7 +99,8 @@ async function reviewRuntimeHarness({ failShot, blockShot = false, oversize = fa
const context = createContext({ createServer, randomUUID, existsSync: () => true,
readFile: async () => '', packageMetadata: { version: 'test' },
createRequire: () => ({ resolve: () => { throw new Error('no peer in tests'); } }),
- AGENT_SCENE_CAPABILITIES, AGENT_SCENE_DEFAULT_LIMITS, RENDER_PASS_NAMES, RENDER_PASS_DEPTH_RANGE, normalizeReview, REVIEW_LIMITS, isPreviewHost, BRANCH_LIMITS, validateBranchName,
+ AGENT_SCENE_CAPABILITIES, AGENT_SCENE_DEFAULT_LIMITS, RENDER_PASS_NAMES, RENDER_PASS_DEPTH_RANGE, VIDEO_ENCODERS, MAXIMUM_VIDEO_SECONDS,
+ audioInputArguments, createAudioLibrary, measureStreamSeconds, filmTimelineDuration, filmTimelineShotStarts, sampleFilmTimeline, normalizeReview, REVIEW_LIMITS, isPreviewHost, BRANCH_LIMITS, validateBranchName,
chromium: { launch: async () => browser }, URL, Buffer, process, performance, setTimeout, clearTimeout,
});
new Script(`${source}\nglobalThis.runtime = createAgentRuntime({ backend: 'cpu' });`).runInContext(context);
diff --git a/tests/film-timeline.test.js b/tests/film-timeline.test.js
new file mode 100644
index 00000000..398dc6c1
--- /dev/null
+++ b/tests/film-timeline.test.js
@@ -0,0 +1,186 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import { mkdtemp, mkdir, rm, symlink, writeFile } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { createAgentScene, AGENT_SCENE_CAPABILITIES } from '../src/agent-scene.js';
+import { filmTimelineDuration, filmTimelineShotStarts, normalizeFilmTimeline, sampleFilmTimeline } from '../src/film-timeline.js';
+import { createAgentRenderJobs } from '../scripts/agent-render-jobs.mjs';
+import { createAudioLibrary } from '../scripts/job-audio.mjs';
+
+function recipeWith(extra = {}) {
+ return {
+ format: '67js.scene', schemaVersion: 1,
+ geometries: [{ id: 'box', type: 'box' }],
+ materials: [{ id: 'grey', color: [0.5, 0.5, 0.5] }],
+ nodes: [{ id: 'block', geometry: 'box', material: 'grey' }],
+ camera: { eye: [0, 1, 6], target: [0, 0, 0], fov: 40 },
+ ...extra,
+ };
+}
+
+const threeShots = {
+ shots: [
+ { name: 'wide', duration: 2 },
+ { name: 'close', duration: 3, camera: { eye: [0, 0.5, 2], fov: 30 }, dip: 1 },
+ { name: 'end', duration: 1 },
+ ],
+};
+
+test('a timeline keeps its shots, camera overrides and durations through the scene', () => {
+ const scene = createAgentScene(recipeWith({ timeline: threeShots }));
+ const exported = scene.exportRecipe();
+ assert.deepEqual(exported.timeline.shots.map(shot => shot.name), ['wide', 'close', 'end']);
+ assert.deepEqual(exported.timeline.shots[1].camera, { eye: [0, 0.5, 2], fov: 30 });
+ assert.equal(filmTimelineDuration(exported.timeline), 6);
+ assert.deepEqual(filmTimelineShotStarts(exported.timeline).map(shot => shot.start), [0, 2, 5]);
+});
+
+test('set-timeline edits the timeline and null removes it', () => {
+ const scene = createAgentScene(recipeWith());
+ assert.ok(AGENT_SCENE_CAPABILITIES.operations.includes('set-timeline'));
+ scene.apply([{ type: 'set-timeline', timeline: threeShots }], { expectedRevision: scene.revision });
+ assert.equal(scene.exportRecipe().timeline.shots.length, 3);
+ scene.apply([{ type: 'set-timeline', timeline: null }], { expectedRevision: scene.revision });
+ assert.equal(Object.hasOwn(scene.exportRecipe(), 'timeline'), false);
+ assert.throws(() => scene.apply([{ type: 'set-timeline' }], { expectedRevision: scene.revision }), /requires timeline/);
+});
+
+test('hostile timelines are rejected with a reason', () => {
+ const rejected = [
+ [{ shots: [] }, /1 to 64/],
+ [{ shots: [{ name: 'a', duration: 1 }], layers: [] }, /unsupported field "layers"/],
+ [{ shots: [{ name: 'a b', duration: 1 }] }, /name must be/],
+ [{ shots: [{ name: '../x', duration: 1 }] }, /name must be/],
+ [{ shots: [{ name: 'a', duration: 1 }, { name: 'a', duration: 1 }] }, /used twice/],
+ [{ shots: [{ name: 'a', duration: 0.01 }] }, /duration must be/],
+ [{ shots: [{ name: 'a', duration: 31 }] }, /duration must be/],
+ [{ shots: [{ name: 'a', duration: 30 }, { name: 'b', duration: 30 }, { name: 'c', duration: 1 }] }, /the most is 60/],
+ [{ shots: [{ name: 'a', duration: 1, motionStart: 0 }] }, /no motion, physics or cloth/],
+ [{ shots: [{ name: 'a', duration: 1, dip: 4 }] }, /dip is longer/],
+ [{ shots: [{ name: 'a', duration: 1, camera: 'close' }] }, /plain object/],
+ [{ shots: [{ name: 'a', duration: 1, extra: true }] }, /unsupported field "extra"/],
+ [{ shots: Array.from({ length: 65 }, (unused, index) => ({ name: `s${index}`, duration: 0.1 })) }, /1 to 64/],
+ ];
+ for (const [timeline, message] of rejected) {
+ assert.throws(() => createAgentScene(recipeWith({ timeline })), message);
+ }
+ assert.throws(() => createAgentScene(recipeWith({ timeline: { shots: [{ name: 'a', duration: 1, camera: { eye: [0, 0, 0], target: [0, 0, 0], fov: 400 } }] } })), /fov|camera/i);
+ assert.throws(() => createAgentScene(recipeWith({ timeline: { shots: [{ name: 'a', duration: 1, camera: { zoom: 2 } }] } })), /camera/);
+ assert.throws(() => normalizeFilmTimeline(Object.create({ shots: [] }), recipeWith()), /plain object/);
+ for (const duration of [Number.NaN, Infinity, '2', null]) {
+ assert.throws(() => normalizeFilmTimeline({ shots: [{ name: 'a', duration }] }, recipeWith()), /duration must be/);
+ }
+});
+
+test('motion must cover the shots unless it loops or the shot sets motionStart', () => {
+ const motion = { duration: 4, tracks: [{ kind: 'node', id: 'block', property: 'translation', keyframes: [{ time: 0, value: [0, 0, 0] }, { time: 4, value: [1, 0, 0] }] }] };
+ assert.throws(() => createAgentScene(recipeWith({ motion, timeline: threeShots })), /reads motion up to 5 s/);
+ const replayed = { shots: [{ name: 'a', duration: 3 }, { name: 'b', duration: 3, motionStart: 2 }] };
+ assert.throws(() => createAgentScene(recipeWith({ motion, timeline: replayed })), /reads motion up to 5 s/);
+ assert.doesNotThrow(() => createAgentScene(recipeWith({ motion: { ...motion, loop: true }, timeline: threeShots })));
+ const cuts = { shots: [{ name: 'a', duration: 2 }, { name: 'b', duration: 2, motionStart: 0 }] };
+ assert.doesNotThrow(() => createAgentScene(recipeWith({ motion, timeline: cuts })));
+});
+
+test('sampling is stateless: a time gives one shot, motion clock, camera and brightness in any order', () => {
+ const motion = { duration: 10, tracks: [{ kind: 'node', id: 'block', property: 'translation', keyframes: [{ time: 0, value: [0, 0, 0] }, { time: 10, value: [1, 0, 0] }] }] };
+ const recipe = recipeWith({ motion });
+ const timeline = normalizeFilmTimeline({ shots: [
+ { name: 'wide', duration: 2 },
+ { name: 'close', duration: 3, motionStart: 7, camera: { fov: 30 }, dip: 1 },
+ ] }, recipe);
+ const first = sampleFilmTimeline(timeline, recipe, 2.25);
+ assert.equal(first.shotName, 'close');
+ assert.equal(first.motionTime, 7.25);
+ assert.deepEqual(first.camera, { fov: 30 });
+ assert.equal(first.brightness, 0.5);
+ const order = [4.99, 0, 2.25, 1.99, 2.25];
+ const samples = order.map(time => JSON.stringify(sampleFilmTimeline(timeline, recipe, time)));
+ assert.equal(samples[2], samples[4]);
+ assert.equal(sampleFilmTimeline(timeline, recipe, 0).shotName, 'wide');
+ assert.equal(sampleFilmTimeline(timeline, recipe, 1.75).brightness, 0.5);
+ assert.equal(sampleFilmTimeline(timeline, recipe, 2).brightness, 0);
+ assert.equal(sampleFilmTimeline(timeline, recipe, 3).brightness, 1);
+ assert.equal(sampleFilmTimeline(timeline, recipe, 5).shotName, 'close');
+ assert.throws(() => sampleFilmTimeline(timeline, recipe, 5.01), /outside/);
+ assert.throws(() => sampleFilmTimeline(timeline, recipe, -1), /outside/);
+ const stillRecipe = recipeWith();
+ assert.equal(sampleFilmTimeline(normalizeFilmTimeline(threeShots, stillRecipe), stillRecipe, 3).motionTime, null);
+});
+
+async function controllerFor(context) {
+ const root = await mkdtemp(join(tmpdir(), '67js-timeline-jobs-'));
+ const controller = await createAgentRenderJobs({ root, async run({ signal }) {
+ await new Promise(resolve => signal.addEventListener('abort', resolve, { once: true }));
+ throw signal.reason;
+ } });
+ context.after(async () => {
+ await controller.close();
+ await rm(root, { recursive: true, force: true });
+ });
+ return controller;
+}
+
+function submission(settings, recipe = createAgentScene(recipeWith({ timeline: threeShots })).exportRecipe()) {
+ return { sourceRevision: 0, snapshot: { recipe }, settings: { kind: 'video', width: 64, height: 64, fps: 10, ...settings } };
+}
+
+test('timeline settings derive the duration and reject mixed clocks and ranges past the end', async context => {
+ const controller = await controllerFor(context);
+ const record = await controller.submit(submission({ timeline: {} }));
+ assert.equal(controller.status(record.jobId).settings.duration, 6);
+ assert.equal(controller.status(record.jobId).settings.frameCount, 60);
+ assert.deepEqual(controller.status(record.jobId).settings.timeline, { start: 0 });
+ controller.cancel(record.jobId);
+ while (!['cancelled', 'failed'].includes(controller.status(record.jobId).state)) await new Promise(resolve => setTimeout(resolve, 10));
+ const rejected = [
+ { timeline: { start: 7 } },
+ { timeline: { start: 4 }, duration: 3 },
+ { timeline: { offset: 1 } },
+ { timeline: {}, motion: { start: 0 } },
+ { timeline: { start: -1 } },
+ ];
+ for (const settings of rejected) await assert.rejects(controller.submit(submission(settings)));
+ await assert.rejects(controller.submit(submission({ timeline: {} }, recipeWith())), /require a recipe with a timeline/);
+});
+
+test('encoder is a bounded enum and audio is a plain file name, both video only', async context => {
+ const controller = await controllerFor(context);
+ const hostileEncoders = ['libx264', 'nvenc -f lavfi', 'cpu; rm -rf', '', null, 7, ['cpu'], { name: 'cpu' }];
+ for (const encoder of hostileEncoders) await assert.rejects(controller.submit(submission({ encoder })), /encoder/);
+ await assert.rejects(controller.submit(submission({ kind: 'image', encoder: 'cpu' })), /encoder needs kind video/);
+ const hostileFiles = ['../score.wav', '..\\score.wav', 'C:\\score.wav', '/etc/passwd.wav', 'http://example.com/a.wav', 'file:score.wav',
+ 'concat:a.wav|b.wav', '-i score.wav', 'score.wav\0.mp3', 'score.exe', 'score', '.wav', 'a b.wav', 'a'.repeat(70) + '.wav', ['score.wav'], { toString: () => 'score.wav' }, 7];
+ for (const file of hostileFiles) await assert.rejects(controller.submit(submission({ audio: { file } })), /audio/);
+ await assert.rejects(controller.submit(submission({ audio: { file: 'score.wav', gain: 2 } })), /Unknown audio field/);
+ await assert.rejects(controller.submit(submission({ audio: { file: 'score.wav', offset: -1 } })), /audio offset/);
+ await assert.rejects(controller.submit(submission({ kind: 'image', audio: { file: 'score.wav' } })), /audio needs kind video/);
+ const accepted = await controller.submit(submission({ encoder: 'nvenc', audio: { file: 'score.wav', offset: 1.5 } }));
+ assert.deepEqual(controller.status(accepted.jobId).settings.audio, { file: 'score.wav', offset: 1.5 });
+ assert.equal(controller.status(accepted.jobId).settings.encoder, 'nvenc');
+});
+
+test('the audio library resolves plain files only and refuses links, empty files and wrong names', async context => {
+ const root = await mkdtemp(join(tmpdir(), '67js-audio-library-'));
+ const outside = await mkdtemp(join(tmpdir(), '67js-audio-outside-'));
+ context.after(() => Promise.all([rm(root, { recursive: true, force: true }), rm(outside, { recursive: true, force: true })]));
+ await writeFile(join(root, 'score.wav'), 'RIFF');
+ await writeFile(join(root, 'empty.wav'), '');
+ await writeFile(join(outside, 'secret.wav'), 'RIFF');
+ await mkdir(join(root, 'folder.wav'));
+ const library = createAudioLibrary(root);
+ assert.equal(await library.resolve('score.wav'), join(root, 'score.wav'));
+ await assert.rejects(library.resolve('missing.wav'), /not in the audio folder/);
+ await assert.rejects(library.resolve('empty.wav'), /1 byte/);
+ await assert.rejects(library.resolve('folder.wav'), /regular file/);
+ await assert.rejects(library.resolve('../secret.wav'), /not allowed/);
+ await assert.rejects(library.resolve(join(outside, 'secret.wav')), /not allowed/);
+ try {
+ await symlink(join(outside, 'secret.wav'), join(root, 'link.wav'));
+ await assert.rejects(library.resolve('link.wav'), /regular file|outside/);
+ } catch (error) {
+ if (error.code !== 'EPERM') throw error;
+ }
+ assert.throws(() => createAudioLibrary('relative/folder'), /absolute/);
+});