cuetake 0.4.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,12 +3,22 @@
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, and outside the camera the Subtitles and keycaps. Everything but the page is agent-written
8
- * 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).
9
13
  *
10
- * 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;
11
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.
12
22
  */
13
23
  import * as MB from '/mediabunny.js';
14
24
  import { cameraTrack } from '/camera.js';
@@ -16,6 +26,11 @@ import { cursorTrack, drawnShape, pointerAt, presses, sparksAt } from '/cursor.j
16
26
  import { layout, outputSize, cameraView, previewSheet, brandColor } from '/stage.js';
17
27
  import { burnsIn, cuesFor, lineProblems } from '/narration.js';
18
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';
19
34
 
20
35
  const VERTEX = `#version 300 es
21
36
  in vec2 p; void main() { gl_Position = vec4(p, 0, 1); }`;
@@ -31,6 +46,7 @@ uniform vec4 uWindow; // the window (chrome + page) in output pixels: l
31
46
  uniform float uRadius; // the window's corner radius in output pixels
32
47
  uniform float uZoom; // the camera zoom; 1 for Background layers
33
48
  out vec4 color; // premultiplied RGBA
49
+ #define main cuetakeMain
34
50
  vec2 pixel() { return vec2(gl_FragCoord.x, uResolution.y - gl_FragCoord.y); }
35
51
  vec4 previous(vec2 px) { return texture(uPrevious, vec2(px.x, uResolution.y - px.y) / uResolution); }
36
52
  float windowDistance(vec2 px) {
@@ -38,31 +54,103 @@ float windowDistance(vec2 px) {
38
54
  return length(max(q, 0.0)) + min(max(q.x, q.y), 0.0) - uRadius;
39
55
  }
40
56
  `;
41
- 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; }`;
42
63
  // An image layer is drawn over the layers below it.
43
64
  const IMAGE_LAYER = `uniform sampler2D image;
44
65
  void main() { vec4 top = texture(image, pixel() / uResolution); color = top + previous(pixel()) * (1.0 - top.a); }`;
45
66
  const BLIT = `#version 300 es
46
67
  precision highp float;
47
- uniform sampler2D uImage; uniform vec2 uRes; out vec4 color;
48
- void main() { color = texture(uImage, gl_FragCoord.xy / uRes); }`;
49
- // 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.
50
82
  const PAGE = `#version 300 es
51
83
  precision highp float;
52
- 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;
53
85
  uniform sampler2D uSource;
86
+ uniform int uHidden; uniform vec4 uHideRect[${MASK_BOXES}]; uniform vec4 uHideStyle[${MASK_BOXES}]; uniform vec4 uHideColor[${MASK_BOXES}];
54
87
  out vec4 color;
55
- float roundedBox(vec2 p, vec4 rect, float r) {
56
- vec2 q = abs(p - rect.xy - rect.zw * 0.5) - (rect.zw * 0.5 - r);
57
- 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;
58
98
  }
59
99
  void main() {
60
100
  vec2 pixel = vec2(gl_FragCoord.x, uRes.y - gl_FragCoord.y);
61
101
  vec2 stage = (pixel - uRes * 0.5) / uCam.z + uCam.xy;
62
102
  float inside = clamp(0.5 - roundedBox(stage, uWindow, uRadius) * uCam.z, 0.0, 1.0);
63
103
  if (inside <= 0.0 || stage.y < uPage.y) discard;
64
- 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;
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);
65
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
+ }
66
154
  // Sprites (chrome, cursor, click effects) are premultiplied textures placed by a stage rectangle under the camera.
67
155
  const SPRITE_VERTEX = `#version 300 es
68
156
  in vec2 p;
@@ -125,8 +213,8 @@ const canvas2d = (width, height) => {
125
213
  return canvas.getContext('2d');
126
214
  };
127
215
 
128
- /** The compositor for one stage: the Background drawn once, then per frame effects, page and sprites. */
129
- 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) {
130
218
  const { width, height } = stage, unit = Math.min(width, height) / 1080;
131
219
  const canvas = new OffscreenCanvas(width, height);
132
220
  const gl = canvas.getContext('webgl2', { alpha: false, antialias: false, depth: false });
@@ -169,13 +257,7 @@ function createCompositor(stage, sourceWidth, sourceHeight, brand) {
169
257
  gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
170
258
  gl.viewport(0, 0, width, height);
171
259
 
172
- // Mipmaps keep zoomed-out text from aliasing when the 2× Source is minified.
173
- const pageTexture = texture();
174
- gl.texStorage2D(gl.TEXTURE_2D, Math.floor(Math.log2(Math.max(sourceWidth, sourceHeight))) + 1, gl.RGBA8, sourceWidth, sourceHeight);
175
- const pageProgram = program(VERTEX, PAGE);
176
- gl.uniform4f(pageProgram.uniform('uPage'), stage.page.x, stage.page.y, stage.page.w, stage.page.h);
177
- gl.uniform4f(pageProgram.uniform('uWindow'), stage.window.x, stage.window.y, stage.window.w, stage.window.h);
178
- gl.uniform1f(pageProgram.uniform('uRadius'), stage.radius);
260
+ const pageProgram = program(VERTEX, PAGE), spotlightProgram = program(VERTEX, SPOTLIGHT);
179
261
  const blitProgram = program(VERTEX, BLIT);
180
262
  const spriteProgram = program(SPRITE_VERTEX, SPRITE_FRAGMENT), spriteRect = spriteProgram.uniform('uRect'), spriteAlpha = spriteProgram.uniform('uAlpha');
181
263
 
@@ -187,8 +269,8 @@ function createCompositor(stage, sourceWidth, sourceHeight, brand) {
187
269
  ...params.filter(([name]) => !HEADER_UNIFORMS.has(name)).map(([name, [type]]) => `uniform ${type} ${name};`),
188
270
  ...images.flatMap(([name]) => [`uniform sampler2D ${name};`, `uniform vec2 ${name}Size;`]),
189
271
  ].join('\n');
190
- const p = program(VERTEX, `${SHADER_HEADER}${declarations}\n#line 1\n${source}`, item);
191
- 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);
192
274
  gl.uniform1i(p.uniform('uPrevious'), 0); gl.uniform1i(p.uniform('uPage'), 1);
193
275
  for (const [name, [type, values]] of params) gl[`uniform${type === 'float' ? 1 : type.at(-1)}fv`](p.uniform(name), values);
194
276
  const textures = images.map(([name, image], i) => {
@@ -203,32 +285,71 @@ function createCompositor(stage, sourceWidth, sourceHeight, brand) {
203
285
  return response.text();
204
286
  };
205
287
  /** Draws one program over the full screen with uPrevious and uPage bound; window uniforms in output pixels. */
206
- const run = (p, previous, windowRect, radius, zoom) => {
288
+ const run = (p, previous, page, windowRect, radius, zoom, opacity = 1) => {
207
289
  gl.useProgram(p.p);
208
- gl.uniform4f(p.uniform('uWindow'), ...windowRect); gl.uniform1f(p.uniform('uRadius'), radius); gl.uniform1f(p.uniform('uZoom'), zoom);
209
- 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);
210
292
  p.textures?.forEach((t, i) => bind(2 + i, t));
211
293
  gl.bindVertexArray(fullScreen); gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
212
294
  gl.activeTexture(gl.TEXTURE0);
213
295
  };
214
296
  const checkGpu = what => { if (gl.isContextLost()) throw new Error(`${what} stopped the GPU; simplify the shader`); };
215
297
 
216
- 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; };
217
299
  const framebuffer = gl.createFramebuffer();
218
300
  let background = target(), effects = [];
219
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
+ };
220
330
  return {
221
331
  canvas,
332
+ /** Whether the GPU can average moments for motion blur. */
333
+ blurs,
222
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),
223
337
  /** Frees the GPU context; a Preview makes one compositor per tile. */
224
338
  dispose() { gl.getExtension('WEBGL_lose_context')?.loseContext(); },
225
- upload(frame) {
226
- 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);
227
348
  gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, gl.RGBA, gl.UNSIGNED_BYTE, frame);
228
349
  gl.generateMipmap(gl.TEXTURE_2D);
229
350
  },
230
- /** Draws the Background layers in order, each over the result so far, starting from black. */
231
- 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) {
232
353
  let other = target();
233
354
  gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
234
355
  gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, background, 0);
@@ -247,7 +368,7 @@ function createCompositor(stage, sourceWidth, sourceHeight, brand) {
247
368
  gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
248
369
  gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, other, 0);
249
370
  gl.disable(gl.BLEND);
250
- run(p, background, restWindow, stage.radius, 1);
371
+ run(p, background, page, restWindow, stage.radius, 1);
251
372
  [background, other] = [other, background];
252
373
  }
253
374
  gl.bindFramebuffer(gl.FRAMEBUFFER, null);
@@ -269,21 +390,49 @@ function createCompositor(stage, sourceWidth, sourceHeight, brand) {
269
390
  return t;
270
391
  },
271
392
  /**
272
- * One frame with the camera at stage point (x, y) and `zoom`; `draw(texture, rect, opacity)` in
273
- * `overlay` places sprites in stage pixels, and in `screen` in output pixels, outside the camera.
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`.
274
402
  */
275
- frame(x, y, zoom, overlay, screen) {
276
- gl.disable(gl.BLEND);
277
- gl.useProgram(blitProgram.p); bind(0, background); gl.bindVertexArray(fullScreen); gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
278
- gl.enable(gl.BLEND);
279
- const shown = [(stage.window.x - x) * zoom + width / 2, (stage.window.y - y) * zoom + height / 2, stage.window.w * zoom, stage.window.h * zoom];
280
- for (const p of effects) run(p, background, shown, stage.radius * zoom, zoom);
281
- gl.useProgram(pageProgram.p); gl.uniform3f(pageProgram.camera, x, y, zoom);
282
- bind(0, pageTexture); gl.bindVertexArray(fullScreen); gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
283
- gl.useProgram(spriteProgram.p); gl.uniform3f(spriteProgram.camera, x, y, zoom); gl.bindVertexArray(unitQuad);
403
+ frame(views, windows, overlay, cursors, cursorArea, screen) {
404
+ drawInto(null);
405
+ gl.disable(gl.BLEND); blit(background); gl.enable(gl.BLEND);
284
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); };
285
- overlay(place);
286
- if (screen) { gl.uniform3f(spriteProgram.camera, width / 2, height / 2, 1); screen(place); }
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); }
287
436
  if (effects.length) checkGpu('A window effect');
288
437
  },
289
438
  };
@@ -291,27 +440,28 @@ function createCompositor(stage, sourceWidth, sourceHeight, brand) {
291
440
 
292
441
  /**
293
442
  * The chrome bar: drawing code exporting `height` (CSS px) and `draw(ctx, { width, height, radius, url,
294
- * params, files })`, or an image as wide as the window. `paint(scale, radius)` rasterizes it, clipped to
295
- * 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.
296
446
  */
297
- async function loadChrome(item, width, url) {
447
+ async function loadChrome(item, windowWidth) {
298
448
  let height, paint;
299
449
  if (item.kind === 'image') {
300
450
  const image = await loadImage(item, item.url);
301
- height = item.height ?? image.naturalHeight * width / image.naturalWidth;
302
- 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);
303
453
  } else {
304
454
  const module = await loadModule(item), files = await loadFiles(item), params = paramsOf(item);
305
455
  height = item.height ?? (typeof module.height === 'function' ? module.height(params) : module.height) ?? 0;
306
- 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 });
307
457
  }
308
458
  return {
309
459
  height,
310
- canvas(scale, radius) {
460
+ canvas(width, scale, radius, url) {
311
461
  const ctx = canvas2d(width * scale, height * scale);
312
462
  ctx.scale(scale, scale);
313
463
  ctx.beginPath(); ctx.roundRect(0, 0, width, height + radius, [radius, radius, 0, 0]); ctx.clip();
314
- try { paint(ctx, radius); } catch (error) { throw fail(item, error); }
464
+ try { paint(ctx, width, radius, url); } catch (error) { throw fail(item, error); }
315
465
  return ctx.canvas;
316
466
  },
317
467
  };
@@ -389,6 +539,8 @@ async function loadScreenDrawing(item, name) {
389
539
  }
390
540
 
391
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);
392
544
  /** Each Line's audio decoded at 48 kHz; the error names a Line whose audio cannot be read. */
393
545
  async function decodeLines(lines) {
394
546
  const context = new OfflineAudioContext(1, 1, SAMPLE_RATE);
@@ -401,14 +553,15 @@ async function decodeLines(lines) {
401
553
  }
402
554
 
403
555
  /**
404
- * The Narration as Render plays it: each Line's decoded audio and measured duration, and its subtitle
405
- * cues. Lines that overlap or run past `seconds`, the Final's length, stop the Render.
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.
406
559
  */
407
- async function prepareNarration(narration, subtitles, seconds) {
560
+ async function prepareNarration(narration, subtitles, seconds, map) {
408
561
  if (!narration?.lines.length) return null;
409
562
  const buffers = await decodeLines(narration.lines);
410
- const placed = narration.lines.map((line, i) => ({ ...line, duration: buffers[i].duration }));
411
- const problems = lineProblems(placed, seconds);
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)];
412
565
  if (problems.length) throw new Error(`The Narration does not fit: ${problems.join('; ')}`);
413
566
  return { placed, buffers, cues: cuesFor(placed, narration.language, subtitles, seconds) };
414
567
  }
@@ -424,6 +577,62 @@ function mixLines({ placed, buffers }, volume, seconds) {
424
577
  return context.startRendering();
425
578
  }
426
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
+
427
636
  /** The page's brand color from the Source's first frame. */
428
637
  function brandOf(firstFrame) {
429
638
  const ctx = new OffscreenCanvas(96, 60).getContext('2d', { willReadFrequently: true });
@@ -439,13 +648,19 @@ export function avcCodec(width, height, fps) {
439
648
  return `avc1.6400${level.toString(16).toUpperCase().padStart(2, '0')}`;
440
649
  }
441
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
+
442
657
  /** Decodes a track with bounded look-ahead so memory stays flat on long Takes. */
443
658
  function frameReader(track, decoderConfig) {
444
659
  const ready = [], waiting = [];
445
660
  let failure = null, submitted = 0, decoded = 0, ended = false;
446
661
  const wake = () => waiting.splice(0).forEach(resolve => resolve());
447
662
  const decoder = new VideoDecoder({ output: frame => { decoded++; ready.push(frame); wake(); }, error: error => { failure = error; wake(); } });
448
- decoder.configure(decoderConfig);
663
+ decoder.configure({ ...decoderConfig, optimizeForLatency: true });
449
664
  const packets = new MB.EncodedPacketSink(track).packets();
450
665
  return {
451
666
  stats: () => ({ submitted, decoded }),
@@ -453,7 +668,7 @@ function frameReader(track, decoderConfig) {
453
668
  while (!ready.length) {
454
669
  if (failure) throw failure;
455
670
  if (ended) return null;
456
- 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; }
457
672
  const packet = await packets.next();
458
673
  if (packet.done) { await decoder.flush(); ended = true; continue; }
459
674
  decoder.decode(packet.value.toEncodedVideoChunk());
@@ -477,40 +692,162 @@ async function encoderConfig(width, height, fps, quality) {
477
692
  }
478
693
 
479
694
  /**
480
-
481
- /**
482
- * Everything Render draws for one Edit (as forRender in styles.js serves it). `firstFrame` is the
483
- * 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.
484
699
  */
485
- async function createScene(edit, viewport, { pointer, shapes, events }, firstFrame, sourceWidth, sourceHeight, cues = []) {
486
- const { camera, cursor, clickEffect, keycaps, shortcuts, frame, subtitles } = edit;
487
- 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;
488
707
  const stage = layout(edit, viewport, chrome?.height ?? 0);
489
- const compositor = createCompositor(stage, sourceWidth, sourceHeight, brandOf(firstFrame));
490
- compositor.upload(firstFrame);
491
- 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));
492
716
  await compositor.loadEffects(frame.effects ?? []);
493
- // 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.
494
720
  const at = (x, y) => [stage.page.x + x * stage.scale, stage.page.y + y * stage.scale];
495
721
  const sharpest = stage.scale * camera.maxZoom * 2;
496
- const chromeTexture = chrome ? compositor.sprite(chrome.canvas(sharpest, stage.radius / stage.scale)) : null;
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
+ };
497
779
  const cursorSprites = cursor ? await loadCursor(cursor) : {};
498
- const cursorTextures = Object.fromEntries(Object.entries(cursorSprites).map(([shape, sprite]) => [shape, sprite.canvases(sharpest).map(canvas => compositor.sprite(canvas))]));
499
- const drawn = new Set(Object.keys(cursorSprites)), track = cursor && cursorTrack({ pointer, shapes, events }, 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);
500
782
  const effect = clickEffect ? await loadClickEffect(clickEffect, cursor ? Object.fromEntries(Object.entries(cursor).filter(([key]) => !['ref', 'kind', 'url', 'files'].includes(key))) : {}) : null;
501
- const pressList = presses(events);
783
+ const pressList = presses(placed.events);
502
784
  const subtitleDrawing = burnsIn(subtitles) && cues.length ? await loadScreenDrawing(subtitles, 'Subtitles') : null;
503
- const keys = keycapTrack(shortcuts, keycaps), keycapDrawing = keys.shows.length ? await loadScreenDrawing(keycaps, 'Keycaps') : null;
504
- const unit = Math.min(stage.width, stage.height) / 1080;
505
- let effectTexture = null, subtitleTexture = null, shown = -1, keycapTexture = null, keycapsShown = 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;
506
810
  return {
507
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,
508
816
  /**
509
- * Draws output time `t` with the camera showing `crop`, a viewport rectangle in CSS pixels; returns
510
- * the index of the cue it shows, or -1, and the keycap show, or null.
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.
511
820
  */
512
- draw(t, crop) {
513
- const view = cameraView(crop, stage, viewport);
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));
850
+ });
514
851
  const cue = subtitleDrawing ? cues.findIndex(c => t >= c.start && t < c.end) : -1;
515
852
  if (cue >= 0 && cue !== shown) subtitleTexture = compositor.sprite(subtitleDrawing.canvas(stage.width, stage.height, { rows: cues[cue].rows }), subtitleTexture, false);
516
853
  shown = cue;
@@ -518,27 +855,24 @@ async function createScene(edit, viewport, { pointer, shapes, events }, firstFra
518
855
  const keycap = keycapDrawing && keys.at(t), drawnAs = keycap && `${keycap.index}×${keycap.count}`;
519
856
  if (keycap && drawnAs !== keycapsShown) keycapTexture = compositor.sprite(keycapDrawing.canvas(stage.width, stage.height, { keys: keycap.keys, count: keycap.count }), keycapTexture, false);
520
857
  keycapsShown = drawnAs ?? keycapsShown;
521
- compositor.frame(view.x, view.y, view.zoom, draw => {
522
- if (chromeTexture) draw(chromeTexture, [stage.window.x, stage.window.y, stage.window.w, stage.chrome]);
523
- for (const press of effect ? sparksAt(pressList, clickEffect, t) : []) {
524
- // Each click effect is drawn at its on-screen scale so thin strokes stay crisp.
525
- const scale = stage.scale * view.zoom, ctx = canvas2d(2 * effect.reach * scale, 2 * effect.reach * scale);
526
- ctx.scale(scale, scale); ctx.translate(effect.reach, effect.reach);
527
- effect.paint(ctx, press.progress);
528
- effectTexture = compositor.sprite(ctx.canvas, effectTexture, false);
529
- draw(effectTexture, [...at(press.x - effect.reach, press.y - effect.reach), 2 * effect.reach * stage.scale, 2 * effect.reach * stage.scale]);
530
- }
531
- // The Cursor scales around its hotspot, so a press keeps its tip on the target.
532
- const now = track && track.at(t);
533
- if (now) {
534
- const shape = drawnShape(now.shape, drawn), sprite = cursorSprites[shape], k = now.scale, frames = cursorTextures[shape];
535
- draw(frames[Math.floor(t * frames.length) % frames.length], [...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]);
536
- }
537
- }, cue >= 0 || keycap ? draw => {
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 => {
538
871
  if (cue >= 0) draw(subtitleTexture, [0, 0, stage.width, stage.height]);
539
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);
540
874
  } : null);
541
- return { cue, keycap };
875
+ return { cue, keycap, badge, masks: [...new Set(shownNow.flatMap(w => w.masks ?? []))], averaged: { camera: views.length, cursor: cursors.length } };
542
876
  },
543
877
  };
544
878
  }
@@ -551,39 +885,79 @@ const uploadStream = url => new WritableStream({
551
885
  },
552
886
  });
553
887
 
554
- window.cuetakeRender = async ({ sourceUrl, finalUrl, duration, viewport, pointer, shapes, events, edit, narration }) => {
555
- 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;
556
919
  const { width, height } = outputSize(edit);
557
920
  const started = performance.now();
558
- const input = new MB.Input({ formats: MB.ALL_FORMATS, source: new MB.UrlSource(sourceUrl) });
559
- const track = await input.getPrimaryVideoTrack();
560
- const reader = frameReader(track, await track.getDecoderConfig());
561
- const frameCount = Math.round(duration * fps), seconds = frameCount / fps;
562
- const voice = await prepareNarration(narration, edit.subtitles, seconds);
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);
563
925
  const output = new MB.Output({ format: new MB.Mp4OutputFormat({ fastStart: 'reserve' }), target: new MB.StreamTarget(uploadStream(finalUrl), { chunked: true }) });
564
926
  const packets = new MB.EncodedVideoPacketSource('avc');
565
927
  output.addVideoTrack(packets, { frameRate: fps, maximumPacketCount: frameCount });
566
- // AAC where the platform encodes it (macOS, Windows), else Opus; fed a second ahead of the video.
928
+ let failure = null, muxed = Promise.resolve();
929
+ // The mix is fed a second ahead of the video.
567
930
  let audio = null;
568
931
  if (voice) {
569
- const codec = await MB.getFirstEncodableAudioCodec(['aac', 'opus'], { numberOfChannels: 1, sampleRate: SAMPLE_RATE, bitrate: AUDIO_BITRATE });
570
- if (!codec) throw new Error('This browser encodes neither AAC nor Opus audio');
571
- const source = new MB.AudioBufferSource({ codec, bitrate: AUDIO_BITRATE });
932
+ const { codec, config } = await audioConfig(), source = new MB.EncodedAudioPacketSource(codec);
572
933
  // Mediabunny's bound: a packet per 10 ms at most, plus a third for safety.
573
934
  output.addAudioTrack(source, { maximumPacketCount: Math.ceil(seconds * 100 * 4 / 3) + 16 });
574
- audio = { codec, source, mix: await mixLines(voice, narration.volume, seconds), fed: 0 };
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 };
575
950
  }
576
951
  const feedAudio = async until => {
577
952
  const end = Math.min(audio.mix.length, Math.round(until * SAMPLE_RATE));
578
953
  if (end <= audio.fed) return;
579
- const chunk = new AudioBuffer({ length: end - audio.fed, numberOfChannels: 1, sampleRate: SAMPLE_RATE });
580
- chunk.copyToChannel(audio.mix.getChannelData(0).subarray(audio.fed, end), 0);
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) });
581
955
  audio.fed = end;
582
- await audio.source.add(chunk);
956
+ audio.encoder.encode(data); data.close();
957
+ while (audio.encoder.encodeQueueSize > 2) await new Promise(resolve => audio.encoder.addEventListener('dequeue', resolve, { once: true }));
583
958
  };
584
959
  await output.start();
585
960
  const { config, quantizer } = await encoderConfig(width, height, fps, quality);
586
- let failure = null, muxed = Promise.resolve();
587
961
  const encoder = new VideoEncoder({
588
962
  output(chunk, meta) {
589
963
  // Chromium tags the stream sRGB; the pixels are BT.709, so label them as such.
@@ -596,45 +970,58 @@ window.cuetakeRender = async ({ sourceUrl, finalUrl, duration, viewport, pointer
596
970
  });
597
971
  encoder.configure(config);
598
972
 
599
- let current = await reader.next(), next = await reader.next(), uploaded = null;
600
- if (!current) throw new Error('Source has no video frames');
601
- const cues = voice?.cues ?? [], shownFrames = cues.map(() => null), keycapFrames = [];
602
- const scene = await createScene(edit, viewport, { pointer, shapes, events }, current, track.codedWidth, track.codedHeight, cues), { compositor } = scene;
603
- const cameraPath = cameraTrack({ targets: camera.targets, viewport, camera, duration, fps, pointerAt: t => pointerAt(pointer, t) });
604
- 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 };
605
978
  try {
606
979
  for (let i = 0; i < frameCount; i++) {
607
980
  if (failure) throw failure;
608
- // Sample and hold: show the latest Source frame at or before this output time (VFR → CFR).
609
- const due = origin + Math.round(i * 1e6 / fps);
610
- while (next && next.timestamp <= due) { current.close(); current = next; next = await reader.next(); }
611
- if (uploaded !== current) { compositor.upload(current); uploaded = current; }
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
+ }
612
986
  if (audio && i % fps === 0) await feedAudio(i / fps + 1);
613
- const { cue, keycap } = scene.draw(i / fps, cameraPath[i]);
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++;
614
991
  if (cue >= 0) shownFrames[cue] = [shownFrames[cue]?.[0] ?? i, i];
615
992
  if (keycap) keycapFrames[keycap.index] = [keycapFrames[keycap.index]?.[0] ?? i, i];
993
+ if (badge) badgeFrames[badge.index] = [badgeFrames[badge.index]?.[0] ?? i, i];
616
994
  const videoFrame = new VideoFrame(compositor.canvas, { timestamp: Math.round(i * 1e6 / fps), duration: Math.round(1e6 / fps) });
617
995
  encoder.encode(videoFrame, { keyFrame: i % (fps * 2) === 0, ...(quantizer ? { avc: { quantizer } } : {}) });
618
996
  videoFrame.close();
619
997
  while (encoder.encodeQueueSize > 4) await new Promise(resolve => encoder.addEventListener('dequeue', resolve, { once: true }));
620
998
  }
621
999
  await encoder.flush();
1000
+ if (failure) throw failure;
1001
+ if (audio) { await feedAudio(Infinity); await audio.encoder.flush(); }
622
1002
  await muxed;
623
1003
  if (failure) throw failure;
624
- if (audio) await feedAudio(Infinity);
625
1004
  await output.finalize();
626
1005
  } finally {
627
- current?.close(); next?.close(); reader.close();
1006
+ for (const source of sources.values()) source.close();
628
1007
  if (encoder.state !== 'closed') encoder.close();
1008
+ if (audio && audio.encoder.state !== 'closed') audio.encoder.close();
629
1009
  }
630
1010
  return {
631
- 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,
632
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 },
633
1015
  seconds: +((performance.now() - started) / 1000).toFixed(2),
634
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 })) }),
635
1021
  ...(scene.keycapShows.length && { keycaps: scene.keycapShows.map((show, i) => ({ t: show.t, keys: show.keys, presses: show.presses.length, frames: keycapFrames[i] ?? null })) }),
636
1022
  ...(voice && {
637
- audio: { codec: audio.codec, sampleRate: SAMPLE_RATE, channels: 1, bitrate: AUDIO_BITRATE },
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 },
638
1025
  lines: voice.placed.map(({ id, start, duration }) => ({ id, start, duration })),
639
1026
  // Each cue with the first and last output frame it was drawn on (null when Subtitles are not burned in).
640
1027
  subtitles: cues.map((cue, i) => ({ ...cue, frames: shownFrames[i] })),
@@ -691,33 +1078,37 @@ window.cuetakeMeasure = async lines => {
691
1078
  };
692
1079
 
693
1080
  /**
694
- * 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
695
1082
  * `at` seconds with the Final's camera, or (`at` null) over the last moment with the camera wide.
696
1083
  */
697
- window.cuetakePreview = async ({ sourceUrl, duration, viewport, pointer, shapes, events, tiles, at, narration }) => {
698
- const input = new MB.Input({ formats: MB.ALL_FORMATS, source: new MB.UrlSource(sourceUrl) });
699
- const track = await input.getPrimaryVideoTrack();
700
- const sink = new MB.VideoSampleSink(track), origin = await track.getFirstTimestamp();
701
- const t = at ?? duration;
702
- const firstSample = await sink.getSample(origin), sample = await sink.getSample(origin + t);
703
- if (!firstSample || !sample) throw new Error('Source has no video frames');
704
- 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
+ }
705
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]));
706
1100
  const sheet = previewSheet(tiles.map(({ edit }) => outputSize(edit)));
707
1101
  const ctx = new OffscreenCanvas(sheet.width, sheet.height).getContext('2d');
708
1102
  ctx.fillStyle = '#111114'; ctx.fillRect(0, 0, sheet.width, sheet.height);
709
1103
  ctx.imageSmoothingQuality = 'high';
710
1104
  ctx.font = '600 22px system-ui, -apple-system, sans-serif'; ctx.textBaseline = 'middle'; ctx.fillStyle = '#e5e7eb';
711
1105
  for (const [i, { name, edit }] of tiles.entries()) {
712
- const voice = await prepareNarration(narration, edit.subtitles, Math.round(duration * edit.output.fps) / edit.output.fps);
713
- const scene = await createScene(edit, viewport, { pointer, shapes, events }, firstFrame, track.codedWidth, track.codedHeight, voice?.cues);
714
- let crop = { x: 0, y: 0, w: viewport.width, h: viewport.height };
715
- if (at !== null) {
716
- const { fps } = edit.output, path = cameraTrack({ targets: edit.camera.targets, viewport, camera: edit.camera, duration, fps, pointerAt: s => pointerAt(pointer, s) });
717
- crop = path[Math.min(Math.round(at * fps), path.length - 1)] ?? crop;
718
- }
719
- scene.compositor.upload(frame);
720
- 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);
721
1112
  // Copy before yielding: the WebGL canvas does not keep its drawing buffer.
722
1113
  const tile = sheet.tiles[i];
723
1114
  ctx.drawImage(scene.compositor.canvas, tile.x, tile.y, tile.w, tile.h);
@@ -725,7 +1116,10 @@ window.cuetakePreview = async ({ sourceUrl, duration, viewport, pointer, shapes,
725
1116
  scene.compositor.dispose();
726
1117
  }
727
1118
  return await pngBase64(ctx.canvas);
728
- } 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
+ }
729
1123
  };
730
1124
 
731
1125
  async function pngBase64(canvas) {