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
/********************************************************************
 *                                                                  *
 * THIS FILE IS PART OF THE OggTheora SOFTWARE CODEC SOURCE CODE.   *
 * USE, DISTRIBUTION AND REPRODUCTION OF THIS LIBRARY SOURCE IS     *
 * GOVERNED BY A BSD-STYLE SOURCE LICENSE INCLUDED WITH THIS SOURCE *
 * IN 'COPYING'. PLEASE READ THESE TERMS BEFORE DISTRIBUTING.       *
 *                                                                  *
 * THE Theora SOURCE CODE IS COPYRIGHT (C) 2002-2009                *
 * by the Xiph.Org Foundation http://www.xiph.org/                  *
 *                                                                  *
 ********************************************************************

  function: mode selection code
  last mod: $Id$

 ********************************************************************/
#include <limits.h>
#include <string.h>
#include "encint.h"
#include "modedec.h"



typedef struct oc_fr_state           oc_fr_state;
typedef struct oc_qii_state          oc_qii_state;
typedef struct oc_enc_pipeline_state oc_enc_pipeline_state;
typedef struct oc_rd_metric          oc_rd_metric;
typedef struct oc_mode_choice        oc_mode_choice;



/*There are 8 possible schemes used to encode macro block modes.
  Schemes 0-6 use a maximally-skewed Huffman code to code each of the modes.
  The same set of Huffman codes is used for each of these 7 schemes, but the
   mode assigned to each codeword varies.
  Scheme 0 writes a custom mapping from codeword to MB mode to the bitstream,
   while schemes 1-6 have a fixed mapping.
  Scheme 7 just encodes each mode directly in 3 bits.*/

/*The mode orderings for the various mode coding schemes.
  Scheme 0 uses a custom alphabet, which is not stored in this table.
  This is the inverse of the equivalent table OC_MODE_ALPHABETS in the
   decoder.*/
static const unsigned char OC_MODE_RANKS[7][OC_NMODES]={
  /*Last MV dominates.*/ 
  /*L P M N I G GM 4*/
  {3,4,2,0,1,5,6,7},
  /*L P N M I G GM 4*/
  {2,4,3,0,1,5,6,7},
  /*L M P N I G GM 4*/
  {3,4,1,0,2,5,6,7},
  /*L M N P I G GM 4*/
  {2,4,1,0,3,5,6,7},
  /*No MV dominates.*/
  /*N L P M I G GM 4*/
  {0,4,3,1,2,5,6,7},
  /*N G L P M I GM 4*/
  {0,5,4,2,3,1,6,7},
  /*Default ordering.*/
  /*N I M L P G GM 4*/
  {0,1,2,3,4,5,6,7}
};



/*Initialize the mode scheme chooser.
  This need only be called once per encoder.*/
void oc_mode_scheme_chooser_init(oc_mode_scheme_chooser *_chooser){
  int si;
  _chooser->mode_ranks[0]=_chooser->scheme0_ranks;
  for(si=1;si<8;si++)_chooser->mode_ranks[si]=OC_MODE_RANKS[si-1];
}

/*Reset the mode scheme chooser.
  This needs to be called once for each frame, including the first.*/
static void oc_mode_scheme_chooser_reset(oc_mode_scheme_chooser *_chooser){
  int si;
  memset(_chooser->mode_counts,0,OC_NMODES*sizeof(*_chooser->mode_counts));
  /*Scheme 0 starts with 24 bits to store the mode list in.*/
  _chooser->scheme_bits[0]=24;
  memset(_chooser->scheme_bits+1,0,7*sizeof(*_chooser->scheme_bits));
  for(si=0;si<8;si++){
    /*Scheme 7 should always start first, and scheme 0 should always start
       last.*/
    _chooser->scheme_list[si]=7-si;
    _chooser->scheme0_list[si]=_chooser->scheme0_ranks[si]=si;
  }
}


/*This is the real purpose of this data structure: not actually selecting a
   mode scheme, but estimating the cost of coding a given mode given all the
   modes selected so far.
  This is done via opportunity cost: the cost is defined as the number of bits
   required to encode all the modes selected so far including the current one
   using the best possible scheme, minus the number of bits required to encode
   all the modes selected so far not including the current one using the best
   possible scheme.
  The computational expense of doing this probably makes it overkill.
  Just be happy we take a greedy approach instead of trying to solve the
   global mode-selection problem (which is NP-hard).
  _mb_mode: The mode to determine the cost of.
  Return: The number of bits required to code this mode.*/
static int oc_mode_scheme_chooser_cost(oc_mode_scheme_chooser *_chooser,
 int _mb_mode){
  int scheme0;
  int scheme1;
  int best_bits;
  int mode_bits;
  int si;
  int scheme_bits;
  scheme0=_chooser->scheme_list[0];
  scheme1=_chooser->scheme_list[1];
  best_bits=_chooser->scheme_bits[scheme0];
  mode_bits=OC_MODE_BITS[scheme0+1>>3][_chooser->mode_ranks[scheme0][_mb_mode]];
  /*Typical case: If the difference between the best scheme and the next best
     is greater than 6 bits, then adding just one mode cannot change which
     scheme we use.*/
  if(_chooser->scheme_bits[scheme1]-best_bits>6)return mode_bits;
  /*Otherwise, check to see if adding this mode selects a different scheme as
     the best.*/
  si=1;
  best_bits+=mode_bits;
  do{
    /*For any scheme except 0, we can just use the bit cost of the mode's rank
       in that scheme.*/
    if(scheme1!=0){
      scheme_bits=_chooser->scheme_bits[scheme1]+
       OC_MODE_BITS[scheme1+1>>3][_chooser->mode_ranks[scheme1][_mb_mode]];
    }
    else{
      int ri;
      /*For scheme 0, incrementing the mode count could potentially change the
         mode's rank.
        Find the index where the mode would be moved to in the optimal list,
         and use its bit cost instead of the one for the mode's current
         position in the list.*/
      /*We don't recompute scheme bits; this is computing opportunity cost, not
         an update.*/
      for(ri=_chooser->scheme0_ranks[_mb_mode];ri>0&&
       _chooser->mode_counts[_mb_mode]>=
       _chooser->mode_counts[_chooser->scheme0_list[ri-1]];ri--);
      scheme_bits=_chooser->scheme_bits[0]+OC_MODE_BITS[0][ri];
    }
    if(scheme_bits<best_bits)best_bits=scheme_bits;
    if(++si>=8)break;
    scheme1=_chooser->scheme_list[si];
  }
  while(_chooser->scheme_bits[scheme1]-_chooser->scheme_bits[scheme0]<=6);
  return best_bits-_chooser->scheme_bits[scheme0];
}

/*Incrementally update the mode counts and per-scheme bit counts and re-order
   the scheme lists once a mode has been selected.
  _mb_mode: The mode that was chosen.*/
static void oc_mode_scheme_chooser_update(oc_mode_scheme_chooser *_chooser,
 int _mb_mode){
  int ri;
  int si;
  _chooser->mode_counts[_mb_mode]++;
  /*Re-order the scheme0 mode list if necessary.*/
  for(ri=_chooser->scheme0_ranks[_mb_mode];ri>0;ri--){
    int pmode;
    pmode=_chooser->scheme0_list[ri-1];
    if(_chooser->mode_counts[pmode]>=_chooser->mode_counts[_mb_mode])break;
    /*Reorder the mode ranking.*/
    _chooser->scheme0_ranks[pmode]++;
    _chooser->scheme0_list[ri]=pmode;
  }
  _chooser->scheme0_ranks[_mb_mode]=ri;
  _chooser->scheme0_list[ri]=_mb_mode;
  /*Now add the bit cost for the mode to each scheme.*/
  for(si=0;si<8;si++){
    _chooser->scheme_bits[si]+=
     OC_MODE_BITS[si+1>>3][_chooser->mode_ranks[si][_mb_mode]];
  }
  /*Finally, re-order the list of schemes.*/
  for(si=1;si<8;si++){
    int sj;
    int scheme0;
    int bits0;
    sj=si;
    scheme0=_chooser->scheme_list[si];
    bits0=_chooser->scheme_bits[scheme0];
    do{
      int scheme1;
      scheme1=_chooser->scheme_list[sj-1];
      if(bits0>=_chooser->scheme_bits[scheme1])break;
      _chooser->scheme_list[sj]=scheme1;
    }
    while(--sj>0);
    _chooser->scheme_list[sj]=scheme0;
  }
}



/*The number of bits required to encode a super block run.
  _run_count: The desired run count; must be positive and less than 4130.*/
static int oc_sb_run_bits(int _run_count){
  int i;
  for(i=0;_run_count>=OC_SB_RUN_VAL_MIN[i+1];i++);
  return OC_SB_RUN_CODE_NBITS[i];
}

/*The number of bits required to encode a block run.
  _run_count: The desired run count; must be positive and less than 30.*/
static int oc_block_run_bits(int _run_count){
  return OC_BLOCK_RUN_CODE_NBITS[_run_count-1];
}



/*State to track coded block flags and their bit cost.*/
struct oc_fr_state{
  ptrdiff_t  bits;
  unsigned   sb_partial_count:16;
  unsigned   sb_full_count:16;
  unsigned   b_coded_count_prev:8;
  unsigned   b_coded_count:8;
  unsigned   b_count:8;
  signed int sb_partial:2;
  signed int sb_full:2;
  signed int b_coded_prev:2;
  signed int b_coded:2;
};



static void oc_fr_state_init(oc_fr_state *_fr){
  _fr->bits=0;
  _fr->sb_partial_count=0;
  _fr->sb_full_count=0;
  _fr->b_coded_count_prev=0;
  _fr->b_coded_count=0;
  _fr->b_count=0;
  _fr->sb_partial=-1;
  _fr->sb_full=-1;
  _fr->b_coded_prev=-1;
  _fr->b_coded=-1;
}


static void oc_fr_state_advance_sb(oc_fr_state *_fr,
 int _sb_partial,int _sb_full){
  ptrdiff_t bits;
  int       sb_partial_count;
  int       sb_full_count;
  bits=_fr->bits;
  /*Extend the sb_partial run, or start a new one.*/
  sb_partial_count=_fr->sb_partial;
  if(_fr->sb_partial==_sb_partial){
    if(sb_partial_count>=4129){
      bits++;
      sb_partial_count=0;
    }
    else bits-=oc_sb_run_bits(sb_partial_count);
  }
  else sb_partial_count=0;
  sb_partial_count++;
  bits+=oc_sb_run_bits(sb_partial_count);
  if(!_sb_partial){
    /*Extend the sb_full run, or start a new one.*/
    sb_full_count=_fr->sb_full_count;
    if(_fr->sb_full==_sb_full){
      if(sb_full_count>=4129){
        bits++;
        sb_full_count=0;
      }
      else bits-=oc_sb_run_bits(sb_full_count);
    }
    else sb_full_count=0;
    sb_full_count++;
    bits+=oc_sb_run_bits(sb_full_count);
    _fr->sb_full=_sb_full;
    _fr->sb_full_count=sb_full_count;
  }
  _fr->bits=bits;
  _fr->sb_partial=_sb_partial;
  _fr->sb_partial_count=sb_partial_count;
}

/*Flush any outstanding block flags for a SB (e.g., one with fewer than 16
   blocks).*/
static void oc_fr_state_flush_sb(oc_fr_state *_fr){
  ptrdiff_t bits;
  int       sb_partial;
  int       sb_full=sb_full;<--- Redundant assignment of 'sb_full' to itself.<--- Uninitialized variable: sb_full
  int       b_coded_count;
  int       b_coded;
  int       b_count;
  b_count=_fr->b_count;
  if(b_count>0){
    bits=_fr->bits;
    b_coded=_fr->b_coded;
    b_coded_count=_fr->b_coded_count;
    if(b_coded_count>=b_count){
      /*This SB was fully coded/uncoded; roll back the partial block flags.*/
      bits-=oc_block_run_bits(b_coded_count);
      if(b_coded_count>b_count)bits+=oc_block_run_bits(b_coded_count-b_count);
      sb_partial=0;
      sb_full=b_coded;
      b_coded=_fr->b_coded_prev;
      b_coded_count=_fr->b_coded_count_prev;
    }
    else{
      /*It was partially coded.*/
      sb_partial=1;
      /*sb_full is unused.*/
    }
    _fr->bits=bits;
    _fr->b_coded_count=b_coded_count;
    _fr->b_coded_count_prev=b_coded_count;
    _fr->b_count=0;
    _fr->b_coded=b_coded;
    _fr->b_coded_prev=b_coded;
    oc_fr_state_advance_sb(_fr,sb_partial,sb_full);
  }
}

static void oc_fr_state_advance_block(oc_fr_state *_fr,int _b_coded){
  ptrdiff_t bits;
  int       b_coded_count;
  int       b_count;
  int       sb_partial;
  int       sb_full=sb_full;<--- Redundant assignment of 'sb_full' to itself.<--- Uninitialized variable: sb_full
  bits=_fr->bits;
  /*Extend the b_coded run, or start a new one.*/
  b_coded_count=_fr->b_coded_count;
  if(_fr->b_coded==_b_coded)bits-=oc_block_run_bits(b_coded_count);
  else b_coded_count=0;
  b_coded_count++;
  b_count=_fr->b_count+1;
  if(b_count>=16){
    /*We finished a superblock.*/
    if(b_coded_count>=16){
      /*It was fully coded/uncoded; roll back the partial block flags.*/
      if(b_coded_count>16)bits+=oc_block_run_bits(b_coded_count-16);
      sb_partial=0;
      sb_full=_b_coded;
      _b_coded=_fr->b_coded_prev;
      b_coded_count=_fr->b_coded_count_prev;
    }
    else{
      bits+=oc_block_run_bits(b_coded_count);
      /*It was partially coded.*/
      sb_partial=1;
      /*sb_full is unused.*/
    }
    _fr->bits=bits;
    _fr->b_coded_count=b_coded_count;
    _fr->b_coded_count_prev=b_coded_count;
    _fr->b_count=0;
    _fr->b_coded=_b_coded;
    _fr->b_coded_prev=_b_coded;
    oc_fr_state_advance_sb(_fr,sb_partial,sb_full);
  }
  else{
    bits+=oc_block_run_bits(b_coded_count);
    _fr->bits=bits;
    _fr->b_coded_count=b_coded_count;
    _fr->b_count=b_count;
    _fr->b_coded=_b_coded;
  }
}

static void oc_fr_skip_block(oc_fr_state *_fr){
  oc_fr_state_advance_block(_fr,0);
}

static void oc_fr_code_block(oc_fr_state *_fr){
  oc_fr_state_advance_block(_fr,1);
}

static int oc_fr_cost1(const oc_fr_state *_fr){
  oc_fr_state tmp;
  ptrdiff_t   bits;
  *&tmp=*_fr;
  oc_fr_skip_block(&tmp);
  bits=tmp.bits;
  *&tmp=*_fr;
  oc_fr_code_block(&tmp);
  return (int)(tmp.bits-bits);
}

static int oc_fr_cost4(const oc_fr_state *_pre,const oc_fr_state *_post){
  oc_fr_state tmp;
  *&tmp=*_pre;
  oc_fr_skip_block(&tmp);
  oc_fr_skip_block(&tmp);
  oc_fr_skip_block(&tmp);
  oc_fr_skip_block(&tmp);
  return (int)(_post->bits-tmp.bits);
}



struct oc_qii_state{
  ptrdiff_t  bits;
  unsigned   qi01_count:14;
  signed int qi01:2;
  unsigned   qi12_count:14;
  signed int qi12:2;
};



static void oc_qii_state_init(oc_qii_state *_qs){
  _qs->bits=0;
  _qs->qi01_count=0;
  _qs->qi01=-1;
  _qs->qi12_count=0;
  _qs->qi12=-1;
}


static void oc_qii_state_advance(oc_qii_state *_qd,
 const oc_qii_state *_qs,int _qii){
  ptrdiff_t bits;
  int       qi01;
  int       qi01_count;
  int       qi12;
  int       qi12_count;
  bits=_qs->bits;
  qi01=_qii+1>>1;
  qi01_count=_qs->qi01_count;
  if(qi01==_qs->qi01){
    if(qi01_count>=4129){
      bits++;
      qi01_count=0;
    }
    else bits-=oc_sb_run_bits(qi01_count);
  }
  else qi01_count=0;
  qi01_count++;
  bits+=oc_sb_run_bits(qi01_count);
  qi12_count=_qs->qi12_count;
  if(_qii){
    qi12=_qii>>1;
    if(qi12==_qs->qi12){
      if(qi12_count>=4129){
        bits++;
        qi12_count=0;
      }
      else bits-=oc_sb_run_bits(qi12_count);
    }
    else qi12_count=0;
    qi12_count++;
    bits+=oc_sb_run_bits(qi12_count);
  }
  else qi12=_qs->qi12;
  _qd->bits=bits;
  _qd->qi01=qi01;
  _qd->qi01_count=qi01_count;
  _qd->qi12=qi12;
  _qd->qi12_count=qi12_count;
}



/*Temporary encoder state for the analysis pipeline.*/
struct oc_enc_pipeline_state{
  int                 bounding_values[256];
  oc_fr_state         fr[3];
  oc_qii_state        qs[3];
  /*Condensed dequantization tables.*/
  const ogg_uint16_t *dequant[3][3][2];
  /*Condensed quantization tables.*/
  const oc_iquant    *enquant[3][3][2];
  /*Skip SSD storage for the current MCU in each plane.*/
  unsigned           *skip_ssd[3];
  /*Coded/uncoded fragment lists for each plane for the current MCU.*/
  ptrdiff_t          *coded_fragis[3];
  ptrdiff_t          *uncoded_fragis[3];
  ptrdiff_t           ncoded_fragis[3];
  ptrdiff_t           nuncoded_fragis[3];
  /*The starting fragment for the current MCU in each plane.*/
  ptrdiff_t           froffset[3];
  /*The starting row for the current MCU in each plane.*/
  int                 fragy0[3];
  /*The ending row for the current MCU in each plane.*/
  int                 fragy_end[3];
  /*The starting superblock for the current MCU in each plane.*/
  unsigned            sbi0[3];
  /*The ending superblock for the current MCU in each plane.*/
  unsigned            sbi_end[3];
  /*The number of tokens for zzi=1 for each color plane.*/
  int                 ndct_tokens1[3];
  /*The outstanding eob_run count for zzi=1 for each color plane.*/
  int                 eob_run1[3];
  /*Whether or not the loop filter is enabled.*/
  int                 loop_filter;
};


static void oc_enc_pipeline_init(oc_enc_ctx *_enc,oc_enc_pipeline_state *_pipe){
  ptrdiff_t *coded_fragis;
  unsigned   mcu_nvsbs;
  ptrdiff_t  mcu_nfrags;
  int        hdec;
  int        vdec;
  int        pli;
  int        qii;
  int        qti;
  /*Initialize the per-plane coded block flag trackers.
    These are used for bit-estimation purposes only; the real flag bits span
     all three planes, so we can't compute them in parallel.*/
  for(pli=0;pli<3;pli++)oc_fr_state_init(_pipe->fr+pli);
  for(pli=0;pli<3;pli++)oc_qii_state_init(_pipe->qs+pli);
  /*Set up the per-plane skip SSD storage pointers.*/
  mcu_nvsbs=_enc->mcu_nvsbs;
  mcu_nfrags=mcu_nvsbs*_enc->state.fplanes[0].nhsbs*16;
  hdec=!(_enc->state.info.pixel_fmt&1);
  vdec=!(_enc->state.info.pixel_fmt&2);
  _pipe->skip_ssd[0]=_enc->mcu_skip_ssd;
  _pipe->skip_ssd[1]=_pipe->skip_ssd[0]+mcu_nfrags;
  _pipe->skip_ssd[2]=_pipe->skip_ssd[1]+(mcu_nfrags>>hdec+vdec);
  /*Set up per-plane pointers to the coded and uncoded fragments lists.
    Unlike the decoder, each planes' coded and uncoded fragment list is kept
     separate during the analysis stage; we only make the coded list for all
     three planes contiguous right before the final packet is output
     (destroying the uncoded lists, which are no longer needed).*/
  coded_fragis=_enc->state.coded_fragis;
  for(pli=0;pli<3;pli++){
    _pipe->coded_fragis[pli]=coded_fragis;
    coded_fragis+=_enc->state.fplanes[pli].nfrags;
    _pipe->uncoded_fragis[pli]=coded_fragis;
  }
  memset(_pipe->ncoded_fragis,0,sizeof(_pipe->ncoded_fragis));
  memset(_pipe->nuncoded_fragis,0,sizeof(_pipe->nuncoded_fragis));
  /*Set up condensed quantizer tables.*/
  for(pli=0;pli<3;pli++){
    for(qii=0;qii<_enc->state.nqis;qii++){
      int qi;
      qi=_enc->state.qis[qii];
      for(qti=0;qti<2;qti++){
        _pipe->dequant[pli][qii][qti]=_enc->state.dequant_tables[qi][pli][qti];
        _pipe->enquant[pli][qii][qti]=_enc->enquant_tables[qi][pli][qti];
      }
    }
  }
  /*Initialize the tokenization state.*/
  for(pli=0;pli<3;pli++){
    _pipe->ndct_tokens1[pli]=0;
    _pipe->eob_run1[pli]=0;
  }
  /*Initialize the bounding value array for the loop filter.*/
  _pipe->loop_filter=!oc_state_loop_filter_init(&_enc->state,
   _pipe->bounding_values);
}

/*Sets the current MCU stripe to super block row _sby.
  Return: A non-zero value if this was the last MCU.*/
static int oc_enc_pipeline_set_stripe(oc_enc_ctx *_enc,
 oc_enc_pipeline_state *_pipe,int _sby){
  const oc_fragment_plane *fplane;
  unsigned                 mcu_nvsbs;
  int                      sby_end;
  int                      notdone;
  int                      vdec;
  int                      pli;
  mcu_nvsbs=_enc->mcu_nvsbs;
  sby_end=_enc->state.fplanes[0].nvsbs;
  notdone=_sby+mcu_nvsbs<sby_end;
  if(notdone)sby_end=_sby+mcu_nvsbs;
  vdec=0;
  for(pli=0;pli<3;pli++){
    fplane=_enc->state.fplanes+pli;
    _pipe->sbi0[pli]=fplane->sboffset+(_sby>>vdec)*fplane->nhsbs;
    _pipe->fragy0[pli]=_sby<<2-vdec;
    _pipe->froffset[pli]=fplane->froffset
     +_pipe->fragy0[pli]*(ptrdiff_t)fplane->nhfrags;
    if(notdone){
      _pipe->sbi_end[pli]=fplane->sboffset+(sby_end>>vdec)*fplane->nhsbs;
      _pipe->fragy_end[pli]=sby_end<<2-vdec;
    }
    else{
      _pipe->sbi_end[pli]=fplane->sboffset+fplane->nsbs;
      _pipe->fragy_end[pli]=fplane->nvfrags;
    }
    vdec=!(_enc->state.info.pixel_fmt&2);
  }
  return notdone;
}

static void oc_enc_pipeline_finish_mcu_plane(oc_enc_ctx *_enc,
 oc_enc_pipeline_state *_pipe,int _pli,int _sdelay,int _edelay){
  int refi;
  /*Copy over all the uncoded fragments from this plane and advance the uncoded
     fragment list.*/
  _pipe->uncoded_fragis[_pli]-=_pipe->nuncoded_fragis[_pli];
  oc_state_frag_copy_list(&_enc->state,_pipe->uncoded_fragis[_pli],
   _pipe->nuncoded_fragis[_pli],OC_FRAME_SELF,OC_FRAME_PREV,_pli);
  _pipe->nuncoded_fragis[_pli]=0;
  /*Perform DC prediction.*/
  oc_enc_pred_dc_frag_rows(_enc,_pli,
   _pipe->fragy0[_pli],_pipe->fragy_end[_pli]);
  /*Finish DC tokenization.*/
  oc_enc_tokenize_dc_frag_list(_enc,_pli,
   _pipe->coded_fragis[_pli],_pipe->ncoded_fragis[_pli],
   _pipe->ndct_tokens1[_pli],_pipe->eob_run1[_pli]);
  _pipe->ndct_tokens1[_pli]=_enc->ndct_tokens[_pli][1];
  _pipe->eob_run1[_pli]=_enc->eob_run[_pli][1];
  /*And advance the coded fragment list.*/
  _enc->state.ncoded_fragis[_pli]+=_pipe->ncoded_fragis[_pli];
  _pipe->coded_fragis[_pli]+=_pipe->ncoded_fragis[_pli];
  _pipe->ncoded_fragis[_pli]=0;
  /*Apply the loop filter if necessary.*/
  refi=_enc->state.ref_frame_idx[OC_FRAME_SELF];
  if(_pipe->loop_filter){
    oc_state_loop_filter_frag_rows(&_enc->state,_pipe->bounding_values,
     refi,_pli,_pipe->fragy0[_pli]-_sdelay,_pipe->fragy_end[_pli]-_edelay);
  }
  else _sdelay=_edelay=0;
  /*To fill borders, we have an additional two pixel delay, since a fragment
     in the next row could filter its top edge, using two pixels from a
     fragment in this row.
    But there's no reason to delay a full fragment between the two.*/
  oc_state_borders_fill_rows(&_enc->state,refi,_pli,
   (_pipe->fragy0[_pli]-_sdelay<<3)-(_sdelay<<1),
   (_pipe->fragy_end[_pli]-_edelay<<3)-(_edelay<<1));
}



/*Cost information about the coded blocks in a MB.*/
struct oc_rd_metric{
  int uncoded_ac_ssd;
  int coded_ac_ssd;
  int ac_bits;
  int dc_flag;
};



static int oc_enc_block_transform_quantize(oc_enc_ctx *_enc,
 oc_enc_pipeline_state *_pipe,int _pli,ptrdiff_t _fragi,int _overhead_bits,
 oc_rd_metric *_mo,oc_token_checkpoint **_stack){
  OC_ALIGN16(ogg_int16_t  dct[64]);
  OC_ALIGN16(ogg_int16_t  data[64]);
  ogg_uint16_t            dc_dequant;
  const ogg_uint16_t     *dequant;
  const oc_iquant        *enquant;
  ptrdiff_t               frag_offs;
  int                     ystride;
  const unsigned char    *src;
  const unsigned char    *ref;
  unsigned char          *dst;
  int                     frame_type;
  int                     nonzero;
  unsigned                uncoded_ssd;
  unsigned                coded_ssd;
  int                     coded_dc;
  oc_token_checkpoint    *checkpoint;
  oc_fragment            *frags;
  int                     mb_mode;
  int                     mv_offs[2];
  int                     nmv_offs;
  int                     ac_bits;
  int                     borderi;
  int                     qti;
  int                     qii;
  int                     pi;
  int                     zzi;
  int                     v;
  int                     val;
  int                     d;
  int                     s;
  int                     dc;
  frags=_enc->state.frags;
  frag_offs=_enc->state.frag_buf_offs[_fragi];
  ystride=_enc->state.ref_ystride[_pli];
  src=_enc->state.ref_frame_data[OC_FRAME_IO]+frag_offs;
  borderi=frags[_fragi].borderi;
  qii=frags[_fragi].qii;
  if(qii&~3){
#if !defined(OC_COLLECT_METRICS)
    if(_enc->sp_level>=OC_SP_LEVEL_EARLY_SKIP){
      /*Enable early skip detection.*/
      frags[_fragi].coded=0;
      return 0;
    }
#endif
    /*Try and code this block anyway.*/
    qii&=3;
    frags[_fragi].qii=qii;
  }
  mb_mode=frags[_fragi].mb_mode;
  ref=_enc->state.ref_frame_data[
   _enc->state.ref_frame_idx[OC_FRAME_FOR_MODE(mb_mode)]]+frag_offs;
  dst=_enc->state.ref_frame_data[_enc->state.ref_frame_idx[OC_FRAME_SELF]]
   +frag_offs;
  /*Motion compensation:*/
  switch(mb_mode){
    case OC_MODE_INTRA:{
      nmv_offs=0;
      oc_enc_frag_sub_128(_enc,data,src,ystride);
    }break;
    case OC_MODE_GOLDEN_NOMV:
    case OC_MODE_INTER_NOMV:{
      nmv_offs=1;
      mv_offs[0]=0;
      oc_enc_frag_sub(_enc,data,src,ref,ystride);
    }break;
    default:{
      const oc_mv *frag_mvs;
      frag_mvs=(const oc_mv *)_enc->state.frag_mvs;
      nmv_offs=oc_state_get_mv_offsets(&_enc->state,mv_offs,_pli,
       frag_mvs[_fragi][0],frag_mvs[_fragi][1]);
      if(nmv_offs>1){
        oc_enc_frag_copy2(_enc,dst,
         ref+mv_offs[0],ref+mv_offs[1],ystride);
        oc_enc_frag_sub(_enc,data,src,dst,ystride);
      }
      else oc_enc_frag_sub(_enc,data,src,ref+mv_offs[0],ystride);
    }break;
  }
#if defined(OC_COLLECT_METRICS)
  {
    unsigned satd;
    switch(nmv_offs){
      case 0:satd=oc_enc_frag_intra_satd(_enc,src,ystride);break;
      case 1:{
        satd=oc_enc_frag_satd_thresh(_enc,src,ref+mv_offs[0],ystride,UINT_MAX);
      }break;
      default:{
        satd=oc_enc_frag_satd_thresh(_enc,src,dst,ystride,UINT_MAX);
      }
    }
    _enc->frag_satd[_fragi]=satd;
  }
#endif
  /*Transform:*/
  oc_enc_fdct8x8(_enc,dct,data);
  /*Quantize the DC coefficient:*/
  qti=mb_mode!=OC_MODE_INTRA;
  enquant=_pipe->enquant[_pli][0][qti];
  dc_dequant=_pipe->dequant[_pli][0][qti][0];
  v=dct[0];
  val=v<<1;
  s=OC_SIGNMASK(val);
  val+=dc_dequant+s^s;
  val=((enquant[0].m*(ogg_int32_t)val>>16)+val>>enquant[0].l)-s;
  dc=OC_CLAMPI(-580,val,580);
  nonzero=0;
  /*Quantize the AC coefficients:*/
  dequant=_pipe->dequant[_pli][qii][qti];
  enquant=_pipe->enquant[_pli][qii][qti];
  for(zzi=1;zzi<64;zzi++){
    v=dct[OC_FZIG_ZAG[zzi]];
    d=dequant[zzi];
    val=v<<1;
    v=abs(val);
    if(v>=d){
      s=OC_SIGNMASK(val);
      /*The bias added here rounds ties away from zero, since token
         optimization can only decrease the magnitude of the quantized
         value.*/
      val+=d+s^s;
      /*Note the arithmetic right shift is not guaranteed by ANSI C.
        Hopefully no one still uses ones-complement architectures.*/
      val=((enquant[zzi].m*(ogg_int32_t)val>>16)+val>>enquant[zzi].l)-s;
      data[zzi]=OC_CLAMPI(-580,val,580);
      nonzero=zzi;
    }
    else data[zzi]=0;
  }
  /*Tokenize.*/
  checkpoint=*_stack;
  ac_bits=oc_enc_tokenize_ac(_enc,_pli,_fragi,data,dequant,dct,nonzero+1,
   _stack,qti?0:3);
  /*Reconstruct.
    TODO: nonzero may need to be adjusted after tokenization.*/
  if(nonzero==0){
    ogg_int16_t p;
    int         ci;
    /*We round this dequant product (and not any of the others) because there's
       no iDCT rounding.*/
    p=(ogg_int16_t)(dc*(ogg_int32_t)dc_dequant+15>>5);
    /*LOOP VECTORIZES.*/
    for(ci=0;ci<64;ci++)data[ci]=p;
  }
  else{
    data[0]=dc*dc_dequant;
    oc_idct8x8(&_enc->state,data,nonzero+1);
  }
  if(!qti)oc_enc_frag_recon_intra(_enc,dst,ystride,data);
  else{
    oc_enc_frag_recon_inter(_enc,dst,
     nmv_offs==1?ref+mv_offs[0]:dst,ystride,data);
  }
  frame_type=_enc->state.frame_type;
#if !defined(OC_COLLECT_METRICS)
  if(frame_type!=OC_INTRA_FRAME)
#endif
  {
    /*In retrospect, should we have skipped this block?*/
    oc_enc_frag_sub(_enc,data,src,dst,ystride);
    coded_ssd=coded_dc=0;
    if(borderi<0){
      for(pi=0;pi<64;pi++){
        coded_ssd+=data[pi]*data[pi];
        coded_dc+=data[pi];
      }
    }
    else{
      ogg_int64_t mask;
      mask=_enc->state.borders[borderi].mask;
      for(pi=0;pi<64;pi++,mask>>=1)if(mask&1){
        coded_ssd+=data[pi]*data[pi];
        coded_dc+=data[pi];
      }
    }
    /*Scale to match DCT domain.*/
    coded_ssd<<=4;
    /*We actually only want the AC contribution to the SSD.*/
    coded_ssd-=coded_dc*coded_dc>>2;
#if defined(OC_COLLECT_METRICS)
    _enc->frag_ssd[_fragi]=coded_ssd;
  }
  if(frame_type!=OC_INTRA_FRAME){
#endif
    uncoded_ssd=_pipe->skip_ssd[_pli][_fragi-_pipe->froffset[_pli]];
    if(uncoded_ssd<UINT_MAX){
      /*Although the fragment coding overhead determination is accurate, it is
         greedy, using very coarse-grained local information.
        Allowing it to mildly discourage coding turns out to be beneficial, but
         it's not clear that allowing it to encourage coding through negative
         coding overhead deltas is useful.
        For that reason, we disallow negative coding_overheads.*/
      if(_overhead_bits<0)_overhead_bits=0;
      if(uncoded_ssd<=coded_ssd+(_overhead_bits+ac_bits)*_enc->lambda&&
       /*Don't allow luma blocks to be skipped in 4MV mode when VP3
          compatibility is enabled.*/
       (!_enc->vp3_compatible||mb_mode!=OC_MODE_INTER_MV_FOUR||_pli)){
        /*Hm, not worth it; roll back.*/
        oc_enc_tokenlog_rollback(_enc,checkpoint,(*_stack)-checkpoint);
        *_stack=checkpoint;
        frags[_fragi].coded=0;
        return 0;
      }
    }
    else _mo->dc_flag=1;
    _mo->uncoded_ac_ssd+=uncoded_ssd;
    _mo->coded_ac_ssd+=coded_ssd;
    _mo->ac_bits+=ac_bits;
  }
  oc_qii_state_advance(_pipe->qs+_pli,_pipe->qs+_pli,qii);
  frags[_fragi].dc=dc;
  frags[_fragi].coded=1;
  return 1;
}

static int oc_enc_mb_transform_quantize_luma(oc_enc_ctx *_enc,
 oc_enc_pipeline_state *_pipe,unsigned _mbi,int _mode_overhead){
  /*Worst case token stack usage for 4 fragments.*/
  oc_token_checkpoint  stack[64*4];
  oc_token_checkpoint *stackptr;
  const oc_sb_map     *sb_maps;
  signed char         *mb_modes;
  oc_fragment         *frags;
  ptrdiff_t           *coded_fragis;
  ptrdiff_t            ncoded_fragis;
  ptrdiff_t           *uncoded_fragis;
  ptrdiff_t            nuncoded_fragis;
  oc_rd_metric         mo;
  oc_fr_state          fr_checkpoint;
  oc_qii_state         qs_checkpoint;
  int                  mb_mode;
  int                  ncoded;
  ptrdiff_t            fragi;
  int                  bi;
  *&fr_checkpoint=*(_pipe->fr+0);
  *&qs_checkpoint=*(_pipe->qs+0);
  sb_maps=(const oc_sb_map *)_enc->state.sb_maps;
  mb_modes=_enc->state.mb_modes;
  frags=_enc->state.frags;
  coded_fragis=_pipe->coded_fragis[0];
  ncoded_fragis=_pipe->ncoded_fragis[0];
  uncoded_fragis=_pipe->uncoded_fragis[0];
  nuncoded_fragis=_pipe->nuncoded_fragis[0];
  mb_mode=mb_modes[_mbi];
  ncoded=0;
  stackptr=stack;
  memset(&mo,0,sizeof(mo));
  for(bi=0;bi<4;bi++){
    fragi=sb_maps[_mbi>>2][_mbi&3][bi];
    frags[fragi].mb_mode=mb_mode;
    if(oc_enc_block_transform_quantize(_enc,
     _pipe,0,fragi,oc_fr_cost1(_pipe->fr+0),&mo,&stackptr)){
      oc_fr_code_block(_pipe->fr+0);
      coded_fragis[ncoded_fragis++]=fragi;
      ncoded++;
    }
    else{
      *(uncoded_fragis-++nuncoded_fragis)=fragi;
      oc_fr_skip_block(_pipe->fr+0);
    }
  }
  if(_enc->state.frame_type!=OC_INTRA_FRAME){
    if(ncoded>0&&!mo.dc_flag){
      int cost;
      /*Some individual blocks were worth coding.
        See if that's still true when accounting for mode and MV overhead.*/
      cost=mo.coded_ac_ssd+_enc->lambda*(mo.ac_bits
       +oc_fr_cost4(&fr_checkpoint,_pipe->fr+0)+_mode_overhead);
      if(mo.uncoded_ac_ssd<=cost){
        /*Taking macroblock overhead into account, it is not worth coding this
           MB.*/
        oc_enc_tokenlog_rollback(_enc,stack,stackptr-stack);
        *(_pipe->fr+0)=*&fr_checkpoint;
        *(_pipe->qs+0)=*&qs_checkpoint;
        for(bi=0;bi<4;bi++){
          fragi=sb_maps[_mbi>>2][_mbi&3][bi];
          if(frags[fragi].coded){
            *(uncoded_fragis-++nuncoded_fragis)=fragi;
            frags[fragi].coded=0;
          }
          oc_fr_skip_block(_pipe->fr+0);
        }
        ncoded_fragis-=ncoded;
        ncoded=0;
      }
    }
    /*If no luma blocks coded, the mode is forced.*/
    if(ncoded==0)mb_modes[_mbi]=OC_MODE_INTER_NOMV;
    /*Assume that a 1MV with a single coded block is always cheaper than a 4MV
       with a single coded block.
      This may not be strictly true: a 4MV computes chroma MVs using (0,0) for
       skipped blocks, while a 1MV does not.*/
    else if(ncoded==1&&mb_mode==OC_MODE_INTER_MV_FOUR){
      mb_modes[_mbi]=OC_MODE_INTER_MV;
    }
  }
  _pipe->ncoded_fragis[0]=ncoded_fragis;
  _pipe->nuncoded_fragis[0]=nuncoded_fragis;
  return ncoded;
}

static void oc_enc_sb_transform_quantize_chroma(oc_enc_ctx *_enc,
 oc_enc_pipeline_state *_pipe,int _pli,int _sbi_start,int _sbi_end){
  const oc_sb_map *sb_maps;
  oc_sb_flags     *sb_flags;
  ptrdiff_t       *coded_fragis;
  ptrdiff_t        ncoded_fragis;
  ptrdiff_t       *uncoded_fragis;
  ptrdiff_t        nuncoded_fragis;
  int              sbi;
  sb_maps=(const oc_sb_map *)_enc->state.sb_maps;
  sb_flags=_enc->state.sb_flags;
  coded_fragis=_pipe->coded_fragis[_pli];
  ncoded_fragis=_pipe->ncoded_fragis[_pli];
  uncoded_fragis=_pipe->uncoded_fragis[_pli];
  nuncoded_fragis=_pipe->nuncoded_fragis[_pli];
  for(sbi=_sbi_start;sbi<_sbi_end;sbi++){
    /*Worst case token stack usage for 1 fragment.*/
    oc_token_checkpoint stack[64];
    oc_rd_metric        mo;
    int                 quadi;
    int                 bi;
    memset(&mo,0,sizeof(mo));
    for(quadi=0;quadi<4;quadi++)for(bi=0;bi<4;bi++){
      ptrdiff_t fragi;
      fragi=sb_maps[sbi][quadi][bi];
      if(fragi>=0){
        oc_token_checkpoint *stackptr;
        stackptr=stack;
        if(oc_enc_block_transform_quantize(_enc,
         _pipe,_pli,fragi,oc_fr_cost1(_pipe->fr+_pli),&mo,&stackptr)){
          coded_fragis[ncoded_fragis++]=fragi;
          oc_fr_code_block(_pipe->fr+_pli);
        }
        else{
          *(uncoded_fragis-++nuncoded_fragis)=fragi;
          oc_fr_skip_block(_pipe->fr+_pli);
        }
      }
    }
    oc_fr_state_flush_sb(_pipe->fr+_pli);
    sb_flags[sbi].coded_fully=_pipe->fr[_pli].sb_full;
    sb_flags[sbi].coded_partially=_pipe->fr[_pli].sb_partial;
  }
  _pipe->ncoded_fragis[_pli]=ncoded_fragis;
  _pipe->nuncoded_fragis[_pli]=nuncoded_fragis;
}

/*Mode decision is done by exhaustively examining all potential choices.
  Obviously, doing the motion compensation, fDCT, tokenization, and then
   counting the bits each token uses is computationally expensive.
  Theora's EOB runs can also split the cost of these tokens across multiple
   fragments, and naturally we don't know what the optimal choice of Huffman
   codes will be until we know all the tokens we're going to encode in all the
   fragments.
  So we use a simple approach to estimating the bit cost and distortion of each
   mode based upon the SATD value of the residual before coding.
  The mathematics behind the technique are outlined by Kim \cite{Kim03}, but
   the process (modified somewhat from that of the paper) is very simple.
  We build a non-linear regression of the mappings from
   (pre-transform+quantization) SATD to (post-transform+quantization) bits and
   SSD for each qi.
  A separate set of mappings is kept for each quantization type and color
   plane.
  The mappings are constructed by partitioning the SATD values into a small
   number of bins (currently 24) and using a linear regression in each bin
   (as opposed to the 0th-order regression used by Kim).
  The bit counts and SSD measurements are obtained by examining actual encoded
   frames, with appropriate lambda values and optimal Huffman codes selected.
  EOB bits are assigned to the fragment that started the EOB run (as opposed to
   dividing them among all the blocks in the run; though the latter approach
   seems more theoretically correct, Monty's testing showed a small improvement
   with the former, though that may have been merely statistical noise).

  @ARTICLE{Kim03,
    author="Hyun Mun Kim",
    title="Adaptive Rate Control Using Nonlinear Regression",
    journal="IEEE Transactions on Circuits and Systems for Video Technology",
    volume=13,
    number=5,
    pages="432--439",
    month=May,
    year=2003
  }*/

/*Computes (_ssd+_lambda*_rate)/(1<<OC_BIT_SCALE) with rounding, avoiding
   overflow for large lambda values.*/
#define OC_MODE_RD_COST(_ssd,_rate,_lambda) \
 ((_ssd)>>OC_BIT_SCALE)+((_rate)>>OC_BIT_SCALE)*(_lambda) \
 +(((_ssd)&(1<<OC_BIT_SCALE)-1)+((_rate)&(1<<OC_BIT_SCALE)-1)*(_lambda) \
 +((1<<OC_BIT_SCALE)>>1)>>OC_BIT_SCALE)

/*Estimate the R-D cost of the DCT coefficients given the SATD of a block after
   prediction.*/
static unsigned oc_dct_cost2(unsigned *_ssd,
 int _qi,int _pli,int _qti,int _satd){
  unsigned rmse;
  int      bin;
  int      dx;
  int      y0;
  int      z0;
  int      dy;
  int      dz;
  /*SATD metrics for chroma planes vary much less than luma, so we scale them
     by 4 to distribute them into the mode decision bins more evenly.*/
  _satd<<=_pli+1&2;
  bin=OC_MINI(_satd>>OC_SAD_SHIFT,OC_SAD_BINS-2);
  dx=_satd-(bin<<OC_SAD_SHIFT);
  y0=OC_MODE_RD[_qi][_pli][_qti][bin].rate;
  z0=OC_MODE_RD[_qi][_pli][_qti][bin].rmse;
  dy=OC_MODE_RD[_qi][_pli][_qti][bin+1].rate-y0;
  dz=OC_MODE_RD[_qi][_pli][_qti][bin+1].rmse-z0;
  rmse=OC_MAXI(z0+(dz*dx>>OC_SAD_SHIFT),0);
  *_ssd=rmse*rmse>>2*OC_RMSE_SCALE-OC_BIT_SCALE;
  return OC_MAXI(y0+(dy*dx>>OC_SAD_SHIFT),0);
}

/*Select luma block-level quantizers for a MB in an INTRA frame.*/
static unsigned oc_analyze_intra_mb_luma(oc_enc_ctx *_enc,
 const oc_qii_state *_qs,unsigned _mbi){
  const unsigned char *src;
  const ptrdiff_t     *frag_buf_offs;
  const oc_sb_map     *sb_maps;
  oc_fragment         *frags;
  ptrdiff_t            frag_offs;
  ptrdiff_t            fragi;
  oc_qii_state         qs[4][3];
  unsigned             cost[4][3];
  unsigned             ssd[4][3];
  unsigned             rate[4][3];
  int                  prev[3][3];
  unsigned             satd;
  unsigned             best_cost;
  unsigned             best_ssd;
  unsigned             best_rate;
  int                  best_qii;
  int                  qii;
  int                  lambda;
  int                  ystride;
  int                  nqis;
  int                  bi;
  frag_buf_offs=_enc->state.frag_buf_offs;
  sb_maps=(const oc_sb_map *)_enc->state.sb_maps;
  src=_enc->state.ref_frame_data[OC_FRAME_IO];
  ystride=_enc->state.ref_ystride[0];
  fragi=sb_maps[_mbi>>2][_mbi&3][0];
  frag_offs=frag_buf_offs[fragi];
  satd=oc_enc_frag_intra_satd(_enc,src+frag_offs,ystride);
  nqis=_enc->state.nqis;
  lambda=_enc->lambda;
  for(qii=0;qii<nqis;qii++){
    oc_qii_state_advance(qs[0]+qii,_qs,qii);
    rate[0][qii]=oc_dct_cost2(ssd[0]+qii,_enc->state.qis[qii],0,0,satd)
     +(qs[0][qii].bits-_qs->bits<<OC_BIT_SCALE);<--- Uninitialized variable: qs
    cost[0][qii]=OC_MODE_RD_COST(ssd[0][qii],rate[0][qii],lambda);<--- Uninitialized variable: ssd
  }
  for(bi=1;bi<4;bi++){
    fragi=sb_maps[_mbi>>2][_mbi&3][bi];
    frag_offs=frag_buf_offs[fragi];
    satd=oc_enc_frag_intra_satd(_enc,src+frag_offs,ystride);
    for(qii=0;qii<nqis;qii++){
      oc_qii_state qt[3];
      unsigned     cur_ssd;
      unsigned     cur_rate;
      int          best_qij;
      int          qij;
      oc_qii_state_advance(qt+0,qs[bi-1]+0,qii);
      cur_rate=oc_dct_cost2(&cur_ssd,_enc->state.qis[qii],0,0,satd);
      best_ssd=ssd[bi-1][0]+cur_ssd;
      best_rate=rate[bi-1][0]+cur_rate
       +(qt[0].bits-qs[bi-1][0].bits<<OC_BIT_SCALE);
      best_cost=OC_MODE_RD_COST(best_ssd,best_rate,lambda);
      best_qij=0;
      for(qij=1;qij<nqis;qij++){
        unsigned chain_ssd;
        unsigned chain_rate;
        unsigned chain_cost;
        oc_qii_state_advance(qt+qij,qs[bi-1]+qij,qii);
        chain_ssd=ssd[bi-1][qij]+cur_ssd;
        chain_rate=rate[bi-1][qij]+cur_rate
         +(qt[qij].bits-qs[bi-1][qij].bits<<OC_BIT_SCALE);
        chain_cost=OC_MODE_RD_COST(chain_ssd,chain_rate,lambda);
        if(chain_cost<best_cost){
          best_cost=chain_cost;
          best_ssd=chain_ssd;
          best_rate=chain_rate;
          best_qij=qij;
        }
      }
      *(qs[bi]+qii)=*(qt+best_qij);
      cost[bi][qii]=best_cost;
      ssd[bi][qii]=best_ssd;
      rate[bi][qii]=best_rate;
      prev[bi-1][qii]=best_qij;
    }
  }
  best_qii=0;
  best_cost=cost[3][0];
  for(qii=1;qii<nqis;qii++){
    if(cost[3][qii]<best_cost){
      best_cost=cost[3][qii];
      best_qii=qii;
    }
  }
  frags=_enc->state.frags;
  for(bi=3;;){
    fragi=sb_maps[_mbi>>2][_mbi&3][bi];
    frags[fragi].qii=best_qii;
    if(bi--<=0)break;
    best_qii=prev[bi][best_qii];
  }
  return best_cost;
}

/*Select a block-level quantizer for a single chroma block in an INTRA frame.*/
static unsigned oc_analyze_intra_chroma_block(oc_enc_ctx *_enc,
 const oc_qii_state *_qs,int _pli,ptrdiff_t _fragi){
  const unsigned char *src;
  oc_fragment         *frags;
  ptrdiff_t            frag_offs;
  oc_qii_state         qt[3];
  unsigned             cost[3];
  unsigned             satd;
  unsigned             best_cost;
  int                  best_qii;
  int                  qii;
  int                  lambda;
  int                  ystride;
  int                  nqis;
  src=_enc->state.ref_frame_data[OC_FRAME_IO];
  ystride=_enc->state.ref_ystride[_pli];
  frag_offs=_enc->state.frag_buf_offs[_fragi];
  satd=oc_enc_frag_intra_satd(_enc,src+frag_offs,ystride);
  nqis=_enc->state.nqis;
  lambda=_enc->lambda;
  best_qii=0;
  for(qii=0;qii<nqis;qii++){
    unsigned cur_rate;
    unsigned cur_ssd;
    oc_qii_state_advance(qt+qii,_qs,qii);
    cur_rate=oc_dct_cost2(&cur_ssd,_enc->state.qis[qii],_pli,0,satd)
     +(qt[qii].bits-_qs->bits<<OC_BIT_SCALE);
    cost[qii]=OC_MODE_RD_COST(cur_ssd,cur_rate,lambda);
  }
  best_cost=cost[0];
  for(qii=1;qii<nqis;qii++){
    if(cost[qii]<best_cost){
      best_cost=cost[qii];
      best_qii=qii;
    }
  }
  frags=_enc->state.frags;
  frags[_fragi].qii=best_qii;
  return best_cost;
}

static void oc_enc_sb_transform_quantize_intra_chroma(oc_enc_ctx *_enc,
 oc_enc_pipeline_state *_pipe,int _pli,int _sbi_start,int _sbi_end){
  const oc_sb_map *sb_maps;
  oc_sb_flags     *sb_flags;
  ptrdiff_t       *coded_fragis;
  ptrdiff_t        ncoded_fragis;
  int              sbi;
  sb_maps=(const oc_sb_map *)_enc->state.sb_maps;
  sb_flags=_enc->state.sb_flags;<--- Variable 'sb_flags' is assigned a value that is never used.
  coded_fragis=_pipe->coded_fragis[_pli];
  ncoded_fragis=_pipe->ncoded_fragis[_pli];
  for(sbi=_sbi_start;sbi<_sbi_end;sbi++){
    /*Worst case token stack usage for 1 fragment.*/
    oc_token_checkpoint stack[64];
    int                 quadi;
    int                 bi;
    for(quadi=0;quadi<4;quadi++)for(bi=0;bi<4;bi++){
      ptrdiff_t fragi;
      fragi=sb_maps[sbi][quadi][bi];
      if(fragi>=0){
        oc_token_checkpoint *stackptr;
        oc_analyze_intra_chroma_block(_enc,_pipe->qs+_pli,_pli,fragi);
        stackptr=stack;
        oc_enc_block_transform_quantize(_enc,
         _pipe,_pli,fragi,0,NULL,&stackptr);
        coded_fragis[ncoded_fragis++]=fragi;
      }
    }
  }
  _pipe->ncoded_fragis[_pli]=ncoded_fragis;
}

/*Analysis stage for an INTRA frame.*/
void oc_enc_analyze_intra(oc_enc_ctx *_enc,int _recode){
  oc_enc_pipeline_state   pipe;
  const unsigned char    *map_idxs;
  int                     nmap_idxs;
  oc_sb_flags            *sb_flags;
  signed char            *mb_modes;
  const oc_mb_map        *mb_maps;
  oc_mb_enc_info         *embs;
  oc_fragment            *frags;
  unsigned                stripe_sby;
  unsigned                mcu_nvsbs;
  int                     notstart;
  int                     notdone;
  int                     refi;
  int                     pli;
  _enc->state.frame_type=OC_INTRA_FRAME;
  oc_enc_tokenize_start(_enc);
  oc_enc_pipeline_init(_enc,&pipe);
  /*Choose MVs and MB modes and quantize and code luma.
    Must be done in Hilbert order.*/
  map_idxs=OC_MB_MAP_IDXS[_enc->state.info.pixel_fmt];
  nmap_idxs=OC_MB_MAP_NIDXS[_enc->state.info.pixel_fmt];
  _enc->state.ncoded_fragis[0]=0;
  _enc->state.ncoded_fragis[1]=0;
  _enc->state.ncoded_fragis[2]=0;
  sb_flags=_enc->state.sb_flags;
  mb_modes=_enc->state.mb_modes;
  mb_maps=(const oc_mb_map *)_enc->state.mb_maps;
  embs=_enc->mb_info;<--- Variable 'embs' is assigned a value that is never used.
  frags=_enc->state.frags;
  notstart=0;
  notdone=1;
  mcu_nvsbs=_enc->mcu_nvsbs;
  for(stripe_sby=0;notdone;stripe_sby+=mcu_nvsbs){
    unsigned sbi;
    unsigned sbi_end;
    notdone=oc_enc_pipeline_set_stripe(_enc,&pipe,stripe_sby);
    sbi_end=pipe.sbi_end[0];
    for(sbi=pipe.sbi0[0];sbi<sbi_end;sbi++){
      int quadi;
      /*Mode addressing is through Y plane, always 4 MB per SB.*/
      for(quadi=0;quadi<4;quadi++)if(sb_flags[sbi].quad_valid&1<<quadi){
        unsigned  mbi;
        int       mapii;
        int       mapi;
        int       bi;
        ptrdiff_t fragi;
        mbi=sbi<<2|quadi;
        /*Motion estimation:
          We always do a basic 1MV search for all macroblocks, coded or not,
           keyframe or not.*/
        if(!_recode&&_enc->state.curframe_num>0)oc_mcenc_search(_enc,mbi);
        oc_analyze_intra_mb_luma(_enc,pipe.qs+0,mbi);
        mb_modes[mbi]=OC_MODE_INTRA;
        oc_enc_mb_transform_quantize_luma(_enc,&pipe,mbi,0);
        /*Propagate final MB mode and MVs to the chroma blocks.*/
        for(mapii=4;mapii<nmap_idxs;mapii++){
          mapi=map_idxs[mapii];
          pli=mapi>>2;
          bi=mapi&3;
          fragi=mb_maps[mbi][pli][bi];
          frags[fragi].mb_mode=OC_MODE_INTRA;
        }
      }
    }
    oc_enc_pipeline_finish_mcu_plane(_enc,&pipe,0,notstart,notdone);
    /*Code chroma planes.*/
    for(pli=1;pli<3;pli++){
      oc_enc_sb_transform_quantize_intra_chroma(_enc,&pipe,
       pli,pipe.sbi0[pli],pipe.sbi_end[pli]);
      oc_enc_pipeline_finish_mcu_plane(_enc,&pipe,pli,notstart,notdone);
    }
    notstart=1;
  }
  /*Finish filling in the reference frame borders.*/
  refi=_enc->state.ref_frame_idx[OC_FRAME_SELF];
  for(pli=0;pli<3;pli++)oc_state_borders_fill_caps(&_enc->state,refi,pli);
  _enc->state.ntotal_coded_fragis=_enc->state.nfrags;
}



/*Cost information about a MB mode.*/
struct oc_mode_choice{
  unsigned      cost;
  unsigned      ssd;
  unsigned      rate;
  unsigned      overhead;
  unsigned char qii[12];
};



static void oc_mode_set_cost(oc_mode_choice *_modec,int _lambda){
  _modec->cost=OC_MODE_RD_COST(_modec->ssd,
   _modec->rate+_modec->overhead,_lambda);
}

/*A set of skip SSD's to use to disable early skipping.*/
static const unsigned OC_NOSKIP[12]={
  UINT_MAX,UINT_MAX,UINT_MAX,UINT_MAX,
  UINT_MAX,UINT_MAX,UINT_MAX,UINT_MAX,
  UINT_MAX,UINT_MAX,UINT_MAX,UINT_MAX
};

/*The estimated number of bits used by a coded chroma block to specify the AC
   quantizer.
  TODO: Currently this is just 0.5*log2(3) (estimating about 50% compression);
   measurements suggest this is in the right ballpark, but it varies somewhat
   with lambda.*/
#define OC_CHROMA_QII_RATE ((0xCAE00D1DU>>31-OC_BIT_SCALE)+1>>1)

static void oc_analyze_mb_mode_luma(oc_enc_ctx *_enc,
 oc_mode_choice *_modec,const oc_fr_state *_fr,const oc_qii_state *_qs,
 const unsigned _frag_satd[12],const unsigned _skip_ssd[12],int _qti){
  oc_fr_state  fr;
  oc_qii_state qs;
  unsigned     ssd;
  unsigned     rate;
  int          overhead;
  unsigned     satd;
  unsigned     best_ssd;
  unsigned     best_rate;
  int          best_overhead;
  int          best_fri;
  int          best_qii;
  unsigned     cur_cost;
  unsigned     cur_ssd;
  unsigned     cur_rate;
  int          cur_overhead;
  int          lambda;
  int          nqis;
  int          nskipped;
  int          bi;
  int          qii;
  lambda=_enc->lambda;
  nqis=_enc->state.nqis;
  /*We could do a trellis optimization here, but we don't make final skip
     decisions until after transform+quantization, so the result wouldn't be
     optimal anyway.
    Instead we just use a greedy approach; for most SATD values, the
     differences between the qiis are large enough to drown out the cost to
     code the flags, anyway.*/
  *&fr=*_fr;
  *&qs=*_qs;
  ssd=rate=overhead=nskipped=0;
  for(bi=0;bi<4;bi++){
    oc_fr_state  ft[2];
    oc_qii_state qt[3];
    unsigned     best_cost;
    satd=_frag_satd[bi];
    *(ft+0)=*&fr;
    oc_fr_code_block(ft+0);
    oc_qii_state_advance(qt+0,&qs,0);
    best_overhead=(ft[0].bits-fr.bits<<OC_BIT_SCALE);
    best_rate=oc_dct_cost2(&best_ssd,_enc->state.qis[0],0,_qti,satd)
     +(qt[0].bits-qs.bits<<OC_BIT_SCALE);
    best_cost=OC_MODE_RD_COST(ssd+best_ssd,rate+best_rate+best_overhead,lambda);
    best_fri=0;
    best_qii=0;
    for(qii=1;qii<nqis;qii++){
      oc_qii_state_advance(qt+qii,&qs,qii);
      cur_rate=oc_dct_cost2(&cur_ssd,_enc->state.qis[qii],0,_qti,satd)
       +(qt[qii].bits-qs.bits<<OC_BIT_SCALE);
      cur_cost=OC_MODE_RD_COST(ssd+cur_ssd,rate+cur_rate+best_overhead,lambda);
      if(cur_cost<best_cost){
        best_cost=cur_cost;
        best_ssd=cur_ssd;
        best_rate=cur_rate;
        best_qii=qii;
      }
    }
    if(_skip_ssd[bi]<UINT_MAX&&nskipped<3){
      *(ft+1)=*&fr;
      oc_fr_skip_block(ft+1);
      cur_overhead=ft[1].bits-fr.bits<<OC_BIT_SCALE;
      cur_ssd=_skip_ssd[bi]<<OC_BIT_SCALE;
      cur_cost=OC_MODE_RD_COST(ssd+cur_ssd,rate+cur_overhead,lambda);
      if(cur_cost<=best_cost){
        best_ssd=cur_ssd;
        best_rate=0;
        best_overhead=cur_overhead;
        best_fri=1;
        best_qii+=4;
      }
    }
    rate+=best_rate;
    ssd+=best_ssd;
    overhead+=best_overhead;
    *&fr=*(ft+best_fri);
    if(best_fri==0)*&qs=*(qt+best_qii);
    else nskipped++;
    _modec->qii[bi]=best_qii;
  }
  _modec->ssd=ssd;
  _modec->rate=rate;
  _modec->overhead=OC_MAXI(overhead,0);
}

static void oc_analyze_mb_mode_chroma(oc_enc_ctx *_enc,
 oc_mode_choice *_modec,const oc_fr_state *_fr,const oc_qii_state *_qs,
 const unsigned _frag_satd[12],const unsigned _skip_ssd[12],int _qti){
  unsigned ssd;
  unsigned rate;
  unsigned satd;
  unsigned best_ssd;
  unsigned best_rate;
  int      best_qii;
  unsigned cur_cost;
  unsigned cur_ssd;
  unsigned cur_rate;
  int      lambda;
  int      nblocks;
  int      nqis;
  int      pli;
  int      bi;
  int      qii;
  lambda=_enc->lambda;
  nqis=_enc->state.nqis;
  ssd=_modec->ssd;
  rate=_modec->rate;
  /*Because (except in 4:4:4 mode) we aren't considering chroma blocks in coded
     order, we assume a constant overhead for coded block and qii flags.*/
  nblocks=OC_MB_MAP_NIDXS[_enc->state.info.pixel_fmt];
  nblocks=(nblocks-4>>1)+4;
  bi=4;
  for(pli=1;pli<3;pli++){
    for(;bi<nblocks;bi++){
      unsigned best_cost;
      satd=_frag_satd[bi];
      best_rate=oc_dct_cost2(&best_ssd,_enc->state.qis[0],pli,_qti,satd)
       +OC_CHROMA_QII_RATE;
      best_cost=OC_MODE_RD_COST(ssd+best_ssd,rate+best_rate,lambda);
      best_qii=0;
      for(qii=1;qii<nqis;qii++){
        cur_rate=oc_dct_cost2(&cur_ssd,_enc->state.qis[qii],0,_qti,satd)
         +OC_CHROMA_QII_RATE;
        cur_cost=OC_MODE_RD_COST(ssd+cur_ssd,rate+cur_rate,lambda);
        if(cur_cost<best_cost){
          best_cost=cur_cost;
          best_ssd=cur_ssd;
          best_rate=cur_rate;
          best_qii=qii;
        }
      }
      if(_skip_ssd[bi]<UINT_MAX){
        cur_ssd=_skip_ssd[bi]<<OC_BIT_SCALE;
        cur_cost=OC_MODE_RD_COST(ssd+cur_ssd,rate,lambda);
        if(cur_cost<=best_cost){
          best_ssd=cur_ssd;
          best_rate=0;
          best_qii+=4;
        }
      }
      rate+=best_rate;
      ssd+=best_ssd;
      _modec->qii[bi]=best_qii;
    }
    nblocks=(nblocks-4<<1)+4;
  }
  _modec->ssd=ssd;
  _modec->rate=rate;
}

static void oc_skip_cost(oc_enc_ctx *_enc,oc_enc_pipeline_state *_pipe,
 unsigned _mbi,unsigned _ssd[12]){
  OC_ALIGN16(ogg_int16_t  buffer[64]);
  const unsigned char    *src;
  const unsigned char    *ref;
  int                     ystride;
  const oc_fragment      *frags;
  const ptrdiff_t        *frag_buf_offs;
  const ptrdiff_t        *sb_map;
  const oc_mb_map_plane  *mb_map;
  const unsigned char    *map_idxs;
  int                     map_nidxs;
  ogg_int64_t             mask;<--- Shadowed declaration
  unsigned                uncoded_ssd;
  int                     uncoded_dc;
  unsigned                dc_dequant;
  int                     dc_flag;
  int                     mapii;
  int                     mapi;
  int                     pli;
  int                     bi;
  ptrdiff_t               fragi;
  ptrdiff_t               frag_offs;
  int                     borderi;
  int                     pi;
  src=_enc->state.ref_frame_data[OC_FRAME_IO];
  ref=_enc->state.ref_frame_data[_enc->state.ref_frame_idx[OC_FRAME_PREV]];
  ystride=_enc->state.ref_ystride[0];
  frags=_enc->state.frags;
  frag_buf_offs=_enc->state.frag_buf_offs;
  sb_map=_enc->state.sb_maps[_mbi>>2][_mbi&3];
  dc_dequant=_enc->state.dequant_tables[_enc->state.qis[0]][0][1][0];
  for(bi=0;bi<4;bi++){
    fragi=sb_map[bi];
    frag_offs=frag_buf_offs[fragi];
    oc_enc_frag_sub(_enc,buffer,src+frag_offs,ref+frag_offs,ystride);
    borderi=frags[fragi].borderi;
    uncoded_ssd=uncoded_dc=0;
    if(borderi<0){
      for(pi=0;pi<64;pi++){
        uncoded_ssd+=buffer[pi]*buffer[pi];
        uncoded_dc+=buffer[pi];
      }
    }
    else{
      ogg_int64_t mask;<--- Shadow variable
      mask=_enc->state.borders[borderi].mask;
      for(pi=0;pi<64;pi++,mask>>=1)if(mask&1){
        uncoded_ssd+=buffer[pi]*buffer[pi];
        uncoded_dc+=buffer[pi];
      }
    }
    /*Scale to match DCT domain.*/
    uncoded_ssd<<=4;
    /*We actually only want the AC contribution to the SSD.*/
    uncoded_ssd-=uncoded_dc*uncoded_dc>>2;
    /*DC is a special case; if there's more than a full-quantizer improvement
       in the effective DC component, always force-code the block.*/
    dc_flag=abs(uncoded_dc)>dc_dequant<<1;
    uncoded_ssd|=-dc_flag;
    _pipe->skip_ssd[0][fragi-_pipe->froffset[0]]=_ssd[bi]=uncoded_ssd;
  }
  mb_map=(const oc_mb_map_plane *)_enc->state.mb_maps[_mbi];
  map_nidxs=OC_MB_MAP_NIDXS[_enc->state.info.pixel_fmt];
  map_idxs=OC_MB_MAP_IDXS[_enc->state.info.pixel_fmt];
  map_nidxs=(map_nidxs-4>>1)+4;
  mapii=4;
  for(pli=1;pli<3;pli++){
    ystride=_enc->state.ref_ystride[pli];
    dc_dequant=_enc->state.dequant_tables[_enc->state.qis[0]][pli][1][0];
    for(;mapii<map_nidxs;mapii++){
      mapi=map_idxs[mapii];
      bi=mapi&3;
      fragi=mb_map[pli][bi];
      frag_offs=frag_buf_offs[fragi];
      oc_enc_frag_sub(_enc,buffer,src+frag_offs,ref+frag_offs,ystride);
      borderi=frags[fragi].borderi;
      uncoded_ssd=uncoded_dc=0;
      if(borderi<0){
        for(pi=0;pi<64;pi++){
          uncoded_ssd+=buffer[pi]*buffer[pi];
          uncoded_dc+=buffer[pi];
        }
      }
      else{
        mask=_enc->state.borders[borderi].mask;
        for(pi=0;pi<64;pi++,mask>>=1)if(mask&1){
          uncoded_ssd+=buffer[pi]*buffer[pi];
          uncoded_dc+=buffer[pi];
        }
      }
      /*Scale to match DCT domain.*/
      uncoded_ssd<<=4;
      /*We actually only want the AC contribution to the SSD.*/
      uncoded_ssd-=uncoded_dc*uncoded_dc>>2;
      /*DC is a special case; if there's more than a full-quantizer improvement
         in the effective DC component, always force-code the block.*/
      dc_flag=abs(uncoded_dc)>dc_dequant<<1;
      uncoded_ssd|=-dc_flag;
      _pipe->skip_ssd[pli][fragi-_pipe->froffset[pli]]=_ssd[mapii]=uncoded_ssd;
    }
    map_nidxs=(map_nidxs-4<<1)+4;
  }
}

static void oc_mb_intra_satd(oc_enc_ctx *_enc,unsigned _mbi,
 unsigned _frag_satd[12]){
  const unsigned char   *src;
  const ptrdiff_t       *frag_buf_offs;
  const ptrdiff_t       *sb_map;
  const oc_mb_map_plane *mb_map;
  const unsigned char   *map_idxs;
  int                    map_nidxs;
  int                    mapii;
  int                    mapi;
  int                    ystride;
  int                    pli;
  int                    bi;
  ptrdiff_t              fragi;
  ptrdiff_t              frag_offs;
  frag_buf_offs=_enc->state.frag_buf_offs;
  sb_map=_enc->state.sb_maps[_mbi>>2][_mbi&3];
  src=_enc->state.ref_frame_data[OC_FRAME_IO];
  ystride=_enc->state.ref_ystride[0];
  for(bi=0;bi<4;bi++){
    fragi=sb_map[bi];
    frag_offs=frag_buf_offs[fragi];
    _frag_satd[bi]=oc_enc_frag_intra_satd(_enc,src+frag_offs,ystride);
  }
  mb_map=(const oc_mb_map_plane *)_enc->state.mb_maps[_mbi];
  map_idxs=OC_MB_MAP_IDXS[_enc->state.info.pixel_fmt];
  map_nidxs=OC_MB_MAP_NIDXS[_enc->state.info.pixel_fmt];
  /*Note: This assumes ref_ystride[1]==ref_ystride[2].*/
  ystride=_enc->state.ref_ystride[1];
  for(mapii=4;mapii<map_nidxs;mapii++){
    mapi=map_idxs[mapii];
    pli=mapi>>2;
    bi=mapi&3;
    fragi=mb_map[pli][bi];
    frag_offs=frag_buf_offs[fragi];
    _frag_satd[mapii]=oc_enc_frag_intra_satd(_enc,src+frag_offs,ystride);
  }
}

static void oc_cost_intra(oc_enc_ctx *_enc,oc_mode_choice *_modec,
 unsigned _mbi,const oc_fr_state *_fr,const oc_qii_state *_qs,
 const unsigned _frag_satd[12],const unsigned _skip_ssd[12]){
  oc_analyze_mb_mode_luma(_enc,_modec,_fr,_qs,_frag_satd,_skip_ssd,0);
  oc_analyze_mb_mode_chroma(_enc,_modec,_fr,_qs,_frag_satd,_skip_ssd,0);
  _modec->overhead+=
   oc_mode_scheme_chooser_cost(&_enc->chooser,OC_MODE_INTRA)<<OC_BIT_SCALE;
  oc_mode_set_cost(_modec,_enc->lambda);
}

static void oc_cost_inter(oc_enc_ctx *_enc,oc_mode_choice *_modec,
 unsigned _mbi,int _mb_mode,const signed char *_mv,
 const oc_fr_state *_fr,const oc_qii_state *_qs,const unsigned _skip_ssd[12]){
  unsigned               frag_satd[12];
  const unsigned char   *src;
  const unsigned char   *ref;
  int                    ystride;
  const ptrdiff_t       *frag_buf_offs;
  const ptrdiff_t       *sb_map;
  const oc_mb_map_plane *mb_map;
  const unsigned char   *map_idxs;
  int                    map_nidxs;
  int                    mapii;
  int                    mapi;
  int                    mv_offs[2];
  int                    dx;
  int                    dy;
  int                    pli;
  int                    bi;
  ptrdiff_t              fragi;
  ptrdiff_t              frag_offs;
  src=_enc->state.ref_frame_data[OC_FRAME_IO];
  ref=_enc->state.ref_frame_data[
   _enc->state.ref_frame_idx[OC_FRAME_FOR_MODE(_mb_mode)]];
  ystride=_enc->state.ref_ystride[0];
  frag_buf_offs=_enc->state.frag_buf_offs;
  sb_map=_enc->state.sb_maps[_mbi>>2][_mbi&3];
  dx=_mv[0];
  dy=_mv[1];
  _modec->rate=_modec->ssd=0;
  if(oc_state_get_mv_offsets(&_enc->state,mv_offs,0,dx,dy)>1){
    for(bi=0;bi<4;bi++){
      fragi=sb_map[bi];
      frag_offs=frag_buf_offs[fragi];
      frag_satd[bi]=oc_enc_frag_satd2_thresh(_enc,src+frag_offs,
       ref+frag_offs+mv_offs[0],ref+frag_offs+mv_offs[1],ystride,UINT_MAX);
    }
  }
  else{
    for(bi=0;bi<4;bi++){
      fragi=sb_map[bi];
      frag_offs=frag_buf_offs[fragi];
      frag_satd[bi]=oc_enc_frag_satd_thresh(_enc,src+frag_offs,
       ref+frag_offs+mv_offs[0],ystride,UINT_MAX);
    }
  }
  mb_map=(const oc_mb_map_plane *)_enc->state.mb_maps[_mbi];
  map_idxs=OC_MB_MAP_IDXS[_enc->state.info.pixel_fmt];
  map_nidxs=OC_MB_MAP_NIDXS[_enc->state.info.pixel_fmt];
  /*Note: This assumes ref_ystride[1]==ref_ystride[2].*/
  ystride=_enc->state.ref_ystride[1];
  if(oc_state_get_mv_offsets(&_enc->state,mv_offs,1,dx,dy)>1){
    for(mapii=4;mapii<map_nidxs;mapii++){
      mapi=map_idxs[mapii];
      pli=mapi>>2;
      bi=mapi&3;
      fragi=mb_map[pli][bi];
      frag_offs=frag_buf_offs[fragi];
      frag_satd[mapii]=oc_enc_frag_satd2_thresh(_enc,src+frag_offs,
       ref+frag_offs+mv_offs[0],ref+frag_offs+mv_offs[1],ystride,UINT_MAX);
    }
  }
  else{
    for(mapii=4;mapii<map_nidxs;mapii++){
      mapi=map_idxs[mapii];
      pli=mapi>>2;
      bi=mapi&3;
      fragi=mb_map[pli][bi];
      frag_offs=frag_buf_offs[fragi];
      frag_satd[mapii]=oc_enc_frag_satd_thresh(_enc,src+frag_offs,
       ref+frag_offs+mv_offs[0],ystride,UINT_MAX);
    }
  }
  oc_analyze_mb_mode_luma(_enc,_modec,_fr,_qs,frag_satd,_skip_ssd,1);
  oc_analyze_mb_mode_chroma(_enc,_modec,_fr,_qs,frag_satd,_skip_ssd,1);
  _modec->overhead+=
   oc_mode_scheme_chooser_cost(&_enc->chooser,_mb_mode)<<OC_BIT_SCALE;
  oc_mode_set_cost(_modec,_enc->lambda);
}

static void oc_cost_inter_nomv(oc_enc_ctx *_enc,oc_mode_choice *_modec,
 unsigned _mbi,int _mb_mode,const oc_fr_state *_fr,const oc_qii_state *_qs,
 const unsigned _skip_ssd[12]){
  static const oc_mv OC_MV_ZERO;
  oc_cost_inter(_enc,_modec,_mbi,_mb_mode,OC_MV_ZERO,_fr,_qs,_skip_ssd);
}

static int oc_cost_inter1mv(oc_enc_ctx *_enc,oc_mode_choice *_modec,
 unsigned _mbi,int _mb_mode,const signed char *_mv,
 const oc_fr_state *_fr,const oc_qii_state *_qs,const unsigned _skip_ssd[12]){
  int bits0;
  oc_cost_inter(_enc,_modec,_mbi,_mb_mode,_mv,_fr,_qs,_skip_ssd);
  bits0=OC_MV_BITS[0][_mv[0]+31]+OC_MV_BITS[0][_mv[1]+31];
  _modec->overhead+=OC_MINI(_enc->mv_bits[0]+bits0,_enc->mv_bits[1]+12)
   -OC_MINI(_enc->mv_bits[0],_enc->mv_bits[1])<<OC_BIT_SCALE;
  oc_mode_set_cost(_modec,_enc->lambda);
  return bits0;
}

/*A mapping from oc_mb_map (raster) ordering to oc_sb_map (Hilbert) ordering.*/
static const unsigned char OC_MB_PHASE[4][4]={
  {0,1,3,2},{0,3,1,2},{0,3,1,2},{2,3,1,0}
};

static void oc_cost_inter4mv(oc_enc_ctx *_enc,oc_mode_choice *_modec,
 unsigned _mbi,oc_mv _mv[4],const oc_fr_state *_fr,const oc_qii_state *_qs,
 const unsigned _skip_ssd[12]){
  unsigned               frag_satd[12];
  oc_mv                  lbmvs[4];
  oc_mv                  cbmvs[4];
  const unsigned char   *src;
  const unsigned char   *ref;
  int                    ystride;
  const ptrdiff_t       *frag_buf_offs;
  oc_mv                 *frag_mvs;
  const oc_mb_map_plane *mb_map;
  const unsigned char   *map_idxs;
  int                    map_nidxs;
  int                    nqis;
  int                    mapii;
  int                    mapi;
  int                    mv_offs[2];
  int                    dx;
  int                    dy;
  int                    pli;
  int                    bi;
  ptrdiff_t              fragi;
  ptrdiff_t              frag_offs;
  int                    bits0;
  int                    bits1;
  unsigned               satd;
  src=_enc->state.ref_frame_data[OC_FRAME_IO];
  ref=_enc->state.ref_frame_data[_enc->state.ref_frame_idx[OC_FRAME_PREV]];
  ystride=_enc->state.ref_ystride[0];
  frag_buf_offs=_enc->state.frag_buf_offs;
  frag_mvs=_enc->state.frag_mvs;
  mb_map=(const oc_mb_map_plane *)_enc->state.mb_maps[_mbi];
  _modec->rate=_modec->ssd=0;
  for(bi=0;bi<4;bi++){
    fragi=mb_map[0][bi];
    dx=_mv[bi][0];
    dy=_mv[bi][1];
    /*Save the block MVs as the current ones while we're here; we'll replace
       them if we don't ultimately choose 4MV mode.*/
    frag_mvs[fragi][0]=(signed char)dx;
    frag_mvs[fragi][1]=(signed char)dy;
    frag_offs=frag_buf_offs[fragi];
    if(oc_state_get_mv_offsets(&_enc->state,mv_offs,0,dx,dy)>1){
      satd=oc_enc_frag_satd2_thresh(_enc,src+frag_offs,
       ref+frag_offs+mv_offs[0],ref+frag_offs+mv_offs[1],ystride,UINT_MAX);
    }
    else{
      satd=oc_enc_frag_satd_thresh(_enc,src+frag_offs,
       ref+frag_offs+mv_offs[0],ystride,UINT_MAX);
    }
    frag_satd[OC_MB_PHASE[_mbi&3][bi]]=satd;
  }
  oc_analyze_mb_mode_luma(_enc,_modec,_fr,_qs,frag_satd,
   _enc->vp3_compatible?OC_NOSKIP:_skip_ssd,1);
  /*Figure out which blocks are being skipped and give them (0,0) MVs.*/
  bits0=0;
  bits1=0;
  nqis=_enc->state.nqis;
  for(bi=0;bi<4;bi++){
    if(_modec->qii[OC_MB_PHASE[_mbi&3][bi]]>=nqis){
      memset(lbmvs+bi,0,sizeof(*lbmvs));
    }
    else{
      memcpy(lbmvs+bi,_mv+bi,sizeof(*lbmvs));
      bits0+=OC_MV_BITS[0][_mv[bi][0]+31]+OC_MV_BITS[0][_mv[bi][1]+31];
      bits1+=12;
    }
  }
  (*OC_SET_CHROMA_MVS_TABLE[_enc->state.info.pixel_fmt])(cbmvs,
   (const oc_mv *)lbmvs);
  map_idxs=OC_MB_MAP_IDXS[_enc->state.info.pixel_fmt];
  map_nidxs=OC_MB_MAP_NIDXS[_enc->state.info.pixel_fmt];
  /*Note: This assumes ref_ystride[1]==ref_ystride[2].*/
  ystride=_enc->state.ref_ystride[1];
  for(mapii=4;mapii<map_nidxs;mapii++){
    mapi=map_idxs[mapii];
    pli=mapi>>2;
    bi=mapi&3;
    fragi=mb_map[pli][bi];
    dx=cbmvs[bi][0];
    dy=cbmvs[bi][1];
    frag_offs=frag_buf_offs[fragi];
    /*TODO: We could save half these calls by re-using the results for the Cb
       and Cr planes; is it worth it?*/
    if(oc_state_get_mv_offsets(&_enc->state,mv_offs,pli,dx,dy)>1){
      satd=oc_enc_frag_satd2_thresh(_enc,src+frag_offs,
       ref+frag_offs+mv_offs[0],ref+frag_offs+mv_offs[1],ystride,UINT_MAX);
    }
    else{
      satd=oc_enc_frag_satd_thresh(_enc,src+frag_offs,
       ref+frag_offs+mv_offs[0],ystride,UINT_MAX);
    }
    frag_satd[mapii]=satd;
  }
  oc_analyze_mb_mode_chroma(_enc,_modec,_fr,_qs,frag_satd,_skip_ssd,1);
  _modec->overhead+=
   oc_mode_scheme_chooser_cost(&_enc->chooser,OC_MODE_INTER_MV_FOUR)
   +OC_MINI(_enc->mv_bits[0]+bits0,_enc->mv_bits[1]+bits1)
   -OC_MINI(_enc->mv_bits[0],_enc->mv_bits[1])<<OC_BIT_SCALE;
  oc_mode_set_cost(_modec,_enc->lambda);
}

int oc_enc_analyze_inter(oc_enc_ctx *_enc,int _allow_keyframe,int _recode){
  oc_set_chroma_mvs_func  set_chroma_mvs;
  oc_enc_pipeline_state   pipe;
  oc_qii_state            intra_luma_qs;
  oc_mv                   last_mv;
  oc_mv                   prior_mv;
  ogg_int64_t             interbits;
  ogg_int64_t             intrabits;
  const unsigned char    *map_idxs;
  int                     nmap_idxs;
  unsigned               *coded_mbis;
  unsigned               *uncoded_mbis;
  size_t                  ncoded_mbis;
  size_t                  nuncoded_mbis;
  oc_sb_flags            *sb_flags;
  signed char            *mb_modes;
  const oc_sb_map        *sb_maps;
  const oc_mb_map        *mb_maps;
  oc_mb_enc_info         *embs;
  oc_fragment            *frags;
  oc_mv                  *frag_mvs;
  int                     qi;
  unsigned                stripe_sby;
  unsigned                mcu_nvsbs;
  int                     notstart;
  int                     notdone;
  int                     vdec;
  unsigned                sbi;
  unsigned                sbi_end;
  int                     refi;
  int                     pli;
  set_chroma_mvs=OC_SET_CHROMA_MVS_TABLE[_enc->state.info.pixel_fmt];
  _enc->state.frame_type=OC_INTER_FRAME;
  oc_mode_scheme_chooser_reset(&_enc->chooser);
  oc_enc_tokenize_start(_enc);
  oc_enc_pipeline_init(_enc,&pipe);
  if(_allow_keyframe)oc_qii_state_init(&intra_luma_qs);
  _enc->mv_bits[0]=_enc->mv_bits[1]=0;
  interbits=intrabits=0;
  last_mv[0]=last_mv[1]=prior_mv[0]=prior_mv[1]=0;
  /*Choose MVs and MB modes and quantize and code luma.
    Must be done in Hilbert order.*/
  map_idxs=OC_MB_MAP_IDXS[_enc->state.info.pixel_fmt];
  nmap_idxs=OC_MB_MAP_NIDXS[_enc->state.info.pixel_fmt];
  qi=_enc->state.qis[0];
  coded_mbis=_enc->coded_mbis;
  uncoded_mbis=coded_mbis+_enc->state.nmbs;
  ncoded_mbis=0;
  nuncoded_mbis=0;
  _enc->state.ncoded_fragis[0]=0;
  _enc->state.ncoded_fragis[1]=0;
  _enc->state.ncoded_fragis[2]=0;
  sb_flags=_enc->state.sb_flags;
  mb_modes=_enc->state.mb_modes;
  sb_maps=(const oc_sb_map *)_enc->state.sb_maps;
  mb_maps=(const oc_mb_map *)_enc->state.mb_maps;
  embs=_enc->mb_info;
  frags=_enc->state.frags;
  frag_mvs=_enc->state.frag_mvs;
  vdec=!(_enc->state.info.pixel_fmt&2);
  notstart=0;
  notdone=1;
  mcu_nvsbs=_enc->mcu_nvsbs;
  for(stripe_sby=0;notdone;stripe_sby+=mcu_nvsbs){
    notdone=oc_enc_pipeline_set_stripe(_enc,&pipe,stripe_sby);
    sbi_end=pipe.sbi_end[0];
    for(sbi=pipe.sbi0[0];sbi<sbi_end;sbi++){
      int quadi;
      /*Mode addressing is through Y plane, always 4 MB per SB.*/
      for(quadi=0;quadi<4;quadi++)if(sb_flags[sbi].quad_valid&1<<quadi){
        oc_mode_choice modes[8];
        unsigned       skip_ssd[12];
        unsigned       intra_satd[12];
        int            mb_mv_bits_0;
        int            mb_gmv_bits_0;
        int            inter_mv_pref;
        int            mb_mode;
        int            dx;
        int            dy;
        unsigned       mbi;
        int            mapii;
        int            mapi;
        int            bi;
        ptrdiff_t      fragi;
        mbi=sbi<<2|quadi;
        /*Motion estimation:
          We always do a basic 1MV search for all macroblocks, coded or not,
           keyframe or not.*/
        if(!_recode&&_enc->sp_level<OC_SP_LEVEL_NOMC)oc_mcenc_search(_enc,mbi);
        dx=dy=0;
        /*Find the block choice with the lowest estimated coding cost.
          If a Cb or Cr block is coded but no Y' block from a macro block then
           the mode MUST be OC_MODE_INTER_NOMV.
          This is the default state to which the mode data structure is
           initialised in encoder and decoder at the start of each frame.*/
        /*Block coding cost is estimated from correlated SATD metrics.*/
        /*At this point, all blocks that are in frame are still marked coded.*/
        if(!_recode){
          memcpy(embs[mbi].unref_mv,
           embs[mbi].analysis_mv[0],sizeof(embs[mbi].unref_mv));
          embs[mbi].refined=0;
        }
        oc_mb_intra_satd(_enc,mbi,intra_satd);
        /*Estimate the cost of coding this MB in a keyframe.*/
        if(_allow_keyframe){
          oc_cost_intra(_enc,modes+OC_MODE_INTRA,mbi,
           pipe.fr+0,&intra_luma_qs,intra_satd,OC_NOSKIP);
          intrabits+=modes[OC_MODE_INTRA].rate;
          for(bi=0;bi<4;bi++){
            oc_qii_state_advance(&intra_luma_qs,&intra_luma_qs,
             modes[OC_MODE_INTRA].qii[bi]);
          }
        }
        /*Estimate the cost in a delta frame for various modes.*/
        oc_skip_cost(_enc,&pipe,mbi,skip_ssd);
        oc_cost_inter_nomv(_enc,modes+OC_MODE_INTER_NOMV,mbi,
         OC_MODE_INTER_NOMV,pipe.fr+0,pipe.qs+0,skip_ssd);
        if(_enc->sp_level<OC_SP_LEVEL_NOMC){
          oc_cost_intra(_enc,modes+OC_MODE_INTRA,mbi,
           pipe.fr+0,pipe.qs+0,intra_satd,skip_ssd);
          mb_mv_bits_0=oc_cost_inter1mv(_enc,modes+OC_MODE_INTER_MV,mbi,<--- mb_mv_bits_0 is assigned
           OC_MODE_INTER_MV,embs[mbi].unref_mv[OC_FRAME_PREV],
           pipe.fr+0,pipe.qs+0,skip_ssd);
          oc_cost_inter(_enc,modes+OC_MODE_INTER_MV_LAST,mbi,
           OC_MODE_INTER_MV_LAST,last_mv,pipe.fr+0,pipe.qs+0,skip_ssd);
          oc_cost_inter(_enc,modes+OC_MODE_INTER_MV_LAST2,mbi,
           OC_MODE_INTER_MV_LAST2,prior_mv,pipe.fr+0,pipe.qs+0,skip_ssd);
          oc_cost_inter4mv(_enc,modes+OC_MODE_INTER_MV_FOUR,mbi,
           embs[mbi].block_mv,pipe.fr+0,pipe.qs+0,skip_ssd);
          oc_cost_inter_nomv(_enc,modes+OC_MODE_GOLDEN_NOMV,mbi,
           OC_MODE_GOLDEN_NOMV,pipe.fr+0,pipe.qs+0,skip_ssd);
          mb_gmv_bits_0=oc_cost_inter1mv(_enc,modes+OC_MODE_GOLDEN_MV,mbi,
           OC_MODE_GOLDEN_MV,embs[mbi].unref_mv[OC_FRAME_GOLD],
           pipe.fr+0,pipe.qs+0,skip_ssd);
          /*The explicit MV modes (2,6,7) have not yet gone through halfpel
             refinement.
            We choose the explicit MV mode that's already furthest ahead on
             R-D cost and refine only that one.
            We have to be careful to remember which ones we've refined so that
             we don't refine it again if we re-encode this frame.*/
          inter_mv_pref=_enc->lambda*3;
          if(modes[OC_MODE_INTER_MV_FOUR].cost<modes[OC_MODE_INTER_MV].cost&&
           modes[OC_MODE_INTER_MV_FOUR].cost<modes[OC_MODE_GOLDEN_MV].cost){
            if(!(embs[mbi].refined&0x80)){
              oc_mcenc_refine4mv(_enc,mbi);
              embs[mbi].refined|=0x80;
            }
            oc_cost_inter4mv(_enc,modes+OC_MODE_INTER_MV_FOUR,mbi,
             embs[mbi].ref_mv,pipe.fr+0,pipe.qs+0,skip_ssd);
          }
          else if(modes[OC_MODE_GOLDEN_MV].cost+inter_mv_pref<
           modes[OC_MODE_INTER_MV].cost){
            if(!(embs[mbi].refined&0x40)){
              oc_mcenc_refine1mv(_enc,mbi,OC_FRAME_GOLD);
              embs[mbi].refined|=0x40;
            }
            mb_gmv_bits_0=oc_cost_inter1mv(_enc,modes+OC_MODE_GOLDEN_MV,mbi,
             OC_MODE_GOLDEN_MV,embs[mbi].analysis_mv[0][OC_FRAME_GOLD],
             pipe.fr+0,pipe.qs+0,skip_ssd);
          }
          if(!(embs[mbi].refined&0x04)){
            oc_mcenc_refine1mv(_enc,mbi,OC_FRAME_PREV);
            embs[mbi].refined|=0x04;
          }
          mb_mv_bits_0=oc_cost_inter1mv(_enc,modes+OC_MODE_INTER_MV,mbi,<--- mb_mv_bits_0 is overwritten
           OC_MODE_INTER_MV,embs[mbi].analysis_mv[0][OC_FRAME_PREV],
           pipe.fr+0,pipe.qs+0,skip_ssd);
          /*Finally, pick the mode with the cheapest estimated R-D cost.*/
          mb_mode=OC_MODE_INTER_NOMV;
          if(modes[OC_MODE_INTRA].cost<modes[OC_MODE_INTER_NOMV].cost){
            mb_mode=OC_MODE_INTRA;
          }
          if(modes[OC_MODE_INTER_MV_LAST].cost<modes[mb_mode].cost){
            mb_mode=OC_MODE_INTER_MV_LAST;
          }
          if(modes[OC_MODE_INTER_MV_LAST2].cost<modes[mb_mode].cost){
            mb_mode=OC_MODE_INTER_MV_LAST2;
          }
          if(modes[OC_MODE_GOLDEN_NOMV].cost<modes[mb_mode].cost){
            mb_mode=OC_MODE_GOLDEN_NOMV;
          }
          if(modes[OC_MODE_GOLDEN_MV].cost<modes[mb_mode].cost){
            mb_mode=OC_MODE_GOLDEN_MV;
          }
          if(modes[OC_MODE_INTER_MV_FOUR].cost<modes[mb_mode].cost){
            mb_mode=OC_MODE_INTER_MV_FOUR;
          }
          /*We prefer OC_MODE_INTER_MV, but not over LAST and LAST2.*/
          if(mb_mode==OC_MODE_INTER_MV_LAST||mb_mode==OC_MODE_INTER_MV_LAST2){
            inter_mv_pref=0;
          }
          if(modes[OC_MODE_INTER_MV].cost<modes[mb_mode].cost+inter_mv_pref){
            mb_mode=OC_MODE_INTER_MV;
          }
        }
        else{
          oc_cost_inter_nomv(_enc,modes+OC_MODE_GOLDEN_NOMV,mbi,
           OC_MODE_GOLDEN_NOMV,pipe.fr+0,pipe.qs+0,skip_ssd);
          mb_mode=OC_MODE_INTER_NOMV;
          if(modes[OC_MODE_INTRA].cost<modes[OC_MODE_INTER_NOMV].cost){
            mb_mode=OC_MODE_INTRA;
          }
          if(modes[OC_MODE_GOLDEN_NOMV].cost<modes[mb_mode].cost){
            mb_mode=OC_MODE_GOLDEN_NOMV;
          }
          mb_mv_bits_0=mb_gmv_bits_0=0;
        }
        mb_modes[mbi]=mb_mode;
        /*Propagate the MVs to the luma blocks.*/
        if(mb_mode!=OC_MODE_INTER_MV_FOUR){
          switch(mb_mode){
            case OC_MODE_INTER_MV:{
              dx=embs[mbi].analysis_mv[0][OC_FRAME_PREV][0];
              dy=embs[mbi].analysis_mv[0][OC_FRAME_PREV][1];
            }break;
            case OC_MODE_INTER_MV_LAST:{
              dx=last_mv[0];
              dy=last_mv[1];
            }break;
            case OC_MODE_INTER_MV_LAST2:{
              dx=prior_mv[0];
              dy=prior_mv[1];
            }break;
            case OC_MODE_GOLDEN_MV:{
              dx=embs[mbi].analysis_mv[0][OC_FRAME_GOLD][0];
              dy=embs[mbi].analysis_mv[0][OC_FRAME_GOLD][1];
            }break;
          }
          for(bi=0;bi<4;bi++){
            fragi=mb_maps[mbi][0][bi];
            frag_mvs[fragi][0]=(signed char)dx;
            frag_mvs[fragi][1]=(signed char)dy;
          }
        }
        for(bi=0;bi<4;bi++){
          fragi=sb_maps[mbi>>2][mbi&3][bi];
          frags[fragi].qii=modes[mb_mode].qii[bi];
        }
        if(oc_enc_mb_transform_quantize_luma(_enc,&pipe,mbi,
         modes[mb_mode].overhead>>OC_BIT_SCALE)>0){
          int orig_mb_mode;
          orig_mb_mode=mb_mode;
          mb_mode=mb_modes[mbi];
          switch(mb_mode){
            case OC_MODE_INTER_MV:{
              memcpy(prior_mv,last_mv,sizeof(prior_mv));
              /*If we're backing out from 4MV, find the MV we're actually
                 using.*/
              if(orig_mb_mode==OC_MODE_INTER_MV_FOUR){
                for(bi=0;;bi++){
                  fragi=mb_maps[mbi][0][bi];
                  if(frags[fragi].coded){
                    memcpy(last_mv,frag_mvs[fragi],sizeof(last_mv));
                    dx=frag_mvs[fragi][0];
                    dy=frag_mvs[fragi][1];
                    break;
                  }
                }
                mb_mv_bits_0=OC_MV_BITS[0][dx+31]+OC_MV_BITS[0][dy+31];
              }
              /*Otherwise we used the original analysis MV.*/
              else{
                memcpy(last_mv,
                 embs[mbi].analysis_mv[0][OC_FRAME_PREV],sizeof(last_mv));
              }
              _enc->mv_bits[0]+=mb_mv_bits_0;
              _enc->mv_bits[1]+=12;
            }break;
            case OC_MODE_INTER_MV_LAST2:{
              oc_mv tmp_mv;
              memcpy(tmp_mv,prior_mv,sizeof(tmp_mv));
              memcpy(prior_mv,last_mv,sizeof(prior_mv));
              memcpy(last_mv,tmp_mv,sizeof(last_mv));
            }break;
            case OC_MODE_GOLDEN_MV:{
              _enc->mv_bits[0]+=mb_gmv_bits_0;
              _enc->mv_bits[1]+=12;
            }break;
            case OC_MODE_INTER_MV_FOUR:{
              oc_mv lbmvs[4];
              oc_mv cbmvs[4];
              memcpy(prior_mv,last_mv,sizeof(prior_mv));
              for(bi=0;bi<4;bi++){
                fragi=mb_maps[mbi][0][bi];
                if(frags[fragi].coded){
                  memcpy(last_mv,frag_mvs[fragi],sizeof(last_mv));
                  memcpy(lbmvs[bi],frag_mvs[fragi],sizeof(lbmvs[bi]));
                  _enc->mv_bits[0]+=OC_MV_BITS[0][frag_mvs[fragi][0]+31]
                   +OC_MV_BITS[0][frag_mvs[fragi][1]+31];
                  _enc->mv_bits[1]+=12;
                }
                /*Replace the block MVs for not-coded blocks with (0,0).*/
                else memset(lbmvs[bi],0,sizeof(lbmvs[bi]));
              }
              (*set_chroma_mvs)(cbmvs,(const oc_mv *)lbmvs);
              for(mapii=4;mapii<nmap_idxs;mapii++){
                mapi=map_idxs[mapii];
                pli=mapi>>2;
                bi=mapi&3;
                fragi=mb_maps[mbi][pli][bi];
                frags[fragi].mb_mode=mb_mode;
                frags[fragi].qii=modes[OC_MODE_INTER_MV_FOUR].qii[mapii];
                memcpy(frag_mvs[fragi],cbmvs[bi],sizeof(frag_mvs[fragi]));
              }
            }break;
          }
          coded_mbis[ncoded_mbis++]=mbi;
          oc_mode_scheme_chooser_update(&_enc->chooser,mb_mode);
          interbits+=modes[mb_mode].rate+modes[mb_mode].overhead;
        }
        else{
          *(uncoded_mbis-++nuncoded_mbis)=mbi;
          mb_mode=OC_MODE_INTER_NOMV;
          dx=dy=0;
        }
        /*Propagate final MB mode and MVs to the chroma blocks.
          This has already been done for 4MV mode, since it requires individual
           block motion vectors.*/
        if(mb_mode!=OC_MODE_INTER_MV_FOUR){
          for(mapii=4;mapii<nmap_idxs;mapii++){
            mapi=map_idxs[mapii];
            pli=mapi>>2;
            bi=mapi&3;
            fragi=mb_maps[mbi][pli][bi];
            frags[fragi].mb_mode=mb_mode;
            /*If we switched from 4MV mode to INTER_MV mode, then the qii
               values won't have been chosen with the right MV, but it's
               probaby not worth re-estimating them.*/
            frags[fragi].qii=modes[mb_mode].qii[mapii];
            frag_mvs[fragi][0]=(signed char)dx;
            frag_mvs[fragi][1]=(signed char)dy;
          }
        }
      }
      oc_fr_state_flush_sb(pipe.fr+0);
      sb_flags[sbi].coded_fully=pipe.fr[0].sb_full;
      sb_flags[sbi].coded_partially=pipe.fr[0].sb_partial;
    }
    oc_enc_pipeline_finish_mcu_plane(_enc,&pipe,0,notstart,notdone);
    /*Code chroma planes.*/
    for(pli=1;pli<3;pli++){
      oc_enc_sb_transform_quantize_chroma(_enc,&pipe,
       pli,pipe.sbi0[pli],pipe.sbi_end[pli]);
      oc_enc_pipeline_finish_mcu_plane(_enc,&pipe,pli,notstart,notdone);
    }
    notstart=1;
  }
  /*Finish filling in the reference frame borders.*/
  refi=_enc->state.ref_frame_idx[OC_FRAME_SELF];
  for(pli=0;pli<3;pli++)oc_state_borders_fill_caps(&_enc->state,refi,pli);
  /*Finish adding flagging overhead costs to inter bit counts to determine if
     we should have coded a key frame instead.*/
  if(_allow_keyframe){
    if(interbits>intrabits)return 1;
    /*Technically the chroma plane counts are over-estimations, because they
       don't account for continuing runs from the luma planes, but the
       inaccuracy is small.*/
    for(pli=0;pli<3;pli++)interbits+=pipe.fr[pli].bits<<OC_BIT_SCALE;
    interbits+=OC_MINI(_enc->mv_bits[0],_enc->mv_bits[1])<<OC_BIT_SCALE;
    interbits+=
     _enc->chooser.scheme_bits[_enc->chooser.scheme_list[0]]<<OC_BIT_SCALE;
    if(interbits>intrabits)return 1;
  }
  _enc->ncoded_mbis=ncoded_mbis;
  /*Compact the coded fragment list.*/
  {
    ptrdiff_t ncoded_fragis;
    ncoded_fragis=_enc->state.ncoded_fragis[0];
    for(pli=1;pli<3;pli++){
      memmove(_enc->state.coded_fragis+ncoded_fragis,
       _enc->state.coded_fragis+_enc->state.fplanes[pli].froffset,
       _enc->state.ncoded_fragis[pli]*sizeof(*_enc->state.coded_fragis));
      ncoded_fragis+=_enc->state.ncoded_fragis[pli];
    }
    _enc->state.ntotal_coded_fragis=ncoded_fragis;
  }
  return 0;
}

#if defined(OC_COLLECT_METRICS)
# include <stdio.h>
# include <math.h>

/*TODO: It may be helpful (for block-level quantizers especially) to separate
   out the contributions from AC and DC into separate tables.*/

# define OC_ZWEIGHT   (0.25)

static void oc_mode_metrics_add(oc_mode_metrics *_metrics,
 double _w,int _satd,int _rate,double _rmse){
  double rate;
  /*Accumulate statistics without the scaling; this lets us change the scale
     factor yet still use old data.*/
  rate=ldexp(_rate,-OC_BIT_SCALE);
  if(_metrics->fragw>0){
    double dsatd;
    double drate;
    double drmse;
    double w;
    dsatd=_satd-_metrics->satd/_metrics->fragw;
    drate=rate-_metrics->rate/_metrics->fragw;
    drmse=_rmse-_metrics->rmse/_metrics->fragw;
    w=_metrics->fragw*_w/(_metrics->fragw+_w);
    _metrics->satd2+=dsatd*dsatd*w;
    _metrics->satdrate+=dsatd*drate*w;
    _metrics->rate2+=drate*drate*w;
    _metrics->satdrmse+=dsatd*drmse*w;
    _metrics->rmse2+=drmse*drmse*w;
  }
  _metrics->fragw+=_w;
  _metrics->satd+=_satd*_w;
  _metrics->rate+=rate*_w;
  _metrics->rmse+=_rmse*_w;
}

static void oc_mode_metrics_merge(oc_mode_metrics *_dst,
 const oc_mode_metrics *_src,int _n){
  int i;
  /*Find a non-empty set of metrics.*/
  for(i=0;i<_n&&_src[i].fragw<=0;i++);
  if(i>=_n){
    memset(_dst,0,sizeof(*_dst));
    return;
  }
  memcpy(_dst,_src+i,sizeof(*_dst));
  /*And iterate over the remaining non-empty sets of metrics.*/
  for(i++;i<_n;i++)if(_src[i].fragw>0){
    double wa;
    double wb;
    double dsatd;
    double drate;
    double drmse;
    double w;
    wa=_dst->fragw;
    wb=_src[i].fragw;
    dsatd=_src[i].satd/wb-_dst->satd/wa;
    drate=_src[i].rate/wb-_dst->rate/wa;
    drmse=_src[i].rmse/wb-_dst->rmse/wa;
    w=wa*wb/(wa+wb);
    _dst->fragw+=_src[i].fragw;
    _dst->satd+=_src[i].satd;
    _dst->rate+=_src[i].rate;
    _dst->rmse+=_src[i].rmse;
    _dst->satd2+=_src[i].satd2+dsatd*dsatd*w;
    _dst->satdrate+=_src[i].satdrate+dsatd*drate*w;
    _dst->rate2+=_src[i].rate2+drate*drate*w;
    _dst->satdrmse+=_src[i].satdrmse+dsatd*drmse*w;
    _dst->rmse2+=_src[i].rmse2+drmse*drmse*w;
  }
}

/*Compile collected SATD/rate/RMSE metrics into a form that's immediately
   useful for mode decision.*/
static void oc_enc_mode_metrics_update(oc_enc_ctx *_enc,int _qi){
  int pli;
  int qti;
  oc_restore_fpu(&_enc->state);
  /*Convert raw collected data into cleaned up sample points.*/
  for(pli=0;pli<3;pli++){
    for(qti=0;qti<2;qti++){
      double fragw;
      int    bin0;
      int    bin1;
      int    bin;
      fragw=0;
      bin0=bin1=0;
      for(bin=0;bin<OC_SAD_BINS;bin++){
        oc_mode_metrics metrics;
        OC_MODE_RD[_qi][pli][qti][bin].rate=0;
        OC_MODE_RD[_qi][pli][qti][bin].rmse=0;
        /*Find some points on either side of the current bin.*/
        while((bin1<bin+1||fragw<OC_ZWEIGHT)&&bin1<OC_SAD_BINS-1){
          fragw+=OC_MODE_METRICS[_qi][pli][qti][bin1++].fragw;
        }
        while(bin0+1<bin&&bin0+1<bin1&&
         fragw-OC_MODE_METRICS[_qi][pli][qti][bin0].fragw>=OC_ZWEIGHT){
          fragw-=OC_MODE_METRICS[_qi][pli][qti][bin0++].fragw;
        }
        /*Merge statistics and fit lines.*/
        oc_mode_metrics_merge(&metrics,
         OC_MODE_METRICS[_qi][pli][qti]+bin0,bin1-bin0);
        if(metrics.fragw>0&&metrics.satd2>0){
          double a;
          double b;
          double msatd;
          double mrate;
          double mrmse;
          double rate;
          double rmse;
          msatd=metrics.satd/metrics.fragw;
          mrate=metrics.rate/metrics.fragw;
          mrmse=metrics.rmse/metrics.fragw;
          /*Compute the points on these lines corresponding to the actual bin
             value.*/
          b=metrics.satdrate/metrics.satd2;
          a=mrate-b*msatd;
          rate=ldexp(a+b*(bin<<OC_SAD_SHIFT),OC_BIT_SCALE);
          OC_MODE_RD[_qi][pli][qti][bin].rate=
           (ogg_int16_t)OC_CLAMPI(-32768,(int)(rate+0.5),32767);
          b=metrics.satdrmse/metrics.satd2;
          a=mrmse-b*msatd;
          rmse=ldexp(a+b*(bin<<OC_SAD_SHIFT),OC_RMSE_SCALE);
          OC_MODE_RD[_qi][pli][qti][bin].rmse=
           (ogg_int16_t)OC_CLAMPI(-32768,(int)(rmse+0.5),32767);
        }
      }
    }
  }
}



/*The following token skipping code used to also be used in the decoder (and
   even at one point other places in the encoder).
  However, it was obsoleted by other optimizations, and is now only used here.
  It has been moved here to avoid generating the code when it's not needed.*/

/*Determines the number of blocks or coefficients to be skipped for a given
   token value.
  _token:      The token value to skip.
  _extra_bits: The extra bits attached to this token.
  Return: A positive value indicates that number of coefficients are to be
           skipped in the current block.
          Otherwise, the negative of the return value indicates that number of
           blocks are to be ended.*/
typedef ptrdiff_t (*oc_token_skip_func)(int _token,int _extra_bits);

/*Handles the simple end of block tokens.*/
static ptrdiff_t oc_token_skip_eob(int _token,int _extra_bits){
  int nblocks_adjust;
  nblocks_adjust=OC_UNIBBLE_TABLE32(0,1,2,3,7,15,0,0,_token)+1;
  return -_extra_bits-nblocks_adjust;
}

/*The last EOB token has a special case, where an EOB run of size zero ends all
   the remaining blocks in the frame.*/
static ptrdiff_t oc_token_skip_eob6(int _token,int _extra_bits){
  /*Note: We want to return -PTRDIFF_MAX, but that requires C99, which is not
     yet available everywhere; this should be equivalent.*/
  if(!_extra_bits)return -(~(size_t)0>>1);
  return -_extra_bits;
}

/*Handles the pure zero run tokens.*/
static ptrdiff_t oc_token_skip_zrl(int _token,int _extra_bits){
  return _extra_bits+1;
}

/*Handles a normal coefficient value token.*/
static ptrdiff_t oc_token_skip_val(void){
  return 1;
}

/*Handles a category 1A zero run/coefficient value combo token.*/
static ptrdiff_t oc_token_skip_run_cat1a(int _token){
  return _token-OC_DCT_RUN_CAT1A+2;
}

/*Handles category 1b, 1c, 2a, and 2b zero run/coefficient value combo tokens.*/
static ptrdiff_t oc_token_skip_run(int _token,int _extra_bits){
  int run_cati;
  int ncoeffs_mask;
  int ncoeffs_adjust;
  run_cati=_token-OC_DCT_RUN_CAT1B;
  ncoeffs_mask=OC_BYTE_TABLE32(3,7,0,1,run_cati);
  ncoeffs_adjust=OC_BYTE_TABLE32(7,11,2,3,run_cati);
  return (_extra_bits&ncoeffs_mask)+ncoeffs_adjust;
}

/*A jump table for computing the number of coefficients or blocks to skip for
   a given token value.
  This reduces all the conditional branches, etc., needed to parse these token
   values down to one indirect jump.*/
static const oc_token_skip_func OC_TOKEN_SKIP_TABLE[TH_NDCT_TOKENS]={
  oc_token_skip_eob,
  oc_token_skip_eob,
  oc_token_skip_eob,
  oc_token_skip_eob,
  oc_token_skip_eob,
  oc_token_skip_eob,
  oc_token_skip_eob6,
  oc_token_skip_zrl,
  oc_token_skip_zrl,
  (oc_token_skip_func)oc_token_skip_val,
  (oc_token_skip_func)oc_token_skip_val,
  (oc_token_skip_func)oc_token_skip_val,
  (oc_token_skip_func)oc_token_skip_val,
  (oc_token_skip_func)oc_token_skip_val,
  (oc_token_skip_func)oc_token_skip_val,
  (oc_token_skip_func)oc_token_skip_val,
  (oc_token_skip_func)oc_token_skip_val,
  (oc_token_skip_func)oc_token_skip_val,
  (oc_token_skip_func)oc_token_skip_val,
  (oc_token_skip_func)oc_token_skip_val,
  (oc_token_skip_func)oc_token_skip_val,
  (oc_token_skip_func)oc_token_skip_val,
  (oc_token_skip_func)oc_token_skip_val,
  (oc_token_skip_func)oc_token_skip_run_cat1a,
  (oc_token_skip_func)oc_token_skip_run_cat1a,
  (oc_token_skip_func)oc_token_skip_run_cat1a,
  (oc_token_skip_func)oc_token_skip_run_cat1a,
  (oc_token_skip_func)oc_token_skip_run_cat1a,
  oc_token_skip_run,
  oc_token_skip_run,
  oc_token_skip_run,
  oc_token_skip_run
};

/*Determines the number of blocks or coefficients to be skipped for a given
   token value.
  _token:      The token value to skip.
  _extra_bits: The extra bits attached to this token.
  Return: A positive value indicates that number of coefficients are to be
           skipped in the current block.
          Otherwise, the negative of the return value indicates that number of
           blocks are to be ended.
          0 will never be returned, so that at least one coefficient in one
           block will always be decoded for every token.*/
static ptrdiff_t oc_dct_token_skip(int _token,int _extra_bits){
  return (*OC_TOKEN_SKIP_TABLE[_token])(_token,_extra_bits);
}



void oc_enc_mode_metrics_collect(oc_enc_ctx *_enc){
  static const unsigned char OC_ZZI_HUFF_OFFSET[64]={
     0,16,16,16,16,16,32,32,
    32,32,32,32,32,32,32,48,
    48,48,48,48,48,48,48,48,
    48,48,48,48,64,64,64,64,
    64,64,64,64,64,64,64,64,
    64,64,64,64,64,64,64,64,
    64,64,64,64,64,64,64,64
  };
  const oc_fragment *frags;
  const unsigned    *frag_satd;
  const unsigned    *frag_ssd;
  const ptrdiff_t   *coded_fragis;
  ptrdiff_t          ncoded_fragis;
  ptrdiff_t          fragii;
  double             fragw;
  int                qti;
  int                qii;
  int                qi;
  int                pli;
  int                zzi;
  int                token;
  int                eb;
  oc_restore_fpu(&_enc->state);
  /*Load any existing mode metrics if we haven't already.*/
  if(!oc_has_mode_metrics){
    FILE *fmetrics;
    memset(OC_MODE_METRICS,0,sizeof(OC_MODE_METRICS));
    fmetrics=fopen("modedec.stats","rb");
    if(fmetrics!=NULL){
      fread(OC_MODE_METRICS,sizeof(OC_MODE_METRICS),1,fmetrics);
      fclose(fmetrics);
    }
    for(qi=0;qi<64;qi++)oc_enc_mode_metrics_update(_enc,qi);
    oc_has_mode_metrics=1;
  }
  qti=_enc->state.frame_type;
  frags=_enc->state.frags;
  frag_satd=_enc->frag_satd;
  frag_ssd=_enc->frag_ssd;
  coded_fragis=_enc->state.coded_fragis;
  ncoded_fragis=fragii=0;
  /*Weight the fragments by the inverse frame size; this prevents HD content
     from dominating the statistics.*/
  fragw=1.0/_enc->state.nfrags;
  for(pli=0;pli<3;pli++){
    ptrdiff_t ti[64];
    int       eob_token[64];
    int       eob_run[64];
    /*Set up token indices and eob run counts.
      We don't bother trying to figure out the real cost of the runs that span
       coefficients; instead we use the costs that were available when R-D
       token optimization was done.*/
    for(zzi=0;zzi<64;zzi++){
      ti[zzi]=_enc->dct_token_offs[pli][zzi];
      if(ti[zzi]>0){
        token=_enc->dct_tokens[pli][zzi][0];
        eb=_enc->extra_bits[pli][zzi][0];
        eob_token[zzi]=token;
        eob_run[zzi]=-oc_dct_token_skip(token,eb);
      }
      else{
        eob_token[zzi]=OC_NDCT_EOB_TOKEN_MAX;
        eob_run[zzi]=0;
      }
    }
    /*Scan the list of coded fragments for this plane.*/
    ncoded_fragis+=_enc->state.ncoded_fragis[pli];
    for(;fragii<ncoded_fragis;fragii++){
      ptrdiff_t    fragi;
      ogg_uint32_t frag_bits;
      int          huffi;
      int          skip;
      int          mb_mode;
      unsigned     satd;
      int          bin;
      fragi=coded_fragis[fragii];
      frag_bits=0;
      for(zzi=0;zzi<64;){
        if(eob_run[zzi]>0){
          /*We've reached the end of the block.*/
          eob_run[zzi]--;
          break;
        }
        huffi=_enc->huff_idxs[qti][zzi>0][pli+1>>1]
         +OC_ZZI_HUFF_OFFSET[zzi];
        if(eob_token[zzi]<OC_NDCT_EOB_TOKEN_MAX){
          /*This token caused an EOB run to be flushed.
            Therefore it gets the bits associated with it.*/
          frag_bits+=_enc->huff_codes[huffi][eob_token[zzi]].nbits
           +OC_DCT_TOKEN_EXTRA_BITS[eob_token[zzi]];
          eob_token[zzi]=OC_NDCT_EOB_TOKEN_MAX;
        }
        token=_enc->dct_tokens[pli][zzi][ti[zzi]];
        eb=_enc->extra_bits[pli][zzi][ti[zzi]];
        ti[zzi]++;
        skip=oc_dct_token_skip(token,eb);
        if(skip<0){
          eob_token[zzi]=token;
          eob_run[zzi]=-skip;
        }
        else{
          /*A regular DCT value token; accumulate the bits for it.*/
          frag_bits+=_enc->huff_codes[huffi][token].nbits
           +OC_DCT_TOKEN_EXTRA_BITS[token];
          zzi+=skip;
        }
      }
      mb_mode=frags[fragi].mb_mode;
      qi=_enc->state.qis[frags[fragi].qii];
      satd=frag_satd[fragi]<<(pli+1&2);
      bin=OC_MINI(satd>>OC_SAD_SHIFT,OC_SAD_BINS-1);
      oc_mode_metrics_add(OC_MODE_METRICS[qi][pli][mb_mode!=OC_MODE_INTRA]+bin,
       fragw,satd,frag_bits<<OC_BIT_SCALE,sqrt(frag_ssd[fragi]));
    }
  }
  /*Update global SATD/rate/RMSE estimation matrix.*/
  for(qii=0;qii<_enc->state.nqis;qii++){
    oc_enc_mode_metrics_update(_enc,_enc->state.qis[qii]);
  }
}

void oc_enc_mode_metrics_dump(oc_enc_ctx *_enc){
  FILE *fmetrics;
  int   qi;
  /*Generate sample points for complete list of QI values.*/
  for(qi=0;qi<64;qi++)oc_enc_mode_metrics_update(_enc,qi);
  fmetrics=fopen("modedec.stats","wb");
  if(fmetrics!=NULL){
    fwrite(OC_MODE_METRICS,sizeof(OC_MODE_METRICS),1,fmetrics);
    fclose(fmetrics);
  }
  fprintf(stdout,
   "/*File generated by libtheora with OC_COLLECT_METRICS"
   " defined at compile time.*/\n"
   "#if !defined(_modedec_H)\n"
   "# define _modedec_H (1)\n"
   "\n"
   "\n"
   "\n"
   "# if defined(OC_COLLECT_METRICS)\n"
   "typedef struct oc_mode_metrics oc_mode_metrics;\n"
   "# endif\n"
   "typedef struct oc_mode_rd      oc_mode_rd;\n"
   "\n"
   "\n"
   "\n"
   "/*The number of extra bits of precision at which to store rate"
   " metrics.*/\n"
   "# define OC_BIT_SCALE  (%i)\n"
   "/*The number of extra bits of precision at which to store RMSE metrics.\n"
   "  This must be at least half OC_BIT_SCALE (rounded up).*/\n"
   "# define OC_RMSE_SCALE (%i)\n"
   "/*The number of bins to partition statistics into.*/\n"
   "# define OC_SAD_BINS   (%i)\n"
   "/*The number of bits of precision to drop"
   " from SAD scores to assign them to a\n"
   "   bin.*/\n"
   "# define OC_SAD_SHIFT  (%i)\n"
   "\n"
   "\n"
   "\n"
   "# if defined(OC_COLLECT_METRICS)\n"
   "struct oc_mode_metrics{\n"
   "  double fragw;\n"
   "  double satd;\n"
   "  double rate;\n"
   "  double rmse;\n"
   "  double satd2;\n"
   "  double satdrate;\n"
   "  double rate2;\n"
   "  double satdrmse;\n"
   "  double rmse2;\n"
   "};\n"
   "\n"
   "\n"
   "int             oc_has_mode_metrics;\n"
   "oc_mode_metrics OC_MODE_METRICS[64][3][2][OC_SAD_BINS];\n"
   "# endif\n"
   "\n"
   "\n"
   "\n"
   "struct oc_mode_rd{\n"
   "  ogg_int16_t rate;\n"
   "  ogg_int16_t rmse;\n"
   "};\n"
   "\n"
   "\n"
   "# if !defined(OC_COLLECT_METRICS)\n"
   "static const\n"
   "# endif\n"
   "oc_mode_rd OC_MODE_RD[64][3][2][OC_SAD_BINS]={\n",
   OC_BIT_SCALE,OC_RMSE_SCALE,OC_SAD_BINS,OC_SAD_SHIFT);
  for(qi=0;qi<64;qi++){
    int pli;
    fprintf(stdout,"  {\n");
    for(pli=0;pli<3;pli++){
      int qti;
      fprintf(stdout,"    {\n");
      for(qti=0;qti<2;qti++){
        int bin;
        static const char *pl_names[3]={"Y'","Cb","Cr"};
        static const char *qti_names[2]={"INTRA","INTER"};
        fprintf(stdout,"      /*%s  qi=%i  %s*/\n",
         pl_names[pli],qi,qti_names[qti]);
        fprintf(stdout,"      {\n");
        fprintf(stdout,"        ");
        for(bin=0;bin<OC_SAD_BINS;bin++){
          if(bin&&!(bin&0x3))fprintf(stdout,"\n        ");
          fprintf(stdout,"{%5i,%5i}",
           OC_MODE_RD[qi][pli][qti][bin].rate,
           OC_MODE_RD[qi][pli][qti][bin].rmse);
          if(bin+1<OC_SAD_BINS)fprintf(stdout,",");
        }
        fprintf(stdout,"\n      }");
        if(qti<1)fprintf(stdout,",");
        fprintf(stdout,"\n");
      }
      fprintf(stdout,"    }");
      if(pli<2)fprintf(stdout,",");
      fprintf(stdout,"\n");
    }
    fprintf(stdout,"  }");
    if(qi<63)fprintf(stdout,",");
    fprintf(stdout,"\n");
  }
  fprintf(stdout,
   "};\n"
   "\n"
   "#endif\n");
}
#endif