ag-psd 34.2.3 → 34.2.4

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/src/psdReader.ts CHANGED
@@ -31,6 +31,7 @@ export interface PsdReader extends ReadOptions {
31
31
  layersInGlobalInfo?: boolean; // layers were read from Lr16/Lr32/Layr global additional info
32
32
  imageResourcesWhitelistSet?: Set<string>; // `imageResourcesWhitelist` option converted to a Set
33
33
  log(...args: any[]): void;
34
+ sectionEnd?: number; // end offset of the innermost section being read (descriptors are not read past it)
34
35
  // text decoders, created lazily (null if not supported)
35
36
  utf8Decoder?: TextDecoder | null;
36
37
  utf8StrictDecoder?: TextDecoder | null;
@@ -1148,7 +1149,8 @@ function readImageData(reader: PsdReader, psd: Psd) {
1148
1149
  if (supportedColorModes.indexOf(psd.colorMode!) === -1)
1149
1150
  throw new Error(`Color mode not supported: ${psd.colorMode}`);
1150
1151
 
1151
- if (compression !== Compression.RawData && compression !== Compression.RleCompressed)
1152
+ if (compression !== Compression.RawData && compression !== Compression.RleCompressed &&
1153
+ compression !== Compression.ZipWithoutPrediction && compression !== Compression.ZipWithPrediction)
1152
1154
  throw new Error(`Compression type not supported: ${compression}`);
1153
1155
 
1154
1156
  const imageData = createImageDataBitDepth(width, height, bitsPerChannel, 4, reader.totalMemoryLimit);
@@ -1166,7 +1168,7 @@ function readImageData(reader: PsdReader, psd: Psd) {
1166
1168
  bytes = readBytes(reader, rowBytes * height);
1167
1169
  } else {
1168
1170
  bytes = new Uint8Array(rowBytes * height);
1169
- readDataRLE(reader, { data: bytes, width: rowBytes, height }, rowBytes, height, 8, 1, [0], reader.large);
1171
+ readCompositeChannels(reader, compression, { data: bytes, width: rowBytes, height }, 8, 1, [0]);
1170
1172
  }
1171
1173
 
1172
1174
  decodeBitmap(bytes, imageData.data, width, height);
@@ -1258,11 +1260,80 @@ function readCompositeChannels(reader: PsdReader, compression: Compression, pixe
1258
1260
  }
1259
1261
  } else if (compression === Compression.RleCompressed) {
1260
1262
  readDataRLE(reader, pixelData, pixelData.width, pixelData.height, bitsPerChannel, step, offsets, reader.large);
1263
+ } else if (compression === Compression.ZipWithoutPrediction || compression === Compression.ZipWithPrediction) {
1264
+ readCompositeChannelsZip(reader, pixelData, bitsPerChannel, step, offsets, compression === Compression.ZipWithPrediction);
1261
1265
  } else {
1262
1266
  throw new Error(`Compression not supported: ${compression}`);
1263
1267
  }
1264
1268
  }
1265
1269
 
1270
+ // Zip compressed composite image data has no lengths of channels. Applications that write it (Photoshop writes RLE)
1271
+ // store each channel as a separate zlib stream, like channels of layers, or all the channels in one stream. Reads all
1272
+ // the remaining data, the composite image is the last section of the file.
1273
+ function readCompositeChannelsZip(reader: PsdReader, pixelData: PixelData, bitsPerChannel: number, step: number, offsets: number[], prediction: boolean) {
1274
+ const { width, height } = pixelData;
1275
+ const bpv = bytesPerValue(bitsPerChannel);
1276
+ const channelSize = width * height * bpv;
1277
+ verifyArrayType(pixelData.data, bpv);
1278
+
1279
+ const input = readBytes(reader, Math.max(0, reader.view.byteLength - reader.offset));
1280
+ consumeMemory(reader, channelSize);
1281
+
1282
+ try {
1283
+ const channel = new Uint8Array(channelSize);
1284
+
1285
+ for (let i = 0, position = 0; i < offsets.length && position < input.length; i++) {
1286
+ if (i) channel.fill(0);
1287
+ const stream = inflateZlibStream(input.subarray(position), channel);
1288
+
1289
+ if (i === 0 && stream.overflow) {
1290
+ readCompositeChannelsZipSingleStream(reader, input, pixelData, bpv, step, offsets, prediction);
1291
+ return;
1292
+ }
1293
+
1294
+ if (stream.overflow) {
1295
+ warnOrThrow(reader, zipOverflow.message);
1296
+ } else if (!stream.complete) {
1297
+ warnOrThrow(reader, 'Invalid zip data: unexpected end of data');
1298
+ }
1299
+
1300
+ if (offsets[i] >= 0) writeZipChannel(channel, pixelData, width, height, bpv, step, offsets[i], prediction);
1301
+ position += stream.length;
1302
+ }
1303
+ } finally {
1304
+ recoverMemory(reader, channelSize);
1305
+ }
1306
+ }
1307
+
1308
+ // all the channels in one zlib stream, one after another
1309
+ function readCompositeChannelsZipSingleStream(
1310
+ reader: PsdReader, input: Uint8Array, pixelData: PixelData, bpv: number, step: number, offsets: number[], prediction: boolean
1311
+ ) {
1312
+ const { width, height } = pixelData;
1313
+ const channelSize = width * height * bpv;
1314
+ const size = channelSize * offsets.length;
1315
+ consumeMemory(reader, size);
1316
+
1317
+ try {
1318
+ const channels = new Uint8Array(size);
1319
+ const stream = inflateZlibStream(input, channels);
1320
+
1321
+ if (stream.overflow) {
1322
+ warnOrThrow(reader, zipOverflow.message);
1323
+ } else if (!stream.complete) {
1324
+ warnOrThrow(reader, 'Invalid zip data: unexpected end of data');
1325
+ }
1326
+
1327
+ for (let i = 0; i < offsets.length; i++) {
1328
+ if (offsets[i] < 0) continue;
1329
+ const channel = channels.subarray(i * channelSize, (i + 1) * channelSize);
1330
+ writeZipChannel(channel, pixelData, width, height, bpv, step, offsets[i], prediction);
1331
+ }
1332
+ } finally {
1333
+ recoverMemory(reader, size);
1334
+ }
1335
+ }
1336
+
1266
1337
  // un-premultiplies colors from white matte, used for composite image of documents with global alpha
1267
1338
  function removeWhiteMatte({ data, width, height }: PixelData) {
1268
1339
  const size = width * height * 4;
@@ -1469,6 +1540,55 @@ function inflateLimited(compressed: Uint8Array, expectedSize: number, reader: Ps
1469
1540
  return output;
1470
1541
  }
1471
1542
 
1543
+ // Inflates the zlib stream at the start of `input` into `output`. Returns the length of the stream in `input`
1544
+ // (header and checksum included) and whether the stream ended within `input` without exceeding `output`.
1545
+ // The data is inflated as raw deflate data, because in zlib mode pako continues into the stream that follows as if
1546
+ // it was part of the same data. The checksum is not verified.
1547
+ function inflateZlibStream(input: Uint8Array, output: Uint8Array) {
1548
+ const cmf = input[0], flg = input[1];
1549
+
1550
+ // deflate compression method, valid header check bits, no preset dictionary
1551
+ if (input.length < 2 || (cmf & 0x0f) !== 8 || ((cmf << 8) | flg) % 31 !== 0 || (flg & 0x20) !== 0) {
1552
+ throw new Error('Invalid zip data: incorrect header check');
1553
+ }
1554
+
1555
+ let written = 0;
1556
+ let overflow = false;
1557
+ let ended = false;
1558
+ let deflateLength = 0;
1559
+
1560
+ const inflator = new Inflate({ chunkSize: Math.max(1024, Math.min(output.length, 0x10000)), raw: true });
1561
+ inflator.onData = (chunk: any) => {
1562
+ const data = chunk as Uint8Array;
1563
+ const count = Math.min(data.length, output.length - written);
1564
+ if (count > 0) output.set(count === data.length ? data : data.subarray(0, count), written);
1565
+ written += count;
1566
+
1567
+ if (count < data.length) {
1568
+ overflow = true;
1569
+ throw zipOverflow;
1570
+ }
1571
+ };
1572
+ inflator.onEnd = (status: number) => {
1573
+ inflator.err = status;
1574
+ inflator.msg = (inflator as any).strm?.msg || '';
1575
+ ended = true;
1576
+ deflateLength = (inflator as any).strm?.next_in ?? 0;
1577
+ };
1578
+
1579
+ try {
1580
+ inflator.push(input.subarray(2), true);
1581
+ } catch (e) {
1582
+ if (e !== zipOverflow) throw e;
1583
+ }
1584
+
1585
+ if (overflow) return { length: input.length, complete: false, overflow };
1586
+ if (inflator.err) throw new Error(`Invalid zip data: ${inflator.msg}`);
1587
+ if (!ended) return { length: input.length, complete: false, overflow }; // data ends before the stream does
1588
+
1589
+ return { length: Math.min(input.length, 2 + deflateLength + 4), complete: true, overflow };
1590
+ }
1591
+
1472
1592
  export function readDataZip(
1473
1593
  compressed: Uint8Array, pixelData: PixelData | undefined, width: number, height: number, bitDepth: number, step: number,
1474
1594
  offset: number, prediction: boolean, reader?: PsdReader
@@ -1477,62 +1597,69 @@ export function readDataZip(
1477
1597
 
1478
1598
  if (!pixelData || offset < 0 || offset >= step) return;
1479
1599
 
1480
- const data = pixelData.data;
1481
- verifyArrayType(data, bpv);
1600
+ verifyArrayType(pixelData.data, bpv);
1482
1601
 
1483
1602
  const expectedSize = width * height * bpv;
1484
1603
  if (reader) consumeMemory(reader, expectedSize);
1485
1604
 
1486
1605
  try {
1487
- const decompressed = inflateLimited(compressed, expectedSize, reader);
1606
+ writeZipChannel(inflateLimited(compressed, expectedSize, reader), pixelData, width, height, bpv, step, offset, prediction);
1607
+ } finally {
1608
+ if (reader) recoverMemory(reader, expectedSize);
1609
+ }
1610
+ }
1488
1611
 
1489
- if (bpv === 1) {
1490
- for (let y = 0, i = 0; y < height; y++) {
1491
- let prev = 0;
1612
+ // writes inflated values of one channel to `pixelData` (modifies `decompressed` when decoding 32bit prediction)
1613
+ function writeZipChannel(
1614
+ decompressed: Uint8Array, pixelData: PixelData, width: number, height: number, bpv: number, step: number,
1615
+ offset: number, prediction: boolean
1616
+ ) {
1617
+ const data = pixelData.data;
1492
1618
 
1493
- for (let x = 0, p = offset + y * width * step; x < width; x++, i++, p += step) {
1494
- let v = decompressed[i];
1495
- if (prediction) v = prev = (prev + v) & 0xff;
1496
- data[p] = v;
1497
- }
1619
+ if (bpv === 1) {
1620
+ for (let y = 0, i = 0; y < height; y++) {
1621
+ let prev = 0;
1622
+
1623
+ for (let x = 0, p = offset + y * width * step; x < width; x++, i++, p += step) {
1624
+ let v = decompressed[i];
1625
+ if (prediction) v = prev = (prev + v) & 0xff;
1626
+ data[p] = v;
1498
1627
  }
1499
- } else if (bpv === 2) {
1500
- for (let y = 0, i = 0; y < height; y++) {
1501
- let prev = 0;
1502
-
1503
- for (let x = 0, p = offset + y * width * step; x < width; x++, i += 2, p += step) {
1504
- let v = (decompressed[i] << 8) | decompressed[i + 1];
1505
- if (prediction) v = prev = (prev + v) & 0xffff;
1506
- data[p] = v;
1507
- }
1628
+ }
1629
+ } else if (bpv === 2) {
1630
+ for (let y = 0, i = 0; y < height; y++) {
1631
+ let prev = 0;
1632
+
1633
+ for (let x = 0, p = offset + y * width * step; x < width; x++, i += 2, p += step) {
1634
+ let v = (decompressed[i] << 8) | decompressed[i + 1];
1635
+ if (prediction) v = prev = (prev + v) & 0xffff;
1636
+ data[p] = v;
1508
1637
  }
1509
- } else {
1510
- const dst = new Uint32Array(data.buffer, data.byteOffset, data.length);
1638
+ }
1639
+ } else {
1640
+ const dst = new Uint32Array(data.buffer, data.byteOffset, data.length);
1511
1641
 
1512
- if (prediction) {
1513
- // bytes are delta encoded per row and stored in planar order (all 1st bytes, all 2nd bytes, ...)
1514
- decodePredicted(decompressed, width * 4, height);
1642
+ if (prediction) {
1643
+ // bytes are delta encoded per row and stored in planar order (all 1st bytes, all 2nd bytes, ...)
1644
+ decodePredicted(decompressed, width * 4, height);
1515
1645
 
1516
- for (let y = 0, di = offset; y < height; y++) {
1517
- let a = width * 4 * y;
1646
+ for (let y = 0, di = offset; y < height; y++) {
1647
+ let a = width * 4 * y;
1518
1648
 
1519
- for (let x = 0; x < width; x++, a++, di += step) {
1520
- const b = a + width;
1521
- const c = b + width;
1522
- const d = c + width;
1523
- dst[di] = ((decompressed[a] << 24) | (decompressed[b] << 16) | (decompressed[c] << 8) | decompressed[d]) >>> 0;
1524
- }
1649
+ for (let x = 0; x < width; x++, a++, di += step) {
1650
+ const b = a + width;
1651
+ const c = b + width;
1652
+ const d = c + width;
1653
+ dst[di] = ((decompressed[a] << 24) | (decompressed[b] << 16) | (decompressed[c] << 8) | decompressed[d]) >>> 0;
1525
1654
  }
1526
- } else {
1527
- const view = new DataView(decompressed.buffer, decompressed.byteOffset, decompressed.byteLength);
1655
+ }
1656
+ } else {
1657
+ const view = new DataView(decompressed.buffer, decompressed.byteOffset, decompressed.byteLength);
1528
1658
 
1529
- for (let i = 0, j = 0, di = offset, size = width * height; i < size; i++, j += 4, di += step) {
1530
- dst[di] = view.getUint32(j, false);
1531
- }
1659
+ for (let i = 0, j = 0, di = offset, size = width * height; i < size; i++, j += 4, di += step) {
1660
+ dst[di] = view.getUint32(j, false);
1532
1661
  }
1533
1662
  }
1534
- } finally {
1535
- if (reader) recoverMemory(reader, expectedSize);
1536
1663
  }
1537
1664
  }
1538
1665
 
@@ -1722,7 +1849,15 @@ export function readSection<T>(
1722
1849
  let end = reader.offset + length;
1723
1850
  if (end > reader.view.byteLength) throw new Error('Section exceeds file size');
1724
1851
 
1725
- const result = func(() => end - reader.offset);
1852
+ const parentSectionEnd = reader.sectionEnd;
1853
+ reader.sectionEnd = end;
1854
+ let result: T;
1855
+
1856
+ try {
1857
+ result = func(() => end - reader.offset);
1858
+ } finally {
1859
+ reader.sectionEnd = parentSectionEnd;
1860
+ }
1726
1861
 
1727
1862
  if (reader.offset !== end) {
1728
1863
  if (reader.offset > end) {