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
//! AudioParam interface
use std::slice::{Iter, IterMut};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use crate::context::AudioContextRegistration;
use crate::node::{
AudioNode, ChannelConfig, ChannelConfigOptions, ChannelCountMode, ChannelInterpretation,
};
use crate::render::{AudioParamValues, AudioProcessor, AudioRenderQuantum, RenderScope};
use crate::{AtomicF32, RENDER_QUANTUM_SIZE};
use std::sync::OnceLock;
/// For SetTargetAtTime event, that theoretically cannot end, if the diff between
/// the current value and the target is below this threshold, the value is set
/// to target value and the event is considered ended.
const SNAP_TO_TARGET: f32 = 1e-10;
// arguments sanity check functions for automation methods
#[track_caller]
fn assert_non_negative(value: f64) {
if value < 0. {
panic!(
"RangeError - timing value ({:?}) should not be negative",
value
);
}
}
#[track_caller]
fn assert_strictly_positive(value: f64) {
if value <= 0. {
panic!(
"RangeError - duration ({:?}) should be strictly positive",
value
);
}
}
#[track_caller]
fn assert_not_zero(value: f32) {
if value == 0. {
panic!(
"RangeError - value ({:?}) should not be equal to zero",
value,
)
}
}
#[track_caller]
fn assert_sequence_length(values: &[f32]) {
if values.len() < 2 {
panic!(
"InvalidStateError - sequence length ({:?}) should not be less than 2",
values.len()
)
}
}
/// Precision of AudioParam value calculation per render quantum
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
pub enum AutomationRate {
/// Audio Rate - sampled for each sample-frame of the block
A,
/// Control Rate - sampled at the time of the very first sample-frame,
/// then used for the entire block
K,
}
impl AutomationRate {
fn is_a_rate(self) -> bool {
match self {
AutomationRate::A => true,
AutomationRate::K => false,
}
}
}
/// Options for constructing an [`AudioParam`]
#[derive(Clone, Debug)]
pub struct AudioParamDescriptor {
pub automation_rate: AutomationRate,
pub default_value: f32,
pub min_value: f32,
pub max_value: f32,
}
#[derive(PartialEq, Eq, Debug)]
enum AudioParamEventType {
SetValue,
SetValueAtTime,
LinearRampToValueAtTime,
ExponentialRampToValueAtTime,
CancelScheduledValues,
SetTargetAtTime,
CancelAndHoldAtTime,
SetValueCurveAtTime,
}
#[derive(Debug)]
pub(crate) struct AudioParamEvent {
event_type: AudioParamEventType,
value: f32,
time: f64,
time_constant: Option<f64>, // populated by `SetTargetAtTime` events
cancel_time: Option<f64>, // populated by `CancelAndHoldAtTime` events
duration: Option<f64>, // populated by `SetValueCurveAtTime` events
values: Option<Box<[f32]>>, // populated by `SetValueCurveAtTime` events
}
// Event queue that contains `AudioParamEvent`s, most of the time, events must be
// ordered (using stable sort), some operation may break this ordering (e.g. `push`)
// in which cases `sort` must be called explicitly.
// In the current implementation of the param rendering, `sort` is called once after
// all events have been inserted in the queue at each `tick` (with the exception
// `CancelAndHoldAtTime` which needs a clean queue to find its neighbors, but this
// occurs during the insertion of events)
// After this point, the queue should be considered sorted and no operations that
// breaks the ordering should be done.
#[derive(Debug)]
struct AudioParamEventTimeline {
inner: Vec<AudioParamEvent>,
dirty: bool,
}
impl AudioParamEventTimeline {
fn new() -> Self {
Self {
inner: Vec::new(),
dirty: false,
}
}
fn push(&mut self, item: AudioParamEvent) {
self.dirty = true;
self.inner.push(item);
}
// `pop` and `retain` preserve order so they don't make the queue dirty
fn pop(&mut self) -> Option<AudioParamEvent> {
if !self.inner.is_empty() {
Some(self.inner.remove(0))
} else {
None
}
}
fn retain<F>(&mut self, func: F)
where
F: Fn(&AudioParamEvent) -> bool,
{
self.inner.retain(func);
}
// Only used to handle special cases in `ExponentialRampToValueAtTime`:
// as the replaced item has the same time, order is preserved.
// If the method turned out to be used elsewhere, this could maybe
// become wrong, be careful here.
fn replace_peek(&mut self, item: AudioParamEvent) {
self.inner[0] = item;
}
fn is_empty(&self) -> bool {
self.inner.is_empty()
}
fn unsorted_peek(&self) -> Option<&AudioParamEvent> {
self.inner.get(0)
}
// panic if dirty, we are doing something wrong here
fn peek(&self) -> Option<&AudioParamEvent> {
if self.dirty {
panic!("`AudioParamEventTimeline`: Invalid `.peek()` call, the queue is dirty");
}
self.inner.get(0)
}
fn next(&self) -> Option<&AudioParamEvent> {
if self.dirty {
panic!("`AudioParamEventTimeline`: Invalid `.next()` call, the queue is dirty");
}
self.inner.get(1)
}
fn sort(&mut self) {
self.inner
.sort_by(|a, b| a.time.partial_cmp(&b.time).unwrap());
self.dirty = false;
}
fn iter(&mut self) -> Iter<'_, AudioParamEvent> {
self.inner.iter()
}
fn iter_mut(&mut self) -> IterMut<'_, AudioParamEvent> {
self.inner.iter_mut()
}
}
/// AudioParam controls an individual aspect of an AudioNode's functionality, such as volume.
pub struct AudioParam {
registration: AudioContextRegistration,
raw_parts: AudioParamRaw,
}
// helper struct to attach / detach to context (for borrow reasons)
#[derive(Clone)]
pub(crate) struct AudioParamRaw {
default_value: f32, // immutable
min_value: f32, // immutable
max_value: f32, // immutable
automation_rate_constrained: bool,
// TODO Use `Weak` instead of `Arc`. The `AudioParamProcessor` is the owner.
shared_parts: Arc<AudioParamShared>,
}
impl AudioNode for AudioParam {
fn registration(&self) -> &AudioContextRegistration {
&self.registration
}
fn channel_config(&self) -> &'static ChannelConfig {
static INSTANCE: OnceLock<ChannelConfig> = OnceLock::new();
INSTANCE.get_or_init(|| {
ChannelConfigOptions {
count: 1,
count_mode: ChannelCountMode::Explicit,
interpretation: ChannelInterpretation::Discrete,
}
.into()
})
}
fn number_of_inputs(&self) -> usize {
1
}
fn number_of_outputs(&self) -> usize {
1
}
fn set_channel_count(&self, _v: usize) {
panic!("AudioParam has channel count constraints");
}
fn set_channel_count_mode(&self, _v: ChannelCountMode) {
panic!("AudioParam has channel count mode constraints");
}
fn set_channel_interpretation(&self, _v: ChannelInterpretation) {
panic!("AudioParam has channel interpretation constraints");
}
}
impl AudioParam {
/// Current value of the automation rate of the AudioParam
pub fn automation_rate(&self) -> AutomationRate {
self.raw_parts.shared_parts.load_automation_rate()
}
/// Update the current value of the automation rate of the AudioParam
///
/// # Panics
///
/// Some nodes have automation rate constraints and may panic when updating the value.
pub fn set_automation_rate(&self, value: AutomationRate) {
if self.raw_parts.automation_rate_constrained && value != self.automation_rate() {
panic!("InvalidStateError: automation rate cannot be changed for this param");
}
self.registration().post_message(value);
}
pub(crate) fn set_automation_rate_constrained(&mut self, value: bool) {
self.raw_parts.automation_rate_constrained = value;
}
pub fn default_value(&self) -> f32 {
self.raw_parts.default_value
}
pub fn min_value(&self) -> f32 {
self.raw_parts.min_value
}
pub fn max_value(&self) -> f32 {
self.raw_parts.max_value
}
/// Retrieve the current value of the `AudioParam`.
//
// @note: the choice here is to have this coherent with the first sample of
// the last rendered block, which means `intrinsic_value` must be calculated
// for next_block_time at each tick.
// @note - maybe check with spec editors that it is correct
//
// see. test_linear_ramp_arate_multiple_blocks
// test_linear_ramp_krate_multiple_blocks
// test_exponential_ramp_a_rate_multiple_blocks
// test_exponential_ramp_k_rate_multiple_blocks
pub fn value(&self) -> f32 {
self.raw_parts.shared_parts.load_current_value()
}
/// Set the value of the `AudioParam`.
///
/// Is equivalent to calling the `set_value_at_time` method with the current
/// AudioContext's currentTime
//
// @note: Setting this attribute has the effect of assigning the requested value
// to the [[current value]] slot, and calling the setValueAtTime() method
// with the current AudioContext's currentTime and [[current value]].
// Any exceptions that would be thrown by setValueAtTime() will also be
// thrown by setting this attribute.
// cf. https://www.w3.org/TR/webaudio/#dom-audioparam-value
pub fn set_value(&self, value: f32) -> &Self {
self.send_event(self.set_value_raw(value))
}
fn set_value_raw(&self, value: f32) -> AudioParamEvent {
// current_value should always be clamped
let clamped = value.clamp(self.raw_parts.min_value, self.raw_parts.max_value);
self.raw_parts.shared_parts.store_current_value(clamped);
// this event is meant to update param intrinsic value before any calculation
// is done, will behave as SetValueAtTime with `time == block_timestamp`
AudioParamEvent {
event_type: AudioParamEventType::SetValue,
value,
time: 0.,
time_constant: None,
cancel_time: None,
duration: None,
values: None,
}
}
/// Schedules a parameter value change at the given time.
///
/// # Panics
///
/// Will panic if `start_time` is negative
pub fn set_value_at_time(&self, value: f32, start_time: f64) -> &Self {
self.send_event(self.set_value_at_time_raw(value, start_time))
}
fn set_value_at_time_raw(&self, value: f32, start_time: f64) -> AudioParamEvent {
assert_non_negative(start_time);
AudioParamEvent {
event_type: AudioParamEventType::SetValueAtTime,
value,
time: start_time,
time_constant: None,
cancel_time: None,
duration: None,
values: None,
}
}
/// Schedules a linear continuous change in parameter value from the
/// previous scheduled parameter value to the given value.
///
/// # Panics
///
/// Will panic if `end_time` is negative
pub fn linear_ramp_to_value_at_time(&self, value: f32, end_time: f64) -> &Self {
self.send_event(self.linear_ramp_to_value_at_time_raw(value, end_time))
}
fn linear_ramp_to_value_at_time_raw(&self, value: f32, end_time: f64) -> AudioParamEvent {
assert_non_negative(end_time);
AudioParamEvent {
event_type: AudioParamEventType::LinearRampToValueAtTime,
value,
time: end_time,
time_constant: None,
cancel_time: None,
duration: None,
values: None,
}
}
/// Schedules an exponential continuous change in parameter value from the
/// previous scheduled parameter value to the given value.
///
/// # Panics
///
/// Will panic if:
/// - `value` is zero
/// - `end_time` is negative
pub fn exponential_ramp_to_value_at_time(&self, value: f32, end_time: f64) -> &Self {
self.send_event(self.exponential_ramp_to_value_at_time_raw(value, end_time))
}
fn exponential_ramp_to_value_at_time_raw(&self, value: f32, end_time: f64) -> AudioParamEvent {
assert_not_zero(value);
assert_non_negative(end_time);
AudioParamEvent {
event_type: AudioParamEventType::ExponentialRampToValueAtTime,
value,
time: end_time,
time_constant: None,
cancel_time: None,
duration: None,
values: None,
}
}
/// Start exponentially approaching the target value at the given time with
/// a rate having the given time constant.
///
/// # Panics
///
/// Will panic if:
/// - `start_time` is negative
/// - `time_constant` is negative
pub fn set_target_at_time(&self, value: f32, start_time: f64, time_constant: f64) -> &Self {
self.send_event(self.set_target_at_time_raw(value, start_time, time_constant))
}
fn set_target_at_time_raw(
&self,
value: f32,
start_time: f64,
time_constant: f64,
) -> AudioParamEvent {
assert_non_negative(start_time);
assert_non_negative(time_constant);
// [spec] If timeConstant is zero, the output value jumps immediately to the final value.
if time_constant == 0. {
AudioParamEvent {
event_type: AudioParamEventType::SetValueAtTime,
value,
time: start_time,
time_constant: None,
cancel_time: None,
duration: None,
values: None,
}
} else {
AudioParamEvent {
event_type: AudioParamEventType::SetTargetAtTime,
value,
time: start_time,
time_constant: Some(time_constant),
cancel_time: None,
duration: None,
values: None,
}
}
}
/// Cancels all scheduled parameter changes with times greater than or equal
/// to `cancel_time`.
///
/// # Panics
///
/// Will panic if `cancel_time` is negative
pub fn cancel_scheduled_values(&self, cancel_time: f64) -> &Self {
self.send_event(self.cancel_scheduled_values_raw(cancel_time))
}
fn cancel_scheduled_values_raw(&self, cancel_time: f64) -> AudioParamEvent {
assert_non_negative(cancel_time);
AudioParamEvent {
event_type: AudioParamEventType::CancelScheduledValues,
value: 0., // no value
time: cancel_time,
time_constant: None,
cancel_time: None,
duration: None,
values: None,
}
}
/// Cancels all scheduled parameter changes with times greater than or equal
/// to `cancel_time` and the automation value that would have happened at
/// that time is then propagated for all future time.
///
/// # Panics
///
/// Will panic if `cancel_time` is negative
pub fn cancel_and_hold_at_time(&self, cancel_time: f64) -> &Self {
self.send_event(self.cancel_and_hold_at_time_raw(cancel_time))
}
fn cancel_and_hold_at_time_raw(&self, cancel_time: f64) -> AudioParamEvent {
assert_non_negative(cancel_time);
AudioParamEvent {
event_type: AudioParamEventType::CancelAndHoldAtTime,
value: 0., // value will be defined by cancel event
time: cancel_time,
time_constant: None,
cancel_time: None,
duration: None,
values: None,
}
}
/// Sets an array of arbitrary parameter values starting at the given time
/// for the given duration.
///
/// # Panics
///
/// Will panic if:
/// - `value` length is less than 2
/// - `start_time` is negative
/// - `duration` is negative or equal to zero
pub fn set_value_curve_at_time(&self, values: &[f32], start_time: f64, duration: f64) -> &Self {
self.send_event(self.set_value_curve_at_time_raw(values, start_time, duration))
}
fn set_value_curve_at_time_raw(
&self,
values: &[f32],
start_time: f64,
duration: f64,
) -> AudioParamEvent {
assert_sequence_length(values);
assert_non_negative(start_time);
assert_strictly_positive(duration);
// When this method is called, an internal copy of the curve is
// created for automation purposes.
let copy = values.to_vec();
let boxed_copy = copy.into_boxed_slice();
AudioParamEvent {
event_type: AudioParamEventType::SetValueCurveAtTime,
value: 0., // value will be defined at the end of the event
time: start_time,
time_constant: None,
cancel_time: None,
duration: Some(duration),
values: Some(boxed_copy),
}
}
// helper function to detach from context (for borrow reasons)
pub(crate) fn into_raw_parts(self) -> AudioParamRaw {
let Self {
registration: _,
raw_parts,
} = self;
raw_parts
}
// helper function to attach to context (for borrow reasons)
pub(crate) fn from_raw_parts(
registration: AudioContextRegistration,
raw_parts: AudioParamRaw,
) -> Self {
Self {
registration,
raw_parts,
}
}
fn send_event(&self, event: AudioParamEvent) -> &Self {
self.registration().post_message(event);
self
}
}
// Atomic fields of `AudioParam` that could be safely shared between threads
// when wrapped into an `Arc`.
//
// Uses the canonical ordering for handover of values, i.e. `Acquire` on load
// and `Release` on store.
#[derive(Debug)]
pub(crate) struct AudioParamShared {
current_value: AtomicF32,
is_a_rate: AtomicBool,
}
impl AudioParamShared {
pub(crate) fn new(current_value: f32, automation_rate: AutomationRate) -> Self {
Self {
current_value: AtomicF32::new(current_value),
is_a_rate: AtomicBool::new(automation_rate.is_a_rate()),
}
}
pub(crate) fn load_current_value(&self) -> f32 {
self.current_value.load(Ordering::Acquire)
}
pub(crate) fn store_current_value(&self, value: f32) {
self.current_value.store(value, Ordering::Release);
}
pub(crate) fn load_automation_rate(&self) -> AutomationRate {
if self.is_a_rate.load(Ordering::Acquire) {
AutomationRate::A
} else {
AutomationRate::K
}
}
pub(crate) fn store_automation_rate(&self, automation_rate: AutomationRate) {
self.is_a_rate
.store(automation_rate.is_a_rate(), Ordering::Release);
}
}
#[derive(Debug)]
pub(crate) struct AudioParamProcessor {
default_value: f32, // immutable
min_value: f32, // immutable
max_value: f32, // immutable
intrinsic_value: f32,
automation_rate: AutomationRate,
shared_parts: Arc<AudioParamShared>,
event_timeline: AudioParamEventTimeline,
last_event: Option<AudioParamEvent>,
buffer: Vec<f32>,
}
impl AudioProcessor for AudioParamProcessor {
fn process(
&mut self,
inputs: &[AudioRenderQuantum],
outputs: &mut [AudioRenderQuantum],
_params: AudioParamValues<'_>,
scope: &RenderScope,
) -> bool {
let period = 1. / scope.sample_rate as f64;
let input = &inputs[0]; // single input mode
let output = &mut outputs[0];
self.compute_intrinsic_values(scope.current_time, period, RENDER_QUANTUM_SIZE);
self.mix_to_output(input, output);
true // has intrinsic value
}
fn onmessage(&mut self, msg: Box<dyn std::any::Any + Send + 'static>) {
if let Some(&automation_rate) = msg.downcast_ref::<AutomationRate>() {
self.automation_rate = automation_rate;
self.shared_parts.store_automation_rate(automation_rate);
return;
}
match msg.downcast::<AudioParamEvent>() {
Ok(event) => self.handle_incoming_event(*event),
_ => log::warn!("AudioParamProcessor: Ignoring incoming message"),
}
}
}
impl AudioParamProcessor {
// warning: tick in called directly in the unit tests so everything important
// for the tests should be done here
fn compute_intrinsic_values(&mut self, block_time: f64, dt: f64, count: usize) -> &[f32] {
self.compute_buffer(block_time, dt, count);
self.buffer.as_slice()
}
fn mix_to_output(&mut self, input: &AudioRenderQuantum, output: &mut AudioRenderQuantum) {
#[cfg(test)]
assert!(self.buffer.len() == 1 || self.buffer.len() == RENDER_QUANTUM_SIZE);
if self.buffer.len() == 1 && input.is_silent() {
let mut value = self.buffer[0];
if value.is_nan() {
value = self.default_value;
}
output.set_single_valued(true);
let output_channel = output.channel_data_mut(0);
output_channel[0] = value.clamp(self.min_value, self.max_value);
} else {
// @note: we could add two other optimizations here:
// - when buffer.len() == 1 and buffer[0] == 0., then we don't need to
// zip and add, but we still need to clamp
// - when input.is_silent(), then we can copy_from_slice the buffer into
// output and then just clamp
*output = input.clone();
output.set_single_valued(false);
output
.channel_data_mut(0)
.iter_mut()
.zip(self.buffer.iter().cycle())
.for_each(|(o, p)| {
*o += p;
if o.is_nan() {
*o = self.default_value;
}
*o = o.clamp(self.min_value, self.max_value)
});
}
}
// 𝑣(𝑡) = 𝑉0 + (𝑉1−𝑉0) * ((𝑡−𝑇0) / (𝑇1−𝑇0))
#[inline(always)]
fn compute_linear_ramp_sample(
&self,
start_time: f64,
duration: f64,
start_value: f32,
diff: f32, // end_value - start_value
time: f64,
) -> f32 {
let phase = (time - start_time) / duration;
diff.mul_add(phase as f32, start_value)
}
// v(t) = v1 * (v2/v1)^((t-t1) / (t2-t1))
#[inline(always)]
fn compute_exponential_ramp_sample(
&self,
start_time: f64,
duration: f64,
start_value: f32,
ratio: f32, // end_value / start_value
time: f64,
) -> f32 {
let phase = (time - start_time) / duration;
start_value * ratio.powf(phase as f32)
}
// 𝑣(𝑡) = 𝑉1 + (𝑉0 − 𝑉1) * 𝑒^−((𝑡−𝑇0) / 𝜏)
#[inline(always)]
fn compute_set_target_sample(
&self,
start_time: f64,
time_constant: f64,
end_value: f32,
diff: f32, // start_value - end_value
time: f64,
) -> f32 {
let exponent = -1. * ((time - start_time) / time_constant);
diff.mul_add(exponent.exp() as f32, end_value)
}
// 𝑘=⌊𝑁−1 / 𝑇𝐷 * (𝑡−𝑇0)⌋
// Then 𝑣(𝑡) is computed by linearly interpolating between 𝑉[𝑘] and 𝑉[𝑘+1],
#[inline(always)]
fn compute_set_value_curve_sample(
&self,
start_time: f64,
duration: f64,
values: &[f32],
time: f64,
) -> f32 {
if time - start_time >= duration {
values[values.len() - 1]
} else {
let position = (values.len() - 1) as f64 * (time - start_time) / duration;
let k = position as usize;
let phase = (position - position.floor()) as f32;
(values[k + 1] - values[k]).mul_add(phase, values[k])
}
}
fn handle_incoming_event(&mut self, event: AudioParamEvent) {
// cf. https://www.w3.org/TR/webaudio/#computation-of-value
// 1. paramIntrinsicValue will be calculated at each time, which is either the
// value set directly to the value attribute, or, if there are any automation
// events with times before or at this time, the value as calculated from
// these events. If automation events are removed from a given time range,
// then the paramIntrinsicValue value will remain unchanged and stay at its
// previous value until either the value attribute is directly set, or
// automation events are added for the time range.
// handle CancelScheduledValues events
// cf. https://www.w3.org/TR/webaudio/#dom-audioparam-cancelscheduledvalues
if event.event_type == AudioParamEventType::CancelScheduledValues {
// peek current event before inserting new events, and possibly sort
// the queue, we need that for checking that we are (or not) in the middle
// of a ramp when handling `CancelScheduledValues`
// @note - probably not robust enough in some edge cases where the
// event is not the first received at this tick (`SetValueCurveAtTime`
// and `CancelAndHold` need to sort the queue)
let some_current_event = self.event_timeline.unsorted_peek();
match some_current_event {
None => (),
Some(current_event) => {
// @note - The spec is not particularly clear about what to do
// with on-going SetTarget events, but both Chrome and Firefox
// ignore the Cancel event if at same time nor if startTime is
// equal to cancelTime, this can makes sens as the event time
// (which is a `startTime` for `SetTarget`) is before the `cancelTime`
// (maybe this should be clarified w/ spec editors)
match current_event.event_type {
AudioParamEventType::LinearRampToValueAtTime
| AudioParamEventType::ExponentialRampToValueAtTime => {
// we are in the middle of a ramp
//
// @note - Firefox and Chrome behave differently
// on this: Firefox actually restore intrinsic_value
// from the value at the beginning of the vent, while
// Chrome just keeps the current intrinsic_value
// The spec is not very clear there, but Firefox
// seems to be more compliant:
// "Any active automations whose automation event
// time is less than cancelTime are also cancelled,
// and such cancellations may cause discontinuities
// because the original value (**from before such
// automation**) is restored immediately."
//
// @note - last_event cannot be `None` here, because
// linear or exponential ramps are always preceded
// by another event (even a set_value_at_time
// inserted implicitly), so if the ramp is the next
// event that means that at least one event has
// already been processed.
if current_event.time >= event.time {
let last_event = self.last_event.as_ref().unwrap();
self.intrinsic_value = last_event.value;
}
}
_ => (),
}
}
}
// remove all events in queue where event.time >= cancel_time
// i.e. keep all events where event.time < cancel_time
self.event_timeline
.retain(|queued| queued.time < event.time);
return; // cancel_values events are not inserted in queue
}
if event.event_type == AudioParamEventType::CancelAndHoldAtTime {
// 1. Let 𝐸1 be the event (if any) at time 𝑡1 where 𝑡1 is the
// largest number satisfying 𝑡1 ≤ 𝑡𝑐.
// 2. Let 𝐸2 be the event (if any) at time 𝑡2 where 𝑡2 is the
// smallest number satisfying 𝑡𝑐 < 𝑡2.
let mut e1: Option<&mut AudioParamEvent> = None;
let mut e2: Option<&mut AudioParamEvent> = None;
let mut t1 = f64::MIN;
let mut t2 = f64::MAX;
// we need a sorted timeline here to find siblings
self.event_timeline.sort();
for queued in self.event_timeline.iter_mut() {
// closest before cancel time: if several events at same time,
// we want the last one
if queued.time >= t1 && queued.time <= event.time {
t1 = queued.time;
e1 = Some(queued);
// closest after cancel time: if several events at same time,
// we want the first one
} else if queued.time < t2 && queued.time > event.time {
t2 = queued.time;
e2 = Some(queued);
}
}
// If 𝐸2 exists:
if let Some(matched) = e2 {
// If 𝐸2 is a linear or exponential ramp,
// Effectively rewrite 𝐸2 to be the same kind of ramp ending
// at time 𝑡𝑐 with an end value that would be the value of the
// original ramp at time 𝑡𝑐.
// @note - this is done during the actual computation of the
// ramp using the cancel_time
if matched.event_type == AudioParamEventType::LinearRampToValueAtTime
|| matched.event_type == AudioParamEventType::ExponentialRampToValueAtTime
{
matched.cancel_time = Some(event.time);
}
} else if let Some(matched) = e1 {
if matched.event_type == AudioParamEventType::SetTargetAtTime {
// Implicitly insert a setValueAtTime event at time 𝑡𝑐 with
// the value that the setTarget would
// @note - same strategy as for ramps
matched.cancel_time = Some(event.time);
} else if matched.event_type == AudioParamEventType::SetValueCurveAtTime {
// If 𝐸1 is a setValueCurve with a start time of 𝑡3 and a duration of 𝑑
// If 𝑡𝑐 <= 𝑡3 + 𝑑 :
// Effectively replace this event with a setValueCurve event
// with a start time of 𝑡3 and a new duration of 𝑡𝑐−𝑡3. However,
// this is not a true replacement; this automation MUST take
// care to produce the same output as the original, and not
// one computed using a different duration. (That would cause
// sampling of the value curve in a slightly different way,
// producing different results.)
let start_time = matched.time;
let duration = matched.duration.unwrap();
if event.time <= start_time + duration {
matched.cancel_time = Some(event.time);
}
}
}
// [spec] Remove all events with time greater than 𝑡𝑐.
self.event_timeline.retain(|queued| {
let mut time = queued.time;
// if the event has a `cancel_time` we use it instead of `time`
if let Some(cancel_time) = queued.cancel_time {
time = cancel_time;
}
time <= event.time
});
return; // cancel_and_hold events are not inserted timeline
}
// handle SetValueCurveAtTime
// @note - These rules argue in favor of having events inserted in
// the control thread, let's panic for now
//
// [spec] If setValueCurveAtTime() is called for time 𝑇 and duration 𝐷
// and there are any events having a time strictly greater than 𝑇, but
// strictly less than 𝑇+𝐷, then a NotSupportedError exception MUST be thrown.
// In other words, it’s not ok to schedule a value curve during a time period
// containing other events, but it’s ok to schedule a value curve exactly
// at the time of another event.
if event.event_type == AudioParamEventType::SetValueCurveAtTime {
// check if we don't try to insert at the time of another event
let start_time = event.time;
let end_time = start_time + event.duration.unwrap();
for queued in self.event_timeline.iter() {
if queued.time > start_time && queued.time < end_time {
panic!(
"NotSupportedError: scheduling SetValueCurveAtTime ({:?}) at
time of another automation event ({:?})",
event, queued,
);
}
}
}
// [spec] Similarly a NotSupportedError exception MUST be thrown if any
// automation method is called at a time which is contained in [𝑇,𝑇+𝐷), 𝑇
// being the time of the curve and 𝐷 its duration.
// @note - Cancel methods are not automation methods
if event.event_type == AudioParamEventType::SetValueAtTime
|| event.event_type == AudioParamEventType::SetValue
|| event.event_type == AudioParamEventType::LinearRampToValueAtTime
|| event.event_type == AudioParamEventType::ExponentialRampToValueAtTime
|| event.event_type == AudioParamEventType::SetTargetAtTime
{
for queued in self.event_timeline.iter() {
if queued.event_type == AudioParamEventType::SetValueCurveAtTime {
let start_time = queued.time;
let end_time = start_time + queued.duration.unwrap();
if event.time > start_time && event.time < end_time {
panic!(
"NotSupportedError: scheduling automation event ({:?})
during SetValueCurveAtTime ({:?})",
event, queued,
);
}
}
}
}
// handle SetValue - param intrinsic value must be updated from event value
if event.event_type == AudioParamEventType::SetValue {
self.intrinsic_value = event.value;
}
// If no event in the timeline and event_type is `LinearRampToValueAtTime`
// or `ExponentialRampToValue` at time, we must insert a `SetValueAtTime`
// with intrinsic value and calling time.
// cf. https://www.w3.org/TR/webaudio/#dom-audioparam-linearramptovalueattime
// cf. https://www.w3.org/TR/webaudio/#dom-audioparam-exponentialramptovalueattime
if self.event_timeline.is_empty()
&& self.last_event.is_none()
&& (event.event_type == AudioParamEventType::LinearRampToValueAtTime
|| event.event_type == AudioParamEventType::ExponentialRampToValueAtTime)
{
let set_value_event = AudioParamEvent {
event_type: AudioParamEventType::SetValue,
value: self.intrinsic_value,
// make sure the event is applied before any other event, time
// will be replaced by the block timestamp during event processing
time: 0.,
time_constant: None,
cancel_time: None,
duration: None,
values: None,
};
self.event_timeline.push(set_value_event);
}
// for SetTarget, this behavior is not per se specified, but it allows
// to make sure we have a stable start_value available without having
// to store it elsewhere.
if self.event_timeline.is_empty()
&& event.event_type == AudioParamEventType::SetTargetAtTime
{
let set_value_event = AudioParamEvent {
event_type: AudioParamEventType::SetValue,
value: self.intrinsic_value,
// make sure the event is applied before any other event, time
// will be replaced by the block timestamp during event processing
time: 0.,
time_constant: None,
cancel_time: None,
duration: None,
values: None,
};
self.event_timeline.push(set_value_event);
}
self.event_timeline.push(event);
self.event_timeline.sort();
}
fn compute_buffer(&mut self, block_time: f64, dt: f64, count: usize) {
// Set [[current value]] to the value of paramIntrinsicValue at the
// beginning of this render quantum.
let clamped = self.intrinsic_value.clamp(self.min_value, self.max_value);
self.shared_parts.store_current_value(clamped);
// clear the buffer for this block
self.buffer.clear();
let is_a_rate = self.automation_rate.is_a_rate();
let is_k_rate = !is_a_rate;
let next_block_time = dt.mul_add(count as f64, block_time);
// Check if we can safely return a buffer of length 1 even for a-rate params.
// Several cases allow us to do so:
// - The timeline is empty
// - The timeline is not empty: in such case if `event.time >= next_block_time`
// AND `event_type` is not `LinearRampToValueAtTime` or `ExponentialRampToValueAtTime`
// this is safe, i.e.:
// + For linear and exponential ramps `event.time` is the end time while their
// start time is `last_event.time`, therefore if `peek()` is of these
// types, we are in the middle of the ramp.
// + For all other event, `event.time` is their start time.
// (@note - `SetTargetAtTime` events also uses `last_event` but only for
// its value, not for its timing information, so no problem there)
let is_constant_block = match self.event_timeline.peek() {
None => true,
Some(event) => {
if event.event_type != AudioParamEventType::LinearRampToValueAtTime
&& event.event_type != AudioParamEventType::ExponentialRampToValueAtTime
{
event.time >= next_block_time
} else {
false
}
}
};
if is_k_rate || is_constant_block {
self.buffer.push(self.intrinsic_value);
// nothing to compute in timeline, for both k-rate and a-rate
if is_constant_block {
return;
}
}
loop {
let some_event = self.event_timeline.peek();
match some_event {
None => {
if is_a_rate {
self.buffer.resize(count, self.intrinsic_value);
}
break;
}
Some(event) => {
match event.event_type {
AudioParamEventType::SetValue | AudioParamEventType::SetValueAtTime => {
let value = event.value;
let mut time = event.time;
// `set_value` calls and implicitly inserted events
// are inserted with a `time = 0.` to make sure
// they are processed first, replacing w/ block_time
// allows to conform to the spec:
// cf. https://www.w3.org/TR/webaudio/#dom-audioparam-value
// cf. https://www.w3.org/TR/webaudio/#dom-audioparam-linearramptovalueattime
// cf. https://www.w3.org/TR/webaudio/#dom-audioparam-exponentialramptovalueattime
if time == 0. {
time = block_time;
}
// fill buffer with current intrinsic value until `event.time`
if is_a_rate {
let end_index = ((time - block_time).max(0.) / dt) as usize;
let end_index_clipped = end_index.min(count);
for _ in self.buffer.len()..end_index_clipped {
self.buffer.push(self.intrinsic_value);
}
}
if time > next_block_time {
break;
} else {
self.intrinsic_value = value;
// no computation has been done on `time`
#[allow(clippy::float_cmp)]
if time != event.time {
// store as last event with the applied time
let mut event = self.event_timeline.pop().unwrap();
event.time = time;
self.last_event = Some(event);
} else {
self.last_event = self.event_timeline.pop();
}
}
}
// cf. https://www.w3.org/TR/webaudio/#dom-audioparam-linearramptovalueattime
// 𝑣(𝑡) = 𝑉0 + (𝑉1−𝑉0) * ((𝑡−𝑇0) / (𝑇1−𝑇0))
AudioParamEventType::LinearRampToValueAtTime => {
let last_event = self.last_event.as_ref().unwrap();
let start_time = last_event.time;
let mut end_time = event.time;
// compute duration before clapping `end_time` to
// `cancel_time` to keep declared slope of the ramp
let duration = end_time - start_time;
if let Some(cancel_time) = event.cancel_time {
end_time = cancel_time;
}
let start_value = last_event.value;
let end_value = event.value;
let diff = end_value - start_value;
if is_a_rate {
let start_index = self.buffer.len();
// we need to `ceil()` because if `end_time` is between two samples
// we actually want the sample before `end_time` to be computed
let end_index =
((end_time - block_time).max(0.) / dt).ceil() as usize;
let end_index_clipped = end_index.min(count);
// compute "real" value according to `t` then clamp it
// cf. Example 7 https://www.w3.org/TR/webaudio/#computation-of-value
if end_index_clipped > start_index {
let mut time = (start_index as f64).mul_add(dt, block_time);
for _ in start_index..end_index_clipped {
let value = self.compute_linear_ramp_sample(
start_time,
duration,
start_value,
diff,
time,
);
self.buffer.push(value);
time += dt;
self.intrinsic_value = value;
}
}
}
// Event will continue in next tick:
// compute value for `next_block_time` so that `param.value()`
// stays coherent, also allows to properly fill k-rate
// within next block too
if end_time >= next_block_time {
let value = self.compute_linear_ramp_sample(
start_time,
duration,
start_value,
diff,
next_block_time,
);
self.intrinsic_value = value;
break;
// Event cancelled during this block
} else if event.cancel_time.is_some() {
let value = self.compute_linear_ramp_sample(
start_time,
duration,
start_value,
diff,
end_time,
);
self.intrinsic_value = value;
let mut last_event = self.event_timeline.pop().unwrap();
last_event.time = end_time;
last_event.value = value;
self.last_event = Some(last_event);
// Event ended during this block
} else {
self.intrinsic_value = end_value;
self.last_event = self.event_timeline.pop();
}
}
// cf. https://www.w3.org/TR/webaudio/#dom-audioparam-exponentialramptovalueattime
// v(t) = v1 * (v2/v1)^((t-t1) / (t2-t1))
AudioParamEventType::ExponentialRampToValueAtTime => {
let last_event = self.last_event.as_ref().unwrap();
let start_time = last_event.time;
let mut end_time = event.time;
// compute duration before clapping `end_time` to
// `cancel_time` to keep declared slope of the ramp
let duration = end_time - start_time;
if let Some(cancel_time) = event.cancel_time {
end_time = cancel_time;
}
let start_value = last_event.value;
let end_value = event.value;
let ratio = end_value / start_value;
// Handle edge cases:
// > If 𝑉0 and 𝑉1 have opposite signs or if 𝑉0 is zero,
// > then 𝑣(𝑡)=𝑉0 for 𝑇0≤𝑡<𝑇1.
// as:
// > If there are no more events after this ExponentialRampToValue
// > event then for 𝑡≥𝑇1, 𝑣(𝑡)=𝑉1.
// this should thus behave as a SetValue
if start_value == 0. || start_value * end_value < 0. {
let event = AudioParamEvent {
event_type: AudioParamEventType::SetValueAtTime,
time: end_time,
value: end_value,
time_constant: None,
cancel_time: None,
duration: None,
values: None,
};
self.event_timeline.replace_peek(event);
} else {
if is_a_rate {
let start_index = self.buffer.len();
// we need to `ceil()` because if `end_time` is between two samples
// we actually want the sample before `end_time` to be computed
// @todo - more tests
let end_index =
((end_time - block_time).max(0.) / dt).ceil() as usize;
let end_index_clipped = end_index.min(count);
if end_index_clipped > start_index {
let mut time = (start_index as f64).mul_add(dt, block_time);
for _ in start_index..end_index_clipped {
let value = self.compute_exponential_ramp_sample(
start_time,
duration,
start_value,
ratio,
time,
);
self.buffer.push(value);
self.intrinsic_value = value;
time += dt;
}
}
}
// Event will continue in next tick:
// compute value for `next_block_time` so that `param.value()`
// stays coherent, also allows to properly fill k-rate
// within next block too
if end_time >= next_block_time {
let value = self.compute_exponential_ramp_sample(
start_time,
duration,
start_value,
ratio,
next_block_time,
);
self.intrinsic_value = value;
break;
// Event cancelled during this block
} else if event.cancel_time.is_some() {
let value = self.compute_exponential_ramp_sample(
start_time,
duration,
start_value,
ratio,
end_time,
);
self.intrinsic_value = value;
let mut last_event = self.event_timeline.pop().unwrap();
last_event.time = end_time;
last_event.value = value;
self.last_event = Some(last_event);
// Event ended during this block
} else {
self.intrinsic_value = end_value;
self.last_event = self.event_timeline.pop();
}
}
}
// https://webaudio.github.io/web-audio-api/#dom-audioparam-settargetattime
// 𝑣(𝑡) = 𝑉1 + (𝑉0 − 𝑉1) * 𝑒^−((𝑡−𝑇0) / 𝜏)
//
// @todo - as SetTarget never resolves on an end value, some
// strategy could be implemented here so that when the value
// is close enough to the target a SetValue event could be
// inserted in the timeline. This could be done at k-rate.
// Note that Chrome has such strategy, cf. `HasSetTargetConverged`
AudioParamEventType::SetTargetAtTime => {
let mut end_time = next_block_time;
let mut ended = false;
// handle next event stop SetTarget if any
let some_next_event = self.event_timeline.next();
if let Some(next_event) = some_next_event {
match next_event.event_type {
AudioParamEventType::LinearRampToValueAtTime
| AudioParamEventType::ExponentialRampToValueAtTime => {
// [spec] If the preceding event is a SetTarget
// event, 𝑇0 and 𝑉0 are chosen from the current
// time and value of SetTarget automation. That
// is, if the SetTarget event has not started,
// 𝑇0 is the start time of the event, and 𝑉0
// is the value just before the SetTarget event
// starts. In this case, the LinearRampToValue
// event effectively replaces the SetTarget event.
// If the SetTarget event has already started,
// 𝑇0 is the current context time, and 𝑉0 is
// the current SetTarget automation value at time 𝑇0.
// In both cases, the automation curve is continuous.
end_time = block_time;
ended = true;
}
_ => {
// For all other events, the SetTarget
// event ends at the time of the next event.
if next_event.time < next_block_time {
end_time = next_event.time;
ended = true;
}
}
}
}
// handle CancelAndHoldAtTime
if let Some(cancel_time) = event.cancel_time {
if cancel_time < next_block_time {
end_time = cancel_time;
ended = true;
}
}
let start_time = event.time;
// if SetTarget is the first event registered, we implicitly
// insert a SetValue event just before just as for Ramps.
// Therefore we are sure last_event exists
let start_value = self.last_event.as_ref().unwrap().value;
let end_value = event.value;
let diff = start_value - end_value;
let time_constant = event.time_constant.unwrap();
if is_a_rate {
let start_index = self.buffer.len();
// we need to `ceil()` because if `end_time` is between two samples
// we actually want the sample before `end_time` to be computed
// @todo - more tests
let end_index =
((end_time - block_time).max(0.) / dt).ceil() as usize;
let end_index_clipped = end_index.min(count);
if end_index_clipped > start_index {
let mut time = (start_index as f64).mul_add(dt, block_time);
for _ in start_index..end_index_clipped {
// check if we have reached start_time
let value = if time - start_time < 0. {
self.intrinsic_value
} else {
self.compute_set_target_sample(
start_time,
time_constant,
end_value,
diff,
time,
)
};
self.buffer.push(value);
self.intrinsic_value = value;
time += dt;
}
}
}
if !ended {
// compute value for `next_block_time` so that `param.value()`
// stays coherent (see. comment in `AudioParam`)
// allows to properly fill k-rate within next block too
let value = self.compute_set_target_sample(
start_time,
time_constant,
end_value,
diff,
next_block_time,
);
let diff = (end_value - value).abs();
// abort event if diff is below SNAP_TO_TARGET
if diff < SNAP_TO_TARGET {
self.intrinsic_value = end_value;
// if end_value is zero, the buffer might contain
// subnormals, we need to check that and flush to zero
if end_value == 0. {
for v in self.buffer.iter_mut() {
if v.is_subnormal() {
*v = 0.;
}
}
}
let event = AudioParamEvent {
event_type: AudioParamEventType::SetValueAtTime,
time: next_block_time,
value: end_value,
time_constant: None,
cancel_time: None,
duration: None,
values: None,
};
self.event_timeline.replace_peek(event);
} else {
self.intrinsic_value = value;
}
break;
} else {
// setTarget has no "real" end value, compute according
// to next event start time
let value = self.compute_set_target_sample(
start_time,
time_constant,
end_value,
diff,
end_time,
);
self.intrinsic_value = value;
// end_value and end_time must be stored for use
// as start time by next event
let mut event = self.event_timeline.pop().unwrap();
event.time = end_time;
event.value = value;
self.last_event = Some(event);
}
}
AudioParamEventType::SetValueCurveAtTime => {
let start_time = event.time;
let duration = event.duration.unwrap();
let values = event.values.as_ref().unwrap();
let mut end_time = start_time + duration;
// we must check for the cancel event after we have
// the "real" duration computed to not change the
// slope of the ramp
if let Some(cancel_time) = event.cancel_time {
end_time = cancel_time;
}
if is_a_rate {
let start_index = self.buffer.len();
// we need to `ceil()` because if `end_time` is between two samples
// we actually want the sample before `end_time` to be computed
// @todo - more tests
let end_index =
((end_time - block_time).max(0.) / dt).ceil() as usize;
let end_index_clipped = end_index.min(count);
if end_index_clipped > start_index {
let mut time = (start_index as f64).mul_add(dt, block_time);
for _ in start_index..end_index_clipped {
// check if we have reached start_time
let value = if time - start_time < 0. {
self.intrinsic_value
} else {
self.compute_set_value_curve_sample(
start_time, duration, values, time,
)
};
self.buffer.push(value);
self.intrinsic_value = value;
time += dt;
}
}
}
// event will continue in next tick
if end_time >= next_block_time {
// compute value for `next_block_time` so that `param.value()`
// stays coherent (see. comment in `AudioParam`)
// allows to properly fill k-rate within next block too
let value = self.compute_set_value_curve_sample(
start_time,
duration,
values,
next_block_time,
);
self.intrinsic_value = value;
break;
// handle end of event during this block
} else {
// event has been cancelled
if event.cancel_time.is_some() {
let value = self.compute_set_value_curve_sample(
start_time, duration, values, end_time,
);
self.intrinsic_value = value;
let mut last_event = self.event_timeline.pop().unwrap();
last_event.time = end_time;
last_event.value = value;
self.last_event = Some(last_event);
// event has ended
} else {
let value = values[values.len() - 1];
let mut last_event = self.event_timeline.pop().unwrap();
last_event.time = end_time;
last_event.value = value;
self.intrinsic_value = value;
self.last_event = Some(last_event);
}
}
}
_ => panic!(
"AudioParamEvent {:?} should not appear in AudioParamEventTimeline",
event.event_type
),
}
}
}
}
}
}
pub(crate) fn audio_param_pair(
descriptor: AudioParamDescriptor,
registration: AudioContextRegistration,
) -> (AudioParam, AudioParamProcessor) {
let AudioParamDescriptor {
automation_rate,
default_value,
max_value,
min_value,
} = descriptor;
let shared_parts = Arc::new(AudioParamShared::new(default_value, automation_rate));
let param = AudioParam {
registration,
raw_parts: AudioParamRaw {
default_value,
max_value,
min_value,
automation_rate_constrained: false,
shared_parts: Arc::clone(&shared_parts),
},
};
let processor = AudioParamProcessor {
intrinsic_value: default_value,
default_value,
min_value,
max_value,
automation_rate,
shared_parts,
event_timeline: AudioParamEventTimeline::new(),
last_event: None,
buffer: Vec::with_capacity(RENDER_QUANTUM_SIZE),
};
(param, processor)
}
#[cfg(test)]
mod tests {
use float_eq::assert_float_eq;
use crate::context::{BaseAudioContext, OfflineAudioContext};
use crate::render::Alloc;
use super::*;
#[test]
#[should_panic]
fn test_assert_non_negative_fail() {
assert_non_negative(-1.);
}
#[test]
fn test_assert_non_negative() {
assert_non_negative(0.);
}
#[test]
#[should_panic]
fn test_assert_strictly_positive_fail() {
assert_strictly_positive(0.);
}
#[test]
fn test_assert_strictly_positive() {
assert_strictly_positive(0.1);
}
#[test]
#[should_panic]
fn test_assert_not_zero_fail() {
assert_not_zero(0.);
}
#[test]
fn test_assert_not_zero() {
assert_not_zero(-0.1);
assert_not_zero(0.1);
}
#[test]
#[should_panic]
fn test_assert_sequence_length_fail() {
assert_sequence_length(&[0.; 1]);
}
#[test]
fn test_assert_sequence_length() {
assert_sequence_length(&[0.; 2]);
}
#[test]
fn test_default_and_accessors() {
let context = OfflineAudioContext::new(1, 0, 48000.);
let opts = AudioParamDescriptor {
automation_rate: AutomationRate::A,
default_value: 0.,
min_value: -10.,
max_value: 10.,
};
let (param, _render) = audio_param_pair(opts, context.mock_registration());
assert_eq!(param.automation_rate(), AutomationRate::A);
assert_float_eq!(param.default_value(), 0., abs_all <= 0.);
assert_float_eq!(param.min_value(), -10., abs_all <= 0.);
assert_float_eq!(param.max_value(), 10., abs_all <= 0.);
assert_float_eq!(param.value(), 0., abs_all <= 0.);
}
#[test]
fn test_set_value() {
{
let context = OfflineAudioContext::new(1, 0, 48000.);
let opts = AudioParamDescriptor {
automation_rate: AutomationRate::A,
default_value: 0.,
min_value: -10.,
max_value: 10.,
};
let (param, mut render) = audio_param_pair(opts, context.mock_registration());
render.handle_incoming_event(param.set_value_raw(2.));
assert_float_eq!(param.value(), 2., abs_all <= 0.);
let vs = render.compute_intrinsic_values(0., 1., 10);
assert_float_eq!(param.value(), 2., abs_all <= 0.);
assert_float_eq!(vs, &[2.; 10][..], abs_all <= 0.);
}
// make sure param.value() is properly clamped
{
let context = OfflineAudioContext::new(1, 0, 48000.);
let opts = AudioParamDescriptor {
automation_rate: AutomationRate::A,
default_value: 0.,
min_value: 0.,
max_value: 1.,
};
let (param, mut render) = audio_param_pair(opts, context.mock_registration());
render.handle_incoming_event(param.set_value_raw(2.));
assert_float_eq!(param.value(), 1., abs_all <= 0.);
let vs = render.compute_intrinsic_values(0., 1., 10);
// value should clamped while intrinsic value should not
assert_float_eq!(param.value(), 1., abs_all <= 0.);
assert_float_eq!(vs, &[2.; 10][..], abs_all <= 0.);
}
}
#[test]
fn test_steps_a_rate() {
let context = OfflineAudioContext::new(1, 0, 48000.);
{
let opts = AudioParamDescriptor {
automation_rate: AutomationRate::A,
default_value: 0.,
min_value: -10.,
max_value: 10.,
};
let (param, mut render) = audio_param_pair(opts, context.mock_registration());
render.handle_incoming_event(param.set_value_at_time_raw(5., 2.0));
render.handle_incoming_event(param.set_value_at_time_raw(12., 8.0)); // should clamp
render.handle_incoming_event(param.set_value_at_time_raw(8., 10.0)); // should not occur 1st run
let vs = render.compute_intrinsic_values(0., 1., 10);
assert_float_eq!(
vs,
&[0., 0., 5., 5., 5., 5., 5., 5., 12., 12.][..],
abs_all <= 0.
);
// no event left in timeline, i.e. length is 1
let vs = render.compute_intrinsic_values(10., 1., 10);
assert_float_eq!(vs, &[8.; 1][..], abs_all <= 0.);
}
{
// events spread on several blocks
let opts = AudioParamDescriptor {
automation_rate: AutomationRate::A,
default_value: 0.,
min_value: -10.,
max_value: 10.,
};
let (param, mut render) = audio_param_pair(opts, context.mock_registration());
render.handle_incoming_event(param.set_value_at_time_raw(5., 2.0));
render.handle_incoming_event(param.set_value_at_time_raw(8., 12.0));
let vs = render.compute_intrinsic_values(0., 1., 10);
assert_float_eq!(
vs,
&[0., 0., 5., 5., 5., 5., 5., 5., 5., 5.][..],
abs_all <= 0.
);
let vs = render.compute_intrinsic_values(10., 1., 10);
assert_float_eq!(
vs,
&[5., 5., 8., 8., 8., 8., 8., 8., 8., 8.][..],
abs_all <= 0.
);
}
}
#[test]
fn test_steps_k_rate() {
let context = OfflineAudioContext::new(1, 0, 48000.);
let opts = AudioParamDescriptor {
automation_rate: AutomationRate::K,
default_value: 0.,
min_value: -10.,
max_value: 10.,
};
let (param, mut render) = audio_param_pair(opts, context.mock_registration());
render.handle_incoming_event(param.set_value_at_time_raw(5., 2.0));
render.handle_incoming_event(param.set_value_at_time_raw(12., 8.0)); // should not appear in results
render.handle_incoming_event(param.set_value_at_time_raw(8., 10.0)); // should not occur 1st run
render.handle_incoming_event(param.set_value_at_time_raw(3., 14.0)); // should appear in 3rd run
let vs = render.compute_intrinsic_values(0., 1., 10);
assert_float_eq!(vs, &[0.; 1][..], abs_all <= 0.);
let vs = render.compute_intrinsic_values(10., 1., 10);
assert_float_eq!(vs, &[8.; 1][..], abs_all <= 0.);
let vs = render.compute_intrinsic_values(20., 1., 10);
assert_float_eq!(vs, &[3.; 1][..], abs_all <= 0.);
}
#[test]
fn test_linear_ramp_arate() {
let context = OfflineAudioContext::new(1, 0, 48000.);
let opts = AudioParamDescriptor {
automation_rate: AutomationRate::A,
default_value: 0.,
min_value: -10.,
max_value: 10.,
};
let (param, mut render) = audio_param_pair(opts, context.mock_registration());
// set to 5 at t = 2
render.handle_incoming_event(param.set_value_at_time_raw(5., 2.0));
// ramp to 8 from t = 2 to t = 5
render.handle_incoming_event(param.linear_ramp_to_value_at_time_raw(8.0, 5.0));
// ramp to 0 from t = 5 to t = 13
render.handle_incoming_event(param.linear_ramp_to_value_at_time_raw(0., 13.0));
let vs = render.compute_intrinsic_values(0., 1., 10);
assert_float_eq!(
vs,
&[0., 0., 5., 6., 7., 8., 7., 6., 5., 4.][..],
abs_all <= 0.
);
}
#[test]
fn test_linear_ramp_arate_end_of_block() {
let context = OfflineAudioContext::new(1, 0, 48000.);
let opts = AudioParamDescriptor {
automation_rate: AutomationRate::A,
default_value: 0.,
min_value: -10.,
max_value: 10.,
};
let (param, mut render) = audio_param_pair(opts, context.mock_registration());
// set to 0 at t = 0
render.handle_incoming_event(param.set_value_at_time_raw(0., 0.));
// ramp to 9 from t = 0 to t = 9
render.handle_incoming_event(param.linear_ramp_to_value_at_time_raw(9.0, 9.0));
let vs = render.compute_intrinsic_values(0., 1., 10);
assert_float_eq!(
vs,
&[0., 1., 2., 3., 4., 5., 6., 7., 8., 9.][..],
abs_all <= 0.
);
}
#[test]
// @note - with real params, a set_value event is always used to provide
// init value to the param. Therefore this test is purely theoretical and
// in real world the param would not behave like that, which is wrong
// @todo - open an issue to review how init value is passed (or how last_event is set)
fn test_linear_ramp_arate_implicit_set_value() {
let context = OfflineAudioContext::new(1, 0, 48000.);
let opts = AudioParamDescriptor {
automation_rate: AutomationRate::A,
default_value: 0.,
min_value: -10.,
max_value: 10.,
};
let (param, mut render) = audio_param_pair(opts, context.mock_registration());
// mimic a ramp inserted after start
// i.e. setTimeout(() => param.linearRampToValueAtTime(10, now + 10)), 10 * 1000);
// no event in timeline here, i.e. length is 1
let vs = render.compute_intrinsic_values(0., 1., 10);
assert_float_eq!(vs, &[0.; 1][..], abs_all <= 0.);
// implicitly insert a SetValue event at time 10
render.handle_incoming_event(param.linear_ramp_to_value_at_time_raw(10.0, 20.0));
let vs = render.compute_intrinsic_values(10., 1., 10);
assert_float_eq!(
vs,
&[0., 1., 2., 3., 4., 5., 6., 7., 8., 9.][..],
abs_all <= 0.
);
// ramp finishes on first value of this block, i.e. length is 10
let vs = render.compute_intrinsic_values(20., 1., 10);
assert_float_eq!(vs, &[10.; 10][..], abs_all <= 0.);
}
#[test]
fn test_linear_ramp_arate_multiple_blocks() {
// regression test for issue #9
let context = OfflineAudioContext::new(1, 0, 48000.);
let opts = AudioParamDescriptor {
automation_rate: AutomationRate::A,
default_value: 0.,
min_value: -20.,
max_value: 20.,
};
let (param, mut render) = audio_param_pair(opts, context.mock_registration());
// ramp to 20 from t = 0 to t = 20
render.handle_incoming_event(param.linear_ramp_to_value_at_time_raw(20.0, 20.0));
// first quantum t = 0..10
let vs = render.compute_intrinsic_values(0., 1., 10);
assert_float_eq!(
vs,
&[0., 1., 2., 3., 4., 5., 6., 7., 8., 9.][..],
abs_all <= 0.
);
assert_float_eq!(param.value(), 0., abs <= 0.);
// next quantum t = 10..20
let vs = render.compute_intrinsic_values(10., 1., 10);
assert_float_eq!(
vs,
&[10., 11., 12., 13., 14., 15., 16., 17., 18., 19.][..],
abs_all <= 0.
);
assert_float_eq!(param.value(), 10., abs <= 0.);
// ramp finished t = 20..30
let vs = render.compute_intrinsic_values(20., 1., 10);
assert_float_eq!(vs, &[20.0; 10][..], abs_all <= 0.);
assert_float_eq!(param.value(), 20., abs <= 0.);
}
#[test]
fn test_linear_ramp_krate_multiple_blocks() {
// regression test for issue #9
let context = OfflineAudioContext::new(1, 0, 48000.);
{
let opts = AudioParamDescriptor {
automation_rate: AutomationRate::K,
default_value: 0.,
min_value: -20.,
max_value: 20.,
};
let (param, mut render) = audio_param_pair(opts, context.mock_registration());
// ramp to 20 from t = 0 to t = 20
render.handle_incoming_event(param.linear_ramp_to_value_at_time_raw(20.0, 20.0));
// first quantum t = 0..10
let vs = render.compute_intrinsic_values(0., 1., 10);
assert_float_eq!(vs, &[0.; 1][..], abs_all <= 0.);
assert_float_eq!(param.value(), 0., abs <= 0.);
// next quantum t = 10..20
let vs = render.compute_intrinsic_values(10., 1., 10);
assert_float_eq!(vs, &[10.; 1][..], abs_all <= 0.);
assert_float_eq!(param.value(), 10., abs <= 0.);
// ramp finished t = 20..30
let vs = render.compute_intrinsic_values(20., 1., 10);
assert_float_eq!(vs, &[20.0; 1][..], abs_all <= 0.);
assert_float_eq!(param.value(), 20., abs <= 0.);
}
{
// finish in the middle of a block
let opts = AudioParamDescriptor {
automation_rate: AutomationRate::K,
default_value: 0.,
min_value: -20.,
max_value: 20.,
};
let (param, mut render) = audio_param_pair(opts, context.mock_registration());
// ramp to 20 from t = 0 to t = 20
render.handle_incoming_event(param.linear_ramp_to_value_at_time_raw(15.0, 15.0));
// first quantum t = 0..10
let vs = render.compute_intrinsic_values(0., 1., 10);
assert_float_eq!(vs, &[0.; 1][..], abs_all <= 0.);
assert_float_eq!(param.value(), 0., abs <= 0.);
// next quantum t = 10..20
let vs = render.compute_intrinsic_values(10., 1., 10);
assert_float_eq!(vs, &[10.; 1][..], abs_all <= 0.);
assert_float_eq!(param.value(), 10., abs <= 0.);
// ramp finished t = 20..30
let vs = render.compute_intrinsic_values(20., 1., 10);
assert_float_eq!(vs, &[15.0; 1][..], abs_all <= 0.);
assert_float_eq!(param.value(), 15., abs <= 0.);
}
}
#[test]
fn test_linear_ramp_start_time() {
let context = OfflineAudioContext::new(1, 0, 48000.);
let opts = AudioParamDescriptor {
automation_rate: AutomationRate::A,
default_value: 0.,
min_value: -10.,
max_value: 10.,
};
let (param, mut render) = audio_param_pair(opts, context.mock_registration());
render.handle_incoming_event(param.set_value_at_time_raw(1., 0.));
render.handle_incoming_event(param.linear_ramp_to_value_at_time_raw(-1., 10.));
let vs = render.compute_intrinsic_values(0., 1., 10);
assert_float_eq!(
vs,
&[1., 0.8, 0.6, 0.4, 0.2, 0., -0.2, -0.4, -0.6, -0.8][..],
abs_all <= 1e-7
);
let vs = render.compute_intrinsic_values(10., 1., 10);
assert_float_eq!(vs, &[-1.; 10][..], abs_all <= 0.);
// start time should be end time of last event, i.e. 10.
render.handle_incoming_event(param.linear_ramp_to_value_at_time_raw(1., 30.));
let vs = render.compute_intrinsic_values(20., 1., 10);
assert_float_eq!(
vs,
&[0., 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9][..],
abs_all <= 1e-7
);
}
#[test]
fn test_exponential_ramp_a_rate() {
let context = OfflineAudioContext::new(1, 0, 48000.);
let opts = AudioParamDescriptor {
automation_rate: AutomationRate::A,
default_value: 0.,
min_value: 0.,
max_value: 1.,
};
let (param, mut render) = audio_param_pair(opts, context.mock_registration());
// set to 0.0001 at t=0 (0. is a special case)
render.handle_incoming_event(param.set_value_at_time_raw(0.0001, 0.));
// ramp to 1 from t = 0 to t = 10
render.handle_incoming_event(param.exponential_ramp_to_value_at_time_raw(1.0, 10.));
// compute resulting buffer:
// v(t) = v1*(v2/v1)^((t-t1)/(t2-t1))
let mut res = Vec::<f32>::with_capacity(10);
let start: f32 = 0.0001;
let end: f32 = 1.;
for t in 0..10 {
let value = start * (end / start).powf(t as f32 / 10.);
res.push(value);
}
let vs = render.compute_intrinsic_values(0., 1., 10);
assert_float_eq!(vs, &res[..], abs_all <= 0.);
let vs = render.compute_intrinsic_values(10., 1., 10);
assert_float_eq!(vs, &[1.0; 10][..], abs_all <= 0.);
}
#[test]
fn test_exponential_ramp_a_rate_multiple_blocks() {
let context = OfflineAudioContext::new(1, 0, 48000.);
let opts = AudioParamDescriptor {
automation_rate: AutomationRate::A,
default_value: 0.,
min_value: 0.,
max_value: 1.,
};
let (param, mut render) = audio_param_pair(opts, context.mock_registration());
let start: f32 = 0.0001; // use 0.0001 as 0. is a special case
let end: f32 = 1.;
render.handle_incoming_event(param.set_value_at_time_raw(start, 3.));
// ramp to 1 from t = 3. to t = 13.
render.handle_incoming_event(param.exponential_ramp_to_value_at_time_raw(end, 13.));
// compute resulting buffer:
let mut res = vec![0.; 3];
// set_value is implicit here as this is the first value of the computed ramp
// exponential ramp (v(t) = v1*(v2/v1)^((t-t1)/(t2-t1)))
for t in 0..10 {
let value = start * (end / start).powf(t as f32 / 10.);
res.push(value);
}
// fill remaining with target value
res.append(&mut vec![1.; 7]);
let vs = render.compute_intrinsic_values(0., 1., 10);
assert_float_eq!(vs, &res[0..10], abs_all <= 0.);
assert_float_eq!(param.value(), res[0], abs <= 0.);
let vs = render.compute_intrinsic_values(10., 1., 10);
assert_float_eq!(vs, &res[10..20], abs_all <= 0.);
assert_float_eq!(param.value(), res[10], abs <= 0.);
}
#[test]
fn test_exponential_ramp_a_rate_zero_and_opposite_target() {
let context = OfflineAudioContext::new(1, 0, 48000.);
{
// zero target
let opts = AudioParamDescriptor {
automation_rate: AutomationRate::A,
default_value: 0.,
min_value: 0.,
max_value: 1.,
};
let (param, mut render) = audio_param_pair(opts, context.mock_registration());
// set v=0. at t=0 (0. is a special case)
render.handle_incoming_event(param.set_value_at_time_raw(0., 0.));
// ramp to 1 from t=0 to t=5 -> should behave as a set target at t=5
render.handle_incoming_event(param.exponential_ramp_to_value_at_time_raw(1.0, 5.));
let vs = render.compute_intrinsic_values(0., 1., 10);
assert_float_eq!(
vs,
&[0., 0., 0., 0., 0., 1., 1., 1., 1., 1.][..],
abs_all <= 0.
);
}
{
// opposite signs
let opts = AudioParamDescriptor {
automation_rate: AutomationRate::A,
default_value: 0.,
min_value: -1.,
max_value: 1.,
};
let (param, mut render) = audio_param_pair(opts, context.mock_registration());
// set v=-1. at t=0
render.handle_incoming_event(param.set_value_at_time_raw(-1., 0.));
// ramp to 1 from t=0 to t=5 -> should behave as a set target at t=5
render.handle_incoming_event(param.exponential_ramp_to_value_at_time_raw(1.0, 5.));
let vs = render.compute_intrinsic_values(0., 1., 10);
assert_float_eq!(
vs,
&[-1., -1., -1., -1., -1., 1., 1., 1., 1., 1.][..],
abs_all <= 0.
);
}
}
#[test]
#[should_panic]
fn test_exponential_ramp_to_zero() {
let context = OfflineAudioContext::new(1, 0, 48000.);
let opts = AudioParamDescriptor {
automation_rate: AutomationRate::A,
default_value: 1.,
min_value: 0.,
max_value: 1.,
};
let (param, mut render) = audio_param_pair(opts, context.mock_registration());
render.handle_incoming_event(param.exponential_ramp_to_value_at_time_raw(0.0, 10.));
}
#[test]
fn test_exponential_ramp_k_rate_multiple_blocks() {
let context = OfflineAudioContext::new(1, 0, 48000.);
let opts = AudioParamDescriptor {
automation_rate: AutomationRate::K,
default_value: 0.,
min_value: 0.,
max_value: 1.,
};
let (param, mut render) = audio_param_pair(opts, context.mock_registration());
let start: f32 = 0.0001; // use 0.0001 as 0. is a special case
let end: f32 = 1.;
render.handle_incoming_event(param.set_value_at_time_raw(start, 3.));
// ramp to 1 from t = 3. to t = 13.
render.handle_incoming_event(param.exponential_ramp_to_value_at_time_raw(end, 13.));
// compute resulting buffer:
let mut res = vec![0.; 3];
// set_value is implicit here as this is the first value of the computed ramp
// exponential ramp (v(t) = v1*(v2/v1)^((t-t1)/(t2-t1)))
for t in 0..10 {
let value = start * (end / start).powf(t as f32 / 10.);
res.push(value);
}
// fill remaining with target value
res.append(&mut vec![1.; 7]);
// recreate k-rate blocks from computed values
let vs = render.compute_intrinsic_values(0., 1., 10);
assert_float_eq!(vs, &[res[0]; 1][..], abs_all <= 0.);
let vs = render.compute_intrinsic_values(10., 1., 10);
assert_float_eq!(vs, &[res[10]; 1][..], abs_all <= 0.);
let vs = render.compute_intrinsic_values(20., 1., 10);
assert_float_eq!(vs, &[1.; 1][..], abs_all <= 0.);
}
#[test]
fn test_exponential_ramp_k_rate_zero_and_opposite_target() {
let context = OfflineAudioContext::new(1, 0, 48000.);
{
// zero target
let opts = AudioParamDescriptor {
automation_rate: AutomationRate::K,
default_value: 0.,
min_value: 0.,
max_value: 1.,
};
let (param, mut render) = audio_param_pair(opts, context.mock_registration());
// ramp to 1 from t=0 to t=5 -> should behave as a set target at t=5
render.handle_incoming_event(param.exponential_ramp_to_value_at_time_raw(1.0, 5.));
let vs = render.compute_intrinsic_values(0., 1., 10);
assert_float_eq!(vs, &[0.; 1][..], abs_all <= 0.);
let vs = render.compute_intrinsic_values(10., 1., 10);
assert_float_eq!(vs, &[1.; 1][..], abs_all <= 0.);
}
{
// opposite signs
let opts = AudioParamDescriptor {
automation_rate: AutomationRate::K,
default_value: -1.,
min_value: -1.,
max_value: 1.,
};
let (param, mut render) = audio_param_pair(opts, context.mock_registration());
// ramp to 1 from t=0 to t=5 -> should behave as a set target at t=5
render.handle_incoming_event(param.exponential_ramp_to_value_at_time_raw(1.0, 5.));
let vs = render.compute_intrinsic_values(0., 1., 10);
assert_float_eq!(vs, &[-1.; 1][..], abs_all <= 0.);
let vs = render.compute_intrinsic_values(10., 1., 10);
assert_float_eq!(vs, &[1.; 1][..], abs_all <= 0.);
}
}
#[test]
fn test_exponential_ramp_start_time() {
let context = OfflineAudioContext::new(1, 0, 48000.);
let opts = AudioParamDescriptor {
automation_rate: AutomationRate::A,
default_value: 0.,
min_value: -10.,
max_value: 10.,
};
let (param, mut render) = audio_param_pair(opts, context.mock_registration());
render.handle_incoming_event(param.set_value_at_time_raw(0., 0.));
render.handle_incoming_event(param.linear_ramp_to_value_at_time_raw(1., 10.));
let vs = render.compute_intrinsic_values(0., 1., 10);
assert_float_eq!(
vs,
&[0., 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9][..],
abs_all <= 1e-7
);
let vs = render.compute_intrinsic_values(10., 1., 10);
assert_float_eq!(vs, &[1.; 10][..], abs_all <= 0.);
// start time should be end time of last event, i.e. 10.
render.handle_incoming_event(param.exponential_ramp_to_value_at_time_raw(0.0001, 30.));
let vs = render.compute_intrinsic_values(20., 1., 10);
// compute expected on 20 samples, the 10 last ones should be in vs
let start: f32 = 1.;
let end: f32 = 0.0001;
let mut res = [0.; 20];
for (t, v) in res.iter_mut().enumerate() {
*v = start * (end / start).powf(t as f32 / 20.);
}
assert_float_eq!(vs, &res[10..], abs_all <= 1e-7);
}
#[test]
fn test_set_target_at_time_a_rate() {
let context = OfflineAudioContext::new(1, 0, 48000.);
{
let opts = AudioParamDescriptor {
automation_rate: AutomationRate::A,
default_value: 0.,
min_value: 0.,
max_value: 1.,
};
let (param, mut render) = audio_param_pair(opts, context.mock_registration());
// 𝑣(𝑡) = 𝑉1 + (𝑉0 − 𝑉1) * 𝑒^−((𝑡−𝑇0) / 𝜏)
let v0: f32 = 0.;
let v1: f32 = 1.;
let t0: f64 = 0.;
let time_constant: f64 = 1.;
render.handle_incoming_event(param.set_value_at_time_raw(v0, t0));
render.handle_incoming_event(param.set_target_at_time_raw(v1, t0, time_constant));
let vs = render.compute_intrinsic_values(0., 1., 10);
let mut res = Vec::<f32>::with_capacity(10);
for t in 0..10 {
let val = v1 + (v0 - v1) * (-1. * ((t as f64 - t0) / time_constant)).exp() as f32;
res.push(val);
}
assert_float_eq!(vs, &res[..], abs_all <= 0.);
}
{
// implicit SetValue if SetTarget is first event
let opts = AudioParamDescriptor {
automation_rate: AutomationRate::A,
default_value: 0.,
min_value: 0.,
max_value: 1.,
};
let (param, mut render) = audio_param_pair(opts, context.mock_registration());
// 𝑣(𝑡) = 𝑉1 + (𝑉0 − 𝑉1) * 𝑒^−((𝑡−𝑇0) / 𝜏)
let v0: f32 = 0.; // will be implicitly set in param (see default_value)
let v1: f32 = 1.;
let t0: f64 = 0.;
let time_constant: f64 = 1.;
render.handle_incoming_event(param.set_target_at_time_raw(v1, t0, time_constant));
let vs = render.compute_intrinsic_values(0., 1., 10);
let mut res = Vec::<f32>::with_capacity(10);
for t in 0..10 {
let val = v1 + (v0 - v1) * (-1. * ((t as f64 - t0) / time_constant)).exp() as f32;
res.push(val);
}
assert_float_eq!(vs, &res[..], abs_all <= 0.);
}
{
// start later in block with arbitrary values
let opts = AudioParamDescriptor {
automation_rate: AutomationRate::A,
default_value: 0.,
min_value: 0.,
max_value: 100.,
};
let (param, mut render) = audio_param_pair(opts, context.mock_registration());
// 𝑣(𝑡) = 𝑉1 + (𝑉0 − 𝑉1) * 𝑒^−((𝑡−𝑇0) / 𝜏)
let v0: f32 = 1.;
let v1: f32 = 42.;
let t0: f64 = 1.;
let time_constant: f64 = 2.1;
render.handle_incoming_event(param.set_value_at_time_raw(v0, t0));
render.handle_incoming_event(param.set_target_at_time_raw(v1, t0, time_constant));
let mut res = Vec::<f32>::with_capacity(10);
for t in 0..10 {
let val = v1 + (v0 - v1) * (-1. * ((t as f64 - t0) / time_constant)).exp() as f32;
res.push(val);
}
// start_time is 1.
res[0] = 0.;
let vs = render.compute_intrinsic_values(0., 1., 10);
assert_float_eq!(vs, &res[..], abs_all <= 0.);
}
{
// handle time_constant == 0.
let opts = AudioParamDescriptor {
automation_rate: AutomationRate::A,
default_value: 0.,
min_value: 0.,
max_value: 100.,
};
let (param, mut render) = audio_param_pair(opts, context.mock_registration());
render.handle_incoming_event(param.set_target_at_time_raw(1., 1., 0.));
let mut res = [1.; 10];
res[0] = 0.; // start_time is 1.
let vs = render.compute_intrinsic_values(0., 1., 10);
assert_float_eq!(vs, &res[..], abs_all <= 0.);
}
}
#[test]
fn test_set_target_at_time_a_rate_multiple_blocks() {
let context = OfflineAudioContext::new(1, 0, 48000.);
{
let opts = AudioParamDescriptor {
automation_rate: AutomationRate::A,
default_value: 0.,
min_value: 0.,
max_value: 2.,
};
let (param, mut render) = audio_param_pair(opts, context.mock_registration());
// 𝑣(𝑡) = 𝑉1 + (𝑉0 − 𝑉1) * 𝑒^−((𝑡−𝑇0) / 𝜏)
let v0: f32 = 0.;
let v1: f32 = 2.;
let t0: f64 = 0.;
let time_constant: f64 = 1.;
// ramp to 1 from t=0 to t=5 -> should behave as a set target at t=5
render.handle_incoming_event(param.set_value_at_time_raw(v0, t0));
render.handle_incoming_event(param.set_target_at_time_raw(v1, t0, time_constant));
let mut res = Vec::<f32>::with_capacity(20);
for t in 0..20 {
let val = v1 + (v0 - v1) * (-1. * ((t as f64 - t0) / time_constant)).exp() as f32;
res.push(val);
}
let vs = render.compute_intrinsic_values(0., 1., 10);
assert_float_eq!(vs, &res[0..10], abs_all <= 0.);
let vs = render.compute_intrinsic_values(10., 1., 10);
assert_float_eq!(vs, &res[10..20], abs_all <= 0.);
}
}
#[test]
fn test_set_target_at_time_a_rate_followed_by_set_value() {
let context = OfflineAudioContext::new(1, 0, 48000.);
{
let opts = AudioParamDescriptor {
automation_rate: AutomationRate::A,
default_value: 0.,
min_value: 0.,
max_value: 2.,
};
let (param, mut render) = audio_param_pair(opts, context.mock_registration());
// 𝑣(𝑡) = 𝑉1 + (𝑉0 − 𝑉1) * 𝑒^−((𝑡−𝑇0) / 𝜏)
let v0: f32 = 0.;
let v1: f32 = 2.;
let t0: f64 = 0.;
let time_constant: f64 = 1.;
render.handle_incoming_event(param.set_value_at_time_raw(v0, t0));
render.handle_incoming_event(param.set_target_at_time_raw(v1, t0, time_constant));
render.handle_incoming_event(param.set_value_at_time_raw(0.5, 15.));
let mut res = Vec::<f32>::with_capacity(20);
for t in 0..15 {
let val = v1 + (v0 - v1) * (-1. * ((t as f64 - t0) / time_constant)).exp() as f32;
res.push(val);
}
res.resize(20, 0.5);
let vs = render.compute_intrinsic_values(0., 1., 10);
assert_float_eq!(vs, &res[0..10], abs_all <= 0.);
let vs = render.compute_intrinsic_values(10., 1., 10);
assert_float_eq!(vs, &res[10..20], abs_all <= 0.);
}
}
#[test]
fn test_set_target_at_time_ends_at_threshold() {
let context = OfflineAudioContext::new(1, 0, 48000.);
let opts = AudioParamDescriptor {
automation_rate: AutomationRate::A,
default_value: 0.,
min_value: 0.,
max_value: 2.,
};
let (param, mut render) = audio_param_pair(opts, context.mock_registration());
render.handle_incoming_event(param.set_value_at_time_raw(1., 0.));
render.handle_incoming_event(param.set_target_at_time_raw(0., 1., 0.2));
let vs = render.compute_intrinsic_values(0., 1., 128);
for v in vs.iter() {
assert!(!v.is_subnormal());
}
// check peek() has been replaced with set_value event
let peek = render.event_timeline.peek();
assert_eq!(
peek.unwrap().event_type,
AudioParamEventType::SetValueAtTime
);
// this buffer should be filled with target values
let vs = render.compute_intrinsic_values(10., 1., 128);
assert_float_eq!(vs[..], [0.; 128], abs_all <= 0.);
}
#[test]
fn test_set_target_at_time_waits_for_start_time() {
let context = OfflineAudioContext::new(1, 0, 48000.);
let opts = AudioParamDescriptor {
automation_rate: AutomationRate::A,
default_value: 0.,
min_value: 0.,
max_value: 2.,
};
let (param, mut render) = audio_param_pair(opts, context.mock_registration());
render.handle_incoming_event(param.set_value_at_time_raw(1., 0.));
render.handle_incoming_event(param.set_target_at_time_raw(0., 5., 1.));
let vs = render.compute_intrinsic_values(0., 1., 10);
assert_float_eq!(vs[0], 1., abs <= 0.);
assert_float_eq!(vs[1], 1., abs <= 0.);
assert_float_eq!(vs[2], 1., abs <= 0.);
assert_float_eq!(vs[3], 1., abs <= 0.);
assert_float_eq!(vs[4], 1., abs <= 0.);
assert_float_eq!(vs[5], 1., abs <= 0.);
}
#[test]
fn test_set_target_at_time_a_rate_followed_by_ramp() {
let context = OfflineAudioContext::new(1, 0, 48000.);
{
let opts = AudioParamDescriptor {
automation_rate: AutomationRate::A,
default_value: 0.,
min_value: 0.,
max_value: 10.,
};
let (param, mut render) = audio_param_pair(opts, context.mock_registration());
// 𝑣(𝑡) = 𝑉1 + (𝑉0 − 𝑉1) * 𝑒^−((𝑡−𝑇0) / 𝜏)
let v0: f32 = 0.;
let v1: f32 = 2.;
let t0: f64 = 0.;
let time_constant: f64 = 10.;
render.handle_incoming_event(param.set_value_at_time_raw(v0, t0));
render.handle_incoming_event(param.set_target_at_time_raw(v1, t0, time_constant));
let mut res = Vec::<f32>::with_capacity(20);
for t in 0..11 {
// we compute the 10th elements as it will be the start value of the ramp
let val = v1 + (v0 - v1) * (-1. * ((t as f64 - t0) / time_constant)).exp() as f32;
res.push(val);
}
let vs = render.compute_intrinsic_values(0., 1., 10);
assert_float_eq!(vs, &res[0..10], abs_all <= 0.);
// ramp
let v0 = res.pop().unwrap(); // v0 is defined by the SetTarget
let v1 = 10.;
let t0 = 10.;
let t1 = 20.;
render.handle_incoming_event(param.linear_ramp_to_value_at_time_raw(v1, t1));
for t in 10..20 {
let time = t as f64;
let value = v0 + (v1 - v0) * (time - t0) as f32 / (t1 - t0) as f32;
res.push(value);
}
let vs = render.compute_intrinsic_values(10., 1., 10);
assert_float_eq!(vs, &res[10..20], abs_all <= 1.0e-6);
// ramp ended
let vs = render.compute_intrinsic_values(20., 1., 10);
assert_float_eq!(vs, &[v1; 10][..], abs_all <= 0.);
}
}
#[test]
fn test_set_target_at_time_k_rate_multiple_blocks() {
let context = OfflineAudioContext::new(1, 0, 48000.);
{
let opts = AudioParamDescriptor {
automation_rate: AutomationRate::K,
default_value: 0.,
min_value: 0.,
max_value: 2.,
};
let (param, mut render) = audio_param_pair(opts, context.mock_registration());
// 𝑣(𝑡) = 𝑉1 + (𝑉0 − 𝑉1) * 𝑒^−((𝑡−𝑇0) / 𝜏)
let v0: f32 = 0.;
let v1: f32 = 2.;
let t0: f64 = 0.;
let time_constant: f64 = 1.;
// ramp to 1 from t=0 to t=5 -> should behave as a set target at t=5
render.handle_incoming_event(param.set_value_at_time_raw(v0, t0));
render.handle_incoming_event(param.set_target_at_time_raw(v1, t0, time_constant));
let mut res = Vec::<f32>::with_capacity(20);
for t in 0..20 {
let val = v1 + (v0 - v1) * (-1. * ((t as f64 - t0) / time_constant)).exp() as f32;
res.push(val);
}
let vs = render.compute_intrinsic_values(0., 1., 10);
assert_float_eq!(vs, &[res[0]; 1][..], abs_all <= 0.);
let vs = render.compute_intrinsic_values(10., 1., 10);
assert_float_eq!(vs, &[res[10]; 1][..], abs_all <= 0.);
}
}
#[test]
// regression test for bcebfe6
fn test_set_target_at_time_snap_to_value() {
let context = OfflineAudioContext::new(1, 0, 48000.);
let opts = AudioParamDescriptor {
automation_rate: AutomationRate::A,
default_value: 0.,
min_value: 0.,
max_value: 1.,
};
let (param, mut render) = audio_param_pair(opts, context.mock_registration());
let v0: f32 = 1.;
let v1: f32 = 0.;
let t0: f64 = 0.;
let time_constant: f64 = 1.;
render.handle_incoming_event(param.set_value_at_time_raw(v0, t0));
render.handle_incoming_event(param.set_target_at_time_raw(v1, t0, time_constant));
let mut res = [0.; 30];
// 𝑣(𝑡) = 𝑉1 + (𝑉0 − 𝑉1) * 𝑒^−((𝑡−𝑇0) / 𝜏)
res.iter_mut().enumerate().for_each(|(t, r)| {
*r = v1 + (v0 - v1) * (-1. * ((t as f64 - t0) / time_constant)).exp() as f32;
});
let vs = render.compute_intrinsic_values(0., 1., 10);
assert_float_eq!(vs, &res[..10], abs_all <= 0.);
let vs = render.compute_intrinsic_values(10., 1., 10);
assert_float_eq!(vs, &res[10..20], abs_all <= 0.);
// the distance between the target value and the value just after this block
// is smaller than SNAP_TO_TARGET (i.e. 1e-10)
let vs = render.compute_intrinsic_values(20., 1., 10);
assert_float_eq!(vs, &res[20..30], abs_all <= 0.);
// then this block should be [0.; 10]
let vs = render.compute_intrinsic_values(30., 1., 10);
assert_float_eq!(vs, &[0.; 10][..], abs_all <= 0.);
}
#[test]
fn test_cancel_scheduled_values() {
let context = OfflineAudioContext::new(1, 0, 48000.);
let opts = AudioParamDescriptor {
automation_rate: AutomationRate::A,
default_value: 0.,
min_value: 0.,
max_value: 10.,
};
let (param, mut render) = audio_param_pair(opts, context.mock_registration());
for t in 0..10 {
render.handle_incoming_event(param.set_value_at_time_raw(t as f32, t as f64));
}
render.handle_incoming_event(param.cancel_scheduled_values_raw(5.));
let vs = render.compute_intrinsic_values(0., 1., 10);
assert_float_eq!(
vs,
&[0., 1., 2., 3., 4., 4., 4., 4., 4., 4.][..],
abs_all <= 0.
);
}
#[test]
fn test_cancel_scheduled_values_ramp() {
let context = OfflineAudioContext::new(1, 0, 48000.);
{
let opts = AudioParamDescriptor {
automation_rate: AutomationRate::A,
default_value: 0.,
min_value: 0.,
max_value: 10.,
};
let (param, mut render) = audio_param_pair(opts, context.mock_registration());
render.handle_incoming_event(param.set_value_at_time_raw(0., 0.));
render.handle_incoming_event(param.linear_ramp_to_value_at_time_raw(10., 10.));
// cancels the ramp, the set value event is kept in timeline
render.handle_incoming_event(param.cancel_scheduled_values_raw(10.));
let vs = render.compute_intrinsic_values(0., 1., 10);
assert_float_eq!(vs, &[0.; 10][..], abs_all <= 0.);
}
// ramp already started, go back to previous value
{
let opts = AudioParamDescriptor {
automation_rate: AutomationRate::A,
default_value: 0.,
min_value: 0.,
max_value: 20.,
};
let (param, mut render) = audio_param_pair(opts, context.mock_registration());
render.handle_incoming_event(param.set_value_at_time_raw(0., 0.));
render.handle_incoming_event(param.linear_ramp_to_value_at_time_raw(20., 20.));
let vs = render.compute_intrinsic_values(0., 1., 10);
assert_float_eq!(
vs,
&[0., 1., 2., 3., 4., 5., 6., 7., 8., 9.][..],
abs_all <= 0.
);
// the SetValue event has been consumed in first tick and the ramp
// is removed from timeline, no event left in timeline (length is 1)
render.handle_incoming_event(param.cancel_scheduled_values_raw(10.));
let vs = render.compute_intrinsic_values(10., 1., 10);
assert_float_eq!(vs, &[0.; 1][..], abs_all <= 0.);
}
// make sure we can't go into a situation where next_event is a ramp
// and last_event is not defined
// @see - note in CancelScheduledValues insertion in timeline
{
let opts = AudioParamDescriptor {
automation_rate: AutomationRate::A,
default_value: 0.,
min_value: 0.,
max_value: 10.,
};
let (param, mut render) = audio_param_pair(opts, context.mock_registration());
// the SetValue from param inserted by the Ramp is left in timeline
// i.e. length is 10
render.handle_incoming_event(param.linear_ramp_to_value_at_time_raw(10., 10.));
render.handle_incoming_event(param.cancel_scheduled_values_raw(10.)); // cancels the ramp
let vs = render.compute_intrinsic_values(0., 1., 10);
assert_float_eq!(vs, &[0.; 10][..], abs_all <= 0.);
}
{
let opts = AudioParamDescriptor {
automation_rate: AutomationRate::A,
default_value: 0.,
min_value: 0.,
max_value: 20.,
};
let (param, mut render) = audio_param_pair(opts, context.mock_registration());
render.handle_incoming_event(param.linear_ramp_to_value_at_time_raw(20., 20.));
let vs = render.compute_intrinsic_values(0., 1., 10);
assert_float_eq!(
vs,
&[0., 1., 2., 3., 4., 5., 6., 7., 8., 9.][..],
abs_all <= 0.
);
// ramp is removed from timeline, no event left
render.handle_incoming_event(param.cancel_scheduled_values_raw(10.));
let vs = render.compute_intrinsic_values(10., 1., 10);
assert_float_eq!(vs, &[0.; 1][..], abs_all <= 0.);
}
}
#[test]
fn test_cancel_and_hold() {
let context = OfflineAudioContext::new(1, 0, 48000.);
{
let opts = AudioParamDescriptor {
automation_rate: AutomationRate::A,
default_value: 0.,
min_value: 0.,
max_value: 10.,
};
let (param, mut render) = audio_param_pair(opts, context.mock_registration());
render.handle_incoming_event(param.set_value_at_time_raw(1., 1.));
render.handle_incoming_event(param.set_value_at_time_raw(2., 2.));
render.handle_incoming_event(param.set_value_at_time_raw(3., 3.));
render.handle_incoming_event(param.set_value_at_time_raw(4., 4.));
render.handle_incoming_event(param.cancel_and_hold_at_time_raw(2.5));
let vs = render.compute_intrinsic_values(0., 1., 10);
assert_float_eq!(
vs,
&[0., 1., 2., 2., 2., 2., 2., 2., 2., 2.][0..10],
abs_all <= 0.
);
}
}
#[test]
fn test_cancel_and_hold_during_set_target() {
let context = OfflineAudioContext::new(1, 0, 48000.);
{
let opts = AudioParamDescriptor {
automation_rate: AutomationRate::A,
default_value: 0.,
min_value: 0.,
max_value: 2.,
};
let (param, mut render) = audio_param_pair(opts, context.mock_registration());
// 𝑣(𝑡) = 𝑉1 + (𝑉0 − 𝑉1) * 𝑒^−((𝑡−𝑇0) / 𝜏)
let v0: f32 = 0.;
let v1: f32 = 2.;
let t0: f64 = 0.;
let time_constant: f64 = 1.;
render.handle_incoming_event(param.set_value_at_time_raw(v0, t0));
render.handle_incoming_event(param.set_target_at_time_raw(v1, t0, time_constant));
render.handle_incoming_event(param.cancel_and_hold_at_time_raw(15.));
let mut res = Vec::<f32>::with_capacity(20);
// compute index 15 to have hold_value
for t in 0..16 {
let val = v1 + (v0 - v1) * (-1. * ((t as f64 - t0) / time_constant)).exp() as f32;
res.push(val);
}
let hold_value = res.pop().unwrap();
res.resize(20, hold_value);
let vs = render.compute_intrinsic_values(0., 1., 10);
assert_float_eq!(vs, &res[0..10], abs_all <= 0.);
let vs = render.compute_intrinsic_values(10., 1., 10);
assert_float_eq!(vs, &res[10..20], abs_all <= 0.);
}
}
#[test]
fn test_cancel_and_hold_during_linear_ramp() {
let context = OfflineAudioContext::new(1, 0, 48000.);
{
let opts = AudioParamDescriptor {
automation_rate: AutomationRate::A,
default_value: 0.,
min_value: 0.,
max_value: 10.,
};
let (param, mut render) = audio_param_pair(opts, context.mock_registration());
render.handle_incoming_event(param.linear_ramp_to_value_at_time_raw(10., 10.));
render.handle_incoming_event(param.cancel_and_hold_at_time_raw(5.));
let vs = render.compute_intrinsic_values(0., 1., 10);
assert_float_eq!(
vs,
&[0., 1., 2., 3., 4., 5., 5., 5., 5., 5.][0..10],
abs_all <= 0.
);
}
{
// cancel between two samples
let opts = AudioParamDescriptor {
automation_rate: AutomationRate::A,
default_value: 0.,
min_value: 0.,
max_value: 10.,
};
let (param, mut render) = audio_param_pair(opts, context.mock_registration());
render.handle_incoming_event(param.linear_ramp_to_value_at_time_raw(10., 10.));
render.handle_incoming_event(param.cancel_and_hold_at_time_raw(4.5));
let vs = render.compute_intrinsic_values(0., 1., 10);
assert_float_eq!(
vs,
&[0., 1., 2., 3., 4., 4.5, 4.5, 4.5, 4.5, 4.5][0..10],
abs_all <= 0.
);
}
}
#[test]
fn test_cancel_and_hold_during_exponential_ramp() {
let context = OfflineAudioContext::new(1, 0, 48000.);
{
let opts = AudioParamDescriptor {
automation_rate: AutomationRate::A,
default_value: 0.,
min_value: 0.,
max_value: 10.,
};
let (param, mut render) = audio_param_pair(opts, context.mock_registration());
// set to 0.0001 at t=0 (0. is a special case)
render.handle_incoming_event(param.set_value_at_time_raw(0.0001, 0.));
render.handle_incoming_event(param.exponential_ramp_to_value_at_time_raw(1.0, 10.));
render.handle_incoming_event(param.cancel_and_hold_at_time_raw(5.));
// compute resulting buffer:
// v(t) = v1*(v2/v1)^((t-t1)/(t2-t1))
let mut res = Vec::<f32>::with_capacity(10);
let start: f32 = 0.0001;
let end: f32 = 1.;
for t in 0..6 {
let value = start * (end / start).powf(t as f32 / 10.);
res.push(value);
}
let hold_value = res.pop().unwrap();
res.resize(10, hold_value);
let vs = render.compute_intrinsic_values(0., 1., 10);
assert_float_eq!(vs, &res[..], abs_all <= 0.);
}
{
// cancel between 2 samples
let opts = AudioParamDescriptor {
automation_rate: AutomationRate::A,
default_value: 0.,
min_value: 0.,
max_value: 10.,
};
let (param, mut render) = audio_param_pair(opts, context.mock_registration());
// set to 0.0001 at t=0 (0. is a special case)
render.handle_incoming_event(param.set_value_at_time_raw(0.0001, 0.));
render.handle_incoming_event(param.exponential_ramp_to_value_at_time_raw(1.0, 10.));
render.handle_incoming_event(param.cancel_and_hold_at_time_raw(4.5));
// compute resulting buffer:
// v(t) = v1*(v2/v1)^((t-t1)/(t2-t1))
let mut res = Vec::<f32>::with_capacity(10);
let start: f32 = 0.0001;
let end: f32 = 1.;
for t in 0..5 {
let value = start * (end / start).powf(t as f32 / 10.);
res.push(value);
}
let hold_value = start * (end / start).powf(4.5 / 10.);
res.resize(10, hold_value);
let vs = render.compute_intrinsic_values(0., 1., 10);
assert_float_eq!(vs, &res[..], abs_all <= 0.);
}
}
#[test]
fn test_cancel_and_hold_during_set_value_curve() {
let context = OfflineAudioContext::new(1, 0, 48000.);
{
let opts = AudioParamDescriptor {
automation_rate: AutomationRate::A,
default_value: 0.,
min_value: 0.,
max_value: 2.,
};
let (param, mut render) = audio_param_pair(opts, context.mock_registration());
let curve = [0., 0.5, 1., 0.5, 0.];
render.handle_incoming_event(param.set_value_curve_at_time_raw(&curve[..], 0., 10.));
render.handle_incoming_event(param.cancel_and_hold_at_time_raw(5.));
let vs = render.compute_intrinsic_values(0., 1., 10);
assert_float_eq!(
vs,
&[0., 0.2, 0.4, 0.6, 0.8, 1., 1., 1., 1., 1.][..],
abs_all <= 1e-7
);
}
{
// sub-sample
let opts = AudioParamDescriptor {
automation_rate: AutomationRate::A,
default_value: 0.,
min_value: 0.,
max_value: 2.,
};
let (param, mut render) = audio_param_pair(opts, context.mock_registration());
let curve = [0., 0.5, 1., 0.5, 0.];
render.handle_incoming_event(param.set_value_curve_at_time_raw(&curve[..], 0., 10.));
render.handle_incoming_event(param.cancel_and_hold_at_time_raw(4.5));
let vs = render.compute_intrinsic_values(0., 1., 10);
assert_float_eq!(
vs,
&[0., 0.2, 0.4, 0.6, 0.8, 0.9, 0.9, 0.9, 0.9, 0.9][..],
abs_all <= 1e-7
);
}
}
#[test]
fn test_set_value_curve_at_time_a_rate() {
let context = OfflineAudioContext::new(1, 0, 48000.);
let opts = AudioParamDescriptor {
automation_rate: AutomationRate::A,
default_value: 0.,
min_value: 0.,
max_value: 10.,
};
let (param, mut render) = audio_param_pair(opts, context.mock_registration());
// set to 0.0001 at t=0 (0. is a special case)
let curve = [0., 0.5, 1., 0.5, 0.];
render.handle_incoming_event(param.set_value_curve_at_time_raw(&curve[..], 0., 10.));
let vs = render.compute_intrinsic_values(0., 1., 10);
assert_float_eq!(
vs,
&[0., 0.2, 0.4, 0.6, 0.8, 1., 0.8, 0.6, 0.4, 0.2][..],
abs_all <= 1e-7
);
let vs = render.compute_intrinsic_values(10., 1., 10);
assert_float_eq!(vs, &[0.; 10][..], abs_all <= 0.);
}
#[test]
fn test_set_value_curve_at_time_a_rate_multiple_frames() {
let context = OfflineAudioContext::new(1, 0, 48000.);
let opts = AudioParamDescriptor {
automation_rate: AutomationRate::A,
default_value: 0.,
min_value: 0.,
max_value: 10.,
};
let (param, mut render) = audio_param_pair(opts, context.mock_registration());
// set to 0.0001 at t=0 (0. is a special case)
let curve = [0., 0.5, 1., 0.5, 0.];
render.handle_incoming_event(param.set_value_curve_at_time_raw(&curve[..], 0., 20.));
let vs = render.compute_intrinsic_values(0., 1., 10);
assert_float_eq!(
vs,
&[0., 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9][..],
abs_all <= 1e-7
);
let vs = render.compute_intrinsic_values(10., 1., 10);
assert_float_eq!(
vs,
&[1., 0.9, 0.8, 0.7, 0.6, 0.5, 0.4, 0.3, 0.2, 0.1][..],
abs_all <= 1e-7
);
let vs = render.compute_intrinsic_values(20., 1., 10);
assert_float_eq!(vs, &[0.; 10][..], abs_all <= 0.);
}
#[test]
#[should_panic]
fn test_set_value_curve_at_time_insert_while_another_event() {
let context = OfflineAudioContext::new(1, 0, 48000.);
let opts = AudioParamDescriptor {
automation_rate: AutomationRate::A,
default_value: 1.,
min_value: 0.,
max_value: 1.,
};
let (param, mut render) = audio_param_pair(opts, context.mock_registration());
render.handle_incoming_event(param.set_value_at_time_raw(0.0, 5.));
let curve = [0., 0.5, 1., 0.5, 0.];
render.handle_incoming_event(param.set_value_curve_at_time_raw(&curve[..], 0., 10.));
// this is necessary as the panic is triggered in the audio thread
// @note - argues in favor of maintaining the queue in control thread
let _vs = render.compute_intrinsic_values(0., 1., 10);
}
#[test]
#[should_panic]
fn test_set_value_curve_at_time_insert_another_event_inside() {
let context = OfflineAudioContext::new(1, 0, 48000.);
let opts = AudioParamDescriptor {
automation_rate: AutomationRate::A,
default_value: 1.,
min_value: 0.,
max_value: 1.,
};
let (param, mut render) = audio_param_pair(opts, context.mock_registration());
let curve = [0., 0.5, 1., 0.5, 0.];
render.handle_incoming_event(param.set_value_curve_at_time_raw(&curve[..], 0., 10.));
render.handle_incoming_event(param.set_value_at_time_raw(0.0, 5.));
// this is necessary as the panic is triggered in the audio thread
// @note - argues in favor of maintaining the queue in control thread
let _vs = render.compute_intrinsic_values(0., 1., 10);
}
#[test]
fn test_set_value_curve_waits_for_start_time() {
let context = OfflineAudioContext::new(1, 0, 48000.);
let opts = AudioParamDescriptor {
automation_rate: AutomationRate::A,
default_value: 0.,
min_value: 0.,
max_value: 10.,
};
let (param, mut render) = audio_param_pair(opts, context.mock_registration());
// set to 0.0001 at t=0 (0. is a special case)
let curve = [0., 0.5, 1., 0.5, 0.];
render.handle_incoming_event(param.set_value_curve_at_time_raw(&curve[..], 5., 10.));
let vs = render.compute_intrinsic_values(0., 1., 10);
assert_float_eq!(
vs,
&[0., 0., 0., 0., 0., 0., 0.2, 0.4, 0.6, 0.8][..],
abs_all <= 0.
);
}
#[test]
fn test_update_automation_rate_to_k() {
let context = OfflineAudioContext::new(1, 0, 48000.);
let opts = AudioParamDescriptor {
automation_rate: AutomationRate::A,
default_value: 0.,
min_value: -10.,
max_value: 10.,
};
let (param, mut render) = audio_param_pair(opts, context.mock_registration());
render.onmessage(Box::new(AutomationRate::K));
render.handle_incoming_event(param.set_value_at_time_raw(2., 0.000001));
let vs = render.compute_intrinsic_values(0., 1., 10);
assert_float_eq!(vs, &[0.; 1][..], abs_all <= 0.);
}
#[test]
fn test_update_automation_rate_to_a() {
let context = OfflineAudioContext::new(1, 0, 48000.);
let opts = AudioParamDescriptor {
automation_rate: AutomationRate::K,
default_value: 0.,
min_value: -10.,
max_value: 10.,
};
let (param, mut render) = audio_param_pair(opts, context.mock_registration());
render.onmessage(Box::new(AutomationRate::A));
render.handle_incoming_event(param.set_value_at_time_raw(2., 0.000001));
let vs = render.compute_intrinsic_values(0., 1., 10);
assert_float_eq!(vs, &[2.; 10][..], abs_all <= 0.);
}
#[test]
fn test_varying_param_size() {
// event registered online during rendering
{
let context = OfflineAudioContext::new(1, 0, 48000.);
let opts = AudioParamDescriptor {
automation_rate: AutomationRate::A,
default_value: 0.,
min_value: 0.,
max_value: 10.,
};
let (param, mut render) = audio_param_pair(opts, context.mock_registration());
render.handle_incoming_event(param.set_value_at_time_raw(0., 0.));
render.handle_incoming_event(param.linear_ramp_to_value_at_time_raw(9., 9.));
// first block should be length 10 (128 in real world)
let vs = render.compute_intrinsic_values(0., 1., 10);
let expected = [0., 1., 2., 3., 4., 5., 6., 7., 8., 9.];
assert_float_eq!(vs, &expected[..], abs_all <= 0.);
// second block should have length 1
let vs = render.compute_intrinsic_values(10., 1., 10);
let expected = [9.; 1];
assert_float_eq!(vs, &expected[..], abs_all <= 0.);
// insert event in third block, should have length 10
render.handle_incoming_event(param.set_value_at_time_raw(1., 25.));
let vs = render.compute_intrinsic_values(20., 1., 10);
let expected = [9., 9., 9., 9., 9., 1., 1., 1., 1., 1.];
assert_float_eq!(vs, &expected[..], abs_all <= 0.);
// fourth block should have length 1
let vs = render.compute_intrinsic_values(30., 1., 10);
let expected = [1.; 1];
assert_float_eq!(vs, &expected[..], abs_all <= 0.);
}
// event registered before rendering
{
let context = OfflineAudioContext::new(1, 0, 48000.);
let opts = AudioParamDescriptor {
automation_rate: AutomationRate::A,
default_value: 0.,
min_value: 0.,
max_value: 10.,
};
let (param, mut render) = audio_param_pair(opts, context.mock_registration());
render.handle_incoming_event(param.set_value_at_time_raw(0., 0.));
render.handle_incoming_event(param.linear_ramp_to_value_at_time_raw(9., 9.));
render.handle_incoming_event(param.set_value_at_time_raw(1., 25.));
// first block should be length 10 (128 in real world)
let vs = render.compute_intrinsic_values(0., 1., 10);
let expected = [0., 1., 2., 3., 4., 5., 6., 7., 8., 9.];
assert_float_eq!(vs, &expected[..], abs_all <= 0.);
// second block should have length 1
let vs = render.compute_intrinsic_values(10., 1., 10);
let expected = [9.; 1];
assert_float_eq!(vs, &expected[..], abs_all <= 0.);
// set value event in third block, length should be 10
let vs = render.compute_intrinsic_values(20., 1., 10);
let expected = [9., 9., 9., 9., 9., 1., 1., 1., 1., 1.];
assert_float_eq!(vs, &expected[..], abs_all <= 0.);
// fourth block should have length 1
let vs = render.compute_intrinsic_values(30., 1., 10);
let expected = [1.; 1];
assert_float_eq!(vs, &expected[..], abs_all <= 0.);
}
}
#[test]
fn test_varying_param_size_modulated() {
let alloc = Alloc::with_capacity(1);
// buffer length is 1 and input is silence (no modulation)
{
let context = OfflineAudioContext::new(1, 0, 48000.);
let opts = AudioParamDescriptor {
automation_rate: AutomationRate::A,
default_value: 0.,
min_value: 0.,
max_value: 10.,
};
let (_param, mut render) = audio_param_pair(opts, context.mock_registration());
// no event in timeline, buffer length is 1
let vs = render.compute_intrinsic_values(0., 1., 128);
assert_float_eq!(vs, &[0.; 1][..], abs_all <= 0.);
// mix to output step, input is silence
let signal = alloc.silence();
let input = AudioRenderQuantum::from(signal);
let signal = alloc.silence();
let mut output = AudioRenderQuantum::from(signal);
render.mix_to_output(&input, &mut output);
assert!(output.single_valued());
assert_float_eq!(output.channel_data(0)[0], 0., abs <= 0.);
}
// buffer length is 1 and input is non silent
{
let context = OfflineAudioContext::new(1, 0, 48000.);
let opts = AudioParamDescriptor {
automation_rate: AutomationRate::A,
default_value: 0.,
min_value: 0.,
max_value: 10.,
};
let (_param, mut render) = audio_param_pair(opts, context.mock_registration());
// no event in timeline, buffer length is 1
let vs = render.compute_intrinsic_values(0., 1., 128);
assert_float_eq!(vs, &[0.; 1][..], abs_all <= 0.);
// mix to output step, input is not silence
let signal = alloc.silence();
let mut input = AudioRenderQuantum::from(signal);
input.channel_data_mut(0)[0] = 1.;
let signal = alloc.silence();
let mut output = AudioRenderQuantum::from(signal);
render.mix_to_output(&input, &mut output);
let mut expected = [0.; 128];
expected[0] = 1.;
assert!(!output.single_valued());
assert_float_eq!(output.channel_data(0)[..], &expected[..], abs_all <= 0.);
}
}
#[test]
fn test_full_render_chain() {
let alloc = Alloc::with_capacity(1);
// prevent regression between the different processing stage
let context = OfflineAudioContext::new(1, 0, 48000.);
let min = 2.;
let max = 42.;
let default = 2.;
let opts = AudioParamDescriptor {
automation_rate: AutomationRate::A,
default_value: default,
min_value: min,
max_value: max,
};
let (param, mut render) = audio_param_pair(opts, context.mock_registration());
render.handle_incoming_event(param.set_value_raw(128.));
render.handle_incoming_event(param.linear_ramp_to_value_at_time_raw(0., 128.));
let intrinsic_values = render.compute_intrinsic_values(0., 1., 128);
let mut expected = [0.; 128];
for (i, v) in expected.iter_mut().enumerate() {
*v = 128. - i as f32;
}
assert_float_eq!(intrinsic_values, &expected[..], abs_all <= 0.);
let signal = alloc.silence();
let mut input = AudioRenderQuantum::from(signal);
input.channel_data_mut(0)[0] = f32::NAN;
let signal = alloc.silence();
let mut output = AudioRenderQuantum::from(signal);
render.mix_to_output(&input, &mut output);
// clamp expected
expected.iter_mut().for_each(|v| *v = v.clamp(min, max));
// fix NAN at position 0
expected[0] = 2.;
assert_float_eq!(output.channel_data(0)[..], &expected[..], abs_all <= 0.);
}
}