cuetake 0.0.0-stage → 0.2.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.
@@ -0,0 +1,454 @@
1
+ /**
2
+ * Runs inside Chromium (see render.js). Source WebM → VideoDecoder → one WebGL2 pass per output
3
+ * frame → VideoEncoder (H.264) → MP4, streamed back to Node in chunks.
4
+ *
5
+ * Spaces: camera crops are CSS pixels of the viewport; the Source texture is sampled by UV only;
6
+ * "stage" is the Final's pixels at camera zoom 1, laid out by stage.js.
7
+ */
8
+ import * as MB from '/mediabunny.js';
9
+ import { cameraTrack } from '/camera.js';
10
+ import { pointerAt, presses, sparksAt, cursorGeometry, drawSpark, ARROW_PATH } from '/cursor.js';
11
+ import { layout, cameraView, previewSheet, BACKGROUNDS, autoBackground, brandHue } from '/stage.js';
12
+
13
+ const VERTEX = `#version 300 es
14
+ in vec2 p; void main() { gl_Position = vec4(p, 0, 1); }`;
15
+ const FRAGMENT = `#version 300 es
16
+ precision highp float;
17
+ uniform vec2 uRes; // output size
18
+ uniform vec3 uCam; // stage point at the output center, and zoom
19
+ uniform vec4 uPage; // page rectangle in stage pixels
20
+ uniform vec4 uWindow; // window rectangle (chrome + page) in stage pixels
21
+ uniform float uRadius; // window corner radius, stage pixels
22
+ uniform float uFramed; // 0: page fills the stage
23
+ uniform float uShadow; // drop shadow strength
24
+ uniform float uBlur; // 1: background is the blurred page
25
+ uniform vec3 uBase; // mesh background: base color under up to four blobs
26
+ uniform vec4 uBlobs[4]; // x, y, radius as stage fractions
27
+ uniform vec3 uBlobColors[4];
28
+ uniform int uBlobCount;
29
+ uniform sampler2D uSource;
30
+ out vec4 color;
31
+
32
+ float roundedBox(vec2 p, vec4 rect, float r) {
33
+ vec2 q = abs(p - rect.xy - rect.zw * 0.5) - (rect.zw * 0.5 - r);
34
+ return length(max(q, 0.0)) + min(max(q.x, q.y), 0.0) - r;
35
+ }
36
+ float noise(vec2 p) { return fract(sin(dot(p, vec2(12.9898, 78.233))) * 43758.5453); }
37
+
38
+ void main() {
39
+ vec2 pixel = vec2(gl_FragCoord.x, uRes.y - gl_FragCoord.y);
40
+ vec2 stage = (pixel - uRes * 0.5) / uCam.z + uCam.xy;
41
+ vec2 pageUv = clamp((stage - uPage.xy) / uPage.zw, 0.0, 1.0);
42
+ if (uFramed < 0.5) { color = vec4(texture(uSource, pageUv).rgb, 1.0); return; }
43
+
44
+ vec3 c;
45
+ if (uBlur > 0.5) {
46
+ // Cover the stage with the page, then read a coarse mip level as a cheap wide blur.
47
+ float r = (uRes.x / uRes.y) / (uPage.z / uPage.w);
48
+ vec2 uv = 0.5 + (stage / uRes - 0.5) * vec2(min(1.0, r), min(1.0, 1.0 / r)) / 1.2;
49
+ c = textureLod(uSource, uv, 6.0).rgb * 0.8;
50
+ } else {
51
+ c = uBase;
52
+ for (int i = 3; i >= 0; i--) {
53
+ if (i >= uBlobCount) continue;
54
+ float d = length((stage / uRes - uBlobs[i].xy) / uBlobs[i].z);
55
+ c = mix(c, uBlobColors[i], 1.0 - smoothstep(0.0, 0.7, d));
56
+ }
57
+ }
58
+ // Grain dithers the gradients so H.264 does not band them.
59
+ c += (noise(pixel) - 0.5) * 0.035;
60
+
61
+ float unit = min(uRes.x, uRes.y) / 1080.0;
62
+ float shadow = uShadow * (1.0 - smoothstep(-60.0 * unit, 60.0 * unit, roundedBox(stage - vec2(0.0, 24.0 * unit), uWindow, uRadius)));
63
+ c = mix(c, vec3(0.0), shadow * 0.55);
64
+
65
+ float edge = roundedBox(stage, uWindow, uRadius) * uCam.z; // output pixels from the window edge
66
+ float inside = clamp(0.5 - edge, 0.0, 1.0);
67
+ if (stage.y >= uPage.y) c = mix(c, texture(uSource, pageUv).rgb, inside);
68
+ c = mix(c, vec3(1.0), 0.18 * (1.0 - smoothstep(0.0, 1.0, abs(edge)))); // hairline rim
69
+ color = vec4(c, 1.0);
70
+ }`;
71
+ // Sprites (cursor, sparks) are premultiplied textures placed by a stage rectangle under the same camera.
72
+ const SPRITE_VERTEX = `#version 300 es
73
+ in vec2 p;
74
+ uniform vec2 uRes; uniform vec3 uCam; uniform vec4 uRect;
75
+ out vec2 uv;
76
+ void main() {
77
+ vec2 pixel = (uRect.xy + p * uRect.zw - uCam.xy) * uCam.z + uRes * 0.5;
78
+ gl_Position = vec4(pixel.x / uRes.x * 2.0 - 1.0, 1.0 - pixel.y / uRes.y * 2.0, 0, 1);
79
+ uv = p;
80
+ }`;
81
+ const SPRITE_FRAGMENT = `#version 300 es
82
+ precision highp float;
83
+ uniform sampler2D uSprite;
84
+ in vec2 uv; out vec4 color;
85
+ void main() { color = texture(uSprite, uv); }`;
86
+
87
+ /** Smallest H.264 High level whose frame-size and macroblock-rate limits fit. */
88
+ export function avcCodec(width, height, fps) {
89
+ const frame = Math.ceil(width / 16) * Math.ceil(height / 16), rate = frame * fps;
90
+ const levels = [[42, 8704, 522240], [50, 22080, 589824], [51, 36864, 983040], [52, 36864, 2073600], [60, 139264, 4177920], [61, 139264, 8355840], [62, 139264, 16711680]];
91
+ const [level] = levels.find(([, maxFrame, maxRate]) => frame <= maxFrame && rate <= maxRate) ?? levels.at(-1);
92
+ return `avc1.6400${level.toString(16).toUpperCase().padStart(2, '0')}`;
93
+ }
94
+
95
+ /** Decodes a track with bounded look-ahead so memory stays flat on long Takes. */
96
+ function frameReader(track, decoderConfig) {
97
+ const ready = [], waiting = [];
98
+ let failure = null, submitted = 0, decoded = 0, ended = false;
99
+ const wake = () => waiting.splice(0).forEach(resolve => resolve());
100
+ const decoder = new VideoDecoder({ output: frame => { decoded++; ready.push(frame); wake(); }, error: error => { failure = error; wake(); } });
101
+ decoder.configure(decoderConfig);
102
+ const packets = new MB.EncodedPacketSink(track).packets();
103
+ return {
104
+ stats: () => ({ submitted, decoded }),
105
+ async next() {
106
+ while (!ready.length) {
107
+ if (failure) throw failure;
108
+ if (ended) return null;
109
+ if (submitted - decoded >= 6) { await new Promise(resolve => waiting.push(resolve)); continue; }
110
+ const packet = await packets.next();
111
+ if (packet.done) { await decoder.flush(); ended = true; continue; }
112
+ decoder.decode(packet.value.toEncodedVideoChunk());
113
+ submitted++;
114
+ }
115
+ return ready.shift();
116
+ },
117
+ close() { ready.splice(0).forEach(frame => frame.close()); if (decoder.state !== 'closed') decoder.close(); },
118
+ };
119
+ }
120
+
121
+ /** `backdrop` is the static part of the frame: whether there is one, its background and shadow. */
122
+ function createCompositor(stage, backdrop, sourceWidth, sourceHeight) {
123
+ const { width, height } = stage;
124
+ const canvas = new OffscreenCanvas(width, height);
125
+ const gl = canvas.getContext('webgl2', { alpha: false, antialias: false, depth: false });
126
+ const shader = (type, text) => {
127
+ 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));
129
+ return s;
130
+ };
131
+ const program = (vertex, fragment) => {
132
+ const p = gl.createProgram();
133
+ gl.attachShader(p, shader(gl.VERTEX_SHADER, vertex)); gl.attachShader(p, shader(gl.FRAGMENT_SHADER, fragment));
134
+ gl.bindAttribLocation(p, 0, 'p');
135
+ gl.linkProgram(p);
136
+ if (!gl.getProgramParameter(p, gl.LINK_STATUS)) throw new Error(gl.getProgramInfoLog(p));
137
+ gl.useProgram(p);
138
+ gl.uniform2f(gl.getUniformLocation(p, 'uRes'), width, height);
139
+ return { p, camera: gl.getUniformLocation(p, 'uCam'), uniform: name => gl.getUniformLocation(p, name) };
140
+ };
141
+ const quad = corners => {
142
+ const vao = gl.createVertexArray(); gl.bindVertexArray(vao);
143
+ gl.bindBuffer(gl.ARRAY_BUFFER, gl.createBuffer());
144
+ gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(corners), gl.STATIC_DRAW);
145
+ gl.enableVertexAttribArray(0); gl.vertexAttribPointer(0, 2, gl.FLOAT, false, 0, 0);
146
+ return vao;
147
+ };
148
+ const texture = (filter = gl.LINEAR_MIPMAP_LINEAR) => {
149
+ const t = gl.createTexture(); gl.bindTexture(gl.TEXTURE_2D, t);
150
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filter);
151
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
152
+ 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
+ return t;
154
+ };
155
+ const pageProgram = program(VERTEX, FRAGMENT);
156
+ const set = (name, ...v) => gl[`uniform${v.length}f`](pageProgram.uniform(name), ...v);
157
+ set('uPage', stage.page.x, stage.page.y, stage.page.w, stage.page.h);
158
+ set('uWindow', stage.window.x, stage.window.y, stage.window.w, stage.window.h);
159
+ set('uRadius', stage.radius); set('uFramed', backdrop.framed ? 1 : 0); set('uShadow', backdrop.shadow ? 1 : 0); set('uBlur', backdrop.background ? 0 : 1);
160
+ if (backdrop.background) {
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);
174
+ gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, true);
175
+ gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
176
+ gl.viewport(0, 0, width, height);
177
+ const info = gl.getExtension('WEBGL_debug_renderer_info');
178
+ return {
179
+ canvas,
180
+ gpu: info ? gl.getParameter(info.UNMASKED_RENDERER_WEBGL) : 'unknown',
181
+ /** Frees the GPU context; a Preview makes one compositor per tile. */
182
+ dispose() { gl.getExtension('WEBGL_lose_context')?.loseContext(); },
183
+ upload(frame) {
184
+ gl.bindTexture(gl.TEXTURE_2D, pageTexture);
185
+ gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, gl.RGBA, gl.UNSIGNED_BYTE, frame);
186
+ gl.generateMipmap(gl.TEXTURE_2D);
187
+ },
188
+ /** A sprite texture from a 2D canvas; pass `into` to reuse one. */
189
+ sprite(image, into, mipmaps = true) {
190
+ const t = into ?? texture(mipmaps ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
191
+ gl.bindTexture(gl.TEXTURE_2D, t);
192
+ gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, image);
193
+ if (mipmaps) gl.generateMipmap(gl.TEXTURE_2D);
194
+ return t;
195
+ },
196
+ /** Draws the page under the camera; `draw(texture, rect)` in `overlay` then places sprites in stage pixels. */
197
+ frame(x, y, zoom, overlay) {
198
+ gl.disable(gl.BLEND);
199
+ gl.useProgram(pageProgram.p); gl.uniform3f(pageProgram.camera, x, y, zoom);
200
+ gl.bindTexture(gl.TEXTURE_2D, pageTexture); gl.bindVertexArray(fullScreen);
201
+ gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
202
+ gl.enable(gl.BLEND);
203
+ gl.useProgram(spriteProgram.p); gl.uniform3f(spriteProgram.camera, x, y, zoom); gl.bindVertexArray(unit);
204
+ overlay((t, rect) => { gl.bindTexture(gl.TEXTURE_2D, t); gl.uniform4f(spriteRect, ...rect); gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4); });
205
+ },
206
+ };
207
+ }
208
+
209
+ /** The cursor drawn once at `scale` device pixels per CSS pixel, with room for its shadow. */
210
+ function cursorSprite(cursor, scale) {
211
+ const { width, height } = cursorGeometry(cursor);
212
+ const margin = 4;
213
+ const canvas = new OffscreenCanvas(Math.ceil((width + 2 * margin) * scale), Math.ceil((height + 2 * margin) * scale));
214
+ const ctx = canvas.getContext('2d');
215
+ ctx.scale(scale, scale);
216
+ ctx.translate(margin, margin);
217
+ ctx.shadowColor = '#00000055'; ctx.shadowBlur = 2 * scale; ctx.shadowOffsetY = 1 * scale;
218
+ if (cursor.style === 'arrow') {
219
+ ctx.scale(width / 28, height / 36);
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);
224
+ } else {
225
+ ctx.beginPath(); ctx.arc(width / 2, height / 2, width / 2, 0, 2 * Math.PI);
226
+ ctx.fillStyle = cursor.color; ctx.fill();
227
+ ctx.shadowColor = 'transparent';
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();
229
+ }
230
+ // Size in CSS pixels, including the shadow margin.
231
+ return { canvas, margin, width: canvas.width / scale, height: canvas.height / scale };
232
+ }
233
+
234
+ /** The window's chrome bar at `scale` pixels per CSS pixel: traffic lights, and for `browser` an address field. */
235
+ function chromeSprite(frame, viewportWidth, heightCss, radiusCss, scale) {
236
+ const canvas = new OffscreenCanvas(Math.ceil(viewportWidth * scale), Math.ceil(heightCss * scale));
237
+ const ctx = canvas.getContext('2d');
238
+ ctx.scale(scale, scale);
239
+ ctx.beginPath(); ctx.roundRect(0, 0, viewportWidth, heightCss + radiusCss, [radiusCss, radiusCss, 0, 0]);
240
+ ctx.fillStyle = frame.window === 'browser' ? '#f3f3f5' : '#ececef'; ctx.fill();
241
+ ctx.fillStyle = '#d4d4d8'; ctx.fillRect(0, heightCss - 1, viewportWidth, 1);
242
+ ['#ff5f57', '#febc2e', '#28c840'].forEach((light, i) => {
243
+ ctx.beginPath(); ctx.arc(20 + i * 20, heightCss / 2, 6, 0, 2 * Math.PI);
244
+ ctx.fillStyle = light; ctx.fill(); ctx.strokeStyle = '#0000001f'; ctx.lineWidth = 0.5; ctx.stroke();
245
+ });
246
+ if (frame.window === 'browser') {
247
+ const w = 420, h = 28, x = (viewportWidth - w) / 2, y = (heightCss - h) / 2;
248
+ ctx.beginPath(); ctx.roundRect(x, y, w, h, h / 2);
249
+ ctx.fillStyle = '#ffffff'; ctx.fill(); ctx.strokeStyle = '#e4e4e7'; ctx.lineWidth = 0.8; ctx.stroke();
250
+ ctx.font = '13px system-ui, -apple-system, sans-serif'; ctx.textBaseline = 'middle';
251
+ const text = frame.url ?? '', textWidth = ctx.measureText(text).width, left = viewportWidth / 2 - (textWidth + 16) / 2;
252
+ ctx.fillStyle = '#71717a'; // padlock
253
+ ctx.beginPath(); ctx.roundRect(left, y + 13, 9, 7, 1.5); ctx.fill();
254
+ ctx.strokeStyle = '#71717a'; ctx.lineWidth = 1.3; ctx.beginPath(); ctx.arc(left + 4.5, y + 13, 2.8, Math.PI, 0); ctx.stroke();
255
+ ctx.fillStyle = '#52525b'; ctx.fillText(text, left + 16, heightCss / 2 + 0.5);
256
+ }
257
+ return canvas;
258
+ }
259
+
260
+ /** The background: a mesh preset, a mesh around the page's brand hue, or null for the blurred page. */
261
+ function backgroundFor(frame, firstFrame) {
262
+ if (frame.background === 'blur') return null;
263
+ if (frame.background !== 'auto') return BACKGROUNDS[frame.background];
264
+ const ctx = new OffscreenCanvas(96, 60).getContext('2d', { willReadFrequently: true });
265
+ ctx.drawImage(firstFrame, 0, 0, 96, 60);
266
+ const hue = brandHue(ctx.getImageData(0, 0, 96, 60).data);
267
+ return hue === null ? BACKGROUNDS.aurora : autoBackground(hue);
268
+ }
269
+
270
+ /** Prefers constant-quality hardware encoding; software encoders only offer a bitrate. */
271
+ async function encoderConfig(width, height, fps, quality) {
272
+ const base = { codec: avcCodec(width, height, fps), width, height, framerate: fps, latencyMode: 'quality', avc: { format: 'avc' } };
273
+ const quantizer = { ...base, hardwareAcceleration: 'prefer-hardware', bitrateMode: 'quantizer' };
274
+ if ((await VideoEncoder.isConfigSupported(quantizer)).supported) return { config: quantizer, quantizer: quality };
275
+ const bitrate = { ...base, bitrateMode: 'variable', bitrate: Math.round(width * height * fps * 0.07) };
276
+ if ((await VideoEncoder.isConfigSupported(bitrate)).supported) return { config: bitrate };
277
+ throw new Error(`No H.264 encoder supports ${width}×${height} at ${fps} fps`);
278
+ }
279
+
280
+ /**
281
+ * Everything Render draws for one Edit: the stage under the camera, then the chrome, click sparks and
282
+ * cursor. `firstFrame` is the Source's first frame, which picks the `auto` background.
283
+ */
284
+ function createScene(edit, viewport, { pointer, events }, firstFrame, sourceWidth, sourceHeight) {
285
+ const { camera, cursor, clickEffect, frame } = edit;
286
+ const stage = layout(edit, viewport);
287
+ const compositor = createCompositor(stage, { framed: Boolean(frame), shadow: frame && frame.shadow, background: frame && backgroundFor(frame, firstFrame) }, sourceWidth, sourceHeight);
288
+ // Page CSS pixels → stage pixels; sprites are rasterized for the closest zoom and mipmapped below it.
289
+ const at = (x, y) => [stage.page.x + x * stage.scale, stage.page.y + y * stage.scale];
290
+ const sharpest = stage.scale * camera.maxZoom * 2;
291
+ const geometry = cursorGeometry(cursor);
292
+ const pointerSprite = cursorSprite(cursor, sharpest);
293
+ const pointerTexture = compositor.sprite(pointerSprite.canvas);
294
+ const chromeTexture = stage.chrome ? compositor.sprite(chromeSprite(frame, viewport.width, stage.chrome / stage.scale, stage.radius / stage.scale, sharpest)) : null;
295
+ const pressList = presses(events);
296
+ const sparkReach = clickEffect.radius + clickEffect.length + 8;
297
+ let sparkTexture = null;
298
+ return {
299
+ stage, compositor,
300
+ /** Draws output time `t` with the camera showing `crop`, a viewport rectangle in CSS pixels. */
301
+ draw(t, crop) {
302
+ const view = cameraView(crop, stage, viewport);
303
+ compositor.frame(view.x, view.y, view.zoom, draw => {
304
+ if (chromeTexture) draw(chromeTexture, [stage.window.x, stage.window.y, stage.window.w, stage.chrome]);
305
+ for (const spark of sparksAt(pressList, clickEffect, t)) {
306
+ // Each spark is drawn at its on-screen scale so the thin rays stay crisp.
307
+ const scale = stage.scale * view.zoom, size = Math.ceil(2 * sparkReach * scale);
308
+ const ctx = new OffscreenCanvas(size, size).getContext('2d');
309
+ ctx.scale(scale, scale);
310
+ drawSpark(ctx, sparkReach, sparkReach, spark.progress, clickEffect, cursor.color);
311
+ sparkTexture = compositor.sprite(ctx.canvas, sparkTexture, false);
312
+ draw(sparkTexture, [...at(spark.x - sparkReach, spark.y - sparkReach), 2 * sparkReach * stage.scale, 2 * sparkReach * stage.scale]);
313
+ }
314
+ const point = pointerAt(pointer, t);
315
+ if (point) draw(pointerTexture, [...at(point.x - geometry.hotspot.x - pointerSprite.margin, point.y - geometry.hotspot.y - pointerSprite.margin), pointerSprite.width * stage.scale, pointerSprite.height * stage.scale]);
316
+ });
317
+ },
318
+ };
319
+ }
320
+
321
+ /** A WritableStream that posts each positioned chunk to Node, which writes it into the Final. */
322
+ const uploadStream = url => new WritableStream({
323
+ async write(chunk) {
324
+ const response = await fetch(`${url}?position=${chunk.position}`, { method: 'POST', body: chunk.data });
325
+ if (!response.ok) throw new Error(`Writing the Final failed: ${response.status}`);
326
+ },
327
+ });
328
+
329
+ window.cuetakeRender = async ({ sourceUrl, finalUrl, duration, viewport, pointer, events, edit }) => {
330
+ const { camera } = edit, { quality, fps } = edit.output;
331
+ const { width, height } = layout(edit, viewport);
332
+ const started = performance.now();
333
+ const input = new MB.Input({ formats: MB.ALL_FORMATS, source: new MB.UrlSource(sourceUrl) });
334
+ const track = await input.getPrimaryVideoTrack();
335
+ const reader = frameReader(track, await track.getDecoderConfig());
336
+ const frameCount = Math.round(duration * fps);
337
+ const output = new MB.Output({ format: new MB.Mp4OutputFormat({ fastStart: 'reserve' }), target: new MB.StreamTarget(uploadStream(finalUrl), { chunked: true }) });
338
+ const packets = new MB.EncodedVideoPacketSource('avc');
339
+ output.addVideoTrack(packets, { frameRate: fps, maximumPacketCount: frameCount });
340
+ await output.start();
341
+ const { config, quantizer } = await encoderConfig(width, height, fps, quality);
342
+ let failure = null, muxed = Promise.resolve();
343
+ const encoder = new VideoEncoder({
344
+ output(chunk, meta) {
345
+ // Chromium tags the stream sRGB; the pixels are BT.709, so label them as such.
346
+ const colorSpace = meta?.decoderConfig?.colorSpace;
347
+ if (colorSpace) meta = { ...meta, decoderConfig: { ...meta.decoderConfig, colorSpace: { ...colorSpace, transfer: 'bt709' } } };
348
+ const packet = MB.EncodedPacket.fromEncodedChunk(chunk);
349
+ muxed = muxed.then(() => packets.add(packet, meta)).catch(error => { failure ??= error; });
350
+ },
351
+ error(error) { failure ??= error; },
352
+ });
353
+ encoder.configure(config);
354
+
355
+ let current = await reader.next(), next = await reader.next(), uploaded = null;
356
+ if (!current) throw new Error('Source has no video frames');
357
+ const scene = createScene(edit, viewport, { pointer, events }, current, track.codedWidth, track.codedHeight), { compositor } = scene;
358
+ const cameraPath = cameraTrack({ targets: camera.targets, viewport, camera, duration, fps, pointerAt: t => pointerAt(pointer, t) });
359
+ const origin = current.timestamp;
360
+ try {
361
+ for (let i = 0; i < frameCount; i++) {
362
+ if (failure) throw failure;
363
+ // Sample and hold: show the latest Source frame at or before this output time (VFR → CFR).
364
+ const due = origin + Math.round(i * 1e6 / fps);
365
+ while (next && next.timestamp <= due) { current.close(); current = next; next = await reader.next(); }
366
+ if (uploaded !== current) { compositor.upload(current); uploaded = current; }
367
+ scene.draw(i / fps, cameraPath[i]);
368
+ const videoFrame = new VideoFrame(compositor.canvas, { timestamp: Math.round(i * 1e6 / fps), duration: Math.round(1e6 / fps) });
369
+ encoder.encode(videoFrame, { keyFrame: i % (fps * 2) === 0, ...(quantizer ? { avc: { quantizer } } : {}) });
370
+ videoFrame.close();
371
+ while (encoder.encodeQueueSize > 4) await new Promise(resolve => encoder.addEventListener('dequeue', resolve, { once: true }));
372
+ }
373
+ await encoder.flush();
374
+ await muxed;
375
+ if (failure) throw failure;
376
+ await output.finalize();
377
+ } finally {
378
+ current?.close(); next?.close(); reader.close();
379
+ if (encoder.state !== 'closed') encoder.close();
380
+ }
381
+ return {
382
+ width, height, frames: frameCount, sourceFrames: reader.stats().decoded, codec: config.codec,
383
+ rateControl: quantizer ? `quantizer ${quantizer}` : `variable ${config.bitrate} bps`, gpu: compositor.gpu,
384
+ seconds: +((performance.now() - started) / 1000).toFixed(2),
385
+ };
386
+ };
387
+
388
+ /** Reads a Final's container metadata and decodes every frame. */
389
+ window.cuetakeInspect = async url => {
390
+ const input = new MB.Input({ formats: MB.ALL_FORMATS, source: new MB.UrlSource(url) });
391
+ const track = await input.getPrimaryVideoTrack();
392
+ const stats = await track.computePacketStats();
393
+ const reader = frameReader(track, await track.getDecoderConfig());
394
+ let frames = 0;
395
+ try { for (let frame; (frame = await reader.next());) { frames++; frame.close(); } }
396
+ finally { reader.close(); }
397
+ return {
398
+ codec: await track.getCodecParameterString(), width: track.displayWidth, height: track.displayHeight,
399
+ duration: await input.computeDuration(), fps: +stats.averagePacketRate.toFixed(3), packets: stats.packetCount, decodedFrames: frames,
400
+ };
401
+ };
402
+
403
+ /**
404
+ * A Preview as a base64 PNG: each tile's Edit composed by the same scene as Render, over the Source at
405
+ * `at` seconds with the Final's camera, or (`at` null) over the last moment with the camera wide.
406
+ */
407
+ window.cuetakePreview = async ({ sourceUrl, duration, viewport, pointer, events, tiles, at }) => {
408
+ const input = new MB.Input({ formats: MB.ALL_FORMATS, source: new MB.UrlSource(sourceUrl) });
409
+ const track = await input.getPrimaryVideoTrack();
410
+ const sink = new MB.VideoSampleSink(track), origin = await track.getFirstTimestamp();
411
+ const t = at ?? duration;
412
+ const firstSample = await sink.getSample(origin), sample = await sink.getSample(origin + t);
413
+ if (!firstSample || !sample) throw new Error('Source has no video frames');
414
+ const firstFrame = firstSample.toVideoFrame(), frame = sample.toVideoFrame();
415
+ try {
416
+ const sheet = previewSheet(tiles.map(({ edit }) => layout(edit, viewport)));
417
+ const ctx = new OffscreenCanvas(sheet.width, sheet.height).getContext('2d');
418
+ ctx.fillStyle = '#111114'; ctx.fillRect(0, 0, sheet.width, sheet.height);
419
+ ctx.imageSmoothingQuality = 'high';
420
+ ctx.font = '600 22px system-ui, -apple-system, sans-serif'; ctx.textBaseline = 'middle'; ctx.fillStyle = '#e5e7eb';
421
+ tiles.forEach(({ name, edit }, i) => {
422
+ const scene = createScene(edit, viewport, { pointer, events }, firstFrame, track.codedWidth, track.codedHeight);
423
+ let crop = { x: 0, y: 0, w: viewport.width, h: viewport.height };
424
+ if (at !== null) {
425
+ const { fps } = edit.output, path = cameraTrack({ targets: edit.camera.targets, viewport, camera: edit.camera, duration, fps, pointerAt: s => pointerAt(pointer, s) });
426
+ crop = path[Math.min(Math.round(at * fps), path.length - 1)] ?? crop;
427
+ }
428
+ scene.compositor.upload(frame);
429
+ scene.draw(t, crop);
430
+ // Copy before yielding: the WebGL canvas does not keep its drawing buffer.
431
+ const tile = sheet.tiles[i];
432
+ ctx.drawImage(scene.compositor.canvas, tile.x, tile.y, tile.w, tile.h);
433
+ if (tile.label) ctx.fillText(name, tile.label.x, tile.label.y);
434
+ scene.compositor.dispose();
435
+ });
436
+ return await pngBase64(ctx.canvas);
437
+ } finally { firstFrame.close(); frame.close(); firstSample.close(); sample.close(); }
438
+ };
439
+
440
+ async function pngBase64(canvas) {
441
+ const blob = canvas.convertToBlob ? await canvas.convertToBlob({ type: 'image/png' }) : await new Promise(resolve => canvas.toBlob(resolve, 'image/png'));
442
+ const bytes = new Uint8Array(await blob.arrayBuffer());
443
+ let binary = '';
444
+ for (let i = 0; i < bytes.length; i += 32768) binary += String.fromCharCode(...bytes.subarray(i, i + 32768));
445
+ return btoa(binary);
446
+ }
447
+
448
+ /** One Final frame at `seconds`, as a base64 PNG. */
449
+ window.cuetakeFrame = async (url, seconds) => {
450
+ const input = new MB.Input({ formats: MB.ALL_FORMATS, source: new MB.UrlSource(url) });
451
+ const wrapped = await new MB.CanvasSink(await input.getPrimaryVideoTrack()).getCanvas(seconds);
452
+ if (!wrapped) throw new Error(`No frame at ${seconds} s`);
453
+ return pngBase64(wrapped.canvas);
454
+ };
package/src/render.js ADDED
@@ -0,0 +1,92 @@
1
+ import fs from 'node:fs/promises';
2
+ import { createRequire } from 'node:module';
3
+ import { dirname, join } from 'node:path';
4
+ import { fileURLToPath } from 'node:url';
5
+ import { chromium } from 'playwright';
6
+
7
+ /**
8
+ * Render runs in a headless Chromium page (ADR 0001). Files reach the page through intercepted
9
+ * requests on a private origin, so no port is opened: the Source is served with byte ranges and
10
+ * the Final arrives as positioned chunks written straight to disk.
11
+ */
12
+ const ORIGIN = 'https://render.cuetake.invalid';
13
+ // The bundled build is a single file the page can import; the package's own entry is many modules.
14
+ const mediabunnyBundle = join(dirname(createRequire(import.meta.url).resolve('mediabunny')), 'mediabunny.min.mjs');
15
+ const pageFiles = {
16
+ '/render.html': { body: '<!doctype html><meta charset="utf-8"><script type="module" src="/render-page.js"></script>', type: 'text/html' },
17
+ '/render-page.js': { path: fileURLToPath(new URL('./render-page.js', import.meta.url)), type: 'text/javascript' },
18
+ '/camera.js': { path: fileURLToPath(new URL('./camera.js', import.meta.url)), type: 'text/javascript' },
19
+ '/cursor.js': { path: fileURLToPath(new URL('./cursor.js', import.meta.url)), type: 'text/javascript' },
20
+ '/stage.js': { path: fileURLToPath(new URL('./stage.js', import.meta.url)), type: 'text/javascript' },
21
+ '/mediabunny.js': { path: mediabunnyBundle, type: 'text/javascript' },
22
+ };
23
+
24
+ async function serveRange(route, path) {
25
+ const { size } = await fs.stat(path);
26
+ const match = /bytes=(\d+)-(\d*)/.exec(route.request().headers().range ?? '');
27
+ const start = match ? Number(match[1]) : 0;
28
+ const end = match && match[2] ? Math.min(Number(match[2]), size - 1) : size - 1;
29
+ const handle = await fs.open(path);
30
+ try {
31
+ const body = Buffer.alloc(end - start + 1);
32
+ await handle.read(body, 0, body.length, start);
33
+ await route.fulfill({ status: match ? 206 : 200, body, headers: { 'content-type': 'application/octet-stream', 'accept-ranges': 'bytes', 'content-range': `bytes ${start}-${end}/${size}` } });
34
+ } finally { await handle.close(); }
35
+ }
36
+
37
+ /** Opens the render page with `files` ({ name: path }) readable and `writable` ({ name: handle }) writable. */
38
+ async function withRenderPage({ files = {}, writable = {} }, task) {
39
+ const browser = await chromium.launch({ headless: true, channel: 'chromium' });
40
+ try {
41
+ const page = await browser.newPage();
42
+ const errors = [];
43
+ page.on('pageerror', error => errors.push(error.message));
44
+ await page.route(`${ORIGIN}/**`, async route => {
45
+ const { pathname, searchParams } = new URL(route.request().url());
46
+ const name = pathname.slice('/files/'.length);
47
+ if (route.request().method() === 'POST' && writable[name]) {
48
+ const body = route.request().postDataBuffer();
49
+ await writable[name].write(body, 0, body.length, Number(searchParams.get('position')));
50
+ return route.fulfill({ status: 204 });
51
+ }
52
+ if (files[name]) return serveRange(route, files[name]);
53
+ const file = pageFiles[pathname];
54
+ if (!file) return route.fulfill({ status: 404 });
55
+ return route.fulfill({ body: file.body ?? await fs.readFile(file.path), contentType: file.type });
56
+ });
57
+ await page.goto(`${ORIGIN}/render.html`);
58
+ await page.waitForFunction(() => window.cuetakeRender, null, { timeout: 15_000 }).catch(() => { throw new Error(`Render page failed to load: ${errors.join('; ')}`); });
59
+ return await task(page);
60
+ } finally { await browser.close(); }
61
+ }
62
+
63
+ /** Composes the Final from a Source, Timeline and Edit. */
64
+ export async function renderFinal({ sourcePath, finalPath, timeline, edit }) {
65
+ const handle = await fs.open(finalPath, 'w');
66
+ try {
67
+ return await withRenderPage({ files: { source: sourcePath }, writable: { final: handle } }, page => page.evaluate(options => window.cuetakeRender(options), {
68
+ sourceUrl: `${ORIGIN}/files/source`, finalUrl: `${ORIGIN}/files/final`, duration: timeline.duration,
69
+ viewport: timeline.viewport, pointer: timeline.pointer ?? [], events: timeline.events ?? [], edit,
70
+ }));
71
+ } finally { await handle.close(); }
72
+ }
73
+
74
+ /** A Preview PNG of `tiles` ([{ name, edit }]) at `at` seconds, or at the end with the camera wide. No Final is touched. */
75
+ export async function composePreview({ sourcePath, timeline, tiles, at }) {
76
+ const png = await withRenderPage({ files: { source: sourcePath } }, page => page.evaluate(options => window.cuetakePreview(options), {
77
+ sourceUrl: `${ORIGIN}/files/source`, duration: timeline.duration, viewport: timeline.viewport,
78
+ pointer: timeline.pointer ?? [], events: timeline.events ?? [], tiles, at: at ?? null,
79
+ }));
80
+ return Buffer.from(png, 'base64');
81
+ }
82
+
83
+ /** Container metadata of a Final plus a full decode. */
84
+ export function inspectFinal(path) {
85
+ return withRenderPage({ files: { final: path } }, page => page.evaluate(url => window.cuetakeInspect(url), `${ORIGIN}/files/final`));
86
+ }
87
+
88
+ /** A PNG of the Final at `seconds`, for agents to look at without FFmpeg. */
89
+ export async function extractFrame(path, seconds) {
90
+ const png = await withRenderPage({ files: { final: path } }, page => page.evaluate(([url, at]) => window.cuetakeFrame(url, at), [`${ORIGIN}/files/final`, seconds]));
91
+ return Buffer.from(png, 'base64');
92
+ }
package/src/stage.js ADDED
@@ -0,0 +1,114 @@
1
+ /**
2
+ * Stage layout shared by Node and the render page. Pure functions, no imports.
3
+ *
4
+ * The stage is the Final's pixel grid. With a frame, the page sits in a window (optional chrome
5
+ * bar above it) centered on a background, inset by padding. Without one, the page fills the stage.
6
+ */
7
+
8
+ const even = n => Math.round(n / 2) * 2;
9
+ export const SHORT_SIDE = { '1080p': 1080, '1440p': 1440, '2160p': 2160 };
10
+ /** Chrome bar heights in page CSS pixels. */
11
+ export const CHROME_HEIGHT = { none: 0, macos: 28, browser: 44 };
12
+
13
+ /** The Final's pixel size. `size` names the short side; `aspect` is ignored without a frame. */
14
+ export function outputSize(edit, viewport) {
15
+ const short = SHORT_SIDE[edit.output.size] ?? edit.output.size;
16
+ if (!edit.frame) return viewport.width >= viewport.height
17
+ ? { width: even(short * viewport.width / viewport.height), height: short }
18
+ : { width: short, height: even(short * viewport.height / viewport.width) };
19
+ const long = even(short * 16 / 9);
20
+ return { '16:9': { width: long, height: short }, '9:16': { width: short, height: long }, '1:1': { width: short, height: short } }[edit.output.aspect];
21
+ }
22
+
23
+ /** Where the window, its chrome and the page sit on the stage, in stage pixels. `scale` is stage px per CSS px. */
24
+ export function layout(edit, viewport) {
25
+ const { width, height } = outputSize(edit, viewport);
26
+ if (!edit.frame) {
27
+ const scale = width / viewport.width;
28
+ return { width, height, scale, chrome: 0, radius: 0, page: { x: 0, y: 0, w: width, h: height }, window: { x: 0, y: 0, w: width, h: height } };
29
+ }
30
+ const pad = Math.min(width, height) * edit.frame.padding;
31
+ const chromeCss = CHROME_HEIGHT[edit.frame.window];
32
+ const scale = Math.min((width - 2 * pad) / viewport.width, (height - 2 * pad) / (viewport.height + chromeCss));
33
+ const w = viewport.width * scale, h = (viewport.height + chromeCss) * scale;
34
+ const window = { x: (width - w) / 2, y: (height - h) / 2, w, h };
35
+ const chrome = chromeCss * scale;
36
+ return {
37
+ width, height, scale, chrome, radius: edit.frame.radius * Math.min(width, height) / 1080,
38
+ window, page: { x: window.x, y: window.y + chrome, w, h: h - chrome },
39
+ };
40
+ }
41
+
42
+ /**
43
+ * The camera for a viewport crop: the stage point at the Final's center and the zoom. Zoom 1 shows
44
+ * the whole stage; zooming keeps the view inside the stage, so background shows near page edges.
45
+ */
46
+ export function cameraView(crop, stage, viewport) {
47
+ const zoom = viewport.width / crop.w;
48
+ const half = { x: stage.width / (2 * zoom), y: stage.height / (2 * zoom) };
49
+ const clamp = (v, min, max) => Math.max(min, Math.min(max, v));
50
+ return {
51
+ x: clamp(stage.page.x + (crop.x + crop.w / 2) * stage.scale, half.x, stage.width - half.x),
52
+ y: clamp(stage.page.y + (crop.y + crop.h / 2) * stage.scale, half.y, stage.height - half.y),
53
+ zoom,
54
+ };
55
+ }
56
+
57
+ /** Mesh backgrounds: a base color under soft radial blobs [x, y, radius] as fractions of the stage. */
58
+ export const BACKGROUNDS = {
59
+ aurora: { base: '#1e1b4b', blobs: [[0.15, 0.2, 0.7, '#7c3aed'], [0.85, 0.15, 0.6, '#db2777'], [0.7, 0.9, 0.75, '#2563eb'], [0.2, 0.85, 0.55, '#0ea5e9']] },
60
+ sunset: { base: '#431407', blobs: [[0.1, 0.15, 0.7, '#f97316'], [0.9, 0.25, 0.65, '#e11d48'], [0.6, 0.95, 0.7, '#a21caf'], [0.25, 0.8, 0.45, '#facc15']] },
61
+ ocean: { base: '#082f49', blobs: [[0.2, 0.1, 0.65, '#14b8a6'], [0.85, 0.3, 0.7, '#0284c7'], [0.4, 0.95, 0.75, '#1e3a8a'], [0.95, 0.9, 0.4, '#22d3ee']] },
62
+ graphite: { base: '#0a0a0a', blobs: [[0.3, 0.2, 0.7, '#3f3f46'], [0.8, 0.8, 0.7, '#27272a']] },
63
+ paper: { base: '#f4f4f5', blobs: [[0.5, 0, 0.8, '#ffffff'], [0.5, 1.1, 0.7, '#e4e4e7']] },
64
+ };
65
+
66
+ const hsl = (h, s, l) => {
67
+ const k = n => (n + h / 30) % 12, a = s * Math.min(l, 1 - l);
68
+ const f = n => l - a * Math.max(-1, Math.min(k(n) - 3, 9 - k(n), 1));
69
+ return '#' + [f(0), f(8), f(4)].map(v => Math.round(v * 255).toString(16).padStart(2, '0')).join('');
70
+ };
71
+
72
+ /** A mesh around a brand hue, as picked by `brandHue`. */
73
+ export function autoBackground(hue) {
74
+ return { base: hsl(hue, 0.55, 0.12), blobs: [[0.15, 0.2, 0.7, hsl(hue, 0.8, 0.55)], [0.85, 0.15, 0.6, hsl((hue + 40) % 360, 0.75, 0.55)], [0.7, 0.9, 0.75, hsl((hue + 330) % 360, 0.8, 0.5)], [0.2, 0.85, 0.55, hsl((hue + 20) % 360, 0.7, 0.35)]] };
75
+ }
76
+
77
+ /** The hue of the most frequent saturated color in RGBA pixels, or null for a colorless page. */
78
+ export function brandHue(rgba) {
79
+ const buckets = new Map();
80
+ for (let i = 0; i < rgba.length; i += 4) {
81
+ const r = rgba[i], g = rgba[i + 1], b = rgba[i + 2], max = Math.max(r, g, b), min = Math.min(r, g, b);
82
+ const saturation = max ? (max - min) / max : 0;
83
+ if (saturation < 0.35) continue;
84
+ const key = (r >> 5) * 64 + (g >> 5) * 8 + (b >> 5);
85
+ const bucket = buckets.get(key) ?? { n: 0, r: 0, g: 0, b: 0, saturation: 0 };
86
+ bucket.n++; bucket.r += r; bucket.g += g; bucket.b += b; bucket.saturation += saturation;
87
+ buckets.set(key, bucket);
88
+ }
89
+ const top = [...buckets.values()].sort((a, b) => b.saturation - a.saturation)[0];
90
+ if (!top) return null;
91
+ const [r, g, b] = [top.r, top.g, top.b].map(v => v / top.n / 255), max = Math.max(r, g, b), d = max - Math.min(r, g, b);
92
+ const hue = max === r ? 60 * (((g - b) / d) % 6) : max === g ? 60 * ((b - r) / d + 2) : 60 * ((r - g) / d + 4);
93
+ return (hue + 360) % 360;
94
+ }
95
+
96
+ /**
97
+ * Where Preview tiles sit on one sheet, in sheet pixels. A single tile is the sheet; several are shown
98
+ * at half size in a grid of up to three columns, each with its label above it. Each row is as tall as
99
+ * its tallest tile, so a portrait tile does not stretch the other rows.
100
+ */
101
+ export function previewSheet(sizes) {
102
+ if (sizes.length === 1) return { width: sizes[0].width, height: sizes[0].height, tiles: [{ x: 0, y: 0, w: sizes[0].width, h: sizes[0].height, label: null }] };
103
+ const scale = 0.5, gap = 32, label = 44;
104
+ const columns = sizes.length <= 4 ? 2 : 3, cellWidth = Math.max(...sizes.map(s => s.width)) * scale;
105
+ const rows = Array.from({ length: Math.ceil(sizes.length / columns) }, (_, row) => Math.max(...sizes.slice(row * columns, (row + 1) * columns).map(s => s.height)) * scale);
106
+ const rowTop = rows.map((_, row) => gap + rows.slice(0, row).reduce((sum, h) => sum + label + h + gap, 0));
107
+ return {
108
+ width: gap + columns * (cellWidth + gap), height: rowTop.at(-1) + label + rows.at(-1) + gap,
109
+ tiles: sizes.map(({ width, height }, i) => {
110
+ const x = gap + (i % columns) * (cellWidth + gap) + (cellWidth - width * scale) / 2, y = rowTop[Math.floor(i / columns)];
111
+ return { x, y: y + label, w: width * scale, h: height * scale, label: { x, y: y + label / 2 } };
112
+ }),
113
+ };
114
+ }