@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/CHANGELOG.md ADDED
@@ -0,0 +1,37 @@
1
+ # @bb-studio/exr
2
+
3
+ ## 0.4.0
4
+
5
+ ### Minor Changes
6
+
7
+ - Add precision-aware native RGBA decoding for synchronous and browser worker-assisted reads. Retain selected HALF samples in binary16 storage and use Float32 for mixed FLOAT/UINT selections.
8
+ - Add caller-owned reusable browser worker sessions with bounded cohort admission, cancellation, disposal and explicit idle-worker release.
9
+ - Support abortable worker-assisted decoding.
10
+
11
+ ### Patch Changes
12
+
13
+ - Assemble selected RGBA channels directly into interleaved output, avoiding unused channel planes and full-resolution intermediates.
14
+ - Consume worker-decoded scanline blocks incrementally with bounded slots and ordered assembly.
15
+ - Transfer owned ZIP/DWA worker output without redundant copies and reuse required scratch storage.
16
+ - Distinguish worker initialization, dispatch, execution and delivery in decode diagnostics.
17
+ - Raise the minimum fflate version to 0.8.3 to address a dependency security advisory.
18
+
19
+ ## 0.3.0
20
+
21
+ ### Minor Changes
22
+
23
+ - Add random-access scanline reading and progressive chunk and region decoding through a platform-independent byte source.
24
+
25
+ ## 0.2.0
26
+
27
+ ### Minor Changes
28
+
29
+ - Decode selected named channels and encode named UINT channels.
30
+
31
+ ## 0.1.3
32
+
33
+ ### Patch Changes
34
+
35
+ - Add RGBA decoding, encoding and image inspection helpers, and typed writer attributes.
36
+
37
+ Earlier published versions are listed in the [npm version history](https://www.npmjs.com/package/@bb-studio/exr?activeTab=versions).
package/README.md CHANGED
@@ -12,6 +12,8 @@ OpenEXR scanline parser/decoder/encoder and backend-neutral RGBA helpers for bro
12
12
  npm install @bb-studio/exr
13
13
  ```
14
14
 
15
+ Native RGBA decoding and reusable worker sessions require version 0.4.0 or newer. See the [changelog](./CHANGELOG.md).
16
+
15
17
  ## Image API
16
18
 
17
19
  ```ts
@@ -25,7 +27,93 @@ const encodedImage = encodeExrRgba(
25
27
  );
26
28
  ```
27
29
 
28
- `decodeExrRgba` selects the requested part, or the first part with a data window, expands sampled channels, and resolves conventional RGB/A names including layered suffixes and Y/luma fallback. The result retains data/display windows, channel descriptors, and part attributes.
30
+ `decodeExrRgba` selects the requested part, or the first part with a data window, expands sampled channels, and resolves conventional RGB/A names including layered suffixes and Y/luma fallback. The result retains data/display windows, channel descriptors, and part attributes. Full-resolution selected channels are decoded directly into the final interleaved Float32 RGBA allocation; only selected subsampled channels require compact planar sample storage. Auxiliary channels not used by RGBA are not materialized. The planar and RGBA APIs share scanline validation and decompression.
31
+
32
+ `decodeExrNativeRgba` uses the same RGBA selection and numeric semantics but
33
+ returns an explicit storage discriminant. When all selected channels are
34
+ HALF it writes binary16 bits directly into a `Uint16Array`, without a
35
+ full-sized Float32 intermediate. FLOAT and normalized UINT selections
36
+ retain Float32 storage. Alpha NaNs are canonicalized; NaN payloads are
37
+ not a preservation contract. For numeric CPU algorithms continue to use
38
+ `decodeExrRgba`.
39
+
40
+ ```ts
41
+ import { decodeExrNativeRgba, getExrRgbaStoragePrecision, inspectExrImage } from '@bb-studio/exr';
42
+
43
+ const info = inspectExrImage(buffer);
44
+ const image = decodeExrNativeRgba(buffer);
45
+ if (image.storagePrecision === 'float16') {
46
+ // Binary16 bits suitable for HALF texture storage.
47
+ } else {
48
+ // Numeric Float32 samples.
49
+ }
50
+ const predictedPrecision = getExrRgbaStoragePrecision(info.part.channels);
51
+ ```
52
+
53
+ The browser entry point also exposes `decodeExrNativeRgbaWithWorkers`
54
+ with the same result contract and worker cancellation options.
55
+
56
+ ### Reusable browser worker session
57
+
58
+ For a viewport or other long-lived decoder owner, reuse the worker modules
59
+ across independent frames without keeping the previous frame's output or
60
+ part-specific scratch:
61
+
62
+ ```ts
63
+ import { ExrWorkerSession, decodeExrNativeRgbaWithWorkers } from '@bb-studio/exr/browser';
64
+
65
+ const workerSession = new ExrWorkerSession(16); // Total owned workers, not per frame.
66
+ try {
67
+ for (const buffer of frames) {
68
+ const image = await decodeExrNativeRgbaWithWorkers(buffer, {
69
+ workerSession,
70
+ maxWorkers: 8,
71
+ signal,
72
+ });
73
+ // The caller owns image.rgba.
74
+ }
75
+ } finally {
76
+ workerSession.dispose();
77
+ }
78
+ ```
79
+
80
+ The session admits complete worker cohorts in FIFO order, bounded by its
81
+ capacity (1–16 workers). Each decode keeps its existing per-job worker
82
+ limit. A successful cohort returns to the owner after its last response
83
+ has been consumed; reset messages drop the previous DWA part and ZIP/DWA
84
+ scratch references before another decode runs. Failed or aborted cohorts
85
+ are terminated, without canceling other leases. Disposal aborts active and
86
+ queued decodes and terminates all owned workers. The caller must bound its
87
+ concurrent submissions and dispose the session: the capacity bounds worker
88
+ slots, not input/output memory retained by queued callers. Idle workers
89
+ retain evaluated modules and may retain browser heap capacity until GC.
90
+ At an explicit owner-controlled resource boundary, `workerSession.releaseIdle()`
91
+ terminates only currently idle workers and returns their count. It is safe
92
+ to call while other leases are active or requests are waiting. It does not
93
+ abort requests, change capacity, dispose the session, or schedule a timer.
94
+ The next decode recreates any missing workers on demand. Releasing workers
95
+ makes their memory eligible for reclamation, not a synchronous process
96
+ memory or GC guarantee. Prefer `dispose()` for permanent owner teardown.
97
+
98
+ Stateless calls without a session retain their one-call worker lifetime.
99
+ A custom session factory must implement the built-in reset protocol;
100
+ `workerSession` and per-call `workerFactory` are mutually exclusive.
101
+
102
+ The `workerReusedCount` metric counts previously initialized workers
103
+ acquired by a frame. `workerLeaseWaitMs` includes acquisition and any worker
104
+ creation before dispatch; `workerCreateMs` measures initialization
105
+ submission inside the decode phase, not session acquisition.
106
+
107
+ For worker-assisted decoding, `decode.complete` event metrics distinguish
108
+ worker creation/initialization submission (`workerCreateMs`), complete worker
109
+ phase wall time (`workerWallMs`), first and later dispatch-to-handler queue
110
+ time (`workerFirstTaskQueueMs`, `workerNextTaskQueueMs`), handler execution
111
+ (`workerDecodeMs`) and response delivery (`workerResponseQueueMs`).
112
+ Queue and execution metrics are summed across concurrent tasks; do not add them to calculate frame latency. First-task delay includes module loading, initialization
113
+ and scheduling; it is not an isolated module-startup measurement.
114
+ `workerTimingSamples` and `workerFirstTaskSamples` expose timing coverage;
115
+ custom worker factories may omit timing. Missing samples must not be treated
116
+ as zero-cost work.
29
117
 
30
118
  `encodeExrRgba` accepts straight `Float32Array` RGBA pixels plus optional named channels, typed attributes, compression, and non-zero data/display windows. It returns EXR bytes and has no Blob, renderer, or platform dependency.
31
119
 
@@ -95,8 +183,9 @@ The worker-assisted `decodeExrPartWithWorkers` API accepts the same selection.
95
183
  import { decodeExrPartWithWorkers, expandDecodedPartChannels } from '@bb-studio/exr/browser';
96
184
  ```
97
185
 
98
- - `decodeExrPartWithWorkers` optionally pre-decodes ZIP/DWA chunks using workers.
186
+ - `decodeExrPartWithWorkers` optionally decompresses ZIP/DWA chunks using workers and consumes them incrementally in offset-table order. Each worker slot owns at most one unconsumed response or active task, bounding decoded-block retention independently of image chunk count. The `decode.complete` diagnostic reports summed synchronous assembly time, worker task/byte totals and peak ready-queue bytes/chunks.
99
187
  - `decodeExrRgbaWithWorkers` applies the same RGBA semantics through the worker-assisted path.
188
+ - Worker-assisted decode APIs accept an optional `AbortSignal`. An aborted decode rejects with the signal reason, clears pending decoded blocks, and terminates its own workers before settling. Already-aborted signals are checked before allocation; synchronous fallback decoding cannot be interrupted by a browser event until the main thread yields.
100
189
  - `expandDecodedPartChannels` is available from the root package and remains re-exported here for existing browser consumers.
101
190
 
102
191
  ## Error/Diagnostics
@@ -110,7 +199,65 @@ import { decodeExrPartWithWorkers, expandDecodedPartChannels } from '@bb-studio/
110
199
  - Compression: `NO_COMPRESSION`, `RLE_COMPRESSION`, `ZIPS_COMPRESSION`, `ZIP_COMPRESSION`, `PIZ_COMPRESSION`, `PXR24_COMPRESSION`, `B44_COMPRESSION`, `B44A_COMPRESSION`.
111
200
  - Pixel types: `UINT`, `HALF`, `FLOAT`.
112
201
 
202
+ ## Random-access and progressive decoding
203
+
204
+ The async reader accepts a platform-independent byte source (no HTTP, filesystem,
205
+ DOM or renderer dependencies). The existing synchronous `decodeExrPart` and
206
+ worker-assisted full-buffer APIs remain available and use the same scanline
207
+ decoding kernel and offset-table utilities.
208
+
209
+ ```ts
210
+ import { openExr, type ExrRandomAccessSource } from '@bb-studio/exr';
211
+
212
+ const source: ExrRandomAccessSource = {
213
+ size: file.size,
214
+ async readRange(offset, length, signal) {
215
+ signal?.throwIfAborted();
216
+ return file.slice(offset, offset + length).arrayBuffer();
217
+ },
218
+ };
219
+
220
+ const reader = await openExr(source, { signal });
221
+ const partId = reader.structure.parts[0].id;
222
+ const chunks = reader.getChunks(partId);
223
+
224
+ // Fetch only the chunks intersecting this region, and return cropped
225
+ // sampled-native channel planes. Coordinates are inclusive EXR coordinates.
226
+ const region = await reader.decodeRegion({
227
+ partId,
228
+ region: { xMin: 100, yMin: 200, xMax: 399, yMax: 499 },
229
+ channelNames: ['R', 'G', 'B'],
230
+ signal,
231
+ });
232
+
233
+ // Progressive full-width scanline bands with their original coordinates.
234
+ for await (const band of reader.decodeChunks({
235
+ partId,
236
+ batchBytes: 2 * 1024 * 1024,
237
+ priority: () => currentVisibleWindow,
238
+ signal,
239
+ })) {
240
+ // Upload or otherwise consume band.channels and band.window.
241
+ }
242
+ ```
243
+
244
+ Use `bufferExrSource(buffer)` for ArrayBuffer or Uint8Array inputs.
245
+ `reader.decodePart({ partId, signal })` is the async full-part convenience API.
246
+
247
+ - `readRange` returns exactly the requested bytes, except a short read at EOF;
248
+ `size` may be omitted if unknown. Each decode can be cancelled independently.
249
+ - `openExr` reads only the header and offset table, with a bounded metadata
250
+ budget (16 MiB by default). Chunk sizes are inferred from adjacent physical
251
+ offsets, or read from the final chunk header when file size is unknown.
252
+ - `decodeChunks` yields coalesced complete scanline bands, not cropped tiles.
253
+ `decodeRegion` crops sampled-native planes to the intersecting region.
254
+ Horizontal cropping does not reduce the scanline bytes that must be fetched.
255
+ - All existing flat scanline codecs are available, including multipart scanline
256
+ files and sampled channels. Async decompression currently runs on the calling
257
+ thread; the existing full-buffer browser worker path is unchanged.
258
+ - The consumer owns network scheduling, caching, source lifetime and rendering.
259
+ Tiled/deep images, mipmaps and ripmaps are not supported by this reader yet.
260
+
113
261
  ## License
114
262
 
115
- - Package license: MIT ([`LICENSE`](./LICENSE))
116
- - Third-party dependency notices: [`THIRD_PARTY_LICENSES.md`](./THIRD_PARTY_LICENSES.md)
263
+ MIT ([LICENSE](./LICENSE)) · [Third-party notices](./THIRD_PARTY_LICENSES.md)
@@ -4,14 +4,14 @@ The `@bb-studio/exr` package includes the following third-party dependency:
4
4
 
5
5
  ## fflate
6
6
 
7
- - Version: `0.8.2`
7
+ - Version: `0.8.3`
8
8
  - License: `MIT`
9
9
  - Repository: <https://github.com/101arrowz/fflate>
10
10
  - Source license file: `node_modules/fflate/LICENSE`
11
11
 
12
12
  ### MIT License (fflate)
13
13
 
14
- Copyright (c) 2023 Arjun Barrett
14
+ Copyright (c) 2026 Arjun Barrett
15
15
 
16
16
  Permission is hereby granted, free of charge, to any person obtaining a copy
17
17
  of this software and associated documentation files (the "Software"), to deal
@@ -0,0 +1,9 @@
1
+ // src/browser/workerDecodeTiming.ts
2
+ function workerDecodeClock() {
3
+ return performance.timeOrigin + performance.now();
4
+ }
5
+
6
+ export {
7
+ workerDecodeClock
8
+ };
9
+ //# sourceMappingURL=chunk-RJALO6PD.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/browser/workerDecodeTiming.ts"],"sourcesContent":["/** Clock shared by browser window and dedicated worker contexts. */\nexport function workerDecodeClock(): number {\n return performance.timeOrigin + performance.now();\n}\n\n/** Optional for injected WorkerFactory implementations. Built-in workers report\n * the execution interval, excluding transport and initial module evaluation. */\nexport interface WorkerDecodeTiming {\n startedAt: number;\n finishedAt: number;\n}\n"],"mappings":";AACO,SAAS,oBAA4B;AAC1C,SAAO,YAAY,aAAa,YAAY,IAAI;AAClD;","names":[]}
@@ -1,3 +1,7 @@
1
+ import {
2
+ workerDecodeClock
3
+ } from "./chunk-RJALO6PD.js";
4
+
1
5
  // src/reader/compression/dwa.ts
2
6
  import { unzlibSync } from "fflate";
3
7
 
@@ -397,6 +401,10 @@ var DWA_DC_SCRATCH = {
397
401
  inflate: new Uint8Array(0),
398
402
  output: new Uint8Array(0)
399
403
  };
404
+ function resetDwaDecodeScratch() {
405
+ DWA_DC_SCRATCH.inflate = new Uint8Array(0);
406
+ DWA_DC_SCRATCH.output = new Uint8Array(0);
407
+ }
400
408
  function undoZipPredictorAndInterleave(data, output) {
401
409
  const length = data.length;
402
410
  if (length === 0) {
@@ -995,9 +1003,7 @@ function decodeDwaChunk(context) {
995
1003
  if (decodedWords !== header.totalAcUncompressedCount) {
996
1004
  throw new Error("Invalid DWA AC DEFLATE payload length.");
997
1005
  }
998
- const decodedView = new Uint16Array(decoded.buffer, decoded.byteOffset, decodedWords);
999
- acBuffer = new Uint16Array(decodedWords);
1000
- acBuffer.set(decodedView);
1006
+ acBuffer = new Uint16Array(decoded.buffer, decoded.byteOffset, decodedWords);
1001
1007
  cursor.value += header.acCompressedSize;
1002
1008
  break;
1003
1009
  }
@@ -1022,9 +1028,7 @@ function decodeDwaChunk(context) {
1022
1028
  if (dcWords !== header.totalDcUncompressedCount) {
1023
1029
  throw new Error("Invalid DWA DC payload length.");
1024
1030
  }
1025
- const dcView = new Uint16Array(dcBytes.buffer, dcBytes.byteOffset, dcWords);
1026
- dcBuffer = new Uint16Array(dcWords);
1027
- dcBuffer.set(dcView);
1031
+ dcBuffer = new Uint16Array(dcBytes.buffer, dcBytes.byteOffset, dcWords);
1028
1032
  cursor.value += header.dcCompressedSize;
1029
1033
  } else if (header.totalDcUncompressedCount !== 0) {
1030
1034
  throw new Error("Invalid DWA DC payload metadata.");
@@ -1040,9 +1044,7 @@ function decodeDwaChunk(context) {
1040
1044
  if (decoded.byteLength !== header.rleUncompressedSize) {
1041
1045
  throw new Error("Invalid DWA RLE intermediate payload length.");
1042
1046
  }
1043
- const decodedRle = decodeRunLength(decoded, header.rleRawSize);
1044
- rleBuffer = new Uint8Array(decodedRle.byteLength);
1045
- rleBuffer.set(decodedRle);
1047
+ rleBuffer = decodeRunLength(decoded, header.rleRawSize);
1046
1048
  cursor.value += header.rleCompressedSize;
1047
1049
  } else if (header.rleCompressedSize !== 0 || header.rleUncompressedSize !== 0) {
1048
1050
  throw new Error("Invalid DWA RLE payload metadata.");
@@ -1139,18 +1141,20 @@ function decodeDwaBlock(context) {
1139
1141
  var scope = self;
1140
1142
  var part = null;
1141
1143
  var partId = 0;
1142
- function toTransferBuffer(view) {
1143
- const output = new Uint8Array(view.byteLength);
1144
- output.set(view);
1145
- return output.buffer;
1146
- }
1147
1144
  scope.onmessage = (event) => {
1148
1145
  const message = event.data;
1146
+ if (message.type === "reset") {
1147
+ part = null;
1148
+ partId = 0;
1149
+ resetDwaDecodeScratch();
1150
+ return;
1151
+ }
1149
1152
  if (message.type === "init") {
1150
1153
  part = message.part;
1151
1154
  partId = message.partId;
1152
1155
  return;
1153
1156
  }
1157
+ const startedAt = workerDecodeClock();
1154
1158
  try {
1155
1159
  if (!part) {
1156
1160
  throw new Error("DWA worker is not initialized.");
@@ -1165,11 +1169,12 @@ scope.onmessage = (event) => {
1165
1169
  chunkY: message.chunkY,
1166
1170
  linesInChunk: message.linesInChunk
1167
1171
  });
1168
- const transfer = toTransferBuffer(decoded);
1172
+ const transfer = decoded.buffer;
1169
1173
  const response = {
1170
1174
  id: message.id,
1171
1175
  ok: true,
1172
- decoded: transfer
1176
+ decoded: transfer,
1177
+ timing: { startedAt, finishedAt: workerDecodeClock() }
1173
1178
  };
1174
1179
  scope.postMessage(response, [transfer]);
1175
1180
  } catch (error) {