@bb-studio/exr 0.1.2 → 0.1.3

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/README.md CHANGED
@@ -4,7 +4,7 @@
4
4
  [![GitHub Pages](https://img.shields.io/badge/GitHub%20Pages-Live%20Demo-0?logo=github)](https://promto-c.github.io/exr-lab/)
5
5
  [![GitHub](https://img.shields.io/github/stars/promto-c/exr-lab)](https://github.com/promto-c/exr-lab)
6
6
 
7
- OpenEXR scanline parser/decoder for browser and Node.js.
7
+ OpenEXR scanline parser/decoder/encoder and backend-neutral RGBA helpers for browser and Node.js.
8
8
 
9
9
  ## Install
10
10
 
@@ -12,6 +12,23 @@ OpenEXR scanline parser/decoder for browser and Node.js.
12
12
  npm install @bb-studio/exr
13
13
  ```
14
14
 
15
+ ## Image API
16
+
17
+ ```ts
18
+ import { decodeExrRgba, encodeExrRgba, inspectExrImage } from '@bb-studio/exr';
19
+
20
+ const info = inspectExrImage(buffer);
21
+ const image = decodeExrRgba(buffer);
22
+ const encodedImage = encodeExrRgba(
23
+ { width: image.width, height: image.height, rgba: image.rgba },
24
+ { precision: 'half', includeAlpha: true },
25
+ );
26
+ ```
27
+
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.
29
+
30
+ `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
+
15
32
  ## Core API
16
33
 
17
34
  ```ts
@@ -66,7 +83,8 @@ import { decodeExrPartWithWorkers, expandDecodedPartChannels } from '@bb-studio/
66
83
  ```
67
84
 
68
85
  - `decodeExrPartWithWorkers` optionally pre-decodes ZIP/DWA chunks using workers.
69
- - `expandDecodedPartChannels` converts sampled channels into full-resolution planes.
86
+ - `decodeExrRgbaWithWorkers` applies the same RGBA semantics through the worker-assisted path.
87
+ - `expandDecodedPartChannels` is available from the root package and remains re-exported here for existing browser consumers.
70
88
 
71
89
  ## Error/Diagnostics
72
90
 
@@ -14,6 +14,8 @@ interface EventCapableOptions {
14
14
  onEvent?: ExrEventCallback;
15
15
  }
16
16
 
17
+ type ExrBinaryInput = ArrayBuffer | Uint8Array;
18
+
17
19
  type ExrPixelType = 0 | 1 | 2;
18
20
  type ExrCompression = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9;
19
21
 
@@ -80,7 +82,23 @@ interface DecodeExrPartWithWorkersOptions extends DecodeExrPartOptions {
80
82
  }
81
83
  declare function decodeExrPartWithWorkers(bufferInput: ArrayBuffer | Uint8Array, structure: ExrStructure, options: DecodeExrPartWithWorkersOptions): Promise<DecodedPart>;
82
84
 
85
+ interface DecodedExrRgbaImage {
86
+ width: number;
87
+ height: number;
88
+ rgba: Float32Array;
89
+ partId: number;
90
+ dataWindow: ExrWindow;
91
+ displayWindow?: ExrWindow;
92
+ channels: readonly ExrChannel[];
93
+ attributes: Readonly<Record<string, unknown>>;
94
+ }
95
+
96
+ type DecodeExrRgbaWithWorkersOptions = Omit<DecodeExrPartWithWorkersOptions, 'partId'> & {
97
+ partId?: number;
98
+ };
99
+ declare function decodeExrRgbaWithWorkers(buffer: ExrBinaryInput, options?: DecodeExrRgbaWithWorkersOptions): Promise<DecodedExrRgbaImage>;
100
+
83
101
  declare function expandSampledChannel(width: number, height: number, xMin: number, yMin: number, channel: DecodedChannel): Float32Array;
84
102
  declare function expandDecodedPartChannels(decoded: DecodedPart, dataWindow: ExrWindow): Record<string, Float32Array>;
85
103
 
86
- export { type DecodeExrPartWithWorkersOptions, type WorkerFactory, decodeExrPartWithWorkers, expandDecodedPartChannels, expandSampledChannel };
104
+ export { type DecodeExrPartWithWorkersOptions, type DecodeExrRgbaWithWorkersOptions, type WorkerFactory, decodeExrPartWithWorkers, decodeExrRgbaWithWorkers, expandDecodedPartChannels, expandSampledChannel };
@@ -1,4 +1,5 @@
1
1
  // src/shared/constants.ts
2
+ var EXR_MAGIC = 20000630;
2
3
  var COMPRESSION_NAMES = {
3
4
  0: "NO_COMPRESSION",
4
5
  1: "RLE_COMPRESSION",
@@ -3099,7 +3100,7 @@ async function decodeExrPartWithWorkers(bufferInput, structure, options) {
3099
3100
  });
3100
3101
  }
3101
3102
 
3102
- // src/browser/expandSampledChannels.ts
3103
+ // src/reader/expandSampledChannels.ts
3103
3104
  function clamp2(value, min, max) {
3104
3105
  if (value < min) return min;
3105
3106
  if (value > max) return max;
@@ -3162,8 +3163,451 @@ function expandDecodedPartChannels(decoded, dataWindow) {
3162
3163
  }
3163
3164
  return output;
3164
3165
  }
3166
+
3167
+ // src/reader/rgbaChannels.ts
3168
+ function normalizeChannelName(name) {
3169
+ return name.split(".").pop()?.toUpperCase() ?? "";
3170
+ }
3171
+ function pickChannel(channels, aliases) {
3172
+ for (const alias of aliases) {
3173
+ const exact = channels[alias];
3174
+ if (exact) return exact;
3175
+ }
3176
+ const normalizedAliases = new Set(aliases.map((alias) => alias.toUpperCase()));
3177
+ for (const [name, channel] of Object.entries(channels)) {
3178
+ if (normalizedAliases.has(normalizeChannelName(name))) return channel;
3179
+ }
3180
+ return void 0;
3181
+ }
3182
+ function decodedPartToRgba(width, height, dataWindow, channels) {
3183
+ const expanded = expandDecodedPartChannels({ width, height, channels }, dataWindow);
3184
+ const fallback = Object.values(expanded)[0] ?? new Float32Array(width * height);
3185
+ const red = pickChannel(expanded, ["R", "RED"]) ?? fallback;
3186
+ const luma = pickChannel(expanded, ["Y", "LUMA", "LUMINANCE"]);
3187
+ const green = pickChannel(expanded, ["G", "GREEN"]) ?? luma ?? red;
3188
+ const blue = pickChannel(expanded, ["B", "BLUE"]) ?? luma ?? red;
3189
+ const alpha = pickChannel(expanded, ["A", "ALPHA"]);
3190
+ const pixelCount = width * height;
3191
+ const rgba = new Float32Array(pixelCount * 4);
3192
+ for (let index = 0; index < pixelCount; index += 1) {
3193
+ const offset = index * 4;
3194
+ rgba[offset] = Number.isFinite(red[index]) ? red[index] : 0;
3195
+ rgba[offset + 1] = Number.isFinite(green[index]) ? green[index] : rgba[offset];
3196
+ rgba[offset + 2] = Number.isFinite(blue[index]) ? blue[index] : rgba[offset];
3197
+ rgba[offset + 3] = alpha ? Math.max(0, alpha[index]) : 1;
3198
+ }
3199
+ return rgba;
3200
+ }
3201
+
3202
+ // src/reader/parseExrStructure.ts
3203
+ function nowMs2() {
3204
+ return typeof performance !== "undefined" ? performance.now() : Date.now();
3205
+ }
3206
+ var BinaryReader = class {
3207
+ constructor(buffer) {
3208
+ this.buffer = buffer;
3209
+ this.view = new DataView(buffer);
3210
+ }
3211
+ view;
3212
+ offset = 0;
3213
+ get byteLength() {
3214
+ return this.view.byteLength;
3215
+ }
3216
+ ensureAvailable(count, code, context) {
3217
+ if (count < 0 || this.offset + count > this.view.byteLength) {
3218
+ throw new ExrError("TRUNCATED_FILE", `Unexpected EOF while reading ${context}.`, {
3219
+ code,
3220
+ offset: this.offset,
3221
+ requested: count,
3222
+ size: this.view.byteLength
3223
+ });
3224
+ }
3225
+ }
3226
+ peekUint8() {
3227
+ this.ensureAvailable(1, "peek_u8", "byte");
3228
+ return this.view.getUint8(this.offset);
3229
+ }
3230
+ readUint8() {
3231
+ this.ensureAvailable(1, "u8", "byte");
3232
+ const value = this.view.getUint8(this.offset);
3233
+ this.offset += 1;
3234
+ return value;
3235
+ }
3236
+ readInt32() {
3237
+ this.ensureAvailable(4, "i32", "int32");
3238
+ const value = this.view.getInt32(this.offset, true);
3239
+ this.offset += 4;
3240
+ return value;
3241
+ }
3242
+ readUint32() {
3243
+ this.ensureAvailable(4, "u32", "uint32");
3244
+ const value = this.view.getUint32(this.offset, true);
3245
+ this.offset += 4;
3246
+ return value;
3247
+ }
3248
+ readFloat32() {
3249
+ this.ensureAvailable(4, "f32", "float32");
3250
+ const value = this.view.getFloat32(this.offset, true);
3251
+ this.offset += 4;
3252
+ return value;
3253
+ }
3254
+ readCString(context) {
3255
+ let value = "";
3256
+ while (this.offset < this.view.byteLength) {
3257
+ const ch = this.readUint8();
3258
+ if (ch === 0) return value;
3259
+ value += String.fromCharCode(ch);
3260
+ }
3261
+ throw new ExrError("TRUNCATED_FILE", `Unterminated string while reading ${context}.`, {
3262
+ offset: this.offset
3263
+ });
3264
+ }
3265
+ readCStringWithin(limit, context) {
3266
+ if (limit < this.offset || limit > this.view.byteLength) {
3267
+ throw new ExrError("MALFORMED_HEADER", `Invalid bounded read while parsing ${context}.`, {
3268
+ offset: this.offset,
3269
+ limit
3270
+ });
3271
+ }
3272
+ let value = "";
3273
+ while (this.offset < limit) {
3274
+ const ch = this.readUint8();
3275
+ if (ch === 0) return value;
3276
+ value += String.fromCharCode(ch);
3277
+ }
3278
+ throw new ExrError("MALFORMED_HEADER", `Unterminated string while reading ${context}.`, {
3279
+ offset: this.offset,
3280
+ limit
3281
+ });
3282
+ }
3283
+ skip(count, context) {
3284
+ this.ensureAvailable(count, "skip", context);
3285
+ this.offset += count;
3286
+ }
3287
+ };
3288
+ function emit2(onEvent, event) {
3289
+ onEvent?.(event);
3290
+ }
3291
+ function ensureExactAttributeSize(name, type, size, expected) {
3292
+ if (size !== expected) {
3293
+ throw new ExrError("MALFORMED_HEADER", `Invalid ${type} attribute size for ${name}.`, {
3294
+ attribute: name,
3295
+ expected,
3296
+ actual: size
3297
+ });
3298
+ }
3299
+ }
3300
+ function parsePartHeader(reader, index) {
3301
+ if (reader.peekUint8() === 0) {
3302
+ return null;
3303
+ }
3304
+ const attributes = {};
3305
+ const channels = [];
3306
+ while (reader.offset < reader.byteLength) {
3307
+ const name = reader.readCString("attribute name");
3308
+ if (name === "") {
3309
+ break;
3310
+ }
3311
+ const type = reader.readCString(`attribute type for ${name}`);
3312
+ const size = reader.readInt32();
3313
+ if (size < 0) {
3314
+ throw new ExrError("MALFORMED_HEADER", `Negative attribute size for ${name}.`, {
3315
+ attribute: name,
3316
+ size
3317
+ });
3318
+ }
3319
+ const valueStart = reader.offset;
3320
+ reader.ensureAvailable(size, "attribute_size", `attribute payload for ${name}`);
3321
+ let value;
3322
+ if (type === "chlist") {
3323
+ const channelEnd = valueStart + size;
3324
+ let sawChannelListTerminator = false;
3325
+ while (reader.offset < channelEnd) {
3326
+ const channelName = reader.readCStringWithin(channelEnd, "channel name");
3327
+ if (channelName === "") {
3328
+ sawChannelListTerminator = true;
3329
+ break;
3330
+ }
3331
+ if (reader.offset + 16 > channelEnd) {
3332
+ throw new ExrError("MALFORMED_HEADER", `Truncated channel record for ${channelName}.`, {
3333
+ attribute: name,
3334
+ channel: channelName,
3335
+ offset: reader.offset,
3336
+ channelEnd
3337
+ });
3338
+ }
3339
+ const pixelType = reader.readInt32();
3340
+ const pLinear = reader.readUint8();
3341
+ reader.skip(3, "channel reserved bytes");
3342
+ const xSampling = reader.readInt32();
3343
+ const ySampling = reader.readInt32();
3344
+ channels.push({
3345
+ name: channelName,
3346
+ pixelType,
3347
+ pLinear,
3348
+ xSampling,
3349
+ ySampling
3350
+ });
3351
+ }
3352
+ if (!sawChannelListTerminator) {
3353
+ throw new ExrError("MALFORMED_HEADER", "Channel list payload is missing terminator.", {
3354
+ attribute: name,
3355
+ size
3356
+ });
3357
+ }
3358
+ if (reader.offset !== channelEnd) {
3359
+ throw new ExrError("MALFORMED_HEADER", "Channel list payload had trailing bytes.", {
3360
+ attribute: name,
3361
+ offset: reader.offset,
3362
+ expectedEnd: channelEnd
3363
+ });
3364
+ }
3365
+ value = `(${channels.length} channels)`;
3366
+ } else if (type === "compression") {
3367
+ ensureExactAttributeSize(name, type, size, 1);
3368
+ value = reader.readUint8();
3369
+ } else if (type === "box2i") {
3370
+ ensureExactAttributeSize(name, type, size, 16);
3371
+ value = {
3372
+ xMin: reader.readInt32(),
3373
+ yMin: reader.readInt32(),
3374
+ xMax: reader.readInt32(),
3375
+ yMax: reader.readInt32()
3376
+ };
3377
+ } else if (type === "string") {
3378
+ let stringValue = "";
3379
+ for (let i = 0; i < size; i++) {
3380
+ const charCode = reader.readUint8();
3381
+ if (charCode === 0) break;
3382
+ stringValue += String.fromCharCode(charCode);
3383
+ }
3384
+ value = stringValue;
3385
+ } else if (type === "int") {
3386
+ ensureExactAttributeSize(name, type, size, 4);
3387
+ value = reader.readInt32();
3388
+ } else if (type === "float") {
3389
+ ensureExactAttributeSize(name, type, size, 4);
3390
+ value = reader.readFloat32();
3391
+ } else if (type === "chromaticities") {
3392
+ ensureExactAttributeSize(name, type, size, 32);
3393
+ value = {
3394
+ redX: reader.readFloat32(),
3395
+ redY: reader.readFloat32(),
3396
+ greenX: reader.readFloat32(),
3397
+ greenY: reader.readFloat32(),
3398
+ blueX: reader.readFloat32(),
3399
+ blueY: reader.readFloat32(),
3400
+ whiteX: reader.readFloat32(),
3401
+ whiteY: reader.readFloat32()
3402
+ };
3403
+ } else {
3404
+ reader.skip(size, `unknown attribute ${name}`);
3405
+ value = `<${type} data>`;
3406
+ }
3407
+ reader.offset = valueStart + size;
3408
+ attributes[name] = value;
3409
+ }
3410
+ return {
3411
+ id: index,
3412
+ attributes,
3413
+ channels,
3414
+ dataWindow: attributes.dataWindow,
3415
+ displayWindow: attributes.displayWindow,
3416
+ compression: attributes.compression,
3417
+ type: attributes.type
3418
+ };
3419
+ }
3420
+ function parseExrStructure(bufferInput, options = {}) {
3421
+ const onEvent = options.onEvent;
3422
+ const t0 = nowMs2();
3423
+ const buffer = toArrayBuffer(bufferInput);
3424
+ if (buffer.byteLength < 8) {
3425
+ throw new ExrError("BUFFER_TOO_SMALL", "Buffer is too small to be an EXR file.", {
3426
+ size: buffer.byteLength
3427
+ });
3428
+ }
3429
+ const reader = new BinaryReader(buffer);
3430
+ const tMagic = nowMs2();
3431
+ const magic = reader.readUint32();
3432
+ if (magic !== EXR_MAGIC) {
3433
+ emit2(onEvent, {
3434
+ phase: "parse",
3435
+ level: "error",
3436
+ code: "parse.magic.invalid",
3437
+ message: "Invalid EXR magic number.",
3438
+ metrics: {
3439
+ expected: `0x${EXR_MAGIC.toString(16)}`,
3440
+ actual: `0x${magic.toString(16)}`
3441
+ }
3442
+ });
3443
+ throw new ExrError("INVALID_MAGIC", "Invalid EXR magic number.", {
3444
+ expected: EXR_MAGIC,
3445
+ actual: magic
3446
+ });
3447
+ }
3448
+ emit2(onEvent, {
3449
+ phase: "parse",
3450
+ level: "info",
3451
+ code: "parse.magic.ok",
3452
+ message: "Parsed EXR magic number.",
3453
+ metrics: {
3454
+ ms: (nowMs2() - tMagic).toFixed(3),
3455
+ magic: `0x${EXR_MAGIC.toString(16)}`
3456
+ }
3457
+ });
3458
+ const tVersion = nowMs2();
3459
+ const versionField = reader.readUint32();
3460
+ const version = versionField & 255;
3461
+ const flags = versionField >> 8;
3462
+ const isMultipart = (flags & 16) !== 0;
3463
+ emit2(onEvent, {
3464
+ phase: "parse",
3465
+ level: "info",
3466
+ code: "parse.version.ok",
3467
+ message: "Parsed EXR version and flags.",
3468
+ metrics: {
3469
+ ms: (nowMs2() - tVersion).toFixed(3),
3470
+ version,
3471
+ flags,
3472
+ multipart: isMultipart ? 1 : 0
3473
+ }
3474
+ });
3475
+ const parts = [];
3476
+ let partIndex = 0;
3477
+ while (reader.offset < reader.byteLength) {
3478
+ const tHeader = nowMs2();
3479
+ const part = parsePartHeader(reader, partIndex);
3480
+ if (!part) {
3481
+ if (isMultipart) {
3482
+ reader.skip(1, "multipart header terminator");
3483
+ }
3484
+ break;
3485
+ }
3486
+ parts.push(part);
3487
+ emit2(onEvent, {
3488
+ phase: "parse",
3489
+ level: "info",
3490
+ code: "parse.part.ok",
3491
+ message: `Parsed part ${part.id} header.`,
3492
+ metrics: {
3493
+ ms: (nowMs2() - tHeader).toFixed(3),
3494
+ partId: part.id,
3495
+ channels: part.channels.length,
3496
+ compression: COMPRESSION_NAMES[part.compression ?? -1] || "UNKNOWN"
3497
+ }
3498
+ });
3499
+ partIndex += 1;
3500
+ if (!isMultipart) {
3501
+ break;
3502
+ }
3503
+ if (reader.offset >= reader.byteLength) {
3504
+ throw new ExrError("TRUNCATED_FILE", "Unexpected EOF while reading multipart headers.", {
3505
+ offset: reader.offset
3506
+ });
3507
+ }
3508
+ if (reader.peekUint8() === 0) {
3509
+ reader.skip(1, "multipart headers terminator");
3510
+ break;
3511
+ }
3512
+ }
3513
+ if (parts.length === 0) {
3514
+ throw new ExrError("MALFORMED_HEADER", "No EXR headers were parsed.", {
3515
+ offset: reader.offset
3516
+ });
3517
+ }
3518
+ const structure = {
3519
+ magic,
3520
+ version,
3521
+ flags,
3522
+ isMultipart,
3523
+ parts,
3524
+ headerEndOffset: reader.offset
3525
+ };
3526
+ emit2(onEvent, {
3527
+ phase: "parse",
3528
+ level: "info",
3529
+ code: "parse.complete",
3530
+ message: "EXR structure parsed.",
3531
+ metrics: {
3532
+ ms: (nowMs2() - t0).toFixed(3),
3533
+ parts: parts.length,
3534
+ headerEndOffset: structure.headerEndOffset
3535
+ }
3536
+ });
3537
+ return structure;
3538
+ }
3539
+
3540
+ // src/reader/exrImage.ts
3541
+ function selectExrImagePart(structure, partId) {
3542
+ if (partId !== void 0) {
3543
+ const part2 = structure.parts.find((candidate) => candidate.id === partId);
3544
+ if (!part2) {
3545
+ throw new ExrError("PART_NOT_FOUND", `Part ${partId} was not found in EXR structure.`, {
3546
+ partId
3547
+ });
3548
+ }
3549
+ if (!part2.dataWindow) {
3550
+ throw new ExrError("MISSING_DATA_WINDOW", `Part ${partId} is missing a data window.`, {
3551
+ partId
3552
+ });
3553
+ }
3554
+ return part2;
3555
+ }
3556
+ const part = structure.parts.find((candidate) => candidate.dataWindow);
3557
+ if (!part?.dataWindow) {
3558
+ throw new ExrError(
3559
+ "MISSING_DATA_WINDOW",
3560
+ "EXR file does not contain a decodable scanline part."
3561
+ );
3562
+ }
3563
+ return part;
3564
+ }
3565
+ function getExrPartDimensions(part) {
3566
+ if (!part.dataWindow) {
3567
+ throw new ExrError("MISSING_DATA_WINDOW", `Part ${part.id} is missing a data window.`, {
3568
+ partId: part.id
3569
+ });
3570
+ }
3571
+ return {
3572
+ width: part.dataWindow.xMax - part.dataWindow.xMin + 1,
3573
+ height: part.dataWindow.yMax - part.dataWindow.yMin + 1
3574
+ };
3575
+ }
3576
+ function inspectExrImage(buffer, options = {}) {
3577
+ const structure = parseExrStructure(buffer, { onEvent: options.onEvent });
3578
+ const part = selectExrImagePart(structure, options.partId);
3579
+ const dimensions = getExrPartDimensions(part);
3580
+ return {
3581
+ structure,
3582
+ part,
3583
+ partId: part.id,
3584
+ ...dimensions,
3585
+ dataWindow: part.dataWindow,
3586
+ displayWindow: part.displayWindow
3587
+ };
3588
+ }
3589
+
3590
+ // src/browser/decodeExrRgbaWithWorkers.ts
3591
+ async function decodeExrRgbaWithWorkers(buffer, options = {}) {
3592
+ const info = inspectExrImage(buffer, options);
3593
+ const decoded = await decodeExrPartWithWorkers(buffer, info.structure, {
3594
+ ...options,
3595
+ partId: info.partId
3596
+ });
3597
+ return {
3598
+ width: info.width,
3599
+ height: info.height,
3600
+ rgba: decodedPartToRgba(info.width, info.height, info.dataWindow, decoded.channels),
3601
+ partId: info.partId,
3602
+ dataWindow: info.dataWindow,
3603
+ displayWindow: info.displayWindow,
3604
+ channels: info.part.channels,
3605
+ attributes: info.part.attributes
3606
+ };
3607
+ }
3165
3608
  export {
3166
3609
  decodeExrPartWithWorkers,
3610
+ decodeExrRgbaWithWorkers,
3167
3611
  expandDecodedPartChannels,
3168
3612
  expandSampledChannel
3169
3613
  };