cap_msmf.hpp 99.4 KB
Newer Older
wester committed
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
#ifdef WINRT
#define ICustomStreamSink StreamSink
#ifndef __cplusplus_winrt
#include "wrl.h"
#endif
#else
EXTERN_C const IID IID_ICustomStreamSink;

class DECLSPEC_UUID("4F8A1939-2FD3-46DB-AE70-DB7E0DD79B73") DECLSPEC_NOVTABLE ICustomStreamSink : public IUnknown
{
public:
    virtual HRESULT Initialize() = 0;
    virtual HRESULT Shutdown() = 0;
    virtual HRESULT Start(MFTIME start) = 0;
    virtual HRESULT Pause() = 0;
    virtual HRESULT Restart() = 0;
    virtual HRESULT Stop() = 0;
};
#endif

#define MF_PROP_SAMPLEGRABBERCALLBACK L"samplegrabbercallback"
#define MF_PROP_VIDTYPE L"vidtype"
#define MF_PROP_VIDENCPROPS L"videncprops"

#include <initguid.h>

// MF_MEDIASINK_SAMPLEGRABBERCALLBACK: {26957AA7-AFF4-464c-BB8B-07BA65CE11DF}
// Type: IUnknown*
DEFINE_GUID(MF_MEDIASINK_SAMPLEGRABBERCALLBACK,
            0x26957aa7, 0xaff4, 0x464c, 0xbb, 0x8b, 0x7, 0xba, 0x65, 0xce, 0x11, 0xdf);

// {4BD133CC-EB9B-496E-8865-0813BFBC6FAA}
DEFINE_GUID(MF_STREAMSINK_ID, 0x4bd133cc, 0xeb9b, 0x496e, 0x88, 0x65, 0x8, 0x13, 0xbf, 0xbc, 0x6f, 0xaa);

// {C9E22A8C-6A50-4D78-9183-0834A02A3780}
DEFINE_GUID(MF_STREAMSINK_MEDIASINKINTERFACE,
    0xc9e22a8c, 0x6a50, 0x4d78, 0x91, 0x83, 0x8, 0x34, 0xa0, 0x2a, 0x37, 0x80);

// {DABD13AB-26B7-47C2-97C1-4B04C187B838}
DEFINE_GUID(MF_MEDIASINK_PREFERREDTYPE,
    0xdabd13ab, 0x26b7, 0x47c2, 0x97, 0xc1, 0x4b, 0x4, 0xc1, 0x87, 0xb8, 0x38);

#include <utility>
#ifdef _UNICODE
#define MAKE_MAP(e) std::map<e, std::wstring>
#define MAKE_ENUM(e) std::pair<e, std::wstring>
#define MAKE_ENUM_PAIR(e, str) std::pair<e, std::wstring>(str, L#str)
#else
#define MAKE_MAP(e) std::map<e, std::string>
#define MAKE_ENUM(e) std::pair<e, std::string>
#define MAKE_ENUM_PAIR(e, str) std::pair<e, std::string>(str, #str)
#endif

MAKE_ENUM(MediaEventType) MediaEventTypePairs[] = {
    MAKE_ENUM_PAIR(MediaEventType, MEUnknown),
    MAKE_ENUM_PAIR(MediaEventType, MEError),
    MAKE_ENUM_PAIR(MediaEventType, MEExtendedType),
    MAKE_ENUM_PAIR(MediaEventType, MENonFatalError),
    MAKE_ENUM_PAIR(MediaEventType, MEGenericV1Anchor),
    MAKE_ENUM_PAIR(MediaEventType, MESessionUnknown),
    MAKE_ENUM_PAIR(MediaEventType, MESessionTopologySet),
    MAKE_ENUM_PAIR(MediaEventType, MESessionTopologiesCleared),
    MAKE_ENUM_PAIR(MediaEventType, MESessionStarted),
    MAKE_ENUM_PAIR(MediaEventType, MESessionPaused),
    MAKE_ENUM_PAIR(MediaEventType, MESessionStopped),
    MAKE_ENUM_PAIR(MediaEventType, MESessionClosed),
    MAKE_ENUM_PAIR(MediaEventType, MESessionEnded),
    MAKE_ENUM_PAIR(MediaEventType, MESessionRateChanged),
    MAKE_ENUM_PAIR(MediaEventType, MESessionScrubSampleComplete),
    MAKE_ENUM_PAIR(MediaEventType, MESessionCapabilitiesChanged),
    MAKE_ENUM_PAIR(MediaEventType, MESessionTopologyStatus),
    MAKE_ENUM_PAIR(MediaEventType, MESessionNotifyPresentationTime),
    MAKE_ENUM_PAIR(MediaEventType, MENewPresentation),
    MAKE_ENUM_PAIR(MediaEventType, MELicenseAcquisitionStart),
    MAKE_ENUM_PAIR(MediaEventType, MELicenseAcquisitionCompleted),
    MAKE_ENUM_PAIR(MediaEventType, MEIndividualizationStart),
    MAKE_ENUM_PAIR(MediaEventType, MEIndividualizationCompleted),
    MAKE_ENUM_PAIR(MediaEventType, MEEnablerProgress),
    MAKE_ENUM_PAIR(MediaEventType, MEEnablerCompleted),
    MAKE_ENUM_PAIR(MediaEventType, MEPolicyError),
    MAKE_ENUM_PAIR(MediaEventType, MEPolicyReport),
    MAKE_ENUM_PAIR(MediaEventType, MEBufferingStarted),
    MAKE_ENUM_PAIR(MediaEventType, MEBufferingStopped),
    MAKE_ENUM_PAIR(MediaEventType, MEConnectStart),
    MAKE_ENUM_PAIR(MediaEventType, MEConnectEnd),
    MAKE_ENUM_PAIR(MediaEventType, MEReconnectStart),
    MAKE_ENUM_PAIR(MediaEventType, MEReconnectEnd),
    MAKE_ENUM_PAIR(MediaEventType, MERendererEvent),
    MAKE_ENUM_PAIR(MediaEventType, MESessionStreamSinkFormatChanged),
    MAKE_ENUM_PAIR(MediaEventType, MESessionV1Anchor),
    MAKE_ENUM_PAIR(MediaEventType, MESourceUnknown),
    MAKE_ENUM_PAIR(MediaEventType, MESourceStarted),
    MAKE_ENUM_PAIR(MediaEventType, MEStreamStarted),
    MAKE_ENUM_PAIR(MediaEventType, MESourceSeeked),
    MAKE_ENUM_PAIR(MediaEventType, MEStreamSeeked),
    MAKE_ENUM_PAIR(MediaEventType, MENewStream),
    MAKE_ENUM_PAIR(MediaEventType, MEUpdatedStream),
    MAKE_ENUM_PAIR(MediaEventType, MESourceStopped),
    MAKE_ENUM_PAIR(MediaEventType, MEStreamStopped),
    MAKE_ENUM_PAIR(MediaEventType, MESourcePaused),
    MAKE_ENUM_PAIR(MediaEventType, MEStreamPaused),
    MAKE_ENUM_PAIR(MediaEventType, MEEndOfPresentation),
    MAKE_ENUM_PAIR(MediaEventType, MEEndOfStream),
    MAKE_ENUM_PAIR(MediaEventType, MEMediaSample),
    MAKE_ENUM_PAIR(MediaEventType, MEStreamTick),
    MAKE_ENUM_PAIR(MediaEventType, MEStreamThinMode),
    MAKE_ENUM_PAIR(MediaEventType, MEStreamFormatChanged),
    MAKE_ENUM_PAIR(MediaEventType, MESourceRateChanged),
    MAKE_ENUM_PAIR(MediaEventType, MEEndOfPresentationSegment),
    MAKE_ENUM_PAIR(MediaEventType, MESourceCharacteristicsChanged),
    MAKE_ENUM_PAIR(MediaEventType, MESourceRateChangeRequested),
    MAKE_ENUM_PAIR(MediaEventType, MESourceMetadataChanged),
    MAKE_ENUM_PAIR(MediaEventType, MESequencerSourceTopologyUpdated),
    MAKE_ENUM_PAIR(MediaEventType, MESourceV1Anchor),
    MAKE_ENUM_PAIR(MediaEventType, MESinkUnknown),
    MAKE_ENUM_PAIR(MediaEventType, MEStreamSinkStarted),
    MAKE_ENUM_PAIR(MediaEventType, MEStreamSinkStopped),
    MAKE_ENUM_PAIR(MediaEventType, MEStreamSinkPaused),
    MAKE_ENUM_PAIR(MediaEventType, MEStreamSinkRateChanged),
    MAKE_ENUM_PAIR(MediaEventType, MEStreamSinkRequestSample),
    MAKE_ENUM_PAIR(MediaEventType, MEStreamSinkMarker),
    MAKE_ENUM_PAIR(MediaEventType, MEStreamSinkPrerolled),
    MAKE_ENUM_PAIR(MediaEventType, MEStreamSinkScrubSampleComplete),
    MAKE_ENUM_PAIR(MediaEventType, MEStreamSinkFormatChanged),
    MAKE_ENUM_PAIR(MediaEventType, MEStreamSinkDeviceChanged),
    MAKE_ENUM_PAIR(MediaEventType, MEQualityNotify),
    MAKE_ENUM_PAIR(MediaEventType, MESinkInvalidated),
    MAKE_ENUM_PAIR(MediaEventType, MEAudioSessionNameChanged),
    MAKE_ENUM_PAIR(MediaEventType, MEAudioSessionVolumeChanged),
    MAKE_ENUM_PAIR(MediaEventType, MEAudioSessionDeviceRemoved),
    MAKE_ENUM_PAIR(MediaEventType, MEAudioSessionServerShutdown),
    MAKE_ENUM_PAIR(MediaEventType, MEAudioSessionGroupingParamChanged),
    MAKE_ENUM_PAIR(MediaEventType, MEAudioSessionIconChanged),
    MAKE_ENUM_PAIR(MediaEventType, MEAudioSessionFormatChanged),
    MAKE_ENUM_PAIR(MediaEventType, MEAudioSessionDisconnected),
    MAKE_ENUM_PAIR(MediaEventType, MEAudioSessionExclusiveModeOverride),
    MAKE_ENUM_PAIR(MediaEventType, MESinkV1Anchor),
#if (WINVER >= 0x0602) // Available since Win 8
    MAKE_ENUM_PAIR(MediaEventType, MECaptureAudioSessionVolumeChanged),
    MAKE_ENUM_PAIR(MediaEventType, MECaptureAudioSessionDeviceRemoved),
    MAKE_ENUM_PAIR(MediaEventType, MECaptureAudioSessionFormatChanged),
    MAKE_ENUM_PAIR(MediaEventType, MECaptureAudioSessionDisconnected),
    MAKE_ENUM_PAIR(MediaEventType, MECaptureAudioSessionExclusiveModeOverride),
    MAKE_ENUM_PAIR(MediaEventType, MECaptureAudioSessionServerShutdown),
    MAKE_ENUM_PAIR(MediaEventType, MESinkV2Anchor),
#endif
    MAKE_ENUM_PAIR(MediaEventType, METrustUnknown),
    MAKE_ENUM_PAIR(MediaEventType, MEPolicyChanged),
    MAKE_ENUM_PAIR(MediaEventType, MEContentProtectionMessage),
    MAKE_ENUM_PAIR(MediaEventType, MEPolicySet),
    MAKE_ENUM_PAIR(MediaEventType, METrustV1Anchor),
    MAKE_ENUM_PAIR(MediaEventType, MEWMDRMLicenseBackupCompleted),
    MAKE_ENUM_PAIR(MediaEventType, MEWMDRMLicenseBackupProgress),
    MAKE_ENUM_PAIR(MediaEventType, MEWMDRMLicenseRestoreCompleted),
    MAKE_ENUM_PAIR(MediaEventType, MEWMDRMLicenseRestoreProgress),
    MAKE_ENUM_PAIR(MediaEventType, MEWMDRMLicenseAcquisitionCompleted),
    MAKE_ENUM_PAIR(MediaEventType, MEWMDRMIndividualizationCompleted),
    MAKE_ENUM_PAIR(MediaEventType, MEWMDRMIndividualizationProgress),
    MAKE_ENUM_PAIR(MediaEventType, MEWMDRMProximityCompleted),
    MAKE_ENUM_PAIR(MediaEventType, MEWMDRMLicenseStoreCleaned),
    MAKE_ENUM_PAIR(MediaEventType, MEWMDRMRevocationDownloadCompleted),
    MAKE_ENUM_PAIR(MediaEventType, MEWMDRMV1Anchor),
    MAKE_ENUM_PAIR(MediaEventType, METransformUnknown),
    MAKE_ENUM_PAIR(MediaEventType, METransformNeedInput),
    MAKE_ENUM_PAIR(MediaEventType, METransformHaveOutput),
    MAKE_ENUM_PAIR(MediaEventType, METransformDrainComplete),
    MAKE_ENUM_PAIR(MediaEventType, METransformMarker),
#if (WINVER >= 0x0602) // Available since Win 8
    MAKE_ENUM_PAIR(MediaEventType, MEByteStreamCharacteristicsChanged),
    MAKE_ENUM_PAIR(MediaEventType, MEVideoCaptureDeviceRemoved),
    MAKE_ENUM_PAIR(MediaEventType, MEVideoCaptureDevicePreempted),
#endif
    MAKE_ENUM_PAIR(MediaEventType, MEReservedMax)
};
MAKE_MAP(MediaEventType) MediaEventTypeMap(MediaEventTypePairs, MediaEventTypePairs + sizeof(MediaEventTypePairs) / sizeof(MediaEventTypePairs[0]));

MAKE_ENUM(MFSTREAMSINK_MARKER_TYPE) StreamSinkMarkerTypePairs[] = {
    MAKE_ENUM_PAIR(MFSTREAMSINK_MARKER_TYPE, MFSTREAMSINK_MARKER_DEFAULT),
    MAKE_ENUM_PAIR(MFSTREAMSINK_MARKER_TYPE, MFSTREAMSINK_MARKER_ENDOFSEGMENT),
    MAKE_ENUM_PAIR(MFSTREAMSINK_MARKER_TYPE, MFSTREAMSINK_MARKER_TICK),
    MAKE_ENUM_PAIR(MFSTREAMSINK_MARKER_TYPE, MFSTREAMSINK_MARKER_EVENT)
};
MAKE_MAP(MFSTREAMSINK_MARKER_TYPE) StreamSinkMarkerTypeMap(StreamSinkMarkerTypePairs, StreamSinkMarkerTypePairs + sizeof(StreamSinkMarkerTypePairs) / sizeof(StreamSinkMarkerTypePairs[0]));

#ifdef WINRT

#ifdef __cplusplus_winrt
#define _ContextCallback Concurrency::details::_ContextCallback
#define BEGIN_CALL_IN_CONTEXT(hr, var, ...) hr = S_OK;\
    var._CallInContext([__VA_ARGS__]() {
#define END_CALL_IN_CONTEXT(hr) if (FAILED(hr)) throw Platform::Exception::CreateException(hr);\
});
#define END_CALL_IN_CONTEXT_BASE });
#else
#define _ContextCallback Concurrency_winrt::details::_ContextCallback
#define BEGIN_CALL_IN_CONTEXT(hr, var, ...) hr = var._CallInContext([__VA_ARGS__]() -> HRESULT {
#define END_CALL_IN_CONTEXT(hr) return hr;\
});
#define END_CALL_IN_CONTEXT_BASE return S_OK;\
});
#endif
#define GET_CURRENT_CONTEXT _ContextCallback::_CaptureCurrent()
#define SAVE_CURRENT_CONTEXT(var) _ContextCallback var = GET_CURRENT_CONTEXT

#define COMMA ,

#ifdef __cplusplus_winrt
#define _Object Platform::Object^
#define _ObjectObj Platform::Object^
#define _String Platform::String^
#define _StringObj Platform::String^
#define _StringReference ref new Platform::String
#define _StringReferenceObj Platform::String^
#define _DeviceInformationCollection Windows::Devices::Enumeration::DeviceInformationCollection
#define _MediaCapture Windows::Media::Capture::MediaCapture
#define _MediaCaptureVideoPreview Windows::Media::Capture::MediaCapture
#define _MediaCaptureInitializationSettings Windows::Media::Capture::MediaCaptureInitializationSettings
#define _VideoDeviceController Windows::Media::Devices::VideoDeviceController
#define _MediaDeviceController Windows::Media::Devices::VideoDeviceController
#define _MediaEncodingProperties Windows::Media::MediaProperties::IMediaEncodingProperties
#define _VideoEncodingProperties Windows::Media::MediaProperties::VideoEncodingProperties
#define _MediaStreamType Windows::Media::Capture::MediaStreamType
#define _AsyncInfo Windows::Foundation::IAsyncInfo
#define _AsyncAction Windows::Foundation::IAsyncAction
#define _AsyncOperation Windows::Foundation::IAsyncOperation
#define _DeviceClass Windows::Devices::Enumeration::DeviceClass
#define _IDeviceInformation Windows::Devices::Enumeration::DeviceInformation
#define _DeviceInformation Windows::Devices::Enumeration::DeviceInformation
#define _DeviceInformationStatics Windows::Devices::Enumeration::DeviceInformation
#define _MediaEncodingProfile Windows::Media::MediaProperties::MediaEncodingProfile
#define _StreamingCaptureMode Windows::Media::Capture::StreamingCaptureMode
#define _PropertySet Windows::Foundation::Collections::PropertySet
#define _Map Windows::Foundation::Collections::PropertySet
#define _PropertyValueStatics Windows::Foundation::PropertyValue
#define _VectorView Windows::Foundation::Collections::IVectorView
#define _StartPreviewToCustomSinkIdAsync StartPreviewToCustomSinkAsync
#define _InitializeWithSettingsAsync InitializeAsync
#define _FindAllAsyncDeviceClass FindAllAsync
#define _MediaExtension Windows::Media::IMediaExtension
#define BEGIN_CREATE_ASYNC(type, ...) (Concurrency::create_async([__VA_ARGS__]() {
#define END_CREATE_ASYNC(hr) if (FAILED(hr)) throw Platform::Exception::CreateException(hr);\
}))
#define DEFINE_TASK Concurrency::task
#define CREATE_TASK Concurrency::create_task
#define CREATE_OR_CONTINUE_TASK(_task, rettype, func) _task = (_task == Concurrency::task<rettype>()) ? Concurrency::create_task(func) : _task.then([func](rettype) -> rettype { return func(); });
#define DEFINE_RET_VAL(x)
#define DEFINE_RET_TYPE(x)
#define DEFINE_RET_FORMAL(x) x
#define RET_VAL(x) return x;
#define RET_VAL_BASE
#define MAKE_STRING(str) str
#define GET_STL_STRING(str) std::wstring(str->Data())
#define GET_STL_STRING_RAW(str) std::wstring(str->Data())
#define MAKE_WRL_OBJ(x) x^
#define MAKE_WRL_REF(x) x^
#define MAKE_OBJ_REF(x) x^
#define MAKE_WRL_AGILE_REF(x) Platform::Agile<x^>
#define MAKE_PROPERTY_BACKING(Type, PropName) property Type PropName;
#define MAKE_PROPERTY(Type, PropName, PropValue)
#define MAKE_PROPERTY_STRING(Type, PropName, PropValue)
#define MAKE_READONLY_PROPERTY(Type, PropName, PropValue) property Type PropName\
{\
    Type get() { return PropValue; }\
}
#define THROW_INVALID_ARG throw ref new Platform::InvalidArgumentException();
#define RELEASE_AGILE_WRL(x) x = nullptr;
#define RELEASE_WRL(x) x = nullptr;
#define GET_WRL_OBJ_FROM_REF(objtype, obj, orig, hr) objtype^ obj = orig;\
hr = S_OK;
#define GET_WRL_OBJ_FROM_OBJ(objtype, obj, orig, hr) objtype^ obj = safe_cast<objtype^>(orig);\
hr = S_OK;
#define WRL_ENUM_GET(obj, prefix, prop) obj::##prop
#define WRL_PROP_GET(obj, prop, arg, hr) arg = obj->##prop;\
hr = S_OK;
#define WRL_PROP_PUT(obj, prop, arg, hr) obj->##prop = arg;\
hr = S_OK;
#define WRL_METHOD_BASE(obj, method, ret, hr) ret = obj->##method();\
hr = S_OK;
#define WRL_METHOD(obj, method, ret, hr, ...) ret = obj->##method(__VA_ARGS__);\
hr = S_OK;
#define WRL_METHOD_NORET_BASE(obj, method, hr) obj->##method();\
    hr = S_OK;
#define WRL_METHOD_NORET(obj, method, hr, ...) obj->##method(__VA_ARGS__);\
    hr = S_OK;
#define REF_WRL_OBJ(obj) &obj
#define DEREF_WRL_OBJ(obj) obj
#define DEREF_AGILE_WRL_OBJ(obj) obj.Get()
#define DEREF_AS_NATIVE_WRL_OBJ(type, obj) reinterpret_cast<type*>(obj)
#define PREPARE_TRANSFER_WRL_OBJ(obj) obj
#define ACTIVATE_LOCAL_OBJ_BASE(objtype) ref new objtype()
#define ACTIVATE_LOCAL_OBJ(objtype, ...) ref new objtype(__VA_ARGS__)
#define ACTIVATE_EVENT_HANDLER(objtype, ...) ref new objtype(__VA_ARGS__)
#define ACTIVATE_OBJ(rtclass, objtype, obj, hr) MAKE_WRL_OBJ(objtype) obj = ref new objtype();\
hr = S_OK;
#define ACTIVATE_STATIC_OBJ(rtclass, objtype, obj, hr) objtype obj;\
hr = S_OK;
#else
#define _Object IInspectable*
#define _ObjectObj Microsoft::WRL::ComPtr<IInspectable>
#define _String HSTRING
#define _StringObj Microsoft::WRL::Wrappers::HString
#define _StringReference Microsoft::WRL::Wrappers::HStringReference
#define _StringReferenceObj Microsoft::WRL::Wrappers::HStringReference
#define _DeviceInformationCollection ABI::Windows::Devices::Enumeration::DeviceInformationCollection
#define _MediaCapture ABI::Windows::Media::Capture::IMediaCapture
#define _MediaCaptureVideoPreview ABI::Windows::Media::Capture::IMediaCaptureVideoPreview
#define _MediaCaptureInitializationSettings ABI::Windows::Media::Capture::IMediaCaptureInitializationSettings
#define _VideoDeviceController ABI::Windows::Media::Devices::IVideoDeviceController
#define _MediaDeviceController ABI::Windows::Media::Devices::IMediaDeviceController
#define _MediaEncodingProperties ABI::Windows::Media::MediaProperties::IMediaEncodingProperties
#define _VideoEncodingProperties ABI::Windows::Media::MediaProperties::IVideoEncodingProperties
#define _MediaStreamType ABI::Windows::Media::Capture::MediaStreamType
#define _AsyncInfo ABI::Windows::Foundation::IAsyncInfo
#define _AsyncAction ABI::Windows::Foundation::IAsyncAction
#define _AsyncOperation ABI::Windows::Foundation::IAsyncOperation
#define _DeviceClass ABI::Windows::Devices::Enumeration::DeviceClass
#define _IDeviceInformation ABI::Windows::Devices::Enumeration::IDeviceInformation
#define _DeviceInformation ABI::Windows::Devices::Enumeration::DeviceInformation
#define _DeviceInformationStatics ABI::Windows::Devices::Enumeration::IDeviceInformationStatics
#define _MediaEncodingProfile ABI::Windows::Media::MediaProperties::IMediaEncodingProfile
#define _StreamingCaptureMode ABI::Windows::Media::Capture::StreamingCaptureMode
#define _PropertySet ABI::Windows::Foundation::Collections::IPropertySet
#define _Map ABI::Windows::Foundation::Collections::IMap<HSTRING, IInspectable *>
#define _PropertyValueStatics ABI::Windows::Foundation::IPropertyValueStatics
#define _VectorView ABI::Windows::Foundation::Collections::IVectorView
#define _StartPreviewToCustomSinkIdAsync StartPreviewToCustomSinkIdAsync
#define _InitializeWithSettingsAsync InitializeWithSettingsAsync
#define _FindAllAsyncDeviceClass FindAllAsyncDeviceClass
#define _MediaExtension ABI::Windows::Media::IMediaExtension
#define BEGIN_CREATE_ASYNC(type, ...) Concurrency_winrt::create_async<type>([__VA_ARGS__]() -> HRESULT {
#define END_CREATE_ASYNC(hr) return hr;\
})
#define DEFINE_TASK Concurrency_winrt::task
#define CREATE_TASK Concurrency_winrt::create_task
#define CREATE_OR_CONTINUE_TASK(_task, rettype, func) _task = (_task == Concurrency_winrt::task<rettype>()) ? Concurrency_winrt::create_task<rettype>(func) : _task.then([func](rettype, rettype* retVal) -> HRESULT { return func(retVal); });
#define DEFINE_RET_VAL(x) x* retVal
#define DEFINE_RET_TYPE(x) <x>
#define DEFINE_RET_FORMAL(x) HRESULT
#define RET_VAL(x) *retVal = x;\
return S_OK;
#define RET_VAL_BASE return S_OK;
#define MAKE_STRING(str) Microsoft::WRL::Wrappers::HStringReference(L##str)
#define GET_STL_STRING(str) std::wstring(str.GetRawBuffer(NULL))
#define GET_STL_STRING_RAW(str) WindowsGetStringRawBuffer(str, NULL)
#define MAKE_WRL_OBJ(x) Microsoft::WRL::ComPtr<x>
#define MAKE_WRL_REF(x) x*
#define MAKE_OBJ_REF(x) x
#define MAKE_WRL_AGILE_REF(x) x*
#define MAKE_PROPERTY_BACKING(Type, PropName) Type PropName;
#define MAKE_PROPERTY(Type, PropName, PropValue) STDMETHODIMP get_##PropName(Type* pVal) { if (pVal) { *pVal = PropValue; } else { return E_INVALIDARG; } return S_OK; }\
    STDMETHODIMP put_##PropName(Type Val) { PropValue = Val; return S_OK; }
#define MAKE_PROPERTY_STRING(Type, PropName, PropValue) STDMETHODIMP get_##PropName(Type* pVal) { if (pVal) { return ::WindowsDuplicateString(PropValue.Get(), pVal); } else { return E_INVALIDARG; } }\
    STDMETHODIMP put_##PropName(Type Val) { return PropValue.Set(Val); }
#define MAKE_READONLY_PROPERTY(Type, PropName, PropValue) STDMETHODIMP get_##PropName(Type* pVal) { if (pVal) { *pVal = PropValue; } else { return E_INVALIDARG; } return S_OK; }
#define THROW_INVALID_ARG RoOriginateError(E_INVALIDARG, nullptr);
#define RELEASE_AGILE_WRL(x) if (x) { (x)->Release(); x = nullptr; }
#define RELEASE_WRL(x) if (x) { (x)->Release(); x = nullptr; }
#define GET_WRL_OBJ_FROM_REF(objtype, obj, orig, hr) Microsoft::WRL::ComPtr<objtype> obj;\
hr = orig->QueryInterface(__uuidof(objtype), &obj);
#define GET_WRL_OBJ_FROM_OBJ(objtype, obj, orig, hr) Microsoft::WRL::ComPtr<objtype> obj;\
hr = orig.As(&obj);
#define WRL_ENUM_GET(obj, prefix, prop) obj::prefix##_##prop
#define WRL_PROP_GET(obj, prop, arg, hr) hr = obj->get_##prop(&arg);
#define WRL_PROP_PUT(obj, prop, arg, hr) hr = obj->put_##prop(arg);
#define WRL_METHOD_BASE(obj, method, ret, hr) hr = obj->##method(&ret);
#define WRL_METHOD(obj, method, ret, hr, ...) hr = obj->##method(__VA_ARGS__, &ret);
#define WRL_METHOD_NORET_BASE(obj, method, hr) hr = obj->##method();
#define REF_WRL_OBJ(obj) obj.GetAddressOf()
#define DEREF_WRL_OBJ(obj) obj.Get()
#define DEREF_AGILE_WRL_OBJ(obj) obj
#define DEREF_AS_NATIVE_WRL_OBJ(type, obj) obj.Get()
#define PREPARE_TRANSFER_WRL_OBJ(obj) obj.Detach()
#define ACTIVATE_LOCAL_OBJ_BASE(objtype) Microsoft::WRL::Make<objtype>()
#define ACTIVATE_LOCAL_OBJ(objtype, ...) Microsoft::WRL::Make<objtype>(__VA_ARGS__)
#define ACTIVATE_EVENT_HANDLER(objtype, ...) Microsoft::WRL::Callback<objtype>(__VA_ARGS__).Get()
#define ACTIVATE_OBJ(rtclass, objtype, obj, hr) MAKE_WRL_OBJ(objtype) obj;\
{\
    Microsoft::WRL::ComPtr<IActivationFactory> objFactory;\
    hr = Windows::Foundation::GetActivationFactory(Microsoft::WRL::Wrappers::HStringReference(rtclass).Get(), objFactory.ReleaseAndGetAddressOf());\
    if (SUCCEEDED(hr)) {\
        Microsoft::WRL::ComPtr<IInspectable> pInsp;\
        hr = objFactory->ActivateInstance(pInsp.GetAddressOf());\
        if (SUCCEEDED(hr)) hr = pInsp.As(&obj);\
    }\
}
#define ACTIVATE_STATIC_OBJ(rtclass, objtype, obj, hr) objtype obj;\
{\
    Microsoft::WRL::ComPtr<IActivationFactory> objFactory;\
    hr = Windows::Foundation::GetActivationFactory(Microsoft::WRL::Wrappers::HStringReference(rtclass).Get(), objFactory.ReleaseAndGetAddressOf());\
    if (SUCCEEDED(hr)) {\
        if (SUCCEEDED(hr)) hr = objFactory.As(&obj);\
    }\
}
#endif

#define _ComPtr Microsoft::WRL::ComPtr
#else

#define _COM_SMARTPTR_DECLARE(T,var) T ## Ptr var

template <class T>
class ComPtr
{
public:
    ComPtr() throw()
    {
    }
    ComPtr(T* lp) throw()
    {
        p = lp;
    }
    ComPtr(_In_ const ComPtr<T>& lp) throw()
    {
        p = lp.p;
    }
    virtual ~ComPtr()
    {
    }

    T** operator&() throw()
    {
        assert(p == NULL);
        return p.operator&();
    }
    T* operator->() const throw()
    {
        assert(p != NULL);
        return p.operator->();
    }
    bool operator!() const throw()
    {
        return p.operator==(NULL);
    }
    bool operator==(_In_opt_ T* pT) const throw()
    {
        return p.operator==(pT);
    }
    bool operator!=(_In_opt_ T* pT) const throw()
    {
        return p.operator!=(pT);
    }
    operator bool()
    {
        return p.operator!=(NULL);
    }

    T* const* GetAddressOf() const throw()
    {
        return &p;
    }

    T** GetAddressOf() throw()
    {
        return &p;
    }

    T** ReleaseAndGetAddressOf() throw()
    {
        p.Release();
        return &p;
    }

    T* Get() const throw()
    {
        return p;
    }

    // Attach to an existing interface (does not AddRef)
    void Attach(_In_opt_ T* p2) throw()
    {
        p.Attach(p2);
    }
    // Detach the interface (does not Release)
    T* Detach() throw()
    {
        return p.Detach();
    }
    _Check_return_ HRESULT CopyTo(_Deref_out_opt_ T** ppT) throw()
    {
        assert(ppT != NULL);
        if (ppT == NULL)
            return E_POINTER;
        *ppT = p;
        if (p != NULL)
            p->AddRef();
        return S_OK;
    }

    void Reset()
    {
        p.Release();
    }

    // query for U interface
    template<typename U>
    HRESULT As(_Inout_ U** lp) const throw()
    {
        return p->QueryInterface(__uuidof(U), reinterpret_cast<void**>(lp));
    }
    // query for U interface
    template<typename U>
    HRESULT As(_Out_ ComPtr<U>* lp) const throw()
    {
        return p->QueryInterface(__uuidof(U), reinterpret_cast<void**>(lp->ReleaseAndGetAddressOf()));
    }
private:
    _COM_SMARTPTR_TYPEDEF(T, __uuidof(T));
    _COM_SMARTPTR_DECLARE(T, p);
};

#define _ComPtr ComPtr
#endif

template <class TBase=IMFAttributes>
class CBaseAttributes : public TBase
{
protected:
    // This version of the constructor does not initialize the
    // attribute store. The derived class must call Initialize() in
    // its own constructor.
    CBaseAttributes()
    {
    }

    // This version of the constructor initializes the attribute
    // store, but the derived class must pass an HRESULT parameter
    // to the constructor.

    CBaseAttributes(HRESULT& hr, UINT32 cInitialSize = 0)
    {
        hr = Initialize(cInitialSize);
    }

    // The next version of the constructor uses a caller-provided
    // implementation of IMFAttributes.

    // (Sometimes you want to delegate IMFAttributes calls to some
    // other object that implements IMFAttributes, rather than using
    // MFCreateAttributes.)

    CBaseAttributes(HRESULT& hr, IUnknown *pUnk)
    {
        hr = Initialize(pUnk);
    }

    virtual ~CBaseAttributes()
    {
    }

    // Initializes the object by creating the standard Media Foundation attribute store.
    HRESULT Initialize(UINT32 cInitialSize = 0)
    {
        if (_spAttributes.Get() == nullptr)
        {
            return MFCreateAttributes(&_spAttributes, cInitialSize);
        }
        else
        {
            return S_OK;
        }
    }

    // Initializes this object from a caller-provided attribute store.
    // pUnk: Pointer to an object that exposes IMFAttributes.
    HRESULT Initialize(IUnknown *pUnk)
    {
        if (_spAttributes)
        {
            _spAttributes.Reset();
            _spAttributes = nullptr;
        }


        return pUnk->QueryInterface(IID_PPV_ARGS(&_spAttributes));
    }

public:

    // IMFAttributes methods

    STDMETHODIMP GetItem(REFGUID guidKey, PROPVARIANT* pValue)
    {
        assert(_spAttributes);
        return _spAttributes->GetItem(guidKey, pValue);
    }

    STDMETHODIMP GetItemType(REFGUID guidKey, MF_ATTRIBUTE_TYPE* pType)
    {
        assert(_spAttributes);
        return _spAttributes->GetItemType(guidKey, pType);
    }

    STDMETHODIMP CompareItem(REFGUID guidKey, REFPROPVARIANT Value, BOOL* pbResult)
    {
        assert(_spAttributes);
        return _spAttributes->CompareItem(guidKey, Value, pbResult);
    }

    STDMETHODIMP Compare(
        IMFAttributes* pTheirs,
        MF_ATTRIBUTES_MATCH_TYPE MatchType,
        BOOL* pbResult
        )
    {
        assert(_spAttributes);
        return _spAttributes->Compare(pTheirs, MatchType, pbResult);
    }

    STDMETHODIMP GetUINT32(REFGUID guidKey, UINT32* punValue)
    {
        assert(_spAttributes);
        return _spAttributes->GetUINT32(guidKey, punValue);
    }

    STDMETHODIMP GetUINT64(REFGUID guidKey, UINT64* punValue)
    {
        assert(_spAttributes);
        return _spAttributes->GetUINT64(guidKey, punValue);
    }

    STDMETHODIMP GetDouble(REFGUID guidKey, double* pfValue)
    {
        assert(_spAttributes);
        return _spAttributes->GetDouble(guidKey, pfValue);
    }

    STDMETHODIMP GetGUID(REFGUID guidKey, GUID* pguidValue)
    {
        assert(_spAttributes);
        return _spAttributes->GetGUID(guidKey, pguidValue);
    }

    STDMETHODIMP GetStringLength(REFGUID guidKey, UINT32* pcchLength)
    {
        assert(_spAttributes);
        return _spAttributes->GetStringLength(guidKey, pcchLength);
    }

    STDMETHODIMP GetString(REFGUID guidKey, LPWSTR pwszValue, UINT32 cchBufSize, UINT32* pcchLength)
    {
        assert(_spAttributes);
        return _spAttributes->GetString(guidKey, pwszValue, cchBufSize, pcchLength);
    }

    STDMETHODIMP GetAllocatedString(REFGUID guidKey, LPWSTR* ppwszValue, UINT32* pcchLength)
    {
        assert(_spAttributes);
        return _spAttributes->GetAllocatedString(guidKey, ppwszValue, pcchLength);
    }

    STDMETHODIMP GetBlobSize(REFGUID guidKey, UINT32* pcbBlobSize)
    {
        assert(_spAttributes);
        return _spAttributes->GetBlobSize(guidKey, pcbBlobSize);
    }

    STDMETHODIMP GetBlob(REFGUID guidKey, UINT8* pBuf, UINT32 cbBufSize, UINT32* pcbBlobSize)
    {
        assert(_spAttributes);
        return _spAttributes->GetBlob(guidKey, pBuf, cbBufSize, pcbBlobSize);
    }

    STDMETHODIMP GetAllocatedBlob(REFGUID guidKey, UINT8** ppBuf, UINT32* pcbSize)
    {
        assert(_spAttributes);
        return _spAttributes->GetAllocatedBlob(guidKey, ppBuf, pcbSize);
    }

    STDMETHODIMP GetUnknown(REFGUID guidKey, REFIID riid, LPVOID* ppv)
    {
        assert(_spAttributes);
        return _spAttributes->GetUnknown(guidKey, riid, ppv);
    }

    STDMETHODIMP SetItem(REFGUID guidKey, REFPROPVARIANT Value)
    {
        assert(_spAttributes);
        return _spAttributes->SetItem(guidKey, Value);
    }

    STDMETHODIMP DeleteItem(REFGUID guidKey)
    {
        assert(_spAttributes);
        return _spAttributes->DeleteItem(guidKey);
    }

    STDMETHODIMP DeleteAllItems()
    {
        assert(_spAttributes);
        return _spAttributes->DeleteAllItems();
    }

    STDMETHODIMP SetUINT32(REFGUID guidKey, UINT32 unValue)
    {
        assert(_spAttributes);
        return _spAttributes->SetUINT32(guidKey, unValue);
    }

    STDMETHODIMP SetUINT64(REFGUID guidKey,UINT64 unValue)
    {
        assert(_spAttributes);
        return _spAttributes->SetUINT64(guidKey, unValue);
    }

    STDMETHODIMP SetDouble(REFGUID guidKey, double fValue)
    {
        assert(_spAttributes);
        return _spAttributes->SetDouble(guidKey, fValue);
    }

    STDMETHODIMP SetGUID(REFGUID guidKey, REFGUID guidValue)
    {
        assert(_spAttributes);
        return _spAttributes->SetGUID(guidKey, guidValue);
    }

    STDMETHODIMP SetString(REFGUID guidKey, LPCWSTR wszValue)
    {
        assert(_spAttributes);
        return _spAttributes->SetString(guidKey, wszValue);
    }

    STDMETHODIMP SetBlob(REFGUID guidKey, const UINT8* pBuf, UINT32 cbBufSize)
    {
        assert(_spAttributes);
        return _spAttributes->SetBlob(guidKey, pBuf, cbBufSize);
    }

    STDMETHODIMP SetUnknown(REFGUID guidKey, IUnknown* pUnknown)
    {
        assert(_spAttributes);
        return _spAttributes->SetUnknown(guidKey, pUnknown);
    }

    STDMETHODIMP LockStore()
    {
        assert(_spAttributes);
        return _spAttributes->LockStore();
    }

    STDMETHODIMP UnlockStore()
    {
        assert(_spAttributes);
        return _spAttributes->UnlockStore();
    }

    STDMETHODIMP GetCount(UINT32* pcItems)
    {
        assert(_spAttributes);
        return _spAttributes->GetCount(pcItems);
    }

    STDMETHODIMP GetItemByIndex(UINT32 unIndex, GUID* pguidKey, PROPVARIANT* pValue)
    {
        assert(_spAttributes);
        return _spAttributes->GetItemByIndex(unIndex, pguidKey, pValue);
    }

    STDMETHODIMP CopyAllItems(IMFAttributes* pDest)
    {
        assert(_spAttributes);
        return _spAttributes->CopyAllItems(pDest);
    }

    // Helper functions

    HRESULT SerializeToStream(DWORD dwOptions, IStream* pStm)
        // dwOptions: Flags from MF_ATTRIBUTE_SERIALIZE_OPTIONS
    {
        assert(_spAttributes);
        return MFSerializeAttributesToStream(_spAttributes.Get(), dwOptions, pStm);
    }

    HRESULT DeserializeFromStream(DWORD dwOptions, IStream* pStm)
    {
        assert(_spAttributes);
        return MFDeserializeAttributesFromStream(_spAttributes.Get(), dwOptions, pStm);
    }

    // SerializeToBlob: Stores the attributes in a byte array.
    //
    // ppBuf: Receives a pointer to the byte array.
    // pcbSize: Receives the size of the byte array.
    //
    // The caller must free the array using CoTaskMemFree.
    HRESULT SerializeToBlob(UINT8 **ppBuffer, UINT *pcbSize)
    {
        assert(_spAttributes);

        if (ppBuffer == NULL)
        {
            return E_POINTER;
        }
        if (pcbSize == NULL)
        {
            return E_POINTER;
        }

        HRESULT hr = S_OK;
        UINT32 cbSize = 0;
        BYTE *pBuffer = NULL;

        CHECK_HR(hr = MFGetAttributesAsBlobSize(_spAttributes.Get(), &cbSize));

        pBuffer = (BYTE*)CoTaskMemAlloc(cbSize);
        if (pBuffer == NULL)
        {
            CHECK_HR(hr = E_OUTOFMEMORY);
        }

        CHECK_HR(hr = MFGetAttributesAsBlob(_spAttributes.Get(), pBuffer, cbSize));

        *ppBuffer = pBuffer;
        *pcbSize = cbSize;

done:
        if (FAILED(hr))
        {
            *ppBuffer = NULL;
            *pcbSize = 0;
            CoTaskMemFree(pBuffer);
        }
        return hr;
    }

    HRESULT DeserializeFromBlob(const UINT8* pBuffer, UINT cbSize)
    {
        assert(_spAttributes);
        return MFInitAttributesFromBlob(_spAttributes.Get(), pBuffer, cbSize);
    }

    HRESULT GetRatio(REFGUID guidKey, UINT32* pnNumerator, UINT32* punDenominator)
    {
        assert(_spAttributes);
        return MFGetAttributeRatio(_spAttributes.Get(), guidKey, pnNumerator, punDenominator);
    }

    HRESULT SetRatio(REFGUID guidKey, UINT32 unNumerator, UINT32 unDenominator)
    {
        assert(_spAttributes);
        return MFSetAttributeRatio(_spAttributes.Get(), guidKey, unNumerator, unDenominator);
    }

    // Gets an attribute whose value represents the size of something (eg a video frame).
    HRESULT GetSize(REFGUID guidKey, UINT32* punWidth, UINT32* punHeight)
    {
        assert(_spAttributes);
        return MFGetAttributeSize(_spAttributes.Get(), guidKey, punWidth, punHeight);
    }

    // Sets an attribute whose value represents the size of something (eg a video frame).
    HRESULT SetSize(REFGUID guidKey, UINT32 unWidth, UINT32 unHeight)
    {
        assert(_spAttributes);
        return MFSetAttributeSize (_spAttributes.Get(), guidKey, unWidth, unHeight);
    }

protected:
    _ComPtr<IMFAttributes> _spAttributes;
};

class StreamSink :
#ifdef WINRT
    public Microsoft::WRL::RuntimeClass<
    Microsoft::WRL::RuntimeClassFlags< Microsoft::WRL::RuntimeClassType::ClassicCom>,
    IMFStreamSink,
    IMFMediaEventGenerator,
    IMFMediaTypeHandler,
    CBaseAttributes<> >
#else
    public IMFStreamSink,
    public IMFMediaTypeHandler,
    public CBaseAttributes<>,
    public ICustomStreamSink
#endif
{
public:
    // IUnknown methods
#if defined(_MSC_VER) && _MSC_VER >= 1700  // '_Outptr_result_nullonfailure_' SAL is avaialable since VS 2012
    STDMETHOD(QueryInterface)(REFIID riid, _Outptr_result_nullonfailure_ void **ppv)
#else
    STDMETHOD(QueryInterface)(REFIID riid, void **ppv)
#endif
    {
        if (ppv == nullptr) {
            return E_POINTER;
        }
        (*ppv) = nullptr;
        HRESULT hr = S_OK;
        if (riid == IID_IMarshal) {
            return MarshalQI(riid, ppv);
        } else {
#ifdef WINRT
            hr = RuntimeClassT::QueryInterface(riid, ppv);
#else
            if (riid == IID_IUnknown || riid == IID_IMFStreamSink) {
                *ppv = static_cast<IMFStreamSink*>(this);
                AddRef();
            } else if (riid == IID_IMFMediaEventGenerator) {
                *ppv = static_cast<IMFMediaEventGenerator*>(this);
                AddRef();
            } else if (riid == IID_IMFMediaTypeHandler) {
                *ppv = static_cast<IMFMediaTypeHandler*>(this);
                AddRef();
            } else if (riid == IID_IMFAttributes) {
                *ppv = static_cast<IMFAttributes*>(this);
                AddRef();
            } else if (riid == IID_ICustomStreamSink) {
                *ppv = static_cast<ICustomStreamSink*>(this);
                AddRef();
            } else
                hr = E_NOINTERFACE;
#endif
        }

        return hr;
    }

#ifdef WINRT
    STDMETHOD(RuntimeClassInitialize)() { return S_OK; }
#else
    ULONG STDMETHODCALLTYPE AddRef()
    {
        return InterlockedIncrement(&m_cRef);
    }
    ULONG STDMETHODCALLTYPE Release()
    {
        ULONG cRef = InterlockedDecrement(&m_cRef);
        if (cRef == 0)
        {
            delete this;
        }
        return cRef;
    }
#endif
    HRESULT MarshalQI(REFIID riid, LPVOID* ppv)
    {
        HRESULT hr = S_OK;
        if (m_spFTM == nullptr) {
            EnterCriticalSection(&m_critSec);
            if (m_spFTM == nullptr) {
                hr = CoCreateFreeThreadedMarshaler((IMFStreamSink*)this, &m_spFTM);
            }
            LeaveCriticalSection(&m_critSec);
        }

        if (SUCCEEDED(hr)) {
            if (m_spFTM == nullptr) {
                hr = E_UNEXPECTED;
            }
            else {
                hr = m_spFTM.Get()->QueryInterface(riid, ppv);
            }
        }
        return hr;
    }
    enum State
    {
        State_TypeNotSet = 0,    // No media type is set
        State_Ready,             // Media type is set, Start has never been called.
        State_Started,
        State_Stopped,
        State_Paused,
        State_Count              // Number of states
    };
    StreamSink() : m_IsShutdown(false),
        m_StartTime(0), m_fGetStartTimeFromSample(false), m_fWaitingForFirstSample(false),
        m_state(State_TypeNotSet), m_pParent(nullptr),
        m_imageWidthInPixels(0), m_imageHeightInPixels(0) {
#ifdef WINRT
        m_token.value = 0;
#else
        m_bConnected = false;
#endif
        InitializeCriticalSectionEx(&m_critSec, 3000, 0);
        ZeroMemory(&m_guiCurrentSubtype, sizeof(m_guiCurrentSubtype));
        CBaseAttributes::Initialize(0U);
        DebugPrintOut(L"StreamSink::StreamSink\n");
    }
    virtual ~StreamSink() {
        DeleteCriticalSection(&m_critSec);
        assert(m_IsShutdown);
        DebugPrintOut(L"StreamSink::~StreamSink\n");
    }

    HRESULT Initialize()
    {
        HRESULT hr;
        // Create the event queue helper.
        hr = MFCreateEventQueue(&m_spEventQueue);
        if (SUCCEEDED(hr))
        {
            _ComPtr<IMFMediaSink> pMedSink;
            hr = CBaseAttributes<>::GetUnknown(MF_STREAMSINK_MEDIASINKINTERFACE, __uuidof(IMFMediaSink), (LPVOID*)pMedSink.GetAddressOf());
            assert(pMedSink.Get() != NULL);
            if (SUCCEEDED(hr)) {
                hr = pMedSink.Get()->QueryInterface(IID_PPV_ARGS(&m_pParent));
            }
        }
        return hr;
    }

    HRESULT CheckShutdown() const
    {
        if (m_IsShutdown)
        {
            return MF_E_SHUTDOWN;
        }
        else
        {
            return S_OK;
        }
    }
    // Called when the presentation clock starts.
    HRESULT Start(MFTIME start)
    {
        HRESULT hr = S_OK;
        EnterCriticalSection(&m_critSec);
        if (m_state != State_TypeNotSet) {
            if (start != PRESENTATION_CURRENT_POSITION)
            {
                m_StartTime = start;        // Cache the start time.
                m_fGetStartTimeFromSample = false;
            }
            else
            {
                m_fGetStartTimeFromSample = true;
            }
            m_state = State_Started;
            GUID guiMajorType;
            m_fWaitingForFirstSample = SUCCEEDED(m_spCurrentType->GetMajorType(&guiMajorType)) && (guiMajorType == MFMediaType_Video);
            hr = QueueEvent(MEStreamSinkStarted, GUID_NULL, hr, NULL);
            if (SUCCEEDED(hr)) {
                hr = QueueEvent(MEStreamSinkRequestSample, GUID_NULL, hr, NULL);
            }
        }
        else hr = MF_E_NOT_INITIALIZED;
        LeaveCriticalSection(&m_critSec);
        return hr;
    }

    // Called when the presentation clock pauses.
    HRESULT Pause()
    {
        EnterCriticalSection(&m_critSec);

        HRESULT hr = S_OK;

        if (m_state != State_Stopped && m_state != State_TypeNotSet) {
            m_state = State_Paused;
            hr = QueueEvent(MEStreamSinkPaused, GUID_NULL, hr, NULL);
        } else if (hr == State_TypeNotSet)
            hr = MF_E_NOT_INITIALIZED;
        else
            hr = MF_E_INVALIDREQUEST;
        LeaveCriticalSection(&m_critSec);
        return hr;
    }
    // Called when the presentation clock restarts.
    HRESULT Restart()
    {
        EnterCriticalSection(&m_critSec);

        HRESULT hr = S_OK;

        if (m_state == State_Paused) {
            m_state = State_Started;
            hr = QueueEvent(MEStreamSinkStarted, GUID_NULL, hr, NULL);
            if (SUCCEEDED(hr)) {
                hr = QueueEvent(MEStreamSinkRequestSample, GUID_NULL, hr, NULL);
            }
        } else if (hr == State_TypeNotSet)
            hr = MF_E_NOT_INITIALIZED;
        else
            hr = MF_E_INVALIDREQUEST;
        LeaveCriticalSection(&m_critSec);
        return hr;
    }
    // Called when the presentation clock stops.
    HRESULT Stop()
    {
        EnterCriticalSection(&m_critSec);

        HRESULT hr = S_OK;
        if (m_state != State_TypeNotSet) {
            m_state = State_Stopped;
            hr = QueueEvent(MEStreamSinkStopped, GUID_NULL, hr, NULL);
        }
        else hr = MF_E_NOT_INITIALIZED;
        LeaveCriticalSection(&m_critSec);
        return hr;
    }

    // Shuts down the stream sink.
    HRESULT Shutdown()
    {
        _ComPtr<IMFSampleGrabberSinkCallback> pSampleCallback;
        HRESULT hr = S_OK;
        assert(!m_IsShutdown);
        hr = m_pParent->GetUnknown(MF_MEDIASINK_SAMPLEGRABBERCALLBACK, IID_IMFSampleGrabberSinkCallback, (LPVOID*)pSampleCallback.GetAddressOf());
        if (SUCCEEDED(hr)) {
            hr = pSampleCallback->OnShutdown();
        }

        if (m_spEventQueue) {
            hr = m_spEventQueue->Shutdown();
        }
        if (m_pParent)
            m_pParent->Release();
        m_spCurrentType.Reset();
        m_IsShutdown = TRUE;

        return hr;
    }

    //IMFStreamSink
    HRESULT STDMETHODCALLTYPE GetMediaSink(
    /* [out] */ __RPC__deref_out_opt IMFMediaSink **ppMediaSink) {
        if (ppMediaSink == NULL)
        {
            return E_INVALIDARG;
        }

        EnterCriticalSection(&m_critSec);

        HRESULT hr = CheckShutdown();

        if (SUCCEEDED(hr))
        {
            _ComPtr<IMFMediaSink> pMedSink;
            hr = CBaseAttributes<>::GetUnknown(MF_STREAMSINK_MEDIASINKINTERFACE, __uuidof(IMFMediaSink), (LPVOID*)pMedSink.GetAddressOf());
            if (SUCCEEDED(hr)) {
                *ppMediaSink = pMedSink.Detach();
            }
        }

        LeaveCriticalSection(&m_critSec);
        DebugPrintOut(L"StreamSink::GetMediaSink: HRESULT=%i\n", hr);
        return hr;
    }

    HRESULT STDMETHODCALLTYPE GetIdentifier(
        /* [out] */ __RPC__out DWORD *pdwIdentifier) {
        if (pdwIdentifier == NULL)
        {
            return E_INVALIDARG;
        }

        EnterCriticalSection(&m_critSec);

        HRESULT hr = CheckShutdown();

        if (SUCCEEDED(hr))
        {
            hr = GetUINT32(MF_STREAMSINK_ID, (UINT32*)pdwIdentifier);
        }

        LeaveCriticalSection(&m_critSec);
        DebugPrintOut(L"StreamSink::GetIdentifier: HRESULT=%i\n", hr);
        return hr;
    }

    HRESULT STDMETHODCALLTYPE GetMediaTypeHandler(
        /* [out] */ __RPC__deref_out_opt IMFMediaTypeHandler **ppHandler) {
        if (ppHandler == NULL)
        {
            return E_INVALIDARG;
        }

        EnterCriticalSection(&m_critSec);

        HRESULT hr = CheckShutdown();

        // This stream object acts as its own type handler, so we QI ourselves.
        if (SUCCEEDED(hr))
        {
            hr = QueryInterface(IID_IMFMediaTypeHandler, (void**)ppHandler);
        }

        LeaveCriticalSection(&m_critSec);
        DebugPrintOut(L"StreamSink::GetMediaTypeHandler: HRESULT=%i\n", hr);
        return hr;
    }

    HRESULT STDMETHODCALLTYPE ProcessSample(IMFSample *pSample) {
        _ComPtr<IMFMediaBuffer> pInput;
        _ComPtr<IMFSampleGrabberSinkCallback> pSampleCallback;
        BYTE *pSrc = NULL;          // Source buffer.
        // Stride if the buffer does not support IMF2DBuffer
        LONGLONG hnsTime = 0;
        LONGLONG hnsDuration = 0;
        DWORD cbMaxLength;
        DWORD cbCurrentLength = 0;
        GUID guidMajorType;
        if (pSample == NULL)
        {
            return E_INVALIDARG;
        }
        HRESULT hr = S_OK;

        EnterCriticalSection(&m_critSec);

        if (m_state != State_Started && m_state != State_Paused) {
            if (m_state == State_TypeNotSet)
                hr = MF_E_NOT_INITIALIZED;
            else
                hr = MF_E_INVALIDREQUEST;
        }
        if (SUCCEEDED(hr))
            hr = CheckShutdown();
        if (SUCCEEDED(hr)) {
            hr = pSample->ConvertToContiguousBuffer(&pInput);
            if (SUCCEEDED(hr)) {
                hr = pSample->GetSampleTime(&hnsTime);
            }
            if (SUCCEEDED(hr)) {
                hr = pSample->GetSampleDuration(&hnsDuration);
            }
            if (SUCCEEDED(hr)) {
                hr = GetMajorType(&guidMajorType);
            }
            if (SUCCEEDED(hr)) {
                hr = m_pParent->GetUnknown(MF_MEDIASINK_SAMPLEGRABBERCALLBACK, IID_IMFSampleGrabberSinkCallback, (LPVOID*)pSampleCallback.GetAddressOf());
            }
            if (SUCCEEDED(hr)) {
                hr = pInput->Lock(&pSrc, &cbMaxLength, &cbCurrentLength);
            }
            if (SUCCEEDED(hr)) {
                hr = pSampleCallback->OnProcessSample(guidMajorType, 0, hnsTime, hnsDuration, pSrc, cbCurrentLength);
                pInput->Unlock();
            }
            if (SUCCEEDED(hr)) {
                hr = QueueEvent(MEStreamSinkRequestSample, GUID_NULL, S_OK, NULL);
            }
        }
        LeaveCriticalSection(&m_critSec);
        return hr;
    }

    HRESULT STDMETHODCALLTYPE PlaceMarker(
        /* [in] */ MFSTREAMSINK_MARKER_TYPE eMarkerType,
        /* [in] */ __RPC__in const PROPVARIANT * /*pvarMarkerValue*/,
        /* [in] */ __RPC__in const PROPVARIANT * /*pvarContextValue*/) {
        eMarkerType;
        EnterCriticalSection(&m_critSec);

        HRESULT hr = S_OK;
        if (m_state == State_TypeNotSet)
            hr = MF_E_NOT_INITIALIZED;

        if (SUCCEEDED(hr))
            hr = CheckShutdown();

        if (SUCCEEDED(hr))
        {
            //at shutdown will receive MFSTREAMSINK_MARKER_ENDOFSEGMENT
            hr = QueueEvent(MEStreamSinkRequestSample, GUID_NULL, S_OK, NULL);
        }

        LeaveCriticalSection(&m_critSec);
        DebugPrintOut(L"StreamSink::PlaceMarker: HRESULT=%i %s\n", hr, StreamSinkMarkerTypeMap.at(eMarkerType).c_str());
        return hr;
    }

    HRESULT STDMETHODCALLTYPE Flush(void) {
        EnterCriticalSection(&m_critSec);

        HRESULT hr = CheckShutdown();

        if (SUCCEEDED(hr))
        {
        }

        LeaveCriticalSection(&m_critSec);
        DebugPrintOut(L"StreamSink::Flush: HRESULT=%i\n", hr);
        return hr;
    }

    //IMFMediaEventGenerator
    HRESULT STDMETHODCALLTYPE GetEvent(
        DWORD dwFlags, IMFMediaEvent **ppEvent) {
        // NOTE:
        // GetEvent can block indefinitely, so we don't hold the lock.
        // This requires some juggling with the event queue pointer.

        HRESULT hr = S_OK;

        _ComPtr<IMFMediaEventQueue> pQueue;

        {
            EnterCriticalSection(&m_critSec);

            // Check shutdown
            hr = CheckShutdown();

            // Get the pointer to the event queue.
            if (SUCCEEDED(hr))
            {
                pQueue = m_spEventQueue.Get();
            }
            LeaveCriticalSection(&m_critSec);
        }

        // Now get the event.
        if (SUCCEEDED(hr))
        {
            hr = pQueue->GetEvent(dwFlags, ppEvent);
        }
        MediaEventType meType = MEUnknown;
        if (SUCCEEDED(hr) && SUCCEEDED((*ppEvent)->GetType(&meType)) && meType == MEStreamSinkStopped) {
        }
        HRESULT hrStatus = S_OK;
        if (SUCCEEDED(hr))
            hr = (*ppEvent)->GetStatus(&hrStatus);
        if (SUCCEEDED(hr))
            DebugPrintOut(L"StreamSink::GetEvent: HRESULT=%i %s\n", hrStatus, MediaEventTypeMap.at(meType).c_str());
        else
            DebugPrintOut(L"StreamSink::GetEvent: HRESULT=%i\n", hr);
        return hr;
    }

    HRESULT STDMETHODCALLTYPE BeginGetEvent(
        IMFAsyncCallback *pCallback, IUnknown *punkState) {
        HRESULT hr = S_OK;

        EnterCriticalSection(&m_critSec);

        hr = CheckShutdown();

        if (SUCCEEDED(hr))
        {
            hr = m_spEventQueue->BeginGetEvent(pCallback, punkState);
        }
        LeaveCriticalSection(&m_critSec);
        DebugPrintOut(L"StreamSink::BeginGetEvent: HRESULT=%i\n", hr);
        return hr;
    }

    HRESULT STDMETHODCALLTYPE EndGetEvent(
        IMFAsyncResult *pResult, IMFMediaEvent **ppEvent) {
        HRESULT hr = S_OK;

        EnterCriticalSection(&m_critSec);

        hr = CheckShutdown();

        if (SUCCEEDED(hr))
        {
            hr = m_spEventQueue->EndGetEvent(pResult, ppEvent);
        }

        MediaEventType meType = MEUnknown;
        if (SUCCEEDED(hr) && SUCCEEDED((*ppEvent)->GetType(&meType)) && meType == MEStreamSinkStopped) {
        }

        LeaveCriticalSection(&m_critSec);
        HRESULT hrStatus = S_OK;
        if (SUCCEEDED(hr))
            hr = (*ppEvent)->GetStatus(&hrStatus);
        if (SUCCEEDED(hr))
            DebugPrintOut(L"StreamSink::EndGetEvent: HRESULT=%i %s\n", hrStatus, MediaEventTypeMap.at(meType).c_str());
        else
            DebugPrintOut(L"StreamSink::EndGetEvent: HRESULT=%i\n", hr);
        return hr;
    }

    HRESULT STDMETHODCALLTYPE QueueEvent(
        MediaEventType met, REFGUID guidExtendedType,
        HRESULT hrStatus, const PROPVARIANT *pvValue) {
        HRESULT hr = S_OK;

        EnterCriticalSection(&m_critSec);

        hr = CheckShutdown();

        if (SUCCEEDED(hr))
        {
            hr = m_spEventQueue->QueueEventParamVar(met, guidExtendedType, hrStatus, pvValue);
        }

        LeaveCriticalSection(&m_critSec);
        DebugPrintOut(L"StreamSink::QueueEvent: HRESULT=%i %s\n", hrStatus, MediaEventTypeMap.at(met).c_str());
        DebugPrintOut(L"StreamSink::QueueEvent: HRESULT=%i\n", hr);
        return hr;
    }

    /// IMFMediaTypeHandler methods

    // Check if a media type is supported.
    STDMETHODIMP IsMediaTypeSupported(
        /* [in] */ IMFMediaType *pMediaType,
        /* [out] */ IMFMediaType **ppMediaType)
    {
        if (pMediaType == nullptr)
        {
            return E_INVALIDARG;
        }

        EnterCriticalSection(&m_critSec);

        GUID majorType = GUID_NULL;

        HRESULT hr = CheckShutdown();

        if (SUCCEEDED(hr))
        {
            hr = pMediaType->GetGUID(MF_MT_MAJOR_TYPE, &majorType);
        }

        // First make sure it's video or audio type.
        if (SUCCEEDED(hr))
        {
            if (majorType != MFMediaType_Video && majorType != MFMediaType_Audio)
            {
                hr = MF_E_INVALIDTYPE;
            }
        }

        if (SUCCEEDED(hr) && m_spCurrentType != nullptr)
        {
            GUID guiNewSubtype;
            if (FAILED(pMediaType->GetGUID(MF_MT_SUBTYPE, &guiNewSubtype)) ||
                guiNewSubtype != m_guiCurrentSubtype)
            {
                hr = MF_E_INVALIDTYPE;
            }
        }
        // We don't return any "close match" types.
        if (ppMediaType)
        {
            *ppMediaType = nullptr;
        }

        if (ppMediaType && SUCCEEDED(hr)) {
            _ComPtr<IMFMediaType> pType;
            hr = MFCreateMediaType(ppMediaType);
            if (SUCCEEDED(hr)) {
                hr = m_pParent->GetUnknown(MF_MEDIASINK_PREFERREDTYPE, __uuidof(IMFMediaType), (LPVOID*)&pType);
            }
            if (SUCCEEDED(hr)) {
                hr = pType->LockStore();
            }
            bool bLocked = false;
            if (SUCCEEDED(hr)) {
                bLocked = true;
                UINT32 uiCount;
                UINT32 uiTotal;
                hr = pType->GetCount(&uiTotal);
                for (uiCount = 0; SUCCEEDED(hr) && uiCount < uiTotal; uiCount++) {
                    GUID guid;
                    PROPVARIANT propval;
                    hr = pType->GetItemByIndex(uiCount, &guid, &propval);
                    if (SUCCEEDED(hr) && (guid == MF_MT_FRAME_SIZE || guid == MF_MT_MAJOR_TYPE || guid == MF_MT_PIXEL_ASPECT_RATIO ||
                        guid == MF_MT_ALL_SAMPLES_INDEPENDENT || guid == MF_MT_INTERLACE_MODE || guid == MF_MT_SUBTYPE)) {
                        hr = (*ppMediaType)->SetItem(guid, propval);
                        PropVariantClear(&propval);
                    }
                }
            }
            if (bLocked) {
                hr = pType->UnlockStore();
            }
        }
        LeaveCriticalSection(&m_critSec);
        DebugPrintOut(L"StreamSink::IsMediaTypeSupported: HRESULT=%i\n", hr);
        return hr;
    }


    // Return the number of preferred media types.
    STDMETHODIMP GetMediaTypeCount(DWORD *pdwTypeCount)
    {
        if (pdwTypeCount == nullptr)
        {
            return E_INVALIDARG;
        }

        EnterCriticalSection(&m_critSec);

        HRESULT hr = CheckShutdown();

        if (SUCCEEDED(hr))
        {
            // We've got only one media type
            *pdwTypeCount = 1;
        }

        LeaveCriticalSection(&m_critSec);
        DebugPrintOut(L"StreamSink::GetMediaTypeCount: HRESULT=%i\n", hr);
        return hr;
    }


    // Return a preferred media type by index.
    STDMETHODIMP GetMediaTypeByIndex(
        /* [in] */ DWORD dwIndex,
        /* [out] */ IMFMediaType **ppType)
    {
        if (ppType == NULL) {
            return E_INVALIDARG;
        }

        EnterCriticalSection(&m_critSec);

        HRESULT hr = CheckShutdown();

        if (dwIndex > 0)
        {
            hr = MF_E_NO_MORE_TYPES;
        } else {
            //return preferred type based on media capture library 6 elements preferred preview type
            //hr = m_spCurrentType.CopyTo(ppType);
            if (SUCCEEDED(hr)) {
                _ComPtr<IMFMediaType> pType;
                hr = MFCreateMediaType(ppType);
                if (SUCCEEDED(hr)) {
                    hr = m_pParent->GetUnknown(MF_MEDIASINK_PREFERREDTYPE, __uuidof(IMFMediaType), (LPVOID*)&pType);
                }
                if (SUCCEEDED(hr)) {
                    hr = pType->LockStore();
                }
                bool bLocked = false;
                if (SUCCEEDED(hr)) {
                    bLocked = true;
                    UINT32 uiCount;
                    UINT32 uiTotal;
                    hr = pType->GetCount(&uiTotal);
                    for (uiCount = 0; SUCCEEDED(hr) && uiCount < uiTotal; uiCount++) {
                        GUID guid;
                        PROPVARIANT propval;
                        hr = pType->GetItemByIndex(uiCount, &guid, &propval);
                        if (SUCCEEDED(hr) && (guid == MF_MT_FRAME_SIZE || guid == MF_MT_MAJOR_TYPE || guid == MF_MT_PIXEL_ASPECT_RATIO ||
                            guid == MF_MT_ALL_SAMPLES_INDEPENDENT || guid == MF_MT_INTERLACE_MODE || guid == MF_MT_SUBTYPE)) {
                            hr = (*ppType)->SetItem(guid, propval);
                            PropVariantClear(&propval);
                        }
                    }
                }
                if (bLocked) {
                    hr = pType->UnlockStore();
                }
            }
        }

        LeaveCriticalSection(&m_critSec);
        DebugPrintOut(L"StreamSink::GetMediaTypeByIndex: HRESULT=%i\n", hr);
        return hr;
    }


    // Set the current media type.
    STDMETHODIMP SetCurrentMediaType(IMFMediaType *pMediaType)
    {
        if (pMediaType == NULL) {
            return E_INVALIDARG;
        }
        EnterCriticalSection(&m_critSec);

        HRESULT hr = S_OK;
        if (m_state != State_TypeNotSet && m_state != State_Ready)
            hr = MF_E_INVALIDREQUEST;
        if (SUCCEEDED(hr))
            hr = CheckShutdown();

        // We don't allow format changes after streaming starts.

        // We set media type already
        if (m_state >= State_Ready)
        {
            if (SUCCEEDED(hr))
            {
                hr = IsMediaTypeSupported(pMediaType, NULL);
            }
        }

        if (SUCCEEDED(hr))
        {
            hr = MFCreateMediaType(m_spCurrentType.ReleaseAndGetAddressOf());
            if (SUCCEEDED(hr))
            {
                hr = pMediaType->CopyAllItems(m_spCurrentType.Get());
            }
            if (SUCCEEDED(hr))
            {
                hr = m_spCurrentType->GetGUID(MF_MT_SUBTYPE, &m_guiCurrentSubtype);
            }
            GUID guid;
            if (SUCCEEDED(hr)) {
                hr = m_spCurrentType->GetMajorType(&guid);
            }
            if (SUCCEEDED(hr) && guid == MFMediaType_Video) {
                hr = MFGetAttributeSize(m_spCurrentType.Get(), MF_MT_FRAME_SIZE, &m_imageWidthInPixels, &m_imageHeightInPixels);
            }
            if (SUCCEEDED(hr))
            {
                m_state = State_Ready;
            }
        }

        LeaveCriticalSection(&m_critSec);
        DebugPrintOut(L"StreamSink::SetCurrentMediaType: HRESULT=%i\n", hr);
        return hr;
    }

    // Return the current media type, if any.
    STDMETHODIMP GetCurrentMediaType(IMFMediaType **ppMediaType)
    {
        if (ppMediaType == NULL) {
            return E_INVALIDARG;
        }

        EnterCriticalSection(&m_critSec);

        HRESULT hr = CheckShutdown();

        if (SUCCEEDED(hr)) {
            if (m_spCurrentType == nullptr) {
                hr = MF_E_NOT_INITIALIZED;
            }
        }

        if (SUCCEEDED(hr)) {
            hr = m_spCurrentType.CopyTo(ppMediaType);
        }

        LeaveCriticalSection(&m_critSec);
        DebugPrintOut(L"StreamSink::GetCurrentMediaType: HRESULT=%i\n", hr);
        return hr;
    }


    // Return the major type GUID.
    STDMETHODIMP GetMajorType(GUID *pguidMajorType)
    {
        HRESULT hr;
        if (pguidMajorType == nullptr) {
            return E_INVALIDARG;
        }

        _ComPtr<IMFMediaType> pType;
        hr = m_pParent->GetUnknown(MF_MEDIASINK_PREFERREDTYPE, __uuidof(IMFMediaType), (LPVOID*)&pType);
        if (SUCCEEDED(hr)) {
            hr = pType->GetMajorType(pguidMajorType);
        }
        DebugPrintOut(L"StreamSink::GetMajorType: HRESULT=%i\n", hr);
        return hr;
    }
private:
#ifdef WINRT
    EventRegistrationToken m_token;
#else
    bool m_bConnected;
#endif

    bool m_IsShutdown;                // Flag to indicate if Shutdown() method was called.
    CRITICAL_SECTION m_critSec;
#ifndef WINRT
    long m_cRef;
#endif
    IMFAttributes*        m_pParent;
    _ComPtr<IMFMediaType>        m_spCurrentType;
    _ComPtr<IMFMediaEventQueue>  m_spEventQueue;              // Event queue

    _ComPtr<IUnknown>            m_spFTM;
    State                       m_state;
    bool                        m_fGetStartTimeFromSample;
    bool                        m_fWaitingForFirstSample;
    MFTIME                      m_StartTime;                 // Presentation time when the clock started.
    GUID                        m_guiCurrentSubtype;
    UINT32                      m_imageWidthInPixels;
    UINT32                      m_imageHeightInPixels;
};

// Notes:
//
// The List class template implements a simple double-linked list.
// It uses STL's copy semantics.

// There are two versions of the Clear() method:
//  Clear(void) clears the list w/out cleaning up the object.
//  Clear(FN fn) takes a functor object that releases the objects, if they need cleanup.

// The List class supports enumeration. Example of usage:
//
// List<T>::POSIITON pos = list.GetFrontPosition();
// while (pos != list.GetEndPosition())
// {
//     T item;
//     hr = list.GetItemPos(&item);
//     pos = list.Next(pos);
// }

// The ComPtrList class template derives from List<> and implements a list of COM pointers.

template <class T>
struct NoOp
{
    void operator()(T& /*t*/)
    {
    }
};

template <class T>
class List
{
protected:

    // Nodes in the linked list
    struct Node
    {
        Node *prev;
        Node *next;
        T    item;

        Node() : prev(nullptr), next(nullptr)
        {
        }

        Node(T item) : prev(nullptr), next(nullptr)
        {
            this->item = item;
        }

        T Item() const { return item; }
    };

public:

    // Object for enumerating the list.
    class POSITION
    {
        friend class List<T>;

    public:
        POSITION() : pNode(nullptr)
        {
        }

        bool operator==(const POSITION &p) const
        {
            return pNode == p.pNode;
        }

        bool operator!=(const POSITION &p) const
        {
            return pNode != p.pNode;
        }

    private:
        const Node *pNode;

        POSITION(Node *p) : pNode(p)
        {
        }
    };

protected:
    Node    m_anchor;  // Anchor node for the linked list.
    DWORD   m_count;   // Number of items in the list.

    Node* Front() const
    {
        return m_anchor.next;
    }

    Node* Back() const
    {
        return m_anchor.prev;
    }

    virtual HRESULT InsertAfter(T item, Node *pBefore)
    {
        if (pBefore == nullptr)
        {
            return E_POINTER;
        }

        Node *pNode = new Node(item);
        if (pNode == nullptr)
        {
            return E_OUTOFMEMORY;
        }

        Node *pAfter = pBefore->next;

        pBefore->next = pNode;
        pAfter->prev = pNode;

        pNode->prev = pBefore;
        pNode->next = pAfter;

        m_count++;

        return S_OK;
    }

    virtual HRESULT GetItem(const Node *pNode, T* ppItem)
    {
        if (pNode == nullptr || ppItem == nullptr)
        {
            return E_POINTER;
        }

        *ppItem = pNode->item;
        return S_OK;
    }

    // RemoveItem:
    // Removes a node and optionally returns the item.
    // ppItem can be nullptr.
    virtual HRESULT RemoveItem(Node *pNode, T *ppItem)
    {
        if (pNode == nullptr)
        {
            return E_POINTER;
        }

        assert(pNode != &m_anchor); // We should never try to remove the anchor node.
        if (pNode == &m_anchor)
        {
            return E_INVALIDARG;
        }


        T item;

        // The next node's previous is this node's previous.
        pNode->next->prev = pNode->prev;

        // The previous node's next is this node's next.
        pNode->prev->next = pNode->next;

        item = pNode->item;
        delete pNode;

        m_count--;

        if (ppItem)
        {
            *ppItem = item;
        }

        return S_OK;
    }

public:

    List()
    {
        m_anchor.next = &m_anchor;
        m_anchor.prev = &m_anchor;

        m_count = 0;
    }

    virtual ~List()
    {
        Clear();
    }

    // Insertion functions
    HRESULT InsertBack(T item)
    {
        return InsertAfter(item, m_anchor.prev);
    }


    HRESULT InsertFront(T item)
    {
        return InsertAfter(item, &m_anchor);
    }

    HRESULT InsertPos(POSITION pos, T item)
    {
        if (pos.pNode == nullptr)
        {
            return InsertBack(item);
        }

        return InsertAfter(item, pos.pNode->prev);
    }

    // RemoveBack: Removes the tail of the list and returns the value.
    // ppItem can be nullptr if you don't want the item back. (But the method does not release the item.)
    HRESULT RemoveBack(T *ppItem)
    {
        if (IsEmpty())
        {
            return E_FAIL;
        }
        else
        {
            return RemoveItem(Back(), ppItem);
        }
    }

    // RemoveFront: Removes the head of the list and returns the value.
    // ppItem can be nullptr if you don't want the item back. (But the method does not release the item.)
    HRESULT RemoveFront(T *ppItem)
    {
        if (IsEmpty())
        {
            return E_FAIL;
        }
        else
        {
            return RemoveItem(Front(), ppItem);
        }
    }

    // GetBack: Gets the tail item.
    HRESULT GetBack(T *ppItem)
    {
        if (IsEmpty())
        {
            return E_FAIL;
        }
        else
        {
            return GetItem(Back(), ppItem);
        }
    }

    // GetFront: Gets the front item.
    HRESULT GetFront(T *ppItem)
    {
        if (IsEmpty())
        {
            return E_FAIL;
        }
        else
        {
            return GetItem(Front(), ppItem);
        }
    }


    // GetCount: Returns the number of items in the list.
    DWORD GetCount() const { return m_count; }

    bool IsEmpty() const
    {
        return (GetCount() == 0);
    }

    // Clear: Takes a functor object whose operator()
    // frees the object on the list.
    template <class FN>
    void Clear(FN& clear_fn)
    {
        Node *n = m_anchor.next;

        // Delete the nodes
        while (n != &m_anchor)
        {
            clear_fn(n->item);

            Node *tmp = n->next;
            delete n;
            n = tmp;
        }

        // Reset the anchor to point at itself
        m_anchor.next = &m_anchor;
        m_anchor.prev = &m_anchor;

        m_count = 0;
    }

    // Clear: Clears the list. (Does not delete or release the list items.)
    virtual void Clear()
    {
        NoOp<T> clearOp;
        Clear<>(clearOp);
    }


    // Enumerator functions

    POSITION FrontPosition()
    {
        if (IsEmpty())
        {
            return POSITION(nullptr);
        }
        else
        {
            return POSITION(Front());
        }
    }

    POSITION EndPosition() const
    {
        return POSITION();
    }

    HRESULT GetItemPos(POSITION pos, T *ppItem)
    {
        if (pos.pNode)
        {
            return GetItem(pos.pNode, ppItem);
        }
        else
        {
            return E_FAIL;
        }
    }

    POSITION Next(const POSITION pos)
    {
        if (pos.pNode && (pos.pNode->next != &m_anchor))
        {
            return POSITION(pos.pNode->next);
        }
        else
        {
            return POSITION(nullptr);
        }
    }

    // Remove an item at a position.
    // The item is returns in ppItem, unless ppItem is nullptr.
    // NOTE: This method invalidates the POSITION object.
    HRESULT Remove(POSITION& pos, T *ppItem)
    {
        if (pos.pNode)
        {
            // Remove const-ness temporarily...
            Node *pNode = const_cast<Node*>(pos.pNode);

            pos = POSITION();

            return RemoveItem(pNode, ppItem);
        }
        else
        {
            return E_INVALIDARG;
        }
    }

};



// Typical functors for Clear method.

// ComAutoRelease: Releases COM pointers.
// MemDelete: Deletes pointers to new'd memory.

class ComAutoRelease
{
public:
    void operator()(IUnknown *p)
    {
        if (p)
        {
            p->Release();
        }
    }
};

class MemDelete
{
public:
    void operator()(void *p)
    {
        if (p)
        {
            delete p;
        }
    }
};


// ComPtrList class
// Derived class that makes it safer to store COM pointers in the List<> class.
// It automatically AddRef's the pointers that are inserted onto the list
// (unless the insertion method fails).
//
// T must be a COM interface type.
// example: ComPtrList<IUnknown>
//
// NULLABLE: If true, client can insert nullptr pointers. This means GetItem can
// succeed but return a nullptr pointer. By default, the list does not allow nullptr
// pointers.

#ifdef _MSC_VER
#pragma warning(push)
#pragma warning(disable: 4127) // constant expression
#endif

template <class T, bool NULLABLE = FALSE>
class ComPtrList : public List<T*>
{
public:

    typedef T* Ptr;

    void Clear()
    {
        ComAutoRelease car;
        List<Ptr>::Clear(car);
    }

    ~ComPtrList()
    {
        Clear();
    }

protected:
    HRESULT InsertAfter(Ptr item, Node *pBefore)
    {
        // Do not allow nullptr item pointers unless NULLABLE is true.
        if (item == nullptr && !NULLABLE)
        {
            return E_POINTER;
        }

        if (item)
        {
            item->AddRef();
        }

        HRESULT hr = List<Ptr>::InsertAfter(item, pBefore);
        if (FAILED(hr) && item != nullptr)
        {
            item->Release();
        }
        return hr;
    }

    HRESULT GetItem(const Node *pNode, Ptr* ppItem)
    {
        Ptr pItem = nullptr;

        // The base class gives us the pointer without AddRef'ing it.
        // If we return the pointer to the caller, we must AddRef().
        HRESULT hr = List<Ptr>::GetItem(pNode, &pItem);
        if (SUCCEEDED(hr))
        {
            assert(pItem || NULLABLE);
            if (pItem)
            {
                *ppItem = pItem;
                (*ppItem)->AddRef();
            }
        }
        return hr;
    }

    HRESULT RemoveItem(Node *pNode, Ptr *ppItem)
    {
        // ppItem can be nullptr, but we need to get the
        // item so that we can release it.

        // If ppItem is not nullptr, we will AddRef it on the way out.

        Ptr pItem = nullptr;

        HRESULT hr = List<Ptr>::RemoveItem(pNode, &pItem);

        if (SUCCEEDED(hr))
        {
            assert(pItem || NULLABLE);
            if (ppItem && pItem)
            {
                *ppItem = pItem;
                (*ppItem)->AddRef();
            }

            if (pItem)
            {
                pItem->Release();
                pItem = nullptr;
            }
        }

        return hr;
    }
};

#ifdef _MSC_VER
#pragma warning(pop)
#endif

/* Be sure to declare webcam device capability in manifest
  For better media capture support, add the following snippet with correct module name to the project manifest
    (videoio needs DLL activation class factoryentry points):
  <Extensions>
    <Extension Category="windows.activatableClass.inProcessServer">
      <InProcessServer>
        <Path>modulename</Path>
        <ActivatableClass ActivatableClassId="cv.MediaSink" ThreadingModel="both" />
      </InProcessServer>
    </Extension>
  </Extensions>*/

extern const __declspec(selectany) WCHAR RuntimeClass_CV_MediaSink[] = L"cv.MediaSink";

class MediaSink :
#ifdef WINRT
    public Microsoft::WRL::RuntimeClass<
    Microsoft::WRL::RuntimeClassFlags< Microsoft::WRL::RuntimeClassType::WinRtClassicComMix >,
    Microsoft::WRL::Implements<ABI::Windows::Media::IMediaExtension>,
    IMFMediaSink,
    IMFClockStateSink,
    Microsoft::WRL::FtmBase,
    CBaseAttributes<>>
#else
    public IMFMediaSink, public IMFClockStateSink, public CBaseAttributes<>
#endif
{
#ifdef WINRT
    InspectableClass(RuntimeClass_CV_MediaSink, BaseTrust)
public:
#else
public:
    ULONG STDMETHODCALLTYPE AddRef()
    {
        return InterlockedIncrement(&m_cRef);
    }
    ULONG STDMETHODCALLTYPE Release()
    {
        ULONG cRef = InterlockedDecrement(&m_cRef);
        if (cRef == 0)
        {
            delete this;
        }
        return cRef;
    }
#if defined(_MSC_VER) && _MSC_VER >= 1700  // '_Outptr_result_nullonfailure_' SAL is avaialable since VS 2012
    STDMETHOD(QueryInterface)(REFIID riid, _Outptr_result_nullonfailure_ void **ppv)
#else
    STDMETHOD(QueryInterface)(REFIID riid, void **ppv)
#endif
    {
        if (ppv == nullptr) {
            return E_POINTER;
        }
        (*ppv) = nullptr;
        HRESULT hr = S_OK;
        if (riid == IID_IUnknown ||
            riid == IID_IMFMediaSink) {
            (*ppv) = static_cast<IMFMediaSink*>(this);
            AddRef();
        } else if (riid == IID_IMFClockStateSink) {
            (*ppv) = static_cast<IMFClockStateSink*>(this);
            AddRef();
        } else if (riid == IID_IMFAttributes) {
            (*ppv) = static_cast<IMFAttributes*>(this);
            AddRef();
        } else {
            hr = E_NOINTERFACE;
        }

        return hr;
    }
#endif
    MediaSink() : m_IsShutdown(false), m_llStartTime(0) {
        CBaseAttributes<>::Initialize(0U);
        InitializeCriticalSectionEx(&m_critSec, 3000, 0);
        DebugPrintOut(L"MediaSink::MediaSink\n");
    }

    virtual ~MediaSink() {
        DebugPrintOut(L"MediaSink::~MediaSink\n");
        DeleteCriticalSection(&m_critSec);
        assert(m_IsShutdown);
    }
    HRESULT CheckShutdown() const
    {
        if (m_IsShutdown)
        {
            return MF_E_SHUTDOWN;
        }
        else
        {
            return S_OK;
        }
    }
#ifdef WINRT
    STDMETHODIMP SetProperties(ABI::Windows::Foundation::Collections::IPropertySet *pConfiguration)
    {
        HRESULT hr = S_OK;
        if (pConfiguration) {
            Microsoft::WRL::ComPtr<IInspectable> spInsp;
            Microsoft::WRL::ComPtr<ABI::Windows::Foundation::Collections::IMap<HSTRING, IInspectable *>> spSetting;
            Microsoft::WRL::ComPtr<ABI::Windows::Foundation::IPropertyValue> spPropVal;
            Microsoft::WRL::ComPtr<ABI::Windows::Media::MediaProperties::IMediaEncodingProperties> pMedEncProps;
            UINT32 uiType = ABI::Windows::Media::Capture::MediaStreamType_VideoPreview;

            hr = pConfiguration->QueryInterface(IID_PPV_ARGS(&spSetting));
            if (FAILED(hr)) {
                hr = E_FAIL;
            }

            if (SUCCEEDED(hr)) {
                hr = spSetting->Lookup(Microsoft::WRL::Wrappers::HStringReference(MF_PROP_SAMPLEGRABBERCALLBACK).Get(), spInsp.ReleaseAndGetAddressOf());
                if (FAILED(hr)) {
                    hr = E_INVALIDARG;
                }
                if (SUCCEEDED(hr)) {
                    hr = SetUnknown(MF_MEDIASINK_SAMPLEGRABBERCALLBACK, spInsp.Get());
                }
            }
            if (SUCCEEDED(hr)) {
                hr = spSetting->Lookup(Microsoft::WRL::Wrappers::HStringReference(MF_PROP_VIDTYPE).Get(), spInsp.ReleaseAndGetAddressOf());
                if (FAILED(hr)) {
                    hr = E_INVALIDARG;
                }
                if (SUCCEEDED(hr)) {
                    if (SUCCEEDED(hr = spInsp.As(&spPropVal))) {
                        hr = spPropVal->GetUInt32(&uiType);
                    }
                }
            }
            if (SUCCEEDED(hr)) {
                hr = spSetting->Lookup(Microsoft::WRL::Wrappers::HStringReference(MF_PROP_VIDENCPROPS).Get(), spInsp.ReleaseAndGetAddressOf());
                if (FAILED(hr)) {
                    hr = E_INVALIDARG;
                }
                if (SUCCEEDED(hr)) {
                    hr = spInsp.As(&pMedEncProps);
                }
            }
            if (SUCCEEDED(hr)) {
                hr = SetMediaStreamProperties((ABI::Windows::Media::Capture::MediaStreamType)uiType, pMedEncProps.Get());
            }
        }

        return hr;
    }
    static DWORD GetStreamId(ABI::Windows::Media::Capture::MediaStreamType mediaStreamType)
    {
        return 3 - mediaStreamType;
    }
    static HRESULT AddAttribute(_In_ GUID guidKey, _In_ ABI::Windows::Foundation::IPropertyValue *pValue, _In_ IMFAttributes* pAttr)
    {
        HRESULT hr = S_OK;
        PROPVARIANT var;
        ABI::Windows::Foundation::PropertyType type;
        hr = pValue->get_Type(&type);
        ZeroMemory(&var, sizeof(var));

        if (SUCCEEDED(hr))
        {
            switch (type)
            {
            case ABI::Windows::Foundation::PropertyType_UInt8Array:
            {
                                                                      UINT32 cbBlob;
                                                                      BYTE *pbBlog = nullptr;
                                                                      hr = pValue->GetUInt8Array(&cbBlob, &pbBlog);
                                                                      if (SUCCEEDED(hr))
                                                                      {
                                                                          if (pbBlog == nullptr)
                                                                          {
                                                                              hr = E_INVALIDARG;
                                                                          }
                                                                          else
                                                                          {
                                                                              hr = pAttr->SetBlob(guidKey, pbBlog, cbBlob);
                                                                          }
                                                                      }
                                                                      CoTaskMemFree(pbBlog);
            }
                break;

            case ABI::Windows::Foundation::PropertyType_Double:
            {
                                                                  DOUBLE value;
                                                                  hr = pValue->GetDouble(&value);
                                                                  if (SUCCEEDED(hr))
                                                                  {
                                                                      hr = pAttr->SetDouble(guidKey, value);
                                                                  }
            }
                break;

            case ABI::Windows::Foundation::PropertyType_Guid:
            {
                                                                GUID value;
                                                                hr = pValue->GetGuid(&value);
                                                                if (SUCCEEDED(hr))
                                                                {
                                                                    hr = pAttr->SetGUID(guidKey, value);
                                                                }
            }
                break;

            case ABI::Windows::Foundation::PropertyType_String:
            {
                        Microsoft::WRL::Wrappers::HString value;
                        hr = pValue->GetString(value.GetAddressOf());
                                                                  if (SUCCEEDED(hr))
                                                                  {
                                                                      UINT32 len = 0;
                            LPCWSTR szValue = WindowsGetStringRawBuffer(value.Get(), &len);
                                                                      hr = pAttr->SetString(guidKey, szValue);
                                                                  }
            }
                break;

            case ABI::Windows::Foundation::PropertyType_UInt32:
            {
                                                                  UINT32 value;
                                                                  hr = pValue->GetUInt32(&value);
                                                                  if (SUCCEEDED(hr))
                                                                  {
                                                                      pAttr->SetUINT32(guidKey, value);
                                                                  }
            }
                break;

            case ABI::Windows::Foundation::PropertyType_UInt64:
            {
                                                                  UINT64 value;
                                                                  hr = pValue->GetUInt64(&value);
                                                                  if (SUCCEEDED(hr))
                                                                  {
                                                                      hr = pAttr->SetUINT64(guidKey, value);
                                                                  }
            }
                break;

            case ABI::Windows::Foundation::PropertyType_Inspectable:
            {
                                                                       Microsoft::WRL::ComPtr<IInspectable> value;
                                                                       hr = TYPE_E_TYPEMISMATCH;
                                                                       if (SUCCEEDED(hr))
                                                                       {
                                                                           pAttr->SetUnknown(guidKey, value.Get());
                                                                       }
            }
                break;

                // ignore unknown values
            }
        }

        return hr;
    }
    static HRESULT ConvertPropertiesToMediaType(_In_ ABI::Windows::Media::MediaProperties::IMediaEncodingProperties *pMEP, _Outptr_ IMFMediaType **ppMT)
    {
        HRESULT hr = S_OK;
        _ComPtr<IMFMediaType> spMT;
        Microsoft::WRL::ComPtr<ABI::Windows::Foundation::Collections::IMap<GUID, IInspectable*>> spMap;
        Microsoft::WRL::ComPtr<ABI::Windows::Foundation::Collections::IIterable<ABI::Windows::Foundation::Collections::IKeyValuePair<GUID, IInspectable*>*>> spIterable;
        Microsoft::WRL::ComPtr<ABI::Windows::Foundation::Collections::IIterator<ABI::Windows::Foundation::Collections::IKeyValuePair<GUID, IInspectable*>*>> spIterator;

        if (pMEP == nullptr || ppMT == nullptr)
        {
            return E_INVALIDARG;
        }
        *ppMT = nullptr;

                hr = pMEP->get_Properties(spMap.GetAddressOf());

        if (SUCCEEDED(hr))
        {
            hr = spMap.As(&spIterable);
        }
        if (SUCCEEDED(hr))
        {
            hr = spIterable->First(&spIterator);
        }
        if (SUCCEEDED(hr))
        {
            MFCreateMediaType(spMT.ReleaseAndGetAddressOf());
        }

        boolean hasCurrent = false;
        if (SUCCEEDED(hr))
        {
            hr = spIterator->get_HasCurrent(&hasCurrent);
        }

        while (hasCurrent)
        {
            Microsoft::WRL::ComPtr<ABI::Windows::Foundation::Collections::IKeyValuePair<GUID, IInspectable*> > spKeyValuePair;
            Microsoft::WRL::ComPtr<IInspectable> spValue;
            Microsoft::WRL::ComPtr<ABI::Windows::Foundation::IPropertyValue> spPropValue;
            GUID guidKey;

            hr = spIterator->get_Current(&spKeyValuePair);
            if (FAILED(hr))
            {
                break;
            }
            hr = spKeyValuePair->get_Key(&guidKey);
            if (FAILED(hr))
            {
                break;
            }
            hr = spKeyValuePair->get_Value(&spValue);
            if (FAILED(hr))
            {
                break;
            }
            hr = spValue.As(&spPropValue);
            if (FAILED(hr))
            {
                break;
            }
            hr = AddAttribute(guidKey, spPropValue.Get(), spMT.Get());
            if (FAILED(hr))
            {
                break;
            }

            hr = spIterator->MoveNext(&hasCurrent);
            if (FAILED(hr))
            {
                break;
            }
        }


        if (SUCCEEDED(hr))
        {
            Microsoft::WRL::ComPtr<IInspectable> spValue;
            Microsoft::WRL::ComPtr<ABI::Windows::Foundation::IPropertyValue> spPropValue;
            GUID guiMajorType;

            hr = spMap->Lookup(MF_MT_MAJOR_TYPE, spValue.GetAddressOf());

            if (SUCCEEDED(hr))
            {
                hr = spValue.As(&spPropValue);
            }
            if (SUCCEEDED(hr))
            {
                hr = spPropValue->GetGuid(&guiMajorType);
            }
            if (SUCCEEDED(hr))
            {
                if (guiMajorType != MFMediaType_Video && guiMajorType != MFMediaType_Audio)
                {
                    hr = E_UNEXPECTED;
                }
            }
        }

        if (SUCCEEDED(hr))
        {
            *ppMT = spMT.Detach();
        }

        return hr;
    }
            //this should be passed through SetProperties!
            HRESULT SetMediaStreamProperties(ABI::Windows::Media::Capture::MediaStreamType MediaStreamType,
        _In_opt_ ABI::Windows::Media::MediaProperties::IMediaEncodingProperties *mediaEncodingProperties)
    {
        HRESULT hr = S_OK;
        _ComPtr<IMFMediaType> spMediaType;

        if (MediaStreamType != ABI::Windows::Media::Capture::MediaStreamType_VideoPreview &&
            MediaStreamType != ABI::Windows::Media::Capture::MediaStreamType_VideoRecord &&
            MediaStreamType != ABI::Windows::Media::Capture::MediaStreamType_Audio)
        {
            return E_INVALIDARG;
        }

        RemoveStreamSink(GetStreamId(MediaStreamType));

        if (mediaEncodingProperties != nullptr)
        {
            _ComPtr<IMFStreamSink> spStreamSink;
            hr = ConvertPropertiesToMediaType(mediaEncodingProperties, &spMediaType);
            if (SUCCEEDED(hr))
            {
                hr = AddStreamSink(GetStreamId(MediaStreamType), nullptr, spStreamSink.GetAddressOf());
            }
            if (SUCCEEDED(hr)) {
                hr = SetUnknown(MF_MEDIASINK_PREFERREDTYPE, spMediaType.Detach());
            }
        }

        return hr;
    }
#endif
    //IMFMediaSink
    HRESULT STDMETHODCALLTYPE GetCharacteristics(
        /* [out] */ __RPC__out DWORD *pdwCharacteristics) {
        HRESULT hr;
        if (pdwCharacteristics == NULL) return E_INVALIDARG;
        EnterCriticalSection(&m_critSec);
        if (SUCCEEDED(hr = CheckShutdown())) {
                    //if had an activation object for the sink, shut down would be managed and MF_STREAM_SINK_SUPPORTS_ROTATION appears to be setable to TRUE
                    *pdwCharacteristics = MEDIASINK_FIXED_STREAMS;// | MEDIASINK_REQUIRE_REFERENCE_MEDIATYPE;
        }
        LeaveCriticalSection(&m_critSec);
        DebugPrintOut(L"MediaSink::GetCharacteristics: HRESULT=%i\n", hr);
        return hr;
    }

    HRESULT STDMETHODCALLTYPE AddStreamSink(
        DWORD dwStreamSinkIdentifier, IMFMediaType * /*pMediaType*/, IMFStreamSink **ppStreamSink) {
        _ComPtr<IMFStreamSink> spMFStream;
        _ComPtr<ICustomStreamSink> pStream;
        EnterCriticalSection(&m_critSec);
        HRESULT hr = CheckShutdown();

        if (SUCCEEDED(hr))
        {
            hr = GetStreamSinkById(dwStreamSinkIdentifier, &spMFStream);
        }

        if (SUCCEEDED(hr))
        {
            hr = MF_E_STREAMSINK_EXISTS;
        }
        else
        {
            hr = S_OK;
        }

        if (SUCCEEDED(hr))
        {
#ifdef WINRT
            pStream = Microsoft::WRL::Make<StreamSink>();
            if (pStream == nullptr) {
                hr = E_OUTOFMEMORY;
            }
            if (SUCCEEDED(hr))
                hr = pStream.As<IMFStreamSink>(&spMFStream);
#else
            StreamSink* pSink = new StreamSink();
            if (pSink) {
                hr = pSink->QueryInterface(IID_IMFStreamSink, (void**)spMFStream.GetAddressOf());
                if (SUCCEEDED(hr)) {
                    hr = spMFStream.As(&pStream);
                }
                if (FAILED(hr)) delete pSink;
            }
#endif
        }

        // Initialize the stream.
        _ComPtr<IMFAttributes> pAttr;
        if (SUCCEEDED(hr)) {
            hr = pStream.As(&pAttr);
        }
        if (SUCCEEDED(hr)) {
            hr = pAttr->SetUINT32(MF_STREAMSINK_ID, dwStreamSinkIdentifier);
            if (SUCCEEDED(hr)) {
                hr = pAttr->SetUnknown(MF_STREAMSINK_MEDIASINKINTERFACE, (IMFMediaSink*)this);
            }
        }
        if (SUCCEEDED(hr)) {
            hr = pStream->Initialize();
        }

        if (SUCCEEDED(hr))
        {
            ComPtrList<IMFStreamSink>::POSITION pos = m_streams.FrontPosition();
            ComPtrList<IMFStreamSink>::POSITION posEnd = m_streams.EndPosition();

            // Insert in proper position
            for (; pos != posEnd; pos = m_streams.Next(pos))
            {
                DWORD dwCurrId;
                _ComPtr<IMFStreamSink> spCurr;
                hr = m_streams.GetItemPos(pos, &spCurr);
                if (FAILED(hr))
                {
                    break;
                }
                hr = spCurr->GetIdentifier(&dwCurrId);
                if (FAILED(hr))
                {
                    break;
                }

                if (dwCurrId > dwStreamSinkIdentifier)
                {
                    break;
                }
            }

            if (SUCCEEDED(hr))
            {
                hr = m_streams.InsertPos(pos, spMFStream.Get());
            }
        }

        if (SUCCEEDED(hr))
        {
            *ppStreamSink = spMFStream.Detach();
        }
        LeaveCriticalSection(&m_critSec);
        DebugPrintOut(L"MediaSink::AddStreamSink: HRESULT=%i\n", hr);
        return hr;
    }

    HRESULT STDMETHODCALLTYPE RemoveStreamSink(DWORD dwStreamSinkIdentifier) {
        EnterCriticalSection(&m_critSec);
        HRESULT hr = CheckShutdown();
        ComPtrList<IMFStreamSink>::POSITION pos = m_streams.FrontPosition();
        ComPtrList<IMFStreamSink>::POSITION endPos = m_streams.EndPosition();
        _ComPtr<IMFStreamSink> spStream;

        if (SUCCEEDED(hr))
        {
            for (; pos != endPos; pos = m_streams.Next(pos))
            {
                hr = m_streams.GetItemPos(pos, &spStream);
                DWORD dwId;

                if (FAILED(hr))
                {
                    break;
                }

                hr = spStream->GetIdentifier(&dwId);
                if (FAILED(hr) || dwId == dwStreamSinkIdentifier)
                {
                    break;
                }
            }

            if (pos == endPos)
            {
                hr = MF_E_INVALIDSTREAMNUMBER;
            }
        }

        if (SUCCEEDED(hr))
        {
            hr = m_streams.Remove(pos, nullptr);
                    _ComPtr<ICustomStreamSink> spCustomSink;
#ifdef WINRT
                    spCustomSink = static_cast<StreamSink*>(spStream.Get());
                    hr = S_OK;
#else
                    hr = spStream.As(&spCustomSink);
#endif
                    if (SUCCEEDED(hr))
                        hr = spCustomSink->Shutdown();
        }
        LeaveCriticalSection(&m_critSec);
        DebugPrintOut(L"MediaSink::RemoveStreamSink: HRESULT=%i\n", hr);
        return hr;
    }

    HRESULT STDMETHODCALLTYPE GetStreamSinkCount(DWORD *pStreamSinkCount) {
        if (pStreamSinkCount == NULL)
        {
            return E_INVALIDARG;
        }

        EnterCriticalSection(&m_critSec);

        HRESULT hr = CheckShutdown();

        if (SUCCEEDED(hr))
        {
            *pStreamSinkCount = m_streams.GetCount();
        }

        LeaveCriticalSection(&m_critSec);
        DebugPrintOut(L"MediaSink::GetStreamSinkCount: HRESULT=%i\n", hr);
        return hr;
    }

    HRESULT STDMETHODCALLTYPE GetStreamSinkByIndex(
        DWORD dwIndex, IMFStreamSink **ppStreamSink) {
        if (ppStreamSink == NULL)
        {
            return E_INVALIDARG;
        }

        _ComPtr<IMFStreamSink> spStream;
        EnterCriticalSection(&m_critSec);
        DWORD cStreams = m_streams.GetCount();

        if (dwIndex >= cStreams)
        {
            return MF_E_INVALIDINDEX;
        }

        HRESULT hr = CheckShutdown();

        if (SUCCEEDED(hr))
        {
            ComPtrList<IMFStreamSink>::POSITION pos = m_streams.FrontPosition();
            ComPtrList<IMFStreamSink>::POSITION endPos = m_streams.EndPosition();
            DWORD dwCurrent = 0;

            for (; pos != endPos && dwCurrent < dwIndex; pos = m_streams.Next(pos), ++dwCurrent)
            {
                // Just move to proper position
            }

            if (pos == endPos)
            {
                hr = MF_E_UNEXPECTED;
            }
            else
            {
                hr = m_streams.GetItemPos(pos, &spStream);
            }
        }

        if (SUCCEEDED(hr))
        {
            *ppStreamSink = spStream.Detach();
        }
        LeaveCriticalSection(&m_critSec);
        DebugPrintOut(L"MediaSink::GetStreamSinkByIndex: HRESULT=%i\n", hr);
        return hr;
    }

    HRESULT STDMETHODCALLTYPE GetStreamSinkById(
        DWORD dwStreamSinkIdentifier, IMFStreamSink **ppStreamSink) {
        if (ppStreamSink == NULL)
        {
            return E_INVALIDARG;
        }

        EnterCriticalSection(&m_critSec);
        HRESULT hr = CheckShutdown();
        _ComPtr<IMFStreamSink> spResult;

        if (SUCCEEDED(hr))
        {
            ComPtrList<IMFStreamSink>::POSITION pos = m_streams.FrontPosition();
            ComPtrList<IMFStreamSink>::POSITION endPos = m_streams.EndPosition();

            for (; pos != endPos; pos = m_streams.Next(pos))
            {
                _ComPtr<IMFStreamSink> spStream;
                hr = m_streams.GetItemPos(pos, &spStream);
                DWORD dwId;

                if (FAILED(hr))
                {
                    break;
                }

                hr = spStream->GetIdentifier(&dwId);
                if (FAILED(hr))
                {
                    break;
                }
                else if (dwId == dwStreamSinkIdentifier)
                {
                    spResult = spStream;
                    break;
                }
            }

            if (pos == endPos)
            {
                hr = MF_E_INVALIDSTREAMNUMBER;
            }
        }

        if (SUCCEEDED(hr))
        {
            assert(spResult);
            *ppStreamSink = spResult.Detach();
        }
        LeaveCriticalSection(&m_critSec);
        DebugPrintOut(L"MediaSink::GetStreamSinkById: HRESULT=%i\n", hr);
        return hr;
    }

    HRESULT STDMETHODCALLTYPE SetPresentationClock(
        IMFPresentationClock *pPresentationClock) {
        EnterCriticalSection(&m_critSec);

        HRESULT hr = CheckShutdown();

        // If we already have a clock, remove ourselves from that clock's
        // state notifications.
        if (SUCCEEDED(hr)) {
            if (m_spClock) {
                hr = m_spClock->RemoveClockStateSink(this);
            }
        }

        // Register ourselves to get state notifications from the new clock.
        if (SUCCEEDED(hr)) {
            if (pPresentationClock) {
                hr = pPresentationClock->AddClockStateSink(this);
            }
        }

        _ComPtr<IMFSampleGrabberSinkCallback> pSampleCallback;
        if (SUCCEEDED(hr)) {
            // Release the pointer to the old clock.
            // Store the pointer to the new clock.
            m_spClock = pPresentationClock;
            hr = GetUnknown(MF_MEDIASINK_SAMPLEGRABBERCALLBACK, IID_IMFSampleGrabberSinkCallback, (LPVOID*)pSampleCallback.GetAddressOf());
        }
        LeaveCriticalSection(&m_critSec);
        if (SUCCEEDED(hr))
            hr = pSampleCallback->OnSetPresentationClock(pPresentationClock);
        DebugPrintOut(L"MediaSink::SetPresentationClock: HRESULT=%i\n", hr);
        return hr;
    }

    HRESULT STDMETHODCALLTYPE GetPresentationClock(
        IMFPresentationClock **ppPresentationClock) {
        if (ppPresentationClock == NULL) {
            return E_INVALIDARG;
        }

        EnterCriticalSection(&m_critSec);

        HRESULT hr = CheckShutdown();

        if (SUCCEEDED(hr)) {
            if (!m_spClock) {
                hr = MF_E_NO_CLOCK; // There is no presentation clock.
            } else {
                // Return the pointer to the caller.
                hr = m_spClock.CopyTo(ppPresentationClock);
            }
        }
        LeaveCriticalSection(&m_critSec);
        DebugPrintOut(L"MediaSink::GetPresentationClock: HRESULT=%i\n", hr);
        return hr;
    }

    HRESULT STDMETHODCALLTYPE Shutdown(void) {
        EnterCriticalSection(&m_critSec);

        HRESULT hr = CheckShutdown();

        if (SUCCEEDED(hr)) {
            ForEach(m_streams, ShutdownFunc());
            m_streams.Clear();
            m_spClock.ReleaseAndGetAddressOf();

                    _ComPtr<IMFMediaType> pType;
                    hr = CBaseAttributes<>::GetUnknown(MF_MEDIASINK_PREFERREDTYPE, __uuidof(IMFMediaType), (LPVOID*)pType.GetAddressOf());
                    if (SUCCEEDED(hr)) {
            hr = DeleteItem(MF_MEDIASINK_PREFERREDTYPE);
                    }
            m_IsShutdown = true;
        }

        LeaveCriticalSection(&m_critSec);
        DebugPrintOut(L"MediaSink::Shutdown: HRESULT=%i\n", hr);
        return hr;
    }
    class ShutdownFunc
    {
    public:
        HRESULT operator()(IMFStreamSink *pStream) const
        {
                    _ComPtr<ICustomStreamSink> spCustomSink;
                    HRESULT hr;
#ifdef WINRT
                    spCustomSink = static_cast<StreamSink*>(pStream);
#else
                    hr = pStream->QueryInterface(IID_PPV_ARGS(spCustomSink.GetAddressOf()));
                    if (FAILED(hr)) return hr;
#endif
                    hr = spCustomSink->Shutdown();
                    return hr;
        }
    };

    class StartFunc
    {
    public:
        StartFunc(LONGLONG llStartTime)
            : _llStartTime(llStartTime)
        {
        }

        HRESULT operator()(IMFStreamSink *pStream) const
        {
                    _ComPtr<ICustomStreamSink> spCustomSink;
                    HRESULT hr;
#ifdef WINRT
                    spCustomSink = static_cast<StreamSink*>(pStream);
#else
                    hr = pStream->QueryInterface(IID_PPV_ARGS(spCustomSink.GetAddressOf()));
                    if (FAILED(hr)) return hr;
#endif
                    hr = spCustomSink->Start(_llStartTime);
                    return hr;
        }

        LONGLONG _llStartTime;
    };

    class StopFunc
    {
    public:
        HRESULT operator()(IMFStreamSink *pStream) const
        {
                    _ComPtr<ICustomStreamSink> spCustomSink;
                    HRESULT hr;
#ifdef WINRT
                    spCustomSink = static_cast<StreamSink*>(pStream);
#else
                    hr = pStream->QueryInterface(IID_PPV_ARGS(spCustomSink.GetAddressOf()));
                    if (FAILED(hr)) return hr;
#endif
                    hr = spCustomSink->Stop();
                    return hr;
        }
    };

    template <class T, class TFunc>
    HRESULT ForEach(ComPtrList<T> &col, TFunc fn)
    {
        ComPtrList<T>::POSITION pos = col.FrontPosition();
        ComPtrList<T>::POSITION endPos = col.EndPosition();
        HRESULT hr = S_OK;

        for (; pos != endPos; pos = col.Next(pos))
        {
            _ComPtr<T> spStream;

            hr = col.GetItemPos(pos, &spStream);
            if (FAILED(hr))
            {
                break;
            }

            hr = fn(spStream.Get());
        }

        return hr;
    }
    //IMFClockStateSink
    HRESULT STDMETHODCALLTYPE OnClockStart(
        MFTIME hnsSystemTime,
        LONGLONG llClockStartOffset) {
        EnterCriticalSection(&m_critSec);
        HRESULT hr = CheckShutdown();

        if (SUCCEEDED(hr))
        {
            // Start each stream.
            m_llStartTime = llClockStartOffset;
            hr = ForEach(m_streams, StartFunc(llClockStartOffset));
        }
        _ComPtr<IMFSampleGrabberSinkCallback> pSampleCallback;
        if (SUCCEEDED(hr))
            hr = GetUnknown(MF_MEDIASINK_SAMPLEGRABBERCALLBACK, IID_IMFSampleGrabberSinkCallback, (LPVOID*)pSampleCallback.GetAddressOf());
        LeaveCriticalSection(&m_critSec);
        if (SUCCEEDED(hr))
            hr = pSampleCallback->OnClockStart(hnsSystemTime, llClockStartOffset);
        DebugPrintOut(L"MediaSink::OnClockStart: HRESULT=%i\n", hr);
        return hr;
    }

    HRESULT STDMETHODCALLTYPE OnClockStop(
        MFTIME hnsSystemTime) {
        EnterCriticalSection(&m_critSec);
        HRESULT hr = CheckShutdown();

        if (SUCCEEDED(hr))
        {
            // Stop each stream
            hr = ForEach(m_streams, StopFunc());
        }
        _ComPtr<IMFSampleGrabberSinkCallback> pSampleCallback;
        if (SUCCEEDED(hr))
            hr = GetUnknown(MF_MEDIASINK_SAMPLEGRABBERCALLBACK, IID_IMFSampleGrabberSinkCallback, (LPVOID*)pSampleCallback.GetAddressOf());
        LeaveCriticalSection(&m_critSec);
        if (SUCCEEDED(hr))
            hr = pSampleCallback->OnClockStop(hnsSystemTime);
        DebugPrintOut(L"MediaSink::OnClockStop: HRESULT=%i\n", hr);
        return hr;
    }

    HRESULT STDMETHODCALLTYPE OnClockPause(
        MFTIME hnsSystemTime) {
        HRESULT hr;
        _ComPtr<IMFSampleGrabberSinkCallback> pSampleCallback;
        hr = GetUnknown(MF_MEDIASINK_SAMPLEGRABBERCALLBACK, IID_IMFSampleGrabberSinkCallback, (LPVOID*)pSampleCallback.GetAddressOf());
        if (SUCCEEDED(hr))
            hr = pSampleCallback->OnClockPause(hnsSystemTime);
        DebugPrintOut(L"MediaSink::OnClockPause: HRESULT=%i\n", hr);
        return hr;
    }

    HRESULT STDMETHODCALLTYPE OnClockRestart(
        MFTIME hnsSystemTime) {
           HRESULT hr;
        _ComPtr<IMFSampleGrabberSinkCallback> pSampleCallback;
        hr = GetUnknown(MF_MEDIASINK_SAMPLEGRABBERCALLBACK, IID_IMFSampleGrabberSinkCallback, (LPVOID*)pSampleCallback.GetAddressOf());
        if (SUCCEEDED(hr))
            hr = pSampleCallback->OnClockRestart(hnsSystemTime);
        DebugPrintOut(L"MediaSink::OnClockRestart: HRESULT=%i\n", hr);
        return hr;
    }

    HRESULT STDMETHODCALLTYPE OnClockSetRate(
        MFTIME hnsSystemTime,
        float flRate) {
           HRESULT hr;
        _ComPtr<IMFSampleGrabberSinkCallback> pSampleCallback;
        hr = GetUnknown(MF_MEDIASINK_SAMPLEGRABBERCALLBACK, IID_IMFSampleGrabberSinkCallback, (LPVOID*)pSampleCallback.GetAddressOf());
        if (SUCCEEDED(hr))
            hr = pSampleCallback->OnClockSetRate(hnsSystemTime, flRate);
        DebugPrintOut(L"MediaSink::OnClockSetRate: HRESULT=%i\n", hr);
        return hr;
    }
private:
#ifndef WINRT
    long m_cRef;
#endif
    CRITICAL_SECTION            m_critSec;
    bool                        m_IsShutdown;
    ComPtrList<IMFStreamSink>    m_streams;
    _ComPtr<IMFPresentationClock>    m_spClock;
    LONGLONG                        m_llStartTime;
};

#ifdef WINRT
ActivatableClass(MediaSink);
#endif