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
|
/*
==============================================================================
This file is part of the JUCE framework examples.
Copyright (c) Raw Material Software Limited
The code included in this file is provided under the terms of the ISC license
http://www.isc.org/downloads/software-support-policy/isc-license. Permission
to use, copy, modify, and/or distribute this software for any purpose with or
without fee is hereby granted provided that the above copyright notice and
this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
==============================================================================
*/
/*******************************************************************************
The block below describes the properties of this PIP. A PIP is a short snippet
of code that can be read by the Projucer and used to generate a JUCE project.
BEGIN_JUCE_PIP_METADATA
name: SamplerPlugin
version: 1.0.0
vendor: JUCE
website: http://juce.com
description: Sampler audio plugin.
dependencies: juce_audio_basics, juce_audio_devices, juce_audio_formats,
juce_audio_plugin_client, juce_audio_processors,
juce_audio_utils, juce_core, juce_data_structures,
juce_events, juce_graphics, juce_gui_basics, juce_gui_extra
exporters: xcode_mac, vs2022
moduleFlags: JUCE_STRICT_REFCOUNTEDPOINTER=1
type: AudioProcessor
mainClass: SamplerAudioProcessor
useLocalCopy: 1
pluginCharacteristics: pluginIsSynth, pluginWantsMidiIn
END_JUCE_PIP_METADATA
*******************************************************************************/
#pragma once
#include "../Assets/DemoUtilities.h"
#include <array>
#include <atomic>
#include <memory>
#include <vector>
#include <tuple>
#include <iomanip>
#include <sstream>
#include <functional>
#include <mutex>
namespace IDs
{
#define DECLARE_ID(name) const juce::Identifier name (#name);
DECLARE_ID (DATA_MODEL)
DECLARE_ID (sampleReader)
DECLARE_ID (centreFrequencyHz)
DECLARE_ID (loopMode)
DECLARE_ID (loopPointsSeconds)
DECLARE_ID (MPE_SETTINGS)
DECLARE_ID (synthVoices)
DECLARE_ID (voiceStealingEnabled)
DECLARE_ID (legacyModeEnabled)
DECLARE_ID (mpeZoneLayout)
DECLARE_ID (legacyFirstChannel)
DECLARE_ID (legacyLastChannel)
DECLARE_ID (legacyPitchbendRange)
DECLARE_ID (VISIBLE_RANGE)
DECLARE_ID (totalRange)
DECLARE_ID (visibleRange)
#undef DECLARE_ID
} // namespace IDs
enum class LoopMode
{
none,
forward,
pingpong
};
// We want to send type-erased commands to the audio thread, but we also
// want those commands to contain move-only resources, so that we can
// construct resources on the gui thread, and then transfer ownership
// cheaply to the audio thread. We can't do this with std::function
// because it enforces that functions are copy-constructible.
// Therefore, we use a very simple templated type-eraser here.
template <typename Proc>
struct Command
{
virtual ~Command() noexcept = default;
virtual void run (Proc& proc) = 0;
};
template <typename Proc, typename Func>
class TemplateCommand final : public Command<Proc>,
private Func
{
public:
template <typename FuncPrime>
explicit TemplateCommand (FuncPrime&& funcPrime)
: Func (std::forward<FuncPrime> (funcPrime))
{}
void run (Proc& proc) override { (*this) (proc); }
};
template <typename Proc>
class CommandFifo final
{
public:
explicit CommandFifo (int size)
: buffer ((size_t) size),
abstractFifo (size)
{}
CommandFifo()
: CommandFifo (1024)
{}
template <typename Item>
void push (Item&& item) noexcept
{
auto command = makeCommand (std::forward<Item> (item));
abstractFifo.write (1).forEach ([&] (int index)
{
buffer[size_t (index)] = std::move (command);
});
}
void call (Proc& proc) noexcept
{
abstractFifo.read (abstractFifo.getNumReady()).forEach ([&] (int index)
{
buffer[size_t (index)]->run (proc);
});
}
private:
template <typename Func>
static std::unique_ptr<Command<Proc>> makeCommand (Func&& func)
{
using Decayed = std::decay_t<Func>;
return std::make_unique<TemplateCommand<Proc, Decayed>> (std::forward<Func> (func));
}
std::vector<std::unique_ptr<Command<Proc>>> buffer;
AbstractFifo abstractFifo;
};
//==============================================================================
// Represents the constant parts of an audio sample: its name, sample rate,
// length, and the audio sample data itself.
// Samples might be pretty big, so we'll keep shared_ptrs to them most of the
// time, to reduce duplication and copying.
class Sample final
{
public:
Sample (AudioFormatReader& source, double maxSampleLengthSecs)
: sourceSampleRate (source.sampleRate),
length (jmin (int (source.lengthInSamples),
int (maxSampleLengthSecs * sourceSampleRate))),
data (jmin (2, int (source.numChannels)), length + 4)
{
if (length == 0)
throw std::runtime_error ("Unable to load sample");
source.read (&data, 0, length + 4, 0, true, true);
}
double getSampleRate() const { return sourceSampleRate; }
int getLength() const { return length; }
const AudioBuffer<float>& getBuffer() const { return data; }
private:
double sourceSampleRate;
int length;
AudioBuffer<float> data;
};
//==============================================================================
// A class which contains all the information related to sample-playback, such
// as sample data, loop points, and loop kind.
// It is expected that multiple sampler voices will maintain pointers to a
// single instance of this class, to avoid redundant duplication of sample
// data in memory.
class MPESamplerSound final
{
public:
void setSample (std::unique_ptr<Sample> value)
{
sample = std::move (value);
setLoopPointsInSeconds (loopPoints);
}
Sample* getSample() const
{
return sample.get();
}
void setLoopPointsInSeconds (Range<double> value)
{
loopPoints = sample == nullptr ? value
: Range<double> (0, sample->getLength() / sample->getSampleRate())
.constrainRange (value);
}
Range<double> getLoopPointsInSeconds() const
{
return loopPoints;
}
void setCentreFrequencyInHz (double centre)
{
centreFrequencyInHz = centre;
}
double getCentreFrequencyInHz() const
{
return centreFrequencyInHz;
}
void setLoopMode (LoopMode type)
{
loopMode = type;
}
LoopMode getLoopMode() const
{
return loopMode;
}
private:
std::unique_ptr<Sample> sample;
double centreFrequencyInHz { 440.0 };
Range<double> loopPoints;
LoopMode loopMode { LoopMode::none };
};
//==============================================================================
class MPESamplerVoice final : public MPESynthesiserVoice
{
public:
explicit MPESamplerVoice (std::shared_ptr<const MPESamplerSound> sound)
: samplerSound (std::move (sound))
{
jassert (samplerSound != nullptr);
}
void noteStarted() override
{
jassert (currentlyPlayingNote.isValid());
jassert (currentlyPlayingNote.keyState == MPENote::keyDown
|| currentlyPlayingNote.keyState == MPENote::keyDownAndSustained);
level .setTargetValue (currentlyPlayingNote.noteOnVelocity.asUnsignedFloat());
frequency.setTargetValue (currentlyPlayingNote.getFrequencyInHertz());
auto loopPoints = samplerSound->getLoopPointsInSeconds();
loopBegin.setTargetValue (loopPoints.getStart() * samplerSound->getSample()->getSampleRate());
loopEnd .setTargetValue (loopPoints.getEnd() * samplerSound->getSample()->getSampleRate());
for (auto smoothed : { &level, &frequency, &loopBegin, &loopEnd })
smoothed->reset (currentSampleRate, smoothingLengthInSeconds);
previousPressure = currentlyPlayingNote.pressure.asUnsignedFloat();
currentSamplePos = 0.0;
tailOff = 0.0;
}
void noteStopped (bool allowTailOff) override
{
jassert (currentlyPlayingNote.keyState == MPENote::off);
if (allowTailOff && approximatelyEqual (tailOff, 0.0))
tailOff = 1.0;
else
stopNote();
}
void notePressureChanged() override
{
const auto currentPressure = static_cast<double> (currentlyPlayingNote.pressure.asUnsignedFloat());
const auto deltaPressure = currentPressure - previousPressure;
level.setTargetValue (jlimit (0.0, 1.0, level.getCurrentValue() + deltaPressure));
previousPressure = currentPressure;
}
void notePitchbendChanged() override
{
frequency.setTargetValue (currentlyPlayingNote.getFrequencyInHertz());
}
void noteTimbreChanged() override {}
void noteKeyStateChanged() override {}
void renderNextBlock (AudioBuffer<float>& outputBuffer,
int startSample,
int numSamples) override
{
render (outputBuffer, startSample, numSamples);
}
void renderNextBlock (AudioBuffer<double>& outputBuffer,
int startSample,
int numSamples) override
{
render (outputBuffer, startSample, numSamples);
}
double getCurrentSamplePosition() const
{
return currentSamplePos;
}
private:
template <typename Element>
void render (AudioBuffer<Element>& outputBuffer, int startSample, int numSamples)
{
jassert (samplerSound->getSample() != nullptr);
auto loopPoints = samplerSound->getLoopPointsInSeconds();
loopBegin.setTargetValue (loopPoints.getStart() * samplerSound->getSample()->getSampleRate());
loopEnd .setTargetValue (loopPoints.getEnd() * samplerSound->getSample()->getSampleRate());
auto& data = samplerSound->getSample()->getBuffer();
auto inL = data.getReadPointer (0);
auto inR = data.getNumChannels() > 1 ? data.getReadPointer (1) : nullptr;
auto outL = outputBuffer.getWritePointer (0, startSample);
if (outL == nullptr)
return;
auto outR = outputBuffer.getNumChannels() > 1 ? outputBuffer.getWritePointer (1, startSample)
: nullptr;
size_t writePos = 0;
while (--numSamples >= 0 && renderNextSample (inL, inR, outL, outR, writePos))
writePos += 1;
}
template <typename Element>
bool renderNextSample (const float* inL,
const float* inR,
Element* outL,
Element* outR,
size_t writePos)
{
auto currentLevel = level.getNextValue();
auto currentFrequency = frequency.getNextValue();
auto currentLoopBegin = loopBegin.getNextValue();
auto currentLoopEnd = loopEnd.getNextValue();
if (isTailingOff())
{
currentLevel *= tailOff;
tailOff *= 0.9999;
if (tailOff < 0.005)
{
stopNote();
return false;
}
}
auto pos = (int) currentSamplePos;
auto nextPos = pos + 1;
auto alpha = (Element) (currentSamplePos - pos);
auto invAlpha = 1.0f - alpha;
// just using a very simple linear interpolation here..
auto l = static_cast<Element> (currentLevel * (inL[pos] * invAlpha + inL[nextPos] * alpha));
auto r = static_cast<Element> ((inR != nullptr) ? currentLevel * (inR[pos] * invAlpha + inR[nextPos] * alpha)
: l);
if (outR != nullptr)
{
outL[writePos] += l;
outR[writePos] += r;
}
else
{
outL[writePos] += (l + r) * 0.5f;
}
std::tie (currentSamplePos, currentDirection) = getNextState (currentFrequency,
currentLoopBegin,
currentLoopEnd);
if (currentSamplePos > samplerSound->getSample()->getLength())
{
stopNote();
return false;
}
return true;
}
double getSampleValue() const;
bool isTailingOff() const
{
return ! approximatelyEqual (tailOff, 0.0);
}
void stopNote()
{
clearCurrentNote();
currentSamplePos = 0.0;
}
enum class Direction
{
forward,
backward
};
std::tuple<double, Direction> getNextState (double freq,
double begin,
double end) const
{
auto nextPitchRatio = freq / samplerSound->getCentreFrequencyInHz();
auto nextSamplePos = currentSamplePos;
auto nextDirection = currentDirection;
// Move the current sample pos in the correct direction
switch (currentDirection)
{
case Direction::forward:
nextSamplePos += nextPitchRatio;
break;
case Direction::backward:
nextSamplePos -= nextPitchRatio;
break;
default:
break;
}
// Update current sample position, taking loop mode into account
// If the loop mode was changed while we were travelling backwards, deal
// with it gracefully.
if (nextDirection == Direction::backward && nextSamplePos < begin)
{
nextSamplePos = begin;
nextDirection = Direction::forward;
return std::tuple<double, Direction> (nextSamplePos, nextDirection);
}
if (samplerSound->getLoopMode() == LoopMode::none)
return std::tuple<double, Direction> (nextSamplePos, nextDirection);
if (nextDirection == Direction::forward && end < nextSamplePos && !isTailingOff())
{
if (samplerSound->getLoopMode() == LoopMode::forward)
nextSamplePos = begin;
else if (samplerSound->getLoopMode() == LoopMode::pingpong)
{
nextSamplePos = end;
nextDirection = Direction::backward;
}
}
return std::tuple<double, Direction> (nextSamplePos, nextDirection);
}
std::shared_ptr<const MPESamplerSound> samplerSound;
SmoothedValue<double> level { 0 };
SmoothedValue<double> frequency { 0 };
SmoothedValue<double> loopBegin;
SmoothedValue<double> loopEnd;
double previousPressure { 0 };
double currentSamplePos { 0 };
double tailOff { 0 };
Direction currentDirection { Direction::forward };
double smoothingLengthInSeconds { 0.01 };
};
template <typename Contents>
class ReferenceCountingAdapter final : public ReferenceCountedObject
{
public:
template <typename... Args>
explicit ReferenceCountingAdapter (Args&&... args)
: contents (std::forward<Args> (args)...)
{}
const Contents& get() const
{
return contents;
}
Contents& get()
{
return contents;
}
private:
Contents contents;
};
template <typename Contents, typename... Args>
std::unique_ptr<ReferenceCountingAdapter<Contents>>
make_reference_counted (Args&&... args)
{
auto adapter = new ReferenceCountingAdapter<Contents> (std::forward<Args> (args)...);
return std::unique_ptr<ReferenceCountingAdapter<Contents>> (adapter);
}
//==============================================================================
inline std::unique_ptr<AudioFormatReader> makeAudioFormatReader (AudioFormatManager& manager,
const void* sampleData,
size_t dataSize)
{
return std::unique_ptr<AudioFormatReader> (manager.createReaderFor (std::make_unique<MemoryInputStream> (sampleData,
dataSize,
false)));
}
inline std::unique_ptr<AudioFormatReader> makeAudioFormatReader (AudioFormatManager& manager,
const File& file)
{
return std::unique_ptr<AudioFormatReader> (manager.createReaderFor (file));
}
//==============================================================================
class AudioFormatReaderFactory
{
public:
AudioFormatReaderFactory() = default;
AudioFormatReaderFactory (const AudioFormatReaderFactory&) = default;
AudioFormatReaderFactory (AudioFormatReaderFactory&&) = default;
AudioFormatReaderFactory& operator= (const AudioFormatReaderFactory&) = default;
AudioFormatReaderFactory& operator= (AudioFormatReaderFactory&&) = default;
virtual ~AudioFormatReaderFactory() noexcept = default;
virtual std::unique_ptr<AudioFormatReader> make (AudioFormatManager&) const = 0;
virtual std::unique_ptr<AudioFormatReaderFactory> clone() const = 0;
};
//==============================================================================
class MemoryAudioFormatReaderFactory final : public AudioFormatReaderFactory
{
public:
explicit MemoryAudioFormatReaderFactory (MemoryBlock mb)
: memoryBlock (std::make_shared<MemoryBlock> (std::move (mb)))
{
}
std::unique_ptr<AudioFormatReader> make (AudioFormatManager& manager) const override
{
return makeAudioFormatReader (manager, memoryBlock->getData(), memoryBlock->getSize());
}
std::unique_ptr<AudioFormatReaderFactory> clone() const override
{
return std::unique_ptr<AudioFormatReaderFactory> (new MemoryAudioFormatReaderFactory (*this));
}
private:
std::shared_ptr<MemoryBlock> memoryBlock;
};
//==============================================================================
class FileAudioFormatReaderFactory final : public AudioFormatReaderFactory
{
public:
explicit FileAudioFormatReaderFactory (File fileIn)
: file (std::move (fileIn))
{}
std::unique_ptr<AudioFormatReader> make (AudioFormatManager& manager) const override
{
return makeAudioFormatReader (manager, file);
}
std::unique_ptr<AudioFormatReaderFactory> clone() const override
{
return std::unique_ptr<AudioFormatReaderFactory> (new FileAudioFormatReaderFactory (*this));
}
private:
File file;
};
namespace juce
{
template<>
struct VariantConverter<LoopMode>
{
static LoopMode fromVar (const var& v)
{
return static_cast<LoopMode> (int (v));
}
static var toVar (LoopMode loopMode)
{
return static_cast<int> (loopMode);
}
};
template <typename Wrapped>
struct GenericVariantConverter
{
static Wrapped fromVar (const var& v)
{
auto cast = dynamic_cast<ReferenceCountingAdapter<Wrapped>*> (v.getObject());
jassert (cast != nullptr);
return cast->get();
}
static var toVar (Wrapped range)
{
return { make_reference_counted<Wrapped> (std::move (range)).release() };
}
};
template <typename Numeric>
struct VariantConverter<Range<Numeric>> final : GenericVariantConverter<Range<Numeric>> {};
template<>
struct VariantConverter<MPEZoneLayout> final : GenericVariantConverter<MPEZoneLayout> {};
template<>
struct VariantConverter<std::shared_ptr<AudioFormatReaderFactory>> final
: GenericVariantConverter<std::shared_ptr<AudioFormatReaderFactory>>
{};
} // namespace juce
//==============================================================================
class VisibleRangeDataModel final : private ValueTree::Listener
{
public:
class Listener
{
public:
virtual ~Listener() noexcept = default;
virtual void totalRangeChanged (Range<double>) {}
virtual void visibleRangeChanged (Range<double>) {}
};
VisibleRangeDataModel()
: VisibleRangeDataModel (ValueTree (IDs::VISIBLE_RANGE))
{}
explicit VisibleRangeDataModel (const ValueTree& vt)
: valueTree (vt),
totalRange (valueTree, IDs::totalRange, nullptr),
visibleRange (valueTree, IDs::visibleRange, nullptr)
{
jassert (valueTree.hasType (IDs::VISIBLE_RANGE));
valueTree.addListener (this);
}
VisibleRangeDataModel (const VisibleRangeDataModel& other)
: VisibleRangeDataModel (other.valueTree)
{}
VisibleRangeDataModel& operator= (const VisibleRangeDataModel& other)
{
auto copy (other);
swap (copy);
return *this;
}
Range<double> getTotalRange() const
{
return totalRange;
}
void setTotalRange (Range<double> value, UndoManager* undoManager)
{
totalRange.setValue (value, undoManager);
setVisibleRange (visibleRange, undoManager);
}
Range<double> getVisibleRange() const
{
return visibleRange;
}
void setVisibleRange (Range<double> value, UndoManager* undoManager)
{
visibleRange.setValue (totalRange.get().constrainRange (value), undoManager);
}
void addListener (Listener& listener)
{
listenerList.add (&listener);
}
void removeListener (Listener& listener)
{
listenerList.remove (&listener);
}
void swap (VisibleRangeDataModel& other) noexcept
{
using std::swap;
swap (other.valueTree, valueTree);
}
private:
void valueTreePropertyChanged (ValueTree&, const Identifier& property) override
{
if (property == IDs::totalRange)
{
totalRange.forceUpdateOfCachedValue();
listenerList.call ([this] (Listener& l) { l.totalRangeChanged (totalRange); });
}
else if (property == IDs::visibleRange)
{
visibleRange.forceUpdateOfCachedValue();
listenerList.call ([this] (Listener& l) { l.visibleRangeChanged (visibleRange); });
}
}
void valueTreeChildAdded (ValueTree&, ValueTree&) override { jassertfalse; }
void valueTreeChildRemoved (ValueTree&, ValueTree&, int) override { jassertfalse; }
void valueTreeChildOrderChanged (ValueTree&, int, int) override { jassertfalse; }
void valueTreeParentChanged (ValueTree&) override { jassertfalse; }
ValueTree valueTree;
CachedValue<Range<double>> totalRange;
CachedValue<Range<double>> visibleRange;
ListenerList<Listener> listenerList;
};
//==============================================================================
class MPESettingsDataModel final : private ValueTree::Listener
{
public:
class Listener
{
public:
virtual ~Listener() noexcept = default;
virtual void synthVoicesChanged (int) {}
virtual void voiceStealingEnabledChanged (bool) {}
virtual void legacyModeEnabledChanged (bool) {}
virtual void mpeZoneLayoutChanged (const MPEZoneLayout&) {}
virtual void legacyFirstChannelChanged (int) {}
virtual void legacyLastChannelChanged (int) {}
virtual void legacyPitchbendRangeChanged (int) {}
};
MPESettingsDataModel()
: MPESettingsDataModel (ValueTree (IDs::MPE_SETTINGS))
{}
explicit MPESettingsDataModel (const ValueTree& vt)
: valueTree (vt),
synthVoices (valueTree, IDs::synthVoices, nullptr, 15),
voiceStealingEnabled (valueTree, IDs::voiceStealingEnabled, nullptr, false),
legacyModeEnabled (valueTree, IDs::legacyModeEnabled, nullptr, true),
mpeZoneLayout (valueTree, IDs::mpeZoneLayout, nullptr, {}),
legacyFirstChannel (valueTree, IDs::legacyFirstChannel, nullptr, 1),
legacyLastChannel (valueTree, IDs::legacyLastChannel, nullptr, 15),
legacyPitchbendRange (valueTree, IDs::legacyPitchbendRange, nullptr, 48)
{
jassert (valueTree.hasType (IDs::MPE_SETTINGS));
valueTree.addListener (this);
}
MPESettingsDataModel (const MPESettingsDataModel& other)
: MPESettingsDataModel (other.valueTree)
{}
MPESettingsDataModel& operator= (const MPESettingsDataModel& other)
{
auto copy (other);
swap (copy);
return *this;
}
int getSynthVoices() const
{
return synthVoices;
}
void setSynthVoices (int value, UndoManager* undoManager)
{
synthVoices.setValue (Range<int> (1, 20).clipValue (value), undoManager);
}
bool getVoiceStealingEnabled() const
{
return voiceStealingEnabled;
}
void setVoiceStealingEnabled (bool value, UndoManager* undoManager)
{
voiceStealingEnabled.setValue (value, undoManager);
}
bool getLegacyModeEnabled() const
{
return legacyModeEnabled;
}
void setLegacyModeEnabled (bool value, UndoManager* undoManager)
{
legacyModeEnabled.setValue (value, undoManager);
}
MPEZoneLayout getMPEZoneLayout() const
{
return mpeZoneLayout;
}
void setMPEZoneLayout (MPEZoneLayout value, UndoManager* undoManager)
{
mpeZoneLayout.setValue (value, undoManager);
}
int getLegacyFirstChannel() const
{
return legacyFirstChannel;
}
void setLegacyFirstChannel (int value, UndoManager* undoManager)
{
legacyFirstChannel.setValue (Range<int> (1, legacyLastChannel).clipValue (value), undoManager);
}
int getLegacyLastChannel() const
{
return legacyLastChannel;
}
void setLegacyLastChannel (int value, UndoManager* undoManager)
{
legacyLastChannel.setValue (Range<int> (legacyFirstChannel, 15).clipValue (value), undoManager);
}
int getLegacyPitchbendRange() const
{
return legacyPitchbendRange;
}
void setLegacyPitchbendRange (int value, UndoManager* undoManager)
{
legacyPitchbendRange.setValue (Range<int> (0, 95).clipValue (value), undoManager);
}
void addListener (Listener& listener)
{
listenerList.add (&listener);
}
void removeListener (Listener& listener)
{
listenerList.remove (&listener);
}
void swap (MPESettingsDataModel& other) noexcept
{
using std::swap;
swap (other.valueTree, valueTree);
}
private:
void valueTreePropertyChanged (ValueTree&, const Identifier& property) override
{
if (property == IDs::synthVoices)
{
synthVoices.forceUpdateOfCachedValue();
listenerList.call ([this] (Listener& l) { l.synthVoicesChanged (synthVoices); });
}
else if (property == IDs::voiceStealingEnabled)
{
voiceStealingEnabled.forceUpdateOfCachedValue();
listenerList.call ([this] (Listener& l) { l.voiceStealingEnabledChanged (voiceStealingEnabled); });
}
else if (property == IDs::legacyModeEnabled)
{
legacyModeEnabled.forceUpdateOfCachedValue();
listenerList.call ([this] (Listener& l) { l.legacyModeEnabledChanged (legacyModeEnabled); });
}
else if (property == IDs::mpeZoneLayout)
{
mpeZoneLayout.forceUpdateOfCachedValue();
listenerList.call ([this] (Listener& l) { l.mpeZoneLayoutChanged (mpeZoneLayout); });
}
else if (property == IDs::legacyFirstChannel)
{
legacyFirstChannel.forceUpdateOfCachedValue();
listenerList.call ([this] (Listener& l) { l.legacyFirstChannelChanged (legacyFirstChannel); });
}
else if (property == IDs::legacyLastChannel)
{
legacyLastChannel.forceUpdateOfCachedValue();
listenerList.call ([this] (Listener& l) { l.legacyLastChannelChanged (legacyLastChannel); });
}
else if (property == IDs::legacyPitchbendRange)
{
legacyPitchbendRange.forceUpdateOfCachedValue();
listenerList.call ([this] (Listener& l) { l.legacyPitchbendRangeChanged (legacyPitchbendRange); });
}
}
void valueTreeChildAdded (ValueTree&, ValueTree&) override { jassertfalse; }
void valueTreeChildRemoved (ValueTree&, ValueTree&, int) override { jassertfalse; }
void valueTreeChildOrderChanged (ValueTree&, int, int) override { jassertfalse; }
void valueTreeParentChanged (ValueTree&) override { jassertfalse; }
ValueTree valueTree;
CachedValue<int> synthVoices;
CachedValue<bool> voiceStealingEnabled;
CachedValue<bool> legacyModeEnabled;
CachedValue<MPEZoneLayout> mpeZoneLayout;
CachedValue<int> legacyFirstChannel;
CachedValue<int> legacyLastChannel;
CachedValue<int> legacyPitchbendRange;
ListenerList<Listener> listenerList;
};
//==============================================================================
class DataModel final : private ValueTree::Listener
{
public:
class Listener
{
public:
virtual ~Listener() noexcept = default;
virtual void sampleReaderChanged (std::shared_ptr<AudioFormatReaderFactory>) {}
virtual void centreFrequencyHzChanged (double) {}
virtual void loopModeChanged (LoopMode) {}
virtual void loopPointsSecondsChanged (Range<double>) {}
};
explicit DataModel (AudioFormatManager& audioFormatManagerIn)
: DataModel (audioFormatManagerIn, ValueTree (IDs::DATA_MODEL))
{}
DataModel (AudioFormatManager& audioFormatManagerIn, const ValueTree& vt)
: audioFormatManager (&audioFormatManagerIn),
valueTree (vt),
sampleReader (valueTree, IDs::sampleReader, nullptr),
centreFrequencyHz (valueTree, IDs::centreFrequencyHz, nullptr),
loopMode (valueTree, IDs::loopMode, nullptr, LoopMode::none),
loopPointsSeconds (valueTree, IDs::loopPointsSeconds, nullptr)
{
jassert (valueTree.hasType (IDs::DATA_MODEL));
valueTree.addListener (this);
}
DataModel (const DataModel& other)
: DataModel (*other.audioFormatManager, other.valueTree)
{}
DataModel& operator= (const DataModel& other)
{
auto copy (other);
swap (copy);
return *this;
}
std::unique_ptr<AudioFormatReader> getSampleReader() const
{
return sampleReader != nullptr ? sampleReader.get()->make (*audioFormatManager) : nullptr;
}
void setSampleReader (std::unique_ptr<AudioFormatReaderFactory> readerFactory,
UndoManager* undoManager)
{
sampleReader.setValue (std::move (readerFactory), undoManager);
setLoopPointsSeconds (Range<double> (0, getSampleLengthSeconds()).constrainRange (loopPointsSeconds),
undoManager);
}
double getSampleLengthSeconds() const
{
if (auto r = getSampleReader())
return (double) r->lengthInSamples / r->sampleRate;
return 1.0;
}
double getCentreFrequencyHz() const
{
return centreFrequencyHz;
}
void setCentreFrequencyHz (double value, UndoManager* undoManager)
{
centreFrequencyHz.setValue (Range<double> (20, 20000).clipValue (value),
undoManager);
}
LoopMode getLoopMode() const
{
return loopMode;
}
void setLoopMode (LoopMode value, UndoManager* undoManager)
{
loopMode.setValue (value, undoManager);
}
Range<double> getLoopPointsSeconds() const
{
return loopPointsSeconds;
}
void setLoopPointsSeconds (Range<double> value, UndoManager* undoManager)
{
loopPointsSeconds.setValue (Range<double> (0, getSampleLengthSeconds()).constrainRange (value),
undoManager);
}
MPESettingsDataModel mpeSettings()
{
return MPESettingsDataModel (valueTree.getOrCreateChildWithName (IDs::MPE_SETTINGS, nullptr));
}
void addListener (Listener& listener)
{
listenerList.add (&listener);
}
void removeListener (Listener& listener)
{
listenerList.remove (&listener);
}
void swap (DataModel& other) noexcept
{
using std::swap;
swap (other.valueTree, valueTree);
}
AudioFormatManager& getAudioFormatManager() const
{
return *audioFormatManager;
}
private:
void valueTreePropertyChanged (ValueTree&, const Identifier& property) override
{
if (property == IDs::sampleReader)
{
sampleReader.forceUpdateOfCachedValue();
listenerList.call ([this] (Listener& l) { l.sampleReaderChanged (sampleReader); });
}
else if (property == IDs::centreFrequencyHz)
{
centreFrequencyHz.forceUpdateOfCachedValue();
listenerList.call ([this] (Listener& l) { l.centreFrequencyHzChanged (centreFrequencyHz); });
}
else if (property == IDs::loopMode)
{
loopMode.forceUpdateOfCachedValue();
listenerList.call ([this] (Listener& l) { l.loopModeChanged (loopMode); });
}
else if (property == IDs::loopPointsSeconds)
{
loopPointsSeconds.forceUpdateOfCachedValue();
listenerList.call ([this] (Listener& l) { l.loopPointsSecondsChanged (loopPointsSeconds); });
}
}
void valueTreeChildAdded (ValueTree&, ValueTree&) override {}
void valueTreeChildRemoved (ValueTree&, ValueTree&, int) override { jassertfalse; }
void valueTreeChildOrderChanged (ValueTree&, int, int) override { jassertfalse; }
void valueTreeParentChanged (ValueTree&) override { jassertfalse; }
AudioFormatManager* audioFormatManager;
ValueTree valueTree;
CachedValue<std::shared_ptr<AudioFormatReaderFactory>> sampleReader;
CachedValue<double> centreFrequencyHz;
CachedValue<LoopMode> loopMode;
CachedValue<Range<double>> loopPointsSeconds;
ListenerList<Listener> listenerList;
};
namespace
{
void initialiseComboBoxWithConsecutiveIntegers (Component& owner,
ComboBox& comboBox,
Label& label,
int firstValue,
int numValues,
int valueToSelect)
{
for (auto i = 0; i < numValues; ++i)
comboBox.addItem (String (i + firstValue), i + 1);
comboBox.setSelectedId (valueToSelect - firstValue + 1);
label.attachToComponent (&comboBox, true);
owner.addAndMakeVisible (comboBox);
}
constexpr int controlHeight = 24;
constexpr int controlSeparation = 6;
} // namespace
//==============================================================================
class MPELegacySettingsComponent final : public Component,
private MPESettingsDataModel::Listener
{
public:
explicit MPELegacySettingsComponent (const MPESettingsDataModel& model,
UndoManager& um)
: dataModel (model),
undoManager (&um)
{
dataModel.addListener (*this);
initialiseComboBoxWithConsecutiveIntegers (*this, legacyStartChannel, legacyStartChannelLabel, 1, 16, 1);
initialiseComboBoxWithConsecutiveIntegers (*this, legacyEndChannel, legacyEndChannelLabel, 1, 16, 16);
initialiseComboBoxWithConsecutiveIntegers (*this, legacyPitchbendRange, legacyPitchbendRangeLabel, 0, 96, 2);
legacyStartChannel.onChange = [this]
{
if (isLegacyModeValid())
{
undoManager->beginNewTransaction();
dataModel.setLegacyFirstChannel (getFirstChannel(), undoManager);
}
};
legacyEndChannel.onChange = [this]
{
if (isLegacyModeValid())
{
undoManager->beginNewTransaction();
dataModel.setLegacyLastChannel (getLastChannel(), undoManager);
}
};
legacyPitchbendRange.onChange = [this]
{
if (isLegacyModeValid())
{
undoManager->beginNewTransaction();
dataModel.setLegacyPitchbendRange (legacyPitchbendRange.getText().getIntValue(), undoManager);
}
};
}
int getMinHeight() const
{
return (controlHeight * 3) + (controlSeparation * 2);
}
private:
void resized() override
{
Rectangle<int> r (proportionOfWidth (0.65f), 0, proportionOfWidth (0.25f), getHeight());
for (auto& comboBox : { &legacyStartChannel, &legacyEndChannel, &legacyPitchbendRange })
{
comboBox->setBounds (r.removeFromTop (controlHeight));
r.removeFromTop (controlSeparation);
}
}
bool isLegacyModeValid()
{
if (! areLegacyModeParametersValid())
{
handleInvalidLegacyModeParameters();
return false;
}
return true;
}
void legacyFirstChannelChanged (int value) override
{
legacyStartChannel.setSelectedId (value, dontSendNotification);
}
void legacyLastChannelChanged (int value) override
{
legacyEndChannel.setSelectedId (value, dontSendNotification);
}
void legacyPitchbendRangeChanged (int value) override
{
legacyPitchbendRange.setSelectedId (value + 1, dontSendNotification);
}
int getFirstChannel() const
{
return legacyStartChannel.getText().getIntValue();
}
int getLastChannel() const
{
return legacyEndChannel.getText().getIntValue();
}
bool areLegacyModeParametersValid() const
{
return getFirstChannel() <= getLastChannel();
}
void handleInvalidLegacyModeParameters()
{
auto options = MessageBoxOptions::makeOptionsOk (AlertWindow::WarningIcon,
"Invalid legacy mode channel layout",
"Cannot set legacy mode start/end channel:\n"
"The end channel must not be less than the start channel!",
"Got it");
messageBox = AlertWindow::showScopedAsync (options, nullptr);
}
MPESettingsDataModel dataModel;
ComboBox legacyStartChannel, legacyEndChannel, legacyPitchbendRange;
Label legacyStartChannelLabel { {}, "First channel" },
legacyEndChannelLabel { {}, "Last channel" },
legacyPitchbendRangeLabel { {}, "Pitchbend range (semitones)" };
UndoManager* undoManager;
ScopedMessageBox messageBox;
};
//==============================================================================
class MPENewSettingsComponent final : public Component,
private MPESettingsDataModel::Listener
{
public:
MPENewSettingsComponent (const MPESettingsDataModel& model,
UndoManager& um)
: dataModel (model),
undoManager (&um)
{
dataModel.addListener (*this);
addAndMakeVisible (isLowerZoneButton);
isLowerZoneButton.setToggleState (true, NotificationType::dontSendNotification);
initialiseComboBoxWithConsecutiveIntegers (*this, memberChannels, memberChannelsLabel, 0, 16, 15);
initialiseComboBoxWithConsecutiveIntegers (*this, masterPitchbendRange, masterPitchbendRangeLabel, 0, 96, 2);
initialiseComboBoxWithConsecutiveIntegers (*this, notePitchbendRange, notePitchbendRangeLabel, 0, 96, 48);
for (auto& button : { &setZoneButton, &clearAllZonesButton })
addAndMakeVisible (button);
setZoneButton.onClick = [this]
{
auto isLowerZone = isLowerZoneButton.getToggleState();
auto numMemberChannels = memberChannels.getText().getIntValue();
auto perNotePb = notePitchbendRange.getText().getIntValue();
auto masterPb = masterPitchbendRange.getText().getIntValue();
if (isLowerZone)
zoneLayout.setLowerZone (numMemberChannels, perNotePb, masterPb);
else
zoneLayout.setUpperZone (numMemberChannels, perNotePb, masterPb);
undoManager->beginNewTransaction();
dataModel.setMPEZoneLayout (zoneLayout, undoManager);
};
clearAllZonesButton.onClick = [this]
{
zoneLayout.clearAllZones();
undoManager->beginNewTransaction();
dataModel.setMPEZoneLayout (zoneLayout, undoManager);
};
}
int getMinHeight() const
{
return (controlHeight * 6) + (controlSeparation * 6);
}
private:
void resized() override
{
Rectangle<int> r (proportionOfWidth (0.65f), 0, proportionOfWidth (0.25f), getHeight());
isLowerZoneButton.setBounds (r.removeFromTop (controlHeight));
r.removeFromTop (controlSeparation);
for (auto& comboBox : { &memberChannels, &masterPitchbendRange, ¬ePitchbendRange })
{
comboBox->setBounds (r.removeFromTop (controlHeight));
r.removeFromTop (controlSeparation);
}
r.removeFromTop (controlSeparation);
auto buttonLeft = proportionOfWidth (0.5f);
setZoneButton.setBounds (r.removeFromTop (controlHeight).withLeft (buttonLeft));
r.removeFromTop (controlSeparation);
clearAllZonesButton.setBounds (r.removeFromTop (controlHeight).withLeft (buttonLeft));
}
void mpeZoneLayoutChanged (const MPEZoneLayout& value) override
{
zoneLayout = value;
}
MPESettingsDataModel dataModel;
MPEZoneLayout zoneLayout;
ComboBox memberChannels, masterPitchbendRange, notePitchbendRange;
ToggleButton isLowerZoneButton { "Lower zone" };
Label memberChannelsLabel { {}, "Nr. of member channels" },
masterPitchbendRangeLabel { {}, "Master pitchbend range (semitones)" },
notePitchbendRangeLabel { {}, "Note pitchbend range (semitones)" };
TextButton setZoneButton { "Set zone" },
clearAllZonesButton { "Clear all zones" };
UndoManager* undoManager;
};
//==============================================================================
class MPESettingsComponent final : public Component,
private MPESettingsDataModel::Listener
{
public:
MPESettingsComponent (const MPESettingsDataModel& model,
UndoManager& um)
: dataModel (model),
legacySettings (dataModel, um),
newSettings (dataModel, um),
undoManager (&um)
{
dataModel.addListener (*this);
addAndMakeVisible (newSettings);
addChildComponent (legacySettings);
initialiseComboBoxWithConsecutiveIntegers (*this, numberOfVoices, numberOfVoicesLabel, 1, 20, 15);
numberOfVoices.onChange = [this]
{
undoManager->beginNewTransaction();
dataModel.setSynthVoices (numberOfVoices.getText().getIntValue(), undoManager);
};
for (auto& button : { &legacyModeEnabledToggle, &voiceStealingEnabledToggle })
{
addAndMakeVisible (button);
}
legacyModeEnabledToggle.onClick = [this]
{
undoManager->beginNewTransaction();
dataModel.setLegacyModeEnabled (legacyModeEnabledToggle.getToggleState(), undoManager);
};
voiceStealingEnabledToggle.onClick = [this]
{
undoManager->beginNewTransaction();
dataModel.setVoiceStealingEnabled (voiceStealingEnabledToggle.getToggleState(), undoManager);
};
}
private:
void resized() override
{
auto topHeight = jmax (legacySettings.getMinHeight(), newSettings.getMinHeight());
auto r = getLocalBounds();
r.removeFromTop (15);
auto top = r.removeFromTop (topHeight);
legacySettings.setBounds (top);
newSettings.setBounds (top);
r.removeFromLeft (proportionOfWidth (0.65f));
r = r.removeFromLeft (proportionOfWidth (0.25f));
auto toggleLeft = proportionOfWidth (0.25f);
legacyModeEnabledToggle.setBounds (r.removeFromTop (controlHeight).withLeft (toggleLeft));
r.removeFromTop (controlSeparation);
voiceStealingEnabledToggle.setBounds (r.removeFromTop (controlHeight).withLeft (toggleLeft));
r.removeFromTop (controlSeparation);
numberOfVoices.setBounds (r.removeFromTop (controlHeight));
}
void legacyModeEnabledChanged (bool value) override
{
legacySettings.setVisible (value);
newSettings.setVisible (! value);
legacyModeEnabledToggle.setToggleState (value, dontSendNotification);
}
void voiceStealingEnabledChanged (bool value) override
{
voiceStealingEnabledToggle.setToggleState (value, dontSendNotification);
}
void synthVoicesChanged (int value) override
{
numberOfVoices.setSelectedId (value, dontSendNotification);
}
MPESettingsDataModel dataModel;
MPELegacySettingsComponent legacySettings;
MPENewSettingsComponent newSettings;
ToggleButton legacyModeEnabledToggle { "Enable Legacy Mode" },
voiceStealingEnabledToggle { "Enable synth voice stealing" };
ComboBox numberOfVoices;
Label numberOfVoicesLabel { {}, "Number of synth voices" };
UndoManager* undoManager;
};
//==============================================================================
class LoopPointMarker final : public Component
{
public:
using MouseCallback = std::function<void (LoopPointMarker&, const MouseEvent&)>;
LoopPointMarker (String marker,
MouseCallback onMouseDownIn,
MouseCallback onMouseDragIn,
MouseCallback onMouseUpIn)
: text (std::move (marker)),
onMouseDown (std::move (onMouseDownIn)),
onMouseDrag (std::move (onMouseDragIn)),
onMouseUp (std::move (onMouseUpIn))
{
setMouseCursor (MouseCursor::LeftRightResizeCursor);
}
private:
void resized() override
{
auto height = 20;
auto triHeight = 6;
auto bounds = getLocalBounds();
Path newPath;
newPath.addRectangle (bounds.removeFromBottom (height));
newPath.startNewSubPath (bounds.getBottomLeft().toFloat());
newPath.lineTo (bounds.getBottomRight().toFloat());
Point<float> apex (static_cast<float> (bounds.getX() + (bounds.getWidth() / 2)),
static_cast<float> (bounds.getBottom() - triHeight));
newPath.lineTo (apex);
newPath.closeSubPath();
newPath.addLineSegment (Line<float> (apex, Point<float> (apex.getX(), 0)), 1);
path = newPath;
}
void paint (Graphics& g) override
{
g.setColour (Colours::deepskyblue);
g.fillPath (path);
auto height = 20;
g.setColour (Colours::white);
g.drawText (text, getLocalBounds().removeFromBottom (height), Justification::centred);
}
bool hitTest (int x, int y) override
{
return path.contains ((float) x, (float) y);
}
void mouseDown (const MouseEvent& e) override
{
onMouseDown (*this, e);
}
void mouseDrag (const MouseEvent& e) override
{
onMouseDrag (*this, e);
}
void mouseUp (const MouseEvent& e) override
{
onMouseUp (*this, e);
}
String text;
Path path;
MouseCallback onMouseDown;
MouseCallback onMouseDrag;
MouseCallback onMouseUp;
};
//==============================================================================
class Ruler final : public Component,
private VisibleRangeDataModel::Listener
{
public:
explicit Ruler (const VisibleRangeDataModel& model)
: visibleRange (model)
{
visibleRange.addListener (*this);
setMouseCursor (MouseCursor::LeftRightResizeCursor);
}
private:
void paint (Graphics& g) override
{
auto minDivisionWidth = 50.0f;
auto maxDivisions = (float) getWidth() / minDivisionWidth;
auto lookFeel = dynamic_cast<LookAndFeel_V4*> (&getLookAndFeel());
auto bg = lookFeel->getCurrentColourScheme()
.getUIColour (LookAndFeel_V4::ColourScheme::UIColour::widgetBackground);
g.setGradientFill (ColourGradient (bg.brighter(),
0,
0,
bg.darker(),
0,
(float) getHeight(),
false));
g.fillAll();
g.setColour (bg.brighter());
g.drawHorizontalLine (0, 0.0f, (float) getWidth());
g.setColour (bg.darker());
g.drawHorizontalLine (1, 0.0f, (float) getWidth());
g.setColour (Colours::lightgrey);
auto minLog = std::ceil (std::log10 (visibleRange.getVisibleRange().getLength() / maxDivisions));
auto precision = 2 + std::abs (minLog);
auto divisionMagnitude = std::pow (10, minLog);
auto startingDivision = std::ceil (visibleRange.getVisibleRange().getStart() / divisionMagnitude);
for (auto div = startingDivision; div * divisionMagnitude < visibleRange.getVisibleRange().getEnd(); ++div)
{
auto time = div * divisionMagnitude;
auto xPos = (time - visibleRange.getVisibleRange().getStart()) * getWidth()
/ visibleRange.getVisibleRange().getLength();
std::ostringstream outStream;
outStream << std::setprecision (roundToInt (precision)) << time;
const auto bounds = Rectangle<int> (Point<int> (roundToInt (xPos) + 3, 0),
Point<int> (roundToInt (xPos + minDivisionWidth), getHeight()));
g.drawText (outStream.str(), bounds, Justification::centredLeft, false);
g.drawVerticalLine (roundToInt (xPos), 2.0f, (float) getHeight());
}
}
void mouseDown (const MouseEvent& e) override
{
visibleRangeOnMouseDown = visibleRange.getVisibleRange();
timeOnMouseDown = visibleRange.getVisibleRange().getStart()
+ (visibleRange.getVisibleRange().getLength() * e.getMouseDownX()) / getWidth();
}
void mouseDrag (const MouseEvent& e) override
{
// Work out the scale of the new range
auto unitDistance = 100.0f;
auto scaleFactor = 1.0 / std::pow (2, (float) e.getDistanceFromDragStartY() / unitDistance);
// Now position it so that the mouse continues to point at the same
// place on the ruler.
auto visibleLength = std::max (0.12, visibleRangeOnMouseDown.getLength() * scaleFactor);
auto rangeBegin = timeOnMouseDown - visibleLength * e.x / getWidth();
const Range<double> range (rangeBegin, rangeBegin + visibleLength);
visibleRange.setVisibleRange (range, nullptr);
}
void visibleRangeChanged (Range<double>) override
{
repaint();
}
VisibleRangeDataModel visibleRange;
Range<double> visibleRangeOnMouseDown;
double timeOnMouseDown;
};
//==============================================================================
class LoopPointsOverlay final : public Component,
private DataModel::Listener,
private VisibleRangeDataModel::Listener
{
public:
LoopPointsOverlay (const DataModel& dModel,
const VisibleRangeDataModel& vModel,
UndoManager& undoManagerIn)
: dataModel (dModel),
visibleRange (vModel),
beginMarker ("B",
[this] (LoopPointMarker& m, const MouseEvent& e) { this->loopPointMouseDown (m, e); },
[this] (LoopPointMarker& m, const MouseEvent& e) { this->loopPointDragged (m, e); },
[this] (LoopPointMarker& m, const MouseEvent& e) { this->loopPointMouseUp (m, e); }),
endMarker ("E",
[this] (LoopPointMarker& m, const MouseEvent& e) { this->loopPointMouseDown (m, e); },
[this] (LoopPointMarker& m, const MouseEvent& e) { this->loopPointDragged (m, e); },
[this] (LoopPointMarker& m, const MouseEvent& e) { this->loopPointMouseUp (m, e); }),
undoManager (&undoManagerIn)
{
dataModel .addListener (*this);
visibleRange.addListener (*this);
for (auto ptr : { &beginMarker, &endMarker })
addAndMakeVisible (ptr);
}
private:
void resized() override
{
positionLoopPointMarkers();
}
void loopPointMouseDown (LoopPointMarker&, const MouseEvent&)
{
loopPointsOnMouseDown = dataModel.getLoopPointsSeconds();
undoManager->beginNewTransaction();
}
void loopPointDragged (LoopPointMarker& marker, const MouseEvent& e)
{
auto x = xPositionToTime (e.getEventRelativeTo (this).position.x);
const Range<double> newLoopRange (&marker == &beginMarker ? x : loopPointsOnMouseDown.getStart(),
&marker == &endMarker ? x : loopPointsOnMouseDown.getEnd());
dataModel.setLoopPointsSeconds (newLoopRange, undoManager);
}
void loopPointMouseUp (LoopPointMarker& marker, const MouseEvent& e)
{
auto x = xPositionToTime (e.getEventRelativeTo (this).position.x);
const Range<double> newLoopRange (&marker == &beginMarker ? x : loopPointsOnMouseDown.getStart(),
&marker == &endMarker ? x : loopPointsOnMouseDown.getEnd());
dataModel.setLoopPointsSeconds (newLoopRange, undoManager);
}
void loopPointsSecondsChanged (Range<double>) override
{
positionLoopPointMarkers();
}
void visibleRangeChanged (Range<double>) override
{
positionLoopPointMarkers();
}
double timeToXPosition (double time) const
{
return (time - visibleRange.getVisibleRange().getStart()) * getWidth()
/ visibleRange.getVisibleRange().getLength();
}
double xPositionToTime (double xPosition) const
{
return ((xPosition * visibleRange.getVisibleRange().getLength()) / getWidth())
+ visibleRange.getVisibleRange().getStart();
}
void positionLoopPointMarkers()
{
auto halfMarkerWidth = 7;
for (auto tup : { std::make_tuple (&beginMarker, dataModel.getLoopPointsSeconds().getStart()),
std::make_tuple (&endMarker, dataModel.getLoopPointsSeconds().getEnd()) })
{
auto ptr = std::get<0> (tup);
auto time = std::get<1> (tup);
ptr->setSize (halfMarkerWidth * 2, getHeight());
ptr->setTopLeftPosition (roundToInt (timeToXPosition (time) - halfMarkerWidth), 0);
}
}
DataModel dataModel;
VisibleRangeDataModel visibleRange;
Range<double> loopPointsOnMouseDown;
LoopPointMarker beginMarker, endMarker;
UndoManager* undoManager;
};
//==============================================================================
class PlaybackPositionOverlay final : public Component,
private Timer,
private VisibleRangeDataModel::Listener
{
public:
using Provider = std::function<std::vector<float>()>;
PlaybackPositionOverlay (const VisibleRangeDataModel& model,
Provider providerIn)
: visibleRange (model),
provider (std::move (providerIn))
{
visibleRange.addListener (*this);
startTimer (16);
}
private:
void paint (Graphics& g) override
{
g.setColour (Colours::red);
for (auto position : provider())
{
g.drawVerticalLine (roundToInt (timeToXPosition (position)), 0.0f, (float) getHeight());
}
}
void timerCallback() override
{
repaint();
}
void visibleRangeChanged (Range<double>) override
{
repaint();
}
double timeToXPosition (double time) const
{
return (time - visibleRange.getVisibleRange().getStart()) * getWidth()
/ visibleRange.getVisibleRange().getLength();
}
VisibleRangeDataModel visibleRange;
Provider provider;
};
//==============================================================================
class WaveformView final : public Component,
private ChangeListener,
private DataModel::Listener,
private VisibleRangeDataModel::Listener
{
public:
WaveformView (const DataModel& model,
const VisibleRangeDataModel& vr)
: dataModel (model),
visibleRange (vr),
thumbnailCache (4),
thumbnail (4, dataModel.getAudioFormatManager(), thumbnailCache)
{
dataModel .addListener (*this);
visibleRange.addListener (*this);
thumbnail .addChangeListener (this);
}
private:
void paint (Graphics& g) override
{
// Draw the waveforms
g.fillAll (Colours::black);
auto numChannels = thumbnail.getNumChannels();
if (numChannels == 0)
{
g.setColour (Colours::white);
g.drawFittedText ("No File Loaded", getLocalBounds(), Justification::centred, 1);
return;
}
auto bounds = getLocalBounds();
auto channelHeight = bounds.getHeight() / numChannels;
for (auto i = 0; i != numChannels; ++i)
{
drawChannel (g, i, bounds.removeFromTop (channelHeight));
}
}
void changeListenerCallback (ChangeBroadcaster* source) override
{
if (source == &thumbnail)
repaint();
}
void sampleReaderChanged (std::shared_ptr<AudioFormatReaderFactory> value) override
{
if (value != nullptr)
{
if (auto reader = value->make (dataModel.getAudioFormatManager()))
{
thumbnail.setReader (reader.release(), currentHashCode);
currentHashCode += 1;
return;
}
}
thumbnail.clear();
}
void visibleRangeChanged (Range<double>) override
{
repaint();
}
void drawChannel (Graphics& g, int channel, Rectangle<int> bounds)
{
g.setGradientFill (ColourGradient (Colours::lightblue,
bounds.getTopLeft().toFloat(),
Colours::darkgrey,
bounds.getBottomLeft().toFloat(),
false));
thumbnail.drawChannel (g,
bounds,
visibleRange.getVisibleRange().getStart(),
visibleRange.getVisibleRange().getEnd(),
channel,
1.0f);
}
DataModel dataModel;
VisibleRangeDataModel visibleRange;
AudioThumbnailCache thumbnailCache;
AudioThumbnail thumbnail;
int64 currentHashCode = 0;
};
//==============================================================================
class WaveformEditor final : public Component,
private DataModel::Listener
{
public:
WaveformEditor (const DataModel& model,
PlaybackPositionOverlay::Provider provider,
UndoManager& undoManager)
: dataModel (model),
waveformView (model, visibleRange),
playbackOverlay (visibleRange, std::move (provider)),
loopPoints (dataModel, visibleRange, undoManager),
ruler (visibleRange)
{
dataModel.addListener (*this);
addAndMakeVisible (waveformView);
addAndMakeVisible (playbackOverlay);
addChildComponent (loopPoints);
loopPoints.setAlwaysOnTop (true);
waveformView.toBack();
addAndMakeVisible (ruler);
}
private:
void resized() override
{
auto bounds = getLocalBounds();
ruler .setBounds (bounds.removeFromTop (25));
waveformView .setBounds (bounds);
playbackOverlay.setBounds (bounds);
loopPoints .setBounds (bounds);
}
void loopModeChanged (LoopMode value) override
{
loopPoints.setVisible (value != LoopMode::none);
}
void sampleReaderChanged (std::shared_ptr<AudioFormatReaderFactory>) override
{
auto lengthInSeconds = dataModel.getSampleLengthSeconds();
visibleRange.setTotalRange (Range<double> (0, lengthInSeconds), nullptr);
visibleRange.setVisibleRange (Range<double> (0, lengthInSeconds), nullptr);
}
DataModel dataModel;
VisibleRangeDataModel visibleRange;
WaveformView waveformView;
PlaybackPositionOverlay playbackOverlay;
LoopPointsOverlay loopPoints;
Ruler ruler;
};
//==============================================================================
class MainSamplerView final : public Component,
private DataModel::Listener,
private ChangeListener
{
public:
MainSamplerView (const DataModel& model,
PlaybackPositionOverlay::Provider provider,
UndoManager& um)
: dataModel (model),
waveformEditor (dataModel, std::move (provider), um),
undoManager (um)
{
dataModel.addListener (*this);
addAndMakeVisible (waveformEditor);
addAndMakeVisible (loadNewSampleButton);
addAndMakeVisible (undoButton);
addAndMakeVisible (redoButton);
auto setReader = [this] (const FileChooser& fc)
{
const auto result = fc.getResult();
if (result != File())
{
undoManager.beginNewTransaction();
auto readerFactory = new FileAudioFormatReaderFactory (result);
dataModel.setSampleReader (std::unique_ptr<AudioFormatReaderFactory> (readerFactory),
&undoManager);
}
};
loadNewSampleButton.onClick = [this, setReader]
{
fileChooser.launchAsync (FileBrowserComponent::FileChooserFlags::openMode |
FileBrowserComponent::FileChooserFlags::canSelectFiles,
setReader);
};
addAndMakeVisible (centreFrequency);
centreFrequency.onValueChange = [this]
{
undoManager.beginNewTransaction();
dataModel.setCentreFrequencyHz (centreFrequency.getValue(),
centreFrequency.isMouseButtonDown() ? nullptr : &undoManager);
};
centreFrequency.setRange (20, 20000, 1);
centreFrequency.setSliderStyle (Slider::SliderStyle::IncDecButtons);
centreFrequency.setIncDecButtonsMode (Slider::IncDecButtonMode::incDecButtonsDraggable_Vertical);
auto radioGroupId = 1;
for (auto buttonPtr : { &loopKindNone, &loopKindForward, &loopKindPingpong })
{
addAndMakeVisible (buttonPtr);
buttonPtr->setRadioGroupId (radioGroupId, dontSendNotification);
buttonPtr->setClickingTogglesState (true);
}
loopKindNone.onClick = [this]
{
if (loopKindNone.getToggleState())
{
undoManager.beginNewTransaction();
dataModel.setLoopMode (LoopMode::none, &undoManager);
}
};
loopKindForward.onClick = [this]
{
if (loopKindForward.getToggleState())
{
undoManager.beginNewTransaction();
dataModel.setLoopMode (LoopMode::forward, &undoManager);
}
};
loopKindPingpong.onClick = [this]
{
if (loopKindPingpong.getToggleState())
{
undoManager.beginNewTransaction();
dataModel.setLoopMode (LoopMode::pingpong, &undoManager);
}
};
undoButton.onClick = [this] { undoManager.undo(); };
redoButton.onClick = [this] { undoManager.redo(); };
addAndMakeVisible (centreFrequencyLabel);
addAndMakeVisible (loopKindLabel);
changeListenerCallback (&undoManager);
undoManager.addChangeListener (this);
}
~MainSamplerView() override
{
undoManager.removeChangeListener (this);
}
private:
void changeListenerCallback (ChangeBroadcaster* source) override
{
if (source == &undoManager)
{
undoButton.setEnabled (undoManager.canUndo());
redoButton.setEnabled (undoManager.canRedo());
}
}
void resized() override
{
auto bounds = getLocalBounds();
auto topBar = bounds.removeFromTop (50);
auto padding = 4;
loadNewSampleButton .setBounds (topBar.removeFromRight (100).reduced (padding));
redoButton .setBounds (topBar.removeFromRight (100).reduced (padding));
undoButton .setBounds (topBar.removeFromRight (100).reduced (padding));
centreFrequencyLabel.setBounds (topBar.removeFromLeft (100).reduced (padding));
centreFrequency .setBounds (topBar.removeFromLeft (100).reduced (padding));
auto bottomBar = bounds.removeFromBottom (50);
loopKindLabel .setBounds (bottomBar.removeFromLeft (100).reduced (padding));
loopKindNone .setBounds (bottomBar.removeFromLeft (80) .reduced (padding));
loopKindForward .setBounds (bottomBar.removeFromLeft (80) .reduced (padding));
loopKindPingpong.setBounds (bottomBar.removeFromLeft (80) .reduced (padding));
waveformEditor.setBounds (bounds);
}
void loopModeChanged (LoopMode value) override
{
switch (value)
{
case LoopMode::none:
loopKindNone.setToggleState (true, dontSendNotification);
break;
case LoopMode::forward:
loopKindForward.setToggleState (true, dontSendNotification);
break;
case LoopMode::pingpong:
loopKindPingpong.setToggleState (true, dontSendNotification);
break;
default:
break;
}
}
void centreFrequencyHzChanged (double value) override
{
centreFrequency.setValue (value, dontSendNotification);
}
DataModel dataModel;
WaveformEditor waveformEditor;
TextButton loadNewSampleButton { "Load New Sample" };
TextButton undoButton { "Undo" };
TextButton redoButton { "Redo" };
Slider centreFrequency;
TextButton loopKindNone { "None" },
loopKindForward { "Forward" },
loopKindPingpong { "Ping Pong" };
Label centreFrequencyLabel { {}, "Sample Centre Freq / Hz" },
loopKindLabel { {}, "Looping Mode" };
FileChooser fileChooser { "Select a file to load...", File(),
dataModel.getAudioFormatManager().getWildcardForAllFormats() };
UndoManager& undoManager;
};
//==============================================================================
struct ProcessorState
{
int synthVoices;
bool legacyModeEnabled;
Range<int> legacyChannels;
int legacyPitchbendRange;
bool voiceStealingEnabled;
MPEZoneLayout mpeZoneLayout;
std::unique_ptr<AudioFormatReaderFactory> readerFactory;
Range<double> loopPointsSeconds;
double centreFrequencyHz;
LoopMode loopMode;
};
//==============================================================================
class SamplerAudioProcessor final : public AudioProcessor
{
public:
SamplerAudioProcessor()
: AudioProcessor (BusesProperties().withOutput ("Output", AudioChannelSet::stereo(), true))
{
if (auto inputStream = createAssetInputStream ("cello.wav"))
{
MemoryBlock mb;
inputStream->readIntoMemoryBlock (mb);
readerFactory = std::make_unique<MemoryAudioFormatReaderFactory> (std::move (mb));
}
if (readerFactory != nullptr)
{
AudioFormatManager manager;
manager.registerBasicFormats();
if (auto reader = readerFactory->make (manager))
{
auto sample = std::make_unique<Sample> (*reader, 10.0);
auto lengthInSeconds = sample->getLength() / sample->getSampleRate();
samplerSound->setLoopPointsInSeconds ({ lengthInSeconds * 0.1, lengthInSeconds * 0.9 });
samplerSound->setSample (std::move (sample));
}
}
// Start with the max number of voices
for (auto i = 0; i != maxVoices; ++i)
synthesiser.addVoice (new MPESamplerVoice (samplerSound));
}
void prepareToPlay (double sampleRate, int) override
{
synthesiser.setCurrentPlaybackSampleRate (sampleRate);
}
void releaseResources() override {}
bool isBusesLayoutSupported (const BusesLayout& layouts) const override
{
return layouts.getMainOutputChannelSet() == AudioChannelSet::mono()
|| layouts.getMainOutputChannelSet() == AudioChannelSet::stereo();
}
//==============================================================================
AudioProcessorEditor* createEditor() override
{
// This function will be called from the message thread. We lock the command
// queue to ensure that no messages are processed for the duration of this
// call.
SpinLock::ScopedLockType lock (commandQueueMutex);
ProcessorState state;
state.synthVoices = synthesiser.getNumVoices();
state.legacyModeEnabled = synthesiser.isLegacyModeEnabled();
state.legacyChannels = synthesiser.getLegacyModeChannelRange();
state.legacyPitchbendRange = synthesiser.getLegacyModePitchbendRange();
state.voiceStealingEnabled = synthesiser.isVoiceStealingEnabled();
state.mpeZoneLayout = synthesiser.getZoneLayout();
state.readerFactory = readerFactory == nullptr ? nullptr : readerFactory->clone();
auto sound = samplerSound;
state.loopPointsSeconds = sound->getLoopPointsInSeconds();
state.centreFrequencyHz = sound->getCentreFrequencyInHz();
state.loopMode = sound->getLoopMode();
return new SamplerAudioProcessorEditor (*this, std::move (state));
}
bool hasEditor() const override { return true; }
//==============================================================================
const String getName() const override { return "SamplerPlugin"; }
bool acceptsMidi() const override { return true; }
bool producesMidi() const override { return false; }
bool isMidiEffect() const override { return false; }
double getTailLengthSeconds() const override { return 0.0; }
//==============================================================================
int getNumPrograms() override { return 1; }
int getCurrentProgram() override { return 0; }
void setCurrentProgram (int) override {}
const String getProgramName (int) override { return "None"; }
void changeProgramName (int, const String&) override {}
//==============================================================================
void getStateInformation (MemoryBlock&) override {}
void setStateInformation (const void*, int) override {}
//==============================================================================
void processBlock (AudioBuffer<float>& buffer, MidiBuffer& midi) override
{
process (buffer, midi);
}
void processBlock (AudioBuffer<double>& buffer, MidiBuffer& midi) override
{
process (buffer, midi);
}
// These should be called from the GUI thread, and will block until the
// command buffer has enough room to accept a command.
void setSample (std::unique_ptr<AudioFormatReaderFactory> fact, AudioFormatManager& formatManager)
{
class SetSampleCommand
{
public:
SetSampleCommand (std::unique_ptr<AudioFormatReaderFactory> r,
std::unique_ptr<Sample> sampleIn,
std::vector<std::unique_ptr<MPESamplerVoice>> newVoicesIn)
: readerFactory (std::move (r)),
sample (std::move (sampleIn)),
newVoices (std::move (newVoicesIn))
{}
void operator() (SamplerAudioProcessor& proc)
{
proc.readerFactory = std::move (readerFactory);
auto sound = proc.samplerSound;
sound->setSample (std::move (sample));
auto numberOfVoices = proc.synthesiser.getNumVoices();
proc.synthesiser.clearVoices();
for (auto it = begin (newVoices); proc.synthesiser.getNumVoices() < numberOfVoices; ++it)
{
proc.synthesiser.addVoice (it->release());
}
}
private:
std::unique_ptr<AudioFormatReaderFactory> readerFactory;
std::unique_ptr<Sample> sample;
std::vector<std::unique_ptr<MPESamplerVoice>> newVoices;
};
// Note that all allocation happens here, on the main message thread. Then,
// we transfer ownership across to the audio thread.
auto loadedSamplerSound = samplerSound;
std::vector<std::unique_ptr<MPESamplerVoice>> newSamplerVoices;
newSamplerVoices.reserve (maxVoices);
for (auto i = 0; i != maxVoices; ++i)
newSamplerVoices.emplace_back (new MPESamplerVoice (loadedSamplerSound));
if (fact == nullptr)
{
commands.push (SetSampleCommand (std::move (fact),
nullptr,
std::move (newSamplerVoices)));
}
else if (auto reader = fact->make (formatManager))
{
commands.push (SetSampleCommand (std::move (fact),
std::unique_ptr<Sample> (new Sample (*reader, 10.0)),
std::move (newSamplerVoices)));
}
}
void setCentreFrequency (double centreFrequency)
{
commands.push ([centreFrequency] (SamplerAudioProcessor& proc)
{
auto loaded = proc.samplerSound;
if (loaded != nullptr)
loaded->setCentreFrequencyInHz (centreFrequency);
});
}
void setLoopMode (LoopMode loopMode)
{
commands.push ([loopMode] (SamplerAudioProcessor& proc)
{
auto loaded = proc.samplerSound;
if (loaded != nullptr)
loaded->setLoopMode (loopMode);
});
}
void setLoopPoints (Range<double> loopPoints)
{
commands.push ([loopPoints] (SamplerAudioProcessor& proc)
{
auto loaded = proc.samplerSound;
if (loaded != nullptr)
loaded->setLoopPointsInSeconds (loopPoints);
});
}
void setMPEZoneLayout (MPEZoneLayout layout)
{
commands.push ([layout] (SamplerAudioProcessor& proc)
{
// setZoneLayout will lock internally, so we don't care too much about
// ensuring that the layout doesn't get copied or destroyed on the
// audio thread. If the audio glitches while updating midi settings
// it doesn't matter too much.
proc.synthesiser.setZoneLayout (layout);
});
}
void setLegacyModeEnabled (int pitchbendRange, Range<int> channelRange)
{
commands.push ([pitchbendRange, channelRange] (SamplerAudioProcessor& proc)
{
proc.synthesiser.enableLegacyMode (pitchbendRange, channelRange);
});
}
void setVoiceStealingEnabled (bool voiceStealingEnabled)
{
commands.push ([voiceStealingEnabled] (SamplerAudioProcessor& proc)
{
proc.synthesiser.setVoiceStealingEnabled (voiceStealingEnabled);
});
}
void setNumberOfVoices (int numberOfVoices)
{
// We don't want to call 'new' on the audio thread. Normally, we'd
// construct things here, on the GUI thread, and then move them into the
// command lambda. Unfortunately, C++11 doesn't have extended lambda
// capture, so we use a custom struct instead.
class SetNumVoicesCommand
{
public:
SetNumVoicesCommand (std::vector<std::unique_ptr<MPESamplerVoice>> newVoicesIn)
: newVoices (std::move (newVoicesIn))
{}
void operator() (SamplerAudioProcessor& proc)
{
if ((int) newVoices.size() < proc.synthesiser.getNumVoices())
proc.synthesiser.reduceNumVoices (int (newVoices.size()));
else
for (auto it = begin (newVoices); (size_t) proc.synthesiser.getNumVoices() < newVoices.size(); ++it)
proc.synthesiser.addVoice (it->release());
}
private:
std::vector<std::unique_ptr<MPESamplerVoice>> newVoices;
};
numberOfVoices = std::min ((int) maxVoices, numberOfVoices);
auto loadedSamplerSound = samplerSound;
std::vector<std::unique_ptr<MPESamplerVoice>> newSamplerVoices;
newSamplerVoices.reserve ((size_t) numberOfVoices);
for (auto i = 0; i != numberOfVoices; ++i)
newSamplerVoices.emplace_back (new MPESamplerVoice (loadedSamplerSound));
commands.push (SetNumVoicesCommand (std::move (newSamplerVoices)));
}
// These accessors are just for an 'overview' and won't give the exact
// state of the audio engine at a particular point in time.
// If you call getNumVoices(), get the result '10', and then call
// getPlaybackPosiiton (9), there's a chance the audio engine will have
// been updated to remove some voices in the meantime, so the returned
// value won't correspond to an existing voice.
int getNumVoices() const { return synthesiser.getNumVoices(); }
float getPlaybackPosition (int voice) const { return playbackPositions.at ((size_t) voice); }
private:
//==============================================================================
class SamplerAudioProcessorEditor final : public AudioProcessorEditor,
public FileDragAndDropTarget,
private DataModel::Listener,
private MPESettingsDataModel::Listener
{
public:
SamplerAudioProcessorEditor (SamplerAudioProcessor& p, ProcessorState state)
: AudioProcessorEditor (&p),
samplerAudioProcessor (p),
mainSamplerView (dataModel,
[&p]
{
std::vector<float> ret;
auto voices = p.getNumVoices();
ret.reserve ((size_t) voices);
for (auto i = 0; i != voices; ++i)
ret.emplace_back (p.getPlaybackPosition (i));
return ret;
},
undoManager)
{
dataModel.addListener (*this);
mpeSettings.addListener (*this);
formatManager.registerBasicFormats();
addAndMakeVisible (tabbedComponent);
auto lookFeel = dynamic_cast<LookAndFeel_V4*> (&getLookAndFeel());
auto bg = lookFeel->getCurrentColourScheme()
.getUIColour (LookAndFeel_V4::ColourScheme::UIColour::widgetBackground);
tabbedComponent.addTab ("Sample Editor", bg, &mainSamplerView, false);
tabbedComponent.addTab ("MPE Settings", bg, &settingsComponent, false);
mpeSettings.setSynthVoices (state.synthVoices, nullptr);
mpeSettings.setLegacyModeEnabled (state.legacyModeEnabled, nullptr);
mpeSettings.setLegacyFirstChannel (state.legacyChannels.getStart(), nullptr);
mpeSettings.setLegacyLastChannel (state.legacyChannels.getEnd(), nullptr);
mpeSettings.setLegacyPitchbendRange (state.legacyPitchbendRange, nullptr);
mpeSettings.setVoiceStealingEnabled (state.voiceStealingEnabled, nullptr);
mpeSettings.setMPEZoneLayout (state.mpeZoneLayout, nullptr);
dataModel.setSampleReader (std::move (state.readerFactory), nullptr);
dataModel.setLoopPointsSeconds (state.loopPointsSeconds, nullptr);
dataModel.setCentreFrequencyHz (state.centreFrequencyHz, nullptr);
dataModel.setLoopMode (state.loopMode, nullptr);
// Make sure that before the constructor has finished, you've set the
// editor's size to whatever you need it to be.
setResizable (true, true);
setResizeLimits (640, 480, 2560, 1440);
setSize (640, 480);
}
private:
void resized() override
{
tabbedComponent.setBounds (getLocalBounds());
}
bool keyPressed (const KeyPress& key) override
{
if (key == KeyPress ('z', ModifierKeys::commandModifier, 0))
{
undoManager.undo();
return true;
}
if (key == KeyPress ('z', ModifierKeys::commandModifier | ModifierKeys::shiftModifier, 0))
{
undoManager.redo();
return true;
}
return Component::keyPressed (key);
}
bool isInterestedInFileDrag (const StringArray& files) override
{
WildcardFileFilter filter (formatManager.getWildcardForAllFormats(), {}, "Known Audio Formats");
return files.size() == 1 && filter.isFileSuitable (files[0]);
}
void filesDropped (const StringArray& files, int, int) override
{
jassert (files.size() == 1);
undoManager.beginNewTransaction();
auto r = new FileAudioFormatReaderFactory (files[0]);
dataModel.setSampleReader (std::unique_ptr<AudioFormatReaderFactory> (r),
&undoManager);
}
void sampleReaderChanged (std::shared_ptr<AudioFormatReaderFactory> value) override
{
samplerAudioProcessor.setSample (value == nullptr ? nullptr : value->clone(),
dataModel.getAudioFormatManager());
}
void centreFrequencyHzChanged (double value) override
{
samplerAudioProcessor.setCentreFrequency (value);
}
void loopPointsSecondsChanged (Range<double> value) override
{
samplerAudioProcessor.setLoopPoints (value);
}
void loopModeChanged (LoopMode value) override
{
samplerAudioProcessor.setLoopMode (value);
}
void synthVoicesChanged (int value) override
{
samplerAudioProcessor.setNumberOfVoices (value);
}
void voiceStealingEnabledChanged (bool value) override
{
samplerAudioProcessor.setVoiceStealingEnabled (value);
}
void legacyModeEnabledChanged (bool value) override
{
if (value)
setProcessorLegacyMode();
else
setProcessorMPEMode();
}
void mpeZoneLayoutChanged (const MPEZoneLayout&) override
{
setProcessorMPEMode();
}
void legacyFirstChannelChanged (int) override
{
setProcessorLegacyMode();
}
void legacyLastChannelChanged (int) override
{
setProcessorLegacyMode();
}
void legacyPitchbendRangeChanged (int) override
{
setProcessorLegacyMode();
}
void setProcessorLegacyMode()
{
samplerAudioProcessor.setLegacyModeEnabled (mpeSettings.getLegacyPitchbendRange(),
Range<int> (mpeSettings.getLegacyFirstChannel(),
mpeSettings.getLegacyLastChannel()));
}
void setProcessorMPEMode()
{
samplerAudioProcessor.setMPEZoneLayout (mpeSettings.getMPEZoneLayout());
}
SamplerAudioProcessor& samplerAudioProcessor;
AudioFormatManager formatManager;
DataModel dataModel { formatManager };
UndoManager undoManager;
MPESettingsDataModel mpeSettings { dataModel.mpeSettings() };
TabbedComponent tabbedComponent { TabbedButtonBar::Orientation::TabsAtTop };
MPESettingsComponent settingsComponent { dataModel.mpeSettings(), undoManager };
MainSamplerView mainSamplerView;
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (SamplerAudioProcessorEditor)
};
//==============================================================================
template <typename Element>
void process (AudioBuffer<Element>& buffer, MidiBuffer& midiMessages)
{
// Try to acquire a lock on the command queue.
// If we were successful, we pop all pending commands off the queue and
// apply them to the processor.
// If we weren't able to acquire the lock, it's because someone called
// createEditor, which requires that the processor data model stays in
// a valid state for the duration of the call.
const GenericScopedTryLock<SpinLock> lock (commandQueueMutex);
if (lock.isLocked())
commands.call (*this);
synthesiser.renderNextBlock (buffer, midiMessages, 0, buffer.getNumSamples());
auto loadedSamplerSound = samplerSound;
if (loadedSamplerSound->getSample() == nullptr)
return;
auto numVoices = synthesiser.getNumVoices();
// Update the current playback positions
for (auto i = 0; i < maxVoices; ++i)
{
auto* voicePtr = dynamic_cast<MPESamplerVoice*> (synthesiser.getVoice (i));
if (i < numVoices && voicePtr != nullptr)
playbackPositions[(size_t) i] = static_cast<float> (voicePtr->getCurrentSamplePosition() / loadedSamplerSound->getSample()->getSampleRate());
else
playbackPositions[(size_t) i] = 0.0f;
}
}
CommandFifo<SamplerAudioProcessor> commands;
std::unique_ptr<AudioFormatReaderFactory> readerFactory;
std::shared_ptr<MPESamplerSound> samplerSound = std::make_shared<MPESamplerSound>();
MPESynthesiser synthesiser;
// This mutex is used to ensure we don't modify the processor state during
// a call to createEditor, which would cause the UI to become desynched
// with the real state of the processor.
SpinLock commandQueueMutex;
enum { maxVoices = 20 };
// This is used for visualising the current playback position of each voice.
std::array<std::atomic<float>, maxVoices> playbackPositions;
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (SamplerAudioProcessor)
};
|