jixel 0.5.11

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
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
/*
 * // 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;

pub(crate) mod nested_profile;
pub(crate) mod portable_profile;

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`]. With an ANS `global_code` the empty stream's
///   final state follows, as libjxl writes it: jxl-oxide reads it even when
///   no channel is coded here.
pub(crate) fn write_lfglobal_alpha_section(
    alpha: &AlphaPlane,
    xsize: usize,
    ysize: usize,
    step: u32,
    global_code_ans: bool,
    scratch: &mut CoderScratch,
    w: &mut BitWriter,
) {
    assert_eq!(alpha.len(), xsize * ysize);
    if xsize <= GROUP_DIM && ysize <= GROUP_DIM && step > 1 {
        write_lattice_section(alpha, step, 0, 0, xsize, ysize, xsize, scratch, w);
    } else 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);
        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);
        if global_code_ans {
            w.write(32, u64::from(crate::entropy::ANS_SIGNATURE << 16));
        }
    }
}

/// 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,
    step: u32,
    global_code_ans: bool,
    scratch: &mut CoderScratch,
    w: &mut BitWriter,
) {
    write_lfglobal_alpha_section(alpha, xsize, ysize, step, global_code_ans, 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,
    step: u32,
    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;
    }
    if step > 1 {
        write_lattice_section(alpha, step, x0, y0, gw, gh, full_xsize, scratch, w);
        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);
    }
}

/// The GlobalModular part of a palette-coded extra channel larger than a
/// group: its Palette transform and the palette itself (one row of
/// `entries`, `bits` deep) under a local one-leaf tree; the indices follow
/// per AC group.
pub(crate) fn write_global_palette_alpha_modular(
    entries: &[i32],
    bits: u8,
    scratch: &mut CoderScratch,
    w: &mut BitWriter,
) {
    let meta = if bits <= 8 {
        AlphaPlane::U8(entries.iter().map(|&v| v as u8).collect())
    } else {
        AlphaPlane::U16 {
            data: entries.iter().map(|&v| v as u16).collect(),
            bits,
        }
    };
    let tokens = tokenize_channel(&meta, entries.len(), 1);
    w.write(1, 0); // use_global_tree = false
    w.write(1, 1); // wp_header all_default
    crate::lossless::write_palette_transform(1, entries.len() as u32, w);
    let pixel_code = build_pixel_code(&tokens, scratch);
    write_tree_and_pixel_histograms(&pixel_code, scratch, w);
    let code_ref = pixel_code.as_ref();
    for tok in &tokens {
        write_token(*tok, &code_ref, w);
    }
}

/// Snap a plane onto the lattice `{max - step·n}`: the maximum (no ink for
/// a K channel, opaque for alpha) stays exact and every value moves by at
/// most half a step.
pub(crate) fn snap_to_lattice(plane: &mut AlphaPlane, step: u32) {
    let max = match plane {
        AlphaPlane::U8(_) => 255u32,
        AlphaPlane::U16 { bits, .. } => (1u32 << *bits) - 1,
        AlphaPlane::F32(_) => unreachable!("float planes are not quantized"),
    };
    let divider = crate::fast_divide::DividerI32::new(step as i32);
    let half = step / 2;
    let snap = |v: u32| -> u32 {
        let ink = max - v.min(max);
        let q = (((ink + half) as i32 / divider) as u32) * step;
        max - q.min(max - max % step)
    };
    match plane {
        AlphaPlane::U8(data) => data.iter_mut().for_each(|v| *v = snap(u32::from(*v)) as u8),
        AlphaPlane::U16 { data, .. } => data
            .iter_mut()
            .for_each(|v| *v = snap(u32::from(*v)) as u16),
        AlphaPlane::F32(_) => unreachable!(),
    }
}

/// One modular section of a plane snapped by [`snap_to_lattice`]. Every
/// stored value is congruent to the maximum modulo `step`, and so is the
/// Gradient prediction from such values: residuals are whole steps, coded
/// through the leaf multiplier. The group's first pixel has no neighbors and
/// predicts 0, so it takes a Zero leaf whose offset restores the residue.
#[allow(clippy::too_many_arguments)]
fn write_lattice_section(
    plane: &AlphaPlane,
    step: u32,
    x0: usize,
    y0: usize,
    gw: usize,
    gh: usize,
    stride: usize,
    scratch: &mut CoderScratch,
    w: &mut BitWriter,
) {
    const PROP_Y: u32 = 2;
    const PROP_X: u32 = 3;
    const PREDICTOR_ZERO: u32 = 0;
    let max = match plane {
        AlphaPlane::U8(_) => 255i32,
        AlphaPlane::U16 { bits, .. } => (1i32 << *bits) - 1,
        AlphaPlane::F32(_) => unreachable!(),
    };
    let step_i = step as i32;
    let divider = crate::fast_divide::DividerI32::new(step_i);
    let residue = max.rem_euclid(step_i);
    let log = step.trailing_zeros();
    let bits = (step >> log) - 1;
    let leaf = |predictor: u32, offset: i32| {
        [
            Token::new(TREE_CTX_PROPERTY, 0),
            Token::new(TREE_CTX_PREDICTOR, predictor),
            Token::new(TREE_CTX_OFFSET, pack_signed(offset)),
            Token::new(TREE_CTX_MULTIPLIER_LOG, log),
            Token::new(TREE_CTX_MULTIPLIER_BITS, bits),
        ]
    };
    // Breadth first: y > 0 ? leaf 0 : (x > 0 ? leaf 1 : leaf 2).
    let mut tree_tokens = vec![
        Token::new(TREE_CTX_PROPERTY, PROP_Y + 1),
        Token::new(TREE_CTX_SPLITVAL, pack_signed(0)),
    ];
    tree_tokens.extend(leaf(PREDICTOR_GRADIENT, 0));
    tree_tokens.extend([
        Token::new(TREE_CTX_PROPERTY, PROP_X + 1),
        Token::new(TREE_CTX_SPLITVAL, pack_signed(0)),
    ]);
    tree_tokens.extend(leaf(PREDICTOR_GRADIENT, 0));
    tree_tokens.extend(leaf(PREDICTOR_ZERO, residue));

    let mut tokens = Vec::with_capacity(gw * gh);
    for y in 0..gh {
        for x in 0..gw {
            let at = |dx: usize, dy: usize| plane.get_i32((y0 + y - dy) * stride + x0 + x - dx);
            let v = at(0, 0);
            let (context, pred) = match (x, y) {
                (0, 0) => (2, residue),
                (_, 0) => (1, at(1, 0)),
                (0, _) => (0, at(0, 1)),
                _ => (0, gradient(at(1, 0), at(0, 1), at(1, 1))),
            };
            debug_assert_eq!((v - pred).rem_euclid(step_i), 0, "value off the lattice");
            tokens.push(Token::new(context, pack_signed((v - pred) / divider)));
        }
    }

    write_group_header_local_tree(w);
    // The tree's entropy code (no LZ77), then its tokens.
    crate::entropy::write_raced_token_stream(
        &tree_tokens,
        NUM_TREE_CONTEXTS,
        &mut scratch.huffman_pool,
        w,
    );
    let pixel_code = build_pixel_code_n(&tokens, 3, &mut scratch.huffman_pool);
    w.write(1, 0); // no LZ77 for the pixel entropy code
    write_entropy_code(&pixel_code.as_ref(), &mut scratch.huffman_pool, w);
    let code_ref = pixel_code.as_ref();
    for tok in &tokens {
        write_token(*tok, &code_ref, w);
    }
}

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);
}

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),
    ];
    // The tree's entropy code (no LZ77), then its tokens.
    crate::entropy::write_raced_token_stream(
        &tree_tokens,
        NUM_TREE_CONTEXTS,
        &mut scratch.huffman_pool,
        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),
    ];
    // The tree's entropy code (no LZ77), then its tokens.
    crate::entropy::write_raced_token_stream(
        &tree_tokens,
        NUM_TREE_CONTEXTS,
        &mut scratch.huffman_pool,
        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 complete alpha plane using the shared group gradient kernels
/// and the LfGlobal single-leaf tree's context = 0.
fn tokenize_channel(alpha: &AlphaPlane, xsize: usize, ysize: usize) -> Vec<Token> {
    let mut tokens = vec![Token::new(0, 0); xsize * ysize];
    if tokens.is_empty() {
        return tokens;
    }
    match alpha {
        AlphaPlane::U8(data) => {
            tokenize_ac_group_alpha_u8(data, xsize, 0, 0, xsize, ysize, &mut tokens)
        }
        AlphaPlane::U16 { data, .. } => {
            tokenize_ac_group_alpha_u16(data, xsize, 0, 0, xsize, ysize, &mut tokens)
        }
        AlphaPlane::F32(data) => {
            tokenize_ac_group_alpha(data, xsize, 0, 0, xsize, ysize, &mut tokens)
        }
    }
    // Group kernels select contexts by gradient sign; this tree has one leaf.
    for token in &mut tokens {
        token.context = 0;
    }
    tokens
}

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

    #[test]
    fn lattice_snap_matches_the_division_formula() {
        for bits in [8u8, 12, 16] {
            let max = (1u32 << bits) - 1;
            for step in [1u32, 2, 3, 5, 7, 16, 17, 64, 255, 1000] {
                let source: Vec<u16> = (0..=max).map(|v| v as u16).collect();
                let mut plane = AlphaPlane::U16 {
                    data: source.clone(),
                    bits,
                };
                snap_to_lattice(&mut plane, step);
                let AlphaPlane::U16 { data, .. } = plane else {
                    unreachable!()
                };
                for (&got, &v) in data.iter().zip(&source) {
                    let ink = max - u32::from(v).min(max);
                    let q = ((ink + step / 2) / step) * step;
                    let want = max - q.min(max - max % step);
                    assert_eq!(u32::from(got), want, "bits={bits} step={step} v={v}");
                }
            }
        }
    }
    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);
        for t in &toks {
            assert_eq!(t.value, 0);
        }
    }

    #[test]
    fn tokenize_channel_matches_scalar_for_all_sample_types() {
        for width in [
            1usize, 2, 3, 4, 5, 7, 8, 9, 15, 16, 17, 31, 32, 33, 255, 256,
        ] {
            for height in [1usize, 2, 7] {
                let mut state = 0x1234_5678u32;
                let samples: Vec<u16> = (0..width * 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();
                for alpha in [
                    AlphaPlane::U8(samples.iter().map(|&v| v as u8).collect()),
                    AlphaPlane::U16 {
                        data: samples.clone(),
                        bits: 16,
                    },
                    AlphaPlane::F32(samples.iter().map(|&v| i32::from(v) - 32768).collect()),
                ] {
                    let tokens = tokenize_channel(&alpha, width, height);
                    assert_eq!(tokens.len(), width * height);
                    for y in 0..height {
                        for x in 0..width {
                            let at = |x, y| alpha.get_i32(y * width + x);
                            let west = if x > 0 { at(x - 1, y) } else { 0 };
                            let north = if y > 0 { at(x, y - 1) } else { 0 };
                            let northwest = if x > 0 && y > 0 { at(x - 1, y - 1) } else { 0 };
                            let expected = pack_signed(at(x, y) - gradient(west, north, northwest));
                            let token = tokens[y * width + x];
                            assert_eq!(
                                (token.context, token.value),
                                (0, expected),
                                "channel token mismatch at ({x}, {y}) for {width}x{height}",
                            );
                        }
                    }
                }
            }
        }
    }

    #[test]
    fn tokenize_empty_channel() {
        for (width, height) in [(0, 0), (0, 3), (3, 0)] {
            assert!(tokenize_channel(&AlphaPlane::U8(Vec::new()), width, height).is_empty());
        }
    }

    #[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, 1, true, &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 chan = vec![200u8; 512 * 400];
        let alpha = AlphaPlane::from_u8(chan);
        let mut scratch = CoderScratch::default();
        let bits = |ans: bool, scratch: &mut CoderScratch| {
            let mut w = BitWriter::new();
            write_lfglobal_alpha_section(&alpha, 512, 400, 1, ans, scratch, &mut w);
            w.bits_written()
        };
        // Large path: only the 4-bit GroupHeader, plus the empty stream's
        // final state when the global code is ANS.
        assert_eq!(bits(false, &mut scratch), 4);
        assert_eq!(bits(true, &mut scratch), 4 + 32);
    }

    #[test]
    fn near_constant_16bit_alpha_group_takes_the_lz77_section() {
        // 65535 predicted from zero is literal symbol 67, above the 8-bit
        // length alphabet start. One impure sample otherwise forces the
        // prefix floor of a bit per pixel.
        let (w, h) = (512, 256);
        let mut data = vec![u16::MAX; w * h];
        data[1234] = u16::MAX - 1;
        let alpha = AlphaPlane::U16 { data, bits: 16 };
        let mut scratch = CoderScratch::default();
        let mut section = BitWriter::new();
        write_ac_group_alpha(&alpha, w, h, 0, 0, 256, 256, 1, &mut scratch, &mut section);
        assert!(section.bits_written() < 1024, "{}", section.bits_written());
    }
}