@jimp/jpeg-js 0.0.0-stage → 2.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 (225) hide show
  1. package/LICENSE +129 -0
  2. package/LICENSE-APACHE-2.0 +202 -0
  3. package/NOTICE +27 -0
  4. package/README.ijg +260 -0
  5. package/README.md +261 -2
  6. package/dist/browser/compat.d.ts +44 -0
  7. package/dist/browser/compat.d.ts.map +1 -0
  8. package/dist/browser/compat.js +42 -0
  9. package/dist/browser/compat.js.map +1 -0
  10. package/dist/browser/decode.d.ts +73 -0
  11. package/dist/browser/decode.d.ts.map +1 -0
  12. package/dist/browser/decode.js +82 -0
  13. package/dist/browser/decode.js.map +1 -0
  14. package/dist/browser/decoder/arithmetic.d.ts +66 -0
  15. package/dist/browser/decoder/arithmetic.d.ts.map +1 -0
  16. package/dist/browser/decoder/arithmetic.js +374 -0
  17. package/dist/browser/decoder/arithmetic.js.map +1 -0
  18. package/dist/browser/decoder/decoder.d.ts +87 -0
  19. package/dist/browser/decoder/decoder.d.ts.map +1 -0
  20. package/dist/browser/decoder/decoder.js +869 -0
  21. package/dist/browser/decoder/decoder.js.map +1 -0
  22. package/dist/browser/decoder/huffman.d.ts +64 -0
  23. package/dist/browser/decoder/huffman.d.ts.map +1 -0
  24. package/dist/browser/decoder/huffman.js +260 -0
  25. package/dist/browser/decoder/huffman.js.map +1 -0
  26. package/dist/browser/decoder/idct.d.ts +20 -0
  27. package/dist/browser/decoder/idct.d.ts.map +1 -0
  28. package/dist/browser/decoder/idct.js +222 -0
  29. package/dist/browser/decoder/idct.js.map +1 -0
  30. package/dist/browser/decoder/output.d.ts +17 -0
  31. package/dist/browser/decoder/output.d.ts.map +1 -0
  32. package/dist/browser/decoder/output.js +351 -0
  33. package/dist/browser/decoder/output.js.map +1 -0
  34. package/dist/browser/decoder/scan-tables.d.ts +7 -0
  35. package/dist/browser/decoder/scan-tables.d.ts.map +1 -0
  36. package/dist/browser/decoder/scan-tables.js +13 -0
  37. package/dist/browser/decoder/scan-tables.js.map +1 -0
  38. package/dist/browser/decoder/scan.d.ts +57 -0
  39. package/dist/browser/decoder/scan.d.ts.map +1 -0
  40. package/dist/browser/decoder/scan.js +381 -0
  41. package/dist/browser/decoder/scan.js.map +1 -0
  42. package/dist/browser/decoder/smoothing.d.ts +28 -0
  43. package/dist/browser/decoder/smoothing.d.ts.map +1 -0
  44. package/dist/browser/decoder/smoothing.js +345 -0
  45. package/dist/browser/decoder/smoothing.js.map +1 -0
  46. package/dist/browser/decoder/standard-tables.d.ts +19 -0
  47. package/dist/browser/decoder/standard-tables.d.ts.map +1 -0
  48. package/dist/browser/decoder/standard-tables.js +50 -0
  49. package/dist/browser/decoder/standard-tables.js.map +1 -0
  50. package/dist/browser/encode.d.ts +57 -0
  51. package/dist/browser/encode.d.ts.map +1 -0
  52. package/dist/browser/encode.js +57 -0
  53. package/dist/browser/encode.js.map +1 -0
  54. package/dist/browser/encoder/encoder.d.ts +65 -0
  55. package/dist/browser/encoder/encoder.d.ts.map +1 -0
  56. package/dist/browser/encoder/encoder.js +713 -0
  57. package/dist/browser/encoder/encoder.js.map +1 -0
  58. package/dist/browser/encoder/huffman.d.ts +19 -0
  59. package/dist/browser/encoder/huffman.d.ts.map +1 -0
  60. package/dist/browser/encoder/huffman.js +135 -0
  61. package/dist/browser/encoder/huffman.js.map +1 -0
  62. package/dist/browser/encoder/progressive.d.ts +20 -0
  63. package/dist/browser/encoder/progressive.d.ts.map +1 -0
  64. package/dist/browser/encoder/progressive.js +315 -0
  65. package/dist/browser/encoder/progressive.js.map +1 -0
  66. package/dist/browser/encoder/writer.d.ts +18 -0
  67. package/dist/browser/encoder/writer.d.ts.map +1 -0
  68. package/dist/browser/encoder/writer.js +71 -0
  69. package/dist/browser/encoder/writer.js.map +1 -0
  70. package/dist/browser/errors.d.ts +27 -0
  71. package/dist/browser/errors.d.ts.map +1 -0
  72. package/dist/browser/errors.js +28 -0
  73. package/dist/browser/errors.js.map +1 -0
  74. package/dist/browser/index.d.ts +12 -0
  75. package/dist/browser/index.d.ts.map +1 -0
  76. package/dist/browser/index.js +8 -0
  77. package/dist/browser/index.js.map +1 -0
  78. package/dist/browser/package.json +3 -0
  79. package/dist/commonjs/compat.d.ts +44 -0
  80. package/dist/commonjs/compat.d.ts.map +1 -0
  81. package/dist/commonjs/compat.js +46 -0
  82. package/dist/commonjs/compat.js.map +1 -0
  83. package/dist/commonjs/decode.d.ts +73 -0
  84. package/dist/commonjs/decode.d.ts.map +1 -0
  85. package/dist/commonjs/decode.js +86 -0
  86. package/dist/commonjs/decode.js.map +1 -0
  87. package/dist/commonjs/decoder/arithmetic.d.ts +66 -0
  88. package/dist/commonjs/decoder/arithmetic.d.ts.map +1 -0
  89. package/dist/commonjs/decoder/arithmetic.js +380 -0
  90. package/dist/commonjs/decoder/arithmetic.js.map +1 -0
  91. package/dist/commonjs/decoder/decoder.d.ts +87 -0
  92. package/dist/commonjs/decoder/decoder.d.ts.map +1 -0
  93. package/dist/commonjs/decoder/decoder.js +873 -0
  94. package/dist/commonjs/decoder/decoder.js.map +1 -0
  95. package/dist/commonjs/decoder/huffman.d.ts +64 -0
  96. package/dist/commonjs/decoder/huffman.d.ts.map +1 -0
  97. package/dist/commonjs/decoder/huffman.js +265 -0
  98. package/dist/commonjs/decoder/huffman.js.map +1 -0
  99. package/dist/commonjs/decoder/idct.d.ts +20 -0
  100. package/dist/commonjs/decoder/idct.d.ts.map +1 -0
  101. package/dist/commonjs/decoder/idct.js +226 -0
  102. package/dist/commonjs/decoder/idct.js.map +1 -0
  103. package/dist/commonjs/decoder/output.d.ts +17 -0
  104. package/dist/commonjs/decoder/output.d.ts.map +1 -0
  105. package/dist/commonjs/decoder/output.js +354 -0
  106. package/dist/commonjs/decoder/output.js.map +1 -0
  107. package/dist/commonjs/decoder/scan-tables.d.ts +7 -0
  108. package/dist/commonjs/decoder/scan-tables.d.ts.map +1 -0
  109. package/dist/commonjs/decoder/scan-tables.js +16 -0
  110. package/dist/commonjs/decoder/scan-tables.js.map +1 -0
  111. package/dist/commonjs/decoder/scan.d.ts +57 -0
  112. package/dist/commonjs/decoder/scan.d.ts.map +1 -0
  113. package/dist/commonjs/decoder/scan.js +385 -0
  114. package/dist/commonjs/decoder/scan.js.map +1 -0
  115. package/dist/commonjs/decoder/smoothing.d.ts +28 -0
  116. package/dist/commonjs/decoder/smoothing.d.ts.map +1 -0
  117. package/dist/commonjs/decoder/smoothing.js +349 -0
  118. package/dist/commonjs/decoder/smoothing.js.map +1 -0
  119. package/dist/commonjs/decoder/standard-tables.d.ts +19 -0
  120. package/dist/commonjs/decoder/standard-tables.d.ts.map +1 -0
  121. package/dist/commonjs/decoder/standard-tables.js +53 -0
  122. package/dist/commonjs/decoder/standard-tables.js.map +1 -0
  123. package/dist/commonjs/encode.d.ts +57 -0
  124. package/dist/commonjs/encode.d.ts.map +1 -0
  125. package/dist/commonjs/encode.js +60 -0
  126. package/dist/commonjs/encode.js.map +1 -0
  127. package/dist/commonjs/encoder/encoder.d.ts +65 -0
  128. package/dist/commonjs/encoder/encoder.d.ts.map +1 -0
  129. package/dist/commonjs/encoder/encoder.js +720 -0
  130. package/dist/commonjs/encoder/encoder.js.map +1 -0
  131. package/dist/commonjs/encoder/huffman.d.ts +19 -0
  132. package/dist/commonjs/encoder/huffman.d.ts.map +1 -0
  133. package/dist/commonjs/encoder/huffman.js +139 -0
  134. package/dist/commonjs/encoder/huffman.js.map +1 -0
  135. package/dist/commonjs/encoder/progressive.d.ts +20 -0
  136. package/dist/commonjs/encoder/progressive.d.ts.map +1 -0
  137. package/dist/commonjs/encoder/progressive.js +318 -0
  138. package/dist/commonjs/encoder/progressive.js.map +1 -0
  139. package/dist/commonjs/encoder/writer.d.ts +18 -0
  140. package/dist/commonjs/encoder/writer.d.ts.map +1 -0
  141. package/dist/commonjs/encoder/writer.js +75 -0
  142. package/dist/commonjs/encoder/writer.js.map +1 -0
  143. package/dist/commonjs/errors.d.ts +27 -0
  144. package/dist/commonjs/errors.d.ts.map +1 -0
  145. package/dist/commonjs/errors.js +35 -0
  146. package/dist/commonjs/errors.js.map +1 -0
  147. package/dist/commonjs/index.d.ts +12 -0
  148. package/dist/commonjs/index.d.ts.map +1 -0
  149. package/dist/commonjs/index.js +19 -0
  150. package/dist/commonjs/index.js.map +1 -0
  151. package/dist/commonjs/package.json +3 -0
  152. package/dist/esm/compat.d.ts +44 -0
  153. package/dist/esm/compat.d.ts.map +1 -0
  154. package/dist/esm/compat.js +42 -0
  155. package/dist/esm/compat.js.map +1 -0
  156. package/dist/esm/decode.d.ts +73 -0
  157. package/dist/esm/decode.d.ts.map +1 -0
  158. package/dist/esm/decode.js +82 -0
  159. package/dist/esm/decode.js.map +1 -0
  160. package/dist/esm/decoder/arithmetic.d.ts +66 -0
  161. package/dist/esm/decoder/arithmetic.d.ts.map +1 -0
  162. package/dist/esm/decoder/arithmetic.js +374 -0
  163. package/dist/esm/decoder/arithmetic.js.map +1 -0
  164. package/dist/esm/decoder/decoder.d.ts +87 -0
  165. package/dist/esm/decoder/decoder.d.ts.map +1 -0
  166. package/dist/esm/decoder/decoder.js +869 -0
  167. package/dist/esm/decoder/decoder.js.map +1 -0
  168. package/dist/esm/decoder/huffman.d.ts +64 -0
  169. package/dist/esm/decoder/huffman.d.ts.map +1 -0
  170. package/dist/esm/decoder/huffman.js +260 -0
  171. package/dist/esm/decoder/huffman.js.map +1 -0
  172. package/dist/esm/decoder/idct.d.ts +20 -0
  173. package/dist/esm/decoder/idct.d.ts.map +1 -0
  174. package/dist/esm/decoder/idct.js +222 -0
  175. package/dist/esm/decoder/idct.js.map +1 -0
  176. package/dist/esm/decoder/output.d.ts +17 -0
  177. package/dist/esm/decoder/output.d.ts.map +1 -0
  178. package/dist/esm/decoder/output.js +351 -0
  179. package/dist/esm/decoder/output.js.map +1 -0
  180. package/dist/esm/decoder/scan-tables.d.ts +7 -0
  181. package/dist/esm/decoder/scan-tables.d.ts.map +1 -0
  182. package/dist/esm/decoder/scan-tables.js +13 -0
  183. package/dist/esm/decoder/scan-tables.js.map +1 -0
  184. package/dist/esm/decoder/scan.d.ts +57 -0
  185. package/dist/esm/decoder/scan.d.ts.map +1 -0
  186. package/dist/esm/decoder/scan.js +381 -0
  187. package/dist/esm/decoder/scan.js.map +1 -0
  188. package/dist/esm/decoder/smoothing.d.ts +28 -0
  189. package/dist/esm/decoder/smoothing.d.ts.map +1 -0
  190. package/dist/esm/decoder/smoothing.js +345 -0
  191. package/dist/esm/decoder/smoothing.js.map +1 -0
  192. package/dist/esm/decoder/standard-tables.d.ts +19 -0
  193. package/dist/esm/decoder/standard-tables.d.ts.map +1 -0
  194. package/dist/esm/decoder/standard-tables.js +50 -0
  195. package/dist/esm/decoder/standard-tables.js.map +1 -0
  196. package/dist/esm/encode.d.ts +57 -0
  197. package/dist/esm/encode.d.ts.map +1 -0
  198. package/dist/esm/encode.js +57 -0
  199. package/dist/esm/encode.js.map +1 -0
  200. package/dist/esm/encoder/encoder.d.ts +65 -0
  201. package/dist/esm/encoder/encoder.d.ts.map +1 -0
  202. package/dist/esm/encoder/encoder.js +713 -0
  203. package/dist/esm/encoder/encoder.js.map +1 -0
  204. package/dist/esm/encoder/huffman.d.ts +19 -0
  205. package/dist/esm/encoder/huffman.d.ts.map +1 -0
  206. package/dist/esm/encoder/huffman.js +135 -0
  207. package/dist/esm/encoder/huffman.js.map +1 -0
  208. package/dist/esm/encoder/progressive.d.ts +20 -0
  209. package/dist/esm/encoder/progressive.d.ts.map +1 -0
  210. package/dist/esm/encoder/progressive.js +315 -0
  211. package/dist/esm/encoder/progressive.js.map +1 -0
  212. package/dist/esm/encoder/writer.d.ts +18 -0
  213. package/dist/esm/encoder/writer.d.ts.map +1 -0
  214. package/dist/esm/encoder/writer.js +71 -0
  215. package/dist/esm/encoder/writer.js.map +1 -0
  216. package/dist/esm/errors.d.ts +27 -0
  217. package/dist/esm/errors.d.ts.map +1 -0
  218. package/dist/esm/errors.js +28 -0
  219. package/dist/esm/errors.js.map +1 -0
  220. package/dist/esm/index.d.ts +12 -0
  221. package/dist/esm/index.d.ts.map +1 -0
  222. package/dist/esm/index.js +8 -0
  223. package/dist/esm/index.js.map +1 -0
  224. package/dist/esm/package.json +3 -0
  225. package/package.json +99 -4
@@ -0,0 +1,869 @@
1
+ /*
2
+ * JPEG decoder: marker parsing, frame setup and orchestration.
3
+ *
4
+ * Copyright 2011 notmasteryet
5
+ * Copyright 2014 Mozilla Foundation
6
+ *
7
+ * Licensed under the Apache License, Version 2.0 (the "License");
8
+ * you may not use this file except in compliance with the License.
9
+ * You may obtain a copy of the License at
10
+ *
11
+ * http://www.apache.org/licenses/LICENSE-2.0
12
+ *
13
+ * Unless required by applicable law or agreed to in writing, software
14
+ * distributed under the License is distributed on an "AS IS" BASIS,
15
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16
+ * See the License for the specific language governing permissions and
17
+ * limitations under the License.
18
+ *
19
+ * This code was forked from https://github.com/notmasteryet/jpgjs, through
20
+ * jpeg-js (https://github.com/jpeg-js/jpeg-js) and pdf.js
21
+ * (https://github.com/mozilla/pdf.js, src/core/jpg.js and jpeg_utils.js).
22
+ *
23
+ * - The JPEG specification can be found in the ITU CCITT Recommendation T.81
24
+ * (www.w3.org/Graphics/JPEG/itu-t81.pdf)
25
+ * - The JFIF specification can be found in the JPEG File Interchange Format
26
+ * (www.w3.org/Graphics/JPEG/jfif3.pdf)
27
+ * - The Adobe Application-Specific JPEG markers in the
28
+ * Supporting the DCT Filters in PostScript Level 2, Technical Note #5116
29
+ * (partners.adobe.com/public/developer/en/ps/sdk/5116.DCT_Filter.pdf)
30
+ *
31
+ * Modified by Jimp contributors (2026):
32
+ * - translated to TypeScript, with a JpegError subclass for every failure
33
+ * instead of TypeErrors on malformed input;
34
+ * - every segment is bounds-checked; SOS before SOF, unknown component IDs,
35
+ * missing tables, bad sampling factors and bad progression parameters are
36
+ * rejected;
37
+ * - recovery from junk between segments, a lost 0xFF before a marker, segment
38
+ * lengths that are off and a missing EOI, merged from jpeg-js and Jimp;
39
+ * - DNL support only for frames whose SOF height is 0, found by scanning ahead
40
+ * instead of re-parsing;
41
+ * - entropy decoding, IDCT, upsampling and colour conversion are replaced by
42
+ * ports of libjpeg-turbo's (scan.ts, idct.ts, output.ts), and arithmetic
43
+ * coding is supported (arithmetic.ts);
44
+ * - sequential images are decoded one MCU row at a time, straight into sample
45
+ * planes, and colour conversion picks the colour space like libjpeg;
46
+ * - resolution and memory limits from jpeg-js, plus external tables (JPEG
47
+ * abbreviated format).
48
+ */
49
+ import { JpegFormatError, JpegLimitError, JpegUnsupportedError, } from "../errors.js";
50
+ import { defaultConditioning, } from "./arithmetic.js";
51
+ import { buildHuffmanTable } from "./huffman.js";
52
+ import { createIdctContext, idctBlock, } from "./idct.js";
53
+ import { convertToRgb, } from "./output.js";
54
+ import { decodeScan, NATURAL_ORDER } from "./scan.js";
55
+ import { smoothAndTransform, smoothingUseful } from "./smoothing.js";
56
+ import { STANDARD_TABLES } from "./standard-tables.js";
57
+ /** Maximum number of blocks in an MCU, as in libjpeg (D_MAX_BLOCKS_IN_MCU). */
58
+ const MAX_BLOCKS_IN_MCU = 10;
59
+ /** Defends against files with an absurd number of (empty) scans. */
60
+ const MAX_SCANS = 1000;
61
+ const SOF_NAMES = {
62
+ 0xc3: "lossless",
63
+ 0xc5: "differential sequential (hierarchical)",
64
+ 0xc6: "differential progressive (hierarchical)",
65
+ 0xc7: "differential lossless (hierarchical)",
66
+ 0xcb: "arithmetic-coded lossless",
67
+ 0xcd: "arithmetic-coded differential sequential (hierarchical)",
68
+ 0xce: "arithmetic-coded differential progressive (hierarchical)",
69
+ 0xcf: "arithmetic-coded differential lossless (hierarchical)",
70
+ };
71
+ function hex(value) {
72
+ return value.toString(16).toUpperCase().padStart(2, "0");
73
+ }
74
+ function isMarkerCode(code) {
75
+ return code !== undefined && code >= 0xc0 && code <= 0xfe;
76
+ }
77
+ /** Markers that are followed by a length field. */
78
+ function hasLength(code) {
79
+ return !(code >= 0xd0 && code <= 0xd9) && code !== 0x01;
80
+ }
81
+ export class JpegDecoder {
82
+ options;
83
+ width = 0;
84
+ height = 0;
85
+ jfif = false;
86
+ adobe = null;
87
+ exif;
88
+ comments = [];
89
+ frame = null;
90
+ quantTables = [];
91
+ dcTables = [];
92
+ acTables = [];
93
+ restartInterval = 0;
94
+ conditioning = defaultConditioning();
95
+ /** Sequential image whose single scan is decoded one MCU row at a time. */
96
+ streaming = false;
97
+ scans = 0;
98
+ idct = null;
99
+ memoryUsed = 0;
100
+ /** See ScanResult.lastGoodRow. */
101
+ lastGoodRow = 0;
102
+ constructor(options) {
103
+ this.options = options;
104
+ }
105
+ get tolerant() {
106
+ return this.options.tolerantDecoding;
107
+ }
108
+ corrupt(message) {
109
+ if (!this.tolerant) {
110
+ throw new JpegFormatError(message);
111
+ }
112
+ }
113
+ /** Tracks memory use against maxMemoryUsageInMB, like jpeg-js. */
114
+ requestMemory(bytes) {
115
+ const max = this.options.maxMemoryUsageInMB * 1024 * 1024;
116
+ this.memoryUsed += bytes;
117
+ if (this.memoryUsed > max) {
118
+ const exceeded = Math.ceil((this.memoryUsed - max) / 1024 / 1024);
119
+ throw new JpegLimitError(`maxMemoryUsageInMB limit exceeded by at least ${exceeded}MB`);
120
+ }
121
+ }
122
+ parse(data) {
123
+ if (this.options.tables) {
124
+ this.parseMarkers(this.options.tables, true);
125
+ }
126
+ this.parseMarkers(data, false);
127
+ const frame = this.frame;
128
+ if (!frame) {
129
+ throw new JpegFormatError("JPEG data contains no image (no SOF marker)");
130
+ }
131
+ if (this.scans === 0) {
132
+ throw new JpegFormatError("JPEG data contains no image data (no SOS marker)");
133
+ }
134
+ if (!this.streaming) {
135
+ this.finishCoefficients(frame);
136
+ }
137
+ }
138
+ parseMarkers(data, tablesOnly) {
139
+ const length = data.length;
140
+ if (length < 2 || data[0] !== 0xff || data[1] !== 0xd8) {
141
+ throw new JpegFormatError(tablesOnly
142
+ ? "JPEG tables don't start with an SOI marker"
143
+ : "SOI not found: the data is not a JPEG");
144
+ }
145
+ let offset = 2;
146
+ while (offset < length) {
147
+ if (data[offset] !== 0xff || !isMarkerCode(data[offset + 1])) {
148
+ // Fill bytes before a marker
149
+ if (data[offset] === 0xff && data[offset + 1] === 0xff) {
150
+ offset++;
151
+ continue;
152
+ }
153
+ const next = this.recoverMarker(data, offset);
154
+ if (next < 0) {
155
+ break;
156
+ }
157
+ // Unless the marker only lost its 0xFF, parse from where it is
158
+ if (next !== offset) {
159
+ offset = next;
160
+ continue;
161
+ }
162
+ }
163
+ const code = data[offset + 1];
164
+ let segmentEnd = offset + 2;
165
+ if (hasLength(code)) {
166
+ if (offset + 4 > length) {
167
+ this.corrupt("JPEG data ends inside a marker segment");
168
+ break;
169
+ }
170
+ const segmentLength = (data[offset + 2] << 8) | data[offset + 3];
171
+ segmentEnd = offset + 2 + segmentLength;
172
+ if (segmentLength < 2 || segmentEnd > length) {
173
+ // Only metadata can be cut short and leave a usable image
174
+ if (code >= 0xe0 || code === 0xfe) {
175
+ this.corrupt(`Bad length of ${this.describe(code)}`);
176
+ break;
177
+ }
178
+ throw new JpegFormatError(`Bad length of ${this.describe(code)}`);
179
+ }
180
+ }
181
+ const start = offset + 4;
182
+ if (code === 0xd9) {
183
+ break;
184
+ }
185
+ if (tablesOnly &&
186
+ code !== 0xdb &&
187
+ code !== 0xc4 &&
188
+ code !== 0xdd &&
189
+ code !== 0xcc &&
190
+ !(code >= 0xe0 && code <= 0xef) &&
191
+ code !== 0xfe) {
192
+ throw new JpegFormatError(`JPEG tables can only contain DQT, DHT and DRI markers, not ${this.describe(code)}`);
193
+ }
194
+ switch (code) {
195
+ case 0xe0:
196
+ case 0xe1:
197
+ case 0xe2:
198
+ case 0xe3:
199
+ case 0xe4:
200
+ case 0xe5:
201
+ case 0xe6:
202
+ case 0xe7:
203
+ case 0xe8:
204
+ case 0xe9:
205
+ case 0xea:
206
+ case 0xeb:
207
+ case 0xec:
208
+ case 0xed:
209
+ case 0xee:
210
+ case 0xef:
211
+ case 0xfe:
212
+ segmentEnd = this.fixSegmentEnd(data, start, segmentEnd);
213
+ if (!tablesOnly) {
214
+ this.readAppSegment(code, data.subarray(start, segmentEnd));
215
+ }
216
+ offset = segmentEnd;
217
+ break;
218
+ case 0xdb:
219
+ this.readQuantTables(data, start, segmentEnd);
220
+ offset = segmentEnd;
221
+ break;
222
+ case 0xc4:
223
+ this.readHuffmanTables(data, start, segmentEnd);
224
+ offset = segmentEnd;
225
+ break;
226
+ case 0xdd:
227
+ if (segmentEnd - start < 2) {
228
+ throw new JpegFormatError("Bad length of DRI marker");
229
+ }
230
+ this.restartInterval = (data[start] << 8) | data[start + 1];
231
+ offset = segmentEnd;
232
+ break;
233
+ case 0xc0:
234
+ case 0xc1:
235
+ case 0xc2:
236
+ case 0xc9:
237
+ case 0xca:
238
+ this.readFrame(code, data, start, segmentEnd);
239
+ offset = segmentEnd;
240
+ break;
241
+ case 0xc3:
242
+ case 0xc5:
243
+ case 0xc6:
244
+ case 0xc7:
245
+ case 0xcb:
246
+ case 0xcd:
247
+ case 0xce:
248
+ case 0xcf:
249
+ throw new JpegUnsupportedError(`Unsupported JPEG process: ${SOF_NAMES[code]} (SOF${code - 0xc0}) JPEGs are not supported`);
250
+ case 0xda:
251
+ offset = this.readScan(data, start, segmentEnd);
252
+ break;
253
+ case 0xd8: // SOI
254
+ case 0xd0: // RSTn outside a scan, e.g. extra ones after it
255
+ case 0xd1:
256
+ case 0xd2:
257
+ case 0xd3:
258
+ case 0xd4:
259
+ case 0xd5:
260
+ case 0xd6:
261
+ case 0xd7:
262
+ offset += 2;
263
+ break;
264
+ case 0xcc:
265
+ this.readConditioning(data, start, segmentEnd);
266
+ offset = segmentEnd;
267
+ break;
268
+ case 0xdc: // DNL: read ahead in readFrame() when it's needed
269
+ offset = segmentEnd;
270
+ break;
271
+ default:
272
+ // JPGn, DHP, EXP, ... Skip them like APPn if their length is sane
273
+ this.corrupt(`Unsupported JPEG marker ${this.describe(code)}`);
274
+ offset = this.fixSegmentEnd(data, start, segmentEnd);
275
+ break;
276
+ }
277
+ }
278
+ }
279
+ describe(code) {
280
+ return `marker 0xFF${hex(code)}`;
281
+ }
282
+ /**
283
+ * Called when a marker was expected at `offset` but isn't there. Finds where
284
+ * parsing should go on, or returns -1 to stop.
285
+ */
286
+ recoverMarker(data, offset) {
287
+ const length = data.length;
288
+ this.corrupt(`Corrupt JPEG data: expected a marker at offset ${offset}, found 0x${hex(data[offset])}`);
289
+ // The 0xFF of the marker was lost (seen from Pixel phones, jpeg-js #84):
290
+ // parse it from here
291
+ const code = data[offset + 1];
292
+ if (isMarkerCode(code) &&
293
+ hasLength(code) &&
294
+ offset + 4 <= length &&
295
+ this.segmentEndsWell(data, offset + 2 + ((data[offset + 2] << 8) | data[offset + 3]))) {
296
+ return offset;
297
+ }
298
+ // Otherwise skip to the next marker, like libjpeg does (and Jimp did
299
+ // with skipJunkBeforeMarkers)
300
+ for (let i = offset + 1; i + 1 < length; i++) {
301
+ if (data[i] !== 0xff) {
302
+ continue;
303
+ }
304
+ const next = data[i + 1];
305
+ if (!isMarkerCode(next) || next === 0xff) {
306
+ continue;
307
+ }
308
+ if (!hasLength(next) ||
309
+ next === 0xda ||
310
+ (i + 4 <= length &&
311
+ this.segmentEndsWell(data, i + 2 + ((data[i + 2] << 8) | data[i + 3])))) {
312
+ return i;
313
+ }
314
+ }
315
+ return -1;
316
+ }
317
+ /** Whether a segment ending at `end` is followed by a marker or the end. */
318
+ segmentEndsWell(data, end) {
319
+ return end === data.length || (end < data.length && data[end] === 0xff);
320
+ }
321
+ /**
322
+ * Fixes the end of a segment whose length doesn't lead to a marker, by
323
+ * searching for one in the data (pdf.js readDataBlock).
324
+ */
325
+ fixSegmentEnd(data, start, end) {
326
+ if (this.segmentEndsWell(data, end)) {
327
+ return end;
328
+ }
329
+ this.corrupt("Corrupt JPEG data: bad marker segment length");
330
+ for (let i = start; i + 1 < data.length; i++) {
331
+ if (data[i] === 0xff &&
332
+ isMarkerCode(data[i + 1]) &&
333
+ data[i + 1] !== 0xff) {
334
+ return i;
335
+ }
336
+ }
337
+ return data.length;
338
+ }
339
+ readAppSegment(code, segment) {
340
+ const is = (...bytes) => bytes.every((byte, index) => segment[index] === byte);
341
+ if (code === 0xfe) {
342
+ let comment = "";
343
+ for (let i = 0; i < segment.length; i += 0x8000) {
344
+ comment += String.fromCharCode(...segment.subarray(i, i + 0x8000));
345
+ }
346
+ this.comments.push(comment);
347
+ }
348
+ else if (code === 0xe0 && is(0x4a, 0x46, 0x49, 0x46, 0)) {
349
+ // JFIF\0
350
+ this.jfif = true;
351
+ }
352
+ else if (code === 0xe1 && is(0x45, 0x78, 0x69, 0x66, 0)) {
353
+ // Exif\0. Like jpeg-js, everything after "Exif\0", so starting with the
354
+ // second padding byte
355
+ this.exif = segment.slice(5);
356
+ }
357
+ else if (code === 0xee && is(0x41, 0x64, 0x6f, 0x62, 0x65)) {
358
+ // Adobe
359
+ this.adobe = { transformCode: segment[11] ?? 0 };
360
+ }
361
+ }
362
+ readQuantTables(data, offset, end) {
363
+ while (offset < end) {
364
+ const spec = data[offset++];
365
+ const precision = spec >> 4;
366
+ if (precision > 1) {
367
+ throw new JpegFormatError("Bogus DQT: invalid table precision");
368
+ }
369
+ if (offset + 64 * (precision + 1) > end) {
370
+ throw new JpegFormatError("Bad length of DQT marker");
371
+ }
372
+ const table = new Uint16Array(64);
373
+ for (let i = 0; i < 64; i++) {
374
+ if (precision === 0) {
375
+ table[NATURAL_ORDER[i]] = data[offset++];
376
+ }
377
+ else {
378
+ table[NATURAL_ORDER[i]] = (data[offset] << 8) | data[offset + 1];
379
+ offset += 2;
380
+ }
381
+ }
382
+ this.quantTables[spec & 15] = table;
383
+ }
384
+ }
385
+ readHuffmanTables(data, offset, end) {
386
+ while (offset < end) {
387
+ const spec = data[offset++];
388
+ const tableClass = spec >> 4;
389
+ if (tableClass > 1 || offset + 16 > end) {
390
+ throw new JpegFormatError("Bogus DHT: invalid table");
391
+ }
392
+ const counts = data.subarray(offset, offset + 16);
393
+ let count = 0;
394
+ for (let i = 0; i < 16; i++) {
395
+ count += counts[i];
396
+ }
397
+ offset += 16;
398
+ if (count > 256 || offset + count > end) {
399
+ throw new JpegFormatError("Bogus DHT: invalid table");
400
+ }
401
+ const table = buildHuffmanTable(counts, data.subarray(offset, offset + count), tableClass === 0);
402
+ offset += count;
403
+ (tableClass === 0 ? this.dcTables : this.acTables)[spec & 15] = table;
404
+ }
405
+ }
406
+ /** DAC: arithmetic coding conditioning, like libjpeg's get_dac(). */
407
+ readConditioning(data, offset, end) {
408
+ if ((end - offset) % 2 !== 0) {
409
+ throw new JpegFormatError("Bad length of DAC marker");
410
+ }
411
+ for (; offset < end; offset += 2) {
412
+ const index = data[offset];
413
+ const value = data[offset + 1];
414
+ const table = index & 15;
415
+ if (index >= 32 || table > 3) {
416
+ throw new JpegFormatError(`Bogus DAC index ${index}`);
417
+ }
418
+ if (index >= 16) {
419
+ this.conditioning.acK[table] = value;
420
+ }
421
+ else {
422
+ this.conditioning.dcLower[table] = value & 15;
423
+ this.conditioning.dcUpper[table] = value >> 4;
424
+ if ((value & 15) > value >> 4) {
425
+ throw new JpegFormatError(`Bogus DAC value 0x${hex(value)}`);
426
+ }
427
+ }
428
+ }
429
+ }
430
+ readFrame(code, data, offset, end) {
431
+ if (this.frame) {
432
+ throw new JpegFormatError("JPEG data has more than one frame (SOF marker)");
433
+ }
434
+ if (end - offset < 6) {
435
+ throw new JpegFormatError("Bad length of SOF marker");
436
+ }
437
+ const precision = data[offset];
438
+ let height = (data[offset + 1] << 8) | data[offset + 2];
439
+ const width = (data[offset + 3] << 8) | data[offset + 4];
440
+ const count = data[offset + 5];
441
+ if (precision !== 8 && precision !== 12) {
442
+ throw new JpegUnsupportedError(`Unsupported JPEG data precision: ${precision} bits (only 8 and 12 are supported)`);
443
+ }
444
+ if (count === 0 || end - offset < 6 + count * 3) {
445
+ throw new JpegFormatError("Bad length of SOF marker");
446
+ }
447
+ if (count !== 1 && count !== 3 && count !== 4) {
448
+ throw new JpegUnsupportedError(`Unsupported JPEG colour format: ${count} components`);
449
+ }
450
+ if (width === 0) {
451
+ throw new JpegFormatError("Empty JPEG image (width is 0)");
452
+ }
453
+ if (height === 0) {
454
+ // The height is in a DNL marker after the first scan
455
+ height = this.findDnlHeight(data, end);
456
+ }
457
+ const megapixels = (width * height) / 1e6;
458
+ if (megapixels > this.options.maxResolutionInMP) {
459
+ const exceeded = Math.ceil(megapixels - this.options.maxResolutionInMP);
460
+ throw new JpegLimitError(`maxResolutionInMP limit exceeded by ${exceeded}MP`);
461
+ }
462
+ const components = [];
463
+ let maxH = 1;
464
+ let maxV = 1;
465
+ for (let i = 0; i < count; i++) {
466
+ const p = offset + 6 + i * 3;
467
+ const id = data[p];
468
+ const h = data[p + 1] >> 4;
469
+ const v = data[p + 1] & 15;
470
+ if (h < 1 || h > 4 || v < 1 || v > 4) {
471
+ throw new JpegFormatError("Invalid sampling factor, expected values above 0 and up to 4");
472
+ }
473
+ maxH = Math.max(maxH, h);
474
+ maxV = Math.max(maxV, v);
475
+ components.push({
476
+ id,
477
+ h,
478
+ v,
479
+ quantId: data[p + 2],
480
+ quantTable: null,
481
+ blocksPerLine: 0,
482
+ blocksPerColumn: 0,
483
+ blocksPerLineMcu: 0,
484
+ blocksPerColumnMcu: 0,
485
+ width: 0,
486
+ height: 0,
487
+ coefficients: new Int16Array(0),
488
+ plane: null,
489
+ dcTable: null,
490
+ acTable: null,
491
+ pred: 0,
492
+ dcArithmetic: 0,
493
+ acArithmetic: 0,
494
+ dcContext: 0,
495
+ scanned: false,
496
+ coefBits: new Int8Array(64).fill(-1),
497
+ previousCoefBits: new Int8Array(64),
498
+ });
499
+ }
500
+ const mcusPerLine = Math.ceil(width / (8 * maxH));
501
+ const mcusPerColumn = Math.ceil(height / (8 * maxV));
502
+ const sampleBytes = precision > 8 ? 2 : 1;
503
+ let planeBytes = 0;
504
+ let coefficientBytes = 0;
505
+ for (const component of components) {
506
+ component.width = Math.ceil((width * component.h) / maxH);
507
+ component.height = Math.ceil((height * component.v) / maxV);
508
+ component.blocksPerLine = Math.ceil(component.width / 8);
509
+ component.blocksPerColumn = Math.ceil(component.height / 8);
510
+ component.blocksPerLineMcu = mcusPerLine * component.h;
511
+ component.blocksPerColumnMcu = mcusPerColumn * component.v;
512
+ planeBytes +=
513
+ component.blocksPerLine * component.blocksPerColumn * 64 * sampleBytes;
514
+ coefficientBytes +=
515
+ component.blocksPerLineMcu * component.blocksPerColumnMcu * 128;
516
+ }
517
+ this.width = width;
518
+ this.height = height;
519
+ const progressive = code === 0xc2 || code === 0xca;
520
+ this.frame = {
521
+ progressive,
522
+ arithmetic: code === 0xc9 || code === 0xca,
523
+ precision,
524
+ width,
525
+ height,
526
+ components,
527
+ maxH,
528
+ maxV,
529
+ mcusPerLine,
530
+ mcusPerColumn,
531
+ };
532
+ // The planes and the output, plus the coefficients of a progressive JPEG
533
+ this.requestMemory(planeBytes + width * height * 4);
534
+ if (progressive) {
535
+ this.requestMemory(coefficientBytes);
536
+ }
537
+ }
538
+ /** Finds the DNL marker that gives the height of a frame. */
539
+ findDnlHeight(data, offset) {
540
+ for (let i = offset; i + 5 < data.length; i++) {
541
+ if (data[i] === 0xff && data[i + 1] === 0xdc) {
542
+ const height = (data[i + 4] << 8) | data[i + 5];
543
+ if (height > 0) {
544
+ return height;
545
+ }
546
+ }
547
+ }
548
+ throw new JpegFormatError("Empty JPEG image (height is 0 and there is no DNL marker)");
549
+ }
550
+ readScan(data, offset, end) {
551
+ const frame = this.frame;
552
+ if (!frame) {
553
+ throw new JpegFormatError("Corrupt JPEG data: SOS marker before SOF marker");
554
+ }
555
+ if (++this.scans > MAX_SCANS) {
556
+ throw new JpegLimitError(`JPEG has more than ${MAX_SCANS} scans`);
557
+ }
558
+ const count = data[offset++];
559
+ if (count < 1 || count > 4 || end - offset !== count * 2 + 3) {
560
+ throw new JpegFormatError("Bad length of SOS marker");
561
+ }
562
+ const components = [];
563
+ for (let i = 0; i < count; i++) {
564
+ const id = data[offset++];
565
+ const tables = data[offset++];
566
+ const component = frame.components.find((c) => c.id === id);
567
+ if (!component || components.includes(component)) {
568
+ throw new JpegFormatError(`Invalid component ID ${id} in SOS marker`);
569
+ }
570
+ if (frame.arithmetic) {
571
+ if (tables >> 4 > 3 || (tables & 15) > 3) {
572
+ throw new JpegFormatError("Invalid arithmetic table in SOS marker");
573
+ }
574
+ component.dcArithmetic = tables >> 4;
575
+ component.acArithmetic = tables & 15;
576
+ }
577
+ else {
578
+ component.dcTable = this.huffmanTable(this.dcTables, tables >> 4, true, frame.progressive);
579
+ component.acTable = this.huffmanTable(this.acTables, tables & 15, false, frame.progressive);
580
+ }
581
+ components.push(component);
582
+ }
583
+ const spectralStart = data[offset++];
584
+ const spectralEnd = data[offset++];
585
+ const approxHigh = data[offset] >> 4;
586
+ const approxLow = data[offset] & 15;
587
+ if (frame.progressive) {
588
+ const dc = spectralStart === 0;
589
+ if ((dc
590
+ ? spectralEnd !== 0
591
+ : spectralStart > spectralEnd || spectralEnd > 63 || count !== 1) ||
592
+ (approxHigh !== 0 && approxLow !== approxHigh - 1) ||
593
+ approxLow > 13) {
594
+ throw new JpegFormatError(`Invalid progressive parameters Ss=${spectralStart} Se=${spectralEnd} Ah=${approxHigh} Al=${approxLow}`);
595
+ }
596
+ }
597
+ // Check the tables each kind of scan needs
598
+ const needsDC = !frame.progressive || (spectralStart === 0 && approxHigh === 0);
599
+ const needsAC = !frame.progressive || spectralStart > 0;
600
+ for (const component of components) {
601
+ if (frame.arithmetic) {
602
+ break;
603
+ }
604
+ if ((needsDC && !component.dcTable) || (needsAC && !component.acTable)) {
605
+ throw new JpegFormatError("Huffman table missing for SOS component");
606
+ }
607
+ }
608
+ if (count > 1) {
609
+ let blocks = 0;
610
+ for (const component of components) {
611
+ blocks += component.h * component.v;
612
+ }
613
+ if (blocks > MAX_BLOCKS_IN_MCU) {
614
+ throw new JpegFormatError("Sampling factors too large for interleaved scan");
615
+ }
616
+ }
617
+ const scanStart = end;
618
+ if (!frame.progressive && this.streaming) {
619
+ // The image is complete, ignore further scans
620
+ return this.skipScan(data, scanStart);
621
+ }
622
+ for (const component of components) {
623
+ if (!component.quantTable) {
624
+ component.quantTable = this.quantTables[component.quantId] ?? null;
625
+ if (!component.quantTable &&
626
+ !frame.progressive &&
627
+ count === frame.components.length) {
628
+ throw new JpegFormatError(`Quantization table ${component.quantId} is missing`);
629
+ }
630
+ }
631
+ }
632
+ this.checkEnoughData(frame, data, scanStart, components, needsDC ? (frame.progressive ? 1 : 2) : 0);
633
+ const firstScan = this.scans === 1;
634
+ if (firstScan) {
635
+ this.idct = createIdctContext(frame.precision);
636
+ this.streaming = !frame.progressive && count === frame.components.length;
637
+ }
638
+ if (this.streaming) {
639
+ return this.decodeStreamingScan(frame, data, scanStart, components);
640
+ }
641
+ if (frame.progressive) {
642
+ // Track the progression for block smoothing, like jdphuff.c
643
+ for (const { coefBits, previousCoefBits } of components) {
644
+ const from = Math.min(spectralStart, 1);
645
+ const to = Math.max(spectralEnd, 9);
646
+ for (let i = from; i <= to; i++) {
647
+ previousCoefBits[i] = this.scans > 1 ? coefBits[i] : 0;
648
+ }
649
+ for (let i = spectralStart; i <= spectralEnd; i++) {
650
+ coefBits[i] = approxLow;
651
+ }
652
+ }
653
+ }
654
+ for (const component of components) {
655
+ if (component.coefficients.length === 0) {
656
+ if (!frame.progressive) {
657
+ this.requestMemory(component.blocksPerLineMcu * component.blocksPerColumnMcu * 128);
658
+ }
659
+ component.coefficients = this.allocate(() => new Int16Array(component.blocksPerLineMcu * component.blocksPerColumnMcu * 64));
660
+ }
661
+ component.scanned = true;
662
+ }
663
+ const result = decodeScan(data, scanStart, {
664
+ components,
665
+ progressive: frame.progressive,
666
+ spectralStart,
667
+ spectralEnd,
668
+ approxHigh,
669
+ approxLow,
670
+ mcusPerLine: frame.mcusPerLine,
671
+ mcusPerColumn: frame.mcusPerColumn,
672
+ restartInterval: this.restartInterval,
673
+ arithmetic: frame.arithmetic ? this.conditioning : undefined,
674
+ }, this.scanOptions());
675
+ this.lastGoodRow = result.lastGoodRow;
676
+ return result.offset;
677
+ }
678
+ scanOptions() {
679
+ return {
680
+ tolerant: this.tolerant,
681
+ allowTruncated: this.options.allowTruncated,
682
+ };
683
+ }
684
+ huffmanTable(tables, id, isDC, progressive) {
685
+ let table = tables[id];
686
+ // Like libjpeg-turbo, fall back on the tables of the JPEG standard
687
+ // (Annex K) in sequential JPEGs: Motion JPEG frames leave them out
688
+ if (!table && !progressive && id < 2) {
689
+ const standard = STANDARD_TABLES[isDC ? "dc" : "ac"][id];
690
+ table = buildHuffmanTable(standard.counts, standard.symbols, isDC);
691
+ tables[id] = table;
692
+ }
693
+ return table ?? null;
694
+ }
695
+ /**
696
+ * Rejects a frame that is too big for the data left before decoding it, so
697
+ * a small file can't make the decoder allocate and decode a huge image.
698
+ * Every block needs at least one bit per scan for its DC coefficient, two
699
+ * for a sequential scan (with the end-of-block code).
700
+ */
701
+ checkEnoughData(frame, data, offset, components, bitsPerBlock) {
702
+ // Arithmetic coding can take less than a bit per block
703
+ if (this.options.allowTruncated || bitsPerBlock === 0 || frame.arithmetic) {
704
+ return;
705
+ }
706
+ let blocks = 0;
707
+ for (const component of components) {
708
+ blocks +=
709
+ components.length === 1
710
+ ? component.blocksPerLine * component.blocksPerColumn
711
+ : frame.mcusPerLine * frame.mcusPerColumn * component.h * component.v;
712
+ }
713
+ // Leave a row of MCUs, which may be missing (see checkTruncated())
714
+ const rowBlocks = frame.mcusPerLine * frame.maxH * frame.maxV * components.length;
715
+ if (((blocks - rowBlocks) * bitsPerBlock) / 8 > data.length - offset) {
716
+ throw new JpegFormatError("JPEG data is truncated: the image data ends before the image is complete");
717
+ }
718
+ }
719
+ allocate(create) {
720
+ try {
721
+ return create();
722
+ }
723
+ catch (error) {
724
+ if (error instanceof RangeError) {
725
+ throw new JpegLimitError("Could not allocate enough memory for the image");
726
+ }
727
+ throw error;
728
+ }
729
+ }
730
+ createPlane(frame, component) {
731
+ const size = component.blocksPerLine * component.blocksPerColumn * 64;
732
+ component.plane = this.allocate(() => frame.precision > 8 ? new Uint16Array(size) : new Uint8Array(size));
733
+ }
734
+ decodeStreamingScan(frame, data, offset, components) {
735
+ const single = components.length === 1;
736
+ const idct = this.idct;
737
+ for (const component of components) {
738
+ const rows = single ? 1 : component.v;
739
+ component.coefficients = new Int16Array(component.blocksPerLineMcu * rows * 64);
740
+ this.createPlane(frame, component);
741
+ component.scanned = true;
742
+ }
743
+ const onRow = (mcuRow) => {
744
+ for (const component of components) {
745
+ const rows = single ? 1 : component.v;
746
+ const { blocksPerLine, blocksPerColumn, blocksPerLineMcu, coefficients, } = component;
747
+ const plane = component.plane;
748
+ const stride = blocksPerLine * 8;
749
+ const quantTable = component.quantTable;
750
+ for (let j = 0; j < rows; j++) {
751
+ const blockRow = mcuRow * rows + j;
752
+ if (blockRow >= blocksPerColumn) {
753
+ break;
754
+ }
755
+ for (let col = 0; col < blocksPerLine; col++) {
756
+ idctBlock(idct, coefficients, (j * blocksPerLineMcu + col) * 64, quantTable, plane, blockRow * 8 * stride + col * 8, stride);
757
+ }
758
+ }
759
+ coefficients.fill(0);
760
+ }
761
+ };
762
+ return decodeScan(data, offset, {
763
+ components,
764
+ progressive: false,
765
+ spectralStart: 0,
766
+ spectralEnd: 63,
767
+ approxHigh: 0,
768
+ approxLow: 0,
769
+ mcusPerLine: frame.mcusPerLine,
770
+ mcusPerColumn: frame.mcusPerColumn,
771
+ restartInterval: this.restartInterval,
772
+ arithmetic: frame.arithmetic ? this.conditioning : undefined,
773
+ onRow,
774
+ }, this.scanOptions()).offset;
775
+ }
776
+ /** Skips the data of a scan that isn't decoded. */
777
+ skipScan(data, offset) {
778
+ for (let i = offset; i + 1 < data.length; i++) {
779
+ const next = data[i + 1];
780
+ if (data[i] === 0xff &&
781
+ next !== 0 &&
782
+ next !== 0xff &&
783
+ !(next >= 0xd0 && next <= 0xd7)) {
784
+ return i;
785
+ }
786
+ }
787
+ return data.length;
788
+ }
789
+ /** IDCT of the stored coefficients of a progressive or multi-scan JPEG. */
790
+ finishCoefficients(frame) {
791
+ const idct = this.idct;
792
+ const latched = frame.components.every((c) => c.quantTable);
793
+ const smoothing = frame.progressive &&
794
+ latched &&
795
+ smoothingUseful(frame.components.map((c) => ({ ...c, quantTable: c.quantTable })));
796
+ for (const component of frame.components) {
797
+ if (!component.scanned) {
798
+ this.corrupt("JPEG data is missing a colour component");
799
+ }
800
+ const quantTable = component.quantTable ?? this.quantTables[component.quantId];
801
+ if (!quantTable) {
802
+ throw new JpegFormatError(`Quantization table ${component.quantId} is missing`);
803
+ }
804
+ this.createPlane(frame, component);
805
+ if (!component.scanned) {
806
+ continue;
807
+ }
808
+ if (smoothing) {
809
+ smoothAndTransform(idct, { ...component, quantTable }, component.plane, this.scans, this.lastGoodRow, frame.mcusPerColumn);
810
+ component.coefficients = new Int16Array(0);
811
+ continue;
812
+ }
813
+ const { blocksPerLine, blocksPerColumn, blocksPerLineMcu, coefficients } = component;
814
+ const plane = component.plane;
815
+ const stride = blocksPerLine * 8;
816
+ for (let row = 0; row < blocksPerColumn; row++) {
817
+ for (let col = 0; col < blocksPerLine; col++) {
818
+ idctBlock(idct, coefficients, (row * blocksPerLineMcu + col) * 64, quantTable, plane, row * 8 * stride + col * 8, stride);
819
+ }
820
+ }
821
+ // Free the coefficients before the output is allocated
822
+ component.coefficients = new Int16Array(0);
823
+ }
824
+ }
825
+ /**
826
+ * The colour space of the data, picked like libjpeg does unless
827
+ * `colorTransform` says whether to transform from YCbCr (or YCCK).
828
+ */
829
+ get colorSpace() {
830
+ const frame = this.frame;
831
+ const count = frame.components.length;
832
+ const transform = this.options.colorTransform;
833
+ if (count === 1) {
834
+ return "grayscale";
835
+ }
836
+ if (count === 3) {
837
+ if (transform !== undefined) {
838
+ return transform ? "ycbcr" : "rgb";
839
+ }
840
+ if (this.jfif) {
841
+ return "ycbcr";
842
+ }
843
+ if (this.adobe) {
844
+ return this.adobe.transformCode === 0 ? "rgb" : "ycbcr";
845
+ }
846
+ const [a, b, c] = frame.components;
847
+ // ASCII 'R', 'G', 'B'
848
+ return a.id === 0x52 && b.id === 0x47 && c.id === 0x42 ? "rgb" : "ycbcr";
849
+ }
850
+ if (transform !== undefined) {
851
+ return transform ? "ycck" : "cmyk";
852
+ }
853
+ return this.adobe && this.adobe.transformCode !== 0 ? "ycck" : "cmyk";
854
+ }
855
+ /** Converts the decoded image to RGBA (`channels` 4) or RGB. */
856
+ getPixels(output, channels) {
857
+ const frame = this.frame;
858
+ const components = frame.components.map((c) => ({
859
+ plane: c.plane,
860
+ stride: c.blocksPerLine * 8,
861
+ width: c.width,
862
+ height: c.height,
863
+ h: c.h,
864
+ v: c.v,
865
+ }));
866
+ convertToRgb(components, this.colorSpace, frame.width, frame.height, frame.precision, channels, output);
867
+ }
868
+ }
869
+ //# sourceMappingURL=decoder.js.map