cuetake 0.2.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.
- package/README.md +8 -6
- package/package.json +2 -2
- package/src/auth.js +8 -1
- package/src/cli.js +26 -8
- package/src/cursor.js +57 -30
- package/src/director.js +80 -25
- package/src/edit.js +55 -45
- package/src/environment.js +23 -7
- package/src/look.js +88 -60
- package/src/motion.js +66 -0
- package/src/narration.js +146 -0
- package/src/pipeline.js +188 -33
- package/src/probe.js +78 -20
- package/src/render-page.js +498 -207
- package/src/render.js +68 -17
- package/src/shortcuts.js +73 -0
- package/src/stage.js +28 -44
- package/src/styles/arrow.js +133 -0
- package/src/styles/browser.js +24 -0
- package/src/styles/dot.js +12 -0
- package/src/styles/fluted.glsl +35 -0
- package/src/styles/keycaps.js +38 -0
- package/src/styles/macos.js +12 -0
- package/src/styles/shadow.glsl +10 -0
- package/src/styles/spark.js +19 -0
- package/src/styles/subtitles.js +17 -0
- package/src/styles.js +108 -0
- package/src/uninstall.js +62 -0
package/src/render-page.js
CHANGED
|
@@ -1,74 +1,69 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Runs inside Chromium (see render.js). Source WebM → VideoDecoder →
|
|
3
|
-
*
|
|
2
|
+
* Runs inside Chromium (see render.js). Source WebM → VideoDecoder → WebGL2 → VideoEncoder (H.264) →
|
|
3
|
+
* MP4, streamed back to Node in chunks.
|
|
4
|
+
*
|
|
5
|
+
* Each output frame is the Background (drawn once, still in output pixels), the window effects (drawn
|
|
6
|
+
* every frame around the window as the camera moves it), the page, then the chrome, click effects and
|
|
7
|
+
* Cursor, and outside the camera the Subtitles and keycaps. Everything but the page is agent-written
|
|
8
|
+
* shaders, drawing code or images (ADR 0005).
|
|
4
9
|
*
|
|
5
10
|
* Spaces: camera crops are CSS pixels of the viewport; the Source texture is sampled by UV only;
|
|
6
11
|
* "stage" is the Final's pixels at camera zoom 1, laid out by stage.js.
|
|
7
12
|
*/
|
|
8
13
|
import * as MB from '/mediabunny.js';
|
|
9
14
|
import { cameraTrack } from '/camera.js';
|
|
10
|
-
import {
|
|
11
|
-
import { layout, cameraView, previewSheet,
|
|
15
|
+
import { cursorTrack, drawnShape, pointerAt, presses, sparksAt } from '/cursor.js';
|
|
16
|
+
import { layout, outputSize, cameraView, previewSheet, brandColor } from '/stage.js';
|
|
17
|
+
import { burnsIn, cuesFor, lineProblems } from '/narration.js';
|
|
18
|
+
import { keycapTrack } from '/shortcuts.js';
|
|
12
19
|
|
|
13
20
|
const VERTEX = `#version 300 es
|
|
14
21
|
in vec2 p; void main() { gl_Position = vec4(p, 0, 1); }`;
|
|
15
|
-
|
|
22
|
+
/** Prepended to every agent shader, whose own source then starts at line 1. */
|
|
23
|
+
const SHADER_HEADER = `#version 300 es
|
|
24
|
+
precision highp float;
|
|
25
|
+
uniform vec2 uResolution; // output pixels
|
|
26
|
+
uniform float uUnit; // output pixels per 1080p pixel
|
|
27
|
+
uniform vec3 uBrand; // the page's brand color, RGB 0–1
|
|
28
|
+
uniform sampler2D uPrevious; // Background layers: the layers below; window effects: the Background
|
|
29
|
+
uniform sampler2D uPage; // the page: its first frame for Background layers, the current one for window effects
|
|
30
|
+
uniform vec4 uWindow; // the window (chrome + page) in output pixels: left, top, width, height
|
|
31
|
+
uniform float uRadius; // the window's corner radius in output pixels
|
|
32
|
+
uniform float uZoom; // the camera zoom; 1 for Background layers
|
|
33
|
+
out vec4 color; // premultiplied RGBA
|
|
34
|
+
vec2 pixel() { return vec2(gl_FragCoord.x, uResolution.y - gl_FragCoord.y); }
|
|
35
|
+
vec4 previous(vec2 px) { return texture(uPrevious, vec2(px.x, uResolution.y - px.y) / uResolution); }
|
|
36
|
+
float windowDistance(vec2 px) {
|
|
37
|
+
vec2 q = abs(px - uWindow.xy - uWindow.zw * 0.5) - (uWindow.zw * 0.5 - uRadius);
|
|
38
|
+
return length(max(q, 0.0)) + min(max(q.x, q.y), 0.0) - uRadius;
|
|
39
|
+
}
|
|
40
|
+
`;
|
|
41
|
+
const HEADER_UNIFORMS = new Set(['uResolution', 'uUnit', 'uBrand', 'uPrevious', 'uPage', 'uWindow', 'uRadius', 'uZoom']);
|
|
42
|
+
// An image layer is drawn over the layers below it.
|
|
43
|
+
const IMAGE_LAYER = `uniform sampler2D image;
|
|
44
|
+
void main() { vec4 top = texture(image, pixel() / uResolution); color = top + previous(pixel()) * (1.0 - top.a); }`;
|
|
45
|
+
const BLIT = `#version 300 es
|
|
16
46
|
precision highp float;
|
|
17
|
-
uniform vec2 uRes;
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
uniform
|
|
23
|
-
uniform float uShadow; // drop shadow strength
|
|
24
|
-
uniform float uBlur; // 1: background is the blurred page
|
|
25
|
-
uniform vec3 uBase; // mesh background: base color under up to four blobs
|
|
26
|
-
uniform vec4 uBlobs[4]; // x, y, radius as stage fractions
|
|
27
|
-
uniform vec3 uBlobColors[4];
|
|
28
|
-
uniform int uBlobCount;
|
|
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.
|
|
50
|
+
const PAGE = `#version 300 es
|
|
51
|
+
precision highp float;
|
|
52
|
+
uniform vec2 uRes; uniform vec3 uCam; uniform vec4 uPage; uniform vec4 uWindow; uniform float uRadius;
|
|
29
53
|
uniform sampler2D uSource;
|
|
30
54
|
out vec4 color;
|
|
31
|
-
|
|
32
55
|
float roundedBox(vec2 p, vec4 rect, float r) {
|
|
33
56
|
vec2 q = abs(p - rect.xy - rect.zw * 0.5) - (rect.zw * 0.5 - r);
|
|
34
57
|
return length(max(q, 0.0)) + min(max(q.x, q.y), 0.0) - r;
|
|
35
58
|
}
|
|
36
|
-
float noise(vec2 p) { return fract(sin(dot(p, vec2(12.9898, 78.233))) * 43758.5453); }
|
|
37
|
-
|
|
38
59
|
void main() {
|
|
39
60
|
vec2 pixel = vec2(gl_FragCoord.x, uRes.y - gl_FragCoord.y);
|
|
40
61
|
vec2 stage = (pixel - uRes * 0.5) / uCam.z + uCam.xy;
|
|
41
|
-
|
|
42
|
-
if (
|
|
43
|
-
|
|
44
|
-
vec3 c;
|
|
45
|
-
if (uBlur > 0.5) {
|
|
46
|
-
// Cover the stage with the page, then read a coarse mip level as a cheap wide blur.
|
|
47
|
-
float r = (uRes.x / uRes.y) / (uPage.z / uPage.w);
|
|
48
|
-
vec2 uv = 0.5 + (stage / uRes - 0.5) * vec2(min(1.0, r), min(1.0, 1.0 / r)) / 1.2;
|
|
49
|
-
c = textureLod(uSource, uv, 6.0).rgb * 0.8;
|
|
50
|
-
} else {
|
|
51
|
-
c = uBase;
|
|
52
|
-
for (int i = 3; i >= 0; i--) {
|
|
53
|
-
if (i >= uBlobCount) continue;
|
|
54
|
-
float d = length((stage / uRes - uBlobs[i].xy) / uBlobs[i].z);
|
|
55
|
-
c = mix(c, uBlobColors[i], 1.0 - smoothstep(0.0, 0.7, d));
|
|
56
|
-
}
|
|
57
|
-
}
|
|
58
|
-
// Grain dithers the gradients so H.264 does not band them.
|
|
59
|
-
c += (noise(pixel) - 0.5) * 0.035;
|
|
60
|
-
|
|
61
|
-
float unit = min(uRes.x, uRes.y) / 1080.0;
|
|
62
|
-
float shadow = uShadow * (1.0 - smoothstep(-60.0 * unit, 60.0 * unit, roundedBox(stage - vec2(0.0, 24.0 * unit), uWindow, uRadius)));
|
|
63
|
-
c = mix(c, vec3(0.0), shadow * 0.55);
|
|
64
|
-
|
|
65
|
-
float edge = roundedBox(stage, uWindow, uRadius) * uCam.z; // output pixels from the window edge
|
|
66
|
-
float inside = clamp(0.5 - edge, 0.0, 1.0);
|
|
67
|
-
if (stage.y >= uPage.y) c = mix(c, texture(uSource, pageUv).rgb, inside);
|
|
68
|
-
c = mix(c, vec3(1.0), 0.18 * (1.0 - smoothstep(0.0, 1.0, abs(edge)))); // hairline rim
|
|
69
|
-
color = vec4(c, 1.0);
|
|
62
|
+
float inside = clamp(0.5 - roundedBox(stage, uWindow, uRadius) * uCam.z, 0.0, 1.0);
|
|
63
|
+
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;
|
|
70
65
|
}`;
|
|
71
|
-
// Sprites (cursor,
|
|
66
|
+
// Sprites (chrome, cursor, click effects) are premultiplied textures placed by a stage rectangle under the camera.
|
|
72
67
|
const SPRITE_VERTEX = `#version 300 es
|
|
73
68
|
in vec2 p;
|
|
74
69
|
uniform vec2 uRes; uniform vec3 uCam; uniform vec4 uRect;
|
|
@@ -80,62 +75,74 @@ void main() {
|
|
|
80
75
|
}`;
|
|
81
76
|
const SPRITE_FRAGMENT = `#version 300 es
|
|
82
77
|
precision highp float;
|
|
83
|
-
uniform sampler2D uSprite;
|
|
78
|
+
uniform sampler2D uSprite; uniform float uAlpha;
|
|
84
79
|
in vec2 uv; out vec4 color;
|
|
85
|
-
void main() { color = texture(uSprite, uv); }`;
|
|
80
|
+
void main() { color = texture(uSprite, uv) * uAlpha; }`;
|
|
86
81
|
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
82
|
+
// Item keys CueTake reads itself; every other key is a parameter for the item's shader or drawing code.
|
|
83
|
+
const OWN_KEYS = new Set(['shader', 'draw', 'image', 'files', 'ref', 'kind', 'url']);
|
|
84
|
+
const SLOT_KEYS = new Set(['size', 'hotspot', 'press', 'duration', 'singleKeys', 'reach', 'height', 'burn', 'maxChars', 'maxRows', 'minDuration']);
|
|
85
|
+
const paramsOf = item => Object.fromEntries(Object.entries(item).filter(([key]) => !OWN_KEYS.has(key) && (item.kind === 'shader' || !SLOT_KEYS.has(key))));
|
|
86
|
+
const fail = (item, error) => new Error(`${item.ref}: ${error?.message ?? error}`);
|
|
87
|
+
|
|
88
|
+
/** A parameter as a GLSL uniform: numbers and booleans are floats, 2–4 numbers a vector, '#rrggbb(aa)' a color. */
|
|
89
|
+
function uniformOf(value) {
|
|
90
|
+
if (typeof value === 'number') return ['float', [value]];
|
|
91
|
+
if (typeof value === 'boolean') return ['float', [value ? 1 : 0]];
|
|
92
|
+
if (Array.isArray(value) && value.length >= 2 && value.length <= 4 && value.every(n => typeof n === 'number')) return [`vec${value.length}`, value];
|
|
93
|
+
if (typeof value === 'string' && /^#([0-9a-f]{6}|[0-9a-f]{8})$/i.test(value)) {
|
|
94
|
+
const channels = value.slice(1).match(/../g).map(h => parseInt(h, 16) / 255);
|
|
95
|
+
return [`vec${channels.length}`, channels];
|
|
96
|
+
}
|
|
97
|
+
return null;
|
|
93
98
|
}
|
|
94
99
|
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
submitted++;
|
|
114
|
-
}
|
|
115
|
-
return ready.shift();
|
|
116
|
-
},
|
|
117
|
-
close() { ready.splice(0).forEach(frame => frame.close()); if (decoder.state !== 'closed') decoder.close(); },
|
|
118
|
-
};
|
|
100
|
+
async function loadImage(item, url) {
|
|
101
|
+
const image = new Image();
|
|
102
|
+
image.src = url;
|
|
103
|
+
try { await image.decode(); } catch { throw fail(item, `${url.split('/').pop()} is not an image the browser can open`); }
|
|
104
|
+
return image;
|
|
105
|
+
}
|
|
106
|
+
const FONT = /\.(woff2?|ttf|otf)$/i;
|
|
107
|
+
/** An item's `files` for drawing code: images as <img> elements, fonts registered under their key. */
|
|
108
|
+
async function loadFiles(item) {
|
|
109
|
+
const loaded = {};
|
|
110
|
+
for (const [name, url] of Object.entries(item.files ?? {})) {
|
|
111
|
+
if (FONT.test(url)) {
|
|
112
|
+
const face = new FontFace(name, `url(${url})`);
|
|
113
|
+
try { await face.load(); } catch (error) { throw fail(item, error); }
|
|
114
|
+
document.fonts.add(face); loaded[name] = name;
|
|
115
|
+
} else loaded[name] = await loadImage(item, url);
|
|
116
|
+
}
|
|
117
|
+
return loaded;
|
|
119
118
|
}
|
|
119
|
+
async function loadModule(item) {
|
|
120
|
+
try { return await import(item.url); } catch (error) { throw fail(item, error); }
|
|
121
|
+
}
|
|
122
|
+
const canvas2d = (width, height) => {
|
|
123
|
+
const canvas = document.createElement('canvas');
|
|
124
|
+
canvas.width = Math.max(1, Math.ceil(width)); canvas.height = Math.max(1, Math.ceil(height));
|
|
125
|
+
return canvas.getContext('2d');
|
|
126
|
+
};
|
|
120
127
|
|
|
121
|
-
/**
|
|
122
|
-
function createCompositor(stage,
|
|
123
|
-
const { width, height } = stage;
|
|
128
|
+
/** The compositor for one stage: the Background drawn once, then per frame effects, page and sprites. */
|
|
129
|
+
function createCompositor(stage, sourceWidth, sourceHeight, brand) {
|
|
130
|
+
const { width, height } = stage, unit = Math.min(width, height) / 1080;
|
|
124
131
|
const canvas = new OffscreenCanvas(width, height);
|
|
125
132
|
const gl = canvas.getContext('webgl2', { alpha: false, antialias: false, depth: false });
|
|
126
|
-
const
|
|
133
|
+
const compile = (type, text, item) => {
|
|
127
134
|
const s = gl.createShader(type); gl.shaderSource(s, text); gl.compileShader(s);
|
|
128
|
-
if (!gl.getShaderParameter(s, gl.COMPILE_STATUS)) throw new Error(gl.getShaderInfoLog(s));
|
|
135
|
+
if (!gl.getShaderParameter(s, gl.COMPILE_STATUS)) throw item ? fail(item, gl.getShaderInfoLog(s).trim()) : new Error(gl.getShaderInfoLog(s));
|
|
129
136
|
return s;
|
|
130
137
|
};
|
|
131
|
-
const program = (vertex, fragment) => {
|
|
138
|
+
const program = (vertex, fragment, item) => {
|
|
132
139
|
const p = gl.createProgram();
|
|
133
|
-
gl.attachShader(p,
|
|
140
|
+
gl.attachShader(p, compile(gl.VERTEX_SHADER, vertex, item)); gl.attachShader(p, compile(gl.FRAGMENT_SHADER, fragment, item));
|
|
134
141
|
gl.bindAttribLocation(p, 0, 'p');
|
|
135
142
|
gl.linkProgram(p);
|
|
136
|
-
if (!gl.getProgramParameter(p, gl.LINK_STATUS)) throw new Error(gl.getProgramInfoLog(p));
|
|
143
|
+
if (!gl.getProgramParameter(p, gl.LINK_STATUS)) throw item ? fail(item, gl.getProgramInfoLog(p)) : new Error(gl.getProgramInfoLog(p));
|
|
137
144
|
gl.useProgram(p);
|
|
138
|
-
gl.uniform2f(gl.getUniformLocation(p,
|
|
145
|
+
for (const name of ['uRes', 'uResolution']) gl.uniform2f(gl.getUniformLocation(p, name), width, height);
|
|
139
146
|
return { p, camera: gl.getUniformLocation(p, 'uCam'), uniform: name => gl.getUniformLocation(p, name) };
|
|
140
147
|
};
|
|
141
148
|
const quad = corners => {
|
|
@@ -152,32 +159,67 @@ function createCompositor(stage, backdrop, sourceWidth, sourceHeight) {
|
|
|
152
159
|
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
|
|
153
160
|
return t;
|
|
154
161
|
};
|
|
155
|
-
const
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
const rgb = hex => [1, 3, 5].map(i => parseInt(hex.slice(i, i + 2), 16) / 255);
|
|
162
|
-
set('uBase', ...rgb(backdrop.background.base));
|
|
163
|
-
const blobs = backdrop.background.blobs.slice(0, 4);
|
|
164
|
-
gl.uniform1i(pageProgram.uniform('uBlobCount'), blobs.length);
|
|
165
|
-
gl.uniform4fv(pageProgram.uniform('uBlobs'), blobs.flatMap(([x, y, r]) => [x, y, r, 0]).concat(Array(16).fill(0)).slice(0, 16));
|
|
166
|
-
gl.uniform3fv(pageProgram.uniform('uBlobColors'), blobs.flatMap(b => rgb(b[3])).concat(Array(12).fill(0)).slice(0, 12));
|
|
167
|
-
}
|
|
168
|
-
const spriteProgram = program(SPRITE_VERTEX, SPRITE_FRAGMENT);
|
|
169
|
-
const spriteRect = spriteProgram.uniform('uRect');
|
|
170
|
-
const fullScreen = quad([-1, -1, 1, -1, -1, 1, 1, 1]), unit = quad([0, 0, 1, 0, 0, 1, 1, 1]);
|
|
171
|
-
// Mipmaps keep zoomed-out text from aliasing when the 2× Source is minified.
|
|
172
|
-
const pageTexture = texture();
|
|
173
|
-
gl.texStorage2D(gl.TEXTURE_2D, Math.floor(Math.log2(Math.max(sourceWidth, sourceHeight))) + 1, gl.RGBA8, sourceWidth, sourceHeight);
|
|
162
|
+
const imageTexture = image => {
|
|
163
|
+
const t = texture(); gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, image); gl.generateMipmap(gl.TEXTURE_2D);
|
|
164
|
+
return t;
|
|
165
|
+
};
|
|
166
|
+
const bind = (unitIndex, t) => { gl.activeTexture(gl.TEXTURE0 + unitIndex); gl.bindTexture(gl.TEXTURE_2D, t); };
|
|
167
|
+
const fullScreen = quad([-1, -1, 1, -1, -1, 1, 1, 1]), unitQuad = quad([0, 0, 1, 0, 0, 1, 1, 1]);
|
|
174
168
|
gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, true);
|
|
175
169
|
gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
|
|
176
170
|
gl.viewport(0, 0, width, height);
|
|
177
|
-
|
|
171
|
+
|
|
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);
|
|
179
|
+
const blitProgram = program(VERTEX, BLIT);
|
|
180
|
+
const spriteProgram = program(SPRITE_VERTEX, SPRITE_FRAGMENT), spriteRect = spriteProgram.uniform('uRect'), spriteAlpha = spriteProgram.uniform('uAlpha');
|
|
181
|
+
|
|
182
|
+
/** An agent shader with its parameters declared and set, and its `files` bound from texture unit 2. */
|
|
183
|
+
async function agentProgram(item, source) {
|
|
184
|
+
const params = Object.entries(paramsOf(item)).map(([name, value]) => [name, uniformOf(value)]).filter(([name, u]) => u && /^[A-Za-z_]\w*$/.test(name));
|
|
185
|
+
const images = await Promise.all(Object.entries(item.files ?? {}).map(async ([name, url]) => [name, await loadImage(item, url)]));
|
|
186
|
+
const declarations = [
|
|
187
|
+
...params.filter(([name]) => !HEADER_UNIFORMS.has(name)).map(([name, [type]]) => `uniform ${type} ${name};`),
|
|
188
|
+
...images.flatMap(([name]) => [`uniform sampler2D ${name};`, `uniform vec2 ${name}Size;`]),
|
|
189
|
+
].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);
|
|
192
|
+
gl.uniform1i(p.uniform('uPrevious'), 0); gl.uniform1i(p.uniform('uPage'), 1);
|
|
193
|
+
for (const [name, [type, values]] of params) gl[`uniform${type === 'float' ? 1 : type.at(-1)}fv`](p.uniform(name), values);
|
|
194
|
+
const textures = images.map(([name, image], i) => {
|
|
195
|
+
gl.useProgram(p.p); gl.uniform1i(p.uniform(name), 2 + i); gl.uniform2f(p.uniform(`${name}Size`), image.naturalWidth, image.naturalHeight);
|
|
196
|
+
return imageTexture(image);
|
|
197
|
+
});
|
|
198
|
+
return { ...p, textures };
|
|
199
|
+
}
|
|
200
|
+
const shaderSource = async item => {
|
|
201
|
+
const response = await fetch(item.url);
|
|
202
|
+
if (!response.ok) throw fail(item, `could not be read (${response.status})`);
|
|
203
|
+
return response.text();
|
|
204
|
+
};
|
|
205
|
+
/** 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) => {
|
|
207
|
+
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);
|
|
210
|
+
p.textures?.forEach((t, i) => bind(2 + i, t));
|
|
211
|
+
gl.bindVertexArray(fullScreen); gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
|
|
212
|
+
gl.activeTexture(gl.TEXTURE0);
|
|
213
|
+
};
|
|
214
|
+
const checkGpu = what => { if (gl.isContextLost()) throw new Error(`${what} stopped the GPU; simplify the shader`); };
|
|
215
|
+
|
|
216
|
+
const target = () => { const t = texture(gl.LINEAR); gl.texStorage2D(gl.TEXTURE_2D, 1, gl.RGBA8, width, height); return t; };
|
|
217
|
+
const framebuffer = gl.createFramebuffer();
|
|
218
|
+
let background = target(), effects = [];
|
|
219
|
+
const restWindow = [stage.window.x, stage.window.y, stage.window.w, stage.window.h];
|
|
178
220
|
return {
|
|
179
221
|
canvas,
|
|
180
|
-
gpu: info ? gl.getParameter(info.UNMASKED_RENDERER_WEBGL) : 'unknown',
|
|
222
|
+
gpu: (() => { const info = gl.getExtension('WEBGL_debug_renderer_info'); return info ? gl.getParameter(info.UNMASKED_RENDERER_WEBGL) : 'unknown'; })(),
|
|
181
223
|
/** Frees the GPU context; a Preview makes one compositor per tile. */
|
|
182
224
|
dispose() { gl.getExtension('WEBGL_lose_context')?.loseContext(); },
|
|
183
225
|
upload(frame) {
|
|
@@ -185,6 +227,39 @@ function createCompositor(stage, backdrop, sourceWidth, sourceHeight) {
|
|
|
185
227
|
gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, gl.RGBA, gl.UNSIGNED_BYTE, frame);
|
|
186
228
|
gl.generateMipmap(gl.TEXTURE_2D);
|
|
187
229
|
},
|
|
230
|
+
/** Draws the Background layers in order, each over the result so far, starting from black. */
|
|
231
|
+
async drawBackground(layers) {
|
|
232
|
+
let other = target();
|
|
233
|
+
gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
|
|
234
|
+
gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, background, 0);
|
|
235
|
+
gl.clearColor(0, 0, 0, 1); gl.clear(gl.COLOR_BUFFER_BIT);
|
|
236
|
+
for (const item of layers) {
|
|
237
|
+
let p;
|
|
238
|
+
if (item.kind === 'image') {
|
|
239
|
+
// Cover the output, centered, at full resolution (SVG rasterizes at this size).
|
|
240
|
+
const image = await loadImage(item, item.url), w = image.naturalWidth || width, h = image.naturalHeight || height;
|
|
241
|
+
const k = Math.max(width / w, height / h), ctx = canvas2d(width, height);
|
|
242
|
+
ctx.drawImage(image, (width - w * k) / 2, (height - h * k) / 2, w * k, h * k);
|
|
243
|
+
p = await agentProgram({ ref: item.ref, kind: 'shader' }, IMAGE_LAYER);
|
|
244
|
+
p.textures = [imageTexture(ctx.canvas)]; gl.uniform1i(p.uniform('image'), 2);
|
|
245
|
+
} else if (item.kind === 'shader') p = await agentProgram(item, await shaderSource(item));
|
|
246
|
+
else throw fail(item, 'Background layers are shaders or images');
|
|
247
|
+
gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
|
|
248
|
+
gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, other, 0);
|
|
249
|
+
gl.disable(gl.BLEND);
|
|
250
|
+
run(p, background, restWindow, stage.radius, 1);
|
|
251
|
+
[background, other] = [other, background];
|
|
252
|
+
}
|
|
253
|
+
gl.bindFramebuffer(gl.FRAMEBUFFER, null);
|
|
254
|
+
checkGpu('A Background layer');
|
|
255
|
+
},
|
|
256
|
+
async loadEffects(items) {
|
|
257
|
+
effects = [];
|
|
258
|
+
for (const item of items) {
|
|
259
|
+
if (item.kind !== 'shader') throw fail(item, 'window effects are shaders');
|
|
260
|
+
effects.push(await agentProgram(item, await shaderSource(item)));
|
|
261
|
+
}
|
|
262
|
+
},
|
|
188
263
|
/** A sprite texture from a 2D canvas; pass `into` to reuse one. */
|
|
189
264
|
sprite(image, into, mipmaps = true) {
|
|
190
265
|
const t = into ?? texture(mipmaps ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
|
|
@@ -193,80 +268,204 @@ function createCompositor(stage, backdrop, sourceWidth, sourceHeight) {
|
|
|
193
268
|
if (mipmaps) gl.generateMipmap(gl.TEXTURE_2D);
|
|
194
269
|
return t;
|
|
195
270
|
},
|
|
196
|
-
/**
|
|
197
|
-
|
|
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) {
|
|
198
276
|
gl.disable(gl.BLEND);
|
|
199
|
-
gl.useProgram(
|
|
200
|
-
gl.bindTexture(gl.TEXTURE_2D, pageTexture); gl.bindVertexArray(fullScreen);
|
|
201
|
-
gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
|
|
277
|
+
gl.useProgram(blitProgram.p); bind(0, background); gl.bindVertexArray(fullScreen); gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
|
|
202
278
|
gl.enable(gl.BLEND);
|
|
203
|
-
|
|
204
|
-
|
|
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);
|
|
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); }
|
|
287
|
+
if (effects.length) checkGpu('A window effect');
|
|
205
288
|
},
|
|
206
289
|
};
|
|
207
290
|
}
|
|
208
291
|
|
|
209
|
-
/**
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
ctx.
|
|
220
|
-
const path = new Path2D(ARROW_PATH);
|
|
221
|
-
ctx.fillStyle = cursor.color; ctx.fill(path);
|
|
222
|
-
ctx.shadowColor = 'transparent';
|
|
223
|
-
ctx.lineJoin = 'round'; ctx.lineWidth = 1.7; ctx.strokeStyle = '#171717'; ctx.stroke(path);
|
|
292
|
+
/**
|
|
293
|
+
* 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.
|
|
296
|
+
*/
|
|
297
|
+
async function loadChrome(item, width, url) {
|
|
298
|
+
let height, paint;
|
|
299
|
+
if (item.kind === 'image') {
|
|
300
|
+
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);
|
|
224
303
|
} else {
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
ctx.
|
|
228
|
-
ctx.lineWidth = 1.5; ctx.strokeStyle = '#171717'; ctx.beginPath(); ctx.arc(width / 2, height / 2, width / 2 - 0.75, 0, 2 * Math.PI); ctx.stroke();
|
|
304
|
+
const module = await loadModule(item), files = await loadFiles(item), params = paramsOf(item);
|
|
305
|
+
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 });
|
|
229
307
|
}
|
|
230
|
-
|
|
231
|
-
|
|
308
|
+
return {
|
|
309
|
+
height,
|
|
310
|
+
canvas(scale, radius) {
|
|
311
|
+
const ctx = canvas2d(width * scale, height * scale);
|
|
312
|
+
ctx.scale(scale, scale);
|
|
313
|
+
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); }
|
|
315
|
+
return ctx.canvas;
|
|
316
|
+
},
|
|
317
|
+
};
|
|
232
318
|
}
|
|
233
319
|
|
|
234
|
-
/**
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
320
|
+
/**
|
|
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.
|
|
326
|
+
*/
|
|
327
|
+
async function loadCursor(item) {
|
|
328
|
+
let boxes, paint;
|
|
329
|
+
if (item.kind === 'image') {
|
|
330
|
+
const image = await loadImage(item, item.url);
|
|
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);
|
|
333
|
+
} else {
|
|
334
|
+
const module = await loadModule(item), files = await loadFiles(item), params = paramsOf(item);
|
|
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 });
|
|
338
|
+
}
|
|
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
|
+
}));
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
/**
|
|
360
|
+
* A click effect: drawing code exporting `reach` (CSS px it may draw from the click, or a function of
|
|
361
|
+
* its parameters) and `draw(ctx, { progress, params, files, cursor })` with the origin at the click,
|
|
362
|
+
* or an image that fades out over the effect.
|
|
363
|
+
*/
|
|
364
|
+
async function loadClickEffect(item, cursor) {
|
|
365
|
+
if (item.kind === 'image') {
|
|
366
|
+
const image = await loadImage(item, item.url), w = item.size ?? (image.naturalWidth || 48), h = w * (image.naturalHeight / image.naturalWidth || 1);
|
|
367
|
+
return { reach: Math.max(w, h) / 2, paint: (ctx, progress) => { ctx.globalAlpha = 1 - progress; ctx.drawImage(image, -w / 2, -h / 2, w, h); } };
|
|
256
368
|
}
|
|
257
|
-
|
|
369
|
+
const module = await loadModule(item), files = await loadFiles(item), params = paramsOf(item);
|
|
370
|
+
const reach = item.reach ?? (typeof module.reach === 'function' ? module.reach(params) : module.reach) ?? 64;
|
|
371
|
+
return { reach, paint: (ctx, progress) => { try { module.draw(ctx, { progress, params, files, cursor }); } catch (error) { throw fail(item, error); } } };
|
|
372
|
+
}
|
|
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();
|
|
258
425
|
}
|
|
259
426
|
|
|
260
|
-
/** The
|
|
261
|
-
function
|
|
262
|
-
if (frame.background === 'blur') return null;
|
|
263
|
-
if (frame.background !== 'auto') return BACKGROUNDS[frame.background];
|
|
427
|
+
/** The page's brand color from the Source's first frame. */
|
|
428
|
+
function brandOf(firstFrame) {
|
|
264
429
|
const ctx = new OffscreenCanvas(96, 60).getContext('2d', { willReadFrequently: true });
|
|
265
430
|
ctx.drawImage(firstFrame, 0, 0, 96, 60);
|
|
266
|
-
|
|
267
|
-
return hue === null ? BACKGROUNDS.aurora : autoBackground(hue);
|
|
431
|
+
return brandColor(ctx.getImageData(0, 0, 96, 60).data);
|
|
268
432
|
}
|
|
269
433
|
|
|
434
|
+
/** Smallest H.264 High level whose frame-size and macroblock-rate limits fit. */
|
|
435
|
+
export function avcCodec(width, height, fps) {
|
|
436
|
+
const frame = Math.ceil(width / 16) * Math.ceil(height / 16), rate = frame * fps;
|
|
437
|
+
const levels = [[42, 8704, 522240], [50, 22080, 589824], [51, 36864, 983040], [52, 36864, 2073600], [60, 139264, 4177920], [61, 139264, 8355840], [62, 139264, 16711680]];
|
|
438
|
+
const [level] = levels.find(([, maxFrame, maxRate]) => frame <= maxFrame && rate <= maxRate) ?? levels.at(-1);
|
|
439
|
+
return `avc1.6400${level.toString(16).toUpperCase().padStart(2, '0')}`;
|
|
440
|
+
}
|
|
441
|
+
|
|
442
|
+
/** Decodes a track with bounded look-ahead so memory stays flat on long Takes. */
|
|
443
|
+
function frameReader(track, decoderConfig) {
|
|
444
|
+
const ready = [], waiting = [];
|
|
445
|
+
let failure = null, submitted = 0, decoded = 0, ended = false;
|
|
446
|
+
const wake = () => waiting.splice(0).forEach(resolve => resolve());
|
|
447
|
+
const decoder = new VideoDecoder({ output: frame => { decoded++; ready.push(frame); wake(); }, error: error => { failure = error; wake(); } });
|
|
448
|
+
decoder.configure(decoderConfig);
|
|
449
|
+
const packets = new MB.EncodedPacketSink(track).packets();
|
|
450
|
+
return {
|
|
451
|
+
stats: () => ({ submitted, decoded }),
|
|
452
|
+
async next() {
|
|
453
|
+
while (!ready.length) {
|
|
454
|
+
if (failure) throw failure;
|
|
455
|
+
if (ended) return null;
|
|
456
|
+
if (submitted - decoded >= 6) { await new Promise(resolve => waiting.push(resolve)); continue; }
|
|
457
|
+
const packet = await packets.next();
|
|
458
|
+
if (packet.done) { await decoder.flush(); ended = true; continue; }
|
|
459
|
+
decoder.decode(packet.value.toEncodedVideoChunk());
|
|
460
|
+
submitted++;
|
|
461
|
+
}
|
|
462
|
+
return ready.shift();
|
|
463
|
+
},
|
|
464
|
+
close() { ready.splice(0).forEach(frame => frame.close()); if (decoder.state !== 'closed') decoder.close(); },
|
|
465
|
+
};
|
|
466
|
+
}
|
|
467
|
+
|
|
468
|
+
|
|
270
469
|
/** Prefers constant-quality hardware encoding; software encoders only offer a bitrate. */
|
|
271
470
|
async function encoderConfig(width, height, fps, quality) {
|
|
272
471
|
const base = { codec: avcCodec(width, height, fps), width, height, framerate: fps, latencyMode: 'quality', avc: { format: 'avc' } };
|
|
@@ -278,42 +477,68 @@ async function encoderConfig(width, height, fps, quality) {
|
|
|
278
477
|
}
|
|
279
478
|
|
|
280
479
|
/**
|
|
281
|
-
|
|
282
|
-
|
|
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.
|
|
283
484
|
*/
|
|
284
|
-
function createScene(edit, viewport, { pointer, events }, firstFrame, sourceWidth, sourceHeight) {
|
|
285
|
-
const { camera, cursor, clickEffect, frame } = edit;
|
|
286
|
-
const
|
|
287
|
-
const
|
|
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;
|
|
488
|
+
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 ?? []);
|
|
492
|
+
await compositor.loadEffects(frame.effects ?? []);
|
|
288
493
|
// Page CSS pixels → stage pixels; sprites are rasterized for the closest zoom and mipmapped below it.
|
|
289
494
|
const at = (x, y) => [stage.page.x + x * stage.scale, stage.page.y + y * stage.scale];
|
|
290
495
|
const sharpest = stage.scale * camera.maxZoom * 2;
|
|
291
|
-
const
|
|
292
|
-
const
|
|
293
|
-
const
|
|
294
|
-
const
|
|
496
|
+
const chromeTexture = chrome ? compositor.sprite(chrome.canvas(sharpest, stage.radius / stage.scale)) : null;
|
|
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);
|
|
500
|
+
const effect = clickEffect ? await loadClickEffect(clickEffect, cursor ? Object.fromEntries(Object.entries(cursor).filter(([key]) => !['ref', 'kind', 'url', 'files'].includes(key))) : {}) : null;
|
|
295
501
|
const pressList = presses(events);
|
|
296
|
-
const
|
|
297
|
-
|
|
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;
|
|
298
506
|
return {
|
|
299
|
-
stage, compositor,
|
|
300
|
-
/**
|
|
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
|
+
*/
|
|
301
512
|
draw(t, crop) {
|
|
302
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;
|
|
303
521
|
compositor.frame(view.x, view.y, view.zoom, draw => {
|
|
304
522
|
if (chromeTexture) draw(chromeTexture, [stage.window.x, stage.window.y, stage.window.w, stage.chrome]);
|
|
305
|
-
for (const
|
|
306
|
-
// Each
|
|
307
|
-
const scale = stage.scale * view.zoom,
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
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]);
|
|
313
536
|
}
|
|
314
|
-
|
|
315
|
-
if (
|
|
316
|
-
|
|
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 };
|
|
317
542
|
},
|
|
318
543
|
};
|
|
319
544
|
}
|
|
@@ -326,17 +551,36 @@ const uploadStream = url => new WritableStream({
|
|
|
326
551
|
},
|
|
327
552
|
});
|
|
328
553
|
|
|
329
|
-
window.cuetakeRender = async ({ sourceUrl, finalUrl, duration, viewport, pointer, events, edit }) => {
|
|
554
|
+
window.cuetakeRender = async ({ sourceUrl, finalUrl, duration, viewport, pointer, shapes, events, edit, narration }) => {
|
|
330
555
|
const { camera } = edit, { quality, fps } = edit.output;
|
|
331
|
-
const { width, height } =
|
|
556
|
+
const { width, height } = outputSize(edit);
|
|
332
557
|
const started = performance.now();
|
|
333
558
|
const input = new MB.Input({ formats: MB.ALL_FORMATS, source: new MB.UrlSource(sourceUrl) });
|
|
334
559
|
const track = await input.getPrimaryVideoTrack();
|
|
335
560
|
const reader = frameReader(track, await track.getDecoderConfig());
|
|
336
|
-
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);
|
|
337
563
|
const output = new MB.Output({ format: new MB.Mp4OutputFormat({ fastStart: 'reserve' }), target: new MB.StreamTarget(uploadStream(finalUrl), { chunked: true }) });
|
|
338
564
|
const packets = new MB.EncodedVideoPacketSource('avc');
|
|
339
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
|
+
};
|
|
340
584
|
await output.start();
|
|
341
585
|
const { config, quantizer } = await encoderConfig(width, height, fps, quality);
|
|
342
586
|
let failure = null, muxed = Promise.resolve();
|
|
@@ -354,7 +598,8 @@ window.cuetakeRender = async ({ sourceUrl, finalUrl, duration, viewport, pointer
|
|
|
354
598
|
|
|
355
599
|
let current = await reader.next(), next = await reader.next(), uploaded = null;
|
|
356
600
|
if (!current) throw new Error('Source has no video frames');
|
|
357
|
-
const
|
|
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;
|
|
358
603
|
const cameraPath = cameraTrack({ targets: camera.targets, viewport, camera, duration, fps, pointerAt: t => pointerAt(pointer, t) });
|
|
359
604
|
const origin = current.timestamp;
|
|
360
605
|
try {
|
|
@@ -364,7 +609,10 @@ window.cuetakeRender = async ({ sourceUrl, finalUrl, duration, viewport, pointer
|
|
|
364
609
|
const due = origin + Math.round(i * 1e6 / fps);
|
|
365
610
|
while (next && next.timestamp <= due) { current.close(); current = next; next = await reader.next(); }
|
|
366
611
|
if (uploaded !== current) { compositor.upload(current); uploaded = current; }
|
|
367
|
-
|
|
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];
|
|
368
616
|
const videoFrame = new VideoFrame(compositor.canvas, { timestamp: Math.round(i * 1e6 / fps), duration: Math.round(1e6 / fps) });
|
|
369
617
|
encoder.encode(videoFrame, { keyFrame: i % (fps * 2) === 0, ...(quantizer ? { avc: { quantizer } } : {}) });
|
|
370
618
|
videoFrame.close();
|
|
@@ -373,6 +621,7 @@ window.cuetakeRender = async ({ sourceUrl, finalUrl, duration, viewport, pointer
|
|
|
373
621
|
await encoder.flush();
|
|
374
622
|
await muxed;
|
|
375
623
|
if (failure) throw failure;
|
|
624
|
+
if (audio) await feedAudio(Infinity);
|
|
376
625
|
await output.finalize();
|
|
377
626
|
} finally {
|
|
378
627
|
current?.close(); next?.close(); reader.close();
|
|
@@ -382,11 +631,38 @@ window.cuetakeRender = async ({ sourceUrl, finalUrl, duration, viewport, pointer
|
|
|
382
631
|
width, height, frames: frameCount, sourceFrames: reader.stats().decoded, codec: config.codec,
|
|
383
632
|
rateControl: quantizer ? `quantizer ${quantizer}` : `variable ${config.bitrate} bps`, gpu: compositor.gpu,
|
|
384
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
|
+
}),
|
|
385
642
|
};
|
|
386
643
|
};
|
|
387
644
|
|
|
388
|
-
/**
|
|
389
|
-
|
|
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 = []) => {
|
|
390
666
|
const input = new MB.Input({ formats: MB.ALL_FORMATS, source: new MB.UrlSource(url) });
|
|
391
667
|
const track = await input.getPrimaryVideoTrack();
|
|
392
668
|
const stats = await track.computePacketStats();
|
|
@@ -394,17 +670,31 @@ window.cuetakeInspect = async url => {
|
|
|
394
670
|
let frames = 0;
|
|
395
671
|
try { for (let frame; (frame = await reader.next());) { frames++; frame.close(); } }
|
|
396
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 }))));
|
|
397
680
|
return {
|
|
398
681
|
codec: await track.getCodecParameterString(), width: track.displayWidth, height: track.displayHeight,
|
|
399
|
-
duration: await
|
|
682
|
+
duration: await track.computeDuration(), fps: +stats.averagePacketRate.toFixed(3), packets: stats.packetCount, decodedFrames: frames,
|
|
683
|
+
audio, lines: measured,
|
|
400
684
|
};
|
|
401
685
|
};
|
|
402
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
|
+
|
|
403
693
|
/**
|
|
404
694
|
* A Preview as a base64 PNG: each tile's Edit composed by the same scene as Render, over the Source at
|
|
405
695
|
* `at` seconds with the Final's camera, or (`at` null) over the last moment with the camera wide.
|
|
406
696
|
*/
|
|
407
|
-
window.cuetakePreview = async ({ sourceUrl, duration, viewport, pointer, events, tiles, at }) => {
|
|
697
|
+
window.cuetakePreview = async ({ sourceUrl, duration, viewport, pointer, shapes, events, tiles, at, narration }) => {
|
|
408
698
|
const input = new MB.Input({ formats: MB.ALL_FORMATS, source: new MB.UrlSource(sourceUrl) });
|
|
409
699
|
const track = await input.getPrimaryVideoTrack();
|
|
410
700
|
const sink = new MB.VideoSampleSink(track), origin = await track.getFirstTimestamp();
|
|
@@ -413,13 +703,14 @@ window.cuetakePreview = async ({ sourceUrl, duration, viewport, pointer, events,
|
|
|
413
703
|
if (!firstSample || !sample) throw new Error('Source has no video frames');
|
|
414
704
|
const firstFrame = firstSample.toVideoFrame(), frame = sample.toVideoFrame();
|
|
415
705
|
try {
|
|
416
|
-
const sheet = previewSheet(tiles.map(({ edit }) =>
|
|
706
|
+
const sheet = previewSheet(tiles.map(({ edit }) => outputSize(edit)));
|
|
417
707
|
const ctx = new OffscreenCanvas(sheet.width, sheet.height).getContext('2d');
|
|
418
708
|
ctx.fillStyle = '#111114'; ctx.fillRect(0, 0, sheet.width, sheet.height);
|
|
419
709
|
ctx.imageSmoothingQuality = 'high';
|
|
420
710
|
ctx.font = '600 22px system-ui, -apple-system, sans-serif'; ctx.textBaseline = 'middle'; ctx.fillStyle = '#e5e7eb';
|
|
421
|
-
|
|
422
|
-
const
|
|
711
|
+
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);
|
|
423
714
|
let crop = { x: 0, y: 0, w: viewport.width, h: viewport.height };
|
|
424
715
|
if (at !== null) {
|
|
425
716
|
const { fps } = edit.output, path = cameraTrack({ targets: edit.camera.targets, viewport, camera: edit.camera, duration, fps, pointerAt: s => pointerAt(pointer, s) });
|
|
@@ -432,7 +723,7 @@ window.cuetakePreview = async ({ sourceUrl, duration, viewport, pointer, events,
|
|
|
432
723
|
ctx.drawImage(scene.compositor.canvas, tile.x, tile.y, tile.w, tile.h);
|
|
433
724
|
if (tile.label) ctx.fillText(name, tile.label.x, tile.label.y);
|
|
434
725
|
scene.compositor.dispose();
|
|
435
|
-
}
|
|
726
|
+
}
|
|
436
727
|
return await pngBase64(ctx.canvas);
|
|
437
728
|
} finally { firstFrame.close(); frame.close(); firstSample.close(); sample.close(); }
|
|
438
729
|
};
|