@hyperframes/engine 0.4.6 → 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 (74) 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/hdrCapture.d.ts +62 -0
  19. package/dist/services/hdrCapture.d.ts.map +1 -0
  20. package/dist/services/hdrCapture.js +259 -0
  21. package/dist/services/hdrCapture.js.map +1 -0
  22. package/dist/services/screenshotService.d.ts +34 -0
  23. package/dist/services/screenshotService.d.ts.map +1 -1
  24. package/dist/services/screenshotService.js +97 -19
  25. package/dist/services/screenshotService.js.map +1 -1
  26. package/dist/services/streamingEncoder.d.ts +18 -3
  27. package/dist/services/streamingEncoder.d.ts.map +1 -1
  28. package/dist/services/streamingEncoder.js +104 -50
  29. package/dist/services/streamingEncoder.js.map +1 -1
  30. package/dist/services/videoFrameExtractor.d.ts.map +1 -1
  31. package/dist/services/videoFrameExtractor.js +109 -18
  32. package/dist/services/videoFrameExtractor.js.map +1 -1
  33. package/dist/services/videoFrameInjector.d.ts +54 -0
  34. package/dist/services/videoFrameInjector.d.ts.map +1 -1
  35. package/dist/services/videoFrameInjector.js +159 -0
  36. package/dist/services/videoFrameInjector.js.map +1 -1
  37. package/dist/utils/alphaBlit.d.ts +105 -0
  38. package/dist/utils/alphaBlit.d.ts.map +1 -0
  39. package/dist/utils/alphaBlit.js +550 -0
  40. package/dist/utils/alphaBlit.js.map +1 -0
  41. package/dist/utils/ffprobe.d.ts +10 -0
  42. package/dist/utils/ffprobe.d.ts.map +1 -1
  43. package/dist/utils/ffprobe.js +7 -0
  44. package/dist/utils/ffprobe.js.map +1 -1
  45. package/dist/utils/hdr.d.ts +82 -0
  46. package/dist/utils/hdr.d.ts.map +1 -0
  47. package/dist/utils/hdr.js +87 -0
  48. package/dist/utils/hdr.js.map +1 -0
  49. package/dist/utils/layerCompositor.d.ts +36 -0
  50. package/dist/utils/layerCompositor.d.ts.map +1 -0
  51. package/dist/utils/layerCompositor.js +49 -0
  52. package/dist/utils/layerCompositor.js.map +1 -0
  53. package/package.json +3 -2
  54. package/src/config.ts +16 -0
  55. package/src/index.ts +42 -0
  56. package/src/services/browserManager.ts +6 -3
  57. package/src/services/chunkEncoder.test.ts +88 -0
  58. package/src/services/chunkEncoder.ts +35 -9
  59. package/src/services/chunkEncoder.types.ts +3 -0
  60. package/src/services/hdrCapture.test.ts +159 -0
  61. package/src/services/hdrCapture.ts +354 -0
  62. package/src/services/screenshotService.ts +102 -17
  63. package/src/services/streamingEncoder.test.ts +228 -0
  64. package/src/services/streamingEncoder.ts +153 -63
  65. package/src/services/videoFrameExtractor.ts +135 -31
  66. package/src/services/videoFrameInjector.ts +200 -0
  67. package/src/utils/alphaBlit.test.ts +993 -0
  68. package/src/utils/alphaBlit.ts +643 -0
  69. package/src/utils/ffprobe.ts +22 -0
  70. package/src/utils/hdr.test.ts +191 -0
  71. package/src/utils/hdr.ts +137 -0
  72. package/src/utils/layerCompositor.test.ts +141 -0
  73. package/src/utils/layerCompositor.ts +58 -0
  74. package/tsconfig.json +2 -1
@@ -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
+ }
@@ -133,6 +133,82 @@ export async function pageScreenshotCapture(page: Page, options: CaptureOptions)
133
133
  return Buffer.from(result.data, "base64");
134
134
  }
135
135
 
136
+ /**
137
+ * Capture a screenshot with transparent background (PNG + alpha channel).
138
+ *
139
+ * Used in the two-pass HDR compositing pipeline — captures DOM content
140
+ * (text, graphics, SDR overlays) with transparency where the background shows,
141
+ * so it can be overlaid on top of native HDR video frames in FFmpeg.
142
+ *
143
+ * Sets and restores the background color override on every call. For sessions
144
+ * that capture many frames, prefer calling initTransparentBackground() once
145
+ * at session init, then captureAlphaPng() per frame to avoid the 2× CDP
146
+ * round-trip overhead.
147
+ */
148
+ export async function captureScreenshotWithAlpha(
149
+ page: Page,
150
+ width: number,
151
+ height: number,
152
+ ): Promise<Buffer> {
153
+ const client = await getCdpSession(page);
154
+ // Force transparent background so the screenshot has a real alpha channel
155
+ await client.send("Emulation.setDefaultBackgroundColorOverride", {
156
+ color: { r: 0, g: 0, b: 0, a: 0 },
157
+ });
158
+ try {
159
+ const result = await client.send("Page.captureScreenshot", {
160
+ format: "png",
161
+ fromSurface: true,
162
+ captureBeyondViewport: false,
163
+ optimizeForSpeed: false, // `true` uses a zero-alpha-aware fast path that crushes real alpha values — observed empirically, CDP docs don't spell it out
164
+ clip: { x: 0, y: 0, width, height, scale: 1 },
165
+ });
166
+ return Buffer.from(result.data, "base64");
167
+ } finally {
168
+ // Restore opaque background even if captureScreenshot throws, otherwise
169
+ // subsequent opaque captures keep a transparent background.
170
+ await client.send("Emulation.setDefaultBackgroundColorOverride", {}).catch(() => {});
171
+ }
172
+ }
173
+
174
+ /**
175
+ * Set the page background to transparent once for a dedicated HDR DOM session.
176
+ *
177
+ * Call this once after session initialization. Then use captureAlphaPng() per
178
+ * frame instead of captureScreenshotWithAlpha() to skip the per-frame CDP
179
+ * background override round-trips.
180
+ *
181
+ * Only use on sessions that are exclusively dedicated to transparent capture
182
+ * (e.g., the HDR two-pass DOM layer session) — the background will stay
183
+ * transparent for the lifetime of the session.
184
+ */
185
+ export async function initTransparentBackground(page: Page): Promise<void> {
186
+ const client = await getCdpSession(page);
187
+ await client.send("Emulation.setDefaultBackgroundColorOverride", {
188
+ color: { r: 0, g: 0, b: 0, a: 0 },
189
+ });
190
+ }
191
+
192
+ /**
193
+ * Capture a transparent-background PNG screenshot without setting the
194
+ * background color override. Requires initTransparentBackground() to have
195
+ * been called once on this session.
196
+ *
197
+ * Faster than captureScreenshotWithAlpha() for per-frame use in the HDR
198
+ * two-pass compositing loop.
199
+ */
200
+ export async function captureAlphaPng(page: Page, width: number, height: number): Promise<Buffer> {
201
+ const client = await getCdpSession(page);
202
+ const result = await client.send("Page.captureScreenshot", {
203
+ format: "png",
204
+ fromSurface: true,
205
+ captureBeyondViewport: false,
206
+ optimizeForSpeed: false, // must be false to preserve alpha
207
+ clip: { x: 0, y: 0, width, height, scale: 1 },
208
+ });
209
+ return Buffer.from(result.data, "base64");
210
+ }
211
+
136
212
  export async function injectVideoFramesBatch(
137
213
  page: Page,
138
214
  updates: Array<{ videoId: string; dataUri: string }>,
@@ -160,16 +236,11 @@ export async function injectVideoFramesBatch(
160
236
  }
161
237
  if (!img) continue;
162
238
 
163
- if (!sourceIsStatic) {
164
- img.style.position = computedStyle.position;
165
- img.style.width = computedStyle.width;
166
- img.style.height = computedStyle.height;
167
- img.style.top = computedStyle.top;
168
- img.style.left = computedStyle.left;
169
- img.style.right = computedStyle.right;
170
- img.style.bottom = computedStyle.bottom;
171
- img.style.inset = computedStyle.inset;
172
- } else {
239
+ // Always use absolute positioning so the <img> overlays the <video>
240
+ // instead of flowing below it. With position:relative, both elements
241
+ // stack vertically — the <img> lands below the video and gets clipped
242
+ // by any overflow:hidden ancestor (e.g., border-radius wrappers).
243
+ {
173
244
  const videoRect = video.getBoundingClientRect();
174
245
  const offsetLeft = Number.isFinite(video.offsetLeft) ? video.offsetLeft : 0;
175
246
  const offsetTop = Number.isFinite(video.offsetTop) ? video.offsetTop : 0;
@@ -235,14 +306,28 @@ export async function syncVideoFrameVisibility(
235
306
  const active = new Set(ids);
236
307
  const videos = Array.from(document.querySelectorAll("video[data-start]")) as HTMLVideoElement[];
237
308
  for (const video of videos) {
238
- if (active.has(video.id)) continue;
239
- video.style.removeProperty("display");
240
- video.style.setProperty("visibility", "hidden", "important");
241
- video.style.setProperty("opacity", "0", "important");
242
- video.style.setProperty("pointer-events", "none", "important");
243
309
  const img = video.nextElementSibling as HTMLElement | null;
244
- if (img && img.classList.contains("__render_frame__")) {
245
- img.style.visibility = "hidden";
310
+ const hasImg = img && img.classList.contains("__render_frame__");
311
+ if (active.has(video.id)) {
312
+ // Active video: show injected <img>, hide native <video>.
313
+ // Do NOT clobber inline opacity here — GSAP-controlled opacity must
314
+ // survive until injectVideoFramesBatch reads it via getComputedStyle.
315
+ // visibility:hidden alone hides the native element without affecting
316
+ // its computed opacity.
317
+ video.style.setProperty("visibility", "hidden", "important");
318
+ video.style.setProperty("pointer-events", "none", "important");
319
+ if (hasImg) {
320
+ img.style.visibility = "visible";
321
+ }
322
+ } else {
323
+ // Inactive video: hide both
324
+ video.style.removeProperty("display");
325
+ video.style.setProperty("visibility", "hidden", "important");
326
+ video.style.setProperty("opacity", "0", "important");
327
+ video.style.setProperty("pointer-events", "none", "important");
328
+ if (hasImg) {
329
+ img.style.visibility = "hidden";
330
+ }
246
331
  }
247
332
  }
248
333
  }, activeVideoIds);