Skip to content

packages/core/src/lib/recording/recording.ts

Read as Markdown

This is the source snapshot used to build these API details. View this revision on GitHub.

Back to reference

1 import { GLOBAL_STATE } from "../global-state.js";
2 import { update } from "../update.js";
3 import type { Canvas, PibblInstance } from "../types.js";
4 import { workerSource } from "./worker-source.js";
5 import { bytes } from "./wasm-bytes.js";
6 import type {
7   PibblFrameRecording,
8   PibblFrameRecordingOptions,
9   PibblFrameRecordingSession,
10   PibblRecordedFrameInfo,
11   PibblGifExportOptions,
12   PibblRenderCompletion,
13 } from "./types.js";
14 
15 /** Private deterministic ownership evidence; not a public diagnostics API. */
16 export const recordingResources = {
17   workers: 0,
18   urls: 0,
19   observers: 0,
20   timers: 0,
21   abortListeners: 0,
22   requests: 0,
23   exports: 0,
24 };
25 const owners = /* @__PURE__ */ new WeakMap<
26   PibblFrameRecording,
27   RecordingClient
28 >();
29 function aborted(message = "Recording cancelled."): DOMException {
30   return new DOMException(message, "AbortError");
31 }
32 function positive(value: number, name: string): void {
33   if (!Number.isFinite(value) || value <= 0)
34     throw new RangeError(`${name} must be finite and greater than zero.`);
35 }
36 function listen(
37   signal: AbortSignal | undefined,
38   callback: () => void,
39 ): () => void {
40   if (!signal) return () => {};
41   let attached = true;
42   signal.addEventListener("abort", callback, { once: true });
43   recordingResources.abortListeners++;
44   return () => {
45     if (!attached) return;
46     attached = false;
47     signal.removeEventListener("abort", callback);
48     recordingResources.abortListeners--;
49   };
50 }
51 interface Request {
52   gif: boolean;
53   resolve: (bytes: ArrayBuffer) => void;
54   reject: (error: unknown) => void;
55   cleanup: () => void;
56   progress?: (value: number) => void;
57   result?: ArrayBuffer;
58   error?: unknown;
59 }
60 class RecordingClient {
61   worker?: Worker;
62   closed = false;
63   private url?: string;
64   private nextId = 0;
65   private pending = new Map<number, Request>();
66   private exporting = false;
67   onmessage: (data: any) => void = () => {};
68   onerror: (error: unknown) => void = () => {};
69 
70   async initialize(frameBytes: number, estimatedBytes: number): Promise<void> {
71     await Promise.resolve();
72     if (this.closed) return;
73     const source = workerSource;
74     this.url = URL.createObjectURL(
75       new Blob([source], { type: "text/javascript" }),
76     );
77     recordingResources.urls++;
78     try {
79       this.worker = new Worker(this.url, { name: "Pibbl frame recording" });
80       recordingResources.workers++;
81       this.worker.onmessage = ({ data }) => {
82         if (this.closed) return;
83         if (data.type === "ready") this.revoke();
84         if (data.type === "fatal") {
85           this.onerror(new Error(data.message));
86           return;
87         }
88         const request = this.pending.get(data.id);
89         if (request) {
90           if (data.type === "progress" && !request.error) {
91             try {
92               request.progress?.(data.progress);
93             } catch (error) {
94               this.cancelExport(data.id, error);
95             }
96           } else if (data.type === "result") {
97             if (request.gif) request.result = data.buffer;
98             else this.settle(data.id, data.buffer);
99           } else if (data.type === "error") {
100             this.settle(data.id, undefined, new Error(data.message));
101           } else if (data.type === "exportReleased") {
102             this.settle(data.id, request.result, request.error);
103           }
104         }
105         this.onmessage(data);
106       };
107       this.worker.onerror = (event) =>
108         this.onerror(new Error(event.message || "Recording worker failed."));
109       this.worker.onmessageerror = () =>
110         this.onerror(
111           new Error("Recording worker message could not be decoded."),
112         );
113       const buffer = Uint8Array.from(atob(bytes), (char) =>
114         char.charCodeAt(0),
115       ).buffer;
116       this.send({ type: "start", bytes: buffer, frameBytes, estimatedBytes }, [
117         buffer,
118       ]);
119     } catch (error) {
120       this.revoke();
121       throw error;
122     }
123   }
124   send(data: unknown, transfer: Transferable[] = []): void {
125     if (this.closed || !this.worker)
126       throw aborted("Recording has been disposed.");
127     this.worker.postMessage(data, transfer);
128   }
129   request(data: any, options?: PibblGifExportOptions): Promise<ArrayBuffer> {
130     if (this.closed)
131       return Promise.reject(aborted("Recording has been disposed."));
132     if (options?.signal?.aborted)
133       return Promise.reject(aborted("GIF export cancelled."));
134     const gif = data.type === "gif";
135     if (gif && this.exporting)
136       return Promise.reject(
137         new Error("A GIF export is already running for this recording."),
138       );
139     const id = ++this.nextId;
140     if (gif) {
141       this.exporting = true;
142       recordingResources.exports++;
143     }
144     return new Promise((resolve, reject) => {
145       const request: Request = {
146         gif,
147         resolve,
148         reject,
149         cleanup: () => {},
150         progress: options?.onProgress,
151       };
152       this.pending.set(id, request);
153       recordingResources.requests++;
154       request.cleanup = listen(options?.signal, () =>
155         this.cancelExport(id, aborted("GIF export cancelled.")),
156       );
157       try {
158         this.send({ ...data, id });
159       } catch (error) {
160         this.settle(id, undefined, error);
161       }
162     });
163   }
164   private cancelExport(id: number, error: unknown): void {
165     const request = this.pending.get(id);
166     if (!request || request.error) return;
167     request.error = error;
168     request.cleanup();
169     try {
170       this.send({ type: "cancelExport", id });
171     } catch {
172       this.settle(id, undefined, error);
173     }
174   }
175   private settle(id: number, result?: ArrayBuffer, error?: unknown): void {
176     const request = this.pending.get(id);
177     if (!request) return;
178     this.pending.delete(id);
179     request.cleanup();
180     recordingResources.requests--;
181     if (request.gif) {
182       this.exporting = false;
183       recordingResources.exports--;
184     }
185     if (error !== undefined) request.reject(error);
186     else if (result) request.resolve(result);
187     else request.reject(new Error("Recording worker returned no result."));
188   }
189   private revoke(): void {
190     if (!this.url) return;
191     URL.revokeObjectURL(this.url);
192     this.url = undefined;
193     recordingResources.urls--;
194   }
195   dispose(error: unknown = aborted("Recording has been disposed.")): void {
196     if (this.closed) return;
197     this.closed = true;
198     if (this.worker) {
199       this.worker.onmessage =
200         this.worker.onerror =
201         this.worker.onmessageerror =
202           null;
203       this.worker.terminate();
204       this.worker = undefined;
205       recordingResources.workers--;
206     }
207     this.revoke();
208     for (const id of this.pending.keys()) this.settle(id, undefined, error);
209     this.onmessage = this.onerror = () => {};
210   }
211 }
212 
213 // Completed recording methods capture only their worker and metadata, never
214 // the capture session's mount, signal, controls, or lifecycle callbacks.
215 function retainRecording(
216   client: RecordingClient,
217   frames: readonly PibblRecordedFrameInfo[],
218   duration: number,
219 ): PibblFrameRecording {
220   const result: PibblFrameRecording = Object.freeze({
221     duration,
222     frames,
223     async readFrame(index: number) {
224       if (!Number.isInteger(index) || index < 0 || index >= frames.length)
225         throw new RangeError("Frame index is out of range.");
226       const buffer = await client.request({ type: "read", index });
227       return { ...frames[index], data: new Uint8ClampedArray(buffer) };
228     },
229     dispose() {
230       client.dispose();
231     },
232   });
233   owners.set(result, client);
234   client.onmessage = () => {};
235   client.onerror = (error) => client.dispose(error);
236   return result;
237 }
238 
239 /**
240  * Record committed bitmap frames from any live Pibbl root canvas.
241  *
242  * Capture uses the existing render lifecycle; it never starts a render loop.
243  * Stop retains frames; cancel discards them. Dispose the completed recording
244  * after reading or exporting it. Resizing, failed renders, unreadable pixels,
245  * allocation failure, and capture queue overflow reject and release the session.
246  *
247  * @param canvas The canvas belonging to a live Pibbl root mount.
248  * @param options Capture duration, maximum frame rate, allocation headroom, and cancellation.
249  * @returns Stable controls and promises for one recording session.
250  * @see {@link PibblFrameRecordingOptions}
251  * @see {@link PibblFrameRecordingSession}
252  */
253 export function recordFrames(
254   canvas: Canvas,
255   options: PibblFrameRecordingOptions,
256 ): PibblFrameRecordingSession {
257   positive(options.duration, "duration");
258   const frameRate = options.frameRate ?? 60;
259   const headroom = options.memoryHeadroom ?? 1.15;
260   positive(frameRate, "frameRate");
261   positive(headroom, "memoryHeadroom");
262   if (headroom < 1)
263     throw new RangeError("memoryHeadroom must be at least one.");
264   if (options.duration > 2_147_483_647)
265     throw new RangeError("duration exceeds the supported timer range.");
266   let instance: PibblInstance | undefined =
267     GLOBAL_STATE.pibblInstances.get(canvas);
268   if (!instance || instance.parent || instance.mainTeardowns.closed)
269     throw new Error("recordFrames requires a live Pibbl root canvas.");
270   let target: Canvas | undefined = canvas;
271   const client = new RecordingClient();
272   const metadata: PibblRecordedFrameInfo[] = [];
273   let phase: "starting" | "capturing" | "finishing" | "finished" | "cancelled" =
274     "starting";
275   let initializing = false;
276   let workerReady = false,
277     stopRequested = false;
278   let started = 0,
279     last = -Infinity,
280     duration = 0,
281     pendingFrames = 0;
282   let width = 0,
283     height = 0;
284   let pendingRenderGeneration = 0;
285   let lastNotifiedGeneration = 0;
286   let timer: ReturnType<typeof setTimeout> | undefined;
287   let sampleTimer: ReturnType<typeof setTimeout> | undefined;
288   let removeAbort = () => {};
289   let resolveReady!: () => void, rejectReady!: (error: unknown) => void;
290   let resolveFinished!: (recording: PibblFrameRecording) => void,
291     rejectFinished!: (error: unknown) => void;
292   const ready = new Promise<void>((resolve, reject) => {
293     resolveReady = resolve;
294     rejectReady = reject;
295   });
296   const finished = new Promise<PibblFrameRecording>((resolve, reject) => {
297     resolveFinished = resolve;
298     rejectFinished = reject;
299   });
300   // Cancellation is legitimate even when applications only await one of these promises.
301   void ready.catch(() => {});
302   void finished.catch(() => {});
303   function clearSampleTimer(): void {
304     if (sampleTimer === undefined) return;
305     clearTimeout(sampleTimer);
306     sampleTimer = undefined;
307     recordingResources.timers--;
308   }
309   function detach(): void {
310     clearSampleTimer();
311     if (timer !== undefined) {
312       clearTimeout(timer);
313       timer = undefined;
314       recordingResources.timers--;
315     }
316     removeAbort();
317     removeAbort = () => {};
318     if (instance) {
319       instance.mainTeardowns.remove(rootDisposed);
320       if (instance.rootFrameObservers?.delete(observe))
321         recordingResources.observers--;
322       if (!instance.rootFrameObservers?.size)
323         instance.rootFrameObservers = undefined;
324     }
325     instance = undefined;
326     target = undefined;
327   }
328   function fail(error: unknown): void {
329     if (phase === "finished" || phase === "cancelled") return;
330     phase = "cancelled";
331     detach();
332     client.dispose(error);
333     metadata.length = 0;
334     rejectReady(error);
335     rejectFinished(error);
336   }
337   function rootDisposed(): void {
338     fail(aborted("Pibbl mount disposed during recording."));
339   }
340   function stop(): void {
341     if (phase === "starting") {
342       stopRequested = true;
343       return;
344     }
345     if (phase !== "capturing") return;
346     duration = Math.min(options.duration, performance.now() - started);
347     phase = "finishing";
348     detach();
349     try {
350       client.send({ type: "finish" });
351     } catch (error) {
352       fail(error);
353     }
354   }
355   function capture(renderGeneration: number): void {
356     if (!target) return;
357     if (!Number.isSafeInteger(renderGeneration) || renderGeneration <= 0)
358       throw new Error("Recording requires a committed render generation.");
359     if (target.width !== width || target.height !== height)
360       throw new Error("Canvas backing size changed during recording.");
361     const now = performance.now();
362     const initial = phase === "starting";
363     const timestamp = initial ? 0 : now - started;
364     if (!initial && timestamp >= options.duration) {
365       stop();
366       return;
367     }
368     if (!initial && timestamp - last < 1000 / frameRate) {
369       // One pending successful render may be sampled later; no rendering is scheduled.
370       // This preserves its final static bitmap when no further renders occur.
371       if (sampleTimer === undefined) {
372         sampleTimer = setTimeout(
373           () => {
374             sampleTimer = undefined;
375             recordingResources.timers--;
376             if (phase !== "capturing") return;
377             try {
378               capture(pendingRenderGeneration);
379             } catch (error) {
380               fail(error);
381             }
382           },
383           Math.ceil(1000 / frameRate - (timestamp - last)),
384         );
385         recordingResources.timers++;
386       }
387       return;
388     }
389     clearSampleTimer();
390     if (pendingFrames >= 3)
391       throw new Error(
392         "Recording capture queue overflow; no frames were silently dropped.",
393       );
394     const context = target.getContext("2d") as
395       CanvasRenderingContext2D | OffscreenCanvasRenderingContext2D | null;
396     if (!context)
397       throw new Error("Recording requires a readable Canvas 2D surface.");
398     const pixels = context.getImageData(0, 0, width, height);
399     client.send({ type: "frame", timestamp, buffer: pixels.data.buffer }, [
400       pixels.data.buffer,
401     ]);
402     pendingFrames++;
403     const info = Object.freeze({ timestamp, width, height, renderGeneration });
404     metadata.push(info);
405     options.onFrameCaptured?.(info);
406     // Callbacks may release the session while its first capture is initializing.
407     if (phase !== "starting" && phase !== "capturing") return;
408     last = timestamp;
409     if (initial) {
410       started = now;
411       phase = "capturing";
412       timer = setTimeout(stop, options.duration);
413       recordingResources.timers++;
414       resolveReady();
415       if (stopRequested) stop();
416     }
417   }
418   function observe(success: boolean, renderGeneration: number): void {
419     if (phase === "finished" || phase === "cancelled") return;
420     if (renderGeneration > lastNotifiedGeneration) {
421       lastNotifiedGeneration = renderGeneration;
422       const completion: PibblRenderCompletion = success
423         ? { status: "committed", generation: renderGeneration }
424         : { status: "failed", generation: renderGeneration };
425       try {
426         options.onRenderComplete?.(Object.freeze(completion));
427       } catch (error) {
428         fail(error);
429         return;
430       }
431     }
432     if (!success) {
433       fail(new Error("Pibbl render failed during recording."));
434       return;
435     }
436     if (phase !== "starting" && phase !== "capturing") return;
437     pendingRenderGeneration = renderGeneration;
438     if (!workerReady) {
439       initialize();
440       return;
441     }
442     try {
443       capture(renderGeneration);
444     } catch (error) {
445       fail(error);
446     }
447   }
448   client.onerror = (error) => {
449     fail(error);
450     client.dispose(error);
451   };
452   client.onmessage = (data) => {
453     if (data.type === "ready") {
454       workerReady = true;
455       if (!instance || phase !== "starting") return;
456       if (
457         instance.committedRenderGeneration &&
458         instance.committedRenderGeneration === instance.renderGeneration
459       )
460         observe(true, instance.committedRenderGeneration);
461       else update(instance.canvas);
462     } else if (data.type === "ack") pendingFrames--;
463     else if (data.type === "finished" && phase === "finishing") {
464       phase = "finished";
465       const frames = Object.freeze(metadata.splice(0));
466       const result = retainRecording(client, frames, duration);
467       resolveFinished(result);
468     }
469   };
470   const session = Object.freeze({
471     ready,
472     finished,
473     stop,
474     cancel: () => fail(aborted()),
475   });
476   if (options.signal?.aborted) {
477     fail(aborted());
478     return session;
479   }
480   instance.rootFrameObservers ??= new Set();
481   instance.rootFrameObservers.add(observe);
482   recordingResources.observers++;
483   instance.mainTeardowns.add(rootDisposed);
484   removeAbort = listen(options.signal, () => fail(aborted()));
485   if (
486     instance.surface.kind === "root" &&
487     (instance.surface.display.width <= 0 ||
488       instance.surface.display.height <= 0)
489   ) {
490     fail(new Error("Recording requires a nonzero display surface."));
491   } else if (
492     instance.committedRenderGeneration &&
493     instance.committedRenderGeneration === instance.renderGeneration
494   )
495     initialize();
496   else update(instance.canvas);
497   function initialize(): void {
498     if (initializing || phase !== "starting" || !target) return;
499     initializing = true;
500     width = target!.width;
501     height = target!.height;
502     const frameBytes = width * height * 4;
503     const estimatedBytes = Math.ceil(
504       frameBytes *
505         Math.max(1, Math.ceil((options.duration * frameRate) / 1000)) *
506         headroom,
507     );
508     if (
509       !frameBytes ||
510       !Number.isSafeInteger(estimatedBytes) ||
511       estimatedBytes > 0xff000000
512     ) {
513       fail(
514         new RangeError(
515           "Estimated recording exceeds WASM32 addressable storage.",
516         ),
517       );
518     } else void client.initialize(frameBytes, estimatedBytes).catch(fail);
519   }
520   return session;
521 }
522 
523 /**
524  * Encode a retained recording to an image/gif Blob in its worker's WASM encoder.
525  *
526  * Pixels remain worker-owned. Cancellation stops encoding and preserves the
527  * recording; disposing the recording cancels all pending reads and exports.
528  * GIF timing is rounded cumulatively to 10ms units. Without an opaque background,
529  * alpha below 128 is transparent and other pixels are opaque. Only one export
530  * per recording may run at a time. Requires workers, WebAssembly, and blob-worker CSP permission.
531  *
532  * @param recording Retained frames returned by recordFrames.
533  * @param options Output dimensions, palette, dithering, sampling, looping, background, progress, and cancellation.
534  * @returns Encoded GIF bytes as a caller-owned Blob.
535  * @see {@link PibblGifExportOptions}
536  * @see {@link PibblFrameRecording}
537  */
538 export async function exportGif(
539   recording: PibblFrameRecording,
540   options: PibblGifExportOptions = {},
541 ): Promise<Blob> {
542   const client = owners.get(recording);
543   if (!client)
544     throw new TypeError(
545       "exportGif requires a recording returned by recordFrames.",
546     );
547   const frameRate = options.frameRate ?? 25;
548   positive(frameRate, "frameRate");
549   if (frameRate > 100)
550     throw new RangeError("GIF frameRate must not exceed 100.");
551   const repeat = options.repeatCount ?? -1;
552   if (
553     options.repeatCount !== undefined &&
554     (!Number.isInteger(repeat) || repeat < 0 || repeat > 65535)
555   )
556     throw new RangeError("repeatCount must be an integer from zero to 65535.");
557   const source = recording.frames[0];
558   const integer = (
559     value: number,
560     name: string,
561     maximum: number,
562     minimum = 1,
563   ) => {
564     if (!Number.isInteger(value) || value < minimum || value > maximum)
565       throw new RangeError(
566         `${name} must be an integer from ${minimum} to ${maximum}.`,
567       );
568     return value;
569   };
570   const width = integer(
571     options.width ??
572       (options.height === undefined
573         ? source.width
574         : Math.max(
575             1,
576             Math.round((source.width * options.height) / source.height),
577           )),
578     "width",
579     65535,
580   );
581   const height = integer(
582     options.height ??
583       (options.width === undefined
584         ? source.height
585         : Math.max(
586             1,
587             Math.round((source.height * options.width) / source.width),
588           )),
589     "height",
590     65535,
591   );
592   if (width * height * 4 > 0xff000000)
593     throw new RangeError("GIF bitmap exceeds WASM32 memory capacity.");
594   const maxColors = integer(options.maxColors ?? 256, "maxColors", 256, 2);
595   const quantizationSampleFactor = integer(
596     options.quantizationSampleFactor ?? 10,
597     "quantizationSampleFactor",
598     30,
599   );
600   const paletteSampleCount = integer(
601     options.paletteSampleCount ?? 262144,
602     "paletteSampleCount",
603     16777216,
604   );
605   if (options.dithering !== undefined && typeof options.dithering !== "boolean")
606     throw new TypeError("dithering must be a boolean.");
607   const opaqueColor = (color: string, name: string) => {
608     if (typeof color !== "string")
609       throw new TypeError(`${name} must be a valid opaque CSS color.`);
610     const context = new OffscreenCanvas(1, 1).getContext("2d")!;
611     context.fillStyle = "#010203";
612     context.fillStyle = color;
613     const first = context.fillStyle;
614     context.fillStyle = "#040506";
615     context.fillStyle = color;
616     if (context.fillStyle !== first)
617       throw new TypeError(`${name} must be a valid opaque CSS color.`);
618     context.fillRect(0, 0, 1, 1);
619     const pixel = context.getImageData(0, 0, 1, 1).data;
620     if (pixel[3] !== 255) throw new TypeError(`${name} must be opaque.`);
621     return [pixel[0], pixel[1], pixel[2]];
622   };
623   let background = -1;
624   if (options.background !== undefined) {
625     const [r, g, b] = opaqueColor(options.background, "background");
626     background = (r << 16) | (g << 8) | b;
627   }
628   let palette: number[] = [];
629   if (options.palette !== undefined) {
630     if (
631       !Array.isArray(options.palette) ||
632       !options.palette.length ||
633       options.palette.length > maxColors - (background < 0 ? 1 : 0)
634     )
635       throw new RangeError(
636         "palette must contain opaque colors fitting maxColors (including transparency).",
637       );
638     palette = options.palette.flatMap((color) =>
639       opaqueColor(color, "palette color"),
640     );
641   }
642   const buffer = await client.request(
643     {
644       type: "gif",
645       duration: recording.duration,
646       width,
647       height,
648       sourceWidth: source.width,
649       sourceHeight: source.height,
650       maxColors,
651       palette,
652       dithering: options.dithering ?? false,
653       quantizationSampleFactor,
654       paletteSampleCount,
655       frameRate,
656       repeatCount: repeat,
657       background,
658     },
659     options,
660   );
661   return new Blob([buffer], { type: "image/gif" });
662 }
663 

Documentation built with @pibbl/core 0.0.2, revision a1dcf8e. ALPHA — NOT FOR PRODUCTION USE.