1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636 5637 5638 5639 5640 5641 5642 5643 5644 5645 5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5656 5657 5658 5659 5660 5661 5662 5663 5664 5665 5666 5667 5668 5669 5670 5671 5672 5673 5674 5675 5676 5677 5678 5679 5680 5681 5682 5683 5684 5685 5686 5687 5688 5689 5690 5691 5692 5693 5694 5695 5696 5697 5698 5699 5700 5701 5702 5703 5704 5705 5706 5707 5708 5709 5710 5711 5712 5713 5714 5715 5716 5717 5718 5719 5720 5721 5722 5723 5724 5725 5726 5727 5728 5729 5730 5731 5732 5733 5734 5735 5736 5737 5738 5739 5740 5741 5742 5743 5744 5745 5746 5747 5748 5749 5750 5751 5752 5753 5754 5755 5756 5757 5758 5759 5760 5761 5762 5763 5764 5765 5766 5767 5768 5769 5770 5771 5772 5773 5774 5775 5776 5777 5778 5779 5780 5781 5782 5783 5784 5785 5786 5787 5788 5789 5790 5791 5792 5793 5794 5795 5796 5797 5798 5799 5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820 5821 5822 5823 5824 5825 5826 5827 5828 5829 5830 5831 5832 5833 5834 5835 5836 5837 5838 5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856 5857 5858 5859 5860 5861 5862 5863 5864 5865 5866 5867 5868
|
/*
* Snd_fx.cpp
* -----------
* Purpose: Processing of pattern commands, song length calculation...
* Notes : This needs some heavy refactoring.
* I thought of actually adding an effect interface class. Every pattern effect
* could then be moved into its own class that inherits from the effect interface.
* If effect handling differs severly between module formats, every format would have
* its own class for that effect. Then, a call chain of effect classes could be set up
* for each format, since effects cannot be processed in the same order in all formats.
* Authors: Olivier Lapicque
* OpenMPT Devs
* The OpenMPT source code is released under the BSD license. Read LICENSE for more details.
*/
#include "stdafx.h"
#include "Sndfile.h"
#include "mod_specifications.h"
#ifdef MODPLUG_TRACKER
#include "../mptrack/Moddoc.h"
#endif // MODPLUG_TRACKER
#include "tuning.h"
#include "Tables.h"
#include "modsmp_ctrl.h" // For updating the loop wraparound data with the invert loop effect
#include "plugins/PlugInterface.h"
OPENMPT_NAMESPACE_BEGIN
// Formats which have 7-bit (0...128) instead of 6-bit (0...64) global volume commands, or which are imported to this range (mostly formats which are converted to IT internally)
#ifdef MODPLUG_TRACKER
#define GLOBALVOL_7BIT_FORMATS_EXT (MOD_TYPE_MT2)
#else
#define GLOBALVOL_7BIT_FORMATS_EXT Enum<MODTYPE>::value_type()
#endif // MODPLUG_TRACKER
#define GLOBALVOL_7BIT_FORMATS (MOD_TYPE_IT | MOD_TYPE_MPT | MOD_TYPE_IMF | MOD_TYPE_J2B | MOD_TYPE_MID | MOD_TYPE_AMS | MOD_TYPE_AMS2 | MOD_TYPE_DBM | MOD_TYPE_PTM | MOD_TYPE_MDL | GLOBALVOL_7BIT_FORMATS_EXT)
// Compensate frequency slide LUTs depending on whether we are handling periods or frequency - "up" and "down" in function name are seen from frequency perspective.
static uint32 GetLinearSlideDownTable (const CSoundFile *sndFile, uint32 i) { MPT_ASSERT(i < CountOf(LinearSlideDownTable)); return sndFile->m_playBehaviour[kHertzInLinearMode] ? LinearSlideDownTable[i] : LinearSlideUpTable[i]; }
static uint32 GetLinearSlideUpTable (const CSoundFile *sndFile, uint32 i) { MPT_ASSERT(i < CountOf(LinearSlideDownTable)); return sndFile->m_playBehaviour[kHertzInLinearMode] ? LinearSlideUpTable[i] : LinearSlideDownTable[i]; }
static uint32 GetFineLinearSlideDownTable(const CSoundFile *sndFile, uint32 i) { MPT_ASSERT(i < CountOf(FineLinearSlideDownTable)); return sndFile->m_playBehaviour[kHertzInLinearMode] ? FineLinearSlideDownTable[i] : FineLinearSlideUpTable[i]; }
static uint32 GetFineLinearSlideUpTable (const CSoundFile *sndFile, uint32 i) { MPT_ASSERT(i < CountOf(FineLinearSlideDownTable)); return sndFile->m_playBehaviour[kHertzInLinearMode] ? FineLinearSlideUpTable[i] : FineLinearSlideDownTable[i]; }
////////////////////////////////////////////////////////////
// Length
// Memory class for GetLength() code
class GetLengthMemory
{
protected:
const CSoundFile &sndFile;
public:
CSoundFile::PlayState state;
struct ChnSettings
{
double patLoop;
CSoundFile::samplecount_t patLoopSmp;
ROWINDEX patLoopStart;
uint32 ticksToRender; // When using sample sync, we still need to render this many ticks
bool incChanged; // When using sample sync, note frequency has changed
uint8 vol;
void Reset()
{
patLoop = 0.0;
patLoopSmp = 0;
patLoopStart = 0;
vol = 0xFF;
}
};
#ifndef NO_PLUGINS
typedef std::map<std::pair<ModCommand::INSTR, uint16>, uint16> PlugParamMap;
PlugParamMap plugParams;
#endif
std::vector<ChnSettings> chnSettings;
double elapsedTime;
static const uint32 IGNORE_CHANNEL = uint32_max;
GetLengthMemory(const CSoundFile &sf)
: sndFile(sf)
, state(sf.m_PlayState)
, chnSettings(sf.GetNumChannels())
{
Reset();
}
void Reset()
{
plugParams.clear();
elapsedTime = 0.0;
state.m_lTotalSampleCount = 0;
state.m_nMusicSpeed = sndFile.m_nDefaultSpeed;
state.m_nMusicTempo = sndFile.m_nDefaultTempo;
state.m_nGlobalVolume = sndFile.m_nDefaultGlobalVolume;
for(CHANNELINDEX chn = 0; chn < sndFile.GetNumChannels(); chn++)
{
chnSettings[chn].Reset();
state.Chn[chn].Reset(ModChannel::resetTotal, sndFile, chn);
state.Chn[chn].nOldGlobalVolSlide = 0;
state.Chn[chn].nOldChnVolSlide = 0;
state.Chn[chn].nNote = state.Chn[chn].nNewNote = state.Chn[chn].nLastNote = NOTE_NONE;
}
}
// Increment playback position of sample and envelopes on a channel
void RenderChannel(CHANNELINDEX channel, uint32 tickDuration, uint32 portaStart = uint32_max)
{
ModChannel &chn = state.Chn[channel];
uint32 numTicks = chnSettings[channel].ticksToRender;
if(numTicks == IGNORE_CHANNEL || numTicks == 0 || (chn.nInc == 0 && !chnSettings[channel].incChanged) || chn.pModSample == nullptr)
{
return;
}
const SmpLength sampleEnd = chn.dwFlags[CHN_LOOP] ? chn.nLoopEnd : chn.nLength;
const SmpLength loopLength = chn.nLoopEnd - chn.nLoopStart;
const bool itEnvMode = sndFile.m_playBehaviour[kITEnvelopePositionHandling];
const bool updatePitchEnv = (chn.PitchEnv.flags & (ENV_ENABLED | ENV_FILTER)) == ENV_ENABLED;
bool stopNote = false;
int32 inc = chn.nInc * tickDuration;
if(chn.dwFlags[CHN_PINGPONGFLAG]) inc = -inc;
for(uint32 i = 0; i < numTicks; i++)
{
bool updateInc = (chn.PitchEnv.flags & (ENV_ENABLED | ENV_FILTER)) == ENV_ENABLED;
if(i >= portaStart)
{
const ModCommand *p = sndFile.Patterns[state.m_nPattern].GetpModCommand(state.m_nRow, channel);
if(p->command == CMD_TONEPORTAMENTO) sndFile.TonePortamento(&chn, p->param);
else if(p->command == CMD_TONEPORTAVOL) sndFile.TonePortamento(&chn, 0);
if(p->volcmd == VOLCMD_TONEPORTAMENTO)
{
uint32 param = p->vol;
if(sndFile.GetType() & (MOD_TYPE_IT | MOD_TYPE_MPT | MOD_TYPE_AMS | MOD_TYPE_AMS2 | MOD_TYPE_DMF | MOD_TYPE_DBM | MOD_TYPE_IMF | MOD_TYPE_PSM | MOD_TYPE_J2B | MOD_TYPE_ULT | MOD_TYPE_OKT | MOD_TYPE_MT2 | MOD_TYPE_MDL))
{
param = ImpulseTrackerPortaVolCmd[param & 0x0F];
} else
{
// Close enough. Do not bother with idiosyncratic FT2 behaviour here.
param <<= 4;
}
sndFile.TonePortamento(&chn, param);
}
updateInc = true;
}
int period = chn.nPeriod;
if(itEnvMode) sndFile.IncrementEnvelopePositions(&chn);
if(updatePitchEnv)
{
sndFile.ProcessPitchFilterEnvelope(&chn, period);
updateInc = true;
}
if(!itEnvMode) sndFile.IncrementEnvelopePositions(&chn);
int vol = 0;
sndFile.ProcessInstrumentFade(&chn, vol);
if(updateInc || chnSettings[channel].incChanged)
{
chn.nInc = sndFile.GetChannelIncrement(&chn, period, 0);
chnSettings[channel].incChanged = false;
inc = chn.nInc * tickDuration;
if(chn.dwFlags[CHN_PINGPONGFLAG]) inc = -inc;
}
chn.nPosLo += inc;
chn.nPos += ((int32)chn.nPosLo >> 16);
chn.nPosLo &= 0xFFFF;
if(chn.nPos >= sampleEnd)
{
if(chn.dwFlags[CHN_LOOP])
{
// We exceeded the sample loop, go back to loop start.
if(chn.dwFlags[CHN_PINGPONGLOOP])
{
// Ping-pong loops are not supported for now.
stopNote = true;
break;
} else
{
if(chn.nPos >= chn.nLoopEnd + loopLength)
{
const SmpLength overshoot = chn.nPos - chn.nLoopEnd;
chn.nPos -= (overshoot / loopLength) * loopLength;
}
while(chn.nPos >= chn.nLoopEnd)
{
chn.nPos -= loopLength;
}
}
} else
{
// Past sample end.
stopNote = true;
break;
}
}
}
if(stopNote)
{
chn.Stop();
chn.nPortamentoDest = 0;
}
chnSettings[channel].ticksToRender = 0;
}
};
// Get mod length in various cases. Parameters:
// [in] adjustMode: See enmGetLengthResetMode for possible adjust modes.
// [in] target: Time or position target which should be reached, or no target to get length of the first sub song. Use GetLengthTarget::StartPos to also specify a position from where the seeking should begin.
// [out] See definition of type GetLengthType for the returned values.
std::vector<GetLengthType> CSoundFile::GetLength(enmGetLengthResetMode adjustMode, GetLengthTarget target)
//--------------------------------------------------------------------------------------------------------
{
std::vector<GetLengthType> results;
GetLengthType retval;
retval.startOrder = target.startOrder;
retval.startRow = target.startRow;
// Are we trying to reach a certain pattern position?
const bool hasSearchTarget = target.mode != GetLengthTarget::NoTarget;
const bool adjustSamplePos = (adjustMode & eAdjustSamplePositions) == eAdjustSamplePositions;
SEQUENCEINDEX sequence = target.sequence;
if(sequence > Order.GetNumSequences()) sequence = Order.GetCurrentSequenceIndex();
const ModSequence &orderList = Order.GetSequence(sequence);
GetLengthMemory memory(*this);
// Temporary visited rows vector (so that GetLength() won't interfere with the player code if the module is playing at the same time)
RowVisitor visitedRows(*this, sequence);
memory.state.m_nNextRow = memory.state.m_nRow = target.startRow;
memory.state.m_nNextOrder = memory.state.m_nCurrentOrder = target.startOrder;
// Fast LUTs for commands that are too weird / complicated / whatever to emulate in sample position adjust mode.
std::bitset<MAX_EFFECTS> forbiddenCommands;
std::bitset<MAX_VOLCMDS> forbiddenVolCommands;
if(adjustSamplePos)
{
forbiddenCommands.set(CMD_ARPEGGIO); forbiddenCommands.set(CMD_PORTAMENTOUP);
forbiddenCommands.set(CMD_PORTAMENTODOWN); forbiddenCommands.set(CMD_XFINEPORTAUPDOWN);
forbiddenCommands.set(CMD_NOTESLIDEUP); forbiddenCommands.set(CMD_NOTESLIDEUPRETRIG);
forbiddenCommands.set(CMD_NOTESLIDEDOWN); forbiddenCommands.set(CMD_NOTESLIDEDOWNRETRIG);
forbiddenVolCommands.set(VOLCMD_PORTAUP); forbiddenVolCommands.set(VOLCMD_PORTADOWN);
forbiddenVolCommands.set(VOLCMD_VOLSLIDEUP); forbiddenVolCommands.set(VOLCMD_VOLSLIDEDOWN);
forbiddenVolCommands.set(VOLCMD_FINEVOLUP); forbiddenVolCommands.set(VOLCMD_FINEVOLDOWN);
// Optimize away channels for which it's pointless to adjust sample positions
for(CHANNELINDEX i = 0; i < GetNumChannels(); i++)
{
if(ChnSettings[i].dwFlags[CHN_MUTE]) memory.chnSettings[i].ticksToRender = GetLengthMemory::IGNORE_CHANNEL;
}
if(target.mode == GetLengthTarget::SeekPosition && target.pos.order < orderList.GetLength())
{
// If we know where to seek, we can directly rule out any channels on which a new note would be triggered right at the start.
const PATTERNINDEX seekPat = orderList[target.pos.order];
if(Patterns.IsValidPat(seekPat) && Patterns[seekPat].IsValidRow(target.pos.row))
{
const ModCommand *m = Patterns[seekPat].GetRow(target.pos.row);
for(CHANNELINDEX i = 0; i < GetNumChannels(); i++, m++)
{
if(m->note == NOTE_NOTECUT || m->note == NOTE_KEYOFF || (m->note == NOTE_FADE && GetNumInstruments())
|| (m->IsNote() && !m->IsPortamento()))
{
memory.chnSettings[i].ticksToRender = GetLengthMemory::IGNORE_CHANNEL;
}
}
}
}
}
// If samples are being synced, force them to resync if tick duration changes
uint32 oldTickDuration = 0;
for (;;)
{
// Time target reached.
if(target.mode == GetLengthTarget::SeekSeconds && memory.elapsedTime >= target.time)
{
retval.targetReached = true;
break;
}
uint32 rowDelay = 0, tickDelay = 0;
memory.state.m_nRow = memory.state.m_nNextRow;
memory.state.m_nCurrentOrder = memory.state.m_nNextOrder;
if(memory.state.m_nCurrentOrder >= orderList.size())
{
memory.state.m_nCurrentOrder = orderList.GetRestartPos();
break;
}
// Check if pattern is valid
memory.state.m_nPattern = orderList[memory.state.m_nCurrentOrder];
bool positionJumpOnThisRow = false;
bool patternBreakOnThisRow = false;
bool patternLoopEndedOnThisRow = false, patternLoopStartedOnThisRow = false;
if(memory.state.m_nPattern == orderList.GetIgnoreIndex() && target.mode == GetLengthTarget::SeekPosition && memory.state.m_nCurrentOrder == target.pos.order)
{
// Early test: Target is inside +++ pattern
retval.targetReached = true;
break;
}
while(memory.state.m_nPattern >= Patterns.Size())
{
// End of song?
if((memory.state.m_nPattern == orderList.GetInvalidPatIndex()) || (memory.state.m_nCurrentOrder >= orderList.size()))
{
if(memory.state.m_nCurrentOrder == orderList.GetRestartPos())
break;
else
memory.state.m_nCurrentOrder = orderList.GetRestartPos();
} else
{
memory.state.m_nCurrentOrder++;
}
memory.state.m_nPattern = (memory.state.m_nCurrentOrder < orderList.size()) ? orderList[memory.state.m_nCurrentOrder] : orderList.GetInvalidPatIndex();
memory.state.m_nNextOrder = memory.state.m_nCurrentOrder;
if((!Patterns.IsValidPat(memory.state.m_nPattern)) && visitedRows.IsVisited(memory.state.m_nCurrentOrder, 0, true))
{
if(!hasSearchTarget || !visitedRows.GetFirstUnvisitedRow(memory.state.m_nNextOrder, memory.state.m_nNextRow, true))
{
// We aren't searching for a specific row, or we couldn't find any more unvisited rows.
break;
} else
{
// We haven't found the target row yet, but we found some other unplayed row... continue searching from here.
retval.duration = memory.elapsedTime;
results.push_back(retval);
retval.startRow = memory.state.m_nNextRow;
retval.startOrder = memory.state.m_nNextOrder;
memory.Reset();
memory.state.m_nRow = memory.state.m_nNextRow;
memory.state.m_nCurrentOrder = memory.state.m_nNextOrder;
memory.state.m_nPattern = orderList[memory.state.m_nCurrentOrder];
break;
}
}
}
if(memory.state.m_nNextOrder == ORDERINDEX_INVALID)
{
// GetFirstUnvisitedRow failed, so there is nothing more to play
break;
}
// Skip non-existing patterns
if((memory.state.m_nPattern >= Patterns.Size()) || (!Patterns[memory.state.m_nPattern]))
{
// If there isn't even a tune, we should probably stop here.
if(memory.state.m_nCurrentOrder == orderList.GetRestartPos())
{
if(!hasSearchTarget || !visitedRows.GetFirstUnvisitedRow(memory.state.m_nNextOrder, memory.state.m_nNextRow, true))
{
// We aren't searching for a specific row, or we couldn't find any more unvisited rows.
break;
} else
{
// We haven't found the target row yet, but we found some other unplayed row... continue searching from here.
retval.duration = memory.elapsedTime;
results.push_back(retval);
retval.startRow = memory.state.m_nNextRow;
retval.startOrder = memory.state.m_nNextOrder;
memory.Reset();
continue;
}
}
memory.state.m_nNextOrder = memory.state.m_nCurrentOrder + 1;
continue;
}
// Should never happen
if(memory.state.m_nRow >= Patterns[memory.state.m_nPattern].GetNumRows())
memory.state.m_nRow = 0;
// Check whether target was reached.
if(target.mode == GetLengthTarget::SeekPosition && memory.state.m_nCurrentOrder == target.pos.order && memory.state.m_nRow == target.pos.row)
{
retval.targetReached = true;
break;
}
if(visitedRows.IsVisited(memory.state.m_nCurrentOrder, memory.state.m_nRow, true))
{
if(!hasSearchTarget || !visitedRows.GetFirstUnvisitedRow(memory.state.m_nNextOrder, memory.state.m_nNextRow, true))
{
// We aren't searching for a specific row, or we couldn't find any more unvisited rows.
break;
} else
{
// We haven't found the target row yet, but we found some other unplayed row... continue searching from here.
retval.duration = memory.elapsedTime;
results.push_back(retval);
retval.startRow = memory.state.m_nNextRow;
retval.startOrder = memory.state.m_nNextOrder;
memory.Reset();
continue;
}
}
retval.endOrder = memory.state.m_nCurrentOrder;
retval.endRow = memory.state.m_nRow;
// Update next position
memory.state.m_nNextRow = memory.state.m_nRow + 1;
if(memory.state.m_nNextRow >= Patterns[memory.state.m_nPattern].GetNumRows())
{
memory.state.m_nNextRow = 0;
memory.state.m_nNextOrder++;
}
// Jumped to invalid pattern row?
if(memory.state.m_nRow >= Patterns[memory.state.m_nPattern].GetNumRows())
{
memory.state.m_nRow = 0;
}
// New pattern?
if(!memory.state.m_nRow)
{
for(CHANNELINDEX chn = 0; chn < GetNumChannels(); chn++)
{
memory.chnSettings[chn].patLoop = memory.elapsedTime;
memory.chnSettings[chn].patLoopSmp = memory.state.m_lTotalSampleCount;
}
}
ModChannel *pChn = memory.state.Chn;
// For various effects, we need to know first how many ticks there are in this row.
const ModCommand *p = Patterns[memory.state.m_nPattern].GetRow(memory.state.m_nRow);
for(CHANNELINDEX nChn = 0; nChn < GetNumChannels(); nChn++, p++)
{
if(m_playBehaviour[kST3NoMutedChannels] && ChnSettings[nChn].dwFlags[CHN_MUTE]) // not even effects are processed on muted S3M channels
continue;
if(p->IsPcNote())
{
#ifndef NO_PLUGINS
if((adjustMode & eAdjust) && p->instr > 0 && p->instr <= MAX_MIXPLUGINS)
{
memory.plugParams[std::make_pair(p->instr, p->GetValueVolCol())] = p->GetValueEffectCol();
}
#endif // NO_PLUGINS
pChn[nChn].rowCommand.Clear();
continue;
}
pChn[nChn].rowCommand = *p;
switch(p->command)
{
case CMD_SPEED:
#ifdef MODPLUG_TRACKER
// FT2 appears to be decrementing the tick count before checking for zero,
// so it effectively counts down 65536 ticks with speed = 0 (song speed is a 16-bit variable in FT2)
if(GetType() == MOD_TYPE_XM && !p->param)
{
memory.state.m_nMusicSpeed = uint16_max;
}
#endif // MODPLUG_TRACKER
if(p->param > 0) memory.state.m_nMusicSpeed = p->param;
break;
case CMD_TEMPO:
if(m_playBehaviour[kMODVBlankTiming])
{
// ProTracker MODs with VBlank timing: All Fxx parameters set the tick count.
if(p->param != 0) memory.state.m_nMusicSpeed = p->param;
}
break;
case CMD_S3MCMDEX:
if((p->param & 0xF0) == 0x60)
{
// Fine Pattern Delay
tickDelay += (p->param & 0x0F);
} if((p->param & 0xF0) == 0xE0 && !rowDelay)
{
// Pattern Delay
if(!(GetType() & MOD_TYPE_S3M) || (p->param & 0x0F) != 0)
{
// While Impulse Tracker *does* count S60 as a valid row delay (and thus ignores any other row delay commands on the right),
// Scream Tracker 3 simply ignores such commands.
rowDelay = 1 + (p->param & 0x0F);
}
}
break;
case CMD_MODCMDEX:
if((p->param & 0xF0) == 0xE0)
{
// Pattern Delay
rowDelay = 1 + (p->param & 0x0F);
}
break;
}
}
if(rowDelay == 0) rowDelay = 1;
const uint32 numTicks = (memory.state.m_nMusicSpeed + tickDelay) * rowDelay;
const uint32 nonRowTicks = numTicks - rowDelay;
for(CHANNELINDEX nChn = 0; nChn < GetNumChannels(); pChn++, nChn++) if(!pChn->rowCommand.IsEmpty())
{
if(m_playBehaviour[kST3NoMutedChannels] && ChnSettings[nChn].dwFlags[CHN_MUTE]) // not even effects are processed on muted S3M channels
continue;
ModCommand::COMMAND command = pChn->rowCommand.command;
ModCommand::PARAM param = pChn->rowCommand.param;
ModCommand::NOTE note = pChn->rowCommand.note;
if (pChn->rowCommand.instr)
{
pChn->nNewIns = pChn->rowCommand.instr;
pChn->nLastNote = NOTE_NONE;
memory.chnSettings[nChn].vol = 0xFF;
}
if (pChn->rowCommand.IsNote()) pChn->nLastNote = note;
if (pChn->rowCommand.volcmd == VOLCMD_VOLUME) { memory.chnSettings[nChn].vol = pChn->rowCommand.vol; }
switch(command)
{
// Position Jump
case CMD_POSITIONJUMP:
positionJumpOnThisRow = true;
memory.state.m_nNextOrder = static_cast<ORDERINDEX>(CalculateXParam(memory.state.m_nPattern, memory.state.m_nRow, nChn));
memory.state.m_nNextPatStartRow = 0; // FT2 E60 bug
// see http://forum.openmpt.org/index.php?topic=2769.0 - FastTracker resets Dxx if Bxx is called _after_ Dxx
// Test case: PatternJump.mod
if(!patternBreakOnThisRow || (GetType() & (MOD_TYPE_MOD | MOD_TYPE_XM)))
memory.state.m_nNextRow = 0;
if (adjustMode & eAdjust)
{
pChn->nPatternLoopCount = 0;
pChn->nPatternLoop = 0;
}
break;
// Pattern Break
case CMD_PATTERNBREAK:
{
ROWINDEX row = PatternBreak(memory.state, nChn, param);
if(row != ROWINDEX_INVALID)
{
patternBreakOnThisRow = true;
memory.state.m_nNextRow = row;
if(!positionJumpOnThisRow)
{
memory.state.m_nNextOrder = memory.state.m_nCurrentOrder + 1;
}
if(adjustMode & eAdjust)
{
pChn->nPatternLoopCount = 0;
pChn->nPatternLoop = 0;
}
}
}
break;
// Set Tempo
case CMD_TEMPO:
if(!m_playBehaviour[kMODVBlankTiming])
{
TEMPO tempo(CalculateXParam(memory.state.m_nPattern, memory.state.m_nRow, nChn), 0);
if ((adjustMode & eAdjust) && (GetType() & (MOD_TYPE_S3M | MOD_TYPE_IT | MOD_TYPE_MPT)))
{
if (tempo.GetInt()) pChn->nOldTempo = static_cast<uint8>(tempo.GetInt()); else tempo.Set(pChn->nOldTempo);
}
if (tempo.GetInt() >= 0x20) memory.state.m_nMusicTempo = tempo;
else
{
// Tempo Slide
TEMPO tempoDiff((tempo.GetInt() & 0x0F) * nonRowTicks, 0);
if ((tempo.GetInt() & 0xF0) == 0x10)
{
memory.state.m_nMusicTempo += tempoDiff;
} else
{
if(tempoDiff < memory.state.m_nMusicTempo)
memory.state.m_nMusicTempo -= tempoDiff;
else
memory.state.m_nMusicTempo.Set(0);
}
}
TEMPO tempoMin = GetModSpecifications().GetTempoMin(), tempoMax = GetModSpecifications().GetTempoMax();
if(m_playBehaviour[kTempoClamp]) // clamp tempo correctly in compatible mode
{
tempoMax.Set(255);
}
Limit(memory.state.m_nMusicTempo, tempoMin, tempoMax);
}
break;
case CMD_S3MCMDEX:
switch(param & 0xF0)
{
case 0x90:
if(param <= 0x91)
{
pChn->dwFlags.set(CHN_SURROUND, param == 0x91);
}
break;
case 0xA0:
// High sample offset
pChn->nOldHiOffset = param & 0x0F;
break;
case 0xB0:
// Pattern Loop
if (param & 0x0F)
{
patternLoopEndedOnThisRow = true;
} else
{
CHANNELINDEX firstChn = nChn, lastChn = nChn;
if(GetType() == MOD_TYPE_S3M)
{
// ST3 has only one global loop memory.
firstChn = 0;
lastChn = GetNumChannels() - 1;
}
for(CHANNELINDEX c = firstChn; c <= lastChn; c++)
{
memory.chnSettings[c].patLoop = memory.elapsedTime;
memory.chnSettings[c].patLoopSmp = memory.state.m_lTotalSampleCount;
memory.chnSettings[c].patLoopStart = memory.state.m_nRow;
}
patternLoopStartedOnThisRow = true;
}
break;
}
break;
case CMD_MODCMDEX:
if ((param & 0xF0) == 0x60)
{
// Pattern Loop
if (param & 0x0F)
{
memory.state.m_nNextPatStartRow = memory.chnSettings[nChn].patLoopStart; // FT2 E60 bug
patternLoopEndedOnThisRow = true;
} else
{
patternLoopStartedOnThisRow = true;
memory.chnSettings[nChn].patLoop = memory.elapsedTime;
memory.chnSettings[nChn].patLoopSmp = memory.state.m_lTotalSampleCount;
memory.chnSettings[nChn].patLoopStart = memory.state.m_nRow;
}
}
break;
case CMD_XFINEPORTAUPDOWN:
// ignore high offset in compatible mode
if(((param & 0xF0) == 0xA0) && !m_playBehaviour[kFT2RestrictXCommand]) pChn->nOldHiOffset = param & 0x0F;
break;
}
// The following calculations are not interesting if we just want to get the song length.
if (!(adjustMode & eAdjust)) continue;
switch(command)
{
// Portamento Up/Down
case CMD_PORTAMENTOUP:
case CMD_PORTAMENTODOWN:
if (param) pChn->nOldPortaUpDown = param;
break;
// Tone-Portamento
case CMD_TONEPORTAMENTO:
if (param) pChn->nPortamentoSlide = param << 2;
break;
// Offset
case CMD_OFFSET:
if (param) pChn->oldOffset = param << 8;
break;
// Volume Slide
case CMD_VOLUMESLIDE:
case CMD_TONEPORTAVOL:
if (param) pChn->nOldVolumeSlide = param;
break;
// Set Volume
case CMD_VOLUME:
memory.chnSettings[nChn].vol = param;
break;
// Global Volume
case CMD_GLOBALVOLUME:
// ST3 applies global volume on tick 1 and does other weird things, but we won't emulate this for now.
// if((GetType() & MOD_TYPE_S3M) && memory.musicSpeed <= 1)
// {
// break;
// }
if(!(GetType() & GLOBALVOL_7BIT_FORMATS)) param <<= 1;
// IT compatibility 16. ST3 and IT ignore out-of-range values
if(param <= 128)
{
memory.state.m_nGlobalVolume = param << 1;
} else if(!(GetType() & (MOD_TYPE_IT | MOD_TYPE_MPT | MOD_TYPE_S3M)))
{
memory.state.m_nGlobalVolume = 256;
}
break;
// Global Volume Slide
case CMD_GLOBALVOLSLIDE:
if(m_playBehaviour[kPerChannelGlobalVolSlide])
{
// IT compatibility 16. Global volume slide params are stored per channel (FT2/IT)
if (param) pChn->nOldGlobalVolSlide = param; else param = pChn->nOldGlobalVolSlide;
} else
{
if (param) memory.state.Chn[0].nOldGlobalVolSlide = param; else param = memory.state.Chn[0].nOldGlobalVolSlide;
}
if (((param & 0x0F) == 0x0F) && (param & 0xF0))
{
param >>= 4;
if (!(GetType() & GLOBALVOL_7BIT_FORMATS)) param <<= 1;
memory.state.m_nGlobalVolume += param << 1;
} else if (((param & 0xF0) == 0xF0) && (param & 0x0F))
{
param = (param & 0x0F) << 1;
if (!(GetType() & GLOBALVOL_7BIT_FORMATS)) param <<= 1;
memory.state.m_nGlobalVolume -= param;
} else if (param & 0xF0)
{
param >>= 4;
param <<= 1;
if (!(GetType() & GLOBALVOL_7BIT_FORMATS)) param <<= 1;
memory.state.m_nGlobalVolume += param * nonRowTicks;
} else
{
param = (param & 0x0F) << 1;
if (!(GetType() & GLOBALVOL_7BIT_FORMATS)) param <<= 1;
memory.state.m_nGlobalVolume -= param * nonRowTicks;
}
Limit(memory.state.m_nGlobalVolume, 0, 256);
break;
case CMD_CHANNELVOLUME:
if (param <= 64) pChn->nGlobalVol = param;
break;
case CMD_CHANNELVOLSLIDE:
{
if (param) pChn->nOldChnVolSlide = param; else param = pChn->nOldChnVolSlide;
int32 volume = pChn->nGlobalVol;
if((param & 0x0F) == 0x0F && (param & 0xF0))
volume += (param >> 4); // Fine Up
else if((param & 0xF0) == 0xF0 && (param & 0x0F))
volume -= (param & 0x0F); // Fine Down
else if(param & 0x0F) // Down
volume -= (param & 0x0F) * nonRowTicks;
else // Up
volume += ((param & 0xF0) >> 4) * nonRowTicks;
Limit(volume, 0, 64);
pChn->nGlobalVol = volume;
}
break;
case CMD_PANNING8:
Panning(pChn, param, Pan8bit);
break;
case CMD_MODCMDEX:
case CMD_S3MCMDEX:
if((param & 0xF0) == 0x80)
{
Panning(pChn, (param & 0x0F), Pan4bit);
}
break;
case CMD_VIBRATOVOL:
if (param) pChn->nOldVolumeSlide = param;
param = 0;
MPT_FALLTHROUGH;
case CMD_VIBRATO:
Vibrato(pChn, param);
break;
case CMD_FINEVIBRATO:
FineVibrato(pChn, param);
break;
}
switch(pChn->rowCommand.volcmd)
{
case VOLCMD_PANNING:
Panning(pChn, pChn->rowCommand.vol, Pan6bit);
break;
case VOLCMD_VIBRATOSPEED:
// FT2 does not automatically enable vibrato with the "set vibrato speed" command
if(m_playBehaviour[kFT2VolColVibrato])
pChn->nVibratoSpeed = pChn->rowCommand.vol & 0x0F;
else
Vibrato(pChn, pChn->rowCommand.vol << 4);
break;
case VOLCMD_VIBRATODEPTH:
Vibrato(pChn, pChn->rowCommand.vol);
break;
}
}
// Interpret F00 effect in XM files as "stop song"
if(GetType() == MOD_TYPE_XM && memory.state.m_nMusicSpeed == uint16_max)
{
break;
}
memory.state.m_nCurrentRowsPerBeat = m_nDefaultRowsPerBeat;
if(Patterns[memory.state.m_nPattern].GetOverrideSignature())
{
memory.state.m_nCurrentRowsPerBeat = Patterns[memory.state.m_nPattern].GetRowsPerBeat();
}
const uint32 tickDuration = GetTickDuration(memory.state);
const uint32 rowDuration = tickDuration * numTicks;
memory.elapsedTime += static_cast<double>(rowDuration) / static_cast<double>(m_MixerSettings.gdwMixingFreq);
memory.state.m_lTotalSampleCount += rowDuration;
if(adjustSamplePos)
{
// Super experimental and dirty sample seeking
pChn = memory.state.Chn;
for(CHANNELINDEX nChn = 0; nChn < GetNumChannels(); pChn++, nChn++)
{
if(memory.chnSettings[nChn].ticksToRender == GetLengthMemory::IGNORE_CHANNEL)
continue;
uint32 startTick = 0;
const ModCommand &m = pChn->rowCommand;
uint32 paramHi = m.param >> 4, paramLo = m.param & 0x0F;
bool porta = m.command == CMD_TONEPORTAMENTO || m.command == CMD_TONEPORTAVOL || m.volcmd == VOLCMD_TONEPORTAMENTO;
bool stopNote = patternLoopStartedOnThisRow; // It's too much trouble to keep those pattern loops in sync...
if(m.instr) pChn->proTrackerOffset = 0;
if(m.IsNote())
{
if(porta && memory.chnSettings[nChn].incChanged)
{
// If there's a portamento, the current channel increment mustn't be 0 in NoteChange()
pChn->nInc = GetChannelIncrement(pChn, pChn->nPeriod, 0);
}
int32 setPan = pChn->nPan;
pChn->nNewNote = pChn->nLastNote;
if(pChn->nNewIns != 0) InstrumentChange(pChn, pChn->nNewIns, porta);
NoteChange(pChn, m.note, porta);
memory.chnSettings[nChn].incChanged = true;
if((m.command == CMD_MODCMDEX || m.command == CMD_S3MCMDEX) && (m.param & 0xF0) == 0xD0 && paramLo < numTicks)
{
startTick = paramLo;
} else if(m.command == CMD_DELAYCUT && paramHi < numTicks)
{
startTick = paramHi;
}
if(rowDelay > 1 && startTick != 0 && (GetType() & (MOD_TYPE_S3M | MOD_TYPE_IT | MOD_TYPE_MPT)))
{
startTick += (memory.state.m_nMusicSpeed + tickDelay) * (rowDelay - 1);
}
if(!porta) memory.chnSettings[nChn].ticksToRender = 0;
// Panning commands have to be re-applied after a note change with potential pan change.
if(m.command == CMD_PANNING8
|| ((m.command == CMD_MODCMDEX || m.command == CMD_S3MCMDEX) && paramHi == 0x8)
|| m.volcmd == VOLCMD_PANNING)
{
pChn->nPan = setPan;
}
if(m.command == CMD_OFFSET)
{
bool isExtended = false;
SmpLength offset = CalculateXParam(memory.state.m_nPattern, memory.state.m_nRow, nChn, &isExtended);
if(!isExtended)
{
offset <<= 8;
if(offset == 0) offset = pChn->oldOffset;
offset += static_cast<SmpLength>(pChn->nOldHiOffset) << 16;
}
SampleOffset(*pChn, offset);
} else if(m.volcmd == VOLCMD_OFFSET)
{
if(m.vol <= CountOf(pChn->pModSample->cues) && pChn->pModSample != nullptr)
{
SmpLength offset;
if(m.vol == 0)
offset = pChn->oldOffset;
else
offset = pChn->oldOffset = pChn->pModSample->cues[m.vol - 1];
SampleOffset(*pChn, offset);
}
}
}
if(m.note == NOTE_KEYOFF || m.note == NOTE_NOTECUT || (m.note == NOTE_FADE && GetNumInstruments())
|| ((m.command == CMD_MODCMDEX || m.command == CMD_S3MCMDEX) && (m.param & 0xF0) == 0xC0 && paramLo < numTicks)
|| (m.command == CMD_DELAYCUT && paramLo != 0 && startTick + paramLo < numTicks))
{
stopNote = true;
}
if(m.command == CMD_VOLUME)
{
pChn->nVolume = m.param * 4;
} else if(m.volcmd == VOLCMD_VOLUME)
{
pChn->nVolume = m.vol * 4;
}
if(pChn->pModSample && !stopNote)
{
// Check if we don't want to emulate some effect and thus stop processing.
if(m.command < MAX_EFFECTS)
{
if(forbiddenCommands[m.command])
{
stopNote = true;
} else if(m.command == CMD_MODCMDEX)
{
// Special case: Slides using extended commands
switch(m.param & 0xF0)
{
case 0x10:
case 0x20:
case 0xA0:
case 0xB0:
stopNote = true;
}
}
}
if(m.volcmd < MAX_VOLCMDS && forbiddenVolCommands[m.volcmd])
{
stopNote = true;
}
}
if(stopNote)
{
pChn->Stop();
memory.chnSettings[nChn].ticksToRender = 0;
} else
{
if(oldTickDuration != tickDuration && oldTickDuration != 0)
{
memory.RenderChannel(nChn, oldTickDuration); // Re-sync what we've got so far
}
switch(m.command)
{
case CMD_TONEPORTAVOL:
case CMD_VOLUMESLIDE:
if(m.param || (GetType() != MOD_TYPE_MOD))
{
for(uint32 i = 0; i < numTicks; i++)
{
pChn->isFirstTick = (i == 0);
VolumeSlide(pChn, m.param);
}
}
break;
case CMD_S3MCMDEX:
if(m.param == 0x9E)
{
// Play forward
memory.RenderChannel(nChn, oldTickDuration); // Re-sync what we've got so far
pChn->dwFlags.reset(CHN_PINGPONGFLAG);
} else if(m.param == 0x9F)
{
// Reverse
memory.RenderChannel(nChn, oldTickDuration); // Re-sync what we've got so far
pChn->dwFlags.set(CHN_PINGPONGFLAG);
if(!pChn->nPos && pChn->nLength && (m.IsNote() || !pChn->dwFlags[CHN_LOOP]))
{
pChn->nPos = pChn->nLength - 1;
pChn->nPosLo = 0xFFFF;
}
} else if((m.param & 0xF0) == 0x70)
{
// TODO
//ExtendedS3MCommands(nChn, param);
}
break;
}
if(porta)
{
// Portamento needs immediate syncing, as the pitch changes on each tick
uint32 portaTick = memory.chnSettings[nChn].ticksToRender + startTick + 1;
memory.chnSettings[nChn].ticksToRender += numTicks;
memory.RenderChannel(nChn, tickDuration, portaTick);
} else
{
memory.chnSettings[nChn].ticksToRender += (numTicks - startTick);
}
}
}
}
oldTickDuration = tickDuration;
// Pattern loop is not executed in FT2 if there are any position jump or pattern break commands on the same row.
// Pattern loop is not executed in IT if there are any position jump commands on the same row.
// Test case for FT2 exception: PatLoop-Jumps.xm, PatLoop-Various.xm
// Test case for IT: exception: LoopBreak.it
if(patternLoopEndedOnThisRow
&& (!m_playBehaviour[kFT2PatternLoopWithJumps] || !(positionJumpOnThisRow || patternBreakOnThisRow))
&& (!m_playBehaviour[kITPatternLoopWithJumps] || !positionJumpOnThisRow))
{
std::map<double, int> startTimes;
// This is really just a simple estimation for nested pattern loops. It should handle cases correctly where all parallel loops start and end on the same row.
// If one of them starts or ends "in between", it will most likely calculate a wrong duration.
// For S3M files, it's also way off.
pChn = memory.state.Chn;
for(CHANNELINDEX nChn = 0; nChn < GetNumChannels(); nChn++, pChn++)
{
ModCommand::COMMAND command = pChn->rowCommand.command;
ModCommand::PARAM param = pChn->rowCommand.param;
if((command == CMD_S3MCMDEX && param >= 0xB1 && param <= 0xBF)
|| (command == CMD_MODCMDEX && param >= 0x61 && param <= 0x6F))
{
const double start = memory.chnSettings[nChn].patLoop;
if(!startTimes[start]) startTimes[start] = 1;
startTimes[start] = Util::lcm<int>(startTimes[start], 1 + (param & 0x0F));
}
}
for(std::map<double, int>::iterator i = startTimes.begin(); i != startTimes.end(); i++)
{
memory.elapsedTime += (memory.elapsedTime - i->first) * (double)(i->second - 1);
for(CHANNELINDEX nChn = 0; nChn < GetNumChannels(); nChn++, pChn++)
{
if(memory.chnSettings[nChn].patLoop == i->first)
{
memory.state.m_lTotalSampleCount += (memory.state.m_lTotalSampleCount - memory.chnSettings[nChn].patLoopSmp) * (i->second - 1);
break;
}
}
}
if(GetType() == MOD_TYPE_IT)
{
// IT pattern loop start row update - at the end of a pattern loop, set pattern loop start to next row (for upcoming pattern loops with missing SB0)
pChn = memory.state.Chn;
for(CHANNELINDEX nChn = 0; nChn < GetNumChannels(); nChn++, pChn++)
{
if((pChn->rowCommand.command == CMD_S3MCMDEX && pChn->rowCommand.param >= 0xB1 && pChn->rowCommand.param <= 0xBF))
{
memory.chnSettings[nChn].patLoop = memory.elapsedTime;
memory.chnSettings[nChn].patLoopSmp = memory.state.m_lTotalSampleCount;
}
}
}
}
}
// Now advance the sample positions for sample seeking on channels that are still playing
if(adjustSamplePos)
{
for(CHANNELINDEX nChn = 0; nChn < GetNumChannels(); nChn++)
{
if(memory.chnSettings[nChn].ticksToRender != GetLengthMemory::IGNORE_CHANNEL)
{
memory.RenderChannel(nChn, oldTickDuration);
}
}
}
if(retval.targetReached || target.mode == GetLengthTarget::NoTarget)
{
retval.lastOrder = memory.state.m_nCurrentOrder;
retval.lastRow = memory.state.m_nRow;
}
retval.duration = memory.elapsedTime;
results.push_back(retval);
// Store final variables
if(adjustMode & eAdjust)
{
if(retval.targetReached || target.mode == GetLengthTarget::NoTarget)
{
// Target found, or there is no target (i.e. play whole song)...
m_PlayState = memory.state;
m_PlayState.m_nFrameDelay = m_PlayState.m_nPatternDelay = 0;
m_PlayState.m_nTickCount = Util::MaxValueOfType(m_PlayState.m_nTickCount) - 1;
m_PlayState.m_bPositionChanged = true;
for(CHANNELINDEX n = 0; n < GetNumChannels(); n++)
{
if(memory.state.Chn[n].nLastNote != NOTE_NONE)
{
m_PlayState.Chn[n].nNewNote = memory.state.Chn[n].nLastNote;
}
if(memory.chnSettings[n].vol != 0xFF && !adjustSamplePos)
{
if(memory.chnSettings[n].vol > 64) memory.chnSettings[n].vol = 64;
m_PlayState.Chn[n].nVolume = memory.chnSettings[n].vol * 4;
}
}
#ifndef NO_PLUGINS
// If there were any PC events, update plugin parameters to their latest value.
std::bitset<MAX_MIXPLUGINS> plugSetProgram;
for(GetLengthMemory::PlugParamMap::const_iterator param = memory.plugParams.begin(); param != memory.plugParams.end(); param++)
{
PLUGINDEX plug = param->first.first - 1;
IMixPlugin *plugin = m_MixPlugins[plug].pMixPlugin;
if(plugin != nullptr)
{
if(!plugSetProgram[plug])
{
// Used for bridged plugins to avoid sending out individual messages for each parameter.
plugSetProgram.set(plug);
plugin->BeginSetProgram();
}
plugin->SetParameter(param->first.second, param->second / PlugParamValue(ModCommand::maxColumnValue));
}
}
if(plugSetProgram.any())
{
for(PLUGINDEX i = 0; i < MAX_MIXPLUGINS; i++)
{
if(plugSetProgram[i])
{
m_MixPlugins[i].pMixPlugin->EndSetProgram();
}
}
}
#endif // NO_PLUGINS
} else if(adjustMode != eAdjustOnSuccess)
{
// Target not found (e.g. when jumping to a hidden sub song), reset global variables...
m_PlayState.m_nMusicSpeed = m_nDefaultSpeed;
m_PlayState.m_nMusicTempo = m_nDefaultTempo;
m_PlayState.m_nGlobalVolume = m_nDefaultGlobalVolume;
}
// When adjusting the playback status, we will also want to update the visited rows vector according to the current position.
if(sequence != Order.GetCurrentSequenceIndex())
{
Order.SetSequence(sequence);
}
visitedSongRows.Set(visitedRows);
}
return results;
}
//////////////////////////////////////////////////////////////////////////////////////////////////
// Effects
// Change sample or instrument number.
void CSoundFile::InstrumentChange(ModChannel *pChn, uint32 instr, bool bPorta, bool bUpdVol, bool bResetEnv) const
//----------------------------------------------------------------------------------------------------------------
{
if(instr >= MAX_INSTRUMENTS) return;
const ModInstrument *pIns = (instr < MAX_INSTRUMENTS) ? Instruments[instr] : nullptr;
const ModSample *pSmp = &Samples[instr];
ModCommand::NOTE note = pChn->nNewNote;
if(note == NOTE_NONE && m_playBehaviour[kITInstrWithoutNote]) return;
if(pIns != nullptr && ModCommand::IsNote(note))
{
// Impulse Tracker ignores empty slots.
// We won't ignore them if a plugin is assigned to this slot, so that VSTis still work as intended.
// Test case: emptyslot.it, PortaInsNum.it, gxsmp.it, gxsmp2.it
if(pIns->Keyboard[note - NOTE_MIN] == 0 && m_playBehaviour[kITEmptyNoteMapSlot] && !pIns->HasValidMIDIChannel())
{
pChn->pModInstrument = pIns;
return;
}
if(pIns->NoteMap[note - NOTE_MIN] > NOTE_MAX) return;
uint32 n = pIns->Keyboard[note - NOTE_MIN];
pSmp = ((n) && (n < MAX_SAMPLES)) ? &Samples[n] : nullptr;
} else if(GetNumInstruments())
{
// No valid instrument, or not a valid note.
if (note >= NOTE_MIN_SPECIAL) return;
if(m_playBehaviour[kITEmptyNoteMapSlot] && (pIns == nullptr || !pIns->HasValidMIDIChannel()))
{
// Impulse Tracker ignores empty slots.
// We won't ignore them if a plugin is assigned to this slot, so that VSTis still work as intended.
// Test case: emptyslot.it, PortaInsNum.it, gxsmp.it, gxsmp2.it
pChn->pModInstrument = nullptr;
pChn->nNewIns = 0;
return;
}
pSmp = nullptr;
}
bool returnAfterVolumeAdjust = false;
// instrumentChanged is used for IT carry-on env option
bool instrumentChanged = (pIns != pChn->pModInstrument);
const bool sampleChanged = (pChn->pModSample != nullptr) && (pSmp != pChn->pModSample);
const bool newTuning = (GetType() == MOD_TYPE_MPT && pIns && pIns->pTuning);
// Playback behavior change for MPT: With portamento don't change sample if it is in
// the same instrument as previous sample.
if(bPorta && newTuning && pIns == pChn->pModInstrument && sampleChanged)
return;
if(sampleChanged && bPorta)
{
// IT compatibility: No sample change (also within multi-sample instruments) during portamento when using Compatible Gxx.
// Test case: PortaInsNumCompat.it, PortaSampleCompat.it
if(m_playBehaviour[kITPortamentoInstrument] && m_SongFlags[SONG_ITCOMPATGXX])
{
pSmp = pChn->pModSample;
}
// Special XM hack (also applies to MOD / S3M, except when playing IT-style S3Ms, such as k_vision.s3m)
// Test case: PortaSmpChange.mod, PortaSmpChange.s3m
if((!instrumentChanged && (GetType() & (MOD_TYPE_XM | MOD_TYPE_MT2)) && pIns)
|| (GetType() & (MOD_TYPE_MOD | MOD_TYPE_PLM))
|| m_playBehaviour[kST3PortaSampleChange])
{
// FT2 doesn't change the sample in this case,
// but still uses the sample info from the old one (bug?)
returnAfterVolumeAdjust = true;
}
}
// IT Compatibility: Envelope pickup after SCx cut (but don't do this when working with plugins, or else envelope carry stops working)
// Test case: cut-carry.it
if(pChn->nInc == 0 && (GetType() & (MOD_TYPE_IT | MOD_TYPE_MPT)) && (!pIns || !pIns->HasValidMIDIChannel()))
{
instrumentChanged = true;
}
// FT2 compatibility: new instrument + portamento = ignore new instrument number, but reload old instrument settings (the world of XM is upside down...)
// And this does *not* happen if volume column portamento is used together with note delay... (handled in ProcessEffects(), where all the other note delay stuff is.)
// Test case: porta-delay.xm
if(instrumentChanged && bPorta && m_playBehaviour[kFT2PortaIgnoreInstr] && (pChn->pModInstrument != nullptr || pChn->pModSample != nullptr))
{
pIns = pChn->pModInstrument;
pSmp = pChn->pModSample;
instrumentChanged = false;
} else
{
pChn->pModInstrument = pIns;
}
// Update Volume
if (bUpdVol && (!(GetType() & (MOD_TYPE_MOD | MOD_TYPE_S3M)) || ((pSmp != nullptr && pSmp->pSample != nullptr) || pChn->HasMIDIOutput())))
{
pChn->nVolume = 0;
if(pSmp)
{
pChn->nVolume = pSmp->nVolume;
} else if(pIns && pIns->nMixPlug)
{
pChn->nVolume = pChn->GetVSTVolume();
}
}
if(returnAfterVolumeAdjust && sampleChanged && m_playBehaviour[kMODSampleSwap] && pSmp != nullptr)
{
// ProTracker applies new instrument's finetune but keeps the old sample playing.
// Test case: PortaSwapPT.mod
pChn->nFineTune = pSmp->nFineTune;
}
if(returnAfterVolumeAdjust) return;
// Instrument adjust
pChn->nNewIns = 0;
// IT Compatiblity: NNA is reset on every note change, not every instrument change (fixes s7xinsnum.it).
if (pIns && ((!m_playBehaviour[kITNNAReset] && pSmp) || pIns->nMixPlug))
pChn->nNNA = pIns->nNNA;
// Update volume
if (pIns)
{
pChn->nInsVol = pIns->nGlobalVol;
if(pSmp != nullptr)
{
pChn->nInsVol = (pSmp->nGlobalVol * pChn->nInsVol) >> 6;
}
} else if (pSmp != nullptr)
{
pChn->nInsVol = pSmp->nGlobalVol;
}
// Update panning
// FT2 compatibility: Only reset panning on instrument numbers, not notes (bUpdVol condition)
// Test case: PanMemory.xm
// IT compatibility: Sample and instrument panning is only applied on note change, not instrument change
// Test case: PanReset.it
if((bUpdVol || !(GetType() & (MOD_TYPE_XM | MOD_TYPE_MT2))) && !m_playBehaviour[kITPanningReset])
{
ApplyInstrumentPanning(pChn, pIns, pSmp);
}
// Reset envelopes
if(bResetEnv)
{
// Blurb by Storlek (from the SchismTracker code):
// Conditions experimentally determined to cause envelope reset in Impulse Tracker:
// - no note currently playing (of course)
// - note given, no portamento
// - instrument number given, portamento, compat gxx enabled
// - instrument number given, no portamento, after keyoff, old effects enabled
// If someone can enlighten me to what the logic really is here, I'd appreciate it.
// Seems like it's just a total mess though, probably to get XMs to play right.
bool reset, resetAlways;
// IT Compatibility: Envelope reset
// Test case: EnvReset.it
if(m_playBehaviour[kITEnvelopeReset])
{
const bool insNumber = (instr != 0);
reset = (!pChn->nLength
|| (insNumber && bPorta && m_SongFlags[SONG_ITCOMPATGXX])
|| (insNumber && !bPorta && pChn->dwFlags[CHN_NOTEFADE | CHN_KEYOFF] && m_SongFlags[SONG_ITOLDEFFECTS]));
// NOTE: IT2.14 with SB/GUS/etc. output is different. We are going after IT's WAV writer here.
// For SB/GUS/etc. emulation, envelope carry should only apply when the NNA isn't set to "Note Cut".
// Test case: CarryNNA.it
resetAlways = (!pChn->nFadeOutVol || instrumentChanged || pChn->dwFlags[CHN_KEYOFF]);
} else
{
reset = (!bPorta || !(GetType() & (MOD_TYPE_IT | MOD_TYPE_MPT | MOD_TYPE_DBM)) || m_SongFlags[SONG_ITCOMPATGXX]
|| !pChn->nLength || (pChn->dwFlags[CHN_NOTEFADE] && !pChn->nFadeOutVol));
resetAlways = !(GetType() & (MOD_TYPE_IT | MOD_TYPE_MPT | MOD_TYPE_DBM)) || instrumentChanged || pIns == nullptr || pChn->dwFlags[CHN_KEYOFF | CHN_NOTEFADE];
}
if(reset)
{
pChn->dwFlags.set(CHN_FASTVOLRAMP);
if(pIns != nullptr)
{
if(resetAlways)
{
pChn->ResetEnvelopes();
} else
{
if(!pIns->VolEnv.dwFlags[ENV_CARRY]) pChn->VolEnv.Reset();
if(!pIns->PanEnv.dwFlags[ENV_CARRY]) pChn->PanEnv.Reset();
if(!pIns->PitchEnv.dwFlags[ENV_CARRY]) pChn->PitchEnv.Reset();
}
}
// IT Compatibility: Autovibrato reset
if(!m_playBehaviour[kITVibratoTremoloPanbrello])
{
pChn->nAutoVibDepth = 0;
pChn->nAutoVibPos = 0;
}
} else if(pIns != nullptr && !pIns->VolEnv.dwFlags[ENV_ENABLED])
{
if(m_playBehaviour[kITPortamentoInstrument])
{
pChn->VolEnv.Reset();
} else
{
pChn->ResetEnvelopes();
}
}
}
// Invalid sample ?
if(pSmp == nullptr && (pIns == nullptr || !pIns->HasValidMIDIChannel()))
{
pChn->pModSample = nullptr;
pChn->nInsVol = 0;
return;
}
// Tone-Portamento doesn't reset the pingpong direction flag
if(bPorta && pSmp == pChn->pModSample && pSmp != nullptr)
{
// If channel length is 0, we cut a previous sample using SCx. In that case, we have to update sample length, loop points, etc...
if(GetType() & (MOD_TYPE_S3M|MOD_TYPE_IT|MOD_TYPE_MPT) && pChn->nLength != 0) return;
pChn->dwFlags.reset(CHN_KEYOFF | CHN_NOTEFADE);
pChn->dwFlags = (pChn->dwFlags & (CHN_CHANNELFLAGS | CHN_PINGPONGFLAG));
} else //if(!instrumentChanged || pChn->rowCommand.instr != 0 || !IsCompatibleMode(TRK_FASTTRACKER2)) // SampleChange.xm?
{
pChn->dwFlags.reset(CHN_KEYOFF | CHN_NOTEFADE);
// IT compatibility tentative fix: Don't change bidi loop direction when
// no sample nor instrument is changed.
if((m_playBehaviour[kITPingPongNoReset] || !(GetType() & (MOD_TYPE_IT | MOD_TYPE_MPT))) && pSmp == pChn->pModSample && !instrumentChanged)
pChn->dwFlags = (pChn->dwFlags & (CHN_CHANNELFLAGS | CHN_PINGPONGFLAG));
else
pChn->dwFlags = (pChn->dwFlags & CHN_CHANNELFLAGS);
if(pIns)
{
// Copy envelope flags (we actually only need the "enabled" and "pitch" flag)
pChn->VolEnv.flags = pIns->VolEnv.dwFlags;
pChn->PanEnv.flags = pIns->PanEnv.dwFlags;
pChn->PitchEnv.flags = pIns->PitchEnv.dwFlags;
// A cutoff frequency of 0 should not be reset just because the filter envelope is enabled.
// Test case: FilterEnvReset.it
if((pIns->PitchEnv.dwFlags & (ENV_ENABLED | ENV_FILTER)) == (ENV_ENABLED | ENV_FILTER) && !m_playBehaviour[kITFilterBehaviour])
{
if(!pChn->nCutOff) pChn->nCutOff = 0x7F;
}
if(pIns->IsCutoffEnabled()) pChn->nCutOff = pIns->GetCutoff();
if(pIns->IsResonanceEnabled()) pChn->nResonance = pIns->GetResonance();
}
}
if(pSmp == nullptr)
{
pChn->pModSample = nullptr;
pChn->nLength = 0;
return;
}
if(bPorta && pChn->nLength == 0 && (m_playBehaviour[kFT2PortaNoNote] || m_playBehaviour[kITPortaNoNote]))
{
// IT/FT2 compatibility: If the note just stopped on the previous tick, prevent it from restarting.
// Test cases: PortaJustStoppedNote.xm, PortaJustStoppedNote.it
pChn->nInc = 0;
}
pChn->pModSample = pSmp;
pChn->nLength = pSmp->nLength;
pChn->nLoopStart = pSmp->nLoopStart;
pChn->nLoopEnd = pSmp->nLoopEnd;
// ProTracker "oneshot" loops (if loop start is 0, play the whole sample once and then repeat until loop end)
if(m_playBehaviour[kMODOneShotLoops] && pChn->nLoopStart == 0) pChn->nLoopEnd = pSmp->nLength;
pChn->dwFlags |= (pSmp->uFlags & (CHN_SAMPLEFLAGS | CHN_SURROUND));
// IT Compatibility: Autovibrato reset
if(m_playBehaviour[kITVibratoTremoloPanbrello])
{
pChn->nAutoVibDepth = 0;
pChn->nAutoVibPos = 0;
}
if(newTuning)
{
pChn->nC5Speed = pSmp->nC5Speed;
pChn->m_CalculateFreq = true;
pChn->nFineTune = 0;
} else if(!bPorta || sampleChanged || !(GetType() & (MOD_TYPE_MOD | MOD_TYPE_XM)))
{
// Don't reset finetune changed by "set finetune" command.
// Test case: finetune.xm, finetune.mod
// But *do* change the finetune if we switch to a different sample, to fix
// Miranda`s axe by Jamson (jam007.xm) - this file doesn't use compatible play mode,
// so we may want to use IsCompatibleMode instead if further problems arise.
pChn->nC5Speed = pSmp->nC5Speed;
pChn->nFineTune = pSmp->nFineTune;
}
pChn->nTranspose = pSmp->RelativeTone;
// FT2 compatibility: Don't reset portamento target with new instrument numbers.
// Test case: Porta-Pickup.xm
// ProTracker does the same.
// Test case: PortaTarget.mod
if(!m_playBehaviour[kFT2PortaTargetNoReset] && GetType() != MOD_TYPE_MOD)
{
pChn->nPortamentoDest = 0;
}
pChn->m_PortamentoFineSteps = 0;
if(pChn->dwFlags[CHN_SUSTAINLOOP])
{
pChn->nLoopStart = pSmp->nSustainStart;
pChn->nLoopEnd = pSmp->nSustainEnd;
if(pChn->dwFlags[CHN_PINGPONGSUSTAIN]) pChn->dwFlags.set(CHN_PINGPONGLOOP);
pChn->dwFlags.set(CHN_LOOP);
}
if(pChn->dwFlags[CHN_LOOP] && pChn->nLoopEnd < pChn->nLength) pChn->nLength = pChn->nLoopEnd;
// Fix sample position on instrument change. This is needed for IT "on the fly" sample change.
// XXX is this actually called? In ProcessEffects(), a note-on effect is emulated if there's an on the fly sample change!
if(pChn->nPos >= pChn->nLength)
{
if((GetType() & (MOD_TYPE_IT | MOD_TYPE_MPT)))
{
pChn->nPos = pChn->nPosLo = 0;
}
}
}
void CSoundFile::NoteChange(ModChannel *pChn, int note, bool bPorta, bool bResetEnv, bool bManual) const
//------------------------------------------------------------------------------------------------------
{
if (note < NOTE_MIN) return;
const ModSample *pSmp = pChn->pModSample;
const ModInstrument *pIns = pChn->pModInstrument;
const bool newTuning = (GetType() == MOD_TYPE_MPT && pIns != nullptr && pIns->pTuning);
// save the note that's actually used, as it's necessary to properly calculate PPS and stuff
const int realnote = note;
if((pIns) && (note - NOTE_MIN < (int)CountOf(pIns->Keyboard)))
{
uint32 n = pIns->Keyboard[note - NOTE_MIN];
if((n) && (n < MAX_SAMPLES))
{
pSmp = &Samples[n];
} else if(m_playBehaviour[kITEmptyNoteMapSlot] && !pChn->HasMIDIOutput())
{
// Impulse Tracker ignores empty slots.
// We won't ignore them if a plugin is assigned to this slot, so that VSTis still work as intended.
// Test case: emptyslot.it, PortaInsNum.it, gxsmp.it, gxsmp2.it
return;
}
note = pIns->NoteMap[note-1];
}
// Key Off
if(note > NOTE_MAX)
{
// Key Off (+ Invalid Note for XM - TODO is this correct?)
if(note == NOTE_KEYOFF || !(GetType() & (MOD_TYPE_IT|MOD_TYPE_MPT)))
{
KeyOff(pChn);
} else // Invalid Note -> Note Fade
{
if(/*note == NOTE_FADE && */ GetNumInstruments())
pChn->dwFlags.set(CHN_NOTEFADE);
}
// Note Cut
if (note == NOTE_NOTECUT)
{
pChn->dwFlags.set(CHN_NOTEFADE | CHN_FASTVOLRAMP);
// IT compatibility: Stopping sample playback by setting sample increment to 0 rather than volume
// Test case: NoteOffInstr.it
if ((!(GetType() & (MOD_TYPE_IT | MOD_TYPE_MPT))) || (m_nInstruments != 0 && !m_playBehaviour[kITInstrWithNoteOff])) pChn->nVolume = 0;
if(m_playBehaviour[kITInstrWithNoteOff]) pChn->nInc = 0;
pChn->nFadeOutVol = 0;
}
// IT compatibility tentative fix: Clear channel note memory.
if(m_playBehaviour[kITClearOldNoteAfterCut])
{
pChn->nNote = pChn->nNewNote = NOTE_NONE;
}
return;
}
if(newTuning)
{
if(!bPorta || pChn->nNote == NOTE_NONE)
pChn->nPortamentoDest = 0;
else
{
pChn->nPortamentoDest = pIns->pTuning->GetStepDistance(pChn->nNote, pChn->m_PortamentoFineSteps, static_cast<CTuningBase::NOTEINDEXTYPE>(note), 0);
//Here pChn->nPortamentoDest means 'steps to slide'.
pChn->m_PortamentoFineSteps = -pChn->nPortamentoDest;
}
}
if(!bPorta && (GetType() & (MOD_TYPE_XM | MOD_TYPE_MED | MOD_TYPE_MT2)))
{
if(pSmp)
{
pChn->nTranspose = pSmp->RelativeTone;
pChn->nFineTune = pSmp->nFineTune;
}
}
// IT Compatibility: Update multisample instruments frequency even if instrument is not specified (fixes the guitars in spx-shuttledeparture.it)
// Test case: freqreset-noins.it
if(!bPorta && pSmp && m_playBehaviour[kITMultiSampleBehaviour]) pChn->nC5Speed = pSmp->nC5Speed;
if(bPorta && pChn->nInc == 0)
{
if(m_playBehaviour[kFT2PortaNoNote])
{
// FT2 Compatibility: Ignore notes with portamento if there was no note playing.
// Test case: 3xx-no-old-samp.xm
pChn->nPeriod = 0;
return;
} else if(m_playBehaviour[kITPortaNoNote])
{
// IT Compatibility: Ignore portamento command if no note was playing (e.g. if a previous note has faded out).
// Test case: Fade-Porta.it
bPorta = false;
}
}
if(GetType() & (MOD_TYPE_XM|MOD_TYPE_MT2|MOD_TYPE_MED|MOD_TYPE_MOD))
{
note += pChn->nTranspose;
// RealNote = PatternNote + RelativeTone; (0..118, 0 = C-0, 118 = A#9)
Limit(note, NOTE_MIN + 11, NOTE_MIN + 130); // 119 possible notes
} else
{
Limit(note, NOTE_MIN, NOTE_MAX);
}
if(m_playBehaviour[kITRealNoteMapping])
{
// need to memorize the original note for various effects (e.g. PPS)
pChn->nNote = static_cast<ModCommand::NOTE>(Clamp(realnote, NOTE_MIN, NOTE_MAX));
} else
{
pChn->nNote = static_cast<ModCommand::NOTE>(note);
}
pChn->m_CalculateFreq = true;
if ((!bPorta) || (GetType() & (MOD_TYPE_S3M|MOD_TYPE_IT|MOD_TYPE_MPT)))
pChn->nNewIns = 0;
uint32 period = GetPeriodFromNote(note, pChn->nFineTune, pChn->nC5Speed);
pChn->nPanbrelloOffset = 0;
// IT compatibility: Sample and instrument panning is only applied on note change, not instrument change
// Test case: PanReset.it
if(m_playBehaviour[kITPanningReset]) ApplyInstrumentPanning(pChn, pIns, pSmp);
if(bResetEnv && !bPorta)
{
pChn->nVolSwing = pChn->nPanSwing = 0;
pChn->nResSwing = pChn->nCutSwing = 0;
if(pIns)
{
// IT Compatiblity: NNA is reset on every note change, not every instrument change (fixes spx-farspacedance.it).
if(m_playBehaviour[kITNNAReset]) pChn->nNNA = pIns->nNNA;
if(!pIns->VolEnv.dwFlags[ENV_CARRY]) pChn->VolEnv.Reset();
if(!pIns->PanEnv.dwFlags[ENV_CARRY]) pChn->PanEnv.Reset();
if(!pIns->PitchEnv.dwFlags[ENV_CARRY]) pChn->PitchEnv.Reset();
// Volume Swing
if(pIns->nVolSwing)
{
pChn->nVolSwing = ((mpt::random<int8>(AccessPRNG()) * pIns->nVolSwing) / 64 + 1) * (m_playBehaviour[kITSwingBehaviour] ? pChn->nInsVol : ((pChn->nVolume + 1) / 2)) / 199;
}
// Pan Swing
if(pIns->nPanSwing)
{
pChn->nPanSwing = ((mpt::random<int8>(AccessPRNG()) * pIns->nPanSwing * 4) / 128);
if(!m_playBehaviour[kITSwingBehaviour])
{
pChn->nRestorePanOnNewNote = pChn->nPan + 1;
}
}
// Cutoff Swing
if(pIns->nCutSwing)
{
int32 d = ((int32)pIns->nCutSwing * (int32)(static_cast<int32>(mpt::random<int8>(AccessPRNG())) + 1)) / 128;
pChn->nCutSwing = (int16)((d * pChn->nCutOff + 1) / 128);
pChn->nRestoreCutoffOnNewNote = pChn->nCutOff + 1;
}
// Resonance Swing
if(pIns->nResSwing)
{
int32 d = ((int32)pIns->nResSwing * (int32)(static_cast<int32>(mpt::random<int8>(AccessPRNG())) + 1)) / 128;
pChn->nResSwing = (int16)((d * pChn->nResonance + 1) / 128);
pChn->nRestoreResonanceOnNewNote = pChn->nResonance + 1;
}
}
}
if(!pSmp) return;
if(period)
{
if((!bPorta) || (!pChn->nPeriod)) pChn->nPeriod = period;
if(!newTuning)
{
// FT2 compatibility: Don't reset portamento target with new notes.
// Test case: Porta-Pickup.xm
// ProTracker does the same.
// Test case: PortaTarget.mod
// IT compatibility: Portamento target is completely cleared with new notes.
// Test case: PortaReset.it
if(bPorta || !(m_playBehaviour[kFT2PortaTargetNoReset] || m_playBehaviour[kITClearPortaTarget] || GetType() == MOD_TYPE_MOD))
{
pChn->nPortamentoDest = period;
}
}
if(!bPorta || (!pChn->nLength && !(GetType() & MOD_TYPE_S3M)))
{
pChn->pModSample = pSmp;
pChn->nLength = pSmp->nLength;
pChn->nLoopEnd = pSmp->nLength;
pChn->nLoopStart = 0;
pChn->nPos = 0;
pChn->nPosLo = 0;
if(m_SongFlags[SONG_PT_MODE] && !pChn->rowCommand.instr)
{
pChn->nPos = pChn->proTrackerOffset;
LimitMax(pChn->nPos, pChn->nLength - 1);
} else
{
pChn->proTrackerOffset = 0;
}
pChn->dwFlags = (pChn->dwFlags & CHN_CHANNELFLAGS) | (pSmp->uFlags & (CHN_SAMPLEFLAGS | CHN_SURROUND));
pChn->dwFlags.reset(CHN_PORTAMENTO);
if(pChn->dwFlags[CHN_SUSTAINLOOP])
{
pChn->nLoopStart = pSmp->nSustainStart;
pChn->nLoopEnd = pSmp->nSustainEnd;
pChn->dwFlags.set(CHN_PINGPONGLOOP, pChn->dwFlags[CHN_PINGPONGSUSTAIN]);
pChn->dwFlags.set(CHN_LOOP);
if (pChn->nLength > pChn->nLoopEnd) pChn->nLength = pChn->nLoopEnd;
} else if(pChn->dwFlags[CHN_LOOP])
{
pChn->nLoopStart = pSmp->nLoopStart;
pChn->nLoopEnd = pSmp->nLoopEnd;
if (pChn->nLength > pChn->nLoopEnd) pChn->nLength = pChn->nLoopEnd;
}
// ProTracker "oneshot" loops (if loop start is 0, play the whole sample once and then repeat until loop end)
if(m_playBehaviour[kMODOneShotLoops] && pChn->nLoopStart == 0) pChn->nLoopEnd = pChn->nLength = pSmp->nLength;
if(pChn->dwFlags[CHN_REVERSE])
{
pChn->dwFlags.set(CHN_PINGPONGFLAG);
pChn->nPos = pChn->nLength - 1;
}
// Handle "retrigger" waveform type
if(pChn->nVibratoType < 4)
{
// IT Compatibilty: Slightly different waveform offsets (why does MPT have two different offsets here with IT old effects enabled and disabled?)
if(!m_playBehaviour[kITVibratoTremoloPanbrello] && (GetType() & (MOD_TYPE_IT | MOD_TYPE_MPT)) && !m_SongFlags[SONG_ITOLDEFFECTS])
pChn->nVibratoPos = 0x10;
else if(GetType() == MOD_TYPE_MTM)
pChn->nVibratoPos = 0x20;
else
pChn->nVibratoPos = 0;
}
// IT Compatibility: No "retrigger" waveform here
if(!m_playBehaviour[kITVibratoTremoloPanbrello] && pChn->nTremoloType < 4)
{
pChn->nTremoloPos = 0;
}
}
if(pChn->nPos >= pChn->nLength) pChn->nPos = pChn->nLoopStart;
} else
{
bPorta = false;
}
if (!bPorta
|| (!(GetType() & (MOD_TYPE_IT | MOD_TYPE_MPT | MOD_TYPE_DBM)))
|| (pChn->dwFlags[CHN_NOTEFADE] && !pChn->nFadeOutVol)
|| (m_SongFlags[SONG_ITCOMPATGXX] && pChn->rowCommand.instr != 0))
{
if((GetType() & (MOD_TYPE_IT | MOD_TYPE_MPT | MOD_TYPE_DBM)) && pChn->dwFlags[CHN_NOTEFADE] && !pChn->nFadeOutVol)
{
pChn->ResetEnvelopes();
// IT Compatibility: Autovibrato reset
if(!m_playBehaviour[kITVibratoTremoloPanbrello])
{
pChn->nAutoVibDepth = 0;
pChn->nAutoVibPos = 0;
}
pChn->dwFlags.reset(CHN_NOTEFADE);
pChn->nFadeOutVol = 65536;
}
if ((!bPorta) || (!m_SongFlags[SONG_ITCOMPATGXX]) || (pChn->rowCommand.instr))
{
if ((!(GetType() & (MOD_TYPE_XM|MOD_TYPE_MT2))) || (pChn->rowCommand.instr))
{
pChn->dwFlags.reset(CHN_NOTEFADE);
pChn->nFadeOutVol = 65536;
}
}
}
// IT compatibility: Don't reset key-off flag on porta notes unless Compat Gxx is enabled
// Test case: Off-Porta.it, Off-Porta-CompatGxx.it
if(m_playBehaviour[kITDontResetNoteOffOnPorta] && bPorta && (!m_SongFlags[SONG_ITCOMPATGXX] || pChn->rowCommand.instr == 0))
pChn->dwFlags.reset(CHN_EXTRALOUD);
else
pChn->dwFlags.reset(CHN_EXTRALOUD | CHN_KEYOFF);
// Enable Ramping
if(!bPorta)
{
pChn->nLeftVU = pChn->nRightVU = 0xFF;
pChn->dwFlags.reset(CHN_FILTER);
pChn->dwFlags.set(CHN_FASTVOLRAMP);
// IT compatibility 15. Retrigger is reset in RetrigNote (Tremor doesn't store anything here, so we just don't reset this as well)
if(!m_playBehaviour[kITRetrigger] && !m_playBehaviour[kITTremor])
{
// FT2 compatibility: Retrigger is reset in RetrigNote, tremor in ProcessEffects
if(!m_playBehaviour[kFT2Retrigger] && !m_playBehaviour[kFT2Tremor])
{
pChn->nRetrigCount = 0;
pChn->nTremorCount = 0;
}
}
if(bResetEnv)
{
pChn->nAutoVibDepth = 0;
pChn->nAutoVibPos = 0;
}
pChn->rightVol = pChn->leftVol = 0;
bool useFilter = !m_SongFlags[SONG_MPTFILTERMODE];
// Setup Initial Filter for this note
if(pIns)
{
if(pIns->IsResonanceEnabled())
{
pChn->nResonance = pIns->GetResonance();
useFilter = true;
}
if(pIns->IsCutoffEnabled())
{
pChn->nCutOff = pIns->GetCutoff();
useFilter = true;
}
if(useFilter && (pIns->nFilterMode != FLTMODE_UNCHANGED))
{
pChn->nFilterMode = pIns->nFilterMode;
}
} else
{
pChn->nVolSwing = pChn->nPanSwing = 0;
pChn->nCutSwing = pChn->nResSwing = 0;
}
if((pChn->nCutOff < 0x7F || m_playBehaviour[kITFilterBehaviour]) && useFilter)
{
SetupChannelFilter(pChn, true);
}
}
// Special case for MPT
if (bManual) pChn->dwFlags.reset(CHN_MUTE);
if((pChn->dwFlags[CHN_MUTE] && (m_MixerSettings.MixerFlags & SNDMIX_MUTECHNMODE))
|| (pChn->pModSample != nullptr && pChn->pModSample->uFlags[CHN_MUTE] && !bManual)
|| (pChn->pModInstrument != nullptr && pChn->pModInstrument->dwFlags[INS_MUTE] && !bManual))
{
if (!bManual) pChn->nPeriod = 0;
}
}
// Apply sample or instrumernt panning
void CSoundFile::ApplyInstrumentPanning(ModChannel *pChn, const ModInstrument *instr, const ModSample *smp) const
//---------------------------------------------------------------------------------------------------------------
{
int32 newPan = int32_min;
// Default instrument panning
if(instr != nullptr && instr->dwFlags[INS_SETPANNING])
newPan = instr->nPan;
// Default sample panning
if(smp != nullptr && smp->uFlags[CHN_PANNING])
newPan = smp->nPan;
if(newPan != int32_min)
{
pChn->nPan = newPan;
// IT compatibility: Sample and instrument panning overrides channel surround status.
// Test case: SmpInsPanSurround.it
if(m_playBehaviour[kPanOverride] && !m_SongFlags[SONG_SURROUNDPAN])
{
pChn->dwFlags.reset(CHN_SURROUND);
}
}
}
CHANNELINDEX CSoundFile::GetNNAChannel(CHANNELINDEX nChn) const
//-------------------------------------------------------------
{
const ModChannel *pChn = &m_PlayState.Chn[nChn];
// Check for empty channel
const ModChannel *pi = &m_PlayState.Chn[m_nChannels];
for (CHANNELINDEX i = m_nChannels; i < MAX_CHANNELS; i++, pi++) if (!pi->nLength) return i;
if (!pChn->nFadeOutVol) return 0;
// All channels are used: check for lowest volume
CHANNELINDEX result = 0;
uint32 vol = (1u << (14 + 9)) / 4u; // 25%
uint32 envpos = uint32_max;
const ModChannel *pj = &m_PlayState.Chn[m_nChannels];
for (CHANNELINDEX j = m_nChannels; j < MAX_CHANNELS; j++, pj++)
{
if (!pj->nFadeOutVol) return j;
// Use a combination of real volume [14 bit] (which includes volume envelopes, but also potentially global volume) and note volume [9 bit].
// Rationale: We need volume envelopes in case e.g. all NNA channels are playing at full volume but are looping on a 0-volume envelope node.
// But if global volume is not applied to master and the global volume temporarily drops to 0, we would kill arbitrary channels. Hence, add the note volume as well.
uint32 v = (pj->nRealVolume << 9) | pj->nVolume;
if(pj->dwFlags[CHN_LOOP]) v >>= 1;
if ((v < vol) || ((v == vol) && (pj->VolEnv.nEnvPosition > envpos)))
{
envpos = pj->VolEnv.nEnvPosition;
vol = v;
result = j;
}
}
return result;
}
CHANNELINDEX CSoundFile::CheckNNA(CHANNELINDEX nChn, uint32 instr, int note, bool forceCut)
//-----------------------------------------------------------------------------------------
{
CHANNELINDEX nnaChn = CHANNELINDEX_INVALID;
ModChannel *pChn = &m_PlayState.Chn[nChn];
const ModInstrument *pIns = nullptr;
if(!ModCommand::IsNote(static_cast<ModCommand::NOTE>(note)))
{
return nnaChn;
}
// Always NNA cut - using
if((!(GetType() & (MOD_TYPE_IT | MOD_TYPE_MPT | MOD_TYPE_MT2)) || !m_nInstruments || forceCut) && !pChn->HasMIDIOutput())
{
if(!pChn->nLength || pChn->dwFlags[CHN_MUTE] || !(pChn->rightVol | pChn->leftVol))
{
return CHANNELINDEX_INVALID;
}
nnaChn = GetNNAChannel(nChn);
if(!nnaChn) return CHANNELINDEX_INVALID;
ModChannel &chn = m_PlayState.Chn[nnaChn];
// Copy Channel
chn = *pChn;
chn.dwFlags.reset(CHN_VIBRATO | CHN_TREMOLO | CHN_MUTE | CHN_PORTAMENTO);
chn.nPanbrelloOffset = 0;
chn.nMasterChn = nChn + 1;
chn.nCommand = CMD_NONE;
chn.rowCommand.Clear();
// Cut the note
chn.nFadeOutVol = 0;
chn.dwFlags.set(CHN_NOTEFADE | CHN_FASTVOLRAMP);
// Stop this channel
pChn->nLength = pChn->nPos = pChn->nPosLo = 0;
pChn->nROfs = pChn->nLOfs = 0;
pChn->rightVol = pChn->leftVol = 0;
return nnaChn;
}
if(instr >= MAX_INSTRUMENTS) instr = 0;
const ModSample *pSample = pChn->pModSample;
// If no instrument is given, assume previous instrument to still be valid.
// Test case: DNA-NoInstr.it
pIns = instr > 0 ? Instruments[instr] : pChn->pModInstrument;
if(pIns != nullptr)
{
uint32 n = pIns->Keyboard[note - NOTE_MIN];
note = pIns->NoteMap[note - NOTE_MIN];
if ((n) && (n < MAX_SAMPLES))
{
pSample = &Samples[n];
} else if(m_playBehaviour[kITEmptyNoteMapSlot] && !pIns->HasValidMIDIChannel())
{
// Impulse Tracker ignores empty slots.
// We won't ignore them if a plugin is assigned to this slot, so that VSTis still work as intended.
// Test case: emptyslot.it, PortaInsNum.it, gxsmp.it, gxsmp2.it
return CHANNELINDEX_INVALID;
}
}
ModChannel *p = pChn;
//if (!pIns) return;
if (pChn->dwFlags[CHN_MUTE]) return CHANNELINDEX_INVALID;
bool applyDNAtoPlug; //rewbs.VSTiNNA
for(CHANNELINDEX i = nChn; i < MAX_CHANNELS; p++, i++)
if(i >= m_nChannels || p == pChn)
{
applyDNAtoPlug = false; //rewbs.VSTiNNA
if((p->nMasterChn == nChn + 1 || p == pChn) && p->pModInstrument != nullptr)
{
bool bOk = false;
// Duplicate Check Type
switch(p->pModInstrument->nDCT)
{
// Note
case DCT_NOTE:
if(note && p->nNote == note && pIns == p->pModInstrument) bOk = true;
if(pIns && pIns->nMixPlug) applyDNAtoPlug = true; //rewbs.VSTiNNA
break;
// Sample
case DCT_SAMPLE:
if(pSample != nullptr && pSample == p->pModSample) bOk = true;
break;
// Instrument
case DCT_INSTRUMENT:
if(pIns == p->pModInstrument) bOk = true;
//rewbs.VSTiNNA
if(pIns && pIns->nMixPlug) applyDNAtoPlug = true;
break;
// Plugin
case DCT_PLUGIN:
if(pIns && (pIns->nMixPlug) && (pIns->nMixPlug == p->pModInstrument->nMixPlug))
{
applyDNAtoPlug = true;
bOk = true;
}
//end rewbs.VSTiNNA
break;
}
// Duplicate Note Action
if (bOk)
{
#ifndef NO_PLUGINS
if (applyDNAtoPlug && p->nNote != NOTE_NONE)
{
switch(p->pModInstrument->nDNA)
{
case DNA_NOTECUT:
case DNA_NOTEOFF:
case DNA_NOTEFADE:
// Switch off duplicated note played on this plugin
SendMIDINote(i, p->nNote + NOTE_MAX_SPECIAL, 0);
break;
}
}
#endif // NO_PLUGINS
switch(p->pModInstrument->nDNA)
{
// Cut
case DNA_NOTECUT:
KeyOff(p);
p->nVolume = 0;
break;
// Note Off
case DNA_NOTEOFF:
KeyOff(p);
break;
// Note Fade
case DNA_NOTEFADE:
p->dwFlags.set(CHN_NOTEFADE);
break;
}
if(!p->nVolume)
{
p->nFadeOutVol = 0;
p->dwFlags.set(CHN_NOTEFADE | CHN_FASTVOLRAMP);
}
}
}
}
// Do we need to apply New/Duplicate Note Action to a VSTi?
bool applyNNAtoPlug = false;
#ifndef NO_PLUGINS
IMixPlugin *pPlugin = nullptr;
if(pChn->HasMIDIOutput() && ModCommand::IsNote(pChn->nNote)) // instro sends to a midi chan
{
PLUGINDEX nPlugin = GetBestPlugin(nChn, PrioritiseInstrument, RespectMutes);
if(nPlugin > 0 && nPlugin <= MAX_MIXPLUGINS)
{
pPlugin = m_MixPlugins[nPlugin-1].pMixPlugin;
if(pPlugin)
{
// apply NNA to this Plug iff this plug is currently playing a note on this tracking chan
// (and if it is playing a note, we know that would be the last note played on this chan).
ModCommand::NOTE note = pChn->nNote;
// Caution: When in compatible mode, ModChannel::nNote stores the "real" note, not the mapped note!
if(m_playBehaviour[kITRealNoteMapping] && note < CountOf(p->pModInstrument->NoteMap))
{
note = p->pModInstrument->NoteMap[note - 1];
}
applyNNAtoPlug = pPlugin->IsNotePlaying(note, GetBestMidiChannel(nChn), nChn);
}
}
}
#endif // NO_PLUGINS
// New Note Action
//if ((pChn->nVolume) && (pChn->nLength))
if((pChn->nVolume != 0 && pChn->nLength != 0) || applyNNAtoPlug) //rewbs.VSTiNNA
{
nnaChn = GetNNAChannel(nChn);
if(nnaChn != 0)
{
ModChannel *p = &m_PlayState.Chn[nnaChn];
// Copy Channel
*p = *pChn;
p->dwFlags.reset(CHN_VIBRATO | CHN_TREMOLO | CHN_PORTAMENTO);
p->nPanbrelloOffset = 0;
p->nMasterChn = nChn < GetNumChannels() ? nChn + 1 : 0;
p->nCommand = CMD_NONE;
#ifndef NO_PLUGINS
if(applyNNAtoPlug && pPlugin)
{
//Move note to the NNA channel (odd, but makes sense with DNA stuff).
//Actually a bad idea since it then become very hard to kill some notes.
//pPlugin->MoveNote(pChn->nNote, pChn->pModInstrument->nMidiChannel, nChn, n);
switch(pChn->nNNA)
{
case NNA_NOTEOFF:
case NNA_NOTECUT:
case NNA_NOTEFADE:
//switch off note played on this plugin, on this tracker channel and midi channel
//pPlugin->MidiCommand(pChn->pModInstrument->nMidiChannel, pChn->pModInstrument->nMidiProgram, pChn->nNote + NOTE_MAX_SPECIAL, 0, n);
SendMIDINote(nChn, NOTE_KEYOFF, 0);
break;
}
}
#endif // NO_PLUGINS
// Key Off the note
switch(pChn->nNNA)
{
case NNA_NOTEOFF:
KeyOff(p);
break;
case NNA_NOTECUT:
p->nFadeOutVol = 0;
case NNA_NOTEFADE:
p->dwFlags.set(CHN_NOTEFADE);
break;
}
if(!p->nVolume)
{
p->nFadeOutVol = 0;
p->dwFlags.set(CHN_NOTEFADE | CHN_FASTVOLRAMP);
}
// Stop this channel
pChn->nLength = pChn->nPos = pChn->nPosLo = 0;
pChn->nROfs = pChn->nLOfs = 0;
}
}
return nnaChn;
}
bool CSoundFile::ProcessEffects()
//-------------------------------
{
ModChannel *pChn = m_PlayState.Chn;
ROWINDEX nBreakRow = ROWINDEX_INVALID; // Is changed if a break to row command is encountered
ROWINDEX nPatLoopRow = ROWINDEX_INVALID; // Is changed if a pattern loop jump-back is executed
ORDERINDEX nPosJump = ORDERINDEX_INVALID;
// ScreamTracker 2 only updates effects on every 16th tick.
if((m_PlayState.m_nTickCount & 0x0F) != 0 && GetType() == MOD_TYPE_STM)
{
return true;
}
for(CHANNELINDEX nChn = 0; nChn < GetNumChannels(); nChn++, pChn++)
{
const uint32 tickCount = m_PlayState.m_nTickCount % (m_PlayState.m_nMusicSpeed + m_PlayState.m_nFrameDelay);
uint32 instr = pChn->rowCommand.instr;
uint32 volcmd = pChn->rowCommand.volcmd;
uint32 vol = pChn->rowCommand.vol;
uint32 cmd = pChn->rowCommand.command;
uint32 param = pChn->rowCommand.param;
bool bPorta = pChn->rowCommand.IsPortamento();
uint32 nStartTick = 0;
pChn->isFirstTick = m_SongFlags[SONG_FIRSTTICK];
pChn->dwFlags.reset(CHN_FASTVOLRAMP);
// Process parameter control note.
if(pChn->rowCommand.note == NOTE_PC)
{
#ifndef NO_PLUGINS
const PLUGINDEX plug = pChn->rowCommand.instr;
const PlugParamIndex plugparam = pChn->rowCommand.GetValueVolCol();
const PlugParamValue value = pChn->rowCommand.GetValueEffectCol() / PlugParamValue(ModCommand::maxColumnValue);
if(plug > 0 && plug <= MAX_MIXPLUGINS && m_MixPlugins[plug - 1].pMixPlugin)
m_MixPlugins[plug-1].pMixPlugin->SetParameter(plugparam, value);
#endif // NO_PLUGINS
}
// Process continuous parameter control note.
// Row data is cleared after first tick so on following
// ticks using channels m_nPlugParamValueStep to identify
// the need for parameter control. The condition cmd == 0
// is to make sure that m_nPlugParamValueStep != 0 because
// of NOTE_PCS, not because of macro.
if(pChn->rowCommand.note == NOTE_PCS || (cmd == CMD_NONE && pChn->m_plugParamValueStep != 0))
{
#ifndef NO_PLUGINS
const bool isFirstTick = m_SongFlags[SONG_FIRSTTICK];
if(isFirstTick)
pChn->m_RowPlug = pChn->rowCommand.instr;
const PLUGINDEX nPlug = pChn->m_RowPlug;
const bool hasValidPlug = (nPlug > 0 && nPlug <= MAX_MIXPLUGINS && m_MixPlugins[nPlug-1].pMixPlugin);
if(hasValidPlug)
{
if(isFirstTick)
pChn->m_RowPlugParam = ModCommand::GetValueVolCol(pChn->rowCommand.volcmd, pChn->rowCommand.vol);
const PlugParamIndex plugparam = pChn->m_RowPlugParam;
if(isFirstTick)
{
PlugParamValue targetvalue = ModCommand::GetValueEffectCol(pChn->rowCommand.command, pChn->rowCommand.param) / PlugParamValue(ModCommand::maxColumnValue);
pChn->m_plugParamTargetValue = targetvalue;
pChn->m_plugParamValueStep = (targetvalue - m_MixPlugins[nPlug-1].pMixPlugin->GetParameter(plugparam)) / float(GetNumTicksOnCurrentRow());
}
if(m_PlayState.m_nTickCount + 1 == GetNumTicksOnCurrentRow())
{ // On last tick, set parameter exactly to target value.
m_MixPlugins[nPlug-1].pMixPlugin->SetParameter(plugparam, pChn->m_plugParamTargetValue);
}
else
m_MixPlugins[nPlug-1].pMixPlugin->ModifyParameter(plugparam, pChn->m_plugParamValueStep);
}
#endif // NO_PLUGINS
}
// Apart from changing parameters, parameter control notes are intended to be 'invisible'.
// To achieve this, clearing the note data so that rest of the process sees the row as empty row.
if(ModCommand::IsPcNote(pChn->rowCommand.note))
{
pChn->ClearRowCmd();
instr = 0;
volcmd = VOLCMD_NONE;
vol = 0;
cmd = 0;
param = 0;
bPorta = false;
}
// Process Invert Loop (MOD Effect, called every row if it's active)
if(!m_SongFlags[SONG_FIRSTTICK])
{
InvertLoop(&m_PlayState.Chn[nChn]);
} else
{
if(instr) m_PlayState.Chn[nChn].nEFxOffset = 0;
}
// Process special effects (note delay, pattern delay, pattern loop)
if (cmd == CMD_DELAYCUT)
{
//:xy --> note delay until tick x, note cut at tick x+y
nStartTick = (param & 0xF0) >> 4;
const uint32 cutAtTick = nStartTick + (param & 0x0F);
NoteCut(nChn, cutAtTick, m_playBehaviour[kITSCxStopsSample]);
} else if ((cmd == CMD_MODCMDEX) || (cmd == CMD_S3MCMDEX))
{
if ((!param) && (GetType() & (MOD_TYPE_S3M|MOD_TYPE_IT|MOD_TYPE_MPT)))
param = pChn->nOldCmdEx;
else
pChn->nOldCmdEx = static_cast<ModCommand::PARAM>(param);
// Note Delay ?
if ((param & 0xF0) == 0xD0)
{
nStartTick = param & 0x0F;
if(nStartTick == 0)
{
//IT compatibility 22. SD0 == SD1
if(GetType() & (MOD_TYPE_IT | MOD_TYPE_MPT))
nStartTick = 1;
//ST3 ignores notes with SD0 completely
else if(GetType() == MOD_TYPE_S3M)
continue;
} else if(nStartTick >= (m_PlayState.m_nMusicSpeed + m_PlayState.m_nFrameDelay) && m_playBehaviour[kITOutOfRangeDelay])
{
// IT compatibility 08. Handling of out-of-range delay command.
// Additional test case: tickdelay.it
if(instr)
{
pChn->nNewIns = static_cast<ModCommand::INSTR>(instr);
}
continue;
}
} else if(m_SongFlags[SONG_FIRSTTICK])
{
// Pattern Loop ?
if((((param & 0xF0) == 0x60 && cmd == CMD_MODCMDEX)
|| ((param & 0xF0) == 0xB0 && cmd == CMD_S3MCMDEX))
&& !(m_playBehaviour[kST3NoMutedChannels] && ChnSettings[nChn].dwFlags[CHN_MUTE])) // not even effects are processed on muted S3M channels
{
ROWINDEX nloop = PatternLoop(pChn, param & 0x0F);
if (nloop != ROWINDEX_INVALID)
{
// FT2 compatibility: E6x overwrites jump targets of Dxx effects that are located left of the E6x effect.
// Test cases: PatLoop-Jumps.xm, PatLoop-Various.xm
if(nBreakRow != ROWINDEX_INVALID && m_playBehaviour[kFT2PatternLoopWithJumps])
{
nBreakRow = nloop;
}
nPatLoopRow = nloop;
}
if(GetType() == MOD_TYPE_S3M)
{
// ST3 doesn't have per-channel pattern loop memory, so spam all changes to other channels as well.
for (CHANNELINDEX i = 0; i < GetNumChannels(); i++)
{
m_PlayState.Chn[i].nPatternLoop = pChn->nPatternLoop;
m_PlayState.Chn[i].nPatternLoopCount = pChn->nPatternLoopCount;
}
}
} else if ((param & 0xF0) == 0xE0)
{
// Pattern Delay
// In Scream Tracker 3 / Impulse Tracker, only the first delay command on this row is considered.
// Test cases: PatternDelays.it, PatternDelays.s3m, PatternDelays.xm
// XXX In Scream Tracker 3, the "left" channels are evaluated before the "right" channels, which is not emulated here!
if(!(GetType() & (MOD_TYPE_S3M | MOD_TYPE_IT | MOD_TYPE_MPT)) || !m_PlayState.m_nPatternDelay)
{
if(!(GetType() & (MOD_TYPE_S3M)) || (param & 0x0F) != 0)
{
// While Impulse Tracker *does* count S60 as a valid row delay (and thus ignores any other row delay commands on the right),
// Scream Tracker 3 simply ignores such commands.
m_PlayState.m_nPatternDelay = 1 + (param & 0x0F);
}
}
}
}
}
if(GetType() == MOD_TYPE_MTM && cmd == CMD_MODCMDEX && (param & 0xF0) == 0xD0)
{
// Apparently, retrigger and note delay have the same behaviour in MultiTracker:
// They both restart the note at tick x, and if there is a note on the same row,
// this note is started on the first tick.
nStartTick = 0;
param = 0x90 | (param & 0x0F);
}
if(nStartTick != 0 && pChn->rowCommand.note == NOTE_KEYOFF && pChn->rowCommand.volcmd == VOLCMD_PANNING && m_playBehaviour[kFT2PanWithDelayedNoteOff])
{
// FT2 compatibility: If there's a delayed note off, panning commands are ignored. WTF!
// Test case: PanOff.xm
pChn->rowCommand.volcmd = VOLCMD_NONE;
}
bool triggerNote = (m_PlayState.m_nTickCount == nStartTick); // Can be delayed by a note delay effect
if((GetType() & (MOD_TYPE_S3M | MOD_TYPE_IT | MOD_TYPE_MPT)) && nStartTick > 0 && tickCount == nStartTick)
{
// IT compatibility: Delayed notes (using SDx) that are on the same row as a Row Delay effect are retriggered. Scream Tracker 3 does the same.
// Test case: PatternDelay-NoteDelay.it
triggerNote = true;
} else if(m_playBehaviour[kFT2OutOfRangeDelay] && nStartTick >= m_PlayState.m_nMusicSpeed)
{
// FT2 compatibility: Note delays greater than the song speed should be ignored.
// However, EEx pattern delay is *not* considered at all.
// Test case: DelayCombination.xm, PortaDelay.xm
triggerNote = false;
}
// IT compatibility: Tick-0 vs non-tick-0 effect distinction is always based on tick delay.
// Test case: SlideDelay.it
if(m_playBehaviour[kITFirstTickHandling])
{
pChn->isFirstTick = tickCount == nStartTick;
}
// FT2 compatibility: Note + portamento + note delay = no portamento
// Test case: PortaDelay.xm
if(m_playBehaviour[kFT2PortaDelay] && nStartTick != 0)
{
bPorta = false;
}
if(m_SongFlags[SONG_PT_MODE] && instr && !m_PlayState.m_nTickCount)
{
// Instrument number resets the stacked ProTracker offset.
// Test case: ptoffset.mod
pChn->proTrackerOffset = 0;
// ProTracker compatibility: Instrument change always happens on the first tick, even when there is a note delay.
// Test case: InstrDelay.mod
if(!triggerNote)
{
InstrumentChange(pChn, instr, true, true, false);
}
}
// Handles note/instrument/volume changes
if(triggerNote)
{
ModCommand::NOTE note = pChn->rowCommand.note;
if(instr) pChn->nNewIns = static_cast<ModCommand::INSTR>(instr);
if(ModCommand::IsNote(note) && m_playBehaviour[kFT2Transpose])
{
// Notes that exceed FT2's limit are completely ignored.
// Test case: NoteLimit.xm
int transpose = pChn->nTranspose;
if(instr && !bPorta)
{
// Refresh transpose
// Test case: NoteLimit2.xm
SAMPLEINDEX sample = SAMPLEINDEX_INVALID;
if(GetNumInstruments())
{
// Instrument mode
if(instr <= GetNumInstruments() && Instruments[instr] != nullptr)
{
sample = Instruments[instr]->Keyboard[note - NOTE_MIN];
}
} else
{
// Sample mode
sample = static_cast<SAMPLEINDEX>(instr);
}
if(sample <= GetNumSamples())
{
transpose = GetSample(sample).RelativeTone;
}
}
const int computedNote = note + transpose;
if((computedNote < NOTE_MIN + 11 || computedNote > NOTE_MIN + 130))
{
note = NOTE_NONE;
}
} else if((GetType() & (MOD_TYPE_IT | MOD_TYPE_MPT)) && GetNumInstruments() != 0 && ModCommand::IsNoteOrEmpty(static_cast<ModCommand::NOTE>(note)))
{
// IT compatibility: Invalid instrument numbers do nothing, but they are remembered for upcoming notes and do not trigger a note in that case.
// Test case: InstrumentNumberChange.it
INSTRUMENTINDEX instrToCheck = static_cast<INSTRUMENTINDEX>((instr != 0) ? instr : pChn->nOldIns);
if(instrToCheck != 0 && (instrToCheck > GetNumInstruments() || Instruments[instrToCheck] == nullptr))
{
note = NOTE_NONE;
instr = 0;
}
}
// XM: FT2 ignores a note next to a K00 effect, and a fade-out seems to be done when no volume envelope is present (not exactly the Kxx behaviour)
if(cmd == CMD_KEYOFF && param == 0 && m_playBehaviour[kFT2KeyOff])
{
note = NOTE_NONE;
instr = 0;
}
bool retrigEnv = note == NOTE_NONE && instr != 0;
// Apparently, any note number in a pattern causes instruments to recall their original volume settings - no matter if there's a Note Off next to it or whatever.
// Test cases: keyoff+instr.xm, delay.xm
bool reloadSampleSettings = (m_playBehaviour[kFT2ReloadSampleSettings] && instr != 0);
// ProTracker Compatibility: If a sample was stopped before, lone instrument numbers can retrigger it
// Test case: PTSwapEmpty.mod
bool keepInstr = (GetType() & (MOD_TYPE_IT | MOD_TYPE_MPT)) || (m_playBehaviour[kMODSampleSwap] && pChn->nInc == 0 && pChn->pModSample != nullptr && pChn->pModSample->pSample == nullptr);
// Now it's time for some FT2 crap...
if (GetType() & (MOD_TYPE_XM | MOD_TYPE_MT2))
{
// XM: Key-Off + Sample == Note Cut (BUT: Only if no instr number or volume effect is present!)
// Test case: NoteOffVolume.xm
if(note == NOTE_KEYOFF
&& ((!instr && volcmd != VOLCMD_VOLUME && cmd != CMD_VOLUME) || !m_playBehaviour[kFT2KeyOff])
&& (pChn->pModInstrument == nullptr || !pChn->pModInstrument->VolEnv.dwFlags[ENV_ENABLED]))
{
pChn->dwFlags.set(CHN_FASTVOLRAMP);
pChn->nVolume = 0;
note = NOTE_NONE;
instr = 0;
retrigEnv = false;
} else if(m_playBehaviour[kFT2RetrigWithNoteDelay] && !m_SongFlags[SONG_FIRSTTICK])
{
// FT2 Compatibility: Some special hacks for rogue note delays... (EDx with x > 0)
// Apparently anything that is next to a note delay behaves totally unpredictable in FT2. Swedish tracker logic. :)
retrigEnv = true;
// Portamento + Note Delay = No Portamento
// Test case: porta-delay.xm
bPorta = false;
if(note == NOTE_NONE)
{
// If there's a note delay but no real note, retrig the last note.
// Test case: delay2.xm, delay3.xm
note = static_cast<ModCommand::NOTE>(pChn->nNote - pChn->nTranspose);
} else if(note >= NOTE_MIN_SPECIAL)
{
// Gah! Even Note Off + Note Delay will cause envelopes to *retrigger*! How stupid is that?
// ... Well, and that is actually all it does if there's an envelope. No fade out, no nothing. *sigh*
// Test case: OffDelay.xm
note = NOTE_NONE;
keepInstr = false;
reloadSampleSettings = true;
} else
{
// Normal note
keepInstr = true;
reloadSampleSettings = true;
}
}
}
if((retrigEnv && !m_playBehaviour[kFT2ReloadSampleSettings]) || reloadSampleSettings)
{
const ModSample *oldSample = nullptr;
// Reset default volume when retriggering envelopes
if(GetNumInstruments())
{
oldSample = pChn->pModSample;
} else if (instr <= GetNumSamples())
{
// Case: Only samples are used; no instruments.
oldSample = &Samples[instr];
}
if(oldSample != nullptr)
{
pChn->nVolume = oldSample->nVolume;
if(reloadSampleSettings)
{
// Also reload panning
pChn->nPan = oldSample->nPan;
}
}
}
// FT2 compatibility: Instrument number disables tremor effect
// Test case: TremorInstr.xm, TremoRecover.xm
if(m_playBehaviour[kFT2Tremor] && instr != 0)
{
pChn->nTremorCount = 0x20;
}
if(retrigEnv) //Case: instrument with no note data.
{
//IT compatibility: Instrument with no note.
if(m_playBehaviour[kITInstrWithoutNote] || GetType() == MOD_TYPE_PLM)
{
if(GetNumInstruments())
{
// Instrument mode
if(instr < MAX_INSTRUMENTS && pChn->pModInstrument != Instruments[instr])
note = pChn->nNote;
} else
{
// Sample mode
if(instr < MAX_SAMPLES && pChn->pModSample != &Samples[instr])
note = pChn->nNote;
}
}
if (GetNumInstruments() && (GetType() & (MOD_TYPE_XM|MOD_TYPE_MT2)))
{
pChn->ResetEnvelopes();
pChn->dwFlags.set(CHN_FASTVOLRAMP);
pChn->dwFlags.reset(CHN_NOTEFADE);
pChn->nAutoVibDepth = 0;
pChn->nAutoVibPos = 0;
pChn->nFadeOutVol = 65536;
}
if (!keepInstr) instr = 0;
}
// Invalid Instrument ?
if (instr >= MAX_INSTRUMENTS) instr = 0;
// Note Cut/Off/Fade => ignore instrument
if (note >= NOTE_MIN_SPECIAL)
{
// IT compatibility: Default volume of sample is recalled if instrument number is next to a note-off.
// Test case: NoteOffInstr.it, noteoff2.it
if(m_playBehaviour[kITInstrWithNoteOff] && instr)
{
SAMPLEINDEX smp = static_cast<SAMPLEINDEX>(instr);
if(GetNumInstruments())
{
smp = 0;
if(instr <= GetNumInstruments() && Instruments[instr] != nullptr && ModCommand::IsNote(pChn->nLastNote))
{
smp = Instruments[instr]->Keyboard[pChn->nLastNote - NOTE_MIN];
}
}
if(smp > 0 && smp <= GetNumSamples())
pChn->nVolume = Samples[smp].nVolume;
}
instr = 0;
}
if(ModCommand::IsNote(note))
{
pChn->nNewNote = pChn->nLastNote = note;
// New Note Action ?
if(!bPorta)
{
CheckNNA(nChn, instr, note, false);
}
}
if(note)
{
if(pChn->nRestorePanOnNewNote > 0)
{
pChn->nPan = pChn->nRestorePanOnNewNote - 1;
pChn->nRestorePanOnNewNote = 0;
}
if(pChn->nRestoreResonanceOnNewNote > 0)
{
pChn->nResonance = pChn->nRestoreResonanceOnNewNote - 1;
pChn->nRestoreResonanceOnNewNote = 0;
}
if(pChn->nRestoreCutoffOnNewNote > 0)
{
pChn->nCutOff = pChn->nRestoreCutoffOnNewNote - 1;
pChn->nRestoreCutoffOnNewNote = 0;
}
}
// Instrument Change ?
if(instr)
{
const ModSample *oldSample = pChn->pModSample;
//const ModInstrument *oldInstrument = pChn->pModInstrument;
InstrumentChange(pChn, instr, bPorta, true);
// IT compatibility: Keep new instrument number for next instrument-less note even if sample playback is stopped
// Test case: StoppedInstrSwap.it
if(GetType() == MOD_TYPE_MOD)
{
// Test case: PortaSwapPT.mod
if(!bPorta || !m_playBehaviour[kMODSampleSwap]) pChn->nNewIns = 0;
} else
{
if(!m_playBehaviour[kITInstrWithNoteOff] || ModCommand::IsNote(note)) pChn->nNewIns = 0;
}
if(m_playBehaviour[kITPortamentoSwapResetsPos])
{
// Test cases: PortaInsNum.it, PortaSample.it
if(ModCommand::IsNote(note) && oldSample != pChn->pModSample)
{
//const bool newInstrument = oldInstrument != pChn->pModInstrument && pChn->pModInstrument->Keyboard[pChn->nNewNote - NOTE_MIN] != 0;
pChn->nPos = pChn->nPosLo = 0;
}
} else if ((GetType() & (MOD_TYPE_S3M | MOD_TYPE_IT | MOD_TYPE_MPT) && oldSample != pChn->pModSample && ModCommand::IsNote(note)))
{
// Special IT case: portamento+note causes sample change -> ignore portamento
bPorta = false;
} else if(m_playBehaviour[kMODSampleSwap] && pChn->nInc == 0)
{
// If channel was paused and is resurrected by a lone instrument number, reset the sample position.
// Test case: PTSwapEmpty.mod
pChn->nPos = pChn->nPosLo = 0;
}
}
// New Note ?
if (note)
{
if ((!instr) && (pChn->nNewIns) && (note < 0x80))
{
InstrumentChange(pChn, pChn->nNewIns, bPorta, false, !(GetType() & (MOD_TYPE_XM|MOD_TYPE_MT2)));
pChn->nNewIns = 0;
}
NoteChange(pChn, note, bPorta, !(GetType() & (MOD_TYPE_XM|MOD_TYPE_MT2)));
if ((bPorta) && (GetType() & (MOD_TYPE_XM|MOD_TYPE_MT2)) && (instr))
{
pChn->dwFlags.set(CHN_FASTVOLRAMP);
pChn->ResetEnvelopes();
pChn->nAutoVibDepth = 0;
pChn->nAutoVibPos = 0;
}
}
// Tick-0 only volume commands
if (volcmd == VOLCMD_VOLUME)
{
if (vol > 64) vol = 64;
pChn->nVolume = vol << 2;
pChn->dwFlags.set(CHN_FASTVOLRAMP);
} else
if (volcmd == VOLCMD_PANNING)
{
Panning(pChn, vol, Pan6bit);
}
#ifndef NO_PLUGINS
if (m_nInstruments) ProcessMidiOut(nChn);
#endif // NO_PLUGINS
}
if(m_playBehaviour[kST3NoMutedChannels] && ChnSettings[nChn].dwFlags[CHN_MUTE]) // not even effects are processed on muted S3M channels
continue;
// Volume Column Effect (except volume & panning)
/* A few notes, paraphrased from ITTECH.TXT by Storlek (creator of schismtracker):
Ex/Fx/Gx are shared with Exx/Fxx/Gxx; Ex/Fx are 4x the 'normal' slide value
Gx is linked with Ex/Fx if Compat Gxx is off, just like Gxx is with Exx/Fxx
Gx values: 1, 4, 8, 16, 32, 64, 96, 128, 255
Ax/Bx/Cx/Dx values are used directly (i.e. D9 == D09), and are NOT shared with Dxx
(value is stored into nOldVolParam and used by A0/B0/C0/D0)
Hx uses the same value as Hxx and Uxx, and affects the *depth*
so... hxx = (hx | (oldhxx & 0xf0)) ???
TODO is this done correctly?
*/
bool doVolumeColumn = m_PlayState.m_nTickCount >= nStartTick;
// FT2 compatibility: If there's a note delay, volume column effects are NOT executed
// on the first tick and, if there's an instrument number, on the delayed tick.
// Test case: VolColDelay.xm, PortaDelay.xm
if(m_playBehaviour[kFT2VolColDelay] && nStartTick != 0)
{
doVolumeColumn = m_PlayState.m_nTickCount != 0 && (m_PlayState.m_nTickCount != nStartTick || (pChn->rowCommand.instr == 0 && volcmd != VOLCMD_TONEPORTAMENTO));
}
if(volcmd > VOLCMD_PANNING && doVolumeColumn)
{
if (volcmd == VOLCMD_TONEPORTAMENTO)
{
uint32 param = 0;
if(GetType() & (MOD_TYPE_IT | MOD_TYPE_MPT | MOD_TYPE_AMS | MOD_TYPE_AMS2 | MOD_TYPE_DMF | MOD_TYPE_DBM | MOD_TYPE_IMF | MOD_TYPE_PSM | MOD_TYPE_J2B | MOD_TYPE_ULT | MOD_TYPE_OKT | MOD_TYPE_MT2 | MOD_TYPE_MDL))
{
param = ImpulseTrackerPortaVolCmd[vol & 0x0F];
} else
{
if(cmd == CMD_TONEPORTAMENTO && GetType() == MOD_TYPE_XM)
{
// Yes, FT2 is *that* weird. If there is a Mx command in the volume column
// and a normal 3xx command, the 3xx command is ignored but the Mx command's
// effectiveness is doubled.
// Test case: TonePortamentoMemory.xm
cmd = CMD_NONE;
vol *= 2;
}
param = vol << 4;
// FT2 compatibility: If there's a portamento and a note delay, execute the portamento, but don't update the parameter
// Test case: PortaDelay.xm
if(m_playBehaviour[kFT2PortaDelay] && nStartTick != 0)
{
param = 0;
}
}
TonePortamento(pChn, param);
} else
{
// FT2 Compatibility: FT2 ignores some volume commands with parameter = 0.
if(m_playBehaviour[kFT2VolColMemory] && vol == 0)
{
switch(volcmd)
{
case VOLCMD_VOLUME:
case VOLCMD_PANNING:
case VOLCMD_VIBRATODEPTH:
break;
case VOLCMD_PANSLIDELEFT:
// FT2 Compatibility: Pan slide left with zero parameter causes panning to be set to full left on every non-row tick.
// Test case: PanSlideZero.xm
if(!m_SongFlags[SONG_FIRSTTICK])
{
pChn->nPan = 0;
}
MPT_FALLTHROUGH;
default:
// no memory here.
volcmd = VOLCMD_NONE;
}
} else if(!m_playBehaviour[kITVolColMemory])
{
// IT Compatibility: Effects in the volume column don't have an unified memory.
// Test case: VolColMemory.it
if(vol) pChn->nOldVolParam = static_cast<ModCommand::PARAM>(vol); else vol = pChn->nOldVolParam;
}
switch(volcmd)
{
case VOLCMD_VOLSLIDEUP:
case VOLCMD_VOLSLIDEDOWN:
// IT Compatibility: Volume column volume slides have their own memory
// Test case: VolColMemory.it
if(vol == 0 && m_playBehaviour[kITVolColMemory])
{
vol = pChn->nOldVolParam;
if(vol == 0)
break;
} else
{
pChn->nOldVolParam = static_cast<ModCommand::PARAM>(vol);
}
VolumeSlide(pChn, static_cast<ModCommand::PARAM>(volcmd == VOLCMD_VOLSLIDEUP ? (vol << 4) : vol));
break;
case VOLCMD_FINEVOLUP:
// IT Compatibility: Fine volume slides in the volume column are only executed on the first tick, not on multiples of the first tick in case of pattern delay
// Test case: FineVolColSlide.it
if(m_PlayState.m_nTickCount == nStartTick || !m_playBehaviour[kITVolColMemory])
{
// IT Compatibility: Volume column volume slides have their own memory
// Test case: VolColMemory.it
FineVolumeUp(pChn, static_cast<ModCommand::PARAM>(vol), m_playBehaviour[kITVolColMemory]);
}
break;
case VOLCMD_FINEVOLDOWN:
// IT Compatibility: Fine volume slides in the volume column are only executed on the first tick, not on multiples of the first tick in case of pattern delay
// Test case: FineVolColSlide.it
if(m_PlayState.m_nTickCount == nStartTick || !m_playBehaviour[kITVolColMemory])
{
// IT Compatibility: Volume column volume slides have their own memory
// Test case: VolColMemory.it
FineVolumeDown(pChn, static_cast<ModCommand::PARAM>(vol), m_playBehaviour[kITVolColMemory]);
}
break;
case VOLCMD_VIBRATOSPEED:
// FT2 does not automatically enable vibrato with the "set vibrato speed" command
if(m_playBehaviour[kFT2VolColVibrato])
pChn->nVibratoSpeed = vol & 0x0F;
else
Vibrato(pChn, vol << 4);
break;
case VOLCMD_VIBRATODEPTH:
Vibrato(pChn, vol);
break;
case VOLCMD_PANSLIDELEFT:
PanningSlide(pChn, static_cast<ModCommand::PARAM>(vol), !m_playBehaviour[kFT2VolColMemory]);
break;
case VOLCMD_PANSLIDERIGHT:
PanningSlide(pChn, static_cast<ModCommand::PARAM>(vol << 4), !m_playBehaviour[kFT2VolColMemory]);
break;
case VOLCMD_PORTAUP:
// IT compatibility (one of the first testcases - link effect memory)
PortamentoUp(nChn, static_cast<ModCommand::PARAM>(vol << 2), m_playBehaviour[kITVolColFinePortamento]);
break;
case VOLCMD_PORTADOWN:
// IT compatibility (one of the first testcases - link effect memory)
PortamentoDown(nChn, static_cast<ModCommand::PARAM>(vol << 2), m_playBehaviour[kITVolColFinePortamento]);
break;
case VOLCMD_OFFSET:
if (triggerNote && pChn->pModSample && vol <= CountOf(pChn->pModSample->cues))
{
SmpLength offset;
if(vol == 0)
offset = pChn->oldOffset;
else
offset = pChn->oldOffset = pChn->pModSample->cues[vol - 1];
SampleOffset(*pChn, offset);
}
break;
}
}
}
// Effects
if(cmd != CMD_NONE) switch (cmd)
{
// Set Volume
case CMD_VOLUME:
if(m_SongFlags[SONG_FIRSTTICK])
{
pChn->nVolume = (param < 64) ? param * 4 : 256;
pChn->dwFlags.set(CHN_FASTVOLRAMP);
}
break;
// Portamento Up
case CMD_PORTAMENTOUP:
if ((!param) && (GetType() & MOD_TYPE_MOD)) break;
PortamentoUp(nChn, static_cast<ModCommand::PARAM>(param));
break;
// Portamento Down
case CMD_PORTAMENTODOWN:
if ((!param) && (GetType() & MOD_TYPE_MOD)) break;
PortamentoDown(nChn, static_cast<ModCommand::PARAM>(param));
break;
// Volume Slide
case CMD_VOLUMESLIDE:
if (param || (GetType() != MOD_TYPE_MOD)) VolumeSlide(pChn, static_cast<ModCommand::PARAM>(param));
break;
// Tone-Portamento
case CMD_TONEPORTAMENTO:
TonePortamento(pChn, param);
break;
// Tone-Portamento + Volume Slide
case CMD_TONEPORTAVOL:
if ((param) || (GetType() != MOD_TYPE_MOD)) VolumeSlide(pChn, static_cast<ModCommand::PARAM>(param));
TonePortamento(pChn, 0);
break;
// Vibrato
case CMD_VIBRATO:
Vibrato(pChn, param);
break;
// Vibrato + Volume Slide
case CMD_VIBRATOVOL:
if ((param) || (GetType() != MOD_TYPE_MOD)) VolumeSlide(pChn, static_cast<ModCommand::PARAM>(param));
Vibrato(pChn, 0);
break;
// Set Speed
case CMD_SPEED:
if(m_SongFlags[SONG_FIRSTTICK])
SetSpeed(param);
break;
// Set Tempo
case CMD_TEMPO:
if(m_playBehaviour[kMODVBlankTiming])
{
// ProTracker MODs with VBlank timing: All Fxx parameters set the tick count.
if(m_SongFlags[SONG_FIRSTTICK] && param != 0) SetSpeed(param);
break;
}
{
param = CalculateXParam(m_PlayState.m_nPattern, m_PlayState.m_nRow, nChn);
if (GetType() & (MOD_TYPE_S3M|MOD_TYPE_IT|MOD_TYPE_MPT))
{
if (param) pChn->nOldTempo = static_cast<ModCommand::PARAM>(param); else param = pChn->nOldTempo;
}
TEMPO t(param, 0);
LimitMax(t, GetModSpecifications().GetTempoMax());
SetTempo(t);
}
break;
// Set Offset
case CMD_OFFSET:
if (triggerNote)
{
// FT2 compatibility: Portamento + Offset = Ignore offset
// Test case: porta-offset.xm
if(bPorta && GetType() == MOD_TYPE_XM)
{
break;
}
bool isExtended = false;
SmpLength offset = CalculateXParam(m_PlayState.m_nPattern, m_PlayState.m_nRow, nChn, &isExtended);
if(!isExtended)
{
// No X-param (normal behaviour)
offset <<= 8;
if (offset) pChn->oldOffset = offset; else offset = pChn->oldOffset;
offset += static_cast<SmpLength>(pChn->nOldHiOffset) << 16;
}
SampleOffset(*pChn, offset);
}
break;
// Arpeggio
case CMD_ARPEGGIO:
// IT compatibility 01. Don't ignore Arpeggio if no note is playing (also valid for ST3)
if(m_PlayState.m_nTickCount) break;
if((!pChn->nPeriod || !pChn->nNote)
&& (pChn->pModInstrument == nullptr || !pChn->pModInstrument->HasValidMIDIChannel()) // Plugin arpeggio
&& !m_playBehaviour[kITArpeggio] && (GetType() & (MOD_TYPE_IT | MOD_TYPE_MPT))) break;
if (!param && (GetType() & (MOD_TYPE_XM | MOD_TYPE_MOD))) break; // Only important when editing MOD/XM files (000 effects are removed when loading files where this means "no effect")
pChn->nCommand = CMD_ARPEGGIO;
if (param) pChn->nArpeggio = static_cast<ModCommand::PARAM>(param);
break;
// Retrig
case CMD_RETRIG:
if (GetType() & (MOD_TYPE_XM|MOD_TYPE_MT2))
{
if (!(param & 0xF0)) param |= pChn->nRetrigParam & 0xF0;
if (!(param & 0x0F)) param |= pChn->nRetrigParam & 0x0F;
param |= 0x100; // increment retrig count on first row
}
// IT compatibility 15. Retrigger
if(m_playBehaviour[kITRetrigger])
{
if (param) pChn->nRetrigParam = static_cast<uint8>(param & 0xFF);
RetrigNote(nChn, pChn->nRetrigParam, (volcmd == VOLCMD_OFFSET) ? vol + 1 : 0);
} else
{
// XM Retrig
if (param) pChn->nRetrigParam = static_cast<uint8>(param & 0xFF); else param = pChn->nRetrigParam;
RetrigNote(nChn, param, (volcmd == VOLCMD_OFFSET) ? vol + 1 : 0);
}
break;
// Tremor
case CMD_TREMOR:
if(!m_SongFlags[SONG_FIRSTTICK])
{
break;
}
// IT compatibility 12. / 13. Tremor (using modified DUMB's Tremor logic here because of old effects - http://dumb.sf.net/)
if(m_playBehaviour[kITTremor])
{
if(param && !m_SongFlags[SONG_ITOLDEFFECTS])
{
// Old effects have different length interpretation (+1 for both on and off)
if(param & 0xF0) param -= 0x10;
if(param & 0x0F) param -= 0x01;
}
pChn->nTremorCount |= 0x80; // set on/off flag
} else if(m_playBehaviour[kFT2Tremor])
{
// XM Tremor. Logic is being processed in sndmix.cpp
pChn->nTremorCount |= 0x80; // set on/off flag
}
pChn->nCommand = CMD_TREMOR;
if (param) pChn->nTremorParam = static_cast<ModCommand::PARAM>(param);
break;
// Set Global Volume
case CMD_GLOBALVOLUME:
// IT compatibility: Only apply global volume on first tick (and multiples)
// Test case: GlobalVolFirstTick.it
if(!m_SongFlags[SONG_FIRSTTICK])
break;
// ST3 applies global volume on tick 1 and does other weird things, but we won't emulate this for now.
// if(((GetType() & MOD_TYPE_S3M) && m_nTickCount != 1)
// || (!(GetType() & MOD_TYPE_S3M) && !m_SongFlags[SONG_FIRSTTICK]))
// {
// break;
// }
// FT2 compatibility: On channels that are "left" of the global volume command, the new global volume is not applied
// until the second tick of the row. Since we apply global volume on the mix buffer rather than note volumes, this
// cannot be fixed for now.
// Test case: GlobalVolume.xm
// if(IsCompatibleMode(TRK_FASTTRACKER2) && m_SongFlags[SONG_FIRSTTICK] && m_nMusicSpeed > 1)
// {
// break;
// }
if (!(GetType() & GLOBALVOL_7BIT_FORMATS)) param *= 2;
// IT compatibility 16. ST3 and IT ignore out-of-range values.
// Test case: globalvol-invalid.it
if(param <= 128)
{
m_PlayState.m_nGlobalVolume = param * 2;
} else if(!(GetType() & (MOD_TYPE_IT | MOD_TYPE_MPT | MOD_TYPE_S3M)))
{
m_PlayState.m_nGlobalVolume = 256;
}
break;
// Global Volume Slide
case CMD_GLOBALVOLSLIDE:
//IT compatibility 16. Saving last global volume slide param per channel (FT2/IT)
if(m_playBehaviour[kPerChannelGlobalVolSlide])
GlobalVolSlide(static_cast<ModCommand::PARAM>(param), pChn->nOldGlobalVolSlide);
else
GlobalVolSlide(static_cast<ModCommand::PARAM>(param), m_PlayState.Chn[0].nOldGlobalVolSlide);
break;
// Set 8-bit Panning
case CMD_PANNING8:
if(m_SongFlags[SONG_FIRSTTICK])
{
Panning(pChn, param, Pan8bit);
}
break;
// Panning Slide
case CMD_PANNINGSLIDE:
PanningSlide(pChn, static_cast<ModCommand::PARAM>(param));
break;
// Tremolo
case CMD_TREMOLO:
Tremolo(pChn, param);
break;
// Fine Vibrato
case CMD_FINEVIBRATO:
FineVibrato(pChn, param);
break;
// MOD/XM Exx Extended Commands
case CMD_MODCMDEX:
ExtendedMODCommands(nChn, static_cast<ModCommand::PARAM>(param));
break;
// S3M/IT Sxx Extended Commands
case CMD_S3MCMDEX:
if(m_playBehaviour[kST3EffectMemory] && param == 0)
{
param = pChn->nArpeggio; // S00 uses the last non-zero effect parameter as memory, like other effects including Arpeggio, so we "borrow" our memory there.
}
ExtendedS3MCommands(nChn, static_cast<ModCommand::PARAM>(param));
break;
// Key Off
case CMD_KEYOFF:
// This is how Key Off is supposed to sound... (in FT2 at least)
if(m_playBehaviour[kFT2KeyOff])
{
if (m_PlayState.m_nTickCount == param)
{
// XM: Key-Off + Sample == Note Cut
if(pChn->pModInstrument == nullptr || !pChn->pModInstrument->VolEnv.dwFlags[ENV_ENABLED])
{
if(param == 0 && (pChn->rowCommand.instr || pChn->rowCommand.volcmd != VOLCMD_NONE)) // FT2 is weird....
{
pChn->dwFlags.set(CHN_NOTEFADE);
}
else
{
pChn->dwFlags.set(CHN_FASTVOLRAMP);
pChn->nVolume = 0;
}
}
KeyOff(pChn);
}
}
// This is how it's NOT supposed to sound...
else
{
if(m_SongFlags[SONG_FIRSTTICK])
KeyOff(pChn);
}
break;
// Extra-fine porta up/down
case CMD_XFINEPORTAUPDOWN:
switch(param & 0xF0)
{
case 0x10: ExtraFinePortamentoUp(pChn, param & 0x0F); break;
case 0x20: ExtraFinePortamentoDown(pChn, param & 0x0F); break;
// ModPlug XM Extensions (ignore in compatible mode)
case 0x50:
case 0x60:
case 0x70:
case 0x90:
case 0xA0:
if(!m_playBehaviour[kFT2RestrictXCommand]) ExtendedS3MCommands(nChn, static_cast<ModCommand::PARAM>(param));
break;
}
break;
// Set Channel Global Volume
case CMD_CHANNELVOLUME:
if(!m_SongFlags[SONG_FIRSTTICK]) break;
if (param <= 64)
{
pChn->nGlobalVol = param;
pChn->dwFlags.set(CHN_FASTVOLRAMP);
}
break;
// Channel volume slide
case CMD_CHANNELVOLSLIDE:
ChannelVolSlide(pChn, static_cast<ModCommand::PARAM>(param));
break;
// Panbrello (IT)
case CMD_PANBRELLO:
Panbrello(pChn, param);
break;
// Set Envelope Position
case CMD_SETENVPOSITION:
if(m_SongFlags[SONG_FIRSTTICK])
{
pChn->VolEnv.nEnvPosition = param;
// FT2 compatibility: FT2 only sets the position of the panning envelope if the volume envelope's sustain flag is set
// Test case: SetEnvPos.xm
if(!m_playBehaviour[kFT2SetPanEnvPos] || pChn->VolEnv.flags[ENV_SUSTAIN])
{
pChn->PanEnv.nEnvPosition = param;
pChn->PitchEnv.nEnvPosition = param;
}
}
break;
// Position Jump
case CMD_POSITIONJUMP:
m_PlayState.m_nNextPatStartRow = 0; // FT2 E60 bug
nPosJump = static_cast<ORDERINDEX>(CalculateXParam(m_PlayState.m_nPattern, m_PlayState.m_nRow, nChn));
if(m_SongFlags[SONG_PATTERNLOOP] && m_PlayState.m_nSeqOverride == ORDERINDEX_INVALID)
{
m_PlayState.m_nSeqOverride = nPosJump;
//Releasing pattern loop after position jump could cause
//instant jumps - modifying behavior so that now position jumps
//occurs also when pattern loop is enabled.
}
// see http://forum.openmpt.org/index.php?topic=2769.0 - FastTracker resets Dxx if Bxx is called _after_ Dxx
// Test case: PatternJump.mod
if((GetType() & (MOD_TYPE_MOD | MOD_TYPE_XM)) && nBreakRow != ROWINDEX_INVALID)
{
nBreakRow = 0;
}
break;
// Pattern Break
case CMD_PATTERNBREAK:
{
ROWINDEX row = PatternBreak(m_PlayState, nChn, static_cast<ModCommand::PARAM>(param));
if(row != ROWINDEX_INVALID)
{
nBreakRow = row;
if(m_SongFlags[SONG_PATTERNLOOP])
{
//If song is set to loop and a pattern break occurs we should stay on the same pattern.
//Use nPosJump to force playback to "jump to this pattern" rather than move to next, as by default.
//rewbs.to
nPosJump = (int)m_PlayState.m_nCurrentOrder;
}
}
}
break;
// IMF / PTM Note Slides
case CMD_NOTESLIDEUP:
case CMD_NOTESLIDEDOWN:
case CMD_NOTESLIDEUPRETRIG:
case CMD_NOTESLIDEDOWNRETRIG:
// Note that this command seems to be a bit buggy in Polytracker... Luckily, no tune seems to seriously use this
// (Vic uses it e.g. in Spaceman or Perfect Reason to slide effect samples, noone will notice the difference :)
NoteSlide(pChn, param, cmd == CMD_NOTESLIDEUP || cmd == CMD_NOTESLIDEUPRETRIG, cmd == CMD_NOTESLIDEUPRETRIG || cmd == CMD_NOTESLIDEDOWNRETRIG);
break;
// PTM Reverse sample + offset (executed on every tick)
case CMD_REVERSEOFFSET:
if(pChn->pModSample != nullptr)
{
pChn->dwFlags.set(CHN_PINGPONGFLAG);
pChn->dwFlags.reset(CHN_LOOP);
pChn->nLength = pChn->pModSample->nLength; // If there was a loop, extend sample to whole length.
pChn->nPos = (pChn->nLength - 1) - std::min<SmpLength>(SmpLength(param) << 8, pChn->nLength - 1);
pChn->nPosLo = 0;
}
break;
#ifndef NO_PLUGINS
// DBM: Toggle DSP Echo
case CMD_DBMECHO:
if(m_PlayState.m_nTickCount == 0)
{
uint32 chns = (param >> 4), enable = (param & 0x0F);
if(chns > 1 || enable > 2)
{
break;
}
CHANNELINDEX firstChn = nChn, lastChn = nChn;
if(chns == 1)
{
firstChn = 0;
lastChn = m_nChannels - 1;
}
for(CHANNELINDEX c = firstChn; c <= lastChn; c++)
{
ChnSettings[c].dwFlags.set(CHN_NOFX, enable == 1);
m_PlayState.Chn[c].dwFlags.set(CHN_NOFX, enable == 1);
}
}
break;
#endif // NO_PLUGINS
}
if(m_playBehaviour[kST3EffectMemory] && param != 0)
{
UpdateS3MEffectMemory(pChn, static_cast<ModCommand::PARAM>(param));
}
if(pChn->rowCommand.instr)
{
// Not necessarily consistent with actually playing instrument for IT compatibility
pChn->nOldIns = pChn->rowCommand.instr;
}
} // for(...) end
// Navigation Effects
if(m_SongFlags[SONG_FIRSTTICK])
{
const bool doPatternLoop = (nPatLoopRow != ROWINDEX_INVALID);
const bool doBreakRow = (nBreakRow != ROWINDEX_INVALID);
const bool doPosJump = (nPosJump != ORDERINDEX_INVALID);
// Pattern Loop
if(doPatternLoop)
{
m_PlayState.m_nNextOrder = m_PlayState.m_nCurrentOrder;
m_PlayState.m_nNextRow = nPatLoopRow;
if(m_PlayState.m_nPatternDelay)
{
m_PlayState.m_nNextRow++;
}
// As long as the pattern loop is running, mark the looped rows as not visited yet
visitedSongRows.ResetPatternLoop(m_PlayState.m_nCurrentOrder, nPatLoopRow);
}
// Pattern Break / Position Jump only if no loop running
// Exception: FastTracker 2 in all cases, Impulse Tracker in case of position jump
// Test case for FT2 exception: PatLoop-Jumps.xm, PatLoop-Various.xm
// Test case for IT: exception: LoopBreak.it
if((doBreakRow || doPosJump)
&& (!doPatternLoop || m_playBehaviour[kFT2PatternLoopWithJumps] || (m_playBehaviour[kITPatternLoopWithJumps] && doPosJump)))
{
if(!doPosJump) nPosJump = m_PlayState.m_nCurrentOrder + 1;
if(!doBreakRow) nBreakRow = 0;
m_SongFlags.set(SONG_BREAKTOROW);
if(nPosJump >= Order.size())
{
nPosJump = 0;
}
// IT / FT2 compatibility: don't reset loop count on pattern break.
// Test case: gm-trippy01.it, PatLoop-Break.xm, PatLoop-Weird.xm, PatLoop-Break.mod
if(nPosJump != m_PlayState.m_nCurrentOrder
&& !m_playBehaviour[kITPatternLoopBreak] && !m_playBehaviour[kFT2PatternLoopWithJumps] && GetType() != MOD_TYPE_MOD)
{
for(CHANNELINDEX i = 0; i < GetNumChannels(); i++)
{
m_PlayState.Chn[i].nPatternLoopCount = 0;
}
}
m_PlayState.m_nNextOrder = nPosJump;
m_PlayState.m_nNextRow = nBreakRow;
}
}
return true;
}
////////////////////////////////////////////////////////////
// Channels effects
// Update the effect memory of all S3M effects that use the last non-zero effect parameter as memory (Dxy, Exx, Fxx, Ixy, Jxy, Kxy, Lxy, Qxy, Rxy, Sxy)
// Test case: ParamMemory.s3m
void CSoundFile::UpdateS3MEffectMemory(ModChannel *pChn, ModCommand::PARAM param) const
//-------------------------------------------------------------------------------------
{
pChn->nOldVolumeSlide = param; // Dxy / Kxy / Lxy
pChn->nOldPortaUpDown = param; // Exx / Fxx
pChn->nTremorParam = param; // Ixy
pChn->nArpeggio = param; // Jxy
pChn->nRetrigParam = param; // Qxy
pChn->nTremoloDepth = (param & 0x0F) << 2; // Rxy
pChn->nTremoloSpeed = (param >> 4) & 0x0F; // Rxy
// Sxy is not handled here.
}
// Calculate full parameter for effects that support parameter extension at the given pattern location.
// maxCommands sets the maximum number of XParam commands to look at for this effect
// isExtended returns if the command is actually using any XParam extensions.
uint32 CSoundFile::CalculateXParam(PATTERNINDEX pat, ROWINDEX row, CHANNELINDEX chn, bool *isExtended) const
//------------------------------------------------------------------------------------------------------------
{
if(isExtended != nullptr) *isExtended = false;
ROWINDEX maxCommands = 4;
const ModCommand *m = Patterns[pat].GetpModCommand(row, chn);
uint32 val = m->param;
switch(m->command)
{
case CMD_OFFSET:
// 24 bit command
maxCommands = 2;
break;
case CMD_TEMPO:
case CMD_PATTERNBREAK:
case CMD_POSITIONJUMP:
// 16 bit command
maxCommands = 1;
break;
default:
return val;
}
const bool xmTempoFix = m->command == CMD_TEMPO && GetType() == MOD_TYPE_XM;
ROWINDEX numRows = std::min(Patterns[pat].GetNumRows() - row - 1, maxCommands);
while(numRows > 0)
{
m += Patterns[pat].GetNumChannels();
if(m->command != CMD_XPARAM)
{
break;
}
if(xmTempoFix && val < 256)
{
// With XM, 0x20 is the lowest tempo. Anything below changes ticks per row.
val -= 0x20;
}
val = (val << 8) | m->param;
numRows--;
if(isExtended != nullptr) *isExtended = true;
}
return val;
}
ROWINDEX CSoundFile::PatternBreak(PlayState &state, CHANNELINDEX chn, uint8 param) const
//--------------------------------------------------------------------------------------
{
if(param >= 64 && (GetType() & MOD_TYPE_S3M))
{
// ST3 ignores invalid pattern breaks.
return ROWINDEX_INVALID;
}
state.m_nNextPatStartRow = 0; // FT2 E60 bug
return static_cast<ROWINDEX>(CalculateXParam(state.m_nPattern, state.m_nRow, chn));
}
void CSoundFile::PortamentoUp(CHANNELINDEX nChn, ModCommand::PARAM param, const bool doFinePortamentoAsRegular)
//-------------------------------------------------------------------------------------------------------------
{
ModChannel *pChn = &m_PlayState.Chn[nChn];
if(param)
pChn->nOldPortaUpDown = param;
else
param = pChn->nOldPortaUpDown;
const bool doFineSlides = !doFinePortamentoAsRegular && !(GetType() & (MOD_TYPE_MOD | MOD_TYPE_XM | MOD_TYPE_MT2 | MOD_TYPE_MED | MOD_TYPE_AMF0 | MOD_TYPE_DIGI));
// Process MIDI pitch bend for instrument plugins
MidiPortamento(nChn, param, doFineSlides);
if(GetType() == MOD_TYPE_MPT && pChn->pModInstrument && pChn->pModInstrument->pTuning)
{
// Portamento for instruments with custom tuning
if(param >= 0xF0 && !doFinePortamentoAsRegular)
PortamentoFineMPT(pChn, param - 0xF0);
else if(param >= 0xE0 && !doFinePortamentoAsRegular)
PortamentoExtraFineMPT(pChn, param - 0xE0);
else
PortamentoMPT(pChn, param);
return;
} else if(GetType() == MOD_TYPE_PLM)
{
// A normal portamento up or down makes a follow-up tone portamento go the same direction.
pChn->nPortamentoDest = 1;
}
if (doFineSlides && param >= 0xE0)
{
if (param & 0x0F)
{
if ((param & 0xF0) == 0xF0)
{
FinePortamentoUp(pChn, param & 0x0F);
return;
} else if ((param & 0xF0) == 0xE0 && GetType() != MOD_TYPE_DBM)
{
ExtraFinePortamentoUp(pChn, param & 0x0F);
return;
}
}
if(GetType() != MOD_TYPE_DBM)
{
// DBM only has fine slides, no extra-fine slides.
return;
}
}
// Regular Slide
if(!pChn->isFirstTick || (m_PlayState.m_nMusicSpeed == 1 && m_playBehaviour[kSlidesAtSpeed1]) || GetType() == MOD_TYPE_669)
{
DoFreqSlide(pChn, -int(param) * 4);
}
}
void CSoundFile::PortamentoDown(CHANNELINDEX nChn, ModCommand::PARAM param, const bool doFinePortamentoAsRegular)
//---------------------------------------------------------------------------------------------------------------
{
ModChannel *pChn = &m_PlayState.Chn[nChn];
if(param)
pChn->nOldPortaUpDown = param;
else
param = pChn->nOldPortaUpDown;
const bool doFineSlides = !doFinePortamentoAsRegular && !(GetType() & (MOD_TYPE_MOD | MOD_TYPE_XM | MOD_TYPE_MT2 | MOD_TYPE_MED | MOD_TYPE_AMF0 | MOD_TYPE_DIGI));
// Process MIDI pitch bend for instrument plugins
MidiPortamento(nChn, -static_cast<int>(param), doFineSlides);
if(GetType() == MOD_TYPE_MPT && pChn->pModInstrument && pChn->pModInstrument->pTuning)
{
// Portamento for instruments with custom tuning
if(param >= 0xF0 && !doFinePortamentoAsRegular)
PortamentoFineMPT(pChn, -static_cast<int>(param - 0xF0));
else if(param >= 0xE0 && !doFinePortamentoAsRegular)
PortamentoExtraFineMPT(pChn, -static_cast<int>(param - 0xE0));
else
PortamentoMPT(pChn, -static_cast<int>(param));
return;
} else if(GetType() == MOD_TYPE_PLM)
{
// A normal portamento up or down makes a follow-up tone portamento go the same direction.
pChn->nPortamentoDest = 65535;
}
if(doFineSlides && param >= 0xE0)
{
if (param & 0x0F)
{
if ((param & 0xF0) == 0xF0)
{
FinePortamentoDown(pChn, param & 0x0F);
return;
} else if ((param & 0xF0) == 0xE0 && GetType() != MOD_TYPE_DBM)
{
ExtraFinePortamentoDown(pChn, param & 0x0F);
return;
}
}
if(GetType() != MOD_TYPE_DBM)
{
// DBM only has fine slides, no extra-fine slides.
return;
}
}
if(!pChn->isFirstTick || (m_PlayState.m_nMusicSpeed == 1 && m_playBehaviour[kSlidesAtSpeed1]) || GetType() == MOD_TYPE_669)
{
DoFreqSlide(pChn, int(param) * 4);
}
}
// Send portamento commands to plugins
void CSoundFile::MidiPortamento(CHANNELINDEX nChn, int param, bool doFineSlides)
//------------------------------------------------------------------------------
{
int actualParam = mpt::abs(param);
int pitchBend = 0;
// Old MIDI Pitch Bends:
// - Applied on every tick
// - No fine pitch slides (they are interpreted as normal slides)
// New MIDI Pitch Bends:
// - Behaviour identical to sample pitch bends if the instrument's PWD parameter corresponds to the actual VSTi setting.
if(doFineSlides && actualParam >= 0xE0 && !m_playBehaviour[kOldMIDIPitchBends])
{
if(m_PlayState.Chn[nChn].isFirstTick)
{
// Extra fine slide...
pitchBend = (actualParam & 0x0F) * sgn(param);
if(actualParam >= 0xF0)
{
// ... or just a fine slide!
pitchBend *= 4;
}
}
} else if(!m_PlayState.Chn[nChn].isFirstTick || m_playBehaviour[kOldMIDIPitchBends])
{
// Regular slide
pitchBend = param * 4;
}
if(pitchBend)
{
#ifndef NO_PLUGINS
IMixPlugin *plugin = GetChannelInstrumentPlugin(nChn);
if(plugin != nullptr)
{
int8 pwd = 13; // Early OpenMPT legacy... Actually it's not *exactly* 13, but close enough...
if(m_PlayState.Chn[nChn].pModInstrument != nullptr)
{
pwd = m_PlayState.Chn[nChn].pModInstrument->midiPWD;
}
plugin->MidiPitchBend(GetBestMidiChannel(nChn), pitchBend, pwd);
}
#endif // NO_PLUGINS
}
}
void CSoundFile::FinePortamentoUp(ModChannel *pChn, ModCommand::PARAM param) const
//--------------------------------------------------------------------------------
{
if(GetType() == MOD_TYPE_XM)
{
// FT2 compatibility: E1x / E2x / X1x / X2x memory is not linked
// Test case: Porta-LinkMem.xm
if(param) pChn->nOldFinePortaUpDown = (pChn->nOldFinePortaUpDown & 0x0F) | (param << 4); else param = (pChn->nOldFinePortaUpDown >> 4);
} else if(GetType() == MOD_TYPE_MT2)
{
if(param) pChn->nOldFinePortaUpDown = param; else param = pChn->nOldFinePortaUpDown;
}
if(pChn->isFirstTick)
{
if ((pChn->nPeriod) && (param))
{
if(m_SongFlags[SONG_LINEARSLIDES] && GetType() != MOD_TYPE_XM)
{
int oldPeriod = pChn->nPeriod;
pChn->nPeriod = Util::muldivr(pChn->nPeriod, GetLinearSlideUpTable(this, param & 0x0F), 65536);
if(oldPeriod == pChn->nPeriod) pChn->nPeriod++;
} else
{
pChn->nPeriod -= (int)(param * 4);
if (pChn->nPeriod < 1)
{
pChn->nPeriod = 1;
if(GetType() == MOD_TYPE_S3M)
{
pChn->nFadeOutVol = 0;
pChn->dwFlags.set(CHN_NOTEFADE | CHN_FASTVOLRAMP);
}
}
}
}
}
}
void CSoundFile::FinePortamentoDown(ModChannel *pChn, ModCommand::PARAM param) const
//----------------------------------------------------------------------------------
{
if(GetType() == MOD_TYPE_XM)
{
// FT2 compatibility: E1x / E2x / X1x / X2x memory is not linked
// Test case: Porta-LinkMem.xm
if(param) pChn->nOldFinePortaUpDown = (pChn->nOldFinePortaUpDown & 0xF0) | (param & 0x0F); else param = (pChn->nOldFinePortaUpDown & 0x0F);
} else if(GetType() == MOD_TYPE_MT2)
{
if(param) pChn->nOldFinePortaUpDown = param; else param = pChn->nOldFinePortaUpDown;
}
if(pChn->isFirstTick)
{
if ((pChn->nPeriod) && (param))
{
if (m_SongFlags[SONG_LINEARSLIDES] && GetType() != MOD_TYPE_XM)
{
int oldPeriod = pChn->nPeriod;
pChn->nPeriod = Util::muldivr(pChn->nPeriod, GetLinearSlideDownTable(this, param & 0x0F), 65536);
if(oldPeriod == pChn->nPeriod) pChn->nPeriod--;
} else
{
pChn->nPeriod += (int)(param * 4);
if (pChn->nPeriod > 0xFFFF) pChn->nPeriod = 0xFFFF;
}
}
}
}
void CSoundFile::ExtraFinePortamentoUp(ModChannel *pChn, ModCommand::PARAM param) const
//-------------------------------------------------------------------------------------
{
if(GetType() == MOD_TYPE_XM)
{
// FT2 compatibility: E1x / E2x / X1x / X2x memory is not linked
// Test case: Porta-LinkMem.xm
if(param) pChn->nOldExtraFinePortaUpDown = (pChn->nOldExtraFinePortaUpDown & 0x0F) | (param << 4); else param = (pChn->nOldExtraFinePortaUpDown >> 4);
} else if(GetType() == MOD_TYPE_MT2)
{
if(param) pChn->nOldFinePortaUpDown = param; else param = pChn->nOldFinePortaUpDown;
}
if(pChn->isFirstTick)
{
if ((pChn->nPeriod) && (param))
{
if(m_SongFlags[SONG_LINEARSLIDES] && GetType() != MOD_TYPE_XM)
{
int oldPeriod = pChn->nPeriod;
pChn->nPeriod = Util::muldivr(pChn->nPeriod, GetFineLinearSlideUpTable(this, param & 0x0F), 65536);
if(oldPeriod == pChn->nPeriod) pChn->nPeriod++;
} else
{
pChn->nPeriod -= (int)(param);
if (pChn->nPeriod < 1)
{
pChn->nPeriod = 1;
if(GetType() == MOD_TYPE_S3M)
{
pChn->nFadeOutVol = 0;
pChn->dwFlags.set(CHN_NOTEFADE | CHN_FASTVOLRAMP);
}
}
}
}
}
}
void CSoundFile::ExtraFinePortamentoDown(ModChannel *pChn, ModCommand::PARAM param) const
//---------------------------------------------------------------------------------------
{
if(GetType() == MOD_TYPE_XM)
{
// FT2 compatibility: E1x / E2x / X1x / X2x memory is not linked
// Test case: Porta-LinkMem.xm
if(param) pChn->nOldExtraFinePortaUpDown = (pChn->nOldExtraFinePortaUpDown & 0xF0) | (param & 0x0F); else param = (pChn->nOldExtraFinePortaUpDown & 0x0F);
} else if(GetType() == MOD_TYPE_MT2)
{
if(param) pChn->nOldFinePortaUpDown = param; else param = pChn->nOldFinePortaUpDown;
}
if(pChn->isFirstTick)
{
if ((pChn->nPeriod) && (param))
{
if(m_SongFlags[SONG_LINEARSLIDES] && GetType() != MOD_TYPE_XM)
{
int oldPeriod = pChn->nPeriod;
pChn->nPeriod = Util::muldivr(pChn->nPeriod, GetFineLinearSlideDownTable(this, param & 0x0F), 65536);
if(oldPeriod == pChn->nPeriod) pChn->nPeriod--;
} else
{
pChn->nPeriod += (int)(param);
if (pChn->nPeriod > 0xFFFF) pChn->nPeriod = 0xFFFF;
}
}
}
}
// Implemented for IMF compatibility, can't actually save this in any formats
// Slide up / down every x ticks by y semitones
void CSoundFile::NoteSlide(ModChannel *pChn, uint32 param, bool slideUp, bool retrig) const
//-----------------------------------------------------------------------------------------
{
uint8 x, y;
if(m_SongFlags[SONG_FIRSTTICK])
{
x = param & 0xF0;
if (x)
pChn->nNoteSlideSpeed = (x >> 4);
y = param & 0x0F;
if (y)
pChn->nNoteSlideStep = y;
pChn->nNoteSlideCounter = pChn->nNoteSlideSpeed;
} else
{
if (--pChn->nNoteSlideCounter == 0)
{
pChn->nNoteSlideCounter = pChn->nNoteSlideSpeed;
// update it
pChn->nPeriod = GetPeriodFromNote
((slideUp ? 1 : -1) * pChn->nNoteSlideStep + GetNoteFromPeriod(pChn->nPeriod), 8363, 0);
if(retrig)
{
pChn->nPos = pChn->nPosLo = 0;
}
}
}
}
// Portamento Slide
void CSoundFile::TonePortamento(ModChannel *pChn, uint32 param) const
//-------------------------------------------------------------------
{
pChn->dwFlags.set(CHN_PORTAMENTO);
//IT compatibility 03: Share effect memory with portamento up/down
if((!m_SongFlags[SONG_ITCOMPATGXX] && m_playBehaviour[kITPortaMemoryShare]) || GetType() == MOD_TYPE_PLM)
{
if(param == 0) param = pChn->nOldPortaUpDown;
pChn->nOldPortaUpDown = static_cast<uint8>(param);
}
if(GetType() == MOD_TYPE_MPT && pChn->pModInstrument && pChn->pModInstrument->pTuning)
{
//Behavior: Param tells number of finesteps(or 'fullsteps'(notes) with glissando)
//to slide per row(not per tick).
const int32 old_PortamentoTickSlide = (m_PlayState.m_nTickCount != 0) ? pChn->m_PortamentoTickSlide : 0;
if(param)
pChn->nPortamentoSlide = param;
else
if(pChn->nPortamentoSlide == 0)
return;
if((pChn->nPortamentoDest > 0 && pChn->nPortamentoSlide < 0) ||
(pChn->nPortamentoDest < 0 && pChn->nPortamentoSlide > 0))
pChn->nPortamentoSlide = -pChn->nPortamentoSlide;
pChn->m_PortamentoTickSlide = static_cast<int32>((m_PlayState.m_nTickCount + 1.0) * pChn->nPortamentoSlide / m_PlayState.m_nMusicSpeed);
if(pChn->dwFlags[CHN_GLISSANDO])
{
pChn->m_PortamentoTickSlide *= pChn->pModInstrument->pTuning->GetFineStepCount() + 1;
//With glissando interpreting param as notes instead of finesteps.
}
const int32 slide = pChn->m_PortamentoTickSlide - old_PortamentoTickSlide;
if(mpt::abs(pChn->nPortamentoDest) <= mpt::abs(slide))
{
if(pChn->nPortamentoDest != 0)
{
pChn->m_PortamentoFineSteps += pChn->nPortamentoDest;
pChn->nPortamentoDest = 0;
pChn->m_CalculateFreq = true;
}
} else
{
pChn->m_PortamentoFineSteps += slide;
pChn->nPortamentoDest -= slide;
pChn->m_CalculateFreq = true;
}
return;
} //End candidate MPT behavior.
bool doPorta = !pChn->isFirstTick || (GetType() & (MOD_TYPE_DBM | MOD_TYPE_669)) || (m_PlayState.m_nMusicSpeed == 1 && m_playBehaviour[kSlidesAtSpeed1]);
if(GetType() == MOD_TYPE_PLM && param >= 0xF0)
{
param -= 0xF0;
doPorta = pChn->isFirstTick;
}
if(param)
{
if(GetType() == MOD_TYPE_669)
{
param *= 10;
}
pChn->nPortamentoSlide = param * 4;
}
if(pChn->nPeriod && pChn->nPortamentoDest && doPorta)
{
if (pChn->nPeriod < pChn->nPortamentoDest)
{
int32 delta = pChn->nPortamentoSlide;
if(m_SongFlags[SONG_LINEARSLIDES] && GetType() != MOD_TYPE_XM)
{
uint32 n = pChn->nPortamentoSlide / 4;
if (n > 255) n = 255;
// Return (a*b+c/2)/c - no divide error
// Table is 65536*2(n/192)
delta = Util::muldivr(pChn->nPeriod, LinearSlideUpTable[n], 65536) - pChn->nPeriod;
if (delta < 1) delta = 1;
}
pChn->nPeriod += delta;
if (pChn->nPeriod > pChn->nPortamentoDest) pChn->nPeriod = pChn->nPortamentoDest;
} else
if (pChn->nPeriod > pChn->nPortamentoDest)
{
int32 delta = -pChn->nPortamentoSlide;
if(m_SongFlags[SONG_LINEARSLIDES] && GetType() != MOD_TYPE_XM)
{
uint32 n = pChn->nPortamentoSlide / 4;
if (n > 255) n = 255;
delta = Util::muldivr(pChn->nPeriod, LinearSlideDownTable[n], 65536) - pChn->nPeriod;
if (delta > -1) delta = -1;
}
pChn->nPeriod += delta;
if (pChn->nPeriod < pChn->nPortamentoDest) pChn->nPeriod = pChn->nPortamentoDest;
}
}
// IT compatibility 23. Portamento with no note
// ProTracker also disables portamento once the target is reached.
// Test case: PortaTarget.mod
if(pChn->nPeriod == pChn->nPortamentoDest && (m_playBehaviour[kITPortaTargetReached] || GetType() == MOD_TYPE_MOD))
pChn->nPortamentoDest = 0;
}
void CSoundFile::Vibrato(ModChannel *p, uint32 param) const
//---------------------------------------------------------
{
p->m_VibratoDepth = (param & 0x0F) / 15.0F;
//'New tuning'-thing: 0 - 1 <-> No depth - Full depth.
if (param & 0x0F) p->nVibratoDepth = (param & 0x0F) * 4;
if (param & 0xF0) p->nVibratoSpeed = (param >> 4) & 0x0F;
p->dwFlags.set(CHN_VIBRATO);
}
void CSoundFile::FineVibrato(ModChannel *p, uint32 param) const
//-------------------------------------------------------------
{
if (param & 0x0F) p->nVibratoDepth = param & 0x0F;
if (param & 0xF0) p->nVibratoSpeed = (param >> 4) & 0x0F;
p->dwFlags.set(CHN_VIBRATO);
// ST3 compatibility: Do not distinguish between vibrato types in effect memory
// Test case: VibratoTypeChange.s3m
if(m_playBehaviour[kST3VibratoMemory] && (param & 0x0F))
{
p->nVibratoDepth *= 4u;
}
}
void CSoundFile::Panbrello(ModChannel *p, uint32 param) const
//-----------------------------------------------------------
{
if (param & 0x0F) p->nPanbrelloDepth = param & 0x0F;
if (param & 0xF0) p->nPanbrelloSpeed = (param >> 4) & 0x0F;
}
void CSoundFile::Panning(ModChannel *pChn, uint32 param, PanningType panBits) const
//---------------------------------------------------------------------------------
{
// No panning in ProTracker mode
if(m_playBehaviour[kMODIgnorePanning])
{
return;
}
// IT Compatibility (and other trackers as well): panning disables surround (unless panning in rear channels is enabled, which is not supported by the original trackers anyway)
if (!m_SongFlags[SONG_SURROUNDPAN] && (panBits == Pan8bit || m_playBehaviour[kPanOverride]))
{
pChn->dwFlags.reset(CHN_SURROUND);
}
if(panBits == Pan4bit)
{
// 0...15 panning
pChn->nPan = (param * 256 + 8) / 15;
} else if(panBits == Pan6bit)
{
// 0...64 panning
if(param > 64) param = 64;
pChn->nPan = param * 4;
} else
{
if(!(GetType() & (MOD_TYPE_S3M | MOD_TYPE_DSM | MOD_TYPE_AMF | MOD_TYPE_MTM)))
{
// Real 8-bit panning
pChn->nPan = param;
} else
{
// 7-bit panning + surround
if(param <= 0x80)
{
pChn->nPan = param << 1;
} else if(param == 0xA4)
{
pChn->dwFlags.set(CHN_SURROUND);
pChn->nPan = 0x80;
}
}
}
pChn->dwFlags.set(CHN_FASTVOLRAMP);
pChn->nRestorePanOnNewNote = 0;
//IT compatibility 20. Set pan overrides random pan
if(m_playBehaviour[kPanOverride])
{
pChn->nPanSwing = 0;
pChn->nPanbrelloOffset = 0;
}
}
void CSoundFile::VolumeSlide(ModChannel *pChn, ModCommand::PARAM param)
//---------------------------------------------------------------------
{
if (param)
pChn->nOldVolumeSlide = param;
else
param = pChn->nOldVolumeSlide;
if((GetType() & (MOD_TYPE_MOD | MOD_TYPE_XM | MOD_TYPE_MT2 | MOD_TYPE_MED | MOD_TYPE_DIGI)))
{
// MOD / XM nibble priority
if((param & 0xF0) != 0)
{
param &= 0xF0;
} else
{
param &= 0x0F;
}
}
int newvolume = pChn->nVolume;
if(!(GetType() & (MOD_TYPE_MOD | MOD_TYPE_XM | MOD_TYPE_AMF0 | MOD_TYPE_MED | MOD_TYPE_DIGI)))
{
if ((param & 0x0F) == 0x0F) //Fine upslide or slide -15
{
if (param & 0xF0) //Fine upslide
{
FineVolumeUp(pChn, (param >> 4), false);
return;
} else //Slide -15
{
if(pChn->isFirstTick && !m_SongFlags[SONG_FASTVOLSLIDES])
{
newvolume -= 0x0F * 4;
}
}
} else
if ((param & 0xF0) == 0xF0) //Fine downslide or slide +15
{
if (param & 0x0F) //Fine downslide
{
FineVolumeDown(pChn, (param & 0x0F), false);
return;
} else //Slide +15
{
if(pChn->isFirstTick && !m_SongFlags[SONG_FASTVOLSLIDES])
{
newvolume += 0x0F * 4;
}
}
}
}
if(!pChn->isFirstTick || m_SongFlags[SONG_FASTVOLSLIDES] || (m_PlayState.m_nMusicSpeed == 1 && GetType() == MOD_TYPE_DBM))
{
// IT compatibility: Ignore slide commands with both nibbles set.
if (param & 0x0F)
{
if(!(GetType() & (MOD_TYPE_IT | MOD_TYPE_MPT)) || (param & 0xF0) == 0)
newvolume -= (int)((param & 0x0F) * 4);
}
else
{
newvolume += (int)((param & 0xF0) >> 2);
}
if (GetType() == MOD_TYPE_MOD) pChn->dwFlags.set(CHN_FASTVOLRAMP);
}
newvolume = Clamp(newvolume, 0, 256);
pChn->nVolume = newvolume;
}
void CSoundFile::PanningSlide(ModChannel *pChn, ModCommand::PARAM param, bool memory)
//-----------------------------------------------------------------------------------
{
if(memory)
{
// FT2 compatibility: Use effect memory (lxx and rxx in XM shouldn't use effect memory).
// Test case: PanSlideMem.xm
if(param)
pChn->nOldPanSlide = param;
else
param = pChn->nOldPanSlide;
}
if((GetType() & (MOD_TYPE_XM | MOD_TYPE_MT2)))
{
// XM nibble priority
if((param & 0xF0) != 0)
{
param &= 0xF0;
} else
{
param &= 0x0F;
}
}
int32 nPanSlide = 0;
if(!(GetType() & (MOD_TYPE_XM | MOD_TYPE_MT2)))
{
if (((param & 0x0F) == 0x0F) && (param & 0xF0))
{
if(m_SongFlags[SONG_FIRSTTICK])
{
param = (param & 0xF0) / 4u;
nPanSlide = - (int)param;
}
} else if (((param & 0xF0) == 0xF0) && (param & 0x0F))
{
if(m_SongFlags[SONG_FIRSTTICK])
{
nPanSlide = (param & 0x0F) * 4u;
}
} else if(!m_SongFlags[SONG_FIRSTTICK])
{
if (param & 0x0F)
{
// IT compatibility: Ignore slide commands with both nibbles set.
if(!(GetType() & (MOD_TYPE_IT | MOD_TYPE_MPT)) || (param & 0xF0) == 0)
nPanSlide = (int)((param & 0x0F) * 4u);
} else
{
nPanSlide = -(int)((param & 0xF0) / 4u);
}
}
} else
{
if(!m_SongFlags[SONG_FIRSTTICK])
{
if (param & 0xF0)
{
nPanSlide = (int)((param & 0xF0) / 4u);
} else
{
nPanSlide = -(int)((param & 0x0F) * 4u);
}
// FT2 compatibility: FT2's panning slide is like IT's fine panning slide (not as deep)
if(m_playBehaviour[kFT2PanSlide])
nPanSlide /= 4;
}
}
if (nPanSlide)
{
nPanSlide += pChn->nPan;
nPanSlide = Clamp(nPanSlide, 0, 256);
pChn->nPan = nPanSlide;
pChn->nRestorePanOnNewNote = 0;
}
}
void CSoundFile::FineVolumeUp(ModChannel *pChn, ModCommand::PARAM param, bool volCol) const
//-----------------------------------------------------------------------------------------
{
if(GetType() == MOD_TYPE_XM)
{
// FT2 compatibility: EAx / EBx memory is not linked
// Test case: FineVol-LinkMem.xm
if(param) pChn->nOldFineVolUpDown = (param << 4) | (pChn->nOldFineVolUpDown & 0x0F); else param = (pChn->nOldFineVolUpDown >> 4);
} else if(volCol)
{
if(param) pChn->nOldVolParam = param; else param = pChn->nOldVolParam;
} else
{
if(param) pChn->nOldFineVolUpDown = param; else param = pChn->nOldFineVolUpDown;
}
if(pChn->isFirstTick)
{
pChn->nVolume += param * 4;
if(pChn->nVolume > 256) pChn->nVolume = 256;
if(GetType() & MOD_TYPE_MOD) pChn->dwFlags.set(CHN_FASTVOLRAMP);
}
}
void CSoundFile::FineVolumeDown(ModChannel *pChn, ModCommand::PARAM param, bool volCol) const
//-------------------------------------------------------------------------------------------
{
if(GetType() == MOD_TYPE_XM)
{
// FT2 compatibility: EAx / EBx memory is not linked
// Test case: FineVol-LinkMem.xm
if(param) pChn->nOldFineVolUpDown = param | (pChn->nOldFineVolUpDown & 0xF0); else param = (pChn->nOldFineVolUpDown & 0x0F);
} else if(volCol)
{
if(param) pChn->nOldVolParam = param; else param = pChn->nOldVolParam;
} else
{
if(param) pChn->nOldFineVolUpDown = param; else param = pChn->nOldFineVolUpDown;
}
if(pChn->isFirstTick)
{
pChn->nVolume -= param * 4;
if(pChn->nVolume < 0) pChn->nVolume = 0;
if(GetType() & MOD_TYPE_MOD) pChn->dwFlags.set(CHN_FASTVOLRAMP);
}
}
void CSoundFile::Tremolo(ModChannel *pChn, uint32 param) const
//------------------------------------------------------------
{
if (param & 0x0F) pChn->nTremoloDepth = (param & 0x0F) << 2;
if (param & 0xF0) pChn->nTremoloSpeed = (param >> 4) & 0x0F;
pChn->dwFlags.set(CHN_TREMOLO);
}
void CSoundFile::ChannelVolSlide(ModChannel *pChn, ModCommand::PARAM param) const
//-------------------------------------------------------------------------------
{
int32 nChnSlide = 0;
if (param) pChn->nOldChnVolSlide = param; else param = pChn->nOldChnVolSlide;
if (((param & 0x0F) == 0x0F) && (param & 0xF0))
{
if(m_SongFlags[SONG_FIRSTTICK]) nChnSlide = param >> 4;
} else if (((param & 0xF0) == 0xF0) && (param & 0x0F))
{
if(m_SongFlags[SONG_FIRSTTICK]) nChnSlide = - (int)(param & 0x0F);
} else
{
if(!m_SongFlags[SONG_FIRSTTICK])
{
if (param & 0x0F)
{
if(!(GetType() & (MOD_TYPE_IT | MOD_TYPE_MPT | MOD_TYPE_J2B | MOD_TYPE_DBM)) || (param & 0xF0) == 0)
nChnSlide = -(int)(param & 0x0F);
} else
{
nChnSlide = (int)((param & 0xF0) >> 4);
}
}
}
if (nChnSlide)
{
nChnSlide += pChn->nGlobalVol;
nChnSlide = Clamp(nChnSlide, 0, 64);
pChn->nGlobalVol = nChnSlide;
}
}
void CSoundFile::ExtendedMODCommands(CHANNELINDEX nChn, ModCommand::PARAM param)
//------------------------------------------------------------------------------
{
ModChannel *pChn = &m_PlayState.Chn[nChn];
uint8 command = param & 0xF0;
param &= 0x0F;
switch(command)
{
// E0x: Set Filter
// E1x: Fine Portamento Up
case 0x10: if ((param) || (GetType() & (MOD_TYPE_XM|MOD_TYPE_MT2))) FinePortamentoUp(pChn, param); break;
// E2x: Fine Portamento Down
case 0x20: if ((param) || (GetType() & (MOD_TYPE_XM|MOD_TYPE_MT2))) FinePortamentoDown(pChn, param); break;
// E3x: Set Glissando Control
case 0x30: pChn->dwFlags.set(CHN_GLISSANDO, param != 0); break;
// E4x: Set Vibrato WaveForm
case 0x40: pChn->nVibratoType = param & 0x07; break;
// E5x: Set FineTune
case 0x50: if(!m_SongFlags[SONG_FIRSTTICK])
{
break;
}
if(GetType() & (MOD_TYPE_MOD | MOD_TYPE_DIGI | MOD_TYPE_AMF0 | MOD_TYPE_MED))
{
pChn->nFineTune = MOD2XMFineTune(param);
if(pChn->nPeriod && pChn->rowCommand.IsNote()) pChn->nPeriod = GetPeriodFromNote(pChn->nNote, pChn->nFineTune, pChn->nC5Speed);
} else if(pChn->rowCommand.IsNote())
{
pChn->nFineTune = MOD2XMFineTune(param - 8);
if(pChn->nPeriod) pChn->nPeriod = GetPeriodFromNote(pChn->nNote, pChn->nFineTune, pChn->nC5Speed);
}
break;
// E6x: Pattern Loop
// E7x: Set Tremolo WaveForm
case 0x70: pChn->nTremoloType = param & 0x07; break;
// E8x: Set 4-bit Panning
case 0x80:
if(m_SongFlags[SONG_FIRSTTICK])
{
Panning(pChn, param, Pan4bit);
}
break;
// E9x: Retrig
case 0x90: RetrigNote(nChn, param); break;
// EAx: Fine Volume Up
case 0xA0: if ((param) || (GetType() & (MOD_TYPE_XM|MOD_TYPE_MT2))) FineVolumeUp(pChn, param, false); break;
// EBx: Fine Volume Down
case 0xB0: if ((param) || (GetType() & (MOD_TYPE_XM|MOD_TYPE_MT2))) FineVolumeDown(pChn, param, false); break;
// ECx: Note Cut
case 0xC0: NoteCut(nChn, param, false); break;
// EDx: Note Delay
// EEx: Pattern Delay
case 0xF0:
if(GetType() == MOD_TYPE_MOD) // MOD: Invert Loop
{
pChn->nEFxSpeed = param;
if(m_SongFlags[SONG_FIRSTTICK]) InvertLoop(pChn);
} else // XM: Set Active Midi Macro
{
pChn->nActiveMacro = param;
}
break;
}
}
void CSoundFile::ExtendedS3MCommands(CHANNELINDEX nChn, ModCommand::PARAM param)
//------------------------------------------------------------------------------
{
ModChannel *pChn = &m_PlayState.Chn[nChn];
uint8 command = param & 0xF0;
param &= 0x0F;
switch(command)
{
// S0x: Set Filter
// S1x: Set Glissando Control
case 0x10: pChn->dwFlags.set(CHN_GLISSANDO, param != 0); break;
// S2x: Set FineTune
case 0x20: if(!m_SongFlags[SONG_FIRSTTICK]) break;
if(GetType() != MOD_TYPE_669)
{
pChn->nC5Speed = S3MFineTuneTable[param];
pChn->nFineTune = MOD2XMFineTune(param);
if (pChn->nPeriod) pChn->nPeriod = GetPeriodFromNote(pChn->nNote, pChn->nFineTune, pChn->nC5Speed);
} else if(pChn->pModSample != nullptr)
{
pChn->nC5Speed = pChn->pModSample->nC5Speed + param * 80;
}
break;
// S3x: Set Vibrato Waveform
case 0x30: if(GetType() == MOD_TYPE_S3M)
{
pChn->nVibratoType = param & 0x03;
} else
{
// IT compatibility: Ignore waveform types > 3
if(m_playBehaviour[kITVibratoTremoloPanbrello])
pChn->nVibratoType = (param < 0x04) ? param : 0;
else
pChn->nVibratoType = param & 0x07;
}
break;
// S4x: Set Tremolo Waveform
case 0x40: if(GetType() == MOD_TYPE_S3M)
{
pChn->nTremoloType = param & 0x03;
} else
{
// IT compatibility: Ignore waveform types > 3
if(m_playBehaviour[kITVibratoTremoloPanbrello])
pChn->nTremoloType = (param < 0x04) ? param : 0;
else
pChn->nTremoloType = param & 0x07;
}
break;
// S5x: Set Panbrello Waveform
case 0x50:
// IT compatibility: Ignore waveform types > 3
if(m_playBehaviour[kITVibratoTremoloPanbrello])
{
pChn->nPanbrelloType = (param < 0x04) ? param : 0;
pChn->nPanbrelloPos = 0;
} else
{
pChn->nPanbrelloType = param & 0x07;
}
break;
// S6x: Pattern Delay for x frames
case 0x60:
if(m_SongFlags[SONG_FIRSTTICK] && m_PlayState.m_nTickCount == 0)
{
// Tick delays are added up.
// Scream Tracker 3 does actually not support this command.
// We'll use the same behaviour as for Impulse Tracker, as we can assume that
// most S3Ms that make use of this command were made with Impulse Tracker.
// MPT added this command to the XM format through the X6x effect, so we will use
// the same behaviour here as well.
// Test cases: PatternDelays.it, PatternDelays.s3m, PatternDelays.xm
m_PlayState.m_nFrameDelay += param;
}
break;
// S7x: Envelope Control / Instrument Control
case 0x70: if(!m_SongFlags[SONG_FIRSTTICK]) break;
switch(param)
{
case 0:
case 1:
case 2:
{
ModChannel *bkp = &m_PlayState.Chn[m_nChannels];
for (CHANNELINDEX i=m_nChannels; i<MAX_CHANNELS; i++, bkp++)
{
if (bkp->nMasterChn == nChn+1)
{
if (param == 1)
{
KeyOff(bkp);
} else if (param == 2)
{
bkp->dwFlags.set(CHN_NOTEFADE);
} else
{
bkp->dwFlags.set(CHN_NOTEFADE);
bkp->nFadeOutVol = 0;
}
#ifndef NO_PLUGINS
const ModInstrument *pIns = bkp->pModInstrument;
IMixPlugin *pPlugin;
if(pIns != nullptr && pIns->nMixPlug && (pPlugin = m_MixPlugins[pIns->nMixPlug - 1].pMixPlugin) != nullptr)
{
pPlugin->MidiCommand(GetBestMidiChannel(nChn), pIns->nMidiProgram, pIns->wMidiBank, bkp->nNote + NOTE_MAX_SPECIAL, 0, nChn);
}
#endif // NO_PLUGINS
}
}
}
break;
case 3: pChn->nNNA = NNA_NOTECUT; break;
case 4: pChn->nNNA = NNA_CONTINUE; break;
case 5: pChn->nNNA = NNA_NOTEOFF; break;
case 6: pChn->nNNA = NNA_NOTEFADE; break;
case 7: pChn->VolEnv.flags.reset(ENV_ENABLED); break;
case 8: pChn->VolEnv.flags.set(ENV_ENABLED); break;
case 9: pChn->PanEnv.flags.reset(ENV_ENABLED); break;
case 10: pChn->PanEnv.flags.set(ENV_ENABLED); break;
case 11: pChn->PitchEnv.flags.reset(ENV_ENABLED); break;
case 12: pChn->PitchEnv.flags.set(ENV_ENABLED); break;
case 13: // S7D: Enable pitch envelope, force to play as pitch envelope
case 14: // S7E: Enable pitch envelope, force to play as filter envelope
if(GetType() == MOD_TYPE_MPT)
{
pChn->PitchEnv.flags.set(ENV_ENABLED);
pChn->PitchEnv.flags.set(ENV_FILTER, param != 13);
}
break;
}
break;
// S8x: Set 4-bit Panning
case 0x80:
if(m_SongFlags[SONG_FIRSTTICK])
{
Panning(pChn, param, Pan4bit);
}
break;
// S9x: Sound Control
case 0x90: ExtendedChannelEffect(pChn, param); break;
// SAx: Set 64k Offset
case 0xA0: if(m_SongFlags[SONG_FIRSTTICK])
{
pChn->nOldHiOffset = static_cast<uint8>(param);
if (!m_playBehaviour[kITHighOffsetNoRetrig] && pChn->rowCommand.IsNote())
{
SmpLength pos = param << 16;
if (pos < pChn->nLength) pChn->nPos = pos;
}
}
break;
// SBx: Pattern Loop
// SCx: Note Cut
case 0xC0:
if(param == 0)
{
//IT compatibility 22. SC0 == SC1
if(GetType() & (MOD_TYPE_IT | MOD_TYPE_MPT))
param = 1;
// ST3 doesn't cut notes with SC0
else if(GetType() == MOD_TYPE_S3M)
return;
}
// S3M/IT compatibility: Note Cut really cuts notes and does not just mute them (so that following volume commands could restore the sample)
// Test case: scx.it
NoteCut(nChn, param, m_playBehaviour[kITSCxStopsSample] || GetType() == MOD_TYPE_S3M);
break;
// SDx: Note Delay
// SEx: Pattern Delay for x rows
// SFx: S3M: Not used, IT: Set Active Midi Macro
case 0xF0:
if(GetType() != MOD_TYPE_S3M)
{
pChn->nActiveMacro = static_cast<uint8>(param);
}
break;
}
}
void CSoundFile::ExtendedChannelEffect(ModChannel *pChn, uint32 param)
//--------------------------------------------------------------------
{
// S9x and X9x commands (S3M/XM/IT only)
if(!m_SongFlags[SONG_FIRSTTICK]) return;
switch(param & 0x0F)
{
// S90: Surround Off
case 0x00: pChn->dwFlags.reset(CHN_SURROUND); break;
// S91: Surround On
case 0x01: pChn->dwFlags.set(CHN_SURROUND); pChn->nPan = 128; break;
////////////////////////////////////////////////////////////
// ModPlug Extensions
// S98: Reverb Off
case 0x08:
pChn->dwFlags.reset(CHN_REVERB);
pChn->dwFlags.set(CHN_NOREVERB);
break;
// S99: Reverb On
case 0x09:
pChn->dwFlags.reset(CHN_NOREVERB);
pChn->dwFlags.set(CHN_REVERB);
break;
// S9A: 2-Channels surround mode
case 0x0A:
m_SongFlags.reset(SONG_SURROUNDPAN);
break;
// S9B: 4-Channels surround mode
case 0x0B:
m_SongFlags.set(SONG_SURROUNDPAN);
break;
// S9C: IT Filter Mode
case 0x0C:
m_SongFlags.reset(SONG_MPTFILTERMODE);
break;
// S9D: MPT Filter Mode
case 0x0D:
m_SongFlags.set(SONG_MPTFILTERMODE);
break;
// S9E: Go forward
case 0x0E:
pChn->dwFlags.reset(CHN_PINGPONGFLAG);
break;
// S9F: Go backward (and set playback position to the end if sample just started)
case 0x0F:
if(!pChn->nPos && pChn->nLength && (pChn->rowCommand.IsNote() || !pChn->dwFlags[CHN_LOOP]))
{
pChn->nPos = pChn->nLength - 1;
pChn->nPosLo = 0xFFFF;
}
pChn->dwFlags.set(CHN_PINGPONGFLAG);
break;
}
}
void CSoundFile::InvertLoop(ModChannel *pChn)
//-------------------------------------------
{
// EFx implementation for MOD files (PT 1.1A and up: Invert Loop)
// This effect trashes samples. Thanks to 8bitbubsy for making this work. :)
if(GetType() != MOD_TYPE_MOD || pChn->nEFxSpeed == 0) return;
// we obviously also need a sample for this
ModSample *pModSample = const_cast<ModSample *>(pChn->pModSample);
if(pModSample == nullptr || pModSample->pSample == nullptr || !pModSample->uFlags[CHN_LOOP] || pModSample->uFlags[CHN_16BIT]) return;
pChn->nEFxDelay += ModEFxTable[pChn->nEFxSpeed & 0x0F];
if((pChn->nEFxDelay & 0x80) == 0) return; // only applied if the "delay" reaches 128
pChn->nEFxDelay = 0;
if (++pChn->nEFxOffset >= pModSample->nLoopEnd - pModSample->nLoopStart)
pChn->nEFxOffset = 0;
// TRASH IT!!! (Yes, the sample!)
uint8 &sample = static_cast<uint8 *>(pModSample->pSample)[pModSample->nLoopStart + pChn->nEFxOffset];
sample = ~sample;
ctrlSmp::PrecomputeLoops(*pModSample, *this, false);
}
// Process a MIDI Macro.
// Parameters:
// [in] nChn: Mod channel to apply macro on
// [in] isSmooth: If true, internal macros are interpolated between two rows
// [in] macro: Actual MIDI Macro string
// [in] param: Parameter for parametric macros (Z00 - Z7F)
// [in] plugin: Plugin to send MIDI message to (if not specified but needed, it is autodetected)
void CSoundFile::ProcessMIDIMacro(CHANNELINDEX nChn, bool isSmooth, const char *macro, uint8 param, PLUGINDEX plugin)
//-------------------------------------------------------------------------------------------------------------------
{
ModChannel &chn = m_PlayState.Chn[nChn];
const ModInstrument *pIns = GetNumInstruments() ? chn.pModInstrument : nullptr;
unsigned char out[MACRO_LENGTH];
uint32 outPos = 0; // output buffer position, which also equals the number of complete bytes
const uint8 lastZxxParam = chn.lastZxxParam;
bool firstNibble = true;
for(uint32 pos = 0; pos < (MACRO_LENGTH - 1) && macro[pos]; pos++)
{
bool isNibble = false; // did we parse a nibble or a byte value?
unsigned char data = 0; // data that has just been parsed
// Parse next macro byte... See Impulse Tracker's MIDI.TXT for detailed information on each possible character.
if(macro[pos] >= '0' && macro[pos] <= '9')
{
isNibble = true;
data = (unsigned char)macro[pos] - '0';
}
else if(macro[pos] >= 'A' && macro[pos] <= 'F')
{
isNibble = true;
data = (unsigned char)macro[pos] - 'A' + 0x0A;
} else if(macro[pos] == 'c') // c: MIDI channel
{
isNibble = true;
data = (unsigned char)GetBestMidiChannel(nChn);
} else if(macro[pos] == 'n') // n: note value (last triggered note)
{
if(ModCommand::IsNote(chn.nLastNote))
{
data = (unsigned char)(chn.nLastNote - NOTE_MIN);
}
} else if(macro[pos] == 'v') // v: velocity
{
// This is "almost" how IT does it - apparently, IT seems to lag one row behind on global volume or channel volume changes.
const int swing = (m_playBehaviour[kITSwingBehaviour] || m_playBehaviour[kMPTOldSwingBehaviour]) ? chn.nVolSwing : 0;
const int vol = Util::muldiv((chn.nVolume + swing) * m_PlayState.m_nGlobalVolume, chn.nGlobalVol * chn.nInsVol, 1 << 20);
data = (unsigned char)Clamp(vol / 2, 1, 127);
//data = (unsigned char)MIN((chn.nVolume * chn.nGlobalVol * m_nGlobalVolume) >> (1 + 6 + 8), 127);
} else if(macro[pos] == 'u') // u: volume (calculated)
{
// Same note as with velocity applies here, but apparently also for instrument / sample volumes?
const int vol = Util::muldiv(chn.nCalcVolume * m_PlayState.m_nGlobalVolume, chn.nGlobalVol * chn.nInsVol, 1 << 26);
data = (unsigned char)Clamp(vol / 2, 1, 127);
//data = (unsigned char)MIN((chn.nCalcVolume * chn.nGlobalVol * m_nGlobalVolume) >> (7 + 6 + 8), 127);
} else if(macro[pos] == 'x') // x: pan set
{
data = (unsigned char)std::min(chn.nPan / 2, 127);
} else if(macro[pos] == 'y') // y: calculated pan
{
data = (unsigned char)std::min(chn.nRealPan / 2, 127);
} else if(macro[pos] == 'a') // a: high byte of bank select
{
if(pIns && pIns->wMidiBank)
{
data = (unsigned char)(((pIns->wMidiBank - 1) >> 7) & 0x7F);
}
} else if(macro[pos] == 'b') // b: low byte of bank select
{
if(pIns && pIns->wMidiBank)
{
data = (unsigned char)((pIns->wMidiBank - 1) & 0x7F);
}
} else if(macro[pos] == 'p') // p: program select
{
if(pIns && pIns->nMidiProgram)
{
data = (unsigned char)((pIns->nMidiProgram - 1) & 0x7F);
}
} else if(macro[pos] == 'z') // z: macro data
{
data = param & 0x7F;
if(isSmooth && chn.lastZxxParam < 0x80
&& (outPos < 3 || out[outPos - 3] != 0xF0 || out[outPos - 2] < 0xF0))
{
// Interpolation for external MIDI messages - interpolation for internal messages
// is handled separately to allow for more than 7-bit granularity where it's possible
data = (uint8)CalculateSmoothParamChange((float)lastZxxParam, (float)data);
}
chn.lastZxxParam = data;
} else // unrecognized byte (e.g. space char)
{
continue;
}
// Append parsed data
if(isNibble) // parsed a nibble (constant or 'c' variable)
{
if(firstNibble)
{
out[outPos] = data;
} else
{
out[outPos] = (out[outPos] << 4) | data;
outPos++;
}
firstNibble = !firstNibble;
} else // parsed a byte (variable)
{
if(!firstNibble) // From MIDI.TXT: '9n' is exactly the same as '09 n' or '9 n' -- so finish current byte first
{
outPos++;
}
out[outPos++] = data;
firstNibble = true;
}
}
if(!firstNibble)
{
// Finish current byte
outPos++;
}
if(outPos == 0)
{
// Nothing there to send!
return;
}
// Macro string has been parsed and translated, now send the message(s)...
uint32 sendPos = 0;
while(sendPos < outPos)
{
uint32 sendLen = 0;
if(out[sendPos] == 0xF0)
{
// SysEx start
if((outPos - sendPos >= 4) && (out[sendPos + 1] == 0xF0 || out[sendPos + 1] == 0xF1))
{
// Internal macro (normal (F0F0) or extended (F0F1)), 4 bytes long
sendLen = 4;
} else
{
// SysEx message, find end of message
for(uint32 i = sendPos + 1; i < outPos; i++)
{
if(out[i] == 0xF7)
{
// Found end of SysEx message
sendLen = i - sendPos + 1;
break;
}
}
if(sendLen == 0)
{
// Didn't find end, so "invent" end of SysEx message
out[outPos++] = 0xF7;
sendLen = outPos - sendPos;
}
}
} else
{
// Other MIDI messages, find beginning of next message
while(sendPos + (++sendLen) < outPos)
{
if((out[sendPos + sendLen] & 0x80) != 0)
{
// Next message begins here.
break;
}
}
}
if(sendLen == 0)
{
break;
}
uint32 bytesSent = SendMIDIData(nChn, isSmooth, out + sendPos, sendLen, plugin);
// Ideally (if there's no error in the macro data), we should have sendLen == bytesSent.
if(bytesSent > 0)
{
sendPos += bytesSent;
} else
{
sendPos += sendLen;
}
}
}
// Calculate smooth MIDI macro slide parameter for current tick.
float CSoundFile::CalculateSmoothParamChange(float currentValue, float param) const
//---------------------------------------------------------------------------------
{
MPT_ASSERT(GetNumTicksOnCurrentRow() > m_PlayState.m_nTickCount);
const uint32 ticksLeft = GetNumTicksOnCurrentRow() - m_PlayState.m_nTickCount;
if(ticksLeft > 1)
{
// Slide param
const float step = (param - currentValue) / (float)ticksLeft;
return (currentValue + step);
} else
{
// On last tick, set exact value.
return param;
}
}
// Process MIDI macro data parsed by ProcessMIDIMacro... return bytes sent on success, 0 on (parse) failure.
uint32 CSoundFile::SendMIDIData(CHANNELINDEX nChn, bool isSmooth, const unsigned char *macro, uint32 macroLen, PLUGINDEX plugin)
//------------------------------------------------------------------------------------------------------------------------------
{
if(macroLen < 1)
{
return 0;
}
ModChannel *pChn = &m_PlayState.Chn[nChn];
if(macro[0] == 0xF0 && (macro[1] == 0xF0 || macro[1] == 0xF1))
{
// Internal device.
if(macroLen < 4)
{
return 0;
}
const bool isExtended = (macro[1] == 0xF1);
const uint8 macroCode = macro[2];
const uint8 param = macro[3];
if(macroCode == 0x00 && !isExtended)
{
// F0.F0.00.xx: Set CutOff
int oldcutoff = pChn->nCutOff;
if(param < 0x80)
{
if(!isSmooth)
{
pChn->nCutOff = param;
} else
{
pChn->nCutOff = (uint8)CalculateSmoothParamChange((float)pChn->nCutOff, (float)param);
}
pChn->nRestoreCutoffOnNewNote = 0;
}
oldcutoff -= pChn->nCutOff;
if(oldcutoff < 0) oldcutoff = -oldcutoff;
if((pChn->nVolume > 0) || (oldcutoff < 0x10)
|| !pChn->dwFlags[CHN_FILTER] || (!(pChn->rightVol | pChn->leftVol)))
SetupChannelFilter(pChn, !pChn->dwFlags[CHN_FILTER]);
return 4;
} else if(macroCode == 0x01 && !isExtended)
{
// F0.F0.01.xx: Set Resonance
if(param < 0x80)
{
pChn->nRestoreResonanceOnNewNote = 0;
if(!isSmooth)
{
pChn->nResonance = param;
} else
{
pChn->nResonance = (uint8)CalculateSmoothParamChange((float)pChn->nResonance, (float)param);
}
}
SetupChannelFilter(pChn, !pChn->dwFlags[CHN_FILTER]);
return 4;
} else if(macroCode == 0x02 && !isExtended)
{
// F0.F0.02.xx: Set filter mode (high nibble determines filter mode)
if(param < 0x20)
{
pChn->nFilterMode = (param >> 4);
SetupChannelFilter(pChn, !pChn->dwFlags[CHN_FILTER]);
}
return 4;
#ifndef NO_PLUGINS
} else if(macroCode == 0x03 && !isExtended)
{
// F0.F0.03.xx: Set plug dry/wet
const PLUGINDEX nPlug = (plugin != 0) ? plugin : GetBestPlugin(nChn, PrioritiseChannel, EvenIfMuted);
if ((nPlug) && (nPlug <= MAX_MIXPLUGINS) && param < 0x80)
{
const float newRatio = 1.0f - (static_cast<float>(param & 0x7F) / 127.0f);
if(!isSmooth)
{
m_MixPlugins[nPlug - 1].fDryRatio = newRatio;
} else
{
m_MixPlugins[nPlug - 1].fDryRatio = CalculateSmoothParamChange(m_MixPlugins[nPlug - 1].fDryRatio, newRatio);
}
}
return 4;
} else if((macroCode & 0x80) || isExtended)
{
// F0.F0.{80|n}.xx / F0.F1.n.xx: Set VST effect parameter n to xx
const PLUGINDEX nPlug = (plugin != 0) ? plugin : GetBestPlugin(nChn, PrioritiseChannel, EvenIfMuted);
const uint32 plugParam = isExtended ? (0x80 + macroCode) : (macroCode & 0x7F);
if((nPlug) && (nPlug <= MAX_MIXPLUGINS))
{
IMixPlugin *pPlugin = m_MixPlugins[nPlug - 1].pMixPlugin;
if(pPlugin && param < 0x80)
{
const float fParam = param / 127.0f;
if(!isSmooth)
{
pPlugin->SetParameter(plugParam, fParam);
} else
{
pPlugin->SetParameter(plugParam, CalculateSmoothParamChange(pPlugin->GetParameter(plugParam), fParam));
}
}
}
return 4;
#endif // NO_PLUGINS
}
// If we reach this point, the internal macro was invalid.
} else
{
#ifndef NO_PLUGINS
// Not an internal device. Pass on to appropriate plugin.
const CHANNELINDEX plugChannel = (nChn < GetNumChannels()) ? nChn + 1 : pChn->nMasterChn;
if(plugChannel > 0 && plugChannel <= GetNumChannels()) // XXX do we need this? I guess it might be relevant for previewing notes in the pattern... Or when using this mechanism for volume/panning!
{
PLUGINDEX nPlug = 0;
if(!pChn->dwFlags[CHN_NOFX])
{
nPlug = (plugin != 0) ? plugin : GetBestPlugin(nChn, PrioritiseChannel, EvenIfMuted);
}
if(nPlug > 0 && nPlug <= MAX_MIXPLUGINS)
{
IMixPlugin *pPlugin = m_MixPlugins[nPlug - 1].pMixPlugin;
if (pPlugin != nullptr)
{
if(macro[0] == 0xF0)
{
pPlugin->MidiSysexSend(macro, macroLen);
} else
{
for(uint32 pos = 0; pos < macroLen;)
{
uint32 len = std::min<uint32>(MIDIEvents::GetEventLength(macro[pos]), macroLen - pos);
uint32 curData = 0;
memcpy(&curData, macro + pos, len);
pPlugin->MidiSend(curData);
pos += len;
}
}
}
}
}
#else
MPT_UNREFERENCED_PARAMETER(plugin);
#endif // NO_PLUGINS
return macroLen;
}
return 0;
}
void CSoundFile::SendMIDINote(CHANNELINDEX chn, uint16 note, uint16 volume)
//-------------------------------------------------------------------------
{
#ifndef NO_PLUGINS
const ModInstrument *pIns = m_PlayState.Chn[chn].pModInstrument;
// instro sends to a midi chan
if (pIns && pIns->HasValidMIDIChannel())
{
PLUGINDEX nPlug = pIns->nMixPlug;
if ((nPlug) && (nPlug <= MAX_MIXPLUGINS))
{
IMixPlugin *pPlug = m_MixPlugins[nPlug-1].pMixPlugin;
if (pPlug != nullptr)
{
pPlug->MidiCommand(GetBestMidiChannel(chn), pIns->nMidiProgram, pIns->wMidiBank, note, volume, chn);
}
}
}
#endif // NO_PLUGINS
}
void CSoundFile::SampleOffset(ModChannel &chn, SmpLength param) const
//-------------------------------------------------------------------
{
chn.proTrackerOffset += param;
if(param >= chn.nLoopEnd && GetType() == MOD_TYPE_MTM && chn.dwFlags[CHN_LOOP] && chn.nLoopEnd > 0)
{
// Offset wrap-around
param = (param - chn.nLoopStart) % (chn.nLoopEnd - chn.nLoopStart) + chn.nLoopStart;
}
if(GetType() == MOD_TYPE_MDL && chn.dwFlags[CHN_16BIT])
{
// Digitrakker really uses byte offsets, not sample offsets. WTF!
param /= 2u;
} else if(GetType() == MOD_TYPE_PLM)
{
// Offset in Disorder Tracker 2 is a percentage
param = Util::muldiv_unsigned(chn.nLength, param >> 8, 255);
}
if(chn.rowCommand.IsNote())
{
// IT compatibility: If this note is not mapped to a sample, ignore it.
// Test case: empty_sample_offset.it
if(chn.pModInstrument != nullptr)
{
SAMPLEINDEX smp = chn.pModInstrument->Keyboard[chn.rowCommand.note - NOTE_MIN];
if(smp == 0 || smp > GetNumSamples())
return;
}
if(m_SongFlags[SONG_PT_MODE])
{
// ProTracker compatbility: PT1/2-style funky 9xx offset command
// Test case: ptoffset.mod
chn.nPos = chn.proTrackerOffset;
chn.proTrackerOffset += param;
} else
{
chn.nPos = param;
}
chn.nPosLo = 0;
if (chn.nPos >= chn.nLength || (chn.dwFlags[CHN_LOOP] && chn.nPos >= chn.nLoopEnd))
{
// Offset beyond sample size
if (!(GetType() & (MOD_TYPE_XM | MOD_TYPE_MT2 | MOD_TYPE_MOD | MOD_TYPE_MTM)))
{
// IT Compatibility: Offset
if(m_playBehaviour[kITOffset])
{
if(m_SongFlags[SONG_ITOLDEFFECTS])
chn.nPos = chn.nLength; // Old FX: Clip to end of sample
else
chn.nPos = 0; // Reset to beginning of sample
} else
{
chn.nPos = chn.nLoopStart;
if(m_SongFlags[SONG_ITOLDEFFECTS] && chn.nLength > 4)
{
chn.nPos = chn.nLength - 2;
}
}
} else if(m_playBehaviour[kFT2OffsetOutOfRange] || GetType() == MOD_TYPE_MTM)
{
// FT2 Compatibility: Don't play note if offset is beyond sample length
// Test case: 3xx-no-old-samp.xm
chn.dwFlags.set(CHN_FASTVOLRAMP);
chn.nVolume = chn.nPeriod = 0;
} else if(GetType() == MOD_TYPE_MOD && chn.dwFlags[CHN_LOOP])
{
chn.nPos = chn.nLoopStart;
}
}
} else if ((param < chn.nLength) && (GetType() & (MOD_TYPE_MTM | MOD_TYPE_DMF | MOD_TYPE_MDL | MOD_TYPE_PLM)))
{
// Some trackers can also call offset effects without notes next to them...
chn.nPos = param;
chn.nPosLo = 0;
}
}
void CSoundFile::RetrigNote(CHANNELINDEX nChn, int param, int offset)
//-------------------------------------------------------------------
{
// Retrig: bit 8 is set if it's the new XM retrig
ModChannel &chn = m_PlayState.Chn[nChn];
int retrigSpeed = param & 0x0F;
int retrigCount = chn.nRetrigCount;
bool doRetrig = false;
// IT compatibility 15. Retrigger
if(m_playBehaviour[kITRetrigger])
{
if(m_PlayState.m_nTickCount == 0 && chn.rowCommand.note)
{
chn.nRetrigCount = param & 0xf;
} else if(!chn.nRetrigCount || !--chn.nRetrigCount)
{
chn.nRetrigCount = param & 0xf;
doRetrig = true;
}
} else if(m_playBehaviour[kFT2Retrigger] && (param & 0x100))
{
// Buggy-like-hell FT2 Rxy retrig!
// Test case: retrig.xm
if(m_SongFlags[SONG_FIRSTTICK])
{
// Here are some really stupid things FT2 does on the first tick.
// Test case: RetrigTick0.xm
if(chn.rowCommand.instr > 0 && chn.rowCommand.IsNoteOrEmpty()) retrigCount = 1;
if(chn.rowCommand.volcmd == VOLCMD_VOLUME && chn.rowCommand.vol != 0)
{
// I guess this condition simply checked if the volume byte was != 0 in FT2.
chn.nRetrigCount = retrigCount;
return;
}
}
if(retrigCount >= retrigSpeed)
{
if(!m_SongFlags[SONG_FIRSTTICK] || !chn.rowCommand.IsNote())
{
doRetrig = true;
retrigCount = 0;
}
}
} else
{
// old routines
if (GetType() & (MOD_TYPE_S3M|MOD_TYPE_IT|MOD_TYPE_MPT))
{
if (!retrigSpeed) retrigSpeed = 1;
if ((retrigCount) && (!(retrigCount % retrigSpeed))) doRetrig = true;
retrigCount++;
} else if(GetType() == MOD_TYPE_MTM)
{
// In MultiTracker, E9x retriggers the last note at exactly the x-th tick of the row
doRetrig = m_PlayState.m_nTickCount == static_cast<uint32>(param & 0x0F) && retrigSpeed != 0;
} else
{
int realspeed = retrigSpeed;
// FT2 bug: if a retrig (Rxy) occours together with a volume command, the first retrig interval is increased by one tick
if ((param & 0x100) && (chn.rowCommand.volcmd == VOLCMD_VOLUME) && (chn.rowCommand.param & 0xF0)) realspeed++;
if(!m_SongFlags[SONG_FIRSTTICK] || (param & 0x100))
{
if (!realspeed) realspeed = 1;
if ((!(param & 0x100)) && (m_PlayState.m_nMusicSpeed) && (!(m_PlayState.m_nTickCount % realspeed))) doRetrig = true;
retrigCount++;
} else if (GetType() & (MOD_TYPE_XM|MOD_TYPE_MT2)) retrigCount = 0;
if (retrigCount >= realspeed)
{
if ((m_PlayState.m_nTickCount) || ((param & 0x100) && (!chn.rowCommand.note))) doRetrig = true;
}
if(m_playBehaviour[kFT2Retrigger] && param == 0)
{
// E90 = Retrig instantly, and only once
doRetrig = (m_PlayState.m_nTickCount == 0);
}
}
}
// IT compatibility: If a sample is shorter than the retrig time (i.e. it stops before the retrig counter hits zero), it is not retriggered.
// Test case: retrig-short.it
if(chn.nLength == 0 && m_playBehaviour[kITShortSampleRetrig] && !chn.HasMIDIOutput())
{
return;
}
if(doRetrig)
{
uint32 dv = (param >> 4) & 0x0F;
int vol = chn.nVolume;
if (dv)
{
// FT2 compatibility: Retrig + volume will not change volume of retrigged notes
if(!m_playBehaviour[kFT2Retrigger] || !(chn.rowCommand.volcmd == VOLCMD_VOLUME))
{
if (retrigTable1[dv])
vol = (vol * retrigTable1[dv]) >> 4;
else
vol += ((int)retrigTable2[dv]) << 2;
}
Limit(vol, 0, 256);
chn.dwFlags.set(CHN_FASTVOLRAMP);
}
uint32 note = chn.nNewNote;
int32 oldPeriod = chn.nPeriod;
if ((note) && (note <= NOTE_MAX) && (chn.nLength)) CheckNNA(nChn, 0, note, true);
bool resetEnv = false;
if(GetType() & (MOD_TYPE_XM|MOD_TYPE_MT2))
{
if((chn.rowCommand.instr) && (param < 0x100))
{
InstrumentChange(&chn, chn.rowCommand.instr, false, false);
resetEnv = true;
}
if (param < 0x100) resetEnv = true;
}
// IT compatibility: Really weird combination of envelopes and retrigger (see Storlek's q.it testcase)
// Test case: retrig.it
NoteChange(&chn, note, m_playBehaviour[kITRetrigger], resetEnv);
chn.nVolume = vol;
if(m_nInstruments)
{
chn.rowCommand.note = static_cast<ModCommand::NOTE>(note); // No retrig without note...
#ifndef NO_PLUGINS
ProcessMidiOut(nChn); //Send retrig to Midi
#endif // NO_PLUGINS
}
if ((GetType() & (MOD_TYPE_IT|MOD_TYPE_MPT)) && (!chn.rowCommand.note) && (oldPeriod)) chn.nPeriod = oldPeriod;
if (!(GetType() & (MOD_TYPE_S3M|MOD_TYPE_IT|MOD_TYPE_MPT))) retrigCount = 0;
// IT compatibility: see previous IT compatibility comment =)
if(m_playBehaviour[kITRetrigger]) chn.nPos = chn.nPosLo = 0;
offset--;
if(offset >= 0 && offset <= static_cast<int>(CountOf(chn.pModSample->cues)) && chn.pModSample != nullptr)
{
if(offset == 0) offset = chn.oldOffset;
else offset = chn.oldOffset = chn.pModSample->cues[offset - 1];
SampleOffset(chn, offset);
}
}
// buggy-like-hell FT2 Rxy retrig!
if(m_playBehaviour[kFT2Retrigger] && (param & 0x100)) retrigCount++;
// Now we can also store the retrig value for IT...
if(!m_playBehaviour[kITRetrigger])
chn.nRetrigCount = retrigCount;
}
void CSoundFile::DoFreqSlide(ModChannel *pChn, int32 nFreqSlide) const
//--------------------------------------------------------------------
{
if(!pChn->nPeriod) return;
if(GetType() == MOD_TYPE_669)
{
// Like other oldskool trackers, Composer 669 doesn't have linear slides...
// But the slides are done in Hertz rather than periods, meaning that they
// are more effective in the lower notes (rather than the higher notes).
nFreqSlide *= -20;
}
if(m_SongFlags[SONG_LINEARSLIDES] && GetType() != MOD_TYPE_XM)
{
// IT Linear slides
const int32 nOldPeriod = pChn->nPeriod;
if (nFreqSlide < 0)
{
uint32 n = (-nFreqSlide) / 4;
if (n)
{
if (n > 255) n = 255;
pChn->nPeriod = Util::muldivr(pChn->nPeriod, GetLinearSlideUpTable(this, n), 65536);
if (pChn->nPeriod == nOldPeriod) pChn->nPeriod++;
}
} else
{
uint32 n = (nFreqSlide) / 4;
if (n)
{
if (n > 255) n = 255;
pChn->nPeriod = Util::muldivr(pChn->nPeriod, GetLinearSlideDownTable(this, n), 65536);
if (pChn->nPeriod == nOldPeriod) pChn->nPeriod--;
}
}
} else
{
pChn->nPeriod += nFreqSlide;
}
if (pChn->nPeriod < 1)
{
pChn->nPeriod = 1;
if(GetType() == MOD_TYPE_S3M)
{
pChn->nFadeOutVol = 0;
pChn->dwFlags.set(CHN_NOTEFADE | CHN_FASTVOLRAMP);
}
}
}
void CSoundFile::NoteCut(CHANNELINDEX nChn, uint32 nTick, bool cutSample)
//-----------------------------------------------------------------------
{
if (m_PlayState.m_nTickCount == nTick)
{
ModChannel *pChn = &m_PlayState.Chn[nChn];
if(cutSample)
{
pChn->nInc = 0;
pChn->nFadeOutVol = 0;
pChn->dwFlags.set(CHN_NOTEFADE);
} else
{
pChn->nVolume = 0;
}
pChn->dwFlags.set(CHN_FASTVOLRAMP);
// instro sends to a midi chan
SendMIDINote(nChn, /*pChn->nNote+*/NOTE_MAX_SPECIAL, 0);
}
}
void CSoundFile::KeyOff(ModChannel *pChn) const
//---------------------------------------------
{
const bool bKeyOn = !pChn->dwFlags[CHN_KEYOFF];
pChn->dwFlags.set(CHN_KEYOFF);
if(pChn->pModInstrument != nullptr && !pChn->VolEnv.flags[ENV_ENABLED])
{
pChn->dwFlags.set(CHN_NOTEFADE);
}
if (!pChn->nLength) return;
if (pChn->dwFlags[CHN_SUSTAINLOOP] && pChn->pModSample && bKeyOn)
{
const ModSample *pSmp = pChn->pModSample;
if(pSmp->uFlags[CHN_LOOP])
{
if (pSmp->uFlags[CHN_PINGPONGLOOP])
pChn->dwFlags.set(CHN_PINGPONGLOOP);
else
pChn->dwFlags.reset(CHN_PINGPONGLOOP | CHN_PINGPONGFLAG);
pChn->dwFlags.set(CHN_LOOP);
pChn->nLength = pSmp->nLength;
pChn->nLoopStart = pSmp->nLoopStart;
pChn->nLoopEnd = pSmp->nLoopEnd;
if (pChn->nLength > pChn->nLoopEnd) pChn->nLength = pChn->nLoopEnd;
if(pChn->nPos > pChn->nLength)
{
// Test case: SusAfterLoop.it
pChn->nPos = pChn->nPos - pChn->nLength + pChn->nLoopStart;
pChn->nPosLo = 0;
}
} else
{
pChn->dwFlags.reset(CHN_LOOP | CHN_PINGPONGLOOP | CHN_PINGPONGFLAG);
pChn->nLength = pSmp->nLength;
}
}
if (pChn->pModInstrument)
{
const ModInstrument *pIns = pChn->pModInstrument;
if((pIns->VolEnv.dwFlags[ENV_LOOP] || (GetType() & (MOD_TYPE_XM | MOD_TYPE_MT2 | MOD_TYPE_MDL))) && pIns->nFadeOut != 0)
{
pChn->dwFlags.set(CHN_NOTEFADE);
}
if (pIns->VolEnv.nReleaseNode != ENV_RELEASE_NODE_UNSET)
{
pChn->VolEnv.nEnvValueAtReleaseJump = pIns->VolEnv.GetValueFromPosition(pChn->VolEnv.nEnvPosition, 256);
pChn->VolEnv.nEnvPosition = pIns->VolEnv[pIns->VolEnv.nReleaseNode].tick;
}
}
}
//////////////////////////////////////////////////////////
// CSoundFile: Global Effects
void CSoundFile::SetSpeed(uint32 param)
//-------------------------------------
{
#ifdef MODPLUG_TRACKER
// FT2 appears to be decrementing the tick count before checking for zero,
// so it effectively counts down 65536 ticks with speed = 0 (song speed is a 16-bit variable in FT2)
if(GetType() == MOD_TYPE_XM && !param)
{
m_PlayState.m_nMusicSpeed = uint16_max;
}
#endif // MODPLUG_TRACKER
if(param > 0) m_PlayState.m_nMusicSpeed = param;
}
void CSoundFile::SetTempo(TEMPO param, bool setAsNonModcommand)
//-------------------------------------------------------------
{
const CModSpecifications& specs = GetModSpecifications();
const TEMPO minTempo = (GetType() == MOD_TYPE_MDL) ? TEMPO(1, 0) : TEMPO(32, 0);
if(setAsNonModcommand)
{
// Set tempo from UI - ignore slide commands and such.
m_PlayState.m_nMusicTempo = Clamp(param, specs.GetTempoMin(), specs.GetTempoMax());
} else if (param >= minTempo && m_SongFlags[SONG_FIRSTTICK])
{
m_PlayState.m_nMusicTempo = param;
if (param > GetModSpecifications().GetTempoMax()) param = GetModSpecifications().GetTempoMax();
} else if (param < minTempo && !m_SongFlags[SONG_FIRSTTICK])
{
// Tempo Slide
TEMPO tempDiff(param.GetInt() & 0x0F, 0);
if ((param.GetInt() & 0xF0) == 0x10)
m_PlayState.m_nMusicTempo += tempDiff;
else
m_PlayState.m_nMusicTempo -= tempDiff;
TEMPO tempoMin = GetModSpecifications().GetTempoMin(), tempoMax = GetModSpecifications().GetTempoMax();
if(m_playBehaviour[kTempoClamp]) // clamp tempo correctly in compatible mode
{
tempoMax.Set(255);
}
Limit(m_PlayState.m_nMusicTempo, tempoMin, tempoMax);
}
}
ROWINDEX CSoundFile::PatternLoop(ModChannel *pChn, uint32 param)
//--------------------------------------------------------------
{
if (param)
{
// Loop Repeat
if(pChn->nPatternLoopCount)
{
// There's a loop left
pChn->nPatternLoopCount--;
if(!pChn->nPatternLoopCount)
{
// IT compatibility 10. Pattern loops (+ same fix for S3M files)
// When finishing a pattern loop, the next loop without a dedicated SB0 starts on the first row after the previous loop.
if(m_playBehaviour[kITPatternLoopTargetReset] || (GetType() == MOD_TYPE_S3M))
{
pChn->nPatternLoop = m_PlayState.m_nRow + 1;
}
return ROWINDEX_INVALID;
}
} else
{
// First time we get into the loop => Set loop count.
// IT compatibility 10. Pattern loops (+ same fix for XM / MOD / S3M files)
if(!m_playBehaviour[kITFT2PatternLoop] && !(GetType() & (MOD_TYPE_MOD | MOD_TYPE_S3M)))
{
ModChannel *p = m_PlayState.Chn;
for(CHANNELINDEX i = 0; i < GetNumChannels(); i++, p++) if (p != pChn)
{
// Loop on other channel
if(p->nPatternLoopCount) return ROWINDEX_INVALID;
}
}
pChn->nPatternLoopCount = static_cast<uint8>(param);
}
m_PlayState.m_nNextPatStartRow = pChn->nPatternLoop; // Nasty FT2 E60 bug emulation!
return pChn->nPatternLoop;
} else
{
// Loop Start
pChn->nPatternLoop = m_PlayState.m_nRow;
}
return ROWINDEX_INVALID;
}
void CSoundFile::GlobalVolSlide(ModCommand::PARAM param, uint8 &nOldGlobalVolSlide)
//-----------------------------------------------------------------------------------
{
int32 nGlbSlide = 0;
if (param) nOldGlobalVolSlide = param; else param = nOldGlobalVolSlide;
if((GetType() & (MOD_TYPE_XM | MOD_TYPE_MT2)))
{
// XM nibble priority
if((param & 0xF0) != 0)
{
param &= 0xF0;
} else
{
param &= 0x0F;
}
}
if (((param & 0x0F) == 0x0F) && (param & 0xF0))
{
if(m_SongFlags[SONG_FIRSTTICK]) nGlbSlide = (param >> 4) * 2;
} else
if (((param & 0xF0) == 0xF0) && (param & 0x0F))
{
if(m_SongFlags[SONG_FIRSTTICK]) nGlbSlide = - (int)((param & 0x0F) * 2);
} else
{
if(!m_SongFlags[SONG_FIRSTTICK])
{
if (param & 0xF0)
{
// IT compatibility: Ignore slide commands with both nibbles set.
if(!(GetType() & (MOD_TYPE_IT | MOD_TYPE_MPT | MOD_TYPE_IMF | MOD_TYPE_J2B | MOD_TYPE_MID | MOD_TYPE_AMS | MOD_TYPE_AMS2 | MOD_TYPE_DBM)) || (param & 0x0F) == 0)
nGlbSlide = (int)((param & 0xF0) >> 4) * 2;
} else
{
nGlbSlide = -(int)((param & 0x0F) * 2);
}
}
}
if (nGlbSlide)
{
if(!(GetType() & (MOD_TYPE_IT | MOD_TYPE_MPT | MOD_TYPE_IMF | MOD_TYPE_J2B | MOD_TYPE_MID | MOD_TYPE_AMS | MOD_TYPE_AMS2 | MOD_TYPE_DBM))) nGlbSlide *= 2;
nGlbSlide += m_PlayState.m_nGlobalVolume;
Limit(nGlbSlide, 0, 256);
m_PlayState.m_nGlobalVolume = nGlbSlide;
}
}
//////////////////////////////////////////////////////
// Note/Period/Frequency functions
// Find lowest note which has same or lower period as a given period (i.e. the note has the same or higher frequency)
uint32 CSoundFile::GetNoteFromPeriod(uint32 period, int32 nFineTune, uint32 nC5Speed) const
//-----------------------------------------------------------------------------------------
{
if(!period) return 0;
if(m_playBehaviour[kFT2Periods])
{
// FT2's "RelocateTon" function actually rounds up and down, while GetNoteFromPeriod normally just truncates.
nFineTune += 64;
}
// This essentially implements std::lower_bound, with the difference that we don't need an iterable container.
uint32 minNote = NOTE_MIN, maxNote = NOTE_MAX, count = maxNote - minNote + 1;
const bool periodIsFreq = m_SongFlags[SONG_LINEARSLIDES] && m_playBehaviour[kHertzInLinearMode] && GetType() != MOD_TYPE_XM;
while(count > 0)
{
const uint32 step = count / 2, midNote = minNote + step;
uint32 n = GetPeriodFromNote(midNote, nFineTune, nC5Speed);
if((n > period && !periodIsFreq) || (n < period && periodIsFreq) || !n)
{
minNote = midNote + 1;
count -= step + 1;
} else
{
count = step;
}
}
return minNote;
}
uint32 CSoundFile::GetPeriodFromNote(uint32 note, int32 nFineTune, uint32 nC5Speed) const
//---------------------------------------------------------------------------------------
{
if (note == NOTE_NONE || (note >= NOTE_MIN_SPECIAL)) return 0;
note -= NOTE_MIN;
if (GetType() & (MOD_TYPE_IT|MOD_TYPE_MPT|MOD_TYPE_MT2|MOD_TYPE_S3M|MOD_TYPE_STM|MOD_TYPE_ULT|MOD_TYPE_WAV|MOD_TYPE_669|MOD_TYPE_PLM|MOD_TYPE_DSM
|MOD_TYPE_FAR|MOD_TYPE_DMF|MOD_TYPE_PTM|MOD_TYPE_AMS|MOD_TYPE_AMS2|MOD_TYPE_DBM|MOD_TYPE_AMF|MOD_TYPE_PSM|MOD_TYPE_J2B|MOD_TYPE_IMF|MOD_TYPE_UAX))
{
if(m_SongFlags[SONG_LINEARSLIDES] || GetType() == MOD_TYPE_669)
{
// In IT linear slide mode, directly use frequency in Hertz rather than periods.
if(m_playBehaviour[kHertzInLinearMode] || GetType() == MOD_TYPE_669)
return Util::muldiv_unsigned(nC5Speed, LinearSlideUpTable[(note % 12u) * 16u] << (note / 12u), 65536 << 5);
else
return (FreqS3MTable[note % 12u] << 5) >> (note / 12);
} else
{
if (!nC5Speed)
nC5Speed = 8363;
LimitMax(nC5Speed, uint32_max >> (note / 12u));
//(a*b)/c
return Util::muldiv_unsigned(8363, (FreqS3MTable[note % 12u] << 5), nC5Speed << (note / 12u));
//8363 * freq[note%12] / nC5Speed * 2^(5-note/12)
}
} else if (GetType() == MOD_TYPE_MDL)
{
// MDL uses non-linear slides, but their effectiveness does not depend on the middle-C frequency.
return (FreqS3MTable[note % 12u] << 4) >> (note / 12);
} else if (GetType() == MOD_TYPE_XM)
{
if (note < 12) note = 12;
note -= 12;
// FT2 Compatibility: The lower three bits of the finetune are truncated.
// Test case: Finetune-Precision.xm
if(m_playBehaviour[kFT2FinetunePrecision])
{
nFineTune &= ~7;
}
if(m_SongFlags[SONG_LINEARSLIDES])
{
int l = ((NOTE_MAX - note) << 6) - (nFineTune / 2);
if (l < 1) l = 1;
return static_cast<uint32>(l);
} else
{
int finetune = nFineTune;
uint32 rnote = (note % 12) << 3;
uint32 roct = note / 12;
int rfine = finetune / 16;
int i = rnote + rfine + 8;
Limit(i , 0, 103);
uint32 per1 = XMPeriodTable[i];
if(finetune < 0)
{
rfine--;
finetune = -finetune;
} else rfine++;
i = rnote+rfine+8;
if (i < 0) i = 0;
if (i >= 104) i = 103;
uint32 per2 = XMPeriodTable[i];
rfine = finetune & 0x0F;
per1 *= 16-rfine;
per2 *= rfine;
return ((per1 + per2) << 1) >> roct;
}
} else
{
nFineTune = XM2MODFineTune(nFineTune);
if ((nFineTune) || (note < 36) || (note >= 36 + 6 * 12))
return (ProTrackerTunedPeriods[nFineTune * 12u + note % 12u] << 5) >> (note / 12u);
else
return (ProTrackerPeriodTable[note - 36] << 2);
}
}
// Converts period value to sample frequency. Return value is fixed point, with FREQ_FRACBITS fractional bits.
uint32 CSoundFile::GetFreqFromPeriod(uint32 period, uint32 c5speed, int32 nPeriodFrac) const
//------------------------------------------------------------------------------------------
{
if (!period) return 0;
if (GetType() & (MOD_TYPE_MED | MOD_TYPE_MOD | MOD_TYPE_DIGI | MOD_TYPE_MTM | MOD_TYPE_AMF0 | MOD_TYPE_OKT | MOD_TYPE_SFX))
{
return ((3546895L * 4) << FREQ_FRACBITS) / period;
} else if (GetType() == MOD_TYPE_XM)
{
if(m_playBehaviour[kFT2Periods])
{
// FT2 compatibility: Period is a 16-bit value in FT2, and it overflows happily.
// Test case: FreqWraparound.xm
period &= 0xFFFF;
}
if(m_SongFlags[SONG_LINEARSLIDES])
{
uint32 octave;
if(m_playBehaviour[kFT2Periods])
{
// Under normal circumstances, this calculation returns the same values as the non-compatible one.
// However, once the 12 octaves are exceeded (through portamento slides), the octave shift goes
// crazy in FT2, meaning that the frequency wraps around randomly...
// The entries in FT2's conversion table are four times as big, hence we have to do an additional shift by two bits.
// Test case: FreqWraparound.xm
// 12 octaves * (12 * 64) LUT entries = 9216, add 767 for rounding
uint32 div = ((9216u + 767u - period) / 768);
octave = ((14 - div) & 0x1F);
} else
{
octave = (period / 768) + 2;
}
return (XMLinearTable[period % 768] << (FREQ_FRACBITS + 2)) >> octave;
} else
{
if(!period) period = 1;
return ((8363 * 1712L) << FREQ_FRACBITS) / period;
}
} else if(GetType() == MOD_TYPE_669)
{
// We only really use c5speed for the finetune pattern command. All samples in 669 files have the same middle-C speed (imported as 8363 Hz).
return (period + c5speed - 8363) << FREQ_FRACBITS;
} else if(GetType() == MOD_TYPE_MDL)
{
if (!c5speed) c5speed = 8363;
return Util::muldiv(c5speed, (1712L << 7) << FREQ_FRACBITS, (period << 8) + nPeriodFrac);
} else
{
LimitMax(period, Util::MaxValueOfType(period) >> 8);
if(m_SongFlags[SONG_LINEARSLIDES])
{
if(m_playBehaviour[kHertzInLinearMode])
{
// IT linear slides already use frequencies instead of periods.
static_assert(FREQ_FRACBITS <= 8, "Check this shift operator");
return uint32(((uint64(period) << 8) + nPeriodFrac) >> (8 - FREQ_FRACBITS));
} else
{
if (!c5speed) c5speed = 8363;
return Util::muldiv(c5speed, (1712L << 8) << FREQ_FRACBITS, (period << 8) + nPeriodFrac);
}
} else
{
return Util::muldiv(8363, (1712L << 8) << FREQ_FRACBITS, (period << 8) + nPeriodFrac);
}
}
}
PLUGINDEX CSoundFile::GetBestPlugin(CHANNELINDEX nChn, PluginPriority priority, PluginMutePriority respectMutes) const
//--------------------------------------------------------------------------------------------------------------------
{
if (nChn >= MAX_CHANNELS) //Check valid channel number
{
return 0;
}
//Define search source order
PLUGINDEX nPlugin = 0;
switch (priority)
{
case ChannelOnly:
nPlugin = GetChannelPlugin(nChn, respectMutes);
break;
case InstrumentOnly:
nPlugin = GetActiveInstrumentPlugin(nChn, respectMutes);
break;
case PrioritiseInstrument:
nPlugin = GetActiveInstrumentPlugin(nChn, respectMutes);
if ((!nPlugin) || (nPlugin > MAX_MIXPLUGINS))
{
nPlugin = GetChannelPlugin(nChn, respectMutes);
}
break;
case PrioritiseChannel:
nPlugin = GetChannelPlugin(nChn, respectMutes);
if ((!nPlugin) || (nPlugin > MAX_MIXPLUGINS))
{
nPlugin = GetActiveInstrumentPlugin(nChn, respectMutes);
}
break;
}
return nPlugin; // 0 Means no plugin found.
}
PLUGINDEX CSoundFile::GetChannelPlugin(CHANNELINDEX nChn, PluginMutePriority respectMutes) const
//----------------------------------------------------------------------------------------------
{
const ModChannel &channel = m_PlayState.Chn[nChn];
PLUGINDEX nPlugin;
if((respectMutes == RespectMutes && channel.dwFlags[CHN_MUTE]) || channel.dwFlags[CHN_NOFX])
{
nPlugin = 0;
} else
{
// If it looks like this is an NNA channel, we need to find the master channel.
// This ensures we pick up the right ChnSettings.
// NB: nMasterChn == 0 means no master channel, so we need to -1 to get correct index.
if (nChn >= m_nChannels && channel.nMasterChn > 0)
{
nChn = channel.nMasterChn - 1;
}
if(nChn < MAX_BASECHANNELS)
{
nPlugin = ChnSettings[nChn].nMixPlugin;
} else
{
nPlugin = 0;
}
}
return nPlugin;
}
PLUGINDEX CSoundFile::GetActiveInstrumentPlugin(CHANNELINDEX nChn, PluginMutePriority respectMutes) const
//-------------------------------------------------------------------------------------------------------
{
// Unlike channel settings, pModInstrument is copied from the original chan to the NNA chan,
// so we don't need to worry about finding the master chan.
PLUGINDEX plug = 0;
if(m_PlayState.Chn[nChn].pModInstrument != nullptr)
{
if(respectMutes == RespectMutes && m_PlayState.Chn[nChn].pModSample && m_PlayState.Chn[nChn].pModSample->uFlags[CHN_MUTE])
{
plug = 0;
} else
{
plug = m_PlayState.Chn[nChn].pModInstrument->nMixPlug;
}
}
return plug;
}
// Retrieve the plugin that is associated with the channel's current instrument.
// No plugin is returned if the channel is muted or if the instrument doesn't have a MIDI channel set up,
// As this is meant to be used with instrument plugins.
IMixPlugin *CSoundFile::GetChannelInstrumentPlugin(CHANNELINDEX chn) const
//------------------------------------------------------------------------
{
#ifndef NO_PLUGINS
if(m_PlayState.Chn[chn].dwFlags[CHN_MUTE | CHN_SYNCMUTE])
{
// Don't process portamento on muted channels. Note that this might have a side-effect
// on other channels which trigger notes on the same MIDI channel of the same plugin,
// as those won't be pitch-bent anymore.
return nullptr;
}
if(m_PlayState.Chn[chn].HasMIDIOutput())
{
const ModInstrument *pIns = m_PlayState.Chn[chn].pModInstrument;
// Instrument sends to a MIDI channel
if(pIns->nMixPlug != 0 && pIns->nMixPlug <= MAX_MIXPLUGINS)
{
return m_MixPlugins[pIns->nMixPlug - 1].pMixPlugin;
}
}
#else
MPT_UNREFERENCED_PARAMETER(chn);
#endif // NO_PLUGINS
return nullptr;
}
// Get the MIDI channel currently associated with a given tracker channel
uint8 CSoundFile::GetBestMidiChannel(CHANNELINDEX nChn) const
//-----------------------------------------------------------
{
if(nChn >= MAX_CHANNELS)
{
return 0;
}
const ModInstrument *ins = m_PlayState.Chn[nChn].pModInstrument;
if(ins != nullptr)
{
if(ins->nMidiChannel == MidiMappedChannel)
{
// For mapped channels, return their pattern channel, modulo 16 (because there are only 16 MIDI channels)
return (m_PlayState.Chn[nChn].nMasterChn ? (m_PlayState.Chn[nChn].nMasterChn - 1) : nChn) % 16;
} else if(ins->HasValidMIDIChannel())
{
return (ins->nMidiChannel - 1) & 0x0F;
}
}
return 0;
}
void CSoundFile::HandlePatternTransitionEvents()
//----------------------------------------------
{
if (!m_PlayState.m_bPatternTransitionOccurred)
return;
// MPT sequence override
if(m_PlayState.m_nSeqOverride != ORDERINDEX_INVALID && m_PlayState.m_nSeqOverride < Order.size())
{
if(m_SongFlags[SONG_PATTERNLOOP])
{
m_PlayState.m_nPattern = Order[m_PlayState.m_nSeqOverride];
}
m_PlayState.m_nNextOrder = m_PlayState.m_nSeqOverride;
m_PlayState.m_nSeqOverride = ORDERINDEX_INVALID;
}
// Channel mutes
#ifdef MODPLUG_TRACKER
for (CHANNELINDEX chan = 0; chan < GetNumChannels(); chan++)
{
if (m_bChannelMuteTogglePending[chan])
{
if(GetpModDoc())
{
GetpModDoc()->MuteChannel(chan, !GetpModDoc()->IsChannelMuted(chan));
}
m_bChannelMuteTogglePending[chan] = false;
}
}
#endif // MODPLUG_TRACKER
m_PlayState.m_bPatternTransitionOccurred = false;
}
// Update time signatures (global or pattern-specific). Don't forget to call this when changing the RPB/RPM settings anywhere!
void CSoundFile::UpdateTimeSignature()
//------------------------------------
{
if(!Patterns.IsValidIndex(m_PlayState.m_nPattern) || !Patterns[m_PlayState.m_nPattern].GetOverrideSignature())
{
m_PlayState.m_nCurrentRowsPerBeat = m_nDefaultRowsPerBeat;
m_PlayState.m_nCurrentRowsPerMeasure = m_nDefaultRowsPerMeasure;
} else
{
m_PlayState.m_nCurrentRowsPerBeat = Patterns[m_PlayState.m_nPattern].GetRowsPerBeat();
m_PlayState.m_nCurrentRowsPerMeasure = Patterns[m_PlayState.m_nPattern].GetRowsPerMeasure();
}
}
void CSoundFile::PortamentoMPT(ModChannel* pChn, int param)
//---------------------------------------------------------
{
//Behavior: Modifies portamento by param-steps on every tick.
//Note that step meaning depends on tuning.
pChn->m_PortamentoFineSteps += param;
pChn->m_CalculateFreq = true;
}
void CSoundFile::PortamentoFineMPT(ModChannel* pChn, int param)
//-------------------------------------------------------------
{
//Behavior: Divides portamento change between ticks/row. For example
//if Ticks/row == 6, and param == +-6, portamento goes up/down by one tuning-dependent
//fine step every tick.
if(m_PlayState.m_nTickCount == 0)
pChn->nOldFinePortaUpDown = 0;
const int tickParam = static_cast<int>((m_PlayState.m_nTickCount + 1.0) * param / m_PlayState.m_nMusicSpeed);
pChn->m_PortamentoFineSteps += (param >= 0) ? tickParam - pChn->nOldFinePortaUpDown : tickParam + pChn->nOldFinePortaUpDown;
if(m_PlayState.m_nTickCount + 1 == m_PlayState.m_nMusicSpeed)
pChn->nOldFinePortaUpDown = static_cast<int8>(mpt::abs(param));
else
pChn->nOldFinePortaUpDown = static_cast<int8>(mpt::abs(tickParam));
pChn->m_CalculateFreq = true;
}
void CSoundFile::PortamentoExtraFineMPT(ModChannel* pChn, int param)
//------------------------------------------------------------------
{
// This kinda behaves like regular fine portamento.
// It changes the pitch by n finetune steps on the first tick.
if(pChn->isFirstTick)
{
pChn->m_PortamentoFineSteps += param;
pChn->m_CalculateFreq = true;
}
}
OPENMPT_NAMESPACE_END
|