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
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
/*
 * // 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.
 */

// rANS entropy coding for JXL. Every format-bearing routine below was
// transcribed from libjxl (ans_common.{h,cc}, ans_params.h, enc_ans.{h,cc},
// dec_ans.{h,cc}) — not reconstructed from memory — and validated by
// round-tripping against a decoder also transcribed from libjxl:
//   * histogram normalization + encoding: randomized round-trips
//     (1-, 2-, and >=3-symbol/general cases).  [hist_selftest.rs]
//   * alias table + reverse_map + put_symbol + token stream: 8000 randomized
//     round-trips, and the libjxl final-state check (state == ANS_SIGNATURE<<16
//     after decode) passes every trial.  [ans_full_selftest.rs]
//
// Run the djxl pixel-identity oracle before trusting format-bearing changes end
// to end.

use super::TokenSlice;
use super::histogram::Histogram;
#[cfg(test)]
use super::token::Token;
use crate::bit_writer::BitWriter;
use crate::entropy::dlog2::{f_fmla, f_log2};
use crate::entropy::fast_div_u16::FastDivU16;
#[cfg(not(target_arch = "aarch64"))]
use crate::fast_divide::DividerU64;
use std::sync::OnceLock;

pub(crate) const ANS_LOG_TAB_SIZE: u32 = 12;
pub(crate) const ANS_TAB_SIZE: u32 = 1 << ANS_LOG_TAB_SIZE; // 4096
pub(crate) const ANS_SIGNATURE: u32 = 0x13;

/// A normalized ANS distribution together with the representation selected for
/// its bitstream header. Method 0 is flat, method 1 is the lowest precision,
/// and methods 2..=12 use progressively more count precision. Small trees use
/// their dedicated representation regardless of `method`.
#[derive(Clone)]
pub(crate) struct AnsHistogram {
    pub(crate) freqs: Vec<u16>,
    method: u8,
    omit_pos: u8,
    cost: f64,
}

// Alias-table geometry for the 128-symbol alphabet (log_alpha_size = 7).
const LOG_ALPHA_SIZE: usize = 7;
const TABLE_ENTRIES: usize = 1 << LOG_ALPHA_SIZE; // 128
const LOG_ENTRY_SIZE: usize = ANS_LOG_TAB_SIZE as usize - LOG_ALPHA_SIZE; // 5
const ENTRY_SIZE: u32 = 1 << LOG_ENTRY_SIZE; // 32
const ENTRY_SIZE_M1: u32 = ENTRY_SIZE - 1;

pub(crate) fn normalize_counts(counts: &[u32], freqs: &mut Vec<u16>) {
    let n = counts.len();
    if freqs.len() != n {
        freqs.resize(n, 0);
    }
    normalize_counts_into(counts, freqs);
}

/// Keep the first maximum on ties. Separating the value reduction from the
/// position search avoids vectorizing a wide index alongside every count.
#[inline]
fn first_maximum(freqs: &[u16]) -> (usize, u16) {
    let maximum = freqs.iter().copied().max().unwrap_or(0);
    let position = freqs.iter().position(|&freq| freq == maximum).unwrap_or(0);
    (position, maximum)
}

pub(crate) fn normalize_counts_into(counts: &[u32], freqs: &mut [u16]) {
    normalize_counts_first_maximum(counts, freqs);
}

/// Normalize and return the position of the first maximum frequency, which
/// the deficit branch already knows without another scan.
pub(crate) fn normalize_counts_first_maximum(counts: &[u32], freqs: &mut [u16]) -> usize {
    debug_assert_eq!(counts.len(), freqs.len());
    let total: u64 = counts.iter().map(|&c| c as u64).sum();
    if total == 0 {
        freqs.fill(0);
        return 0;
    }
    // AArch64's hardware divide wins over reciprocal setup for these short
    // histograms; other targets reuse the precomputed 64-bit divisor.
    #[cfg(target_arch = "aarch64")]
    let divider = total;
    #[cfg(not(target_arch = "aarch64"))]
    let divider = DividerU64::new(total);
    let table = ANS_TAB_SIZE as i64;
    // A positive count below twice one normalized unit always produces 1
    // after the minimum-frequency clamp. The shifted threshold avoids
    // overflowing even when the total count is large.
    let unit_limit = (total - 1) >> (ANS_LOG_TAB_SIZE - 1);
    let mut sum: i64 = 0;
    for (freq, &count) in freqs.iter_mut().zip(counts.iter()) {
        *freq = if u64::from(count) <= unit_limit {
            u16::from(count != 0)
        } else {
            (u64::from(count) * u64::from(ANS_TAB_SIZE) / divider) as u16
        };
        sum += i64::from(*freq);
    }
    while sum != table {
        let (mi, mf) = first_maximum(freqs);
        if sum < table {
            // Incrementing the first maximum keeps it the first maximum,
            // so the entire deficit belongs to this same symbol.
            freqs[mi] += (table - sum) as u16;
            return mi;
        } else if mf > 1 {
            freqs[mi] -= 1;
            sum -= 1;
        } else {
            break;
        }
    }
    first_maximum(freqs).0
}

/// Length of the populated alphabet prefix, scanning eight counts at a time
/// since most of the 128-entry table is usually empty.
pub(crate) fn populated_alphabet_size(counts: &[u32]) -> usize {
    let (chunks, tail) = counts.as_chunks::<8>();
    if let Some(i) = tail.iter().rposition(|&c| c != 0) {
        return chunks.len() * 8 + i + 1;
    }
    for (k, chunk) in chunks.iter().enumerate().rev() {
        if chunk.iter().fold(0u32, |acc, &c| acc | c) != 0 {
            let i = chunk.iter().rposition(|&c| c != 0).unwrap_or(0);
            return k * 8 + i + 1;
        }
    }
    0
}

#[derive(Clone, Copy)]
struct AllowedCount {
    count: u16,
    step_log: u8,
    delta_log: f64,
}

struct AllowedCounts {
    descending: Vec<AllowedCount>,
    index: Box<[u16; ANS_TAB_SIZE as usize]>,
}

static ALLOWED_COUNTS: OnceLock<[AllowedCounts; ANS_LOG_TAB_SIZE as usize]> = OnceLock::new();
static COUNT_LOG2: OnceLock<Box<[f64]>> = OnceLock::new();

fn count_log2() -> &'static [f64] {
    COUNT_LOG2.get_or_init(|| {
        (0..=ANS_TAB_SIZE)
            .map(|v| if v == 0 { 0.0 } else { f_log2(v as f64) })
            .collect::<Vec<_>>()
            .into_boxed_slice()
    })
}

fn allowed_counts() -> &'static [AllowedCounts; ANS_LOG_TAB_SIZE as usize] {
    ALLOWED_COUNTS.get_or_init(|| {
        let logs = count_log2();
        core::array::from_fn(|shift| {
            let mut descending = Vec::with_capacity(ANS_TAB_SIZE as usize);
            let mut index = Box::new([0u16; ANS_TAB_SIZE as usize]);
            let mut last = u16::MAX;
            for i in (0..ANS_TAB_SIZE as u16).rev() {
                let step_log = if i == 0 {
                    0
                } else {
                    let log = floor_log2(i as u32) as i32;
                    (log - get_pop_count_precision(log, shift as i32)) as u8
                };
                let current = i & !((1u16 << step_log) - 1);
                if current == last {
                    continue;
                }
                last = current;
                let slot = descending.len();
                index[current as usize] = slot as u16;
                if current == 0 {
                    descending.push(AllowedCount {
                        count: 0,
                        step_log: 0,
                        delta_log: f64::INFINITY,
                    });
                } else {
                    let previous = descending.last().map_or(current, |v| v.count);
                    descending.push(AllowedCount {
                        count: current,
                        step_log: if slot == 0 {
                            0
                        } else {
                            floor_log2((previous - current) as u32) as u8
                        },
                        delta_log: if slot == 0 {
                            0.0
                        } else {
                            logs[previous as usize] - logs[current as usize]
                        },
                    });
                }
            }
            AllowedCounts { descending, index }
        })
    })
}

#[derive(Clone, Copy)]
struct AdjustableBin {
    source_count: u32,
    count_index: usize,
    bin_index: usize,
}

/// Normalize to a distribution representable with `shift` precision. This is
/// the same greedy entropy maximization used by libjxl: one largest bin absorbs
/// the remainder while the other bins move among representable counts.
fn rebalance_counts(counts: &[u32], alphabet_size: usize, shift: usize) -> Option<AnsHistogram> {
    let total: u64 = counts[..alphabet_size].iter().map(|&v| v as u64).sum();
    if total == 0 {
        return Some(AnsHistogram {
            freqs: vec![0; counts.len()],
            method: (shift + 1) as u8,
            omit_pos: 0,
            cost: 0.0,
        });
    }
    let allowed = &allowed_counts()[shift];
    let logs = count_log2();
    let mut freqs = vec![0u16; counts.len()];
    let norm = ANS_TAB_SIZE as f64 / total as f64;
    let mut omit_pos = 0usize;
    let mut max_source = 0u32;
    let mut rest = ANS_TAB_SIZE as i32;
    let mut bins = Vec::with_capacity(alphabet_size);

    for i in 0..alphabet_size {
        let source = counts[i];
        if source > max_source {
            max_source = source;
            omit_pos = i;
        }
        let target = source as f64 * norm;
        let mut count = target.round().clamp((source != 0) as u8 as f64, 4095.0) as u16;
        let log = if count == 0 {
            0
        } else {
            floor_log2(count as u32) as i32
        };
        let step_log = if count == 0 {
            0
        } else {
            log - get_pop_count_precision(log, shift as i32)
        };
        count &= !((1u16 << step_log) - 1);
        freqs[i] = count;
        rest -= count as i32;
        if target > 1.0 {
            bins.push(AdjustableBin {
                source_count: source,
                count_index: allowed.index[count as usize] as usize,
                bin_index: i,
            });
        }
    }
    bins.retain(|b| b.bin_index != omit_pos);
    rest += freqs[omit_pos] as i32;

    if !bins.is_empty() {
        let max_step_log = allowed.descending[1].step_log as usize;
        loop {
            let mut balance_inc = [0.0f64; ANS_LOG_TAB_SIZE as usize - 1];
            let mut balance_dec = [0.0f64; ANS_LOG_TAB_SIZE as usize - 1];
            for log in 0..=max_step_log {
                let delta = 1i32 << log;
                if rest >= ANS_TAB_SIZE as i32 {
                    balance_inc[log] = 0.0;
                    balance_dec[log] = 0.0;
                } else if rest > 1 {
                    balance_inc[log] = if rest > delta {
                        max_source as f64 * (logs[rest as usize] - logs[(rest - delta) as usize])
                    } else {
                        f64::INFINITY
                    };
                    balance_dec[log] = if rest + delta < ANS_TAB_SIZE as i32 {
                        max_source as f64 * (logs[(rest + delta) as usize] - logs[rest as usize])
                    } else {
                        f64::INFINITY
                    };
                } else {
                    balance_inc[log] = f64::INFINITY;
                    balance_dec[log] = f64::INFINITY;
                }
            }

            let inc_delta = |b: &AdjustableBin| {
                let a = allowed.descending[b.count_index];
                (b.source_count as f64 * a.delta_log - balance_inc[a.step_log as usize])
                    / (1u32 << a.step_log) as f64
            };
            let dec_delta = |b: &AdjustableBin| {
                let a = allowed.descending[b.count_index + 1];
                (b.source_count as f64 * a.delta_log - balance_dec[a.step_log as usize])
                    / (1u32 << a.step_log) as f64
            };

            let best_inc = bins
                .iter()
                .enumerate()
                .max_by(|(_, a), (_, b)| inc_delta(a).total_cmp(&inc_delta(b)))
                .map(|(i, _)| i)
                .unwrap();
            if inc_delta(&bins[best_inc]) > 0.0 {
                let step = allowed.descending[bins[best_inc].count_index].step_log;
                bins[best_inc].count_index -= 1;
                rest -= 1i32 << step;
                continue;
            }
            let best_dec = bins
                .iter()
                .enumerate()
                .min_by(|(_, a), (_, b)| dec_delta(a).total_cmp(&dec_delta(b)))
                .map(|(i, _)| i)
                .unwrap();
            if dec_delta(&bins[best_dec]) >= 0.0 {
                break;
            }
            bins[best_dec].count_index += 1;
            let step = allowed.descending[bins[best_dec].count_index].step_log;
            rest += 1i32 << step;
        }
        for bin in bins {
            freqs[bin.bin_index] = allowed.descending[bin.count_index].count;
        }
        for i in 0..omit_pos {
            if freqs[i] >= 2048 {
                freqs[omit_pos] = freqs[i];
                omit_pos = i;
                break;
            }
        }
    }
    if !(1..ANS_TAB_SIZE as i32).contains(&rest) {
        return None;
    }
    freqs[omit_pos] = rest as u16;
    Some(AnsHistogram {
        freqs,
        method: (shift + 1) as u8,
        omit_pos: omit_pos as u8,
        cost: 0.0,
    })
}

#[derive(Clone, Copy, Default)]
struct AliasEntry {
    cutoff: u32,
    right_value: u32,
    freq0: u32,
    offsets1: u32,
    freq1_xor_freq0: u32,
}

fn init_alias_table(distribution_in: &[u16]) -> [AliasEntry; TABLE_ENTRIES] {
    let range = ANS_TAB_SIZE;
    let entry_size = ENTRY_SIZE;
    let mut dist: Vec<u32> = distribution_in.iter().map(|&x| x as u32).collect();
    while dist.last() == Some(&0) {
        dist.pop();
    }
    if dist.is_empty() {
        dist.push(range);
    }
    let mut a = [AliasEntry::default(); TABLE_ENTRIES];

    if let Some(sym) = dist.iter().position(|&v| v == ANS_TAB_SIZE) {
        for i in 0..TABLE_ENTRIES {
            a[i].right_value = sym as u32;
            a[i].cutoff = 0;
            a[i].offsets1 = entry_size * i as u32;
            a[i].freq0 = 0;
            a[i].freq1_xor_freq0 = ANS_TAB_SIZE;
        }
        return a;
    }

    let mut underfull: Vec<u32> = Vec::with_capacity(TABLE_ENTRIES);
    let mut overfull: Vec<u32> = Vec::with_capacity(TABLE_ENTRIES);
    let mut cutoffs = [0u32; TABLE_ENTRIES];
    for (i, (&dist, cutoff)) in dist.iter().zip(cutoffs.iter_mut()).enumerate() {
        *cutoff = dist;
        if *cutoff > entry_size {
            overfull.push(i as u32);
        } else if *cutoff < entry_size {
            underfull.push(i as u32);
        }
    }
    for (i, cutoff) in
        (dist.len()..TABLE_ENTRIES).zip(cutoffs[dist.len()..TABLE_ENTRIES].iter_mut())
    {
        *cutoff = 0;
        underfull.push(i as u32);
    }
    while let Some(over) = overfull.pop() {
        let under = underfull.pop().expect("alias: underfull stack empty");
        let under_by = entry_size - cutoffs[under as usize];
        cutoffs[over as usize] -= under_by;
        a[under as usize].right_value = over;
        a[under as usize].offsets1 = cutoffs[over as usize];
        if cutoffs[over as usize] < entry_size {
            underfull.push(over);
        } else if cutoffs[over as usize] > entry_size {
            overfull.push(over);
        }
    }
    for (i, (&cutoff, a)) in cutoffs[..TABLE_ENTRIES]
        .iter()
        .zip(a[..TABLE_ENTRIES].iter_mut())
        .enumerate()
    {
        if cutoff == entry_size {
            a.right_value = i as u32;
            a.offsets1 = 0;
            a.cutoff = 0;
        } else {
            a.offsets1 -= cutoff;
            a.cutoff = cutoff;
        }
        let freq0 = if i < dist.len() { dist[i] } else { 0 };
        let i1 = a.right_value as usize;
        let freq1 = if i1 < dist.len() { dist[i1] } else { 0 };
        a.freq0 = freq0;
        a.freq1_xor_freq0 = freq1 ^ freq0;
    }
    a
}

struct AliasSymbol {
    value: usize,
    offset: usize,
}

#[inline]
fn alias_lookup(a: &[AliasEntry; TABLE_ENTRIES], value: u32) -> AliasSymbol {
    let i = (value >> LOG_ENTRY_SIZE) as usize;
    let pos = value & ENTRY_SIZE_M1;
    let greater = pos >= a[i].cutoff;
    let offsets1_or_0 = if greater { a[i].offsets1 } else { 0 };
    AliasSymbol {
        value: if greater {
            a[i].right_value as usize
        } else {
            i
        },
        offset: (offsets1_or_0 + pos) as usize,
    }
}

/// Per-symbol encoder info. `reverse_offset` selects this symbol's range in the
/// histogram's flat reverse map (the inverse of the alias lookup).
#[derive(Clone, Copy)]
pub(crate) struct AnsEncSymbolInfo {
    pub(crate) freq: u16,
    divider: FastDivU16,
    reverse_offset: u16,
}

/// Build the alias table for `freqs` and derive per-symbol encoder info.
/// `freqs` must sum to ANS_TAB_SIZE and `reverse_map` must have exactly that
/// many entries. The caller owns the storage so tables for every histogram can
/// share one allocation without placing an 8 KiB temporary on the stack.
pub(crate) fn build_symbol_info(freqs: &[u16], reverse_map: &mut [u16]) -> Vec<AnsEncSymbolInfo> {
    assert_eq!(reverse_map.len(), ANS_TAB_SIZE as usize);
    reverse_map.fill(0);
    let alias = init_alias_table(freqs);
    let mut reverse_offset = 0u16;
    let symbols: Vec<AnsEncSymbolInfo> = freqs
        .iter()
        .map(|&freq| {
            let info = AnsEncSymbolInfo {
                freq,
                divider: FastDivU16::new_or_one(freq),
                reverse_offset,
            };
            reverse_offset += freq;
            info
        })
        .collect();
    // A cluster that received no tokens has an all-zero table; its symbols
    // are never coded, so the empty table is harmless.
    debug_assert!(
        u32::from(reverse_offset) == ANS_TAB_SIZE || freqs.iter().all(|&f| f == 0),
        "frequencies sum to {reverse_offset}, expected {ANS_TAB_SIZE}"
    );

    for slot in 0..ANS_TAB_SIZE {
        let s = alias_lookup(&alias, slot);
        if s.value < symbols.len() && s.offset < symbols[s.value].freq as usize {
            let offset = symbols[s.value].reverse_offset as usize + s.offset;
            reverse_map[offset] = slot as u16;
        }
    }
    symbols
}

pub(crate) struct AnsCoder {
    state: u32,
}
impl AnsCoder {
    pub(crate) fn new() -> Self {
        Self {
            state: ANS_SIGNATURE << 16,
        }
    }
    #[inline]
    pub(crate) fn put_symbol(
        &mut self,
        info: &AnsEncSymbolInfo,
        reverse_map: &[u16],
    ) -> Option<u16> {
        let freq = info.freq as u32;
        debug_assert!(freq > 0, "ANS symbol with zero frequency");
        // A single-symbol table has an identity reverse map. Its frequency
        // is too large to renormalize a u32 state, and q * 4096 + rem is
        // exactly the input state, so neither the state nor the stream moves.
        if freq == ANS_TAB_SIZE {
            return None;
        }
        let reverse_offset = info.reverse_offset as usize;
        debug_assert!(reverse_offset + freq as usize <= reverse_map.len());

        let mut state = self.state;
        let mut emitted = None;
        if (state >> (32 - ANS_LOG_TAB_SIZE)) >= freq {
            emitted = Some((state & 0xffff) as u16);
            state >>= 16;
        }

        let (q, rem) = info.divider.div_rem_fast(state, freq);
        let mapped = reverse_map[reverse_offset + rem as usize] as u32;
        self.state = (q << ANS_LOG_TAB_SIZE) + mapped;
        emitted
    }
    #[inline]
    pub(crate) fn state(&self) -> u32 {
        self.state
    }
}

const ANS_NO_EMIT: u32 = u32::MAX;

pub(crate) fn write_ans_tokens<'a>(
    tokens: impl Into<TokenSlice<'a>>,
    context_map: &[u8],
    symbol_info: &[Vec<AnsEncSymbolInfo>],
    reverse_maps: &[u16],
    hybrid_uint_configs: &[super::token::HybridUintConfig],
    w: &mut BitWriter,
) {
    let tokens = tokens.into();
    // The reverse ANS traversal records, per token, the renormalization word
    // (or `ANS_NO_EMIT`) in the high half and the extra bits in the low half,
    // with the extra-bit count alongside, so the forward pass only writes.
    let mut emitted: Vec<u64> = Vec::with_capacity(tokens.len());
    let mut extra_bits: Vec<u8> = Vec::with_capacity(tokens.len());
    let mut coder = AnsCoder::new();
    tokens.iter().rev().for_each(|t| {
        let hist = context_map[t.context as usize] as usize;
        let (sym, nbits, bits) =
            super::token::uint_encode_with_config(t.value, hybrid_uint_configs[hist]);
        let start = hist * ANS_TAB_SIZE as usize;
        let word = coder.put_symbol(
            &symbol_info[hist][sym as usize],
            &reverse_maps[start..start + ANS_TAB_SIZE as usize],
        );
        emitted.push((u64::from(word.map_or(ANS_NO_EMIT, u32::from)) << 32) | u64::from(bits));
        extra_bits.push(nbits as u8);
    });
    w.write(32, coder.state() as u64);
    for (&packed, &nbits) in emitted.iter().rev().zip(extra_bits.iter().rev()) {
        let word = (packed >> 32) as u32;
        if word != ANS_NO_EMIT {
            w.write(16, u64::from(word));
        }
        if nbits != 0 {
            w.write(nbits as usize, packed & 0xffff_ffff);
        }
    }
}

#[cfg(test)]
pub(crate) fn ans_tokens_bits<'a>(
    tokens: impl Into<TokenSlice<'a>>,
    context_map: &[u8],
    symbol_info: &[Vec<AnsEncSymbolInfo>],
    reverse_maps: &[u16],
    hybrid_uint_configs: &[super::token::HybridUintConfig],
) -> usize {
    let tokens = tokens.into();
    let mut coder = AnsCoder::new();
    let mut bits = 32usize;
    tokens.iter().rev().for_each(|t| {
        let hist = context_map[t.context as usize] as usize;
        let (sym, nbits, _) =
            super::token::uint_encode_with_config(t.value, hybrid_uint_configs[hist]);
        let reverse_start = hist * ANS_TAB_SIZE as usize;
        let reverse_map = &reverse_maps[reverse_start..reverse_start + ANS_TAB_SIZE as usize];
        if coder
            .put_symbol(&symbol_info[hist][sym as usize], reverse_map)
            .is_some()
        {
            bits += 16;
        }
        bits += nbits as usize;
    });
    bits
}

#[derive(Clone, Copy)]
pub(crate) struct AnsTokenCodeRef<'a> {
    pub(crate) context_map: &'a [u8],
    pub(crate) symbol_info: &'a [Vec<AnsEncSymbolInfo>],
    pub(crate) reverse_maps: &'a [u16],
    pub(crate) hybrid_uint_configs: &'a [super::token::HybridUintConfig],
}

/// Exact bits of one ANS stream under `code`: its 32-bit state plus every
/// token's extra bits and renormalization words.
pub(crate) fn ans_tokens_bits_under<'a>(
    tokens: impl Into<TokenSlice<'a>>,
    code: &AnsTokenCodeRef<'_>,
) -> usize {
    let tokens = tokens.into();
    let mut coder = AnsCoder::new();
    let mut bits = 32usize;
    tokens.iter().rev().for_each(|token| {
        let hist = code.context_map[token.context as usize] as usize;
        let (symbol, nbits, _) =
            super::token::uint_encode_with_config(token.value, code.hybrid_uint_configs[hist]);
        let reverse_start = hist * ANS_TAB_SIZE as usize;
        if coder
            .put_symbol(
                &code.symbol_info[hist][symbol as usize],
                &code.reverse_maps[reverse_start..reverse_start + ANS_TAB_SIZE as usize],
            )
            .is_some()
        {
            bits += 16;
        }
        bits += nbits as usize;
    });
    bits
}

/// Count two ANS streams in one traversal, sharing symbolization when their
/// configurations agree. Reclustering may choose different configurations,
/// so each state must use its own symbol and extra-bit count in that case.
#[cfg(test)]
pub(crate) fn ans_tokens_bits_pair<'a>(
    tokens: impl Into<TokenSlice<'a>>,
    first: &AnsTokenCodeRef<'_>,
    second: &AnsTokenCodeRef<'_>,
) -> (usize, usize) {
    let tokens = tokens.into();
    let mut first_coder = AnsCoder::new();
    let mut second_coder = AnsCoder::new();
    let mut first_bits = 32usize;
    let mut second_bits = 32usize;
    tokens.iter().rev().for_each(|token| {
        let context = token.context as usize;
        let first_hist = first.context_map[context] as usize;
        let second_hist = second.context_map[context] as usize;
        let first_config = first.hybrid_uint_configs[first_hist];
        let (symbol, nbits, _) = super::token::uint_encode_with_config(token.value, first_config);
        let second_config = second.hybrid_uint_configs[second_hist];
        let (second_symbol, second_nbits, _) = if first_config == second_config {
            (symbol, nbits, 0)
        } else {
            super::token::uint_encode_with_config(token.value, second_config)
        };

        let first_reverse_start = first_hist * ANS_TAB_SIZE as usize;
        if first_coder
            .put_symbol(
                &first.symbol_info[first_hist][symbol as usize],
                &first.reverse_maps
                    [first_reverse_start..first_reverse_start + ANS_TAB_SIZE as usize],
            )
            .is_some()
        {
            first_bits += 16;
        }
        let second_reverse_start = second_hist * ANS_TAB_SIZE as usize;
        if second_coder
            .put_symbol(
                &second.symbol_info[second_hist][second_symbol as usize],
                &second.reverse_maps
                    [second_reverse_start..second_reverse_start + ANS_TAB_SIZE as usize],
            )
            .is_some()
        {
            second_bits += 16;
        }
        first_bits += nbits as usize;
        second_bits += second_nbits as usize;
    });
    (first_bits, second_bits)
}

#[inline]
fn floor_log2(x: u32) -> u32 {
    31 - x.leading_zeros()
} // x > 0

#[inline]
fn get_pop_count_precision(logcount: i32, shift: i32) -> i32 {
    let r = logcount.min(shift - ((ANS_LOG_TAB_SIZE as i32 - logcount) >> 1));
    if r < 0 { 0 } else { r }
}

pub(crate) trait HistogramWriter {
    fn write(&mut self, n_bits: usize, bits: u64);
}

impl HistogramWriter for BitWriter {
    #[inline]
    fn write(&mut self, n_bits: usize, bits: u64) {
        BitWriter::write(self, n_bits, bits);
    }
}

#[derive(Default)]
struct HistogramBitCounter(usize);

impl HistogramWriter for HistogramBitCounter {
    #[inline]
    fn write(&mut self, n_bits: usize, _bits: u64) {
        self.0 += n_bits;
    }
}

fn store_varlen_u8<W: HistogramWriter>(n: u32, w: &mut W) {
    if n == 0 {
        w.write(1, 0);
    } else {
        w.write(1, 1);
        let nbits = floor_log2(n);
        w.write(3, nbits as u64);
        w.write(nbits as usize, (n - (1 << nbits)) as u64);
    }
}

static K_BIT_WIDTH_LENGTHS: [u8; 14] = [5, 4, 4, 4, 4, 4, 3, 3, 3, 3, 3, 6, 7, 7];
static K_BIT_WIDTH_SYMBOLS: [u8; 14] = [17, 11, 15, 3, 9, 7, 4, 2, 5, 6, 0, 33, 1, 65];

/// Serialize one selected normalized histogram. `_log_alpha_size` is accepted
/// for API symmetry; the body trims to the true alphabet size.
pub(crate) fn encode_histogram<W: HistogramWriter>(
    histogram: &AnsHistogram,
    _log_alpha_size: u32,
    w: &mut W,
) {
    let freqs = &histogram.freqs;
    let mut alphabet_size = freqs.len();
    while alphabet_size > 0 && freqs[alphabet_size - 1] == 0 {
        alphabet_size -= 1;
    }
    debug_assert!(alphabet_size <= TABLE_ENTRIES);
    if histogram.method == 0 {
        w.write(1, 0); // non-small
        w.write(1, 1); // uniform
        debug_assert!(alphabet_size > 0);
        store_varlen_u8((alphabet_size - 1) as u32, w);
        return;
    }
    let mut symbols = [0usize; 2];
    let mut num_symbols = 0usize;
    for (i, &freq) in freqs[..alphabet_size].iter().enumerate() {
        if freq != 0 {
            if num_symbols < symbols.len() {
                symbols[num_symbols] = i;
            }
            num_symbols += 1;
        }
    }

    if num_symbols <= 2 {
        w.write(1, 1); // small-tree marker
        if num_symbols == 0 {
            w.write(1, 0);
            store_varlen_u8(0, w);
        } else {
            w.write(1, (num_symbols - 1) as u64);
            for &s in &symbols[..num_symbols] {
                store_varlen_u8(s as u32, w);
            }
        }
        if num_symbols == 2 {
            w.write(ANS_LOG_TAB_SIZE as usize, freqs[symbols[0]] as u64);
        }
        return;
    }

    // General tree.
    w.write(1, 0); // non-small
    w.write(1, 0); // non-flat
    let method = histogram.method as u32;
    let upper_bound_log = floor_log2(ANS_LOG_TAB_SIZE + 1); // 3
    let log = floor_log2(method); // 3
    w.write(log as usize, ((1u32 << log) - 1) as u64);
    if log != upper_bound_log {
        w.write(1, 0);
    }
    w.write(log as usize, (((1u32 << log) - 1) & method) as u64);

    store_varlen_u8((alphabet_size - 3) as u32, w);

    let omit_pos = histogram.omit_pos as usize;
    debug_assert!(omit_pos < alphabet_size);

    let mut bit_width = [0u8; TABLE_ENTRIES];
    let mut omit_width: i32 = 10;
    for (i, (bit_width, &count)) in bit_width
        .iter_mut()
        .zip(freqs[..alphabet_size].iter())
        .enumerate()
    {
        if i != omit_pos && count > 0 {
            *bit_width = (floor_log2(count as u32) + 1) as u8;
            let cand = *bit_width as i32 + if i < omit_pos { 1 } else { 0 };
            if cand > omit_width {
                omit_width = cand;
            }
        }
    }
    bit_width[omit_pos] = omit_width as u8;

    // Runs are split around the omitted count because it may use an artificial
    // bit width. Only runs of five or more save space with the static code.
    const MIN_REPS: usize = 5;
    const RLE_SYMBOL: usize = ANS_LOG_TAB_SIZE as usize + 1;
    let mut same = [0u8; TABLE_ENTRIES];
    let mut last = 0usize;
    for i in 1..=alphabet_size {
        if i == alphabet_size || i == omit_pos || i == omit_pos + 1 || freqs[i] != freqs[last] {
            same[last] = (i - last) as u8;
            last = i;
        }
    }

    let mut i = 0usize;
    while i < alphabet_size {
        let bw = bit_width[i] as usize;
        w.write(
            K_BIT_WIDTH_LENGTHS[bw] as usize,
            K_BIT_WIDTH_SYMBOLS[bw] as u64,
        );
        let run = same[i] as usize;
        if run >= MIN_REPS {
            w.write(
                K_BIT_WIDTH_LENGTHS[RLE_SYMBOL] as usize,
                K_BIT_WIDTH_SYMBOLS[RLE_SYMBOL] as u64,
            );
            store_varlen_u8((run - MIN_REPS) as u32, w);
            i += run;
        } else {
            i += 1;
        }
    }

    // Mantissa bits.
    let shift: i32 = (method - 1) as i32;
    if shift != 0 {
        let mut i = 0usize;
        while i < alphabet_size {
            let bit_width = bit_width[i];
            let count = freqs[i] as i32;
            if bit_width > 1 && i != omit_pos {
                let code = bit_width as i32 - 1;
                let bitcount = get_pop_count_precision(code, shift);
                let drop_bits = code - bitcount;
                debug_assert_eq!(count & ((1 << drop_bits) - 1), 0);
                w.write(
                    bitcount as usize,
                    ((count >> drop_bits) - (1 << bitcount)) as u64,
                );
            }
            let run = same[i] as usize;
            i += if run >= MIN_REPS { run } else { 1 };
        }
    }
}

fn flat_histogram(len: usize, storage_len: usize) -> AnsHistogram {
    let base = ANS_TAB_SIZE as usize / len;
    let remainder = ANS_TAB_SIZE as usize % len;
    let mut freqs = vec![0u16; storage_len];
    for (i, freq) in freqs[..len].iter_mut().enumerate() {
        *freq = (base + usize::from(i < remainder)) as u16;
    }
    AnsHistogram {
        freqs,
        method: 0,
        omit_pos: 0,
        cost: 0.0,
    }
}

fn histogram_cost(counts: &[u32], histogram: &AnsHistogram) -> f64 {
    ans_data_bits(counts, &histogram.freqs) + ans_table_bits(histogram)
}

/// Reusable buffers for `fast_ans_population_cost_scratch`: the clusterers
/// evaluate hundreds of thousands of candidate merges per frame, and the
/// per-call `Vec` allocations of the plain version dominated their time.
pub(crate) struct AnsCostScratch {
    freqs: [u16; TABLE_ENTRIES],
}

impl AnsCostScratch {
    pub(crate) fn new() -> Self {
        Self {
            freqs: [0; TABLE_ENTRIES],
        }
    }
}

struct FlatPopulationCost {
    symbol_bits: Box<[f64]>,
    table_bits: f64,
}

fn flat_population_costs() -> &'static [FlatPopulationCost] {
    static COSTS: OnceLock<Box<[FlatPopulationCost]>> = OnceLock::new();
    COSTS.get_or_init(|| {
        let logs = count_log2();
        (1..=TABLE_ENTRIES)
            .map(|len| {
                let flat = flat_histogram(len, len);
                FlatPopulationCost {
                    symbol_bits: flat
                        .freqs
                        .iter()
                        .map(|&freq| ANS_LOG_TAB_SIZE as f64 - logs[freq as usize])
                        .collect(),
                    table_bits: ans_table_bits(&flat),
                }
            })
            .collect()
    })
}

/// `fast_ans_population_cost` without allocation; identical result.
pub(crate) fn fast_ans_population_cost_scratch(
    counts: &[u32],
    data_scale: usize,
    scratch: &mut AnsCostScratch,
) -> f64 {
    debug_assert_eq!(counts.len(), TABLE_ENTRIES);
    let alphabet_size = populated_alphabet_size(counts);
    if alphabet_size == 0 {
        return 3.0;
    }
    // Normalization preserves zero counts. Keep the reusable buffers at the
    // active alphabet length so cost/table scans do not revisit zero tails.
    let counts = &counts[..alphabet_size];
    let freqs = &mut scratch.freqs[..alphabet_size];
    let omit_pos = normalize_counts_first_maximum(counts, freqs);
    // The flat distribution depends only on alphabet length. Cache its exact
    // symbol prices and serialized table size, and price both candidates in
    // one scan. Each accumulator retains the original symbol and FMA order.
    let flat = &flat_population_costs()[alphabet_size - 1];
    let logs = count_log2();
    let mut precise_bits = 0.0;
    let mut flat_bits = 0.0;
    for ((&count, &freq), &flat_price) in counts.iter().zip(freqs.iter()).zip(&flat.symbol_bits) {
        if count != 0 {
            precise_bits = f_fmla(
                count as f64,
                ANS_LOG_TAB_SIZE as f64 - logs[freq.max(1) as usize],
                precise_bits,
            );
            flat_bits = f_fmla(count as f64, flat_price, flat_bits);
        }
    }
    (precise_bits * data_scale as f64 + precise_ans_table_bits(freqs, omit_pos) as f64)
        .min(flat_bits * data_scale as f64 + flat.table_bits)
}

pub(crate) fn fast_ans_population_cost(counts: &[u32], data_scale: usize) -> f64 {
    let mut alphabet_size = counts.len();
    while alphabet_size > 0 && counts[alphabet_size - 1] == 0 {
        alphabet_size -= 1;
    }

    let mut freqs = Vec::new();
    normalize_counts(counts, &mut freqs);
    let (omit_pos, _) = first_maximum(&freqs[..alphabet_size]);
    let precise = AnsHistogram {
        freqs,
        method: 12,
        omit_pos: omit_pos as u8,
        cost: 0.0,
    };
    let scaled_cost = |histogram: &AnsHistogram| {
        ans_data_bits(counts, &histogram.freqs) * data_scale as f64 + ans_table_bits(histogram)
    };
    let mut best = scaled_cost(&precise);
    if alphabet_size != 0 {
        best = best.min(scaled_cost(&flat_histogram(alphabet_size, counts.len())));
    }
    best
}

/// Select the flat, small, or count-precision representation minimizing the
/// exact serialized header bits plus the modeled ANS payload bits.
pub(crate) fn optimize_ans_histogram(counts: &[u32]) -> AnsHistogram {
    let mut alphabet_size = counts.len();
    while alphabet_size > 0 && counts[alphabet_size - 1] == 0 {
        alphabet_size -= 1;
    }
    if alphabet_size == 0 {
        return AnsHistogram {
            freqs: vec![0; counts.len()],
            method: 1,
            omit_pos: 0,
            cost: 3.0,
        };
    }

    let mut best = flat_histogram(alphabet_size, counts.len());
    let mut best_cost = histogram_cost(counts, &best);
    best.cost = best_cost;
    let num_symbols = counts[..alphabet_size].iter().filter(|&&v| v != 0).count();
    if num_symbols == 1 {
        let symbol = counts[..alphabet_size]
            .iter()
            .position(|&v| v != 0)
            .unwrap();
        let mut freqs = vec![0; counts.len()];
        freqs[symbol] = ANS_TAB_SIZE as u16;
        let mut histogram = AnsHistogram {
            freqs,
            method: 1,
            omit_pos: symbol as u8,
            cost: 0.0,
        };
        histogram.cost = histogram_cost(counts, &histogram);
        return histogram;
    }

    // Small trees always store their one free population count at full
    // precision, so trying lower shifts would only change payload cost.
    if num_symbols == 2 {
        let mut freqs = Vec::new();
        normalize_counts(counts, &mut freqs);
        let omit_pos = freqs
            .iter()
            .enumerate()
            .max_by_key(|&(_, f)| f)
            .map_or(0, |(i, _)| i);
        let precise = AnsHistogram {
            freqs,
            method: 12,
            omit_pos: omit_pos as u8,
            cost: 0.0,
        };
        let precise_cost = histogram_cost(counts, &precise);
        if precise_cost < best_cost {
            let mut precise = precise;
            precise.cost = precise_cost;
            return precise;
        }
        return best;
    }

    // Full precision needs no constrained rebalance; retain the existing fast
    // normalization and additionally test libjxl's minimum/midpoint probes.
    let mut precise_freqs = Vec::new();
    normalize_counts(counts, &mut precise_freqs);
    let (precise_omit, _) = first_maximum(&precise_freqs[..alphabet_size]);
    let precise = AnsHistogram {
        freqs: precise_freqs,
        method: 12,
        omit_pos: precise_omit as u8,
        cost: 0.0,
    };
    let precise_cost = histogram_cost(counts, &precise);
    if precise_cost < best_cost {
        best = precise;
        best_cost = precise_cost;
        best.cost = best_cost;
    }

    // These are the remaining libjxl fast-strategy probes. Together with the
    // exact full-precision table above they capture the useful header/data
    // trade-off without making tiny images pay for twelve greedy rebalances.
    for shift in [0usize, ANS_LOG_TAB_SIZE as usize / 2] {
        if let Some(candidate) = rebalance_counts(counts, alphabet_size, shift) {
            let cost = histogram_cost(counts, &candidate);
            if cost < best_cost {
                best = candidate;
                best_cost = cost;
                best.cost = best_cost;
            }
        }
    }
    best
}

/// Extend the normal optimizer's precision search on a final histogram.
/// Its flat/small forms and shifts 0 and 6 are already in the incumbent.
/// Shift 11 also tests constrained full-precision normalization, which can
/// improve on the normal optimizer's faster full-precision normalization.
pub(crate) fn refine_ans_histogram_precision(
    counts: &[u32],
    incumbent: &AnsHistogram,
) -> Option<AnsHistogram> {
    let alphabet_size = counts.iter().rposition(|&c| c != 0).map_or(0, |i| i + 1);
    if counts[..alphabet_size].iter().filter(|&&c| c != 0).count() < 3 {
        return None;
    }
    let mut best = None;
    let mut best_cost = histogram_cost(counts, incumbent);
    for shift in [1, 2, 3, 4, 5, 7, 8, 9, 10, 11] {
        if let Some(mut candidate) = rebalance_counts(counts, alphabet_size, shift) {
            let cost = histogram_cost(counts, &candidate);
            if cost < best_cost {
                candidate.cost = cost;
                best = Some(candidate);
                best_cost = cost;
            }
        }
    }
    best
}

pub(crate) fn ans_data_bits(counts: &[u32], freqs: &[u16]) -> f64 {
    let mut bits = 0.0f64;
    let logs = count_log2();
    for (&freqs, &count) in freqs.iter().zip(counts.iter()) {
        if count == 0 {
            continue;
        }
        let f = freqs.max(1) as usize;
        bits = f_fmla(count as f64, ANS_LOG_TAB_SIZE as f64 - logs[f], bits);
    }
    bits
}

pub(crate) fn huffman_data_bits(counts: &[u32], depths: &[u8]) -> f64 {
    let mut bits = 0.0f64;
    for (&count, &depth) in counts.iter().zip(depths[..counts.len()].iter()) {
        bits = f_fmla(count as f64, depth as f64, bits);
    }
    bits
}

/// Count the full-precision header used by the clustering cost model. Its
/// mantissas need exactly `bit_width - 1` bits, so count them alongside the
/// width codes without building the serializer's width and run arrays.
fn precise_ans_table_bits(freqs: &[u16], omit_pos: usize) -> usize {
    fn varlen_bits(n: usize) -> usize {
        if n == 0 {
            1
        } else {
            4 + floor_log2(n as u32) as usize
        }
    }
    fn width(freq: u16) -> usize {
        (u16::BITS - freq.leading_zeros()) as usize
    }
    // Runs cannot cross the omitted count, whose width may be artificial.
    fn run_bits(freq: u16, run: usize) -> usize {
        let width = width(freq);
        let entry_bits = K_BIT_WIDTH_LENGTHS[width] as usize + width.saturating_sub(1);
        if run >= 5 {
            entry_bits
                + K_BIT_WIDTH_LENGTHS[ANS_LOG_TAB_SIZE as usize + 1] as usize
                + varlen_bits(run - 5)
        } else {
            run * entry_bits
        }
    }

    let mut symbols = freqs
        .iter()
        .enumerate()
        .filter_map(|(i, &freq)| (freq != 0).then_some(i));
    let Some(first) = symbols.next() else {
        return 3;
    };
    let Some(second) = symbols.next() else {
        return 2 + varlen_bits(first);
    };
    if symbols.next().is_none() {
        return 2 + varlen_bits(first) + varlen_bits(second) + ANS_LOG_TAB_SIZE as usize;
    }

    fn side_bits(freqs: &[u16]) -> (usize, u16) {
        let Some((&first, rest)) = freqs.split_first() else {
            return (0, 0);
        };
        let mut bits = 0;
        let mut max_freq = 0;
        let mut run_freq = first;
        let mut run = 1;
        for &freq in rest {
            if freq == run_freq {
                run += 1;
            } else {
                bits += run_bits(run_freq, run);
                max_freq = max_freq.max(run_freq);
                run_freq = freq;
                run = 1;
            }
        }
        (bits + run_bits(run_freq, run), max_freq.max(run_freq))
    }

    let (before, rest) = freqs.split_at(omit_pos.min(freqs.len()));
    let (before_bits, before) = side_bits(before);
    let (after_bits, after) = side_bits(rest.get(1..).unwrap_or_default());
    let omit_width = 10.max(width(before) + 1).max(width(after));
    // Non-small, non-flat, method 12, alphabet size, and the omitted width.
    8 + varlen_bits(freqs.len() - 3)
        + K_BIT_WIDTH_LENGTHS[omit_width] as usize
        + before_bits
        + after_bits
}

/// Exact table-overhead measurement. Full-precision cost probes can count
/// width codes and mantissas together; other forms use the actual serializer.
pub(crate) fn ans_table_bits(histogram: &AnsHistogram) -> f64 {
    if histogram.method == 12 {
        let alphabet_size = histogram
            .freqs
            .iter()
            .rposition(|&f| f != 0)
            .map_or(0, |i| i + 1);
        return precise_ans_table_bits(
            &histogram.freqs[..alphabet_size],
            histogram.omit_pos as usize,
        ) as f64;
    }
    let mut w = HistogramBitCounter::default();
    encode_histogram(histogram, LOG_ALPHA_SIZE as u32, &mut w);
    w.0 as f64
}

pub(crate) fn huffman_tree_bits_estimate(depths: &[u8]) -> f64 {
    let used = depths.iter().filter(|&&d| d != 0).count();
    f_fmla(used as f64, 4.0, 8.0)
}

/// Decide prefix vs rANS for a clustered-histogram bundle. true => prefix.
/// Picks the smaller total encoding (data + table); tie -> prefix (faster).
pub(crate) fn choose_use_prefix_code(
    histograms: &[Histogram],
    ans_histograms: &[AnsHistogram],
    huffman_depths: &[[u8; super::prefix_code::ALPHABET_SIZE]],
) -> bool {
    let mut ans_total = 0.0f64;
    let mut huff_total = 0.0f64;
    for ((h, histogram), depths) in histograms
        .iter()
        .zip(ans_histograms)
        .zip(huffman_depths.iter())
    {
        ans_total += histogram.cost;
        huff_total += huffman_data_bits(&h.counts, depths) + huffman_tree_bits_estimate(depths);
    }
    huff_total <= ans_total
}

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

    #[test]
    fn precise_table_cost_matches_serialized_bits() {
        let mut state = 0xc39e_729bu32;
        let check = |freqs: Vec<u16>, omit_pos: usize| {
            let histogram = AnsHistogram {
                freqs,
                method: 12,
                omit_pos: omit_pos as u8,
                cost: 0.0,
            };
            let mut writer = BitWriter::new();
            encode_histogram(&histogram, LOG_ALPHA_SIZE as u32, &mut writer);
            assert_eq!(
                ans_table_bits(&histogram) as usize,
                writer.bits_written(),
                "freqs={:?}, omit_pos={omit_pos}",
                histogram.freqs
            );
        };
        for case in 0..2_000 {
            let len = (case * 73) % (TABLE_ENTRIES + 1);
            let mut counts = [0; TABLE_ENTRIES];
            for (i, count) in counts[..len].iter_mut().enumerate() {
                state ^= state << 13;
                state ^= state >> 17;
                state ^= state << 5;
                *count = match case % 4 {
                    0 => 1,
                    1 => u32::from(i % 7 == 0) * (state % 10_000),
                    2 => u32::from(i == 0 || i + 1 == len),
                    _ => state % 10_000,
                };
            }
            let mut freqs = Vec::new();
            normalize_counts(&counts, &mut freqs);
            let (omit, _) = first_maximum(&freqs);
            check(freqs.clone(), omit);
            freqs.truncate(len);
            check(freqs, omit);
        }
        // Exercise the four/five-count RLE boundary, long zero/equal runs,
        // and runs split by the omitted population at either end or inside.
        for run in [4, 5, 6, 63, 126] {
            for repeated in [0, 1, 16] {
                let mut freqs = vec![repeated; run];
                freqs.extend([2, ANS_TAB_SIZE as u16 - repeated * run as u16 - 2]);
                for omit in [0, run / 2, freqs.len() - 1] {
                    check(freqs.clone(), omit);
                }
            }
        }
    }

    #[test]
    fn scratch_population_cost_matches_full_alphabet_after_reuse() {
        let mut scratch = AnsCostScratch::new();
        let mut state = 0x392dda71u32;
        // Alternate alphabet sizes so a shorter histogram follows a longer
        // one, including empty, singleton, sparse and full alphabets.
        for case in 0..1024 {
            let len = (case * 73) % (TABLE_ENTRIES + 1);
            let mut counts = [0; TABLE_ENTRIES];
            for (i, count) in counts[..len].iter_mut().enumerate() {
                state ^= state << 13;
                state ^= state >> 17;
                state ^= state << 5;
                *count = match case % 4 {
                    0 => 1,
                    1 => {
                        if i % 3 == 0 {
                            state % 10_000
                        } else {
                            0
                        }
                    }
                    2 => {
                        if i + 1 == len {
                            u32::MAX
                        } else {
                            0
                        }
                    }
                    _ => state % 10_000,
                };
            }
            for scale in [0, 1, 3, 17] {
                assert_eq!(
                    fast_ans_population_cost_scratch(&counts, scale, &mut scratch).to_bits(),
                    fast_ans_population_cost(&counts, scale).to_bits(),
                    "case={case}, scale={scale}",
                );
            }
        }
    }

    #[test]
    fn normalization_matches_one_count_at_a_time() {
        fn reference(counts: &[u32]) -> Vec<u16> {
            let total: u64 = counts.iter().map(|&c| u64::from(c)).sum();
            if total == 0 {
                return vec![0; counts.len()];
            }
            let mut freqs: Vec<u16> = counts
                .iter()
                .map(|&c| {
                    if c == 0 {
                        0
                    } else {
                        (u64::from(c) * u64::from(ANS_TAB_SIZE) / total).max(1) as u16
                    }
                })
                .collect();
            let mut sum: u32 = freqs.iter().map(|&f| u32::from(f)).sum();
            while sum != ANS_TAB_SIZE {
                let maximum = *freqs.iter().max().unwrap();
                let first = freqs.iter().position(|&f| f == maximum).unwrap();
                if sum < ANS_TAB_SIZE {
                    freqs[first] += 1;
                    sum += 1;
                } else if maximum > 1 {
                    freqs[first] -= 1;
                    sum -= 1;
                } else {
                    break;
                }
            }
            freqs
        }
        let mut state = 0x235da23eu32;
        for case in 0..2048 {
            let len = case % (TABLE_ENTRIES + 1);
            let counts: Vec<u32> = (0..len)
                .map(|i| {
                    state ^= state << 13;
                    state ^= state >> 17;
                    state ^= state << 5;
                    match case % 6 {
                        0 => 0,
                        1 => 1, // Equal maxima: the first symbol must retain the deficit.
                        2 => {
                            if i == len / 2 {
                                u32::MAX
                            } else {
                                1
                            }
                        } // Excess counts.
                        3 => state % 11,
                        4 => {
                            if i % 3 == 0 {
                                0
                            } else {
                                state
                            }
                        }
                        _ => state,
                    }
                })
                .collect();
            let mut freqs = vec![u16::MAX; len];
            normalize_counts_into(&counts, &mut freqs);
            assert_eq!(freqs, reference(&counts), "case={case}");
        }
    }

    fn assert_flat_reverse_map(freqs: &[u16]) {
        let alias = init_alias_table(freqs);
        let mut reverse_map = vec![0u16; ANS_TAB_SIZE as usize];
        let info = build_symbol_info(freqs, &mut reverse_map);
        let mut legacy: Vec<Vec<u16>> = freqs
            .iter()
            .map(|&freq| vec![0u16; freq as usize])
            .collect();
        for slot in 0..ANS_TAB_SIZE {
            let decoded = alias_lookup(&alias, slot);
            legacy[decoded.value][decoded.offset] = slot as u16;
        }
        assert_eq!(reverse_map.len(), ANS_TAB_SIZE as usize);
        assert_eq!(info.len(), freqs.len());

        let mut expected_offset = 0usize;
        for (symbol, (&freq, symbol_info)) in freqs.iter().zip(&info).enumerate() {
            assert_eq!(symbol_info.freq, freq);
            assert_eq!(symbol_info.reverse_offset as usize, expected_offset);
            assert_eq!(
                &reverse_map[expected_offset..expected_offset + freq as usize],
                legacy[symbol]
            );
            for remainder in 0..freq as usize {
                let slot = reverse_map[expected_offset + remainder] as u32;
                let decoded = alias_lookup(&alias, slot);
                assert_eq!(decoded.value, symbol);
                assert_eq!(decoded.offset, remainder);
            }
            expected_offset += freq as usize;
        }
        assert_eq!(expected_offset, ANS_TAB_SIZE as usize);
    }

    #[test]
    fn flat_reverse_map_inverts_alias_lookup() {
        // Keep symbol metadata small: the 4096-entry reverse table belongs to
        // the shared flat storage, never in a per-symbol or stack-local object.
        assert!(core::mem::size_of::<AnsEncSymbolInfo>() <= 16);

        let mut single = [0u16; TABLE_ENTRIES];
        single[37] = ANS_TAB_SIZE as u16;
        assert_flat_reverse_map(&single);

        let counts: [u32; TABLE_ENTRIES] =
            core::array::from_fn(|symbol| ((symbol * 29 + symbol * symbol * 7 + 11) % 251) as u32);
        let mut normalized = Vec::new();
        normalize_counts(&counts, &mut normalized);
        assert_flat_reverse_map(&normalized);
    }

    #[test]
    fn single_symbol_leaves_every_state_unchanged() {
        for symbol in [0, 37, TABLE_ENTRIES - 1] {
            let mut freqs = [0u16; TABLE_ENTRIES];
            freqs[symbol] = ANS_TAB_SIZE as u16;
            let mut reverse_map = vec![0u16; ANS_TAB_SIZE as usize];
            let info = build_symbol_info(&freqs, &mut reverse_map);
            assert!(
                reverse_map
                    .iter()
                    .enumerate()
                    .all(|(i, &v)| i == v as usize)
            );
            for state in [0, 1, 65_535, 65_536, 0x13ab_0000, u32::MAX] {
                let mut coder = AnsCoder { state };
                assert_eq!(coder.put_symbol(&info[symbol], &reverse_map), None);
                assert_eq!(coder.state(), state);
            }
        }
    }

    #[test]
    fn symbol_info_builds_on_a_small_stack() {
        crate::thread_pool::ThreadPool::on_small_stack(|| {
            let counts: [u32; TABLE_ENTRIES] =
                core::array::from_fn(|symbol| (symbol * 37 % 257 + 1) as u32);
            let mut freqs = Vec::new();
            normalize_counts(&counts, &mut freqs);
            let mut reverse_map = vec![0u16; ANS_TAB_SIZE as usize];
            let symbols = build_symbol_info(&freqs, &mut reverse_map);
            assert_eq!(symbols.len(), TABLE_ENTRIES);
        });
    }

    #[test]
    fn optimized_histograms_are_valid_and_representable() {
        let mut state = 0x1234_5678_9abc_def0u64;
        for case in 0..500 {
            let len = case % TABLE_ENTRIES + 1;
            let mut counts = vec![0u32; TABLE_ENTRIES];
            for count in &mut counts[..len] {
                state = state
                    .wrapping_mul(6_364_136_223_846_793_005)
                    .wrapping_add(1_442_695_040_888_963_407);
                *count = ((state >> 33) as u32) % 10_000;
            }
            // Keep the ANS builder's non-empty precondition while still
            // exercising sparse and long equal-count runs.
            counts[case % len] = counts[case % len].max(1);
            let histogram = optimize_ans_histogram(&counts);
            let refined = refine_ans_histogram_precision(&counts, &histogram);
            if let Some(refined) = &refined {
                assert!(histogram_cost(&counts, refined) < histogram_cost(&counts, &histogram));
            }
            for histogram in std::iter::once(histogram).chain(refined) {
                assert_eq!(
                    histogram.freqs.iter().map(|&v| v as u32).sum::<u32>(),
                    ANS_TAB_SIZE
                );
                assert!(histogram.method <= 12);
                if histogram.method == 0 {
                    let expected = flat_histogram(len, counts.len());
                    assert_eq!(histogram.freqs, expected.freqs);
                    continue;
                }
                for (i, (&source, &freq)) in counts.iter().zip(&histogram.freqs).enumerate() {
                    assert_eq!(source == 0, freq == 0);
                    if freq != 0 && i != histogram.omit_pos as usize {
                        let log = floor_log2(freq as u32) as i32;
                        let precision = get_pop_count_precision(log, histogram.method as i32 - 1);
                        let dropped = log - precision;
                        assert_eq!(freq & ((1u16 << dropped) - 1), 0);
                    }
                }
                let mut writer = BitWriter::new();
                encode_histogram(&histogram, LOG_ALPHA_SIZE as u32, &mut writer);
                assert!(writer.bits_written() != 0);
            }
        }
    }

    #[test]
    fn precision_refinement_skips_empty_and_small_histograms() {
        for counts in [vec![0; 128], vec![0, 23, 0], vec![7, 0, 11]] {
            let incumbent = optimize_ans_histogram(&counts);
            assert!(refine_ans_histogram_precision(&counts, &incumbent).is_none());
        }
    }

    #[test]
    fn flat_and_rle_forms_reduce_header_bits() {
        let flat = flat_histogram(128, 128);
        assert_eq!(ans_table_bits(&flat), 12.0);

        let mut freqs = vec![16u16; 128];
        freqs[0] += 2048;
        let histogram = AnsHistogram {
            freqs,
            method: 12,
            omit_pos: 0,
            cost: 0.0,
        };
        // Without RLE, 127 identical width-5 counts alone need 508 bits.
        assert!(ans_table_bits(&histogram) < 100.0);
    }

    #[test]
    fn token_bit_counter_matches_writer_exactly() {
        use crate::entropy::token::{HybridUintConfig, uint_encode_with_config};

        let tokens: Vec<Token> = (0..5000)
            .map(|i| Token::new((i % 3 == 0) as u32, (i * 37 % 911) as u32))
            .collect();
        let context_map = [0u8, 1u8];
        let configs = [HybridUintConfig::DEFAULT; 2];
        let mut counts = [[0u32; TABLE_ENTRIES]; 2];
        for token in &tokens {
            let histogram = context_map[token.context as usize] as usize;
            let (symbol, _, _) = uint_encode_with_config(token.value, configs[histogram]);
            counts[histogram][symbol as usize] += 1;
        }
        let histograms: Vec<AnsHistogram> = counts
            .iter()
            .map(|counts| optimize_ans_histogram(counts))
            .collect();
        let mut reverse_maps = vec![0u16; histograms.len() * ANS_TAB_SIZE as usize];
        let symbols: Vec<Vec<AnsEncSymbolInfo>> = histograms
            .iter()
            .enumerate()
            .map(|(index, histogram)| {
                let start = index * ANS_TAB_SIZE as usize;
                build_symbol_info(
                    &histogram.freqs,
                    &mut reverse_maps[start..start + ANS_TAB_SIZE as usize],
                )
            })
            .collect();

        let mut writer = BitWriter::new();
        write_ans_tokens(
            &tokens,
            &context_map,
            &symbols,
            &reverse_maps,
            &configs,
            &mut writer,
        );
        assert_eq!(
            ans_tokens_bits(&tokens, &context_map, &symbols, &reverse_maps, &configs),
            writer.bits_written()
        );
        let code = AnsTokenCodeRef {
            context_map: &context_map,
            symbol_info: &symbols,
            reverse_maps: &reverse_maps,
            hybrid_uint_configs: &configs,
        };
        assert_eq!(
            ans_tokens_bits_pair(&tokens, &code, &code),
            (writer.bits_written(), writer.bits_written())
        );

        let merged_counts: [u32; TABLE_ENTRIES] =
            core::array::from_fn(|symbol| counts[0][symbol] + counts[1][symbol]);
        let merged_histogram = optimize_ans_histogram(&merged_counts);
        let mut merged_reverse_map = vec![0u16; ANS_TAB_SIZE as usize];
        let merged_symbols = vec![build_symbol_info(
            &merged_histogram.freqs,
            &mut merged_reverse_map,
        )];
        let merged_context_map = [0u8, 0u8];
        let merged_configs = [HybridUintConfig::DEFAULT];
        let merged_code = AnsTokenCodeRef {
            context_map: &merged_context_map,
            symbol_info: &merged_symbols,
            reverse_maps: &merged_reverse_map,
            hybrid_uint_configs: &merged_configs,
        };
        let mut merged_writer = BitWriter::new();
        write_ans_tokens(
            &tokens,
            &merged_context_map,
            &merged_symbols,
            &merged_reverse_map,
            &merged_configs,
            &mut merged_writer,
        );
        assert_eq!(
            ans_tokens_bits_pair(&tokens, &code, &merged_code),
            (writer.bits_written(), merged_writer.bits_written())
        );
    }
}