jixel 0.2.2

Tiny JPEG XL encoder
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
/*
 * // Copyright (c) Radzivon Bartoshyk 5/2026. All rights reserved.
 * //
 * // Redistribution and use in source and binary forms, with or without modification,
 * // are permitted provided that the following conditions are met:
 * //
 * // 1.  Redistributions of source code must retain the above copyright notice, this
 * // list of conditions and the following disclaimer.
 * //
 * // 2.  Redistributions in binary form must reproduce the above copyright notice,
 * // this list of conditions and the following disclaimer in the documentation
 * // and/or other materials provided with the distribution.
 * //
 * // 3.  Neither the name of the copyright holder nor the names of its
 * // contributors may be used to endorse or promote products derived from
 * // this software without specific prior written permission.
 * //
 * // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
 * // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 * // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
use crate::bit_writer::BitWriter;
use crate::entropy::{
    ALPHABET_SIZE, Histogram, OwnedEntropyCode, PrefixCode, Token, build_huffman_codes,
    write_entropy_code, write_token,
};

pub(crate) const K_ICC_HEADER_SIZE: usize = 128;
pub(crate) const K_NUM_ICC_CONTEXTS: usize = 41;

// Commands recognised by the decoder's UnpredictICC.
const K_COMMAND_INSERT: u8 = 1;

/// 4-letter ICC tags used in the header prediction template.
const K_MNTR: [u8; 4] = *b"mntr";
const K_RGB_: [u8; 4] = *b"RGB ";
const K_XYZ_: [u8; 4] = *b"XYZ ";
const K_ACSP: [u8; 4] = *b"acsp";

/// Initial 128-byte header prediction template — matches libjxl's
/// `ICCInitialHeaderPrediction()`.
fn icc_initial_header_prediction() -> [u8; K_ICC_HEADER_SIZE] {
    let mut h = [0u8; K_ICC_HEADER_SIZE];
    h[8] = 4;
    h[12..16].copy_from_slice(&K_MNTR);
    h[16..20].copy_from_slice(&K_RGB_);
    h[20..24].copy_from_slice(&K_XYZ_);
    h[36..40].copy_from_slice(&K_ACSP);
    // Magic constants from the reference (creation-date-ish fields):
    h[68] = 0;
    h[69] = 0;
    h[70] = 246;
    h[71] = 214;
    h[72] = 0;
    h[73] = 1;
    h[74] = 0;
    h[75] = 0;
    h[76] = 0;
    h[77] = 0;
    h[78] = 211;
    h[79] = 45;
    h
}

/// Update the header prediction at position `pos` based on previously decoded
/// ICC bytes.  Mirrors libjxl's `ICCPredictHeader`.
fn icc_predict_header(icc: &[u8], header: &mut [u8; K_ICC_HEADER_SIZE], pos: usize) {
    let size = icc.len();
    if pos == 8 && size >= 8 {
        header[80] = icc[4];
        header[81] = icc[5];
        header[82] = icc[6];
        header[83] = icc[7];
    }
    if pos == 41 && size >= 41 {
        if icc[40] == b'A' {
            header[41] = b'P';
            header[42] = b'P';
            header[43] = b'L';
        }
        if icc[40] == b'M' {
            header[41] = b'S';
            header[42] = b'F';
            header[43] = b'T';
        }
    }
    if pos == 42 && size >= 42 {
        if icc[40] == b'S' && icc[41] == b'G' {
            header[42] = b'I';
            header[43] = b' ';
        }
        if icc[40] == b'S' && icc[41] == b'U' {
            header[42] = b'N';
            header[43] = b'W';
        }
    }
}

/// `EncodeVarInt`: 7 bits/byte, MSB = continuation.
fn encode_varint(value: u64, out: &mut Vec<u8>) {
    let mut v = value;
    while v > 127 {
        out.push(((v & 127) as u8) | 128);
        v >>= 7;
    }
    out.push((v & 127) as u8);
}

// libjxl's ByteKind1 / ByteKind2 used to choose one of 41 ICC ANS contexts.
fn byte_kind_1(b: u8) -> u8 {
    if b.is_ascii_lowercase() {
        return 0;
    }
    if b.is_ascii_uppercase() {
        return 0;
    }
    if b.is_ascii_digit() {
        return 1;
    }
    if b == b'.' || b == b',' {
        return 1;
    }
    if b == 0 {
        return 2;
    }
    if b == 1 {
        return 3;
    }
    if b < 16 {
        return 4;
    }
    if b == 255 {
        return 6;
    }
    if b > 240 {
        return 5;
    }
    7
}
fn byte_kind_2(b: u8) -> u8 {
    if b.is_ascii_lowercase() {
        return 0;
    }
    if b.is_ascii_uppercase() {
        return 0;
    }
    if b.is_ascii_digit() {
        return 1;
    }
    if b == b'.' || b == b',' {
        return 1;
    }
    if b < 16 {
        return 2;
    }
    if b > 240 {
        return 3;
    }
    4
}

/// Context index for byte `i` of the predicted/encoded stream, given the two
/// previous bytes.  Returns a value in `0..K_NUM_ICC_CONTEXTS`.
pub(crate) fn iccans_context(i: usize, prev1: u8, prev2: u8) -> usize {
    if i <= 128 {
        return 0;
    }
    1 + (byte_kind_1(prev1) as usize) + (byte_kind_2(prev2) as usize) * 8
}

/// Run libjxl's minimal-strategy `PredictICC`: header delta + 1 insert command.
/// Returns the byte stream the decoder's `UnpredictICC` will turn back into the
/// original ICC profile.
pub(crate) fn predict_icc_minimal(icc: &[u8]) -> Vec<u8> {
    let mut out: Vec<u8> = Vec::with_capacity(icc.len() + 32);

    // 1. Output size (decoder verifies it matches the reconstructed profile).
    encode_varint(icc.len() as u64, &mut out);

    // Header data bytes (icc[i] - predicted[i] for i in 0..128).  Built first
    // so we can compute commands_size before writing it.
    let mut header_data: Vec<u8> = Vec::with_capacity(K_ICC_HEADER_SIZE);
    let mut header = icc_initial_header_prediction();
    // The reference also stuffs `icc.size()` into header[0..4] before predicting.
    // EncodeUint32(0, size, &header) — big-endian.
    let sz_be = (icc.len() as u32).to_be_bytes();
    header[0..4].copy_from_slice(&sz_be);
    let header_bound = K_ICC_HEADER_SIZE.min(icc.len());
    for i in 0..header_bound {
        icc_predict_header(icc, &mut header, i);
        header_data.push(icc[i].wrapping_sub(header[i]));
    }

    // 2. Commands stream.
    let mut commands: Vec<u8> = Vec::new();
    if icc.len() <= K_ICC_HEADER_SIZE {
        // Profiles ≤ 128 bytes have no commands — just the header delta.
        encode_varint(0, &mut commands);
    } else {
        // 0 tags (VarInt 0), then one Insert command for the entire tail.
        encode_varint(0, &mut commands);
        commands.push(K_COMMAND_INSERT);
        let tail_len = icc.len() - K_ICC_HEADER_SIZE;
        encode_varint(tail_len as u64, &mut commands);
    }

    // 3. csize, then commands bytes, then data bytes.
    encode_varint(commands.len() as u64, &mut out);
    out.extend_from_slice(&commands);
    out.extend_from_slice(&header_data);
    if icc.len() > K_ICC_HEADER_SIZE {
        out.extend_from_slice(&icc[K_ICC_HEADER_SIZE..]);
    }

    out
}

/// Write a `U64Coder` value (selectors 0..3 per libjxl `fields.cc`).
fn write_u64(value: u64, w: &mut BitWriter) {
    if value == 0 {
        w.write(2, 0);
    } else if value <= 16 {
        w.write(2, 1);
        w.write(4, value - 1);
    } else if value <= 272 {
        w.write(2, 2);
        w.write(8, value - 17);
    } else {
        w.write(2, 3);
        w.write(12, value & 4095);
        let mut v = value >> 12;
        let mut shift: u32 = 12;
        while v > 0 && shift < 60 {
            w.write(1, 1);
            w.write(8, v & 255);
            v >>= 8;
            shift += 8;
        }
        if v > 0 {
            w.write(1, 1);
            w.write(4, v & 15);
        } else {
            w.write(1, 0);
        }
    }
}

/// Apply a single-symbol patch to a prefix code (mirrors `build_lz_pixel_code`).
fn single_symbol_patch(pc: &mut PrefixCode) {
    let mut nonzero = 0;
    let mut idx = 0;
    for (i, &d) in pc.depths.iter().enumerate() {
        if d != 0 {
            nonzero += 1;
            idx = i;
            if nonzero > 1 {
                break;
            }
        }
    }
    if nonzero == 1 {
        if idx == 0 {
            pc.depths[idx] = 0;
            pc.bits[idx] = 0;
        } else {
            pc.depths[0] = 1;
            pc.bits[0] = 0;
            pc.depths[idx] = 1;
            pc.bits[idx] = 1;
        }
    }
}

/// Build a 41-context prefix code from the predicted ICC byte stream.
fn build_icc_code(enc: &[u8]) -> OwnedEntropyCode {
    use crate::entropy::cluster_histograms;

    let num_contexts = K_NUM_ICC_CONTEXTS;
    // Each context gets its own raw histogram first.
    use crate::entropy::uint_encode;
    let mut histograms: Vec<Histogram> = vec![Histogram::new(); num_contexts];
    for (i, &b) in enc.iter().enumerate() {
        let prev1 = if i > 0 { enc[i - 1] } else { 0 };
        let prev2 = if i > 1 { enc[i - 2] } else { 0 };
        let ctx = iccans_context(i, prev1, prev2);
        let (tok, _, _) = uint_encode(b as u32);
        debug_assert!((tok as usize) < ALPHABET_SIZE);
        histograms[ctx].add(tok);
    }

    let mut context_map: Vec<u8> = Vec::new();
    cluster_histograms(&mut histograms, &mut context_map);

    let mut code = OwnedEntropyCode {
        context_map,
        prefix_codes: build_huffman_codes(&histograms),
        orig_context_map: None,
        orig_num_contexts: num_contexts,
        use_prefix_code: true,
        ans_freqs: Vec::new(),
        ans_symbols: Vec::new(),
    };
    for pc in &mut code.prefix_codes {
        single_symbol_patch(pc);
    }
    code
}

/// Emit the JXL ICC stream right after the color encoding bits.
/// `icc` must be non-empty.
pub(crate) fn write_icc_stream(icc: &[u8], w: &mut BitWriter) {
    assert!(!icc.is_empty(), "ICC profile must be non-empty");
    let enc = predict_icc_minimal(icc);

    // 1. U64 size of the predicted stream.
    write_u64(enc.len() as u64, w);

    // 2. Entropy-coded payload over 41 contexts.
    let code = build_icc_code(&enc);
    // Header: `lz77.enabled = 0`, then context map + prefix codes.
    w.write(1, 0); // LZ77 disabled
    write_entropy_code(&code.as_ref(), w);

    // 3. Emit tokens.
    let code_ref = code.as_ref();
    for (i, &b) in enc.iter().enumerate() {
        let prev1 = if i > 0 { enc[i - 1] } else { 0 };
        let prev2 = if i > 1 { enc[i - 2] } else { 0 };
        let ctx = iccans_context(i, prev1, prev2);
        write_token(Token::new(ctx as u32, b as u32), &code_ref, w);
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn varint_round_trip() {
        let test = [0u64, 1, 126, 127, 128, 255, 16383, 16384, 12345678];
        for &v in &test {
            let mut buf = Vec::new();
            encode_varint(v, &mut buf);
            // Decode manually.
            let mut x = 0u64;
            let mut shift = 0;
            for &b in &buf {
                x |= ((b & 127) as u64) << shift;
                if b & 128 == 0 {
                    break;
                }
                shift += 7;
            }
            assert_eq!(x, v, "varint round-trip {v}");
        }
    }

    #[test]
    fn iccans_context_in_bounds() {
        for i in 0..200 {
            for b1 in [0u8, 1, 16, 100, 200, 255] {
                for b2 in [0u8, 1, 16, 100, 200, 255] {
                    let c = iccans_context(i, b1, b2);
                    assert!(c < K_NUM_ICC_CONTEXTS, "ctx {c} out of range");
                }
            }
        }
    }

    #[test]
    fn minimal_predict_round_trips_via_format() {
        // Construct a fake ICC of 200 bytes (header + 72 tail).
        let mut icc = vec![0u8; 200];
        icc[0..4].copy_from_slice(&(200u32).to_be_bytes());
        icc[8] = 4;
        icc[12..16].copy_from_slice(b"mntr");
        icc[16..20].copy_from_slice(b"RGB ");
        icc[20..24].copy_from_slice(b"XYZ ");
        icc[36..40].copy_from_slice(b"acsp");
        // Fill tail with arbitrary bytes.
        for i in K_ICC_HEADER_SIZE..200 {
            icc[i] = i as u8;
        }

        let enc = predict_icc_minimal(&icc);
        // VarInt(osize=200) = 2 bytes (200 needs 8 bits → 2 varint bytes).
        // VarInt(csize) — depends.
        // commands: VarInt(0) (= 1 byte) + Insert (1 byte) + VarInt(72) (= 1 byte) = 3 bytes
        // Header delta: 128 bytes (mostly zeros — the prediction template matches).
        // Tail: 72 bytes.
        // Total ≈ 2 + 1 + 3 + 128 + 72 = 206 bytes.
        // (Plus the U64 size header at the JXL bit level, which is separate.)
        assert!(
            enc.len() >= 200 && enc.len() <= 220,
            "enc.len() = {}",
            enc.len()
        );

        // Header delta starts at offset = VarInt(osize len) + VarInt(csize len) + csize.
        // For osize=200 (1 varint byte? Actually 200 > 127 so 2 bytes), csize=3 (1 byte).
        // After: 128 bytes of header_data, then 72 tail bytes.
        // First few header_data bytes should be zero (icc matches template at those positions).
    }

    #[test]
    fn write_icc_stream_smoke() {
        // Build a tiny synthetic ICC and verify write_icc_stream produces a non-empty bitstream
        // with the expected leading U64-encoded size.
        let mut icc = vec![0u8; K_ICC_HEADER_SIZE + 16];
        let len = icc.len() as u32;
        icc[0..4].copy_from_slice(&len.to_be_bytes());
        icc[8] = 4;
        icc[12..16].copy_from_slice(b"mntr");
        icc[16..20].copy_from_slice(b"RGB ");
        icc[20..24].copy_from_slice(b"XYZ ");
        icc[36..40].copy_from_slice(b"acsp");
        let mut w = BitWriter::new();
        write_icc_stream(&icc, &mut w);
        w.zero_pad_to_byte();
        let bytes = w.into_bytes();
        assert!(!bytes.is_empty());
    }
}