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

/*****************************************************************************
 *
 * Filename:
 * ---------
 *    wfcapi.c
 *
 * Project:
 * --------
 *    MAUI
 *
 * Description:
 * ------------
 *    MTK implemented OpenWF Composition.
 *    
 * Author:
 * -------
 * -------
 *
 *============================================================================
 *             HISTORY
 * Below this line, this part is controlled by ClearCase. DO NOT MODIFY!!
 *------------------------------------------------------------------------------
 * $Log$
 *
 * 01 23 2014 edwardyc.lin
 * removed!
 * 	.
 *
 * 01 23 2014 edwardyc.lin
 * removed!
 * 	.
 *
 * 11 12 2012 joey.pan
 * removed!
 * Fix MT6260 LCD build error.
 *
 * 11 07 2012 chrono.wu
 * removed!
 * .
 * 
 * 07 24 2012 haitao.shang
 * removed!
 * .
 *
 * 07 18 2012 haitao.shang
 * removed!
 * .
 *
 * 07 18 2012 haitao.shang
 * removed!
 * .
 *
 * 07 17 2012 haitao.shang
 * removed!
 * .
 *
 * 05 28 2012 jody.li
 * removed!
 * .
 *
 * 05 25 2012 jody.li
 * removed!
 * .
 *
 * 04 12 2012 xiaoyong.ye
 * removed!
 * Support ARGB6666 transform from DDv2 to LWF.
 *
 * 04 11 2012 xiaoyong.ye
 * removed!
 * Fix build error.
 *
 * 04 11 2012 xiaoyong.ye
 * removed!
 * Support ARGB6666 transform from DDv2 to LWF.
 *
 * 03 08 2012 yinli.liang
 * removed!
 * .
 *
 * 02 23 2012 yinli.liang
 * removed!
 * .
 *
 * 02 10 2012 haitao.shang
 * removed!
 * .
 *
 * 01 05 2012 xiaoyong.ye
 * removed!
 * Cancel the timer and blt the last blt request immediately if has in wfcDeactivate() for fast exit automode.
 *
 * 12 25 2011 xiaoyong.ye
 * removed!
 * Add pPort .
 *
 * 12 25 2011 xiaoyong.ye
 * removed!
 * BW adjust for MT6256 more than one layer in 3D MMI scenario.
 *
 * 12 08 2011 yinli.liang
 * removed!
 * .
 *
 * 11 10 2011 yinli.liang
 * removed!
 * .
 *
 * 11 03 2011 yinli.liang
 * removed!
 * .
 *
 * 10 27 2011 yinli.liang
 * removed!
 * Remove not used temp variable: source and sourceCfg
 *
 * 10 27 2011 yinli.liang
 * removed!
 * .
 *
 * 10 25 2011 xiaoyong.ye
 * removed!
 * Remove user_version_code for FlattenGetOwnership().
 *
 * 10 24 2011 xiaoyong.ye
 * removed!
 * To mask flatten_api.h with #if defined(__MTK_TARGET__) when building MoDIS, to avoid building error.
 *
 * 10 20 2011 xiaoyong.ye
 * removed!
 * .
 *
 * 10 14 2011 bin.han
 * removed!
 * .
 *
 * 10 12 2011 dong.guo
 * removed!
 * .
 *
 * 10 12 2011 dong.guo
 * removed!
 * .
 *
 * 09 06 2011 haitao.shang
 * removed!
 * .
 *
 * 09 02 2011 zifeng.qiu
 * removed!
 * .
 *
 * 08 10 2011 zifeng.qiu
 * removed!
 * .
 *
 * 08 04 2011 bin.han
 * removed!
 * .
 *
 * 07 26 2011 zifeng.qiu
 * removed!
 *   DDv2 On Modis Check In.
 *
 * 07 21 2011 bin.han
 * removed!
 * .
 *
 * 07 13 2011 bin.han
 * removed!
 * .
 *
 * 07 08 2011 bin.han
 * removed!
 * Fix LOW_COST
 *
 * 07 06 2011 bin.han
 * removed!
 * .
 *
 * 07 05 2011 zifeng.qiu
 * removed!
 * .
 *
 * 07 04 2011 bin.han
 * removed!
 * .
 *
 * 07 01 2011 bin.han
 * removed!
 * LOW_COST_SUPPORT
 *
 * 06 28 2011 tianshu.qiu
 * removed!
 * .
 *
 * 06 23 2011 bin.han
 * removed!
 * .
 *
 * 06 22 2011 bin.han
 * removed!
 * .
 *
 * 06 15 2011 bin.han
 * removed!
 * cleanup code and add comment
 *
 * 06 09 2011 zifeng.qiu
 * removed!
 * Add error handling for DDv2.
 *
 * 06 08 2011 bin.han
 * removed!
 * .
 *
 * 06 02 2011 matthew.chen
 * removed!
 * Check in slim-ed DDv2 to Maui
 *
 * 06 01 2011 bin.han
 * removed!
 * RAM size reduction
 *
 * 05 23 2011 zifeng.qiu
 * removed!
 * .
 *
 * 05 23 2011 zifeng.qiu
 * removed!
 * Revise timer-insert-mechanism.
 *
 * 05 20 2011 zifeng.qiu
 * removed!
 * .
 *
 * 05 18 2011 zifeng.qiu
 * removed!
 * Event Group Slim.
 *
 * 05 18 2011 zifeng.qiu
 * removed!
 * Event Group Slim.
 *
 * 05 13 2011 zifeng.qiu
 * removed!
 * .
 *
 * 05 13 2011 bin.han
 * removed!
 * .
 *
 * 05 12 2011 zifeng.qiu
 * removed!
 * .
 *
 * 05 11 2011 zifeng.qiu
 * removed!
 * Resolve lcd_sleep_in & out racing condition.
 *
 * 05 11 2011 tianshu.qiu
 * removed!
 * .
 *
 * 05 11 2011 tianshu.qiu
 * removed!
 * .
 *
 * 04 24 2011 tianshu.qiu
 * removed!
 * .
 *
 * 04 22 2011 tianshu.qiu
 * removed!
 * .
 *
 * 04 21 2011 bin.han
 * removed!
 * .
 *
 * 04 21 2011 bin.han
 * removed!
 * .
 *
 * 04 19 2011 matthew.chen
 * removed!
 * .
 *
 * 04 18 2011 tianshu.qiu
 * removed!
 * .
 *
 * 04 18 2011 matthew.chen
 * removed!
 * Fix potential racing issue for 1112MP by adding WFC API semaphore in WFC_Lock & WFC_Unlock.
 *
 * 04 15 2011 tianshu.qiu
 * removed!
 * .
 *
 * 04 15 2011 bin.han
 * removed!
 * .
 *
 * 04 15 2011 tianshu.qiu
 * removed!
 * .
 *
 * 04 14 2011 zifeng.qiu
 * removed!
 * .
 *
 * 04 11 2011 tianshu.qiu
 * removed!
 * .
 *
 * 04 08 2011 bin.han
 * removed!
 * .
 *
 * 04 07 2011 tianshu.qiu
 * removed!
 * .
 *
 * 04 01 2011 zifeng.qiu
 * removed!
 * .
 *
 * 03 18 2011 tianshu.qiu
 * removed!
 * .
 *
 * 03 15 2011 tianshu.qiu
 * removed!
 * .
 *
 * 03 14 2011 tianshu.qiu
 * removed!
 * .
 *
 * 03 14 2011 tianshu.qiu
 * removed!
 * .
 *
 * 03 12 2011 tianshu.qiu
 * removed!
 * .
 *
 * 03 11 2011 tianshu.qiu
 * removed!
 * .
 *
 * 03 09 2011 tianshu.qiu
 * removed!
 * .
 *
 * 03 08 2011 ct.fang
 * removed!
 * .
 *
 * 03 07 2011 chelun.tsai
 * removed!
 * wfd header move to hal.
 *
 * 03 05 2011 tianshu.qiu
 * removed!
 * .
 *
 * 03 04 2011 tianshu.qiu
 * removed!
 * .
 *
 * 03 03 2011 tianshu.qiu
 * removed!
 * .
 *
 * 03 02 2011 tianshu.qiu
 * removed!
 * .
 *
 * 03 02 2011 tianshu.qiu
 * removed!
 * .
 *
 * 02 23 2011 bin.han
 * removed!
 * .
 *
 * 02 18 2011 tianshu.qiu
 * removed!
 * .
 *
 * 02 18 2011 ct.fang
 * removed!
 * .
 *
 *------------------------------------------------------------------------------
 * Upper this line, this part is controlled by ClearCase. DO NOT MODIFY!!
 *============================================================================
 * Copyright (c) 2009 The Khronos Group Inc.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and/or associated documentation files (the
 * "Materials"), to deal in the Materials without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sublicense, and/or sell copies of the Materials, and to
 * permit persons to whom the Materials are furnished to do so, subject to
 * the following conditions:
 *
 * The above copyright notice and this permission notice shall be included
 * in all copies or substantial portions of the Materials.
 *
 * THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
 * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
 * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
 * MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS.
 */

/*! \ingroup wfc
 *  \file wfcapi.c
 *  \brief OpenWF Composition SI, API implementation.
 *
 *  For function documentations, see OpenWF Composition specification 1.0
 *
 *  The general layout of an API function is:
 *  - grab API mutex (lock API)
 *  - check parameter validity
 *  - invoke implementation function (WFD_...)
 *  - unlock API
 *  - return
 *
 */
/******************************************************************************
 * Include directives
 ******************************************************************************/
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>

#include <wfc\wfc.h>
#include <wfc\wfcext.h>

#include "common\owftypes.h"
#include "common\owfnativestream.h"
#include "common\owfimage.h"

#include "drv_features_display.h"
#include "drv_sw_features_display.h"

#include "drv_hisr.h"

#include "rgb_rotator_api.h"
#include "yuv_rotator_api.h"
#include "lcd_sw_inc.h"

#include "egl\eglext.h"
#include "wfd\inc\wfd.h"

#include "wfc\inc\wfc_internal.h"
#include "wfc\inc\wfc_mm_api.h"
#include "wfc\inc\wfc_internal_debug.h"

#include "debug\inc\lcd_catcher_log.h"

#include "wfd\inc\wfd_common.h"

#include "kal_release.h"

#if defined(__RF_DESENSE_TEST__)
#include "rf_desense_test.h"
#endif

#if defined(__MTK_TARGET__)
#include "flatten_api.h"
#endif

#if defined(__MTK_TARGET__) && defined(MT6256)
#include "emi_sw.h"
#endif

#define wfdGetError(x) WFD_ERROR_NONE

/******************************************************************************
 * Utilities
 ******************************************************************************/

#define GET_CONTEXT(c, h, x) \
    do { \
    c = (WFCContextConfig*)(h); \
    if (_wfc_check_handle((WFCHandle)(c)) == KAL_FALSE) \
        return (x); \
    } while (0)

#define GET_CONTEXT_NR(c, h) \
    do { \
    c = (WFCContextConfig*)(h); \
    if (_wfc_check_handle((WFCHandle)(c)) == KAL_FALSE) \
        return; \
    } while (0)

#define GET_ELEMENT(e, h, x) \
    do { \
    e = (WFCElementConfig*)(h); \
    if (_wfc_check_handle((WFCHandle)(e)) == KAL_FALSE) \
        return (x); \
    } while (0)

#define GET_ELEMENT_NR(e, h) \
    do { \
    e = (WFCElementConfig*)(h); \
    if (_wfc_check_handle((WFCHandle)(e)) == KAL_FALSE) \
        return; \
    } while (0)

/******************************************************************************
 * Macro definitions
 ******************************************************************************/


/******************************************************************************
 * Local type definitions
 ******************************************************************************/
typedef enum
{
    _WFC_FRAME_DONE_EVENT_CONTEXT_NONE  = 0,
    _WFC_FRAME_DONE_EVENT_CONTEXT_LCD_0 = 0x8000000,
    _WFC_FRAME_DONE_EVENT_CONTEXT_LCD_1 = 0x4000000,
    _WFC_FRAME_DONE_EVENT_CONTEXT_FRAME_BUFFER = 0x2000000,
    _WFC_FRAME_DONE_EVENT_CONTEXT_TVOUT = 0x1000000,
    _WFC_FRAME_DONE_EVENT_CONTEXT_ALL = 0xF000000
} _WFC_FRAME_DONE_EVENT_ENUM;


/******************************************************************************
 * Local variables
 ******************************************************************************/
//static OWF_MUTEX           mutex;

static volatile kal_bool _global_data_init = KAL_FALSE;

static volatile WFCDeviceConfig _wfc_device_cfg = {0};

static volatile WFCContextConfig _wfc_context_cfg_lcd_0;
#ifdef DUAL_LCD
static volatile WFCContextConfig _wfc_context_cfg_lcd_1;
#endif
static volatile WFCContextConfig _wfc_context_cfg_frame_buffer;

static volatile WFCSourceConfig _wfc_sources[WFC_MAX_SOURCE_NUMBER];
static volatile WFCElementConfig _wfc_elements[WFC_ELEMENT_MAX_COUNT];

static volatile WFCContextConfig_* _wfc_dbg_context_lcd0;
#ifdef DUAL_LCD
static volatile WFCContextConfig_* _wfc_dbg_context_lcd1;
#endif
//static volatile WFCContextConfig_* _wfc_dbg_context_frame_buffer;

static volatile WFCDbgStructure wfc_dbg_structure;

// TODO: [o] check if we can change to use a mutex or a enh mutex.
static kal_semid _wfc_commit_mutex = KAL_NILSEM_ID;
static kal_semid _wfc_source_mutex = KAL_NILSEM_ID;
volatile WFCboolean _wfc_committed_flag = WFC_FALSE; //Xiaoyong: flag to record the blt request in auto mode
// KeTing: The frame done event groups of every context
kal_eventgrpid _owf_event = KAL_NILEVENTGRP_ID;
extern kal_bool _timer_run_status;
/******************************************************************************
 * Local functions
 ******************************************************************************/
#if defined(WFC_DBG_SUPPORT)

#if !defined(__LOW_COST_SUPPORT_COMMON__) && !defined(__LOW_COST_SUPPORT_ULC__)
    #define WFC_DBG_ENTRY_CNT 32     
#else
    #define WFC_DBG_ENTRY_CNT 32      //Bin extend to debug
#endif

typedef struct
{
    WFCDbgIdEnum id;
    WFCuint      time;
    kal_taskid   taskid;
    WFCErrorCode wfcError;
    WFCuint      value0;
    WFCuint      value1;
    WFCuint      value2;
} WFCDbgCtrlBlk;

volatile static WFDuint _WFCDbgCnt = 0;
volatile static WFCDbgCtrlBlk _WFCDbgDat[WFC_DBG_ENTRY_CNT];

void wfcTrace(WFCDbgIdEnum id)
{
    kal_uint32 index;

    kal_uint32 mask = SaveAndSetIRQMask();
    index = _WFCDbgCnt;
    _WFCDbgCnt++;
    _WFCDbgCnt &= (WFC_DBG_ENTRY_CNT-1);
    RestoreIRQMask(mask);

    _WFCDbgDat[index].taskid = kal_get_task_self_id();
    _WFCDbgDat[index].id = id;
    _WFCDbgDat[index].wfcError = _wfc_device_cfg._lastErrorCode;
    _WFCDbgDat[index].time = drv_get_current_time();
    _WFCDbgDat[index].value0 = 0;
    _WFCDbgDat[index].value1 = 0;
    _WFCDbgDat[index].value2 = 0;
}

void wfcTrace3(WFCDbgIdEnum id, WFCuint value0, WFCuint value1, WFCuint value2)
{
  kal_uint32 index;

  kal_uint32 mask = SaveAndSetIRQMask();
  index = _WFCDbgCnt;
  _WFCDbgCnt++;
  _WFCDbgCnt &= (WFC_DBG_ENTRY_CNT-1);
  RestoreIRQMask(mask);

  _WFCDbgDat[index].id    = id;
  _WFCDbgDat[index].wfcError = _wfc_device_cfg._lastErrorCode;
  _WFCDbgDat[index].time  = drv_get_current_time();
  _WFCDbgDat[index].taskid  = kal_get_task_self_id();
  _WFCDbgDat[index].value0 = value0;
  _WFCDbgDat[index].value1 = value1;
  _WFCDbgDat[index].value2 = value2;
}
#endif


static void 
WFC_Commit_Lock(void)
{
    if (kal_query_systemInit() == KAL_TRUE)
    {
        return;
    }
    if (NULL  == _wfc_commit_mutex)
    {
        _wfc_commit_mutex = kal_create_sem("WFC_COMMIT", 1);
    }
    kal_take_sem(_wfc_commit_mutex, KAL_INFINITE_WAIT);
}

static void 
WFC_Commit_Unlock()
{
    if (kal_query_systemInit() == KAL_TRUE)
    {
        return;
    }
    if (NULL != _wfc_commit_mutex)
    {
        kal_give_sem(_wfc_commit_mutex);
    }
}

static void 
WFC_Source_Lock(void)
{
    if (kal_query_systemInit() == KAL_TRUE)
    {
        return;
    }

    if (NULL  == _wfc_source_mutex)
    {
        _wfc_source_mutex = kal_create_sem("WFC_SOURCE", 1);
    }

    kal_take_sem(_wfc_source_mutex, KAL_INFINITE_WAIT);
}

static void 
WFC_Source_Unlock()
{
    if (kal_query_systemInit() == KAL_TRUE)
    {
        //wfcTrace(WFCDBG____SEMA__UNLOCK_IN_EXCEPTION);
        return;
    }

    if (NULL != _wfc_source_mutex)
    {
        kal_give_sem(_wfc_source_mutex);
    }
}


static kal_bool _wfc_check_handle(WFCHandle handle)
{
    if (NULL == handle)
    {
        _wfc_set_error(WFC_ERROR_BAD_HANDLE);
        return KAL_FALSE;
    }
    return KAL_TRUE;
}

/**
 *  \status OK
 *  the return value is integer rotation angle (clockwise)
 */
static WFDint 
_wfc_convert_rotation_angle_to_int(WFCRotation rotation_angle)
{
#if 0
/* under construction !*/
/* under construction !*/
/* under construction !*/
/* under construction !*/
/* under construction !*/
/* under construction !*/
/* under construction !*/
/* under construction !*/
/* under construction !*/
/* under construction !*/
/* under construction !*/
/* under construction !*/
/* under construction !*/
/* under construction !*/
#endif
    return ((rotation_angle - WFC_ROTATION_0) * 90);
}

/**
 *  \status OK
 * The return value is TRANSPARENCY typedef for WFD
 */
static WFDbitfield 
_wfc_convert_transparency(WFCbitfield transparency)
{
    WFDbitfield ret = 0x0;

    //if (!(transparency & (~WFC_TRANSPARENCY_ELEMENT_GLOBAL_ALPHA)))
    if (transparency & WFC_TRANSPARENCY_ELEMENT_GLOBAL_ALPHA)
    {
        ret |= WFD_TRANSPARENCY_GLOBAL_ALPHA;
    }

    //if (!(transparency & (~WFC_TRANSPARENCY_SOURCE)))
    if (transparency & WFC_TRANSPARENCY_SOURCE)
    {
        ret |= WFD_TRANSPARENCY_SOURCE_ALPHA;
    }

    //if (!(transparency & (~WFC_TRANSPARENCY_SOURCE_COLOR_KEY_MTK)))
    if (transparency & WFC_TRANSPARENCY_SOURCE_COLOR_KEY_MTK)
    {
        ret |= WFD_TRANSPARENCY_SOURCE_COLOR;
    }

    return ret;
}



// KeTing: Change the context handle to wfc frame done event enum
static _WFC_FRAME_DONE_EVENT_ENUM
_wfc_convert_context_handle_to_frame_done_enum (WFCContextConfig *pContext)
{
    if (pContext == &_wfc_context_cfg_lcd_0)
    {
        return _WFC_FRAME_DONE_EVENT_CONTEXT_LCD_0;
    }
#ifdef DUAL_LCD
    else if (pContext == &_wfc_context_cfg_lcd_1)
    {
        return _WFC_FRAME_DONE_EVENT_CONTEXT_LCD_1;
    }
#endif
    else if (pContext == &_wfc_context_cfg_frame_buffer)
    {
        return _WFC_FRAME_DONE_EVENT_CONTEXT_FRAME_BUFFER;
    }
    else
    {
        return _WFC_FRAME_DONE_EVENT_CONTEXT_NONE;
    }
}


WFCboolean _wfc_check_element_inserted(WFCContextConfig* pContext, WFCElement element)
{
    kal_uint32 i = 0;
   if(pContext == NULL || element == NULL)
      return WFC_FALSE;
    
    for(i=0;i<WFC_CONTEXT_MAX_INSERTED_ELEMENT;i++)
    {
	    if (pContext->capturedRWAttrib->_insertedElements[i] == element)
	    {
			return WFC_TRUE;
	    }
	}

	 return WFC_FALSE;
}


void _wfc_rectangle_and(OWF_RECTANGLE* pRect1, OWF_RECTANGLE* pRect2, OWF_RECTANGLE* pRectResult)
{
    WFCint left, right, top, bottom, width, height;
    if ((pRect1->width == 0) || (pRect1->height == 0) || (pRect2->width == 0) || (pRect2->height == 0))
    {
        memset(pRectResult, 0, sizeof(OWF_RECTANGLE));
        return;
    }
    if (pRect1->x < pRect2->x)
        left = pRect2->x;
    else
        left = pRect1->x;
    if ((pRect1->x + pRect1->width) < (pRect2->x + pRect2->width))
        right = pRect1->x + pRect1->width;
    else
        right = pRect2->x + pRect2->width;
    if (left < right)
        width = right - left;
    else
        width = 0;
    if (pRect1->y < pRect2->y)
        top = pRect2->y;
    else
        top = pRect1->y;
    if ((pRect1->y + pRect1->height) < (pRect2->y + pRect2->height))
        bottom = pRect1->y + pRect1->height;
    else
        bottom = pRect2->y + pRect2->height;
    if (top < bottom)
        height = bottom - top;
    else
        height = 0;
    if ((width == 0) || (height == 0))
        pRectResult->x = pRectResult->y = pRectResult->width = pRectResult->height = 0;
    else
    {
        pRectResult->x = left;
        pRectResult->y = top;
        pRectResult->width = width;
        pRectResult->height = height;
    }
}


void _wfc_rectangle_or(OWF_RECTANGLE* pRect1, OWF_RECTANGLE* pRect2, OWF_RECTANGLE* pRectResult)
{
    WFCint left, right, top, bottom;
    if ((pRect1->width == 0) || (pRect1->height == 0))
    {
        memcpy(pRectResult, pRect2, sizeof(OWF_RECTANGLE));
        return;
    }
    if ((pRect2->width == 0) || (pRect2->height == 0))
    {
        memcpy(pRectResult, pRect1, sizeof(OWF_RECTANGLE));
        return;
    }
    if (pRect1->x < pRect2->x)
        left = pRect1->x;
    else
        left = pRect2->x;
    if ((pRect1->x + pRect1->width) < (pRect2->x + pRect2->width))
        right = pRect2->x + pRect2->width;
    else
        right = pRect1->x + pRect1->width;
    if (pRect1->y < pRect2->y)
        top = pRect1->y;
    else
        top = pRect2->y;
    if ((pRect1->y + pRect1->height) < (pRect2->y + pRect2->height))
        bottom = pRect2->y + pRect2->height;
    else
        bottom = pRect1->y + pRect1->height;
    pRectResult->x = left;
    pRectResult->y = top;
    pRectResult->width = right - left;
    pRectResult->height = bottom - top;
}

static void _wfc_invoke_callback(WFCContextConfig *pContext, WFCContextEventTypeMTK event)
{
    kal_uint32 i;

    // TODO: [o] set event here... 
    for (i = WFC_CONTEXT_GDI_CALLBACK_COUNT; i-- != 0; )
    {
        WFCCallbackType *pCallback = &(pContext->capturedRWAttrib->gdiCallbacks[i]);
        if ((event == pCallback->event) && 
            (NULL != pCallback->cbfunc))
        {
            pCallback->cbfunc(event, pCallback->cbparam);
        }
    }
    for (i = WFC_CONTEXT_MM_CALLBACK_COUNT; i-- != 0; )
    {
        WFCCallbackType *pCallback = &(pContext->capturedRWAttrib->mmCallbacks[i]);
        if ((event == pCallback->event) && 
            (NULL != pCallback->cbfunc))
        {
            pCallback->cbfunc(event, pCallback->cbparam);
        }
    }
}

/**
 *  \status OK
 * This function is as callback registed to WFD
 */
static void _wfc_engine_event_hdlr(WFDEventType event, void* param)
{
    kal_uint32 savedMask;
    WFCContextConfig* pContext = param;
	#if (!(defined (MT6250) || defined (MT6260) || defined (MT6261)))
    kal_uint32 bCallback = 0;
	#endif
    WFC_ASSERT(NULL != param);
    
    wfcTrace(WFCDBG____CALLBACK___________ENGINE);


    // callback to user (GDI or MM)
    _wfc_invoke_callback(pContext, WFC_CONTEXT_EVENT_COMPOSITION_FINISH_ALWAYS_CALLBACK_MTK);
    if (WFC_AUTONOMOUS_STATE_ON == pContext->_autonomousMode)
    {
        // after previous commit setting is latched,  the ROI can be restored and callback can be invoked
        if (pContext->_autoModeCommitLatched == WFC_TRUE)
        {
            pContext->capturedRWAttrib->destinationRect.x += pContext->_autoModeRoiRect.x - pContext->capturedRWAttrib->roiRect.x;
            pContext->capturedRWAttrib->destinationRect.y += pContext->_autoModeRoiRect.y - pContext->capturedRWAttrib->roiRect.y;
            pContext->capturedRWAttrib->destinationRect.width = pContext->_autoModeRoiRect.width;
            pContext->capturedRWAttrib->destinationRect.height = pContext->_autoModeRoiRect.height;
            pContext->capturedRWAttrib->roiRect = pContext->_autoModeRoiRect;
            _wfc_invoke_callback(pContext, WFC_CONTEXT_EVENT_COMPOSITION_FINISH_MTK);
					#if (!(defined (MT6250) || defined (MT6260) || defined (MT6261)))
                    bCallback = 1;
					#endif
			_wfc_committed_flag = WFC_FALSE; //Xiaoyong:clear the blt request in auto mode
        }
    }
    else
            {
                _wfc_invoke_callback(pContext, WFC_CONTEXT_EVENT_COMPOSITION_FINISH_MTK);
				#if (!(defined (MT6250) || defined (MT6260) || defined (MT6261)))
                bCallback = 1;
				#endif
            }

    // KeTing: Set to non-busy after all resources are free
    savedMask = SaveAndSetIRQMask();
    pContext->_busy = WFC_FALSE;
    RestoreIRQMask(savedMask);

    // KeTing: In fact, it donesn't matter to put before or after setting the busy flag
    // KeTing: Because the function is always called in drv_hisr and has the highest priority
    _wfc_set_context_frame_done_event(pContext, WFC_TRUE);

    if (WFC_AUTONOMOUS_STATE_ON == pContext->_autonomousMode)
    {
        // KeTing: Please invoke this function after de-assert busy flag
        _wfc_autonomous_frame_done_callback(pContext);
    }
	#if (!(defined (MT6250) || defined (MT6260) || defined (MT6261)))
    DDV2CatcherLogL3D4(TRACE_DDV2_RENDERING, DDV2_TRC_WFCENGINEEVENTHANDLER,
                                             drv_get_current_time(),
                                             (kal_uint32)kal_get_current_thread_ID(),
                                             (kal_uint32)(param),
                                             bCallback);
	#endif


}

static void _wfc_wait_until_wfd_not_busy(WFCContextConfig* pContext)
{
    kal_uint32 event_group;

    while(WFC_TRUE == _wfc_is_wfd_busy(pContext))
    {
        // KeTing: Note here is not only retrieve the target context frame done event
        // KeTing: This is because there may be other context occupy the same wfd device
        kal_retrieve_eg_events(_owf_event,
            (kal_uint32)(_WFC_FRAME_DONE_EVENT_CONTEXT_ALL),
            KAL_OR, &event_group, KAL_SUSPEND);

    }
}

// KeTing: Check if this wfd ening is used by some context in autonomous mode
static WFCboolean _wfc_is_engine_in_autonomous_mode(WFDDevice engine)
{
    // KeTing: Do not use "else" since lcd_0, lcd_1, and tvout may use the same engine
    // KeTing: We have to check all the contexts with the same engine
    if (engine == _wfc_context_cfg_lcd_0._engine && WFC_AUTONOMOUS_STATE_ON == _wfc_context_cfg_lcd_0._autonomousMode)
    {
        return WFC_TRUE;
    }
#ifdef DUAL_LCD
    if (engine == _wfc_context_cfg_lcd_1._engine && WFC_AUTONOMOUS_STATE_ON == _wfc_context_cfg_lcd_1._autonomousMode)
    {
        return WFC_TRUE;
    }
#endif
    // KeTing: None of the context with the same engine is in autonomous mode
    return WFC_FALSE;
}

// KeTing: Check if this wfd ening is used by some context in autonomous mode
static WFCboolean _wfc_is_context_in_autonomous_mode(WFCContext ctx)
{
    if ((WFCuint)ctx == (WFCuint)&_wfc_context_cfg_lcd_0 && WFC_AUTONOMOUS_STATE_ON == _wfc_context_cfg_lcd_0._autonomousMode)
    {
        return WFC_TRUE;
    }
#ifdef DUAL_LCD
    if ((WFCuint)ctx == (WFCuint)&_wfc_context_cfg_lcd_1 && WFC_AUTONOMOUS_STATE_ON == _wfc_context_cfg_lcd_1._autonomousMode)
    {
        return WFC_TRUE;
    }
#endif
    // KeTing: None of the context with the same engine is in autonomous mode
    return WFC_FALSE;
}


/******************************************************************************
 * WFC internal functions
 ******************************************************************************/

/**
 *  Record the first unread error code.
 *  \status OK
 */
void _wfc_set_error(WFCErrorCode error)
{
    if (WFC_ERROR_NONE == _wfc_device_cfg._lastErrorCode)
    {
        _wfc_device_cfg._lastErrorCode = error;
    }
    wfcTrace(WFCDBG_________________ERROR_HAPPEN);
}

// KeTing: Check if any context using the same wfd engine is busy
WFCboolean _wfc_is_wfd_busy(WFCContextConfig* pContext)
{
    WFD_DEVICE* pEngine = (WFD_DEVICE*)pContext->_engine;
    if (WFD_TRUE == pContext->_busy || WFD_TRUE == pEngine->busyFlag)
    {
        return WFC_TRUE;
    }
    else
    {
        kal_uint32 i;
        for (i = 0; i < WFC_CONTEXT_MAX_COUNT; i++)
        {
            WFCContextConfig *pOtherContext = (WFCContextConfig *)(_wfc_device_cfg._createdContexts[i]);
            if (WFC_TRUE == pOtherContext->_busy && pOtherContext->_engine == (WFCHandle)pEngine)
            {
                return WFC_TRUE;
            }
        }
        return WFC_FALSE;
    }
}

// KeTing: To set or clear the target context WFC frame done event
// KeTing: If setEvent == true, set the frame done event
// KeTing: Else clear the event
void _wfc_set_context_frame_done_event(WFCContextConfig *pContext, WFCboolean setEvent)
{
    kal_uint32 frm_done_event_bit_id;

    frm_done_event_bit_id = (kal_uint32)(_wfc_convert_context_handle_to_frame_done_enum(pContext));

    if (WFC_TRUE == setEvent)
    {
        kal_set_eg_events(_owf_event,
            frm_done_event_bit_id,
            KAL_OR);
    }
    else
    {
        kal_set_eg_events(_owf_event,
            ~frm_done_event_bit_id,
            KAL_AND);
    }
}

#if defined (__GOVL_SUPPORT__)
static kal_uint32 gdi_handle = 0;
static void flatten_api_cb(void *flatten_api_cb_para)
{ 
    _wfc_engine_event_hdlr(WFD_EVENT_DATA_TRANSFER_COMPLETE_MTK,  flatten_api_cb_para);
    if (FLATTEN_RESULT_OK != FlattenReleaseOwnership(gdi_handle))
    {
        ASSERT(0);
    }
}
#endif
/** 
 *  To config the WFD for compose and activate
 *  Please note this function provides no protection and assumes the caller will lock
 *  the needed informtion. Also the parameter checking should be the resposibility of
 *  the caller.
 *  \status XX
 */
void _wfc_config_wfd_and_commit(WFCContextConfig* pContext, WFCboolean wait)
{
    int i;
    WFD_DEVICE* pEngine = NULL;
    WFD_PORT* pPort = NULL;
    OWF_RECTANGLE Rect;

    pEngine = (WFD_DEVICE*) pContext->_engine;
    pPort = (WFD_PORT*) pContext->_port;

    DDV2CatcherLogL3D8(TRACE_DDV2_RENDERING, DDV2_TRC_WFCCONFIGWFDANDCOMMIT,
                                             drv_get_current_time(),
                                             (kal_uint32)kal_get_current_thread_ID(),
                                             (kal_uint32)(pContext),
                                             (kal_uint32)(pEngine),
                                             (kal_uint32)(pPort),
                                             pContext->type,
                                             wait, 0);
    
    // The following section is used for RF-Desense test. 
    // When the return value of rf_desense_get_curr_mode() is NO_LCD_UPDATE, we bypass blt and flatten and call callback function directly.
    // When the return value of rf_desense_get_curr_mode() is NO_LCM_UPDATE, we only bypass blt operations.
#if defined(__RF_DESENSE_TEST__)
    if (RF_DESENSE_MODE_NO_LCD_UPDATE == rf_desense_get_curr_mode())
    {
        pContext->_autoModeCommitLatched = WFC_TRUE;
        _wfc_engine_event_hdlr(WFD_EVENT_DATA_TRANSFER_COMPLETE_MTK, (void*)(pContext));
        kal_prompt_trace(MOD_MED, "[RF Desense] [RF Desense No LCD Update] Pass!\n");
        return;
    }
    
    if (RF_DESENSE_MODE_NO_LCM_UPDATE == rf_desense_get_curr_mode())
    {
        if (WFC_CONTEXT_TYPE_ON_SCREEN == pContext->type)
        {
            pContext->_autoModeCommitLatched = WFC_TRUE;
            _wfc_engine_event_hdlr(WFD_EVENT_DATA_TRANSFER_COMPLETE_MTK, (void*)(pContext));
            kal_prompt_trace(MOD_MED, "[RF Desense] [RF Desense No LCM Update] Pass!\n");
            return;
        }
    }
#endif //#if defined(__RF_DESENSE_TEST__)

#if defined (__GOVL_SUPPORT__)
if (WFC_CONTEXT_TYPE_OFF_SCREEN == pContext->type)
{
    FlattenResultEnum flatten_result;
    FlattenCtrlStruct flatten_ctrl_config = {0};

    //Get User Handle
    if (0 == gdi_handle) 
    {
        gdi_handle = FlattenGetUserHandle();
    }

    // Get Flatten API's Ownership
    {
        flatten_result = FlattenGetOwnership(gdi_handle, KAL_TRUE, KAL_FALSE);
        if (FLATTEN_RESULT_OK != flatten_result)
        {
            ASSERT(0);
        }
    } 
   
    // Config Flatten Ctrl...
    {
        //OWF_RECTANGLE TargetRect;
        // background color
        //pPort->config.backgroundColor[0] = (pContext->capturedRWAttrib->bgColor&0xFF000000)>>24;   // A
        //pPort->config.backgroundColor[1] = (pContext->capturedRWAttrib->bgColor&0x00FF0000)>>16;   // R
        //pPort->config.backgroundColor[2] = (pContext->capturedRWAttrib->bgColor&0x0000FF00)>>8;    // G
        //pPort->config.backgroundColor[3] = (pContext->capturedRWAttrib->bgColor&0x000000FF);       // B
        flatten_ctrl_config.bgColor = pContext->capturedRWAttrib->bgColor;

        Rect = pContext->capturedRWAttrib->roiRect;

        //memcpy(pPort->config.roiDestRectangle, &Rect, sizeof(WFDint)*4);
        flatten_ctrl_config.roiRect_x = Rect.x;
        flatten_ctrl_config.roiRect_y = Rect.y;
        flatten_ctrl_config.roiRect_width = Rect.width;
        flatten_ctrl_config.roiRect_height = Rect.height;

        Rect.x = (WFDint) pContext->capturedRWAttrib->destinationRect.x + Rect.x - pContext->capturedRWAttrib->roiRect.x;
        Rect.y = (WFDint) pContext->capturedRWAttrib->destinationRect.y + Rect.y - pContext->capturedRWAttrib->roiRect.y;

        //memcpy(pPort->config.partialRefreshRectangle, &Rect, sizeof(WFDint)*4);
        flatten_ctrl_config.destinationRect_x = Rect.x;
        flatten_ctrl_config.destinationRect_y = Rect.y;
        flatten_ctrl_config.destinationRect_width = Rect.width;
        flatten_ctrl_config.destinationRect_height = Rect.height;

        //pPort->config.syncEnable = (WFDboolean)(pContext->capturedRWAttrib->enableVsync);
        //pPort->config.blockModeReq = (WFDboolean)(wait);
        flatten_ctrl_config.blocking_req = (kal_bool)(wait);

        // config memout's output image
        {
            OWF_IMAGE target_image = (pContext->capturedRWAttrib->memOutTarget.image);
            FLATTEN_PIXEL_FORMAT flatten_ctrl_format;
            //pPort->config.targetImage = &(pContext->capturedRWAttrib->memOutTarget.image);
            flatten_ctrl_config.memOut_image_width = target_image.width;
            flatten_ctrl_config.memOut_image_height = target_image.height;
            flatten_ctrl_config.memOut_image_stride = target_image.stride;
            flatten_ctrl_config.memOut_image_pixelSize = target_image.pixelSize;
            switch(target_image.format.pixelFormat)
            {
                case OWF_IMAGE_ARGB8888: flatten_ctrl_format = FLATTEN_IMAGE_ARGB8888; break; 
                case OWF_IMAGE_XRGB8888: flatten_ctrl_format = FLATTEN_IMAGE_XRGB8888; break; 
                case OWF_IMAGE_RGB888: flatten_ctrl_format = FLATTEN_IMAGE_RGB888; break; 
                case OWF_IMAGE_BGR888: flatten_ctrl_format = FLATTEN_IMAGE_BGR888; break; 
                case OWF_IMAGE_RGB565: flatten_ctrl_format = FLATTEN_IMAGE_RGB565; break; 
                case OWF_IMAGE_L32: flatten_ctrl_format = FLATTEN_IMAGE_L32; break; 
                case OWF_IMAGE_L16: flatten_ctrl_format = FLATTEN_IMAGE_L16; break; 
                case OWF_IMAGE_L8: flatten_ctrl_format = FLATTEN_IMAGE_L8; break; 
                case OWF_IMAGE_L1: flatten_ctrl_format = FLATTEN_IMAGE_L1; break; 
                case OWF_IMAGE_UYVY: flatten_ctrl_format = FLATTEN_IMAGE_UYVY; break; 
                case OWF_IMAGE_ARGB6666: flatten_ctrl_format = FLATTEN_IMAGE_ARGB6666; break; 
                default: flatten_ctrl_format = FLATTEN_IMAGE_NOT_SUPPORTED; break; 
            }
            flatten_ctrl_config.memOut_image_format_pixelFormat = flatten_ctrl_format;
            flatten_ctrl_config.memOut_image_format_linear = (kal_bool)(target_image.format.linear);
            flatten_ctrl_config.memOut_image_format_premultiplied = (kal_bool)(target_image.format.premultiplied);
            flatten_ctrl_config.memOut_image_format_rowPadding = target_image.format.rowPadding;
            flatten_ctrl_config.memOut_image_datamax = target_image.dataMax;
            flatten_ctrl_config.memOut_image_alpha = target_image.alpha;
            flatten_ctrl_config.memOut_image_data = target_image.data;
        }

        // callback functions...
        //pPort->config.updateDoneCallback[0] = (WFDuint) _wfc_engine_event_hdlr;
        //pPort->config.updateDoneCallback[1] = (WFDuint) pContext;
        if (KAL_FALSE == (kal_bool)wait)
        {
            flatten_ctrl_config.flatten_nonblocking_callback = flatten_api_cb;
            flatten_ctrl_config.cbparam = (void *)pContext;
        } 
        // palette table address
        //pPort->config.paletteTable = (WFDuint) pContext->capturedRWAttrib->paletteTable;
        flatten_ctrl_config.paletteTable = (kal_uint32)pContext->capturedRWAttrib->paletteTable;

    } 

    // Config Flatten Layer...
    {
        kal_uint32 i;

        // Clear WFD port setting
        //memset(pPort->config.bindedPipelines, 0, sizeof(pPort->config.bindedPipelines));
        for (i = 0; i < WFC_CONTEXT_MAX_INSERTED_ELEMENT; i++)
        {
            /// Only apply inserted elements
            if (WFC_INVALID_HANDLE != pContext->capturedRWAttrib->_insertedElements[i])
            {
                //WFDSource source;
                WFCElementConfig* pElement = (WFCElementConfig*) pContext->capturedRWAttrib->_insertedElements[i];
                //WFCSourceConfig*  sourceCfg;
                //WFD_PIPELINE* pPipeline = &(pEngine->pipelines[i]);

                FlattenLayerStruct flatten_layer_config = {0};
                FLATTEN_PIXEL_FORMAT flatten_layer_format;
                OWF_IMAGE source_image;

                //if (i >= pEngine->pipelineCount)
                if (i >= 4)
                {
                    // Error!
                    continue;
                }

                /// if the inserted element without source, bypass this layer
                if (WFC_INVALID_HANDLE == pElement->capturedRWAttrib->source)
                {
                    DDV2CatcherLogL1D2(TRACE_DDV2_WARNING, DDV2_TRC_WARNING_CONFIGWFD_NOSOURCE,
                                                           drv_get_current_time(),
                                                           (kal_uint32)kal_get_current_thread_ID());
                    _wfc_set_error(WFC_ERROR_ILLEGAL_ARGUMENT);
                    continue;
                }
                
                // KeTing: If the image is not ready, don't blt this element
                // KeTing: This will happen if multiple streams are existed, the sync element changes buffer prior than other streams
                // KeTing: In this situation, we will not yet wrap the stream as image if the stream has not changed buffer yet
                if (OWF_INVALID_HANDLE == ((WFCSourceConfig*)pElement->capturedRWAttrib->source)->image.data)
                {
                    DDV2CatcherLogL1D2(TRACE_DDV2_WARNING, DDV2_TRC_WARNING_CONFIGWFD_NOBUFFER,
                                                           drv_get_current_time(),
                                                           (kal_uint32)kal_get_current_thread_ID());
                    _wfc_set_error(WFC_ERROR_UNSUPPORTED);
                    continue;
                }

                // Set Pipeline attributes
                // Set flatten_layer_config
                //pPipeline->config.flip = (WFDboolean)(pElement->capturedRWAttrib->flip);
                flatten_layer_config.flip = (kal_bool)(pElement->capturedRWAttrib->flip);
                //pPipeline->config.mirror = WFD_FALSE;
                //pPipeline->config.rotation = _wfc_convert_rotation_angle_to_int(pElement->capturedRWAttrib->rotationAngle);
                flatten_layer_config.rotationAngle = (FLATTENRotationType)_wfc_convert_rotation_angle_to_int(pElement->capturedRWAttrib->rotationAngle);
                //pPipeline->config.transparencyEnable = (WFDuint)(_wfc_convert_transparency(pElement->capturedRWAttrib->transparencyType));
                flatten_layer_config.transparencyType = (FLATTENbitfield)(_wfc_convert_transparency(pElement->capturedRWAttrib->transparencyType));
                //pPipeline->config.globalAlpha = pElement->capturedRWAttrib->globalAlpha;
                flatten_layer_config.globalAlpha = pElement->capturedRWAttrib->globalAlpha;
                //pPipeline->config.ditherEnable = pElement->capturedRWAttrib->enableSpatialDithering;
                flatten_layer_config.enableSpatialDithering = (kal_bool)(pElement->capturedRWAttrib->enableSpatialDithering); 
                //pPipeline->config.transparencyColor = pElement->capturedRWAttrib->sourceColorKey;
                flatten_layer_config.sourceColorKey = pElement->capturedRWAttrib->sourceColorKey;
                //pPipeline->config.dcEnable = pElement->capturedRWAttrib->isDCLayer;
		
                //memcpy(pPipeline->config.sourceRectangle, &(pElement->capturedRWAttrib->sourceRect), sizeof(WFDint)*4);
                flatten_layer_config.sourceRect_x = pElement->capturedRWAttrib->sourceRect.x;
                flatten_layer_config.sourceRect_y = pElement->capturedRWAttrib->sourceRect.y;
                flatten_layer_config.sourceRect_width = pElement->capturedRWAttrib->sourceRect.width;
                flatten_layer_config.sourceRect_height = pElement->capturedRWAttrib->sourceRect.height;

                //memcpy(pPipeline->config.destinationRectangle, &(pElement->capturedRWAttrib->destinationRect), sizeof(WFDint)*4);
                flatten_layer_config.destinationRect_x = pElement->capturedRWAttrib->destinationRect.x;
                flatten_layer_config.destinationRect_y = pElement->capturedRWAttrib->destinationRect.y;
                flatten_layer_config.destinationRect_width = pElement->capturedRWAttrib->destinationRect.width;
                flatten_layer_config.destinationRect_height = pElement->capturedRWAttrib->destinationRect.height;

                //pPipeline->config.image_source = &(((WFCSourceConfig*)pElement->capturedRWAttrib->source)->image);
                source_image = (((WFCSourceConfig*)pElement->capturedRWAttrib->source)->image);
                flatten_layer_config.image_source_width = source_image.width;
                flatten_layer_config.image_source_height = source_image.height;
                flatten_layer_config.image_source_stride = source_image.stride;
                flatten_layer_config.image_source_pixelSize = source_image.pixelSize;
                switch(source_image.format.pixelFormat)
                {
                    case OWF_IMAGE_ARGB8888: flatten_layer_format = FLATTEN_IMAGE_ARGB8888; break; 
                    case OWF_IMAGE_XRGB8888: flatten_layer_format = FLATTEN_IMAGE_XRGB8888; break; 
                    case OWF_IMAGE_RGB888: flatten_layer_format = FLATTEN_IMAGE_RGB888; break; 
                    case OWF_IMAGE_BGR888: flatten_layer_format = FLATTEN_IMAGE_BGR888; break; 
                    case OWF_IMAGE_RGB565: flatten_layer_format = FLATTEN_IMAGE_RGB565; break; 
                    case OWF_IMAGE_L32: flatten_layer_format = FLATTEN_IMAGE_L32; break; 
                    case OWF_IMAGE_L16: flatten_layer_format = FLATTEN_IMAGE_L16; break; 
                    case OWF_IMAGE_L8: flatten_layer_format = FLATTEN_IMAGE_L8; break; 
                    case OWF_IMAGE_L1: flatten_layer_format = FLATTEN_IMAGE_L1; break; 
                    case OWF_IMAGE_ARGB6666: flatten_layer_format = FLATTEN_IMAGE_ARGB6666; break; 	
                    case OWF_IMAGE_UYVY: flatten_layer_format = FLATTEN_IMAGE_UYVY; break; 
                    default: flatten_layer_format = FLATTEN_IMAGE_NOT_SUPPORTED; break; 
                }
                flatten_layer_config.image_source_format_pixelFormat = flatten_layer_format;
                flatten_layer_config.image_source_format_premultiplied = (kal_bool)(source_image.format.premultiplied);
                flatten_layer_config.image_source_format_linear = (kal_bool)(source_image.format.linear);
                flatten_layer_config.image_source_format_rowPadding = source_image.format.rowPadding;
                flatten_layer_config.image_source_datamax = source_image.dataMax;
                flatten_layer_config.image_source_alpha = source_image.alpha;
                flatten_layer_config.image_source_data = source_image.data;
                
                flatten_layer_config.isConstantValue = KAL_FALSE;

                switch(i)
                {
                    case 0:
                    flatten_result = FlattenConfigLayer(gdi_handle, FLATTEN_LAYER0, &flatten_layer_config);
                    break;
                    case 1:
                    flatten_result = FlattenConfigLayer(gdi_handle, FLATTEN_LAYER1, &flatten_layer_config);
                    break;
                    case 2:
                    flatten_result = FlattenConfigLayer(gdi_handle, FLATTEN_LAYER2, &flatten_layer_config);
                    break;
                    case 3:
                    flatten_result = FlattenConfigLayer(gdi_handle, FLATTEN_LAYER3, &flatten_layer_config);
                    break;
                } 
                if (FLATTEN_RESULT_OK != flatten_result)
                    ASSERT(0);
                //pPipeline->config.portId = (WFDPort)(pPort);
                //pPort->config.bindedPipelines[i] = WFD_TRUE;
                switch(i)
                {
                    case 0: flatten_ctrl_config.flatten_enable_layer |= FLATTEN_LAYER0; break;
                    case 1: flatten_ctrl_config.flatten_enable_layer |= FLATTEN_LAYER1; break;
                    case 2: flatten_ctrl_config.flatten_enable_layer |= FLATTEN_LAYER2; break;
                    case 3: flatten_ctrl_config.flatten_enable_layer |= FLATTEN_LAYER3; break;
                    default: ASSERT(0); break;
                }
                
            }
        }
    }

    // Moved here to control blocking or non-blocking mode...
    // pPort->config.doBlt = WFD_TRUE;

    wfcTrace(WFCDBG____CONFIG_______________PORT);

    //wfdDeviceCommit((WFDDevice)pEngine, WFD_COMMIT_ENTIRE_PORT, (WFDHandle)pPort);
    flatten_result = FlattenStart(gdi_handle, &flatten_ctrl_config);
    if (FLATTEN_RESULT_OK != flatten_result)
        ASSERT(0);


    if (KAL_TRUE == (kal_bool)wait)
    {
        flatten_api_cb((void *)pContext);
    }
    
    // KeTing: WFD error handling
    
}
else
#endif //#if defined (__GOVL_SUPPORT__)
{
    // Config WFDPort accordingly...
    {
        OWF_RECTANGLE TargetRect;
        // background color
        pPort->config.backgroundColor[0] = (pContext->capturedRWAttrib->bgColor&0xFF000000)>>24;   // A
        pPort->config.backgroundColor[1] = (pContext->capturedRWAttrib->bgColor&0x00FF0000)>>16;   // R
        pPort->config.backgroundColor[2] = (pContext->capturedRWAttrib->bgColor&0x0000FF00)>>8;    // G
        pPort->config.backgroundColor[3] = (pContext->capturedRWAttrib->bgColor&0x000000FF);       // B

        Rect = pContext->capturedRWAttrib->roiRect;
        // Merge video rectangle with ROI. Only for on screen context in auto mode.
        if (WFC_CONTEXT_TYPE_ON_SCREEN == pContext->type)
        {
            if (WFC_AUTONOMOUS_STATE_ON == pContext->_autonomousMode)
            {
                // Calculate video region. Saved in pContext->_autoModeRoiRect.
                memset(&(pContext->_autoModeRoiRect), 0, sizeof(OWF_RECTANGLE));
                for (i = WFC_CONTEXT_MAX_INSERTED_ELEMENT; i-- != 0; )
                {
                    WFCElementConfig* pElement = (WFCElementConfig*)pContext->capturedRWAttrib->_insertedElements[i];
                    if (WFC_INVALID_HANDLE != pElement && WFC_TRUE == pElement->capturedRWAttrib->isVideoLayer)
                    {
                        OWF_RECTANGLE videoElementRect = pElement->capturedRWAttrib->destinationRect;
                        if (_wfc_convert_rotation_angle_to_int(pElement->capturedRWAttrib->rotationAngle)/90%2)
                        {
                            videoElementRect.width = pElement->capturedRWAttrib->sourceRect.height;
                            videoElementRect.height = pElement->capturedRWAttrib->sourceRect.width;
                        }
                        else
                        {
                            videoElementRect.width = pElement->capturedRWAttrib->sourceRect.width;
                            videoElementRect.height = pElement->capturedRWAttrib->sourceRect.height;
                        }
                        _wfc_rectangle_or(&videoElementRect, &(pContext->_autoModeRoiRect), &(pContext->_autoModeRoiRect));
                    }
                }
                _wfc_rectangle_or(&(pContext->_autoModeRoiRect), &Rect, &Rect);
            }
            // The ROI should be in screen rectangle.
            TargetRect.x = TargetRect.y = 0;
            TargetRect.width = ((WFD_PORT*)(pContext->_port))->config.portWidth;
            TargetRect.height = ((WFD_PORT*)(pContext->_port))->config.portHeight;
            _wfc_rectangle_and(&TargetRect, &Rect, &Rect);
        }

        memcpy(pPort->config.roiDestRectangle, &Rect, sizeof(WFDint)*4);

        Rect.x = (WFDint) pContext->capturedRWAttrib->destinationRect.x + Rect.x - pContext->capturedRWAttrib->roiRect.x;
        Rect.y = (WFDint) pContext->capturedRWAttrib->destinationRect.y + Rect.y - pContext->capturedRWAttrib->roiRect.y;

        memcpy(pPort->config.partialRefreshRectangle, &Rect, sizeof(WFDint)*4);

        if (WFC_CONTEXT_TYPE_ON_SCREEN == pContext->type)
            pContext->_autoModeCommitLatched = WFC_TRUE;

        pPort->config.syncEnable = (WFDboolean)(pContext->capturedRWAttrib->enableVsync);
        pPort->config.blockModeReq = (WFDboolean)(wait);

#if 0
/* under construction !*/
/* under construction !*/
/* under construction !*/
/* under construction !*/
/* under construction !*/
/* under construction !*/
/* under construction !*/
/* under construction !*/
#endif

        // config memout's output image
        if ((WFC_CONTEXT_TYPE_OFF_SCREEN == pContext->type) || 
            (WFC_TRUE == pContext->capturedRWAttrib->enableConcurrentMemOut))
        {
            pPort->config.targetImage = &(pContext->capturedRWAttrib->memOutTarget.image);
        }

        // callback functions...
        pPort->config.updateDoneCallback[0] = (WFDuint) _wfc_engine_event_hdlr;
        pPort->config.updateDoneCallback[1] = (WFDuint) pContext;
        
        // palette table address
        pPort->config.paletteTable = (WFDuint) pContext->capturedRWAttrib->paletteTable;
    }

    // Config WFDPipelines accordingly...
    {
        kal_uint32 i;

        // Clear WFD port setting
        memset(pPort->config.bindedPipelines, 0, sizeof(pPort->config.bindedPipelines));
        for (i = 0; i < WFC_CONTEXT_MAX_INSERTED_ELEMENT; i++)
        {
            /// Only apply inserted elements
            if (WFC_INVALID_HANDLE != pContext->capturedRWAttrib->_insertedElements[i])
            {
                //WFDSource source;
                WFCElementConfig* pElement = (WFCElementConfig*) pContext->capturedRWAttrib->_insertedElements[i];
                //WFCSourceConfig*  sourceCfg;
                WFD_PIPELINE* pPipeline = &(pEngine->pipelines[i]);

                if (i >= pEngine->pipelineCount)
                {
                    // Error!
                    continue;
                }

                /// if the inserted element without source, bypass this layer
                if (WFC_INVALID_HANDLE == pElement->capturedRWAttrib->source)
                {
                    DDV2CatcherLogL1D2(TRACE_DDV2_WARNING, DDV2_TRC_WARNING_CONFIGWFD_NOSOURCE,
                                                           drv_get_current_time(),
                                                           (kal_uint32)kal_get_current_thread_ID());
                    _wfc_set_error(WFC_ERROR_ILLEGAL_ARGUMENT);
                    continue;
                }
                
                // KeTing: If the image is not ready, don't blt this element
                // KeTing: This will happen if multiple streams are existed, the sync element changes buffer prior than other streams
                // KeTing: In this situation, we will not yet wrap the stream as image if the stream has not changed buffer yet
                if (OWF_INVALID_HANDLE == ((WFCSourceConfig*)pElement->capturedRWAttrib->source)->image.data)
                {
                    DDV2CatcherLogL1D2(TRACE_DDV2_WARNING, DDV2_TRC_WARNING_CONFIGWFD_NOBUFFER,
                                                           drv_get_current_time(),
                                                           (kal_uint32)kal_get_current_thread_ID());
                    _wfc_set_error(WFC_ERROR_UNSUPPORTED);
                    continue;
                }

                // Set Pipeline attributes
                pPipeline->config.flip = (WFDboolean)(pElement->capturedRWAttrib->flip);
                pPipeline->config.mirror = WFD_FALSE;
                pPipeline->config.rotation = _wfc_convert_rotation_angle_to_int(pElement->capturedRWAttrib->rotationAngle);
                pPipeline->config.transparencyEnable = (WFDuint)(_wfc_convert_transparency(pElement->capturedRWAttrib->transparencyType));
                pPipeline->config.globalAlpha = pElement->capturedRWAttrib->globalAlpha;
                pPipeline->config.ditherEnable = (WFDboolean)pElement->capturedRWAttrib->enableSpatialDithering;
                pPipeline->config.transparencyColor = pElement->capturedRWAttrib->sourceColorKey;
                pPipeline->config.dcEnable = (WFDboolean)pElement->capturedRWAttrib->isDCLayer;
				//this is for MT6255 or later chip support 3D feature.
				#ifdef DRV_LCD_3D_MODE_SUPPORT
				pPipeline->config._3DEnable = (WFDboolean)pElement->capturedRWAttrib->is3DLayer;
				if(WFD_TRUE == pPipeline->config._3DEnable)
				{
					if( WFC_3D_IMAGE_PORTRAIT_MODE == pElement->capturedRWAttrib->_3DimageViewMode)
						pPipeline->config._3DPortraitMode = WFD_TRUE;
					else if( WFC_3D_IMAGE_LANDSCAPE_MODE == pElement->capturedRWAttrib->_3DimageViewMode)
						pPipeline->config._3DPortraitMode = WFD_FALSE;
					else
						ASSERT(0);//error
					
					if( WFC_3D_IMAGE_LEFT_EYE_FIRST_MODE == pElement->capturedRWAttrib->_3DimageFirstEyeMode)
						pPipeline->config._3DLeftEyeFirst = WFD_TRUE;
					else if( WFC_3D_IMAGE_RIGHT_EYE_FIRST_MODE == pElement->capturedRWAttrib->_3DimageFirstEyeMode)
						pPipeline->config._3DLeftEyeFirst = WFD_FALSE;
					else
						ASSERT(0);//error
					/*
					if( WFC_3D_START_ADDR_FOR_LEFT_MODE == pElement->capturedRWAttrib->_3DimageStartAddrMode)
						pPipeline->config._3DStartAddrForLeft = WFD_TRUE;
					else ( WFC_3D_START_ADDR_FOR_RIGHT_MODE == pElement->capturedRWAttrib->_3DimageStartAddrMode)
						pPipeline->config._3DStartAddrForLeft = WFD_FALSE;
					else
						//error*/
				}
				#endif
								
                /// Bin: this is only for MT6253, enable fast rotator for video layer in auto mode
                ///        but fast rotator is available only one layer, we did not handle more than one layer case
                if (pContext->_autonomousMode == WFC_AUTONOMOUS_STATE_ON)
                    pPipeline->config.FastRotatorEnable = (WFDboolean)(pElement->capturedRWAttrib->isVideoLayer);
                else
                {
                    pPipeline->config.FastRotatorEnable = (WFDboolean)(0);
                    pPipeline->config.dcEnable = (WFDboolean)(0);
                } 
                memcpy(pPipeline->config.sourceRectangle, &(pElement->capturedRWAttrib->sourceRect), sizeof(WFDint)*4);
                memcpy(pPipeline->config.destinationRectangle, &(pElement->capturedRWAttrib->destinationRect), sizeof(WFDint)*4);

                pPipeline->config.image_source = &(((WFCSourceConfig*)pElement->capturedRWAttrib->source)->image);

                pPipeline->config.portId = (WFDPort)(pPort);
                pPort->config.bindedPipelines[i] = WFD_TRUE;
				//handler for the second pipeline for the 3D image base on the first pipeline.
				//the first pipeline config from wfc element[0],the user of the wfc just only config element[0] for 3D image.
				#ifdef DRV_LCD_3D_MODE_SUPPORT
				if(WFD_TRUE == pPipeline->config._3DEnable)
				{
					WFD_PIPELINE* pPipeline2 = &(pEngine->pipelines[i+1]);
					if(0 != i)//for 6255 now(2012.6.26),,only element[0]can config as 3D feature.
						ASSERT(0);
					if(WFC_INVALID_HANDLE != pContext->capturedRWAttrib->_insertedElements[i+1])
						ASSERT(0);//3D layer just config element[0],element[1] should be NULL 
					//
					memcpy(pPipeline2,pPipeline,sizeof(WFD_PIPELINE));
					
					pPipeline2->config.id = i+1;
					
					if( WFC_3D_IMAGE_PORTRAIT_MODE == pElement->capturedRWAttrib->_3DimageViewMode)
					{	
						pPipeline2->config.sourceRectangle[0] = pPipeline->config.sourceRectangle[0] + pPipeline->config.sourceRectangle[2]/2;
						//lcd layer size is half of SW layer size,so adjust pPipeline->config.sourceRectangle.width for PORTRAIT_MODE.
						pPipeline->config.sourceRectangle[2] = pPipeline->config.sourceRectangle[2]/2;
						pPipeline2->config.sourceRectangle[2] = pPipeline->config.sourceRectangle[2];
					}
					else if( WFC_3D_IMAGE_LANDSCAPE_MODE == pElement->capturedRWAttrib->_3DimageViewMode)
					{
						pPipeline2->config.sourceRectangle[1] = pPipeline->config.sourceRectangle[1] + pPipeline->config.sourceRectangle[3]/2;
						//lcd layer size is half of SW layer size,so adjust pPipeline->config.sourceRectangle.height for LANDSCAPE_MODE.
						pPipeline->config.sourceRectangle[3] = pPipeline->config.sourceRectangle[3]/2;
						pPipeline2->config.sourceRectangle[3] = pPipeline->config.sourceRectangle[3];
					}
					else
					{
						ASSERT(0);
					}
					//todo:
					//handle attribute pElement->capturedRWAttrib->_3DimageStartAddrMode
					//this for rotation to MDP use in the future.
					//default:layer0 for left eye usage,layer1 for right eye usage
					//when rotate 90/270,layer0 will for right eye usage
					pPort->config.bindedPipelines[i+1] = WFD_TRUE;
					
				}
				#endif
            }
        }
    }

    // Moved here to control blocking or non-blocking mode...
    pPort->config.doBlt = WFD_TRUE;

    wfcTrace(WFCDBG____CONFIG_______________PORT);

    wfdDeviceCommit((WFDDevice)pEngine, WFD_COMMIT_ENTIRE_PORT, (WFDHandle)pPort);
    // KeTing: All resources will be destroyed in event handler
    
    // KeTing: WFD error handling
    {
        WFDErrorCode error = wfdGetError(pEngine);
        if (WFD_ERROR_NONE != error && WFD_ERROR_NOT_SUPPORTED != error)
        {
            _wfc_set_error(WFC_ERROR_ILLEGAL_ARGUMENT);
        }
    }
} 
}

/******************************************************************************
 * API definitions
 ******************************************************************************/

/*=========================================================================*/
/*  4. DEVICE                                                              */
/*=========================================================================*/
/***
 *  1. Multiple WFC device in a system? For what? 
 *      Does user really want to learn that we have a LCD and a GOVL?
 *    
 *  2. What about TV OUT? it cannot overlay, so it should be a WFD device only. 
 *      How we use it?
 *  3. If only one WFC device, can it be general enough to cover the case of three HW 
 *      devices? (LCD/GOVL/TVOUT) Single device with three or four context...
 *  4. How about Landscape UI on Portrait LCM? First of all, what compile options are 
 *      available for LCM scan-line directions.
 *      WFC do this for UI...? Map the Landscape mode as one context? Not efficient in terms of HW...
 *  5. If we need to implement sync to provider mode...as current FW trigger...
 *      Pros: if provider frame rate is stable and WFC performance is good, the behavior is predictable...
 *      Cons: Vulnerable to unstable frame rate issues...
 */

/**
 *  There is only one device.
 *  \status OK
 */
WFC_API_CALL WFCint WFC_APIENTRY
wfcEnumerateDevices(WFCint *deviceIds,
                    WFCint deviceIdsCount,
                    const WFCint *filterList)
{
    //WFCint ret = 0;

    // check arguments
    if ((NULL == deviceIds) || (1 > deviceIdsCount))
    {
        // only query for no of WFC devices.
        return 1;
    }

    deviceIds[0] = WFC_DEVICE_ID_DEFAULT;

    return 1;
}

static void _wfc_global_data_init(void)
{
	if(KAL_TRUE == _global_data_init)
		return;
	_global_data_init = KAL_TRUE;//init phase is single thread running,so no need to protect _global_data_init
	
	//init global data before using
	kal_mem_set((void *)(&_wfc_context_cfg_lcd_0),0,sizeof(WFCContextConfig));
	#ifdef DUAL_LCD
	kal_mem_set((void *)(&_wfc_context_cfg_lcd_1),0,sizeof(WFCContextConfig));
	#endif
	kal_mem_set((void *)(&_wfc_context_cfg_frame_buffer),0,sizeof(WFCContextConfig));
	kal_mem_set((void *)(&_wfc_sources[0]),0,sizeof(WFCSourceConfig)*WFC_MAX_SOURCE_NUMBER);
	kal_mem_set((void *)(&_wfc_elements[0]),0,sizeof(WFCElementConfig)*WFC_ELEMENT_MAX_COUNT);
	#if defined(WFC_DBG_SUPPORT)
	kal_mem_set((void *)(&_WFCDbgDat[0]),0,sizeof(WFCDbgCtrlBlk)*WFC_DBG_ENTRY_CNT);
	#endif
}
/**
 *  \status OK
 */
WFC_API_CALL WFCDevice WFC_APIENTRY
wfcCreateDevice(WFCint deviceId, const WFCint *attribList)
{
    WFDint i;
    WFCContextConfig* pContext;
    kal_uint32 memory_out_engine_index = 0;
	//init global data
	_wfc_global_data_init();

    _wfc_dbg_context_lcd0 = (WFCContextConfig_*) (&_wfc_context_cfg_lcd_0);
#ifdef DUAL_LCD
    _wfc_dbg_context_lcd1 = (WFCContextConfig_*) (&_wfc_context_cfg_lcd_1);
#endif
    //_wfc_dbg_context_frame_buffer = (WFCContextConfig_*) (&_wfc_context_cfg_frame_buffer);

    wfc_dbg_structure.ContextLCD0 = (WFCContextConfig_*)(_wfc_dbg_context_lcd0);
#ifdef DUAL_LCD
    wfc_dbg_structure.ContextLCD1 = (WFCContextConfig_*)(_wfc_dbg_context_lcd1);
#endif
    wfc_dbg_structure.ContextMem = (WFCContextConfig_*) (&_wfc_context_cfg_frame_buffer);
    wfc_dbg_structure.Device = (WFCDeviceConfig*)(&_wfc_device_cfg);

    if (WFC_DEVICE_ID_DEFAULT != deviceId)
    {
        return WFC_INVALID_HANDLE;
    }

    // check if already created
    if (WFC_DEVICE_STATE_DESTROYED != _wfc_device_cfg._state)
    {
        return WFC_INVALID_HANDLE;
    }

    // Common Initialization
    _owf_event = kal_create_event_group("_owf_event");
#if defined(__MTK_TARGET__)
    DRV_Register_HISR(DRV_LCD_WFC_HISR_ID,_wfc_autonomous_mode_blt_hisr);
	DRV_Register_HISR(DRV_LCD_RELEASE_DONE_HISR_ID,_wfc_autonomous_release_done_hisr);
#endif
    // Enumerate WFD devices, create them, and map them to contexts of WFC device.
    {
        WFDint deviceIds[WFC_ENGINE_MAX_COUNT] = {-1, -1};
        WFDint deviceIdsCount;

        // After this call, deviceIdsCount should be no bigger than WFC_ENGINE_MAX_COUNT.
        deviceIdsCount = wfdEnumerateDevices(deviceIds, WFC_ENGINE_MAX_COUNT, NULL);

        /**
        * 1. enumerate devices
        * 2. for each device, enumerate ports
        * 3. If found one internal port, place it at _engines[0]
        * 4. If found the second internal port, place it at _engines[1]
        * 5. If found one memory output port, place it at _engines[2]
        * 6. If found one device with only memory output port, replace it at _engines[2]
        * 7. If found one device with TV port, place it at _engines[3]
        */
        for (i = 0; i < deviceIdsCount; i++)
        {
            WFD_DEVICE* pEngine;
            //WFDint portIds[WFC_CONTEXT_MAX_COUNT] = {0};
            WFDint portCount;
            WFDint j;

            pEngine = (WFD_DEVICE*)wfdCreateDevice(deviceIds[i], NULL);

            portCount = pEngine->portCount;

            for (j = 0; j < portCount; j++)
            {
                WFDPortType portType;
                WFD_PORT* pPort = &(pEngine->ports[j]);
                
                portType = pPort->config.type;

                if (WFD_PORT_TYPE_INTERNAL == portType)
                {
                    if (WFC_INVALID_HANDLE == _wfc_device_cfg._engines[0])
                    {
                        // Use the first device and first port found
                        _wfc_device_cfg._engines[0] = (WFCHandle) pEngine;
                        kal_mem_set((void *)(&_wfc_context_cfg_lcd_0), 0x0, sizeof(WFCContextConfig));
                        _wfc_context_cfg_lcd_0._port = (WFCHandle) pPort;
                        _wfc_context_cfg_lcd_0._engine = (WFCHandle) pEngine;
                    }
#ifdef DUAL_LCD
                    else if (WFC_INVALID_HANDLE == _wfc_device_cfg._engines[1])
                    {
                        // Use the first device and first port found
                        _wfc_device_cfg._engines[1] = (WFCHandle) pEngine;
                        kal_mem_set((void *)(&_wfc_context_cfg_lcd_1), 0x0, sizeof(WFCContextConfig));
                        _wfc_context_cfg_lcd_1._port = (WFCHandle) pPort;
                        _wfc_context_cfg_lcd_1._engine = (WFCHandle) pEngine;
                    }
#endif
                    memory_out_engine_index++;
                }

                if (WFD_PORT_TYPE_MEMORY_OUTPUT_MTK == portType)
                {
                    // Directly replace with new device.
                    _wfc_device_cfg._engines[memory_out_engine_index] = (WFCHandle) pEngine;
                    kal_mem_set((void *)(&_wfc_context_cfg_frame_buffer), 0x0, sizeof(WFCContextConfig));
                    _wfc_context_cfg_frame_buffer._port = (WFCHandle) pPort;
                    _wfc_context_cfg_frame_buffer._engine = (WFCHandle) pEngine;
                }

            }
        }
    }

    i=0;
    _wfc_device_cfg._state = WFC_DEVICE_STATE_CREATED;
    _wfc_device_cfg._createdContexts[i++] = (WFCContext)(&_wfc_context_cfg_lcd_0);
#ifdef DUAL_LCD
    _wfc_device_cfg._createdContexts[i++] = (WFCContext)(&_wfc_context_cfg_lcd_1);
#endif
    _wfc_device_cfg._createdContexts[i++] = (WFCContext)(&_wfc_context_cfg_frame_buffer);
    for (i--; i>=0; i--)
    {
        pContext = (WFCContextConfig*)(_wfc_device_cfg._createdContexts[i]);
        pContext->cachedRWAttrib = &(pContext->__RWAttrib[0]);
        pContext->capturedRWAttrib = &(pContext->__RWAttrib[1]);

        pContext->_busy = WFC_FALSE;
        pContext->_autonomousMode = WFC_AUTONOMOUS_STATE_OFF;
    }

    return (WFCDevice) &_wfc_device_cfg;

}

/**
 *  \status OK
 */
WFC_API_CALL WFCErrorCode WFC_APIENTRY
wfcDestroyDevice(WFCDevice dev)
{
    //WFCDeviceConfig* pDevice = NULL;
    //kal_uint32 i;
    // This function should never be called
#if 0
/* under construction !*/
/* under construction !*/
/* under construction !*/
/* under construction !*/
/* under construction !*/
/* under construction !*/
/* under construction !*/
/* under construction !*/
/* under construction !*/
/* under construction !*/
/* under construction !*/
/* under construction !*/
/* under construction !*/
/* under construction !*/
/* under construction !*/
/* under construction !*/
/* under construction !*/
/* under construction !*/
/* under construction !*/
/* under construction !*/
/* under construction !*/
/* under construction !*/
/* under construction !*/
/* under construction !*/
/* under construction !*/
/* under construction !*/
/* under construction !*/
/* under construction !*/
/* under construction !*/
/* under construction !*/
/* under construction !*/
/* under construction !*/
/* under construction !*/
/* under construction !*/
/* under construction !*/
/* under construction !*/
/* under construction !*/
/* under construction !*/
/* under construction !*/
/* under construction !*/
/* under construction !*/
/* under construction !*/
/* under construction !*/
/* under construction !*/
/* under construction !*/
/* under construction !*/
/* under construction !*/
/* under construction !*/
/* under construction !*/
/* under construction !*/
/* under construction !*/
/* under construction !*/
/* under construction !*/
/* under construction !*/
/* under construction !*/
/* under construction !*/
/* under construction !*/
/* under construction !*/
/* under construction !*/
/* under construction !*/
/* under construction !*/
/* under construction !*/
/* under construction !*/
/* under construction !*/
/* under construction !*/
/* under construction !*/
/* under construction !*/
/* under construction !*/
/* under construction !*/
#endif
    return WFC_ERROR_NONE;
}

/**
 *  \status OK
 */
WFC_API_CALL WFCint WFC_APIENTRY
wfcGetDeviceAttribi(WFCDevice dev,
                    WFCDeviceAttrib attrib) 
{
    WFCint result = 0;

    switch (attrib)
    {
    case WFC_DEVICE_CLASS: 
        result = (WFCint) WFC_DEVICE_CLASS_FULLY_CAPABLE;
        break;
    case WFC_DEVICE_ID: 
        result = (WFCint) WFC_DEVICE_ID_DEFAULT;
        break;
    case WFC_DEVICE_NATIVE_DEBUG_TRACE_MTK: 
        result = 0;
        break;

    default: 
        _wfc_set_error(WFC_ERROR_BAD_ATTRIBUTE);
        break;
    }

    return result;
}

/**
 *  \status OK
 */
WFC_API_CALL void WFC_APIENTRY
wfcSetDeviceAttribi(WFCDevice dev,
                    WFCDeviceAttrib attrib, 
                    WFCint value)
{
    return;
}

/**
 *  \status OK
 */
WFC_API_CALL WFCErrorCode WFC_APIENTRY
wfcGetError(WFCDevice dev)
{
    WFCErrorCode ret;

    ret = _wfc_device_cfg._lastErrorCode;
    _wfc_device_cfg._lastErrorCode = WFC_ERROR_NONE;

    return ret;
}


/**
 *  \status OK
 *  this funtion is used for MM to check WFC busy state
 */
WFC_API_CALL WFCboolean WFC_APIENTRY
wfcMMCheckBusy() WFC_APIEXIT
{
    return (_wfc_context_cfg_lcd_0._busy);
}

WFC_API_CALL WFCint WFC_APIENTRY
wfcMMGetContextAttribi(WFCDevice dev,
                     WFCContext ctx,
                     WFCContextAttrib attrib)
{
    WFCContextConfig* pContext = NULL;
    WFCint ret = 0;

    GET_CONTEXT(pContext, ctx, ret);

    switch (attrib)
    {
    case WFC_CONTEXT_CALLBACK_MTK: 
        ret = WFC_CONTEXT_MM_CALLBACK_COUNT*3;
        break;
        
    default: 
        ret = wfcGetContextAttribi(dev, ctx, attrib);
        break;
    }

    return ret;
}
/**
 *  \status OK
 */
WFC_API_CALL void WFC_APIENTRY
wfcMMGetContextAttribiv(WFCDevice dev, 
                      WFCContext ctx, 
                      WFCContextAttrib attrib, 
                      WFCint count, 
                      WFCint *values)
{
    WFCContextConfig* pContext = NULL;

    GET_CONTEXT_NR(pContext, ctx);

    if ((1 > count) || (NULL == values))
    {
        _wfc_set_error(WFC_ERROR_ILLEGAL_ARGUMENT);
        return;
    }
    // clear the values
    kal_mem_set((void*) values, 0x0, sizeof(WFCint)*count);

    switch (attrib)
    {
    case WFC_CONTEXT_CALLBACK_MTK: 
        {
            //kal_uint32 i = 0;
            WFC_ASSERT(count >= 4);
            // TODO: [o] later, there is no need to query this attrib
            break;
        }
    default:
        {
            wfcGetContextAttribiv(dev, ctx, attrib, count, values);
            break;
        }
    }

    return;
}
/**
 *  \status OK
 */
WFC_API_CALL void WFC_APIENTRY
wfcMMSetContextAttribi(WFCDevice dev,
                     WFCContext ctx,
                     WFCContextAttrib attrib,
                     WFCint value) WFC_APIEXIT
{
    WFCContextConfig* pContext = NULL;

    DDV2CatcherLogL3(TRACE_DDV2_CONTEXTATTRIB, DDV2_TRC_WFCMMSETCONTEXTATTRIBI,
                                     drv_get_current_time(),
                                     (kal_uint32)kal_get_current_thread_ID(),
                                     ctx,
                                     attrib,
                                     value);
    GET_CONTEXT_NR(pContext, ctx);
    if(_wfc_is_context_in_autonomous_mode(ctx) == WFC_FALSE)
    {
        ///route to Non-mm set 
        DDV2CatcherLogL3(TRACE_DDV2_ERROR, DDV2_TRC_ERROR_AUTOMODE_STATEERROR,
                                         drv_get_current_time(),
                                         (kal_uint32)kal_get_current_thread_ID(),
                                         WFC_MMSetContextAttribi,
                                         pContext->_autonomousMode);
                                         
        wfcSetContextAttribi(dev, ctx, attrib, value);
        return;
    }
    
    switch (attrib)
    {
        case WFC_CONTEXT_CURRENT_REFRESH_RATE_MTK: 
            pContext->cachedRWAttrib->currRefreshRate = (WFCint) value;
            break;

        case WFC_CONTEXT_AUTONOMOUS_SYNC_MODE_MTK: 
            {
                pContext->cachedRWAttrib->syncTrigger = (WFCAutonomousSyncTriggerMTK) value;
                break;
            }
            
        case WFC_CONTEXT_AUTONOMOUS_PERIOD_MTK: 
            {
                pContext->cachedRWAttrib->period = (WFCuint) value;
                break;
            }
            
        case WFC_CONTEXT_AUTONOMOUS_SYNC_ELEMENT_MTK: 
            {
                pContext->cachedRWAttrib->sync_element = (WFCElement) value;
                break;
            }

        ///From here, all illlegal attributes
        case WFC_CONTEXT_ROTATION: 
            DDV2CatcherLogL3(TRACE_DDV2_ERROR, DDV2_TRC_ERROR_ILLEGAL_WFCMMSETCONTEXTATTRIBI,
                                             drv_get_current_time(),
                                             (kal_uint32)kal_get_current_thread_ID(),
                                             ctx,
                                             attrib,
                                             value);
            _wfc_set_error(WFC_ERROR_MM_SET_ATTR_MTK);
            break;

            
        default: 
            _wfc_set_error(WFC_ERROR_BAD_ATTRIBUTE);
            break;
    }

    return;
}


WFC_API_CALL void WFC_APIENTRY
wfcMMSetContextAttribiv(WFCDevice dev, 
                      WFCContext ctx, 
                      WFCContextAttrib attrib, 
                      WFCint count, 
                      const WFCint *values) WFC_APIEXIT
{
    WFCContextConfig* pContext = NULL;

    if ((count >= 3) && (values != NULL))
    {
        if (attrib==WFC_CONTEXT_AUTONOMOUS_SYNC_TRIGGER_MTK)
            DDV2CatcherLogL3(TRACE_DDV2_CONTEXTATTRIB, DDV2_TRC_WFCMMSETCONTEXTATTRIBIV2,
                                            drv_get_current_time(),
                                            (kal_uint32)kal_get_current_thread_ID(),
                                            ctx,
                                            attrib,
                                            values[0], values[1], values[2], 0);
        else
            DDV2CatcherLogL3(TRACE_DDV2_CONTEXTATTRIB, DDV2_TRC_WFCMMSETCONTEXTATTRIBIV1,
                                            drv_get_current_time(),
                                            (kal_uint32)kal_get_current_thread_ID(),
                                            ctx,
                                            attrib,
                                            values[0], values[1], values[2], (count==4)?values[3]:0);
    }
                                     
    GET_CONTEXT_NR(pContext, ctx);
    if(_wfc_is_context_in_autonomous_mode(ctx) == WFC_FALSE)
    {
        ///route to Non-mm set 
        DDV2CatcherLogL3(TRACE_DDV2_ERROR, DDV2_TRC_ERROR_AUTOMODE_STATEERROR,
                                         drv_get_current_time(),
                                         (kal_uint32)kal_get_current_thread_ID(),
                                         WFC_MMSetContextAttribiv,
                                         pContext->_autonomousMode);
        wfcSetContextAttribiv(dev, ctx, attrib, count, values);
        return;
    }
    
    if ((count < 1) || (NULL == values))
    {
        _wfc_set_error(WFC_ERROR_ILLEGAL_ARGUMENT);
        return;
    }

    switch (attrib)
    {
    case WFC_CONTEXT_CALLBACK_MTK: 
        {
            kal_uint32 i,j, firstEmpty;
            kal_bool found;
            WFC_ASSERT(count >= 4); // TODO: [o] Magical number...

            for (i = 0; i+4 <= count; i+=4) // For each callback set...
            {
                if (WFC_TRUE == (WFCboolean) values[i+3]) // add one callback function...
                {
                    firstEmpty = WFC_CONTEXT_MM_CALLBACK_COUNT;
                    found = KAL_FALSE;
                    for (j = WFC_CONTEXT_MM_CALLBACK_COUNT; j-- != 0; )
                    {
                        // Find an empty slot...
                        if (pContext->cachedRWAttrib->mmCallbacks[j].cbfunc == NULL)
                        {
                            firstEmpty = j;
                        }

                        // Find if already inserted. If found, break
                        if ((pContext->cachedRWAttrib->mmCallbacks[j].event == (WFCContextEventTypeMTK) values[i+0]) && 
                            (pContext->cachedRWAttrib->mmCallbacks[j].cbfunc == (WFCCallbackFunctionPtrMTK) values[i+1]) && 
                            (pContext->cachedRWAttrib->mmCallbacks[j].cbparam == (void*) values[i+2]))
                        {
                            found = KAL_TRUE;
                            break;
                        }
                    }
                    // There is an empty slot also the callback is never inserted before...
                    if ((firstEmpty != WFC_CONTEXT_MM_CALLBACK_COUNT) && (KAL_FALSE == found))
                    {
                        pContext->cachedRWAttrib->mmCallbacks[firstEmpty].event = (WFCContextEventTypeMTK) values[i];
                        pContext->cachedRWAttrib->mmCallbacks[firstEmpty].cbfunc = (WFCCallbackFunctionPtrMTK) values[(i+1)];
                        pContext->cachedRWAttrib->mmCallbacks[firstEmpty].cbparam = (void*) values[(i+2)];
                    }
                }
                else // remove one callback function...
                {
                    for (j = WFC_CONTEXT_MM_CALLBACK_COUNT; j-- != 0; )
                    {
                        if ((pContext->cachedRWAttrib->mmCallbacks[j].event == (WFCContextEventTypeMTK) values[i+0]) && 
                            (pContext->cachedRWAttrib->mmCallbacks[j].cbfunc == (WFCCallbackFunctionPtrMTK) values[i+1]) && 
                            (pContext->cachedRWAttrib->mmCallbacks[j].cbparam == (void*) values[i+2]))
                        {
                            pContext->cachedRWAttrib->mmCallbacks[j].event = (WFCContextEventTypeMTK) 0x0;
                            pContext->cachedRWAttrib->mmCallbacks[j].cbfunc = NULL;
                            pContext->cachedRWAttrib->mmCallbacks[j].cbparam = NULL;
                            break;
                        }
                    }
                }
            }

            break;
        }

        // KeTing: For autonomous mode, set sync source
    case WFC_CONTEXT_AUTONOMOUS_SYNC_TRIGGER_MTK:
        {
            //WFC_ASSERT(count >= 3);
            //pContext->cachedRWAttrib->autonomousSync.syncTrigger = (WFCAutonomousSyncTriggerMTK) values[0];
            //pContext->cachedRWAttrib->autonomousSync.period = (WFCuint) values[1];
            //pContext->cachedRWAttrib->autonomousSync.element = (WFCElement) values[2];
            
            //pContext->cachedRWAttrib->syncTrigger = (WFCAutonomousSyncTriggerMTK) values[0];
            //pContext->cachedRWAttrib->period = (WFCuint) values[1];
            //pContext->cachedRWAttrib->sync_element = (WFCElement) values[2];

            _wfc_set_error(WFC_ERROR_UNSUPPORTED);

            break;
        }


        ///Bin: From here, the attribute setting is illegal for MM
    case WFC_CONTEXT_BG_COLOR: 
    case WFC_CONTEXT_WORKING_BUFFER_MTK: 
    case WFC_CONTEXT_DESTINATION_RECTANGLE_MTK: 
    case WFC_CONTEXT_ROI_RECTANGLE_MTK: 
    case WFC_CONTEXT_CONCURRENT_MEMORY_OUT_RECT_MTK: 
            DDV2CatcherLogL3(TRACE_DDV2_ERROR, DDV2_TRC_ERROR_ILLEGAL_WFCMMSETCONTEXTATTRIBIV,
                                             drv_get_current_time(),
                                             (kal_uint32)kal_get_current_thread_ID(),
                                             ctx,
                                             attrib);
        _wfc_set_error(WFC_ERROR_MM_SET_ATTR_MTK);
        break;

    case WFC_CONTEXT_ALL_ATTRIBUTES_MTK:
        kal_mem_cpy((void*)pContext->cachedRWAttrib->syncTrigger, (void*)values, (sizeof(WFCCtxtRWAttrib) - ((kal_uint32)&(pContext->cachedRWAttrib->syncTrigger) - (kal_uint32)(pContext->cachedRWAttrib))));
    default: 
        _wfc_set_error(WFC_ERROR_BAD_ATTRIBUTE);
        break;
    }
	

    return;
}
/**
 *  \status OK
 */
WFC_API_CALL WFCint WFC_APIENTRY
wfcMMGetElementAttribi(WFCDevice dev,
                     WFCElement element,
                     WFCElementAttrib attrib) WFC_APIEXIT
{
    return wfcGetElementAttribi(dev,element,attrib);
}


/**
 *  \status OK
 */
WFC_API_CALL void WFC_APIENTRY
wfcMMGetElementAttribiv(WFCDevice dev,
                      WFCElement element,
                      WFCElementAttrib attrib,
                      WFCint count,
                      WFCint *values) WFC_APIEXIT
{
    wfcGetElementAttribiv(dev, element,attrib,count,values);
    return;
}

WFC_API_CALL void WFC_APIENTRY
wfcMMSetElementAttribi(WFCDevice dev,
                     WFCElement element,
                     WFCElementAttrib attrib,
                     WFCint value) WFC_APIEXIT
{
    WFCElementConfig* pElement = NULL;
    WFCContextConfig* pContext = NULL;

    DDV2CatcherLogL3(TRACE_DDV2_ELEMENTATTRIB, DDV2_TRC_WFCMMSETELEMENTATTRIBI,
                                     drv_get_current_time(),
                                     (kal_uint32)kal_get_current_thread_ID(),
                                     element,
                                     attrib,
                                     value);
    GET_ELEMENT_NR(pElement, element);
    GET_CONTEXT_NR(pContext, pElement->_context);
    if(_wfc_is_context_in_autonomous_mode(pElement->_context) == WFC_FALSE)
    {
        ///route to Non-mm set 
        DDV2CatcherLogL3(TRACE_DDV2_ERROR, DDV2_TRC_ERROR_AUTOMODE_STATEERROR,
                                         drv_get_current_time(),
                                         (kal_uint32)kal_get_current_thread_ID(),
                                         WFC_MMSetElementAttribi,
                                         pContext->_autonomousMode);

        wfcSetElementAttribi(dev,element,attrib,value);     
        return;
    }

    switch (attrib)
    {
    case WFC_ELEMENT_SOURCE: 
        {
            WFCSourceConfig* pSource = (WFCSourceConfig*) value;
            // If the input source handle is NULL, it means user wants to remove the connection between the source and element.
            WFCSourceConfig* pOriSource;
            pOriSource = (WFCSourceConfig*)(pElement->cachedRWAttrib->source);
            if (pOriSource)
                pOriSource->element = WFC_INVALID_HANDLE;
            pElement->cachedRWAttrib->source = (WFCSource) value;
            // If the input source handle is NULL, it means user wants to remove the connection between the source and element.
            if (pSource)
            {
                pSource->element = element;
            }

            break;
        }  
    case WFC_ELEMENT_SOURCE_FLIP: 
        pElement->cachedRWAttrib->flip = (WFCboolean) value;
        break;
    case WFC_ELEMENT_SOURCE_ROTATION: 
        pElement->cachedRWAttrib->rotationAngle = (WFCRotation) value;
        break;

    case WFC_ELEMENT_VIDEO_LAYER_MTK: 
        pElement->cachedRWAttrib->isVideoLayer = (WFCboolean) value;
        break;
    case WFC_ELEMENT_DC_LAYER_MTK: 
        pElement->cachedRWAttrib->isDCLayer = (WFCboolean) value;
        break;


        ///Bin: From here, the attribute setting is illegal for MM
    case WFC_ELEMENT_SOURCE_COLOR_KEY_MTK: 
    case WFC_ELEMENT_DITHERING_MTK: 
    case WFC_ELEMENT_TRANSPARENCY_TYPES: 
    case WFC_ELEMENT_GLOBAL_ALPHA: 
          DDV2CatcherLogL3(TRACE_DDV2_ERROR, DDV2_TRC_ERROR_ILLEGAL_WFCMMSETELEMENTATTRIBI,
                                             drv_get_current_time(),
                                             (kal_uint32)kal_get_current_thread_ID(),
                                             element,
                                             attrib,
                                             value);   
        _wfc_set_error(WFC_ERROR_MM_SET_ATTR_MTK);
        break;

#ifdef DRV_LCD_3D_MODE_SUPPORT
		//currently,MDP can only set attribute:WFC_ELEMENT_3D_LAYER_MTK,but can expand here if need other attribute.
		case WFC_ELEMENT_3D_LAYER_MTK: 
          pElement->cachedRWAttrib->is3DLayer = (WFCboolean) value;
          break;	  
#endif
    default: 
        _wfc_set_error(WFC_ERROR_BAD_ATTRIBUTE);
        break;
    }

    return;
}


WFC_API_CALL void WFC_APIENTRY
wfcMMSetElementAttribiv(WFCDevice dev,
                      WFCElement element,
                      WFCElementAttrib attrib,
                      WFCint count,
                      const WFCint *values) WFC_APIEXIT
{
    WFCElementConfig* pElement = NULL;
    WFCContextConfig* pContext = NULL;

    if ((count >= 3) && (values != NULL))
       DDV2CatcherLogL3(TRACE_DDV2_ELEMENTATTRIB, DDV2_TRC_WFCMMSETELEMENTATTRIBIV,
                                            drv_get_current_time(),
                                            (kal_uint32)kal_get_current_thread_ID(),
                                            element,
                                            attrib,
                                            values[0], values[1], values[2], (count==4)?values[3]:0);
                                     
    GET_ELEMENT_NR(pElement, element);
    GET_CONTEXT_NR(pContext, pElement->_context);
    if(_wfc_is_context_in_autonomous_mode(pElement->_context) == WFC_FALSE)
    {
        ///route to Non-mm set 
        DDV2CatcherLogL3(TRACE_DDV2_ERROR, DDV2_TRC_ERROR_AUTOMODE_STATEERROR,
                                         drv_get_current_time(),
                                         (kal_uint32)kal_get_current_thread_ID(),
                                         WFC_MMSetElementAttribiv,
                                         pContext->_autonomousMode);

        wfcSetElementAttribiv(dev,element,attrib,count, values);                                 
        return;
    }

    if ((0 >= count) || (NULL == values))
    {
        _wfc_set_error(WFC_ERROR_ILLEGAL_ARGUMENT);
        return;
    }

    switch (attrib)
    {
    case WFC_ELEMENT_SOURCE_RECTANGLE: /* WFCint[4] ==> (offsetX, offsetY, width, height) */
        WFC_ASSERT(4 == count);
        if (4 != count)
        {
            _wfc_set_error(WFC_ERROR_ILLEGAL_ARGUMENT);
            break;
        }
        pElement->cachedRWAttrib->sourceRect.x = (OWFint) values[0];
        pElement->cachedRWAttrib->sourceRect.y = (OWFint) values[1];
        pElement->cachedRWAttrib->sourceRect.width = (OWFint) values[2];
        pElement->cachedRWAttrib->sourceRect.height = (OWFint) values[3];
        break;
    case WFC_ELEMENT_ALL_ATTRIBUTES_MTK:
        kal_mem_cpy((void *)pElement->cachedRWAttrib->source, (void *)values, (sizeof(WFCElementRWAttrib) - ((kal_uint32)&(pElement->cachedRWAttrib->source) - (kal_uint32)(pElement->cachedRWAttrib))));
        break;
    default:
        _wfc_set_error(WFC_ERROR_BAD_ATTRIBUTE); 
        break;
    }

    return;
}


/**
 *  \status XX
 *  this commit function is only for MM auto mode commit
 *  the commited configurations are limitited
 *  for context: only the attributes after syncTrigger(include syncTrigger) in WFCCtxtRWAttrib will be commited and shared attributes (Callback)
 *  for element only the attributes after source(include source) in WFCElementRWAttrib will be commited
 */
WFC_API_CALL void WFC_APIENTRY
wfcMMCommit(WFCDevice dev, WFCContext ctx, WFCElement element, WFCMMCommitType commitType)
{
    WFCContextConfig* pContext = NULL;
    kal_uint32 savedMask;
    kal_bool sync_mode_change = KAL_FALSE;
    WFCboolean needResourceChecking = WFC_FALSE; // KeTing: To see if the commit need to check resource
    WFCSourceConfig* newSource = WFC_INVALID_HANDLE;
    WFCSourceConfig* oldSource = WFC_INVALID_HANDLE;
    WFCElementConfig* pElement = NULL; 
                                     
    wfcTrace(WFCDBG____AUTO_MODE__________COMMIT);
    
    GET_CONTEXT_NR(pContext, ctx);
    GET_ELEMENT_NR(pElement, element);

    //  This is workaround for MED and MDI design
    //  Bin: MDI may Deactivate before make CAL stop, therefore CAL will call wfcMMCommit in none-auto mode 
    //  please refer to mdi_camera_capture_with_quickview()  
    //  1 deactivate  --- MDI
    //  2 exit preview --- MED
    //  3 start capture --- MED
    if(_wfc_is_context_in_autonomous_mode(ctx) == WFC_FALSE)
    {
        DDV2CatcherLogL3(TRACE_DDV2_ERROR, DDV2_TRC_ERROR_AUTOMODE_STATEERROR,
                                         drv_get_current_time(),
                                         (kal_uint32)kal_get_current_thread_ID(),
                                         WFC_MMCommit,
                                         pContext->_autonomousMode);

        ///route to Non-mm commit 
        wfcCommit(dev, ctx, WFC_TRUE);
        return;
    }
    
    // Parameter checking
    if((element == WFC_INVALID_HANDLE) && ((commitType & WFC_COMMIT_ELEMENT) == 0))
    {
        WFC_ASSERT(0);
    }
    
#if defined(__CAMERA_MATV_ESD_RECOVERY_SUPPORT__)
    if (!(kal_if_lisr() || kal_if_hisr()))
#endif
        WFC_Commit_Lock();
        
    DDV2CatcherLogL3(TRACE_DDV2_RENDERING, DDV2_TRC_WFCMMCOMMIT,
                                     drv_get_current_time(),
                                     (kal_uint32)kal_get_current_thread_ID(),
                                     ctx,
                                     element,
                                     commitType);
                                     
    //Zifeng: Check if sync_mode has changed
    if(commitType & WFC_COMMIT_CONTEXT)
    {    
        if ((pContext->cachedRWAttrib->syncTrigger) != (pContext->capturedRWAttrib->syncTrigger))
        {
            sync_mode_change = KAL_TRUE;
            _wfc_clear_autonomous_sync_trigger(pContext);
        }
    }                                     

    {
        /// Mask IRQ here to protect racing of any blt behavior triggered from Timer HISR or MDP callback HISR
        #if defined(MT6253)
            savedMask = kal_take_thread_protect();
        #else
            savedMask = SaveAndSetIRQMask();
        #endif

        // Bin: update context attributes here
        if(commitType & WFC_COMMIT_CONTEXT)
        {
            ///Commit attributes belonged to MM
            kal_mem_cpy((void*)(&pContext->capturedRWAttrib->syncTrigger),
                        (void*)(&pContext->cachedRWAttrib->syncTrigger),
                        (sizeof(WFCCtxtRWAttrib) - ((kal_uint32)&(pContext->capturedRWAttrib->syncTrigger) - (kal_uint32)(pContext->capturedRWAttrib))));
        }                

        // Bin: commit video layer attributes here
        if(commitType & WFC_COMMIT_ELEMENT)
        {
            newSource = (WFCSourceConfig*) pElement->capturedRWAttrib->source;
            oldSource = (WFCSourceConfig*) pElement->cachedRWAttrib->source;

            pElement->_context = (WFCContext)pContext;
            // Bin: update MM owned attributes to captured here
            kal_mem_cpy((void *)&(pElement->capturedRWAttrib->source),
                        (void *)&(pElement->cachedRWAttrib->source),
                        (sizeof(WFCElementRWAttrib) - ((kal_uint32)&(pElement->capturedRWAttrib->source) - (kal_uint32)(pElement->capturedRWAttrib))));

            // KeTing: If the context is busy here, the current rendering must have used the old settings
            // KeTing: Thus have to check whether the resouce is going to be removed
            if (WFC_TRUE == pContext->_busy)
            {
                needResourceChecking = WFC_TRUE;
            }
        }

        #if defined(MT6253)
            kal_give_thread_protect(savedMask);
        #else
            RestoreIRQMask(savedMask);
        #endif
    }

    // KeTing: Block here if some of the resource being changed is under using
    if ((WFC_TRUE == needResourceChecking) && (commitType & WFC_COMMIT_ELEMENT))
    {
        WFCboolean needBlocking = WFC_FALSE;

        // KeTIng: Check if the source of this element is changed
        {
          if (newSource != oldSource)
          {
              needBlocking = WFC_TRUE;
          }
          else if ((WFC_INVALID_HANDLE != newSource) && (WFC_INVALID_HANDLE != oldSource))
          {
            if (newSource->image.data != oldSource->image.data)
            {
              needBlocking = WFC_TRUE;
            }
          }
        }

        if (WFC_TRUE == needBlocking)
        {
            if (WFC_TRUE == pContext->_busy)
            {
                kal_uint32 event_group;
                kal_retrieve_eg_events(_owf_event,
                    (kal_uint32)(_wfc_convert_context_handle_to_frame_done_enum(pContext)),
                    KAL_OR, &event_group, KAL_SUSPEND);
            }
        }
    }

    // KeTing: Attached the stream callback function to each inserted elements
    // KeTing: The callback function will be removed when element is being destroyed
    if(commitType & WFC_COMMIT_ELEMENT)
    {
        WFCSourceConfig* pSource = (WFCSourceConfig*) pElement->capturedRWAttrib->source;
        if ((NULL != pSource) && pSource->useStream && (NULL != pSource->stream))
        {
            owfNativeStreamAddObserver(pSource->stream, _wfc_stream_event_hdlr, (void *)pElement);
        DDV2CatcherLogL3(TRACE_DDV2_AUTOMODE, DDV2_TRC_ADDOBSERVER,
                                         drv_get_current_time(),
                                         (kal_uint32)kal_get_current_thread_ID(),
                                         (kal_uint32)pElement,
                                         (kal_uint32)pSource,
                                         (kal_uint32)pSource->stream);
                                     
        }
    }

    // KeTing: Invoke the autonomous commit callback
    if(commitType & WFC_COMMIT_CONTEXT)
    {    
        if (sync_mode_change)
        {
            if (WFC_FALSE == _wfc_autonomous_commit_callback(pContext))
            {
                _wfc_set_error(WFC_ERROR_ILLEGAL_ARGUMENT);
            }
        }
    }
    
    DDV2CatcherLogL3(TRACE_DDV2_RENDERING, DDV2_TRC_WFCMMCOMMITEND,
                                     drv_get_current_time(),
                                     (kal_uint32)kal_get_current_thread_ID());
#if defined(__CAMERA_MATV_ESD_RECOVERY_SUPPORT__)
    if (!(kal_if_lisr() || kal_if_hisr()))
#endif
        WFC_Commit_Unlock();
        
    return;
}


/**
 *  \status XX
 *  this commit function is only for GDI commit cached setting 
 *  the commited configurations are limitited in auto mode
 *  for context: only the attributes before syncTrigger in WFCCtxtRWAttrib will be commited and shared attributes (Callback) in auto mode
 *  for video element only the attributes before source in WFCElementRWAttrib will be commited in auto mode
 */
WFC_API_CALL void WFC_APIENTRY
wfcCommit(WFCDevice dev, WFCContext ctx, WFCboolean wait)
{
    WFCContextConfig* pContext = NULL;
    kal_uint32 i, j;
    kal_uint32 savedMask;
    WFCboolean needResourceChecking = WFC_FALSE; // KeTing: To see if the commit need to check resource
    WFCboolean inAutoMode = WFC_FALSE;
    
    ///Bin: for auto mode , context commit used
    kal_uint32 mmOwnedContextSize;
    kal_uint8 tempBuffer[sizeof(WFCCtxtRWAttrib)];

    wfcTrace(WFCDBG_______________________COMMIT);

    GET_CONTEXT_NR(pContext, ctx);

    mmOwnedContextSize = sizeof(WFCCtxtRWAttrib) - ((kal_uint32)&(pContext->capturedRWAttrib->syncTrigger) - (kal_uint32)(pContext->capturedRWAttrib));

    WFC_Commit_Lock();
    DDV2CatcherLogL3(TRACE_DDV2_RENDERING, DDV2_TRC_WFCCOMMIT,
                                     drv_get_current_time(),
                                     (kal_uint32)kal_get_current_thread_ID(),
                                     ctx,
                                     pContext->cachedRWAttrib->roiRect.x,
                                     pContext->cachedRWAttrib->roiRect.y,
                                     pContext->cachedRWAttrib->roiRect.width,
                                     pContext->cachedRWAttrib->roiRect.height,
                                     wait);

    ///Bin: Get to know if WFC is in autonomous mode currently, 
    ///       since Commit behavior will be different depends on auto mode
    inAutoMode = _wfc_is_context_in_autonomous_mode(ctx);

    // This code segment is to ignore the width/height of destination Rectangle.
    for (i = WFC_CONTEXT_MAX_INSERTED_ELEMENT; i-- != 0; )
    {
        WFCElementConfig* pElement = (WFCElementConfig*)pContext->cachedRWAttrib->_insertedElements[i];
        if (WFC_INVALID_HANDLE != pElement)
        {
            if((inAutoMode == WFC_TRUE) && (pElement->cachedRWAttrib->isVideoLayer == WFC_TRUE))
            {
                continue;
            }
            else
            {
                OWF_RECTANGLE *srcRect = &(pElement->cachedRWAttrib->sourceRect);
                OWF_RECTANGLE *dstRect = &(pElement->cachedRWAttrib->destinationRect);
                if ((pElement->cachedRWAttrib->rotationAngle == WFC_ROTATION_90) || 
                    (pElement->cachedRWAttrib->rotationAngle == WFC_ROTATION_270))
                {
                    dstRect->width = srcRect->height;
                    dstRect->height = srcRect->width;
                }
                else
                {
                    dstRect->width = srcRect->width;
                    dstRect->height = srcRect->height;
                }
            }
        }
    }


    {
        /// Mask IRQ here to protect racing of any blt behavior triggered from Timer HISR or MDP callback HISR
        #if defined(MT6253)
            savedMask = kal_take_thread_protect();
        #else
            savedMask = SaveAndSetIRQMask();
        #endif
        // Bin: Commit the element attributes here
        for (i = WFC_CONTEXT_MAX_INSERTED_ELEMENT; i-- != 0; )
        {
            if (WFC_INVALID_HANDLE != pContext->cachedRWAttrib->_insertedElements[i])
            {
                WFCElementConfig* pElement = (WFCElementConfig*) pContext->cachedRWAttrib->_insertedElements[i];
                WFCElementRWAttrib *tempElementAttrib = pElement->cachedRWAttrib;

                if((inAutoMode == WFC_TRUE) && (pElement->cachedRWAttrib->isVideoLayer == WFC_TRUE))
                {
                    ///Bin: If video layer and in auto mode, 
                    ///       only update GDI own attribute (the attributes before source in WFCElementRWAttrib) for Video layer ,
                    ///       therefore uusing memory copy here rather than  swap the pointers
                    kal_mem_cpy(((void *)pElement->capturedRWAttrib),
                        ((void *)pElement->cachedRWAttrib),
                        ((kal_uint32)&(pElement->capturedRWAttrib->source) - (kal_uint32)(pElement->capturedRWAttrib)));
                }   
                else
                {
                    ///Bin: Swap the element attributes pointers for None-video layer
                    pElement->cachedRWAttrib = pElement->capturedRWAttrib;
                    pElement->capturedRWAttrib = tempElementAttrib;

                    pElement->_context = (WFCContext)pContext;
                }
            }
        }

        // Bin: Commit the context attributes here          
        {
            // Bin: Swap the context attributes pointers
            WFCCtxtRWAttrib *tempContextAttrib = pContext->cachedRWAttrib;
            pContext->cachedRWAttrib = pContext->capturedRWAttrib;
            pContext->capturedRWAttrib = tempContextAttrib;

            ///Bin: in auto mode, wfcCommit is only allowed to commit the context attributes before syncTrigger in WFCCtxtRWAttrib
            ///       Because we swap pointer before, therefore we need to restore the commited setting owned by MM here
            if(inAutoMode == WFC_TRUE)
            {            
                // restore MM owned attributes
                kal_mem_cpy((void*)tempBuffer,
                            (void*)(&pContext->cachedRWAttrib->syncTrigger),
                            mmOwnedContextSize);

                kal_mem_cpy((void*)(&pContext->cachedRWAttrib->syncTrigger),
                            (void*)(&pContext->capturedRWAttrib->syncTrigger),
                            mmOwnedContextSize);

                kal_mem_cpy((void*)(&pContext->capturedRWAttrib->syncTrigger),
                            (void*)tempBuffer,
                            mmOwnedContextSize);
            }
        }

        // Bin: _autoModeCommitLatched flag is used to make sure when invoke callback function,
        //          this time attribute config setting is applied (this flag if set before trigger WFD)
        //          if this is false, current blting callback function will not invoke callback
        if (&_wfc_context_cfg_frame_buffer != pContext && (inAutoMode == WFC_TRUE))
            pContext->_autoModeCommitLatched = WFC_FALSE;


        // KeTing: If the context is busy here, the current rendering must have used the old settings
        // KeTing: Thus have to check whether the resouce is going to be removed
        if (WFC_TRUE == pContext->_busy)
        {
            needResourceChecking = WFC_TRUE;
        }
        else
        {
        	if (inAutoMode == WFC_TRUE)
        	{
        		_wfc_committed_flag = WFC_TRUE; //Xiaoyong:WFC not busy, the commit indicates the blt request is valid in auto mode
         	}
        }

        #if defined(MT6253)
            kal_give_thread_protect(savedMask);
        #else
            RestoreIRQMask(savedMask);
        #endif


    }

    // KeTing: Block here if some of the resource being changed is under using,
    ///           in case GDI will corrupt the source buffer after return this function
    if (WFC_TRUE == needResourceChecking)
    {
        WFCboolean needBlocking = WFC_FALSE;

        // KeTing: To minimize the waiting time, we have to check the changed items are resources under using or not
        // KeTing: The resources we should protect are wfc sources and wfc elements
        // KeTing: Target for flt didn't be considered here because we do not allow flt in auto mode
        // KeTing: Since wfcCommit should only be called in task level, we will not use I-bit protection here
        for (i = 0; i < WFC_CONTEXT_MAX_INSERTED_ELEMENT; i++)
        {
            WFCElementConfig* pElement = (WFCElementConfig*)pContext->cachedRWAttrib->_insertedElements[i];
            if (WFC_INVALID_HANDLE != pElement)
            {
                // KeTing: Check if the element is removed or not
                {
                    for (j = 0; j < WFC_CONTEXT_MAX_INSERTED_ELEMENT; j++)
                    {
                        if ((WFCElement)pElement == pContext->capturedRWAttrib->_insertedElements[j])
                        {
                            break;
                        }
                    }

                    // Bin: if can not find the element , it means this element is removed...
                    //        need blocking to wait for current blt finish
                    if ( WFC_CONTEXT_MAX_INSERTED_ELEMENT == j)
                    {
                        needBlocking = WFC_TRUE;
                        break;
                    }
                }
                // KeTIng: Check if the source of this element is changed
                {
                    WFCSourceConfig* newSource = (WFCSourceConfig*) pElement->capturedRWAttrib->source;
                    WFCSourceConfig* oldSource = (WFCSourceConfig*) pElement->cachedRWAttrib->source;
                    if (WFC_INVALID_HANDLE != newSource && WFC_INVALID_HANDLE != oldSource)
                    {
                        if (newSource->image.data != oldSource->image.data)
                        {
                            needBlocking = WFC_TRUE;
                            break;
                        }
                    }
                }
            }
        }

        // Bin: if need blocking, wait for current blt done here
        if (WFC_TRUE == needBlocking)
        {
            if (WFC_TRUE == pContext->_busy)
            {
                kal_uint32 event_group;
                kal_retrieve_eg_events(_owf_event,
                    (kal_uint32)(_wfc_convert_context_handle_to_frame_done_enum(pContext)),
                    KAL_OR, &event_group, KAL_SUSPEND);
            }
        }
        if (inAutoMode == WFC_TRUE)
        {
        	_wfc_committed_flag = WFC_TRUE;//Xiaoyong:WFC busy,after the blocking check,the commit indicates the blt request is valid in auto mode
       }
		
    }

    {
        // Bin: 1. for Non-video layer, memcpy captured setting to cached setting to make they are same (since previously , we only swap the pointers...)
        //        2. for video layer in auto mode,  do nothing 
        for (i = WFC_CONTEXT_MAX_INSERTED_ELEMENT; i-- != 0; )
        {
            if (WFC_INVALID_HANDLE != pContext->capturedRWAttrib->_insertedElements[i])
            {
                WFCElementConfig* pElement = (WFCElementConfig*) pContext->capturedRWAttrib->_insertedElements[i];

                if((inAutoMode == WFC_TRUE) && (pElement->capturedRWAttrib->isVideoLayer == WFC_TRUE))
                {
                    continue;
                }
                else
                {
                    // Copy captured attributes to cached attributes
                    kal_mem_cpy((void*) (pElement->cachedRWAttrib), 
                        (void*) (pElement->capturedRWAttrib), 
                        sizeof(WFCElementRWAttrib));
                }
            }
        }

        // Bin: Copy context captured attributes to cached attributes if not in auto mode
        if(inAutoMode == WFC_FALSE)
        {
            kal_mem_cpy((void*) (pContext->cachedRWAttrib), 
                (void*) (pContext->capturedRWAttrib), 
                sizeof(WFCCtxtRWAttrib));
        }
        else    
        {   
            // Bin: If in auto mode, only copy the context attributes owned by GDI to cached attributes
            kal_mem_cpy((void*)(pContext->cachedRWAttrib),
                        (void*)(pContext->capturedRWAttrib),
                        ((kal_uint32)&(pContext->capturedRWAttrib->syncTrigger) - (kal_uint32)(pContext->capturedRWAttrib)));
        }
    }


    // KeTing: Attached the stream callback function to each inserted elements
    // KeTing: The callback function will be removed when element is being destroyed
    for (i = WFC_CONTEXT_MAX_INSERTED_ELEMENT; i-- != 0; )
    {
        if (WFC_INVALID_HANDLE != pContext->capturedRWAttrib->_insertedElements[i])
        {
            WFCElementConfig* pElement = (WFCElementConfig*) pContext->capturedRWAttrib->_insertedElements[i];
            WFCSourceConfig* pSource = (WFCSourceConfig*) pElement->capturedRWAttrib->source;

            
            if((inAutoMode == WFC_TRUE) && (pElement->cachedRWAttrib->isVideoLayer == WFC_TRUE))
            {
                ///Bin: For video layer in automode, the sttribute is belonged to MM, will done in wfcMMCommit()
                continue;
            }
            else
            {
                ///Bin: if the element using stream as source, add callback function for this stream
                if ((NULL != pSource) && pSource->useStream && (NULL != pSource->stream))
                {
                    owfNativeStreamAddObserver(pSource->stream, _wfc_stream_event_hdlr, (void *)pElement);
                    DDV2CatcherLogL3(TRACE_DDV2_AUTOMODE, DDV2_TRC_ADDOBSERVER,
                                                 drv_get_current_time(),
                                                 (kal_uint32)kal_get_current_thread_ID(),
                                                 (kal_uint32)pElement,
                                                 (kal_uint32)pSource,
                                                 (kal_uint32)pSource->stream);
                }
            }
        }
    }

    DDV2CatcherLogL3(TRACE_DDV2_RENDERING, DDV2_TRC_WFCCOMMITEND,
                                           drv_get_current_time(),
                                           (kal_uint32)kal_get_current_thread_ID());
    WFC_Commit_Unlock();
    return;
}

/*=========================================================================*/
/* 5. CONTEXT                                                              */
/*=========================================================================*/
/**
 *  \status OK
 */
WFC_API_CALL WFCContext WFC_APIENTRY
wfcCreateOnScreenContext(WFCDevice dev,
                         WFCint screenNumber,
                         const WFCint* attribList)
{
    volatile WFCContextConfig* pContext = NULL;
    //kal_uint32 i = WFC_CONTEXT_MAX_WORKING_BUF_COUNT;

    wfcTrace(WFCDBG____CREATE_________ONSRN_CNXT);

    if (WFC_SCREEN_LCD_0 == screenNumber)
    {
        pContext = &_wfc_context_cfg_lcd_0;
    }
#ifdef DUAL_LCD
    else if (WFC_SCREEN_LCD_1 == screenNumber)
    {
        pContext = &_wfc_context_cfg_lcd_1;
    }
#endif
    else
    {
        _wfc_set_error(WFC_ERROR_UNSUPPORTED);
        return WFC_INVALID_HANDLE;
    }

    pContext->type = WFC_CONTEXT_TYPE_ON_SCREEN;
    pContext->cachedRWAttrib->syncTrigger = WFC_AUTONOMOUS_SYNC_TO_TIMER;
    pContext->cachedRWAttrib->currRefreshRate = 15;
    pContext->capturedRWAttrib->currRefreshRate = 15;
    pContext->cachedRWAttrib->enableVsync = WFC_TRUE;

    if (WFC_SCREEN_LCD_0 == screenNumber)
        pContext->_timer = kal_create_timer("LCD_WFC_AUTO_0");
    else
        pContext->_timer = kal_create_timer("LCD_WFC_AUTO_1");

    return (WFCContext) pContext;
}

/**
 *  \status OK
 */
WFC_API_CALL WFCContext WFC_APIENTRY
wfcCreateOffScreenContext(WFCDevice dev,
                          WFCNativeStreamType stream,
                          const WFCint *attribList)
{
    WFCContextConfig* pContext = NULL;
    //WFCint portId = 0;

    return (WFCContext) pContext;
}

WFC_API_CALL WFCContext WFC_APIENTRY
wfcCreateOffScreenContextMTK(WFCDevice dev,
                             WFCHandle image,
                             const WFCint *attribList)
{
    volatile WFCContextConfig* pContext = NULL;

    wfcTrace(WFCDBG____CREATE________OFFSRN_CNXT);

    pContext = &_wfc_context_cfg_frame_buffer;
    
    pContext->type = WFC_CONTEXT_TYPE_OFF_SCREEN;
    pContext->cachedRWAttrib->syncTrigger = WFC_AUTONOMOUS_SYNC_TO_NONE;
    // Set target image
    kal_mem_cpy((void*) &(pContext->cachedRWAttrib->memOutTarget.image), 
        (void*) image, sizeof(OWF_IMAGE));
    kal_mem_cpy((void*) &(pContext->capturedRWAttrib->memOutTarget.image), 
        (void*) image, sizeof(OWF_IMAGE));

    pContext->_timer = KAL_NILTIMER_ID;

    return (WFCContext) pContext;
}


/**
 *  \status OK
 */
WFC_API_CALL void WFC_APIENTRY
wfcDestroyContext(WFCDevice dev,
                  WFCContext ctx)
{

}

/**
 *  \status OK
 */
WFC_API_CALL WFCint WFC_APIENTRY
wfcGetContextAttribi(WFCDevice dev,
                     WFCContext ctx,
                     WFCContextAttrib attrib)
{
    WFCContextConfig* pContext = NULL;
    WFCint ret = 0;

    GET_CONTEXT(pContext, ctx, ret);

    switch (attrib)
    {
    case WFC_CONTEXT_TYPE: 
        ret = (WFCint) pContext->type;
        break;
    case WFC_CONTEXT_TARGET_HEIGHT: 
        ret = (WFCint) ((WFD_PORT*)(pContext->_port))->config.portHeight;
        break;
    case WFC_CONTEXT_TARGET_WIDTH: 
        ret = (WFCint) ((WFD_PORT*)(pContext->_port))->config.portWidth;
        break;
    case WFC_CONTEXT_LOWEST_ELEMENT: 
        ret = (WFCint) 0;
        break;
    case WFC_CONTEXT_WORKING_BUFFER_REQ_MTK: 
        ret = (WFCint) 0;
        break;
    case WFC_CONTEXT_REFRESH_RATES_MTK: 
        ret = (WFCint) 1;
        break;
	case WFC_CONTEXT_BLT_MAX_REFRESH_RATE_MTK:
		ret = (WFCint) ((WFD_PORT*)(pContext->_port))->config.portTearFreeRefreshRate;
        break;
    case WFC_CONTEXT_ROTATION: 
        ret = (WFCint) pContext->cachedRWAttrib->rotationAngle;
        break;
    case WFC_CONTEXT_BG_COLOR: 
        ret = (WFCint) pContext->cachedRWAttrib->bgColor;
        break;
    case WFC_CONTEXT_WORKING_BUFFER_MTK: 
        ret = WFC_CONTEXT_MAX_WORKING_BUF_COUNT*4;
        break;
    case WFC_CONTEXT_CALLBACK_MTK: 
        ret = WFC_CONTEXT_GDI_CALLBACK_COUNT*3;
        break;
    case WFC_CONTEXT_CONCURRENT_MEMORY_OUT_MTK: 
        ret = (WFCint) pContext->cachedRWAttrib->enableConcurrentMemOut;
        break;
    case WFC_CONTEXT_CONCURRENT_MEMORY_OUT_STREAM_MTK: 
        ret = (WFCint) pContext->cachedRWAttrib->memOutTarget.stream;
        break;
    case WFC_CONTEXT_CONCURRENT_MEMORY_OUT_IMAGE_MTK: 
    case WFC_CONTEXT_TARGET_IMAGE_MTK: 
        ret = (WFCint) &(pContext->cachedRWAttrib->memOutTarget.image);
        break;
    case WFC_CONTEXT_TOTAL_VSYNC_COUNT_MTK: 
        // TODO: [r] be careful with this one! since we pass back the captured attrib value.
        //ret = (WFCint) pContext->capturedRWAttrib->totalVsyncCount;
        ret = 0;
        break;
    case WFC_CONTEXT_CURRENT_REFRESH_RATE_MTK: 
        ret = (WFCint) pContext->cachedRWAttrib->currRefreshRate;
        break;
    case WFC_CONTEXT_DESTINATION_RECTANGLE_MTK: 
        ret = 4; // array size...but it is fixed...
        break;
    case WFC_CONTEXT_VSYNC_ENABLE_MTK: 
        ret = (WFCboolean) pContext->cachedRWAttrib->enableVsync;
        break;
    case WFC_CONTEXT_IS_FLATTEN_READY_MTK:
        {
            // KeTing: Only off-screen context support flatten
            if (pContext != &_wfc_context_cfg_frame_buffer)
            {
                ret = (WFCint)WFC_FALSE;
                _wfc_set_error(WFC_ERROR_ILLEGAL_ARGUMENT);
                break;
            }

            if (WFC_TRUE == _wfc_is_engine_in_autonomous_mode(pContext->_engine))
            {
                ret = (WFCint)WFC_FALSE;
            }
            else
            {
                ret = (WFCint)WFC_TRUE;
            }
            break;
        }
    case WFC_CONTEXT_PPI_MTK: 
        {
            ret = ((WFD_PORT*)(pContext->_port))->config.ppi;
            if (0 == ret)
            {
                _wfc_set_error(WFC_ERROR_UNSUPPORTED);
            }
            break;
        }
    case WFC_CONTEXT_AUTONOMOUS_SYNC_MODE_MTK: 
        {
            ret = (WFCint)(pContext->cachedRWAttrib->syncTrigger);
            break;
        }
        
    case WFC_CONTEXT_AUTONOMOUS_PERIOD_MTK: 
        {
            ret = (WFCint)(pContext->cachedRWAttrib->period);
            break;
        }
        
    case WFC_CONTEXT_AUTONOMOUS_SYNC_ELEMENT_MTK: 
        {
            ret = (WFCint)(pContext->cachedRWAttrib->sync_element);
            break;
        }
    case WFC_CONTEXT_PALETTE_TABLE_MTK:
        {
            ret = (WFCuint)(pContext->cachedRWAttrib->paletteTable);
            break;
        }
        
    default: 
        _wfc_set_error(WFC_ERROR_BAD_ATTRIBUTE);
        break;
    }

    return ret;
}

/**
 *  \status OK
 */
WFC_API_CALL void WFC_APIENTRY
wfcSetContextAttribi(WFCDevice dev,
                     WFCContext ctx,
                     WFCContextAttrib attrib,
                     WFCint value)
{
    WFCContextConfig* pContext = NULL;
    WFCboolean inAutoMode = WFC_FALSE;
    WFCboolean is_illegal_context_attribi = WFC_FALSE;

    DDV2CatcherLogL3(TRACE_DDV2_CONTEXTATTRIB, DDV2_TRC_WFCSETCONTEXTATTRIBI,
                                     drv_get_current_time(),
                                     (kal_uint32)kal_get_current_thread_ID(),
                                     ctx,
                                     attrib,
                                     value);
    GET_CONTEXT_NR(pContext, ctx);
    inAutoMode = _wfc_is_context_in_autonomous_mode(ctx);

    switch (attrib)
    {
    case WFC_CONTEXT_ROTATION: 
        pContext->cachedRWAttrib->rotationAngle = (WFCRotation) value;
        break;
    case WFC_CONTEXT_BG_COLOR: 
        pContext->cachedRWAttrib->bgColor = (WFCuint) value;
        break;
    case WFC_CONTEXT_CONCURRENT_MEMORY_OUT_MTK: 
        pContext->cachedRWAttrib->enableConcurrentMemOut = (WFCboolean) value;
        break;
    case WFC_CONTEXT_CONCURRENT_MEMORY_OUT_STREAM_MTK: 
        pContext->cachedRWAttrib->memOutTarget.stream = (WFCHandle) value;
        break;
    case WFC_CONTEXT_CONCURRENT_MEMORY_OUT_IMAGE_MTK: 
    case WFC_CONTEXT_TARGET_IMAGE_MTK: 
        kal_mem_cpy((void*) &(pContext->cachedRWAttrib->memOutTarget.image), 
            (void*) value, sizeof(OWF_IMAGE)); 
        break;
    case WFC_CONTEXT_TOTAL_VSYNC_COUNT_MTK: 
        //pContext->cachedRWAttrib->totalVsyncCount = (WFCint) value;
        break;
    case WFC_CONTEXT_VSYNC_ENABLE_MTK:
        pContext->cachedRWAttrib->enableVsync = (WFCboolean) value;
        break;
    case WFC_CONTEXT_PALETTE_TABLE_MTK:
        pContext->cachedRWAttrib->paletteTable = (WFCuint) value;
        break;

        ///Bin: The following are illegal for GDI in Auto mode
    case WFC_CONTEXT_CURRENT_REFRESH_RATE_MTK: 
    {
        if(inAutoMode == WFC_TRUE)
        {
            is_illegal_context_attribi = WFC_TRUE;
        }
        else
        {
            pContext->cachedRWAttrib->currRefreshRate = (WFCint) value;
        }
        break;
    }

    case WFC_CONTEXT_AUTONOMOUS_SYNC_MODE_MTK: 
    {
        if(inAutoMode == WFC_TRUE)
        {
            is_illegal_context_attribi = WFC_TRUE;
        }
        else
        {
            pContext->cachedRWAttrib->syncTrigger = (WFCAutonomousSyncTriggerMTK) value;
        }
        break;
    }
            
    case WFC_CONTEXT_AUTONOMOUS_PERIOD_MTK: 
    {
        if(inAutoMode == WFC_TRUE)
        {
            is_illegal_context_attribi = WFC_TRUE;
        }
        else
        {
            pContext->cachedRWAttrib->period = (WFCuint) value;
        }
        break;
    }
            
    case WFC_CONTEXT_AUTONOMOUS_SYNC_ELEMENT_MTK: 
    {
        if(inAutoMode == WFC_TRUE)
        {
            is_illegal_context_attribi = WFC_TRUE;
        }
        else
        {
            pContext->cachedRWAttrib->sync_element = (WFCElement) value;
        }
        break;
    }

    default: 
        _wfc_set_error(WFC_ERROR_BAD_ATTRIBUTE);
        break;
    }

    if (WFC_TRUE == is_illegal_context_attribi)
    {
        _wfc_set_error(WFC_ERROR_ILLEGAL_ARGUMENT);
        DDV2CatcherLogL3(TRACE_DDV2_ERROR, DDV2_TRC_ERROR_ILLEGAL_WFCSETCONTEXTATTRIBI,
                                         drv_get_current_time(),
                                         (kal_uint32)kal_get_current_thread_ID(),
                                         ctx,
                                         attrib,
                                         value);
    }
    return;
}

/**
 *  \status OK
 */
WFC_API_CALL void WFC_APIENTRY
wfcGetContextAttribiv(WFCDevice dev, 
                      WFCContext ctx, 
                      WFCContextAttrib attrib, 
                      WFCint count, 
                      WFCint *values)
{
    WFCContextConfig* pContext = NULL;

    GET_CONTEXT_NR(pContext, ctx);

    if ((1 > count) || (NULL == values))
    {
        _wfc_set_error(WFC_ERROR_ILLEGAL_ARGUMENT);
        return;
    }

    // clear the values
    kal_mem_set((void*) values, 0x0, sizeof(WFCint)*count);

    switch (attrib)
    {
    case WFC_CONTEXT_WORKING_BUFFER_REQ_MTK:
        {
            break;
        }
    case WFC_CONTEXT_REFRESH_RATES_MTK: 
        {
            values[0] = 30;   ///???
            break;
        }
    case WFC_CONTEXT_BG_COLOR: 
        {
            WFC_ASSERT(count >= 4);
            values[0] = (WFCint) ((pContext->cachedRWAttrib->bgColor >> 16) & 0xFF); // R
            values[1] = (WFCint) ((pContext->cachedRWAttrib->bgColor >>  8) & 0xFF); // G
            values[2] = (WFCint) ((pContext->cachedRWAttrib->bgColor >>  0) & 0xFF); // B
            values[3] = (WFCint) ((pContext->cachedRWAttrib->bgColor >> 24) & 0xFF); // A
            break;
        }
    case WFC_CONTEXT_WORKING_BUFFER_MTK: 
        {
            //kal_uint32 i = 0;
            WFC_ASSERT(count >= 3);
            // TODO: [o] later, there is no need to query this attrib
            break;
        }
    case WFC_CONTEXT_CALLBACK_MTK: 
        {
            //kal_uint32 i = 0;
            WFC_ASSERT(count >= 4);
            // TODO: [o] later, there is no need to query this attrib
            break;
        }
    case WFC_CONTEXT_DESTINATION_RECTANGLE_MTK: 
        {
            WFC_ASSERT(count >= 4);
            values[0] = (WFCint) pContext->cachedRWAttrib->destinationRect.x;
            values[1] = (WFCint) pContext->cachedRWAttrib->destinationRect.y;
            values[2] = (WFCint) pContext->cachedRWAttrib->destinationRect.width;
            values[3] = (WFCint) pContext->cachedRWAttrib->destinationRect.height;
            break;
        }
    case WFC_CONTEXT_ROI_RECTANGLE_MTK: 
        {
            WFC_ASSERT(count >= 4);
            values[0] = (WFCint) pContext->cachedRWAttrib->roiRect.x;
            values[1] = (WFCint) pContext->cachedRWAttrib->roiRect.y;
            values[2] = (WFCint) pContext->cachedRWAttrib->roiRect.width;
            values[3] = (WFCint) pContext->cachedRWAttrib->roiRect.height;
            break;
        }
    case WFC_CONTEXT_CONCURRENT_MEMORY_OUT_RECT_MTK: 
        {
            WFC_ASSERT(count >= 4);
            values[0] = (WFCint) pContext->cachedRWAttrib->concurrentMemOutRect.x;
            values[1] = (WFCint) pContext->cachedRWAttrib->concurrentMemOutRect.y;
            values[2] = (WFCint) pContext->cachedRWAttrib->concurrentMemOutRect.width;
            values[3] = (WFCint) pContext->cachedRWAttrib->concurrentMemOutRect.height;
            break;
        }
        // KeTing: For autonomous sync source
    case WFC_CONTEXT_AUTONOMOUS_SYNC_TRIGGER_MTK:
        {
            //WFC_ASSERT(count >= 3);
            //values[0] = (WFCint) pContext->capturedRWAttrib->autonomousSync.syncTrigger;
            //values[1] = (WFCint) pContext->capturedRWAttrib->autonomousSync.period;
            //values[2] = (WFCint) pContext->capturedRWAttrib->autonomousSync.element;
            
            //values[0] = (WFCint) (pContext->cachedRWAttrib->syncTrigger);
            //values[1] = (WFCint) (pContext->cachedRWAttrib->period);
            //values[2] = (WFCint) (pContext->cachedRWAttrib->sync_element);

            _wfc_set_error(WFC_ERROR_UNSUPPORTED);

            break;
        }
    case WFC_CONTEXT_ALL_ATTRIBUTES_MTK: 
        kal_mem_cpy((void*)values, (void*)pContext->cachedRWAttrib, sizeof(WFCCtxtRWAttrib));
        break;

    default:
        {
            _wfc_set_error(WFC_ERROR_BAD_ATTRIBUTE);
            break;
        }
    }

    return;
}

/**
 *  \status OK
 */
WFC_API_CALL void WFC_APIENTRY
wfcSetContextAttribiv(WFCDevice dev, 
                      WFCContext ctx, 
                      WFCContextAttrib attrib, 
                      WFCint count, 
                      const WFCint *values)
{
    WFCContextConfig* pContext = NULL;
    //WFCboolean inAutoMode = WFC_FALSE;

    if ((count >= 3) && (values != NULL))
    {
        if (attrib==WFC_CONTEXT_AUTONOMOUS_SYNC_TRIGGER_MTK)
            DDV2CatcherLogL3(TRACE_DDV2_CONTEXTATTRIB, DDV2_TRC_WFCSETCONTEXTATTRIBIV2,
                                            drv_get_current_time(),
                                            (kal_uint32)kal_get_current_thread_ID(),
                                            ctx,
                                            attrib,
                                            values[0], values[1], values[2], 0);
        else
            DDV2CatcherLogL3(TRACE_DDV2_CONTEXTATTRIB, DDV2_TRC_WFCSETCONTEXTATTRIBIV1,
                                            drv_get_current_time(),
                                            (kal_uint32)kal_get_current_thread_ID(),
                                            ctx,
                                            attrib,
                                            values[0], values[1], values[2], (count==4)?values[3]:0);
    }

    GET_CONTEXT_NR(pContext, ctx);
    //inAutoMode = _wfc_is_context_in_autonomous_mode(ctx);

    if ((count < 1) || (NULL == values))
    {
        _wfc_set_error(WFC_ERROR_ILLEGAL_ARGUMENT);
        return;
    }

    switch (attrib)
    {
    case WFC_CONTEXT_BG_COLOR: 
        {
            if (count < 4)
            {
                _wfc_set_error(WFC_ERROR_ILLEGAL_ARGUMENT);
                break;
            }
            pContext->cachedRWAttrib->bgColor = ((((kal_uint32) values[0] & 0xFF) << 16) | 
                (((kal_uint32) values[1] & 0xFF) <<  8) | 
                (((kal_uint32) values[2] & 0xFF) <<  0) | 
                (((kal_uint32) values[3] & 0xFF) << 24));
            break;
        }
    case WFC_CONTEXT_WORKING_BUFFER_MTK: 
        {
            kal_uint32 i = 0;
            kal_uint32 size;
            if (count < 3)
            {
                _wfc_set_error(WFC_ERROR_ILLEGAL_ARGUMENT);
                break;
            }

            size = (3*3) < count ? (3*3) : count;

            for (; (i*3)<size; i++)
            {
                pContext->cachedRWAttrib->workingBuffer[i].type = values[(i*3)+0];
                pContext->cachedRWAttrib->workingBuffer[i].startAddress = values[(i*3)+1];
                pContext->cachedRWAttrib->workingBuffer[i].size = values[(i*3)+2];
            }
            break;
        }
    case WFC_CONTEXT_CALLBACK_MTK: 
        {
            kal_uint32 i,j, firstEmpty;
            kal_bool found;
            WFC_ASSERT(count >= 4); // TODO: [o] Magical number...

            for (i = 0; i+4 <= count; i+=4) // For each callback set...
            {
                if (WFC_TRUE == (WFCboolean) values[i+3]) // add one callback function...
                {
                    firstEmpty = WFC_CONTEXT_GDI_CALLBACK_COUNT;
                    found = KAL_FALSE;
                    for (j = WFC_CONTEXT_GDI_CALLBACK_COUNT; j-- != 0; )
                    {
                        // Find an empty slot...
                        if (pContext->cachedRWAttrib->gdiCallbacks[j].cbfunc == NULL)
                        {
                            firstEmpty = j;
                        }

                        // Find if already inserted. If found, break
                        if ((pContext->cachedRWAttrib->gdiCallbacks[j].event == (WFCContextEventTypeMTK) values[i+0]) && 
                            (pContext->cachedRWAttrib->gdiCallbacks[j].cbfunc == (WFCCallbackFunctionPtrMTK) values[i+1]) && 
                            (pContext->cachedRWAttrib->gdiCallbacks[j].cbparam == (void*) values[i+2]))
                        {
                            found = KAL_TRUE;
                            break;
                        }
                    }
                    // There is an empty slot also the callback is never inserted before...
                    if ((firstEmpty != WFC_CONTEXT_GDI_CALLBACK_COUNT) && (KAL_FALSE == found))
                    {
                        pContext->cachedRWAttrib->gdiCallbacks[firstEmpty].event = (WFCContextEventTypeMTK) values[i];
                        pContext->cachedRWAttrib->gdiCallbacks[firstEmpty].cbfunc = (WFCCallbackFunctionPtrMTK) values[(i+1)];
                        pContext->cachedRWAttrib->gdiCallbacks[firstEmpty].cbparam = (void*) values[(i+2)];
                    }
                }
                else // remove one callback function...
                {
                    for (j = WFC_CONTEXT_GDI_CALLBACK_COUNT; j-- != 0; )
                    {
                        if ((pContext->cachedRWAttrib->gdiCallbacks[j].event == (WFCContextEventTypeMTK) values[i+0]) && 
                            (pContext->cachedRWAttrib->gdiCallbacks[j].cbfunc == (WFCCallbackFunctionPtrMTK) values[i+1]) && 
                            (pContext->cachedRWAttrib->gdiCallbacks[j].cbparam == (void*) values[i+2]))
                        {
                            pContext->cachedRWAttrib->gdiCallbacks[j].event = (WFCContextEventTypeMTK)0x0;
                            pContext->cachedRWAttrib->gdiCallbacks[j].cbfunc = NULL;
                            pContext->cachedRWAttrib->gdiCallbacks[j].cbparam = NULL;
                            break;
                        }
                    }
                }
            }

            break;
        }
    case WFC_CONTEXT_DESTINATION_RECTANGLE_MTK: 
        {
            WFC_ASSERT(count >= 4);
            pContext->cachedRWAttrib->destinationRect.x = (OWFint) values[0];
            pContext->cachedRWAttrib->destinationRect.y = (OWFint) values[1];
            pContext->cachedRWAttrib->destinationRect.width = (OWFint) values[2];
            pContext->cachedRWAttrib->destinationRect.height = (OWFint) values[3];
            break;
        }
    case WFC_CONTEXT_ROI_RECTANGLE_MTK: 
        {
            WFC_ASSERT(count >= 4);
            pContext->cachedRWAttrib->roiRect.x = (OWFint) values[0];
            pContext->cachedRWAttrib->roiRect.y = (OWFint) values[1];
            pContext->cachedRWAttrib->roiRect.width = (OWFint) values[2];
            pContext->cachedRWAttrib->roiRect.height = (OWFint) values[3];
            break;
        }
    case WFC_CONTEXT_CONCURRENT_MEMORY_OUT_RECT_MTK: 
        {
            WFC_ASSERT(count >= 4);
            pContext->cachedRWAttrib->concurrentMemOutRect.x = (OWFint) values[0];
            pContext->cachedRWAttrib->concurrentMemOutRect.y = (OWFint) values[1];
            pContext->cachedRWAttrib->concurrentMemOutRect.width = (OWFint) values[2];
            pContext->cachedRWAttrib->concurrentMemOutRect.height = (OWFint) values[3];
            break;
        }


        // KeTing: For autonomous mode, set sync source
        ///Bin: The following are illegal for GDI in Auto mode
    case WFC_CONTEXT_AUTONOMOUS_SYNC_TRIGGER_MTK:
    {
        //if(inAutoMode == WFC_TRUE)
        //{
        //    DDV2CatcherLogL3(TRACE_DDV2_ERROR, DDV2_TRC_ERROR_ILLEGAL_WFCSETCONTEXTATTRIBIV,
        //                                     drv_get_current_time(),
        //                                     (kal_uint32)kal_get_current_thread_ID(),
        //                                     ctx,
        //                                     attrib);
        //}
  
    
            //WFC_ASSERT(count >= 3);
            //pContext->cachedRWAttrib->autonomousSync.syncTrigger = (WFCAutonomousSyncTriggerMTK) values[0];
            //pContext->cachedRWAttrib->autonomousSync.period = (WFCuint) values[1];
            //pContext->cachedRWAttrib->autonomousSync.element = (WFCElement) values[2];
            
            //pContext->cachedRWAttrib->syncTrigger = (WFCAutonomousSyncTriggerMTK) values[0];
            //pContext->cachedRWAttrib->period = (WFCuint) values[1];
            //pContext->cachedRWAttrib->sync_element = (WFCElement) values[2];

            _wfc_set_error(WFC_ERROR_UNSUPPORTED);

            break;
        }
    case WFC_CONTEXT_ALL_ATTRIBUTES_MTK: 
	{
		WFCboolean te_enable = WFC_TRUE;
		///Yinli: GDI will not config enableVsync, so need to backup this attribute.
		te_enable = pContext->cachedRWAttrib->enableVsync;
		
		///bin: only memcpy the attributes gdi will set
		kal_mem_cpy((void*)pContext->cachedRWAttrib, (void*)values, ((kal_uint32)&(pContext->cachedRWAttrib->syncTrigger) - (kal_uint32)(pContext->cachedRWAttrib)));

		///Yinli: Rollback enableVsync
		pContext->cachedRWAttrib->enableVsync = te_enable;
	}

        break;
    default: 
        _wfc_set_error(WFC_ERROR_BAD_ATTRIBUTE);
        break;
    }

    return;
}

/**
 *  \status OK
 */
WFC_API_CALL void WFC_APIENTRY
wfcGetContextAttribfv(WFCDevice dev,
                      WFCContext ctx,
                      WFCContextAttrib attrib,
                      WFCint count,
                      WFCfloat *values) WFC_APIEXIT
{
    _wfc_set_error(WFC_ERROR_UNSUPPORTED);
}

/**
 *  \status OK
 */
WFC_API_CALL void WFC_APIENTRY
wfcSetContextAttribfv(WFCDevice dev,
                      WFCContext ctx,
                      WFCContextAttrib attrib,
                      WFCint count,
                      const WFCfloat *values) WFC_APIEXIT
{
    _wfc_set_error(WFC_ERROR_UNSUPPORTED);
}

/*=========================================================================*/
/* 6. IMAGE PROVIDERS (SOURCES & MASKS)                                    */
/*=========================================================================*/
/**
 *  \status OK
 */
WFC_API_CALL WFCSource WFC_APIENTRY
wfcCreateSourceFromStream(WFCDevice dev,
                          WFCContext ctx,
                          WFCNativeStreamType stream,
                          const WFCint *attribList)
{
    WFCContextConfig* pContext = NULL;
    OWFNativeStreamType nativeStream;
    WFCint i;

    WFC_Source_Lock();
    GET_CONTEXT(pContext, ctx, WFC_INVALID_HANDLE);

    nativeStream = (OWFNativeStreamType) stream;
    if (OWF_INVALID_HANDLE == nativeStream)
    {
        _wfc_set_error(WFC_ERROR_ILLEGAL_ARGUMENT);
        WFC_Source_Unlock();
        return WFC_INVALID_HANDLE;
    }

    // find if any empty slot to put this new source
    for (i = WFC_CONTEXT_MAX_INSERTED_ELEMENT; i-- != 0; )
    {
        if (WFC_FALSE == _wfc_sources[i]._isCreated)
        {
            // 2011/01/16 Added by CT
            _wfc_sources[i].ctxt = ctx;
            _wfc_sources[i].useStream = WFC_TRUE;
            _wfc_sources[i].stream = nativeStream;
            _wfc_sources[i]._streamBuffer = OWF_INVALID_HANDLE;
            _wfc_sources[i]._needChangeBuffer = WFC_FALSE;
            _wfc_sources[i]._isChangingBuffer = WFC_FALSE;
            _wfc_sources[i]._isCreated = WFC_TRUE;

            // KeTing: This is a magic
            // KeTing: We will use this field to see if the stream source is ready to blt or not
            // KeTing: If the stream source is ready, it will be wrapped as an image source and thus this field will be set
            _wfc_sources[i].image.data = OWF_INVALID_HANDLE;
            // check stream parameters

            WFC_Source_Unlock();
            DDV2CatcherLogL3(TRACE_DDV2_RESOURCEALLOCATION, DDV2_TRC_WFCCREATESOURCEFROMSTREAM,
                                               drv_get_current_time(),
                                               (kal_uint32)kal_get_current_thread_ID(),
                                               ctx,
                                               &(_wfc_sources[i]));
            return (WFCSource) &(_wfc_sources[i]);
        }
    }

    _wfc_set_error(WFC_ERROR_OUT_OF_MEMORY);
    WFC_Source_Unlock();
    DDV2CatcherLogL3(TRACE_DDV2_RESOURCEALLOCATION, DDV2_TRC_ERROR_CREATESOURCEFAIL,
                                               drv_get_current_time(),
                                               (kal_uint32)kal_get_current_thread_ID(),
                                               WFC_CreateSourceFromStream);
    return WFC_INVALID_HANDLE;
}

// TODO: [m] GDI requested that the struct of the image should be stored by WFC rather than GDI...
/**
 *  \status OK
 */
WFC_API_CALL WFCSource WFC_APIENTRY
wfcCreateSourceFromImage(WFCDevice dev, 
                         WFCContext ctx,
                         WFCHandle image,
                         const WFCint *attribList)
{
    WFCContextConfig* pContext = NULL;
    OWF_IMAGE* pImage = NULL;
    WFCint i;

    wfcTrace3(WFCDBG____CREATE_IMG____________SRC, (WFCint)image, 0, 0);
    WFC_Source_Lock();
    GET_CONTEXT(pContext, ctx, WFC_INVALID_HANDLE);

    pImage = (OWF_IMAGE*) image;
    if (NULL == pImage)
    {
        _wfc_set_error(WFC_ERROR_ILLEGAL_ARGUMENT);
        WFC_Source_Unlock();
        return WFC_INVALID_HANDLE;
    }

    // find if any empty slot to put this new source
    for (i = WFC_MAX_SOURCE_NUMBER; i-- != 0; )
    {
        if (WFC_FALSE == _wfc_sources[i]._isCreated)
        {
            _wfc_sources[i].ctxt = ctx;
            _wfc_sources[i].useStream = WFC_FALSE;
            kal_mem_cpy((void*) &(_wfc_sources[i].image), 
                (void*) pImage, sizeof(OWF_IMAGE));
            _wfc_sources[i]._isCreated = WFC_TRUE;
            // check stream parameters

            WFC_Source_Unlock();
            DDV2CatcherLogL3(TRACE_DDV2_RESOURCEALLOCATION, DDV2_TRC_WFCCREATESOURCEFROMIMAGE,
                                               drv_get_current_time(),
                                               (kal_uint32)kal_get_current_thread_ID(),
                                               ctx,
                                               image,
                                               &(_wfc_sources[i]));
            return (WFCSource) &(_wfc_sources[i]);
        }
    }

    _wfc_set_error(WFC_ERROR_OUT_OF_MEMORY);
    WFC_Source_Unlock();
    wfcTrace(WFCDBG____CREATE_IMG________SRC_END);
    DDV2CatcherLogL3(TRACE_DDV2_RESOURCEALLOCATION, DDV2_TRC_ERROR_CREATESOURCEFAIL,
                                               drv_get_current_time(),
                                               (kal_uint32)kal_get_current_thread_ID(),
                                               WFC_CreateSourceFromImage);
    return WFC_INVALID_HANDLE;
}

/**
 *  \status OK
 */
WFC_API_CALL void WFC_APIENTRY
wfcDestroySource(WFCDevice dev,
                 WFCSource src)
{
    WFCSourceConfig* pSource;
    WFCElementConfig* pElement;

    DDV2CatcherLogL3(TRACE_DDV2_RESOURCEALLOCATION, DDV2_TRC_WFCDESTROYSOURCE,
                                     drv_get_current_time(),
                                     (kal_uint32)kal_get_current_thread_ID(),
                                     src);
    wfcTrace3(WFCDBG____DESTROY_______________SRC, (WFCuint)src, 0, 0);
    WFC_Source_Lock();
    pSource = (WFCSourceConfig*) src;
    if (NULL == pSource)
    {
        WFC_Source_Unlock();
        return;
    }

    pElement = (WFCElementConfig*) pSource->element;
    // unbind the connection between source and element
    if ((WFC_INVALID_HANDLE != pElement) && ((WFCSource)pSource == pElement->capturedRWAttrib->source))
        pElement->capturedRWAttrib->source = WFC_INVALID_HANDLE;
    kal_mem_set((void*) (pSource), 0x0, sizeof(WFCSourceConfig));

    WFC_Source_Unlock();
    return;

}

WFC_API_CALL WFCSource WFC_APIENTRY
wfcDestroyAndCreateSourceFromImage(WFCDevice dev,
					WFCContext ctx,
					WFCSource oldSrc,
					WFCHandle image,
					const WFCint *attribList)
{
	WFCSourceConfig* pOldSource;
	WFCElementConfig* pElement;
	WFCContextConfig* pContext;
	OWF_IMAGE* pImage;
	
    wfcTrace3(WFCDBG____CREATE_IMG____________SRC, (WFCint)image, 0, 0);
	// check attribute
	GET_CONTEXT(pContext, ctx, WFC_INVALID_HANDLE);

	if(NULL == oldSrc)
	{
		return wfcCreateSourceFromImage(dev, ctx, image, attribList);
	}
	
	pOldSource = (WFCSourceConfig*)oldSrc;
	pImage = (OWF_IMAGE*)image;
	pElement = (WFCElementConfig*)pOldSource->element;
	
	if(	NULL == pImage || WFC_FALSE == pOldSource->_isCreated)
	{
		_wfc_set_error(WFC_ERROR_ILLEGAL_ARGUMENT);
		
		return WFC_INVALID_HANDLE;
	}

    if ((WFC_INVALID_HANDLE != pElement) && ((WFCSource)pOldSource == pElement->capturedRWAttrib->source))
		//unbind the connection between old source and element
		pElement->capturedRWAttrib->source = WFC_INVALID_HANDLE;
	//create new source
	pOldSource->ctxt = ctx;
	pOldSource->useStream = WFC_FALSE;
	pOldSource->element = WFC_INVALID_HANDLE;
	kal_mem_cpy((void*)&(pOldSource->image),(void*) pImage, sizeof(OWF_IMAGE));
	wfcTrace(WFCDBG____CREATE_IMG________SRC_END);
	
	return (WFCSource)pOldSource;

}
/**
 *  \status OK
 */
WFC_API_CALL WFCMask WFC_APIENTRY
wfcCreateMaskFromStream(WFCDevice dev,
                        WFCContext ctx,
                        WFCNativeStreamType stream,
                        const WFCint *attribList) WFC_APIEXIT
{
    _wfc_set_error(WFC_ERROR_UNSUPPORTED);
    return WFC_INVALID_HANDLE;
}

/**
 *  \status OK
 */
WFC_API_CALL void WFC_APIENTRY
wfcDestroyMask(WFCDevice dev,
               WFCMask mask) WFC_APIEXIT
{
    _wfc_set_error(WFC_ERROR_UNSUPPORTED);
    return;
}

/*=========================================================================*/
/* 7. COMPOSITION ELEMENTS                                                 */
/*=========================================================================*/
/**
 *  \status OK
 */
WFC_API_CALL WFCElement WFC_APIENTRY
wfcCreateElement(WFCDevice dev,
                 WFCContext ctx,
                 const WFCint* attribList) WFC_APIEXIT
{
    WFCContextConfig* pContext = NULL;
    WFCElementConfig* pElement = NULL;
    
    wfcTrace(WFCDBG____CREATE____________ELEMENT);

    GET_CONTEXT(pContext, ctx, WFC_INVALID_HANDLE);

    // Find an empty slot in _wfc_elements[]
    {
        WFCint i = WFC_ELEMENT_MAX_COUNT - 1;
        for (; i >= 0; i--)
        {
            if (WFC_INVALID_HANDLE == _wfc_elements[i]._context)
            {
                pElement = (WFCElementConfig*)(&(_wfc_elements[i]));

                // Initialize it
                {
                    pElement->_context = (WFCContext) pContext;
                    pElement->cachedRWAttrib = &(pElement->__RWAttrib[0]);
                    pElement->capturedRWAttrib = &(pElement->__RWAttrib[1]);
                    pElement->cachedRWAttrib->isDCLayer = WFC_FALSE;
                    //pElement->_pipeline = WFC_INVALID_HANDLE;
                }
                break;		  
            }
        }
    }

    if (NULL == pElement)
    {
        _wfc_set_error(WFC_ERROR_OUT_OF_MEMORY);
    }

    DDV2CatcherLogL3(TRACE_DDV2_RESOURCEALLOCATION, DDV2_TRC_WFCCREATEELEMENT,
                                        drv_get_current_time(),
                                        (kal_uint32)kal_get_current_thread_ID(),
                                        ctx,
                                        pElement);
    return (WFCElement) pElement;
}

/**
 *  \status OK
 */
WFC_API_CALL void WFC_APIENTRY
wfcDestroyElement(WFCDevice dev,
                  WFCElement element) WFC_APIEXIT
{
    WFCElementConfig* pElement = NULL;
    WFCSourceConfig* pSource = NULL;
    WFCContextConfig* pContext = NULL;

    wfcTrace3(WFCDBG____DESTROY___________ELEMENT, (WFCuint)element, 0, 0);
    GET_ELEMENT_NR(pElement, element);

    // If the source is a stream, de-register the observer...
    pSource = (WFCSourceConfig*) pElement->capturedRWAttrib->source;
    if ((NULL != pSource) && pSource->useStream && pSource->stream)
    {
        owfNativeStreamRemoveObserver((OWFNativeStreamType) pSource->stream, 
                                  _wfc_stream_event_hdlr, 
                                  (void*) pElement);
    }

    // Destroy pipelines and sources...
    {
        pContext = (WFCContextConfig*) pElement->_context;
        WFC_ASSERT(NULL != pContext);

        if (WFC_INVALID_HANDLE != pElement->capturedRWAttrib->source)
        {
            WFCuint i;
            // destory wfcSourceHandle    

            for (i = 0; i < WFC_MAX_SOURCE_NUMBER; i++)
            {
                if (((WFCSource) (&_wfc_sources[i])) == pElement->capturedRWAttrib->source)
                {
                    // clear source
                    //pContext->_sources[i].source.image = WFC_INVALID_HANDLE;
                    WFCSourceConfig* pSource = (WFCSourceConfig*)(&_wfc_sources[i]);

                    kal_mem_set((void*) (&pSource->image), 0x0, sizeof(OWF_IMAGE));				  
                    kal_mem_set((void*) &(_wfc_sources[i]), 0x0, sizeof(WFCSourceConfig));
                    pElement->capturedRWAttrib->source = WFC_INVALID_HANDLE;				  
                    break;
                }
            }
        }

        //Remove elements from _insertedElements...
        {
            kal_uint32 i = 4;
            for (; i-- > 0; )
            {
                if (pContext->cachedRWAttrib->_insertedElements[i] == element)
                {
                    pContext->cachedRWAttrib->_insertedElements[i] = WFC_INVALID_HANDLE;

                    // Move valid entry up...
                    for (; i++ != (4-1); )
                    {
                        pContext->cachedRWAttrib->_insertedElements[i] ^= pContext->cachedRWAttrib->_insertedElements[i-1];
                        pContext->cachedRWAttrib->_insertedElements[i-1] ^= pContext->cachedRWAttrib->_insertedElements[i];
                        pContext->cachedRWAttrib->_insertedElements[i] ^= pContext->cachedRWAttrib->_insertedElements[i-1];
                    }
                    break;
                }
            }
        }
    }

    // deinitialize self.
    kal_mem_set((void*) pElement, 0x0, sizeof(WFCElementConfig));

    DDV2CatcherLogL3(TRACE_DDV2_RESOURCEALLOCATION, DDV2_TRC_WFCDESTROYELEMENT,
                                        drv_get_current_time(),
                                        (kal_uint32)kal_get_current_thread_ID(),
                                        element);
    return;
}

/**
 *  \status OK
 */
WFC_API_CALL WFCint WFC_APIENTRY
wfcGetElementAttribi(WFCDevice dev,
                     WFCElement element,
                     WFCElementAttrib attrib) WFC_APIEXIT
{
    WFCElementConfig* pElement = NULL;
    WFCint ret = 0;
    GET_ELEMENT(pElement, element, ret);

    switch (attrib)
    {
        case WFC_ELEMENT_SOURCE: 
            ret = (WFCint) pElement->cachedRWAttrib->source;
            break;
        case WFC_ELEMENT_SOURCE_FLIP: 
            ret = (WFCint) pElement->cachedRWAttrib->flip;
            break;
        case WFC_ELEMENT_SOURCE_ROTATION: 
            ret = (WFCint) pElement->cachedRWAttrib->rotationAngle;
            break;
        case WFC_ELEMENT_TRANSPARENCY_TYPES: 
            ret = (WFCint) pElement->cachedRWAttrib->transparencyType;
            break;
        case WFC_ELEMENT_GLOBAL_ALPHA: 
            ret = (WFCint) pElement->cachedRWAttrib->globalAlpha;
            break;
        case WFC_ELEMENT_SOURCE_COLOR_KEY_MTK: 
            ret = (WFCint) pElement->cachedRWAttrib->sourceColorKey;
            break;
        case WFC_ELEMENT_DITHERING_MTK: 
            ret = (WFCint) pElement->cachedRWAttrib->enableSpatialDithering;
            break;
        case WFC_ELEMENT_VIDEO_LAYER_MTK: 
            ret = (WFCint) pElement->cachedRWAttrib->isVideoLayer;
            break;
	#ifdef DRV_LCD_3D_MODE_SUPPORT
        case WFC_ELEMENT_3D_LAYER_MTK: 
            ret = (WFCint) pElement->cachedRWAttrib->is3DLayer;
            break;	
        case WFC_ELEMENT_3D_VIEW_MODE_MTK: 
            ret = (WFCint) pElement->cachedRWAttrib->_3DimageViewMode;
            break;	
	    case WFC_ELEMENT_3D_FIRST_EYE_MODE_MTK: 
            ret = (WFCint) pElement->cachedRWAttrib->_3DimageFirstEyeMode;
            break;	
        case WFC_ELEMENT_3D_START_ADDR_MODE_MTK: 
            ret = (WFCint) pElement->cachedRWAttrib->_3DimageStartAddrMode;
            break;	
	#endif
        default: 
            _wfc_set_error(WFC_ERROR_BAD_ATTRIBUTE);
            break;
    }

    return ret;
}

/**
 *  \status OK
 */
WFC_API_CALL WFCfloat WFC_APIENTRY
wfcGetElementAttribf(WFCDevice dev,
                     WFCElement element,
                     WFCElementAttrib attrib) WFC_APIEXIT
{
    _wfc_set_error(WFC_ERROR_UNSUPPORTED);
    return 0x0;
}

/**
 *  \status OK
 */
WFC_API_CALL void WFC_APIENTRY
wfcGetElementAttribiv(WFCDevice dev,
                      WFCElement element,
                      WFCElementAttrib attrib,
                      WFCint count,
                      WFCint *values) WFC_APIEXIT
{
    WFCElementConfig* pElement = NULL;

    GET_ELEMENT_NR(pElement, element);

    if ((0 >= count) || (NULL == values))
    {
        _wfc_set_error(WFC_ERROR_ILLEGAL_ARGUMENT);
        return;
    }

    switch (attrib)
    {
    case WFC_ELEMENT_DESTINATION_RECTANGLE: /* WFCint[4]    (offsetX, offsetY, width, height) */
        WFC_ASSERT(4 <= count);
        if (4 > count)
        {
            _wfc_set_error(WFC_ERROR_ILLEGAL_ARGUMENT); 
            break;
        }
        values[0] = (WFCint) pElement->cachedRWAttrib->destinationRect.x;
        values[1] = (WFCint) pElement->cachedRWAttrib->destinationRect.y;
        values[2] = (WFCint) pElement->cachedRWAttrib->destinationRect.width;
        values[3] = (WFCint) pElement->cachedRWAttrib->destinationRect.height;
        break;
    case WFC_ELEMENT_SOURCE_RECTANGLE: /* WFCint[4]    (offsetX, offsetY, width, height) */
        WFC_ASSERT(4 <= count);
        if (4 > count)
        {
            _wfc_set_error(WFC_ERROR_ILLEGAL_ARGUMENT);
            break;
        }
        values[0] = (WFCint) pElement->cachedRWAttrib->sourceRect.x;
        values[1] = (WFCint) pElement->cachedRWAttrib->sourceRect.y;
        values[2] = (WFCint) pElement->cachedRWAttrib->sourceRect.width;
        values[3] = (WFCint) pElement->cachedRWAttrib->sourceRect.height;
        break;
    case WFC_ELEMENT_ALL_ATTRIBUTES_MTK:
        kal_mem_cpy((void *)values, (void *)pElement->cachedRWAttrib, sizeof(WFCElementRWAttrib));
        break;
    default:
        _wfc_set_error(WFC_ERROR_BAD_ATTRIBUTE); 
        break;
    }

    return;
}

/**
 *  \status OK
 */
WFC_API_CALL void WFC_APIENTRY
wfcGetElementAttribfv(WFCDevice dev,
                      WFCElement element,
                      WFCElementAttrib attrib,
                      WFCint count,
                      WFCfloat *values) WFC_APIEXIT
{
    _wfc_set_error(WFC_ERROR_UNSUPPORTED);
    return;
}


/**
 *  \status OK
 */
WFC_API_CALL void WFC_APIENTRY
wfcSetElementAttribi(WFCDevice dev,
                     WFCElement element,
                     WFCElementAttrib attrib,
                     WFCint value) WFC_APIEXIT
{
    WFCElementConfig* pElement = NULL;
    WFCContextConfig* pContext = NULL;
    WFCboolean inAutoMode = WFC_FALSE;
    WFCboolean is_AutoMode_VideoElement = WFC_FALSE;
    WFCboolean is_illegal_element_attribi = WFC_FALSE;

    DDV2CatcherLogL3(TRACE_DDV2_ELEMENTATTRIB, DDV2_TRC_WFCSETELEMENTATTRIBI,
                                     drv_get_current_time(),
                                     (kal_uint32)kal_get_current_thread_ID(),
                                     element,
                                     attrib,
                                     value);
    GET_ELEMENT_NR(pElement, element);
    GET_CONTEXT_NR(pContext, pElement->_context);
    inAutoMode = _wfc_is_context_in_autonomous_mode(pElement->_context);

    if(inAutoMode == WFC_TRUE && pElement->cachedRWAttrib->isVideoLayer == WFC_TRUE)
    {
        is_AutoMode_VideoElement = WFC_TRUE;
    }

    switch (attrib)
    {
        case WFC_ELEMENT_TRANSPARENCY_TYPES: 
          pElement->cachedRWAttrib->transparencyType = (WFCbitfield) value;
          break;
        case WFC_ELEMENT_GLOBAL_ALPHA: 
          pElement->cachedRWAttrib->globalAlpha = (WFCint) value;
          break;
        case WFC_ELEMENT_SOURCE_COLOR_KEY_MTK: 
          pElement->cachedRWAttrib->sourceColorKey = (WFCuint) value;
          break;
        case WFC_ELEMENT_DITHERING_MTK: 
          pElement->cachedRWAttrib->enableSpatialDithering = (WFCboolean) value;
          break;
        case WFC_ELEMENT_VIDEO_LAYER_MTK: 
		{
          pElement->cachedRWAttrib->isVideoLayer = (WFCboolean) value;
			  //Yinli:   if GDI modify video-layer flag in auto-mode, will print a log.
			  if(is_AutoMode_VideoElement == WFC_TRUE
			  	&& _wfc_check_element_inserted(pContext, element) == WFC_TRUE
			  	&& (WFCboolean)value == WFC_FALSE)
			  {
				DDV2CatcherLogL3(TRACE_DDV2_ELEMENTATTRIB, DDV2_TRC_WFCSETELEMENTVIDEOFLAGINAUTOMODE,
												 drv_get_current_time(),
												 (kal_uint32)kal_get_current_thread_ID(),
												 element,
												 attrib,
												 (WFCboolean)value);
			  }
          break;
        }

        ///Bin: The following are illegal for GDI in Auto mode
        case WFC_ELEMENT_SOURCE: 
        {
            if (WFC_FALSE == is_AutoMode_VideoElement)
            {
                WFCSourceConfig* pSource = (WFCSourceConfig*) value;
                WFCSourceConfig* pOriSource;
                pOriSource = (WFCSourceConfig*)(pElement->cachedRWAttrib->source);
                if (pOriSource)
                    pOriSource->element = WFC_INVALID_HANDLE;
                pElement->cachedRWAttrib->source = (WFCSource) value;
                // If the input source handle is NULL, it means user wants to remove the connection between the source and element.
                if (pSource)
                {
                    pSource->element = element;
                }                
            } //if (is_AutoMode_VideoElement == WFC_FALSE)
            else
            {
                is_illegal_element_attribi = WFC_TRUE;
            }

            break;
        }  
        case WFC_ELEMENT_SOURCE_FLIP: 
        {
            if (WFC_FALSE == is_AutoMode_VideoElement)
            {
                pElement->cachedRWAttrib->flip = (WFCboolean) value;
            } //if (is_AutoMode_VideoElement == WFC_FALSE)
            else
            {
                is_illegal_element_attribi = WFC_TRUE;
            }
       
            break;
        }  
        case WFC_ELEMENT_SOURCE_ROTATION: 
        {
            if (WFC_FALSE == is_AutoMode_VideoElement)
            {
                pElement->cachedRWAttrib->rotationAngle = (WFCRotation) value;
            } //if (is_AutoMode_VideoElement == WFC_FALSE)
            else
            {
                is_illegal_element_attribi = WFC_TRUE;
            }

            break;
        }  

        case WFC_ELEMENT_DC_LAYER_MTK: 
        {
            if (WFC_FALSE == is_AutoMode_VideoElement)
            {
                pElement->cachedRWAttrib->isDCLayer = (WFCboolean) value;
            } //if (is_AutoMode_VideoElement == WFC_FALSE)
            else
            {
                is_illegal_element_attribi = WFC_TRUE;
            }

            break;
        }  
	#ifdef DRV_LCD_3D_MODE_SUPPORT
		case WFC_ELEMENT_3D_LAYER_MTK: 
          pElement->cachedRWAttrib->is3DLayer = (WFCboolean) value;
          break;
		case WFC_ELEMENT_3D_VIEW_MODE_MTK: 
          pElement->cachedRWAttrib->_3DimageViewMode = (WFC3DViewMode) value;
          break;
		case WFC_ELEMENT_3D_FIRST_EYE_MODE_MTK: 
          pElement->cachedRWAttrib->_3DimageFirstEyeMode = (WFC3DFirstEyeMode) value;
          break;
		case WFC_ELEMENT_3D_START_ADDR_MODE_MTK: 
          pElement->cachedRWAttrib->_3DimageStartAddrMode = (WFC3DStartAddrMode) value;
          break;		  
	#endif
        default: 
            _wfc_set_error(WFC_ERROR_BAD_ATTRIBUTE);
            break;
    }

    if (is_illegal_element_attribi)
    {
        _wfc_set_error(WFC_ERROR_ILLEGAL_ARGUMENT);
        DDV2CatcherLogL3(TRACE_DDV2_ERROR, DDV2_TRC_ERROR_ILLEGAL_WFCSETELEMENTATTRIBI,
                                         drv_get_current_time(),
                                         (kal_uint32)kal_get_current_thread_ID(),
                                         element,
                                         attrib,
                                         value);
    }

    return;
}

/**
 *  \status OK
 */
WFC_API_CALL void WFC_APIENTRY
wfcSetElementAttribf(WFCDevice dev,
                     WFCElement element,
                     WFCElementAttrib attrib,
                     WFCfloat value) WFC_APIEXIT
{
    _wfc_set_error(WFC_ERROR_UNSUPPORTED);
    return;
}

/**
 *  \status OK
 */
WFC_API_CALL void WFC_APIENTRY
wfcSetElementAttribiv(WFCDevice dev,
                      WFCElement element,
                      WFCElementAttrib attrib,
                      WFCint count,
                      const WFCint *values) WFC_APIEXIT
{
    WFCElementConfig* pElement = NULL;
    WFCContextConfig* pContext = NULL;
    WFCboolean inAutoMode = WFC_FALSE;
    WFCboolean is_AutoMode_VideoElement = WFC_FALSE;
    WFCboolean is_illegal_element_attribiv = WFC_FALSE;

    if ((count >= 3) && (values != NULL))
        DDV2CatcherLogL3(TRACE_DDV2_ELEMENTATTRIB, DDV2_TRC_WFCSETELEMENTATTRIBIV,
                                            drv_get_current_time(),
                                            (kal_uint32)kal_get_current_thread_ID(),
                                            element,
                                            attrib,
                                            values[0], values[1], values[2], (count==4)?values[3]:0);
    GET_ELEMENT_NR(pElement, element);
    GET_CONTEXT_NR(pContext, pElement->_context);

    inAutoMode = _wfc_is_context_in_autonomous_mode(pElement->_context);

    if(inAutoMode == WFC_TRUE && pElement->cachedRWAttrib->isVideoLayer == WFC_TRUE)
    {
        is_AutoMode_VideoElement = WFC_TRUE;
    }

    if ((0 >= count) || (NULL == values))
    {
        _wfc_set_error(WFC_ERROR_ILLEGAL_ARGUMENT);
        return;
    }

    switch (attrib)
    {
    case WFC_ELEMENT_DESTINATION_RECTANGLE: /* WFCint[4] ==> (offsetX, offsetY, width, height) */
        WFC_ASSERT(4 == count);
        if (4 != count)
        {
            _wfc_set_error(WFC_ERROR_ILLEGAL_ARGUMENT); 
            break;
        }
        pElement->cachedRWAttrib->destinationRect.x = (OWFint) values[0];
        pElement->cachedRWAttrib->destinationRect.y = (OWFint) values[1];
        pElement->cachedRWAttrib->destinationRect.width = (OWFint) values[2];
        pElement->cachedRWAttrib->destinationRect.height = (OWFint) values[3];
        break;

        
    ///Zifeng: The following are illegal for GDI in Auto mode
    case WFC_ELEMENT_SOURCE_RECTANGLE: /* WFCint[4] ==> (offsetX, offsetY, width, height) */
    {
        if (WFC_FALSE == is_AutoMode_VideoElement)
        {
            WFC_ASSERT(4 == count);
            if (4 != count)
            {
                is_illegal_element_attribiv = WFC_TRUE;
                break;
            }
            pElement->cachedRWAttrib->sourceRect.x = (OWFint) values[0];
            pElement->cachedRWAttrib->sourceRect.y = (OWFint) values[1];
            pElement->cachedRWAttrib->sourceRect.width = (OWFint) values[2];
            pElement->cachedRWAttrib->sourceRect.height = (OWFint) values[3];
        }
        else
        {
            is_illegal_element_attribiv = WFC_TRUE;
        }
        break;
    }
    case WFC_ELEMENT_ALL_ATTRIBUTES_MTK:
		{
			{
				//Yinli:   if GDI modify video-layer flag, will print a log.
				if(((WFCElementRWAttrib*)values)->isVideoLayer != pElement->cachedRWAttrib->isVideoLayer)
			  {
			    #if (DDV2_CATCHERLOG_LEVEL == 3)
			      DDV2CatcherLogL3(TRACE_DDV2_ELEMENTATTRIB, DDV2_TRC_WFCSETELEMENTATTRIBI_VIDEO_FLAG,
													 drv_get_current_time(),
													 (kal_uint32)kal_get_current_thread_ID(),
													 element,
													 attrib,
													 ((WFCElementRWAttrib*)values)->isVideoLayer);
				#elif (DDV2_CATCHERLOG_LEVEL == 2)
				  DDV2CatcherLogL2(TRACE_DDV2_ELEMENTATTRIB, DDV2_TRC_WFCSETELEMENTATTRIBI_VIDEO_FLAG,
													 drv_get_current_time(),
													 (kal_uint32)kal_get_current_thread_ID(),
													 element,
													 attrib,
													 ((WFCElementRWAttrib*)values)->isVideoLayer);
				#endif
			 }
			}
    	///Yinli: if in auto mode but this layer is not inserted, gdi request to consider it as non-video layer
    	///Yinli: so video layer must meet below points concurrently: [1] in auto-mode, [2]the flag of isVideolayer(cachedRWAttribi)  must be true, [3]the elemnt must be inserted in context
		if(is_AutoMode_VideoElement == WFC_TRUE && _wfc_check_element_inserted(pContext, element) == WFC_TRUE)	 
			{
			kal_mem_cpy((void *)pElement->cachedRWAttrib, (void *)values, ((kal_uint32)&(pElement->cachedRWAttrib->source) - (kal_uint32)(pElement->cachedRWAttrib)));
				//Yinli: if the video layer is used by MDP, but AP try to config it as a OSD layer when hw-update mode will assert
				 if(((WFCElementRWAttrib*)values)->isVideoLayer == WFC_FALSE)
					 ASSERT(0);
			}
     	else
        {
			/// clear old source element binding
			if (pElement->cachedRWAttrib->source)
				((WFCSourceConfig*)pElement->cachedRWAttrib->source)->element = WFC_INVALID_HANDLE;

			/// apply new setting except isDCLayer
            kal_mem_cpy((void *)pElement->cachedRWAttrib, (void *)values, ((kal_uint32)&(pElement->cachedRWAttrib->isDCLayer) - (kal_uint32)(pElement->cachedRWAttrib)));

			/// binding new source to this element
			if (pElement->cachedRWAttrib->source)
				((WFCSourceConfig*)pElement->cachedRWAttrib->source)->element = element;
		}
		break;
    	}	
    default:
        _wfc_set_error(WFC_ERROR_BAD_ATTRIBUTE); 
        break;
    }
  
    if (is_illegal_element_attribiv)
    {
        _wfc_set_error(WFC_ERROR_ILLEGAL_ARGUMENT);
        DDV2CatcherLogL3(TRACE_DDV2_ERROR, DDV2_TRC_ERROR_ILLEGAL_WFCSETELEMENTATTRIBIV,
                                         drv_get_current_time(),
                                         (kal_uint32)kal_get_current_thread_ID(),
                                         element,
                                         attrib);
    }

    return;
}

/**
 *  \status OK
 */
WFC_API_CALL void WFC_APIENTRY
wfcSetElementAttribfv(WFCDevice dev,
                      WFCElement element,
                      WFCElementAttrib attrib,
                      WFCint count,
                      const WFCfloat *values) WFC_APIEXIT
{
    _wfc_set_error(WFC_ERROR_UNSUPPORTED);
    return;
}

/**
 *  \status OK
 */
WFC_API_CALL void WFC_APIENTRY
wfcInsertElement(WFCDevice dev,
                 WFCElement element,
                 WFCElement subordinate) WFC_APIEXIT
{
    WFCContextConfig* pContext = NULL;
    WFCElementConfig* pElementUpper = NULL;
    WFCElementConfig* pElementLower = NULL;
	#if (!(defined (MT6250) || defined (MT6260) || defined (MT6261)))
    WFCint ElementOrder = -1;
    WFCint SubordinateOrder = -1;
    WFCboolean bElementVideo = WFC_FALSE;
    WFCboolean bSubordinateVideo = WFC_FALSE;
	#endif

    wfcTrace3(WFCDBG____INSERT____________ELEMENT, (WFCuint)element, (WFCuint)subordinate, 0);
    GET_ELEMENT_NR(pElementUpper, element);


    if (WFC_INVALID_HANDLE != subordinate)
    {
        GET_ELEMENT_NR(pElementLower, subordinate);
        WFC_ASSERT(pElementUpper->_context == pElementLower->_context);
    }
    else
    {
        pElementLower = NULL;
    }

    pContext = (WFCContextConfig*) pElementUpper->_context;

    {
        kal_uint32 i = WFC_CONTEXT_MAX_INSERTED_ELEMENT;
        for (; i-- > 0; )
        {
            if (pContext->cachedRWAttrib->_insertedElements[i] == element)
            {
            	#if (!(defined (MT6250) || defined (MT6260) || defined (MT6261)))
                ElementOrder = i;
                bElementVideo = ((WFCElementConfig*)(pContext->cachedRWAttrib->_insertedElements[i]))->cachedRWAttrib->isVideoLayer;
                pContext->cachedRWAttrib->_insertedElements[i] = WFC_INVALID_HANDLE;
				#endif
                // Move valid entry down...
                for (; i++ != (WFC_CONTEXT_MAX_INSERTED_ELEMENT-1); )
                {
                    pContext->cachedRWAttrib->_insertedElements[i] ^= pContext->cachedRWAttrib->_insertedElements[i-1];
                    pContext->cachedRWAttrib->_insertedElements[i-1] ^= pContext->cachedRWAttrib->_insertedElements[i];
                    pContext->cachedRWAttrib->_insertedElements[i] ^= pContext->cachedRWAttrib->_insertedElements[i-1];
                }
                break;
            }
        }
    }


    // Insert at the top first then move downward if subordinate is not found...
    {
        WFCint i;
        if (WFC_INVALID_HANDLE != pContext->cachedRWAttrib->_insertedElements[WFC_CONTEXT_MAX_INSERTED_ELEMENT-1])
        {
            _wfc_set_error(WFC_ERROR_OUT_OF_MEMORY);
            return;
        }

        pContext->cachedRWAttrib->_insertedElements[WFC_CONTEXT_MAX_INSERTED_ELEMENT-1] = (WFCElement)pElementUpper;

        for (i = WFC_CONTEXT_MAX_INSERTED_ELEMENT - 1; i > 0; i--)
        {
            if ((pContext->cachedRWAttrib->_insertedElements[(i-1)] == subordinate) &&  
                (pContext->cachedRWAttrib->_insertedElements[(i-1)] != WFC_INVALID_HANDLE))
            {
            	#if (!(defined (MT6250) || defined (MT6260) || defined (MT6261)))
                SubordinateOrder = i-1;
                bSubordinateVideo = ((WFCElementConfig*)(pContext->cachedRWAttrib->_insertedElements[(i-1)]))->cachedRWAttrib->isVideoLayer;
				#endif
                break;
            }
            else
            {
                // swap
                pContext->cachedRWAttrib->_insertedElements[(i-1)] ^= pContext->cachedRWAttrib->_insertedElements[i];
                pContext->cachedRWAttrib->_insertedElements[i] ^= pContext->cachedRWAttrib->_insertedElements[(i-1)];
                pContext->cachedRWAttrib->_insertedElements[(i-1)] ^= pContext->cachedRWAttrib->_insertedElements[i];
            }
        }
    }
	#if (!(defined (MT6250) || defined (MT6260) || defined (MT6261)))
    DDV2CatcherLogL3(TRACE_DDV2_ELEMENTINSERTION, DDV2_TRC_WFCINSERTELEMENT,
                                        drv_get_current_time(),
                                        (kal_uint32)kal_get_current_thread_ID(),
                                        pContext,
                                        element,
                                        subordinate,
                                        ElementOrder,
                                        SubordinateOrder,
                                        bElementVideo,
                                        bSubordinateVideo);
	#endif
    return;
}

/**
 *  \status OK
 */
WFC_API_CALL void WFC_APIENTRY
wfcRemoveElement(WFCDevice dev,
                 WFCElement element) WFC_APIEXIT
{
    WFCContextConfig* pContext = NULL;
    WFCElementConfig* pElement = NULL;
	#if (!(defined (MT6250) || defined (MT6260) || defined (MT6261)))
    WFCint ElementOrder = -1;
    WFCboolean bElementVideo = WFC_FALSE;
	#endif
    wfcTrace3(WFCDBG____REMOVE____________ELEMENT, (WFCuint)element, 0, 0);

    GET_ELEMENT_NR(pElement, element);

    pContext = (WFCContextConfig*) pElement->_context;

    {
        kal_uint32 i = WFC_CONTEXT_MAX_INSERTED_ELEMENT;
        for (; i-- > 0; )
        {
            if (pContext->cachedRWAttrib->_insertedElements[i] == element)
            {
            	#if (!(defined (MT6250) || defined (MT6260) || defined (MT6261)))
                ElementOrder = i;
                bElementVideo = ((WFCElementConfig*)(pContext->cachedRWAttrib->_insertedElements[i]))->cachedRWAttrib->isVideoLayer;
				#endif
                pContext->cachedRWAttrib->_insertedElements[i] = WFC_INVALID_HANDLE;

                // Move valid entry down...
                for (; i++ != (WFC_CONTEXT_MAX_INSERTED_ELEMENT - 1); )
                {
                    pContext->cachedRWAttrib->_insertedElements[i] ^= pContext->cachedRWAttrib->_insertedElements[i-1];
                    pContext->cachedRWAttrib->_insertedElements[i-1] ^= pContext->cachedRWAttrib->_insertedElements[i];
                    pContext->cachedRWAttrib->_insertedElements[i] ^= pContext->cachedRWAttrib->_insertedElements[i-1];
                }
                break;
            }
        }
    }
	#if (!(defined (MT6250) || defined (MT6260) || defined (MT6261)))
    DDV2CatcherLogL3(TRACE_DDV2_ELEMENTINSERTION, DDV2_TRC_WFCREMOVEELEMENT,
                                        drv_get_current_time(),
                                        (kal_uint32)kal_get_current_thread_ID(),
                                        pContext,
                                        element,
                                        ElementOrder,
                                        bElementVideo);
	#endif
    return;
  
}

/**
 *  \status OK
 * to let user know which element is inserted above the element
 */
WFC_API_CALL WFCElement WFC_APIENTRY
wfcGetElementAbove(WFCDevice dev, WFCElement element) WFC_APIEXIT
{
    WFCContextConfig* pContext = NULL;
    WFCElementConfig* pElement = NULL;
    WFCElement ret = WFC_INVALID_HANDLE;

    GET_ELEMENT(pElement, element, ret);
    GET_CONTEXT(pContext, pElement->_context, ret);

    {
        kal_uint32 i = WFC_CONTEXT_MAX_INSERTED_ELEMENT;
        for (; i-- != 0; )
        {
            if ((pContext->cachedRWAttrib->_insertedElements[i] == element) && 
                ((WFC_CONTEXT_MAX_INSERTED_ELEMENT-1) > i))
            {
                ret = (WFCElement) pContext->cachedRWAttrib->_insertedElements[(i+1)];
                break;
            }
        }
    }

    return ret;
}

/**
 *  \status OK
 * to let user know which element is inserted under the element
 */
WFC_API_CALL WFCElement WFC_APIENTRY
wfcGetElementBelow(WFCDevice dev, WFCElement element) WFC_APIEXIT
{
    WFCContextConfig* pContext = NULL;
    WFCElementConfig* pElement = NULL;
    WFCElement ret = WFC_INVALID_HANDLE;

    GET_ELEMENT(pElement, element, ret);
    GET_CONTEXT(pContext, pElement->_context, ret);

    {
        kal_uint32 i = WFC_CONTEXT_MAX_INSERTED_ELEMENT;
        for (; i-- > 0; )
        {
            if ((pContext->cachedRWAttrib->_insertedElements[i] == element) && 
                (0 != i))
            {
                ret = (WFCElement) pContext->cachedRWAttrib->_insertedElements[(i-1)];
                break;
            }
        }
    }

    return ret;
}


/**
 *  \status OK
 *  This funtion is used to clone one element include its all setting and binded-source setting
 */
WFC_API_CALL void WFC_APIENTRY
wfcCloneElementAttribute(WFCDevice dev, WFCElement SourceElement, WFCElement DestElement) WFC_APIEXIT
{
    WFCElementConfig* pSrcElement = NULL;
    WFCElementConfig* pDstElement = NULL;
    WFCSourceConfig*  pSrcSource = NULL;
    WFCSourceConfig*  pDstSource = NULL;
    DDV2CatcherLogL3(TRACE_DDV2_RENDERING, DDV2_TRC_WFCCLONEELEMENT,
                                     drv_get_current_time(),
                                     (kal_uint32)kal_get_current_thread_ID(),
                                     SourceElement,
                                     DestElement);

    pSrcElement = (WFCElementConfig*)SourceElement;
    pDstElement = (WFCElementConfig*)DestElement;
    if (pSrcElement == NULL || pDstElement == NULL)
    {
        _wfc_set_error(WFC_ERROR_BAD_HANDLE);
        return;
    }
    pSrcSource = (WFCSourceConfig*) (pSrcElement->cachedRWAttrib->source);
    pDstSource = (WFCSourceConfig*) (pDstElement->cachedRWAttrib->source);
    memcpy(pDstElement->cachedRWAttrib, pSrcElement->cachedRWAttrib, sizeof(WFCElementRWAttrib));
    
    pDstElement->cachedRWAttrib->source = (WFCSource) pDstSource;
    if (pSrcSource == NULL || pDstSource == NULL)
    {
        return;
    }
    memcpy(&(pDstSource->image), &(pSrcSource->image), sizeof(OWF_IMAGE));
}


/*=========================================================================*/
/* 8. RENDERING                                                            */
/*=========================================================================*/

// KeTing: The behaivor of this function is defined as follow
// KeTing: 1. If context is not in autonomous mode, enter autonomous mode
// KeTing: 2. If context is already in autonomous mode, refresh the sync trigger config
WFC_API_CALL void WFC_APIENTRY
wfcActivate(WFCDevice dev,
            WFCContext ctx) WFC_APIEXIT
{
    WFCContextConfig* pContext = NULL;
    WFCCtxtRWAttrib* pContextCatchedAttrib = NULL;
    WFCCtxtRWAttrib* pContextCapturedAttrib = NULL;

    DDV2CatcherLogL3(TRACE_DDV2_RENDERING, DDV2_TRC_WFCACTIVATE,
                                          drv_get_current_time(),
                                          (kal_uint32)kal_get_current_thread_ID(),
                                          ctx);
    wfcTrace(WFCDBG____AUTO_____________ACTIVATE);
    GET_CONTEXT_NR(pContext, ctx);

    pContextCatchedAttrib = pContext->cachedRWAttrib;
    pContextCapturedAttrib = pContext->capturedRWAttrib;
    
    // Bin: Auto mode is not valid for off screen context
    if (&_wfc_context_cfg_frame_buffer == pContext)
    {
        _wfc_set_error(WFC_ERROR_BAD_HANDLE);
        goto Exit;
    }

    if (WFC_AUTONOMOUS_STATE_TURNING_OFF == pContext->_autonomousMode)
    {
        // Bin: this case should not happened in current implementation, therefore using ASSERT(0) to check here
        WFC_ASSERT(0);
        _wfc_set_error(WFC_ERROR_BUSY);
        goto Exit;
    }


    if (WFC_AUTONOMOUS_STATE_OFF == pContext->_autonomousMode)
    {
        //int i;

        // KeTing: Regist the device and context as autonomous mode
        if (WFC_FALSE == _wfc_regist_autonomous_mode(pContext))
        {
            _wfc_set_error(WFC_ERROR_ILLEGAL_ARGUMENT);
            goto Exit;
        }

        // KeTing: Make sure this context is get rid of previous blt
        // KeTing: Do not remove this or we may commit to wfd while it is busy
        _wfc_wait_until_wfd_not_busy(pContext);
        memset(&(pContext->_autoModeRoiRect), 0, sizeof(OWF_RECTANGLE));
    
        // KeTing: This is only for MT6253
        // KeTing: Once it is phased out, the following code segement can also be removed
        ((WFD_DEVICE*)(pContext->_engine))->config.enableFastRotatorMem = WFD_TRUE;
        wfdDeviceCommit(pContext->_engine, WFD_COMMIT_ENTIRE_DEVICE, pContext->_engine);
        
        {
            // When enter Hw_update, AP do not want to consider ROI
            // in Auto mode, the ROI rectangle will be updated in _wfc_wait_until_wfd_not_busy()
            // Here set to zero, is just for easy to merge in _wfc_wait_until_wfd_not_busy()
            pContextCatchedAttrib->roiRect.x = 0;
            pContextCatchedAttrib->roiRect.y = 0;
            pContextCatchedAttrib->destinationRect.x = 0;
            pContextCatchedAttrib->destinationRect.y = 0;
            pContextCatchedAttrib->roiRect.width = pContextCatchedAttrib->destinationRect.width = 0;
            pContextCatchedAttrib->roiRect.height = pContextCatchedAttrib->destinationRect.height = 0;

            kal_mem_cpy((void*) (&(pContextCapturedAttrib->roiRect)), 
                        (void*) (&(pContextCatchedAttrib->roiRect)), 
                        sizeof(OWF_RECTANGLE));
            kal_mem_cpy((void*) &(pContextCapturedAttrib->destinationRect), 
                        (void*) &(pContextCatchedAttrib->destinationRect), 
                        sizeof(OWF_RECTANGLE));
        }
    }

    pContext->_autonomousMode = WFC_AUTONOMOUS_STATE_ON;

Exit:
  
  return;
}



// KeTing: The behaivor of this function is defined as follow
// KeTing: 1. If context is in autonomous mode, leave the autonomous mode
// KeTing: 2. If context is not in autonomous mode, do nothing
WFC_API_CALL void WFC_APIENTRY
wfcDeactivate(WFCDevice dev,
              WFCContext ctx) WFC_APIEXIT
{
    WFCContextConfig* pContext = NULL;

    DDV2CatcherLogL3(TRACE_DDV2_RENDERING, DDV2_TRC_WFCDEACTIVATE,
                                          drv_get_current_time(),
                                          (kal_uint32)kal_get_current_thread_ID(),
                                          ctx);
    wfcTrace(WFCDBG____AUTO___________DEACTIVATE);
    GET_CONTEXT_NR(pContext, ctx);

    // KeTing: If off screen context
    if (&_wfc_context_cfg_frame_buffer == pContext)
    {
        _wfc_set_error(WFC_ERROR_BAD_HANDLE);
        goto Exit;
    }

    // KeTing: If not in autonomous mode...
    if (WFC_AUTONOMOUS_STATE_OFF == pContext->_autonomousMode || WFC_AUTONOMOUS_STATE_TURNING_OFF == pContext->_autonomousMode)
    {
        goto Exit;
    }

    _wfc_wait_until_wfd_not_busy(pContext);//Xiaoyong:wait the previous blt to finish, the GDI will not wait before call wfcDeactivate, for fast exit auto mode
	if (_timer_run_status == KAL_TRUE)
	{ 
		kal_cancel_timer(pContext->_timer);//Xiaoyong:cancel the auto mode timer for fast exit auto mode
		_timer_run_status = KAL_FALSE;
	}
    // KeTing: Make sure this context is get rid of auto mode completely
    // KeTing: Do not remove this or we may commit to wfd while it is busy
	if (_wfc_committed_flag == WFC_TRUE)  //Xiaoyong:If there is valid commit and blt request in audo mode, blt it before exit auto mode, because timer is cancelled
	{
		_wfc_autonomous_activate_hisr_in_deactivate(pContext);
    	kal_sleep_task(1);//make sure hisr will be excuted, !!!FIX ME, is this need???
	}
	_wfc_wait_until_wfd_not_busy(pContext);//Xiaoyong:To wait the last blt if has before exit auto mode	

    // KeTing: De-regist the device and context as autonomous mode
    if (WFC_FALSE == _wfc_deregist_autonomous_mode(pContext))
    {
        goto Exit;
    }

    /// Bin: turning off auto mode to make sure _wfc_autonomous_timer_handler() and _wfc_stream_event_hdlr() stop handle auto mode event
    pContext->_autonomousMode = WFC_AUTONOMOUS_STATE_TURNING_OFF;

    // KeTing: Make sure this context is get rid of auto mode completely
    // KeTing: Do not remove this or we may commit to wfd while it is busy
    _wfc_wait_until_wfd_not_busy(pContext);

    // KeTing: This is only for MT6253
    // KeTing: Once it is phased out, the following code segement can also be removed
    ((WFD_DEVICE*)(pContext->_engine))->config.enableFastRotatorMem = WFD_FALSE;
    wfdDeviceCommit(pContext->_engine, WFD_COMMIT_ENTIRE_DEVICE, pContext->_engine);
    
    /// Finally, exit the autp mode
    pContext->_autonomousMode = WFC_AUTONOMOUS_STATE_OFF;

Exit:
    return;
}


/**
 *  \status OK
 *  This funtion is used for GDI to do blt or flatten in non-auto mode
 *  Notice: this funtion will not commit cached setting, must use wfcCommit funtion to commit the cached setting
 */
WFC_API_CALL void WFC_APIENTRY
wfcCompose(WFCDevice dev,
           WFCContext ctx,
           WFCboolean wait) WFC_APIEXIT
{
    WFCContextConfig* pContext = NULL;
    WFDDevice pEngine = WFD_INVALID_HANDLE;
    #if defined(DDV2_PERFORMANCE_PROFILING_SUPPORT)
    kal_uint32 wfcComposeStartTimeTick = drv_get_current_time();
    #endif

    // KeTing: This is for GDI's request that always invoke callback function even blt fail...
    // KeTing: Set to TRUE by default, only set to FALSE if blt success
    WFCboolean composeFail = WFC_TRUE;

    wfcTrace(WFCDBG______________________COMPOSE);

    GET_CONTEXT_NR(pContext, ctx);

    pEngine = (WFDDevice) pContext->_engine;

    DDV2CatcherLogL3(TRACE_DDV2_RENDERING, DDV2_TRC_WFCCOMPOSE,
                                     drv_get_current_time(),
                                     (kal_uint32)kal_get_current_thread_ID(),
                                     ctx,
                                     pContext->capturedRWAttrib->roiRect.x,
                                     pContext->capturedRWAttrib->roiRect.y,
                                     pContext->capturedRWAttrib->roiRect.width,
                                     pContext->capturedRWAttrib->roiRect.height, wait);

    // KeTing: Not allow compose while in auto mode.
    if (WFC_TRUE == _wfc_is_engine_in_autonomous_mode(pEngine))
    {
        _wfc_set_error(WFC_ERROR_UNSUPPORTED);
        goto Exit;
    }

    // KeTing: If this is a blocking call, wait until context not busy
    if (WFC_TRUE == wait)
    {
        _wfc_wait_until_wfd_not_busy(pContext);
    }
    else
    {
        // KeTing: If this is not a blocking call and context is busy, set error and return
        if (WFC_TRUE == _wfc_is_wfd_busy(pContext))
        {
            _wfc_set_error(WFC_ERROR_BUSY);
            goto Exit;
        }
    }

    // Bin: clear the frame done event flag and set busy flag
    _wfc_set_context_frame_done_event(pContext, WFC_FALSE);
    pContext->_busy = WFC_TRUE;

#if defined(__MTK_TARGET__) && defined(MT6256)	
	// Xiaoyong: For MT6256 3D MMI 2 Layers BW adjust before trigger LCD Blt, see MAUI_03095322
	{
		WFCuint layer_count=0;
		WFCuint i=0;
		WFDPort pPort = WFD_INVALID_HANDLE;
		pPort = (WFDPort) pContext->_port;
		if (((WFD_PORT*)pPort)->config.type == WFD_PORT_TYPE_INTERNAL)// Only for Blt
		{
			for (i = 0; i<WFC_CONTEXT_MAX_INSERTED_ELEMENT; i++)
			{
				if (WFC_INVALID_HANDLE != pContext->capturedRWAttrib->_insertedElements[i])		 
            	{        		
                	if (i >= ((WFD_DEVICE*)pEngine)->pipelineCount)
                	{
                    	// Error!
                    	continue;
                	}
					if(layer_count++ > 1) 
						break;
				}
			}
			if (layer_count >= 2) //if layer count >1, will switch BW to 3D_2_LCD_Layer
			{
				 EMI_SetScenarioBW(MM_SCE_MMI_3D_2_LCD_LAYER);
			}
			else
			{
				 EMI_SetScenarioBW(MM_SCE_MMI_3D_1_LCD_LAYER);
			}
		}
	}
#endif	
    // KeTing: Configure WFD accordingly and then blt 
    //             If blocking-call, it will not return until the current frame is blt done .
    _wfc_config_wfd_and_commit(pContext, wait);


    if (WFD_ERROR_NONE != wfdGetError(pEngine))
    {
        _wfc_set_error(WFC_ERROR_ILLEGAL_ARGUMENT);
        goto Exit;
    }
    else
    {
        composeFail = WFC_FALSE;
    }

Exit:

    #if defined(DDV2_PERFORMANCE_PROFILING_SUPPORT)
    {
        DDV2CatcherLogL3D1(TRACE_DDV2_PROFILING, LCD_TRC_PROFILING_WFC_COMPOSE_TOTAL_TIME,
                                                 drv_get_duration_tick(wfcComposeStartTimeTick, drv_get_current_time()));
    }
    #endif

    if (WFC_TRUE == composeFail)
    {
        _wfc_invoke_callback(pContext, WFC_CONTEXT_EVENT_COMPOSITION_FINISH_MTK);
    }

    return;
}


/*=========================================================================*/
/* 9. SYNCHRONIZATION                                                      */
/*=========================================================================*/
/**
 *  \status OK
 */
WFC_API_CALL void WFC_APIENTRY
wfcFence(WFCDevice dev,
         WFCContext ctx,
         WFCEGLDisplay dpy,
         WFCEGLSync sync)
{
    _wfc_set_error(WFC_ERROR_UNSUPPORTED);
    return;
}

/*=========================================================================*/
/* 10. EXTENSION SUPPORT                                                   */
/*=========================================================================*/
/**
 *  \status OK
 */
WFC_API_CALL WFCint WFC_APIENTRY
wfcGetStrings(WFCDevice dev,
              WFCStringID name,
              const char **strings,
              WFCint stringsCount) WFC_APIEXIT
{
    _wfc_set_error(WFC_ERROR_UNSUPPORTED);
    return 0;
}

/**
 *  \status OK
 */
WFC_API_CALL WFCboolean WFC_APIENTRY
wfcIsExtensionSupported(WFCDevice dev,
                        const char *string) WFC_APIEXIT
{
    _wfc_set_error(WFC_ERROR_UNSUPPORTED);
    return WFC_FALSE;
}

/*=========================================================================*/
/* 11. TEST ONLY API FOR ON SCREEN IMAGE EXPORTING                         */
/*=========================================================================*/
/**
 *  \status OK
 */
WFC_API_CALL WFCNativeStreamType WFC_APIENTRY
wfcGetOnScreenStream(WFCDevice dev, WFCContext ctx) WFC_APIEXIT
{
    _wfc_set_error(WFC_ERROR_UNSUPPORTED);
    return WFC_INVALID_HANDLE;
}