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
/*
 * // 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.
 */

//! DC predictors, token collection, context trees and rate estimates.

use crate::bit_writer::BitWriter;
use crate::coder_scratch::DcPredictorScratch;
use crate::dc_group_data::DcGroupData;
use crate::entropy::{Token, f_log2, pack_signed};
use crate::static_entropy_codes::{
    K_CONTEXT_TREE_TOKENS, K_GRADIENT_CONTEXT_LUT, K_NUM_DC_CONTEXTS,
};
use crate::weighted_predictor::WpParams;

const K_NUM_TREE_CONTEXTS: usize = 6;

pub(super) const K_GRAD_RANGE_MID: i64 = 512;
pub(super) const K_GRAD_RANGE_MIN: i64 = 0;
pub(super) const K_GRAD_RANGE_MAX: i64 = 1023;

#[inline]
pub(super) fn clamped_gradient(n: i32, w: i32, l: i32) -> i32 {
    let mn = n.min(w);
    let mx = n.max(w);
    let g = (n as i64 + w as i64 - l as i64) as i32;
    g.clamp(mn, mx)
}

#[inline(always)]
fn push_dc_wp_token(
    tokens: &mut Vec<Token>,
    gradient_tokens: &mut Vec<Token>,
    collect_gradient: bool,
    wp: &mut crate::weighted_predictor::WpState,
    x: usize,
    y: usize,
    value: i64,
    n: i64,
    w: i64,
    ne: i64,
    nw: i64,
    nn: i64,
    dc_gradient: &DcPredictorChoice,
    mchan: usize,
    props: &mut Vec<crate::dc_tree::DcProp>,
    collect_props: bool,
) {
    let wp_prediction = wp.predict(x, y, n, w, ne, nw, nn);
    let prop = (K_GRAD_RANGE_MID + wp.wp_prop).clamp(K_GRAD_RANGE_MIN, K_GRAD_RANGE_MAX) as usize;
    if collect_props {
        props.push(crate::dc_tree::dc_prop(mchan, prop));
    }
    wp.update(value, x, y);
    // The context comes from the weighted predictor's error whichever predictor
    // the leaf ends up using, so the tree is navigated identically either way
    // and the per-leaf choice below costs nothing to signal.
    let context = K_GRADIENT_CONTEXT_LUT[prop] as usize;
    let prediction = if dc_gradient[context] {
        (n + w - nw).clamp(n.min(w), n.max(w))
    } else {
        wp_prediction
    };
    tokens.push(Token::new(
        context as u32,
        pack_signed((value - prediction) as i32),
    ));
    if collect_gradient {
        let gradient = (n + w - nw).clamp(n.min(w), n.max(w));
        gradient_tokens.push(Token::new(
            context as u32,
            pack_signed((value - gradient) as i32),
        ));
    }
}

/// Per-leaf predictor selection for the DC plane, indexed by DC context.
pub(super) type DcPredictorChoice = [bool; K_NUM_DC_CONTEXTS];

pub(crate) const DC_PREDICTOR_WEIGHTED: DcPredictorChoice = [false; K_NUM_DC_CONTEXTS];
pub(super) const DC_PREDICTOR_GRADIENT: DcPredictorChoice = [true; K_NUM_DC_CONTEXTS];

/// Pick, for every DC leaf independently, whichever predictor codes its own
/// tokens in fewer bits. Both candidate streams share a context assignment, so
/// `wp[i]` and `grad[i]` differ only in value and the merged stream is a
/// per-token pick — no third tokenization pass.
pub(super) fn choose_dc_predictors(
    wp: &[Vec<Token>],
    grad: &[Vec<Token>],
    scratch: &mut DcPredictorScratch,
) -> DcPredictorChoice {
    // [candidate][context][symbol] counts, plus the raw extra bits per context.
    let counts = &mut scratch.counts;
    let extra = &mut scratch.extra;
    // A flat integer fill avoids expanding the reset into row-sized stores.
    counts.as_flattened_mut().fill(0);
    extra.fill(0);
    for (cand, groups) in [wp, grad].into_iter().enumerate() {
        for token in groups.iter().flatten() {
            let (sym, nbits, _) = crate::entropy::uint_encode(token.value);
            let slot = cand * K_NUM_DC_CONTEXTS + token.context as usize;
            counts[slot][sym as usize] += 1;
            extra[slot] += nbits as u64;
        }
    }
    choose_dc_predictors_from_counts(scratch)
}

pub(super) fn choose_dc_predictors_from_counts(scratch: &DcPredictorScratch) -> DcPredictorChoice {
    let counts = &scratch.counts;
    let extra = &scratch.extra;
    let cost = |slot: usize| -> f64 {
        let total: u32 = counts[slot].iter().sum();
        if total == 0 {
            return 0.0;
        }
        let total = f64::from(total);
        let entropy: f64 = counts[slot]
            .iter()
            .filter(|&&n| n != 0)
            .map(|&n| f64::from(n) * f_log2(total / f64::from(n)))
            .sum();
        entropy + extra[slot] as f64
    };
    let mut choice = DC_PREDICTOR_WEIGHTED;
    for (ctx, out) in choice.iter_mut().enumerate() {
        // The per-context Shannon cost ignores the clustering the real code
        // applies afterward, and leaves with few tokens are exactly the ones
        // clustering folds into a neighbor. Require a population and a margin
        // so a leaf only flips when the saving survives that noise.
        let (wp_cost, grad_cost) = (cost(ctx), cost(K_NUM_DC_CONTEXTS + ctx));
        let populated = counts[ctx].iter().sum::<u32>() >= MIN_TOKENS_PER_DC_LEAF;
        *out = populated && grad_cost < wp_cost * DC_PREDICTOR_MARGIN;
    }
    choice
}

/// A DC leaf must own at least this many tokens before its predictor may flip.
const MIN_TOKENS_PER_DC_LEAF: u32 = 256;

/// Required saving before flipping a leaf away from the weighted predictor.
const DC_PREDICTOR_MARGIN: f64 = 0.995;

#[cfg(test)]
fn collect_dc_tokens(
    dc_data: &DcGroupData,
    dc_gradient: &DcPredictorChoice,
    props: &mut Vec<crate::dc_tree::DcProp>,
    collect_props: bool,
) -> Vec<Token> {
    collect_dc_tokens_with_gradient(
        dc_data,
        dc_gradient,
        props,
        collect_props,
        false,
        WpParams::DEFAULT,
    )
    .0
}

pub(crate) fn collect_dc_tokens_with_gradient(
    dc_data: &DcGroupData,
    dc_gradient: &DcPredictorChoice,
    props: &mut Vec<crate::dc_tree::DcProp>,
    collect_props: bool,
    collect_gradient: bool,
    wp_params: WpParams,
) -> (Vec<Token>, Vec<Token>) {
    let token_count = [1usize, 0, 2]
        .into_iter()
        .map(|c| dc_data.quant_dc.plane(c).as_slice().len())
        .sum();
    let mut tokens = Vec::with_capacity(token_count);
    let mut gradient_tokens = Vec::with_capacity(if collect_gradient { token_count } else { 0 });
    for (mchan, c) in [1usize, 0, 2].into_iter().enumerate() {
        let (channel_tokens, channel_gradient) = collect_dc_channel_tokens(
            dc_data,
            mchan,
            c,
            dc_gradient,
            props,
            collect_props,
            collect_gradient,
            wp_params,
        );
        tokens.extend(channel_tokens);
        gradient_tokens.extend(channel_gradient);
    }
    (tokens, gradient_tokens)
}

/// One channel of [`collect_dc_tokens_with_gradient`]: plane `c` of the
/// group coded as modular channel `mchan`. Channels carry no state across
/// each other, so a group's tokens are its channels' in order.
#[allow(clippy::too_many_arguments)]
pub(crate) fn collect_dc_channel_tokens(
    dc_data: &DcGroupData,
    mchan: usize,
    c: usize,
    dc_gradient: &DcPredictorChoice,
    props: &mut Vec<crate::dc_tree::DcProp>,
    collect_props: bool,
    collect_gradient: bool,
    wp_params: WpParams,
) -> (Vec<Token>, Vec<Token>) {
    let plane = dc_data.quant_dc.plane(c);
    let token_count = plane.as_slice().len();
    let mut tokens = Vec::with_capacity(token_count);
    let mut gradient_tokens = Vec::with_capacity(if collect_gradient { token_count } else { 0 });
    walk_dc_channel(
        plane.as_slice(),
        plane.xsize(),
        plane.ysize(),
        plane.xsize(),
        mchan,
        dc_gradient,
        props,
        collect_props,
        collect_gradient,
        wp_params,
        &mut tokens,
        &mut gradient_tokens,
    );
    (tokens, gradient_tokens)
}

/// Tokenize one DC channel: a `xsize`×`ysize` window of rows `stride` apart.
///
/// Weighted-predictor DC, mirroring libjxl's kWPFixedDC path (enc_modular.cc
/// AddVarDCTDC at speed tiers falcon..squirrel): the guess is the
/// self-correcting WP and the context is the WP-error property (modular
/// property 15) bucketed by the same +-500 cutoffs the gradient tree used,
/// so K_GRADIENT_CONTEXT_LUT applies unchanged (write_context_tree emits the
/// matching tree: identical structure, property 15, Weighted leaves). The WP
/// state machine and border conventions are the bit-faithful lossless-path
/// ones, so encoder residuals match the reference decoder exactly.
///
/// NOTE: this walk is shared by the DC coder and by [`price_dc_plane`], which
/// prices the candidate planes of `choose_chroma_dc_coding`. Keep it the
/// single source of the DC tokenization: a change here reaches both, but a
/// change to how DC tokens are entropy-coded elsewhere (contexts, learned
/// trees, token packing) must be mirrored in `price_dc_plane`, or the
/// squeeze decision prices a coder that no longer exists.
#[allow(clippy::too_many_arguments)]
pub(super) fn walk_dc_channel<T: Copy + Into<i64>>(
    data: &[T],
    xsize: usize,
    ysize: usize,
    stride: usize,
    mchan: usize,
    dc_gradient: &DcPredictorChoice,
    props: &mut Vec<crate::dc_tree::DcProp>,
    collect_props: bool,
    collect_gradient: bool,
    wp_params: WpParams,
    tokens: &mut Vec<Token>,
    gradient_tokens: &mut Vec<Token>,
) {
    if xsize == 0 || ysize == 0 {
        return;
    }
    let row = |y: usize| &data[y * stride..y * stride + xsize];
    let mut wp = crate::weighted_predictor::WpState::with_params(xsize, wp_params);

    // On the top row every unavailable north-side neighbor collapses to
    // the value on the left.
    let first_row = row(0);
    let mut left = 0i64;
    for (x, &value) in first_row.iter().enumerate() {
        let value: i64 = value.into();
        push_dc_wp_token(
            tokens,
            gradient_tokens,
            collect_gradient,
            &mut wp,
            x,
            0,
            value,
            left,
            left,
            left,
            left,
            left,
            dc_gradient,
            mchan,
            props,
            collect_props,
        );
        left = value;
    }

    let mut row_above = first_row;
    let mut row_above2 = first_row;
    for y in 1..ysize {
        let current_row = row(y);

        // First column: W and NW replicate N.
        let n: i64 = row_above[0].into();
        let ne: i64 = row_above.get(1).copied().unwrap_or(row_above[0]).into();
        push_dc_wp_token(
            tokens,
            gradient_tokens,
            collect_gradient,
            &mut wp,
            0,
            y,
            current_row[0].into(),
            n,
            n,
            ne,
            n,
            row_above2[0].into(),
            dc_gradient,
            mchan,
            props,
            collect_props,
        );

        // Interior columns have every neighbor available.
        let current_pairs = current_row.array_windows::<2>();
        let north_triplets = row_above.array_windows::<3>();
        for (offset, ((current, north), &nn)) in current_pairs
            .zip(north_triplets)
            .zip(row_above2.iter().skip(1))
            .enumerate()
        {
            push_dc_wp_token(
                tokens,
                gradient_tokens,
                collect_gradient,
                &mut wp,
                offset + 1,
                y,
                current[1].into(),
                north[1].into(),
                current[0].into(),
                north[2].into(),
                north[0].into(),
                nn.into(),
                dc_gradient,
                mchan,
                props,
                collect_props,
            );
        }

        // Last column: NE replicates N. Width one was handled above.
        if xsize > 1 {
            let x = xsize - 1;
            let n: i64 = row_above[x].into();
            push_dc_wp_token(
                tokens,
                gradient_tokens,
                collect_gradient,
                &mut wp,
                x,
                y,
                current_row[x].into(),
                n,
                current_row[x - 1].into(),
                n,
                row_above[x - 1].into(),
                row_above2[x].into(),
                dc_gradient,
                mchan,
                props,
                collect_props,
            );
        }

        row_above2 = row_above;
        row_above = current_row;
    }
}

/// Bits to code `levels` — a `width`×`height` window of a DC plane whose rows
/// are `stride` apart — the way the DC coder codes it: the weighted
/// predictor's residuals in their WP-error contexts, priced as per-context
/// order-0 entropy of the hybrid-uint symbols plus their raw bits. This is
/// the price `choose_chroma_dc_coding` compares its candidate planes with.
///
/// NOTE: keep in step with the DC coder (see [`walk_dc_channel`]).
pub(crate) fn price_dc_plane(levels: &[i32], width: usize, height: usize, stride: usize) -> f64 {
    let mut price = DcPlanePrice::default();
    price.add(levels, width, height, stride);
    price.bits()
}

/// Reusable weighted-predictor price for one channel across DC groups. The
/// predictor restarts for every group, while all groups share the histograms,
/// just as they share the final frame's entropy code.
pub(crate) struct DcPlanePrice {
    pub(super) tokens: Vec<Token>,
    pub(super) counts: Vec<[u32; crate::entropy::ALPHABET_SIZE]>,
    pub(super) raw_bits: u64,
}

impl Default for DcPlanePrice {
    fn default() -> Self {
        Self {
            tokens: Vec::new(),
            counts: vec![[0; crate::entropy::ALPHABET_SIZE]; K_NUM_DC_CONTEXTS],
            raw_bits: 0,
        }
    }
}

impl DcPlanePrice {
    pub(crate) fn clear(&mut self) {
        self.counts.as_flattened_mut().fill(0);
        self.raw_bits = 0;
    }

    pub(crate) fn add<T: Copy + Into<i64>>(
        &mut self,
        levels: &[T],
        width: usize,
        height: usize,
        stride: usize,
    ) {
        self.tokens.clear();
        walk_dc_channel(
            levels,
            width,
            height,
            stride,
            0,
            &DC_PREDICTOR_WEIGHTED,
            &mut Vec::new(),
            false,
            false,
            WpParams::DEFAULT,
            &mut self.tokens,
            &mut Vec::new(),
        );
        for token in &self.tokens {
            let (sym, nbits, _) = crate::entropy::uint_encode(token.value);
            self.counts[token.context as usize][sym as usize] += 1;
            self.raw_bits += u64::from(nbits);
        }
    }

    /// Count a token from an existing weighted-predictor walk.
    pub(super) fn add_token(&mut self, token: Token) {
        let (sym, nbits, _) = crate::entropy::uint_encode(token.value);
        self.counts[token.context as usize][sym as usize] += 1;
        self.raw_bits += u64::from(nbits);
    }

    /// Count another plane price's tokens here, as if they had been added
    /// to this one.
    pub(super) fn merge(&mut self, other: &Self) {
        for (mine, theirs) in self.counts.iter_mut().zip(&other.counts) {
            for (count, &extra) in mine.iter_mut().zip(theirs) {
                *count += extra;
            }
        }
        self.raw_bits += other.raw_bits;
    }

    pub(crate) fn bits(&self) -> f64 {
        let mut bits = self.raw_bits as f64;
        for ctx in &self.counts {
            let total: u32 = ctx.iter().sum();
            if total == 0 {
                continue;
            }
            let total = f64::from(total);
            bits += ctx
                .iter()
                .filter(|&&n| n != 0)
                .map(|&n| f64::from(n) * f_log2(total / f64::from(n)))
                .sum::<f64>();
        }
        bits
    }
}

/// Build and emit the context tree.
pub(crate) fn write_context_tree(
    num_dc_groups: usize,
    dc_gradient: &DcPredictorChoice,
    huffman_pool: &mut Vec<crate::entropy::HuffmanNode>,
    writer: &mut BitWriter,
) {
    let tokens = context_tree_tokens(num_dc_groups, dc_gradient);
    write_tree_tokens(&tokens, huffman_pool, writer);
}

/// The static context tree's tokens.
fn context_tree_tokens(num_dc_groups: usize, dc_gradient: &DcPredictorChoice) -> Vec<Token> {
    // Build tokens with the patched value at index 1.
    let mut tokens: Vec<Token> = K_CONTEXT_TREE_TOKENS
        .iter()
        .map(|&(ctx, val)| Token::new(ctx, val))
        .collect();
    tokens[1].value = pack_signed(1 + num_dc_groups as i32);
    // Retarget the DC-image region (leaves 11..=44) at the Weighted predictor,
    // mirroring libjxl's kWPFixedDC tree (enc_modular.cc / enc_ma PredefinedTree):
    // identical 33 cutoffs, but splitting on the WP-error property (15) instead
    // of the gradient property (9), with Weighted(6) leaves instead of
    // Gradient(5). Parse-aware transform of the static blob: prop-9 splits only
    // occur in the DC region; Gradient leaves also exist at meta contexts 9/10
    // (CfL), so predictor tokens are rewritten only for leaf indices >= 11.
    {
        let mut i = 0usize;
        let mut leaf_idx = 0usize;
        while i < tokens.len() {
            debug_assert_eq!(tokens[i].context, 1);
            if tokens[i].value == 0 {
                if leaf_idx >= 11 && tokens[i + 1].value == 5 && !dc_gradient[leaf_idx] {
                    tokens[i + 1] = Token::new(2, 6); // Gradient -> Weighted
                }
                leaf_idx += 1;
                i += 5;
            } else {
                if tokens[i].value == 9 + 1 {
                    tokens[i] = Token::new(1, 15 + 1); // gradient prop -> WP prop
                }
                i += 2; // split: PROPERTY, SPLITVAL
            }
        }
    }
    tokens
}

/// Serialize a context tree's token stream (its own entropy code included).
pub(crate) fn write_tree_tokens(
    tokens: &[Token],
    huffman_pool: &mut Vec<crate::entropy::HuffmanNode>,
    writer: &mut BitWriter,
) {
    writer.write(1, 1); // not an empty tree
    // The tree's own code over its K_NUM_TREE_CONTEXTS=6 contexts.
    crate::entropy::write_raced_token_stream(tokens, K_NUM_TREE_CONTEXTS, huffman_pool, writer);
}

/// Which context tree the DC bundle is written with.
#[derive(Clone)]
pub(super) enum DcTreeChoice {
    /// The static blob with per-leaf predictor flips.
    Static(DcPredictorChoice),
    /// A per-image learned tree, already serialized to tokens.
    Learned(Vec<Token>),
}

impl DcTreeChoice {
    pub(super) fn tokens(&self, num_dc_groups: usize) -> Vec<Token> {
        match self {
            Self::Static(grad) => context_tree_tokens(num_dc_groups, grad),
            Self::Learned(tokens) => tokens.clone(),
        }
    }
}

#[derive(Clone, Copy)]
pub(super) enum ModularTreeNode {
    /// PROPERTY and SPLITVAL token values; `prop > val` routes to `gt`.
    Split {
        prop: u32,
        val: u32,
        gt: usize,
        le: usize,
    },
    /// PREDICTOR, OFFSET, MULTIPLIER_LOG and MULTIPLIER_BITS token values.
    Leaf([u32; 4]),
}

/// Decode a BFS tree token stream into nodes (children in BFS order).
pub(super) fn parse_tree(tokens: &[Token]) -> Vec<ModularTreeNode> {
    let mut nodes = Vec::new();
    let mut declared = 1usize;
    let mut i = 0usize;
    while nodes.len() < declared {
        let prop = tokens[i].value;
        if prop == 0 {
            let leaf = std::array::from_fn(|k| tokens[i + 1 + k].value);
            nodes.push(ModularTreeNode::Leaf(leaf));
            i += 5;
        } else {
            nodes.push(ModularTreeNode::Split {
                prop,
                val: tokens[i + 1].value,
                gt: declared,
                le: declared + 1,
            });
            declared += 2;
            i += 2;
        }
    }
    debug_assert_eq!(i, tokens.len());
    nodes
}

pub(crate) struct CompactedTree {
    pub(crate) tokens: Vec<Token>,
    pub(crate) context_map: Vec<u8>,
    pub(crate) leaf_remap: Vec<u32>,
}

/// Remove splits whose branches reduce to the same predictor, offset,
/// multiplier and histogram. Remap the leaf IDs in bitstream order.
pub(super) fn compact_tree(tokens: &[Token], context_map: &[u8]) -> Option<CompactedTree> {
    use ModularTreeNode::{Leaf, Split};

    let nodes = parse_tree(tokens);
    let mut leaves: Vec<Option<([u32; 4], u8)>> = vec![None; nodes.len()];
    let mut context = 0;
    for (i, node) in nodes.iter().enumerate() {
        if let Leaf(value) = *node {
            leaves[i] = Some((value, context_map[context]));
            context += 1;
        }
    }
    debug_assert_eq!(context, context_map.len());

    let mut collapsed = false;
    for i in (0..nodes.len()).rev() {
        if let Split { gt, le, .. } = nodes[i]
            && leaves[gt].is_some()
            && leaves[le] == leaves[gt]
        {
            leaves[i] = leaves[gt];
            collapsed = true;
        }
    }
    // A one-leaf tree's pixel code uses an implicit context map.
    if !collapsed || leaves[0].is_some() {
        return None;
    }

    let mut queue = std::collections::VecDeque::from([0]);
    let mut remapped_nodes = vec![0u32; nodes.len()];
    let mut new_tokens = Vec::with_capacity(tokens.len());
    let mut new_map = Vec::with_capacity(context_map.len());
    while let Some(i) = queue.pop_front() {
        if let Some((value, cluster)) = leaves[i] {
            remapped_nodes[i] = new_map.len() as u32;
            new_map.push(cluster);
            new_tokens.push(Token::new(1, 0));
            new_tokens.extend(
                value
                    .into_iter()
                    .enumerate()
                    .map(|(k, v)| Token::new(2 + k as u32, v)),
            );
        } else if let Split { prop, val, gt, le } = nodes[i] {
            new_tokens.push(Token::new(1, prop));
            new_tokens.push(Token::new(0, val));
            queue.extend([gt, le]);
        }
    }
    // A removed subtree's original leaves inherit its replacement leaf ID.
    // Each node's parent precedes it in the original BFS numbering.
    for i in 0..nodes.len() {
        if let Split { gt, le, .. } = nodes[i]
            && leaves[i].is_some()
        {
            remapped_nodes[gt] = remapped_nodes[i];
            remapped_nodes[le] = remapped_nodes[i];
        }
    }
    let leaf_remap = nodes
        .into_iter()
        .zip(remapped_nodes)
        .filter_map(|(node, id)| matches!(node, Leaf(_)).then_some(id))
        .collect();
    Some(CompactedTree {
        tokens: new_tokens,
        context_map: new_map,
        leaf_remap,
    })
}

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

    /// Build one group of `n` tokens in `context`, all carrying `value`.
    fn leaf_tokens(context: u32, value: u32, n: usize) -> Vec<Vec<Token>> {
        vec![(0..n).map(|_| Token::new(context, value)).collect()]
    }

    #[test]
    fn dc_plane_price_pools_histograms_and_restarts_prediction() {
        let mut price = super::DcPlanePrice::default();
        price.add(&[0i16], 1, 1, 1);
        price.add(&[1i16], 1, 1, 1);
        // Two equally frequent symbols in one shared context cost two bits;
        // pricing the one-symbol groups separately would incorrectly cost zero.
        assert_eq!(price.bits(), 2.0);

        price.clear();
        assert_eq!(price.bits(), 0.0);
        price.add(&[100i16], 1, 1, 1);
        price.add(&[100i16], 1, 1, 1);
        // Each group's first sample predicts zero, so both tokens are identical.
        // Treating them as one row would instead code residuals 100 and zero.
        assert_eq!(price.bits(), 2.0 * super::price_dc_plane(&[100], 1, 1, 1));
        assert!(super::price_dc_plane(&[100, 100], 2, 1, 2) < price.bits());
    }

    #[test]
    fn dc_predictor_flips_only_on_a_decisive_populated_win() {
        let n = MIN_TOKENS_PER_DC_LEAF as usize;
        let ctx = 11;
        let mut scratch = DcPredictorScratch::default();

        // Gradient codes every residual as zero; the weighted predictor misses
        // by a wide, multi-extra-bit margin.
        let decisive = choose_dc_predictors(
            &leaf_tokens(ctx, 4000, n),
            &leaf_tokens(ctx, 0, n),
            &mut scratch,
        );
        assert!(decisive[ctx as usize], "a decisive gradient win must flip");

        // Identical streams: the margin must keep the weighted default.
        let tied = choose_dc_predictors(
            &leaf_tokens(ctx, 7, n),
            &leaf_tokens(ctx, 7, n),
            &mut scratch,
        );
        assert!(!tied[ctx as usize], "a tie must not flip");

        // Same decisive win, but below the population floor.
        let sparse = choose_dc_predictors(
            &leaf_tokens(ctx, 4000, n - 1),
            &leaf_tokens(ctx, 0, n - 1),
            &mut scratch,
        );
        assert!(
            !sparse[ctx as usize],
            "an underpopulated leaf must not flip"
        );
    }
}

#[cfg(test)]
mod fused_dc_tests {
    use super::*;
    #[test]
    fn fused_dc_candidates_match_separate_predictor_traversals() {
        for w in [1, 2, 3, 9, 32] {
            for h in [1, 2, 3, 17] {
                let mut dc = DcGroupData::new(w, h).unwrap();
                for c in 0..3 {
                    for y in 0..h {
                        for x in 0..w {
                            let i = (y * w + x + 1) * (c + 7);
                            dc.quant_dc.plane_row_mut(c, y)[x] =
                                (((i * 7919) ^ (i / 7 * 1237)) % 65536) as i16;
                        }
                    }
                }
                for collect_props in [false, true] {
                    for choice in [
                        DC_PREDICTOR_WEIGHTED,
                        DC_PREDICTOR_GRADIENT,
                        std::array::from_fn(|i| i % 2 == 0),
                    ] {
                        let mut expected_props = Vec::new();
                        let expected =
                            collect_dc_tokens(&dc, &choice, &mut expected_props, collect_props);
                        let grad =
                            collect_dc_tokens(&dc, &DC_PREDICTOR_GRADIENT, &mut Vec::new(), false);
                        let mut props = Vec::new();
                        let (fused, fused_grad) = collect_dc_tokens_with_gradient(
                            &dc,
                            &choice,
                            &mut props,
                            collect_props,
                            true,
                            WpParams::DEFAULT,
                        );
                        let values = |ts: Vec<Token>| {
                            ts.into_iter()
                                .map(|t| (t.context, t.value))
                                .collect::<Vec<_>>()
                        };
                        assert_eq!(values(fused), values(expected));
                        assert_eq!(values(fused_grad), values(grad));
                        assert_eq!(props, expected_props);
                    }
                }
            }
        }
    }
}