@margoengine/headless 0.1.0 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,768 +1,1232 @@
1
- # @margoengine/headless
2
-
3
- Render a scene with no page and get PNG bytes back: server thumbnails, an asset pipeline, automated tests. Core draws to
4
- a stand-in canvas, and the frame stays readable because nothing presents it.
5
-
6
- Margo has no video encoder of its own. Video uses WebCodecs in a browser or worker, and in Node the `ffmpeg` you have installed, so rendering to MP4 in Node means installing ffmpeg first.
7
-
8
- This package ships no WebGPU binding, because one is a large download that runs code when installed. Your app chooses
9
- one and passes its `gpu` in. It can be any object with `requestAdapter`: `create([])` from a Node binding such as
10
- [`webgpu`](https://www.npmjs.com/package/webgpu) (`npm install webgpu`; every example here runs on version 0.6.2 in Node, on the GPU the machine has), or `navigator.gpu` in a browser or worker.
11
-
12
- ```ts
13
- import { writeFile } from 'node:fs/promises';
14
- import { Camera, Engine, box, PbrMaterial } from '@margoengine/core';
15
- import { createHeadlessCanvas, installGPU, toPNG } from '@margoengine/headless';
16
- import { create } from 'webgpu';
17
-
18
- const gpu = create([]);
19
- using installed = installGPU({ gpu });
20
- const canvas = createHeadlessCanvas({ width: 512, height: 512 });
21
- const engine = await Engine.create(canvas, { backend: 'webgpu' });
22
- engine.createMesh().setGeometry(box()).setMaterial(new PbrMaterial({ color: '#84d6bd' }));
23
- engine.render({ camera: new Camera({ position: [2, 2, 3], target: [0, 0, 0] }) });
24
- await writeFile('cube.png', await toPNG(engine));
25
- engine.dispose();
26
- ```
27
-
28
- | Export | What it does |
29
- | --- | --- |
30
- | `installGPU({ gpu, globals? })` | Sets `navigator.gpu` and the `GPU*` flag globals a runtime lacks; adds `getPreferredCanvasFormat` (`'rgba8unorm'`) if the binding has none. `globals` defaults to none. `dispose()` or `using` restores everything. |
31
- | `createHeadlessCanvas({ width, height })` | The canvas to pass to `Engine.create`. Both sizes are required. Set `canvas.width` and `canvas.height` to resize; the next `engine.render()` uses them. |
32
- | `readPixels(engine, { signal? })` | The last frame as `{ width, height, data }`: RGBA, straight alpha, top row first. |
33
- | `createFrameReader(engine, { depth?, signal? })` | From `@margoengine/headless/frames`: reads every frame of a film without waiting for each one. See below. |
34
- | `toPNG(engine, { signal? })` | The last frame as PNG file bytes. |
35
- | `encodePNG(pixels)` | RGBA pixels as PNG file bytes. Rejects with a `RangeError` when the size is not a whole number from 1 or `data` is not `width * height * 4` bytes; `encodeJPEG` and `encodeWebP` refuse the same. |
36
-
37
- Call `engine.render()` yourself: `engine.start()` needs `requestAnimationFrame`, which Node does not have. `createStage`
38
- needs a page; `createHeadlessStage` below is its server version.
39
-
40
- ### Reading every frame of a film
41
-
42
- `readPixels` waits for the GPU to finish the frame it was given before it returns. `createFrameReader` from
43
- `@margoengine/headless/frames` keeps up to `depth` copies in flight instead, so the next frame is drawn while earlier
44
- ones are still being read. Call `push()` once after each `engine.render()`: it copies that frame and resolves to the
45
- oldest held frame once `depth` are held. `drain()` gives the rest. The frames and their order are the same as
46
- `readPixels` after every render.
47
-
48
- ```ts
49
- import { writeFile } from 'node:fs/promises';
50
- import { Camera, Engine, box, PbrMaterial } from '@margoengine/core';
51
- import { createHeadlessCanvas, encodePNG, installGPU, type HeadlessPixels } from '@margoengine/headless';
52
- import { createFrameReader } from '@margoengine/headless/frames';
53
- import { create } from 'webgpu';
54
-
55
- const gpu = create([]);
56
- using installed = installGPU({ gpu });
57
- const canvas = createHeadlessCanvas({ width: 320, height: 180 });
58
- const engine = await Engine.create(canvas, { backend: 'webgpu' });
59
- engine.createMesh().setGeometry(box()).setMaterial(new PbrMaterial({ color: '#84d6bd' }));
60
-
61
- const frames: HeadlessPixels[] = [];
62
- {
63
- using reader = createFrameReader(engine, { depth: 3 });
64
- for (let i = 0; i < 12; i++) {
65
- const angle = i / 12;
66
- engine.render({ camera: new Camera({ position: [3 * Math.sin(angle), 2, 3 * Math.cos(angle)], target: [0, 0, 0] }) });
67
- const frame = await reader.push();
68
- if (frame) frames.push(frame);
69
- }
70
- for await (const frame of reader.drain()) frames.push(frame);
71
- }
72
- if (frames.length !== 12) throw new Error(`read ${frames.length} frames`);
73
- await writeFile('last.png', await encodePNG(frames[11]));
74
- engine.dispose();
75
- ```
76
-
77
- | Option or member | What it does |
78
- | --- | --- |
79
- | `depth` | Frames held at once, 1 to 16. Default 3. 1 waits for each frame. Each held frame owns one buffer of `height` rows of `width * 4` bytes rounded up to 256. |
80
- | `signal` | Disposes the reader; waiting reads reject with the reason. Default none. |
81
- | `push()` | Copies the frame just rendered. Resolves to the oldest held frame once `depth` are held, else `undefined`. |
82
- | `drain()` | An async iterator over the frames still held, oldest first. |
83
- | `pending` | Frames copied and not yet handed out. |
84
- | `dispose()` | Frees the buffers; held frames are lost. Also `using`. |
85
-
86
- A reader makes `depth` buffers for a whole film, and `readPixels` keeps one buffer on the canvas between reads of one
87
- size; both free them on a resize.
88
-
89
- ### The same frames on every run
90
-
91
- `readPixels` reads the frame texture this package owns, after the GPU has finished it, so a film drawn on
92
- `createHeadlessCanvas` gives the same bytes on every run from its first frame, alone or beside another process on the
93
- GPU, on WebGPU and the WebGL2 layer (`packages/sky/test/rain-frames-check.mjs`: a 90-frame rain shot with the
94
- Bruneton sky, clouds, AgX and shadows, byte for byte in four fresh browsers). A page that reads its real canvas
95
- instead must read it in the same task as `engine.render()`, as `capture` in `@margoengine/exporters` does: after an
96
- `await`, `drawImage`, `toDataURL` and `createImageBitmap` of a WebGPU canvas give the last frame the browser showed,
97
- which lags by a number of frames that differs from run to run (65 of 90 frames differed between two runs read that
98
- way). On the WebGL2 layer the layer loads its compute part before `requestDevice` answers (KB-COMPAT-FIRSTTASK1 in
99
- docs/known-bugs.md), so a page canvas read in the task of the first render shows that frame, as on WebGPU.
100
-
101
- ### Film frames: anti-aliasing and motion blur from sub-frames
102
-
103
- `renderAccumulated` from `@margoengine/headless/accumulate` renders each frame `samples` times, each render at its own
104
- time inside the open shutter and with its own sub-pixel offset, and averages them in linear light with an `Accumulate`
105
- stage from `@margoengine/post/accumulate` (an optional peer, loaded on first use when no stage is given). The tone curve
106
- is applied once, to the average, so a bright edge or a fast highlight keeps its brightness instead of the dark smear
107
- an average of 8-bit frames gives. Everything that moves blurs, since each render is the scene at its own time:
108
- cameras, skinned and morphed meshes, particles, wind. Each frame is read back once, after its last render.
109
-
110
- ```ts
111
- import { writeFile } from 'node:fs/promises';
112
- import { Camera, Engine, box, PbrMaterial } from '@margoengine/core';
113
- import { createHeadlessCanvas, encodePNG, installGPU } from '@margoengine/headless';
114
- import { renderAccumulated } from '@margoengine/headless/accumulate';
115
- import { encodeEXR } from '@margoengine/headless/formats';
116
- import { Accumulate } from '@margoengine/post/accumulate';
117
- import { PostStack } from '@margoengine/post';
118
- import { Tonemap } from '@margoengine/tonemap';
119
- import { create } from 'webgpu';
120
-
121
- const gpu = create([]);
122
- using installed = installGPU({ gpu });
123
- const engine = await Engine.create(createHeadlessCanvas({ width: 320, height: 180 }), { backend: 'webgpu' });
124
- const cube = engine.createMesh().setGeometry(box()).setMaterial(new PbrMaterial({ color: '#84d6bd' }));
125
- const accumulate = new Accumulate();
126
- PostStack.attach(engine, [accumulate, new Tonemap()]);
127
- const camera = new Camera({ position: [0, 1.5, 4], target: [0, 0, 0] });
128
-
129
- let frames = 0;
130
- for await (const frame of renderAccumulated(engine, {
131
- frames: 4,
132
- fps: 24,
133
- samples: 16, // renders per frame
134
- shutter: 0.5, // a 180 degree shutter
135
- camera,
136
- accumulate,
137
- update: ({ time }) => {
138
- camera.position = [4 * Math.sin(time * 6), 1.5, 4 * Math.cos(time * 6)];
139
- },
140
- })) {
141
- if (frame.data.length !== 320 * 180 * 4) throw new Error('wrong frame size');
142
- await writeFile(`film_${frame.index}.png`, await encodePNG(frame));
143
- frames++;
144
- }
145
- // output: 'linear' gives the mean in linear light, for an EXR.
146
- for await (const frame of renderAccumulated(engine, { frames: 1, samples: 8, camera, accumulate, output: 'linear' }))
147
- await encodeEXR(frame);
148
- if (frames !== 4 || !cube) throw new Error(`rendered ${frames} frames`);
149
- engine.dispose();
150
- ```
151
-
152
- | Option | What it does |
153
- | --- | --- |
154
- | `frames` | How many frames, a whole number from 1. Required. |
155
- | `fps` | Frames per second. Default 30. |
156
- | `samples` | Renders per frame, 1 to 4096. Default 16. 1 renders each frame once, with no offset. |
157
- | `shutter` | Share of the frame interval the shutter is open, 0 to 1. Default 0.5 (180 degrees); 0 is a still instant. |
158
- | `shutterPhase` | `'start'` (open from the frame's time), `'center'` or `'end'`. Default `'start'`. |
159
- | `filter`, `filterWidth` | Pixel filter the offsets are drawn from: `'blackman-harris'` (default), `'gaussian'` or `'box'`; width in pixels, default 2 (1 for `'box'`). |
160
- | `startFrame` | Number of the first frame, for a span of a longer film after a seek with `subFrameSteps`. Default 0. |
161
- | `seed`, `pattern` | The sample pattern's seed (default 0); `'fixed'` (default) repeats it every frame so still edges do not shimmer, `'per-frame'` draws a new one. |
162
- | `camera` | Camera to render through; it is never modified. Default the engine's camera. |
163
- | `update(timing)` | Runs before each render with that render's `time`, `delta`, `index` (frame), `sample` and `samples`. May be async. |
164
- | `accumulate` | The `Accumulate` stage in your PostStack, before `Tonemap`. Default one attached alone and disposed at the end. |
165
- | `output` | `'display'` (default): 8-bit RGBA as `readPixels` reads it. `'linear'`: float RGBA of the mean, for `encodeEXR`. |
166
- | `signal` | Stops between renders or during readback; the iterator rejects with the reason. |
167
-
168
- `renderFrames` from `@margoengine/headless/video` takes the same `samples`, `shutter` and filter options and runs
169
- `renderAccumulated` when `samples` is above 1 or `shutter` above 0, so `renderCutscene` and any film loop get motion
170
- blur by adding two options; with neither it renders each frame once, exactly as before.
171
-
172
- `subFrames(options)` is the same schedule without rendering: each render's `frame`, `sample`, `time`, `delta`, `offset`
173
- and `last`, pure and repeatable. The engine's clocks start at 0 and the deltas keep them on each render's time (a render
174
- before 0, with a `'center'` or `'end'` shutter on frame 0, moves them 0). `startFrame` starts a span of a longer film,
175
- and `subFrameSteps({ ...options, startFrame })` lists the deltas of every render before it, for
176
- `seek(engine, seconds, { steps })` in `@margoengine/cutscene/seek`: the span then gives the whole film's renders, bit
177
- for bit. Times are the middles of `samples` equal slices of the open shutter, in order, so the
178
- deltas add up to the frame interval; offsets are Owen-scrambled Sobol points (Burley 2020) mapped through the filter
179
- (filter importance sampling, Ernst, Stamminger and Greiner 2006) and shuffled against the time order.
180
-
181
- - **Checked on a real GPU** (`npm run test:gpu:accumulate -w @margoengine/headless`, WebGPU and the WebGL2 layer): an
182
- orthographic edge at x = 20.3 px reads 0.297 of the lit level in linear light at 64 box samples (one sample: 0 or 1);
183
- at radiance 4 the edge pixel equals a still lit to that share (244 against 244), far from the mean of the two
184
- display values (76); two runs are bit-identical; an 8 px strip moving 32 px a frame under a 180 degree shutter
185
- spreads over 24 px, keeps its energy (1.000) and centres at 44.03 px against 44 for mid-shutter; an abort rejects
186
- with its reason.
187
- - **Limits.** Effects with their own frame history (TAA's jitter, SSGI multi-bounce) advance once per render, so turn
188
- TAA's jitter off (`velocityOnly`). Simulations see the sub-frame deltas, so a film repeats exactly for fixed `fps`,
189
- `samples`, `shutter` and phase. Cost is `samples` renders a frame. WebGPU and the WebGL2 layer; on the layer's
190
- half-float tier the sum is float16.
191
-
192
- ## A stage without a page
193
-
194
- `@margoengine/headless/stage` gives server thumbnails the same short setup as a page. `createHeadlessStage` returns a real
195
- `Stage`, so its methods and the stage's feature entries work as they do on a page. It needs `@margoengine/stage`, an optional
196
- peer:
197
-
198
- ```ts
199
- import { writeFile } from 'node:fs/promises';
200
- import { createHeadlessStage } from '@margoengine/headless/stage';
201
- import { addSky } from '@margoengine/stage/sky';
202
- import { create } from 'webgpu';
203
-
204
- const gpu = create([]);
205
- using stage = await createHeadlessStage({ gpu, width: 640, height: 360 });
206
- stage.box({ color: '#84d6bd' });
207
- await addSky(stage);
208
- stage.fit();
209
- await writeFile('thumbnail.png', await stage.toPNG());
210
- ```
211
-
212
- | Export | What it does |
213
- | --- | --- |
214
- | `createHeadlessStage({ width, height, gpu?, globals?, onError?, transparent?, ...engineOptions })` | Installs the GPU and creates the engine on a stand-in canvas. `width` and `height` are required. `gpu` defaults to `navigator.gpu`, `globals` to none. `transparent` defaults to false; true leaves the background clear (below). The backend is always WebGPU. Stages alive at once must share one `gpu`; the globals are restored when the last is disposed. |
215
- | `stage.toPNG({ signal? })`, `stage.readPixels({ signal? })` | Draws a frame and gives it as PNG bytes or RGBA pixels. |
216
- | `stage.step(delta?)` | Runs `onTick` and `engine.onFrame` callbacks, then draws a frame that advances plugins by `delta` seconds, 0 to 1 (default 0); a delta outside that range, or a step from inside a step, throws before any callback runs. `stage.resize(width, height)` takes whole numbers from 1. Nothing runs by itself: there are no camera controls and no frame loop. |
217
- | `stage.resize(width, height)` | Sets the image size for the next frame. |
218
-
219
- `stage.onTick` and `stage.engine.onFrame` both run on `step`, so a package that drives itself from `onFrame` advances here too. To load a model
220
- with `addGLTF`, pass an absolute URL, since Node has no page address to resolve against.
221
-
222
- ### Graphics over footage
223
-
224
- `transparent: true` draws no background: `readPixels` gives alpha 0 where nothing was drawn, 255 on the graphics and
225
- the coverage on their edges, as straight alpha, so titles, maps and lower thirds can be laid over recorded video
226
- (`encodeVideo` and `encodeWithFFmpeg` keep it with `alpha: true`). It attaches `TransparentCanvas` from
227
- `@margoengine/environment`, an optional peer. Tonemap, a `PostStack` ending in Tonemap, FXAA or SMAA, and the
228
- `@margoengine/ui` overlay keep it. DOF, TAA and SceneFade are for opaque frames only; the `@margoengine/post` README
229
- lists the other effects.
230
-
231
- ```ts
232
- import { writeFile } from 'node:fs/promises';
233
- import { createHeadlessStage } from '@margoengine/headless/stage';
234
- import { Tonemap } from '@margoengine/tonemap';
235
- import { Panel, Ui, UiRenderer } from '@margoengine/ui';
236
- import { create } from 'webgpu';
237
-
238
- const gpu = create([]);
239
- using stage = await createHeadlessStage({ gpu, width: 640, height: 360, transparent: true });
240
- stage.box({ color: '#84d6bd' });
241
- Tonemap.attach(stage.engine);
242
- const ui = new Ui();
243
- ui.add(new Panel({ background: '#101820c0', width: 280, height: 64, anchor: 'bottom-left' }));
244
- UiRenderer.attach(stage.engine, ui);
245
- stage.fit();
246
- await writeFile('overlay.png', await stage.toPNG());
247
- ```
248
-
249
- ## Choosing the GPU adapter
250
-
251
- On a machine with two GPUs, an integrated one and a discrete one, the render runs on whichever adapter the binding hands out. Three things choose it, checked with the `webgpu` binding 0.6.2 on a Windows PC with an RTX A6000 and an integrated AMD GPU:
252
-
253
- - `gpu.requestAdapter()` called with no options returned the integrated AMD GPU. Code that asks the binding for an adapter itself, to read its name or limits, gets that one unless it passes `{ powerPreference: 'high-performance' }`, which returned the RTX A6000.
254
- - `Engine.create` and `createHeadlessStage` ask for `'high-performance'` themselves when you set nothing (Node reports no Windows browser, so the Windows exception in core's `powerPreference` does not apply) and got the RTX A6000. Set `powerPreference: 'low-power'` for the integrated GPU, or `'high-performance'` to say so in your code. It is an engine option, so `createHeadlessStage({ gpu, width, height, powerPreference })` takes it too.
255
- - `create(['adapter=NVIDIA'])` fixes the choice in the binding: the first adapter whose name contains that text, whatever any caller asks for. The match is case sensitive (`adapter=nvidia` found nothing, `adapter=RTX` and `adapter=Radeon` matched). With no match the binding throws `no suitable backends found` and lists the adapters it has by name, which is the quickest way to learn what to write.
256
-
257
- `engine.gpu.adapterInfo` names the GPU the engine got. This example runs as it stands; set `GPU_ADAPTER` to a part of an adapter name to fix the choice:
258
-
259
- ```ts
260
- import { Engine } from '@margoengine/core';
261
- import { createHeadlessCanvas, installGPU } from '@margoengine/headless';
262
- import { create } from 'webgpu';
263
-
264
- const wanted = process.env.GPU_ADAPTER;
265
- const gpu = create(wanted ? [`adapter=${wanted}`] : []);
266
- using installed = installGPU({ gpu });
267
- const engine = await Engine.create(createHeadlessCanvas({ width: 640, height: 360 }), {
268
- backend: 'webgpu',
269
- powerPreference: 'high-performance',
270
- });
271
- console.log(engine.gpu?.adapterInfo?.device); // for example 'nvidia-rtx-a6000'
272
- engine.dispose();
273
- ```
274
-
275
- The two GPUs render at different speeds, so time your own scene with each before you fix a render machine's choice.
276
-
277
- ## Image sequences and video
278
-
279
- `@margoengine/headless/video` renders a sequence on its own clock, so a slow machine gives the same frames as a fast one,
280
- and encodes it for turntables, trailers and docs. `renderFrames` yields each frame's pixels, and `imageSequence` turns them into
281
- numbered PNG files:
282
-
283
- ```ts
284
- import { writeFile } from 'node:fs/promises';
285
- import { Camera, Engine, box, PbrMaterial } from '@margoengine/core';
286
- import { createHeadlessCanvas, installGPU } from '@margoengine/headless';
287
- import { imageSequence, renderFrames } from '@margoengine/headless/video';
288
- import { create } from 'webgpu';
289
-
290
- const gpu = create([]);
291
- using installed = installGPU({ gpu });
292
- const engine = await Engine.create(createHeadlessCanvas({ width: 640, height: 360 }), { backend: 'webgpu' });
293
- const mesh = engine.createMesh().setGeometry(box()).setMaterial(new PbrMaterial({ color: '#84d6bd' }));
294
- const camera = new Camera({ position: [2, 2, 3], target: [0, 0, 0] });
295
- const frames = renderFrames(engine, {
296
- frames: 90,
297
- fps: 30,
298
- camera,
299
- update: ({ progress }) => mesh.setRotation([0, progress * Math.PI * 2, 0]),
300
- });
301
- for await (const { name, bytes } of imageSequence(frames)) await writeFile(name, bytes);
302
- engine.dispose();
303
- ```
304
-
305
- `encodeVideo` makes a WebM or MP4 file with WebCodecs, in a browser or worker, or anywhere you pass `webCodecs`:
306
-
307
- ```ts
308
- import { Engine, box } from '@margoengine/core';
309
- import { encodeVideo, renderFrames } from '@margoengine/headless/video';
310
- import { createHeadlessCanvas } from '@margoengine/headless';
311
-
312
- // In a browser, which has WebCodecs; the readable canvas keeps each rendered frame.
313
- const engine = await Engine.create(createHeadlessCanvas({ width: 512, height: 512 }), { backend: 'webgpu' });
314
- engine.createMesh().setGeometry(box());
315
-
316
- const video = await encodeVideo(renderFrames(engine, { frames: 90 }), { format: 'mp4' });
317
- const url = URL.createObjectURL(new Blob([video.bytes], { type: video.mimeType }));
318
- ```
319
-
320
- Frames of their own length, such as a capture of real time or a cut that holds a shot, carry `timestamp` (seconds from
321
- the first frame) and the last one its `duration`. Each frame lasts until the next:
322
-
323
- ```ts
324
- import { Engine, box } from '@margoengine/core';
325
- import { encodeVideo, renderFrames, type VideoInputFrame } from '@margoengine/headless/video';
326
- import { createHeadlessCanvas } from '@margoengine/headless';
327
-
328
- const engine = await Engine.create(createHeadlessCanvas({ width: 320, height: 240 }), { backend: 'webgpu' });
329
- const mesh = engine.createMesh().setGeometry(box());
330
-
331
- // Three shots, held for half a second, a quarter of a second and two seconds.
332
- const holds = [0.5, 0.25, 2];
333
- async function* shots(): AsyncGenerator<VideoInputFrame> {
334
- let timestamp = 0;
335
- const update = ({ index }: { index: number }) => mesh.setRotation([0, index, 0]);
336
- for await (const frame of renderFrames(engine, { frames: holds.length, update })) {
337
- yield { ...frame, timestamp, duration: holds[frame.index] };
338
- timestamp += holds[frame.index];
339
- }
340
- }
341
-
342
- const video = await encodeVideo(shots(), { format: 'webm' });
343
- if (video.frames !== 3 || Math.abs(video.duration - 2.75) > 0.001) throw new Error('unexpected timing');
344
- engine.dispose();
345
- ```
346
-
347
- `alpha: true` keeps the frames' alpha, for an overlay an editor or a page lays over other pictures. A second encoder
348
- codes the alpha, and WebM carries it beside each frame as Matroska BlockAdditions, which Chromium's `<video>` and
349
- ffmpeg's libvpx decoders read (both are tested); it takes VP9, else VP8:
350
-
351
- ```ts
352
- import { encodeVideo, type VideoInputFrame } from '@margoengine/headless/video';
353
-
354
- // A white bar fading in over two seconds, clear everywhere else: straight alpha, as readPixels gives it.
355
- function* lowerThird(): Generator<VideoInputFrame> {
356
- const width = 320, height = 180;
357
- for (let index = 0; index < 60; index++) {
358
- const data = new Uint8Array(width * height * 4).fill(255);
359
- for (let i = 0; i < width * height; i++) data[i * 4 + 3] = i >= width * 130 && i < width * 160 ? index * 4 : 0;
360
- yield { width, height, data };
361
- }
362
- }
363
-
364
- const overlay = await encodeVideo(lowerThird(), { alpha: true });
365
- if (!overlay.alpha || !overlay.mimeType.startsWith('video/webm')) throw new Error('no alpha');
366
- ```
367
-
368
- `streamVideo` writes a fragmented MP4, or with `format: 'webm'` a live WebM, piece by piece as the frames are encoded,
369
- so a long render holds one key frame interval of video at a time. Write each piece to a file, a socket or a
370
- `WritableStream`, or append all but the last piece (the index) to a Media Source Extensions `SourceBuffer` to play
371
- while it renders:
372
-
373
- ```ts
374
- import { Engine, box } from '@margoengine/core';
375
- import { renderFrames, streamVideo } from '@margoengine/headless/video';
376
- import { createHeadlessCanvas } from '@margoengine/headless';
377
-
378
- const engine = await Engine.create(createHeadlessCanvas({ width: 320, height: 240 }), { backend: 'webgpu' });
379
- engine.createMesh().setGeometry(box());
380
-
381
- const pieces: Uint8Array<ArrayBuffer>[] = [];
382
- const stop = new AbortController();
383
- for await (const piece of streamVideo(renderFrames(engine, { frames: 60 }), { keyFrameInterval: 1, signal: stop.signal })) {
384
- pieces.push(piece); // or: await writer.write(piece)
385
- }
386
- const file = new Blob(pieces, { type: 'video/mp4' });
387
- if (pieces.length !== 4 || file.size === 0) throw new Error('unexpected stream'); // header, 2 fragments, index
388
- engine.dispose();
389
- ```
390
-
391
- The WebM stream carries alpha too, for an overlay played while it is made:
392
-
393
- ```ts
394
- import { streamVideo, type VideoInputFrame } from '@margoengine/headless/video';
395
-
396
- // A white bar fading in over two seconds, clear everywhere else: straight alpha, as readPixels gives it.
397
- function* fadeIn(): Generator<VideoInputFrame> {
398
- const width = 320, height = 180;
399
- for (let index = 0; index < 60; index++) {
400
- const data = new Uint8Array(width * height * 4).fill(255);
401
- for (let i = 0; i < width * height; i++) data[i * 4 + 3] = i >= width * 130 && i < width * 160 ? index * 4 : 0;
402
- yield { width, height, data };
403
- }
404
- }
405
-
406
- const stream = streamVideo(fadeIn(), { format: 'webm', alpha: true, keyFrameInterval: 1 });
407
- const pieces: Uint8Array<ArrayBuffer>[] = [];
408
- let step;
409
- while (!(step = await stream.next()).done) pieces.push(step.value); // header, 2 clusters, Cues
410
- if (!step.value.alpha || pieces.length !== 4) throw new Error('unexpected stream');
411
- const overlay = new Blob(pieces, { type: step.value.mimeType });
412
- ```
413
-
414
- Node has no WebCodecs, so `@margoengine/headless/ffmpeg` (Node only) pipes the frames to the ffmpeg you have installed. Nothing
415
- is downloaded, and it runs without a shell. `audio` adds sound from plain samples, sent down a second pipe beside the frames:
416
-
417
- ```ts
418
- import { Engine, box, Camera } from '@margoengine/core';
419
- import { renderFrames } from '@margoengine/headless/video';
420
- import { encodeWithFFmpeg } from '@margoengine/headless/ffmpeg';
421
- import { createHeadlessCanvas, installGPU } from '@margoengine/headless';
422
- import { create } from 'webgpu';
423
-
424
- using installed = installGPU({ gpu: create([]) });
425
- const engine = await Engine.create(createHeadlessCanvas({ width: 512, height: 512 }), { backend: 'webgpu' });
426
- engine.createMesh().setGeometry(box());
427
- engine.render({ camera: new Camera({ position: [2, 2, 3], target: [0, 0, 0] }) });
428
-
429
- // Three seconds of a 440 Hz tone, as long as the 90 frames at 30 fps.
430
- const tone = Float32Array.from({ length: 3 * 48000 }, (_, i) => 0.2 * Math.sin((2 * Math.PI * 440 * i) / 48000));
431
- const result = await encodeWithFFmpeg(renderFrames(engine, { frames: 90 }), {
432
- output: 'turntable.mp4',
433
- audio: { channels: [tone], sampleRate: 48000 },
434
- });
435
- if (result.frames !== 90 || result.audioDuration !== 3) throw new Error('unexpected file');
436
- ```
437
-
438
- `npm run test:real-ffmpeg` writes H.264 and VP9 files, with and without AAC and Opus sound, through the ffmpeg you have (`FFMPEG` names another) and decodes them back to check frames, tags, colours, and the sound's length, pitch and level; then it reads alpha back with ffmpeg's libvpx decoder from a VP9 alpha file of `encodeWithFFmpeg`. `npm run test:gpu` does the same for the VP9 and VP8 alpha files `encodeVideo` makes in Chromium, after playing them in a `<video>`.
439
-
440
- | Export | What it does |
441
- | --- | --- |
442
- | `renderFrames(engine, { frames, fps?, camera?, update?, signal? })` | Async iterator of frames: pixels plus `index`, `time`, `delta` and `progress`. `fps` defaults to 30, `camera` to the engine's. `update` runs before each frame is drawn. `progress` is `index / frames`: it never reaches 1, so a full turn loops with no repeated frame. The next frame is not drawn until you ask for it. |
443
- | `imageSequence(frames, { prefix?, digits? })` | Async iterator of `{ index, name, bytes }` PNG files. `prefix` defaults to `'frame_'`, `digits` to 4. |
444
- | `encodeVideo(frames, options?)` | The whole file in memory as `{ bytes, mimeType, codec, width, height, frames, duration }`, plus `alpha: true` when the file carries alpha. `format` `'webm'` (default) or `'mp4'`. `fps` 30. `codec`: a WebCodecs string; default the first supported of VP9, VP8, AV1 for WebM and H.264, VP9, AV1 for MP4. MP4 also takes H.265 (`hvc1.*` or `hev1.*`, for example `'hvc1.1.6.L93.B0'`) where the runtime encodes it (Safari, and Chromium with a platform encoder). `bitrate` `width * height * fps / 10`, at least 100,000. `keyFrameInterval` 2 seconds. `audio` none: `{ channels, sampleRate, bitrate? }` adds sound from plain samples, one `Float32Array` per channel, one or two channels, `bitrate` 128000, as Opus in WebM and as AAC or else Opus in MP4, and the result then has `audioCodec`. `alpha` false: true keeps the frames' alpha (straight, as `readPixels` gives it) in a WebM file, the same codec and settings whose luma is the alpha, and written as each frame's BlockAdditions (BlockAddID 1, AlphaMode 1 on the track, RFC 9559 and the Matroska V_VP8 and V_VP9 mappings); a frame is a key frame, with a cue, only when its colour and its alpha both are. It takes VP9, else VP8; MP4 and AV1 have no binding for alpha, so `format: 'mp4'` or an `av01` codec with `alpha` rejects with code `'unsupported'`. `webCodecs` `globalThis`, with `AudioEncoder` and `AudioData` needed for `audio`, and `AudioDecoder` used to measure an AAC encoder's lead-in (2112 samples, 44 ms at 48 kHz, on Chromium for macOS), which an edit list then cuts so the sound starts on time; without `AudioDecoder` an AAC track plays late by it. `signal` none. Each frame is converted to limited-range BT.709 4:2:0 before the encoder sees it, and the file says so (BT.709 primaries and matrix, sRGB transfer, chroma on the even columns between rows, the H.264 default), so every player draws the colours that were rendered, chroma edges in place. A frame may carry `timestamp`, seconds counted from the first frame's, for frames of varying length (a capture of real time, a cut that holds a shot): give it on every frame or none, each later than the one before; each frame lasts until the next, and the last one its own `duration` (seconds) or else the gap before it. Key frames then come `keyFrameInterval` seconds apart, and WebM states no default frame duration. Without timestamps frame n shows at n / fps. H.264 and H.265 state sizes in steps of two, so an odd width or height gains one repeated last column or row there (the result's `width` and `height` give the size written); VP8, VP9 and AV1 keep odd sizes. `mimeType` names every stream in the file, the sound's too (`video/mp4; codecs="avc1.640033,mp4a.40.2"`), as RFC 6381 asks, so `MediaSource.isTypeSupported` and `canPlayType` judge the whole file. |
445
- | `streamVideo(frames, options?)` | Async iterator of the pieces of a video file as it is encoded. `format` `'mp4'` (default): a fragmented MP4 (ISO/IEC 14496-12 8.8): the header (`ftyp`, `moov` with empty sample tables and `mvex`) once the encoder gives its configuration, then a `moof` and `mdat` per key frame interval as soon as the next key frame shows where it ends, then an `mfra` index so a player seeks the finished file without reading every fragment. `format` `'webm'`: a WebM written as a live stream (RFC 9559 6.2): the header (EBML header, a Segment of unknown size, Info with no duration, Tracks, Tags), then a Cluster per key frame interval as soon as the next key frame shows where it ends, then the Cues; its clusters are `encodeVideo`'s, and `alpha` keeps the frames' alpha as `encodeVideo` does (VP9, else VP8). Joined, the pieces are one file that browsers and ffmpeg play; all but the last piece are what a Media Source Extensions `SourceBuffer` takes. Options are `encodeVideo`'s (`fps`, `codec`, `bitrate`, `keyFrameInterval`, `audio`, `alpha`, `provenance`, `webCodecs`, `signal`) without `maxBytes`: only one key frame interval of encoded video is held, so there is no total to cap. `alpha` with MP4 or an `av01` codec rejects with code `'unsupported'`. `audio` is encoded first and each fragment or cluster carries the sound of the time its frames cover (in MP4 with the same edit list and roll groups as `encodeVideo`). A joined WebM states no duration, as its header went out before the end was known. The iteration's return value is `encodeVideo`'s result without `bytes`. Stopping the iteration (`break`, or `signal`, which rejects with its reason) closes the encoders. |
446
- | `encodeWithFFmpeg(frames, { output, fps?, ffmpeg?, args?, audio?, alpha?, layers?, signal? })` | Writes `output` and resolves `{ output, width, height, frames }`, plus `audioDuration` (seconds) with sound. `audio` none: `{ channels, sampleRate, bitrate? }`, one `Float32Array` per channel from -1 to 1, one or two channels of one length, a whole `sampleRate`, `bitrate` 128000; it goes to ffmpeg as 32-bit float samples on a second pipe (`pipe:3`) while the frames go down standard input, each waiting only for its own room, and is written as Opus for `.webm` and AAC for anything else. With `args` the sound is still input 1 and mapped (`-map 0:v:0 -map 1:a:0`), and its codec is the one your arguments or ffmpeg's default for the file pick. `fps` defaults to 30, `ffmpeg` to `'ffmpeg'` on the `PATH` (or `['nice', 'ffmpeg']`). `args` replaces the output arguments, which default to VP9 at `-crf 32` for `.webm` and H.264 at `-crf 20` for anything else, both 4:2:0, limited range, tagged BT.709 for matrix and primaries and sRGB for transfer, as `encodeVideo` tags them, with chroma made and tagged on the left column between rows. With the default H.264 arguments an odd width or height gains one repeated last column or row, and the result gives the size written. `alpha` false: true keeps the frames' alpha as VP9 with an alpha plane (`yuva420p`), which ffmpeg writes as WebM BlockAdditions; it needs a `.webm` output and the default arguments, and rejects with code `'unsupported'` otherwise (with `args`, choose the pixel format there). `layers` none: each `{ input, rect: { x, y, width, height }, start?, duration?, in?, speed?, fit? }` lays the file `input` over the frames in the box `rect` (whole pixels inside the written frame), from `start` seconds (default 0) for `duration` seconds (default: until the file ends; a still picture needs one), reading the file from `in` seconds (default 0) at `speed` (default 1), cut to `crop` `[x, y, width, height]` of the file first (even whole pixels inside it; default all of it), fitted by `fit` `'contain'` (default: all of it, the rest of the box `pad`, a colour `'#rgb'`, `'#rrggbb'` or `'#rrggbbaa'`, default clear), `'cover'` or `'fill'` (`contain` and `cover` keep the shape the file is shown at, its width times its sample aspect ratio over its height, so a clip with non-square samples such as 720x480 at 32:27 fills a 16:9 box; `fill` stretches to the box), and read with `matrix` and `range` (default: the file's tags; untagged, `'bt709'` at 720 lines or more and `'bt601'` below, at `'tv'` range; an untagged JPEG `'bt601'` at `'pc'`); later layers lie on top. Each clip frame starts on the film frame nearest its own time (`fps=<fps>:round=near`). Frame k shows a layer when start <= k / fps < start + duration, its last frame held to the end of its window, and the video keeps the rendered frames' length. Each layer file is read once with `probeVideo` before the encode. The layers and the colour chain run as one `-filter_complex` graph, the output arguments' `-vf` moved to its end, so a layered video is tagged exactly as a plain one. A failure's `cause` holds the end of ffmpeg's log. |
447
- | `ffmpegArguments(width, height, { output, fps?, args?, audio?, alpha?, layers? })` | The argument list `encodeWithFFmpeg` uses. It reads no file: pass layers through `resolveLayers` first for the default colours. |
448
- | `probeVideo(input, { ffmpeg?, signal? })` | The first video stream of a video or picture file as ffmpeg reports it: `{ codec, pixelFormat, width, height, rgb, matrix?, range? }`, `matrix` and `range` only when the file is tagged with them (ffmpeg's names, such as `'bt709'`, `'bt470bg'`, `'tv'`), `rgb` true for RGB, palette and grey formats. Rejects with code `'failed'` when there is no video stream. |
449
- | `resolveLayers(layers, { ffmpeg?, signal? })` | The layers with `matrix` and `range` filled in for each untagged file by the defaults above, each file read once; a `crop` outside its file throws a RangeError. |
450
- | `layersOverPicture(picture, output, { frame, fps?, layers, ffmpeg?, signal? })` | Lays `layers` over `picture`, a rendered frame `frame` of a video at `fps` (default 30), exactly as `encodeWithFFmpeg` lays them on that frame, and writes `output` (PNG for a `.png` name). The still equals the encode's frame pixel for pixel when the encode is lossless RGB. |
451
- | `layersPictureArguments(width, height, { picture, output, frame, fps?, layers })` | The argument list `layersOverPicture` uses. |
452
-
453
- Frames must all be one size. Video drops alpha unless `alpha` keeps it (WebM only). H.264 and the default ffmpeg settings need even sizes.
454
-
455
- ### Finished files: encoders, joins, sound, stream-copy cuts and layers
456
-
457
- `@margoengine/headless/ffmpeg-files` (Node only) works on finished files with the same ffmpeg, and `encodeWithFFmpeg`
458
- takes `layers`, other video or picture files laid over the frames inside the one encode (picture in picture), put
459
- through the same colour chain as a plain render; `layersOverPicture` lays the same layers over one rendered frame, so a
460
- still matches the video. `encoderArguments` gives a hardware H.264 encoder (NVENC, AMF, Quick
461
- Sync) or x264 the engine's colour handling; `joinVideos` joins chunks by stream copy, writing `avc3` when their
462
- parameter sets differ; `addSound` lays a sound file under a video without encoding the picture again; `copySpan` cuts
463
- a recorded span by stream copy, after checking it is exactly the frames it should be, re-tagged as an engine chunk.
464
-
465
- ```ts
466
- import { writeFile } from 'node:fs/promises';
467
- import { encodePNG } from '@margoengine/headless';
468
- import { encodeWithFFmpeg, layersOverPicture } from '@margoengine/headless/ffmpeg';
469
- import { addSound, checkSpan, copySpan, encoderArguments, joinVideos } from '@margoengine/headless/ffmpeg-files';
470
- import { encodeWav } from '@margoengine/audio/wav';
471
-
472
- // Two one-second chunks of plain frames (any renderFrames source works the same way), each a separate encode.
473
- const frames = (red: number) =>
474
- Array.from({ length: 30 }, () => ({ width: 128, height: 72, data: new Uint8Array(128 * 72 * 4).fill(red) }));
475
- const args = encoderArguments('x264', { preset: 'veryfast' }); // or 'nvenc', 'amf', 'qsv' where the GPU has one
476
- await encodeWithFFmpeg(frames(60), { output: 'part-1.mp4', args });
477
- await encodeWithFFmpeg(frames(200), { output: 'part-2.mp4', args });
478
-
479
- // A third chunk with the middle of part 1 playing in a box at the top left from 0.25 s for half a second, on a dark
480
- // plate where it does not fill the box.
481
- const layers = [
482
- {
483
- input: 'part-1.mp4',
484
- rect: { x: 0, y: 0, width: 64, height: 48 },
485
- start: 0.25,
486
- duration: 0.5,
487
- crop: [32, 18, 64, 36] as const,
488
- pad: '#202830',
489
- },
490
- ];
491
- await encodeWithFFmpeg(frames(120), { output: 'part-3.mp4', args, layers });
492
-
493
- // The same layers over frame 15 of part 3 as one picture: what the video shows at 0.5 s.
494
- await writeFile('frame-15.png', await encodePNG(frames(120)[15]));
495
- await layersOverPicture('frame-15.png', 'still-15.png', { fps: 30, frame: 15, layers });
496
-
497
- const entry = await joinVideos(['part-1.mp4', 'part-2.mp4', 'part-3.mp4'], 'film.mp4');
498
- await writeFile('tone.wav', encodeWav({ sampleRate: 48000, channels: [Float32Array.from({ length: 3 * 48000 }, (_, i) => 0.2 * Math.sin(i / 20))] }));
499
- await addSound('film.mp4', 'tone.wav', 'film-with-sound.mp4');
500
-
501
- // Part 2 starts on a key frame at 1 s, so it cuts out again without an encode.
502
- const check = await checkSpan('film.mp4', { start: 1, frames: 30, fps: 30 });
503
- if (!check.ok || !entry) throw new Error(check.reason ?? 'not H.264');
504
- await copySpan('film.mp4', 'part-2-again.mp4', { start: 1, frames: 30, fps: 30 });
505
- ```
506
-
507
- A layer file is read with the matrix and range it is tagged with. Untagged, it is read as ITU-R BT.709 at 720 lines or
508
- more and ITU-R BT.601 below, at TV range: ITU-T H.273 leaves untagged colour to the application, HD video (SMPTE ST
509
- 296, ST 274) is BT.709 and SD video is BT.601, while ffmpeg's scaler reads every untagged file as BT.601, so an HD
510
- clip came out up to 8 levels off on red and blue. An untagged JPEG is JFIF (ITU-T T.871): BT.601 at full range. A
511
- layer's `matrix` (`'bt709'`, `'bt601'`, `'bt2020'`) and `range` (`'tv'`, `'pc'`) replace the file's own. Each clip
512
- frame starts on the film frame nearest its own time (ffmpeg's `fps` filter, `round=near`), so a 24 fps clip in a 30
513
- fps film repeats one frame in four, evenly.
514
-
515
- `npm run test:real-ffmpeg` also runs these through the ffmpeg you have: the recording's sample times and key flags
516
- against ffprobe's (plain and fragmented MP4), a copied span decoding to the recording's own frames, an engine chunk and
517
- a copied span joined as `avc3` and decoding to both, sound added with the picture packets unchanged, every hardware
518
- encoder ffmpeg lists writing the engine's tags (an encoder with no device is reported, not passed), and layers shown
519
- only inside their window.
520
-
521
- | Export of `/ffmpeg-files` | What it does |
522
- | --- | --- |
523
- | `encoderArguments(encoder?, { quality?, preset? })` | Output arguments for `encodeWithFFmpeg`'s `args`: `encoder` `'x264'` (default, libx264), `'nvenc'`, `'amf'` or `'qsv'`, at constant `quality` 1 to 51 (default 20: x264's CRF, NVENC's CQ with `-preset p5 -tune hq` and no rate cap, AMF's QP on every frame type with `-quality quality`, Quick Sync's global quality). `preset` is x264's (`'ultrafast'` to `'placebo'`) or NVENC's (`'p1'` to `'p7'`). Every encoder gets the default's BT.709, TV range, sRGB transfer and left chroma chain, the same stream tags, the `H264_COLOUR_TAGS` VUI rewrite (whatever the encoder writes itself) and `+faststart`. |
524
- | `H264_COLOUR_TAGS` | The `h264_metadata` bitstream filter that writes the engine's colour into an H.264 stream's parameter sets: primaries 1, transfer 13, matrix 1, TV range, chroma location 0 (ITU-T H.273). |
525
- | `joinVideos(inputs, output, { sampleEntry?, ffmpeg?, signal? })` | Joins files end to end by stream copy (ffmpeg's concat demuxer, `-c copy`, `+faststart`). The files must share codec, size and frame rate, as chunks of one render do. `sampleEntry` `'auto'` (default) writes `avc3` when the inputs' H.264 parameter sets differ, since `avc1` keeps one set in its sample entry and such a join carries each file's own sets in band (ISO/IEC 14496-15), and `avc1` when they agree. Resolves the entry written, or undefined for inputs that are not H.264 MP4. |
526
- | `addSound(video, sound, output, { codec?, bitrate?, offset?, shortest?, ffmpeg?, signal? })` | Lays the first audio stream of `sound` (WAV, FLAC, MP3, AAC, anything ffmpeg reads) under `video` with the picture copied, replacing any sound it had. `codec` `'aac'` (default for MP4 and MOV), `'opus'` (default for WebM) or `'copy'`; `bitrate` 192000; `offset` seconds of picture before the sound starts (default 0); `shortest` ends the file with the shorter of the two (default false). |
527
- | `checkSpan(file, { start, frames, fps, timescale? })` | Whether `frames` frames from `start` of an MP4 or MOV file can be cut by stream copy so frame k sits at start + k / fps: H.264; a key frame within half a tick of `start` (ticks of `timescale`, default `mp4Timescale(fps)`); the next `frames` samples in decode order are exactly frames 0 to frames - 1, each within half a tick of its step, so none is missing and none is an open GOP's leading frame decoded after the key frame. Resolves `{ ok: true }` or `{ ok: false, reason }`. |
528
- | `copySpan(input, output, { start, frames, fps, timescale?, ffmpeg?, signal? })` | Cuts that span by stream copy (no decode, no encode): the picture alone, its VUI rewritten by `H264_COLOUR_TAGS`, at `timescale`, with `+faststart`, so it joins engine chunks with `joinVideos`. Rejects with code `'unsupported'` and the reason when `checkSpan` refuses it. |
529
- | `readVideoTrack(file)` | The first video track of an MP4 or MOV file: `codec` (the sample entry, such as `'avc1'`), `timescale`, `avcConfig` (the `avcC` body, H.264 only) and `samples`, each `{ time, key }` in decode order, from the sample tables and any movie fragments, with the edit list applied (ISO/IEC 14496-12). Reads box headers, `moov` and each `moof`, never the media data. Rejects with code `'unsupported'` when there is no video track. |
530
- | `mp4Timescale(fps)` | The MP4 track timescale ffmpeg gives an encode at a whole `fps` (the rate doubled until it reaches 10,000: 15,360 at 30 and 60 fps), the default timescale of a copied span. |
531
-
532
- Every tool writes through a temporary file beside `output` and renames it once ffmpeg succeeds, so a failure or an
533
- abort leaves no half file; a failure rejects with code `'failed'` and the end of ffmpeg's log in `cause`, and a missing
534
- ffmpeg with code `'unsupported'`. Paths go to ffmpeg as arguments, never through a shell.
535
-
536
- ## Comparing images
537
-
538
- `@margoengine/headless/compare` is for visual regression tests of your own scenes. `compareImages` takes RGBA pixels or PNG
539
- file bytes, made by any tool, and says whether a picture still matches its reference:
540
-
541
- ```ts
542
- import assert from 'node:assert/strict';
543
- import { readFile, writeFile } from 'node:fs/promises';
544
- import { encodePNG, readPixels, createHeadlessCanvas, installGPU } from '@margoengine/headless';
545
- import { compareImages } from '@margoengine/headless/compare';
546
- import { Engine, box, Camera } from '@margoengine/core';
547
- import { create } from 'webgpu';
548
-
549
- using installed = installGPU({ gpu: create([]) });
550
- const engine = await Engine.create(createHeadlessCanvas({ width: 512, height: 512 }), { backend: 'webgpu' });
551
- engine.createMesh().setGeometry(box());
552
- engine.render({ camera: new Camera({ position: [2, 2, 3], target: [0, 0, 0] }) });
553
-
554
- const result = await compareImages(await readPixels(engine), await readFile('reference.png'));
555
- if (!result.pass) await writeFile('difference.png', await encodePNG(result.image));
556
- assert.ok(result.pass, `${result.different} pixels changed, SSIM ${result.ssim}`);
557
- ```
558
-
559
- | Export | What it does |
560
- | --- | --- |
561
- | `compareImages(actual, reference, { threshold?, maxRatio?, minSSIM? })` | Both limits must hold for `pass`. `maxRatio` defaults to 0.001, `minSSIM` to 0.99, `threshold` to 2. Resolves the `pixelDiff` result with `image`, plus `pass` and `ssim`. |
562
- | `pixelDiff(a, b, { threshold?, image?, mask?, clusters? })` | `{ different, total, ratio, largest, mean, box }`. A pixel differs when a channel moves more than `threshold`, 0 to 255, default 2. Colours are compared premultiplied, so colour under full transparency does not count. `box` is the smallest `{ x, y, width, height }` holding every changed pixel, null when none changed. `image: true` adds changed pixels in red over a faded `a`; `mask: true` adds `mask`, one byte a pixel, 1 where it changed; `clusters: gap` adds `clusters`, one box per group of touching changed pixels, joining groups at most `gap` pixels apart. |
563
- | `ssim(a, b, { window?, sigma?, map? })` | Structural similarity as `{ score }`: 1 for identical images. `window` defaults to 11, `sigma` to 1.5, as published, on luma. `map: true` adds the score of each window. |
564
- | `decodePNG(bytes)` | A PNG file as RGBA pixels: every colour type and bit depth, interlaced or not, 16-bit samples cut to 8. A chunk with a bad CRC or a bit depth its colour type cannot have rejects. Colour profiles and gamma are ignored. All of PngSuite reads as Chromium reads it. |
565
-
566
- A pixel count sees how many pixels moved, and SSIM sees whether the picture looks different: a slight brightness change fails
567
- the first and passes the second, and a small hole does the opposite. Images of different sizes reject.
568
-
569
- `box` and `clusters` say where a picture changed, so a test can crop the difference or check that a change stayed inside
570
- the region it meant to touch:
571
-
572
- ```ts
573
- import assert from 'node:assert/strict';
574
- import { pixelDiff } from '@margoengine/headless/compare';
575
-
576
- const width = 64, height = 32;
577
- const before = { width, height, data: new Uint8Array(width * height * 4).fill(255) };
578
- const after = { width, height, data: before.data.slice() };
579
- for (const [x, y] of [[10, 4], [11, 5], [40, 20]]) after.data.set([255, 0, 0, 255], (y * width + x) * 4);
580
-
581
- const diff = pixelDiff(before, after, { mask: true, clusters: 2 });
582
- assert.deepEqual(diff.box, { x: 10, y: 4, width: 31, height: 17 });
583
- assert.deepEqual(diff.clusters, [{ x: 10, y: 4, width: 2, height: 2 }, { x: 40, y: 20, width: 1, height: 1 }]);
584
- assert.equal(diff.mask![5 * width + 11], 1);
585
- ```
586
-
587
- ## Look checks for rendered shots
588
-
589
- `@margoengine/headless/look` reviews rendered frames before a person does: pure functions over 8-bit frames, float
590
- frames and grey masks, each giving a value and a pass against a bound. `checkShot` runs them on every probe frame of a
591
- shot rendered by the shot tool (`tools/shot`, [docs/shots.md](../../docs/shots.md)), with the bounds of the shot file's
592
- `lookBounds`, and gives one contact sheet and one table, so a shot is reviewed as one page. Nothing here needs a GPU.
593
-
594
- ```ts
595
- import { mkdir, readFile, writeFile } from 'node:fs/promises';
596
- import { join } from 'node:path';
597
- import { encodePNG } from '@margoengine/headless';
598
- import { checkShot } from '@margoengine/headless/look';
599
-
600
- // A night sky with 16 grey levels where 8-bit output has 64: the banding a short must not ship.
601
- const width = 270,
602
- height = 480,
603
- data = new Uint8Array(width * height * 4);
604
- for (let y = 0; y < height; y++)
605
- for (let x = 0; x < width; x++) {
606
- const v = 20 + Math.floor((y / height) * 16) * 4;
607
- data.set([v, v, v + 10, 255], (y * width + x) * 4);
608
- }
609
- await mkdir('shot/probes', { recursive: true });
610
- await writeFile('shot/probes/opening.png', await encodePNG({ width, height, data }));
611
-
612
- // The shot tool writes manifest.json beside the frames; its header carries the shot file's lookBounds.
613
- const manifest = {
614
- id: 'night-sky',
615
- header: { lookBounds: { banding: 1, lights: [0, 1] as [number, number] } },
616
- probes: { opening: { frame: 0, file: 'probes/opening.png' } },
617
- };
618
- const report = await checkShot({ manifest, read: (path) => readFile(join('shot', path)) });
619
- await writeFile('shot/look.md', report.markdown);
620
- await writeFile('shot/look.json', JSON.stringify(report.json, null, 2));
621
- await writeFile('shot/look.png', await encodePNG(report.sheet));
622
- console.log(report.pass ? 'looks right' : 'look checks failed: see shot/look.md and shot/look.png');
623
- ```
624
-
625
- The checks, by their `lookBounds` name. A number bound is the largest value that passes, `[low, high]` a range; a
626
- name left out keeps the default below. A check runs when its inputs are there; one named in `lookBounds` that cannot run,
627
- or a name no check has, fails as `not run`, never a pass. A check that ran over a mask with no pixels in it (a
628
- `sky` mask of a frame with no sky in view) passes with `empty` set, `'0 sky pixels'` for `skyClip`, and the table says
629
- `pass (measured 0 sky pixels)`, so that pass is never silent.
630
-
631
- With no `sky` mask, `skyClip` measures inside a `sky-coverage` mask when the probe has one: the pixels
632
- `@margoengine/sky` drew (its `coverage` option), which the shot tool reads from the page's sky. So the flames and a
633
- kettle's glint in an interior are not counted as sky. Only `skyClip` reads it; `grain`, `lights` and `horizonSeam`
634
- keep the `sky` mask or the whole frame. Each `skyClip` row's `mask` says what it measured inside (`sky`,
635
- `sky-coverage` or `frame`), and look.md lists it under the table:
636
-
637
- ```ts
638
- import { checkProbe, lookReport } from '@margoengine/headless/look';
639
-
640
- // An interior: a clipped flame in the lower half, the window's sky in the top-left corner.
641
- const width = 40,
642
- height = 40,
643
- data = new Uint8Array(width * height * 4),
644
- sky = new Uint8Array(width * height);
645
- for (let y = 0; y < height; y++)
646
- for (let x = 0; x < width; x++) {
647
- const v = y >= 20 && x >= 10 && x < 30 ? 255 : 60;
648
- data.set([v, v, v, 255], (y * width + x) * 4);
649
- sky[y * width + x] = x < 12 && y < 12 ? 255 : 0;
650
- }
651
- const frame = { width, height, data };
652
- const rows = checkProbe({ name: 'hearth', frame, masks: { 'sky-coverage': { width, height, data: sky } } }, { skyClip: 0.5 });
653
- const clip = rows.find((row) => row.check === 'skyClip')!;
654
- console.log(clip.value, clip.mask); // 0 'sky-coverage': the flame is not sky
655
- console.log(lookReport([{ name: 'hearth', frame, results: rows }]).markdown.split('Masks:')[1]);
656
- ```
657
-
658
- | Name | Value | Default bound | Needs |
659
- | --- | --- | --- | --- |
660
- | `skyClip` | % of sky pixels with a channel at 254 or more | 0.5 | the frame; the `sky` mask if there is one, else `sky-coverage` if there is one |
661
- | `grain` | noise standard deviation in 8-bit codes (Immerkaer's estimator, blind to ramps) | 1.5 | the frame; measured in the `sky` mask if there is one |
662
- | `speckle` | pixels 24 codes above or below all eight neighbours, per million | 50 | the frame |
663
- | `banding` | % of pixels in flat runs of 6 or more split by a step of 1.5 to 12 codes, a skipped code | 1 | the frame |
664
- | `flat` | % of pixels at the centre of a constant 65 x 65 window, black and white left out | 5 | the frame |
665
- | `blocks` | % of the frame in tiles with steps repeating at the 8-pixel froxel pitch | 1 | the frame |
666
- | `horizonSeam` | luma step at the analytic horizon beyond its surroundings, codes (median over the columns with sky just above the line) | 6 | the camera's `viewProjection` and the `sky` mask (an interior's line runs across walls, not a horizon) |
667
- | `waterSeam` | the same at the water line, the top edge of the `water` mask | 6 | the `water` mask |
668
- | `lights` | bright discs (moon, sun, lamps), against the lights the scene shows; a disc counts when its core clips (luma 250 or more) or a ring just outside it is below 0.7 of the level, so sunlit cumulus puffs that shade into their cloud do not | [0, 1] | the frame; the `sky` mask if there is one |
669
- | `foamEdges` | % of strong foam edges 2 pixels wide or less | 35 | the `foam` mask |
670
- | `crush` | % of pixels at black (channels 2 or less) outside the `dark` mask | 0.5 | the frame |
671
- | `flicker` | largest jump of the mean luma off its trend, codes | 0.75 | `still`: 3 or more frames of a still camera |
672
- | `shimmer` | % of pixels jumping more than 6 codes off their own trend | 0.5 | `still` frames |
673
- | `nan` | pixels with a NaN or infinite channel | 0 | `hdr`: the float frame |
674
- | `backends` | mean FLIP of the WebGPU frame against the WebGL2 compatibility layer's | 0.03 | `compat`: the compat frame |
675
- | `reference` | mean FLIP against a 16-sample reference render | 0.05 | `reference`: the reference frame |
676
- | `penumbra` | T1: noise standard deviation inside the shadow penumbra, codes | 0.7 | the `penumbra` mask |
677
- | `stairs` | T3: % of strong edges (a step over 24 codes) that are one pixel stair steps: a step with no value between its two plateaus in the 3 x 4 window of its two pixels (nothing further than a tenth of the range from both ends), on an edge that is not straight along a pixel row or column | 1 | the frame |
678
- | `colourEdges` | T7: the same on the a* and b* planes: colour edges 4:2:0 smears | 10 | the frame |
679
- | `chromaSmear` | T7: percent of pixels whose colour moves by CIE76 over 6 when the frame is cut to 4:2:0 chroma (BT.709 Y'CbCr, 2 x 2 averages, bilinear read back), no encoder needed | 2 | the frame |
680
- | `shimmerMoving` | T4: % of pixels off by over 6 codes once the camera motion is undone | 0.5 | `moving`: the next frame and each pixel's motion (`reprojectionMotion` makes it from depth and the two view-projections) |
681
- | `motionBlur` | T8: % of edge centres of pixels moving over 8 pixels a frame whose edge is narrower than half their travel | 5 | `moving` |
682
- | `silhouette` | T5: % of the subject's outline with 15 L* or more against what is behind | [80, 100] | the `subject` mask |
683
- | `silhouetteShape` | T5: % of the subject (at 320 x 180, three L* values) in one value | [70, 100] | the `subject` mask |
684
- | `bounce` | T6: shadowed ground luminance as a % of the lit ground's, linear light, each over its mask's interior (`GROUND_INSET`, 1/360 of the shorter side, in from every edge, where the frame mixes both sides) | [10, 35] | the `lit` and `shadow` masks |
685
- | `shadowTint` | T6: lit b* minus shadow b*, points: shadows cooler than the sun, over the masks' interiors as `bounce` | [3, 100] | the `lit` and `shadow` masks |
686
- | `nightLuma`, `nightPeak` | T7: mean luma, and the luma of the brightest 1%, of a night frame | [24, 255], [180, 255] | the frame; run only when a shot names them |
687
-
688
- | Export | What it does |
689
- | --- | --- |
690
- | `checkShot({ manifest, read, signal?, pitch?, pixelsPerDegree?, thumbWidth?, columns?, title? })` | Reads each probe of a shot tool manifest (`probes.<name>.file`, `aovs`, and the optional `reference`, `compat`, `still` PNGs, `hdr` raw RGBA float32 file and `viewProjection`) through `read(path)`, runs `checkProbe` with `header.lookBounds` under `header.lookFamily`'s bounds (and `moving: { next, motion }` per probe: a PNG and a raw float32 file of x, y per pixel), a probe's own `probes.<name>.lookBounds` in their place for the checks it names, and resolves `lookReport`. `signal` stops it between probes. |
691
- | `checkProbe(probe, bounds?, { pitch?, pixelsPerDegree?, family? })` | The rows of one probe `{ name, frame, masks?, hdr?, reference?, compat?, viewProjection?, still?, moving? }`. Masks are one byte or RGBA per pixel, 128 and above inside: `sky`, `water`, `foam`, `dark`, `penumbra`, `subject`, `lit` and `shadow` are read. `family` names a look family (below). `pitch` defaults to 8, `pixelsPerDegree` to 67. |
692
- | `lookReport(probes, { thumbWidth?, columns?, title? })` | `{ pass, json, markdown, sheet }` of `{ name, frame, results }` probes: the table failures first, and a contact sheet of thumbnails (default 270 wide, 4 across) framed green or red and labelled with what failed, each reference check's FLIP map beside its frame. |
693
- | `skyClip`, `grain`, `speckle`, `banding`, `flat`, `blocks`, `horizonSeam`, `waterSeam`, `lights`, `foamEdges`, `crush`, `flicker`, `shimmer`, `nan` | Each check alone, `(frame, options)` with its `bound` and the options above (`flicker` and `shimmer` take the frames), giving `{ check, value, bound, pass, unit, detail }`. `lights` adds `discs` with their centres and radii. |
694
- | `flip(test, reference, { pixelsPerDegree?, map? })` | FLIP (Andersson et al. 2020): the difference a viewer sees flipping between two frames, 0 to 1 per pixel, as `{ mean, p50, p95, p99, max }` and the per-pixel `map` with `map: true`. 67 pixels per degree is a 4K monitor at 0.7 m; a phone at 30 cm showing 1080 pixels across 6.5 cm is about 87. `difference(frame, other, 'reference' or 'backends')` is its check row. |
695
- | `horizonLine(viewProjection, width, height)`, `maskTopEdge(mask)` | The row per column of the horizon of horizontal planes (column-major view-projection, WebGPU clip space) and of a mask's top edge. NaN where there is none. |
696
- | `stairs`, `colourEdges`, `chromaSmear`, `penumbra`, `shimmerMoving`, `motionBlur`, `silhouette`, `silhouetteShape`, `bounce`, `shadowTint`, `nightLuma`, `nightPeak`, `reprojectionMotion(depth, viewProjection, nextViewProjection, width, height)`, `depthFromDistance(distance, eye, viewProjection, width, height, { water, plane, far })` (NDC depth from each pixel's distance to the eye, for `reprojectionMotion`; pixels with no distance meet the sea plane where `water` is 128 or more, or are `far` away), `detailKeptFloor(family)` (T7: 0.5, and 0.6 for `animatedFeature`, as `LOOK_FAMILY_DETAIL_KEPT`) | The clean-frame checks (below), each alone with its `bound`; `reprojectionMotion` gives the motion of every pixel of a still world seen by a moving camera. |
697
- | `LOOK_FAMILY_BOUNDS`, `LOOK_FAMILY_NAMES`, `familyBounds(name)` | The look families and their bounds. |
698
- | `luma(frame)`, `lookBound(bound)`, `LOOK_CHECKS` | BT.709 luma on 0 to 255, a bound as `[low, high]`, and each check's default bound, unit and meaning. |
699
-
700
- **Clean frames and look families.** The clean-frame checks are the look bar of the animated-feature film (T1 to T8, private roadmap section 3): no grain, banding, stairs or shimmer, shapes that read, bounce light in the shadows, colour that survives YouTube's 4:2:0 H.264 and motion that is blurred. `checkProbe(probe, bounds, { family: 'animatedFeature' })` (or `lookFamily: "animatedFeature"` in a shot file) holds every check the probe can run to the family's bound: grain 0.5 codes, penumbra 0.7, speckle 5 ppm, banding 0.2%, stairs 1%, still shimmer 0.1% and flicker 0.3, `shimmerMoving` 0.5%, crush 0.1%, the reference FLIP 0.04, plus the ranges above. A check whose input the probe lacks is left out under a family (a shot that names it in `lookBounds` still fails it as missing); a mask that marks no pixel counts as lacking, so a frame with no subject or no shaded ground runs no `silhouette` or `bounce`, and a shot's own `lookBounds` win by name. `natural` keeps every default. `stairs` and `colourEdges` read the frame alone. A step was once judged against the climb along its own row, which misread an antialiased edge near a pixel axis (one pixel of coverage 0.1 per row is a tenth of the climb on one side and nine tenths on the other): a 16 sample per pixel render of the storm-light shot read 15% `stairs`. They now look for a value between the plateaus around the step; on that shot msaa 1 reads 5.70% over the whole frame (5.98% on the crop in `tests/fixtures/look-real`, against 30.6% by the old test), msaa 4 at supersample 1, 1.5 and 2 read 0.10, 0.00 and 0.01%, and the 16 sample reference 0.00%. The flood draft shots (msaa 1, supersample 1) read 2.7 to 22.7%, which is real aliasing: they are not rendered at the film setting.
701
-
702
- ```ts
703
- import { checkProbe, familyBounds } from '@margoengine/headless/look';
704
-
705
- // A dark disc on pale haze with a resolved (antialiased) edge: the family's stairs bound is 1%.
706
- const size = 48,
707
- data = new Uint8Array(size * size * 4);
708
- for (let y = 0; y < size; y++)
709
- for (let x = 0; x < size; x++) {
710
- const d = Math.hypot(x - 24, y - 24),
711
- v = Math.round(210 - 180 * Math.min(1, Math.max(0, 12.5 - d)));
712
- data.set([v, v, v, 255], (y * size + x) * 4);
713
- }
714
- const rows = checkProbe({ name: 'disc', frame: { width: size, height: size, data } }, {}, { family: 'animatedFeature' });
715
- const stairs = rows.find((row) => row.check === 'stairs')!;
716
- console.log(familyBounds('animatedFeature').stairs, stairs.value, stairs.pass); // [0, 1] 0 true
717
- ```
718
-
719
- Default bounds are starting values for a 1080 x 1920 short; a scene kit or shot file sets its own. FLIP keeps about 30
720
- float planes of the frame's size while it runs, the other checks one or two. Frames and masks of different sizes
721
- reject with a RangeError.
722
-
723
- ## JPEG, WebP and EXR files
724
-
725
- `@margoengine/headless/formats` writes the pixels you read as the files previews and HDR captures need. Nothing here
726
- loads a codec: JPEG and lossless WebP are written in plain code, so they work in Node, a worker and a page.
727
-
728
- ```ts
729
- import { writeFile } from 'node:fs/promises';
730
- import { readPixels, createHeadlessCanvas, installGPU } from '@margoengine/headless';
731
- import { encodeEXR, encodeJPEG, encodeWebP, readTexture } from '@margoengine/headless/formats';
732
- import { Engine, box, Camera } from '@margoengine/core';
733
- import { PostStack } from '@margoengine/post/stack';
734
- import { Bloom } from '@margoengine/post/bloom';
735
- import { create } from 'webgpu';
736
-
737
- using installed = installGPU({ gpu: create([]) });
738
- const engine = await Engine.create(createHeadlessCanvas({ width: 512, height: 512 }), { backend: 'webgpu' });
739
- engine.createMesh().setGeometry(box());
740
- engine.render({ camera: new Camera({ position: [2, 2, 3], target: [0, 0, 0] }) });
741
- const stack = PostStack.attach(engine, [new Bloom({ strength: 0.6 })]);
742
- engine.render({ camera: new Camera({ position: [2, 2, 3], target: [0, 0, 0] }) });
743
-
744
- const pixels = await readPixels(engine);
745
- await writeFile('preview.jpg', encodeJPEG(pixels, { quality: 85 }));
746
- await writeFile('preview.webp', await encodeWebP(pixels));
747
- await writeFile('frame.exr', await encodeEXR(await readTexture(engine, stack.sceneTexture!), { type: 'float' }));
748
- ```
749
-
750
- | Export | What it does |
751
- | --- | --- |
752
- | `encodeJPEG(pixels, { quality?, subsampling?, background? })` | A baseline JPEG. `quality` is 1 to 100, default 90, scaled as other JPEG tools scale it. `subsampling` is `'420'` (default, smaller) or `'444'` (sharper colour edges). JPEG has no alpha, so pixels are laid over `background`, default white. |
753
- | `encodeWebP(pixels, { quality? })` | Unset `quality`: lossless WebP, the same pixels back, with alpha, in any runtime. `quality` 0 to 1: lossy WebP through the runtime's own encoder, so it needs `OffscreenCanvas` and WebP support (a browser or worker). Rejects, never gives a PNG in its place. |
754
- | `encodeEXR(hdr, { type?, signal? })` | Float RGBA as an uncompressed OpenEXR file. `type` is `'half'` (default) or `'float'`. Written by `@margoengine/environment/exr-write`, an optional peer loaded on first use. |
755
- | `readTexture(engine, texture, { signal? })` | Reads an `rgba16float` or `rgba32float` texture with `COPY_SRC` usage to `{ width, height, data }` float pixels. `stack.sceneTexture` from `@margoengine/post/stack` is the linear frame before tone mapping, where values go over 1. |
756
- | `linearPixels(pixels)` | Undoes the sRGB curve of display pixels, for an EXR of an 8-bit frame. Alpha stays linear. |
757
-
758
- The engine's own output is tone-mapped sRGB, so an EXR made from `readPixels` holds display values, not scene light.
759
- For a capture with true highlights, read `stack.sceneTexture`. Images are at most 65,535 pixels wide for JPEG and 16,384 for WebP.
760
-
761
- The errors are listed at [margoengine.com/errors#headless](https://margoengine.com/errors#headless).
762
-
763
- ### Headless stage error callback
764
-
765
- `createHeadlessStage` accepts `onError` as a function; its default is
766
- `undefined`. Pass an error callback or omit the option. Other types throw a
767
- TypeError naming `onError`, both accepted choices and the arguments help link,
768
- before installing GPU globals or creating an engine.
1
+ # @margoengine/headless
2
+
3
+ Render a scene with no page and get PNG bytes back: server thumbnails, an asset pipeline, automated tests. Core draws to
4
+ a stand-in canvas, and the frame stays readable because nothing presents it.
5
+
6
+ Margo has no video encoder of its own. Video uses WebCodecs in a browser or worker, and in Node the `ffmpeg` you have installed, so rendering to MP4 in Node means installing ffmpeg first.
7
+
8
+ This package ships no WebGPU binding, because one is a large download that runs code when installed. Your app chooses
9
+ one and passes its `gpu` in. It can be any object with `requestAdapter`: `create([])` from a Node binding such as
10
+ [`webgpu`](https://www.npmjs.com/package/webgpu) (`npm install webgpu`; every example here runs on version 0.6.2 in Node, on the GPU the machine has), or `navigator.gpu` in a browser or worker.
11
+
12
+ ```ts
13
+ import { writeFile } from 'node:fs/promises';
14
+ import { Camera, Engine, box, PbrMaterial } from '@margoengine/core';
15
+ import { createHeadlessCanvas, installGPU, toPNG } from '@margoengine/headless';
16
+ import { create } from 'webgpu';
17
+
18
+ const gpu = create([]);
19
+ using installed = installGPU({ gpu });
20
+ const canvas = createHeadlessCanvas({ width: 512, height: 512 });
21
+ const engine = await Engine.create(canvas, { backend: 'webgpu' });
22
+ engine.createMesh().setGeometry(box()).setMaterial(new PbrMaterial({ color: '#84d6bd' }));
23
+ engine.render({ camera: new Camera({ position: [2, 2, 3], target: [0, 0, 0] }) });
24
+ await writeFile('cube.png', await toPNG(engine));
25
+ engine.dispose();
26
+ ```
27
+
28
+ | Export | What it does |
29
+ | --- | --- |
30
+ | `installGPU({ gpu, globals? })` | Sets `navigator.gpu` and the `GPU*` flag globals a runtime lacks; adds `getPreferredCanvasFormat` (`'rgba8unorm'`) if the binding has none. `globals` defaults to none. `dispose()` or `using` restores everything. |
31
+ | `createHeadlessCanvas({ width, height })` | The canvas to pass to `Engine.create`. Both sizes are required. Set `canvas.width` and `canvas.height` to resize; the next `engine.render()` uses them. |
32
+ | `readPixels(engine, { signal? })` | The last frame as `{ width, height, data }`: RGBA, straight alpha, top row first. |
33
+ | `createFrameReader(engine, { depth?, signal? })` | From `@margoengine/headless/frames`: reads every frame of a film without waiting for each one. See below. |
34
+ | `toPNG(engine, { signal? })` | The last frame as PNG file bytes. |
35
+ | `encodePNG(pixels)` | RGBA pixels as PNG file bytes. Rejects with a `RangeError` when the size is not a whole number from 1 or `data` is not `width * height * 4` bytes; `encodeJPEG` and `encodeWebP` refuse the same. |
36
+
37
+ Call `engine.render()` yourself: `engine.start()` needs `requestAnimationFrame`, which Node does not have. `createStage`
38
+ needs a page; `createHeadlessStage` below is its server version.
39
+
40
+ ### Reading every frame of a film
41
+
42
+ `readPixels` waits for the GPU to finish the frame it was given before it returns. `createFrameReader` from
43
+ `@margoengine/headless/frames` keeps up to `depth` copies in flight instead, so the next frame is drawn while earlier
44
+ ones are still being read. Call `push()` once after each `engine.render()`: it copies that frame and resolves to the
45
+ oldest held frame once `depth` are held. `drain()` gives the rest. The frames and their order are the same as
46
+ `readPixels` after every render.
47
+
48
+ ```ts
49
+ import { writeFile } from 'node:fs/promises';
50
+ import { Camera, Engine, box, PbrMaterial } from '@margoengine/core';
51
+ import { createHeadlessCanvas, encodePNG, installGPU, type HeadlessPixels } from '@margoengine/headless';
52
+ import { createFrameReader } from '@margoengine/headless/frames';
53
+ import { create } from 'webgpu';
54
+
55
+ const gpu = create([]);
56
+ using installed = installGPU({ gpu });
57
+ const canvas = createHeadlessCanvas({ width: 320, height: 180 });
58
+ const engine = await Engine.create(canvas, { backend: 'webgpu' });
59
+ engine.createMesh().setGeometry(box()).setMaterial(new PbrMaterial({ color: '#84d6bd' }));
60
+
61
+ const frames: HeadlessPixels[] = [];
62
+ {
63
+ using reader = createFrameReader(engine, { depth: 3 });
64
+ for (let i = 0; i < 12; i++) {
65
+ const angle = i / 12;
66
+ engine.render({ camera: new Camera({ position: [3 * Math.sin(angle), 2, 3 * Math.cos(angle)], target: [0, 0, 0] }) });
67
+ const frame = await reader.push();
68
+ if (frame) frames.push(frame);
69
+ }
70
+ for await (const frame of reader.drain()) frames.push(frame);
71
+ }
72
+ if (frames.length !== 12) throw new Error(`read ${frames.length} frames`);
73
+ await writeFile('last.png', await encodePNG(frames[11]));
74
+ engine.dispose();
75
+ ```
76
+
77
+ | Option or member | What it does |
78
+ | --- | --- |
79
+ | `depth` | Frames held at once, 1 to 16. Default 3. 1 waits for each frame. Each held frame owns one buffer of `height` rows of `width * 4` bytes rounded up to 256. |
80
+ | `signal` | Disposes the reader; waiting reads reject with the reason. Default none. |
81
+ | `push()` | Copies the frame just rendered. Resolves to the oldest held frame once `depth` are held, else `undefined`. |
82
+ | `drain()` | An async iterator over the frames still held, oldest first. |
83
+ | `pending` | Frames copied and not yet handed out. |
84
+ | `dispose()` | Frees the buffers; held frames are lost. Also `using`. |
85
+
86
+ A reader makes `depth` buffers for a whole film, and `readPixels` keeps one buffer on the canvas between reads of one
87
+ size; both free them on a resize.
88
+
89
+ ### The same frames on every run
90
+
91
+ `readPixels` reads the frame texture this package owns, after the GPU has finished it, so a film drawn on
92
+ `createHeadlessCanvas` gives the same bytes on every run from its first frame, alone or beside another process on the
93
+ GPU, on WebGPU and the WebGL2 layer (`packages/sky/test/rain-frames-check.mjs`: a 90-frame rain shot with the
94
+ Bruneton sky, clouds, AgX and shadows, byte for byte in four fresh browsers). A page that reads its real canvas
95
+ instead must read it in the same task as `engine.render()`, as `capture` in `@margoengine/exporters` does: after an
96
+ `await`, `drawImage`, `toDataURL` and `createImageBitmap` of a WebGPU canvas give the last frame the browser showed,
97
+ which lags by a number of frames that differs from run to run (65 of 90 frames differed between two runs read that
98
+ way). On the WebGL2 layer the layer loads its compute part before `requestDevice` answers (KB-COMPAT-FIRSTTASK1 in
99
+ docs/known-bugs.md), so a page canvas read in the task of the first render shows that frame, as on WebGPU.
100
+
101
+ ### Film frames: anti-aliasing and motion blur from sub-frames
102
+
103
+ `renderAccumulated` from `@margoengine/headless/accumulate` renders each frame `samples` times, each render at its own
104
+ time inside the open shutter and with its own sub-pixel offset, and averages them in linear light with an `Accumulate`
105
+ stage from `@margoengine/post/accumulate` (an optional peer, loaded on first use when no stage is given). The tone curve
106
+ is applied once, to the average, so a bright edge or a fast highlight keeps its brightness instead of the dark smear
107
+ an average of 8-bit frames gives. Everything that moves blurs, since each render is the scene at its own time:
108
+ cameras, skinned and morphed meshes, particles, wind. Each frame is read back once, after its last render.
109
+
110
+ ```ts
111
+ import { writeFile } from 'node:fs/promises';
112
+ import { Camera, Engine, box, PbrMaterial } from '@margoengine/core';
113
+ import { createHeadlessCanvas, encodePNG, installGPU } from '@margoengine/headless';
114
+ import { renderAccumulated } from '@margoengine/headless/accumulate';
115
+ import { encodeEXR } from '@margoengine/headless/formats';
116
+ import { Accumulate } from '@margoengine/post/accumulate';
117
+ import { PostStack } from '@margoengine/post';
118
+ import { Tonemap } from '@margoengine/tonemap';
119
+ import { create } from 'webgpu';
120
+
121
+ const gpu = create([]);
122
+ using installed = installGPU({ gpu });
123
+ const engine = await Engine.create(createHeadlessCanvas({ width: 320, height: 180 }), { backend: 'webgpu' });
124
+ const cube = engine.createMesh().setGeometry(box()).setMaterial(new PbrMaterial({ color: '#84d6bd' }));
125
+ const accumulate = new Accumulate();
126
+ PostStack.attach(engine, [accumulate, new Tonemap()]);
127
+ const camera = new Camera({ position: [0, 1.5, 4], target: [0, 0, 0] });
128
+
129
+ let frames = 0;
130
+ for await (const frame of renderAccumulated(engine, {
131
+ frames: 4,
132
+ fps: 24,
133
+ samples: 16, // renders per frame
134
+ shutter: 0.5, // a 180 degree shutter
135
+ camera,
136
+ accumulate,
137
+ update: ({ time }) => {
138
+ camera.position = [4 * Math.sin(time * 6), 1.5, 4 * Math.cos(time * 6)];
139
+ },
140
+ })) {
141
+ if (frame.data.length !== 320 * 180 * 4) throw new Error('wrong frame size');
142
+ await writeFile(`film_${frame.index}.png`, await encodePNG(frame));
143
+ frames++;
144
+ }
145
+ // output: 'linear' gives the mean in linear light, for an EXR.
146
+ for await (const frame of renderAccumulated(engine, { frames: 1, samples: 8, camera, accumulate, output: 'linear' }))
147
+ await encodeEXR(frame);
148
+ if (frames !== 4 || !cube) throw new Error(`rendered ${frames} frames`);
149
+ engine.dispose();
150
+ ```
151
+
152
+ | Option | What it does |
153
+ | --- | --- |
154
+ | `frames` | How many frames, a whole number from 1. Required. |
155
+ | `fps` | Frames per second. Default 30. |
156
+ | `samples` | Renders per frame, 1 to 4096. Default 16. 1 renders each frame once, with no offset. |
157
+ | `shutter` | Share of the frame interval the shutter is open, 0 to 1. Default 0.5 (180 degrees); 0 is a still instant. |
158
+ | `shutterPhase` | `'start'` (open from the frame's time), `'center'` or `'end'`. Default `'start'`. |
159
+ | `filter`, `filterWidth` | Pixel filter the offsets are drawn from: `'blackman-harris'` (default), `'gaussian'` or `'box'`; width in pixels, default 2 (1 for `'box'`). |
160
+ | `startFrame` | Number of the first frame, for a span of a longer film after a seek with `subFrameSteps`. Default 0. |
161
+ | `seed`, `pattern` | The sample pattern's seed (default 0); `'fixed'` (default) repeats it every frame so still edges do not shimmer, `'per-frame'` draws a new one. |
162
+ | `camera` | Camera to render through; it is never modified. Default the engine's camera. |
163
+ | `update(timing)` | Runs before each render with that render's `time`, `delta`, `index` (frame), `sample` and `samples`. May be async. |
164
+ | `accumulate` | The `Accumulate` stage in your PostStack, before `Tonemap`. Default one attached alone and disposed at the end. |
165
+ | `output` | `'display'` (default): 8-bit RGBA as `readPixels` reads it. `'linear'`: float RGBA of the mean, for `encodeEXR`. |
166
+ | `signal` | Stops between renders or during readback; the iterator rejects with the reason. |
167
+
168
+ `renderFrames` from `@margoengine/headless/video` takes the same `samples`, `shutter` and filter options and runs
169
+ `renderAccumulated` when `samples` is above 1 or `shutter` above 0, so `renderCutscene` and any film loop get motion
170
+ blur by adding two options; with neither it renders each frame once, exactly as before.
171
+
172
+ `subFrames(options)` is the same schedule without rendering: each render's `frame`, `sample`, `time`, `delta`, `offset`
173
+ and `last`, pure and repeatable. The engine's clocks start at 0 and the deltas keep them on each render's time (a render
174
+ before 0, with a `'center'` or `'end'` shutter on frame 0, moves them 0). `startFrame` starts a span of a longer film,
175
+ and `subFrameSteps({ ...options, startFrame })` lists the deltas of every render before it, for
176
+ `seek(engine, seconds, { steps })` in `@margoengine/cutscene/seek`: the span then gives the whole film's renders, bit
177
+ for bit. Times are the middles of `samples` equal slices of the open shutter, in order, so the
178
+ deltas add up to the frame interval; offsets are Owen-scrambled Sobol points (Burley 2020) mapped through the filter
179
+ (filter importance sampling, Ernst, Stamminger and Greiner 2006) and shuffled against the time order.
180
+
181
+ - **Checked on a real GPU** (`npm run test:gpu:accumulate -w @margoengine/headless`, WebGPU and the WebGL2 layer): an
182
+ orthographic edge at x = 20.3 px reads 0.297 of the lit level in linear light at 64 box samples (one sample: 0 or 1);
183
+ at radiance 4 the edge pixel equals a still lit to that share (244 against 244), far from the mean of the two
184
+ display values (76); two runs are bit-identical; an 8 px strip moving 32 px a frame under a 180 degree shutter
185
+ spreads over 24 px, keeps its energy (1.000) and centres at 44.03 px against 44 for mid-shutter; an abort rejects
186
+ with its reason.
187
+ - **Limits.** Effects with their own frame history (TAA's jitter, SSGI multi-bounce) advance once per render, so turn
188
+ TAA's jitter off (`velocityOnly`). Simulations see the sub-frame deltas, so a film repeats exactly for fixed `fps`,
189
+ `samples`, `shutter` and phase. Cost is `samples` renders a frame. WebGPU and the WebGL2 layer; on the layer's
190
+ half-float tier the sum is float16.
191
+
192
+ ## A stage without a page
193
+
194
+ `@margoengine/headless/stage` gives server thumbnails the same short setup as a page. `createHeadlessStage` returns a real
195
+ `Stage`, so its methods and the stage's feature entries work as they do on a page. It needs `@margoengine/stage`, an optional
196
+ peer:
197
+
198
+ ```ts
199
+ import { writeFile } from 'node:fs/promises';
200
+ import { createHeadlessStage } from '@margoengine/headless/stage';
201
+ import { addSky } from '@margoengine/stage/sky';
202
+ import { create } from 'webgpu';
203
+
204
+ const gpu = create([]);
205
+ using stage = await createHeadlessStage({ gpu, width: 640, height: 360 });
206
+ stage.box({ color: '#84d6bd' });
207
+ await addSky(stage);
208
+ stage.fit();
209
+ await writeFile('thumbnail.png', await stage.toPNG());
210
+ ```
211
+
212
+ | Export | What it does |
213
+ | --- | --- |
214
+ | `createHeadlessStage({ width, height, gpu?, globals?, onError?, transparent?, ...engineOptions })` | Installs the GPU and creates the engine on a stand-in canvas. `width` and `height` are required. `gpu` defaults to `navigator.gpu`, `globals` to none. `transparent` defaults to false; true leaves the background clear (below). The backend is always WebGPU. Stages alive at once must share one `gpu`; the globals are restored when the last is disposed. |
215
+ | `stage.toPNG({ signal? })`, `stage.readPixels({ signal? })` | Draws a frame and gives it as PNG bytes or RGBA pixels. |
216
+ | `stage.step(delta?)` | Runs `onTick` and `engine.onFrame` callbacks, then draws a frame that advances plugins by `delta` seconds, 0 to 1 (default 0); a delta outside that range, or a step from inside a step, throws before any callback runs. `stage.resize(width, height)` takes whole numbers from 1. Nothing runs by itself: there are no camera controls and no frame loop. |
217
+ | `stage.resize(width, height)` | Sets the image size for the next frame. |
218
+
219
+ `stage.onTick` and `stage.engine.onFrame` both run on `step`, so a package that drives itself from `onFrame` advances here too. To load a model
220
+ with `addGLTF`, pass an absolute URL, since Node has no page address to resolve against.
221
+
222
+ ### Graphics over footage
223
+
224
+ `transparent: true` draws no background: `readPixels` gives alpha 0 where nothing was drawn, 255 on the graphics and
225
+ the coverage on their edges, as straight alpha, so titles, maps and lower thirds can be laid over recorded video
226
+ (`encodeVideo` and `encodeWithFFmpeg` keep it with `alpha: true`). It attaches `TransparentCanvas` from
227
+ `@margoengine/environment`, an optional peer. Tonemap, a `PostStack` ending in Tonemap, FXAA or SMAA, and the
228
+ `@margoengine/ui` overlay keep it. DOF, TAA and SceneFade are for opaque frames only; the `@margoengine/post` README
229
+ lists the other effects.
230
+
231
+ ```ts
232
+ import { writeFile } from 'node:fs/promises';
233
+ import { createHeadlessStage } from '@margoengine/headless/stage';
234
+ import { Tonemap } from '@margoengine/tonemap';
235
+ import { Panel, Ui, UiRenderer } from '@margoengine/ui';
236
+ import { create } from 'webgpu';
237
+
238
+ const gpu = create([]);
239
+ using stage = await createHeadlessStage({ gpu, width: 640, height: 360, transparent: true });
240
+ stage.box({ color: '#84d6bd' });
241
+ Tonemap.attach(stage.engine);
242
+ const ui = new Ui();
243
+ ui.add(new Panel({ background: '#101820c0', width: 280, height: 64, anchor: 'bottom-left' }));
244
+ UiRenderer.attach(stage.engine, ui);
245
+ stage.fit();
246
+ await writeFile('overlay.png', await stage.toPNG());
247
+ ```
248
+
249
+ ## Choosing the GPU adapter
250
+
251
+ On a machine with two GPUs, an integrated one and a discrete one, the render runs on whichever adapter the binding hands out. Three things choose it, checked with the `webgpu` binding 0.6.2 on a Windows PC with an RTX A6000 and an integrated AMD GPU:
252
+
253
+ - `gpu.requestAdapter()` called with no options returned the integrated AMD GPU. Code that asks the binding for an adapter itself, to read its name or limits, gets that one unless it passes `{ powerPreference: 'high-performance' }`, which returned the RTX A6000.
254
+ - `Engine.create` and `createHeadlessStage` ask for `'high-performance'` themselves when you set nothing (Node reports no Windows browser, so the Windows exception in core's `powerPreference` does not apply) and got the RTX A6000. Set `powerPreference: 'low-power'` for the integrated GPU, or `'high-performance'` to say so in your code. It is an engine option, so `createHeadlessStage({ gpu, width, height, powerPreference })` takes it too.
255
+ - `create(['adapter=NVIDIA'])` fixes the choice in the binding: the first adapter whose name contains that text, whatever any caller asks for. The match is case sensitive (`adapter=nvidia` found nothing, `adapter=RTX` and `adapter=Radeon` matched). With no match the binding throws `no suitable backends found` and lists the adapters it has by name, which is the quickest way to learn what to write.
256
+
257
+ `engine.gpu.adapterInfo` names the GPU the engine got. This example runs as it stands; set `GPU_ADAPTER` to a part of an adapter name to fix the choice:
258
+
259
+ ```ts
260
+ import { Engine } from '@margoengine/core';
261
+ import { createHeadlessCanvas, installGPU } from '@margoengine/headless';
262
+ import { create } from 'webgpu';
263
+
264
+ const wanted = process.env.GPU_ADAPTER;
265
+ const gpu = create(wanted ? [`adapter=${wanted}`] : []);
266
+ using installed = installGPU({ gpu });
267
+ const engine = await Engine.create(createHeadlessCanvas({ width: 640, height: 360 }), {
268
+ backend: 'webgpu',
269
+ powerPreference: 'high-performance',
270
+ });
271
+ console.log(engine.gpu?.adapterInfo?.device); // for example 'nvidia-rtx-a6000'
272
+ engine.dispose();
273
+ ```
274
+
275
+ The two GPUs render at different speeds, so time your own scene with each before you fix a render machine's choice.
276
+
277
+ ## Image sequences and video
278
+
279
+ `@margoengine/headless/video` renders a sequence on its own clock, so a slow machine gives the same frames as a fast one,
280
+ and encodes it for turntables, trailers and docs. `renderFrames` yields each frame's pixels, and `imageSequence` turns them into
281
+ numbered PNG files:
282
+
283
+ ```ts
284
+ import { writeFile } from 'node:fs/promises';
285
+ import { Camera, Engine, box, PbrMaterial } from '@margoengine/core';
286
+ import { createHeadlessCanvas, installGPU } from '@margoengine/headless';
287
+ import { imageSequence, renderFrames } from '@margoengine/headless/video';
288
+ import { create } from 'webgpu';
289
+
290
+ const gpu = create([]);
291
+ using installed = installGPU({ gpu });
292
+ const engine = await Engine.create(createHeadlessCanvas({ width: 640, height: 360 }), { backend: 'webgpu' });
293
+ const mesh = engine.createMesh().setGeometry(box()).setMaterial(new PbrMaterial({ color: '#84d6bd' }));
294
+ const camera = new Camera({ position: [2, 2, 3], target: [0, 0, 0] });
295
+ const frames = renderFrames(engine, {
296
+ frames: 90,
297
+ fps: 30,
298
+ camera,
299
+ update: ({ progress }) => mesh.setRotation([0, progress * Math.PI * 2, 0]),
300
+ });
301
+ for await (const { name, bytes } of imageSequence(frames)) await writeFile(name, bytes);
302
+ engine.dispose();
303
+ ```
304
+
305
+ `encodeVideo` makes a WebM or MP4 file with WebCodecs, in a browser or worker, or anywhere you pass `webCodecs`:
306
+
307
+ ```ts
308
+ import { Engine, box } from '@margoengine/core';
309
+ import { encodeVideo, renderFrames } from '@margoengine/headless/video';
310
+ import { createHeadlessCanvas } from '@margoengine/headless';
311
+
312
+ // In a browser, which has WebCodecs; the readable canvas keeps each rendered frame.
313
+ const engine = await Engine.create(createHeadlessCanvas({ width: 512, height: 512 }), { backend: 'webgpu' });
314
+ engine.createMesh().setGeometry(box());
315
+
316
+ const video = await encodeVideo(renderFrames(engine, { frames: 90 }), { format: 'mp4' });
317
+ const url = URL.createObjectURL(new Blob([video.bytes], { type: video.mimeType }));
318
+ ```
319
+
320
+ Frames of their own length, such as a capture of real time or a cut that holds a shot, carry `timestamp` (seconds from
321
+ the first frame) and the last one its `duration`. Each frame lasts until the next:
322
+
323
+ ```ts
324
+ import { Engine, box } from '@margoengine/core';
325
+ import { encodeVideo, renderFrames, type VideoInputFrame } from '@margoengine/headless/video';
326
+ import { createHeadlessCanvas } from '@margoengine/headless';
327
+
328
+ const engine = await Engine.create(createHeadlessCanvas({ width: 320, height: 240 }), { backend: 'webgpu' });
329
+ const mesh = engine.createMesh().setGeometry(box());
330
+
331
+ // Three shots, held for half a second, a quarter of a second and two seconds.
332
+ const holds = [0.5, 0.25, 2];
333
+ async function* shots(): AsyncGenerator<VideoInputFrame> {
334
+ let timestamp = 0;
335
+ const update = ({ index }: { index: number }) => mesh.setRotation([0, index, 0]);
336
+ for await (const frame of renderFrames(engine, { frames: holds.length, update })) {
337
+ yield { ...frame, timestamp, duration: holds[frame.index] };
338
+ timestamp += holds[frame.index];
339
+ }
340
+ }
341
+
342
+ const video = await encodeVideo(shots(), { format: 'webm' });
343
+ if (video.frames !== 3 || Math.abs(video.duration - 2.75) > 0.001) throw new Error('unexpected timing');
344
+ engine.dispose();
345
+ ```
346
+
347
+ `alpha: true` keeps the frames' alpha, for an overlay an editor or a page lays over other pictures. A second encoder
348
+ codes the alpha, and WebM carries it beside each frame as Matroska BlockAdditions, which Chromium's `<video>` and
349
+ ffmpeg's libvpx decoders read (both are tested); it takes VP9, else VP8:
350
+
351
+ ```ts
352
+ import { encodeVideo, type VideoInputFrame } from '@margoengine/headless/video';
353
+
354
+ // A white bar fading in over two seconds, clear everywhere else: straight alpha, as readPixels gives it.
355
+ function* lowerThird(): Generator<VideoInputFrame> {
356
+ const width = 320, height = 180;
357
+ for (let index = 0; index < 60; index++) {
358
+ const data = new Uint8Array(width * height * 4).fill(255);
359
+ for (let i = 0; i < width * height; i++) data[i * 4 + 3] = i >= width * 130 && i < width * 160 ? index * 4 : 0;
360
+ yield { width, height, data };
361
+ }
362
+ }
363
+
364
+ const overlay = await encodeVideo(lowerThird(), { alpha: true });
365
+ if (!overlay.alpha || !overlay.mimeType.startsWith('video/webm')) throw new Error('no alpha');
366
+ ```
367
+
368
+ `streamVideo` writes a fragmented MP4, or with `format: 'webm'` a live WebM, piece by piece as the frames are encoded,
369
+ so a long render holds one key frame interval of video at a time. Write each piece to a file, a socket or a
370
+ `WritableStream`, or append all but the last piece (the index) to a Media Source Extensions `SourceBuffer` to play
371
+ while it renders:
372
+
373
+ ```ts
374
+ import { Engine, box } from '@margoengine/core';
375
+ import { renderFrames, streamVideo } from '@margoengine/headless/video';
376
+ import { createHeadlessCanvas } from '@margoengine/headless';
377
+
378
+ const engine = await Engine.create(createHeadlessCanvas({ width: 320, height: 240 }), { backend: 'webgpu' });
379
+ engine.createMesh().setGeometry(box());
380
+
381
+ const pieces: Uint8Array<ArrayBuffer>[] = [];
382
+ const stop = new AbortController();
383
+ for await (const piece of streamVideo(renderFrames(engine, { frames: 60 }), { keyFrameInterval: 1, signal: stop.signal })) {
384
+ pieces.push(piece); // or: await writer.write(piece)
385
+ }
386
+ const file = new Blob(pieces, { type: 'video/mp4' });
387
+ if (pieces.length !== 4 || file.size === 0) throw new Error('unexpected stream'); // header, 2 fragments, index
388
+ engine.dispose();
389
+ ```
390
+
391
+ The WebM stream carries alpha too, for an overlay played while it is made:
392
+
393
+ ```ts
394
+ import { streamVideo, type VideoInputFrame } from '@margoengine/headless/video';
395
+
396
+ // A white bar fading in over two seconds, clear everywhere else: straight alpha, as readPixels gives it.
397
+ function* fadeIn(): Generator<VideoInputFrame> {
398
+ const width = 320, height = 180;
399
+ for (let index = 0; index < 60; index++) {
400
+ const data = new Uint8Array(width * height * 4).fill(255);
401
+ for (let i = 0; i < width * height; i++) data[i * 4 + 3] = i >= width * 130 && i < width * 160 ? index * 4 : 0;
402
+ yield { width, height, data };
403
+ }
404
+ }
405
+
406
+ const stream = streamVideo(fadeIn(), { format: 'webm', alpha: true, keyFrameInterval: 1 });
407
+ const pieces: Uint8Array<ArrayBuffer>[] = [];
408
+ let step;
409
+ while (!(step = await stream.next()).done) pieces.push(step.value); // header, 2 clusters, Cues
410
+ if (!step.value.alpha || pieces.length !== 4) throw new Error('unexpected stream');
411
+ const overlay = new Blob(pieces, { type: step.value.mimeType });
412
+ ```
413
+
414
+ Node has no WebCodecs, so `@margoengine/headless/ffmpeg` (Node only) pipes the frames to the ffmpeg you have installed. Nothing
415
+ is downloaded, and it runs without a shell. `audio` adds sound from plain samples, sent down a second pipe beside the frames:
416
+
417
+ ```ts
418
+ import { Engine, box, Camera } from '@margoengine/core';
419
+ import { renderFrames } from '@margoengine/headless/video';
420
+ import { encodeWithFFmpeg } from '@margoengine/headless/ffmpeg';
421
+ import { createHeadlessCanvas, installGPU } from '@margoengine/headless';
422
+ import { create } from 'webgpu';
423
+
424
+ using installed = installGPU({ gpu: create([]) });
425
+ const engine = await Engine.create(createHeadlessCanvas({ width: 512, height: 512 }), { backend: 'webgpu' });
426
+ engine.createMesh().setGeometry(box());
427
+ engine.render({ camera: new Camera({ position: [2, 2, 3], target: [0, 0, 0] }) });
428
+
429
+ // Three seconds of a 440 Hz tone, as long as the 90 frames at 30 fps.
430
+ const tone = Float32Array.from({ length: 3 * 48000 }, (_, i) => 0.2 * Math.sin((2 * Math.PI * 440 * i) / 48000));
431
+ const result = await encodeWithFFmpeg(renderFrames(engine, { frames: 90 }), {
432
+ output: 'turntable.mp4',
433
+ audio: { channels: [tone], sampleRate: 48000 },
434
+ });
435
+ if (result.frames !== 90 || result.audioDuration !== 3) throw new Error('unexpected file');
436
+ ```
437
+
438
+ `npm run test:real-ffmpeg` writes H.264 and VP9 files, with and without AAC and Opus sound, through the ffmpeg you have (`FFMPEG` names another) and decodes them back to check frames, tags, colours, and the sound's length, pitch and level; then it reads alpha back with ffmpeg's libvpx decoder from a VP9 alpha file of `encodeWithFFmpeg`. `npm run test:gpu` does the same for the VP9 and VP8 alpha files `encodeVideo` makes in Chromium, after playing them in a `<video>`.
439
+
440
+ | Export | What it does |
441
+ | --- | --- |
442
+ | `renderFrames(engine, { frames, fps?, camera?, update?, signal? })` | Async iterator of frames: pixels plus `index`, `time`, `delta` and `progress`. `fps` defaults to 30, `camera` to the engine's. `update` runs before each frame is drawn. `progress` is `index / frames`: it never reaches 1, so a full turn loops with no repeated frame. The next frame is not drawn until you ask for it. |
443
+ | `imageSequence(frames, { prefix?, digits? })` | Async iterator of `{ index, name, bytes }` PNG files. `prefix` defaults to `'frame_'`, `digits` to 4. |
444
+ | `encodeVideo(frames, options?)` | The whole file in memory as `{ bytes, mimeType, codec, width, height, frames, duration }`, plus `alpha: true` when the file carries alpha. `format` `'webm'` (default) or `'mp4'`. `fps` 30. `codec`: a WebCodecs string; default the first supported of VP9, VP8, AV1 for WebM and H.264, VP9, AV1 for MP4. MP4 also takes H.265 (`hvc1.*` or `hev1.*`, for example `'hvc1.1.6.L93.B0'`) where the runtime encodes it (Safari, and Chromium with a platform encoder). `bitrate` `width * height * fps / 10`, at least 100,000. `keyFrameInterval` 2 seconds. `audio` none: `{ channels, sampleRate, bitrate? }` adds sound from plain samples, one `Float32Array` per channel, one or two channels, `bitrate` 128000, as Opus in WebM and as AAC or else Opus in MP4, and the result then has `audioCodec`. `alpha` false: true keeps the frames' alpha (straight, as `readPixels` gives it) in a WebM file, the same codec and settings whose luma is the alpha, and written as each frame's BlockAdditions (BlockAddID 1, AlphaMode 1 on the track, RFC 9559 and the Matroska V_VP8 and V_VP9 mappings); a frame is a key frame, with a cue, only when its colour and its alpha both are. It takes VP9, else VP8; MP4 and AV1 have no binding for alpha, so `format: 'mp4'` or an `av01` codec with `alpha` rejects with code `'unsupported'`. `webCodecs` `globalThis`, with `AudioEncoder` and `AudioData` needed for `audio`, and `AudioDecoder` used to measure an AAC encoder's lead-in (2112 samples, 44 ms at 48 kHz, on Chromium for macOS), which an edit list then cuts so the sound starts on time; without `AudioDecoder` an AAC track plays late by it. `signal` none. Each frame is converted to limited-range BT.709 4:2:0 before the encoder sees it, and the file says so (BT.709 primaries and matrix, sRGB transfer, chroma on the even columns between rows, the H.264 default), so every player draws the colours that were rendered, chroma edges in place. A frame may carry `timestamp`, seconds counted from the first frame's, for frames of varying length (a capture of real time, a cut that holds a shot): give it on every frame or none, each later than the one before; each frame lasts until the next, and the last one its own `duration` (seconds) or else the gap before it. Key frames then come `keyFrameInterval` seconds apart, and WebM states no default frame duration. Without timestamps frame n shows at n / fps. H.264 and H.265 state sizes in steps of two, so an odd width or height gains one repeated last column or row there (the result's `width` and `height` give the size written); VP8, VP9 and AV1 keep odd sizes. `mimeType` names every stream in the file, the sound's too (`video/mp4; codecs="avc1.640033,mp4a.40.2"`), as RFC 6381 asks, so `MediaSource.isTypeSupported` and `canPlayType` judge the whole file. |
445
+ | `streamVideo(frames, options?)` | Async iterator of the pieces of a video file as it is encoded. `format` `'mp4'` (default): a fragmented MP4 (ISO/IEC 14496-12 8.8): the header (`ftyp`, `moov` with empty sample tables and `mvex`) once the encoder gives its configuration, then a `moof` and `mdat` per key frame interval as soon as the next key frame shows where it ends, then an `mfra` index so a player seeks the finished file without reading every fragment. `format` `'webm'`: a WebM written as a live stream (RFC 9559 6.2): the header (EBML header, a Segment of unknown size, Info with no duration, Tracks, Tags), then a Cluster per key frame interval as soon as the next key frame shows where it ends, then the Cues; its clusters are `encodeVideo`'s, and `alpha` keeps the frames' alpha as `encodeVideo` does (VP9, else VP8). Joined, the pieces are one file that browsers and ffmpeg play; all but the last piece are what a Media Source Extensions `SourceBuffer` takes. Options are `encodeVideo`'s (`fps`, `codec`, `bitrate`, `keyFrameInterval`, `audio`, `alpha`, `provenance`, `webCodecs`, `signal`) without `maxBytes`: only one key frame interval of encoded video is held, so there is no total to cap. `alpha` with MP4 or an `av01` codec rejects with code `'unsupported'`. `audio` is encoded first and each fragment or cluster carries the sound of the time its frames cover (in MP4 with the same edit list and roll groups as `encodeVideo`). A joined WebM states no duration, as its header went out before the end was known. The iteration's return value is `encodeVideo`'s result without `bytes`. Stopping the iteration (`break`, or `signal`, which rejects with its reason) closes the encoders. |
446
+ | `encodeWithFFmpeg(frames, { output, fps?, ffmpeg?, args?, audio?, alpha?, layers?, chroma?, signal? })` | Writes `output` and resolves `{ output, width, height, frames }`, plus `audioDuration` (seconds) with sound. `audio` none: `{ channels, sampleRate, bitrate? }`, one `Float32Array` per channel from -1 to 1, one or two channels of one length, a whole `sampleRate`, `bitrate` 128000; it goes to ffmpeg as 32-bit float samples on a second pipe (`pipe:3`) while the frames go down standard input, each waiting only for its own room, and is written as Opus for `.webm` and AAC for anything else. With `args` the sound is still input 1 and mapped (`-map 0:v:0 -map 1:a:0`), and its codec is the one your arguments or ffmpeg's default for the file pick. `fps` defaults to 30, `ffmpeg` to `'ffmpeg'` on the `PATH` (or `['nice', 'ffmpeg']`). `args` replaces the output arguments, which default to VP9 at `-crf 32` for `.webm` and H.264 at `-crf 20` for anything else, both 4:2:0, limited range, tagged BT.709 for matrix and primaries and sRGB for transfer, as `encodeVideo` tags them, with chroma made and tagged on the left column between rows. With the default H.264 arguments an odd width or height gains one repeated last column or row, and the result gives the size written. `alpha` false: true keeps the frames' alpha as VP9 with an alpha plane (`yuva420p`), which ffmpeg writes as WebM BlockAdditions; it needs a `.webm` output and the default arguments, and rejects with code `'unsupported'` otherwise (with `args`, choose the pixel format there). `layers` none: each `{ input, rect: { x, y, width, height }, start?, duration?, in?, speed?, fit? }` lays the file `input` over the frames in the box `rect` (whole pixels inside the written frame), from `start` seconds (default 0) for `duration` seconds (default: until the file ends; a still picture needs one), reading the file from `in` seconds (default 0) at `speed` (default 1), cut to `crop` `[x, y, width, height]` of the file first (even whole pixels inside it; default all of it), fitted by `fit` `'contain'` (default: all of it, the rest of the box `pad`, a colour `'#rgb'`, `'#rrggbb'` or `'#rrggbbaa'`, default clear), `'cover'` or `'fill'` (`contain` and `cover` keep the shape the file is shown at, its width times its sample aspect ratio over its height, so a clip with non-square samples such as 720x480 at 32:27 fills a 16:9 box; `fill` stretches to the box), and read with `matrix` and `range` (default: the file's tags; untagged, `'bt709'` at 720 lines or more and `'bt601'` below, at `'tv'` range; an untagged JPEG `'bt601'` at `'pc'`); later layers lie on top. Each clip frame starts on the film frame nearest its own time (`fps=<fps>:round=near`). Frame k shows a layer when start <= k / fps < start + duration, its last frame held to the end of its window, and the video keeps the rendered frames' length. Each layer file is read once with `probeVideo` before the encode. The layers and the colour chain run as one `-filter_complex` graph, the output arguments' `-vf` moved to its end, so a layered video is tagged exactly as a plain one. A failure's `cause` holds the end of ffmpeg's log. |
447
+ | `ffmpegArguments(width, height, { output, fps?, args?, audio?, alpha?, layers?, chroma? })` | The argument list `encodeWithFFmpeg` uses. `chroma` `'sharp'` (default): the engine makes the 4:2:0 picture (below) and ffmpeg reads I420 frames; `'scaler'`: ffmpeg's scaler makes it from RGBA. `args`, `alpha` and `layers` always use the scaler; any other value is a RangeError. It reads no file: pass layers through `resolveLayers` first for the default colours. |
448
+ | `probeVideo(input, { ffmpeg?, signal? })` | The first video stream of a video or picture file as ffmpeg reports it: `{ codec, pixelFormat, width, height, rgb, matrix?, range? }`, `matrix` and `range` only when the file is tagged with them (ffmpeg's names, such as `'bt709'`, `'bt470bg'`, `'tv'`), `rgb` true for RGB, palette and grey formats. Rejects with code `'failed'` when there is no video stream. |
449
+ | `resolveLayers(layers, { ffmpeg?, signal? })` | The layers with `matrix` and `range` filled in for each untagged file by the defaults above, each file read once; a `crop` outside its file throws a RangeError. |
450
+ | `layersOverPicture(picture, output, { frame, fps?, layers, ffmpeg?, signal? })` | Lays `layers` over `picture`, a rendered frame `frame` of a video at `fps` (default 30), exactly as `encodeWithFFmpeg` lays them on that frame, and writes `output` (PNG for a `.png` name). The still equals the encode's frame pixel for pixel when the encode is lossless RGB. |
451
+ | `layersPictureArguments(width, height, { picture, output, frame, fps?, layers })` | The argument list `layersOverPicture` uses. |
452
+
453
+ Frames must all be one size. Video drops alpha unless `alpha` keeps it (WebM only). H.264 and the default ffmpeg settings need even sizes.
454
+
455
+ ### 4:2:0 made by the engine: sharp chroma
456
+
457
+ A 4:2:0 video keeps one colour sample for every 2 x 2 pixels. A plain filter averages the block's colour, so a dark
458
+ pine needle over orange fire glow comes back red-brown. `@margoengine/headless/yuv420` makes the 4:2:0 picture itself
459
+ and searches each colour sample and each pixel's luma so that the picture a player decodes (bilinear chroma, BT.709,
460
+ limited range, 8 bits) is as close to the source as the samples allow, measured in CIELAB. `encodeWithFFmpeg` uses it by
461
+ default, and the `chromaSmear` look check judges exactly this conversion.
462
+
463
+ ```ts
464
+ import { fromYuv420, i420Bytes, toYuv420 } from '@margoengine/headless/yuv420';
465
+
466
+ const width = 4,
467
+ height = 2,
468
+ rgba = new Uint8Array(width * height * 4).fill(200);
469
+ const picture = toYuv420(rgba, width, height); // { width, height, siting: 'left', y, cb, cr }
470
+ const bytes = i420Bytes(picture); // Y plane, then Cb, then Cr: ffmpeg's yuv420p
471
+ const back = fromYuv420(picture); // RGBA as a player shows it
472
+ console.log(bytes.length, back[0]);
473
+ ```
474
+
475
+ ```ts
476
+ import { Yuv420Pool, yuv420Frames } from '@margoengine/headless/yuv420-pool';
477
+
478
+ const frames = [{ width: 4, height: 2, data: new Uint8Array(32).fill(90) }];
479
+ await using pool = new Yuv420Pool(); // one worker per core but one
480
+ for await (const bytes of yuv420Frames(frames, pool)) console.log(bytes.length); // I420, in order
481
+ ```
482
+
483
+ | Export | What it does |
484
+ | --- | --- |
485
+ | `toYuv420(pixels, width, height, { chroma?, siting?, rounds? }?, channels?)` | The 4:2:0 picture of RGBA (or RGB with `channels` 3) sRGB pixels, BT.709 at limited range. `chroma` `'sharp'` (default) or `'average'` (the plain filter: the transpose of the bilinear read, 1, 2, 1 across and 1, 1 down for `'left'`, the 2 x 2 mean for `'center'`). `siting` `'left'` (default; H.273 chroma sample location type 0, the H.264 default) or `'center'`. `rounds` 4: search rounds. Width and height must be even. |
486
+ | `fromYuv420(picture)` | RGBA as a player decodes it: bilinear chroma at the picture's siting, BT.709, clamped and rounded. |
487
+ | `i420Bytes(picture)` | The planes as one I420 (`yuv420p`) frame. |
488
+ | `Yuv420Pool(size?)` | Worker threads (Node) converting frames: `convert(rgba, width, height, options?)` resolves the I420 bytes; `close()` and `await using` stop them. |
489
+ | `yuv420Frames(frames, pool, options?)` | Async iterator of the I420 bytes of `frames`, in order, `pool.size * 2` converting ahead. |
490
+
491
+ The search (KB-LOOK-RAIL-CHROMA1) starts from the plain filter. Only samples where a pixel they feed decodes more than 3
492
+ (CIE76) from the source are searched. Each round sets each such pixel's luma by a pattern search over whole codes, then
493
+ moves each colour sample by a damped Gauss-Newton step on the sum of the differences of the pixels it feeds (weights
494
+ 1 over the difference, so the sum, not the sum of squares, falls), kept only when that sum falls. A last pass sets the
495
+ luma of every pixel for the rounded colour. A 1080p film frame with much fine colour detail takes about 5 seconds on one
496
+ core; smooth frames take a fraction of that. Sources: J. Ström, J. Samuelsson, K. Dovstam, "Luma Adjustment for High
497
+ Dynamic Range Video", DCC 2016 (https://ieeexplore.ieee.org/document/7786165); K. Chung et al., "Improved gradient
498
+ descent-based chroma subsampling method for color images in VVC", 2020 (https://arxiv.org/abs/2009.10934); S. Wang et
499
+ al., "Joint Chroma Downsampling and Upsampling for Screen Content Image", IEEE TCSVT 26(9), 2016; ITU-R BT.709-6;
500
+ ITU-T H.273 (chroma sample location); CIE 15:2004 (CIELAB); IEC 61966-2-1 (sRGB).
501
+
502
+ ### Finished files: encoders, joins, sound, stream-copy cuts and layers
503
+
504
+ `@margoengine/headless/ffmpeg-files` (Node only) works on finished files with the same ffmpeg, and `encodeWithFFmpeg`
505
+ takes `layers`, other video or picture files laid over the frames inside the one encode (picture in picture), put
506
+ through the same colour chain as a plain render; `layersOverPicture` lays the same layers over one rendered frame, so a
507
+ still matches the video. `encoderArguments` gives a hardware H.264 encoder (NVENC, AMF, Quick
508
+ Sync) or x264 the engine's colour handling; `joinVideos` joins chunks by stream copy, writing `avc3` when their
509
+ parameter sets differ; `addSound` lays a sound file under a video without encoding the picture again; `copySpan` cuts
510
+ a recorded span by stream copy, after checking it is exactly the frames it should be, re-tagged as an engine chunk.
511
+
512
+ ```ts
513
+ import { writeFile } from 'node:fs/promises';
514
+ import { encodePNG } from '@margoengine/headless';
515
+ import { encodeWithFFmpeg, layersOverPicture } from '@margoengine/headless/ffmpeg';
516
+ import { addSound, checkSpan, copySpan, encoderArguments, joinVideos } from '@margoengine/headless/ffmpeg-files';
517
+ import { encodeWav } from '@margoengine/audio/wav';
518
+
519
+ // Two one-second chunks of plain frames (any renderFrames source works the same way), each a separate encode.
520
+ const frames = (red: number) =>
521
+ Array.from({ length: 30 }, () => ({ width: 128, height: 72, data: new Uint8Array(128 * 72 * 4).fill(red) }));
522
+ const args = encoderArguments('x264', { preset: 'veryfast' }); // or 'nvenc', 'amf', 'qsv' where the GPU has one
523
+ await encodeWithFFmpeg(frames(60), { output: 'part-1.mp4', args });
524
+ await encodeWithFFmpeg(frames(200), { output: 'part-2.mp4', args });
525
+
526
+ // A third chunk with the middle of part 1 playing in a box at the top left from 0.25 s for half a second, on a dark
527
+ // plate where it does not fill the box.
528
+ const layers = [
529
+ {
530
+ input: 'part-1.mp4',
531
+ rect: { x: 0, y: 0, width: 64, height: 48 },
532
+ start: 0.25,
533
+ duration: 0.5,
534
+ crop: [32, 18, 64, 36] as const,
535
+ pad: '#202830',
536
+ },
537
+ ];
538
+ await encodeWithFFmpeg(frames(120), { output: 'part-3.mp4', args, layers });
539
+
540
+ // The same layers over frame 15 of part 3 as one picture: what the video shows at 0.5 s.
541
+ await writeFile('frame-15.png', await encodePNG(frames(120)[15]));
542
+ await layersOverPicture('frame-15.png', 'still-15.png', { fps: 30, frame: 15, layers });
543
+
544
+ const entry = await joinVideos(['part-1.mp4', 'part-2.mp4', 'part-3.mp4'], 'film.mp4');
545
+ await writeFile('tone.wav', encodeWav({ sampleRate: 48000, channels: [Float32Array.from({ length: 3 * 48000 }, (_, i) => 0.2 * Math.sin(i / 20))] }));
546
+ await addSound('film.mp4', 'tone.wav', 'film-with-sound.mp4');
547
+
548
+ // Part 2 starts on a key frame at 1 s, so it cuts out again without an encode.
549
+ const check = await checkSpan('film.mp4', { start: 1, frames: 30, fps: 30 });
550
+ if (!check.ok || !entry) throw new Error(check.reason ?? 'not H.264');
551
+ await copySpan('film.mp4', 'part-2-again.mp4', { start: 1, frames: 30, fps: 30 });
552
+ ```
553
+
554
+ A layer file is read with the matrix and range it is tagged with. Untagged, it is read as ITU-R BT.709 at 720 lines or
555
+ more and ITU-R BT.601 below, at TV range: ITU-T H.273 leaves untagged colour to the application, HD video (SMPTE ST
556
+ 296, ST 274) is BT.709 and SD video is BT.601, while ffmpeg's scaler reads every untagged file as BT.601, so an HD
557
+ clip came out up to 8 levels off on red and blue. An untagged JPEG is JFIF (ITU-T T.871): BT.601 at full range. A
558
+ layer's `matrix` (`'bt709'`, `'bt601'`, `'bt2020'`) and `range` (`'tv'`, `'pc'`) replace the file's own. Each clip
559
+ frame starts on the film frame nearest its own time (ffmpeg's `fps` filter, `round=near`), so a 24 fps clip in a 30
560
+ fps film repeats one frame in four, evenly.
561
+
562
+ `npm run test:real-ffmpeg` also runs these through the ffmpeg you have: the recording's sample times and key flags
563
+ against ffprobe's (plain and fragmented MP4), a copied span decoding to the recording's own frames, an engine chunk and
564
+ a copied span joined as `avc3` and decoding to both, sound added with the picture packets unchanged, every hardware
565
+ encoder ffmpeg lists writing the engine's tags (an encoder with no device is reported, not passed), and layers shown
566
+ only inside their window.
567
+
568
+ | Export of `/ffmpeg-files` | What it does |
569
+ | --- | --- |
570
+ | `encoderArguments(encoder?, { quality?, preset? })` | Output arguments for `encodeWithFFmpeg`'s `args`: `encoder` `'x264'` (default, libx264), `'nvenc'`, `'amf'` or `'qsv'`, at constant `quality` 1 to 51 (default 20: x264's CRF, NVENC's CQ with `-preset p5 -tune hq` and no rate cap, AMF's QP on every frame type with `-quality quality`, Quick Sync's global quality). `preset` is x264's (`'ultrafast'` to `'placebo'`) or NVENC's (`'p1'` to `'p7'`). Every encoder gets the default's BT.709, TV range, sRGB transfer and left chroma chain, the same stream tags, the `H264_COLOUR_TAGS` VUI rewrite (whatever the encoder writes itself) and `+faststart`. |
571
+ | `H264_COLOUR_TAGS` | The `h264_metadata` bitstream filter that writes the engine's colour into an H.264 stream's parameter sets: primaries 1, transfer 13, matrix 1, TV range, chroma location 0 (ITU-T H.273). |
572
+ | `joinVideos(inputs, output, { sampleEntry?, ffmpeg?, signal? })` | Joins files end to end by stream copy (ffmpeg's concat demuxer, `-c copy`, `+faststart`). The files must share codec, size and frame rate, as chunks of one render do. `sampleEntry` `'auto'` (default) writes `avc3` when the inputs' H.264 parameter sets differ, since `avc1` keeps one set in its sample entry and such a join carries each file's own sets in band (ISO/IEC 14496-15), and `avc1` when they agree. Resolves the entry written, or undefined for inputs that are not H.264 MP4. |
573
+ | `addSound(video, sound, output, { codec?, bitrate?, offset?, shortest?, ffmpeg?, signal? })` | Lays the first audio stream of `sound` (WAV, FLAC, MP3, AAC, anything ffmpeg reads) under `video` with the picture copied, replacing any sound it had. `codec` `'aac'` (default for MP4 and MOV), `'opus'` (default for WebM) or `'copy'`; `bitrate` 192000; `offset` seconds of picture before the sound starts (default 0); `shortest` ends the file with the shorter of the two (default false). |
574
+ | `checkSpan(file, { start, frames, fps, timescale? })` | Whether `frames` frames from `start` of an MP4 or MOV file can be cut by stream copy so frame k sits at start + k / fps: H.264; a key frame within half a tick of `start` (ticks of `timescale`, default `mp4Timescale(fps)`); the next `frames` samples in decode order are exactly frames 0 to frames - 1, each within half a tick of its step, so none is missing and none is an open GOP's leading frame decoded after the key frame. Resolves `{ ok: true }` or `{ ok: false, reason }`. |
575
+ | `copySpan(input, output, { start, frames, fps, timescale?, ffmpeg?, signal? })` | Cuts that span by stream copy (no decode, no encode): the picture alone, its VUI rewritten by `H264_COLOUR_TAGS`, at `timescale`, with `+faststart`, so it joins engine chunks with `joinVideos`. Rejects with code `'unsupported'` and the reason when `checkSpan` refuses it. |
576
+ | `readVideoTrack(file)` | The first video track of an MP4 or MOV file: `codec` (the sample entry, such as `'avc1'`), `timescale`, `avcConfig` (the `avcC` body, H.264 only) and `samples`, each `{ time, key }` in decode order, from the sample tables and any movie fragments, with the edit list applied (ISO/IEC 14496-12). Reads box headers, `moov` and each `moof`, never the media data. Rejects with code `'unsupported'` when there is no video track. |
577
+ | `mp4Timescale(fps)` | The MP4 track timescale ffmpeg gives an encode at a whole `fps` (the rate doubled until it reaches 10,000: 15,360 at 30 and 60 fps), the default timescale of a copied span. |
578
+
579
+ Every tool writes through a temporary file beside `output` and renames it once ffmpeg succeeds, so a failure or an
580
+ abort leaves no half file; a failure rejects with code `'failed'` and the end of ffmpeg's log in `cause`, and a missing
581
+ ffmpeg with code `'unsupported'`. Paths go to ffmpeg as arguments, never through a shell.
582
+
583
+ ## Comparing images
584
+
585
+ `@margoengine/headless/compare` is for visual regression tests of your own scenes. `compareImages` takes RGBA pixels or PNG
586
+ file bytes, made by any tool, and says whether a picture still matches its reference:
587
+
588
+ ```ts
589
+ import assert from 'node:assert/strict';
590
+ import { readFile, writeFile } from 'node:fs/promises';
591
+ import { encodePNG, readPixels, createHeadlessCanvas, installGPU } from '@margoengine/headless';
592
+ import { compareImages } from '@margoengine/headless/compare';
593
+ import { Engine, box, Camera } from '@margoengine/core';
594
+ import { create } from 'webgpu';
595
+
596
+ using installed = installGPU({ gpu: create([]) });
597
+ const engine = await Engine.create(createHeadlessCanvas({ width: 512, height: 512 }), { backend: 'webgpu' });
598
+ engine.createMesh().setGeometry(box());
599
+ engine.render({ camera: new Camera({ position: [2, 2, 3], target: [0, 0, 0] }) });
600
+
601
+ const result = await compareImages(await readPixels(engine), await readFile('reference.png'));
602
+ if (!result.pass) await writeFile('difference.png', await encodePNG(result.image));
603
+ assert.ok(result.pass, `${result.different} pixels changed, SSIM ${result.ssim}`);
604
+ ```
605
+
606
+ | Export | What it does |
607
+ | --- | --- |
608
+ | `compareImages(actual, reference, { threshold?, maxRatio?, minSSIM? })` | Both limits must hold for `pass`. `maxRatio` defaults to 0.001, `minSSIM` to 0.99, `threshold` to 2. Resolves the `pixelDiff` result with `image`, plus `pass` and `ssim`. |
609
+ | `pixelDiff(a, b, { threshold?, image?, mask?, clusters? })` | `{ different, total, ratio, largest, mean, box }`. A pixel differs when a channel moves more than `threshold`, 0 to 255, default 2. Colours are compared premultiplied, so colour under full transparency does not count. `box` is the smallest `{ x, y, width, height }` holding every changed pixel, null when none changed. `image: true` adds changed pixels in red over a faded `a`; `mask: true` adds `mask`, one byte a pixel, 1 where it changed; `clusters: gap` adds `clusters`, one box per group of touching changed pixels, joining groups at most `gap` pixels apart. |
610
+ | `ssim(a, b, { window?, sigma?, map? })` | Structural similarity as `{ score }`: 1 for identical images. `window` defaults to 11, `sigma` to 1.5, as published, on luma. `map: true` adds the score of each window. |
611
+ | `decodePNG(bytes)` | A PNG file as RGBA pixels: every colour type and bit depth, interlaced or not, 16-bit samples cut to 8. A chunk with a bad CRC or a bit depth its colour type cannot have rejects. Colour profiles and gamma are ignored. All of PngSuite reads as Chromium reads it. |
612
+
613
+ A pixel count sees how many pixels moved, and SSIM sees whether the picture looks different: a slight brightness change fails
614
+ the first and passes the second, and a small hole does the opposite. Images of different sizes reject.
615
+
616
+ `box` and `clusters` say where a picture changed, so a test can crop the difference or check that a change stayed inside
617
+ the region it meant to touch:
618
+
619
+ ```ts
620
+ import assert from 'node:assert/strict';
621
+ import { pixelDiff } from '@margoengine/headless/compare';
622
+
623
+ const width = 64, height = 32;
624
+ const before = { width, height, data: new Uint8Array(width * height * 4).fill(255) };
625
+ const after = { width, height, data: before.data.slice() };
626
+ for (const [x, y] of [[10, 4], [11, 5], [40, 20]]) after.data.set([255, 0, 0, 255], (y * width + x) * 4);
627
+
628
+ const diff = pixelDiff(before, after, { mask: true, clusters: 2 });
629
+ assert.deepEqual(diff.box, { x: 10, y: 4, width: 31, height: 17 });
630
+ assert.deepEqual(diff.clusters, [{ x: 10, y: 4, width: 2, height: 2 }, { x: 40, y: 20, width: 1, height: 1 }]);
631
+ assert.equal(diff.mask![5 * width + 11], 1);
632
+ ```
633
+
634
+ ## Look checks for rendered shots
635
+
636
+ `@margoengine/headless/look` reviews rendered frames before a person does: pure functions over 8-bit frames, float
637
+ frames and grey masks, each giving a value and a pass against a bound. `checkShot` runs them on every probe frame of a
638
+ shot rendered by the shot tool (`tools/shot`, [docs/shots.md](../../docs/shots.md)), with the bounds of the shot file's
639
+ `lookBounds`, and gives one contact sheet and one table, so a shot is reviewed as one page. Nothing here needs a GPU.
640
+
641
+ ```ts
642
+ import { mkdir, readFile, writeFile } from 'node:fs/promises';
643
+ import { join } from 'node:path';
644
+ import { encodePNG } from '@margoengine/headless';
645
+ import { checkShot } from '@margoengine/headless/look';
646
+
647
+ // A night sky with 16 grey levels where 8-bit output has 64: the banding a short must not ship.
648
+ const width = 270,
649
+ height = 480,
650
+ data = new Uint8Array(width * height * 4);
651
+ for (let y = 0; y < height; y++)
652
+ for (let x = 0; x < width; x++) {
653
+ const v = 20 + Math.floor((y / height) * 16) * 4;
654
+ data.set([v, v, v + 10, 255], (y * width + x) * 4);
655
+ }
656
+ await mkdir('shot/probes', { recursive: true });
657
+ await writeFile('shot/probes/opening.png', await encodePNG({ width, height, data }));
658
+
659
+ // The shot tool writes manifest.json beside the frames; its header carries the shot file's lookBounds.
660
+ const manifest = {
661
+ id: 'night-sky',
662
+ header: { lookBounds: { banding: 1, lights: [0, 1] as [number, number] } },
663
+ probes: { opening: { frame: 0, file: 'probes/opening.png' } },
664
+ };
665
+ const report = await checkShot({ manifest, read: (path) => readFile(join('shot', path)) });
666
+ await writeFile('shot/look.md', report.markdown);
667
+ await writeFile('shot/look.json', JSON.stringify(report.json, null, 2));
668
+ await writeFile('shot/look.png', await encodePNG(report.sheet));
669
+ console.log(report.pass ? 'looks right' : 'look checks failed: see shot/look.md and shot/look.png');
670
+ ```
671
+
672
+ The checks, by their `lookBounds` name. A number bound is the largest value that passes, `[low, high]` a range; a
673
+ name left out keeps the default below. A check runs when its inputs are there; one named in `lookBounds` that cannot run,
674
+ or a name no check has, fails as `not run`, never a pass. A check that ran over a mask with no pixels in it (a
675
+ `sky` mask of a frame with no sky in view) passes with `empty` set, `'0 sky pixels'` for `skyClip`, and the table says
676
+ `pass (measured 0 sky pixels)`, so that pass is never silent.
677
+
678
+ With no `sky` mask, `skyClip` measures inside a `sky-coverage` mask when the probe has one: the pixels
679
+ `@margoengine/sky` drew (its `coverage` option), which the shot tool reads from the page's sky. So the flames and a
680
+ kettle's glint in an interior are not counted as sky. Only `skyClip` reads it; `grain`, `lights` and `horizonSeam`
681
+ keep the `sky` mask or the whole frame. Each `skyClip` row's `mask` says what it measured inside (`sky`,
682
+ `sky-coverage` or `frame`), and look.md lists it under the table:
683
+
684
+ ```ts
685
+ import { checkProbe, lookReport } from '@margoengine/headless/look';
686
+
687
+ // An interior: a clipped flame in the lower half, the window's sky in the top-left corner.
688
+ const width = 40,
689
+ height = 40,
690
+ data = new Uint8Array(width * height * 4),
691
+ sky = new Uint8Array(width * height);
692
+ for (let y = 0; y < height; y++)
693
+ for (let x = 0; x < width; x++) {
694
+ const v = y >= 20 && x >= 10 && x < 30 ? 255 : 60;
695
+ data.set([v, v, v, 255], (y * width + x) * 4);
696
+ sky[y * width + x] = x < 12 && y < 12 ? 255 : 0;
697
+ }
698
+ const frame = { width, height, data };
699
+ const rows = checkProbe({ name: 'hearth', frame, masks: { 'sky-coverage': { width, height, data: sky } } }, { skyClip: 0.5 });
700
+ const clip = rows.find((row) => row.check === 'skyClip')!;
701
+ console.log(clip.value, clip.mask); // 0 'sky-coverage': the flame is not sky
702
+ console.log(lookReport([{ name: 'hearth', frame, results: rows }]).markdown.split('Masks:')[1]);
703
+ ```
704
+
705
+ | Name | Value | Default bound | Needs |
706
+ | --- | --- | --- | --- |
707
+ | `skyClip` | % of sky pixels with a channel at 254 or more | 0.5 | the frame; the `sky` mask if there is one, else `sky-coverage` if there is one |
708
+ | `grain` | noise standard deviation in 8-bit codes (Immerkaer's estimator, blind to ramps) | 1.5 | the frame; measured in the `sky` mask if there is one |
709
+ | `speckle` | pixels 24 codes above or below all eight neighbours, per million | 50 | the frame |
710
+ | `banding` | % of pixels in flat runs of 6 or more split by a step of 1.5 to 12 codes, a skipped code; with the probe's `precise` frame, the worse of the frame and its pre-dither codes | 1 | the frame; `precise` to also judge the pre-dither codes |
711
+ | `flat` | % of pixels at the centre of a constant 65 x 65 window, black and white left out; with the probe's `precise` frame, the worse of the frame and its pre-dither codes | 5 | the frame; `precise` to also judge the pre-dither codes |
712
+ | `blocks` | % of the frame in tiles with steps repeating at the 8-pixel froxel pitch | 1 | the frame |
713
+ | `horizonSeam` | luma step at the analytic horizon beyond its surroundings, codes (median over the columns with sky just above the line) | 6 | the camera's `viewProjection` and the `sky` mask (an interior's line runs across walls, not a horizon) |
714
+ | `waterSeam` | the same at the water line, the top edge of the `water` mask | 6 | the `water` mask |
715
+ | `lights` | bright discs (moon, sun, lamps), against the lights the scene shows; a disc counts when its core clips (luma 250 or more) or a ring just outside it is below 0.7 of the level, so sunlit cumulus puffs that shade into their cloud do not | [0, 1] | the frame; the `sky` mask if there is one |
716
+ | `foamEdges` | % of strong foam edges 2 pixels wide or less | 35 | the `foam` mask |
717
+ | `crush` | % of pixels at black (channels 2 or less) outside the `dark` mask | 0.5 | the frame |
718
+ | `flicker` | largest jump of the mean luma off its trend, codes | 0.75 | `still`: 3 or more frames of a still camera |
719
+ | `shimmer` | % of pixels jumping more than 6 codes off their own trend | 0.5 | `still` frames |
720
+ | `nan` | pixels with a NaN or infinite channel | 0 | `hdr`: the float frame |
721
+ | `backends` | mean FLIP of the WebGPU frame against the WebGL2 compatibility layer's | 0.03 | `compat`: the compat frame |
722
+ | `reference` | mean FLIP against a 16-sample reference render | 0.05 | `reference`: the reference frame |
723
+ | `penumbra` | T1: noise standard deviation inside the shadow penumbra on the ground (the `plants` mask left out, at least `PENUMBRA_MIN_PIXELS`, 2,055, interior pixels), codes; with `pool` (the shot's `probePool` frames, or their `penumbraSample` sums) every frame's Laplacian responses are summed as one larger frame, so a far penumbra under a pixel wide still reaches the count | 0.7 | the `penumbra` mask, and `plants` where the shot has plants |
724
+ | `penumbraPlants` | T1 on foliage: grain of the plants inside the penumbra over the grain of the plants outside it, in the same frame (foliage texture detail is not shadow noise, so the plants are held to their own detail; KB-LOOK-TV-PENUMBRA2) | 1 | the `penumbra` and `plants` masks |
725
+ | `stairs` | T3: % of strong edges (a step over 24 codes) that are one pixel stair steps: a step with no value between its two plateaus in the 3 x 4 window of its two pixels (nothing further than a tenth of the range from both ends), on an edge that is not straight along a pixel row or column | 1 | the frame |
726
+ | `colourEdges` | T7: the same on the a* and b* planes: colour edges 4:2:0 smears | 10 | the frame |
727
+ | `chromaSmear` | T7: percent of pixels whose colour moves by CIE76 over 6 through the 4:2:0 conversion the film encode ships (`toYuv420` then `fromYuv420`: sharp chroma, left siting, BT.709 limited range, 8 bits); `chroma: 'average'` judges the plain filter instead | 2 | the frame |
728
+ | `shimmerMoving` | T4: % of pixels more than 6 codes outside the range of the four next-frame pixels their camera motion lands between (a blend of those four is resampling, the TAA neighbourhood clamp of Karis 2014); with `velocity`, what moves other than the camera and its motion blur's reach (McGuire et al. 2012 tile-max, at most `maxBlur`), and with `distance` the camera's parallax trails over what lies a depth step behind, are left out, and a pixel the engine moves under half a pixel of its own lands where its velocity takes it when that velocity is steady, like its neighbours' and on the same surface (`reproject`, default `'velocity'`) | 0.5 | `moving`: the next frame and each pixel's motion (`reprojectionMotion` makes it from depth and the two view-projections) |
729
+ | `motionBlur` | T8: % of edge centres of pixels moving over 8 pixels a frame whose edge is narrower than half the shutter's smear (`shutter` degrees, default 180, smear `shutter / 360` of the travel; `checkShot` reads the angle from `manifest.render` when the shot drew sub-frames) | 5 | `moving` |
730
+ | `silhouette` | T5: % of the subject's outline with 15 L* or more against what is behind | [80, 100] | the `subject` mask |
731
+ | `silhouetteShape` | T5: % of the subject (at 320 x 180, three L* values) in one value | [70, 100] | the `subject` mask |
732
+ | `bounce` | T6: shadowed ground luminance as a % of the lit ground's, linear light, each over its mask's interior (pixels the mask covers whole, 255, then `GROUND_INSET`, 1/360 of the shorter side, in from every edge, where the frame mixes both sides) | [10, 35] under a clear sun; a probe's `light` moves it (`lightBounds`) | the `lit` and `shadow` masks, with at least 30 interior pixels each (else not run); with `albedo-r`, `albedo-g` and `albedo-b`, like surfaces only; with `over`, ground nothing is drawn over |
733
+ | `shadowTint` | T6: lit b* minus shadow b*, points: shadows cooler than the sun, over the masks' interiors as `bounce` | [3, 100] under a clear sun; a probe's `light` moves it (`lightBounds`) | the `lit` and `shadow` masks, with at least 30 interior pixels each (else not run); with `albedo-r`, `albedo-g` and `albedo-b`, like surfaces only; with `over`, ground nothing is drawn over |
734
+ | `nightLuma`, `nightPeak` | T7: mean luma, and the luma of the brightest 1%, of a night frame | [24, 255], [180, 255] | the frame; run only when a shot names them |
735
+
736
+ | Export | What it does |
737
+ | --- | --- |
738
+ | `checkShot({ manifest, read, signal?, pitch?, pixelsPerDegree?, thumbWidth?, columns?, title? })` | Reads each probe of a shot tool manifest (`probes.<name>.file`, `aovs`, and the optional `reference`, `compat`, `still` PNGs, `hdr` raw RGBA float32 file and `viewProjection`) through `read(path)`, runs `checkProbe` with `header.lookBounds` under `header.lookFamily`'s bounds (and `moving: { next, motion }` per probe: a PNG and a raw float32 file of x, y per pixel), a probe's own `probes.<name>.lookBounds` in their place for the checks it names, and resolves `lookReport`. `signal` stops it between probes. |
739
+ | `checkProbe(probe, bounds?, { pitch?, pixelsPerDegree?, family? })` | The rows of one probe `{ name, frame, masks?, hdr?, reference?, compat?, viewProjection?, still?, moving? }`. Masks are one byte or RGBA per pixel, 128 and above inside: `sky`, `water`, `foam`, `dark`, `penumbra`, `plants`, `subject`, `lit` and `shadow` are read. `family` names a look family (below). `pitch` defaults to 8, `pixelsPerDegree` to 67. |
740
+ | `lookReport(probes, { thumbWidth?, columns?, title? })` | `{ pass, json, markdown, sheet }` of `{ name, frame, results }` probes: the table failures first, and a contact sheet of thumbnails (default 270 wide, 4 across) framed green or red and labelled with what failed, each reference check's FLIP map beside its frame. |
741
+ | `skyClip`, `grain`, `speckle`, `banding`, `flat`, `blocks`, `horizonSeam`, `waterSeam`, `lights`, `foamEdges`, `crush`, `flicker`, `shimmer`, `nan` | Each check alone, `(frame, options)` with its `bound` and the options above (`flicker` and `shimmer` take the frames), giving `{ check, value, bound, pass, unit, detail }`. `lights` adds `discs` with their centres and radii. |
742
+ | `flip(test, reference, { pixelsPerDegree?, map? })` | FLIP (Andersson et al. 2020): the difference a viewer sees flipping between two frames, 0 to 1 per pixel, as `{ mean, p50, p95, p99, max }` and the per-pixel `map` with `map: true`. 67 pixels per degree is a 4K monitor at 0.7 m; a phone at 30 cm showing 1080 pixels across 6.5 cm is about 87. `difference(frame, other, 'reference' or 'backends')` is its check row. |
743
+ | `hdrFlip(test, reference, { pixelsPerDegree?, map?, toneMapper?, startExposure?, stopExposure?, exposureMap? })` | HDR-FLIP (Andersson, Nilsson, Shirley and Akenine-Moller 2021) on two linear float frames (RGBA, Float32 or half floats): the largest FLIP error over a range of exposures, pooled as `flip`'s, with `startExposure`, `stopExposure`, `exposures` and, with `exposureMap: true`, the exposure that gave each pixel its error. See "HDR-FLIP" below. |
744
+ | `horizonLine(viewProjection, width, height)`, `maskTopEdge(mask)` | The row per column of the horizon of horizontal planes (column-major view-projection, WebGPU clip space) and of a mask's top edge. NaN where there is none. |
745
+ | `stairs`, `colourEdges`, `chromaSmear`, `penumbra`, `penumbraPlants`, `shimmerMoving`, `motionBlur`, `silhouette`, `silhouetteShape`, `bounce`, `shadowTint`, `albedoOf(frame, masks)`, `GROUND_ALBEDO_LEVELS`, `GROUND_BLOCK`, `PARALLAX_STEP` (1.25: how much farther a surface must be for a camera-moved surface's blur to reach it), `nightLuma`, `nightPeak`, `reprojectionMotion(depth, viewProjection, nextViewProjection, width, height)`, `relativeViewProjections(viewProjection, eye, nextViewProjection, nextEye)` (both matrices moved to the first eye, so far from the origin their float32 translations read no motion in `reprojectionMotion`, KB-SHOT-SUBVEL1), `depthFromDistance(distance, eye, viewProjection, width, height, { water, plane, far })` (NDC depth from each pixel's distance to the eye, for `reprojectionMotion`; pixels with no distance meet the sea plane where `water` is 128 or more, or are `far` away), `detailKeptFloor(family)` (T7: 0.5, and 0.6 for `animatedFeature`, as `LOOK_FAMILY_DETAIL_KEPT`) | The clean-frame checks (below), each alone with its `bound`; `reprojectionMotion` gives the motion of every pixel of a still world seen by a moving camera. |
746
+ | `LOOK_FAMILY_BOUNDS`, `LOOK_FAMILY_NAMES`, `familyBounds(name)` | The look families and their bounds. |
747
+ | `luma(frame)`, `lookBound(bound)`, `LOOK_CHECKS` | BT.709 luma on 0 to 255, a bound as `[low, high]`, and each check's default bound, unit and meaning. |
748
+
749
+ **Flat and banding before the dither** (KB-SHOT-DITHERMOD1, 2026-11-29). The shot tool's 8-bit encode adds a
750
+ triangular dither two levels wide, which breaks every run of identical pixels on the delivered frame, so a flat or banded
751
+ area of the scene shows only in the colours the encode was given. `flat` and `banding` take `codes`, the precise frame
752
+ (RGB floats, sRGB coded 0 to 1), round it to 8-bit codes with no dither (`preDither`), run on both and give the worse
753
+ value, with `detail.frame` and `detail.codes`; `checkProbe` passes a probe's `precise` frame as `codes`. A window left
754
+ identical by the old rectangular dither lies within 1/8192 of one code, so flat on the codes counts every window the
755
+ old encode counted.
756
+
757
+ ```ts
758
+ import { flat, banding, preDither } from '@margoengine/headless/look';
759
+
760
+ const width = 128,
761
+ height = 128,
762
+ // The colours before the encode: one grey, half a level off a code.
763
+ precise = { width, height, data: new Float32Array(width * height * 3).fill(120.5 / 255) },
764
+ frame = { width, height, data: new Uint8Array(width * height * 4) };
765
+ // The delivered frame: 120 or 121 in a pattern, as a dither leaves it.
766
+ for (let i = 0; i < width * height; i++) frame.data.set([120 + (i % 2), 120 + (i % 2), 120 + (i % 2), 255], i * 4);
767
+ const row = flat(frame, { codes: precise });
768
+ console.log(row.detail.frame, row.detail.codes, row.pass); // 0 25 false: the scene is flat
769
+ console.log(banding(frame, { codes: precise }).value, preDither(precise).data[0]); // 0 121
770
+ ```
771
+
772
+ **T6 limits that follow the light** (KB-LOOK-TV-PALL1, 2026-11-26). A probe may carry the light its frame was shaded
773
+ with, `light: { sun: { direction, intensity, colour }, ambient }` (the shot tool records it on every probe: the sun as
774
+ core holds it, `direction` toward the light, and the diffuse light on level ground, irradiance over pi in the same
775
+ units: `Sky.irradiance()` where a sky lights the scene, else `lighting.ambient` x `radiance[3]`). `lightBounds(light,
776
+ base?)` gives its diffuse fraction d, the sky's luminance over the sky's plus the sun's beam on level ground (intensity x
777
+ colour x cos / pi), and the T6 limits for it. A shadow loses the beam and keeps the sky it sees and the light bounced
778
+ into it, both in proportion to the diffuse light, so up to `CLEAR_SUN_DIFFUSE` (0.3336: `erbsDiffuseFraction(0.65)`,
779
+ Erbs, Klein and Duffie 1982, at the clearness index above which a sky is clear, Fakra et al. 2011) the limits stay 10 to
780
+ 35 percent and 3 b*; above it `bounce` is the base x d / 0.3336 (at most 100) and the `shadowTint` floor the base x
781
+ (1 - d) / (1 - 0.3336). `checkProbe` uses them in place of the family's or default limits; a bound the shot names wins.
782
+ Each T6 row records `detail.diffuse`. The timber-valley rail line (2026-11-26): calm, d 0.340 and 0.400 (its sun is 29.5
783
+ degrees up under a cloud deck), limits 10.2 to 35.6 and 12.0 to 42.0 percent, read 17.6 and 28.9; blowup under its smoke
784
+ pall, d 0.943 and 0.942, limits 28.3 to 99.0 and 28.2 to 98.8 percent and tint floors 0.25 and 0.26 b*, read 93.4 and
785
+ 91.3 percent and 0.33 and 0.68 b*: all pass. The same pall frame under a clear sun still fails both, and sunlit-looking
786
+ 20 percent shadows under the pall fail.
787
+
788
+ ```js
789
+ import { lightBounds } from '@margoengine/headless/look';
790
+ const { diffuse, bounce, shadowTint } = lightBounds({
791
+ sun: { direction: [0.87, 0.49, 0], intensity: 0.249, colour: [1, 0.3, 0.04] },
792
+ ambient: [0.33, 0.29, 0.27],
793
+ });
794
+ console.log(diffuse.toFixed(2), bounce.map(Math.round), shadowTint[0].toFixed(2)); // 0.95 [ 28, 99 ] 0.24
795
+ ```
796
+
797
+ **T6 compares within blocks** (KB-LOOK-TV-POOLFAILS1, 2026-11-28). The lit and shadowed ground are compared only
798
+ inside the same block of the frame, `GROUND_BLOCK` (a tenth of its shorter side, 108 pixels at 1080p), as a shadow is
799
+ read across its own edge (Finlayson, Hordley, Lu and Drew, IEEE TPAMI 28(1), 2006), so light that changes across the
800
+ frame, such as a fire's glow in the haze, does not read as the shadow's. `detail.strata` counts block and albedo strata
801
+ both sides hold.
802
+
803
+ ```js
804
+ import { bounce, GROUND_BLOCK } from '@margoengine/headless/look';
805
+
806
+ const size = 60,
807
+ frame = { width: size, height: size, data: new Uint8Array(size * size * 4) },
808
+ mask = (inside) => ({ width: size, height: size, data: Uint8Array.from({ length: size * size }, (_, i) => (inside(i % size) ? 255 : 0)) });
809
+ for (let i = 0; i < size * size; i++) frame.data.set(i % size % 6 < 3 ? [200, 200, 200, 255] : [120, 120, 120, 255], i * 4);
810
+ const row = bounce(frame, { lit: mask((x) => x % 6 < 3), shadow: mask((x) => x % 6 >= 3) });
811
+ console.log(GROUND_BLOCK, Math.round(row.value)); // 0.1 33
812
+ ```
813
+
814
+ **T6 compares like surfaces** (KB-LOOK-TV-TINTMATCH1, 2026-11-28). `bounce` and `shadowTint` take an optional `albedo`,
815
+ an RGBA image of each pixel's surface colour (sRGB coded): the lit and shadowed ground are then cut into strata of like
816
+ albedo (`GROUND_ALBEDO_LEVELS`, 16 per channel), each stratum's lit and shadowed means are compared alone, and the
817
+ strata are pooled with the Cochran-Mantel-Haenszel weight n_lit x n_shadow / (n_lit + n_shadow) (Cochran 1954, Mantel
818
+ and Haenszel 1959), so a surface seen only in the sun or only in the shade does not count. `albedoOf(frame, masks)`
819
+ builds it from three grey masks `albedo-r`, `albedo-g` and `albedo-b` (one channel each, as the shot tool writes an
820
+ AOV), and `checkProbe` passes it on when a probe has all three. Each row then records `detail.matched` (pixels in strata
821
+ both sides hold) and `detail.strata`; with no stratum on both sides the check reports `missing`. Without an albedo the
822
+ ground is one stratum, as before. Bounds unchanged. The timber-valley blowup read mid bounce 103.6 percent (shadowed
823
+ ground brighter than lit, which one surface under one light cannot be) and shadowTint 0.036 b*: its masks held
824
+ different surfaces.
825
+
826
+ ```ts
827
+ import { albedoOf, shadowTint } from '@margoengine/headless/look';
828
+ const size = 64,
829
+ plane = (v: number) => ({ width: size, height: size, data: new Uint8Array(size * size).fill(v) }),
830
+ half = (left: boolean) => ({ width: size, height: size, data: Uint8Array.from({ length: size * size }, (_, i) => ((i % size < 32) === left ? 255 : 0)) }),
831
+ frame = { width: size, height: size, data: new Uint8Array(size * size * 4) };
832
+ for (let i = 0; i < size * size; i++) frame.data.set(i % size < 32 ? [214, 180, 130, 255] : [92, 88, 96, 255], i * 4);
833
+ const albedo = albedoOf(frame, { 'albedo-r': plane(180), 'albedo-g': plane(150), 'albedo-b': plane(110) });
834
+ const row = shadowTint(frame, { lit: half(true), shadow: half(false), albedo });
835
+ console.log(row.value.toFixed(1), row.pass, row.detail.strata); // 34.1 true 1
836
+ ```
837
+
838
+ **T6 reads the light, surface over albedo** (KB-LOOK-TV-POOLFAILS1, 2026-11-28). With an albedo each side's value is its
839
+ light: the stratum's luminance over its albedo's luminance, sums over sums (a ratio estimator, Cochran, "Sampling
840
+ Techniques", 1977), as a Lambertian surface's luminance divides out to its shading (Barrow and Tenenbaum 1978). A
841
+ stratum spans 16 codes, a 1.4 times range of dark albedo, and under a smoke pall, where the sun is under 2 percent of the
842
+ light, the slightly lighter shadowed ground of the timber-valley valley-aerial shot read 101 percent bounce; its light
843
+ reads 99.2 percent, the pall predicting 98.3. Without an albedo the value is the mean luminance, as before.
844
+
845
+ ```js
846
+ import { albedoOf, bounce } from '@margoengine/headless/look';
847
+
848
+ const size = 60,
849
+ lin = (c) => ((c / 255 + 0.055) / 1.055) ** 2.4,
850
+ code = (x) => (x % 6 < 3 ? 64 : 72), // sun on code 64 ground, shade on code 72: one stratum
851
+ shade = (x) => Math.round(255 * 1.055 * (0.5 * lin(code(x)) * (x % 6 < 3 ? 1 : 0.3)) ** (1 / 2.4) - 255 * 0.055),
852
+ frame = { width: size, height: size, data: new Uint8Array(size * size * 4) },
853
+ mask = (inside) => ({ width: size, height: size, data: Uint8Array.from({ length: size * size }, (_, i) => (inside(i % size) ? 255 : 0)) }),
854
+ plane = { width: size, height: size, data: Uint8Array.from({ length: size * size }, (_, i) => code(i % size)) };
855
+ for (let i = 0; i < size * size; i++) frame.data.set([shade(i % size), shade(i % size), shade(i % size), 255], i * 4);
856
+ const albedo = albedoOf(frame, { 'albedo-r': plane, 'albedo-g': plane, 'albedo-b': plane });
857
+ const row = bounce(frame, { lit: mask((x) => x % 6 < 3), shadow: mask((x) => x % 6 >= 3), albedo });
858
+ console.log(Math.round(row.value), row.pass); // 31 true (the shade's light is 30 percent; luminance alone reads 39)
859
+ ```
860
+
861
+ **T6 bounce reads the light before the haze** (KB-LOOK-TV-HAZEBOUNCE1, 2026-11-30). A haze adds the same airlight to lit
862
+ and shadowed ground, and the tone curve bends both, so a frame's luminance lifts the shadowed side's share: under a smoke
863
+ pall, where the sun is 1 percent of the ground's light, the timber-valley blowup read 101.6 percent. `radiance` (a
864
+ `RadianceFrame`, one float of linear luminance a pixel at any one scale) gives each pixel's light before the haze and
865
+ tone map; `bounce` reads it in place of the frame's luminance and `detail.radiance` is 1. The frame still gives b* for
866
+ `shadowTint`. Every pooled frame then needs its own, since a frame's luminance and another's radiance do not add. The
867
+ shot tool writes it as the `radiance` light image (`probes/<name>.radiance.f32`, from the `texture` of a
868
+ `@margoengine/sky/aov` `fogInputCapture` given as a sky's `fog.keepInput`) and `checkShot` reads it.
869
+
870
+ ```js
871
+ import { bounce } from '@margoengine/headless/look';
872
+
873
+ const size = 64,
874
+ light = (x) => (x < 32 ? 0.5 : 0.1), // the ground's own light: shade 20 percent of the sun
875
+ code = Math.round(255 * (1.055 * (0.1 + 0.3) ** (1 / 2.4) - 0.055)),
876
+ frame = { width: size, height: size, data: new Uint8Array(size * size * 4) },
877
+ mask = (inside) => ({ width: size, height: size, data: Uint8Array.from({ length: size * size }, (_, i) => (inside(i % size) ? 255 : 0)) }),
878
+ radiance = { width: size, height: size, data: Float32Array.from({ length: size * size }, (_, i) => light(i % size)) };
879
+ for (let i = 0; i < size * size; i++) {
880
+ const c = i % size < 32 ? Math.round(255 * (1.055 * (0.5 + 0.3) ** (1 / 2.4) - 0.055)) : code; // 0.3 airlight on both
881
+ frame.data.set([c, c, c, 255], i * 4);
882
+ }
883
+ const options = { lit: mask((x) => x < 32), shadow: mask((x) => x >= 32) };
884
+ console.log(Math.round(bounce(frame, options).value), Math.round(bounce(frame, { ...options, radiance }).value)); // 50 20
885
+ ```
886
+
887
+ **T4 leaves out what the next frame covers** (KB-LOOK-TV-SHIMMER2, 2026-11-28). `MovingFrames.back`, each pixel of the
888
+ next frame moved back to this one, makes `shimmerMoving` skip a pixel whose motion and the motion back from where it
889
+ lands do not cancel, |f + b|^2 > 0.01 (|f|^2 + |b|^2) + 0.5 pixels (the forward-backward test, Sundaram, Brox and Keutzer
890
+ 2010): the next frame covers or uncovers it, so it has no match to shimmer against. `detail.occluded` counts them; the
891
+ shot tool writes `moving.back` for every moving probe.
892
+
893
+ **T4 leaves out what moves on purpose** (KB-LOOK-TV-SHIMMER2, 2026-11-28). `MovingFrames.velocity` and `nextVelocity`,
894
+ the engine's own motion of each pixel of this frame and of the next (TAA's velocity with its jitter removed, pixels over
895
+ one frame), make `shimmerMoving` skip a pixel whose surface, or the one its camera motion f lands on, the engine moved
896
+ otherwise, |v - f| > 0.5 pixels: a swaying branch, a flame or a wave, and the sky a branch leaves, change on purpose, so
897
+ they are not shimmer. `detail.animated` counts them; the shot tool writes both when the shot sets
898
+ `moving.velocity: true`.
899
+
900
+ ```js
901
+ import { shimmerMoving } from '@margoengine/headless/look';
902
+
903
+ const size = 8,
904
+ image = () => ({ width: size, height: size, data: new Uint8Array(size * size * 4).fill(128) }),
905
+ motion = { width: size, height: size, data: new Float32Array(size * size * 2) },
906
+ velocity = { width: size, height: size, data: new Float32Array(size * size * 2).fill(1) };
907
+ const row = shimmerMoving(image(), { next: image(), motion, velocity });
908
+ console.log(row.detail.animated); // 64: every pixel moved 1 px more than the still camera
909
+ ```
910
+
911
+ **T4 warps sub-pixel motion along the engine's velocity** (KB-LOOK-TV-POOLFAILS1, 2026-11-29). Grass swaying a quarter
912
+ of a pixel a frame moves less than `animated` leaves out, and a camera-only warp read it as shimmer: on the still
913
+ timber-valley shot in wind, 0.82 percent of the frame, coherent sway at 20 to 30 m (along the wind's screen direction,
914
+ |cos| 0.92 against 0.64 for random directions; frame to frame cosine 0.84). With `velocity` and `nextVelocity`, a
915
+ pixel it still counts lands where the engine's motion takes it, q = p + nextVelocity(q) (reprojection along motion
916
+ vectors: Nehab et al., "Accelerating Real-Time Shading with Reverse Reprojection Caching", Graphics Hardware 2007,
917
+ https://doi.org/10.2312/EGGH/EGGH07/025-036; the warping error of Lai et al., "Learning Blind Video Temporal
918
+ Consistency", ECCV 2018, https://doi.org/10.1007/978-3-030-01267-0_11), only when that motion matches the pixel: steady
919
+ (within 0.05 px plus a quarter of its own motion of the pixel's velocity from the frame before), like its 3 x 3
920
+ neighbours' (the same bound from their median) and, with both distances, on the same surface (within 5 percent).
921
+ Elsewhere it keeps the camera's warp. `detail.reprojected` counts the pixels that took the velocity, and
922
+ `MovingFrames.reproject: 'camera'` (or `checkShot` `reproject`) keeps the camera's warp everywhere. Sparkle, aliased
923
+ alpha-tested blades and vectors aimed at a fault still fail.
924
+
925
+ ```js
926
+ import { shimmerMoving } from '@margoengine/headless/look';
927
+
928
+ const size = 64,
929
+ shade = (u) => 128 + 60 * Math.sin((2 * Math.PI * u) / 8),
930
+ frame = (shift) => {
931
+ const data = new Uint8Array(size * size * 4);
932
+ for (let i = 0; i < size * size; i++) data.fill(Math.round(shade((i % size) - shift)), i * 4, i * 4 + 3), (data[i * 4 + 3] = 255);
933
+ return { width: size, height: size, data };
934
+ },
935
+ field = (v) => ({ width: size, height: size, data: new Float32Array(size * size * 2).map((_, k) => (k % 2 ? 0 : v)) }),
936
+ motion = field(0); // a still camera; the surface sways 0.3 px a frame
937
+ const moving = { next: frame(0.3), motion, velocity: field(0.3), nextVelocity: field(0.3) };
938
+ console.log(shimmerMoving(frame(0), { ...moving, reproject: 'camera' }).value); // 75: the sway reads as shimmer
939
+ console.log(shimmerMoving(frame(0), moving).value); // 0: along the velocity it is motion
940
+ ```
941
+
942
+ **T4 leaves out what a moving surface's blur reaches** (KB-LOOK-TV-SHIMMER2, 2026-11-28). Motion blur smears a swaying
943
+ branch over the still sky beside it, so that sky changes on purpose too. With `velocity`, `shimmerMoving` also skips a
944
+ pixel within the blur radius of a surface the engine moves other than the camera: half that surface's motion over the open
945
+ shutter (`MovingFrames.shutter`, default 180 degrees), at most `MovingFrames.maxBlur` (default 32 px, `MotionBlur`'s
946
+ `maxBlur`), never further than the blur really draws. The search is the reconstruction filter of McGuire, Hennessy,
947
+ Bukowski and Osman ("A Reconstruction Filter for Plausible Motion Blur", I3D 2012, https://doi.org/10.1145/2159616.2159639),
948
+ as `@margoengine/post/motion-blur` draws it: the longest radius per `maxBlur` tile, the longest over each tile's 3 x 3
949
+ neighbours, then a walk along it. `detail.blurred` counts them; a flashing pixel on a still edge beyond the reach still
950
+ fails.
951
+
952
+ ```js
953
+ import { shimmerMoving } from '@margoengine/headless/look';
954
+
955
+ const width = 16,
956
+ height = 4,
957
+ image = () => ({ width, height, data: new Uint8Array(width * height * 4).fill(128) }),
958
+ motion = { width, height, data: new Float32Array(width * height * 2) },
959
+ velocity = { width, height, data: new Float32Array(width * height * 2) };
960
+ for (let y = 0; y < height; y++) velocity.data[(y * width + 8) * 2] = 8; // column 8 sways 8 px a frame
961
+ const row = shimmerMoving(image(), { next: image(), motion, velocity });
962
+ console.log(row.detail.animated, row.detail.blurred); // 4 16: its 2 px smear each way is left out
963
+ ```
964
+
965
+ **T4 follows a mover's whole screen motion and its sub-frames** (KB-SCATTER-FRINGEVEL1, 2026-11-28). The smear is drawn
966
+ in screen space, so its length is the mover's whole velocity over the shutter, the camera's part included: a leaf near
967
+ the lens moving 63 px a frame, 10 px of it its sway, smears 31 px over the still sky behind it, not the 2.5 px its sway
968
+ alone gives. Only pixels whose own surface moves otherwise (velocities more than half a pixel apart) are reached. A
969
+ frame that is the mean of `MovingFrames.subframes` sub-frames (the shot tool's kept frames; `checkShot` passes the
970
+ render's `subframes` when it has a shutter) holds the last sub-frame's velocity, so the trail runs back from the mover
971
+ over its travel between the first and last sub-frame, plus half a slice's blur at either end, and reaches only half a
972
+ slice ahead. With `nextVelocity` and `back`, a pixel landing in the next frame's trail is left out the same way.
973
+
974
+ ```js
975
+ import { shimmerMoving } from '@margoengine/headless/look';
976
+
977
+ const width = 64,
978
+ height = 2,
979
+ image = () => ({ width, height, data: new Uint8Array(width * height * 4).fill(128) }),
980
+ motion = { width, height, data: new Float32Array(width * height * 2) },
981
+ velocity = { width, height, data: new Float32Array(width * height * 2) };
982
+ for (let y = 0; y < height; y++) {
983
+ motion.data[(y * width + 50) * 2] = 53; // a near leaf at column 50: the camera moves it 53 px
984
+ velocity.data[(y * width + 50) * 2] = 63; // and its sway 10 px more
985
+ }
986
+ const row = shimmerMoving(image(), { next: image(), motion, velocity, subframes: 8 });
987
+ console.log(row.detail.blurred); // 64: 30 px of trail behind the leaf and 2 px ahead, in each row
988
+ ```
989
+
990
+ **T4 leaves out the camera's parallax trails, given the distance** (KB-LOOK-TV-POOLFAILS1, 2026-11-29). A camera
991
+ running past near trunks smears each one over the far forest behind it even when nothing sways: on the timber-valley
992
+ rail-line a trunk 22 m off moves 14.6 px a frame and the forest 200 m behind it 2 px, so a 180 degree shutter leaves a
993
+ 7 px ramp on both sides of the trunk, and the one behind it is gone by the next frame. With `MovingFrames.distance` (and
994
+ `nextDistance` for the next frame; the shot tool writes `probes/<name>.distance.f32` and `next-distance.f32`), a
995
+ surface the camera alone moves on screen smears too, but only over a surface at least `PARALLAX_STEP` (1.25) times as
996
+ far: the depth test of the reconstruction filter, so a far surface never reaches over a nearer one and one sloping
997
+ surface never reaches along itself. Without the distance nothing changes. A flash 6 px past a trail still fails.
998
+
999
+ ```js
1000
+ import { shimmerMoving } from '@margoengine/headless/look';
1001
+
1002
+ const width = 64,
1003
+ height = 2,
1004
+ image = () => ({ width, height, data: new Uint8Array(width * height * 4).fill(128) }),
1005
+ trunk = (i) => i % width >= 40 && i % width < 44, // a trunk 22 m off at columns 40 to 43, the forest 200 m behind
1006
+ motion = { width, height, data: new Float32Array(width * height * 2).map((_, k) => (k % 2 ? 0 : trunk(k / 2) ? 14 : 2)) },
1007
+ distance = { width, height, data: new Float32Array(width * height).map((_, i) => (trunk(i) ? 22 : 200)) };
1008
+ const row = shimmerMoving(image(), { next: image(), motion, velocity: motion, subframes: 8, distance });
1009
+ console.log(row.detail.animated, row.detail.blurred); // 0 14: nothing sways; 7 px of trail behind the trunk, each row
1010
+ ```
1011
+
1012
+ **T4 lets a water surface's reflection change with the view** (KB-LOOK-TV-CREEKWATER1, 2026-11-29). A camera running
1013
+ 1 m over a creek at 8 m/s looks ever more steeply down at the water near it, so the water's reflection (its Fresnel
1014
+ share) dims 5 to 11 percent a frame there while its pattern stays put: on the timber-valley creek that was 82,000 off
1015
+ pixels, 4.36 percent of the frame, though the dry bank beside it warped exactly. With `MovingFrames.waterSurface` (the
1016
+ water's own mask, `Water.surfaceTexture` from `@margoengine/water`, the shot's `water-surface` AOV), a pixel marked at
1017
+ least half is compared after a local gain: the next frame's warped mean over this frame's mean, across the water pixels
1018
+ within `WATER_GAIN_RADIUS` (8, a 17 x 17 window: the largest radius over which the creek's measured Fresnel gain
1019
+ field changes a window's gain by under half the 6-code threshold for 99.9 percent of its water pixels). That is a multiplicative brightness field as in Gennert and
1020
+ Negahdaripour ("Relaxing the Brightness Constancy Assumption in Computing Optical Flow", MIT AI Memo 975, 1987), so a
1021
+ smooth slope across the surface passes while a sparkle, point-sampled crests flickering a pixel apart, or the same dimming
1022
+ on ground the mask does not mark (fire or smoke over the water included) still fails. `detail.water` counts the pixels
1023
+ gained; `checkProbe` passes the probe's `water-surface` mask by itself.
1024
+
1025
+ ```js
1026
+ import { shimmerMoving } from '@margoengine/headless/look';
1027
+
1028
+ const width = 32,
1029
+ height = 32,
1030
+ image = (shade) => ({ width, height, data: new Uint8Array(width * height * 4).fill(shade) }),
1031
+ motion = { width, height, data: new Float32Array(width * height * 2) },
1032
+ waterSurface = image(255); // all water
1033
+ const moving = { next: image(110), motion, waterSurface }; // the reflection dims 120 to 110 as the view steepens
1034
+ console.log(shimmerMoving(image(120), { next: image(110), motion }).value); // 100: read as shimmer without the mask
1035
+ console.log(shimmerMoving(image(120), moving).value, shimmerMoving(image(120), moving).detail.water); // 0 1024
1036
+ ```
1037
+
1038
+ **T4 leaves out a flame's own animation** (KB-LOOK-TV-FLAMEMASK1, 2026-11-29). With `MovingFrames.flame` and
1039
+ `nextFlame` (the engine's flame mask, `watchFlameCoverage` of `@margoengine/vfx/flame`: the shot's `flame` AOV and the
1040
+ next frame's copy the shot tool writes beside the probe), a pixel whose flame mask is above zero in this frame, or at its
1041
+ landing in the next, is the flame's own animation and is left out; no threshold is chosen. Smoke, embers and the glow
1042
+ are not in the mask, so a surface seen through them still counts, and all-zero masks (no fire) give the result without
1043
+ them byte for byte. On town-street early, 25,288 of 30,177 off pixels were the flames. `detail.flame` counts the pixels
1044
+ left out; `checkProbe` passes the probe's `flame` mask and the moving entry's `nextFlame` by themselves.
1045
+
1046
+ ```js
1047
+ import { shimmerMoving } from '@margoengine/headless/look';
1048
+
1049
+ const width = 32,
1050
+ height = 32,
1051
+ image = (pixel) => ({ width, height, data: Uint8Array.from({ length: width * height * 4 }, (_, i) => pixel(i >> 2)) }),
1052
+ motion = { width, height, data: new Float32Array(width * height * 2) },
1053
+ flicker = (t) => image((i) => (i % width < 16 ? (i * 37 + t * 91) % 256 : 120)), // a flame flickering on the left
1054
+ flame = image((i) => (i % width < 16 ? 255 : 0));
1055
+ console.log(shimmerMoving(flicker(0), { next: flicker(1), motion }).value > 40); // true: the flame read as shimmer
1056
+ const masked = shimmerMoving(flicker(0), { next: flicker(1), motion, flame, nextFlame: flame });
1057
+ console.log(masked.value, masked.detail.flame); // 0 512
1058
+ ```
1059
+
1060
+ **T8 fails a stepped trail** (KB-LOOK-TV-SUBSTEP1, 2026-11-28). A frame drawn as sharp copies, one per sub-frame, spans
1061
+ the shutter's smear but climbs in jumps between flat steps. `motionBlur` also calls an edge sharp when its ramp (the run
1062
+ between 10 and 90 percent around the edge, at least 8 pixels) climbs one way in three or more separate jumps, each over
1063
+ 12 codes and over twice the ramp's mean climb a pixel. A smooth smear climbs evenly, steepest once in its middle; texture
1064
+ and thin objects, which fall back by over 12 codes inside the run, are not staircases.
1065
+
1066
+ **T6 reads the precise frame and pools frames** (KB-LOOK-TV-TINTRES1, 2026-11-28). `bounce` and `shadowTint` also take
1067
+ `precise`, the frame before its 8 bits (RGB float32, sRGB coded 0 to 1: the shot tool's `probes/<name>.rgb32f`), read in
1068
+ place of the 8-bit frame, and `pool`, more frames of the shot (each its `precise` or `frame` with `lit`, `shadow` and
1069
+ `albedo`, or `groundSample(...)` of one, its strata alone) whose strata add to the probe's. `detail.se` is the value's
1070
+ standard error: the pixels' with one frame, and with more the larger of that and the batch-means error over the frames
1071
+ (Schmeiser 1982), since neighbouring frames see much the same ground; `detail.frames` counts them. A shot asks for this
1072
+ with `probePool: {frames, step}` (docs/shots.md), and `checkShot` reads a probe's `precise` and `pool`.
1073
+
1074
+ ```ts
1075
+ import { groundSample, shadowTint } from '@margoengine/headless/look';
1076
+ const size = 32,
1077
+ half = (left: boolean) => ({ width: size, height: size, data: Uint8Array.from({ length: size * size }, (_, i) => ((i % size < 16) === left ? 255 : 0)) }),
1078
+ frame = { width: size, height: size, data: new Uint8Array(size * size * 4).fill(60) },
1079
+ // One 8-bit colour, but in the floats the shadow's blue is 0.4 of a code higher: a cooler shadow.
1080
+ precise = () => ({ width: size, height: size, data: Float32Array.from({ length: size * size * 3 }, (_, i) => (60 + (i % 3 === 2 ? ((i / 3) % size < 16 ? -0.2 : 0.2) : 0)) / 255) }),
1081
+ lit = half(true),
1082
+ shadow = half(false);
1083
+ const pool = [precise(), precise()].map((p) => groundSample({ precise: p, lit, shadow }));
1084
+ const row = shadowTint(frame, { lit, shadow, precise: precise(), pool });
1085
+ console.log(row.value > 0, row.detail.frames); // true 3
1086
+ ```
1087
+
1088
+ **T6 leaves out ground an effect is drawn over** (KB-LOOK-TV-TINTRES1, 2026-11-28). `bounce` and `shadowTint` take an
1089
+ optional `over` mask (0 to 255, also on each pooled `GroundFrame`): what is drawn over the scene's surfaces after them,
1090
+ such as a flame's or smoke's coverage. Ground any of it covers is left out, since its colour is partly the effect's and
1091
+ not the ground's light; `checkProbe` and `checkShot` take it from a probe's `over` AOV. Each row then records
1092
+ `detail.over`, the percent of the ground interior left out, and reports `missing` when fewer than `GROUND_MIN_PIXELS`
1093
+ (30) lit or shadowed pixels are left, the usual floor for a normal sample mean (Hogg, Tanis and Zimmerman 2015). A real
1094
+ tint fault on ground nothing covers still fails. The shot tool gets it from
1095
+ TAA's `reactiveMask` (the coverage flames, smoke, weather and water already draw for TAA; the timber-valley shot page
1096
+ gives it). The timber-valley blowup's T6 drifted 3.6 b* from frame to frame because its flame volumes, which move and
1097
+ flicker along the shot, sat on ground the sun's masks counted: with the flames' opacity at 0 the spread was 0.9 b*,
1098
+ while the flames' glow, the embers, the fire's light on the haze and the smoke columns each left it unchanged.
1099
+
1100
+ ```ts
1101
+ import { shadowTint } from '@margoengine/headless/look';
1102
+ const size = 32,
1103
+ half = (left: boolean) => ({ width: size, height: size, data: Uint8Array.from({ length: size * size }, (_, i) => ((i % size < 16) === left ? 255 : 0)) }),
1104
+ frame = { width: size, height: size, data: new Uint8Array(size * size * 4) },
1105
+ over = { width: size, height: size, data: new Uint8Array(size * size) };
1106
+ for (let i = 0; i < size * size; i++) {
1107
+ const x = i % size, y = (i / size) | 0, flame = x >= 20 && y < 12;
1108
+ frame.data.set(x < 16 ? [200, 170, 120, 255] : flame ? [255, 150, 40, 255] : [70, 72, 84, 255], i * 4);
1109
+ if (flame) over.data[i] = 255;
1110
+ }
1111
+ const drawn = shadowTint(frame, { lit: half(true), shadow: half(false) }),
1112
+ ground = shadowTint(frame, { lit: half(true), shadow: half(false), over });
1113
+ console.log(drawn.value < ground.value, ground.pass); // true true
1114
+ ```
1115
+
1116
+ **T6 needs 30 umbra pixels to run** (KB-LOOK-TV-POOLFAILS1, 2026-11-29). With or without `over`, `bounce` and
1117
+ `shadowTint` read nothing from fewer than `GROUND_MIN_PIXELS` (30) shadowed ground pixels in full umbra (the `shadow`
1118
+ mask's interior, summed over the pooled frames) or lit ones: a handful gives a value from noise, which could pass.
1119
+ Such a row is `notRun: true` with `pass: false` and a NaN value, and its `missing` names the count against the 30
1120
+ needed. `checkProbe` reports it under a family, an empty shadow mask included; `lookReport` prints it as "not run" and
1121
+ leaves it out of the probe's verdict, so it is neither a pass nor a failure. A bound the shot names itself in
1122
+ `lookBounds` still fails it. The timber-valley rail-line has no opaque caster's umbra in frame (its sun is behind the
1123
+ camera, every trunk's shadow falls behind its own tree): its T6 rows read not run, with the count.
1124
+
1125
+ ```ts
1126
+ import { bounce } from '@margoengine/headless/look';
1127
+ const size = 64,
1128
+ inShadow = (i: number) => i % size >= 20 && i % size < 27 && ((i / size) | 0) >= 20 && ((i / size) | 0) < 27,
1129
+ mask = (shadowed: boolean) => ({ width: size, height: size, data: Uint8Array.from({ length: size * size }, (_, i) => (inShadow(i) === shadowed ? 255 : 0)) }),
1130
+ frame = { width: size, height: size, data: new Uint8Array(size * size * 4) };
1131
+ for (let i = 0; i < size * size; i++) frame.data.set(inShadow(i) ? [96, 100, 118, 255] : [230, 200, 150, 255], i * 4);
1132
+ const row = bounce(frame, { lit: mask(false), shadow: mask(true) });
1133
+ console.log(row.notRun, row.pass, row.missing.includes('counted 25 umbra')); // true false true
1134
+ ```
1135
+
1136
+ **Clean frames and look families.** The clean-frame checks are the look bar of the animated-feature film (T1 to T8, private roadmap section 3): no grain, banding, stairs or shimmer, shapes that read, bounce light in the shadows, colour that survives YouTube's 4:2:0 H.264 and motion that is blurred. `checkProbe(probe, bounds, { family: 'animatedFeature' })` (or `lookFamily: "animatedFeature"` in a shot file) holds every check the probe can run to the family's bound: grain 0.5 codes, penumbra 0.7, penumbraPlants 1, speckle 5 ppm, banding 0.2%, stairs 1%, still shimmer 0.1% and flicker 0.3, `shimmerMoving` 0.5%, crush 0.1%, the reference FLIP 0.04, plus the ranges above. A check whose input the probe lacks is left out under a family (a shot that names it in `lookBounds` still fails it as missing); a mask that marks no pixel counts as lacking, so a frame with no subject runs no `silhouette` (T6 instead reports too little ground as not run, above), and a shot's own `lookBounds` win by name. `natural` keeps every default. `stairs` and `colourEdges` read the frame alone. A step was once judged against the climb along its own row, which misread an antialiased edge near a pixel axis (one pixel of coverage 0.1 per row is a tenth of the climb on one side and nine tenths on the other): a 16 sample per pixel render of the storm-light shot read 15% `stairs`. They now look for a value between the plateaus around the step; on that shot msaa 1 reads 5.70% over the whole frame (5.98% on the crop in `tests/fixtures/look-real`, against 30.6% by the old test), msaa 4 at supersample 1, 1.5 and 2 read 0.10, 0.00 and 0.01%, and the 16 sample reference 0.00%. The flood draft shots (msaa 1, supersample 1) read 2.7 to 22.7%, which is real aliasing: they are not rendered at the film setting.
1137
+
1138
+ ```ts
1139
+ import { checkProbe, familyBounds } from '@margoengine/headless/look';
1140
+
1141
+ // A dark disc on pale haze with a resolved (antialiased) edge: the family's stairs bound is 1%.
1142
+ const size = 48,
1143
+ data = new Uint8Array(size * size * 4);
1144
+ for (let y = 0; y < size; y++)
1145
+ for (let x = 0; x < size; x++) {
1146
+ const d = Math.hypot(x - 24, y - 24),
1147
+ v = Math.round(210 - 180 * Math.min(1, Math.max(0, 12.5 - d)));
1148
+ data.set([v, v, v, 255], (y * size + x) * 4);
1149
+ }
1150
+ const rows = checkProbe({ name: 'disc', frame: { width: size, height: size, data } }, {}, { family: 'animatedFeature' });
1151
+ const stairs = rows.find((row) => row.check === 'stairs')!;
1152
+ console.log(familyBounds('animatedFeature').stairs, stairs.value, stairs.pass); // [0, 1] 0 true
1153
+ ```
1154
+
1155
+ **HDR-FLIP.** `flip` compares two 8-bit frames as shown. A float frame before tone mapping can hide errors that only
1156
+ some exposure shows: noise in a dim corner is invisible at the exposure that suits a lamp. `hdrFlip(test, reference)`
1157
+ exposure compensates both float frames by 2^c, tone maps them (default `'aces'`, Narkowicz's fit as `acesNarkowicz`
1158
+ has it; `'reinhard'`; or the six coefficients of a curve (k0 x^2 + k1 x + k2) / (k3 x^2 + k4 x + k5)), clamps them to
1159
+ 0..1 and keeps each pixel's largest FLIP error over max(2, ceil(stop - start)) exposures spread evenly from
1160
+ `startExposure` to `stopExposure`. By default the start maps the reference's largest luminance to 0.85 after the curve
1161
+ and the stop its median, so every test frame of one reference is judged over the same exposures. Negative, NaN or
1162
+ infinite values reject with a RangeError (run `nan` first), and so does a reference whose largest or median luminance
1163
+ is 0 unless both exposures are given. It costs one FLIP per exposure.
1164
+
1165
+ ```ts
1166
+ import { hdrFlip } from '@margoengine/headless/look';
1167
+
1168
+ // A lamp (luminance 40) over a dim wall; the test frame's wall is 20 percent too dark.
1169
+ const width = 32,
1170
+ height = 32;
1171
+ const frame = (wall: number) => {
1172
+ const data = new Float32Array(width * height * 4);
1173
+ for (let i = 0; i < width * height; i++) {
1174
+ const lamp = i % width > 20 && Math.floor(i / width) < 8;
1175
+ data.set(lamp ? [40, 40, 40, 1] : [wall, wall, wall, 1], i * 4);
1176
+ }
1177
+ return { width, height, data };
1178
+ };
1179
+ const result = hdrFlip(frame(0.04), frame(0.05));
1180
+ console.log(result.startExposure.toFixed(2), result.stopExposure.toFixed(2), result.exposures, result.mean.toFixed(3)); // -4.24 5.41 10 0.199
1181
+ ```
1182
+
1183
+ Default bounds are starting values for a 1080 x 1920 short; a scene kit or shot file sets its own. FLIP keeps about 30
1184
+ float planes of the frame's size while it runs, the other checks one or two. Frames and masks of different sizes
1185
+ reject with a RangeError.
1186
+
1187
+ ## JPEG, WebP and EXR files
1188
+
1189
+ `@margoengine/headless/formats` writes the pixels you read as the files previews and HDR captures need. Nothing here
1190
+ loads a codec: JPEG and lossless WebP are written in plain code, so they work in Node, a worker and a page.
1191
+
1192
+ ```ts
1193
+ import { writeFile } from 'node:fs/promises';
1194
+ import { readPixels, createHeadlessCanvas, installGPU } from '@margoengine/headless';
1195
+ import { encodeEXR, encodeJPEG, encodeWebP, readTexture } from '@margoengine/headless/formats';
1196
+ import { Engine, box, Camera } from '@margoengine/core';
1197
+ import { PostStack } from '@margoengine/post/stack';
1198
+ import { Bloom } from '@margoengine/post/bloom';
1199
+ import { create } from 'webgpu';
1200
+
1201
+ using installed = installGPU({ gpu: create([]) });
1202
+ const engine = await Engine.create(createHeadlessCanvas({ width: 512, height: 512 }), { backend: 'webgpu' });
1203
+ engine.createMesh().setGeometry(box());
1204
+ engine.render({ camera: new Camera({ position: [2, 2, 3], target: [0, 0, 0] }) });
1205
+ const stack = PostStack.attach(engine, [new Bloom({ strength: 0.6 })]);
1206
+ engine.render({ camera: new Camera({ position: [2, 2, 3], target: [0, 0, 0] }) });
1207
+
1208
+ const pixels = await readPixels(engine);
1209
+ await writeFile('preview.jpg', encodeJPEG(pixels, { quality: 85 }));
1210
+ await writeFile('preview.webp', await encodeWebP(pixels));
1211
+ await writeFile('frame.exr', await encodeEXR(await readTexture(engine, stack.sceneTexture!), { type: 'float' }));
1212
+ ```
1213
+
1214
+ | Export | What it does |
1215
+ | --- | --- |
1216
+ | `encodeJPEG(pixels, { quality?, subsampling?, background? })` | A baseline JPEG. `quality` is 1 to 100, default 90, scaled as other JPEG tools scale it. `subsampling` is `'420'` (default, smaller) or `'444'` (sharper colour edges). JPEG has no alpha, so pixels are laid over `background`, default white. |
1217
+ | `encodeWebP(pixels, { quality? })` | Unset `quality`: lossless WebP, the same pixels back, with alpha, in any runtime. `quality` 0 to 1: lossy WebP through the runtime's own encoder, so it needs `OffscreenCanvas` and WebP support (a browser or worker). Rejects, never gives a PNG in its place. |
1218
+ | `encodeEXR(hdr, { type?, signal? })` | Float RGBA as an uncompressed OpenEXR file. `type` is `'half'` (default) or `'float'`. Written by `@margoengine/environment/exr-write`, an optional peer loaded on first use. |
1219
+ | `readTexture(engine, texture, { signal? })` | Reads an `rgba16float` or `rgba32float` texture with `COPY_SRC` usage to `{ width, height, data }` float pixels. `stack.sceneTexture` from `@margoengine/post/stack` is the linear frame before tone mapping, where values go over 1. |
1220
+ | `linearPixels(pixels)` | Undoes the sRGB curve of display pixels, for an EXR of an 8-bit frame. Alpha stays linear. |
1221
+
1222
+ The engine's own output is tone-mapped sRGB, so an EXR made from `readPixels` holds display values, not scene light.
1223
+ For a capture with true highlights, read `stack.sceneTexture`. Images are at most 65,535 pixels wide for JPEG and 16,384 for WebP.
1224
+
1225
+ The errors are listed at [margoengine.com/errors#headless](https://margoengine.com/errors#headless).
1226
+
1227
+ ### Headless stage error callback
1228
+
1229
+ `createHeadlessStage` accepts `onError` as a function; its default is
1230
+ `undefined`. Pass an error callback or omit the option. Other types throw a
1231
+ TypeError naming `onError`, both accepted choices and the arguments help link,
1232
+ before installing GPU globals or creating an engine.