@bb-studio/exr 0.2.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,3 +1,156 @@
1
+ // src/browser/exrWorkerSession.ts
2
+ function getDefaultWorkerFactory() {
3
+ return {
4
+ createZipWorker: () => new Worker(new URL("./zipDecodeWorker.js", import.meta.url), { type: "module" }),
5
+ createDwaWorker: () => new Worker(new URL("./dwaDecodeWorker.js", import.meta.url), { type: "module" })
6
+ };
7
+ }
8
+ var ExrWorkerSession = class {
9
+ constructor(maxWorkers = 8, factory = getDefaultWorkerFactory()) {
10
+ this.maxWorkers = maxWorkers;
11
+ this.factory = factory;
12
+ if (!Number.isSafeInteger(maxWorkers) || maxWorkers < 1 || maxWorkers > 16)
13
+ throw new RangeError("EXR session capacity must be an integer from 1 to 16.");
14
+ }
15
+ controller = new AbortController();
16
+ idle = [];
17
+ active = /* @__PURE__ */ new Set();
18
+ pending = [];
19
+ activeCount = 0;
20
+ draining = false;
21
+ get signal() {
22
+ return this.controller.signal;
23
+ }
24
+ getStatus() {
25
+ return { active: this.activeCount, idle: this.idle.length, waiting: this.pending.length };
26
+ }
27
+ /** @internal Used by the ordered scanline decoder. */
28
+ acquire(kind, requested, signal) {
29
+ const lifetime = AbortSignal.any([signal, this.signal]);
30
+ lifetime.throwIfAborted();
31
+ if (!Number.isSafeInteger(requested) || requested < 1)
32
+ throw new RangeError("Invalid EXR worker cohort size.");
33
+ const count = Math.min(requested, this.maxWorkers);
34
+ return new Promise((resolve, reject) => {
35
+ const entry = {
36
+ kind,
37
+ count,
38
+ signal: lifetime,
39
+ resolve,
40
+ reject,
41
+ abort: () => {
42
+ const index = this.pending.indexOf(entry);
43
+ if (index < 0) return;
44
+ this.pending.splice(index, 1);
45
+ lifetime.removeEventListener("abort", entry.abort);
46
+ reject(lifetime.reason);
47
+ this.drain();
48
+ }
49
+ };
50
+ this.pending.push(entry);
51
+ lifetime.addEventListener("abort", entry.abort, { once: true });
52
+ this.drain();
53
+ });
54
+ }
55
+ drain() {
56
+ if (this.draining || this.signal.aborted) return;
57
+ this.draining = true;
58
+ try {
59
+ while (this.pending.length && !this.signal.aborted) {
60
+ const entry = this.pending[0];
61
+ if (this.activeCount + entry.count > this.maxWorkers) break;
62
+ this.pending.shift();
63
+ entry.signal.removeEventListener("abort", entry.abort);
64
+ const slots = [];
65
+ let reused = 0;
66
+ try {
67
+ entry.signal.throwIfAborted();
68
+ while (slots.length < entry.count) {
69
+ const index = this.idle.findIndex((slot) => slot.kind === entry.kind);
70
+ if (index >= 0) {
71
+ const slot = this.idle.splice(index, 1)[0];
72
+ slot.worker.onerror = slot.worker.onmessageerror = null;
73
+ slots.push(slot);
74
+ reused++;
75
+ } else {
76
+ if (this.activeCount + slots.length + this.idle.length >= this.maxWorkers)
77
+ this.idle.pop().worker.terminate();
78
+ slots.push({
79
+ kind: entry.kind,
80
+ worker: entry.kind === "dwa" ? this.factory.createDwaWorker() : this.factory.createZipWorker()
81
+ });
82
+ }
83
+ }
84
+ entry.signal.throwIfAborted();
85
+ const lease = {
86
+ workers: slots.map((slot) => slot.worker),
87
+ reused,
88
+ release: (success) => {
89
+ if (!this.active.delete(lease)) return;
90
+ this.activeCount -= slots.length;
91
+ for (const slot of slots) {
92
+ const worker = slot.worker;
93
+ worker.onmessage = worker.onerror = worker.onmessageerror = null;
94
+ if (success && !entry.signal.aborted && !this.signal.aborted) {
95
+ try {
96
+ worker.postMessage({ type: "reset" });
97
+ this.idle.push(slot);
98
+ const discard = () => {
99
+ const index = this.idle.indexOf(slot);
100
+ if (index >= 0) {
101
+ this.idle.splice(index, 1);
102
+ worker.terminate();
103
+ }
104
+ };
105
+ worker.onerror = worker.onmessageerror = discard;
106
+ continue;
107
+ } catch {
108
+ }
109
+ }
110
+ worker.terminate();
111
+ }
112
+ this.drain();
113
+ }
114
+ };
115
+ this.active.add(lease);
116
+ this.activeCount += slots.length;
117
+ entry.resolve(lease);
118
+ } catch (error) {
119
+ for (const slot of slots) slot.worker.terminate();
120
+ entry.reject(error);
121
+ }
122
+ }
123
+ } finally {
124
+ this.draining = false;
125
+ }
126
+ }
127
+ /**
128
+ * Release only idle workers at an explicit owner-controlled resource
129
+ * boundary. Active leases and waiting requests remain unchanged.
130
+ * The session remains usable and creates replacements on demand.
131
+ */
132
+ releaseIdle() {
133
+ const slots = this.idle.splice(0);
134
+ for (const { worker } of slots) {
135
+ worker.onmessage = worker.onerror = worker.onmessageerror = null;
136
+ worker.terminate();
137
+ }
138
+ return slots.length;
139
+ }
140
+ /** Cancel active and waiting work and destroy every owned worker. */
141
+ dispose() {
142
+ if (this.signal.aborted) return;
143
+ this.controller.abort(new DOMException("EXR worker session disposed.", "AbortError"));
144
+ for (const lease of [...this.active]) lease.release(false);
145
+ this.releaseIdle();
146
+ }
147
+ };
148
+
149
+ // src/browser/workerDecodeTiming.ts
150
+ function workerDecodeClock() {
151
+ return performance.timeOrigin + performance.now();
152
+ }
153
+
1
154
  // src/shared/constants.ts
2
155
  var EXR_MAGIC = 20000630;
3
156
  var COMPRESSION_NAMES = {
@@ -77,6 +230,58 @@ function float16ToFloat32(h) {
77
230
  return HALF_TO_FLOAT_TABLE[h & 65535];
78
231
  }
79
232
 
233
+ // src/reader/rgbaChannels.ts
234
+ function normalizeChannelName(name) {
235
+ return name.split(".").pop()?.toUpperCase() ?? "";
236
+ }
237
+ function pickChannel(channels, aliases) {
238
+ for (const alias of aliases) {
239
+ const exact = channels[alias];
240
+ if (exact) return exact;
241
+ }
242
+ const normalizedAliases = new Set(aliases.map((alias) => alias.toUpperCase()));
243
+ for (const [name, channel] of Object.entries(channels)) {
244
+ if (normalizedAliases.has(normalizeChannelName(name))) return channel;
245
+ }
246
+ return void 0;
247
+ }
248
+ function selectRgbaChannels(channels) {
249
+ const red = pickChannel(channels, ["R", "RED"]) ?? Object.values(channels)[0];
250
+ const luma = pickChannel(channels, ["Y", "LUMA", "LUMINANCE"]);
251
+ return [
252
+ red,
253
+ pickChannel(channels, ["G", "GREEN"]) ?? luma ?? red,
254
+ pickChannel(channels, ["B", "BLUE"]) ?? luma ?? red,
255
+ pickChannel(channels, ["A", "ALPHA"])
256
+ ];
257
+ }
258
+ function getExrRgbaStoragePrecision(channels, channelNames) {
259
+ const names = channelNames && new Set(channelNames);
260
+ const selected = selectRgbaChannels(
261
+ Object.fromEntries(
262
+ channels.filter((channel) => !names || names.has(channel.name)).map((channel) => [channel.name, channel])
263
+ )
264
+ );
265
+ return selected.every((channel) => !channel || channel.pixelType === 1) ? "float16" : "float32";
266
+ }
267
+
268
+ // src/reader/sampleMap.ts
269
+ function clamp(value, min, max) {
270
+ if (value < min) return min;
271
+ if (value > max) return max;
272
+ return value;
273
+ }
274
+ function buildNearestSampleMap(length, worldMin, sampleOrigin, sampling, sampledLength) {
275
+ const output = new Int32Array(length);
276
+ if (sampledLength <= 0) return output;
277
+ for (let i = 0; i < length; i++) {
278
+ const world = worldMin + i;
279
+ const sample = Math.round((world - sampleOrigin) / sampling);
280
+ output[i] = clamp(sample, 0, sampledLength - 1);
281
+ }
282
+ return output;
283
+ }
284
+
80
285
  // src/reader/compression/b44.ts
81
286
  var HALF_VALUES_PER_BLOCK = 16;
82
287
  var B44_BLOCK_SIZE = 14;
@@ -304,7 +509,7 @@ function decodeB44Block(context) {
304
509
  if (!isSampledCoordinate(y, layout.sampleOriginY, layout.ySampling)) {
305
510
  continue;
306
511
  }
307
- if (layout.firstChunkSampleY < 0 || y < layout.firstChunkSampleY) {
512
+ if (y < layout.firstChunkSampleY) {
308
513
  continue;
309
514
  }
310
515
  const sampledRow = Math.floor((y - layout.firstChunkSampleY) / layout.ySampling);
@@ -1261,9 +1466,7 @@ function decodeDwaChunk(context) {
1261
1466
  if (decodedWords !== header.totalAcUncompressedCount) {
1262
1467
  throw new Error("Invalid DWA AC DEFLATE payload length.");
1263
1468
  }
1264
- const decodedView = new Uint16Array(decoded.buffer, decoded.byteOffset, decodedWords);
1265
- acBuffer = new Uint16Array(decodedWords);
1266
- acBuffer.set(decodedView);
1469
+ acBuffer = new Uint16Array(decoded.buffer, decoded.byteOffset, decodedWords);
1267
1470
  cursor.value += header.acCompressedSize;
1268
1471
  break;
1269
1472
  }
@@ -1288,9 +1491,7 @@ function decodeDwaChunk(context) {
1288
1491
  if (dcWords !== header.totalDcUncompressedCount) {
1289
1492
  throw new Error("Invalid DWA DC payload length.");
1290
1493
  }
1291
- const dcView = new Uint16Array(dcBytes.buffer, dcBytes.byteOffset, dcWords);
1292
- dcBuffer = new Uint16Array(dcWords);
1293
- dcBuffer.set(dcView);
1494
+ dcBuffer = new Uint16Array(dcBytes.buffer, dcBytes.byteOffset, dcWords);
1294
1495
  cursor.value += header.dcCompressedSize;
1295
1496
  } else if (header.totalDcUncompressedCount !== 0) {
1296
1497
  throw new Error("Invalid DWA DC payload metadata.");
@@ -1306,9 +1507,7 @@ function decodeDwaChunk(context) {
1306
1507
  if (decoded.byteLength !== header.rleUncompressedSize) {
1307
1508
  throw new Error("Invalid DWA RLE intermediate payload length.");
1308
1509
  }
1309
- const decodedRle = decodeRunLength(decoded, header.rleRawSize);
1310
- rleBuffer = new Uint8Array(decodedRle.byteLength);
1311
- rleBuffer.set(decodedRle);
1510
+ rleBuffer = decodeRunLength(decoded, header.rleRawSize);
1312
1511
  cursor.value += header.rleCompressedSize;
1313
1512
  } else if (header.rleCompressedSize !== 0 || header.rleUncompressedSize !== 0) {
1314
1513
  throw new Error("Invalid DWA RLE payload metadata.");
@@ -2339,6 +2538,37 @@ function getSupportedReadCompressionText() {
2339
2538
  return Array.from(READ_COMPRESSION_HANDLERS.values()).map((handler) => handler.name).join(", ");
2340
2539
  }
2341
2540
 
2541
+ // src/reader/scanlineIndex.ts
2542
+ function scanlineOffsetTableOffset(structure, partIndex) {
2543
+ let offset = structure.headerEndOffset;
2544
+ for (let i = 0; i < partIndex; i++) {
2545
+ const prior = structure.parts[i];
2546
+ if (!prior.dataWindow) continue;
2547
+ const height = prior.dataWindow.yMax - prior.dataWindow.yMin + 1;
2548
+ offset += Math.ceil(height / getScanlineLinesPerBlock(prior.compression ?? 0)) * 8;
2549
+ }
2550
+ return offset;
2551
+ }
2552
+ function readScanlineOffsets(view, offset, count, partId) {
2553
+ if (!Number.isSafeInteger(offset) || offset < 0 || !Number.isSafeInteger(count) || count < 0 || offset + count * 8 > view.byteLength) {
2554
+ throw new ExrError("MALFORMED_OFFSET_TABLE", "Offset table is truncated or invalid.", {
2555
+ partId,
2556
+ offsetTablePtr: offset,
2557
+ chunkCount: count,
2558
+ size: view.byteLength
2559
+ });
2560
+ }
2561
+ const offsets = new Array(count);
2562
+ for (let i = 0; i < count; i++) {
2563
+ const low = view.getUint32(offset + i * 8, true);
2564
+ const high = view.getUint32(offset + i * 8 + 4, true);
2565
+ if (high > 2097151)
2566
+ throw new ExrError("MALFORMED_OFFSET_TABLE", "Chunk offset exceeds safe integer range.");
2567
+ offsets[i] = high * 4294967296 + low;
2568
+ }
2569
+ return offsets;
2570
+ }
2571
+
2342
2572
  // src/shared/binary.ts
2343
2573
  function toArrayBuffer(input) {
2344
2574
  if (input instanceof ArrayBuffer) {
@@ -2378,21 +2608,9 @@ function isSampledCoordinate4(value, firstSample, sampling) {
2378
2608
  if (value < firstSample) return false;
2379
2609
  return (value - firstSample) % sampling === 0;
2380
2610
  }
2381
- function toNumberOffset(low, high) {
2382
- if (high <= 2097151) {
2383
- return high * 4294967296 + low;
2384
- }
2385
- const combined = BigInt(low) + (BigInt(high) << 32n);
2386
- if (combined > BigInt(Number.MAX_SAFE_INTEGER)) {
2387
- throw new ExrError("MALFORMED_OFFSET_TABLE", "Chunk offset exceeds safe integer range.", {
2388
- offset: combined.toString()
2389
- });
2390
- }
2391
- return Number(combined);
2392
- }
2393
- function buildChannelMeta(part, selectedChannelNames) {
2394
- if (!part.dataWindow) return [];
2395
- const { xMin, xMax, yMin, yMax } = part.dataWindow;
2611
+ function buildChannelMeta(part, selectedChannelNames, outputWindow = part.dataWindow) {
2612
+ if (!part.dataWindow || !outputWindow) return [];
2613
+ const { xMin, xMax, yMin, yMax } = outputWindow;
2396
2614
  return part.channels.map((channel) => {
2397
2615
  const xSampling = channel.xSampling > 0 ? channel.xSampling : 1;
2398
2616
  const ySampling = channel.ySampling > 0 ? channel.ySampling : 1;
@@ -2413,7 +2631,9 @@ function buildChannelMeta(part, selectedChannelNames) {
2413
2631
  sampledHeight,
2414
2632
  sampleOriginX,
2415
2633
  sampleOriginY,
2416
- data: selected ? new Float32Array(sampledWidth * sampledHeight) : new Float32Array(0)
2634
+ data: new Float32Array(0),
2635
+ stride: 1,
2636
+ lane: 0
2417
2637
  };
2418
2638
  });
2419
2639
  }
@@ -2439,132 +2659,77 @@ function getExpectedUncompressedChunkSize(part, channelMeta, chunkY, linesInChun
2439
2659
  }
2440
2660
  function decodeRowIntoChannel(meta, blockData, blockPointer, rowOffset, blockView) {
2441
2661
  const destination = meta.data;
2662
+ const stride = meta.stride;
2663
+ let target = rowOffset * stride + meta.lane;
2442
2664
  const sampleCount = meta.sampledWidth;
2443
2665
  const sourceByteOffset = blockData.byteOffset + blockPointer;
2444
2666
  if (meta.pixelType === 1) {
2667
+ if (destination instanceof Uint16Array) {
2668
+ if ((sourceByteOffset & 1) === 0) {
2669
+ const source = new Uint16Array(blockData.buffer, sourceByteOffset, sampleCount);
2670
+ if (stride === 1) destination.set(source, target);
2671
+ else
2672
+ for (let i = 0; i < sampleCount; i++, target += stride) destination[target] = source[i];
2673
+ } else {
2674
+ for (let i = 0; i < sampleCount; i++, target += stride)
2675
+ destination[target] = blockView.getUint16(blockPointer + (i << 1), true);
2676
+ }
2677
+ return;
2678
+ }
2445
2679
  if ((sourceByteOffset & 1) === 0) {
2446
2680
  const source = new Uint16Array(blockData.buffer, sourceByteOffset, sampleCount);
2447
- for (let i = 0; i < sampleCount; i++) {
2448
- destination[rowOffset + i] = float16ToFloat32(source[i]);
2681
+ for (let i = 0; i < sampleCount; i++, target += stride) {
2682
+ destination[target] = float16ToFloat32(source[i]);
2449
2683
  }
2450
2684
  return;
2451
2685
  }
2452
- for (let i = 0; i < sampleCount; i++) {
2453
- destination[rowOffset + i] = float16ToFloat32(
2454
- blockView.getUint16(blockPointer + (i << 1), true)
2455
- );
2686
+ for (let i = 0; i < sampleCount; i++, target += stride) {
2687
+ destination[target] = float16ToFloat32(blockView.getUint16(blockPointer + (i << 1), true));
2456
2688
  }
2457
2689
  return;
2458
2690
  }
2691
+ if (destination instanceof Uint16Array) throw new Error("Non-HALF channel in native HALF output");
2459
2692
  if (meta.pixelType === 2) {
2460
2693
  if ((sourceByteOffset & 3) === 0) {
2461
2694
  const source = new Float32Array(blockData.buffer, sourceByteOffset, sampleCount);
2462
- destination.set(source, rowOffset);
2695
+ if (stride === 1) {
2696
+ destination.set(source, target);
2697
+ } else {
2698
+ for (let i = 0; i < sampleCount; i++, target += stride) {
2699
+ destination[target] = source[i];
2700
+ }
2701
+ }
2463
2702
  return;
2464
2703
  }
2465
- for (let i = 0; i < sampleCount; i++) {
2466
- destination[rowOffset + i] = blockView.getFloat32(blockPointer + (i << 2), true);
2704
+ for (let i = 0; i < sampleCount; i++, target += stride) {
2705
+ destination[target] = blockView.getFloat32(blockPointer + (i << 2), true);
2467
2706
  }
2468
2707
  return;
2469
2708
  }
2470
2709
  if ((sourceByteOffset & 3) === 0) {
2471
2710
  const source = new Uint32Array(blockData.buffer, sourceByteOffset, sampleCount);
2472
- for (let i = 0; i < sampleCount; i++) {
2473
- destination[rowOffset + i] = source[i] * INV_UINT32_MAX;
2711
+ for (let i = 0; i < sampleCount; i++, target += stride) {
2712
+ destination[target] = source[i] * INV_UINT32_MAX;
2474
2713
  }
2475
2714
  return;
2476
2715
  }
2477
- for (let i = 0; i < sampleCount; i++) {
2478
- destination[rowOffset + i] = blockView.getUint32(blockPointer + (i << 2), true) * INV_UINT32_MAX;
2716
+ for (let i = 0; i < sampleCount; i++, target += stride) {
2717
+ destination[target] = blockView.getUint32(blockPointer + (i << 2), true) * INV_UINT32_MAX;
2479
2718
  }
2480
2719
  }
2481
- function decodeExrPart(bufferInput, structure, options) {
2482
- const buffer = toArrayBuffer(bufferInput);
2720
+ function createScanlineDecoderWithOutput(part, isMultipart, options, window, createOutput) {
2483
2721
  const onEvent = options.onEvent;
2484
- const t0 = nowMs();
2485
- const partIndex = structure.parts.findIndex((part2) => part2.id === options.partId);
2486
- if (partIndex < 0) {
2487
- throw new ExrError("PART_NOT_FOUND", `Part ${options.partId} was not found in EXR structure.`, {
2488
- partId: options.partId
2489
- });
2490
- }
2491
- const part = structure.parts[partIndex];
2492
- if (part.type === "tiledimage") {
2493
- throw new ExrError("UNSUPPORTED_PART_TYPE", "Tiled EXR parts are not supported.", {
2494
- partId: options.partId,
2495
- type: part.type
2496
- });
2497
- }
2498
2722
  const compression = part.compression ?? 0;
2499
- const compressionHandler = getReadCompressionHandler(compression);
2500
- if (!compressionHandler) {
2501
- throw new ExrError(
2502
- "UNSUPPORTED_COMPRESSION",
2503
- `Unsupported compression. Supported: ${getSupportedReadCompressionText()}.`,
2504
- {
2505
- partId: options.partId,
2506
- compression
2507
- }
2508
- );
2509
- }
2510
- if (!part.dataWindow) {
2511
- throw new ExrError("MISSING_DATA_WINDOW", "EXR part is missing required dataWindow.", {
2512
- partId: options.partId
2513
- });
2723
+ const handler = getReadCompressionHandler(compression);
2724
+ if (!handler)
2725
+ throw new ExrError("UNSUPPORTED_COMPRESSION", "Unsupported compression.", { compression });
2726
+ const dataWindow = part.dataWindow;
2727
+ if (!dataWindow || window.xMin !== dataWindow.xMin || window.xMax !== dataWindow.xMax) {
2728
+ throw new ExrError("MISSING_DATA_WINDOW", "A full-width scanline band is required.");
2514
2729
  }
2515
- const view = new DataView(buffer);
2516
- const width = part.dataWindow.xMax - part.dataWindow.xMin + 1;
2517
- const height = part.dataWindow.yMax - part.dataWindow.yMin + 1;
2730
+ const compressionHandler = handler;
2731
+ const partWindow = dataWindow;
2518
2732
  const linesPerBlock = compressionHandler.linesPerBlock;
2519
- const chunkCount = Math.ceil(height / linesPerBlock);
2520
- emit(onEvent, {
2521
- phase: "decode",
2522
- level: "info",
2523
- code: "decode.setup",
2524
- message: `Decoder setup for part ${part.id}.`,
2525
- metrics: {
2526
- partId: part.id,
2527
- width,
2528
- height,
2529
- channels: part.channels.length,
2530
- compression: compressionHandler.name || COMPRESSION_NAMES[compression] || "UNKNOWN",
2531
- chunks: chunkCount
2532
- }
2533
- });
2534
- let offsetTablePtr = structure.headerEndOffset;
2535
- for (let i = 0; i < partIndex; i++) {
2536
- const prior = structure.parts[i];
2537
- if (!prior.dataWindow) continue;
2538
- const priorHeight = prior.dataWindow.yMax - prior.dataWindow.yMin + 1;
2539
- const priorChunks = Math.ceil(priorHeight / getScanlineLinesPerBlock(prior.compression ?? 0));
2540
- offsetTablePtr += priorChunks * 8;
2541
- }
2542
- if (offsetTablePtr < 0 || offsetTablePtr + chunkCount * 8 > view.byteLength) {
2543
- throw new ExrError("MALFORMED_OFFSET_TABLE", "Offset table is truncated or invalid.", {
2544
- partId: options.partId,
2545
- offsetTablePtr,
2546
- chunkCount,
2547
- size: view.byteLength
2548
- });
2549
- }
2550
- const tOffsets = nowMs();
2551
- const chunkOffsets = new Array(chunkCount);
2552
- for (let i = 0; i < chunkCount; i++) {
2553
- const low = view.getUint32(offsetTablePtr + i * 8, true);
2554
- const high = view.getUint32(offsetTablePtr + i * 8 + 4, true);
2555
- chunkOffsets[i] = toNumberOffset(low, high);
2556
- }
2557
- emit(onEvent, {
2558
- phase: "decode",
2559
- level: "info",
2560
- code: "decode.offsets.read",
2561
- message: "Read chunk offsets.",
2562
- metrics: {
2563
- partId: part.id,
2564
- count: chunkOffsets.length,
2565
- ms: (nowMs() - tOffsets).toFixed(3)
2566
- }
2567
- });
2568
2733
  const selectedChannelNames = options.channelNames ? new Set(options.channelNames) : void 0;
2569
2734
  if (selectedChannelNames) {
2570
2735
  for (const name of selectedChannelNames) {
@@ -2576,16 +2741,14 @@ function decodeExrPart(bufferInput, structure, options) {
2576
2741
  }
2577
2742
  }
2578
2743
  }
2579
- const channelMeta = buildChannelMeta(part, selectedChannelNames);
2744
+ const channelMeta = buildChannelMeta(part, selectedChannelNames, window);
2745
+ const finish = createOutput(channelMeta, window);
2580
2746
  const zipScratch = {
2581
2747
  inflate: new Uint8Array(0),
2582
2748
  output: new Uint8Array(0)
2583
2749
  };
2584
- const tDecode = nowMs();
2585
- let bytesRead = 0;
2586
- for (let chunkIndex = 0; chunkIndex < chunkOffsets.length; chunkIndex++) {
2587
- const chunkOffset = chunkOffsets[chunkIndex];
2588
- const chunkHeaderSize = structure.isMultipart ? 12 : 8;
2750
+ function decodeChunk(buffer, view, chunkOffset, chunkIndex, workerBlock) {
2751
+ const chunkHeaderSize = isMultipart ? 12 : 8;
2589
2752
  if (chunkOffset < 0 || chunkOffset + chunkHeaderSize > view.byteLength) {
2590
2753
  throw new ExrError("MALFORMED_CHUNK", "Chunk header is outside file bounds.", {
2591
2754
  partId: part.id,
@@ -2593,10 +2756,10 @@ function decodeExrPart(bufferInput, structure, options) {
2593
2756
  chunkOffset
2594
2757
  });
2595
2758
  }
2596
- let chunkY = 0;
2597
- let dataSize = 0;
2598
- let dataPtr = chunkOffset;
2599
- if (structure.isMultipart) {
2759
+ let chunkY;
2760
+ let dataSize;
2761
+ let dataPtr;
2762
+ if (isMultipart) {
2600
2763
  const partNumber = view.getInt32(chunkOffset, true);
2601
2764
  chunkY = view.getInt32(chunkOffset + 4, true);
2602
2765
  dataSize = view.getInt32(chunkOffset + 8, true);
@@ -2613,7 +2776,7 @@ function decodeExrPart(bufferInput, structure, options) {
2613
2776
  actualPart: partNumber
2614
2777
  }
2615
2778
  });
2616
- continue;
2779
+ return 0;
2617
2780
  }
2618
2781
  } else {
2619
2782
  chunkY = view.getInt32(chunkOffset, true);
@@ -2629,7 +2792,13 @@ function decodeExrPart(bufferInput, structure, options) {
2629
2792
  dataSize
2630
2793
  });
2631
2794
  }
2632
- const linesInChunk = Math.max(0, Math.min(linesPerBlock, part.dataWindow.yMax - chunkY + 1));
2795
+ const linesInChunk = Math.max(0, Math.min(linesPerBlock, partWindow.yMax - chunkY + 1));
2796
+ if (linesInChunk <= 0 || chunkY < window.yMin || chunkY + linesInChunk - 1 > window.yMax) {
2797
+ throw new ExrError("MALFORMED_CHUNK", "Chunk is outside the requested scanline band.", {
2798
+ chunkY,
2799
+ chunkIndex
2800
+ });
2801
+ }
2633
2802
  const expectedUncompressedSize = getExpectedUncompressedChunkSize(
2634
2803
  part,
2635
2804
  channelMeta,
@@ -2638,7 +2807,7 @@ function decodeExrPart(bufferInput, structure, options) {
2638
2807
  );
2639
2808
  const predecodedZipBlock = options.predecodedZipBlocks?.get(chunkIndex);
2640
2809
  const predecodedDwaBlock = options.predecodedDwaBlocks?.get(chunkIndex);
2641
- const predecodedBlock = predecodedZipBlock ?? predecodedDwaBlock;
2810
+ const predecodedBlock = workerBlock ?? predecodedZipBlock ?? predecodedDwaBlock;
2642
2811
  const blockData = predecodedBlock ? predecodedBlock : dataSize === expectedUncompressedSize ? new Uint8Array(buffer, dataPtr, dataSize) : compressionHandler.decodeBlock({
2643
2812
  buffer,
2644
2813
  dataPtr,
@@ -2651,12 +2820,11 @@ function decodeExrPart(bufferInput, structure, options) {
2651
2820
  linesInChunk,
2652
2821
  zipScratch: compression === 2 || compression === 3 ? zipScratch : void 0
2653
2822
  });
2654
- bytesRead += dataSize;
2655
2823
  let blockPointer = 0;
2656
2824
  const blockView = new DataView(blockData.buffer, blockData.byteOffset, blockData.byteLength);
2657
2825
  for (let dy = 0; dy < linesInChunk; dy++) {
2658
2826
  const y = chunkY + dy;
2659
- if (y < part.dataWindow.yMin) {
2827
+ if (y < partWindow.yMin) {
2660
2828
  continue;
2661
2829
  }
2662
2830
  for (const meta of channelMeta) {
@@ -2703,39 +2871,271 @@ function decodeExrPart(bufferInput, structure, options) {
2703
2871
  }
2704
2872
  });
2705
2873
  }
2874
+ return dataSize;
2706
2875
  }
2707
- const decodedChannels = {};
2708
- for (const meta of channelMeta) {
2709
- if (!meta.selected) continue;
2710
- decodedChannels[meta.channel.name] = {
2711
- pixelType: meta.channel.pixelType,
2712
- xSampling: meta.channel.xSampling,
2713
- ySampling: meta.channel.ySampling,
2714
- sampledWidth: meta.sampledWidth,
2715
- sampledHeight: meta.sampledHeight,
2716
- sampleOriginX: meta.sampleOriginX,
2717
- sampleOriginY: meta.sampleOriginY,
2718
- data: meta.data
2876
+ return {
2877
+ decodeChunk,
2878
+ finish,
2879
+ getPlanarBytes: () => channelMeta.reduce(
2880
+ (bytes, meta) => bytes + (meta.stride === 1 ? meta.data.byteLength : 0),
2881
+ 0
2882
+ )
2883
+ };
2884
+ }
2885
+ function createPlanarOutput(meta, window) {
2886
+ for (const channel of meta) {
2887
+ if (channel.selected)
2888
+ channel.data = new Float32Array(channel.sampledWidth * channel.sampledHeight);
2889
+ }
2890
+ return () => {
2891
+ const channels = {};
2892
+ for (const entry of meta) {
2893
+ if (!entry.selected) continue;
2894
+ if (!(entry.data instanceof Float32Array)) throw new Error("Invalid planar storage");
2895
+ channels[entry.channel.name] = {
2896
+ pixelType: entry.channel.pixelType,
2897
+ xSampling: entry.channel.xSampling,
2898
+ ySampling: entry.channel.ySampling,
2899
+ sampledWidth: entry.sampledWidth,
2900
+ sampledHeight: entry.sampledHeight,
2901
+ sampleOriginX: entry.sampleOriginX,
2902
+ sampleOriginY: entry.sampleOriginY,
2903
+ data: entry.data
2904
+ };
2905
+ }
2906
+ return {
2907
+ width: window.xMax - window.xMin + 1,
2908
+ height: window.yMax - window.yMin + 1,
2909
+ channels
2719
2910
  };
2911
+ };
2912
+ }
2913
+ function createRgbaOutput(meta, window, allocate) {
2914
+ const width = window.xMax - window.xMin + 1;
2915
+ const height = window.yMax - window.yMin + 1;
2916
+ const channels = Object.fromEntries(
2917
+ meta.filter((entry) => entry.selected).map((entry) => [entry.channel.name, entry])
2918
+ );
2919
+ const selected = selectRgbaChannels(channels);
2920
+ const rgba = allocate(width * height * 4);
2921
+ const lanes = selected.map((entry) => entry === void 0 ? -1 : selected.indexOf(entry));
2922
+ const sampled = [];
2923
+ for (const entry of meta) {
2924
+ const lane = selected.indexOf(entry);
2925
+ entry.selected = lane >= 0;
2926
+ if (!entry.selected) continue;
2927
+ if (entry.sampledWidth === width && entry.sampledHeight === height && entry.sampleOriginX === window.xMin && entry.sampleOriginY === window.yMin && entry.channel.xSampling <= 1 && entry.channel.ySampling <= 1) {
2928
+ entry.data = rgba;
2929
+ entry.stride = 4;
2930
+ entry.lane = lane;
2931
+ } else {
2932
+ entry.data = allocate(entry.sampledWidth * entry.sampledHeight);
2933
+ sampled.push({ entry, lane });
2934
+ }
2935
+ }
2936
+ return () => {
2937
+ for (const { entry, lane } of sampled) {
2938
+ if (!entry.data.length) continue;
2939
+ const xMap = buildNearestSampleMap(
2940
+ width,
2941
+ window.xMin,
2942
+ entry.sampleOriginX,
2943
+ Math.max(1, entry.channel.xSampling),
2944
+ entry.sampledWidth
2945
+ );
2946
+ const yMap = buildNearestSampleMap(
2947
+ height,
2948
+ window.yMin,
2949
+ entry.sampleOriginY,
2950
+ Math.max(1, entry.channel.ySampling),
2951
+ entry.sampledHeight
2952
+ );
2953
+ for (let y = 0; y < height; y++) {
2954
+ const row = yMap[y] * entry.sampledWidth;
2955
+ let offset = y * width * 4 + lane;
2956
+ for (let x = 0; x < width; x++, offset += 4) {
2957
+ rgba[offset] = entry.data[row + xMap[x]];
2958
+ }
2959
+ }
2960
+ }
2961
+ const [r, g, b, a] = lanes;
2962
+ if (rgba instanceof Uint16Array) {
2963
+ const finite = (bits) => (bits & 31744) !== 31744;
2964
+ for (let offset = 0; offset < rgba.length; offset += 4) {
2965
+ const rawRed = r < 0 ? 0 : rgba[offset + r];
2966
+ const rawGreen = g < 0 ? rawRed : rgba[offset + g];
2967
+ const rawBlue = b < 0 ? rawRed : rgba[offset + b];
2968
+ const rawAlpha = a < 0 ? 15360 : rgba[offset + a];
2969
+ const red = finite(rawRed) ? rawRed : 0;
2970
+ rgba[offset] = red;
2971
+ rgba[offset + 1] = finite(rawGreen) ? rawGreen : red;
2972
+ rgba[offset + 2] = finite(rawBlue) ? rawBlue : red;
2973
+ const alphaNaN = (rawAlpha & 32767) > 31744;
2974
+ rgba[offset + 3] = alphaNaN ? 32256 : rawAlpha & 32768 ? 0 : rawAlpha;
2975
+ }
2976
+ return rgba;
2977
+ }
2978
+ for (let offset = 0; offset < rgba.length; offset += 4) {
2979
+ const rawRed = r < 0 ? 0 : rgba[offset + r];
2980
+ const rawGreen = g < 0 ? rawRed : rgba[offset + g];
2981
+ const rawBlue = b < 0 ? rawRed : rgba[offset + b];
2982
+ const alpha = a < 0 ? 1 : Math.max(0, rgba[offset + a]);
2983
+ const red = Number.isFinite(rawRed) ? rawRed : 0;
2984
+ rgba[offset] = red;
2985
+ rgba[offset + 1] = Number.isFinite(rawGreen) ? rawGreen : red;
2986
+ rgba[offset + 2] = Number.isFinite(rawBlue) ? rawBlue : red;
2987
+ rgba[offset + 3] = alpha;
2988
+ }
2989
+ return rgba;
2990
+ };
2991
+ }
2992
+ function preparePartWithOutput(bufferInput, structure, options, createOutput) {
2993
+ const buffer = toArrayBuffer(bufferInput);
2994
+ const onEvent = options.onEvent;
2995
+ const t0 = nowMs();
2996
+ const partIndex = structure.parts.findIndex((part2) => part2.id === options.partId);
2997
+ if (partIndex < 0) {
2998
+ throw new ExrError("PART_NOT_FOUND", `Part ${options.partId} was not found in EXR structure.`, {
2999
+ partId: options.partId
3000
+ });
3001
+ }
3002
+ const part = structure.parts[partIndex];
3003
+ if ((structure.flags & 2) !== 0 || part.type && part.type !== "scanlineimage" || (structure.flags & 8) !== 0) {
3004
+ throw new ExrError("UNSUPPORTED_PART_TYPE", "Only flat scanline EXR parts are supported.", {
3005
+ partId: options.partId,
3006
+ type: part.type ?? "unknown"
3007
+ });
2720
3008
  }
3009
+ const compression = part.compression ?? 0;
3010
+ const compressionHandler = getReadCompressionHandler(compression);
3011
+ if (!compressionHandler) {
3012
+ throw new ExrError(
3013
+ "UNSUPPORTED_COMPRESSION",
3014
+ `Unsupported compression. Supported: ${getSupportedReadCompressionText()}.`,
3015
+ {
3016
+ partId: options.partId,
3017
+ compression
3018
+ }
3019
+ );
3020
+ }
3021
+ if (!part.dataWindow) {
3022
+ throw new ExrError("MISSING_DATA_WINDOW", "EXR part is missing required dataWindow.", {
3023
+ partId: options.partId
3024
+ });
3025
+ }
3026
+ const view = new DataView(buffer);
3027
+ const width = part.dataWindow.xMax - part.dataWindow.xMin + 1;
3028
+ const height = part.dataWindow.yMax - part.dataWindow.yMin + 1;
3029
+ const linesPerBlock = compressionHandler.linesPerBlock;
3030
+ const chunkCount = Math.ceil(height / linesPerBlock);
2721
3031
  emit(onEvent, {
2722
3032
  phase: "decode",
2723
3033
  level: "info",
2724
- code: "decode.complete",
2725
- message: `Decoded part ${part.id}.`,
3034
+ code: "decode.setup",
3035
+ message: `Decoder setup for part ${part.id}.`,
2726
3036
  metrics: {
2727
3037
  partId: part.id,
2728
- channels: Object.keys(decodedChannels).length,
2729
- readKB: (bytesRead / 1024).toFixed(1),
2730
- ms: (nowMs() - tDecode).toFixed(3),
2731
- totalMs: (nowMs() - t0).toFixed(3)
3038
+ width,
3039
+ height,
3040
+ channels: part.channels.length,
3041
+ compression: compressionHandler.name || COMPRESSION_NAMES[compression] || "UNKNOWN",
3042
+ chunks: chunkCount
2732
3043
  }
2733
3044
  });
2734
- return {
2735
- width,
2736
- height,
2737
- channels: decodedChannels
2738
- };
3045
+ const tOffsets = nowMs();
3046
+ const chunkOffsets = readScanlineOffsets(
3047
+ view,
3048
+ scanlineOffsetTableOffset(structure, partIndex),
3049
+ chunkCount,
3050
+ part.id
3051
+ );
3052
+ emit(onEvent, {
3053
+ phase: "decode",
3054
+ level: "info",
3055
+ code: "decode.offsets.read",
3056
+ message: "Read chunk offsets.",
3057
+ metrics: {
3058
+ partId: part.id,
3059
+ count: chunkOffsets.length,
3060
+ ms: (nowMs() - tOffsets).toFixed(3)
3061
+ }
3062
+ });
3063
+ const decoder = createScanlineDecoderWithOutput(
3064
+ part,
3065
+ structure.isMultipart,
3066
+ options,
3067
+ part.dataWindow,
3068
+ createOutput
3069
+ );
3070
+ const tDecode = nowMs();
3071
+ let bytesRead = 0;
3072
+ let assemblyMs = 0;
3073
+ let nextChunk = 0;
3074
+ function consume(chunkIndex, workerBlock) {
3075
+ if (chunkIndex !== nextChunk || chunkIndex >= chunkOffsets.length) {
3076
+ throw new Error("Scanline chunks must be consumed in offset-table order.");
3077
+ }
3078
+ const started = nowMs();
3079
+ bytesRead += decoder.decodeChunk(
3080
+ buffer,
3081
+ view,
3082
+ chunkOffsets[chunkIndex],
3083
+ chunkIndex,
3084
+ workerBlock
3085
+ );
3086
+ assemblyMs += nowMs() - started;
3087
+ nextChunk++;
3088
+ }
3089
+ function finish(workerMetrics = {}) {
3090
+ if (nextChunk !== chunkOffsets.length) throw new Error("Incomplete scanline decode.");
3091
+ const tFinalize = nowMs();
3092
+ const result = decoder.finish();
3093
+ const rgba = result instanceof Float32Array || result instanceof Uint16Array;
3094
+ emit(onEvent, {
3095
+ phase: "decode",
3096
+ level: "info",
3097
+ code: "decode.complete",
3098
+ message: `Decoded part ${part.id}.`,
3099
+ metrics: {
3100
+ partId: part.id,
3101
+ channels: options.channelNames ? new Set(options.channelNames).size : part.channels.length,
3102
+ outputLayout: rgba ? "rgba" : "planar",
3103
+ ...rgba ? { storagePrecision: result instanceof Uint16Array ? "float16" : "float32" } : {},
3104
+ planarBytes: decoder.getPlanarBytes(),
3105
+ rgbaBytes: rgba ? result.byteLength : 0,
3106
+ assemblyMs,
3107
+ finalizeMs: (nowMs() - tFinalize).toFixed(3),
3108
+ ...workerMetrics,
3109
+ readKB: (bytesRead / 1024).toFixed(1),
3110
+ ms: (nowMs() - tDecode).toFixed(3),
3111
+ totalMs: (nowMs() - t0).toFixed(3)
3112
+ }
3113
+ });
3114
+ return result;
3115
+ }
3116
+ return { chunkOffsets, consume, finish };
3117
+ }
3118
+ function prepareExrPart(buffer, structure, options) {
3119
+ return preparePartWithOutput(buffer, structure, options, createPlanarOutput);
3120
+ }
3121
+ function prepareExrPartRgba(buffer, structure, options) {
3122
+ return preparePartWithOutput(
3123
+ buffer,
3124
+ structure,
3125
+ options,
3126
+ (meta, window) => createRgbaOutput(meta, window, (length) => new Float32Array(length))
3127
+ );
3128
+ }
3129
+ function prepareExrPartNativeRgba(buffer, structure, options) {
3130
+ const part = structure.parts.find((candidate) => candidate.id === options.partId);
3131
+ if (!part || getExrRgbaStoragePrecision(part.channels, options.channelNames) === "float32")
3132
+ return prepareExrPartRgba(buffer, structure, options);
3133
+ return preparePartWithOutput(
3134
+ buffer,
3135
+ structure,
3136
+ options,
3137
+ (meta, window) => createRgbaOutput(meta, window, (length) => new Uint16Array(length))
3138
+ );
2739
3139
  }
2740
3140
 
2741
3141
  // src/browser/decodeExrPartWithWorkers.ts
@@ -2746,7 +3146,7 @@ var DWAB_COMPRESSION = 9;
2746
3146
  var DEFAULT_MIN_ZIP_CHUNKS = 8;
2747
3147
  var DEFAULT_MIN_DWA_CHUNKS = 2;
2748
3148
  var DEFAULT_MAX_WORKERS = 8;
2749
- function clamp(value, min, max) {
3149
+ function clamp2(value, min, max) {
2750
3150
  if (value < min) return min;
2751
3151
  if (value > max) return max;
2752
3152
  return value;
@@ -2771,16 +3171,6 @@ function isSampledCoordinate5(value, firstSample, sampling) {
2771
3171
  if (value < firstSample) return false;
2772
3172
  return (value - firstSample) % sampling === 0;
2773
3173
  }
2774
- function toNumberOffset2(low, high) {
2775
- if (high <= 2097151) {
2776
- return high * 4294967296 + low;
2777
- }
2778
- const combined = BigInt(low) + (BigInt(high) << 32n);
2779
- if (combined > BigInt(Number.MAX_SAFE_INTEGER)) {
2780
- throw new Error("Chunk offset exceeds safe integer range.");
2781
- }
2782
- return Number(combined);
2783
- }
2784
3174
  function buildZipChannelMeta(part) {
2785
3175
  if (!part.dataWindow) return [];
2786
3176
  const { xMin, xMax, yMin, yMax } = part.dataWindow;
@@ -2824,7 +3214,7 @@ function getParallelWorkerCount(taskCount, maxWorkers) {
2824
3214
  const target = hardware > 1 ? hardware - 1 : 1;
2825
3215
  return Math.max(1, Math.min(taskCount, target, maxWorkers));
2826
3216
  }
2827
- function collectCompressedChunkTasks(buffer, structure, part, partIndex) {
3217
+ function collectCompressedChunkTasks(buffer, structure, part, chunkOffsets) {
2828
3218
  if (!part.dataWindow) return [];
2829
3219
  const compression = part.compression ?? 0;
2830
3220
  if (compression !== ZIPS_COMPRESSION && compression !== ZIP_COMPRESSION && compression !== DWAA_COMPRESSION && compression !== DWAB_COMPRESSION) {
@@ -2832,25 +3222,6 @@ function collectCompressedChunkTasks(buffer, structure, part, partIndex) {
2832
3222
  }
2833
3223
  const view = new DataView(buffer);
2834
3224
  const linesPerBlock = getScanlineLinesPerBlock(compression);
2835
- const height = part.dataWindow.yMax - part.dataWindow.yMin + 1;
2836
- const chunkCount = Math.ceil(height / linesPerBlock);
2837
- let offsetTablePtr = structure.headerEndOffset;
2838
- for (let i = 0; i < partIndex; i++) {
2839
- const prior = structure.parts[i];
2840
- if (!prior.dataWindow) continue;
2841
- const priorHeight = prior.dataWindow.yMax - prior.dataWindow.yMin + 1;
2842
- const priorChunks = Math.ceil(priorHeight / getScanlineLinesPerBlock(prior.compression ?? 0));
2843
- offsetTablePtr += priorChunks * 8;
2844
- }
2845
- if (offsetTablePtr < 0 || offsetTablePtr + chunkCount * 8 > view.byteLength) {
2846
- throw new Error("Offset table is truncated or invalid.");
2847
- }
2848
- const chunkOffsets = new Array(chunkCount);
2849
- for (let i = 0; i < chunkCount; i++) {
2850
- const low = view.getUint32(offsetTablePtr + i * 8, true);
2851
- const high = view.getUint32(offsetTablePtr + i * 8 + 4, true);
2852
- chunkOffsets[i] = toNumberOffset2(low, high);
2853
- }
2854
3225
  const channelMeta = buildZipChannelMeta(part);
2855
3226
  const tasks = [];
2856
3227
  for (let chunkIndex = 0; chunkIndex < chunkOffsets.length; chunkIndex++) {
@@ -2859,9 +3230,9 @@ function collectCompressedChunkTasks(buffer, structure, part, partIndex) {
2859
3230
  if (chunkOffset < 0 || chunkOffset + chunkHeaderSize > view.byteLength) {
2860
3231
  throw new Error(`Chunk ${chunkIndex} header is outside file bounds.`);
2861
3232
  }
2862
- let chunkY = 0;
2863
- let dataSize = 0;
2864
- let dataPtr = chunkOffset;
3233
+ let chunkY;
3234
+ let dataSize;
3235
+ let dataPtr;
2865
3236
  if (structure.isMultipart) {
2866
3237
  const partNumber = view.getInt32(chunkOffset, true);
2867
3238
  chunkY = view.getInt32(chunkOffset + 4, true);
@@ -2898,322 +3269,241 @@ function collectCompressedChunkTasks(buffer, structure, part, partIndex) {
2898
3269
  }
2899
3270
  return tasks;
2900
3271
  }
2901
- function getDefaultWorkerFactory() {
2902
- return {
2903
- createZipWorker: () => new Worker(new URL("./zipDecodeWorker.js", import.meta.url), { type: "module" }),
2904
- createDwaWorker: () => new Worker(new URL("./dwaDecodeWorker.js", import.meta.url), { type: "module" })
3272
+ function consumeWorkerTasks(buffer, tasks, part, maxWorkers, workerFactory, consume, signal, lease, leaseWaitMs = 0) {
3273
+ const workerCount = lease?.workers.length ?? getParallelWorkerCount(tasks.length, maxWorkers);
3274
+ const isDwa = part.compression === DWAA_COMPRESSION || part.compression === DWAB_COMPRESSION;
3275
+ const workerStartedAt = performance.now();
3276
+ const metrics = {
3277
+ workerTasks: tasks.length,
3278
+ workerCount,
3279
+ workerReusedCount: lease?.reused ?? 0,
3280
+ workerLeaseWaitMs: leaseWaitMs,
3281
+ workerDecodedBytes: 0,
3282
+ peakQueuedDecodedBytes: 0,
3283
+ peakQueuedDecodedChunks: 0,
3284
+ workerTimingSamples: 0,
3285
+ workerFirstTaskSamples: 0,
3286
+ workerFirstTaskQueueMs: 0,
3287
+ workerNextTaskQueueMs: 0,
3288
+ workerDecodeMs: 0,
3289
+ workerResponseQueueMs: 0,
3290
+ workerCreateMs: 0,
3291
+ workerWallMs: 0
2905
3292
  };
2906
- }
2907
- async function decodeZipTasksInWorkers(buffer, tasks, maxWorkers, workerFactory) {
2908
- if (tasks.length === 0) {
2909
- return /* @__PURE__ */ new Map();
2910
- }
2911
- const workerCount = getParallelWorkerCount(tasks.length, maxWorkers);
2912
- const workers = [];
2913
- const taskByMessageId = /* @__PURE__ */ new Map();
2914
- const blocks = /* @__PURE__ */ new Map();
2915
3293
  return new Promise((resolve, reject) => {
2916
- let completed = 0;
2917
- let nextTaskIndex = 0;
2918
- let nextMessageId = 1;
3294
+ const workers = [];
3295
+ const idle = [];
3296
+ const ready = /* @__PURE__ */ new Map();
3297
+ const dispatched = /* @__PURE__ */ new Set();
3298
+ let nextTask = 0;
3299
+ let nextConsume = 0;
3300
+ let queuedBytes = 0;
2919
3301
  let settled = false;
2920
- const cleanup = () => {
3302
+ let pumping = false;
3303
+ function cleanup(success = false) {
3304
+ signal?.removeEventListener("abort", abort);
3305
+ ready.clear();
3306
+ idle.length = 0;
3307
+ if (lease) {
3308
+ lease.release(success);
3309
+ return;
3310
+ }
2921
3311
  for (const worker of workers) {
3312
+ worker.onmessage = null;
3313
+ worker.onerror = null;
3314
+ worker.onmessageerror = null;
2922
3315
  worker.terminate();
2923
3316
  }
2924
- };
2925
- const fail = (error) => {
3317
+ }
3318
+ function abort() {
2926
3319
  if (settled) return;
2927
3320
  settled = true;
2928
3321
  cleanup();
2929
- reject(error instanceof Error ? error : new Error(String(error)));
2930
- };
2931
- const finishIfDone = () => {
2932
- if (settled || completed !== tasks.length) return;
3322
+ reject(signal?.reason);
3323
+ }
3324
+ function fail(error) {
3325
+ if (settled) return;
2933
3326
  settled = true;
2934
3327
  cleanup();
2935
- resolve(blocks);
2936
- };
2937
- const dispatchNextTask = (worker) => {
2938
- if (settled || nextTaskIndex >= tasks.length) return;
2939
- const task = tasks[nextTaskIndex++];
2940
- const messageId = nextMessageId++;
2941
- taskByMessageId.set(messageId, task);
2942
- const compressed = new Uint8Array(task.dataSize);
2943
- compressed.set(new Uint8Array(buffer, task.dataPtr, task.dataSize));
2944
- const request = {
2945
- id: messageId,
2946
- compressed: compressed.buffer,
2947
- expectedUncompressedSize: task.expectedUncompressedSize
2948
- };
2949
- worker.postMessage(request, [request.compressed]);
2950
- };
2951
- for (let i = 0; i < workerCount; i++) {
2952
- const worker = workerFactory.createZipWorker();
2953
- workers.push(worker);
3328
+ reject(error instanceof Error ? error : new Error(String(error)));
3329
+ }
3330
+ function dispatch(worker, index) {
3331
+ const task = tasks[index];
3332
+ const compressed = buffer.slice(task.dataPtr, task.dataPtr + task.dataSize);
3333
+ const id = index + 1;
3334
+ const firstTask = !dispatched.has(worker);
3335
+ dispatched.add(worker);
3336
+ let sentAt = 0;
2954
3337
  worker.onmessage = (event) => {
2955
3338
  if (settled) return;
2956
- const response = event.data;
2957
- const task = taskByMessageId.get(response.id);
2958
- if (!task) {
2959
- fail(new Error("Received worker response for unknown ZIP task."));
2960
- return;
2961
- }
2962
- taskByMessageId.delete(response.id);
2963
- if (response.ok === false) {
2964
- fail(new Error(response.error || "ZIP worker failed."));
2965
- return;
3339
+ try {
3340
+ const response = event.data;
3341
+ if (response.id !== id || index < nextConsume || ready.has(index)) {
3342
+ throw new Error("Received worker response for unknown or completed EXR task.");
3343
+ }
3344
+ if (!response.ok) throw new Error(response.error || "EXR worker failed.");
3345
+ const receivedAt = workerDecodeClock();
3346
+ const timing = response.timing;
3347
+ if (timing && Number.isFinite(timing.startedAt) && Number.isFinite(timing.finishedAt) && timing.finishedAt >= timing.startedAt && timing.startedAt >= sentAt - 1 && timing.finishedAt <= receivedAt + 1) {
3348
+ metrics.workerTimingSamples++;
3349
+ const queueMs = Math.max(0, timing.startedAt - sentAt);
3350
+ if (firstTask) {
3351
+ metrics.workerFirstTaskSamples++;
3352
+ metrics.workerFirstTaskQueueMs += queueMs;
3353
+ } else {
3354
+ metrics.workerNextTaskQueueMs += queueMs;
3355
+ }
3356
+ metrics.workerDecodeMs += timing.finishedAt - timing.startedAt;
3357
+ metrics.workerResponseQueueMs += Math.max(0, receivedAt - timing.finishedAt);
3358
+ }
3359
+ const block = new Uint8Array(response.decoded);
3360
+ ready.set(index, { worker, block });
3361
+ queuedBytes += block.byteLength;
3362
+ metrics.workerDecodedBytes += block.byteLength;
3363
+ metrics.peakQueuedDecodedBytes = Math.max(metrics.peakQueuedDecodedBytes, queuedBytes);
3364
+ metrics.peakQueuedDecodedChunks = Math.max(metrics.peakQueuedDecodedChunks, ready.size);
3365
+ pump();
3366
+ } catch (error) {
3367
+ fail(error);
2966
3368
  }
2967
- blocks.set(task.chunkIndex, new Uint8Array(response.decoded));
2968
- completed += 1;
2969
- dispatchNextTask(worker);
2970
- finishIfDone();
2971
- };
2972
- worker.onerror = (event) => {
2973
- fail(event.error || new Error(event.message || "ZIP worker error."));
2974
3369
  };
2975
- dispatchNextTask(worker);
2976
- }
2977
- });
2978
- }
2979
- async function decodeDwaTasksInWorkers(buffer, tasks, part, maxWorkers, workerFactory) {
2980
- if (tasks.length === 0) {
2981
- return /* @__PURE__ */ new Map();
2982
- }
2983
- const workerCount = getParallelWorkerCount(tasks.length, maxWorkers);
2984
- const workers = [];
2985
- const taskByMessageId = /* @__PURE__ */ new Map();
2986
- const blocks = /* @__PURE__ */ new Map();
2987
- return new Promise((resolve, reject) => {
2988
- let completed = 0;
2989
- let nextTaskIndex = 0;
2990
- let nextMessageId = 1;
2991
- let settled = false;
2992
- const cleanup = () => {
2993
- for (const worker of workers) {
2994
- worker.terminate();
2995
- }
2996
- };
2997
- const fail = (error) => {
2998
- if (settled) return;
2999
- settled = true;
3000
- cleanup();
3001
- reject(error instanceof Error ? error : new Error(String(error)));
3002
- };
3003
- const finishIfDone = () => {
3004
- if (settled || completed !== tasks.length) return;
3005
- settled = true;
3006
- cleanup();
3007
- resolve(blocks);
3008
- };
3009
- const dispatchNextTask = (worker) => {
3010
- if (settled || nextTaskIndex >= tasks.length) return;
3011
- const task = tasks[nextTaskIndex++];
3012
- const messageId = nextMessageId++;
3013
- taskByMessageId.set(messageId, task);
3014
- const compressed = new Uint8Array(task.dataSize);
3015
- compressed.set(new Uint8Array(buffer, task.dataPtr, task.dataSize));
3016
- const request = {
3370
+ const request = isDwa ? {
3017
3371
  type: "decode",
3018
- id: messageId,
3019
- compressed: compressed.buffer,
3372
+ id,
3373
+ compressed,
3020
3374
  chunkIndex: task.chunkIndex,
3021
3375
  chunkY: task.chunkY,
3022
3376
  linesInChunk: task.linesInChunk
3023
- };
3024
- worker.postMessage(request, [request.compressed]);
3025
- };
3026
- for (let i = 0; i < workerCount; i++) {
3027
- const worker = workerFactory.createDwaWorker();
3028
- workers.push(worker);
3029
- const initMessage = {
3030
- type: "init",
3031
- part,
3032
- partId: part.id
3033
- };
3034
- worker.postMessage(initMessage);
3035
- worker.onmessage = (event) => {
3036
- if (settled) return;
3037
- const response = event.data;
3038
- const task = taskByMessageId.get(response.id);
3039
- if (!task) {
3040
- fail(new Error("Received worker response for unknown DWA task."));
3041
- return;
3377
+ } : { id, compressed, expectedUncompressedSize: task.expectedUncompressedSize };
3378
+ sentAt = workerDecodeClock();
3379
+ worker.postMessage(request, [compressed]);
3380
+ }
3381
+ function pump() {
3382
+ if (settled || pumping) return;
3383
+ pumping = true;
3384
+ try {
3385
+ while (!settled) {
3386
+ const entry = ready.get(nextConsume);
3387
+ if (entry) {
3388
+ consume(tasks[nextConsume], entry.block);
3389
+ if (settled) break;
3390
+ queuedBytes -= entry.block.byteLength;
3391
+ ready.delete(nextConsume++);
3392
+ idle.push(entry.worker);
3393
+ continue;
3394
+ }
3395
+ if (nextConsume === tasks.length) {
3396
+ settled = true;
3397
+ cleanup(true);
3398
+ metrics.workerWallMs = performance.now() - workerStartedAt;
3399
+ resolve(metrics);
3400
+ break;
3401
+ }
3402
+ if (!idle.length || nextTask >= tasks.length) break;
3403
+ dispatch(idle.pop(), nextTask++);
3042
3404
  }
3043
- taskByMessageId.delete(response.id);
3044
- if (response.ok === false) {
3045
- fail(new Error(response.error || "DWA worker failed."));
3046
- return;
3405
+ } catch (error) {
3406
+ fail(error);
3407
+ } finally {
3408
+ pumping = false;
3409
+ }
3410
+ }
3411
+ signal?.addEventListener("abort", abort, { once: true });
3412
+ if (signal?.aborted) {
3413
+ abort();
3414
+ return;
3415
+ }
3416
+ try {
3417
+ for (let i = 0; i < workerCount && !settled; i++) {
3418
+ const worker = lease?.workers[i] ?? (isDwa ? workerFactory.createDwaWorker() : workerFactory.createZipWorker());
3419
+ if (settled) {
3420
+ worker.terminate();
3421
+ break;
3047
3422
  }
3048
- blocks.set(task.chunkIndex, new Uint8Array(response.decoded));
3049
- completed += 1;
3050
- dispatchNextTask(worker);
3051
- finishIfDone();
3052
- };
3053
- worker.onerror = (event) => {
3054
- fail(event.error || new Error(event.message || "DWA worker error."));
3055
- };
3056
- dispatchNextTask(worker);
3423
+ workers.push(worker);
3424
+ worker.onerror = (event) => fail(event.error || new Error(event.message || "EXR worker error."));
3425
+ worker.onmessageerror = () => fail(new Error("Invalid EXR worker message."));
3426
+ if (isDwa) {
3427
+ const init = { type: "init", part, partId: part.id };
3428
+ worker.postMessage(init);
3429
+ }
3430
+ if (!settled) idle.push(worker);
3431
+ }
3432
+ metrics.workerCreateMs = performance.now() - workerStartedAt;
3433
+ pump();
3434
+ } catch (error) {
3435
+ fail(error);
3057
3436
  }
3058
3437
  });
3059
3438
  }
3060
- function canUseParallelChunkDecode() {
3061
- return typeof Worker !== "undefined";
3062
- }
3063
- function mergePredecodedMaps(base, patch) {
3064
- if (!base && !patch) return void 0;
3065
- const merged = /* @__PURE__ */ new Map();
3066
- for (const [k, v] of base ?? []) merged.set(k, v);
3067
- for (const [k, v] of patch ?? []) merged.set(k, v);
3068
- return merged;
3069
- }
3070
- async function decodeExrPartWithWorkers(bufferInput, structure, options) {
3439
+ async function decodePartWithWorkers(bufferInput, structure, options, prepare) {
3440
+ if (options.workerSession && options.workerFactory)
3441
+ throw new Error("workerSession and workerFactory are mutually exclusive.");
3442
+ if (options.workerSession)
3443
+ options = {
3444
+ ...options,
3445
+ signal: AbortSignal.any([
3446
+ options.workerSession.signal,
3447
+ ...options.signal ? [options.signal] : []
3448
+ ])
3449
+ };
3450
+ options.signal?.throwIfAborted();
3071
3451
  const buffer = toArrayBuffer(bufferInput);
3072
- const partIndex = structure.parts.findIndex((candidate) => candidate.id === options.partId);
3073
- const part = partIndex >= 0 ? structure.parts[partIndex] : null;
3074
- if (!part?.dataWindow) {
3075
- return decodeExrPart(buffer, structure, options);
3076
- }
3077
- const maxWorkers = clamp(options.maxWorkers ?? DEFAULT_MAX_WORKERS, 1, DEFAULT_MAX_WORKERS);
3452
+ const session = prepare(buffer, structure, options);
3453
+ options.signal?.throwIfAborted();
3454
+ const part = structure.parts.find((candidate) => candidate.id === options.partId);
3455
+ const compression = part.compression ?? 0;
3456
+ const maxWorkers = clamp2(options.maxWorkers ?? DEFAULT_MAX_WORKERS, 1, DEFAULT_MAX_WORKERS);
3078
3457
  const minZipChunks = Math.max(1, options.minZipChunks ?? DEFAULT_MIN_ZIP_CHUNKS);
3079
3458
  const minDwaChunks = Math.max(1, options.minDwaChunks ?? DEFAULT_MIN_DWA_CHUNKS);
3080
- let predecodedZipBlocks;
3081
- let predecodedDwaBlocks;
3082
- const compression = part.compression ?? 0;
3083
- const workerFactory = options.workerFactory ?? getDefaultWorkerFactory();
3084
- if (canUseParallelChunkDecode()) {
3085
- if (compression === ZIPS_COMPRESSION || compression === ZIP_COMPRESSION) {
3086
- const tasks = collectCompressedChunkTasks(buffer, structure, part, partIndex);
3087
- if (tasks.length >= minZipChunks) {
3088
- predecodedZipBlocks = await decodeZipTasksInWorkers(
3089
- buffer,
3090
- tasks,
3091
- maxWorkers,
3092
- workerFactory
3093
- );
3094
- }
3095
- }
3096
- if (compression === DWAA_COMPRESSION || compression === DWAB_COMPRESSION) {
3097
- const tasks = collectCompressedChunkTasks(buffer, structure, part, partIndex);
3098
- if (tasks.length >= minDwaChunks) {
3099
- predecodedDwaBlocks = await decodeDwaTasksInWorkers(
3100
- buffer,
3101
- tasks,
3102
- part,
3103
- maxWorkers,
3104
- workerFactory
3105
- );
3106
- }
3107
- }
3108
- }
3109
- const mergedZipBlocks = mergePredecodedMaps(options.predecodedZipBlocks, predecodedZipBlocks);
3110
- const mergedDwaBlocks = mergePredecodedMaps(options.predecodedDwaBlocks, predecodedDwaBlocks);
3111
- return decodeExrPart(buffer, structure, {
3112
- partId: options.partId,
3113
- channelNames: options.channelNames,
3114
- onEvent: options.onEvent,
3115
- predecodedZipBlocks: mergedZipBlocks,
3116
- predecodedDwaBlocks: mergedDwaBlocks
3117
- });
3118
- }
3119
-
3120
- // src/reader/expandSampledChannels.ts
3121
- function clamp2(value, min, max) {
3122
- if (value < min) return min;
3123
- if (value > max) return max;
3124
- return value;
3125
- }
3126
- function buildNearestSampleMap(length, worldMin, sampleOrigin, sampling, sampledLength) {
3127
- const output = new Int32Array(length);
3128
- if (sampledLength <= 0) return output;
3129
- for (let i = 0; i < length; i++) {
3130
- const world = worldMin + i;
3131
- const sample = Math.round((world - sampleOrigin) / sampling);
3132
- output[i] = clamp2(sample, 0, sampledLength - 1);
3133
- }
3134
- return output;
3135
- }
3136
- function expandSampledChannel(width, height, xMin, yMin, channel) {
3137
- if (channel.sampledWidth === 0 || channel.sampledHeight === 0 || channel.data.length === 0) {
3138
- return new Float32Array(width * height);
3139
- }
3140
- const xSampling = channel.xSampling > 0 ? channel.xSampling : 1;
3141
- const ySampling = channel.ySampling > 0 ? channel.ySampling : 1;
3142
- if (xSampling === 1 && ySampling === 1 && channel.sampledWidth === width && channel.sampledHeight === height && channel.sampleOriginX === xMin && channel.sampleOriginY === yMin) {
3143
- return channel.data;
3144
- }
3145
- const output = new Float32Array(width * height);
3146
- const xSampleMap = buildNearestSampleMap(
3147
- width,
3148
- xMin,
3149
- channel.sampleOriginX,
3150
- xSampling,
3151
- channel.sampledWidth
3152
- );
3153
- const ySampleMap = buildNearestSampleMap(
3154
- height,
3155
- yMin,
3156
- channel.sampleOriginY,
3157
- ySampling,
3158
- channel.sampledHeight
3159
- );
3160
- for (let y = 0; y < height; y++) {
3161
- const sampleY = ySampleMap[y];
3162
- const targetRow = y * width;
3163
- const sourceRow = sampleY * channel.sampledWidth;
3164
- for (let x = 0; x < width; x++) {
3165
- output[targetRow + x] = channel.data[sourceRow + xSampleMap[x]];
3459
+ const isDwa = compression === DWAA_COMPRESSION || compression === DWAB_COMPRESSION;
3460
+ const isZip = compression === ZIPS_COMPRESSION || compression === ZIP_COMPRESSION;
3461
+ let nextChunk = 0;
3462
+ let metrics;
3463
+ if (typeof Worker !== "undefined" && (isZip || isDwa)) {
3464
+ const tasks = collectCompressedChunkTasks(buffer, structure, part, session.chunkOffsets);
3465
+ if (tasks.length >= (isDwa ? minDwaChunks : minZipChunks)) {
3466
+ const leaseStarted = performance.now();
3467
+ const lease = options.workerSession ? await options.workerSession.acquire(
3468
+ isDwa ? "dwa" : "zip",
3469
+ getParallelWorkerCount(tasks.length, maxWorkers),
3470
+ options.signal
3471
+ ) : void 0;
3472
+ const leaseWaitMs = lease ? performance.now() - leaseStarted : 0;
3473
+ metrics = await consumeWorkerTasks(
3474
+ buffer,
3475
+ tasks,
3476
+ part,
3477
+ maxWorkers,
3478
+ options.workerFactory ?? getDefaultWorkerFactory(),
3479
+ (task, block) => {
3480
+ while (nextChunk < task.chunkIndex) {
3481
+ options.signal?.throwIfAborted();
3482
+ session.consume(nextChunk++);
3483
+ }
3484
+ options.signal?.throwIfAborted();
3485
+ session.consume(
3486
+ nextChunk++,
3487
+ isDwa ? options.predecodedZipBlocks?.get(task.chunkIndex) ?? block : block
3488
+ );
3489
+ },
3490
+ options.signal,
3491
+ lease,
3492
+ leaseWaitMs
3493
+ );
3166
3494
  }
3167
3495
  }
3168
- return output;
3169
- }
3170
- function expandDecodedPartChannels(decoded, dataWindow) {
3171
- const output = {};
3172
- for (const [name, channel] of Object.entries(decoded.channels)) {
3173
- output[name] = expandSampledChannel(
3174
- decoded.width,
3175
- decoded.height,
3176
- dataWindow.xMin,
3177
- dataWindow.yMin,
3178
- channel
3179
- );
3180
- }
3181
- return output;
3182
- }
3183
-
3184
- // src/reader/rgbaChannels.ts
3185
- function normalizeChannelName(name) {
3186
- return name.split(".").pop()?.toUpperCase() ?? "";
3187
- }
3188
- function pickChannel(channels, aliases) {
3189
- for (const alias of aliases) {
3190
- const exact = channels[alias];
3191
- if (exact) return exact;
3496
+ options.signal?.throwIfAborted();
3497
+ while (nextChunk < session.chunkOffsets.length) {
3498
+ options.signal?.throwIfAborted();
3499
+ session.consume(nextChunk++);
3192
3500
  }
3193
- const normalizedAliases = new Set(aliases.map((alias) => alias.toUpperCase()));
3194
- for (const [name, channel] of Object.entries(channels)) {
3195
- if (normalizedAliases.has(normalizeChannelName(name))) return channel;
3196
- }
3197
- return void 0;
3501
+ const result = session.finish(metrics ? { ...metrics } : {});
3502
+ options.signal?.throwIfAborted();
3503
+ return result;
3198
3504
  }
3199
- function decodedPartToRgba(width, height, dataWindow, channels) {
3200
- const expanded = expandDecodedPartChannels({ width, height, channels }, dataWindow);
3201
- const fallback = Object.values(expanded)[0] ?? new Float32Array(width * height);
3202
- const red = pickChannel(expanded, ["R", "RED"]) ?? fallback;
3203
- const luma = pickChannel(expanded, ["Y", "LUMA", "LUMINANCE"]);
3204
- const green = pickChannel(expanded, ["G", "GREEN"]) ?? luma ?? red;
3205
- const blue = pickChannel(expanded, ["B", "BLUE"]) ?? luma ?? red;
3206
- const alpha = pickChannel(expanded, ["A", "ALPHA"]);
3207
- const pixelCount = width * height;
3208
- const rgba = new Float32Array(pixelCount * 4);
3209
- for (let index = 0; index < pixelCount; index += 1) {
3210
- const offset = index * 4;
3211
- rgba[offset] = Number.isFinite(red[index]) ? red[index] : 0;
3212
- rgba[offset + 1] = Number.isFinite(green[index]) ? green[index] : rgba[offset];
3213
- rgba[offset + 2] = Number.isFinite(blue[index]) ? blue[index] : rgba[offset];
3214
- rgba[offset + 3] = alpha ? Math.max(0, alpha[index]) : 1;
3215
- }
3216
- return rgba;
3505
+ function decodeExrPartWithWorkers(buffer, structure, options) {
3506
+ return decodePartWithWorkers(buffer, structure, options, prepareExrPart);
3217
3507
  }
3218
3508
 
3219
3509
  // src/reader/parseExrStructure.ts
@@ -3320,7 +3610,7 @@ function parsePartHeader(reader, index) {
3320
3610
  }
3321
3611
  const attributes = {};
3322
3612
  const channels = [];
3323
- while (reader.offset < reader.byteLength) {
3613
+ for (; ; ) {
3324
3614
  const name = reader.readCString("attribute name");
3325
3615
  if (name === "") {
3326
3616
  break;
@@ -3604,17 +3894,11 @@ function inspectExrImage(buffer, options = {}) {
3604
3894
  };
3605
3895
  }
3606
3896
 
3607
- // src/browser/decodeExrRgbaWithWorkers.ts
3608
- async function decodeExrRgbaWithWorkers(buffer, options = {}) {
3609
- const info = inspectExrImage(buffer, options);
3610
- const decoded = await decodeExrPartWithWorkers(buffer, info.structure, {
3611
- ...options,
3612
- partId: info.partId
3613
- });
3897
+ // src/reader/decodeExrRgba.ts
3898
+ function getExrRgbaImageMetadata(info) {
3614
3899
  return {
3615
3900
  width: info.width,
3616
3901
  height: info.height,
3617
- rgba: decodedPartToRgba(info.width, info.height, info.dataWindow, decoded.channels),
3618
3902
  partId: info.partId,
3619
3903
  dataWindow: info.dataWindow,
3620
3904
  displayWindow: info.displayWindow,
@@ -3622,7 +3906,89 @@ async function decodeExrRgbaWithWorkers(buffer, options = {}) {
3622
3906
  attributes: info.part.attributes
3623
3907
  };
3624
3908
  }
3909
+ function describeExrNativeRgba(info, rgba) {
3910
+ const metadata = getExrRgbaImageMetadata(info);
3911
+ return rgba instanceof Uint16Array ? { ...metadata, storagePrecision: "float16", rgba } : { ...metadata, storagePrecision: "float32", rgba };
3912
+ }
3913
+
3914
+ // src/browser/decodeExrRgbaWithWorkers.ts
3915
+ async function decodeExrRgbaWithWorkers(buffer, options = {}) {
3916
+ options.signal?.throwIfAborted();
3917
+ const info = inspectExrImage(buffer, options);
3918
+ const rgba = await decodePartWithWorkers(
3919
+ buffer,
3920
+ info.structure,
3921
+ {
3922
+ ...options,
3923
+ partId: info.partId
3924
+ },
3925
+ prepareExrPartRgba
3926
+ );
3927
+ return { ...getExrRgbaImageMetadata(info), rgba };
3928
+ }
3929
+ async function decodeExrNativeRgbaWithWorkers(buffer, options = {}) {
3930
+ options.signal?.throwIfAborted();
3931
+ const info = inspectExrImage(buffer, options);
3932
+ const rgba = await decodePartWithWorkers(
3933
+ buffer,
3934
+ info.structure,
3935
+ { ...options, partId: info.partId },
3936
+ prepareExrPartNativeRgba
3937
+ );
3938
+ return describeExrNativeRgba(info, rgba);
3939
+ }
3940
+
3941
+ // src/reader/expandSampledChannels.ts
3942
+ function expandSampledChannel(width, height, xMin, yMin, channel) {
3943
+ if (channel.sampledWidth === 0 || channel.sampledHeight === 0 || channel.data.length === 0) {
3944
+ return new Float32Array(width * height);
3945
+ }
3946
+ const xSampling = channel.xSampling > 0 ? channel.xSampling : 1;
3947
+ const ySampling = channel.ySampling > 0 ? channel.ySampling : 1;
3948
+ if (xSampling === 1 && ySampling === 1 && channel.sampledWidth === width && channel.sampledHeight === height && channel.sampleOriginX === xMin && channel.sampleOriginY === yMin) {
3949
+ return channel.data;
3950
+ }
3951
+ const output = new Float32Array(width * height);
3952
+ const xSampleMap = buildNearestSampleMap(
3953
+ width,
3954
+ xMin,
3955
+ channel.sampleOriginX,
3956
+ xSampling,
3957
+ channel.sampledWidth
3958
+ );
3959
+ const ySampleMap = buildNearestSampleMap(
3960
+ height,
3961
+ yMin,
3962
+ channel.sampleOriginY,
3963
+ ySampling,
3964
+ channel.sampledHeight
3965
+ );
3966
+ for (let y = 0; y < height; y++) {
3967
+ const sampleY = ySampleMap[y];
3968
+ const targetRow = y * width;
3969
+ const sourceRow = sampleY * channel.sampledWidth;
3970
+ for (let x = 0; x < width; x++) {
3971
+ output[targetRow + x] = channel.data[sourceRow + xSampleMap[x]];
3972
+ }
3973
+ }
3974
+ return output;
3975
+ }
3976
+ function expandDecodedPartChannels(decoded, dataWindow) {
3977
+ const output = {};
3978
+ for (const [name, channel] of Object.entries(decoded.channels)) {
3979
+ output[name] = expandSampledChannel(
3980
+ decoded.width,
3981
+ decoded.height,
3982
+ dataWindow.xMin,
3983
+ dataWindow.yMin,
3984
+ channel
3985
+ );
3986
+ }
3987
+ return output;
3988
+ }
3625
3989
  export {
3990
+ ExrWorkerSession,
3991
+ decodeExrNativeRgbaWithWorkers,
3626
3992
  decodeExrPartWithWorkers,
3627
3993
  decodeExrRgbaWithWorkers,
3628
3994
  expandDecodedPartChannels,