summaryrefslogtreecommitdiff
path: root/media/libaom/src/av1/av1_cx_iface.c
blob: 12de7ea8ab43c57d08cbac33e6f45d90176cb048 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
/*
 * Copyright (c) 2016, Alliance for Open Media. All rights reserved
 *
 * This source code is subject to the terms of the BSD 2 Clause License and
 * the Alliance for Open Media Patent License 1.0. If the BSD 2 Clause License
 * was not distributed with this source code in the LICENSE file, you can
 * obtain it at www.aomedia.org/license/software. If the Alliance for Open
 * Media Patent License 1.0 was not distributed with this source code in the
 * PATENTS file, you can obtain it at www.aomedia.org/license/patent.
 */
#include <stdlib.h>
#include <string.h>

#include "aom_mem/aom_mem.h"
#include "config/aom_config.h"
#include "config/aom_version.h"

#include "aom_ports/mem_ops.h"

#include "aom/aom_encoder.h"
#include "aom/internal/aom_codec_internal.h"

#include "av1/av1_iface_common.h"
#include "av1/encoder/bitstream.h"
#include "av1/encoder/encoder.h"
#include "av1/encoder/ethread.h"
#include "av1/encoder/external_partition.h"
#include "av1/encoder/firstpass.h"
#include "av1/arg_defs.h"

#include "common/args_helper.h"

struct av1_extracfg {
  int cpu_used;
  unsigned int enable_auto_alt_ref;
  unsigned int enable_auto_bwd_ref;
  unsigned int noise_sensitivity;
  unsigned int sharpness;
  unsigned int static_thresh;
  unsigned int row_mt;
#if CONFIG_FRAME_PARALLEL_ENCODE
  unsigned int fp_mt;
#endif
  unsigned int tile_columns;  // log2 number of tile columns
  unsigned int tile_rows;     // log2 number of tile rows
  unsigned int enable_tpl_model;
  unsigned int enable_keyframe_filtering;
  unsigned int arnr_max_frames;
  unsigned int arnr_strength;
  unsigned int min_gf_interval;
  unsigned int max_gf_interval;
  unsigned int gf_min_pyr_height;
  unsigned int gf_max_pyr_height;
  aom_tune_metric tuning;
  const char *vmaf_model_path;
  const char *partition_info_path;
  aom_dist_metric dist_metric;
  unsigned int cq_level;  // constrained quality level
  unsigned int rc_max_intra_bitrate_pct;
  unsigned int rc_max_inter_bitrate_pct;
  unsigned int gf_cbr_boost_pct;
  unsigned int lossless;
  unsigned int enable_cdef;
  unsigned int enable_restoration;
  unsigned int force_video_mode;
  unsigned int enable_obmc;
  unsigned int disable_trellis_quant;
  unsigned int enable_qm;
  unsigned int qm_y;
  unsigned int qm_u;
  unsigned int qm_v;
  unsigned int qm_min;
  unsigned int qm_max;
  unsigned int num_tg;
  unsigned int mtu_size;

  aom_timing_info_type_t timing_info_type;
  unsigned int frame_parallel_decoding_mode;
  int enable_dual_filter;
  unsigned int enable_chroma_deltaq;
  AQ_MODE aq_mode;
  DELTAQ_MODE deltaq_mode;
  int deltaq_strength;
  int deltalf_mode;
  unsigned int frame_periodic_boost;
  aom_bit_depth_t bit_depth;
  aom_tune_content content;
  aom_color_primaries_t color_primaries;
  aom_transfer_characteristics_t transfer_characteristics;
  aom_matrix_coefficients_t matrix_coefficients;
  aom_chroma_sample_position_t chroma_sample_position;
  int color_range;
  int render_width;
  int render_height;
  aom_superblock_size_t superblock_size;
  unsigned int single_tile_decoding;
  int error_resilient_mode;
  int s_frame_mode;

  int film_grain_test_vector;
  const char *film_grain_table_filename;
  unsigned int motion_vector_unit_test;
#if CONFIG_FRAME_PARALLEL_ENCODE && CONFIG_FPMT_TEST
  unsigned int fpmt_unit_test;
#endif
  unsigned int cdf_update_mode;
  int enable_rect_partitions;    // enable rectangular partitions for sequence
  int enable_ab_partitions;      // enable AB partitions for sequence
  int enable_1to4_partitions;    // enable 1:4 and 4:1 partitions for sequence
  int min_partition_size;        // min partition size [4,8,16,32,64,128]
  int max_partition_size;        // max partition size [4,8,16,32,64,128]
  int enable_intra_edge_filter;  // enable intra-edge filter for sequence
  int enable_order_hint;         // enable order hint for sequence
  int enable_tx64;               // enable 64-pt transform usage for sequence
  int enable_flip_idtx;          // enable flip and identity transform types
  int enable_rect_tx;        // enable rectangular transform usage for sequence
  int enable_dist_wtd_comp;  // enable dist wtd compound for sequence
  int max_reference_frames;  // maximum number of references per frame
  int enable_reduced_reference_set;  // enable reduced set of references
  int enable_ref_frame_mvs;          // sequence level
  int allow_ref_frame_mvs;           // frame level
  int enable_masked_comp;            // enable masked compound for sequence
  int enable_onesided_comp;          // enable one sided compound for sequence
  int enable_interintra_comp;        // enable interintra compound for sequence
  int enable_smooth_interintra;      // enable smooth interintra mode usage
  int enable_diff_wtd_comp;          // enable diff-wtd compound usage
  int enable_interinter_wedge;       // enable interinter-wedge compound usage
  int enable_interintra_wedge;       // enable interintra-wedge compound usage
  int enable_global_motion;          // enable global motion usage for sequence
  int enable_warped_motion;          // sequence level
  int allow_warped_motion;           // frame level
  int enable_filter_intra;           // enable filter intra for sequence
  int enable_smooth_intra;           // enable smooth intra modes for sequence
  int enable_paeth_intra;            // enable Paeth intra mode for sequence
  int enable_cfl_intra;              // enable CFL uv intra mode for sequence
  int enable_directional_intra;      // enable directional modes for sequence
  int enable_diagonal_intra;  // enable D45 to D203 intra modes for sequence
  int enable_superres;
  int enable_overlay;  // enable overlay for filtered arf frames
  int enable_palette;
  int enable_intrabc;
  int enable_angle_delta;
#if CONFIG_DENOISE
  float noise_level;
  int noise_block_size;
  int enable_dnl_denoising;
#endif

  unsigned int chroma_subsampling_x;
  unsigned int chroma_subsampling_y;
  int reduced_tx_type_set;
  int use_intra_dct_only;
  int use_inter_dct_only;
  int use_intra_default_tx_only;
  int enable_tx_size_search;
  int quant_b_adapt;
  unsigned int vbr_corpus_complexity_lap;
  AV1_LEVEL target_seq_level_idx[MAX_NUM_OPERATING_POINTS];
  // Bit mask to specify which tier each of the 32 possible operating points
  // conforms to.
  unsigned int tier_mask;
  // min_cr / 100 is the target minimum compression ratio for each frame.
  unsigned int min_cr;
  COST_UPDATE_TYPE coeff_cost_upd_freq;
  COST_UPDATE_TYPE mode_cost_upd_freq;
  COST_UPDATE_TYPE mv_cost_upd_freq;
  COST_UPDATE_TYPE dv_cost_upd_freq;
  unsigned int ext_tile_debug;
  unsigned int sb_multipass_unit_test;
  // Total number of passes. If this number is -1, then we assume passes = 1 or
  // 2 (passes = 1 if pass == AOM_RC_ONE_PASS and passes = 2 otherwise).
  int passes;
  int fwd_kf_dist;

  LOOPFILTER_CONTROL loopfilter_control;
  // the name of the second pass output file when passes > 2
  const char *two_pass_output;
  const char *second_pass_log;
  // Automatically determine whether to disable several intra tools
  // when "--deltaq-mode=3" is true.
  // Default as 0.
  // When set to 1, the encoder will analyze the reconstruction quality
  // as compared to the source image in the preprocessing pass.
  // If the recontruction quality is considered high enough, we disable
  // the following intra coding tools, for better encoding speed:
  // "--enable_smooth_intra",
  // "--enable_paeth_intra",
  // "--enable_cfl_intra",
  // "--enable_diagonal_intra".
  int auto_intra_tools_off;
  int strict_level_conformance;
};

#if CONFIG_REALTIME_ONLY
// Settings changed for realtime only build:
// cpu_used: 7
// enable_tpl_model: 0
// enable_restoration: 0
// enable_obmc: 0
// deltaq_mode: NO_DELTA_Q
// enable_global_motion usage: 0
// enable_warped_motion at sequence level: 0
// allow_warped_motion at frame level: 0
// coeff_cost_upd_freq: COST_UPD_OFF
// mode_cost_upd_freq: COST_UPD_OFF
// mv_cost_upd_freq: COST_UPD_OFF
// dv_cost_upd_freq: COST_UPD_OFF
static const struct av1_extracfg default_extra_cfg = {
  7,  // cpu_used
  1,  // enable_auto_alt_ref
  0,  // enable_auto_bwd_ref
  0,  // noise_sensitivity
  0,  // sharpness
  0,  // static_thresh
  1,  // row_mt
#if CONFIG_FRAME_PARALLEL_ENCODE
  0,  // fp_mt
#endif
  0,              // tile_columns
  0,              // tile_rows
  0,              // enable_tpl_model
  1,              // enable_keyframe_filtering
  7,              // arnr_max_frames
  5,              // arnr_strength
  0,              // min_gf_interval; 0 -> default decision
  0,              // max_gf_interval; 0 -> default decision
  0,              // gf_min_pyr_height
  5,              // gf_max_pyr_height
  AOM_TUNE_PSNR,  // tuning
  "/usr/local/share/model/vmaf_v0.6.1.json",  // VMAF model path
  ".",                                        // partition info path
  AOM_DIST_METRIC_PSNR,                       // dist_metric
  10,                                         // cq_level
  0,                                          // rc_max_intra_bitrate_pct
  0,                                          // rc_max_inter_bitrate_pct
  0,                                          // gf_cbr_boost_pct
  0,                                          // lossless
  1,                                          // enable_cdef
  0,                                          // enable_restoration
  0,                                          // force_video_mode
  0,                                          // enable_obmc
  3,                                          // disable_trellis_quant
  0,                                          // enable_qm
  DEFAULT_QM_Y,                               // qm_y
  DEFAULT_QM_U,                               // qm_u
  DEFAULT_QM_V,                               // qm_v
  DEFAULT_QM_FIRST,                           // qm_min
  DEFAULT_QM_LAST,                            // qm_max
  1,                                          // max number of tile groups
  0,                                          // mtu_size
  AOM_TIMING_UNSPECIFIED,       // No picture timing signaling in bitstream
  0,                            // frame_parallel_decoding_mode
  1,                            // enable dual filter
  0,                            // enable delta quant in chroma planes
  NO_AQ,                        // aq_mode
  NO_DELTA_Q,                   // deltaq_mode
  100,                          // deltaq_strength
  0,                            // delta lf mode
  0,                            // frame_periodic_boost
  AOM_BITS_8,                   // Bit depth
  AOM_CONTENT_DEFAULT,          // content
  AOM_CICP_CP_UNSPECIFIED,      // CICP color primaries
  AOM_CICP_TC_UNSPECIFIED,      // CICP transfer characteristics
  AOM_CICP_MC_UNSPECIFIED,      // CICP matrix coefficients
  AOM_CSP_UNKNOWN,              // chroma sample position
  0,                            // color range
  0,                            // render width
  0,                            // render height
  AOM_SUPERBLOCK_SIZE_DYNAMIC,  // superblock_size
  1,                            // this depends on large_scale_tile.
  0,                            // error_resilient_mode off by default.
  0,                            // s_frame_mode off by default.
  0,                            // film_grain_test_vector
  NULL,                         // film_grain_table_filename
  0,                            // motion_vector_unit_test
#if CONFIG_FRAME_PARALLEL_ENCODE && CONFIG_FPMT_TEST
  0,  // fpmt_unit_test
#endif
  1,    // CDF update mode
  1,    // enable rectangular partitions
  1,    // enable ab shape partitions
  1,    // enable 1:4 and 4:1 partitions
  4,    // min_partition_size
  128,  // max_partition_size
  1,    // enable intra edge filter
  1,    // frame order hint
  1,    // enable 64-pt transform usage
  1,    // enable flip and identity transform
  1,    // enable rectangular transform usage
  1,    // dist-wtd compound
  7,    // max_reference_frames
  0,    // enable_reduced_reference_set
  1,    // enable_ref_frame_mvs sequence level
  1,    // allow ref_frame_mvs frame level
  1,    // enable masked compound at sequence level
  1,    // enable one sided compound at sequence level
  1,    // enable interintra compound at sequence level
  1,    // enable smooth interintra mode
  1,    // enable difference-weighted compound
  1,    // enable interinter wedge compound
  1,    // enable interintra wedge compound
  0,    // enable_global_motion usage
  0,    // enable_warped_motion at sequence level
  0,    // allow_warped_motion at frame level
  1,    // enable filter intra at sequence level
  1,    // enable smooth intra modes usage for sequence
  1,    // enable Paeth intra mode usage for sequence
  1,    // enable CFL uv intra mode usage for sequence
  1,    // enable directional intra mode usage for sequence
  1,    // enable D45 to D203 intra mode usage for sequence
  1,    // superres
  1,    // enable overlay
  1,    // enable palette
  1,    // enable intrabc
  1,    // enable angle delta
#if CONFIG_DENOISE
  0,   // noise_level
  32,  // noise_block_size
  1,   // enable_dnl_denoising
#endif
  0,  // chroma_subsampling_x
  0,  // chroma_subsampling_y
  0,  // reduced_tx_type_set
  0,  // use_intra_dct_only
  0,  // use_inter_dct_only
  0,  // use_intra_default_tx_only
  1,  // enable_tx_size_search
  0,  // quant_b_adapt
  0,  // vbr_corpus_complexity_lap
  {
      SEQ_LEVEL_MAX, SEQ_LEVEL_MAX, SEQ_LEVEL_MAX, SEQ_LEVEL_MAX, SEQ_LEVEL_MAX,
      SEQ_LEVEL_MAX, SEQ_LEVEL_MAX, SEQ_LEVEL_MAX, SEQ_LEVEL_MAX, SEQ_LEVEL_MAX,
      SEQ_LEVEL_MAX, SEQ_LEVEL_MAX, SEQ_LEVEL_MAX, SEQ_LEVEL_MAX, SEQ_LEVEL_MAX,
      SEQ_LEVEL_MAX, SEQ_LEVEL_MAX, SEQ_LEVEL_MAX, SEQ_LEVEL_MAX, SEQ_LEVEL_MAX,
      SEQ_LEVEL_MAX, SEQ_LEVEL_MAX, SEQ_LEVEL_MAX, SEQ_LEVEL_MAX, SEQ_LEVEL_MAX,
      SEQ_LEVEL_MAX, SEQ_LEVEL_MAX, SEQ_LEVEL_MAX, SEQ_LEVEL_MAX, SEQ_LEVEL_MAX,
      SEQ_LEVEL_MAX, SEQ_LEVEL_MAX,
  },               // target_seq_level_idx
  0,               // tier_mask
  0,               // min_cr
  COST_UPD_OFF,    // coeff_cost_upd_freq
  COST_UPD_OFF,    // mode_cost_upd_freq
  COST_UPD_OFF,    // mv_cost_upd_freq
  COST_UPD_OFF,    // dv_cost_upd_freq
  0,               // ext_tile_debug
  0,               // sb_multipass_unit_test
  -1,              // passes
  -1,              // fwd_kf_dist
  LOOPFILTER_ALL,  // loopfilter_control
  NULL,            // two_pass_output
  NULL,            // second_pass_log
  0,               // auto_intra_tools_off
  0,               // strict_level_conformance
};
#else
static const struct av1_extracfg default_extra_cfg = {
  0,              // cpu_used
  1,              // enable_auto_alt_ref
  0,              // enable_auto_bwd_ref
  0,              // noise_sensitivity
  0,              // sharpness
  0,              // static_thresh
  1,              // row_mt
#if CONFIG_FRAME_PARALLEL_ENCODE
  0,              // fp_mt
#endif
  0,              // tile_columns
  0,              // tile_rows
  1,              // enable_tpl_model
  1,              // enable_keyframe_filtering
  7,              // arnr_max_frames
  5,              // arnr_strength
  0,              // min_gf_interval; 0 -> default decision
  0,              // max_gf_interval; 0 -> default decision
  0,              // gf_min_pyr_height
  5,              // gf_max_pyr_height
  AOM_TUNE_PSNR,  // tuning
  "/usr/local/share/model/vmaf_v0.6.1.json",  // VMAF model path
  ".",                                        // partition info path
  AOM_DIST_METRIC_PSNR,                       // dist_metric
  10,                                         // cq_level
  0,                                          // rc_max_intra_bitrate_pct
  0,                                          // rc_max_inter_bitrate_pct
  0,                                          // gf_cbr_boost_pct
  0,                                          // lossless
  1,                                          // enable_cdef
  1,                                          // enable_restoration
  0,                                          // force_video_mode
  1,                                          // enable_obmc
  3,                                          // disable_trellis_quant
  0,                                          // enable_qm
  DEFAULT_QM_Y,                               // qm_y
  DEFAULT_QM_U,                               // qm_u
  DEFAULT_QM_V,                               // qm_v
  DEFAULT_QM_FIRST,                           // qm_min
  DEFAULT_QM_LAST,                            // qm_max
  1,                                          // max number of tile groups
  0,                                          // mtu_size
  AOM_TIMING_UNSPECIFIED,       // No picture timing signaling in bitstream
  0,                            // frame_parallel_decoding_mode
  1,                            // enable dual filter
  0,                            // enable delta quant in chroma planes
  NO_AQ,                        // aq_mode
  DELTA_Q_OBJECTIVE,            // deltaq_mode
  100,                          // deltaq_strength
  0,                            // delta lf mode
  0,                            // frame_periodic_boost
  AOM_BITS_8,                   // Bit depth
  AOM_CONTENT_DEFAULT,          // content
  AOM_CICP_CP_UNSPECIFIED,      // CICP color primaries
  AOM_CICP_TC_UNSPECIFIED,      // CICP transfer characteristics
  AOM_CICP_MC_UNSPECIFIED,      // CICP matrix coefficients
  AOM_CSP_UNKNOWN,              // chroma sample position
  0,                            // color range
  0,                            // render width
  0,                            // render height
  AOM_SUPERBLOCK_SIZE_DYNAMIC,  // superblock_size
  1,                            // this depends on large_scale_tile.
  0,                            // error_resilient_mode off by default.
  0,                            // s_frame_mode off by default.
  0,                            // film_grain_test_vector
  NULL,                         // film_grain_table_filename
  0,                            // motion_vector_unit_test
#if CONFIG_FRAME_PARALLEL_ENCODE && CONFIG_FPMT_TEST
  0,                            // fpmt_unit_test
#endif
  1,                            // CDF update mode
  1,                            // enable rectangular partitions
  1,                            // enable ab shape partitions
  1,                            // enable 1:4 and 4:1 partitions
  4,                            // min_partition_size
  128,                          // max_partition_size
  1,                            // enable intra edge filter
  1,                            // frame order hint
  1,                            // enable 64-pt transform usage
  1,                            // enable flip and identity transform
  1,                            // enable rectangular transform usage
  1,                            // dist-wtd compound
  7,                            // max_reference_frames
  0,                            // enable_reduced_reference_set
  1,                            // enable_ref_frame_mvs sequence level
  1,                            // allow ref_frame_mvs frame level
  1,                            // enable masked compound at sequence level
  1,                            // enable one sided compound at sequence level
  1,                            // enable interintra compound at sequence level
  1,                            // enable smooth interintra mode
  1,                            // enable difference-weighted compound
  1,                            // enable interinter wedge compound
  1,                            // enable interintra wedge compound
  1,                            // enable_global_motion usage
  1,                            // enable_warped_motion at sequence level
  1,                            // allow_warped_motion at frame level
  1,                            // enable filter intra at sequence level
  1,                            // enable smooth intra modes usage for sequence
  1,                            // enable Paeth intra mode usage for sequence
  1,                            // enable CFL uv intra mode usage for sequence
  1,   // enable directional intra mode usage for sequence
  1,   // enable D45 to D203 intra mode usage for sequence
  1,   // superres
  1,   // enable overlay
  1,   // enable palette
  1,   // enable intrabc
  1,   // enable angle delta
#if CONFIG_DENOISE
  0,   // noise_level
  32,  // noise_block_size
  1,   // enable_dnl_denoising
#endif
  0,   // chroma_subsampling_x
  0,   // chroma_subsampling_y
  0,   // reduced_tx_type_set
  0,   // use_intra_dct_only
  0,   // use_inter_dct_only
  0,   // use_intra_default_tx_only
  1,   // enable_tx_size_search
  0,   // quant_b_adapt
  0,   // vbr_corpus_complexity_lap
  {
      SEQ_LEVEL_MAX, SEQ_LEVEL_MAX, SEQ_LEVEL_MAX, SEQ_LEVEL_MAX, SEQ_LEVEL_MAX,
      SEQ_LEVEL_MAX, SEQ_LEVEL_MAX, SEQ_LEVEL_MAX, SEQ_LEVEL_MAX, SEQ_LEVEL_MAX,
      SEQ_LEVEL_MAX, SEQ_LEVEL_MAX, SEQ_LEVEL_MAX, SEQ_LEVEL_MAX, SEQ_LEVEL_MAX,
      SEQ_LEVEL_MAX, SEQ_LEVEL_MAX, SEQ_LEVEL_MAX, SEQ_LEVEL_MAX, SEQ_LEVEL_MAX,
      SEQ_LEVEL_MAX, SEQ_LEVEL_MAX, SEQ_LEVEL_MAX, SEQ_LEVEL_MAX, SEQ_LEVEL_MAX,
      SEQ_LEVEL_MAX, SEQ_LEVEL_MAX, SEQ_LEVEL_MAX, SEQ_LEVEL_MAX, SEQ_LEVEL_MAX,
      SEQ_LEVEL_MAX, SEQ_LEVEL_MAX,
  },               // target_seq_level_idx
  0,               // tier_mask
  0,               // min_cr
  COST_UPD_SB,     // coeff_cost_upd_freq
  COST_UPD_SB,     // mode_cost_upd_freq
  COST_UPD_SB,     // mv_cost_upd_freq
  COST_UPD_SB,     // dv_cost_upd_freq
  0,               // ext_tile_debug
  0,               // sb_multipass_unit_test
  -1,              // passes
  -1,              // fwd_kf_dist
  LOOPFILTER_ALL,  // loopfilter_control
  NULL,            // two_pass_output
  NULL,            // second_pass_log
  0,               // auto_intra_tools_off
  0,               // strict_level_conformance
};
#endif

struct aom_codec_alg_priv {
  aom_codec_priv_t base;
  aom_codec_enc_cfg_t cfg;
  struct av1_extracfg extra_cfg;
  aom_rational64_t timestamp_ratio;
  aom_codec_pts_t pts_offset;
  unsigned char pts_offset_initialized;
  AV1EncoderConfig oxcf;
  AV1_PRIMARY *ppi;
  unsigned char *cx_data;
  size_t cx_data_sz;
  size_t pending_cx_data_sz;
  aom_image_t preview_img;
  aom_enc_frame_flags_t next_frame_flags;
  aom_codec_pkt_list_decl(256) pkt_list;
  unsigned int fixed_kf_cntr;
  // BufferPool that holds all reference frames.
  BufferPool *buffer_pool;

  // lookahead instance variables
  BufferPool *buffer_pool_lap;
  FIRSTPASS_STATS *frame_stats_buffer;
  // Number of stats buffers required for look ahead
  int num_lap_buffers;
  STATS_BUFFER_CTX stats_buf_context;
};

static INLINE int gcd(int64_t a, int b) {
  int remainder;
  while (b > 0) {
    remainder = (int)(a % b);
    a = b;
    b = remainder;
  }

  return (int)a;
}

static INLINE void reduce_ratio(aom_rational64_t *ratio) {
  const int denom = gcd(ratio->num, ratio->den);
  ratio->num /= denom;
  ratio->den /= denom;
}

static aom_codec_err_t update_error_state(
    aom_codec_alg_priv_t *ctx, const struct aom_internal_error_info *error) {
  const aom_codec_err_t res = error->error_code;

  if (res != AOM_CODEC_OK)
    ctx->base.err_detail = error->has_detail ? error->detail : NULL;

  return res;
}

// This function deep copies a string src to *dst. For default string we will
// use a string literal, and otherwise we will allocate memory for the string.
static aom_codec_err_t allocate_and_set_string(const char *src,
                                               const char *default_src,
                                               const char **dst,
                                               char *err_detail) {
  if (!src) {
    snprintf(err_detail, ARG_ERR_MSG_MAX_LEN,
             "Null pointer given to a string parameter.");
    return AOM_CODEC_INVALID_PARAM;
  }
  if (*dst && strcmp(src, *dst) == 0) return AOM_CODEC_OK;
  // If the input is exactly the same as default, we will use the string
  // literal, so do not free here.
  if (*dst != default_src) {
    aom_free((void *)*dst);
  }

  if (default_src && strcmp(src, default_src) == 0) {
    // default_src should be a string literal
    *dst = default_src;
  } else {
    size_t len = strlen(src) + 1;
    char *tmp = aom_malloc(len * sizeof(*tmp));
    if (!tmp) {
      snprintf(err_detail, ARG_ERR_MSG_MAX_LEN,
               "Failed to allocate memory for copying parameters.");
      return AOM_CODEC_MEM_ERROR;
    }
    memcpy(tmp, src, len);
    *dst = tmp;
  }
  return 0;
}

#undef ERROR
#define ERROR(str)                  \
  do {                              \
    ctx->base.err_detail = str;     \
    return AOM_CODEC_INVALID_PARAM; \
  } while (0)

#define RANGE_CHECK(p, memb, lo, hi)                   \
  do {                                                 \
    if (!((p)->memb >= (lo) && (p)->memb <= (hi)))     \
      ERROR(#memb " out of range [" #lo ".." #hi "]"); \
  } while (0)

#define RANGE_CHECK_HI(p, memb, hi)                                     \
  do {                                                                  \
    if (!((p)->memb <= (hi))) ERROR(#memb " out of range [.." #hi "]"); \
  } while (0)

#define RANGE_CHECK_BOOL(p, memb)                                     \
  do {                                                                \
    if (!!((p)->memb) != (p)->memb) ERROR(#memb " expected boolean"); \
  } while (0)

static aom_codec_err_t validate_config(aom_codec_alg_priv_t *ctx,
                                       const aom_codec_enc_cfg_t *cfg,
                                       const struct av1_extracfg *extra_cfg) {
  RANGE_CHECK(cfg, g_w, 1, 65535);  // 16 bits available
  RANGE_CHECK(cfg, g_h, 1, 65535);  // 16 bits available
  RANGE_CHECK(cfg, g_timebase.den, 1, 1000000000);
  RANGE_CHECK(cfg, g_timebase.num, 1, cfg->g_timebase.den);
  RANGE_CHECK_HI(cfg, g_profile, MAX_PROFILES - 1);

  RANGE_CHECK_HI(cfg, rc_max_quantizer, 63);
  RANGE_CHECK_HI(cfg, rc_min_quantizer, cfg->rc_max_quantizer);
  RANGE_CHECK_BOOL(extra_cfg, lossless);
  RANGE_CHECK_HI(extra_cfg, aq_mode, AQ_MODE_COUNT - 1);
  RANGE_CHECK_HI(extra_cfg, deltaq_mode, DELTA_Q_MODE_COUNT - 1);
  RANGE_CHECK_HI(extra_cfg, deltalf_mode, 1);
  RANGE_CHECK_HI(extra_cfg, frame_periodic_boost, 1);
#if CONFIG_REALTIME_ONLY
  RANGE_CHECK(cfg, g_usage, AOM_USAGE_REALTIME, AOM_USAGE_REALTIME);
#else
  RANGE_CHECK_HI(cfg, g_usage, AOM_USAGE_ALL_INTRA);
#endif
  RANGE_CHECK_HI(cfg, g_threads, MAX_NUM_THREADS);
  RANGE_CHECK(cfg, rc_end_usage, AOM_VBR, AOM_Q);
  RANGE_CHECK_HI(cfg, rc_undershoot_pct, 100);
  RANGE_CHECK_HI(cfg, rc_overshoot_pct, 100);
  RANGE_CHECK_HI(cfg, rc_2pass_vbr_bias_pct, 100);
  RANGE_CHECK(cfg, kf_mode, AOM_KF_DISABLED, AOM_KF_AUTO);
  RANGE_CHECK_HI(cfg, rc_dropframe_thresh, 100);
  RANGE_CHECK(cfg, g_pass, AOM_RC_ONE_PASS, AOM_RC_THIRD_PASS);
  if (cfg->g_pass == AOM_RC_ONE_PASS) {
    RANGE_CHECK_HI(cfg, g_lag_in_frames, MAX_TOTAL_BUFFERS);
  } else {
    RANGE_CHECK_HI(cfg, g_lag_in_frames, MAX_LAG_BUFFERS);
  }
  if (cfg->g_usage == AOM_USAGE_ALL_INTRA) {
    RANGE_CHECK_HI(cfg, g_lag_in_frames, 0);
    RANGE_CHECK_HI(cfg, kf_max_dist, 0);
  }
  RANGE_CHECK_HI(extra_cfg, min_gf_interval, MAX_LAG_BUFFERS - 1);
  RANGE_CHECK_HI(extra_cfg, max_gf_interval, MAX_LAG_BUFFERS - 1);
  if (extra_cfg->max_gf_interval > 0) {
    RANGE_CHECK(extra_cfg, max_gf_interval,
                AOMMAX(2, extra_cfg->min_gf_interval), (MAX_LAG_BUFFERS - 1));
  }
  RANGE_CHECK_HI(extra_cfg, gf_min_pyr_height, 5);
  RANGE_CHECK_HI(extra_cfg, gf_max_pyr_height, 5);
  if (extra_cfg->gf_min_pyr_height > extra_cfg->gf_max_pyr_height) {
    ERROR(
        "gf_min_pyr_height must be less than or equal to "
        "gf_max_pyramid_height");
  }

  RANGE_CHECK_HI(cfg, rc_resize_mode, RESIZE_MODES - 1);
  RANGE_CHECK(cfg, rc_resize_denominator, SCALE_NUMERATOR,
              SCALE_NUMERATOR << 1);
  RANGE_CHECK(cfg, rc_resize_kf_denominator, SCALE_NUMERATOR,
              SCALE_NUMERATOR << 1);
  RANGE_CHECK_HI(cfg, rc_superres_mode, AOM_SUPERRES_AUTO);
  RANGE_CHECK(cfg, rc_superres_denominator, SCALE_NUMERATOR,
              SCALE_NUMERATOR << 1);
  RANGE_CHECK(cfg, rc_superres_kf_denominator, SCALE_NUMERATOR,
              SCALE_NUMERATOR << 1);
  RANGE_CHECK(cfg, rc_superres_qthresh, 1, 63);
  RANGE_CHECK(cfg, rc_superres_kf_qthresh, 1, 63);
  RANGE_CHECK_HI(extra_cfg, cdf_update_mode, 2);

  RANGE_CHECK_HI(extra_cfg, motion_vector_unit_test, 2);
#if CONFIG_FRAME_PARALLEL_ENCODE && CONFIG_FPMT_TEST
  RANGE_CHECK_HI(extra_cfg, fpmt_unit_test, 1);
#endif
  RANGE_CHECK_HI(extra_cfg, sb_multipass_unit_test, 1);
  RANGE_CHECK_HI(extra_cfg, ext_tile_debug, 1);
  RANGE_CHECK_HI(extra_cfg, enable_auto_alt_ref, 1);
  RANGE_CHECK_HI(extra_cfg, enable_auto_bwd_ref, 2);
  RANGE_CHECK(extra_cfg, cpu_used, 0,
              (cfg->g_usage == AOM_USAGE_REALTIME) ? 10 : 9);
  RANGE_CHECK_HI(extra_cfg, noise_sensitivity, 6);
  RANGE_CHECK(extra_cfg, superblock_size, AOM_SUPERBLOCK_SIZE_64X64,
              AOM_SUPERBLOCK_SIZE_DYNAMIC);
  RANGE_CHECK_HI(cfg, large_scale_tile, 1);
  RANGE_CHECK_HI(extra_cfg, single_tile_decoding, 1);

  RANGE_CHECK_HI(extra_cfg, row_mt, 1);
#if CONFIG_FRAME_PARALLEL_ENCODE
  RANGE_CHECK_HI(extra_cfg, fp_mt, 1);
#endif

  RANGE_CHECK_HI(extra_cfg, tile_columns, 6);
  RANGE_CHECK_HI(extra_cfg, tile_rows, 6);

  RANGE_CHECK_HI(cfg, monochrome, 1);

  if (cfg->large_scale_tile && extra_cfg->aq_mode)
    ERROR(
        "Adaptive quantization are not supported in large scale tile "
        "coding.");

  RANGE_CHECK_HI(extra_cfg, sharpness, 7);
  RANGE_CHECK_HI(extra_cfg, arnr_max_frames, 15);
  RANGE_CHECK_HI(extra_cfg, arnr_strength, 6);
  RANGE_CHECK_HI(extra_cfg, cq_level, 63);
  RANGE_CHECK(cfg, g_bit_depth, AOM_BITS_8, AOM_BITS_12);
  RANGE_CHECK(cfg, g_input_bit_depth, 8, 12);
  RANGE_CHECK(extra_cfg, content, AOM_CONTENT_DEFAULT, AOM_CONTENT_INVALID - 1);

  if (cfg->g_pass >= AOM_RC_SECOND_PASS) {
    const size_t packet_sz = sizeof(FIRSTPASS_STATS);
    const int n_packets = (int)(cfg->rc_twopass_stats_in.sz / packet_sz);
    const FIRSTPASS_STATS *stats;

    if (cfg->rc_twopass_stats_in.buf == NULL)
      ERROR("rc_twopass_stats_in.buf not set.");

    if (cfg->rc_twopass_stats_in.sz % packet_sz)
      ERROR("rc_twopass_stats_in.sz indicates truncated packet.");

    if (cfg->rc_twopass_stats_in.sz < 2 * packet_sz)
      ERROR("rc_twopass_stats_in requires at least two packets.");

    stats =
        (const FIRSTPASS_STATS *)cfg->rc_twopass_stats_in.buf + n_packets - 1;

    if ((int)(stats->count + 0.5) != n_packets - 1)
      ERROR("rc_twopass_stats_in missing EOS stats packet");
  }

  if (extra_cfg->passes != -1 && cfg->g_pass == AOM_RC_ONE_PASS &&
      extra_cfg->passes != 1) {
    ERROR("One pass encoding but passes != 1.");
  }

  if (extra_cfg->passes != -1 && (int)cfg->g_pass > extra_cfg->passes) {
    ERROR("Current pass is larger than total number of passes.");
  }

  if (cfg->g_profile <= (unsigned int)PROFILE_1 &&
      cfg->g_bit_depth > AOM_BITS_10) {
    ERROR("Codec bit-depth 12 not supported in profile < 2");
  }
  if (cfg->g_profile <= (unsigned int)PROFILE_1 &&
      cfg->g_input_bit_depth > 10) {
    ERROR("Source bit-depth 12 not supported in profile < 2");
  }

  if (cfg->rc_end_usage == AOM_Q) {
    RANGE_CHECK_HI(cfg, use_fixed_qp_offsets, 1);
  } else {
    if (cfg->use_fixed_qp_offsets > 0) {
      ERROR("--use_fixed_qp_offsets can only be used with --end-usage=q");
    }
  }

  RANGE_CHECK(extra_cfg, color_primaries, AOM_CICP_CP_BT_709,
              AOM_CICP_CP_EBU_3213);  // Need to check range more precisely to
                                      // check for reserved values?
  RANGE_CHECK(extra_cfg, transfer_characteristics, AOM_CICP_TC_BT_709,
              AOM_CICP_TC_HLG);
  RANGE_CHECK(extra_cfg, matrix_coefficients, AOM_CICP_MC_IDENTITY,
              AOM_CICP_MC_ICTCP);
  RANGE_CHECK(extra_cfg, color_range, 0, 1);

  /* Average corpus complexity is supported only in the case of single pass
   * VBR*/
  if (cfg->g_pass == AOM_RC_ONE_PASS && cfg->rc_end_usage == AOM_VBR)
    RANGE_CHECK_HI(extra_cfg, vbr_corpus_complexity_lap,
                   MAX_VBR_CORPUS_COMPLEXITY);
  else if (extra_cfg->vbr_corpus_complexity_lap != 0)
    ERROR(
        "VBR corpus complexity is supported only in the case of single pass "
        "VBR mode.");

#if !CONFIG_TUNE_BUTTERAUGLI
  if (extra_cfg->tuning == AOM_TUNE_BUTTERAUGLI) {
    ERROR(
        "This error may be related to the wrong configuration options: try to "
        "set -DCONFIG_TUNE_BUTTERAUGLI=1 at the time CMake is run.");
  }
#endif

#if !CONFIG_TUNE_VMAF
  if (extra_cfg->tuning >= AOM_TUNE_VMAF_WITH_PREPROCESSING &&
      extra_cfg->tuning <= AOM_TUNE_VMAF_NEG_MAX_GAIN) {
    ERROR(
        "This error may be related to the wrong configuration options: try to "
        "set -DCONFIG_TUNE_VMAF=1 at the time CMake is run.");
  }
#endif

  RANGE_CHECK(extra_cfg, tuning, AOM_TUNE_PSNR, AOM_TUNE_BUTTERAUGLI);

  RANGE_CHECK(extra_cfg, dist_metric, AOM_DIST_METRIC_PSNR,
              AOM_DIST_METRIC_QM_PSNR);

  RANGE_CHECK(extra_cfg, timing_info_type, AOM_TIMING_UNSPECIFIED,
              AOM_TIMING_DEC_MODEL);

  RANGE_CHECK(extra_cfg, film_grain_test_vector, 0, 16);

  if (extra_cfg->lossless) {
    if (extra_cfg->aq_mode != 0)
      ERROR("Only --aq_mode=0 can be used with --lossless=1.");
    if (extra_cfg->enable_chroma_deltaq)
      ERROR("Only --enable_chroma_deltaq=0 can be used with --lossless=1.");
  }

  RANGE_CHECK(extra_cfg, max_reference_frames, 3, 7);
  RANGE_CHECK(extra_cfg, enable_reduced_reference_set, 0, 1);
  RANGE_CHECK_HI(extra_cfg, chroma_subsampling_x, 1);
  RANGE_CHECK_HI(extra_cfg, chroma_subsampling_y, 1);

  RANGE_CHECK_HI(extra_cfg, disable_trellis_quant, 3);
  RANGE_CHECK(extra_cfg, coeff_cost_upd_freq, 0, 3);
  RANGE_CHECK(extra_cfg, mode_cost_upd_freq, 0, 3);
  RANGE_CHECK(extra_cfg, mv_cost_upd_freq, 0, 3);
  RANGE_CHECK(extra_cfg, dv_cost_upd_freq, 0, 3);

  RANGE_CHECK(extra_cfg, min_partition_size, 4, 128);
  RANGE_CHECK(extra_cfg, max_partition_size, 4, 128);
  RANGE_CHECK_HI(extra_cfg, min_partition_size, extra_cfg->max_partition_size);

  for (int i = 0; i < MAX_NUM_OPERATING_POINTS; ++i) {
    const int level_idx = extra_cfg->target_seq_level_idx[i];
    if (!is_valid_seq_level_idx(level_idx) && level_idx != SEQ_LEVELS) {
      ERROR("Target sequence level index is invalid");
    }
  }

  RANGE_CHECK(extra_cfg, deltaq_strength, 0, 1000);
  RANGE_CHECK_HI(extra_cfg, loopfilter_control, 3);
  RANGE_CHECK_HI(extra_cfg, enable_cdef, 2);
  RANGE_CHECK_BOOL(extra_cfg, auto_intra_tools_off);
  RANGE_CHECK_BOOL(extra_cfg, strict_level_conformance);

  return AOM_CODEC_OK;
}

static aom_codec_err_t validate_img(aom_codec_alg_priv_t *ctx,
                                    const aom_image_t *img) {
  switch (img->fmt) {
    case AOM_IMG_FMT_YV12:
    case AOM_IMG_FMT_NV12:
    case AOM_IMG_FMT_I420:
    case AOM_IMG_FMT_YV1216:
    case AOM_IMG_FMT_I42016: break;
    case AOM_IMG_FMT_I444:
    case AOM_IMG_FMT_I44416:
      if (ctx->cfg.g_profile == (unsigned int)PROFILE_0 &&
          !ctx->cfg.monochrome) {
        ERROR("Invalid image format. I444 images not supported in profile.");
      }
      break;
    case AOM_IMG_FMT_I422:
    case AOM_IMG_FMT_I42216:
      if (ctx->cfg.g_profile != (unsigned int)PROFILE_2) {
        ERROR("Invalid image format. I422 images not supported in profile.");
      }
      break;
    default:
      ERROR(
          "Invalid image format. Only YV12, NV12, I420, I422, I444 images are "
          "supported.");
      break;
  }

  if (img->d_w != ctx->cfg.g_w || img->d_h != ctx->cfg.g_h)
    ERROR("Image size must match encoder init configuration size");

#if CONFIG_TUNE_BUTTERAUGLI
  if (ctx->extra_cfg.tuning == AOM_TUNE_BUTTERAUGLI) {
    if (img->bit_depth > 8) {
      ERROR("Only 8 bit depth images supported in tune=butteraugli mode.");
    }
    if (img->mc != 0 && img->mc != AOM_CICP_MC_BT_709 &&
        img->mc != AOM_CICP_MC_BT_601 && img->mc != AOM_CICP_MC_BT_470_B_G) {
      ERROR(
          "Only BT.709 and BT.601 matrix coefficients supported in "
          "tune=butteraugli mode. Identity matrix is treated as BT.601.");
    }
  }
#endif

  return AOM_CODEC_OK;
}

static int get_image_bps(const aom_image_t *img) {
  switch (img->fmt) {
    case AOM_IMG_FMT_YV12:
    case AOM_IMG_FMT_NV12:
    case AOM_IMG_FMT_I420: return 12;
    case AOM_IMG_FMT_I422: return 16;
    case AOM_IMG_FMT_I444: return 24;
    case AOM_IMG_FMT_YV1216:
    case AOM_IMG_FMT_I42016: return 24;
    case AOM_IMG_FMT_I42216: return 32;
    case AOM_IMG_FMT_I44416: return 48;
    default: assert(0 && "Invalid image format"); break;
  }
  return 0;
}

// Set appropriate options to disable frame super-resolution.
static void disable_superres(SuperResCfg *const superres_cfg) {
  superres_cfg->superres_mode = AOM_SUPERRES_NONE;
  superres_cfg->superres_scale_denominator = SCALE_NUMERATOR;
  superres_cfg->superres_kf_scale_denominator = SCALE_NUMERATOR;
  superres_cfg->superres_qthresh = 255;
  superres_cfg->superres_kf_qthresh = 255;
}

static void update_default_encoder_config(const cfg_options_t *cfg,
                                          struct av1_extracfg *extra_cfg) {
  extra_cfg->enable_cdef = (cfg->disable_cdef == 0) ? 1 : 0;
  extra_cfg->enable_restoration = (cfg->disable_lr == 0);
  extra_cfg->superblock_size = (cfg->super_block_size == 64)
                                   ? AOM_SUPERBLOCK_SIZE_64X64
                                   : (cfg->super_block_size == 128)
                                         ? AOM_SUPERBLOCK_SIZE_128X128
                                         : AOM_SUPERBLOCK_SIZE_DYNAMIC;
  extra_cfg->enable_warped_motion = (cfg->disable_warp_motion == 0);
  extra_cfg->enable_dist_wtd_comp = (cfg->disable_dist_wtd_comp == 0);
  extra_cfg->enable_diff_wtd_comp = (cfg->disable_diff_wtd_comp == 0);
  extra_cfg->enable_dual_filter = (cfg->disable_dual_filter == 0);
  extra_cfg->enable_angle_delta = (cfg->disable_intra_angle_delta == 0);
  extra_cfg->enable_rect_partitions = (cfg->disable_rect_partition_type == 0);
  extra_cfg->enable_ab_partitions = (cfg->disable_ab_partition_type == 0);
  extra_cfg->enable_1to4_partitions = (cfg->disable_1to4_partition_type == 0);
  extra_cfg->max_partition_size = cfg->max_partition_size;
  extra_cfg->min_partition_size = cfg->min_partition_size;
  extra_cfg->enable_intra_edge_filter = (cfg->disable_intra_edge_filter == 0);
  extra_cfg->enable_tx64 = (cfg->disable_tx_64x64 == 0);
  extra_cfg->enable_flip_idtx = (cfg->disable_flip_idtx == 0);
  extra_cfg->enable_masked_comp = (cfg->disable_masked_comp == 0);
  extra_cfg->enable_interintra_comp = (cfg->disable_inter_intra_comp == 0);
  extra_cfg->enable_smooth_interintra = (cfg->disable_smooth_inter_intra == 0);
  extra_cfg->enable_interinter_wedge = (cfg->disable_inter_inter_wedge == 0);
  extra_cfg->enable_interintra_wedge = (cfg->disable_inter_intra_wedge == 0);
  extra_cfg->enable_global_motion = (cfg->disable_global_motion == 0);
  extra_cfg->enable_filter_intra = (cfg->disable_filter_intra == 0);
  extra_cfg->enable_smooth_intra = (cfg->disable_smooth_intra == 0);
  extra_cfg->enable_paeth_intra = (cfg->disable_paeth_intra == 0);
  extra_cfg->enable_cfl_intra = (cfg->disable_cfl == 0);
  extra_cfg->enable_obmc = (cfg->disable_obmc == 0);
  extra_cfg->enable_palette = (cfg->disable_palette == 0);
  extra_cfg->enable_intrabc = (cfg->disable_intrabc == 0);
  extra_cfg->disable_trellis_quant = cfg->disable_trellis_quant;
  extra_cfg->allow_ref_frame_mvs = (cfg->disable_ref_frame_mv == 0);
  extra_cfg->enable_ref_frame_mvs = (cfg->disable_ref_frame_mv == 0);
  extra_cfg->enable_onesided_comp = (cfg->disable_one_sided_comp == 0);
  extra_cfg->enable_reduced_reference_set = cfg->reduced_reference_set;
  extra_cfg->reduced_tx_type_set = cfg->reduced_tx_type_set;
}

static aom_codec_err_t set_encoder_config(AV1EncoderConfig *oxcf,
                                          const aom_codec_enc_cfg_t *cfg,
                                          struct av1_extracfg *extra_cfg) {
  if (cfg->encoder_cfg.init_by_cfg_file) {
    update_default_encoder_config(&cfg->encoder_cfg, extra_cfg);
  }

  TuneCfg *const tune_cfg = &oxcf->tune_cfg;

  FrameDimensionCfg *const frm_dim_cfg = &oxcf->frm_dim_cfg;

  TileConfig *const tile_cfg = &oxcf->tile_cfg;

  ResizeCfg *const resize_cfg = &oxcf->resize_cfg;

  GFConfig *const gf_cfg = &oxcf->gf_cfg;

  PartitionCfg *const part_cfg = &oxcf->part_cfg;

  IntraModeCfg *const intra_mode_cfg = &oxcf->intra_mode_cfg;

  TxfmSizeTypeCfg *const txfm_cfg = &oxcf->txfm_cfg;

  CompoundTypeCfg *const comp_type_cfg = &oxcf->comp_type_cfg;

  SuperResCfg *const superres_cfg = &oxcf->superres_cfg;

  KeyFrameCfg *const kf_cfg = &oxcf->kf_cfg;

  DecoderModelCfg *const dec_model_cfg = &oxcf->dec_model_cfg;

  RateControlCfg *const rc_cfg = &oxcf->rc_cfg;

  QuantizationCfg *const q_cfg = &oxcf->q_cfg;

  ColorCfg *const color_cfg = &oxcf->color_cfg;

  InputCfg *const input_cfg = &oxcf->input_cfg;

  AlgoCfg *const algo_cfg = &oxcf->algo_cfg;

  ToolCfg *const tool_cfg = &oxcf->tool_cfg;

  const int is_vbr = cfg->rc_end_usage == AOM_VBR;
  oxcf->profile = cfg->g_profile;
  oxcf->max_threads = (int)cfg->g_threads;

  switch (cfg->g_usage) {
    case AOM_USAGE_REALTIME: oxcf->mode = REALTIME; break;
    case AOM_USAGE_ALL_INTRA: oxcf->mode = ALLINTRA; break;
    default: oxcf->mode = GOOD; break;
  }

  // Set frame-dimension related configuration.
  frm_dim_cfg->width = cfg->g_w;
  frm_dim_cfg->height = cfg->g_h;
  frm_dim_cfg->forced_max_frame_width = cfg->g_forced_max_frame_width;
  frm_dim_cfg->forced_max_frame_height = cfg->g_forced_max_frame_height;
  frm_dim_cfg->render_width = extra_cfg->render_width;
  frm_dim_cfg->render_height = extra_cfg->render_height;

  // Set input video related configuration.
  input_cfg->input_bit_depth = cfg->g_input_bit_depth;
  // guess a frame rate if out of whack, use 30
  input_cfg->init_framerate = (double)cfg->g_timebase.den / cfg->g_timebase.num;
  if (cfg->g_pass >= AOM_RC_SECOND_PASS) {
    const size_t packet_sz = sizeof(FIRSTPASS_STATS);
    const int n_packets = (int)(cfg->rc_twopass_stats_in.sz / packet_sz);
    input_cfg->limit = n_packets - 1;
  } else {
    input_cfg->limit = cfg->g_limit;
  }
  input_cfg->chroma_subsampling_x = extra_cfg->chroma_subsampling_x;
  input_cfg->chroma_subsampling_y = extra_cfg->chroma_subsampling_y;
  if (input_cfg->init_framerate > 180) {
    input_cfg->init_framerate = 30;
    dec_model_cfg->timing_info_present = 0;
  }

  // Set Decoder model configuration.
  if (extra_cfg->timing_info_type == AOM_TIMING_EQUAL ||
      extra_cfg->timing_info_type == AOM_TIMING_DEC_MODEL) {
    dec_model_cfg->timing_info_present = 1;
    dec_model_cfg->timing_info.num_units_in_display_tick = cfg->g_timebase.num;
    dec_model_cfg->timing_info.time_scale = cfg->g_timebase.den;
    dec_model_cfg->timing_info.num_ticks_per_picture = 1;
  } else {
    dec_model_cfg->timing_info_present = 0;
  }
  if (extra_cfg->timing_info_type == AOM_TIMING_EQUAL) {
    dec_model_cfg->timing_info.equal_picture_interval = 1;
    dec_model_cfg->decoder_model_info_present_flag = 0;
    dec_model_cfg->display_model_info_present_flag = 1;
  } else if (extra_cfg->timing_info_type == AOM_TIMING_DEC_MODEL) {
    //    if( extra_cfg->arnr_strength > 0 )
    //    {
    //      printf("Only --arnr-strength=0 can currently be used with
    //      --timing-info=model."); return AOM_CODEC_INVALID_PARAM;
    //    }
    //    if( extra_cfg->enable_superres)
    //    {
    //      printf("Only --superres-mode=0 can currently be used with
    //      --timing-info=model."); return AOM_CODEC_INVALID_PARAM;
    //    }
    dec_model_cfg->num_units_in_decoding_tick = cfg->g_timebase.num;
    dec_model_cfg->timing_info.equal_picture_interval = 0;
    dec_model_cfg->decoder_model_info_present_flag = 1;
    dec_model_cfg->display_model_info_present_flag = 1;
  }

  oxcf->pass = cfg->g_pass;
  // For backward compatibility, assume that if extra_cfg->passes==-1, then
  // passes = 1 or 2.
  if (extra_cfg->passes == -1) {
    if (cfg->g_pass == AOM_RC_ONE_PASS) {
      oxcf->passes = 1;
    } else {
      oxcf->passes = 2;
    }
  } else {
    oxcf->passes = extra_cfg->passes;
  }

  // Set Rate Control configuration.
  rc_cfg->max_intra_bitrate_pct = extra_cfg->rc_max_intra_bitrate_pct;
  rc_cfg->max_inter_bitrate_pct = extra_cfg->rc_max_inter_bitrate_pct;
  rc_cfg->gf_cbr_boost_pct = extra_cfg->gf_cbr_boost_pct;
  rc_cfg->mode = cfg->rc_end_usage;
  rc_cfg->min_cr = extra_cfg->min_cr;
  rc_cfg->best_allowed_q =
      extra_cfg->lossless ? 0 : av1_quantizer_to_qindex(cfg->rc_min_quantizer);
  rc_cfg->worst_allowed_q =
      extra_cfg->lossless ? 0 : av1_quantizer_to_qindex(cfg->rc_max_quantizer);
  rc_cfg->cq_level = av1_quantizer_to_qindex(extra_cfg->cq_level);
  rc_cfg->under_shoot_pct = cfg->rc_undershoot_pct;
  rc_cfg->over_shoot_pct = cfg->rc_overshoot_pct;
  rc_cfg->maximum_buffer_size_ms = is_vbr ? 240000 : cfg->rc_buf_sz;
  rc_cfg->starting_buffer_level_ms = is_vbr ? 60000 : cfg->rc_buf_initial_sz;
  rc_cfg->optimal_buffer_level_ms = is_vbr ? 60000 : cfg->rc_buf_optimal_sz;
  // Convert target bandwidth from Kbit/s to Bit/s
  rc_cfg->target_bandwidth = 1000 * cfg->rc_target_bitrate;
  rc_cfg->drop_frames_water_mark = cfg->rc_dropframe_thresh;
  rc_cfg->vbr_corpus_complexity_lap = extra_cfg->vbr_corpus_complexity_lap;
  rc_cfg->vbrbias = cfg->rc_2pass_vbr_bias_pct;
  rc_cfg->vbrmin_section = cfg->rc_2pass_vbr_minsection_pct;
  rc_cfg->vbrmax_section = cfg->rc_2pass_vbr_maxsection_pct;

  // Set Toolset related configuration.
  tool_cfg->bit_depth = cfg->g_bit_depth;
  tool_cfg->cdef_control = (CDEF_CONTROL)extra_cfg->enable_cdef;
  tool_cfg->enable_restoration =
      (cfg->g_usage == AOM_USAGE_REALTIME) ? 0 : extra_cfg->enable_restoration;
  tool_cfg->force_video_mode = extra_cfg->force_video_mode;
  tool_cfg->enable_palette = extra_cfg->enable_palette;
  // FIXME(debargha): Should this be:
  // tool_cfg->enable_ref_frame_mvs  = extra_cfg->allow_ref_frame_mvs &
  //                                         extra_cfg->enable_order_hint ?
  // Disallow using temporal MVs while large_scale_tile = 1.
  tool_cfg->enable_ref_frame_mvs =
      extra_cfg->allow_ref_frame_mvs && !cfg->large_scale_tile;
  tool_cfg->superblock_size = extra_cfg->superblock_size;
  tool_cfg->enable_monochrome = cfg->monochrome;
  tool_cfg->full_still_picture_hdr = cfg->full_still_picture_hdr;
  tool_cfg->enable_dual_filter = extra_cfg->enable_dual_filter;
  tool_cfg->enable_order_hint = extra_cfg->enable_order_hint;
  tool_cfg->enable_interintra_comp = extra_cfg->enable_interintra_comp;
  tool_cfg->ref_frame_mvs_present =
      extra_cfg->enable_ref_frame_mvs & extra_cfg->enable_order_hint;
  tool_cfg->enable_global_motion = extra_cfg->enable_global_motion;
  tool_cfg->error_resilient_mode =
      cfg->g_error_resilient | extra_cfg->error_resilient_mode;
  tool_cfg->frame_parallel_decoding_mode =
      extra_cfg->frame_parallel_decoding_mode;

  // Set Quantization related configuration.
  q_cfg->using_qm = extra_cfg->enable_qm;
  q_cfg->qm_minlevel = extra_cfg->qm_min;
  q_cfg->qm_maxlevel = extra_cfg->qm_max;
  q_cfg->quant_b_adapt = extra_cfg->quant_b_adapt;
  q_cfg->enable_chroma_deltaq = extra_cfg->enable_chroma_deltaq;
  q_cfg->aq_mode = extra_cfg->aq_mode;
  q_cfg->deltaq_mode = extra_cfg->deltaq_mode;
  q_cfg->deltaq_strength = extra_cfg->deltaq_strength;
  q_cfg->use_fixed_qp_offsets =
      cfg->use_fixed_qp_offsets && (rc_cfg->mode == AOM_Q);
  q_cfg->enable_hdr_deltaq =
      (q_cfg->deltaq_mode == DELTA_Q_HDR) &&
      (cfg->g_bit_depth == AOM_BITS_10) &&
      (extra_cfg->color_primaries == AOM_CICP_CP_BT_2020);

  tool_cfg->enable_deltalf_mode =
      (q_cfg->deltaq_mode != NO_DELTA_Q) && extra_cfg->deltalf_mode;

  // Set cost update frequency configuration.
  oxcf->cost_upd_freq.coeff = (COST_UPDATE_TYPE)extra_cfg->coeff_cost_upd_freq;
  oxcf->cost_upd_freq.mode = (COST_UPDATE_TYPE)extra_cfg->mode_cost_upd_freq;
  // Avoid MV cost update for allintra encoding mode.
  oxcf->cost_upd_freq.mv = (cfg->kf_max_dist != 0)
                               ? (COST_UPDATE_TYPE)extra_cfg->mv_cost_upd_freq
                               : COST_UPD_OFF;
  oxcf->cost_upd_freq.dv = (COST_UPDATE_TYPE)extra_cfg->dv_cost_upd_freq;

  // Set frame resize mode configuration.
  resize_cfg->resize_mode = (RESIZE_MODE)cfg->rc_resize_mode;
  resize_cfg->resize_scale_denominator = (uint8_t)cfg->rc_resize_denominator;
  resize_cfg->resize_kf_scale_denominator =
      (uint8_t)cfg->rc_resize_kf_denominator;
  if (resize_cfg->resize_mode == RESIZE_FIXED &&
      resize_cfg->resize_scale_denominator == SCALE_NUMERATOR &&
      resize_cfg->resize_kf_scale_denominator == SCALE_NUMERATOR)
    resize_cfg->resize_mode = RESIZE_NONE;

  // Set encoder algorithm related configuration.
  algo_cfg->enable_overlay = extra_cfg->enable_overlay;
  algo_cfg->disable_trellis_quant = extra_cfg->disable_trellis_quant;
  algo_cfg->sharpness = extra_cfg->sharpness;
  algo_cfg->arnr_max_frames = extra_cfg->arnr_max_frames;
  algo_cfg->arnr_strength = extra_cfg->arnr_strength;
  algo_cfg->cdf_update_mode = (uint8_t)extra_cfg->cdf_update_mode;
  // TODO(any): Fix and Enable TPL for resize-mode > 0
  algo_cfg->enable_tpl_model =
      resize_cfg->resize_mode ? 0 : extra_cfg->enable_tpl_model;
  algo_cfg->loopfilter_control = extra_cfg->loopfilter_control;

  // Set two-pass stats configuration.
  oxcf->twopass_stats_in = cfg->rc_twopass_stats_in;

  if (extra_cfg->two_pass_output)
    oxcf->two_pass_output = extra_cfg->two_pass_output;

  oxcf->second_pass_log = extra_cfg->second_pass_log;

  // Set Key frame configuration.
  kf_cfg->fwd_kf_enabled = cfg->fwd_kf_enabled;
  kf_cfg->auto_key =
      cfg->kf_mode == AOM_KF_AUTO && cfg->kf_min_dist != cfg->kf_max_dist;
  kf_cfg->key_freq_min = cfg->kf_min_dist;
  kf_cfg->key_freq_max = cfg->kf_max_dist;
  kf_cfg->sframe_dist = cfg->sframe_dist;
  kf_cfg->sframe_mode = cfg->sframe_mode;
  kf_cfg->enable_sframe = extra_cfg->s_frame_mode;
  kf_cfg->enable_keyframe_filtering = extra_cfg->enable_keyframe_filtering;
  kf_cfg->fwd_kf_dist = extra_cfg->fwd_kf_dist;
  // Disable key frame filtering in all intra mode.
  if (cfg->kf_max_dist == 0) {
    kf_cfg->enable_keyframe_filtering = 0;
  }
  kf_cfg->enable_intrabc = extra_cfg->enable_intrabc;

  oxcf->speed = extra_cfg->cpu_used;

  // Set Color related configuration.
  color_cfg->color_primaries = extra_cfg->color_primaries;
  color_cfg->transfer_characteristics = extra_cfg->transfer_characteristics;
  color_cfg->matrix_coefficients = extra_cfg->matrix_coefficients;
  color_cfg->color_range = extra_cfg->color_range;
  color_cfg->chroma_sample_position = extra_cfg->chroma_sample_position;

  // Set Group of frames configuration.
  // Force lag_in_frames to 0 for REALTIME mode
  gf_cfg->lag_in_frames = (oxcf->mode == REALTIME)
                              ? 0
                              : clamp(cfg->g_lag_in_frames, 0, MAX_LAG_BUFFERS);
  gf_cfg->enable_auto_arf = extra_cfg->enable_auto_alt_ref;
  gf_cfg->enable_auto_brf = extra_cfg->enable_auto_bwd_ref;
  gf_cfg->min_gf_interval = extra_cfg->min_gf_interval;
  gf_cfg->max_gf_interval = extra_cfg->max_gf_interval;
  gf_cfg->gf_min_pyr_height = extra_cfg->gf_min_pyr_height;
  gf_cfg->gf_max_pyr_height = extra_cfg->gf_max_pyr_height;

  // Set tune related configuration.
  tune_cfg->tuning = extra_cfg->tuning;
  tune_cfg->vmaf_model_path = extra_cfg->vmaf_model_path;
  tune_cfg->content = extra_cfg->content;
  if (cfg->large_scale_tile) {
    tune_cfg->film_grain_test_vector = 0;
    tune_cfg->film_grain_table_filename = NULL;
  } else {
    tune_cfg->film_grain_test_vector = extra_cfg->film_grain_test_vector;
    tune_cfg->film_grain_table_filename = extra_cfg->film_grain_table_filename;
  }
  tune_cfg->dist_metric = extra_cfg->dist_metric;
#if CONFIG_DENOISE
  oxcf->noise_level = extra_cfg->noise_level;
  oxcf->noise_block_size = extra_cfg->noise_block_size;
  oxcf->enable_dnl_denoising = extra_cfg->enable_dnl_denoising;
#endif

#if CONFIG_AV1_TEMPORAL_DENOISING
  // Temporal denoiser is for nonrd pickmode so disable it for speed < 7.
  // Also disable it for speed 7 for now since it needs to be modified for
  // the check_partition_merge_mode feature.
  if (cfg->g_bit_depth == AOM_BITS_8 && oxcf->speed > 7) {
    oxcf->noise_sensitivity = extra_cfg->noise_sensitivity;
  } else {
    oxcf->noise_sensitivity = 0;
  }
#endif
  // Set Tile related configuration.
  tile_cfg->num_tile_groups = extra_cfg->num_tg;
  // In large-scale tile encoding mode, num_tile_groups is always 1.
  if (cfg->large_scale_tile) tile_cfg->num_tile_groups = 1;
  tile_cfg->mtu = extra_cfg->mtu_size;
  tile_cfg->enable_large_scale_tile = cfg->large_scale_tile;
  tile_cfg->enable_single_tile_decoding =
      (tile_cfg->enable_large_scale_tile) ? extra_cfg->single_tile_decoding : 0;
  tile_cfg->tile_columns = extra_cfg->tile_columns;
  tile_cfg->tile_rows = extra_cfg->tile_rows;
  tile_cfg->tile_width_count = AOMMIN(cfg->tile_width_count, MAX_TILE_COLS);
  tile_cfg->tile_height_count = AOMMIN(cfg->tile_height_count, MAX_TILE_ROWS);
  for (int i = 0; i < tile_cfg->tile_width_count; i++) {
    tile_cfg->tile_widths[i] = AOMMAX(cfg->tile_widths[i], 1);
  }
  for (int i = 0; i < tile_cfg->tile_height_count; i++) {
    tile_cfg->tile_heights[i] = AOMMAX(cfg->tile_heights[i], 1);
  }
  tile_cfg->enable_ext_tile_debug = extra_cfg->ext_tile_debug;

  if (tile_cfg->enable_large_scale_tile) {
    // The superblock_size can only be AOM_SUPERBLOCK_SIZE_64X64 or
    // AOM_SUPERBLOCK_SIZE_128X128 while tile_cfg->enable_large_scale_tile = 1.
    // If superblock_size = AOM_SUPERBLOCK_SIZE_DYNAMIC, hard set it to
    // AOM_SUPERBLOCK_SIZE_64X64(default value in large_scale_tile).
    if (extra_cfg->superblock_size != AOM_SUPERBLOCK_SIZE_64X64 &&
        extra_cfg->superblock_size != AOM_SUPERBLOCK_SIZE_128X128)
      tool_cfg->superblock_size = AOM_SUPERBLOCK_SIZE_64X64;
  }

  // Set reference frame related configuration.
  oxcf->ref_frm_cfg.max_reference_frames = extra_cfg->max_reference_frames;
  oxcf->ref_frm_cfg.enable_reduced_reference_set =
      extra_cfg->enable_reduced_reference_set;
  oxcf->ref_frm_cfg.enable_onesided_comp = extra_cfg->enable_onesided_comp;

  oxcf->row_mt = extra_cfg->row_mt;
#if CONFIG_FRAME_PARALLEL_ENCODE
  oxcf->fp_mt = extra_cfg->fp_mt;
#endif

  // Set motion mode related configuration.
  oxcf->motion_mode_cfg.enable_obmc = extra_cfg->enable_obmc;
  oxcf->motion_mode_cfg.enable_warped_motion = extra_cfg->enable_warped_motion;
#if !CONFIG_REALTIME_ONLY
  oxcf->motion_mode_cfg.allow_warped_motion =
      (extra_cfg->allow_warped_motion & extra_cfg->enable_warped_motion);
#else
  oxcf->motion_mode_cfg.allow_warped_motion =
      (cfg->g_usage == AOM_USAGE_REALTIME && oxcf->speed >= 7)
          ? false
          : (extra_cfg->allow_warped_motion & extra_cfg->enable_warped_motion);
#endif

  // Set partition related configuration.
  part_cfg->enable_rect_partitions = extra_cfg->enable_rect_partitions;
  part_cfg->enable_ab_partitions = extra_cfg->enable_ab_partitions;
  part_cfg->enable_1to4_partitions = extra_cfg->enable_1to4_partitions;
  part_cfg->min_partition_size = extra_cfg->min_partition_size;
  part_cfg->max_partition_size = extra_cfg->max_partition_size;

  // Set intra mode configuration.
  intra_mode_cfg->enable_angle_delta = extra_cfg->enable_angle_delta;
  intra_mode_cfg->enable_intra_edge_filter =
      extra_cfg->enable_intra_edge_filter;
  intra_mode_cfg->enable_filter_intra = extra_cfg->enable_filter_intra;
  intra_mode_cfg->enable_smooth_intra = extra_cfg->enable_smooth_intra;
  intra_mode_cfg->enable_paeth_intra = extra_cfg->enable_paeth_intra;
  intra_mode_cfg->enable_cfl_intra = extra_cfg->enable_cfl_intra;
  intra_mode_cfg->enable_directional_intra =
      extra_cfg->enable_directional_intra;
  intra_mode_cfg->enable_diagonal_intra = extra_cfg->enable_diagonal_intra;
  intra_mode_cfg->auto_intra_tools_off = extra_cfg->auto_intra_tools_off;

  // Set transform size/type configuration.
  txfm_cfg->enable_tx64 = extra_cfg->enable_tx64;
  txfm_cfg->enable_flip_idtx = extra_cfg->enable_flip_idtx;
  txfm_cfg->enable_rect_tx = extra_cfg->enable_rect_tx;
  txfm_cfg->reduced_tx_type_set = extra_cfg->reduced_tx_type_set;
  txfm_cfg->use_intra_dct_only = extra_cfg->use_intra_dct_only;
  txfm_cfg->use_inter_dct_only = extra_cfg->use_inter_dct_only;
  txfm_cfg->use_intra_default_tx_only = extra_cfg->use_intra_default_tx_only;
  txfm_cfg->enable_tx_size_search = extra_cfg->enable_tx_size_search;

  // Set compound type configuration.
  comp_type_cfg->enable_dist_wtd_comp =
      extra_cfg->enable_dist_wtd_comp & extra_cfg->enable_order_hint;
  comp_type_cfg->enable_masked_comp = extra_cfg->enable_masked_comp;
  comp_type_cfg->enable_diff_wtd_comp =
      extra_cfg->enable_masked_comp & extra_cfg->enable_diff_wtd_comp;
  comp_type_cfg->enable_interinter_wedge =
      extra_cfg->enable_masked_comp & extra_cfg->enable_interinter_wedge;
  comp_type_cfg->enable_smooth_interintra =
      extra_cfg->enable_interintra_comp && extra_cfg->enable_smooth_interintra;
  comp_type_cfg->enable_interintra_wedge =
      extra_cfg->enable_interintra_comp & extra_cfg->enable_interintra_wedge;

  // Set Super-resolution mode configuration.
  if (extra_cfg->lossless || cfg->large_scale_tile) {
    disable_superres(superres_cfg);
  } else {
    superres_cfg->superres_mode = cfg->rc_superres_mode;
    superres_cfg->superres_scale_denominator =
        (uint8_t)cfg->rc_superres_denominator;
    superres_cfg->superres_kf_scale_denominator =
        (uint8_t)cfg->rc_superres_kf_denominator;
    superres_cfg->superres_qthresh =
        av1_quantizer_to_qindex(cfg->rc_superres_qthresh);
    superres_cfg->superres_kf_qthresh =
        av1_quantizer_to_qindex(cfg->rc_superres_kf_qthresh);
    if (superres_cfg->superres_mode == AOM_SUPERRES_FIXED &&
        superres_cfg->superres_scale_denominator == SCALE_NUMERATOR &&
        superres_cfg->superres_kf_scale_denominator == SCALE_NUMERATOR) {
      disable_superres(superres_cfg);
    }
    if (superres_cfg->superres_mode == AOM_SUPERRES_QTHRESH &&
        superres_cfg->superres_qthresh == 255 &&
        superres_cfg->superres_kf_qthresh == 255) {
      disable_superres(superres_cfg);
    }
  }

  superres_cfg->enable_superres =
      (superres_cfg->superres_mode != AOM_SUPERRES_NONE) &&
      extra_cfg->enable_superres;
  if (!superres_cfg->enable_superres) {
    disable_superres(superres_cfg);
  }

  if (input_cfg->limit == 1) {
    // still picture mode, display model and timing is meaningless
    dec_model_cfg->display_model_info_present_flag = 0;
    dec_model_cfg->timing_info_present = 0;
  }

  oxcf->save_as_annexb = cfg->save_as_annexb;

  // Set unit test related configuration.
  oxcf->unit_test_cfg.motion_vector_unit_test =
      extra_cfg->motion_vector_unit_test;
  oxcf->unit_test_cfg.sb_multipass_unit_test =
      extra_cfg->sb_multipass_unit_test;

  // For allintra encoding mode, inter-frame motion search is not applicable and
  // the intraBC motion vectors are restricted within the tile boundaries. Hence
  // a smaller frame border size (AOM_ENC_ALLINTRA_BORDER) is used in this case.
  oxcf->border_in_pixels =
      (resize_cfg->resize_mode || superres_cfg->superres_mode)
          ? AOM_BORDER_IN_PIXELS
          : (oxcf->kf_cfg.key_freq_max == 0) ? AOM_ENC_ALLINTRA_BORDER
                                             : AOM_ENC_NO_SCALE_BORDER;
  memcpy(oxcf->target_seq_level_idx, extra_cfg->target_seq_level_idx,
         sizeof(oxcf->target_seq_level_idx));
  oxcf->tier_mask = extra_cfg->tier_mask;

  oxcf->partition_info_path = extra_cfg->partition_info_path;

  oxcf->strict_level_conformance = extra_cfg->strict_level_conformance;

  return AOM_CODEC_OK;
}

static aom_codec_err_t encoder_set_config(aom_codec_alg_priv_t *ctx,
                                          const aom_codec_enc_cfg_t *cfg) {
  InitialDimensions *const initial_dimensions =
      &ctx->ppi->cpi->initial_dimensions;
  aom_codec_err_t res;
  int force_key = 0;

  if (cfg->g_w != ctx->cfg.g_w || cfg->g_h != ctx->cfg.g_h) {
    if (cfg->g_lag_in_frames > 1 || cfg->g_pass != AOM_RC_ONE_PASS)
      ERROR("Cannot change width or height after initialization");
    if (!valid_ref_frame_size(ctx->cfg.g_w, ctx->cfg.g_h, cfg->g_w, cfg->g_h) ||
        (initial_dimensions->width &&
         (int)cfg->g_w > initial_dimensions->width) ||
        (initial_dimensions->height &&
         (int)cfg->g_h > initial_dimensions->height))
      force_key = 1;
  }

  // Prevent increasing lag_in_frames. This check is stricter than it needs
  // to be -- the limit is not increasing past the first lag_in_frames
  // value, but we don't track the initial config, only the last successful
  // config.
  if (cfg->g_lag_in_frames > ctx->cfg.g_lag_in_frames)
    ERROR("Cannot increase lag_in_frames");
  // Prevent changing lag_in_frames if Lookahead Processing is enabled
  if (cfg->g_lag_in_frames != ctx->cfg.g_lag_in_frames &&
      ctx->num_lap_buffers > 0)
    ERROR("Cannot change lag_in_frames if LAP is enabled");

  res = validate_config(ctx, cfg, &ctx->extra_cfg);

  if (res == AOM_CODEC_OK) {
    ctx->cfg = *cfg;
    set_encoder_config(&ctx->oxcf, &ctx->cfg, &ctx->extra_cfg);
    // On profile change, request a key frame
    force_key |= ctx->ppi->seq_params.profile != ctx->oxcf.profile;
    bool is_sb_size_changed = false;
    av1_change_config_seq(ctx->ppi, &ctx->oxcf, &is_sb_size_changed);
#if CONFIG_FRAME_PARALLEL_ENCODE
    int i;
    for (i = 0; i < ctx->ppi->num_fp_contexts; i++) {
      av1_change_config(ctx->ppi->parallel_cpi[i], &ctx->oxcf,
                        is_sb_size_changed);
    }
#else
    av1_change_config(ctx->ppi->cpi, &ctx->oxcf, is_sb_size_changed);
#endif  // CONFIG_FRAME_PARALLEL_ENCODE
    if (ctx->ppi->cpi_lap != NULL) {
      av1_change_config(ctx->ppi->cpi_lap, &ctx->oxcf, is_sb_size_changed);
    }
  }

  if (force_key) ctx->next_frame_flags |= AOM_EFLAG_FORCE_KF;

  return res;
}

static aom_fixed_buf_t *encoder_get_global_headers(aom_codec_alg_priv_t *ctx) {
  return av1_get_global_headers(ctx->ppi);
}

static aom_codec_err_t ctrl_get_quantizer(aom_codec_alg_priv_t *ctx,
                                          va_list args) {
  int *const arg = va_arg(args, int *);
  if (arg == NULL) return AOM_CODEC_INVALID_PARAM;
  *arg = av1_get_quantizer(ctx->ppi->cpi);
  return AOM_CODEC_OK;
}

static aom_codec_err_t ctrl_get_quantizer64(aom_codec_alg_priv_t *ctx,
                                            va_list args) {
  int *const arg = va_arg(args, int *);
  if (arg == NULL) return AOM_CODEC_INVALID_PARAM;
  *arg = av1_qindex_to_quantizer(av1_get_quantizer(ctx->ppi->cpi));
  return AOM_CODEC_OK;
}

static aom_codec_err_t ctrl_get_loopfilter_level(aom_codec_alg_priv_t *ctx,
                                                 va_list args) {
  int *const arg = va_arg(args, int *);
  if (arg == NULL) return AOM_CODEC_INVALID_PARAM;
  *arg = ctx->ppi->cpi->common.lf.filter_level[0];
  return AOM_CODEC_OK;
}

static aom_codec_err_t ctrl_get_baseline_gf_interval(aom_codec_alg_priv_t *ctx,
                                                     va_list args) {
  int *const arg = va_arg(args, int *);
  if (arg == NULL) return AOM_CODEC_INVALID_PARAM;
  *arg = ctx->ppi->p_rc.baseline_gf_interval;
  return AOM_CODEC_OK;
}

static aom_codec_err_t update_extra_cfg(aom_codec_alg_priv_t *ctx,
                                        struct av1_extracfg *extra_cfg) {
  const aom_codec_err_t res = validate_config(ctx, &ctx->cfg, extra_cfg);
  if (res == AOM_CODEC_OK) {
    ctx->extra_cfg = *extra_cfg;
    set_encoder_config(&ctx->oxcf, &ctx->cfg, &ctx->extra_cfg);
#if CONFIG_FRAME_PARALLEL_ENCODE
    av1_check_fpmt_config(ctx->ppi, &ctx->oxcf);
#endif
    bool is_sb_size_changed = false;
    av1_change_config_seq(ctx->ppi, &ctx->oxcf, &is_sb_size_changed);
#if CONFIG_FRAME_PARALLEL_ENCODE
    int i;
    for (i = 0; i < ctx->ppi->num_fp_contexts; i++) {
      av1_change_config(ctx->ppi->parallel_cpi[i], &ctx->oxcf,
                        is_sb_size_changed);
    }
#else
    av1_change_config(ctx->ppi->cpi, &ctx->oxcf, is_sb_size_changed);
#endif  // CONFIG_FRAME_PARALLEL_ENCODE
    if (ctx->ppi->cpi_lap != NULL) {
      av1_change_config(ctx->ppi->cpi_lap, &ctx->oxcf, is_sb_size_changed);
    }
  }
  return res;
}

static aom_codec_err_t ctrl_set_cpuused(aom_codec_alg_priv_t *ctx,
                                        va_list args) {
  struct av1_extracfg extra_cfg = ctx->extra_cfg;
  extra_cfg.cpu_used = CAST(AOME_SET_CPUUSED, args);
  return update_extra_cfg(ctx, &extra_cfg);
}

static aom_codec_err_t ctrl_set_enable_auto_alt_ref(aom_codec_alg_priv_t *ctx,
                                                    va_list args) {
  struct av1_extracfg extra_cfg = ctx->extra_cfg;
  extra_cfg.enable_auto_alt_ref = CAST(AOME_SET_ENABLEAUTOALTREF, args);
  return update_extra_cfg(ctx, &extra_cfg);
}

static aom_codec_err_t ctrl_set_enable_auto_bwd_ref(aom_codec_alg_priv_t *ctx,
                                                    va_list args) {
  struct av1_extracfg extra_cfg = ctx->extra_cfg;
  extra_cfg.enable_auto_bwd_ref = CAST(AOME_SET_ENABLEAUTOBWDREF, args);
  return update_extra_cfg(ctx, &extra_cfg);
}

static aom_codec_err_t ctrl_set_noise_sensitivity(aom_codec_alg_priv_t *ctx,
                                                  va_list args) {
  struct av1_extracfg extra_cfg = ctx->extra_cfg;
  extra_cfg.noise_sensitivity = CAST(AV1E_SET_NOISE_SENSITIVITY, args);
  return update_extra_cfg(ctx, &extra_cfg);
}

static aom_codec_err_t ctrl_set_sharpness(aom_codec_alg_priv_t *ctx,
                                          va_list args) {
  struct av1_extracfg extra_cfg = ctx->extra_cfg;
  extra_cfg.sharpness = CAST(AOME_SET_SHARPNESS, args);
  return update_extra_cfg(ctx, &extra_cfg);
}

static aom_codec_err_t ctrl_set_static_thresh(aom_codec_alg_priv_t *ctx,
                                              va_list args) {
  struct av1_extracfg extra_cfg = ctx->extra_cfg;
  extra_cfg.static_thresh = CAST(AOME_SET_STATIC_THRESHOLD, args);
  return update_extra_cfg(ctx, &extra_cfg);
}

static aom_codec_err_t ctrl_set_row_mt(aom_codec_alg_priv_t *ctx,
                                       va_list args) {
  struct av1_extracfg extra_cfg = ctx->extra_cfg;
  extra_cfg.row_mt = CAST(AV1E_SET_ROW_MT, args);
  return update_extra_cfg(ctx, &extra_cfg);
}

static aom_codec_err_t ctrl_set_tile_columns(aom_codec_alg_priv_t *ctx,
                                             va_list args) {
  struct av1_extracfg extra_cfg = ctx->extra_cfg;
  extra_cfg.tile_columns = CAST(AV1E_SET_TILE_COLUMNS, args);
  return update_extra_cfg(ctx, &extra_cfg);
}

static aom_codec_err_t ctrl_set_tile_rows(aom_codec_alg_priv_t *ctx,
                                          va_list args) {
  struct av1_extracfg extra_cfg = ctx->extra_cfg;
  extra_cfg.tile_rows = CAST(AV1E_SET_TILE_ROWS, args);
  return update_extra_cfg(ctx, &extra_cfg);
}

static aom_codec_err_t ctrl_set_enable_tpl_model(aom_codec_alg_priv_t *ctx,
                                                 va_list args) {
  struct av1_extracfg extra_cfg = ctx->extra_cfg;
  const unsigned int tpl_model_arg = CAST(AV1E_SET_ENABLE_TPL_MODEL, args);
#if CONFIG_REALTIME_ONLY
  if (tpl_model_arg) {
    ERROR("TPL model can't be turned on in realtime only build.");
  }
#endif
  extra_cfg.enable_tpl_model = tpl_model_arg;
  return update_extra_cfg(ctx, &extra_cfg);
}

static aom_codec_err_t ctrl_set_enable_keyframe_filtering(
    aom_codec_alg_priv_t *ctx, va_list args) {
  struct av1_extracfg extra_cfg = ctx->extra_cfg;
  extra_cfg.enable_keyframe_filtering =
      CAST(AV1E_SET_ENABLE_KEYFRAME_FILTERING, args);
  return update_extra_cfg(ctx, &extra_cfg);
}

static aom_codec_err_t ctrl_set_arnr_max_frames(aom_codec_alg_priv_t *ctx,
                                                va_list args) {
  struct av1_extracfg extra_cfg = ctx->extra_cfg;
  extra_cfg.arnr_max_frames = CAST(AOME_SET_ARNR_MAXFRAMES, args);
  return update_extra_cfg(ctx, &extra_cfg);
}

static aom_codec_err_t ctrl_set_arnr_strength(aom_codec_alg_priv_t *ctx,
                                              va_list args) {
  struct av1_extracfg extra_cfg = ctx->extra_cfg;
  extra_cfg.arnr_strength = CAST(AOME_SET_ARNR_STRENGTH, args);
  return update_extra_cfg(ctx, &extra_cfg);
}

static aom_codec_err_t ctrl_set_tuning(aom_codec_alg_priv_t *ctx,
                                       va_list args) {
  struct av1_extracfg extra_cfg = ctx->extra_cfg;
  extra_cfg.tuning = CAST(AOME_SET_TUNING, args);
  return update_extra_cfg(ctx, &extra_cfg);
}

static aom_codec_err_t ctrl_set_cq_level(aom_codec_alg_priv_t *ctx,
                                         va_list args) {
  struct av1_extracfg extra_cfg = ctx->extra_cfg;
  extra_cfg.cq_level = CAST(AOME_SET_CQ_LEVEL, args);
  return update_extra_cfg(ctx, &extra_cfg);
}

static aom_codec_err_t ctrl_set_rc_max_intra_bitrate_pct(
    aom_codec_alg_priv_t *ctx, va_list args) {
  struct av1_extracfg extra_cfg = ctx->extra_cfg;
  extra_cfg.rc_max_intra_bitrate_pct =
      CAST(AOME_SET_MAX_INTRA_BITRATE_PCT, args);
  return update_extra_cfg(ctx, &extra_cfg);
}

static aom_codec_err_t ctrl_set_rc_max_inter_bitrate_pct(
    aom_codec_alg_priv_t *ctx, va_list args) {
  struct av1_extracfg extra_cfg = ctx->extra_cfg;
  extra_cfg.rc_max_inter_bitrate_pct =
      CAST(AOME_SET_MAX_INTER_BITRATE_PCT, args);
  return update_extra_cfg(ctx, &extra_cfg);
}

static aom_codec_err_t ctrl_set_rc_gf_cbr_boost_pct(aom_codec_alg_priv_t *ctx,
                                                    va_list args) {
  struct av1_extracfg extra_cfg = ctx->extra_cfg;
  extra_cfg.gf_cbr_boost_pct = CAST(AV1E_SET_GF_CBR_BOOST_PCT, args);
  return update_extra_cfg(ctx, &extra_cfg);
}

static aom_codec_err_t ctrl_set_lossless(aom_codec_alg_priv_t *ctx,
                                         va_list args) {
  struct av1_extracfg extra_cfg = ctx->extra_cfg;
  extra_cfg.lossless = CAST(AV1E_SET_LOSSLESS, args);
  return update_extra_cfg(ctx, &extra_cfg);
}

static aom_codec_err_t ctrl_set_enable_cdef(aom_codec_alg_priv_t *ctx,
                                            va_list args) {
  struct av1_extracfg extra_cfg = ctx->extra_cfg;
  extra_cfg.enable_cdef = CAST(AV1E_SET_ENABLE_CDEF, args);
  return update_extra_cfg(ctx, &extra_cfg);
}

static aom_codec_err_t ctrl_set_enable_restoration(aom_codec_alg_priv_t *ctx,
                                                   va_list args) {
  struct av1_extracfg extra_cfg = ctx->extra_cfg;
  const unsigned int restoration_arg = CAST(AV1E_SET_ENABLE_RESTORATION, args);
#if CONFIG_REALTIME_ONLY
  if (restoration_arg) {
    ERROR("Restoration can't be turned on in realtime only build.");
  }
#endif
  extra_cfg.enable_restoration = restoration_arg;
  return update_extra_cfg(ctx, &extra_cfg);
}

static aom_codec_err_t ctrl_set_force_video_mode(aom_codec_alg_priv_t *ctx,
                                                 va_list args) {
  struct av1_extracfg extra_cfg = ctx->extra_cfg;
  extra_cfg.force_video_mode = CAST(AV1E_SET_FORCE_VIDEO_MODE, args);
  return update_extra_cfg(ctx, &extra_cfg);
}

static aom_codec_err_t ctrl_set_enable_obmc(aom_codec_alg_priv_t *ctx,
                                            va_list args) {
  struct av1_extracfg extra_cfg = ctx->extra_cfg;
  const unsigned int obmc_arg = CAST(AV1E_SET_ENABLE_OBMC, args);
#if CONFIG_REALTIME_ONLY
  if (obmc_arg) {
    ERROR("OBMC can't be enabled in realtime only build.");
  }
#endif
  extra_cfg.enable_obmc = obmc_arg;
  return update_extra_cfg(ctx, &extra_cfg);
}

static aom_codec_err_t ctrl_set_disable_trellis_quant(aom_codec_alg_priv_t *ctx,
                                                      va_list args) {
  struct av1_extracfg extra_cfg = ctx->extra_cfg;
  extra_cfg.disable_trellis_quant = CAST(AV1E_SET_DISABLE_TRELLIS_QUANT, args);
  return update_extra_cfg(ctx, &extra_cfg);
}

static aom_codec_err_t ctrl_set_enable_qm(aom_codec_alg_priv_t *ctx,
                                          va_list args) {
  struct av1_extracfg extra_cfg = ctx->extra_cfg;
  extra_cfg.enable_qm = CAST(AV1E_SET_ENABLE_QM, args);
  return update_extra_cfg(ctx, &extra_cfg);
}
static aom_codec_err_t ctrl_set_qm_y(aom_codec_alg_priv_t *ctx, va_list args) {
  struct av1_extracfg extra_cfg = ctx->extra_cfg;
  extra_cfg.qm_y = CAST(AV1E_SET_QM_Y, args);
  return update_extra_cfg(ctx, &extra_cfg);
}
static aom_codec_err_t ctrl_set_qm_u(aom_codec_alg_priv_t *ctx, va_list args) {
  struct av1_extracfg extra_cfg = ctx->extra_cfg;
  extra_cfg.qm_u = CAST(AV1E_SET_QM_U, args);
  return update_extra_cfg(ctx, &extra_cfg);
}
static aom_codec_err_t ctrl_set_qm_v(aom_codec_alg_priv_t *ctx, va_list args) {
  struct av1_extracfg extra_cfg = ctx->extra_cfg;
  extra_cfg.qm_v = CAST(AV1E_SET_QM_V, args);
  return update_extra_cfg(ctx, &extra_cfg);
}
static aom_codec_err_t ctrl_set_qm_min(aom_codec_alg_priv_t *ctx,
                                       va_list args) {
  struct av1_extracfg extra_cfg = ctx->extra_cfg;
  extra_cfg.qm_min = CAST(AV1E_SET_QM_MIN, args);
  return update_extra_cfg(ctx, &extra_cfg);
}

static aom_codec_err_t ctrl_set_qm_max(aom_codec_alg_priv_t *ctx,
                                       va_list args) {
  struct av1_extracfg extra_cfg = ctx->extra_cfg;
  extra_cfg.qm_max = CAST(AV1E_SET_QM_MAX, args);
  return update_extra_cfg(ctx, &extra_cfg);
}

static aom_codec_err_t ctrl_set_num_tg(aom_codec_alg_priv_t *ctx,
                                       va_list args) {
  struct av1_extracfg extra_cfg = ctx->extra_cfg;
  extra_cfg.num_tg = CAST(AV1E_SET_NUM_TG, args);
  return update_extra_cfg(ctx, &extra_cfg);
}

static aom_codec_err_t ctrl_set_mtu(aom_codec_alg_priv_t *ctx, va_list args) {
  struct av1_extracfg extra_cfg = ctx->extra_cfg;
  extra_cfg.mtu_size = CAST(AV1E_SET_MTU, args);
  return update_extra_cfg(ctx, &extra_cfg);
}
static aom_codec_err_t ctrl_set_timing_info_type(aom_codec_alg_priv_t *ctx,
                                                 va_list args) {
  struct av1_extracfg extra_cfg = ctx->extra_cfg;
  extra_cfg.timing_info_type = CAST(AV1E_SET_TIMING_INFO_TYPE, args);
  return update_extra_cfg(ctx, &extra_cfg);
}

static aom_codec_err_t ctrl_set_enable_dual_filter(aom_codec_alg_priv_t *ctx,
                                                   va_list args) {
  struct av1_extracfg extra_cfg = ctx->extra_cfg;
  extra_cfg.enable_dual_filter = CAST(AV1E_SET_ENABLE_DUAL_FILTER, args);
  return update_extra_cfg(ctx, &extra_cfg);
}

static aom_codec_err_t ctrl_set_enable_chroma_deltaq(aom_codec_alg_priv_t *ctx,
                                                     va_list args) {
  struct av1_extracfg extra_cfg = ctx->extra_cfg;
  extra_cfg.enable_chroma_deltaq = CAST(AV1E_SET_ENABLE_CHROMA_DELTAQ, args);
  return update_extra_cfg(ctx, &extra_cfg);
}

static aom_codec_err_t ctrl_set_enable_rect_partitions(
    aom_codec_alg_priv_t *ctx, va_list args) {
  struct av1_extracfg extra_cfg = ctx->extra_cfg;
  extra_cfg.enable_rect_partitions =
      CAST(AV1E_SET_ENABLE_RECT_PARTITIONS, args);
  return update_extra_cfg(ctx, &extra_cfg);
}

static aom_codec_err_t ctrl_set_enable_ab_partitions(aom_codec_alg_priv_t *ctx,
                                                     va_list args) {
  struct av1_extracfg extra_cfg = ctx->extra_cfg;
  extra_cfg.enable_ab_partitions = CAST(AV1E_SET_ENABLE_AB_PARTITIONS, args);
  return update_extra_cfg(ctx, &extra_cfg);
}

static aom_codec_err_t ctrl_set_enable_1to4_partitions(
    aom_codec_alg_priv_t *ctx, va_list args) {
  struct av1_extracfg extra_cfg = ctx->extra_cfg;
  extra_cfg.enable_1to4_partitions =
      CAST(AV1E_SET_ENABLE_1TO4_PARTITIONS, args);
  return update_extra_cfg(ctx, &extra_cfg);
}

static aom_codec_err_t ctrl_set_min_partition_size(aom_codec_alg_priv_t *ctx,
                                                   va_list args) {
  struct av1_extracfg extra_cfg = ctx->extra_cfg;
  extra_cfg.min_partition_size = CAST(AV1E_SET_MIN_PARTITION_SIZE, args);
  return update_extra_cfg(ctx, &extra_cfg);
}

static aom_codec_err_t ctrl_set_max_partition_size(aom_codec_alg_priv_t *ctx,
                                                   va_list args) {
  struct av1_extracfg extra_cfg = ctx->extra_cfg;
  extra_cfg.max_partition_size = CAST(AV1E_SET_MAX_PARTITION_SIZE, args);
  return update_extra_cfg(ctx, &extra_cfg);
}

static aom_codec_err_t ctrl_set_enable_intra_edge_filter(
    aom_codec_alg_priv_t *ctx, va_list args) {
  struct av1_extracfg extra_cfg = ctx->extra_cfg;
  extra_cfg.enable_intra_edge_filter =
      CAST(AV1E_SET_ENABLE_INTRA_EDGE_FILTER, args);
  return update_extra_cfg(ctx, &extra_cfg);
}

static aom_codec_err_t ctrl_set_enable_order_hint(aom_codec_alg_priv_t *ctx,
                                                  va_list args) {
  struct av1_extracfg extra_cfg = ctx->extra_cfg;
  extra_cfg.enable_order_hint = CAST(AV1E_SET_ENABLE_ORDER_HINT, args);
  return update_extra_cfg(ctx, &extra_cfg);
}

static aom_codec_err_t ctrl_set_enable_tx64(aom_codec_alg_priv_t *ctx,
                                            va_list args) {
  struct av1_extracfg extra_cfg = ctx->extra_cfg;
  extra_cfg.enable_tx64 = CAST(AV1E_SET_ENABLE_TX64, args);
  return update_extra_cfg(ctx, &extra_cfg);
}

static aom_codec_err_t ctrl_set_enable_flip_idtx(aom_codec_alg_priv_t *ctx,
                                                 va_list args) {
  struct av1_extracfg extra_cfg = ctx->extra_cfg;
  extra_cfg.enable_flip_idtx = CAST(AV1E_SET_ENABLE_FLIP_IDTX, args);
  return update_extra_cfg(ctx, &extra_cfg);
}

static aom_codec_err_t ctrl_set_enable_rect_tx(aom_codec_alg_priv_t *ctx,
                                               va_list args) {
  struct av1_extracfg extra_cfg = ctx->extra_cfg;
  extra_cfg.enable_rect_tx = CAST(AV1E_SET_ENABLE_RECT_TX, args);
  return update_extra_cfg(ctx, &extra_cfg);
}

static aom_codec_err_t ctrl_set_enable_dist_wtd_comp(aom_codec_alg_priv_t *ctx,
                                                     va_list args) {
  struct av1_extracfg extra_cfg = ctx->extra_cfg;
  extra_cfg.enable_dist_wtd_comp = CAST(AV1E_SET_ENABLE_DIST_WTD_COMP, args);
  return update_extra_cfg(ctx, &extra_cfg);
}

static aom_codec_err_t ctrl_set_max_reference_frames(aom_codec_alg_priv_t *ctx,
                                                     va_list args) {
  struct av1_extracfg extra_cfg = ctx->extra_cfg;
  extra_cfg.max_reference_frames = CAST(AV1E_SET_MAX_REFERENCE_FRAMES, args);
  return update_extra_cfg(ctx, &extra_cfg);
}

static aom_codec_err_t ctrl_set_enable_reduced_reference_set(
    aom_codec_alg_priv_t *ctx, va_list args) {
  struct av1_extracfg extra_cfg = ctx->extra_cfg;
  extra_cfg.enable_reduced_reference_set =
      CAST(AV1E_SET_REDUCED_REFERENCE_SET, args);
  return update_extra_cfg(ctx, &extra_cfg);
}

static aom_codec_err_t ctrl_set_enable_ref_frame_mvs(aom_codec_alg_priv_t *ctx,
                                                     va_list args) {
  struct av1_extracfg extra_cfg = ctx->extra_cfg;
  extra_cfg.enable_ref_frame_mvs = CAST(AV1E_SET_ENABLE_REF_FRAME_MVS, args);
  return update_extra_cfg(ctx, &extra_cfg);
}

static aom_codec_err_t ctrl_set_allow_ref_frame_mvs(aom_codec_alg_priv_t *ctx,
                                                    va_list args) {
  struct av1_extracfg extra_cfg = ctx->extra_cfg;
  extra_cfg.allow_ref_frame_mvs = CAST(AV1E_SET_ALLOW_REF_FRAME_MVS, args);
  return update_extra_cfg(ctx, &extra_cfg);
}

static aom_codec_err_t ctrl_set_enable_masked_comp(aom_codec_alg_priv_t *ctx,
                                                   va_list args) {
  struct av1_extracfg extra_cfg = ctx->extra_cfg;
  extra_cfg.enable_masked_comp = CAST(AV1E_SET_ENABLE_MASKED_COMP, args);
  return update_extra_cfg(ctx, &extra_cfg);
}

static aom_codec_err_t ctrl_set_enable_onesided_comp(aom_codec_alg_priv_t *ctx,
                                                     va_list args) {
  struct av1_extracfg extra_cfg = ctx->extra_cfg;
  extra_cfg.enable_onesided_comp = CAST(AV1E_SET_ENABLE_ONESIDED_COMP, args);
  return update_extra_cfg(ctx, &extra_cfg);
}

static aom_codec_err_t ctrl_set_enable_interintra_comp(
    aom_codec_alg_priv_t *ctx, va_list args) {
  struct av1_extracfg extra_cfg = ctx->extra_cfg;
  extra_cfg.enable_interintra_comp =
      CAST(AV1E_SET_ENABLE_INTERINTRA_COMP, args);
  return update_extra_cfg(ctx, &extra_cfg);
}

static aom_codec_err_t ctrl_set_enable_smooth_interintra(
    aom_codec_alg_priv_t *ctx, va_list args) {
  struct av1_extracfg extra_cfg = ctx->extra_cfg;
  extra_cfg.enable_smooth_interintra =
      CAST(AV1E_SET_ENABLE_SMOOTH_INTERINTRA, args);
  return update_extra_cfg(ctx, &extra_cfg);
}

static aom_codec_err_t ctrl_set_enable_diff_wtd_comp(aom_codec_alg_priv_t *ctx,
                                                     va_list args) {
  struct av1_extracfg extra_cfg = ctx->extra_cfg;
  extra_cfg.enable_diff_wtd_comp = CAST(AV1E_SET_ENABLE_DIFF_WTD_COMP, args);
  return update_extra_cfg(ctx, &extra_cfg);
}

static aom_codec_err_t ctrl_set_enable_interinter_wedge(
    aom_codec_alg_priv_t *ctx, va_list args) {
  struct av1_extracfg extra_cfg = ctx->extra_cfg;
  extra_cfg.enable_interinter_wedge =
      CAST(AV1E_SET_ENABLE_INTERINTER_WEDGE, args);
  return update_extra_cfg(ctx, &extra_cfg);
}

static aom_codec_err_t ctrl_set_enable_interintra_wedge(
    aom_codec_alg_priv_t *ctx, va_list args) {
  struct av1_extracfg extra_cfg = ctx->extra_cfg;
  extra_cfg.enable_interintra_wedge =
      CAST(AV1E_SET_ENABLE_INTERINTRA_WEDGE, args);
  return update_extra_cfg(ctx, &extra_cfg);
}

static aom_codec_err_t ctrl_set_enable_global_motion(aom_codec_alg_priv_t *ctx,
                                                     va_list args) {
  struct av1_extracfg extra_cfg = ctx->extra_cfg;
  const int global_motion_arg = CAST(AV1E_SET_ENABLE_GLOBAL_MOTION, args);
#if CONFIG_REALTIME_ONLY
  if (global_motion_arg) {
    ERROR("Global motion can't be enabled in realtime only build.");
  }
#endif
  extra_cfg.enable_global_motion = global_motion_arg;
  return update_extra_cfg(ctx, &extra_cfg);
}

static aom_codec_err_t ctrl_set_enable_warped_motion(aom_codec_alg_priv_t *ctx,
                                                     va_list args) {
  struct av1_extracfg extra_cfg = ctx->extra_cfg;
  const int warped_motion_arg = CAST(AV1E_SET_ENABLE_WARPED_MOTION, args);
#if CONFIG_REALTIME_ONLY
  if (warped_motion_arg) {
    ERROR("Warped motion can't be enabled in realtime only build.");
  }
#endif
  extra_cfg.enable_warped_motion = warped_motion_arg;
  return update_extra_cfg(ctx, &extra_cfg);
}

static aom_codec_err_t ctrl_set_allow_warped_motion(aom_codec_alg_priv_t *ctx,
                                                    va_list args) {
  struct av1_extracfg extra_cfg = ctx->extra_cfg;
  extra_cfg.allow_warped_motion = CAST(AV1E_SET_ALLOW_WARPED_MOTION, args);
  return update_extra_cfg(ctx, &extra_cfg);
}

static aom_codec_err_t ctrl_set_enable_filter_intra(aom_codec_alg_priv_t *ctx,
                                                    va_list args) {
  struct av1_extracfg extra_cfg = ctx->extra_cfg;
  extra_cfg.enable_filter_intra = CAST(AV1E_SET_ENABLE_FILTER_INTRA, args);
  return update_extra_cfg(ctx, &extra_cfg);
}

static aom_codec_err_t ctrl_set_enable_smooth_intra(aom_codec_alg_priv_t *ctx,
                                                    va_list args) {
  struct av1_extracfg extra_cfg = ctx->extra_cfg;
  extra_cfg.enable_smooth_intra = CAST(AV1E_SET_ENABLE_SMOOTH_INTRA, args);
  return update_extra_cfg(ctx, &extra_cfg);
}

static aom_codec_err_t ctrl_set_enable_directional_intra(
    aom_codec_alg_priv_t *ctx, va_list args) {
  struct av1_extracfg extra_cfg = ctx->extra_cfg;
  extra_cfg.enable_directional_intra =
      CAST(AV1E_SET_ENABLE_DIRECTIONAL_INTRA, args);
  return update_extra_cfg(ctx, &extra_cfg);
}

static aom_codec_err_t ctrl_set_enable_diagonal_intra(aom_codec_alg_priv_t *ctx,
                                                      va_list args) {
  struct av1_extracfg extra_cfg = ctx->extra_cfg;
  extra_cfg.enable_diagonal_intra = CAST(AV1E_SET_ENABLE_DIAGONAL_INTRA, args);
  return update_extra_cfg(ctx, &extra_cfg);
}

static aom_codec_err_t ctrl_set_enable_paeth_intra(aom_codec_alg_priv_t *ctx,
                                                   va_list args) {
  struct av1_extracfg extra_cfg = ctx->extra_cfg;
  extra_cfg.enable_paeth_intra = CAST(AV1E_SET_ENABLE_PAETH_INTRA, args);
  return update_extra_cfg(ctx, &extra_cfg);
}

static aom_codec_err_t ctrl_set_enable_cfl_intra(aom_codec_alg_priv_t *ctx,
                                                 va_list args) {
  struct av1_extracfg extra_cfg = ctx->extra_cfg;
  extra_cfg.enable_cfl_intra = CAST(AV1E_SET_ENABLE_CFL_INTRA, args);
  return update_extra_cfg(ctx, &extra_cfg);
}

static aom_codec_err_t ctrl_set_enable_superres(aom_codec_alg_priv_t *ctx,
                                                va_list args) {
  struct av1_extracfg extra_cfg = ctx->extra_cfg;
  extra_cfg.enable_superres = CAST(AV1E_SET_ENABLE_SUPERRES, args);
  return update_extra_cfg(ctx, &extra_cfg);
}

static aom_codec_err_t ctrl_set_enable_overlay(aom_codec_alg_priv_t *ctx,
                                               va_list args) {
  struct av1_extracfg extra_cfg = ctx->extra_cfg;
  extra_cfg.enable_overlay = CAST(AV1E_SET_ENABLE_OVERLAY, args);
  return update_extra_cfg(ctx, &extra_cfg);
}

static aom_codec_err_t ctrl_set_enable_palette(aom_codec_alg_priv_t *ctx,
                                               va_list args) {
  struct av1_extracfg extra_cfg = ctx->extra_cfg;
  extra_cfg.enable_palette = CAST(AV1E_SET_ENABLE_PALETTE, args);
  return update_extra_cfg(ctx, &extra_cfg);
}

static aom_codec_err_t ctrl_set_enable_intrabc(aom_codec_alg_priv_t *ctx,
                                               va_list args) {
  struct av1_extracfg extra_cfg = ctx->extra_cfg;
  extra_cfg.enable_intrabc = CAST(AV1E_SET_ENABLE_INTRABC, args);
  return update_extra_cfg(ctx, &extra_cfg);
}

static aom_codec_err_t ctrl_set_enable_angle_delta(aom_codec_alg_priv_t *ctx,
                                                   va_list args) {
  struct av1_extracfg extra_cfg = ctx->extra_cfg;
  extra_cfg.enable_angle_delta = CAST(AV1E_SET_ENABLE_ANGLE_DELTA, args);
  return update_extra_cfg(ctx, &extra_cfg);
}

static aom_codec_err_t ctrl_set_error_resilient_mode(aom_codec_alg_priv_t *ctx,
                                                     va_list args) {
  struct av1_extracfg extra_cfg = ctx->extra_cfg;
  extra_cfg.error_resilient_mode = CAST(AV1E_SET_ERROR_RESILIENT_MODE, args);
  return update_extra_cfg(ctx, &extra_cfg);
}

static aom_codec_err_t ctrl_set_s_frame_mode(aom_codec_alg_priv_t *ctx,
                                             va_list args) {
  struct av1_extracfg extra_cfg = ctx->extra_cfg;
  extra_cfg.s_frame_mode = CAST(AV1E_SET_S_FRAME_MODE, args);
  return update_extra_cfg(ctx, &extra_cfg);
}

static aom_codec_err_t ctrl_set_frame_parallel_decoding_mode(
    aom_codec_alg_priv_t *ctx, va_list args) {
  struct av1_extracfg extra_cfg = ctx->extra_cfg;
  extra_cfg.frame_parallel_decoding_mode =
      CAST(AV1E_SET_FRAME_PARALLEL_DECODING, args);
  return update_extra_cfg(ctx, &extra_cfg);
}

static aom_codec_err_t ctrl_set_single_tile_decoding(aom_codec_alg_priv_t *ctx,
                                                     va_list args) {
  struct av1_extracfg extra_cfg = ctx->extra_cfg;
  extra_cfg.single_tile_decoding = CAST(AV1E_SET_SINGLE_TILE_DECODING, args);
  return update_extra_cfg(ctx, &extra_cfg);
}

static aom_codec_err_t ctrl_set_aq_mode(aom_codec_alg_priv_t *ctx,
                                        va_list args) {
  struct av1_extracfg extra_cfg = ctx->extra_cfg;
  extra_cfg.aq_mode = CAST(AV1E_SET_AQ_MODE, args);
  return update_extra_cfg(ctx, &extra_cfg);
}

static aom_codec_err_t ctrl_set_reduced_tx_type_set(aom_codec_alg_priv_t *ctx,
                                                    va_list args) {
  struct av1_extracfg extra_cfg = ctx->extra_cfg;
  extra_cfg.reduced_tx_type_set = CAST(AV1E_SET_REDUCED_TX_TYPE_SET, args);
  return update_extra_cfg(ctx, &extra_cfg);
}

static aom_codec_err_t ctrl_set_intra_dct_only(aom_codec_alg_priv_t *ctx,
                                               va_list args) {
  struct av1_extracfg extra_cfg = ctx->extra_cfg;
  extra_cfg.use_intra_dct_only = CAST(AV1E_SET_INTRA_DCT_ONLY, args);
  return update_extra_cfg(ctx, &extra_cfg);
}

static aom_codec_err_t ctrl_set_inter_dct_only(aom_codec_alg_priv_t *ctx,
                                               va_list args) {
  struct av1_extracfg extra_cfg = ctx->extra_cfg;
  extra_cfg.use_inter_dct_only = CAST(AV1E_SET_INTER_DCT_ONLY, args);
  return update_extra_cfg(ctx, &extra_cfg);
}

static aom_codec_err_t ctrl_set_intra_default_tx_only(aom_codec_alg_priv_t *ctx,
                                                      va_list args) {
  struct av1_extracfg extra_cfg = ctx->extra_cfg;
  extra_cfg.use_intra_default_tx_only =
      CAST(AV1E_SET_INTRA_DEFAULT_TX_ONLY, args);
  return update_extra_cfg(ctx, &extra_cfg);
}

static aom_codec_err_t ctrl_set_enable_tx_size_search(aom_codec_alg_priv_t *ctx,
                                                      va_list args) {
  struct av1_extracfg extra_cfg = ctx->extra_cfg;
  extra_cfg.enable_tx_size_search = CAST(AV1E_SET_ENABLE_TX_SIZE_SEARCH, args);
  return update_extra_cfg(ctx, &extra_cfg);
}

static aom_codec_err_t ctrl_set_quant_b_adapt(aom_codec_alg_priv_t *ctx,
                                              va_list args) {
  struct av1_extracfg extra_cfg = ctx->extra_cfg;
  extra_cfg.quant_b_adapt = CAST(AV1E_SET_QUANT_B_ADAPT, args);
  return update_extra_cfg(ctx, &extra_cfg);
}

static aom_codec_err_t ctrl_set_vbr_corpus_complexity_lap(
    aom_codec_alg_priv_t *ctx, va_list args) {
  struct av1_extracfg extra_cfg = ctx->extra_cfg;
  extra_cfg.vbr_corpus_complexity_lap =
      CAST(AV1E_SET_VBR_CORPUS_COMPLEXITY_LAP, args);
  return update_extra_cfg(ctx, &extra_cfg);
}
static aom_codec_err_t ctrl_set_coeff_cost_upd_freq(aom_codec_alg_priv_t *ctx,
                                                    va_list args) {
  struct av1_extracfg extra_cfg = ctx->extra_cfg;
  extra_cfg.coeff_cost_upd_freq = CAST(AV1E_SET_COEFF_COST_UPD_FREQ, args);
  return update_extra_cfg(ctx, &extra_cfg);
}

static aom_codec_err_t ctrl_set_mode_cost_upd_freq(aom_codec_alg_priv_t *ctx,
                                                   va_list args) {
  struct av1_extracfg extra_cfg = ctx->extra_cfg;
  extra_cfg.mode_cost_upd_freq = CAST(AV1E_SET_MODE_COST_UPD_FREQ, args);
  return update_extra_cfg(ctx, &extra_cfg);
}

static aom_codec_err_t ctrl_set_mv_cost_upd_freq(aom_codec_alg_priv_t *ctx,
                                                 va_list args) {
  struct av1_extracfg extra_cfg = ctx->extra_cfg;
  extra_cfg.mv_cost_upd_freq = CAST(AV1E_SET_MV_COST_UPD_FREQ, args);
  return update_extra_cfg(ctx, &extra_cfg);
}

static aom_codec_err_t ctrl_set_dv_cost_upd_freq(aom_codec_alg_priv_t *ctx,
                                                 va_list args) {
  struct av1_extracfg extra_cfg = ctx->extra_cfg;
  extra_cfg.dv_cost_upd_freq = CAST(AV1E_SET_DV_COST_UPD_FREQ, args);
  return update_extra_cfg(ctx, &extra_cfg);
}

static aom_codec_err_t ctrl_set_vmaf_model_path(aom_codec_alg_priv_t *ctx,
                                                va_list args) {
  struct av1_extracfg extra_cfg = ctx->extra_cfg;
  const char *str = CAST(AV1E_SET_VMAF_MODEL_PATH, args);
  const aom_codec_err_t ret = allocate_and_set_string(
      str, default_extra_cfg.vmaf_model_path, &extra_cfg.vmaf_model_path,
      ctx->ppi->error.detail);
  if (ret != AOM_CODEC_OK) return ret;
  return update_extra_cfg(ctx, &extra_cfg);
}

static aom_codec_err_t ctrl_set_partition_info_path(aom_codec_alg_priv_t *ctx,
                                                    va_list args) {
  struct av1_extracfg extra_cfg = ctx->extra_cfg;
  const char *str = CAST(AV1E_SET_PARTITION_INFO_PATH, args);
  const aom_codec_err_t ret = allocate_and_set_string(
      str, default_extra_cfg.partition_info_path,
      &extra_cfg.partition_info_path, ctx->ppi->error.detail);
  if (ret != AOM_CODEC_OK) return ret;
  return update_extra_cfg(ctx, &extra_cfg);
}

static aom_codec_err_t ctrl_set_film_grain_test_vector(
    aom_codec_alg_priv_t *ctx, va_list args) {
  struct av1_extracfg extra_cfg = ctx->extra_cfg;
  extra_cfg.film_grain_test_vector =
      CAST(AV1E_SET_FILM_GRAIN_TEST_VECTOR, args);
  return update_extra_cfg(ctx, &extra_cfg);
}

static aom_codec_err_t ctrl_set_film_grain_table(aom_codec_alg_priv_t *ctx,
                                                 va_list args) {
  struct av1_extracfg extra_cfg = ctx->extra_cfg;
  const char *str = CAST(AV1E_SET_FILM_GRAIN_TABLE, args);
  if (str == NULL) {
    // this parameter allows NULL as its value
    extra_cfg.film_grain_table_filename = str;
  } else {
    const aom_codec_err_t ret = allocate_and_set_string(
        str, default_extra_cfg.film_grain_table_filename,
        &extra_cfg.film_grain_table_filename, ctx->ppi->error.detail);
    if (ret != AOM_CODEC_OK) return ret;
  }
  return update_extra_cfg(ctx, &extra_cfg);
}

static aom_codec_err_t ctrl_set_denoise_noise_level(aom_codec_alg_priv_t *ctx,
                                                    va_list args) {
#if !CONFIG_DENOISE
  (void)ctx;
  (void)args;
  return AOM_CODEC_INCAPABLE;
#else
  struct av1_extracfg extra_cfg = ctx->extra_cfg;
  extra_cfg.noise_level =
      ((float)CAST(AV1E_SET_DENOISE_NOISE_LEVEL, args)) / 10.0f;
  return update_extra_cfg(ctx, &extra_cfg);
#endif
}

static aom_codec_err_t ctrl_set_denoise_block_size(aom_codec_alg_priv_t *ctx,
                                                   va_list args) {
#if !CONFIG_DENOISE
  (void)ctx;
  (void)args;
  return AOM_CODEC_INCAPABLE;
#else
  struct av1_extracfg extra_cfg = ctx->extra_cfg;
  extra_cfg.noise_block_size = CAST(AV1E_SET_DENOISE_BLOCK_SIZE, args);
  return update_extra_cfg(ctx, &extra_cfg);
#endif
}

static aom_codec_err_t ctrl_set_enable_dnl_denoising(aom_codec_alg_priv_t *ctx,
                                                     va_list args) {
#if !CONFIG_DENOISE
  (void)ctx;
  (void)args;
  return AOM_CODEC_INCAPABLE;
#else
  struct av1_extracfg extra_cfg = ctx->extra_cfg;
  extra_cfg.enable_dnl_denoising = CAST(AV1E_SET_ENABLE_DNL_DENOISING, args);
  return update_extra_cfg(ctx, &extra_cfg);
#endif
}

static aom_codec_err_t ctrl_set_deltaq_mode(aom_codec_alg_priv_t *ctx,
                                            va_list args) {
  struct av1_extracfg extra_cfg = ctx->extra_cfg;
  const DELTAQ_MODE deltaq_arg = CAST(AV1E_SET_DELTAQ_MODE, args);
#if CONFIG_REALTIME_ONLY
  if (deltaq_arg > NO_DELTA_Q) {
    ERROR("Delta Q mode can't be enabled in realtime only build.");
  }
#endif
  extra_cfg.deltaq_mode = deltaq_arg;
  return update_extra_cfg(ctx, &extra_cfg);
}

static aom_codec_err_t ctrl_set_deltaq_strength(aom_codec_alg_priv_t *ctx,
                                                va_list args) {
  struct av1_extracfg extra_cfg = ctx->extra_cfg;
  extra_cfg.deltaq_strength = CAST(AV1E_SET_DELTAQ_STRENGTH, args);
  return update_extra_cfg(ctx, &extra_cfg);
}

static aom_codec_err_t ctrl_set_deltalf_mode(aom_codec_alg_priv_t *ctx,
                                             va_list args) {
  struct av1_extracfg extra_cfg = ctx->extra_cfg;
  extra_cfg.deltalf_mode = CAST(AV1E_SET_DELTALF_MODE, args);
  return update_extra_cfg(ctx, &extra_cfg);
}

static aom_codec_err_t ctrl_set_min_gf_interval(aom_codec_alg_priv_t *ctx,
                                                va_list args) {
  struct av1_extracfg extra_cfg = ctx->extra_cfg;
  extra_cfg.min_gf_interval = CAST(AV1E_SET_MIN_GF_INTERVAL, args);
  return update_extra_cfg(ctx, &extra_cfg);
}

static aom_codec_err_t ctrl_set_max_gf_interval(aom_codec_alg_priv_t *ctx,
                                                va_list args) {
  struct av1_extracfg extra_cfg = ctx->extra_cfg;
  extra_cfg.max_gf_interval = CAST(AV1E_SET_MAX_GF_INTERVAL, args);
  return update_extra_cfg(ctx, &extra_cfg);
}

static aom_codec_err_t ctrl_set_gf_min_pyr_height(aom_codec_alg_priv_t *ctx,
                                                  va_list args) {
  struct av1_extracfg extra_cfg = ctx->extra_cfg;
  extra_cfg.gf_min_pyr_height = CAST(AV1E_SET_GF_MIN_PYRAMID_HEIGHT, args);
  return update_extra_cfg(ctx, &extra_cfg);
}

static aom_codec_err_t ctrl_set_gf_max_pyr_height(aom_codec_alg_priv_t *ctx,
                                                  va_list args) {
  struct av1_extracfg extra_cfg = ctx->extra_cfg;
  extra_cfg.gf_max_pyr_height = CAST(AV1E_SET_GF_MAX_PYRAMID_HEIGHT, args);
  return update_extra_cfg(ctx, &extra_cfg);
}

static aom_codec_err_t ctrl_set_frame_periodic_boost(aom_codec_alg_priv_t *ctx,
                                                     va_list args) {
  struct av1_extracfg extra_cfg = ctx->extra_cfg;
  extra_cfg.frame_periodic_boost = CAST(AV1E_SET_FRAME_PERIODIC_BOOST, args);
  return update_extra_cfg(ctx, &extra_cfg);
}

static aom_codec_err_t ctrl_enable_motion_vector_unit_test(
    aom_codec_alg_priv_t *ctx, va_list args) {
  struct av1_extracfg extra_cfg = ctx->extra_cfg;
  extra_cfg.motion_vector_unit_test =
      CAST(AV1E_ENABLE_MOTION_VECTOR_UNIT_TEST, args);
  return update_extra_cfg(ctx, &extra_cfg);
}

static aom_codec_err_t ctrl_enable_fpmt_unit_test(aom_codec_alg_priv_t *ctx,
                                                  va_list args) {
#if !(CONFIG_FRAME_PARALLEL_ENCODE && CONFIG_FPMT_TEST)
  (void)args;
  (void)ctx;
  return AOM_CODEC_INCAPABLE;
#else
  struct av1_extracfg extra_cfg = ctx->extra_cfg;
  extra_cfg.fpmt_unit_test = CAST(AV1E_SET_FP_MT_UNIT_TEST, args);
  ctx->ppi->fpmt_unit_test_cfg = (extra_cfg.fpmt_unit_test == 1)
                                     ? PARALLEL_ENCODE
                                     : PARALLEL_SIMULATION_ENCODE;
  return update_extra_cfg(ctx, &extra_cfg);
#endif
}

static aom_codec_err_t ctrl_enable_ext_tile_debug(aom_codec_alg_priv_t *ctx,
                                                  va_list args) {
  struct av1_extracfg extra_cfg = ctx->extra_cfg;
  extra_cfg.ext_tile_debug = CAST(AV1E_ENABLE_EXT_TILE_DEBUG, args);
  return update_extra_cfg(ctx, &extra_cfg);
}

static aom_codec_err_t ctrl_set_target_seq_level_idx(aom_codec_alg_priv_t *ctx,
                                                     va_list args) {
  struct av1_extracfg extra_cfg = ctx->extra_cfg;
  const int val = CAST(AV1E_SET_TARGET_SEQ_LEVEL_IDX, args);
  const int level = val % 100;
  const int operating_point_idx = val / 100;
  if (operating_point_idx >= 0 &&
      operating_point_idx < MAX_NUM_OPERATING_POINTS) {
    extra_cfg.target_seq_level_idx[operating_point_idx] = (AV1_LEVEL)level;
  }
  return update_extra_cfg(ctx, &extra_cfg);
}

static aom_codec_err_t ctrl_set_tier_mask(aom_codec_alg_priv_t *ctx,
                                          va_list args) {
  struct av1_extracfg extra_cfg = ctx->extra_cfg;
  extra_cfg.tier_mask = CAST(AV1E_SET_TIER_MASK, args);
  return update_extra_cfg(ctx, &extra_cfg);
}

static aom_codec_err_t ctrl_set_min_cr(aom_codec_alg_priv_t *ctx,
                                       va_list args) {
  struct av1_extracfg extra_cfg = ctx->extra_cfg;
  extra_cfg.min_cr = CAST(AV1E_SET_MIN_CR, args);
  return update_extra_cfg(ctx, &extra_cfg);
}

static aom_codec_err_t ctrl_enable_sb_multipass_unit_test(
    aom_codec_alg_priv_t *ctx, va_list args) {
  struct av1_extracfg extra_cfg = ctx->extra_cfg;
  extra_cfg.sb_multipass_unit_test =
      CAST(AV1E_ENABLE_SB_MULTIPASS_UNIT_TEST, args);
  return update_extra_cfg(ctx, &extra_cfg);
}

static aom_codec_err_t ctrl_set_external_partition(aom_codec_alg_priv_t *ctx,
                                                   va_list args) {
  AV1_COMP *const cpi = ctx->ppi->cpi;
  aom_ext_part_funcs_t funcs = *CAST(AV1E_SET_EXTERNAL_PARTITION, args);
  aom_ext_part_config_t config;
  // TODO(chengchen): verify the sb_size has been set at this point.
  config.superblock_size = cpi->common.seq_params->sb_size;
  const aom_codec_err_t status =
      av1_ext_part_create(funcs, config, &cpi->ext_part_controller);
  return status;
}

static aom_codec_err_t ctrl_set_loopfilter_control(aom_codec_alg_priv_t *ctx,
                                                   va_list args) {
  struct av1_extracfg extra_cfg = ctx->extra_cfg;
  extra_cfg.loopfilter_control = CAST(AV1E_SET_LOOPFILTER_CONTROL, args);
  return update_extra_cfg(ctx, &extra_cfg);
}

static aom_codec_err_t ctrl_set_rtc_external_rc(aom_codec_alg_priv_t *ctx,
                                                va_list args) {
  ctx->ppi->cpi->rc.rtc_external_ratectrl =
      CAST(AV1E_SET_RTC_EXTERNAL_RC, args);
  return AOM_CODEC_OK;
}

#if !CONFIG_REALTIME_ONLY
static aom_codec_err_t create_stats_buffer(FIRSTPASS_STATS **frame_stats_buffer,
                                           STATS_BUFFER_CTX *stats_buf_context,
                                           int num_lap_buffers) {
  aom_codec_err_t res = AOM_CODEC_OK;

  int size = get_stats_buf_size(num_lap_buffers, MAX_LAG_BUFFERS);
  *frame_stats_buffer =
      (FIRSTPASS_STATS *)aom_calloc(size, sizeof(FIRSTPASS_STATS));
  if (*frame_stats_buffer == NULL) return AOM_CODEC_MEM_ERROR;

  stats_buf_context->stats_in_start = *frame_stats_buffer;
  stats_buf_context->stats_in_end = stats_buf_context->stats_in_start;
  stats_buf_context->stats_in_buf_end =
      stats_buf_context->stats_in_start + size;

  stats_buf_context->total_left_stats = aom_calloc(1, sizeof(FIRSTPASS_STATS));
  if (stats_buf_context->total_left_stats == NULL) return AOM_CODEC_MEM_ERROR;
  av1_twopass_zero_stats(stats_buf_context->total_left_stats);
  stats_buf_context->total_stats = aom_calloc(1, sizeof(FIRSTPASS_STATS));
  if (stats_buf_context->total_stats == NULL) return AOM_CODEC_MEM_ERROR;
  av1_twopass_zero_stats(stats_buf_context->total_stats);
  return res;
}
#endif

static aom_codec_err_t create_context_and_bufferpool(
    AV1_PRIMARY *ppi, AV1_COMP **p_cpi, BufferPool **p_buffer_pool,
    AV1EncoderConfig *oxcf, COMPRESSOR_STAGE stage, int lap_lag_in_frames) {
  aom_codec_err_t res = AOM_CODEC_OK;

  if (*p_buffer_pool == NULL) {
    *p_buffer_pool = (BufferPool *)aom_calloc(1, sizeof(BufferPool));
    if (*p_buffer_pool == NULL) return AOM_CODEC_MEM_ERROR;

#if CONFIG_MULTITHREAD
    if (pthread_mutex_init(&((*p_buffer_pool)->pool_mutex), NULL)) {
      return AOM_CODEC_MEM_ERROR;
    }
#endif
  }
  *p_cpi = av1_create_compressor(ppi, oxcf, *p_buffer_pool, stage,
                                 lap_lag_in_frames);
  if (*p_cpi == NULL) res = AOM_CODEC_MEM_ERROR;

  return res;
}

static aom_codec_err_t ctrl_set_fp_mt(aom_codec_alg_priv_t *ctx, va_list args) {
#if !CONFIG_FRAME_PARALLEL_ENCODE
  (void)args;
  (void)ctx;
  return AOM_CODEC_INCAPABLE;
#else
  struct av1_extracfg extra_cfg = ctx->extra_cfg;
  extra_cfg.fp_mt = CAST(AV1E_SET_FP_MT, args);
  const aom_codec_err_t result = update_extra_cfg(ctx, &extra_cfg);
  int num_fp_contexts = 1;
  if (ctx->ppi->num_fp_contexts == 1) {
    num_fp_contexts =
        av1_compute_num_fp_contexts(ctx->ppi, &ctx->ppi->parallel_cpi[0]->oxcf);
    if (num_fp_contexts > 1) {
      int i;
      for (i = 1; i < num_fp_contexts; i++) {
        int res = create_context_and_bufferpool(
            ctx->ppi, &ctx->ppi->parallel_cpi[i], &ctx->buffer_pool, &ctx->oxcf,
            ENCODE_STAGE, -1);
        if (res != AOM_CODEC_OK) {
          return res;
        }
#if !CONFIG_REALTIME_ONLY
        ctx->ppi->parallel_cpi[i]->twopass_frame.stats_in =
            ctx->ppi->twopass.stats_buf_ctx->stats_in_start;
#endif
      }
    }
  }
  ctx->ppi->num_fp_contexts = num_fp_contexts;
  return result;
#endif
}

static aom_codec_err_t ctrl_set_auto_intra_tools_off(aom_codec_alg_priv_t *ctx,
                                                     va_list args) {
  struct av1_extracfg extra_cfg = ctx->extra_cfg;
  extra_cfg.auto_intra_tools_off = CAST(AV1E_SET_AUTO_INTRA_TOOLS_OFF, args);
  return update_extra_cfg(ctx, &extra_cfg);
}

static aom_codec_err_t encoder_init(aom_codec_ctx_t *ctx) {
  aom_codec_err_t res = AOM_CODEC_OK;

  if (ctx->priv == NULL) {
    aom_codec_alg_priv_t *const priv = aom_calloc(1, sizeof(*priv));
    if (priv == NULL) return AOM_CODEC_MEM_ERROR;

    ctx->priv = (aom_codec_priv_t *)priv;
    ctx->priv->init_flags = ctx->init_flags;

    // Update the reference to the config structure to an internal copy.
    assert(ctx->config.enc);
    priv->cfg = *ctx->config.enc;
    ctx->config.enc = &priv->cfg;

    priv->extra_cfg = default_extra_cfg;
    // Special handling:
    // By default, if omitted, --enable-cdef = 1.
    // Here we set its default value to 0 when --allintra is turned on.
    // However, if users set --enable-cdef = 1 from command line,
    // The encoder still respects it.
    if (priv->cfg.g_usage == ALLINTRA) {
      priv->extra_cfg.enable_cdef = 0;
    }
    av1_initialize_enc(priv->cfg.g_usage, priv->cfg.rc_end_usage);

    res = validate_config(priv, &priv->cfg, &priv->extra_cfg);

    if (res == AOM_CODEC_OK) {
      int *num_lap_buffers = &priv->num_lap_buffers;
      int lap_lag_in_frames = 0;
      *num_lap_buffers = 0;
      priv->timestamp_ratio.den = priv->cfg.g_timebase.den;
      priv->timestamp_ratio.num =
          (int64_t)priv->cfg.g_timebase.num * TICKS_PER_SEC;
      reduce_ratio(&priv->timestamp_ratio);

      set_encoder_config(&priv->oxcf, &priv->cfg, &priv->extra_cfg);
      if (priv->oxcf.rc_cfg.mode != AOM_CBR &&
          priv->oxcf.pass == AOM_RC_ONE_PASS && priv->oxcf.mode == GOOD) {
        // Enable look ahead - enabled for AOM_Q, AOM_CQ, AOM_VBR
        *num_lap_buffers =
            AOMMIN((int)priv->cfg.g_lag_in_frames,
                   AOMMIN(MAX_LAP_BUFFERS, priv->oxcf.kf_cfg.key_freq_max +
                                               SCENE_CUT_KEY_TEST_INTERVAL));
        if ((int)priv->cfg.g_lag_in_frames - (*num_lap_buffers) >=
            LAP_LAG_IN_FRAMES) {
          lap_lag_in_frames = LAP_LAG_IN_FRAMES;
        }
      }
      priv->oxcf.use_highbitdepth =
          (ctx->init_flags & AOM_CODEC_USE_HIGHBITDEPTH) ? 1 : 0;

      priv->ppi = av1_create_primary_compressor(&priv->pkt_list.head,
                                                *num_lap_buffers, &priv->oxcf);
      if (!priv->ppi) return AOM_CODEC_MEM_ERROR;

#if !CONFIG_REALTIME_ONLY
      res = create_stats_buffer(&priv->frame_stats_buffer,
                                &priv->stats_buf_context, *num_lap_buffers);
      if (res != AOM_CODEC_OK) return AOM_CODEC_MEM_ERROR;

      assert(MAX_LAP_BUFFERS >= MAX_LAG_BUFFERS);
      int size = get_stats_buf_size(*num_lap_buffers, MAX_LAG_BUFFERS);
      for (int i = 0; i < size; i++)
        priv->ppi->twopass.frame_stats_arr[i] = &priv->frame_stats_buffer[i];

      priv->ppi->twopass.stats_buf_ctx = &priv->stats_buf_context;
#endif

#if CONFIG_FRAME_PARALLEL_ENCODE
      assert(priv->ppi->num_fp_contexts >= 1);
      res = create_context_and_bufferpool(
          priv->ppi, &priv->ppi->parallel_cpi[0], &priv->buffer_pool,
          &priv->oxcf, ENCODE_STAGE, -1);
      if (res != AOM_CODEC_OK) {
        return res;
      }
#if !CONFIG_REALTIME_ONLY
      priv->ppi->parallel_cpi[0]->twopass_frame.stats_in =
          priv->ppi->twopass.stats_buf_ctx->stats_in_start;
#endif
      priv->ppi->cpi = priv->ppi->parallel_cpi[0];
#else
      res = create_context_and_bufferpool(priv->ppi, &priv->ppi->cpi,
                                          &priv->buffer_pool, &priv->oxcf,
                                          ENCODE_STAGE, -1);
#if !CONFIG_REALTIME_ONLY
      priv->ppi->cpi->twopass_frame.stats_in =
          priv->ppi->twopass.stats_buf_ctx->stats_in_start;
#endif
#endif  // CONFIG_FRAME_PARALLEL_ENCODE

      // Create another compressor if look ahead is enabled
      if (res == AOM_CODEC_OK && *num_lap_buffers) {
        res = create_context_and_bufferpool(
            priv->ppi, &priv->ppi->cpi_lap, &priv->buffer_pool_lap, &priv->oxcf,
            LAP_STAGE, clamp(lap_lag_in_frames, 0, MAX_LAG_BUFFERS));
      }
    }
  }

  return res;
}

static void destroy_context_and_bufferpool(AV1_COMP *cpi,
                                           BufferPool **p_buffer_pool) {
  av1_remove_compressor(cpi);
  if (*p_buffer_pool) {
    av1_free_ref_frame_buffers(*p_buffer_pool);
#if CONFIG_MULTITHREAD
    pthread_mutex_destroy(&(*p_buffer_pool)->pool_mutex);
#endif
    aom_free(*p_buffer_pool);
    *p_buffer_pool = NULL;
  }
}

static void destroy_stats_buffer(STATS_BUFFER_CTX *stats_buf_context,
                                 FIRSTPASS_STATS *frame_stats_buffer) {
  aom_free(stats_buf_context->total_left_stats);
  aom_free(stats_buf_context->total_stats);
  aom_free(frame_stats_buffer);
}

static void check_and_free_string(const char *default_str, const char **ptr) {
  if (*ptr == default_str) {
    // Default should be a literal. Do not free.
    return;
  }
  aom_free((void *)*ptr);
  *ptr = NULL;
}

static void destroy_extra_config(struct av1_extracfg *extra_cfg) {
#if CONFIG_TUNE_VMAF
  check_and_free_string(default_extra_cfg.vmaf_model_path,
                        &extra_cfg->vmaf_model_path);
#endif
  check_and_free_string(default_extra_cfg.two_pass_output,
                        &extra_cfg->two_pass_output);
  check_and_free_string(default_extra_cfg.two_pass_output,
                        &extra_cfg->second_pass_log);
  check_and_free_string(default_extra_cfg.partition_info_path,
                        &extra_cfg->partition_info_path);
  check_and_free_string(default_extra_cfg.film_grain_table_filename,
                        &extra_cfg->film_grain_table_filename);
}

static aom_codec_err_t encoder_destroy(aom_codec_alg_priv_t *ctx) {
  free(ctx->cx_data);
  destroy_extra_config(&ctx->extra_cfg);

  if (ctx->ppi) {
    AV1_PRIMARY *ppi = ctx->ppi;
#if CONFIG_FRAME_PARALLEL_ENCODE
    for (int i = 0; i < MAX_PARALLEL_FRAMES - 1; i++) {
      if (ppi->parallel_frames_data[i].cx_data) {
        free(ppi->parallel_frames_data[i].cx_data);
      }
    }
#endif
#if CONFIG_ENTROPY_STATS
    print_entropy_stats(ppi);
#endif
#if CONFIG_INTERNAL_STATS
    print_internal_stats(ppi);
#endif
#if CONFIG_FRAME_PARALLEL_ENCODE
    int i;
    for (i = 0; i < MAX_PARALLEL_FRAMES; i++) {
      destroy_context_and_bufferpool(ppi->parallel_cpi[i], &ctx->buffer_pool);
    }
    ppi->cpi = NULL;
#else
    destroy_context_and_bufferpool(ppi->cpi, &ctx->buffer_pool);
#endif  // CONFIG_FRAME_PARALLEL_ENCODE
    if (ppi->cpi_lap) {
      destroy_context_and_bufferpool(ppi->cpi_lap, &ctx->buffer_pool_lap);
    }
    av1_remove_primary_compressor(ppi);
  }
  destroy_stats_buffer(&ctx->stats_buf_context, ctx->frame_stats_buffer);
  aom_free(ctx);
  return AOM_CODEC_OK;
}

static aom_codec_frame_flags_t get_frame_pkt_flags(const AV1_COMP *cpi,
                                                   unsigned int lib_flags) {
  aom_codec_frame_flags_t flags = lib_flags << 16;
  if (lib_flags & FRAMEFLAGS_KEY) flags |= AOM_FRAME_IS_KEY;
  if (lib_flags & FRAMEFLAGS_INTRAONLY) flags |= AOM_FRAME_IS_INTRAONLY;
  if (lib_flags & FRAMEFLAGS_SWITCH) flags |= AOM_FRAME_IS_SWITCH;
  if (lib_flags & FRAMEFLAGS_ERROR_RESILIENT)
    flags |= AOM_FRAME_IS_ERROR_RESILIENT;
  if (cpi->droppable) flags |= AOM_FRAME_IS_DROPPABLE;

  return flags;
}

// TODO(Mufaddal): Check feasibility of abstracting functions related to LAP
// into a separate function.
static aom_codec_err_t encoder_encode(aom_codec_alg_priv_t *ctx,
                                      const aom_image_t *img,
                                      aom_codec_pts_t pts,
                                      unsigned long duration,
                                      aom_enc_frame_flags_t enc_flags) {
  const size_t kMinCompressedSize = 8192;
  volatile aom_codec_err_t res = AOM_CODEC_OK;
  AV1_PRIMARY *const ppi = ctx->ppi;
  volatile aom_codec_pts_t ptsvol = pts;
  AV1_COMP_DATA cpi_data = { 0 };

  cpi_data.timestamp_ratio = &ctx->timestamp_ratio;
  cpi_data.flush = !img;
  // LAP context
  AV1_COMP *cpi_lap = ppi->cpi_lap;
  if (ppi->cpi == NULL) return AOM_CODEC_INVALID_PARAM;

  if (ppi->lap_enabled && cpi_lap == NULL &&
      ppi->cpi->oxcf.pass == AOM_RC_ONE_PASS)
    return AOM_CODEC_INVALID_PARAM;

  if (img != NULL) {
    res = validate_img(ctx, img);
    if (res == AOM_CODEC_OK) {
      const size_t uncompressed_frame_sz = ALIGN_POWER_OF_TWO(ctx->cfg.g_w, 5) *
                                           ALIGN_POWER_OF_TWO(ctx->cfg.g_h, 5) *
                                           get_image_bps(img) / 8;

      // Due to the presence of no-show frames, the ctx->cx_data buffer holds
      // compressed data corresponding to multiple frames. As no-show frames are
      // not possible for all intra frame encoding with no forward key frames,
      // the buffer is allocated with a smaller size in this case.
      //
      // For pseudo random input, the compressed frame size is seen to exceed
      // the uncompressed frame size, but is less than 2 times the uncompressed
      // frame size. Hence the size of the buffer is chosen as 2 times the
      // uncompressed frame size.
      int multiplier = 8;
      if (ppi->cpi->oxcf.kf_cfg.key_freq_max == 0 &&
          !ppi->cpi->oxcf.kf_cfg.fwd_kf_enabled)
        multiplier = 2;
      size_t data_sz = uncompressed_frame_sz * multiplier;
      if (data_sz < kMinCompressedSize) data_sz = kMinCompressedSize;
      if (ctx->cx_data == NULL || ctx->cx_data_sz < data_sz) {
        ctx->cx_data_sz = data_sz;
        free(ctx->cx_data);
        ctx->cx_data = (unsigned char *)malloc(ctx->cx_data_sz);
        if (ctx->cx_data == NULL) {
          ctx->cx_data_sz = 0;
          return AOM_CODEC_MEM_ERROR;
        }
      }
#if CONFIG_FRAME_PARALLEL_ENCODE
      for (int i = 0; i < ppi->num_fp_contexts - 1; i++) {
        if (ppi->parallel_frames_data[i].cx_data == NULL) {
          ppi->parallel_frames_data[i].cx_data_sz = uncompressed_frame_sz;
          ppi->parallel_frames_data[i].frame_display_order_hint = -1;
          ppi->parallel_frames_data[i].frame_size = 0;
          ppi->parallel_frames_data[i].cx_data =
              (unsigned char *)malloc(ppi->parallel_frames_data[i].cx_data_sz);
          if (ppi->parallel_frames_data[i].cx_data == NULL) {
            ppi->parallel_frames_data[i].cx_data_sz = 0;
            return AOM_CODEC_MEM_ERROR;
          }
        }
      }
#endif
    }
  }

  aom_codec_pkt_list_init(&ctx->pkt_list);

  volatile aom_enc_frame_flags_t flags = enc_flags;

  // The jmp_buf is valid only for the duration of the function that calls
  // setjmp(). Therefore, this function must reset the 'setjmp' field to 0
  // before it returns.
  if (setjmp(ppi->error.jmp)) {
    ppi->error.setjmp = 0;
    res = update_error_state(ctx, &ppi->error);
    return res;
  }
  ppi->error.setjmp = 1;

  if (ppi->use_svc && ppi->cpi->svc.use_flexible_mode == 0 && flags == 0)
    av1_set_svc_fixed_mode(ppi->cpi);

  // Note(yunqing): While applying encoding flags, always start from enabling
  // all, and then modifying according to the flags. Previous frame's flags are
  // overwritten.
  av1_apply_encoding_flags(ppi->cpi, flags);
  if (cpi_lap != NULL) {
    av1_apply_encoding_flags(cpi_lap, flags);
  }

#if CONFIG_TUNE_VMAF
  if (ctx->extra_cfg.tuning >= AOM_TUNE_VMAF_WITH_PREPROCESSING &&
      ctx->extra_cfg.tuning <= AOM_TUNE_VMAF_NEG_MAX_GAIN) {
    aom_init_vmaf_model(&ppi->cpi->vmaf_info.vmaf_model,
                        ppi->cpi->oxcf.tune_cfg.vmaf_model_path);
  }
#endif

  // Handle fixed keyframe intervals
  if (is_stat_generation_stage(ppi->cpi) || is_one_pass_rt_params(ppi->cpi)) {
    if (ctx->cfg.kf_mode == AOM_KF_AUTO &&
        ctx->cfg.kf_min_dist == ctx->cfg.kf_max_dist) {
      if (ppi->cpi->common.spatial_layer_id == 0 &&
          ++ctx->fixed_kf_cntr > ctx->cfg.kf_min_dist) {
        flags |= AOM_EFLAG_FORCE_KF;
        ctx->fixed_kf_cntr = 1;
      }
    }
  }

  if (res == AOM_CODEC_OK) {
#if CONFIG_FRAME_PARALLEL_ENCODE
    AV1_COMP *cpi = ppi->cpi;
#else
    AV1_COMP *const cpi = ppi->cpi;
#endif

    // Set up internal flags
    if (ctx->base.init_flags & AOM_CODEC_USE_PSNR) ppi->b_calculate_psnr = 1;

    if (img != NULL) {
      if (!ctx->pts_offset_initialized) {
        ctx->pts_offset = ptsvol;
        ctx->pts_offset_initialized = 1;
      }
      ptsvol -= ctx->pts_offset;
      int64_t src_time_stamp =
          timebase_units_to_ticks(cpi_data.timestamp_ratio, ptsvol);
      int64_t src_end_time_stamp =
          timebase_units_to_ticks(cpi_data.timestamp_ratio, ptsvol + duration);

      YV12_BUFFER_CONFIG sd;
      res = image2yuvconfig(img, &sd);
      // When generating a monochrome stream, make |sd| a monochrome image.
      if (ctx->cfg.monochrome) {
        sd.u_buffer = sd.v_buffer = NULL;
        sd.uv_stride = 0;
        sd.monochrome = 1;
      }
      int use_highbitdepth = (sd.flags & YV12_FLAG_HIGHBITDEPTH) != 0;
      int subsampling_x = sd.subsampling_x;
      int subsampling_y = sd.subsampling_y;

      if (!ppi->lookahead) {
        int lag_in_frames = cpi_lap != NULL ? cpi_lap->oxcf.gf_cfg.lag_in_frames
                                            : cpi->oxcf.gf_cfg.lag_in_frames;

        ppi->lookahead = av1_lookahead_init(
            cpi->oxcf.frm_dim_cfg.width, cpi->oxcf.frm_dim_cfg.height,
            subsampling_x, subsampling_y, use_highbitdepth, lag_in_frames,
            cpi->oxcf.border_in_pixels, cpi->common.features.byte_alignment,
            ctx->num_lap_buffers, (cpi->oxcf.kf_cfg.key_freq_max == 0),
            cpi->oxcf.tool_cfg.enable_global_motion);
      }
      if (!ppi->lookahead)
        aom_internal_error(&ppi->error, AOM_CODEC_MEM_ERROR,
                           "Failed to allocate lag buffers");
#if CONFIG_FRAME_PARALLEL_ENCODE
      int i;
      for (i = 0; i < ppi->num_fp_contexts; i++) {
        av1_check_initial_width(ppi->parallel_cpi[i], use_highbitdepth,
                                subsampling_x, subsampling_y);
      }
#else
      av1_check_initial_width(cpi, use_highbitdepth, subsampling_x,
                              subsampling_y);
#endif
      if (cpi_lap != NULL) {
        av1_check_initial_width(cpi_lap, use_highbitdepth, subsampling_x,
                                subsampling_y);
      }

      // Store the original flags in to the frame buffer. Will extract the
      // key frame flag when we actually encode this frame.
      if (av1_receive_raw_frame(cpi, flags | ctx->next_frame_flags, &sd,
                                src_time_stamp, src_end_time_stamp)) {
        res = update_error_state(ctx, &ppi->error);
      }
      ctx->next_frame_flags = 0;
    }

    cpi_data.cx_data = ctx->cx_data;
    cpi_data.cx_data_sz = ctx->cx_data_sz;

    /* Any pending invisible frames? */
    if (ctx->pending_cx_data_sz) {
      cpi_data.cx_data += ctx->pending_cx_data_sz;
      cpi_data.cx_data_sz -= ctx->pending_cx_data_sz;

      /* TODO: this is a minimal check, the underlying codec doesn't respect
       * the buffer size anyway.
       */
      if (cpi_data.cx_data_sz < ctx->cx_data_sz / 2) {
        aom_internal_error(&ppi->error, AOM_CODEC_ERROR,
                           "Compressed data buffer too small");
      }
    }

    int is_frame_visible = 0;
    int has_no_show_keyframe = 0;
    int num_workers = 0;

    if (cpi->oxcf.pass == AOM_RC_FIRST_PASS) {
#if !CONFIG_REALTIME_ONLY
      num_workers = ppi->p_mt_info.num_mod_workers[MOD_FP] =
          av1_fp_compute_num_enc_workers(cpi);
#endif
    } else {
      av1_compute_num_workers_for_mt(cpi);
      num_workers = av1_get_max_num_workers(cpi);
    }
    if ((num_workers > 1) && (ppi->p_mt_info.num_workers == 0)) {
#if CONFIG_FRAME_PARALLEL_ENCODE
      // Obtain the maximum no. of frames that can be supported in a parallel
      // encode set.
      if (is_stat_consumption_stage(cpi)) {
        ppi->num_fp_contexts = av1_compute_num_fp_contexts(ppi, &cpi->oxcf);
      }
#endif  // CONFIG_FRAME_PARALLEL_ENCODE
      av1_create_workers(ppi, num_workers);
      av1_init_tile_thread_data(ppi, cpi->oxcf.pass == AOM_RC_FIRST_PASS);
#if CONFIG_MULTITHREAD
#if CONFIG_FRAME_PARALLEL_ENCODE
      for (int i = 0; i < ppi->num_fp_contexts; i++) {
        av1_init_mt_sync(ppi->parallel_cpi[i],
                         ppi->parallel_cpi[i]->oxcf.pass == AOM_RC_FIRST_PASS);
      }
#else
      av1_init_mt_sync(cpi, cpi->oxcf.pass == 1);
#endif  // CONFIG_FRAME_PARALLEL_ENCODE
      if (cpi_lap != NULL) {
        av1_init_mt_sync(cpi_lap, 1);
      }
#endif  // CONFIG_MULTITHREAD
    }
#if CONFIG_FRAME_PARALLEL_ENCODE
    for (int i = 0; i < ppi->num_fp_contexts; i++) {
      av1_init_frame_mt(ppi, ppi->parallel_cpi[i]);
    }
#else
    av1_init_frame_mt(ppi, cpi);
#endif  // CONFIG_FRAME_PARALLEL_ENCODE
    if (cpi_lap != NULL) {
      av1_init_frame_mt(ppi, cpi_lap);
    }

    // Call for LAP stage
    if (cpi_lap != NULL) {
      AV1_COMP_DATA cpi_lap_data = { 0 };
      cpi_lap_data.flush = !img;
      cpi_lap_data.timestamp_ratio = &ctx->timestamp_ratio;
      const int status = av1_get_compressed_data(cpi_lap, &cpi_lap_data);
      if (status != -1) {
        if (status != AOM_CODEC_OK) {
          aom_internal_error(&ppi->error, AOM_CODEC_ERROR, NULL);
        }
      }
      av1_post_encode_updates(cpi_lap, &cpi_lap_data);
    }

#if CONFIG_FRAME_PARALLEL_ENCODE
    // Recalculate the maximum number of frames that can be encoded in
    // parallel at the beginning of sub gop.
    if (is_stat_consumption_stage(cpi) && ppi->gf_group.size > 0 &&
        cpi->gf_frame_index == ppi->gf_group.size) {
      ppi->num_fp_contexts = av1_compute_num_fp_contexts(ppi, &cpi->oxcf);
    }
#endif  // CONFIG_FRAME_PARALLEL_ENCODE

    // Get the next visible frame. Invisible frames get packed with the next
    // visible frame.
    while (cpi_data.cx_data_sz >= ctx->cx_data_sz / 2 && !is_frame_visible) {
#if CONFIG_FRAME_PARALLEL_ENCODE
      int simulate_parallel_frame = 0;
      int status = -1;
      cpi->do_frame_data_update = true;
#if CONFIG_FRAME_PARALLEL_ENCODE_2
      cpi->ref_idx_to_skip = INVALID_IDX;
      cpi->ref_refresh_index = INVALID_IDX;
      cpi->refresh_idx_available = false;
#endif  // CONFIG_FRAME_PARALLEL_ENCODE_2

#if CONFIG_FPMT_TEST
      simulate_parallel_frame =
          cpi->ppi->fpmt_unit_test_cfg == PARALLEL_SIMULATION_ENCODE ? 1 : 0;
      if (simulate_parallel_frame) {
        if (ppi->num_fp_contexts > 1 && ppi->gf_group.size > 1) {
          if (cpi->gf_frame_index < ppi->gf_group.size) {
            calc_frame_data_update_flag(&ppi->gf_group, cpi->gf_frame_index,
                                        &cpi->do_frame_data_update);
          }
        }
        status = av1_get_compressed_data(cpi, &cpi_data);
      }

#endif
      if (!simulate_parallel_frame) {
        if (ppi->gf_group.frame_parallel_level[cpi->gf_frame_index] == 0) {
          status = av1_get_compressed_data(cpi, &cpi_data);
        } else if (ppi->gf_group.frame_parallel_level[cpi->gf_frame_index] ==
                   1) {
          status = av1_compress_parallel_frames(ppi, &cpi_data);
        } else {
          cpi = av1_get_parallel_frame_enc_data(ppi, &cpi_data);
          status = AOM_CODEC_OK;
        }
      }
#else
      const int status = av1_get_compressed_data(cpi, &cpi_data);
#endif  // CONFIG_FRAME_PARALLEL_ENCODE
      if (status == -1) break;
      if (status != AOM_CODEC_OK) {
        aom_internal_error(&ppi->error, AOM_CODEC_ERROR, NULL);
      }
#if CONFIG_FRAME_PARALLEL_ENCODE
      if (ppi->num_fp_contexts > 0 && frame_is_intra_only(&cpi->common)) {
        av1_init_sc_decisions(ppi);
      }
#endif

      ppi->seq_params_locked = 1;
      av1_post_encode_updates(cpi, &cpi_data);

#if CONFIG_ENTROPY_STATS
      if (ppi->cpi->oxcf.pass != 1 && !cpi->common.show_existing_frame)
        av1_accumulate_frame_counts(&ppi->aggregate_fc, &cpi->counts);
#endif
#if CONFIG_INTERNAL_STATS
      if (ppi->cpi->oxcf.pass != 1) {
        ppi->total_time_compress_data += cpi->time_compress_data;
        ppi->total_recode_hits += cpi->frame_recode_hits;
        ppi->total_bytes += cpi->bytes;
        for (int i = 0; i < MAX_MODES; i++) {
          ppi->total_mode_chosen_counts[i] += cpi->mode_chosen_counts[i];
        }
      }
#endif  // CONFIG_INTERNAL_STATS

      if (!cpi_data.frame_size) continue;
      assert(cpi_data.cx_data != NULL && cpi_data.cx_data_sz != 0);
      const int write_temporal_delimiter =
          !cpi->common.spatial_layer_id && !ctx->pending_cx_data_sz;

      if (write_temporal_delimiter) {
        uint32_t obu_header_size = 1;
        const uint32_t obu_payload_size = 0;
        const size_t length_field_size =
            aom_uleb_size_in_bytes(obu_payload_size);

        const size_t move_offset = obu_header_size + length_field_size;
        memmove(ctx->cx_data + move_offset, ctx->cx_data, cpi_data.frame_size);
        obu_header_size =
            av1_write_obu_header(&ppi->level_params, &cpi->frame_header_count,
                                 OBU_TEMPORAL_DELIMITER, 0, ctx->cx_data);

        // OBUs are preceded/succeeded by an unsigned leb128 coded integer.
        if (av1_write_uleb_obu_size(obu_header_size, obu_payload_size,
                                    ctx->cx_data) != AOM_CODEC_OK) {
          aom_internal_error(&ppi->error, AOM_CODEC_ERROR, NULL);
        }

        cpi_data.frame_size +=
            obu_header_size + obu_payload_size + length_field_size;
      }

      if (ctx->oxcf.save_as_annexb) {
        size_t curr_frame_size = cpi_data.frame_size;
        if (av1_convert_sect5obus_to_annexb(cpi_data.cx_data,
                                            &curr_frame_size) != AOM_CODEC_OK) {
          aom_internal_error(&ppi->error, AOM_CODEC_ERROR, NULL);
        }
        cpi_data.frame_size = curr_frame_size;

        // B_PRIME (add frame size)
        const size_t length_field_size =
            aom_uleb_size_in_bytes(cpi_data.frame_size);
        memmove(cpi_data.cx_data + length_field_size, cpi_data.cx_data,
                cpi_data.frame_size);
        if (av1_write_uleb_obu_size(0, (uint32_t)cpi_data.frame_size,
                                    cpi_data.cx_data) != AOM_CODEC_OK) {
          aom_internal_error(&ppi->error, AOM_CODEC_ERROR, NULL);
        }
        cpi_data.frame_size += length_field_size;
      }

      ctx->pending_cx_data_sz += cpi_data.frame_size;

      cpi_data.cx_data += cpi_data.frame_size;
      cpi_data.cx_data_sz -= cpi_data.frame_size;

      is_frame_visible = cpi->common.show_frame;

      has_no_show_keyframe |=
          (!is_frame_visible &&
           cpi->common.current_frame.frame_type == KEY_FRAME);
    }
    if (is_frame_visible) {
      // Add the frame packet to the list of returned packets.
      aom_codec_cx_pkt_t pkt;

      // decrement frames_left counter
      ppi->frames_left = AOMMAX(0, ppi->frames_left - 1);
      if (ctx->oxcf.save_as_annexb) {
        //  B_PRIME (add TU size)
        size_t tu_size = ctx->pending_cx_data_sz;
        const size_t length_field_size = aom_uleb_size_in_bytes(tu_size);
        memmove(ctx->cx_data + length_field_size, ctx->cx_data, tu_size);
        if (av1_write_uleb_obu_size(0, (uint32_t)tu_size, ctx->cx_data) !=
            AOM_CODEC_OK) {
          aom_internal_error(&ppi->error, AOM_CODEC_ERROR, NULL);
        }
        ctx->pending_cx_data_sz += length_field_size;
      }

      pkt.kind = AOM_CODEC_CX_FRAME_PKT;

      pkt.data.frame.buf = ctx->cx_data;
      pkt.data.frame.sz = ctx->pending_cx_data_sz;
      pkt.data.frame.partition_id = -1;
      pkt.data.frame.vis_frame_size = cpi_data.frame_size;

      pkt.data.frame.pts = ticks_to_timebase_units(cpi_data.timestamp_ratio,
                                                   cpi_data.ts_frame_start) +
                           ctx->pts_offset;
      pkt.data.frame.flags = get_frame_pkt_flags(cpi, cpi_data.lib_flags);
      if (has_no_show_keyframe) {
        // If one of the invisible frames in the packet is a keyframe, set
        // the delayed random access point flag.
        pkt.data.frame.flags |= AOM_FRAME_IS_DELAYED_RANDOM_ACCESS_POINT;
      }
      pkt.data.frame.duration = (uint32_t)ticks_to_timebase_units(
          cpi_data.timestamp_ratio,
          cpi_data.ts_frame_end - cpi_data.ts_frame_start);

      aom_codec_pkt_list_add(&ctx->pkt_list.head, &pkt);

      ctx->pending_cx_data_sz = 0;
    }
  }

  ppi->error.setjmp = 0;
  return res;
}

static const aom_codec_cx_pkt_t *encoder_get_cxdata(aom_codec_alg_priv_t *ctx,
                                                    aom_codec_iter_t *iter) {
  return aom_codec_pkt_list_get(&ctx->pkt_list.head, iter);
}

static aom_codec_err_t ctrl_set_reference(aom_codec_alg_priv_t *ctx,
                                          va_list args) {
  av1_ref_frame_t *const frame = va_arg(args, av1_ref_frame_t *);

  if (frame != NULL) {
    YV12_BUFFER_CONFIG sd;

    image2yuvconfig(&frame->img, &sd);
    av1_set_reference_enc(ctx->ppi->cpi, frame->idx, &sd);
    return AOM_CODEC_OK;
  } else {
    return AOM_CODEC_INVALID_PARAM;
  }
}

static aom_codec_err_t ctrl_copy_reference(aom_codec_alg_priv_t *ctx,
                                           va_list args) {
  av1_ref_frame_t *const frame = va_arg(args, av1_ref_frame_t *);

  if (frame != NULL) {
    YV12_BUFFER_CONFIG sd;

    image2yuvconfig(&frame->img, &sd);
    av1_copy_reference_enc(ctx->ppi->cpi, frame->idx, &sd);
    return AOM_CODEC_OK;
  } else {
    return AOM_CODEC_INVALID_PARAM;
  }
}

static aom_codec_err_t ctrl_get_reference(aom_codec_alg_priv_t *ctx,
                                          va_list args) {
  av1_ref_frame_t *const frame = va_arg(args, av1_ref_frame_t *);

  if (frame != NULL) {
    YV12_BUFFER_CONFIG *fb = get_ref_frame(&ctx->ppi->cpi->common, frame->idx);
    if (fb == NULL) return AOM_CODEC_ERROR;

    yuvconfig2image(&frame->img, fb, NULL);
    return AOM_CODEC_OK;
  } else {
    return AOM_CODEC_INVALID_PARAM;
  }
}

static aom_codec_err_t ctrl_get_new_frame_image(aom_codec_alg_priv_t *ctx,
                                                va_list args) {
  aom_image_t *const new_img = va_arg(args, aom_image_t *);

  if (new_img != NULL) {
    YV12_BUFFER_CONFIG new_frame;

    if (av1_get_last_show_frame(ctx->ppi->cpi, &new_frame) == 0) {
      yuvconfig2image(new_img, &new_frame, NULL);
      return AOM_CODEC_OK;
    } else {
      return AOM_CODEC_ERROR;
    }
  } else {
    return AOM_CODEC_INVALID_PARAM;
  }
}

static aom_codec_err_t ctrl_copy_new_frame_image(aom_codec_alg_priv_t *ctx,
                                                 va_list args) {
  aom_image_t *const new_img = va_arg(args, aom_image_t *);

  if (new_img != NULL) {
    YV12_BUFFER_CONFIG new_frame;

    if (av1_get_last_show_frame(ctx->ppi->cpi, &new_frame) == 0) {
      YV12_BUFFER_CONFIG sd;
      image2yuvconfig(new_img, &sd);
      return av1_copy_new_frame_enc(&ctx->ppi->cpi->common, &new_frame, &sd);
    } else {
      return AOM_CODEC_ERROR;
    }
  } else {
    return AOM_CODEC_INVALID_PARAM;
  }
}

static aom_image_t *encoder_get_preview(aom_codec_alg_priv_t *ctx) {
  YV12_BUFFER_CONFIG sd;

  if (av1_get_preview_raw_frame(ctx->ppi->cpi, &sd) == 0) {
    yuvconfig2image(&ctx->preview_img, &sd, NULL);
    return &ctx->preview_img;
  } else {
    return NULL;
  }
}

static aom_codec_err_t ctrl_use_reference(aom_codec_alg_priv_t *ctx,
                                          va_list args) {
  const int reference_flag = va_arg(args, int);

  av1_use_as_reference(&ctx->ppi->cpi->ext_flags.ref_frame_flags,
                       reference_flag);
  return AOM_CODEC_OK;
}

static aom_codec_err_t ctrl_set_roi_map(aom_codec_alg_priv_t *ctx,
                                        va_list args) {
  (void)ctx;
  (void)args;

  // TODO(yaowu): Need to re-implement and test for AV1.
  return AOM_CODEC_INVALID_PARAM;
}

static aom_codec_err_t ctrl_set_active_map(aom_codec_alg_priv_t *ctx,
                                           va_list args) {
  aom_active_map_t *const map = va_arg(args, aom_active_map_t *);

  if (map) {
    if (!av1_set_active_map(ctx->ppi->cpi, map->active_map, (int)map->rows,
                            (int)map->cols))
      return AOM_CODEC_OK;
    else
      return AOM_CODEC_INVALID_PARAM;
  } else {
    return AOM_CODEC_INVALID_PARAM;
  }
}

static aom_codec_err_t ctrl_get_active_map(aom_codec_alg_priv_t *ctx,
                                           va_list args) {
  aom_active_map_t *const map = va_arg(args, aom_active_map_t *);

  if (map) {
    if (!av1_get_active_map(ctx->ppi->cpi, map->active_map, (int)map->rows,
                            (int)map->cols))
      return AOM_CODEC_OK;
    else
      return AOM_CODEC_INVALID_PARAM;
  } else {
    return AOM_CODEC_INVALID_PARAM;
  }
}

static aom_codec_err_t ctrl_set_scale_mode(aom_codec_alg_priv_t *ctx,
                                           va_list args) {
  aom_scaling_mode_t *const mode = va_arg(args, aom_scaling_mode_t *);

  if (mode) {
    const int res = av1_set_internal_size(
        &ctx->ppi->cpi->oxcf, &ctx->ppi->cpi->resize_pending_params,
        (AOM_SCALING)mode->h_scaling_mode, (AOM_SCALING)mode->v_scaling_mode);
#if CONFIG_FRAME_PARALLEL_ENCODE
    av1_check_fpmt_config(ctx->ppi, &ctx->ppi->cpi->oxcf);
#endif
    return (res == 0) ? AOM_CODEC_OK : AOM_CODEC_INVALID_PARAM;
  } else {
    return AOM_CODEC_INVALID_PARAM;
  }
}

static aom_codec_err_t ctrl_set_spatial_layer_id(aom_codec_alg_priv_t *ctx,
                                                 va_list args) {
  const int spatial_layer_id = va_arg(args, int);
  if (spatial_layer_id >= MAX_NUM_SPATIAL_LAYERS)
    return AOM_CODEC_INVALID_PARAM;
  ctx->ppi->cpi->common.spatial_layer_id = spatial_layer_id;
  return AOM_CODEC_OK;
}

static aom_codec_err_t ctrl_set_number_spatial_layers(aom_codec_alg_priv_t *ctx,
                                                      va_list args) {
  const int number_spatial_layers = va_arg(args, int);
  if (number_spatial_layers > MAX_NUM_SPATIAL_LAYERS)
    return AOM_CODEC_INVALID_PARAM;
  ctx->ppi->number_spatial_layers = number_spatial_layers;
  return AOM_CODEC_OK;
}

static aom_codec_err_t ctrl_set_layer_id(aom_codec_alg_priv_t *ctx,
                                         va_list args) {
  aom_svc_layer_id_t *const data = va_arg(args, aom_svc_layer_id_t *);
  ctx->ppi->cpi->common.spatial_layer_id = data->spatial_layer_id;
  ctx->ppi->cpi->common.temporal_layer_id = data->temporal_layer_id;
  ctx->ppi->cpi->svc.spatial_layer_id = data->spatial_layer_id;
  ctx->ppi->cpi->svc.temporal_layer_id = data->temporal_layer_id;
  return AOM_CODEC_OK;
}

static aom_codec_err_t ctrl_set_svc_params(aom_codec_alg_priv_t *ctx,
                                           va_list args) {
  AV1_PRIMARY *const ppi = ctx->ppi;
  AV1_COMP *const cpi = ppi->cpi;
  AV1_COMMON *const cm = &cpi->common;
  aom_svc_params_t *const params = va_arg(args, aom_svc_params_t *);
  int64_t target_bandwidth = 0;
  ppi->number_spatial_layers = params->number_spatial_layers;
  ppi->number_temporal_layers = params->number_temporal_layers;
  cpi->svc.number_spatial_layers = params->number_spatial_layers;
  cpi->svc.number_temporal_layers = params->number_temporal_layers;
  if (ppi->number_spatial_layers > 1 || ppi->number_temporal_layers > 1) {
    unsigned int sl, tl;
    ctx->ppi->use_svc = 1;
    for (sl = 0; sl < ppi->number_spatial_layers; ++sl) {
      for (tl = 0; tl < ppi->number_temporal_layers; ++tl) {
        const int layer = LAYER_IDS_TO_IDX(sl, tl, ppi->number_temporal_layers);
        LAYER_CONTEXT *lc = &cpi->svc.layer_context[layer];
        lc->max_q = params->max_quantizers[layer];
        lc->min_q = params->min_quantizers[layer];
        lc->scaling_factor_num = params->scaling_factor_num[sl];
        lc->scaling_factor_den = params->scaling_factor_den[sl];
        lc->layer_target_bitrate = 1000 * params->layer_target_bitrate[layer];
        lc->framerate_factor = params->framerate_factor[tl];
        if (tl == ppi->number_temporal_layers - 1)
          target_bandwidth += lc->layer_target_bitrate;
      }
    }
    if (cm->current_frame.frame_number == 0) {
      if (!cpi->ppi->seq_params_locked) {
        SequenceHeader *const seq_params = &ppi->seq_params;
        seq_params->operating_points_cnt_minus_1 =
            ppi->number_spatial_layers * ppi->number_temporal_layers - 1;
        av1_init_seq_coding_tools(ppi, &cpi->oxcf, 1);
      }
      av1_init_layer_context(cpi);
    }
    av1_update_layer_context_change_config(cpi, target_bandwidth);
  }
#if CONFIG_FRAME_PARALLEL_ENCODE
  av1_check_fpmt_config(ctx->ppi, &ctx->ppi->cpi->oxcf);
#endif  // CONFIG_FRAME_PARALLEL_ENCODE
  return AOM_CODEC_OK;
}

static aom_codec_err_t ctrl_set_svc_ref_frame_config(aom_codec_alg_priv_t *ctx,
                                                     va_list args) {
  AV1_COMP *const cpi = ctx->ppi->cpi;
  aom_svc_ref_frame_config_t *const data =
      va_arg(args, aom_svc_ref_frame_config_t *);
  cpi->svc.set_ref_frame_config = 1;
  for (unsigned int i = 0; i < INTER_REFS_PER_FRAME; ++i) {
    cpi->svc.reference[i] = data->reference[i];
    cpi->svc.ref_idx[i] = data->ref_idx[i];
  }
  for (unsigned int i = 0; i < REF_FRAMES; ++i)
    cpi->svc.refresh[i] = data->refresh[i];
  cpi->svc.use_flexible_mode = 1;
  cpi->svc.ksvc_fixed_mode = 0;
  return AOM_CODEC_OK;
}

static aom_codec_err_t ctrl_set_svc_ref_frame_comp_pred(
    aom_codec_alg_priv_t *ctx, va_list args) {
  AV1_COMP *const cpi = ctx->ppi->cpi;
  aom_svc_ref_frame_comp_pred_t *const data =
      va_arg(args, aom_svc_ref_frame_comp_pred_t *);
  cpi->svc.ref_frame_comp[0] = data->use_comp_pred[0];
  cpi->svc.ref_frame_comp[1] = data->use_comp_pred[1];
  cpi->svc.ref_frame_comp[2] = data->use_comp_pred[2];
  return AOM_CODEC_OK;
}

static aom_codec_err_t ctrl_set_tune_content(aom_codec_alg_priv_t *ctx,
                                             va_list args) {
  struct av1_extracfg extra_cfg = ctx->extra_cfg;
  extra_cfg.content = CAST(AV1E_SET_TUNE_CONTENT, args);
  return update_extra_cfg(ctx, &extra_cfg);
}

static aom_codec_err_t ctrl_set_cdf_update_mode(aom_codec_alg_priv_t *ctx,
                                                va_list args) {
  struct av1_extracfg extra_cfg = ctx->extra_cfg;
  extra_cfg.cdf_update_mode = CAST(AV1E_SET_CDF_UPDATE_MODE, args);
  return update_extra_cfg(ctx, &extra_cfg);
}

static aom_codec_err_t ctrl_set_color_primaries(aom_codec_alg_priv_t *ctx,
                                                va_list args) {
  struct av1_extracfg extra_cfg = ctx->extra_cfg;
  extra_cfg.color_primaries = CAST(AV1E_SET_COLOR_PRIMARIES, args);
  return update_extra_cfg(ctx, &extra_cfg);
}

static aom_codec_err_t ctrl_set_transfer_characteristics(
    aom_codec_alg_priv_t *ctx, va_list args) {
  struct av1_extracfg extra_cfg = ctx->extra_cfg;
  extra_cfg.transfer_characteristics =
      CAST(AV1E_SET_TRANSFER_CHARACTERISTICS, args);
  return update_extra_cfg(ctx, &extra_cfg);
}

static aom_codec_err_t ctrl_set_matrix_coefficients(aom_codec_alg_priv_t *ctx,
                                                    va_list args) {
  struct av1_extracfg extra_cfg = ctx->extra_cfg;
  extra_cfg.matrix_coefficients = CAST(AV1E_SET_MATRIX_COEFFICIENTS, args);
  return update_extra_cfg(ctx, &extra_cfg);
}

static aom_codec_err_t ctrl_set_chroma_sample_position(
    aom_codec_alg_priv_t *ctx, va_list args) {
  struct av1_extracfg extra_cfg = ctx->extra_cfg;
  extra_cfg.chroma_sample_position =
      CAST(AV1E_SET_CHROMA_SAMPLE_POSITION, args);
  return update_extra_cfg(ctx, &extra_cfg);
}

static aom_codec_err_t ctrl_set_color_range(aom_codec_alg_priv_t *ctx,
                                            va_list args) {
  struct av1_extracfg extra_cfg = ctx->extra_cfg;
  extra_cfg.color_range = CAST(AV1E_SET_COLOR_RANGE, args);
  return update_extra_cfg(ctx, &extra_cfg);
}

static aom_codec_err_t ctrl_set_render_size(aom_codec_alg_priv_t *ctx,
                                            va_list args) {
  struct av1_extracfg extra_cfg = ctx->extra_cfg;
  int *const render_size = va_arg(args, int *);
  extra_cfg.render_width = render_size[0];
  extra_cfg.render_height = render_size[1];
  return update_extra_cfg(ctx, &extra_cfg);
}

static aom_codec_err_t ctrl_set_superblock_size(aom_codec_alg_priv_t *ctx,
                                                va_list args) {
  struct av1_extracfg extra_cfg = ctx->extra_cfg;
  extra_cfg.superblock_size = CAST(AV1E_SET_SUPERBLOCK_SIZE, args);
  return update_extra_cfg(ctx, &extra_cfg);
}

static aom_codec_err_t ctrl_set_chroma_subsampling_x(aom_codec_alg_priv_t *ctx,
                                                     va_list args) {
  struct av1_extracfg extra_cfg = ctx->extra_cfg;
  extra_cfg.chroma_subsampling_x = CAST(AV1E_SET_CHROMA_SUBSAMPLING_X, args);
  return update_extra_cfg(ctx, &extra_cfg);
}

static aom_codec_err_t ctrl_set_chroma_subsampling_y(aom_codec_alg_priv_t *ctx,
                                                     va_list args) {
  struct av1_extracfg extra_cfg = ctx->extra_cfg;
  extra_cfg.chroma_subsampling_y = CAST(AV1E_SET_CHROMA_SUBSAMPLING_Y, args);
  return update_extra_cfg(ctx, &extra_cfg);
}

static aom_codec_err_t encoder_set_option(aom_codec_alg_priv_t *ctx,
                                          const char *name, const char *value) {
  if (ctx == NULL || name == NULL || value == NULL)
    return AOM_CODEC_INVALID_PARAM;
  struct av1_extracfg extra_cfg = ctx->extra_cfg;
  // Used to mock the argv with just one string "--{name}={value}"
  char *argv[2] = { NULL, "" };
  size_t len = strlen(name) + strlen(value) + 4;
  char *const err_string = ctx->ppi->error.detail;

#if __STDC_VERSION__ >= 201112L
  // We use the keyword _Static_assert because clang-cl does not allow the
  // convenience macro static_assert to be used in function scope. See
  // https://bugs.llvm.org/show_bug.cgi?id=48904.
  _Static_assert(sizeof(ctx->ppi->error.detail) >= ARG_ERR_MSG_MAX_LEN,
                 "The size of the err_msg buffer for arg_match_helper must be "
                 "at least ARG_ERR_MSG_MAX_LEN");
#else
  assert(sizeof(ctx->ppi->error.detail) >= ARG_ERR_MSG_MAX_LEN);
#endif

  argv[0] = aom_malloc(len * sizeof(argv[1][0]));
  if (!argv[0]) return AOM_CODEC_MEM_ERROR;
  snprintf(argv[0], len, "--%s=%s", name, value);
  struct arg arg;
  aom_codec_err_t err = AOM_CODEC_OK;

  int match = 1;
  if (arg_match_helper(&arg, &g_av1_codec_arg_defs.enable_keyframe_filtering,
                       argv, err_string)) {
    extra_cfg.enable_keyframe_filtering =
        arg_parse_uint_helper(&arg, err_string);
  } else if (arg_match_helper(&arg, &g_av1_codec_arg_defs.min_gf_interval, argv,
                              err_string)) {
    extra_cfg.min_gf_interval = arg_parse_uint_helper(&arg, err_string);
  } else if (arg_match_helper(&arg, &g_av1_codec_arg_defs.max_gf_interval, argv,
                              err_string)) {
    extra_cfg.max_gf_interval = arg_parse_uint_helper(&arg, err_string);
  } else if (arg_match_helper(&arg, &g_av1_codec_arg_defs.gf_min_pyr_height,
                              argv, err_string)) {
    extra_cfg.gf_min_pyr_height = arg_parse_uint_helper(&arg, err_string);
  } else if (arg_match_helper(&arg, &g_av1_codec_arg_defs.gf_max_pyr_height,
                              argv, err_string)) {
    extra_cfg.gf_max_pyr_height = arg_parse_uint_helper(&arg, err_string);
  } else if (arg_match_helper(&arg, &g_av1_codec_arg_defs.cpu_used_av1, argv,
                              err_string)) {
    extra_cfg.cpu_used = arg_parse_uint_helper(&arg, err_string);
  } else if (arg_match_helper(&arg, &g_av1_codec_arg_defs.auto_altref, argv,
                              err_string)) {
    extra_cfg.enable_auto_alt_ref = arg_parse_uint_helper(&arg, err_string);
  } else if (arg_match_helper(&arg, &g_av1_codec_arg_defs.noise_sens, argv,
                              err_string)) {
    extra_cfg.noise_sensitivity = arg_parse_uint_helper(&arg, err_string);
  } else if (arg_match_helper(&arg, &g_av1_codec_arg_defs.sharpness, argv,
                              err_string)) {
    extra_cfg.sharpness = arg_parse_uint_helper(&arg, err_string);
  } else if (arg_match_helper(&arg, &g_av1_codec_arg_defs.static_thresh, argv,
                              err_string)) {
    extra_cfg.static_thresh = arg_parse_uint_helper(&arg, err_string);
  } else if (arg_match_helper(&arg, &g_av1_codec_arg_defs.rowmtarg, argv,
                              err_string)) {
    extra_cfg.row_mt = arg_parse_uint_helper(&arg, err_string);
  }
#if CONFIG_FRAME_PARALLEL_ENCODE
  else if (arg_match_helper(&arg, &g_av1_codec_arg_defs.fpmtarg, argv,
                            err_string)) {
    extra_cfg.fp_mt = arg_parse_uint_helper(&arg, err_string);
  }
#endif
  else if (arg_match_helper(&arg, &g_av1_codec_arg_defs.tile_cols, argv,
                            err_string)) {
    extra_cfg.tile_columns = arg_parse_uint_helper(&arg, err_string);
  } else if (arg_match_helper(&arg, &g_av1_codec_arg_defs.tile_rows, argv,
                              err_string)) {
    extra_cfg.tile_rows = arg_parse_uint_helper(&arg, err_string);
  } else if (arg_match_helper(&arg, &g_av1_codec_arg_defs.enable_tpl_model,
                              argv, err_string)) {
    extra_cfg.enable_tpl_model = arg_parse_uint_helper(&arg, err_string);
  } else if (arg_match_helper(&arg, &g_av1_codec_arg_defs.arnr_maxframes, argv,
                              err_string)) {
    extra_cfg.arnr_max_frames = arg_parse_uint_helper(&arg, err_string);
  } else if (arg_match_helper(&arg, &g_av1_codec_arg_defs.arnr_strength, argv,
                              err_string)) {
    extra_cfg.arnr_strength = arg_parse_uint_helper(&arg, err_string);
  } else if (arg_match_helper(&arg, &g_av1_codec_arg_defs.tune_metric, argv,
                              err_string)) {
    extra_cfg.tuning = arg_parse_enum_helper(&arg, err_string);
  }
#if CONFIG_TUNE_VMAF
  else if (arg_match_helper(&arg, &g_av1_codec_arg_defs.vmaf_model_path, argv,
                            err_string)) {
    err = allocate_and_set_string(value, default_extra_cfg.vmaf_model_path,
                                  &extra_cfg.vmaf_model_path, err_string);
  }
#endif
  else if (arg_match_helper(&arg, &g_av1_codec_arg_defs.partition_info_path,
                            argv, err_string)) {
    err = allocate_and_set_string(value, default_extra_cfg.partition_info_path,
                                  &extra_cfg.partition_info_path, err_string);
  } else if (arg_match_helper(&arg, &g_av1_codec_arg_defs.dist_metric, argv,
                              err_string)) {
    extra_cfg.dist_metric = arg_parse_enum_helper(&arg, err_string);
  } else if (arg_match_helper(&arg, &g_av1_codec_arg_defs.cq_level, argv,
                              err_string)) {
    extra_cfg.cq_level = arg_parse_uint_helper(&arg, err_string);
  } else if (arg_match_helper(&arg, &g_av1_codec_arg_defs.max_intra_rate_pct,
                              argv, err_string)) {
    extra_cfg.rc_max_intra_bitrate_pct =
        arg_parse_uint_helper(&arg, err_string);
  } else if (arg_match_helper(&arg, &g_av1_codec_arg_defs.max_inter_rate_pct,
                              argv, err_string)) {
    extra_cfg.rc_max_inter_bitrate_pct =
        arg_parse_uint_helper(&arg, err_string);
  } else if (arg_match_helper(&arg, &g_av1_codec_arg_defs.gf_cbr_boost_pct,
                              argv, err_string)) {
    extra_cfg.gf_cbr_boost_pct = arg_parse_uint_helper(&arg, err_string);
  } else if (arg_match_helper(&arg, &g_av1_codec_arg_defs.lossless, argv,
                              err_string)) {
    extra_cfg.lossless = arg_parse_uint_helper(&arg, err_string);
  } else if (arg_match_helper(&arg, &g_av1_codec_arg_defs.enable_cdef, argv,
                              err_string)) {
    extra_cfg.enable_cdef = arg_parse_uint_helper(&arg, err_string);
  } else if (arg_match_helper(&arg, &g_av1_codec_arg_defs.enable_restoration,
                              argv, err_string)) {
    extra_cfg.enable_restoration = arg_parse_uint_helper(&arg, err_string);
  } else if (arg_match_helper(&arg, &g_av1_codec_arg_defs.force_video_mode,
                              argv, err_string)) {
    extra_cfg.force_video_mode = arg_parse_uint_helper(&arg, err_string);
  } else if (arg_match_helper(&arg, &g_av1_codec_arg_defs.enable_obmc, argv,
                              err_string)) {
    extra_cfg.enable_obmc = arg_parse_uint_helper(&arg, err_string);
  } else if (arg_match_helper(&arg, &g_av1_codec_arg_defs.disable_trellis_quant,
                              argv, err_string)) {
    extra_cfg.disable_trellis_quant = arg_parse_uint_helper(&arg, err_string);
  } else if (arg_match_helper(&arg, &g_av1_codec_arg_defs.enable_qm, argv,
                              err_string)) {
    extra_cfg.enable_qm = arg_parse_uint_helper(&arg, err_string);
  } else if (arg_match_helper(&arg, &g_av1_codec_arg_defs.qm_max, argv,
                              err_string)) {
    extra_cfg.qm_max = arg_parse_uint_helper(&arg, err_string);
  } else if (arg_match_helper(&arg, &g_av1_codec_arg_defs.qm_min, argv,
                              err_string)) {
    extra_cfg.qm_min = arg_parse_uint_helper(&arg, err_string);
  } else if (arg_match_helper(&arg, &g_av1_codec_arg_defs.num_tg, argv,
                              err_string)) {
    extra_cfg.num_tg = arg_parse_uint_helper(&arg, err_string);
  } else if (arg_match_helper(&arg, &g_av1_codec_arg_defs.mtu_size, argv,
                              err_string)) {
    extra_cfg.mtu_size = arg_parse_uint_helper(&arg, err_string);
  } else if (arg_match_helper(&arg, &g_av1_codec_arg_defs.timing_info, argv,
                              err_string)) {
    extra_cfg.timing_info_type = arg_parse_enum_helper(&arg, err_string);
  } else if (arg_match_helper(&arg,
                              &g_av1_codec_arg_defs.frame_parallel_decoding,
                              argv, err_string)) {
    extra_cfg.frame_parallel_decoding_mode =
        arg_parse_uint_helper(&arg, err_string);
  } else if (arg_match_helper(&arg, &g_av1_codec_arg_defs.enable_dual_filter,
                              argv, err_string)) {
    extra_cfg.enable_dual_filter = arg_parse_uint_helper(&arg, err_string);
  } else if (arg_match_helper(&arg, &g_av1_codec_arg_defs.enable_chroma_deltaq,
                              argv, err_string)) {
    extra_cfg.enable_chroma_deltaq = arg_parse_uint_helper(&arg, err_string);
  } else if (arg_match_helper(&arg, &g_av1_codec_arg_defs.aq_mode, argv,
                              err_string)) {
    extra_cfg.aq_mode = arg_parse_uint_helper(&arg, err_string);
  } else if (arg_match_helper(&arg, &g_av1_codec_arg_defs.deltaq_mode, argv,
                              err_string)) {
    extra_cfg.deltaq_mode = arg_parse_uint_helper(&arg, err_string);
  } else if (arg_match_helper(&arg, &g_av1_codec_arg_defs.deltaq_strength, argv,
                              err_string)) {
    extra_cfg.deltaq_strength = arg_parse_uint_helper(&arg, err_string);
  } else if (arg_match_helper(&arg, &g_av1_codec_arg_defs.deltalf_mode, argv,
                              err_string)) {
    extra_cfg.deltalf_mode = arg_parse_uint_helper(&arg, err_string);
  } else if (arg_match_helper(&arg, &g_av1_codec_arg_defs.frame_periodic_boost,
                              argv, err_string)) {
    extra_cfg.frame_periodic_boost = arg_parse_uint_helper(&arg, err_string);
  } else if (arg_match_helper(&arg, &g_av1_codec_arg_defs.tune_content, argv,
                              err_string)) {
    extra_cfg.content = arg_parse_enum_helper(&arg, err_string);
  } else if (arg_match_helper(&arg, &g_av1_codec_arg_defs.input_color_primaries,
                              argv, err_string)) {
    extra_cfg.color_primaries = arg_parse_enum_helper(&arg, err_string);
  } else if (arg_match_helper(
                 &arg, &g_av1_codec_arg_defs.input_transfer_characteristics,
                 argv, err_string)) {
    extra_cfg.transfer_characteristics =
        arg_parse_enum_helper(&arg, err_string);
  } else if (arg_match_helper(&arg,
                              &g_av1_codec_arg_defs.input_matrix_coefficients,
                              argv, err_string)) {
    extra_cfg.matrix_coefficients = arg_parse_enum_helper(&arg, err_string);
  } else if (arg_match_helper(
                 &arg, &g_av1_codec_arg_defs.input_chroma_sample_position, argv,
                 err_string)) {
    extra_cfg.chroma_sample_position = arg_parse_enum_helper(&arg, err_string);
  } else if (arg_match_helper(&arg, &g_av1_codec_arg_defs.superblock_size, argv,
                              err_string)) {
    extra_cfg.superblock_size = arg_parse_enum_helper(&arg, err_string);
  } else if (arg_match_helper(&arg, &g_av1_codec_arg_defs.error_resilient_mode,
                              argv, err_string)) {
    extra_cfg.error_resilient_mode = arg_parse_int_helper(&arg, err_string);
  } else if (arg_match_helper(&arg, &g_av1_codec_arg_defs.sframe_mode, argv,
                              err_string)) {
    extra_cfg.s_frame_mode = arg_parse_int_helper(&arg, err_string);
  } else if (arg_match_helper(&arg, &g_av1_codec_arg_defs.film_grain_test, argv,
                              err_string)) {
    extra_cfg.film_grain_test_vector = arg_parse_int_helper(&arg, err_string);
  } else if (arg_match_helper(&arg, &g_av1_codec_arg_defs.film_grain_table,
                              argv, err_string)) {
    if (value == NULL) {
      // this parameter allows NULL as its value
      extra_cfg.film_grain_table_filename = value;
    } else {
      err = allocate_and_set_string(
          value, default_extra_cfg.film_grain_table_filename,
          &extra_cfg.film_grain_table_filename, err_string);
    }
  } else if (arg_match_helper(&arg, &g_av1_codec_arg_defs.cdf_update_mode, argv,
                              err_string)) {
    extra_cfg.cdf_update_mode = arg_parse_int_helper(&arg, err_string);
  } else if (arg_match_helper(&arg,
                              &g_av1_codec_arg_defs.enable_rect_partitions,
                              argv, err_string)) {
    extra_cfg.enable_rect_partitions = arg_parse_int_helper(&arg, err_string);
  } else if (arg_match_helper(&arg, &g_av1_codec_arg_defs.enable_ab_partitions,
                              argv, err_string)) {
    extra_cfg.enable_ab_partitions = arg_parse_int_helper(&arg, err_string);
  } else if (arg_match_helper(&arg,
                              &g_av1_codec_arg_defs.enable_1to4_partitions,
                              argv, err_string)) {
    extra_cfg.enable_1to4_partitions = arg_parse_int_helper(&arg, err_string);
  } else if (arg_match_helper(&arg, &g_av1_codec_arg_defs.min_partition_size,
                              argv, err_string)) {
    extra_cfg.min_partition_size = arg_parse_int_helper(&arg, err_string);
  } else if (arg_match_helper(&arg, &g_av1_codec_arg_defs.max_partition_size,
                              argv, err_string)) {
    extra_cfg.max_partition_size = arg_parse_int_helper(&arg, err_string);
  } else if (arg_match_helper(&arg,
                              &g_av1_codec_arg_defs.enable_intra_edge_filter,
                              argv, err_string)) {
    extra_cfg.enable_intra_edge_filter =
        arg_parse_uint_helper(&arg, err_string);
  } else if (arg_match_helper(&arg, &g_av1_codec_arg_defs.enable_order_hint,
                              argv, err_string)) {
    extra_cfg.enable_order_hint = arg_parse_int_helper(&arg, err_string);
  } else if (arg_match_helper(&arg, &g_av1_codec_arg_defs.enable_tx64, argv,
                              err_string)) {
    extra_cfg.enable_tx64 = arg_parse_int_helper(&arg, err_string);
  } else if (arg_match_helper(&arg, &g_av1_codec_arg_defs.enable_flip_idtx,
                              argv, err_string)) {
    extra_cfg.enable_flip_idtx = arg_parse_int_helper(&arg, err_string);
  } else if (arg_match_helper(&arg, &g_av1_codec_arg_defs.enable_rect_tx, argv,
                              err_string)) {
    extra_cfg.enable_rect_tx = arg_parse_int_helper(&arg, err_string);
  } else if (arg_match_helper(&arg, &g_av1_codec_arg_defs.enable_dist_wtd_comp,
                              argv, err_string)) {
    extra_cfg.enable_dist_wtd_comp = arg_parse_int_helper(&arg, err_string);
  } else if (arg_match_helper(&arg, &g_av1_codec_arg_defs.max_reference_frames,
                              argv, err_string)) {
    extra_cfg.max_reference_frames = arg_parse_int_helper(&arg, err_string);
  } else if (arg_match_helper(&arg, &g_av1_codec_arg_defs.reduced_reference_set,
                              argv, err_string)) {
    extra_cfg.enable_reduced_reference_set =
        arg_parse_int_helper(&arg, err_string);
  } else if (arg_match_helper(&arg, &g_av1_codec_arg_defs.enable_ref_frame_mvs,
                              argv, err_string)) {
    extra_cfg.enable_ref_frame_mvs = arg_parse_int_helper(&arg, err_string);
  } else if (arg_match_helper(&arg, &g_av1_codec_arg_defs.enable_masked_comp,
                              argv, err_string)) {
    extra_cfg.enable_masked_comp = arg_parse_int_helper(&arg, err_string);
  } else if (arg_match_helper(&arg, &g_av1_codec_arg_defs.enable_onesided_comp,
                              argv, err_string)) {
    extra_cfg.enable_onesided_comp = arg_parse_int_helper(&arg, err_string);
  } else if (arg_match_helper(&arg,
                              &g_av1_codec_arg_defs.enable_interintra_comp,
                              argv, err_string)) {
    extra_cfg.enable_interintra_comp = arg_parse_int_helper(&arg, err_string);
  } else if (arg_match_helper(&arg,
                              &g_av1_codec_arg_defs.enable_smooth_interintra,
                              argv, err_string)) {
    extra_cfg.enable_smooth_interintra = arg_parse_int_helper(&arg, err_string);
  } else if (arg_match_helper(&arg, &g_av1_codec_arg_defs.enable_diff_wtd_comp,
                              argv, err_string)) {
    extra_cfg.enable_diff_wtd_comp = arg_parse_int_helper(&arg, err_string);
  } else if (arg_match_helper(&arg,
                              &g_av1_codec_arg_defs.enable_interinter_wedge,
                              argv, err_string)) {
    extra_cfg.enable_interinter_wedge = arg_parse_int_helper(&arg, err_string);
  } else if (arg_match_helper(&arg,
                              &g_av1_codec_arg_defs.enable_interintra_wedge,
                              argv, err_string)) {
    extra_cfg.enable_interintra_wedge = arg_parse_int_helper(&arg, err_string);
  } else if (arg_match_helper(&arg, &g_av1_codec_arg_defs.enable_global_motion,
                              argv, err_string)) {
    extra_cfg.enable_global_motion = arg_parse_int_helper(&arg, err_string);
  } else if (arg_match_helper(&arg, &g_av1_codec_arg_defs.enable_warped_motion,
                              argv, err_string)) {
    extra_cfg.enable_warped_motion = arg_parse_int_helper(&arg, err_string);
  } else if (arg_match_helper(&arg, &g_av1_codec_arg_defs.enable_filter_intra,
                              argv, err_string)) {
    extra_cfg.enable_filter_intra = arg_parse_int_helper(&arg, err_string);
  } else if (arg_match_helper(&arg, &g_av1_codec_arg_defs.enable_smooth_intra,
                              argv, err_string)) {
    extra_cfg.enable_smooth_intra = arg_parse_int_helper(&arg, err_string);
  } else if (arg_match_helper(&arg, &g_av1_codec_arg_defs.enable_paeth_intra,
                              argv, err_string)) {
    extra_cfg.enable_paeth_intra = arg_parse_int_helper(&arg, err_string);
  } else if (arg_match_helper(&arg, &g_av1_codec_arg_defs.enable_cfl_intra,
                              argv, err_string)) {
    extra_cfg.enable_cfl_intra = arg_parse_int_helper(&arg, err_string);
  } else if (arg_match_helper(&arg,
                              &g_av1_codec_arg_defs.enable_directional_intra,
                              argv, err_string)) {
    extra_cfg.enable_directional_intra = arg_parse_int_helper(&arg, err_string);
  } else if (arg_match_helper(&arg, &g_av1_codec_arg_defs.enable_diagonal_intra,
                              argv, err_string)) {
    extra_cfg.enable_diagonal_intra = arg_parse_int_helper(&arg, err_string);
  } else if (arg_match_helper(&arg, &g_av1_codec_arg_defs.enable_overlay, argv,
                              err_string)) {
    extra_cfg.enable_overlay = arg_parse_int_helper(&arg, err_string);
  } else if (arg_match_helper(&arg, &g_av1_codec_arg_defs.enable_palette, argv,
                              err_string)) {
    extra_cfg.enable_palette = arg_parse_int_helper(&arg, err_string);
  } else if (arg_match_helper(&arg, &g_av1_codec_arg_defs.enable_intrabc, argv,
                              err_string)) {
    extra_cfg.enable_intrabc = arg_parse_int_helper(&arg, err_string);
  } else if (arg_match_helper(&arg, &g_av1_codec_arg_defs.enable_angle_delta,
                              argv, err_string)) {
    extra_cfg.enable_angle_delta = arg_parse_int_helper(&arg, err_string);
  } else if (arg_match_helper(&arg, &g_av1_codec_arg_defs.reduced_tx_type_set,
                              argv, err_string)) {
    extra_cfg.reduced_tx_type_set = arg_parse_int_helper(&arg, err_string);
  } else if (arg_match_helper(&arg, &g_av1_codec_arg_defs.use_intra_dct_only,
                              argv, err_string)) {
    extra_cfg.use_intra_dct_only = arg_parse_int_helper(&arg, err_string);
  } else if (arg_match_helper(&arg, &g_av1_codec_arg_defs.use_inter_dct_only,
                              argv, err_string)) {
    extra_cfg.use_inter_dct_only = arg_parse_int_helper(&arg, err_string);
  } else if (arg_match_helper(&arg,
                              &g_av1_codec_arg_defs.use_intra_default_tx_only,
                              argv, err_string)) {
    extra_cfg.use_intra_default_tx_only =
        arg_parse_int_helper(&arg, err_string);
  } else if (arg_match_helper(&arg, &g_av1_codec_arg_defs.quant_b_adapt, argv,
                              err_string)) {
    extra_cfg.quant_b_adapt = arg_parse_int_helper(&arg, err_string);
  } else if (arg_match_helper(&arg,
                              &g_av1_codec_arg_defs.vbr_corpus_complexity_lap,
                              argv, err_string)) {
    extra_cfg.vbr_corpus_complexity_lap =
        arg_parse_uint_helper(&arg, err_string);
  } else if (arg_match_helper(&arg, &g_av1_codec_arg_defs.set_tier_mask, argv,
                              err_string)) {
    extra_cfg.tier_mask = arg_parse_uint_helper(&arg, err_string);
  } else if (arg_match_helper(&arg, &g_av1_codec_arg_defs.set_min_cr, argv,
                              err_string)) {
    extra_cfg.min_cr = arg_parse_uint_helper(&arg, err_string);
  } else if (arg_match_helper(&arg, &g_av1_codec_arg_defs.coeff_cost_upd_freq,
                              argv, err_string)) {
    extra_cfg.coeff_cost_upd_freq = arg_parse_uint_helper(&arg, err_string);
  } else if (arg_match_helper(&arg, &g_av1_codec_arg_defs.mode_cost_upd_freq,
                              argv, err_string)) {
    extra_cfg.mode_cost_upd_freq = arg_parse_uint_helper(&arg, err_string);
  } else if (arg_match_helper(&arg, &g_av1_codec_arg_defs.mv_cost_upd_freq,
                              argv, err_string)) {
    extra_cfg.mv_cost_upd_freq = arg_parse_uint_helper(&arg, err_string);
  } else if (arg_match_helper(&arg, &g_av1_codec_arg_defs.dv_cost_upd_freq,
                              argv, err_string)) {
    extra_cfg.dv_cost_upd_freq = arg_parse_uint_helper(&arg, err_string);
  }
#if CONFIG_DENOISE
  else if (arg_match_helper(&arg, &g_av1_codec_arg_defs.denoise_noise_level,
                            argv, err_string)) {
    extra_cfg.noise_level =
        (float)arg_parse_int_helper(&arg, err_string) / 10.0f;
  } else if (arg_match_helper(&arg, &g_av1_codec_arg_defs.denoise_block_size,
                              argv, err_string)) {
    extra_cfg.noise_block_size = arg_parse_uint_helper(&arg, err_string);
  } else if (arg_match_helper(&arg, &g_av1_codec_arg_defs.enable_dnl_denoising,
                              argv, err_string)) {
    extra_cfg.enable_dnl_denoising = arg_parse_uint_helper(&arg, err_string);
  }
#endif
  else if (arg_match_helper(&arg, &g_av1_codec_arg_defs.target_seq_level_idx,
                            argv, err_string)) {
    const int val = arg_parse_int_helper(&arg, err_string);
    const int level = val % 100;
    const int operating_point_idx = val / 100;
    if (operating_point_idx >= 0 &&
        operating_point_idx < MAX_NUM_OPERATING_POINTS) {
      extra_cfg.target_seq_level_idx[operating_point_idx] = (AV1_LEVEL)level;
    }
  } else if (arg_match_helper(&arg,
                              &g_av1_codec_arg_defs.input_chroma_subsampling_x,
                              argv, err_string)) {
    extra_cfg.chroma_subsampling_x = arg_parse_uint_helper(&arg, err_string);
  } else if (arg_match_helper(&arg,
                              &g_av1_codec_arg_defs.input_chroma_subsampling_y,
                              argv, err_string)) {
    extra_cfg.chroma_subsampling_y = arg_parse_uint_helper(&arg, err_string);
  } else if (arg_match_helper(&arg, &g_av1_codec_arg_defs.passes, argv,
                              err_string)) {
    extra_cfg.passes = arg_parse_int_helper(&arg, err_string);
  } else if (arg_match_helper(&arg, &g_av1_codec_arg_defs.fwd_kf_dist, argv,
                              err_string)) {
    extra_cfg.fwd_kf_dist = arg_parse_int_helper(&arg, err_string);
  } else if (arg_match_helper(&arg, &g_av1_codec_arg_defs.two_pass_output, argv,
                              err_string)) {
    err = allocate_and_set_string(value, default_extra_cfg.two_pass_output,
                                  &extra_cfg.two_pass_output, err_string);
  } else if (arg_match_helper(&arg, &g_av1_codec_arg_defs.second_pass_log, argv,
                              err_string)) {
    err = allocate_and_set_string(value, default_extra_cfg.second_pass_log,
                                  &extra_cfg.second_pass_log, err_string);
  } else if (arg_match_helper(&arg, &g_av1_codec_arg_defs.loopfilter_control,
                              argv, err_string)) {
    extra_cfg.loopfilter_control = arg_parse_int_helper(&arg, err_string);
  } else if (arg_match_helper(&arg, &g_av1_codec_arg_defs.auto_intra_tools_off,
                              argv, err_string)) {
    extra_cfg.auto_intra_tools_off = arg_parse_uint_helper(&arg, err_string);
  } else if (arg_match_helper(&arg,
                              &g_av1_codec_arg_defs.strict_level_conformance,
                              argv, err_string)) {
    extra_cfg.strict_level_conformance = arg_parse_int_helper(&arg, err_string);
  } else {
    match = 0;
    snprintf(err_string, ARG_ERR_MSG_MAX_LEN, "Cannot find aom option %s",
             name);
  }
  aom_free(argv[0]);

  if (err != AOM_CODEC_OK) {
    ctx->base.err_detail = err_string;
    return err;
  }

  if (strlen(err_string) != 0) {
    ctx->base.err_detail = err_string;
    return AOM_CODEC_INVALID_PARAM;
  }

  ctx->base.err_detail = NULL;

  if (!match) {
    return AOM_CODEC_INVALID_PARAM;
  }
  return update_extra_cfg(ctx, &extra_cfg);
}

static aom_codec_err_t ctrl_get_seq_level_idx(aom_codec_alg_priv_t *ctx,
                                              va_list args) {
  int *const arg = va_arg(args, int *);
  if (arg == NULL) return AOM_CODEC_INVALID_PARAM;
  return av1_get_seq_level_idx(&ctx->ppi->seq_params, &ctx->ppi->level_params,
                               arg);
}

static aom_codec_err_t ctrl_get_target_seq_level_idx(aom_codec_alg_priv_t *ctx,
                                                     va_list args) {
  int *const arg = va_arg(args, int *);
  if (arg == NULL) return AOM_CODEC_INVALID_PARAM;
  return av1_get_target_seq_level_idx(&ctx->ppi->seq_params,
                                      &ctx->ppi->level_params, arg);
}

static aom_codec_ctrl_fn_map_t encoder_ctrl_maps[] = {
  { AV1_COPY_REFERENCE, ctrl_copy_reference },
  { AOME_USE_REFERENCE, ctrl_use_reference },

  // Setters
  { AV1_SET_REFERENCE, ctrl_set_reference },
  { AOME_SET_ROI_MAP, ctrl_set_roi_map },
  { AOME_SET_ACTIVEMAP, ctrl_set_active_map },
  { AOME_SET_SCALEMODE, ctrl_set_scale_mode },
  { AOME_SET_SPATIAL_LAYER_ID, ctrl_set_spatial_layer_id },
  { AOME_SET_CPUUSED, ctrl_set_cpuused },
  { AOME_SET_ENABLEAUTOALTREF, ctrl_set_enable_auto_alt_ref },
  { AOME_SET_ENABLEAUTOBWDREF, ctrl_set_enable_auto_bwd_ref },
  { AOME_SET_SHARPNESS, ctrl_set_sharpness },
  { AOME_SET_STATIC_THRESHOLD, ctrl_set_static_thresh },
  { AV1E_SET_ROW_MT, ctrl_set_row_mt },
  { AV1E_SET_FP_MT, ctrl_set_fp_mt },
  { AV1E_SET_TILE_COLUMNS, ctrl_set_tile_columns },
  { AV1E_SET_TILE_ROWS, ctrl_set_tile_rows },
  { AV1E_SET_ENABLE_TPL_MODEL, ctrl_set_enable_tpl_model },
  { AV1E_SET_ENABLE_KEYFRAME_FILTERING, ctrl_set_enable_keyframe_filtering },
  { AOME_SET_ARNR_MAXFRAMES, ctrl_set_arnr_max_frames },
  { AOME_SET_ARNR_STRENGTH, ctrl_set_arnr_strength },
  { AOME_SET_TUNING, ctrl_set_tuning },
  { AOME_SET_CQ_LEVEL, ctrl_set_cq_level },
  { AOME_SET_MAX_INTRA_BITRATE_PCT, ctrl_set_rc_max_intra_bitrate_pct },
  { AOME_SET_NUMBER_SPATIAL_LAYERS, ctrl_set_number_spatial_layers },
  { AV1E_SET_MAX_INTER_BITRATE_PCT, ctrl_set_rc_max_inter_bitrate_pct },
  { AV1E_SET_GF_CBR_BOOST_PCT, ctrl_set_rc_gf_cbr_boost_pct },
  { AV1E_SET_LOSSLESS, ctrl_set_lossless },
  { AV1E_SET_ENABLE_CDEF, ctrl_set_enable_cdef },
  { AV1E_SET_ENABLE_RESTORATION, ctrl_set_enable_restoration },
  { AV1E_SET_FORCE_VIDEO_MODE, ctrl_set_force_video_mode },
  { AV1E_SET_ENABLE_OBMC, ctrl_set_enable_obmc },
  { AV1E_SET_DISABLE_TRELLIS_QUANT, ctrl_set_disable_trellis_quant },
  { AV1E_SET_ENABLE_QM, ctrl_set_enable_qm },
  { AV1E_SET_QM_Y, ctrl_set_qm_y },
  { AV1E_SET_QM_U, ctrl_set_qm_u },
  { AV1E_SET_QM_V, ctrl_set_qm_v },
  { AV1E_SET_QM_MIN, ctrl_set_qm_min },
  { AV1E_SET_QM_MAX, ctrl_set_qm_max },
  { AV1E_SET_NUM_TG, ctrl_set_num_tg },
  { AV1E_SET_MTU, ctrl_set_mtu },
  { AV1E_SET_TIMING_INFO_TYPE, ctrl_set_timing_info_type },
  { AV1E_SET_FRAME_PARALLEL_DECODING, ctrl_set_frame_parallel_decoding_mode },
  { AV1E_SET_ERROR_RESILIENT_MODE, ctrl_set_error_resilient_mode },
  { AV1E_SET_S_FRAME_MODE, ctrl_set_s_frame_mode },
  { AV1E_SET_ENABLE_RECT_PARTITIONS, ctrl_set_enable_rect_partitions },
  { AV1E_SET_ENABLE_AB_PARTITIONS, ctrl_set_enable_ab_partitions },
  { AV1E_SET_ENABLE_1TO4_PARTITIONS, ctrl_set_enable_1to4_partitions },
  { AV1E_SET_MIN_PARTITION_SIZE, ctrl_set_min_partition_size },
  { AV1E_SET_MAX_PARTITION_SIZE, ctrl_set_max_partition_size },
  { AV1E_SET_ENABLE_DUAL_FILTER, ctrl_set_enable_dual_filter },
  { AV1E_SET_ENABLE_CHROMA_DELTAQ, ctrl_set_enable_chroma_deltaq },
  { AV1E_SET_ENABLE_INTRA_EDGE_FILTER, ctrl_set_enable_intra_edge_filter },
  { AV1E_SET_ENABLE_ORDER_HINT, ctrl_set_enable_order_hint },
  { AV1E_SET_ENABLE_TX64, ctrl_set_enable_tx64 },
  { AV1E_SET_ENABLE_FLIP_IDTX, ctrl_set_enable_flip_idtx },
  { AV1E_SET_ENABLE_RECT_TX, ctrl_set_enable_rect_tx },
  { AV1E_SET_ENABLE_DIST_WTD_COMP, ctrl_set_enable_dist_wtd_comp },
  { AV1E_SET_MAX_REFERENCE_FRAMES, ctrl_set_max_reference_frames },
  { AV1E_SET_REDUCED_REFERENCE_SET, ctrl_set_enable_reduced_reference_set },
  { AV1E_SET_ENABLE_REF_FRAME_MVS, ctrl_set_enable_ref_frame_mvs },
  { AV1E_SET_ALLOW_REF_FRAME_MVS, ctrl_set_allow_ref_frame_mvs },
  { AV1E_SET_ENABLE_MASKED_COMP, ctrl_set_enable_masked_comp },
  { AV1E_SET_ENABLE_ONESIDED_COMP, ctrl_set_enable_onesided_comp },
  { AV1E_SET_ENABLE_INTERINTRA_COMP, ctrl_set_enable_interintra_comp },
  { AV1E_SET_ENABLE_SMOOTH_INTERINTRA, ctrl_set_enable_smooth_interintra },
  { AV1E_SET_ENABLE_DIFF_WTD_COMP, ctrl_set_enable_diff_wtd_comp },
  { AV1E_SET_ENABLE_INTERINTER_WEDGE, ctrl_set_enable_interinter_wedge },
  { AV1E_SET_ENABLE_INTERINTRA_WEDGE, ctrl_set_enable_interintra_wedge },
  { AV1E_SET_ENABLE_GLOBAL_MOTION, ctrl_set_enable_global_motion },
  { AV1E_SET_ENABLE_WARPED_MOTION, ctrl_set_enable_warped_motion },
  { AV1E_SET_ALLOW_WARPED_MOTION, ctrl_set_allow_warped_motion },
  { AV1E_SET_ENABLE_FILTER_INTRA, ctrl_set_enable_filter_intra },
  { AV1E_SET_ENABLE_SMOOTH_INTRA, ctrl_set_enable_smooth_intra },
  { AV1E_SET_ENABLE_PAETH_INTRA, ctrl_set_enable_paeth_intra },
  { AV1E_SET_ENABLE_CFL_INTRA, ctrl_set_enable_cfl_intra },
  { AV1E_SET_ENABLE_DIRECTIONAL_INTRA, ctrl_set_enable_directional_intra },
  { AV1E_SET_ENABLE_DIAGONAL_INTRA, ctrl_set_enable_diagonal_intra },
  { AV1E_SET_ENABLE_SUPERRES, ctrl_set_enable_superres },
  { AV1E_SET_ENABLE_OVERLAY, ctrl_set_enable_overlay },
  { AV1E_SET_ENABLE_PALETTE, ctrl_set_enable_palette },
  { AV1E_SET_ENABLE_INTRABC, ctrl_set_enable_intrabc },
  { AV1E_SET_ENABLE_ANGLE_DELTA, ctrl_set_enable_angle_delta },
  { AV1E_SET_AQ_MODE, ctrl_set_aq_mode },
  { AV1E_SET_REDUCED_TX_TYPE_SET, ctrl_set_reduced_tx_type_set },
  { AV1E_SET_INTRA_DCT_ONLY, ctrl_set_intra_dct_only },
  { AV1E_SET_INTER_DCT_ONLY, ctrl_set_inter_dct_only },
  { AV1E_SET_INTRA_DEFAULT_TX_ONLY, ctrl_set_intra_default_tx_only },
  { AV1E_SET_QUANT_B_ADAPT, ctrl_set_quant_b_adapt },
  { AV1E_SET_COEFF_COST_UPD_FREQ, ctrl_set_coeff_cost_upd_freq },
  { AV1E_SET_MODE_COST_UPD_FREQ, ctrl_set_mode_cost_upd_freq },
  { AV1E_SET_MV_COST_UPD_FREQ, ctrl_set_mv_cost_upd_freq },
  { AV1E_SET_DELTAQ_MODE, ctrl_set_deltaq_mode },
  { AV1E_SET_DELTAQ_STRENGTH, ctrl_set_deltaq_strength },
  { AV1E_SET_DELTALF_MODE, ctrl_set_deltalf_mode },
  { AV1E_SET_FRAME_PERIODIC_BOOST, ctrl_set_frame_periodic_boost },
  { AV1E_SET_TUNE_CONTENT, ctrl_set_tune_content },
  { AV1E_SET_CDF_UPDATE_MODE, ctrl_set_cdf_update_mode },
  { AV1E_SET_COLOR_PRIMARIES, ctrl_set_color_primaries },
  { AV1E_SET_TRANSFER_CHARACTERISTICS, ctrl_set_transfer_characteristics },
  { AV1E_SET_MATRIX_COEFFICIENTS, ctrl_set_matrix_coefficients },
  { AV1E_SET_CHROMA_SAMPLE_POSITION, ctrl_set_chroma_sample_position },
  { AV1E_SET_COLOR_RANGE, ctrl_set_color_range },
  { AV1E_SET_NOISE_SENSITIVITY, ctrl_set_noise_sensitivity },
  { AV1E_SET_MIN_GF_INTERVAL, ctrl_set_min_gf_interval },
  { AV1E_SET_MAX_GF_INTERVAL, ctrl_set_max_gf_interval },
  { AV1E_SET_GF_MIN_PYRAMID_HEIGHT, ctrl_set_gf_min_pyr_height },
  { AV1E_SET_GF_MAX_PYRAMID_HEIGHT, ctrl_set_gf_max_pyr_height },
  { AV1E_SET_RENDER_SIZE, ctrl_set_render_size },
  { AV1E_SET_SUPERBLOCK_SIZE, ctrl_set_superblock_size },
  { AV1E_SET_SINGLE_TILE_DECODING, ctrl_set_single_tile_decoding },
  { AV1E_SET_VMAF_MODEL_PATH, ctrl_set_vmaf_model_path },
  { AV1E_SET_PARTITION_INFO_PATH, ctrl_set_partition_info_path },
  { AV1E_SET_FILM_GRAIN_TEST_VECTOR, ctrl_set_film_grain_test_vector },
  { AV1E_SET_FILM_GRAIN_TABLE, ctrl_set_film_grain_table },
  { AV1E_SET_DENOISE_NOISE_LEVEL, ctrl_set_denoise_noise_level },
  { AV1E_SET_DENOISE_BLOCK_SIZE, ctrl_set_denoise_block_size },
  { AV1E_SET_ENABLE_DNL_DENOISING, ctrl_set_enable_dnl_denoising },
  { AV1E_ENABLE_MOTION_VECTOR_UNIT_TEST, ctrl_enable_motion_vector_unit_test },
  { AV1E_SET_FP_MT_UNIT_TEST, ctrl_enable_fpmt_unit_test },
  { AV1E_ENABLE_EXT_TILE_DEBUG, ctrl_enable_ext_tile_debug },
  { AV1E_SET_TARGET_SEQ_LEVEL_IDX, ctrl_set_target_seq_level_idx },
  { AV1E_SET_TIER_MASK, ctrl_set_tier_mask },
  { AV1E_SET_MIN_CR, ctrl_set_min_cr },
  { AV1E_SET_SVC_LAYER_ID, ctrl_set_layer_id },
  { AV1E_SET_SVC_PARAMS, ctrl_set_svc_params },
  { AV1E_SET_SVC_REF_FRAME_CONFIG, ctrl_set_svc_ref_frame_config },
  { AV1E_SET_SVC_REF_FRAME_COMP_PRED, ctrl_set_svc_ref_frame_comp_pred },
  { AV1E_SET_VBR_CORPUS_COMPLEXITY_LAP, ctrl_set_vbr_corpus_complexity_lap },
  { AV1E_ENABLE_SB_MULTIPASS_UNIT_TEST, ctrl_enable_sb_multipass_unit_test },
  { AV1E_SET_DV_COST_UPD_FREQ, ctrl_set_dv_cost_upd_freq },
  { AV1E_SET_EXTERNAL_PARTITION, ctrl_set_external_partition },
  { AV1E_SET_ENABLE_TX_SIZE_SEARCH, ctrl_set_enable_tx_size_search },
  { AV1E_SET_LOOPFILTER_CONTROL, ctrl_set_loopfilter_control },
  { AV1E_SET_AUTO_INTRA_TOOLS_OFF, ctrl_set_auto_intra_tools_off },
  { AV1E_SET_RTC_EXTERNAL_RC, ctrl_set_rtc_external_rc },

  // Getters
  { AOME_GET_LAST_QUANTIZER, ctrl_get_quantizer },
  { AOME_GET_LAST_QUANTIZER_64, ctrl_get_quantizer64 },
  { AOME_GET_LOOPFILTER_LEVEL, ctrl_get_loopfilter_level },
  { AV1_GET_REFERENCE, ctrl_get_reference },
  { AV1E_GET_ACTIVEMAP, ctrl_get_active_map },
  { AV1_GET_NEW_FRAME_IMAGE, ctrl_get_new_frame_image },
  { AV1_COPY_NEW_FRAME_IMAGE, ctrl_copy_new_frame_image },
  { AV1E_SET_CHROMA_SUBSAMPLING_X, ctrl_set_chroma_subsampling_x },
  { AV1E_SET_CHROMA_SUBSAMPLING_Y, ctrl_set_chroma_subsampling_y },
  { AV1E_GET_SEQ_LEVEL_IDX, ctrl_get_seq_level_idx },
  { AV1E_GET_BASELINE_GF_INTERVAL, ctrl_get_baseline_gf_interval },
  { AV1E_GET_TARGET_SEQ_LEVEL_IDX, ctrl_get_target_seq_level_idx },

  CTRL_MAP_END,
};

static const aom_codec_enc_cfg_t encoder_usage_cfg[] = {
#if !CONFIG_REALTIME_ONLY
  {
      // NOLINT
      AOM_USAGE_GOOD_QUALITY,  // g_usage - non-realtime usage
      0,                       // g_threads
      0,                       // g_profile

      320,         // g_w
      240,         // g_h
      0,           // g_limit
      0,           // g_forced_max_frame_width
      0,           // g_forced_max_frame_height
      AOM_BITS_8,  // g_bit_depth
      8,           // g_input_bit_depth

      { 1, 30 },  // g_timebase

      0,  // g_error_resilient

      AOM_RC_ONE_PASS,  // g_pass

      35,  // g_lag_in_frames

      0,                // rc_dropframe_thresh
      RESIZE_NONE,      // rc_resize_mode
      SCALE_NUMERATOR,  // rc_resize_denominator
      SCALE_NUMERATOR,  // rc_resize_kf_denominator

      AOM_SUPERRES_NONE,  // rc_superres_mode
      SCALE_NUMERATOR,    // rc_superres_denominator
      SCALE_NUMERATOR,    // rc_superres_kf_denominator
      63,                 // rc_superres_qthresh
      32,                 // rc_superres_kf_qthresh

      AOM_VBR,      // rc_end_usage
      { NULL, 0 },  // rc_twopass_stats_in
      { NULL, 0 },  // rc_firstpass_mb_stats_in
      256,          // rc_target_bitrate
      0,            // rc_min_quantizer
      63,           // rc_max_quantizer
      25,           // rc_undershoot_pct
      25,           // rc_overshoot_pct

      6000,  // rc_max_buffer_size
      4000,  // rc_buffer_initial_size
      5000,  // rc_buffer_optimal_size

      50,    // rc_two_pass_vbrbias
      0,     // rc_two_pass_vbrmin_section
      2000,  // rc_two_pass_vbrmax_section

      // keyframing settings (kf)
      0,                       // fwd_kf_enabled
      AOM_KF_AUTO,             // kf_mode
      0,                       // kf_min_dist
      9999,                    // kf_max_dist
      0,                       // sframe_dist
      1,                       // sframe_mode
      0,                       // large_scale_tile
      0,                       // monochrome
      0,                       // full_still_picture_hdr
      0,                       // save_as_annexb
      0,                       // tile_width_count
      0,                       // tile_height_count
      { 0 },                   // tile_widths
      { 0 },                   // tile_heights
      0,                       // use_fixed_qp_offsets
      { -1, -1, -1, -1, -1 },  // fixed_qp_offsets
      { 0, 128, 128, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
        0, 0,   0,   0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },  // cfg
  },
#endif  // !CONFIG_REALTIME_ONLY
  {
      // NOLINT
      AOM_USAGE_REALTIME,  // g_usage - real-time usage
      0,                   // g_threads
      0,                   // g_profile

      320,         // g_w
      240,         // g_h
      0,           // g_limit
      0,           // g_forced_max_frame_width
      0,           // g_forced_max_frame_height
      AOM_BITS_8,  // g_bit_depth
      8,           // g_input_bit_depth

      { 1, 30 },  // g_timebase

      0,  // g_error_resilient

      AOM_RC_ONE_PASS,  // g_pass

      0,  // g_lag_in_frames

      0,                // rc_dropframe_thresh
      RESIZE_NONE,      // rc_resize_mode
      SCALE_NUMERATOR,  // rc_resize_denominator
      SCALE_NUMERATOR,  // rc_resize_kf_denominator

      AOM_SUPERRES_NONE,  // rc_superres_mode
      SCALE_NUMERATOR,    // rc_superres_denominator
      SCALE_NUMERATOR,    // rc_superres_kf_denominator
      63,                 // rc_superres_qthresh
      32,                 // rc_superres_kf_qthresh

      AOM_CBR,      // rc_end_usage
      { NULL, 0 },  // rc_twopass_stats_in
      { NULL, 0 },  // rc_firstpass_mb_stats_in
      256,          // rc_target_bitrate
      0,            // rc_min_quantizer
      63,           // rc_max_quantizer
      25,           // rc_undershoot_pct
      25,           // rc_overshoot_pct

      6000,  // rc_max_buffer_size
      4000,  // rc_buffer_initial_size
      5000,  // rc_buffer_optimal_size

      50,    // rc_two_pass_vbrbias
      0,     // rc_two_pass_vbrmin_section
      2000,  // rc_two_pass_vbrmax_section

      // keyframing settings (kf)
      0,                       // fwd_kf_enabled
      AOM_KF_AUTO,             // kf_mode
      0,                       // kf_min_dist
      9999,                    // kf_max_dist
      0,                       // sframe_dist
      1,                       // sframe_mode
      0,                       // large_scale_tile
      0,                       // monochrome
      0,                       // full_still_picture_hdr
      0,                       // save_as_annexb
      0,                       // tile_width_count
      0,                       // tile_height_count
      { 0 },                   // tile_widths
      { 0 },                   // tile_heights
      0,                       // use_fixed_qp_offsets
      { -1, -1, -1, -1, -1 },  // fixed_qp_offsets
      { 0, 128, 128, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
        0, 0,   0,   0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },  // cfg
  },
#if !CONFIG_REALTIME_ONLY
  {
      // NOLINT
      AOM_USAGE_ALL_INTRA,  // g_usage - all intra usage
      0,                    // g_threads
      0,                    // g_profile

      320,         // g_w
      240,         // g_h
      0,           // g_limit
      0,           // g_forced_max_frame_width
      0,           // g_forced_max_frame_height
      AOM_BITS_8,  // g_bit_depth
      8,           // g_input_bit_depth

      { 1, 30 },  // g_timebase

      0,  // g_error_resilient

      AOM_RC_ONE_PASS,  // g_pass

      0,  // g_lag_in_frames

      0,                // rc_dropframe_thresh
      RESIZE_NONE,      // rc_resize_mode
      SCALE_NUMERATOR,  // rc_resize_denominator
      SCALE_NUMERATOR,  // rc_resize_kf_denominator

      AOM_SUPERRES_NONE,  // rc_superres_mode
      SCALE_NUMERATOR,    // rc_superres_denominator
      SCALE_NUMERATOR,    // rc_superres_kf_denominator
      63,                 // rc_superres_qthresh
      32,                 // rc_superres_kf_qthresh

      AOM_Q,        // rc_end_usage
      { NULL, 0 },  // rc_twopass_stats_in
      { NULL, 0 },  // rc_firstpass_mb_stats_in
      256,          // rc_target_bitrate
      0,            // rc_min_quantizer
      63,           // rc_max_quantizer
      25,           // rc_undershoot_pct
      25,           // rc_overshoot_pct

      6000,  // rc_max_buffer_size
      4000,  // rc_buffer_initial_size
      5000,  // rc_buffer_optimal_size

      50,    // rc_two_pass_vbrbias
      0,     // rc_two_pass_vbrmin_section
      2000,  // rc_two_pass_vbrmax_section

      // keyframing settings (kf)
      0,                       // fwd_kf_enabled
      AOM_KF_DISABLED,         // kf_mode
      0,                       // kf_min_dist
      0,                       // kf_max_dist
      0,                       // sframe_dist
      1,                       // sframe_mode
      0,                       // large_scale_tile
      0,                       // monochrome
      0,                       // full_still_picture_hdr
      0,                       // save_as_annexb
      0,                       // tile_width_count
      0,                       // tile_height_count
      { 0 },                   // tile_widths
      { 0 },                   // tile_heights
      0,                       // use_fixed_qp_offsets
      { -1, -1, -1, -1, -1 },  // fixed_qp_offsets
      { 0, 128, 128, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
        0, 0,   0,   0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },  // cfg
  },
#endif  // !CONFIG_REALTIME_ONLY
};

// This data structure and function are exported in aom/aomcx.h
#ifndef VERSION_STRING
#define VERSION_STRING
#endif
aom_codec_iface_t aom_codec_av1_cx_algo = {
  "AOMedia Project AV1 Encoder" VERSION_STRING,
  AOM_CODEC_INTERNAL_ABI_VERSION,
  AOM_CODEC_CAP_HIGHBITDEPTH | AOM_CODEC_CAP_ENCODER |
      AOM_CODEC_CAP_PSNR,  // aom_codec_caps_t
  encoder_init,            // aom_codec_init_fn_t
  encoder_destroy,         // aom_codec_destroy_fn_t
  encoder_ctrl_maps,       // aom_codec_ctrl_fn_map_t
  {
      // NOLINT
      NULL,  // aom_codec_peek_si_fn_t
      NULL,  // aom_codec_get_si_fn_t
      NULL,  // aom_codec_decode_fn_t
      NULL,  // aom_codec_get_frame_fn_t
      NULL   // aom_codec_set_fb_fn_t
  },
  {
      // NOLINT
      NELEMENTS(encoder_usage_cfg),  // cfg_count
      encoder_usage_cfg,             // aom_codec_enc_cfg_t
      encoder_encode,                // aom_codec_encode_fn_t
      encoder_get_cxdata,            // aom_codec_get_cx_data_fn_t
      encoder_set_config,            // aom_codec_enc_config_set_fn_t
      encoder_get_global_headers,    // aom_codec_get_global_headers_fn_t
      encoder_get_preview            // aom_codec_get_preview_frame_fn_t
  },
  encoder_set_option  // aom_codec_set_option_fn_t
};

aom_codec_iface_t *aom_codec_av1_cx(void) { return &aom_codec_av1_cx_algo; }