jixel 0.2.16

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
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
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
/*
 * // 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 super::{NUM_TREE_CONTEXTS, build_balanced_tree_tokens};
use crate::bit_writer::BitWriter;
use crate::coder_scratch::{CoderScratch, LZ77_MAX_CONTEXTS, LzEntropyScratch};
use crate::entropy::{
    EntropyCode, Histogram, Token, build_huffman_codes_into, cluster_histograms_fixed,
    optimize_entropy_code, write_entropy_code, write_token,
};

pub(super) const LZ77_MIN_SYMBOL: u32 = 64;
pub(super) const LZ77_MIN_LENGTH: u32 = 3;
// special_distance[1] = (dx=1, dy=0) -> one token back.
pub(super) const LZ77_DIST_VALUE: u32 = 1;
pub(super) const LZ77_NUM_SPECIAL_DISTANCES: u32 = 120;

/// Hybrid-encode `length_value` (`run_length - LZ77_MIN_LENGTH`).
/// Returns `(alphabet_token, nbits, payload)`.
#[inline]
pub(super) fn lz77_length_encode(length_value: u32) -> (u32, u32, u32) {
    // split_exponent = 4, msb_in_token = 0, lsb_in_token = 0
    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)
    }
}

/// One emission unit in an LZ77-compressed token stream.
#[derive(Clone, Copy)]
pub(crate) struct LzToken {
    context: u32,
    value: u32,
    /// Zero denotes a literal. Encoded LZ77 distances are always at least one.
    distance: u32,
}

impl LzToken {
    #[inline]
    fn pixel(context: u32, value: u32) -> Self {
        Self {
            context,
            value,
            distance: 0,
        }
    }

    #[inline]
    fn lz77(context: u32, length_value: u32, distance_value: u32) -> Self {
        debug_assert_ne!(distance_value, 0);
        Self {
            context,
            value: length_value,
            distance: distance_value,
        }
    }

    #[inline]
    fn is_lz77(self) -> bool {
        self.distance != 0
    }
}

#[inline]
fn fingerprint(tokens: &[Token], pos: usize) -> u32 {
    let mut hash = 0x9e37_79b9u32;
    for token in &tokens[pos..tokens.len().min(pos + 3)] {
        hash ^= token.value.wrapping_mul(0x85eb_ca6b).rotate_left(13);
        hash = hash.wrapping_mul(0xc2b2_ae35) ^ token.context;
    }
    hash
}

fn has_repetition(tokens: &[Token], scratch: &mut Vec<u32>) -> bool {
    const MAX_SAMPLES: usize = 8_192;
    const SAMPLE_TABLE_SIZE: usize = 1 << 14;
    if tokens.len() < 256 {
        return true;
    }
    let stride = tokens.len().div_ceil(MAX_SAMPLES).max(1);
    if scratch.len() < SAMPLE_TABLE_SIZE {
        scratch.resize(SAMPLE_TABLE_SIZE, 0);
    }
    scratch.fill(0);
    let table = scratch;
    let mut samples = 0usize;
    let mut repeats = 0usize;
    for pos in (0..tokens.len().saturating_sub(2)).step_by(stride) {
        let fingerprint = fingerprint(tokens, pos) | 1;
        let slot = fingerprint as usize & (SAMPLE_TABLE_SIZE - 1);
        repeats += usize::from(table[slot] == fingerprint);
        table[slot] = fingerprint;
        samples += 1;
    }
    repeats * 5 >= samples
}

fn match_len(tokens: &[Token], a: usize, b: usize) -> usize {
    const MAX_MATCH: usize = 1 << 20;
    let max_len = (tokens.len() - b).min(MAX_MATCH);
    let mut len = 0usize;
    while len < max_len {
        let x = tokens[a + len];
        let y = tokens[b + len];
        if x.context != y.context || x.value != y.value {
            break;
        }
        len += 1;
        if a + len == b {
            let period = b - a;
            while len < max_len {
                let x = tokens[b + len - period];
                let y = tokens[b + len];
                if x.context != y.context || x.value != y.value {
                    break;
                }
                len += 1;
            }
            break;
        }
    }
    len
}

const RING_HASH_BITS: usize = 17;
const RING_HASH_SIZE: usize = 1 << RING_HASH_BITS;
const RING_BUCKET: usize = 8;

#[inline]
fn ring_hash(tokens: &[Token], pos: usize) -> usize {
    fingerprint(tokens, pos) as usize & (RING_HASH_SIZE - 1)
}

/// Cursor word layout: bits 0..3 = ring write index, bit 3 = "ring wrapped"
/// (all slots live), bits 16.. = epoch stamp. A bucket whose stamp differs
/// from the current call's epoch is logically empty — no per-call memset of
/// the (multi-MB) entry table.
const RING_WRAPPED: u32 = 1 << 3;

#[inline]
fn ring_bucket_state(cursors: &mut [u32], h: usize, epoch: u32) -> u32 {
    let word = cursors[h];
    if word >> 16 != epoch {
        let fresh = epoch << 16;
        cursors[h] = fresh;
        fresh
    } else {
        word
    }
}

#[inline]
fn ring_insert(entries: &mut [u32], cursors: &mut [u32], h: usize, pos: usize, epoch: u32) {
    let word = ring_bucket_state(cursors, h, epoch);
    let idx = (word as usize) & (RING_BUCKET - 1);
    entries[h * RING_BUCKET + idx] = pos as u32;
    let next = (idx + 1) & (RING_BUCKET - 1);
    let wrapped = (word & RING_WRAPPED) | if next == 0 { RING_WRAPPED } else { 0 };
    cursors[h] = (epoch << 16) | wrapped | next as u32;
}

fn find_match_ring(
    tokens: &[Token],
    pos: usize,
    entries: &[u32],
    cursors: &mut [u32],
    max_probes: usize,
    epoch: u32,
) -> (usize, usize) {
    if pos + LZ77_MIN_LENGTH as usize > tokens.len() {
        return (0, 0);
    }
    let h = ring_hash(tokens, pos);
    let base = h * RING_BUCKET;
    let word = ring_bucket_state(cursors, h, epoch);
    let idx = (word as usize) & (RING_BUCKET - 1);
    let live = if word & RING_WRAPPED != 0 {
        RING_BUCKET
    } else {
        idx
    };
    let mut best_len = 0usize;
    let mut best_dist = 0usize;
    // Newest-first scan: on equal lengths the nearest (cheapest) distance wins
    // for free.
    for k in 1..=live.min(max_probes) {
        let slot = (idx + RING_BUCKET - k) % RING_BUCKET;
        let candidate_pos = entries[base + slot] as usize;
        let len = match_len(tokens, candidate_pos, pos);
        if len > best_len {
            best_len = len;
            best_dist = pos - candidate_pos;
        }
    }
    (best_len, best_dist)
}

#[cfg(test)]
fn lz77_compress(tokens: &[Token]) -> Vec<LzToken> {
    let mut scratch = CoderScratch::default();
    lz77_compress_with_depth_into(tokens, 8, &mut scratch.lz_depth, &mut scratch.lz_candidate);
    scratch.lz_candidate.clone()
}

#[derive(Clone)]
struct RunLzTokens<'a> {
    tokens: &'a [Token],
    pos: usize,
    pending: Option<LzToken>,
}

impl<'a> RunLzTokens<'a> {
    fn new(tokens: &'a [Token]) -> Self {
        Self {
            tokens,
            pos: 0,
            pending: None,
        }
    }
}

impl Iterator for RunLzTokens<'_> {
    type Item = LzToken;

    fn next(&mut self) -> Option<Self::Item> {
        if let Some(token) = self.pending.take() {
            return Some(token);
        }
        let token = *self.tokens.get(self.pos)?;
        let mut end = self.pos + 1;
        while end < self.tokens.len()
            && self.tokens[end].context == token.context
            && self.tokens[end].value == token.value
        {
            end += 1;
        }
        let copied = end - self.pos - 1;
        self.pos += 1;
        if copied >= LZ77_MIN_LENGTH as usize {
            self.pending = Some(LzToken::lz77(
                token.context,
                copied as u32 - LZ77_MIN_LENGTH,
                LZ77_DIST_VALUE,
            ));
            self.pos = end;
        }
        Some(LzToken::pixel(token.context, token.value))
    }
}

#[inline]
pub(super) fn lz77_compress_for_speed(
    tokens: &[Token],
    distance_context: u32,
    speed: crate::Speed,
    scratch: &mut CoderScratch,
) -> Vec<LzToken> {
    // Fast stays runs-only
    if speed != crate::Speed::Slow || !has_repetition(tokens, &mut scratch.lz_repetitions) {
        return lz77_compress_runs(tokens);
    }
    lz77_compress_with_depth_into(tokens, 8, &mut scratch.lz_depth, &mut scratch.lz_candidate);
    let run_token_count = run_token_count(tokens);
    if scratch.lz_candidate.len() * 100 > run_token_count * 90 {
        return lz77_compress_runs(tokens);
    }
    let deep_bits = estimate_payload_bits(
        scratch.lz_candidate.iter().copied(),
        distance_context,
        &mut scratch.lz_entropy,
        &mut scratch.huffman_pool,
    );
    let run_bits = estimate_payload_bits(
        RunLzTokens::new(tokens),
        distance_context,
        &mut scratch.lz_entropy,
        &mut scratch.huffman_pool,
    );
    if deep_bits * 100 <= run_bits * 90 {
        scratch.lz_candidate.clone()
    } else {
        lz77_compress_runs(tokens)
    }
}

fn estimate_payload_bits<I>(
    tokens: I,
    distance_context: u32,
    scratch: &mut LzEntropyScratch,
    huffman_pool: &mut Vec<crate::entropy::HuffmanNode>,
) -> u64
where
    I: Iterator<Item = LzToken> + Clone,
{
    let num_contexts = distance_context as usize + 1;
    assert!(num_contexts <= LZ77_MAX_CONTEXTS);
    let histograms = &mut scratch.histograms[..num_contexts];
    histograms.fill(Histogram::new());
    for (context, slot) in scratch.context_map[..num_contexts].iter_mut().enumerate() {
        *slot = context as u8;
    }
    lz_add_histograms(
        tokens.clone(),
        &scratch.context_map[..num_contexts],
        histograms,
        LZ77_MIN_SYMBOL,
        distance_context,
    );
    let codes = &mut scratch.prefix_codes[..num_contexts];
    build_huffman_codes_into(histograms, codes, huffman_pool);
    let mut bits = 0u64;
    for token in tokens {
        if token.is_lz77() {
            let (symbol, nbits, _) = lz77_length_encode(token.value);
            bits += codes[token.context as usize].depths[(LZ77_MIN_SYMBOL + symbol) as usize]
                as u64
                + nbits as u64;
            let (symbol, nbits, _) = crate::entropy::uint_encode(token.distance);
            bits += codes[distance_context as usize].depths[symbol as usize] as u64 + nbits as u64;
        } else {
            let (symbol, nbits, _) = crate::entropy::uint_encode(token.value);
            bits += codes[token.context as usize].depths[symbol as usize] as u64 + nbits as u64;
        }
    }
    bits
}

fn run_token_count(tokens: &[Token]) -> usize {
    let mut count = 0usize;
    let mut i = 0usize;
    while i < tokens.len() {
        count += 1;
        let token = tokens[i];
        let mut end = i + 1;
        while end < tokens.len()
            && tokens[end].context == token.context
            && tokens[end].value == token.value
        {
            end += 1;
        }
        if end - i > LZ77_MIN_LENGTH as usize {
            count += 1;
            i = end;
        } else {
            i += 1;
        }
    }
    count
}

pub(super) fn lz77_compress_runs(tokens: &[Token]) -> Vec<LzToken> {
    let mut out = Vec::with_capacity(run_token_count(tokens));
    out.extend(RunLzTokens::new(tokens));
    out
}

fn lz77_compress_with_depth_into(
    tokens: &[Token],
    max_probes: usize,
    scratch: &mut Vec<u32>,
    out: &mut Vec<LzToken>,
) {
    out.clear();
    debug_assert!(
        out.capacity() >= tokens.len(),
        "LZ77 candidate scratch was not fully preallocated"
    );
    const ENTRIES_LEN: usize = RING_HASH_SIZE * RING_BUCKET;
    let total = ENTRIES_LEN + RING_HASH_SIZE + 1;
    if scratch.len() < total {
        scratch.clear();
        scratch.resize(total, 0);
    }
    let (entries, rest) = scratch.split_at_mut(ENTRIES_LEN);
    let (cursors, epoch_word) = rest.split_at_mut(RING_HASH_SIZE);
    let mut epoch = (epoch_word[0] + 1) & 0xffff;
    if epoch == 0 {
        cursors.fill(0);
        epoch = 1;
    }
    epoch_word[0] = epoch;
    let mut i = 0usize;
    while i < tokens.len() {
        let (match_len, distance) = find_match_ring(tokens, i, entries, cursors, max_probes, epoch);
        let threshold = if distance <= 16 { 4 } else { 5 };
        if match_len >= threshold {
            let distance_value = if distance == 1 {
                LZ77_DIST_VALUE
            } else {
                LZ77_NUM_SPECIAL_DISTANCES + distance as u32 - 1
            };
            out.push(LzToken::lz77(
                tokens[i].context,
                match_len as u32 - LZ77_MIN_LENGTH,
                distance_value,
            ));
            for pos in i..i + match_len {
                ring_insert(entries, cursors, ring_hash(tokens, pos), pos, epoch);
            }
            i += match_len;
        } else {
            let token = tokens[i];
            out.push(LzToken::pixel(token.context, token.value));
            ring_insert(entries, cursors, ring_hash(tokens, i), i, epoch);
            i += 1;
        }
    }
}

fn lz_add_histograms<I>(
    toks: I,
    context_map: &[u8],
    histograms: &mut [Histogram],
    min_symbol: u32,
    distance_context: u32,
) where
    I: IntoIterator<Item = LzToken>,
{
    for t in toks {
        if t.is_lz77() {
            let (len_tok, _, _) = lz77_length_encode(t.value);
            let pixel_cluster = context_map[t.context as usize] as usize;
            histograms[pixel_cluster].add(min_symbol + len_tok);

            let dist_cluster = context_map[distance_context as usize] as usize;
            let (symbol, _, _) = crate::entropy::uint_encode(t.distance);
            histograms[dist_cluster].add(symbol);
        } else {
            let (sym, _, _) = crate::entropy::uint_encode(t.value);
            let cluster = context_map[t.context as usize] as usize;
            histograms[cluster].add(sym);
        }
    }
}

/// Build per-cluster prefix codes from an `LzToken` stream.
/// `nb_chans + 1` contexts: `nb_chans` channel leaves + 1 distance context.
pub(super) fn build_lz_pixel_code<'tokens, 'scratch, I>(
    streams: I,
    nb_chans: usize,
    min_symbol: u32,
    refined: bool,
    scratch: &'scratch mut LzEntropyScratch,
    huffman_pool: &mut Vec<crate::entropy::HuffmanNode>,
) -> EntropyCode<'scratch>
where
    I: Iterator<Item = &'tokens [LzToken]> + Clone,
{
    let distance_context = nb_chans as u32;
    let num_contexts = nb_chans + 1;
    assert!(num_contexts <= LZ77_MAX_CONTEXTS);
    let refined = refined
        && streams.clone().any(|toks| {
            toks.iter()
                .any(|token| token.is_lz77() && token.distance != LZ77_DIST_VALUE)
        });
    let LzEntropyScratch {
        histograms,
        prefix_codes,
        context_map,
        configs,
        clustering,
    } = scratch;
    let histograms = &mut histograms[..num_contexts];
    histograms.fill(Histogram::new());
    for (context, slot) in context_map[..num_contexts].iter_mut().enumerate() {
        *slot = context as u8;
    }
    for toks in streams.clone() {
        lz_add_histograms(
            toks.iter().copied(),
            &context_map[..num_contexts],
            histograms,
            min_symbol,
            distance_context,
        );
    }

    let num_clusters = cluster_histograms_fixed(
        histograms,
        &mut context_map[..num_contexts],
        refined,
        clustering,
        huffman_pool,
    );
    let histograms = &mut histograms[..num_clusters];
    let configs = &mut configs[..num_clusters];

    if refined {
        let mut raw_values = vec![Vec::<u32>::new(); num_clusters];
        let mut literal_values = vec![Vec::<u32>::new(); num_clusters];
        for toks in streams.clone() {
            for &tok in toks {
                if tok.is_lz77() {
                    raw_values[context_map[distance_context as usize] as usize].push(tok.distance);
                } else {
                    let cluster = context_map[tok.context as usize] as usize;
                    raw_values[cluster].push(tok.value);
                    literal_values[cluster].push(tok.value);
                }
            }
        }
        for (cluster, values) in raw_values.iter().enumerate() {
            let selected = crate::entropy::select_hybrid_config(values, huffman_pool);
            configs[cluster] = if literal_values[cluster].iter().all(|&value| {
                crate::entropy::uint_encode_with_config(value, selected).0 < min_symbol
            }) {
                selected
            } else {
                crate::entropy::HybridUintConfig::DEFAULT
            };
        }
        histograms.fill(Histogram::new());
        for toks in streams {
            for &tok in toks {
                if tok.is_lz77() {
                    let (len_tok, _, _) = lz77_length_encode(tok.value);
                    histograms[context_map[tok.context as usize] as usize]
                        .add(min_symbol + len_tok);
                    let cluster = context_map[distance_context as usize] as usize;
                    let (symbol, _, _) =
                        crate::entropy::uint_encode_with_config(tok.distance, configs[cluster]);
                    histograms[cluster].add(symbol);
                } else {
                    let cluster = context_map[tok.context as usize] as usize;
                    let (symbol, _, _) =
                        crate::entropy::uint_encode_with_config(tok.value, configs[cluster]);
                    histograms[cluster].add(symbol);
                }
            }
        }
    } else {
        configs.fill(crate::entropy::HybridUintConfig::DEFAULT);
    }

    let prefix_codes = &mut prefix_codes[..num_clusters];
    build_huffman_codes_into(histograms, prefix_codes, huffman_pool);

    // Apply the single-symbol patch (mirrors build_pixel_code) per cluster so
    // that contexts with one unique symbol still emit a parseable code.
    for pc in prefix_codes.iter_mut() {
        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;
            }
        }
    }
    EntropyCode {
        context_map: &context_map[..num_contexts],
        num_contexts,
        prefix_codes,
        hybrid_uint_configs: configs,
        num_prefix_codes: num_clusters,
        orig_context_map: None,
        orig_num_contexts: num_contexts,
        use_prefix_code: true,
        ans_histograms: &[],
        ans_symbols: &[],
        ans_reverse_maps: &[],
    }
}

/// Emit one `LzToken` into the bitstream.
#[inline]
pub(super) fn write_lz_token(
    t: LzToken,
    distance_context: u32,
    code: &EntropyCode<'_>,
    min_symbol: u32,
    w: &mut BitWriter,
) {
    if t.is_lz77() {
        let (len_tok, len_nbits, len_bits) = lz77_length_encode(t.value);
        let sym = min_symbol + len_tok;
        let pcluster = code.context_map[t.context as usize] as usize;
        let pc = &code.prefix_codes[pcluster];
        let d = pc.depths[sym as usize] as usize;
        debug_assert!(
            d > 0,
            "LZ77 length symbol {} unrepresented in histogram",
            sym
        );
        let data = (pc.bits[sym as usize] as u64) | ((len_bits as u64) << d);
        w.write(d + len_nbits as usize, data);

        let dcluster = code.context_map[distance_context as usize] as usize;
        let dc = &code.prefix_codes[dcluster];
        let (dist_symbol, dist_nbits, dist_bits) =
            crate::entropy::uint_encode_with_config(t.distance, code.hybrid_uint_configs[dcluster]);
        let dd = dc.depths[dist_symbol as usize] as usize;
        if dd > 0 {
            let data = dc.bits[dist_symbol as usize] as u64 | ((dist_bits as u64) << dd);
            w.write(dd + dist_nbits as usize, data);
        } else if dist_nbits != 0 {
            w.write(dist_nbits as usize, dist_bits as u64);
        }
    } else {
        let cluster = code.context_map[t.context as usize] as usize;
        let (sym, nbits, bits) =
            crate::entropy::uint_encode_with_config(t.value, code.hybrid_uint_configs[cluster]);
        let pc = &code.prefix_codes[cluster];
        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);
    }
}
/// Write the LZ77 sub-bundle (matches `LZ77Params::VisitFields` and `DecodeUintConfig`):
///   1 bit:  enabled = 1
///   U32 min_symbol:  U32(Val(224), Val(512), Val(4096), BitsOffset(15, 8))
///                    For LZ77_MIN_SYMBOL = 64: selector 3 → "11" + 15 bits (64 - 8) = 56
///   U32 min_length:  U32(Val(3), Val(4), BitsOffset(2, 5), BitsOffset(8, 9))
///                    For LZ77_MIN_LENGTH = 3: selector 0 → "00"
///   length_uint_config: DecodeUintConfig(log_alpha_size = 8).
///                       split_exp = 4 (in CeilLog2(8+1) = 4 bits = "0010" LSB-first),
///                       msb_in_token = 0 (in CeilLog2(4+1) = 3 bits = "000"),
///                       lsb_in_token = 0 (in CeilLog2(4-0+1) = 3 bits = "000").
fn write_lz77_header(min_symbol: u32, w: &mut BitWriter) {
    w.write(1, 1); // enabled
    // min_symbol: selector 3 (Bits(15) + 8), value 64 → payload = 56
    w.write(2, 0b11);
    w.write(15, (min_symbol - 8) as u64);
    // min_length: selector 0 (Val(3))
    w.write(2, 0b00);
    // length_uint_config (split=4, msb=0, lsb=0):
    w.write(4, 4);
    w.write(3, 0);
    w.write(3, 0);
}

/// Write the local tree + LZ77-enabled pixel histograms, then return.
/// The pixel `code` must have `nb_chans + 1` contexts (last = distance).
pub(super) fn write_local_tree_lz77(
    predictors: &[u32],
    pixel_code: &EntropyCode<'_>,
    min_symbol: u32,
    huffman_pool: &mut Vec<crate::entropy::HuffmanNode>,
    w: &mut BitWriter,
) {
    let tree_tokens = build_balanced_tree_tokens(predictors);
    write_tree_lz77(&tree_tokens, pixel_code, min_symbol, huffman_pool, w);
}

/// Write a pre-built MA tree (token stream) + the LZ77 pixel code header.
pub(super) fn write_tree_lz77(
    tree_tokens: &[Token],
    pixel_code: &EntropyCode<'_>,
    min_symbol: u32,
    huffman_pool: &mut Vec<crate::entropy::HuffmanNode>,
    w: &mut BitWriter,
) {
    let tree_code = optimize_entropy_code(tree_tokens, NUM_TREE_CONTEXTS, huffman_pool);
    let tree_code_ref = tree_code.as_ref();

    // Tree's entropy code: no LZ77 in the tree itself.
    w.write(1, 0);
    write_entropy_code(&tree_code_ref, huffman_pool, w);
    for tok in tree_tokens {
        write_token(*tok, &tree_code_ref, w);
    }

    // Pixel entropy code: LZ77 ENABLED for the main bitstream.
    write_lz77_header(min_symbol, w);
    // The decoder appends an extra context (distance) when LZ77 is on, so the
    // context map we write must already include it as its last entry.
    write_entropy_code(pixel_code, huffman_pool, w);
}

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

    fn expand(stream: &[LzToken]) -> Vec<Token> {
        let mut out = Vec::new();
        for &token in stream {
            if token.is_lz77() {
                let distance = if token.distance == LZ77_DIST_VALUE {
                    1
                } else {
                    (token.distance - LZ77_NUM_SPECIAL_DISTANCES + 1) as usize
                };
                for _ in 0..token.value + LZ77_MIN_LENGTH {
                    let source = out.len() - distance;
                    out.push(out[source]);
                }
            } else {
                out.push(Token::new(token.context, token.value));
            }
        }
        out
    }

    fn same_tokens(a: &[Token], b: &[Token]) -> bool {
        a.len() == b.len()
            && a.iter()
                .zip(b)
                .all(|(a, b)| a.context == b.context && a.value == b.value)
    }

    #[test]
    fn hash_chain_finds_non_run_matches_and_round_trips() {
        let pattern: Vec<Token> = (0..37)
            .map(|i| Token::new((i % 3) as u32, ((i * 29 + i * i) % 251) as u32))
            .collect();
        let mut input = pattern.clone();
        input.extend((0..11).map(|i| Token::new(1, 900 + i)));
        input.extend_from_slice(&pattern);
        input.extend_from_slice(&pattern);
        let compressed = lz77_compress(&input);
        assert!(
            compressed
                .iter()
                .any(|token| token.is_lz77() && token.distance >= LZ77_NUM_SPECIAL_DISTANCES)
        );
        assert!(same_tokens(&expand(&compressed), &input));
    }

    #[test]
    fn hash_chain_uses_compact_distance_for_runs() {
        let input = vec![Token::new(0, 7); 128];
        let compressed = lz77_compress(&input);
        assert!(
            compressed
                .iter()
                .any(|token| token.is_lz77() && token.distance == LZ77_DIST_VALUE)
        );
        assert!(same_tokens(&expand(&compressed), &input));
    }

    #[test]
    fn lz_token_is_compact() {
        assert_eq!(std::mem::size_of::<LzToken>(), 12);
    }

    #[test]
    fn fixed_context_storage_covers_the_largest_squeeze_tree() {
        let steps = crate::squeeze::default_squeeze_steps(
            crate::encode_image::MAX_DIMENSION,
            crate::encode_image::MAX_DIMENSION,
            4,
        );
        let contexts = 4 * (steps.len() + 1) + 1;
        assert_eq!(steps.len(), 54);
        assert_eq!(contexts, LZ77_MAX_CONTEXTS);
    }

    #[test]
    fn speed_policy_keeps_fast_run_only_and_slow_structured_search() {
        let pattern: Vec<Token> = (0..64)
            .map(|i| Token::new((i % 3) as u32, ((i * 37 + 11) % 257) as u32))
            .collect();
        let input: Vec<Token> = pattern.iter().copied().cycle().take(512).collect();
        let mut scratch = CoderScratch::default();
        let fast = lz77_compress_for_speed(&input, 3, crate::Speed::Fast, &mut scratch);
        assert!(
            !fast
                .iter()
                .any(|token| token.is_lz77() && token.distance != LZ77_DIST_VALUE)
        );
        let slow = lz77_compress_for_speed(&input, 3, crate::Speed::Slow, &mut scratch);
        assert!(
            slow.iter()
                .any(|token| token.is_lz77() && token.distance != LZ77_DIST_VALUE)
        );
        assert!(same_tokens(&expand(&slow), &input));
    }

    fn tokens(n: usize, period: usize) -> Vec<Token> {
        (0..n)
            .map(|i| Token::new((i % 3) as u32, (i % period) as u32))
            .collect()
    }

    #[test]
    fn hash_chain_scratch_is_reset_between_calls() {
        let big = tokens(200_000, 7);
        let small = tokens(5_000, 7);
        let clean = std::thread::spawn({
            let small = small.clone();
            move || {
                let mut scratch = Vec::new();
                let mut out = Vec::with_capacity(small.len());
                lz77_compress_with_depth_into(&small, 8, &mut scratch, &mut out);
                out.len()
            }
        })
        .join()
        .unwrap();
        let mut scratch = Vec::new();
        let mut out = Vec::with_capacity(big.len());
        lz77_compress_with_depth_into(&big, 8, &mut scratch, &mut out);
        lz77_compress_with_depth_into(&small, 8, &mut scratch, &mut out);
        assert_eq!(clean, out.len());
    }

    #[test]
    fn deep_search_handles_varied_stream_lengths() {
        let mut scratch = Vec::new();
        let mut out = Vec::with_capacity(50_000);
        for len in [1_000usize, 50_000, 3_000] {
            lz77_compress_with_depth_into(&tokens(len, 5), 8, &mut scratch, &mut out);
        }
    }
}