rapier-jxl 1.1.21 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/jpeg.mjs CHANGED
@@ -1,382 +1,39 @@
1
- // Rapier's JPEG XL encoder: reading a JPEG's coefficients. MIT (LICENSE).
2
- // A JPEG is not decoded to pixels here: its quantised DCT coefficients are recovered from the Huffman-coded scans
3
- // (baseline, extended sequential and progressive, 8-bit, grey or three components) so they can be carried into a
4
- // JPEG XL frame as they are. Anything else (arithmetic coding, 12-bit, lossless, hierarchical, four components, a
5
- // height left to a DNL marker, a colour profile other than sRGB) is refused with JXL_JPEG and the picture takes the
6
- // ordinary path instead. So is a JPEG cut short, a scan with bytes missing or left over, a restart marker out of
7
- // order, or a progressive file whose scans do not finish every coefficient: nothing here invents pixels a file lost.
8
- // The frame's dimensions are admitted against LIMITS before a coefficient plane is allocated, so a header naming a
9
- // picture the module would never encode costs nothing.
10
- import {LIMITS} from './bits.mjs';
11
-
12
- export const ZIGZAG = [0, 1, 8, 16, 9, 2, 3, 10, 17, 24, 32, 25, 18, 11, 4, 5, 12, 19, 26, 33, 40, 48, 41, 34, 27, 20, 13, 6, 7, 14, 21, 28,
13
- 35, 42, 49, 56, 57, 50, 43, 36, 29, 22, 15, 23, 30, 37, 44, 51, 58, 59, 52, 45, 38, 31, 39, 46, 53, 60, 61, 54, 47, 55, 62, 63];
14
-
15
- export function jpegError(message, code = 'JXL_JPEG') { return Object.assign(new Error('JPEG: ' + message), {code}); }
16
-
17
- // A 16-bit lookup: entry = (code length << 8) | symbol, 0 for no code.
18
- function buildHuffman(counts, symbols) {
19
- const lookup = new Uint16Array(65536);
20
- let code = 0, k = 0;
21
- for (let length = 1; length <= 16; length++) {
22
- for (let i = 0; i < counts[length - 1]; i++) {
23
- const symbol = symbols[k++], start = code << (16 - length), n = 1 << (16 - length);
24
- // An all-ones code would turn the required scan padding into a symbol.
25
- if (start + n >= 65536) throw jpegError('bad Huffman table');
26
- lookup.fill((length << 8) | symbol, start, start + n);
27
- code++;
28
- }
29
- code <<= 1;
30
- }
31
- return lookup;
32
- }
33
-
34
- // The ICC profile a JPEG carries in its APP2 segments says sRGB (or the grey of the same curve), or the picture is
35
- // refused: the frame declares sRGB, and a profile this module does not carry must not change what the colours mean.
36
- function profileIsSRGB(chunks) {
37
- const parts = [];
38
- for (let i = 1; i <= chunks.count; i++) { if (!chunks.parts[i]) throw jpegError('a colour profile cut short'); parts.push(chunks.parts[i]); }
39
- const size = parts.reduce((n, p) => n + p.length, 0), profile = new Uint8Array(size);
40
- for (let i = 0, at = 0; i < parts.length; at += parts[i].length, i++) profile.set(parts[i], at);
41
- const u32 = at => at + 4 <= size ? ((profile[at] << 24) | (profile[at + 1] << 16) | (profile[at + 2] << 8) | profile[at + 3]) >>> 0 : 0;
42
- const sig = at => at + 4 <= size ? String.fromCharCode(profile[at], profile[at + 1], profile[at + 2], profile[at + 3]) : '';
43
- const tags = u32(128);
44
- if (size < 132 || 132 + tags * 12 > size) return false;
45
- for (let i = 0; i < tags; i++) {
46
- const at = 132 + i * 12;
47
- if (sig(at) !== 'desc') continue;
48
- const offset = u32(at + 4), length = u32(at + 8);
49
- if (offset + length > size || length < 16) return false;
50
- let text = '';
51
- if (sig(offset) === 'desc') { const n = Math.min(u32(offset + 8), length - 12); for (let j = 0; j < n; j++) text += String.fromCharCode(profile[offset + 12 + j]); }
52
- else if (sig(offset) === 'mluc') {
53
- if (!u32(offset + 8) || length < 28) return false;
54
- const n = u32(offset + 20), start = offset + u32(offset + 24);
55
- if (start + n > size) return false;
56
- for (let j = 0; j + 1 < n; j += 2) text += String.fromCharCode((profile[start + j] << 8) | profile[start + j + 1]);
57
- } else return false;
58
- return /sRGB|sGray|IEC ?61966/i.test(text);
59
- }
60
- return false;
61
- }
62
-
63
- export function parseJPEG(bytes) {
64
- if (!(bytes.length > 4) || bytes[0] !== 0xFF || bytes[1] !== 0xD8) throw jpegError('not a JPEG');
65
- const quant = [], huffman = [[], []], badDC = new Set(), icc = {count: 0, parts: []};
66
- let frame = null, restartInterval = 0, adobeTransform = -1, jfif = false, orientation = 1, pos = 2;
67
- const u16 = at => (bytes[at] << 8) | bytes[at + 1];
68
- const signatureAt = (at, signature) => {
69
- for (let i = 0; i < signature.length; i++) if (bytes[at + i] !== signature.charCodeAt(i)) return false;
70
- return true;
71
- };
72
- for (;;) {
73
- if (pos >= bytes.length) { if (frame && frame.scans) break; throw jpegError('truncated'); }
74
- if (bytes[pos] !== 0xFF) throw jpegError('marker expected');
75
- while (bytes[pos] === 0xFF) pos++;
76
- const marker = bytes[pos++];
77
- if (marker === 0xD9) break;
78
- if (marker === 0xD8) throw jpegError('a second start');
79
- if (marker >= 0xD0 && marker <= 0xD7) throw jpegError('a restart marker outside a scan');
80
- if (marker === 0x01) continue;
81
- if (pos + 2 > bytes.length) throw jpegError('truncated');
82
- const length = u16(pos), segment = pos + 2, end = pos + length;
83
- if (length < 2 || end > bytes.length) throw jpegError('bad segment');
84
- pos = end;
85
- if (marker === 0xDB) {
86
- for (let at = segment; at < end;) {
87
- const pq = bytes[at] >> 4, tq = bytes[at] & 15;
88
- if (pq > 1 || tq > 3 || at + 1 + (pq ? 128 : 64) > end) throw jpegError('bad quantisation table');
89
- at++;
90
- const table = new Int32Array(64);
91
- for (let k = 0; k < 64; k++) { table[ZIGZAG[k]] = pq ? u16(at) : bytes[at]; at += pq ? 2 : 1; if (!table[ZIGZAG[k]]) throw jpegError('a zero quantisation step'); }
92
- if (frame?.progressive && frame.components.some(c => c.tq === tq && c.quant && c.coverage.some(v => v !== 0) && c.quant.some((v, k) => v !== table[k]))) throw jpegError('a quantisation table changed between progressive scans');
93
- quant[tq] = table;
94
- }
95
- } else if (marker === 0xC4) {
96
- for (let at = segment; at < end;) {
97
- const tc = bytes[at] >> 4, th = bytes[at] & 15;
98
- if (tc > 1 || th > 3 || at + 17 > end) throw jpegError('bad Huffman table');
99
- at++;
100
- const counts = bytes.subarray(at, at + 16);
101
- let total = 0;
102
- for (const c of counts) total += c;
103
- if (total > 256 || at + 16 + total > end) throw jpegError('bad Huffman table');
104
- const symbols = bytes.subarray(at + 16, at + 16 + total);
105
- huffman[tc][th] = buildHuffman(counts, symbols);
106
- // libjpeg refuses a DC table naming a symbol above 15 when a scan first reads DC through it, used or not.
107
- if (tc === 0) { if (symbols.some(s => s > 15)) badDC.add(th); else badDC.delete(th); }
108
- at += 16 + total;
109
- }
110
- } else if (marker === 0xC0 || marker === 0xC1 || marker === 0xC2) {
111
- if (frame) throw jpegError('two frames');
112
- if (end - segment < 6) throw jpegError('bad frame header');
113
- if (bytes[segment] !== 8) throw jpegError('only 8-bit samples');
114
- const height = u16(segment + 1), width = u16(segment + 3), count = bytes[segment + 5];
115
- if (!width || !height) throw jpegError('a height left to a DNL marker');
116
- if (count !== 1 && count !== 3) throw jpegError('only grey or three components');
117
- if (end - segment < 6 + count * 3) throw jpegError('bad frame header');
118
- // Admitted before a plane is allocated: the limits are the module's, the same the checked API keeps.
119
- if (width > LIMITS.edge || height > LIMITS.edge) throw jpegError('a picture past ' + LIMITS.edge + ' pixels on a side', 'JXL_DIMENSIONS');
120
- if (width * height > LIMITS.pixels) throw jpegError('a picture past ' + LIMITS.pixels + ' pixels', 'JXL_DIMENSIONS');
121
- const components = [];
122
- let blocksPerMcu = 0;
123
- for (let i = 0, at = segment + 6; i < count; i++, at += 3) {
124
- const h = bytes[at + 1] >> 4, v = bytes[at + 1] & 15, tq = bytes[at + 2];
125
- if (h < 1 || h > 4 || v < 1 || v > 4) throw jpegError('bad sampling');
126
- if (tq > 3) throw jpegError('bad quantisation table');
127
- if (components.some(c => c.id === bytes[at])) throw jpegError('two components with one id');
128
- blocksPerMcu += h * v;
129
- components.push({id: bytes[at], h, v, tq, pred: 0, coverage: new Int8Array(64).fill(-1)});
130
- }
131
- if (blocksPerMcu > 10) throw jpegError('bad sampling');
132
- const hmax = Math.max(...components.map(c => c.h)), vmax = Math.max(...components.map(c => c.v));
133
- const mcusX = Math.ceil(width / (8 * hmax)), mcusY = Math.ceil(height / (8 * vmax));
134
- for (const c of components) {
135
- c.blocksW = Math.ceil(Math.ceil(width * c.h / hmax) / 8); c.blocksH = Math.ceil(Math.ceil(height * c.v / vmax) / 8);
136
- c.stride = mcusX * c.h; c.rows = mcusY * c.v;
137
- c.coeffs = new Int16Array(c.stride * c.rows * 64);
138
- }
139
- frame = {progressive: marker === 0xC2, width, height, components, hmax, vmax, mcusX, mcusY, scans: 0};
140
- } else if (marker === 0xC3 || (marker >= 0xC5 && marker <= 0xC7) || (marker >= 0xC9 && marker <= 0xCB) || (marker >= 0xCD && marker <= 0xCF)) {
141
- throw jpegError('lossless, hierarchical or arithmetic coding');
142
- } else if (marker === 0xDD) { if (length < 4) throw jpegError('bad segment'); restartInterval = u16(segment); }
143
- else if (marker === 0xDC) throw jpegError('a DNL marker');
144
- else if (marker === 0xDA) {
145
- if (!frame) throw jpegError('a scan before the frame');
146
- const n = bytes[segment], scan = [];
147
- if (n < 1 || n > 4 || segment + 1 + n * 2 + 3 > end) throw jpegError('bad scan header');
148
- let at = segment + 1;
149
- for (let i = 0; i < n; i++, at += 2) {
150
- const component = frame.components.find(c => c.id === bytes[at]);
151
- if (!component) throw jpegError('a scan of an unknown component');
152
- if (scan.some(s => s.component === component)) throw jpegError('a component twice in one scan');
153
- // A table may be reused for another component after this one's scans. Keep the table that actually
154
- // decoded each component, not whatever happens to occupy its slot at the end of the file.
155
- if (!component.quant) component.quant = quant[component.tq];
156
- if (!component.quant) throw jpegError('a scan without its quantisation table');
157
- scan.push({component, dc: huffman[0][bytes[at + 1] >> 4], ac: huffman[1][bytes[at + 1] & 15], dcSlot: bytes[at + 1] >> 4});
158
- }
159
- const ss = bytes[at], se = bytes[at + 1], ah = bytes[at + 2] >> 4, al = bytes[at + 2] & 15;
160
- if ((!frame.progressive || (ss === 0 && ah === 0)) && scan.some(s => badDC.has(s.dcSlot))) throw jpegError('bad Huffman table');
161
- pos = decodeScan(bytes, end, frame, scan, ss, se, ah, al, restartInterval);
162
- frame.scans++;
163
- } else if (marker === 0xE0) {
164
- if (signatureAt(segment, 'JFIF')) jfif = true;
165
- } else if (marker === 0xE1) {
166
- if (orientation === 1 && signatureAt(segment, 'Exif')) orientation = exifOrientation(bytes, segment + 6, end);
167
- } else if (marker === 0xE2) {
168
- if (length >= 16 && signatureAt(segment, 'ICC_PROFILE\0')) {
169
- const seq = bytes[segment + 12], count = bytes[segment + 13];
170
- if (!seq || !count || seq > count || (icc.count && icc.count !== count) || icc.parts[seq]) throw jpegError('a colour profile cut short');
171
- icc.count = count; icc.parts[seq] = bytes.subarray(segment + 14, end);
172
- }
173
- } else if (marker === 0xEE) {
174
- if (length >= 14 && signatureAt(segment, 'Adobe')) adobeTransform = bytes[segment + 11];
175
- }
176
- }
177
- if (!frame || !frame.scans) throw jpegError('no picture');
178
- for (const c of frame.components) {
179
- for (let k = 0; k < 64; k++) if (c.coverage[k] !== 0) throw jpegError(frame.progressive ? 'a progressive JPEG whose scans do not finish every coefficient' : 'a component without its scan');
180
- }
181
- if (icc.count && !profileIsSRGB(icc)) throw jpegError('a colour profile other than sRGB (decode the picture and encode its pixels)');
182
- // Colour as libjxl reads it: JFIF means YCbCr; else an Adobe marker decides; else component ids spelling RGB.
183
- let rgb = false;
184
- if (frame.components.length === 3 && !jfif) {
185
- if (adobeTransform >= 0) rgb = adobeTransform === 0;
186
- else rgb = frame.components[0].id === 0x52 && frame.components[1].id === 0x47 && frame.components[2].id === 0x42;
187
- }
188
- return {width: frame.width, height: frame.height, components: frame.components, progressive: frame.progressive, ycbcr: !rgb, orientation};
189
- }
190
-
191
- // The Exif orientation tag (0x0112) of the first image directory, 1 when absent or unreadable.
192
- function exifOrientation(bytes, start, end) {
193
- const big = bytes[start] === 0x4D && bytes[start + 1] === 0x4D;
194
- if (!big && !(bytes[start] === 0x49 && bytes[start + 1] === 0x49)) return 1;
195
- const u16 = at => at + 2 > end ? 0 : big ? (bytes[at] << 8) | bytes[at + 1] : bytes[at] | (bytes[at + 1] << 8);
196
- const u32 = at => at + 4 > end ? 0 : big ? ((bytes[at] << 24) | (bytes[at + 1] << 16) | (bytes[at + 2] << 8) | bytes[at + 3]) >>> 0 : (bytes[at] | (bytes[at + 1] << 8) | (bytes[at + 2] << 16) | (bytes[at + 3] << 24)) >>> 0;
197
- if (u16(start + 2) !== 42) return 1;
198
- const ifd = start + u32(start + 4), entries = u16(ifd);
199
- for (let i = 0, at = ifd + 2; i < entries && at + 12 <= end; i++, at += 12) {
200
- if (u16(at) !== 0x0112) continue;
201
- const value = u16(at + 8);
202
- return value >= 1 && value <= 8 ? value : 1;
203
- }
204
- return 1;
1
+ // SPDX-License-Identifier: MIT
2
+ // Rapier JXL's JPEG door: a JPEG carried as its coefficients into JPEG XL, its quantised DCT coefficients,
3
+ // quantisation tables, colour and subsampling kept, only the entropy coding changed, so the picture decodes to the
4
+ // JPEG's own pixels in fewer bytes. Baseline, extended sequential and progressive scans, with restarts; 8-bit; grey,
5
+ // YCbCr or RGB; an Exif orientation kept; a profile that is sRGB or Display P3 by what it does declared in the header.
6
+ // Not carried: the JPEG reconstruction data (the JPEG file itself cannot be rebuilt from the stream), the ICC bytes,
7
+ // Exif beyond the orientation, XMP. A JPEG this path does not take (arithmetic coding, 12-bit, lossless, CMYK, a DNL
8
+ // height, another colour profile, a file cut short) is refused as JXL_JPEG; decode it and encode its pixels instead.
9
+ import {parseJPEG} from './jfif.mjs';
10
+ import {varDCTSteps} from './vardct.mjs';
11
+ import {JPEG_LIMITS, complete} from './bits.mjs';
12
+ import {fault, admitSize, job} from './admit.mjs';
13
+
14
+ // This door's limits (bits.mjs): 64 million pixels, its memory 6.4 bytes a pixel at 4:4:4 and 3.3 at 4:2:0 besides the
15
+ // JPEG at that size, so a phone's 24 and 48 megapixel JPEGs are carried.
16
+ export {JPEG_LIMITS as LIMITS};
17
+
18
+ export function transcode(jpeg) {
19
+ const it = transcodeSteps(jpeg);
20
+ complete(it);
21
+ return {bytes: it.bytes, width: it.width, height: it.height, orientation: it.orientation};
205
22
  }
206
23
 
207
- // What a scan may be, and what it leaves coded: sequential scans code a component whole at once; progressive scans
208
- // code the DC first, then AC bands, each bit plane once, from the top down. `coverage[k]` is the lowest bit plane
209
- // coefficient k has been coded to (-1 never), and the picture is complete only when every one reaches 0.
210
- function admitScan(frame, scan, ss, se, ah, al) {
211
- const progressive = frame.progressive;
212
- if (!progressive) {
213
- if (ss !== 0 || se !== 63 || ah !== 0 || al !== 0) throw jpegError('a bad spectral selection');
214
- for (const s of scan) { if (s.component.coverage.some(v => v !== -1)) throw jpegError('a component coded twice'); s.component.coverage.fill(0); }
215
- return;
216
- }
217
- if (al > 13 || (ah && ah !== al + 1)) throw jpegError('a bad successive approximation');
218
- if (ss === 0) {
219
- if (se !== 0) throw jpegError('a bad spectral selection');
220
- for (const {component} of scan) {
221
- if (component.coverage[0] !== (ah ? ah : -1)) throw jpegError(ah ? 'a refinement scan out of order' : 'a DC scan twice');
222
- component.coverage[0] = al;
223
- }
224
- return;
225
- }
226
- if (scan.length !== 1) throw jpegError('an interleaved AC scan');
227
- if (se > 63 || ss > se) throw jpegError('a bad spectral selection');
228
- const {coverage} = scan[0].component;
229
- if (coverage[0] === -1) throw jpegError('an AC scan before the DC scan');
230
- for (let k = ss; k <= se; k++) {
231
- if (coverage[k] !== (ah ? ah : -1)) throw jpegError(ah ? 'a refinement scan out of order' : 'a band coded twice');
232
- coverage[k] = al;
233
- }
24
+ // The same work as a job (admit.mjs): the scans read in the first step, which also sets the job's width, height and
25
+ // orientation (the picture as shown), then the VarDCT writer's steps.
26
+ export function transcodeSteps(jpeg) {
27
+ if (!(jpeg instanceof Uint8Array) || !jpeg.length) throw fault('JXL_INPUT', 'A JPEG is a non-empty Uint8Array.');
28
+ if (jpeg.length > JPEG_LIMITS.bytes) throw fault('JXL_SIZE', 'A JPEG is at most 16 MiB.');
29
+ const it = job(carry(jpeg, shown => Object.assign(it, shown)));
30
+ return it;
234
31
  }
235
32
 
236
- function decodeScan(bytes, start, frame, scan, ss, se, ah, al, restartInterval) {
237
- admitScan(frame, scan, ss, se, ah, al);
238
- // `pad` counts the bits in `buffer` that are not the file's: zero bytes fed once a marker or the end is reached, so
239
- // the lookahead always holds 24 bits. A code or a value that would take them is a scan cut short.
240
- let pos = start, buffer = 0, count = 0, pad = 0, marker = false;
241
- const fill = () => {
242
- while (count <= 24) {
243
- let byte = 0;
244
- if (marker || pos >= bytes.length) { marker = true; pad += 8; }
245
- else {
246
- byte = bytes[pos];
247
- if (byte === 0xFF) {
248
- const next = bytes[pos + 1];
249
- if (next === 0) pos += 2;
250
- else if (next === 0xFF) { pos++; continue; }
251
- else { marker = true; byte = 0; pad += 8; }
252
- } else pos++;
253
- }
254
- buffer = ((buffer << 8) | byte) >>> 0; count += 8;
255
- }
256
- };
257
- const short = () => jpegError('a scan cut short');
258
- const receive = n => { if (!n) return 0; fill(); if (n > count - pad) throw short(); const value = (buffer >>> (count - n)) & ((1 << n) - 1); count -= n; return value; };
259
- const extend = (value, n) => value < (1 << (n - 1)) ? value - (1 << n) + 1 : value;
260
- const decode = table => {
261
- if (!table) throw jpegError('a scan without its Huffman table');
262
- fill();
263
- const entry = table[(buffer >>> (count - 16)) & 0xFFFF];
264
- if (!entry) throw jpegError('bad Huffman code');
265
- if ((entry >> 8) > count - pad) throw short();
266
- count -= entry >> 8;
267
- return entry & 255;
268
- };
269
- // The bytes of an interval are consumed whole but for the last one's padding bits; then its marker, in order.
270
- const atMarker = () => {
271
- const remaining = count - pad;
272
- if (remaining >= 8) throw jpegError('bytes left over in a scan');
273
- if (eobrun) throw jpegError('an end-of-band run past its interval');
274
- if (remaining && ((buffer >>> pad) & ((1 << remaining) - 1)) !== (1 << remaining) - 1) throw jpegError('bad scan padding');
275
- while (pos + 1 < bytes.length && bytes[pos] === 0xFF && bytes[pos + 1] === 0xFF) pos++;
276
- };
277
- const restart = index => {
278
- atMarker();
279
- if (!(bytes[pos] === 0xFF && bytes[pos + 1] === 0xD0 + (index & 7))) throw jpegError('a restart marker missing or out of order');
280
- pos += 2; buffer = 0; count = 0; pad = 0; marker = false;
281
- for (const s of scan) s.component.pred = 0;
282
- eobrun = 0;
283
- };
284
- const dcValue = (s, t) => {
285
- if (t > 11) throw jpegError('a DC value out of range');
286
- const diff = t ? extend(receive(t), t) : 0;
287
- s.component.pred += diff;
288
- if (s.component.pred > 2047 || s.component.pred < -2048) throw jpegError('a DC value out of range');
289
- return s.component.pred;
290
- };
291
- const acValue = (size, shift) => {
292
- if (size > 10) throw jpegError('an AC value out of range');
293
- const value = extend(receive(size), size) * (1 << shift);
294
- if (value > 1023 || value < -1023) throw jpegError('an AC value out of range');
295
- return value;
296
- };
297
- let eobrun = 0;
298
- const single = scan.length === 1, progressive = frame.progressive;
299
- const baseline = (s, coeffs, at) => {
300
- coeffs[at] = dcValue(s, decode(s.dc));
301
- acFirst(s, coeffs, at);
302
- };
303
- const dcFirst = (s, coeffs, at) => {
304
- const value = dcValue(s, decode(s.dc)) * (1 << al);
305
- if (value > 2047 || value < -2048) throw jpegError('a DC value out of range');
306
- coeffs[at] = value;
307
- };
308
- const dcRefine = (s, coeffs, at) => { if (receive(1)) coeffs[at] |= 1 << al; };
309
- const pastBand = () => jpegError('coefficients past the ' + (progressive ? 'band' : 'block'));
310
- // Sequential scans use this same first AC pass after their DC: admission fixes ss=0, se=63, al=0. Only a
311
- // progressive scan may carry an end-of-band run across blocks; a sequential nonzero run still refuses here.
312
- const acFirst = (s, coeffs, at) => {
313
- if (eobrun > 0) { eobrun--; return; }
314
- for (let k = ss || 1; k <= se;) {
315
- const rs = decode(s.ac), r = rs >> 4, size = rs & 15;
316
- if (!size) {
317
- if (r < 15) {
318
- if (r && !progressive) throw jpegError('an end-of-band run in a sequential scan');
319
- eobrun = (1 << r) - 1 + (r ? receive(r) : 0); break;
320
- }
321
- k += 16; if (k > se + 1) throw pastBand(); continue;
322
- }
323
- k += r;
324
- if (k > se) throw pastBand();
325
- coeffs[at + ZIGZAG[k]] = acValue(size, al);
326
- k++;
327
- }
328
- };
329
- const acRefine = (s, coeffs, at) => {
330
- const p1 = 1 << al, m1 = -1 << al;
331
- let k = ss;
332
- if (eobrun <= 0) {
333
- for (; k <= se; k++) {
334
- const rs = decode(s.ac);
335
- let r = rs >> 4, value = 0;
336
- const size = rs & 15;
337
- if (size) { if (size !== 1) throw jpegError('a bad refinement code'); value = receive(1) ? p1 : m1; }
338
- else if (r !== 15) { eobrun = 1 << r; if (r) eobrun += receive(r); break; }
339
- for (; k <= se; k++) {
340
- const z = at + ZIGZAG[k];
341
- if (coeffs[z] !== 0) { if (receive(1) && (coeffs[z] & p1) === 0) coeffs[z] += coeffs[z] >= 0 ? p1 : m1; }
342
- else if (--r < 0) break;
343
- }
344
- if (r >= 0 || (value && k > se)) throw jpegError('coefficients past the band');
345
- if (value) coeffs[at + ZIGZAG[k]] = value;
346
- }
347
- }
348
- if (eobrun > 0) {
349
- for (; k <= se; k++) {
350
- const z = at + ZIGZAG[k];
351
- if (coeffs[z] !== 0 && receive(1) && (coeffs[z] & p1) === 0) coeffs[z] += coeffs[z] >= 0 ? p1 : m1;
352
- }
353
- eobrun--;
354
- }
355
- };
356
- const block = !progressive ? baseline : ss === 0 ? (ah === 0 ? dcFirst : dcRefine) : (ah === 0 ? acFirst : acRefine);
357
- for (const s of scan) s.component.pred = 0;
358
- const first = scan[0].component;
359
- const total = single ? first.blocksW * first.blocksH : frame.mcusX * frame.mcusY;
360
- for (let unit = 0; unit < total; unit++) {
361
- if (restartInterval && unit > 0 && unit % restartInterval === 0) restart(unit / restartInterval - 1);
362
- if (single) {
363
- const by = (unit / first.blocksW) | 0, bx = unit - by * first.blocksW;
364
- block(scan[0], first.coeffs, (by * first.stride + bx) * 64);
365
- } else {
366
- const my = (unit / frame.mcusX) | 0, mx = unit - my * frame.mcusX;
367
- for (const s of scan) {
368
- const c = s.component;
369
- for (let v = 0; v < c.v; v++) for (let h = 0; h < c.h; h++) block(s, c.coeffs, ((my * c.v + v) * c.stride + mx * c.h + h) * 64);
370
- }
371
- }
372
- }
373
- // The scan ends at a marker or EOF. A final complete interval may carry its next restart marker, once.
374
- atMarker();
375
- if (bytes[pos] === 0xFF && bytes[pos + 1] >= 0xD0 && bytes[pos + 1] <= 0xD7) {
376
- if (!restartInterval || total % restartInterval || bytes[pos + 1] !== 0xD0 + ((total / restartInterval - 1) & 7)) throw jpegError('a restart marker out of order');
377
- pos += 2;
378
- while (pos + 1 < bytes.length && bytes[pos] === 0xFF && bytes[pos + 1] === 0xFF) pos++;
379
- }
380
- if (pos < bytes.length && !(bytes[pos] === 0xFF && pos + 1 < bytes.length && bytes[pos + 1] !== 0 && bytes[pos + 1] !== 0xFF)) throw jpegError('bytes left over after a scan');
381
- return pos;
33
+ function* carry(jpeg, shown) {
34
+ const parsed = parseJPEG(jpeg);
35
+ admitSize(parsed.width, parsed.height, JPEG_LIMITS);
36
+ const swapped = parsed.orientation >= 5;
37
+ shown({width: swapped ? parsed.height : parsed.width, height: swapped ? parsed.width : parsed.height, orientation: parsed.orientation});
38
+ return yield* varDCTSteps(parsed);
382
39
  }
package/lossless.mjs CHANGED
@@ -3,7 +3,7 @@
3
3
  // alpha is dropped and a grey picture keeps one channel; up to 2048 colours try a palette against direct encoded
4
4
  // cost. YCoCg decorrelates colour; samples choose gradient/average prediction; each channel takes one prefix code, zero runs
5
5
  // as LZ77 copies; groups of 256x256 pixels, each an independent section.
6
- import {BitWriter} from './bits.mjs';
6
+ import {BitWriter, complete, part} from './bits.mjs';
7
7
  import {writeImageHeader, writeModularFrameHeader, groupLayout, assembleCodestream, GROUP_DIM} from './frame.mjs';
8
8
  import {buildCode, writePrefixCode} from './prefix.mjs';
9
9
  import {AVERAGE_PREDICTOR, GRADIENT_PREDICTOR, ALPHABET, leaf, channelTree, writeTree, writeModularHeader, writeChannelHistograms, codeChannel} from './modular.mjs';
@@ -33,7 +33,7 @@ export function inspectPixels(rgba, width, height, {palette: wantPalette = true}
33
33
  }
34
34
  if (wantPalette && seen.size < MAX_PALETTE) {
35
35
  const entries = [...seen.keys()];
36
- const byte = (k, c) => Math.floor(k / 256 ** c) % 256;
36
+ const byte = (k, c) => (k >>> 8 * c) & 255;
37
37
  const weight = k => (0.299 * byte(k, 0) + 0.587 * byte(k, 1) + 0.114 * byte(k, 2) + 0.01) * (channels === 4 ? byte(k, 3) : 1);
38
38
  entries.sort((a, b) => weight(a) - weight(b));
39
39
  const index = new Map([[0, 0]]);
@@ -43,13 +43,17 @@ export function inspectPixels(rgba, width, height, {palette: wantPalette = true}
43
43
  return {colour, alpha, channels, palette};
44
44
  }
45
45
 
46
- export function encodeLossless(rgba, width, height, {shape = inspectPixels(rgba, width, height)} = {}) {
46
+ export function encodeLossless(rgba, width, height, options) { return complete(losslessSteps(rgba, width, height, options)); }
47
+
48
+ // The same, a group of one pass per step.
49
+ export function* losslessSteps(rgba, width, height, {shape = inspectPixels(rgba, width, height), colorSpace} = {}) {
47
50
  // The complete stream cost includes the palette, tree, histograms and group headers. A candidate that reaches
48
51
  // the stream limit must not hide a smaller valid representation of the same pixels.
49
52
  let best, oversized;
50
- for (const candidate of shape.palette ? [shape, {...shape, palette: null}] : [shape]) {
53
+ const candidates = shape.palette ? [shape, {...shape, palette: null}] : [shape];
54
+ for (let i = 0; i < candidates.length; i++) {
51
55
  try {
52
- const bytes = encodeLosslessPlan(rgba, width, height, candidate);
56
+ const bytes = yield* part(planSteps(rgba, width, height, candidates[i], colorSpace), i, candidates.length);
53
57
  if (!best || bytes.length < best.length) best = bytes;
54
58
  } catch (error) { if (error.code !== 'JXL_SIZE') throw error; oversized = error; }
55
59
  }
@@ -57,7 +61,7 @@ export function encodeLossless(rgba, width, height, {shape = inspectPixels(rgba,
57
61
  return best;
58
62
  }
59
63
 
60
- function encodeLosslessPlan(rgba, width, height, shape) {
64
+ function* planSteps(rgba, width, height, shape, colorSpace) {
61
65
  const {channels, palette} = shape;
62
66
  const layout = groupLayout(width, height);
63
67
  const streamChannels = palette ? 2 : channels; // the palette's meta channel and the index channel
@@ -91,13 +95,14 @@ function encodeLosslessPlan(rgba, width, height, shape) {
91
95
  const pictureLeaf = c => leaves[palette ? (layout.single ? 1 : 0) : c];
92
96
  const pictureChannels = palette ? 1 : channels;
93
97
 
94
- const forGroups = visit => {
95
- for (let gy = 0; gy < layout.groupsY; gy++) for (let gx = 0; gx < layout.groupsX; gx++) {
96
- const x0 = gx * GROUP_DIM, y0 = gy * GROUP_DIM, w = Math.min(GROUP_DIM, width - x0), h = Math.min(GROUP_DIM, height - y0);
97
- fill(x0, y0, w, h);
98
- visit(gy * layout.groupsX + gx, w, h);
99
- }
98
+ // A group's planes filled, then visited; each group of each pass is one step, row by row.
99
+ const groups = layout.groupsX * layout.groupsY, total = 2 * groups;
100
+ const group = (g, visit) => {
101
+ const x0 = g % layout.groupsX * GROUP_DIM, y0 = (g / layout.groupsX | 0) * GROUP_DIM, w = Math.min(GROUP_DIM, width - x0), h = Math.min(GROUP_DIM, height - y0);
102
+ fill(x0, y0, w, h);
103
+ visit(w, h);
100
104
  };
105
+ let done = 0;
101
106
 
102
107
  // Three small spatial samples choose gradient/average per channel. The same token code prices
103
108
  // both the prefix header and raw residual bits. Fixed YCoCg avoids choosing RGB from a sparse corner
@@ -128,11 +133,14 @@ function encodeLosslessPlan(rgba, width, height, shape) {
128
133
  // Pass one: token histograms per leaf.
129
134
  const freqs = leaves.map(() => new Uint32Array(ALPHABET)), freqOf = l => freqs[leaves.indexOf(l)];
130
135
  if (paletteRows) codeChannel(null, freqOf(leaves[0]), paletteRows, palette.colours.length, channels, leaves[0]);
131
- forGroups((g, w, h) => { for (let c = 0; c < pictureChannels; c++) codeChannel(null, freqOf(pictureLeaf(c)), planes[c], w, h, pictureLeaf(c)); });
136
+ for (let g = 0; g < groups; g++) {
137
+ group(g, (w, h) => { for (let c = 0; c < pictureChannels; c++) codeChannel(null, freqOf(pictureLeaf(c)), planes[c], w, h, pictureLeaf(c)); });
138
+ yield ++done / total;
139
+ }
132
140
 
133
141
  // Pass two: the sections.
134
142
  const header = new BitWriter(256);
135
- writeImageHeader(header, width, height, shape.colour, shape.alpha);
143
+ writeImageHeader(header, width, height, shape.colour, shape.alpha, {colorSpace});
136
144
  writeModularFrameHeader(header, {alpha: shape.alpha});
137
145
  const global = new BitWriter(4096);
138
146
  global.write(1, 1); // default DC quantisation
@@ -144,17 +152,21 @@ function encodeLosslessPlan(rgba, width, height, shape) {
144
152
  if (paletteRows) codeChannel(global, codeOf(leaves[0]), paletteRows, palette.colours.length, channels, leaves[0]);
145
153
  const sections = [];
146
154
  if (layout.single) {
147
- forGroups((g, w, h) => { for (let c = 0; c < pictureChannels; c++) codeChannel(global, codeOf(pictureLeaf(c)), planes[c], w, h, pictureLeaf(c)); });
155
+ group(0, (w, h) => { for (let c = 0; c < pictureChannels; c++) codeChannel(global, codeOf(pictureLeaf(c)), planes[c], w, h, pictureLeaf(c)); });
156
+ yield 1;
148
157
  sections.push(global.finish());
149
158
  } else {
150
159
  sections.push(global.finish());
151
160
  for (let i = 0; i < layout.dcGroupsX * layout.dcGroupsY + 1; i++) sections.push(new Uint8Array(0));
152
- forGroups((g, w, h) => {
153
- const section = new BitWriter(w * h * pictureChannels + 64);
154
- writeModularHeader(section, {useGlobalTree: true, transforms: []});
155
- for (let c = 0; c < pictureChannels; c++) codeChannel(section, codeOf(pictureLeaf(c)), planes[c], w, h, pictureLeaf(c));
156
- sections.push(section.finish());
157
- });
161
+ for (let g = 0; g < groups; g++) {
162
+ group(g, (w, h) => {
163
+ const section = new BitWriter(w * h * pictureChannels + 64);
164
+ writeModularHeader(section, {useGlobalTree: true, transforms: []});
165
+ for (let c = 0; c < pictureChannels; c++) codeChannel(section, codeOf(pictureLeaf(c)), planes[c], w, h, pictureLeaf(c));
166
+ sections.push(section.finish());
167
+ });
168
+ yield ++done / total;
169
+ }
158
170
  }
159
171
  return assembleCodestream(header, sections);
160
172
  }