cuetake 0.3.0 → 0.4.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.
@@ -4,15 +4,18 @@
4
4
  *
5
5
  * Each output frame is the Background (drawn once, still in output pixels), the window effects (drawn
6
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).
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).
8
9
  *
9
10
  * Spaces: camera crops are CSS pixels of the viewport; the Source texture is sampled by UV only;
10
11
  * "stage" is the Final's pixels at camera zoom 1, laid out by stage.js.
11
12
  */
12
13
  import * as MB from '/mediabunny.js';
13
14
  import { cameraTrack } from '/camera.js';
14
- import { pointerAt, presses, sparksAt } from '/cursor.js';
15
+ import { cursorTrack, drawnShape, pointerAt, presses, sparksAt } from '/cursor.js';
15
16
  import { layout, outputSize, cameraView, previewSheet, brandColor } from '/stage.js';
17
+ import { burnsIn, cuesFor, lineProblems } from '/narration.js';
18
+ import { keycapTrack } from '/shortcuts.js';
16
19
 
17
20
  const VERTEX = `#version 300 es
18
21
  in vec2 p; void main() { gl_Position = vec4(p, 0, 1); }`;
@@ -72,13 +75,13 @@ void main() {
72
75
  }`;
73
76
  const SPRITE_FRAGMENT = `#version 300 es
74
77
  precision highp float;
75
- uniform sampler2D uSprite;
78
+ uniform sampler2D uSprite; uniform float uAlpha;
76
79
  in vec2 uv; out vec4 color;
77
- void main() { color = texture(uSprite, uv); }`;
80
+ void main() { color = texture(uSprite, uv) * uAlpha; }`;
78
81
 
79
82
  // Item keys CueTake reads itself; every other key is a parameter for the item's shader or drawing code.
80
83
  const OWN_KEYS = new Set(['shader', 'draw', 'image', 'files', 'ref', 'kind', 'url']);
81
- const SLOT_KEYS = new Set(['size', 'hotspot', 'duration', 'reach', 'height']);
84
+ const SLOT_KEYS = new Set(['size', 'hotspot', 'press', 'duration', 'singleKeys', 'reach', 'height', 'burn', 'maxChars', 'maxRows', 'minDuration']);
82
85
  const paramsOf = item => Object.fromEntries(Object.entries(item).filter(([key]) => !OWN_KEYS.has(key) && (item.kind === 'shader' || !SLOT_KEYS.has(key))));
83
86
  const fail = (item, error) => new Error(`${item.ref}: ${error?.message ?? error}`);
84
87
 
@@ -174,7 +177,7 @@ function createCompositor(stage, sourceWidth, sourceHeight, brand) {
174
177
  gl.uniform4f(pageProgram.uniform('uWindow'), stage.window.x, stage.window.y, stage.window.w, stage.window.h);
175
178
  gl.uniform1f(pageProgram.uniform('uRadius'), stage.radius);
176
179
  const blitProgram = program(VERTEX, BLIT);
177
- const spriteProgram = program(SPRITE_VERTEX, SPRITE_FRAGMENT), spriteRect = spriteProgram.uniform('uRect');
180
+ const spriteProgram = program(SPRITE_VERTEX, SPRITE_FRAGMENT), spriteRect = spriteProgram.uniform('uRect'), spriteAlpha = spriteProgram.uniform('uAlpha');
178
181
 
179
182
  /** An agent shader with its parameters declared and set, and its `files` bound from texture unit 2. */
180
183
  async function agentProgram(item, source) {
@@ -265,8 +268,11 @@ function createCompositor(stage, sourceWidth, sourceHeight, brand) {
265
268
  if (mipmaps) gl.generateMipmap(gl.TEXTURE_2D);
266
269
  return t;
267
270
  },
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) {
271
+ /**
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.
274
+ */
275
+ frame(x, y, zoom, overlay, screen) {
270
276
  gl.disable(gl.BLEND);
271
277
  gl.useProgram(blitProgram.p); bind(0, background); gl.bindVertexArray(fullScreen); gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
272
278
  gl.enable(gl.BLEND);
@@ -275,7 +281,9 @@ function createCompositor(stage, sourceWidth, sourceHeight, brand) {
275
281
  gl.useProgram(pageProgram.p); gl.uniform3f(pageProgram.camera, x, y, zoom);
276
282
  bind(0, pageTexture); gl.bindVertexArray(fullScreen); gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
277
283
  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); });
284
+ 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); }
279
287
  if (effects.length) checkGpu('A window effect');
280
288
  },
281
289
  };
@@ -310,33 +318,42 @@ async function loadChrome(item, width, url) {
310
318
  }
311
319
 
312
320
  /**
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.
321
+ * The cursor: drawing code exporting `shapes` (each shape's { width, height, hotspot: [x, y] } in the
322
+ * code's own units, `default` among them, with `frames` for one that loops each second) and
323
+ * `draw(ctx, { shape, phase, params, files })` in those units, or an image of the default shape whose
324
+ * `hotspot` the item names. The default shape is `size` CSS px wide and the others share its scale;
325
+ * each sprite has a margin of a quarter box around it for shadows.
316
326
  */
317
327
  async function loadCursor(item) {
318
- let box, paint;
328
+ let boxes, paint;
319
329
  if (item.kind === 'image') {
320
330
  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);
331
+ boxes = { default: { width: image.naturalWidth || 32, height: image.naturalHeight || 32, hotspot: item.hotspot ?? [0, 0] } };
332
+ paint = ctx => ctx.drawImage(image, 0, 0, boxes.default.width, boxes.default.height);
323
333
  } else {
324
334
  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 });
335
+ boxes = module.shapes;
336
+ if (!boxes?.default) throw fail(item, 'a cursor exports `shapes` with a `default` box');
337
+ paint = (ctx, shape, phase) => module.draw(ctx, { shape, phase, params, files });
327
338
  }
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
- };
339
+ const k = (item.size ?? 24) / boxes.default.width;
340
+ return Object.fromEntries(Object.entries(boxes).map(([shape, box]) => {
341
+ const margin = Math.max(box.width, box.height) / 4;
342
+ return [shape, {
343
+ /** Where the sprite's top-left sits relative to the pointer, and its size, in CSS px. */
344
+ offset: { x: -(box.hotspot[0] + margin) * k, y: -(box.hotspot[1] + margin) * k },
345
+ size: { w: (box.width + 2 * margin) * k, h: (box.height + 2 * margin) * k },
346
+ /** The shape's pictures through one second, or its only one. */
347
+ canvases(scale) {
348
+ return Array.from({ length: Math.max(1, Math.round(box.frames ?? 1)) }, (_, frame, frames = box.frames ?? 1) => {
349
+ const ctx = canvas2d((box.width + 2 * margin) * k * scale, (box.height + 2 * margin) * k * scale);
350
+ ctx.scale(k * scale, k * scale); ctx.translate(margin, margin);
351
+ try { paint(ctx, shape, frame / frames); } catch (error) { throw fail(item, error); }
352
+ return ctx.canvas;
353
+ });
354
+ },
355
+ }];
356
+ }));
340
357
  }
341
358
 
342
359
  /**
@@ -354,6 +371,59 @@ async function loadClickEffect(item, cursor) {
354
371
  return { reach, paint: (ctx, progress) => { try { module.draw(ctx, { progress, params, files, cursor }); } catch (error) { throw fail(item, error); } } };
355
372
  }
356
373
 
374
+ /**
375
+ * Drawing code over the whole Final in 1080p pixels, outside the camera, such as Subtitles and keycaps:
376
+ * `draw(ctx, { width, height, ...what, params, files })`. `canvas(width, height, what)` rasterizes it at output size.
377
+ */
378
+ async function loadScreenDrawing(item, name) {
379
+ if (item.kind !== 'draw') throw fail(item, `${name} are drawing code`);
380
+ const module = await loadModule(item), files = await loadFiles(item), params = paramsOf(item);
381
+ return {
382
+ canvas(width, height, what) {
383
+ const unit = Math.min(width, height) / 1080, ctx = canvas2d(width, height);
384
+ ctx.scale(unit, unit);
385
+ try { module.draw(ctx, { width: width / unit, height: height / unit, ...what, params, files }); } catch (error) { throw fail(item, error); }
386
+ return ctx.canvas;
387
+ },
388
+ };
389
+ }
390
+
391
+ const SAMPLE_RATE = 48000, AUDIO_BITRATE = 128000;
392
+ /** Each Line's audio decoded at 48 kHz; the error names a Line whose audio cannot be read. */
393
+ async function decodeLines(lines) {
394
+ const context = new OfflineAudioContext(1, 1, SAMPLE_RATE);
395
+ return Promise.all(lines.map(async line => {
396
+ const response = await fetch(line.url);
397
+ if (!response.ok) throw new Error(`Line '${line.id}': its audio ${line.audio} could not be read (${response.status})`);
398
+ try { return await context.decodeAudioData(await response.arrayBuffer()); }
399
+ 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`); }
400
+ }));
401
+ }
402
+
403
+ /**
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.
406
+ */
407
+ async function prepareNarration(narration, subtitles, seconds) {
408
+ if (!narration?.lines.length) return null;
409
+ 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);
412
+ if (problems.length) throw new Error(`The Narration does not fit: ${problems.join('; ')}`);
413
+ return { placed, buffers, cues: cuesFor(placed, narration.language, subtitles, seconds) };
414
+ }
415
+
416
+ /** The Lines mixed into one mono track `seconds` long, each at its start and volume. */
417
+ function mixLines({ placed, buffers }, volume, seconds) {
418
+ const context = new OfflineAudioContext(1, Math.max(1, Math.round(seconds * SAMPLE_RATE)), SAMPLE_RATE);
419
+ placed.forEach((line, i) => {
420
+ const source = new AudioBufferSourceNode(context, { buffer: buffers[i] });
421
+ source.connect(new GainNode(context, { gain: (volume ?? 1) * (line.volume ?? 1) })).connect(context.destination);
422
+ source.start(line.start);
423
+ });
424
+ return context.startRendering();
425
+ }
426
+
357
427
  /** The page's brand color from the Source's first frame. */
358
428
  function brandOf(firstFrame) {
359
429
  const ctx = new OffscreenCanvas(96, 60).getContext('2d', { willReadFrequently: true });
@@ -412,8 +482,8 @@ async function encoderConfig(width, height, fps, quality) {
412
482
  * Everything Render draws for one Edit (as forRender in styles.js serves it). `firstFrame` is the
413
483
  * Source's first frame: Background layers see it, and it picks the brand color.
414
484
  */
415
- async function createScene(edit, viewport, { pointer, events }, firstFrame, sourceWidth, sourceHeight) {
416
- const { camera, cursor, clickEffect, frame } = edit;
485
+ async function createScene(edit, viewport, { pointer, shapes, events }, firstFrame, sourceWidth, sourceHeight, cues = []) {
486
+ const { camera, cursor, clickEffect, keycaps, shortcuts, frame, subtitles } = edit;
417
487
  const chrome = frame.chrome ? await loadChrome(frame.chrome, viewport.width, frame.url ?? '') : null;
418
488
  const stage = layout(edit, viewport, chrome?.height ?? 0);
419
489
  const compositor = createCompositor(stage, sourceWidth, sourceHeight, brandOf(firstFrame));
@@ -424,16 +494,30 @@ async function createScene(edit, viewport, { pointer, events }, firstFrame, sour
424
494
  const at = (x, y) => [stage.page.x + x * stage.scale, stage.page.y + y * stage.scale];
425
495
  const sharpest = stage.scale * camera.maxZoom * 2;
426
496
  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));
497
+ 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);
429
500
  const effect = clickEffect ? await loadClickEffect(clickEffect, cursor ? Object.fromEntries(Object.entries(cursor).filter(([key]) => !['ref', 'kind', 'url', 'files'].includes(key))) : {}) : null;
430
501
  const pressList = presses(events);
431
- let effectTexture = null;
502
+ 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;
432
506
  return {
433
- stage, compositor,
434
- /** Draws output time `t` with the camera showing `crop`, a viewport rectangle in CSS pixels. */
507
+ stage, compositor, keycapShows: keys.shows,
508
+ /**
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.
511
+ */
435
512
  draw(t, crop) {
436
513
  const view = cameraView(crop, stage, viewport);
514
+ const cue = subtitleDrawing ? cues.findIndex(c => t >= c.start && t < c.end) : -1;
515
+ if (cue >= 0 && cue !== shown) subtitleTexture = compositor.sprite(subtitleDrawing.canvas(stage.width, stage.height, { rows: cues[cue].rows }), subtitleTexture, false);
516
+ shown = cue;
517
+ // Each show is drawn once, and again when its count goes up; CueTake fades it and lifts it into place.
518
+ const keycap = keycapDrawing && keys.at(t), drawnAs = keycap && `${keycap.index}×${keycap.count}`;
519
+ if (keycap && drawnAs !== keycapsShown) keycapTexture = compositor.sprite(keycapDrawing.canvas(stage.width, stage.height, { keys: keycap.keys, count: keycap.count }), keycapTexture, false);
520
+ keycapsShown = drawnAs ?? keycapsShown;
437
521
  compositor.frame(view.x, view.y, view.zoom, draw => {
438
522
  if (chromeTexture) draw(chromeTexture, [stage.window.x, stage.window.y, stage.window.w, stage.chrome]);
439
523
  for (const press of effect ? sparksAt(pressList, clickEffect, t) : []) {
@@ -444,9 +528,17 @@ async function createScene(edit, viewport, { pointer, events }, firstFrame, sour
444
528
  effectTexture = compositor.sprite(ctx.canvas, effectTexture, false);
445
529
  draw(effectTexture, [...at(press.x - effect.reach, press.y - effect.reach), 2 * effect.reach * stage.scale, 2 * effect.reach * stage.scale]);
446
530
  }
447
- const point = pointerSprite && pointerAt(pointer, t);
448
- if (point) draw(pointerTexture, [...at(point.x + pointerSprite.offset.x, point.y + pointerSprite.offset.y), pointerSprite.size.w * stage.scale, pointerSprite.size.h * stage.scale]);
449
- });
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 => {
538
+ if (cue >= 0) draw(subtitleTexture, [0, 0, stage.width, stage.height]);
539
+ if (keycap) draw(keycapTexture, [0, keycap.rise * unit, stage.width, stage.height], keycap.opacity);
540
+ } : null);
541
+ return { cue, keycap };
450
542
  },
451
543
  };
452
544
  }
@@ -459,17 +551,36 @@ const uploadStream = url => new WritableStream({
459
551
  },
460
552
  });
461
553
 
462
- window.cuetakeRender = async ({ sourceUrl, finalUrl, duration, viewport, pointer, events, edit }) => {
554
+ window.cuetakeRender = async ({ sourceUrl, finalUrl, duration, viewport, pointer, shapes, events, edit, narration }) => {
463
555
  const { camera } = edit, { quality, fps } = edit.output;
464
556
  const { width, height } = outputSize(edit);
465
557
  const started = performance.now();
466
558
  const input = new MB.Input({ formats: MB.ALL_FORMATS, source: new MB.UrlSource(sourceUrl) });
467
559
  const track = await input.getPrimaryVideoTrack();
468
560
  const reader = frameReader(track, await track.getDecoderConfig());
469
- const frameCount = Math.round(duration * fps);
561
+ const frameCount = Math.round(duration * fps), seconds = frameCount / fps;
562
+ const voice = await prepareNarration(narration, edit.subtitles, seconds);
470
563
  const output = new MB.Output({ format: new MB.Mp4OutputFormat({ fastStart: 'reserve' }), target: new MB.StreamTarget(uploadStream(finalUrl), { chunked: true }) });
471
564
  const packets = new MB.EncodedVideoPacketSource('avc');
472
565
  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.
567
+ let audio = null;
568
+ 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 });
572
+ // Mediabunny's bound: a packet per 10 ms at most, plus a third for safety.
573
+ output.addAudioTrack(source, { maximumPacketCount: Math.ceil(seconds * 100 * 4 / 3) + 16 });
574
+ audio = { codec, source, mix: await mixLines(voice, narration.volume, seconds), fed: 0 };
575
+ }
576
+ const feedAudio = async until => {
577
+ const end = Math.min(audio.mix.length, Math.round(until * SAMPLE_RATE));
578
+ 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);
581
+ audio.fed = end;
582
+ await audio.source.add(chunk);
583
+ };
473
584
  await output.start();
474
585
  const { config, quantizer } = await encoderConfig(width, height, fps, quality);
475
586
  let failure = null, muxed = Promise.resolve();
@@ -487,7 +598,8 @@ window.cuetakeRender = async ({ sourceUrl, finalUrl, duration, viewport, pointer
487
598
 
488
599
  let current = await reader.next(), next = await reader.next(), uploaded = null;
489
600
  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;
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;
491
603
  const cameraPath = cameraTrack({ targets: camera.targets, viewport, camera, duration, fps, pointerAt: t => pointerAt(pointer, t) });
492
604
  const origin = current.timestamp;
493
605
  try {
@@ -497,7 +609,10 @@ window.cuetakeRender = async ({ sourceUrl, finalUrl, duration, viewport, pointer
497
609
  const due = origin + Math.round(i * 1e6 / fps);
498
610
  while (next && next.timestamp <= due) { current.close(); current = next; next = await reader.next(); }
499
611
  if (uploaded !== current) { compositor.upload(current); uploaded = current; }
500
- scene.draw(i / fps, cameraPath[i]);
612
+ if (audio && i % fps === 0) await feedAudio(i / fps + 1);
613
+ const { cue, keycap } = scene.draw(i / fps, cameraPath[i]);
614
+ if (cue >= 0) shownFrames[cue] = [shownFrames[cue]?.[0] ?? i, i];
615
+ if (keycap) keycapFrames[keycap.index] = [keycapFrames[keycap.index]?.[0] ?? i, i];
501
616
  const videoFrame = new VideoFrame(compositor.canvas, { timestamp: Math.round(i * 1e6 / fps), duration: Math.round(1e6 / fps) });
502
617
  encoder.encode(videoFrame, { keyFrame: i % (fps * 2) === 0, ...(quantizer ? { avc: { quantizer } } : {}) });
503
618
  videoFrame.close();
@@ -506,6 +621,7 @@ window.cuetakeRender = async ({ sourceUrl, finalUrl, duration, viewport, pointer
506
621
  await encoder.flush();
507
622
  await muxed;
508
623
  if (failure) throw failure;
624
+ if (audio) await feedAudio(Infinity);
509
625
  await output.finalize();
510
626
  } finally {
511
627
  current?.close(); next?.close(); reader.close();
@@ -515,11 +631,38 @@ window.cuetakeRender = async ({ sourceUrl, finalUrl, duration, viewport, pointer
515
631
  width, height, frames: frameCount, sourceFrames: reader.stats().decoded, codec: config.codec,
516
632
  rateControl: quantizer ? `quantizer ${quantizer}` : `variable ${config.bitrate} bps`, gpu: compositor.gpu,
517
633
  seconds: +((performance.now() - started) / 1000).toFixed(2),
634
+ // Each keycap show with the first and last output frame it was drawn on.
635
+ ...(scene.keycapShows.length && { keycaps: scene.keycapShows.map((show, i) => ({ t: show.t, keys: show.keys, presses: show.presses.length, frames: keycapFrames[i] ?? null })) }),
636
+ ...(voice && {
637
+ audio: { codec: audio.codec, sampleRate: SAMPLE_RATE, channels: 1, bitrate: AUDIO_BITRATE },
638
+ lines: voice.placed.map(({ id, start, duration }) => ({ id, start, duration })),
639
+ // Each cue with the first and last output frame it was drawn on (null when Subtitles are not burned in).
640
+ subtitles: cues.map((cue, i) => ({ ...cue, frames: shownFrames[i] })),
641
+ }),
518
642
  };
519
643
  };
520
644
 
521
- /** Reads a Final's container metadata and decodes every frame. */
522
- window.cuetakeInspect = async url => {
645
+ /** Decodes every packet of an audio track; returns how many packets and how many decoded chunks it saw. */
646
+ async function decodeAudioTrack(track) {
647
+ let decoded = 0, packets = 0, failure = null;
648
+ const decoder = new AudioDecoder({ output: data => { decoded++; data.close(); }, error: error => { failure = error; } });
649
+ decoder.configure(await track.getDecoderConfig());
650
+ try {
651
+ for await (const packet of new MB.EncodedPacketSink(track).packets()) {
652
+ decoder.decode(packet.toEncodedAudioChunk()); packets++;
653
+ while (decoder.decodeQueueSize > 16) await new Promise(resolve => decoder.addEventListener('dequeue', resolve, { once: true }));
654
+ }
655
+ await decoder.flush();
656
+ } finally { if (decoder.state !== 'closed') decoder.close(); }
657
+ if (failure) throw failure;
658
+ return { packets, decoded };
659
+ }
660
+
661
+ /**
662
+ * Reads a Final's container metadata and decodes every frame and audio packet. `lines` ([{ id, url,
663
+ * audio }]) are decoded too, giving each Line's duration or the reason it cannot be read.
664
+ */
665
+ window.cuetakeInspect = async (url, lines = []) => {
523
666
  const input = new MB.Input({ formats: MB.ALL_FORMATS, source: new MB.UrlSource(url) });
524
667
  const track = await input.getPrimaryVideoTrack();
525
668
  const stats = await track.computePacketStats();
@@ -527,17 +670,31 @@ window.cuetakeInspect = async url => {
527
670
  let frames = 0;
528
671
  try { for (let frame; (frame = await reader.next());) { frames++; frame.close(); } }
529
672
  finally { reader.close(); }
673
+ const audioTrack = await input.getPrimaryAudioTrack();
674
+ let audio = null;
675
+ if (audioTrack) {
676
+ audio = { codec: await audioTrack.getCodecParameterString(), sampleRate: audioTrack.sampleRate, channels: audioTrack.numberOfChannels, duration: await audioTrack.computeDuration() };
677
+ try { audio = { ...audio, ...await decodeAudioTrack(audioTrack) }; } catch (error) { audio.error = error.message; }
678
+ }
679
+ 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
680
  return {
531
681
  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,
682
+ duration: await track.computeDuration(), fps: +stats.averagePacketRate.toFixed(3), packets: stats.packetCount, decodedFrames: frames,
683
+ audio, lines: measured,
533
684
  };
534
685
  };
535
686
 
687
+ /** Each Line's audio duration in seconds, for the Director to hold each Line while it is spoken. */
688
+ window.cuetakeMeasure = async lines => {
689
+ const buffers = await decodeLines(lines);
690
+ return Object.fromEntries(lines.map((line, i) => [line.id, buffers[i].duration]));
691
+ };
692
+
536
693
  /**
537
694
  * A Preview as a base64 PNG: each tile's Edit composed by the same scene as Render, over the Source at
538
695
  * `at` seconds with the Final's camera, or (`at` null) over the last moment with the camera wide.
539
696
  */
540
- window.cuetakePreview = async ({ sourceUrl, duration, viewport, pointer, events, tiles, at }) => {
697
+ window.cuetakePreview = async ({ sourceUrl, duration, viewport, pointer, shapes, events, tiles, at, narration }) => {
541
698
  const input = new MB.Input({ formats: MB.ALL_FORMATS, source: new MB.UrlSource(sourceUrl) });
542
699
  const track = await input.getPrimaryVideoTrack();
543
700
  const sink = new MB.VideoSampleSink(track), origin = await track.getFirstTimestamp();
@@ -552,7 +709,8 @@ window.cuetakePreview = async ({ sourceUrl, duration, viewport, pointer, events,
552
709
  ctx.imageSmoothingQuality = 'high';
553
710
  ctx.font = '600 22px system-ui, -apple-system, sans-serif'; ctx.textBaseline = 'middle'; ctx.fillStyle = '#e5e7eb';
554
711
  for (const [i, { name, edit }] of tiles.entries()) {
555
- const scene = await createScene(edit, viewport, { pointer, events }, firstFrame, track.codedWidth, track.codedHeight);
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);
556
714
  let crop = { x: 0, y: 0, w: viewport.width, h: viewport.height };
557
715
  if (at !== null) {
558
716
  const { fps } = edit.output, path = cameraTrack({ targets: edit.camera.targets, viewport, camera: edit.camera, duration, fps, pointerAt: s => pointerAt(pointer, s) });
package/src/render.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import fs from 'node:fs/promises';
2
2
  import { createRequire } from 'node:module';
3
- import { dirname, join } from 'node:path';
3
+ import { basename, dirname, extname, join } from 'node:path';
4
4
  import { fileURLToPath } from 'node:url';
5
5
  import { chromium } from 'playwright';
6
6
  import { contentType } from './styles.js';
@@ -20,6 +20,8 @@ const pageFiles = {
20
20
  '/camera.js': { path: fileURLToPath(new URL('./camera.js', import.meta.url)), type: 'text/javascript' },
21
21
  '/cursor.js': { path: fileURLToPath(new URL('./cursor.js', import.meta.url)), type: 'text/javascript' },
22
22
  '/stage.js': { path: fileURLToPath(new URL('./stage.js', import.meta.url)), type: 'text/javascript' },
23
+ '/narration.js': { path: fileURLToPath(new URL('./narration.js', import.meta.url)), type: 'text/javascript' },
24
+ '/shortcuts.js': { path: fileURLToPath(new URL('./shortcuts.js', import.meta.url)), type: 'text/javascript' },
23
25
  '/mediabunny.js': { path: mediabunnyBundle, type: 'text/javascript' },
24
26
  };
25
27
 
@@ -62,12 +64,18 @@ async function withRenderPage({ files = {}, writable = {} }, task) {
62
64
  });
63
65
  await page.goto(`${ORIGIN}/render.html`);
64
66
  await page.waitForFunction(() => window.cuetakeRender, null, { timeout: 15_000 }).catch(() => { throw new Error(`Render page failed to load: ${errors.join('; ')}`); });
65
- const result = await task(page).catch(error => { throw offline(error, blocked); });
67
+ const result = await task(page).catch(error => { throw offline(fromPage(error), blocked); });
66
68
  if (blocked.length) throw offline(null, blocked);
67
69
  return result;
68
70
  } finally { await browser.close(); }
69
71
  }
70
72
 
73
+ /** An error thrown in the render page, without Playwright's prefix and the page's stack. */
74
+ function fromPage(error) {
75
+ const message = error.message.replace(/^page\.evaluate: (Error: )?/, '').split(/\n\s+at /)[0];
76
+ return message === error.message ? error : new Error(message);
77
+ }
78
+
71
79
  /** Names what styling code tried to fetch, which the render page cannot. */
72
80
  function offline(error, blocked) {
73
81
  if (!blocked.length) return error;
@@ -75,29 +83,57 @@ function offline(error, blocked) {
75
83
  return new Error(error ? `${error.message}\n${note}` : note);
76
84
  }
77
85
 
78
- /** Composes the Final from a Source, Timeline and Edit; `files` serves the Edit's styling files (styles.js forRender). */
79
- export async function renderFinal({ sourcePath, finalPath, timeline, edit, files = {} }) {
86
+ /**
87
+ * Lines as the render page reads them, `{ id, audio, url, ... }`, with their audio served from `files`.
88
+ * Each Line is `{ id, path, ... }`, `path` being its audio file.
89
+ */
90
+ function servedLines(lines, files) {
91
+ return lines.map(({ path, ...line }, i) => {
92
+ const name = `line-${i}${extname(path)}`;
93
+ files[name] = path;
94
+ return { ...line, audio: basename(path), url: `${ORIGIN}/files/${name}` };
95
+ });
96
+ }
97
+
98
+ /**
99
+ * Composes the Final from a Source, Timeline and Edit; `files` serves the Edit's styling files (styles.js
100
+ * forRender). `narration` ({ language, volume, lines }) adds its Lines' audio and Subtitles.
101
+ */
102
+ export async function renderFinal({ sourcePath, finalPath, timeline, edit, files = {}, narration = null }) {
80
103
  const handle = await fs.open(finalPath, 'w');
104
+ const served = { ...files, source: sourcePath };
105
+ const spoken = narration && { ...narration, lines: servedLines(narration.lines, served) };
81
106
  try {
82
- return await withRenderPage({ files: { ...files, source: sourcePath }, writable: { final: handle } }, page => page.evaluate(options => window.cuetakeRender(options), {
107
+ return await withRenderPage({ files: served, writable: { final: handle } }, page => page.evaluate(options => window.cuetakeRender(options), {
83
108
  sourceUrl: `${ORIGIN}/files/source`, finalUrl: `${ORIGIN}/files/final`, duration: timeline.duration,
84
- viewport: timeline.viewport, pointer: timeline.pointer ?? [], events: timeline.events ?? [], edit,
109
+ viewport: timeline.viewport, pointer: timeline.pointer ?? [], shapes: timeline.shapes ?? [], events: timeline.events ?? [], edit, narration: spoken,
85
110
  }));
86
111
  } finally { await handle.close(); }
87
112
  }
88
113
 
89
114
  /** A Preview PNG of `tiles` ([{ name, edit }]) at `at` seconds, or at the end with the camera wide. No Final is touched. */
90
- export async function composePreview({ sourcePath, timeline, tiles, at, files = {} }) {
91
- const png = await withRenderPage({ files: { ...files, source: sourcePath } }, page => page.evaluate(options => window.cuetakePreview(options), {
115
+ export async function composePreview({ sourcePath, timeline, tiles, at, files = {}, narration = null }) {
116
+ const served = { ...files, source: sourcePath };
117
+ const spoken = narration && { ...narration, lines: servedLines(narration.lines, served) };
118
+ const png = await withRenderPage({ files: served }, page => page.evaluate(options => window.cuetakePreview(options), {
92
119
  sourceUrl: `${ORIGIN}/files/source`, duration: timeline.duration, viewport: timeline.viewport,
93
- pointer: timeline.pointer ?? [], events: timeline.events ?? [], tiles, at: at ?? null,
120
+ pointer: timeline.pointer ?? [], shapes: timeline.shapes ?? [], events: timeline.events ?? [], tiles, at: at ?? null, narration: spoken,
94
121
  }));
95
122
  return Buffer.from(png, 'base64');
96
123
  }
97
124
 
98
- /** Container metadata of a Final plus a full decode. */
99
- export function inspectFinal(path) {
100
- return withRenderPage({ files: { final: path } }, page => page.evaluate(url => window.cuetakeInspect(url), `${ORIGIN}/files/final`));
125
+ /** Container metadata of a Final plus a full decode of its video and audio, and of each Line's audio (`lines`: [{ id, path }]). */
126
+ export function inspectFinal(path, lines = []) {
127
+ const files = { final: path };
128
+ const served = servedLines(lines, files);
129
+ return withRenderPage({ files }, page => page.evaluate(([url, lines]) => window.cuetakeInspect(url, lines), [`${ORIGIN}/files/final`, served]));
130
+ }
131
+
132
+ /** Each Line's audio duration in seconds (`lines`: [{ id, path }]); the error names a Line whose audio cannot be decoded. */
133
+ export function measureLines(lines) {
134
+ const files = {};
135
+ const served = servedLines(lines, files);
136
+ return withRenderPage({ files }, page => page.evaluate(lines => window.cuetakeMeasure(lines), served));
101
137
  }
102
138
 
103
139
  /** A PNG of the Final at `seconds`, for agents to look at without FFmpeg. */
@@ -0,0 +1,73 @@
1
+ /**
2
+ * Shortcuts and their keycaps, shared by Node and the render page. Pure functions, no imports; seconds throughout.
3
+ *
4
+ * A Shortcut is a key pressed outside a text field, or with Control, Alt or Meta held inside one: typing
5
+ * into a field already shows on the page, a shortcut does not. Its `keys` are the held modifiers in
6
+ * macOS order (Control, Alt, Shift, Meta), then the key, named as the DOM names it (`K`, `Enter`,
7
+ * `ArrowUp`, `Space`), so the same press reads the same on every keyboard layout Playwright plays.
8
+ */
9
+
10
+ const MODIFIERS = [['ctrlKey', 'Control'], ['altKey', 'Alt'], ['shiftKey', 'Shift'], ['metaKey', 'Meta']];
11
+ // Keys that only change another key, or carry no key of their own.
12
+ const NOT_SHOWN = new Set(['Control', 'Alt', 'Shift', 'Meta', 'AltGraph', 'CapsLock', 'Fn', 'FnLock', 'Hyper', 'Super', 'Symbol', 'SymbolLock', 'OS', 'Process', 'Dead', 'Unidentified', '']);
13
+ const FADE_IN = 0.12, FADE_OUT = 0.25; // seconds keycaps take to appear and to go
14
+ const RISE = 12; // 1080p pixels keycaps rise as they appear
15
+
16
+ /** The key a keydown names: a letter or digit by its place on the keyboard, so held modifiers do not change it. */
17
+ function keyName({ key, code = '' }) {
18
+ if (/^Key[A-Z]$/.test(code)) return code.slice(3);
19
+ if (/^Digit\d$/.test(code)) return code.slice(5);
20
+ if (key === ' ') return 'Space';
21
+ return key?.length === 1 ? key.toUpperCase() : key;
22
+ }
23
+
24
+ /**
25
+ * The keys a keydown shows, or null for one that is typing, a modifier on its own or the key repeating.
26
+ * `down` holds the event's `key`, `code`, modifier flags and `repeat`, and `field`: whether a text field had focus.
27
+ */
28
+ export function shortcutKeys(down) {
29
+ const key = keyName(down);
30
+ if (down.repeat || NOT_SHOWN.has(key ?? '')) return null;
31
+ if (down.field && !down.ctrlKey && !down.altKey && !down.metaKey) return null;
32
+ return [...MODIFIERS.filter(([flag]) => down[flag]).map(([, name]) => name), key];
33
+ }
34
+
35
+ const sameKeys = (a, b) => a.length === b.length && a.every((key, i) => key === b[i]);
36
+
37
+ /**
38
+ * When each Shortcut's keycaps show: from its press until `duration` after, joined by later presses of
39
+ * the same keys while it shows, which count up. A new Shortcut replaces the one showing at once, without fading.
40
+ */
41
+ export function keycapShows(shortcuts, duration) {
42
+ const shows = [];
43
+ for (const { t, keys } of shortcuts.toSorted((a, b) => a.t - b.t)) {
44
+ const last = shows.at(-1);
45
+ if (last && t < last.end && sameKeys(last.keys, keys)) { last.presses.push(t); last.end = t + duration; continue; }
46
+ const replacing = Boolean(last && t < last.end);
47
+ if (replacing) { last.end = t; last.replaced = true; }
48
+ shows.push({ t, end: t + duration, keys, presses: [t], replacing, replaced: false });
49
+ }
50
+ return shows;
51
+ }
52
+
53
+ const easeOut = u => 1 - (1 - u) ** 3;
54
+
55
+ /**
56
+ * The keycaps through a Take: `at(t)` gives the index of the show on screen, its keys, how many times
57
+ * they have been pressed, its opacity and how far below its place it is (1080p pixels), or null.
58
+ * `keycaps` is the Edit's keycaps item; `false` shows none, and a key pressed alone shows only with `singleKeys`.
59
+ */
60
+ export function keycapTrack(shortcuts, keycaps) {
61
+ const shown = (shortcuts ?? []).filter(shortcut => keycaps?.singleKeys || shortcut.keys.length > 1);
62
+ const shows = keycaps ? keycapShows(shown, keycaps.duration ?? 1.5) : [];
63
+ return {
64
+ shows,
65
+ at(t) {
66
+ const index = shows.findIndex(show => t >= show.t && t < show.end);
67
+ if (index < 0) return null;
68
+ const show = shows[index], appear = show.replacing ? 1 : Math.min(1, (t - show.t) / FADE_IN);
69
+ const leave = show.replaced ? 1 : Math.min(1, (show.end - t) / FADE_OUT);
70
+ return { index, keys: show.keys, count: show.presses.filter(p => p <= t).length, opacity: Math.max(0, Math.min(appear, leave)), rise: RISE * (1 - easeOut(appear)) };
71
+ },
72
+ };
73
+ }