jixel 0.2.19

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
/*
 * // 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,
};

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.
        write_group_header_local_tree(w);
        let tokens = tokenize_channel(alpha, xsize, ysize, 0, 0, xsize, ysize, xsize);
        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);
        }
    } 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(data, full_xsize, x0, y0, gw, gh, &mut scratch.alpha_tokens)
            }
            AlphaPlane::U16 { data, .. } => {
                tokenize_ac_group_alpha(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)
            }
        }
    }

    const NUM_CTX: usize = 2; // leaf 0 (grad > 0), leaf 1 (grad <= 0)
    let pixel_code = build_pixel_code_n(&scratch.alpha_tokens, NUM_CTX, &mut scratch.huffman_pool);
    write_group_header_local_tree(w); // use_global_tree=0, wp default, 0 transforms
    write_split_tree(scratch, w); // 2-leaf Gradient tree, split on property 9 at 0
    w.write(1, 0); // no LZ77 for the pixel entropy code
    write_entropy_code(&pixel_code.as_ref(), &mut scratch.huffman_pool, w); // context map + 2 prefix codes
    let code_ref = pixel_code.as_ref();
    for tok in &scratch.alpha_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]
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;
    }
}

/// Collapse runs of identical packed residuals in RASTER order into LZ77 copies.
/// A run of L identical values is emitted as one literal (first pixel) followed,
/// when `L-1 >= LZ77_MIN_LENGTH`, by a copy of `L-1` covering the rest. The copy
/// length symbol is coded on the context of the first copied pixel (the pixel
/// right after the literal), matching how the decoder reads it.
#[allow(dead_code)]
fn lz77_compress_alpha(tokens: &[Token]) -> Vec<crate::lz77_ac::AcLz> {
    use crate::lz77_ac::{AcLz, LZ77_MIN_LENGTH};
    let mut out: Vec<AcLz> = Vec::with_capacity(tokens.len());
    let mut i = 0;
    while i < tokens.len() {
        let v = tokens[i].value;
        // Always emit the first element of the run as a literal (on its context).
        out.push(AcLz::Lit {
            context: tokens[i].context,
            value: v,
        });
        // Extend the run over identical *values* (context is irrelevant during a
        // copy — the decoder ignores it while replaying window values).
        let mut j = i + 1;
        while j < tokens.len() && tokens[j].value == v {
            j += 1;
        }
        let run_extra = (j - i - 1) as u32; // copied pixels after the literal
        if run_extra >= LZ77_MIN_LENGTH {
            // Copy covers pixels [i+1, j); length symbol coded on pixel (i+1)'s
            // context, distance 1 (repeat previous value).
            out.push(AcLz::Copy {
                context: tokens[i + 1].context,
                length_value: run_extra - LZ77_MIN_LENGTH,
            });
            i = j;
        } else {
            i += 1;
        }
    }
    out
}

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

/// Estimate the encoded size in bits of the plain (non-LZ) pixel token stream.
#[allow(dead_code)]
fn estimate_plain_bits(tokens: &[Token], code: &OwnedEntropyCode) -> u64 {
    let code_ref = code.as_ref();
    let mut bits: u64 = 0;
    for t in tokens {
        let (sym, nbits, _) = crate::entropy::uint_encode(t.value);
        let cl = code_ref.context_map[t.context as usize] as usize;
        let pc = &code_ref.prefix_codes[cl];
        // Single-symbol contexts cost 0 code bits (only extra bits).
        let d = if pc.single_symbol {
            0
        } else {
            pc.depths[sym as usize] as u64
        };
        bits += d + nbits as u64;
    }
    bits
}

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

    #[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 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().len() > 0);
        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);
    }
}