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
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
/*
 * Copyright (c) Radzivon Bartoshyk 6/2026. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification,
 * are permitted provided that the following conditions are met:
 *
 * 1.  Redistributions of source code must retain the above copyright notice, this
 * list of conditions and the following disclaimer.
 *
 * 2.  Redistributions in binary form must reproduce the above copyright notice,
 * this list of conditions and the following disclaimer in the documentation
 * and/or other materials provided with the distribution.
 *
 * 3.  Neither the name of the copyright holder nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

use crate::env::BlockContext;
use crate::headers::{AdaptiveBoolean, FrameHeader, MAX_SEGMENTS, RestorationType};
use crate::internal::{LoopFilterState, NsWienerBank, ScalableMotionParams};
use crate::intops::{imax, imin};
use crate::levels::{Av2Block, BlockSize, Mv, RefPair, TIP_FRAME};

use crate::msac::{MsacBackend, MsacReader};

use crate::pixel::{BitDepth, Pixel};
use crate::quantizer::dq_lookup;
use crate::tables::{NS_WIENER_COEF_RANGE_UV, NS_WIENER_COEF_RANGE_Y};
use crate::{TealdustError, refmvs};

mod block_decode;
mod frame_setup;
mod loopfilter;
pub(crate) mod lr_cdef_line_save;
mod recon_inter;
mod recon_intra;
mod recon_opfl;
mod syntax;
pub(crate) use block_decode::*;
pub(crate) use frame_setup::*;
pub(crate) use loopfilter::*;
pub(crate) use recon_inter::*;
pub(crate) use recon_intra::*;
pub(crate) use recon_opfl::*;
pub(crate) use syntax::*;

pub(crate) fn init_wiener(frame_hdr: &FrameHeader, lf: &mut LoopFilterState) {
    let rtype = frame_hdr.restoration.p[0].restoration_type;
    if rtype == RestorationType::None as u8 {
        return;
    }

    let qidx = frame_hdr.quant.yac as i32;
    lf.base_q = dq_lookup(qidx);

    let idx = if qidx < 130 {
        0
    } else if qidx < 190 {
        1
    } else if qidx < 220 {
        2
    } else {
        3
    };
    lf.wiener_idx = idx;

    if rtype == RestorationType::NsWiener as u8 || rtype == RestorationType::Switchable as u8 {
        let num_classes_idx = frame_hdr.restoration.p[0].ns.num_classes_idx as usize;
        if num_classes_idx > 0 {
            lf.ns_subclass_class_idx = Some(num_classes_idx - 1);
        } else {
            lf.ns_subclass_class_idx = None;
        }
    } else {
        lf.ns_subclass_class_idx = None;
    }
}

pub fn compute_restore_planes(frame_hdr: &FrameHeader) -> i32 {
    let has_y = frame_hdr.restoration.p[0].restoration_type != RestorationType::None as u8
        || frame_hdr.gdf.enabled != AdaptiveBoolean::Off;
    let has_u = frame_hdr.restoration.p[1].restoration_type != RestorationType::None as u8;
    let has_v = frame_hdr.restoration.p[2].restoration_type != RestorationType::None as u8;
    (has_y as i32) | ((has_u as i32) << 1) | ((has_v as i32) << 2)
}

pub fn compute_gdf_ref_dst_idx(frame_hdr: &FrameHeader, absrefdist: &[u8; 7]) -> i32 {
    if frame_hdr.gdf.enabled == AdaptiveBoolean::Off {
        return 0;
    }
    let is_inter_or_switch = (frame_hdr.frame_type as u8) & 1 != 0;
    if !is_inter_or_switch {
        return 0;
    }
    let mut max_dist = 0i32;
    for i in 0..imin(frame_hdr.n_ref_frames as i32, 2) as usize {
        max_dist = imax(max_dist, absrefdist[i] as i32);
    }
    static REF_DST_IDX_TBL: [i32; 12] = [5, 1, 2, 3, 3, 3, 4, 4, 4, 4, 4, 5];
    REF_DST_IDX_TBL[imin(max_dist, 11) as usize]
}

/// Superblock geometry needed to read its loop-restoration unit info.
#[derive(Clone, Copy)]
pub(crate) struct SbLrGeom {
    pub(crate) bx: i32,
    pub(crate) by: i32,
    pub(crate) col_start: i32,
    pub(crate) col_end: i32,
    pub(crate) row_start: i32,
    pub(crate) row_end: i32,
    pub(crate) ss_hor: i32,
    pub(crate) ss_ver: i32,
    pub(crate) sbsz: i32,
    pub(crate) sb256w: i32,
}

/// The chroma loop-restoration read deferred to between the SDP luma and
/// chroma partition trees: with a 64x64 superblock root in an intra frame the
/// two trees split at the root, and AVM reads each tree's restoration info at
/// its own root (dav2d `read_sb_restoration` in `decode_sb`).
pub(crate) struct SdpLrRead<'a> {
    pub(crate) lr_mask: &'a mut [crate::lf_mask::Av2Restoration],
    pub(crate) bank: &'a mut [NsWienerBank; 3],
    pub(crate) frame_hdr: &'a FrameHeader,
    pub(crate) geom: SbLrGeom,
}

/// Reads the loop-restoration unit info of `planes` for the superblock at
/// `g.bx`/`g.by`.
pub(crate) fn read_sb_restoration<const UPDATE_CDF: bool, M: MsacReader<UPDATE_CDF>>(
    msac: &mut M,
    cdf_m: &mut crate::cdf::CdfModeContext,
    lr_mask: &mut [crate::lf_mask::Av2Restoration],
    bank: &mut [NsWienerBank; 3],
    frame_hdr: &FrameHeader,
    g: &SbLrGeom,
    planes: std::ops::Range<usize>,
) {
    for p in planes {
        let (ss_ver, ss_hor) = if p == 0 { (0, 0) } else { (g.ss_ver, g.ss_hor) };
        let rtype_u8 = frame_hdr.restoration.p[p].restoration_type;
        if rtype_u8 == RestorationType::None as u8 {
            continue;
        }
        // Restoration is active for this plane, so the LR mask is
        // allocated for valid streams. Guard against an empty mask (a
        // degenerate frame from a malformed header) before indexing it.
        if lr_mask.is_empty() || lr_mask[0].lr[p].is_empty() {
            continue;
        }
        let tx = (4 * (g.bx - g.col_start)) >> ss_hor;
        let ty = (4 * (g.by - g.row_start)) >> ss_ver;
        let unit_sz_log2 = frame_hdr.restoration.unit_size[(p != 0) as usize] as i32;
        let unit_sz = 1i32 << unit_sz_log2;
        let mask = unit_sz - 1;
        if (tx | ty) & mask != 0 {
            continue;
        }
        let tw = (g.col_end * 4) >> ss_hor;
        let th = (g.row_end * 4) >> ss_ver;
        let half_unit = unit_sz >> 1;
        let fx = (4 * g.bx) >> ss_hor;
        let fy = (g.by * 4) >> ss_ver;
        if (ty != 0 && fy + half_unit > th) || (tx != 0 && fx + half_unit > tw) {
            continue;
        }

        let frame_type = match rtype_u8 {
            1 => RestorationType::PcWiener,
            2 => RestorationType::NsWiener,
            3 => RestorationType::Switchable,
            _ => RestorationType::None,
        };

        let sbw = g.sbsz >> ss_hor;
        let sbh = g.sbsz >> ss_ver;
        let lruw = imax(1, imin(tw - fx + half_unit, sbw) >> unit_sz_log2);
        let lruh = imax(1, imin(th - fy + half_unit, sbh) >> unit_sz_log2);
        for _y in 0..lruh {
            for x in 0..lruw {
                // Derive the (slot, unit_idx) of this restoration unit from
                // its frame position, mirroring the filter side
                // (looprestoration.rs `lr_sbrow`/`lr_stripe`): the filter
                // derives both the SB-256 slot and the 4x4 local unit index
                // from the unit's *luma-scale* top-left, so the read side
                // must do the same for the two to agree when an SB spans
                // more than one unit (unit_size < superblock size).
                //
                // `fx`/`fy` are this SB's subsampled top-left; the unit's
                // subsampled position is `fx + x*unit_sz` / `fy + _y*unit_sz`.
                // Shift back to luma scale (`<< ss_*`) before the >>8 (slot)
                // and >>6 (local 64-grid index) reductions, exactly as the
                // filter does (`aligned_unit_pos <<= ss_ver`; horizontal uses
                // `shift_hor = 8 - ss_hor`). At x == _y == 0 this reduces to
                // the previous `sb_idx` / `start_unit_idx` byte-for-byte, so
                // single-unit streams are unchanged.
                let upx = (fx + x * unit_sz) << ss_hor;
                let upy = (fy + _y * unit_sz) << ss_ver;
                let slot = (upy >> 8) * g.sb256w + (upx >> 8);
                let uidx = (((upy >> 6) & 3) << 2) | ((upx >> 6) & 3);
                // For valid streams these indices are always in range;
                // clamp so a malformed unit-size/geometry can't index the
                // LR mask out of bounds (the entropy read still happens, so
                // MSAC stays in sync). No-op for valid input.
                let unit_idx = (uidx.max(0) as usize).min(lr_mask[0].lr[p].len() - 1);
                let lr_slot = (slot.max(0) as usize).min(lr_mask.len() - 1);
                let ns_plane = &frame_hdr.restoration.p[p].ns;
                read_restoration_info(
                    &mut *msac,
                    &mut *cdf_m,
                    &mut bank[p],
                    &mut lr_mask[lr_slot].lr[p][unit_idx],
                    p,
                    frame_type,
                    ns_plane,
                );
            }
        }
    }
}

pub(crate) fn init_ns_wiener_bank(bank: &mut NsWienerBank, pl: usize, n_classes: usize) {
    bank.bank_size = [0; 16];
    bank.bank_idx = [0; 16];
    let cf_range: &[[i8; 2]] = if pl > 0 {
        &NS_WIENER_COEF_RANGE_UV
    } else {
        &NS_WIENER_COEF_RANGE_Y
    };
    let n_coeffs = 16 + if pl > 0 { 2 } else { 0 };
    for n in 0..n_classes {
        for m in 0..n_coeffs {
            bank.filter[0][n][m] = cf_range[m][1] + ((1i8 << cf_range[m][0]) >> 1);
        }
    }
}

#[inline]
fn try_clone_vec<T: Clone>(src: &[T]) -> Result<Vec<T>, ()> {
    let mut out = Vec::new();
    out.try_reserve_exact(src.len()).map_err(|_| ())?;
    out.extend_from_slice(src);
    Ok(out)
}

pub(crate) fn init_start_of_tile_row(
    buf: &mut Vec<u8>,
    sbh: i32,
    tile_rows: u8,
    row_start_sb: &[u16],
) -> Result<(), ()> {
    let sbh = usize::try_from(sbh).map_err(|_| ())?;
    if buf.len() != sbh {
        if sbh > buf.len() {
            buf.try_reserve_exact(sbh - buf.len()).map_err(|_| ())?;
        }
        buf.resize(sbh, 0);
    } else {
        buf.fill(0);
    }
    let mut sby = 0usize;
    for tile_row in 0..tile_rows as usize {
        if sby >= sbh {
            break;
        }
        buf[sby] = ((tile_row << 1) | 1) as u8;
        sby += 1;
        // For valid streams row_start_sb[tile_row + 1] <= sbh; clamp the bound so
        // a malformed tiling whose row starts exceed the frame height cannot
        // write past the sbh-sized buffer. No-op for valid input.
        let end = (row_start_sb[tile_row + 1] as usize).min(sbh);
        while sby < end {
            buf[sby] = (tile_row << 1) as u8;
            sby += 1;
        }
    }
    Ok(())
}

pub fn neg_deinterleave(diff: i32, r: i32, max: i32) -> i32 {
    if r == 0 {
        return diff;
    }
    if r >= max - 1 {
        return max - diff - 1;
    }
    if 2 * r < max {
        if diff <= 2 * r {
            if diff & 1 != 0 {
                r + ((diff + 1) >> 1)
            } else {
                r - (diff >> 1)
            }
        } else {
            diff
        }
    } else {
        if diff <= 2 * (max - r - 1) {
            if diff & 1 != 0 {
                r + ((diff + 1) >> 1)
            } else {
                r - (diff >> 1)
            }
        } else {
            max - (diff + 1)
        }
    }
}

pub(crate) fn init_quant_tables(
    frame_hdr: &FrameHeader,
    qidx: i32,
    dq: &mut [[[u32; 2]; 3]; MAX_SEGMENTS],
    qmax: i32,
) {
    let n = if frame_hdr.segmentation.enabled != 0 {
        8
    } else {
        1
    };
    for i in 0..n {
        let yac = if frame_hdr.segmentation.enabled != 0 {
            qidx + frame_hdr.segmentation.d.delta_q[i] as i32
        } else {
            qidx
        };
        let ydc = yac + frame_hdr.quant.ydc_delta as i32;
        let uac = yac + frame_hdr.quant.uac_delta as i32;
        let udc = yac + frame_hdr.quant.udc_delta as i32;
        let vac = yac + frame_hdr.quant.vac_delta as i32;
        let vdc = yac + frame_hdr.quant.vdc_delta as i32;

        // AVM clamps the effective qindex to the bit-depth MAXQ (255/303/351).
        dq[i][0][0] = dq_lookup(ydc.min(qmax)) as u32;
        dq[i][0][1] = dq_lookup(yac.min(qmax)) as u32;
        dq[i][1][0] = dq_lookup(udc.min(qmax)) as u32;
        dq[i][1][1] = dq_lookup(uac.min(qmax)) as u32;
        dq[i][2][0] = dq_lookup(vdc.min(qmax)) as u32;
        dq[i][2][1] = dq_lookup(vac.min(qmax)) as u32;
    }
}

/// Recompute the per-segment dequant tables for a single qindex (used by the
/// per-superblock delta-q path; mirrors `init_quant_tables` with state pulled
/// from `SbFrameInfo` instead of `FrameHeader`).
pub fn init_quant_tables_fi(
    fi: &SbFrameInfo,
    qidx: i32,
    dq: &mut [[[u32; 2]; 3]; MAX_SEGMENTS],
    qmax: i32,
) {
    let n = if fi.seg_enabled { 8 } else { 1 };
    for i in 0..n {
        let yac = if fi.seg_enabled {
            qidx + fi.seg_delta_q[i] as i32
        } else {
            qidx
        };
        let ydc = yac + fi.q_ydc_delta;
        let uac = yac + fi.q_uac_delta;
        let udc = yac + fi.q_udc_delta;
        let vac = yac + fi.q_vac_delta;
        let vdc = yac + fi.q_vdc_delta;

        // AVM clamps the effective qindex to the bit-depth MAXQ (255/303/351).
        dq[i][0][0] = dq_lookup(ydc.min(qmax)) as u32;
        dq[i][0][1] = dq_lookup(yac.min(qmax)) as u32;
        dq[i][1][0] = dq_lookup(udc.min(qmax)) as u32;
        dq[i][1][1] = dq_lookup(uac.min(qmax)) as u32;
        dq[i][2][0] = dq_lookup(vdc.min(qmax)) as u32;
        dq[i][2][1] = dq_lookup(vac.min(qmax)) as u32;
    }
}

pub(crate) const N_SWITCHABLE_FILTERS: usize = 3;

pub(crate) fn reset_context(ctx: &mut BlockContext, keyframe: bool, is_tip_frame: bool) {
    ctx.tx_lpf_y.fill(3);
    ctx.tx_lpf_uv.fill(2);
    if is_tip_frame {
        return;
    }
    ctx.midx.fill(0xff);
    ctx.intra.fill(keyframe as u8);
    ctx.uvmode.fill(0); // DC_PRED
    if keyframe {
        ctx.mode.fill(0); // DC_PRED
    }
    ctx.partition[0].fill(0);
    ctx.partition[1].fill(0);
    ctx.skip_txfm.fill(0);
    ctx.skip_mode.fill(0);
    if !keyframe {
        ctx.reference[0].fill(-1);
        ctx.reference[1].fill(-1);
        ctx.comp_type.fill(0);
        ctx.mode.fill(13); // NEARMV
    }
    ctx.mrl.fill(0);
    ctx.lcoef.fill(0x40);
    ctx.ccoef[0].fill(0x40);
    ctx.ccoef[1].fill(0x40);
    ctx.filter.fill(N_SWITCHABLE_FILTERS as u8);
    ctx.seg_pred.fill(0);
    ctx.pal_sz.fill(0);
}

#[derive(Default)]
pub struct SbFrameInfo {
    pub bw: i32,
    pub bh: i32,
    pub ss_ver: i32,
    pub ss_hor: i32,
    pub root_bs: BlockSize,
    pub is_inter_or_switch: bool,
    pub sdp: bool,
    pub ext_sdp: bool,
    pub ext_partitions: bool,
    pub uneven_4way: bool,
    pub max_pb_aspect_ratio_log2: u8,
    pub n_passes: i32,
    // Segmentation
    pub seg_enabled: bool,
    pub seg_update_map: bool,
    pub seg_temporal: bool,
    pub seg_preskip: bool,
    pub seg_ext: bool,
    pub seg_last_active_segid: u8,
    pub seg_globalmv_mask: u16,
    pub seg_skip_mask: u16,
    pub seg_lossless: [u8; crate::headers::MAX_SEGMENTS],
    // Delta-q (per-superblock)
    pub delta_q_present: bool,
    pub delta_q_res_log2: u8,
    pub quant_yac: i32,
    pub sb128: i32,
    pub b4_stride: isize,
    // Quantizer deltas, needed to recompute per-SB dequant tables on delta-q.
    pub q_ydc_delta: i32,
    pub q_uac_delta: i32,
    pub q_udc_delta: i32,
    pub q_vac_delta: i32,
    pub q_vdc_delta: i32,
    pub seg_delta_q: [i16; crate::headers::MAX_SEGMENTS],
    // GDF / CDEF-index / CCSO (read at SB / 64x64 boundaries, before delta-q)
    pub gdf_enabled: crate::headers::AdaptiveBoolean,
    /// log2 of the GDF unit size in 64px units.
    pub gdf_sz_log2: i32,
    pub cur_w: i32,
    pub cur_h: i32,
    pub cdef_enabled: bool,
    pub cdef_on_skiptx: bool,
    pub cdef_n_strengths: u8,
    pub ccso_enabled: [bool; 3],
    pub ccso_sb_reuse: [bool; 3],
    /// Base-2 CCSO unit size in luma pixels. Mirrors AVM's
    /// get_ccso_unit_size_log2_adaptive_tile() / spec CcsoLumaSizeLog2.
    pub ccso_unit_log2: i32,
    /// Number of CCSO units per frame row, used for current/previous ccsomap indexing.
    pub ccso_unit_w: i32,
    // Frame flags
    pub skip_mode_enabled: bool,
    pub allow_intrabc: bool,
    pub any_lossless: bool,
    pub has_chroma_layout: bool,
    // Sequence features
    pub idtx_intra: bool,
    pub mrls: bool,
    pub mhccp: bool,
    pub cfl: bool,
    pub allow_screen_content_tools: bool,
    pub intra_dip: bool,
    pub force_integer_mv: bool,
    pub max_bvp_drl_bits: u8,
    pub max_drl_bits: u8,
    pub bawp: bool,
    pub intra_bawp: bool,
    pub txfm_switchable: bool,
    pub skip_mode_refs: RefPair,
    pub n_ref_frames: u8,
    pub warp_motion: bool,
    pub motion_modes: u8,
    pub adaptive_mvd: bool,
    pub flex_mvres: bool,
    pub mv_precision: u8,
    pub mvd_sign_derive: bool,
    pub tip_frame_mode: u8,
    /// `frame_hdr->tip.global_wtd_idx` — selects the TIP block CWP weight from
    pub tip_global_wtd_idx: u8,
    pub six_param_warp_delta: bool,
    pub subpel_filter_mode: u8,
    pub switchable_comp_refs: bool,
    pub num_same_ref_comp: u8,
    pub refdir: [u8; 8],
    pub refdist: [i8; 8],
    pub opfl_refine_type: u8,
    pub masked_compound: bool,
    pub cwp: bool,
    pub refine_mv_enabled: bool,
    pub absrefdist: [u8; 8],
    /// (`comp_type`) neighbour context. -1/-2 sentinel when no future ref.
    pub furthest_future_refidx: i8,
    /// `f->rf.tip.ref` (the TIP reference pair). Used by `get_compref_ctx` to
    /// match TIP-coded neighbours against the current block's compound refs.
    pub tip: RefPair,
    // Tile bounds
    pub tile_col_start: i32,
    pub tile_col_end: i32,
    pub tile_row_start: i32,
    pub tile_row_end: i32,
    pub sb_step: i32,
}

pub struct SbFrameInfoArgs<'a> {
    pub seq_hdr: &'a crate::headers::SequenceHeader,
    pub frame_hdr: &'a FrameHeader,
    pub bw: i32,
    pub bh: i32,
    pub root_bs: BlockSize,
    pub sb_step: i32,
    pub n_passes: i32,
    pub refdir: [u8; 8],
    pub refdist: &'a [i8; 7],
    pub absrefdist: &'a [u8; 7],
    pub skip_mode_refs: RefPair,
    pub tile_col_start: i32,
    pub tile_col_end: i32,
    pub tile_row_start: i32,
    pub tile_row_end: i32,
    pub furthest_future_refidx: i8,
    pub tip: RefPair,
}

/// GDF unit size (log2, in 64px units): the SB size when
/// `gdf_unit_matches_sbsz`, otherwise at least 128px, dropping back to 64px
/// when a tile boundary falls on an odd 64px SB so units never cross tiles.
pub(crate) fn gdf_unit_log2_from_headers(
    seq_hdr: &crate::headers::SequenceHeader,
    frame_hdr: &FrameHeader,
) -> i32 {
    let sb128 = frame_hdr.sb128 as i32;
    let log2 = imax((!seq_hdr.gdf_unit_matches_sbsz) as i32, sb128);
    if !seq_hdr.gdf_unit_matches_sbsz && sb128 == 0 {
        let tiles = &frame_hdr.tiling.t;
        let odd_col = tiles.col_start_sb[1..tiles.cols as usize]
            .iter()
            .any(|&s| s & 1 != 0);
        let odd_row = tiles.row_start_sb[1..tiles.rows as usize]
            .iter()
            .any(|&s| s & 1 != 0);
        if odd_col || odd_row {
            return 0;
        }
    }
    log2
}

pub(crate) fn ccso_unit_log2_from_headers(
    seq_hdr: &crate::headers::SequenceHeader,
    frame_hdr: &FrameHeader,
) -> i32 {
    const CCSO_LUMA_SIZE_LOG2: i32 = 8;
    let sb_size_log2 = 6 + frame_hdr.sb128 as i32;

    if seq_hdr.ccso_unit_matches_sbsz {
        return sb_size_log2;
    }

    let tiles = &frame_hdr.tiling.t;
    if tiles.cols == 1 && tiles.rows == 1 {
        return CCSO_LUMA_SIZE_LOG2;
    }

    if sb_size_log2 >= CCSO_LUMA_SIZE_LOG2 {
        return sb_size_log2;
    }

    let mut e2 = 0i32;
    let mut e4 = 0i32;
    for i in 0..tiles.cols.saturating_sub(1) as usize {
        let size = tiles.col_start_sb[i + 1] as i32 - tiles.col_start_sb[i] as i32;
        e2 += size & 1;
        e4 += size & 3;
    }
    for i in 0..tiles.rows.saturating_sub(1) as usize {
        let size = tiles.row_start_sb[i + 1] as i32 - tiles.row_start_sb[i] as i32;
        e2 += size & 1;
        e4 += size & 3;
    }

    if e4 == 0 {
        imin(sb_size_log2 + 2, CCSO_LUMA_SIZE_LOG2)
    } else if e2 == 0 {
        imin(sb_size_log2 + 1, CCSO_LUMA_SIZE_LOG2)
    } else {
        sb_size_log2
    }
}

impl SbFrameInfo {
    /// Build the per-superblock frame info bundle from the live sequence and
    /// frame headers plus the frame-level geometry and reference state.
    ///
    /// `refdir`/`refdist`/`absrefdist`/`skip_mode_refs` are precomputed on the
    /// `FrameContext` (see `refmvs::init_frame`); the 7-element refmvs arrays are
    /// zero-padded into the 8-element layout this struct uses.
    pub fn from_frame(args: SbFrameInfoArgs<'_>) -> Self {
        let SbFrameInfoArgs {
            seq_hdr,
            frame_hdr,
            bw,
            bh,
            root_bs,
            sb_step,
            n_passes,
            refdir,
            refdist,
            absrefdist,
            skip_mode_refs,
            tile_col_start,
            tile_col_end,
            tile_row_start,
            tile_row_end,
            furthest_future_refidx,
            tip,
        } = args;
        let mut refdist8 = [0i8; 8];
        refdist8[..7].copy_from_slice(refdist);
        let mut absrefdist8 = [0u8; 8];
        absrefdist8[..7].copy_from_slice(absrefdist);

        let ccso_unit_log2 = ccso_unit_log2_from_headers(seq_hdr, frame_hdr);
        let ccso_unit_mi = 1 << (ccso_unit_log2 - 2);
        let ccso_unit_w = (bw + ccso_unit_mi - 1) / ccso_unit_mi;

        SbFrameInfo {
            bw,
            bh,
            ss_ver: seq_hdr.ss_ver as i32,
            ss_hor: seq_hdr.ss_hor as i32,
            root_bs,
            is_inter_or_switch: frame_hdr.is_inter_or_switch(),
            sdp: seq_hdr.sdp,
            ext_sdp: seq_hdr.ext_sdp,
            ext_partitions: seq_hdr.ext_partitions,
            uneven_4way: seq_hdr.uneven_4way_partitions,
            max_pb_aspect_ratio_log2: seq_hdr.max_pb_aspect_ratio_log2,
            n_passes,
            seg_enabled: frame_hdr.segmentation.enabled != 0,
            seg_update_map: frame_hdr.segmentation.update_map != 0,
            seg_temporal: frame_hdr.segmentation.temporal != 0,
            seg_preskip: frame_hdr.segmentation.preskip != 0,
            seg_ext: seq_hdr.segmentation.ext,
            seg_last_active_segid: frame_hdr.segmentation.last_active_segid as u8,
            seg_globalmv_mask: frame_hdr.segmentation.d.globalmv_mask,
            seg_skip_mask: frame_hdr.segmentation.d.skip_mask,
            seg_lossless: frame_hdr.segmentation.lossless,
            delta_q_present: frame_hdr.delta.q.present != 0,
            delta_q_res_log2: frame_hdr.delta.q.res_log2,
            quant_yac: frame_hdr.quant.yac as i32,
            sb128: frame_hdr.sb128 as i32,
            b4_stride: ((bw + 63) & !63) as isize,
            q_ydc_delta: frame_hdr.quant.ydc_delta as i32,
            q_uac_delta: frame_hdr.quant.uac_delta as i32,
            q_udc_delta: frame_hdr.quant.udc_delta as i32,
            q_vac_delta: frame_hdr.quant.vac_delta as i32,
            q_vdc_delta: frame_hdr.quant.vdc_delta as i32,
            seg_delta_q: frame_hdr.segmentation.d.delta_q,
            gdf_enabled: frame_hdr.gdf.enabled,
            gdf_sz_log2: gdf_unit_log2_from_headers(seq_hdr, frame_hdr),
            cur_w: frame_hdr.width,
            cur_h: frame_hdr.height,
            cdef_enabled: frame_hdr.cdef.enabled != 0,
            cdef_on_skiptx: frame_hdr.cdef.on_skiptx != 0,
            cdef_n_strengths: frame_hdr.cdef.n_strengths,
            ccso_enabled: [
                frame_hdr.ccso.p[0].enabled != 0,
                frame_hdr.ccso.p[1].enabled != 0,
                frame_hdr.ccso.p[2].enabled != 0,
            ],
            ccso_sb_reuse: [
                frame_hdr.ccso.p[0].sb_reuse != 0,
                frame_hdr.ccso.p[1].sb_reuse != 0,
                frame_hdr.ccso.p[2].sb_reuse != 0,
            ],
            ccso_unit_log2,
            ccso_unit_w,
            skip_mode_enabled: frame_hdr.skip_mode_enabled != 0,
            allow_intrabc: frame_hdr.allow_intrabc != 0,
            any_lossless: frame_hdr.any_lossless != 0,
            has_chroma_layout: seq_hdr.layout != crate::headers::PixelLayout::I400,
            idtx_intra: seq_hdr.idtx_intra,
            mrls: seq_hdr.mrls,
            mhccp: seq_hdr.mhccp,
            cfl: seq_hdr.cfl,
            allow_screen_content_tools: frame_hdr.allow_screen_content_tools != 0,
            intra_dip: seq_hdr.intra_dip,
            force_integer_mv: frame_hdr.force_integer_mv != 0,
            max_bvp_drl_bits: frame_hdr.max_bvp_drl_bits,
            max_drl_bits: frame_hdr.max_drl_bits,
            bawp: frame_hdr.bawp != 0,
            intra_bawp: frame_hdr.intra_bawp,
            txfm_switchable: frame_hdr.txfm_mode == crate::headers::TxfmMode::Switchable,
            skip_mode_refs,
            n_ref_frames: frame_hdr.n_ref_frames,
            warp_motion: frame_hdr.warp_motion != 0,
            motion_modes: frame_hdr.motion_modes,
            adaptive_mvd: seq_hdr.adaptive_mvd,
            flex_mvres: seq_hdr.flex_mvres,
            mv_precision: frame_hdr.mv_precision,
            mvd_sign_derive: seq_hdr.mvd_sign_derive,
            tip_frame_mode: frame_hdr.tip.frame_mode,
            tip_global_wtd_idx: frame_hdr.tip.global_wtd_idx,
            six_param_warp_delta: seq_hdr.six_param_warp_delta,
            subpel_filter_mode: frame_hdr.subpel_filter_mode as u8,
            switchable_comp_refs: frame_hdr.switchable_comp_refs != 0,
            num_same_ref_comp: seq_hdr.num_same_ref_comp,
            refdir,
            refdist: refdist8,
            opfl_refine_type: frame_hdr.opfl_refine_type,
            masked_compound: seq_hdr.masked_compound,
            cwp: seq_hdr.cwp,
            refine_mv_enabled: seq_hdr.refine_mv,
            absrefdist: absrefdist8,
            furthest_future_refidx,
            tip,
            tile_col_start,
            tile_col_end,
            tile_row_start,
            tile_row_end,
            sb_step,
        }
    }
}

/// Read-only per-frame reconstruction scalars (shared ref).
pub struct ReconFrameCtx<'a> {
    pub exec: &'a crate::exec_context::ExecContext,
    pub dq: &'a [[[u32; 2]; 3]; MAX_SEGMENTS],
    pub qm: &'a [[Option<&'static [u8]>; 3]; crate::levels::N_RECT_TX_SIZES],
    pub y_stride_px: usize,
    pub uv_stride_px: usize,
    pub ss_hor: i32,
    pub ss_ver: i32,
    pub bitdepth_max: i32,
    pub seq_fsc: bool,
    pub seq_ist: [bool; 2],
    pub seq_cctx: bool,
    pub layout: crate::headers::PixelLayout,
    // Extra frame/seq state needed by the reconstruction (coef + intra) leaf.
    pub bitdepth: u32,
    pub seg_lossless: [u8; crate::headers::MAX_SEGMENTS],
    pub reduced_txtp_set: i32,
    pub tcq: bool,
    pub parity_hiding: bool,
    pub seq_intra_edge_filter: bool,
    pub seq_ibp: bool,
    pub seq_inter_ddt: bool,
    /// `seq_hdr->cfl_ds_filter_index` — chroma-from-luma downsampling filter.
    pub cfl_ds_filter_index: i32,
    pub ibp_weights: [[[u8; 16]; 16]; 7],
}

std::thread_local! {
    /// Per-thread reusable coefficient scratch (one max 64x64 transform block).
    static CF_SCRATCH_8: core::cell::RefCell<[i16; 64 * 64]> =
        const { core::cell::RefCell::new([0; 64 * 64]) };

    static CF_SCRATCH_16: core::cell::RefCell<[i32; 64 * 64]> =
        const { core::cell::RefCell::new([0; 64 * 64]) };

    /// Per-thread reusable buffer for the pre-luma-LR luma snapshot read by the
    /// chroma single-Wiener cross-component refine. Sized to the full luma plane
    /// (so the kernel keeps indexing it by absolute offset), but only the band
    /// around the current superblock row is refreshed each row — see
    /// `filter_sbrow`. This replaces a full-plane `dst_y.to_vec()` per sbrow,
    /// which was the dominant memory-traffic cost of the filter phase.
    static LUMA_SNAP: core::cell::RefCell<Vec<u8>> =
        const { core::cell::RefCell::new(Vec::new()) };
    static LUMA_SNAP_HBD: core::cell::RefCell<Vec<u16>> =
        const { core::cell::RefCell::new(Vec::new()) };
}

#[derive(Clone, Copy, Default)]
struct LumaTxRecord {
    tx: u8,
    bx: i16,
    by: i16,
    pb_col_start: i16,
    pb_row_start: i16,
    eob: i16,
    stx: i8,
    txtp: u16,
    cf_off: u32,
    cf_len: u16,
    lossless: bool,
}

/// Coefficient scratch/replay storage selector.  `ReconScratch` is shared by
/// lowbd and highbd decode workers, so it owns both narrow and wide coefficient
/// vectors and this trait selects the one matching `BD::Coef`.
pub(crate) trait DecodeCoeff: crate::pixel::Coeff {
    fn with_cf_scratch<R>(f: impl FnOnce(&mut [Self]) -> R) -> R;
    fn scratch_chroma_cf_mut(s: &mut ReconScratch) -> &mut Vec<Self>;
    fn scratch_luma_cf_ref(s: &ReconScratch) -> &[Self];
    fn scratch_luma_cf_mut(s: &mut ReconScratch) -> &mut Vec<Self>;
    fn scratch_chroma_tx_cf_ref(s: &ReconScratch) -> &[Self];
    fn scratch_chroma_tx_cf_mut(s: &mut ReconScratch) -> &mut Vec<Self>;
    fn replay_luma_cf(s: &SbReplayStore) -> &[Self];
    fn replay_luma_cf_mut(s: &mut SbReplayStore) -> &mut Vec<Self>;
    fn replay_chroma_cf(s: &SbReplayStore) -> &[Self];
    fn replay_chroma_cf_mut(s: &mut SbReplayStore) -> &mut Vec<Self>;
}

impl DecodeCoeff for i16 {
    #[inline(always)]
    fn with_cf_scratch<R>(f: impl FnOnce(&mut [Self]) -> R) -> R {
        CF_SCRATCH_8.with(|cell| {
            let mut guard = cell.borrow_mut();
            f(&mut guard[..])
        })
    }
    #[inline(always)]
    fn scratch_chroma_cf_mut(s: &mut ReconScratch) -> &mut Vec<Self> {
        &mut s.chroma_cf8
    }
    #[inline(always)]
    fn scratch_luma_cf_ref(s: &ReconScratch) -> &[Self] {
        &s.luma_tx_cf8
    }
    #[inline(always)]
    fn scratch_luma_cf_mut(s: &mut ReconScratch) -> &mut Vec<Self> {
        &mut s.luma_tx_cf8
    }
    #[inline(always)]
    fn scratch_chroma_tx_cf_ref(s: &ReconScratch) -> &[Self] {
        &s.chroma_tx_cf8
    }
    #[inline(always)]
    fn scratch_chroma_tx_cf_mut(s: &mut ReconScratch) -> &mut Vec<Self> {
        &mut s.chroma_tx_cf8
    }
    #[inline(always)]
    fn replay_luma_cf(s: &SbReplayStore) -> &[Self] {
        &s.luma_tx_cf8
    }
    #[inline(always)]
    fn replay_luma_cf_mut(s: &mut SbReplayStore) -> &mut Vec<Self> {
        &mut s.luma_tx_cf8
    }
    #[inline(always)]
    fn replay_chroma_cf(s: &SbReplayStore) -> &[Self] {
        &s.chroma_tx_cf8
    }
    #[inline(always)]
    fn replay_chroma_cf_mut(s: &mut SbReplayStore) -> &mut Vec<Self> {
        &mut s.chroma_tx_cf8
    }
}

impl DecodeCoeff for i32 {
    #[inline(always)]
    fn with_cf_scratch<R>(f: impl FnOnce(&mut [Self]) -> R) -> R {
        CF_SCRATCH_16.with(|cell| {
            let mut guard = cell.borrow_mut();
            f(&mut guard[..])
        })
    }
    #[inline(always)]
    fn scratch_chroma_cf_mut(s: &mut ReconScratch) -> &mut Vec<Self> {
        &mut s.chroma_cf32
    }
    #[inline(always)]
    fn scratch_luma_cf_ref(s: &ReconScratch) -> &[Self] {
        &s.luma_tx_cf32
    }
    #[inline(always)]
    fn scratch_luma_cf_mut(s: &mut ReconScratch) -> &mut Vec<Self> {
        &mut s.luma_tx_cf32
    }
    #[inline(always)]
    fn scratch_chroma_tx_cf_ref(s: &ReconScratch) -> &[Self] {
        &s.chroma_tx_cf32
    }
    #[inline(always)]
    fn scratch_chroma_tx_cf_mut(s: &mut ReconScratch) -> &mut Vec<Self> {
        &mut s.chroma_tx_cf32
    }
    #[inline(always)]
    fn replay_luma_cf(s: &SbReplayStore) -> &[Self] {
        &s.luma_tx_cf32
    }
    #[inline(always)]
    fn replay_luma_cf_mut(s: &mut SbReplayStore) -> &mut Vec<Self> {
        &mut s.luma_tx_cf32
    }
    #[inline(always)]
    fn replay_chroma_cf(s: &SbReplayStore) -> &[Self] {
        &s.chroma_tx_cf32
    }
    #[inline(always)]
    fn replay_chroma_cf_mut(s: &mut SbReplayStore) -> &mut Vec<Self> {
        &mut s.chroma_tx_cf32
    }
}

/// One deferred chroma residual block.
#[derive(Clone, Copy)]
struct ChromaTxRecord {
    cbx: i16,
    cby: i16,
    cbs: u8,
    sdp_active: bool,
    n_tu: u16,
    cf_off: u32,
    cf_len: u32,
    u_has_cf: i32,
    /// Offset of this block's `n_tu` transform types / EOBs in
    /// `chroma_tx_txtp` / `chroma_tx_eob`.
    meta_off: u32,
}

impl Default for ChromaTxRecord {
    fn default() -> Self {
        Self {
            cbx: 0,
            cby: 0,
            cbs: BlockSize::Invalid as u8,
            sdp_active: false,
            n_tu: 0,
            cf_off: 0,
            cf_len: 0,
            u_has_cf: 0,
            meta_off: 0,
        }
    }
}

/// One parsed leaf block.  This is enough for partition/block replay once the
/// residual readers have queued their coefficient payloads.
#[derive(Clone, Copy, Default)]
struct BlockRecord {
    b: Av2Block,
    bx: i16,
    by: i16,
    cbx: i16,
    cby: i16,
    lbs: i8,
    cbs: i8,
}

/// Chroma 4px transform units of the largest chroma block (256x256 in 4:4:4).
pub(crate) const MAX_CHROMA_TU: usize = 64 * 64;

/// A complete replay payload for one root superblock.
#[derive(Clone, Default)]
pub(crate) struct SbReplayStore {
    part: Vec<u8>,
    block_rec: Vec<BlockRecord>,
    luma_tx: Vec<LumaTxRecord>,
    luma_tx_cf8: Vec<i16>,
    luma_tx_cf32: Vec<i32>,
    chroma_tx: Vec<ChromaTxRecord>,
    chroma_tx_cf8: Vec<i16>,
    chroma_tx_cf32: Vec<i32>,
    chroma_tx_txtp: Vec<[u16; 2]>,
    chroma_tx_eob: Vec<[i16; 2]>,
}

impl SbReplayStore {
    #[inline]
    fn clear(&mut self) {
        self.part.clear();
        self.block_rec.clear();
        self.luma_tx.clear();
        self.luma_tx_cf8.clear();
        self.luma_tx_cf32.clear();
        self.chroma_tx.clear();
        self.chroma_tx_cf8.clear();
        self.chroma_tx_cf32.clear();
        self.chroma_tx_txtp.clear();
        self.chroma_tx_eob.clear();
    }

    /// Move the just-parsed replay payload out of the worker-local scratch.
    /// Heap allocations are preserved on the destination between calls.
    #[inline]
    fn capture_from<C: DecodeCoeff>(&mut self, part_w: &[u8], scratch: &mut ReconScratch) {
        self.clear();
        self.part.extend_from_slice(part_w);

        self.block_rec.append(&mut scratch.block_rec);
        self.luma_tx.append(&mut scratch.luma_tx);
        C::replay_luma_cf_mut(self).append(C::scratch_luma_cf_mut(scratch));
        self.chroma_tx.append(&mut scratch.chroma_tx);
        C::replay_chroma_cf_mut(self).append(C::scratch_chroma_tx_cf_mut(scratch));
        self.chroma_tx_txtp.append(&mut scratch.chroma_tx_txtp);
        self.chroma_tx_eob.append(&mut scratch.chroma_tx_eob);

        scratch.block_rpos = 0;
        scratch.luma_tx_rpos = 0;
        scratch.chroma_tx_rpos = 0;
    }

    /// Prepare a worker-local scratch for a reconstruction replay.  This clones
    /// the compact metadata/coefficient payload for now; the scheduler-facing
    /// version can replace this with a move once each `SbReplayStore` is owned by
    /// exactly one recon task.
    #[inline]
    fn load_into<C: DecodeCoeff>(&self, scratch: &mut ReconScratch) {
        scratch.block_rec.clear();
        scratch.block_rec.extend_from_slice(&self.block_rec);

        scratch.luma_tx.clear();
        scratch.luma_tx.extend_from_slice(&self.luma_tx);
        C::scratch_luma_cf_mut(scratch).clear();
        C::scratch_luma_cf_mut(scratch).extend_from_slice(C::replay_luma_cf(self));

        scratch.chroma_tx.clear();
        scratch.chroma_tx.extend_from_slice(&self.chroma_tx);
        C::scratch_chroma_tx_cf_mut(scratch).clear();
        C::scratch_chroma_tx_cf_mut(scratch).extend_from_slice(C::replay_chroma_cf(self));
        scratch.chroma_tx_txtp.clear();
        scratch
            .chroma_tx_txtp
            .extend_from_slice(&self.chroma_tx_txtp);
        scratch.chroma_tx_eob.clear();
        scratch.chroma_tx_eob.extend_from_slice(&self.chroma_tx_eob);

        scratch.reset_replay_cursors();
    }
}

/// `Dav2dTaskContext` used by the luma recon leaf). `is_coded[0]` tracks the
/// 64x64 grid of decoded luma tx blocks for top-right / bottom-left availability.
pub struct ReconScratch {
    pub is_coded: [[u64; 64]; 2],
    /// SDP semi-decoupled partitioning: when the luma-only tree decodes a block
    /// it records its intra direction mode (and FSC flag) into this 16x16 map
    /// (indexed `(by & 15) * 16 + (bx & 15)`), which the chroma-only tree reads
    pub luma_intra_dir_mode_map: [u8; 256],
    pub luma_fsc_map: [u8; 256],
    /// Chroma coefficient / metadata storage used to split the chroma decode of
    /// a >64px block into a coef-read phase (with the first luma 64x64) and a
    /// recon phase (with the last), mirroring the `cbs_stage` mechanism in
    pub chroma_cf8: Vec<i16>,
    pub chroma_cf32: Vec<i32>,
    /// Per-TU chroma transform types / EOBs of the current chroma block, in
    /// 4px units (a 256x256 4:4:4 block has `MAX_CHROMA_TU` of them).
    pub chroma_txtp: Box<[[u16; 2]; MAX_CHROMA_TU]>,
    pub chroma_eob: Box<[[i16; 2]; MAX_CHROMA_TU]>,
    /// IntraBC chroma: co-located luma transform type of the coding block's
    /// origin, used to seed chroma TUs when chroma covers several luma blocks.
    pub ibc_uv_txtp_seed: u16,
    pub chroma_u_has_cf: i32,
    /// Deferred chroma residual payloads for entropy/recon replay.
    chroma_tx: Vec<ChromaTxRecord>,
    chroma_tx_cf8: Vec<i16>,
    chroma_tx_cf32: Vec<i32>,
    pub(crate) chroma_tx_txtp: Vec<[u16; 2]>,
    pub(crate) chroma_tx_eob: Vec<[i16; 2]>,
    chroma_tx_rpos: usize,
    /// Parsed block replay stream.
    block_rec: Vec<BlockRecord>,
    block_rpos: usize,
    /// Deferred luma transform payloads for future entropy/recon split.
    /// `luma_tx` records order; `luma_tx_cf` owns the corresponding coefficient
    /// slices. `luma_tx_rpos` is the replay cursor used by ReconOnly.
    luma_tx: Vec<LumaTxRecord>,
    luma_tx_cf8: Vec<i16>,
    luma_tx_cf32: Vec<i32>,
    luma_tx_rpos: usize,
    /// Per-4x4 luma transform type map (full txtp incl. secondary-tx bits),
    /// indexed `(by & 15) * 16 + (bx & 15)`. Written by the luma residual walk
    pub txtp_map: [u16; 256],
    /// TIP per-8x8 refined-MV grid (`t->rmv`): a 16x16 grid (one entry per 8x8
    /// unit within a 128x128 superblock) of `[2 versions][2 refs]` MVs. Written
    /// by the luma `tip_pred` (version 0 = luma MV post-refine, version 1 =
    /// chroma-scaled MV) and read back by the chroma `rmv_uvpred`. Indexed
    /// `((by & 31) >> 1) * 16 + ((bx & 31) >> 1)`.
    pub rmv: [[[Mv; 2]; 2]; 256],
    /// Above/left palette-color cache (`t->al_pal`): `[a/l][bx4|by4][8 colors]`,
    /// indexed by `bx & 63` (above) / `by & 63` (left). Written by the palette
    /// recon (`copy_pal_block_y`) and read by `read_pal_plane` to build the
    /// per-block palette color cache. Never explicitly reset — gating is via the
    pub al_pal: [[[u16; 8]; 64]; 2],
    /// Current palette block's color list (`t->scratch.pal`, 8 entries). Filled
    /// by `read_pal_plane` during parse and consumed by the palette recon fill.
    pub pal: [u16; 8],
    /// Current palette block's packed index map (`t->scratch.pal_idx_y`). `pack`
    /// stores two indices per byte; sized for the largest palette block (64x64).
    pub pal_idx_y: Box<[u8; 64 * 64]>,
    /// Unpacked palette index scratch (avoids a per-block heap alloc).
    pub pal_idx_unpack: Box<[u8; 64 * 64]>,
    /// Reusable coefficient-level neighbour map for `decode_coefs` (worst case
    /// 33*33 = 1089). Only the prefix actually used by the current transform is
    /// cleared per block, so small TUs avoid a full 1089-byte memset.
    pub coef_levels: [i8; 1089],
    /// Non-zero coefficient records replayed by the sign pass.
    pub coef_nz: [u32; 1024],
    /// Reusable inverse-transform scratch (`Txfm2d` buffer)
    pub itx_tmp: Box<[i32; crate::itx_2d::ITX_TMP_PIXELS]>,
    /// Reusable compound-prediction temporary planes. Compound inter used to
    /// allocate two `Vec<i16>` buffers for every luma/chroma block; these buffers
    /// are taken out around the MC/blend step so `ReconCtx` can still be borrowed
    /// mutably by the prediction helpers.
    compound_tmp0: Vec<i16>,
    compound_tmp1: Vec<i16>,
    /// Reusable inter MC mid-plane scratch for two-pass bilinear/8tap SIMD.
    inter_mc_tmp: Vec<i16>,
    /// Reusable 128x128 mask buffer for SEG/BACP compound blending.
    compound_seg_mask: Vec<u8>,
}

impl Default for ReconScratch {
    fn default() -> Self {
        Self {
            is_coded: [[0u64; 64]; 2],
            luma_intra_dir_mode_map: [0u8; 256],
            luma_fsc_map: [0u8; 256],
            chroma_cf8: Vec::new(),
            chroma_cf32: Vec::new(),
            chroma_txtp: Box::new([[0u16; 2]; MAX_CHROMA_TU]),
            chroma_eob: Box::new([[-1i16; 2]; MAX_CHROMA_TU]),
            ibc_uv_txtp_seed: 0,
            chroma_u_has_cf: 0,
            chroma_tx: Vec::new(),
            chroma_tx_cf8: Vec::new(),
            chroma_tx_cf32: Vec::new(),
            chroma_tx_txtp: Vec::new(),
            chroma_tx_eob: Vec::new(),
            chroma_tx_rpos: 0,
            block_rec: Vec::new(),
            block_rpos: 0,
            luma_tx: Vec::new(),
            luma_tx_cf8: Vec::new(),
            luma_tx_cf32: Vec::new(),
            luma_tx_rpos: 0,
            txtp_map: [0u16; 256],
            rmv: [[[Mv::default(); 2]; 2]; 256],
            al_pal: [[[0u16; 8]; 64]; 2],
            pal: [0u16; 8],
            pal_idx_y: Box::new([0u8; 64 * 64]),
            pal_idx_unpack: Box::new([0u8; 64 * 64]),
            coef_levels: [0i8; 1089],
            coef_nz: [0u32; 1024],
            itx_tmp: Box::new([0i32; crate::itx_2d::ITX_TMP_PIXELS]),
            compound_tmp0: Vec::new(),
            compound_tmp1: Vec::new(),
            inter_mc_tmp: Vec::new(),
            compound_seg_mask: Vec::new(),
        }
    }
}

impl ReconScratch {
    #[inline]
    pub(crate) fn take_chroma_cf<C: DecodeCoeff>(&mut self) -> Vec<C> {
        core::mem::take(C::scratch_chroma_cf_mut(self))
    }

    #[inline]
    pub(crate) fn put_chroma_cf<C: DecodeCoeff>(&mut self, v: Vec<C>) {
        *C::scratch_chroma_cf_mut(self) = v;
    }

    #[inline]
    pub(crate) fn chroma_tx_cf<C: DecodeCoeff>(&self) -> &[C] {
        // SAFETY-free dispatch through the concrete trait impl.
        C::scratch_chroma_tx_cf_ref(self)
    }

    #[inline]
    pub(crate) fn chroma_tx_cf_mut<C: DecodeCoeff>(&mut self) -> &mut Vec<C> {
        C::scratch_chroma_tx_cf_mut(self)
    }

    #[inline]
    pub(crate) fn luma_tx_cf<C: DecodeCoeff>(&self) -> &[C] {
        C::scratch_luma_cf_ref(self)
    }

    #[inline]
    pub(crate) fn luma_tx_cf_mut<C: DecodeCoeff>(&mut self) -> &mut Vec<C> {
        C::scratch_luma_cf_mut(self)
    }

    #[inline]
    fn trim_retained_capacity(&mut self) {
        drop_vec_if_capacity_gt(&mut self.chroma_cf8, MAX_RETAINED_REPLAY_COEF_BYTES);
        drop_vec_if_capacity_gt(&mut self.chroma_cf32, MAX_RETAINED_REPLAY_COEF_BYTES);
        drop_vec_if_capacity_gt(
            &mut self.chroma_tx,
            MAX_RETAINED_REPLAY_RECORDS * core::mem::size_of::<ChromaTxRecord>(),
        );
        drop_vec_if_capacity_gt(&mut self.chroma_tx_cf8, MAX_RETAINED_REPLAY_COEF_BYTES);
        drop_vec_if_capacity_gt(&mut self.chroma_tx_cf32, MAX_RETAINED_REPLAY_COEF_BYTES);
        drop_vec_if_capacity_gt(
            &mut self.block_rec,
            MAX_RETAINED_REPLAY_RECORDS * core::mem::size_of::<BlockRecord>(),
        );
        drop_vec_if_capacity_gt(
            &mut self.luma_tx,
            MAX_RETAINED_REPLAY_RECORDS * core::mem::size_of::<LumaTxRecord>(),
        );
        drop_vec_if_capacity_gt(&mut self.luma_tx_cf8, MAX_RETAINED_REPLAY_COEF_BYTES);
        drop_vec_if_capacity_gt(&mut self.luma_tx_cf32, MAX_RETAINED_REPLAY_COEF_BYTES);
        drop_vec_if_capacity_gt(
            &mut self.compound_tmp0,
            128 * 128 * core::mem::size_of::<i16>(),
        );
        drop_vec_if_capacity_gt(
            &mut self.compound_tmp1,
            128 * 128 * core::mem::size_of::<i16>(),
        );
        drop_vec_if_capacity_gt(
            &mut self.inter_mc_tmp,
            128 * (128 + 7) * core::mem::size_of::<i16>(),
        );
        drop_vec_if_capacity_gt(&mut self.compound_seg_mask, 128 * 128);
    }

    #[inline]
    fn reset_for_sbrow(&mut self, inter: bool) {
        self.is_coded = [[0u64; 64]; 2];
        self.luma_intra_dir_mode_map = [0u8; 256];
        self.luma_fsc_map = [0u8; 256];
        self.chroma_txtp.fill([0u16; 2]);
        self.chroma_eob.fill([-1i16; 2]);
        self.chroma_u_has_cf = 0;
        self.chroma_tx.clear();
        self.chroma_tx_cf8.clear();
        self.chroma_tx_cf32.clear();
        self.chroma_tx_txtp.clear();
        self.chroma_tx_eob.clear();
        self.chroma_tx_rpos = 0;
        self.block_rec.clear();
        self.block_rpos = 0;
        self.luma_tx.clear();
        self.luma_tx_cf8.clear();
        self.luma_tx_cf32.clear();
        self.luma_tx_rpos = 0;
        self.txtp_map = [0u16; 256];
        if inter {
            self.rmv = [[[Mv::default(); 2]; 2]; 256];
        }
        self.al_pal = [[[0u16; 8]; 64]; 2];
        self.pal = [0u16; 8];
        // coef_levels: decode_coefs zero-fills its used prefix per TU.
        // coef_nz: records[..nz_n] are written before read by construction.
        self.chroma_cf8.clear();
        self.chroma_cf32.clear();
        // pal_idx_y: read_pal_indices packs the full region pal_pred reads.
        // `itx_tmp` and the compound MC temporaries are fully overwritten on the
        // used prefix when taken. Keep their capacity across superblock rows.
    }

    #[inline]
    pub(crate) fn inter_mc_tmp_mut(&mut self) -> &mut Vec<i16> {
        &mut self.inter_mc_tmp
    }

    pub(crate) fn take_compound_tmp(&mut self, len: usize) -> [Vec<i16>; 2] {
        let mut tmp = [
            core::mem::take(&mut self.compound_tmp0),
            core::mem::take(&mut self.compound_tmp1),
        ];
        for v in &mut tmp {
            if v.len() != len {
                v.resize(len, 0);
            }
            v.fill(0);
        }
        tmp
    }

    #[inline]
    pub(crate) fn put_compound_tmp(&mut self, tmp: [Vec<i16>; 2]) {
        let [tmp0, tmp1] = tmp;
        self.compound_tmp0 = tmp0;
        self.compound_tmp1 = tmp1;
    }

    #[inline]
    pub(crate) fn take_compound_seg_mask(&mut self) -> Vec<u8> {
        let mut mask = core::mem::take(&mut self.compound_seg_mask);
        if mask.len() != 128 * 128 {
            mask.resize(128 * 128, 0);
        } else {
            mask.fill(0);
        }
        mask
    }

    #[inline]
    pub(crate) fn put_compound_seg_mask(&mut self, mask: Vec<u8>) {
        self.compound_seg_mask = mask;
    }

    #[inline]
    fn reset_replay_cursors(&mut self) {
        self.block_rpos = 0;
        self.luma_tx_rpos = 0;
        self.chroma_tx_rpos = 0;
        self.is_coded = [[0u64; 64]; 2];
    }
}

fn make_refmv_tile(ra_len: usize, bw: i32, bh: i32) -> refmvs::Tile {
    refmvs::Tile {
        rp_proj_off: 0,
        rp_traj_off: 0,
        ra: vec![refmvs::Block::default(); ra_len.max(1)],
        ra_off: 0,
        ra_tl: refmvs::Block::default(),
        r: refmvs::zeroed_block_rows(),
        tile_col: refmvs::TileRange { start: 0, end: bw },
        tile_row: refmvs::TileRange { start: 0, end: bh },
        bank: refmvs::MvBank {
            mv: [[[Mv::default(); 2]; 4]; 9],
            cwp_idx: [[0; 4]; 3],
            reference: [RefPair::default(); 4],
            size: [0; 9],
            idx: [0; 9],
            hits: [0; 2],
            avail: 0,
        },
        warp: refmvs::WarpBank {
            mat: [[[0; 6]; 4]; 7],
            warp_type: [[0; 4]; 7],
            hits: 0,
            size: [0; 7],
            idx: [0; 7],
        },
    }
}

fn prepare_refmv_tile(rt: &mut refmvs::Tile, ra_len: usize, bw: i32, bh: i32) -> Result<(), ()> {
    let ra_len = ra_len.max(1);
    if rt.ra.len() != ra_len {
        if ra_len > rt.ra.len() {
            rt.ra
                .try_reserve_exact(ra_len - rt.ra.len())
                .map_err(|_| ())?;
        }
        rt.ra.resize(ra_len, refmvs::Block::default());
    }
    rt.rp_proj_off = 0;
    rt.rp_traj_off = 0;
    rt.ra_off = 0;
    rt.ra_tl = refmvs::Block::default();
    rt.tile_col = refmvs::TileRange { start: 0, end: bw };
    rt.tile_row = refmvs::TileRange { start: 0, end: bh };
    rt.bank.size = [0; 9];
    rt.bank.idx = [0; 9];
    rt.bank.hits = [0; 2];
    rt.bank.avail = 0;
    rt.warp.size = [0; 7];
    rt.warp.idx = [0; 7];
    rt.warp.hits = 0;
    Ok(())
}

struct DecodeWorkerScratch {
    rt: refmvs::Tile,
    recon_scratch: ReconScratch,
    part_w: Vec<u8>,
    ccso_tmp_buf: Vec<u8>,
    ccso_tmp_buf_hbd: Vec<u16>,
    recon_edge8: Box<[u8; 2048]>,
    recon_edge16: Box<[u16; 2048]>,
}

impl DecodeWorkerScratch {
    fn new(ra_len: usize, bw: i32, bh: i32) -> Self {
        Self {
            rt: make_refmv_tile(ra_len, bw, bh),
            recon_scratch: ReconScratch::default(),
            part_w: Vec::new(),
            ccso_tmp_buf: Vec::new(),
            ccso_tmp_buf_hbd: Vec::new(),
            recon_edge8: Box::new([0u8; 2048]),
            recon_edge16: Box::new([0u16; 2048]),
        }
    }

    fn prepare(&mut self, ra_len: usize, bw: i32, bh: i32) -> Result<(), ()> {
        prepare_refmv_tile(&mut self.rt, ra_len, bw, bh)?;
        self.part_w.clear();
        Ok(())
    }

    fn trim_retained_capacity(&mut self) {
        if self.rt.ra.capacity() > MAX_RETAINED_WORKER_RA_BLOCKS {
            self.rt.ra = Vec::new();
        }
        drop_vec_if_capacity_gt(&mut self.part_w, MAX_RETAINED_PARTITION_BYTES);
        drop_vec_if_capacity_gt(&mut self.ccso_tmp_buf, MAX_RETAINED_CCSO_TMP_BYTES);
        drop_vec_if_capacity_gt(&mut self.ccso_tmp_buf_hbd, MAX_RETAINED_CCSO_TMP_BYTES);
        self.recon_scratch.trim_retained_capacity();
    }
}

trait DecodeEdgePixel: Pixel {
    fn edge_mut<'a>(
        edge8: &'a mut Box<[u8; 2048]>,
        edge16: &'a mut Box<[u16; 2048]>,
    ) -> &'a mut [Self; 2048];
}

impl DecodeEdgePixel for u8 {
    #[inline(always)]
    fn edge_mut<'a>(
        edge8: &'a mut Box<[u8; 2048]>,
        _edge16: &'a mut Box<[u16; 2048]>,
    ) -> &'a mut [Self; 2048] {
        edge8.as_mut()
    }
}

impl DecodeEdgePixel for u16 {
    #[inline(always)]
    fn edge_mut<'a>(
        _edge8: &'a mut Box<[u8; 2048]>,
        edge16: &'a mut Box<[u16; 2048]>,
    ) -> &'a mut [Self; 2048] {
        edge16.as_mut()
    }
}

const MAX_RETAINED_WORKER_RA_BLOCKS: usize = 1 << 20;
const MAX_RETAINED_PARTITION_BYTES: usize = 1 << 20;
const MAX_RETAINED_CCSO_TMP_BYTES: usize = 2 << 20;
const MAX_RETAINED_REPLAY_RECORDS: usize = 1 << 18;
const MAX_RETAINED_REPLAY_COEF_BYTES: usize = 8 << 20;

#[inline]
fn drop_vec_if_capacity_gt<T>(v: &mut Vec<T>, max_bytes: usize) {
    let elem = core::mem::size_of::<T>().max(1);
    if v.capacity() > max_bytes / elem {
        *v = Vec::new();
    }
}

std::thread_local! {
    /// Per-pool-worker decode scratch that used to allocate/zero ~512 KiB of
    /// ref-MV state plus recon scratch every frame.
    static WORKER_SCRATCH: core::cell::RefCell<Option<DecodeWorkerScratch>> =
        const { core::cell::RefCell::new(None) };
}

/// Release caller-thread TLS decode scratch. Worker-thread TLS is destroyed when
/// the decoder's private thread pool is dropped; this helper covers the caller
/// thread used by ST decode and by the scoped MT participant.
pub(crate) fn clear_thread_local_decode_scratch() {
    WORKER_SCRATCH.with(|ws| {
        *ws.borrow_mut() = None;
    });
    LUMA_SNAP.with(|snap| {
        *snap.borrow_mut() = Vec::new();
    });
    LUMA_SNAP_HBD.with(|snap| {
        *snap.borrow_mut() = Vec::new();
    });
}
/// Mutable reconstruction borrows bundled so only one new param threads through
/// decode_sb's recursion (Rust auto-reborrows &mut ReconCtx at each call).
pub struct ReconCtx<'a, 'f, BD: BitDepth> {
    pub bd: BD,
    pub dst_y: &'a mut [BD::Pixel],
    pub dst_u: &'a mut [BD::Pixel],
    pub dst_v: &'a mut [BD::Pixel],
    pub cdf_coef: &'a mut crate::cdf::CdfCoefContext,
    pub cf: &'a mut [BD::Coef],
    pub frame: &'a ReconFrameCtx<'f>,
    /// built once per frame; consumed by the compound + interintra recon.
    pub masks: &'f crate::wedge::Masks,
    /// Per-superblock recon scratch (is_coded grid). Reset by the caller at each
    /// superblock boundary, mirroring the C `memset(t->is_coded, ...)`.
    pub scratch: &'a mut ReconScratch,
    /// Temporary edge buffer for `prepare_intra_edges` (`t->scratch.edge`,
    /// 257 entries wide; we use a generous fixed slab indexed from the middle).
    pub edge: &'a mut [BD::Pixel],
    /// Current-frame segment id map (`f->cur_segmap`), `b4_stride * bh` entries.
    /// Written by decode_b over the block footprint when segmentation is enabled.
    pub cur_segmap: &'a mut [u8],
    /// Previous-frame segment map (`f->prev_segmap`), present only when the frame
    /// has a primary reference; `None` for frame-0 / no-primary-ref keyframes.
    pub prev_segmap: Option<&'a [u8]>,
    /// `f->b4_stride` — row stride of the segment maps (in 4x4 units).
    pub b4_stride: isize,
    /// Chroma segment-id map (`f->lf.segmap_uv`), written per chroma block when
    /// segmentation + chroma deblock are on; consumed by the deblock UV pass.
    pub segmap_uv: &'a mut [u8],
    /// `f->lf.uv_segmap_stride`; 0 when `segmap_uv` is unused.
    pub segmap_uv_stride: isize,
    /// Running per-superblock quantizer index (`ts->last_qidx`). Updated by the
    /// per-SB delta-q parse; seeded from `frame_hdr.quant.yac` at tile start.
    pub last_qidx: i32,
    /// Per-superblock recomputed dequant tables (`ts->dqmem`).
    pub dqmem: [[[u32; 2]; 3]; crate::headers::MAX_SEGMENTS],
    /// Currently active dequant tables (`ts->dq`): either the frame-wide
    /// `recon.frame.dq` or `dqmem` when a per-SB delta-q shifts the qindex.
    pub dq_active: [[[u32; 2]; 3]; crate::headers::MAX_SEGMENTS],
    /// Set when a parsed seg_id is out of range (`seg_id >= 16`), mirroring the
    /// C `return -1` that aborts the frame.
    pub seg_id_err: bool,
    /// Loop-filter mask array (`f->lf.mask` / per-SB `Av2Filter`) — the gdf,
    /// cdef-index and ccso reads write into it and read neighbor SB values.
    pub lf_mask: &'a mut [crate::lf_mask::Av2Filter],
    /// Index of the current superblock's `Av2Filter` within `lf_mask`.
    pub lf_idx: usize,
    /// `f->sb256w` — superblock-row stride into `lf_mask` (for top neighbor).
    pub sb256w: i32,
    /// Current-frame CCSO map (`f->cur_ccsomap`), written per-SB; empty if unused.
    pub cur_ccsomap: &'a mut [u8],
    /// Previous-frame CCSO maps (`f->prev_ccsomap`); `None` per plane if absent.
    pub prev_ccsomap: [Option<&'a [u8]>; 3],
    /// Per-tile reference-MV state (`t->rt`): spatial `r` grid + above-row `ra` +
    /// MV/warp banks. Maintained via splat for every block so IntraBC block
    pub rt: &'a mut refmvs::Tile,
    /// Frame-level reference-MV state (`f->rf`): iw4/ih4/sbsz + header refs.
    pub rf: &'a refmvs::Frame,
    /// Current-frame temporal MV grid (`f->mvs` == `rf.rp`), written by the inter
    /// splat so later frames can reference these MVs. Empty when ref_frame_mvs is
    /// disabled. Held separately from `rf` (which is shared immutably) so the
    /// per-block temporal save can mutate it.
    pub cur_mvs: &'a mut [refmvs::TemporalBlock],
    /// Per-reference picture pixel planes for inter motion compensation
    /// (`f->refp[i].p`). `None` for refs the current frame does not use.
    pub refp: &'a [Option<std::sync::Arc<crate::picture::Picture>>; 7],
    /// Per-reference scaling parameters (`f->svc[i]`); scale==0 means unscaled.
    pub svc: &'a [[ScalableMotionParams; 2]; 7],
    /// Inter-chroma `u_has_cf` flag (`t->u_has_cf`): set by the U plane's coef
    /// decode, consumed by the V plane's context (decode_coefs). Per chroma block.
    pub scratch_u_has_cf: i32,
    /// Sequence/frame headers needed by `refmvs_find` for IntraBC candidates.
    pub seq_hdr: &'a crate::headers::SequenceHeader,
    pub frm_hdr: &'a FrameHeader,
    /// Per-block derived warp motion parameters (`t->warpmv[0..2]`), computed in
    /// the inter MV-resolution step and consumed by `recon_b_inter`'s warp MC.
    pub warpmv: [crate::headers::WarpedMotionParams; 2],
    /// Above-superblock-row edge context snapshot (`t->a_sb_cache`). Taken at the
    /// start of each superblock from the above-row block context, before the
    /// current SB's blocks overwrite it. Inter warp/single-ref/has_cs_ext context
    /// derivations consult this (at 8x8 resolution) for blocks at the SB top edge,
    /// because the 8x8 rounding can otherwise read `a` entries already clobbered
    pub a_sb_cache: crate::env::SBEdgeCtx,
    /// Per-plane block-adaptive weighted prediction state (`t->pb.bawp[plane]` =
    /// alpha/beta). The luma plane derives alpha/beta from neighbour templates;
    /// chroma reuses the luma alpha. Sub-blocks of a >64px partition reuse the
    pub bawp_ab: [(i32, i32); 3],
}

/// Arguments for one tile/superblock-row entropy/reconstruction pass.
///
/// This used to be a 30+ argument function. Keeping the frequently-mutated
/// frame/tile state in one named packet makes the call sites audit-able without
/// changing the hot decode path after inlining.
pub(crate) struct DecodeTileSbrowEntropyCtx<
    'a,
    'f,
    BD: BitDepth,
    const UPDATE_CDF: bool,
    M: MsacReader<UPDATE_CDF>,
> {
    pub(crate) bd: BD,
    pub(crate) fi: &'a SbFrameInfo,
    pub(crate) frame_hdr: &'a FrameHeader,
    pub(crate) ts: &'a mut crate::internal::TileState,
    pub(crate) msac: &'a mut M,
    pub(crate) a_arr: &'a mut [BlockContext],
    pub(crate) lf_mask: &'a mut [crate::lf_mask::Av2Filter],
    pub(crate) lr_mask: &'a mut [crate::lf_mask::Av2Restoration],
    /// `TileSeamLpf::right` / `bottom` (see there), plus its `h4` / `w4`.
    pub(crate) seam_right: &'a mut [u8],
    pub(crate) seam_bottom: &'a mut [u8],
    pub(crate) seam_h4: usize,
    pub(crate) seam_w4: usize,
    pub(crate) l: &'a mut BlockContext,
    pub(crate) dst_y: &'a mut [BD::Pixel],
    pub(crate) dst_u: &'a mut [BD::Pixel],
    pub(crate) dst_v: &'a mut [BD::Pixel],
    pub(crate) cf: &'a mut [BD::Coef],
    pub(crate) recon_scratch: &'a mut ReconScratch,
    pub(crate) recon_edge: &'a mut [BD::Pixel; 2048],
    pub(crate) recon_frame: &'a ReconFrameCtx<'f>,
    pub(crate) cur_segmap: &'a mut [u8],
    pub(crate) prev_segmap: Option<&'a [u8]>,
    pub(crate) segmap_uv: &'a mut [u8],
    pub(crate) segmap_uv_stride: isize,
    pub(crate) cur_ccsomap: &'a mut [u8],
    pub(crate) prev_ccsomap: [Option<&'a [u8]>; 3],
    pub(crate) part_w: &'a mut Vec<u8>,
    pub(crate) part_r: &'a [u8],
    pub(crate) by: i32,
    pub(crate) sb256w: i32,
    pub(crate) pass: u8,
    pub(crate) root_bs: BlockSize,
    pub(crate) c_root_bs: BlockSize,
    pub(crate) rt: &'a mut refmvs::Tile,
    pub(crate) rf: &'a refmvs::Frame,
    pub(crate) cur_mvs: &'a mut [refmvs::TemporalBlock],
    pub(crate) refp: &'a [Option<std::sync::Arc<crate::picture::Picture>>; 7],
    pub(crate) svc: &'a [[ScalableMotionParams; 2]; 7],
    pub(crate) seq_hdr: &'a crate::headers::SequenceHeader,
    pub(crate) frm_hdr: &'a FrameHeader,
    pub(crate) masks: &'a crate::wedge::Masks,
}

/// Decode one superblock row of a tile (entropy/parse pass).
///
/// for the single-pass, single-thread case. Reads per-superblock restoration
/// info and CDEF index reset, then drives `decode_sb` across the row.
pub(crate) fn decode_tile_sbrow_entropy<
    BD: BitDepth,
    const UPDATE_CDF: bool,
    M: MsacReader<UPDATE_CDF>,
>(
    ctx: DecodeTileSbrowEntropyCtx<'_, '_, BD, UPDATE_CDF, M>,
) -> Result<(), ()>
where
    BD::Coef: DecodeCoeff,
{
    let DecodeTileSbrowEntropyCtx {
        bd,
        fi,
        frame_hdr,
        ts,
        msac,
        a_arr,
        lf_mask,
        lr_mask,
        seam_right,
        seam_bottom,
        seam_h4,
        seam_w4,
        l,
        dst_y,
        dst_u,
        dst_v,
        cf,
        recon_scratch,
        recon_edge,
        recon_frame,
        cur_segmap,
        prev_segmap,
        segmap_uv,
        segmap_uv_stride,
        cur_ccsomap,
        prev_ccsomap,
        part_w,
        part_r,
        by,
        sb256w,
        pass,
        root_bs,
        c_root_bs,
        rt,
        rf,
        cur_mvs,
        refp,
        svc,
        seq_hdr,
        frm_hdr,
        masks,
    } = ctx;
    let sb_step = fi.sb_step;
    let sb256y = by >> 6;
    let tile_row = ts.tiling.row;
    let col_start = ts.tiling.col_start;
    let col_end = ts.tiling.col_end;
    let row_start = ts.tiling.row_start;
    let row_end = ts.tiling.row_end;

    let refmvs_active = fi.allow_intrabc || fi.is_inter_or_switch;

    // Per-worker reusable reconstruction scratch. The MV scratch is only
    // touched by inter refinement; intra frames skip its 4 KB re-clear.
    recon_scratch.reset_for_sbrow(refmvs_active);

    let mut sb_last_qidx = ts.last_qidx;
    let mut sb_dqmem = ts.dqmem;
    let mut sb_seg_err = false;

    if refmvs_active {
        crate::refmvs::tile_sbrow_init(
            rt,
            rf,
            col_start,
            col_end,
            row_start,
            row_end,
            by >> 6,
            tile_row,
        );
    }
    let is_key_or_intra = frame_hdr.is_key_or_intra();

    let mut bx = col_start;
    while bx < col_end {
        let a_idx = (tile_row * sb256w + (bx >> 6)) as usize;
        let lf_idx = ((bx >> 6) + sb256y * sb256w) as usize;

        // Reset is_coded for this superblock: whole-array store compiles to
        // inline vector stores instead of per-row memset calls.
        recon_scratch.is_coded = [[0u64; 64]; 2];

        // reset_context path); marks all 4x4 units intra (invalid mv) so that
        // not-yet-decoded neighbours are skipped by refmvs_find.
        if refmvs_active {
            crate::refmvs::reset_sb(
                rt,
                sb_step,
                seq_hdr.refmv_bank,
                is_key_or_intra,
                frm_hdr.tip.frame_mode,
                by,
                bx,
            );
        }

        // frame_mode==2 whole-frame TIP superblocks are not entropy decoded
        // loop-restoration info read, synthesizing a single TIP block per SB
        // instead. Those two reads only apply to the entropy/decode_sb path.
        let is_tip_frame = frm_hdr.tip.frame_mode == 2;

        // Reset CDEF indices for this superblock's coverage in the lf mask.
        if !is_tip_frame {
            match root_bs {
                BlockSize::Bs64x64 => {
                    let idx = (((bx & 0x30) >> 4) + ((by & 0x30) >> 2)) as usize;
                    lf_mask[lf_idx].cdef_idx[idx] = -1;
                }
                BlockSize::Bs128x128 => {
                    let idx = (((bx & 32) >> 4) + ((by & 32) >> 2)) as usize;
                    lf_mask[lf_idx].cdef_idx[idx] = -1;
                    lf_mask[lf_idx].cdef_idx[idx + 1] = -1;
                    lf_mask[lf_idx].cdef_idx[idx + 4] = -1;
                    lf_mask[lf_idx].cdef_idx[idx + 5] = -1;
                }
                BlockSize::Bs256x256 => {
                    for k in 0..16 {
                        lf_mask[lf_idx].cdef_idx[k] = -1;
                    }
                }
                _ => {}
            }
        }

        // Per-plane loop-restoration unit info. With SDP and a 64x64 root the
        // chroma planes are read later, between the luma and chroma trees.
        let sbsz = sb_step * 4;
        let sdp_root_split =
            root_bs == BlockSize::Bs64x64 && fi.sdp && !fi.is_inter_or_switch && !is_tip_frame;
        let lr_geom = SbLrGeom {
            bx,
            by,
            col_start,
            col_end,
            row_start,
            row_end,
            ss_hor: fi.ss_hor,
            ss_ver: fi.ss_ver,
            sbsz,
            sb256w,
        };
        if !is_tip_frame {
            read_sb_restoration(
                &mut *msac,
                &mut ts.cdf.m,
                &mut *lr_mask,
                &mut ts.ns_wiener_bank,
                frame_hdr,
                &lr_geom,
                0..if sdp_root_split { 1 } else { 3 },
            );
        }
        let mut dir = 0i32;
        let mut sdp_cfl_disallowed = 0i32;
        let mut intra_region = 0i32;
        let mut bx_m = bx;
        let mut by_m = by;
        let mut cbx = bx;
        let mut cby = by;
        let mut part_w_idx = 0usize;
        let mut part_r_idx = 0usize;

        // Active dequant tables for this superblock: frame-wide unless a prior
        // delta-q has shifted the running qindex away from `quant.yac`.
        let dq_active_init = if sb_last_qidx == fi.quant_yac {
            *recon_frame.dq
        } else {
            sb_dqmem
        };

        let mut recon = ReconCtx {
            bd,
            dst_y: &mut *dst_y,
            dst_u: &mut *dst_u,
            dst_v: &mut *dst_v,
            cdf_coef: &mut ts.cdf.coef,
            cf: &mut *cf,
            frame: recon_frame,
            masks,
            scratch: &mut *recon_scratch,
            edge: &mut recon_edge[..],
            cur_segmap: &mut *cur_segmap,
            prev_segmap,
            b4_stride: fi.b4_stride,
            segmap_uv: &mut *segmap_uv,
            segmap_uv_stride,
            last_qidx: sb_last_qidx,
            dqmem: sb_dqmem,
            dq_active: dq_active_init,
            seg_id_err: false,
            lf_mask: &mut *lf_mask,
            lf_idx,
            sb256w,
            cur_ccsomap: &mut cur_ccsomap[..],
            prev_ccsomap: [prev_ccsomap[0], prev_ccsomap[1], prev_ccsomap[2]],
            rt: &mut *rt,
            rf,
            cur_mvs: &mut *cur_mvs,
            refp,
            svc,
            scratch_u_has_cf: 0,
            seq_hdr,
            frm_hdr,
            warpmv: [crate::headers::WarpedMotionParams::default(); 2],
            a_sb_cache: crate::env::SBEdgeCtx::default(),
            bawp_ab: [(256, 0); 3],
        };

        // Snapshot the above-row block context into `a_sb_cache` before the
        // single-ref / has_cs_ext context derivations read this at the SB top
        // edge at 8x8 resolution. `ref` is always copied; `motion_mode` only
        // when there is a superblock above (otherwise the SB-top path is gated
        // off by `have_top`).
        if fi.is_inter_or_switch {
            let a_src = &a_arr[a_idx];
            recon.a_sb_cache.reference[0].copy_from_slice(&a_src.reference[0]);
            recon.a_sb_cache.reference[1].copy_from_slice(&a_src.reference[1]);
            if by > row_start {
                recon
                    .a_sb_cache
                    .motion_mode
                    .copy_from_slice(&a_src.motion_mode);
            }
        }

        if is_tip_frame {
            tip_frame_recon_sb(
                &mut recon,
                msac,
                &mut ts.cdf.m,
                &mut a_arr[a_idx],
                l,
                bx,
                by,
                root_bs,
                c_root_bs,
                fi,
            )?;
        } else {
            let intra_split_capable = !fi.is_inter_or_switch && !fi.allow_intrabc;
            let wants_split =
                intra_split_capable && (fi.n_passes > 1 || pass != crate::internal::PASS_ALL);

            if wants_split {
                let do_entropy = (pass & crate::internal::Pass::Entropy as u8) != 0;
                let do_recon = (pass & crate::internal::Pass::Recon as u8) != 0;

                // External split tasks will call this function once with
                // `pass=Entropy` and later with `pass=Recon`.  The old local
                // scaffold (`pass=PASS_ALL`, `n_passes>1`) still uses the same
                // owned store so both paths exercise identical replay payloads.
                let mut local_replay = SbReplayStore::default();

                if do_entropy {
                    {
                        let mut sb_ctx = SbCtx {
                            fi,
                            bx: &mut bx_m,
                            by: &mut by_m,
                            cbx: &mut cbx,
                            cby: &mut cby,
                            intra_region: &mut intra_region,
                            sdp_cfl_disallowed: &mut sdp_cfl_disallowed,
                            a: &mut a_arr[a_idx],
                            l: &mut *l,
                            msac: &mut *msac,
                            cdf_m: &mut ts.cdf.m,
                            cdf_mv: &mut ts.cdf.mv,
                            cdf_dmv: &mut ts.cdf.dmv,
                            part_w: &mut *part_w,
                            part_w_idx: &mut part_w_idx,
                            part_r,
                            part_r_idx: &mut part_r_idx,
                            sdp_lr: sdp_root_split.then_some(SdpLrRead {
                                lr_mask: &mut *lr_mask,
                                bank: &mut ts.ns_wiener_bank,
                                frame_hdr,
                                geom: lr_geom,
                            }),
                        };
                        decode_sb(
                            &mut sb_ctx,
                            &mut recon,
                            crate::internal::Pass::Entropy as u8,
                            root_bs,
                            c_root_bs,
                            &mut dir,
                        )?;
                    }

                    if do_recon {
                        local_replay.capture_from::<BD::Coef>(part_w, recon.scratch);
                    }
                }

                if do_recon {
                    if do_entropy {
                        local_replay.load_into::<BD::Coef>(recon.scratch);
                    } else {
                        // A real scheduler replay will have preloaded the scratch
                        // from its tile/sbrow-owned `SbReplayStore` before entering
                        // this pass.  Keep the cursor reset here so replay-only
                        // unit tests can call the pass directly after filling
                        // `recon.scratch`.
                        recon.scratch.reset_replay_cursors();
                    }

                    bx_m = bx;
                    by_m = by;
                    cbx = bx;
                    cby = by;
                    intra_region = 0;
                    sdp_cfl_disallowed = 0;
                    part_r_idx = 0;
                    let mut replay_part_w: Vec<u8> = Vec::new();
                    let mut replay_part_w_idx = 0usize;
                    let mut recon_dir = 0i32;
                    let replay_part_r: &[u8] = if do_entropy {
                        &local_replay.part[..]
                    } else {
                        part_r
                    };
                    let mut sb_ctx = SbCtx {
                        fi,
                        bx: &mut bx_m,
                        by: &mut by_m,
                        cbx: &mut cbx,
                        cby: &mut cby,
                        intra_region: &mut intra_region,
                        sdp_cfl_disallowed: &mut sdp_cfl_disallowed,
                        a: &mut a_arr[a_idx],
                        l: &mut *l,
                        msac: &mut *msac,
                        cdf_m: &mut ts.cdf.m,
                        cdf_mv: &mut ts.cdf.mv,
                        cdf_dmv: &mut ts.cdf.dmv,
                        part_w: &mut replay_part_w,
                        part_w_idx: &mut replay_part_w_idx,
                        part_r: replay_part_r,
                        part_r_idx: &mut part_r_idx,
                        sdp_lr: None,
                    };
                    decode_sb(
                        &mut sb_ctx,
                        &mut recon,
                        crate::internal::Pass::Recon as u8,
                        root_bs,
                        c_root_bs,
                        &mut recon_dir,
                    )?;
                }
            } else {
                if pass != crate::internal::PASS_ALL {
                    // Partial passes for inter/IntraBC are not safe until the MVRES
                    // replay path is wired.  Fail loudly rather than re-reading
                    // entropy or reconstructing with unresolved motion state.
                    return Err(());
                }
                let mut sb_ctx = SbCtx {
                    fi,
                    bx: &mut bx_m,
                    by: &mut by_m,
                    cbx: &mut cbx,
                    cby: &mut cby,
                    intra_region: &mut intra_region,
                    sdp_cfl_disallowed: &mut sdp_cfl_disallowed,
                    a: &mut a_arr[a_idx],
                    l: &mut *l,
                    msac: &mut *msac,
                    cdf_m: &mut ts.cdf.m,
                    cdf_mv: &mut ts.cdf.mv,
                    cdf_dmv: &mut ts.cdf.dmv,
                    part_w: &mut *part_w,
                    part_w_idx: &mut part_w_idx,
                    part_r,
                    part_r_idx: &mut part_r_idx,
                    sdp_lr: sdp_root_split.then_some(SdpLrRead {
                        lr_mask: &mut *lr_mask,
                        bank: &mut ts.ns_wiener_bank,
                        frame_hdr,
                        geom: lr_geom,
                    }),
                };
                decode_sb(
                    &mut sb_ctx,
                    &mut recon,
                    crate::internal::PASS_ALL,
                    root_bs,
                    c_root_bs,
                    &mut dir,
                )?;
            }
        }

        // Persist running delta-q state for the next superblock / sbrow.
        sb_last_qidx = recon.last_qidx;
        sb_dqmem = recon.dqmem;
        sb_seg_err |= recon.seg_id_err;

        // Save THIS superblock's bottom row into the above-row `ra` buffer (and
        // its top-left backup `ra_tl`) for the next SB row's neighbor access.
        // range so that `ra_tl` captures the correct per-SB top-left value; a
        // once-per-row save would leave `ra_tl` reflecting only the row's far
        // right edge and corrupt the SB-boundary top-left MV candidate.
        if refmvs_active {
            let crate::refmvs::Tile {
                r,
                ra,
                ra_tl,
                ra_off,
                ..
            } = &mut *recon.rt;
            crate::refmvs::save_tmvs(
                r,
                &mut ra[*ra_off..],
                ra_tl,
                bx >> 1,
                (bx + sb_step) >> 1,
                row_start >> 1,
                (by + sb_step) >> 1,
                rf.ih8,
                rf.iw8,
            );
        }

        bx += sb_step;
    }

    // Write back the running per-tile delta-q state.
    ts.last_qidx = sb_last_qidx;
    ts.dqmem = sb_dqmem;

    // Capture this tile's right column (from `l`) and, on its last sbrow, its
    // bottom row (from `a`) for the deblocker's tile-seam clamp.
    let ss_hor = (seq_hdr.layout != crate::headers::PixelLayout::I444) as usize;
    let ss_ver = (seq_hdr.layout == crate::headers::PixelLayout::I420) as usize;
    let tiles = &frame_hdr.tiling.t;
    let tile_col = ts.tiling.col as usize;
    if tile_col + 1 < tiles.cols as usize {
        let by = by as usize;
        let rows = (sb_step as usize).min(row_end as usize - by);
        for (pl, src, ss) in [(0, &l.tx_lpf_y, 0), (1, &l.tx_lpf_uv, ss_ver)] {
            let base = (tile_col * 2 + pl) * seam_h4 + (by >> ss);
            let n = (rows + ss) >> ss;
            let off = (by & 63) >> ss;
            seam_right[base..base + n].copy_from_slice(&src[off..off + n]);
        }
    }
    let tile_row_u = tile_row as usize;
    if by + sb_step >= row_end && tile_row_u + 1 < tiles.rows as usize {
        let a_row = tile_row_u * sb256w as usize;
        for x4 in col_start as usize..(col_end as usize).min(seam_w4) {
            let a = &a_arr[a_row + (x4 >> 6)];
            seam_bottom[tile_row_u * 2 * seam_w4 + x4] = a.tx_lpf_y[x4 & 63];
        }
        for xc in (col_start as usize >> ss_hor)..((col_end as usize + ss_hor) >> ss_hor) {
            let a = &a_arr[a_row + ((xc << ss_hor) >> 6)];
            seam_bottom[(tile_row_u * 2 + 1) * seam_w4 + xc] = a.tx_lpf_uv[xc & (63 >> ss_hor)];
        }
    }

    // Abort the frame on an out-of-range segment id (C `return -1`).
    if sb_seg_err {
        return Err(());
    }

    // Error out on symbol-decoder overread. frame_mode==2 whole-frame TIP frames
    // carry no entropy data — their (empty) symbol decoder is never advanced, so
    if frm_hdr.tip.frame_mode != 2 && msac.cnt() <= -15 {
        return Err(());
    }

    Ok(())
}

/// Minimal shared-mutable view used only by the parallel tile-row decode below.
struct DisjointMut<T> {
    ptr: *mut T,
    len: usize,
}

impl<T> Clone for DisjointMut<T> {
    fn clone(&self) -> Self {
        *self
    }
}
impl<T> Copy for DisjointMut<T> {}

// SAFETY: the wrapper is just a `(ptr, len)` pair; sharing it across threads is
// sound provided the disjointness invariant documented above is upheld by the
// caller (the tile-row partition).
unsafe impl<T: Send> Send for DisjointMut<T> {}
unsafe impl<T: Send> Sync for DisjointMut<T> {}

impl<T> DisjointMut<T> {
    fn new(s: &mut [T]) -> Self {
        Self {
            ptr: s.as_mut_ptr(),
            len: s.len(),
        }
    }
    /// SAFETY: the caller must only access indices that are disjoint from every
    /// other concurrent caller (guaranteed here by the tile-row partition).
    #[allow(clippy::mut_from_ref)]
    unsafe fn whole(&self) -> &mut [T] {
        unsafe { std::slice::from_raw_parts_mut(self.ptr, self.len) }
    }
}

#[inline]
fn parallel_tiles_complete(progress: &[std::sync::atomic::AtomicUsize], totals: &[usize]) -> bool {
    use std::sync::atomic::Ordering::Acquire;
    progress
        .iter()
        .zip(totals)
        .all(|(done, &total)| done.load(Acquire) >= total)
}

pub fn decode_frame_main(
    fc: &mut crate::internal::FrameContext,
    n_passes: i32,
    n_tc: i32,
    pool: Option<&crate::mtpool::ThreadPool>,
) -> Result<(), ()> {
    #[cfg(feature = "adaptive_cdf")]
    {
        if fc.frame_hdr.disable_cdf_update != 0 {
            decode_frame_main_select::<false>(fc, n_passes, n_tc, pool)
        } else {
            decode_frame_main_select::<true>(fc, n_passes, n_tc, pool)
        }
    }

    #[cfg(not(feature = "adaptive_cdf"))]
    {
        decode_frame_main_select::<true>(fc, n_passes, n_tc, pool)
    }
}

#[inline]
fn decode_frame_main_select<const UPDATE_CDF: bool>(
    fc: &mut crate::internal::FrameContext,
    n_passes: i32,
    n_tc: i32,
    pool: Option<&crate::mtpool::ThreadPool>,
) -> Result<(), ()> {
    #[cfg(all(target_arch = "x86_64", feature = "sse"))]
    {
        decode_frame_main_inner::<UPDATE_CDF, crate::msac::SseMsacBackend>(fc, n_passes, n_tc, pool)
    }
    #[cfg(not(all(target_arch = "x86_64", feature = "sse")))]
    {
        decode_frame_main_inner::<UPDATE_CDF, crate::msac::ScalarMsacBackend>(
            fc, n_passes, n_tc, pool,
        )
    }
}

fn decode_frame_main_inner<const UPDATE_CDF: bool, B: MsacBackend<UPDATE_CDF>>(
    fc: &mut crate::internal::FrameContext,
    n_passes: i32,
    n_tc: i32,
    pool: Option<&crate::mtpool::ThreadPool>,
) -> Result<(), ()> {
    let crate::internal::FrameContext {
        exec,
        seq_hdr,
        frame_hdr,
        a,
        ts,
        lf,
        sb256w,
        sb_step,
        root_bs,
        bw,
        bh,
        refdir,
        refdist,
        absrefdist,
        furthest_future_refidx,
        skip_mode_refs,
        cur_pic,
        dq,
        qm,
        bitdepth_max,
        ss_hor,
        ss_ver,
        cur_segmap,
        prev_segmap,
        cur_ccsomap,
        prev_ccsomap,
        b4_stride,
        sb256h,
        sbh,
        rf,
        inloop_filters,
        refp,
        mvs,
        ref_mvs,
        refrefpoc,
        refcnt,
        refpoc,
        svc,
        ..
    } = fc;
    let exec = &*exec;
    let fc_sb256h = *sb256h;
    let fc_sbh = *sbh;
    let fc_inloop_filters = *inloop_filters;

    let seq_hdr = &**seq_hdr;
    let frame_hdr = &**frame_hdr;
    let root_bs = *root_bs;
    let sb256w = *sb256w;
    let sb_step = *sb_step;
    let bw = *bw;
    let bh = *bh;
    let b4_stride_v = *b4_stride;

    if frame_hdr.segmentation.enabled != 0 {
        let needed = (b4_stride_v as usize) * 64 * (fc_sb256h as usize);
        if cur_segmap.len() != needed {
            if needed > cur_segmap.len() {
                cur_segmap
                    .try_reserve_exact(needed - cur_segmap.len())
                    .map_err(|_| ())?;
            }
            cur_segmap.resize(needed, 0);
        }
        cur_segmap.fill(0);
    }
    let any_ccso_plane = frame_hdr.ccso.p.iter().any(|p| p.enabled != 0);
    if frame_hdr.ccso.enabled != 0 && any_ccso_plane {
        let ccso_unit_log2 = ccso_unit_log2_from_headers(seq_hdr, frame_hdr);
        let ccso_unit_mi = 1usize << (ccso_unit_log2 - 2);
        let ccso_unit_w = (bw as usize).div_ceil(ccso_unit_mi);
        let ccso_unit_h = (bh as usize).div_ceil(ccso_unit_mi);
        let needed = 3usize
            .saturating_mul(ccso_unit_w)
            .saturating_mul(ccso_unit_h);
        if cur_ccsomap.len() != needed {
            if needed > cur_ccsomap.len() {
                cur_ccsomap
                    .try_reserve_exact(needed - cur_ccsomap.len())
                    .map_err(|_| ())?;
            }
            cur_ccsomap.resize(needed, 0);
        }
        cur_ccsomap.fill(0);
    } else {
        cur_ccsomap.clear();
    }

    let prev_segmap_ref: Option<&[u8]> = prev_segmap.as_deref();
    let prev_ccsomap_ref: [Option<&[u8]>; 3] = [
        prev_ccsomap[0].as_deref(),
        prev_ccsomap[1].as_deref(),
        prev_ccsomap[2].as_deref(),
    ];
    let refdir = *refdir;
    let skip_mode_refs = *skip_mode_refs;

    let ss_hor_v = *ss_hor;
    let ss_ver_v = *ss_ver;
    let bitdepth_max_v = *bitdepth_max;
    // The plane allocation is sized for the 128-aligned frame dimensions (see
    // DefaultPicAllocator::alloc_picture: `aligned_h = (h + 127) & !127`), which
    // gives bottom padding past the cropped/visible height. Reconstruction
    // legitimately writes whole transform blocks that overhang the visible edge
    // padded). Span the slices over the *allocated* height so those overhang
    // writes stay in bounds rather than panicking on the cropped height.
    let aligned_h: usize = ((cur_pic.p.h.max(0) as usize) + 127) & !127;
    let y_h: usize = aligned_h;
    let uv_h: usize = if seq_hdr.layout == crate::headers::PixelLayout::I400 {
        0
    } else {
        aligned_h >> ss_ver_v
    };
    // Byte strides as allocated; the recon path indexes planes in *samples*, so
    // `*_stride_px` below is the per-sample stride (byte stride / bytes-per-sample).
    let y_stride_bytes: usize = cur_pic.stride[0].unsigned_abs();
    let uv_stride_bytes: usize = cur_pic.stride[1].unsigned_abs();
    // bitdepth in bits from bitdepth_max (255 -> 8, 1023 -> 10, 4095 -> 12).
    let bitdepth_v: u32 = (crate::intops::ulog2((bitdepth_max_v + 1) as u32)) as u32;
    let bytes_per_sample: usize = if bitdepth_v > 8 { 2 } else { 1 };
    let y_stride_px: usize = y_stride_bytes / bytes_per_sample;
    let uv_stride_px: usize = uv_stride_bytes / bytes_per_sample;
    // `f->seq_hdr->hbd` (0 for 8bpc, 1 for 10/12bpc); used by deblock thresholds.
    let hbd_v: i32 = (bitdepth_v > 8) as i32;
    // once per frame for the compound + interintra recon paths.
    let masks = crate::wedge::masks();
    let recon_frame = ReconFrameCtx {
        exec,
        dq: &*dq,
        qm: &*qm,
        y_stride_px,
        uv_stride_px,
        ss_hor: ss_hor_v,
        ss_ver: ss_ver_v,
        bitdepth_max: bitdepth_max_v,
        seq_fsc: seq_hdr.fsc,
        seq_ist: seq_hdr.ist,
        seq_cctx: seq_hdr.cctx,
        layout: seq_hdr.layout,
        bitdepth: bitdepth_v,
        seg_lossless: frame_hdr.segmentation.lossless,
        reduced_txtp_set: frame_hdr.reduced_txtp_set as i32,
        tcq: frame_hdr.tcq != 0,
        parity_hiding: frame_hdr.parity_hiding != 0,
        seq_intra_edge_filter: seq_hdr.intra_edge_filter,
        seq_ibp: seq_hdr.ibp,
        seq_inter_ddt: seq_hdr.inter_ddt,
        cfl_ds_filter_index: seq_hdr.cfl_ds_filter_index as i32,
        ibp_weights: *crate::ibp::ibp_weights(),
    };

    let c_root_bs = if seq_hdr.layout == crate::headers::PixelLayout::I400 {
        BlockSize::Invalid
    } else {
        root_bs
    };
    let cols = frame_hdr.tiling.t.cols as i32;
    let rows = frame_hdr.tiling.t.rows as i32;
    let keyframe = frame_hdr.is_key_or_intra();
    let is_tip = frame_hdr.tip.frame_mode == 2;

    // multi-threaded reset lives in decode_frame_init. Without this, the above
    // neighbour `midx`/mode arrays retain default 0 instead of the 0xff "no
    // neighbour" sentinel, corrupting intra-mode context derivation.
    if n_tc <= 1 {
        let n_a = (sb256w * rows) as usize;
        for ctx in a.iter_mut().take(n_a) {
            reset_context(ctx, keyframe, is_tip);
        }
    }

    // Initialize the reference-MV frame state (`f->rf`) and a per-tile working
    // Tile. For IntraBC on an intra frame only the spatial grid / above-row /
    // banks are needed (no temporal candidates). For inter frames the reference
    // temporal MVs are wired and (when use_ref_frame_mvs) projected per sbrow.
    let allow_intrabc = frame_hdr.allow_intrabc != 0;
    let is_inter_or_switch = frame_hdr.is_inter_or_switch();
    let refmvs_active = allow_intrabc || is_inter_or_switch;
    if refmvs_active {
        refmvs::init_frame(
            rf, seq_hdr, frame_hdr, refpoc, refrefpoc, refcnt, ref_mvs, false, false,
        )?;
    }

    // ref_frame_mvs is enabled, sized for the whole frame; the per-block splat
    // (splat_oneref_mv's `t_dst`) writes decoded MVs into `rf.rp` so later frames
    let _ = &mvs;
    if refmvs_active && seq_hdr.ref_frame_mvs {
        let needed = (fc_sb256h as usize) * 32 * ((b4_stride_v >> 1) as usize);
        if rf.rp.len() != needed {
            if needed > rf.rp.len() {
                rf.rp
                    .try_reserve_exact(needed - rf.rp.len())
                    .map_err(|_| ())?;
            }
            rf.rp.resize(needed, refmvs::TemporalBlock::default());
        }
        rf.rp.fill(refmvs::TemporalBlock::default());
    } else {
        rf.rp.clear();
    }

    // The projection of reference temporal MVs into `rf.rp_proj`
    // path uses a rolling-window projection buffer (`rp_proj_off` is a fixed
    // 2-row top margin, not a per-sbrow base), so each sbrow's load_tmvs
    // overwrites the previous sbrow's projection; batching all rows up front
    // would leave only the last row's data and corrupt the temporal MV grid
    // that the inter tmvp candidates and frame_mode=2 whole-frame TIP recon read.
    let need_load_tmvs = is_inter_or_switch && frame_hdr.use_ref_frame_mvs != 0;
    // Hold the current-frame temporal MV grid separately so the inter splat can
    // mutate it while `rf` itself stays shared immutably (refmvs_find reads it).
    let mut cur_mvs: Vec<refmvs::TemporalBlock> = std::mem::take(&mut rf.rp);
    // Reference pixel planes for inter MC, shared from the FrameContext refp.
    let refp_pics: [Option<std::sync::Arc<crate::picture::Picture>>; 7] =
        std::array::from_fn(|i| refp[i].pic.clone());
    let svc_v = *svc;

    // Compound `comp_type`/`get_compref_ctx` neighbour contexts need the
    // few scalar `rf` fields needed before the loop so `rf` can be re-borrowed
    // mutably (for the per-sbrow load_tmvs) inside it.
    let ffr_idx = *furthest_future_refidx;
    let tip_ref = rf.tip.reference;
    let rf_rp_stride = rf.rp_stride;

    // Precompute the per-frame filter parameters once (deblock thresholds, CDEF
    // strength decomposition, etc.) so the per-superblock-row filter pass can run
    // without re-deriving them. Filters are gated by `fc.inloop_filters`.
    let filter_params = FilterFrameParams::new(
        seq_hdr,
        frame_hdr,
        ss_hor_v,
        ss_ver_v,
        cur_pic.stride[0],
        cur_pic.stride[1],
        bitdepth_v as i32,
        fc_inloop_filters,
    );
    let sb128 = frame_hdr.sb128 as i32;

    // for every superblock-row in the tile row, THEN PHASE B runs the deferred
    // filter pass `for sby: filter_sbrow(sby)`.Filters must run only after a
    // whole tile row has decoded because intrabc reads pre-filter pixels to the
    // left within the tile row.
    macro_rules! run_decode_tile_rows {
        ($bd:expr, $Pixel:ty, $Coef:ty) => {{
            let bd_local = $bd;
            let estimated_decode_units = (((bh + sb_step - 1) / sb_step).max(0) as usize)
                .saturating_mul(cols.max(0) as usize);
            let estimated_filter_bands = ((bh + 15) >> 4).max(0) as usize;
            let do_parallel = (n_tc as usize) >= 2
                && !need_load_tmvs
                && (estimated_decode_units > 1 || estimated_filter_bands > 1);
            let active_pool = pool;
            let (dst_y, dst_u, dst_v): (&mut [$Pixel], &mut [$Pixel], &mut [$Pixel]) = cur_pic
                .plane_slices_rows3_mut::<$Pixel>(
                y_h,
                uv_h,
                seq_hdr.layout != crate::headers::PixelLayout::I400,
            );
            if do_parallel {
                // One persistent dispatch replaces the old decode-barrier-filter
                // two-phase. Every worker runs the same loop and pulls whichever
                // unit is available, preferring filter so that as decode marches
                // top-to-bottom the loop-filter trails a couple of rows behind it
                // on spare workers instead of waiting on a global barrier:
                //   (1) a *ready* filter tile-row — ready once its own and its
                //       vertically-adjacent rows (tr-1,tr,tr+1) have finished
                //       decoding, so every seam pixel/mask entry it reads exists;
                //   (2) else the next decode tile (claimed row-major);
                //   (3) else PARK on a condvar until a decode completion (or the
                //       final filter completion) signals progress. Workers never
                //       busy-spin — the spin is exactly what regressed the earlier
                //       fused attempt, its progress-poll traffic competing with the
                //       decode critical path.
                let n_tiles = (rows as usize) * (cols as usize);
                let rows_us = rows as usize;
                let max_workers = (n_tc as usize).max(1);
                let dst_y_dm = DisjointMut::new(dst_y);
                let dst_u_dm = DisjointMut::new(dst_u);
                let dst_v_dm = DisjointMut::new(dst_v);
                let a_dm = DisjointMut::new(&mut a[..]);
                let filter_params = &filter_params;
                let cseg_dm = DisjointMut::new(&mut cur_segmap[..]);
                let cccso_dm = DisjointMut::new(&mut cur_ccsomap[..]);
                let cmvs_dm = DisjointMut::new(&mut cur_mvs[..]);
                let ts_dm = DisjointMut::new(&mut ts[..]);
                let recon_frame = &recon_frame;
                let refp_pics = &refp_pics;
                let svc_v = &svc_v;
                let rf_imm: &refmvs::Frame = &*rf;
                let prev_ccsomap_ref = prev_ccsomap_ref;
                let refdist: &[i8; 7] = refdist;
                let absrefdist: &[u8; 7] = absrefdist;

                // Split `lf` into disjoint field borrows: masks are written by
                // decode (and the idempotent bottom-edge crop) through DisjointMut;
                // everything else is read-only for the whole dispatch.
                let lf = &mut *lf;
                let uv_segmap_stride = lf.uv_segmap_stride;
                let base_q = lf.base_q;
                let gdf_ref_dst_idx = lf.gdf_ref_dst_idx;
                let wiener_idx = lf.wiener_idx;
                let ns_subclass_class_idx = lf.ns_subclass_class_idx;
                let restore_planes = lf.restore_planes;
                let lf_start_of_tile_row: &[u8] = &lf.start_of_tile_row;
                let mask_dm = DisjointMut::new(&mut lf.mask[..]);
                let lrmask_dm = DisjointMut::new(&mut lf.lr_mask[..]);
                let (seam_h4, seam_w4) = (lf.seam_lpf.h4, lf.seam_lpf.w4);
                let seam_r_dm = DisjointMut::new(&mut lf.seam_lpf.right[..]);
                let seam_b_dm = DisjointMut::new(&mut lf.seam_lpf.bottom[..]);
                let seguv_dm =
                    DisjointMut::new(std::sync::Arc::make_mut(&mut lf.segmap_uv).as_mut_slice());
                let mask_dm = &mask_dm;
                let lrmask_dm = &lrmask_dm;
                let seam_r_dm = &seam_r_dm;
                let seam_b_dm = &seam_b_dm;
                let seguv_dm = &seguv_dm;

                let got_err = std::sync::atomic::AtomicBool::new(false);
                let got_err = &got_err;

                let cols_us = cols as usize;
                let tile_nsb: Vec<usize> = {
                    let ts_ref = unsafe { ts_dm.whole() };
                    (0..n_tiles)
                        .map(|t| {
                            let tb = &ts_ref[t].tiling;
                            (((tb.row_end - tb.row_start) + sb_step - 1) / sb_step).max(0) as usize
                        })
                        .collect()
                };
                let tile_nsb = &tile_nsb[..];
                let sb64h_us = ((bh + 15) >> 4).max(0) as usize;
                let by64_tile_row: Vec<usize> = {
                    let ts_ref = unsafe { ts_dm.whole() };
                    let mut map = vec![0usize; sb64h_us];
                    for tr in 0..rows_us {
                        let tb = &ts_ref[tr * cols_us].tiling;
                        let by64_start = ((tb.row_start + 15) >> 4).max(0) as usize;
                        let by64_end = ((tb.row_end + 15) >> 4).max(0) as usize;
                        for slot in map
                            .iter_mut()
                            .take(by64_end.min(sb64h_us))
                            .skip(by64_start.min(sb64h_us))
                        {
                            *slot = tr;
                        }
                    }
                    map
                };
                let by64_tile_row = &by64_tile_row[..];
                let n_decode_units = tile_nsb.iter().copied().sum::<usize>();
                let n_filter_units = sb64h_us;
                // Every sb64 band is filtered, including a partial bottom band when
                // `bh` is not a multiple of 16 (`h4 = min(bh - y64 * 16, 16)` inside
                // the band filters). Skipping it left the last rows unfiltered, e.g.
                // the horizontal edge at the frame bottom that AVM deblocks.
                let n_filter_bands = n_filter_units;
                let n_workers = max_workers
                    .min(n_decode_units.max(n_filter_units).max(1))
                    .max(1);
                let tile_sbrow: Vec<std::sync::atomic::AtomicUsize> = (0..n_tiles)
                    .map(|_| std::sync::atomic::AtomicUsize::new(0))
                    .collect();
                let tile_sbrow = &tile_sbrow[..];
                let tile_busy: Vec<std::sync::atomic::AtomicBool> = (0..n_tiles)
                    .map(|_| std::sync::atomic::AtomicBool::new(false))
                    .collect();
                let tile_busy = &tile_busy[..];
                let dec_remaining: Vec<std::sync::atomic::AtomicUsize> = (0..rows_us)
                    .map(|_| std::sync::atomic::AtomicUsize::new(cols as usize))
                    .collect();
                let dec_remaining = &dec_remaining[..];
                let sb64_dec_remaining: Vec<std::sync::atomic::AtomicUsize> = (0..n_filter_units)
                    .map(|_| std::sync::atomic::AtomicUsize::new(cols_us))
                    .collect();
                let sb64_dec_remaining = &sb64_dec_remaining[..];
                let granular_filter_ready = !allow_intrabc;
                let flt_done = std::sync::atomic::AtomicUsize::new(0);
                let flt_done = &flt_done;
                // Filter scheduler.
                //   deblock      : single owner, in-order        -> deblock_progress
                //   CDEF SAVE    : single owner, in-order (cheap)-> cdef_save_progress
                //   CDEF FILTER  : data-parallel rows            -> cdef_filter_claim/_done
                //   LR           : data-parallel rows            -> lr_claim/flt_done
                let deblock_rows_busy = std::sync::atomic::AtomicBool::new(false);
                let deblock_rows_busy = &deblock_rows_busy;
                let deblock_cols_claim = std::sync::atomic::AtomicUsize::new(0);
                let deblock_cols_claim = &deblock_cols_claim;
                let cols_done: Vec<std::sync::atomic::AtomicBool> = (0..n_filter_bands)
                    .map(|_| std::sync::atomic::AtomicBool::new(false))
                    .collect();
                let cols_done = &cols_done;
                let deblock_progress = std::sync::atomic::AtomicUsize::new(0);
                let deblock_progress = &deblock_progress;
                let cdef_save_progress = std::sync::atomic::AtomicUsize::new(0);
                let cdef_save_progress = &cdef_save_progress;
                let cdef_save_claim = std::sync::atomic::AtomicUsize::new(0);
                let cdef_save_claim = &cdef_save_claim;
                // Per-band CDEF-SAVE completion. SAVE is data-parallel (each band
                // writes disjoint seam slots: cdef_line[k] and cdef_top one-past, which
                // save(k+1) skips), so it finishes out of order; cdef-filter(k) needs
                // save(k-1) and save(k) (it reads cdef_line[k-1] and cdef_top[k+1]).
                let cdef_save_done: Vec<std::sync::atomic::AtomicBool> = (0..n_filter_bands)
                    .map(|_| std::sync::atomic::AtomicBool::new(false))
                    .collect();
                let cdef_save_done = &cdef_save_done;
                let cdef_filter_claim = std::sync::atomic::AtomicUsize::new(0);
                let cdef_filter_claim = &cdef_filter_claim;
                let cdef_filter_done = std::sync::atomic::AtomicUsize::new(0);
                let cdef_filter_done = &cdef_filter_done;
                let lr_claim = std::sync::atomic::AtomicUsize::new(0);
                let lr_claim = &lr_claim;
                // Per-band CDEF-FILTER completion flags. CDEF-filter rows finish out
                // of order, so LR (which needs its own root's CDEF complete) checks
                // these rather than the done count, letting LR overlap CDEF-filter
                // instead of waiting at a full-CDEF barrier.
                let cdef_band_done: Vec<std::sync::atomic::AtomicBool> = (0..n_filter_bands)
                    .map(|_| std::sync::atomic::AtomicBool::new(false))
                    .collect();
                let cdef_band_done = &cdef_band_done;
                // `filter_progress` retained as the LR completion cursor for
                // park/wake accounting (== flt_done after the LR pass).
                let filter_progress = std::sync::atomic::AtomicUsize::new(0);
                let filter_progress = &filter_progress;
                // Per-frame seam line buffers, pre-sized so the parallel passes never
                // resize. Written by the single-owner SAVE/deblock passes, read by the
                // parallel FILTER/LR passes; the two phases are separated in time by
                // the cursors, so DisjointMut shared access is sound.
                let n_roots_alloc = ((n_filter_bands >> sb128) + 2).max(1);
                let mono_alloc = seq_hdr.layout == crate::headers::PixelLayout::I400;
                ensure_filter_lines(
                    &mut lf.cdef_line_store,
                    &mut lf.cdef_top_store,
                    &mut lf.lr_db_store,
                    bh,
                    filter_params.y_stride,
                    filter_params.uv_stride,
                    n_roots_alloc,
                    mono_alloc,
                )?;
                if bd_local.bitdepth() > 8 {
                    ensure_filter_lines_hbd(
                        &mut lf.cdef_line_store_hbd,
                        &mut lf.cdef_top_store_hbd,
                        &mut lf.lr_db_store_hbd,
                        bh,
                        filter_params.y_stride,
                        filter_params.uv_stride,
                        n_roots_alloc,
                        mono_alloc,
                    )?;
                }
                let cdef_line_dm = DisjointMut::new(&mut lf.cdef_line_store[..]);
                let cdef_line_dm = &cdef_line_dm;
                let cdef_top_dm = DisjointMut::new(&mut lf.cdef_top_store[..]);
                let cdef_top_dm = &cdef_top_dm;
                let lr_db_dm = DisjointMut::new(&mut lf.lr_db_store[..]);
                let lr_db_dm = &lr_db_dm;
                let cdef_line_hbd_dm = DisjointMut::new(&mut lf.cdef_line_store_hbd[..]);
                let cdef_line_hbd_dm = &cdef_line_hbd_dm;
                let cdef_top_hbd_dm = DisjointMut::new(&mut lf.cdef_top_store_hbd[..]);
                let cdef_top_hbd_dm = &cdef_top_hbd_dm;
                let lr_db_hbd_dm = DisjointMut::new(&mut lf.lr_db_store_hbd[..]);
                let lr_db_hbd_dm = &lr_db_hbd_dm;
                crate::decode::lr_cdef_line_save::ensure_lr_cdef_line(
                    &mut lf.lr_cdef_line,
                    rows_us,
                    filter_params.y_stride,
                    filter_params.uv_stride,
                    mono_alloc,
                )?;
                if bd_local.bitdepth() > 8 {
                    crate::decode::lr_cdef_line_save::ensure_lr_cdef_line_hbd(
                        &mut lf.lr_cdef_line_hbd,
                        rows_us,
                        crate::decode::loopfilter::hbd_sample_stride(filter_params.y_stride),
                        crate::decode::loopfilter::hbd_sample_stride(filter_params.uv_stride),
                        mono_alloc,
                    )?;
                }
                let lr_cdef_dm = DisjointMut::new(std::slice::from_mut(&mut lf.lr_cdef_line));
                let lr_cdef_dm = &lr_cdef_dm;
                let lr_cdef_hbd_dm = DisjointMut::new(std::slice::from_mut(&mut lf.lr_cdef_line_hbd));
                let lr_cdef_hbd_dm = &lr_cdef_hbd_dm;
                let park_mx = std::sync::Mutex::new(());
                let park_mx = &park_mx;
                let park_cv = std::sync::Condvar::new();
                let park_cv = &park_cv;
                let park_waiters = std::sync::atomic::AtomicUsize::new(0);
                let park_waiters = &park_waiters;
                // A single global "something progressed" counter. Every producer
                // wake site bumps it (Release) after publishing its work, so an idle
                // worker can detect that progress happened with ONE relaxed-ish
                // atomic load instead of re-scanning all `n_tiles + n_filter_units`
                // per-unit atomics each spin iteration (that scan bounces O(units)
                // cache lines that other workers are actively writing, which is the
                // dominant source of MT timing noise on many-core targets). The
                // epoch is only a spin/scan-avoidance hint: the authoritative park
                // decision is still the full predicate recheck under `park_mx`, so a
                // missed bump can at worst cost a redundant scan, never a lost wakeup.
                let progress_epoch = std::sync::atomic::AtomicUsize::new(0);
                let progress_epoch = &progress_epoch;
                // Number of cheap epoch-poll spins before falling back to yield then
                // pthread_cond_wait. Each spin is now a single atomic load (not an
                // O(tiles+units) scan), so this trades a little busy-wait for avoiding
                // the high-variance OS condvar wakeup when work lands a few hundred
                // cycles later. Tunable; measure on the target.
                const PARK_SPIN_ITERS: usize = 96;
                let wake_one = || {
                    // Publish "progress happened" before (possibly) signalling, so a
                    // spinning worker that loads the new epoch also observes the work.
                    progress_epoch.fetch_add(1, std::sync::atomic::Ordering::Release);
                    // Avoid the pthread mutex/condvar path when all workers are
                    // currently running. A waiter increments `park_waiters` before
                    // its final predicate recheck under `park_mx`, so skipping here
                    // cannot lose a wakeup: either the waiter will see the freshly
                    // published atomic state during that final recheck, or it will
                    // have become visible in `park_waiters` before this notify.
                    if park_waiters.load(std::sync::atomic::Ordering::Relaxed) != 0 {
                        let _guard = park_mx.lock().unwrap_or_else(|e| e.into_inner());
                        park_cv.notify_one();
                    }
                };
                let wake_one = &wake_one;
                let wake_all = || {
                    progress_epoch.fetch_add(1, std::sync::atomic::Ordering::Release);
                    if park_waiters.load(std::sync::atomic::Ordering::Relaxed) != 0 {
                        let _guard = park_mx.lock().unwrap_or_else(|e| e.into_inner());
                        park_cv.notify_all();
                    }
                };
                let wake_all = &wake_all;
                let worker_seq = std::sync::atomic::AtomicUsize::new(0);
                let worker_seq = &worker_seq;

                let worker = || {
                    use std::sync::atomic::Ordering::{AcqRel, Acquire, Relaxed, Release};
                    let worker_id = worker_seq.fetch_add(1, Relaxed);
                    // A filter sb64 row is ready when the owning tile-row and its
                    // vertical neighbor tile-rows are fully decoded (Acquire pairs
                    // with the decode Release).
                    let tile_row_ready = |tr: usize| -> bool {
                        let lo = tr.saturating_sub(1);
                        let hi = (tr + 1).min(rows_us - 1);
                        (lo..=hi).all(|r| dec_remaining[r].load(Acquire) == 0)
                    };
                    let sb64_decoded = |by64: usize| -> bool {
                        sb64_dec_remaining
                            .get(by64)
                            .map(|r| r.load(Acquire) == 0)
                            .unwrap_or(true)
                    };
                    let filter_ready = |by64: usize| -> bool {
                        if granular_filter_ready {
                            // Deblock rows and the root-SB CDEF seam read the top
                            // neighbor. They do not need the next band: CDEF's
                            // normal by64 slice deliberately leaves the bottom two
                            // 4x4 rows for the following task.
                            sb64_decoded(by64) && (by64 == 0 || sb64_decoded(by64 - 1))
                        } else {
                            by64_tile_row
                                .get(by64)
                                .map(|&tr| tile_row_ready(tr))
                                .unwrap_or(false)
                        }
                    };
                    <$Coef as DecodeCoeff>::with_cf_scratch(|cf| {
                        WORKER_SCRATCH.with(|ws_cell| {
                            let mut ws_guard = ws_cell.borrow_mut();
                            let ws = ws_guard.get_or_insert_with(|| {
                                DecodeWorkerScratch::new(rf_rp_stride.max(1) as usize, bw, bh)
                            });
                            ws.trim_retained_capacity();
                            if ws.prepare(rf_rp_stride.max(1) as usize, bw, bh).is_err() {
                                got_err.store(true, Relaxed);
                                return;
                            }
                            let DecodeWorkerScratch {
                                rt,
                                recon_scratch,
                                part_w,
                                ccso_tmp_buf,
                                ccso_tmp_buf_hbd,
                                recon_edge8,
                                recon_edge16,
                            } = &mut *ws;
                            let recon_edge =
                                <$Pixel as DecodeEdgePixel>::edge_mut(recon_edge8, recon_edge16);
                            let mut l = BlockContext::default();
                            let part_r: &[u8] = &[];
                            let mut cached_fi: Option<(usize, SbFrameInfo)> = None;

                            loop {
                                if got_err.load(Relaxed) {
                                    return;
                                }
                                // Snapshot the progress epoch *before* the phase-1/2 work
                                // scan below.
                                let seen_epoch = progress_epoch.load(Acquire);

                                let mut claimed = None;
                                let start_t = if n_tiles != 0 { worker_id % n_tiles } else { 0 };
                                for ti in 0..n_tiles {
                                    let t = (start_t + ti) % n_tiles;
                                    if tile_sbrow[t].load(Acquire) >= tile_nsb[t] {
                                        continue;
                                    }
                                    if tile_busy[t].swap(true, AcqRel) {
                                        continue; // another worker is advancing this tile
                                    }
                                    if tile_sbrow[t].load(Acquire) >= tile_nsb[t] {
                                        tile_busy[t].store(false, Release);
                                        continue;
                                    }
                                    claimed = Some(t);
                                    break;
                                }
                                if let Some(t) = claimed {
                                    let tr = t / cols_us;
                                    let ts_idx = t;
                                    let a = unsafe { a_dm.whole() };
                                    let cur_segmap = unsafe { cseg_dm.whole() };
                                    let cur_ccsomap = unsafe { cccso_dm.whole() };
                                    let cur_mvs = unsafe { cmvs_dm.whole() };
                                    let ts = unsafe { ts_dm.whole() };
                                    let dst_y = unsafe { dst_y_dm.whole() };
                                    let dst_u = unsafe { dst_u_dm.whole() };
                                    let dst_v = unsafe { dst_v_dm.whole() };
                                    let mask = unsafe { mask_dm.whole() };
                                    let lr_mask = unsafe { lrmask_dm.whole() };
                                    // Each tile writes only its own seam slots.
                                    let seam_right = unsafe { seam_r_dm.whole() };
                                    let seam_bottom = unsafe { seam_b_dm.whole() };
                                    let segmap_uv = unsafe { seguv_dm.whole() };
                                    let (cs, ce, rs, re) = {
                                        let tb = &ts[ts_idx].tiling;
                                        (tb.col_start, tb.col_end, tb.row_start, tb.row_end)
                                    };
                                    if cached_fi.as_ref().map_or(true, |(ct, _)| *ct != t) {
                                        cached_fi = Some((
                                            t,
                                            SbFrameInfo::from_frame(SbFrameInfoArgs {
                                                seq_hdr,
                                                frame_hdr,
                                                bw,
                                                bh,
                                                root_bs,
                                                sb_step,
                                                n_passes,
                                                refdir,
                                                refdist,
                                                absrefdist,
                                                skip_mode_refs,
                                                tile_col_start: cs,
                                                tile_col_end: ce,
                                                tile_row_start: rs,
                                                tile_row_end: re,
                                                furthest_future_refidx: ffr_idx,
                                                tip: tip_ref,
                                            }),
                                        ));
                                    }
                                    let fi = &cached_fi.as_ref().unwrap().1;

                                    // Keep advancing the same tile while it remains ready.
                                    loop {
                                        let s = tile_sbrow[t].load(Relaxed);
                                        if s >= tile_nsb[t] {
                                            tile_busy[t].store(false, Release);
                                            wake_one();
                                            break;
                                        }

                                        let by = rs + (s as i32) * sb_step;
                                        let buf = std::mem::take(&mut ts[ts_idx].msac_buf);
                                        part_w.clear();
                                        reset_context(&mut l, keyframe, is_tip);
                                        // Resume this tile's parked entropy state for sbrow `s`.
                                        let (sbrow_res, saved_msac_state) = {
                                            let mut msac = B::resume(&buf, ts[ts_idx].msac_state);
                                            let sbrow_res = decode_tile_sbrow_entropy(
                                                DecodeTileSbrowEntropyCtx {
                                                    bd: bd_local,
                                                    fi,
                                                    frame_hdr,
                                                    ts: &mut ts[ts_idx],
                                                    msac: &mut msac,
                                                    a_arr: &mut *a,
                                                    lf_mask: &mut *mask,
                                                    lr_mask: &mut *lr_mask,
                                                    seam_right: &mut *seam_right,
                                                    seam_bottom: &mut *seam_bottom,
                                                    seam_h4,
                                                    seam_w4,
                                                    l: &mut l,
                                                    dst_y: &mut *dst_y,
                                                    dst_u: &mut *dst_u,
                                                    dst_v: &mut *dst_v,
                                                    cf: &mut *cf,
                                                    recon_scratch: &mut *recon_scratch,
                                                    recon_edge: &mut *recon_edge,
                                                    recon_frame,
                                                    cur_segmap: &mut cur_segmap[..],
                                                    prev_segmap: prev_segmap_ref,
                                                    segmap_uv: &mut *segmap_uv,
                                                    segmap_uv_stride: uv_segmap_stride,
                                                    cur_ccsomap: &mut cur_ccsomap[..],
                                                    prev_ccsomap: prev_ccsomap_ref,
                                                    part_w: &mut *part_w,
                                                    part_r,
                                                    by,
                                                    sb256w,
                                                    pass: crate::internal::PASS_ALL,
                                                    root_bs,
                                                    c_root_bs,
                                                    rt: &mut *rt,
                                                    rf: rf_imm,
                                                    cur_mvs: &mut *cur_mvs,
                                                    refp: refp_pics,
                                                    svc: svc_v,
                                                    seq_hdr,
                                                    frm_hdr: frame_hdr,
                                                    masks,
                                                },
                                            );
                                            let saved_msac_state = msac.save();
                                            (sbrow_res, saved_msac_state)
                                        };
                                        // Park the advanced entropy state + buffer back. The MSAC
                                        // context is dropped before moving `buf` back into the tile
                                        // state, so the borrowed buffer cannot outlive this scope.
                                        ts[ts_idx].msac_state = saved_msac_state;
                                        ts[ts_idx].msac_buf = buf;
                                        if sbrow_res.is_err() {
                                            got_err.store(true, Relaxed);
                                            cf.fill(<$Coef as crate::pixel::Coeff>::ZERO);
                                            tile_busy[t].store(false, Release);
                                            wake_all();
                                            return;
                                        }

                                        let new_s = s + 1;
                                        tile_sbrow[t].store(new_s, Release);

                                        // Publish the exact sb64 bands covered by this
                                        // decoded root-sbrow. This is what lets the
                                        // filter side trail decode at sb64 granularity
                                        // instead of waiting for the whole tile-row.
                                        let row_start = by.max(0) as usize;
                                        let row_end =
                                            (by + sb_step).min(re).min(bh).max(by) as usize;
                                        let by64_start = (row_start >> 4).min(n_filter_units);
                                        let by64_end = ((row_end + 15) >> 4).min(n_filter_units);
                                        let mut made_filter_ready = false;
                                        for by64 in by64_start..by64_end {
                                            if sb64_dec_remaining[by64].fetch_sub(1, AcqRel) == 1 {
                                                made_filter_ready = true;
                                            }
                                        }

                                        if new_s >= tile_nsb[t] {
                                            tile_busy[t].store(false, Release);
                                            dec_remaining[tr].fetch_sub(1, AcqRel);
                                            wake_one();
                                            break;
                                        }
                                        if made_filter_ready {
                                            wake_one();
                                        }
                                    }
                                    continue;
                                }

                                // Reconstruction writes disjoint tile rows, but the
                                // in-loop filters deliberately reach across sb64
                                // boundaries. Running either filter work beside
                                // reconstruction, or two adjacent filter bands beside
                                // each other, aliases those boundary pixels. Finish the
                                // parallel tile decode first, then let worker zero run
                                // the ordered filter pipeline while the dispatch keeps
                                // the other workers joined.
                                let decode_done = parallel_tiles_complete(tile_sbrow, tile_nsb);
                                if !decode_done {
                                    std::thread::yield_now();
                                    continue;
                                }
                                if worker_id != 0 {
                                    return;
                                }

                                // (2) Filter pipeline
                                let mut did_work = false;
                                macro_rules! run_stage {
                                    ($k:expr, $stages:expr) => {{
                                        let by64 = $k as i32;
                                        let cur_segmap = unsafe { cseg_dm.whole() };
                                        let dst_y = unsafe { dst_y_dm.whole() };
                                        let dst_u = unsafe { dst_u_dm.whole() };
                                        let dst_v = unsafe { dst_v_dm.whole() };
                                        let sh = FilterShared {
                                            mask: unsafe { &*mask_dm.whole() },
                                            lr_mask: unsafe { &*lrmask_dm.whole() },
                                            segmap_uv: unsafe { &*seguv_dm.whole() },
                                            start_of_tile_row: lf_start_of_tile_row,
                                            seams: crate::lf_mask::TileSeams {
                                                right: unsafe { &*seam_r_dm.whole() },
                                                bottom: unsafe { &*seam_b_dm.whole() },
                                                h4: seam_h4,
                                                w4: seam_w4,
                                            },
                                            uv_segmap_stride,
                                            base_q,
                                            gdf_ref_dst_idx,
                                            wiener_idx,
                                            ns_subclass_class_idx,
                                            restore_planes,
                                        };
                                        // SAFETY: SAVE/deblock (writers) and FILTER/LR
                                        // (readers) of the seam buffers are separated in
                                        // time by the stage cursors, so the DisjointMut
                                        // accesses never overlap a write with a read.
                                        filter_sb64(
                                            bd_local,
                                            crate::decode::loopfilter::FilterSb64Ctx {
                                                exec,
                                                seq_hdr,
                                                frame_hdr,
                                                sh: &sh,
                                                fp: filter_params,
                                                cur_segmap,
                                                b4_stride: b4_stride_v,
                                                hbd: hbd_v,
                                                inloop: fc_inloop_filters,
                                                sbh: fc_sbh,
                                                sb_step,
                                                sb256w,
                                                sb128,
                                                bw,
                                                bh,
                                            },
                                            crate::decode::loopfilter::FilterSb64Scratch {
                                                cdef_line: unsafe { cdef_line_dm.whole() },
                                                cdef_top: unsafe { cdef_top_dm.whole() },
                                                lr_db_line: unsafe { lr_db_dm.whole() },
                                                lr_cdef_line: unsafe { &mut lr_cdef_dm.whole()[0] },
                                                ccso_tmp_buf: &mut *ccso_tmp_buf,
                                                cdef_line_hbd: unsafe { cdef_line_hbd_dm.whole() },
                                                cdef_top_hbd: unsafe { cdef_top_hbd_dm.whole() },
                                                lr_db_line_hbd: unsafe { lr_db_hbd_dm.whole() },
                                                lr_cdef_line_hbd: unsafe {
                                                    &mut lr_cdef_hbd_dm.whole()[0]
                                                },
                                                ccso_tmp_buf_hbd: &mut *ccso_tmp_buf_hbd,
                                            },
                                            crate::decode::loopfilter::FilterSb64Dst {
                                                y: &mut *dst_y,
                                                u: &mut *dst_u,
                                                v: &mut *dst_v,
                                            },
                                            crate::decode::loopfilter::FilterSb64Band {
                                                by64,
                                                stages: $stages,
                                            },
                                        );
                                    }};
                                }

                                // Stage A0: deblock COLS (data-parallel). Vertical edges are
                                // within-band and independent, so any worker filters any
                                // decode-ready band's columns. CAS-claim ready bands.
                                loop {
                                    let k = deblock_cols_claim.load(Acquire);
                                    // The horizontal pass for band k-1 reaches into
                                    // the first rows of band k. Do not start k's
                                    // vertical pass until that predecessor has
                                    // completed, otherwise both workers write the
                                    // same boundary pixels concurrently.
                                    if k >= n_filter_bands
                                        || deblock_progress.load(Acquire) < k
                                        || !filter_ready(k)
                                    {
                                        break;
                                    }
                                    if deblock_cols_claim
                                        .compare_exchange_weak(k, k + 1, AcqRel, Relaxed)
                                        .is_err()
                                    {
                                        continue;
                                    }
                                    run_stage!(k, crate::decode::STAGE_DEBLOCK_COLS);
                                    cols_done[k].store(true, Release);
                                    did_work = true;
                                    wake_one();
                                }

                                // Stage A1: deblock ROWS
                                if deblock_rows_busy
                                    .compare_exchange(false, true, AcqRel, Relaxed)
                                    .is_ok()
                                {
                                    let mut adv = false;
                                    loop {
                                        let k = deblock_progress.load(Relaxed);
                                        if k >= n_filter_bands || !cols_done[k].load(Acquire) {
                                            break;
                                        }
                                        run_stage!(k, crate::decode::STAGE_DEBLOCK_ROWS);
                                        deblock_progress.store(k + 1, Release);
                                        did_work = true;
                                        adv = true;
                                    }
                                    deblock_rows_busy.store(false, Release);
                                    if adv {
                                        wake_one();
                                    }
                                }

                                // Stage B: CDEF SAVE
                                loop {
                                    let k = cdef_save_claim.load(Acquire);
                                    if k >= n_filter_bands {
                                        break;
                                    }
                                    let dp = deblock_progress.load(Acquire);
                                    if k + 1 >= dp && dp < n_filter_bands {
                                        break;
                                    }
                                    if cdef_save_claim
                                        .compare_exchange_weak(k, k + 1, AcqRel, Relaxed)
                                        .is_err()
                                    {
                                        continue;
                                    }
                                    run_stage!(k, crate::decode::STAGE_CDEF_SAVE);
                                    cdef_save_done[k].store(true, Release);
                                    cdef_save_progress.fetch_add(1, AcqRel);
                                    did_work = true;
                                    wake_one();
                                }

                                // Stage C: CDEF FILTER
                                loop {
                                    let k = cdef_filter_claim.load(Acquire);
                                    if k >= n_filter_bands {
                                        break;
                                    }
                                    // The next root's LR backup (`copy_db`, taken
                                    // once its last band is deblocked) includes the
                                    // two rows above its first stripe, which lie in
                                    // band `k`: filtering them first would back up
                                    // CDEF output (sb128/sb256 roots span bands).
                                    let next_root_end = (((k + 1) >> sb128) + 1) << sb128;
                                    let ready = cdef_save_done[k].load(Acquire)
                                        && (k == 0 || cdef_save_done[k - 1].load(Acquire))
                                        && deblock_progress.load(Acquire)
                                            >= next_root_end.min(n_filter_bands);
                                    if !ready {
                                        break;
                                    }
                                    if cdef_filter_claim
                                        .compare_exchange_weak(k, k + 1, AcqRel, Relaxed)
                                        .is_err()
                                    {
                                        continue;
                                    }
                                    run_stage!(k, crate::decode::STAGE_CDEF_FILTER);
                                    cdef_band_done[k].store(true, Release);
                                    let d = cdef_filter_done.fetch_add(1, AcqRel) + 1;
                                    did_work = true;
                                    if d >= n_filter_bands {
                                        wake_all();
                                    }
                                }

                                // Stage D: LR
                                loop {
                                    let k = lr_claim.load(Acquire);
                                    if k >= n_filter_bands {
                                        break;
                                    }
                                    let root_first = (k >> sb128) << sb128;
                                    let ready =
                                        (root_first..=k).all(|j| cdef_band_done[j].load(Acquire));
                                    // Cross-tile-row CDEF line (findings issue #2): the
                                    // previous tile row's bottom CDEF rows are saved
                                    // during CDEF-FILTER of THIS tile row's first band
                                    // (= `root_first` for the first root of a tile row),
                                    // which the base readiness above already waits for
                                    // (`cdef_band_done[root_first]`). So no extra gate is
                                    // needed and the MT scheduler is unchanged.
                                    if !ready {
                                        break;
                                    }
                                    if lr_claim
                                        .compare_exchange_weak(k, k + 1, AcqRel, Relaxed)
                                        .is_err()
                                    {
                                        continue;
                                    }
                                    run_stage!(k, crate::decode::STAGE_LR);
                                    filter_progress.fetch_add(1, AcqRel);
                                    let done_now = flt_done.fetch_add(1, AcqRel) + 1;
                                    did_work = true;
                                    if done_now >= n_filter_bands {
                                        wake_all();
                                    }
                                }

                                if did_work {
                                    continue;
                                }

                                // (3) Nothing claimable now.
                                if flt_done.load(Relaxed) >= n_filter_bands {
                                    return;
                                }

                                let mut should_park = true;
                                for _ in 0..PARK_SPIN_ITERS {
                                    if got_err.load(Relaxed)
                                        || flt_done.load(Relaxed) >= n_filter_bands
                                    {
                                        return;
                                    }
                                    if progress_epoch.load(Acquire) != seen_epoch {
                                        should_park = false;
                                        break;
                                    }
                                    std::hint::spin_loop();
                                }
                                if should_park {
                                    for _ in 0..2 {
                                        std::thread::yield_now();
                                        if got_err.load(Relaxed)
                                            || flt_done.load(Relaxed) >= n_filter_bands
                                        {
                                            return;
                                        }
                                        if progress_epoch.load(Acquire) != seen_epoch {
                                            should_park = false;
                                            break;
                                        }
                                    }
                                }
                                if !should_park {
                                    continue;
                                }

                                let guard = park_mx.lock().unwrap_or_else(|e| e.into_inner());
                                park_waiters.fetch_add(1, Relaxed);
                                if got_err.load(Relaxed) || flt_done.load(Relaxed) >= n_filter_bands
                                {
                                    park_waiters.fetch_sub(1, Relaxed);
                                    return;
                                }
                                let more_decode = (0..n_tiles).any(|t| {
                                    tile_sbrow[t].load(Relaxed) < tile_nsb[t]
                                        && !tile_busy[t].load(Relaxed)
                                });
                                let dp = deblock_progress.load(Acquire);
                                let deblock_cols_av = {
                                    let c = deblock_cols_claim.load(Acquire);
                                    c < n_filter_bands && filter_ready(c)
                                };
                                let deblock_rows_av = !deblock_rows_busy.load(Relaxed)
                                    && dp < n_filter_bands
                                    && cols_done.get(dp).map_or(false, |b| b.load(Acquire));
                                let cdef_save_av = {
                                    let c = cdef_save_claim.load(Acquire);
                                    c < n_filter_bands && (c + 1 < dp || dp >= n_filter_bands)
                                };
                                let cdef_filter_av = {
                                    let c = cdef_filter_claim.load(Acquire);
                                    c < n_filter_bands
                                        && cdef_save_done[c].load(Acquire)
                                        && (c == 0 || cdef_save_done[c - 1].load(Acquire))
                                };
                                let lr_av = {
                                    let k = lr_claim.load(Acquire);
                                    k < n_filter_bands && {
                                        let rf = (k >> sb128) << sb128;
                                        (rf..=k).all(|j| cdef_band_done[j].load(Acquire))
                                    }
                                };
                                let ready_filter = deblock_cols_av
                                    || deblock_rows_av
                                    || cdef_save_av
                                    || cdef_filter_av
                                    || lr_av;
                                if more_decode || ready_filter {
                                    park_waiters.fetch_sub(1, Relaxed);
                                    drop(guard);
                                    continue;
                                }
                                let guard = park_cv.wait(guard).unwrap_or_else(|e| e.into_inner());
                                park_waiters.fetch_sub(1, Relaxed);
                                drop(guard);
                            }
                        });
                    });
                };
                crate::mtpool::dispatch(active_pool, n_workers, &worker);
                if got_err.load(std::sync::atomic::Ordering::Relaxed) {
                    return Err(());
                }
            } else {
                <$Coef as DecodeCoeff>::with_cf_scratch(|cf| {
                    WORKER_SCRATCH.with(|ws_cell| -> Result<(), ()> {
                        let mut ws_guard = ws_cell.borrow_mut();
                        let ws = ws_guard.get_or_insert_with(|| {
                            DecodeWorkerScratch::new(rf_rp_stride.max(1) as usize, bw, bh)
                        });
                        ws.trim_retained_capacity();
                        ws.prepare(rf_rp_stride.max(1) as usize, bw, bh)?;
                        let DecodeWorkerScratch {
                            rt,
                            recon_scratch,
                            part_w,
                            recon_edge8,
                            recon_edge16,
                            ..
                        } = &mut *ws;
                        let recon_edge =
                            <$Pixel as DecodeEdgePixel>::edge_mut(recon_edge8, recon_edge16);
                        let mut l = BlockContext::default();
                        let part_r: &[u8] = &[];

                        for tr in 0..rows {
                            let ts_base = (tr * cols) as usize;
                            // Every tile-col in a tile row has the same row range;
                            // derive it from tile-col zero and compute the tiny
                            // per-tile `SbFrameInfo` on demand. This removes the
                            // ST-only Vec<Vec<u8>>/Vec<Msac>/Vec<SbFrameInfo>
                            // setup and uses the same save/resume MSAC state that
                            // the worker path already uses.
                            let (row_rs, row_re) = {
                                let t = &ts[ts_base].tiling;
                                (t.row_start, t.row_end)
                            };

                            // PHASE A: decode every superblock-row across all tile-cols.
                            let mut by = row_rs;
                            while by < row_re {
                                // Project reference temporal MVs into the rolling-window `rf.rp_proj`.
                                // Run once per sbrow over the full block-row width, before any
                                // tile-col reads it, so the inter tmvp candidates and frame_mode=2
                                // whole-frame TIP recon see this row's projection.
                                if need_load_tmvs {
                                    let by_end = (by + sb_step) >> 1;
                                    refmvs::load_tmvs(
                                        rf,
                                        tr,
                                        0,
                                        bw >> 1,
                                        by >> 1,
                                        by_end,
                                        seq_hdr.mv_traj,
                                        frame_hdr.tip.frame_mode,
                                        seq_hdr.tip_hole_fill,
                                        frame_hdr.tmvp_sample_step as i32,
                                        frame_hdr.n_ref_frames as i32,
                                    );
                                }
                                let rf_ref: &refmvs::Frame = &*rf;
                                for tc in 0..cols as usize {
                                    let ts_idx = ts_base + tc;
                                    let (cs, ce, rs, re) = {
                                        let t = &ts[ts_idx].tiling;
                                        (t.col_start, t.col_end, t.row_start, t.row_end)
                                    };
                                    if by < rs || by >= re {
                                        continue;
                                    }
                                    let fi = SbFrameInfo::from_frame(SbFrameInfoArgs {
                                        seq_hdr,
                                        frame_hdr,
                                        bw,
                                        bh,
                                        root_bs,
                                        sb_step,
                                        n_passes,
                                        refdir,
                                        refdist,
                                        absrefdist,
                                        skip_mode_refs,
                                        tile_col_start: cs,
                                        tile_col_end: ce,
                                        tile_row_start: rs,
                                        tile_row_end: re,
                                        furthest_future_refidx: ffr_idx,
                                        tip: tip_ref,
                                    });
                                    let buf = std::mem::take(&mut ts[ts_idx].msac_buf);
                                    part_w.clear();
                                    reset_context(&mut l, keyframe, is_tip);
                                    let (sbrow_res, saved_msac_state) = {
                                        let mut msac = B::resume(&buf, ts[ts_idx].msac_state);
                                        let sbrow_res = decode_tile_sbrow_entropy(
                                            DecodeTileSbrowEntropyCtx {
                                                bd: bd_local,
                                                fi: &fi,
                                                frame_hdr,
                                                ts: &mut ts[ts_idx],
                                                msac: &mut msac,
                                                a_arr: &mut *a,
                                                lf_mask: &mut lf.mask,
                                                lr_mask: &mut lf.lr_mask,
                                                seam_right: &mut lf.seam_lpf.right,
                                                seam_bottom: &mut lf.seam_lpf.bottom,
                                                seam_h4: lf.seam_lpf.h4,
                                                seam_w4: lf.seam_lpf.w4,
                                                l: &mut l,
                                                dst_y: &mut *dst_y,
                                                dst_u: &mut *dst_u,
                                                dst_v: &mut *dst_v,
                                                cf: &mut *cf,
                                                recon_scratch: &mut *recon_scratch,
                                                recon_edge: &mut *recon_edge,
                                                recon_frame: &recon_frame,
                                                cur_segmap: &mut cur_segmap[..],
                                                prev_segmap: prev_segmap_ref,
                                                segmap_uv: std::sync::Arc::make_mut(&mut lf.segmap_uv)
                                                    .as_mut_slice(),
                                                segmap_uv_stride: lf.uv_segmap_stride,
                                                cur_ccsomap: &mut cur_ccsomap[..],
                                                prev_ccsomap: prev_ccsomap_ref,
                                                part_w: &mut *part_w,
                                                part_r,
                                                by,
                                                sb256w,
                                                pass: crate::internal::PASS_ALL,
                                                root_bs,
                                                c_root_bs,
                                                rt: &mut *rt,
                                                rf: rf_ref,
                                                cur_mvs: &mut cur_mvs[..],
                                                refp: &refp_pics,
                                                svc: &svc_v,
                                                seq_hdr,
                                                frm_hdr: frame_hdr,
                                                masks,
                                            },
                                        );
                                        let saved_msac_state = msac.save();
                                        (sbrow_res, saved_msac_state)
                                    };
                                    ts[ts_idx].msac_state = saved_msac_state;
                                    ts[ts_idx].msac_buf = buf;
                                    sbrow_res?;
                                }
                                by += sb_step;
                            }

                            // PHASE B: frame-level spec-order filter
                            if tr + 1 == rows {
                                let sb64h = (bh + 15) >> 4;
                                let nfb = sb64h;
                                let n_roots = ((sb64h >> sb128) + 2) as usize;
                                let mono = seq_hdr.layout == crate::headers::PixelLayout::I400;
                                ensure_filter_lines(
                                    &mut lf.cdef_line_store,
                                    &mut lf.cdef_top_store,
                                    &mut lf.lr_db_store,
                                    bh,
                                    filter_params.y_stride,
                                    filter_params.uv_stride,
                                    n_roots,
                                    mono,
                                )?;
                                crate::decode::lr_cdef_line_save::ensure_lr_cdef_line(
                                    &mut lf.lr_cdef_line,
                                    rows as usize,
                                    filter_params.y_stride,
                                    filter_params.uv_stride,
                                    mono,
                                )?;
                                if bd_local.bitdepth() > 8 {
                                    let y_s = crate::decode::loopfilter::hbd_sample_stride(
                                        filter_params.y_stride,
                                    );
                                    let uv_s = crate::decode::loopfilter::hbd_sample_stride(
                                        filter_params.uv_stride,
                                    );
                                    crate::decode::lr_cdef_line_save::ensure_lr_cdef_line_hbd(
                                        &mut lf.lr_cdef_line_hbd,
                                        rows as usize,
                                        y_s,
                                        uv_s,
                                        mono,
                                    )?;
                                }
                                if bd_local.bitdepth() > 8 {
                                    ensure_filter_lines_hbd(
                                        &mut lf.cdef_line_store_hbd,
                                        &mut lf.cdef_top_store_hbd,
                                        &mut lf.lr_db_store_hbd,
                                        bh,
                                        filter_params.y_stride,
                                        filter_params.uv_stride,
                                        n_roots,
                                        mono,
                                    )?;
                                }
                                for stage in [
                                    crate::decode::STAGE_DEBLOCK,
                                    crate::decode::STAGE_CDEF,
                                    crate::decode::STAGE_LR,
                                ] {
                                    for by64 in 0..nfb {
                                        let sh = FilterShared {
                                            mask: &lf.mask[..],
                                            lr_mask: &lf.lr_mask[..],
                                            segmap_uv: &lf.segmap_uv[..],
                                            start_of_tile_row: &lf.start_of_tile_row[..],
                                            seams: lf.seam_lpf.view(),
                                            uv_segmap_stride: lf.uv_segmap_stride,
                                            base_q: lf.base_q,
                                            gdf_ref_dst_idx: lf.gdf_ref_dst_idx,
                                            wiener_idx: lf.wiener_idx,
                                            ns_subclass_class_idx: lf.ns_subclass_class_idx,
                                            restore_planes: lf.restore_planes,
                                        };
                                        filter_sb64(
                                            bd_local,
                                            crate::decode::loopfilter::FilterSb64Ctx {
                                                exec,
                                                seq_hdr,
                                                frame_hdr,
                                                sh: &sh,
                                                fp: &filter_params,
                                                cur_segmap,
                                                b4_stride: b4_stride_v,
                                                hbd: hbd_v,
                                                inloop: fc_inloop_filters,
                                                sbh: fc_sbh,
                                                sb_step,
                                                sb256w,
                                                sb128,
                                                bw,
                                                bh,
                                            },
                                            crate::decode::loopfilter::FilterSb64Scratch {
                                                cdef_line: &mut lf.cdef_line_store,
                                                cdef_top: &mut lf.cdef_top_store,
                                                lr_db_line: &mut lf.lr_db_store,
                                                lr_cdef_line: &mut lf.lr_cdef_line,
                                                ccso_tmp_buf: &mut lf.ccso_tmp_buf,
                                                cdef_line_hbd: &mut lf.cdef_line_store_hbd,
                                                cdef_top_hbd: &mut lf.cdef_top_store_hbd,
                                                lr_db_line_hbd: &mut lf.lr_db_store_hbd,
                                                lr_cdef_line_hbd: &mut lf.lr_cdef_line_hbd,
                                                ccso_tmp_buf_hbd: &mut lf.ccso_tmp_buf_hbd,
                                            },
                                            crate::decode::loopfilter::FilterSb64Dst {
                                                y: &mut *dst_y,
                                                u: &mut *dst_u,
                                                v: &mut *dst_v,
                                            },
                                            crate::decode::loopfilter::FilterSb64Band {
                                                by64,
                                                stages: stage,
                                            },
                                        );
                                    }
                                }
                            }
                        }
                        Ok(())
                    })
                })?;
            }
        }};
    }

    if bitdepth_v > 8 {
        run_decode_tile_rows!(crate::pixel::BitDepth16::new(bitdepth_v as u8), u16, i32);
    } else {
        run_decode_tile_rows!(crate::pixel::BitDepth8, u8, i16);
    }

    // Restore the (now-populated) temporal MV grid into `rf.rp` so the
    // reference-list update can publish it to c.refs[i].refmvs.
    rf.rp = cur_mvs;

    Ok(())
}

/// Orchestrate a single-threaded frame decode: init -> CDF init -> main loop.
#[allow(clippy::too_many_arguments)]
pub fn decode_frame(
    fc: &mut crate::internal::FrameContext,
    n_tc: i32,
    n_passes: i32,
    in_cdf: Option<&crate::cdf::CdfContext>,
    qcat: usize,
    pool: Option<&crate::mtpool::ThreadPool>,
) -> Result<(), TealdustError> {
    let frame_hdr = fc.frame_hdr.clone();
    let seq_hdr = fc.seq_hdr.clone();

    decode_frame_init(
        &frame_hdr,
        &seq_hdr,
        &mut fc.lf,
        &mut fc.ts,
        &mut fc.n_ts,
        &mut fc.a,
        &mut fc.a_sz,
        &mut fc.dq,
        &mut fc.qm,
        &fc.absrefdist,
        fc.sbh,
        fc.sb256w,
        fc.sb256h,
        fc.bw,
        fc.bh,
        n_tc,
    )
    .map_err(|_| TealdustError::FrameSetupFailed)?;

    if frame_hdr.tip.frame_mode != 2 {
        let r = decode_frame_init_cdf(
            &mut fc.ts,
            &fc.tile,
            &frame_hdr,
            in_cdf,
            qcat,
            fc.sb_shift,
            fc.bw,
            fc.bh,
            n_tc,
            pool,
        );
        r.map_err(|_| TealdustError::CdfInitFailed)?;
    } else {
        decode_tip_frame_init(&mut fc.ts, &frame_hdr, fc.sb_shift, fc.bw, fc.bh, n_tc);
    }

    let r = decode_frame_main(fc, n_passes, n_tc, pool);
    r.map_err(|_| TealdustError::InvalidTileData)?;

    // path the update tile's adapted CDF (or, with avg_cdf_type, the average of
    // the tiles' CDFs) becomes `out_cdf` with its symbol counts reset. Only produced when CDF update
    // is enabled (otherwise refs keep `in_cdf`, handled by the ref-list update).
    if frame_hdr.tip.frame_mode != 2 && frame_hdr.disable_cdf_update == 0 {
        let n_tiles = frame_hdr.tiling.t.cols as usize * frame_hdr.tiling.t.rows as usize;
        let averaged = if seq_hdr.avg_cdf && seq_hdr.avg_cdf_type != 0 && n_tiles > 1 {
            // AVM averages the first `1 << log2` tiles (log2 = floor(log2(n)),
            // at most 3).
            let log2 = (usize::BITS - 1 - n_tiles.leading_zeros()).min(3);
            let used = 1usize << log2;
            (fc.ts.len() >= used).then(|| {
                crate::cdf::CdfContext::tile_average(fc.ts[..used].iter().map(|t| &t.cdf), log2)
            })
        } else {
            None
        };
        let upd = frame_hdr.tiling.update as usize;
        if let Some(mut out) = averaged.or_else(|| fc.ts.get(upd).map(|ts| ts.cdf.clone())) {
            out.reset_count(frame_hdr.is_key_or_intra());
            fc.out_cdf = Some(std::sync::Arc::new(out));
        }
    }

    Ok(())
}

/// Build a `FrameContext` from the decoder context's parsed headers and tile
/// data, then run to decode.
///
/// The context is moved out for the duration of the decode (so it borrows
/// independently of `c`, e.g. `c.pool`) and always moved back afterward — even on
/// error — so its scratch allocations survive to the next frame.
pub fn submit_frame(
    c: &mut crate::internal::DecoderContext,
    n_tc: i32,
) -> Result<(), TealdustError> {
    let mut fc = std::mem::take(&mut c.fc);
    let r = submit_frame_inner(c, &mut fc, n_tc);
    c.fc = fc;
    r
}

fn submit_frame_inner(
    c: &mut crate::internal::DecoderContext,
    fc: &mut crate::internal::FrameContext,
    n_tc: i32,
) -> Result<(), TealdustError> {
    use crate::headers::PixelLayout;

    let seq_hdr = c
        .seq_hdr
        .clone()
        .ok_or(TealdustError::MissingSequenceHeader)?;
    let frame_hdr = c
        .frame_hdr
        .clone()
        .ok_or(TealdustError::MissingFrameHeader)?;

    let sb128 = frame_hdr.sb128 as i32;
    let layout = seq_hdr.layout;
    fc.ss_ver = (layout == PixelLayout::I420) as i32;
    fc.ss_hor = matches!(layout, PixelLayout::I420 | PixelLayout::I422) as i32;
    fc.root_bs = match sb128 {
        0 => BlockSize::Bs64x64,
        1 => BlockSize::Bs128x128,
        _ => BlockSize::Bs256x256,
    };
    fc.bw = ((frame_hdr.width + 7) >> 3) << 1;
    fc.bh = ((frame_hdr.height + 7) >> 3) << 1;
    fc.sb256w = (fc.bw + 63) >> 6;
    fc.sb256h = (fc.bh + 63) >> 6;
    fc.sb_shift = 4 + sb128;
    fc.sb_step = 16 << sb128;
    fc.sbh = (fc.bh + fc.sb_step - 1) >> fc.sb_shift;
    fc.b4_stride = ((fc.bw + 63) & !63) as isize;
    let bpc = 8 + seq_hdr.hbd as i32 * 2;
    fc.bitdepth_max = (1 << bpc) - 1;
    // Intra neighbors have no reference direction; -1 sentinel (mirrors C
    // lib.c init) so compound/ref context lookups treat them correctly.
    fc.refdir_intra = -1;

    fc.tile = std::mem::take(&mut c.tile);
    fc.n_tile_data = c.n_tile_data;
    fc.inloop_filters = c.inloop_filters;

    // Allocate the output picture that reconstruction writes into, drawing from
    // the decoder's persistent pool allocator so a freed frame's planes are
    // recycled rather than re-allocated.
    let allocator = c.pic_allocator.clone();
    fc.cur_pic = crate::picture::Picture::alloc(
        frame_hdr.width,
        frame_hdr.height,
        layout,
        bpc,
        Some(seq_hdr.clone()),
        Some(frame_hdr.clone()),
        allocator,
    )
    .ok_or(TealdustError::OutOfMemory)?;

    // Attach display metadata that was parsed from metadata OBUs before this frame.
    fc.cur_pic.content_light_level = c.content_light;

    // Attach the frame's film-grain synthesis params to the picture so the output
    if frame_hdr.film_grain.present != 0 {
        fc.cur_pic.fgm = c.fgm[frame_hdr.film_grain.id as usize];
    }

    let qcat = crate::cdf::cdf_thread_init_static_qcat(frame_hdr.quant.yac as u32) as usize;

    let is_inter_or_switch = frame_hdr.is_inter_or_switch();
    let allow_intrabc = frame_hdr.allow_intrabc != 0;

    // Validate each signaled reference, share its picture into `fc.refp[i]`,
    // and compute the per-ref scaling / global-warp-allowed flags. Single-ref
    // bring-up: scaled references (svc != 0) are validated but the scaled-MC
    // path is a follow-up; an unequal-dimension ref triggers the deferral note.
    let mut ref_coded_width = [0i32; 7];
    if is_inter_or_switch {
        for i in 0..7 {
            let refidx = usize::try_from(frame_hdr.refidx[i])
                .ok()
                .filter(|&idx| idx < c.refs.len())
                .ok_or(TealdustError::InvalidReferenceFrame)?;
            let rp = &c.refs[refidx].p;
            let rpic = rp.pic.as_ref();
            let valid = rpic.is_some_and(|p| {
                let pw = p.p.w;
                let ph = p.p.h;
                frame_hdr.width * 2 >= pw
                    && frame_hdr.height * 2 >= ph
                    && frame_hdr.width <= pw * 16
                    && frame_hdr.height <= ph * 16
                    && seq_hdr.layout == p.p.layout
                    && bpc == p.p.bpc
            });
            if !valid {
                return Err(TealdustError::InvalidReferenceFrame);
            }
            let p = rpic.unwrap();
            fc.refp[i].pic = Some(p.clone());
            fc.refp[i].frame_hdr = rp.frame_hdr.clone();
            ref_coded_width[i] = p.frame_hdr.as_ref().map(|h| h.width).unwrap_or(p.p.w);
            if frame_hdr.width != p.p.w || frame_hdr.height != p.p.h {
                let scale_fac = |ref_sz: i32, this_sz: i32| -> i32 {
                    (((ref_sz << 14) + (this_sz >> 1)) / this_sz) as i32
                };
                fc.svc[i][0].scale = scale_fac(p.p.w, frame_hdr.width);
                fc.svc[i][1].scale = scale_fac(p.p.h, frame_hdr.height);
                fc.svc[i][0].step = (fc.svc[i][0].scale + 8) >> 4;
                fc.svc[i][1].step = (fc.svc[i][1].scale + 8) >> 4;
            } else {
                fc.svc[i][0].scale = 0;
                fc.svc[i][1].scale = 0;
            }
            let mut gm = frame_hdr.gmv.m[i];
            fc.gmv_warp_allowed[i] = (gm.wm_type > crate::headers::WarpedMotionType::Translation
                && frame_hdr.force_integer_mv == 0
                && crate::warpmv::get_shear_params(&mut gm) == 0
                && fc.svc[i][0].scale == 0) as u8;
        }
    }

    // primary_ref_frame == NONE -> static qcat init (keyframe path). Otherwise
    // clone the saved CDF of the primary ref. The avg primary/secondary CDF
    // path (use_pri_sec_cdf) is deferred (not exercised by the bring-up clips).
    let p_ref_idx = frame_hdr.primary_ref_frame;
    let in_cdf: Option<crate::cdf::CdfContext> = if p_ref_idx == crate::headers::PRIMARY_REF_NONE {
        fc.use_pri_sec_cdf = 0;
        None
    } else {
        // entropy context is the weighted average of the primary and secondary
        // reference CDFs: in_cdf = (pri*7 + sec*1 + 4) >> 3 (cdf.c:6650).
        let s_ref_idx = frame_hdr.secondary_ref_frame;
        let use_pri_sec = s_ref_idx != crate::headers::PRIMARY_REF_NONE
            && frame_hdr.frame_type == crate::headers::FrameType::Inter
            && seq_hdr.avg_cdf
            && seq_hdr.avg_cdf_type == 0
            && frame_hdr.tip.frame_mode != 2;
        fc.use_pri_sec_cdf = use_pri_sec as i32;
        let pri_ref = frame_hdr
            .refidx
            .get(p_ref_idx as usize)
            .copied()
            .and_then(|idx| usize::try_from(idx).ok())
            .filter(|&idx| idx < c.refs.len())
            .ok_or(TealdustError::InvalidReferenceFrame)?;
        if use_pri_sec {
            let sec_ref = frame_hdr
                .refidx
                .get(s_ref_idx as usize)
                .copied()
                .and_then(|idx| usize::try_from(idx).ok())
                .filter(|&idx| idx < c.refs.len())
                .ok_or(TealdustError::InvalidReferenceFrame)?;
            let default_cdf = crate::cdf::CdfContext::init_from_defaults(qcat);
            let src1 = c.refs[pri_ref].cdf.as_deref().unwrap_or(&default_cdf);
            let src2 = c.refs[sec_ref].cdf.as_deref().unwrap_or(&default_cdf);
            let mut out = crate::cdf::CdfContext::init_from_defaults(qcat);
            out.pri_sec_average(
                &src1.m, &src1.coef, &src1.mv, &src1.dmv, &src2.m, &src2.coef, &src2.mv, &src2.dmv,
            );
            Some(out)
        } else {
            c.refs[pri_ref].cdf.as_ref().map(|a| (**a).clone())
        }
    };

    fc.seq_hdr = seq_hdr.clone();
    fc.frame_hdr = frame_hdr.clone();
    fc.exec = c.exec.clone();
    fc.in_cdf = in_cdf;

    let use_rfm = is_inter_or_switch || allow_intrabc;
    if use_rfm {
        if is_inter_or_switch {
            let poc = frame_hdr.frame_offset as i32;
            let nbits = seq_hdr.order_hint_n_bits as i32;
            let mut furthest_future_refidx: i32 = -2;
            for i in 0..7 {
                let rpoc = fc.refp[i]
                    .frame_hdr
                    .as_ref()
                    .map(|h| h.frame_offset as i32)
                    .unwrap_or(0);
                fc.refpoc[i] = rpoc as u8;
                let delta = crate::env::get_poc_diff(nbits, rpoc, poc);
                fc.refdist[i] = delta as i8;
                fc.absrefdist[i] = delta.unsigned_abs() as u8;
                fc.refdir[i] = (delta > 0) as u8;
                if delta > 0
                    && (furthest_future_refidx < 0
                        || (fc.refdist[furthest_future_refidx as usize] as i32) < delta)
                {
                    furthest_future_refidx = i as i32;
                }
            }
            fc.furthest_future_refidx = furthest_future_refidx as i8;
            // refdir[TIP_FRAME] is a fixed sentinel: TIP references are always
            // treated as a future-direction ref for context derivation
            // ref-context (get_comp_ctx / single-ref) reads refdir[ref] for a
            // TIP neighbour (ref == TIP_FRAME), so this slot must be 1.
            fc.refdir[TIP_FRAME as usize] = 1;
        } else {
            fc.refpoc = [0; 7];
        }
        if frame_hdr.use_ref_frame_mvs != 0 {
            let bw = ((frame_hdr.width + 7) >> 3) << 1;
            let bh = ((frame_hdr.height + 7) >> 3) << 1;
            for i in 0..7 {
                let refidx = usize::try_from(frame_hdr.refidx[i])
                    .ok()
                    .filter(|&idx| idx < c.refs.len())
                    .ok_or(TealdustError::InvalidReferenceFrame)?;
                let ref_w = ((ref_coded_width[i] + 7) >> 3) << 1;
                let ref_h = ((fc.refp[i].pic.as_ref().map(|p| p.p.h).unwrap_or(0) + 7) >> 3) << 1;
                if c.refs[refidx].refmvs.is_some() && ref_w == bw && ref_h == bh {
                    fc.ref_mvs[i] = c.refs[refidx].refmvs.clone();
                } else {
                    fc.ref_mvs[i] = None;
                }
                fc.refrefpoc[i] = c.refs[refidx].refpoc;
                fc.refcnt[i] = fc.refp[i]
                    .frame_hdr
                    .as_ref()
                    .map(|h| h.n_ref_frames)
                    .unwrap_or(0);
            }
        }
    }

    if frame_hdr.segmentation.enabled != 0
        && (frame_hdr.segmentation.temporal != 0 || frame_hdr.segmentation.update_map == 0)
    {
        let pri = frame_hdr.primary_ref_frame as usize;
        if pri >= ref_coded_width.len() {
            return Err(TealdustError::InvalidReferenceFrame);
        }
        let ref_w = ((ref_coded_width[pri] + 7) >> 3) << 1;
        let ref_h = ((fc.refp[pri].pic.as_ref().map(|p| p.p.h).unwrap_or(0) + 7) >> 3) << 1;
        let bw = ((frame_hdr.width + 7) >> 3) << 1;
        let bh = ((frame_hdr.height + 7) >> 3) << 1;
        if ref_w == bw && ref_h == bh {
            let refidx = usize::try_from(frame_hdr.refidx[pri])
                .ok()
                .filter(|&idx| idx < c.refs.len())
                .ok_or(TealdustError::InvalidReferenceFrame)?;
            fc.prev_segmap = c.refs[refidx].segmap.clone();
        }
    }

    fc.prev_ccsomap = [None, None, None];
    if frame_hdr.ccso.enabled != 0 && is_inter_or_switch {
        for p in 0..3 {
            let cp = &frame_hdr.ccso.p[p];
            if cp.enabled != 0 && cp.sb_reuse != 0 {
                let refidx = frame_hdr
                    .refidx
                    .get(cp.refidx as usize)
                    .copied()
                    .and_then(|idx| usize::try_from(idx).ok())
                    .filter(|&idx| idx < c.refs.len())
                    .ok_or(TealdustError::InvalidReferenceFrame)?;
                fc.prev_ccsomap[p] = c.refs[refidx].ccsomap.clone();
            }
        }
    }

    let skip_mode_r1 = (frame_hdr.skip_mode_enabled != 0
        && frame_hdr.n_ref_frames > 1
        && (fc.absrefdist[0] as i32 - fc.absrefdist[1] as i32).abs() <= 1)
        as i8;
    fc.skip_mode_refs = RefPair {
        r: [0, skip_mode_r1],
    };

    let in_cdf_ref = fc.in_cdf.take();
    // The decoder's worker pool is created in `Decoder::open()`, sized as
    // `n_tc - 1` helper threads because the caller participates in each dispatch.
    // Keep this fallback for contexts constructed directly in tests.
    if n_tc >= 2 && c.pool.is_none() {
        c.pool = Some(crate::mtpool::ThreadPool::new((n_tc - 1) as usize));
    }
    decode_frame(
        &mut *fc,
        n_tc,
        1,
        in_cdf_ref.as_ref(),
        qcat,
        c.pool.as_ref(),
    )?;

    // on failure. Single-thread decode here is synchronous and already succeeded,
    // so we publish after success (equivalent for n_fc == 1). The decoded picture
    // is shared into every refreshed slot so later frames can reference it.
    let cur_pic = std::mem::take(&mut fc.cur_pic);
    let shared = std::sync::Arc::new(cur_pic);
    let out_cdf_for_refs: Option<std::sync::Arc<crate::cdf::CdfContext>> =
        if frame_hdr.disable_cdf_update == 0 {
            fc.out_cdf.clone()
        } else {
            in_cdf_ref.map(std::sync::Arc::new)
        };
    let cur_segmap_arc: Option<Vec<u8>> = if !fc.cur_segmap.is_empty() {
        Some(try_clone_vec(&fc.cur_segmap).map_err(|_| TealdustError::OutOfMemory)?)
    } else {
        None
    };
    let cur_ccsomap_arc: Option<Vec<u8>> = if !fc.cur_ccsomap.is_empty() {
        Some(try_clone_vec(&fc.cur_ccsomap).map_err(|_| TealdustError::OutOfMemory)?)
    } else {
        None
    };
    let cur_tp = crate::internal::ThreadPicture {
        showable: frame_hdr.show_immediate == 0,
        frame_hdr: Some(frame_hdr.clone()),
        pic: Some(shared.clone()),
        disp_order: crate::output_order::disp_order_hint(
            c,
            frame_hdr.frame_offset as u32,
            seq_hdr.order_hint_n_bits as u32,
            frame_hdr.closed_loop_key != 0,
        ),
        out_done: Some(std::sync::Arc::new(std::sync::atomic::AtomicBool::new(
            false,
        ))),
    };
    let refresh = frame_hdr.refresh_frame_flags;
    for i in 0..8 {
        if refresh & (1 << i) != 0 {
            crate::output_order::output_before_overwrite(c, i);
            c.refs[i].p = cur_tp.clone();
            c.refs[i].cdf = out_cdf_for_refs.clone();
            c.refs[i].segmap = if frame_hdr.segmentation.update_map != 0 {
                cur_segmap_arc.clone()
            } else {
                fc.prev_segmap.clone()
            };
            if is_inter_or_switch {
                c.refs[i].refmvs = if fc.rf.rp.is_empty() {
                    None
                } else {
                    Some(try_clone_vec(&fc.rf.rp).map_err(|_| TealdustError::OutOfMemory)?)
                };
            }
            c.refs[i].ccsomap = cur_ccsomap_arc.clone();
            c.refs[i].refpoc = fc.refpoc;
        }
    }

    // Output follows AVM: a frame shown immediately is output now (with the
    // waiting implicitly shown frames around it in display order); others
    // wait in their reference slots. Outputs share the slots' plane buffers by
    // reference count; film grain is applied to a fresh copy at output time.
    if frame_hdr.show_immediate != 0 {
        crate::output_order::output_frame_buffers(c, &cur_tp);
    }
    Ok(())
}

/// One color plane's copy descriptor. `src` is a shared read of the source
/// plane; `dst` launders the destination plane's `&mut` into a raw `(ptr, len)`
/// so the disjoint row bands can be written from several threads at once.
struct PlaneCopy<'a> {
    src: &'a [u8],
    dst: DisjointMut<u8>,
    row_bytes: usize,
    s_stride: usize,
    d_stride: usize,
    ph: usize,
}

/// Deep-copies `src` into a freshly allocated, independently owned picture,
/// parallelising the plane copy across the decoder's worker pool.
///
/// Each participating thread (the caller plus `pool` helpers) claims an id and
/// copies a contiguous, disjoint band of rows from every plane, so the result is
/// byte-identical regardless of thread count. With no pool — or `n_threads <= 1`,
/// or fewer rows than threads — it runs the sequential copy on the caller with no
/// thread hand-off at all. The thread count is clamped to the pool's real
/// capacity so every row is covered exactly once.
pub(crate) fn clone_picture_mt(
    src: &crate::picture::Picture,
    n_threads: u32,
    pool: Option<&crate::mtpool::ThreadPool>,
    allocator: std::sync::Arc<dyn crate::picture::PicAllocator>,
) -> crate::picture::Picture {
    let mut dst = match crate::picture::Picture::alloc(
        src.p.w,
        src.p.h,
        src.p.layout,
        src.p.bpc,
        src.seq_hdr.clone(),
        src.frame_hdr.clone(),
        allocator,
    ) {
        Some(p) => p,
        None => return crate::picture::Picture::new(),
    };
    dst.fgm = src.fgm;
    dst.content_light_level = src.content_light_level;

    let n_planes = if src.p.layout == crate::headers::PixelLayout::I400 {
        1
    } else {
        3
    };
    let bytes = src.bytes_per_sample();

    // Gather per-plane descriptors. `DisjointMut::new` captures only a raw
    // pointer, so taking the three `&mut` plane slices in turn does not hold
    // overlapping borrows of `dst`.
    let mut planes: Vec<PlaneCopy> = Vec::with_capacity(n_planes);
    for pl in 0..n_planes {
        let row_bytes = src.plane_w(pl) * bytes;
        let s_stride = src.stride_bytes(pl);
        let d_stride = dst.stride_bytes(pl);
        let ph = src.plane_h(pl);
        let Some(src_plane) = src.plane_bytes(pl) else {
            continue;
        };
        let Some(dst_plane) = dst.plane_bytes_mut(pl) else {
            continue;
        };
        planes.push(PlaneCopy {
            src: src_plane,
            dst: DisjointMut::new(dst_plane),
            row_bytes,
            s_stride,
            d_stride,
            ph,
        });
    }

    // Only engage the pool when one is present and there is real width to
    // exploit; otherwise n_run == 1 runs everything on the caller, no spawn.
    let want = (n_threads as usize).max(1);
    let active = pool.filter(|_| want >= 2);
    let cap = match active {
        Some(p) => p.workers() + 1,
        None => 1,
    };
    let n_run = want.min(cap).max(1);

    let seq = std::sync::atomic::AtomicUsize::new(0);
    let copy_job = || {
        // One id per participant (exactly `n_run` participants run), so the
        // bands below partition each plane's rows with no gaps or overlap.
        let id = seq
            .fetch_add(1, std::sync::atomic::Ordering::Relaxed)
            .min(n_run - 1);
        for p in &planes {
            let r0 = p.ph * id / n_run;
            let r1 = p.ph * (id + 1) / n_run;
            // SAFETY: every participant writes a disjoint band of rows.
            let dst = unsafe { p.dst.whole() };
            for y in r0..r1 {
                let s0 = y * p.s_stride;
                let d0 = y * p.d_stride;
                dst[d0..d0 + p.row_bytes].copy_from_slice(&p.src[s0..s0 + p.row_bytes]);
            }
        }
    };
    crate::mtpool::dispatch(active, n_run, &copy_job);
    dst
}

pub(crate) fn picture_has_grain(pic: &crate::picture::Picture) -> bool {
    match pic.fgm {
        Some(fgd) => {
            fgd.num_points[0] != 0
                || fgd.num_points[1] != 0
                || fgd.num_points[2] != 0
                || (fgd.clip_to_restricted_range && fgd.chroma_scaling_from_luma)
        }
        None => false,
    }
}

pub(crate) fn apply_grain_to_picture_mt(
    src: &crate::picture::Picture,
    n_threads: u32,
    pool: Option<&crate::mtpool::ThreadPool>,
    allocator: std::sync::Arc<dyn crate::picture::PicAllocator>,
) -> crate::picture::Picture {
    let fgd = match src.fgm {
        Some(f) => f,
        None => return clone_picture_mt(src, n_threads, pool, allocator.clone()),
    };
    let mut dst = clone_picture_mt(src, n_threads, pool, allocator.clone());
    let seed = src
        .frame_hdr
        .as_ref()
        .map(|h| h.film_grain.seed)
        .unwrap_or(0);

    let ss_ver = src.p.layout == crate::headers::PixelLayout::I420;
    let ss_hor = matches!(
        src.p.layout,
        crate::headers::PixelLayout::I420 | crate::headers::PixelLayout::I422
    );
    let has_chroma = src.p.layout != crate::headers::PixelLayout::I400;

    let aligned_h = (src.p.h as usize + 127) & !127;
    let uv_rows = aligned_h >> ss_ver as usize;

    if src.p.bpc == 8 {
        let y_stride = src.stride[0];
        let uv_stride = src.stride[1];
        let src_y = src.plane_bytes_rows(0, aligned_h).unwrap_or(&[]);
        let (src_u, src_v): (&[u8], &[u8]) = if has_chroma {
            (
                src.plane_bytes_rows(1, uv_rows).unwrap_or(&[]),
                src.plane_bytes_rows(2, uv_rows).unwrap_or(&[]),
            )
        } else {
            (&[], &[])
        };
        let (dst_y, dst_u, dst_v) = dst.plane_bytes_rows3_mut(aligned_h, uv_rows, has_chroma);

        crate::filmgrain::apply_grain_8bpc_mt(
            dst_y,
            dst_u,
            dst_v,
            src_y,
            src_u,
            src_v,
            y_stride,
            uv_stride,
            &fgd,
            src.p.w as usize,
            src.p.h as usize,
            seed,
            ss_hor,
            ss_ver,
            n_threads,
            pool,
        );
    } else {
        debug_assert!(src.p.bpc > 8);
        let y_stride = src.stride[0].unsigned_abs() / core::mem::size_of::<u16>();
        let uv_stride = src.stride[1].unsigned_abs() / core::mem::size_of::<u16>();
        let src_y = src.plane_slice::<u16>(0).unwrap_or(&[]);
        let (src_u, src_v): (&[u16], &[u16]) = if has_chroma {
            (
                src.plane_slice::<u16>(1).unwrap_or(&[]),
                src.plane_slice::<u16>(2).unwrap_or(&[]),
            )
        } else {
            (&[], &[])
        };
        let (dst_y, dst_u, dst_v) =
            dst.plane_slices_rows3_mut::<u16>(aligned_h, uv_rows, has_chroma);

        crate::filmgrain::apply_grain_hbd_mt(
            dst_y,
            dst_u,
            dst_v,
            src_y,
            src_u,
            src_v,
            y_stride,
            uv_stride,
            &fgd,
            src.p.w as usize,
            src.p.h as usize,
            seed,
            ss_hor,
            ss_ver,
            src.p.bpc as usize,
            n_threads,
            pool,
        );
    }

    dst
}

fn get_snglref_ctx(
    a: &BlockContext,
    l: &BlockContext,
    yb4: usize,
    xb4: usize,
    have_top: bool,
    have_left: bool,
    have_top_right: bool,
    have_bottom_left: bool,
    b_dim: &[u8],
    ref_idx: i8,
) -> usize {
    const NEWMV0_MASK: u32 =
        (1 << 15) | (1 << 20) | (1 << 22) | (1 << 23) | (1 << 26) | (1 << 27) | (1 << 28);
    const NEWMV1_MASK: u32 = (1 << 19) | (1 << 22) | (1 << 25) | (1 << 27);

    let mut row = 0i32;
    let mut col = 0i32;
    let mut newmv = 0i32;

    macro_rules! add_matching {
        ($ctx:expr, $cnt:ident, $idx:expr) => {
            if $ctx.reference[0][$idx] as i8 == ref_idx {
                $cnt += 1;
                newmv += (((1u32 << $ctx.mode[$idx]) & NEWMV0_MASK) != 0) as i32;
            } else if $ctx.reference[1][$idx] as i8 == ref_idx {
                $cnt += 1;
                newmv += (((1u32 << $ctx.mode[$idx]) & NEWMV1_MASK) != 0) as i32;
            }
        };
    }
    if have_top {
        add_matching!(a, col, xb4);
        if have_top_right {
            add_matching!(a, col, xb4 + b_dim[0] as usize - 1);
        }
    }
    if have_left {
        add_matching!(l, row, yb4);
        if have_bottom_left {
            add_matching!(l, row, yb4 + b_dim[1] as usize - 1);
        }
    }

    ((row != 0) as usize) + ((col != 0) as usize) + 2 * ((newmv != 0) as usize)
}

#[cfg(test)]
mod parallel_filter_schedule_tests {
    use super::parallel_tiles_complete;
    use std::sync::atomic::AtomicUsize;

    #[test]
    fn filter_phase_waits_for_every_tile_row() {
        let progress = [AtomicUsize::new(3), AtomicUsize::new(1)];
        let totals = [3, 2];
        assert!(!parallel_tiles_complete(&progress, &totals));

        progress[1].store(2, std::sync::atomic::Ordering::Release);
        assert!(parallel_tiles_complete(&progress, &totals));
    }
}