jixel 0.2.22

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
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
/*
 * // 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::adaptive_quant::dirty_log2f;
use crate::bit_writer::BitWriter;
use crate::entropy::{
    Histogram, OwnedEntropyCode, Token, build_huffman_codes, cluster_histograms, uint_encode,
    write_entropy_code,
};

pub(crate) const LZ77_MIN_SYMBOL: u32 = 64;
pub(crate) const LZ77_MIN_LENGTH: u32 = 3;
pub(crate) const LZ77_DIST_VALUE: u32 = 0;

#[inline]
pub(crate) fn lz77_length_encode(length_value: u32) -> (u32, u32, u32) {
    if length_value < 16 {
        (length_value, 0, 0)
    } else {
        let n = 31 - length_value.leading_zeros();
        let token = 16 + n - 4;
        let nbits = n;
        let bits = length_value - (1 << n);
        (token, nbits, bits)
    }
}

#[derive(Clone, Copy)]
pub(crate) enum AcLz {
    /// A literal AC token, emitted via the normal uint_encode path.
    Lit { context: u32, value: u32 },
    /// Back-reference: copy `length_value + LZ77_MIN_LENGTH` previous tokens.
    /// The length symbol is coded on `context` (the repeated token's context),
    /// then a distance symbol on the distance context.
    Copy { context: u32, length_value: u32 },
}

/// Collapse runs of identical (context, value) AC tokens into back-references.
pub(crate) fn lz77_compress_ac(tokens: &[Token]) -> Vec<AcLz> {
    // Collapse runs of identical AC tokens into a literal + distance-1 back-ref.
    let n = tokens.len();
    let mut out: Vec<AcLz> = Vec::with_capacity(n);
    let mut i = 0;
    while i < n {
        let t = tokens[i];
        out.push(AcLz::Lit {
            context: t.context,
            value: t.value,
        });
        let mut j = i + 1;
        while j < n && tokens[j].context == t.context && tokens[j].value == t.value {
            j += 1;
        }
        let run_extra = (j - i - 1) as u32; // copies after the first literal
        if run_extra >= LZ77_MIN_LENGTH && t.value != 0 {
            out.push(AcLz::Copy {
                context: t.context,
                length_value: run_extra - LZ77_MIN_LENGTH,
            });
            i = j;
        } else {
            i += 1;
        }
    }
    out
}
#[allow(dead_code)] // kept for a future (correct) LZ77 alpha path; see modular::write_ac_group_alpha
pub(crate) fn build_lz_code_no_cluster(
    streams: &[Vec<AcLz>],
    num_contexts: usize,
    huffman_pool: &mut Vec<crate::entropy::HuffmanNode>,
) -> OwnedEntropyCode {
    let distance_context = (num_contexts - 1) as u32;
    let mut histograms = vec![Histogram::new(); num_contexts];
    for stream in streams {
        for t in stream {
            match *t {
                AcLz::Lit { context, value } => {
                    let (sym, _, _) = uint_encode(value);
                    histograms[context as usize].add(sym);
                }
                AcLz::Copy {
                    context,
                    length_value,
                } => {
                    let (len_tok, _, _) = lz77_length_encode(length_value);
                    histograms[context as usize].add(LZ77_MIN_SYMBOL + len_tok);
                    histograms[distance_context as usize].add(LZ77_DIST_VALUE);
                }
            }
        }
    }
    let context_map: Vec<u8> = (0..num_contexts as u8).collect();
    let mut prefix_codes = build_huffman_codes(&histograms, huffman_pool);

    for pc in &mut prefix_codes {
        let mut nonzero = 0usize;
        let mut idx = 0usize;
        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[0] = 0;
                pc.bits[0] = 0;
            } else {
                pc.depths[0] = 1;
                pc.bits[0] = 0;
                pc.depths[idx] = 1;
                pc.bits[idx] = 1;
            }
        }
        pc.update_single_symbol();
    }
    OwnedEntropyCode {
        context_map,
        prefix_codes,
        hybrid_uint_configs: vec![crate::entropy::HybridUintConfig::DEFAULT; num_contexts],
        orig_context_map: None,
        orig_num_contexts: num_contexts,
        use_prefix_code: true,
        ans_histograms: Vec::new(),
        ans_pricing_freqs: Vec::new(),
        ans_symbols: Vec::new(),
        ans_reverse_maps: Vec::new(),
    }
}

/// Build per-context histograms over the LZ-compressed stream, then cluster
/// them (libjxl-tiny clusters to <= 8). `num_contexts` already includes the
/// trailing distance context. Returns an `OwnedEntropyCode` whose
/// `orig_context_map` has `num_contexts` entries (the distance context is the
/// last), so `write_entropy_code` signals it correctly.
pub(crate) fn build_ac_lz_code(
    streams: &[Vec<AcLz>],
    num_contexts: usize,
    huffman_pool: &mut Vec<crate::entropy::HuffmanNode>,
) -> OwnedEntropyCode {
    let distance_context = (num_contexts - 1) as u32;
    let mut histograms = vec![Histogram::new(); num_contexts];
    for stream in streams {
        for t in stream {
            match *t {
                AcLz::Lit { context, value } => {
                    let (sym, _, _) = uint_encode(value);
                    histograms[context as usize].add(sym);
                }
                AcLz::Copy {
                    context,
                    length_value,
                } => {
                    let (len_tok, _, _) = lz77_length_encode(length_value);
                    histograms[context as usize].add(LZ77_MIN_SYMBOL + len_tok);
                    histograms[distance_context as usize].add(LZ77_DIST_VALUE);
                }
            }
        }
    }

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

    OwnedEntropyCode {
        context_map,
        prefix_codes,
        hybrid_uint_configs: vec![crate::entropy::HybridUintConfig::DEFAULT; histograms.len()],
        orig_context_map: None,
        orig_num_contexts: num_contexts,
        use_prefix_code: true,
        ans_histograms: Vec::new(),
        ans_pricing_freqs: Vec::new(),
        ans_symbols: Vec::new(),
        ans_reverse_maps: Vec::new(),
    }
}

/// Estimate the encoded size in bits of an LZ stream under `code`, including
/// the literal/length prefix-code bits and the hybrid-uint extra bits and the
/// distance symbols. Used to decide whether LZ77 is worth enabling.
pub(crate) fn estimate_ac_lz_bits(
    streams: &[Vec<AcLz>],
    code: &OwnedEntropyCode,
    num_contexts: usize,
) -> u64 {
    let distance_context = num_contexts - 1;
    let mut bits: u64 = 0;
    for stream in streams {
        for t in stream {
            match *t {
                AcLz::Lit { context, value } => {
                    let (sym, nbits, _) = uint_encode(value);
                    let cl = code.context_map[context as usize] as usize;
                    let pc = &code.prefix_codes[cl];
                    let d = if pc.single_symbol {
                        0
                    } else {
                        pc.depths[sym as usize] as u64
                    };
                    bits += d + nbits as u64;
                }
                AcLz::Copy {
                    context,
                    length_value,
                } => {
                    let (len_tok, len_nbits, _) = lz77_length_encode(length_value);
                    let sym = LZ77_MIN_SYMBOL + len_tok;
                    let cl = code.context_map[context as usize] as usize;
                    let pc = &code.prefix_codes[cl];
                    let d = if pc.single_symbol {
                        0
                    } else {
                        pc.depths[sym as usize] as u64
                    };
                    bits += d + len_nbits as u64;
                    let (dsym, dnbits, _) = uint_encode(LZ77_DIST_VALUE);
                    let dcl = code.context_map[distance_context] as usize;
                    let dpc = &code.prefix_codes[dcl];
                    let dd = if dpc.single_symbol {
                        0
                    } else {
                        dpc.depths[dsym as usize] as u64
                    };
                    bits += dd + dnbits as u64;
                }
            }
        }
    }
    bits
}

pub(crate) fn estimate_ac_plain_bits<'a, I>(streams: I, code: &OwnedEntropyCode) -> u64
where
    I: IntoIterator<Item = &'a [Token]>,
{
    if !code.use_prefix_code {
        // rANS approaches the histogram entropy: a symbol with normalized
        // frequency `f` out of `ANS_TAB_SIZE` costs -log2(f / ANS_TAB_SIZE).
        let cost: Vec<Vec<f32>> = code
            .ans_histograms
            .iter()
            .map(|histogram| {
                histogram
                    .freqs
                    .iter()
                    .map(|&f| {
                        if f == 0 {
                            crate::entropy::ANS_LOG_TAB_SIZE as f32
                        } else {
                            crate::entropy::ANS_LOG_TAB_SIZE as f32 - dirty_log2f(f as f32)
                        }
                    })
                    .collect()
            })
            .collect();
        let mut bits = 0.0f64;
        for tokens in streams {
            for t in tokens {
                let cl = code.context_map[t.context as usize] as usize;
                let (sym, nbits, _) =
                    crate::entropy::uint_encode_with_config(t.value, code.hybrid_uint_configs[cl]);
                bits += cost[cl][sym as usize] as f64 + nbits as f64;
            }
        }
        return bits as u64;
    }
    let mut bits: u64 = 0;
    for tokens in streams {
        for t in tokens {
            let cl = code.context_map[t.context as usize] as usize;
            let (sym, nbits, _) =
                crate::entropy::uint_encode_with_config(t.value, code.hybrid_uint_configs[cl]);
            bits += code.prefix_codes[cl].depths[sym as usize] as u64 + nbits as u64;
        }
    }
    bits
}
#[inline]
pub(crate) fn write_ac_lz(
    t: AcLz,
    code: &OwnedEntropyCode,
    num_contexts: usize,
    w: &mut BitWriter,
) {
    let distance_context = num_contexts - 1;
    match t {
        AcLz::Lit { context, value } => {
            let (sym, nbits, bits) = uint_encode(value);
            let cluster = code.context_map[context as usize] as usize;
            let pc = &code.prefix_codes[cluster];
            if pc.single_symbol {
                w.write(nbits as usize, bits as u64);
            } else {
                let d = pc.depths[sym as usize] as usize;
                let data = (pc.bits[sym as usize] as u64) | ((bits as u64) << d);
                w.write(d + nbits as usize, data);
            }
        }
        AcLz::Copy {
            context,
            length_value,
        } => {
            let (len_tok, len_nbits, len_bits) = lz77_length_encode(length_value);
            let sym = LZ77_MIN_SYMBOL + len_tok;
            let pcluster = code.context_map[context as usize] as usize;
            let pc = &code.prefix_codes[pcluster];
            if pc.single_symbol {
                w.write(len_nbits as usize, len_bits as u64);
            } else {
                let d = pc.depths[sym as usize] as usize;
                debug_assert!(d > 0, "LZ77 AC length symbol {} unrepresented", sym);
                let data = (pc.bits[sym as usize] as u64) | ((len_bits as u64) << d);
                w.write(d + len_nbits as usize, data);
            }

            // Distance symbol: value LZ77_DIST_VALUE, coded on the distance ctx.
            let (dsym, dnbits, dbits) = uint_encode(LZ77_DIST_VALUE);
            let dcluster = code.context_map[distance_context] as usize;
            let dpc = &code.prefix_codes[dcluster];
            if dpc.single_symbol {
                w.write(dnbits as usize, dbits as u64);
            } else {
                let dd = dpc.depths[dsym as usize] as usize;
                let ddata = (dpc.bits[dsym as usize] as u64) | ((dbits as u64) << dd);
                w.write(dd + dnbits as usize, ddata);
            }
        }
    }
}

/// Write the AC LZ77 sub-bundle header (mirrors `write_lz77_header` in the
/// lossless path): enabled bit + min_symbol (64) + min_length (3) +
/// length_uint_config(split=4, msb=0, lsb=0). Then the entropy code.
pub(crate) fn write_ac_lz_header_and_code(
    code: &OwnedEntropyCode,
    huffman_pool: &mut Vec<crate::entropy::HuffmanNode>,
    w: &mut BitWriter,
) {
    w.write(1, 1); // lz77 enabled
    // min_symbol: U32(Val(224), Val(512), Val(4096), BitsOffset(15,8)).
    // For 64: selector 3 -> "11" + 15 bits of (64 - 8) = 56.
    w.write(2, 0b11);
    w.write(15, (LZ77_MIN_SYMBOL - 8) as u64);
    // min_length: U32(Val(3), ...). For 3: selector 0.
    w.write(2, 0b00);
    // length_uint_config: split_exp=4 (4 bits), msb=0 (3 bits), lsb=0 (3 bits).
    w.write(4, 4);
    w.write(3, 0);
    w.write(3, 0);
    // The entropy code: its context map already carries the trailing distance
    // context as the last (orig_num_contexts-th) entry.
    write_entropy_code(&code.as_ref(), huffman_pool, w);
}

#[cfg(test)]
mod tests {
    use super::estimate_ac_plain_bits;
    use crate::ac_context::K_NUM_AC_CONTEXTS;
    use crate::entropy::{Token, optimize_entropy_code_ac};

    /// A skewed AC stream is coded with rANS, which beats the Huffman floor of
    /// 1 bit/symbol. The plain estimate must reflect that, otherwise the LZ77
    /// comparison in `enc_frame` sees an inflated plain cost and switches to a
    /// prefix-coded LZ77 bundle that is actually larger.
    #[test]
    fn plain_estimate_prices_the_ans_path_below_the_huffman_floor() {
        // 99% zeros in one context: entropy is ~0.08 bit/symbol, Huffman 1.0.
        let tokens: Vec<Token> = (0..20_000)
            .map(|i| Token {
                context: 0,
                value: u32::from(i % 100 == 0),
            })
            .collect();
        let mut scratch = crate::coder_scratch::CoderScratch::default();
        let code = optimize_entropy_code_ac(&tokens, K_NUM_AC_CONTEXTS, &mut scratch.huffman_pool);
        assert!(
            !code.use_prefix_code,
            "expected the rANS path for this stream"
        );

        let estimate = estimate_ac_plain_bits(std::iter::once(tokens.as_slice()), &code);
        let huffman_floor = tokens.len() as u64;
        assert!(
            estimate < huffman_floor / 2,
            "ANS estimate {estimate} should be far below the {huffman_floor}-bit Huffman floor"
        );
    }
}

#[cfg(test)]
mod lz77_distance_tests {
    use super::{AcLz, LZ77_DIST_VALUE, LZ77_MIN_LENGTH, lz77_compress_ac, lz77_length_encode};
    use crate::entropy::Token;

    /// Model of the JXL reader: a back-reference copies `length` symbols from
    /// `distance` back, where `distance = written_value + 1` because these
    /// streams carry no special-distance table, and the reader clamps a distance
    /// that reaches past the start of the stream.
    fn decode(stream: &[AcLz]) -> Vec<(u32, u32)> {
        let mut out: Vec<(u32, u32)> = Vec::new();
        for item in stream {
            match *item {
                AcLz::Lit { context, value } => out.push((context, value)),
                AcLz::Copy {
                    context: _,
                    length_value,
                } => {
                    let length = length_value + LZ77_MIN_LENGTH;
                    let distance = (LZ77_DIST_VALUE + 1).min(out.len() as u32).max(1) as usize;
                    for _ in 0..length {
                        let src = out.len() - distance;
                        out.push(out[src]);
                    }
                }
            }
        }
        out
    }

    /// The compressor and the reader must agree on the distance convention. With
    /// the historical value of 1 (i.e. distance 2) this fails for any run that
    /// has history in front of it — which is why the bug survived: a run at the
    /// very start of a stream decodes correctly thanks to the reader's clamp.
    #[test]
    fn lz77_round_trips_including_runs_with_history() {
        let cases: Vec<Vec<Token>> = vec![
            vec![Token::new(0, 5); 8],
            {
                let mut v = vec![Token::new(0, 9), Token::new(0, 3)];
                v.extend(std::iter::repeat_n(Token::new(0, 7), 10));
                v
            },
            {
                let mut v = Vec::new();
                for i in 0..6u32 {
                    v.push(Token::new(0, i));
                    v.extend(std::iter::repeat_n(Token::new(0, 100 + i), 5));
                }
                v
            },
        ];
        for tokens in cases {
            let expected: Vec<(u32, u32)> = tokens.iter().map(|t| (t.context, t.value)).collect();
            let compressed = lz77_compress_ac(&tokens);
            assert_eq!(decode(&compressed), expected);
        }
    }

    /// A length symbol must stay inside the alphabet the prefix code covers.
    #[test]
    fn lz77_length_tokens_stay_in_alphabet() {
        for length_value in [0u32, 1, 7, 63, 255, 4095] {
            let (tok, nbits, _) = lz77_length_encode(length_value);
            assert!(tok < 64, "length token {tok} escapes the alphabet");
            assert!(nbits <= 32);
        }
    }
}