cuetake 0.1.0 → 0.3.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.
@@ -1,74 +1,66 @@
1
1
  /**
2
- * Runs inside Chromium (see render.js). Source WebM → VideoDecoder → one WebGL2 pass per output
3
- * frame → VideoEncoder (H.264) → MP4, streamed back to Node in chunks.
2
+ * Runs inside Chromium (see render.js). Source WebM → VideoDecoder → WebGL2 → VideoEncoder (H.264) →
3
+ * MP4, streamed back to Node in chunks.
4
+ *
5
+ * Each output frame is the Background (drawn once, still in output pixels), the window effects (drawn
6
+ * every frame around the window as the camera moves it), the page, then the chrome, click effects and
7
+ * cursor. Everything but the page is agent-written shaders, drawing code or images (ADR 0005).
4
8
  *
5
9
  * Spaces: camera crops are CSS pixels of the viewport; the Source texture is sampled by UV only;
6
10
  * "stage" is the Final's pixels at camera zoom 1, laid out by stage.js.
7
11
  */
8
12
  import * as MB from '/mediabunny.js';
9
13
  import { cameraTrack } from '/camera.js';
10
- import { pointerAt, presses, sparksAt, cursorGeometry, drawSpark, ARROW_PATH } from '/cursor.js';
11
- import { layout, cameraView, BACKGROUNDS, autoBackground, brandHue } from '/stage.js';
14
+ import { pointerAt, presses, sparksAt } from '/cursor.js';
15
+ import { layout, outputSize, cameraView, previewSheet, brandColor } from '/stage.js';
12
16
 
13
17
  const VERTEX = `#version 300 es
14
18
  in vec2 p; void main() { gl_Position = vec4(p, 0, 1); }`;
15
- const FRAGMENT = `#version 300 es
19
+ /** Prepended to every agent shader, whose own source then starts at line 1. */
20
+ const SHADER_HEADER = `#version 300 es
21
+ precision highp float;
22
+ uniform vec2 uResolution; // output pixels
23
+ uniform float uUnit; // output pixels per 1080p pixel
24
+ uniform vec3 uBrand; // the page's brand color, RGB 0–1
25
+ uniform sampler2D uPrevious; // Background layers: the layers below; window effects: the Background
26
+ uniform sampler2D uPage; // the page: its first frame for Background layers, the current one for window effects
27
+ uniform vec4 uWindow; // the window (chrome + page) in output pixels: left, top, width, height
28
+ uniform float uRadius; // the window's corner radius in output pixels
29
+ uniform float uZoom; // the camera zoom; 1 for Background layers
30
+ out vec4 color; // premultiplied RGBA
31
+ vec2 pixel() { return vec2(gl_FragCoord.x, uResolution.y - gl_FragCoord.y); }
32
+ vec4 previous(vec2 px) { return texture(uPrevious, vec2(px.x, uResolution.y - px.y) / uResolution); }
33
+ float windowDistance(vec2 px) {
34
+ vec2 q = abs(px - uWindow.xy - uWindow.zw * 0.5) - (uWindow.zw * 0.5 - uRadius);
35
+ return length(max(q, 0.0)) + min(max(q.x, q.y), 0.0) - uRadius;
36
+ }
37
+ `;
38
+ const HEADER_UNIFORMS = new Set(['uResolution', 'uUnit', 'uBrand', 'uPrevious', 'uPage', 'uWindow', 'uRadius', 'uZoom']);
39
+ // An image layer is drawn over the layers below it.
40
+ const IMAGE_LAYER = `uniform sampler2D image;
41
+ void main() { vec4 top = texture(image, pixel() / uResolution); color = top + previous(pixel()) * (1.0 - top.a); }`;
42
+ const BLIT = `#version 300 es
16
43
  precision highp float;
17
- uniform vec2 uRes; // output size
18
- uniform vec3 uCam; // stage point at the output center, and zoom
19
- uniform vec4 uPage; // page rectangle in stage pixels
20
- uniform vec4 uWindow; // window rectangle (chrome + page) in stage pixels
21
- uniform float uRadius; // window corner radius, stage pixels
22
- uniform float uFramed; // 0: page fills the stage
23
- uniform float uShadow; // drop shadow strength
24
- uniform float uBlur; // 1: background is the blurred page
25
- uniform vec3 uBase; // mesh background: base color under up to four blobs
26
- uniform vec4 uBlobs[4]; // x, y, radius as stage fractions
27
- uniform vec3 uBlobColors[4];
28
- uniform int uBlobCount;
44
+ uniform sampler2D uImage; uniform vec2 uRes; out vec4 color;
45
+ void main() { color = texture(uImage, gl_FragCoord.xy / uRes); }`;
46
+ // The page inside the window's rounded rectangle, below the chrome, under the camera.
47
+ const PAGE = `#version 300 es
48
+ precision highp float;
49
+ uniform vec2 uRes; uniform vec3 uCam; uniform vec4 uPage; uniform vec4 uWindow; uniform float uRadius;
29
50
  uniform sampler2D uSource;
30
51
  out vec4 color;
31
-
32
52
  float roundedBox(vec2 p, vec4 rect, float r) {
33
53
  vec2 q = abs(p - rect.xy - rect.zw * 0.5) - (rect.zw * 0.5 - r);
34
54
  return length(max(q, 0.0)) + min(max(q.x, q.y), 0.0) - r;
35
55
  }
36
- float noise(vec2 p) { return fract(sin(dot(p, vec2(12.9898, 78.233))) * 43758.5453); }
37
-
38
56
  void main() {
39
57
  vec2 pixel = vec2(gl_FragCoord.x, uRes.y - gl_FragCoord.y);
40
58
  vec2 stage = (pixel - uRes * 0.5) / uCam.z + uCam.xy;
41
- vec2 pageUv = clamp((stage - uPage.xy) / uPage.zw, 0.0, 1.0);
42
- if (uFramed < 0.5) { color = vec4(texture(uSource, pageUv).rgb, 1.0); return; }
43
-
44
- vec3 c;
45
- if (uBlur > 0.5) {
46
- // Cover the stage with the page, then read a coarse mip level as a cheap wide blur.
47
- float r = (uRes.x / uRes.y) / (uPage.z / uPage.w);
48
- vec2 uv = 0.5 + (stage / uRes - 0.5) * vec2(min(1.0, r), min(1.0, 1.0 / r)) / 1.2;
49
- c = textureLod(uSource, uv, 6.0).rgb * 0.8;
50
- } else {
51
- c = uBase;
52
- for (int i = 3; i >= 0; i--) {
53
- if (i >= uBlobCount) continue;
54
- float d = length((stage / uRes - uBlobs[i].xy) / uBlobs[i].z);
55
- c = mix(c, uBlobColors[i], 1.0 - smoothstep(0.0, 0.7, d));
56
- }
57
- }
58
- // Grain dithers the gradients so H.264 does not band them.
59
- c += (noise(pixel) - 0.5) * 0.035;
60
-
61
- float unit = min(uRes.x, uRes.y) / 1080.0;
62
- float shadow = uShadow * (1.0 - smoothstep(-60.0 * unit, 60.0 * unit, roundedBox(stage - vec2(0.0, 24.0 * unit), uWindow, uRadius)));
63
- c = mix(c, vec3(0.0), shadow * 0.55);
64
-
65
- float edge = roundedBox(stage, uWindow, uRadius) * uCam.z; // output pixels from the window edge
66
- float inside = clamp(0.5 - edge, 0.0, 1.0);
67
- if (stage.y >= uPage.y) c = mix(c, texture(uSource, pageUv).rgb, inside);
68
- c = mix(c, vec3(1.0), 0.18 * (1.0 - smoothstep(0.0, 1.0, abs(edge)))); // hairline rim
69
- color = vec4(c, 1.0);
59
+ float inside = clamp(0.5 - roundedBox(stage, uWindow, uRadius) * uCam.z, 0.0, 1.0);
60
+ if (inside <= 0.0 || stage.y < uPage.y) discard;
61
+ color = vec4(texture(uSource, clamp((stage - uPage.xy) / uPage.zw, 0.0, 1.0)).rgb, 1.0) * inside;
70
62
  }`;
71
- // Sprites (cursor, sparks) are premultiplied textures placed by a stage rectangle under the same camera.
63
+ // Sprites (chrome, cursor, click effects) are premultiplied textures placed by a stage rectangle under the camera.
72
64
  const SPRITE_VERTEX = `#version 300 es
73
65
  in vec2 p;
74
66
  uniform vec2 uRes; uniform vec3 uCam; uniform vec4 uRect;
@@ -84,58 +76,70 @@ uniform sampler2D uSprite;
84
76
  in vec2 uv; out vec4 color;
85
77
  void main() { color = texture(uSprite, uv); }`;
86
78
 
87
- /** Smallest H.264 High level whose frame-size and macroblock-rate limits fit. */
88
- export function avcCodec(width, height, fps) {
89
- const frame = Math.ceil(width / 16) * Math.ceil(height / 16), rate = frame * fps;
90
- const levels = [[42, 8704, 522240], [50, 22080, 589824], [51, 36864, 983040], [52, 36864, 2073600], [60, 139264, 4177920], [61, 139264, 8355840], [62, 139264, 16711680]];
91
- const [level] = levels.find(([, maxFrame, maxRate]) => frame <= maxFrame && rate <= maxRate) ?? levels.at(-1);
92
- return `avc1.6400${level.toString(16).toUpperCase().padStart(2, '0')}`;
79
+ // Item keys CueTake reads itself; every other key is a parameter for the item's shader or drawing code.
80
+ const OWN_KEYS = new Set(['shader', 'draw', 'image', 'files', 'ref', 'kind', 'url']);
81
+ const SLOT_KEYS = new Set(['size', 'hotspot', 'duration', 'reach', 'height']);
82
+ const paramsOf = item => Object.fromEntries(Object.entries(item).filter(([key]) => !OWN_KEYS.has(key) && (item.kind === 'shader' || !SLOT_KEYS.has(key))));
83
+ const fail = (item, error) => new Error(`${item.ref}: ${error?.message ?? error}`);
84
+
85
+ /** A parameter as a GLSL uniform: numbers and booleans are floats, 2–4 numbers a vector, '#rrggbb(aa)' a color. */
86
+ function uniformOf(value) {
87
+ if (typeof value === 'number') return ['float', [value]];
88
+ if (typeof value === 'boolean') return ['float', [value ? 1 : 0]];
89
+ if (Array.isArray(value) && value.length >= 2 && value.length <= 4 && value.every(n => typeof n === 'number')) return [`vec${value.length}`, value];
90
+ if (typeof value === 'string' && /^#([0-9a-f]{6}|[0-9a-f]{8})$/i.test(value)) {
91
+ const channels = value.slice(1).match(/../g).map(h => parseInt(h, 16) / 255);
92
+ return [`vec${channels.length}`, channels];
93
+ }
94
+ return null;
93
95
  }
94
96
 
95
- /** Decodes a track with bounded look-ahead so memory stays flat on long Takes. */
96
- function frameReader(track, decoderConfig) {
97
- const ready = [], waiting = [];
98
- let failure = null, submitted = 0, decoded = 0, ended = false;
99
- const wake = () => waiting.splice(0).forEach(resolve => resolve());
100
- const decoder = new VideoDecoder({ output: frame => { decoded++; ready.push(frame); wake(); }, error: error => { failure = error; wake(); } });
101
- decoder.configure(decoderConfig);
102
- const packets = new MB.EncodedPacketSink(track).packets();
103
- return {
104
- stats: () => ({ submitted, decoded }),
105
- async next() {
106
- while (!ready.length) {
107
- if (failure) throw failure;
108
- if (ended) return null;
109
- if (submitted - decoded >= 6) { await new Promise(resolve => waiting.push(resolve)); continue; }
110
- const packet = await packets.next();
111
- if (packet.done) { await decoder.flush(); ended = true; continue; }
112
- decoder.decode(packet.value.toEncodedVideoChunk());
113
- submitted++;
114
- }
115
- return ready.shift();
116
- },
117
- close() { ready.splice(0).forEach(frame => frame.close()); if (decoder.state !== 'closed') decoder.close(); },
118
- };
97
+ async function loadImage(item, url) {
98
+ const image = new Image();
99
+ image.src = url;
100
+ try { await image.decode(); } catch { throw fail(item, `${url.split('/').pop()} is not an image the browser can open`); }
101
+ return image;
102
+ }
103
+ const FONT = /\.(woff2?|ttf|otf)$/i;
104
+ /** An item's `files` for drawing code: images as <img> elements, fonts registered under their key. */
105
+ async function loadFiles(item) {
106
+ const loaded = {};
107
+ for (const [name, url] of Object.entries(item.files ?? {})) {
108
+ if (FONT.test(url)) {
109
+ const face = new FontFace(name, `url(${url})`);
110
+ try { await face.load(); } catch (error) { throw fail(item, error); }
111
+ document.fonts.add(face); loaded[name] = name;
112
+ } else loaded[name] = await loadImage(item, url);
113
+ }
114
+ return loaded;
115
+ }
116
+ async function loadModule(item) {
117
+ try { return await import(item.url); } catch (error) { throw fail(item, error); }
119
118
  }
119
+ const canvas2d = (width, height) => {
120
+ const canvas = document.createElement('canvas');
121
+ canvas.width = Math.max(1, Math.ceil(width)); canvas.height = Math.max(1, Math.ceil(height));
122
+ return canvas.getContext('2d');
123
+ };
120
124
 
121
- /** `look` is the static part of the frame: stage layout, background and shadow. */
122
- function createCompositor(stage, look, sourceWidth, sourceHeight) {
123
- const { width, height } = stage;
125
+ /** The compositor for one stage: the Background drawn once, then per frame effects, page and sprites. */
126
+ function createCompositor(stage, sourceWidth, sourceHeight, brand) {
127
+ const { width, height } = stage, unit = Math.min(width, height) / 1080;
124
128
  const canvas = new OffscreenCanvas(width, height);
125
129
  const gl = canvas.getContext('webgl2', { alpha: false, antialias: false, depth: false });
126
- const shader = (type, text) => {
130
+ const compile = (type, text, item) => {
127
131
  const s = gl.createShader(type); gl.shaderSource(s, text); gl.compileShader(s);
128
- if (!gl.getShaderParameter(s, gl.COMPILE_STATUS)) throw new Error(gl.getShaderInfoLog(s));
132
+ if (!gl.getShaderParameter(s, gl.COMPILE_STATUS)) throw item ? fail(item, gl.getShaderInfoLog(s).trim()) : new Error(gl.getShaderInfoLog(s));
129
133
  return s;
130
134
  };
131
- const program = (vertex, fragment) => {
135
+ const program = (vertex, fragment, item) => {
132
136
  const p = gl.createProgram();
133
- gl.attachShader(p, shader(gl.VERTEX_SHADER, vertex)); gl.attachShader(p, shader(gl.FRAGMENT_SHADER, fragment));
137
+ gl.attachShader(p, compile(gl.VERTEX_SHADER, vertex, item)); gl.attachShader(p, compile(gl.FRAGMENT_SHADER, fragment, item));
134
138
  gl.bindAttribLocation(p, 0, 'p');
135
139
  gl.linkProgram(p);
136
- if (!gl.getProgramParameter(p, gl.LINK_STATUS)) throw new Error(gl.getProgramInfoLog(p));
140
+ if (!gl.getProgramParameter(p, gl.LINK_STATUS)) throw item ? fail(item, gl.getProgramInfoLog(p)) : new Error(gl.getProgramInfoLog(p));
137
141
  gl.useProgram(p);
138
- gl.uniform2f(gl.getUniformLocation(p, 'uRes'), width, height);
142
+ for (const name of ['uRes', 'uResolution']) gl.uniform2f(gl.getUniformLocation(p, name), width, height);
139
143
  return { p, camera: gl.getUniformLocation(p, 'uCam'), uniform: name => gl.getUniformLocation(p, name) };
140
144
  };
141
145
  const quad = corners => {
@@ -152,37 +156,107 @@ function createCompositor(stage, look, sourceWidth, sourceHeight) {
152
156
  gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
153
157
  return t;
154
158
  };
155
- const pageProgram = program(VERTEX, FRAGMENT);
156
- const set = (name, ...v) => gl[`uniform${v.length}f`](pageProgram.uniform(name), ...v);
157
- set('uPage', stage.page.x, stage.page.y, stage.page.w, stage.page.h);
158
- set('uWindow', stage.window.x, stage.window.y, stage.window.w, stage.window.h);
159
- set('uRadius', stage.radius); set('uFramed', look.framed ? 1 : 0); set('uShadow', look.shadow ? 1 : 0); set('uBlur', look.background ? 0 : 1);
160
- if (look.background) {
161
- const rgb = hex => [1, 3, 5].map(i => parseInt(hex.slice(i, i + 2), 16) / 255);
162
- set('uBase', ...rgb(look.background.base));
163
- const blobs = look.background.blobs.slice(0, 4);
164
- gl.uniform1i(pageProgram.uniform('uBlobCount'), blobs.length);
165
- gl.uniform4fv(pageProgram.uniform('uBlobs'), blobs.flatMap(([x, y, r]) => [x, y, r, 0]).concat(Array(16).fill(0)).slice(0, 16));
166
- gl.uniform3fv(pageProgram.uniform('uBlobColors'), blobs.flatMap(b => rgb(b[3])).concat(Array(12).fill(0)).slice(0, 12));
167
- }
168
- const spriteProgram = program(SPRITE_VERTEX, SPRITE_FRAGMENT);
169
- const spriteRect = spriteProgram.uniform('uRect');
170
- const fullScreen = quad([-1, -1, 1, -1, -1, 1, 1, 1]), unit = quad([0, 0, 1, 0, 0, 1, 1, 1]);
171
- // Mipmaps keep zoomed-out text from aliasing when the 2× Source is minified.
172
- const pageTexture = texture();
173
- gl.texStorage2D(gl.TEXTURE_2D, Math.floor(Math.log2(Math.max(sourceWidth, sourceHeight))) + 1, gl.RGBA8, sourceWidth, sourceHeight);
159
+ const imageTexture = image => {
160
+ const t = texture(); gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, image); gl.generateMipmap(gl.TEXTURE_2D);
161
+ return t;
162
+ };
163
+ const bind = (unitIndex, t) => { gl.activeTexture(gl.TEXTURE0 + unitIndex); gl.bindTexture(gl.TEXTURE_2D, t); };
164
+ const fullScreen = quad([-1, -1, 1, -1, -1, 1, 1, 1]), unitQuad = quad([0, 0, 1, 0, 0, 1, 1, 1]);
174
165
  gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, true);
175
166
  gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
176
167
  gl.viewport(0, 0, width, height);
177
- const info = gl.getExtension('WEBGL_debug_renderer_info');
168
+
169
+ // Mipmaps keep zoomed-out text from aliasing when the 2× Source is minified.
170
+ const pageTexture = texture();
171
+ gl.texStorage2D(gl.TEXTURE_2D, Math.floor(Math.log2(Math.max(sourceWidth, sourceHeight))) + 1, gl.RGBA8, sourceWidth, sourceHeight);
172
+ const pageProgram = program(VERTEX, PAGE);
173
+ gl.uniform4f(pageProgram.uniform('uPage'), stage.page.x, stage.page.y, stage.page.w, stage.page.h);
174
+ gl.uniform4f(pageProgram.uniform('uWindow'), stage.window.x, stage.window.y, stage.window.w, stage.window.h);
175
+ gl.uniform1f(pageProgram.uniform('uRadius'), stage.radius);
176
+ const blitProgram = program(VERTEX, BLIT);
177
+ const spriteProgram = program(SPRITE_VERTEX, SPRITE_FRAGMENT), spriteRect = spriteProgram.uniform('uRect');
178
+
179
+ /** An agent shader with its parameters declared and set, and its `files` bound from texture unit 2. */
180
+ async function agentProgram(item, source) {
181
+ const params = Object.entries(paramsOf(item)).map(([name, value]) => [name, uniformOf(value)]).filter(([name, u]) => u && /^[A-Za-z_]\w*$/.test(name));
182
+ const images = await Promise.all(Object.entries(item.files ?? {}).map(async ([name, url]) => [name, await loadImage(item, url)]));
183
+ const declarations = [
184
+ ...params.filter(([name]) => !HEADER_UNIFORMS.has(name)).map(([name, [type]]) => `uniform ${type} ${name};`),
185
+ ...images.flatMap(([name]) => [`uniform sampler2D ${name};`, `uniform vec2 ${name}Size;`]),
186
+ ].join('\n');
187
+ const p = program(VERTEX, `${SHADER_HEADER}${declarations}\n#line 1\n${source}`, item);
188
+ gl.uniform1f(p.uniform('uUnit'), unit); gl.uniform3f(p.uniform('uBrand'), ...brand);
189
+ gl.uniform1i(p.uniform('uPrevious'), 0); gl.uniform1i(p.uniform('uPage'), 1);
190
+ for (const [name, [type, values]] of params) gl[`uniform${type === 'float' ? 1 : type.at(-1)}fv`](p.uniform(name), values);
191
+ const textures = images.map(([name, image], i) => {
192
+ gl.useProgram(p.p); gl.uniform1i(p.uniform(name), 2 + i); gl.uniform2f(p.uniform(`${name}Size`), image.naturalWidth, image.naturalHeight);
193
+ return imageTexture(image);
194
+ });
195
+ return { ...p, textures };
196
+ }
197
+ const shaderSource = async item => {
198
+ const response = await fetch(item.url);
199
+ if (!response.ok) throw fail(item, `could not be read (${response.status})`);
200
+ return response.text();
201
+ };
202
+ /** Draws one program over the full screen with uPrevious and uPage bound; window uniforms in output pixels. */
203
+ const run = (p, previous, windowRect, radius, zoom) => {
204
+ gl.useProgram(p.p);
205
+ gl.uniform4f(p.uniform('uWindow'), ...windowRect); gl.uniform1f(p.uniform('uRadius'), radius); gl.uniform1f(p.uniform('uZoom'), zoom);
206
+ bind(0, previous); bind(1, pageTexture);
207
+ p.textures?.forEach((t, i) => bind(2 + i, t));
208
+ gl.bindVertexArray(fullScreen); gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
209
+ gl.activeTexture(gl.TEXTURE0);
210
+ };
211
+ const checkGpu = what => { if (gl.isContextLost()) throw new Error(`${what} stopped the GPU; simplify the shader`); };
212
+
213
+ const target = () => { const t = texture(gl.LINEAR); gl.texStorage2D(gl.TEXTURE_2D, 1, gl.RGBA8, width, height); return t; };
214
+ const framebuffer = gl.createFramebuffer();
215
+ let background = target(), effects = [];
216
+ const restWindow = [stage.window.x, stage.window.y, stage.window.w, stage.window.h];
178
217
  return {
179
218
  canvas,
180
- gpu: info ? gl.getParameter(info.UNMASKED_RENDERER_WEBGL) : 'unknown',
219
+ gpu: (() => { const info = gl.getExtension('WEBGL_debug_renderer_info'); return info ? gl.getParameter(info.UNMASKED_RENDERER_WEBGL) : 'unknown'; })(),
220
+ /** Frees the GPU context; a Preview makes one compositor per tile. */
221
+ dispose() { gl.getExtension('WEBGL_lose_context')?.loseContext(); },
181
222
  upload(frame) {
182
223
  gl.bindTexture(gl.TEXTURE_2D, pageTexture);
183
224
  gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, gl.RGBA, gl.UNSIGNED_BYTE, frame);
184
225
  gl.generateMipmap(gl.TEXTURE_2D);
185
226
  },
227
+ /** Draws the Background layers in order, each over the result so far, starting from black. */
228
+ async drawBackground(layers) {
229
+ let other = target();
230
+ gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
231
+ gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, background, 0);
232
+ gl.clearColor(0, 0, 0, 1); gl.clear(gl.COLOR_BUFFER_BIT);
233
+ for (const item of layers) {
234
+ let p;
235
+ if (item.kind === 'image') {
236
+ // Cover the output, centered, at full resolution (SVG rasterizes at this size).
237
+ const image = await loadImage(item, item.url), w = image.naturalWidth || width, h = image.naturalHeight || height;
238
+ const k = Math.max(width / w, height / h), ctx = canvas2d(width, height);
239
+ ctx.drawImage(image, (width - w * k) / 2, (height - h * k) / 2, w * k, h * k);
240
+ p = await agentProgram({ ref: item.ref, kind: 'shader' }, IMAGE_LAYER);
241
+ p.textures = [imageTexture(ctx.canvas)]; gl.uniform1i(p.uniform('image'), 2);
242
+ } else if (item.kind === 'shader') p = await agentProgram(item, await shaderSource(item));
243
+ else throw fail(item, 'Background layers are shaders or images');
244
+ gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
245
+ gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, other, 0);
246
+ gl.disable(gl.BLEND);
247
+ run(p, background, restWindow, stage.radius, 1);
248
+ [background, other] = [other, background];
249
+ }
250
+ gl.bindFramebuffer(gl.FRAMEBUFFER, null);
251
+ checkGpu('A Background layer');
252
+ },
253
+ async loadEffects(items) {
254
+ effects = [];
255
+ for (const item of items) {
256
+ if (item.kind !== 'shader') throw fail(item, 'window effects are shaders');
257
+ effects.push(await agentProgram(item, await shaderSource(item)));
258
+ }
259
+ },
186
260
  /** A sprite texture from a 2D canvas; pass `into` to reuse one. */
187
261
  sprite(image, into, mipmaps = true) {
188
262
  const t = into ?? texture(mipmaps ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
@@ -191,80 +265,137 @@ function createCompositor(stage, look, sourceWidth, sourceHeight) {
191
265
  if (mipmaps) gl.generateMipmap(gl.TEXTURE_2D);
192
266
  return t;
193
267
  },
194
- /** Draws the page under the camera; `draw(texture, rect)` in `overlay` then places sprites in stage pixels. */
268
+ /** One frame with the camera at stage point (x, y) and `zoom`; `draw(texture, rect)` in `overlay` places sprites in stage pixels. */
195
269
  frame(x, y, zoom, overlay) {
196
270
  gl.disable(gl.BLEND);
197
- gl.useProgram(pageProgram.p); gl.uniform3f(pageProgram.camera, x, y, zoom);
198
- gl.bindTexture(gl.TEXTURE_2D, pageTexture); gl.bindVertexArray(fullScreen);
199
- gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
271
+ gl.useProgram(blitProgram.p); bind(0, background); gl.bindVertexArray(fullScreen); gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
200
272
  gl.enable(gl.BLEND);
201
- gl.useProgram(spriteProgram.p); gl.uniform3f(spriteProgram.camera, x, y, zoom); gl.bindVertexArray(unit);
273
+ const shown = [(stage.window.x - x) * zoom + width / 2, (stage.window.y - y) * zoom + height / 2, stage.window.w * zoom, stage.window.h * zoom];
274
+ for (const p of effects) run(p, background, shown, stage.radius * zoom, zoom);
275
+ gl.useProgram(pageProgram.p); gl.uniform3f(pageProgram.camera, x, y, zoom);
276
+ bind(0, pageTexture); gl.bindVertexArray(fullScreen); gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
277
+ gl.useProgram(spriteProgram.p); gl.uniform3f(spriteProgram.camera, x, y, zoom); gl.bindVertexArray(unitQuad);
202
278
  overlay((t, rect) => { gl.bindTexture(gl.TEXTURE_2D, t); gl.uniform4f(spriteRect, ...rect); gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4); });
279
+ if (effects.length) checkGpu('A window effect');
203
280
  },
204
281
  };
205
282
  }
206
283
 
207
- /** The cursor drawn once at `scale` device pixels per CSS pixel, with room for its shadow. */
208
- function cursorSprite(cursor, scale) {
209
- const { width, height } = cursorGeometry(cursor);
210
- const margin = 4;
211
- const canvas = new OffscreenCanvas(Math.ceil((width + 2 * margin) * scale), Math.ceil((height + 2 * margin) * scale));
212
- const ctx = canvas.getContext('2d');
213
- ctx.scale(scale, scale);
214
- ctx.translate(margin, margin);
215
- ctx.shadowColor = '#00000055'; ctx.shadowBlur = 2 * scale; ctx.shadowOffsetY = 1 * scale;
216
- if (cursor.style === 'arrow') {
217
- ctx.scale(width / 28, height / 36);
218
- const path = new Path2D(ARROW_PATH);
219
- ctx.fillStyle = cursor.color; ctx.fill(path);
220
- ctx.shadowColor = 'transparent';
221
- ctx.lineJoin = 'round'; ctx.lineWidth = 1.7; ctx.strokeStyle = '#171717'; ctx.stroke(path);
284
+ /**
285
+ * The chrome bar: drawing code exporting `height` (CSS px) and `draw(ctx, { width, height, radius, url,
286
+ * params, files })`, or an image as wide as the window. `paint(scale, radius)` rasterizes it, clipped to
287
+ * the window's rounded top.
288
+ */
289
+ async function loadChrome(item, width, url) {
290
+ let height, paint;
291
+ if (item.kind === 'image') {
292
+ const image = await loadImage(item, item.url);
293
+ height = item.height ?? image.naturalHeight * width / image.naturalWidth;
294
+ paint = ctx => ctx.drawImage(image, 0, 0, width, height);
222
295
  } else {
223
- ctx.beginPath(); ctx.arc(width / 2, height / 2, width / 2, 0, 2 * Math.PI);
224
- ctx.fillStyle = cursor.color; ctx.fill();
225
- ctx.shadowColor = 'transparent';
226
- ctx.lineWidth = 1.5; ctx.strokeStyle = '#171717'; ctx.beginPath(); ctx.arc(width / 2, height / 2, width / 2 - 0.75, 0, 2 * Math.PI); ctx.stroke();
296
+ const module = await loadModule(item), files = await loadFiles(item), params = paramsOf(item);
297
+ height = item.height ?? (typeof module.height === 'function' ? module.height(params) : module.height) ?? 0;
298
+ paint = (ctx, radius) => module.draw(ctx, { width, height, radius, url, params, files });
227
299
  }
228
- // Size in CSS pixels, including the shadow margin.
229
- return { canvas, margin, width: canvas.width / scale, height: canvas.height / scale };
300
+ return {
301
+ height,
302
+ canvas(scale, radius) {
303
+ const ctx = canvas2d(width * scale, height * scale);
304
+ ctx.scale(scale, scale);
305
+ ctx.beginPath(); ctx.roundRect(0, 0, width, height + radius, [radius, radius, 0, 0]); ctx.clip();
306
+ try { paint(ctx, radius); } catch (error) { throw fail(item, error); }
307
+ return ctx.canvas;
308
+ },
309
+ };
230
310
  }
231
311
 
232
- /** The window's chrome bar at `scale` pixels per CSS pixel: traffic lights, and for `browser` an address field. */
233
- function chromeSprite(frame, viewportWidth, heightCss, radiusCss, scale) {
234
- const canvas = new OffscreenCanvas(Math.ceil(viewportWidth * scale), Math.ceil(heightCss * scale));
235
- const ctx = canvas.getContext('2d');
236
- ctx.scale(scale, scale);
237
- ctx.beginPath(); ctx.roundRect(0, 0, viewportWidth, heightCss + radiusCss, [radiusCss, radiusCss, 0, 0]);
238
- ctx.fillStyle = frame.window === 'browser' ? '#f3f3f5' : '#ececef'; ctx.fill();
239
- ctx.fillStyle = '#d4d4d8'; ctx.fillRect(0, heightCss - 1, viewportWidth, 1);
240
- ['#ff5f57', '#febc2e', '#28c840'].forEach((light, i) => {
241
- ctx.beginPath(); ctx.arc(20 + i * 20, heightCss / 2, 6, 0, 2 * Math.PI);
242
- ctx.fillStyle = light; ctx.fill(); ctx.strokeStyle = '#0000001f'; ctx.lineWidth = 0.5; ctx.stroke();
243
- });
244
- if (frame.window === 'browser') {
245
- const w = 420, h = 28, x = (viewportWidth - w) / 2, y = (heightCss - h) / 2;
246
- ctx.beginPath(); ctx.roundRect(x, y, w, h, h / 2);
247
- ctx.fillStyle = '#ffffff'; ctx.fill(); ctx.strokeStyle = '#e4e4e7'; ctx.lineWidth = 0.8; ctx.stroke();
248
- ctx.font = '13px system-ui, -apple-system, sans-serif'; ctx.textBaseline = 'middle';
249
- const text = frame.url ?? '', textWidth = ctx.measureText(text).width, left = viewportWidth / 2 - (textWidth + 16) / 2;
250
- ctx.fillStyle = '#71717a'; // padlock
251
- ctx.beginPath(); ctx.roundRect(left, y + 13, 9, 7, 1.5); ctx.fill();
252
- ctx.strokeStyle = '#71717a'; ctx.lineWidth = 1.3; ctx.beginPath(); ctx.arc(left + 4.5, y + 13, 2.8, Math.PI, 0); ctx.stroke();
253
- ctx.fillStyle = '#52525b'; ctx.fillText(text, left + 16, heightCss / 2 + 0.5);
312
+ /**
313
+ * The cursor: drawing code exporting `box` ({ width, height, hotspot: [x, y] } in its own units) and
314
+ * `draw(ctx, { params, files })` in those units, or an image whose `hotspot` the item names. It is shown
315
+ * `size` CSS px wide, with a margin of a quarter box around it for shadows.
316
+ */
317
+ async function loadCursor(item) {
318
+ let box, paint;
319
+ if (item.kind === 'image') {
320
+ const image = await loadImage(item, item.url);
321
+ box = { width: image.naturalWidth || 32, height: image.naturalHeight || 32, hotspot: item.hotspot ?? [0, 0] };
322
+ paint = ctx => ctx.drawImage(image, 0, 0, box.width, box.height);
323
+ } else {
324
+ const module = await loadModule(item), files = await loadFiles(item), params = paramsOf(item);
325
+ box = { ...module.box, ...(item.hotspot && { hotspot: item.hotspot }) };
326
+ paint = ctx => module.draw(ctx, { params, files });
254
327
  }
255
- return canvas;
328
+ const k = (item.size ?? 24) / box.width, margin = Math.max(box.width, box.height) / 4;
329
+ return {
330
+ /** Where the sprite's top-left sits relative to the pointer, and its size, in CSS px. */
331
+ offset: { x: -(box.hotspot[0] + margin) * k, y: -(box.hotspot[1] + margin) * k },
332
+ size: { w: (box.width + 2 * margin) * k, h: (box.height + 2 * margin) * k },
333
+ canvas(scale) {
334
+ const ctx = canvas2d((box.width + 2 * margin) * k * scale, (box.height + 2 * margin) * k * scale);
335
+ ctx.scale(k * scale, k * scale); ctx.translate(margin, margin);
336
+ try { paint(ctx); } catch (error) { throw fail(item, error); }
337
+ return ctx.canvas;
338
+ },
339
+ };
256
340
  }
257
341
 
258
- /** The background: a mesh preset, a mesh around the page's brand hue, or null for the blurred page. */
259
- function backgroundFor(frame, firstFrame) {
260
- if (frame.background === 'blur') return null;
261
- if (frame.background !== 'auto') return BACKGROUNDS[frame.background];
342
+ /**
343
+ * A click effect: drawing code exporting `reach` (CSS px it may draw from the click, or a function of
344
+ * its parameters) and `draw(ctx, { progress, params, files, cursor })` with the origin at the click,
345
+ * or an image that fades out over the effect.
346
+ */
347
+ async function loadClickEffect(item, cursor) {
348
+ if (item.kind === 'image') {
349
+ const image = await loadImage(item, item.url), w = item.size ?? (image.naturalWidth || 48), h = w * (image.naturalHeight / image.naturalWidth || 1);
350
+ return { reach: Math.max(w, h) / 2, paint: (ctx, progress) => { ctx.globalAlpha = 1 - progress; ctx.drawImage(image, -w / 2, -h / 2, w, h); } };
351
+ }
352
+ const module = await loadModule(item), files = await loadFiles(item), params = paramsOf(item);
353
+ const reach = item.reach ?? (typeof module.reach === 'function' ? module.reach(params) : module.reach) ?? 64;
354
+ return { reach, paint: (ctx, progress) => { try { module.draw(ctx, { progress, params, files, cursor }); } catch (error) { throw fail(item, error); } } };
355
+ }
356
+
357
+ /** The page's brand color from the Source's first frame. */
358
+ function brandOf(firstFrame) {
262
359
  const ctx = new OffscreenCanvas(96, 60).getContext('2d', { willReadFrequently: true });
263
360
  ctx.drawImage(firstFrame, 0, 0, 96, 60);
264
- const hue = brandHue(ctx.getImageData(0, 0, 96, 60).data);
265
- return hue === null ? BACKGROUNDS.aurora : autoBackground(hue);
361
+ return brandColor(ctx.getImageData(0, 0, 96, 60).data);
362
+ }
363
+
364
+ /** Smallest H.264 High level whose frame-size and macroblock-rate limits fit. */
365
+ export function avcCodec(width, height, fps) {
366
+ const frame = Math.ceil(width / 16) * Math.ceil(height / 16), rate = frame * fps;
367
+ const levels = [[42, 8704, 522240], [50, 22080, 589824], [51, 36864, 983040], [52, 36864, 2073600], [60, 139264, 4177920], [61, 139264, 8355840], [62, 139264, 16711680]];
368
+ const [level] = levels.find(([, maxFrame, maxRate]) => frame <= maxFrame && rate <= maxRate) ?? levels.at(-1);
369
+ return `avc1.6400${level.toString(16).toUpperCase().padStart(2, '0')}`;
370
+ }
371
+
372
+ /** Decodes a track with bounded look-ahead so memory stays flat on long Takes. */
373
+ function frameReader(track, decoderConfig) {
374
+ const ready = [], waiting = [];
375
+ let failure = null, submitted = 0, decoded = 0, ended = false;
376
+ const wake = () => waiting.splice(0).forEach(resolve => resolve());
377
+ const decoder = new VideoDecoder({ output: frame => { decoded++; ready.push(frame); wake(); }, error: error => { failure = error; wake(); } });
378
+ decoder.configure(decoderConfig);
379
+ const packets = new MB.EncodedPacketSink(track).packets();
380
+ return {
381
+ stats: () => ({ submitted, decoded }),
382
+ async next() {
383
+ while (!ready.length) {
384
+ if (failure) throw failure;
385
+ if (ended) return null;
386
+ if (submitted - decoded >= 6) { await new Promise(resolve => waiting.push(resolve)); continue; }
387
+ const packet = await packets.next();
388
+ if (packet.done) { await decoder.flush(); ended = true; continue; }
389
+ decoder.decode(packet.value.toEncodedVideoChunk());
390
+ submitted++;
391
+ }
392
+ return ready.shift();
393
+ },
394
+ close() { ready.splice(0).forEach(frame => frame.close()); if (decoder.state !== 'closed') decoder.close(); },
395
+ };
266
396
  }
267
397
 
398
+
268
399
  /** Prefers constant-quality hardware encoding; software encoders only offer a bitrate. */
269
400
  async function encoderConfig(width, height, fps, quality) {
270
401
  const base = { codec: avcCodec(width, height, fps), width, height, framerate: fps, latencyMode: 'quality', avc: { format: 'avc' } };
@@ -275,6 +406,51 @@ async function encoderConfig(width, height, fps, quality) {
275
406
  throw new Error(`No H.264 encoder supports ${width}×${height} at ${fps} fps`);
276
407
  }
277
408
 
409
+ /**
410
+
411
+ /**
412
+ * Everything Render draws for one Edit (as forRender in styles.js serves it). `firstFrame` is the
413
+ * Source's first frame: Background layers see it, and it picks the brand color.
414
+ */
415
+ async function createScene(edit, viewport, { pointer, events }, firstFrame, sourceWidth, sourceHeight) {
416
+ const { camera, cursor, clickEffect, frame } = edit;
417
+ const chrome = frame.chrome ? await loadChrome(frame.chrome, viewport.width, frame.url ?? '') : null;
418
+ const stage = layout(edit, viewport, chrome?.height ?? 0);
419
+ const compositor = createCompositor(stage, sourceWidth, sourceHeight, brandOf(firstFrame));
420
+ compositor.upload(firstFrame);
421
+ await compositor.drawBackground(frame.background ?? []);
422
+ await compositor.loadEffects(frame.effects ?? []);
423
+ // Page CSS pixels → stage pixels; sprites are rasterized for the closest zoom and mipmapped below it.
424
+ const at = (x, y) => [stage.page.x + x * stage.scale, stage.page.y + y * stage.scale];
425
+ const sharpest = stage.scale * camera.maxZoom * 2;
426
+ const chromeTexture = chrome ? compositor.sprite(chrome.canvas(sharpest, stage.radius / stage.scale)) : null;
427
+ const pointerSprite = cursor ? await loadCursor(cursor) : null;
428
+ const pointerTexture = pointerSprite && compositor.sprite(pointerSprite.canvas(sharpest));
429
+ const effect = clickEffect ? await loadClickEffect(clickEffect, cursor ? Object.fromEntries(Object.entries(cursor).filter(([key]) => !['ref', 'kind', 'url', 'files'].includes(key))) : {}) : null;
430
+ const pressList = presses(events);
431
+ let effectTexture = null;
432
+ return {
433
+ stage, compositor,
434
+ /** Draws output time `t` with the camera showing `crop`, a viewport rectangle in CSS pixels. */
435
+ draw(t, crop) {
436
+ const view = cameraView(crop, stage, viewport);
437
+ compositor.frame(view.x, view.y, view.zoom, draw => {
438
+ if (chromeTexture) draw(chromeTexture, [stage.window.x, stage.window.y, stage.window.w, stage.chrome]);
439
+ for (const press of effect ? sparksAt(pressList, clickEffect, t) : []) {
440
+ // Each click effect is drawn at its on-screen scale so thin strokes stay crisp.
441
+ const scale = stage.scale * view.zoom, ctx = canvas2d(2 * effect.reach * scale, 2 * effect.reach * scale);
442
+ ctx.scale(scale, scale); ctx.translate(effect.reach, effect.reach);
443
+ effect.paint(ctx, press.progress);
444
+ effectTexture = compositor.sprite(ctx.canvas, effectTexture, false);
445
+ draw(effectTexture, [...at(press.x - effect.reach, press.y - effect.reach), 2 * effect.reach * stage.scale, 2 * effect.reach * stage.scale]);
446
+ }
447
+ const point = pointerSprite && pointerAt(pointer, t);
448
+ if (point) draw(pointerTexture, [...at(point.x + pointerSprite.offset.x, point.y + pointerSprite.offset.y), pointerSprite.size.w * stage.scale, pointerSprite.size.h * stage.scale]);
449
+ });
450
+ },
451
+ };
452
+ }
453
+
278
454
  /** A WritableStream that posts each positioned chunk to Node, which writes it into the Final. */
279
455
  const uploadStream = url => new WritableStream({
280
456
  async write(chunk) {
@@ -284,8 +460,8 @@ const uploadStream = url => new WritableStream({
284
460
  });
285
461
 
286
462
  window.cuetakeRender = async ({ sourceUrl, finalUrl, duration, viewport, pointer, events, edit }) => {
287
- const { camera, cursor, clickEffect, frame } = edit, { quality, fps } = edit.output;
288
- const stage = layout(edit, viewport), { width, height } = stage;
463
+ const { camera } = edit, { quality, fps } = edit.output;
464
+ const { width, height } = outputSize(edit);
289
465
  const started = performance.now();
290
466
  const input = new MB.Input({ formats: MB.ALL_FORMATS, source: new MB.UrlSource(sourceUrl) });
291
467
  const track = await input.getPrimaryVideoTrack();
@@ -311,18 +487,8 @@ window.cuetakeRender = async ({ sourceUrl, finalUrl, duration, viewport, pointer
311
487
 
312
488
  let current = await reader.next(), next = await reader.next(), uploaded = null;
313
489
  if (!current) throw new Error('Source has no video frames');
314
- const compositor = createCompositor(stage, { framed: Boolean(frame), shadow: frame && frame.shadow, background: frame && backgroundFor(frame, current) }, track.codedWidth, track.codedHeight);
490
+ const scene = await createScene(edit, viewport, { pointer, events }, current, track.codedWidth, track.codedHeight), { compositor } = scene;
315
491
  const cameraPath = cameraTrack({ targets: camera.targets, viewport, camera, duration, fps, pointerAt: t => pointerAt(pointer, t) });
316
- // Page CSS pixels → stage pixels; sprites are rasterized for the closest zoom and mipmapped below it.
317
- const at = (x, y) => [stage.page.x + x * stage.scale, stage.page.y + y * stage.scale];
318
- const sharpest = stage.scale * camera.maxZoom * 2;
319
- const geometry = cursorGeometry(cursor);
320
- const pointerSprite = cursorSprite(cursor, sharpest);
321
- const pointerTexture = compositor.sprite(pointerSprite.canvas);
322
- const chromeTexture = stage.chrome ? compositor.sprite(chromeSprite(frame, viewport.width, stage.chrome / stage.scale, stage.radius / stage.scale, sharpest)) : null;
323
- const pressList = presses(events);
324
- const sparkReach = clickEffect.radius + clickEffect.length + 8;
325
- let sparkTexture = null;
326
492
  const origin = current.timestamp;
327
493
  try {
328
494
  for (let i = 0; i < frameCount; i++) {
@@ -331,21 +497,7 @@ window.cuetakeRender = async ({ sourceUrl, finalUrl, duration, viewport, pointer
331
497
  const due = origin + Math.round(i * 1e6 / fps);
332
498
  while (next && next.timestamp <= due) { current.close(); current = next; next = await reader.next(); }
333
499
  if (uploaded !== current) { compositor.upload(current); uploaded = current; }
334
- const t = i / fps, view = cameraView(cameraPath[i], stage, viewport);
335
- compositor.frame(view.x, view.y, view.zoom, draw => {
336
- if (chromeTexture) draw(chromeTexture, [stage.window.x, stage.window.y, stage.window.w, stage.chrome]);
337
- for (const spark of sparksAt(pressList, clickEffect, t)) {
338
- // Each spark is drawn at its on-screen scale so the thin rays stay crisp.
339
- const scale = stage.scale * view.zoom, size = Math.ceil(2 * sparkReach * scale);
340
- const ctx = new OffscreenCanvas(size, size).getContext('2d');
341
- ctx.scale(scale, scale);
342
- drawSpark(ctx, sparkReach, sparkReach, spark.progress, clickEffect, cursor.color);
343
- sparkTexture = compositor.sprite(ctx.canvas, sparkTexture, false);
344
- draw(sparkTexture, [...at(spark.x - sparkReach, spark.y - sparkReach), 2 * sparkReach * stage.scale, 2 * sparkReach * stage.scale]);
345
- }
346
- const point = pointerAt(pointer, t);
347
- if (point) draw(pointerTexture, [...at(point.x - geometry.hotspot.x - pointerSprite.margin, point.y - geometry.hotspot.y - pointerSprite.margin), pointerSprite.width * stage.scale, pointerSprite.height * stage.scale]);
348
- });
500
+ scene.draw(i / fps, cameraPath[i]);
349
501
  const videoFrame = new VideoFrame(compositor.canvas, { timestamp: Math.round(i * 1e6 / fps), duration: Math.round(1e6 / fps) });
350
502
  encoder.encode(videoFrame, { keyFrame: i % (fps * 2) === 0, ...(quantizer ? { avc: { quantizer } } : {}) });
351
503
  videoFrame.close();
@@ -381,15 +533,55 @@ window.cuetakeInspect = async url => {
381
533
  };
382
534
  };
383
535
 
384
- /** One Final frame at `seconds`, as a base64 PNG. */
385
- window.cuetakeFrame = async (url, seconds) => {
386
- const input = new MB.Input({ formats: MB.ALL_FORMATS, source: new MB.UrlSource(url) });
387
- const wrapped = await new MB.CanvasSink(await input.getPrimaryVideoTrack()).getCanvas(seconds);
388
- if (!wrapped) throw new Error(`No frame at ${seconds} s`);
389
- const { canvas } = wrapped;
536
+ /**
537
+ * A Preview as a base64 PNG: each tile's Edit composed by the same scene as Render, over the Source at
538
+ * `at` seconds with the Final's camera, or (`at` null) over the last moment with the camera wide.
539
+ */
540
+ window.cuetakePreview = async ({ sourceUrl, duration, viewport, pointer, events, tiles, at }) => {
541
+ const input = new MB.Input({ formats: MB.ALL_FORMATS, source: new MB.UrlSource(sourceUrl) });
542
+ const track = await input.getPrimaryVideoTrack();
543
+ const sink = new MB.VideoSampleSink(track), origin = await track.getFirstTimestamp();
544
+ const t = at ?? duration;
545
+ const firstSample = await sink.getSample(origin), sample = await sink.getSample(origin + t);
546
+ if (!firstSample || !sample) throw new Error('Source has no video frames');
547
+ const firstFrame = firstSample.toVideoFrame(), frame = sample.toVideoFrame();
548
+ try {
549
+ const sheet = previewSheet(tiles.map(({ edit }) => outputSize(edit)));
550
+ const ctx = new OffscreenCanvas(sheet.width, sheet.height).getContext('2d');
551
+ ctx.fillStyle = '#111114'; ctx.fillRect(0, 0, sheet.width, sheet.height);
552
+ ctx.imageSmoothingQuality = 'high';
553
+ ctx.font = '600 22px system-ui, -apple-system, sans-serif'; ctx.textBaseline = 'middle'; ctx.fillStyle = '#e5e7eb';
554
+ for (const [i, { name, edit }] of tiles.entries()) {
555
+ const scene = await createScene(edit, viewport, { pointer, events }, firstFrame, track.codedWidth, track.codedHeight);
556
+ let crop = { x: 0, y: 0, w: viewport.width, h: viewport.height };
557
+ if (at !== null) {
558
+ const { fps } = edit.output, path = cameraTrack({ targets: edit.camera.targets, viewport, camera: edit.camera, duration, fps, pointerAt: s => pointerAt(pointer, s) });
559
+ crop = path[Math.min(Math.round(at * fps), path.length - 1)] ?? crop;
560
+ }
561
+ scene.compositor.upload(frame);
562
+ scene.draw(t, crop);
563
+ // Copy before yielding: the WebGL canvas does not keep its drawing buffer.
564
+ const tile = sheet.tiles[i];
565
+ ctx.drawImage(scene.compositor.canvas, tile.x, tile.y, tile.w, tile.h);
566
+ if (tile.label) ctx.fillText(name, tile.label.x, tile.label.y);
567
+ scene.compositor.dispose();
568
+ }
569
+ return await pngBase64(ctx.canvas);
570
+ } finally { firstFrame.close(); frame.close(); firstSample.close(); sample.close(); }
571
+ };
572
+
573
+ async function pngBase64(canvas) {
390
574
  const blob = canvas.convertToBlob ? await canvas.convertToBlob({ type: 'image/png' }) : await new Promise(resolve => canvas.toBlob(resolve, 'image/png'));
391
575
  const bytes = new Uint8Array(await blob.arrayBuffer());
392
576
  let binary = '';
393
577
  for (let i = 0; i < bytes.length; i += 32768) binary += String.fromCharCode(...bytes.subarray(i, i + 32768));
394
578
  return btoa(binary);
579
+ }
580
+
581
+ /** One Final frame at `seconds`, as a base64 PNG. */
582
+ window.cuetakeFrame = async (url, seconds) => {
583
+ const input = new MB.Input({ formats: MB.ALL_FORMATS, source: new MB.UrlSource(url) });
584
+ const wrapped = await new MB.CanvasSink(await input.getPrimaryVideoTrack()).getCanvas(seconds);
585
+ if (!wrapped) throw new Error(`No frame at ${seconds} s`);
586
+ return pngBase64(wrapped.canvas);
395
587
  };