jixel 0.2.23

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
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
/*
 * // 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::coder_scratch::CoderScratch;
use crate::encode_image::AlphaPlane;
use crate::entropy::{
    HuffmanNode, OwnedEntropyCode, Token, optimize_entropy_code, pack_signed, write_entropy_code,
    write_prefix_codes, write_token,
};
use std::sync::OnceLock;

const TREE_CTX_SPLITVAL: u32 = 0;
const TREE_CTX_PROPERTY: u32 = 1;
const TREE_CTX_PREDICTOR: u32 = 2;
const TREE_CTX_OFFSET: u32 = 3;
const TREE_CTX_MULTIPLIER_LOG: u32 = 4;
const TREE_CTX_MULTIPLIER_BITS: u32 = 5;
const NUM_TREE_CONTEXTS: usize = 6;
const PREDICTOR_GRADIENT: u32 = 5;

/// AC group dimension in pixels.  Matches `K_GROUP_DIM` in enc_frame.rs.
const GROUP_DIM: usize = 256;

/// Write the LfGlobal modular section for the alpha channel.
///
/// * **Small images** (`xsize ≤ GROUP_DIM && ysize ≤ GROUP_DIM`): writes the
///   complete modular section — GroupHeader + local tree + pixel histograms +
///   all pixel tokens — into `w` (the LfGlobal section writer).
///
/// * **Large images**: writes only the 4-bit GroupHeader
///   (`use_global_tree=1`).  Per-AC-group pixel tokens are written later by
///   [`write_ac_group_alpha`].
pub(crate) fn write_lfglobal_alpha_section(
    alpha: &AlphaPlane,
    xsize: usize,
    ysize: usize,
    scratch: &mut CoderScratch,
    w: &mut BitWriter,
) {
    assert_eq!(alpha.len(), xsize * ysize);
    if xsize <= GROUP_DIM && ysize <= GROUP_DIM {
        // Small path: everything in the LfGlobal section. Same two candidates
        // as `write_ac_group_alpha`: plain single-context prefix coding vs the
        // lossless path's LZ77+rANS section; exact bit comparison picks.
        let tokens = tokenize_channel(alpha, xsize, ysize, 0, 0, xsize, ysize, xsize);
        let mut plain = BitWriter::new();
        {
            write_group_header_local_tree(&mut plain);
            let pixel_code = build_pixel_code(&tokens, scratch);
            write_tree_and_pixel_histograms(&pixel_code, scratch, &mut plain);
            let code_ref = pixel_code.as_ref();
            for tok in &tokens {
                write_token(*tok, &code_ref, &mut plain);
            }
        }
        let mut lz = BitWriter::new();
        let lz_ok = crate::lossless::write_single_channel_lz77_section(&tokens, scratch, &mut lz);
        if lz_ok && lz.bits_written() < plain.bits_written() {
            w.append(&lz);
        } else {
            w.append(&plain);
        }
    } else {
        // Large path: just the GroupHeader; pixels come per AC group.
        write_group_header_global_tree(w);
    }
}

/// Convenience shim so callers that already pass `write_global_alpha_modular`
/// continue to compile without changes.  Delegates to
/// [`write_lfglobal_alpha_section`].
#[inline]
pub(crate) fn write_global_alpha_modular(
    alpha: &AlphaPlane,
    xsize: usize,
    ysize: usize,
    scratch: &mut CoderScratch,
    w: &mut BitWriter,
) {
    write_lfglobal_alpha_section(alpha, xsize, ysize, scratch, w);
}

pub(crate) fn write_ac_group_alpha(
    alpha: &AlphaPlane,
    full_xsize: usize,
    full_ysize: usize,
    x0: usize,
    y0: usize,
    gw: usize,
    gh: usize,
    scratch: &mut CoderScratch,
    w: &mut BitWriter,
) {
    // Small-image path: alpha lives entirely in LfGlobal; nothing per group.
    if full_xsize <= GROUP_DIM && full_ysize <= GROUP_DIM {
        return;
    }

    let full_size = full_xsize
        .checked_mul(full_ysize)
        .expect("alpha dimensions overflow usize");
    assert_eq!(alpha.len(), full_size);
    assert!(x0 <= full_xsize && gw <= full_xsize - x0);
    assert!(y0 <= full_ysize && gh <= full_ysize - y0);

    let token_count = gw
        .checked_mul(gh)
        .expect("alpha group size overflows usize");
    scratch.alpha_tokens.resize(token_count, Token::new(0, 0));
    if token_count != 0 {
        match alpha {
            AlphaPlane::U8(data) => tokenize_ac_group_alpha_u8(
                data,
                full_xsize,
                x0,
                y0,
                gw,
                gh,
                &mut scratch.alpha_tokens,
            ),
            AlphaPlane::U16 { data, .. } => tokenize_ac_group_alpha_u16(
                data,
                full_xsize,
                x0,
                y0,
                gw,
                gh,
                &mut scratch.alpha_tokens,
            ),
            AlphaPlane::F32(data) => {
                tokenize_ac_group_alpha(data, full_xsize, x0, y0, gw, gh, &mut scratch.alpha_tokens)
            }
        }
    }

    // Candidate A (plain): 2-leaf grad-sign tree + per-leaf prefix codes.
    // Optimal for exactly-constant planes, where the bulk leaf degenerates to a
    // zero-bit single-symbol code. Candidate B (LZ77): single-leaf Gradient
    // tree + run collapse + rANS, shared with the lossless path; rescues
    // near-constant planes, where a few impure pixels otherwise force the
    // 1 bit/pixel prefix floor onto every pixel of the group. Exact bit
    // comparison picks per group.
    let tokens = std::mem::take(&mut scratch.alpha_tokens);
    let mut plain = BitWriter::new();
    {
        const NUM_CTX: usize = 2; // leaf 0 (grad > 0), leaf 1 (grad <= 0)
        let pixel_code = build_pixel_code_n(&tokens, NUM_CTX, &mut scratch.huffman_pool);
        write_group_header_local_tree(&mut plain); // use_global_tree=0, wp default, 0 transforms
        write_split_tree(scratch, &mut plain); // 2-leaf Gradient tree, split on property 9 at 0
        plain.write(1, 0); // no LZ77 for the pixel entropy code
        write_entropy_code(&pixel_code.as_ref(), &mut scratch.huffman_pool, &mut plain);
        let code_ref = pixel_code.as_ref();
        for tok in &tokens {
            write_token(*tok, &code_ref, &mut plain);
        }
    }
    let mut lz = BitWriter::new();
    let lz_ok = crate::lossless::write_single_channel_lz77_section(&tokens, scratch, &mut lz);
    scratch.alpha_tokens = tokens;
    if lz_ok && lz.bits_written() < plain.bits_written() {
        w.append(&lz);
    } else {
        w.append(&plain);
    }
}

trait AlphaSample: Copy {
    const ZERO: Self;

    fn to_i32(self) -> i32;
}

impl AlphaSample for u8 {
    const ZERO: Self = 0;

    #[inline]
    fn to_i32(self) -> i32 {
        self as i32
    }
}

impl AlphaSample for u16 {
    const ZERO: Self = 0;

    #[inline]
    fn to_i32(self) -> i32 {
        self as i32
    }
}

impl AlphaSample for i32 {
    const ZERO: Self = 0;

    #[inline]
    fn to_i32(self) -> i32 {
        self
    }
}

#[inline]
fn alpha_token<T: AlphaSample>(v: T, w: T, n: T, nw: T) -> Token {
    let v = v.to_i32();
    let w = w.to_i32();
    let n = n.to_i32();
    let nw = nw.to_i32();
    let grad = w + n - nw;
    let pred = grad.clamp(w.min(n), w.max(n));
    let context = if grad > 0 { 0 } else { 1 };
    Token::new(context, pack_signed(v - pred))
}

#[inline]
pub(crate) fn alpha_token_u8(v: u8, w: u8, n: u8, nw: u8) -> Token {
    alpha_token(v, w, n, nw)
}

#[inline]
pub(crate) fn alpha_token_u16(v: u16, w: u16, n: u16, nw: u16) -> Token {
    alpha_token(v, w, n, nw)
}

type TokenizeAlphaFirstRowFn<T> = fn(&[T], &mut [Token]);
type TokenizeAlphaInteriorFn<T> = fn(&[T], &[T], &mut [Token]);
type TokenizeAlphaFns<T> = (TokenizeAlphaFirstRowFn<T>, TokenizeAlphaInteriorFn<T>);
type TokenizeAlphaU8Fns = TokenizeAlphaFns<u8>;

#[cfg(not(all(target_arch = "aarch64", feature = "neon")))]
fn tokenize_alpha_u8_first_row_scalar(row: &[u8], out: &mut [Token]) {
    debug_assert_eq!(row.len(), out.len());
    for ((&value, &west), out) in row[1..].iter().zip(row.iter()).zip(out[1..].iter_mut()) {
        *out = alpha_token_u8(value, west, 0, 0);
    }
}

#[cfg(not(all(target_arch = "aarch64", feature = "neon")))]
fn tokenize_alpha_u8_interior_scalar(row: &[u8], north: &[u8], out: &mut [Token]) {
    debug_assert_eq!(row.len(), north.len());
    debug_assert_eq!(row.len(), out.len());
    for ((((&value, &west), &north), &northwest), out) in row[1..]
        .iter()
        .zip(row.iter())
        .zip(north[1..].iter())
        .zip(north.iter())
        .zip(out[1..].iter_mut())
    {
        *out = alpha_token_u8(value, west, north, northwest);
    }
}

#[cfg(all(target_arch = "aarch64", feature = "neon"))]
fn select_tokenize_alpha_u8() -> TokenizeAlphaU8Fns {
    (
        |row, out| unsafe { crate::neon::tokenize_alpha_u8_first_row_neon(row, out) },
        |row, north, out| unsafe { crate::neon::tokenize_alpha_u8_interior_neon(row, north, out) },
    )
}

#[cfg(not(all(target_arch = "aarch64", feature = "neon")))]
fn select_tokenize_alpha_u8() -> TokenizeAlphaU8Fns {
    #[cfg(all(target_arch = "x86_64", feature = "avx"))]
    if std::is_x86_feature_detected!("avx2") {
        return (
            |row, out| unsafe { crate::avx::tokenize_alpha_u8_first_row_avx2(row, out) },
            |row, north, out| unsafe {
                crate::avx::tokenize_alpha_u8_interior_avx2(row, north, out)
            },
        );
    }

    #[cfg(all(any(target_arch = "x86_64", target_arch = "x86"), feature = "sse"))]
    if std::is_x86_feature_detected!("sse4.1") {
        return (
            |row, out| unsafe { crate::sse::tokenize_alpha_u8_first_row_sse41(row, out) },
            |row, north, out| unsafe {
                crate::sse::tokenize_alpha_u8_interior_sse41(row, north, out)
            },
        );
    }

    (
        tokenize_alpha_u8_first_row_scalar,
        tokenize_alpha_u8_interior_scalar,
    )
}

static TOKENIZE_ALPHA_U8: OnceLock<TokenizeAlphaU8Fns> = OnceLock::new();

#[inline]
fn selected_tokenize_alpha_u8() -> TokenizeAlphaU8Fns {
    *TOKENIZE_ALPHA_U8.get_or_init(select_tokenize_alpha_u8)
}

fn tokenize_ac_group_alpha_with<T: AlphaSample>(
    first_row: TokenizeAlphaFirstRowFn<T>,
    interior: TokenizeAlphaInteriorFn<T>,
    samples: &[T],
    stride: usize,
    x0: usize,
    y0: usize,
    gw: usize,
    gh: usize,
    dst: &mut [Token],
) {
    debug_assert_ne!(gw, 0);
    debug_assert_ne!(gh, 0);
    debug_assert_eq!(dst.len(), gw * gh);

    let mut src_rows = samples.chunks_exact(stride).skip(y0).take(gh);
    let mut dst_rows = dst.chunks_exact_mut(gw);
    let first = &src_rows.next().unwrap()[x0..x0 + gw];
    let first_dst = dst_rows.next().unwrap();

    let (&first_value, _) = first.split_first().unwrap();
    let (first_out, _) = first_dst.split_first_mut().unwrap();
    *first_out = alpha_token(first_value, T::ZERO, T::ZERO, T::ZERO);
    first_row(first, first_dst);

    let mut north = first;
    for (row, out) in src_rows.zip(dst_rows) {
        let row = &row[x0..x0 + gw];
        let (&value, _) = row.split_first().unwrap();
        let (&north_value, _) = north.split_first().unwrap();
        let (first_out, _) = out.split_first_mut().unwrap();
        *first_out = alpha_token(value, T::ZERO, north_value, T::ZERO);
        interior(row, north, out);
        north = row;
    }
}

#[inline]
fn tokenize_ac_group_alpha_u8(
    samples: &[u8],
    stride: usize,
    x0: usize,
    y0: usize,
    gw: usize,
    gh: usize,
    dst: &mut [Token],
) {
    let (first_row, interior) = selected_tokenize_alpha_u8();
    tokenize_ac_group_alpha_with(first_row, interior, samples, stride, x0, y0, gw, gh, dst);
}

type TokenizeAlphaU16Fns = TokenizeAlphaFns<u16>;

#[cfg(not(all(target_arch = "aarch64", feature = "neon")))]
fn tokenize_alpha_u16_first_row_scalar(row: &[u16], out: &mut [Token]) {
    debug_assert_eq!(row.len(), out.len());
    for ((&value, &west), out) in row[1..].iter().zip(row.iter()).zip(out[1..].iter_mut()) {
        *out = alpha_token_u16(value, west, 0, 0);
    }
}

#[cfg(not(all(target_arch = "aarch64", feature = "neon")))]
fn tokenize_alpha_u16_interior_scalar(row: &[u16], north: &[u16], out: &mut [Token]) {
    debug_assert_eq!(row.len(), north.len());
    debug_assert_eq!(row.len(), out.len());
    for ((((&value, &west), &north), &northwest), out) in row[1..]
        .iter()
        .zip(row.iter())
        .zip(north[1..].iter())
        .zip(north.iter())
        .zip(out[1..].iter_mut())
    {
        *out = alpha_token_u16(value, west, north, northwest);
    }
}

#[cfg(all(target_arch = "aarch64", feature = "neon"))]
fn select_tokenize_alpha_u16() -> TokenizeAlphaU16Fns {
    (
        |row, out| unsafe { crate::neon::tokenize_alpha_u16_first_row_neon(row, out) },
        |row, north, out| unsafe { crate::neon::tokenize_alpha_u16_interior_neon(row, north, out) },
    )
}

#[cfg(not(all(target_arch = "aarch64", feature = "neon")))]
fn select_tokenize_alpha_u16() -> TokenizeAlphaU16Fns {
    #[cfg(all(target_arch = "x86_64", feature = "avx"))]
    if std::is_x86_feature_detected!("avx2") {
        return (
            |row, out| unsafe { crate::avx::tokenize_alpha_u16_first_row_avx2(row, out) },
            |row, north, out| unsafe {
                crate::avx::tokenize_alpha_u16_interior_avx2(row, north, out)
            },
        );
    }

    #[cfg(all(any(target_arch = "x86_64", target_arch = "x86"), feature = "sse"))]
    if std::is_x86_feature_detected!("sse4.1") {
        return (
            |row, out| unsafe { crate::sse::tokenize_alpha_u16_first_row_sse41(row, out) },
            |row, north, out| unsafe {
                crate::sse::tokenize_alpha_u16_interior_sse41(row, north, out)
            },
        );
    }

    (
        tokenize_alpha_u16_first_row_scalar,
        tokenize_alpha_u16_interior_scalar,
    )
}

static TOKENIZE_ALPHA_U16: OnceLock<TokenizeAlphaU16Fns> = OnceLock::new();

#[inline]
fn selected_tokenize_alpha_u16() -> TokenizeAlphaU16Fns {
    *TOKENIZE_ALPHA_U16.get_or_init(select_tokenize_alpha_u16)
}

#[inline]
fn tokenize_ac_group_alpha_u16(
    samples: &[u16],
    stride: usize,
    x0: usize,
    y0: usize,
    gw: usize,
    gh: usize,
    dst: &mut [Token],
) {
    let (first_row, interior) = selected_tokenize_alpha_u16();
    tokenize_ac_group_alpha_with(first_row, interior, samples, stride, x0, y0, gw, gh, dst);
}

#[inline]
fn tokenize_ac_group_alpha<T: AlphaSample>(
    samples: &[T],
    stride: usize,
    x0: usize,
    y0: usize,
    gw: usize,
    gh: usize,
    dst: &mut [Token],
) {
    debug_assert_ne!(gw, 0);
    debug_assert_ne!(gh, 0);
    debug_assert_eq!(dst.len(), gw * gh);

    let mut src_rows = samples.chunks_exact(stride).skip(y0).take(gh);
    let mut dst_rows = dst.chunks_exact_mut(gw);
    let first = &src_rows.next().unwrap()[x0..x0 + gw];
    let first_dst = dst_rows.next().unwrap();

    first_dst[0] = alpha_token(first[0], T::ZERO, T::ZERO, T::ZERO);
    for ((&v, &w), out) in first[1..]
        .iter()
        .zip(first[..gw - 1].iter())
        .zip(first_dst[1..].iter_mut())
    {
        *out = alpha_token(v, w, T::ZERO, T::ZERO);
    }

    let mut north = first;
    for (row, out) in src_rows.zip(dst_rows) {
        let row = &row[x0..x0 + gw];
        out[0] = alpha_token(row[0], T::ZERO, north[0], T::ZERO);

        for ((((&v, &w), &n), &nw), out) in row[1..]
            .iter()
            .zip(row[..gw - 1].iter())
            .zip(north[1..].iter())
            .zip(north[..gw - 1].iter())
            .zip(out[1..].iter_mut())
        {
            *out = alpha_token(v, w, n, nw);
        }
        north = row;
    }
}

/// GroupHeader: use_global_tree=0, wp_header.all_default=1, 0 transforms.
/// (4 bits)  Used for the LfGlobal local-tree path.
pub(crate) fn write_group_header_local_tree(w: &mut BitWriter) {
    w.write(1, 0); // use_global_tree = false
    w.write(1, 1); // wp_header all_default
    w.write(2, 0); // 0 transforms
}

/// GroupHeader: use_global_tree=1, wp_header.all_default=1, 0 transforms.
/// (4 bits)  Used for LfGlobal and per-AC-group headers in the large-image path.
fn write_group_header_global_tree(w: &mut BitWriter) {
    w.write(1, 1); // use_global_tree = true
    w.write(1, 1); // wp_header all_default
    w.write(2, 0); // 0 transforms
}

pub(crate) fn write_tree_and_pixel_histograms(
    pixel_code: &OwnedEntropyCode,
    scratch: &mut CoderScratch,
    w: &mut BitWriter,
) {
    let tree_tokens = [
        Token::new(TREE_CTX_PROPERTY, 0),
        Token::new(TREE_CTX_PREDICTOR, PREDICTOR_GRADIENT),
        Token::new(TREE_CTX_OFFSET, pack_signed(0)),
        Token::new(TREE_CTX_MULTIPLIER_LOG, 0),
        Token::new(TREE_CTX_MULTIPLIER_BITS, 0),
    ];
    let tree_code =
        optimize_entropy_code(&tree_tokens, NUM_TREE_CONTEXTS, &mut scratch.huffman_pool);
    let tree_code_ref = tree_code.as_ref();

    w.write(1, 0); // no LZ77 for tree entropy code
    write_entropy_code(&tree_code_ref, &mut scratch.huffman_pool, w);
    for tok in &tree_tokens {
        write_token(*tok, &tree_code_ref, w);
    }

    // num_contexts = 1: decoder skips context map entirely — write prefix
    // codes directly (no write_context_map).
    w.write(1, 0); // no LZ77 for pixel entropy code
    write_prefix_codes(
        &pixel_code.prefix_codes,
        &pixel_code.hybrid_uint_configs,
        &mut scratch.huffman_pool,
        w,
    );
}

/// Like `write_tree_and_pixel_histograms` but emits a 2-leaf tree that splits on
/// modular property 9 (the raw gradient W+N-NW) at splitval 0. Pixels with
/// grad > 0 take leaf 0, others leaf 1; both leaves predict with Gradient. The
/// tree is decoded breadth-first: a split node (property+1, splitval) followed
/// by its two leaf nodes. Two pixel prefix codes follow (one per leaf), written
/// via the context map the decoder builds from num_contexts = 2.
/// Write the 2-leaf alpha tree: a split node on property 9 (raw gradient) at
/// splitval 0, followed by two Gradient-predictor leaves. The pixel entropy
/// code is written separately by the caller (so it can choose plain vs LZ77).
#[allow(dead_code)]
fn write_split_tree(scratch: &mut CoderScratch, w: &mut BitWriter) {
    // Property index 9 = raw gradient (W+N-NW) in libjxl's property order.
    const PROP_GRAD: u32 = 9;
    let tree_tokens = [
        // Split node: property = PROP_GRAD (encoded as property+1), splitval 0.
        Token::new(TREE_CTX_PROPERTY, PROP_GRAD + 1),
        Token::new(TREE_CTX_SPLITVAL, pack_signed(0)),
        // Leaf 0 (grad > 0): Gradient predictor, offset 0, multiplier 1.
        Token::new(TREE_CTX_PROPERTY, 0),
        Token::new(TREE_CTX_PREDICTOR, PREDICTOR_GRADIENT),
        Token::new(TREE_CTX_OFFSET, pack_signed(0)),
        Token::new(TREE_CTX_MULTIPLIER_LOG, 0),
        Token::new(TREE_CTX_MULTIPLIER_BITS, 0),
        // Leaf 1 (grad <= 0): same.
        Token::new(TREE_CTX_PROPERTY, 0),
        Token::new(TREE_CTX_PREDICTOR, PREDICTOR_GRADIENT),
        Token::new(TREE_CTX_OFFSET, pack_signed(0)),
        Token::new(TREE_CTX_MULTIPLIER_LOG, 0),
        Token::new(TREE_CTX_MULTIPLIER_BITS, 0),
    ];
    let tree_code =
        optimize_entropy_code(&tree_tokens, NUM_TREE_CONTEXTS, &mut scratch.huffman_pool);
    let tree_code_ref = tree_code.as_ref();

    w.write(1, 0); // no LZ77 for tree entropy code
    write_entropy_code(&tree_code_ref, &mut scratch.huffman_pool, w);
    for tok in &tree_tokens {
        write_token(*tok, &tree_code_ref, w);
    }
}

pub(crate) fn build_pixel_code(tokens: &[Token], scratch: &mut CoderScratch) -> OwnedEntropyCode {
    build_pixel_code_n(tokens, 1, &mut scratch.huffman_pool)
}

fn build_pixel_code_n(
    tokens: &[Token],
    num_contexts: usize,
    huffman_pool: &mut Vec<HuffmanNode>,
) -> OwnedEntropyCode {
    let mut code = if num_contexts > 1 {
        // Keep contexts separate — the whole point of the multi-leaf alpha tree
        // is that the bulk-zero leaf must not be merged with the rare-corner
        // leaf, or it loses its single-symbol (zero-bit) property.
        crate::entropy::build_entropy_code_no_cluster(tokens, num_contexts, huffman_pool)
    } else {
        optimize_entropy_code(tokens, num_contexts, huffman_pool)
    };
    for pc in &mut code.prefix_codes {
        // Count non-zero depths and remember the position of the only one (if any).
        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 {
            // Single-symbol case.
            //
            // JXL has two distinct encodings for a degenerate prefix code:
            //
            //   (a) alphabet_size == 1: the decoder consumes ZERO bits per token
            //       and emits token value 0 every time. This only works if the
            //       single live symbol is token 0 — otherwise the decoder gets
            //       the wrong token AND leaves our extra-bit payload unconsumed,
            //       desynchronising the bitstream.
            //
            //   (b) A valid 2-symbol simple Huffman code where both symbols share
            //       a 1-bit code. The encoder always picks our real token (cost:
            //       1 wasted bit per pixel), the decoder synchronizes correctly.
            //
            // CreateHuffmanTree gives us depth=1 with bits=0 for the placeholder,
            // but the actual encoded value would be `0` — wrong if our token > 0.
            // We use (a) only when the symbol IS token 0, and (b) otherwise.
            if idx == 0 {
                // Plain (a): zero depth & bits so write_prefix_code emits the
                // "alphabet_size == 1" header (4 bits, value 1) and write_token
                // emits zero bits.
                pc.depths[idx] = 0;
                pc.bits[idx] = 0;
            } else {
                // (b): synthesize a second symbol at index 0 with depth 1 and
                // assign codes {0 → "0", idx → "1"} so the encoder always emits
                // "1" + extra bits, and the decoder follows the same logic.
                pc.depths[0] = 1;
                pc.bits[0] = 0;
                pc.depths[idx] = 1;
                pc.bits[idx] = 1;
            }
        }
        pc.update_single_symbol();
    }
    code
}

#[inline]
pub(crate) fn gradient(w: i32, n: i32, nw: i32) -> i32 {
    let lo = w.min(n);
    let hi = w.max(n);
    (w + n - nw).clamp(lo, hi)
}

/// Tokenize a rectangular slice [x0..x0+gw, y0..y0+gh] of `alpha` (which
/// has the given `full_xsize` stride) using context = 0.
fn tokenize_channel(
    alpha: &AlphaPlane,
    _full_xsize: usize,
    _full_ysize: usize,
    x0: usize,
    y0: usize,
    gw: usize,
    gh: usize,
    stride: usize,
) -> Vec<Token> {
    let _ = _full_ysize;
    let mut tokens = Vec::with_capacity(gw * gh);
    for y in y0..y0 + gh {
        for x in x0..x0 + gw {
            let v = alpha.get_i32(y * stride + x);
            let w_ = if x > 0 {
                alpha.get_i32(y * stride + x - 1)
            } else {
                0
            };
            let n_ = if y > 0 {
                alpha.get_i32((y - 1) * stride + x)
            } else {
                0
            };
            let nw_ = if x > 0 && y > 0 {
                alpha.get_i32((y - 1) * stride + x - 1)
            } else {
                0
            };
            let pred = gradient(w_, n_, nw_);
            tokens.push(Token::new(0, pack_signed(v - pred)));
        }
    }
    tokens
}

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

    fn check_ac_group_tokenization<T: AlphaSample>(
        samples: &[T],
        stride: usize,
        x0: usize,
        y0: usize,
        gw: usize,
        gh: usize,
    ) {
        let mut actual = vec![Token::new(0, 0); gw * gh];
        tokenize_ac_group_alpha(samples, stride, x0, y0, gw, gh, &mut actual);

        for gy in 0..gh {
            for gx in 0..gw {
                let at = |x: usize, y: usize| samples[(y0 + y) * stride + x0 + x].to_i32();
                let v = at(gx, gy);
                let w = if gx == 0 { 0 } else { at(gx - 1, gy) };
                let n = if gy == 0 { 0 } else { at(gx, gy - 1) };
                let nw = if gx == 0 || gy == 0 {
                    0
                } else {
                    at(gx - 1, gy - 1)
                };
                let pred = gradient(w, n, nw);
                let expected =
                    Token::new(if w + n - nw > 0 { 0 } else { 1 }, pack_signed(v - pred));
                let actual = &actual[gy * gw + gx];
                assert_eq!(actual.context, expected.context);
                assert_eq!(actual.value, expected.value);
            }
        }
    }

    fn check_u8_tokenizer((first_row, interior): TokenizeAlphaU8Fns) {
        for &gw in &[1usize, 2, 7, 8, 9, 15, 16, 17, 31, 32, 255, 256] {
            for &gh in &[1usize, 2, 3, 7] {
                let x0 = 3;
                let y0 = 2;
                let stride = x0 + gw + 5;
                let height = y0 + gh + 1;
                let mut state = 0x1234_5678u32 ^ (gw as u32) ^ ((gh as u32) << 16);
                let samples: Vec<u8> = (0..stride * height)
                    .map(|i| {
                        state = state.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);
                        match i & 7 {
                            0 => 0,
                            1 => 255,
                            _ => (state >> 24) as u8,
                        }
                    })
                    .collect();

                let sentinel = Token::new(u32::MAX, u32::MAX);
                let mut expected = vec![sentinel; gw * gh];
                let mut actual = vec![sentinel; gw * gh];
                tokenize_ac_group_alpha(&samples, stride, x0, y0, gw, gh, &mut expected);
                tokenize_ac_group_alpha_with(
                    first_row,
                    interior,
                    &samples,
                    stride,
                    x0,
                    y0,
                    gw,
                    gh,
                    &mut actual,
                );

                for (i, (actual, expected)) in actual.iter().zip(&expected).enumerate() {
                    assert_eq!(
                        (actual.context, actual.value),
                        (expected.context, expected.value),
                        "u8 alpha token mismatch at index {i} for {gw}x{gh}",
                    );
                }
            }
        }
    }

    fn check_u16_tokenizer((first_row, interior): TokenizeAlphaU16Fns) {
        for gw in [1usize, 2, 3, 4, 5, 7, 8, 9, 15, 16, 17, 31, 32, 255, 256] {
            for gh in [1usize, 2, 3, 7] {
                let x0 = 3;
                let y0 = 2;
                let stride = x0 + gw + 5;
                let height = y0 + gh + 1;
                let mut state = 0x89ab_cdefu32 ^ (gw as u32) ^ ((gh as u32) << 16);
                let samples: Vec<u16> = (0..stride * height)
                    .map(|i| {
                        state = state.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);
                        match i & 7 {
                            0 => 0,
                            1 => u16::MAX,
                            _ => (state >> 16) as u16,
                        }
                    })
                    .collect();

                let sentinel = Token::new(u32::MAX, u32::MAX);
                let mut expected = vec![sentinel; gw * gh];
                let mut actual = vec![sentinel; gw * gh];
                tokenize_ac_group_alpha(&samples, stride, x0, y0, gw, gh, &mut expected);
                tokenize_ac_group_alpha_with(
                    first_row,
                    interior,
                    &samples,
                    stride,
                    x0,
                    y0,
                    gw,
                    gh,
                    &mut actual,
                );

                for (i, (actual, expected)) in actual.iter().zip(&expected).enumerate() {
                    assert_eq!(
                        (actual.context, actual.value),
                        (expected.context, expected.value),
                        "u16 alpha token mismatch at index {i} for {gw}x{gh}",
                    );
                }
            }
        }
    }

    #[test]
    fn gradient_basic() {
        assert_eq!(gradient(50, 50, 0), 50);
        assert_eq!(gradient(50, 50, 100), 50);
        assert_eq!(gradient(10, 20, 5), 20);
        assert_eq!(gradient(10, 20, 25), 10);
        assert_eq!(gradient(10, 20, 15), 15);
    }

    #[test]
    fn tokenize_constant_zero() {
        let chan = vec![0u8; 16 * 16];
        let alpha = AlphaPlane::from_u8(chan);
        let toks = tokenize_channel(&alpha, 16, 16, 0, 0, 16, 16, 16);
        for t in &toks {
            assert_eq!(t.value, 0);
        }
    }

    #[test]
    fn tokenize_ac_group_matches_scalar_for_all_sample_types() {
        let u8_samples: Vec<u8> = (0..64).map(|v| ((v * 37 + 11) % 251) as u8).collect();
        check_ac_group_tokenization(&u8_samples, 8, 2, 1, 5, 6);
        check_ac_group_tokenization(&u8_samples, 8, 4, 3, 1, 1);

        let u16_samples: Vec<u16> = (0..64).map(|v| ((v * 977 + 31) % 4096) as u16).collect();
        check_ac_group_tokenization(&u16_samples, 8, 1, 2, 6, 5);

        let i32_samples: Vec<i32> = (0..64).map(|v| (v * 43 + 17) % 257 - 128).collect();
        check_ac_group_tokenization(&i32_samples, 8, 3, 1, 4, 7);
    }

    #[test]
    fn selected_u8_ac_group_tokenizer_matches_scalar() {
        check_u8_tokenizer(selected_tokenize_alpha_u8());
    }

    #[cfg(all(target_arch = "aarch64", feature = "neon"))]
    #[test]
    fn neon_u8_ac_group_tokenizer_matches_scalar() {
        check_u8_tokenizer((
            |row, out| unsafe { crate::neon::tokenize_alpha_u8_first_row_neon(row, out) },
            |row, north, out| unsafe {
                crate::neon::tokenize_alpha_u8_interior_neon(row, north, out)
            },
        ));
    }

    #[cfg(all(target_arch = "x86_64", feature = "avx"))]
    #[test]
    fn avx2_u8_ac_group_tokenizer_matches_scalar() {
        if std::is_x86_feature_detected!("avx2") {
            check_u8_tokenizer((
                |row, out| unsafe { crate::avx::tokenize_alpha_u8_first_row_avx2(row, out) },
                |row, north, out| unsafe {
                    crate::avx::tokenize_alpha_u8_interior_avx2(row, north, out)
                },
            ));
        }
    }

    #[cfg(all(any(target_arch = "x86_64", target_arch = "x86"), feature = "sse"))]
    #[test]
    fn sse41_u8_ac_group_tokenizer_matches_scalar() {
        if std::is_x86_feature_detected!("sse4.1") {
            check_u8_tokenizer((
                |row, out| unsafe { crate::sse::tokenize_alpha_u8_first_row_sse41(row, out) },
                |row, north, out| unsafe {
                    crate::sse::tokenize_alpha_u8_interior_sse41(row, north, out)
                },
            ));
        }
    }

    #[test]
    fn selected_u16_ac_group_tokenizer_matches_scalar() {
        check_u16_tokenizer(selected_tokenize_alpha_u16());
    }

    #[cfg(all(target_arch = "aarch64", feature = "neon"))]
    #[test]
    fn neon_u16_ac_group_tokenizer_matches_scalar() {
        check_u16_tokenizer((
            |row, out| unsafe { crate::neon::tokenize_alpha_u16_first_row_neon(row, out) },
            |row, north, out| unsafe {
                crate::neon::tokenize_alpha_u16_interior_neon(row, north, out)
            },
        ));
    }

    #[cfg(all(target_arch = "x86_64", feature = "avx"))]
    #[test]
    fn avx2_u16_ac_group_tokenizer_matches_scalar() {
        if std::is_x86_feature_detected!("avx2") {
            check_u16_tokenizer((
                |row, out| unsafe { crate::avx::tokenize_alpha_u16_first_row_avx2(row, out) },
                |row, north, out| unsafe {
                    crate::avx::tokenize_alpha_u16_interior_avx2(row, north, out)
                },
            ));
        }
    }

    #[cfg(all(any(target_arch = "x86_64", target_arch = "x86"), feature = "sse"))]
    #[test]
    fn sse41_u16_ac_group_tokenizer_matches_scalar() {
        if std::is_x86_feature_detected!("sse4.1") {
            check_u16_tokenizer((
                |row, out| unsafe { crate::sse::tokenize_alpha_u16_first_row_sse41(row, out) },
                |row, north, out| unsafe {
                    crate::sse::tokenize_alpha_u16_interior_sse41(row, north, out)
                },
            ));
        }
    }

    #[test]
    fn write_alpha_small_emits_bytes() {
        let mut w = BitWriter::new();
        let chan = vec![128u8; 8 * 8];
        let alpha = AlphaPlane::from_u8(chan);
        let mut scratch = CoderScratch::default();
        write_global_alpha_modular(&alpha, 8, 8, &mut scratch, &mut w);
        let bits = w.bits_written();
        w.zero_pad_to_byte();
        assert!(!w.into_bytes().is_empty());
        assert!(bits > 0);
    }

    #[test]
    fn write_alpha_large_emits_header_only() {
        let mut w = BitWriter::new();
        let chan = vec![200u8; 512 * 400];
        let alpha = AlphaPlane::from_u8(chan);
        let mut scratch = CoderScratch::default();
        write_lfglobal_alpha_section(&alpha, 512, 400, &mut scratch, &mut w);
        // Large path: only 4 bits (GroupHeader).
        assert_eq!(w.bits_written(), 4);
    }
}