sp_drv.c 96.1 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
/*****************************************************************************
*  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) 2005
*
*  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:
 * ---------
 * l1sp.c
 *
 * Project:
 * --------
 *   MAUI
 *
 * Description:
 * ------------
 *   L1SP Interface 
 *
 * Author:
 * -------
 * -------
 *
 *==============================================================================
 *             HISTORY
 * Below this line, this part is controlled by PVCS VM. DO NOT MODIFY!!
 *------------------------------------------------------------------------------
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 * removed!
 * removed!
 * removed!
 * removed!
 * removed!
 * removed!
 * removed!
 * removed!
 * removed!
 * removed!
 * removed!
 * removed!
 * removed!
 * removed!
 * removed!
 * removed!
 * removed!
 * removed!
 * removed!
 * removed!
 * removed!
 * removed!
 * removed!
 * removed!
 * removed!
 * removed!
 * removed!
 * removed!
 * removed!
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 *
 *
 * removed!
 * removed!
 * removed!
 * removed!
 *
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 *
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 *
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 *
 * removed!
 * removed!
 *
 * removed!
 * removed!
 *
 * removed!
 * removed!
 *
 * removed!
 * removed!
 *
 * removed!
 * removed!
 *
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 *
 * removed!
 * removed!
 *
 * removed!
 * removed!
 *
 * removed!
 * removed!
 *
 * removed!
 * removed!
 *
 * removed!
 * removed!
 *
 * removed!
 * removed!
 *
 * removed!
 * removed!
 *
 * removed!
 * removed!
 *
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 *
 * removed!
 * removed!
 *
 * removed!
 * removed!
 *
 * removed!
 * removed!
 *
 * removed!
 * removed!
 *
 * removed!
 * removed!
 *
 * removed!
 * removed!
 *
 * removed!
 * removed!
 *
 * removed!
 * removed!
 *
 * removed!
 * removed!
 *
 * removed!
 * removed!
 *
 * removed!
 * removed!
 *
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 *
 * removed!
 * removed!
 *
 * removed!
 * removed!
 *
 * removed!
 * removed!
 *
 * removed!
 * removed!
 *
 * removed!
 * removed!
 *
 * removed!
 * removed!
 *
 * removed!
 * removed!
 *
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 *
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 *------------------------------------------------------------------------------
 * Upper this line, this part is controlled by PVCS VM. DO NOT MODIFY!!
 *==============================================================================
 *******************************************************************************/
#include "kal_public_api.h"
#include "kal_general_types.h"
//#include "kal_non_specific_general_types.h"
//#include "kal_release.h"
#include "kal_trace.h"
#include "string.h"
#include "reg_base.h"
//#include "ps_trace.h"
#include "custom_equipment.h" /* custom_cfg_audio_ec_range() */
#include "device.h" /* MAX_VOL_LEVEL,  in ps\l4\include */
#include "audcoeff_default.h"

#include "audio_def.h"
#include "speech_def.h"
#include "l1audio.h"
#include "l1audio_trace.h"
#include "l1sp_trc.h"
#include "ddload.h"
#include "media.h"
#include "afe.h"
#include "am.h"
#include "speech_enh_def.h"

#if defined(__VM_CODEC_SUPPORT__) 
#include "l1audio_sph_trc.h"   
#endif

#ifdef __TWOMICNR_SUPPORT__
#include "two_mic_NR_custom_if.h"
#endif

#if defined(__CVSD_CODEC_SUPPORT__) 
#include "bt_sco_app.h"
#endif

/* ------------------------------------------------------------------------------ */
/*  Speech Interface                                                              */
/* ------------------------------------------------------------------------------ */

typedef enum{
	L1SP_NVRAM_VALUES_FLAG_MODE = 0x1,
	L1SP_NVRAM_VALUES_FLAG_IN_FIR = 0x2,
	L1SP_NVRAM_VALUES_FLAG_OUT_FIR = 0x4,
	L1SP_NVRAM_VALUES_FLAG_WB_MODE = 0x8,
	L1SP_NVRAM_VALUES_FLAG_WB_IN_FIR = 0x10,
	L1SP_NVRAM_VALUES_FLAG_WB_OUT_FIR = 0x20,
	L1SP_NVRAM_VALUES_FLAG_RECORD_MODE = 0x40,
	L1SP_NVRAM_VALUES_FLAG_RECORD_IN_FIR = 0x80,
	L1SP_NVRAM_VALUES_FLAG_VOLUME_PARAM = 0x100,
}L1SP_INTERNAL_NVRAM_VALUES_FLAG; // for NvramValuesFlag


static struct {
   uint16   aud_id;

   uint8    sph_mode;
   uint8    sph_level;
   uint16   sph_c_para[NUM_COMMON_PARAS];
   uint16   sph_m_para[NUM_MODE_PARAS];
   uint16   sph_v_para[NUM_VOL_PARAS];   
#if defined(__DUAL_MIC_SUPPORT__)
   int16    sph_dmnr_para[NUM_DMNR_PARAM];
#if defined(__AMRWB_LINK_SUPPORT__)
   int16    sph_wb_dmnr_para[NUM_WB_DMNR_PARAM];
#endif
#endif    
   uint8    min_ec_level;
   uint8    max_ec_level;
   uint8    mic_volume; 
   uint8    mic_volume_fromMED; 
   uint8    mic_volume_adapted; 
   uint8    sph_dl_vol;
   uint16   spe_app_mask;    //record the usage every application should have . Ex. phonecall should be turned on DMNR. please do not update the mask directly, please use function l1sp_updateSpeFlag() to update
   uint16   spe_usr_mask;   //record the usage use choose . Ex. phonecall should be turned on DMNR, but users can decide whether turn on or not.please do not update the mask directly, please use function l1sp_updateSpeFlag() to update   
   uint8    spe_state;   
   bool     spe_flag;   
   bool     isULMute;
   bool     tch_state; // true: TCH on; false: TCH off
   bool     pcmplayback_flag; // only used in META taste function.
   bool     speech_dmnr_loopback;     
   bool     isVocOn;
   uint8    state;          
   uint8    output_dev;
   bool     bt_on;
   bool     interRAT;
   void (*onHandler)(void *); 
   void (*offHandler)(void *); 

#if defined(__ECALL_SUPPORT__)
   void (*pcm4wayOnHandler)(void *); 
   void (*pcm4wayOffHandler)(void *);
#endif

   //value from nvram 
   uint16   setNvramValuesFlag; //bit 0 for sph_allModePara, bit 1 for sph_allInFirCoeff, bit 2 for sph_allOutFirCoeff, 
                                //bit 3 for sph_allWbModePara, bit 4 for sph_allWbInFirCoeff, bit 5 for sph_allWbOutFirCoeff
                                //bit 6 for recordModePara, bit 7 for recordInFirCoeff
                                //bit 8 for sph_allVolumePara 
   
   uint16 sph_allModePara[NUM_SPH_MODE][NUM_MODE_PARAS];   
   int16 sph_allInFirCoeff[NUM_SPH_INPUT_FIR][NUM_FIR_COEFFS];
   int16 sph_allOutFirCoeff[NUM_SPH_OUTPUT_FIR][NUM_FIR_COEFFS];
   uint16 sph_allVolumePara[3][7][4];
   uint16 sph_selectedOutFirIndex;
   
#if defined(__AMRWB_LINK_SUPPORT__)
   uint16 sph_allWbModePara[NUM_SPH_MODE][NUM_MODE_PARAS];
   int16 sph_allWbInFirCoeff[NUM_SPH_INPUT_FIR][NUM_WB_FIR_COEFFS];
   int16 sph_allWbOutFirCoeff[NUM_SPH_OUTPUT_FIR][NUM_WB_FIR_COEFFS];
#endif //__AMRWB_LINK_SUPPORT__

#if defined(__HD_RECORD__)
   uint16 recordModePara[NUM_RECORD_SPH_MODE][NUM_MODE_PARAS];
   int16  recordInFirCoeff[NUM_RECORD_INPUT_FIR][NUM_WB_FIR_COEFFS];
   uint16 *recordModeFirMappingCh1;
#if defined(__STEREO_RECORD__)
   uint16 *recordModeFirMappingCh2;
#endif 
   uint8  *recordModeDeviceMapping;
#endif //defined(__HD_RECORD__)

   int16 numOfRecordMode;
   int16 numOfRecordInFir;
   
#if defined(__CVSD_CODEC_SUPPORT__) 
   kal_uint8  cordless_path;
#endif
#if defined(__VOICE_CHANGER_SUPPORT__)
   SPH_VOICE_CHANGER_MODE vchg_mode;
#endif
} l1sp;

static kal_bool lineon_flag = KAL_FALSE; 

#if _SPE_FOR_TEST_SIM_
#include "Sim_common_enums.h"
#if defined(MT6255) || defined(MT6250) || defined(MT6260) || defined(MT6261) || defined(MT2501) || defined(MT2502)
const uint16 m_para_for_test_sim[NUM_MAX_MODE_PARAS] = 
{
       96,       221, 16388,  30,   57351,    31,   400,     0, \
     4112,      229,     3,     0,       0,     0,     0,     8192  \
};
#endif
#endif//#if _SPE_FOR_TEST_SIM_

extern void AFE_SetGainFastRamp(kal_bool enable);
extern void SPE_CustomProcess(kal_bool enable, kal_uint16 sph_mode, SPE_Par_Struct *SPE_PAR, kal_uint8 *next_state);
extern void DTMF_MCU_StopAndWait(void);
#if defined(__CVSD_CODEC_SUPPORT__) 
extern void BT_SCO_SpeechPath_ON(BT_SCO_APP_SPEECH_PATH uPath);
#endif
extern void PcmSink_TerminateSound(void);
extern void AFE_TurnOnLoopback(void);
extern void AFE_TurnOffLoopback(void);

#if defined(__BT_SUPPORT__)
bool L1SP_IsBluetoothOn( void )
{
   return (bool)(l1sp.sph_mode==SPH_MODE_BT_CORDLESS || l1sp.sph_mode==SPH_MODE_BT_EARPHONE || 
      l1sp.sph_mode==SPH_MODE_BT_CARKIT || l1sp.sph_mode==SPH_MODE_LINEIN_VIA_BT_CORDLESS);
}
#endif

void L1SP_UpdateSpeechPara( uint16 sph_m_para[NUM_MAX_MODE_PARAS] )
{
   memcpy(l1sp.sph_m_para, sph_m_para, NUM_MODE_PARAS*sizeof(uint16));
}

#if (defined(__CENTRALIZED_SLEEP_MANAGER__) && (defined(MT6250) || defined(MT6260) || defined(MT6261) || defined(MT2501) || defined(MT2502)))
static kal_uint16 L1SP_GetAudID(void)/*Be careful.Before Locking SleepMode, to access DSP sherrif tasks much time. So access DSP must be after SetFlag*/
{
   kal_uint16 aud_id;
   aud_id = L1Audio_GetAudioID();
   L1Audio_SetFlag( aud_id );
   return aud_id;
}
static void L1SP_FreeAudID(kal_uint16 aud_id)
{
   L1Audio_ClearFlag( aud_id );
   L1Audio_FreeAudioID( aud_id );
}
#endif

/*******************************************************************/
/*   The new interface for DSP speech enhancement function / Bluetooth */
/*******************************************************************/
uint8 spe_table[SPH_MODE_UNDEFINED] = {
#if defined(__HQA_AUDIO__) && !(__HQA_AUDIO_AEC_NR_DRC__)
    //----------------------------------SPH_MODE_NORMAL----------------------------------------------//
    0,
    //----------------------------------SPH_MODE_EARPHONE--------------------------------------------//
    0,
    //----------------------------------SPH_MODE_LOUDSPK---------------------------------------------//
    0,
    //----------------------------------SPH_MODE_BT_EARPHONE-----------------------------------------//
    0,
    //----------------------------------SPH_MODE_BT_CORDLESS-----------------------------------------//
    0,
    //----------------------------------SPH_MODE_BT_CARKIT-------------------------------------------//
    0,
    //----------------------------------SPH_MODE_AUX1------------------------------------------------//
    0,
    //----------------------------------SPH_MODE_AUX2------------------------------------------------//
    // Used for megaphone
    0,
    //----------------------------------SPH_MODE_LINEIN_VIA_BT_CORDLESS------------------------------//
    0
#elif defined(MT6255) || defined(MT6250) || defined(MT6260) || defined(MT6261) || defined(MT2501) || defined(MT2502)
    //----------------------------------SPH_MODE_NORMAL----------------------------------------------//
    0
#if defined(AEC_ENABLE)
    + SPE_AEC_FLAG
#if defined(__DUAL_MIC_SUPPORT__)
    + SPE_DMNR_FLAG
#endif  // #if defined(__DUAL_MIC_SUPPORT__)
#endif  // #if defined(AEC_ENABLE)
#if TDDNC_SUPPORT
    + SPE_TDDNC_FLAG
#endif
    + SPE_UL_NR_FLAG + SPE_DL_NR_FLAG + SPE_AGC_FLAG,
    //----------------------------------SPH_MODE_EARPHONE--------------------------------------------//
    0
#if defined(AEC_ENABLE)
    + SPE_AEC_FLAG
#endif
#if TDDNC_SUPPORT
    + SPE_TDDNC_FLAG
#endif
    + SPE_UL_NR_FLAG + SPE_DL_NR_FLAG + SPE_AGC_FLAG,
    //----------------------------------SPH_MODE_LOUDSPK---------------------------------------------//
    0
#if defined(AEC_ENABLE)
    + SPE_AEC_FLAG
#endif
#if TDDNC_SUPPORT
    + SPE_TDDNC_FLAG
#endif
    + SPE_UL_NR_FLAG + SPE_DL_NR_FLAG + SPE_AGC_FLAG,
    //----------------------------------SPH_MODE_BT_EARPHONE-----------------------------------------//
    0
#if defined(AEC_ENABLE) && defined(__BT_SUPPORT__)
    + SPE_AEC_FLAG
#endif
#if TDDNC_SUPPORT
    + SPE_TDDNC_FLAG
#endif
    + SPE_UL_NR_FLAG + SPE_DL_NR_FLAG + SPE_AGC_FLAG,
    //----------------------------------SPH_MODE_BT_CORDLESS-----------------------------------------//
    0
#if defined(BT_DIALER_SPE_FOR_LOUDSPEAKER) || defined(BT_DIALER_SPE_FOR_RECEIVER)
#if defined(AEC_ENABLE)
    + SPE_AEC_FLAG
#endif
    + SPE_UL_NR_FLAG + SPE_DL_NR_FLAG
#endif  // #if defined(BT_DIALER_SPE_FOR_LOUDSPEAKER) || defined(BT_DIALER_SPE_FOR_RECEIVER)
    ,
    //----------------------------------SPH_MODE_BT_CARKIT-------------------------------------------//
    0
#if defined(AEC_ENABLE)
    + SPE_AEC_FLAG
#endif
#if TDDNC_SUPPORT
    + SPE_TDDNC_FLAG
#endif
    + SPE_UL_NR_FLAG + SPE_DL_NR_FLAG + SPE_AGC_FLAG,
    //----------------------------------SPH_MODE_AUX1------------------------------------------------//
    0,
    //----------------------------------SPH_MODE_AUX2------------------------------------------------//
    // Used for megaphone
    0
#if defined(AEC_ENABLE)
    + SPE_AEC_FLAG
#endif
#if TDDNC_SUPPORT
    + SPE_TDDNC_FLAG
#endif
    + SPE_UL_NR_FLAG + SPE_DL_NR_FLAG + SPE_AGC_FLAG,
    //----------------------------------SPH_MODE_LINEIN_VIA_BT_CORDLESS------------------------------//
    0
#endif
};   

#if __RELOAD_DSP_COEFF__

void L1SP_Reload_DMNR_Para(void)
{
#if defined(__DUAL_MIC_SUPPORT__)

	SPE_LoadDmnrCoeffs(l1sp.sph_dmnr_para);
	
#if defined(__AMRWB_LINK_SUPPORT__)
	SPE_LoadWbDmnrCoeffs(l1sp.sph_wb_dmnr_para);
#endif //__AMRWB_LINK_SUPPORT__

#endif //__DUAL_MIC_SUPPORT__
}

void L1SP_Reload_SPE_Para( void )
{
   SPE_LoadSpeechPara(l1sp.sph_c_para, l1sp.sph_m_para, l1sp.sph_v_para);
}
#endif

void L1SP_Init_PCMPlayback(uint8 sph_mode, bool bDigitalGain, uint16 digital_gain)
{
	 unsigned short Speech_Normal_Mode_Para[16] = DEFAULT_SPEECH_NORMAL_MODE_PARA;
   unsigned short Speech_Earphone_Mode_Para[16] = DEFAULT_SPEECH_EARPHONE_MODE_PARA;
   unsigned short Speech_Loudspeaker_Mode_Para[16] = DEFAULT_SPEECH_LOUDSPK_MODE_PARA;
	 
	 switch(sph_mode) {
	 case SPH_MODE_NORMAL:
	     if(bDigitalGain == true) {
	        Speech_Normal_Mode_Para[7] = digital_gain;
	     }
	 	  L1SP_SetSpeechMode(SPH_MODE_NORMAL, Speech_Normal_Mode_Para);
	 		break;
	 case SPH_MODE_EARPHONE:
	     if(bDigitalGain == true) {
	        Speech_Earphone_Mode_Para[7] = digital_gain;
	     }
	 	  L1SP_SetSpeechMode(SPH_MODE_EARPHONE, Speech_Earphone_Mode_Para);
	 	  break;
	 case SPH_MODE_LOUDSPK: 
	     if(bDigitalGain == true) {
	        Speech_Loudspeaker_Mode_Para[7] = digital_gain;
	     }
	 	  L1SP_SetSpeechMode(SPH_MODE_LOUDSPK, Speech_Loudspeaker_Mode_Para);
	 	  break;
	 default:
	 	  break;
	 } 
}

void L1SP_EnableStrmPcmSPE(void)
{
	 l1sp.pcmplayback_flag = true;
}

void L1SP_DisableStrmPcmSPE(void)
{
	 l1sp.pcmplayback_flag = false;
}

bool L1SP_CheckStrmPcmSPE(void)
{
	 return l1sp.pcmplayback_flag;
}

void l1sp_updateSpeAppMask(uint16 updateFlags, bool enable)
{
	if(enable)
		l1sp.spe_app_mask |= (updateFlags);
	else
		l1sp.spe_app_mask &= ~(updateFlags);

	kal_trace( TRACE_INFO, L1SP_UPDATE_SPE_APP_MASK, l1sp.spe_app_mask, l1sp.spe_usr_mask, updateFlags, enable);
	
}

void l1sp_updateSpeUsrMask(uint16 updateFlags, bool enable)
{
	if(enable)
		l1sp.spe_usr_mask |= (updateFlags);
	else
		l1sp.spe_usr_mask &= ~(updateFlags);

	kal_trace( TRACE_INFO, L1SP_UPDATE_SPE_USR_MASK, l1sp.spe_app_mask, l1sp.spe_usr_mask, updateFlags, enable);	
}

void SetSpeechEnhancement( bool ec )
{
#if defined(CHIP_BACK_SPH_PHONE_CALL)
    // no speech enhancement at chip back phone call
    return;
#endif
    if (((!AM_IsAmInSpeechState() || !l1sp.spe_flag) && !l1sp.pcmplayback_flag)
        || Media_IsKaraoke())
    {
        return;
    }
    
    ASSERT(l1sp.sph_mode<SPH_MODE_UNDEFINED);
    
    kal_trace( TRACE_INFO, L1SP_APPLY_MODE, (ec) ? 1 : 0, l1sp.sph_mode, l1sp.sph_level, l1sp.mic_volume);
    
    if (ec)
    {
        uint8 next_state, keep_on_state, on_state, off_state;
        uint8 i;
        
        next_state = spe_table[l1sp.sph_mode];
        if (l1sp.bt_on)
        {   // For BT PLC
            l1sp_updateSpeAppMask(SPH_ENH_MASK_AGC, false);
        }
        
        {
            SPE_Par_Struct spe_par;
            spe_par.mode_par   = l1sp.sph_m_para;
            spe_par.common_par = l1sp.sph_c_para;
            AM_GetFirCoeffs(&spe_par.in_fir, &spe_par.out_fir);
            SPE_CustomProcess(KAL_TRUE,0,0,0);	
        }
        
        // Use "l1sp.spe_app_mask" to control the open / close of speech enhancment
        for (i = 0; i < NUM_OF_SPH_FLAG; i++)
        {
            uint8 tempMaskBit = (1<<i);
            if (((l1sp.spe_app_mask & tempMaskBit) == 0 || (l1sp.spe_usr_mask & tempMaskBit) == 0)
	            && (next_state & tempMaskBit))
            {
                next_state -= tempMaskBit;
            }
        }
        
        keep_on_state = next_state & l1sp.spe_state; 
        on_state = next_state - keep_on_state;
        off_state = l1sp.spe_state - keep_on_state;
        
        kal_trace( TRACE_INFO, L1SP_SET_ENHANCEMENT, keep_on_state, on_state, off_state);
        
        if (off_state)
        {
            SPE_TurnOffProcess(off_state);
        }
        
        if (next_state)
        {
            kal_trace(TRACE_INFO, L1SP_SPEECH_ENHANCEMENT, next_state, l1sp.sph_m_para[0], l1sp.sph_m_para[1], l1sp.sph_c_para[0], l1sp.sph_c_para[1]);
            
            if (next_state & (SPE_AEC_FLAG + SPE_UL_NR_FLAG + SPE_DL_NR_FLAG))
            {
                SPE_LoadSpeechPara(l1sp.sph_c_para, l1sp.sph_m_para, l1sp.sph_v_para);
            }
            
#if defined(__DUAL_MIC_SUPPORT__)
            if (next_state & SPE_DMNR_FLAG)
            {
                SPE_LoadDmnrCoeffs(l1sp.sph_dmnr_para);
#if defined(__AMRWB_LINK_SUPPORT__)
                SPE_LoadWbDmnrCoeffs(l1sp.sph_wb_dmnr_para);
#endif //__AMRWB_LINK_SUPPORT__
            }
#endif //__DUAL_MIC_SUPPORT__
            
            if (on_state)
            {
                SPE_TurnOnProcess(on_state);
            }
        }
        
        l1sp.spe_state = next_state;
        SPE_Clear_DLL_Entry(l1sp.spe_state);
    }
    else
    {
        if (l1sp.spe_state)
        {
            SPE_TurnOffProcess(l1sp.spe_state);
            l1sp.spe_state = 0;
            SPE_Clear_DLL_Entry(0);
        }
        
        SPE_CustomProcess(KAL_FALSE,0,0,0);
    }
    
    if (l1sp.spe_app_mask & SPH_ENH_MASK_SIDETONE)
    {
#if defined(AEC_ENABLE)
        if (l1sp.sph_mode == SPH_MODE_LOUDSPK)
#else
        if (l1sp.sph_mode == SPH_MODE_LOUDSPK || (l1sp.sph_mode == SPH_MODE_NORMAL && l1sp.sph_level == MAX_VOL_LEVEL - 1))
#endif
        {
            AFE_SetSidetone(false); // If AEC is turned off or the big volume of DL, it will cause sidetone to generate the howling effect
        }
        else
        {
            AFE_SetSidetone(true);
        }
    }
    
    return;
}

void L1SP_LoadCommonSpeechPara( uint16 c_para[NUM_MAX_COMMON_PARAS] )
{
#if (defined(__CENTRALIZED_SLEEP_MANAGER__) && (defined(MT6250) || defined(MT6260) || defined(MT6261) || defined(MT2501) || defined(MT2502)))
   kal_uint16 aud_id = L1SP_GetAudID();
#endif    
   memcpy(l1sp.sph_c_para, c_para, NUM_COMMON_PARAS*sizeof(uint16));
   SetSpeechEnhancement( true );
   
   // Some common parameters are used in non-speech function
   // Force to load common parameter
   SPE_LoadSpeechPara(l1sp.sph_c_para, NULL, NULL);

#if (defined(__CENTRALIZED_SLEEP_MANAGER__) && (defined(MT6250) || defined(MT6260) || defined(MT6261) || defined(MT2501) || defined(MT2502)))
   L1SP_FreeAudID(aud_id);
#endif
}

#if defined(__DUAL_MIC_SUPPORT__)

/**
@deprecated
*/
void L1SP_SetABFPara( kal_int16 DMNR_para[NUM_DMNR_PARAM] )
{
   L1SP_SetDMNRPara(DMNR_para);
}

void L1SP_SetDMNRPara( kal_int16 DMNR_para[NUM_DMNR_PARAM] )
{
	
	memcpy(&l1sp.sph_dmnr_para, DMNR_para, NUM_DMNR_PARAM*sizeof(uint16));
	SPE_LoadDmnrCoeffs(l1sp.sph_dmnr_para);
}

#if defined(__AMRWB_LINK_SUPPORT__)
void L1SP_SetWbDMNRPara( kal_int16 WB_DMNR_para[NUM_WB_DMNR_PARAM] )
{
	memcpy(&l1sp.sph_wb_dmnr_para, WB_DMNR_para, NUM_WB_DMNR_PARAM*sizeof(uint16));
	SPE_LoadWbDmnrCoeffs(l1sp.sph_wb_dmnr_para);
}

#endif //__AMRWB_LINK_SUPPORT__


#endif //__DUAL_MIC_SUPPORT__

void L1SP_SetDualMicNR( kal_bool enable )
{
	kal_trace( TRACE_INFO, L1SP_ENABLE_DUAL_MIC_NR, enable );
	
#if defined(__DUAL_MIC_SUPPORT__)
   /*
   if(enable)
      l1sp.spe_app_mask |= (SPH_ENH_MASK_DMNR);
   else
      l1sp.spe_app_mask &= ~(SPH_ENH_MASK_DMNR);
      */
   l1sp_updateSpeUsrMask(SPH_ENH_MASK_DMNR, enable);
   if(l1sp.spe_state) { // already turn on speech enhancement 
      SetSpeechEnhancement(KAL_TRUE);
   }

#endif //__DUAL_MIC_SUPPORT__

}

kal_uint8 L1SP_GetSpeechMode( void )
{
    return l1sp.sph_mode;
}

#if defined(__CVSD_CODEC_SUPPORT__) 
static void setBt(uint32 scene, uint32 preScene)
{
   kal_brief_trace( TRACE_GROUP_SCO, L1AUDIO_BTSCO_SET_BT, scene, preScene, l1sp.bt_on);
   ASSERT(scene != SPH_MODE_LINEIN_VIA_BT_CORDLESS); //not available from MT6250 & MT6260
   BT_SCO_Disable_All_APP();
   
   if(l1sp.bt_on || scene == SPH_MODE_BT_CORDLESS || scene == SPH_MODE_BT_EARPHONE || scene == SPH_MODE_BT_CARKIT)
   {
      DTMF_MCU_StopAndWait();
      KT_StopAndWait();
      TONE_StopAndWait();
   }

   if(l1sp.bt_on)
   {
      if(AM_IsBTCordlessMode() || AM_IsBluetoothOn())
      {
         if( preScene == SPH_MODE_BT_CORDLESS) 
         {
            AM_BTCordlessOff();
         } 
         AM_BluetoothOff();
      }
      l1sp.bt_on = false;
   }

   if( scene == SPH_MODE_BT_CORDLESS || scene == SPH_MODE_BT_EARPHONE || scene == SPH_MODE_BT_CARKIT )
   {
      if(l1sp.cordless_path == SPH_CORDLESS_PATH_BT)
      {
         if( scene == SPH_MODE_BT_CORDLESS) 
         {
            extern void BT_SCO_Cordless_ON(kal_uint32 uSampleRate, kal_uint32 uChannelNumber);
            BT_SCO_Cordless_ON(8000, 1);
         }
         else if(AM_IsAudioPlaybackOn() != -1)
         {
#if defined ( __BT_AUDIO_VIA_SCO__ )          	
            extern void BT_SCO_AudioPath_ON(void);
            BT_SCO_AudioPath_ON();
#endif            
         }
         else if(L1SP_IsSpeechOn())
         {
            BT_SCO_SpeechPath_ON(BT_SCO_APP_SPEECH_PATH_BOTH);
         }
         else if(AM_IsToneOn()|| AM_IsKeyToneOn())
         {
            BT_SCO_SpeechPath_ON(BT_SCO_APP_SPEECH_PATH_BTUL);
         }
         else if(AM_IsConflictState())
         {
            BT_SCO_SpeechPath_ON(BT_SCO_APP_SPEECH_PATH_BTDL);
         }
      }
      else //SPH_CORDLESS_PATH_PCM
      {
         if( scene == SPH_MODE_BT_CORDLESS) 
         {
            AM_BluetoothOn(1);
            AM_BTCordlessOn();
         }
         else if(scene==SPH_MODE_BT_EARPHONE || scene==SPH_MODE_BT_CARKIT)
         {
            AM_BluetoothOn(2);
         }
      }
      l1sp.bt_on = true;
   } 
}
#else
static void setBt(uint32 scene, uint32 preScene)
{
#if defined(__BT_SUPPORT__)   
	   // Turn off the BT related function
	   if( preScene == SPH_MODE_BT_CORDLESS ) {
		  AM_BTCordlessOff();
	   }
	//#if defined(__BT_FM_VIA_SCO__)
	   if( preScene == SPH_MODE_LINEIN_VIA_BT_CORDLESS ){
		  AM_PCM8K_RecordOff( true );
	   }
	//#endif
	
	   if((l1sp.bt_on) && (preScene != scene))
		  {
			 AM_BluetoothOff();
			 l1sp.bt_on = false;
		  }
	
	   if( scene == SPH_MODE_BT_CORDLESS || scene == SPH_MODE_BT_EARPHONE || 
		  scene == SPH_MODE_BT_CARKIT || scene == SPH_MODE_LINEIN_VIA_BT_CORDLESS )
	   {
		  if ((scene==SPH_MODE_BT_CORDLESS || scene==SPH_MODE_LINEIN_VIA_BT_CORDLESS)) 
		  {
			 KT_StopAndWait();
			 TONE_StopAndWait();
			 DTMF_MCU_StopAndWait();
			 if (!l1sp.bt_on)
			 {
				AM_BluetoothOn(1);
			 }	 
		  } else {
			 if (!l1sp.bt_on)
			 {
				AM_BluetoothOn(2);
			 }
		  }
		  
		  l1sp.bt_on = true;
		  
		  if (scene == SPH_MODE_BT_CORDLESS) {
			 AM_BTCordlessOn();
		  }
	//#if defined(__BT_FM_VIA_SCO__)
		  if( scene == SPH_MODE_LINEIN_VIA_BT_CORDLESS ){
			 AM_PCM8K_RecordOn(); //Just for turn on related AFE mic, and set am.state to avoid others application execution
		  }
	//#endif
	   } 
#endif 
}
#endif

static void changeSpeechMode(uint8 prev_sph_mode, uint8 after_sph_mode, 
	uint16 m_paras[NUM_MAX_MODE_PARAS])
{
   kal_trace( TRACE_INFO, L1SP_CHANGE_ENH_MODE, prev_sph_mode, after_sph_mode, l1sp.sph_mode );
	
   if( prev_sph_mode != after_sph_mode ) { // Allow quick adaptation when change mode		
      SetSpeechEnhancement( false );		
   }
   #ifdef __GAIN_TABLE_SUPPORT__
   else{
      kal_uint16 spe_idx = 0;
      for(spe_idx = 0; spe_idx < NUM_MAX_MODE_PARAS; spe_idx++){
         if(m_paras[spe_idx] != l1sp.sph_m_para[spe_idx]){
            SetSpeechEnhancement( false );
            break;
         }
      }
   }
	#endif /* __GAIN_TABLE_SUPPORT__ */
	
   l1sp.sph_mode = after_sph_mode;

   memcpy(l1sp.sph_m_para, m_paras, NUM_MODE_PARAS*sizeof(uint16));
   kal_trace( TRACE_INFO, L1SP_SET_MODE, l1sp.sph_mode, l1sp.sph_level, l1sp.mic_volume );

   SetSpeechEnhancement( true );
}

void L1SP_SetSpeechMode(uint8 mode, uint16 m_para[NUM_MAX_MODE_PARAS])
{
    uint8 prev_sph_mode = l1sp.sph_mode;
#if (defined(__CENTRALIZED_SLEEP_MANAGER__) && (defined(MT6250) || defined(MT6260) || defined(MT6261) || defined(MT2501) || defined(MT2502)))
    kal_uint16 aud_id = L1SP_GetAudID();
#endif   
#if 0 //defined(CHIP_BACK_SPH_PHONE_CALL)
/* under construction !*/
#endif
#if defined(__ENABLE_AUDIO_DVT__)
    {
        extern kal_bool Always_SetBTmode;
        if (Always_SetBTmode)
        {
            mode = SPH_MODE_BT_EARPHONE;
        }
    }
#endif
#ifdef DSDA_VIA_PCM_INTERFACE
    mode = SPH_MODE_BT_EARPHONE;
#endif
    
    setBt(mode, prev_sph_mode);
    changeSpeechMode(l1sp.sph_mode, mode, m_para);   
    
    // Set SRC control
    if (prev_sph_mode != mode)
    {
#if defined(__BT_SUPPORT__) && !defined(__CVSD_CODEC_SUPPORT__)  
        if (AM_IsBTCordlessMode() || AM_IsSpeechOn())
#else
        if (AM_IsSpeechOn())
#endif
		{
            AM_SetSRCCtrl();
		}
	}
    
#if (defined(__CENTRALIZED_SLEEP_MANAGER__) && (defined(MT6250) || defined(MT6260) || defined(MT6261) || defined(MT2501) || defined(MT2502)))
    L1SP_FreeAudID(aud_id);
#endif
    
    return;
}

static void l1sp_getFirMappingByScene(const uint32 scene, 
	uint8 *devMode, uint8 *enhMode,
	uint8 *inFir, uint8 *outFir)
{
	uint8 tempDevMode = 0xff; 
	uint8 tempEnhMode = 0xff;
	uint8 tempInFir = 0xff; 
	uint8 tempOutFir = 0xff;
	
	switch(scene) {
	case SPH_ENH_AND_FIR_SCENE_NORMAL:
		tempDevMode = SPH_MODE_NORMAL;
		tempEnhMode = SPH_MODE_NORMAL;
		tempInFir = SPH_FIR_COEFF_NORMAL;
#if defined(__SMART_PHONE_MODEM__)
		tempOutFir = SPH_FIR_COEFF_NORMAL;
#else		
		tempOutFir = l1sp.sph_selectedOutFirIndex; //using enginerning mode's setting for the FIR index
#endif		
		break;
	case SPH_ENH_AND_FIR_SCENE_EARPHONE:
	case SPH_ENH_AND_FIR_SCENE_LOUDSPK:
		tempDevMode = scene;
		tempEnhMode = scene;
		tempInFir = scene;
		tempOutFir = scene;
		break;	
#if defined(__BT_SUPPORT__)		
	case SPH_ENH_AND_FIR_SCENE_BT_EARPHONE:
	case SPH_ENH_AND_FIR_SCENE_BT_CORDLESS:
	case SPH_ENH_AND_FIR_SCENE_BT_CARKIT:
		tempDevMode = scene;
		tempEnhMode = scene;
		tempInFir = SPH_FIR_COEFF_BT; 
		tempOutFir = SPH_FIR_COEFF_BT;
		break;
#endif
	case SPH_ENH_AND_FIR_SCENE_AUX1:
		tempDevMode = SPH_MODE_AUX1; //scene
		tempEnhMode = SPH_MODE_AUX1; //scene
		tempInFir = SPH_FIR_COEFF_VOIP_NORMAL;
		tempOutFir = SPH_FIR_COEFF_VOIP_NORMAL;
		break;
	case SPH_ENH_AND_FIR_SCENE_AUX2:
		tempDevMode = SPH_MODE_AUX2;
		tempEnhMode = SPH_MODE_AUX2;
		tempInFir = SPH_FIR_COEFF_VOIP_HANDFREE;
		tempOutFir = SPH_FIR_COEFF_VOIP_HANDFREE;
		break;
	case SPH_ENH_AND_FIR_SCENE_LINEIN_VIA_BT_CORDLESS:
		tempDevMode =  SPH_MODE_LINEIN_VIA_BT_CORDLESS;
		tempEnhMode =  SPH_MODE_LINEIN_VIA_BT_CORDLESS;
		tempInFir = SPH_FIR_COEFF_BT; 
		tempOutFir = SPH_FIR_COEFF_BT;
		break;

	//VOIP related
	case SPH_ENH_AND_FIR_SCENE_VOIP_NORMAL:
		tempDevMode = SPH_MODE_AUX1;
		tempEnhMode = SPH_MODE_AUX1;
		tempInFir = SPH_FIR_COEFF_VOIP_NORMAL;
		tempOutFir = SPH_FIR_COEFF_VOIP_NORMAL;
		break;
	case SPH_ENH_AND_FIR_SCENE_VOIP_LOADSPK:
		tempDevMode = SPH_MODE_AUX2;
		tempEnhMode = SPH_MODE_AUX2;
		tempInFir = SPH_FIR_COEFF_VOIP_HANDFREE;
		tempOutFir = SPH_FIR_COEFF_VOIP_HANDFREE;
		break;
		
	//CTM related
	case SPH_ENH_AND_FIR_SCENE_CTM_BAUDOT:		
	case SPH_ENH_AND_FIR_SCENE_CTM_DIRECT:
		tempDevMode = l1sp.sph_mode; 
		tempEnhMode = l1sp.sph_mode;
		//use default	
		break;

	//CTM HCO
	case SPH_ENH_AND_FIR_SCENE_CTM_HCO_NORMAL: // using Eng Mode's selected_FIR_output_index to decide which is 		
	    tempDevMode = SPH_MODE_NORMAL;
		tempEnhMode = SPH_MODE_NORMAL;
#if defined(__SMART_PHONE_MODEM__)
		tempOutFir = SPH_FIR_COEFF_NORMAL;
#else		
		tempOutFir = l1sp.sph_selectedOutFirIndex;
#endif
		break;
	case SPH_ENH_AND_FIR_SCENE_CTM_HCO_EARPHONE:
	    tempDevMode = SPH_MODE_EARPHONE;
		tempEnhMode = SPH_MODE_EARPHONE;
		tempOutFir = SPH_FIR_COEFF_HEADSET;		
		break;
	case SPH_ENH_AND_FIR_SCENE_CTM_HCO_LOUDSPK:
	    tempDevMode = SPH_MODE_LOUDSPK;
		tempEnhMode = SPH_MODE_LOUDSPK;
		tempOutFir = SPH_FIR_COEFF_HANDFREE;
		break;
	case SPH_ENH_AND_FIR_SCENE_CTM_HCO_BT:
	    tempDevMode = SPH_MODE_BT_EARPHONE;
		tempEnhMode = SPH_MODE_BT_EARPHONE;
		tempOutFir = SPH_FIR_COEFF_BT;
		break;
	case SPH_ENH_AND_FIR_SCENE_CTM_HCO_VOIP_NORMAL:
	    tempDevMode = SPH_MODE_AUX1;
		tempEnhMode = SPH_MODE_AUX1;
		tempOutFir = SPH_FIR_COEFF_VOIP_NORMAL;
		break;
	case SPH_ENH_AND_FIR_SCENE_CTM_HCO_VOIP_LOUDSPK:
	    tempDevMode = SPH_MODE_AUX2;
		tempEnhMode = SPH_MODE_AUX2;
		tempOutFir = SPH_FIR_COEFF_VOIP_HANDFREE;
		break;

	//CTM VCO
	case SPH_ENH_AND_FIR_SCENE_CTM_VCO_NORMAL:
	    tempDevMode = SPH_MODE_NORMAL;
		tempEnhMode = SPH_MODE_NORMAL;
		tempInFir = SPH_FIR_COEFF_NORMAL;
		break;
	case SPH_ENH_AND_FIR_SCENE_CTM_VCO_EARPHONE:
	    tempDevMode = SPH_MODE_EARPHONE;
		tempEnhMode = SPH_MODE_EARPHONE;
		tempInFir = SPH_FIR_COEFF_HEADSET;	
		break;
	case SPH_ENH_AND_FIR_SCENE_CTM_VCO_LOUDSPK:
	    tempDevMode = SPH_MODE_LOUDSPK;
		tempEnhMode = SPH_MODE_LOUDSPK;
		tempInFir = SPH_FIR_COEFF_HANDFREE;
		break;
	case SPH_ENH_AND_FIR_SCENE_CTM_VCO_BT:
	    tempDevMode = SPH_MODE_BT_EARPHONE;
		tempEnhMode = SPH_MODE_BT_EARPHONE;
		tempInFir = SPH_FIR_COEFF_BT;
		break;
	case SPH_ENH_AND_FIR_SCENE_CTM_VCO_VOIP_NORMAL:
	    tempDevMode = SPH_MODE_AUX1;
		tempEnhMode = SPH_MODE_AUX1;
		tempInFir = SPH_FIR_COEFF_VOIP_NORMAL;
		break;
	case SPH_ENH_AND_FIR_SCENE_CTM_VCO_VOIP_LOUDSPK:
	    tempDevMode = SPH_MODE_AUX2;
		tempEnhMode = SPH_MODE_AUX2;
		tempInFir = SPH_FIR_COEFF_VOIP_HANDFREE;
		break;
		
	default:
#if defined(__HD_RECORD__) && (!defined(__SMART_PHONE_MODEM__)) //Only for feature phone use
				if(scene>SPH_ENH_AND_FIR_SCENE_CTM_VCO_VOIP_LOUDSPK && l1sp.numOfRecordMode>0){ 				
					tempEnhMode = (scene-SPH_ENH_AND_FIR_SCENE_INCALL_END)-1; 
					tempDevMode = l1sp.recordModeDeviceMapping[tempEnhMode];
					tempInFir = l1sp.recordModeFirMappingCh1[tempEnhMode];
#if defined(__STEREO_RECORD__)
					tempOutFir = l1sp.recordModeFirMappingCh2[tempEnhMode];
#endif
				} else 
		
#endif //defined(__HD_RECORD__) && (!defined(__SMART_PHONE_MODEM__))
		{
			ASSERT(0);
		}

	}
	
	*devMode = tempDevMode;
	*enhMode = tempEnhMode;
	*inFir = tempInFir;
	*outFir = tempOutFir;
	
}

/**
	new interface to replace L1SP_SetSpeechMode(), L1SP_Write_Audio_Coefficients(), 
	L1SP_Write_WB_Audio_Coefficients() in the same time. 

	if you want to use personal configuration, you can use original interfaces. 

	@scene: [Input] scenario for different enhancement and fir combination. 
*/
void L1SP_SetSpeechEnhanceAndFir(uint32 scene, uint32 updatedCoeff)

{
	uint8 modeIndex = 0;
	uint8 inFirIndex = 0;
	uint8 outFirIndex = 0;
	uint8 devModeIndex = 0; 

	bool isNeedSpeMaskUpdate = (bool)(!AM_IsAmInSpeechState());
	//speech mode
//----------------- original scenario ---------------
#ifdef __SMART_PHONE_MODEM__
	if(scene <SPH_MODE_UNDEFINED)
#else //feature phone
	if(scene <SPH_ENH_AND_FIR_SCENE_INCALL_END)
#endif //__SMART_PHONE_MODEM__
	{ //keeping the original scenario

		l1sp_getFirMappingByScene(scene, &devModeIndex, &modeIndex, 
			&inFirIndex, &outFirIndex);

		//speech mode
#ifdef WB_SPE_SUPPORT 
		if((updatedCoeff == 0) || (updatedCoeff&SPH_ENH_AND_FIR_UPDATE_TYPE_WB_ENH_MODE)!=0){
			if(l1sp.setNvramValuesFlag & L1SP_NVRAM_VALUES_FLAG_WB_MODE)//(l1sp.has_all_wb_sph_m_para)
				L1SP_SetWbSpeechPara(l1sp.sph_allWbModePara[modeIndex]);
		}
#endif 		
		if((updatedCoeff == 0) || (updatedCoeff&SPH_ENH_AND_FIR_UPDATE_TYPE_NB_ENH_MODE)!=0)
			L1SP_SetSpeechMode(devModeIndex, l1sp.sph_allModePara[modeIndex]);

		// Write NB FIR
		if((updatedCoeff == 0) || (updatedCoeff&SPH_ENH_AND_FIR_UPDATE_TYPE_NB_FIR)!=0)
			L1SP_Write_Audio_Coefficients_ByFirIndex(inFirIndex, outFirIndex); 
		//L1SP_Write_Audio_Coefficients(l1sp.sph_allInFirCoeff[inFirIndex], l1sp.sph_allOutFirCoeff[outFirIndex]);

#ifdef WB_SPE_SUPPORT 
		if((updatedCoeff == 0) || (updatedCoeff&SPH_ENH_AND_FIR_UPDATE_TYPE_WB_FIR)!=0){
			if((l1sp.setNvramValuesFlag & L1SP_NVRAM_VALUES_FLAG_WB_IN_FIR)
				&& (l1sp.setNvramValuesFlag & L1SP_NVRAM_VALUES_FLAG_WB_OUT_FIR)) {
				//(l1sp.has_all_wb_sph_in_FIR_coeffs && l1sp.has_all_wb_sph_out_FIR_coeffs) {
				L1SP_Write_WB_Audio_Coefficients(l1sp.sph_allWbInFirCoeff[inFirIndex],
					l1sp.sph_allWbOutFirCoeff[outFirIndex]);
			}
		}
#endif	
	}

//----------------- recording scenario ---------------
#if defined(__SMART_PHONE_MODEM__) || defined(__HD_RECORD__)
	
#if defined(__SMART_PHONE_MODEM__) //smart phone
	else if (scene>=SPH_MODE_UNDEFINED && scene<= (SPH_MODE_UNDEFINED + l1sp.numOfRecordMode))
#elif defined(__HD_RECORD__) //feature phone
	else if (scene>SPH_ENH_AND_FIR_SCENE_INCALL_END && scene < (SPH_ENH_AND_FIR_SCENE_INCALL_END + l1sp.numOfRecordMode))
#endif
	{

		uint16 emDebugInfo = L1Audio_GetDebugInfo(AMR_REC_DEBUG_INFO);

		//only open uplink nr when recording. (AGC should be on)
		/*
		if(isNeedSpeMaskUpdate) {
			l1sp_updateSpeAppMask(0xff, false);
			l1sp_updateSpeAppMask(SPH_ENH_MASK_ULNR, true);
		}
		*/

		//get the mode params		
#if defined(__SMART_PHONE_MODEM__)
		modeIndex = scene - SPH_MODE_UNDEFINED;
		devModeIndex = l1sp.recordModeDeviceMapping[modeIndex]; 
		
		outFirIndex = SPH_FIR_COEFF_NORMAL; //useless in this scenario, just keep safe
		if(l1sp.recordModeFirMappingCh1 == NULL) {
			inFirIndex = SPH_FIR_COEFF_NORMAL;
			//FIXME: should add log
		} else {			
			inFirIndex = l1sp.recordModeFirMapping[modeIndex];
#if defined(__STEREO_RECORD__) || defined(__SMART_PHONE_MODEM__) 
			outFirIndex = l1sp.recordModeFirMappingCh2[modeIndex];
#endif

		}
#else //only for feature phone usage
		l1sp_getFirMappingByScene(scene, &devModeIndex, &modeIndex, 
			&inFirIndex, &outFirIndex);
#endif

		//speech enhancment mode & device mode setting
		if(emDebugInfo&0x1) { //when debug info parameter2 bit0 = 1, using normal mode parameter
			modeIndex = SPH_MODE_NORMAL;
			devModeIndex = SPH_MODE_NORMAL;
#ifdef WB_SPE_SUPPORT	
        	if((updatedCoeff == 0) || (updatedCoeff&SPH_ENH_AND_FIR_UPDATE_TYPE_WB_ENH_MODE)!=0){
				L1SP_SetWbSpeechPara(l1sp.sph_allModePara[modeIndex]); //NB mode paramter!!
        	}
#endif
			if((updatedCoeff == 0) || (updatedCoeff&SPH_ENH_AND_FIR_UPDATE_TYPE_NB_ENH_MODE)!=0) {
				L1SP_SetSpeechMode(devModeIndex, l1sp.sph_allModePara[modeIndex]); //Send mode parameter to DSP. 
			}
			
		} else {			
#ifdef WB_SPE_SUPPORT
			if((updatedCoeff == 0) || (updatedCoeff&SPH_ENH_AND_FIR_UPDATE_TYPE_WB_ENH_MODE)!=0){			
				L1SP_SetWbSpeechPara(l1sp.recordModePara[modeIndex]); 
			}
#endif //WB_SPE_SUPPORT
			if((updatedCoeff == 0) || (updatedCoeff&SPH_ENH_AND_FIR_UPDATE_TYPE_NB_ENH_MODE)!=0){			
				L1SP_SetSpeechMode(devModeIndex, l1sp.recordModePara[modeIndex]); //Send mode parameter to DSP. 
			}
		}

		// Write NB FIR
		//for recording, DSP only use WB FIR after full solution is provided, 
		//the parameters just keep safe. by using 
		if((updatedCoeff == 0) || (updatedCoeff&SPH_ENH_AND_FIR_UPDATE_TYPE_NB_FIR)!=0) {
			if(inFirIndex >= NUM_SPH_INPUT_FIR){
				L1SP_Write_Audio_Coefficients_ByFirIndex(0xff, 0xff);
			} else {
				L1SP_Write_Audio_Coefficients_ByFirIndex(inFirIndex, 0xff);
			}			
		}

		// Write WB FIR
#ifdef WB_SPE_SUPPORT
		if((updatedCoeff == 0) || (updatedCoeff&SPH_ENH_AND_FIR_UPDATE_TYPE_WB_FIR)!=0){
			int16 *inFirs;
			int16 *outFirs;
			
			if(inFirIndex == 0xff) {
				inFirs = audio_alloc_mem(NUM_WB_FIR_COEFFS*sizeof(int16));
				memset(inFirs, 0, (NUM_WB_FIR_COEFFS)*sizeof(int16));
				inFirs[0] = 0x7fff;
			} else if (inFirIndex >= NUM_SPH_INPUT_FIR) {
				inFirs = l1sp.recordInFirCoeff[(inFirIndex-NUM_SPH_INPUT_FIR)];
			} else {
				inFirs = l1sp.sph_allWbInFirCoeff[inFirIndex];
			}

			if(outFirIndex == 0xff) {
				outFirs = audio_alloc_mem(NUM_WB_FIR_COEFFS*sizeof(int16));
				memset(outFirs, 0, (NUM_WB_FIR_COEFFS)*sizeof(int16));
				outFirs[0] = 0x7fff;
			} else if (outFirIndex >= NUM_SPH_INPUT_FIR) {
				outFirs = l1sp.recordInFirCoeff[(outFirIndex-NUM_SPH_INPUT_FIR)];
			} else {
				outFirs = l1sp.sph_allWbOutFirCoeff[outFirIndex];
			}

			L1SP_Write_WB_Audio_Coefficients(inFirs, outFirs);

			if(inFirIndex == 0xff) {
				audio_free_mem(inFirs);
			}
			if(outFirIndex == 0xff) {
				audio_free_mem(outFirs);
			}
			
			/*
			if(inFirIndex >= NUM_SPH_INPUT_FIR) {
#if defined(__STEREO_RECORD__) || defined(__SMART_PHONE_MODEM__)//set the second mic FIR
				if(outFirIndex!=0xff && outFirIndex>= NUM_SPH_INPUT_FIR){ 
					L1SP_Write_WB_Audio_Coefficients(l1sp.recordInFirCoeff[(inFirIndex-NUM_SPH_INPUT_FIR)],
						l1sp.recordInFirCoeff[(outFirIndex-NUM_SPH_INPUT_FIR)]);
				} else { 
					L1SP_Write_WB_Audio_Coefficients(l1sp.recordInFirCoeff[(inFirIndex-NUM_SPH_INPUT_FIR)],
						l1sp.sph_allWbOutFirCoeff[outFirIndex]); 
				}
#else
				L1SP_Write_WB_Audio_Coefficients(l1sp.recordInFirCoeff[(inFirIndex-NUM_SPH_INPUT_FIR)],
					l1sp.sph_allOutFirCoeff[outFirIndex]); //useless in this scenario, just keep safe
#endif
			} else {		
#if defined(__STEREO_RECORD__) || defined(__SMART_PHONE_MODEM__)//set the second mic FIR
				if(outFirIndex!=0xff && outFirIndex>= NUM_SPH_INPUT_FIR){ 
					L1SP_Write_WB_Audio_Coefficients(l1sp.sph_allWbInFirCoeff[inFirIndex],
						l1sp.recordInFirCoeff[(outFirIndex-NUM_SPH_INPUT_FIR)]);
				} else { 
					L1SP_Write_WB_Audio_Coefficients(l1sp.sph_allWbInFirCoeff[inFirIndex],
						l1sp.sph_allWbOutFirCoeff[outFirIndex]); 
				}
#else

				L1SP_Write_WB_Audio_Coefficients(l1sp.sph_allWbInFirCoeff[inFirIndex],
					l1sp.sph_allWbOutFirCoeff[outFirIndex]);
#endif

			}
			*/
		}
#endif //WB_SPE_SUPPORT

	}
#endif //__HD_RECORD__ || __SMART_PHONE_MODEM__
//---------------------- undefined cases --------------------
	else { // undefined cases. 
		kal_trace ( TRACE_INFO, L1SP_USELESS_SET, scene, 0, 0);
	}
	
	kal_trace( TRACE_INFO, L1SP_SET_ENH_FIR, scene, modeIndex, inFirIndex, outFirIndex, isNeedSpeMaskUpdate, l1sp.spe_app_mask);
	
}
/**
	@index: [Input] Identify which LID is going to provide
	@buffer: [Output] Buffer with the contain the result
	@len: [Input] Length of the output buffer
*/
void L1SP_GetNvramInfoByIndex(L1SP_NVRAM_INFO_INDEX index, void *buffer, uint16 len)
{
	switch(index)
	{
#if defined(__AMRWB_LINK_SUPPORT__)
	case L1SP_NVRAM_INFO_INDEX_WB_SPEECH_INPUT_FIR:
	{
		ASSERT(len == (NUM_SPH_INPUT_FIR * NUM_WB_FIR_COEFFS));
		memcpy(buffer, l1sp.sph_allWbInFirCoeff, sizeof(kal_uint16) * NUM_SPH_INPUT_FIR * NUM_WB_FIR_COEFFS);
	}
		break;
	case L1SP_NVRAM_INFO_INDEX_WB_SPEECH_OUTPUT_FIR:
	{
		ASSERT(len == (NUM_SPH_OUTPUT_FIR * NUM_WB_FIR_COEFFS));
		memcpy(buffer, l1sp.sph_allWbOutFirCoeff, sizeof(kal_uint16) * NUM_SPH_OUTPUT_FIR * NUM_WB_FIR_COEFFS);
	}
		break;
	case L1SP_NVRAM_INFO_INDEX_WB_SPEECH_MODE_PARAM:
	{
		ASSERT(len == (NUM_SPH_MODE * NUM_MAX_MODE_PARAS));
		memcpy(l1sp.sph_allWbModePara, buffer, sizeof(kal_uint16) * NUM_SPH_MODE * NUM_MAX_MODE_PARAS);
	}
		break;
#endif	
	default:
		ASSERT(0); 
	}
}

#if defined(__HD_RECORD__)
extern const short HD_RECORD_MODE_FIR_MAPPING_CH1[NUM_RECORD_SPH_MODE];
#if defined(__STEREO_RECORD__)
extern const short HD_RECORD_MODE_FIR_MAPPING_CH2[NUM_RECORD_SPH_MODE];
#endif
extern const char HD_RECORD_MODE_DEVICE_MAPPING[NUM_RECORD_SPH_MODE];
#endif
/**
	MED can put all nvram structure to AUD via this function. Audio/Speech driver will parsing the LID by itself. 
	
	@index: [Input] Identify which LID is used to parsing the buffer
	@buffer: [Input] Buffer with the contain from nvram
	@len: [Input] Length of the input buffer
*/
void L1SP_SetNvramInfoByIndex(L1SP_NVRAM_INFO_INDEX index, uint8* buffer, uint16 len)
{
	switch(index)
	{
	case L1SP_NVRAM_INFO_INDEX_UNDEF:		

		break;
	case L1SP_NVRAM_INFO_INDEX_PARAM:
	{
		int16 bufCur=0;

		//NB input FIR
		kal_mem_cpy(l1sp.sph_allInFirCoeff, (buffer + bufCur), (sizeof(kal_uint16)* 6 * NUM_FIR_COEFFS));
		l1sp.setNvramValuesFlag |= L1SP_NVRAM_VALUES_FLAG_IN_FIR;
        bufCur += (sizeof(kal_uint16)* 6 * NUM_FIR_COEFFS);

		//NB output FIR
        kal_mem_cpy(l1sp.sph_allOutFirCoeff, (buffer + bufCur) , (sizeof(kal_uint16)* 6 * NUM_FIR_COEFFS));
		l1sp.setNvramValuesFlag |= L1SP_NVRAM_VALUES_FLAG_OUT_FIR;
        bufCur += (sizeof(kal_uint16)* 6 * NUM_FIR_COEFFS);

		//selected FIR
		kal_mem_cpy(&(l1sp.sph_selectedOutFirIndex), (buffer + bufCur), sizeof(kal_uint16));
		bufCur += sizeof(kal_uint16);
		
		//common
		{
		uint16 *data = (uint16 *)(buffer + bufCur);
		L1SP_LoadCommonSpeechPara(data); //common paramter will copy into l1sp.sph_c_para in this function
		bufCur += sizeof(kal_uint16) * 12; //hardcoding size
		}

		//mode parameter
		kal_mem_cpy(l1sp.sph_allModePara, (buffer + bufCur) , (sizeof(kal_uint16)* NUM_SPH_MODE * 16));
		l1sp.setNvramValuesFlag |= L1SP_NVRAM_VALUES_FLAG_MODE;
		bufCur += (sizeof(kal_uint16)* NUM_SPH_MODE * 16);

		kal_mem_cpy(l1sp.sph_allVolumePara, (buffer + bufCur), (sizeof(kal_uint16)*3*7*4));
		l1sp.setNvramValuesFlag |= L1SP_NVRAM_VALUES_FLAG_VOLUME_PARAM;
		
		/*		
	    	kal_uint16 Media_Playback_Maximum_Swing;
    		kal_int16 Melody_FIR_Coeff_Tbl[25];
	    	kal_int16 audio_compensation_coeff[3][45];
		*/
	}
		break;
		
#if defined(__AMRWB_LINK_SUPPORT__)
	case L1SP_NVRAM_INFO_INDEX_WB_SPEECH_INPUT_FIR:
	{
		memcpy(l1sp.sph_allWbInFirCoeff, buffer, sizeof(kal_uint16) * NUM_SPH_INPUT_FIR * NUM_WB_FIR_COEFFS);
		l1sp.setNvramValuesFlag |= L1SP_NVRAM_VALUES_FLAG_WB_IN_FIR; // (1<<4) bit [4]
	}
		break;
	case L1SP_NVRAM_INFO_INDEX_WB_SPEECH_OUTPUT_FIR:
	{
		memcpy(l1sp.sph_allWbOutFirCoeff, buffer, sizeof(kal_uint16) * NUM_SPH_OUTPUT_FIR * NUM_WB_FIR_COEFFS);
		l1sp.setNvramValuesFlag |= L1SP_NVRAM_VALUES_FLAG_WB_OUT_FIR; // (1<<5) bit [5]
	}
		break;
	case L1SP_NVRAM_INFO_INDEX_WB_SPEECH_MODE_PARAM:
	{
		memcpy(l1sp.sph_allWbModePara, buffer, sizeof(kal_uint16) * NUM_SPH_MODE * NUM_MAX_MODE_PARAS);
		l1sp.setNvramValuesFlag |= L1SP_NVRAM_VALUES_FLAG_WB_MODE; // (1<<3) bit [3]
	}
		break;
#endif

#if defined(__HD_RECORD__)
	case L1SP_NVRAM_INFO_INDEX_HD_RECORD:
	{
		int16 bufCur=0, secLen;

		//enhancment mode 
		secLen = NUM_RECORD_SPH_MODE*NUM_MODE_PARAS*sizeof(uint16);
		memcpy(l1sp.recordModePara, (buffer + bufCur), secLen);
		bufCur += secLen;
		l1sp.numOfRecordMode = NUM_RECORD_SPH_MODE;
		l1sp.setNvramValuesFlag |= L1SP_NVRAM_VALUES_FLAG_RECORD_MODE; // (1<<6) bit [6]

		//input fir
		secLen = NUM_RECORD_INPUT_FIR*NUM_WB_FIR_COEFFS*sizeof(int16);
		memcpy(l1sp.recordInFirCoeff, (buffer + bufCur), secLen);
		bufCur += secLen;
		l1sp.numOfRecordInFir= NUM_RECORD_INPUT_FIR;
		l1sp.setNvramValuesFlag |= L1SP_NVRAM_VALUES_FLAG_RECORD_IN_FIR; // (1<<7) bit [7]

		l1sp.recordModeFirMappingCh1 = ((uint16 *)HD_RECORD_MODE_FIR_MAPPING_CH1);
#if defined(__STEREO_RECORD__)
		l1sp.recordModeFirMappingCh2 = ((uint16 *)HD_RECORD_MODE_FIR_MAPPING_CH2);
#endif
		l1sp_setRecordModeDeviceMapping((uint8 *)HD_RECORD_MODE_DEVICE_MAPPING, NUM_RECORD_SPH_MODE, NUM_RECORD_SPH_MODE);
	}
		break;
#endif //__HD_RECORD__	

	default:
		ASSERT(0); 
	}
		
}



//=============================================================================

int16 l1sp_getNumOfRecordMode(void)
{
	//default return value is 0 if "__HD_RECORD__" and "smart_phone" is not open. 
	return l1sp.numOfRecordMode;
}

#if defined(__HD_RECORD__)
void l1sp_setRecordModeDeviceMapping(uint8 *mappingTable, int16 length, int16 numOfRecordMode)
{
	ASSERT(numOfRecordMode == l1sp.numOfRecordMode);
	ASSERT(length == l1sp.numOfRecordMode);
	
	l1sp.recordModeDeviceMapping = mappingTable;
}

#endif

//=============================================================================

/**
	(related to customer folder)
	@return: number of enhancement mode sets, include speech used(in-call) and HD record used (when compile optin opened)
*/
kal_int16 L1SP_GetNumOfAllEnhancementMode()
{
	//physical number inside the nvram
	return (8 
#if defined(__HD_RECORD__)
		+ NUM_RECORD_SPH_MODE
#endif 
	);
}

//=============================================================================

/**
	user: maybe META
	(related to customer folder)
	For example, if you want to query wb input fir numbers, please invoke L1SP_GetNumOfAllFir(1,0) to get the result.
	
	@isWideBand: 0 is narrow band (8k), >0 is wide band(16k)
	@isOutputFir: 0 is for input FIR, >0 is for output FIR 
	@return: number of FIR sets. includes speech used(in-call), recording used (when compile option opened)
*/
kal_int16 L1SP_GetNumOfAllFir(kal_uint8 isWideBand, kal_uint8 isOutputFir)
{
	if(isWideBand == 0) { //NB
		if(isOutputFir)
			return NUM_SPH_OUTPUT_FIR;
		else
			return NUM_SPH_INPUT_FIR;
	}else{ //WB
		if(isOutputFir) {
			return NUM_SPH_OUTPUT_FIR;
		} else {
			return (NUM_SPH_INPUT_FIR
#if defined(__HD_RECORD__)
					+ NUM_RECORD_INPUT_FIR
#endif 
			);
		}

	}
}


//=============================================================================

#if defined(__HD_RECORD__)
extern const short HD_RECORD_MODE_CATEGORY[NUM_RECORD_SPH_MODE];
#endif

/**
	user: should be META only
	(realted to customer folder)

	@inputBufLength: [Input] the length of result buffer provided by caller. 
	  The value of "inputBufLength" and "1 * @return" should be equal, because category is a 1D array.
	@categoryResult: [Output] An array indicate which tab(category) the enhancement belongs to. 
	  0 for "in-call", 1 for "voice-record", 2 for "vedio-record". For example: categoryResult[0] = 0, categoryResult[1] = 0 ....	  
	@return: number of all enhancement mode sets, when <= 0, it means some error occur when function execution

*/
int16 L1SP_GetAllEnhancementModeCategory(int16 inputBufLength, int16 *categoryResult)

{
	int16 i;
	int16 result1[8];
	int16 numofEnhMode = L1SP_GetNumOfAllEnhancementMode();
	
	//error handling when buffer size is too small
	if(inputBufLength < (numofEnhMode*1)){
		return -1;
	}
	
	for(i=0; i<8; i++) {
		result1[i] = 0;
	}
		
	memcpy(categoryResult, result1, 8 * sizeof(int16));

#if defined(__HD_RECORD__)
	if(NUM_RECORD_SPH_MODE > 0)
		memcpy(&categoryResult[8], HD_RECORD_MODE_CATEGORY, NUM_RECORD_SPH_MODE*sizeof(kal_int16));
#endif

	return numofEnhMode;
}

//=============================================================================

#define QUOTE(x) #x
#define SPEECH_MODE_NAME_NORMAL QUOTE(Normal Mode)
#define SPEECH_MODE_NAME_EARPHONE QUOTE(Earphone Mode)
#define SPEECH_MODE_NAME_LOUDSPK QUOTE(Loud Speaker Mode)
#define SPEECH_MODE_NAME_BT_EARPHONE QUOTE(BlueTooth Earphone Mode)
#define SPEECH_MODE_NAME_BT_CORDLESS QUOTE(BuleTooth Cordless Mode)
#define SPEECH_MODE_NAME_BT_CARKIT QUOTE(BT Carkit Mode)
#define SPEECH_MODE_NAME_AUX1 QUOTE(AUX1 Mode)
#define SPEECH_MODE_NAME_AUX2 QUOTE(AUX2 Mode)

#if defined(__HD_RECORD__)
extern const char HD_RECORD_MODE_NAMES[NUM_RECORD_SPH_MODE][LEN_OF_ENHANCEMENT_MODE_NAME];
#endif //__HD_RECORD__
/**
	user: should be META only
	(realted to customer folder)

	@inputBufLength: [Input] the length of result buffer provided by caller. 
	  The value of "inputBufLength" and "@return * LEN_OF_ENHANCEMENT_MODE_NAME" should be equal. 	
	@nameResult: [Output] An array of names for different enhancement modes
	  (for every record, the max length is LEN_OF_ENHANCEMENT_MODE_NAME, i.e. 30) 
	@return: number of all enhancement mode sets, when <= 0, it means some error occur when function execution
*/
int16 L1SP_GetAllEnhancementModeName(int16 inputBufLength, char *nameResult)

{
	int16 totalModeNum; 
	
	char result[(8
#if defined(__HD_RECORD__)
		+NUM_RECORD_SPH_MODE
#endif //__HD_RECORD__
		)][LEN_OF_ENHANCEMENT_MODE_NAME];

	totalModeNum = L1SP_GetNumOfAllEnhancementMode();
	
	//erro handling when result buffer size is too small
	if(inputBufLength < (totalModeNum*LEN_OF_ENHANCEMENT_MODE_NAME)){
		return -1;
	}

	//normal process
	{
		char temp[LEN_OF_ENHANCEMENT_MODE_NAME] = SPEECH_MODE_NAME_NORMAL;
		memcpy(result[0], temp, LEN_OF_ENHANCEMENT_MODE_NAME*sizeof(char));
	}
	{
		char temp[LEN_OF_ENHANCEMENT_MODE_NAME] = SPEECH_MODE_NAME_EARPHONE;
		memcpy(result[1], temp, LEN_OF_ENHANCEMENT_MODE_NAME*sizeof(char));
	}
	{
		char temp[LEN_OF_ENHANCEMENT_MODE_NAME] = SPEECH_MODE_NAME_LOUDSPK;
		memcpy(result[2], temp, LEN_OF_ENHANCEMENT_MODE_NAME*sizeof(char));
	}
	{
		char temp[LEN_OF_ENHANCEMENT_MODE_NAME] = SPEECH_MODE_NAME_BT_EARPHONE;
		memcpy(result[3], temp, LEN_OF_ENHANCEMENT_MODE_NAME*sizeof(char));
	}
	{
		char temp[LEN_OF_ENHANCEMENT_MODE_NAME] = SPEECH_MODE_NAME_BT_CORDLESS;
		memcpy(result[4], temp, LEN_OF_ENHANCEMENT_MODE_NAME*sizeof(char));
	}
	{
		char temp[LEN_OF_ENHANCEMENT_MODE_NAME] = SPEECH_MODE_NAME_BT_CARKIT;
		memcpy(result[5], temp, LEN_OF_ENHANCEMENT_MODE_NAME*sizeof(char));
	}
	{
		char temp[LEN_OF_ENHANCEMENT_MODE_NAME] = SPEECH_MODE_NAME_AUX1;
		memcpy(result[6], temp, LEN_OF_ENHANCEMENT_MODE_NAME*sizeof(char));
	}
	{
		char temp[LEN_OF_ENHANCEMENT_MODE_NAME] = SPEECH_MODE_NAME_AUX2;
		memcpy(result[7], temp, LEN_OF_ENHANCEMENT_MODE_NAME*sizeof(char));
	}

#if defined(__HD_RECORD__)
	if(NUM_RECORD_SPH_MODE > 0)
		memcpy(result[8], HD_RECORD_MODE_NAMES, NUM_RECORD_SPH_MODE*LEN_OF_ENHANCEMENT_MODE_NAME*sizeof(char));
#endif

	memcpy(nameResult, result, totalModeNum*LEN_OF_ENHANCEMENT_MODE_NAME*sizeof(char));
	
	
	return totalModeNum;
}

//=============================================================================
#ifdef __HD_RECORD__
extern const char HD_RECORD_MODE_CATEGORY_NAME[NUM_RECORD_SPH_MODE_CATEGORY][LEN_OF_ENHANCEMENT_CATEGORY_NAME];
#endif

/**
	user: should be META only
	(realted to customer folder)

	@inputBufLength: [Input] the length of result buffer provided by caller. 
	  The value of "inputBufLength" and "@return * LEN_OF_ENHANCEMENT_CATEGORY_NAME" should be equal. 	
	@categoryName: [Output] An array indicate each tab's name. For example, 
	                        tab 0 is named "in-call"; tab 1 is named "voice-record"; Tab 2 is named "video-record"
	                        The max length of name is LEN_OF_ENHANCEMENT_CATEGORY_NAME, i.e. 20. 
	@return: number of enhancement categories, when <= 0, it means some error occur when function execution

*/
int16 L1SP_GetAllEnhancementCategoryName(int16 inputBufLength, char *categoryName)
{
	char result[(1
#if defined(__HD_RECORD__)		
		+NUM_RECORD_SPH_MODE_CATEGORY
#endif //__HD_RECORD__
		)][LEN_OF_ENHANCEMENT_CATEGORY_NAME];

	int16 catgNum = L1SP_GetNumOfAllEnhancementCategory();
	
	//error handling when result buffer is too small
	if(inputBufLength < (catgNum*LEN_OF_ENHANCEMENT_CATEGORY_NAME)){
		return -1;
	}
	
	{
		char temp[LEN_OF_ENHANCEMENT_CATEGORY_NAME] = "In-call";
		memcpy(result[0], temp, LEN_OF_ENHANCEMENT_CATEGORY_NAME*sizeof(char));
	}

#if defined(__HD_RECORD__)
	memcpy(result[1], HD_RECORD_MODE_CATEGORY_NAME, NUM_RECORD_SPH_MODE_CATEGORY*LEN_OF_ENHANCEMENT_CATEGORY_NAME*sizeof(char));
#endif

	memcpy(categoryName, result, catgNum*LEN_OF_ENHANCEMENT_CATEGORY_NAME*sizeof(char));	

	return catgNum;
}

//=============================================================================

/**
	user: should be META only
	(realted to customer folder)
	
	@return: number of all enhancement category
*/
int16 L1SP_GetNumOfAllEnhancementCategory(void)
{
	return ( 1 
#if defined(__HD_RECORD__)
		+ NUM_RECORD_SPH_MODE_CATEGORY
#endif  //__HD_RECORD__
		);
}

//=============================================================================

/**
	user: should be META only
	(realted to customer folder)
		
	@inputBufLength: [Input] the length of result buffer provided by caller. 
	  The value of "inputBufLength" and "@return * 1" should be equal, because number of param is a 1D array. 	
	@paramNumOfCatg: [Output] An array indicate the number of enhancement mode parameters in each tab's (i.e. category). 
	  For example, category 0 has 32 parameters in each mode; category 1 has 16 parameters in each mode
	@return:  number of enhancement categories, when <= 0, it means some error occur when function execution
	
*/
int16 L1SP_GetNumOfAllEnhancementCategoryParam(int16 inputBufLength, int16 *paramNumOfCatg)
{
	int16 i;
	int16 totalResultNum = L1SP_GetNumOfAllEnhancementCategory();

	//error handling
	if(inputBufLength < (totalResultNum*1)){
		return -1;
	}

	//others
#ifdef __AMRWB_LINK_SUPPORT__
	paramNumOfCatg[0] = NUM_MODE_PARAS*2;
#else //NB only
	paramNumOfCatg[0] = NUM_MODE_PARAS;
#endif //__AMRWB_LINK_SUPPORT__

	for(i=1; i< totalResultNum; i++) {
		paramNumOfCatg[i] = NUM_MODE_PARAS;
	}

	return totalResultNum;
	

}


void L1SP_SetOutputDevice( uint8 device )
{
   l1sp.output_dev = device;
   AFE_SetOutputDevice( L1SP_SPEECH, device );   
}

uint8 L1SP_GetOutputDevice(void)
{
   return l1sp.output_dev;
}

void L1SP_SetOutputVolume( uint8 volume1, int8 digital_gain_index )
{
   l1sp.sph_dl_vol = volume1;
   AFE_SetOutputVolume( L1SP_SPEECH, volume1, digital_gain_index );   
}

#if defined(__GAIN_TABLE_SUPPORT__)
void L1SP_SetOutputGainControl( uint32 gain )
{
   //l1sp.sph_dl_vol = volume1;//Need take care here
   AFE_SetOutputGainControl( L1SP_SPEECH, gain );
}
#endif

void L1SP_SetSpeechVolumeLevel( kal_uint8 level, kal_uint16 v_para[NUM_MAX_VOL_PARAS] )
{
#if (defined(__CENTRALIZED_SLEEP_MANAGER__) && (defined(MT6250) || defined(MT6260) || defined(MT6261) || defined(MT2501) || defined(MT2502)))
   kal_uint16 aud_id = L1SP_GetAudID();
#endif   
   if( level<MAX_VOL_LEVEL ) {
      l1sp.sph_level = level;
      memcpy(l1sp.sph_v_para, v_para, NUM_VOL_PARAS*sizeof(uint16));
      kal_trace( TRACE_INFO, L1SP_SET_MODE, l1sp.sph_mode, l1sp.sph_level, l1sp.mic_volume );
      SetSpeechEnhancement( true );
   }
#if (defined(__CENTRALIZED_SLEEP_MANAGER__) && (defined(MT6250) || defined(MT6260) || defined(MT6261) || defined(MT2501) || defined(MT2502)))
   L1SP_FreeAudID(aud_id);
#endif   
}

/**
	this function is to replace L1SP_SetSpeechVolumeLevel()
	
	@level: [input] speech volume level for speech
	@v_paraIndex: [input] volume paramter (saving in nvram) index
*/
void L1SP_SetSpeechVolumeLevelByIndex(kal_uint8 level, kal_uint8 v_paraIndex)
{
	L1SP_SetSpeechVolumeLevel(level, l1sp.sph_allVolumePara[v_paraIndex][level]);
}


void L1SP_SetInputSource( uint8 src )
{
   AFE_SetInputSource( src );
}

uint8 L1SP_GetInputSource( void )
{
   return AFE_GetInputSource();
}

void sub_SetMicrophoneVolume( uint8 mic_volume )
{
   if( mic_volume == 0 )// special case when mic_volume = 0, mute microphone
      AFE_MuteMicrophone( KAL_TRUE );
   else if( !l1sp.isULMute )
      AFE_MuteMicrophone( KAL_FALSE );

   l1sp.mic_volume = mic_volume;
   AFE_SetMicrophoneVolume( mic_volume );
   kal_trace( TRACE_INFO, L1SP_SET_MODE, l1sp.sph_mode, l1sp.sph_level, mic_volume );    
   
   SetSpeechEnhancement( true );
}

void L1SP_SetMicrophoneVolume( uint8 mic_volume )
{
#if (defined(__CENTRALIZED_SLEEP_MANAGER__) && (defined(MT6250) || defined(MT6260) || defined(MT6261) || defined(MT2501) || defined(MT2502)))
   kal_uint16 aud_id = L1SP_GetAudID();
#endif
   /* For the sake of integration, 
      In 8k record, driver will decrease 10dB Microphone Volume, and Speech Enhancement in DSP will compensate it. 
      In 16k record, we has no wideband-speech-enhancement, we cannot decrease Mic-Vol when 16k record 
      Please check Media_Record and L1SP_SetMicrophoneVolume
      */   

   if( mic_volume == 0 )// special case when mic_volume = 0, mute microphone
      AFE_MuteMicrophone( KAL_TRUE );
   else if( !l1sp.isULMute )
      AFE_MuteMicrophone( KAL_FALSE );

   kal_trace( TRACE_INFO, L1SP_SET_MIC_VOL, mic_volume, l1sp.sph_m_para[4]);	
   l1sp.mic_volume_fromMED = mic_volume;

   {
      if(mic_volume > 40)
         mic_volume -= 40;//down 10 dB
      else
         mic_volume = 0;
   }
   l1sp.mic_volume_adapted = mic_volume;
   kal_trace( TRACE_INFO, L1SP_ADAPT_MIC_VOL, l1sp.mic_volume_adapted);	

   
   //l1sp.mic_volume = mic_volume;
#ifndef WB_SPE_SUPPORT 
   if(AM_RECORD_16K == AM_GetRecordFormat()){   	
      sub_SetMicrophoneVolume( l1sp.mic_volume_fromMED );   //WB recording doesn't decrease by 10dB      
   }else{  
      sub_SetMicrophoneVolume( l1sp.mic_volume_adapted );   //NB recording decrease by 10dB
   }
#else
	 sub_SetMicrophoneVolume( l1sp.mic_volume_adapted );   //always decrease by 10dB
#endif  
#if (defined(__CENTRALIZED_SLEEP_MANAGER__) && (defined(MT6250) || defined(MT6260) || defined(MT6261) || defined(MT2501) || defined(MT2502)))
   L1SP_FreeAudID(aud_id);
#endif
}

#if defined(__GAIN_TABLE_SUPPORT__)
void L1SP_SetMicGainControl( uint32 mic_gain )
{
   //kal_trace( TRACE_INFO, L1SP_SET_MIC_VOL, mic_volume, l1sp.sph_m_para[4]);
   kal_uint32 mic_volume = mic_gain >> 26;
   kal_trace( TRACE_INFO, L1SP_SET_MIC_GAIN_CONTROL, mic_gain);
   //if( (l1sp.sph_m_para[4] & 0x2000) )
   {
      if(mic_volume >= 10)
         mic_volume -= 10;//down 10 dB
      else
         mic_volume = 0;
   }
   mic_gain = (mic_gain & 0x03FFFFFF) | (mic_volume << 26);
   //kal_trace( TRACE_INFO, L1SP_ADAPT_MIC_VOL, mic_volume);	
   kal_trace( TRACE_INFO, L1SP_ADAPT_MIC_GAIN_CONTROL, mic_gain);

   AFE_SetMicGainControl( mic_gain );
}
#endif

uint8 L1SP_GetMicrophoneVolume( void )
{
   return l1sp.mic_volume_fromMED;
}

void L1SP_SetSidetoneVolume( uint8 sidetone )
{
   AFE_SetSidetoneVolume( sidetone );
}

uint8 L1SP_GetSidetoneVolume( void )
{
   return AFE_GetSidetoneVolume();
}

void L1SP_MuteMicrophone( bool mute )
{
#if (defined(__CENTRALIZED_SLEEP_MANAGER__) && (defined(MT6250) || defined(MT6260) || defined(MT6261) || defined(MT2501) || defined(MT2502)))
   kal_uint16 aud_id = L1SP_GetAudID();
#endif   
   //AFE_MuteMicrophone( mute ); // do not use AFE_MuteMicrophone for speech enhancement
   AM_MuteULSpeech( mute );
   l1sp.isULMute = mute;
#if (defined(__CENTRALIZED_SLEEP_MANAGER__) && (defined(MT6250) || defined(MT6260) || defined(MT6261) || defined(MT2501) || defined(MT2502)))
   L1SP_FreeAudID(aud_id);
#endif   
}

void L1SP_MuteSpeaker( bool mute )
{
   AFE_MuteSpeaker( L1SP_SPEECH, mute );
}

bool L1SP_IsMicrophoneMuted( void )
{
   bool ret;
#if (defined(__CENTRALIZED_SLEEP_MANAGER__) && defined(MTK_SLEEP_ENABLE) && (defined(MT6250) || defined(MT6260) || defined(MT6261) || defined(MT2501) || defined(MT2502)))
   kal_uint16 aud_id = L1SP_GetAudID();
#endif   
   ret = AM_IsULSpeechMuted();
#if (defined(__CENTRALIZED_SLEEP_MANAGER__) && defined(MTK_SLEEP_ENABLE) && (defined(MT6250) || defined(MT6260) || defined(MT6261) || defined(MT2501) || defined(MT2502)))
   L1SP_FreeAudID(aud_id);
#endif 
   return ret;
}

extern void CSR_SP3G_Callback( SP3G_Event event, void *data );
extern void vt_SP3G_Callback( kal_uint8 event, void *data );

#if defined( __UMTS_RAT__ ) || defined( __UMTS_TDD128_MODE__ )
void L1SP_3G_Request(void)
{  
   if(l1sp.state ==  L1SP_STATE_3G_SPEECH_ON)
   {
      CSR_SP3G_Callback(SP3G_CODEC_READY, (void*)SP3G_Rab_Id());
      return;
   }
}
#endif

void L1SP_SetState(uint8 state)
{
#if defined( __UMTS_RAT__ ) || defined( __UMTS_TDD128_MODE__ )
   if( ( l1sp.state == L1SP_STATE_3G_SPEECH_ON && state == L1SP_STATE_2G_SPEECH_ON ) ||
      ( l1sp.state == L1SP_STATE_2G_SPEECH_ON && state == L1SP_STATE_3G_SPEECH_ON ) )
      l1sp.interRAT = true;
#endif
   l1sp.state = state; 
   L1Audio_Msg_Speech_State(L1Audio_Speech_State(state));
}

uint8 L1SP_GetState( void )
{
   return l1sp.state; 
}

#if _SPE_FOR_TEST_SIM_
//====================================================================
//l1spDspAdaptVol run under hisr
kal_uint16 pre_Sig_Energy;
kal_uint16 frame_index=0;

#define IDLE_NOISE_ADAPT_THRESHOLD 8

static void l1spDspAdaptVol(void *data)
{
   kal_uint8 vol_get;
   kal_int16 vol_get_temp;
   kal_int8 digiGainIdx_get;
   
   kal_uint16 PGA_max;//=(PFA_parameter & 0x003E)>>1;
   kal_uint16 PGA_decay;
   kal_uint16 PGA_parameter;//=L1Audio_GetDebugInfo(1);
   kal_uint16 PGA_stick_flag;//Dr.Nien wants to test digital or audio part genrating noise
   kal_uint16 PGA_threshold;
   kal_uint8 gpre_volume;
   
   PGA_parameter=L1Audio_GetDebugInfo(1);
   PGA_max=(PGA_parameter & 0x003E)>>1;
   PGA_decay=(PGA_parameter & 0x00C0)>>6;
   PGA_stick_flag=(PGA_parameter &0x0100)>>8;
   PGA_threshold=(PGA_parameter &0x0E00)>>9;
   PGA_threshold+=4;
   PGA_threshold=0x1<<PGA_threshold;
   AFE_GetOutputVolume( L1SP_SPEECH, &vol_get, &digiGainIdx_get );
   gpre_volume = vol_get;   
   frame_index++;
   if(frame_index>2000)
      frame_index=200;
   if( l1sp.sph_dl_vol<vol_get ) //protection
      vol_get=l1sp.sph_dl_vol;

   if( PGA_parameter & 0x0001 ){
#if defined(MT6253) || defined(MT6253E) || defined(MT6253L)|| defined(MT6252) || defined(MT6252H)
      if( AM_IsKeyToneOn() || AM_IsToneOn()
#ifdef BGSND_ENABLE
          || AM_IsBgsndOn()
#endif
      ){
         //kal_prompt_trace(MOD_L1SP,"restore gain");
         AFE_SetOutputVolume( L1SP_SPEECH, l1sp.sph_dl_vol, 0 );
      }else
#endif
      if(((PGA_stick_flag==0)&& (pre_Sig_Energy<16) && (*DP2_ADAPT_VOL < IDLE_NOISE_ADAPT_THRESHOLD))||((PGA_stick_flag==1)&&(frame_index%200>=100))){ 
         if ( (l1sp.sph_dl_vol-vol_get) >= PGA_max*16 )  // avoid special case vol = 0 will mute
            vol_get_temp = l1sp.sph_dl_vol-PGA_max*16;
         else
            vol_get_temp = vol_get - (PGA_decay+1)*16;
         if(vol_get_temp<1)
            vol_get_temp=1;
         vol_get=(kal_uint8)vol_get_temp;
         kal_dev_trace( TRACE_INFO, L1SP_DEC_SPK_VOL, vol_get, *DP2_ADAPT_VOL );
		 //if(vol_get!=gpre_volume)
			 AFE_SetOutputVolume( L1SP_SPEECH, vol_get, 0 );
      }
      else if(((PGA_stick_flag==0)&&(*DP2_ADAPT_VOL > PGA_threshold)) || ((PGA_stick_flag==1)&&(frame_index%200<100))){
         kal_dev_trace( TRACE_INFO, L1SP_INC_SPK_VOL, vol_get, *DP2_ADAPT_VOL );
         //if(l1sp.sph_dl_vol!=gpre_volume)
	         AFE_SetOutputVolume( L1SP_SPEECH, l1sp.sph_dl_vol, 0 );
      }
   }
   pre_Sig_Energy=*DP2_ADAPT_VOL;
}
#endif

kal_bool L1SP_IsSpeechOn( void )
{
    return (AM_IsSpeechOn());
}

void L1SP_Speech_On( uint8 RAT_Mode )
{
   kal_uint32 module_id = MOD_L1AUDIO_SPH_SRV;
   kal_uint32 voc_pattern = TVCI_CREATE_FILE;
   kal_uint32 *voc_ptr = &voc_pattern;

   if( AM_IsSpeechOn() )
      return;

#if defined(__CVSD_CODEC_SUPPORT__) 
    {
        kal_uint32 uCurrentSpMode = L1SP_GetSpeechMode();
        if (uCurrentSpMode == SPH_MODE_BT_EARPHONE || uCurrentSpMode == SPH_MODE_BT_CARKIT)
        {
            BT_SCO_Disable_All_APP();
        }
    }
#endif

#if defined(__VIBRATION_SPEAKER_SUPPORT__)
   VIBR_Vibration_Deactivate();
#endif
   PcmSink_TerminateSound();

#if _SPE_FOR_TEST_SIM_
#ifdef __GEMINI__
   if( is_test_sim( SIM1 ) || is_test_sim( SIM2 ))
#else 
   if( is_test_sim() )
#endif 
   {
      if( ( L1Audio_GetDebugInfo(1) & 0x1000 ) == 0 ){//use test SIM parameter
         extern void L1Audio_SetDebugInfoN( kal_uint16 index, kal_uint16 debug_info );
         L1Audio_SetDebugInfoN(1, 2569);
         l1sp.sph_m_para[8] = (l1sp.sph_m_para[8] & 0xCFFF) | (m_para_for_test_sim[8] & 0x3000);
         l1sp.sph_m_para[9] = (l1sp.sph_m_para[9] & 0xEFFF) | (m_para_for_test_sim[9] & 0x1000);
      }
   }
#endif //#if _SPE_FOR_TEST_SIM_
   
   TONE_StopAndWait();
   KT_StopAndWait();
   DTMF_MCU_StopAndWait(); 
   l1sp_updateSpeAppMask(0xff, true);

   AFE_SetDigitalGain(L1SP_SPEECH, 100);


   l1sp.aud_id = L1Audio_GetAudioID();
   L1Audio_SetFlag( l1sp.aud_id );     /* To lock sleep mode */
#if defined(CHIP_BACK_SPH_PHONE_CALL)
    // no dynamic download for chip back speech phone call
#else
#if defined(AEC_ENABLE)
   DSP_DynamicDownload( DDID_NOISE_REDUCTION );   
#endif
#endif

   SPE_SetSBSD( false ); //When true, SpeechDSP will do ErroreConceilment for speech frame quality.But Modem have SAIC which focus on the same purpose, drivers always turns off this function.

#if defined( __UMTS_RAT__ ) || defined( __UMTS_TDD128_MODE__ )
#ifdef __VIDEO_CALL_SUPPORT__
/* under construction !*/
/* under construction !*/
/* under construction !*/
#endif
      //In Dual mode, allow 2G/3G capability at initialization stage  for InterRAT HO
      //if 3G324M, there is no InterRAT
      sp3g_speech_init( RAT_3G_MODE );

   if( SP3G_Rab_State() && RAT_Mode != RAT_3G324M_MODE ){
      RAT_Mode = RAT_3G_MODE;
   }else if ( l1sp.tch_state )
      RAT_Mode = RAT_2G_MODE;
   l1sp.interRAT = false;
#endif

#if _SPE_FOR_TEST_SIM_
   L1Audio_HookHisrHandler( DP_D2C_ADAPT_VOL, l1spDspAdaptVol, 0 );
#endif

   AM_SpeechOn(RAT_Mode);
      
   SetSpeechEnhancement( true );

   switch(RAT_Mode)
   {
      case RAT_2G_MODE:
         L1SP_SetState(L1SP_STATE_2G_SPEECH_ON);     
         break;
#if defined( __UMTS_RAT__ ) || defined( __UMTS_TDD128_MODE__ )
      case RAT_3G_MODE: 
         L1SP_SetState(L1SP_STATE_3G_SPEECH_ON);
         CSR_SP3G_Callback(SP3G_CODEC_READY, (void*)SP3G_Rab_Id());
         break;
#ifdef __VIDEO_CALL_SUPPORT__
/* under construction !*/
/* under construction !*/
/* under construction !*/
/* under construction !*/
#endif
#endif
      default: 
         ASSERT(false);
   }
   if(l1sp.onHandler != NULL)
      l1sp.onHandler( (void *)l1sp.state );

#if defined(__ECALL_SUPPORT__)
   if (l1sp.pcm4wayOnHandler != NULL)
      l1sp.pcm4wayOnHandler( (void *)0);
#endif

#ifndef __L1_STANDALONE__ // avoid link error
#if defined(__VM_CODEC_SUPPORT__)
   if(!tst_trace_check_ps_filter_off(TRACE_GROUP_VOC, &module_id, 0x2))
   {
      l1sp.isVocOn = true;
      tst_vc_response(TVCI_VM_LOGGING, (const kal_uint8*)voc_ptr, 4);
      vmRecord(NULL, 0, true); // type is to match MEDIA_FORMAT_GSM_FR
   }
   else
   {
      l1sp.isVocOn = false;
   }
#endif
#endif

#if defined(__CVSD_CODEC_SUPPORT__)
    {
        kal_uint32 uCurrentSpMode = L1SP_GetSpeechMode();
        if (   (uCurrentSpMode == SPH_MODE_BT_EARPHONE || uCurrentSpMode == SPH_MODE_BT_CARKIT)
            && l1sp.cordless_path == SPH_CORDLESS_PATH_BT)
        {
            BT_SCO_SpeechPath_ON(BT_SCO_APP_SPEECH_PATH_BOTH);
        }
    }
#endif

}


void L1SP_Afe_On( kal_uint32 afe_mode )
{
   if( AM_IsAfeOn() )
      return;   
   TONE_StopAndWait();
   KT_StopAndWait();
   PcmSink_TerminateSound();
   l1sp.aud_id = L1Audio_GetAudioID();
   L1Audio_SetFlag( l1sp.aud_id );     /* To lock sleep mode */
            
   AM_AfeOn(afe_mode);   
}

void L1SP_Afe_Off( void )
{
   if( !AM_IsAfeOn() )
      return;   
   AM_AfeOff();  
   L1Audio_ClearFlag( l1sp.aud_id );
   L1Audio_FreeAudioID( l1sp.aud_id );       
}

void L1SP_Register_Service(void (*onHandler)(void *), void (*offHandler)(void *))
{
   l1sp.onHandler = onHandler;   
   l1sp.offHandler = offHandler;
}

void L1SP_UnRegister_Service( void )
{
   l1sp.onHandler = NULL;   
   l1sp.offHandler = NULL;
}

#if defined(__ECALL_SUPPORT__)
void L1SP_Register_Pcm4WayService(void (*onHandler)(void *), void (*offHandler)(void *))
{
   l1sp.pcm4wayOnHandler = onHandler; 
   l1sp.pcm4wayOffHandler = offHandler;
}

void L1SP_UnRegister_Pcm4Way_Service( void )
{
   l1sp.pcm4wayOnHandler = NULL; 
   l1sp.pcm4wayOffHandler = NULL;
}
#endif

void L1SP_Speech_Off( void )
{
   kal_uint32 uCurrentSpMode;

#ifndef __L1_STANDALONE__ // avoid link error
#if defined(__VM_CODEC_SUPPORT__)
	if(l1sp.isVocOn)
   {
      kal_uint32 voc_pattern = TVCI_CLOSE_FILE;
      kal_uint32 *voc_ptr = &voc_pattern;
      
      vmStop(NULL);
      tst_vc_response(TVCI_VM_LOGGING, (const kal_uint8*)voc_ptr, 4);
      l1sp.isVocOn = false;
   }
#endif
#endif

   if( !AM_IsSpeechOn() )
      return;

#if defined(__CVSD_CODEC_SUPPORT__) 
   uCurrentSpMode = L1SP_GetSpeechMode();
   if( uCurrentSpMode == SPH_MODE_BT_EARPHONE || uCurrentSpMode == SPH_MODE_BT_CARKIT )
   {
      BT_SCO_Disable_All_APP();
   }
#endif

#if defined(__ECALL_SUPPORT__)
   if (l1sp.pcm4wayOffHandler != NULL)
      l1sp.pcm4wayOffHandler( (void *)0 );
#endif

   if(l1sp.offHandler != NULL)
      l1sp.offHandler( (void *)l1sp.state );
   SetSpeechEnhancement( false );

   AM_SpeechOff();

#if _SPE_FOR_TEST_SIM_
   L1Audio_UnhookHisrHandler( DP_D2C_ADAPT_VOL );
#endif

#if defined( __UMTS_RAT__ )
/* under construction !*/
/* under construction !*/
/* under construction !*/
/* under construction !*/
/* under construction !*/
#ifdef __VIDEO_CALL_SUPPORT__
/* under construction !*/
#endif
/* under construction !*/
/* under construction !*/
/* under construction !*/
/* under construction !*/
/* under construction !*/
/* under construction !*/
/* under construction !*/
#ifdef __VIDEO_CALL_SUPPORT__
/* under construction !*/
#endif
/* under construction !*/
/* under construction !*/
#ifdef __VIDEO_CALL_SUPPORT__
/* under construction !*/
/* under construction !*/
/* under construction !*/
#endif
/* under construction !*/
/* under construction !*/
/* under construction !*/
/* under construction !*/
/* under construction !*/
/* under construction !*/
/* under construction !*/
/* under construction !*/
/* under construction !*/
/* under construction !*/
/* under construction !*/
#endif
   L1SP_SetState( L1SP_STATE_IDLE );

   SPE_SetSBSD( false );

#if defined(__VIBRATION_SPEAKER_SUPPORT__)
   VIBR_Vibration_Activate();
#endif
   
   L1Audio_ClearFlag( l1sp.aud_id );
   L1Audio_FreeAudioID( l1sp.aud_id );
}

void L1SP_Set_DAI_Mode( uint8 mode )
{
	//this feature is phased out
  //AM_SetDAIMode( mode );
}

void L1SP_SetAfeLoopback( bool enable )
{
#if (defined(__CENTRALIZED_SLEEP_MANAGER__) && (defined(MT6250) || defined(MT6260) || defined(MT6261) || defined(MT2501) || defined(MT2502)))
   kal_uint16 aud_id = L1SP_GetAudID();
#endif      
   if( enable )
      AFE_TurnOnLoopback();
   else
      AFE_TurnOffLoopback();
#if (defined(__CENTRALIZED_SLEEP_MANAGER__) && (defined(MT6250) || defined(MT6260) || defined(MT6261) || defined(MT2501) || defined(MT2502)))
   L1SP_FreeAudID(aud_id);
#endif      
}
/*for MIC2 loopback*/
void L1SP_SetAfeLoopback2( bool enable )
{
   if( enable ){
      #if defined(MT6256)
      l1sp_updateSpeAppMask(SPH_ENH_MASK_AGC, false);
      SetSpeechEnhancement(KAL_TRUE);
      AFE_TurnOnLoopback2();
      #else
      AFE_TurnOnLoopback();
      #endif
   }
   else{
      AFE_TurnOffLoopback();
   }
}

kal_bool L1SP_GetAfeLoopbackStatus( void )
{
   return AFE_GetLoopbackStatus();
}

void L1SP_SetFIR( bool enable )
{
   if( enable ){
      AFE_TurnOnFIR( L1SP_SPEECH );
      AFE_TurnOnFIR( L1SP_VOICE );
   }else{
      AFE_TurnOffFIR( L1SP_SPEECH );
      AFE_TurnOffFIR( L1SP_VOICE );
   }
}

void L1SP_Write_Audio_Coefficients( const int16 in_coeff[45], const int16 out_coeff[45] )
{
#if (defined(__CENTRALIZED_SLEEP_MANAGER__) && (defined(MT6250) || defined(MT6260) || defined(MT6261) || defined(MT2501) || defined(MT2502)))
   kal_uint16 aud_id = L1SP_GetAudID();
#endif   
   AM_WriteFirCoeffs( in_coeff, out_coeff );
#if (defined(__CENTRALIZED_SLEEP_MANAGER__) && (defined(MT6250) || defined(MT6260) || defined(MT6261) || defined(MT2501) || defined(MT2502)))
   L1SP_FreeAudID(aud_id);
#endif   
}


void L1SP_Write_Audio_Coefficients_ByFirIndex( const uint8 inFirIndex, 
	const uint8 outOrIn2FirIndex)
{

	int16 *inCoeff; //[NUM_FIR_COEFFS];
	int16 *outOrIn2Coeff; //[NUM_FIR_COEFFS];

	inCoeff = audio_alloc_mem(NUM_FIR_COEFFS*sizeof(int16));
	outOrIn2Coeff = audio_alloc_mem(NUM_FIR_COEFFS*sizeof(int16));
		
	if(inFirIndex == 0xff) {
		inCoeff[0] = 0x7fff;
		memset(&inCoeff[1], 0, (NUM_FIR_COEFFS-1)*sizeof(int16));
	} else {
		memcpy(inCoeff, l1sp.sph_allInFirCoeff[inFirIndex], (NUM_FIR_COEFFS)*sizeof(int16));		
	}

	if(outOrIn2FirIndex == 0xff) {
		outOrIn2Coeff[0] = 0x7fff;
		memset(&outOrIn2Coeff[1], 0, (NUM_FIR_COEFFS-1)*sizeof(int16));
	} else {
		memcpy(outOrIn2Coeff, l1sp.sph_allOutFirCoeff[outOrIn2FirIndex], (NUM_FIR_COEFFS)*sizeof(int16));		
	}

	L1SP_Write_Audio_Coefficients( inCoeff, outOrIn2Coeff );

	audio_free_mem((void **)(&inCoeff));
	audio_free_mem((void **)(&outOrIn2Coeff));
	
}

void L1SP_EnableSpeechEnhancement( bool enable )
{
   if(enable)
   {
      l1sp.spe_flag = true;
      SetSpeechEnhancement(true);
   }
   else 
   {
      SetSpeechEnhancement(false);
      l1sp.spe_flag = false;
   }      
}

void L1SP_LoadSpeechPara( void ) 
{
#if (defined(__CENTRALIZED_SLEEP_MANAGER__) && (defined(MT6250) || defined(MT6260) || defined(MT6261) || defined(MT2501) || defined(MT2502)))
   kal_uint16 aud_id = L1SP_GetAudID();
#endif   
   SPE_LoadSpeechPara(l1sp.sph_c_para, l1sp.sph_m_para, l1sp.sph_v_para);   
#if (defined(__CENTRALIZED_SLEEP_MANAGER__) && (defined(MT6250) || defined(MT6260) || defined(MT6261) || defined(MT2501) || defined(MT2502)))
   L1SP_FreeAudID(aud_id);
#endif      
}

void L1SP_Init( void )
{
#if defined(CHIP_BACK_SPH_PHONE_CALL)
    // default set to normal mode for chip back phone call scenario
   l1sp.sph_mode = SPH_MODE_NORMAL;
#else
   l1sp.sph_mode = SPH_MODE_UNDEFINED;
#endif
#ifndef __L1_STANDALONE__
   custom_cfg_audio_ec_range( &l1sp.min_ec_level, &l1sp.max_ec_level );
#else
   l1sp.min_ec_level = 1;
   l1sp.max_ec_level = 6;
#endif
   memset(&l1sp.sph_c_para, 0, NUM_COMMON_PARAS*sizeof(uint16));
   memset(&l1sp.sph_m_para, 0, NUM_MODE_PARAS*sizeof(uint16));
   memset(&l1sp.sph_v_para, 0, NUM_VOL_PARAS*sizeof(uint16));
   
#if defined(__DUAL_MIC_SUPPORT__)
   memset(&l1sp.sph_dmnr_para, 0, NUM_DMNR_PARAM*sizeof(uint16));
#ifdef __AMRWB_LINK_SUPPORT__   
   memset(&l1sp.sph_wb_dmnr_para, 0, NUM_WB_DMNR_PARAM*sizeof(uint16));
#endif
#endif 

   l1sp.mic_volume = AFE_GetMicrophoneVolume(); // get initial value

#if defined(__BT_SUPPORT__)   
   l1sp.bt_on = false;
#endif

#if defined( __UMTS_RAT__ )
/* under construction !*/
/* under construction !*/
#endif

   SPE_Init();
   l1sp.spe_flag = true;
   l1sp.isULMute = false;
   l1sp.spe_state = 0;
   
   //default set the DMNR on
   l1sp.spe_app_mask = 0xffff;
   l1sp.spe_usr_mask = 0xffff;
   
   l1sp.sph_dl_vol = 128;
   l1sp.pcmplayback_flag = KAL_FALSE;
   l1sp.speech_dmnr_loopback = KAL_FALSE; 
   
   l1sp.onHandler = NULL;
   l1sp.offHandler = NULL;
#if defined(__ECALL_SUPPORT__)
   l1sp.pcm4wayOnHandler = NULL; 
   l1sp.pcm4wayOffHandler = NULL;
#endif
   l1sp.output_dev = 0;
   L1SP_SetState(L1SP_STATE_IDLE);


   l1sp.setNvramValuesFlag = 0;
   memset(l1sp.sph_allModePara, 0, NUM_SPH_MODE*NUM_MODE_PARAS*sizeof(uint16));
   memset(l1sp.sph_allInFirCoeff, 0, NUM_SPH_INPUT_FIR*NUM_FIR_COEFFS*sizeof(int16));
   memset(l1sp.sph_allOutFirCoeff, 0, NUM_SPH_OUTPUT_FIR*NUM_FIR_COEFFS*sizeof(int16));
   memset(l1sp.sph_allVolumePara, 0, 3*7*4*sizeof(uint16));
   
   l1sp.sph_selectedOutFirIndex = 0;
#if defined(__HD_RECORD__)
   memset(l1sp.recordModePara, 0, NUM_RECORD_SPH_MODE*NUM_MODE_PARAS*sizeof(uint16));
   memset(l1sp.recordInFirCoeff, 0, NUM_RECORD_INPUT_FIR*NUM_WB_FIR_COEFFS*sizeof(int16));
   l1sp.recordModeFirMappingCh1 = NULL;
#if defined(__STEREO_RECORD__)   
   l1sp.recordModeFirMappingCh2 = NULL;
#endif //__STEREO_RECORD__
   l1sp.recordModeDeviceMapping = NULL;
#endif //__HD_RECORD__
   l1sp.numOfRecordMode = 0;
   l1sp.numOfRecordInFir = 0;
      
#if defined(__CVSD_CODEC_SUPPORT__) 
   l1sp.cordless_path = SPH_CORDLESS_PATH_BT;
#endif
}
kal_bool L1SP_TCH_State( void )
{
   return l1sp.tch_state;
}

// run under l1 LISR context
void L1SP_TCH_Notify( bool bOn )
{
#if defined( __UMTS_RAT__ )
/* 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
}

void L1SP_SpeechLoopBackEnable(kal_bool fgEnable)
{
#if defined(MT6235) || defined(MT6235B) || defined(MT6236) || defined(MT6536B) || defined(MT6268) || defined(MT6253) || defined(MT6256) || defined(MT6251) || defined(MT6253E) || defined(MT6253L)|| defined(MT6252) || defined(MT6252H)

    #define LOOP_BACK_ON    (kal_uint16)(0x1 << 6)
    
    if (fgEnable)
    {
        *DSP_SPEECH_DEBUG_MODE = *DSP_SPEECH_DEBUG_MODE | LOOP_BACK_ON;
    }
    else
    {
        *DSP_SPEECH_DEBUG_MODE = *DSP_SPEECH_DEBUG_MODE & ~LOOP_BACK_ON;
    }

    //kal_prompt_trace(MOD_L1SP,"DSP_SPEECH_DEBUG_MODE[%08x]    = (%04x) \r\n", DSP_SPEECH_DEBUG_MODE, *DSP_SPEECH_DEBUG_MODE);
#else
    (void)fgEnable;
#endif    
}

void L1SP_SetCordLessPath( kal_uint8 uPath )
{
#if defined(__CVSD_CODEC_SUPPORT__) 
   kal_brief_trace( TRACE_GROUP_SCO, L1AUDIO_BTSCO_SET_CORDLESS_PATH, l1sp.cordless_path, uPath);
   ASSERT(uPath < SPH_CORDLESS_PATH_UNDEFINED);
   l1sp.cordless_path = uPath;
#endif
}

void LINEIN_SetOutputDevice( uint8 device )
{
   AFE_SetOutputDevice( L1SP_LINEIN, device );
}

void LINEIN_SetOutputVolume( uint8 volume1, int8 digital_gain_index )
{
   AFE_SetOutputVolume( L1SP_LINEIN, volume1, digital_gain_index );
}

void LINEIN_Open()
{
#if defined(__VIBRATION_SPEAKER_SUPPORT__)
   VIBR_Vibration_Deactivate();
#endif
   PcmSink_TerminateSound();
   if (!lineon_flag){
      ktLock();
      AFE_TurnOnSpeaker(L1SP_LINEIN);
      lineon_flag = KAL_TRUE;
   }
}

void LINEIN_Close()
{
   if(lineon_flag){
#if defined(MT6253E) || defined(MT6253L) || defined(MT6252H) || defined(MT6252)
      AFE_SetGainFastRamp(KAL_TRUE);    
#endif

      AFE_TurnOffSpeaker(L1SP_LINEIN);

#if defined(MT6253E) || defined(MT6253L) || defined(MT6252H) || defined(MT6252)
      kal_sleep_task(3);
      AFE_SetGainFastRamp(KAL_FALSE);    
#endif

      ktUnlock();
      lineon_flag = KAL_FALSE;
   }
#if defined(__VIBRATION_SPEAKER_SUPPORT__)
   VIBR_Vibration_Activate();
#endif
}

void LINEIN_MuteSpeaker( bool mute )
{
   AFE_MuteSpeaker( L1SP_LINEIN, mute );
}

#if defined(__GAIN_TABLE_SUPPORT__)
void LINEIN_SetOutputGainControl( kal_uint32 gain ){
   AFE_SetOutputGainControl( L1SP_LINEIN, gain );
}

void LINEIN_SetOutputGainControlDualPath( kal_uint32 ext_amp_gain ){
   AFE_SetOutputGainControlDualPath( L1SP_LINEIN, ext_amp_gain );
}
#endif

#if defined(__DUAL_MIC_SUPPORT__)
#include "pcm4way.h"

#define FRAME_BUF_NO (32)
#define NB_FRAME_SIZE   (160)
static uint16 PCM_UL_BUF[FRAME_BUF_NO][NB_FRAME_SIZE];
static uint16 PCM_DL_BUF[FRAME_BUF_NO][NB_FRAME_SIZE];
static uint32 DELAY = 12;
static uint32 UL_tmp_w, UL_tmp_r;
static uint32 DL_tmp_w, DL_tmp_r;

void AcousticLoopback_PCM4WAY_HisrHdl()
{
   {
      if( (UL_tmp_w - UL_tmp_r) < FRAME_BUF_NO ){        
         PCM4WAY_GetFromMic((uint16*)PCM_UL_BUF[UL_tmp_w & (FRAME_BUF_NO - 1)]);
         kal_brief_trace(TRACE_INFO, L1SP_DMNR_LOOPBACK_FROM_MIC, 
                          PCM_UL_BUF[UL_tmp_w & (FRAME_BUF_NO - 1)][0],
                          PCM_UL_BUF[UL_tmp_w & (FRAME_BUF_NO - 1)][1],
                          PCM_UL_BUF[UL_tmp_w & (FRAME_BUF_NO - 1)][2],
                          PCM_UL_BUF[UL_tmp_w & (FRAME_BUF_NO - 1)][3]);         
         UL_tmp_w++;            
      }else{
         kal_brief_trace( TRACE_INFO, L1SP_DMNR_LOOPBACK_SKIP_MIC); 
      }

      if( (UL_tmp_w - UL_tmp_r) >= DELAY ){
         PCM4WAY_PutToSE(PCM_UL_BUF[UL_tmp_r & (FRAME_BUF_NO - 1)]);   
         kal_brief_trace( TRACE_INFO, L1SP_DMNR_LOOPBACK_TO_SE, 
                          PCM_UL_BUF[UL_tmp_r & (FRAME_BUF_NO - 1)][0],
                          PCM_UL_BUF[UL_tmp_r & (FRAME_BUF_NO - 1)][1],
                          PCM_UL_BUF[UL_tmp_r & (FRAME_BUF_NO - 1)][2],
                          PCM_UL_BUF[UL_tmp_r & (FRAME_BUF_NO - 1)][3]);               
         UL_tmp_r++;
      }else{
         kal_brief_trace( TRACE_INFO, L1SP_DMNR_LOOPBACK_FILL_SE); 
         PCM4WAY_FillSE(0);
      }
   }

   {
      if( (DL_tmp_w - DL_tmp_r) < FRAME_BUF_NO ){        
         PCM4WAY_GetFromSD((uint16*)PCM_DL_BUF[DL_tmp_w & (FRAME_BUF_NO - 1)]);
         kal_brief_trace( TRACE_INFO, L1SP_DMNR_LOOPBACK_FROM_SD, 
                          PCM_DL_BUF[DL_tmp_w & (FRAME_BUF_NO - 1)][0],
                          PCM_DL_BUF[DL_tmp_w & (FRAME_BUF_NO - 1)][1],
                          PCM_DL_BUF[DL_tmp_w & (FRAME_BUF_NO - 1)][2],
                          PCM_DL_BUF[DL_tmp_w & (FRAME_BUF_NO - 1)][3]);
         DL_tmp_w++;            
      }else{
         kal_brief_trace( TRACE_INFO, L1SP_DMNR_LOOPBACK_SKIP_SD); 
      }

      if( (DL_tmp_w - DL_tmp_r) >= DELAY ){
         PCM4WAY_PutToSpk(PCM_DL_BUF[DL_tmp_r & (FRAME_BUF_NO - 1)]);  
         kal_brief_trace( TRACE_INFO, L1SP_DMNR_LOOPBACK_TO_SPK, 
                          PCM_DL_BUF[DL_tmp_r & (FRAME_BUF_NO - 1)][0],
                          PCM_DL_BUF[DL_tmp_r & (FRAME_BUF_NO - 1)][1],
                          PCM_DL_BUF[DL_tmp_r & (FRAME_BUF_NO - 1)][2],
                          PCM_DL_BUF[DL_tmp_r & (FRAME_BUF_NO - 1)][3]);         
         DL_tmp_r++;          
      }else{
         kal_brief_trace( TRACE_INFO, L1SP_DMNR_LOOPBACK_FILL_SPK); 
         PCM4WAY_FillSpk(0);
      }
   }
   kal_brief_trace( TRACE_INFO, L1SP_DMNR_LOOPBACK_UL_DL_INDEX, UL_tmp_w, UL_tmp_r, DL_tmp_w, DL_tmp_r);
}

void ABF_SetAcousticLoopback( kal_bool loopback )
{
   if(loopback){
      if(ABF_GetAcousticLoopbackStatus()){
         kal_brief_trace( TRACE_INFO,  L1SP_DMNR_LOOPBACK_ILLEGAL_OPEN);
         return;
      }
   	
      UL_tmp_w = UL_tmp_r = DL_tmp_w = DL_tmp_r = 0;
      {
         int32 I;
         for( I = 0; FRAME_BUF_NO > I; I++ ){
            memset(PCM_UL_BUF, 0, sizeof(uint16)*NB_FRAME_SIZE);
            memset(PCM_DL_BUF, 0, sizeof(uint16)*NB_FRAME_SIZE);
         }         
      }
      //L1SP_EnableDLSpeechEnhancement(false);  
      L1SP_Speech_On(RAT_2G_MODE);
      L1SP_SpeechLoopBackEnable(KAL_TRUE);
      PCM4WAY_Start(AcousticLoopback_PCM4WAY_HisrHdl, 0);
      l1sp.speech_dmnr_loopback = KAL_TRUE;
   } else {
      if(!ABF_GetAcousticLoopbackStatus()){
         kal_brief_trace( TRACE_INFO,  L1SP_DMNR_LOOPBACK_ILLEGAL_CLOSE);
         return;
      }

      PCM4WAY_Stop(0);
      L1SP_SpeechLoopBackEnable(KAL_FALSE);
     
      L1SP_Speech_Off();
      //L1SP_EnableDLSpeechEnhancement(true);      
      l1sp.speech_dmnr_loopback = KAL_FALSE;
   }
}
kal_bool ABF_GetAcousticLoopbackStatus( void )
{
   return l1sp.speech_dmnr_loopback;
}
#endif

#if defined(MT6260) || defined(MT6261) || defined(MT2501) || defined(MT2502)
#define MIC_MAX_VALUE_FOR_INTENSITY 5000
#else   // chip compile option
#define MIC_MAX_VALUE_FOR_INTENSITY 12000
#endif  // chip compile option
#define MIC_MIN_VALUE_FOR_INTENSITY 0

void L1SP_GetIntensityExtremeValues(kal_uint32 *p_intensity_max_value, kal_uint32 *p_intensity_min_value)
{
    *p_intensity_max_value = MIC_MAX_VALUE_FOR_INTENSITY;
    *p_intensity_min_value = MIC_MIN_VALUE_FOR_INTENSITY;
    
    return;
}

#ifndef BOUNDED
#define BOUNDED(in,up,lo) ((in) > (up) ? (up) : (in) < (lo) ? (lo) : (in))
#endif

kal_uint32 L1SP_GetFrameIntensity(kal_uint32 channel)
{
#if defined(MT6260) || defined(MT6261) || defined(MT2501) || defined(MT2502)
    {
        kal_uint16 record_intensity = *DSP_PCM_FRM_PEAK_UL;
        record_intensity = BOUNDED(record_intensity, MIC_MAX_VALUE_FOR_INTENSITY, MIC_MIN_VALUE_FOR_INTENSITY);
        return record_intensity;
    }
#else   // chip compile option
#if defined(WAV_CODEC)   
    {   //Now, we only use the FIRST_MIC, which is defined into 0
        kal_uint32 record_intensity = pcmGetFrameIntensity();
        record_intensity = BOUNDED(record_intensity, MIC_MAX_VALUE_FOR_INTENSITY, MIC_MIN_VALUE_FOR_INTENSITY);
        return record_intensity;
    }
#else
   return 0;
#endif   
#endif  // chip compile option
}

/* Just for Factory Usage */
void L1SP_AcousticLoopbackOn (void)
{
#if defined( __ACOUSTIC_LOOPBACK_SUPPORT__ )      
   AcousticLoopbackOn();
#endif   
}

/* Just for Factory Usage */
void L1SP_AcousticLoopbackOff (void)
{
#if defined( __ACOUSTIC_LOOPBACK_SUPPORT__ )         
   AcousticLoopbackOff();
#endif   
}

/* Just for Factory Usage */
void L1SP_AcousticLoopbackSpeechMode(kal_uint8 u1Mode)
{
#if defined( __ACOUSTIC_LOOPBACK_SUPPORT__ )   
   AcousticLoopbackSpeechMode(u1Mode);
#endif       
}

/* Just for Factory Usage */
kal_bool L1SP_AcousticLoopbackStatus(void)
{
#if defined( __ACOUSTIC_LOOPBACK_SUPPORT__ )   
   return AcousticLoopbackStatus();
#else
    return KAL_FALSE;
#endif       
}

/* Just for Factory Usage */
void L1SP_AcousticLoopbackBypassMode(kal_uint8 u1Mode)
{
#if defined( __ACOUSTIC_LOOPBACK_SUPPORT__ )   
   AcousticLoopbackBypassMode(u1Mode);
#endif    
}

/* Just for Factory Usage */
void L1SP_AcousticLoopbackLength (kal_uint32 u4Length)
{
#if defined( __ACOUSTIC_LOOPBACK_SUPPORT__ )   
   AcousticLoopbackLength(u4Length);
#endif   
}

void L1SP_MutePCMOuputPort ( kal_bool fMute )
{
#if defined(MT6252)
   #define PCM_MUTE    (kal_uint16)(0x1 << 15)
	kal_brief_trace( TRACE_INFO, L1SP_Mute_PCM_Ouput_Port, fMute );
   if(fMute)
   {
      *DSP_AUDIO_CTRL2 = *DSP_AUDIO_CTRL2 | PCM_MUTE;
   }
   else
   {
      *DSP_AUDIO_CTRL2 = *DSP_AUDIO_CTRL2 & ~PCM_MUTE;
   }
#endif
}


#if defined( __VOICE_CHANGER_SUPPORT__ )
extern kal_bool SPE_GetCustomProcessState(void);

kal_bool L1SP_SetVoiceChangerMode(SPH_VOICE_CHANGER_MODE mode)
{
    kal_bool process_on = SPE_GetCustomProcessState();
    kal_trace( TRACE_GROUP_AUD_SPE_CSUT, SPEECH_VCH_SET_MODE, l1sp.vchg_mode, mode, process_on,AM_IsSpeechOn());  
    if( mode== SPH_VC_NORMAL && process_on)
    {
    	 l1sp.vchg_mode = mode;
    	 SPE_CustomProcess(KAL_FALSE,0,0,0);
    	 
    }
    else if(process_on && (l1sp.vchg_mode!=mode))
    {
    	 SPE_CustomProcess(KAL_FALSE,0,0,0);
    	 l1sp.vchg_mode = mode;
    	 SPE_CustomProcess(KAL_TRUE,0,0,0);	
    }
    else if(AM_IsSpeechOn() && !process_on)
    {
    	 l1sp.vchg_mode = mode;	
    	 SPE_CustomProcess(KAL_TRUE,0,0,0);    	 
    }
    else
    {
    	 l1sp.vchg_mode = mode;	
    }	
    return KAL_TRUE;
}

SPH_VOICE_CHANGER_MODE L1SP_GetVoiceChangerMode(void)
{
    return l1sp.vchg_mode;
}
#endif