cuetake 0.3.0 → 0.5.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.
@@ -3,16 +3,34 @@
3
3
  * MP4, streamed back to Node in chunks.
4
4
  *
5
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).
6
+ * every frame around the window as the camera moves it), the page, then the chrome; each popup window
7
+ * over it the same way; then click effects and the Cursor, and outside the camera the Subtitles and
8
+ * keycaps. Masks (masks.js) blur or cover parts of a page as it is drawn, and spotlights dim the windows
9
+ * and the Background around parts of them, all in one pass after the last window. Everything but the pages and masks is agent-written shaders, drawing code or images (ADR 0005). Each
10
+ * Tab has its own Source (ADR 0008); tabs.js says which show at each moment. A Take of Apps has one Tab,
11
+ * its Desktop, drawn once per App window showing (desktop.js), each clipped to its frame with its own
12
+ * effects, so the Background shows between them (ADR 0009).
8
13
  *
9
- * Spaces: camera crops are CSS pixels of the viewport; the Source texture is sampled by UV only;
14
+ * Spaces: camera crops are CSS pixels of the viewport, the window's, which each Tab's input is moved
15
+ * into (tabs.js); the Source textures are sampled by UV only;
10
16
  * "stage" is the Final's pixels at camera zoom 1, laid out by stage.js.
17
+ *
18
+ * Times: the Timeline and the Edit are in Source time, the Final in its own, and time-map.js maps
19
+ * between them. The page's own motion (the Source, the Cursor, click effects) plays at the Final
20
+ * moment's Source time, so it fast-forwards with the page; the camera, keycaps, Subtitles and audio
21
+ * keep their pace in Final time.
11
22
  */
12
23
  import * as MB from '/mediabunny.js';
13
24
  import { cameraTrack } from '/camera.js';
14
- import { pointerAt, presses, sparksAt } from '/cursor.js';
25
+ import { cursorTrack, drawnShape, pointerAt, presses, sparksAt } from '/cursor.js';
15
26
  import { layout, outputSize, cameraView, previewSheet, brandColor } from '/stage.js';
27
+ import { burnsIn, cuesFor, lineProblems } from '/narration.js';
28
+ import { keycapTrack } from '/shortcuts.js';
29
+ import { badgeAt, linesInFinal, retimed, timeMap } from '/time-map.js';
30
+ import { inWindow, tabTrack, windowMaps } from '/tabs.js';
31
+ import { cropAt, exposure, moments, shutterOf } from '/shutter.js';
32
+ import { mergedPast, maskProblems, maskTrack } from '/masks.js';
33
+ import { drawnWindows, windowsAt } from '/desktop.js';
16
34
 
17
35
  const VERTEX = `#version 300 es
18
36
  in vec2 p; void main() { gl_Position = vec4(p, 0, 1); }`;
@@ -28,6 +46,7 @@ uniform vec4 uWindow; // the window (chrome + page) in output pixels: l
28
46
  uniform float uRadius; // the window's corner radius in output pixels
29
47
  uniform float uZoom; // the camera zoom; 1 for Background layers
30
48
  out vec4 color; // premultiplied RGBA
49
+ #define main cuetakeMain
31
50
  vec2 pixel() { return vec2(gl_FragCoord.x, uResolution.y - gl_FragCoord.y); }
32
51
  vec4 previous(vec2 px) { return texture(uPrevious, vec2(px.x, uResolution.y - px.y) / uResolution); }
33
52
  float windowDistance(vec2 px) {
@@ -35,31 +54,103 @@ float windowDistance(vec2 px) {
35
54
  return length(max(q, 0.0)) + min(max(q.x, q.y), 0.0) - uRadius;
36
55
  }
37
56
  `;
38
- const HEADER_UNIFORMS = new Set(['uResolution', 'uUnit', 'uBrand', 'uPrevious', 'uPage', 'uWindow', 'uRadius', 'uZoom']);
57
+ const HEADER_UNIFORMS = new Set(['uResolution', 'uUnit', 'uBrand', 'uPrevious', 'uPage', 'uWindow', 'uRadius', 'uZoom', 'uOpacity']);
58
+ /** Appended to every agent shader: CueTake fades its output, such as a popup window's shadow as it opens. */
59
+ const SHADER_FOOTER = `
60
+ #undef main
61
+ uniform float uOpacity;
62
+ void main() { cuetakeMain(); color *= uOpacity; }`;
39
63
  // An image layer is drawn over the layers below it.
40
64
  const IMAGE_LAYER = `uniform sampler2D image;
41
65
  void main() { vec4 top = texture(image, pixel() / uResolution); color = top + previous(pixel()) * (1.0 - top.a); }`;
42
66
  const BLIT = `#version 300 es
43
67
  precision highp float;
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.
68
+ uniform sampler2D uImage; uniform vec2 uRes; uniform float uAlpha; out vec4 color;
69
+ void main() { color = texture(uImage, gl_FragCoord.xy / uRes) * uAlpha; }`;
70
+ // Rounded boxes in stage pixels, shared by the page and the spotlight.
71
+ const ROUNDED_BOX = `
72
+ float roundedBox(vec2 p, vec4 rect, float r) {
73
+ vec2 q = abs(p - rect.xy - rect.zw * 0.5) - (rect.zw * 0.5 - r);
74
+ return length(max(q, 0.0)) + min(max(q.x, q.y), 0.0) - r;
75
+ }`;
76
+ /** How many boxes one pass of the page or a spotlight takes; more are merged into the last (masks.js). */
77
+ const MASK_BOXES = 32;
78
+ // A page inside its window's rounded rectangle, below the chrome, under the camera. Its blurred and
79
+ // covered masks are drawn with it, replacing the page where they sit, so a page fading in or out never
80
+ // shows what they hide. Each hidden box has a style: its corner radius, 0 to blur or 1 to cover, and
81
+ // the blur's mip level; covers have a color.
47
82
  const PAGE = `#version 300 es
48
83
  precision highp float;
49
- uniform vec2 uRes; uniform vec3 uCam; uniform vec4 uPage; uniform vec4 uWindow; uniform float uRadius;
84
+ uniform vec2 uRes; uniform vec3 uCam; uniform vec4 uPage; uniform vec4 uWindow; uniform float uRadius; uniform float uAlpha;
50
85
  uniform sampler2D uSource;
86
+ uniform int uHidden; uniform vec4 uHideRect[${MASK_BOXES}]; uniform vec4 uHideStyle[${MASK_BOXES}]; uniform vec4 uHideColor[${MASK_BOXES}];
51
87
  out vec4 color;
52
- float roundedBox(vec2 p, vec4 rect, float r) {
53
- vec2 q = abs(p - rect.xy - rect.zw * 0.5) - (rect.zw * 0.5 - r);
54
- return length(max(q, 0.0)) + min(max(q.x, q.y), 0.0) - r;
88
+ ${ROUNDED_BOX}
89
+ // A Gaussian over 7×7 taps of a mip level, two taps to a standard deviation: unreadable, and cheap at any size.
90
+ vec3 blurred(vec2 uv, float lod) {
91
+ vec2 step = exp2(lod) / vec2(textureSize(uSource, 0));
92
+ vec3 sum = vec3(0.0); float total = 0.0;
93
+ for (int i = -3; i <= 3; i++) for (int j = -3; j <= 3; j++) {
94
+ float w = exp(-float(i * i + j * j) / 8.0);
95
+ sum += textureLod(uSource, clamp(uv + vec2(i, j) * step, 0.0, 1.0), lod).rgb * w; total += w;
96
+ }
97
+ return sum / total;
55
98
  }
56
99
  void main() {
57
100
  vec2 pixel = vec2(gl_FragCoord.x, uRes.y - gl_FragCoord.y);
58
101
  vec2 stage = (pixel - uRes * 0.5) / uCam.z + uCam.xy;
59
102
  float inside = clamp(0.5 - roundedBox(stage, uWindow, uRadius) * uCam.z, 0.0, 1.0);
60
103
  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;
104
+ vec2 uv = clamp((stage - uPage.xy) / uPage.zw, 0.0, 1.0);
105
+ vec3 rgb = texture(uSource, uv).rgb;
106
+ for (int i = 0; i < ${MASK_BOXES}; i++) {
107
+ if (i >= uHidden) break;
108
+ vec4 r = uHideRect[i], style = uHideStyle[i];
109
+ float hidden = clamp(0.5 - roundedBox(stage, r, min(style.x, 0.5 * min(r.z, r.w))) * uCam.z, 0.0, 1.0);
110
+ if (hidden > 0.0) rgb = mix(rgb, style.y > 0.5 ? uHideColor[i].rgb : blurred(uv, style.z), hidden);
111
+ }
112
+ color = vec4(rgb, 1.0) * inside * uAlpha;
62
113
  }`;
114
+ // Every spotlight showing, in one pass: the frame dimmed by `uColor.a`, and lit inside each box by its
115
+ // weight, the light falling off over its feather in stage pixels across its edge. Each box's style is
116
+ // its corner radius, its feather and its weight.
117
+ const SPOTLIGHT = `#version 300 es
118
+ precision highp float;
119
+ uniform vec2 uRes; uniform vec3 uCam; uniform int uCount; uniform vec4 uRects[${MASK_BOXES}]; uniform vec4 uStyles[${MASK_BOXES}];
120
+ uniform vec4 uColor;
121
+ out vec4 color;
122
+ ${ROUNDED_BOX}
123
+ void main() {
124
+ vec2 pixel = vec2(gl_FragCoord.x, uRes.y - gl_FragCoord.y);
125
+ vec2 stage = (pixel - uRes * 0.5) / uCam.z + uCam.xy;
126
+ float lit = 0.0;
127
+ for (int i = 0; i < ${MASK_BOXES}; i++) {
128
+ if (i >= uCount) break;
129
+ vec4 r = uRects[i], style = uStyles[i];
130
+ // The light falls off across the box's edge, half inside it and half out.
131
+ float soft = max(style.y, 1.0 / uCam.z) * 0.5;
132
+ lit = max(lit, style.z * (1.0 - smoothstep(-soft, soft, roundedBox(stage, r, min(style.x, 0.5 * min(r.z, r.w))))));
133
+ }
134
+ float a = uColor.a * (1.0 - lit);
135
+ color = vec4(uColor.rgb * a, a);
136
+ }`;
137
+
138
+ /**
139
+ * The spotlights showing (`{ rects, corner, feather, color, dim, opacity }`, in stage pixels) as one
140
+ * pass, so none dims another's region: the frame dims as much as the strongest, in its color, and each
141
+ * lights its boxes as far as it has eased in beside the furthest. Null when none dims.
142
+ */
143
+ function spotlightPass(lights) {
144
+ const strongest = lights.reduce((a, b) => (b.dim * b.opacity > a.dim * a.opacity ? b : a), lights[0]);
145
+ if (!strongest || strongest.dim * strongest.opacity <= 0) return null;
146
+ const furthest = Math.max(...lights.map(light => light.opacity));
147
+ const boxes = mergedPast(lights.flatMap(light => light.rects.map(([x, y, width, height]) => ({ rect: { x, y, width, height }, light }))), MASK_BOXES);
148
+ return {
149
+ count: boxes.length, rects: new Float32Array(boxes.flatMap(({ rect }) => [rect.x, rect.y, rect.width, rect.height])),
150
+ styles: new Float32Array(boxes.flatMap(({ light }) => [light.corner, light.feather, light.opacity / furthest, 0])),
151
+ color: [...strongest.color, strongest.dim * strongest.opacity],
152
+ };
153
+ }
63
154
  // Sprites (chrome, cursor, click effects) are premultiplied textures placed by a stage rectangle under the camera.
64
155
  const SPRITE_VERTEX = `#version 300 es
65
156
  in vec2 p;
@@ -72,13 +163,13 @@ void main() {
72
163
  }`;
73
164
  const SPRITE_FRAGMENT = `#version 300 es
74
165
  precision highp float;
75
- uniform sampler2D uSprite;
166
+ uniform sampler2D uSprite; uniform float uAlpha;
76
167
  in vec2 uv; out vec4 color;
77
- void main() { color = texture(uSprite, uv); }`;
168
+ void main() { color = texture(uSprite, uv) * uAlpha; }`;
78
169
 
79
170
  // Item keys CueTake reads itself; every other key is a parameter for the item's shader or drawing code.
80
171
  const OWN_KEYS = new Set(['shader', 'draw', 'image', 'files', 'ref', 'kind', 'url']);
81
- const SLOT_KEYS = new Set(['size', 'hotspot', 'duration', 'reach', 'height']);
172
+ const SLOT_KEYS = new Set(['size', 'hotspot', 'press', 'duration', 'singleKeys', 'reach', 'height', 'burn', 'maxChars', 'maxRows', 'minDuration']);
82
173
  const paramsOf = item => Object.fromEntries(Object.entries(item).filter(([key]) => !OWN_KEYS.has(key) && (item.kind === 'shader' || !SLOT_KEYS.has(key))));
83
174
  const fail = (item, error) => new Error(`${item.ref}: ${error?.message ?? error}`);
84
175
 
@@ -122,8 +213,8 @@ const canvas2d = (width, height) => {
122
213
  return canvas.getContext('2d');
123
214
  };
124
215
 
125
- /** The compositor for one stage: the Background drawn once, then per frame effects, page and sprites. */
126
- function createCompositor(stage, sourceWidth, sourceHeight, brand) {
216
+ /** The compositor for one stage: the Background drawn once, then per frame each window's effects, page and chrome, and sprites. */
217
+ function createCompositor(stage, brand) {
127
218
  const { width, height } = stage, unit = Math.min(width, height) / 1080;
128
219
  const canvas = new OffscreenCanvas(width, height);
129
220
  const gl = canvas.getContext('webgl2', { alpha: false, antialias: false, depth: false });
@@ -166,15 +257,9 @@ function createCompositor(stage, sourceWidth, sourceHeight, brand) {
166
257
  gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
167
258
  gl.viewport(0, 0, width, height);
168
259
 
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);
260
+ const pageProgram = program(VERTEX, PAGE), spotlightProgram = program(VERTEX, SPOTLIGHT);
176
261
  const blitProgram = program(VERTEX, BLIT);
177
- const spriteProgram = program(SPRITE_VERTEX, SPRITE_FRAGMENT), spriteRect = spriteProgram.uniform('uRect');
262
+ const spriteProgram = program(SPRITE_VERTEX, SPRITE_FRAGMENT), spriteRect = spriteProgram.uniform('uRect'), spriteAlpha = spriteProgram.uniform('uAlpha');
178
263
 
179
264
  /** An agent shader with its parameters declared and set, and its `files` bound from texture unit 2. */
180
265
  async function agentProgram(item, source) {
@@ -184,8 +269,8 @@ function createCompositor(stage, sourceWidth, sourceHeight, brand) {
184
269
  ...params.filter(([name]) => !HEADER_UNIFORMS.has(name)).map(([name, [type]]) => `uniform ${type} ${name};`),
185
270
  ...images.flatMap(([name]) => [`uniform sampler2D ${name};`, `uniform vec2 ${name}Size;`]),
186
271
  ].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);
272
+ const p = program(VERTEX, `${SHADER_HEADER}${declarations}\n#line 1\n${source}\n${SHADER_FOOTER}`, item);
273
+ gl.uniform1f(p.uniform('uUnit'), unit); gl.uniform3f(p.uniform('uBrand'), ...brand); gl.uniform1f(p.uniform('uOpacity'), 1);
189
274
  gl.uniform1i(p.uniform('uPrevious'), 0); gl.uniform1i(p.uniform('uPage'), 1);
190
275
  for (const [name, [type, values]] of params) gl[`uniform${type === 'float' ? 1 : type.at(-1)}fv`](p.uniform(name), values);
191
276
  const textures = images.map(([name, image], i) => {
@@ -200,32 +285,71 @@ function createCompositor(stage, sourceWidth, sourceHeight, brand) {
200
285
  return response.text();
201
286
  };
202
287
  /** 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) => {
288
+ const run = (p, previous, page, windowRect, radius, zoom, opacity = 1) => {
204
289
  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);
290
+ gl.uniform4f(p.uniform('uWindow'), ...windowRect); gl.uniform1f(p.uniform('uRadius'), radius); gl.uniform1f(p.uniform('uZoom'), zoom); gl.uniform1f(p.uniform('uOpacity'), opacity);
291
+ bind(0, previous); bind(1, page);
207
292
  p.textures?.forEach((t, i) => bind(2 + i, t));
208
293
  gl.bindVertexArray(fullScreen); gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
209
294
  gl.activeTexture(gl.TEXTURE0);
210
295
  };
211
296
  const checkGpu = what => { if (gl.isContextLost()) throw new Error(`${what} stopped the GPU; simplify the shader`); };
212
297
 
213
- const target = () => { const t = texture(gl.LINEAR); gl.texStorage2D(gl.TEXTURE_2D, 1, gl.RGBA8, width, height); return t; };
298
+ const target = (format = gl.RGBA8) => { const t = texture(gl.LINEAR); gl.texStorage2D(gl.TEXTURE_2D, 1, format, width, height); return t; };
214
299
  const framebuffer = gl.createFramebuffer();
215
300
  let background = target(), effects = [];
216
301
  const restWindow = [stage.window.x, stage.window.y, stage.window.w, stage.window.h];
302
+ const blit = (image, alpha = 1) => { gl.useProgram(blitProgram.p); gl.uniform1f(blitProgram.uniform('uAlpha'), alpha); bind(0, image); gl.bindVertexArray(fullScreen); gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4); };
303
+ const drawInto = (buffer, image) => { gl.bindFramebuffer(gl.FRAMEBUFFER, buffer); if (buffer) gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, image, 0); };
304
+
305
+ // Motion blur averages moments in a half-float buffer, so many faint moments add up without banding.
306
+ // Without float render targets the Final shows one sharp moment per frame. The buffers are made on
307
+ // the first blurred frame, so a Final without blur holds no extra GPU memory.
308
+ const blurs = !!gl.getExtension('EXT_color_buffer_float');
309
+ const momentBuffer = gl.createFramebuffer(), sumBuffer = gl.createFramebuffer();
310
+ let layer = null, sum = null;
311
+ /**
312
+ * Draws `count` moments of premultiplied content over the frame so far, averaged: each moment over a
313
+ * clear layer, the layers summed at 1/count each, the sum drawn over the frame. Averaging the layers
314
+ * then drawing them over is the average of drawing each over, since the frame below is the same for
315
+ * all. `area`, [x, y, w, h] in output pixels with y down, bounds what the moments draw.
316
+ */
317
+ const averaged = (count, drawMoment, area) => {
318
+ if (count === 1) return drawMoment(0);
319
+ layer ??= target(); sum ??= target(gl.RGBA16F);
320
+ if (area) { gl.enable(gl.SCISSOR_TEST); gl.scissor(Math.floor(area[0]), Math.floor(height - area[1] - area[3]), Math.ceil(area[2]) + 1, Math.ceil(area[3]) + 1); }
321
+ drawInto(sumBuffer, sum); gl.clearColor(0, 0, 0, 0); gl.clear(gl.COLOR_BUFFER_BIT);
322
+ for (let i = 0; i < count; i++) {
323
+ drawInto(momentBuffer, layer); gl.clear(gl.COLOR_BUFFER_BIT);
324
+ gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA); drawMoment(i);
325
+ drawInto(sumBuffer, sum); gl.blendFunc(gl.ONE, gl.ONE); blit(layer, 1 / count);
326
+ }
327
+ drawInto(null); gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA); blit(sum);
328
+ gl.disable(gl.SCISSOR_TEST);
329
+ };
217
330
  return {
218
331
  canvas,
332
+ /** Whether the GPU can average moments for motion blur. */
333
+ blurs,
219
334
  gpu: (() => { const info = gl.getExtension('WEBGL_debug_renderer_info'); return info ? gl.getParameter(info.UNMASKED_RENDERER_WEBGL) : 'unknown'; })(),
335
+ /** The widest and tallest texture the GPU holds; a larger sprite would draw black. */
336
+ maxTextureSize: gl.getParameter(gl.MAX_TEXTURE_SIZE),
220
337
  /** Frees the GPU context; a Preview makes one compositor per tile. */
221
338
  dispose() { gl.getExtension('WEBGL_lose_context')?.loseContext(); },
222
- upload(frame) {
223
- gl.bindTexture(gl.TEXTURE_2D, pageTexture);
339
+ /** A texture for a Source `width` × `height`, which `upload` fills with each frame. */
340
+ pageTexture(width, height) {
341
+ // Mipmaps keep zoomed-out text from aliasing when the 2× Source is minified.
342
+ const t = texture();
343
+ gl.texStorage2D(gl.TEXTURE_2D, Math.floor(Math.log2(Math.max(width, height))) + 1, gl.RGBA8, width, height);
344
+ return t;
345
+ },
346
+ upload(page, frame) {
347
+ gl.bindTexture(gl.TEXTURE_2D, page);
224
348
  gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, gl.RGBA, gl.UNSIGNED_BYTE, frame);
225
349
  gl.generateMipmap(gl.TEXTURE_2D);
226
350
  },
227
- /** Draws the Background layers in order, each over the result so far, starting from black. */
228
- async drawBackground(layers) {
351
+ /** Draws the Background layers in order, each over the result so far, starting from black; they see `page`. */
352
+ async drawBackground(layers, page) {
229
353
  let other = target();
230
354
  gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
231
355
  gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, background, 0);
@@ -244,7 +368,7 @@ function createCompositor(stage, sourceWidth, sourceHeight, brand) {
244
368
  gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
245
369
  gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, other, 0);
246
370
  gl.disable(gl.BLEND);
247
- run(p, background, restWindow, stage.radius, 1);
371
+ run(p, background, page, restWindow, stage.radius, 1);
248
372
  [background, other] = [other, background];
249
373
  }
250
374
  gl.bindFramebuffer(gl.FRAMEBUFFER, null);
@@ -265,17 +389,50 @@ function createCompositor(stage, sourceWidth, sourceHeight, brand) {
265
389
  if (mipmaps) gl.generateMipmap(gl.TEXTURE_2D);
266
390
  return t;
267
391
  },
268
- /** One frame with the camera at stage point (x, y) and `zoom`; `draw(texture, rect)` in `overlay` places sprites in stage pixels. */
269
- frame(x, y, zoom, overlay) {
270
- gl.disable(gl.BLEND);
271
- gl.useProgram(blitProgram.p); bind(0, background); gl.bindVertexArray(fullScreen); gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
272
- gl.enable(gl.BLEND);
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);
278
- overlay((t, rect) => { gl.bindTexture(gl.TEXTURE_2D, t); gl.uniform4f(spriteRect, ...rect); gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4); });
392
+ /**
393
+ * One frame over the Background. Under each of `views`, the camera ({ x, y, zoom }: the stage point
394
+ * at the Final's center) at the moments the frame averages, each of `windows` is drawn in order, each
395
+ * `{ page, pageRect, window, radius, opacity, effects, chrome: { texture, rect }, hidden, spotlights }`
396
+ * in stage pixels, with the window effects around it when `effects` and its blurred and covered boxes
397
+ * (`hidden`: `{ count, rects, styles, colors }`) drawn with the page. Every window's `spotlights`
398
+ * (`{ rects, corner, feather, color, dim, opacity }`) then dim the windows and the Background together
399
+ * in one pass, and `draw(texture, rect, opacity)` in `overlay` places sprites in stage pixels. Then each of `cursors`, `{ view, texture, rect, opacity }` at the moments
400
+ * the Cursor averages, within `cursorArea` in output pixels; and `screen` places sprites in output
401
+ * pixels, outside the camera. Several views or cursors need `blurs`.
402
+ */
403
+ frame(views, windows, overlay, cursors, cursorArea, screen) {
404
+ drawInto(null);
405
+ gl.disable(gl.BLEND); blit(background); gl.enable(gl.BLEND);
406
+ const place = (t, rect, opacity = 1) => { gl.bindTexture(gl.TEXTURE_2D, t); gl.uniform4f(spriteRect, ...rect); gl.uniform1f(spriteAlpha, opacity); gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4); };
407
+ const sprites = ({ x, y, zoom }) => { gl.useProgram(spriteProgram.p); gl.uniform3f(spriteProgram.camera, x, y, zoom); gl.bindVertexArray(unitQuad); };
408
+ const spotlight = spotlightPass(windows.flatMap(w => (w.spotlights ?? []).map(light => ({ ...light, opacity: light.opacity * w.opacity }))));
409
+ averaged(views.length, i => {
410
+ const view = views[i], { x, y, zoom } = view;
411
+ for (const w of windows) {
412
+ const shown = [(w.window.x - x) * zoom + width / 2, (w.window.y - y) * zoom + height / 2, w.window.w * zoom, w.window.h * zoom];
413
+ if (w.effects) for (const p of effects) run(p, background, w.page, shown, w.radius * zoom, zoom, w.opacity);
414
+ gl.useProgram(pageProgram.p); gl.uniform3f(pageProgram.camera, x, y, zoom);
415
+ gl.uniform4f(pageProgram.uniform('uPage'), w.pageRect.x, w.pageRect.y, w.pageRect.w, w.pageRect.h);
416
+ gl.uniform4f(pageProgram.uniform('uWindow'), w.window.x, w.window.y, w.window.w, w.window.h);
417
+ gl.uniform1f(pageProgram.uniform('uRadius'), w.radius); gl.uniform1f(pageProgram.uniform('uAlpha'), w.opacity);
418
+ gl.uniform1i(pageProgram.uniform('uHidden'), w.hidden?.count ?? 0);
419
+ if (w.hidden?.count) {
420
+ gl.uniform4fv(pageProgram.uniform('uHideRect'), w.hidden.rects); gl.uniform4fv(pageProgram.uniform('uHideStyle'), w.hidden.styles); gl.uniform4fv(pageProgram.uniform('uHideColor'), w.hidden.colors);
421
+ }
422
+ bind(0, w.page); gl.bindVertexArray(fullScreen); gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
423
+ if (w.chrome) { sprites(view); place(w.chrome.texture, w.chrome.rect, w.opacity); }
424
+ }
425
+ if (spotlight) {
426
+ gl.useProgram(spotlightProgram.p); gl.uniform3f(spotlightProgram.camera, x, y, zoom);
427
+ gl.uniform1i(spotlightProgram.uniform('uCount'), spotlight.count); gl.uniform4fv(spotlightProgram.uniform('uRects'), spotlight.rects);
428
+ gl.uniform4fv(spotlightProgram.uniform('uStyles'), spotlight.styles); gl.uniform4f(spotlightProgram.uniform('uColor'), ...spotlight.color);
429
+ gl.bindVertexArray(fullScreen); gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
430
+ }
431
+ sprites(view);
432
+ overlay(place);
433
+ });
434
+ if (cursors.length) averaged(cursors.length, i => { sprites(cursors[i].view); place(cursors[i].texture, cursors[i].rect, cursors[i].opacity); }, cursorArea);
435
+ if (screen) { sprites({ x: width / 2, y: height / 2, zoom: 1 }); screen(place); }
279
436
  if (effects.length) checkGpu('A window effect');
280
437
  },
281
438
  };
@@ -283,60 +440,70 @@ function createCompositor(stage, sourceWidth, sourceHeight, brand) {
283
440
 
284
441
  /**
285
442
  * 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.
443
+ * params, files })`, or an image as wide as the window. `canvas(width, scale, radius, url)` rasterizes
444
+ * it `width` CSS px wide, the window's or a popup window's, with the address bar showing `url`, clipped
445
+ * to the window's rounded top.
288
446
  */
289
- async function loadChrome(item, width, url) {
447
+ async function loadChrome(item, windowWidth) {
290
448
  let height, paint;
291
449
  if (item.kind === 'image') {
292
450
  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);
451
+ height = item.height ?? image.naturalHeight * windowWidth / image.naturalWidth;
452
+ paint = (ctx, width) => ctx.drawImage(image, 0, 0, width, height);
295
453
  } else {
296
454
  const module = await loadModule(item), files = await loadFiles(item), params = paramsOf(item);
297
455
  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 });
456
+ paint = (ctx, width, radius, url) => module.draw(ctx, { width, height, radius, url, params, files });
299
457
  }
300
458
  return {
301
459
  height,
302
- canvas(scale, radius) {
460
+ canvas(width, scale, radius, url) {
303
461
  const ctx = canvas2d(width * scale, height * scale);
304
462
  ctx.scale(scale, scale);
305
463
  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); }
464
+ try { paint(ctx, width, radius, url); } catch (error) { throw fail(item, error); }
307
465
  return ctx.canvas;
308
466
  },
309
467
  };
310
468
  }
311
469
 
312
470
  /**
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.
471
+ * The cursor: drawing code exporting `shapes` (each shape's { width, height, hotspot: [x, y] } in the
472
+ * code's own units, `default` among them, with `frames` for one that loops each second) and
473
+ * `draw(ctx, { shape, phase, params, files })` in those units, or an image of the default shape whose
474
+ * `hotspot` the item names. The default shape is `size` CSS px wide and the others share its scale;
475
+ * each sprite has a margin of a quarter box around it for shadows.
316
476
  */
317
477
  async function loadCursor(item) {
318
- let box, paint;
478
+ let boxes, paint;
319
479
  if (item.kind === 'image') {
320
480
  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);
481
+ boxes = { default: { width: image.naturalWidth || 32, height: image.naturalHeight || 32, hotspot: item.hotspot ?? [0, 0] } };
482
+ paint = ctx => ctx.drawImage(image, 0, 0, boxes.default.width, boxes.default.height);
323
483
  } else {
324
484
  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 });
485
+ boxes = module.shapes;
486
+ if (!boxes?.default) throw fail(item, 'a cursor exports `shapes` with a `default` box');
487
+ paint = (ctx, shape, phase) => module.draw(ctx, { shape, phase, params, files });
327
488
  }
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
- };
489
+ const k = (item.size ?? 24) / boxes.default.width;
490
+ return Object.fromEntries(Object.entries(boxes).map(([shape, box]) => {
491
+ const margin = Math.max(box.width, box.height) / 4;
492
+ return [shape, {
493
+ /** Where the sprite's top-left sits relative to the pointer, and its size, in CSS px. */
494
+ offset: { x: -(box.hotspot[0] + margin) * k, y: -(box.hotspot[1] + margin) * k },
495
+ size: { w: (box.width + 2 * margin) * k, h: (box.height + 2 * margin) * k },
496
+ /** The shape's pictures through one second, or its only one. */
497
+ canvases(scale) {
498
+ return Array.from({ length: Math.max(1, Math.round(box.frames ?? 1)) }, (_, frame, frames = box.frames ?? 1) => {
499
+ const ctx = canvas2d((box.width + 2 * margin) * k * scale, (box.height + 2 * margin) * k * scale);
500
+ ctx.scale(k * scale, k * scale); ctx.translate(margin, margin);
501
+ try { paint(ctx, shape, frame / frames); } catch (error) { throw fail(item, error); }
502
+ return ctx.canvas;
503
+ });
504
+ },
505
+ }];
506
+ }));
340
507
  }
341
508
 
342
509
  /**
@@ -354,6 +521,118 @@ async function loadClickEffect(item, cursor) {
354
521
  return { reach, paint: (ctx, progress) => { try { module.draw(ctx, { progress, params, files, cursor }); } catch (error) { throw fail(item, error); } } };
355
522
  }
356
523
 
524
+ /**
525
+ * Drawing code over the whole Final in 1080p pixels, outside the camera, such as Subtitles and keycaps:
526
+ * `draw(ctx, { width, height, ...what, params, files })`. `canvas(width, height, what)` rasterizes it at output size.
527
+ */
528
+ async function loadScreenDrawing(item, name) {
529
+ if (item.kind !== 'draw') throw fail(item, `${name} are drawing code`);
530
+ const module = await loadModule(item), files = await loadFiles(item), params = paramsOf(item);
531
+ return {
532
+ canvas(width, height, what) {
533
+ const unit = Math.min(width, height) / 1080, ctx = canvas2d(width, height);
534
+ ctx.scale(unit, unit);
535
+ try { module.draw(ctx, { width: width / unit, height: height / unit, ...what, params, files }); } catch (error) { throw fail(item, error); }
536
+ return ctx.canvas;
537
+ },
538
+ };
539
+ }
540
+
541
+ const SAMPLE_RATE = 48000, AUDIO_BITRATE = 128000;
542
+ /** WebCodecs microseconds as samples at SAMPLE_RATE. */
543
+ const samplesIn = microseconds => Math.round(microseconds * SAMPLE_RATE / 1e6);
544
+ /** Each Line's audio decoded at 48 kHz; the error names a Line whose audio cannot be read. */
545
+ async function decodeLines(lines) {
546
+ const context = new OfflineAudioContext(1, 1, SAMPLE_RATE);
547
+ return Promise.all(lines.map(async line => {
548
+ const response = await fetch(line.url);
549
+ if (!response.ok) throw new Error(`Line '${line.id}': its audio ${line.audio} could not be read (${response.status})`);
550
+ try { return await context.decodeAudioData(await response.arrayBuffer()); }
551
+ catch { throw new Error(`Line '${line.id}': its audio ${line.audio} is not a format the browser decodes; use WAV, MP3, M4A, Ogg or FLAC`); }
552
+ }));
553
+ }
554
+
555
+ /**
556
+ * The Narration as Render plays it: each Line's decoded audio and measured duration, placed in Final
557
+ * time by `map`, and its subtitle cues. Lines that overlap, run past `seconds`, the Final's length, or
558
+ * speak while it fast-forwards stop the Render.
559
+ */
560
+ async function prepareNarration(narration, subtitles, seconds, map) {
561
+ if (!narration?.lines.length) return null;
562
+ const buffers = await decodeLines(narration.lines);
563
+ const { lines: placed, problems: forwarded } = linesInFinal(narration.lines.map((line, i) => ({ ...line, duration: buffers[i].duration })), map);
564
+ const problems = [...forwarded, ...lineProblems(placed, seconds)];
565
+ if (problems.length) throw new Error(`The Narration does not fit: ${problems.join('; ')}`);
566
+ return { placed, buffers, cues: cuesFor(placed, narration.language, subtitles, seconds) };
567
+ }
568
+
569
+ /** The Lines mixed into one mono track `seconds` long, each at its start and volume. */
570
+ function mixLines({ placed, buffers }, volume, seconds) {
571
+ const context = new OfflineAudioContext(1, Math.max(1, Math.round(seconds * SAMPLE_RATE)), SAMPLE_RATE);
572
+ placed.forEach((line, i) => {
573
+ const source = new AudioBufferSourceNode(context, { buffer: buffers[i] });
574
+ source.connect(new GainNode(context, { gain: (volume ?? 1) * (line.volume ?? 1) })).connect(context.destination);
575
+ source.start(line.start);
576
+ });
577
+ return context.startRendering();
578
+ }
579
+
580
+ /** The first audio encoder config the browser supports: AAC where the platform encodes it (macOS, Windows), else Opus. */
581
+ async function audioConfig() {
582
+ for (const [codec, codecString] of [['aac', 'mp4a.40.2'], ['opus', 'opus']]) {
583
+ const config = { codec: codecString, numberOfChannels: 1, sampleRate: SAMPLE_RATE, bitrate: AUDIO_BITRATE };
584
+ if ((await AudioEncoder.isConfigSupported(config).catch(() => ({}))).supported) return { codec, config };
585
+ }
586
+ throw new Error('This browser encodes neither AAC nor Opus audio');
587
+ }
588
+
589
+ /**
590
+ * How many samples `config`'s encoder delays its input, measured: a burst of noise is encoded, decoded
591
+ * and lined up against itself. AAC encoders start with priming (2112 samples on macOS) yet stamp the
592
+ * first packet 0; Opus declares its own pre-skip, so it measures 0. Lengths here are in samples.
593
+ */
594
+ async function encoderDelay(config) {
595
+ const burst = 4096, longest = 8192, sent = new Float32Array(burst + longest + 2048);
596
+ for (let i = 0, seed = 1; i < burst; i++) { seed = (Math.imul(seed, 1664525) + 1013904223) >>> 0; sent[i] = seed / 2 ** 32 - 0.5; }
597
+ const chunks = [];
598
+ let decoderConfig = null, failure = null;
599
+ const encoder = new AudioEncoder({ output: (chunk, meta) => { chunks.push(chunk); decoderConfig ??= meta?.decoderConfig; }, error: error => { failure ??= error; } });
600
+ const received = new Float32Array(sent.length + longest);
601
+ const decoder = new AudioDecoder({
602
+ output: data => {
603
+ // Each decoded sample goes where its timestamp says, so a delay the encoder declares itself counts as none.
604
+ const at = samplesIn(data.timestamp), samples = new Float32Array(data.numberOfFrames);
605
+ data.copyTo(samples, { planeIndex: 0, format: 'f32-planar' });
606
+ data.close();
607
+ const from = Math.max(0, -at);
608
+ received.set(samples.subarray(from, Math.max(from, received.length - at)), at + from);
609
+ },
610
+ error: error => { failure ??= error; },
611
+ });
612
+ try {
613
+ encoder.configure(config);
614
+ const input = new AudioData({ format: 'f32-planar', sampleRate: SAMPLE_RATE, numberOfFrames: sent.length, numberOfChannels: 1, timestamp: 0, data: sent });
615
+ encoder.encode(input); input.close();
616
+ await encoder.flush();
617
+ decoder.configure(decoderConfig);
618
+ for (const chunk of chunks) decoder.decode(chunk);
619
+ await decoder.flush();
620
+ } finally {
621
+ if (encoder.state !== 'closed') encoder.close();
622
+ if (decoder.state !== 'closed') decoder.close();
623
+ }
624
+ if (failure) throw failure;
625
+ let best = 0, delay = -1;
626
+ for (let lag = 0; lag <= longest; lag++) {
627
+ let sum = 0;
628
+ for (let i = 0; i < burst; i++) sum += sent[i] * received[i + lag];
629
+ if (sum > best) { best = sum; delay = lag; }
630
+ }
631
+ const energy = sent.reduce((sum, v) => sum + v * v, 0);
632
+ if (best < energy / 2) throw new Error(`Could not measure the ${config.codec} encoder's delay`);
633
+ return delay;
634
+ }
635
+
357
636
  /** The page's brand color from the Source's first frame. */
358
637
  function brandOf(firstFrame) {
359
638
  const ctx = new OffscreenCanvas(96, 60).getContext('2d', { willReadFrequently: true });
@@ -369,13 +648,19 @@ export function avcCodec(width, height, fps) {
369
648
  return `avc1.6400${level.toString(16).toUpperCase().padStart(2, '0')}`;
370
649
  }
371
650
 
651
+ /**
652
+ * Frames decoded at most this many packets ahead. An H.264 decoder may hold back up to its 16-frame
653
+ * buffer before it outputs one, as with an App's MP4 Source, so fewer would wait on it forever.
654
+ */
655
+ const DECODE_AHEAD = 20;
656
+
372
657
  /** Decodes a track with bounded look-ahead so memory stays flat on long Takes. */
373
658
  function frameReader(track, decoderConfig) {
374
659
  const ready = [], waiting = [];
375
660
  let failure = null, submitted = 0, decoded = 0, ended = false;
376
661
  const wake = () => waiting.splice(0).forEach(resolve => resolve());
377
662
  const decoder = new VideoDecoder({ output: frame => { decoded++; ready.push(frame); wake(); }, error: error => { failure = error; wake(); } });
378
- decoder.configure(decoderConfig);
663
+ decoder.configure({ ...decoderConfig, optimizeForLatency: true });
379
664
  const packets = new MB.EncodedPacketSink(track).packets();
380
665
  return {
381
666
  stats: () => ({ submitted, decoded }),
@@ -383,7 +668,7 @@ function frameReader(track, decoderConfig) {
383
668
  while (!ready.length) {
384
669
  if (failure) throw failure;
385
670
  if (ended) return null;
386
- if (submitted - decoded >= 6) { await new Promise(resolve => waiting.push(resolve)); continue; }
671
+ if (submitted - decoded >= DECODE_AHEAD) { await new Promise(resolve => waiting.push(resolve)); continue; }
387
672
  const packet = await packets.next();
388
673
  if (packet.done) { await decoder.flush(); ended = true; continue; }
389
674
  decoder.decode(packet.value.toEncodedVideoChunk());
@@ -407,46 +692,187 @@ async function encoderConfig(width, height, fps, quality) {
407
692
  }
408
693
 
409
694
  /**
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.
695
+ * Everything Render draws for one Edit (as forRender in styles.js serves it). `timeline` holds the
696
+ * pointer path, cursor shapes, events, Tabs and the boxes of masked elements; `sizes` maps each Tab to its Source's size. `firstFrame`
697
+ * is the first Tab's first frame: Background layers see it, and it picks the brand color. `map` is the
698
+ * Take's time map. Each Tab's input is moved into the window's CSS pixels by where its popup sits.
414
699
  */
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;
700
+ async function createScene(edit, viewport, { pointer, shapes, events, tabs, elements = [], windows = null }, sizes, firstFrame, cues, map) {
701
+ const { camera, cursor, clickEffect, keycaps, shortcuts, frame, subtitles, fastForwardBadge } = edit;
702
+ // A mask Render cannot draw would show what it hides, so it stops the Render.
703
+ const maskIssues = maskProblems(edit.masks, elements, tabs.map(tab => tab.id));
704
+ if (maskIssues.length) throw new Error(`The masks cannot be drawn: ${maskIssues.join('; ')}`);
705
+ const masks = maskTrack(edit.masks, elements, map);
706
+ const chrome = frame.chrome ? await loadChrome(frame.chrome, viewport.width) : null;
418
707
  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 ?? []);
708
+ const compositor = createCompositor(stage, brandOf(firstFrame));
709
+ const pages = new Map();
710
+ const upload = (tab, videoFrame) => {
711
+ if (!pages.has(tab)) pages.set(tab, compositor.pageTexture(sizes.get(tab).width, sizes.get(tab).height));
712
+ compositor.upload(pages.get(tab), videoFrame);
713
+ };
714
+ upload(tabs[0].id, firstFrame);
715
+ await compositor.drawBackground(frame.background ?? [], pages.get(tabs[0].id));
422
716
  await compositor.loadEffects(frame.effects ?? []);
423
- // Page CSS pixels → stage pixels; sprites are rasterized for the closest zoom and mipmapped below it.
717
+ const maps = windowMaps(tabs, viewport, edit.tabs.placement), placed = inWindow({ pointer, events }, camera.targets, maps);
718
+ const shownTabs = tabTrack({ tabs, events, viewport }, edit.tabs, map), byId = new Map(tabs.map(tab => [tab.id, tab]));
719
+ // Window CSS pixels → stage pixels; sprites are rasterized for the closest zoom and mipmapped below it.
424
720
  const at = (x, y) => [stage.page.x + x * stage.scale, stage.page.y + y * stage.scale];
425
721
  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));
722
+ // A sprite past the GPU's texture limit draws black, so a large one is rasterized only as sharp as fits.
723
+ const fitting = (w, h) => Math.min(sharpest, compositor.maxTextureSize / Math.max(w, h, 1));
724
+ // Each Tab's address bar shows its text from `frame.urls` at each Source time; the first Tab starts on
725
+ // `frame.url`, any other empty. One sprite per width and text.
726
+ const addresses = (frame.urls ?? []).toSorted((a, b) => a.t - b.t);
727
+ const addressAt = (tab, source) => addresses.findLast(address => (address.tab ?? 0) === tab && address.t <= source)?.url ?? (tab === tabs[0].id ? frame.url ?? '' : '');
728
+ const chromeTextures = new Map();
729
+ const chromeFor = (width, url) => {
730
+ const key = `${width} ${url}`;
731
+ if (!chromeTextures.has(key)) chromeTextures.set(key, compositor.sprite(chrome.canvas(width, fitting(width, chrome.height), stage.radius / stage.scale, url)));
732
+ return chromeTextures.get(key);
733
+ };
734
+ /** A window as the compositor draws it: the window's own tab, or a popup window where it sits, scaled by its animation. */
735
+ const windowOf = ({ tab, popup, opacity, scale }, source, effects) => {
736
+ const url = addressAt(tab, source);
737
+ if (!popup) return { page: pages.get(tab), pageRect: stage.page, window: stage.window, radius: stage.radius, opacity, effects, chrome: chrome && { texture: chromeFor(viewport.width, url), rect: [stage.window.x, stage.window.y, stage.window.w, stage.chrome] } };
738
+ const m = maps.get(tab), { width, height } = byId.get(tab).viewport, bar = chrome ? chrome.height * m.scale : 0;
739
+ const [x, y] = at(m.x, m.y - bar), w = width * m.scale * stage.scale, h = (height * m.scale + bar) * stage.scale;
740
+ const window = { x: x + w * (1 - scale) / 2, y: y + h * (1 - scale) / 2, w: w * scale, h: h * scale }, top = bar * stage.scale * scale;
741
+ return {
742
+ page: pages.get(tab), pageRect: { x: window.x, y: window.y + top, w: window.w, h: window.h - top }, window, radius: stage.radius * m.scale * scale, opacity, effects,
743
+ chrome: chrome && { texture: chromeFor(width, url), rect: [window.x, window.y, window.w, top] },
744
+ };
745
+ };
746
+ /**
747
+ * The App windows of a Take of Apps (desktop.js) showing at Source time `source`, as the compositor
748
+ * draws them: each a window of its own over the Desktop's page, clipped to its frame and corners, with
749
+ * the window effects around those over no other (drawnWindows), so the Background shows between them. The chrome, if any, sits over the
750
+ * first; its spotlights are drawn once, with the last.
751
+ */
752
+ const desktopWindows = (desktop, source) => {
753
+ const drawn = drawnWindows(windowsAt(windows, source), viewport, stage.page);
754
+ return drawn.map(({ window, radius, effects }, i) => ({ ...desktop, window, radius, effects, chrome: i === 0 ? desktop.chrome : null, spotlit: i === drawn.length - 1 }));
755
+ };
756
+ /**
757
+ * A window with the masks on its Tab (`shown`, maskTrack's) in stage pixels: blurs and covers hidden
758
+ * with its page, a blur at the mip level of its strength in the Tab's Source, and its spotlights.
759
+ */
760
+ const masked = (w, tab, now) => {
761
+ const own = now.filter(mask => mask.tab === tab);
762
+ if (!own.length) return w;
763
+ const { width, height } = byId.get(tab).viewport, sx = w.pageRect.w / width, sy = w.pageRect.h / height, devicePerCss = sizes.get(tab).width / width;
764
+ const toStage = r => [w.pageRect.x + r.x * sx, w.pageRect.y + r.y * sy, r.width * sx, r.height * sy];
765
+ const hidden = mergedPast(own.filter(mask => mask.effect !== 'spotlight').flatMap(mask => mask.rects.map(rect => ({ rect, mask }))), MASK_BOXES);
766
+ const color = value => uniformOf(value)?.[1] ?? [0, 0, 0];
767
+ return {
768
+ ...w, masks: own.map(mask => mask.index),
769
+ hidden: hidden.length ? {
770
+ count: hidden.length, rects: new Float32Array(hidden.flatMap(({ rect }) => toStage(rect))),
771
+ styles: new Float32Array(hidden.flatMap(({ mask }) => [mask.radius * sx, mask.effect === 'cover' ? 1 : 0, Math.max(0, Math.log2(mask.blur * devicePerCss / 2) || 0), 0])),
772
+ colors: new Float32Array(hidden.flatMap(({ mask }) => [...(mask.effect === 'cover' ? color(mask.color) : [0, 0, 0]), 1])),
773
+ } : null,
774
+ spotlights: w.spotlit === false ? [] : own.filter(mask => mask.effect === 'spotlight').map(mask => ({
775
+ rects: mask.rects.map(toStage), corner: mask.radius * sx, feather: mask.feather * sx, color: color(mask.color), dim: mask.dim, opacity: mask.opacity,
776
+ })),
777
+ };
778
+ };
779
+ const cursorSprites = cursor ? await loadCursor(cursor) : {};
780
+ const cursorTextures = Object.fromEntries(Object.entries(cursorSprites).map(([shape, sprite]) => [shape, sprite.canvases(fitting(sprite.size.w, sprite.size.h)).map(canvas => compositor.sprite(canvas))]));
781
+ const drawn = new Set(Object.keys(cursorSprites)), track = cursor && cursorTrack({ pointer: placed.pointer, shapes, events: placed.events }, cursor);
429
782
  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;
783
+ const pressList = presses(placed.events);
784
+ const subtitleDrawing = burnsIn(subtitles) && cues.length ? await loadScreenDrawing(subtitles, 'Subtitles') : null;
785
+ const keys = keycapTrack(retimed(shortcuts, map), keycaps), keycapDrawing = keys.shows.length ? await loadScreenDrawing(keycaps, 'Keycaps') : null;
786
+ const badgeDrawing = fastForwardBadge && map.spans.length ? await loadScreenDrawing(fastForwardBadge, 'Fast-forward badges') : null;
787
+ const unit = Math.min(stage.width, stage.height) / 1080, spacing = 2 * unit; // on-screen pixels between the moments a frame averages
788
+ /** Where stage point `p` shows on screen, in output pixels, under the camera `view`. */
789
+ const onScreen = (p, view) => [(p[0] - view.x) * view.zoom + stage.width / 2, (p[1] - view.y) * view.zoom + stage.height / 2];
790
+ const apart = (a, b) => Math.hypot(a[0] - b[0], a[1] - b[1]); // the distance between two points
791
+ const corners = [[0, 0], [stage.width, 0], [0, stage.height], [stage.width, stage.height]];
792
+ /** How far, in output pixels, what the camera shows at view `to` has moved on screen since view `from`: the most at any corner of the Final. */
793
+ const cameraMoved = (from, to) => Math.max(...corners.map(c => apart(onScreen([(c[0] - stage.width / 2) / to.zoom + to.x, (c[1] - stage.height / 2) / to.zoom + to.y], from), c)));
794
+ /** The Cursor at Final time `time` under `view`, as the compositor places it, with its tip in stage pixels; null before the first pointer sample. */
795
+ const cursorAt = (time, view) => {
796
+ const now = track && track.at(map.sourceAt(time));
797
+ if (!now) return null;
798
+ // The Cursor scales around its hotspot, so a press keeps its tip on the target.
799
+ const shape = drawnShape(now.shape, drawn), sprite = cursorSprites[shape], k = now.scale, frames = cursorTextures[shape];
800
+ return { view, tip: at(now.x, now.y), texture: frames[Math.floor(time * frames.length) % frames.length], rect: [...at(now.x + sprite.offset.x * k, now.y + sprite.offset.y * k), sprite.size.w * k * stage.scale, sprite.size.h * k * stage.scale] };
801
+ };
802
+ /** The output pixels the Cursor covers at its moments, [x, y, w, h], inside the Final. */
803
+ const areaOf = cursors => {
804
+ const points = cursors.flatMap(({ view, rect: [x, y, w, h] }) => [onScreen([x, y], view), onScreen([x + w, y + h], view)]);
805
+ const left = Math.max(0, Math.min(...points.map(p => p[0]))), top = Math.max(0, Math.min(...points.map(p => p[1])));
806
+ return [left, top, Math.max(0, Math.min(stage.width, Math.max(...points.map(p => p[0]))) - left), Math.max(0, Math.min(stage.height, Math.max(...points.map(p => p[1]))) - top)];
807
+ };
808
+ const effectTextures = [];
809
+ let subtitleTexture = null, shown = -1, keycapTexture = null, keycapsShown = null, badgeTexture = null, badgeShown = null;
432
810
  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]);
811
+ stage, compositor, keycapShows: keys.shows,
812
+ /** The Tabs shown at Final time `t`, in drawing order. */
813
+ shown: t => shownTabs.at(t),
814
+ /** Fills a Tab's page with a frame of its Source. */
815
+ upload,
816
+ /**
817
+ * The camera's crop for every frame of the Final: its targets move to the window's CSS pixels and to
818
+ * Final time, it follows the pointer at each moment's Source time, and it cuts to wide where the
819
+ * window shows another tab.
820
+ */
821
+ crops() {
822
+ const targets = retimed(placed.targets, map, ['t', 'until']), scrolls = retimed(camera.scrolls ?? [], map, ['start', 'end']);
823
+ return cameraTrack({ targets, viewport, camera, duration: map.duration, fps: edit.output.fps, pointerAt: t => pointerAt(placed.pointer, map.sourceAt(t)), cuts: shownTabs.cuts, scrolls });
824
+ },
825
+ /**
826
+ * Draws Final time `t` with the camera showing `camera(time)`, a viewport rectangle in CSS pixels at
827
+ * any Final time; returns the index of the cue it shows, or -1, the keycap show, or null, the
828
+ * fast-forward badge, or null, the indexes of the masks it drew, and how many moments the camera
829
+ * and the Cursor averaged (`averaged`).
830
+ *
831
+ * Motion blur: over the frame's exposure (shutter.js) the window and what moves with it are composed
832
+ * under the camera at several moments, and the Cursor at several points of its path, each one moment
833
+ * per two 1080p pixels it moves on screen. The Background stays still, and the page shows one Source
834
+ * frame, so motion inside the page is not blurred.
835
+ */
836
+ draw(t, camera) {
837
+ const viewAt = time => cameraView(camera(time), stage, viewport), view = viewAt(t), source = map.sourceAt(t);
838
+ const span = compositor.blurs ? exposure(t, edit.output.fps, edit.output.shutter, shownTabs.cuts) : null, startView = span && viewAt(span.start);
839
+ const views = moments(t, span, span ? cameraMoved(startView, view) : 0, spacing).map(time => time === t ? view : viewAt(time));
840
+ // The window's effects are drawn once, under the tab it shows first. Each window carries the masks on its Tab.
841
+ const maskedNow = masks.at(t);
842
+ // The Cursor fades out as a spotlight fades in, so nothing but the light draws the eye.
843
+ const lit = Math.max(0, ...maskedNow.filter(mask => mask.effect === 'spotlight').map(mask => mask.opacity));
844
+ const cursorEnd = lit < 1 ? cursorAt(t, view) : null, cursorStart = span && cursorEnd && cursorAt(span.start, startView);
845
+ const cursors = moments(t, cursorStart ? span : null, cursorStart ? apart(onScreen(cursorStart.tip, startView), onScreen(cursorEnd.tip, view)) : 0, spacing)
846
+ .map(time => time === t ? cursorEnd : cursorAt(time, viewAt(time))).filter(Boolean).map(cursor => ({ ...cursor, opacity: 1 - lit }));
847
+ const shownNow = shownTabs.at(t).filter(({ tab }) => pages.has(tab)).flatMap((shownTab, i) => {
848
+ const w = windowOf(shownTab, source, i === 0 || shownTab.popup);
849
+ return (windows ? desktopWindows(w, source) : [w]).map(each => masked(each, shownTab.tab, maskedNow));
449
850
  });
851
+ const cue = subtitleDrawing ? cues.findIndex(c => t >= c.start && t < c.end) : -1;
852
+ if (cue >= 0 && cue !== shown) subtitleTexture = compositor.sprite(subtitleDrawing.canvas(stage.width, stage.height, { rows: cues[cue].rows }), subtitleTexture, false);
853
+ shown = cue;
854
+ // Each show is drawn once, and again when its count goes up; CueTake fades it and lifts it into place.
855
+ const keycap = keycapDrawing && keys.at(t), drawnAs = keycap && `${keycap.index}×${keycap.count}`;
856
+ if (keycap && drawnAs !== keycapsShown) keycapTexture = compositor.sprite(keycapDrawing.canvas(stage.width, stage.height, { keys: keycap.keys, count: keycap.count }), keycapTexture, false);
857
+ keycapsShown = drawnAs ?? keycapsShown;
858
+ // A badge is drawn once per rate; CueTake fades it in and out with its span.
859
+ const badge = badgeDrawing && badgeAt(map, t);
860
+ if (badge && badge.rate !== badgeShown) badgeTexture = compositor.sprite(badgeDrawing.canvas(stage.width, stage.height, { rate: badge.rate }), badgeTexture, false);
861
+ badgeShown = badge ? badge.rate : badgeShown;
862
+ // Each click effect is drawn once a frame, at its on-screen scale so thin strokes stay crisp, then placed under each view.
863
+ const sparks = (effect ? sparksAt(pressList, clickEffect, source) : []).map((press, i) => {
864
+ const scale = stage.scale * view.zoom, ctx = canvas2d(2 * effect.reach * scale, 2 * effect.reach * scale);
865
+ ctx.scale(scale, scale); ctx.translate(effect.reach, effect.reach);
866
+ effect.paint(ctx, press.progress);
867
+ effectTextures[i] = compositor.sprite(ctx.canvas, effectTextures[i], false);
868
+ return [effectTextures[i], [...at(press.x - effect.reach, press.y - effect.reach), 2 * effect.reach * stage.scale, 2 * effect.reach * stage.scale]];
869
+ });
870
+ compositor.frame(views, shownNow, draw => { for (const [texture, rect] of sparks) draw(texture, rect); }, cursors, cursors.length > 1 ? areaOf(cursors) : null, cue >= 0 || keycap || badge ? draw => {
871
+ if (cue >= 0) draw(subtitleTexture, [0, 0, stage.width, stage.height]);
872
+ if (keycap) draw(keycapTexture, [0, keycap.rise * unit, stage.width, stage.height], keycap.opacity);
873
+ if (badge) draw(badgeTexture, [0, 0, stage.width, stage.height], badge.opacity);
874
+ } : null);
875
+ return { cue, keycap, badge, masks: [...new Set(shownNow.flatMap(w => w.masks ?? []))], averaged: { camera: views.length, cursor: cursors.length } };
450
876
  },
451
877
  };
452
878
  }
@@ -459,20 +885,79 @@ const uploadStream = url => new WritableStream({
459
885
  },
460
886
  });
461
887
 
462
- window.cuetakeRender = async ({ sourceUrl, finalUrl, duration, viewport, pointer, events, edit }) => {
463
- const { camera } = edit, { quality, fps } = edit.output;
888
+ /**
889
+ * Each Tab's Source read in order, for sample and hold: `at(seconds)` gives the latest frame at or
890
+ * before that Source time of the Take, or the first before it. A Tab that records nothing is left out.
891
+ */
892
+ async function openSources(sources, tabs) {
893
+ const opened = new Map();
894
+ for (const { tab, url } of sources) {
895
+ const track = await new MB.Input({ formats: MB.ALL_FORMATS, source: new MB.UrlSource(url) }).getPrimaryVideoTrack();
896
+ const reader = frameReader(track, await track.getDecoderConfig());
897
+ const current = await reader.next();
898
+ if (!current) { reader.close(); continue; }
899
+ const start = tabs.find(t => t.id === tab)?.start ?? 0, state = { current, next: await reader.next(), origin: current.timestamp };
900
+ opened.set(tab, {
901
+ reader, size: { width: track.codedWidth, height: track.codedHeight }, first: current,
902
+ async at(seconds) {
903
+ const due = state.origin + Math.round((seconds - start) * 1e6);
904
+ while (state.next && state.next.timestamp <= due) {
905
+ if (state.current !== current) state.current.close();
906
+ state.current = state.next; state.next = await reader.next();
907
+ }
908
+ return state.current;
909
+ },
910
+ close() { if (state.current !== current) state.current.close(); state.next?.close(); current.close(); reader.close(); },
911
+ });
912
+ }
913
+ if (!opened.has(tabs[0].id)) throw new Error('Source has no video frames');
914
+ return opened;
915
+ }
916
+
917
+ window.cuetakeRender = async ({ sources: sourceUrls, finalUrl, duration, viewport, pointer, shapes, events, tabs, elements, windows, edit, narration }) => {
918
+ const { quality, fps } = edit.output;
464
919
  const { width, height } = outputSize(edit);
465
920
  const started = performance.now();
466
- const input = new MB.Input({ formats: MB.ALL_FORMATS, source: new MB.UrlSource(sourceUrl) });
467
- const track = await input.getPrimaryVideoTrack();
468
- const reader = frameReader(track, await track.getDecoderConfig());
469
- const frameCount = Math.round(duration * fps);
921
+ const sources = await openSources(sourceUrls, tabs);
922
+ const map = timeMap(edit.fastForward, duration);
923
+ const frameCount = Math.round(map.duration * fps), seconds = frameCount / fps;
924
+ const voice = await prepareNarration(narration, edit.subtitles, seconds, map);
470
925
  const output = new MB.Output({ format: new MB.Mp4OutputFormat({ fastStart: 'reserve' }), target: new MB.StreamTarget(uploadStream(finalUrl), { chunked: true }) });
471
926
  const packets = new MB.EncodedVideoPacketSource('avc');
472
927
  output.addVideoTrack(packets, { frameRate: fps, maximumPacketCount: frameCount });
928
+ let failure = null, muxed = Promise.resolve();
929
+ // The mix is fed a second ahead of the video.
930
+ let audio = null;
931
+ if (voice) {
932
+ const { codec, config } = await audioConfig(), source = new MB.EncodedAudioPacketSource(codec);
933
+ // Mediabunny's bound: a packet per 10 ms at most, plus a third for safety.
934
+ output.addAudioTrack(source, { maximumPacketCount: Math.ceil(seconds * 100 * 4 / 3) + 16 });
935
+ // Both in samples: the encoder's delay, and the mix, as long as the video.
936
+ const delay = await encoderDelay(config), mix = await mixLines(voice, narration.volume, seconds);
937
+ const encoder = new AudioEncoder({
938
+ output(chunk, meta) {
939
+ // Each packet is stamped by the input it encodes: the priming falls before 0, which the MP4's
940
+ // edit list then skips, and packets that start after the video are left out.
941
+ const start = samplesIn(chunk.timestamp) - delay;
942
+ if (start >= mix.length) return;
943
+ const packet = MB.EncodedPacket.fromEncodedChunk(chunk).clone({ timestamp: start / SAMPLE_RATE, duration: samplesIn(chunk.duration) / SAMPLE_RATE });
944
+ muxed = muxed.then(() => source.add(packet, meta)).catch(error => { failure ??= error; });
945
+ },
946
+ error(error) { failure ??= error; },
947
+ });
948
+ encoder.configure(config);
949
+ audio = { codec, delay, encoder, mix, fed: 0 };
950
+ }
951
+ const feedAudio = async until => {
952
+ const end = Math.min(audio.mix.length, Math.round(until * SAMPLE_RATE));
953
+ if (end <= audio.fed) return;
954
+ const data = new AudioData({ format: 'f32-planar', sampleRate: SAMPLE_RATE, numberOfFrames: end - audio.fed, numberOfChannels: 1, timestamp: Math.round(audio.fed * 1e6 / SAMPLE_RATE), data: audio.mix.getChannelData(0).slice(audio.fed, end) });
955
+ audio.fed = end;
956
+ audio.encoder.encode(data); data.close();
957
+ while (audio.encoder.encodeQueueSize > 2) await new Promise(resolve => audio.encoder.addEventListener('dequeue', resolve, { once: true }));
958
+ };
473
959
  await output.start();
474
960
  const { config, quantizer } = await encoderConfig(width, height, fps, quality);
475
- let failure = null, muxed = Promise.resolve();
476
961
  const encoder = new VideoEncoder({
477
962
  output(chunk, meta) {
478
963
  // Chromium tags the stream sRGB; the pixels are BT.709, so label them as such.
@@ -485,41 +970,86 @@ window.cuetakeRender = async ({ sourceUrl, finalUrl, duration, viewport, pointer
485
970
  });
486
971
  encoder.configure(config);
487
972
 
488
- let current = await reader.next(), next = await reader.next(), uploaded = null;
489
- if (!current) throw new Error('Source has no video frames');
490
- const scene = await createScene(edit, viewport, { pointer, events }, current, track.codedWidth, track.codedHeight), { compositor } = scene;
491
- const cameraPath = cameraTrack({ targets: camera.targets, viewport, camera, duration, fps, pointerAt: t => pointerAt(pointer, t) });
492
- const origin = current.timestamp;
973
+ const cues = voice?.cues ?? [], shownFrames = cues.map(() => null), keycapFrames = [], badgeFrames = [], maskFrames = [];
974
+ const sizes = new Map([...sources].map(([tab, source]) => [tab, source.size]));
975
+ const recorded = tabs.filter(tab => sources.has(tab.id)), uploaded = new Map();
976
+ const scene = await createScene(edit, viewport, { pointer, shapes, events, tabs: recorded, elements, windows }, sizes, sources.get(recorded[0].id).first, cues, map), { compositor } = scene;
977
+ const crops = scene.crops(), camera = time => cropAt(crops, fps, time), blurred = { camera: 0, cursor: 0 };
493
978
  try {
494
979
  for (let i = 0; i < frameCount; i++) {
495
980
  if (failure) throw failure;
496
- // Sample and hold: show the latest Source frame at or before this output time (VFR → CFR).
497
- const due = origin + Math.round(i * 1e6 / fps);
498
- while (next && next.timestamp <= due) { current.close(); current = next; next = await reader.next(); }
499
- if (uploaded !== current) { compositor.upload(current); uploaded = current; }
500
- scene.draw(i / fps, cameraPath[i]);
981
+ // Sample and hold: each Tab shown shows the latest frame of its Source at or before this moment's Source time (VFR → CFR).
982
+ for (const { tab } of scene.shown(i / fps)) {
983
+ const frame = await sources.get(tab)?.at(map.sourceAt(i / fps));
984
+ if (frame && uploaded.get(tab) !== frame) { scene.upload(tab, frame); uploaded.set(tab, frame); }
985
+ }
986
+ if (audio && i % fps === 0) await feedAudio(i / fps + 1);
987
+ const { cue, keycap, badge, masks, averaged } = scene.draw(i / fps, camera);
988
+ for (const index of masks) maskFrames[index] = [maskFrames[index]?.[0] ?? i, i];
989
+ if (averaged.camera > 1) blurred.camera++;
990
+ if (averaged.cursor > 1) blurred.cursor++;
991
+ if (cue >= 0) shownFrames[cue] = [shownFrames[cue]?.[0] ?? i, i];
992
+ if (keycap) keycapFrames[keycap.index] = [keycapFrames[keycap.index]?.[0] ?? i, i];
993
+ if (badge) badgeFrames[badge.index] = [badgeFrames[badge.index]?.[0] ?? i, i];
501
994
  const videoFrame = new VideoFrame(compositor.canvas, { timestamp: Math.round(i * 1e6 / fps), duration: Math.round(1e6 / fps) });
502
995
  encoder.encode(videoFrame, { keyFrame: i % (fps * 2) === 0, ...(quantizer ? { avc: { quantizer } } : {}) });
503
996
  videoFrame.close();
504
997
  while (encoder.encodeQueueSize > 4) await new Promise(resolve => encoder.addEventListener('dequeue', resolve, { once: true }));
505
998
  }
506
999
  await encoder.flush();
1000
+ if (failure) throw failure;
1001
+ if (audio) { await feedAudio(Infinity); await audio.encoder.flush(); }
507
1002
  await muxed;
508
1003
  if (failure) throw failure;
509
1004
  await output.finalize();
510
1005
  } finally {
511
- current?.close(); next?.close(); reader.close();
1006
+ for (const source of sources.values()) source.close();
512
1007
  if (encoder.state !== 'closed') encoder.close();
1008
+ if (audio && audio.encoder.state !== 'closed') audio.encoder.close();
513
1009
  }
514
1010
  return {
515
- width, height, frames: frameCount, sourceFrames: reader.stats().decoded, codec: config.codec,
1011
+ width, height, frames: frameCount, sourceFrames: [...sources.values()].reduce((sum, source) => sum + source.reader.stats().decoded, 0), codec: config.codec,
516
1012
  rateControl: quantizer ? `quantizer ${quantizer}` : `variable ${config.bitrate} bps`, gpu: compositor.gpu,
1013
+ // How many frames blurred the camera's and the Cursor's motion; a GPU without float render targets blurs none.
1014
+ motionBlur: { shutter: compositor.blurs ? shutterOf(edit.output.shutter) : 0, ...(!compositor.blurs && shutterOf(edit.output.shutter) > 0 && { note: 'This GPU cannot render to float textures, so the Final has no motion blur' }), frames: blurred },
517
1015
  seconds: +((performance.now() - started) / 1000).toFixed(2),
1016
+ // Each keycap show with the first and last output frame it was drawn on.
1017
+ // Each fast-forward in Final seconds, with the first and last frame its badge was drawn on (null without a badge).
1018
+ ...(map.spans.length && { fastForwards: map.spans.map((span, i) => ({ ...span, frames: badgeFrames[i] ?? null })) }),
1019
+ // Each mask with its span in Final seconds and the first and last frame it was drawn on (null when its element never showed).
1020
+ ...(edit.masks?.length && { masks: edit.masks.map(({ effect, element, box, start = 0, end }, i) => ({ effect, ...(element !== undefined ? { element } : { box }), start: map.outputAt(start), end: end === undefined ? seconds : map.outputAt(end), frames: maskFrames[i] ?? null })) }),
1021
+ ...(scene.keycapShows.length && { keycaps: scene.keycapShows.map((show, i) => ({ t: show.t, keys: show.keys, presses: show.presses.length, frames: keycapFrames[i] ?? null })) }),
1022
+ ...(voice && {
1023
+ // `encoderDelay`: the samples the encoder delays its input by (AAC's priming), which the MP4's edit list skips.
1024
+ audio: { codec: audio.codec, sampleRate: SAMPLE_RATE, channels: 1, bitrate: AUDIO_BITRATE, encoderDelay: audio.delay },
1025
+ lines: voice.placed.map(({ id, start, duration }) => ({ id, start, duration })),
1026
+ // Each cue with the first and last output frame it was drawn on (null when Subtitles are not burned in).
1027
+ subtitles: cues.map((cue, i) => ({ ...cue, frames: shownFrames[i] })),
1028
+ }),
518
1029
  };
519
1030
  };
520
1031
 
521
- /** Reads a Final's container metadata and decodes every frame. */
522
- window.cuetakeInspect = async url => {
1032
+ /** Decodes every packet of an audio track; returns how many packets and how many decoded chunks it saw. */
1033
+ async function decodeAudioTrack(track) {
1034
+ let decoded = 0, packets = 0, failure = null;
1035
+ const decoder = new AudioDecoder({ output: data => { decoded++; data.close(); }, error: error => { failure = error; } });
1036
+ decoder.configure(await track.getDecoderConfig());
1037
+ try {
1038
+ for await (const packet of new MB.EncodedPacketSink(track).packets()) {
1039
+ decoder.decode(packet.toEncodedAudioChunk()); packets++;
1040
+ while (decoder.decodeQueueSize > 16) await new Promise(resolve => decoder.addEventListener('dequeue', resolve, { once: true }));
1041
+ }
1042
+ await decoder.flush();
1043
+ } finally { if (decoder.state !== 'closed') decoder.close(); }
1044
+ if (failure) throw failure;
1045
+ return { packets, decoded };
1046
+ }
1047
+
1048
+ /**
1049
+ * Reads a Final's container metadata and decodes every frame and audio packet. `lines` ([{ id, url,
1050
+ * audio }]) are decoded too, giving each Line's duration or the reason it cannot be read.
1051
+ */
1052
+ window.cuetakeInspect = async (url, lines = []) => {
523
1053
  const input = new MB.Input({ formats: MB.ALL_FORMATS, source: new MB.UrlSource(url) });
524
1054
  const track = await input.getPrimaryVideoTrack();
525
1055
  const stats = await track.computePacketStats();
@@ -527,39 +1057,58 @@ window.cuetakeInspect = async url => {
527
1057
  let frames = 0;
528
1058
  try { for (let frame; (frame = await reader.next());) { frames++; frame.close(); } }
529
1059
  finally { reader.close(); }
1060
+ const audioTrack = await input.getPrimaryAudioTrack();
1061
+ let audio = null;
1062
+ if (audioTrack) {
1063
+ audio = { codec: await audioTrack.getCodecParameterString(), sampleRate: audioTrack.sampleRate, channels: audioTrack.numberOfChannels, duration: await audioTrack.computeDuration() };
1064
+ try { audio = { ...audio, ...await decodeAudioTrack(audioTrack) }; } catch (error) { audio.error = error.message; }
1065
+ }
1066
+ const measured = await Promise.all(lines.map(line => decodeLines([line]).then(([buffer]) => ({ id: line.id, duration: buffer.duration }), error => ({ id: line.id, error: error.message }))));
530
1067
  return {
531
1068
  codec: await track.getCodecParameterString(), width: track.displayWidth, height: track.displayHeight,
532
- duration: await input.computeDuration(), fps: +stats.averagePacketRate.toFixed(3), packets: stats.packetCount, decodedFrames: frames,
1069
+ duration: await track.computeDuration(), fps: +stats.averagePacketRate.toFixed(3), packets: stats.packetCount, decodedFrames: frames,
1070
+ audio, lines: measured,
533
1071
  };
534
1072
  };
535
1073
 
1074
+ /** Each Line's audio duration in seconds, for the Director to hold each Line while it is spoken. */
1075
+ window.cuetakeMeasure = async lines => {
1076
+ const buffers = await decodeLines(lines);
1077
+ return Object.fromEntries(lines.map((line, i) => [line.id, buffers[i].duration]));
1078
+ };
1079
+
536
1080
  /**
537
- * A Preview as a base64 PNG: each tile's Edit composed by the same scene as Render, over the Source at
1081
+ * A Preview as a base64 PNG: each tile's Edit composed by the same scene as Render, over the Sources at
538
1082
  * `at` seconds with the Final's camera, or (`at` null) over the last moment with the camera wide.
539
1083
  */
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();
1084
+ window.cuetakePreview = async ({ sources: sourceUrls, duration, viewport, pointer, shapes, events, tabs, elements, windows, tiles, at, narration }) => {
1085
+ const map = timeMap(tiles[0]?.edit.fastForward, duration), t = at ?? map.duration, source = map.sourceAt(t);
1086
+ // Each Tab's first frame, and its frame at `t`, the latest at or before it or else its first.
1087
+ const frames = new Map(), samples = [];
1088
+ for (const { tab, url } of sourceUrls) {
1089
+ const track = await new MB.Input({ formats: MB.ALL_FORMATS, source: new MB.UrlSource(url) }).getPrimaryVideoTrack();
1090
+ const sink = new MB.VideoSampleSink(track), origin = await track.getFirstTimestamp(), start = tabs.find(other => other.id === tab)?.start ?? 0;
1091
+ const first = await sink.getSample(origin);
1092
+ if (!first) continue;
1093
+ const latest = await sink.getSample(origin + Math.max(0, source - start)) ?? first;
1094
+ samples.push(first, latest);
1095
+ frames.set(tab, { size: { width: track.codedWidth, height: track.codedHeight }, first: first.toVideoFrame(), now: latest.toVideoFrame() });
1096
+ }
548
1097
  try {
1098
+ if (!frames.has(tabs[0].id)) throw new Error('Source has no video frames');
1099
+ const recorded = tabs.filter(tab => frames.has(tab.id)), sizes = new Map([...frames].map(([tab, { size }]) => [tab, size]));
549
1100
  const sheet = previewSheet(tiles.map(({ edit }) => outputSize(edit)));
550
1101
  const ctx = new OffscreenCanvas(sheet.width, sheet.height).getContext('2d');
551
1102
  ctx.fillStyle = '#111114'; ctx.fillRect(0, 0, sheet.width, sheet.height);
552
1103
  ctx.imageSmoothingQuality = 'high';
553
1104
  ctx.font = '600 22px system-ui, -apple-system, sans-serif'; ctx.textBaseline = 'middle'; ctx.fillStyle = '#e5e7eb';
554
1105
  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);
1106
+ const voice = await prepareNarration(narration, edit.subtitles, Math.round(map.duration * edit.output.fps) / edit.output.fps, map);
1107
+ const scene = await createScene(edit, viewport, { pointer, shapes, events, tabs: recorded, elements, windows }, sizes, frames.get(recorded[0].id).first, voice?.cues ?? [], map);
1108
+ // At `at` the camera moves as in the Final, blurred the same way; otherwise it is wide and still.
1109
+ const wide = { x: 0, y: 0, w: viewport.width, h: viewport.height }, path = at === null ? [] : scene.crops();
1110
+ for (const { tab } of scene.shown(t)) scene.upload(tab, frames.get(tab).now);
1111
+ scene.draw(t, path.length ? time => cropAt(path, edit.output.fps, time) : () => wide);
563
1112
  // Copy before yielding: the WebGL canvas does not keep its drawing buffer.
564
1113
  const tile = sheet.tiles[i];
565
1114
  ctx.drawImage(scene.compositor.canvas, tile.x, tile.y, tile.w, tile.h);
@@ -567,7 +1116,10 @@ window.cuetakePreview = async ({ sourceUrl, duration, viewport, pointer, events,
567
1116
  scene.compositor.dispose();
568
1117
  }
569
1118
  return await pngBase64(ctx.canvas);
570
- } finally { firstFrame.close(); frame.close(); firstSample.close(); sample.close(); }
1119
+ } finally {
1120
+ for (const { first, now } of frames.values()) { first.close(); now.close(); }
1121
+ for (const sample of samples) sample.close();
1122
+ }
571
1123
  };
572
1124
 
573
1125
  async function pngBase64(canvas) {