still265 0.6.1

Pure-Rust HEVC/H.265 still-image encoder with BPG and HEIC support
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
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
//! Experimental single-scan rate-distortion-optimized quantization (RDOQ).
//!
//! This is an *alternative* to the exact greedy per-coefficient refinement in
//! `encoder::refine_levels_rdoq_limited`. Instead of mutating one coefficient
//! at a time and re-pricing the whole transform block, it makes each
//! coefficient's level decision once, in a single reverse (high-frequency ->
//! DC) scan, pricing the candidate levels with CABAC entropy-bit estimates
//! taken from the block's entry context state (the standard HM/x265 RDOQ
//! approximation: contexts are frozen for pricing rather than re-coded).
//!
//! It reuses the *same* RD framework as the greedy path — coefficient-domain
//! SSE distortion, the same `lambda`, the same 1/32768-bit rate units — so its
//! decisions are directly comparable. Selected per [`Effort`] tier
//! (`Placebo` keeps exact greedy; the practical tiers use this) and
//! overridable via `BPG_RDOQ_SINGLESCAN`. It is *not* byte-identical to the
//! greedy path.
//!
//! Stages implemented:
//! - **(a)** per-coefficient level decision (reverse scan, local RD).
//! - **(b)** last-significant-coefficient-position optimization: after the
//!   level decision, choose the scan position to terminate coding at (zeroing
//!   the higher-frequency tail, or the whole block) by minimizing total RD —
//!   this is what recovers the low-bitrate efficiency stage (a) left behind.
//! - **(c)** per-sub-block `coded_sub_block_flag` all-zero forcing: for each
//!   middle sub-block (explicit-CSBF, i.e. strictly between the DC and the
//!   last-significant sub-block), zero the whole sub-block when CSBF=0 + the
//!   dropped-coefficient distortion beats coding it. Net RD win on the test
//!   corpus (occasional sub-1% local loss from the frozen-context estimate).

use crate::cabac::CabacEstimator;
use crate::contexts::{Contexts, ctx};
use crate::residual::{
    ResidualPricingScratch, ScanOrder, estimate_residual_bits_into, get_scan_4x4,
    get_scan_sub_block,
};
use crate::transform::DequantParams;

/// x265 `g_quantScales` (forward quant scale per `qp % 6`).
const QUANT_SCALE: [i64; 6] = [26214, 23302, 20560, 18396, 16384, 14564];
const MAX_TR_DYNAMIC_RANGE: i32 = 15;
const QUANT_SHIFT: i32 = 14;
/// x265 `SCALE_BITS`: the bit-shift used to scale coefficient-domain
/// distortion into pixel-domain SSE (see `transform.rs` for derivation).
/// Without this scaling, the CABAC-bit term dominates the RD cost and
/// RDOQ aggressively zeroes coefficients (32×–2048× too few bits for
/// 8-bit 4×4–32×32 transforms).
const SCALE_BITS: i32 = 15;

/// One bypass bin in 1/32768-bit units.
const BYPASS_BITS: u64 = CabacEstimator::SCALE;

/// Diagnostic multiplier on the RDOQ rate/distortion lambda
/// (`BPG_RDOQ_LAMBDA_SCALE`, default 1.0). >1 penalizes bits more, <1 keeps
/// more. This is intentionally separate from StillSearch's pixel-domain lambda
/// gate so RDOQ unit changes can be swept without perturbing mode decisions.
fn rdoq_lambda_scale() -> f64 {
    use std::sync::OnceLock;
    static V: OnceLock<f64> = OnceLock::new();
    *V.get_or_init(|| {
        std::env::var("BPG_RDOQ_LAMBDA_SCALE")
            .ok()
            .and_then(|s| s.trim().parse::<f64>().ok())
            .filter(|v| v.is_finite() && *v > 0.0)
            .unwrap_or(1.0)
    })
}

/// A/B gate for x265's coding-group carry shape. In x265 `rdoQuant`, the
/// greater1 carry (`c1`) is reset to 1 at the start of every coefficient group;
/// an empty group therefore clears any previous `c1 == 0` carry before the next
/// lower-frequency group. The historical still265 single-scan path left the
/// carry unchanged across empty groups.
fn x265_empty_cg_carry_enabled() -> bool {
    use std::sync::OnceLock;
    static V: OnceLock<bool> = OnceLock::new();
    *V.get_or_init(|| {
        std::env::var("BPG_RDOQ_X265_EMPTY_CG_CARRY")
            .ok()
            .map(|s| matches!(s.trim().to_ascii_lowercase().as_str(), "1" | "true" | "on"))
            .unwrap_or(false)
    })
}

/// A/B gate for x265's last-significant refinement envelope. x265 evaluates
/// candidate last positions walking high-frequency -> low-frequency, but stops
/// after the first coded coefficient whose selected absolute level is > 1
/// (`rdoqLevel > 1`). The historical still265 path considered every non-zero
/// coefficient as a possible last.
fn x265_last_stop_enabled() -> bool {
    use std::sync::OnceLock;
    static V: OnceLock<bool> = OnceLock::new();
    *V.get_or_init(|| {
        std::env::var("BPG_RDOQ_X265_LAST_STOP")
            .ok()
            .map(|s| matches!(s.trim().to_ascii_lowercase().as_str(), "1" | "true" | "on"))
            .unwrap_or(false)
    })
}

/// Number of `coeff_abs_level_remaining` bins for `value` at Rice parameter
/// `rice` (truncated-Rice prefix + EGk), matching `encode_coeff_abs_level_remaining`.
pub(crate) fn rice_bins(value: u32, rice: u32) -> u32 {
    if value < (4u32 << rice) {
        (value >> rice) + 1 + rice
    } else {
        let mut p = 4u32;
        loop {
            let base = ((1u32 << (p - 3)) + 2) << rice;
            let width = 1u32 << (p - 3 + rice);
            if value < base + width {
                return p + 1 + (p - 3 + rice);
            }
            p += 1;
        }
    }
}

/// Magnitude (`coeff_abs_level_greater1/2` + `coeff_abs_level_remaining`) bits
/// for an absolute `level >= 1`, given the *tracked* coding-group state. Faithful
/// port of x265 `getICRateCost` (common/quant.cpp): `gt1`/`gt2` are the
/// greater1/greater2 flag entropy bits (`[0]`/`[1]`) for the current
/// `4*ctxSet+c1` / `ctxSet+c2` contexts, `c1c2idx` selects the `{1,2,1,3}`
/// `base_level`, and `go_rice` is the adapted Rice parameter. Excludes the sign
/// bypass bit (the caller adds it).
#[inline]
fn ic_level_bits(
    level: u32,
    base_level: u32,
    gt1: [u64; 2],
    gt2: [u64; 2],
    c1c2idx: u32,
    go_rice: u32,
) -> u64 {
    let diff = level as i64 - base_level as i64;
    if diff < 0 {
        // level is 1 or 2 (below base_level): just the greater1 flag, plus the
        // greater2 flag when level == 2.
        gt1[(level == 2) as usize] + if level == 2 { gt2[0] } else { 0 }
    } else {
        // level >= base_level: greater1/greater2 "=1" flags (when still within
        // their per-group budgets) plus the remaining truncated-Rice/EGk code.
        let c1c2_rate =
            (if c1c2idx & 1 != 0 { gt1[1] } else { 0 }) + (if c1c2idx == 3 { gt2[1] } else { 0 });
        rice_bins(diff as u32, go_rice) as u64 * BYPASS_BITS + c1c2_rate
    }
}

/// Estimated bits for one axis of `last_sig_coeff_{x,y}` (context-coded
/// truncated-unary prefix + bypass suffix), mirroring `encode_last_prefix` /
/// `encode_bypass_bits` but counting entropy bits instead of coding.
#[cfg(test)]
fn last_axis_bits(ctxs: &Contexts, value: u32, log2_size: u8, c_idx: u8, is_x: bool) -> u64 {
    let ctx_base = if is_x {
        ctx::LAST_SIG_COEFF_X_PREFIX
    } else {
        ctx::LAST_SIG_COEFF_Y_PREFIX
    };
    let (ctx_offset, ctx_shift) = if c_idx == 0 {
        let offset = 3 * (log2_size as usize - 2) + ((log2_size as usize - 1) >> 2);
        let shift = (log2_size + 1) >> 2;
        (offset, shift)
    } else {
        (15usize, log2_size - 2)
    };
    let max_prefix = ((log2_size << 1) - 1) as u32;
    let (prefix, n_bits) = if value <= 3 {
        (value, 0u8)
    } else {
        let group = 31 - value.leading_zeros();
        (2 * group + ((value >> (group - 1)) & 1), (group - 1) as u8)
    };

    let mut bits = 0u64;
    for j in 0..prefix {
        let ci = ctx_base + ctx_offset + (j as usize >> ctx_shift as usize);
        bits += ctxs.models[ci].entropy_bits(1) as u64;
    }
    if prefix < max_prefix {
        let ci = ctx_base + ctx_offset + (prefix as usize >> ctx_shift as usize);
        bits += ctxs.models[ci].entropy_bits(0) as u64;
    }
    if value > 3 {
        bits += n_bits as u64 * BYPASS_BITS;
    }
    bits
}

/// Fill last-position costs for one axis in O(size): every value shares the
/// same context-coded truncated-unary prefix, so carry its cumulative `1`-bin
/// cost instead of walking the prefix again for each table entry.
#[inline]
fn fill_last_axis_bits(
    out: &mut [u64; 32],
    ctxs: &Contexts,
    size: usize,
    log2_size: u8,
    c_idx: u8,
    is_x: bool,
) {
    let ctx_base = if is_x {
        ctx::LAST_SIG_COEFF_X_PREFIX
    } else {
        ctx::LAST_SIG_COEFF_Y_PREFIX
    };
    let (ctx_offset, ctx_shift) = if c_idx == 0 {
        (
            3 * (log2_size as usize - 2) + ((log2_size as usize - 1) >> 2),
            (log2_size + 1) >> 2,
        )
    } else {
        (15usize, log2_size - 2)
    };
    let max_prefix = ((log2_size << 1) - 1) as usize;
    let mut one_prefix = [0u64; 11];
    for prefix in 0..max_prefix {
        let ci = ctx_base + ctx_offset + (prefix >> ctx_shift as usize);
        one_prefix[prefix + 1] = one_prefix[prefix] + ctxs.models[ci].entropy_bits(1) as u64;
    }

    for (value, slot) in out.iter_mut().take(size).enumerate() {
        let value = value as u32;
        let (prefix, n_bits) = if value <= 3 {
            (value as usize, 0u8)
        } else {
            let group = 31 - value.leading_zeros();
            (
                (2 * group + ((value >> (group - 1)) & 1)) as usize,
                (group - 1) as u8,
            )
        };
        let mut bits = one_prefix[prefix];
        if prefix < max_prefix {
            let ci = ctx_base + ctx_offset + (prefix >> ctx_shift as usize);
            bits += ctxs.models[ci].entropy_bits(0) as u64;
        }
        if value > 3 {
            bits += n_bits as u64 * BYPASS_BITS;
        }
        *slot = bits;
    }
}

/// Per-coefficient state captured during the level-decision scan, indexed by
/// forward (DC -> high-frequency) combined scan rank.
///
/// RD costs are in the x265 `rdoQuant` int64 fixed-point domain:
/// `(d*d << scale_bits) + ((lambda_q8 * frac_bits) >> 8)` with `frac_bits` in
/// 1/32768-bit units. All sums stay well below 2^63, so the arithmetic is
/// exact (the earlier f64 domain rounded above 2^53) and the per-coefficient
/// loop runs integer-only.
#[derive(Clone, Copy, Default)]
struct CoeffRec {
    idx: usize, // row-major coefficient index
    x: u32,
    y: u32,
    level: i16,     // chosen signed level (0 if quantized away)
    dist0: i64,     // distortion if zeroed (scaled by << scale_bits)
    rd_normal: i64, // RD cost coded as a normal coefficient (sig flag + level)
    rd_last: i64,   // RD cost coded as the last significant coeff (no sig flag)
}

/// `rd_last` sentinel for "this coefficient cannot be the last" (level == 0).
/// Stage (b) never reads `rd_last` for zero levels, so the sentinel is never
/// added into a cost sum.
const RD_NEVER: i64 = i64::MAX;

#[derive(Default)]
pub struct RdoqScratch {
    recs: Vec<CoeffRec>,
    suff_zero: Vec<i64>,
    pref_normal: Vec<i64>,
    levels: Vec<i16>,
    price_scratch: ResidualPricingScratch,
    dequant: Vec<i16>,
    recon: Vec<i16>,
    trial_levels: Vec<i16>,
}

pub struct RdoqResult<'a> {
    pub levels: &'a mut [i16],
    pub nnz: u32,
}

/// Optional psy-rdoq inputs (x265 `rdoQuant` + `psyRdoQuant_c`): bias RDOQ
/// toward preserving the SOURCE block's AC energy in the reconstruction.
///
/// `src_dct` is the source block's forward transform taken with the SAME
/// basis as the residual (including DST for 4x4 intra luma — a deliberate
/// divergence from x265, which transforms fenc with DCT even then; same-basis
/// is the correct form of their intent), row-major, same layout as `coeffs`.
/// `psy_scale` is `round(psy_rdoq * 256) * lambda_q8`, with `lambda_q8` the
/// Q8 sqrt-domain (SAD) lambda `floor(x265_sad_lambda(qp, bit_depth) * 256)`.
///
/// For each AC position the reconstructed-without-residual ("predicted")
/// coefficient is `src_dct[pos] - coeffs[pos]`, and candidate costs are
/// credited `PSYVALUE(rec) = (psy_scale * rec) >> max(0, 2*transform_shift+1)`
/// for the AC energy `rec` they reconstruct (quant.cpp:885,972,1004-1007).
#[derive(Clone, Copy)]
pub struct RdoqPsy<'a> {
    pub src_dct: &'a [i16],
    pub psy_scale: i64,
}

/// Experimental post-RDOQ residual-pricing models selected by
/// `BPG_RDOQ_PRICING`. `Frozen` is the existing single-scan behavior.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum RdoqPricingMode {
    #[default]
    Frozen,
    Running,
    Hybrid,
    ExactCleanup,
    BoundedTrellis,
}

/// `BPG_RDOQ_REFINE` gate (default off). Post-RDOQ coordinate-descent that
/// minimizes pixel-domain SSE + lambda * exact-CABAC residual bits (priced from
/// the frozen `price_base` contexts).
///
/// DIAGNOSTIC / RD-NEGATIVE — DO NOT ENABLE BY DEFAULT. The `rdoq_optimality_tests`
/// self-test shows RDOQ sits ~1.5% above this objective's coordinate-descent
/// optimum, but wiring the refinement into a real encode is **RD-negative**
/// (4MP q28/30/32: bigger files, equal/worse decoded PSNR, ≈−0.03 dB at equal
/// bytes). recon==decode still holds, and SDH is off in the Slow path, so the
/// loss is not a round-trip or sign-hiding bug: the frozen-context
/// `estimate_residual_bits` diverges from the real evolving-context coded cost,
/// so aggressively optimizing it over-fits. Conclusion: RDOQ coefficient
/// *selection* is effectively well-calibrated for real coding; the 1.5% is an
/// artifact of the offline objective, not recoverable real RD. Kept as a probe.
pub fn rdoq_refine_enabled() -> bool {
    use std::sync::OnceLock;
    static V: OnceLock<bool> = OnceLock::new();
    *V.get_or_init(|| {
        std::env::var("BPG_RDOQ_REFINE")
            .ok()
            .map(|s| matches!(s.trim(), "1" | "true" | "on"))
            .unwrap_or(false)
    })
}

/// Coordinate-descent refinement of RDOQ `levels` toward the true-RD optimum.
/// Candidates per position: `{0, |L|-1, |L|, |L|+1}` with the level's (or
/// coefficient's) sign — the same RD-relevant neighborhood the trellis chooses
/// among. Returns the refined nnz. `residual` is the pixel-domain residual the
/// transform was taken of, used for exact SSE distortion via `reconstruct_residual`.
#[allow(clippy::too_many_arguments)]
pub fn refine_rdoq_levels(
    base_ctxs: &Contexts,
    coeffs: &[i16],
    residual: &[i16],
    levels: &mut [i16],
    log2_size: u8,
    c_idx: u8,
    qp: i32,
    bit_depth: u8,
    is_dst4: bool,
    scan: ScanOrder,
    lambda: f64,
) -> u32 {
    use crate::residual::{ResidualPricingScratch, estimate_residual_bits_into};
    use crate::transform::reconstruct_residual;
    let mut scratch = ResidualPricingScratch::default();
    let cost = |levels: &[i16], scratch: &mut ResidualPricingScratch| -> f64 {
        let recon = reconstruct_residual(levels, log2_size, qp, bit_depth, is_dst4);
        let dist: f64 = residual
            .iter()
            .zip(&recon)
            .map(|(&r, &c)| {
                let d = r as i64 - c as i64;
                (d * d) as f64
            })
            .sum();
        let bits =
            estimate_residual_bits_into(base_ctxs, levels, log2_size, c_idx, scan, false, scratch);
        dist + lambda * bits as f64 / CabacEstimator::SCALE as f64
    };
    let mut best = cost(levels, &mut scratch);
    loop {
        let mut improved = false;
        for i in 0..levels.len() {
            let sign: i32 = if levels[i] != 0 {
                levels[i].signum() as i32
            } else if coeffs[i] != 0 {
                coeffs[i].signum() as i32
            } else {
                continue; // zero coeff stays zero
            };
            let m = levels[i].unsigned_abs() as i32;
            let cands = [
                0i16,
                (sign * (m - 1).max(0)) as i16,
                (sign * (m + 1)) as i16,
            ];
            for &cand in &cands {
                if cand == levels[i] {
                    continue;
                }
                let save = levels[i];
                levels[i] = cand;
                let c = cost(levels, &mut scratch);
                if c + 1e-6 < best {
                    best = c;
                    improved = true;
                } else {
                    levels[i] = save;
                }
            }
        }
        if !improved {
            break;
        }
    }
    levels.iter().filter(|&&l| l != 0).count() as u32
}

#[allow(clippy::too_many_arguments)]
fn exact_rd_cost(
    base_ctxs: &Contexts,
    residual: &[i16],
    levels: &[i16],
    log2_size: u8,
    c_idx: u8,
    qp: i32,
    bit_depth: u8,
    is_dst4: bool,
    scan: ScanOrder,
    lambda: f64,
    scratch: &mut RdoqScratch,
) -> f64 {
    crate::transform::reconstruct_residual_into(
        levels,
        log2_size,
        qp,
        bit_depth,
        is_dst4,
        &mut scratch.dequant,
        &mut scratch.recon,
    );
    let dist: f64 = residual
        .iter()
        .zip(&scratch.recon)
        .map(|(&r, &c)| {
            let d = r as i64 - c as i64;
            (d * d) as f64
        })
        .sum();
    let bits = estimate_residual_bits_into(
        base_ctxs,
        levels,
        log2_size,
        c_idx,
        scan,
        false,
        &mut scratch.price_scratch,
    );
    dist + lambda * bits as f64 / CabacEstimator::SCALE as f64
}

fn level_sign(coeff: i16, level: i16) -> Option<i32> {
    if level != 0 {
        Some(level.signum() as i32)
    } else if coeff != 0 {
        Some(coeff.signum() as i32)
    } else {
        None
    }
}

fn signed_level(sign: i32, mag: i32) -> i16 {
    let mag = mag.clamp(0, i16::MAX as i32);
    (sign * mag) as i16
}

fn nnz(levels: &[i16]) -> u32 {
    levels.iter().filter(|&&l| l != 0).count() as u32
}

fn scan_indices(log2_size: u8, scan: ScanOrder) -> Vec<usize> {
    let size = 1usize << log2_size;
    let mut out = Vec::with_capacity(size * size);
    for &(sbx, sby) in get_scan_sub_block(log2_size, scan).iter() {
        for &(px, py) in get_scan_4x4(scan).iter() {
            let x = sbx as usize * 4 + px as usize;
            let y = sby as usize * 4 + py as usize;
            if x < size && y < size {
                out.push(y * size + x);
            }
        }
    }
    out
}

#[allow(clippy::too_many_arguments)]
fn keep_if_better(
    base_ctxs: &Contexts,
    residual: &[i16],
    levels: &mut [i16],
    log2_size: u8,
    c_idx: u8,
    qp: i32,
    bit_depth: u8,
    is_dst4: bool,
    scan: ScanOrder,
    lambda: f64,
    scratch: &mut RdoqScratch,
    best: &mut f64,
) -> bool {
    let cost = exact_rd_cost(
        base_ctxs, residual, levels, log2_size, c_idx, qp, bit_depth, is_dst4, scan, lambda,
        scratch,
    );
    if cost + 1e-6 < *best {
        *best = cost;
        true
    } else {
        false
    }
}

#[allow(clippy::too_many_arguments)]
fn try_set_level(
    base_ctxs: &Contexts,
    residual: &[i16],
    levels: &mut [i16],
    idx: usize,
    cand: i16,
    log2_size: u8,
    c_idx: u8,
    qp: i32,
    bit_depth: u8,
    is_dst4: bool,
    scan: ScanOrder,
    lambda: f64,
    scratch: &mut RdoqScratch,
    best: &mut f64,
) -> bool {
    if levels[idx] == cand {
        return false;
    }
    let save = levels[idx];
    levels[idx] = cand;
    if keep_if_better(
        base_ctxs, residual, levels, log2_size, c_idx, qp, bit_depth, is_dst4, scan, lambda,
        scratch, best,
    ) {
        true
    } else {
        levels[idx] = save;
        false
    }
}

#[allow(clippy::too_many_arguments)]
fn exact_drop_sweep(
    base_ctxs: &Contexts,
    coeffs: &[i16],
    residual: &[i16],
    levels: &mut [i16],
    order: &[usize],
    log2_size: u8,
    c_idx: u8,
    qp: i32,
    bit_depth: u8,
    is_dst4: bool,
    scan: ScanOrder,
    lambda: f64,
    scratch: &mut RdoqScratch,
    best: &mut f64,
) -> bool {
    let mut improved = false;
    for &idx in order.iter().rev() {
        let cur = levels[idx];
        if cur == 0 {
            continue;
        }
        let sign = level_sign(coeffs[idx], cur).unwrap_or(1);
        let mag = cur.unsigned_abs() as i32;
        let down = signed_level(sign, mag - 1);
        if try_set_level(
            base_ctxs, residual, levels, idx, down, log2_size, c_idx, qp, bit_depth, is_dst4, scan,
            lambda, scratch, best,
        ) {
            improved = true;
        }
        if levels[idx] != 0
            && try_set_level(
                base_ctxs, residual, levels, idx, 0, log2_size, c_idx, qp, bit_depth, is_dst4,
                scan, lambda, scratch, best,
            )
        {
            improved = true;
        }
    }
    improved
}

#[allow(clippy::too_many_arguments)]
fn exact_tail_cleanup(
    base_ctxs: &Contexts,
    residual: &[i16],
    levels: &mut [i16],
    order: &[usize],
    log2_size: u8,
    c_idx: u8,
    qp: i32,
    bit_depth: u8,
    is_dst4: bool,
    scan: ScanOrder,
    lambda: f64,
    scratch: &mut RdoqScratch,
    best: &mut f64,
) -> bool {
    let mut improved = false;
    scratch.trial_levels.clear();
    scratch.trial_levels.extend_from_slice(levels);
    if scratch.trial_levels.iter().any(|&l| l != 0) {
        for v in &mut scratch.trial_levels {
            *v = 0;
        }
        let trial = scratch.trial_levels.clone();
        let cost = exact_rd_cost(
            base_ctxs, residual, &trial, log2_size, c_idx, qp, bit_depth, is_dst4, scan, lambda,
            scratch,
        );
        if cost + 1e-6 < *best {
            *best = cost;
            levels.copy_from_slice(&trial);
            improved = true;
        }
    }

    scratch.trial_levels.clear();
    scratch.trial_levels.extend_from_slice(levels);
    for last_rank in (0..order.len()).rev() {
        let last_idx = order[last_rank];
        if levels[last_idx] == 0 {
            continue;
        }
        scratch.trial_levels.copy_from_slice(levels);
        for &idx in order.iter().skip(last_rank + 1) {
            scratch.trial_levels[idx] = 0;
        }
        let trial = scratch.trial_levels.clone();
        let cost = exact_rd_cost(
            base_ctxs, residual, &trial, log2_size, c_idx, qp, bit_depth, is_dst4, scan, lambda,
            scratch,
        );
        if cost + 1e-6 < *best {
            *best = cost;
            levels.copy_from_slice(&trial);
            improved = true;
        }
    }
    improved
}

#[allow(clippy::too_many_arguments)]
fn exact_subblock_cleanup(
    base_ctxs: &Contexts,
    residual: &[i16],
    levels: &mut [i16],
    log2_size: u8,
    c_idx: u8,
    qp: i32,
    bit_depth: u8,
    is_dst4: bool,
    scan: ScanOrder,
    lambda: f64,
    scratch: &mut RdoqScratch,
    best: &mut f64,
) -> bool {
    let size = 1usize << log2_size;
    let sb_width = size / 4;
    let mut improved = false;
    for &(sbx, sby) in get_scan_sub_block(log2_size, scan).iter().rev() {
        let (sbx, sby) = (sbx as usize, sby as usize);
        if sbx >= sb_width || sby >= sb_width {
            continue;
        }
        let mut has_nz = false;
        scratch.trial_levels.clear();
        scratch.trial_levels.extend_from_slice(levels);
        for y in sby * 4..((sby + 1) * 4).min(size) {
            for x in sbx * 4..((sbx + 1) * 4).min(size) {
                let idx = y * size + x;
                has_nz |= scratch.trial_levels[idx] != 0;
                scratch.trial_levels[idx] = 0;
            }
        }
        if !has_nz {
            continue;
        }
        let trial = scratch.trial_levels.clone();
        let cost = exact_rd_cost(
            base_ctxs, residual, &trial, log2_size, c_idx, qp, bit_depth, is_dst4, scan, lambda,
            scratch,
        );
        if cost + 1e-6 < *best {
            *best = cost;
            levels.copy_from_slice(&trial);
            improved = true;
        }
    }
    improved
}

#[allow(clippy::too_many_arguments)]
fn exact_coordinate_descent(
    base_ctxs: &Contexts,
    coeffs: &[i16],
    residual: &[i16],
    levels: &mut [i16],
    order: &[usize],
    log2_size: u8,
    c_idx: u8,
    qp: i32,
    bit_depth: u8,
    is_dst4: bool,
    scan: ScanOrder,
    lambda: f64,
    scratch: &mut RdoqScratch,
    best: &mut f64,
) {
    loop {
        let mut improved = false;
        for &idx in order.iter().rev() {
            let Some(sign) = level_sign(coeffs[idx], levels[idx]) else {
                continue;
            };
            let mag = levels[idx].unsigned_abs() as i32;
            let cands = [0, signed_level(sign, mag - 1), signed_level(sign, mag + 1)];
            for cand in cands {
                if try_set_level(
                    base_ctxs, residual, levels, idx, cand, log2_size, c_idx, qp, bit_depth,
                    is_dst4, scan, lambda, scratch, best,
                ) {
                    improved = true;
                }
            }
        }
        if !improved {
            break;
        }
    }
}

#[allow(clippy::too_many_arguments)]
fn bounded_trellis(
    base_ctxs: &Contexts,
    coeffs: &[i16],
    residual: &[i16],
    levels: &mut [i16],
    order: &[usize],
    log2_size: u8,
    c_idx: u8,
    qp: i32,
    bit_depth: u8,
    is_dst4: bool,
    scan: ScanOrder,
    lambda: f64,
    beam_width: usize,
    scratch: &mut RdoqScratch,
    best: &mut f64,
) {
    const MAX_TRELLIS_POSITIONS: usize = 32;
    let beam_width = beam_width.clamp(1, 16);
    let mut positions: Vec<usize> = order
        .iter()
        .rev()
        .copied()
        .filter(|&idx| levels[idx] != 0 || coeffs[idx] != 0)
        .take(MAX_TRELLIS_POSITIONS)
        .collect();
    if positions.is_empty() {
        return;
    }
    positions.reverse();

    let mut beam = vec![(levels.to_vec(), *best)];
    for idx in positions {
        let mut next: Vec<(Vec<i16>, f64)> = Vec::new();
        for (state, _) in beam.iter() {
            let Some(sign) = level_sign(coeffs[idx], state[idx]) else {
                continue;
            };
            let mag = state[idx].unsigned_abs() as i32;
            let cands = [
                state[idx],
                0,
                signed_level(sign, mag - 1),
                signed_level(sign, mag + 1),
            ];
            for cand in cands {
                let mut candidate = state.clone();
                candidate[idx] = cand;
                if next.iter().any(|(seen, _)| seen == &candidate) {
                    continue;
                }
                let cost = exact_rd_cost(
                    base_ctxs, residual, &candidate, log2_size, c_idx, qp, bit_depth, is_dst4,
                    scan, lambda, scratch,
                );
                next.push((candidate, cost));
            }
        }
        next.sort_by(|a, b| a.1.total_cmp(&b.1));
        next.truncate(beam_width);
        if next.is_empty() {
            break;
        }
        beam = next;
    }
    if let Some((state, cost)) = beam.first() {
        if *cost + 1e-6 < *best {
            *best = *cost;
            levels.copy_from_slice(state);
        }
    }
}

/// Applies opt-in residual-pricing experiments after the normal frozen
/// single-scan RDOQ decision. Returns the resulting non-zero coefficient count.
#[allow(clippy::too_many_arguments)]
pub fn apply_rdoq_pricing_mode(
    base_ctxs: &Contexts,
    coeffs: &[i16],
    residual: &[i16],
    levels: &mut [i16],
    log2_size: u8,
    c_idx: u8,
    qp: i32,
    bit_depth: u8,
    is_dst4: bool,
    scan: ScanOrder,
    lambda: f64,
    mode: RdoqPricingMode,
    trellis_beam: usize,
    scratch: &mut RdoqScratch,
) -> u32 {
    if mode == RdoqPricingMode::Frozen {
        return nnz(levels);
    }

    let order = scan_indices(log2_size, scan);
    let mut best = exact_rd_cost(
        base_ctxs, residual, levels, log2_size, c_idx, qp, bit_depth, is_dst4, scan, lambda,
        scratch,
    );

    match mode {
        RdoqPricingMode::Frozen => {}
        RdoqPricingMode::Running => exact_coordinate_descent(
            base_ctxs, coeffs, residual, levels, &order, log2_size, c_idx, qp, bit_depth, is_dst4,
            scan, lambda, scratch, &mut best,
        ),
        RdoqPricingMode::Hybrid => {
            exact_tail_cleanup(
                base_ctxs, residual, levels, &order, log2_size, c_idx, qp, bit_depth, is_dst4,
                scan, lambda, scratch, &mut best,
            );
            exact_drop_sweep(
                base_ctxs, coeffs, residual, levels, &order, log2_size, c_idx, qp, bit_depth,
                is_dst4, scan, lambda, scratch, &mut best,
            );
        }
        RdoqPricingMode::ExactCleanup => loop {
            let changed_tail = exact_tail_cleanup(
                base_ctxs, residual, levels, &order, log2_size, c_idx, qp, bit_depth, is_dst4,
                scan, lambda, scratch, &mut best,
            );
            let changed_sb = exact_subblock_cleanup(
                base_ctxs, residual, levels, log2_size, c_idx, qp, bit_depth, is_dst4, scan,
                lambda, scratch, &mut best,
            );
            let changed_drop = exact_drop_sweep(
                base_ctxs, coeffs, residual, levels, &order, log2_size, c_idx, qp, bit_depth,
                is_dst4, scan, lambda, scratch, &mut best,
            );
            if !(changed_tail || changed_sb || changed_drop) {
                break;
            }
        },
        RdoqPricingMode::BoundedTrellis => bounded_trellis(
            base_ctxs,
            coeffs,
            residual,
            levels,
            &order,
            log2_size,
            c_idx,
            qp,
            bit_depth,
            is_dst4,
            scan,
            lambda,
            trellis_beam,
            scratch,
            &mut best,
        ),
    }
    nnz(levels)
}

/// Scratch-backed single-scan RDOQ. The returned levels borrow from `scratch`;
/// callers should copy them only when a materialized coded block is needed.
#[allow(clippy::too_many_arguments)]
pub fn rdoq_single_scan_into<'scratch>(
    ctxs: &Contexts,
    coeffs: &[i16],
    log2_size: u8,
    c_idx: u8,
    qp: i32,
    bit_depth: u8,
    scan_order: ScanOrder,
    lambda: f64,
    level2: bool,
    psy: Option<RdoqPsy<'_>>,
    scratch: &'scratch mut RdoqScratch,
) -> RdoqResult<'scratch> {
    let size = 1usize << log2_size;
    let scan_sub = get_scan_sub_block(log2_size, scan_order);
    let scan_pos = get_scan_4x4(scan_order);
    let scan_idx = scan_order as u8;
    let sb_width = size / 4;

    // Forward-quant scaling (matches `transform::quantize`).
    let per = qp / 6;
    let rem = (qp % 6) as usize;
    let transform_shift = MAX_TR_DYNAMIC_RANGE - bit_depth as i32 - log2_size as i32;
    let qbits = QUANT_SHIFT + per + transform_shift;
    let scale = QUANT_SCALE[rem];
    let round = 1i64 << (qbits - 1); // round-to-nearest center for the candidate level

    let dq = DequantParams::new(log2_size, qp, bit_depth);
    // x265 `rdoQuant` int64 fixed-point cost domain:
    //   RDCOST(d, bits) = ((d*d) << scaleBits) + ((lambda2_q8 * bits) >> 8)
    // with `bits` in 1/32768-bit units and `lambda2_q8` the SSE-domain lambda
    // in Q8. `scaleBits` lifts coefficient-domain squared error to pixel-domain
    // SSE (see `transform.rs`); it is always positive here
    // (`SCALE_BITS - 2*transform_shift`, transform_shift <= 5). Costs stay
    // below ~2^56 for a 32x32 block, so i64 sums are exact — the earlier f64
    // domain rounded above 2^53 — and the hot loop runs integer-only.
    let scale_bits = (SCALE_BITS - 2 * transform_shift) as u32;
    debug_assert!((SCALE_BITS - 2 * transform_shift) > 0);
    let lam = (rdoq_lambda_scale() * lambda * 256.0).round() as i64;
    let rate = |bits: u64| -> i64 { (lam * bits as i64) >> 8 };
    // psy-rdoq (x265 quant.cpp `rdoQuant` psy path): AC-only energy credit.
    // `PSYVALUE(rec) = (psy_scale * rec) >> max(0, 2*transform_shift + 1)`.
    // The credit is SUBTRACTED from candidate costs, so costs (and the
    // uncoded/zeroing distortion sums that fold it in) may go negative; the
    // whole cost domain here is i64, which stays exact.
    let psy_shift = (2 * transform_shift + 1).max(0) as u32;
    let psy_value = |rec: i64| -> i64 {
        match psy {
            Some(p) => (p.psy_scale * rec) >> psy_shift,
            None => 0,
        }
    };
    // Predicted (reconstructed-without-residual) coefficient at raster `idx`;
    // `None` when psy is off or at the DC position (psy is AC-only).
    let psy_predicted = |idx: usize| -> Option<i64> {
        match psy {
            Some(p) if idx != 0 => Some(p.src_dct[idx] as i64 - coeffs[idx] as i64),
            _ => None,
        }
    };
    let bits = |ci: usize, bin: u8| -> u64 { ctxs.models[ci].entropy_bits(bin) as u64 };

    // Frozen representative greater1/greater2 contexts (greater1_ctx = 1, first
    // significant coefficient; prev_subblock_had_gt1 = 0). Used when `level2` is
    // off (the legacy single-scan rate model).
    let ctx_set = if c_idx > 0 { 0usize } else { 2 };
    let gt1_ci =
        ctx::COEFF_ABS_LEVEL_GREATER1_FLAG + if c_idx > 0 { 16 } else { 0 } + ctx_set * 4 + 1;
    let gt2_ci = ctx::COEFF_ABS_LEVEL_GREATER2_FLAG + if c_idx > 0 { 4 } else { 0 } + ctx_set;
    // coeff_abs_level bits (greater1 + greater2 + remaining + sign) for abs level l>=1.
    let magnitude_bits = |l: u32| -> u64 {
        let mag = match l {
            1 => bits(gt1_ci, 0),
            2 => bits(gt1_ci, 1) + bits(gt2_ci, 0),
            _ => bits(gt1_ci, 1) + bits(gt2_ci, 1) + rice_bins(l - 3, 0) as u64 * BYPASS_BITS,
        };
        mag + BYPASS_BITS // sign
    };

    // `level2` (x265 `rdoqQuant`) greater1/greater2 context banks. Per-coefficient
    // indices are `gt1_base + 4*ctxSet + c1` and `gt2_base + ctxSet` (the `+c2`
    // term in x265 is only read when c2 == 0, so it folds into `ctxSet`).
    let gt1_base = ctx::COEFF_ABS_LEVEL_GREATER1_FLAG + if c_idx > 0 { 16 } else { 0 };
    let gt2_base = ctx::COEFF_ABS_LEVEL_GREATER2_FLAG + if c_idx > 0 { 4 } else { 0 };

    // Pre-pass: reverse-scan for the last significant coefficient under
    // round-to-nearest quant.
    // `q >= 1  ⟺  abs*scale + round >= 1<<qbits  ⟺  abs >= ceil(round/scale)`
    // (since `round` is exactly half of `1<<qbits`). Positions after the last
    // significant rank can never be coded (stage (b) only considers significant
    // `last` candidates and never prices ranks beyond it), so all work past it
    // is trimmed to a pure zeroing-distortion suffix, and an all-insignificant
    // block returns immediately. Scanning high->low frequency stops at the
    // first significant coefficient instead of touching the whole block.
    debug_assert_eq!(scan_sub.len() * 16, size * size);
    let sig_threshold = ((round + scale - 1) / scale) as u32;
    let mut last_sig_rank: isize = -1;
    'find_last: for (sb_i, &(sbx, sby)) in scan_sub.iter().enumerate().rev() {
        let row0 = sby as usize * 4 * size + sbx as usize * 4;
        for pos in (0..16).rev() {
            let (px, py) = scan_pos[pos];
            let abs = coeffs[row0 + py as usize * size + px as usize].unsigned_abs() as u32;
            if abs >= sig_threshold {
                last_sig_rank = (sb_i * 16 + pos) as isize;
                break 'find_last;
            }
        }
    }
    if last_sig_rank < 0 {
        scratch.levels.clear();
        scratch.levels.resize(size * size, 0);
        return RdoqResult {
            levels: &mut scratch.levels,
            nnz: 0,
        };
    }
    let last_cg = last_sig_rank as usize / 16;
    let last_cg_top = last_sig_rank as usize % 16;
    let kept_cgs = last_cg + 1;
    let kept = last_sig_rank as usize + 1;

    // Records are indexed by forward combined scan rank (rank = sb*16 + pos;
    // the scan tables cover the block exactly, so ranks are arithmetic).
    // Fields are filled during the stage-(a) scan.
    let recs = &mut scratch.recs;
    recs.clear();
    recs.resize(kept, CoeffRec::default());

    // Zeroing distortion of the trimmed tail (ranks kept..size*size). Full
    // coding groups beyond the last significant one first, then the last
    // group's tail positions. i64 sums are order-independent and exact.
    // With psy on, each tail position's uncoded cost also carries its psy
    // credit (`-PSYVALUE(predicted)` — when nothing is coded the recon coef
    // equals the predicted coef), keeping the CBF=0 total and the stage
    // (b)/(c) comparisons consistent with the per-record uncoded costs. The
    // trimmed tail never contains the DC position (its ranks are strictly
    // above `last_sig_rank >= 0`), so `psy_predicted`'s AC gate is enough.
    let mut tail_zero_dist = 0i64;
    for &(sbx, sby) in scan_sub[kept_cgs..].iter() {
        let row0 = sby as usize * 4 * size + sbx as usize * 4;
        for &(px, py) in scan_pos.iter() {
            let idx = row0 + py as usize * size + px as usize;
            let abs = coeffs[idx].unsigned_abs() as i64;
            tail_zero_dist += (abs * abs) << scale_bits;
            if let Some(predicted) = psy_predicted(idx) {
                tail_zero_dist -= psy_value(predicted);
            }
        }
    }
    {
        let (sbx, sby) = scan_sub[last_cg];
        let row0 = sby as usize * 4 * size + sbx as usize * 4;
        for pos in last_cg_top + 1..16 {
            let (px, py) = scan_pos[pos];
            let idx = row0 + py as usize * size + px as usize;
            let abs = coeffs[idx].unsigned_abs() as i64;
            tail_zero_dist += (abs * abs) << scale_bits;
            if let Some(predicted) = psy_predicted(idx) {
                tail_zero_dist -= psy_value(predicted);
            }
        }
    }

    // --- Stage (a): per-coefficient level decision, reverse sub-block scan. ---
    let mut coded_sb_flags = [0u8; 8];
    // `level2` coding-group state carried across groups (x265 `rdoqQuant`):
    // `prev_cg_c1` is the previous coded group's final greater1 context, used to
    // bump `ctxSet` for the next group.
    let mut prev_cg_c1 = 1u32;
    for (sb_i, &(sbx, sby)) in scan_sub[..kept_cgs].iter().enumerate().rev() {
        let sbx = sbx as usize;
        let sby = sby as usize;
        let right = sbx + 1 < sb_width && (coded_sb_flags[sby] & (1u8 << (sbx + 1))) != 0;
        let below = sby + 1 < sb_width && (coded_sb_flags[sby + 1] & (1u8 << sbx)) != 0;
        let prev_csbf = (right as u8) | ((below as u8) << 1);

        // Per-group greater1/greater2 state (x265 quant.cpp:778-866). `ctx_set`
        // is 2 for non-DC luma groups, 0 otherwise, +1 if the previous group
        // ended with c1 == 0. The greater1/greater2 flag budgets (`c1_idx < 8`,
        // `c2_idx == 0`) and the adapted Rice parameter (`go_rice`) reset here.
        let cg_is_not_dc = !(sbx == 0 && sby == 0);
        let mut ctx_set2 = if cg_is_not_dc && c_idx == 0 { 2u32 } else { 0 };
        if prev_cg_c1 == 0 {
            ctx_set2 += 1;
        }
        let mut c1 = 1u32;
        let mut c2 = 0u32;
        let mut go_rice = 0u32;
        let mut level_threshold = 3u32;
        let mut c1_idx = 0u32;
        let mut c2_idx = 0u32;

        // The greater2 context index only depends on `ctx_set2`, fixed for the
        // whole group — hoist its entropy bits out of the position loop.
        let gt2 = if level2 {
            let gt2_ci = gt2_base + ctx_set2 as usize;
            [bits(gt2_ci, 0), bits(gt2_ci, 1)]
        } else {
            [0, 0]
        };

        let sig_row =
            crate::residual::sig_ctx_row(log2_size, c_idx, scan_idx, !cg_is_not_dc, prev_csbf);
        let mut sb_has_sig = false;
        // Positions above the last significant rank in the last group carry no
        // record (their zeroing distortion lives in `tail_zero_dist`).
        let top = if sb_i == last_cg { last_cg_top } else { 15 };
        for pos in (0..=top).rev() {
            let (px, py) = scan_pos[pos];
            let x = sbx * 4 + px as usize;
            let y = sby * 4 + py as usize;
            let rank = sb_i * 16 + pos;
            let idx = y * size + x;
            let coeff = coeffs[idx];
            let abs = coeff.unsigned_abs() as i64;
            let q = ((abs * scale + round) >> qbits).min(32767) as i32;

            let sig_ci = sig_row[pos] as usize;
            let sig0 = bits(sig_ci, 0);
            // Uncoded cost, including the psy credit for AC positions
            // (quant.cpp:885: recon coef == predicted coef when uncoded).
            // Folding it into `dist0` propagates it to `rd_normal` for zero
            // levels, the stage-(b) zeroing suffixes, and the stage-(c)
            // sub-block zeroing sums.
            let predicted = psy_predicted(idx);
            let mut dist0 = (abs * abs) << scale_bits;
            if let Some(predicted) = predicted {
                dist0 -= psy_value(predicted);
            }

            let rec = &mut recs[rank];
            rec.idx = idx;
            rec.x = x as u32;
            rec.y = y as u32;
            rec.dist0 = dist0;

            // Match x265's RDOQ refinement boundary: start from the
            // round-to-nearest quantized level, never resurrect an initial
            // zero, and only compare the kept level with one step down. An
            // initial zero needs no level-rate parameters and no state advance,
            // so it exits before the greater1/greater2 lookups.
            if q == 0 {
                rec.level = 0;
                rec.rd_normal = dist0 + rate(sig0);
                rec.rd_last = RD_NEVER;
                continue;
            }

            let sig1 = bits(sig_ci, 1);
            // Per-coefficient `level2` rate parameters from the tracked state
            // (`gt2` was hoisted per group above).
            let (base_level, gt1, c1c2idx) = if level2 {
                let c1c2idx =
                    (if c1_idx < 8 { 1u32 } else { 0 }) + (if c2_idx == 0 { 2 } else { 0 });
                let base_level = if c1_idx < 8 {
                    if c2_idx == 0 { 3 } else { 2 }
                } else {
                    1
                };
                let gt1_ci = gt1_base + 4 * ctx_set2 as usize + c1 as usize;
                (base_level, [bits(gt1_ci, 0), bits(gt1_ci, 1)], c1c2idx)
            } else {
                (0, [0, 0], 0)
            };

            let mut best_l = 0i64;
            let mut best_levbits = 0u64;
            let mut best_distl = dist0;
            let mut best_cost = dist0 + rate(sig0);
            for l in (q - 1).max(1)..=q {
                let unquant = dq.apply(l as i16) as i64;
                let dl = abs - unquant;
                let mut dist = (dl * dl) << scale_bits;
                if let Some(predicted) = predicted {
                    // quant.cpp:972,1004-1007: credit the candidate for the
                    // AC energy it reconstructs. The unquantized level is an
                    // absolute value, so sign-align the predicted coef with
                    // the coefficient before summing.
                    let aligned = if coeff >= 0 { predicted } else { -predicted };
                    dist -= psy_value((unquant + aligned).abs());
                }
                let mb = if level2 {
                    ic_level_bits(l as u32, base_level, gt1, gt2, c1c2idx, go_rice) + BYPASS_BITS
                } else {
                    magnitude_bits(l as u32)
                };
                let cost = dist + rate(sig1 + mb);
                if cost < best_cost {
                    best_cost = cost;
                    best_l = l as i64;
                    best_levbits = mb;
                    best_distl = dist;
                }
            }

            let rec = &mut recs[rank];
            rec.dist0 = dist0;
            if best_l != 0 {
                rec.level = if coeff < 0 { -best_l } else { best_l } as i16;
                rec.rd_normal = best_distl + rate(sig1 + best_levbits);
                rec.rd_last = best_distl + rate(best_levbits);
                sb_has_sig = true;
            } else {
                rec.level = 0;
                rec.rd_normal = dist0 + rate(sig0);
                rec.rd_last = RD_NEVER; // a zero coeff can never be the last
            }

            // Advance the `level2` greater1/greater2/Rice state (x265 quant.cpp:1074-1091).
            if level2 {
                let l = best_l as u32; // chosen absolute level (0 if zeroed)
                if l >= base_level && go_rice < 4 && l > level_threshold {
                    go_rice += 1;
                    level_threshold <<= 1;
                }
                if best_l != 0 {
                    c1_idx += 1;
                }
                if l > 1 {
                    c1 = 0;
                    if c2 < 2 {
                        c2 += 1;
                    }
                    c2_idx += 1;
                } else if (c1 == 1 || c1 == 2) && best_l != 0 {
                    c1 += 1;
                }
            }
        }
        // Carry this group's final greater1 context only when it coded a
        // coefficient (empty groups leave c1 == 1 and don't shift the next
        // group's ctxSet), matching x265 skipping all-zero groups.
        if level2 {
            if sb_has_sig || x265_empty_cg_carry_enabled() {
                prev_cg_c1 = c1;
            }
        }
        if sb_has_sig {
            coded_sb_flags[sby] |= 1u8 << sbx;
        }
    }

    // --- Stage (b): last-significant-position optimization. ---
    // Choose the forward scan rank `p` (a significant coefficient) to be the
    // last coded coefficient: ranks < p are coded normally, p is coded as last
    // (its sig flag inferred), ranks > p are zeroed (distortion only). Also
    // consider zeroing the whole block (cbf = 0).
    let total = recs.len();
    // Suffix distortion of zeroing rank..end. `suff_zero[total]` seeds the
    // trimmed tail's zeroing distortion so costs match the untrimmed pass.
    let suff_zero = &mut scratch.suff_zero;
    suff_zero.clear();
    suff_zero.resize(total + 1, 0);
    suff_zero[total] = tail_zero_dist;
    for k in (0..total).rev() {
        suff_zero[k] = suff_zero[k + 1] + recs[k].dist0;
    }
    // Baseline: all-zero block (cbf = 0), no residual bits.
    let mut best_cost = suff_zero[0];
    let mut best_last: isize = -1;

    // `last_sig_coeff_x/y` prices depend only on the axis value for this block.
    // Cache the two tiny axis tables once per RDOQ call instead of walking the
    // truncated-unary contexts for every non-zero last-position candidate.
    let mut last_x_bits_by_val = [0u64; 32];
    let mut last_y_bits_by_val = [0u64; 32];
    fill_last_axis_bits(&mut last_x_bits_by_val, ctxs, size, log2_size, c_idx, true);
    fill_last_axis_bits(&mut last_y_bits_by_val, ctxs, size, log2_size, c_idx, false);
    let last_bits_for_rec = |rec: &CoeffRec| -> u64 {
        let (raw_x, raw_y) = if scan_order == ScanOrder::Vertical {
            (rec.y as usize, rec.x as usize)
        } else {
            (rec.x as usize, rec.y as usize)
        };
        last_x_bits_by_val[raw_x] + last_y_bits_by_val[raw_y]
    };

    let last_stop = x265_last_stop_enabled();
    if last_stop {
        // Prefix RD of coding ranks 0..k as normal coefficients. Only the
        // diagnostic reverse-scan envelope needs random prefix lookup; the
        // default forward scan below carries the prefix in a scalar and avoids
        // one Vec fill per RDOQ call.
        let pref_normal = &mut scratch.pref_normal;
        pref_normal.clear();
        pref_normal.resize(total + 1, 0);
        for k in 0..total {
            pref_normal[k + 1] = pref_normal[k] + recs[k].rd_normal;
        }
        for p in (0..total).rev() {
            if recs[p].level == 0 {
                continue;
            }
            let lp = rate(last_bits_for_rec(&recs[p]));
            let cost = pref_normal[p] + recs[p].rd_last + suff_zero[p + 1] + lp;
            if cost < best_cost {
                best_cost = cost;
                best_last = p as isize;
            }
            if recs[p].level.unsigned_abs() > 1 {
                break;
            }
        }
    } else {
        let mut pref_normal = 0i64;
        for p in 0..total {
            if recs[p].level != 0 {
                let lp = rate(last_bits_for_rec(&recs[p]));
                let cost = pref_normal + recs[p].rd_last + suff_zero[p + 1] + lp;
                if cost < best_cost {
                    best_cost = cost;
                    best_last = p as isize;
                }
            }
            pref_normal += recs[p].rd_normal;
        }
    }

    // --- Stage (c): middle sub-block `coded_sub_block_flag` all-zero forcing. ---
    // For each sub-block coded with an explicit CSBF (strictly between the DC
    // sub-block and the last-significant sub-block, in forward scan order),
    // compare keeping it (CSBF=1: pay each coefficient's sig/level bits) against
    // zeroing it (CSBF=0: pay only the flag, take the distortion of dropping
    // every coefficient). Zeroing is always a bitstream-valid choice — the
    // residual encoder re-derives CSBF from the levels — so this can only change
    // RD, never validity. Sub-blocks are visited high->low frequency so a
    // neighbour's final coded state is known when its CSBF context is priced.
    // Ranks are arithmetic, so the last coefficient's sub-block scan index is
    // `last / 16`; with fewer than two groups before it the loop below is
    // empty, so skip the coded-state build entirely.
    let last_sb_scan = if best_last >= 0 {
        best_last as usize / 16
    } else {
        0
    };
    if last_sb_scan > 1 {
        let last = best_last as usize;

        // Final coded-sub-block state from the post-stage-(b) levels.
        let mut coded = [0u8; 8];
        for rec in recs.iter().take(last + 1) {
            if rec.level != 0 {
                coded[rec.y as usize / 4] |= 1u8 << (rec.x as usize / 4);
            }
        }

        for sb_scan in (1..last_sb_scan).rev() {
            let (sbx, sby) = scan_sub[sb_scan];
            let (sbx, sby) = (sbx as usize, sby as usize);
            if (coded[sby] & (1u8 << sbx)) == 0 {
                continue; // already empty: CSBF=0 either way
            }
            let right = sbx + 1 < sb_width && (coded[sby] & (1u8 << (sbx + 1))) != 0;
            let below = sby + 1 < sb_width && (coded[sby + 1] & (1u8 << sbx)) != 0;
            let csbf_neighbors = (right as u8) | ((below as u8) << 1);
            let csbf_ci = ctx::CODED_SUB_BLOCK_FLAG
                + (csbf_neighbors != 0) as usize
                + if c_idx > 0 { 2 } else { 0 };

            let mut keep = rate(bits(csbf_ci, 1));
            let mut zero = rate(bits(csbf_ci, 0));
            for rank in sb_scan * 16..(sb_scan + 1) * 16 {
                keep += recs[rank].rd_normal;
                zero += recs[rank].dist0;
            }

            // Keep/zero uses frozen contexts and ignores the prev_csbf context
            // shift zeroing imposes on lower-frequency neighbours, so this
            // greedy decision (like HM/x265's sub-block RDOQ) is a net RD win
            // but can lose a fraction of a percent on the odd block. A slack
            // margin was tried and made it worse (it blocked genuine wins
            // without fixing the directional misestimates), so decide bare.
            if zero < keep {
                for rank in sb_scan * 16..(sb_scan + 1) * 16 {
                    recs[rank].level = 0;
                }
                coded[sby] &= !(1u8 << sbx);
            }
        }
    }

    // Emit levels, zeroing everything after the chosen last position.
    let levels = &mut scratch.levels;
    levels.clear();
    levels.resize(size * size, 0);
    let mut nnz = 0u32;
    if best_last >= 0 {
        let last = best_last as usize;
        for rec in recs.iter().take(last + 1) {
            if rec.level != 0 {
                levels[rec.idx] = rec.level;
                nnz += 1;
            }
        }
    }

    RdoqResult {
        levels: &mut scratch.levels,
        nnz,
    }
}

#[cfg(test)]
mod rdoq_optimality_tests {
    //! Self-contained RDOQ selection-quality probe. Block distortion is
    //! `SSE(residual, reconstruct_residual(levels))` — prediction/reference
    //! independent — so we can feed a known residual through still265's RDOQ and
    //! compare its TRUE rate-distortion cost against a coordinate-descent optimum
    //! (candidates {0, |hq|-1, |hq|, |hq|+1} per coefficient, the RD-relevant
    //! neighborhood x265's trellis also chooses among). If a cheap local search
    //! consistently beats RDOQ on TRUE RD, the trellis is leaving bits on the
    //! table; if not, RDOQ selection is near-optimal and the still265-vs-x265
    //! gap is NOT in coefficient selection.
    use super::{
        RdoqPricingMode, RdoqPsy, RdoqScratch, apply_rdoq_pricing_mode, rdoq_single_scan_into,
    };
    use crate::cabac::CabacEstimator;
    use crate::contexts::Contexts;
    use crate::residual::{ScanOrder, estimate_residual_bits};
    use crate::transform::{forward_transform, quantize, reconstruct_residual};

    fn lambda(qp: i32) -> f64 {
        0.57 * 2f64.powf((qp as f64 - 12.0) / 3.0)
    }

    /// Test-only convenience wrapper around [`rdoq_single_scan_into`]: owns its
    /// scratch and returns owned levels, matching the shape these probes want.
    #[allow(clippy::too_many_arguments)]
    fn rdoq_single_scan(
        ctxs: &Contexts,
        coeffs: &[i16],
        log2_size: u8,
        c_idx: u8,
        qp: i32,
        bit_depth: u8,
        scan_order: ScanOrder,
        lambda: f64,
        level2: bool,
        psy: Option<RdoqPsy<'_>>,
    ) -> (Vec<i16>, u32) {
        let mut scratch = RdoqScratch::default();
        let result = rdoq_single_scan_into(
            ctxs,
            coeffs,
            log2_size,
            c_idx,
            qp,
            bit_depth,
            scan_order,
            lambda,
            level2,
            psy,
            &mut scratch,
        );
        (result.levels.to_vec(), result.nnz)
    }

    fn true_rd(
        levels: &[i16],
        residual: &[i16],
        log2: u8,
        qp: i32,
        bd: u8,
        scan: ScanOrder,
        lam: f64,
    ) -> (f64, f64, u64) {
        let recon = reconstruct_residual(levels, log2, qp, bd, false);
        let dist: f64 = residual
            .iter()
            .zip(&recon)
            .map(|(&r, &c)| {
                let d = r as i64 - c as i64;
                (d * d) as f64
            })
            .sum();
        let mut ctx = Contexts::new(qp);
        let bits = estimate_residual_bits(&mut ctx, levels, log2, 0, scan, false);
        (
            dist + lam * bits as f64 / CabacEstimator::SCALE as f64,
            dist,
            bits,
        )
    }

    #[test]
    fn pricing_modes_do_not_worsen_exact_rd_objective() {
        let log2 = 3;
        let qp = 28;
        let bd = 8;
        let scan = ScanOrder::Diagonal;
        let lam = lambda(qp);
        let residual: Vec<i16> = (0..64)
            .map(|i| {
                let x = (i & 7) as i16;
                let y = (i >> 3) as i16;
                (x * 9 - y * 5 + ((i % 5) as i16 - 2) * 7).clamp(-127, 127)
            })
            .collect();
        let coeffs = forward_transform(&residual, log2, false, bd);
        let ctx = Contexts::new(qp);
        let (start, _) = rdoq_single_scan(&ctx, &coeffs, log2, 0, qp, bd, scan, lam, true, None);

        for mode in [
            RdoqPricingMode::Running,
            RdoqPricingMode::Hybrid,
            RdoqPricingMode::ExactCleanup,
            RdoqPricingMode::BoundedTrellis,
        ] {
            let mut levels = start.clone();
            let before = true_rd(&levels, &residual, log2, qp, bd, scan, lam).0;
            let mut scratch = RdoqScratch::default();
            let returned_nnz = apply_rdoq_pricing_mode(
                &ctx,
                &coeffs,
                &residual,
                &mut levels,
                log2,
                0,
                qp,
                bd,
                false,
                scan,
                lam,
                mode,
                4,
                &mut scratch,
            );
            let after = true_rd(&levels, &residual, log2, qp, bd, scan, lam).0;
            assert!(
                after <= before + 1e-6,
                "{mode:?} worsened exact RD: before={before}, after={after}"
            );
            assert_eq!(
                returned_nnz,
                levels.iter().filter(|&&l| l != 0).count() as u32
            );
        }
    }

    /// Coordinate-descent over the per-coefficient RD-relevant candidate set,
    /// starting from `start`, minimizing true RD.
    fn optimize(
        start: &[i16],
        hq: &[i16],
        coeffs: &[i16],
        residual: &[i16],
        log2: u8,
        qp: i32,
        bd: u8,
        scan: ScanOrder,
        lam: f64,
    ) -> Vec<i16> {
        let mut cur = start.to_vec();
        let mut best = true_rd(&cur, residual, log2, qp, bd, scan, lam).0;
        loop {
            let mut improved = false;
            for i in 0..cur.len() {
                let center = hq[i];
                let sign: i16 = if center != 0 {
                    center.signum()
                } else if coeffs[i] != 0 {
                    coeffs[i].signum()
                } else {
                    1
                };
                let m = center.unsigned_abs() as i32;
                let cands = [
                    0i16,
                    (sign as i32 * (m - 1).max(0)) as i16,
                    (sign as i32 * m) as i16,
                    (sign as i32 * (m + 1)) as i16,
                ];
                for &cand in &cands {
                    if cand == cur[i] {
                        continue;
                    }
                    let save = cur[i];
                    cur[i] = cand;
                    let c = true_rd(&cur, residual, log2, qp, bd, scan, lam).0;
                    if c + 1e-6 < best {
                        best = c;
                        improved = true;
                    } else {
                        cur[i] = save;
                    }
                }
            }
            if !improved {
                break;
            }
        }
        cur
    }

    /// Deterministic Laplacian-ish residual generator (seeded LCG).
    fn make_residual(n: usize, scale: f64, seed: u64) -> Vec<i16> {
        let mut s = seed.wrapping_add(0x9E3779B97F4A7C15);
        let mut next = || {
            s = s
                .wrapping_mul(6364136223846793005)
                .wrapping_add(1442695040888963407);
            ((s >> 33) as f64) / (1u64 << 31) as f64
        };
        (0..n)
            .map(|_| {
                let u = next().max(1e-6);
                let sign = if next() < 0.5 { -1.0 } else { 1.0 };
                (sign * -scale * u.ln()).round().clamp(-90.0, 90.0) as i16
            })
            .collect()
    }

    #[test]
    fn rdoq_vs_bruteforce_optimum() {
        let log2: u8 = 3; // 8x8 luma
        let n = 1usize << (2 * log2);
        let bd = 8u8;
        let scan = ScanOrder::Diagonal;
        let mut agg_rdoq_excess = 0.0f64; // % over optimum
        let mut agg_hq_excess = 0.0f64;
        let mut count = 0;
        let mut rdoq_beaten = 0;
        println!(
            "\n  qp scale seed | nnz(hq/rdoq/opt) | RD hq / rdoq / opt | rdoq-excess% hq-excess%"
        );
        for qp in [22i32, 28, 34] {
            let lam = lambda(qp);
            for &scale in &[6.0f64, 12.0, 22.0] {
                for seed in 0..6u64 {
                    let residual = make_residual(n, scale, seed * 131 + qp as u64);
                    let coeffs = forward_transform(&residual, log2, false, bd);
                    let (hq, _) = quantize(&coeffs, log2, qp, bd);
                    let ctx = Contexts::new(qp);
                    let (rdoq, _) =
                        rdoq_single_scan(&ctx, &coeffs, log2, 0, qp, bd, scan, lam, true, None);
                    if hq.iter().all(|&l| l == 0) && rdoq.iter().all(|&l| l == 0) {
                        continue;
                    }
                    let opt_from_hq =
                        optimize(&hq, &hq, &coeffs, &residual, log2, qp, bd, scan, lam);
                    let opt_from_rdoq =
                        optimize(&rdoq, &hq, &coeffs, &residual, log2, qp, bd, scan, lam);
                    let rd_hq = true_rd(&hq, &residual, log2, qp, bd, scan, lam).0;
                    let rd_rdoq = true_rd(&rdoq, &residual, log2, qp, bd, scan, lam).0;
                    let rd_o1 = true_rd(&opt_from_hq, &residual, log2, qp, bd, scan, lam).0;
                    let rd_o2 = true_rd(&opt_from_rdoq, &residual, log2, qp, bd, scan, lam).0;
                    let rd_opt = rd_o1.min(rd_o2);
                    let nz = |v: &[i16]| v.iter().filter(|&&l| l != 0).count();
                    let rdoq_excess = 100.0 * (rd_rdoq - rd_opt) / rd_opt.max(1.0);
                    let hq_excess = 100.0 * (rd_hq - rd_opt) / rd_opt.max(1.0);
                    agg_rdoq_excess += rdoq_excess;
                    agg_hq_excess += hq_excess;
                    count += 1;
                    if rd_opt + 1.0 < rd_rdoq {
                        rdoq_beaten += 1;
                    }
                    if seed < 2 {
                        println!(
                            "  {qp:2} {scale:4.0} {seed:4} | {:2}/{:2}/{:2} | {:9.0} {:9.0} {:9.0} | {:+6.2}% {:+6.2}%",
                            nz(&hq),
                            nz(&rdoq),
                            nz(&opt_from_rdoq),
                            rd_hq,
                            rd_rdoq,
                            rd_opt,
                            rdoq_excess,
                            hq_excess
                        );
                    }
                }
            }
        }
        println!(
            "\n  AGGREGATE over {count} blocks: mean RDOQ excess over local-opt = {:.3}%, \
             mean hard-quant excess = {:.3}%, RDOQ beaten in {rdoq_beaten}/{count} blocks",
            agg_rdoq_excess / count as f64,
            agg_hq_excess / count as f64
        );
    }
}

#[cfg(test)]
mod psy_rdoq_tests {
    use super::{RdoqPsy, RdoqScratch, rdoq_single_scan_into};
    use crate::contexts::Contexts;
    use crate::residual::ScanOrder;

    fn lambda(qp: i32) -> f64 {
        0.57 * 2f64.powf((qp as f64 - 12.0) / 3.0)
    }

    /// Test-only convenience wrapper around [`rdoq_single_scan_into`]: owns its
    /// scratch and returns owned levels, matching the shape these probes want.
    #[allow(clippy::too_many_arguments)]
    fn rdoq_single_scan(
        ctxs: &Contexts,
        coeffs: &[i16],
        log2_size: u8,
        c_idx: u8,
        qp: i32,
        bit_depth: u8,
        scan_order: ScanOrder,
        lambda: f64,
        level2: bool,
        psy: Option<RdoqPsy<'_>>,
    ) -> (Vec<i16>, u32) {
        let mut scratch = RdoqScratch::default();
        let result = rdoq_single_scan_into(
            ctxs,
            coeffs,
            log2_size,
            c_idx,
            qp,
            bit_depth,
            scan_order,
            lambda,
            level2,
            psy,
            &mut scratch,
        );
        (result.levels.to_vec(), result.nnz)
    }

    /// psy-rdoq keeps an AC coefficient that plain RDOQ zeroes: a lone small
    /// AC coefficient quantizes to level 1 but its sig/level/last bits
    /// outweigh the distortion saving, so plain RDOQ drops the whole block.
    /// With a psy bias (source DCT == residual DCT, so the uncoded credit is
    /// zero while a coded level reconstructs AC energy), the coefficient is
    /// kept.
    #[test]
    fn psy_keeps_ac_coefficient_that_plain_rdoq_zeroes() {
        let log2 = 3u8;
        let size = 1usize << log2;
        let qp = 34;
        let bd = 8u8;
        let scan = ScanOrder::Diagonal;
        let lam = lambda(qp);
        let ctx = Contexts::new(qp);

        let mut coeffs = vec![0i16; size * size];
        let pos = 3 * size + 2;
        coeffs[pos] = 260; // just above the qp34 8x8 significance threshold (256)

        let (plain, plain_nnz) =
            rdoq_single_scan(&ctx, &coeffs, log2, 0, qp, bd, scan, lam, true, None);
        assert_eq!(plain[pos], 0, "test premise: plain RDOQ zeroes this coef");
        assert_eq!(plain_nnz, 0);

        let psy = RdoqPsy {
            src_dct: &coeffs,   // predicted == 0 everywhere: uncoded preserves no AC energy
            psy_scale: 1 << 28, // strong synthetic psy weight
        };
        let (kept, kept_nnz) =
            rdoq_single_scan(&ctx, &coeffs, log2, 0, qp, bd, scan, lam, true, Some(psy));
        assert_ne!(kept[pos], 0, "psy-rdoq must keep the AC coefficient");
        assert_eq!(kept_nnz, 1);
        assert!(kept[pos] > 0, "level sign must follow the coefficient sign");
    }

    /// The psy bias is AC-only: a DC-only block must be unaffected even by an
    /// extreme psy weight and a wildly different DC prediction.
    #[test]
    fn psy_skips_dc_position() {
        let log2 = 3u8;
        let size = 1usize << log2;
        let qp = 30;
        let bd = 8u8;
        let scan = ScanOrder::Diagonal;
        let lam = lambda(qp);
        let ctx = Contexts::new(qp);

        let mut coeffs = vec![0i16; size * size];
        coeffs[0] = 600;

        let (plain, plain_nnz) =
            rdoq_single_scan(&ctx, &coeffs, log2, 0, qp, bd, scan, lam, true, None);

        let mut src_dct = vec![0i16; size * size];
        src_dct[0] = 30000; // huge DC "prediction" energy that must be ignored
        let psy = RdoqPsy {
            src_dct: &src_dct,
            psy_scale: 1 << 30,
        };
        let (biased, biased_nnz) =
            rdoq_single_scan(&ctx, &coeffs, log2, 0, qp, bd, scan, lam, true, Some(psy));
        assert_eq!(plain, biased, "DC-only block must be psy-invariant");
        assert_eq!(plain_nnz, biased_nnz);
    }
}

#[cfg(test)]
mod last_axis_table_tests {
    use super::{fill_last_axis_bits, last_axis_bits};
    use crate::contexts::Contexts;

    #[test]
    fn cumulative_last_axis_tables_match_scalar_reference() {
        for qp in [0, 22, 28, 37, 51] {
            let ctxs = Contexts::new(qp);
            for log2_size in 2..=5 {
                let size = 1usize << log2_size;
                for c_idx in [0u8, 1, 2] {
                    for is_x in [false, true] {
                        let mut got = [0u64; 32];
                        fill_last_axis_bits(&mut got, &ctxs, size, log2_size, c_idx, is_x);
                        for (value, &bits) in got.iter().take(size).enumerate() {
                            assert_eq!(
                                bits,
                                last_axis_bits(&ctxs, value as u32, log2_size, c_idx, is_x,),
                                "qp={qp} log2={log2_size} c={c_idx} x={is_x} value={value}",
                            );
                        }
                    }
                }
            }
        }
    }
}

#[cfg(test)]
mod context_drift_sizing {
    //! Sizes the agent's "rate-context fidelity" suspect: still265 prices all
    //! in-CTU trial decisions from `price_base` frozen at CTU entry, but real
    //! coded bits use the CABAC context evolving block-by-block. This measures
    //! how much a textured block's exact CABAC bit cost moves between a fresh
    //! CTU-entry context and one drifted by ~30 prior textured blocks (mid-CTU).
    //! If the per-block drift is tiny, the frozen-context approximation cannot
    //! account for the ~0.3 dB texture gap and the running-context RD build is
    //! not worth it.
    use crate::contexts::Contexts;
    use crate::residual::{ScanOrder, estimate_residual_bits};
    use crate::transform::{forward_transform, quantize};

    fn make_residual(n: usize, scale: f64, seed: u64) -> Vec<i16> {
        let mut s = seed.wrapping_add(0x9E3779B97F4A7C15);
        let mut next = || {
            s = s
                .wrapping_mul(6364136223846793005)
                .wrapping_add(1442695040888963407);
            ((s >> 33) as f64) / (1u64 << 31) as f64
        };
        (0..n)
            .map(|_| {
                let u = next().max(1e-6);
                let sign = if next() < 0.5 { -1.0 } else { 1.0 };
                (sign * -scale * u.ln()).round().clamp(-90.0, 90.0) as i16
            })
            .collect()
    }

    #[test]
    fn context_drift_pricing_magnitude() {
        let log2 = 3u8;
        let n = 1usize << (2 * log2);
        let bd = 8u8;
        let scan = ScanOrder::Diagonal;
        let drift_blocks = 30; // ~mid-CTU position (64 8x8 blocks per 64x64 CTU)
        for qp in [22i32, 28, 34] {
            for &scale in &[8.0f64, 18.0] {
                let mut sum_fresh = 0i64;
                let mut sum_drift = 0i64;
                let mut sum_abs_delta = 0i64;
                let trials = 40;
                for t in 0..trials {
                    let coeffs = forward_transform(
                        &make_residual(n, scale, t * 7 + qp as u64),
                        log2,
                        false,
                        bd,
                    );
                    let (levels, _) = quantize(&coeffs, log2, qp, bd);
                    // (a) fresh CTU-entry context
                    let mut cf = Contexts::new(qp);
                    let bf = estimate_residual_bits(&mut cf, &levels, log2, 0, scan, false) as i64;
                    // (b) context drifted by coding `drift_blocks` prior textured blocks
                    let mut cd = Contexts::new(qp);
                    for k in 0..drift_blocks {
                        let pc = forward_transform(
                            &make_residual(n, scale, 9000 + t * 131 + k * 17 + qp as u64),
                            log2,
                            false,
                            bd,
                        );
                        let (pl, _) = quantize(&pc, log2, qp, bd);
                        let _ = estimate_residual_bits(&mut cd, &pl, log2, 0, scan, false);
                    }
                    let bd2 = estimate_residual_bits(&mut cd, &levels, log2, 0, scan, false) as i64;
                    sum_fresh += bf;
                    sum_drift += bd2;
                    sum_abs_delta += (bf - bd2).abs();
                }
                let scale_u = crate::cabac::CabacEstimator::SCALE as f64;
                let mf = sum_fresh as f64 / trials as f64 / scale_u;
                let md = sum_drift as f64 / trials as f64 / scale_u;
                println!(
                    "  qp{qp} scale{scale:4.0}: fresh={mf:7.1}b drift={md:7.1}b  mean_signed_delta={:+.2}b ({:+.2}%)  mean_abs_delta={:.2}b",
                    md - mf,
                    100.0 * (md - mf) / mf,
                    sum_abs_delta as f64 / trials as f64 / scale_u
                );
            }
        }
    }
}