ag-psd 33.0.0 → 34.1.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.
Files changed (91) hide show
  1. package/.v8-cache/v24.7.0-x64-ef5a0af0/05135617 +0 -0
  2. package/.v8-cache/v24.7.0-x64-ef5a0af0/226e2801 +0 -0
  3. package/.v8-cache/v24.7.0-x64-ef5a0af0/4511bacf +0 -0
  4. package/.v8-cache/v24.7.0-x64-ef5a0af0/68416cb2 +0 -0
  5. package/.v8-cache/v24.7.0-x64-ef5a0af0/71df9cb3 +0 -0
  6. package/.v8-cache/v24.7.0-x64-ef5a0af0/7ea06cea +0 -0
  7. package/.v8-cache/v24.7.0-x64-ef5a0af0/87cf2209 +0 -0
  8. package/.v8-cache/v24.7.0-x64-ef5a0af0/932f0770 +0 -0
  9. package/.v8-cache/v24.7.0-x64-ef5a0af0/acc36e66 +0 -0
  10. package/.v8-cache/v24.7.0-x64-ef5a0af0/b3c2fab7 +0 -0
  11. package/.v8-cache/v24.7.0-x64-ef5a0af0/c0b789d2 +0 -0
  12. package/.v8-cache/v24.7.0-x64-ef5a0af0/c314aece +0 -0
  13. package/.v8-cache/v24.7.0-x64-ef5a0af0/cfc49f4f +0 -0
  14. package/.v8-cache/v24.7.0-x64-ef5a0af0/d13d7610 +0 -0
  15. package/.v8-cache/v24.7.0-x64-ef5a0af0/dc86f000 +0 -0
  16. package/.v8-cache/v24.7.0-x64-ef5a0af0/e03e2acd +0 -0
  17. package/.v8-cache/v24.7.0-x64-ef5a0af0/e6b99945 +0 -0
  18. package/CHANGELOG.md +28 -0
  19. package/README.md +12 -1
  20. package/README_PSD.md +26 -10
  21. package/TODO.md +9 -94
  22. package/dist/abr.js +12 -7
  23. package/dist/abr.js.map +1 -1
  24. package/dist/additionalInfo.d.ts +2 -0
  25. package/dist/additionalInfo.js +375 -78
  26. package/dist/additionalInfo.js.map +1 -1
  27. package/dist/bundle.js +1661 -407
  28. package/dist/descriptor.d.ts +14 -5
  29. package/dist/descriptor.js +102 -64
  30. package/dist/descriptor.js.map +1 -1
  31. package/dist/helpers.d.ts +6 -0
  32. package/dist/helpers.js +242 -2
  33. package/dist/helpers.js.map +1 -1
  34. package/dist/imageResources.d.ts +2 -0
  35. package/dist/imageResources.js +113 -7
  36. package/dist/imageResources.js.map +1 -1
  37. package/dist/index.d.ts +3 -2
  38. package/dist/index.js +6 -1
  39. package/dist/index.js.map +1 -1
  40. package/dist/psd.d.ts +171 -22
  41. package/dist/psd.js.map +1 -1
  42. package/dist/psdReader.d.ts +5 -1
  43. package/dist/psdReader.js +295 -120
  44. package/dist/psdReader.js.map +1 -1
  45. package/dist/psdWriter.d.ts +1 -0
  46. package/dist/psdWriter.js +336 -91
  47. package/dist/psdWriter.js.map +1 -1
  48. package/dist/text.d.ts +32 -1
  49. package/dist/text.js +58 -0
  50. package/dist/text.js.map +1 -1
  51. package/dist-es/abr.js +12 -7
  52. package/dist-es/abr.js.map +1 -1
  53. package/dist-es/additionalInfo.d.ts +2 -0
  54. package/dist-es/additionalInfo.js +375 -78
  55. package/dist-es/additionalInfo.js.map +1 -1
  56. package/dist-es/descriptor.d.ts +14 -5
  57. package/dist-es/descriptor.js +102 -64
  58. package/dist-es/descriptor.js.map +1 -1
  59. package/dist-es/helpers.d.ts +6 -0
  60. package/dist-es/helpers.js +242 -2
  61. package/dist-es/helpers.js.map +1 -1
  62. package/dist-es/imageResources.d.ts +2 -0
  63. package/dist-es/imageResources.js +113 -7
  64. package/dist-es/imageResources.js.map +1 -1
  65. package/dist-es/index.d.ts +3 -2
  66. package/dist-es/index.js +6 -1
  67. package/dist-es/index.js.map +1 -1
  68. package/dist-es/psd.d.ts +171 -22
  69. package/dist-es/psd.js.map +1 -1
  70. package/dist-es/psdReader.d.ts +5 -1
  71. package/dist-es/psdReader.js +295 -120
  72. package/dist-es/psdReader.js.map +1 -1
  73. package/dist-es/psdWriter.d.ts +1 -0
  74. package/dist-es/psdWriter.js +336 -91
  75. package/dist-es/psdWriter.js.map +1 -1
  76. package/dist-es/text.d.ts +32 -1
  77. package/dist-es/text.js +58 -0
  78. package/dist-es/text.js.map +1 -1
  79. package/fuzz.js +808 -0
  80. package/package.json +1 -1
  81. package/perf.js +312 -9
  82. package/src/abr.ts +14 -7
  83. package/src/additionalInfo.ts +448 -91
  84. package/src/descriptor.ts +103 -58
  85. package/src/helpers.ts +262 -2
  86. package/src/imageResources.ts +138 -7
  87. package/src/index.ts +3 -2
  88. package/src/psd.ts +145 -22
  89. package/src/psdReader.ts +315 -118
  90. package/src/psdWriter.ts +345 -90
  91. package/src/text.ts +76 -1
package/src/psdReader.ts CHANGED
@@ -1,9 +1,9 @@
1
1
  import { Inflate } from 'pako';
2
- import { Psd, Layer, ColorMode, SectionDividerType, LayerAdditionalInfo, ReadOptions, LayerMaskData, Color, PatternInfo, GlobalLayerMaskInfo, RGB, PixelData, PixelArray, ChannelID, Compression } from './psd';
3
- import { resetImageData, offsetForChannel, decodeBitmap, createImageData, toBlendMode, LayerMaskFlags, MaskParams, ColorSpace, largeAdditionalInfoKeys, largeAdditionalInfoKeysObserved, imageDataToCanvas, normalizeLabAB } from './helpers';
2
+ import { Psd, Layer, ColorMode, SectionDividerType, LayerAdditionalInfo, ReadOptions, LayerMaskData, Color, PatternInfo, GlobalLayerMaskInfo, RGB, PixelData, PixelArray, ChannelID, Compression, FilterEffectsMask } from './psd';
3
+ import { resetImageData, offsetForChannel, decodeBitmap, createImageData, toBlendMode, LayerMaskFlags, MaskParams, ColorSpace, largeAdditionalInfoKeys, largeAdditionalInfoKeysObserved, imageDataToCanvas, normalizeLabAB, cmykToRgbValues } from './helpers';
4
4
  import { infoHandlersMap } from './additionalInfo';
5
5
  import { decodeString } from './utf8';
6
- import { InternalImageResources, resourceHandlersMap } from './imageResources';
6
+ import { InternalImageResources, resourceHandlersMap, shouldReadResource } from './imageResources';
7
7
 
8
8
  interface ChannelInfo {
9
9
  id: ChannelID;
@@ -139,6 +139,9 @@ export function readFixedPointPath32(reader: PsdReader): number {
139
139
 
140
140
  // NOTE: returned array may alias the reader's underlying buffer, never write into it
141
141
  export function readBytes(reader: PsdReader, length: number) {
142
+ // negative length comes from sizes computed from malformed data (e.g. section shorter than its header)
143
+ if (!(length >= 0)) throw new Error(`Invalid length: ${length}`);
144
+
142
145
  const start = reader.offset;
143
146
  const viewLength = reader.view.byteLength;
144
147
  reader.offset += length;
@@ -185,6 +188,8 @@ export function readUnicodeString(reader: PsdReader) {
185
188
  }
186
189
 
187
190
  const STRING_CHUNK_SIZE = 0x2000;
191
+ // shorter strings (most descriptor keys, OSTypes and names) are faster to build with simple loop than String.fromCharCode.apply
192
+ const SHORT_STRING_LENGTH = 64;
188
193
 
189
194
  function checkReadBounds(reader: PsdReader, size: number) {
190
195
  if (reader.offset < 0 || (reader.offset + size) > reader.view.byteLength) {
@@ -198,10 +203,21 @@ function readUtf16String(reader: PsdReader, length: number, littleEndian: boolea
198
203
  checkReadBounds(reader, length * 2);
199
204
 
200
205
  const view = reader.view;
201
- const codes = new Uint16Array(Math.min(length, STRING_CHUNK_SIZE));
202
206
  let offset = reader.offset;
203
207
  let text = '';
204
208
 
209
+ if (length <= SHORT_STRING_LENGTH) {
210
+ for (let i = 0; i < length; i++, offset += 2) {
211
+ text += String.fromCharCode(view.getUint16(offset, littleEndian));
212
+ }
213
+
214
+ reader.offset = offset;
215
+ if (text.charCodeAt(text.length - 1) === 0) text = text.substring(0, text.length - 1);
216
+ return text;
217
+ }
218
+
219
+ const codes = new Uint16Array(Math.min(length, STRING_CHUNK_SIZE));
220
+
205
221
  for (let i = 0; i < length; i += STRING_CHUNK_SIZE) {
206
222
  const count = Math.min(STRING_CHUNK_SIZE, length - i);
207
223
 
@@ -241,6 +257,19 @@ export function readUnicodeStringWithLengthLE(reader: PsdReader, length: number)
241
257
  export function readAsciiString(reader: PsdReader, length: number) {
242
258
  if (!(length > 0)) return '';
243
259
  checkReadBounds(reader, length);
260
+
261
+ if (length <= SHORT_STRING_LENGTH) {
262
+ const view = reader.view;
263
+ let text = '';
264
+
265
+ for (let i = 0, offset = reader.offset; i < length; i++, offset++) {
266
+ text += String.fromCharCode(view.getUint8(offset));
267
+ }
268
+
269
+ reader.offset += length;
270
+ return text;
271
+ }
272
+
244
273
  const text = bytesToString(new Uint8Array(reader.view.buffer, reader.view.byteOffset + reader.offset, length));
245
274
  reader.offset += length;
246
275
  return text;
@@ -260,7 +289,16 @@ export function checkSignature(reader: PsdReader, a: string, b?: string) {
260
289
  }
261
290
 
262
291
  function readShortString(reader: PsdReader, length: number) {
263
- return bytesToString(readBytes(reader, length));
292
+ const bytes = readBytes(reader, length);
293
+ if (length > SHORT_STRING_LENGTH) return bytesToString(bytes);
294
+
295
+ let text = '';
296
+
297
+ for (let i = 0; i < bytes.length; i++) {
298
+ text += String.fromCharCode(bytes[i]);
299
+ }
300
+
301
+ return text;
264
302
  }
265
303
 
266
304
  function isValidSignature(sig: string) {
@@ -333,14 +371,19 @@ export function readPsd(reader: PsdReader, readOptions: ReadOptions = {}) {
333
371
 
334
372
  readSection(reader, 2, left => {
335
373
  const handler = resourceHandlersMap[id];
336
- const skip = id === 1036 && !!reader.skipThumbnail;
337
374
 
338
- if (handler && !skip) {
339
- try {
340
- handler.read(reader, imageResources, left, { signature, id, name, width, height });
341
- } catch (e) {
342
- if (reader.throwForMissingFeatures) throw e;
375
+ if (handler) {
376
+ const skip = (id === 1036 && !!reader.skipThumbnail) || !shouldReadResource(handler, reader.imageResourcesWhitelist);
377
+
378
+ if (skip) {
343
379
  skipBytes(reader, left());
380
+ } else {
381
+ try {
382
+ handler.read(reader, imageResources, left, { signature, id, name, width, height });
383
+ } catch (e) {
384
+ if (reader.throwForMissingFeatures) throw e;
385
+ skipBytes(reader, left());
386
+ }
344
387
  }
345
388
  } else {
346
389
  reader.logMissingFeatures && reader.log(`Unhandled image resource: ${id} (${left()})`);
@@ -458,6 +501,10 @@ export function readLayerInfo(reader: PsdReader, psd: Psd, imageResources: Inter
458
501
  l.opened = type === SectionDividerType.OpenFolder;
459
502
  l.children = [];
460
503
 
504
+ // group layers can't have image data, some broken files have it, ignore it like Photoshop does
505
+ delete l.canvas;
506
+ delete l.imageData;
507
+
461
508
  if (l.sectionDivider?.key) {
462
509
  l.blendMode = toBlendMode[l.sectionDivider.key] ?? l.blendMode;
463
510
  }
@@ -675,8 +722,8 @@ function readLayerChannelImageData(reader: PsdReader, psd: Psd, layer: Layer, ch
675
722
  let compression = Compression.RawData;
676
723
  let data: Uint8Array | undefined = undefined;
677
724
 
678
- if (channel.length === 1) throw new Error('Invalid channel length');
679
- if (channel.length) {
725
+ // channel length of 1 is invalid (should be 0 or at least 2), skip the byte and treat channel as empty
726
+ if (channel.length >= 2) {
680
727
  compression = readUint16(reader) as Compression;
681
728
  // try to fix broken files where there's 1 byte shift of channel
682
729
  if (compression > 3) {
@@ -702,7 +749,14 @@ function readLayerChannelImageData(reader: PsdReader, psd: Psd, layer: Layer, ch
702
749
  }
703
750
 
704
751
  if (!reader.useRawData) {
705
- decodeLayerImageData(layer, reader);
752
+ try {
753
+ decodeLayerImageData(layer, reader);
754
+ } catch (e) {
755
+ // corrupted image data of one layer shouldn't prevent reading rest of the file
756
+ if (reader.throwForMissingFeatures || (e as Error).message === 'Exceeded memory limit') throw e;
757
+ reader.logMissingFeatures && reader.log(`Failed to decode layer image data: ${(e as Error).message}`);
758
+ delete layer.rawData;
759
+ }
706
760
  }
707
761
  }
708
762
 
@@ -761,6 +815,73 @@ export function getLayerRealMaskCanvas(layer: Layer) {
761
815
  return imageDataToCanvasSafe(getLayerRealMaskImageData(layer));
762
816
  }
763
817
 
818
+ export function getFilterEffectsMaskImageData(mask: FilterEffectsMask) {
819
+ const { depth, channels, colorMode = ColorMode.RGB } = mask;
820
+ const width = Math.max(0, mask.right - mask.left);
821
+ const height = Math.max(0, mask.bottom - mask.top);
822
+ if (!width || !height) return undefined;
823
+
824
+ const cmyk = colorMode === ColorMode.CMYK;
825
+ if (cmyk && depth !== 8 && depth !== 16) throw new Error('bitsPerChannel not supported');
826
+
827
+ const step = cmyk ? 5 : 4;
828
+ // channels are color channels, followed by user mask and transparency
829
+ const transparencyIndex = channels.length - 1;
830
+ const colorChannels = Math.min(cmyk ? 4 : (colorMode === ColorMode.Grayscale ? 1 : 3), channels.length - 2);
831
+ let imageData = createImageDataBitDepth(width, height, depth, step, undefined);
832
+
833
+ for (let i = 0; i < channels.length; i++) {
834
+ const channel = channels[i];
835
+ if (!channel) continue;
836
+
837
+ if (i < colorChannels) {
838
+ readFilterEffectsChannel(channel, imageData, width, height, depth, i, step);
839
+ } else if (i === transparencyIndex) {
840
+ readFilterEffectsChannel(channel, imageData, width, height, depth, step - 1, step);
841
+ }
842
+ }
843
+
844
+ if (colorMode === ColorMode.Grayscale) setupGrayscale(imageData);
845
+ if (!channels[transparencyIndex]) resetAlpha(imageData, cmyk);
846
+
847
+ if (cmyk) {
848
+ const cmykData = imageData;
849
+ imageData = createImageDataBitDepth(cmykData.width, cmykData.height, depth, 4, undefined);
850
+ cmykToRgb(cmykData, imageData, false);
851
+ }
852
+
853
+ return imageData;
854
+ }
855
+
856
+ export function getFilterEffectsMaskExtraImageData(mask: FilterEffectsMask) {
857
+ const { extra, depth } = mask;
858
+ if (!extra) return undefined;
859
+
860
+ const width = Math.max(0, extra.right - extra.left);
861
+ const height = Math.max(0, extra.bottom - extra.top);
862
+ if (!width || !height) return undefined;
863
+
864
+ const maskData = createImageDataBitDepth(width, height, depth, 4, undefined);
865
+ readFilterEffectsChannel(extra, maskData, width, height, depth, 0, 4);
866
+ setupGrayscale(maskData);
867
+ resetAlpha(maskData, false);
868
+ return maskData;
869
+ }
870
+
871
+ export function getFilterEffectsMaskCanvas(mask: FilterEffectsMask) {
872
+ return imageDataToCanvasSafe(getFilterEffectsMaskImageData(mask));
873
+ }
874
+
875
+ export function getFilterEffectsMaskExtraCanvas(mask: FilterEffectsMask) {
876
+ return imageDataToCanvasSafe(getFilterEffectsMaskExtraImageData(mask));
877
+ }
878
+
879
+ function readFilterEffectsChannel({ compressionMode, data }: { compressionMode: Compression; data: Uint8Array; }, pixels: PixelData, width: number, height: number, depth: number, offset: number, step: number) {
880
+ const reader = createReader(data.buffer, data.byteOffset, data.byteLength);
881
+ // RLE row lengths are always 4 bytes, same as in PSB files
882
+ readData(reader, data.byteLength, pixels, compressionMode, width, height, depth, offset, true, step);
883
+ }
884
+
764
885
  function imageDataToCanvasSafe(imageData: PixelData | undefined) {
765
886
  return imageData && imageDataToCanvas(imageData);
766
887
  }
@@ -924,7 +1045,7 @@ export function readGlobalLayerMaskInfo(reader: PsdReader) {
924
1045
  const colorSpace2 = readUint16(reader);
925
1046
  const colorSpace3 = readUint16(reader);
926
1047
  const colorSpace4 = readUint16(reader);
927
- const opacity = readUint16(reader) / 100; // 0 - 100
1048
+ const opacity = Math.min(readUint16(reader), 100) / 100; // 0 - 100 (some files have values out of range)
928
1049
  const kind = readUint8(reader);
929
1050
  skipBytes(reader, left()); // 3 bytes of padding ?
930
1051
  return { overlayColorSpace, colorSpace1, colorSpace2, colorSpace3, colorSpace4, opacity, kind };
@@ -1191,10 +1312,7 @@ function toRange(value: number, max: number) {
1191
1312
  return value <= 0 ? 0 : (value >= max ? max : value);
1192
1313
  }
1193
1314
 
1194
- // Polynomial approximation of U.S. Web Coated (SWOP) v2 CMYK to RGB conversion (default CMYK profile of Photoshop).
1195
- // Coefficients are taken from pdf.js (DeviceCmykCS in src/core/colorspace.js, https://github.com/mozilla/pdf.js),
1196
- // Copyright 2012 Mozilla Foundation, licensed under the Apache License, Version 2.0
1197
- // (http://www.apache.org/licenses/LICENSE-2.0)
1315
+ // converts CMYK data to RGB using approximation of U.S. Web Coated (SWOP) v2 profile (see cmykToRgbValues)
1198
1316
  // cmyk - 8 or 16 bit data with 5 channels (cmyka), rgb - 8 or 16 bit data with 4 channels (rgba)
1199
1317
  // removeMatte - colors are blended with white (no ink), used for composite image of documents with global alpha
1200
1318
  function cmykToRgb(cmyk: PixelData, rgb: PixelData, removeMatte: boolean) {
@@ -1203,6 +1321,7 @@ function cmykToRgb(cmyk: PixelData, rgb: PixelData, removeMatte: boolean) {
1203
1321
  const dstData = rgb.data;
1204
1322
  const srcMax = srcData instanceof Uint16Array ? 0xffff : 0xff;
1205
1323
  const dstMax = dstData instanceof Uint16Array ? 0xffff : 0xff;
1324
+ const out = [0, 0, 0];
1206
1325
 
1207
1326
  for (let src = 0, dst = 0; dst < size; src += 5, dst += 4) {
1208
1327
  const a = srcData[src + 4];
@@ -1221,21 +1340,10 @@ function cmykToRgb(cmyk: PixelData, rgb: PixelData, removeMatte: boolean) {
1221
1340
  k = Math.min(1, k * ra);
1222
1341
  }
1223
1342
 
1224
- dstData[dst] = toRange(255 +
1225
- c * (-4.387332384609988 * c + 54.48615194189176 * m + 18.82290502165302 * y + 212.25662451639585 * k - 285.2331026137004) +
1226
- m * (1.7149763477362134 * m - 5.6096736904047315 * y - 17.873870861415444 * k - 5.497006427196366) +
1227
- y * (-2.5217340131683033 * y - 21.248923337353073 * k + 17.5119270841813) +
1228
- k * (-21.86122147463605 * k - 189.48180835922747), dstMax);
1229
- dstData[dst + 1] = toRange(255 +
1230
- c * (8.841041422036149 * c + 60.118027045597366 * m + 6.871425592049007 * y + 31.159100130055922 * k - 79.2970844816548) +
1231
- m * (-15.310361306967817 * m + 17.575251261109482 * y + 131.35250912493976 * k - 190.9453302588951) +
1232
- y * (4.444339102852739 * y + 9.8632861493405 * k - 24.86741582555878) +
1233
- k * (-20.737325471181034 * k - 187.80453709719578), dstMax);
1234
- dstData[dst + 2] = toRange(255 +
1235
- c * (0.8842522430003296 * c + 8.078677503112928 * m + 30.89978309703729 * y - 0.23883238689178934 * k - 14.183576799673286) +
1236
- m * (10.49593273432072 * m + 63.02378494754052 * y + 50.606957656360734 * k - 112.23884253719248) +
1237
- y * (0.03296041114873217 * y + 115.60384449646641 * k - 193.58209356861505) +
1238
- k * (-22.33816807309886 * k - 180.12613974708367), dstMax);
1343
+ cmykToRgbValues(c, m, y, k, out);
1344
+ dstData[dst] = toRange(out[0], dstMax);
1345
+ dstData[dst + 1] = toRange(out[1], dstMax);
1346
+ dstData[dst + 2] = toRange(out[2], dstMax);
1239
1347
  dstData[dst + 3] = srcMax === dstMax ? a : Math.round(a * dstMax / srcMax);
1240
1348
  }
1241
1349
  }
@@ -1313,12 +1421,12 @@ function decodePredicted(data: Uint8Array, width: number, height: number) {
1313
1421
  const zipOverflow = new Error('Decompressed data exceeds expected size');
1314
1422
 
1315
1423
  // inflates data, stopping when output exceeds expected size (protects against zip bombs)
1316
- function inflateLimited(compressed: Uint8Array, expectedSize: number, reader: PsdReader | undefined) {
1424
+ function inflateLimited(compressed: Uint8Array, expectedSize: number, reader: PsdReader | undefined, raw = false): Uint8Array {
1317
1425
  const output = new Uint8Array(expectedSize);
1318
1426
  let position = 0;
1319
1427
  let overflow = false;
1320
1428
 
1321
- const inflator = new Inflate({ chunkSize: Math.max(1024, Math.min(expectedSize, 0x10000)) });
1429
+ const inflator = new Inflate({ chunkSize: Math.max(1024, Math.min(expectedSize, 0x10000)), raw });
1322
1430
  inflator.onData = (chunk: any) => {
1323
1431
  const data = chunk as Uint8Array;
1324
1432
  const count = Math.min(data.length, expectedSize - position);
@@ -1344,6 +1452,10 @@ function inflateLimited(compressed: Uint8Array, expectedSize: number, reader: Ps
1344
1452
 
1345
1453
  if (overflow) {
1346
1454
  if (reader) warnOrThrow(reader, zipOverflow.message);
1455
+ } else if (inflator.err && inflator.msg === 'incorrect data check' && !raw) {
1456
+ // some files have zeroed checksum (filter effects masks written by Photoshop), inflate again skipping zlib header and checksum
1457
+ if (reader) warnOrThrow(reader, `Invalid zip data: ${inflator.msg}`);
1458
+ return inflateLimited(compressed.subarray(2), expectedSize, reader, true);
1347
1459
  } else if (inflator.err) {
1348
1460
  throw new Error(`Invalid zip data: ${inflator.msg}`);
1349
1461
  }
@@ -1418,8 +1530,8 @@ export function readDataZip(
1418
1530
  }
1419
1531
  }
1420
1532
 
1421
- // decodes single PackBits row, returns number of decoded values
1422
- function decodeRLERow(src: Uint8Array, i: number, end: number, dst: PixelArray, p: number, step: number, count: number) {
1533
+ // decodes single PackBits row into byte buffer, returns number of decoded bytes
1534
+ function decodeRLERow(src: Uint8Array, i: number, end: number, dst: Uint8Array, count: number) {
1423
1535
  let x = 0;
1424
1536
 
1425
1537
  while (i < end && x < count) {
@@ -1431,19 +1543,15 @@ function decodeRLERow(src: Uint8Array, i: number, end: number, dst: PixelArray,
1431
1543
  const value = src[i++];
1432
1544
  let n = 257 - header;
1433
1545
  if (n > count - x) n = count - x;
1546
+ dst.fill(value, x, x + n);
1434
1547
  x += n;
1435
-
1436
- for (; n > 0; n--, p += step) {
1437
- dst[p] = value;
1438
- }
1439
1548
  } else if (header < 128) {
1440
1549
  let n = header + 1;
1441
1550
  if (n > count - x) n = count - x;
1442
1551
  if (n > end - i) n = end - i;
1443
- x += n;
1444
1552
 
1445
- for (; n > 0; n--, p += step) {
1446
- dst[p] = src[i++];
1553
+ for (; n > 0; n--) {
1554
+ dst[x++] = src[i++];
1447
1555
  }
1448
1556
  } else {
1449
1557
  // ignore 128
@@ -1453,6 +1561,51 @@ function decodeRLERow(src: Uint8Array, i: number, end: number, dst: PixelArray,
1453
1561
  return x;
1454
1562
  }
1455
1563
 
1564
+ // decodes RLE rows of single 8bit channel, writing values to `data` with `step`
1565
+ // (kept as single function with the loops, inlining row decoder into readDataRLE makes V8 generate much slower code)
1566
+ function decodeRLEChannel8(
1567
+ src: Uint8Array, lengths: Uint16Array | Uint32Array, li: number, pos: number, width: number, height: number,
1568
+ data: PixelArray, offset: number, step: number
1569
+ ) {
1570
+ const srcEnd = src.length | 0;
1571
+
1572
+ for (let y = 0; y < height; y++, li++) {
1573
+ let i = (pos < srcEnd ? pos : srcEnd) | 0;
1574
+ pos += lengths[li];
1575
+ const end = (pos < srcEnd ? pos : srcEnd) | 0;
1576
+ let p = (offset + y * width * step) | 0;
1577
+ let x = 0;
1578
+
1579
+ while (i < end && x < width) {
1580
+ const header = src[i++] | 0;
1581
+
1582
+ if (header > 128) {
1583
+ if (i >= end) break;
1584
+
1585
+ const value = src[i++] | 0;
1586
+ let n = (257 - header) | 0;
1587
+ if (n > width - x) n = (width - x) | 0;
1588
+ x = (x + n) | 0;
1589
+
1590
+ for (const pe = (p + n * step) | 0; p < pe; p = (p + step) | 0) {
1591
+ data[p] = value;
1592
+ }
1593
+ } else if (header < 128) {
1594
+ let n = (header + 1) | 0;
1595
+ if (n > width - x) n = (width - x) | 0;
1596
+ if (n > end - i) n = (end - i) | 0;
1597
+ x = (x + n) | 0;
1598
+
1599
+ for (const ie = (i + n) | 0; i < ie; i = (i + 1) | 0, p = (p + step) | 0) {
1600
+ data[p] = src[i];
1601
+ }
1602
+ } else {
1603
+ // ignore 128
1604
+ }
1605
+ }
1606
+ }
1607
+ }
1608
+
1456
1609
  // converts big-endian 16/32-bit values from bytes and writes them to `data` starting at `p` with `step`
1457
1610
  function scatterValues(bytes: Uint8Array, count: number, bpv: number, data: PixelArray, p: number, step: number) {
1458
1611
  if (bpv === 2) {
@@ -1468,10 +1621,10 @@ function scatterValues(bytes: Uint8Array, count: number, bpv: number, data: Pixe
1468
1621
  }
1469
1622
  }
1470
1623
 
1471
- // decodes RLE rows of single channel, each row starts at the beginning of the image row
1472
- function decodeRLEChannel(
1624
+ // decodes RLE rows of single 16bit or 32bit channel, each row is decoded into `row` buffer and then converted to values
1625
+ function decodeRLEChannelWide(
1473
1626
  src: Uint8Array, lengths: Uint16Array | Uint32Array, li: number, pos: number, width: number, height: number,
1474
- data: PixelArray, offset: number, step: number, bpv: number, row: Uint8Array | undefined
1627
+ data: PixelArray, offset: number, step: number, bpv: number, row: Uint8Array
1475
1628
  ) {
1476
1629
  const srcEnd = src.length;
1477
1630
  const rowSize = width * bpv;
@@ -1483,12 +1636,8 @@ function decodeRLEChannel(
1483
1636
 
1484
1637
  if (rowStart >= rowEnd) continue;
1485
1638
 
1486
- if (bpv === 1) {
1487
- decodeRLERow(src, rowStart, rowEnd, data, offset + y * width * step, step, width);
1488
- } else {
1489
- const decoded = decodeRLERow(src, rowStart, rowEnd, row!, 0, 1, rowSize);
1490
- scatterValues(row!, Math.floor(decoded / bpv), bpv, data, offset + y * width * step, step);
1491
- }
1639
+ const decoded = decodeRLERow(src, rowStart, rowEnd, row, rowSize);
1640
+ scatterValues(row, Math.floor(decoded / bpv), bpv, data, offset + y * width * step, step);
1492
1641
  }
1493
1642
  }
1494
1643
 
@@ -1496,15 +1645,19 @@ export function readDataRLE(reader: PsdReader, pixelData: PixelData | undefined,
1496
1645
  const data = pixelData && pixelData.data;
1497
1646
  const rows = offsets.length * height;
1498
1647
  const lengthSize = large ? 4 : 2;
1648
+ const lengthsMemory = rows * lengthSize;
1649
+ const srcEnd = reader.view.byteLength;
1650
+ const bpv = bytesPerValue(bitDepth); // throws before consuming memory
1651
+ let lengths: Uint16Array | Uint32Array;
1499
1652
 
1500
- consumeMemory(reader, rows * lengthSize);
1653
+ consumeMemory(reader, lengthsMemory);
1501
1654
 
1502
1655
  try {
1503
- if ((reader.offset + rows * lengthSize) > reader.view.byteLength) {
1656
+ if ((reader.offset + lengthsMemory) > srcEnd) {
1504
1657
  throw new Error('RLE row lengths exceed buffer length');
1505
1658
  }
1506
1659
 
1507
- const lengths = large ? new Uint32Array(rows) : new Uint16Array(rows);
1660
+ lengths = large ? new Uint32Array(rows) : new Uint16Array(rows);
1508
1661
  let total = 0;
1509
1662
 
1510
1663
  if (large) {
@@ -1513,36 +1666,39 @@ export function readDataRLE(reader: PsdReader, pixelData: PixelData | undefined,
1513
1666
  for (let i = 0; i < rows; i++) total += (lengths[i] = readUint16(reader));
1514
1667
  }
1515
1668
 
1516
- const start = reader.offset;
1517
- const srcEnd = reader.view.byteLength;
1518
-
1519
- if (total > (srcEnd - start)) {
1669
+ if (total > (srcEnd - reader.offset)) {
1520
1670
  // broken or truncated file, decode only data that is available
1521
1671
  warnOrThrow(reader, 'RLE data exceeds buffer length');
1522
1672
  }
1523
1673
 
1524
- const bpv = bytesPerValue(bitDepth);
1525
1674
  if (data) verifyArrayType(data, bpv);
1675
+ } catch (e) {
1676
+ recoverMemory(reader, lengthsMemory);
1677
+ throw e;
1678
+ }
1526
1679
 
1527
- const src = new Uint8Array(reader.view.buffer, reader.view.byteOffset, srcEnd);
1528
- const row = (data && bpv > 1) ? new Uint8Array(width * bpv) : undefined;
1529
- let pos = start;
1680
+ // decoding can't throw, it's kept outside of try block because V8 generates much slower code for loops inlined into try block
1681
+ const src = new Uint8Array(reader.view.buffer, reader.view.byteOffset, srcEnd);
1682
+ const row = (data && bpv > 1) ? new Uint8Array(width * bpv) : undefined;
1683
+ let pos = reader.offset;
1530
1684
 
1531
- for (let c = 0, li = 0; c < offsets.length; c++, li += height) {
1532
- const offset = offsets[c] | 0;
1533
- const channelStart = pos;
1685
+ for (let c = 0, li = 0; c < offsets.length; c++, li += height) {
1686
+ const offset = offsets[c] | 0;
1687
+ const channelStart = pos;
1534
1688
 
1535
- for (let y = 0; y < height; y++) pos += lengths[li + y];
1689
+ for (let y = 0; y < height; y++) pos += lengths[li + y];
1536
1690
 
1537
- if (data && offset >= 0 && offset < step) {
1538
- decodeRLEChannel(src, lengths, li, channelStart, width, height, data, offset, step, bpv, row);
1691
+ if (data && offset >= 0 && offset < step) {
1692
+ if (bpv === 1) {
1693
+ decodeRLEChannel8(src, lengths, li, channelStart, width, height, data, offset, step);
1694
+ } else {
1695
+ decodeRLEChannelWide(src, lengths, li, channelStart, width, height, data, offset, step, bpv, row!);
1539
1696
  }
1540
1697
  }
1541
-
1542
- reader.offset = pos;
1543
- } finally {
1544
- recoverMemory(reader, rows * lengthSize);
1545
1698
  }
1699
+
1700
+ reader.offset = pos;
1701
+ recoverMemory(reader, lengthsMemory);
1546
1702
  }
1547
1703
 
1548
1704
  export function readSection<T>(
@@ -1690,21 +1846,15 @@ export function readPattern(reader: PsdReader): PatternInfo {
1690
1846
  if (channelsCount > 64) throw new Error(`Invalid pattern channel count: ${channelsCount}`);
1691
1847
  // channels cover whole pattern, each 2 bytes of RLE data can produce at most 128 bytes
1692
1848
  if (width * height > (Math.min(end, reader.view.byteLength) - reader.offset) * 64) throw new Error('Pattern data out of bounds');
1693
- const size = width * height * 4;
1694
- consumeMemory(reader, size);
1695
- const data = new Uint8Array(size);
1696
-
1697
- for (let i = 3; i < data.byteLength; i += 4) {
1698
- data[i] = 255;
1699
- }
1700
1849
 
1701
1850
  // first written arrays are color channels, next one is transparency (Photoshop stores it in the last, sheet mask, array)
1702
1851
  const colorChannels = colorMode === ColorMode.RGB ? 3 : (colorMode === ColorMode.CMYK ? 4 : 1);
1703
- // CMYK channels are decoded into separate buffer (5 values per pixel, inverted, 0 = 100% ink) and converted to RGB at the end
1704
- const cmyk = colorMode === ColorMode.CMYK ? new Uint8Array(width * height * 5).fill(255) : undefined;
1705
- if (cmyk) consumeMemory(reader, cmyk.byteLength);
1706
- const alphaTarget = cmyk ? 4 : 3;
1852
+ const isCmyk = colorMode === ColorMode.CMYK;
1853
+ const alphaTarget = isCmyk ? 4 : 3;
1854
+ const channels: { target: number; depth: number; compressionMode: number; cdata: Uint8Array; ctop: number; cleft: number; w: number; h: number; rowBytes: number; channelSize: number; }[] = [];
1855
+ let maxDecodeSize = 0;
1707
1856
 
1857
+ // validate all channels before allocating any image data
1708
1858
  for (let i = 0, ch = 0; i < (channelsCount + 2) && reader.offset + 4 <= end; i++) {
1709
1859
  const has = readUint32(reader);
1710
1860
  if (!has) continue;
@@ -1738,72 +1888,119 @@ export function readPattern(reader: PsdReader): PatternInfo {
1738
1888
  const h = cbottom - ctop;
1739
1889
  const rowBytes = w * (depth / 8);
1740
1890
  const channelSize = rowBytes * h;
1741
- let bytes: Uint8Array;
1742
1891
 
1743
1892
  if (compressionMode === 0) {
1744
1893
  if (cdata.byteLength < channelSize) throw new Error('Pattern channel data out of bounds');
1745
- bytes = cdata;
1746
1894
  } else if (compressionMode === 1) {
1747
1895
  // each 2 bytes of RLE data can produce at most 128 bytes
1748
1896
  if (channelSize > cdata.byteLength * 64) throw new Error('Pattern channel data out of bounds');
1897
+ maxDecodeSize = Math.max(maxDecodeSize, channelSize);
1898
+ } else {
1899
+ throw new Error('Invalid pattern compression mode');
1900
+ }
1901
+
1902
+ channels.push({ target, depth, compressionMode, cdata, ctop, cleft, w, h, rowBytes, channelSize });
1903
+ }
1904
+
1905
+ // check peak memory up front (image data, CMYK buffer and largest RLE decode buffer),
1906
+ // image data is consumed only after successful decoding so failed patterns don't reduce the limit
1907
+ const size = width * height * 4;
1908
+ const cmykSize = isCmyk ? width * height * 5 : 0;
1909
+ consumeMemory(reader, size + cmykSize + maxDecodeSize);
1910
+ recoverMemory(reader, size + cmykSize + maxDecodeSize);
1911
+
1912
+ const data = new Uint8Array(size);
1913
+
1914
+ for (let i = 3; i < data.byteLength; i += 4) {
1915
+ data[i] = 255;
1916
+ }
1917
+
1918
+ // CMYK channels are decoded into separate buffer (5 values per pixel, inverted, 0 = 100% ink) and converted to RGB at the end
1919
+ const cmyk = isCmyk ? new Uint8Array(cmykSize).fill(255) : undefined;
1920
+
1921
+ for (const { target, depth, compressionMode, cdata, ctop, cleft, w, h, rowBytes, channelSize } of channels) {
1922
+ let bytes = cdata;
1749
1923
 
1750
- consumeMemory(reader, channelSize);
1924
+ if (compressionMode === 1) {
1751
1925
  bytes = new Uint8Array(channelSize);
1752
1926
  const cdataReader = createReader(cdata.buffer, cdata.byteOffset, cdata.byteLength);
1753
1927
  readDataRLE(cdataReader, { data: bytes, width: rowBytes, height: h }, rowBytes, h, 8, 1, [0], false);
1754
- } else {
1755
- throw new Error('Invalid pattern compression mode');
1756
1928
  }
1757
1929
 
1930
+ if (depth !== 8) bytes = patternChannelTo8bit(bytes, w * h, depth);
1931
+
1758
1932
  const ox = cleft - left;
1759
1933
  const oy = ctop - top;
1760
1934
 
1761
- for (let y = 0; y < h; y++) {
1762
- for (let x = 0; x < w; x++) {
1763
- const src = x + y * w;
1764
- const dst = (ox + x + (y + oy) * width) * 4;
1765
- const value = depth === 8 ? bytes[src] : patternValueTo8bit(bytes, src, depth);
1766
-
1767
- if (cmyk) {
1768
- cmyk[(ox + x + (y + oy) * width) * 5 + target] = value;
1769
- } else if (target === 3) {
1770
- data[dst + 3] = value;
1771
- } else if (colorMode === ColorMode.Indexed) {
1772
- const color = palette[value];
1773
- data[dst + 0] = color.r;
1774
- data[dst + 1] = color.g;
1775
- data[dst + 2] = color.b;
1776
- } else if (colorMode === ColorMode.Grayscale) {
1935
+ if (cmyk) {
1936
+ copyPatternChannel(bytes, cmyk, w, h, (ox + oy * width) * 5 + target, width * 5, 5);
1937
+ } else if (target === 3 || colorMode === ColorMode.RGB) {
1938
+ copyPatternChannel(bytes, data, w, h, (ox + oy * width) * 4 + target, width * 4, 4);
1939
+ } else if (colorMode === ColorMode.Indexed) {
1940
+ const colors = new Uint8Array(256 * 3);
1941
+
1942
+ for (let i = 0; i < 256; i++) {
1943
+ colors[i * 3 + 0] = palette[i].r;
1944
+ colors[i * 3 + 1] = palette[i].g;
1945
+ colors[i * 3 + 2] = palette[i].b;
1946
+ }
1947
+
1948
+ for (let y = 0; y < h; y++) {
1949
+ for (let x = 0, src = y * w, dst = (ox + (y + oy) * width) * 4; x < w; x++, src++, dst += 4) {
1950
+ const index = bytes[src] * 3;
1951
+ data[dst + 0] = colors[index + 0];
1952
+ data[dst + 1] = colors[index + 1];
1953
+ data[dst + 2] = colors[index + 2];
1954
+ }
1955
+ }
1956
+ } else { // grayscale
1957
+ for (let y = 0; y < h; y++) {
1958
+ for (let x = 0, src = y * w, dst = (ox + (y + oy) * width) * 4; x < w; x++, src++, dst += 4) {
1959
+ const value = bytes[src];
1777
1960
  data[dst + 0] = value;
1778
1961
  data[dst + 1] = value;
1779
1962
  data[dst + 2] = value;
1780
- } else {
1781
- data[dst + target] = value;
1782
1963
  }
1783
1964
  }
1784
1965
  }
1785
-
1786
- if (compressionMode === 1) recoverMemory(reader, channelSize);
1787
1966
  }
1788
1967
 
1789
1968
  if (cmyk) {
1790
1969
  cmykToRgb({ width, height, data: cmyk }, { width, height, data }, false);
1791
- recoverMemory(reader, cmyk.byteLength);
1792
1970
  }
1793
1971
 
1972
+ consumeMemory(reader, size);
1794
1973
  reader.offset = end;
1795
1974
 
1796
1975
  return { id, name, x, y, bounds: { x: left, y: top, w: width, h: height }, data };
1797
1976
  }
1798
1977
 
1799
- // converts big-endian 16bit or 32bit (float) value at given index to 8bit value
1800
- function patternValueTo8bit(bytes: Uint8Array, index: number, depth: number) {
1978
+ // converts big-endian 16bit or 32bit (float) values to 8bit values
1979
+ function patternChannelTo8bit(bytes: Uint8Array, count: number, depth: number) {
1980
+ const result = new Uint8Array(count);
1981
+
1801
1982
  if (depth === 16) {
1802
- return Math.round(((bytes[index * 2] << 8) | bytes[index * 2 + 1]) / 257);
1983
+ for (let i = 0; i < count; i++) {
1984
+ result[i] = Math.round(((bytes[i * 2] << 8) | bytes[i * 2 + 1]) / 257);
1985
+ }
1803
1986
  } else {
1804
- const view = new DataView(bytes.buffer, bytes.byteOffset + index * 4, 4);
1805
- const value = view.getFloat32(0, false);
1806
- return value > 0 ? (value < 1 ? Math.round(value * 255) : 255) : 0;
1987
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
1988
+
1989
+ for (let i = 0; i < count; i++) {
1990
+ const value = view.getFloat32(i * 4, false);
1991
+ result[i] = value > 0 ? (value < 1 ? Math.round(value * 255) : 255) : 0;
1992
+ }
1993
+ }
1994
+
1995
+ return result;
1996
+ }
1997
+
1998
+ // copies w x h channel values into interleaved data starting at `offset`
1999
+ function copyPatternChannel(bytes: Uint8Array, data: Uint8Array, w: number, h: number, offset: number, stride: number, step: number) {
2000
+ for (let y = 0, src = 0; y < h; y++) {
2001
+ for (let x = 0, dst = offset + y * stride; x < w; x++, src++, dst += step) {
2002
+ data[dst] = bytes[src];
2003
+ }
1807
2004
  }
1808
2005
  }
1809
2006