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/vardct.mjs CHANGED
@@ -3,12 +3,13 @@
3
3
  // a JPEG: its quantisation tables as raw dequantisation matrices, its DC values as the DC image, its colour
4
4
  // (YCbCr, or RGB) and chroma subsampling kept, every block an 8x8 DCT, no filters, no smoothing, no chroma from
5
5
  // luma. Only the entropy coding changes: JPEG XL's contexts over the coefficients, with prefix codes.
6
- import {BitWriter, float16Bits, packSigned, ceilLog2} from './bits.mjs';
6
+ import {BitWriter, float16Bits, packSigned, ceilLog2, complete} from './bits.mjs';
7
7
  import {writeImageHeader, writeFrameHeaderEnd, finishSections, assembleCodestream, GROUP_DIM} from './frame.mjs';
8
8
  import {ZERO_PREDICTOR, GRADIENT_PREDICTOR, ALPHABET, leaf, channelTree, writeTree, writeModularHeader, writeChannelHistograms, codeChannel} from './modular.mjs';
9
- import {writeContextMap, writeHistograms} from './prefix.mjs';
9
+ import {writeContextMap, writeHistograms, buildCode, uintConfig, countToken, writeHybrid} from './prefix.mjs';
10
10
  import {TokenCounts, buildTokenCoding} from './entropy.mjs';
11
- import {parseJPEG, jpegError, ZIGZAG} from './jpeg.mjs';
11
+ import {parseJPEG, jpegError, ZIGZAG} from './jfif.mjs';
12
+ import {admitOutputSize} from './admit.mjs';
12
13
 
13
14
  const NONZERO_BUCKETS = 37, ZERO_DENSITY_CONTEXTS = 458, ORDERS = 13;
14
15
  const COEFF_FREQ_CONTEXT = [0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 15, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
@@ -69,12 +70,21 @@ export function transcodeJPEG(bytes, jpeg = parseJPEG(bytes)) { return encodeVar
69
70
 
70
71
  // Shared coefficient writer. Pixel encoding supplies the same natural-order DCT8 planes as the JPEG reader;
71
72
  // quantScale lets its raw integer matrices carry fractional steps without a second entropy/frame writer.
72
- export function encodeVarDCT(jpeg) {
73
+ export function encodeVarDCT(jpeg, plan) { return complete(varDCTSteps(jpeg, plan)); }
74
+
75
+ // The same as steps: a group of each counting pass, a DC group, an AC group per step.
76
+ export function* varDCTSteps(jpeg, plan = {}) {
73
77
  const {width, height, components, alpha} = jpeg, grey = components.length === 1;
74
78
  const quantScale = jpeg.quantScale || 1;
79
+ // The raw tables' denominator, 1 / (8 x 255 x quantScale), is a normal binary16: where it would be subnormal (the
80
+ // photo door's), it is doubled until it is not and every block's quantisation field doubled with it, so the decoder's
81
+ // dequantised coefficients are the same. A decoder that reads a subnormal wrong (jxl-rs 0.7.4 halves them) reads these.
82
+ let field = jpeg.quantFieldBase || 1;
83
+ while (field / (8 * 255 * quantScale) < 1 / 16384) field *= 2;
75
84
  const ycbcr = jpeg.ycbcr || grey;
76
85
  const map = grey ? [0, 0, 0] : ycbcr ? [1, 0, 2] : [0, 1, 2]; // frame channel (X, Y, B) to JPEG component
77
86
  const comps = map.map(i => components[i]);
87
+ const orders = plan.orders ? map.map(i => plan.orders[i].map(k => SCAN[k])) : [SCAN, SCAN, SCAN];
78
88
  const log2 = v => v === 1 ? 0 : v === 2 ? 1 : -1;
79
89
  const rawH = comps.map(c => log2(c.h)), rawV = comps.map(c => log2(c.v));
80
90
  if (rawH.includes(-1) || rawV.includes(-1)) throw jpegError('sampling factors other than one or two');
@@ -105,7 +115,7 @@ export function encodeVarDCT(jpeg) {
105
115
  let contexts = blockContexts(lumaDc, wanted, grey);
106
116
 
107
117
  const header = new BitWriter(256);
108
- writeImageHeader(header, width, height, grey ? 1 : 3, !!alpha, {orientation: jpeg.orientation});
118
+ writeImageHeader(header, width, height, grey ? 1 : 3, !!alpha, {orientation: jpeg.orientation, colorSpace: jpeg.colorSpace});
109
119
  // The frame header: VarDCT, adaptive DC smoothing skipped, the colour and subsampling of the JPEG.
110
120
  header.write(1, 0); header.write(2, 0); header.write(1, 0);
111
121
  header.write(2, 2); header.write(8, 128 - 17); // flags: kSkipAdaptiveDCSmoothing
@@ -133,22 +143,39 @@ export function encodeVarDCT(jpeg) {
133
143
  const offset = contexts.zeroDensityOffset(blockCtx);
134
144
  let prev = count > 4 ? 0 : 1, left = count;
135
145
  for (let k = 1; k < 64 && left; k++) {
136
- const coeff = coeffs[at + SCAN[k]];
146
+ const coeff = coeffs[at + orders[c][k]];
137
147
  emit(offset + zeroDensityContext(left, k, prev), packSigned(coeff));
138
148
  prev = coeff ? 1 : 0; left -= prev;
139
149
  }
140
150
  }
141
151
  };
142
152
  // Bucketed contexts win on photographs and lose on small or flat pictures: both are counted and the cheaper kept.
143
- const countWith = chosen => { contexts = chosen; const counts = new TokenCounts(chosen.contexts); for (let g = 0; g < numGroups; g++) tokens(g, (ctx, value) => counts.add(ctx, value)); return buildTokenCoding(counts); };
144
- let coding = countWith(contexts);
153
+ const total = (wanted > 0 ? 3 : 2) * numGroups + numDcGroups;
154
+ let done = 0;
155
+ const countWith = function* (chosen) {
156
+ contexts = chosen;
157
+ const counts = new TokenCounts(chosen.contexts);
158
+ for (let g = 0; g < numGroups; g++) { tokens(g, (ctx, value) => counts.add(ctx, value)); yield ++done / total; }
159
+ return (plan.coding || buildTokenCoding)(counts, plan.clusters);
160
+ };
161
+ let coding = yield* countWith(contexts);
145
162
  if (wanted > 0) {
146
- const bucketed = contexts, plain = blockContexts(lumaDc, 0, grey), plainCoding = countWith(plain);
163
+ const bucketed = contexts, plain = blockContexts(lumaDc, 0, grey), plainCoding = yield* countWith(plain);
147
164
  if (plainCoding.bits <= coding.bits) coding = plainCoding; else contexts = bucketed;
148
165
  }
149
166
 
150
167
  const writers = Array.from({length: single ? 1 : 2 + numDcGroups + numGroups}, () => null);
151
168
  const section = index => writers[single ? 0 : index] || (writers[single ? 0 : index] = new BitWriter(4096));
169
+ // Refuse as completed sections cross the whole-stream bound, before later groups or section copies allocate.
170
+ // A one-group frame shares its writer, so only its growth since the last checkpoint is charged again.
171
+ const sectionSizes = new Uint32Array(writers.length);
172
+ let sectionBytes = 0;
173
+ const checkSection = index => {
174
+ index = single ? 0 : index;
175
+ const size = Math.ceil(writers[index].bitLength / 8);
176
+ sectionBytes += size - sectionSizes[index]; sectionSizes[index] = size;
177
+ admitOutputSize(sectionBytes);
178
+ };
152
179
 
153
180
  // DC global: the DC quantisation of each channel, the quantizer at scale one, luma and chroma block contexts, no
154
181
  // chroma from luma, no global modular tree.
@@ -177,6 +204,7 @@ export function encodeVarDCT(jpeg) {
177
204
  dc.write(1, 0); dc.write(2, 0); dc.write(16, 0); dc.write(16, 0); dc.write(8, 128); dc.write(8, 128);
178
205
  dc.write(1, 0);
179
206
  if (alpha) writeModularStream(dc, [single ? alphaPlane(0, 0) : {w: 0, h: 0, data: new Int32Array(0)}], GRADIENT_PREDICTOR);
207
+ checkSection(0);
180
208
 
181
209
  // DC groups: the DC coefficients as a modular image (luma first), then the AC metadata: all blocks 8x8 DCT at
182
210
  // quant one, no chroma-from-luma tiles, no sharpness.
@@ -197,17 +225,23 @@ export function encodeVarDCT(jpeg) {
197
225
  const count = rw * rh, bits = ceilLog2(count);
198
226
  if (bits) w.write(bits, count - 1);
199
227
  const cw = (rw + 7) >> 3, ch = (rh + 7) >> 3;
228
+ // Every block's strategy (DCT8, row 0) and quantisation field less one (row 1); a field above one is a constant row,
229
+ // which the gradient predictor codes as one residual.
230
+ const blocks = new Int32Array(count * 2).fill(field - 1, count);
231
+ if (jpeg.quantFields) for (let y = 0; y < rh; y++) for (let x = 0; x < rw; x++) blocks[count + y * rw + x] = jpeg.quantFields[(y0 + y) * xsizeBlocks + x0 + x] - 1;
200
232
  writeModularStream(w, [
201
233
  {w: cw, h: ch, data: new Int32Array(cw * ch)}, {w: cw, h: ch, data: new Int32Array(cw * ch)},
202
- {w: count, h: 2, data: new Int32Array(count * 2)}, {w: rw, h: rh, data: new Int32Array(count)},
203
- ], ZERO_PREDICTOR);
234
+ {w: count, h: 2, data: blocks}, {w: rw, h: rh, data: new Int32Array(count)},
235
+ ], field > 1 ? GRADIENT_PREDICTOR : ZERO_PREDICTOR);
236
+ checkSection(1 + g);
237
+ yield ++done / total;
204
238
  }
205
239
 
206
240
  // AC global: the JPEG's quantisation tables as the raw DCT8 matrices (transposed into the frame's layout), the
207
241
  // other kinds from the library, one histogram set, the natural coefficient order, the AC histograms.
208
242
  const ac = section(1 + numDcGroups);
209
243
  ac.write(1, 0);
210
- ac.write(3, 7); ac.write(16, float16Bits(1 / (8 * 255 * quantScale)));
244
+ ac.write(3, 7); ac.write(16, float16Bits(field / (8 * 255 * quantScale)));
211
245
  writeModularStream(ac, [0, 1, 2].map(c => {
212
246
  const data = new Int32Array(64), quant = comps[c].quant;
213
247
  for (let y = 0; y < 8; y++) for (let x = 0; x < 8; x++) data[8 * x + y] = quant[8 * y + x];
@@ -215,13 +249,36 @@ export function encodeVarDCT(jpeg) {
215
249
  }), GRADIENT_PREDICTOR);
216
250
  for (let i = 1; i < 17; i++) ac.write(3, 0);
217
251
  if (numGroups > 1) ac.write(ceilLog2(numGroups), 0);
218
- ac.write(2, 2);
219
- writeHistograms(ac, {contextMap: coding.contextMap, histograms: coding.histograms});
252
+ if (plan.orders) {
253
+ // DCT8 is order 0. Permutations name positions in the natural scan and are carried as a Lehmer code,
254
+ // skipping DC. A prefix histogram may serve all eight permutation contexts.
255
+ ac.writeU32([[0, 95], [0, 19], [0, 0], [13, 0]], 1);
256
+ const values = [];
257
+ for (const c of map) {
258
+ const available = Array.from({length: 64}, (_, k) => k), lehmer = plan.orders[c].map(k => {
259
+ const at = available.indexOf(k); available.splice(at, 1); return at;
260
+ });
261
+ let end = 64;
262
+ while (end > 1 && !lehmer[end - 1]) end--;
263
+ values.push(end - 1, ...lehmer.slice(1, end));
264
+ }
265
+ const config = uintConfig(0), freqs = new Uint32Array(64);
266
+ for (const value of values) countToken(config, value, freqs);
267
+ const code = buildCode(freqs);
268
+ writeHistograms(ac, {contextMap: new Uint8Array(8), histograms: [{config, code}]});
269
+ for (const value of values) writeHybrid(ac, code, config, value);
270
+ } else ac.write(2, 2);
271
+ if (coding.writeHistograms) coding.writeHistograms(ac);
272
+ else writeHistograms(ac, {contextMap: coding.contextMap, histograms: coding.histograms});
273
+ checkSection(1 + numDcGroups);
220
274
 
221
275
  for (let g = 0; g < numGroups; g++) {
222
276
  const w = section(2 + numDcGroups + g);
223
277
  tokens(g, (ctx, value) => coding.write(w, ctx, value));
278
+ if (coding.flush) coding.flush(w);
224
279
  if (alpha && !single) writeModularStream(w, [alphaPlane(g % groupsX, Math.floor(g / groupsX))], GRADIENT_PREDICTOR);
280
+ checkSection(2 + numDcGroups + g);
281
+ yield ++done / total;
225
282
  }
226
283
  return assembleCodestream(header, finishSections(writers));
227
284
  }
package/weighted.mjs ADDED
@@ -0,0 +1,89 @@
1
+ // Rapier's JPEG XL encoder: the self-correcting (weighted) predictor. MIT (LICENSE).
2
+ // The specification's modular predictor 6 under the default header every Rapier stream writes (p1 16, p2 10, p3 7, 7,
3
+ // 7, 0, 0; weights 13, 12, 12, 12): four sub-predictions in eighths of a level, each weighted by its error on the
4
+ // pixels above and to the left, clamped to the neighbours when their errors disagree in sign. The decoder keeps the
5
+ // same state for each channel of each group, so the encoder runs it over the plane it codes, and with it the
6
+ // property it offers a tree (15: of the errors to the west, north, north-west and north-east, the one largest in
7
+ // size). Integer arithmetic only: every engine predicts alike.
8
+ import {packSigned} from './bits.mjs';
9
+ import {countToken, writeHybrid} from './prefix.mjs';
10
+ import {LZ77, RESIDUAL_CONFIG} from './modular.mjs';
11
+
12
+ export const WEIGHTED_PREDICTOR = 6, WEIGHTED_PROPERTY = 15;
13
+ // libjxl's cut points on that property for its fixed weighted tree: 34 contexts, from which a coder merges neighbours.
14
+ export const WEIGHTED_CUTS = [-500, -392, -255, -191, -127, -95, -63, -47, -31, -23, -15, -11, -7, -4, -3, -1, 0, 1, 3, 5, 7, 11, 15, 23, 31, 47,
15
+ 63, 95, 127, 191, 255, 392, 500];
16
+ // The context of a property value: how many cut points lie below it.
17
+ const BUCKET = Int8Array.from({length: 1003}, (_, i) => WEIGHTED_CUTS.filter(cut => cut < i - 501).length);
18
+ const DIVISORS = Int32Array.from({length: 64}, (_, i) => Math.floor(16777216 / (i + 1)));
19
+ const calculateWeight = (sum, most) => { const shift = Math.max(0, 26 - Math.clz32(sum + 1)); return 4 + ((most * DIVISORS[sum >> shift]) >> shift); };
20
+ // Common error sums use the same fixed arithmetic, computed once. Larger sums take the original formula.
21
+ const WEIGHTS = [12, 13].map(most => Int32Array.from({length: 2048}, (_, sum) => calculateWeight(sum, most)));
22
+ const errorWeight = (sum, most) => sum < 2048 ? WEIGHTS[most - 12][sum] : calculateWeight(sum, most);
23
+ const SINGLE = new Int32Array(WEIGHTED_CUTS.length + 1);
24
+ let weightedScratch;
25
+
26
+ // Codes one channel plane with the weighted predictor, as codeChannel codes the others (a residual per pixel, eight
27
+ // or more zero residuals as one zero and an LZ77 copy), each token through the target of its pixel's context:
28
+ // `contextOf[k]` is the target of the k-th cut interval (all one target when absent). Counting when `w` is null
29
+ // (targets are histograms), writing otherwise (targets are prefix codes). Exact planes only: the offset applies, the
30
+ // multiplier is one. The effort-only local modeller can request the raw unsigned residuals and signed property in
31
+ // caller-owned arrays instead; it then owns tokenisation, while this one loop remains the predictor's state owner.
32
+ export function codeWeighted(w, targets, plane, width, height, offset = 0, contextOf = SINGLE, residuals, properties) {
33
+ const stride = width + 2;
34
+ // A call owns its state until it returns; a nested writer call gets a separate scratch allocation.
35
+ const state = weightedScratch && weightedScratch[0].length >= 2 * stride ? weightedScratch : Array.from({length: 6}, (_, i) => new Int32Array(i < 5 ? 2 * stride : 8));
36
+ weightedScratch = null;
37
+ for (const array of state) array.fill(0);
38
+ const [errors0, errors1, errors2, errors3, error, runContexts] = state;
39
+ let run = 0;
40
+ const emit = (context, value, config = RESIDUAL_CONFIG, base = 0) => { if (w) writeHybrid(w, targets[context], config, value, base); else countToken(config, value, targets[context], base); };
41
+ // A run's first zero goes through its own pixel's context and the copy's length through the next pixel's, where the
42
+ // decoder reads them.
43
+ const flush = () => {
44
+ if (!run) return;
45
+ if (run > LZ77.minLength) { emit(runContexts[0], 0); emit(runContexts[1], run - LZ77.minLength - 1, LZ77.lengthConfig, LZ77.minSymbol); }
46
+ else for (let i = 0; i < run; i++) emit(runContexts[i], 0);
47
+ run = 0;
48
+ };
49
+ for (let y = 0, index = 0; y < height; y++) {
50
+ const cur = y & 1 ? 0 : stride, prev = y & 1 ? stride : 0;
51
+ for (let x = 0; x < width; x++, index++) {
52
+ const left = x ? plane[index - 1] : y ? plane[index - width] : 0, top = y ? plane[index - width] : left;
53
+ const topright = x + 1 < width && y ? plane[index - width + 1] : top;
54
+ const n = prev + x, ne = x < width - 1 ? n + 1 : n, nw = x ? n - 1 : n;
55
+ let w0 = errorWeight(errors0[n] + errors0[ne] + errors0[nw], 13), w1 = errorWeight(errors1[n] + errors1[ne] + errors1[nw], 12);
56
+ let w2 = errorWeight(errors2[n] + errors2[ne] + errors2[nw], 12), w3 = errorWeight(errors3[n] + errors3[ne] + errors3[nw], 12);
57
+ const N = top * 8, W = left * 8, NE = topright * 8;
58
+ const teW = x ? error[cur + x - 1] : 0, teN = error[n], teNW = error[nw], teNE = error[ne], sumWN = teN + teW;
59
+ let most = teW;
60
+ if (Math.abs(teN) > Math.abs(most)) most = teN;
61
+ if (Math.abs(teNW) > Math.abs(most)) most = teNW;
62
+ if (Math.abs(teNE) > Math.abs(most)) most = teNE;
63
+ const context = contextOf[BUCKET[most < -501 ? 0 : most > 501 ? 1002 : most + 501]];
64
+ if (properties) properties[index] = most;
65
+ const p0 = W + NE - N, p1 = N - (((sumWN + teNE) * 16) >> 5), p2 = W - (((sumWN + teNW) * 10) >> 5);
66
+ const p3 = N - (((teNW + teN + teNE) * 7) >> 5);
67
+ // The weighted average: the weights scaled to sum between 16 and 64, then a division by table.
68
+ const shift = 27 - Math.clz32(w0 + w1 + w2 + w3);
69
+ w0 >>= shift; w1 >>= shift; w2 >>= shift; w3 >>= shift;
70
+ const sum = w0 + w1 + w2 + w3;
71
+ let pred = Math.floor(((sum >> 1) - 1 + p0 * w0 + p1 * w1 + p2 * w2 + p3 * w3) * DIVISORS[sum - 1] / 16777216);
72
+ if (((teN ^ teW) | (teN ^ teNW)) <= 0) {
73
+ const lo = Math.min(W, NE, N), hi = Math.max(W, NE, N);
74
+ pred = pred < lo ? lo : pred > hi ? hi : pred;
75
+ }
76
+ const value = plane[index], r = value - ((pred + 3) >> 3) - offset;
77
+ if (residuals) residuals[index] = packSigned(r);
78
+ else if (r === 0) { if (run < 8) runContexts[run] = context; run++; }
79
+ else { flush(); emit(context, packSigned(r)); }
80
+ // The state the decoder keeps: the prediction's error, and each sub-prediction's, added into the next row's view.
81
+ const v = value * 8, e0 = (Math.abs(p0 - v) + 3) >> 3, e1 = (Math.abs(p1 - v) + 3) >> 3, e2 = (Math.abs(p2 - v) + 3) >> 3, e3 = (Math.abs(p3 - v) + 3) >> 3;
82
+ error[cur + x] = pred - v;
83
+ errors0[cur + x] = e0; errors1[cur + x] = e1; errors2[cur + x] = e2; errors3[cur + x] = e3;
84
+ errors0[prev + x + 1] += e0; errors1[prev + x + 1] += e1; errors2[prev + x + 1] += e2; errors3[prev + x + 1] += e3;
85
+ }
86
+ }
87
+ flush();
88
+ weightedScratch = state;
89
+ }
package/writer.mjs ADDED
@@ -0,0 +1,17 @@
1
+ // SPDX-License-Identifier: MIT
2
+ // Rapier JXL's layers, for the author of a module: the JPEG XL specification's structures (ISO/IEC 18181-1), written.
3
+ // A module imports from here alone, composes its headers and frames from these parts, never changes a layer's object
4
+ // or default, and refuses with the five codes. This surface changes only with the package's major version; what lies
5
+ // behind it may change in any release. Readable modules only: the one-file builds rename these parts' properties.
6
+ export {LIMITS, PHOTO_LIMITS, JPEG_LIMITS, BitWriter, packSigned, floorLog2, ceilLog2, float16Bits, complete, part} from './bits.mjs';
7
+ export {codeLengths, canonicalCodes, buildCode, writePrefixCode, uintConfig, writeUintConfig, hybridToken, countToken, writeHybrid, writeContextMap, writeHistograms} from './prefix.mjs';
8
+ export {GROUP_DIM, DC_GROUP_DIM, writeImageHeader, writeModularFrameHeader, writeFrameHeaderEnd, writeTOC, groupLayout, finishSections, assembleCodestream} from './frame.mjs';
9
+ export {PREDICTOR, LZ77, RESIDUAL_CONFIG, ALPHABET, leaf, split, channelTree, streamTree, writeTree, writeTransform, writeModularHeader, writeChannelHistograms, codeChannel} from './modular.mjs';
10
+ export {WEIGHTED_PREDICTOR, WEIGHTED_PROPERTY, WEIGHTED_CUTS, codeWeighted} from './weighted.mjs';
11
+ export {forwardSqueeze, defaultSqueezeParams} from './squeeze.mjs';
12
+ export {inspectPixels, encodeLossless, losslessSteps} from './lossless.mjs';
13
+ export {distanceFromQuality, quantiserFor, encodeLossy, lossySteps} from './lossy.mjs';
14
+ export {TokenCounts, buildTokenCoding} from './entropy.mjs';
15
+ export {encodeVarDCT, varDCTSteps, transcodeJPEG} from './vardct.mjs';
16
+ export {parseJPEG, profileSpace, ZIGZAG} from './jfif.mjs';
17
+ export {fault, admitOptions, admitSize, admitPixels, answer, guard, job} from './admit.mjs';
package/lossless.d.mts DELETED
@@ -1,3 +0,0 @@
1
- // SPDX-License-Identifier: MIT
2
- export {encodeLosslessRGBA, LIMITS} from './index.mjs';
3
- export type {Pixels, Limits, ErrorCode, EncoderError} from './index.mjs';
package/lossless.min.mjs DELETED
@@ -1,2 +0,0 @@
1
- /*! Rapier JXL 1.1.21 | MIT License Copyright (c) 2026 rapier.website Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
2
- function t(t){return t>=0?2*t:2*-t-1}function n(t){return 31-Math.clz32(t)}function o(t){return t<=1?0:32-Math.clz32(t-1)}function e(t,n){const o=new Uint8Array(t.length),e=[];for(let n=0;n<t.length;n++)t[n]>0&&e.push(n);if(!e.length)return o;if(1===e.length)return o[e[0]]=1,o;for(let r=1;;r*=2){const i=e.map(n=>({w:Math.max(t[n],r),t:n,l:null,r:null})).sort((t,n)=>t.w-n.w||t.t-n.t),s=[];let c=0,f=0;const l=()=>c<i.length&&(f>=s.length||i[c].w<=s[f].w)?i[c++]:s[f++];for(;i.length-c+(s.length-f)>1;){const t=l(),n=l();s.push({w:t.w+n.w,t:-1,l:t,r:n})}const h=[[l(),0]];let a=0;for(;h.length;){const[t,n]=h.pop();t.t>=0?(o[t.t]=n,n>a&&(a=n)):h.push([t.l,n+1],[t.r,n+1])}if(a<=n)return o}}function r(t,n,o,e,r,i){const s=[];for(;s.push(e&r),e>>=i;)e--;for(let e=s.length-1;e>=0;e--)t.push(o),n.push(s[e])}function i(t,n){let o=0;for(let e=0;e<n;e++)o=o<<1|1&t,t>>=1;return o}function s(t){const n=new Uint32Array(17),o=new Uint32Array(17),e=new Uint16Array(t.length);for(const o of t)n[o]++;n[0]=0;for(let t=1,e=0;t<=16;t++)e=e+n[t-1]<<1,o[t]=e;for(let n=0;n<t.length;n++)t[n]&&(e[n]=i(o[t[n]]++,t[n]));return e}function c(t){const n=[];for(let o=0;o<t.length;o++)t[o]>0&&n.push(o);const o=n.length,r=n[o-1]+1||1,i=o<=4?new Uint8Array(r):e(t,15).subarray(0,r);let c=0;if(o<=4){n.sort((n,o)=>t[o]-t[n]||n-o),c=4===o&&t[n[0]]>t[n[2]]+t[n[3]]?1:0;const e=o<2?[0]:2===o?[1,1]:3===o?[1,2,2]:c?[1,2,3,3]:[2,2,2,2];n.forEach((t,n)=>{i[t]=e[n]}),n.sort((t,n)=>i[t]-i[n]||t-n)}return{o:r,i:i,h:s(i),u:o&&o<=4?n:null,p:c}}function f(t,o){if(o.o<=1)return;if(o.u){const e=n(o.o-1)+1;t.write(2,1),t.write(2,o.u.length-1);for(const n of o.u)t.write(e,n);return void(4===o.u.length&&t.write(1,o.p))}const i=o.i,c=[],f=[];let l=i.length-1;for(;l>0&&!i[l];)l--;let h=8;for(let t=0;t<=l;){const n=i[t];let o=1;for(;t+o<=l&&i[t+o]===n;)o++;let e=o;if(n&&n!==h&&(c.push(n),f.push(0),e--,h=n),e<3)for(let t=0;t<e;t++)c.push(n),f.push(0);else r(c,f,n?16:17,e-3,n?3:7,n?2:3);t+=o}const a=new Uint32Array(18);for(const t of c)a[t]++;let u=0;for(const t of a)t&&u++;1===u&&(a[c[0]?0:1]=a[c[0]]);const w=e(a,5),p=s(w);let y=18;for(;y>0&&!w[S[y-1]];)y--;t.write(2,0);for(let n=0;n<y;n++){const o=w[S[n]];t.write(T[o],X[o])}for(let n=0;n<c.length;n++){const o=c[n];t.write(w[o],p[o]),16===o?t.write(2,f[n]):17===o&&t.write(3,f[n])}}function l(t,n=0,o=0){return{split:t,M:n,A:o,m:1<<t}}function h(t,n,e=15){t.write(o(e+1),n.split),n.split!==e&&(t.write(o(n.split+1),n.M),t.write(o(n.split-n.M+1),n.A))}function a(t,o,e){if(o<t.m)return e[0]=o,e[1]=0,void(e[2]=0);const r=n(o),i=o-(1<<r),s=r-t.M-t.A;e[0]=t.m+(r-t.split<<t.M+t.A|i>>r-t.M<<t.A|i&(1<<t.A)-1),e[1]=s,e[2]=o>>t.A&(1<<s)-1}function u(t,n,o,e=0){a(t,n,N),o[e+N[0]]++}function w(t,n,o,e,r=0){a(o,e,N);const i=r+N[0];t.write(n.i[i],n.h[i]),N[1]&&t.write(N[1],N[2])}function p(t,{U:e=null,I:r,L:i}){t.write(1,e?1:0),e&&(t.S([[0,224],[0,512],[0,4096],[15,8]],e.T),t.S([[0,3],[0,4],[2,5],[8,9]],e.minLength),h(t,e.X,8)),r.length>1&&function(t,n){let e=0;for(const t of n)e=Math.max(e,t);const r=e?o(e+1):0;if(r<=3){if(t.write(1,1),t.write(2,r),r)for(const o of n)t.write(r,o);return}t.write(1,0),t.write(1,0);const i=l(8),s=l(4),f=n.length>=64,h=new Uint32Array(f?257:e+1),a=[];for(let t=0;t<n.length;){let o=1;for(;f&&t+o<n.length&&n[t+o]===n[t];)o++;if(o>=8)a.push([n[t],o-1]),h[n[t]]++,u(s,o-1-7,h,224),t+=o;else{for(let e=0;e<o;e++)a.push([n[t],0]),h[n[t]]++;t+=o}}const y=c(h);if(!f){p(t,{I:new Uint8Array(1),L:[{config:i,code:y}]});for(const[n]of a)w(t,y,i,n);return}const g=new Uint32Array(1);g[0]=1,p(t,{U:{T:224,minLength:7,X:s},I:new Uint8Array([1,0]),L:[{config:l(0),code:c(g)},{config:i,code:y}]});for(const[n,o]of a)w(t,y,i,n),o&&w(t,y,s,o-7,224)}(t,r),t.write(1,1);for(const n of i)h(t,n.config,15);for(const o of i){const e=o.code.o-1;if(e){const o=n(e);t.write(1,1),t.write(4,o),t.write(o,e-(1<<o))}else t.write(1,0)}for(const n of i)f(t,n.code)}function y(t,n=0,o=1){return{N:t,offset:n,J:o,context:-1}}function g(t,n){const o=[[3,0],[6,8],[10,72],[13,1096]];if("rct"===n.type)t.write(2,0),t.S(o,n._),t.S([[0,6],[2,0],[4,2],[6,10]],n.C??6);else if("palette"===n.type)t.write(2,1),t.S(o,n._),t.S([[0,1],[0,3],[0,4],[13,1]],n.G),t.S([[8,0],[10,256],[12,1280],[16,5376]],n.O),t.S([[0,0],[8,1],[10,257],[16,1281]],n.P??0),t.write(4,n.N??0);else{if("squeeze"!==n.type)throw new Error("unknown transform "+n.type);{t.write(2,2);const e=n.v??[];t.S([[0,0],[4,1],[6,9],[8,41]],e.length);for(const n of e)t.write(1,n.B?1:0),t.write(1,n.j?1:0),t.S(o,n._),t.S([[0,1],[0,2],[0,3],[4,4]],n.G)}}}function M(t,{k:n=!0,R:o=[]}={}){t.write(1,n?1:0),t.write(1,1),t.S([[0,0],[0,1],[4,2],[8,18]],o.length);for(const n of o)g(t,n)}function d(n,o,e,r,i,s){const c=s.N,f=s.offset,l=s.J,h=O,a=C;let p=0;const y=(t,e=h,r=0)=>{n?w(n,o,e,t,r):u(e,t,o,r)},g=()=>{if(p){if(p>=8)y(0),y(p-7-1,a,224);else for(let t=0;t<p;t++)y(0);p=0}},M=(n,o)=>{const r=e[n];let i;1===l?i=r-o-f:(i=Math.round((r-o-f)/l),e[n]=o+f+i*l),0!==i?(g(),y(t(i))):p++};for(let t=0,n=0;t<i;t++)for(let o=0;o<r;o++,n++){let i;if(0===c)i=0;else{const s=o?e[n-1]:t?e[n-r]:0,f=t?e[n-r]:s;if(1===c)i=s;else if(2===c)i=f;else if(3===c)i=(s+f)/2|0;else{const l=s+f-(o&&t?e[n-r-1]:s);if(5===c){const t=s<f?s:f,n=s<f?f:s;i=l<t?t:l>n?n:l}else{if(4!==c)throw new Error("predictor "+c+" is not coded here");i=Math.abs(l-s)<Math.abs(l-f)?s:f}}}M(n,i)}g()}function A(t,n){t.S([[9,1],[13,1],[18,1],[30,1]],n)}function m(t,n,o,{palette:e=!0}={}){const r=n*o;let i=!0,s=!0;for(let n=0,o=0;o<r&&(255===t[n+3]||(i=!1,s))&&(t[n]===t[n+1]&&t[n]===t[n+2]||(s=!1,i));o++,n+=4);const c=s?1:3,f=!i,l=c+(f?1:0),h=n=>s?f?t[n]+256*t[n+3]:t[n]:t[n]+256*t[n+1]+65536*t[n+2]+(f?16777216*t[n+3]:0),a=new Map;let u=null;for(let t=0,n=0;e&&n<r;n++,t+=4){const n=h(t);if(0!==n&&!a.has(n)&&(a.set(n,1),a.size>=2048))break}if(e&&a.size<2048){const t=[...a.keys()],n=(t,n)=>Math.floor(t/256**n)%256,o=t=>(.299*n(t,0)+.587*n(t,1)+.114*n(t,2)+.01)*(4===l?n(t,3):1);t.sort((t,n)=>o(t)-o(n));const e=new Map([[0,0]]);t.forEach((t,n)=>e.set(t,n+1)),u={colours:[0,...t],index:e,key:h,byte:n}}return{colour:c,alpha:f,channels:l,palette:u}}function U(n,o,e,r){const{channels:i,palette:s}=r,l=function(t,n){const o=Math.ceil(t/z),e=Math.ceil(n/z);return{Y:o,Z:e,q:Math.ceil(t/2048),D:Math.ceil(n/2048),F:1===o&&1===e}}(o,e),h=s?2:i,a=Array.from({length:h},()=>y(_)),g=function(t){return function(t,n){const o=(e,r)=>{if(e===r)return n?t[e].H:t[e];const i=e+r>>1;return function(t,n,o,e){return{K:t,V:n,left:o,right:e}}(n,n?t[i].W:i,o(i+1,r),o(e,i))};return o(0,t.length-1)}(t,0)}(a),m=Array.from({length:h},()=>new Int16Array(65536)),U=(t,e,r,c)=>{for(let f=0;f<c;f++){let c=4*((e+f)*o+t),l=f*r;for(let t=0;t<r;t++,c+=4,l++)if(s)m[0][l]=s.index.get(s.key(c));else if(i>=3){const t=n[c],o=n[c+1],e=n[c+2],r=t-e,s=e+(r>>1),f=o-s;m[0][l]=s+(f>>1),m[1][l]=r,m[2][l]=f,4===i&&(m[3][l]=n[c+3])}else m[0][l]=n[c],2===i&&(m[1][l]=n[c+3])}};let b=null;if(s){const t=s.colours.length;b=new Int16Array(t*i),s.colours.forEach((n,o)=>{for(let e=0;e<i;e++)b[e*t+o]=s.byte(n,e)})}const x=t=>a[s?l.F?1:0:t],E=s?1:i,I=t=>{for(let n=0;n<l.Z;n++)for(let r=0;r<l.Y;r++){const i=r*z,s=n*z,c=Math.min(z,o-i),f=Math.min(z,e-s);U(i,s,c,f),t(n*l.Y+r,c,f)}};if(!s){const t=t=>{const n=c(t),o=new L(128);f(o,n);let e=o.$;for(let o=0;o<t.length;o++)t[o]&&(e+=t[o]*(n.i[o]+Math.max(0,o<224?o-1:o-236)));return e},n=Math.min(o,32),r=Math.min(e,32),s=[_,J].map(t=>({N:t,tt:a.map(()=>new Uint32Array(257))}));for(const t of[0,.5,1]){U(Math.floor((o-n)*t),Math.floor((e-r)*t),n,r);for(const t of s)for(let o=0;o<i;o++)d(null,t.tt[o],m[o],n,r,y(t.N))}a.forEach((n,o)=>{const e=s.map(n=>t(n.tt[o])),r=e[1]<e[0]?1:0;n.N=s[r].N})}const S=s?[{type:"palette",_:0,G:i,O:s.colours.length}]:i>=3?[{type:"rct",_:0,C:6}]:[],T=a.map(()=>new Uint32Array(257)),X=t=>T[a.indexOf(t)];b&&d(null,X(a[0]),b,s.colours.length,i,a[0]),I((t,n,o)=>{for(let t=0;t<E;t++)d(null,X(x(t)),m[t],n,o,x(t))});const N=new L(256);!function(t,n,o,e,r,{xyb:i=!1,orientation:s=1}={}){t.write(16,2815),t.write(1,0),A(t,o),t.write(3,0),A(t,n),t.write(1,0);const c=1!==s;t.write(1,c?1:0),c&&t.write(6,s-1),t.write(4,8),r?t.write(3,5):t.write(2,0),t.write(1,i?1:0),3===e?t.write(1,1):t.write(15,14100),c&&t.write(1,1),t.write(2,0),t.write(1,1),t.nt()}(N,o,e,r.colour,r.alpha),function(t,{alpha:n}){t.write(9,8),n&&t.write(2,0),t.write(2,1),function(t,n){t.write(n?7:5,0),t.write(11,1)}(t,n)}(N,{alpha:r.alpha});const C=new L(4096);C.write(1,1),C.write(1,1);const P=function(n,o){const e=[o],r=[],i=[];for(const n of e){if(n.left){r.push(n.K+1,t(n.V)),e.push(n.left,n.right);continue}n.context=i.length,i.push(n);const o=1===n.J?0:31-Math.clz32(n.J&-n.J);r.push(0,n.N,t(n.offset),o,(n.J>>o)-1)}const s=new Uint32Array(64);for(const t of r)u(O,t,s);const f=c(s);p(n,{I:new Uint8Array(6),L:[{config:O,code:f}]});for(const t of r)w(n,f,O,t);return i}(C,g),v=function(t,n,o,e=t=>t.context){const r=new Uint8Array(n.length+1);for(const t of n)r[t.context]=e(t)+1;const i=new Uint32Array(2);i[1]=1;const s=[{config:O,code:c(i)}],f=Math.max(...r);for(let t=0;t<f;t++)s.push({config:O,code:c(o[t])});return p(t,{U:G,I:r,L:s}),s}(C,P,T,t=>a.indexOf(t)),B=t=>v[a.indexOf(t)+1].code;M(C,{k:!0,R:S}),b&&d(C,B(a[0]),b,s.colours.length,i,a[0]);const j=[];if(l.F)I((t,n,o)=>{for(let t=0;t<E;t++)d(C,B(x(t)),m[t],n,o,x(t))}),j.push(C.finish());else{j.push(C.finish());for(let t=0;t<l.q*l.D+1;t++)j.push(new Uint8Array(0));I((t,n,o)=>{const e=new L(n*o*E+64);M(e,{k:!0,R:[]});for(let t=0;t<E;t++)d(e,B(x(t)),m[t],n,o,x(t));j.push(e.finish())})}return function(t,n){const o=n.map(t=>t.length);!function(t,n){t.write(1,0),t.nt();for(const o of n)t.S([[10,0],[14,1024],[22,17408],[30,4211712]],o);t.nt()}(t,o);const e=t.finish(),r=new Uint8Array(e.length+o.reduce((t,n)=>t+n,0));r.set(e);let i=e.length;for(const t of n)r.set(t,i),i+=t.length;return r}(N,j)}function b(t,n,o){if(function(t,n){if(!Number.isInteger(t)||!Number.isInteger(n)||t<1||n<1)throw P("JXL_INPUT","A picture is at least one pixel wide and high, in whole pixels.");if(t>E.edge||n>E.edge)throw P("JXL_DIMENSIONS","A picture is at most "+E.edge+" pixels on a side.");if(t*n>E.pixels)throw P("JXL_DIMENSIONS","A picture is at most "+E.pixels.toLocaleString("en-US")+" pixels.")}(n,o),!(t instanceof Uint8Array||t instanceof Uint8ClampedArray))throw P("JXL_INPUT","Pixels are a Uint8Array or Uint8ClampedArray of RGBA bytes.");if(t.length!==n*o*4)throw P("JXL_INPUT","Pixels are width * height * 4 bytes: straight (not premultiplied) RGBA, row by row.")}function x(t,n,o){return b(t,n,o),function(t){try{return t()}catch(t){if(t instanceof RangeError&&!t.code)throw P("JXL_MEMORY","Not enough memory for this picture.");throw t}}(()=>function(t){if(t.length>E.bytes)throw P("JXL_SIZE","The encoded picture exceeds 16 MiB.");return t}(function(t,n,o,{shape:e=m(t,n,o)}={}){let r,i;for(const s of e.palette?[e,{...e,palette:null}]:[e])try{const e=U(t,n,o,s);(!r||e.length<r.length)&&(r=e)}catch(t){if("JXL_SIZE"!==t.code)throw t;i=t}if(!r)throw i;return r}(t,n,o,{shape:m(t,n,o)})))}const E=Object.freeze({bytes:16777216,pixels:24e6,edge:16384}),I=Array.from({length:33},(t,n)=>2**n);class L{constructor(t=4096){this.bytes=new Uint8Array(t),this.at=0,this.ot=0,this.pending=0}write(t,n){if(t>32||n<0||n>=(I[t]??2**t))throw new Error("bit write out of range: "+t+" bits, "+n);let o=this.ot+n*(1<<this.pending),e=this.pending+t;this.at+5>=this.bytes.length&&this.grow();const r=this.bytes;for(;e>=8;)r[this.at++]=255&o,o=Math.floor(o/256),e-=8;this.ot=o,this.pending=e}S(t,n){for(let o=0;o<4;o++){const[e,r]=t[o];if(n>=r&&n-r<2**e)return this.write(2,o),void(e&&this.write(e,n-r))}throw new Error("U32 value out of range: "+n)}nt(){this.pending&&(this.at+1>=this.bytes.length&&this.grow(),this.bytes[this.at++]=this.ot,this.ot=0,this.pending=0)}get $(){return 8*this.at+this.pending}grow(t=0){const n=E.bytes+64;if(this.at+t+16>n)throw Object.assign(new Error("The encoded picture exceeds 16 MiB."),{code:"JXL_SIZE"});const o=new Uint8Array(Math.min(n,Math.max(2*this.bytes.length,this.at+t+16)));o.set(this.bytes.subarray(0,this.at)),this.bytes=o}append(t){if(this.at+t.at+8>=this.bytes.length&&this.grow(t.at+8),this.pending)for(let n=0;n<t.at;n++)this.write(8,t.bytes[n]);else this.bytes.set(t.bytes.subarray(0,t.at),this.at),this.at+=t.at;t.pending&&this.write(t.pending,t.ot)}finish(){const t=this.at+(this.pending?1:0),n=this.bytes.slice(0,t);return this.pending&&(n[this.at]=this.ot),n}}const S=[1,2,3,4,0,5,17,6,16,7,8,9,10,11,12,13,14,15],T=[2,4,3,2,2,4],X=[0,7,3,2,1,15],N=[0,0,0],J=3,_=5,C=l(4),G=Object.freeze({T:224,minLength:7,X:C}),O=l(0),z=256,P=(t,n)=>Object.assign(new Error(n),{code:t});export{x as encodeLosslessRGBA,E as LIMITS};