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

media / gpu / windows / media_foundation_video_encode_accelerator_win.cc [blame]

// Copyright 2016 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#ifdef UNSAFE_BUFFERS_BUILD
// TODO(crbug.com/40285824): Remove this and convert code to safer constructs.
#pragma allow_unsafe_buffers
#endif

#include "media/gpu/windows/media_foundation_video_encode_accelerator_win.h"

#include <objbase.h>

#include <codecapi.h>
#include <d3d11_1.h>
#include <mfapi.h>
#include <mferror.h>
#include <mftransform.h>

#include <algorithm>
#include <iterator>
#include <memory>
#include <utility>
#include <vector>

#include "base/containers/fixed_flat_set.h"
#include "base/features.h"
#include "base/memory/shared_memory_mapping.h"
#include "base/memory/unsafe_shared_memory_region.h"
#include "base/native_library.h"
#include "base/task/sequenced_task_runner.h"
#include "base/task/thread_pool.h"
#include "base/time/time.h"
#include "base/trace_event/trace_event.h"
#include "base/win/scoped_co_mem.h"
#include "base/win/scoped_variant.h"
#include "base/win/win_util.h"
#include "build/build_config.h"
#include "gpu/command_buffer/service/shared_context_state.h"
#include "gpu/ipc/common/dxgi_helpers.h"
#include "gpu/ipc/service/shared_image_stub.h"
#include "media/base/bitstream_buffer.h"
#include "media/base/media_log.h"
#include "media/base/media_switches.h"
#include "media/base/video_codecs.h"
#include "media/base/video_frame.h"
#include "media/base/video_util.h"
#include "media/base/win/color_space_util_win.h"
#include "media/base/win/mf_helpers.h"
#include "media/base/win/mf_initializer.h"
#include "media/gpu/gpu_video_encode_accelerator_helpers.h"
#include "media/gpu/h264_rate_controller.h"
#include "media/gpu/h264_ratectrl_rtc.h"
#include "media/gpu/windows/av1_video_rate_control_wrapper.h"
#include "media/gpu/windows/h264_video_rate_control_wrapper.h"
#include "media/gpu/windows/mf_video_encoder_shared_state.h"
#include "media/gpu/windows/mf_video_encoder_switches.h"
#include "media/gpu/windows/vp9_video_rate_control_wrapper.h"
#include "media/parsers/temporal_scalability_id_extractor.h"
#include "third_party/libaom/source/libaom/av1/ratectrl_rtc.h"
#include "third_party/libvpx/source/libvpx/vp9/ratectrl_rtc.h"
#include "third_party/libyuv/include/libyuv.h"
#include "ui/gfx/color_space_win.h"
#include "ui/gfx/gpu_memory_buffer.h"

using Microsoft::WRL::ComPtr;

namespace media {

namespace {
constexpr uint32_t kDefaultGOPLength = 3000;
constexpr uint32_t kDefaultTargetBitrate = 5000000u;
constexpr size_t kNumInputBuffers = 3;
// Media Foundation uses 100 nanosecond units for time, see
// https://msdn.microsoft.com/en-us/library/windows/desktop/ms697282(v=vs.85).aspx.
constexpr size_t kOneMicrosecondInMFSampleTimeUnits = 10;

// Get distance from current frame to next temporal base layer frame.
uint32_t GetDistanceToNextTemporalBaseLayer(uint32_t frame_number,
                                            uint32_t temporal_layer_count) {
  DCHECK(temporal_layer_count >= 1 && temporal_layer_count <= 3);
  uint32_t pattern_count = 1 << (temporal_layer_count - 1);
  return (frame_number % pattern_count == 0)
             ? 0
             : pattern_count - (frame_number % pattern_count);
}

// Per
// https://learn.microsoft.com/en-us/windows/win32/medfound/handling-stream-changes,
// encoders should only accept an input type that matches the currently
// configured output type. If we want to change the frame rate, a
// stream restart flow is needed, which in turn generates a key-frame on the
// stream restart. This is not friendly for WebRTC encoding, which adjusts the
// encoding frame rate frequently.
// To mitigate this, we only configure the frame rate during HMFT
// initialization. On subsequent frame rate update request, if new frame rate is
// larger than currently configured frame rate and bitrate is kept unchanged,
// this implies average encoded frame size should decrease proportionally. Since
// we don't actually configure the new frame rate into HMFT(to avoid stream
// restart), we emulate this average frame size decrease by proportionally
// decreasing the target/peak bitrate(which does not require stream restart).
// This is similar for frame rate update request that is lower than currently
// configured, by increasing bitrate to emulate average frame size increase.
// See https://crbug.com/1295815 for more details.
uint32_t AdjustBitrateToFrameRate(uint32_t bitrate,
                                  uint32_t configured_framerate,
                                  uint32_t requested_framerate) {
  if (requested_framerate == 0u) {
    return 0u;
  }

  return bitrate * configured_framerate / requested_framerate;
}

VideoRateControlWrapper::RateControlConfig CreateRateControllerConfig(
    const VideoBitrateAllocation& bitrate_allocation,
    gfx::Size size,
    uint32_t frame_rate,
    int num_temporal_layers,
    VideoCodec codec,
    VideoEncodeAccelerator::Config::ContentType content_type) {
  // Fill rate control config variables.
  VideoRateControlWrapper::RateControlConfig config;
  config.content_type = content_type;
  config.width = size.width();
  config.height = size.height();
  config.target_bandwidth = bitrate_allocation.GetSumBps() / 1000;
  config.framerate = frame_rate;
  config.ss_number_layers = 1;
  config.ts_number_layers = num_temporal_layers;
  switch (codec) {
    case VideoCodec::kVP9: {
      config.max_quantizer = kVP9MaxQuantizer;
      config.min_quantizer = kVP9MinQuantizer;
      break;
    }
    case VideoCodec::kAV1: {
      config.max_quantizer = kAV1MaxQuantizer;
      config.min_quantizer = kAV1MinQuantizer;
      break;
    }
    case VideoCodec::kH264: {
      config.max_quantizer = kH264MaxQuantizer;
      config.min_quantizer = kH264MinQuantizer;
      break;
    }
#if BUILDFLAG(ENABLE_PLATFORM_HEVC)
    case VideoCodec::kHEVC: {
      config.max_quantizer = kH265MaxQuantizer;
      config.min_quantizer = kH265MinQuantizer;
      break;
    }
#endif  // BUILDFLAG(ENABLE_PLATFORM_HEVC)
    default:
      NOTREACHED();
  }
  int bitrate_sum = 0;
  for (int tid = 0; tid < num_temporal_layers; ++tid) {
    bitrate_sum += bitrate_allocation.GetBitrateBps(0, tid);
    config.layer_target_bitrate[tid] = bitrate_sum / 1000;
    config.ts_rate_decimator[tid] = 1u << (num_temporal_layers - tid - 1);
    config.min_quantizers[tid] = config.min_quantizer;
    config.max_quantizers[tid] = config.max_quantizer;
  }
  if ((codec == VideoCodec::kH264 || codec == VideoCodec::kHEVC) &&
      num_temporal_layers > 1 &&
      base::FeatureList::IsEnabled(kMediaFoundationSWBRCUseFixedDeltaQP)) {
    // `fixed_delta_qp` is used by H.264 and H.265 SW BRCs only in temporal
    // scalability video mode.
    config.fixed_delta_qp = kMediaFoundationSWBRCFixedDeltaQPValue.Get();
  }
  return config;
}

bool IsMatchingDevice(CHROME_LUID desired_luid, ID3D11Device* device) {
  ComDXGIDevice dxgi_device;
  if (FAILED(device->QueryInterface(IID_PPV_ARGS(&dxgi_device)))) {
    return false;
  }
  ComDXGIAdapter dxgi_adapter;
  if (FAILED(dxgi_device->GetAdapter(&dxgi_adapter))) {
    return false;
  }
  DXGI_ADAPTER_DESC adapter_desc{};
  if (FAILED(dxgi_adapter->GetDesc(&adapter_desc))) {
    return false;
  }

  if (adapter_desc.AdapterLuid.HighPart == desired_luid.HighPart &&
      adapter_desc.AdapterLuid.LowPart == desired_luid.LowPart) {
    return true;
  }

  return false;
}

}  // namespace

struct MediaFoundationVideoEncodeAccelerator::PendingInput {
  PendingInput() = default;
  ~PendingInput() = default;
  PendingInput(const PendingInput&) = default;
  // If true, output bits should be discarded and the rate control object
  // shouldn't be let known about the encode.
  bool discard_output = false;
  EncodeOptions options;
  base::TimeDelta timestamp;
  gfx::ColorSpace color_space;
  ComMFSample input_sample;
  bool resolving_shared_image = false;
};

class MediaFoundationVideoEncodeAccelerator::EncodeOutput {
 public:
  EncodeOutput(uint32_t size, const BitstreamBufferMetadata& md)
      : metadata(md), data_(size) {}

  EncodeOutput(const EncodeOutput&) = delete;
  EncodeOutput& operator=(const EncodeOutput&) = delete;

  uint8_t* memory() { return data_.data(); }
  int size() const { return static_cast<int>(data_.size()); }

  BitstreamBufferMetadata metadata;

 private:
  std::vector<uint8_t> data_;
};

struct MediaFoundationVideoEncodeAccelerator::BitstreamBufferRef {
  BitstreamBufferRef() = delete;

  BitstreamBufferRef(int32_t id,
                     base::WritableSharedMemoryMapping mapping,
                     size_t size)
      : id(id), mapping(std::move(mapping)), size(size) {}

  BitstreamBufferRef(const BitstreamBufferRef&) = delete;
  BitstreamBufferRef& operator=(const BitstreamBufferRef&) = delete;

  const int32_t id;
  base::WritableSharedMemoryMapping mapping;
  const size_t size;
};

MediaFoundationVideoEncodeAccelerator::MediaFoundationVideoEncodeAccelerator(
    const gpu::GpuPreferences& gpu_preferences,
    const gpu::GpuDriverBugWorkarounds& gpu_workarounds,
    CHROME_LUID luid)
    : task_runner_(base::SingleThreadTaskRunner::GetCurrentDefault()),
      luid_(luid),
      gpu_preferences_(gpu_preferences),
      workarounds_(gpu_workarounds) {
  weak_ptr_ = weak_factory_.GetWeakPtr();
  bitrate_allocation_.SetBitrate(0, 0, kDefaultTargetBitrate);
}

MediaFoundationVideoEncodeAccelerator::
    ~MediaFoundationVideoEncodeAccelerator() {
  DVLOG(3) << __func__;
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  DCHECK(async_callback_ref_.IsOne());
}

VideoEncodeAccelerator::SupportedProfiles
MediaFoundationVideoEncodeAccelerator::GetSupportedProfiles() {
  TRACE_EVENT0("gpu,startup",
               "MediaFoundationVideoEncodeAccelerator::GetSupportedProfiles");
  DVLOG(3) << __func__;
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);

  MediaFoundationVideoEncoderSharedState* mf_shared_state =
      MediaFoundationVideoEncoderSharedState::GetInstance(workarounds_);

  return mf_shared_state->GetSupportedProfiles();
}

bool MediaFoundationVideoEncodeAccelerator::Initialize(
    const Config& config,
    Client* client,
    std::unique_ptr<MediaLog> media_log) {
  DVLOG(3) << __func__ << ": " << config.AsHumanReadableString();
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  media_log_ = std::move(media_log);

  bool is_supported_format = false;
  if (base::FeatureList::IsEnabled(kMediaFoundationD3DVideoProcessing)) {
    is_supported_format =
        base::ranges::find(kSupportedPixelFormatsD3DVideoProcessing,
                           config.input_format) != kSupportedPixelFormats.end();
  } else {
    is_supported_format =
        base::ranges::find(kSupportedPixelFormats, config.input_format) !=
        kSupportedPixelFormats.end();
  }

  if (!is_supported_format) {
    MEDIA_LOG(ERROR, media_log_)
        << "Input format not supported= "
        << VideoPixelFormatToString(config.input_format);
    return false;
  }

  if (config.output_profile >= H264PROFILE_MIN &&
      config.output_profile <= H264PROFILE_MAX) {
    if (GetH264VProfile(config.output_profile, config.is_constrained_h264) ==
        eAVEncH264VProfile_unknown) {
      MEDIA_LOG(ERROR, media_log_)
          << "Output profile not supported = " << config.output_profile;
      return false;
    }
    codec_ = VideoCodec::kH264;
  } else if (config.output_profile >= VP9PROFILE_MIN &&
             config.output_profile <= VP9PROFILE_MAX) {
    if (GetVP9VProfile(config.output_profile) == eAVEncVP9VProfile_unknown) {
      MEDIA_LOG(ERROR, media_log_)
          << "Output profile not supported = " << config.output_profile;
      return false;
    }
    codec_ = VideoCodec::kVP9;
  } else if (config.output_profile == AV1PROFILE_PROFILE_MAIN) {
    codec_ = VideoCodec::kAV1;
  } else if (config.output_profile == HEVCPROFILE_MAIN) {
#if BUILDFLAG(ENABLE_PLATFORM_HEVC)
    if (base::FeatureList::IsEnabled(kPlatformHEVCEncoderSupport)) {
      codec_ = VideoCodec::kHEVC;
    }
#endif
  }
  profile_ = config.output_profile;
  content_type_ = config.content_type;

  if (codec_ == VideoCodec::kUnknown) {
    MEDIA_LOG(ERROR, media_log_)
        << "Output profile not supported = " << config.output_profile;
    return false;
  }

  if (config.HasSpatialLayer()) {
    MEDIA_LOG(ERROR, media_log_) << "MediaFoundation does not support "
                                    "spatial layer encoding.";
    return false;
  }
  client_ = client;

  input_format_ = config.input_format;
  input_visible_size_ = config.input_visible_size;
  if (config.framerate > 0) {
    frame_rate_ = config.framerate;
  } else {
    frame_rate_ = kDefaultFrameRateNumerator / kDefaultFrameRateDenominator;
  }
  bitrate_allocation_ = AllocateBitrateForDefaultEncoding(config);

  bitstream_buffer_size_ =
      EstimateBitstreamBufferSize(bitrate_allocation_.GetSumBitrate(),
                                  frame_rate_, config.input_visible_size);
  gop_length_ = config.gop_length.value_or(kDefaultGOPLength);
  low_latency_mode_ = config.require_low_delay;

  if (config.HasTemporalLayer())
    num_temporal_layers_ = config.spatial_layers.front().num_of_temporal_layers;

  input_since_keyframe_count_ = 0;
  zero_layer_counter_ = 0;
  // Init bitream parser in the case temporal scalability encoding.
  svc_parser_ = std::make_unique<TemporalScalabilityIdExtractor>(
      codec_, num_temporal_layers_);

  if (state_ == kAcquiringCommandBuffer) {
    SetState(kInitializingWithCommandBuffer);
  } else {
    SetState(kInitializing);
  }

  std::vector<ComPtr<IMFActivate>> activates =
      EnumerateHardwareEncoders(codec_);

  if (activates.empty()) {
    NotifyErrorStatus({EncoderStatus::Codes::kEncoderInitializationError,
                       "Failed finding a hardware encoder MFT"});
    return false;
  }

  bool activated = ActivateAsyncEncoder(activates, config.is_constrained_h264);
  activates.clear();

  if (!activated) {
    NotifyErrorStatus({EncoderStatus::Codes::kEncoderInitializationError,
                       "Failed activating an async hardware encoder MFT"});
    return false;
  }

  // Set the SW implementation of the rate controller. Do nothing if SW RC is
  // not supported.
  SetSWRateControl();

  if (!SetEncoderModes()) {
    NotifyErrorStatus({EncoderStatus::Codes::kEncoderInitializationError,
                       "Failed to set encoder modes"});
    return false;
  }

  if (!InitializeInputOutputParameters(config.output_profile,
                                       config.is_constrained_h264)) {
    NotifyErrorStatus({EncoderStatus::Codes::kEncoderInitializationError,
                       "Failed to set input/output param."});
    return false;
  }

  // Get the max framerate and max/min resolutions of the given codec.
  //
  // NOTE:
  // We first attempt to retrieve max framerate and max/min resolutions from
  // cached data. If there is a cache miss, that implies the current encoder is
  // not on the same adapter as that used by "GetSupportedProfiles". If so we
  // use the actual encoder to retrieve max framerate and max/min resolutions.
  // The property `MF_VIDEO_MAX_MB_PER_SEC`, which we use to calculate the
  // resolution, is a static value stored in the encoder provided by the GPU
  // driver. It doesn't change regardless of the parameters we set for
  // `SetOutputType()` except for `MF_MT_MAJOR_TYPE` and `MF_MT_SUBTYPE`. So, as
  // long as the actual encoder remains the same, the result should be
  // unchanged. If the actual encoder can't handle the incoming resolution, we
  // can simply reject it without hesitation.
  if (base::FeatureList::IsEnabled(kExpandMediaFoundationEncodingResolutions)) {
    size_t activate_hash = GetMFTGuidHash(activate_.Get());
    MediaFoundationVideoEncoderSharedState* shared_state =
        MediaFoundationVideoEncoderSharedState::GetInstance(workarounds_);
    DCHECK(shared_state);
    const auto& max_framerate_and_resolutions =
        shared_state->GetMaxFramerateAndResolutions(activate_hash);
    const auto& min_resolution = shared_state->GetMinResolution(activate_hash);
    max_framerate_and_resolutions_ =
        !max_framerate_and_resolutions.empty()
            ? max_framerate_and_resolutions
            : GetMaxFramerateAndResolutionsFromMFT(
                  codec_, encoder_.Get(), /*allow_set_output_type=*/false);
    min_resolution_ = !min_resolution.IsEmpty()
                          ? min_resolution
                          : GetMinResolution(codec_, vendor_);
  } else {
    max_framerate_and_resolutions_ = {kDefaultMaxFramerateAndResolution};
    min_resolution_ = kDefaultMinResolution;
  }
  // Ideally, we should check size before `InitializeInputOutputParameters()`
  // because it sets `MF_MT_FRAME_SIZE` when `SetOutputType()` is called.
  // However, since we can only retrieve `MF_VIDEO_MAX_MB_PER_SEC` after calling
  // `SetOutputType()`, we have to check the frame size at this point.
  if (!IsFrameSizeAllowed(config.input_visible_size)) {
    NotifyErrorStatus({EncoderStatus::Codes::kEncoderUnsupportedConfig,
                       "Unsupported frame size"});
    return false;
  }

  for (auto& [framerate, resolution] : max_framerate_and_resolutions_) {
    // TODO(crbug.com/382015342): Add implementation for checking bitrate
    // limits.
    encoder_info_.resolution_rate_limits.emplace_back(
        resolution, /*min_start_bitrate_bps=*/0, /*min_bitrate_bps=*/0,
        /*max_bitrate_bps=*/0, /*max_framerate_numerator=*/framerate,
        /*max_framerate_denominator=*/1);

    resolution.Transpose();
    encoder_info_.resolution_rate_limits.emplace_back(
        resolution,
        /*min_start_bitrate_bps=*/0, /*min_bitrate_bps=*/0,
        /*max_bitrate_bps=*/0, /*max_framerate_numerator=*/framerate,
        /*max_framerate_denominator=*/1);
    resolution.Transpose();
  }

  encoder_info_.implementation_name = "MediaFoundationVideoEncodeAccelerator";
  // Currently, MFVEA does not support odd resolution well. The implementation
  // here reports alignment of 2 in the EncoderInfo, together with simulcast
  // layers applied.
  // See https://crbug.com/1275453 for more details.
  encoder_info_.requested_resolution_alignment = 2;
  encoder_info_.apply_alignment_to_all_simulcast_layers = true;
  encoder_info_.has_trusted_rate_controller = false;
  DCHECK(encoder_info_.is_hardware_accelerated);
  DCHECK(encoder_info_.supports_native_handle);
  DCHECK(encoder_info_.reports_average_qp);
  DCHECK(!encoder_info_.supports_simulcast);
  if (config.HasSpatialLayer() || config.HasTemporalLayer()) {
    DCHECK(!config.spatial_layers.empty());
    for (size_t i = 0; i < config.spatial_layers.size(); ++i) {
      encoder_info_.fps_allocation[i] =
          GetFpsAllocation(config.spatial_layers[i].num_of_temporal_layers);
    }
  } else {
    constexpr uint8_t kFullFramerate = 255;
    encoder_info_.fps_allocation[0] = {kFullFramerate};
  }

  encoder_info_.supports_frame_size_change =
      !workarounds_.disable_media_foundation_frame_size_change;

  if (state_ == kInitializing) {
    if (!InitializeMFT(nullptr)) {
      return false;
    }
  }

  // Notify encoder info change to client after initialization succeeded.
  client_->NotifyEncoderInfoChange(encoder_info_);

  return true;
}

bool MediaFoundationVideoEncodeAccelerator::InitializeMFT(
    ID3D11Device* shared_device) {
  HRESULT hr;
  if (IsMediaFoundationD3D11VideoCaptureEnabled()) {
    MEDIA_LOG(INFO, media_log_)
        << "Preferred DXGI device " << luid_.HighPart << ":" << luid_.LowPart;
    if (shared_device) {
      MEDIA_LOG(INFO, media_log_) << "Using shared d3d device";
      dxgi_device_manager_ = DXGIDeviceManager::Create(luid_, shared_device);
    } else {
      dxgi_device_manager_ = DXGIDeviceManager::Create(luid_);
    }

    if (!dxgi_device_manager_) {
      NotifyErrorStatus({EncoderStatus::Codes::kEncoderInitializationError,
                         "Failed to create DXGIDeviceManager"});
      return false;
    }

    LUID mft_luid{0, 0};
    UINT32 out_size = 0;
    activate_->GetBlob(MFT_ENUM_ADAPTER_LUID,
                       reinterpret_cast<BYTE*>(&mft_luid), sizeof(LUID),
                       &out_size);

    hr = E_FAIL;
    if (out_size == sizeof(LUID) && mft_luid.HighPart == luid_.HighPart &&
        mft_luid.LowPart == luid_.LowPart) {
      // Only try to set the device manager for MFTs on the correct adapter.
      // Don't rely on MFT rejecting the device manager.
      auto mf_dxgi_device_manager =
          dxgi_device_manager_->GetMFDXGIDeviceManager();
      hr = encoder_->ProcessMessage(
          MFT_MESSAGE_SET_D3D_MANAGER,
          reinterpret_cast<ULONG_PTR>(mf_dxgi_device_manager.Get()));
    }
    // Can't use D3D11 decoding if HMFT is on a wrong LUID or rejects
    // setting a DXGI device manager.
    if (FAILED(hr)) {
      dxgi_resource_mapping_required_ = true;
      MEDIA_LOG(INFO, media_log_)
          << "Couldn't set DXGIDeviceManager, fallback to non-D3D11 encoding";
    }
  }

  hr = encoder_->QueryInterface(IID_PPV_ARGS(&event_generator_));
  if (FAILED(hr)) {
    NotifyErrorStatus({EncoderStatus::Codes::kEncoderInitializationError,
                       "Couldn't get event generator: " + PrintHr(hr)});
    return false;
  }

  event_generator_->BeginGetEvent(this, nullptr);

  // Start the asynchronous processing model
  hr = encoder_->ProcessMessage(MFT_MESSAGE_COMMAND_FLUSH, 0);
  if (FAILED(hr)) {
    NotifyErrorStatus(
        {EncoderStatus::Codes::kEncoderInitializationError,
         "Couldn't set ProcessMessage MFT_MESSAGE_COMMAND_FLUSH: " +
             PrintHr(hr)});
    return false;
  }
  hr = encoder_->ProcessMessage(MFT_MESSAGE_NOTIFY_BEGIN_STREAMING, 0);
  if (FAILED(hr)) {
    NotifyErrorStatus(
        {EncoderStatus::Codes::kEncoderInitializationError,
         "Couldn't set ProcessMessage MFT_MESSAGE_NOTIFY_BEGIN_STREAMING: " +
             PrintHr(hr)});
    return false;
  }
  hr = encoder_->ProcessMessage(MFT_MESSAGE_NOTIFY_START_OF_STREAM, 0);
  if (FAILED(hr)) {
    NotifyErrorStatus(
        {EncoderStatus::Codes::kEncoderInitializationError,
         "Couldn't set ProcessMessage MFT_MESSAGE_NOTIFY_START_OF_STREAM: " +
             PrintHr(hr)});
    return false;
  }
  encoder_needs_input_counter_ = 0;

  if (!base::FeatureList::IsEnabled(kMediaFoundationD3DVideoProcessing) ||
      input_format_ == PIXEL_FORMAT_NV12) {
    return true;
  }

  mf_video_processor_ =
      std::make_unique<MediaFoundationVideoProcessorAccelerator>(
          gpu_preferences_, workarounds_);
  MediaFoundationVideoProcessorAccelerator::Config vp_config;
  vp_config.input_format = input_format_;
  vp_config.input_visible_size = input_visible_size_;
  // Primaries information is provided per frame and will be
  // attached to the corresponding IMFSample.  This color
  // space information now serves as a default if frame
  // primaries are unknown.
  vp_config.input_color_space = gfx::ColorSpace::CreateREC709();
  vp_config.output_format = VideoPixelFormat::PIXEL_FORMAT_NV12;
  vp_config.output_visible_size = input_visible_size_;
  vp_config.output_color_space = gfx::ColorSpace::CreateREC709();
  if (dxgi_resource_mapping_required_) {
    hr = mf_video_processor_->Initialize(vp_config, nullptr,
                                         media_log_->Clone());
  } else {
    hr = mf_video_processor_->Initialize(vp_config, dxgi_device_manager_,
                                         media_log_->Clone());
  }

  if (FAILED(hr)) {
    NotifyErrorStatus({EncoderStatus::Codes::kEncoderInitializationError,
                       "Couldn't initialize MF video processor for color "
                       "format conversion"});
    return false;
  }

  MEDIA_LOG(INFO, media_log_)
      << "Using video processor to convert from " << input_format_
      << " to encoder accepted " << vp_config.output_format;

  return true;
}

void MediaFoundationVideoEncodeAccelerator::Encode(
    scoped_refptr<VideoFrame> frame,
    bool force_keyframe) {
  Encode(std::move(frame), EncodeOptions(force_keyframe));
}

void MediaFoundationVideoEncodeAccelerator::Encode(
    scoped_refptr<VideoFrame> frame,
    const EncodeOptions& options) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  if (codec_ == VideoCodec::kVP9 &&
      workarounds_.avoid_consecutive_keyframes_for_vp9 &&
      last_frame_was_keyframe_request_ && options.key_frame) {
    // Force a fake frame in between two key frames that come in a row. The
    // MFVEA will discard the output of this frame, and the client will never
    // see any side effects, but it helps working around crbug.com/1473665.
    EncodeOptions discard_options(/*key_frame=*/false);
    EncodeInternal(frame, discard_options, /*discard_output=*/true);
  }

  bool force_key_frame =
      (input_since_keyframe_count_ + pending_input_queue_.size()) %
          gop_length_ ==
      0;

  bool discard_high_layer_frames =
      (((codec_ == VideoCodec::kVP9 || codec_ == VideoCodec::kAV1) &&
        vendor_ == DriverVendor::kIntel) ||
       (codec_ == VideoCodec::kH264 && (vendor_ == DriverVendor::kIntel ||
                                        vendor_ == DriverVendor::kNvidia))) &&
      IsTemporalScalabilityCoding() && (options.key_frame || force_key_frame);

  if (discard_high_layer_frames) {
    // Currently, Intel and NVIDIA drivers only allow apps to request keyframe
    // on base layer(T0) when encoding at L1T2/L1T3, any keyframe requests on
    // T1/T2 layer will be ignored by driver and not return a keyframe. For
    // VP9, AV1 and H.264, we expect when keyframe is requested, encoder will
    // reset the temporal layer state and produce a keyframe, to work around
    // this issue, MFVEA will add input and internally discard output until
    // driver transition to T0 layer.

    uint32_t distance_to_base_layer = GetDistanceToNextTemporalBaseLayer(
        input_since_keyframe_count_ + pending_input_queue_.size(),
        num_temporal_layers_);
    for (uint32_t i = 0; i < distance_to_base_layer; ++i) {
      EncodeOptions discard_options(/*key_frame=*/false);
      EncodeInternal(frame, discard_options, /*discard_output=*/true);
    }
  }

  EncodeInternal(std::move(frame), options, /*discard_output=*/false);
  last_frame_was_keyframe_request_ = options.key_frame;
}

void MediaFoundationVideoEncodeAccelerator::QueueInput(
    scoped_refptr<media::VideoFrame> frame,
    const VideoEncoder::EncodeOptions& options,
    bool discard_output) {
  PendingInput result;
  auto hr = MFCreateSample(&result.input_sample);
  if (FAILED(hr)) {
    NotifyErrorStatus({EncoderStatus::Codes::kEncoderInitializationError,
                       "Failed to create sample"});
    return;
  }
  result.timestamp = frame->timestamp();
  result.color_space = frame->ColorSpace();
  result.options = options;
  result.discard_output = discard_output;

  if (!frame->VideoFrame::HasMappableGpuBuffer() && frame->HasSharedImage() &&
      command_buffer_helper_) {
    result.resolving_shared_image = true;
    pending_input_queue_.push_back(result);
    auto d3d_device = dxgi_device_manager_->GetDevice();
    if (!d3d_device) {
      NotifyErrorStatus({EncoderStatus::Codes::kSystemAPICallError,
                         "Failed to get D3D device manager"});
      return;
    }

    gpu_task_runner_->PostTask(
        FROM_HERE,
        base::BindOnce(
            &GenerateSampleFromSharedImageVideoFrame, frame,
            std::move(d3d_device), command_buffer_helper_,
            base::BindPostTask(
                task_runner_,
                base::BindOnce(&MediaFoundationVideoEncodeAccelerator::
                                   OnSharedImageSampleAvailable,
                               weak_ptr_))));
    return;
  }

  hr = PopulateInputSampleBuffer(result, std::move(frame));
  if (FAILED(hr)) {
    NotifyErrorStatus({EncoderStatus::Codes::kEncoderFailedEncode,
                       "Failed to populate input sample buffer"});
    return;
  }

  pending_input_queue_.push_back(result);
}

void MediaFoundationVideoEncodeAccelerator::EncodeInternal(
    scoped_refptr<VideoFrame> frame,
    const EncodeOptions& options,
    bool discard_output) {
  DVLOG(3) << __func__;
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);

  switch (state_) {
    case kEncoding: {
      QueueInput(std::move(frame), options, discard_output);
      // Check the status of METransformNeedInput counter, only feed input when
      // MFT is ready.
      if (encoder_needs_input_counter_ > 0) {
        FeedInputs();
      }
      break;
    }
    case kInitializingWithCommandBuffer:
      [[fallthrough]];
    case kWaitingForCommandBuffer:
      [[fallthrough]];
    case kInitializing: {
      QueueInput(std::move(frame), options, discard_output);
      break;
    }
    default:
      NotifyErrorStatus({EncoderStatus::Codes::kEncoderFailedEncode,
                         "Unexpected encoder state"});
      DVLOG(3) << "Abandon input frame for video encoder."
               << " State: " << static_cast<int>(state_);
  }
}

void MediaFoundationVideoEncodeAccelerator::UseOutputBitstreamBuffer(
    BitstreamBuffer buffer) {
  DVLOG(3) << __func__ << ": buffer size=" << buffer.size();
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);

  if (buffer.size() < bitstream_buffer_size_) {
    NotifyErrorStatus({EncoderStatus::Codes::kInvalidOutputBuffer,
                       "Output BitstreamBuffer isn't big enough: " +
                           base::NumberToString(buffer.size()) + " vs. " +
                           base::NumberToString(bitstream_buffer_size_)});
    return;
  }

  // After mapping, |region| is no longer necessary and it can be destroyed.
  // |mapping| will keep the shared memory region open.
  auto region = buffer.TakeRegion();
  auto mapping = region.Map();
  if (!mapping.IsValid()) {
    NotifyErrorStatus({EncoderStatus::Codes::kSystemAPICallError,
                       "Failed mapping shared memory"});
    return;
  }
  auto buffer_ref = std::make_unique<BitstreamBufferRef>(
      buffer.id(), std::move(mapping), buffer.size());

  if (encoder_output_queue_.empty()) {
    bitstream_buffer_queue_.push_back(std::move(buffer_ref));
    return;
  }
  auto encode_output = std::move(encoder_output_queue_.front());
  encoder_output_queue_.pop_front();
  memcpy(buffer_ref->mapping.memory(), encode_output->memory(),
         encode_output->size());

  client_->BitstreamBufferReady(buffer_ref->id, encode_output->metadata);
  if (encoder_output_queue_.empty() && state_ == kPostFlushing) {
    // We were waiting for all the outputs to be consumed by the client.
    // Now once it's happened, we can signal the Flush() has finished
    // and continue encoding.
    SetState(kEncoding);
    std::move(flush_callback_).Run(true);
  }
}

void MediaFoundationVideoEncodeAccelerator::RequestEncodingParametersChange(
    const Bitrate& bitrate,
    uint32_t framerate,
    const std::optional<gfx::Size>& size) {
  DVLOG(3) << __func__ << ": bitrate=" << bitrate.ToString()
           << ": framerate=" << framerate
           << ": size=" << (size.has_value() ? size->ToString() : "nullopt");
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);

  VideoBitrateAllocation allocation(bitrate.mode());
  switch (bitrate.mode()) {
    case Bitrate::Mode::kVariable:
      allocation.SetBitrate(0, 0, bitrate.target_bps());
      allocation.SetPeakBps(bitrate.peak_bps());
      break;
    case Bitrate::Mode::kConstant:
      allocation.SetBitrate(0, 0, bitrate.target_bps());
      break;
    case Bitrate::Mode::kExternal:
      break;
  }

  RequestEncodingParametersChange(allocation, framerate, size);
}

void MediaFoundationVideoEncodeAccelerator::RequestEncodingParametersChange(
    const VideoBitrateAllocation& bitrate_allocation,
    uint32_t framerate,
    const std::optional<gfx::Size>& size) {
  DVLOG(3) << __func__ << ": bitrate=" << bitrate_allocation.GetSumBps()
           << ": framerate=" << framerate
           << ": size=" << (size.has_value() ? size->ToString() : "nullopt");
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);

  DCHECK(imf_output_media_type_);
  DCHECK(imf_input_media_type_);
  DCHECK(encoder_);

  // RTC will pass a very small bitrate(1 bps) to the encoder when its bitrate
  // allocator assigns zero bitrate as part of initial setup. Ignore the request
  // to avoid CHECK failures on those BRC creations.
  if (bitrate_allocation.GetSumBps() <= 1) {
    DLOG(WARNING) << "Ignoring bitrate allocation request with 1 bps or less.";
    return;
  }

  if (bitrate_allocation.GetMode() != bitrate_allocation_.GetMode()) {
    NotifyErrorStatus({EncoderStatus::Codes::kEncoderUnsupportedConfig,
                       "Can't change bitrate mode after Initialize()"});
    return;
  }

  if (framerate == 0) {
    framerate = kDefaultFrameRateNumerator / kDefaultFrameRateDenominator;
  }

  if (framerate == frame_rate_ && bitrate_allocation == bitrate_allocation_ &&
      !size.has_value()) {
    return;
  }

  bitrate_allocation_ = bitrate_allocation;
  frame_rate_ = framerate;
  // For SW BRC we don't reconfigure the encoder.
  if (rate_ctrl_) {
    rate_ctrl_->UpdateRateControl(CreateRateControllerConfig(
        bitrate_allocation_, size.value_or(input_visible_size_), frame_rate_,
        num_temporal_layers_, codec_, content_type_));
  } else {
    VARIANT var;
    var.vt = VT_UI4;
    HRESULT hr;
    switch (bitrate_allocation_.GetMode()) {
      case Bitrate::Mode::kVariable:
        var.ulVal = AdjustBitrateToFrameRate(bitrate_allocation_.GetPeakBps(),
                                             configured_frame_rate_, framerate);
        DVLOG(3) << "bitrate_allocation_.GetPeakBps() is "
                 << bitrate_allocation_.GetPeakBps();
        DVLOG(3) << "configured_frame_rate_ is " << configured_frame_rate_;
        DVLOG(3) << "framerate is " << framerate;
        DVLOG(3) << "Setting AVEncCommonMaxBitRate to " << var.ulVal;
        hr = codec_api_->SetValue(&CODECAPI_AVEncCommonMaxBitRate, &var);
        if (FAILED(hr)) {
          NotifyErrorStatus({EncoderStatus::Codes::kSystemAPICallError,
                             "Couldn't set max bitrate" + PrintHr(hr)});
          return;
        }
        [[fallthrough]];
      case Bitrate::Mode::kConstant:
        var.ulVal = AdjustBitrateToFrameRate(bitrate_allocation_.GetSumBps(),
                                             configured_frame_rate_, framerate);
        DVLOG(3) << "bitrate_allocation_.GetSumBps() is "
                 << bitrate_allocation_.GetSumBps();
        DVLOG(3) << "configured_frame_rate_ is " << configured_frame_rate_;
        DVLOG(3) << "framerate is " << framerate;
        DVLOG(3) << "Setting CODECAPI_AVEncCommonMeanBitRate to " << var.ulVal;
        hr = codec_api_->SetValue(&CODECAPI_AVEncCommonMeanBitRate, &var);
        if (FAILED(hr)) {
          NotifyErrorStatus({EncoderStatus::Codes::kSystemAPICallError,
                             "Couldn't set mean bitrate" + PrintHr(hr)});
          return;
        }
        break;
      case Bitrate::Mode::kExternal:
        DVLOG(3)
            << "RequestEncodingParametersChange for Bitrate::Mode::kExternal";
        break;
    }
  }

  if (size.has_value()) {
    UpdateFrameSize(size.value());
  }
}

bool MediaFoundationVideoEncodeAccelerator::IsFrameSizeAllowed(gfx::Size size) {
  // It's possible `max_framerate_and_resolutions_` is empty when we
  // failed to retrieve `MF_VIDEO_MAX_MB_PER_SEC`.
  DCHECK(!min_resolution_.IsEmpty());

  for (auto& [frame_rate, resolution] : max_framerate_and_resolutions_) {
    // TODO(crbug.com/365813271): Add framerate check once we can make sure
    // WebRTC check framerate before calling `RequestEncodingParametersChange`.
    if (size.width() >= min_resolution_.width() &&
        size.height() >= min_resolution_.height() &&
        size.width() <= resolution.width() &&
        size.height() <= resolution.height()) {
      return true;
    }

    size.Transpose();
    // Portrait profile only transpose max resolution.
    if (size.height() >= min_resolution_.width() &&
        size.width() >= min_resolution_.height() &&
        size.width() <= resolution.width() &&
        size.height() <= resolution.height()) {
      return true;
    }

    size.Transpose();
  }

  return false;
}

void MediaFoundationVideoEncodeAccelerator::UpdateFrameSize(
    const gfx::Size& frame_size) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  DCHECK(imf_output_media_type_);
  DCHECK(imf_input_media_type_);
  DCHECK(activate_);
  DCHECK(encoder_);
  DCHECK_NE(input_visible_size_, frame_size);
  DCHECK(pending_input_queue_.empty());

  if (!IsFrameSizeAllowed(frame_size)) {
    NotifyErrorStatus({EncoderStatus::Codes::kEncoderUnsupportedConfig,
                       "Unsupported frame size"});
    return;
  }
  input_visible_size_ = frame_size;

  HRESULT hr = S_OK;
  // As this method is expected to be called after Flush(), it's safe to send
  // MFT_MESSAGE_COMMAND_FLUSH here. Without MFT_MESSAGE_COMMAND_FLUSH, MFT may
  // either:
  // - report 0x80004005 (Unspecified error) when encode the first frame after
  //   resolution change on Intel platform.
  // - report issues with SPS/PPS in the NALU analyzer phase of the tests on
  //   Qualcomm platform.
  if (vendor_ == DriverVendor::kIntel || vendor_ == DriverVendor::kQualcomm) {
    hr = encoder_->ProcessMessage(MFT_MESSAGE_COMMAND_FLUSH, 0);
    if (FAILED(hr)) {
      NotifyErrorStatus(
          {EncoderStatus::Codes::kSystemAPICallError,
           "Couldn't set ProcessMessage MFT_MESSAGE_COMMAND_FLUSH: " +
               PrintHr(hr)});
      return;
    }
  }
  // Reset the need input counter since MFT was notified to end stream.
  encoder_needs_input_counter_ = 0;
  hr = encoder_->ProcessMessage(MFT_MESSAGE_NOTIFY_END_OF_STREAM, 0);
  if (FAILED(hr)) {
    NotifyErrorStatus(
        {EncoderStatus::Codes::kSystemAPICallError,
         "Couldn't set ProcessMessage MFT_MESSAGE_NOTIFY_END_OF_STREAM: " +
             PrintHr(hr)});
    return;
  }
  hr = encoder_->ProcessMessage(MFT_MESSAGE_NOTIFY_END_STREAMING, 0);
  if (FAILED(hr)) {
    NotifyErrorStatus(
        {EncoderStatus::Codes::kSystemAPICallError,
         "Couldn't set ProcessMessage MFT_MESSAGE_NOTIFY_END_STREAMING: " +
             PrintHr(hr)});
    return;
  }
  hr = encoder_->SetInputType(input_stream_id_, nullptr, 0);
  if (FAILED(hr)) {
    NotifyErrorStatus(
        {EncoderStatus::Codes::kSystemAPICallError,
         "Couldn't set input stream type to nullptr: " + PrintHr(hr)});
    return;
  }
  hr = encoder_->SetOutputType(output_stream_id_, nullptr, 0);
  if (FAILED(hr)) {
    NotifyErrorStatus(
        {EncoderStatus::Codes::kSystemAPICallError,
         "Couldn't set output stream type to nullptr: " + PrintHr(hr)});
    return;
  }
  hr = MFSetAttributeSize(imf_output_media_type_.Get(), MF_MT_FRAME_SIZE,
                          input_visible_size_.width(),
                          input_visible_size_.height());
  if (FAILED(hr)) {
    NotifyErrorStatus({EncoderStatus::Codes::kSystemAPICallError,
                       "Couldn't set output frame size: " + PrintHr(hr)});
    return;
  }
  hr = encoder_->SetOutputType(output_stream_id_, imf_output_media_type_.Get(),
                               0);
  if (FAILED(hr)) {
    NotifyErrorStatus({EncoderStatus::Codes::kSystemAPICallError,
                       "Couldn't set output media type: " + PrintHr(hr)});
    return;
  }
  hr = MFSetAttributeSize(imf_input_media_type_.Get(), MF_MT_FRAME_SIZE,
                          input_visible_size_.width(),
                          input_visible_size_.height());
  if (FAILED(hr)) {
    NotifyErrorStatus({EncoderStatus::Codes::kSystemAPICallError,
                       "Couldn't set input frame size: " + PrintHr(hr)});
    return;
  }
  hr = encoder_->SetInputType(input_stream_id_, imf_input_media_type_.Get(), 0);
  if (FAILED(hr)) {
    NotifyErrorStatus({EncoderStatus::Codes::kSystemAPICallError,
                       "Couldn't set input media type: " + PrintHr(hr)});
    return;
  }
  hr = encoder_->ProcessMessage(MFT_MESSAGE_NOTIFY_BEGIN_STREAMING, 0);
  if (FAILED(hr)) {
    NotifyErrorStatus(
        {EncoderStatus::Codes::kSystemAPICallError,
         "Couldn't set ProcessMessage MFT_MESSAGE_NOTIFY_BEGIN_STREAMING: " +
             PrintHr(hr)});
    return;
  }
  hr = encoder_->ProcessMessage(MFT_MESSAGE_NOTIFY_START_OF_STREAM, 0);
  if (FAILED(hr)) {
    NotifyErrorStatus(
        {EncoderStatus::Codes::kSystemAPICallError,
         "Couldn't set ProcessMessage MFT_MESSAGE_NOTIFY_START_OF_STREAM: " +
             PrintHr(hr)});
    return;
  }

  bitstream_buffer_size_ = EstimateBitstreamBufferSize(
      bitrate_allocation_.GetSumBitrate(), frame_rate_, input_visible_size_);
  bitstream_buffer_queue_.clear();
  // Reset the input frame counter since MFT was notified to end the streaming
  // and restart with new frame size.
  input_since_keyframe_count_ = 0;
  client_->RequireBitstreamBuffers(kNumInputBuffers, input_visible_size_,
                                   bitstream_buffer_size_);
}

void MediaFoundationVideoEncodeAccelerator::Destroy() {
  DVLOG(3) << __func__;
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);

  if (activate_) {
    activate_->ShutdownObject();
    activate_->Release();
  }
  delete this;
}

void MediaFoundationVideoEncodeAccelerator::DrainEncoder() {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  auto hr = encoder_->ProcessMessage(MFT_MESSAGE_COMMAND_DRAIN, 0);
  if (FAILED(hr)) {
    std::move(flush_callback_).Run(/*success=*/false);
    return;
  }
  SetState(kFlushing);
}

void MediaFoundationVideoEncodeAccelerator::Flush(
    FlushCallback flush_callback) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  DCHECK(flush_callback);

  if (state_ != kEncoding || !encoder_) {
    DCHECK(false) << "Called Flush() with unexpected state."
                  << " State: " << static_cast<int>(state_);
    std::move(flush_callback).Run(/*success=*/false);
    return;
  }

  flush_callback_ = std::move(flush_callback);
  if (pending_input_queue_.empty()) {
    // There are no pending inputs we can just ask MF encoder to drain without
    // having to wait for any more METransformNeedInput requests.
    DrainEncoder();
  } else {
    // Otherwise METransformNeedInput will call DrainEncoder() when all the
    // inputs from `pending_input_queue_` were fed to the MF encoder.
    SetState(kPreFlushing);
  }
}

bool MediaFoundationVideoEncodeAccelerator::IsFlushSupported() {
  return true;
}

bool MediaFoundationVideoEncodeAccelerator::IsGpuFrameResizeSupported() {
  return true;
}

MediaFoundationVideoEncodeAccelerator::GetCommandBufferHelperResult::
    GetCommandBufferHelperResult() = default;
MediaFoundationVideoEncodeAccelerator::GetCommandBufferHelperResult::
    GetCommandBufferHelperResult(const MediaFoundationVideoEncodeAccelerator::
                                     GetCommandBufferHelperResult& other) =
        default;
MediaFoundationVideoEncodeAccelerator::GetCommandBufferHelperResult::
    ~GetCommandBufferHelperResult() = default;

MediaFoundationVideoEncodeAccelerator::GetCommandBufferHelperResult
GetCommandBufferHelperOnGpuThread(
    base::RepeatingCallback<scoped_refptr<CommandBufferHelper>()>
        get_command_buffer_helper_cb,
    CHROME_LUID luid) {
  MediaFoundationVideoEncodeAccelerator::GetCommandBufferHelperResult result;
  result.command_buffer_helper = get_command_buffer_helper_cb.Run();
  scoped_refptr<gpu::SharedContextState> shared_context_state =
      result.command_buffer_helper->GetSharedImageStub()
          ->shared_context_state();

  if (shared_context_state->GetD3D11Device()) {
    DCHECK(
        IsMatchingDevice(luid, shared_context_state->GetD3D11Device().Get()));
    result.shared_d3d_device = shared_context_state->GetD3D11Device();
    Microsoft::WRL::ComPtr<ID3D11Multithread> multi_threaded;
    HRESULT hr =
        result.shared_d3d_device->QueryInterface(IID_PPV_ARGS(&multi_threaded));
    CHECK(SUCCEEDED(hr));
    multi_threaded->SetMultithreadProtected(TRUE);
  }

  return result;
}

void MediaFoundationVideoEncodeAccelerator::SetCommandBufferHelperCB(
    base::RepeatingCallback<scoped_refptr<CommandBufferHelper>()>
        get_command_buffer_helper_cb,
    scoped_refptr<base::SingleThreadTaskRunner> gpu_task_runner) {
  if (!base::FeatureList::IsEnabled(kMediaFoundationSharedImageEncode)) {
    return;
  }

  SetState(kAcquiringCommandBuffer);
  gpu_task_runner_ = gpu_task_runner;
  gpu_task_runner->PostTaskAndReplyWithResult(
      FROM_HERE,
      base::BindOnce(&GetCommandBufferHelperOnGpuThread,
                     get_command_buffer_helper_cb, luid_),
      base::BindOnce(&MediaFoundationVideoEncodeAccelerator::
                         OnCommandBufferHelperAvailable,
                     weak_ptr_));
}

bool MediaFoundationVideoEncodeAccelerator::ActivateAsyncEncoder(
    std::vector<ComPtr<IMFActivate>>& activates,
    bool is_constrained_h264) {
  DVLOG(3) << __func__;
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);

  // Try to create the encoder with priority according to merit value.
  HRESULT hr = E_FAIL;
  for (auto& activate : activates) {
    auto vendor = GetDriverVendor(activate.Get());

    // Skip NVIDIA GPU due to https://crbug.com/1088650 for constrained
    // baseline profile H.264 encoding, and go to the next instance according
    // to merit value.
    if (codec_ == VideoCodec::kH264 && is_constrained_h264 &&
        vendor == DriverVendor::kNvidia) {
      DLOG(WARNING) << "Skipped NVIDIA GPU due to https://crbug.com/1088650";
      continue;
    }

    if (num_temporal_layers_ >
        GetMaxTemporalLayerVendorLimit(vendor, codec_, workarounds_)) {
      DLOG(WARNING) << "Skipped GPUs due to not supporting temporal layer";
      continue;
    }

    DCHECK(!encoder_);
    DCHECK(!activate_);
    hr = activate->ActivateObject(IID_PPV_ARGS(&encoder_));
    if (encoder_.Get() != nullptr) {
      DCHECK(SUCCEEDED(hr));
      activate_ = activate;
      vendor_ = vendor;

      // Print the friendly name.
      base::win::ScopedCoMem<WCHAR> friendly_name;
      UINT32 name_length;
      activate_->GetAllocatedString(MFT_FRIENDLY_NAME_Attribute, &friendly_name,
                                    &name_length);
      DVLOG(3) << "Selected asynchronous hardware encoder's friendly name: "
               << friendly_name;
      // Encoder is successfully activated.
      break;
    } else {
      DCHECK(FAILED(hr));

      // The component that calls ActivateObject is
      // responsible for calling ShutdownObject,
      // https://docs.microsoft.com/en-us/windows/win32/api/mfobjects/nf-mfobjects-imfactivate-shutdownobject.
      activate->ShutdownObject();
    }
  }

  RETURN_ON_HR_FAILURE(hr, "Couldn't activate asynchronous hardware encoder",
                       false);
  RETURN_ON_FAILURE((encoder_.Get() != nullptr),
                    "No asynchronous hardware encoder instance created", false);

  ComMFAttributes all_attributes;
  hr = encoder_->GetAttributes(&all_attributes);
  if (SUCCEEDED(hr)) {
    // An asynchronous MFT must support dynamic format changes,
    // https://docs.microsoft.com/en-us/windows/win32/medfound/asynchronous-mfts#format-changes.
    UINT32 dynamic = FALSE;
    hr = all_attributes->GetUINT32(MFT_SUPPORT_DYNAMIC_FORMAT_CHANGE, &dynamic);
    if (!dynamic) {
      DLOG(ERROR) << "Couldn't support dynamic format change.";
      return false;
    }

    // Unlock the selected asynchronous MFTs,
    // https://docs.microsoft.com/en-us/windows/win32/medfound/asynchronous-mfts#unlocking-asynchronous-mfts.
    UINT32 async = FALSE;
    hr = all_attributes->GetUINT32(MF_TRANSFORM_ASYNC, &async);
    if (!async) {
      DLOG(ERROR) << "MFT encoder is not asynchronous.";
      return false;
    }

    hr = all_attributes->SetUINT32(MF_TRANSFORM_ASYNC_UNLOCK, TRUE);
    RETURN_ON_HR_FAILURE(hr, "Couldn't unlock transform async", false);
  }

  return true;
}

bool MediaFoundationVideoEncodeAccelerator::InitializeInputOutputParameters(
    VideoCodecProfile output_profile,
    bool is_constrained_h264) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  DCHECK(encoder_);

  DWORD input_count = 0;
  DWORD output_count = 0;
  HRESULT hr = encoder_->GetStreamCount(&input_count, &output_count);
  RETURN_ON_HR_FAILURE(hr, "Couldn't get stream count", false);
  if (input_count < 1 || output_count < 1) {
    DLOG(ERROR) << "Stream count too few: input " << input_count << ", output "
                << output_count;
    return false;
  }

  std::vector<DWORD> input_ids(input_count, 0);
  std::vector<DWORD> output_ids(output_count, 0);
  hr = encoder_->GetStreamIDs(input_count, input_ids.data(), output_count,
                              output_ids.data());
  if (hr == S_OK) {
    input_stream_id_ = input_ids[0];
    output_stream_id_ = output_ids[0];
  } else if (hr == E_NOTIMPL) {
    input_stream_id_ = 0;
    output_stream_id_ = 0;
  } else {
    DLOG(ERROR) << "Couldn't find stream ids from hardware encoder.";
    return false;
  }

  // Initialize output parameters.
  hr = MFCreateMediaType(&imf_output_media_type_);
  RETURN_ON_HR_FAILURE(hr, "Couldn't create output media type", false);
  hr = imf_output_media_type_->SetGUID(MF_MT_MAJOR_TYPE, MFMediaType_Video);
  RETURN_ON_HR_FAILURE(hr, "Couldn't set media type", false);
  hr = imf_output_media_type_->SetGUID(MF_MT_SUBTYPE,
                                       VideoCodecToMFSubtype(codec_));
  RETURN_ON_HR_FAILURE(hr, "Couldn't set video format", false);

  if (!rate_ctrl_) {
    UINT32 bitrate = AdjustBitrateToFrameRate(bitrate_allocation_.GetSumBps(),
                                              frame_rate_, frame_rate_);
    DVLOG(3) << "MF_MT_AVG_BITRATE is " << bitrate;
    // Setting MF_MT_AVG_BITRATE to zero will make some encoders upset
    if (bitrate > 0) {
      hr = imf_output_media_type_->SetUINT32(MF_MT_AVG_BITRATE, bitrate);
      RETURN_ON_HR_FAILURE(hr, "Couldn't set bitrate", false);
    }
  }
  configured_frame_rate_ = frame_rate_;

  hr = MFSetAttributeRatio(imf_output_media_type_.Get(), MF_MT_FRAME_RATE,
                           configured_frame_rate_, 1);
  RETURN_ON_HR_FAILURE(hr, "Couldn't set frame rate", false);
  hr = MFSetAttributeSize(imf_output_media_type_.Get(), MF_MT_FRAME_SIZE,
                          input_visible_size_.width(),
                          input_visible_size_.height());
  RETURN_ON_HR_FAILURE(hr, "Couldn't set frame size", false);
  hr = imf_output_media_type_->SetUINT32(MF_MT_INTERLACE_MODE,
                                         MFVideoInterlace_Progressive);
  RETURN_ON_HR_FAILURE(hr, "Couldn't set interlace mode", false);
  if (codec_ == VideoCodec::kH264) {
    hr = imf_output_media_type_->SetUINT32(
        MF_MT_MPEG2_PROFILE,
        GetH264VProfile(output_profile, is_constrained_h264));
  } else if (codec_ == VideoCodec::kVP9) {
    hr = imf_output_media_type_->SetUINT32(MF_MT_MPEG2_PROFILE,
                                           GetVP9VProfile(output_profile));
  } else if (codec_ == VideoCodec::kHEVC) {
    hr = imf_output_media_type_->SetUINT32(MF_MT_MPEG2_PROFILE,
                                           GetHEVCProfile(output_profile));
  }
  RETURN_ON_HR_FAILURE(hr, "Couldn't set codec profile", false);
  hr = encoder_->SetOutputType(output_stream_id_, imf_output_media_type_.Get(),
                               0);
  RETURN_ON_HR_FAILURE(hr, "Couldn't set output media type", false);

  // Initialize input parameters.
  hr = MFCreateMediaType(&imf_input_media_type_);
  RETURN_ON_HR_FAILURE(hr, "Couldn't create input media type", false);
  hr = imf_input_media_type_->SetGUID(MF_MT_MAJOR_TYPE, MFMediaType_Video);
  RETURN_ON_HR_FAILURE(hr, "Couldn't set media type", false);
  hr = imf_input_media_type_->SetGUID(MF_MT_SUBTYPE, MFVideoFormat_NV12);
  RETURN_ON_HR_FAILURE(hr, "Couldn't set video format", false);
  DVLOG(3) << "MF_MT_FRAME_RATE is " << configured_frame_rate_;
  hr = MFSetAttributeRatio(imf_input_media_type_.Get(), MF_MT_FRAME_RATE,
                           configured_frame_rate_, 1);
  RETURN_ON_HR_FAILURE(hr, "Couldn't set frame rate", false);
  DVLOG(3) << "MF_MT_FRAME_SIZE is " << input_visible_size_.width() << "x"
           << input_visible_size_.height();
  hr = MFSetAttributeSize(imf_input_media_type_.Get(), MF_MT_FRAME_SIZE,
                          input_visible_size_.width(),
                          input_visible_size_.height());
  RETURN_ON_HR_FAILURE(hr, "Couldn't set frame size", false);
  hr = imf_input_media_type_->SetUINT32(MF_MT_INTERLACE_MODE,
                                        MFVideoInterlace_Progressive);
  RETURN_ON_HR_FAILURE(hr, "Couldn't set interlace mode", false);
  hr = encoder_->SetInputType(input_stream_id_, imf_input_media_type_.Get(), 0);
  RETURN_ON_HR_FAILURE(hr, "Couldn't set input media type", false);

  return true;
}

void MediaFoundationVideoEncodeAccelerator::SetSWRateControl() {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);

  // Use SW BRC only in the case CBR encoding with number of temporal layers no
  // more than 3.
  if (bitrate_allocation_.GetMode() != Bitrate::Mode::kConstant ||
      !base::FeatureList::IsEnabled(kMediaFoundationUseSoftwareRateCtrl) ||
      num_temporal_layers_ > 3) {
    return;
  }

  // The following codecs support SW BRC: VP9, H264, HEVC, and AV1.
  VideoCodec kCodecsHaveSWBRC[] = {
      VideoCodec::kVP9,
      VideoCodec::kH264,
#if BUILDFLAG(ENABLE_PLATFORM_HEVC)
      VideoCodec::kHEVC,
#endif  // BUILDFLAG(ENABLE_PLATFORM_HEVC)
      VideoCodec::kAV1,
  };
  if (!base::Contains(kCodecsHaveSWBRC, codec_)) {
    return;
  }

  // Qualcomm (and possibly other vendor) AV1 HMFT does not work with SW BRC.
  // More info: https://crbug.com/343757696
  if (codec_ == VideoCodec::kAV1 && vendor_ == DriverVendor::kQualcomm) {
    return;  // SW BRC and QCOM AV1 HMFT not ok
  }

  if (codec_ == VideoCodec::kH264) {
    // H264 SW BRC supports up to two temporal layers.
    if (num_temporal_layers_ > 2) {
      return;
    }

    // Check feature flag for the camera source.
    if (content_type_ == VideoEncodeAccelerator::Config::ContentType::kCamera &&
        !base::FeatureList::IsEnabled(kMediaFoundationUseSWBRCForH264Camera)) {
      return;
    }

    // Check feature flag for the desktop source.
    if (content_type_ ==
            VideoEncodeAccelerator::Config::ContentType::kDisplay &&
        !base::FeatureList::IsEnabled(kMediaFoundationUseSWBRCForH264Desktop)) {
      return;
    }
  }

#if BUILDFLAG(ENABLE_PLATFORM_HEVC)
  if (codec_ == VideoCodec::kHEVC) {
    // H264 SW BRC supports up to two temporal layers.
    if (num_temporal_layers_ > 2) {
      return;
    }

    // Check feature flag.
    if ((vendor_ != DriverVendor::kIntel ||
         !workarounds_.disable_hevc_hmft_cbr_encoding) &&
        !base::FeatureList::IsEnabled(kMediaFoundationUseSWBRCForH265)) {
      return;
    }
  }
#endif

  VideoRateControlWrapper::RateControlConfig rate_config =
      CreateRateControllerConfig(bitrate_allocation_, input_visible_size_,
                                 frame_rate_, num_temporal_layers_, codec_,
                                 content_type_);
  if (codec_ == VideoCodec::kVP9) {
    rate_ctrl_ = VP9RateControl::Create(rate_config);
  } else if (codec_ == VideoCodec::kAV1) {
    rate_ctrl_ = AV1RateControl::Create(rate_config);
  } else if (codec_ == VideoCodec::kH264) {
    rate_ctrl_ = H264RateControl::Create(rate_config);
  } else if (codec_ == VideoCodec::kHEVC) {
#if BUILDFLAG(ENABLE_PLATFORM_HEVC)
    // Reuse the H.264 rate controller for HEVC.
    rate_ctrl_ = H264RateControl::Create(rate_config);
#endif  // BUILDFLAG(ENABLE_PLATFORM_HEVC)
  }
}

bool MediaFoundationVideoEncodeAccelerator::SetEncoderModes() {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  DCHECK(encoder_);

  HRESULT hr = encoder_.As(&codec_api_);
  RETURN_ON_HR_FAILURE(hr, "Couldn't get ICodecAPI", false);

  VARIANT var;
  var.vt = VT_UI4;
  switch (bitrate_allocation_.GetMode()) {
    case Bitrate::Mode::kConstant:
      if (rate_ctrl_) {
        DVLOG(3) << "SetEncoderModes() with Bitrate::Mode::kConstant and "
                    "rate_ctrl_, using eAVEncCommonRateControlMode_Quality";
        var.ulVal = eAVEncCommonRateControlMode_Quality;
      } else {
        DVLOG(3) << "SetEncoderModes() with Bitrate::Mode::kConstant and no "
                    "rate_ctrl_, using eAVEncCommonRateControlMode_CBR";
        var.ulVal = eAVEncCommonRateControlMode_CBR;
      }
      break;
    case Bitrate::Mode::kVariable: {
      DCHECK(!rate_ctrl_);
      DVLOG(3) << "SetEncoderModes() with Bitrate::Mode::kVariable, using "
                  "eAVEncCommonRateControlMode_PeakConstrainedVBR";
      var.ulVal = eAVEncCommonRateControlMode_PeakConstrainedVBR;
      break;
    }
    case Bitrate::Mode::kExternal:
      // Unsupported.
      DVLOG(3) << "SetEncoderModes() with Bitrate::Mode::kExternal, using "
                  "eAVEncCommonRateControlMode_Quality";
      var.ulVal = eAVEncCommonRateControlMode_Quality;
      break;
  }
  hr = codec_api_->SetValue(&CODECAPI_AVEncCommonRateControlMode, &var);
  RETURN_ON_HR_FAILURE(hr, "Couldn't set CommonRateControlMode", false);

  // Intel drivers want the layer count to be set explicitly for H.264/HEVC,
  // even if it's one.
  const bool set_svc_layer_count =
      (num_temporal_layers_ > 1) ||
      (vendor_ == DriverVendor::kIntel &&
       (codec_ == VideoCodec::kH264 || codec_ == VideoCodec::kHEVC));
  if (set_svc_layer_count) {
    var.ulVal = num_temporal_layers_;
    DVLOG(3) << "Setting CODECAPI_AVEncVideoTemporalLayerCount to "
             << var.ulVal;
    hr = codec_api_->SetValue(&CODECAPI_AVEncVideoTemporalLayerCount, &var);
    RETURN_ON_HR_FAILURE(hr, "Couldn't set temporal layer count", false);

    // On Intel platform at L1T2, for some codecs(AV1 & HEVC), recent drivers
    // allow configuring the number of reference frames to 1, which will produce
    // bitstream that follows WebRTC SVC spec for L1T2. For L1T3, however,
    // driver does not allow reducing the number of reference frames to 1.
    if (vendor_ == DriverVendor::kIntel && num_temporal_layers_ == 2) {
      if (S_OK ==
          codec_api_->IsModifiable(&CODECAPI_AVEncVideoMaxNumRefFrame)) {
        var.ulVal = 1;
        DVLOG(3) << "Setting CODECAPI_AVEncVideoMaxNumRefFrame to "
                 << var.ulVal;
        hr = codec_api_->SetValue(&CODECAPI_AVEncVideoMaxNumRefFrame, &var);
        if (SUCCEEDED(hr)) {
          encoder_produces_svc_spec_compliant_bitstream_ = true;
        } else {
          // Failing to set number of reference frames is not fatal.
          DVLOG(3) << "Couldn't set CODECAPI_AVEncVideoMaxNumRefFrame to 1";
        }
      }
    }
  }

  if (!rate_ctrl_ &&
      bitrate_allocation_.GetMode() != Bitrate::Mode::kExternal) {
    var.ulVal = AdjustBitrateToFrameRate(bitrate_allocation_.GetSumBps(),
                                         configured_frame_rate_, frame_rate_);
    DVLOG(3) << "bitrate_allocation_.GetSumBps() is "
             << bitrate_allocation_.GetSumBps();
    DVLOG(3) << "configured_frame_rate_ is " << configured_frame_rate_;
    DVLOG(3) << "framerate is " << frame_rate_;
    DVLOG(3) << "Setting CODECAPI_AVEncCommonMeanBitRate to " << var.ulVal;
    hr = codec_api_->SetValue(&CODECAPI_AVEncCommonMeanBitRate, &var);
    RETURN_ON_HR_FAILURE(hr, "Couldn't set bitrate", false);
  }

  if (bitrate_allocation_.GetMode() == Bitrate::Mode::kVariable) {
    var.ulVal = AdjustBitrateToFrameRate(bitrate_allocation_.GetPeakBps(),
                                         configured_frame_rate_, frame_rate_);
    DVLOG(3) << "bitrate_allocation_.GetPeakBps() is "
             << bitrate_allocation_.GetPeakBps();
    DVLOG(3) << "configured_frame_rate_ is " << configured_frame_rate_;
    DVLOG(3) << "framerate is " << frame_rate_;
    DVLOG(3) << "Setting CODECAPI_AVEncCommonMaxBitRate to " << var.ulVal;
    hr = codec_api_->SetValue(&CODECAPI_AVEncCommonMaxBitRate, &var);
    RETURN_ON_HR_FAILURE(hr, "Couldn't set bitrate", false);
  }

  if (S_OK == codec_api_->IsModifiable(&CODECAPI_AVEncAdaptiveMode)) {
    var.ulVal = eAVEncAdaptiveMode_Resolution;
    DVLOG(3) << "Setting CODECAPI_AVEncAdaptiveMode to " << var.ulVal;
    hr = codec_api_->SetValue(&CODECAPI_AVEncAdaptiveMode, &var);
    RETURN_ON_HR_FAILURE(hr, "Couldn't set adaptive mode", false);
  }

  var.ulVal = gop_length_;
  DVLOG(3) << "Setting CODECAPI_AVEncMPVGOPSize to " << var.ulVal;
  hr = codec_api_->SetValue(&CODECAPI_AVEncMPVGOPSize, &var);
  RETURN_ON_HR_FAILURE(hr, "Couldn't set keyframe interval", false);

  if (S_OK == codec_api_->IsModifiable(&CODECAPI_AVLowLatencyMode)) {
    var.vt = VT_BOOL;
    var.boolVal = low_latency_mode_ ? VARIANT_TRUE : VARIANT_FALSE;
    DVLOG(3) << "Setting CODECAPI_AVLowLatencyMode to " << var.boolVal;
    hr = codec_api_->SetValue(&CODECAPI_AVLowLatencyMode, &var);
    RETURN_ON_HR_FAILURE(hr, "Couldn't set low latency mode", false);
  }

  // For AV1 screen content encoding, configure scenario to enable AV1
  // SCC tools(palette mode, intra block copy, etc.) This will also turn
  // off CDEF on I-frame, and enable long term reference for screen contents.
  // For other codecs this may impact some encoding parameters as well.
  // TODO(crbugs.com/336592435): Set scenario info if we confirm it
  // works on other vendors, and possibly set eAVScenarioInfo_VideoConference
  // for camera streams if all drivers support it.
  if (S_OK == codec_api_->IsModifiable(&CODECAPI_AVScenarioInfo) &&
      vendor_ == DriverVendor::kIntel &&
      content_type_ == Config::ContentType::kDisplay) {
    var.vt = VT_UI4;
    var.ulVal = eAVScenarioInfo_DisplayRemoting;
    hr = codec_api_->SetValue(&CODECAPI_AVScenarioInfo, &var);
    RETURN_ON_HR_FAILURE(hr, "Couldn't set scenario info", false);
  }

  // For QCOM there are DCHECK issues with frame-dropping and timestamps due
  // to the AVScenarioInfo and b-frames, respectively.  Disable these, see
  // mfenc.c for similar logic.
  if (vendor_ == DriverVendor::kQualcomm) {
    var.vt = VT_UI4;
    // More info: https://crbug.com/343757695
    var.ulVal = eAVScenarioInfo_CameraRecord;
    hr = codec_api_->SetValue(&CODECAPI_AVScenarioInfo, &var);
    RETURN_ON_HR_FAILURE(hr, "Couldn't set scenario info", false);

    // More info: https://crbug.com/343748806
    var.ulVal = 0;
    hr = codec_api_->SetValue(&CODECAPI_AVEncMPVDefaultBPictureCount, &var);
    RETURN_ON_HR_FAILURE(hr, "Couldn't set bframe count", false);
  }

  return true;
}

void MediaFoundationVideoEncodeAccelerator::NotifyErrorStatus(
    EncoderStatus status) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  CHECK(!status.is_ok());
  CHECK(media_log_);
  SetState(kError);
  MEDIA_LOG(ERROR, media_log_) << status.message();
  DLOG(ERROR) << "Call NotifyErrorStatus(): code="
              << static_cast<int>(status.code())
              << ", message=" << status.message();
  CHECK(client_);
  client_->NotifyErrorStatus(std::move(status));
}

void MediaFoundationVideoEncodeAccelerator::FeedInputs() {
  if (pending_input_queue_.empty()) {
    return;
  }

  // There's no point in trying to feed more than one input here,
  // because MF encoder never accepts more than one input in a row.
  auto& next_input = pending_input_queue_.front();
  if (next_input.resolving_shared_image) {
    return;
  }

  HRESULT hr = ProcessInput(next_input);
  if (hr == MF_E_NOTACCEPTING) {
    return;
  }
  if (FAILED(hr)) {
    NotifyErrorStatus({EncoderStatus::Codes::kSystemAPICallError,
                       "Failed to encode pending frame: " + PrintHr(hr)});
    return;
  }
  encoder_needs_input_counter_--;
  pending_input_queue_.pop_front();
  input_since_keyframe_count_++;
}

HRESULT MediaFoundationVideoEncodeAccelerator::ProcessInput(
    const PendingInput& input) {
  DVLOG(3) << __func__;
  CHECK(input.input_sample);
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  CHECK(encoder_needs_input_counter_ > 0);
  TRACE_EVENT2("media", "MediaFoundationVideoEncodeAccelerator::ProcessInput",
               "timestamp", input.timestamp, "discard_output",
               input.discard_output);

  HRESULT hr = S_OK;
  if (has_not_accepted_sample_) {
    // Let's validate that prepared sample actually matches the metadata.
    const OutOfBandMetadata& metadata = sample_metadata_queue_.back();
    if (metadata.timestamp != input.timestamp) {
      LOG(ERROR) << "Prepared sample doesn't match metadata.";
      return E_FAIL;
    }
  } else {
    // Force key frame for the first frame in GOP.
    bool force_key_frame = input_since_keyframe_count_ % gop_length_ == 0;

    // Reset the frame count when keyframe is requested.
    if (input.options.key_frame || force_key_frame) {
      input_since_keyframe_count_ = 0;
    }

    int max_quantizer = AVEncQPtoQindex(codec_, GetMaxQuantizer(codec_));
    std::optional<uint8_t> quantizer;
    int temporal_id = 0;
    if (input.options.quantizer.has_value()) {
      DCHECK_EQ(codec_, VideoCodec::kH264);
      quantizer = std::clamp(static_cast<int>(input.options.quantizer.value()),
                             1, kH26xMaxQp);
    } else if (rate_ctrl_ && !input.discard_output) {
      VideoRateControlWrapper::FrameParams frame_params{};
      frame_params.frame_type =
          input.options.key_frame || force_key_frame
              ? VideoRateControlWrapper::FrameParams::FrameType::kKeyFrame
              : VideoRateControlWrapper::FrameParams::FrameType::kInterFrame;
      // H.264 and H.265 SW BRC need timestamp information.
      frame_params.timestamp = input.timestamp.InMilliseconds();
      temporal_id =
          svc_parser_->AssignTemporalIdBySvcSpec(input_since_keyframe_count_);
      frame_params.temporal_layer_id = temporal_id;
      // For now, MFVEA does not support spatial layer encoding.
      frame_params.spatial_layer_id = 0;
      // If there exists a rate_ctrl_, the qp computed by rate_ctrl_ should be
      // set on sample metadata and carried over from input to output.
      int computed_qp = rate_ctrl_->ComputeQP(frame_params);
      if (computed_qp < 0) {
        // Negative QP values mean that the frame should be dropped. We use
        // maximum QP in that case.
        // Drop frame functionality is not supported yet.
        // TODO(b/361250558): Support drop frame for H.264/HEVC Rate Controller
        computed_qp = max_quantizer;
      }
      quantizer = std::clamp(computed_qp, 1, max_quantizer);
    } else if (input.discard_output) {
      // Set up encoder for maximum speed if we're anyway going to discard the
      // output.
      quantizer = max_quantizer;
    }

    if (quantizer.has_value()) {
      VARIANT var;
      var.vt = VT_UI4;
      var.ulVal = temporal_id;
      DVLOG(3) << "Setting CODECAPI_AVEncVideoSelectLayer to " << var.ulVal;
      hr = codec_api_->SetValue(&CODECAPI_AVEncVideoSelectLayer, &var);
      RETURN_ON_HR_FAILURE(hr, "Couldn't set select temporal layer", hr);
      var.vt = VT_UI8;
      var.ullVal = QindextoAVEncQP(codec_, quantizer.value());
      DVLOG(3) << "Setting CODECAPI_AVEncVideoEncodeQP to " << var.ullVal;
      hr = codec_api_->SetValue(&CODECAPI_AVEncVideoEncodeQP, &var);
      RETURN_ON_HR_FAILURE(hr, "Couldn't set frame QP", hr);
      hr = input.input_sample->SetUINT64(MFSampleExtension_VideoEncodeQP,
                                         var.ullVal);
      RETURN_ON_HR_FAILURE(hr, "Couldn't set input sample attribute QP", hr);
    }
    if (input.options.key_frame || force_key_frame) {
      VARIANT var;
      var.vt = VT_UI4;
      var.ulVal = 1;
      DVLOG(3) << "Setting CODECAPI_AVEncVideoForceKeyFrame to " << var.ulVal;
      hr = codec_api_->SetValue(&CODECAPI_AVEncVideoForceKeyFrame, &var);
      RETURN_ON_HR_FAILURE(hr, "Set CODECAPI_AVEncVideoForceKeyFrame failed",
                           hr);
    }

    // We don't actually tell the MFT about the color space since all current
    // MFT implementations just write UNSPECIFIED in the bitstream, and setting
    // it can actually break some encoders; see https://crbug.com/1446081.
    sample_metadata_queue_.push_back(
        OutOfBandMetadata{.color_space = input.color_space,
                          .discard_output = input.discard_output,
                          .qp = quantizer,
                          .frame_id = input_since_keyframe_count_,
                          .timestamp = input.timestamp});
  }

  {
    TRACE_EVENT1("media", "IMFTransform::ProcessInput", "timestamp",
                 input.timestamp);
    hr = encoder_->ProcessInput(input_stream_id_, input.input_sample.Get(), 0);
  }

  // Check if ProcessInput() actually accepted the sample, if not, remember that
  // we don't need to prepare sample next time but just check the timestamp and
  // use it directly. This is a workaround for crbug.com/377749373 since HMFT
  // may reject to accept the new input which is corresponding to a
  // METransformNeedInput event.
  has_not_accepted_sample_ = (hr == MF_E_NOTACCEPTING);
  return hr;
}

HRESULT MediaFoundationVideoEncodeAccelerator::PopulateInputSampleBuffer(
    const PendingInput& input,
    scoped_refptr<VideoFrame> frame) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  auto input_sample = input.input_sample;
  bool supported_shared_image =
      frame->HasSharedImage() && command_buffer_helper_;
  if (frame->storage_type() !=
          VideoFrame::StorageType::STORAGE_GPU_MEMORY_BUFFER &&
      !frame->IsMappable() && !supported_shared_image) {
    LOG(ERROR) << "Unsupported video frame storage type";
    return MF_E_INVALID_STREAM_DATA;
  }

  TRACE_EVENT1(
      "media",
      "MediaFoundationVideoEncodeAccelerator::PopulateInputSampleBuffer",
      "timestamp", frame->timestamp());

  bool is_supported_format;
  if (base::FeatureList::IsEnabled(kMediaFoundationD3DVideoProcessing)) {
    is_supported_format =
        base::ranges::find(kSupportedPixelFormatsD3DVideoProcessing,
                           frame->format()) != kSupportedPixelFormats.end();
  } else {
    is_supported_format =
        base::ranges::find(kSupportedPixelFormats, frame->format()) !=
        kSupportedPixelFormats.end();
  }
  if (!is_supported_format) {
    LOG(ERROR) << "Unsupported video frame format";
    return MF_E_INVALID_STREAM_DATA;
  }

  auto hr = input_sample->SetSampleTime(frame->timestamp().InMicroseconds() *
                                        kOneMicrosecondInMFSampleTimeUnits);
  RETURN_ON_HR_FAILURE(hr, "SetSampleTime() failed", hr);

  UINT64 sample_duration = 0;
  hr = MFFrameRateToAverageTimePerFrame(frame_rate_, 1, &sample_duration);
  RETURN_ON_HR_FAILURE(hr, "Couldn't calculate sample duration", hr);

  hr = input_sample->SetSampleDuration(sample_duration);
  RETURN_ON_HR_FAILURE(hr, "SetSampleDuration() failed", hr);

  if (frame->HasMappableGpuBuffer() || supported_shared_image) {
    if ((frame->HasNativeGpuMemoryBuffer() ||
         (!frame->HasMappableGpuBuffer() && supported_shared_image)) &&
        dxgi_device_manager_ != nullptr) {
      if (!dxgi_resource_mapping_required_) {
        return PopulateInputSampleBufferGpu(std::move(frame), input_sample);
      } else {
        return CopyInputSampleBufferFromGpu(std::move(frame), input_sample);
      }
    }

    // ConvertToMemoryMappedFrame() doesn't copy pixel data,
    // it just maps GPU buffer owned by |frame| and presents it as mapped
    // view in CPU memory. |frame| will unmap the buffer when destructed.
    frame = ConvertToMemoryMappedFrame(std::move(frame));
    if (!frame) {
      LOG(ERROR) << "Failed to map shared memory GMB";
      return E_FAIL;
    }
  }

  const auto kTargetPixelFormat = PIXEL_FORMAT_NV12;
  ComMFMediaBuffer input_buffer;
  hr = input_sample->GetBufferByIndex(0, &input_buffer);
  if (FAILED(hr)) {
    // Allocate a new buffer.
    MFT_INPUT_STREAM_INFO input_stream_info;
    hr = encoder_->GetInputStreamInfo(input_stream_id_, &input_stream_info);
    RETURN_ON_HR_FAILURE(hr, "Couldn't get input stream info", hr);
    hr = MFCreateAlignedMemoryBuffer(
        input_stream_info.cbSize ? input_stream_info.cbSize
                                 : VideoFrame::AllocationSize(
                                       kTargetPixelFormat, input_visible_size_),
        input_stream_info.cbAlignment == 0 ? input_stream_info.cbAlignment
                                           : input_stream_info.cbAlignment - 1,
        &input_buffer);
    RETURN_ON_HR_FAILURE(hr, "Failed to create memory buffer", hr);
    hr = input_buffer->SetCurrentLength(
        input_stream_info.cbSize
            ? input_stream_info.cbSize
            : VideoFrame::AllocationSize(kTargetPixelFormat,
                                         input_visible_size_));
    RETURN_ON_HR_FAILURE(hr, "Failed to set length on buffer", hr);
    hr = input_sample->AddBuffer(input_buffer.Get());
    RETURN_ON_HR_FAILURE(hr, "Failed to add buffer to sample", hr);
  }

  // Establish plain pointers into the input buffer, where we will copy pixel
  // data to.
  MediaBufferScopedPointer scoped_buffer(input_buffer.Get());
  DCHECK(scoped_buffer.get());
  uint8_t* dst_y = scoped_buffer.get();
  size_t dst_y_stride = VideoFrame::RowBytes(
      VideoFrame::Plane::kY, kTargetPixelFormat, input_visible_size_.width());
  uint8_t* dst_uv =
      scoped_buffer.get() +
      dst_y_stride * VideoFrame::Rows(VideoFrame::Plane::kY, kTargetPixelFormat,
                                      input_visible_size_.height());
  size_t dst_uv_stride = VideoFrame::RowBytes(
      VideoFrame::Plane::kUV, kTargetPixelFormat, input_visible_size_.width());
  uint8_t* end =
      dst_uv + dst_uv_stride * VideoFrame::Rows(VideoFrame::Plane::kUV,
                                                kTargetPixelFormat,
                                                input_visible_size_.height());
  DCHECK_GE(static_cast<ptrdiff_t>(scoped_buffer.max_length()),
            end - scoped_buffer.get());

  // Set up a VideoFrame with the data pointing into the input buffer.
  // We need it to ease copying and scaling by reusing ConvertAndScale()
  auto frame_in_buffer = VideoFrame::WrapExternalYuvData(
      kTargetPixelFormat, input_visible_size_, gfx::Rect(input_visible_size_),
      input_visible_size_, dst_y_stride, dst_uv_stride, dst_y, dst_uv,
      frame->timestamp());

  auto status = frame_converter_.ConvertAndScale(*frame, *frame_in_buffer);
  if (!status.is_ok()) {
    LOG(ERROR) << "ConvertAndScale failed with error code: "
               << static_cast<uint32_t>(status.code());
    return E_FAIL;
  }
  return S_OK;
}

// Handle case where video frame is backed by a GPU texture, but needs to be
// copied to CPU memory, if HMFT does not accept texture from adapter
// different from that is currently used for encoding.
HRESULT MediaFoundationVideoEncodeAccelerator::CopyInputSampleBufferFromGpu(
    scoped_refptr<VideoFrame> frame,
    ComMFSample& input_sample) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  DCHECK(frame->storage_type() ==
             VideoFrame::StorageType::STORAGE_GPU_MEMORY_BUFFER ||
         frame->HasSharedImage());
  DCHECK(dxgi_device_manager_);

  auto d3d_device = dxgi_device_manager_->GetDevice();
  if (!d3d_device) {
    LOG(ERROR) << "Failed to get device from MF DXGI device manager";
    return E_HANDLE;
  }

  HRESULT hr;
  ComD3D11Texture2D input_texture;
  if (frame->storage_type() ==
      VideoFrame::StorageType::STORAGE_GPU_MEMORY_BUFFER) {
    gfx::GpuMemoryBufferHandle buffer_handle =
        frame->GetGpuMemoryBufferHandle();
    CHECK(!buffer_handle.is_null());
    CHECK_EQ(buffer_handle.type, gfx::GpuMemoryBufferType::DXGI_SHARED_HANDLE);

    ComD3D11Device1 device1;
    hr = d3d_device.As(&device1);
    RETURN_ON_HR_FAILURE(hr, "Failed to query ID3D11Device1", hr);
    hr = device1->OpenSharedResource1(buffer_handle.dxgi_handle.Get(),
                                      IID_PPV_ARGS(&input_texture));
    RETURN_ON_HR_FAILURE(hr, "Failed to open shared GMB D3D texture", hr);
  } else if (frame->HasSharedImage()) {
    DCHECK(input_sample);
    ComMFMediaBuffer texture_buffer;
    hr = input_sample->GetBufferByIndex(0, &texture_buffer);
    RETURN_ON_HR_FAILURE(hr, "Failed to get sample's buffer", hr);
    Microsoft::WRL::ComPtr<IMFDXGIBuffer> dxgi_buffer;
    hr = texture_buffer.As(&dxgi_buffer);
    RETURN_ON_HR_FAILURE(hr, "Failed to get dxgi buffer", hr);
    hr = dxgi_buffer->GetResource(IID_PPV_ARGS(&input_texture));
  }

  // Check if we need to scale the input texture
  D3D11_TEXTURE2D_DESC input_desc = {};
  input_texture->GetDesc(&input_desc);
  gfx::Size texture_size(input_desc.Width, input_desc.Height);
  ComD3D11Texture2D sample_texture;
  if (texture_size != input_visible_size_ ||
      frame->visible_rect().size() != input_visible_size_ ||
      !frame->visible_rect().origin().IsOrigin()) {
    hr = PerformD3DScaling(input_texture.Get(), frame->visible_rect());
    RETURN_ON_HR_FAILURE(hr, "Failed to perform D3D video processing", hr);
    sample_texture = scaled_d3d11_texture_;
  } else {
    sample_texture = input_texture;
  }

  ComMFMediaBuffer input_buffer;

  // Allocate a new buffer.
  MFT_INPUT_STREAM_INFO input_stream_info;
  hr = encoder_->GetInputStreamInfo(input_stream_id_, &input_stream_info);
  RETURN_ON_HR_FAILURE(hr, "Couldn't get input stream info", hr);
  hr = MFCreateAlignedMemoryBuffer(
      input_stream_info.cbSize
          ? input_stream_info.cbSize
          : VideoFrame::AllocationSize(frame->format(), input_visible_size_),
      input_stream_info.cbAlignment == 0 ? input_stream_info.cbAlignment
                                         : input_stream_info.cbAlignment - 1,
      &input_buffer);
  RETURN_ON_HR_FAILURE(hr, "Failed to create memory buffer for input sample",
                       hr);

  MediaBufferScopedPointer scoped_buffer(input_buffer.Get());
  bool copy_succeeded = gpu::CopyD3D11TexToMem(
      sample_texture.Get(), scoped_buffer.get(), scoped_buffer.max_length(),
      d3d_device.Get(), &staging_texture_);
  if (!copy_succeeded) {
    LOG(ERROR) << "Failed to copy sample to memory.";
    return E_FAIL;
  }
  size_t copied_bytes =
      input_visible_size_.width() * input_visible_size_.height() * 3 / 2;
  hr = input_buffer->SetCurrentLength(copied_bytes);
  RETURN_ON_HR_FAILURE(hr, "Failed to set current buffer length", hr);
  hr = input_sample->RemoveAllBuffers();
  RETURN_ON_HR_FAILURE(hr, "Failed to remove buffers from sample", hr);
  hr = input_sample->AddBuffer(input_buffer.Get());
  RETURN_ON_HR_FAILURE(hr, "Failed to add buffer to sample", hr);

  if (mf_video_processor_) {
    // This sample needs color space conversion
    ComMFSample vp_input_sample = std::move(input_sample);
    hr = mf_video_processor_->Convert(vp_input_sample.Get(), &input_sample);
    RETURN_ON_HR_FAILURE(hr, "Failed to convert input frame", hr);
  }

  return S_OK;
}

// Handle case where video frame is backed by a GPU texture
HRESULT MediaFoundationVideoEncodeAccelerator::PopulateInputSampleBufferGpu(
    scoped_refptr<VideoFrame> frame,
    ComMFSample& input_sample) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  DCHECK(dxgi_device_manager_);

  if (mf_video_processor_) {
    // Using the MF video processor mitigates many of the issues handled below.
    // - MFVP will resize if needed
    // - MFVP acquires the texture's keyed mutex when available and
    //    holds it only for the duration needed.
    // - MFVP will call SetCurrentLength on the output buffer
    // - MFVP will output a different texture that can be used
    //    as encoder input with no synchronization issues.
    HRESULT hr;
    if (frame->HasSharedImage()) {
      ComMFSample vp_input_sample = std::move(input_sample);
      hr = mf_video_processor_->Convert(vp_input_sample.Get(), &input_sample);
    } else {
      input_sample = nullptr;
      hr = mf_video_processor_->Convert(frame, &input_sample);
    }
    RETURN_ON_HR_FAILURE(hr, "Failed to convert input frame", hr);
    return S_OK;
  }

  // Check if we need to scale the input texture
  HRESULT hr;
  ComD3D11Texture2D input_texture;
  ComD3D11Texture2D sample_texture;
  if (frame->storage_type() ==
      VideoFrame::StorageType::STORAGE_GPU_MEMORY_BUFFER) {
    gfx::GpuMemoryBufferHandle buffer_handle =
        frame->GetGpuMemoryBufferHandle();
    CHECK(!buffer_handle.is_null());
    CHECK_EQ(buffer_handle.type, gfx::GpuMemoryBufferType::DXGI_SHARED_HANDLE);

    auto d3d_device = dxgi_device_manager_->GetDevice();
    if (!d3d_device) {
      LOG(ERROR) << "Failed to get device from MF DXGI device manager";
      return E_HANDLE;
    }

    ComD3D11Device1 device1;
    hr = d3d_device.As(&device1);
    RETURN_ON_HR_FAILURE(hr, "Failed to query ID3D11Device1", hr);

    hr = device1->OpenSharedResource1(buffer_handle.dxgi_handle.Get(),
                                      IID_PPV_ARGS(&input_texture));
    RETURN_ON_HR_FAILURE(hr, "Failed to open shared GMB D3D texture", hr);
  } else if (frame->HasSharedImage()) {
    ComMFMediaBuffer texture_buffer;
    hr = input_sample->GetBufferByIndex(0, &texture_buffer);
    RETURN_ON_HR_FAILURE(hr, "Failed to get sample's buffer", hr);
    Microsoft::WRL::ComPtr<IMFDXGIBuffer> dxgi_buffer;
    hr = texture_buffer.As(&dxgi_buffer);
    RETURN_ON_HR_FAILURE(hr, "Failed to get dxgi buffer", hr);
    hr = dxgi_buffer->GetResource(IID_PPV_ARGS(&input_texture));
  }

  if (frame->visible_rect().size() != input_visible_size_) {
    hr = PerformD3DScaling(input_texture.Get(), frame->visible_rect());
    RETURN_ON_HR_FAILURE(hr, "Failed to perform D3D video processing", hr);
    sample_texture = scaled_d3d11_texture_;
  } else {
    // Even though no scaling is needed we still need to copy the texture to
    // avoid concurrent usage causing glitches (https://crbug.com/1462315). This
    // is preferred over holding a keyed mutex for the duration of the encode
    // operation since that can take a significant amount of time and mutex
    // acquisitions (necessary even for read-only operations) are blocking.
      hr = PerformD3DCopy(input_texture.Get(), frame->visible_rect());
      RETURN_ON_HR_FAILURE(hr, "Failed to perform D3D texture copy", hr);
      sample_texture = copied_d3d11_texture_;
  }

  ComMFMediaBuffer input_buffer;
  hr = MFCreateDXGISurfaceBuffer(__uuidof(ID3D11Texture2D),
                                 sample_texture.Get(), 0, FALSE, &input_buffer);
  RETURN_ON_HR_FAILURE(hr, "Failed to create MF DXGI surface buffer", hr);

  // Some encoder MFTs (e.g. Qualcomm) depend on the sample buffer having a
  // valid current length. Call GetMaxLength() to compute the plane size.
  DWORD buffer_length = 0;
  hr = input_buffer->GetMaxLength(&buffer_length);
  RETURN_ON_HR_FAILURE(hr, "Failed to get max buffer length", hr);
  hr = input_buffer->SetCurrentLength(buffer_length);
  RETURN_ON_HR_FAILURE(hr, "Failed to set current buffer length", hr);

  hr = input_sample->RemoveAllBuffers();
  RETURN_ON_HR_FAILURE(hr, "Failed to remove buffers from sample", hr);
  hr = input_sample->AddBuffer(input_buffer.Get());
  RETURN_ON_HR_FAILURE(hr, "Failed to add buffer to sample", hr);
  return S_OK;
}

void MediaFoundationVideoEncodeAccelerator::ProcessOutput() {
  DVLOG(3) << __func__;
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  TRACE_EVENT0("media", "MediaFoundationVideoEncodeAccelerator::ProcessOutput");

  MFT_OUTPUT_DATA_BUFFER output_data_buffer = {0};
  output_data_buffer.dwStreamID = output_stream_id_;
  output_data_buffer.dwStatus = 0;
  output_data_buffer.pEvents = nullptr;
  output_data_buffer.pSample = nullptr;
  DWORD status = 0;
  HRESULT hr = encoder_->ProcessOutput(0, 1, &output_data_buffer, &status);
  // If there is an IMFCollection of events, release it
  if (output_data_buffer.pEvents != nullptr) {
    DVLOG(3) << "Got events from ProcessOutput, but discarding.";
    output_data_buffer.pEvents->Release();
  }
  if (hr == MF_E_TRANSFORM_STREAM_CHANGE) {
    hr = S_OK;
    ComMFMediaType media_type;
    for (DWORD type_index = 0; SUCCEEDED(hr); ++type_index) {
      hr = encoder_->GetOutputAvailableType(output_stream_id_, type_index,
                                            &media_type);
      if (SUCCEEDED(hr)) {
        break;
      }
    }
    hr = encoder_->SetOutputType(output_stream_id_, media_type.Get(), 0);
    return;
  }

  RETURN_ON_HR_FAILURE(hr, "Couldn't get encoded data", );
  DVLOG(3) << "Got encoded data " << PrintHr(hr);

  ComMFSample output_sample;
  ComMFMediaBuffer output_buffer;
  output_sample.Attach(output_data_buffer.pSample);
  hr = output_data_buffer.pSample->GetBufferByIndex(0, &output_buffer);
  RETURN_ON_HR_FAILURE(hr, "Couldn't get buffer by index", );

  base::TimeDelta timestamp;
  LONGLONG sample_time;
  hr = output_data_buffer.pSample->GetSampleTime(&sample_time);
  if (SUCCEEDED(hr)) {
    timestamp =
        base::Microseconds(sample_time / kOneMicrosecondInMFSampleTimeUnits);
  }

  DCHECK(!sample_metadata_queue_.empty());
  const auto metadata = sample_metadata_queue_.front();
  sample_metadata_queue_.pop_front();
  if (metadata.discard_output) {
    return;
  }

  // If `frame_qp` is set here, it will be plumbed down to WebRTC.
  // If not set, the QP may be parsed by WebRTC from the bitstream but only if
  // the QP is trusted (`encoder_info_.reports_average_qp` is true, which it is
  // by default).
  std::optional<int32_t> frame_qp;
  bool should_notify_reports_average_qp_change = false;
  // If there exists a valid qp in sample metadata, do not query HMFT for
  // MFSampleExtension_VideoEncodeQP.
  if (metadata.qp.has_value()) {
    frame_qp = metadata.qp.value();
  } else {
    // For HMFT that continuously reports valid QP, update encoder info so that
    // WebRTC will not use bandwidth quality scaler for resolution adaptation.
    uint64_t frame_qp_from_sample = 0xfffful;
    hr = output_data_buffer.pSample->GetUINT64(MFSampleExtension_VideoEncodeQP,
                                               &frame_qp_from_sample);
    if (vendor_ == DriverVendor::kIntel) {
      if ((FAILED(hr) || !IsValidQp(codec_, frame_qp_from_sample)) &&
          encoder_info_.reports_average_qp) {
        should_notify_reports_average_qp_change = true;
        encoder_info_.reports_average_qp = false;
      }
    }
    // Bits 0-15: Default QP.
    if (SUCCEEDED(hr)) {
      frame_qp = AVEncQPtoQindex(codec_, frame_qp_from_sample & 0xfffful);
    }
  }
  if (should_notify_reports_average_qp_change) {
    client_->NotifyEncoderInfoChange(encoder_info_);
  }

  const bool keyframe = MFGetAttributeUINT32(
      output_data_buffer.pSample, MFSampleExtension_CleanPoint, false);
  DWORD size = 0;
  hr = output_buffer->GetCurrentLength(&size);
  RETURN_ON_HR_FAILURE(hr, "Couldn't get buffer length", );
  DCHECK_NE(size, 0u);

  BitstreamBufferMetadata md(size, keyframe, timestamp);
  if (frame_qp.has_value() && IsValidQp(codec_, *frame_qp)) {
    md.qp = *frame_qp;
  }
  if (metadata.color_space.IsValid()) {
    md.encoded_color_space = metadata.color_space;
  }

  int temporal_id = 0;
  if (IsTemporalScalabilityCoding()) {
    DCHECK(svc_parser_);
    TemporalScalabilityIdExtractor::BitstreamMetadata bits_md;
    MediaBufferScopedPointer scoped_buffer(output_buffer.Get());
    if (!svc_parser_->ParseChunk(base::span(scoped_buffer.get().get(), size),
                                 metadata.frame_id, bits_md)) {
      NotifyErrorStatus({EncoderStatus::Codes::kEncoderHardwareDriverError,
                         "Parse bitstream failed"});
      return;
    }
    temporal_id = bits_md.temporal_id;
    if (codec_ == VideoCodec::kH264) {
      md.h264.emplace().temporal_idx = temporal_id;
    } else if (codec_ == VideoCodec::kHEVC) {
      SVCGenericMetadata& svc = md.svc_generic.emplace();
      svc.temporal_idx = temporal_id;
      svc.spatial_idx = 0;
      // We only get the temporal id from NALU header of output bitstream
      // without extracting the reference structure, so we are not able to
      // provide the reference flags and refresh flags for HEVC, if the
      // |follow_svc_spec| flag is false, and RTC will not send dependency
      // descriptor RTP extension.
      svc.follow_svc_spec = encoder_produces_svc_spec_compliant_bitstream_;
    } else if (codec_ == VideoCodec::kAV1) {
      SVCGenericMetadata& svc = md.svc_generic.emplace();
      svc.temporal_idx = temporal_id;
      svc.spatial_idx = 0;
      svc.follow_svc_spec = encoder_produces_svc_spec_compliant_bitstream_;
      if (!svc.follow_svc_spec) {
        svc.reference_flags = bits_md.reference_idx_flags;
        svc.refresh_flags = bits_md.refresh_frame_flags;
      }
    } else if (codec_ == VideoCodec::kVP9) {
      Vp9Metadata& vp9 = md.vp9.emplace();
      if (keyframe) {
        // |spatial_layer_resolutions| has to be filled if keyframe is
        // requested.
        vp9.spatial_layer_resolutions.emplace_back(input_visible_size_);
        vp9.begin_active_spatial_layer_index = 0;
        vp9.end_active_spatial_layer_index =
            1 /*vp9.spatial_layer_resolutions.size()*/;
      } else {
        // For VP9 L1T2/L1T3 encoding on Intel drivers, a T1 frame may ref the
        // previous T1 frame which leads to not all T0 frame can be a sync point
        // to go up for higher temporal layers. We need to pick out the T0 frame
        // based on deterministic pattern and mark it as up-switch.
        // See https://crbug.com/1358750 for more details.
        if (vendor_ == DriverVendor::kIntel) {
          DCHECK(num_temporal_layers_ >= 2 && num_temporal_layers_ <= 3);
          uint32_t multiplier = num_temporal_layers_ == 3 ? 2 : 4;
          bool is_single_ref = zero_layer_counter_ % multiplier == 0;
          vp9.temporal_up_switch = true;
          if (temporal_id == 0) {
            zero_layer_counter_++;
            if (!is_single_ref) {
              // If |is_single_ref| is false, the subsequent T1 frame will ref
              // the previous T1 frame, so the current frame can not mark as
              // up-switch.
              vp9.temporal_up_switch = false;
            }
          } else if (is_single_ref) {
            // If |is_single_ref| is true, the T1/T2 layer only allowed to ref
            // the frames with lower temporal layer id, add check to guarantee
            // the ref dependency follow the deterministic pattern on Intel
            // drivers.
            for (const auto ref : bits_md.ref_frame_list) {
              if (ref.temporal_id >= temporal_id) {
                NotifyErrorStatus(
                    {EncoderStatus::Codes::kEncoderHardwareDriverError,
                     "VP9 referenced frames check failed "});
                return;
              }
            }
          }
        }
        // Fill the encoding metadata for VP9 non key frames.
        vp9.inter_pic_predicted = true;
        vp9.temporal_idx = temporal_id;
        for (const auto ref : bits_md.ref_frame_list) {
          vp9.p_diffs.push_back(metadata.frame_id - ref.frame_id);
        }
      }
    }
  }

  if (rate_ctrl_) {
    VideoRateControlWrapper::FrameParams frame_params{};
    frame_params.frame_type =
        keyframe ? VideoRateControlWrapper::FrameParams::FrameType::kKeyFrame
                 : VideoRateControlWrapper::FrameParams::FrameType::kInterFrame;
    frame_params.temporal_layer_id = temporal_id;
    frame_params.timestamp = timestamp.InMilliseconds();
    // Notify SW BRC about recent encoded frame size.
    rate_ctrl_->PostEncodeUpdate(size, frame_params);
  }
  DVLOG(3) << "Encoded data with size:" << size << " keyframe " << keyframe;
  // If no bit stream buffer presents, queue the output first.
  if (bitstream_buffer_queue_.empty()) {
    DVLOG(3) << "No bitstream buffers.";

    // We need to copy the output so that encoding can continue.
    auto encode_output = std::make_unique<EncodeOutput>(size, md);
    {
      MediaBufferScopedPointer scoped_buffer(output_buffer.Get());
      memcpy(encode_output->memory(), scoped_buffer.get(), size);
    }
    encoder_output_queue_.push_back(std::move(encode_output));
    return;
  }

  // If `bitstream_buffer_queue_` is not empty,
  // meaning we have output buffers to spare, `encoder_output_queue_` must
  // be empty, otherwise outputs should've already been returned using those
  // buffers.
  DCHECK(encoder_output_queue_.empty());

  // Immediately return encoded buffer with BitstreamBuffer to client.
  auto buffer_ref = std::move(bitstream_buffer_queue_.back());
  bitstream_buffer_queue_.pop_back();

  {
    MediaBufferScopedPointer scoped_buffer(output_buffer.Get());
    if (!buffer_ref->mapping.IsValid() || !scoped_buffer.get()) {
      DLOG(ERROR) << "Failed to copy bitstream media buffer.";
      return;
    }

    memcpy(buffer_ref->mapping.memory(), scoped_buffer.get(), size);
  }

  client_->BitstreamBufferReady(buffer_ref->id, md);
}

void MediaFoundationVideoEncodeAccelerator::MediaEventHandler(
    MediaEventType event_type,
    HRESULT status) {
  DVLOG(3) << __func__;
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  DCHECK(event_generator_);

  if (FAILED(status)) {
    NotifyErrorStatus({EncoderStatus::Codes::kSystemAPICallError,
                       "Media Foundation async error: " + PrintHr(status)});
    return;
  }

  switch (event_type) {
    case METransformNeedInput: {
      encoder_needs_input_counter_++;
      if (state_ == kInitializing || state_ == kInitializingWithCommandBuffer) {
        // HMFT is not ready for receiving inputs until the first
        // METransformNeedInput event is published.
        client_->RequireBitstreamBuffers(kNumInputBuffers, input_visible_size_,
                                         bitstream_buffer_size_);
        if (state_ == kInitializing) {
          SetState(kEncoding);
        } else {
          SetState(kWaitingForCommandBuffer);
        }
      } else if (state_ == kEncoding) {
        FeedInputs();
      } else if (state_ == kPreFlushing) {
        FeedInputs();
        if (pending_input_queue_.empty()) {
          // All pending inputs are sent to the MF encoder, it's time to tell it
          // to drain and produce all outputs.
          DrainEncoder();
        }
      }
      break;
    }
    case METransformHaveOutput: {
      ProcessOutput();
      break;
    }
    case METransformDrainComplete: {
      DCHECK(pending_input_queue_.empty());
      DCHECK(sample_metadata_queue_.empty());
      DCHECK_EQ(state_, kFlushing);
      // Reset the need input counter after drain complete.
      encoder_needs_input_counter_ = 0;
      auto hr = encoder_->ProcessMessage(MFT_MESSAGE_NOTIFY_START_OF_STREAM, 0);
      if (FAILED(hr)) {
        SetState(kError);
        std::move(flush_callback_).Run(false);
        return;
      }
      if (encoder_output_queue_.empty()) {
        // No pending outputs, let's signal that the Flush() is done and
        // continue encoding.
        SetState(kEncoding);
        std::move(flush_callback_).Run(true);
      } else {
        // There are pending outputs that are not returned yet,
        // let's wait for client to consume them, before signaling that
        // the Flush() has finished.
        SetState(kPostFlushing);
      }
      break;
    }
    case MEError: {
      NotifyErrorStatus({EncoderStatus::Codes::kEncoderHardwareDriverError,
                         "Media Foundation encountered a critical failure."});
      break;
    }
    default:
      break;
  }
  event_generator_->BeginGetEvent(this, nullptr);
}

void MediaFoundationVideoEncodeAccelerator::SetState(State state) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);

  DVLOG(3) << "Setting state to: " << state;
  state_ = state;
}

HRESULT MediaFoundationVideoEncodeAccelerator::InitializeD3DVideoProcessing(
    ID3D11Texture2D* input_texture) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  D3D11_TEXTURE2D_DESC input_desc = {};
  input_texture->GetDesc(&input_desc);
  if (vp_desc_.InputWidth == input_desc.Width &&
      vp_desc_.InputHeight == input_desc.Height &&
      scaled_d3d11_texture_desc_.Width ==
          static_cast<UINT>(input_visible_size_.width()) &&
      scaled_d3d11_texture_desc_.Height ==
          static_cast<UINT>(input_visible_size_.height())) {
    return S_OK;
  }

  // Input/output framerates are dummy values for passthrough.
  D3D11_VIDEO_PROCESSOR_CONTENT_DESC vp_desc = {
      .InputFrameFormat = D3D11_VIDEO_FRAME_FORMAT_PROGRESSIVE,
      .InputFrameRate = {60, 1},
      .InputWidth = input_desc.Width,
      .InputHeight = input_desc.Height,
      .OutputFrameRate = {60, 1},
      .OutputWidth = static_cast<UINT>(input_visible_size_.width()),
      .OutputHeight = static_cast<UINT>(input_visible_size_.height()),
      .Usage = D3D11_VIDEO_USAGE_PLAYBACK_NORMAL};

  ComD3D11Device texture_device;
  input_texture->GetDevice(&texture_device);
  ComD3D11VideoDevice video_device;
  HRESULT hr = texture_device.As(&video_device);
  RETURN_ON_HR_FAILURE(hr, "Failed to query for ID3D11VideoDevice", hr);

  ComD3D11VideoProcessorEnumerator video_processor_enumerator;
  hr = video_device->CreateVideoProcessorEnumerator(
      &vp_desc, &video_processor_enumerator);
  RETURN_ON_HR_FAILURE(hr, "CreateVideoProcessorEnumerator failed", hr);

  ComD3D11VideoProcessor video_processor;
  hr = video_device->CreateVideoProcessor(video_processor_enumerator.Get(), 0,
                                          &video_processor);
  RETURN_ON_HR_FAILURE(hr, "CreateVideoProcessor failed", hr);

  ComD3D11DeviceContext device_context;
  texture_device->GetImmediateContext(&device_context);
  ComD3D11VideoContext video_context;
  hr = device_context.As(&video_context);
  RETURN_ON_HR_FAILURE(hr, "Failed to query for ID3D11VideoContext", hr);

  // Auto stream processing (the default) can hurt power consumption.
  video_context->VideoProcessorSetStreamAutoProcessingMode(
      video_processor.Get(), 0, FALSE);

  D3D11_TEXTURE2D_DESC scaled_desc = {
      .Width = static_cast<UINT>(input_visible_size_.width()),
      .Height = static_cast<UINT>(input_visible_size_.height()),
      .MipLevels = 1,
      .ArraySize = 1,
      .Format = DXGI_FORMAT_NV12,
      .SampleDesc = {1, 0},
      .Usage = D3D11_USAGE_DEFAULT,
      .BindFlags = D3D11_BIND_SHADER_RESOURCE | D3D11_BIND_RENDER_TARGET,
      .CPUAccessFlags = 0,
      .MiscFlags = 0};
  ComD3D11Texture2D scaled_d3d11_texture;
  hr = texture_device->CreateTexture2D(&scaled_desc, nullptr,
                                       &scaled_d3d11_texture);
  RETURN_ON_HR_FAILURE(hr, "Failed to create texture", hr);

  hr = SetDebugName(scaled_d3d11_texture.Get(),
                    "MFVideoEncodeAccelerator_ScaledTexture");
  RETURN_ON_HR_FAILURE(hr, "Failed to set debug name", hr);

  D3D11_VIDEO_PROCESSOR_OUTPUT_VIEW_DESC output_desc = {};
  output_desc.ViewDimension = D3D11_VPOV_DIMENSION_TEXTURE2D;
  output_desc.Texture2D.MipSlice = 0;
  ComD3D11VideoProcessorOutputView vp_output_view;
  hr = video_device->CreateVideoProcessorOutputView(
      scaled_d3d11_texture.Get(), video_processor_enumerator.Get(),
      &output_desc, &vp_output_view);
  RETURN_ON_HR_FAILURE(hr, "CreateVideoProcessorOutputView failed", hr);

  video_device_ = std::move(video_device);
  video_processor_enumerator_ = std::move(video_processor_enumerator);
  video_processor_ = std::move(video_processor);
  video_context_ = std::move(video_context);
  vp_desc_ = std::move(vp_desc);
  scaled_d3d11_texture_ = std::move(scaled_d3d11_texture);
  scaled_d3d11_texture_->GetDesc(&scaled_d3d11_texture_desc_);
  vp_output_view_ = std::move(vp_output_view);
  return S_OK;
}

HRESULT MediaFoundationVideoEncodeAccelerator::PerformD3DScaling(
    ID3D11Texture2D* input_texture,
    const gfx::Rect& visible_rect) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  HRESULT hr = InitializeD3DVideoProcessing(input_texture);
  RETURN_ON_HR_FAILURE(hr, "Couldn't initialize D3D video processing", hr);

  // Set the color space for passthrough.
  auto src_color_space = gfx::ColorSpace::CreateSRGB();
  auto output_color_space = gfx::ColorSpace::CreateSRGB();

  D3D11_VIDEO_PROCESSOR_COLOR_SPACE src_d3d11_color_space =
      gfx::ColorSpaceWin::GetD3D11ColorSpace(src_color_space);
  video_context_->VideoProcessorSetStreamColorSpace(video_processor_.Get(), 0,
                                                    &src_d3d11_color_space);
  D3D11_VIDEO_PROCESSOR_COLOR_SPACE output_d3d11_color_space =
      gfx::ColorSpaceWin::GetD3D11ColorSpace(output_color_space);
  video_context_->VideoProcessorSetOutputColorSpace(video_processor_.Get(),
                                                    &output_d3d11_color_space);

  {
    std::optional<gpu::DXGIScopedReleaseKeyedMutex> release_keyed_mutex;
    ComDXGIKeyedMutex keyed_mutex;
    hr = input_texture->QueryInterface(IID_PPV_ARGS(&keyed_mutex));
    if (SUCCEEDED(hr)) {
      // The producer may still be using this texture for a short period of
      // time, so wait long enough to hopefully avoid glitches. For example,
      // all levels of the texture share the same keyed mutex, so if the
      // hardware decoder acquired the mutex to decode into a different array
      // level then it still may block here temporarily.
      constexpr int kMaxSyncTimeMs = 100;
      hr = keyed_mutex->AcquireSync(0, kMaxSyncTimeMs);
      // Can't check for FAILED(hr) because AcquireSync may return e.g.
      // WAIT_ABANDONED.
      if (hr != S_OK && hr != WAIT_TIMEOUT) {
        LOG(ERROR) << "Failed to acquire mutex: " << PrintHr(hr);
        return E_FAIL;
      }
      release_keyed_mutex.emplace(std::move(keyed_mutex), 0);
    }

    // Setup |video_context_| for VPBlt operation.
    D3D11_VIDEO_PROCESSOR_INPUT_VIEW_DESC input_desc = {};
    input_desc.ViewDimension = D3D11_VPIV_DIMENSION_TEXTURE2D;
    input_desc.Texture2D.ArraySlice = 0;
    ComD3D11VideoProcessorInputView input_view;
    hr = video_device_->CreateVideoProcessorInputView(
        input_texture, video_processor_enumerator_.Get(), &input_desc,
        &input_view);
    RETURN_ON_HR_FAILURE(hr, "CreateVideoProcessorInputView failed", hr);

    D3D11_VIDEO_PROCESSOR_STREAM stream = {.Enable = true,
                                           .OutputIndex = 0,
                                           .InputFrameOrField = 0,
                                           .PastFrames = 0,
                                           .FutureFrames = 0,
                                           .pInputSurface = input_view.Get()};

    D3D11_TEXTURE2D_DESC input_texture_desc = {};
    input_texture->GetDesc(&input_texture_desc);
    RECT source_rect = {static_cast<LONG>(visible_rect.x()),
                        static_cast<LONG>(visible_rect.y()),
                        static_cast<LONG>(visible_rect.right()),
                        static_cast<LONG>(visible_rect.bottom())};
    video_context_->VideoProcessorSetStreamSourceRect(video_processor_.Get(), 0,
                                                      TRUE, &source_rect);

    D3D11_TEXTURE2D_DESC output_texture_desc = {};
    scaled_d3d11_texture_->GetDesc(&output_texture_desc);
    RECT dest_rect = {0, 0, static_cast<LONG>(output_texture_desc.Width),
                      static_cast<LONG>(output_texture_desc.Height)};
    video_context_->VideoProcessorSetOutputTargetRect(video_processor_.Get(),
                                                      TRUE, &dest_rect);
    video_context_->VideoProcessorSetStreamDestRect(video_processor_.Get(), 0,
                                                    TRUE, &dest_rect);

    hr = video_context_->VideoProcessorBlt(
        video_processor_.Get(), vp_output_view_.Get(), 0, 1, &stream);
    RETURN_ON_HR_FAILURE(hr, "VideoProcessorBlt failed", hr);
  }

  return hr;
}

HRESULT MediaFoundationVideoEncodeAccelerator::InitializeD3DCopying(
    ID3D11Texture2D* input_texture) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  D3D11_TEXTURE2D_DESC input_desc = {};
  input_texture->GetDesc(&input_desc);
  // Return early if `copied_d3d11_texture_` is already the correct size,
  // avoiding the overhead of creating a new destination texture.
  if (copied_d3d11_texture_) {
    D3D11_TEXTURE2D_DESC copy_desc = {};
    copied_d3d11_texture_->GetDesc(©_desc);
    if (input_desc.Width == copy_desc.Width &&
        input_desc.Height == copy_desc.Height) {
      return S_OK;
    }
  }
  ComD3D11Device texture_device;
  input_texture->GetDevice(&texture_device);
  D3D11_TEXTURE2D_DESC copy_desc = {
      .Width = input_desc.Width,
      .Height = input_desc.Height,
      .MipLevels = 1,
      .ArraySize = 1,
      .Format = DXGI_FORMAT_NV12,
      .SampleDesc = {1, 0},
      .Usage = D3D11_USAGE_DEFAULT,
      .BindFlags = D3D11_BIND_SHADER_RESOURCE | D3D11_BIND_RENDER_TARGET,
      .CPUAccessFlags = 0,
      .MiscFlags = 0};
  ComD3D11Texture2D copied_d3d11_texture;
  HRESULT hr = texture_device->CreateTexture2D(©_desc, nullptr,
                                               &copied_d3d11_texture);
  RETURN_ON_HR_FAILURE(hr, "Failed to create texture", hr);
  hr = SetDebugName(copied_d3d11_texture.Get(),
                    "MFVideoEncodeAccelerator_CopiedTexture");
  RETURN_ON_HR_FAILURE(hr, "Failed to set debug name", hr);
  copied_d3d11_texture_ = std::move(copied_d3d11_texture);
  return S_OK;
}

HRESULT MediaFoundationVideoEncodeAccelerator::PerformD3DCopy(
    ID3D11Texture2D* input_texture,
    const gfx::Rect& visible_rect) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  HRESULT hr = InitializeD3DCopying(input_texture);
  RETURN_ON_HR_FAILURE(hr, "Couldn't initialize D3D copying", hr);

  ComD3D11Device d3d_device = dxgi_device_manager_->GetDevice();
  if (!d3d_device) {
    LOG(ERROR) << "Failed to get device from MF DXGI device manager";
    return E_HANDLE;
  }
  ComD3D11DeviceContext device_context;
  d3d_device->GetImmediateContext(&device_context);

  {
    // We need to hold a keyed mutex during the copy operation.
    std::optional<gpu::DXGIScopedReleaseKeyedMutex> release_keyed_mutex;
    ComDXGIKeyedMutex keyed_mutex;
    hr = input_texture->QueryInterface(IID_PPV_ARGS(&keyed_mutex));
    if (SUCCEEDED(hr)) {
      constexpr int kMaxSyncTimeMs = 100;
      hr = keyed_mutex->AcquireSync(0, kMaxSyncTimeMs);
      // Can't check for FAILED(hr) because AcquireSync may return e.g.
      // WAIT_ABANDONED.
      if (hr != S_OK && hr != WAIT_TIMEOUT) {
        LOG(ERROR) << "Failed to acquire mutex: " << PrintHr(hr);
        return E_FAIL;
      }
      release_keyed_mutex.emplace(std::move(keyed_mutex), 0);
    }

    D3D11_BOX src_box = {static_cast<UINT>(visible_rect.x()),
                         static_cast<UINT>(visible_rect.y()),
                         0,
                         static_cast<UINT>(visible_rect.right()),
                         static_cast<UINT>(visible_rect.bottom()),
                         1};
    device_context->CopySubresourceRegion(copied_d3d11_texture_.Get(), 0, 0, 0,
                                          0, input_texture, 0, &src_box);
  }
  return S_OK;
}

void MediaFoundationVideoEncodeAccelerator::OnCommandBufferHelperAvailable(
    const GetCommandBufferHelperResult& result) {
  command_buffer_helper_ = result.command_buffer_helper;
  if (!InitializeMFT(result.shared_d3d_device.Get())) {
    // InitializeMFT will call NotifyErrorStatus if an error occurs
    return;
  }

  if (state_ == kAcquiringCommandBuffer) {
    // CommandBufferHelper acquired before Initialize is called, go to
    // uninitialized state so full initialization can be done
    // in Initialize.
    SetState(kUninitialized);
  } else if (state_ == kWaitingForCommandBuffer) {
    SetState(kEncoding);
    FeedInputs();
  } else if (state_ == kInitializingWithCommandBuffer) {
    SetState(kInitializing);
  }
}

void MediaFoundationVideoEncodeAccelerator::OnSharedImageSampleAvailable(
    scoped_refptr<VideoFrame> frame,
    ComMFSample sample,
    HRESULT hrResult) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  if (FAILED(hrResult)) {
    LOG(ERROR) << "Failed to obtain shared image for encoding: "
               << PrintHr(hrResult);
    NotifyErrorStatus({EncoderStatus::Codes::kSystemAPICallError,
                       "Failed to obtain shared image for encoding"});
    return;
  }

  DCHECK(!pending_input_queue_.empty());
  auto& next_input = pending_input_queue_.front();
  next_input.input_sample = sample;
  next_input.resolving_shared_image = false;

  HRESULT hr = PopulateInputSampleBuffer(next_input, std::move(frame));
  if (FAILED(hr)) {
    NotifyErrorStatus({EncoderStatus::Codes::kEncoderFailedEncode,
                       "Failed to populate input sample buffer"});
    return;
  }

  if (encoder_needs_input_counter_ > 0) {
    FeedInputs();
  }
}

HRESULT MediaFoundationVideoEncodeAccelerator::GetParameters(DWORD* pdwFlags,
                                                             DWORD* pdwQueue) {
  *pdwFlags = MFASYNC_FAST_IO_PROCESSING_CALLBACK;
  *pdwQueue = MFASYNC_CALLBACK_QUEUE_TIMER;
  return S_OK;
}

HRESULT MediaFoundationVideoEncodeAccelerator::Invoke(
    IMFAsyncResult* pAsyncResult) {
  ComMFMediaEvent media_event;
  RETURN_IF_FAILED(event_generator_->EndGetEvent(pAsyncResult, &media_event));

  MediaEventType event_type = MEUnknown;
  RETURN_IF_FAILED(media_event->GetType(&event_type));

  HRESULT status = S_OK;
  media_event->GetStatus(&status);

  // Invoke() is called on some random OS thread, so we must post to our event
  // handler since MediaFoundationVideoEncodeAccelerator is single threaded.
  task_runner_->PostTask(
      FROM_HERE,
      base::BindOnce(&MediaFoundationVideoEncodeAccelerator::MediaEventHandler,
                     weak_ptr_, event_type, status));
  return status;
}

ULONG MediaFoundationVideoEncodeAccelerator::AddRef() {
  return async_callback_ref_.Increment();
}

ULONG MediaFoundationVideoEncodeAccelerator::Release() {
  DCHECK(!async_callback_ref_.IsOne());
  return async_callback_ref_.Decrement() ? 1 : 0;
}

HRESULT MediaFoundationVideoEncodeAccelerator::QueryInterface(REFIID riid,
                                                              void** ppv) {
  static const QITAB kQI[] = {
      QITABENT(MediaFoundationVideoEncodeAccelerator, IMFAsyncCallback), {0}};
  return QISearch(this, kQI, riid, ppv);
}

}  // namespace media