@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.
package/dist/index.cjs CHANGED
@@ -22,13 +22,17 @@ var index_exports = {};
22
22
  __export(index_exports, {
23
23
  EXR_EVENT_CODES: () => EXR_EVENT_CODES,
24
24
  ExrError: () => ExrError,
25
+ bufferExrSource: () => bufferExrSource,
26
+ decodeExrNativeRgba: () => decodeExrNativeRgba,
25
27
  decodeExrPart: () => decodeExrPart,
26
28
  decodeExrRgba: () => decodeExrRgba,
27
29
  encodeExrRgba: () => encodeExrRgba,
28
30
  expandDecodedPartChannels: () => expandDecodedPartChannels,
29
31
  expandSampledChannel: () => expandSampledChannel,
32
+ getExrRgbaStoragePrecision: () => getExrRgbaStoragePrecision,
30
33
  inspectExrImage: () => inspectExrImage,
31
34
  isExrError: () => isExrError,
35
+ openExr: () => openExr,
32
36
  parseExr: () => parseExr,
33
37
  parseExrStructure: () => parseExrStructure,
34
38
  readExr: () => readExr,
@@ -198,7 +202,7 @@ function parsePartHeader(reader, index) {
198
202
  }
199
203
  const attributes = {};
200
204
  const channels = [];
201
- while (reader.offset < reader.byteLength) {
205
+ for (; ; ) {
202
206
  const name = reader.readCString("attribute name");
203
207
  if (name === "") {
204
208
  break;
@@ -504,6 +508,58 @@ function float32ToFloat16(value) {
504
508
  return sign | exponent << 10 | mantissa + 4096 >> 13;
505
509
  }
506
510
 
511
+ // src/reader/rgbaChannels.ts
512
+ function normalizeChannelName(name) {
513
+ return name.split(".").pop()?.toUpperCase() ?? "";
514
+ }
515
+ function pickChannel(channels, aliases) {
516
+ for (const alias of aliases) {
517
+ const exact2 = channels[alias];
518
+ if (exact2) return exact2;
519
+ }
520
+ const normalizedAliases = new Set(aliases.map((alias) => alias.toUpperCase()));
521
+ for (const [name, channel] of Object.entries(channels)) {
522
+ if (normalizedAliases.has(normalizeChannelName(name))) return channel;
523
+ }
524
+ return void 0;
525
+ }
526
+ function selectRgbaChannels(channels) {
527
+ const red = pickChannel(channels, ["R", "RED"]) ?? Object.values(channels)[0];
528
+ const luma = pickChannel(channels, ["Y", "LUMA", "LUMINANCE"]);
529
+ return [
530
+ red,
531
+ pickChannel(channels, ["G", "GREEN"]) ?? luma ?? red,
532
+ pickChannel(channels, ["B", "BLUE"]) ?? luma ?? red,
533
+ pickChannel(channels, ["A", "ALPHA"])
534
+ ];
535
+ }
536
+ function getExrRgbaStoragePrecision(channels, channelNames) {
537
+ const names = channelNames && new Set(channelNames);
538
+ const selected = selectRgbaChannels(
539
+ Object.fromEntries(
540
+ channels.filter((channel) => !names || names.has(channel.name)).map((channel) => [channel.name, channel])
541
+ )
542
+ );
543
+ return selected.every((channel) => !channel || channel.pixelType === 1) ? "float16" : "float32";
544
+ }
545
+
546
+ // src/reader/sampleMap.ts
547
+ function clamp(value, min, max) {
548
+ if (value < min) return min;
549
+ if (value > max) return max;
550
+ return value;
551
+ }
552
+ function buildNearestSampleMap(length, worldMin, sampleOrigin, sampling, sampledLength) {
553
+ const output = new Int32Array(length);
554
+ if (sampledLength <= 0) return output;
555
+ for (let i = 0; i < length; i++) {
556
+ const world = worldMin + i;
557
+ const sample = Math.round((world - sampleOrigin) / sampling);
558
+ output[i] = clamp(sample, 0, sampledLength - 1);
559
+ }
560
+ return output;
561
+ }
562
+
507
563
  // src/reader/compression/b44.ts
508
564
  var HALF_VALUES_PER_BLOCK = 16;
509
565
  var B44_BLOCK_SIZE = 14;
@@ -731,7 +787,7 @@ function decodeB44Block(context) {
731
787
  if (!isSampledCoordinate(y, layout.sampleOriginY, layout.ySampling)) {
732
788
  continue;
733
789
  }
734
- if (layout.firstChunkSampleY < 0 || y < layout.firstChunkSampleY) {
790
+ if (y < layout.firstChunkSampleY) {
735
791
  continue;
736
792
  }
737
793
  const sampledRow = Math.floor((y - layout.firstChunkSampleY) / layout.ySampling);
@@ -1688,9 +1744,7 @@ function decodeDwaChunk(context) {
1688
1744
  if (decodedWords !== header.totalAcUncompressedCount) {
1689
1745
  throw new Error("Invalid DWA AC DEFLATE payload length.");
1690
1746
  }
1691
- const decodedView = new Uint16Array(decoded.buffer, decoded.byteOffset, decodedWords);
1692
- acBuffer = new Uint16Array(decodedWords);
1693
- acBuffer.set(decodedView);
1747
+ acBuffer = new Uint16Array(decoded.buffer, decoded.byteOffset, decodedWords);
1694
1748
  cursor.value += header.acCompressedSize;
1695
1749
  break;
1696
1750
  }
@@ -1715,9 +1769,7 @@ function decodeDwaChunk(context) {
1715
1769
  if (dcWords !== header.totalDcUncompressedCount) {
1716
1770
  throw new Error("Invalid DWA DC payload length.");
1717
1771
  }
1718
- const dcView = new Uint16Array(dcBytes.buffer, dcBytes.byteOffset, dcWords);
1719
- dcBuffer = new Uint16Array(dcWords);
1720
- dcBuffer.set(dcView);
1772
+ dcBuffer = new Uint16Array(dcBytes.buffer, dcBytes.byteOffset, dcWords);
1721
1773
  cursor.value += header.dcCompressedSize;
1722
1774
  } else if (header.totalDcUncompressedCount !== 0) {
1723
1775
  throw new Error("Invalid DWA DC payload metadata.");
@@ -1733,9 +1785,7 @@ function decodeDwaChunk(context) {
1733
1785
  if (decoded.byteLength !== header.rleUncompressedSize) {
1734
1786
  throw new Error("Invalid DWA RLE intermediate payload length.");
1735
1787
  }
1736
- const decodedRle = decodeRunLength(decoded, header.rleRawSize);
1737
- rleBuffer = new Uint8Array(decodedRle.byteLength);
1738
- rleBuffer.set(decodedRle);
1788
+ rleBuffer = decodeRunLength(decoded, header.rleRawSize);
1739
1789
  cursor.value += header.rleCompressedSize;
1740
1790
  } else if (header.rleCompressedSize !== 0 || header.rleUncompressedSize !== 0) {
1741
1791
  throw new Error("Invalid DWA RLE payload metadata.");
@@ -2766,6 +2816,37 @@ function getSupportedReadCompressionText() {
2766
2816
  return Array.from(READ_COMPRESSION_HANDLERS.values()).map((handler) => handler.name).join(", ");
2767
2817
  }
2768
2818
 
2819
+ // src/reader/scanlineIndex.ts
2820
+ function scanlineOffsetTableOffset(structure, partIndex) {
2821
+ let offset = structure.headerEndOffset;
2822
+ for (let i = 0; i < partIndex; i++) {
2823
+ const prior = structure.parts[i];
2824
+ if (!prior.dataWindow) continue;
2825
+ const height = prior.dataWindow.yMax - prior.dataWindow.yMin + 1;
2826
+ offset += Math.ceil(height / getScanlineLinesPerBlock(prior.compression ?? 0)) * 8;
2827
+ }
2828
+ return offset;
2829
+ }
2830
+ function readScanlineOffsets(view, offset, count, partId) {
2831
+ if (!Number.isSafeInteger(offset) || offset < 0 || !Number.isSafeInteger(count) || count < 0 || offset + count * 8 > view.byteLength) {
2832
+ throw new ExrError("MALFORMED_OFFSET_TABLE", "Offset table is truncated or invalid.", {
2833
+ partId,
2834
+ offsetTablePtr: offset,
2835
+ chunkCount: count,
2836
+ size: view.byteLength
2837
+ });
2838
+ }
2839
+ const offsets = new Array(count);
2840
+ for (let i = 0; i < count; i++) {
2841
+ const low = view.getUint32(offset + i * 8, true);
2842
+ const high = view.getUint32(offset + i * 8 + 4, true);
2843
+ if (high > 2097151)
2844
+ throw new ExrError("MALFORMED_OFFSET_TABLE", "Chunk offset exceeds safe integer range.");
2845
+ offsets[i] = high * 4294967296 + low;
2846
+ }
2847
+ return offsets;
2848
+ }
2849
+
2769
2850
  // src/reader/decodeExrPart.ts
2770
2851
  var UINT32_MAX = 4294967295;
2771
2852
  var INV_UINT32_MAX = 1 / UINT32_MAX;
@@ -2795,21 +2876,9 @@ function isSampledCoordinate4(value, firstSample, sampling) {
2795
2876
  if (value < firstSample) return false;
2796
2877
  return (value - firstSample) % sampling === 0;
2797
2878
  }
2798
- function toNumberOffset(low, high) {
2799
- if (high <= 2097151) {
2800
- return high * 4294967296 + low;
2801
- }
2802
- const combined = BigInt(low) + (BigInt(high) << 32n);
2803
- if (combined > BigInt(Number.MAX_SAFE_INTEGER)) {
2804
- throw new ExrError("MALFORMED_OFFSET_TABLE", "Chunk offset exceeds safe integer range.", {
2805
- offset: combined.toString()
2806
- });
2807
- }
2808
- return Number(combined);
2809
- }
2810
- function buildChannelMeta(part, selectedChannelNames) {
2811
- if (!part.dataWindow) return [];
2812
- const { xMin, xMax, yMin, yMax } = part.dataWindow;
2879
+ function buildChannelMeta(part, selectedChannelNames, outputWindow = part.dataWindow) {
2880
+ if (!part.dataWindow || !outputWindow) return [];
2881
+ const { xMin, xMax, yMin, yMax } = outputWindow;
2813
2882
  return part.channels.map((channel) => {
2814
2883
  const xSampling = channel.xSampling > 0 ? channel.xSampling : 1;
2815
2884
  const ySampling = channel.ySampling > 0 ? channel.ySampling : 1;
@@ -2830,7 +2899,9 @@ function buildChannelMeta(part, selectedChannelNames) {
2830
2899
  sampledHeight,
2831
2900
  sampleOriginX,
2832
2901
  sampleOriginY,
2833
- data: selected ? new Float32Array(sampledWidth * sampledHeight) : new Float32Array(0)
2902
+ data: new Float32Array(0),
2903
+ stride: 1,
2904
+ lane: 0
2834
2905
  };
2835
2906
  });
2836
2907
  }
@@ -2856,132 +2927,77 @@ function getExpectedUncompressedChunkSize(part, channelMeta, chunkY, linesInChun
2856
2927
  }
2857
2928
  function decodeRowIntoChannel(meta, blockData, blockPointer, rowOffset, blockView) {
2858
2929
  const destination = meta.data;
2930
+ const stride = meta.stride;
2931
+ let target = rowOffset * stride + meta.lane;
2859
2932
  const sampleCount = meta.sampledWidth;
2860
2933
  const sourceByteOffset = blockData.byteOffset + blockPointer;
2861
2934
  if (meta.pixelType === 1) {
2935
+ if (destination instanceof Uint16Array) {
2936
+ if ((sourceByteOffset & 1) === 0) {
2937
+ const source = new Uint16Array(blockData.buffer, sourceByteOffset, sampleCount);
2938
+ if (stride === 1) destination.set(source, target);
2939
+ else
2940
+ for (let i = 0; i < sampleCount; i++, target += stride) destination[target] = source[i];
2941
+ } else {
2942
+ for (let i = 0; i < sampleCount; i++, target += stride)
2943
+ destination[target] = blockView.getUint16(blockPointer + (i << 1), true);
2944
+ }
2945
+ return;
2946
+ }
2862
2947
  if ((sourceByteOffset & 1) === 0) {
2863
2948
  const source = new Uint16Array(blockData.buffer, sourceByteOffset, sampleCount);
2864
- for (let i = 0; i < sampleCount; i++) {
2865
- destination[rowOffset + i] = float16ToFloat32(source[i]);
2949
+ for (let i = 0; i < sampleCount; i++, target += stride) {
2950
+ destination[target] = float16ToFloat32(source[i]);
2866
2951
  }
2867
2952
  return;
2868
2953
  }
2869
- for (let i = 0; i < sampleCount; i++) {
2870
- destination[rowOffset + i] = float16ToFloat32(
2871
- blockView.getUint16(blockPointer + (i << 1), true)
2872
- );
2954
+ for (let i = 0; i < sampleCount; i++, target += stride) {
2955
+ destination[target] = float16ToFloat32(blockView.getUint16(blockPointer + (i << 1), true));
2873
2956
  }
2874
2957
  return;
2875
2958
  }
2959
+ if (destination instanceof Uint16Array) throw new Error("Non-HALF channel in native HALF output");
2876
2960
  if (meta.pixelType === 2) {
2877
2961
  if ((sourceByteOffset & 3) === 0) {
2878
2962
  const source = new Float32Array(blockData.buffer, sourceByteOffset, sampleCount);
2879
- destination.set(source, rowOffset);
2963
+ if (stride === 1) {
2964
+ destination.set(source, target);
2965
+ } else {
2966
+ for (let i = 0; i < sampleCount; i++, target += stride) {
2967
+ destination[target] = source[i];
2968
+ }
2969
+ }
2880
2970
  return;
2881
2971
  }
2882
- for (let i = 0; i < sampleCount; i++) {
2883
- destination[rowOffset + i] = blockView.getFloat32(blockPointer + (i << 2), true);
2972
+ for (let i = 0; i < sampleCount; i++, target += stride) {
2973
+ destination[target] = blockView.getFloat32(blockPointer + (i << 2), true);
2884
2974
  }
2885
2975
  return;
2886
2976
  }
2887
2977
  if ((sourceByteOffset & 3) === 0) {
2888
2978
  const source = new Uint32Array(blockData.buffer, sourceByteOffset, sampleCount);
2889
- for (let i = 0; i < sampleCount; i++) {
2890
- destination[rowOffset + i] = source[i] * INV_UINT32_MAX;
2979
+ for (let i = 0; i < sampleCount; i++, target += stride) {
2980
+ destination[target] = source[i] * INV_UINT32_MAX;
2891
2981
  }
2892
2982
  return;
2893
2983
  }
2894
- for (let i = 0; i < sampleCount; i++) {
2895
- destination[rowOffset + i] = blockView.getUint32(blockPointer + (i << 2), true) * INV_UINT32_MAX;
2984
+ for (let i = 0; i < sampleCount; i++, target += stride) {
2985
+ destination[target] = blockView.getUint32(blockPointer + (i << 2), true) * INV_UINT32_MAX;
2896
2986
  }
2897
2987
  }
2898
- function decodeExrPart(bufferInput, structure, options) {
2899
- const buffer = toArrayBuffer(bufferInput);
2988
+ function createScanlineDecoderWithOutput(part, isMultipart, options, window, createOutput) {
2900
2989
  const onEvent = options.onEvent;
2901
- const t0 = nowMs2();
2902
- const partIndex = structure.parts.findIndex((part2) => part2.id === options.partId);
2903
- if (partIndex < 0) {
2904
- throw new ExrError("PART_NOT_FOUND", `Part ${options.partId} was not found in EXR structure.`, {
2905
- partId: options.partId
2906
- });
2907
- }
2908
- const part = structure.parts[partIndex];
2909
- if (part.type === "tiledimage") {
2910
- throw new ExrError("UNSUPPORTED_PART_TYPE", "Tiled EXR parts are not supported.", {
2911
- partId: options.partId,
2912
- type: part.type
2913
- });
2914
- }
2915
2990
  const compression = part.compression ?? 0;
2916
- const compressionHandler = getReadCompressionHandler(compression);
2917
- if (!compressionHandler) {
2918
- throw new ExrError(
2919
- "UNSUPPORTED_COMPRESSION",
2920
- `Unsupported compression. Supported: ${getSupportedReadCompressionText()}.`,
2921
- {
2922
- partId: options.partId,
2923
- compression
2924
- }
2925
- );
2926
- }
2927
- if (!part.dataWindow) {
2928
- throw new ExrError("MISSING_DATA_WINDOW", "EXR part is missing required dataWindow.", {
2929
- partId: options.partId
2930
- });
2991
+ const handler = getReadCompressionHandler(compression);
2992
+ if (!handler)
2993
+ throw new ExrError("UNSUPPORTED_COMPRESSION", "Unsupported compression.", { compression });
2994
+ const dataWindow = part.dataWindow;
2995
+ if (!dataWindow || window.xMin !== dataWindow.xMin || window.xMax !== dataWindow.xMax) {
2996
+ throw new ExrError("MISSING_DATA_WINDOW", "A full-width scanline band is required.");
2931
2997
  }
2932
- const view = new DataView(buffer);
2933
- const width = part.dataWindow.xMax - part.dataWindow.xMin + 1;
2934
- const height = part.dataWindow.yMax - part.dataWindow.yMin + 1;
2998
+ const compressionHandler = handler;
2999
+ const partWindow = dataWindow;
2935
3000
  const linesPerBlock = compressionHandler.linesPerBlock;
2936
- const chunkCount = Math.ceil(height / linesPerBlock);
2937
- emit2(onEvent, {
2938
- phase: "decode",
2939
- level: "info",
2940
- code: "decode.setup",
2941
- message: `Decoder setup for part ${part.id}.`,
2942
- metrics: {
2943
- partId: part.id,
2944
- width,
2945
- height,
2946
- channels: part.channels.length,
2947
- compression: compressionHandler.name || COMPRESSION_NAMES[compression] || "UNKNOWN",
2948
- chunks: chunkCount
2949
- }
2950
- });
2951
- let offsetTablePtr = structure.headerEndOffset;
2952
- for (let i = 0; i < partIndex; i++) {
2953
- const prior = structure.parts[i];
2954
- if (!prior.dataWindow) continue;
2955
- const priorHeight = prior.dataWindow.yMax - prior.dataWindow.yMin + 1;
2956
- const priorChunks = Math.ceil(priorHeight / getScanlineLinesPerBlock(prior.compression ?? 0));
2957
- offsetTablePtr += priorChunks * 8;
2958
- }
2959
- if (offsetTablePtr < 0 || offsetTablePtr + chunkCount * 8 > view.byteLength) {
2960
- throw new ExrError("MALFORMED_OFFSET_TABLE", "Offset table is truncated or invalid.", {
2961
- partId: options.partId,
2962
- offsetTablePtr,
2963
- chunkCount,
2964
- size: view.byteLength
2965
- });
2966
- }
2967
- const tOffsets = nowMs2();
2968
- const chunkOffsets = new Array(chunkCount);
2969
- for (let i = 0; i < chunkCount; i++) {
2970
- const low = view.getUint32(offsetTablePtr + i * 8, true);
2971
- const high = view.getUint32(offsetTablePtr + i * 8 + 4, true);
2972
- chunkOffsets[i] = toNumberOffset(low, high);
2973
- }
2974
- emit2(onEvent, {
2975
- phase: "decode",
2976
- level: "info",
2977
- code: "decode.offsets.read",
2978
- message: "Read chunk offsets.",
2979
- metrics: {
2980
- partId: part.id,
2981
- count: chunkOffsets.length,
2982
- ms: (nowMs2() - tOffsets).toFixed(3)
2983
- }
2984
- });
2985
3001
  const selectedChannelNames = options.channelNames ? new Set(options.channelNames) : void 0;
2986
3002
  if (selectedChannelNames) {
2987
3003
  for (const name of selectedChannelNames) {
@@ -2993,16 +3009,14 @@ function decodeExrPart(bufferInput, structure, options) {
2993
3009
  }
2994
3010
  }
2995
3011
  }
2996
- const channelMeta = buildChannelMeta(part, selectedChannelNames);
3012
+ const channelMeta = buildChannelMeta(part, selectedChannelNames, window);
3013
+ const finish = createOutput(channelMeta, window);
2997
3014
  const zipScratch = {
2998
3015
  inflate: new Uint8Array(0),
2999
3016
  output: new Uint8Array(0)
3000
3017
  };
3001
- const tDecode = nowMs2();
3002
- let bytesRead = 0;
3003
- for (let chunkIndex = 0; chunkIndex < chunkOffsets.length; chunkIndex++) {
3004
- const chunkOffset = chunkOffsets[chunkIndex];
3005
- const chunkHeaderSize = structure.isMultipart ? 12 : 8;
3018
+ function decodeChunk(buffer, view, chunkOffset, chunkIndex, workerBlock) {
3019
+ const chunkHeaderSize = isMultipart ? 12 : 8;
3006
3020
  if (chunkOffset < 0 || chunkOffset + chunkHeaderSize > view.byteLength) {
3007
3021
  throw new ExrError("MALFORMED_CHUNK", "Chunk header is outside file bounds.", {
3008
3022
  partId: part.id,
@@ -3010,10 +3024,10 @@ function decodeExrPart(bufferInput, structure, options) {
3010
3024
  chunkOffset
3011
3025
  });
3012
3026
  }
3013
- let chunkY = 0;
3014
- let dataSize = 0;
3015
- let dataPtr = chunkOffset;
3016
- if (structure.isMultipart) {
3027
+ let chunkY;
3028
+ let dataSize;
3029
+ let dataPtr;
3030
+ if (isMultipart) {
3017
3031
  const partNumber = view.getInt32(chunkOffset, true);
3018
3032
  chunkY = view.getInt32(chunkOffset + 4, true);
3019
3033
  dataSize = view.getInt32(chunkOffset + 8, true);
@@ -3030,7 +3044,7 @@ function decodeExrPart(bufferInput, structure, options) {
3030
3044
  actualPart: partNumber
3031
3045
  }
3032
3046
  });
3033
- continue;
3047
+ return 0;
3034
3048
  }
3035
3049
  } else {
3036
3050
  chunkY = view.getInt32(chunkOffset, true);
@@ -3046,7 +3060,13 @@ function decodeExrPart(bufferInput, structure, options) {
3046
3060
  dataSize
3047
3061
  });
3048
3062
  }
3049
- const linesInChunk = Math.max(0, Math.min(linesPerBlock, part.dataWindow.yMax - chunkY + 1));
3063
+ const linesInChunk = Math.max(0, Math.min(linesPerBlock, partWindow.yMax - chunkY + 1));
3064
+ if (linesInChunk <= 0 || chunkY < window.yMin || chunkY + linesInChunk - 1 > window.yMax) {
3065
+ throw new ExrError("MALFORMED_CHUNK", "Chunk is outside the requested scanline band.", {
3066
+ chunkY,
3067
+ chunkIndex
3068
+ });
3069
+ }
3050
3070
  const expectedUncompressedSize = getExpectedUncompressedChunkSize(
3051
3071
  part,
3052
3072
  channelMeta,
@@ -3055,7 +3075,7 @@ function decodeExrPart(bufferInput, structure, options) {
3055
3075
  );
3056
3076
  const predecodedZipBlock = options.predecodedZipBlocks?.get(chunkIndex);
3057
3077
  const predecodedDwaBlock = options.predecodedDwaBlocks?.get(chunkIndex);
3058
- const predecodedBlock = predecodedZipBlock ?? predecodedDwaBlock;
3078
+ const predecodedBlock = workerBlock ?? predecodedZipBlock ?? predecodedDwaBlock;
3059
3079
  const blockData = predecodedBlock ? predecodedBlock : dataSize === expectedUncompressedSize ? new Uint8Array(buffer, dataPtr, dataSize) : compressionHandler.decodeBlock({
3060
3080
  buffer,
3061
3081
  dataPtr,
@@ -3068,12 +3088,11 @@ function decodeExrPart(bufferInput, structure, options) {
3068
3088
  linesInChunk,
3069
3089
  zipScratch: compression === 2 || compression === 3 ? zipScratch : void 0
3070
3090
  });
3071
- bytesRead += dataSize;
3072
3091
  let blockPointer = 0;
3073
3092
  const blockView = new DataView(blockData.buffer, blockData.byteOffset, blockData.byteLength);
3074
3093
  for (let dy = 0; dy < linesInChunk; dy++) {
3075
3094
  const y = chunkY + dy;
3076
- if (y < part.dataWindow.yMin) {
3095
+ if (y < partWindow.yMin) {
3077
3096
  continue;
3078
3097
  }
3079
3098
  for (const meta of channelMeta) {
@@ -3120,40 +3139,536 @@ function decodeExrPart(bufferInput, structure, options) {
3120
3139
  }
3121
3140
  });
3122
3141
  }
3142
+ return dataSize;
3123
3143
  }
3124
- const decodedChannels = {};
3125
- for (const meta of channelMeta) {
3126
- if (!meta.selected) continue;
3127
- decodedChannels[meta.channel.name] = {
3128
- pixelType: meta.channel.pixelType,
3129
- xSampling: meta.channel.xSampling,
3130
- ySampling: meta.channel.ySampling,
3131
- sampledWidth: meta.sampledWidth,
3132
- sampledHeight: meta.sampledHeight,
3133
- sampleOriginX: meta.sampleOriginX,
3134
- sampleOriginY: meta.sampleOriginY,
3135
- data: meta.data
3144
+ return {
3145
+ decodeChunk,
3146
+ finish,
3147
+ getPlanarBytes: () => channelMeta.reduce(
3148
+ (bytes, meta) => bytes + (meta.stride === 1 ? meta.data.byteLength : 0),
3149
+ 0
3150
+ )
3151
+ };
3152
+ }
3153
+ function createPlanarOutput(meta, window) {
3154
+ for (const channel of meta) {
3155
+ if (channel.selected)
3156
+ channel.data = new Float32Array(channel.sampledWidth * channel.sampledHeight);
3157
+ }
3158
+ return () => {
3159
+ const channels = {};
3160
+ for (const entry of meta) {
3161
+ if (!entry.selected) continue;
3162
+ if (!(entry.data instanceof Float32Array)) throw new Error("Invalid planar storage");
3163
+ channels[entry.channel.name] = {
3164
+ pixelType: entry.channel.pixelType,
3165
+ xSampling: entry.channel.xSampling,
3166
+ ySampling: entry.channel.ySampling,
3167
+ sampledWidth: entry.sampledWidth,
3168
+ sampledHeight: entry.sampledHeight,
3169
+ sampleOriginX: entry.sampleOriginX,
3170
+ sampleOriginY: entry.sampleOriginY,
3171
+ data: entry.data
3172
+ };
3173
+ }
3174
+ return {
3175
+ width: window.xMax - window.xMin + 1,
3176
+ height: window.yMax - window.yMin + 1,
3177
+ channels
3136
3178
  };
3179
+ };
3180
+ }
3181
+ function createScanlineDecoder(part, isMultipart, options, window) {
3182
+ return createScanlineDecoderWithOutput(part, isMultipart, options, window, createPlanarOutput);
3183
+ }
3184
+ function createRgbaOutput(meta, window, allocate) {
3185
+ const width = window.xMax - window.xMin + 1;
3186
+ const height = window.yMax - window.yMin + 1;
3187
+ const channels = Object.fromEntries(
3188
+ meta.filter((entry) => entry.selected).map((entry) => [entry.channel.name, entry])
3189
+ );
3190
+ const selected = selectRgbaChannels(channels);
3191
+ const rgba = allocate(width * height * 4);
3192
+ const lanes = selected.map((entry) => entry === void 0 ? -1 : selected.indexOf(entry));
3193
+ const sampled = [];
3194
+ for (const entry of meta) {
3195
+ const lane = selected.indexOf(entry);
3196
+ entry.selected = lane >= 0;
3197
+ if (!entry.selected) continue;
3198
+ if (entry.sampledWidth === width && entry.sampledHeight === height && entry.sampleOriginX === window.xMin && entry.sampleOriginY === window.yMin && entry.channel.xSampling <= 1 && entry.channel.ySampling <= 1) {
3199
+ entry.data = rgba;
3200
+ entry.stride = 4;
3201
+ entry.lane = lane;
3202
+ } else {
3203
+ entry.data = allocate(entry.sampledWidth * entry.sampledHeight);
3204
+ sampled.push({ entry, lane });
3205
+ }
3206
+ }
3207
+ return () => {
3208
+ for (const { entry, lane } of sampled) {
3209
+ if (!entry.data.length) continue;
3210
+ const xMap = buildNearestSampleMap(
3211
+ width,
3212
+ window.xMin,
3213
+ entry.sampleOriginX,
3214
+ Math.max(1, entry.channel.xSampling),
3215
+ entry.sampledWidth
3216
+ );
3217
+ const yMap = buildNearestSampleMap(
3218
+ height,
3219
+ window.yMin,
3220
+ entry.sampleOriginY,
3221
+ Math.max(1, entry.channel.ySampling),
3222
+ entry.sampledHeight
3223
+ );
3224
+ for (let y = 0; y < height; y++) {
3225
+ const row = yMap[y] * entry.sampledWidth;
3226
+ let offset = y * width * 4 + lane;
3227
+ for (let x = 0; x < width; x++, offset += 4) {
3228
+ rgba[offset] = entry.data[row + xMap[x]];
3229
+ }
3230
+ }
3231
+ }
3232
+ const [r, g, b, a] = lanes;
3233
+ if (rgba instanceof Uint16Array) {
3234
+ const finite = (bits) => (bits & 31744) !== 31744;
3235
+ for (let offset = 0; offset < rgba.length; offset += 4) {
3236
+ const rawRed = r < 0 ? 0 : rgba[offset + r];
3237
+ const rawGreen = g < 0 ? rawRed : rgba[offset + g];
3238
+ const rawBlue = b < 0 ? rawRed : rgba[offset + b];
3239
+ const rawAlpha = a < 0 ? 15360 : rgba[offset + a];
3240
+ const red = finite(rawRed) ? rawRed : 0;
3241
+ rgba[offset] = red;
3242
+ rgba[offset + 1] = finite(rawGreen) ? rawGreen : red;
3243
+ rgba[offset + 2] = finite(rawBlue) ? rawBlue : red;
3244
+ const alphaNaN = (rawAlpha & 32767) > 31744;
3245
+ rgba[offset + 3] = alphaNaN ? 32256 : rawAlpha & 32768 ? 0 : rawAlpha;
3246
+ }
3247
+ return rgba;
3248
+ }
3249
+ for (let offset = 0; offset < rgba.length; offset += 4) {
3250
+ const rawRed = r < 0 ? 0 : rgba[offset + r];
3251
+ const rawGreen = g < 0 ? rawRed : rgba[offset + g];
3252
+ const rawBlue = b < 0 ? rawRed : rgba[offset + b];
3253
+ const alpha = a < 0 ? 1 : Math.max(0, rgba[offset + a]);
3254
+ const red = Number.isFinite(rawRed) ? rawRed : 0;
3255
+ rgba[offset] = red;
3256
+ rgba[offset + 1] = Number.isFinite(rawGreen) ? rawGreen : red;
3257
+ rgba[offset + 2] = Number.isFinite(rawBlue) ? rawBlue : red;
3258
+ rgba[offset + 3] = alpha;
3259
+ }
3260
+ return rgba;
3261
+ };
3262
+ }
3263
+ function preparePartWithOutput(bufferInput, structure, options, createOutput) {
3264
+ const buffer = toArrayBuffer(bufferInput);
3265
+ const onEvent = options.onEvent;
3266
+ const t0 = nowMs2();
3267
+ const partIndex = structure.parts.findIndex((part2) => part2.id === options.partId);
3268
+ if (partIndex < 0) {
3269
+ throw new ExrError("PART_NOT_FOUND", `Part ${options.partId} was not found in EXR structure.`, {
3270
+ partId: options.partId
3271
+ });
3272
+ }
3273
+ const part = structure.parts[partIndex];
3274
+ if ((structure.flags & 2) !== 0 || part.type && part.type !== "scanlineimage" || (structure.flags & 8) !== 0) {
3275
+ throw new ExrError("UNSUPPORTED_PART_TYPE", "Only flat scanline EXR parts are supported.", {
3276
+ partId: options.partId,
3277
+ type: part.type ?? "unknown"
3278
+ });
3279
+ }
3280
+ const compression = part.compression ?? 0;
3281
+ const compressionHandler = getReadCompressionHandler(compression);
3282
+ if (!compressionHandler) {
3283
+ throw new ExrError(
3284
+ "UNSUPPORTED_COMPRESSION",
3285
+ `Unsupported compression. Supported: ${getSupportedReadCompressionText()}.`,
3286
+ {
3287
+ partId: options.partId,
3288
+ compression
3289
+ }
3290
+ );
3291
+ }
3292
+ if (!part.dataWindow) {
3293
+ throw new ExrError("MISSING_DATA_WINDOW", "EXR part is missing required dataWindow.", {
3294
+ partId: options.partId
3295
+ });
3137
3296
  }
3297
+ const view = new DataView(buffer);
3298
+ const width = part.dataWindow.xMax - part.dataWindow.xMin + 1;
3299
+ const height = part.dataWindow.yMax - part.dataWindow.yMin + 1;
3300
+ const linesPerBlock = compressionHandler.linesPerBlock;
3301
+ const chunkCount = Math.ceil(height / linesPerBlock);
3302
+ emit2(onEvent, {
3303
+ phase: "decode",
3304
+ level: "info",
3305
+ code: "decode.setup",
3306
+ message: `Decoder setup for part ${part.id}.`,
3307
+ metrics: {
3308
+ partId: part.id,
3309
+ width,
3310
+ height,
3311
+ channels: part.channels.length,
3312
+ compression: compressionHandler.name || COMPRESSION_NAMES[compression] || "UNKNOWN",
3313
+ chunks: chunkCount
3314
+ }
3315
+ });
3316
+ const tOffsets = nowMs2();
3317
+ const chunkOffsets = readScanlineOffsets(
3318
+ view,
3319
+ scanlineOffsetTableOffset(structure, partIndex),
3320
+ chunkCount,
3321
+ part.id
3322
+ );
3138
3323
  emit2(onEvent, {
3139
3324
  phase: "decode",
3140
3325
  level: "info",
3141
- code: "decode.complete",
3142
- message: `Decoded part ${part.id}.`,
3326
+ code: "decode.offsets.read",
3327
+ message: "Read chunk offsets.",
3143
3328
  metrics: {
3144
3329
  partId: part.id,
3145
- channels: Object.keys(decodedChannels).length,
3146
- readKB: (bytesRead / 1024).toFixed(1),
3147
- ms: (nowMs2() - tDecode).toFixed(3),
3148
- totalMs: (nowMs2() - t0).toFixed(3)
3330
+ count: chunkOffsets.length,
3331
+ ms: (nowMs2() - tOffsets).toFixed(3)
3149
3332
  }
3150
3333
  });
3334
+ const decoder = createScanlineDecoderWithOutput(
3335
+ part,
3336
+ structure.isMultipart,
3337
+ options,
3338
+ part.dataWindow,
3339
+ createOutput
3340
+ );
3341
+ const tDecode = nowMs2();
3342
+ let bytesRead = 0;
3343
+ let assemblyMs = 0;
3344
+ let nextChunk = 0;
3345
+ function consume(chunkIndex, workerBlock) {
3346
+ if (chunkIndex !== nextChunk || chunkIndex >= chunkOffsets.length) {
3347
+ throw new Error("Scanline chunks must be consumed in offset-table order.");
3348
+ }
3349
+ const started = nowMs2();
3350
+ bytesRead += decoder.decodeChunk(
3351
+ buffer,
3352
+ view,
3353
+ chunkOffsets[chunkIndex],
3354
+ chunkIndex,
3355
+ workerBlock
3356
+ );
3357
+ assemblyMs += nowMs2() - started;
3358
+ nextChunk++;
3359
+ }
3360
+ function finish(workerMetrics = {}) {
3361
+ if (nextChunk !== chunkOffsets.length) throw new Error("Incomplete scanline decode.");
3362
+ const tFinalize = nowMs2();
3363
+ const result = decoder.finish();
3364
+ const rgba = result instanceof Float32Array || result instanceof Uint16Array;
3365
+ emit2(onEvent, {
3366
+ phase: "decode",
3367
+ level: "info",
3368
+ code: "decode.complete",
3369
+ message: `Decoded part ${part.id}.`,
3370
+ metrics: {
3371
+ partId: part.id,
3372
+ channels: options.channelNames ? new Set(options.channelNames).size : part.channels.length,
3373
+ outputLayout: rgba ? "rgba" : "planar",
3374
+ ...rgba ? { storagePrecision: result instanceof Uint16Array ? "float16" : "float32" } : {},
3375
+ planarBytes: decoder.getPlanarBytes(),
3376
+ rgbaBytes: rgba ? result.byteLength : 0,
3377
+ assemblyMs,
3378
+ finalizeMs: (nowMs2() - tFinalize).toFixed(3),
3379
+ ...workerMetrics,
3380
+ readKB: (bytesRead / 1024).toFixed(1),
3381
+ ms: (nowMs2() - tDecode).toFixed(3),
3382
+ totalMs: (nowMs2() - t0).toFixed(3)
3383
+ }
3384
+ });
3385
+ return result;
3386
+ }
3387
+ return { chunkOffsets, consume, finish };
3388
+ }
3389
+ function prepareExrPart(buffer, structure, options) {
3390
+ return preparePartWithOutput(buffer, structure, options, createPlanarOutput);
3391
+ }
3392
+ function prepareExrPartRgba(buffer, structure, options) {
3393
+ return preparePartWithOutput(
3394
+ buffer,
3395
+ structure,
3396
+ options,
3397
+ (meta, window) => createRgbaOutput(meta, window, (length) => new Float32Array(length))
3398
+ );
3399
+ }
3400
+ function consumeAll(session) {
3401
+ for (let i = 0; i < session.chunkOffsets.length; i++) session.consume(i);
3402
+ return session.finish();
3403
+ }
3404
+ function decodeExrPart(buffer, structure, options) {
3405
+ return consumeAll(prepareExrPart(buffer, structure, options));
3406
+ }
3407
+ function decodeExrPartRgba(buffer, structure, options) {
3408
+ return consumeAll(prepareExrPartRgba(buffer, structure, options));
3409
+ }
3410
+ function prepareExrPartNativeRgba(buffer, structure, options) {
3411
+ const part = structure.parts.find((candidate) => candidate.id === options.partId);
3412
+ if (!part || getExrRgbaStoragePrecision(part.channels, options.channelNames) === "float32")
3413
+ return prepareExrPartRgba(buffer, structure, options);
3414
+ return preparePartWithOutput(
3415
+ buffer,
3416
+ structure,
3417
+ options,
3418
+ (meta, window) => createRgbaOutput(meta, window, (length) => new Uint16Array(length))
3419
+ );
3420
+ }
3421
+ function decodeExrPartNativeRgba(buffer, structure, options) {
3422
+ return consumeAll(prepareExrPartNativeRgba(buffer, structure, options));
3423
+ }
3424
+
3425
+ // src/reader/openExr.ts
3426
+ var invalid = (message) => new ExrError("MALFORMED_OFFSET_TABLE", message);
3427
+ async function exact(source, offset, length, signal) {
3428
+ signal?.throwIfAborted();
3429
+ if (!Number.isSafeInteger(offset) || !Number.isSafeInteger(length) || offset < 0 || length < 0 || !Number.isSafeInteger(offset + length) || source.size !== void 0 && offset + length > source.size) {
3430
+ throw invalid("Invalid byte range.");
3431
+ }
3432
+ const bytes = await source.readRange(offset, length, signal);
3433
+ signal?.throwIfAborted();
3434
+ if (bytes.byteLength !== length) throw new ExrError("TRUNCATED_FILE", "Incomplete byte range.");
3435
+ return bytes;
3436
+ }
3437
+ function scanlineLayout(structure, part) {
3438
+ const compression = getReadCompressionHandler(part.compression ?? 0);
3439
+ if (!compression) throw new ExrError("UNSUPPORTED_COMPRESSION", "Unsupported compression.");
3440
+ if (structure.flags & 10 || part.type && part.type !== "scanlineimage") {
3441
+ throw new ExrError(
3442
+ "UNSUPPORTED_PART_TYPE",
3443
+ "Random access currently supports flat scanline EXRs."
3444
+ );
3445
+ }
3446
+ const window = part.dataWindow;
3447
+ if (!window || window.xMax < window.xMin || window.yMax < window.yMin) {
3448
+ throw new ExrError("MISSING_DATA_WINDOW", "Invalid EXR data window.");
3449
+ }
3450
+ const lines = compression.linesPerBlock;
3451
+ const count = Math.ceil((window.yMax - window.yMin + 1) / lines);
3452
+ return { window, lines, count };
3453
+ }
3454
+ function bufferExrSource(input) {
3455
+ const buffer = input instanceof ArrayBuffer ? new Uint8Array(input) : input;
3151
3456
  return {
3152
- width,
3153
- height,
3154
- channels: decodedChannels
3457
+ size: buffer.byteLength,
3458
+ async readRange(offset, length, signal) {
3459
+ signal?.throwIfAborted();
3460
+ return Uint8Array.from(buffer.subarray(offset, offset + length)).buffer;
3461
+ }
3462
+ };
3463
+ }
3464
+ async function openExr(source, options = {}) {
3465
+ const limit = options.maxMetadataBytes ?? 16 * 1024 * 1024;
3466
+ if (!Number.isSafeInteger(limit) || limit < 8) throw invalid("Invalid metadata budget.");
3467
+ let length = Math.min(64 * 1024, limit, source.size ?? Infinity);
3468
+ let prefix;
3469
+ let structure;
3470
+ for (; ; ) {
3471
+ options.signal?.throwIfAborted();
3472
+ prefix = await source.readRange(0, length, options.signal);
3473
+ options.signal?.throwIfAborted();
3474
+ try {
3475
+ structure = parseExrStructure(prefix);
3476
+ break;
3477
+ } catch (error) {
3478
+ if (!isExrError(error) || error.code !== "TRUNCATED_FILE" || prefix.byteLength < length || length >= limit)
3479
+ throw error;
3480
+ const next = Math.min(length * 2, limit, source.size ?? Infinity);
3481
+ if (next <= length) throw error;
3482
+ length = next;
3483
+ }
3484
+ }
3485
+ if (options.onEvent) parseExrStructure(prefix, { onEvent: options.onEvent });
3486
+ const layouts = structure.parts.map((part) => scanlineLayout(structure, part));
3487
+ const end = structure.headerEndOffset + layouts.reduce((n, l) => n + l.count * 8, 0);
3488
+ if (!Number.isSafeInteger(end) || end > limit)
3489
+ throw invalid("EXR metadata exceeds configured budget.");
3490
+ const table = end <= prefix.byteLength ? prefix : await exact(source, 0, end, options.signal);
3491
+ const view = new DataView(table);
3492
+ let ptr = structure.headerEndOffset;
3493
+ const chunks = [];
3494
+ for (let p = 0; p < layouts.length; p++) {
3495
+ const { window, count, lines } = layouts[p];
3496
+ const offsets = readScanlineOffsets(view, ptr, count, structure.parts[p].id);
3497
+ ptr += count * 8;
3498
+ for (let i = 0; i < count; i++) {
3499
+ const offset = offsets[i];
3500
+ if (!Number.isSafeInteger(offset) || offset < end || source.size !== void 0 && offset >= source.size)
3501
+ throw invalid("Invalid EXR chunk offset.");
3502
+ const yMin = window.yMin + i * lines;
3503
+ chunks.push({
3504
+ index: i,
3505
+ partId: structure.parts[p].id,
3506
+ yMin,
3507
+ yMax: Math.min(window.yMax, yMin + lines - 1),
3508
+ offset
3509
+ });
3510
+ }
3511
+ }
3512
+ const physical = [...chunks].sort((a, b) => a.offset - b.offset);
3513
+ const lengths = /* @__PURE__ */ new Map();
3514
+ const headerSize = structure.isMultipart ? 12 : 8;
3515
+ for (let i = 0; i < physical.length; i++) {
3516
+ const next = physical[i + 1]?.offset ?? source.size;
3517
+ if (next === void 0) continue;
3518
+ const size = next - physical[i].offset;
3519
+ if (size < headerSize) throw invalid("Overlapping EXR chunks.");
3520
+ lengths.set(physical[i].offset, size);
3521
+ }
3522
+ return new ScanlineExrReader(
3523
+ source,
3524
+ structure,
3525
+ chunks.map((c) => ({ ...c, byteLength: lengths.get(c.offset) }))
3526
+ );
3527
+ }
3528
+ function intersect(a, b) {
3529
+ const window = {
3530
+ xMin: Math.max(a.xMin, b.xMin),
3531
+ yMin: Math.max(a.yMin, b.yMin),
3532
+ xMax: Math.min(a.xMax, b.xMax),
3533
+ yMax: Math.min(a.yMax, b.yMax)
3155
3534
  };
3535
+ if (Object.values(window).some((v) => !Number.isSafeInteger(v)) || window.xMin > window.xMax || window.yMin > window.yMax) {
3536
+ throw new RangeError("Region does not intersect the data window.");
3537
+ }
3538
+ return window;
3156
3539
  }
3540
+ var ScanlineExrReader = class {
3541
+ constructor(source, structure, chunks) {
3542
+ this.source = source;
3543
+ this.structure = structure;
3544
+ this.chunks = chunks;
3545
+ }
3546
+ getChunks(partId) {
3547
+ this.part(partId);
3548
+ return this.chunks.filter((c) => c.partId === partId);
3549
+ }
3550
+ part(id) {
3551
+ const part = this.structure.parts.find((p) => p.id === id);
3552
+ if (!part) throw new ExrError("PART_NOT_FOUND", "EXR part not found.", { partId: id });
3553
+ return part;
3554
+ }
3555
+ /** Yield complete full-width scanline bands. Region selects intersecting chunks, not cropped pixels. */
3556
+ async *decodeChunks(options) {
3557
+ const part = this.part(options.partId);
3558
+ const window = part.dataWindow;
3559
+ const region = options.region ? intersect(window, options.region) : window;
3560
+ const remaining = this.getChunks(part.id).filter(
3561
+ (c) => c.yMax >= region.yMin && c.yMin <= region.yMax
3562
+ );
3563
+ const headerSize = this.structure.isMultipart ? 12 : 8;
3564
+ while (remaining.length) {
3565
+ options.signal?.throwIfAborted();
3566
+ const requestedBytes = typeof options.batchBytes === "function" ? options.batchBytes() : options.batchBytes;
3567
+ const maxBytes = Number.isFinite(requestedBytes) && requestedBytes > 0 ? Math.floor(requestedBytes) : 2 * 1024 * 1024;
3568
+ const priority = options.priority?.();
3569
+ let start = priority ? remaining.findIndex((c) => c.yMax >= priority.yMin && c.yMin <= priority.yMax) : 0;
3570
+ if (start < 0) start = 0;
3571
+ const first = remaining[start];
3572
+ const batch = [first];
3573
+ let size = first.byteLength ?? 0;
3574
+ let rangeOffset = first.offset;
3575
+ let headerBytes;
3576
+ if (first.byteLength !== void 0) {
3577
+ for (let j = start + 1; j < remaining.length; j++) {
3578
+ const prev = batch[batch.length - 1], next = remaining[j];
3579
+ if (next.byteLength === void 0 || next.offset !== prev.offset + prev.byteLength && next.offset + next.byteLength !== prev.offset || next.yMin !== prev.yMax + 1 || size + next.byteLength > maxBytes)
3580
+ break;
3581
+ if (next.offset !== rangeOffset + size && next.offset + next.byteLength !== rangeOffset)
3582
+ break;
3583
+ batch.push(next);
3584
+ rangeOffset = Math.min(rangeOffset, next.offset);
3585
+ size += next.byteLength;
3586
+ }
3587
+ } else {
3588
+ headerBytes = await exact(this.source, first.offset, headerSize, options.signal);
3589
+ const header = new DataView(headerBytes);
3590
+ const payload = header.getInt32(headerSize - 4, true);
3591
+ if (payload < 0) throw new ExrError("MALFORMED_CHUNK", "Invalid EXR chunk length.");
3592
+ size = headerSize + payload;
3593
+ }
3594
+ if (size > 512 * 1024 * 1024)
3595
+ throw new ExrError("MALFORMED_CHUNK", "EXR chunk range exceeds 512 MiB.");
3596
+ let bytes;
3597
+ if (headerBytes) {
3598
+ const payload = await exact(
3599
+ this.source,
3600
+ first.offset + headerSize,
3601
+ size - headerSize,
3602
+ options.signal
3603
+ );
3604
+ const joined = new Uint8Array(size);
3605
+ joined.set(new Uint8Array(headerBytes));
3606
+ joined.set(new Uint8Array(payload), headerSize);
3607
+ bytes = joined.buffer;
3608
+ } else {
3609
+ bytes = await exact(this.source, rangeOffset, size, options.signal);
3610
+ }
3611
+ const view = new DataView(bytes);
3612
+ const band = { ...window, yMin: first.yMin, yMax: batch[batch.length - 1].yMax };
3613
+ const decoder = createScanlineDecoder(part, this.structure.isMultipart, options, band);
3614
+ for (const chunk of batch) {
3615
+ const offset = chunk.offset - rangeOffset;
3616
+ const y = view.getInt32(offset + headerSize - 8, true);
3617
+ const length = view.getInt32(offset + headerSize - 4, true);
3618
+ if (y !== chunk.yMin || length < 0 || length + headerSize > (chunk.byteLength ?? size) || this.structure.isMultipart && view.getInt32(offset, true) !== part.id) {
3619
+ throw new ExrError("MALFORMED_CHUNK", "EXR chunk does not match its index.");
3620
+ }
3621
+ decoder.decodeChunk(bytes, view, offset, chunk.index);
3622
+ }
3623
+ remaining.splice(start, batch.length);
3624
+ yield { ...decoder.finish(), window: band };
3625
+ }
3626
+ }
3627
+ async decodePart(options) {
3628
+ const decoded = await this.decodeRegion({
3629
+ ...options,
3630
+ region: this.part(options.partId).dataWindow
3631
+ });
3632
+ return { width: decoded.width, height: decoded.height, channels: decoded.channels };
3633
+ }
3634
+ /** Return sampled-native planes cropped to the intersection with the data window. */
3635
+ async decodeRegion(options) {
3636
+ const part = this.part(options.partId);
3637
+ const window = intersect(part.dataWindow, options.region);
3638
+ const channels = {};
3639
+ const first = (min, sampling) => Math.ceil(min / sampling) * sampling || 0;
3640
+ for await (const band of this.decodeChunks({ ...options, region: window })) {
3641
+ for (const [name, src] of Object.entries(band.channels)) {
3642
+ const xs = Math.max(1, src.xSampling), ys = Math.max(1, src.ySampling);
3643
+ const x = first(window.xMin, xs), y = first(window.yMin, ys);
3644
+ const width = Math.max(0, Math.floor((window.xMax - x) / xs) + 1);
3645
+ const height = Math.max(0, Math.floor((window.yMax - y) / ys) + 1);
3646
+ const dst = channels[name] ??= {
3647
+ ...src,
3648
+ sampleOriginX: x,
3649
+ sampleOriginY: y,
3650
+ sampledWidth: width,
3651
+ sampledHeight: height,
3652
+ data: new Float32Array(width * height)
3653
+ };
3654
+ if (!width || !height) continue;
3655
+ const startY = Math.max(y, src.sampleOriginY);
3656
+ const endY = Math.min(window.yMax, band.window.yMax);
3657
+ const startX = (x - src.sampleOriginX) / xs;
3658
+ for (let row = startY; row <= endY; row += ys) {
3659
+ const srcOffset = (row - src.sampleOriginY) / ys * src.sampledWidth + startX;
3660
+ dst.data.set(src.data.subarray(srcOffset, srcOffset + width), (row - y) / ys * width);
3661
+ }
3662
+ }
3663
+ }
3664
+ return {
3665
+ window,
3666
+ width: window.xMax - window.xMin + 1,
3667
+ height: window.yMax - window.yMin + 1,
3668
+ channels
3669
+ };
3670
+ }
3671
+ };
3157
3672
 
3158
3673
  // src/reader/readExr.ts
3159
3674
  function readExr(buffer, options = {}) {
@@ -3223,21 +3738,6 @@ function inspectExrImage(buffer, options = {}) {
3223
3738
  }
3224
3739
 
3225
3740
  // src/reader/expandSampledChannels.ts
3226
- function clamp(value, min, max) {
3227
- if (value < min) return min;
3228
- if (value > max) return max;
3229
- return value;
3230
- }
3231
- function buildNearestSampleMap(length, worldMin, sampleOrigin, sampling, sampledLength) {
3232
- const output = new Int32Array(length);
3233
- if (sampledLength <= 0) return output;
3234
- for (let i = 0; i < length; i++) {
3235
- const world = worldMin + i;
3236
- const sample = Math.round((world - sampleOrigin) / sampling);
3237
- output[i] = clamp(sample, 0, sampledLength - 1);
3238
- }
3239
- return output;
3240
- }
3241
3741
  function expandSampledChannel(width, height, xMin, yMin, channel) {
3242
3742
  if (channel.sampledWidth === 0 || channel.sampledHeight === 0 || channel.data.length === 0) {
3243
3743
  return new Float32Array(width * height);
@@ -3286,54 +3786,11 @@ function expandDecodedPartChannels(decoded, dataWindow) {
3286
3786
  return output;
3287
3787
  }
3288
3788
 
3289
- // src/reader/rgbaChannels.ts
3290
- function normalizeChannelName(name) {
3291
- return name.split(".").pop()?.toUpperCase() ?? "";
3292
- }
3293
- function pickChannel(channels, aliases) {
3294
- for (const alias of aliases) {
3295
- const exact = channels[alias];
3296
- if (exact) return exact;
3297
- }
3298
- const normalizedAliases = new Set(aliases.map((alias) => alias.toUpperCase()));
3299
- for (const [name, channel] of Object.entries(channels)) {
3300
- if (normalizedAliases.has(normalizeChannelName(name))) return channel;
3301
- }
3302
- return void 0;
3303
- }
3304
- function decodedPartToRgba(width, height, dataWindow, channels) {
3305
- const expanded = expandDecodedPartChannels({ width, height, channels }, dataWindow);
3306
- const fallback = Object.values(expanded)[0] ?? new Float32Array(width * height);
3307
- const red = pickChannel(expanded, ["R", "RED"]) ?? fallback;
3308
- const luma = pickChannel(expanded, ["Y", "LUMA", "LUMINANCE"]);
3309
- const green = pickChannel(expanded, ["G", "GREEN"]) ?? luma ?? red;
3310
- const blue = pickChannel(expanded, ["B", "BLUE"]) ?? luma ?? red;
3311
- const alpha = pickChannel(expanded, ["A", "ALPHA"]);
3312
- const pixelCount = width * height;
3313
- const rgba = new Float32Array(pixelCount * 4);
3314
- for (let index = 0; index < pixelCount; index += 1) {
3315
- const offset = index * 4;
3316
- rgba[offset] = Number.isFinite(red[index]) ? red[index] : 0;
3317
- rgba[offset + 1] = Number.isFinite(green[index]) ? green[index] : rgba[offset];
3318
- rgba[offset + 2] = Number.isFinite(blue[index]) ? blue[index] : rgba[offset];
3319
- rgba[offset + 3] = alpha ? Math.max(0, alpha[index]) : 1;
3320
- }
3321
- return rgba;
3322
- }
3323
-
3324
3789
  // src/reader/decodeExrRgba.ts
3325
- function decodeExrRgba(buffer, options = {}) {
3326
- const info = inspectExrImage(buffer, options);
3327
- const decoded = decodeExrPart(buffer, info.structure, {
3328
- partId: info.partId,
3329
- predecodedZipBlocks: options.decode?.predecodedZipBlocks,
3330
- predecodedDwaBlocks: options.decode?.predecodedDwaBlocks,
3331
- onEvent: options.onEvent
3332
- });
3790
+ function getExrRgbaImageMetadata(info) {
3333
3791
  return {
3334
3792
  width: info.width,
3335
3793
  height: info.height,
3336
- rgba: decodedPartToRgba(info.width, info.height, info.dataWindow, decoded.channels),
3337
3794
  partId: info.partId,
3338
3795
  dataWindow: info.dataWindow,
3339
3796
  displayWindow: info.displayWindow,
@@ -3341,6 +3798,25 @@ function decodeExrRgba(buffer, options = {}) {
3341
3798
  attributes: info.part.attributes
3342
3799
  };
3343
3800
  }
3801
+ function describeExrNativeRgba(info, rgba) {
3802
+ const metadata = getExrRgbaImageMetadata(info);
3803
+ return rgba instanceof Uint16Array ? { ...metadata, storagePrecision: "float16", rgba } : { ...metadata, storagePrecision: "float32", rgba };
3804
+ }
3805
+ function getDecodeOptions(info, options) {
3806
+ return { ...options.decode, partId: info.partId, onEvent: options.onEvent };
3807
+ }
3808
+ function decodeExrRgba(buffer, options = {}) {
3809
+ const info = inspectExrImage(buffer, options);
3810
+ const rgba = decodeExrPartRgba(buffer, info.structure, getDecodeOptions(info, options));
3811
+ return { ...getExrRgbaImageMetadata(info), rgba };
3812
+ }
3813
+ function decodeExrNativeRgba(buffer, options = {}) {
3814
+ const info = inspectExrImage(buffer, options);
3815
+ return describeExrNativeRgba(
3816
+ info,
3817
+ decodeExrPartNativeRgba(buffer, info.structure, getDecodeOptions(info, options))
3818
+ );
3819
+ }
3344
3820
 
3345
3821
  // src/writer/sampling.ts
3346
3822
  function modulo5(value, base) {
@@ -4174,7 +4650,7 @@ function floatBitsToFloat24Bits(bits) {
4174
4650
  const sign = bits & 2147483648;
4175
4651
  const exponent = bits & 2139095040;
4176
4652
  const mantissa = bits & 8388607;
4177
- let reduced = 0;
4653
+ let reduced;
4178
4654
  if (exponent === 2139095040) {
4179
4655
  if (mantissa !== 0) {
4180
4656
  const shrunkMantissa = mantissa >>> 8;
@@ -5070,13 +5546,17 @@ function encodeExrRgba(image, options) {
5070
5546
  0 && (module.exports = {
5071
5547
  EXR_EVENT_CODES,
5072
5548
  ExrError,
5549
+ bufferExrSource,
5550
+ decodeExrNativeRgba,
5073
5551
  decodeExrPart,
5074
5552
  decodeExrRgba,
5075
5553
  encodeExrRgba,
5076
5554
  expandDecodedPartChannels,
5077
5555
  expandSampledChannel,
5556
+ getExrRgbaStoragePrecision,
5078
5557
  inspectExrImage,
5079
5558
  isExrError,
5559
+ openExr,
5080
5560
  parseExr,
5081
5561
  parseExrStructure,
5082
5562
  readExr,