rapier-jxl 1.1.21 → 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.
package/jpeg.mjs CHANGED
@@ -1,382 +1,15 @@
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;
205
- }
206
-
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
- }
234
- }
235
-
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;
382
- }
1
+ // SPDX-License-Identifier: MIT
2
+ // Rapier JXL's JPEG door: a JPEG carried as its quantised DCT coefficients,
3
+ // quantisation tables, colour and subsampling, with only the entropy coding changed.
4
+ // Baseline, extended sequential and progressive scans, restarts; 8-bit grey, YCbCr or RGB;
5
+ // Exif orientation and an admitted sRGB or Display P3 declaration are kept.
6
+ // Not carried: JPEG reconstruction data, ICC bytes, Exif beyond orientation or XMP.
7
+ // Arithmetic, 12-bit, lossless, CMYK, DNL, another colour profile, truncation or a table
8
+ // libjpeg refuses is JXL_JPEG: decode it and encode its pixels instead.
9
+ import {JPEG_LIMITS} from './bits.mjs';
10
+ import {jpegAnswer, jpegJob} from './jpeg-job.mjs';
11
+ import {coefficientEffortSteps} from './coefficient-effort.mjs';
12
+
13
+ export {JPEG_LIMITS as LIMITS};
14
+ export function transcode(jpeg, options) { return jpegAnswer(transcodeSteps(jpeg, options)); }
15
+ export function transcodeSteps(jpeg, options) { return jpegJob(jpeg, options, coefficientEffortSteps); }
package/local.mjs ADDED
@@ -0,0 +1,197 @@
1
+ // SPDX-License-Identifier: MIT
2
+ // Effort-only Modular modelling. Every group owns its tree and histograms; a bounded group of samples is the
3
+ // working set, and the complete candidate competes against every lower rung at the door.
4
+ import {BitWriter, packSigned} from './bits.mjs';
5
+ import {writeImageHeader, writeModularFrameHeader, groupLayout, assembleCodestream, GROUP_DIM} from './frame.mjs';
6
+ import {buildCode, writePrefixCode, countToken, writeHybrid} from './prefix.mjs';
7
+ import {ALPHABET, LZ77, RESIDUAL_CONFIG, leaf, split, channelTree, writeTree, writeModularHeader, writeChannelHistograms} from './modular.mjs';
8
+ import {codeWeighted} from './weighted.mjs';
9
+ import {admitOutputSize} from './admit.mjs';
10
+
11
+ const localRaw = s => Math.max(0, s < 224 ? s - 1 : s - 236);
12
+ const price = freqs => {
13
+ const code = buildCode(freqs), writer = new BitWriter(128);
14
+ writePrefixCode(writer, code);
15
+ let bits = writer.bitLength;
16
+ for (let s = 0; s < freqs.length; s++) if (freqs[s]) bits += freqs[s] * (code.lengths[s] + localRaw(s));
17
+ return bits;
18
+ };
19
+
20
+ // Residuals are exactly the decoder's unsigned values before entropy coding, including RGB under zero alpha.
21
+ function residuals(plane, width, height, predictor, properties) {
22
+ const out = new Uint32Array(width * height);
23
+ if (predictor === 6) { codeWeighted(null, null, plane, width, height, 0, undefined, out, properties); return out; }
24
+ for (let y = 0, i = 0; y < height; y++) for (let x = 0; x < width; x++, i++) {
25
+ const left = x ? plane[i - 1] : y ? plane[i - width] : 0, top = y ? plane[i - width] : left;
26
+ const nw = x && y ? plane[i - width - 1] : left;
27
+ const prediction = predictor === 3 ? ((left + top) / 2) | 0 : Math.max(Math.min(left, top), Math.min(Math.max(left, top), left + top - nw));
28
+ out[i] = packSigned(plane[i] - prediction);
29
+ }
30
+ return out;
31
+ }
32
+
33
+ function tokens(values, contexts, count = 1) {
34
+ const freqs = Array.from({length: count}, () => new Uint32Array(ALPHABET)), pieces = [];
35
+ const emit = (i, value, base = 0) => {
36
+ const context = contexts ? contexts[i] : 0;
37
+ pieces.push(value, base, context); countToken(base ? LZ77.lengthConfig : RESIDUAL_CONFIG, value, freqs[context], base);
38
+ };
39
+ // A zero run can cross a tree leaf or row. Its first literal and copy use their own samples' contexts.
40
+ for (let i = 0; i < values.length;) {
41
+ let run = 1;
42
+ if (!values[i]) while (i + run < values.length && !values[i + run]) run++;
43
+ emit(i, values[i]);
44
+ if (run > LZ77.minLength) {
45
+ emit(i + 1, run - 1 - LZ77.minLength, LZ77.minSymbol);
46
+ } else for (let n = 1; n < run; n++) emit(i + n, 0);
47
+ i += run;
48
+ }
49
+ return {freqs, pieces};
50
+ }
51
+
52
+ function intervalPlan(values, properties, predictor, property, cuts) {
53
+ const contexts = Uint8Array.from(properties, value => {
54
+ let lo = 0, hi = cuts.length;
55
+ while (lo < hi) { const mid = (lo + hi) >> 1; if (value > cuts[mid]) lo = mid + 1; else hi = mid; }
56
+ return lo;
57
+ });
58
+ const coded = tokens(values, contexts, cuts.length + 1), count = coded.freqs.length, filled = coded.freqs.map(freq => freq.some(n => n));
59
+ const costs = new Float64Array(count + 1).fill(Infinity), from = new Uint8Array(count + 1);
60
+ costs[0] = 0;
61
+ for (let end = 1; end <= count; end++) {
62
+ const freq = new Uint32Array(ALPHABET);
63
+ let own = 0;
64
+ for (let start = end - 1; start >= 0; start--) {
65
+ if (filled[start]) { for (let s = 0; s < ALPHABET; s++) freq[s] += coded.freqs[start][s]; own = price(freq); }
66
+ const bits = costs[start] + own + 24;
67
+ if (bits < costs[end]) { costs[end] = bits; from[end] = start; }
68
+ }
69
+ }
70
+ const spans = [];
71
+ for (let end = count; end; end = from[end]) spans.unshift([from[end], end]);
72
+ const leaves = spans.map(() => leaf(predictor)), mapping = new Uint8Array(count);
73
+ const freqs = spans.map(([start, end], index) => {
74
+ const freq = new Uint32Array(ALPHABET);
75
+ for (let k = start; k < end; k++) { mapping[k] = index; for (let s = 0; s < ALPHABET; s++) freq[s] += coded.freqs[k][s]; }
76
+ return freq;
77
+ });
78
+ for (let i = 2; i < coded.pieces.length; i += 3) coded.pieces[i] = mapping[coded.pieces[i]];
79
+ const tree = (lo, hi) => {
80
+ if (lo === hi) return leaves[lo];
81
+ const mid = (lo + hi) >> 1;
82
+ return split(property, cuts[spans[mid][1] - 1], tree(mid + 1, hi), tree(lo, mid));
83
+ };
84
+ return {leaves, tree: tree(0, spans.length - 1), freqs, pieces: coded.pieces};
85
+ }
86
+
87
+ const WEIGHTED_LOCAL_CUTS = [-127, -31, -7, -1, 0, 1, 7, 31, 127];
88
+ const GRADIENT_CUTS = [-191, -127, -63, -31, -7, -1, 0, 7, 31, 63, 127, 191, 255];
89
+ function localProperties(plane, width, height, property) {
90
+ const out = new Int32Array(width * height);
91
+ for (let y = 0, i = 0; y < height; y++) for (let x = 0; x < width; x++, i++) {
92
+ const left = x ? plane[i - 1] : y ? plane[i - width] : 0, top = y ? plane[i - width] : left;
93
+ const nw = x && y ? plane[i - width - 1] : left;
94
+ out[i] = property === 9 ? left + top - nw : left - nw;
95
+ }
96
+ return out;
97
+ }
98
+ function planPrice(plan) {
99
+ const writer = new BitWriter(512);
100
+ const histograms = writeChannelHistograms(writer, writeTree(writer, plan.tree), plan.freqs, l => plan.leaves.indexOf(l));
101
+ let bits = writer.bitLength;
102
+ plan.freqs.forEach((freq, i) => { const {lengths} = histograms[i + 1].code; for (let s = 0; s < freq.length; s++) bits += freq[s] * ((lengths[s] || 0) + localRaw(s)); });
103
+ return bits;
104
+ }
105
+
106
+ function plansOf(planes, width, height, rung) {
107
+ return planes.map(plane => {
108
+ let best;
109
+ for (const predictor of [5, 3, 6]) {
110
+ const properties = predictor === 6 ? new Int32Array(width * height) : null;
111
+ const values = residuals(plane, width, height, predictor, properties), one = leaf(predictor);
112
+ const candidates = [{...tokens(values), leaves: [one], tree: one}];
113
+ if (properties) candidates.push(intervalPlan(values, properties, predictor, 15, WEIGHTED_LOCAL_CUTS));
114
+ // Property 9 is the unclamped gradient; property 10 is W - NW. Signed cuts let the latter separate both
115
+ // tails around a flat neighbourhood without treating a high-magnitude negative edge as a small one.
116
+ if (rung >= 6 && predictor === 5) for (const property of [9, 10]) {
117
+ const local = localProperties(plane, width, height, property), cuts = property === 9 ? GRADIENT_CUTS : WEIGHTED_LOCAL_CUTS;
118
+ candidates.push(intervalPlan(values, local, predictor, property, cuts));
119
+ }
120
+ for (const plan of candidates) { const bits = planPrice(plan); if (!best || bits < best.bits) best = {...plan, bits}; }
121
+ }
122
+ return best;
123
+ });
124
+ }
125
+
126
+ function writeModel(writer, plans) {
127
+ const leaves = plans.flatMap(plan => plan.leaves);
128
+ const histograms = writeChannelHistograms(writer, writeTree(writer, channelTree(plans.map(plan => plan.tree))), plans.flatMap(plan => plan.freqs), l => leaves.indexOf(l));
129
+ return () => {
130
+ for (let c = 0; c < plans.length; c++) {
131
+ const {pieces} = plans[c], codes = plans[c].leaves.map(l => histograms[leaves.indexOf(l) + 1].code);
132
+ for (let i = 0; i < pieces.length; i += 3) {
133
+ const base = pieces[i + 1];
134
+ writeHybrid(writer, codes[pieces[i + 2]], base ? LZ77.lengthConfig : RESIDUAL_CONFIG, pieces[i], base);
135
+ }
136
+ }
137
+ };
138
+ }
139
+
140
+ export function* localSteps(rgba, width, height, shape, colorSpace, rung = 4, usePalette = false) {
141
+ const {channels} = shape, layout = groupLayout(width, height), groups = layout.groupsX * layout.groupsY;
142
+ const palette = usePalette ? shape.palette : null;
143
+ if (usePalette && !palette) return null;
144
+ const planes = Array.from({length: palette ? 1 : channels}, () => new Int16Array(GROUP_DIM * GROUP_DIM));
145
+ const header = new BitWriter(256);
146
+ writeImageHeader(header, width, height, shape.colour, shape.alpha, {colorSpace});
147
+ writeModularFrameHeader(header, {alpha: shape.alpha});
148
+ const transforms = palette ? [{type: 'palette', beginC: 0, numC: channels, nbColors: palette.colours.length}] : channels >= 3 ? [{type: 'rct', beginC: 0, rctType: 6}] : [];
149
+ // The palette's meta channel precedes the picture in the global section; local AC groups contain only indices.
150
+ let palettePlans;
151
+ if (palette) {
152
+ const count = palette.colours.length, values = new Int16Array(count * channels);
153
+ palette.colours.forEach((colour, i) => { for (let c = 0; c < channels; c++) values[c * count + i] = palette.byte(colour, c); });
154
+ palettePlans = plansOf([values], count, channels, rung);
155
+ }
156
+ const global = new BitWriter(4096), sections = [];
157
+ let sectionBytes = 0;
158
+ const appendSection = writer => {
159
+ // Refuse before copying a completed section or retaining later groups of an oversized optional candidate.
160
+ sectionBytes += Math.ceil(writer.bitLength / 8); admitOutputSize(sectionBytes);
161
+ sections.push(writer.finish());
162
+ };
163
+ global.write(1, 1); global.write(1, 1);
164
+ if (!layout.single) {
165
+ let write;
166
+ if (palettePlans) write = writeModel(global, palettePlans);
167
+ else {
168
+ const leaves = planes.map(() => leaf(5));
169
+ writeChannelHistograms(global, writeTree(global, channelTree(leaves)), planes.map(() => new Uint32Array(ALPHABET)), l => leaves.indexOf(l));
170
+ }
171
+ writeModularHeader(global, {transforms});
172
+ if (write) write();
173
+ appendSection(global);
174
+ for (let i = 0; i < layout.dcGroupsX * layout.dcGroupsY + 1; i++) sections.push(new Uint8Array(0));
175
+ }
176
+ for (let g = 0; g < groups; g++) {
177
+ const x0 = g % layout.groupsX * GROUP_DIM, y0 = (g / layout.groupsX | 0) * GROUP_DIM;
178
+ const w = Math.min(GROUP_DIM, width - x0), h = Math.min(GROUP_DIM, height - y0);
179
+ for (let y = 0; y < h; y++) for (let x = 0, at = y * w, i = ((y0 + y) * width + x0) * 4; x < w; x++, at++, i += 4) {
180
+ if (palette) planes[0][at] = palette.index.get(palette.key(i));
181
+ else if (channels >= 3) {
182
+ const co = rgba[i] - rgba[i + 2], tmp = rgba[i + 2] + (co >> 1), cg = rgba[i + 1] - tmp;
183
+ planes[0][at] = tmp + (cg >> 1); planes[1][at] = co; planes[2][at] = cg;
184
+ if (channels === 4) planes[3][at] = rgba[i + 3];
185
+ } else { planes[0][at] = rgba[i]; if (channels === 2) planes[1][at] = rgba[i + 3]; }
186
+ }
187
+ const picture = plansOf(planes, w, h, rung);
188
+ const plans = palette && layout.single ? [...palettePlans, ...picture] : picture;
189
+ const section = layout.single ? global : new BitWriter(w * h * planes.length + 256);
190
+ if (!layout.single) writeModularHeader(section, {useGlobalTree: false});
191
+ const write = writeModel(section, plans);
192
+ if (layout.single) writeModularHeader(section, {transforms});
193
+ write(); appendSection(section);
194
+ if (yield (g + 1) / groups) return null;
195
+ }
196
+ return assembleCodestream(header, sections);
197
+ }