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/AGENTS.md +18 -10
- package/ENCODER-COMPARISON.md +6 -6
- package/README.md +107 -39
- package/admit.mjs +60 -0
- package/ans.mjs +157 -0
- package/bits.mjs +30 -10
- package/coefficient-ans.mjs +26 -0
- package/coefficient-effort.mjs +62 -0
- package/effort-level.mjs +10 -0
- package/effort.d.mts +12 -0
- package/effort.min.mjs +2 -0
- package/effort.mjs +240 -0
- package/entropy.mjs +16 -1
- package/frame.mjs +20 -10
- package/index.d.mts +13 -17
- package/index.mjs +30 -83
- package/jfif.mjs +418 -0
- package/jpeg-ans.d.mts +3 -0
- package/jpeg-ans.min.mjs +2 -0
- package/jpeg-ans.mjs +9 -0
- package/jpeg-job.mjs +29 -0
- package/jpeg.d.mts +18 -2
- package/jpeg.min.mjs +2 -2
- package/jpeg.mjs +15 -382
- package/local.mjs +197 -0
- package/lossless.mjs +33 -21
- package/lossy.mjs +41 -16
- package/package.json +17 -8
- package/photo-ans.d.mts +3 -0
- package/photo-ans.min.mjs +2 -0
- package/photo-ans.mjs +9 -0
- package/photo-dct.mjs +83 -0
- package/photo-job.mjs +27 -0
- package/photo-quant.mjs +150 -0
- package/photo.d.mts +11 -3
- package/photo.min.mjs +2 -2
- package/photo.mjs +10 -73
- package/public/examples/browser.html +4 -2
- package/public/examples/worker.mjs +34 -9
- package/rapier-jxl.min.mjs +2 -2
- package/sizes.json +286 -76
- package/vardct.mjs +71 -14
- package/weighted.mjs +89 -0
- package/writer.mjs +17 -0
- package/lossless.d.mts +0 -3
- package/lossless.min.mjs +0 -2
package/index.mjs
CHANGED
|
@@ -1,94 +1,41 @@
|
|
|
1
1
|
// SPDX-License-Identifier: MIT
|
|
2
|
-
// Rapier JXL: a JPEG XL encoder in pure JavaScript, the one Rapier's page carries. This is the
|
|
3
|
-
//
|
|
4
|
-
//
|
|
5
|
-
|
|
6
|
-
import {
|
|
7
|
-
import {
|
|
8
|
-
import {
|
|
9
|
-
import {
|
|
2
|
+
// Rapier JXL: a JPEG XL encoder in pure JavaScript, the one Rapier's page carries. This is the core: pixels in, a bare
|
|
3
|
+
// codestream out, exact or lossy, alpha exact. A JPEG is carried by jpeg.mjs and a photograph written by photo.mjs;
|
|
4
|
+
// a module's author takes the layers from writer.mjs. No WebAssembly, no build step, no dependency, nothing read or
|
|
5
|
+
// fetched at run time.
|
|
6
|
+
import {inspectPixels, losslessSteps} from './lossless.mjs';
|
|
7
|
+
import {lossySteps} from './lossy.mjs';
|
|
8
|
+
import {LIMITS, complete, part} from './bits.mjs';
|
|
9
|
+
import {admitOptions, admitPixels, job} from './admit.mjs';
|
|
10
10
|
|
|
11
11
|
// What one call takes at most (bits.mjs): the 16 MiB codestream, 24 million pixels, 16,384 on a side. Larger asks are
|
|
12
12
|
// refused with a coded error before any work, the way a decoder would refuse them after it.
|
|
13
13
|
export {LIMITS};
|
|
14
14
|
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
function
|
|
22
|
-
admitSize(width, height);
|
|
23
|
-
if (!(data instanceof Uint8Array) && !(data instanceof Uint8ClampedArray)) throw fault('JXL_INPUT', 'Pixels are a Uint8Array or Uint8ClampedArray of RGBA bytes.');
|
|
24
|
-
if (data.length !== width * height * 4) throw fault('JXL_INPUT', 'Pixels are width * height * 4 bytes: straight (not premultiplied) RGBA, row by row.');
|
|
25
|
-
}
|
|
26
|
-
function admitQuality(quality) {
|
|
27
|
-
if (typeof quality !== 'number' || !Number.isFinite(quality) || quality < 1 || quality > 100) throw fault('JXL_INPUT', 'Quality is a number from 1 to 100.');
|
|
28
|
-
}
|
|
29
|
-
function answer(bytes) {
|
|
30
|
-
if (bytes.length > LIMITS.bytes) throw fault('JXL_SIZE', 'The encoded picture exceeds 16 MiB.');
|
|
31
|
-
return bytes;
|
|
32
|
-
}
|
|
33
|
-
function guard(work) {
|
|
34
|
-
try { return work(); }
|
|
35
|
-
catch (error) { if (error instanceof RangeError && !error.code) throw fault('JXL_MEMORY', 'Not enough memory for this picture.'); throw error; }
|
|
36
|
-
}
|
|
15
|
+
// Straight RGBA bytes, row by row, to a codestream. Quality 100 (the default) is exact: an opaque alpha is dropped, a
|
|
16
|
+
// grey picture keeps one channel, up to 2048 colours use a palette when its complete stream is smaller, and direct
|
|
17
|
+
// colour goes through reversible YCoCg with gradient or average prediction chosen by samples. Quality 1 to 99 is lossy
|
|
18
|
+
// modular on libjxl's quality-to-distance curve (not equivalent PSNR), alpha still exact; a picture of few colours is
|
|
19
|
+
// answered exact when that is fewer bytes. The samples are sRGB, or Display P3 with {colorSpace: 'display-p3'}: the
|
|
20
|
+
// header declares the space and the samples are written as they are. The options are read before any work.
|
|
21
|
+
export function encode(data, width, height, options) { return complete(encodeSteps(data, width, height, options)); }
|
|
37
22
|
|
|
38
|
-
//
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
export function encodeLosslessRGBA(data, width, height) {
|
|
23
|
+
// The same work as a job (admit.mjs): the call admitted at once, then a group of one pass per step, the same bytes.
|
|
24
|
+
export function encodeSteps(data, width, height, options) {
|
|
25
|
+
const {quality, colorSpace} = admitOptions(options);
|
|
42
26
|
admitPixels(data, width, height);
|
|
43
|
-
return
|
|
27
|
+
return job(pixelSteps(data, width, height, quality, colorSpace));
|
|
44
28
|
}
|
|
45
29
|
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
// attempt that runs out of memory (its planes and Squeeze copies cost eight bytes a pixel and more) still answers.
|
|
58
|
-
const exact = encodeLossless(data, width, height, {shape});
|
|
59
|
-
let bytes;
|
|
60
|
-
try { bytes = encodeLossy(data, width, height, {quality, shape}); }
|
|
61
|
-
catch (error) { if (!(error instanceof RangeError) || error.code) throw error; bytes = exact; }
|
|
62
|
-
return answer(exact.length <= bytes.length ? exact : bytes);
|
|
63
|
-
});
|
|
30
|
+
function* pixelSteps(data, width, height, quality, colorSpace) {
|
|
31
|
+
const shape = inspectPixels(data, width, height);
|
|
32
|
+
if (quality >= 100) return yield* losslessSteps(data, width, height, {shape, colorSpace});
|
|
33
|
+
if (!shape.palette) return yield* lossySteps(data, width, height, {quality, shape, colorSpace});
|
|
34
|
+
// The exact stream of a few-colour picture is cheap to make (256-pixel sections), so it is made first: a lossy
|
|
35
|
+
// attempt that runs out of memory or stream space still leaves that completed answer.
|
|
36
|
+
const exact = yield* part(losslessSteps(data, width, height, {shape, colorSpace}), 0, 2);
|
|
37
|
+
let bytes;
|
|
38
|
+
try { bytes = yield* part(lossySteps(data, width, height, {quality, shape, colorSpace}), 1, 2); }
|
|
39
|
+
catch (error) { if (error.code !== 'JXL_SIZE' && (!(error instanceof RangeError) || error.code)) throw error; bytes = exact; }
|
|
40
|
+
return exact.length <= bytes.length ? exact : bytes;
|
|
64
41
|
}
|
|
65
|
-
|
|
66
|
-
// One call for both: quality 100 (the default) is exact, anything lower is lossy. The options are read before any
|
|
67
|
-
// work: a quality that is not a number from 1 to 100 is JXL_INPUT, never a silent choice.
|
|
68
|
-
export function encode(data, width, height, options = {}) {
|
|
69
|
-
if (options === null || typeof options !== 'object') throw fault('JXL_INPUT', 'Options are an object: {quality}.');
|
|
70
|
-
const quality = options.quality === undefined ? 100 : options.quality;
|
|
71
|
-
admitQuality(quality);
|
|
72
|
-
return quality >= 100 ? encodeLosslessRGBA(data, width, height) : encodeLossyRGBA(data, width, height, quality);
|
|
73
|
-
}
|
|
74
|
-
|
|
75
|
-
// A JPEG carried as its coefficients into JPEG XL: the quantised DCT coefficients, quantisation tables, colour and
|
|
76
|
-
// subsampling kept, only the entropy coding changed, so the picture decodes to the JPEG's own pixels at about a
|
|
77
|
-
// fifth fewer bytes. Baseline, extended sequential and progressive scans, with restarts; 8-bit; grey, YCbCr or RGB;
|
|
78
|
-
// an Exif orientation kept. Not carried: the JPEG reconstruction data (the JPEG file itself cannot be rebuilt from
|
|
79
|
-
// the stream), ICC, Exif beyond the orientation, XMP. A JPEG this path does not take (arithmetic coding, 12-bit,
|
|
80
|
-
// lossless, CMYK, a DNL height, a colour profile other than sRGB, a file cut short) is refused as JXL_JPEG; decode
|
|
81
|
-
// it and encode its pixels instead.
|
|
82
|
-
export function transcode(jpeg) {
|
|
83
|
-
if (!(jpeg instanceof Uint8Array) || !jpeg.length) throw fault('JXL_INPUT', 'A JPEG is a non-empty Uint8Array.');
|
|
84
|
-
if (jpeg.length > LIMITS.bytes) throw fault('JXL_SIZE', 'A JPEG is at most 16 MiB.');
|
|
85
|
-
return guard(() => {
|
|
86
|
-
const parsed = parseJPEG(jpeg);
|
|
87
|
-
admitSize(parsed.width, parsed.height);
|
|
88
|
-
const bytes = answer(transcodeJPEG(jpeg, parsed));
|
|
89
|
-
const swapped = parsed.orientation >= 5;
|
|
90
|
-
return {bytes, width: swapped ? parsed.height : parsed.width, height: swapped ? parsed.width : parsed.height, orientation: parsed.orientation};
|
|
91
|
-
});
|
|
92
|
-
}
|
|
93
|
-
|
|
94
|
-
export {encodeLossless, encodeLossy, transcodeJPEG, parseJPEG, inspectPixels};
|
package/jfif.mjs
ADDED
|
@@ -0,0 +1,418 @@
|
|
|
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 or Display P3) is refused with JXL_JPEG and the
|
|
6
|
+
// picture takes the ordinary path instead. So is a JPEG cut short, a scan with bytes missing or left over, a restart
|
|
7
|
+
// marker out of order, or a progressive file whose scans do not finish every coefficient: nothing here invents pixels
|
|
8
|
+
// a file lost.
|
|
9
|
+
// The frame's dimensions are admitted against the carrier's limits (JPEG_LIMITS) before a coefficient plane is
|
|
10
|
+
// allocated, so a header naming a picture the module would never carry costs nothing.
|
|
11
|
+
import {JPEG_LIMITS} from './bits.mjs';
|
|
12
|
+
|
|
13
|
+
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,
|
|
14
|
+
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];
|
|
15
|
+
|
|
16
|
+
export function jpegError(message, code = 'JXL_JPEG') { return Object.assign(new Error('JPEG: ' + message), {code}); }
|
|
17
|
+
|
|
18
|
+
// A 16-bit lookup: entry = (code length << 8) | symbol, 0 for no code.
|
|
19
|
+
function buildHuffman(counts, symbols) {
|
|
20
|
+
const lookup = new Uint16Array(65536);
|
|
21
|
+
let code = 0, k = 0;
|
|
22
|
+
for (let length = 1; length <= 16; length++) {
|
|
23
|
+
for (let i = 0; i < counts[length - 1]; i++) {
|
|
24
|
+
const symbol = symbols[k++], start = code << (16 - length), n = 1 << (16 - length);
|
|
25
|
+
// An all-ones code would turn the required scan padding into a symbol.
|
|
26
|
+
if (start + n >= 65536) throw jpegError('bad Huffman table');
|
|
27
|
+
lookup.fill((length << 8) | symbol, start, start + n);
|
|
28
|
+
code++;
|
|
29
|
+
}
|
|
30
|
+
code <<= 1;
|
|
31
|
+
}
|
|
32
|
+
return lookup;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
// The colour space an ICC profile gives a JPEG's samples, read from what the profile does, never from what it says:
|
|
36
|
+
// RGB into the XYZ connection space through three colorants within 0.004 of sRGB's or Display P3's (D50, Bradford) and
|
|
37
|
+
// the sRGB curve on every channel, or grey on the sRGB curve (the same in both spaces). Lookup tables, another gamut or
|
|
38
|
+
// another curve name no space this module declares: null, and the JPEG is refused.
|
|
39
|
+
const SRGB = [0.436, 0.2225, 0.0139, 0.3851, 0.7169, 0.0971, 0.143, 0.0606, 0.7139];
|
|
40
|
+
const P3 = [0.5151, 0.2412, -0.001, 0.292, 0.6922, 0.0419, 0.1571, 0.0666, 0.7841];
|
|
41
|
+
// The sRGB curve at sixteenths, and its parameters (g, a, b, c, d) as the ICC's parametric curve 3 writes them.
|
|
42
|
+
const CURVE = [0, 0.00516, 0.01435, 0.02934, 0.05088, 0.07958, 0.11602, 0.16068, 0.21404, 0.27652, 0.34851, 0.43039,
|
|
43
|
+
0.52252, 0.62523, 0.73884, 0.86367, 1];
|
|
44
|
+
const PARAMETERS = [2.4, 1 / 1.055, 0.055 / 1.055, 1 / 12.92, 0.04045];
|
|
45
|
+
function srgbLinear(value) {
|
|
46
|
+
if (value <= 0.04045) return value / 12.92;
|
|
47
|
+
const base = (value + 0.055) / 1.055;
|
|
48
|
+
// base ** 2.4 as fixed arithmetic: the fifth root squared, times base squared. All engines round alike.
|
|
49
|
+
let root = 1;
|
|
50
|
+
for (let i = 0; i < 24; i++) root = (4 * root + base / (root * root * root * root)) / 5;
|
|
51
|
+
return base * base * root * root;
|
|
52
|
+
}
|
|
53
|
+
export function profileSpace(profile) {
|
|
54
|
+
const size = profile.length;
|
|
55
|
+
const u16 = at => (profile[at] << 8) | profile[at + 1];
|
|
56
|
+
const u32 = at => at + 4 <= size ? ((profile[at] << 24) | (profile[at + 1] << 16) | (profile[at + 2] << 8) | profile[at + 3]) >>> 0 : 0;
|
|
57
|
+
const sig = at => at + 4 <= size ? String.fromCharCode(profile[at], profile[at + 1], profile[at + 2], profile[at + 3]) : '';
|
|
58
|
+
const s15 = at => (u32(at) | 0) / 65536, tags = u32(128);
|
|
59
|
+
if (size < 132 || 132 + tags * 12 > size || sig(36) !== 'acsp' || sig(20) !== 'XYZ ') return null;
|
|
60
|
+
const tag = name => {
|
|
61
|
+
for (let i = 0; i < tags; i++) { const at = 132 + i * 12, offset = u32(at + 4); if (sig(at) === name) return offset + u32(at + 8) <= size ? offset : -1; }
|
|
62
|
+
return -1;
|
|
63
|
+
};
|
|
64
|
+
const srgbCurve = name => {
|
|
65
|
+
const at = tag(name);
|
|
66
|
+
if (at < 0) return false;
|
|
67
|
+
if (sig(at) === 'para') {
|
|
68
|
+
const type = u16(at + 8), count = [1, 3, 4, 5, 7][type];
|
|
69
|
+
if (type !== 3 && type !== 4) return false;
|
|
70
|
+
for (let i = 0; i < count; i++) if (Math.abs(s15(at + 12 + 4 * i) - (i < 5 ? PARAMETERS[i] : 0)) > (i ? 0.002 : 0.01)) return false;
|
|
71
|
+
return true;
|
|
72
|
+
}
|
|
73
|
+
const n = sig(at) === 'curv' ? u32(at + 8) : 0;
|
|
74
|
+
if (n < 2 || at + 12 + 2 * n > size) return false;
|
|
75
|
+
// Matching a few knots cannot identify a transfer curve: a monotonic table can differ between them.
|
|
76
|
+
// Check every stored value as well as the interpolated knots below, which also reject coarse linear tables.
|
|
77
|
+
for (let i = 0; i < n; i++) if (Math.abs(u16(at + 12 + 2 * i) / 65535 - srgbLinear(i / (n - 1))) > 0.001) return false;
|
|
78
|
+
return CURVE.every((want, k) => {
|
|
79
|
+
const p = k * (n - 1) / 16, i = Math.floor(p), j = Math.min(n - 1, i + 1), f = p - i;
|
|
80
|
+
return Math.abs((u16(at + 12 + 2 * i) * (1 - f) + u16(at + 12 + 2 * j) * f) / 65535 - want) <= 0.001;
|
|
81
|
+
});
|
|
82
|
+
};
|
|
83
|
+
if (['A2B0', 'A2B1', 'A2B2'].some(name => tag(name) >= 0)) return null;
|
|
84
|
+
if (sig(16) === 'GRAY') return srgbCurve('kTRC') ? 'srgb' : null;
|
|
85
|
+
if (sig(16) !== 'RGB ' || !['rTRC', 'gTRC', 'bTRC'].every(srgbCurve)) return null;
|
|
86
|
+
const colorants = ['rXYZ', 'gXYZ', 'bXYZ'].flatMap(name => { const at = tag(name); return at >= 0 && sig(at) === 'XYZ ' ? [s15(at + 8), s15(at + 12), s15(at + 16)] : [9, 9, 9]; });
|
|
87
|
+
const near = reference => reference.every((v, i) => Math.abs(colorants[i] - v) <= 0.004);
|
|
88
|
+
return near(SRGB) ? 'srgb' : near(P3) ? 'display-p3' : null;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
export function parseJPEG(bytes) {
|
|
92
|
+
if (!(bytes.length > 4) || bytes[0] !== 0xFF || bytes[1] !== 0xD8) throw jpegError('not a JPEG');
|
|
93
|
+
const quant = [], huffman = [[], []], badDC = new Set(), icc = {count: 0, parts: []};
|
|
94
|
+
let frame = null, restartInterval = 0, adobeTransform = -1, jfif = false, orientation = 1, pos = 2;
|
|
95
|
+
const u16 = at => (bytes[at] << 8) | bytes[at + 1];
|
|
96
|
+
const signatureAt = (at, signature) => {
|
|
97
|
+
for (let i = 0; i < signature.length; i++) if (bytes[at + i] !== signature.charCodeAt(i)) return false;
|
|
98
|
+
return true;
|
|
99
|
+
};
|
|
100
|
+
for (;;) {
|
|
101
|
+
if (pos >= bytes.length) { if (frame && frame.scans) break; throw jpegError('truncated'); }
|
|
102
|
+
if (bytes[pos] !== 0xFF) throw jpegError('marker expected');
|
|
103
|
+
while (bytes[pos] === 0xFF) pos++;
|
|
104
|
+
const marker = bytes[pos++];
|
|
105
|
+
if (marker === 0xD9) break;
|
|
106
|
+
if (marker === 0xD8) throw jpegError('a second start');
|
|
107
|
+
if (marker >= 0xD0 && marker <= 0xD7) throw jpegError('a restart marker outside a scan');
|
|
108
|
+
if (marker === 0x01) continue;
|
|
109
|
+
if (pos + 2 > bytes.length) throw jpegError('truncated');
|
|
110
|
+
const length = u16(pos), segment = pos + 2, end = pos + length;
|
|
111
|
+
if (length < 2 || end > bytes.length) throw jpegError('bad segment');
|
|
112
|
+
pos = end;
|
|
113
|
+
if (marker === 0xDB) {
|
|
114
|
+
for (let at = segment; at < end;) {
|
|
115
|
+
const pq = bytes[at] >> 4, tq = bytes[at] & 15;
|
|
116
|
+
if (pq > 1 || tq > 3 || at + 1 + (pq ? 128 : 64) > end) throw jpegError('bad quantisation table');
|
|
117
|
+
at++;
|
|
118
|
+
const table = new Int32Array(64);
|
|
119
|
+
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'); }
|
|
120
|
+
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');
|
|
121
|
+
quant[tq] = table;
|
|
122
|
+
}
|
|
123
|
+
} else if (marker === 0xC4) {
|
|
124
|
+
for (let at = segment; at < end;) {
|
|
125
|
+
const tc = bytes[at] >> 4, th = bytes[at] & 15;
|
|
126
|
+
if (tc > 1 || th > 3 || at + 17 > end) throw jpegError('bad Huffman table');
|
|
127
|
+
at++;
|
|
128
|
+
const counts = bytes.subarray(at, at + 16);
|
|
129
|
+
let total = 0;
|
|
130
|
+
for (const c of counts) total += c;
|
|
131
|
+
if (total > 256 || at + 16 + total > end) throw jpegError('bad Huffman table');
|
|
132
|
+
const symbols = bytes.subarray(at + 16, at + 16 + total);
|
|
133
|
+
huffman[tc][th] = buildHuffman(counts, symbols);
|
|
134
|
+
// libjpeg refuses a DC table naming a symbol above 15 when a scan first reads DC through it, used or not.
|
|
135
|
+
if (tc === 0) { if (symbols.some(s => s > 15)) badDC.add(th); else badDC.delete(th); }
|
|
136
|
+
at += 16 + total;
|
|
137
|
+
}
|
|
138
|
+
} else if (marker === 0xC0 || marker === 0xC1 || marker === 0xC2) {
|
|
139
|
+
if (frame) throw jpegError('two frames');
|
|
140
|
+
if (end - segment < 6) throw jpegError('bad frame header');
|
|
141
|
+
if (bytes[segment] !== 8) throw jpegError('only 8-bit samples');
|
|
142
|
+
const height = u16(segment + 1), width = u16(segment + 3), count = bytes[segment + 5];
|
|
143
|
+
if (!width || !height) throw jpegError('a height left to a DNL marker');
|
|
144
|
+
if (count !== 1 && count !== 3) throw jpegError('only grey or three components');
|
|
145
|
+
if (end - segment < 6 + count * 3) throw jpegError('bad frame header');
|
|
146
|
+
// Admitted before a plane is allocated: the limits are the module's, the same the checked API keeps.
|
|
147
|
+
if (width > JPEG_LIMITS.edge || height > JPEG_LIMITS.edge) throw jpegError('a picture past ' + JPEG_LIMITS.edge + ' pixels on a side', 'JXL_DIMENSIONS');
|
|
148
|
+
if (width * height > JPEG_LIMITS.pixels) throw jpegError('a picture past ' + JPEG_LIMITS.pixels + ' pixels', 'JXL_DIMENSIONS');
|
|
149
|
+
const components = [];
|
|
150
|
+
let blocksPerMcu = 0;
|
|
151
|
+
for (let i = 0, at = segment + 6; i < count; i++, at += 3) {
|
|
152
|
+
const h = bytes[at + 1] >> 4, v = bytes[at + 1] & 15, tq = bytes[at + 2];
|
|
153
|
+
if (h < 1 || h > 4 || v < 1 || v > 4) throw jpegError('bad sampling');
|
|
154
|
+
if (tq > 3) throw jpegError('bad quantisation table');
|
|
155
|
+
if (components.some(c => c.id === bytes[at])) throw jpegError('two components with one id');
|
|
156
|
+
blocksPerMcu += h * v;
|
|
157
|
+
components.push({id: bytes[at], h, v, tq, pred: 0, coverage: new Int8Array(64).fill(-1)});
|
|
158
|
+
}
|
|
159
|
+
if (blocksPerMcu > 10) throw jpegError('bad sampling');
|
|
160
|
+
const hmax = Math.max(...components.map(c => c.h)), vmax = Math.max(...components.map(c => c.v));
|
|
161
|
+
const mcusX = Math.ceil(width / (8 * hmax)), mcusY = Math.ceil(height / (8 * vmax));
|
|
162
|
+
for (const c of components) {
|
|
163
|
+
c.blocksW = Math.ceil(Math.ceil(width * c.h / hmax) / 8); c.blocksH = Math.ceil(Math.ceil(height * c.v / vmax) / 8);
|
|
164
|
+
c.stride = mcusX * c.h; c.rows = mcusY * c.v;
|
|
165
|
+
c.coeffs = new Int16Array(c.stride * c.rows * 64);
|
|
166
|
+
}
|
|
167
|
+
frame = {progressive: marker === 0xC2, width, height, components, hmax, vmax, mcusX, mcusY, scans: 0};
|
|
168
|
+
} else if (marker === 0xC3 || (marker >= 0xC5 && marker <= 0xC7) || (marker >= 0xC9 && marker <= 0xCB) || (marker >= 0xCD && marker <= 0xCF)) {
|
|
169
|
+
throw jpegError('lossless, hierarchical or arithmetic coding');
|
|
170
|
+
} else if (marker === 0xDD) { if (length < 4) throw jpegError('bad segment'); restartInterval = u16(segment); }
|
|
171
|
+
else if (marker === 0xDC) throw jpegError('a DNL marker');
|
|
172
|
+
else if (marker === 0xDA) {
|
|
173
|
+
if (!frame) throw jpegError('a scan before the frame');
|
|
174
|
+
const n = bytes[segment], scan = [];
|
|
175
|
+
if (n < 1 || n > 4 || segment + 1 + n * 2 + 3 > end) throw jpegError('bad scan header');
|
|
176
|
+
let at = segment + 1;
|
|
177
|
+
for (let i = 0; i < n; i++, at += 2) {
|
|
178
|
+
const component = frame.components.find(c => c.id === bytes[at]);
|
|
179
|
+
if (!component) throw jpegError('a scan of an unknown component');
|
|
180
|
+
if (scan.some(s => s.component === component)) throw jpegError('a component twice in one scan');
|
|
181
|
+
// A table may be reused for another component after this one's scans. Keep the table that actually
|
|
182
|
+
// decoded each component, not whatever happens to occupy its slot at the end of the file.
|
|
183
|
+
if (!component.quant) component.quant = quant[component.tq];
|
|
184
|
+
if (!component.quant) throw jpegError('a scan without its quantisation table');
|
|
185
|
+
scan.push({component, dc: huffman[0][bytes[at + 1] >> 4], ac: huffman[1][bytes[at + 1] & 15], dcSlot: bytes[at + 1] >> 4});
|
|
186
|
+
}
|
|
187
|
+
const ss = bytes[at], se = bytes[at + 1], ah = bytes[at + 2] >> 4, al = bytes[at + 2] & 15;
|
|
188
|
+
if ((!frame.progressive || (ss === 0 && ah === 0)) && scan.some(s => badDC.has(s.dcSlot))) throw jpegError('bad Huffman table');
|
|
189
|
+
pos = decodeScan(bytes, end, frame, scan, ss, se, ah, al, restartInterval);
|
|
190
|
+
frame.scans++;
|
|
191
|
+
} else if (marker === 0xE0) {
|
|
192
|
+
if (signatureAt(segment, 'JFIF')) jfif = true;
|
|
193
|
+
} else if (marker === 0xE1) {
|
|
194
|
+
if (orientation === 1 && signatureAt(segment, 'Exif')) orientation = exifOrientation(bytes, segment + 6, end);
|
|
195
|
+
} else if (marker === 0xE2) {
|
|
196
|
+
if (length >= 16 && signatureAt(segment, 'ICC_PROFILE\0')) {
|
|
197
|
+
const seq = bytes[segment + 12], count = bytes[segment + 13];
|
|
198
|
+
if (!seq || !count || seq > count || (icc.count && icc.count !== count) || icc.parts[seq]) throw jpegError('a colour profile cut short');
|
|
199
|
+
icc.count = count; icc.parts[seq] = bytes.subarray(segment + 14, end);
|
|
200
|
+
}
|
|
201
|
+
} else if (marker === 0xEE) {
|
|
202
|
+
if (length >= 14 && signatureAt(segment, 'Adobe')) adobeTransform = bytes[segment + 11];
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
if (!frame || !frame.scans) throw jpegError('no picture');
|
|
206
|
+
for (const c of frame.components) {
|
|
207
|
+
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');
|
|
208
|
+
}
|
|
209
|
+
let colorSpace = 'srgb';
|
|
210
|
+
if (icc.count) {
|
|
211
|
+
const parts = [];
|
|
212
|
+
for (let i = 1; i <= icc.count; i++) { if (!icc.parts[i]) throw jpegError('a colour profile cut short'); parts.push(icc.parts[i]); }
|
|
213
|
+
const profile = new Uint8Array(parts.reduce((n, p) => n + p.length, 0));
|
|
214
|
+
for (let i = 0, at = 0; i < parts.length; at += parts[i].length, i++) profile.set(parts[i], at);
|
|
215
|
+
colorSpace = profileSpace(profile);
|
|
216
|
+
if (!colorSpace) throw jpegError('a colour profile other than sRGB or Display P3 (decode the picture and encode its pixels)');
|
|
217
|
+
}
|
|
218
|
+
// Colour as libjxl reads it: JFIF means YCbCr; else an Adobe marker decides; else component ids spelling RGB.
|
|
219
|
+
let rgb = false;
|
|
220
|
+
if (frame.components.length === 3 && !jfif) {
|
|
221
|
+
if (adobeTransform >= 0) rgb = adobeTransform === 0;
|
|
222
|
+
else rgb = frame.components[0].id === 0x52 && frame.components[1].id === 0x47 && frame.components[2].id === 0x42;
|
|
223
|
+
}
|
|
224
|
+
return {width: frame.width, height: frame.height, components: frame.components, progressive: frame.progressive, ycbcr: !rgb, orientation, colorSpace};
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
// The Exif orientation tag (0x0112) of the first image directory, 1 when absent or unreadable.
|
|
228
|
+
function exifOrientation(bytes, start, end) {
|
|
229
|
+
const big = bytes[start] === 0x4D && bytes[start + 1] === 0x4D;
|
|
230
|
+
if (!big && !(bytes[start] === 0x49 && bytes[start + 1] === 0x49)) return 1;
|
|
231
|
+
const u16 = at => at + 2 > end ? 0 : big ? (bytes[at] << 8) | bytes[at + 1] : bytes[at] | (bytes[at + 1] << 8);
|
|
232
|
+
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;
|
|
233
|
+
if (u16(start + 2) !== 42) return 1;
|
|
234
|
+
const ifd = start + u32(start + 4), entries = u16(ifd);
|
|
235
|
+
for (let i = 0, at = ifd + 2; i < entries && at + 12 <= end; i++, at += 12) {
|
|
236
|
+
if (u16(at) !== 0x0112) continue;
|
|
237
|
+
const value = u16(at + 8);
|
|
238
|
+
return value >= 1 && value <= 8 ? value : 1;
|
|
239
|
+
}
|
|
240
|
+
return 1;
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
// What a scan may be, and what it leaves coded: sequential scans code a component whole at once; progressive scans
|
|
244
|
+
// code the DC first, then AC bands, each bit plane once, from the top down. `coverage[k]` is the lowest bit plane
|
|
245
|
+
// coefficient k has been coded to (-1 never), and the picture is complete only when every one reaches 0.
|
|
246
|
+
function admitScan(frame, scan, ss, se, ah, al) {
|
|
247
|
+
const progressive = frame.progressive;
|
|
248
|
+
if (!progressive) {
|
|
249
|
+
if (ss !== 0 || se !== 63 || ah !== 0 || al !== 0) throw jpegError('a bad spectral selection');
|
|
250
|
+
for (const s of scan) { if (s.component.coverage.some(v => v !== -1)) throw jpegError('a component coded twice'); s.component.coverage.fill(0); }
|
|
251
|
+
return;
|
|
252
|
+
}
|
|
253
|
+
if (al > 13 || (ah && ah !== al + 1)) throw jpegError('a bad successive approximation');
|
|
254
|
+
if (ss === 0) {
|
|
255
|
+
if (se !== 0) throw jpegError('a bad spectral selection');
|
|
256
|
+
for (const {component} of scan) {
|
|
257
|
+
if (component.coverage[0] !== (ah ? ah : -1)) throw jpegError(ah ? 'a refinement scan out of order' : 'a DC scan twice');
|
|
258
|
+
component.coverage[0] = al;
|
|
259
|
+
}
|
|
260
|
+
return;
|
|
261
|
+
}
|
|
262
|
+
if (scan.length !== 1) throw jpegError('an interleaved AC scan');
|
|
263
|
+
if (se > 63 || ss > se) throw jpegError('a bad spectral selection');
|
|
264
|
+
const {coverage} = scan[0].component;
|
|
265
|
+
if (coverage[0] === -1) throw jpegError('an AC scan before the DC scan');
|
|
266
|
+
for (let k = ss; k <= se; k++) {
|
|
267
|
+
if (coverage[k] !== (ah ? ah : -1)) throw jpegError(ah ? 'a refinement scan out of order' : 'a band coded twice');
|
|
268
|
+
coverage[k] = al;
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
function decodeScan(bytes, start, frame, scan, ss, se, ah, al, restartInterval) {
|
|
273
|
+
admitScan(frame, scan, ss, se, ah, al);
|
|
274
|
+
// `pad` counts the bits in `buffer` that are not the file's: zero bytes fed once a marker or the end is reached, so
|
|
275
|
+
// the lookahead always holds 24 bits. A code or a value that would take them is a scan cut short.
|
|
276
|
+
let pos = start, buffer = 0, count = 0, pad = 0, marker = false;
|
|
277
|
+
const fill = () => {
|
|
278
|
+
while (count <= 24) {
|
|
279
|
+
let byte = 0;
|
|
280
|
+
if (marker || pos >= bytes.length) { marker = true; pad += 8; }
|
|
281
|
+
else {
|
|
282
|
+
byte = bytes[pos];
|
|
283
|
+
if (byte === 0xFF) {
|
|
284
|
+
const next = bytes[pos + 1];
|
|
285
|
+
if (next === 0) pos += 2;
|
|
286
|
+
else if (next === 0xFF) { pos++; continue; }
|
|
287
|
+
else { marker = true; byte = 0; pad += 8; }
|
|
288
|
+
} else pos++;
|
|
289
|
+
}
|
|
290
|
+
buffer = ((buffer << 8) | byte) >>> 0; count += 8;
|
|
291
|
+
}
|
|
292
|
+
};
|
|
293
|
+
const short = () => jpegError('a scan cut short');
|
|
294
|
+
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; };
|
|
295
|
+
const extend = (value, n) => value < (1 << (n - 1)) ? value - (1 << n) + 1 : value;
|
|
296
|
+
const decode = table => {
|
|
297
|
+
if (!table) throw jpegError('a scan without its Huffman table');
|
|
298
|
+
fill();
|
|
299
|
+
const entry = table[(buffer >>> (count - 16)) & 0xFFFF];
|
|
300
|
+
if (!entry) throw jpegError('bad Huffman code');
|
|
301
|
+
if ((entry >> 8) > count - pad) throw short();
|
|
302
|
+
count -= entry >> 8;
|
|
303
|
+
return entry & 255;
|
|
304
|
+
};
|
|
305
|
+
// The bytes of an interval are consumed whole but for the last one's padding bits; then its marker, in order.
|
|
306
|
+
const atMarker = () => {
|
|
307
|
+
const remaining = count - pad;
|
|
308
|
+
if (remaining >= 8) throw jpegError('bytes left over in a scan');
|
|
309
|
+
if (eobrun) throw jpegError('an end-of-band run past its interval');
|
|
310
|
+
if (remaining && ((buffer >>> pad) & ((1 << remaining) - 1)) !== (1 << remaining) - 1) throw jpegError('bad scan padding');
|
|
311
|
+
while (pos + 1 < bytes.length && bytes[pos] === 0xFF && bytes[pos + 1] === 0xFF) pos++;
|
|
312
|
+
};
|
|
313
|
+
const restart = index => {
|
|
314
|
+
atMarker();
|
|
315
|
+
if (!(bytes[pos] === 0xFF && bytes[pos + 1] === 0xD0 + (index & 7))) throw jpegError('a restart marker missing or out of order');
|
|
316
|
+
pos += 2; buffer = 0; count = 0; pad = 0; marker = false;
|
|
317
|
+
for (const s of scan) s.component.pred = 0;
|
|
318
|
+
eobrun = 0;
|
|
319
|
+
};
|
|
320
|
+
const dcValue = (s, t) => {
|
|
321
|
+
if (t > 11) throw jpegError('a DC value out of range');
|
|
322
|
+
const diff = t ? extend(receive(t), t) : 0;
|
|
323
|
+
s.component.pred += diff;
|
|
324
|
+
if (s.component.pred > 2047 || s.component.pred < -2048) throw jpegError('a DC value out of range');
|
|
325
|
+
return s.component.pred;
|
|
326
|
+
};
|
|
327
|
+
const acValue = (size, shift) => {
|
|
328
|
+
if (size > 10) throw jpegError('an AC value out of range');
|
|
329
|
+
const value = extend(receive(size), size) * (1 << shift);
|
|
330
|
+
if (value > 1023 || value < -1023) throw jpegError('an AC value out of range');
|
|
331
|
+
return value;
|
|
332
|
+
};
|
|
333
|
+
let eobrun = 0;
|
|
334
|
+
const single = scan.length === 1, progressive = frame.progressive;
|
|
335
|
+
const baseline = (s, coeffs, at) => {
|
|
336
|
+
coeffs[at] = dcValue(s, decode(s.dc));
|
|
337
|
+
acFirst(s, coeffs, at);
|
|
338
|
+
};
|
|
339
|
+
const dcFirst = (s, coeffs, at) => {
|
|
340
|
+
const value = dcValue(s, decode(s.dc)) * (1 << al);
|
|
341
|
+
if (value > 2047 || value < -2048) throw jpegError('a DC value out of range');
|
|
342
|
+
coeffs[at] = value;
|
|
343
|
+
};
|
|
344
|
+
const dcRefine = (s, coeffs, at) => { if (receive(1)) coeffs[at] |= 1 << al; };
|
|
345
|
+
const pastBand = () => jpegError('coefficients past the ' + (progressive ? 'band' : 'block'));
|
|
346
|
+
// Sequential scans use this same first AC pass after their DC: admission fixes ss=0, se=63, al=0. Only a
|
|
347
|
+
// progressive scan may carry an end-of-band run across blocks; a sequential nonzero run still refuses here.
|
|
348
|
+
const acFirst = (s, coeffs, at) => {
|
|
349
|
+
if (eobrun > 0) { eobrun--; return; }
|
|
350
|
+
for (let k = ss || 1; k <= se;) {
|
|
351
|
+
const rs = decode(s.ac), r = rs >> 4, size = rs & 15;
|
|
352
|
+
if (!size) {
|
|
353
|
+
if (r < 15) {
|
|
354
|
+
if (r && !progressive) throw jpegError('an end-of-band run in a sequential scan');
|
|
355
|
+
eobrun = (1 << r) - 1 + (r ? receive(r) : 0); break;
|
|
356
|
+
}
|
|
357
|
+
k += 16; if (k > se + 1) throw pastBand(); continue;
|
|
358
|
+
}
|
|
359
|
+
k += r;
|
|
360
|
+
if (k > se) throw pastBand();
|
|
361
|
+
coeffs[at + ZIGZAG[k]] = acValue(size, al);
|
|
362
|
+
k++;
|
|
363
|
+
}
|
|
364
|
+
};
|
|
365
|
+
const acRefine = (s, coeffs, at) => {
|
|
366
|
+
const p1 = 1 << al, m1 = -1 << al;
|
|
367
|
+
let k = ss;
|
|
368
|
+
if (eobrun <= 0) {
|
|
369
|
+
for (; k <= se; k++) {
|
|
370
|
+
const rs = decode(s.ac);
|
|
371
|
+
let r = rs >> 4, value = 0;
|
|
372
|
+
const size = rs & 15;
|
|
373
|
+
if (size) { if (size !== 1) throw jpegError('a bad refinement code'); value = receive(1) ? p1 : m1; }
|
|
374
|
+
else if (r !== 15) { eobrun = 1 << r; if (r) eobrun += receive(r); break; }
|
|
375
|
+
for (; k <= se; k++) {
|
|
376
|
+
const z = at + ZIGZAG[k];
|
|
377
|
+
if (coeffs[z] !== 0) { if (receive(1) && (coeffs[z] & p1) === 0) coeffs[z] += coeffs[z] >= 0 ? p1 : m1; }
|
|
378
|
+
else if (--r < 0) break;
|
|
379
|
+
}
|
|
380
|
+
if (r >= 0 || (value && k > se)) throw jpegError('coefficients past the band');
|
|
381
|
+
if (value) coeffs[at + ZIGZAG[k]] = value;
|
|
382
|
+
}
|
|
383
|
+
}
|
|
384
|
+
if (eobrun > 0) {
|
|
385
|
+
for (; k <= se; k++) {
|
|
386
|
+
const z = at + ZIGZAG[k];
|
|
387
|
+
if (coeffs[z] !== 0 && receive(1) && (coeffs[z] & p1) === 0) coeffs[z] += coeffs[z] >= 0 ? p1 : m1;
|
|
388
|
+
}
|
|
389
|
+
eobrun--;
|
|
390
|
+
}
|
|
391
|
+
};
|
|
392
|
+
const block = !progressive ? baseline : ss === 0 ? (ah === 0 ? dcFirst : dcRefine) : (ah === 0 ? acFirst : acRefine);
|
|
393
|
+
for (const s of scan) s.component.pred = 0;
|
|
394
|
+
const first = scan[0].component;
|
|
395
|
+
const total = single ? first.blocksW * first.blocksH : frame.mcusX * frame.mcusY;
|
|
396
|
+
for (let unit = 0; unit < total; unit++) {
|
|
397
|
+
if (restartInterval && unit > 0 && unit % restartInterval === 0) restart(unit / restartInterval - 1);
|
|
398
|
+
if (single) {
|
|
399
|
+
const by = (unit / first.blocksW) | 0, bx = unit - by * first.blocksW;
|
|
400
|
+
block(scan[0], first.coeffs, (by * first.stride + bx) * 64);
|
|
401
|
+
} else {
|
|
402
|
+
const my = (unit / frame.mcusX) | 0, mx = unit - my * frame.mcusX;
|
|
403
|
+
for (const s of scan) {
|
|
404
|
+
const c = s.component;
|
|
405
|
+
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);
|
|
406
|
+
}
|
|
407
|
+
}
|
|
408
|
+
}
|
|
409
|
+
// The scan ends at a marker or EOF. A final complete interval may carry its next restart marker, once.
|
|
410
|
+
atMarker();
|
|
411
|
+
if (bytes[pos] === 0xFF && bytes[pos + 1] >= 0xD0 && bytes[pos + 1] <= 0xD7) {
|
|
412
|
+
if (!restartInterval || total % restartInterval || bytes[pos + 1] !== 0xD0 + ((total / restartInterval - 1) & 7)) throw jpegError('a restart marker out of order');
|
|
413
|
+
pos += 2;
|
|
414
|
+
while (pos + 1 < bytes.length && bytes[pos] === 0xFF && bytes[pos + 1] === 0xFF) pos++;
|
|
415
|
+
}
|
|
416
|
+
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');
|
|
417
|
+
return pos;
|
|
418
|
+
}
|
package/jpeg-ans.d.mts
ADDED