1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193
|
/*
* Copyright (C) 2014 Alex Christensen <achristensen@webkit.org>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "MediaPlayerPrivateMediaFoundation.h"
#include "CachedResourceLoader.h"
#include "FrameView.h"
#include "GraphicsContext.h"
#include "HWndDC.h"
#include "HostWindow.h"
#include "NotImplemented.h"
#if USE(CAIRO)
#include "PlatformContextCairo.h"
#endif
#include "SoftLinking.h"
#if PLATFORM(QT)
#include "QWebPageClient.h"
#include <QWindow>
#endif
#if USE(MEDIA_FOUNDATION)
#include <wtf/MainThread.h>
#include <wtf/NeverDestroyed.h>
#include <wtf/text/win/WCharStringExtras.h>
SOFT_LINK_LIBRARY(Mf);
SOFT_LINK_OPTIONAL(Mf, MFCreateSourceResolver, HRESULT, STDAPICALLTYPE, (IMFSourceResolver**));
SOFT_LINK_OPTIONAL(Mf, MFCreateMediaSession, HRESULT, STDAPICALLTYPE, (IMFAttributes*, IMFMediaSession**));
SOFT_LINK_OPTIONAL(Mf, MFCreateTopology, HRESULT, STDAPICALLTYPE, (IMFTopology**));
SOFT_LINK_OPTIONAL(Mf, MFCreateTopologyNode, HRESULT, STDAPICALLTYPE, (MF_TOPOLOGY_TYPE, IMFTopologyNode**));
SOFT_LINK_OPTIONAL(Mf, MFGetService, HRESULT, STDAPICALLTYPE, (IUnknown*, REFGUID, REFIID, LPVOID*));
SOFT_LINK_OPTIONAL(Mf, MFCreateAudioRendererActivate, HRESULT, STDAPICALLTYPE, (IMFActivate**));
SOFT_LINK_OPTIONAL(Mf, MFCreateVideoRendererActivate, HRESULT, STDAPICALLTYPE, (HWND, IMFActivate**));
SOFT_LINK_OPTIONAL(Mf, MFCreateSampleGrabberSinkActivate, HRESULT, STDAPICALLTYPE, (IMFMediaType*, IMFSampleGrabberSinkCallback*, IMFActivate**));
SOFT_LINK_OPTIONAL(Mf, MFGetSupportedMimeTypes, HRESULT, STDAPICALLTYPE, (PROPVARIANT*));
SOFT_LINK_LIBRARY(Mfplat);
SOFT_LINK_OPTIONAL(Mfplat, MFStartup, HRESULT, STDAPICALLTYPE, (ULONG, DWORD));
SOFT_LINK_OPTIONAL(Mfplat, MFShutdown, HRESULT, STDAPICALLTYPE, ());
SOFT_LINK_OPTIONAL(Mfplat, MFCreateMemoryBuffer, HRESULT, STDAPICALLTYPE, (DWORD, IMFMediaBuffer**));
SOFT_LINK_OPTIONAL(Mfplat, MFCreateSample, HRESULT, STDAPICALLTYPE, (IMFSample**));
SOFT_LINK_OPTIONAL(Mfplat, MFCreateMediaType, HRESULT, STDAPICALLTYPE, (IMFMediaType**));
SOFT_LINK_OPTIONAL(Mfplat, MFFrameRateToAverageTimePerFrame, HRESULT, STDAPICALLTYPE, (UINT32, UINT32, UINT64*));
SOFT_LINK_LIBRARY(evr);
SOFT_LINK_OPTIONAL(evr, MFCreateVideoSampleFromSurface, HRESULT, STDAPICALLTYPE, (IUnknown*, IMFSample**));
SOFT_LINK_LIBRARY(Dxva2);
SOFT_LINK_OPTIONAL(Dxva2, DXVA2CreateDirect3DDeviceManager9, HRESULT, STDAPICALLTYPE, (UINT*, IDirect3DDeviceManager9**));
SOFT_LINK_LIBRARY(D3d9);
SOFT_LINK_OPTIONAL(D3d9, Direct3DCreate9Ex, HRESULT, STDAPICALLTYPE, (UINT, IDirect3D9Ex**));
// MFSamplePresenterSampleCounter
// Data type: UINT32
//
// Version number for the video samples. When the presenter increments the version
// number, all samples with the previous version number are stale and should be
// discarded.
static const GUID MFSamplePresenterSampleCounter =
{ 0x869f1f7c, 0x3496, 0x48a9, { 0x88, 0xe3, 0x69, 0x85, 0x79, 0xd0, 0x8c, 0xb6 } };
static const double tenMegahertz = 10000000;
namespace WebCore {
MediaPlayerPrivateMediaFoundation::MediaPlayerPrivateMediaFoundation(MediaPlayer* player)
: m_player(player)
, m_visible(false)
, m_loadingProgress(false)
, m_paused(true)
, m_hasAudio(false)
, m_hasVideo(false)
, m_preparingToPlay(false)
, m_hwndVideo(nullptr)
, m_volume(1.0)
, m_networkState(MediaPlayer::Empty)
, m_readyState(MediaPlayer::HaveNothing)
, m_weakPtrFactory(this)
{
createSession();
createVideoWindow();
}
MediaPlayerPrivateMediaFoundation::~MediaPlayerPrivateMediaFoundation()
{
notifyDeleted();
destroyVideoWindow();
endSession();
}
void MediaPlayerPrivateMediaFoundation::registerMediaEngine(MediaEngineRegistrar registrar)
{
if (isAvailable()) {
registrar([](MediaPlayer* player) { return std::make_unique<MediaPlayerPrivateMediaFoundation>(player); },
getSupportedTypes, supportsType, 0, 0, 0, 0);
}
}
bool MediaPlayerPrivateMediaFoundation::isAvailable()
{
notImplemented();
return true;
}
static const HashSet<String, ASCIICaseInsensitiveHash>& mimeTypeCache()
{
static NeverDestroyed<HashSet<String, ASCIICaseInsensitiveHash>> cachedTypes;
if (cachedTypes.get().size() > 0)
return cachedTypes;
cachedTypes.get().add(String("video/mp4"));
if (!MFGetSupportedMimeTypesPtr())
return cachedTypes;
PROPVARIANT propVarMimeTypeArray;
PropVariantInit(&propVarMimeTypeArray);
HRESULT hr = MFGetSupportedMimeTypesPtr()(&propVarMimeTypeArray);
if (SUCCEEDED(hr)) {
CALPWSTR mimeTypeArray = propVarMimeTypeArray.calpwstr;
for (unsigned i = 0; i < mimeTypeArray.cElems; i++)
cachedTypes.get().add(nullTerminatedWCharToString(mimeTypeArray.pElems[i]));
}
PropVariantClear(&propVarMimeTypeArray);
return cachedTypes;
}
void MediaPlayerPrivateMediaFoundation::getSupportedTypes(HashSet<String, ASCIICaseInsensitiveHash>& types)
{
types = mimeTypeCache();
}
MediaPlayer::SupportsType MediaPlayerPrivateMediaFoundation::supportsType(const MediaEngineSupportParameters& parameters)
{
if (parameters.type.isNull() || parameters.type.isEmpty())
return MediaPlayer::IsNotSupported;
if (mimeTypeCache().contains(parameters.type))
return MediaPlayer::IsSupported;
return MediaPlayer::IsNotSupported;
}
void MediaPlayerPrivateMediaFoundation::load(const String& url)
{
{
LockHolder locker(m_cachedNaturalSizeLock);
m_cachedNaturalSize = FloatSize();
}
startCreateMediaSource(url);
m_networkState = MediaPlayer::Loading;
m_player->networkStateChanged();
m_readyState = MediaPlayer::HaveNothing;
m_player->readyStateChanged();
}
void MediaPlayerPrivateMediaFoundation::cancelLoad()
{
notImplemented();
}
void MediaPlayerPrivateMediaFoundation::play()
{
m_paused = !startSession();
m_preparingToPlay = false;
}
void MediaPlayerPrivateMediaFoundation::pause()
{
if (!m_mediaSession)
return;
m_paused = SUCCEEDED(m_mediaSession->Pause());
}
bool MediaPlayerPrivateMediaFoundation::supportsFullscreen() const
{
return true;
}
FloatSize MediaPlayerPrivateMediaFoundation::naturalSize() const
{
LockHolder locker(m_cachedNaturalSizeLock);
return m_cachedNaturalSize;
}
bool MediaPlayerPrivateMediaFoundation::hasVideo() const
{
return m_hasVideo;
}
bool MediaPlayerPrivateMediaFoundation::hasAudio() const
{
return m_hasAudio;
}
void MediaPlayerPrivateMediaFoundation::setVisible(bool visible)
{
m_visible = visible;
}
bool MediaPlayerPrivateMediaFoundation::seeking() const
{
// We assume seeking is immediately complete.
return false;
}
void MediaPlayerPrivateMediaFoundation::seek(float time)
{
PROPVARIANT propVariant;
PropVariantInit(&propVariant);
propVariant.vt = VT_I8;
propVariant.hVal.QuadPart = static_cast<__int64>(time * tenMegahertz);
HRESULT hr = m_mediaSession->Start(&GUID_NULL, &propVariant);
ASSERT(SUCCEEDED(hr));
PropVariantClear(&propVariant);
m_player->timeChanged();
}
void MediaPlayerPrivateMediaFoundation::setRate(float rate)
{
COMPtr<IMFRateControl> rateControl;
HRESULT hr = MFGetServicePtr()(m_mediaSession.get(), MF_RATE_CONTROL_SERVICE, IID_IMFRateControl, (void**)&rateControl);
if (!SUCCEEDED(hr))
return;
BOOL reduceSamplesInStream = rate > 2.0;
rateControl->SetRate(reduceSamplesInStream, rate);
}
float MediaPlayerPrivateMediaFoundation::duration() const
{
if (!m_mediaSource)
return 0;
IMFPresentationDescriptor* descriptor;
if (!SUCCEEDED(m_mediaSource->CreatePresentationDescriptor(&descriptor)))
return 0;
UINT64 duration;
if (!SUCCEEDED(descriptor->GetUINT64(MF_PD_DURATION, &duration)))
duration = 0;
descriptor->Release();
return static_cast<float>(duration) / tenMegahertz;
}
float MediaPlayerPrivateMediaFoundation::currentTime() const
{
if (!m_presenter)
return 0.0f;
return m_presenter->currentTime();
}
bool MediaPlayerPrivateMediaFoundation::paused() const
{
return m_paused;
}
bool MediaPlayerPrivateMediaFoundation::setAllChannelVolumes(float volume)
{
if (!MFGetServicePtr())
return false;
COMPtr<IMFAudioStreamVolume> audioVolume;
if (!SUCCEEDED(MFGetServicePtr()(m_mediaSession.get(), MR_STREAM_VOLUME_SERVICE, __uuidof(IMFAudioStreamVolume), (void **)&audioVolume)))
return false;
UINT32 channelsCount;
HRESULT hr = audioVolume->GetChannelCount(&channelsCount);
ASSERT(SUCCEEDED(hr));
Vector<float> volumes(channelsCount, volume);
return SUCCEEDED(audioVolume->SetAllVolumes(channelsCount, volumes.data()));
}
void MediaPlayerPrivateMediaFoundation::setVolume(float volume)
{
if (setAllChannelVolumes(volume))
m_volume = volume;
}
bool MediaPlayerPrivateMediaFoundation::supportsMuting() const
{
return true;
}
void MediaPlayerPrivateMediaFoundation::setMuted(bool muted)
{
setAllChannelVolumes(muted ? 0.0 : m_volume);
}
MediaPlayer::NetworkState MediaPlayerPrivateMediaFoundation::networkState() const
{
return m_networkState;
}
MediaPlayer::ReadyState MediaPlayerPrivateMediaFoundation::readyState() const
{
return m_readyState;
}
float MediaPlayerPrivateMediaFoundation::maxTimeSeekable() const
{
return durationDouble();
}
std::unique_ptr<PlatformTimeRanges> MediaPlayerPrivateMediaFoundation::buffered() const
{
auto ranges = std::make_unique<PlatformTimeRanges>();
if (m_presenter && m_presenter->maxTimeLoaded() > 0)
ranges->add(MediaTime::zeroTime(), MediaTime::createWithDouble(m_presenter->maxTimeLoaded()));
return ranges;
}
bool MediaPlayerPrivateMediaFoundation::didLoadingProgress() const
{
return m_loadingProgress;
}
void MediaPlayerPrivateMediaFoundation::setSize(const IntSize& size)
{
m_size = size;
auto videoDisplay = this->videoDisplay();
if (!videoDisplay)
return;
IntPoint positionInWindow(m_lastPaintRect.location());
FrameView* view = nullptr;
float deviceScaleFactor = 1.0f;
if (m_player && m_player->cachedResourceLoader() && m_player->cachedResourceLoader()->document()) {
view = m_player->cachedResourceLoader()->document()->view();
deviceScaleFactor = m_player->cachedResourceLoader()->document()->deviceScaleFactor();
}
LayoutPoint scrollPosition;
if (view) {
scrollPosition = view->scrollPositionForFixedPosition();
positionInWindow = view->convertToContainingWindow(IntPoint(m_lastPaintRect.location()));
}
positionInWindow.move(-scrollPosition.x().toInt(), -scrollPosition.y().toInt());
int x = positionInWindow.x() * deviceScaleFactor;
int y = positionInWindow.y() * deviceScaleFactor;
int w = m_size.width() * deviceScaleFactor;
int h = m_size.height() * deviceScaleFactor;
if (m_hwndVideo)
::MoveWindow(m_hwndVideo, x, y, w, h, FALSE);
RECT rc = { 0, 0, w, h };
videoDisplay->SetVideoPosition(nullptr, &rc);
}
void MediaPlayerPrivateMediaFoundation::paint(GraphicsContext& context, const FloatRect& rect)
{
if (context.paintingDisabled() || !m_player->visible())
return;
m_lastPaintRect = rect;
if (m_presenter)
m_presenter->paintCurrentFrame(context, rect);
}
bool MediaPlayerPrivateMediaFoundation::createSession()
{
if (!MFStartupPtr() || !MFCreateMediaSessionPtr())
return false;
if (FAILED(MFStartupPtr()(MF_VERSION, MFSTARTUP_FULL)))
return false;
if (FAILED(MFCreateMediaSessionPtr()(nullptr, &m_mediaSession)))
return false;
// Get next event.
AsyncCallback* callback = new AsyncCallback(this, true);
HRESULT hr = m_mediaSession->BeginGetEvent(callback, nullptr);
ASSERT(SUCCEEDED(hr));
return true;
}
bool MediaPlayerPrivateMediaFoundation::startSession()
{
if (!m_mediaSession)
return false;
PROPVARIANT varStart;
PropVariantInit(&varStart);
varStart.vt = VT_EMPTY;
HRESULT hr = m_mediaSession->Start(nullptr, &varStart);
ASSERT(SUCCEEDED(hr));
PropVariantClear(&varStart);
return SUCCEEDED(hr);
}
bool MediaPlayerPrivateMediaFoundation::endSession()
{
if (m_mediaSession) {
m_mediaSession->Shutdown();
m_mediaSession = nullptr;
}
if (!MFShutdownPtr())
return false;
HRESULT hr = MFShutdownPtr()();
ASSERT(SUCCEEDED(hr));
return true;
}
bool MediaPlayerPrivateMediaFoundation::startCreateMediaSource(const String& url)
{
if (!MFCreateSourceResolverPtr())
return false;
if (FAILED(MFCreateSourceResolverPtr()(&m_sourceResolver)))
return false;
COMPtr<IUnknown> cancelCookie;
Vector<wchar_t> urlSource = stringToNullTerminatedWChar(url);
AsyncCallback* callback = new AsyncCallback(this, false);
if (FAILED(m_sourceResolver->BeginCreateObjectFromURL(urlSource.data(), MF_RESOLUTION_MEDIASOURCE, nullptr, &cancelCookie, callback, nullptr)))
return false;
return true;
}
bool MediaPlayerPrivateMediaFoundation::endCreatedMediaSource(IMFAsyncResult* asyncResult)
{
MF_OBJECT_TYPE objectType;
COMPtr<IUnknown> source;
HRESULT hr = m_sourceResolver->EndCreateObjectFromURL(asyncResult, &objectType, &source);
if (FAILED(hr))
return false;
hr = source->QueryInterface(IID_PPV_ARGS(&m_mediaSource));
if (FAILED(hr))
return false;
hr = asyncResult->GetStatus();
m_loadingProgress = SUCCEEDED(hr);
auto weakPtr = m_weakPtrFactory.createWeakPtr();
callOnMainThread([weakPtr] {
if (!weakPtr)
return;
weakPtr->onCreatedMediaSource();
});
return true;
}
bool MediaPlayerPrivateMediaFoundation::endGetEvent(IMFAsyncResult* asyncResult)
{
COMPtr<IMFMediaEvent> event;
if (!m_mediaSession)
return false;
// Get the event from the event queue.
HRESULT hr = m_mediaSession->EndGetEvent(asyncResult, &event);
if (FAILED(hr))
return false;
// Get the event type.
MediaEventType mediaEventType;
hr = event->GetType(&mediaEventType);
if (FAILED(hr))
return false;
switch (mediaEventType) {
case MESessionTopologySet: {
auto weakPtr = m_weakPtrFactory.createWeakPtr();
callOnMainThread([weakPtr] {
if (!weakPtr)
return;
weakPtr->onTopologySet();
});
break;
}
case MESessionStarted: {
auto weakPtr = m_weakPtrFactory.createWeakPtr();
callOnMainThread([weakPtr] {
if (!weakPtr)
return;
weakPtr->onSessionStarted();
});
break;
}
case MEBufferingStarted: {
auto weakPtr = m_weakPtrFactory.createWeakPtr();
callOnMainThread([weakPtr] {
if (!weakPtr)
return;
weakPtr->onBufferingStarted();
});
break;
}
case MEBufferingStopped: {
auto weakPtr = m_weakPtrFactory.createWeakPtr();
callOnMainThread([weakPtr] {
if (!weakPtr)
return;
weakPtr->onBufferingStopped();
});
break;
}
case MESessionEnded: {
auto weakPtr = m_weakPtrFactory.createWeakPtr();
callOnMainThread([weakPtr] {
if (!weakPtr)
return;
weakPtr->onSessionEnded();
});
break;
}
case MEMediaSample:
break;
case MEError: {
HRESULT status = S_OK;
event->GetStatus(&status);
break;
}
}
if (mediaEventType != MESessionClosed) {
// For all other events, ask the media session for the
// next event in the queue.
AsyncCallback* callback = new AsyncCallback(this, true);
hr = m_mediaSession->BeginGetEvent(callback, nullptr);
if (FAILED(hr))
return false;
}
return true;
}
bool MediaPlayerPrivateMediaFoundation::createTopologyFromSource()
{
if (!MFCreateTopologyPtr())
return false;
// Create a new topology.
if (FAILED(MFCreateTopologyPtr()(&m_topology)))
return false;
// Create the presentation descriptor for the media source.
if (FAILED(m_mediaSource->CreatePresentationDescriptor(&m_sourcePD)))
return false;
// Get the number of streams in the media source.
DWORD sourceStreams = 0;
if (FAILED(m_sourcePD->GetStreamDescriptorCount(&sourceStreams)))
return false;
// For each stream, create the topology nodes and add them to the topology.
for (DWORD i = 0; i < sourceStreams; i++) {
if (!addBranchToPartialTopology(i))
return false;
}
return true;
}
bool MediaPlayerPrivateMediaFoundation::addBranchToPartialTopology(int stream)
{
// Get the stream descriptor for this stream.
COMPtr<IMFStreamDescriptor> sourceSD;
BOOL selected = FALSE;
if (FAILED(m_sourcePD->GetStreamDescriptorByIndex(stream, &selected, &sourceSD)))
return false;
// Create the topology branch only if the stream is selected.
// Otherwise, do nothing.
if (!selected)
return true;
// Create a source node for this stream.
COMPtr<IMFTopologyNode> sourceNode;
if (!createSourceStreamNode(sourceSD, sourceNode))
return false;
COMPtr<IMFTopologyNode> outputNode;
if (!createOutputNode(sourceSD, outputNode))
return false;
// Add both nodes to the topology.
if (FAILED(m_topology->AddNode(sourceNode.get())))
return false;
if (FAILED(m_topology->AddNode(outputNode.get())))
return false;
// Connect the source node to the output node.
if (FAILED(sourceNode->ConnectOutput(0, outputNode.get(), 0)))
return false;
return true;
}
LRESULT CALLBACK MediaPlayerPrivateMediaFoundation::VideoViewWndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
return DefWindowProc(hWnd, message, wParam, lParam);
}
LPCWSTR MediaPlayerPrivateMediaFoundation::registerVideoWindowClass()
{
const LPCWSTR kVideoWindowClassName = L"WebVideoWindowClass";
static bool haveRegisteredWindowClass = false;
if (haveRegisteredWindowClass)
return kVideoWindowClassName;
haveRegisteredWindowClass = true;
WNDCLASSEX wcex;
wcex.cbSize = sizeof(WNDCLASSEX);
wcex.style = CS_DBLCLKS;
wcex.lpfnWndProc = VideoViewWndProc;
wcex.cbClsExtra = 0;
wcex.cbWndExtra = 0;
wcex.hInstance = nullptr;
wcex.hIcon = nullptr;
wcex.hCursor = ::LoadCursor(0, IDC_ARROW);
wcex.hbrBackground = nullptr;
wcex.lpszMenuName = nullptr;
wcex.lpszClassName = kVideoWindowClassName;
wcex.hIconSm = nullptr;
if (RegisterClassEx(&wcex))
return kVideoWindowClassName;
return nullptr;
}
void MediaPlayerPrivateMediaFoundation::createVideoWindow()
{
HWND hWndParent = nullptr;
FrameView* view = nullptr;
if (!m_player || !m_player->cachedResourceLoader() || !m_player->cachedResourceLoader()->document())
return;
view = m_player->cachedResourceLoader()->document()->view();
if (!view || !view->hostWindow())
return;
PlatformPageClient pageClient = view->hostWindow()->platformPageClient();
#if PLATFORM(QT)
QWindow* ownerWindow = pageClient ? pageClient->ownerWindow() : nullptr;
if (!ownerWindow)
return;
hWndParent = (HWND)ownerWindow->winId();
#else
hWndParent = pageClient;
#endif
m_hwndVideo = CreateWindowEx(WS_EX_NOACTIVATE | WS_EX_TRANSPARENT, registerVideoWindowClass(), 0, WS_CHILD | WS_CLIPSIBLINGS | WS_CLIPCHILDREN,
0, 0, 0, 0, hWndParent, 0, 0, 0);
}
void MediaPlayerPrivateMediaFoundation::destroyVideoWindow()
{
if (m_hwndVideo) {
DestroyWindow(m_hwndVideo);
m_hwndVideo = nullptr;
}
}
void MediaPlayerPrivateMediaFoundation::invalidateFrameView()
{
FrameView* view = nullptr;
if (!m_player || !m_player->cachedResourceLoader() || !m_player->cachedResourceLoader()->document())
return;
view = m_player->cachedResourceLoader()->document()->view();
if (!view)
return;
view->invalidate();
}
void MediaPlayerPrivateMediaFoundation::addListener(MediaPlayerListener* listener)
{
LockHolder locker(m_mutexListeners);
m_listeners.add(listener);
}
void MediaPlayerPrivateMediaFoundation::removeListener(MediaPlayerListener* listener)
{
LockHolder locker(m_mutexListeners);
m_listeners.remove(listener);
}
void MediaPlayerPrivateMediaFoundation::notifyDeleted()
{
LockHolder locker(m_mutexListeners);
for (HashSet<MediaPlayerListener*>::const_iterator it = m_listeners.begin(); it != m_listeners.end(); ++it)
(*it)->onMediaPlayerDeleted();
}
void MediaPlayerPrivateMediaFoundation::setNaturalSize(const FloatSize& size)
{
LockHolder locker(m_cachedNaturalSizeLock);
m_cachedNaturalSize = size;
}
bool MediaPlayerPrivateMediaFoundation::createOutputNode(COMPtr<IMFStreamDescriptor> sourceSD, COMPtr<IMFTopologyNode>& node)
{
if (!MFCreateTopologyNodePtr() || !MFCreateAudioRendererActivatePtr() || !MFCreateVideoRendererActivatePtr())
return false;
if (!sourceSD)
return false;
#ifndef NDEBUG
// Get the stream ID.
DWORD streamID = 0;
sourceSD->GetStreamIdentifier(&streamID); // Just for debugging, ignore any failures.
#endif
COMPtr<IMFMediaTypeHandler> handler;
if (FAILED(sourceSD->GetMediaTypeHandler(&handler)))
return false;
GUID guidMajorType = GUID_NULL;
if (FAILED(handler->GetMajorType(&guidMajorType)))
return false;
// Create a downstream node.
if (FAILED(MFCreateTopologyNodePtr()(MF_TOPOLOGY_OUTPUT_NODE, &node)))
return false;
// Create an IMFActivate object for the renderer, based on the media type.
COMPtr<IMFActivate> rendererActivate;
if (MFMediaType_Audio == guidMajorType) {
// Create the audio renderer.
if (FAILED(MFCreateAudioRendererActivatePtr()(&rendererActivate)))
return false;
m_hasAudio = true;
} else if (MFMediaType_Video == guidMajorType) {
// Create the video renderer.
if (FAILED(MFCreateVideoRendererActivatePtr()(nullptr, &rendererActivate)))
return false;
m_presenter = new CustomVideoPresenter(this);
m_presenter->SetVideoWindow(m_hwndVideo);
if (FAILED(rendererActivate->SetUnknown(MF_ACTIVATE_CUSTOM_VIDEO_PRESENTER_ACTIVATE, static_cast<IMFActivate*>(m_presenter.get()))))
return false;
m_hasVideo = true;
} else
return false;
// Set the IActivate object on the output node.
if (FAILED(node->SetObject(rendererActivate.get())))
return false;
return true;
}
bool MediaPlayerPrivateMediaFoundation::createSourceStreamNode(COMPtr<IMFStreamDescriptor> sourceSD, COMPtr<IMFTopologyNode>& node)
{
if (!MFCreateTopologyNodePtr())
return false;
if (!m_mediaSource || !m_sourcePD || !sourceSD)
return false;
// Create the source-stream node.
HRESULT hr = MFCreateTopologyNodePtr()(MF_TOPOLOGY_SOURCESTREAM_NODE, &node);
if (FAILED(hr))
return false;
// Set attribute: Pointer to the media source.
hr = node->SetUnknown(MF_TOPONODE_SOURCE, m_mediaSource.get());
if (FAILED(hr))
return false;
// Set attribute: Pointer to the presentation descriptor.
hr = node->SetUnknown(MF_TOPONODE_PRESENTATION_DESCRIPTOR, m_sourcePD.get());
if (FAILED(hr))
return false;
// Set attribute: Pointer to the stream descriptor.
hr = node->SetUnknown(MF_TOPONODE_STREAM_DESCRIPTOR, sourceSD.get());
if (FAILED(hr))
return false;
return true;
}
void MediaPlayerPrivateMediaFoundation::updateReadyState()
{
if (!MFGetServicePtr())
return;
COMPtr<IPropertyStore> prop;
// Get the property store from the media session.
HRESULT hr = MFGetServicePtr()(m_mediaSession.get(), MFNETSOURCE_STATISTICS_SERVICE, IID_PPV_ARGS(&prop));
if (FAILED(hr))
return;
PROPERTYKEY key;
key.fmtid = MFNETSOURCE_STATISTICS;
key.pid = MFNETSOURCE_BUFFERPROGRESS_ID;
PROPVARIANT var;
hr = prop->GetValue(key, &var);
const LONG percentageOfPlaybackBufferFilled = var.lVal;
PropVariantClear(&var);
if (FAILED(hr))
return;
MediaPlayer::ReadyState oldReadyState = m_readyState;
if (percentageOfPlaybackBufferFilled >= 100) {
m_readyState = MediaPlayer::HaveEnoughData;
if (m_preparingToPlay) {
pause();
m_preparingToPlay = false;
}
} else if (percentageOfPlaybackBufferFilled > 0)
m_readyState = MediaPlayer::HaveFutureData;
else
m_readyState = MediaPlayer::HaveCurrentData;
if (m_readyState != oldReadyState)
m_player->readyStateChanged();
}
COMPtr<IMFVideoDisplayControl> MediaPlayerPrivateMediaFoundation::videoDisplay()
{
if (m_videoDisplay)
return m_videoDisplay;
if (!MFGetServicePtr())
return nullptr;
MFGetServicePtr()(m_mediaSession.get(), MR_VIDEO_RENDER_SERVICE, IID_PPV_ARGS(&m_videoDisplay));
return m_videoDisplay;
}
void MediaPlayerPrivateMediaFoundation::onCreatedMediaSource()
{
if (!createTopologyFromSource())
return;
// Set the topology on the media session.
HRESULT hr = m_mediaSession->SetTopology(0, m_topology.get());
ASSERT(SUCCEEDED(hr));
}
void MediaPlayerPrivateMediaFoundation::onTopologySet()
{
// This method is called on the main thread as a result of load() being called.
if (auto videoDisplay = this->videoDisplay()) {
RECT rc = { 0, 0, m_size.width(), m_size.height() };
videoDisplay->SetVideoPosition(nullptr, &rc);
}
// It is expected that we start buffering data from the network now.
// We call startSession() to start buffering video data.
// When we have received enough data, we pause, so that we don't actually start the playback.
ASSERT(m_paused);
ASSERT(!m_preparingToPlay);
m_preparingToPlay = startSession();
}
void MediaPlayerPrivateMediaFoundation::onBufferingStarted()
{
updateReadyState();
}
void MediaPlayerPrivateMediaFoundation::onBufferingStopped()
{
updateReadyState();
}
void MediaPlayerPrivateMediaFoundation::onSessionStarted()
{
updateReadyState();
}
void MediaPlayerPrivateMediaFoundation::onSessionEnded()
{
m_networkState = MediaPlayer::Loaded;
m_player->networkStateChanged();
m_paused = true;
m_player->playbackStateChanged();
}
MediaPlayerPrivateMediaFoundation::AsyncCallback::AsyncCallback(MediaPlayerPrivateMediaFoundation* mediaPlayer, bool event)
: m_refCount(0)
, m_mediaPlayer(mediaPlayer)
, m_event(event)
{
if (m_mediaPlayer)
m_mediaPlayer->addListener(this);
}
MediaPlayerPrivateMediaFoundation::AsyncCallback::~AsyncCallback()
{
if (m_mediaPlayer)
m_mediaPlayer->removeListener(this);
}
HRESULT MediaPlayerPrivateMediaFoundation::AsyncCallback::QueryInterface(_In_ REFIID riid, __RPC__deref_out void __RPC_FAR *__RPC_FAR *ppvObject)
{
if (!ppvObject)
return E_POINTER;
if (!IsEqualGUID(riid, IID_IMFAsyncCallback)) {
*ppvObject = nullptr;
return E_NOINTERFACE;
}
*ppvObject = this;
AddRef();
return S_OK;
}
ULONG STDMETHODCALLTYPE MediaPlayerPrivateMediaFoundation::AsyncCallback::AddRef()
{
m_refCount++;
return m_refCount;
}
ULONG STDMETHODCALLTYPE MediaPlayerPrivateMediaFoundation::AsyncCallback::Release()
{
m_refCount--;
ULONG refCount = m_refCount;
if (!refCount)
delete this;
return refCount;
}
HRESULT STDMETHODCALLTYPE MediaPlayerPrivateMediaFoundation::AsyncCallback::GetParameters(__RPC__out DWORD *pdwFlags, __RPC__out DWORD *pdwQueue)
{
// Returning E_NOTIMPL gives default values.
return E_NOTIMPL;
}
HRESULT STDMETHODCALLTYPE MediaPlayerPrivateMediaFoundation::AsyncCallback::Invoke(__RPC__in_opt IMFAsyncResult *pAsyncResult)
{
LockHolder locker(m_mutex);
if (!m_mediaPlayer)
return S_OK;
if (m_event)
m_mediaPlayer->endGetEvent(pAsyncResult);
else
m_mediaPlayer->endCreatedMediaSource(pAsyncResult);
return S_OK;
}
void MediaPlayerPrivateMediaFoundation::AsyncCallback::onMediaPlayerDeleted()
{
LockHolder locker(m_mutex);
m_mediaPlayer = nullptr;
}
MediaPlayerPrivateMediaFoundation::CustomVideoPresenter::CustomVideoPresenter(MediaPlayerPrivateMediaFoundation* mediaPlayer)
: m_mediaPlayer(mediaPlayer)
{
if (m_mediaPlayer)
m_mediaPlayer->addListener(this);
m_sourceRect.top = 0;
m_sourceRect.left = 0;
m_sourceRect.bottom = 1;
m_sourceRect.right = 1;
m_presenterEngine = std::make_unique<Direct3DPresenter>();
if (!m_presenterEngine)
return;
m_scheduler.setPresenter(m_presenterEngine.get());
}
MediaPlayerPrivateMediaFoundation::CustomVideoPresenter::~CustomVideoPresenter()
{
if (m_mediaPlayer)
m_mediaPlayer->removeListener(this);
}
HRESULT MediaPlayerPrivateMediaFoundation::CustomVideoPresenter::QueryInterface(REFIID riid, __RPC__deref_out void __RPC_FAR *__RPC_FAR *ppvObject)
{
*ppvObject = nullptr;
if (IsEqualGUID(riid, IID_IMFGetService))
*ppvObject = static_cast<IMFGetService*>(this);
else if (IsEqualGUID(riid, IID_IMFActivate))
*ppvObject = static_cast<IMFActivate*>(this);
else if (IsEqualGUID(riid, IID_IMFVideoDisplayControl))
*ppvObject = static_cast<IMFVideoDisplayControl*>(this);
else if (IsEqualGUID(riid, IID_IMFVideoPresenter))
*ppvObject = static_cast<IMFVideoPresenter*>(this);
else if (IsEqualGUID(riid, IID_IMFClockStateSink))
*ppvObject = static_cast<IMFClockStateSink*>(this);
else if (IsEqualGUID(riid, IID_IMFVideoDeviceID))
*ppvObject = static_cast<IMFVideoDeviceID*>(this);
else if (IsEqualGUID(riid, IID_IMFTopologyServiceLookupClient))
*ppvObject = static_cast<IMFTopologyServiceLookupClient*>(this);
else if (IsEqualGUID(riid, IID_IUnknown))
*ppvObject = static_cast<IMFVideoPresenter*>(this);
else if (IsEqualGUID(riid, IID_IMFAsyncCallback))
*ppvObject = static_cast<IMFAsyncCallback*>(this);
else
return E_NOINTERFACE;
AddRef();
return S_OK;
}
ULONG MediaPlayerPrivateMediaFoundation::CustomVideoPresenter::AddRef()
{
m_refCount++;
return m_refCount;
}
ULONG MediaPlayerPrivateMediaFoundation::CustomVideoPresenter::Release()
{
m_refCount--;
ULONG refCount = m_refCount;
if (!refCount)
delete this;
return refCount;
}
HRESULT MediaPlayerPrivateMediaFoundation::CustomVideoPresenter::OnClockStart(MFTIME hnsSystemTime, LONGLONG llClockStartOffset)
{
LockHolder locker(m_lock);
// After shutdown, we cannot start.
HRESULT hr = checkShutdown();
if (FAILED(hr))
return hr;
m_renderState = RenderStateStarted;
if (isActive()) {
if (llClockStartOffset != PRESENTATION_CURRENT_POSITION) {
// This is a seek request, flush pending samples.
flush();
}
}
processOutputLoop();
return S_OK;
}
HRESULT MediaPlayerPrivateMediaFoundation::CustomVideoPresenter::OnClockStop(MFTIME hnsSystemTime)
{
LockHolder locker(m_lock);
HRESULT hr = checkShutdown();
if (FAILED(hr))
return hr;
if (m_renderState != RenderStateStopped) {
m_renderState = RenderStateStopped;
flush();
}
return S_OK;
}
HRESULT MediaPlayerPrivateMediaFoundation::CustomVideoPresenter::OnClockPause(MFTIME hnsSystemTime)
{
LockHolder locker(m_lock);
// After shutdown, we cannot pause.
HRESULT hr = checkShutdown();
if (FAILED(hr))
return hr;
m_renderState = RenderStatePaused;
return S_OK;
}
HRESULT MediaPlayerPrivateMediaFoundation::CustomVideoPresenter::OnClockRestart(MFTIME hnsSystemTime)
{
LockHolder locker(m_lock);
HRESULT hr = checkShutdown();
if (FAILED(hr))
return hr;
ASSERT(m_renderState == RenderStatePaused);
m_renderState = RenderStateStarted;
processOutputLoop();
return S_OK;
}
HRESULT MediaPlayerPrivateMediaFoundation::CustomVideoPresenter::OnClockSetRate(MFTIME hnsSystemTime, float rate)
{
LockHolder locker(m_lock);
HRESULT hr = checkShutdown();
if (FAILED(hr))
return hr;
m_rate = rate;
m_scheduler.setClockRate(rate);
return S_OK;
}
HRESULT MediaPlayerPrivateMediaFoundation::CustomVideoPresenter::ProcessMessage(MFVP_MESSAGE_TYPE eMessage, ULONG_PTR ulParam)
{
LockHolder locker(m_lock);
HRESULT hr = checkShutdown();
if (FAILED(hr))
return hr;
switch (eMessage) {
case MFVP_MESSAGE_FLUSH:
hr = flush();
break;
case MFVP_MESSAGE_INVALIDATEMEDIATYPE:
hr = renegotiateMediaType();
break;
case MFVP_MESSAGE_PROCESSINPUTNOTIFY:
// A new input sample is available.
hr = processInputNotify();
break;
case MFVP_MESSAGE_BEGINSTREAMING:
hr = beginStreaming();
break;
case MFVP_MESSAGE_ENDSTREAMING:
hr = endStreaming();
break;
case MFVP_MESSAGE_ENDOFSTREAM:
m_endStreaming = true;
hr = checkEndOfStream();
break;
default:
hr = E_INVALIDARG;
break;
}
return hr;
}
HRESULT MediaPlayerPrivateMediaFoundation::CustomVideoPresenter::GetCurrentMediaType(_Outptr_ IMFVideoMediaType **ppMediaType)
{
LockHolder locker(m_lock);
if (!ppMediaType)
return E_POINTER;
HRESULT hr = checkShutdown();
if (FAILED(hr))
return hr;
if (!m_mediaType)
return MF_E_NOT_INITIALIZED;
return m_mediaType->QueryInterface(__uuidof(IMFVideoMediaType), (void**)&ppMediaType);
}
HRESULT MediaPlayerPrivateMediaFoundation::CustomVideoPresenter::GetDeviceID(IID* pDeviceID)
{
if (!pDeviceID)
return E_POINTER;
*pDeviceID = __uuidof(IDirect3DDevice9);
return S_OK;
}
HRESULT MediaPlayerPrivateMediaFoundation::CustomVideoPresenter::InitServicePointers(IMFTopologyServiceLookup *pLookup)
{
if (!pLookup)
return E_POINTER;
HRESULT hr = S_OK;
LockHolder locker(m_lock);
if (isActive())
return MF_E_INVALIDREQUEST;
m_clock = nullptr;
m_mixer = nullptr;
m_mediaEventSink = nullptr;
// Lookup the services.
DWORD objectCount = 1;
hr = pLookup->LookupService(MF_SERVICE_LOOKUP_GLOBAL, 0, MR_VIDEO_RENDER_SERVICE, IID_PPV_ARGS(&m_clock), &objectCount);
// The clock service is optional.
objectCount = 1;
hr = pLookup->LookupService(MF_SERVICE_LOOKUP_GLOBAL, 0, MR_VIDEO_MIXER_SERVICE, IID_PPV_ARGS(&m_mixer), &objectCount);
if (FAILED(hr))
return hr;
hr = configureMixer(m_mixer.get());
if (FAILED(hr))
return hr;
objectCount = 1;
hr = pLookup->LookupService(MF_SERVICE_LOOKUP_GLOBAL, 0, MR_VIDEO_RENDER_SERVICE, IID_PPV_ARGS(&m_mediaEventSink), &objectCount);
if (FAILED(hr))
return hr;
m_renderState = RenderStateStopped;
return S_OK;
}
HRESULT MediaPlayerPrivateMediaFoundation::CustomVideoPresenter::ReleaseServicePointers()
{
LockHolder locker(m_lock);
m_renderState = RenderStateShutdown;
flush();
setMediaType(nullptr);
m_clock = nullptr;
m_mixer = nullptr;
m_mediaEventSink = nullptr;
return S_OK;
}
HRESULT MediaPlayerPrivateMediaFoundation::CustomVideoPresenter::GetService(REFGUID guidService, REFIID riid, LPVOID* ppvObject)
{
if (!ppvObject)
return E_POINTER;
// We only support MR_VIDEO_RENDER_SERVICE.
if (guidService != MR_VIDEO_RENDER_SERVICE)
return MF_E_UNSUPPORTED_SERVICE;
HRESULT hr = m_presenterEngine->getService(guidService, riid, ppvObject);
if (FAILED(hr))
hr = QueryInterface(riid, ppvObject);
return hr;
}
HRESULT MediaPlayerPrivateMediaFoundation::CustomVideoPresenter::ActivateObject(REFIID riid, void **ppv)
{
if (!ppv)
return E_POINTER;
if (riid == IID_IMFVideoPresenter) {
*ppv = static_cast<IMFVideoPresenter*>(this);
AddRef();
return S_OK;
}
return E_FAIL;
}
HRESULT MediaPlayerPrivateMediaFoundation::CustomVideoPresenter::DetachObject()
{
return S_OK;
}
HRESULT MediaPlayerPrivateMediaFoundation::CustomVideoPresenter::ShutdownObject()
{
return S_OK;
}
HRESULT MediaPlayerPrivateMediaFoundation::CustomVideoPresenter::SetVideoWindow(HWND hwndVideo)
{
LockHolder locker(m_lock);
if (!IsWindow(hwndVideo))
return E_INVALIDARG;
HRESULT hr = S_OK;
HWND oldHwnd = m_presenterEngine->getVideoWindow();
if (oldHwnd != hwndVideo) {
// This will create a new Direct3D device.
hr = m_presenterEngine->setVideoWindow(hwndVideo);
notifyEvent(EC_DISPLAY_CHANGED, 0, 0);
}
return hr;
}
HRESULT MediaPlayerPrivateMediaFoundation::CustomVideoPresenter::GetVideoWindow(HWND* phwndVideo)
{
LockHolder locker(m_lock);
if (!phwndVideo)
return E_POINTER;
*phwndVideo = m_presenterEngine->getVideoWindow();
return S_OK;
}
static HRESULT setMixerSourceRect(IMFTransform* mixer, const MFVideoNormalizedRect& sourceRect)
{
if (!mixer)
return E_POINTER;
COMPtr<IMFAttributes> attributes;
HRESULT hr = mixer->GetAttributes(&attributes);
if (FAILED(hr))
return hr;
return attributes->SetBlob(VIDEO_ZOOM_RECT, (const UINT8*)&sourceRect, sizeof(sourceRect));
}
HRESULT MediaPlayerPrivateMediaFoundation::CustomVideoPresenter::SetVideoPosition(const MFVideoNormalizedRect* pnrcSource, const LPRECT prcDest)
{
LockHolder locker(m_lock);
// First, check that the parameters are valid.
if (!pnrcSource && !prcDest)
return E_POINTER;
if (pnrcSource) {
if ((pnrcSource->left > pnrcSource->right) || (pnrcSource->top > pnrcSource->bottom))
return E_INVALIDARG;
// The source rectangle must be normalized.
if ((pnrcSource->left < 0) || (pnrcSource->right > 1) || (pnrcSource->top < 0) || (pnrcSource->bottom > 1))
return E_INVALIDARG;
}
if (prcDest) {
if ((prcDest->left > prcDest->right) || (prcDest->top > prcDest->bottom))
return E_INVALIDARG;
}
HRESULT hr = S_OK;
// Set the source rectangle.
if (pnrcSource) {
m_sourceRect = *pnrcSource;
if (m_mixer) {
hr = setMixerSourceRect(m_mixer.get(), m_sourceRect);
if (FAILED(hr))
return hr;
}
}
// Set the destination rectangle.
if (prcDest) {
RECT rcOldDest = m_presenterEngine->getDestinationRect();
// If the destination rectangle hasn't changed, we are done.
if (!EqualRect(&rcOldDest, prcDest)) {
hr = m_presenterEngine->setDestinationRect(*prcDest);
if (FAILED(hr))
return hr;
// We need to change the media type when the destination rectangle has changed.
if (m_mixer) {
hr = renegotiateMediaType();
if (hr == MF_E_TRANSFORM_TYPE_NOT_SET) {
// This is not a critical failure; the EVR will let us know when
// we have to set the mixer media type.
hr = S_OK;
} else {
if (FAILED(hr))
return hr;
// We have successfully changed the media type,
// ask for a repaint of the current frame.
m_repaint = true;
processOutput();
}
}
}
}
return S_OK;
}
HRESULT MediaPlayerPrivateMediaFoundation::CustomVideoPresenter::GetVideoPosition(MFVideoNormalizedRect* pnrcSource, LPRECT prcDest)
{
LockHolder locker(m_lock);
if (!pnrcSource || !prcDest)
return E_POINTER;
*pnrcSource = m_sourceRect;
*prcDest = m_presenterEngine->getDestinationRect();
return S_OK;
}
HRESULT MediaPlayerPrivateMediaFoundation::CustomVideoPresenter::RepaintVideo()
{
LockHolder locker(m_lock);
HRESULT hr = checkShutdown();
if (FAILED(hr))
return hr;
// Check that at least one sample has been presented.
if (m_prerolled) {
m_repaint = true;
processOutput();
}
return S_OK;
}
HRESULT MediaPlayerPrivateMediaFoundation::CustomVideoPresenter::Invoke(IMFAsyncResult* pAsyncResult)
{
return onSampleFree(pAsyncResult);
}
void MediaPlayerPrivateMediaFoundation::CustomVideoPresenter::onMediaPlayerDeleted()
{
m_mediaPlayer = nullptr;
}
void MediaPlayerPrivateMediaFoundation::CustomVideoPresenter::paintCurrentFrame(GraphicsContext& context, const FloatRect& r)
{
if (m_presenterEngine)
m_presenterEngine->paintCurrentFrame(context, r);
}
float MediaPlayerPrivateMediaFoundation::CustomVideoPresenter::currentTime()
{
if (!m_clock)
return 0.0f;
LONGLONG clockTime;
MFTIME systemTime;
HRESULT hr = m_clock->GetCorrelatedTime(0, &clockTime, &systemTime);
if (FAILED(hr))
return 0.0f;
// clockTime is in 100 nanoseconds, we need to convert to seconds.
float currentTime = clockTime / tenMegahertz;
if (currentTime > m_maxTimeLoaded)
m_maxTimeLoaded = currentTime;
return currentTime;
}
bool MediaPlayerPrivateMediaFoundation::CustomVideoPresenter::isActive() const
{
return ((m_renderState == RenderStateStarted) || (m_renderState == RenderStatePaused));
}
HRESULT MediaPlayerPrivateMediaFoundation::CustomVideoPresenter::configureMixer(IMFTransform* mixer)
{
COMPtr<IMFVideoDeviceID> videoDeviceID;
HRESULT hr = mixer->QueryInterface(__uuidof(IMFVideoDeviceID), (void**)&videoDeviceID);
if (FAILED(hr))
return hr;
IID deviceID = GUID_NULL;
hr = videoDeviceID->GetDeviceID(&deviceID);
if (FAILED(hr))
return hr;
// The mixer must have this device ID.
if (!IsEqualGUID(deviceID, __uuidof(IDirect3DDevice9)))
return MF_E_INVALIDREQUEST;
setMixerSourceRect(mixer, m_sourceRect);
return S_OK;
}
HRESULT MediaPlayerPrivateMediaFoundation::CustomVideoPresenter::flush()
{
m_prerolled = false;
// Flush the sceduler.
// This call will block until the scheduler thread has finished flushing.
m_scheduler.flush();
if (m_renderState == RenderStateStopped)
m_presenterEngine->presentSample(nullptr, 0);
return S_OK;
}
static bool areMediaTypesEqual(IMFMediaType* type1, IMFMediaType* type2)
{
if (!type1 && !type2)
return true;
if (!type1 || !type2)
return false;
DWORD flags = 0;
return S_OK == type1->IsEqual(type2, &flags);
}
static FloatSize calculateNaturalSize(IMFMediaType* mediaType)
{
UINT32 width = 0, height = 0;
HRESULT hr = MFGetAttributeSize(mediaType, MF_MT_FRAME_SIZE, &width, &height);
if (FAILED(hr) || !height)
return FloatSize();
UINT32 pixelAspectRatioNumerator = 0;
UINT32 pixelAspectRatioDenominator = 0;
hr = MFGetAttributeRatio(mediaType, MF_MT_PIXEL_ASPECT_RATIO, &pixelAspectRatioNumerator, &pixelAspectRatioDenominator);
if (SUCCEEDED(hr) && pixelAspectRatioNumerator && pixelAspectRatioDenominator)
return FloatSize(float(width) * pixelAspectRatioNumerator / pixelAspectRatioDenominator, height);
return FloatSize();
}
HRESULT MediaPlayerPrivateMediaFoundation::CustomVideoPresenter::setMediaType(IMFMediaType* mediaType)
{
if (!mediaType) {
m_mediaType = nullptr;
releaseResources();
return S_OK;
}
// If we have shut down, we cannot set the media type.
HRESULT hr = checkShutdown();
if (FAILED(hr)) {
releaseResources();
return hr;
}
if (areMediaTypesEqual(m_mediaType.get(), mediaType))
return S_OK;
m_mediaType = nullptr;
releaseResources();
// Get allocated samples from the presenter.
VideoSampleList sampleQueue;
hr = m_presenterEngine->createVideoSamples(mediaType, sampleQueue);
if (FAILED(hr)) {
releaseResources();
return hr;
}
// Set the token counter on each sample.
// This will help us to determine when they are invalid, and can be released.
for (auto sample : sampleQueue) {
hr = sample->SetUINT32(MFSamplePresenterSampleCounter, m_tokenCounter);
if (FAILED(hr)) {
releaseResources();
return hr;
}
}
// Add the samples to the sample pool.
hr = m_samplePool.initialize(sampleQueue);
if (FAILED(hr)) {
releaseResources();
return hr;
}
// Set the frame rate.
MFRatio fps = { 0, 0 };
hr = MFGetAttributeRatio(mediaType, MF_MT_FRAME_RATE, (UINT32*)&fps.Numerator, (UINT32*)&fps.Denominator);
if (SUCCEEDED(hr) && fps.Numerator && fps.Denominator)
m_scheduler.setFrameRate(fps);
else {
// We could not get the frame ret, use default.
const MFRatio defaultFrameRate = { 30, 1 };
m_scheduler.setFrameRate(defaultFrameRate);
}
// Update natural size
if (m_mediaPlayer)
m_mediaPlayer->setNaturalSize(calculateNaturalSize(mediaType));
ASSERT(mediaType);
m_mediaType = mediaType;
return S_OK;
}
HRESULT MediaPlayerPrivateMediaFoundation::CustomVideoPresenter::checkShutdown() const
{
if (m_renderState == RenderStateShutdown)
return MF_E_SHUTDOWN;
return S_OK;
}
HRESULT MediaPlayerPrivateMediaFoundation::CustomVideoPresenter::renegotiateMediaType()
{
HRESULT hr = S_OK;
if (!m_mixer)
return MF_E_INVALIDREQUEST;
// Iterate over the available output types of the mixer.
DWORD typeIndex = 0;
bool foundMediaType = false;
while (!foundMediaType && (hr != MF_E_NO_MORE_TYPES)) {
// Get the next available media type.
COMPtr<IMFMediaType> mixerType;
hr = m_mixer->GetOutputAvailableType(0, typeIndex++, &mixerType);
if (FAILED(hr))
break;
// Do we support this media type?
hr = isMediaTypeSupported(mixerType.get());
if (FAILED(hr))
break;
// Make adjustments to proposed media type.
COMPtr<IMFMediaType> optimalType;
hr = createOptimalVideoType(mixerType.get(), &optimalType);
if (FAILED(hr))
break;
// Test whether the mixer can accept the modified media type
hr = m_mixer->SetOutputType(0, optimalType.get(), MFT_SET_TYPE_TEST_ONLY);
if (FAILED(hr))
break;
// Try to set the new media type
hr = setMediaType(optimalType.get());
if (FAILED(hr))
break;
hr = m_mixer->SetOutputType(0, optimalType.get(), 0);
ASSERT(SUCCEEDED(hr));
if (FAILED(hr))
setMediaType(nullptr);
else
foundMediaType = true;
}
return hr;
}
HRESULT MediaPlayerPrivateMediaFoundation::CustomVideoPresenter::processInputNotify()
{
// We have a new sample.
m_sampleNotify = true;
if (!m_mediaType) {
// The media type is not valid.
return MF_E_TRANSFORM_TYPE_NOT_SET;
}
// Invalidate the video area
if (m_mediaPlayer) {
auto weakPtr = m_mediaPlayer->m_weakPtrFactory.createWeakPtr();
callOnMainThread([weakPtr] {
if (weakPtr)
weakPtr->invalidateFrameView();
});
}
// Process sample
processOutputLoop();
return S_OK;
}
static float MFOffsetToFloat(const MFOffset& offset)
{
const int denominator = std::numeric_limits<WORD>::max() + 1;
return offset.value + (float(offset.fract) / denominator);
}
static MFOffset MakeOffset(float v)
{
// v = offset.value + (offset.fract / denominator), where denominator = 65536.0f.
const int denominator = std::numeric_limits<WORD>::max() + 1;
MFOffset offset;
offset.value = short(v);
offset.fract = WORD(denominator * (v - offset.value));
return offset;
}
static MFVideoArea MakeArea(float x, float y, DWORD width, DWORD height)
{
MFVideoArea area;
area.OffsetX = MakeOffset(x);
area.OffsetY = MakeOffset(y);
area.Area.cx = width;
area.Area.cy = height;
return area;
}
static HRESULT validateVideoArea(const MFVideoArea& area, UINT32 width, UINT32 height)
{
float fOffsetX = MFOffsetToFloat(area.OffsetX);
float fOffsetY = MFOffsetToFloat(area.OffsetY);
if (((LONG)fOffsetX + area.Area.cx > width) || ((LONG)fOffsetY + area.Area.cy > height))
return MF_E_INVALIDMEDIATYPE;
return S_OK;
}
HRESULT MediaPlayerPrivateMediaFoundation::CustomVideoPresenter::beginStreaming()
{
return m_scheduler.startScheduler(m_clock.get());
}
HRESULT MediaPlayerPrivateMediaFoundation::CustomVideoPresenter::endStreaming()
{
return m_scheduler.stopScheduler();
}
HRESULT MediaPlayerPrivateMediaFoundation::CustomVideoPresenter::checkEndOfStream()
{
if (!m_endStreaming) {
// We have not received the end-of-stream message from the EVR.
return S_OK;
}
if (m_sampleNotify) {
// There is still input samples available for the mixer.
return S_OK;
}
if (m_samplePool.areSamplesPending()) {
// There are samples scheduled for rendering.
return S_OK;
}
// We are done, notify the EVR.
notifyEvent(EC_COMPLETE, (LONG_PTR)S_OK, 0);
m_endStreaming = false;
return S_OK;
}
HRESULT MediaPlayerPrivateMediaFoundation::CustomVideoPresenter::isMediaTypeSupported(IMFMediaType* mediaType)
{
COMPtr<IMFMediaType> proposedVideoType = mediaType;
// We don't support compressed media types.
BOOL compressed = FALSE;
HRESULT hr = proposedVideoType->IsCompressedFormat(&compressed);
if (FAILED(hr))
return hr;
if (compressed)
return MF_E_INVALIDMEDIATYPE;
// Validate the format.
GUID guidSubType = GUID_NULL;
hr = proposedVideoType->GetGUID(MF_MT_SUBTYPE, &guidSubType);
if (FAILED(hr))
return hr;
D3DFORMAT d3dFormat = (D3DFORMAT)guidSubType.Data1;
// Check if the format can be used as backbuffer format.
hr = m_presenterEngine->checkFormat(d3dFormat);
if (FAILED(hr))
return hr;
// Check interlaced formats.
MFVideoInterlaceMode interlaceMode = MFVideoInterlace_Unknown;
hr = proposedVideoType->GetUINT32(MF_MT_INTERLACE_MODE, (UINT32*)&interlaceMode);
if (FAILED(hr))
return hr;
if (interlaceMode != MFVideoInterlace_Progressive)
return MF_E_INVALIDMEDIATYPE;
UINT32 width = 0, height = 0;
hr = MFGetAttributeSize(proposedVideoType.get(), MF_MT_FRAME_SIZE, &width, &height);
if (FAILED(hr))
return hr;
// Validate apertures.
MFVideoArea videoCropArea;
if (SUCCEEDED(proposedVideoType->GetBlob(MF_MT_PAN_SCAN_APERTURE, (UINT8*)&videoCropArea, sizeof(MFVideoArea), nullptr)))
validateVideoArea(videoCropArea, width, height);
if (SUCCEEDED(proposedVideoType->GetBlob(MF_MT_GEOMETRIC_APERTURE, (UINT8*)&videoCropArea, sizeof(MFVideoArea), nullptr)))
validateVideoArea(videoCropArea, width, height);
if (SUCCEEDED(proposedVideoType->GetBlob(MF_MT_MINIMUM_DISPLAY_APERTURE, (UINT8*)&videoCropArea, sizeof(MFVideoArea), nullptr)))
validateVideoArea(videoCropArea, width, height);
return S_OK;
}
HRESULT MediaPlayerPrivateMediaFoundation::CustomVideoPresenter::createOptimalVideoType(IMFMediaType* proposedType, IMFMediaType** optimalType)
{
COMPtr<IMFMediaType> optimalVideoType;
HRESULT hr = MFCreateMediaTypePtr()(&optimalVideoType);
if (FAILED(hr))
return hr;
hr = optimalVideoType->SetGUID(MF_MT_MAJOR_TYPE, MFMediaType_Video);
if (FAILED(hr))
return hr;
hr = proposedType->CopyAllItems(optimalVideoType.get());
if (FAILED(hr))
return hr;
// We now modify the new media type.
// We assume that the monitor's pixel aspect ratio is 1:1,
// and that the pixel aspect ratio is preserved by the presenter.
hr = MFSetAttributeRatio(optimalVideoType.get(), MF_MT_PIXEL_ASPECT_RATIO, 1, 1);
if (FAILED(hr))
return hr;
// Get the output rectangle.
RECT rcOutput = m_presenterEngine->getDestinationRect();
if (IsRectEmpty(&rcOutput)) {
hr = calculateOutputRectangle(proposedType, rcOutput);
if (FAILED(hr))
return hr;
}
hr = optimalVideoType->SetUINT32(MF_MT_YUV_MATRIX, MFVideoTransferMatrix_BT709);
if (FAILED(hr))
return hr;
hr = optimalVideoType->SetUINT32(MF_MT_TRANSFER_FUNCTION, MFVideoTransFunc_709);
if (FAILED(hr))
return hr;
hr = optimalVideoType->SetUINT32(MF_MT_VIDEO_PRIMARIES, MFVideoPrimaries_BT709);
if (FAILED(hr))
return hr;
hr = optimalVideoType->SetUINT32(MF_MT_VIDEO_NOMINAL_RANGE, MFNominalRange_16_235);
if (FAILED(hr))
return hr;
hr = optimalVideoType->SetUINT32(MF_MT_VIDEO_LIGHTING, MFVideoLighting_dim);
if (FAILED(hr))
return hr;
hr = MFSetAttributeSize(optimalVideoType.get(), MF_MT_FRAME_SIZE, rcOutput.right, rcOutput.bottom);
if (FAILED(hr))
return hr;
MFVideoArea displayArea = MakeArea(0, 0, rcOutput.right, rcOutput.bottom);
hr = optimalVideoType->SetUINT32(MF_MT_PAN_SCAN_ENABLED, FALSE);
if (FAILED(hr))
return hr;
hr = optimalVideoType->SetBlob(MF_MT_GEOMETRIC_APERTURE, (UINT8*)&displayArea, sizeof(MFVideoArea));
if (FAILED(hr))
return hr;
hr = optimalVideoType->SetBlob(MF_MT_PAN_SCAN_APERTURE, (UINT8*)&displayArea, sizeof(MFVideoArea));
if (FAILED(hr))
return hr;
hr = optimalVideoType->SetBlob(MF_MT_MINIMUM_DISPLAY_APERTURE, (UINT8*)&displayArea, sizeof(MFVideoArea));
if (FAILED(hr))
return hr;
*optimalType = optimalVideoType.leakRef();
return S_OK;
}
static RECT correctAspectRatio(const RECT& src, const MFRatio& srcPAR, const MFRatio& destPAR)
{
RECT rc = { 0, 0, src.right - src.left, src.bottom - src.top };
if ((srcPAR.Numerator * destPAR.Denominator) != (srcPAR.Denominator * destPAR.Numerator)) {
// The source and destination aspect ratios are different
// Transform the source aspect ratio to 1:1
if (srcPAR.Numerator > srcPAR.Denominator)
rc.right = MulDiv(rc.right, srcPAR.Numerator, srcPAR.Denominator);
else if (srcPAR.Numerator < srcPAR.Denominator)
rc.bottom = MulDiv(rc.bottom, srcPAR.Denominator, srcPAR.Numerator);
// Transform to destination aspect ratio.
if (destPAR.Numerator > destPAR.Denominator)
rc.bottom = MulDiv(rc.bottom, destPAR.Numerator, destPAR.Denominator);
else if (destPAR.Numerator < destPAR.Denominator)
rc.right = MulDiv(rc.right, destPAR.Denominator, destPAR.Numerator);
}
return rc;
}
static HRESULT GetVideoDisplayArea(IMFMediaType* type, MFVideoArea* area)
{
if (!type || !area)
return E_POINTER;
HRESULT hr = S_OK;
UINT32 width = 0, height = 0;
BOOL bPanScan = MFGetAttributeUINT32(type, MF_MT_PAN_SCAN_ENABLED, FALSE);
if (bPanScan)
hr = type->GetBlob(MF_MT_PAN_SCAN_APERTURE, (UINT8*)area, sizeof(MFVideoArea), nullptr);
if (!bPanScan || hr == MF_E_ATTRIBUTENOTFOUND) {
hr = type->GetBlob(MF_MT_MINIMUM_DISPLAY_APERTURE, (UINT8*)area, sizeof(MFVideoArea), nullptr);
if (hr == MF_E_ATTRIBUTENOTFOUND)
hr = type->GetBlob(MF_MT_GEOMETRIC_APERTURE, (UINT8*)area, sizeof(MFVideoArea), nullptr);
if (hr == MF_E_ATTRIBUTENOTFOUND) {
hr = MFGetAttributeSize(type, MF_MT_FRAME_SIZE, &width, &height);
if (SUCCEEDED(hr))
*area = MakeArea(0.0, 0.0, width, height);
}
}
return hr;
}
HRESULT MediaPlayerPrivateMediaFoundation::CustomVideoPresenter::calculateOutputRectangle(IMFMediaType* proposedType, RECT& outputRect)
{
COMPtr<IMFMediaType> proposedVideoType = proposedType;
UINT32 srcWidth = 0, srcHeight = 0;
HRESULT hr = MFGetAttributeSize(proposedVideoType.get(), MF_MT_FRAME_SIZE, &srcWidth, &srcHeight);
if (FAILED(hr))
return hr;
MFVideoArea displayArea;
ZeroMemory(&displayArea, sizeof(displayArea));
hr = GetVideoDisplayArea(proposedVideoType.get(), &displayArea);
if (FAILED(hr))
return hr;
LONG offsetX = (LONG)MFOffsetToFloat(displayArea.OffsetX);
LONG offsetY = (LONG)MFOffsetToFloat(displayArea.OffsetY);
// Check if the display area is valid.
// If it is valid, we use it. If not, we use the frame dimensions.
RECT rcOutput;
if (displayArea.Area.cx != 0
&& displayArea.Area.cy != 0
&& offsetX + displayArea.Area.cx <= srcWidth
&& offsetY + displayArea.Area.cy <= srcHeight) {
rcOutput.left = offsetX;
rcOutput.right = offsetX + displayArea.Area.cx;
rcOutput.top = offsetY;
rcOutput.bottom = offsetY + displayArea.Area.cy;
} else {
rcOutput.left = 0;
rcOutput.top = 0;
rcOutput.right = srcWidth;
rcOutput.bottom = srcHeight;
}
// Correct aspect ratio.
MFRatio inputPAR = { 1, 1 };
MFRatio outputPAR = { 1, 1 }; // We assume the monitor's pixels are square.
MFGetAttributeRatio(proposedVideoType.get(), MF_MT_PIXEL_ASPECT_RATIO, (UINT32*)&inputPAR.Numerator, (UINT32*)&inputPAR.Denominator);
outputRect = correctAspectRatio(rcOutput, inputPAR, outputPAR);
return S_OK;
}
void MediaPlayerPrivateMediaFoundation::CustomVideoPresenter::processOutputLoop()
{
// Get video frames from the mixer and schedule them for presentation.
HRESULT hr = S_OK;
while (hr == S_OK) {
if (!m_sampleNotify) {
// Currently no more input samples.
hr = MF_E_TRANSFORM_NEED_MORE_INPUT;
break;
}
// We break from the loop if we fail to process a sample.
hr = processOutput();
}
if (hr == MF_E_TRANSFORM_NEED_MORE_INPUT)
checkEndOfStream();
}
static HRESULT setDesiredSampleTime(IMFSample* sample, const LONGLONG& sampleTime, const LONGLONG& duration)
{
// To tell the mixer to give us an earlier frame for repainting, we can set the desired sample time.
// We have to clear the desired sample time before reusing the sample.
if (!sample)
return E_POINTER;
COMPtr<IMFDesiredSample> desired;
HRESULT hr = sample->QueryInterface(__uuidof(IMFDesiredSample), (void**)&desired);
if (SUCCEEDED(hr))
desired->SetDesiredSampleTimeAndDuration(sampleTime, duration);
return hr;
}
static HRESULT clearDesiredSampleTime(IMFSample* sample)
{
if (!sample)
return E_POINTER;
// We need to retrieve some attributes we have set on the sample before we call
// IMFDesiredSample::Clear(), and set them once more, since they are cleared by
// the Clear() call.
UINT32 counter = MFGetAttributeUINT32(sample, MFSamplePresenterSampleCounter, (UINT32)-1);
COMPtr<IMFDesiredSample> desired;
HRESULT hr = sample->QueryInterface(__uuidof(IMFDesiredSample), (void**)&desired);
if (SUCCEEDED(hr)) {
desired->Clear();
hr = sample->SetUINT32(MFSamplePresenterSampleCounter, counter);
if (FAILED(hr))
return hr;
}
return hr;
}
HRESULT MediaPlayerPrivateMediaFoundation::CustomVideoPresenter::processOutput()
{
// This method will try to get a new sample from the mixer.
// It is called when the mixer has a new sample, or when repainting the last frame.
ASSERT(m_sampleNotify || m_repaint);
LONGLONG mixerStartTime = 0, mixerEndTime = 0;
MFTIME systemTime = 0;
bool repaint = m_repaint;
// If the clock has not started, we only present the first sample.
if ((m_renderState != RenderStateStarted) && !m_repaint && m_prerolled)
return S_FALSE;
if (!m_mixer)
return MF_E_INVALIDREQUEST;
// Get a free sample from the pool.
COMPtr<IMFSample> sample;
HRESULT hr = m_samplePool.getSample(sample);
if (hr == MF_E_SAMPLEALLOCATOR_EMPTY)
return S_FALSE; // We will try again later when there are free samples
if (FAILED(hr))
return hr;
ASSERT(sample);
ASSERT(MFGetAttributeUINT32(sample.get(), MFSamplePresenterSampleCounter, (UINT32)-1) == m_tokenCounter);
if (m_repaint) {
// Get the most recent sample from the mixer.
setDesiredSampleTime(sample.get(), m_scheduler.lastSampleTime(), m_scheduler.frameDuration());
m_repaint = false;
} else {
// Clear the desired sample time to get the next sample in the stream.
clearDesiredSampleTime(sample.get());
if (m_clock) {
// Get the starting time of the ProcessOutput call.
m_clock->GetCorrelatedTime(0, &mixerStartTime, &systemTime);
}
}
// Get a sample from the mixer.
MFT_OUTPUT_DATA_BUFFER dataBuffer;
ZeroMemory(&dataBuffer, sizeof(dataBuffer));
dataBuffer.dwStreamID = 0;
dataBuffer.pSample = sample.get();
dataBuffer.dwStatus = 0;
DWORD status = 0;
hr = m_mixer->ProcessOutput(0, 1, &dataBuffer, &status);
// Release events. There are usually no events returned,
// but in case there are, we should release them.
if (dataBuffer.pEvents)
dataBuffer.pEvents->Release();
if (FAILED(hr)) {
HRESULT hr2 = m_samplePool.returnSample(sample.get());
if (FAILED(hr2))
return hr2;
if (hr == MF_E_TRANSFORM_TYPE_NOT_SET) {
// The media type has not been set, renegotiate.
hr = renegotiateMediaType();
} else if (hr == MF_E_TRANSFORM_STREAM_CHANGE) {
// The media type changed, reset it.
setMediaType(nullptr);
} else if (hr == MF_E_TRANSFORM_NEED_MORE_INPUT) {
// The mixer needs more input.
m_sampleNotify = false;
}
} else {
// We have got a sample from the mixer.
if (m_clock && !repaint) {
// Notify the EVR about latency.
m_clock->GetCorrelatedTime(0, &mixerEndTime, &systemTime);
LONGLONG latencyTime = mixerEndTime - mixerStartTime;
notifyEvent(EC_PROCESSING_LATENCY, (LONG_PTR)&latencyTime, 0);
}
// Make sure we are notified when the sample is released
hr = trackSample(sample.get());
if (FAILED(hr))
return hr;
// Deliver the sample for scheduling
hr = deliverSample(sample.get(), repaint);
if (FAILED(hr))
return hr;
// At least one sample has been presented now.
m_prerolled = true;
}
return hr;
}
HRESULT MediaPlayerPrivateMediaFoundation::CustomVideoPresenter::deliverSample(IMFSample* sample, bool repaint)
{
if (!sample)
return E_POINTER;
Direct3DPresenter::DeviceState state = Direct3DPresenter::DeviceOK;
// Determine if the sample should be presented immediately.
bool presentNow = ((m_renderState != RenderStateStarted) || isScrubbing() || repaint);
HRESULT hr = m_presenterEngine->checkDeviceState(state);
if (SUCCEEDED(hr))
hr = m_scheduler.scheduleSample(sample, presentNow);
if (FAILED(hr)) {
// Streaming has failed, notify the EVR.
notifyEvent(EC_ERRORABORT, hr, 0);
} else if (state == Direct3DPresenter::DeviceReset)
notifyEvent(EC_DISPLAY_CHANGED, S_OK, 0);
return hr;
}
HRESULT MediaPlayerPrivateMediaFoundation::CustomVideoPresenter::trackSample(IMFSample* sample)
{
if (!sample)
return E_POINTER;
COMPtr<IMFTrackedSample> tracked;
HRESULT hr = sample->QueryInterface(__uuidof(IMFTrackedSample), (void**)&tracked);
if (FAILED(hr))
return hr;
if (!tracked)
return E_POINTER;
// Set callback object on which the onSampleFree method is invoked when the sample is no longer used.
return tracked->SetAllocator(this, nullptr);
}
void MediaPlayerPrivateMediaFoundation::CustomVideoPresenter::releaseResources()
{
// The token counter is incremented to indicate that existing samples are
// invalid and can be disposed in the method onSampleFree.
m_tokenCounter++;
flush();
m_samplePool.clear();
if (m_presenterEngine)
m_presenterEngine->releaseResources();
}
HRESULT MediaPlayerPrivateMediaFoundation::CustomVideoPresenter::onSampleFree(IMFAsyncResult* result)
{
if (!result)
return E_POINTER;
COMPtr<IUnknown> object;
HRESULT hr = result->GetObject(&object);
if (FAILED(hr)) {
notifyEvent(EC_ERRORABORT, hr, 0);
return hr;
}
COMPtr<IMFSample> sample;
hr = object->QueryInterface(__uuidof(IMFSample), (void**)&sample);
if (FAILED(hr)) {
notifyEvent(EC_ERRORABORT, hr, 0);
return hr;
}
m_lock.lock();
if (MFGetAttributeUINT32(sample.get(), MFSamplePresenterSampleCounter, (UINT32)-1) == m_tokenCounter) {
hr = m_samplePool.returnSample(sample.get());
// Do more processing, since a free sample is available
if (SUCCEEDED(hr))
processOutputLoop();
}
m_lock.unlock();
if (FAILED(hr))
notifyEvent(EC_ERRORABORT, hr, 0);
return hr;
}
void MediaPlayerPrivateMediaFoundation::CustomVideoPresenter::notifyEvent(long EventCode, LONG_PTR Param1, LONG_PTR Param2)
{
if (m_mediaEventSink)
m_mediaEventSink->Notify(EventCode, Param1, Param2);
}
HRESULT MediaPlayerPrivateMediaFoundation::VideoSamplePool::getSample(COMPtr<IMFSample>& sample)
{
LockHolder locker(m_lock);
if (!m_initialized)
return MF_E_NOT_INITIALIZED;
if (m_videoSampleQueue.isEmpty())
return MF_E_SAMPLEALLOCATOR_EMPTY;
sample = m_videoSampleQueue.takeFirst();
m_pending++;
return S_OK;
}
HRESULT MediaPlayerPrivateMediaFoundation::VideoSamplePool::returnSample(IMFSample* sample)
{
if (!sample)
return E_POINTER;
LockHolder locker(m_lock);
if (!m_initialized)
return MF_E_NOT_INITIALIZED;
m_videoSampleQueue.append(sample);
m_pending--;
return S_OK;
}
bool MediaPlayerPrivateMediaFoundation::VideoSamplePool::areSamplesPending()
{
LockHolder locker(m_lock);
if (!m_initialized)
return FALSE;
return (m_pending > 0);
}
HRESULT MediaPlayerPrivateMediaFoundation::VideoSamplePool::initialize(VideoSampleList& samples)
{
LockHolder locker(m_lock);
if (m_initialized)
return MF_E_INVALIDREQUEST;
// Copy the samples
for (auto sample : samples)
m_videoSampleQueue.append(sample);
m_initialized = true;
samples.clear();
return S_OK;
}
void MediaPlayerPrivateMediaFoundation::VideoSamplePool::clear()
{
LockHolder locker(m_lock);
m_videoSampleQueue.clear();
m_initialized = false;
m_pending = 0;
}
// Scheduler thread messages.
enum ScheduleEvent {
EventTerminate = WM_USER,
EventSchedule,
EventFlush
};
void MediaPlayerPrivateMediaFoundation::VideoScheduler::setFrameRate(const MFRatio& fps)
{
UINT64 avgTimePerFrame = 0;
MFFrameRateToAverageTimePerFramePtr()(fps.Numerator, fps.Denominator, &avgTimePerFrame);
m_frameDuration = (MFTIME)avgTimePerFrame;
}
HRESULT MediaPlayerPrivateMediaFoundation::VideoScheduler::startScheduler(IMFClock* clock)
{
if (m_schedulerThread.isValid())
return E_UNEXPECTED;
HRESULT hr = S_OK;
m_clock = clock;
// Use high timer resolution.
timeBeginPeriod(1);
// Create an event to signal that the scheduler thread has started.
m_threadReadyEvent = ::CreateEvent(nullptr, FALSE, FALSE, nullptr);
if (!m_threadReadyEvent.isValid())
return HRESULT_FROM_WIN32(GetLastError());
// Create an event to signal that the flush has completed.
m_flushEvent = ::CreateEvent(nullptr, FALSE, FALSE, nullptr);
if (!m_flushEvent.isValid())
return HRESULT_FROM_WIN32(GetLastError());
// Start scheduler thread.
DWORD threadID = 0;
m_schedulerThread = ::CreateThread(nullptr, 0, schedulerThreadProc, (LPVOID)this, 0, &threadID);
if (!m_schedulerThread.isValid())
return HRESULT_FROM_WIN32(GetLastError());
HANDLE hObjects[] = { m_threadReadyEvent.get(), m_schedulerThread.get() };
// Wait for the thread to start
DWORD result = ::WaitForMultipleObjects(2, hObjects, FALSE, INFINITE);
if (WAIT_OBJECT_0 != result) {
// The thread has terminated.
m_schedulerThread.clear();
return E_UNEXPECTED;
}
m_threadID = threadID;
return hr;
}
HRESULT MediaPlayerPrivateMediaFoundation::VideoScheduler::stopScheduler()
{
if (!m_schedulerThread.isValid())
return S_OK;
// Terminate the scheduler thread
stopThread();
::PostThreadMessage(m_threadID, EventTerminate, 0, 0);
// Wait for the scheduler thread to finish.
::WaitForSingleObject(m_schedulerThread.get(), INFINITE);
LockHolder locker(m_lock);
m_scheduledSamples.clear();
m_schedulerThread.clear();
m_flushEvent.clear();
// Clear previously set timer resolution.
timeEndPeriod(1);
return S_OK;
}
HRESULT MediaPlayerPrivateMediaFoundation::VideoScheduler::flush()
{
// This method will wait for the flush to finish on the worker thread.
if (m_schedulerThread.isValid()) {
::PostThreadMessage(m_threadID, EventFlush, 0, 0);
HANDLE objects[] = { m_flushEvent.get(), m_schedulerThread.get() };
const int schedulerTimeout = 5000;
// Wait for the flush to finish or the thread to terminate.
::WaitForMultipleObjects(2, objects, FALSE, schedulerTimeout);
}
return S_OK;
}
HRESULT MediaPlayerPrivateMediaFoundation::VideoScheduler::scheduleSample(IMFSample* sample, bool presentNow)
{
if (!sample)
return E_POINTER;
if (!m_presenter)
return MF_E_NOT_INITIALIZED;
if (!m_schedulerThread.isValid())
return MF_E_NOT_INITIALIZED;
DWORD exitCode = 0;
::GetExitCodeThread(m_schedulerThread.get(), &exitCode);
if (exitCode != STILL_ACTIVE)
return E_FAIL;
if (presentNow || !m_clock)
m_presenter->presentSample(sample, 0);
else {
// Submit the sample for scheduling.
LockHolder locker(m_lock);
m_scheduledSamples.append(sample);
::PostThreadMessage(m_threadID, EventSchedule, 0, 0);
}
return S_OK;
}
HRESULT MediaPlayerPrivateMediaFoundation::VideoScheduler::processSamplesInQueue(LONG& nextSleep)
{
HRESULT hr = S_OK;
LONG wait = 0;
// Process samples as long as there are samples in the queue, and they have not arrived too early.
while (!m_exitThread) {
COMPtr<IMFSample> sample;
if (true) {
LockHolder locker(m_lock);
if (m_scheduledSamples.isEmpty())
break;
sample = m_scheduledSamples.takeFirst();
}
// Process the sample.
// If the sample has arrived too early, wait will be > 0,
// and the scheduler should go to sleep.
hr = processSample(sample.get(), wait);
if (FAILED(hr))
break;
if (wait > 0)
break;
}
if (!wait) {
// The queue is empty. Sleep until the next message arrives.
wait = INFINITE;
}
nextSleep = wait;
return hr;
}
// MFTimeToMilliseconds: Convert 100-nanosecond time to milliseconds.
static LONG MFTimeToMilliseconds(const LONGLONG& time)
{
return (time / 10000);
}
HRESULT MediaPlayerPrivateMediaFoundation::VideoScheduler::processSample(IMFSample* sample, LONG& nextSleep)
{
if (!sample)
return E_POINTER;
HRESULT hr = S_OK;
LONGLONG presentationTime = 0;
LONGLONG timeNow = 0;
MFTIME systemTime = 0;
bool presentNow = true;
LONG nextSleepTime = 0;
if (m_clock) {
// Get the time stamp of the sample.
// A sample can possibly have no time stamp.
hr = sample->GetSampleTime(&presentationTime);
// Get the clock time.
// If the sample does not have a time stamp, the clock time is not needed.
if (SUCCEEDED(hr))
hr = m_clock->GetCorrelatedTime(0, &timeNow, &systemTime);
// Determine the time until the sample should be presented.
// Samples arriving late, will have negative values.
LONGLONG timeDelta = presentationTime - timeNow;
if (m_playbackRate < 0) {
// Reverse delta for reverse playback.
timeDelta = -timeDelta;
}
LONGLONG frameDurationOneFourth = m_frameDuration / 4;
if (timeDelta < -frameDurationOneFourth) {
// The sample has arrived late.
presentNow = true;
} else if (timeDelta > (3 * frameDurationOneFourth)) {
// We can sleep, the sample has arrived too early.
nextSleepTime = MFTimeToMilliseconds(timeDelta - (3 * frameDurationOneFourth));
// Since sleeping is using the system clock, we need to convert the sleep time
// from presentation time to system time.
nextSleepTime = (LONG)(nextSleepTime / fabsf(m_playbackRate));
presentNow = false;
}
}
if (presentNow)
hr = m_presenter->presentSample(sample, presentationTime);
else {
// Return the sample to the queue, since it is not ready.
LockHolder locker(m_lock);
m_scheduledSamples.prepend(sample);
}
nextSleep = nextSleepTime;
return hr;
}
DWORD WINAPI MediaPlayerPrivateMediaFoundation::VideoScheduler::schedulerThreadProc(LPVOID lpParameter)
{
VideoScheduler* scheduler = reinterpret_cast<VideoScheduler*>(lpParameter);
if (!scheduler)
return static_cast<DWORD>(-1);
return scheduler->schedulerThreadProcPrivate();
}
DWORD MediaPlayerPrivateMediaFoundation::VideoScheduler::schedulerThreadProcPrivate()
{
HRESULT hr = S_OK;
// This will force a message queue to be created for the thread.
MSG msg;
PeekMessage(&msg, nullptr, WM_USER, WM_USER, PM_NOREMOVE);
// The thread is ready.
SetEvent(m_threadReadyEvent.get());
LONG wait = INFINITE;
m_exitThread = false;
while (!m_exitThread) {
// Wait for messages
DWORD result = MsgWaitForMultipleObjects(0, nullptr, FALSE, wait, QS_POSTMESSAGE);
if (result == WAIT_TIMEOUT) {
hr = processSamplesInQueue(wait);
if (FAILED(hr))
m_exitThread = true;
}
while (PeekMessage(&msg, nullptr, 0, 0, PM_REMOVE)) {
bool processSamples = true;
switch (msg.message) {
case EventTerminate:
m_exitThread = true;
break;
case EventFlush:
{
LockHolder lock(m_lock);
m_scheduledSamples.clear();
}
wait = INFINITE;
SetEvent(m_flushEvent.get());
break;
case EventSchedule:
if (processSamples) {
hr = processSamplesInQueue(wait);
if (FAILED(hr))
m_exitThread = true;
processSamples = (wait != INFINITE);
}
break;
}
}
}
return (SUCCEEDED(hr) ? 0 : 1);
}
static HRESULT findAdapter(IDirect3D9* direct3D9, HMONITOR monitor, UINT& adapterID)
{
HRESULT hr = E_FAIL;
UINT adapterCount = direct3D9->GetAdapterCount();
for (UINT i = 0; i < adapterCount; i++) {
HMONITOR monitorTmp = direct3D9->GetAdapterMonitor(i);
if (!monitorTmp)
break;
if (monitorTmp == monitor) {
adapterID = i;
hr = S_OK;
break;
}
}
return hr;
}
MediaPlayerPrivateMediaFoundation::Direct3DPresenter::Direct3DPresenter()
{
SetRectEmpty(&m_destRect);
ZeroMemory(&m_displayMode, sizeof(m_displayMode));
HRESULT hr = initializeD3D();
if (FAILED(hr))
return;
createD3DDevice();
}
MediaPlayerPrivateMediaFoundation::Direct3DPresenter::~Direct3DPresenter()
{
}
HRESULT MediaPlayerPrivateMediaFoundation::Direct3DPresenter::getService(REFGUID guidService, REFIID riid, void** ppv)
{
ASSERT(ppv);
HRESULT hr = S_OK;
if (riid == __uuidof(IDirect3DDeviceManager9)) {
if (!m_deviceManager)
hr = MF_E_UNSUPPORTED_SERVICE;
else {
*ppv = m_deviceManager.get();
m_deviceManager->AddRef();
}
} else
hr = MF_E_UNSUPPORTED_SERVICE;
return hr;
}
HRESULT MediaPlayerPrivateMediaFoundation::Direct3DPresenter::checkFormat(D3DFORMAT format)
{
HRESULT hr = S_OK;
UINT adapter = D3DADAPTER_DEFAULT;
D3DDEVTYPE type = D3DDEVTYPE_HAL;
if (m_device) {
D3DDEVICE_CREATION_PARAMETERS params;
hr = m_device->GetCreationParameters(¶ms);
if (FAILED(hr))
return hr;
adapter = params.AdapterOrdinal;
type = params.DeviceType;
}
D3DDISPLAYMODE mode;
hr = m_direct3D9->GetAdapterDisplayMode(adapter, &mode);
if (FAILED(hr))
return hr;
return m_direct3D9->CheckDeviceType(adapter, type, mode.Format, format, TRUE);
}
HRESULT MediaPlayerPrivateMediaFoundation::Direct3DPresenter::setVideoWindow(HWND hwnd)
{
ASSERT(IsWindow(hwnd));
ASSERT(hwnd != m_hwnd);
{
LockHolder locker(m_lock);
m_hwnd = hwnd;
updateDestRect();
}
return createD3DDevice();
}
HRESULT MediaPlayerPrivateMediaFoundation::Direct3DPresenter::setDestinationRect(const RECT& rcDest)
{
if (EqualRect(&rcDest, &m_destRect))
return S_OK;
LockHolder locker(m_lock);
m_destRect = rcDest;
updateDestRect();
return S_OK;
}
HRESULT MediaPlayerPrivateMediaFoundation::Direct3DPresenter::createVideoSamples(IMFMediaType* format, VideoSampleList& videoSampleQueue)
{
// Create video samples matching the supplied format.
// A swap chain with a single back buffer will be created for each video sample.
// The mixer will render to the back buffer through a surface kept by the sample.
// The surface can be rendered to a window by presenting the swap chain.
// In our case the surface is transferred to system memory, and rendered to a graphics context.
if (!m_hwnd)
return MF_E_INVALIDREQUEST;
if (!format)
return MF_E_UNEXPECTED;
LockHolder locker(m_lock);
releaseResources();
D3DPRESENT_PARAMETERS presentParameters;
HRESULT hr = getSwapChainPresentParameters(format, &presentParameters);
if (FAILED(hr)) {
releaseResources();
return hr;
}
updateDestRect();
static const int presenterBufferCount = 3;
for (int i = 0; i < presenterBufferCount; i++) {
COMPtr<IDirect3DSwapChain9> swapChain;
hr = m_device->CreateAdditionalSwapChain(&presentParameters, &swapChain);
if (FAILED(hr)) {
releaseResources();
return hr;
}
COMPtr<IMFSample> videoSample;
hr = createD3DSample(swapChain.get(), videoSample);
if (FAILED(hr)) {
releaseResources();
return hr;
}
videoSampleQueue.append(videoSample);
}
return hr;
}
void MediaPlayerPrivateMediaFoundation::Direct3DPresenter::releaseResources()
{
m_surfaceRepaint = nullptr;
}
HRESULT MediaPlayerPrivateMediaFoundation::Direct3DPresenter::checkDeviceState(DeviceState& state)
{
LockHolder locker(m_lock);
HRESULT hr = m_device->CheckDeviceState(m_hwnd);
state = DeviceOK;
// Not all failure codes are critical.
switch (hr) {
case S_OK:
case S_PRESENT_OCCLUDED:
case S_PRESENT_MODE_CHANGED:
hr = S_OK;
break;
case D3DERR_DEVICELOST:
case D3DERR_DEVICEHUNG:
hr = createD3DDevice();
if (FAILED(hr))
return hr;
state = DeviceReset;
hr = S_OK;
break;
case D3DERR_DEVICEREMOVED:
state = DeviceRemoved;
break;
case E_INVALIDARG:
// This might happen if the window has been destroyed, or is not valid.
// A new device will be created if a new window is set.
hr = S_OK;
}
return hr;
}
HRESULT MediaPlayerPrivateMediaFoundation::Direct3DPresenter::presentSample(IMFSample* sample, LONGLONG targetPresentationTime)
{
HRESULT hr = S_OK;
LockHolder locker(m_lock);
COMPtr<IDirect3DSurface9> surface;
if (sample) {
COMPtr<IMFMediaBuffer> buffer;
hr = sample->GetBufferByIndex(0, &buffer);
hr = MFGetServicePtr()(buffer.get(), MR_BUFFER_SERVICE, __uuidof(IDirect3DSurface9), (void**)&surface);
} else if (m_surfaceRepaint) {
// Use the last surface.
surface = m_surfaceRepaint;
}
if (surface) {
UINT width = m_destRect.right - m_destRect.left;
UINT height = m_destRect.bottom - m_destRect.top;
if (width > 0 && height > 0) {
if (!m_memSurface || m_width != width || m_height != height) {
D3DFORMAT format = D3DFMT_A8R8G8B8;
D3DSURFACE_DESC desc;
if (SUCCEEDED(surface->GetDesc(&desc)))
format = desc.Format;
m_memSurface.clear();
hr = m_device->CreateOffscreenPlainSurface(width, height, format, D3DPOOL_SYSTEMMEM, &m_memSurface, nullptr);
m_width = width;
m_height = height;
}
// Copy data from video memory to system memory
hr = m_device->GetRenderTargetData(surface.get(), m_memSurface.get());
if (FAILED(hr)) {
m_memSurface = nullptr;
hr = S_OK;
}
}
// Since we want to draw to the GraphicsContext provided in the paint method,
// and not draw directly to the window, we skip presenting the swap chain:
// COMPtr<IDirect3DSwapChain9> swapChain;
// hr = surface->GetContainer(__uuidof(IDirect3DSwapChain9), (LPVOID*)&swapChain));
// hr = presentSwapChain(swapChain, surface));
// Keep the last surface for repaints.
m_surfaceRepaint = surface;
}
if (FAILED(hr)) {
if (hr == D3DERR_DEVICELOST || hr == D3DERR_DEVICENOTRESET || hr == D3DERR_DEVICEHUNG) {
// Ignore this error. We have to reset or recreate the device.
// The presenter will handle this when checking the device state the next time.
hr = S_OK;
}
}
return hr;
}
void MediaPlayerPrivateMediaFoundation::Direct3DPresenter::paintCurrentFrame(WebCore::GraphicsContext& context, const WebCore::FloatRect& destRect)
{
UINT width = m_destRect.right - m_destRect.left;
UINT height = m_destRect.bottom - m_destRect.top;
if (!width || !height)
return;
LockHolder locker(m_lock);
if (!m_memSurface)
return;
D3DLOCKED_RECT lockedRect;
if (SUCCEEDED(m_memSurface->LockRect(&lockedRect, nullptr, D3DLOCK_READONLY))) {
void* data = lockedRect.pBits;
int pitch = lockedRect.Pitch;
#if USE(CAIRO)
D3DFORMAT format = D3DFMT_UNKNOWN;
D3DSURFACE_DESC desc;
if (SUCCEEDED(m_memSurface->GetDesc(&desc)))
format = desc.Format;
cairo_format_t cairoFormat = CAIRO_FORMAT_INVALID;
switch (format) {
case D3DFMT_A8R8G8B8:
cairoFormat = CAIRO_FORMAT_ARGB32;
break;
case D3DFMT_X8R8G8B8:
cairoFormat = CAIRO_FORMAT_RGB24;
break;
}
ASSERT(cairoFormat != CAIRO_FORMAT_INVALID);
cairo_surface_t* image = nullptr;
if (cairoFormat != CAIRO_FORMAT_INVALID)
image = cairo_image_surface_create_for_data(static_cast<unsigned char*>(data), cairoFormat, width, height, pitch);
FloatRect srcRect(0, 0, width, height);
if (image) {
WebCore::PlatformContextCairo* ctxt = context.platformContext();
ctxt->drawSurfaceToContext(image, destRect, srcRect, context);
cairo_surface_destroy(image);
}
#elif PLATFORM(QT)
D3DFORMAT format = D3DFMT_UNKNOWN;
D3DSURFACE_DESC desc;
if (SUCCEEDED(m_memSurface->GetDesc(&desc)))
format = desc.Format;
QImage::Format imageFormat = QImage::Format_Invalid;
switch (format) {
case D3DFMT_A8R8G8B8:
imageFormat = QImage::Format_ARGB32_Premultiplied;
break;
case D3DFMT_X8R8G8B8:
imageFormat = QImage::Format_RGB32;
break;
}
ASSERT(imageFormat != QImage::Format_Invalid);
QImage image(static_cast<unsigned char*>(data), width, height, pitch, imageFormat);
FloatRect srcRect(0, 0, width, height);
QPainter* p = context.platformContext();
p->drawImage(destRect, image, srcRect);
#else
#error "Platform needs to implement drawing of Direct3D surface to graphics context!"
#endif
m_memSurface->UnlockRect();
}
}
HRESULT MediaPlayerPrivateMediaFoundation::Direct3DPresenter::initializeD3D()
{
ASSERT(!m_direct3D9);
ASSERT(!m_deviceManager);
HRESULT hr = Direct3DCreate9ExPtr()(D3D_SDK_VERSION, &m_direct3D9);
if (FAILED(hr))
return hr;
return DXVA2CreateDirect3DDeviceManager9Ptr()(&m_deviceResetToken, &m_deviceManager);
}
HRESULT MediaPlayerPrivateMediaFoundation::Direct3DPresenter::createD3DDevice()
{
HRESULT hr = S_OK;
UINT adapterID = D3DADAPTER_DEFAULT;
LockHolder locker(m_lock);
if (!m_direct3D9 || !m_deviceManager)
return MF_E_NOT_INITIALIZED;
HWND hwnd = GetDesktopWindow();
// We create additional swap chains to present the video frames,
// and do not use the implicit swap chain of the device.
// The size of the back buffer is 1 x 1.
D3DPRESENT_PARAMETERS pp;
ZeroMemory(&pp, sizeof(pp));
pp.BackBufferWidth = 1;
pp.BackBufferHeight = 1;
pp.Windowed = TRUE;
pp.SwapEffect = D3DSWAPEFFECT_COPY;
pp.BackBufferFormat = D3DFMT_UNKNOWN;
pp.hDeviceWindow = hwnd;
pp.Flags = D3DPRESENTFLAG_VIDEO;
pp.PresentationInterval = D3DPRESENT_INTERVAL_DEFAULT;
if (m_hwnd) {
HMONITOR monitor = MonitorFromWindow(m_hwnd, MONITOR_DEFAULTTONEAREST);
hr = findAdapter(m_direct3D9.get(), monitor, adapterID);
if (FAILED(hr))
return hr;
}
D3DCAPS9 ddCaps;
ZeroMemory(&ddCaps, sizeof(ddCaps));
hr = m_direct3D9->GetDeviceCaps(adapterID, D3DDEVTYPE_HAL, &ddCaps);
if (FAILED(hr))
return hr;
DWORD flags = D3DCREATE_NOWINDOWCHANGES | D3DCREATE_MULTITHREADED | D3DCREATE_FPU_PRESERVE;
if (ddCaps.DevCaps & D3DDEVCAPS_HWTRANSFORMANDLIGHT)
flags |= D3DCREATE_HARDWARE_VERTEXPROCESSING;
else
flags |= D3DCREATE_SOFTWARE_VERTEXPROCESSING;
COMPtr<IDirect3DDevice9Ex> device;
hr = m_direct3D9->CreateDeviceEx(adapterID, D3DDEVTYPE_HAL, pp.hDeviceWindow, flags, &pp, nullptr, &device);
if (FAILED(hr))
return hr;
hr = m_direct3D9->GetAdapterDisplayMode(adapterID, &m_displayMode);
if (FAILED(hr))
return hr;
hr = m_deviceManager->ResetDevice(device.get(), m_deviceResetToken);
if (FAILED(hr))
return hr;
m_device = device;
return hr;
}
HRESULT MediaPlayerPrivateMediaFoundation::Direct3DPresenter::createD3DSample(IDirect3DSwapChain9* swapChain, COMPtr<IMFSample>& videoSample)
{
COMPtr<IDirect3DSurface9> surface;
HRESULT hr = swapChain->GetBackBuffer(0, D3DBACKBUFFER_TYPE_MONO, &surface);
if (FAILED(hr))
return hr;
D3DCOLOR colorBlack = D3DCOLOR_ARGB(0xFF, 0x00, 0x00, 0x00);
hr = m_device->ColorFill(surface.get(), nullptr, colorBlack);
if (FAILED(hr))
return hr;
return MFCreateVideoSampleFromSurfacePtr()(surface.get(), &videoSample);
}
HRESULT MediaPlayerPrivateMediaFoundation::Direct3DPresenter::presentSwapChain(IDirect3DSwapChain9* swapChain, IDirect3DSurface9* surface)
{
if (!m_hwnd)
return MF_E_INVALIDREQUEST;
return swapChain->Present(nullptr, &m_destRect, m_hwnd, nullptr, 0);
}
HRESULT MediaPlayerPrivateMediaFoundation::Direct3DPresenter::getSwapChainPresentParameters(IMFMediaType* type, D3DPRESENT_PARAMETERS* presentParams)
{
if (!m_hwnd)
return MF_E_INVALIDREQUEST;
COMPtr<IMFMediaType> videoType = type;
UINT32 width = 0, height = 0;
HRESULT hr = MFGetAttributeSize(videoType.get(), MF_MT_FRAME_SIZE, &width, &height);
if (FAILED(hr))
return hr;
GUID guidSubType = GUID_NULL;
hr = videoType->GetGUID(MF_MT_SUBTYPE, &guidSubType);
if (FAILED(hr))
return hr;
DWORD d3dFormat = guidSubType.Data1;
ZeroMemory(presentParams, sizeof(D3DPRESENT_PARAMETERS));
presentParams->BackBufferWidth = width;
presentParams->BackBufferHeight = height;
presentParams->Windowed = TRUE;
presentParams->SwapEffect = D3DSWAPEFFECT_COPY;
presentParams->BackBufferFormat = (D3DFORMAT)d3dFormat;
presentParams->hDeviceWindow = m_hwnd;
presentParams->Flags = D3DPRESENTFLAG_VIDEO;
presentParams->PresentationInterval = D3DPRESENT_INTERVAL_DEFAULT;
D3DDEVICE_CREATION_PARAMETERS params;
hr = m_device->GetCreationParameters(¶ms);
if (FAILED(hr))
return hr;
if (params.DeviceType != D3DDEVTYPE_HAL)
presentParams->Flags |= D3DPRESENTFLAG_LOCKABLE_BACKBUFFER;
return S_OK;
}
HRESULT MediaPlayerPrivateMediaFoundation::Direct3DPresenter::updateDestRect()
{
if (!m_hwnd)
return S_FALSE;
RECT rcView;
if (!GetClientRect(m_hwnd, &rcView))
return E_FAIL;
// Clip to the client area of the window.
if (m_destRect.right > rcView.right)
m_destRect.right = rcView.right;
if (m_destRect.bottom > rcView.bottom)
m_destRect.bottom = rcView.bottom;
return S_OK;
}
} // namespace WebCore
#endif
|