@bb-studio/exr 0.3.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;
@@ -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.");
@@ -2432,7 +2631,9 @@ function buildChannelMeta(part, selectedChannelNames, outputWindow = part.dataWi
2432
2631
  sampledHeight,
2433
2632
  sampleOriginX,
2434
2633
  sampleOriginY,
2435
- data: selected ? new Float32Array(sampledWidth * sampledHeight) : new Float32Array(0)
2634
+ data: new Float32Array(0),
2635
+ stride: 1,
2636
+ lane: 0
2436
2637
  };
2437
2638
  });
2438
2639
  }
@@ -2458,46 +2659,65 @@ function getExpectedUncompressedChunkSize(part, channelMeta, chunkY, linesInChun
2458
2659
  }
2459
2660
  function decodeRowIntoChannel(meta, blockData, blockPointer, rowOffset, blockView) {
2460
2661
  const destination = meta.data;
2662
+ const stride = meta.stride;
2663
+ let target = rowOffset * stride + meta.lane;
2461
2664
  const sampleCount = meta.sampledWidth;
2462
2665
  const sourceByteOffset = blockData.byteOffset + blockPointer;
2463
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
+ }
2464
2679
  if ((sourceByteOffset & 1) === 0) {
2465
2680
  const source = new Uint16Array(blockData.buffer, sourceByteOffset, sampleCount);
2466
- for (let i = 0; i < sampleCount; i++) {
2467
- destination[rowOffset + i] = float16ToFloat32(source[i]);
2681
+ for (let i = 0; i < sampleCount; i++, target += stride) {
2682
+ destination[target] = float16ToFloat32(source[i]);
2468
2683
  }
2469
2684
  return;
2470
2685
  }
2471
- for (let i = 0; i < sampleCount; i++) {
2472
- destination[rowOffset + i] = float16ToFloat32(
2473
- blockView.getUint16(blockPointer + (i << 1), true)
2474
- );
2686
+ for (let i = 0; i < sampleCount; i++, target += stride) {
2687
+ destination[target] = float16ToFloat32(blockView.getUint16(blockPointer + (i << 1), true));
2475
2688
  }
2476
2689
  return;
2477
2690
  }
2691
+ if (destination instanceof Uint16Array) throw new Error("Non-HALF channel in native HALF output");
2478
2692
  if (meta.pixelType === 2) {
2479
2693
  if ((sourceByteOffset & 3) === 0) {
2480
2694
  const source = new Float32Array(blockData.buffer, sourceByteOffset, sampleCount);
2481
- 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
+ }
2482
2702
  return;
2483
2703
  }
2484
- for (let i = 0; i < sampleCount; i++) {
2485
- 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);
2486
2706
  }
2487
2707
  return;
2488
2708
  }
2489
2709
  if ((sourceByteOffset & 3) === 0) {
2490
2710
  const source = new Uint32Array(blockData.buffer, sourceByteOffset, sampleCount);
2491
- for (let i = 0; i < sampleCount; i++) {
2492
- 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;
2493
2713
  }
2494
2714
  return;
2495
2715
  }
2496
- for (let i = 0; i < sampleCount; i++) {
2497
- 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;
2498
2718
  }
2499
2719
  }
2500
- function createScanlineDecoder(part, isMultipart, options, window) {
2720
+ function createScanlineDecoderWithOutput(part, isMultipart, options, window, createOutput) {
2501
2721
  const onEvent = options.onEvent;
2502
2722
  const compression = part.compression ?? 0;
2503
2723
  const handler = getReadCompressionHandler(compression);
@@ -2522,11 +2742,12 @@ function createScanlineDecoder(part, isMultipart, options, window) {
2522
2742
  }
2523
2743
  }
2524
2744
  const channelMeta = buildChannelMeta(part, selectedChannelNames, window);
2745
+ const finish = createOutput(channelMeta, window);
2525
2746
  const zipScratch = {
2526
2747
  inflate: new Uint8Array(0),
2527
2748
  output: new Uint8Array(0)
2528
2749
  };
2529
- function decodeChunk(buffer, view, chunkOffset, chunkIndex) {
2750
+ function decodeChunk(buffer, view, chunkOffset, chunkIndex, workerBlock) {
2530
2751
  const chunkHeaderSize = isMultipart ? 12 : 8;
2531
2752
  if (chunkOffset < 0 || chunkOffset + chunkHeaderSize > view.byteLength) {
2532
2753
  throw new ExrError("MALFORMED_CHUNK", "Chunk header is outside file bounds.", {
@@ -2535,9 +2756,9 @@ function createScanlineDecoder(part, isMultipart, options, window) {
2535
2756
  chunkOffset
2536
2757
  });
2537
2758
  }
2538
- let chunkY = 0;
2539
- let dataSize = 0;
2540
- let dataPtr = chunkOffset;
2759
+ let chunkY;
2760
+ let dataSize;
2761
+ let dataPtr;
2541
2762
  if (isMultipart) {
2542
2763
  const partNumber = view.getInt32(chunkOffset, true);
2543
2764
  chunkY = view.getInt32(chunkOffset + 4, true);
@@ -2586,7 +2807,7 @@ function createScanlineDecoder(part, isMultipart, options, window) {
2586
2807
  );
2587
2808
  const predecodedZipBlock = options.predecodedZipBlocks?.get(chunkIndex);
2588
2809
  const predecodedDwaBlock = options.predecodedDwaBlocks?.get(chunkIndex);
2589
- const predecodedBlock = predecodedZipBlock ?? predecodedDwaBlock;
2810
+ const predecodedBlock = workerBlock ?? predecodedZipBlock ?? predecodedDwaBlock;
2590
2811
  const blockData = predecodedBlock ? predecodedBlock : dataSize === expectedUncompressedSize ? new Uint8Array(buffer, dataPtr, dataSize) : compressionHandler.decodeBlock({
2591
2812
  buffer,
2592
2813
  dataPtr,
@@ -2652,30 +2873,123 @@ function createScanlineDecoder(part, isMultipart, options, window) {
2652
2873
  }
2653
2874
  return dataSize;
2654
2875
  }
2655
- function finish() {
2656
- const decodedChannels = {};
2657
- for (const meta of channelMeta) {
2658
- if (!meta.selected) continue;
2659
- decodedChannels[meta.channel.name] = {
2660
- pixelType: meta.channel.pixelType,
2661
- xSampling: meta.channel.xSampling,
2662
- ySampling: meta.channel.ySampling,
2663
- sampledWidth: meta.sampledWidth,
2664
- sampledHeight: meta.sampledHeight,
2665
- sampleOriginX: meta.sampleOriginX,
2666
- sampleOriginY: meta.sampleOriginY,
2667
- 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
2668
2904
  };
2669
2905
  }
2670
2906
  return {
2671
2907
  width: window.xMax - window.xMin + 1,
2672
2908
  height: window.yMax - window.yMin + 1,
2673
- channels: decodedChannels
2909
+ channels
2674
2910
  };
2675
- }
2676
- return { decodeChunk, finish };
2911
+ };
2677
2912
  }
2678
- function decodeExrPart(bufferInput, structure, options) {
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) {
2679
2993
  const buffer = toArrayBuffer(bufferInput);
2680
2994
  const onEvent = options.onEvent;
2681
2995
  const t0 = nowMs();
@@ -2746,27 +3060,82 @@ function decodeExrPart(bufferInput, structure, options) {
2746
3060
  ms: (nowMs() - tOffsets).toFixed(3)
2747
3061
  }
2748
3062
  });
2749
- const decoder = createScanlineDecoder(part, structure.isMultipart, options, part.dataWindow);
3063
+ const decoder = createScanlineDecoderWithOutput(
3064
+ part,
3065
+ structure.isMultipart,
3066
+ options,
3067
+ part.dataWindow,
3068
+ createOutput
3069
+ );
2750
3070
  const tDecode = nowMs();
2751
3071
  let bytesRead = 0;
2752
- for (let chunkIndex = 0; chunkIndex < chunkOffsets.length; chunkIndex++) {
2753
- bytesRead += decoder.decodeChunk(buffer, view, chunkOffsets[chunkIndex], chunkIndex);
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;
2754
3115
  }
2755
- const result = decoder.finish();
2756
- emit(onEvent, {
2757
- phase: "decode",
2758
- level: "info",
2759
- code: "decode.complete",
2760
- message: `Decoded part ${part.id}.`,
2761
- metrics: {
2762
- partId: part.id,
2763
- channels: Object.keys(result.channels).length,
2764
- readKB: (bytesRead / 1024).toFixed(1),
2765
- ms: (nowMs() - tDecode).toFixed(3),
2766
- totalMs: (nowMs() - t0).toFixed(3)
2767
- }
2768
- });
2769
- return result;
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
+ );
2770
3139
  }
2771
3140
 
2772
3141
  // src/browser/decodeExrPartWithWorkers.ts
@@ -2777,7 +3146,7 @@ var DWAB_COMPRESSION = 9;
2777
3146
  var DEFAULT_MIN_ZIP_CHUNKS = 8;
2778
3147
  var DEFAULT_MIN_DWA_CHUNKS = 2;
2779
3148
  var DEFAULT_MAX_WORKERS = 8;
2780
- function clamp(value, min, max) {
3149
+ function clamp2(value, min, max) {
2781
3150
  if (value < min) return min;
2782
3151
  if (value > max) return max;
2783
3152
  return value;
@@ -2845,7 +3214,7 @@ function getParallelWorkerCount(taskCount, maxWorkers) {
2845
3214
  const target = hardware > 1 ? hardware - 1 : 1;
2846
3215
  return Math.max(1, Math.min(taskCount, target, maxWorkers));
2847
3216
  }
2848
- function collectCompressedChunkTasks(buffer, structure, part, partIndex) {
3217
+ function collectCompressedChunkTasks(buffer, structure, part, chunkOffsets) {
2849
3218
  if (!part.dataWindow) return [];
2850
3219
  const compression = part.compression ?? 0;
2851
3220
  if (compression !== ZIPS_COMPRESSION && compression !== ZIP_COMPRESSION && compression !== DWAA_COMPRESSION && compression !== DWAB_COMPRESSION) {
@@ -2853,14 +3222,6 @@ function collectCompressedChunkTasks(buffer, structure, part, partIndex) {
2853
3222
  }
2854
3223
  const view = new DataView(buffer);
2855
3224
  const linesPerBlock = getScanlineLinesPerBlock(compression);
2856
- const height = part.dataWindow.yMax - part.dataWindow.yMin + 1;
2857
- const chunkCount = Math.ceil(height / linesPerBlock);
2858
- const chunkOffsets = readScanlineOffsets(
2859
- view,
2860
- scanlineOffsetTableOffset(structure, partIndex),
2861
- chunkCount,
2862
- part.id
2863
- );
2864
3225
  const channelMeta = buildZipChannelMeta(part);
2865
3226
  const tasks = [];
2866
3227
  for (let chunkIndex = 0; chunkIndex < chunkOffsets.length; chunkIndex++) {
@@ -2869,9 +3230,9 @@ function collectCompressedChunkTasks(buffer, structure, part, partIndex) {
2869
3230
  if (chunkOffset < 0 || chunkOffset + chunkHeaderSize > view.byteLength) {
2870
3231
  throw new Error(`Chunk ${chunkIndex} header is outside file bounds.`);
2871
3232
  }
2872
- let chunkY = 0;
2873
- let dataSize = 0;
2874
- let dataPtr = chunkOffset;
3233
+ let chunkY;
3234
+ let dataSize;
3235
+ let dataPtr;
2875
3236
  if (structure.isMultipart) {
2876
3237
  const partNumber = view.getInt32(chunkOffset, true);
2877
3238
  chunkY = view.getInt32(chunkOffset + 4, true);
@@ -2908,322 +3269,241 @@ function collectCompressedChunkTasks(buffer, structure, part, partIndex) {
2908
3269
  }
2909
3270
  return tasks;
2910
3271
  }
2911
- function getDefaultWorkerFactory() {
2912
- return {
2913
- createZipWorker: () => new Worker(new URL("./zipDecodeWorker.js", import.meta.url), { type: "module" }),
2914
- 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
2915
3292
  };
2916
- }
2917
- async function decodeZipTasksInWorkers(buffer, tasks, maxWorkers, workerFactory) {
2918
- if (tasks.length === 0) {
2919
- return /* @__PURE__ */ new Map();
2920
- }
2921
- const workerCount = getParallelWorkerCount(tasks.length, maxWorkers);
2922
- const workers = [];
2923
- const taskByMessageId = /* @__PURE__ */ new Map();
2924
- const blocks = /* @__PURE__ */ new Map();
2925
3293
  return new Promise((resolve, reject) => {
2926
- let completed = 0;
2927
- let nextTaskIndex = 0;
2928
- 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;
2929
3301
  let settled = false;
2930
- 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
+ }
2931
3311
  for (const worker of workers) {
3312
+ worker.onmessage = null;
3313
+ worker.onerror = null;
3314
+ worker.onmessageerror = null;
2932
3315
  worker.terminate();
2933
3316
  }
2934
- };
2935
- const fail = (error) => {
3317
+ }
3318
+ function abort() {
2936
3319
  if (settled) return;
2937
3320
  settled = true;
2938
3321
  cleanup();
2939
- reject(error instanceof Error ? error : new Error(String(error)));
2940
- };
2941
- const finishIfDone = () => {
2942
- if (settled || completed !== tasks.length) return;
3322
+ reject(signal?.reason);
3323
+ }
3324
+ function fail(error) {
3325
+ if (settled) return;
2943
3326
  settled = true;
2944
3327
  cleanup();
2945
- resolve(blocks);
2946
- };
2947
- const dispatchNextTask = (worker) => {
2948
- if (settled || nextTaskIndex >= tasks.length) return;
2949
- const task = tasks[nextTaskIndex++];
2950
- const messageId = nextMessageId++;
2951
- taskByMessageId.set(messageId, task);
2952
- const compressed = new Uint8Array(task.dataSize);
2953
- compressed.set(new Uint8Array(buffer, task.dataPtr, task.dataSize));
2954
- const request = {
2955
- id: messageId,
2956
- compressed: compressed.buffer,
2957
- expectedUncompressedSize: task.expectedUncompressedSize
2958
- };
2959
- worker.postMessage(request, [request.compressed]);
2960
- };
2961
- for (let i = 0; i < workerCount; i++) {
2962
- const worker = workerFactory.createZipWorker();
2963
- 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;
2964
3337
  worker.onmessage = (event) => {
2965
3338
  if (settled) return;
2966
- const response = event.data;
2967
- const task = taskByMessageId.get(response.id);
2968
- if (!task) {
2969
- fail(new Error("Received worker response for unknown ZIP task."));
2970
- return;
2971
- }
2972
- taskByMessageId.delete(response.id);
2973
- if (response.ok === false) {
2974
- fail(new Error(response.error || "ZIP worker failed."));
2975
- 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);
2976
3368
  }
2977
- blocks.set(task.chunkIndex, new Uint8Array(response.decoded));
2978
- completed += 1;
2979
- dispatchNextTask(worker);
2980
- finishIfDone();
2981
- };
2982
- worker.onerror = (event) => {
2983
- fail(event.error || new Error(event.message || "ZIP worker error."));
2984
3369
  };
2985
- dispatchNextTask(worker);
2986
- }
2987
- });
2988
- }
2989
- async function decodeDwaTasksInWorkers(buffer, tasks, part, maxWorkers, workerFactory) {
2990
- if (tasks.length === 0) {
2991
- return /* @__PURE__ */ new Map();
2992
- }
2993
- const workerCount = getParallelWorkerCount(tasks.length, maxWorkers);
2994
- const workers = [];
2995
- const taskByMessageId = /* @__PURE__ */ new Map();
2996
- const blocks = /* @__PURE__ */ new Map();
2997
- return new Promise((resolve, reject) => {
2998
- let completed = 0;
2999
- let nextTaskIndex = 0;
3000
- let nextMessageId = 1;
3001
- let settled = false;
3002
- const cleanup = () => {
3003
- for (const worker of workers) {
3004
- worker.terminate();
3005
- }
3006
- };
3007
- const fail = (error) => {
3008
- if (settled) return;
3009
- settled = true;
3010
- cleanup();
3011
- reject(error instanceof Error ? error : new Error(String(error)));
3012
- };
3013
- const finishIfDone = () => {
3014
- if (settled || completed !== tasks.length) return;
3015
- settled = true;
3016
- cleanup();
3017
- resolve(blocks);
3018
- };
3019
- const dispatchNextTask = (worker) => {
3020
- if (settled || nextTaskIndex >= tasks.length) return;
3021
- const task = tasks[nextTaskIndex++];
3022
- const messageId = nextMessageId++;
3023
- taskByMessageId.set(messageId, task);
3024
- const compressed = new Uint8Array(task.dataSize);
3025
- compressed.set(new Uint8Array(buffer, task.dataPtr, task.dataSize));
3026
- const request = {
3370
+ const request = isDwa ? {
3027
3371
  type: "decode",
3028
- id: messageId,
3029
- compressed: compressed.buffer,
3372
+ id,
3373
+ compressed,
3030
3374
  chunkIndex: task.chunkIndex,
3031
3375
  chunkY: task.chunkY,
3032
3376
  linesInChunk: task.linesInChunk
3033
- };
3034
- worker.postMessage(request, [request.compressed]);
3035
- };
3036
- for (let i = 0; i < workerCount; i++) {
3037
- const worker = workerFactory.createDwaWorker();
3038
- workers.push(worker);
3039
- const initMessage = {
3040
- type: "init",
3041
- part,
3042
- partId: part.id
3043
- };
3044
- worker.postMessage(initMessage);
3045
- worker.onmessage = (event) => {
3046
- if (settled) return;
3047
- const response = event.data;
3048
- const task = taskByMessageId.get(response.id);
3049
- if (!task) {
3050
- fail(new Error("Received worker response for unknown DWA task."));
3051
- 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++);
3404
+ }
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;
3052
3422
  }
3053
- taskByMessageId.delete(response.id);
3054
- if (response.ok === false) {
3055
- fail(new Error(response.error || "DWA worker failed."));
3056
- return;
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);
3057
3429
  }
3058
- blocks.set(task.chunkIndex, new Uint8Array(response.decoded));
3059
- completed += 1;
3060
- dispatchNextTask(worker);
3061
- finishIfDone();
3062
- };
3063
- worker.onerror = (event) => {
3064
- fail(event.error || new Error(event.message || "DWA worker error."));
3065
- };
3066
- dispatchNextTask(worker);
3430
+ if (!settled) idle.push(worker);
3431
+ }
3432
+ metrics.workerCreateMs = performance.now() - workerStartedAt;
3433
+ pump();
3434
+ } catch (error) {
3435
+ fail(error);
3067
3436
  }
3068
3437
  });
3069
3438
  }
3070
- function canUseParallelChunkDecode() {
3071
- return typeof Worker !== "undefined";
3072
- }
3073
- function mergePredecodedMaps(base, patch) {
3074
- if (!base && !patch) return void 0;
3075
- const merged = /* @__PURE__ */ new Map();
3076
- for (const [k, v] of base ?? []) merged.set(k, v);
3077
- for (const [k, v] of patch ?? []) merged.set(k, v);
3078
- return merged;
3079
- }
3080
- 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();
3081
3451
  const buffer = toArrayBuffer(bufferInput);
3082
- const partIndex = structure.parts.findIndex((candidate) => candidate.id === options.partId);
3083
- const part = partIndex >= 0 ? structure.parts[partIndex] : null;
3084
- if (!part?.dataWindow) {
3085
- return decodeExrPart(buffer, structure, options);
3086
- }
3087
- 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);
3088
3457
  const minZipChunks = Math.max(1, options.minZipChunks ?? DEFAULT_MIN_ZIP_CHUNKS);
3089
3458
  const minDwaChunks = Math.max(1, options.minDwaChunks ?? DEFAULT_MIN_DWA_CHUNKS);
3090
- let predecodedZipBlocks;
3091
- let predecodedDwaBlocks;
3092
- const compression = part.compression ?? 0;
3093
- const workerFactory = options.workerFactory ?? getDefaultWorkerFactory();
3094
- if (canUseParallelChunkDecode()) {
3095
- if (compression === ZIPS_COMPRESSION || compression === ZIP_COMPRESSION) {
3096
- const tasks = collectCompressedChunkTasks(buffer, structure, part, partIndex);
3097
- if (tasks.length >= minZipChunks) {
3098
- predecodedZipBlocks = await decodeZipTasksInWorkers(
3099
- buffer,
3100
- tasks,
3101
- maxWorkers,
3102
- workerFactory
3103
- );
3104
- }
3105
- }
3106
- if (compression === DWAA_COMPRESSION || compression === DWAB_COMPRESSION) {
3107
- const tasks = collectCompressedChunkTasks(buffer, structure, part, partIndex);
3108
- if (tasks.length >= minDwaChunks) {
3109
- predecodedDwaBlocks = await decodeDwaTasksInWorkers(
3110
- buffer,
3111
- tasks,
3112
- part,
3113
- maxWorkers,
3114
- workerFactory
3115
- );
3116
- }
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
+ );
3117
3494
  }
3118
3495
  }
3119
- const mergedZipBlocks = mergePredecodedMaps(options.predecodedZipBlocks, predecodedZipBlocks);
3120
- const mergedDwaBlocks = mergePredecodedMaps(options.predecodedDwaBlocks, predecodedDwaBlocks);
3121
- return decodeExrPart(buffer, structure, {
3122
- partId: options.partId,
3123
- channelNames: options.channelNames,
3124
- onEvent: options.onEvent,
3125
- predecodedZipBlocks: mergedZipBlocks,
3126
- predecodedDwaBlocks: mergedDwaBlocks
3127
- });
3128
- }
3129
-
3130
- // src/reader/expandSampledChannels.ts
3131
- function clamp2(value, min, max) {
3132
- if (value < min) return min;
3133
- if (value > max) return max;
3134
- return value;
3135
- }
3136
- function buildNearestSampleMap(length, worldMin, sampleOrigin, sampling, sampledLength) {
3137
- const output = new Int32Array(length);
3138
- if (sampledLength <= 0) return output;
3139
- for (let i = 0; i < length; i++) {
3140
- const world = worldMin + i;
3141
- const sample = Math.round((world - sampleOrigin) / sampling);
3142
- output[i] = clamp2(sample, 0, sampledLength - 1);
3143
- }
3144
- return output;
3145
- }
3146
- function expandSampledChannel(width, height, xMin, yMin, channel) {
3147
- if (channel.sampledWidth === 0 || channel.sampledHeight === 0 || channel.data.length === 0) {
3148
- return new Float32Array(width * height);
3149
- }
3150
- const xSampling = channel.xSampling > 0 ? channel.xSampling : 1;
3151
- const ySampling = channel.ySampling > 0 ? channel.ySampling : 1;
3152
- if (xSampling === 1 && ySampling === 1 && channel.sampledWidth === width && channel.sampledHeight === height && channel.sampleOriginX === xMin && channel.sampleOriginY === yMin) {
3153
- return channel.data;
3154
- }
3155
- const output = new Float32Array(width * height);
3156
- const xSampleMap = buildNearestSampleMap(
3157
- width,
3158
- xMin,
3159
- channel.sampleOriginX,
3160
- xSampling,
3161
- channel.sampledWidth
3162
- );
3163
- const ySampleMap = buildNearestSampleMap(
3164
- height,
3165
- yMin,
3166
- channel.sampleOriginY,
3167
- ySampling,
3168
- channel.sampledHeight
3169
- );
3170
- for (let y = 0; y < height; y++) {
3171
- const sampleY = ySampleMap[y];
3172
- const targetRow = y * width;
3173
- const sourceRow = sampleY * channel.sampledWidth;
3174
- for (let x = 0; x < width; x++) {
3175
- output[targetRow + x] = channel.data[sourceRow + xSampleMap[x]];
3176
- }
3496
+ options.signal?.throwIfAborted();
3497
+ while (nextChunk < session.chunkOffsets.length) {
3498
+ options.signal?.throwIfAborted();
3499
+ session.consume(nextChunk++);
3177
3500
  }
3178
- return output;
3179
- }
3180
- function expandDecodedPartChannels(decoded, dataWindow) {
3181
- const output = {};
3182
- for (const [name, channel] of Object.entries(decoded.channels)) {
3183
- output[name] = expandSampledChannel(
3184
- decoded.width,
3185
- decoded.height,
3186
- dataWindow.xMin,
3187
- dataWindow.yMin,
3188
- channel
3189
- );
3190
- }
3191
- return output;
3192
- }
3193
-
3194
- // src/reader/rgbaChannels.ts
3195
- function normalizeChannelName(name) {
3196
- return name.split(".").pop()?.toUpperCase() ?? "";
3197
- }
3198
- function pickChannel(channels, aliases) {
3199
- for (const alias of aliases) {
3200
- const exact = channels[alias];
3201
- if (exact) return exact;
3202
- }
3203
- const normalizedAliases = new Set(aliases.map((alias) => alias.toUpperCase()));
3204
- for (const [name, channel] of Object.entries(channels)) {
3205
- if (normalizedAliases.has(normalizeChannelName(name))) return channel;
3206
- }
3207
- return void 0;
3501
+ const result = session.finish(metrics ? { ...metrics } : {});
3502
+ options.signal?.throwIfAborted();
3503
+ return result;
3208
3504
  }
3209
- function decodedPartToRgba(width, height, dataWindow, channels) {
3210
- const expanded = expandDecodedPartChannels({ width, height, channels }, dataWindow);
3211
- const fallback = Object.values(expanded)[0] ?? new Float32Array(width * height);
3212
- const red = pickChannel(expanded, ["R", "RED"]) ?? fallback;
3213
- const luma = pickChannel(expanded, ["Y", "LUMA", "LUMINANCE"]);
3214
- const green = pickChannel(expanded, ["G", "GREEN"]) ?? luma ?? red;
3215
- const blue = pickChannel(expanded, ["B", "BLUE"]) ?? luma ?? red;
3216
- const alpha = pickChannel(expanded, ["A", "ALPHA"]);
3217
- const pixelCount = width * height;
3218
- const rgba = new Float32Array(pixelCount * 4);
3219
- for (let index = 0; index < pixelCount; index += 1) {
3220
- const offset = index * 4;
3221
- rgba[offset] = Number.isFinite(red[index]) ? red[index] : 0;
3222
- rgba[offset + 1] = Number.isFinite(green[index]) ? green[index] : rgba[offset];
3223
- rgba[offset + 2] = Number.isFinite(blue[index]) ? blue[index] : rgba[offset];
3224
- rgba[offset + 3] = alpha ? Math.max(0, alpha[index]) : 1;
3225
- }
3226
- return rgba;
3505
+ function decodeExrPartWithWorkers(buffer, structure, options) {
3506
+ return decodePartWithWorkers(buffer, structure, options, prepareExrPart);
3227
3507
  }
3228
3508
 
3229
3509
  // src/reader/parseExrStructure.ts
@@ -3614,17 +3894,11 @@ function inspectExrImage(buffer, options = {}) {
3614
3894
  };
3615
3895
  }
3616
3896
 
3617
- // src/browser/decodeExrRgbaWithWorkers.ts
3618
- async function decodeExrRgbaWithWorkers(buffer, options = {}) {
3619
- const info = inspectExrImage(buffer, options);
3620
- const decoded = await decodeExrPartWithWorkers(buffer, info.structure, {
3621
- ...options,
3622
- partId: info.partId
3623
- });
3897
+ // src/reader/decodeExrRgba.ts
3898
+ function getExrRgbaImageMetadata(info) {
3624
3899
  return {
3625
3900
  width: info.width,
3626
3901
  height: info.height,
3627
- rgba: decodedPartToRgba(info.width, info.height, info.dataWindow, decoded.channels),
3628
3902
  partId: info.partId,
3629
3903
  dataWindow: info.dataWindow,
3630
3904
  displayWindow: info.displayWindow,
@@ -3632,7 +3906,89 @@ async function decodeExrRgbaWithWorkers(buffer, options = {}) {
3632
3906
  attributes: info.part.attributes
3633
3907
  };
3634
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
+ }
3635
3989
  export {
3990
+ ExrWorkerSession,
3991
+ decodeExrNativeRgbaWithWorkers,
3636
3992
  decodeExrPartWithWorkers,
3637
3993
  decodeExrRgbaWithWorkers,
3638
3994
  expandDecodedPartChannels,