@hyperframes/engine 0.4.5 → 0.4.7

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.
Files changed (78) hide show
  1. package/dist/config.d.ts +6 -0
  2. package/dist/config.d.ts.map +1 -1
  3. package/dist/config.js +9 -0
  4. package/dist/config.js.map +1 -1
  5. package/dist/index.d.ts +8 -1
  6. package/dist/index.d.ts.map +1 -1
  7. package/dist/index.js +7 -1
  8. package/dist/index.js.map +1 -1
  9. package/dist/services/browserManager.d.ts.map +1 -1
  10. package/dist/services/browserManager.js +6 -3
  11. package/dist/services/browserManager.js.map +1 -1
  12. package/dist/services/chunkEncoder.d.ts +14 -7
  13. package/dist/services/chunkEncoder.d.ts.map +1 -1
  14. package/dist/services/chunkEncoder.js +25 -9
  15. package/dist/services/chunkEncoder.js.map +1 -1
  16. package/dist/services/chunkEncoder.types.d.ts +4 -0
  17. package/dist/services/chunkEncoder.types.d.ts.map +1 -1
  18. package/dist/services/frameCapture.d.ts.map +1 -1
  19. package/dist/services/frameCapture.js +18 -2
  20. package/dist/services/frameCapture.js.map +1 -1
  21. package/dist/services/hdrCapture.d.ts +62 -0
  22. package/dist/services/hdrCapture.d.ts.map +1 -0
  23. package/dist/services/hdrCapture.js +259 -0
  24. package/dist/services/hdrCapture.js.map +1 -0
  25. package/dist/services/screenshotService.d.ts +34 -0
  26. package/dist/services/screenshotService.d.ts.map +1 -1
  27. package/dist/services/screenshotService.js +97 -19
  28. package/dist/services/screenshotService.js.map +1 -1
  29. package/dist/services/streamingEncoder.d.ts +18 -3
  30. package/dist/services/streamingEncoder.d.ts.map +1 -1
  31. package/dist/services/streamingEncoder.js +104 -50
  32. package/dist/services/streamingEncoder.js.map +1 -1
  33. package/dist/services/videoFrameExtractor.d.ts.map +1 -1
  34. package/dist/services/videoFrameExtractor.js +109 -18
  35. package/dist/services/videoFrameExtractor.js.map +1 -1
  36. package/dist/services/videoFrameInjector.d.ts +54 -0
  37. package/dist/services/videoFrameInjector.d.ts.map +1 -1
  38. package/dist/services/videoFrameInjector.js +159 -0
  39. package/dist/services/videoFrameInjector.js.map +1 -1
  40. package/dist/utils/alphaBlit.d.ts +105 -0
  41. package/dist/utils/alphaBlit.d.ts.map +1 -0
  42. package/dist/utils/alphaBlit.js +550 -0
  43. package/dist/utils/alphaBlit.js.map +1 -0
  44. package/dist/utils/ffprobe.d.ts +10 -0
  45. package/dist/utils/ffprobe.d.ts.map +1 -1
  46. package/dist/utils/ffprobe.js +7 -0
  47. package/dist/utils/ffprobe.js.map +1 -1
  48. package/dist/utils/hdr.d.ts +82 -0
  49. package/dist/utils/hdr.d.ts.map +1 -0
  50. package/dist/utils/hdr.js +87 -0
  51. package/dist/utils/hdr.js.map +1 -0
  52. package/dist/utils/layerCompositor.d.ts +36 -0
  53. package/dist/utils/layerCompositor.d.ts.map +1 -0
  54. package/dist/utils/layerCompositor.js +49 -0
  55. package/dist/utils/layerCompositor.js.map +1 -0
  56. package/package.json +3 -2
  57. package/src/config.ts +16 -0
  58. package/src/index.ts +42 -0
  59. package/src/services/browserManager.ts +6 -3
  60. package/src/services/chunkEncoder.test.ts +88 -0
  61. package/src/services/chunkEncoder.ts +35 -9
  62. package/src/services/chunkEncoder.types.ts +3 -0
  63. package/src/services/frameCapture.ts +31 -4
  64. package/src/services/hdrCapture.test.ts +159 -0
  65. package/src/services/hdrCapture.ts +354 -0
  66. package/src/services/screenshotService.ts +102 -17
  67. package/src/services/streamingEncoder.test.ts +228 -0
  68. package/src/services/streamingEncoder.ts +153 -63
  69. package/src/services/videoFrameExtractor.ts +135 -31
  70. package/src/services/videoFrameInjector.ts +200 -0
  71. package/src/utils/alphaBlit.test.ts +993 -0
  72. package/src/utils/alphaBlit.ts +643 -0
  73. package/src/utils/ffprobe.ts +22 -0
  74. package/src/utils/hdr.test.ts +191 -0
  75. package/src/utils/hdr.ts +137 -0
  76. package/src/utils/layerCompositor.test.ts +141 -0
  77. package/src/utils/layerCompositor.ts +58 -0
  78. package/tsconfig.json +2 -1
@@ -163,6 +163,21 @@ export function isFontResourceError(type: string, text: string, locationUrl: str
163
163
  );
164
164
  }
165
165
 
166
+ async function pollPageExpression(
167
+ page: Page,
168
+ expression: string,
169
+ timeoutMs: number,
170
+ intervalMs: number = 100,
171
+ ): Promise<boolean> {
172
+ const deadline = Date.now() + timeoutMs;
173
+ while (Date.now() < deadline) {
174
+ const ready = Boolean(await page.evaluate(expression));
175
+ if (ready) return true;
176
+ await new Promise((resolve) => setTimeout(resolve, intervalMs));
177
+ }
178
+ return Boolean(await page.evaluate(expression));
179
+ }
180
+
166
181
  export async function initializeSession(session: CaptureSession): Promise<void> {
167
182
  const { page, serverUrl } = session;
168
183
 
@@ -213,17 +228,29 @@ export async function initializeSession(session: CaptureSession): Promise<void>
213
228
 
214
229
  const pageReadyTimeout =
215
230
  session.config?.playerReadyTimeout ?? DEFAULT_CONFIG.playerReadyTimeout;
216
- await page.waitForFunction(
231
+ const pageReady = await pollPageExpression(
232
+ page,
217
233
  `!!(window.__hf && typeof window.__hf.seek === "function" && window.__hf.duration > 0)`,
218
- { timeout: pageReadyTimeout },
234
+ pageReadyTimeout,
219
235
  );
236
+ if (!pageReady) {
237
+ throw new Error(
238
+ `[FrameCapture] window.__hf not ready after ${pageReadyTimeout}ms. Page must expose window.__hf = { duration, seek }.`,
239
+ );
240
+ }
220
241
 
221
242
  // Wait for all video elements to have loaded metadata (dimensions + duration)
222
243
  // Without this, frame 0 captures videos at their 300x150 default size
223
- await page.waitForFunction(
244
+ const videosReady = await pollPageExpression(
245
+ page,
224
246
  `document.querySelectorAll("video").length === 0 || Array.from(document.querySelectorAll("video")).every(v => v.readyState >= 1)`,
225
- { timeout: pageReadyTimeout },
247
+ pageReadyTimeout,
226
248
  );
249
+ if (!videosReady) {
250
+ throw new Error(
251
+ `[FrameCapture] video metadata not ready after ${pageReadyTimeout}ms. Video elements must load metadata before capture starts.`,
252
+ );
253
+ }
227
254
 
228
255
  await page.evaluate(`document.fonts?.ready`);
229
256
 
@@ -0,0 +1,159 @@
1
+ import { describe, it, expect } from "vitest";
2
+ import { float16ToPqRgb } from "./hdrCapture.js";
3
+
4
+ // IEEE 754 half-precision (float16) bit patterns used to feed
5
+ // `float16ToPqRgb`. Encoding rule: sign(1) | exp(5) | frac(10).
6
+ const F16_ZERO = 0x0000; // +0.0
7
+ const F16_HALF = 0x3800; // +0.5 (exp=14, frac=0 → 2^-1)
8
+ const F16_ONE = 0x3c00; // +1.0 (exp=15, frac=0 → 2^0 — SDR white)
9
+ // PQ caps at 10000 nits and SDR_NITS = 203, so the linear input must exceed
10
+ // ~58x SDR white before linearToPQ(L) clips at 1.0. 1024 is well above that.
11
+ const F16_OVERBRIGHT = 0x6400; // +1024.0 (exp=25, frac=0 → 2^10)
12
+
13
+ function makeFloat16Frame(
14
+ width: number,
15
+ height: number,
16
+ pixel: { r: number; g: number; b: number; a: number },
17
+ bytesPerRow: number = width * 8,
18
+ ): Buffer {
19
+ // Row-padded layout matches WebGPU readback: bytesPerRow ≥ width * 8 (4
20
+ // channels × 2 bytes), with garbage bytes after each row's pixel data.
21
+ const buf = Buffer.alloc(height * bytesPerRow);
22
+ for (let y = 0; y < height; y++) {
23
+ for (let x = 0; x < width; x++) {
24
+ const idx = y * bytesPerRow + x * 8;
25
+ buf.writeUInt16LE(pixel.r, idx);
26
+ buf.writeUInt16LE(pixel.g, idx + 2);
27
+ buf.writeUInt16LE(pixel.b, idx + 4);
28
+ buf.writeUInt16LE(pixel.a, idx + 6);
29
+ }
30
+ }
31
+ return buf;
32
+ }
33
+
34
+ describe("float16ToPqRgb", () => {
35
+ it("returns a buffer of width * height * 6 bytes (rgb48le)", () => {
36
+ const frame = makeFloat16Frame(4, 3, { r: 0, g: 0, b: 0, a: 0 });
37
+ const out = float16ToPqRgb(frame, 32, 4, 3);
38
+ expect(out.length).toBe(4 * 3 * 6);
39
+ });
40
+
41
+ it("encodes float16 black to PQ zero (linearToPQ(0) ≈ 0 after uint16 quantization)", () => {
42
+ const frame = makeFloat16Frame(2, 2, {
43
+ r: F16_ZERO,
44
+ g: F16_ZERO,
45
+ b: F16_ZERO,
46
+ a: F16_ZERO,
47
+ });
48
+ const out = float16ToPqRgb(frame, 16, 2, 2);
49
+ for (let i = 0; i < out.length; i += 2) {
50
+ expect(out.readUInt16LE(i)).toBe(0);
51
+ }
52
+ });
53
+
54
+ it("clamps overbright float16 input to PQ 65535 (linearToPQ(>>1.0) → 1.0)", () => {
55
+ // ~1024 linear is well past the 58x-SDR PQ saturation point; output caps
56
+ // at 1.0 → 65535 in uint16.
57
+ const frame = makeFloat16Frame(2, 2, {
58
+ r: F16_OVERBRIGHT,
59
+ g: F16_OVERBRIGHT,
60
+ b: F16_OVERBRIGHT,
61
+ a: F16_ZERO,
62
+ });
63
+ const out = float16ToPqRgb(frame, 16, 2, 2);
64
+ for (let pixel = 0; pixel < 4; pixel++) {
65
+ const dst = pixel * 6;
66
+ expect(out.readUInt16LE(dst)).toBe(65535);
67
+ expect(out.readUInt16LE(dst + 2)).toBe(65535);
68
+ expect(out.readUInt16LE(dst + 4)).toBe(65535);
69
+ }
70
+ });
71
+
72
+ it("preserves channel ordering R, G, B (alpha is discarded)", () => {
73
+ // Distinct float16 values per channel verify the function doesn't
74
+ // mix them up. Alpha is set high but should not appear in the output.
75
+ const frame = makeFloat16Frame(1, 1, {
76
+ r: F16_ONE,
77
+ g: F16_HALF,
78
+ b: F16_ZERO,
79
+ a: F16_ONE,
80
+ });
81
+ const out = float16ToPqRgb(frame, 8, 1, 1);
82
+ const r = out.readUInt16LE(0);
83
+ const g = out.readUInt16LE(2);
84
+ const b = out.readUInt16LE(4);
85
+ expect(r).toBeGreaterThan(g);
86
+ expect(g).toBeGreaterThan(b);
87
+ expect(b).toBe(0);
88
+ });
89
+
90
+ it("is monotonic: higher float16 input produces higher PQ output", () => {
91
+ const dark = makeFloat16Frame(1, 1, { r: F16_ZERO, g: 0, b: 0, a: 0 });
92
+ const mid = makeFloat16Frame(1, 1, { r: F16_HALF, g: 0, b: 0, a: 0 });
93
+ const bright = makeFloat16Frame(1, 1, { r: F16_ONE, g: 0, b: 0, a: 0 });
94
+ const r0 = float16ToPqRgb(dark, 8, 1, 1).readUInt16LE(0);
95
+ const r1 = float16ToPqRgb(mid, 8, 1, 1).readUInt16LE(0);
96
+ const r2 = float16ToPqRgb(bright, 8, 1, 1).readUInt16LE(0);
97
+ expect(r0).toBe(0);
98
+ expect(r1).toBeGreaterThan(r0);
99
+ expect(r2).toBeGreaterThan(r1);
100
+ });
101
+
102
+ it("is deterministic across calls with the same input", () => {
103
+ const frame = makeFloat16Frame(3, 2, {
104
+ r: F16_HALF,
105
+ g: F16_ONE,
106
+ b: F16_ZERO,
107
+ a: F16_ONE,
108
+ });
109
+ const a = float16ToPqRgb(frame, 24, 3, 2);
110
+ const b = float16ToPqRgb(frame, 24, 3, 2);
111
+ expect(a.equals(b)).toBe(true);
112
+ });
113
+
114
+ it("handles padded bytesPerRow (WebGPU 256-byte alignment)", () => {
115
+ // WebGPU readback pads rows to 256-byte multiples. For a 4-pixel-wide
116
+ // frame the actual pixel data is 32 bytes but bytesPerRow is 256.
117
+ const width = 4;
118
+ const height = 2;
119
+ const bytesPerRow = 256;
120
+ const frame = makeFloat16Frame(
121
+ width,
122
+ height,
123
+ { r: F16_HALF, g: F16_HALF, b: F16_HALF, a: 0 },
124
+ bytesPerRow,
125
+ );
126
+ const out = float16ToPqRgb(frame, bytesPerRow, width, height);
127
+ expect(out.length).toBe(width * height * 6);
128
+ // Every R component should be the same non-zero value (uniform input).
129
+ const expected = out.readUInt16LE(0);
130
+ expect(expected).toBeGreaterThan(0);
131
+ for (let pixel = 0; pixel < width * height; pixel++) {
132
+ expect(out.readUInt16LE(pixel * 6)).toBe(expected);
133
+ }
134
+ });
135
+
136
+ it("ignores garbage bytes in the row padding region", () => {
137
+ // Stuff junk into the trailing padding to make sure the PQ encoder
138
+ // walks via bytesPerRow stride and not via raw buffer position.
139
+ const width = 2;
140
+ const height = 2;
141
+ const bytesPerRow = 64;
142
+ const frame = makeFloat16Frame(
143
+ width,
144
+ height,
145
+ { r: F16_ZERO, g: F16_ZERO, b: F16_ZERO, a: F16_ZERO },
146
+ bytesPerRow,
147
+ );
148
+ for (let y = 0; y < height; y++) {
149
+ const padStart = y * bytesPerRow + width * 8;
150
+ for (let i = padStart; i < (y + 1) * bytesPerRow; i++) {
151
+ frame[i] = 0xff;
152
+ }
153
+ }
154
+ const out = float16ToPqRgb(frame, bytesPerRow, width, height);
155
+ for (let i = 0; i < out.length; i += 2) {
156
+ expect(out.readUInt16LE(i)).toBe(0);
157
+ }
158
+ });
159
+ });
@@ -0,0 +1,354 @@
1
+ /// <reference types="@webgpu/types" />
2
+ /**
3
+ * HDR Capture Service
4
+ *
5
+ * Captures HDR video frames via WebGPU float16 readback.
6
+ *
7
+ * The pipeline:
8
+ * 1. FFmpeg extracts raw HDR pixels (rgba64le) from video sources
9
+ * 2. Node converts HLG/PQ signal → linear light → float16
10
+ * 3. writeTexture uploads float16 data to WebGPU rgba16float texture
11
+ * 4. (Optional) WebGPU shader applies GSAP CSS transform
12
+ * 5. readback extracts float16 RGBA via base64 transfer
13
+ * 6. Node converts linear float16 → PQ signal → pipe to FFmpeg H.265
14
+ *
15
+ * Requirements:
16
+ * - Headed Chrome (not headless) — WebGPU unavailable in headless mode
17
+ * - GPU access (Metal on macOS, Vulkan+NVIDIA on Linux)
18
+ *
19
+ * Performance: ~6 fps at 1080x1920 via base64 transfer.
20
+ */
21
+
22
+ import type { Page, Browser, PuppeteerNode } from "puppeteer-core";
23
+ import { existsSync, readdirSync } from "fs";
24
+ import { join } from "path";
25
+ import { homedir } from "os";
26
+
27
+ // ── PQ (SMPTE 2084) OETF ─────────────────────────────────────────────────────
28
+
29
+ const PQ_M1 = 0.1593017578125;
30
+ const PQ_M2 = 78.84375;
31
+ const PQ_C1 = 0.8359375;
32
+ const PQ_C2 = 18.8515625;
33
+ const PQ_C3 = 18.6875;
34
+ const PQ_MAX_NITS = 10000.0;
35
+ const SDR_NITS = 203.0;
36
+
37
+ function linearToPQ(L: number): number {
38
+ const Lp = Math.max(0, (L * SDR_NITS) / PQ_MAX_NITS);
39
+ const Lm1 = Math.pow(Lp, PQ_M1);
40
+ return Math.pow((PQ_C1 + PQ_C2 * Lm1) / (1.0 + PQ_C3 * Lm1), PQ_M2);
41
+ }
42
+
43
+ function float16Decode(h: number): number {
44
+ const sign = (h >> 15) & 1;
45
+ const exp = (h >> 10) & 0x1f;
46
+ const frac = h & 0x3ff;
47
+ if (exp === 0) return (sign ? -1 : 1) * Math.pow(2, -14) * (frac / 1024);
48
+ if (exp === 31) return frac ? NaN : sign ? -Infinity : Infinity;
49
+ return (sign ? -1 : 1) * Math.pow(2, exp - 15) * (1 + frac / 1024);
50
+ }
51
+
52
+ // ── Browser-side interface ────────────────────────────────────────────────────
53
+
54
+ interface HdrCaptureRuntime {
55
+ uploadAndReadback(float16Base64: string): Promise<{ base64: string; bytesPerRow: number }>;
56
+ }
57
+
58
+ // ── Initialization ────────────────────────────────────────────────────────────
59
+
60
+ /**
61
+ * Inject the WebGPU HDR readback runtime into the page.
62
+ *
63
+ * Creates an rgba16float render texture that accepts writeTexture uploads
64
+ * and provides readback via base64 transfer.
65
+ */
66
+ export async function initHdrReadback(page: Page, width: number, height: number): Promise<boolean> {
67
+ return page.evaluate(
68
+ async (w: number, h: number): Promise<boolean> => {
69
+ if (!navigator.gpu) return false;
70
+
71
+ const adapter = await navigator.gpu.requestAdapter();
72
+ if (!adapter) return false;
73
+
74
+ const device = await adapter.requestDevice();
75
+
76
+ const bytesPerPixel = 8; // rgba16float = 4 channels × 2 bytes
77
+ const bytesPerRow = Math.ceil((w * bytesPerPixel) / 256) * 256;
78
+
79
+ // Render texture — includes COPY_DST for writeTexture uploads
80
+ const renderTexture = device.createTexture({
81
+ size: [w, h],
82
+ format: "rgba16float",
83
+ usage:
84
+ GPUTextureUsage.RENDER_ATTACHMENT |
85
+ GPUTextureUsage.COPY_SRC |
86
+ GPUTextureUsage.COPY_DST |
87
+ GPUTextureUsage.TEXTURE_BINDING,
88
+ });
89
+
90
+ const readBuffer = device.createBuffer({
91
+ size: bytesPerRow * h,
92
+ usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ,
93
+ });
94
+
95
+ const captureRuntime = {
96
+ device,
97
+ renderTexture,
98
+ readBuffer,
99
+ bytesPerRow,
100
+ width: w,
101
+ height: h,
102
+
103
+ /**
104
+ * Upload pre-converted float16 RGBA data and read it back.
105
+ * The float16 data must be row-aligned to bytesPerRow.
106
+ *
107
+ * Input: base64-encoded Uint16Array (float16 RGBA, row-padded)
108
+ * Output: base64-encoded readback of the same texture
109
+ */
110
+ async uploadAndReadback(
111
+ float16Base64: string,
112
+ ): Promise<{ base64: string; bytesPerRow: number }> {
113
+ // Decode base64 → Uint8Array
114
+ const binary = atob(float16Base64);
115
+ const bytes = new Uint8Array(binary.length);
116
+ for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
117
+
118
+ // Upload to texture
119
+ device.queue.writeTexture(
120
+ { texture: renderTexture },
121
+ bytes.buffer,
122
+ { bytesPerRow, rowsPerImage: h },
123
+ [w, h],
124
+ );
125
+
126
+ // Readback
127
+ const encoder = device.createCommandEncoder();
128
+ encoder.copyTextureToBuffer(
129
+ { texture: renderTexture },
130
+ { buffer: readBuffer, bytesPerRow },
131
+ [w, h],
132
+ );
133
+ device.queue.submit([encoder.finish()]);
134
+
135
+ await readBuffer.mapAsync(GPUMapMode.READ);
136
+ const readBytes = new Uint8Array(readBuffer.getMappedRange().slice(0));
137
+ readBuffer.unmap();
138
+
139
+ // Base64 encode in chunks
140
+ let b64 = "";
141
+ const chunkSize = 32768;
142
+ for (let i = 0; i < readBytes.length; i += chunkSize) {
143
+ const slice = readBytes.subarray(i, Math.min(i + chunkSize, readBytes.length));
144
+ b64 += String.fromCharCode(...slice);
145
+ }
146
+
147
+ return { base64: btoa(b64), bytesPerRow };
148
+ },
149
+ };
150
+
151
+ (window as unknown as Record<string, unknown>).__hfHdrCapture = captureRuntime;
152
+ return true;
153
+ },
154
+ width,
155
+ height,
156
+ );
157
+ }
158
+
159
+ // ── HDR frame conversion ──────────────────────────────────────────────────────
160
+
161
+ /**
162
+ * Convert raw rgba64le pixels (from FFmpeg) to a base64 string for FFmpeg encoding.
163
+ *
164
+ * For HLG sources: the pixel values are already HLG-encoded. We pass them through
165
+ * as-is (normalized to 16-bit) and tag the output as HLG. No OETF conversion needed —
166
+ * the HLG signal values ARE the correct encoding. Converting to linear and back to
167
+ * PQ produces worse results because every viewer's PQ→display tone-mapping differs
168
+ * from its HLG→display tone-mapping.
169
+ *
170
+ * The WebGPU round-trip is skipped for pass-through — the pixels go directly from
171
+ * FFmpeg extraction to FFmpeg encoding. WebGPU is only needed when transforms
172
+ * (scale, rotate, opacity from GSAP) must be applied to the HDR pixels.
173
+ */
174
+ export function convertHdrFrameToRgb48le(
175
+ rawRgba64le: Buffer,
176
+ width: number,
177
+ height: number,
178
+ ): Buffer {
179
+ const input = new Uint16Array(
180
+ rawRgba64le.buffer,
181
+ rawRgba64le.byteOffset,
182
+ rawRgba64le.byteLength / 2,
183
+ );
184
+
185
+ // Convert RGBA → RGB (drop alpha) for rgb48le output
186
+ const output = Buffer.alloc(width * height * 6);
187
+
188
+ for (let y = 0; y < height; y++) {
189
+ for (let x = 0; x < width; x++) {
190
+ const srcIdx = (y * width + x) * 4;
191
+ const dstIdx = (y * width + x) * 6;
192
+ output.writeUInt16LE(input[srcIdx] ?? 0, dstIdx);
193
+ output.writeUInt16LE(input[srcIdx + 1] ?? 0, dstIdx + 2);
194
+ output.writeUInt16LE(input[srcIdx + 2] ?? 0, dstIdx + 4);
195
+ }
196
+ }
197
+
198
+ return output;
199
+ }
200
+
201
+ // ── Frame upload + readback ───────────────────────────────────────────────────
202
+
203
+ /**
204
+ * Upload a float16 frame to WebGPU and read it back.
205
+ * Call after converting with convertHdrFrameToFloat16Base64.
206
+ */
207
+ export async function uploadAndReadbackHdrFrame(
208
+ page: Page,
209
+ float16Base64: string,
210
+ ): Promise<{ rawBuffer: Buffer; bytesPerRow: number }> {
211
+ const result = await page.evaluate(
212
+ async (b64: string): Promise<{ base64: string; bytesPerRow: number }> => {
213
+ const hdr = (window as unknown as Record<string, unknown>).__hfHdrCapture as
214
+ | HdrCaptureRuntime
215
+ | undefined;
216
+ if (!hdr) throw new Error("HDR capture not initialized");
217
+ return hdr.uploadAndReadback(b64);
218
+ },
219
+ float16Base64,
220
+ );
221
+
222
+ return {
223
+ rawBuffer: Buffer.from(result.base64, "base64"),
224
+ bytesPerRow: result.bytesPerRow,
225
+ };
226
+ }
227
+
228
+ // ── PQ conversion ─────────────────────────────────────────────────────────────
229
+
230
+ /**
231
+ * Convert float16 RGBA readback to PQ-encoded rgb48le for FFmpeg.
232
+ */
233
+ export function float16ToPqRgb(
234
+ rawBuffer: Buffer,
235
+ bytesPerRow: number,
236
+ width: number,
237
+ height: number,
238
+ ): Buffer {
239
+ const data = new Uint16Array(rawBuffer.buffer, rawBuffer.byteOffset, rawBuffer.byteLength / 2);
240
+ const channelsPerRow = bytesPerRow / 2;
241
+ const output = Buffer.alloc(width * height * 6);
242
+
243
+ for (let y = 0; y < height; y++) {
244
+ for (let x = 0; x < width; x++) {
245
+ const srcIdx = y * channelsPerRow + x * 4;
246
+ const r = float16Decode(data[srcIdx] ?? 0);
247
+ const g = float16Decode(data[srcIdx + 1] ?? 0);
248
+ const b = float16Decode(data[srcIdx + 2] ?? 0);
249
+
250
+ const dstIdx = (y * width + x) * 6;
251
+ output.writeUInt16LE(Math.round(Math.min(1.0, linearToPQ(r)) * 65535), dstIdx);
252
+ output.writeUInt16LE(Math.round(Math.min(1.0, linearToPQ(g)) * 65535), dstIdx + 2);
253
+ output.writeUInt16LE(Math.round(Math.min(1.0, linearToPQ(b)) * 65535), dstIdx + 4);
254
+ }
255
+ }
256
+
257
+ return output;
258
+ }
259
+
260
+ // ── Chrome launch ─────────────────────────────────────────────────────────────
261
+
262
+ function resolveHeadedChromePath(): string | undefined {
263
+ const baseDir = join(homedir(), ".cache", "puppeteer", "chrome");
264
+ if (!existsSync(baseDir)) return undefined;
265
+ const versions = readdirSync(baseDir).sort().reverse();
266
+ for (const version of versions) {
267
+ const candidates = [
268
+ join(
269
+ baseDir,
270
+ version,
271
+ "chrome-mac-arm64",
272
+ "Google Chrome for Testing.app",
273
+ "Contents",
274
+ "MacOS",
275
+ "Google Chrome for Testing",
276
+ ),
277
+ join(
278
+ baseDir,
279
+ version,
280
+ "chrome-mac-x64",
281
+ "Google Chrome for Testing.app",
282
+ "Contents",
283
+ "MacOS",
284
+ "Google Chrome for Testing",
285
+ ),
286
+ join(baseDir, version, "chrome-linux64", "chrome"),
287
+ join(baseDir, version, "chrome-win64", "chrome.exe"),
288
+ ];
289
+ for (const binary of candidates) {
290
+ if (existsSync(binary)) return binary;
291
+ }
292
+ }
293
+ return undefined;
294
+ }
295
+
296
+ /**
297
+ * Launch a headed Chrome browser with WebGPU enabled.
298
+ */
299
+ export async function launchHdrBrowser(
300
+ width: number,
301
+ height: number,
302
+ ): Promise<{ browser: Browser; page: Page }> {
303
+ let ppt: PuppeteerNode | undefined;
304
+ try {
305
+ const mod = await import("puppeteer" as string);
306
+ ppt = mod.default;
307
+ } catch (err) {
308
+ const code = (err as NodeJS.ErrnoException | undefined)?.code;
309
+ if (code !== "ERR_MODULE_NOT_FOUND" && code !== "MODULE_NOT_FOUND") {
310
+ throw err;
311
+ }
312
+ const mod = await import("puppeteer-core");
313
+ ppt = mod.default;
314
+ }
315
+ if (!ppt) throw new Error("Neither puppeteer nor puppeteer-core found");
316
+
317
+ const chromePath = resolveHeadedChromePath();
318
+ if (!chromePath) {
319
+ throw new Error(
320
+ "[HDR] No Chrome binary found. Install: npx @puppeteer/browsers install chrome@stable",
321
+ );
322
+ }
323
+
324
+ const browser = await ppt.launch({
325
+ headless: false,
326
+ executablePath: chromePath,
327
+ args: buildHdrChromeArgs(width, height),
328
+ });
329
+
330
+ const page = await browser.newPage();
331
+ await page.setViewport({ width, height });
332
+
333
+ return { browser, page };
334
+ }
335
+
336
+ export function buildHdrChromeArgs(width: number, height: number): string[] {
337
+ return [
338
+ "--enable-unsafe-webgpu",
339
+ "--no-sandbox",
340
+ "--disable-setuid-sandbox",
341
+ "--window-position=-10000,-10000",
342
+ `--window-size=${width},${height}`,
343
+ "--disable-background-timer-throttling",
344
+ "--disable-backgrounding-occluded-windows",
345
+ "--disable-renderer-backgrounding",
346
+ "--disable-background-media-suspend",
347
+ "--disable-extensions",
348
+ "--disable-component-update",
349
+ "--disable-default-apps",
350
+ "--disable-sync",
351
+ "--no-zygote",
352
+ "--force-gpu-mem-available-mb=4096",
353
+ ];
354
+ }