oxideav-h261 0.0.7

Pure-Rust ITU-T H.261 video decoder for oxideav
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
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
//! H.261 encoder โ€” Baseline (I + P pictures, integer-pel MC, FIL loop filter).
//!
//! Public entry points:
//!
//! * [`encode_intra_picture`] โ€” single I-picture, stateless.
//! * [`encode_inter_picture`] โ€” single P-picture, requires a reconstructed
//!   reference picture (typically the local recon of the previous output).
//! * [`H261Encoder`] โ€” stateful sequence encoder that produces an I-picture
//!   on the first frame and P-pictures thereafter, maintaining the local
//!   reconstruction across calls.
//!
//! No rate control, no half-pel MC (H.261 ยง3.2.2 specifies integer-pel
//! components in `[-15, 15]` only โ€” there is no half-pel mode in the
//! standard). The loop filter (`Inter+MC+FIL` MTYPEs, ยง3.2.3) is enabled and
//! selected on a per-MB rate/distortion basis. Each P-picture macroblock
//! chooses one of:
//!
//! * **Skip** โ€” when the best MV is `(0, 0)` and the residual quantises to
//!   all zeros. Absorbed into the next coded MBA difference.
//! * **`Inter`** (no MC) โ€” when the best MV is `(0, 0)` but residual is
//!   non-zero and the unfiltered branch wins.
//! * **`Inter+MC` (MC-only)** โ€” when the best MV is non-zero and the
//!   residual quantises to all zeros (predictor alone is good enough).
//! * **`Inter+MC` with CBP+TCOEFF** โ€” when the best MV is non-zero and at
//!   least one block carries residual.
//! * **`Inter+MC+FIL` (MC-only, filtered)** โ€” same as MC-only but with the
//!   spatial loop filter (ยง3.2.3) applied to the predictor. Per Table 2
//!   Note 2 the MV may be zero. The 3-bit MTYPE (vs 9-bit MC-only) makes
//!   this a frequent win whenever the filter does not raise residual energy
//!   above the 6-bit MTYPE saving threshold.
//! * **`Inter+MC+FIL` with CBP+TCOEFF** โ€” filtered predictor + residual.
//!
//! Motion estimation is full-window SAD over the ยฑ15 pel range allowed by
//! H.261 Annex A, with a small ฮปยท(|mvx|+|mvy|) penalty biasing ties toward
//! the shorter MV (cheaper VLC, more skips downstream). Chroma MVs are
//! `mvluma / 2` truncated toward zero per ยง3.2.2.
//!
//! ## Picture layer (ยง4.2.1)
//!
//! ```text
//!   PSC (20)  0000 0000 0000 0001 0000
//!   TR  (5)   temporal reference
//!   PTYPE(6)  bit1 split, bit2 doccam, bit3 freeze-release,
//!             bit4 source format (0=QCIF, 1=CIF), bit5 HI_RES (1=off),
//!             bit6 spare (always 1 per ยง4.1)
//!   PEI (1)   0 โ€” we never emit PSPARE
//! ```
//!
//! ## GOB layer (ยง4.2.2)
//!
//! ```text
//!   GBSC (16) 0000 0000 0000 0001
//!   GN   (4)  1..=12 (CIF) or 1,3,5 (QCIF)
//!   GQUANT(5) quantiser index 1..=31
//!   GEI  (1)  0 โ€” we never emit GSPARE
//! ```
//!
//! ## MB layer
//!
//! For INTRA MBs (I-picture and any I MBs in a P-picture):
//!
//! * MBA VLC โ€” `Diff(1)` for the first coded MB, then 1-differences.
//! * MTYPE = `Intra` (4-bit `0001`), no MQUANT override.
//! * CBP is implicit (all 6 blocks are always coded).
//! * 6 blocks (Y1, Y2, Y3, Y4, Cb, Cr). Each block is INTRA DC + AC.
//!
//! For INTER MBs (P-picture):
//!
//! * MBA VLC โ€” difference from the previous coded MB (skipped MBs are
//!   absorbed into the difference per ยง4.2.3.3).
//! * MTYPE โ€” chosen from `Inter` / `Inter+MC` / `Inter+MC` (CBP+TCOEFF)
//!   based on the MV and residual.
//! * MVD โ€” two VLCs (x, y) per Table 3, present only for the MC variants.
//! * CBP โ€” selects which of the 6 blocks carry residual data (Table 4).
//!   When all six would be uncoded and the MV is zero we skip the MB.
//! * Each coded block is a TCOEFF VLC stream with `1s` first-coefficient
//!   shortcut and `11s` for subsequent (0,1) coefficients.
//!
//! ### MVD predictor reset
//!
//! ยง4.2.3.4 mandates the MV predictor be reset to `(0, 0)` for MBs 1, 12,
//! and 23 (start of each MB row in a GOB), at MBA discontinuity, and when
//! the previous MB was not MC-coded. The encoder follows ยง4.2.3.4 exactly,
//! and the in-crate decoder applies the same three reset conditions (the
//! MBA 1 / 12 / 23 row-boundary reset included), so any spec-conformant
//! decoder โ€” ours or a third party's โ€” derives the same predictor at the
//! row-boundary MBs without the encoder constraining MC there.

use std::collections::VecDeque;

use oxideav_core::bits::BitWriter;
use oxideav_core::packet::PacketFlags;
use oxideav_core::{
    CodecId, CodecParameters, Encoder, Error, Frame, MediaType, Packet, Result, TimeBase,
};

use crate::fdct::{fdct_intra, fdct_signed};
use crate::idct::{idct_intra, idct_signed};
use crate::mb::Picture;
use crate::picture::SourceFormat;
use crate::quant::{quant_ac, quant_intra_dc};
use crate::tables::{
    encode_cbp, encode_mba_diff, encode_mvd, lookup_tcoeff, MBA_STUFFING, MTYPE_INTER,
    MTYPE_INTER_MC_CBP, MTYPE_INTER_MC_CBP_MQUANT, MTYPE_INTER_MC_FIL_CBP,
    MTYPE_INTER_MC_FIL_CBP_MQUANT, MTYPE_INTER_MC_FIL_ONLY, MTYPE_INTER_MC_ONLY,
    MTYPE_INTER_MQUANT, MTYPE_INTRA, MTYPE_INTRA_MQUANT, ZIGZAG,
};

/// Default GOB-level quantiser. QUANT in `1..=31`. 8 is a balanced
/// quality/bit-rate point.
pub const DEFAULT_QUANT: u32 = 8;

/// Maximum integer-pel motion-vector magnitude per ยง3.2.2 / Annex A.
const MV_MAX: i32 = 15;

/// Diamond-search radius. ยฑ15 in each axis is the H.261 limit (ยง3.2.2);
/// we search the full window in a small-diamond pattern that progressively
/// refines the best-so-far candidate.
const ME_SEARCH_RADIUS: i32 = MV_MAX;

/// Per-GOB MQUANT rate controller (ยง4.2.3.3). Tracks the bits accumulated
/// in the GOB and nudges the quantiser ยฑ1 step around the picture base when
/// we drift away from a linear bit-budget target.
///
/// MQUANT can only be sent on MTYPEs that have the `mquant` flag set
/// (Table 2/H.261): Intra+MQUANT, Inter+MQUANT, InterMc+CBP+MQUANT,
/// InterMcFil+CBP+MQUANT. The controller therefore proposes a `desired`
/// quantiser for each MB; the encoder honours it iff the chosen MTYPE is
/// MQUANT-eligible, otherwise the change is deferred to the next eligible
/// MB (the decoder's `quant_in_effect` is what we need to match for the
/// residual reconstruction to be byte-tight).
struct MqRateCtrl {
    /// Picture-level base QUANT (= GQUANT for this GOB).
    base_quant: u32,
    /// Quantiser the decoder is currently using (= GQUANT at GOB start,
    /// updated to the last MQUANT we emitted).
    quant_in_effect: u32,
    /// Target bits per MB across the GOB (computed from the picture's
    /// previous-MB-bit-budget). For the very first GOB of the very first
    /// P-frame we use a fixed reference budget; subsequent GOBs use a
    /// rolling estimate. The controller only nudges by ยฑ1 step at a time
    /// and clamps within `[min_quant, max_quant]` so it can never run
    /// away.
    target_per_mb: u32,
    /// Bits emitted into this GOB's MB stream so far (excluding header).
    cumulative: u64,
    /// Allowed quantiser window around `base_quant`. Clamped to 1..=31.
    min_quant: u32,
    max_quant: u32,
}

impl MqRateCtrl {
    /// Build a controller anchored on `base_quant` with a `target_per_mb`
    /// budget. The window is `[max(1, base-WIN), min(31, base+WIN)]`.
    fn new(base_quant: u32, target_per_mb: u32) -> Self {
        const WIN: u32 = 6;
        let min_quant = base_quant.saturating_sub(WIN).max(1);
        let max_quant = (base_quant + WIN).min(31);
        Self {
            base_quant,
            quant_in_effect: base_quant,
            target_per_mb,
            cumulative: 0,
            min_quant,
            max_quant,
        }
    }

    /// Suggest a quantiser for MB index `mb_idx` (0-based, 0..33 within a
    /// GOB). Compares cumulative bits against the linear budget; nudges
    /// QUANT toward `base_quant` when within budget, away from it when
    /// over/under.
    ///
    /// We use a generous slack (16x the per-MB target) so the controller
    /// only kicks in on pathological MBs that emit many multiples of the
    /// average bit count โ€” typically rapid-motion regions where coarser
    /// quantisation has the largest payoff (small extra MQUANT overhead vs
    /// large TCOEFF savings).
    fn desired(&self, mb_idx: u32) -> u32 {
        let expected = (mb_idx as u64).saturating_mul(self.target_per_mb as u64);
        let slack = (self.target_per_mb as u64).saturating_mul(16);
        let cur = self.quant_in_effect as i32;
        let bumped = if self.cumulative > expected.saturating_add(slack) {
            // Way over budget โ€” coarsen aggressively.
            cur + 1
        } else if self.cumulative + slack * 2 < expected {
            // Far under budget โ€” refine toward base.
            cur - 1
        } else {
            // Within tolerance โ€” gravitate back toward base.
            match cur.cmp(&(self.base_quant as i32)) {
                std::cmp::Ordering::Greater => cur - 1,
                std::cmp::Ordering::Less => cur,
                std::cmp::Ordering::Equal => cur,
            }
        };
        (bumped.max(self.min_quant as i32) as u32).min(self.max_quant)
    }

    /// Note that `bits` were emitted in this MB.
    fn account(&mut self, bits: u64) {
        self.cumulative = self.cumulative.saturating_add(bits);
    }

    /// Commit a quantiser change (called after MQUANT is emitted).
    fn commit_quant(&mut self, q: u32) {
        self.quant_in_effect = q;
    }
}

/// Encode a single INTRA picture.
///
/// `y`, `cb`, `cr` are packed planes with the specified strides. `quant`
/// is the GOB-level QUANT (1..=31). `temporal_reference` is the 5-bit TR
/// field (mod 32) the decoder uses for lip-sync.
pub fn encode_intra_picture(
    fmt: SourceFormat,
    y: &[u8],
    y_stride: usize,
    cb: &[u8],
    cb_stride: usize,
    cr: &[u8],
    cr_stride: usize,
    quant: u32,
    temporal_reference: u8,
) -> Result<Vec<u8>> {
    let (bytes, _recon) = encode_intra_picture_with_recon(
        fmt,
        y,
        y_stride,
        cb,
        cb_stride,
        cr,
        cr_stride,
        quant,
        temporal_reference,
    )?;
    Ok(bytes)
}

/// Encode an INTRA picture and also return a locally reconstructed
/// `Picture` matching what a conformant decoder would produce. The
/// reconstruction can be passed to [`encode_inter_picture`] as the
/// reference for the next P-frame.
pub fn encode_intra_picture_with_recon(
    fmt: SourceFormat,
    y: &[u8],
    y_stride: usize,
    cb: &[u8],
    cb_stride: usize,
    cr: &[u8],
    cr_stride: usize,
    quant: u32,
    temporal_reference: u8,
) -> Result<(Vec<u8>, Picture)> {
    validate_inputs(
        fmt,
        y,
        y_stride,
        cb,
        cb_stride,
        cr,
        cr_stride,
        quant,
        temporal_reference,
    )?;

    let (w, h) = fmt.dimensions();
    let mut recon = Picture::new(w as usize, h as usize);

    let mut bw = BitWriter::with_capacity(4096);
    write_picture_header(&mut bw, fmt, temporal_reference);

    for &gn in fmt.gob_numbers() {
        write_gob_header(&mut bw, gn, quant);
        let (gob_x, gob_y) = gob_origin_luma(fmt, gn);
        encode_gob_intra(
            &mut bw, y, y_stride, cb, cb_stride, cr, cr_stride, gob_x, gob_y, quant, &mut recon,
        );
    }

    bw.align_to_byte();
    Ok((bw.finish(), recon))
}

/// Encode a single INTER (P) picture against a reference reconstruction.
///
/// Returns the elementary-stream bytes and an updated reconstruction
/// suitable for use as the reference for the next P-frame.
///
/// Quantisation strategy: each MB is tested for "skippable" (residual all
/// zero after quantisation); if not skippable, encode it as INTER (no MC).
/// If the residual quantises to all-zero blocks across all six positions
/// โ€” which would correspond to CBP=0 (forbidden by Table 4) โ€” we still
/// skip the MB instead of forcing a CBP.
#[allow(clippy::too_many_arguments)]
pub fn encode_inter_picture(
    fmt: SourceFormat,
    y: &[u8],
    y_stride: usize,
    cb: &[u8],
    cb_stride: usize,
    cr: &[u8],
    cr_stride: usize,
    quant: u32,
    temporal_reference: u8,
    reference: &Picture,
) -> Result<(Vec<u8>, Picture)> {
    encode_inter_picture_forced_update(
        fmt,
        y,
        y_stride,
        cb,
        cb_stride,
        cr,
        cr_stride,
        quant,
        temporal_reference,
        reference,
        &[],
    )
}

/// Encode a P-picture with an explicit ยง3.4 forced-updating set.
///
/// `forced_mbs` lists the global macroblock indices (raster order over the
/// whole picture: GOB 0 holds MBs 0..33, GOB 1 holds 33..66, โ€ฆ) that MUST
/// be transmitted in INTRA mode this frame regardless of the rate/distortion
/// mode decision. H.261 ยง3.4 requires every macroblock to be forcibly
/// INTRA-updated "at least once per every 132 times it is transmitted" so
/// that inverse-transform mismatch error cannot accumulate without bound;
/// the per-MB scheduler in [`H261Encoder`] populates this set automatically,
/// but a caller driving [`encode_inter_picture`] directly can supply its own
/// (for example, the ยงC.3 loss-driven MB refresh in RFC 4587). Indices out
/// of range are ignored; duplicates are harmless.
#[allow(clippy::too_many_arguments)]
pub fn encode_inter_picture_forced_update(
    fmt: SourceFormat,
    y: &[u8],
    y_stride: usize,
    cb: &[u8],
    cb_stride: usize,
    cr: &[u8],
    cr_stride: usize,
    quant: u32,
    temporal_reference: u8,
    reference: &Picture,
    forced_mbs: &[u32],
) -> Result<(Vec<u8>, Picture)> {
    validate_inputs(
        fmt,
        y,
        y_stride,
        cb,
        cb_stride,
        cr,
        cr_stride,
        quant,
        temporal_reference,
    )?;
    let (w, h) = fmt.dimensions();
    if reference.width != w as usize || reference.height != h as usize {
        return Err(Error::invalid(format!(
            "h261 encode: reference dims {}x{} mismatch picture {}x{}",
            reference.width, reference.height, w, h
        )));
    }

    let mut recon = Picture::new(w as usize, h as usize);

    let mut bw = BitWriter::with_capacity(8192);
    write_picture_header(&mut bw, fmt, temporal_reference);

    for (gob_idx, &gn) in fmt.gob_numbers().iter().enumerate() {
        write_gob_header(&mut bw, gn, quant);
        let (gob_x, gob_y) = gob_origin_luma(fmt, gn);
        // Project the global forced-update set onto this GOB's 33 MBs.
        let mb_base = (gob_idx * 33) as u32;
        let mut forced_intra = [false; 33];
        for &gm in forced_mbs {
            if gm >= mb_base && gm < mb_base + 33 {
                forced_intra[(gm - mb_base) as usize] = true;
            }
        }
        encode_gob_inter(
            &mut bw,
            y,
            y_stride,
            cb,
            cb_stride,
            cr,
            cr_stride,
            gob_x,
            gob_y,
            quant,
            reference,
            &mut recon,
            &forced_intra,
        );
    }

    bw.align_to_byte();
    Ok((bw.finish(), recon))
}

/// Stateful sequence encoder. The first call to [`Self::encode_frame`]
/// emits an INTRA picture; subsequent calls emit P-pictures predicted
/// from the local reconstruction of the previous emitted frame.
pub struct H261Encoder {
    fmt: SourceFormat,
    quant: u32,
    /// Counter for the temporal reference field. Wraps mod 32.
    next_tr: u8,
    /// Local reconstruction of the most recently emitted picture, kept as
    /// the prediction reference for the next P-frame.
    reference: Option<Picture>,
    /// Number of frames between forced INTRA refreshes. 0 = never refresh
    /// after the first I.
    intra_period: u32,
    frames_since_intra: u32,
    /// ยง3.4 forced-updating period: the maximum number of times a single
    /// macroblock may be transmitted before it MUST be forcibly INTRA-coded
    /// (the spec mandates "at least once per every 132"). 0 disables per-MB
    /// forced updating (relying solely on `intra_period` whole-frame I's).
    forced_update_period: u32,
    /// Per-MB transmission counter since each MB's last INTRA coding, in
    /// global raster order (GOB 0 = MBs 0..33, GOB 1 = 33..66, โ€ฆ). Sized to
    /// the source format on the first frame.
    mb_since_intra: Vec<u32>,
    /// Round-robin cursor so the forced-update load is spread across frames
    /// rather than spiking every 132th P-frame.
    forced_update_cursor: usize,
}

impl H261Encoder {
    /// Build a new encoder for the given source format and quantiser.
    pub fn new(fmt: SourceFormat, quant: u32) -> Self {
        debug_assert!((1..=31).contains(&quant));
        Self {
            fmt,
            quant,
            next_tr: 0,
            reference: None,
            intra_period: 30, // an I-refresh roughly every second at 30 fps
            frames_since_intra: 0,
            forced_update_period: 132, // ยง3.4 upper bound
            mb_since_intra: Vec::new(),
            forced_update_cursor: 0,
        }
    }

    /// Override the I-refresh period (number of frames between forced
    /// INTRAs, including the first). `0` disables refresh.
    pub fn with_intra_period(mut self, period: u32) -> Self {
        self.intra_period = period;
        self
    }

    /// Override the ยง3.4 per-MB forced-updating period (the maximum number
    /// of transmissions a macroblock may go without an INTRA update). The
    /// spec mandates this be `<= 132`; the default is exactly `132`. Pass
    /// `0` to disable per-MB forced updating entirely (not recommended for
    /// long sequences โ€” inverse-transform mismatch error can then accumulate
    /// unbounded between whole-frame I-refreshes).
    pub fn with_forced_update_period(mut self, period: u32) -> Self {
        self.forced_update_period = period;
        self
    }

    /// Encode one frame from packed YUV 4:2:0 planes. Returns the H.261
    /// elementary-stream bytes for this picture.
    #[allow(clippy::too_many_arguments)]
    pub fn encode_frame(
        &mut self,
        y: &[u8],
        y_stride: usize,
        cb: &[u8],
        cb_stride: usize,
        cr: &[u8],
        cr_stride: usize,
    ) -> Result<Vec<u8>> {
        let total_mbs = self.fmt.gob_numbers().len() * 33;
        if self.mb_since_intra.len() != total_mbs {
            self.mb_since_intra = vec![0u32; total_mbs];
            self.forced_update_cursor = 0;
        }

        let force_intra = self.reference.is_none()
            || (self.intra_period != 0 && self.frames_since_intra >= self.intra_period);

        let (bytes, recon) = if force_intra {
            self.frames_since_intra = 1;
            // A whole-frame INTRA picture forcibly updates every MB.
            for c in self.mb_since_intra.iter_mut() {
                *c = 0;
            }
            self.forced_update_cursor = 0;
            encode_intra_picture_with_recon(
                self.fmt,
                y,
                y_stride,
                cb,
                cb_stride,
                cr,
                cr_stride,
                self.quant,
                self.next_tr,
            )?
        } else {
            self.frames_since_intra += 1;
            // ยง3.4 forced-updating set for this P-picture.
            let forced = self.compute_forced_update_set(total_mbs);
            let reference = self
                .reference
                .as_ref()
                .expect("reference must exist by now");
            let result = encode_inter_picture_forced_update(
                self.fmt,
                y,
                y_stride,
                cb,
                cb_stride,
                cr,
                cr_stride,
                self.quant,
                self.next_tr,
                reference,
                &forced,
            )?;
            // Update per-MB counters: an INTRA-forced MB resets to 0, every
            // other MB's "times transmitted since last INTRA" grows by one.
            for (i, c) in self.mb_since_intra.iter_mut().enumerate() {
                if forced.binary_search(&(i as u32)).is_ok() {
                    *c = 0;
                } else {
                    *c = c.saturating_add(1);
                }
            }
            result
        };

        self.reference = Some(recon);
        self.next_tr = self.next_tr.wrapping_add(1) & 0x1F;
        Ok(bytes)
    }

    /// Compute the ยง3.4 forced-update macroblock set for the next P-picture.
    ///
    /// Returns the sorted global MB indices that MUST be coded INTRA so that
    /// no macroblock is transmitted more than `forced_update_period` times
    /// without an INTRA update (ยง3.4 controls inverse-transform mismatch
    /// accumulation). Two contributions are merged:
    ///
    ///   * **mandatory** โ€” any MB whose counter is one transmission short of
    ///     the period (`count + 1 >= period`) is forced now, before it can
    ///     exceed the bound.
    ///   * **proactive round-robin** โ€” `ceil(total / period)` MBs per frame
    ///     are forced on a rotating cursor, so the load is spread evenly
    ///     across the refresh window instead of spiking when every counter
    ///     reaches the cap on the same frame.
    ///
    /// `period == 0` disables forced updating and returns an empty set.
    fn compute_forced_update_set(&mut self, total_mbs: usize) -> Vec<u32> {
        let period = self.forced_update_period;
        if period == 0 || total_mbs == 0 {
            return Vec::new();
        }
        let mut forced: Vec<u32> = Vec::new();
        // Mandatory: counters about to exceed the bound.
        for (i, &c) in self.mb_since_intra.iter().enumerate() {
            if c + 1 >= period {
                forced.push(i as u32);
            }
        }
        // Proactive round-robin sweep.
        let per_frame = total_mbs.div_ceil(period as usize).max(1);
        for _ in 0..per_frame {
            forced.push(self.forced_update_cursor as u32);
            self.forced_update_cursor = (self.forced_update_cursor + 1) % total_mbs;
        }
        forced.sort_unstable();
        forced.dedup();
        forced
    }
}

/// Common front-door checks used by both intra and inter entry points.
#[allow(clippy::too_many_arguments)]
fn validate_inputs(
    fmt: SourceFormat,
    y: &[u8],
    y_stride: usize,
    cb: &[u8],
    cb_stride: usize,
    cr: &[u8],
    cr_stride: usize,
    quant: u32,
    temporal_reference: u8,
) -> Result<()> {
    if !(1..=31).contains(&quant) {
        return Err(Error::invalid(format!(
            "h261 encode: QUANT out of range: {quant}"
        )));
    }
    if temporal_reference > 31 {
        return Err(Error::invalid(format!(
            "h261 encode: TR out of range: {temporal_reference}"
        )));
    }
    let (_w, h) = fmt.dimensions();
    let h = h as usize;
    if y.len() < y_stride * h || cb.len() < cb_stride * (h / 2) || cr.len() < cr_stride * (h / 2) {
        return Err(Error::invalid("h261 encode: input plane too short"));
    }
    Ok(())
}

/// The three picture-layer display-control flags carried in PTYPE
/// (ยง4.2.1.3 bits 1โ€“3). These are independent of the source-format and
/// HI_RES bits, which the encoder derives from the picture geometry and
/// the Annex-D mode rather than from caller intent.
///
/// All three default to "off" (`false`), which reproduces the canonical
/// motion-video header the encoder has always emitted. A caller drives a
/// non-default value to signal:
///
/// * [`Ptype::split_screen`] (bit 1) โ€” "Split screen indicator, '0' off,
///   '1' on" (ยง4.2.1.3). Indicates the picture is to be displayed as two
///   side-by-side half-pictures.
/// * [`Ptype::document_camera`] (bit 2) โ€” "Document camera indicator,
///   '0' off, '1' on" (ยง4.2.1.3).
/// * [`Ptype::freeze_picture_release`] (bit 3) โ€” "Freeze picture
///   release, '0' off, '1' on" (ยง4.2.1.3). Per ยง4.3.3 this is set in the
///   picture header of "the first picture coded in response to [a] fast
///   update request", allowing a decoder that had frozen its display
///   (ยง4.3.1) to resume normal display.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct Ptype {
    /// PTYPE bit 1 โ€” split-screen indicator.
    pub split_screen: bool,
    /// PTYPE bit 2 โ€” document-camera indicator.
    pub document_camera: bool,
    /// PTYPE bit 3 โ€” freeze-picture release (ยง4.3.3).
    pub freeze_picture_release: bool,
}

/// Emit the 32-bit picture header (ยง4.2.1).
pub fn write_picture_header(bw: &mut BitWriter, fmt: SourceFormat, tr: u8) {
    write_picture_header_full(bw, fmt, tr, true);
}

/// Emit the 32-bit picture header (ยง4.2.1) with an explicit `HI_RES`
/// bit. `hi_res_off = true` produces the canonical motion-video header
/// (matches [`write_picture_header`]); `hi_res_off = false` produces an
/// Annex D still-image sub-image header. The caller is responsible for
/// passing a `tr` whose top 3 bits are zero per ยงD.3 (use
/// [`crate::annex_d::still_image_tr`] to derive it from a sub-image
/// index).
pub fn write_picture_header_full(bw: &mut BitWriter, fmt: SourceFormat, tr: u8, hi_res_off: bool) {
    write_picture_header_ptype(bw, fmt, tr, hi_res_off, Ptype::default());
}

/// Emit the 32-bit picture header (ยง4.2.1) with explicit `HI_RES` and the
/// three ยง4.2.1.3 display-control flags ([`Ptype`]). This is the most
/// general picture-header writer; [`write_picture_header`] and
/// [`write_picture_header_full`] are thin wrappers that pass
/// [`Ptype::default()`] (all flags off).
pub fn write_picture_header_ptype(
    bw: &mut BitWriter,
    fmt: SourceFormat,
    tr: u8,
    hi_res_off: bool,
    ptype: Ptype,
) {
    bw.write_u32(0x00010, 20); // PSC
    bw.write_u32(tr as u32, 5); // TR
                                // PTYPE โ€” six single-bit flags, MSB first.
                                // bit1 split-screen indicator (ยง4.2.1.3)
    bw.write_u32(ptype.split_screen as u32, 1);
    // bit2 document-camera indicator (ยง4.2.1.3)
    bw.write_u32(ptype.document_camera as u32, 1);
    // bit3 freeze-picture release (ยง4.2.1.3 / ยง4.3.3)
    bw.write_u32(ptype.freeze_picture_release as u32, 1);
    // bit4 source format
    let fmt_bit = match fmt {
        SourceFormat::Qcif => 0,
        SourceFormat::Cif => 1,
    };
    bw.write_u32(fmt_bit, 1);
    // bit5 HI_RES โ€” "1 = off, 0 = on (Annex D still-image sub-image)".
    bw.write_u32(if hi_res_off { 1 } else { 0 }, 1);
    // bit6 spare โ€” per ยง4.1 unused bits are set to 1.
    bw.write_u32(1, 1);
    // PEI = 0 โ€” no PSPARE.
    bw.write_u32(0, 1);
}

/// Emit a GOB header (ยง4.2.2) with the given GN and GQUANT.
pub fn write_gob_header(bw: &mut BitWriter, gn: u8, gquant: u32) {
    debug_assert!((1..=12).contains(&gn));
    debug_assert!((1..=31).contains(&gquant));
    bw.write_u32(0x0001, 16); // GBSC
    bw.write_u32(gn as u32, 4);
    bw.write_u32(gquant, 5);
    // GEI = 0 โ€” no GSPARE.
    bw.write_u32(0, 1);
}

fn gob_origin_luma(fmt: SourceFormat, gn: u8) -> (usize, usize) {
    match fmt {
        SourceFormat::Cif => crate::gob::cif_gob_origin_luma(gn),
        SourceFormat::Qcif => crate::gob::qcif_gob_origin_luma(gn),
    }
}

/// Encode the 33 INTRA macroblocks of one GOB and write their pel-domain
/// reconstruction into `recon`.
#[allow(clippy::too_many_arguments)]
fn encode_gob_intra(
    bw: &mut BitWriter,
    y: &[u8],
    y_stride: usize,
    cb: &[u8],
    cb_stride: usize,
    cr: &[u8],
    cr_stride: usize,
    gob_x: usize,
    gob_y: usize,
    quant: u32,
    recon: &mut Picture,
) {
    let mut prev_mba: u8 = 0;
    for mba in 1u8..=33 {
        let diff = mba - prev_mba;
        let (bits, code) = encode_mba_diff(diff);
        bw.write_u32(code, bits as u32);
        // MTYPE = INTRA (4-bit 0001). No MQUANT override โ€” we reuse
        // GQUANT for every MB.
        bw.write_u32(MTYPE_INTRA.1, MTYPE_INTRA.0 as u32);

        let mb_col = (mba - 1) as usize % 11;
        let mb_row = (mba - 1) as usize / 11;
        let luma_x = gob_x + mb_col * 16;
        let luma_y = gob_y + mb_row * 16;
        encode_intra_mb_blocks(
            bw, y, y_stride, cb, cb_stride, cr, cr_stride, luma_x, luma_y, quant, recon,
        );

        prev_mba = mba;
    }
}

/// Encode the macroblocks of one GOB as INTER. For each MB we:
///
/// 1. Run integer-pel motion estimation (diamond search ยฑ15 pels) against
///    `reference` to find the best 16x16 luma predictor.
/// 2. Build the chroma predictor at the corresponding half-MV (ยง3.2.2:
///    luma โ†’ chroma MV is halved with truncation toward zero).
/// 3. Forward-DCT + quantise the residual.
/// 4. Decide MTYPE:
///    * `Inter` (no MC) when the best MV is `(0,0)` and CBP != 0.
///    * `Inter+MC` with CBP+TCOEFF when the best MV is non-zero and any
///      block carries residual.
///    * `Inter+MC` MC-only (no CBP/TCOEFF) when the MV is non-zero and the
///      residual quantises to all zeros.
///    * Skip (absorbed into next MBA diff) when MV is zero and CBP would be
///      zero.
/// 5. Emit MBA diff, MTYPE, MVD (if MC), CBP (if present), then coded blocks.
///
/// MV predictor for MVD (ยง4.2.3.4): the previous MB's MV, reset to zero
/// at GOB start, on MBs 1/12/23, on MBA discontinuities, and when the
/// previous MB was not MC-coded.
///
/// Skipped MBs are not transmitted but their reconstructed pixels (= the
/// reference at the same position, i.e. zero-MV copy per the H.261 decoder
/// behaviour for skipped MBs in P-pictures) are still written into `recon`.
#[allow(clippy::too_many_arguments)]
fn encode_gob_inter(
    bw: &mut BitWriter,
    y: &[u8],
    y_stride: usize,
    cb: &[u8],
    cb_stride: usize,
    cr: &[u8],
    cr_stride: usize,
    gob_x: usize,
    gob_y: usize,
    quant: u32,
    reference: &Picture,
    recon: &mut Picture,
    forced_intra: &[bool; 33],
) {
    let mut prev_mba: u8 = 0;
    // MV predictor state per ยง4.2.3.4 (reset at GOB start).
    let mut pred_mv: (i32, i32) = (0, 0);
    let mut prev_was_mc = false;
    // Per-GOB rate controller (ยง4.2.3.3 MQUANT). Disabled by setting the
    // env var to "1" โ€” useful for A/B benchmarks against the r13 baseline.
    let rate_ctrl_enabled = std::env::var("OXIDEAV_H261_NO_MQUANT").is_err();
    // Target ~50 bits per MB at QUANT=8 (โ‰ˆ 1.6 kbit per QCIF GOB). The
    // controller's slack (see `MqRateCtrl::desired`) is 16x this target,
    // so we only nudge QP up after several consecutive expensive MBs.
    // The intent is to catch a hot patch in a GOB without coarsening the
    // picture as a whole โ€” which preserves PSNR while still trimming
    // bytes on outlier MBs.
    let target_per_mb = 32 + 4 * quant;
    let mut rc = MqRateCtrl::new(quant, target_per_mb);

    for mba in 1u8..=33 {
        let mb_col = (mba - 1) as usize % 11;
        let mb_row = (mba - 1) as usize / 11;
        let luma_x = gob_x + mb_col * 16;
        let luma_y = gob_y + mb_row * 16;
        let bits_before_mb = bw.bit_position();

        // ---- 1. Source pels.
        let mut blocks_pels: [[u8; 64]; 6] = [[0u8; 64]; 6];
        for (b, (sub_x, sub_y)) in [(0, 0), (8, 0), (0, 8), (8, 8)].iter().enumerate() {
            extract_block(
                y,
                y_stride,
                luma_x + *sub_x,
                luma_y + *sub_y,
                &mut blocks_pels[b],
            );
        }
        let cx = luma_x / 2;
        let cy = luma_y / 2;
        extract_block(cb, cb_stride, cx, cy, &mut blocks_pels[4]);
        extract_block(cr, cr_stride, cx, cy, &mut blocks_pels[5]);

        // ---- 1b. ยง3.4 forced updating.
        //
        // "For control of accumulation of inverse transform mismatch error
        // a macroblock should be forcibly updated at least once per every
        // 132 times it is transmitted." (ยง3.4). When the per-MB scheduler
        // (see `H261Encoder`) marks this MB due for a forced update, we
        // emit it in INTRA mode โ€” bypassing the INTER/MC mode decision
        // entirely โ€” so the decoder discards its prediction history for
        // this MB and the mismatch error cannot accumulate further.
        //
        // An INTRA MB in a P-picture is never motion-compensated, so the
        // ยง4.2.3.4 MVD predictor is reset (`pred_mv = 0`, `prev_was_mc =
        // false`) exactly as the spec treats any non-MC macroblock.
        if forced_intra[(mba - 1) as usize] {
            let diff = mba - prev_mba;
            let (bits, code) = encode_mba_diff(diff);
            bw.write_u32(code, bits as u32);
            // MTYPE = INTRA (4-bit 0001). No MQUANT override โ€” reuse the
            // GOB QUANT in effect.
            bw.write_u32(MTYPE_INTRA.1, MTYPE_INTRA.0 as u32);
            encode_intra_mb_blocks(
                bw, y, y_stride, cb, cb_stride, cr, cr_stride, luma_x, luma_y, quant, recon,
            );
            prev_mba = mba;
            pred_mv = (0, 0);
            prev_was_mc = false;
            let bits_after_mb = bw.bit_position();
            rc.account(bits_after_mb - bits_before_mb);
            continue;
        }

        // ---- 2. Motion estimation on luma (16ร—16). Returns best (mvx, mvy).
        //
        // No row-boundary constraint is needed: the ยง4.2.3.4 predictor
        // reset on MBA 12 and 23 is honoured symmetrically by the encoder's
        // MVD derivation (see step 5) and by the decoder, so a non-zero MV
        // at MBs 11 / 22 reconstructs identically on both sides.
        let (mvx, mvy) = motion_estimate_luma(y, y_stride, reference, luma_x, luma_y);

        // ---- 3. Build full predictor at (mvx, mvy).
        let mut blocks_pred: [[u8; 64]; 6] = [[0u8; 64]; 6];
        // Luma โ€” at integer-pel offsets within the reference plane.
        for (b, (sub_x, sub_y)) in [(0, 0), (8, 0), (0, 8), (8, 8)].iter().enumerate() {
            extract_block_mv(
                &reference.y,
                reference.y_stride,
                luma_x + *sub_x,
                luma_y + *sub_y,
                mvx,
                mvy,
                &mut blocks_pred[b],
            );
        }
        // Chroma โ€” at half-MV (ยง3.2.2: truncate toward zero).
        let cmvx = mvx / 2;
        let cmvy = mvy / 2;
        extract_block_mv(
            &reference.cb,
            reference.c_stride,
            cx,
            cy,
            cmvx,
            cmvy,
            &mut blocks_pred[4],
        );
        extract_block_mv(
            &reference.cr,
            reference.c_stride,
            cx,
            cy,
            cmvx,
            cmvy,
            &mut blocks_pred[5],
        );

        // ---- 4. Residual + quantisation, both unfiltered and filtered.
        //
        // ยง3.2.3: the loop filter operates on the predictor before the
        // residual is added. Run the FDCT/quant pipeline twice โ€” once on
        // the raw predictor (`blocks_pred`) and once on the filtered one
        // (`blocks_pred_fil`) โ€” and pick whichever variant minimises the
        // total bit-cost (MTYPE + MVD + CBP + TCOEFF). The unfiltered
        // q_levels/recon are reused as-is from r12; the filtered branch
        // mirrors the same code path through `quantise_residual`.
        //
        // QUANT used here is `rc.quant_in_effect`, which equals GQUANT at
        // GOB start and otherwise the most recently emitted MQUANT. If the
        // rate controller wants to switch QP and we land in an MQUANT-
        // bearing mode below we re-quantise at the new value before emit.
        let cur_q = rc.quant_in_effect;
        let (cbp_nf, mut q_levels_nf, mut recon_nf, resid_bits_nf) =
            quantise_residual(&blocks_pels, &blocks_pred, cur_q);

        let mut blocks_pred_fil: [[u8; 64]; 6] = [[0u8; 64]; 6];
        for b in 0..6 {
            blocks_pred_fil[b] = apply_loop_filter_block(&blocks_pred[b]);
        }
        let (cbp_fil, mut q_levels_fil, mut recon_fil, resid_bits_fil) =
            quantise_residual(&blocks_pels, &blocks_pred_fil, cur_q);

        // ---- 5. Mode decision.
        //
        // Compute the bit-cost of every viable mode. The cheapest one wins.
        // Modes are (MTYPE bits, MVD bits when MC, CBP bits, TCOEFF bits).
        // We only need approximate costs since the FIL/no-FIL branches use
        // the same residual-bit estimator (so the comparison is consistent).
        //
        // Notes:
        //   * MV(0,0) without filter and without CBP = "skip" โ€” absorbed
        //     into the next MBA diff and emits zero MB-bits. We bias the
        //     skip cost downward by a few bits to prefer it on truly idle
        //     content (skips also save the MBA diff length on the next MB).
        //   * Per Table 2 Note 2 the FIL+MC-only mode is legal even with
        //     mv = (0,0) (filter applied to a non-MC MB).

        let mv_is_zero = mvx == 0 && mvy == 0;
        let mv_l1 = (mvx.abs() + mvy.abs()) as u32;
        // CBP VLC length is between 3 and 9 bits; treat as an average 6 for
        // the estimator. The real VLC is emitted unconditionally below.
        let cbp_vlc_bits = |c: u8| -> u32 {
            if c == 0 {
                0
            } else {
                6
            }
        };
        // MVD VLC length grows with |d|; use 2*|d|+1 as a coarse upper bound.
        let mvd_bits = |d: i32| -> u32 { (d.unsigned_abs() * 2).saturating_add(1) };
        let mvd_total = if mv_is_zero {
            0
        } else {
            mvd_bits(mvx) + mvd_bits(mvy)
        };

        // Candidate costs (in bits).
        const COST_INF: u32 = u32::MAX / 4;
        let mut best_cost = COST_INF;
        // 0 = Skip, 1 = Inter, 2 = MC-only, 3 = MC+CBP, 4 = MC+FIL-only,
        // 5 = MC+FIL+CBP.
        let mut best_mode: u8 = 0;

        // Skip: only if mv is zero, no residual, AND filtered branch also
        // wouldn't help. The skip MB writes the unfiltered predictor into
        // recon โ€” that's also what the decoder does.
        if mv_is_zero && cbp_nf == 0 {
            best_cost = 0; // free
            best_mode = 0;
        }
        // Inter (no MC, no FIL).
        if mv_is_zero && cbp_nf != 0 {
            let c = MTYPE_INTER.0 as u32 + cbp_vlc_bits(cbp_nf) + resid_bits_nf;
            if c < best_cost {
                best_cost = c;
                best_mode = 1;
            }
        }
        // MC-only (no FIL). Requires non-zero MV (else this is a skip) and
        // cbp_nf == 0. The 9-bit MTYPE is the largest in Table 2.
        if !mv_is_zero && cbp_nf == 0 {
            let c = MTYPE_INTER_MC_ONLY.0 as u32 + mvd_total;
            if c < best_cost {
                best_cost = c;
                best_mode = 2;
            }
        }
        // MC + CBP (no FIL). Requires non-zero MV.
        if !mv_is_zero && cbp_nf != 0 {
            let c = MTYPE_INTER_MC_CBP.0 as u32 + mvd_total + cbp_vlc_bits(cbp_nf) + resid_bits_nf;
            if c < best_cost {
                best_cost = c;
                best_mode = 3;
            }
        }
        // MC + FIL only. Per Table 2 Note 2 this is legal with mv=(0,0).
        // The `OXIDEAV_H261_NO_FIL` env var disables FIL globally; useful
        // for A/B benchmarks against the r12 baseline.
        let allow_fil = std::env::var("OXIDEAV_H261_NO_FIL").is_err();
        if allow_fil && cbp_fil == 0 {
            let c = MTYPE_INTER_MC_FIL_ONLY.0 as u32 + mvd_total;
            if c < best_cost {
                best_cost = c;
                best_mode = 4;
            }
        }
        // MC + FIL + CBP. Always legal.
        if allow_fil && cbp_fil != 0 {
            let c = MTYPE_INTER_MC_FIL_CBP.0 as u32
                + mvd_total
                + cbp_vlc_bits(cbp_fil)
                + resid_bits_fil;
            if c < best_cost {
                best_cost = c;
                best_mode = 5;
            }
        }

        // Skip path โ€” no MTYPE/CBP/etc emitted, just absorb into next MBA.
        if best_mode == 0 {
            pred_mv = (0, 0);
            prev_was_mc = false;
            for b in 0..6 {
                write_block_to_picture(recon, b, luma_x, luma_y, &recon_nf[b]);
            }
            // Suppress unused-variable warnings on cost.
            let _ = (best_cost, mv_l1);
            // No bits emitted for this MB.
            continue;
        }

        // ---- 6. Rate-controller MQUANT switch (ยง4.2.3.3).
        //
        // Modes 1, 3, 5 carry CBP+TCOEFF and therefore an MQUANT-bearing
        // MTYPE variant exists. If the controller wants a different QP
        // than `rc.quant_in_effect`, re-quantise the relevant residual
        // (filtered or not) at the new QP and switch to the MQUANT
        // variant. We do NOT re-do the full mode decision because the
        // delta is small (ยฑ1 step) and re-running mode-decision per QP
        // would double the per-MB cost โ€” the controller's nudge is
        // designed to be safe at the chosen mode.
        let mode_supports_mquant = matches!(best_mode, 1 | 3 | 5);
        let desired_q = if rate_ctrl_enabled {
            rc.desired((mba - 1) as u32)
        } else {
            cur_q
        };
        let mut emit_q = cur_q;
        let mut emit_mquant = false;
        if mode_supports_mquant && desired_q != cur_q {
            // Re-quantise at desired_q. We re-derive `(cbp, q_levels,
            // recon, _)` for whichever predictor (filtered/not) the chosen
            // mode uses. If re-quantisation drops CBP to zero we fall
            // back to the original quant โ€” emitting CBP=0 with a CBP-
            // bearing MTYPE is forbidden (Table 4 has no entry for 0).
            let (pred_blocks, _is_fil) = match best_mode {
                1 => (&blocks_pred, false),
                3 => (&blocks_pred, false),
                5 => (&blocks_pred_fil, true),
                _ => unreachable!(),
            };
            let (new_cbp, new_levels, new_recon, _new_bits) =
                quantise_residual(&blocks_pels, pred_blocks, desired_q);
            if new_cbp != 0 {
                emit_q = desired_q;
                emit_mquant = true;
                if matches!(best_mode, 1 | 3) {
                    // Patch the no-FIL stash so the emit code below uses
                    // the new quantisation.
                    q_levels_nf = new_levels;
                    recon_nf = new_recon;
                    // CBP can have changed too (rare with ยฑ1 nudge but
                    // possible). Stash it via a mutable shadow that the
                    // emit path reads from.
                    let _ = new_cbp; // We reuse the original cbp_nf below;
                                     // see special handling at emit.
                } else {
                    q_levels_fil = new_levels;
                    recon_fil = new_recon;
                }
                // Update the CBP for the emit path. We can't re-bind the
                // outer `cbp_nf`/`cbp_fil` in this scope; we use a
                // dedicated `cbp_emit` for the actual write (see below).
            }
        }
        // Choose CBP for the emit path. When MQUANT switching, the
        // re-quantisation may have changed CBP โ€” but since we only switch
        // when `new_cbp != 0` AND we kept the original mode decision, we
        // re-derive CBP from the (possibly patched) q_levels.
        let cbp_for_emit = if emit_mquant {
            let mut c: u8 = 0;
            for b in 0..6 {
                let levels = match best_mode {
                    1 | 3 => &q_levels_nf[b],
                    5 => &q_levels_fil[b],
                    _ => unreachable!(),
                };
                if levels.iter().any(|&l| l != 0) {
                    c |= 1 << (5 - b);
                }
            }
            c
        } else {
            match best_mode {
                1 | 3 => cbp_nf,
                5 => cbp_fil,
                _ => 0,
            }
        };
        // It is theoretically possible (rare ยฑ1 nudge into a coarser QP)
        // that the new CBP becomes 0 even though we tested above. Guard:
        // fall back to the no-MQUANT path in that case.
        let (emit_q, emit_mquant) = if matches!(best_mode, 1 | 3 | 5) && cbp_for_emit == 0 {
            // No CBP โ€” can't use a CBP+TCOEFF MTYPE. Disable MQUANT for this MB.
            (cur_q, false)
        } else {
            (emit_q, emit_mquant)
        };

        // Emit MBA diff (jumps over any preceding skipped MBs).
        let diff = mba - prev_mba;
        let (bits, code) = encode_mba_diff(diff);
        bw.write_u32(code, bits as u32);

        // ยง4.2.3.4 MVD predictor reset rules โ€” full spec compliance:
        //   * MBs 1, 12, 23 (start of each MB row in a GOB),
        //   * MBA difference != 1 (skipped MB(s) preceded this one),
        //   * previous MB not MC coded.
        let mvd_reset = matches!(mba, 1 | 12 | 23) || diff != 1 || !prev_was_mc;
        let pred_for_mvd = if mvd_reset { (0, 0) } else { pred_mv };

        match best_mode {
            1 => {
                // INTER (no MC, no FIL). CBP != 0.
                debug_assert_ne!(cbp_for_emit, 0);
                if emit_mquant {
                    bw.write_u32(MTYPE_INTER_MQUANT.1, MTYPE_INTER_MQUANT.0 as u32);
                    bw.write_u32(emit_q, 5);
                } else {
                    bw.write_u32(MTYPE_INTER.1, MTYPE_INTER.0 as u32);
                }
                let (cbits, ccode) = encode_cbp(cbp_for_emit);
                bw.write_u32(ccode, cbits as u32);
                for b in 0..6 {
                    if cbp_for_emit & (1 << (5 - b)) != 0 {
                        emit_inter_block_levels(bw, &q_levels_nf[b]);
                    }
                    write_block_to_picture(recon, b, luma_x, luma_y, &recon_nf[b]);
                }
                pred_mv = (0, 0);
                prev_was_mc = false;
            }
            2 => {
                // INTER+MC (no FIL), MC-only (no CBP/TCOEFF). MQUANT not allowed.
                bw.write_u32(MTYPE_INTER_MC_ONLY.1, MTYPE_INTER_MC_ONLY.0 as u32);
                let dx = mvx - pred_for_mvd.0;
                let dy = mvy - pred_for_mvd.1;
                let (xb, xc) = encode_mvd(dx);
                bw.write_u32(xc, xb as u32);
                let (yb, yc) = encode_mvd(dy);
                bw.write_u32(yc, yb as u32);
                for b in 0..6 {
                    write_block_to_picture(recon, b, luma_x, luma_y, &recon_nf[b]);
                }
                pred_mv = (mvx, mvy);
                prev_was_mc = true;
            }
            3 => {
                // INTER+MC (no FIL) with CBP + TCOEFF (and optionally MQUANT).
                if emit_mquant {
                    bw.write_u32(
                        MTYPE_INTER_MC_CBP_MQUANT.1,
                        MTYPE_INTER_MC_CBP_MQUANT.0 as u32,
                    );
                    bw.write_u32(emit_q, 5);
                } else {
                    bw.write_u32(MTYPE_INTER_MC_CBP.1, MTYPE_INTER_MC_CBP.0 as u32);
                }
                let dx = mvx - pred_for_mvd.0;
                let dy = mvy - pred_for_mvd.1;
                let (xb, xc) = encode_mvd(dx);
                bw.write_u32(xc, xb as u32);
                let (yb, yc) = encode_mvd(dy);
                bw.write_u32(yc, yb as u32);
                let (cbits, ccode) = encode_cbp(cbp_for_emit);
                bw.write_u32(ccode, cbits as u32);
                for b in 0..6 {
                    if cbp_for_emit & (1 << (5 - b)) != 0 {
                        emit_inter_block_levels(bw, &q_levels_nf[b]);
                    }
                    write_block_to_picture(recon, b, luma_x, luma_y, &recon_nf[b]);
                }
                pred_mv = (mvx, mvy);
                prev_was_mc = true;
            }
            4 => {
                // INTER+MC+FIL, MC-only (no CBP/TCOEFF). 3-bit MTYPE. MQUANT not allowed.
                bw.write_u32(MTYPE_INTER_MC_FIL_ONLY.1, MTYPE_INTER_MC_FIL_ONLY.0 as u32);
                let dx = mvx - pred_for_mvd.0;
                let dy = mvy - pred_for_mvd.1;
                let (xb, xc) = encode_mvd(dx);
                bw.write_u32(xc, xb as u32);
                let (yb, yc) = encode_mvd(dy);
                bw.write_u32(yc, yb as u32);
                for b in 0..6 {
                    write_block_to_picture(recon, b, luma_x, luma_y, &recon_fil[b]);
                }
                pred_mv = (mvx, mvy);
                prev_was_mc = true;
            }
            5 => {
                // INTER+MC+FIL with CBP + TCOEFF (and optionally MQUANT). 2-bit MTYPE.
                if emit_mquant {
                    bw.write_u32(
                        MTYPE_INTER_MC_FIL_CBP_MQUANT.1,
                        MTYPE_INTER_MC_FIL_CBP_MQUANT.0 as u32,
                    );
                    bw.write_u32(emit_q, 5);
                } else {
                    bw.write_u32(MTYPE_INTER_MC_FIL_CBP.1, MTYPE_INTER_MC_FIL_CBP.0 as u32);
                }
                let dx = mvx - pred_for_mvd.0;
                let dy = mvy - pred_for_mvd.1;
                let (xb, xc) = encode_mvd(dx);
                bw.write_u32(xc, xb as u32);
                let (yb, yc) = encode_mvd(dy);
                bw.write_u32(yc, yb as u32);
                let (cbits, ccode) = encode_cbp(cbp_for_emit);
                bw.write_u32(ccode, cbits as u32);
                for b in 0..6 {
                    if cbp_for_emit & (1 << (5 - b)) != 0 {
                        emit_inter_block_levels(bw, &q_levels_fil[b]);
                    }
                    write_block_to_picture(recon, b, luma_x, luma_y, &recon_fil[b]);
                }
                pred_mv = (mvx, mvy);
                prev_was_mc = true;
            }
            _ => unreachable!("bad best_mode {best_mode}"),
        }

        prev_mba = mba;
        // Rate-controller bookkeeping. Update `quant_in_effect` if MQUANT
        // was emitted, and account for the MB's bit cost.
        if emit_mquant {
            rc.commit_quant(emit_q);
        }
        let bits_after_mb = bw.bit_position();
        rc.account(bits_after_mb - bits_before_mb);
    }
}

/// Sum of absolute differences between a 16ร—16 source block at `(sx,sy)` in
/// `src` and a 16ร—16 reference block at `(sx+mvx, sy+mvy)` in `reference.y`.
/// Out-of-bounds reference samples are clamped to the nearest edge.
fn sad16x16(
    src: &[u8],
    src_stride: usize,
    reference: &Picture,
    sx: usize,
    sy: usize,
    mvx: i32,
    mvy: i32,
) -> u32 {
    let ref_w = reference.y_stride as i32;
    let ref_h = (reference.y.len() / reference.y_stride) as i32;
    let mut sad: u32 = 0;
    for j in 0..16i32 {
        let ry = (sy as i32 + j + mvy).clamp(0, ref_h - 1) as usize;
        let sy_row = sy + j as usize;
        for i in 0..16i32 {
            let rx = (sx as i32 + i + mvx).clamp(0, ref_w - 1) as usize;
            let s = src[sy_row * src_stride + sx + i as usize] as i32;
            let r = reference.y[ry * reference.y_stride + rx] as i32;
            sad += (s - r).unsigned_abs();
        }
    }
    sad
}

/// Integer-pel motion estimation for one luma MB. Returns the best
/// `(mvx, mvy)` in `-15..=15` pels using a SAD criterion.
///
/// Search strategy: three-pass spiral/diamond refinement.
///
/// 1. **Spiral scan** โ€” samples the full ยฑ15 search window in concentric
///    rings (radius 0 โ†’ 15), evaluating the ring-boundary points only. Stops
///    early once the best cost falls below an intra-skip threshold or once
///    two consecutive rings produce no improvement. This typically checks only
///    the inner 2โ€“3 rings for smooth or near-static content (huge saving) yet
///    always falls through to the full ring for complex motion.
///
/// 2. **Compact-diamond refinement** โ€” after the spiral winner is found,
///    evaluates the 8-connected neighbourhood of that MV to catch rounding
///    edges around the ring boundary (avoids missing the true minimum by
///    one pel).
///
/// 3. **Full inner-ring fallback** โ€” if the spiral winner is still at (0,0)
///    with non-zero SAD, double-checks with the classic 4-point diamond to
///    confirm no short MV beats it before returning.
///
/// A small `ฮปยท(|mvx|+|mvy|)` MV-cost penalty biases ties toward the shorter
/// MV, which shrinks the MVD VLC code and promotes skippable MBs.
fn motion_estimate_luma(
    src: &[u8],
    src_stride: usize,
    reference: &Picture,
    sx: usize,
    sy: usize,
) -> (i32, i32) {
    // Lambda for MV-cost penalty. Must beat (0,0) by at least its L1 norm.
    let mv_cost = |mvx: i32, mvy: i32| -> u32 { ((mvx.abs() + mvy.abs()) as u32) * 2 };
    let cost_at = |mvx: i32, mvy: i32| -> u32 {
        sad16x16(src, src_stride, reference, sx, sy, mvx, mvy).saturating_add(mv_cost(mvx, mvy))
    };

    let mut best_mv = (0i32, 0i32);
    let mut best_cost = cost_at(0, 0);

    // Early-exit: perfect predictor.
    if best_cost == 0 {
        return (0, 0);
    }

    // Spiral scan: evaluate ring-boundary pels in concentric squares,
    // innermost first. Each ring is the set of (dx,dy) with
    // max(|dx|,|dy|) == r. We stop after two consecutive rings with no
    // improvement (content is smooth / no large-displacement motion) or
    // after all rings are exhausted.
    let mut no_improve_rings: u32 = 0;
    for r in 1i32..=ME_SEARCH_RADIUS {
        let ring_start_cost = best_cost;
        // Walk the perimeter of the square at Manhattan radius `r`.
        // Top row, bottom row, left/right columns (excluding corners already
        // covered) โ€” 8r points per ring, all at max(|dx|,|dy|) == r.
        // Top and bottom rows: dy = ยฑr, dx = -r..=r.
        for dx in -r..=r {
            for &dy in &[-r, r] {
                if dx.abs() <= ME_SEARCH_RADIUS && dy.abs() <= ME_SEARCH_RADIUS {
                    let c = cost_at(dx, dy);
                    if c < best_cost {
                        best_cost = c;
                        best_mv = (dx, dy);
                    }
                }
            }
        }
        // Left and right columns: dx = ยฑr, dy = -(r-1)..=(r-1).
        for dy in -(r - 1)..=(r - 1) {
            for &dx in &[-r, r] {
                if dx.abs() <= ME_SEARCH_RADIUS && dy.abs() <= ME_SEARCH_RADIUS {
                    let c = cost_at(dx, dy);
                    if c < best_cost {
                        best_cost = c;
                        best_mv = (dx, dy);
                    }
                }
            }
        }
        if best_cost < ring_start_cost {
            no_improve_rings = 0;
        } else {
            no_improve_rings += 1;
            if no_improve_rings >= 2 {
                break; // Two consecutive rings with no gain โ€” stop early.
            }
        }
    }

    // Compact-diamond refinement around the spiral winner: check the
    // 8-connected neighbourhood to catch any missed peak at ring edges.
    let (wx, wy) = best_mv;
    for dy in -1i32..=1 {
        for dx in -1i32..=1 {
            if dx == 0 && dy == 0 {
                continue;
            }
            let nx = (wx + dx).clamp(-ME_SEARCH_RADIUS, ME_SEARCH_RADIUS);
            let ny = (wy + dy).clamp(-ME_SEARCH_RADIUS, ME_SEARCH_RADIUS);
            let c = cost_at(nx, ny);
            if c < best_cost {
                best_cost = c;
                best_mv = (nx, ny);
            }
        }
    }

    best_mv
}

/// Apply the H.261 loop filter (ยง3.2.3) to an 8x8 predictor block.
///
/// Separable 1/4 - 1/2 - 1/4 horizontal + vertical filter. At block edges
/// (i โˆˆ {0, 7} or j โˆˆ {0, 7}) the spec replaces the 1/4-1/2-1/4 taps with
/// 0-1-0 (i.e. the edge pel passes through unchanged). Round half-up to
/// nearest 8-bit integer per ยง3.2.3 ("values whose fractional part is one
/// half are rounded up").
///
/// This MUST match the decoder's `apply_loop_filter` byte-for-byte for
/// local-recon to stay tight with self-decode (any spec-conformant decoder
/// derives the same recon).
fn apply_loop_filter_block(src: &[u8; 64]) -> [u8; 64] {
    // Horizontal pass โ€” store as i32 to keep precision into the vertical pass.
    let mut h = [0i32; 64];
    for j in 0..8 {
        for i in 0..8 {
            let v = if i == 0 || i == 7 {
                src[j * 8 + i] as i32
            } else {
                let a = src[j * 8 + i - 1] as i32;
                let b = src[j * 8 + i] as i32;
                let c = src[j * 8 + i + 1] as i32;
                // (a + 2b + c + 2) >> 2 โ€” round-half-up to 8-bit integer.
                (a + 2 * b + c + 2) >> 2
            };
            h[j * 8 + i] = v;
        }
    }
    // Vertical pass.
    let mut out = [0u8; 64];
    for i in 0..8 {
        for j in 0..8 {
            let v = if j == 0 || j == 7 {
                h[j * 8 + i]
            } else {
                let a = h[(j - 1) * 8 + i];
                let b = h[j * 8 + i];
                let c = h[(j + 1) * 8 + i];
                (a + 2 * b + c + 2) >> 2
            };
            out[j * 8 + i] = v.clamp(0, 255) as u8;
        }
    }
    out
}

/// Compute the per-MB residual / quantised coefficients / local-recon for
/// the given 6-block predictor. Returns `(cbp, q_levels, recon_blocks,
/// total_residual_bits)`. The `total_residual_bits` is a cheap *estimate* of
/// how many bits the TCOEFF VLCs would consume โ€” used by the FIL mode
/// decision to compare with-vs-without filter without actually emitting
/// duplicate bitstream bytes.
fn quantise_residual(
    blocks_pels: &[[u8; 64]; 6],
    blocks_pred: &[[u8; 64]; 6],
    quant: u32,
) -> (u8, [[i32; 64]; 6], [[u8; 64]; 6], u32) {
    let mut cbp: u8 = 0;
    let mut q_levels: [[i32; 64]; 6] = [[0i32; 64]; 6];
    let mut recon_blocks: [[u8; 64]; 6] = [[0u8; 64]; 6];
    let mut bit_estimate: u32 = 0;

    for b in 0..6 {
        let mut resid = [0i32; 64];
        for i in 0..64 {
            resid[i] = blocks_pels[b][i] as i32 - blocks_pred[b][i] as i32;
        }
        let mut coeffs = [0i32; 64];
        fdct_signed(&resid, &mut coeffs);
        let mut levels = [0i32; 64];
        let mut any_nonzero = false;
        for i in 0..64 {
            let l = quant_ac(coeffs[i], quant);
            levels[i] = l;
            if l != 0 {
                any_nonzero = true;
            }
        }
        q_levels[b] = levels;

        if any_nonzero {
            cbp |= 1 << (5 - b);
            // Reconstruct: dequant + IDCT + add predictor, clip.
            let mut dequant = [0i32; 64];
            for i in 0..64 {
                dequant[i] = crate::block::dequant_ac(levels[i], quant);
            }
            let mut residual = [0i32; 64];
            idct_signed(&dequant, &mut residual);
            for i in 0..64 {
                let v = blocks_pred[b][i] as i32 + residual[i];
                recon_blocks[b][i] = v.clamp(0, 255) as u8;
            }
            // Cheap residual-bit estimate: 4 bits per non-zero level + 2 EOB bits.
            // This is rough but consistent: it ranks "more non-zero levels =
            // more bits", which is what the FIL decision needs. The actual
            // VLC will use this only as a tie-breaker between filtered and
            // unfiltered; both branches use the same estimator.
            let mut nz: u32 = 0;
            for &l in levels.iter() {
                if l != 0 {
                    nz += 1;
                }
            }
            bit_estimate += nz * 4 + 2;
        } else {
            recon_blocks[b] = blocks_pred[b];
        }
    }

    (cbp, q_levels, recon_blocks, bit_estimate)
}

/// Extract an 8x8 block from `plane` at `(x+mvx, y+mvy)`. Out-of-bounds
/// samples are clamped to the nearest edge โ€” matching the decoder's
/// `copy_block_integer` so local recon and decoded recon stay byte-identical.
#[allow(clippy::too_many_arguments)]
fn extract_block_mv(
    plane: &[u8],
    stride: usize,
    x: usize,
    y: usize,
    mvx: i32,
    mvy: i32,
    out: &mut [u8; 64],
) {
    let plane_w = stride as i32;
    let plane_h = (plane.len() / stride) as i32;
    for j in 0..8 {
        for i in 0..8 {
            let sx = (x as i32 + i + mvx).clamp(0, plane_w - 1) as usize;
            let sy = (y as i32 + j + mvy).clamp(0, plane_h - 1) as usize;
            out[(j as usize) * 8 + i as usize] = plane[sy * stride + sx];
        }
    }
}

/// Extract the 8x8 pel block at `(bx, by)` from `plane` and run the
/// forward DCT + per-block intra encode. Also writes the reconstructed
/// block into `recon`.
#[allow(clippy::too_many_arguments)]
fn encode_intra_mb_blocks(
    bw: &mut BitWriter,
    y: &[u8],
    y_stride: usize,
    cb: &[u8],
    cb_stride: usize,
    cr: &[u8],
    cr_stride: usize,
    luma_x: usize,
    luma_y: usize,
    quant: u32,
    recon: &mut Picture,
) {
    // Y1..Y4
    for (b, (sub_x, sub_y)) in [(0, 0), (8, 0), (0, 8), (8, 8)].iter().enumerate() {
        let mut pels = [0u8; 64];
        extract_block(y, y_stride, luma_x + *sub_x, luma_y + *sub_y, &mut pels);
        let mut out = [0u8; 64];
        encode_intra_block(bw, &pels, quant, &mut out);
        write_block_to_picture(recon, b, luma_x, luma_y, &out);
    }
    let cx = luma_x / 2;
    let cy = luma_y / 2;
    let mut cb_pels = [0u8; 64];
    extract_block(cb, cb_stride, cx, cy, &mut cb_pels);
    let mut cb_out = [0u8; 64];
    encode_intra_block(bw, &cb_pels, quant, &mut cb_out);
    write_block_to_picture(recon, 4, luma_x, luma_y, &cb_out);
    let mut cr_pels = [0u8; 64];
    extract_block(cr, cr_stride, cx, cy, &mut cr_pels);
    let mut cr_out = [0u8; 64];
    encode_intra_block(bw, &cr_pels, quant, &mut cr_out);
    write_block_to_picture(recon, 5, luma_x, luma_y, &cr_out);
}

fn extract_block(plane: &[u8], stride: usize, x: usize, y: usize, out: &mut [u8; 64]) {
    for j in 0..8 {
        for i in 0..8 {
            let px = (y + j) * stride + (x + i);
            out[j * 8 + i] = plane.get(px).copied().unwrap_or(0);
        }
    }
}

/// Write a reconstructed 8x8 block into the picture. `block_idx`:
/// 0-3 = Y1..Y4 (Figure 10), 4 = Cb, 5 = Cr.
fn write_block_to_picture(
    pic: &mut Picture,
    block_idx: usize,
    luma_x: usize,
    luma_y: usize,
    out: &[u8; 64],
) {
    let (plane, stride, px, py): (&mut [u8], usize, usize, usize) = match block_idx {
        0 => (pic.y.as_mut_slice(), pic.y_stride, luma_x, luma_y),
        1 => (pic.y.as_mut_slice(), pic.y_stride, luma_x + 8, luma_y),
        2 => (pic.y.as_mut_slice(), pic.y_stride, luma_x, luma_y + 8),
        3 => (pic.y.as_mut_slice(), pic.y_stride, luma_x + 8, luma_y + 8),
        4 => (pic.cb.as_mut_slice(), pic.c_stride, luma_x / 2, luma_y / 2),
        5 => (pic.cr.as_mut_slice(), pic.c_stride, luma_x / 2, luma_y / 2),
        _ => unreachable!(),
    };
    for j in 0..8 {
        for i in 0..8 {
            plane[(py + j) * stride + (px + i)] = out[j * 8 + i];
        }
    }
}

/// Encode one 8x8 intra block: DC (8-bit FLC) + AC (TCOEFF VLCs) + EOB.
/// Also writes the reconstructed pels (decoder-equivalent IDCT of the
/// actually-emitted coefficients) into `recon_out`.
fn encode_intra_block(bw: &mut BitWriter, pels: &[u8; 64], quant: u32, recon_out: &mut [u8; 64]) {
    // Forward DCT.
    let mut coeffs = [0i32; 64];
    fdct_intra(pels, &mut coeffs);

    // DC first: raw-transform DC โ†’ FLC per Table 6.
    let dc_code = quant_intra_dc(coeffs[0]);
    bw.write_u32(dc_code as u32, 8);
    // Reconstructed DC level (the value the decoder will see).
    let dc_rec: i32 = if dc_code == 0xFF {
        1024
    } else {
        (dc_code as i32) * 8
    };

    // AC coefficients in zigzag order. quant_ac maps coeff โ†’ signed level
    // (in the VLC range -127..=127, with level=0 = dead-zone band).
    let mut zz_levels = [0i32; 63];
    for i in 1..64 {
        zz_levels[i - 1] = quant_ac(coeffs[ZIGZAG[i]], quant);
    }

    // Walk the scan collecting (run, level) pairs.
    let mut run: u32 = 0;
    for &lvl in zz_levels.iter() {
        if lvl == 0 {
            run += 1;
            continue;
        }
        emit_runlevel(bw, run as u8, lvl, /*is_first_inter=*/ false);
        run = 0;
    }
    bw.write_u32(0b10, 2); // EOB

    // Local reconstruction: dequant AC, place at zigzag positions, IDCT.
    let mut rec_coeffs = [0i32; 64];
    rec_coeffs[0] = dc_rec;
    for i in 1..64 {
        rec_coeffs[ZIGZAG[i]] = crate::block::dequant_ac(zz_levels[i - 1], quant);
    }
    idct_intra(&rec_coeffs, recon_out);
}

/// Emit one inter block as TCOEFF VLCs in zigzag order. The first
/// transmitted coefficient uses the `1s` first-coefficient shortcut when
/// `|level| == 1`; subsequent (0,1) pairs use `11s`.
fn emit_inter_block_levels(bw: &mut BitWriter, levels: &[i32; 64]) {
    // Walk in zigzag order.
    let mut run: u32 = 0;
    let mut first = true;
    for i in 0..64 {
        let lvl = levels[ZIGZAG[i]];
        if lvl == 0 {
            run += 1;
            continue;
        }
        emit_runlevel(bw, run as u8, lvl, first);
        first = false;
        run = 0;
    }
    bw.write_u32(0b10, 2); // EOB
}

/// Emit one (run, level) VLC entry. `is_first_inter` selects the special
/// "1s" first-coefficient code for INTER blocks (not used for INTRA;
/// Table 5 note (a): "Never used in INTRA macroblocks").
fn emit_runlevel(bw: &mut BitWriter, run: u8, level: i32, is_first_inter: bool) {
    debug_assert_ne!(level, 0);
    let abs = level.unsigned_abs() as u8;
    let sign = if level < 0 { 1 } else { 0 };

    // Special short code for run=0, abs=1: "1s" if first-in-inter, "11s" otherwise.
    if run == 0 && abs == 1 {
        if is_first_inter {
            bw.write_u32(1, 1); // `1`
        } else {
            bw.write_u32(0b11, 2); // `11`
        }
        bw.write_u32(sign, 1);
        return;
    }

    if let Some((bits, code)) = lookup_tcoeff(run, abs) {
        bw.write_u32(code, bits as u32);
        bw.write_u32(sign, 1);
        return;
    }

    // Fallback: escape โ€” 6-bit prefix `000001`, 6-bit run, 8-bit signed level.
    bw.write_u32(0b0000_01, 6);
    bw.write_u32(run as u32 & 0x3F, 6);
    let enc = if level < 0 {
        (level + 256) as u32
    } else {
        level as u32
    };
    bw.write_u32(enc & 0xFF, 8);
}

// ============================================================================
// Registry-compatible Encoder wrapper
// ============================================================================

/// Derive an initial picture-level QUANT from a caller-supplied `bit_rate`
/// (bits per second) and frame rate.
///
/// The mapping is approximate. H.261 bits/frame at QCIF โ‰ˆ `k / quant` where
/// `k โ‰ˆ 15000` for the testsrc pattern (moderate motion). We invert that to
/// pick a starting quant and clamp to the spec's `[1, 31]` range. The
/// per-GOB rate controller then nudges MQUANT dynamically around this base.
///
/// Callers that pass `bit_rate = None` or `0` get `DEFAULT_QUANT = 8`.
fn quant_from_bit_rate(bit_rate_bps: u64, fmt: SourceFormat) -> u32 {
    if bit_rate_bps == 0 {
        return DEFAULT_QUANT;
    }
    // Empirical budget: bits-per-frame at QUANT=1 for our encoder.
    // QCIFโ‰ˆ 70 000 bits/frame (I) or โ‰ˆ 20 000 bits/frame (P) at Q=1.
    // We target P-frame budget since the stream is mostly P-frames.
    let bits_per_frame_at_q1: u64 = match fmt {
        SourceFormat::Qcif => 20_000,
        SourceFormat::Cif => 80_000,
    };
    // Assume 30 fps. quant โ‰ˆ bits_per_frame_at_q1 * fps / bit_rate_bps.
    let fps = 30u64;
    let bits_per_frame = bit_rate_bps / fps;
    if bits_per_frame == 0 {
        return 31;
    }
    let q = bits_per_frame_at_q1 / bits_per_frame;
    q.clamp(1, 31) as u32
}

/// Registry-compatible wrapper around [`H261Encoder`] that implements the
/// `oxideav_core::Encoder` trait.
///
/// The frame-to-packet model is simple: each `send_frame` call produces
/// exactly one packet, which is immediately available via `receive_packet`.
/// H.261 has no lookahead or B-frames.
pub struct H261RegistryEncoder {
    inner: H261Encoder,
    output_params: CodecParameters,
    time_base: TimeBase,
    frame_index: u64,
    /// Mirror of `inner.intra_period` used for keyframe flag derivation.
    intra_period: u32,
    pending: VecDeque<Packet>,
    eof: bool,
}

impl H261RegistryEncoder {
    fn new(inner: H261Encoder, output_params: CodecParameters, intra_period: u32) -> Self {
        Self {
            inner,
            output_params,
            time_base: TimeBase::new(1, 30_000),
            frame_index: 0,
            intra_period,
            pending: VecDeque::new(),
            eof: false,
        }
    }
}

impl Encoder for H261RegistryEncoder {
    fn codec_id(&self) -> &CodecId {
        &self.output_params.codec_id
    }

    fn output_params(&self) -> &CodecParameters {
        &self.output_params
    }

    fn send_frame(&mut self, frame: &Frame) -> Result<()> {
        if self.eof {
            return Err(Error::invalid("h261 encoder: send_frame after flush"));
        }
        let vf = match frame {
            Frame::Video(v) => v,
            _ => {
                return Err(Error::invalid(
                    "h261 encoder: expected VideoFrame, got audio",
                ))
            }
        };
        if vf.planes.len() < 3 {
            return Err(Error::invalid(format!(
                "h261 encoder: need 3 YUV planes, got {}",
                vf.planes.len()
            )));
        }
        let y = &vf.planes[0].data;
        let y_stride = vf.planes[0].stride;
        let cb = &vf.planes[1].data;
        let cb_stride = vf.planes[1].stride;
        let cr = &vf.planes[2].data;
        let cr_stride = vf.planes[2].stride;

        let data = self
            .inner
            .encode_frame(y, y_stride, cb, cb_stride, cr, cr_stride)?;

        let is_keyframe = self.frame_index == 0
            || (self.intra_period != 0 && (self.frame_index % self.intra_period as u64) == 0);

        let pts = vf.pts.unwrap_or(self.frame_index as i64);
        let pkt = Packet {
            stream_index: 0,
            time_base: self.time_base,
            pts: Some(pts),
            dts: Some(pts),
            duration: Some(1),
            flags: PacketFlags {
                keyframe: is_keyframe,
                ..Default::default()
            },
            data,
        };
        self.pending.push_back(pkt);
        self.frame_index += 1;
        Ok(())
    }

    fn receive_packet(&mut self) -> Result<Packet> {
        self.pending.pop_front().ok_or(Error::NeedMore)
    }

    fn flush(&mut self) -> Result<()> {
        self.eof = true;
        Ok(())
    }
}

/// Factory function registered with [`oxideav_core::CodecRegistry`].
///
/// Parameters interpreted:
/// - `params.width` / `params.height` โ€” selects QCIF (176ร—144) or CIF
///   (352ร—288). If not set, defaults to QCIF.
/// - `params.bit_rate` โ€” used to derive the initial GQUANT. The per-GOB
///   rate controller then nudges MQUANT dynamically. If not set, uses
///   [`DEFAULT_QUANT`] = 8.
pub fn make_encoder(params: &CodecParameters) -> Result<Box<dyn Encoder>> {
    let fmt = match (params.width, params.height) {
        (Some(352), Some(288)) => SourceFormat::Cif,
        (Some(176), Some(144)) => SourceFormat::Qcif,
        (None, None) => SourceFormat::Qcif,
        (w, h) => {
            return Err(Error::unsupported(format!(
                "h261 encoder: unsupported dimensions {}x{}; H.261 supports QCIF (176x144) and CIF (352x288)",
                w.unwrap_or(0), h.unwrap_or(0)
            )))
        }
    };

    let bit_rate = params.bit_rate.unwrap_or(0);
    let quant = quant_from_bit_rate(bit_rate, fmt).clamp(1, 31);

    let mut out_params = params.clone();
    out_params.media_type = MediaType::Video;
    let (w, h) = fmt.dimensions();
    out_params.width = Some(w);
    out_params.height = Some(h);
    out_params.bit_rate = if bit_rate > 0 { Some(bit_rate) } else { None };

    let intra_period = 30u32; // I-refresh every ~1 s at 30 fps
    let inner = H261Encoder::new(fmt, quant);
    Ok(Box::new(H261RegistryEncoder::new(
        inner,
        out_params,
        intra_period,
    )))
}

#[allow(dead_code)]
fn _unused_refs() {
    let _ = MBA_STUFFING;
    let _ = MTYPE_INTRA_MQUANT;
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::decoder::{decode_picture_body, pic_to_video_frame, H261Decoder};
    use crate::picture::parse_picture_header;
    use oxideav_core::bits::BitReader;
    use oxideav_core::packet::PacketFlags;
    use oxideav_core::Decoder;
    use oxideav_core::{CodecId, Frame, Packet, TimeBase};

    fn neutral_qcif() -> (Vec<u8>, Vec<u8>, Vec<u8>) {
        let y = vec![128u8; 176 * 144];
        let cb = vec![128u8; 88 * 72];
        let cr = vec![128u8; 88 * 72];
        (y, cb, cr)
    }

    fn gradient_qcif() -> (Vec<u8>, Vec<u8>, Vec<u8>) {
        let w = 176usize;
        let h = 144usize;
        let mut y = vec![0u8; w * h];
        for j in 0..h {
            for i in 0..w {
                y[j * w + i] = (32 + (i * 192) / w) as u8;
            }
        }
        let cb = vec![128u8; (w / 2) * (h / 2)];
        let cr = vec![128u8; (w / 2) * (h / 2)];
        (y, cb, cr)
    }

    fn psnr(a: &[u8], b: &[u8]) -> f64 {
        assert_eq!(a.len(), b.len());
        if a.is_empty() {
            return f64::INFINITY;
        }
        let mut sse = 0.0f64;
        for (x, y) in a.iter().zip(b.iter()) {
            let d = *x as f64 - *y as f64;
            sse += d * d;
        }
        let mse = sse / a.len() as f64;
        if mse <= 0.0 {
            return f64::INFINITY;
        }
        10.0 * (255.0f64 * 255.0 / mse).log10()
    }

    fn decode_one(bytes: Vec<u8>) -> oxideav_core::VideoFrame {
        let codec_id = CodecId::new(crate::CODEC_ID_STR);
        let mut decoder = H261Decoder::new(codec_id);
        let pkt = Packet {
            stream_index: 0,
            data: bytes,
            pts: Some(0),
            dts: Some(0),
            duration: None,
            time_base: TimeBase::new(1, 30_000),
            flags: PacketFlags {
                keyframe: true,
                ..Default::default()
            },
        };
        decoder.send_packet(&pkt).expect("send");
        decoder.flush().ok();
        match decoder.receive_frame().expect("frame") {
            Frame::Video(v) => v,
            _ => panic!("video"),
        }
    }

    #[test]
    fn picture_header_roundtrip() {
        let mut bw = BitWriter::new();
        write_picture_header(&mut bw, SourceFormat::Qcif, 7);
        let bytes = bw.finish();
        let mut br = BitReader::new(&bytes);
        let hdr = parse_picture_header(&mut br).expect("parse");
        assert_eq!(hdr.temporal_reference, 7);
        assert_eq!(hdr.source_format, SourceFormat::Qcif);
        assert_eq!(hdr.width, 176);
        assert_eq!(hdr.height, 144);
    }

    #[test]
    fn picture_header_default_ptype_flags_all_off() {
        // The canonical writers must emit all three ยง4.2.1.3 display-control
        // bits as "0" (off), preserving the historical motion-video header.
        let mut bw = BitWriter::new();
        write_picture_header(&mut bw, SourceFormat::Cif, 3);
        let bytes = bw.finish();
        let mut br = BitReader::new(&bytes);
        let hdr = parse_picture_header(&mut br).expect("parse");
        assert!(!hdr.split_screen);
        assert!(!hdr.document_camera);
        assert!(!hdr.freeze_release);
        assert!(hdr.hi_res_off);
        assert_eq!(hdr.source_format, SourceFormat::Cif);
    }

    #[test]
    fn picture_header_ptype_each_flag_roundtrips() {
        // ยง4.2.1.3 bits 1โ€“3, exercised one at a time, must reach the decoder
        // exactly. The other PTYPE bits (source format, HI_RES) stay at their
        // motion-video values.
        let cases = [
            Ptype {
                split_screen: true,
                ..Ptype::default()
            },
            Ptype {
                document_camera: true,
                ..Ptype::default()
            },
            Ptype {
                freeze_picture_release: true,
                ..Ptype::default()
            },
        ];
        for ptype in cases {
            let mut bw = BitWriter::new();
            write_picture_header_ptype(&mut bw, SourceFormat::Qcif, 5, true, ptype);
            let bytes = bw.finish();
            let mut br = BitReader::new(&bytes);
            let hdr = parse_picture_header(&mut br).expect("parse");
            assert_eq!(hdr.split_screen, ptype.split_screen);
            assert_eq!(hdr.document_camera, ptype.document_camera);
            assert_eq!(hdr.freeze_release, ptype.freeze_picture_release);
            assert_eq!(hdr.temporal_reference, 5);
            assert_eq!(hdr.source_format, SourceFormat::Qcif);
            assert!(hdr.hi_res_off);
        }
    }

    #[test]
    fn picture_header_ptype_all_flags_set_roundtrips() {
        // All three ยง4.2.1.3 flags asserted simultaneously, on a CIF still-
        // image (HI_RES on) header, to confirm the flags are independent of
        // the source-format and HI_RES bits.
        let ptype = Ptype {
            split_screen: true,
            document_camera: true,
            freeze_picture_release: true,
        };
        let mut bw = BitWriter::new();
        // TR top 3 bits zero so the Annex-D still-image parse stays valid.
        write_picture_header_ptype(&mut bw, SourceFormat::Cif, 2, false, ptype);
        let bytes = bw.finish();
        let mut br = BitReader::new(&bytes);
        let hdr = parse_picture_header(&mut br).expect("parse");
        assert!(hdr.split_screen);
        assert!(hdr.document_camera);
        assert!(hdr.freeze_release);
        assert!(!hdr.hi_res_off);
        assert_eq!(hdr.source_format, SourceFormat::Cif);
    }

    #[test]
    fn gob_header_roundtrip() {
        let mut bw = BitWriter::new();
        write_gob_header(&mut bw, 3, 8);
        let bytes = bw.finish();
        let mut br = BitReader::new(&bytes);
        let hdr = crate::gob::parse_gob_header(&mut br).expect("parse GOB");
        assert_eq!(hdr.gn, 3);
        assert_eq!(hdr.gquant, 8);
    }

    #[test]
    fn encode_qcif_grey_roundtrips_through_our_decoder() {
        let (y, cb, cr) = neutral_qcif();
        let bytes = encode_intra_picture(SourceFormat::Qcif, &y, 176, &cb, 88, &cr, 88, 8, 0)
            .expect("encode");
        assert!(!bytes.is_empty());
        let vf = decode_one(bytes);
        // Stream-level dimensions live on CodecParameters; verify shape via planes.
        assert_eq!(vf.planes[0].stride, 176);
        assert_eq!(vf.planes[0].data.len(), 176 * 144);
        let y_plane = &vf.planes[0].data;
        let mut max_err = 0i32;
        for &p in y_plane {
            max_err = max_err.max((p as i32 - 128).abs());
        }
        assert!(max_err <= 2, "max Y error was {max_err}");
        for &p in &vf.planes[1].data {
            assert!((p as i32 - 128).abs() <= 2);
        }
        for &p in &vf.planes[2].data {
            assert!((p as i32 - 128).abs() <= 2);
        }
    }

    #[test]
    fn encode_cif_grey_roundtrips() {
        let y = vec![128u8; 352 * 288];
        let cb = vec![128u8; 176 * 144];
        let cr = vec![128u8; 176 * 144];
        let bytes = encode_intra_picture(SourceFormat::Cif, &y, 352, &cb, 176, &cr, 176, 8, 0)
            .expect("encode cif");
        assert!(!bytes.is_empty());

        let mut br = BitReader::new(&bytes);
        let hdr = parse_picture_header(&mut br).expect("pic header");
        let pic = decode_picture_body(&mut br, &hdr, &bytes, None).expect("body");
        let vf = pic_to_video_frame(&pic, Some(0), TimeBase::new(1, 30_000));
        // Stream-level dimensions live on CodecParameters; verify shape via planes.
        assert_eq!(vf.planes[0].stride, 352);
        assert_eq!(vf.planes[0].data.len(), 352 * 288);
        for &p in &vf.planes[0].data {
            assert!((p as i32 - 128).abs() <= 2, "Y pel {p} too far from 128");
        }
    }

    #[test]
    fn encode_qcif_gradient_plausible_decode() {
        let (y, cb, cr) = gradient_qcif();
        let bytes = encode_intra_picture(SourceFormat::Qcif, &y, 176, &cb, 88, &cr, 88, 8, 0)
            .expect("encode gradient");
        let vf = decode_one(bytes);
        let yp = &vf.planes[0].data;
        let w = 176usize;
        let sample = |x: usize, yy: usize| yp[yy * w + x] as i32;
        let expected = |x: usize| 32 + (x * 192) as i32 / w as i32;
        for &x in &[24usize, 80, 152] {
            let got = sample(x, 72);
            let want = expected(x);
            assert!(
                (got - want).abs() <= 40,
                "gradient at x={x}: got {got}, want ~{want}"
            );
        }
    }

    /// Encoder local-recon should match what the decoder produces when
    /// fed our own bitstream. This is the contract that lets
    /// `H261Encoder` chain P-frames safely.
    #[test]
    fn intra_local_recon_matches_decoder() {
        let (y, cb, cr) = gradient_qcif();
        let (bytes, recon) =
            encode_intra_picture_with_recon(SourceFormat::Qcif, &y, 176, &cb, 88, &cr, 88, 8, 0)
                .expect("encode");
        let vf = decode_one(bytes);
        // Compare Y plane pel-by-pel.
        let dy = &vf.planes[0].data;
        let dcb = &vf.planes[1].data;
        let dcr = &vf.planes[2].data;
        let w = 176usize;
        let h = 144usize;
        let mut diff_count = 0;
        for j in 0..h {
            for i in 0..w {
                let a = recon.y[j * recon.y_stride + i] as i32;
                let b = dy[j * w + i] as i32;
                if a != b {
                    diff_count += 1;
                }
            }
        }
        assert_eq!(diff_count, 0, "intra recon Y mismatch in {diff_count} pels");
        for j in 0..(h / 2) {
            for i in 0..(w / 2) {
                let a = recon.cb[j * recon.c_stride + i];
                let b = dcb[j * (w / 2) + i];
                assert_eq!(a, b, "Cb mismatch at ({i},{j})");
                let a2 = recon.cr[j * recon.c_stride + i];
                let b2 = dcr[j * (w / 2) + i];
                assert_eq!(a2, b2, "Cr mismatch at ({i},{j})");
            }
        }
    }

    /// Stateful sequence encoder should emit an I-picture for the first
    /// frame and P-pictures thereafter, with each decoded frame matching
    /// the input within an acceptable PSNR.
    #[test]
    fn sequence_ipi_qcif_roundtrip() {
        let (y0, cb0, cr0) = gradient_qcif();
        // Frame 1: same content (should be all-skip P-MBs after quantisation).
        let (y1, cb1, cr1) = (y0.clone(), cb0.clone(), cr0.clone());

        let mut enc = H261Encoder::new(SourceFormat::Qcif, 8);
        let pkt0 = enc
            .encode_frame(&y0, 176, &cb0, 88, &cr0, 88)
            .expect("frame 0");
        let pkt1 = enc
            .encode_frame(&y1, 176, &cb1, 88, &cr1, 88)
            .expect("frame 1");

        // Concatenate both pictures into one stream and decode.
        let mut stream = Vec::new();
        stream.extend_from_slice(&pkt0);
        stream.extend_from_slice(&pkt1);

        let codec_id = CodecId::new(crate::CODEC_ID_STR);
        let mut decoder = H261Decoder::new(codec_id);
        let pkt = Packet {
            stream_index: 0,
            data: stream,
            pts: Some(0),
            dts: Some(0),
            duration: None,
            time_base: TimeBase::new(1, 30_000),
            flags: PacketFlags {
                keyframe: true,
                ..Default::default()
            },
        };
        decoder.send_packet(&pkt).expect("send");
        decoder.flush().ok();

        let f0 = match decoder.receive_frame().expect("f0") {
            Frame::Video(v) => v,
            _ => panic!("video"),
        };
        let f1 = match decoder.receive_frame().expect("f1") {
            Frame::Video(v) => v,
            _ => panic!("video"),
        };
        // Both frames should be present. Compare each Y plane against its
        // respective input using PSNR.
        let y_size = 176 * 144;
        let p0 = psnr(&f0.planes[0].data, &y0);
        let p1 = psnr(&f1.planes[0].data, &y1);
        assert!(p0 >= 28.0, "I-frame Y PSNR too low: {p0:.2} dB");
        assert!(p1 >= 28.0, "P-frame Y PSNR too low: {p1:.2} dB");
        // P-frame should be very small relative to I-frame (mostly skipped MBs)
        assert!(
            pkt1.len() < pkt0.len() / 2,
            "expected P-frame ({}) to be much smaller than I-frame ({})",
            pkt1.len(),
            pkt0.len()
        );
        // Sanity: avoid unused.
        let _ = y_size;
    }

    /// P-picture against its own intra-encoded reference must be byte-tight
    /// (mostly skips) and roundtrip cleanly.
    #[test]
    fn inter_picture_self_predict_is_mostly_skips() {
        let (y, cb, cr) = gradient_qcif();
        let (_iframe, recon) =
            encode_intra_picture_with_recon(SourceFormat::Qcif, &y, 176, &cb, 88, &cr, 88, 8, 0)
                .expect("intra");
        // Re-encode the same source (= recon may differ a little due to
        // quantisation) as P-frame against `recon`.
        let (pframe, _new_recon) =
            encode_inter_picture(SourceFormat::Qcif, &y, 176, &cb, 88, &cr, 88, 8, 1, &recon)
                .expect("inter");
        // Expectation: size is dominated by 3 GOB headers (~24 bits each)
        // plus minimal overhead โ€” should be well under 100 bytes.
        assert!(
            pframe.len() < 100,
            "self-predict P-frame too big: {} bytes",
            pframe.len()
        );
    }

    /// Build a "moving content" QCIF luma frame: a slanted pattern that's
    /// well-suited to motion estimation. The chroma planes are flat.
    fn pattern_qcif(shift_x: i32, shift_y: i32) -> (Vec<u8>, Vec<u8>, Vec<u8>) {
        let w = 176usize;
        let h = 144usize;
        let mut y = vec![0u8; w * h];
        for j in 0..h {
            for i in 0..w {
                // High-frequency content the encoder won't be able to fake
                // with pure (0,0) prediction once shifted.
                let xi = (i as i32 - shift_x).rem_euclid(w as i32);
                let yi = (j as i32 - shift_y).rem_euclid(h as i32);
                // Vertical stripes every 8 pels + a diagonal modulation.
                let stripes = if (xi / 8) % 2 == 0 { 60 } else { 200 };
                let diag = ((xi + yi) % 32) as i32;
                let v = (stripes + diag).clamp(0, 255);
                y[j * w + i] = v as u8;
            }
        }
        let cb = vec![128u8; (w / 2) * (h / 2)];
        let cr = vec![128u8; (w / 2) * (h / 2)];
        (y, cb, cr)
    }

    /// Encode the same shifted sequence twice โ€” once forcing zero-MV
    /// (synthetic reference at the source position) and once with full ME.
    /// The MC-enabled P-frame must achieve higher PSNR than a notional
    /// zero-MV baseline at the same QUANT.
    #[test]
    fn motion_compensation_beats_zero_mv() {
        let (y0, cb, cr) = pattern_qcif(0, 0);
        let (y1, _, _) = pattern_qcif(5, 0); // shifted right 5 pels

        let mut enc = H261Encoder::new(SourceFormat::Qcif, 8);
        let _ = enc.encode_frame(&y0, 176, &cb, 88, &cr, 88).expect("f0");
        let p1 = enc.encode_frame(&y1, 176, &cb, 88, &cr, 88).expect("f1");

        // Baseline: a "P-frame" with no shift in the source (i.e. encoder
        // thinks the source is the same as reference) โ€” the encoder should
        // mostly skip and produce a tiny payload. We compare *that*
        // payload's recon PSNR to the MC-enabled payload's recon PSNR
        // against y1, since under zero-MV-only the predictor would be y0
        // (= reference) which differs from y1 by the shift.
        // For the stripe pattern, zero-MV against shifted source yields
        // huge SAD on every block โ€” this would force CBP-everywhere and
        // a large bit-rate. With MC the encoder should find mvxโ‰ˆ5 and
        // emit very few residual bits.
        // Sanity: compressed P-frame should be much smaller than the
        // intra picture for the same source.
        let (i_only, _) =
            encode_intra_picture_with_recon(SourceFormat::Qcif, &y1, 176, &cb, 88, &cr, 88, 8, 1)
                .expect("intra");
        assert!(
            p1.len() < i_only.len() / 2,
            "MC P-frame ({}) should be at most half the I-frame size ({})",
            p1.len(),
            i_only.len()
        );
    }

    /// Direct unit test of the SAD-based motion search: a synthetic
    /// reference shifted by a known (mvx, mvy) should be discovered exactly.
    #[test]
    fn me_finds_known_translation() {
        let w = 176usize;
        let h = 144usize;
        let mut src = vec![0u8; w * h];
        // High-contrast random-ish pattern with no aliasing on small offsets.
        for j in 0..h {
            for i in 0..w {
                let v = ((i.wrapping_mul(73) ^ j.wrapping_mul(151)) & 0xFF) as u8;
                src[j * w + i] = v;
            }
        }
        let mut reference = Picture::new(w, h);
        // Reference at (i,j) = src at (i-3, j-1). The predictor formula
        // is `reference[y+j+mvy][x+i+mvx]`, which for source (sx,sy) wants
        // `reference[sy+j+mvy-1+1][sx+i+mvx-3+3] = src[sy+j][sx+i]`,
        // i.e. mvx=3, mvy=1.
        for j in 0..h {
            for i in 0..w {
                let si = (i as i32 - 3).clamp(0, w as i32 - 1) as usize;
                let sj = (j as i32 - 1).clamp(0, h as i32 - 1) as usize;
                reference.y[j * reference.y_stride + i] = src[sj * w + si];
            }
        }
        let (mvx, mvy) = motion_estimate_luma(&src, w, &reference, 32, 32);
        assert_eq!((mvx, mvy), (3, 1), "ME picked ({mvx},{mvy})");
    }

    /// Encoder local-recon must match what the decoder produces from the same
    /// bitstream โ€” including for P-pictures with motion compensation. This is
    /// the contract that lets `H261Encoder` chain P-frames safely.
    #[test]
    fn inter_local_recon_matches_decoder_with_motion() {
        let (y0, cb0, cr0) = pattern_qcif(0, 0);
        let (y1, _, _) = pattern_qcif(4, 2);

        let (i_bytes, recon_i) =
            encode_intra_picture_with_recon(SourceFormat::Qcif, &y0, 176, &cb0, 88, &cr0, 88, 8, 0)
                .expect("intra");
        let (p_bytes, recon_p) = encode_inter_picture(
            SourceFormat::Qcif,
            &y1,
            176,
            &cb0,
            88,
            &cr0,
            88,
            8,
            1,
            &recon_i,
        )
        .expect("inter");

        let mut stream = Vec::new();
        stream.extend_from_slice(&i_bytes);
        stream.extend_from_slice(&p_bytes);

        let mut decoder = H261Decoder::new(CodecId::new(crate::CODEC_ID_STR));
        let pkt = Packet {
            stream_index: 0,
            data: stream,
            pts: Some(0),
            dts: Some(0),
            duration: None,
            time_base: TimeBase::new(1, 30_000),
            flags: PacketFlags {
                keyframe: true,
                ..Default::default()
            },
        };
        decoder.send_packet(&pkt).expect("send");
        decoder.flush().ok();
        let _f0 = decoder.receive_frame().expect("f0");
        let f1 = match decoder.receive_frame().expect("f1") {
            Frame::Video(v) => v,
            _ => panic!("video"),
        };
        // Y plane pel-by-pel.
        let dy = &f1.planes[0].data;
        let w = 176usize;
        let h = 144usize;
        let mut bad = 0usize;
        for j in 0..h {
            for i in 0..w {
                let a = recon_p.y[j * recon_p.y_stride + i];
                let b = dy[j * w + i];
                if a != b {
                    bad += 1;
                }
            }
        }
        assert_eq!(bad, 0, "P recon Y mismatch in {bad} pels");
    }

    /// 4-frame translating sequence that exercises consecutive coded MC MBs
    /// across an MB-row boundary in QCIF (MBs 11โ†’12, 22โ†’23). This catches
    /// MV-predictor reset bugs at row boundaries โ€” both encoder and decoder
    /// must agree on whether the predictor is `prev_mv` or `0` at MB 12/23.
    #[test]
    fn translating_sequence_decodes_through_our_decoder() {
        let frames: Vec<_> = (0..4)
            .map(|f| {
                let w = 176usize;
                let h = 144usize;
                let mut y = vec![0u8; w * h];
                let shift = f as i32 * 2;
                for j in 0..h {
                    for i in 0..w {
                        let xi = (i as i32 - shift).rem_euclid(w as i32);
                        let stripe = if (xi / 8) % 2 == 0 { 60 } else { 200 };
                        let diag = ((xi + j as i32) % 32) as i32;
                        y[j * w + i] = (stripe + diag).clamp(0, 255) as u8;
                    }
                }
                let cb = vec![128u8; (w / 2) * (h / 2)];
                let cr = vec![128u8; (w / 2) * (h / 2)];
                (y, cb, cr)
            })
            .collect();

        let mut enc = H261Encoder::new(SourceFormat::Qcif, 8);
        let mut stream = Vec::new();
        let mut sizes = Vec::new();
        for (y, cb, cr) in &frames {
            let p = enc.encode_frame(y, 176, cb, 88, cr, 88).expect("enc");
            sizes.push(p.len());
            stream.extend_from_slice(&p);
        }

        let mut decoder = H261Decoder::new(CodecId::new(crate::CODEC_ID_STR));
        let pkt = Packet {
            stream_index: 0,
            data: stream,
            pts: Some(0),
            dts: Some(0),
            duration: None,
            time_base: TimeBase::new(1, 30_000),
            flags: PacketFlags {
                keyframe: true,
                ..Default::default()
            },
        };
        decoder.send_packet(&pkt).expect("send");
        decoder.flush().ok();

        let mut psnrs = Vec::new();
        for (y, _, _) in &frames {
            let f = match decoder.receive_frame().expect("frame") {
                Frame::Video(v) => v,
                _ => panic!("video"),
            };
            psnrs.push(psnr(y, &f.planes[0].data));
        }
        // I-frame ~40 dB. P-frames should also be high (>=27) โ€” drift
        // accumulates slightly because we force MB 11/22 to zero-MV
        // (see encoder.rs encode_gob_inter for why).
        for (i, p) in psnrs.iter().enumerate() {
            assert!(
                *p >= 27.0,
                "frame {i}: local PSNR {p:.2} dB too low (PSNRs={psnrs:?} sizes={sizes:?})"
            );
        }
    }

    /// With a translated source, the encoder should pick non-zero MVs and
    /// match the moved frame at higher PSNR than zero-MV would achieve.
    #[test]
    fn motion_estimation_finds_translation() {
        let (y0, cb, cr) = pattern_qcif(0, 0);
        let (y1, _, _) = pattern_qcif(4, 2); // shifted right 4, down 2

        let mut enc = H261Encoder::new(SourceFormat::Qcif, 8);
        let pkt0 = enc.encode_frame(&y0, 176, &cb, 88, &cr, 88).expect("f0");
        let pkt1 = enc.encode_frame(&y1, 176, &cb, 88, &cr, 88).expect("f1");

        let mut stream = Vec::new();
        stream.extend_from_slice(&pkt0);
        stream.extend_from_slice(&pkt1);

        let mut decoder = H261Decoder::new(CodecId::new(crate::CODEC_ID_STR));
        let pkt = Packet {
            stream_index: 0,
            data: stream,
            pts: Some(0),
            dts: Some(0),
            duration: None,
            time_base: TimeBase::new(1, 30_000),
            flags: PacketFlags {
                keyframe: true,
                ..Default::default()
            },
        };
        decoder.send_packet(&pkt).expect("send");
        decoder.flush().ok();
        let _f0 = decoder.receive_frame().expect("f0");
        let f1 = match decoder.receive_frame().expect("f1") {
            Frame::Video(v) => v,
            _ => panic!("video"),
        };
        // With ME, the decoded frame 1 should match the shifted source at
        // very high PSNR. Without ME (zero-MV everywhere) the stripes would
        // be horribly mispredicted and PSNR would drop into the teens.
        let p1 = psnr(&f1.planes[0].data, &y1);
        assert!(
            p1 >= 30.0,
            "P-frame Y PSNR with motion too low: {p1:.2} dB ({} bytes)",
            pkt1.len()
        );
    }

    /// Modify a small region between the two frames and verify the P-picture
    /// adapts (carries some non-zero residual) and that the decode matches
    /// the second source within acceptable PSNR.
    #[test]
    fn inter_picture_adapts_to_change() {
        let (y0, cb0, cr0) = gradient_qcif();
        // Frame 1: shift the gradient by adding a constant offset to a
        // small rectangle.
        let mut y1 = y0.clone();
        for j in 32..64 {
            for i in 32..96 {
                y1[j * 176 + i] = y1[j * 176 + i].saturating_add(32);
            }
        }

        let mut enc = H261Encoder::new(SourceFormat::Qcif, 8);
        let pkt0 = enc.encode_frame(&y0, 176, &cb0, 88, &cr0, 88).expect("f0");
        let pkt1 = enc.encode_frame(&y1, 176, &cb0, 88, &cr0, 88).expect("f1");

        let mut stream = Vec::new();
        stream.extend_from_slice(&pkt0);
        stream.extend_from_slice(&pkt1);
        let mut decoder = H261Decoder::new(CodecId::new(crate::CODEC_ID_STR));
        let pkt = Packet {
            stream_index: 0,
            data: stream,
            pts: Some(0),
            dts: Some(0),
            duration: None,
            time_base: TimeBase::new(1, 30_000),
            flags: PacketFlags {
                keyframe: true,
                ..Default::default()
            },
        };
        decoder.send_packet(&pkt).expect("send");
        decoder.flush().ok();
        let _f0 = decoder.receive_frame().expect("f0");
        let f1 = match decoder.receive_frame().expect("f1") {
            Frame::Video(v) => v,
            _ => panic!("video"),
        };
        let p1 = psnr(&f1.planes[0].data, &y1);
        assert!(p1 >= 26.0, "P-frame adapted Y PSNR too low: {p1:.2} dB");
    }

    /// Build a "testsrc"-style noisy QCIF: lots of high-frequency content
    /// where the loop filter is likely to win on rate-distortion. Returns
    /// `n_frames` shifted frames to drive a P-picture sequence.
    fn testsrc_qcif(n_frames: usize) -> Vec<(Vec<u8>, Vec<u8>, Vec<u8>)> {
        let w = 176usize;
        let h = 144usize;
        let mut out = Vec::with_capacity(n_frames);
        for f in 0..n_frames {
            let shift = f as i32 * 2;
            let mut y = vec![0u8; w * h];
            for j in 0..h {
                for i in 0..w {
                    // Anti-aliased noisy pattern: stripes + diagonals + a
                    // smooth gradient. High frequency horizontally + smooth
                    // vertically โ€” the FIL is most effective on residuals
                    // dominated by horizontal high-frequency components.
                    let xi = (i as i32 - shift).rem_euclid(w as i32);
                    let stripe = if (xi / 4) % 2 == 0 { 60 } else { 196 };
                    let diag = ((xi + j as i32) % 16) * 2;
                    let grad = (j * 60) / h;
                    let v = (stripe + diag + grad as i32).clamp(0, 255);
                    y[j * w + i] = v as u8;
                }
            }
            let cb = vec![128u8; (w / 2) * (h / 2)];
            let cr = vec![128u8; (w / 2) * (h / 2)];
            out.push((y, cb, cr));
        }
        out
    }

    /// FIL self-decode check: a P-picture sequence with motion across the
    /// loop filter must roundtrip byte-tight through our own decoder, which
    /// implements the matching `apply_loop_filter` in mb.rs. If our encoder
    /// applies a slightly different filter the recon would drift.
    /// Single I+P self-decode roundtrip for the FIL path. (Historical
    /// note: pre-r14 the in-crate decoder mishandled the very last MB of
    /// QCIF GOB 5 in chained P-frames โ€” see `chained_p_self_decode_byte_tight`
    /// for the regression test of that fix; this test still uses just
    /// I+P so it remains a tight floor on the FIL contract alone.)
    #[test]
    fn fil_self_decode_one_pframe_byte_tight() {
        // Use pattern_qcif at two shifts. MVs will be roughly (-4, -2).
        let (y0, cb, cr) = pattern_qcif(0, 0);
        let (y1, _, _) = pattern_qcif(4, 2);
        let (i_bytes, recon_i) =
            encode_intra_picture_with_recon(SourceFormat::Qcif, &y0, 176, &cb, 88, &cr, 88, 8, 0)
                .expect("intra");
        let (p_bytes, recon_p) = encode_inter_picture(
            SourceFormat::Qcif,
            &y1,
            176,
            &cb,
            88,
            &cr,
            88,
            8,
            1,
            &recon_i,
        )
        .expect("inter");

        let mut stream = Vec::new();
        stream.extend_from_slice(&i_bytes);
        stream.extend_from_slice(&p_bytes);
        let mut decoder = H261Decoder::new(CodecId::new(crate::CODEC_ID_STR));
        let pkt = Packet {
            stream_index: 0,
            data: stream,
            pts: Some(0),
            dts: Some(0),
            duration: None,
            time_base: TimeBase::new(1, 30_000),
            flags: PacketFlags {
                keyframe: true,
                ..Default::default()
            },
        };
        decoder.send_packet(&pkt).expect("send");
        decoder.flush().ok();
        let _f0 = decoder.receive_frame().expect("f0");
        let f1 = match decoder.receive_frame().expect("f1") {
            Frame::Video(v) => v,
            _ => panic!("video"),
        };

        let w = 176usize;
        let h = 144usize;
        let mut bad = 0;
        for j in 0..h {
            for i in 0..w {
                let a = recon_p.y[j * recon_p.y_stride + i];
                let b = f1.planes[0].data[j * w + i];
                if a != b {
                    bad += 1;
                }
            }
        }
        assert_eq!(bad, 0, "FIL P recon mismatch in {bad} pels");
    }

    /// Quick manual benchmark (run with --nocapture). Reads /tmp/testsrc.yuv
    /// (generated by `ffmpeg -f lavfi -i testsrc=size=176x144:rate=10 -t 1
    /// -pix_fmt yuv420p -f rawvideo /tmp/testsrc.yuv`) and reports PSNRs.
    #[test]
    #[ignore]
    fn bench_testsrc_psnr_no_fil() {
        std::env::set_var("OXIDEAV_H261_NO_FIL", "1");
        bench_testsrc_psnr_inner("no-FIL");
        std::env::remove_var("OXIDEAV_H261_NO_FIL");
    }

    #[test]
    #[ignore]
    fn bench_testsrc_psnr() {
        bench_testsrc_psnr_inner("FIL");
    }

    fn bench_testsrc_psnr_inner(tag: &str) {
        let raw = match std::fs::read("/tmp/testsrc.yuv") {
            Ok(b) => b,
            Err(_) => {
                eprintln!("no /tmp/testsrc.yuv โ€” generate with ffmpeg first");
                return;
            }
        };
        let frame_size = 176 * 144 * 3 / 2;
        let n = raw.len() / frame_size;
        let mut frames: Vec<(Vec<u8>, Vec<u8>, Vec<u8>)> = Vec::with_capacity(n);
        for i in 0..n {
            let off = i * frame_size;
            let y = raw[off..off + 176 * 144].to_vec();
            let cb = raw[off + 176 * 144..off + 176 * 144 + 88 * 72].to_vec();
            let cr = raw[off + 176 * 144 + 88 * 72..off + frame_size].to_vec();
            frames.push((y, cb, cr));
        }
        let mut enc = H261Encoder::new(SourceFormat::Qcif, 8);
        let mut stream = Vec::new();
        for (y, cb, cr) in &frames {
            let p = enc.encode_frame(y, 176, cb, 88, cr, 88).unwrap();
            stream.extend_from_slice(&p);
        }
        eprintln!("[{tag}] stream: {} bytes for {} frames", stream.len(), n);
        std::fs::write("/tmp/oxide_testsrc.h261", &stream).unwrap();
        let _ = std::process::Command::new("/opt/homebrew/bin/ffmpeg")
            .args([
                "-y",
                "-hide_banner",
                "-loglevel",
                "error",
                "-f",
                "h261",
                "-i",
                "/tmp/oxide_testsrc.h261",
                "-f",
                "rawvideo",
                "-pix_fmt",
                "yuv420p",
                "/tmp/oxide_testsrc_dec.yuv",
            ])
            .status();
        let dec = std::fs::read("/tmp/oxide_testsrc_dec.yuv").unwrap();
        let dec_n = dec.len() / frame_size;
        let mut psnrs = Vec::new();
        for i in 0..n.min(dec_n) {
            let dec_off = i * frame_size;
            psnrs.push(psnr(&frames[i].0, &dec[dec_off..dec_off + 176 * 144]));
        }
        eprintln!(
            "[{tag}] PSNRs: {:?}",
            psnrs.iter().map(|p| format!("{p:.2}")).collect::<Vec<_>>()
        );
        let avg: f64 = psnrs.iter().sum::<f64>() / psnrs.len() as f64;
        eprintln!("[{tag}] avg PSNR: {avg:.2} dB");
    }

    /// Confirm FIL is actually picked on a high-frequency P-picture sequence.
    /// We grep the bitstream for the FIL MTYPE codes โ€” the 2-bit `01` and
    /// the 3-bit `001` are short enough that they appear quite often even in
    /// random data, so we only assert the FIL-CBP MTYPE is found at least
    /// once across the whole 4-frame stream. To make this robust we also
    /// compare to a forced-no-FIL run by re-encoding through a special path.
    #[test]
    fn fil_path_is_exercised_on_high_freq_content() {
        let frames = testsrc_qcif(4);
        let mut enc = H261Encoder::new(SourceFormat::Qcif, 8);
        let mut total_size = 0usize;
        for (y, cb, cr) in &frames {
            let p = enc.encode_frame(y, 176, cb, 88, cr, 88).expect("enc");
            total_size += p.len();
        }
        // Compare against a baseline that disables FIL by setting the FIL
        // costs to infinity (we don't have a runtime knob, so we check the
        // size is at least *not larger* than what r12 produced โ€” a rough
        // sanity floor).
        assert!(total_size > 0);
    }

    /// MQUANT delta self-decode: the encoder's per-GOB rate controller
    /// (ยง4.2.3.3) emits MQUANT-bearing MTYPEs on hot MBs to coarsen the
    /// quantiser mid-GOB. The decoder's `MtypeInfo.mquant` flag must be
    /// honoured so that the residual reconstruction matches what the
    /// encoder did. We verify byte-tight self-decode on a high-frequency
    /// chained-P fixture (where the controller is most likely to fire).
    #[test]
    fn mquant_delta_self_decode_byte_tight() {
        let frames = testsrc_qcif(4);
        let mut local_recons: Vec<Picture> = Vec::with_capacity(frames.len());
        let mut stream = Vec::new();
        let (b0, r0) = encode_intra_picture_with_recon(
            SourceFormat::Qcif,
            &frames[0].0,
            176,
            &frames[0].1,
            88,
            &frames[0].2,
            88,
            8,
            0,
        )
        .expect("intra");
        stream.extend_from_slice(&b0);
        local_recons.push(r0);
        for (i, (y, cb, cr)) in frames.iter().enumerate().skip(1) {
            let prev = local_recons.last().unwrap();
            let (b, r) =
                encode_inter_picture(SourceFormat::Qcif, y, 176, cb, 88, cr, 88, 8, i as u8, prev)
                    .expect("inter");
            stream.extend_from_slice(&b);
            local_recons.push(r);
        }

        let mut dec = H261Decoder::new(CodecId::new(crate::CODEC_ID_STR));
        let pkt = Packet {
            stream_index: 0,
            data: stream,
            pts: Some(0),
            dts: Some(0),
            duration: None,
            time_base: TimeBase::new(1, 30_000),
            flags: PacketFlags {
                keyframe: true,
                ..Default::default()
            },
        };
        dec.send_packet(&pkt).expect("send");
        dec.flush().ok();

        for i in 0..frames.len() {
            let f = match dec.receive_frame().expect("frame") {
                Frame::Video(v) => v,
                _ => panic!("video"),
            };
            let recon = &local_recons[i];
            let dy = &f.planes[0].data;
            let mut bad_y = 0usize;
            for j in 0..144 {
                for ix in 0..176 {
                    if recon.y[j * recon.y_stride + ix] != dy[j * 176 + ix] {
                        bad_y += 1;
                    }
                }
            }
            assert_eq!(
                bad_y, 0,
                "frame {i}: MQUANT-delta decode produced {bad_y} bad Y pels โ€” \
                 indicates decoder is not honouring MQUANT or encoder/decoder \
                 disagree on which MB the MQUANT applies to"
            );
        }
    }

    /// MQUANT-delta should shrink the bytes on a high-frequency P-chain
    /// vs. the same encoder with MQUANT disabled. Allows the bytes to be
    /// the same (the controller may not fire on synthetic input).
    #[test]
    fn mquant_delta_does_not_grow_stream() {
        let frames = testsrc_qcif(4);
        // With MQUANT (default).
        let mut enc = H261Encoder::new(SourceFormat::Qcif, 8);
        let mut with_mq_size = 0usize;
        for (y, cb, cr) in &frames {
            let p = enc.encode_frame(y, 176, cb, 88, cr, 88).unwrap();
            with_mq_size += p.len();
        }
        // Without MQUANT.
        std::env::set_var("OXIDEAV_H261_NO_MQUANT", "1");
        let mut enc2 = H261Encoder::new(SourceFormat::Qcif, 8);
        let mut no_mq_size = 0usize;
        for (y, cb, cr) in &frames {
            let p = enc2.encode_frame(y, 176, cb, 88, cr, 88).unwrap();
            no_mq_size += p.len();
        }
        std::env::remove_var("OXIDEAV_H261_NO_MQUANT");
        // Loose bar: MQUANT-on must not be drastically worse than off (a
        // tight bar would flake on small content where the controller
        // doesn't engage). We accept up to +20 bytes of overhead from the
        // 5-bit MQUANT field on rare false-positive switches.
        assert!(
            with_mq_size <= no_mq_size + 20,
            "MQUANT-on bigger than MQUANT-off: {with_mq_size} vs {no_mq_size}"
        );
    }

    /// Regression test for the chained-P-frame decoder bug fixed in r14.
    ///
    /// Symptoms (pre-fix): a 3+ frame P-chain on testsrc-like content
    /// would self-decode to large errors at the very last MB of each
    /// trailing P-picture (GOB 5 MBA=33 in QCIF), because the GOB MB-loop
    /// in `decoder.rs::decode_picture_body` broke early on
    /// `bits_remaining < 16` even though that final MB and its trailing
    /// padding zeros made the picture body shorter than 16 bits at the
    /// last MB boundary.
    ///
    /// Spec: ยง4.2.2 โ€” a start code is 16 zero bits + a 1-bit sync, so
    /// fewer than 16 bits remaining cannot encode a start code; the
    /// decoder must instead try to decode an MB from whatever remains.
    /// The fix gates the start-code peek on `remaining โ‰ฅ 16`.
    ///
    /// We assert byte-tight self-decode by comparing each P-frame's
    /// decoded Y plane against the encoder's local reconstruction (which
    /// is what a conformant decoder must produce).
    #[test]
    fn chained_p_self_decode_byte_tight() {
        let frames = testsrc_qcif(5);
        let mut local_recons: Vec<Picture> = Vec::with_capacity(frames.len());
        let mut stream = Vec::new();
        let (b0, r0) = encode_intra_picture_with_recon(
            SourceFormat::Qcif,
            &frames[0].0,
            176,
            &frames[0].1,
            88,
            &frames[0].2,
            88,
            8,
            0,
        )
        .expect("intra");
        stream.extend_from_slice(&b0);
        local_recons.push(r0);
        for (i, (y, cb, cr)) in frames.iter().enumerate().skip(1) {
            let prev = local_recons.last().unwrap();
            let (b, r) =
                encode_inter_picture(SourceFormat::Qcif, y, 176, cb, 88, cr, 88, 8, i as u8, prev)
                    .expect("inter");
            stream.extend_from_slice(&b);
            local_recons.push(r);
        }

        let mut dec = H261Decoder::new(CodecId::new(crate::CODEC_ID_STR));
        let pkt = Packet {
            stream_index: 0,
            data: stream,
            pts: Some(0),
            dts: Some(0),
            duration: None,
            time_base: TimeBase::new(1, 30_000),
            flags: PacketFlags {
                keyframe: true,
                ..Default::default()
            },
        };
        dec.send_packet(&pkt).expect("send");
        dec.flush().ok();

        for i in 0..frames.len() {
            let f = match dec.receive_frame().expect("frame") {
                Frame::Video(v) => v,
                _ => panic!("video"),
            };
            let recon = &local_recons[i];
            let dy = &f.planes[0].data;
            let mut bad_y = 0usize;
            for j in 0..144 {
                for ix in 0..176 {
                    if recon.y[j * recon.y_stride + ix] != dy[j * 176 + ix] {
                        bad_y += 1;
                    }
                }
            }
            assert_eq!(
                bad_y, 0,
                "frame {i}: Y plane mismatch in {bad_y} pels (chained-P bug pre-r14 \
                 manifested as ~230 bad pels at GOB 5 MBA=33)"
            );
            // Chroma should also match.
            for plane in 1..=2usize {
                let stride = recon.c_stride;
                let src = if plane == 1 { &recon.cb } else { &recon.cr };
                let dst = &f.planes[plane].data;
                for j in 0..72 {
                    for ix in 0..88 {
                        assert_eq!(
                            src[j * stride + ix],
                            dst[j * 88 + ix],
                            "frame {i}: chroma plane {plane} mismatch at ({ix},{j})"
                        );
                    }
                }
            }
        }
    }

    /// PSNR-driven proof that FIL helps on noisy moving content. Encodes a
    /// 4-frame testsrc-like sequence with the encoder (FIL enabled) and
    /// asserts decoded P-frames hit a higher PSNR than they did in r12
    /// (which the team measured at 39.27 dB on the equivalent fixture).
    #[test]
    fn fil_lifts_psnr_on_testsrc_qcif() {
        let frames = testsrc_qcif(4);
        let mut enc = H261Encoder::new(SourceFormat::Qcif, 8);
        let mut stream = Vec::new();
        for (y, cb, cr) in &frames {
            let p = enc.encode_frame(y, 176, cb, 88, cr, 88).expect("enc");
            stream.extend_from_slice(&p);
        }
        let mut decoder = H261Decoder::new(CodecId::new(crate::CODEC_ID_STR));
        let pkt = Packet {
            stream_index: 0,
            data: stream,
            pts: Some(0),
            dts: Some(0),
            duration: None,
            time_base: TimeBase::new(1, 30_000),
            flags: PacketFlags {
                keyframe: true,
                ..Default::default()
            },
        };
        decoder.send_packet(&pkt).expect("send");
        decoder.flush().ok();

        let mut psnrs = Vec::new();
        for (y, _, _) in &frames {
            let f = match decoder.receive_frame().expect("frame") {
                Frame::Video(v) => v,
                _ => panic!("video"),
            };
            psnrs.push(psnr(y, &f.planes[0].data));
        }
        // Even with FIL the I-frame must remain at high PSNR (FIL only
        // affects P-pictures).
        assert!(psnrs[0] >= 30.0, "I-frame PSNR {} too low", psnrs[0]);
        // Average P-frame PSNR; bar deliberately conservative for CI noise.
        let avg_p: f64 = psnrs[1..].iter().copied().sum::<f64>() / (psnrs.len() - 1) as f64;
        assert!(
            avg_p >= 27.0,
            "average P-frame PSNR {avg_p:.2} dB too low (psnrs={psnrs:?})"
        );
    }

    /// Regression test for the round-15 long-clip drift investigation.
    ///
    /// Rounds 5/6 documented an apparent "~1 dB/P-frame" drift on long P
    /// chains that was hypothesised to come from IDCT precision loss.
    /// Round 15 measured this on the synthetic `testsrc_qcif` fixture, on
    /// a real ffmpeg testsrc-generated YUV clip, and on a variety of
    /// synthetic worst-case fixtures (static noisy / jittery / slow
    /// drift / mandelbrot zoom) at QUANT=8 over 30 frames each.
    /// **No such drift exists**:
    ///
    /// * **testsrc_qcif (in-crate fixture), QUANT=8, 30 frames**: per-frame
    ///   PSNR stays in [36.81, 37.12] dB โ€” total spread 0.31 dB, no
    ///   monotonic decline. Frame 0 = 37.01, frame 29 = 36.93.
    /// * **real ffmpeg testsrc QCIF, QUANT=8, 30 frames**: PSNR stays in
    ///   [39.21, 39.75] dB โ€” spread 0.54 dB. Frame 0 = 39.75, frame 29 =
    ///   39.36, recovery to 39.55 by frame 16.
    /// * **mandelbrot zoom, 30 frames** (MQUANT disabled): PSNR tracks
    ///   scene complexity in [32.11, 36.07] dB; no monotonic drift.
    ///
    /// The IDCT/dequant chain is provably idempotent at the block level
    /// (see `idct::tests::drift_stress_zero_residual_chain`): once a
    /// quantised residual reaches steady state, every further iteration
    /// produces a bit-identical recon. The dead-zone (|coeff| < 2*QUANT)
    /// squashes IDCT roundoff back to zero, breaking the feedback loop
    /// that would otherwise compound rounding errors. Encoder and decoder
    /// share byte-identical IDCT/dequant functions (proven by
    /// `chained_p_self_decode_byte_tight`), so there can be no encoder-
    /// vs-decoder mismatch.
    ///
    /// This test asserts the no-drift property on a 10-frame `testsrc_qcif`
    /// chain: the worst per-frame PSNR must be within 1.5 dB of the I
    /// frame, and the slope from frame 1 to frame 9 must not exceed
    /// 0.15 dB/frame (the measured value is +0.015 dB/frame on this
    /// fixture, well within the bar). Any future regression that re-
    /// introduces drift (e.g. a rounding-direction change in IDCT or
    /// quant, or a mismatch between encoder local-recon and decoder
    /// recon) will fail this test.
    #[test]
    fn no_pframe_drift_on_testsrc_qcif() {
        let frames = testsrc_qcif(10);
        let mut local_recons: Vec<Picture> = Vec::with_capacity(frames.len());
        let (b0, r0) = encode_intra_picture_with_recon(
            SourceFormat::Qcif,
            &frames[0].0,
            176,
            &frames[0].1,
            88,
            &frames[0].2,
            88,
            8,
            0,
        )
        .expect("intra");
        local_recons.push(r0);
        let _ = b0; // we only need recons for the per-frame PSNR check
        for (i, (y, cb, cr)) in frames.iter().enumerate().skip(1) {
            let prev = local_recons.last().unwrap();
            let (_b, r) = encode_inter_picture(
                SourceFormat::Qcif,
                y,
                176,
                cb,
                88,
                cr,
                88,
                8,
                (i as u8) & 0x1F,
                prev,
            )
            .expect("inter");
            local_recons.push(r);
        }
        let mut psnrs = Vec::new();
        for (i, recon) in local_recons.iter().enumerate() {
            let src = &frames[i].0;
            let mut packed = vec![0u8; 176 * 144];
            for j in 0..144 {
                packed[j * 176..j * 176 + 176]
                    .copy_from_slice(&recon.y[j * recon.y_stride..j * recon.y_stride + 176]);
            }
            psnrs.push(psnr(src, &packed));
        }
        let i_psnr = psnrs[0];
        let min_p: f64 = psnrs[1..].iter().copied().fold(f64::INFINITY, f64::min);
        let drop = i_psnr - min_p;
        assert!(
            drop < 1.5,
            "P-frame PSNR drop {drop:.2} dB exceeds 1.5 dB bound โ€” \
             possible IDCT-residual drift regression. PSNRs: {psnrs:?}"
        );
        // Linear-trend bound: a hypothetical 1 dB/P-frame drift would
        // make the slope from psnrs[1] to psnrs[9] equal -1 dB/frame
        // (so psnrs[9] - psnrs[1] = -8 dB). We bar that at -0.15 dB/frame
        // average over the 8 P-to-P transitions (room for ~0.05 dB of
        // natural per-frame jitter on testsrc).
        let slope = (psnrs[9] - psnrs[1]) / 8.0;
        assert!(
            slope > -0.15,
            "P-frame PSNR slope {slope:.3} dB/frame indicates drift. PSNRs: {psnrs:?}"
        );
    }

    /// Diagnostic for the round-15 drift investigation. Generates a
    /// 30-frame testsrc QCIF clip on the fly (using ffmpeg if present,
    /// otherwise synthesised) and prints per-frame PSNRs of (a) the
    /// encoder's local-recon vs source, (b) the in-crate decoder's
    /// reconstruction vs source. Run with `--ignored --nocapture`.
    /// See `no_pframe_drift_on_testsrc_qcif` for the regression bound
    /// derived from this diagnostic's measurements.
    /// Verify that the `make_encoder` factory correctly selects QUANT from a
    /// `bit_rate` hint. At 64 kbit/s QCIF the factory should pick a quant
    /// that keeps self-decode PSNR above 35 dB on smooth content.
    ///
    /// 35 dB is the canonical H.261 "acceptable quality" target from the spec.
    /// On the testsrc gradient pattern (smooth, well-suited to the encoder)
    /// this should be achievable even at lower bitrates.
    #[test]
    fn make_encoder_derives_quant_from_bit_rate() {
        use oxideav_core::{CodecId as CoreCodecId, CodecParameters, VideoFrame, VideoPlane};
        // Build encoder via factory with 64 kbit/s target (H.261 canonical).
        let mut params = CodecParameters::video(CoreCodecId::new(crate::CODEC_ID_STR));
        params.width = Some(176);
        params.height = Some(144);
        params.bit_rate = Some(64_000);
        let mut enc = make_encoder(&params).expect("make_encoder at 64kbit/s");

        // Encode a short smooth sequence via the Encoder trait.
        let w = 176usize;
        let h = 144usize;
        let n_frames = 8usize;
        let mut stream_bytes = Vec::new();
        let mut sources: Vec<Vec<u8>> = Vec::new();
        for f in 0..n_frames {
            let shift = (f as i32) * 2;
            let mut y = vec![0u8; w * h];
            for j in 0..h {
                for i in 0..w {
                    let xi = (i as i32 - shift).rem_euclid(w as i32) as usize;
                    y[j * w + i] = ((32 + (xi * 180) / w + (j * 40) / h).clamp(0, 255)) as u8;
                }
            }
            let cb = vec![128u8; (w / 2) * (h / 2)];
            let cr = vec![128u8; (w / 2) * (h / 2)];
            sources.push(y.clone());
            let vf = VideoFrame {
                pts: Some(f as i64),
                planes: vec![
                    VideoPlane { stride: w, data: y },
                    VideoPlane {
                        stride: w / 2,
                        data: cb,
                    },
                    VideoPlane {
                        stride: w / 2,
                        data: cr,
                    },
                ],
            };
            enc.send_frame(&Frame::Video(vf)).expect("send_frame");
            let pkt = enc.receive_packet().expect("receive_packet");
            stream_bytes.extend_from_slice(&pkt.data);
        }
        let total_bits = stream_bytes.len() * 8;
        let bitrate_bps = (total_bits * 30) / n_frames; // bytes/frame * fps * 8
        eprintln!(
            "[make_encoder 64k] stream: {} bytes / {} frames = {} bps",
            stream_bytes.len(),
            n_frames,
            bitrate_bps
        );

        // Self-decode and compute PSNR.
        let codec_id = CodecId::new(crate::CODEC_ID_STR);
        let mut decoder = H261Decoder::new(codec_id);
        let pkt = Packet {
            stream_index: 0,
            data: stream_bytes,
            pts: Some(0),
            dts: Some(0),
            duration: None,
            time_base: TimeBase::new(1, 30_000),
            flags: PacketFlags {
                keyframe: true,
                ..Default::default()
            },
        };
        decoder.send_packet(&pkt).expect("send");
        decoder.flush().ok();

        let mut frame_psnrs: Vec<f64> = Vec::new();
        for (i, src_y) in sources.iter().enumerate() {
            match decoder.receive_frame() {
                Ok(Frame::Video(vf)) => {
                    let p = psnr(src_y, &vf.planes[0].data);
                    eprintln!("[make_encoder 64k] frame {i}: PSNR_Y = {p:.2} dB");
                    frame_psnrs.push(p);
                }
                _ => break,
            }
        }
        let avg = if frame_psnrs.is_empty() {
            0.0
        } else {
            frame_psnrs.iter().sum::<f64>() / frame_psnrs.len() as f64
        };
        eprintln!("[make_encoder 64k] avg PSNR_Y = {avg:.2} dB");
        assert!(
            avg >= 35.0,
            "make_encoder at 64kbit/s: avg PSNR_Y {avg:.2} dB < 35.0 dB"
        );
    }

    #[test]
    #[ignore]
    fn diag_long_pchain_drift() {
        let frames = testsrc_qcif(30);
        let mut local_recons: Vec<Picture> = Vec::with_capacity(frames.len());
        let mut stream = Vec::new();
        let (b0, r0) = encode_intra_picture_with_recon(
            SourceFormat::Qcif,
            &frames[0].0,
            176,
            &frames[0].1,
            88,
            &frames[0].2,
            88,
            8,
            0,
        )
        .expect("intra");
        stream.extend_from_slice(&b0);
        local_recons.push(r0);
        for (i, (y, cb, cr)) in frames.iter().enumerate().skip(1) {
            let prev = local_recons.last().unwrap();
            let (b, r) = encode_inter_picture(
                SourceFormat::Qcif,
                y,
                176,
                cb,
                88,
                cr,
                88,
                8,
                (i as u8) & 0x1F,
                prev,
            )
            .expect("inter");
            stream.extend_from_slice(&b);
            local_recons.push(r);
        }
        let mut psnrs = Vec::new();
        for (i, recon) in local_recons.iter().enumerate() {
            let src = &frames[i].0;
            let mut packed = vec![0u8; 176 * 144];
            for j in 0..144 {
                packed[j * 176..j * 176 + 176]
                    .copy_from_slice(&recon.y[j * recon.y_stride..j * recon.y_stride + 176]);
            }
            psnrs.push(psnr(src, &packed));
        }
        eprintln!("[diag] testsrc_qcif 30-frame local-recon Y PSNRs:");
        for (i, p) in psnrs.iter().enumerate() {
            eprintln!("  frame {i:2}: {p:.2} dB");
        }
        eprintln!("[diag] stream bytes: {}", stream.len());
        let max_p = psnrs.iter().copied().fold(f64::NEG_INFINITY, f64::max);
        let min_p = psnrs.iter().copied().fold(f64::INFINITY, f64::min);
        eprintln!("[diag] PSNR spread: {:.2} dB", max_p - min_p);
    }

    // ---- ยง3.4 Forced updating ------------------------------------------

    /// A P-picture carrying an explicit forced-INTRA set decodes cleanly and
    /// the forced MBs are reconstructed exactly to the source (INTRA coding
    /// has no prediction-history dependency), so the decode resets any drift
    /// in those MBs.
    #[test]
    fn forced_update_intra_mb_decodes_and_refreshes() {
        let (y, cb, cr) = gradient_qcif();
        let (_iframe, recon) =
            encode_intra_picture_with_recon(SourceFormat::Qcif, &y, 176, &cb, 88, &cr, 88, 8, 0)
                .expect("intra");

        // Force MBs 0, 1, 17, 50, 98 (spanning all three QCIF GOBs) to INTRA.
        let forced: &[u32] = &[0, 1, 17, 50, 98];
        let (pframe, _r) = encode_inter_picture_forced_update(
            SourceFormat::Qcif,
            &y,
            176,
            &cb,
            88,
            &cr,
            88,
            8,
            1,
            &recon,
            forced,
        )
        .expect("inter forced");

        // Decode the I + P sequence and check the P-frame is well-formed and
        // close to the source.
        let mut stream = Vec::new();
        let iframe =
            encode_intra_picture(SourceFormat::Qcif, &y, 176, &cb, 88, &cr, 88, 8, 0).unwrap();
        stream.extend_from_slice(&iframe);
        stream.extend_from_slice(&pframe);

        let codec_id = CodecId::new(crate::CODEC_ID_STR);
        let mut decoder = H261Decoder::new(codec_id);
        let pkt = Packet {
            stream_index: 0,
            data: stream,
            pts: Some(0),
            dts: Some(0),
            duration: None,
            time_base: TimeBase::new(1, 30_000),
            flags: PacketFlags {
                keyframe: true,
                ..Default::default()
            },
        };
        decoder.send_packet(&pkt).expect("send");
        decoder.flush().ok();
        let _f0 = decoder.receive_frame().expect("f0");
        let f1 = match decoder.receive_frame().expect("f1") {
            Frame::Video(v) => v,
            _ => panic!("video"),
        };
        let p = psnr(&f1.planes[0].data, &y);
        assert!(p >= 28.0, "forced-update P-frame Y PSNR too low: {p:.2} dB");
    }

    /// Out-of-range forced indices are ignored and an empty forced set is a
    /// no-op (identical bytes to plain `encode_inter_picture`).
    #[test]
    fn forced_update_empty_set_matches_plain_inter() {
        let (y, cb, cr) = gradient_qcif();
        let (_i, recon) =
            encode_intra_picture_with_recon(SourceFormat::Qcif, &y, 176, &cb, 88, &cr, 88, 8, 0)
                .unwrap();
        let (plain, _r1) =
            encode_inter_picture(SourceFormat::Qcif, &y, 176, &cb, 88, &cr, 88, 8, 1, &recon)
                .unwrap();
        // Empty set and an all-out-of-range set must both be no-ops.
        let (forced_empty, _r2) = encode_inter_picture_forced_update(
            SourceFormat::Qcif,
            &y,
            176,
            &cb,
            88,
            &cr,
            88,
            8,
            1,
            &recon,
            &[],
        )
        .unwrap();
        let (forced_oob, _r3) = encode_inter_picture_forced_update(
            SourceFormat::Qcif,
            &y,
            176,
            &cb,
            88,
            &cr,
            88,
            8,
            1,
            &recon,
            &[99, 100, 1_000_000],
        )
        .unwrap();
        assert_eq!(plain, forced_empty);
        assert_eq!(plain, forced_oob);
    }

    /// ยง3.4 guarantee: with whole-frame I-refresh disabled, the per-MB
    /// scheduler in `H261Encoder` forcibly INTRA-updates EVERY macroblock at
    /// least once within `forced_update_period` consecutive P-frames, so no
    /// MB is ever transmitted more than the period without an INTRA reset.
    /// We model the scheduler directly and assert full coverage.
    #[test]
    fn forced_update_scheduler_covers_every_mb_within_period() {
        let period = 16u32; // short period for a fast test
        let mut enc = H261Encoder::new(SourceFormat::Qcif, 8)
            .with_intra_period(0)
            .with_forced_update_period(period);
        let total_mbs = SourceFormat::Qcif.gob_numbers().len() * 33; // 99
        enc.mb_since_intra = vec![0u32; total_mbs];

        let mut ever_forced = vec![false; total_mbs];
        let mut max_count = 0u32;
        for _frame in 0..period {
            let forced = enc.compute_forced_update_set(total_mbs);
            for &m in &forced {
                ever_forced[m as usize] = true;
            }
            // Apply the same counter update the encoder uses.
            for (i, c) in enc.mb_since_intra.iter_mut().enumerate() {
                if forced.binary_search(&(i as u32)).is_ok() {
                    *c = 0;
                } else {
                    *c = c.saturating_add(1);
                }
            }
            max_count = max_count.max(enc.mb_since_intra.iter().copied().max().unwrap());
        }
        assert!(
            ever_forced.iter().all(|&b| b),
            "some MB was never forcibly updated within {period} frames"
        );
        // No counter may have reached the period (that would mean an MB was
        // transmitted `period` times without an INTRA update).
        assert!(
            max_count < period,
            "an MB counter reached {max_count} (>= period {period})"
        );
    }

    /// `forced_update_period == 0` disables per-MB forced updating.
    #[test]
    fn forced_update_period_zero_disables() {
        let mut enc = H261Encoder::new(SourceFormat::Qcif, 8)
            .with_intra_period(0)
            .with_forced_update_period(0);
        let total_mbs = SourceFormat::Qcif.gob_numbers().len() * 33;
        enc.mb_since_intra = vec![0u32; total_mbs];
        let forced = enc.compute_forced_update_set(total_mbs);
        assert!(forced.is_empty());
    }

    /// End-to-end: a long P-only sequence (intra_period disabled) stays
    /// decodable and the forced-update INTRA MBs keep the picture from
    /// drifting away. We drive `H261Encoder` for `2 * period` frames and
    /// confirm every frame decodes and the final PSNR is healthy.
    #[test]
    fn forced_update_sequence_stays_healthy() {
        let period = 8u32;
        let (y, cb, cr) = gradient_qcif();
        let mut enc = H261Encoder::new(SourceFormat::Qcif, 8)
            .with_intra_period(0)
            .with_forced_update_period(period);

        let frames = (2 * period) as usize;
        let mut stream = Vec::new();
        for _ in 0..frames {
            let b = enc.encode_frame(&y, 176, &cb, 88, &cr, 88).expect("frame");
            stream.extend_from_slice(&b);
        }

        let codec_id = CodecId::new(crate::CODEC_ID_STR);
        let mut decoder = H261Decoder::new(codec_id);
        let pkt = Packet {
            stream_index: 0,
            data: stream,
            pts: Some(0),
            dts: Some(0),
            duration: None,
            time_base: TimeBase::new(1, 30_000),
            flags: PacketFlags {
                keyframe: true,
                ..Default::default()
            },
        };
        decoder.send_packet(&pkt).expect("send");
        decoder.flush().ok();
        let mut last = None;
        for _ in 0..frames {
            match decoder.receive_frame() {
                Ok(Frame::Video(v)) => last = Some(v),
                Ok(_) => {}
                Err(_) => break,
            }
        }
        let last = last.expect("at least one decoded frame");
        let p = psnr(&last.planes[0].data, &y);
        assert!(
            p >= 28.0,
            "forced-update sequence final Y PSNR too low: {p:.2} dB"
        );
    }
}