File: sndscm.html

package info (click to toggle)
snd 26.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 44,028 kB
  • sloc: ansic: 291,903; lisp: 260,506; ruby: 71,134; sh: 3,293; fortran: 2,342; csh: 1,067; makefile: 294; cpp: 294; python: 87; xml: 27; javascript: 1
file content (11951 lines) | stat: -rw-r--r-- 430,507 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
9972
9973
9974
9975
9976
9977
9978
9979
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
9991
9992
9993
9994
9995
9996
9997
9998
9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125
10126
10127
10128
10129
10130
10131
10132
10133
10134
10135
10136
10137
10138
10139
10140
10141
10142
10143
10144
10145
10146
10147
10148
10149
10150
10151
10152
10153
10154
10155
10156
10157
10158
10159
10160
10161
10162
10163
10164
10165
10166
10167
10168
10169
10170
10171
10172
10173
10174
10175
10176
10177
10178
10179
10180
10181
10182
10183
10184
10185
10186
10187
10188
10189
10190
10191
10192
10193
10194
10195
10196
10197
10198
10199
10200
10201
10202
10203
10204
10205
10206
10207
10208
10209
10210
10211
10212
10213
10214
10215
10216
10217
10218
10219
10220
10221
10222
10223
10224
10225
10226
10227
10228
10229
10230
10231
10232
10233
10234
10235
10236
10237
10238
10239
10240
10241
10242
10243
10244
10245
10246
10247
10248
10249
10250
10251
10252
10253
10254
10255
10256
10257
10258
10259
10260
10261
10262
10263
10264
10265
10266
10267
10268
10269
10270
10271
10272
10273
10274
10275
10276
10277
10278
10279
10280
10281
10282
10283
10284
10285
10286
10287
10288
10289
10290
10291
10292
10293
10294
10295
10296
10297
10298
10299
10300
10301
10302
10303
10304
10305
10306
10307
10308
10309
10310
10311
10312
10313
10314
10315
10316
10317
10318
10319
10320
10321
10322
10323
10324
10325
10326
10327
10328
10329
10330
10331
10332
10333
10334
10335
10336
10337
10338
10339
10340
10341
10342
10343
10344
10345
10346
10347
10348
10349
10350
10351
10352
10353
10354
10355
10356
10357
10358
10359
10360
10361
10362
10363
10364
10365
10366
10367
10368
10369
10370
10371
10372
10373
10374
10375
10376
10377
10378
10379
10380
10381
10382
10383
10384
10385
10386
10387
10388
10389
10390
10391
10392
10393
10394
10395
10396
10397
10398
10399
10400
10401
10402
10403
10404
10405
10406
10407
10408
10409
10410
10411
10412
10413
10414
10415
10416
10417
10418
10419
10420
10421
10422
10423
10424
10425
10426
10427
10428
10429
10430
10431
10432
10433
10434
10435
10436
10437
10438
10439
10440
10441
10442
10443
10444
10445
10446
10447
10448
10449
10450
10451
10452
10453
10454
10455
10456
10457
10458
10459
10460
10461
10462
10463
10464
10465
10466
10467
10468
10469
10470
10471
10472
10473
10474
10475
10476
10477
10478
10479
10480
10481
10482
10483
10484
10485
10486
10487
10488
10489
10490
10491
10492
10493
10494
10495
10496
10497
10498
10499
10500
10501
10502
10503
10504
10505
10506
10507
10508
10509
10510
10511
10512
10513
10514
10515
10516
10517
10518
10519
10520
10521
10522
10523
10524
10525
10526
10527
10528
10529
10530
10531
10532
10533
10534
10535
10536
10537
10538
10539
10540
10541
10542
10543
10544
10545
10546
10547
10548
10549
10550
10551
10552
10553
10554
10555
10556
10557
10558
10559
10560
10561
10562
10563
10564
10565
10566
10567
10568
10569
10570
10571
10572
10573
10574
10575
10576
10577
10578
10579
10580
10581
10582
10583
10584
10585
10586
10587
10588
10589
10590
10591
10592
10593
10594
10595
10596
10597
10598
10599
10600
10601
10602
10603
10604
10605
10606
10607
10608
10609
10610
10611
10612
10613
10614
10615
10616
10617
10618
10619
10620
10621
10622
10623
10624
10625
10626
10627
10628
10629
10630
10631
10632
10633
10634
10635
10636
10637
10638
10639
10640
10641
10642
10643
10644
10645
10646
10647
10648
10649
10650
10651
10652
10653
10654
10655
10656
10657
10658
10659
10660
10661
10662
10663
10664
10665
10666
10667
10668
10669
10670
10671
10672
10673
10674
10675
10676
10677
10678
10679
10680
10681
10682
10683
10684
10685
10686
10687
10688
10689
10690
10691
10692
10693
10694
10695
10696
10697
10698
10699
10700
10701
10702
10703
10704
10705
10706
10707
10708
10709
10710
10711
10712
10713
10714
10715
10716
10717
10718
10719
10720
10721
10722
10723
10724
10725
10726
10727
10728
10729
10730
10731
10732
10733
10734
10735
10736
10737
10738
10739
10740
10741
10742
10743
10744
10745
10746
10747
10748
10749
10750
10751
10752
10753
10754
10755
10756
10757
10758
10759
10760
10761
10762
10763
10764
10765
10766
10767
10768
10769
10770
10771
10772
10773
10774
10775
10776
10777
10778
10779
10780
10781
10782
10783
10784
10785
10786
10787
10788
10789
10790
10791
10792
10793
10794
10795
10796
10797
10798
10799
10800
10801
10802
10803
10804
10805
10806
10807
10808
10809
10810
10811
10812
10813
10814
10815
10816
10817
10818
10819
10820
10821
10822
10823
10824
10825
10826
10827
10828
10829
10830
10831
10832
10833
10834
10835
10836
10837
10838
10839
10840
10841
10842
10843
10844
10845
10846
10847
10848
10849
10850
10851
10852
10853
10854
10855
10856
10857
10858
10859
10860
10861
10862
10863
10864
10865
10866
10867
10868
10869
10870
10871
10872
10873
10874
10875
10876
10877
10878
10879
10880
10881
10882
10883
10884
10885
10886
10887
10888
10889
10890
10891
10892
10893
10894
10895
10896
10897
10898
10899
10900
10901
10902
10903
10904
10905
10906
10907
10908
10909
10910
10911
10912
10913
10914
10915
10916
10917
10918
10919
10920
10921
10922
10923
10924
10925
10926
10927
10928
10929
10930
10931
10932
10933
10934
10935
10936
10937
10938
10939
10940
10941
10942
10943
10944
10945
10946
10947
10948
10949
10950
10951
10952
10953
10954
10955
10956
10957
10958
10959
10960
10961
10962
10963
10964
10965
10966
10967
10968
10969
10970
10971
10972
10973
10974
10975
10976
10977
10978
10979
10980
10981
10982
10983
10984
10985
10986
10987
10988
10989
10990
10991
10992
10993
10994
10995
10996
10997
10998
10999
11000
11001
11002
11003
11004
11005
11006
11007
11008
11009
11010
11011
11012
11013
11014
11015
11016
11017
11018
11019
11020
11021
11022
11023
11024
11025
11026
11027
11028
11029
11030
11031
11032
11033
11034
11035
11036
11037
11038
11039
11040
11041
11042
11043
11044
11045
11046
11047
11048
11049
11050
11051
11052
11053
11054
11055
11056
11057
11058
11059
11060
11061
11062
11063
11064
11065
11066
11067
11068
11069
11070
11071
11072
11073
11074
11075
11076
11077
11078
11079
11080
11081
11082
11083
11084
11085
11086
11087
11088
11089
11090
11091
11092
11093
11094
11095
11096
11097
11098
11099
11100
11101
11102
11103
11104
11105
11106
11107
11108
11109
11110
11111
11112
11113
11114
11115
11116
11117
11118
11119
11120
11121
11122
11123
11124
11125
11126
11127
11128
11129
11130
11131
11132
11133
11134
11135
11136
11137
11138
11139
11140
11141
11142
11143
11144
11145
11146
11147
11148
11149
11150
11151
11152
11153
11154
11155
11156
11157
11158
11159
11160
11161
11162
11163
11164
11165
11166
11167
11168
11169
11170
11171
11172
11173
11174
11175
11176
11177
11178
11179
11180
11181
11182
11183
11184
11185
11186
11187
11188
11189
11190
11191
11192
11193
11194
11195
11196
11197
11198
11199
11200
11201
11202
11203
11204
11205
11206
11207
11208
11209
11210
11211
11212
11213
11214
11215
11216
11217
11218
11219
11220
11221
11222
11223
11224
11225
11226
11227
11228
11229
11230
11231
11232
11233
11234
11235
11236
11237
11238
11239
11240
11241
11242
11243
11244
11245
11246
11247
11248
11249
11250
11251
11252
11253
11254
11255
11256
11257
11258
11259
11260
11261
11262
11263
11264
11265
11266
11267
11268
11269
11270
11271
11272
11273
11274
11275
11276
11277
11278
11279
11280
11281
11282
11283
11284
11285
11286
11287
11288
11289
11290
11291
11292
11293
11294
11295
11296
11297
11298
11299
11300
11301
11302
11303
11304
11305
11306
11307
11308
11309
11310
11311
11312
11313
11314
11315
11316
11317
11318
11319
11320
11321
11322
11323
11324
11325
11326
11327
11328
11329
11330
11331
11332
11333
11334
11335
11336
11337
11338
11339
11340
11341
11342
11343
11344
11345
11346
11347
11348
11349
11350
11351
11352
11353
11354
11355
11356
11357
11358
11359
11360
11361
11362
11363
11364
11365
11366
11367
11368
11369
11370
11371
11372
11373
11374
11375
11376
11377
11378
11379
11380
11381
11382
11383
11384
11385
11386
11387
11388
11389
11390
11391
11392
11393
11394
11395
11396
11397
11398
11399
11400
11401
11402
11403
11404
11405
11406
11407
11408
11409
11410
11411
11412
11413
11414
11415
11416
11417
11418
11419
11420
11421
11422
11423
11424
11425
11426
11427
11428
11429
11430
11431
11432
11433
11434
11435
11436
11437
11438
11439
11440
11441
11442
11443
11444
11445
11446
11447
11448
11449
11450
11451
11452
11453
11454
11455
11456
11457
11458
11459
11460
11461
11462
11463
11464
11465
11466
11467
11468
11469
11470
11471
11472
11473
11474
11475
11476
11477
11478
11479
11480
11481
11482
11483
11484
11485
11486
11487
11488
11489
11490
11491
11492
11493
11494
11495
11496
11497
11498
11499
11500
11501
11502
11503
11504
11505
11506
11507
11508
11509
11510
11511
11512
11513
11514
11515
11516
11517
11518
11519
11520
11521
11522
11523
11524
11525
11526
11527
11528
11529
11530
11531
11532
11533
11534
11535
11536
11537
11538
11539
11540
11541
11542
11543
11544
11545
11546
11547
11548
11549
11550
11551
11552
11553
11554
11555
11556
11557
11558
11559
11560
11561
11562
11563
11564
11565
11566
11567
11568
11569
11570
11571
11572
11573
11574
11575
11576
11577
11578
11579
11580
11581
11582
11583
11584
11585
11586
11587
11588
11589
11590
11591
11592
11593
11594
11595
11596
11597
11598
11599
11600
11601
11602
11603
11604
11605
11606
11607
11608
11609
11610
11611
11612
11613
11614
11615
11616
11617
11618
11619
11620
11621
11622
11623
11624
11625
11626
11627
11628
11629
11630
11631
11632
11633
11634
11635
11636
11637
11638
11639
11640
11641
11642
11643
11644
11645
11646
11647
11648
11649
11650
11651
11652
11653
11654
11655
11656
11657
11658
11659
11660
11661
11662
11663
11664
11665
11666
11667
11668
11669
11670
11671
11672
11673
11674
11675
11676
11677
11678
11679
11680
11681
11682
11683
11684
11685
11686
11687
11688
11689
11690
11691
11692
11693
11694
11695
11696
11697
11698
11699
11700
11701
11702
11703
11704
11705
11706
11707
11708
11709
11710
11711
11712
11713
11714
11715
11716
11717
11718
11719
11720
11721
11722
11723
11724
11725
11726
11727
11728
11729
11730
11731
11732
11733
11734
11735
11736
11737
11738
11739
11740
11741
11742
11743
11744
11745
11746
11747
11748
11749
11750
11751
11752
11753
11754
11755
11756
11757
11758
11759
11760
11761
11762
11763
11764
11765
11766
11767
11768
11769
11770
11771
11772
11773
11774
11775
11776
11777
11778
11779
11780
11781
11782
11783
11784
11785
11786
11787
11788
11789
11790
11791
11792
11793
11794
11795
11796
11797
11798
11799
11800
11801
11802
11803
11804
11805
11806
11807
11808
11809
11810
11811
11812
11813
11814
11815
11816
11817
11818
11819
11820
11821
11822
11823
11824
11825
11826
11827
11828
11829
11830
11831
11832
11833
11834
11835
11836
11837
11838
11839
11840
11841
11842
11843
11844
11845
11846
11847
11848
11849
11850
11851
11852
11853
11854
11855
11856
11857
11858
11859
11860
11861
11862
11863
11864
11865
11866
11867
11868
11869
11870
11871
11872
11873
11874
11875
11876
11877
11878
11879
11880
11881
11882
11883
11884
11885
11886
11887
11888
11889
11890
11891
11892
11893
11894
11895
11896
11897
11898
11899
11900
11901
11902
11903
11904
11905
11906
11907
11908
11909
11910
11911
11912
11913
11914
11915
11916
11917
11918
11919
11920
11921
11922
11923
11924
11925
11926
11927
11928
11929
11930
11931
11932
11933
11934
11935
11936
11937
11938
11939
11940
11941
11942
11943
11944
11945
11946
11947
11948
11949
11950
11951
<!DOCTYPE html>

<html lang="en">
<!-- documentation for some of the Scheme/Ruby/Forth code included with Snd -->

<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" >
<title>Scheme, Ruby, and Forth Functions included with Snd</title>
<style>
	EM.red {color:red; font-style:normal}
        EM.error {color:chocolate; font-style:normal}
	EM.emdef {font-weight: bold; font-style: normal; padding-right: 0.2cm}
	H1 {text-align: center}
	UL {list-style-type: none}
	DIV.greencenter {text-align: center; background-color: lightgreen; padding-top: 0.1cm; padding-bottom: 0.1cm;}

	A {text-decoration:none}
	A:hover {text-decoration:underline}
	A.quiet {color:black; text-decoration:none}
	A.quiet:hover {text-decoration:underline}
	A.def {font-weight: bold; font-style: normal; text-decoration:none; padding-right: 0.2cm}
	EM.def {font-weight: bold; font-style: normal; text-decoration:none; padding-right: 0.2cm}

        TD.center {text-align: center}
        PRE.indented {padding-left: 1.0cm}
        IMG.indented {padding-left: 1.0cm}
        IMG.noborder {border: none; padding-left: 1.0cm}

	DIV.center {text-align: center}
        BODY.body {background-color: #ffffff;    /* white */
	           margin-left: 0.5cm; 
		   margin-right: 0.5cm;
                   }
        TABLE.grayborder {margin-top: 0.5cm;
                      margin-bottom: 0.5cm;
		      margin-left: 1.0cm;
		      border: 8px solid gray;
		      padding-left: 0.1cm;
		      padding-right: 0.1cm;
		      padding-top: 0.1cm;
		      padding-bottom: 0.1cm;
	               }
        DIV.topheader {margin-top: 10px;
	            margin-bottom: 40px;
	            border: 4px solid #00ff00; /* green */
		    background-color: #f5f5dc; /* beige */
		    font-family: 'Helvetica';
		    font-size: 30px;
		    text-align: center;
		    padding-top: 10px;
		    padding-bottom: 10px;
	           }
        DIV.header {margin-top: 50px;
	            margin-bottom: 10px;
		    font-size: 20px;
		    font-weight: bold;
	            border: 4px solid #00ff00; /* green */
		    background-color: #f5f5dc; /* beige */
		    text-align: center;
		    padding-top: 20px;
		    padding-bottom: 20px;
	           }
        DIV.innerheader {margin-top: 60px;
	            margin-bottom: 30px;
	            border: 4px solid #00ff00; /* green */
		    background-color: #eefdee; /* lightgreen */
		    padding-left: 30px;
		    width: 50%;
		    padding-top: 20px;
		    padding-bottom: 20px;
	           }
	DIV.related {text-align:center;
	             border: 1px solid lightgray;
		     margin-bottom: 1.0cm;
		     margin-top: 1.0cm;
		     padding-top: 10px;
		     padding-bottom: 10px;
		     background-color: #f0f0f0;
	            }
        DIV.inset {margin-left: 2.0cm;
	           margin-right: 2.0cm;
		   margin-top: 0.5cm;
		   margin-bottom: 0.5cm;
		   background-color: #f0f0f0;
		   padding-left: 0.25cm;
		   padding-right: 0.25cm;
		   padding-top: 0.25cm;
		   padding-bottom: 0.25cm;
		   }
	DIV.seealso {border: 1px solid lightgray;
		     margin-bottom: 0.5cm;
		     margin-top: 0.5cm;
		     padding-top: 10px;
		     padding-bottom: 10px;
		     padding-left: 0.5cm;
		     background-color: #f0f0f0;
	            }
	DIV.simple {margin-left: 1cm;
		    margin-bottom: 0.5cm;
	           }
        #contents_table tbody tr:nth-child(odd) { background-color: #f2f4ff; }
        TABLE.method {margin-top: 0.5cm;
                      margin-bottom: 0.5cm;
		      margin-left: 1.0cm;
		      border: 1px solid gray;
		      padding-left: 0.1cm;
		      padding-right: 0.1cm;
		      padding-top: 0.1cm;
		      padding-bottom: 0.1cm;
		      }	    
        TH.title {background-color: lightgreen;
		  border: 1px solid gray;
		  padding-top: 0.2cm;	
		  padding-bottom: 0.2cm;
		  text-align: center;
		  }
        TD.methodtitle {background-color: beige;
		  border: 1px solid gray;
		  padding-top: 0.2cm;	
		  padding-bottom: 0.2cm;
		  text-align: center;
		  }
        DIV.separator {margin-top: 40px;
	               margin-bottom: 15px;
	               border: 2px solid #00ff00; /* green */
		       background-color: #f5f5dc; /* beige */
		       padding-top: 4px;
		       width: 30%;
		      border-radius: 4px;
		      -moz-border-radius: 4px;
		      -webkit-border-radius: 4px;
		      } 
	DIV.scheme {background-color: #f2f4ff;
	            border: 1px solid gray;
		    padding-right: 1.0cm;
		    margin-bottom: 0.2cm;
		    }
	DIV.ruby {background-color: #fbfbf0;
	            border: 1px solid gray;
		    padding-right: 1.0cm;
		    margin-bottom: 0.2cm;
		    }
	DIV.forth {background-color: #eefdee;
	            border: 1px solid gray;
		    padding-right: 1.0cm;
		    margin-bottom: 0.2cm;
		    }
        DIV.spacer {margin-top: 1.0cm;
	           }
</style>
</head>
<body class="body">

<div class="topheader" id="introduction">Scheme, Ruby, and Forth Functions included with Snd</div>

<div class="related">
related documentation: &nbsp;
<a href="snd.html">snd.html &nbsp;</a>
<a href="extsnd.html">extsnd.html &nbsp;</a>
<a href="grfsnd.html">grfsnd.html &nbsp;</a>
<a href="sndclm.html">sndclm.html &nbsp;</a>
<a href="sndlib.html">sndlib.html &nbsp;</a>
<a href="fm.html">fm.html &nbsp;</a>
<a href="s7.html">s7.html &nbsp;</a>
<a href="s7-ffi.html">s7-ffi.html &nbsp;</a>
<a href="s7-scm.html">s7-scm.html &nbsp;</a>
<a href="index.html">index.html</a>
</div>


<p>This file describes the Scheme, Ruby, and Forth code included with Snd.
To use this code, load the relevant file:
</p>

<pre class="indented">
Scheme: (load "dsp.scm") or (load-from-path "dsp.scm")
Ruby:   load "dsp.rb"
Forth:  "dsp.fs" file-eval
</pre>

<p>
To start Snd with
the file already loaded, snd -l v.scm, or put the load statement in your initialization file.
For help with Forth and Snd/CLM, see the Forth documentation section "Snd, CLM, and Fth".
</p>


<table class="grayborder"><tr><td>
<table id="contents_table">
<tr><th colspan=2 class="title">Contents</th></tr>
<tbody>
<tr><td><a href="#analogfilterdoc">analog-filter</a></td>
    <td>standard IIR filters (Butterworth, Chebyshev, Bessel, Elliptic)</td></tr>

<tr><td><a href="#animalsdoc">animals</a></td>
    <td>a bunch of animals</td></tr>

<tr><td><a href="#autosavedoc">autosave</a></td>
    <td>auto-save (edit backup) support</td></tr>

<tr><td><a href="#bessdoc">bess</a></td>
    <td>FM demo</td></tr>

<tr><td><a href="#binaryiodoc">binary-io</a></td>
    <td>binary files</td></tr>

<tr><td><a href="#birddoc">bird</a></td>
    <td>North-American birds</td></tr>

<tr><td><a href="#cleandoc">clean</a></td>
    <td>noise reduction</td></tr>

<tr><td><a href="#clminsdoc">clm-ins, jcvoi</a></td>
    <td>various CLM instruments</td></tr>

<tr><td><a href="#dlocsigdoc">dlocsig</a></td>
    <td>moving sounds (Michael Scholz)</td></tr>

<tr><td><a href="#drawdoc">draw</a></td>
    <td>graphics additions</td></tr>

<tr><td><a href="#dspdoc">dsp</a></td>
    <td>various DSP-related procedures</td></tr>

<tr><td><a href="#envdoc">env</a></td>
    <td>envelope functions</td></tr>

<tr><td><a href="#enveddoc">enved</a></td>
    <td>envelope editor</td></tr>

<tr><td><a href="#exampdoc">examp</a></td>
    <td>many examples</td></tr>

<tr><td><a href="#extensionsdoc">extensions</a></td>
    <td>various generally useful Snd extensions</td></tr>

<tr><td><a href="#fadedoc">fade</a></td>
    <td>frequency-domain cross-fades</td></tr>

<tr><td><a href="#freeverbdoc">freeverb</a></td>
    <td>a reverb</td></tr>

<tr><td><a href="sndclm.html#othergenerators">generators.scm</a></td>
    <td>a bunch of generators</td></tr>

<tr><td><a href="#granidoc">grani</a></td>
    <td>CLM's grani (Fernando Lopez-Lezcano) translated by Mike Scholz</td></tr>

<tr><td><a href="#heartdoc">heart</a></td>
    <td>use Snd with non-sound (arbitrary range) data</td></tr>

<tr><td><a href="#hooksdoc">hooks</a></td>
    <td >functions related to hooks</td></tr>

<tr><td><a href="#indexdoc">index</a></td>
    <td>snd-help extension</td></tr>

<tr><td><a href="#dotemacs">inf-snd.el, DotEmacs</a></td>
    <td>Emacs subjob support (Michael Scholz, Fernando Lopez-Lezcano)</td></tr>

<tr><td><a href="#jcrevdoc">jcrev</a></td>
    <td>John Chowning's ancient reverb</td></tr>

<tr><td><a href="#lintdoc">lint</a></td>
    <td>A lint program for scheme code</td></tr>

<tr><td><a href="#maracadoc">maraca</a></td>
    <td>Perry Cook's maraca physical model</td></tr>

<tr><td><a href="#marksdoc">marks</a></td>
    <td>functions related to marks</td></tr>

<tr><td><a href="#maxfdoc">maxf</a></td>
    <td>Max Mathews resonator</td></tr>

<tr><td><a href="#menusdoc">menus</a></td>
    <td>additional menus</td></tr>

<tr><td><a href="#mixdoc">mix</a></td>
    <td>functions related to mixes</td></tr>

<tr><td><a href="#moogdoc">moog</a></td>
    <td>Moog filter</td></tr>

<tr><td><a href="#musglyphs">musglyphs</a></td>
    <td>Music notation symbols (from CMN)</td></tr>

<tr><td><a href="#nbdoc">nb</a></td>
    <td>Popup File info etc</td></tr>

<tr><td><a href="#noisedoc">noise</a></td>
    <td>noise maker</td></tr>

<tr><td><a href="#numericsdoc">numerics</a></td>
    <td>various numerical functions</td></tr>

<tr><td><a href="#peakphasesdoc">peak-phases</a></td>
    <td>phases for the unpulse-train</td></tr>

<tr><td><a href="#pianodoc">piano</a></td>
    <td>piano physical model</td></tr>

<tr><td><a href="#playdoc">play</a></td>
    <td>play-related functions</td></tr>

<tr><td><a href="#polydoc">poly</a></td>
    <td>polynomial-related stuff</td></tr>

<tr><td><a href="#prc95doc">prc95</a></td>
    <td>Perry Cook's physical model examples</td></tr>

<tr><td><a href="#pvocdoc">pvoc</a></td>
    <td>phase-vocoder</td></tr>

<tr><td><a href="#rgbdoc">rgb</a></td>
    <td>color names</td></tr>

<tr><td><a href="#rubberdoc">rubber</a></td>
    <td>rubber-sound</td></tr>

<tr><td><a href="#s7testdoc">s7test</a></td>
    <td>s7 regression tests</td></tr>

<tr><td><a href="#selectiondoc">selection</a></td>
    <td>functions acting on the current selection</td></tr>

<tr><td><a href="#singerdoc">singer</a></td>
    <td>Perry Cook's vocal-tract physical model</td></tr>

<tr><td><a href="#sndolddoc">snd15.scm</a></td>
    <td>Backwards compatibility</td></tr>

<tr><td><a href="#snddiffdoc">snddiff</a></td>
    <td>sound difference detection</td></tr>

<tr><td><a href="#sndgldoc">snd-gl</a></td>
    <td>OpenGL examples (gl.c)</td></tr>

<tr><td><a href="#sndmotifdoc">snd-motif, snd-xm</a></td>
    <td>Motif module (xm.c)</td></tr>

<tr><td><a href="#sndtestdoc">snd-test</a></td>
    <td>Snd regression tests</td></tr>

<tr><td><a href="#sndwarpdoc">sndwarp</a></td>
    <td>Bret Battey's sndwarp instrument</td></tr>

<tr><td><a href="#spectrdoc">spectr</a></td>
    <td>instrument steady state spectra</td></tr>

<tr><td><a href="#stochasticdoc">stochastic</a></td>
    <td>Bill Sack's dynamic stochastic synthesis</td></tr>

<tr><td><a href="#straddoc">strad</a></td>
    <td>string physical model (from CLM)</td></tr>

<tr><td><a href="#tankrevdoc">tankrev</a></td>
    <td>Jon Dattorro's plate reverb (Anders Vinjar)</td></tr>

<tr><td><a href="#vdoc">v</a></td>
    <td>fm-violin</td></tr>

<tr><td><a href="#wsdoc">ws</a></td>
    <td>with-sound</td></tr>

<tr><td><a href="#zipdoc">zip</a></td>
    <td>the zipper (the anti-cross-fader)</td></tr>
</tbody>
</table>
</td></tr></table>




<!--  FILE: analog-filter  -->

<div class="header" id="analogfilterdoc">analog-filter</div>

<!-- main-index |analogfilterdoc:butterworth filters -->
<!-- main-index |analogfilterdoc:bessel filters -->
<!-- main-index |analogfilterdoc:elliptic filters -->
<!-- main-index |analogfilterdoc:chebyshev filters -->

<pre class="indented">
<em class=emdef>make-butterworth-lowpass</em> order fcut
<em class=emdef>make-butterworth-highpass</em> order fcut
<em class=emdef>make-butterworth-bandpass</em> order flo fhi
<em class=emdef>make-butterworth-bandstop</em> order flo fhi

<em class=emdef>make-chebyshev-lowpass</em> order fcut (ripple-dB 1.0)
<em class=emdef>make-chebyshev-highpass</em> order fcut (ripple-dB 1.0)
<em class=emdef>make-chebyshev-bandpass</em> order flo fhi (ripple-dB 1.0)
<em class=emdef>make-chebyshev-bandstop</em> order flo fhi (ripple-dB 1.0)

<em class=emdef>make-inverse-chebyshev-lowpass</em> order fcut (loss-dB 60.0)
<em class=emdef>make-inverse-chebyshev-highpass</em> order fcut (loss-dB 60.0)
<em class=emdef>make-inverse-chebyshev-bandpass</em> order flo fhi (loss-dB 60.0)
<em class=emdef>make-inverse-chebyshev-bandstop</em> order flo fhi (loss-dB 60.0)

<em class=emdef>make-bessel-lowpass</em> order fcut
<em class=emdef>make-bessel-highpass</em> order fcut
<em class=emdef>make-bessel-bandpass</em> order flo fh
<em class=emdef>make-bessel-bandstop</em> order flo fh

<em class=emdef>make-elliptic-lowpass</em> order fcut (ripple-dB 1.0) (loss-dB 60.0)
<em class=emdef>make-elliptic-highpass</em> order fcut (ripple-dB 1.0) (loss-dB 60.0)
<em class=emdef>make-elliptic-bandpass</em> order flo fhi (ripple-dB 1.0) (loss-dB 60.0)
<em class=emdef>make-elliptic-bandstop</em> order flo fhi (ripple-dB 1.0) (loss-dB 60.0)

;; fcut = cutoff frequency in terms of srate = 1.0, 
;; flo = low freq of band, fhi = high freq of band

</pre>

<p>analog-filter.scm has the usual IIR filters: Butterworth, Chebyshev, inverse Chebyshev, Bessel,
and Elliptic filters in lowpass, highpass, bandpass, and bandstop versions.  Each of the lowpass and highpass
"make" functions returns a filter generator, whereas the bandstop and bandpass make functions
return a function of one argument, the current input (the filter generators are built-in in these cases).
The filter order should be an even number; very high orders can cause numerical disaster!
The
elliptic filters depend on GSL, so you'll also need GSL (Snd's configure script includes it by default, if possible).
</p>

<pre class="indented">
(<a class=quiet href="extsnd.html#mapchannel">map-channel</a> (make-elliptic-lowpass 8 .1)) ; 8th order elliptic with cutoff at .1 * srate
</pre>

<p>
One quick way to see the frequency response of your filter is to create a sound that sweeps a sinewave upward
in frequency, run it through the filter, then view the entire sound, treating the x axis as frequency
in terms of srate = 1.0 (for convenience):
</p>

<pre class="indented">
(define (filter-sweep flt chan)
  (let ((phase 0.0)
	(freq 0.0)
	(incr (/ (* 2 pi) 44100.0))
        (samps (<a class=quiet href="sndclm.html#secondstosamples">seconds-&gt;samples</a> 0.5)))
    (do ((i 0 (+ i 1)))
	((= i samps))
      (let ((sval (* .8 (sin phase))))
	(set! phase (+ phase freq)) 
	(set! freq (+ freq incr))
	(<a class=quiet href="sndclm.html#out-any">out-any</a> i (flt sval) chan)))))

(with-sound (:channels 5 :output "test.snd")
  (filter-sweep (make-butterworth-lowpass 8 .1) 0)
  (filter-sweep (make-bessel-lowpass 8 .1) 1)
  (filter-sweep (make-chebyshev-lowpass 8 .1) 2)
  (filter-sweep (make-inverse-chebyshev-lowpass 8 .1) 3)
  (filter-sweep (make-elliptic-lowpass 8 .1) 4))
</pre>


<table class="method">
<tr><td class="methodtitle">IIR filters, order=8, low cutoff at .1 (4410Hz), high cutoff at .3 (13230Hz)</td></tr>
<tr><td>
<img src="pix/iir.png" alt="iir filters">
</td></tr>
</table>

<!--
(define (filter-sweep flt chan)
  (let ((phase 0.0)
	(freq 0.0)
	(incr (/ (* 2 pi) 44100.0))
	(samps (seconds->samples 0.5)))

    (do ((i 0 (+ i 1)))
	((= i samps))

      (let ((sval (* .8 (sin phase))))
	(set! phase (+ phase freq)) 
	(set! freq (+ freq incr))

	(out-any i (flt sval) chan)))))

(define low-cut .1)
(define high-cut .3)

(with-sound (:channels 5 :output "test.snd")
  (filter-sweep (make-butterworth-lowpass 8 low-cut) 0)
  (filter-sweep (make-bessel-lowpass 8 low-cut) 1)
  (filter-sweep (make-chebyshev-lowpass 8 low-cut) 2)
  (filter-sweep (make-inverse-chebyshev-lowpass 8 low-cut) 3)
  (filter-sweep (make-elliptic-lowpass 8 low-cut) 4))

(with-sound (:channels 5 :output "test2.snd")
  (filter-sweep (make-butterworth-highpass 8 high-cut) 0)
  (filter-sweep (make-bessel-highpass 8 high-cut) 1)
  (filter-sweep (make-chebyshev-highpass 8 high-cut) 2)
  (filter-sweep (make-inverse-chebyshev-highpass 8 high-cut) 3)
  (filter-sweep (make-elliptic-highpass 8 high-cut) 4))

(with-sound (:channels 5 :output "test1.snd")
  (filter-sweep (make-butterworth-bandpass 8 low-cut high-cut) 0)
  (filter-sweep (make-bessel-bandpass 8 low-cut high-cut) 1)
  (filter-sweep (make-chebyshev-bandpass 8 low-cut high-cut) 2)
  (filter-sweep (make-inverse-chebyshev-bandpass 8 low-cut high-cut) 3)
  (filter-sweep (make-elliptic-bandpass 8 low-cut high-cut) 4))

(with-sound (:channels 5 :output "test3.snd")
  (filter-sweep (make-butterworth-bandstop 8 low-cut high-cut) 0)
  (filter-sweep (make-bessel-bandstop 8 low-cut high-cut) 1)
  (filter-sweep (make-chebyshev-bandstop 8 low-cut high-cut) 2)
  (filter-sweep (make-inverse-chebyshev-bandstop 8 low-cut high-cut) 3)
  (filter-sweep (make-elliptic-bandstop 8 low-cut high-cut) 4))

(set! *selected-graph-color* (make-color 1 1 1))
(set! *selected-data-color* (make-color 0 0 0))
(set! *axis-label-font* "9x15")

(do ((i 0 (+ i 1)))
    ((= i 4))
  (do ((k 0 (+ 1 k)))
      ((= k 5))
    (set! (x-axis-label i k)
	  (format #f "~A ~A"
		  (if (= k 0) "butterworth"
		      (if (= k 1) "bessel"
			  (if (= k 2) "chebyshev"
			      (if (= k 3) "inverse chebyshev"
				  "elliptic"))))
		  (if (= i 0) "lowpass"
		      (if (= i 1) "highpass"
			  (if (= i 2) "bandpass"
			      "bandstop")))))))
-->


<div class="seealso">
see also: &nbsp; <a href="#dspdoc">dsp</a> &nbsp; <a href="#exampdoc">examp</a> &nbsp; <a href="#moogdoc">moog</a> &nbsp; <a href="#maxfdoc">maxf</a> &nbsp; <a href="#prc95doc">prc95</a> &nbsp; <a href="#grapheq">graphEq</a> &nbsp; <a href="sndclm.html#filter">clm</a>
</div>



<!--  FILE: animals  -->

<div class="header" id="animalsdoc">animals</div>

<p>
People paint birds; why not bird songs?  Check out a Hermit Thrush song down 2 or 3 octaves and slowed down as well (via
granular synthesis, for example) &mdash; incredibly beautiful 2-part microtonal counterpoint.
animals.scm contains several synthesized animal sounds: frogs, birds, insects, and one mammal.
To hear them all, (calling-all-animals).  
</p>

<div class="innerheader">How to Paint a Bird Song</div>

<p>Back in 1980, I wanted some bird songs for "Colony", but my stabs at
a fake bird song were completely unconvincing.  So I went to
my battered bird book (Robbins, Bruun, Zim, Singer "Birds of North America" Golden Press, NY 1966)
which had sonograms
of lots of bird songs.  Unfortunately, the graphs were so tiny that I could barely
read them: 
</p>

<table>
<tr><td>
<img src="pix/golden.png" alt="Lincoln's Sparrow, approximately original size">
</td><td>
<small>Lincoln's Sparrow approximately original size,
but blurrier due to incredibly bad scanner software.
</small>
</td></tr></table>

<p>Graphs like this became <a href="#birddoc">bird.scm</a>.  It surprised me that the synthetic
song could sound good even with just a sinewave and a couple sketchy envelopes.  But squawks
and screeches were harder.  27 years later, I tackled animal sounds again, but now using Snd
and some extremely high quality recordings, mainly from Cornell.  It's not that hard to
match some animal sounds; perhaps someone would like to see the steps I took to match
a Hairy Woodpecker call (hairy-woodpecker in animals.scm).
</p>

<p>
Open the Hairy Woodpecker. Find a squawk that seems within reach, and select it.
</p>
<img class="indented" src="pix/hairy1.png" alt="selecting a squawk">

<p>
Zoom onto the first channel (the vertical slider on the right &mdash; we don't care about stereo here), and center the squawk in the time domain window (C-x v).
Get the selection duration in seconds.  Start the envelope editor dialog (under the Edit menu).  Choose "selection"
and "wave" in that dialog.
</p>

<img class="indented" src="pix/hairy2.png" alt="zoom in">

<p>Since the goal is a CLM instrument that synthesizes this sound, get a "blank bird", and fill
in the duration.
</p>

<pre class="indented">
(definstrument (hairy-woodpecker beg amp)
  (let* ((start (<a class=quiet href="sndclm.html#secondstosamples">seconds-&gt;samples</a> beg))
	 (dur 0.08)                                      ; filled in from the selection duration
	 (stop (+ start (<a class=quiet href="sndclm.html#secondstosamples">seconds-&gt;samples</a> dur)))
	 (ampf (<a class=quiet href="sndclm.html#make-env">make-env</a>                                 ; left blank for the moment
			 :duration dur :scaler amp))
	 (gen1 (<a class=quiet href="sndclm.html#make-oscil">make-oscil</a>))
	 (frqf (<a class=quiet href="sndclm.html#make-env">make-env</a>                                 ; ditto
			 :duration dur :scaler (<a class=quiet href="sndclm.html#hztoradians">hz-&gt;radians</a> 1.0))))
   (do ((i start (+ i 1)))
       ((= i stop))
     (<a class=quiet href="sndclm.html#outa">outa</a> i (* (<a class=quiet href="sndclm.html#env">env</a> ampf)                           ; just a first guess at the synthesis algorithm
	        (<a class=quiet href="sndclm.html#oscil">oscil</a> gen1 (<a class=quiet href="sndclm.html#env">env</a> frqf)))))))
</pre>

<p>Now to get an amplitude envelope, set the y axis limits to be from 0.0 to the selection maxamp:
</p>

<pre class="indented">
(set! (<a class=quiet href="extsnd.html#ybounds">y-bounds</a> (<a class=quiet href="extsnd.html#selectedsound">selected-sound</a>) (<a class=quiet href="extsnd.html#selectedchannel">selected-channel</a>)) (list 0 (<a class=quiet href="extsnd.html#selectionmaxamp">selection-maxamp</a>)))
</pre>

<p>
I have this action bound to the "m" key in my ~/.snd initialization file.  The change is reflected in
the envelope editor.  We can define the amplitude envelope by approximating the shape.  Call it "hairy-amp".
</p>

<img class="indented" src="pix/hairy3.png" alt="get amp env">

<p>Now go to the listener and get the value of hairy-amp as a list of breakpoints.
I usually use this function to get the breakpoints:
</p>

<pre class="indented">
&gt; (define (clean-string e)
    (format #f "(~{~,3F~^ ~})" e))

&gt; (clean-string hairy-amp)
"(0.000 0.000 0.099 0.188 0.152 0.148 0.211 0.558 0.242 0.267 0.278 0.519 0.434 0.472 0.527 0.543 0.612 0.479 
  0.792 0.941 0.831 0.523 0.854 1.000 0.913 0.422 0.927 0.200 0.946 0.430 0.971 0.304 1.000 0.000 )"
</pre>

<p>Plug this list into the bird instrument (ampf).  Now switch to the FFT view (click "f" and "w"), open the
FFT dialog (Options:Transform), choose Blackman10 window, sonogram, 512.  In the color dialog, choose the
"jet" colormap.  In the envelope editor, switch from "amp" to "flt", and resize the dialog window so that
its graph fits the displayed spectrum.  For fast moving sounds, it's important to align the amp and freq
envelopes exactly, but the FFT delays or blurs stuff, so mess with the graph placement until the amplitude
envelope and the spectrum match (bright spots at loud spots and so on).  I bind the arrow keys to precision
movements for this reason (in my ~/.snd file, see <a href="extsnd.html#moveonepixel">move-one-pixel</a>).
</p>

<img class="indented" src="pix/hairy4.png" alt="preapring to get freq env">

<p>Reset the envelope editor (to erase the amp envelope), and press "flt" and "wave" again.
Now zoom in to the main spectral component (drag the FFT y axis up), and
trace out the frequency curve in the envelope editor.  Call it hairy-freq,
and get the list of breakpoints as before in the listener.  Plug that
into the bird instrument.  The "scaler" for the frequency envelope is
the top of the FFT graph in Hz; it is 10KHz in this case.
</p>

<img class="indented" src="pix/hairy5.png" alt="get freq env">

<pre class="indented">
(definstrument (hairy-woodpecker beg amp)
  (let* ((start (<a class=quiet href="sndclm.html#secondstosamples">seconds-&gt;samples</a> beg))
	 (dur 0.08)
	 (stop (+ start (<a class=quiet href="sndclm.html#secondstosamples">seconds-&gt;samples</a> dur)))
	 (ampf (<a class=quiet href="sndclm.html#make-env">make-env</a> '(0.000 0.000 0.099 0.188 0.152 0.148 0.211 0.558 0.242 0.267 0.278 0.519 0.434 0.472 
			   0.527 0.543 0.612 0.479 0.792 0.941 0.831 0.523 0.854 1.000 0.913 0.422 0.927 0.200 
			   0.946 0.430 0.971 0.304 1.000 0.000 )
			 :duration dur :scaler amp))
	 (frqf (<a class=quiet href="sndclm.html#make-env">make-env</a> '(0.000 0.180 0.056 0.213 0.135 0.241 0.167 0.305 0.191 0.396 0.212 0.402 0.242 0.485 
			   0.288 0.506 0.390 0.524 0.509 0.530 0.637 0.537 0.732 0.530 0.770 0.503 0.808 0.503 
			   0.826 0.427 0.848 0.366 0.889 0.345 0.913 0.232 1.000 0.198)
			 :duration dur :scaler (<a class=quiet href="sndclm.html#hztoradians">hz-&gt;radians</a> 10000.0)))
	 (gen1 (<a class=quiet href="sndclm.html#make-oscil">make-oscil</a>)))
   (do ((i start (+ i 1)))
       ((= i stop))
     (<a class=quiet href="sndclm.html#outa">outa</a> i (* (<a class=quiet href="sndclm.html#env">env</a> ampf)
	        (<a class=quiet href="sndclm.html#oscil">oscil</a> gen1 (<a class=quiet href="sndclm.html#env">env</a> frqf)))))))
</pre>

<p>This squawk has more than one component (it is not just a sine wave), and the components follow more or less
the same amplitude envelope (so we can use polywave).  Go to the "single transform"
view (in the Transform dialog), make the FFT size bigger, move the time domain window into about the middle
of the call, and get some estimate of the number of
components and their relative amplitudes (concentrating for now on the steady state).  Change the "make-oscil"
to "make-polywave" and give some first stab at the steady-state spectrum:
</p>

<pre class="indented">
...
(gen1 (<a class=quiet href="sndclm.html#make-polywave">make-polywave</a> :partials (list 1 .9  2 .1  3 .01)))
  ...
(<a class=quiet href="sndclm.html#polywave">polywave</a> gen1 (<a class=quiet href="sndclm.html#env">env</a> frqf))
...
</pre>

<p>Load ws.scm, load the current woodpecker code, and
listen to the squawk: (with-sound (:play #t) (hairy-woodpecker 0.0 0.5)).
Not terrible.  If it's cut off during playback, add a dummy silent call to the end:
(with-sound (:play #t) (hairy-woodpecker 0.0 0.5) (hairy-woodpecker 0.5 0.0)).
We're happy at this stage if it's in the right ballpark.
</p>

<img class="indented" src="pix/hairy6.png" alt="first take">

<p>
The attack and decay sections need work.  Returning to either FFT view, it's clear
there's a set of components moving together at half the steady state frequency, so add another polywave with its own amplitude envelope:
</p>

<pre class="indented">
(definstrument (hairy-woodpecker beg amp)
  (let* ((start (<a class=quiet href="sndclm.html#secondstosamples">seconds-&gt;samples</a> beg))
	 (dur 0.08)
	 (stop (+ start (<a class=quiet href="sndclm.html#secondstosamples">seconds-&gt;samples</a> dur)))
	 (ampf (<a class=quiet href="sndclm.html#make-env">make-env</a> '(0.000 0.000 0.099 0.188 0.152 0.148 0.211 0.558 0.242 0.267 0.278 0.519 0.434 0.472 
			   0.527 0.543 0.612 0.479 0.792 0.941 0.831 0.523 0.854 1.000 0.913 0.422 0.927 0.200 
			   0.946 0.430 0.971 0.304 1.000 0.000 )
			 :duration dur :scaler amp))
	 (frqf (<a class=quiet href="sndclm.html#make-env">make-env</a> '(0.000 0.180 0.056 0.213 0.135 0.241 0.167 0.305 0.191 0.396 0.212 0.402 0.242 0.485 
			   0.288 0.506 0.390 0.524 0.509 0.530 0.637 0.537 0.732 0.530 0.770 0.503 0.808 0.503 
			   0.826 0.427 0.848 0.366 0.889 0.345 0.913 0.232 1.000 0.198)
			 :duration dur :scaler (<a class=quiet href="sndclm.html#hztoradians">hz-&gt;radians</a> 10000.0)))
	 (gen1 (<a class=quiet href="sndclm.html#make-polywave">make-polywave</a> :partials (list 1 .9  2 .09  3 .01)))
	 (gen2 (<a class=quiet href="sndclm.html#make-polywave">make-polywave</a> :partials (list 1 .2  2 .1  3 .1  4 .1  5 .1  6 .05  7 .01))) ; attack and decay
	 (ampf2 (<a class=quiet href="sndclm.html#make-env">make-env</a> '(0 1  .3 1  .4 0 .75 0 .8 1  1 1) :duration dur :scaler 1.0)))      ; its amplitude
    (do ((i start (+ i 1)))
        ((= i stop))
      (let ((frq (<a class=quiet href="sndclm.html#env">env</a> frqf)))
        (<a class=quiet href="sndclm.html#outa">outa</a> i (* (<a class=quiet href="sndclm.html#env">env</a> ampf)
		   (+ (<a class=quiet href="sndclm.html#polywave">polywave</a> gen1 frq)
		      (* (<a class=quiet href="sndclm.html#env">env</a> ampf2)
			 (<a class=quiet href="sndclm.html#polywave">polywave</a> gen2 (* 0.5 frq))))))))))
</pre>

<p>Now patience is the key.  
Use the speed control to slow playback down by an octave or two.
(Perhaps the frequency envelope should end at a higher point?)
Keep tweaking the envelopes and spectral amplitudes until it sounds right!
Total elapsed time?  Two or three hours probably.
</p>

<img class="indented" src="pix/hairy7.png" alt="the end">

<p>animals.scm has all the functions, key bindings, and dialog variable settings mentioned here.
They can save you a ton of time.
</p>

<div class="seealso">
see also: &nbsp; <a href="#birddoc">birds</a>
</div>




<!--  FILE: autosave  -->

<div class="header" id="autosavedoc">autosave</div>

<!-- main-index |autosavedoc:auto-save -->

<pre class="indented">
<em class=emdef>auto-save</em> 
<em class=emdef>cancel-auto-save</em> 
</pre>

<!-- I(auto save):L(auto-save)(exautosave) -->
<!-- I(auto save):A(exautosave) -->

<p>The auto-save code sets up a background process that checks periodically for
unsaved edits, and if any are found it saves them in a temporary file (the name is the base file name enclosed in "#...#" and placed in
the <a href="extsnd.html#tempdir">temp-dir</a> directory).
The time between checks
is set by the variable auto-save-interval which defaults to 60.0 seconds.
To start auto-saving, (load "autosave.scm").  Thereafter (cancel-auto-save)
stops autosaving, and (auto-save) restarts it.
</p>




<!--  FILE: bess  -->

<div class="header" id="bessdoc">bess</div>

<p>bess.scm creates a dialog (named "FM Forever!"),
puts up a bunch of scale widgets, and starts two CLM oscils doing
frequency modulation.
Michael Scholz has contributed a Ruby translation of this with many improvements:
bess.rb.  
</p>

<img class="indented" src="pix/fm.png" alt="fm dialog">

<pre class="indented">
;; bess plays the following:
(* amp 
   (<a class=quiet href="sndclm.html#oscil">oscil</a> carosc 
     (+ (<a class=quiet href="sndclm.html#hztoradians">hz-&gt;radians</a> frequency)
        (* index (<a class=quiet href="sndclm.html#oscil">oscil</a> modosc 
                   (<a class=quiet href="sndclm.html#hztoradians">hz-&gt;radians</a> (* ratio frequency)))))))
</pre>

<p>bess1.scm and bess1.rb 
give you real-time GUI-based control over the fm-violin while it cycles around in a simple
compositional algorithm.  Both were written by
Michael Scholz, based on CLM's bess5.cl and rt.lisp.
</p>

<div class="seealso">
see also: &nbsp; <a href="fm.html#fmintro">fm</a>
</div>



<!--  FILE: binary-io  -->

<div class="header" id="binaryiodoc">binary-io</div>

<!-- main-index |binaryiodoc:binary files -->

<pre class="indented">
<em class=emdef>read|write-l|bint16|32|64</em>
<em class=emdef>read|write-l|bfloat32|64</em>
<em class=emdef>read|write-chars|string</em>
<em class=emdef>read|write-au-header</em>
</pre>

<p>This file has functions to read and write numbers and strings to and from binary files.
The function names are similar to those used for sample-type names, so for example,
read-bint32 reads the next 4 bytes from the current input port,
interpreting them as a big-endian 32-bit integer.
</p>



<!--  FILE: bird  -->

<div class="header" id="birddoc">bird</div>

<pre class="indented">
<em class=def id="bird">bird</em> start dur frequency freqskew amplitude freq-envelope amp-envelope
<em class=def id="bigbird">bigbird</em> start dur frequency freqskew amplitude freq-envelope amp-envelope partials
<em class=emdef>one-bird</em> beg maxdur func birdname
<em class=def id="makebirds">make-birds</em> (output-file "test.snd")
</pre>

<p>
bird.scm is a translation of the Sambox/CLM bird songs.  The two instruments set
up a sine wave (bird) and waveshaping synthesis (bigbird).  Use a
low-pass filter for distance effects (a bird song sounds really silly
reverberated).  All the real information is in the amplitude and frequency
envelopes.  These were transcribed from sonograms found in some bird guides and articles from
the Cornell Ornithology Lab. 
Many of these birds were used in "Colony".  To hear all the
birds, (make-birds).  This writes the sequence out as "test.snd" using with-sound.
Waveshaping is described in Le Brun, "Digital Waveshaping Synthesis", JAES 1979 April, vol 27, no 4, p250.
The lines
</p>

<pre class="indented">
...
(coeffs (<a class=quiet href="sndclm.html#partialstopolynomial">partials-&gt;polynomial</a> (normalize-partials partials)))
...
   (<a class=quiet href="sndclm.html#polynomial">polynomial</a> coeffs
     (<a class=quiet href="sndclm.html#oscil">oscil</a> os (<a class=quiet href="sndclm.html#env">env</a> gls-env))))))
 <!-- ((( -->
</pre>

<p>setup and run the waveshaping synthesis (in this case it's just a fast
additive synthesis).  partials-&gt;polynomial calculates the Chebyshev
polynomial coefficients given the desired spectrum; the spectrum then
results from driving that polynomial with an oscillator.  Besides the
bird guides, there are now numerous recordings of birds that can
be turned into sonograms and transcribed as envelopes. <a href="sndclm.html#oscil">sndclm.html</a> has the
code for the bird instrument in several languages.
</p>

<div class="seealso">
see also: &nbsp; <a href="#animalsdoc">animals</a>
</div>



<!--  FILE: clean  -->

<div class="header" id="cleandoc">clean</div>

<p>This file provides a set of noise reduction functions packaged up in:
</p>

<pre class="indented">
<em class=def id="cleanchannel">clean-channel</em> snd chn
<em class=def id="cleansound">clean-sound</em> snd
</pre>

<p>
clean-channel tries to fix up clicks, pops, hum, DC offset, clipped portions, and hiss using a
variety of functions from dsp.scm.  The final low-pass filter is relatively conservative (that is,
it's not a very intense filter), so you may want to run another filter over the data after calling
clean-channel.
</p>



<div class="innerheader">A Noisy Story</div>
<!-- INDEX cleandoc:Noise Reduction -->

<p>There is no built-in noise reduction function in Snd.
I believe the most common such function is 
some variant of Perry Cook's
Scrubber program (see anoi in clm-ins.scm or fft-squelch in examp.scm).
Secondary tricks involve smoothing functions similar to smooth-channel,
and enveloping to silence stuff between tracks, and so on.
clean-channel came about when
I blithely offered to clean up some recorded telephone conversations.
The first step was to find the clipped locations (where the conversation was
accidentally over-recorded).  I did this first because there were places in the
recordings where the DC offset was huge, causing clipping in a signal that would
otherwise have been safe.  I hoped to reconstruct the signal at the clipped
points, but these would be hard to find once the DC was removed.  A quick check:
</p>

<pre class="indented">
(count-matches (lambda (y) (not (&gt;= 0.9999 y -0.9999))))
</pre>

<p>
returned 5437 (in 18 minutes of sound).  That seemed high, and I thought "maybe
those are just one sample clicks that can easily be smoothed over", so
</p>

<pre class="indented">
(define* (count-clips snd chn)
  (let ((y0 0.0))
    (count-matches
     (lambda (y) (let ((val (not (or (&gt;= 0.9999 y0 -0.9999) 
                                     (&gt;= 0.9999 y -0.9999)))))
		   (set! y0 y)
		   val))
     0 snd chn)))
</pre>

<p>
But this returned 4768!  I made a list of clipped
portions (this function has at least one bug, but I plowed past it &mdash; no
time for perfection...):
</p>

<pre class="indented">
(define* (list-clips snd chn)
  (let ((clip-data (make-vector (* 2 (count-clips snd chn)) 0))
	(clip-ctr 0)
	(clip-beg 0)
	(clip-end 0)
	(clip-max-len 0)
	(in-clip #f)
	(samp 0))
    (scan-channel
     (lambda (y)
       (if (not (&lt;= -0.9999 y 0.9999))
           (begin
	     (unless in-clip
	       (set! in-clip #t)
	       (set! clip-beg samp))
	     (set! clip-end samp))
	   (if in-clip
	       (begin
		 (set! in-clip #f)
		 (set! (clip-data clip-ctr) clip-beg)
		 (set! (clip-data (+ 1 clip-ctr)) clip-end)
		 (set! clip-max-len (max clip-max-len (- (+ clip-end 1) clip-beg)))
		 (set! clip-ctr (+ clip-ctr 2)))))
       (set! samp (+ 1 samp))
       #f)) ; make sure scan doesn't quit prematurely
    (list clip-ctr clip-max-len clip-data)))
</pre>

<p>
which returned a vector of 669 clipped portions, the worst being 42 samples long!
I saved that data in a separate file, just in case of disaster:
</p>


<pre class="indented">
(with-output-to-file "clips" (lambda () (display (list-clips))))
</pre>


<p>
I decided to try to reconstruct the clipped portions before 
filtering them.
This
produced sample values outside -1.0 to 1.0,
so I reset the graph y bounds:
</p>


<pre class="indented">
(set! (<a class=quiet href="extsnd.html#ybounds">y-bounds</a>) (list -1.5 1.5))
</pre>


<p>
Now to conjure up a plausible sine wave between the clip begin and
end points.  (This is also "just-good-enough" software).
</p>

<pre class="indented">
(define (fix-clip clip-beg-1 clip-end-1)
  (and (&gt; clip-end-1 clip-beg-1)
       (let* ((dur (- (+ clip-end-1 1) clip-beg-1))
              (samps (channel-&gt;float-vector (- clip-beg-1 4) (+ dur 9)))
              (clip-beg 3)
              (clip-end (+ dur 4)))
         (let ((samp0 (samps clip-beg))
               (samp1 (samps clip-end)))
           (unless (&gt;= 0.99 samp0 -0.99)
             ;; weird!  some of the clipped passages have "knees"
             ;;   this looks nuts, but no time to scratch my head
             (set! clip-beg (- clip-beg 1))
             (set! samp0 (samps clip-beg))
             (unless (&gt;= 0.99 samp0 -0.99)
               (set! clip-beg (- clip-beg 1))
               (set! samp0 (samps clip-beg))))
           (unless (&gt;= 0.99 samp0 -0.99)
             (set! clip-end (+ 1 clip-end))
             (set! samp1 (samps clip-end))
             (unless (&gt;= 0.99 samp0 -0.99)
               (set! clip-end (+ 1 clip-end))
               (set! samp1 (samps clip-end))))
           ;; now we have semi-plausible bounds
           ;; make sine dependent on rate of change of current 
           (let* ((samp00 (samps (- clip-beg 1)))
                  (samp11 (samps (+ 1 clip-end)))
                  (dist (- clip-end clip-beg))
                  (incr (/ pi dist))
                  (amp (* .125 (+ (abs (- samp0 samp00)) (abs (- samp1 samp11))) dist)))
             (if (&gt; samp0 0.0)
                 ;; clipped at 1.0
                 (do ((i (+ 1 clip-beg) (+ i 1))
                      (angle incr (+ angle incr)))
                     ((= i clip-end))
                   (set! (samps i) (+ 1.0 (* amp (sin angle)))))
                 ;; clipped at -1.0
                 (do ((i (+ 1 clip-beg) (+ i 1))
                      (angle incr (+ angle incr)))
                     ((= i clip-end))
                   (set! (samps i) (- -1.0 (* amp (sin angle))))))
             (float-vector-&gt;channel samps (- clip-beg-1 4)))))))

(define (fix-it n)
  ;; turn off graphics and fix all the clipped sections
  (set! (<a class=quiet href="extsnd.html#squelchupdate">squelch-update</a>) #t)
  (do ((i 0 (+ i 1)))
      ((= i n))
      ;; "clips" here is a list form of the earlier vector of clip locations
    (fix-clip (clips (* i 2)) 
	      (clips (+ 1 (* i 2)))))
  (set! (<a class=quiet href="extsnd.html#squelchupdate">squelch-update</a>) #f))

(fix-it 669)
</pre>

<p id="notchoutrumbleandhiss">
This produced 418 edits, with a maxamp of 2.26.  So scale it back down:
(<a class=quiet href="extsnd.html#scaleto">scale-to</a> .9).
Next I ran some large ffts to see what sort of overall spectrum I had:
(set! (<a class=quiet href="extsnd.html#transformsize">transform-size</a>) (expt 2 23)).
This showed a massive DC component, and numerous harmonics of 60 Hz.
I decided to get rid of the portions that were clearly noise.  Since I was dealing with
telephone recordings, I assumed anything under 40 Hz or above
4000 Hz was extraneous:
</p>

<pre class="indented">
(define* (notch-out-rumble-and-hiss snd chn)
  (let ((cur-srate (exact-&gt;inexact (<a class=quiet href="extsnd.html#srate">srate</a> snd))))
    (<a class=quiet href="extsnd.html#filtersound">filter-sound</a>
     (list 0.0 0.0                    ; get rid of DC
	   (/ 80.0 cur-srate) 0.0     ; get rid of anything under 40 Hz (1.0=srate/2 here)
	   (/ 90.0 cur-srate) 1.0     ; now the passband
	   (/ 7000.0 cur-srate) 1.0 
	   (/ 8000.0 cur-srate) 0.0   ; end passband (40..4000)
	   1.0 0.0)                   ; get rid of some of the hiss
     ;; since I'm assuming the minimum band is 10 Hz here, 
     ;;   cur-srate/10 rounded up to next power of 2 seems a safe filter size
     ;;   filter-sound will actually use overlap-add convolution in this case
     (floor (expt 2 (ceiling (log (/ cur-srate 10.0) 2))))
     snd chn)))

(notch-out-rumble-and-hiss)
</pre>

<p>
By now it was obvious I needed a simple way to play portions of the
sound before and after an edit, sometimes with a tracking cursor.
So I bound a few keys:
</p>

<pre class="indented">
(define (play-from-cursor current)
  (<a class=quiet href="extsnd.html#play">play</a> (<a class=quiet href="extsnd.html#cursor">cursor</a>) #f #f #f #f (and (not current) (- (<a class=quiet href="extsnd.html#editposition">edit-position</a>) 1))))

(define (play-from-cursor-with-tracking current)
  ;; patterned after pfc in extsnd.html
  (let ((old-tracking (<a class=quiet href="extsnd.html#withtrackingcursor">with-tracking-cursor</a>)))
    (set! (<a class=quiet href="extsnd.html#withtrackingcursor">with-tracking-cursor</a>) #t)
    (hook-push <a class=quiet href="extsnd.html#stopplayinghook">stop-playing-hook</a> 
	       (lambda (hook)
		 (set! (<a class=quiet href="extsnd.html#withtrackingcursor">with-tracking-cursor</a>) old-tracking)))
    (<a class=quiet href="extsnd.html#play">play</a> (<a class=quiet href="extsnd.html#cursor">cursor</a>) #f #f #f #f (and (not current) (- (<a class=quiet href="extsnd.html#editposition">edit-position</a>) 1)))))

(<a class=quiet href="extsnd.html#bindkey">bind-key</a> #\p 0 (lambda () 
                  "play from cursor" 
	  	  (play-from-cursor #t) <a class=quiet>keyboard-no-action</a>))
(<a class=quiet href="extsnd.html#bindkey">bind-key</a> #\P 0 (lambda () 
                  "play previous from cursor" 
		  (play-from-cursor #f) <a class=quiet>keyboard-no-action</a>))
(<a class=quiet href="extsnd.html#bindkey">bind-key</a> #\p 4 (lambda () 
                  "play from cursor with tracking" 
		  (play-from-cursor-with-tracking #t) <a class=quiet>keyboard-no-action</a>))
</pre>

<p>
In words, if the mouse is in the channel graph, 'p' plays from the cursor,
'P' plays the previous version from the cursor, and 'C-p' plays from
the cursor with a "tracking cursor".
In several of the sections (the overall sound consisted of a couple dozen
separate conversations), there was a loud mid-range tone.  To figure out what its component frequencies were,
I FFT'd a portion containing only that noise and got this spectrum
(plus a zillion other peaks that didn't look interesting):
</p>

<pre class="indented">
((425 .05) (450 .01) (546 .02) (667 .01) (789 .034) (910 .032) (470 .01))
</pre>

<p>To hear that, I passed this list to <a href="#playsines">play-sines</a>:
</p>

<pre class="indented">
(play-sines '((425 .05) (450 .01) (546 .02) (667 .01) (789 .034) (910 .032) (470 .01)))
</pre>

<p>
And to my surprise, the result was close to the main portion of the hum.  
So now to notch out those frequencies,
and see what is left: (notch-sound (list 425 450 470 546 667 789 910) #f 1 10).
This erased most of the hum, but it also
changed the timbre of the voices which wasn't acceptable.
I goofed around with the notch-width and filter-size parameters, looking
for something that would still do the trick without removing
the personal side of the voices, but in only a few cases was the result
usable. What was being said was not very important, but the
individual characteristics of each voice were.
</p>

<p>
The next step was to take out noisy sections between snippets, mostly
using (<a class=quiet href="extsnd.html#envselection">env-selection</a> '(0 1 1 0 10 0 11 1))
and equalizing each snippet, more or less, with scale-selection-by.
There were a few "you-are-being-recorded" beeps which I deleted (via the Edit
menu delete selection option).  
In some of the conversations,
between sections of speech the background hum would gradually increase, then
the voice would abruptly start with a large peak amplitude. These
were fixed mostly with small-section scale-by's and envelopes.
In the female voice sections, it seemed to help to:
(<a class=quiet href="extsnd.html#filterselection">filter-selection</a> '(0 0 .01 0 .02 1 1 1) 1024)
which got rid of some of the rumble without noticeably affecting
the vocal timbre.
</p>


<div class="seealso">
see also: &nbsp; <a href="extsnd.html#smoothchannel">smooth-channel</a> &nbsp; <a href="#removeclicks">remove-clicks</a> &nbsp; <a href="#fftsmoother">fft-smoother</a> &nbsp;
<a href="#notchoutrumbleandhiss">notch-out-rumble-and-hiss</a> &nbsp; <a href="#fftsquelch">fft-squelch</a> &nbsp;
<a href="#fftcancel">fft-cancel</a> &nbsp;
<a href="#notchchannel">notch-channel</a> &nbsp; <a href="#anoi">anoi</a>
</div>





<!--  FILE: clm-ins  -->

<div class="header" id="clminsdoc">clm-ins</div>

<p>These are instruments from CLM translated for use in Snd.  All expect to be called within <a href="#wsdoc">with-sound</a>
or some equivalent environment. This set of instruments is a bit of a grab-bag; some are just examples of synthesis techniques;
a few others are historical, rather than useful.  If I were using, for example, the fm trumpet,
I'd remove all the attack and decay parameters, moving that up a level to Common Music or whoever calls the trumpet,
and combine several other parameters to reflect the desired output, rather than the details of the algorithm;
30 parameters could be reduced to less than 10, and the resulting instrument would be much easier to use.
But, it is an historical artifact, so I'm reluctant to change it.  
</p>

<p>To try out any of these instruments, start Snd, load ws.scm and clm-ins.scm, then
paste the with-sound call into the listener.  It will automatically write the
new sound file and open it in Snd.
</p>

<div class="separator"></div>
<!-- anoi -->
<pre class="indented">
<em class=def id="anoi">anoi</em> file start dur (fftsize 128) (amp-scaler 1.0) (r 6.28)
</pre>

<p>
anoi is a stab at noise reduction
based on Perry Cook's Scrubber.m.  It tracks an on-going average spectrum, then tries
to squelch that, obviously aimed at reducing background noise in an intermittent signal.
</p>

<pre class="indented">
(<a class=quiet href="#wsdoc">with-sound</a> () (anoi "now.snd" 0 2))
</pre>

<div class="separator"></div>



<!-- attract -->
<pre class="indented">
<em class=emdef>attract</em> beg dur amp c
</pre>

<p>attract is a translation to CLM of an instrument developed by James McCartney (CMJ vol 21 no 3 p 6),
based on a "chaotic" equation.
'c' should be between 1 and 10 or thereabouts.
</p>

<pre class="indented">
(<a class=quiet href="#wsdoc">with-sound</a> () (attract 0 1 .1 1) (attract 1 1 .1 5))
</pre>

<div class="separator"></div>


<!-- bes-fm -->
<pre class="indented">
<em class=emdef>bes-fm</em> beg dur freq amp ratio index
</pre>

<p>bes-fm is J1(J1): <code>(bes-j1 (* index (bes-j1 phase)))</code>; it uses the Bessel functions where FM uses sinusoids.  J0 is also good in this context,
and the few other Jn options that I've tried were ok.
</p>

<pre class="indented">
Scheme:  (with-sound () (bes-fm 0 1 440 10.0 1.0 4.0))
Ruby:    with_sound() do bes_fm(0, 0.5, 440, 5, 1, 8) end
</pre>

<p>So why does this work?  My "back-of-the-envelope" guess is that the Bessel functions
are basically a bump at the start followed by a decaying sinusoid, so
the bump
gives us a percussive attack, and the damped sinusoid gives us
a dynamic spectrum, mimicking FM more or less.
The Bessel functions I0, Jn, and Yn are built-in; Kn and In are implemented in Scheme in snd-test.scm. See <a href="sndclm.html#bess">bess</a> and friends
for many more examples.
</p>
<div class="separator"></div>



<!-- main-index |bagpipe:bagpipe -->
<!-- canter -->
<pre class="indented">
<em class=def id="bagpipe">canter</em> beg dur freq amp ...
</pre>

<p>canter is half of a bagpipe instrument developed by Peter Commons (the other portion is <a href="#drone">drone</a> below).
The (required) trailing parameters are:
</p>

<pre class="indented">
deg dis pcrev ampfun ranfun skewfun skewpc ranpc ranfreq indexfun atdr dcdr
ampfun1 indfun1 fmtfun1 ampfun2 indfun2 fmtfun2 ampfun3 indfun3 fmtfun3 ampfun4 indfun4 fmtfun4
</pre>

<p>Here is a portion of a bagpipe tune:
</p>

<pre class="indented">
(let ((fmt1 '(0 1200 100 1000))
      (fmt2 '(0 2250 100 1800))
      (fmt3 '(0 4500 100 4500))
      (fmt4 '(0 6750 100 8100))
      (amp1 '(0 .67 100 .7))
      (amp2 '(0 .95 100 .95))
      (amp3 '(0 .28 100 .33))
      (amp4 '(0 .14 100 .15))
      (ind1 '(0 .75 100 .65))
      (ind2 '(0 .75 100 .75))
      (ind3 '(0 1 100 1))
      (ind4 '(0 1 100 1))
      (skwf '(0 0 100 0))
      (ampf '(0 0 25 1 75 1 100 0))
      (ranf '(0 .5 100 .5))
      (index '(0 1 100 1))
      (solid '(0 0 5 1 95 1 100 0))
      (bassdr2 '(.5 .06 1 .62 1.5 .07 2.0 .6 2.5 .08 3.0 .56 4.0 .24 5 .98 6 .53 7 
                 .16 8 .33 9 .62 10 .12 12 .14 14 .86 16 .12 23 .14 24 .17))
      (tenordr '(.3 .04 1 .81 2 .27 3 .2 4 .21 5 .18 6 .35 7 .03 8 .07 9 .02 10 .025 11 .035)))
  (<a class=quiet href="#wsdoc">with-sound</a> (:reverb nrev)
    (drone .000 4.000 115.000 (* .25 .500) solid bassdr2 .100 .500 .030 45.000 1 .010 10)
    (drone .000 4.000 229.000 (* .25 .500) solid tenordr .100 .500 .030 45.000 1 .010 11)
    (drone .000 4.000 229.500 (* .25 .500) solid tenordr .100 .500 .030 45.000 1 .010 9)
    (canter .000 2.100 918 (* .25 .700) 45.000 1 .050 ampf ranf skwf 
             .050 .010 10 index .005 .005 amp1 ind1 fmt1 amp2 ind2 fmt2 amp3 ind3 fmt3 amp4 ind4 fmt4)
    (canter  2.100  .300 688.5  (* .25 .700)  45.000 1  .050 ampf ranf skwf
	     .050  .010 10 index  .005  .005 amp1 ind1 fmt1 amp2 ind2 fmt2 amp3 ind3 fmt3 amp4 ind4 fmt4)
    (canter  2.400  .040 826.2  (* .25 .700)  45.000 1  .050 ampf ranf skwf
	     .050  .010 10 index  .005  .005 amp1 ind1 fmt1 amp2 ind2 fmt2 amp3 ind3 fmt3 amp4 ind4 fmt4)
    (canter  2.440  .560 459  (* .25 .700)  45.000 1  .050 ampf ranf skwf
	     .050  .010 10 index  .005  .005 amp1 ind1 fmt1 amp2 ind2 fmt2 amp3 ind3 fmt3 amp4 ind4 fmt4)
    (canter  3.000  .040 408  (* .25 .700)  45.000 1  .050 ampf ranf skwf
	     .050  .010 10 index  .005  .005 amp1 ind1 fmt1 amp2 ind2 fmt2 amp3 ind3 fmt3 amp4 ind4 fmt4)
    (canter  3.040  .040 619.65  (* .25 .700)  45.000 1  .050 ampf ranf skwf
	     .050  .010 10 index  .005  .005 amp1 ind1 fmt1 amp2 ind2 fmt2 amp3 ind3 fmt3 amp4 ind4 fmt4)
    (canter  3.080  .040 408  (* .25 .700)  45.000 1  .050 ampf ranf skwf
	     .050  .010 10 index  .005  .005 amp1 ind1 fmt1 amp2 ind2 fmt2 amp3 ind3 fmt3 amp4 ind4 fmt4)
    (canter  3.120  .040 688.5  (* .25 .700)  45.000 1  .050 ampf ranf skwf
	     .050  .010 10 index  .005  .005 amp1 ind1 fmt1 amp2 ind2 fmt2 amp3 ind3 fmt3 amp4 ind4 fmt4)
    (canter  3.160  .290 459  (* .25 .700)  45.000 1  .050 ampf ranf skwf
	     .050  .010 10 index  .005  .005 amp1 ind1 fmt1 amp2 ind2 fmt2 amp3 ind3 fmt3 amp4 ind4 fmt4)
    (canter  3.450  .150 516.375  (* .25 .700)  45.000 1  .050 ampf ranf skwf
	     .050  .010 10 index  .005  .005 amp1 ind1 fmt1 amp2 ind2 fmt2 amp3 ind3 fmt3 amp4 ind4 fmt4)
    (canter  3.600  .040 826.2  (* .25 .700)  45.000 1  .050 ampf ranf skwf
	     .050  .010 10 index  .005  .005 amp1 ind1 fmt1 amp2 ind2 fmt2 amp3 ind3 fmt3 amp4 ind4 fmt4)
    (canter  3.640  .040 573.75  (* .25 .700)  45.000 1  .050 ampf ranf skwf
	     .050  .010 10 index  .005  .005 amp1 ind1 fmt1 amp2 ind2 fmt2 amp3 ind3 fmt3 amp4 ind4 fmt4)
    (canter  3.680  .040 619.65  (* .25 .700)  45.000 1  .050 ampf ranf skwf
	     .050  .010 10 index  .005  .005 amp1 ind1 fmt1 amp2 ind2 fmt2 amp3 ind3 fmt3 amp4 ind4 fmt4)
    (canter  3.720  .180 573.75  (* .25 .700)  45.000 1  .050 ampf ranf skwf
	     .050  .010 10 index  .005  .005 amp1 ind1 fmt1 amp2 ind2 fmt2 amp3 ind3 fmt3 amp4 ind4 fmt4)
    (canter  3.900  .040 688.5  (* .25 .700)  45.000 1  .050 ampf ranf skwf
	     .050  .010 10 index  .005  .005 amp1 ind1 fmt1 amp2 ind2 fmt2 amp3 ind3 fmt3 amp4 ind4 fmt4)
    (canter  3.940  .260 459  (* .25 .700)  45.000 1  .050 ampf ranf skwf
	     .050  .010 10 index  .005  .005 amp1 ind1 fmt1 amp2 ind2 fmt2 amp3 ind3 fmt3 amp4 ind4 fmt4)))
</pre>

<p>It is not easy to keep track of all these arguments in a long note-list; hence the
development of programs such as Score (Leland Smith), Pla (yers truly), and Common Music (Rick Taube).
The full note list is bag.clm in the CLM tarball.
</p>

<div class="separator"></div>


<!-- main-index |cellon:feedback fm -->
<!-- cellon -->
<pre class="indented">
<em class=def id="cellon">cellon</em> beg dur freq amp ...
</pre>

<p>cellon, developed by Stanislaw Krupowiecz, uses feedback FM as in some old synthesizers.  There's a brief discussion of it in <a href="fm.html">fm.html</a>.
The trailing parameters are:
</p>

<pre class="indented">
ampfun betafun beta0 beta1 betaat betadc ampat ampdc dis pcrev deg pitch1 glissfun glissat 
glissdc pvibfreq pvibpc pvibfun pvibat pvibdc rvibfreq rvibpc rvibfun
</pre>

<p>and I actually don't know what they all do.  I think they're dealing with attack and decay portions
of envelopes; in the old days we felt we had to store one envelope, then kludge around with attack and decay
timings to bash that envelope into the correct shape; this made instruments needlessly messy.
Here's a call:
</p>

<pre class="indented">
(<a class=quiet href="#wsdoc">with-sound</a> () 
  (cellon 0 2 220 .1 '(0 0 25 1 75 1 100 0) '(0 0 25 1 75 1 100 0) .75 1.0 0 0 0 0 1 0 0 220 
          '(0 0 25 1 75 1 100 0) 0 0 0 0 '(0 0 100 0) 0 0 0 0 '(0 0 100 0)))
</pre>

<p>The use of x axis values between 0 and 100, rather than 0.0 and 1.0 is a dead give-away that
this is really ancient stuff.
</p>

<div class="separator"></div>


<!-- clm-expsrc -->
<pre class="indented">
<em class=def id="clmexpsrc">clm-expsrc</em> beg dur input-file exp-ratio src-ratio amp rev start-in-file
</pre>

<p>clm-expsrc can stretch or compress a sound (using granular synthesis) while optionally changing its sampling rate.
'exp-ratio' sets the expansion amount (greater than 1.0 makes the sound longer), and
'src-ratio' sets the sampling rate change (greater than 1.0 makes it higher in pitch).
So to make a sound twice as long, but keep the pitch the same:
</p>

<pre class="indented">
(<a class=quiet href="#wsdoc">with-sound</a> () (clm-expsrc 0 4 "oboe.snd" 2.0 1.0 1.0))
</pre>

<p>'start-in-file' sets where we start reading the input file (in seconds); it defaults to 0.0.
</p>
<div class="separator"></div>



<!-- drone -->
<pre class="indented">
<em class=def id="drone">drone</em> beg dur freq amp ampfun synth ampat ampdc amtrev deg dis rvibamt rvibfreq
</pre>

<p>This is the other half of Peter Common's bagpipe &mdash; see canter above.
'synth' is a list of partials loaded into a table and read via <a href="sndclm.html#table-lookup">table-lookup</a>.
</p>
<div class="separator"></div>


<!-- expandn -->
<pre class="indented">
<em class=emdef>expandn</em> time duration file amp ...
</pre>

<p>
Here is the documentation from Rick Taube's granular synthesis page, edited slightly for the Scheme CLM.
</p>

<p>
The expandn instrument by Michael Klingbeil performs granular syntheisis by time-stretching (expanding/compressing) an input file. 
This effect is achieved by chopping up the input sound into very small segments (grains) that are then overlayed in the ouput stream. 
The larger the segments, the more the output sound is smeared, an effect approaching reverberation.
The expandn instrument parameters are:
</p>

<pre class="indented">
   time duration filename amplitude
	(expand 1.0)
	(matrix #f)
	(ramp 0.4)
	(seglen 0.15)
	(srate 1.0)
	(hop .05)
	(amp-env '(0 0 50 1 100 0))
	(input-start 0.0)
	(grain-amp 0.8)
	(reverb #f)
</pre>

<p>
'time' is the start time of the sound in the output file.
'duration' is the duration of expanded sound. To expand an entire sound, set this to the expansion factor times the input sound's duration.
'filename' is the input file to expand.
'amplitude' is a scaler on the amplitude of the input file. Since the output is created by overlaying many copies of the intput this value is generally less than 1.
'hop' can be a number or an envelope. It is the average length in time between segments (grains) in the output.
'expand' can be a number or an envelope. It sets the amount of expansion to produce in the output file.
'seglen'can be a number or an envelope. It is the length in time of the sound segments (grains).
'srate' can be a number or an envelope. It sets the sampling rate change to apply to the output file.
'amp-env' is the amplitude envelope for the output sound.
'input-start' sets where to start reading in the input file.
'grain-amp' is a scaler on each grain's amplitude.
'matrix' is a list, a mixing matrix.
'reverb' is the reverb amount.
</p>
<div class="separator"></div>


<!-- expfil -->
<pre class="indented">
<em class=emdef>expfil</em> start duration hopsecs rampsecs steadysecs file1 file2
</pre>

<p>expfile interleaves two granular synthesis processes (two readers pasting in tiny sections
of their file, one after the other).
</p>

<pre class="indented">
(<a class=quiet href="#wsdoc">with-sound</a> () 
  (expfil 0 2 .2 .01 .1 "oboe.snd" "fyow.snd")
  (expfil 2 2 .01 .01 .02 "oboe.snd" "fyow.snd"))
</pre>

<div class="separator"></div>


<!-- exp-snd -->
<pre class="indented">
<em class=emdef>exp-snd</em> file beg dur amp (exp-amt 1.0) (ramp .4) (seglen .15) (sr 1.0) (hop .05) ampenv
</pre>

<p>exp-snd is a granular synthesis instrument with envelopes on
the expansion amount ('exp-amt' as a list), segment ramp steepness ('ramp' as a list), 
segment length ('seglen' as a list), hop length ('hop' as a list), amplitude ('ampenv'),
and resampling rate ('sr' as a list).
In the next example, the expansion amount in both calls goes from 1 to 3 over the course of the note,
the ramp time and segment lengths stay the same, the sampling rate changes from 2 to 0.5, and the hop
stays the same (.05 in the first, and .2 in the second).
</p>

<pre class="indented">
(<a class=quiet href="#wsdoc">with-sound</a> ()
  (exp-snd "fyow.snd" 0 3 1 '(0 1 1 3) 0.4 .15 '(0 2 1 .5) 0.05)
  (exp-snd "oboe.snd" 1 3 1 '(0 1 1 3) 0.4 .15 '(0 2 1 .5) 0.2))
</pre>

<div class="separator"></div>


<!-- fm-bell -->
<pre class="indented">
<em class=def id="fmbell">fm-bell</em> beg dur frequency amplitude amp-env index-env index
</pre>
fm-bell is an <a href="fm.html#fmintro">FM</a> instrument developed by Michael McNabb in Mus10 in the late '70s.  It is intended
for low bell sounds (say middle C or so). The lines

<pre class="indented">
  (mod1 (<a class=quiet href="sndclm.html#make-oscil">make-oscil</a> (* frequency 2)))
  (mod2 (<a class=quiet href="sndclm.html#make-oscil">make-oscil</a> (* frequency 1.41)))
  (mod3 (<a class=quiet href="sndclm.html#make-oscil">make-oscil</a> (* frequency 2.82)))
  (mod4 (<a class=quiet href="sndclm.html#make-oscil">make-oscil</a> (* frequency 2.4)))
  (car1 (<a class=quiet href="sndclm.html#make-oscil">make-oscil</a> frequency))
  (car2 (<a class=quiet href="sndclm.html#make-oscil">make-oscil</a> frequency))
  (car3 (<a class=quiet href="sndclm.html#make-oscil">make-oscil</a> (* frequency 2.4)))
</pre>

set up three FM pairs, car1 and mod1 handling the basic harmonic spectra,
car2 and mod2 creating inharmonic spectra (using the square root of 2 more or less
at random), and car3 and mod3 putting a sort of formant at the minor third
(2.4 = a ratio of 12/5 = octave+6/5 = minor tenth).

<pre class="indented">
(<a class=quiet href="#wsdoc">with-sound</a> ()
  (fm-bell 0.0 2.0 220.0 .5
    '(0 0 .1000 1 10 .6000 25 .3000 50 .1500 90 .1000 100 0)
    '(0 1 2 1.1000 25 .7500 75 .5000 100 .5000)
    0.5))
</pre>

<div class="separator"></div>


<!-- fm-drum -->
<pre class="indented">
<em class=def id="fmdrum">fm-drum</em> beg dur freq amp ind (high #f) (deg 0.0) (dist 1.0) (rev-amount 0.01)
</pre>

<p>The fm-drum uses "cascade FM" (see <a href="fm.html">fm.html</a>); it was developed by Jan Mattox.
</p>

<pre class="indented">
(<a class=quiet href="#wsdoc">with-sound</a> () (fm-drum 0 1.5 55 .3 5 #f) (fm-drum 1.5 1.5 66 .3 4 #t))
</pre>

<div class="separator"></div>



<!-- fm-insect -->
<pre class="indented">
<em class=emdef>fm-insect</em> beg dur freq amp ampenv modfreq modskew modenv index indexenv fmindex ratio deg dist rev
</pre>

<p>The fm-insect started as an attempt to get cicada sounds from FM (for the 5th movement of "Colony"), but
ended with:
</p>

<pre class="indented">
(<a class=quiet href="#wsdoc">with-sound</a> (:srate 22050) 
  (let ((locust '(0 0 40 1 95 1 100 .5))
	(bug_hi '(0 1 25 .7 75 .78 100 1))
	(amp    '(0 0 25 1 75 .7 100 0)))
    (fm-insect 0      1.699  4142.627  .015 amp 60 -16.707 locust 500.866 bug_hi  .346  .500)
    (fm-insect 0.195   .233  4126.284  .030 amp 60 -12.142 locust 649.490 bug_hi  .407  .500)
    (fm-insect 0.217  2.057  3930.258  .045 amp 60 -3.011  locust 562.087 bug_hi  .591  .500)
    (fm-insect 2.100  1.500   900.627  .06  amp 40 -16.707 locust 300.866 bug_hi  .346  .500)
    (fm-insect 3.000  1.500   900.627  .06  amp 40 -16.707 locust 300.866 bug_hi  .046  .500)
    (fm-insect 3.450  1.500   900.627  .09  amp 40 -16.707 locust 300.866 bug_hi  .006  .500)
    (fm-insect 3.950  1.500   900.627  .12  amp 40 -10.707 locust 300.866 bug_hi  .346  .500)
    (fm-insect 4.300  1.500   900.627  .09  amp 40 -20.707 locust 300.866 bug_hi  .246  .500)))
</pre>

<p>See <a href="#animalsdoc">animals.scm</a> for much more convincing insect calls.
</p>
<div class="separator"></div>



<!-- fm-trumpet -->
<pre class="indented">
<em class=def id="fmtrumpet">fm-trumpet</em> beg dur ...
</pre>

<p>This is Dexter Morrill's FM-trumpet; see CMJ feb 77 p51.
</p>

<pre class="indented">
(<a class=quiet href="#wsdoc">with-sound</a> () (fm-trumpet 0 .25))
</pre>

<p>As with many instruments from that era, it has a million parameters:
</p>

<pre class="indented">
    beg dur (frq1 250.0) (frq2 1500.0) (amp1 0.5) (amp2 0.1)
    (ampatt1 0.03) (ampdec1 0.35) (ampatt2 0.03) (ampdec2 0.3)
    (modfrq1 250.0) (modind11 0.0) (modind12 2.66) 
    (modfrq2 250.0) (modind21 0.0) (modind22 1.8) 
    (rvibamp 0.007) (rvibfrq 125.0) (vibamp 0.007) (vibfrq 7.0) (vibatt 0.6) (vibdec 0.2)
    (frqskw 0.03) (frqatt 0.06) 
    (ampenv1 '(0 0  25 1  75 .9  100 0)) (ampenv2 '(0 0  25 1  75 .9  100 0)) 
    (indenv1 '(0 0  25 1  75 .9  100 0)) (indenv2 '(0 0  25 1  75 .9  100 0))
    (degree 0.0) (distance 1.0) (reverb-amount 0.005)
</pre>

<p>The pitch depends on the 'modfrq1' and 'modfrq2' parameters, as well as 'frq1' and 'frq2':
</p>

<pre class="indented">
(<a class=quiet href="#wsdoc">with-sound</a> () (fm-trumpet 0 1 :frq1 400 :frq2 1600 :modfrq1 400 :modfrq2 400))
</pre>
<div class="separator"></div>



<pre class="indented">
<em class=def id="fmvoice">fm-voice</em> beg dur ...
</pre>

<p>This is John Chowning's FM voice instrument, used in "Phone" I think.
It is in jcvoi.scm, not clm-ins.scm.  Its parameters are:
</p>

<pre class="indented">
beg dur pitch amp vowel-1 sex-1 ampfun1 ampfun2 ampfun3 
indxfun skewfun vibfun ranfun
dis pcrev deg vibscl pcran skewscl ranpower glissfun glissamt
</pre>

<p>Here's an example:</p>

<pre class="indented">
(let ((ampf '(0 0 1 1 2 1 3 0))) 
  (with-sound (:play #t) 
    (fm-voice 0 1 300 .8 3 1 ampf ampf ampf ampf ampf ampf ampf 1 0 0 .25 .01 0 ampf .01)))
</pre>
<div class="separator"></div>




<!-- main-index |fofins:FOF synthesis -->
<!-- fofins -->
<pre class="indented">
<em class=def id="fofins">fofins</em> beg dur frq amp uvib f0 a0 f1 a1 f2 a2 (amp-env '(0 0 1 1 2 1 3 0))
</pre>

<p>fofins is an implementation of <A HREF="http://www-ccrma.stanford.edu/~serafin/320/lab3/FOF_synthesis.html">FOF synthesis</A>, taken originally from
fof.c of Perry Cook and the article
"Synthesis of the Singing Voice" by Bennett and Rodet in
"Current Directions in Computer Music Research" (MIT Press).
FOF synthesis sets up a wave with the desired spectrum (to mimic vocal formats, for example),
then calls <a href="sndclm.html#wave-train">wave-train</a> to turn that into a tone.
fofins just adds an amplitude envelope and vibrato.
In the Scheme version, there is also an optional trailing vibrato envelope argument (this is slightly different from the CL version):
</p>

<pre class="indented">
(<a class=quiet href="#wsdoc">with-sound</a> ()  ; slowly ramp up the vibrato
  (fofins 0 4 270 .1 0.005 730 .6 1090 .3 2440 .1 
          '(0 0 .5 1 3 .5 10 .2 20 .1 50 .1 60 .2 85 1 100 0)
	  '(0 0 40 0 75 .2 100 1) )
  (fofins 0 4 648 .1 0.005 730 .6 1090 .3 2440 .1 ;648 (* 6/5 540)
          '(0 0 .5 .5 3 .25 6 .1 10 .1 50 .1 60 .2 85 1 100 0)
	  '(0 0 40 0 75 .2 100 1) )
  (fofins 0 4 135 .1 0.005 730 .6 1090 .3 2440 .1 
          '(0 0 1 3 3 1 6 .2 10 .1 50 .1 60 .2 85 1 100 0)
	  '(0 0 40 0 75 .2 100 1)))
</pre>

<div class="separator"></div>


<!-- fullmix -->
<pre class="indented">
<em class=def id="fullmix">fullmix</em> infile beg outdur inbeg matrix srate reverb-amount
</pre>

<p>fullmix is a complicated way to mix stuff. It's built into the CL version of CLM, so there was clamor for some sort
of replacement in other versions of CLM. 
fullmix provides a sound file mixer that can handle any number
of channels of data in and out with scalers and envelopes on any path, sampling rate conversion,
reverb &mdash; you name it! 
'infile' is the file to be mixed:
</p>

<pre class="indented">
(<a class=quiet href="#wsdoc">with-sound</a> () (fullmix "pistol.snd")) ; this places pistol.snd at time 0
</pre>

<p>'beg' is the start time of the mix in the output sound; 
'outdur' is the duration of the mixed-in portion in the output;
'inbeg' is where to start the mix in the input file:
</p>

<pre class="indented">
(<a class=quiet href="#wsdoc">with-sound</a> () (fullmix "pistol.snd" 1.0 2.0 0.25)) 
;; start at 0.25 in pistol.snd, include next 2 secs, put at time 1.0 in output
</pre>

<p>'srate' is the amount of sampling rate conversion to apply, and
'reverb' is the amount of the signal to send to the reverberator:
</p>

<pre class="indented">
(<a class=quiet href="#wsdoc">with-sound</a> (:reverb nrev) (fullmix "pistol.snd" 1.0 2.0 0.25 #f 2.0 0.1)) ; up an octave, lots of reverb!
</pre>

<p>The 'matrix' parameter is much harder to describe.  It is either a number or a list of lists.
In the first case, that number is the amplitude scaler on the output:
</p>

<pre class="indented">
(<a class=quiet href="#wsdoc">with-sound</a> (:reverb nrev) (fullmix "pistol.snd" 1.0 2.0 0.25 0.2 2.0 0.1)) ; same but much softer (0.2 amp)
</pre>

<p>If 'matrix' is a list of lists, each element of the inner lists can be either a number or list a breakpoints (an envelope).
If a number, it is treated as an amplitude scaler for that input and output channel combination.  Each inner list
represents an input channel, so if we have a stereo input file going to a stereo output file and we want
the channels to be mixed straight, but channel 0 at .5 amp and channel 1 at .75:
</p>

<pre class="indented">
(<a class=quiet href="#wsdoc">with-sound</a> (:channels 2) (fullmix "2a.snd" #f #f #f '((0.5 0.0) (0.0 0.75))))
;;                                                       ^   ^     ^   ^
;;                                                       |   |     |   |
;;                                                    0-&gt;0   |  1-&gt;0   |
;;                                                        0-&gt;1      1-&gt;1
</pre>

<p>So, 2a.snd's first channel gets mixed into the output's first channel, scaled by 0.5, 
and its second channel goes to the output second channel scaled by 0.75.
If we have four channels in and are writing a mono file, and want to mix in
only the second channel of the input:
</p>

<pre class="indented">
(<a class=quiet href="#wsdoc">with-sound</a> (:channels 1) (fullmix "4.aiff" #f #f #f '((0.0) (1.0) (0.0) (0.0))))
</pre>

<p>The next complication is that each entry in the inner lists can also be a list of
envelope breakpoints.  In that case, an envelope is applied to that portion of the
mix, rather than just a scaler:
</p>

<pre class="indented">
(<a class=quiet href="#wsdoc">with-sound</a> (:channels 2) (fullmix "oboe.snd" #f #f #f (list (list (list 0 0 1 1 2 0) 0.5))))
;; mono input so one list, envelope output chan 0, scale output chan 1 (two copies of input) 
</pre>

<p>And finally(!) each inner list element can also be a CLM env generator:
</p>

<pre class="indented">
(<a class=quiet href="#wsdoc">with-sound</a> (:channels 2)
  (fullmix "oboe.snd" 1 2 0 (list (list .1 (<a class=quiet href="sndclm.html#make-env">make-env</a> '(0 0 1 1) :duration 2 :scaler .5)))))
</pre>

<p>Here's a Ruby example:
</p>

<pre class="indented">
with_sound(:channels, 2, :statistics, true) do
  fullmix("pistol.snd")
  fullmix("oboe.snd", 1, 2, 0, [[0.1, make_env([0, 0, 1, 1], :duration, 2, :scaler, 0.5)]])
end
</pre>

<p>"srate" can be negative (meaning read in reverse) or a list or breakpoints (an src envelope).
Now we need filters!
</p>

<div class="separator"></div>



<!-- gong -->
<pre class="indented">
<em class=emdef>gong</em> beg dur freq amp (degree 0.0) (distance 1.0) (reverb-amount 0.005)
</pre>

<p>gong is an FM instrument developed by Paul Weineke.
</p>

<pre class="indented">
Scheme:  (with-sound () (gong 0 3 261.61 .3))
Ruby:    with_sound() do gong(0, 3, 261.61, 0.6) end
</pre>

<div class="separator"></div>


<!-- gran-synth -->
<pre class="indented">
<em class=emdef>gran-synth</em> beg dur freq grain-dur grain-hop amp
</pre>

<p>gran-synth sets up a <a href="sndclm.html#wave-train">wave-train</a> playing an enveloped
sinusoid (the "grain" in this case).  'grain-dur' sets the grain's length (in seconds),
'grain-hop' sets the frequency of the <a href="sndclm.html#wave-train">wave-train</a> generator (how quickly the grain is
repeated), and 'freq' sets the grain sinusoid's frequency.
</p>

<pre class="indented">
(<a class=quiet href="#wsdoc">with-sound</a> () (gran-synth 0 1 300 .0189 .03 .4)) ; grain freq 300Hz, repetition rate 33Hz
</pre>

<div class="separator"></div>


<!-- main-index |grapheq:graphic equalizer -->
<!-- graphEq -->
<pre>
<A class=def>graphEq</A> file beg dur or-beg amp (amp-env '(0 1.0 0.8 1.0 1.0 0.0)) (amp-base 1.0) ...
</pre>

<p id="grapheq">graphEq is a sort of non-graphical graphical equalizer, developed by Marco Trevisani. It sets up a bank of formant
generators with an optional envelope on each formant, then filters and envelopes the input file.
Its trailing parameters are:
</p>

<pre class="indented">
(offset-gain 0)  
(gain-freq-list '((0 1 1 0) 440 (0 0 1 1) 660))      
(filt-gain-scale 1)                   
(filt-gain-base 1)                    
(a1 .99)
(stats #t)
</pre>


<p>'a1' is the formant radius.
'gain-freq-list' is a list of gains and frequencies to
filter
The gains can be either numbers or envelopes (one or the other, not a mixture).
'offset-gain' is an offset (addition) to all the gains.
'filt-gain-scale' and 'filt-gain-base' are similar, but apply to the envelopes, if any.
'stats' prints encouraging numbers if #t.
</p>

<pre class="indented">
(<a class=quiet href="#wsdoc">with-sound</a> () (graphEq "oboe.snd")) ; accept all the defaults (Scheme is case sensitive)
</pre>


<p>If we want just steady bands:
</p>

<pre class="indented">
(<a class=quiet href="#wsdoc">with-sound</a> () (graphEq "oboe.snd" 0 0 0 1.0 '(0 1 1 0) 1.0 0 '(.1 440 .3 1500 .2 330)))
</pre>

<div class="separator"></div>



<!-- hammondoid -->
<pre class="indented">
<em class=emdef>hammondoid</em> beg dur freq amp
</pre>

<p>hammondoid is Perry Cook's additive-synthesis Hammond organ.
</p>

<pre class="indented">
(<a class=quiet href="#wsdoc">with-sound</a> () (hammondoid 0 1 440 .1))
</pre>

<div class="separator"></div>



<!-- jl-reverb -->
<pre class="indented">
<em class=emdef>jl-reverb</em> (decay 3.0)
</pre>

<p>jl-reverb is a cavernous version of John Chowning's ancient reverberator.  You can never get enough reverb!
</p>

<pre class="indented">
(<a class=quiet href="#wsdoc">with-sound</a> (:reverb jl-reverb) (fm-violin 0 .1 440 .1 :reverb-amount .1))
</pre>


<p>'decay' is the reverb decay time tacked onto the end of the output sound.
To pass parameters to a reverberator, use the with-sound parameter :reverb-data.  So, if we want
5 seconds of decay:
</p>

<pre class="indented">
(<a class=quiet href="#wsdoc">with-sound</a> (:reverb jl-reverb :reverb-data '(5.0)) (fm-violin 0 .1 440 .1 :reverb-amount .1))
;;                                            ^ this is passed as (jl-reverb 5.0)
</pre>

<div class="separator"></div>



<!-- lbj-piano -->
<pre class="indented">
<em class=def id="lbjpiano">lbj-piano</em> beg dur freq amp (pfreq frequency) (degree 45) (reverb-amount 0) (distance 1)
</pre>

<p>lbj-piano, developed by Doug Fulton, uses James A Moorer's piano spectra and
additive synthesis to mimic a piano.
</p>

<pre class="indented">
(<a class=quiet href="#wsdoc">with-sound</a> () (lbj-piano 0 2 110.0 .2))
</pre>


<p>Doug says, "The high notes sound pretty rotten" and thinks perhaps
one major problem is the lack of mechanical noise.
'pfreq' sets which spectrum to use; it defaults to whatever matches 'freq'.
</p>

<pre class="indented">
(<a class=quiet href="#wsdoc">with-sound</a> () (lbj-piano 0 2 110.0 .2 :pfreq 550))
</pre>

<div class="separator"></div>



<!-- metal -->
<pre class="indented">
<em class=emdef>metal</em> beg dur freq amp
</pre>

<p>metal is another Perry Cook creation (HeavyMtl); it's an FM instrument:
</p>

<pre class="indented">
(<a class=quiet href="#wsdoc">with-sound</a> () (metal 0 1 440 .2))
</pre>

<div class="separator"></div>


<!-- nrev -->
<pre class="indented">
<em class=def id="nrev">nrev</em> (reverb-factor 1.09) (lp-coeff 0.7) (volume-1 1.0)
</pre>

<p>nrev, developed by Michael McNabb, is one of the more popular old-style reverbs. 
It is much cleaner than jc-reverb.
</p>

<pre class="indented">
(<a class=quiet href="#wsdoc">with-sound</a> (:reverb nrev) (fm-violin 0 .1 440 .1 :reverb-amount .1))
</pre>


<p>'reverb-factor' controls the length of the decay &mdash; it should not exceed 1.21 or so.
'lp-coeff' controls the strength of the low pass filter inserted in the feedback loop.
'volume-1' can be used to boost the reverb output.
</p>

<pre class="indented">
(<a class=quiet href="#wsdoc">with-sound</a> (:reverb nrev :reverb-data '(:lp-coeff 0.9 :volume-1 2.0)) 
  (fm-violin 0 .1 440 .1 :reverb-amount .1))
</pre>

<div class="separator"></div>



<!-- main-index |pins:SMS synthesis -->
<!-- pins -->
<pre class="indented">
<em class=def id="pins">pins</em> beg dur file amp ...
</pre>

<p>pins is a simple implementation of the spectral modeling synthesis
of Xavier Serra and Julius Smith (sometimes known as "Sansy" or "SMS").  See
Serra, X., J. O. Smith. 1990. "Spectral Modeling Synthesis:A Sound Analysis/Synthesis Based on a Deterministic plus Stochastic Decomposition". Computer Music Journal, vol. 14(4), 1990.
The idea behind SMS is similar to the phase vocoder,
but tracks spectral peaks so that its resynthesis options are much more sophisticated.
The trailing parameters are:
</p>

<pre class="indented">
(transposition 1.0) (time-scaler 1.0) (fft-size 256) 
     (highest-bin 128) (max-peaks 16) printit attack
</pre>

<p>'transposition' can be used to transpose a sound;
'time-scaler' changes the sound's duration;
'fft-size' may need to be larger if your sampling rate is 44100, or the input sound's
fundamental is below 300 Hz;
'highest-bin' sets how many fft bins we search for spectral peaks;
'max-peaks' sets how many peaks we track (at a maximum) through the sound;
'printit', if set to #t, causes the peak envelopes to be printied;
'attack' is an optional float-vector containing the attack portion of the new sound.
</p>

<pre class="indented">
Scheme:  (with-sound () (pins 0.0 1.0 "now.snd" 1.0 :time-scaler 2.0))
Ruby:    with_sound() do pins(0, 1, "now.snd", 1, :time_scaler, 2) end
</pre>

<p>Xavier has a website devoted to this system, but it seems to move; search for CLAM or SMS.
</p>

<div class="separator"></div>


<!-- pluck -->
<pre class="indented">
<em class=def id="pluck">pluck</em> beg dur freq amp (weighting .5) (lossfact .9)
</pre>
<p>
pluck is based on
the <A HREF="http://ccrma.stanford.edu/~jos/SimpleStrings/Karplus_Strong_Algorithm.html">Karplus-Strong</A> 
algorithm as extended by David Jaffe and Julius Smith &mdash; see 
Jaffe and Smith, "Extensions of the Karplus-Strong Plucked-String Algorithm"
CMJ vol 7 no 2 Summer 1983, reprinted in "The Music Machine".
The basic idea is to fill an array with noise, then filter the array values as it is played repeatedly,
giving a sharp attack and a ringing decay, much like plucking a guitar.  The CMJ article
gives many variations, changing pick position and so on.  Jaffe's "Silicon Valley Breakdown"
makes great use of this instrument.
'weighting' is the ratio of the once-delayed to the twice-delayed samples.  It defaults to .5 which gives a short decay;
anything other than .5 produces a longer decay.  It should be between 0.0 and 1.0. 
'lossfact' can be used to shorten decays.  The most useful values are between .8 and 1.0. 
</p>

<pre class="indented">
(<a class=quiet href="#wsdoc">with-sound</a> () 
  (pluck 0 1 330 .3 .95 .95) 
  (pluck .3 2 330 .3 .9 .9999) 
  (pluck .7 2 330 .3 .8 .99))
</pre>

<p>
In Ruby:
</p>

<pre class="indented">
with_sound() do pluck(0.05, 0.1, 330, 0.1, 0.95, 0.95) end
</pre>

<div class="separator"></div>



<!-- main-index |pqwvox:waveshaping voice -->
<!-- pqw-vox -->
<pre class="indented">
<em class=def id="pqwvox">pqw-vox</em> beg dur freq spacing-freq amp ampfun freqfun freqscl phonemes formant-amps formant-shapes
</pre>

<p>pqw-vox is an extension of Marc LeBrun's instrument vox (described below) to use phase-quadrature (single-sideband)
waveshaping.  It uses both Chebyshev polynomial kinds to set up spectra-producing pairs of waveshapers that will
add in such a way as to cancel either the upper or lower set of sidebands.  These are then ganged together as in
the vox instrument to mimic moving formants.
</p>

<pre class="indented">
(<a class=quiet href="#wsdoc">with-sound</a> () 
  (pqw-vox 0 1 300 300 .1 '(0 0 50 1 100 0) '(0 0 100 1) .3 '(0 L 100 L) '(.5 .25 .1) 
          '((1 1 2 .5) (1 .5 2 .5 3 1) (1 1 4 .5))))

(<a class=quiet href="#wsdoc">with-sound</a> ()
  (pqw-vox 0 2 200 200 .1 '(0 0 50 1 100 0) '(0 0 100 1) .1 '(0 UH 100 ER) '(.8 .15 .05) 
           '((1 1 2 .5) (1 1 2 .5 3 .2 4 .1) (1 1 3 .1 4 .5)))
  (pqw-vox 2 2 200 314 .1 '(0 0 50 1 100 0) '(0 0 100 1) .01 '(0 UH 100 ER) '(.8 .15 .05) 
           '((1 1 2 .5) (1 1 4 .1) (1 1 2 .1 4 .05)))
  (pqw-vox 4 2 100 414 .2 '(0 0 50 1 100 0) '(0 0 100 1) .01 '(0 OW 50 E 100 ER) '(.8 .15 .05) 
           '((1 1 2 .5 3 .1 4 .01) (1 1 4 .1) (1 1 2 .1 4 .05))))
</pre>

<div class="separator"></div>



<!-- pqw -->
<pre class="indented">
<em class=def id="pqw">pqw</em> beg dur freq spacing-freq carrier-freq amplitude ampfun indexfun partials ...
</pre>

<p>pqw is a phase-quadrature waveshaping instrument which produces asymmetric spectra.
The trailing parameters just set the usual degree, distance, and reverb values.
</p>

<pre class="indented">
(<a class=quiet href="#wsdoc">with-sound</a> () (pqw 0 .5 200 1000 .2 '(0 0 25 1 100 0) '(0 1 100 0) '(2 .1 3 .3 6 .5)))
</pre>

<p>To see the asymmetric spectrum most clearly, set the index function above to '(0 1 100 1).
</p>
<div class="separator"></div>



<!-- resflt -->
<pre class="indented">
<em class=emdef>resflt</em> beg dur driver ...
</pre>

<p>resflt, developed by Richard Karpen and Xavier Serra, sets up three resonators (two-pole filters), 
then drives them with either white noise or an <a href="sndclm.html#ncos">ncos</a> pulse train.
Both can be used for vocal effects:
</p>

<pre class="indented">
(<a class=quiet href="#wsdoc">with-sound</a> () 
  (resflt 0 1.0 0 0 0 #f .1 200 230 10 '(0 0 50 1 100 0) '(0 0 100 1) 
          500 .995 .1 1000 .995 .1 2000 .995 .1)
  (resflt 1 1.0 1 10000 .01 '(0 0 50 1 100 0) 0 0 0 0 #f #f 
          500 .995 .1 1000 .995 .1 2000 .995 .1))
</pre>


<p>The trailing parameters are:
</p>

<pre class="indented">
ranfreq noiamp noifun cosamp cosfreq1 cosfreq0 cosnum ampcosfun freqcosfun 
frq1 r1 g1 frq2 r2 g2 frq3 r3 g3
(degree 0.0) (distance 1.0)(reverb-amount 0.005)
</pre>


<p>Set 'driver' to 0 to get the pulse train, or to 1 to get white noise.
In the latter case, 'ranfreq' is the random number generator frequency, 'noiamp' is its amplitude,
and 'noifun' is an amplitude envelope on its output (filter input)
In the pulse case, 'cosamp' is the pulse train amplitude, 'ampcosfun' the amplitude envelope,
'cosfreq0' and 'cosfreq1' set the frequency limits of 'freqcosfun',
and 'cosnum' sets the number of cosines in the pulse.
The three resonators are centered at 'frq1', 'frq2', 'frq3',
with pole-radius 'r1', 'r2', and 'r3' respectively, and
with gains of 'g1', 'g2', and 'g3'.
</p>
<div class="separator"></div>


<!-- reson -->
<pre class="indented">
<em class=def id="reson">reson</em> beg dur freq amp ...
</pre>

<p>reson is a vocal simulator developed by John Chowning.  Its trailing parameters are:
</p>

<pre class="indented">
numformants indxfun skewfun pcskew skewat skewdc vibfreq vibpc ranvibfreq ranvibpc 
degree distance reverb-amount data

'data' is a list of lists of form 
  '(ampf resonfrq resonamp ampat ampdc dev0 dev1 indxat indxdc)
</pre>

<p>Needless to say, no one has ever written out these parameters by hand, so here's an all-time first:
</p>

<pre class="indented">
(<a class=quiet href="#wsdoc">with-sound</a> ()
  (reson 0.0 1.0 440 .1 2 '(0 0 100 1) '(0 0 100 1) .1 .1 .1 5 .01 5 .01 0 1.0 0.01
     '(((0 0 100 1) 1200 .5 .1 .1 0 1.0 .1 .1) ((0 1 100 0) 2400 .5 .1 .1 0 1.0 .1 .1))))
</pre>


<p>But JC got very nice vocal sounds from this &mdash; I must have mistyped somewhere...
Here's another stab at it:
</p>

<pre class="indented">
(<a class=quiet href="#wsdoc">with-sound</a> ()
      (reson 0.0 1.0 440 .1 2 '(0 1 100 0) '(0 0 100 1) .01 .1 .1 5 .01 5 .01 0 1.0 0.01
   	     '(((0 1 100 1) 1000 .65 .1 .1 0 1.0 .1 .1) ((0 0 100 1) 2400 .15 .1 .1 0 1.0 .1 .1))))
</pre>


<p>If you find a good example, please send me it!
</p>
<div class="separator"></div>


<!-- rhodey -->
<pre class="indented">
<em class=emdef>rhodey</em> beg dur freq amp (base .5)
</pre>

<p>rhodey is another of Perry Cook's instruments (an electric piano), based on a pair of FM generators.
</p>

<pre class="indented">
(<a class=quiet href="#wsdoc">with-sound</a> () (rhodey 0 1 440 .2))
</pre>

<p>One of the oscillators is set to a frequency 15 times the requested 'freq', so for higher notes, you'll need to set the srate higher:
</p>

<pre class="indented">
(<a class=quiet href="#wsdoc">with-sound</a> (:srate 44100) (rhodey 0 1 880 .2))
</pre>

<div class="separator"></div>



<!-- main-index |rmsgain:rms, gain, balance gens -->
<!-- rms gain balance -->
<pre class="indented">
<em class=def id="rmsgain">rms</em> gen sig
<em class=emdef>balance</em> gen sig comparison
<em class=emdef>gain</em> gen sig rsmval
<em class=emdef>make-rmsgain</em> (hp 10.0)
</pre>

<p>rms, balance, and gain are an implementation of the balance generators of CLM (based
on CSound originals, Scheme versions originally provided by Fabio Furlanete). 
This section is a paraphrase of balance.html in the CLM tarball which was
written by Sam Hiesz.
balance, rms, and gain are used to track the RMS value of a signal and use
that information to scale some other signal.  rms returns the RMS value;
gain takes a signal and an RMS value and modifies the signal to track the RMS
value; balance packages gain and rms into one function call.
make-rmsgain returns the generator used by rms, gain, and balance.
The 'hp' parameter sets the speed with which the balance process
tracks the RMS signal.  An example is worth a zillion words:
</p>

<pre class="indented">
  (<a class=quiet href="#wsdoc">with-sound</a> (:channels 3)
    (let ((rg (make-rmsgain))
          (rg1 (make-rmsgain 40))
          (rg2 (make-rmsgain 2))
          (e (<a class=quiet href="sndclm.html#make-env">make-env</a> '(0 0 1 1 2 0) :length 10000))
          (e1 (<a class=quiet href="sndclm.html#make-env">make-env</a> '(0 0 1 1) :length 10000))
          (e2 (<a class=quiet href="sndclm.html#make-env">make-env</a> '(0 0 1 1 2 0 10 0) :length 10000))
          (o (<a class=quiet href="sndclm.html#make-oscil">make-oscil</a> 440.0)))
      (do ((i 0 (+ i 1)))
          ((= i 10000))
        (let ((sig (<a class=quiet href="sndclm.html#env">env</a> e)))
          (<a class=quiet href="sndclm.html#outa">outa</a> i (balance rg sig (<a class=quiet href="sndclm.html#env">env</a> e2)))
          (<a class=quiet href="sndclm.html#outa">outb</a> i (balance rg1 sig (<a class=quiet href="sndclm.html#env">env</a> e1)))
          (<a class=quiet href="sndclm.html#outa">outc</a> i (balance rg2 (* .1 (<a class=quiet href="sndclm.html#oscil">oscil</a> o)) (<a class=quiet href="sndclm.html#env">env</a> e2)))))))
</pre>
<div class="separator"></div>



<!-- scratch -->
<pre class="indented">
<em class=def id="scratch">scratch</em> beg file src-ratio turnlist
</pre>

<p>scratch moves back and forth in a sound file according to
a list of turn times much like <a href="#envsoundinterp">env-sound-interp</a>.
With voice input, we can create a "Remembrance of Bugs Bunny":
</p>

<pre class="indented">
Scheme: (with-sound () (scratch 0.0 "now.snd" 1.5 '(0.0 .5 .25 1.0)))
Ruby:   with_sound() do scratch(0, "now.snd", 1.5, [0.0, 0.5, 0.25, 1.0]) end
</pre>


<p>I translate this as: "go forward from 0.0 to 0.5 secs, backwards to 0.25 secs, then forward to 1.0 secs".
</p>
<div class="separator"></div>


<!-- main-index |spectra:additive synthesis -->
<!-- spectra -->
<pre class="indented">
<em class=def id="spectra">spectra</em> beg dur freq amp ...
</pre>

<p>spectra is an additive-synthesis instrument with vibrato and an amplitude envelope.  It was intended originally
to be used with the spectra in spectra.scm (information laboriously gathered at the dawn of the computer era
by James A Moorer).  One such spectrum is labelled "p-a4", so we can hear it via:
</p>

<pre class="indented">
(load "spectr.scm")
(<a class=quiet href="#wsdoc">with-sound</a> () 
  (spectra 0 1 440.0 .1 p-a4 '(0.0 0.0 1.0 1.0 5.0 0.9 12.0 0.5 25.0 0.25 100.0 0.0)))
</pre>

<p>The trailing parameters are:
</p>

<pre class="indented">
 (partials '(1 1 2 0.5))
           (amp-envelope '(0 0 50 1 100 0))
           (vibrato-amplitude 0.005)
           (vibrato-speed 5.0)
           (degree 0.0)
           (distance 1.0)
           (reverb-amount 0.005)
</pre>


<p>We can pass our own partials:
</p>

<pre class="indented">
(<a class=quiet href="#wsdoc">with-sound</a> ()
  (spectra 0 1 440.0 .1 '(1.0 .4 2.0 .2 3.0 .2 4.0 .1 6.0 .1) 
           '(0.0 0.0 1.0 1.0 5.0 0.9 12.0 0.5 25.0 0.25 100.0 0.0)))
</pre>

<div class="separator"></div>



<!-- ssb-fm -->
<pre class="indented">
<em class=def id="ssbfm">ssb-fm</em> gen modsig
<em class=emdef>make-ssb-fm</em> freq
</pre>

<p>These two functions implement
a sort of asymmetric FM using ideas similar to those used in <a href="sndclm.html#ssb-am">ssb-am</a>.
</p>
<div class="separator"></div>



<!-- main-index |stereoflute:flute model -->
<!-- stereo-flute -->
<pre class="indented">
<em class=def id="stereoflute">stereo-flute</em> beg dur freq flow ...
</pre>

<p>This is a physical model of a flute developed by Nicky Hind.
</p>

<pre class="indented">
Scheme:
(with-sound (:channels 2) 
   (stereo-flute 0 1 440 0.55 :flow-envelope '(0 0 1 1 2 1 3 0))
   (stereo-flute 1 3 220 0.55 :flow-envelope '(0 0 1 1 2 1 3 0)))

Ruby:
with_sound() do stereo_flute(0, 2, 440, 0.55, :flow_envelope, [0, 0, 1, 1, 2, 1, 3, 0]) end
</pre>

<p>The trailing parameters are:
</p>

<pre class="indented">
(flow-envelope '(0 1 100 1))
     (decay 0.01) 		; additional time for instrument to decay
     (noise 0.0356) 
     (embouchure-size 0.5)
     (fbk-scl1 0.5)		; these two are crucial for good results
     (fbk-scl2 0.55)
     (offset-pos 0.764264)      ; from 0.0 to 1.0 along the bore
     (out-scl 1.0)
     (a0 0.7) (b1 -0.3)	        ; filter coefficients
     (vib-rate 5) 
     (vib-amount 0.03)
     (ran-rate 5) 
     (ran-amount 0.03)
</pre>

<p>As with physical models in general, you may need to experiment a bit to find
parameters that work.
</p>
<div class="separator"></div>



<!-- main-index |telephone:telephone -->
<!-- touch-tone -->
<pre class="indented">
<em class=def id="telephone">touch-tone</em> beg number
</pre>

<p>This instrument produces telephone tones:
</p>

<pre class="indented">
Scheme:  (with-sound () (touch-tone 0.0 '(7 2 3 4 9 7 1)))
Ruby:    with_sound() do touch_tone(0, [7, 2, 3, 4, 9, 7, 1]) end
</pre>

<p>It is just two sine waves whose frequencies are chosen based on the number pressed.
</p>

<pre class="indented">
  1     2     3   697 Hz
  4     5     6   770 Hz
  7     8     9   852 Hz
        0         941 Hz
 1209  1336  1477 Hz
</pre>


<p>For more than you really want to know about other such sounds, see
<A HREF="http://www.tech-faq.com/telephone-tone-frequencies.shtml">Telephone Tone Frequencies</A>.
</p>
<div class="separator"></div>



<!-- main-index |tubebell:tubular bell -->
<!-- tubebell -->
<pre class="indented">
<em class=def id="tubebell">tubebell</em> beg dur freq amp (base 32.0)
</pre>

<p>Perry Cook's tubular bell:
</p>

<pre class="indented">
(<a class=quiet href="#wsdoc">with-sound</a> () 
  (tubebell 0 2 440 .1 32.0) 
  (tubebell 2 2 220 .1 64.0) 
  (tubebell 4 2 660 .1 .032))
</pre>

<p>'base' is the envelope base:
</p>

<pre class="indented">
(<a class=quiet href="#wsdoc">with-sound</a> () 
  (tubebell 0 2 440 .1 32.0) 
  (tubebell 2 2 220 .1 2048.0) 
  (tubebell 4 3 660 .1 .032))
</pre>

<div class="separator"></div>



<!-- main-index |twotab:spectral interpolation -->
<!-- two-tab -->
<pre class="indented">
<em class=def id="twotab">two-tab</em> beg dur freq amp ...
</pre>

<p>two-tab interpolates between two spectra.
</p>

<pre class="indented">
(<a class=quiet href="#wsdoc">with-sound</a> () (two-tab 0 2 440 .1 '(1.0 1.0) '(3.0 1.0)))
;; go from harmonic 1 to harmonic 3
</pre>

<p>The trailing parameters are:
</p>

<pre class="indented">
(partial-1 '(1.0 1.0 2.0 0.5))
          (partial-2 '(1.0 0.0 3.0 1.0))
          (amp-envelope '(0 0 50 1 100 0))
          (interp-func '(0 1 100 0))
          (vibrato-amplitude 0.005)
          (vibrato-speed 5.0)
          (degree 0.0)
          (distance 1.0)
          (reverb-amount 0.005)
</pre>

<p>'interp-func' determines how we interpolate between the two spectra.  When
it is at 1.0, we get only the first, at 0.0 only the second.
</p>

<pre class="indented">
(<a class=quiet href="#wsdoc">with-sound</a> () (two-tab 0 2 440 .1 '(1.0 1.0) '(3.0 1.0) '(0 0 1 1 2 0) '(0 0 1 1)))
</pre>


<p>is the reverse of the earlier sound.  To go out and back:
</p>

<pre class="indented">
(<a class=quiet href="#wsdoc">with-sound</a> () (two-tab 0 2 440 .1 '(1.0 1.0) '(3.0 1.0) '(0 0 1 1 2 0) '(0 0 1 1 2 0)))
</pre>

<div class="separator"></div>



<!-- main-index |fmvox:fm-talker -->
<!-- vox -->
<pre class="indented">
<em class=def id="fmvox">vox</em> beg dur freq amp ampfun freqfun freqscl voxfun index vibscl
</pre>

<p>vox is a translation of Marc LeBrun's MUS10 waveshaping voice instrument
using FM in this case.  
The basic idea is that each of the three vocal formants is created by two
sets of waveshapers (or oscils producing FM), one centered on the even multiple of the base frequency closest to the desired formant frequency,
and the other on the nearest odd multiple.  As the base frequency moves (due to vibrato or glissando),
these center frequencies are recalculated on each sample, and the respective amplitudes
set to reflect the distance of the current center frequency from the desired formant frequency.  If a center frequency moves 
enough that the previous upper member of the pair has
to become the lower member, the upper waveshaper (which has meanwhile ramped to zero amplitude), jumps
down to its new center. The male-speaker formant table was provided by Robert Poor (see the code
for the complete table of formants).
For details on waveshaping, see Le Brun, "Digital Waveshaping Synthesis", JAES 1979 April, vol 27, no 4, p250.
I used vox in the 5th movement of "Colony" and in "The New Music Liberation Army".
</p>

<pre class="indented">
(<a class=quiet href="#wsdoc">with-sound</a> ()
  (let ((amp-env '(0 0 25 1 75 1 100 0))
        (frq-env '(0 0 5 .5 10 0 100 1)))
  (vox 0 2 170 .4 amp-env frq-env .1 
    '(0 E 25 AE 35 ER 65 ER 75 I 100 UH) '(.8 .15 .05) '(.005 .0125 .025) .05 .1)
  (vox 2 2 110 .4 amp-env frq-env .5 
    '(0 UH 25 UH 35 ER 65 ER 75 UH 100 UH) '(.8 .15 .05) '(.005 .0125 .025))
  (vox 4 2 300 .4 amp-env frq-env .1 
    '(0 I 5 OW 10 I 50 AE 100 OO) '(.8 .15 .05) '(.05 .0125 .025) .02 .1)))
</pre>

<p>Or in Ruby:
</p>

<pre class="indented">
with_sound() do
  amp_env = [0, 0, 25, 1, 75, 1, 100, 0]
  frq_env = [0, 0, 5, 0.5, 10, 0, 100, 1]
  vox(0, 2, 170, 0.4, amp_env, frq_env, 0.1, 
       [0, :E, 25, :AE, 35, :ER, 65, :ER, 75, :I, 100, :UH], 0.05, 0.1)
  vox(2, 2, 300, 0.4, amp_env, frq_env, 0.1, 
       [0, :I, 5, :OW, 10, :I, 50, :AE, 100, :OO], 0.02, 0.1)
  vox(4, 5, 600, 0.4, amp_env, frq_env, 0.1, 
       [0, :I, 5, :OW, 10, :I, 50, :AE, 100, :OO], 0.01, 0.1)
end
</pre>

<p>vox can also be use for less vocal effects:
</p>

<pre class="indented">
(<a class=quiet href="#wsdoc">with-sound</a> (:play #t :scaled-to .5)
  (vox 0 .25 500 .4 '(0 0 .1 1 1 1 2 .5 3 .25 10 0) '(0 0 5 .5 10 0 100 1) .1 
       '(0 E 25 OW 35 ER 105 ER) '(.13 .15 .15) '(.005 .005 .015) .05 .1))
</pre>

<div class="separator"></div>


<!-- wurley -->
<pre class="indented">
<em class=emdef>wurley</em> beg dur freq amp
</pre>

<p>Perry Cook's Wurlitzer (I assume).
</p>

<pre class="indented">
(<a class=quiet href="#wsdoc">with-sound</a> () (wurley 0 1 440 .1))
</pre>

<div class="separator"></div>



<!-- za, zc, zn -->
<pre class="indented">
<em class=emdef>za</em> time dur freq amp length1 length2 feedback feedforward
<em class=emdef>zc</em> time dur freq amp length1 length2 feedback
<em class=emdef>zn</em> time dur freq amp length1 length2 feedforward
</pre>

<p>The "z" instruments demonstrate "zdelay" effects &mdash; interpolating
<a href="sndclm.html#comb">comb</a>, <a href="sndclm.html#notch">notch</a>, and <a href="sndclm.html#all-pass">all-pass</a> filters.
</p>

<pre class="indented">
(<a class=quiet href="#wsdoc">with-sound</a> () (zn 0 1   100 .1 20 100 .995) 
  (zn 1.5 1 100 .1 100 20 .995)
  (zc 3 1   100 .1 20 100 .95) 
  (zc 4.5 1 100 .1 100 20 .95)
  (za 6 1   100 .1 20 100 .95 .95) 
  (za 7.5 1 100 .1 100 20 .95 .95))
</pre>

<div class="separator"></div>

<p>snd-test.scm has examples of calling all these instruments. 
</p>

<div class="seealso">
see also: &nbsp; <a href="#birddoc">bird</a> &nbsp; <a href="sndclm.html#sndclmtop">clm</a> &nbsp; <a href="#dlocsigdoc">dlocsig</a> &nbsp; <a href="#exampdoc">examp</a> &nbsp; <a href="#fadedoc">fade</a> &nbsp; <a href="fm.html#fmintro">fm</a> &nbsp; <a href="#vdoc">fmv</a> &nbsp; <a href="#freeverbdoc">freeverb</a> &nbsp; <a href="#grapheq">graphEq</a> &nbsp; <a href="#granidoc">grani</a> &nbsp; <a href="#jcrevdoc">jcrev</a> &nbsp; <a href="#maracadoc">maraca</a> &nbsp; 
          <a href="#maxfdoc">maxf</a> &nbsp; <a href="#noisedoc">noise</a> &nbsp; <a href="#pianodoc">piano</a> &nbsp; <a href="#prc95doc">prc95</a> &nbsp; <a href="#pvocdoc">pvoc</a> &nbsp; <a href="#singerdoc">singer</a> &nbsp; <a href="#sndwarpdoc">sndwarp</a> &nbsp; <a href="#stochasticdoc">stochastic</a> &nbsp; <a href="#straddoc">strad</a> &nbsp; <a href="#wsdoc">ws</a>
</div>



<!--  FILE: dlocsig  -->

<div class="header" id="dlocsigdoc">dlocsig</div>

<p id="dlocsig">dlocsig is a CLM generator developed by Fernando Lopez-Lezcano that can move sounds in two or three dimensions.
Fernando's CLM/lisp-oriented documentation can be found in
dlocsig.html.
dlocsig.rb is Michael Scholz's translation of dlocsig to Ruby.
It has lots of documentation and examples.  If you load dlocsig.rb, a new menu is added named "Dlocsig".
If you choose a path from this menu, you get a graphical user-interface to play with the various
envelopes that drive dlocsig.  Click the "With_Snd" button to apply the current path choices to the
currently selected sound.  Click "Gnuplot" to get a pretty picture of the path (in 3D!).
An instrument that uses dlocsig is:
</p>

<pre class="indented">
(define* (sinewave start-time duration freq amp (amp-env '(0 1 1 1))
		   (path (make-path :path '(-10 10 0 5 10 10))))
  (let ((vals (<em class=red>make-dlocsig</em> :start-time start-time :duration duration :path path)))
    (let ((dloc (car vals))
	  (beg (cadr vals))
	  (end (caddr vals)))
      (let ((osc (<a class=quiet href="sndclm.html#make-oscil">make-oscil</a> freq))
	    (aenv (<a class=quiet href="sndclm.html#make-env">make-env</a> amp-env :scaler amp :duration duration)))
        (do ((i beg (+ i 1)))
            ((= i end))
	  (<em class=red>dlocsig</em> dloc i (* (<a class=quiet href="sndclm.html#env">env</a> aenv) (<a class=quiet href="sndclm.html#oscil">oscil</a> osc))))))))

(<a class=quiet href="#wsdoc">with-sound</a> (:channels 2) (sinewave 0 1.0 440 .5 :path (make-path '((-10 10) (0.5 0.5) (10 10)) :3d #f)))
</pre>





<!--  FILE: draw  -->

<div class="header" id="drawdoc">draw</div>

<p>draw.scm has examples of graphics-oriented extensions.
</p>


<div class="spacer"></div>
<!-- color-samples -->
<pre class="indented">
<em class=emdef>color-samples</em> color beg dur snd chn
<em class=emdef>uncolor-samples</em> snd chn
</pre>

<p>
color-samples displays the samples from sample 'beg' for 'dur' samples in 'color'
whenever they're in the current time domain view. uncolor-samples cancels this action.
To activate this, add it to <a href="extsnd.html#aftergraphhook">after-graph-hook</a>.
</p>
<div class="spacer"></div>


<!-- display-previous-edits -->
<pre class="indented">
<em class=emdef>display-previous-edits</em> snd chn
</pre>

<p>
display-previous-edits displays all the edits of the current sound, with older edits gradually fading away.
To activate this, add it to <a href="extsnd.html#aftergraphhook">after-graph-hook</a>:
</p>

<pre class="indented">
(hook-push <a class=quiet href="extsnd.html#aftergraphhook">after-graph-hook</a> display-previous-edits)
</pre>

<div class="spacer"></div>


<!-- overlay-rms-env -->
<pre class="indented">
<em class=def id="overlayrmsenv">overlay-rms-env</em> snd chn
</pre>

<p>overlay-rms-env displays the running rms value of the currently displayed data in red, overlayed upon the 
normal graph. To activate it, add it to the <a href="extsnd.html#aftergraphhook">after-graph-hook</a>:
</p>

<pre class="indented">
(hook-push <a class=quiet href="extsnd.html#aftergraphhook">after-graph-hook</a> overlay-rms-env)
</pre>

<div class="spacer"></div>


<!-- overlay-sounds -->
<pre class="indented">
<em class=emdef>overlay-sounds</em> :rest sounds
</pre>

<p>overlay-sounds overlays onto its first argument (a sound) all subsequent arguments: (overlay-sounds 1 0 3).
</p>

<div class="spacer"></div>


<!-- samples-via-colormap -->
<pre class="indented">
<em class=emdef>samples-via-colormap</em> snd chn
</pre>

<p>samples-via-colormap displays the time domain graph using the current colormap (it is really just an example of 
<a href="extsnd.html#colormapref">colormap-ref</a>).  
To activate this, add it to <a href="extsnd.html#aftergraphhook">after-graph-hook</a>:
</p>

<pre class="indented">
(hook-push <a class=quiet href="extsnd.html#aftergraphhook">after-graph-hook</a> samples-via-colormap)
</pre>

<img class="indented" src="pix/samplesviacolormap.png" alt="samples-via-colormap">




<!--  FILE: dsp  -->

<div class="header" id="dspdoc">dsp</div>

<p>dsp.scm is a DSP grabbag, mostly filters.  There are more than 100 functions to describe here, so
an alphabetical list is just a jumble of names.  Instead, I've tried to divide them into several vague
categories: 
<a href="#dspdocfft">FFTs</a>, <a href="#dspdocfir">FIR filters</a>,
<a href="#dspdociir">IIR filters</a>, <a href="#dspdocgens">synthesis</a>,
<a href="#dspdoceffects">sound effects</a>, 
<a href="#dspdocsrc">sampling rate conversion</a>, 
<a href="#dspdocalgebra">linear algebra and stats</a>,
and <a href="#dspdocscanned">scanned synthesis</a>.
</p>


<div class="inset"><p>If you're new to DSP, I recommend Lyons' "Understanding Digital Signal Processing" and Steiglitz, "A
Digital Signal Processing Primer"; 
there are many good books
on advanced calculus &mdash; I especially liked Hildebrand, "Advanced Calculus for Applications", but it may
be out of print (this was about 25 years ago, I think); a great book on complex analysis is Needham, "Visual
Complex Analysis"; Poole's "Linear Algebra" is a very straightforward
introduction; also Halmos, "Linear Algebra Problem Book"; the most enjoyable
Fourier Analysis book is by K&ouml;rner, but you don't want to start with it.
For the ambitious, there is the encyclopedic set of books by Julius Smith.
His "Mathematics of the DFT" and "Introduction to Digital Filters" are very clear.
</p></div>




<!--  dsp FFT  -->

<div class="innerheader" id="dspdocfft">FFTs</div>


<!-- main-index |dht:Hartley transform -->
<!-- dht -->
<pre class="indented">
<em class=def id="dht">dht</em> data
</pre>

<p>dht is the slow form of the Hartley transform, 
taken from Perry Cook's SignalProcessor.m.
The Hartley transform is a kind of Fourier transform.
</p>
<div class="spacer"></div>

  
<!-- display-bark-fft -->
<pre class="indented">
<em class=def id="displaybarkfft">display-bark-fft</em> off color1 color2 color3
<em class=emdef>undisplay-bark-fft</em> 
</pre>

<p>display-bark-fft shows the current spectrum in the "lisp" graph in three
different frequency scales: bark, mel, and erb, each in a different color.
The default ticks follow the bark scale; click anywhere in the lisp graph
to switch to a different tick scale choice.  undisplay-bark-fft turns this
graph off. Here we've used rgb.scm for some color names:
</p>

<pre class="indented">
(display-bark-fft #f sea-green orange alice-blue)
(set! (<a class=quiet href="extsnd.html#selectedgraphcolor">selected-graph-color</a>) gray30)
(set! (<a class=quiet href="extsnd.html#selecteddatacolor">selected-data-color</a>) light-green)
</pre>

<img class="indented" src="pix/bark.png" alt="bark display">
<div class="spacer"></div>



<!-- dolph -->
<pre class="indented">
<em class=def id="dolph">dolph</em> n gamma
</pre>

<p>dolph is the Dolph-Chebyshev fft data window, taken
from Richard Lyons, "Understanding DSP".  The C version used by Snd/CLM is in clm.c.
Another version of the same function,
taken (with a few minor changes) from Julius Smith's "Spectral Audio", is named dolph-1.
</p>
<div class="spacer"></div>


<!-- down-oct and stretch-sound-via-dft -->
<pre class="indented">
<em class=def id="downoct">down-oct</em> n snd chn
<em class=def id="stretchsoundviadft">stretch-sound-via-dft</em> factor snd chn
</pre>

<p>down-oct 
tries to move a sound down by a factor of n (assumed to be a power of 2, 1 = no change) by goofing with the fft data,
then inverse ffting.  
I think this is "stretch" in DSP jargon; to interpolate in the time domain we're squeezing the frequency domain.
The power-of-2 limitation is based on the underlying fft function's insistence on power-of-2 data sizes.
A more general version of this is stretch-sound-via-dft, but it's
extremely slow.
</p>
<div class="spacer"></div>


<!-- goertzel and find-sine -->
<pre class="indented">
<em class=def id="goertzel">goertzel</em> freq beg dur snd
<em class=emdef>find-sine</em> freq beg dur snd
</pre>

<p>goertzel and find-sine find the amplitude of a single component of a spectrum ('freq').
</p>

<pre class="indented">
&gt; (find-sine 550.0 0.0 (framples))
(0.00116420908413177 0.834196665512423)   ; car is amplitude, cadr is phase in radians
&gt; (* (goertzel 550.0 0.0 (framples)) (/ 2.0 (framples)))
0.00116630805062827
</pre>

<div class="spacer"></div>


<!-- periodogram -->
<pre class="indented">
<em class=emdef>periodogram</em> N
</pre>

<p>periodogram (the "Bartlett" version, I think) runs over an entire file, piling up 'N' sized chunks of data,
then displays the results in the "lisp graph" area; this needs a lot of work to be useful!
</p>
<div class="spacer"></div>


<!-- scentroid -->
<pre class="indented">
<em class=def id="scentroid">scentroid</em> file (beg 0.0) dur (db-floor -40.0) (rfreq 100.0) (fftsize 4096)
</pre>
<p>scentroid is Brett Battey's CLM scentroid instrument, translated to Snd/Scheme.
To paraphrase Brett:
scentroid returns (in a float-vector) the continuous spectral centroid envelope of a sound.
The spectral centroid is the "center of gravity" of the spectrum, and it
has a rough correlation to our sense of "brightness" of a sound. 
'db-floor' sets a lower limit on which framples are included in the analysis.
'rfreq' sets the number of  measurements per second.
'fftsize' sets the fft window size (a power of 2).
See also the <a href="sndclm.html#moving-scentroid">moving-scentroid</a> generator in generators.scm.
</p>
<div class="spacer"></div>


<!-- spot-freq -->
<pre class="indented">
<em class=def id="spotfreq">spot-freq</em> samp snd chn
</pre>

<p>spot-freq is a first-pass at using autocorrelation for
pitch tracking; it's easily fooled, but could probably be made relatively robust.
</p>

<pre class="indented">
&gt; (spot-freq 10000)  ; this is oboe.snd, in about .5 secs
555.262096862931    ; 555Hz is correct(!)
</pre>

<p>In the next example, we add spot-freq to the <a href="extsnd.html#mouseclickhook">mouse-click-hook</a> (in Ruby),
so that each time we click somewhere in the graph, the pitch at that point is reported:
</p>

<pre class="indented">
$mouse_click_hook.add_hook!("examp-cursor-hook") do |snd, chn, button, state, x, y, axis|
  if axis == Time_graph
    status_report(format("(freq: %.3f)", spot_freq(cursor(snd, chn))))
  end
end
</pre>

<div class="spacer"></div>


<!-- rotate-phase and zero-phase -->
<pre class="indented">
<em class=emdef>rotate-phase</em> func snd chn
<em class=def id="zerophase">zero-phase</em> snd chn
</pre>

<p>These are fft phase manipulators taken from the phazor package of Scott McNab.
zero-phase takes ffts, sets all phases to 0.0, then unffts.  rotate-phase
is similar, but applies 'func' to the phases.
</p>

<pre class="indented">
(rotate-phase (lambda (x) 0.0))             ; same as (zero-phase)
(rotate-phase (lambda (x) (random 3.1415))) ; randomizes phases
(rotate-phase (lambda (x) x))               ; returns original
(rotate-phase (lambda (x) (- x)))           ; reverses original
</pre>

<p>or in Ruby:
</p>

<pre class="indented">
rotate_phase(lambda {|x| random(PI) })      # randomizes phases
</pre>

<p>and Forth:
</p>

<pre class="indented">
lambda: &lt;{ x }&gt; pi random ; #f #f rotate-phase \ randomizes phases
</pre>

<div class="spacer"></div>


<!-- z-transform and fractional-fourier-transform -->
<pre class="indented">
<em class=def id="ztransform">z-transform</em> rl size z
<em class=def id="fractionalfouriertransform">fractional-fourier-transform</em> rl im size angle
</pre>

<p>z-transform performs a z-transform returning a vector (to accommodate complex results):
</p>

<pre class="indented">
&gt; (define d0 (make-float-vector 8))
d0
;; and similarly for d1 and d2 ...
&gt; (set! (d0 2) 1.0)
1.0
&gt; (set! (d1 2) 1.0)
1.0
&gt; (z-transform d0 8 (exp (make-rectangular 0.0 (* .25 pi))))
;; Ruby: z_transform(d0, 8, exp(Complex(0.0, (2.0 / 8) * PI)))
#(1.0  0.0+1.0i  -1.0  0.0-1.0i  1.0  0.0+1.0i  -1.0  0.0-1.0i)
&gt; (mus-fft d1 d2 8)
#(1.0 0.0 -1.0 -0.0 1.0 0.0 -1.0 -0.0)
&gt; d2
#(0.0 1.0 0.0 -1.0 0.0 1.0 0.0 -1.0)
</pre>

<p>which is a complicated way of showing that if 'z' is e^2*pi*i/n, you get a fourier transform.
fractional-fourier-transform is the slow (DFT) version
of the fractional Fourier Transform. If 'angle' is 1.0, you get a fourier transform.
</p>




<!--  dsp FIR  -->

<div class="innerheader" id="dspdocfir">FIR filters</div>

<!-- FIR filters -->

<pre class="indented">
<em class=def id="makehighpass">make-highpass</em> fc length, <em class=emdef>highpass</em> f in
<em class=def id="makelowpass">make-lowpass</em> fc length, <em class=emdef>lowpass</em> f in
<em class=def id="makebandpass">make-bandpass</em> flo fhi length, <em class=emdef>bandpass</em> f in
<em class=def id="makebandstop">make-bandstop</em> flo fhi length, <em class=emdef>bandstop</em> f in
<em class=def id="makedifferentiator">make-differentiator</em> length, <em class=emdef>differentiator</em> f in
</pre>

<p>make-lowpass and lowpass provide FIR low pass filtering, and similarly for the other four choices.
The order chosen is twice the 'length'; 'fc', 'flo', and 'fhi' are
the edge frequencies in terms of srate = 2 * pi.
</p>

<pre class="indented">
(let ((hp (make-bandpass (* .1 pi) (* .2 pi))))
  (<a class=quiet href="extsnd.html#mapchannel">map-channel</a> (lambda (y)
    (bandpass hp y))))
</pre>

<div class="spacer"></div>


<!-- hilbert-transform -->
<pre class="indented">
<em class=def id="makehilberttransform">make-hilbert-transform</em> length
<em class=def id="hilberttransform">hilbert-transform</em> f in
<em class=emdef>hilbert-transform-via-fft</em> snd chn
<em class=def id="soundtoamp_env">sound-&gt;amp-env</em> snd chn
</pre>

<p>These functions perform the hilbert transform using either an FIR filter (the first two) or an FFT.
One example of its use is sound-&gt;amp-env (from R Lyons).  Another is the <a href="sndclm.html#ssb-am">ssb-am</a> generator in CLM.
</p>
<div class="spacer"></div>


<!-- invert-filter -->
<pre class="indented">
<em class=def id="invertfilter">invert-filter</em> coeffs
</pre>

<p>invert-filter inverts an FIR filter.
Say we previously filtered a sound via 
</p>

<pre class="indented">
(<a class=quiet href="extsnd.html#filterchannel">filter-channel</a> (float-vector .5 .25 .125))
</pre>

<p>and our mouse is broken so we can't use the Undo menu, and we've forgotten that
we could type (undo).  Nothing daunted, we use:
</p>

<pre class="indented">
(<a class=quiet href="extsnd.html#filterchannel">filter-channel</a> (invert-filter (float-vector .5 .25 .125)))
</pre>

<p>There are a million gotchas here.  The primary one is that the inverse filter
can "explode" &mdash; the coefficients can grow without bound.  For example, any
filter returned by <a href="#spectrumtocoeffs">spectrum-&gt;coeffs</a> will be problematic.
</p>
<div class="spacer"></div>


<!-- make-spencer-filter -->
<pre class="indented">
<em class=def id="makespencerfilter">make-spencer-filter</em>
</pre>

<p>This returns a CLM <a href="sndclm.html#fir-filter">fir-filter</a> generator with the standard "Spencer Filter" coefficients.
</p>
<div class="spacer"></div>


<!-- notch -->
<pre class="indented">
<em class=def id="notchsound">notch-sound</em> freqs order s c width
<em class=def id="notchchannel">notch-channel</em> freqs order beg dur s c e trunc width
<em class=def id="notchselection">notch-selection</em> freqs order width
</pre>

<p>notch-channel, notch-selection, and notch-sound are aimed at noise reduction.
Each takes a list of frequencies (in Hz), and an optional filter order, and
notches out each frequency.  The sharpness of the notch is settable
explicitly via the 'width' argument, and implicitly via the
filter 'order'.  A common application cancels 60 Hz hum:
</p>

<pre class="indented">
(notch-channel (do ((freqs ())
                    (i 60 (+ i 60))) 
                   ((= i 3000) 
                    (reverse freqs))
                 (set! freqs (cons i freqs))))
</pre>

<p>Here we've built a list of multiples of 60 and passed it to notch-channel. Its default notch
width is 2 Hz, and its default order tries to maintain that width given the channel's sampling rate,
so the default filter order can be very high (65536).  The filtering is normally done via
convolution (by CLM's convolve generator), so a high filter order is not a big deal.  In ideal
cases, this can reduce the hum and its harmonics by about 90%.
But, if the hum is not absolutely stable, you'll probably want wider notches:
</p>

<pre class="indented">
(notch-channel (do ((freqs ())
                    (i 60 (+ i 60))) 
                   ((= i 3000)
                    (reverse freqs))
                 (set! freqs (cons i freqs)))
                1024)
</pre>

<p>The order of 1024 means we get 20 Hz width minima (44100 Hz srate), so this
notches out much bigger chunks of the spectrum.  You get 98% cancellation, but
also lose more of the original signal.  
</p>
<div class="spacer"></div>


<!-- savitzky-golay-filter -->
<pre class="indented">
<em class=emdef>make-savitzky-golay-filter</em> size (order 2)
<em class=def id="sgfilter">savitzky-golay-filter</em> f in
</pre>

<p>This the Savitzky-Golay filter, assuming symmetrical positioning.  It is an FIR smoothing filter; 
perhaps it could be useful in noise reduction.
</p>

<pre class="indented">
(define (unnoise order)
  (let ((flt (make-savitzky-golay-filter order 2)))
    (<a class=quiet href="extsnd.html#mapchannel">map-channel</a> (lambda (y) (savitzky-golay-filter flt y)))))
</pre>

<p>
For more info on this filter, See "Numerical Recipes in C".
</p>
<div class="spacer"></div>



<!-- spectrum->coeffs and fltit -->
<pre class="indented">
<em class=def id="spectrumtocoeffs">spectrum-&gt;coeffs</em> order spectrum
<em class=emdef>fltit-1</em> order spectr
</pre>

<p>spectrum-&gt;coeffs is a
version of Snd's very simple spectrum-&gt;coefficients procedure ("frequency sampling").
It returns the FIR filter coefficients given the filter 'order' and desired 'spectrum' (a float-vector).
An example of its use is fltit-1.
</p>

<pre class="indented">
(<a class=quiet href="extsnd.html#mapchannel">map-channel</a> (fltit-1 10 (float-vector 0 1.0 0 0 0 0 0 0 1.0 0)))
</pre>

<div class="spacer"></div>


<!-- volterra-filter -->
<pre class="indented">
<em class=emdef>make-volterra-filter</em> acoeffs bcoeffs
<em class=def id="volterrafilter">volterra-filter</em> flt x
</pre>

<p>volterra-filter and
make-volterra-filter implement one form
of a common non-linear FIR filter.
This version is taken from Monson Hayes "Statistical DSP and Modeling";
it is a slight specialization of the form mentioned by J O Smith and others.
The 'acoeffs' apply to the linear terms, and the 'bcoeffs' to the quadratic.
</p>

<pre class="indented">
(let ((flt (make-volterra-filter (float-vector .5 .1) (float-vector .3 .2 .1))))
  (<a class=quiet href="extsnd.html#mapchannel">map-channel</a> (lambda (x) (volterra-filter flt x))))
</pre>



<!--  dsp IIR  -->
<div class="innerheader" id="dspdociir">IIR filters</div>

<!-- make-biquad -->
<pre class="indented">
<em class=def id="makebiquad">make-biquad</em> a0 a1 a2 b1 b2
</pre>

<p>make-biquad is a wrapper for <a href="sndclm.html#make-filter">make-filter</a>
to return a biquad filter section.
</p>
<div class="spacer"></div>


<!-- cascade->canonical -->
<pre class="indented">
<em class=def id="cascadetocanonical">cascade-&gt;canonical</em> coeffs
</pre>

<p>cascade-&gt;canonical 
converts cascade coefficients to canonical form (the form used by CLM's <a href="sndclm.html#filter">filter</a> generator).
'coeffs' is a list of filter coefficients; the function returns a float-vector, ready for
<a href="sndclm.html#make-filter">make-filter</a>.
</p>
<div class="spacer"></div>


<!-- kalman-filter-channel -->
<pre class="indented">
<em class=def id="kalmanfilterchannel">kalman-filter-channel</em> (Q 1.0e-5)
</pre>

<p>This is an experimental function aimed at noise reduction using a Kalman filter.
</p>
<div class="spacer"></div>


<!-- make-butter* -->
<pre class="indented">
<em class=emdef id="makebutter">make-butter-high-pass</em> fq, <em class=emdef>make-butter-hp</em> M fc
<em class=emdef>make-butter-low-pass</em> fq, <em class=emdef>make-butter-lp</em> M fc
<em class=emdef>make-butter-band-pass</em> fq bw, <em class=emdef>make-butter-bp</em> M f1 f2
<em class=emdef>make-butter-band-reject</em> fq bw, <em class=emdef>make-butter-bs</em> M f1 f2
</pre>

<p>These functions produce Butterworth filters, returning a CLM <a href="sndclm.html#filter">filter</a> generator.
The first named ones (make-butter-high-pass et al) are taken from Sam Heisz's CLM version
of Paris Smaragdis's Csound version of Charles Dodge's code from "Computer Music: synthesis, composition, and performance".
The second set (make-butter-lp et al) provide arbitrary order Butterworths.
'M' * 2 is the filter order, 'f1' and 'f2' are the band edges in Hz.
</p>

<pre class="indented">
(<a class=quiet href="extsnd.html#clmchannel">clm-channel</a> (make-butter-bp 3 1000 2000))
(<a class=quiet href="extsnd.html#filtersound">filter-sound</a> (make-butter-low-pass 500.0))
</pre>

<p>See also the notch filter in new-effects.scm, and of course <a href="#analogfilterdoc">analog-filter.scm</a>: the latter renders this section obsolete.
</p>
<div class="spacer"></div>


<!-- IIR filters -->
<pre class="indented">
<em class=emdef id="IIRfilters">make-iir-high-pass-2</em> fc din
<em class=emdef>make-iir-low-pass-2</em> fc din
<em class=emdef>make-iir-band-pass-2</em> f1 f2
<em class=emdef>make-iir-band-stop-2</em> f1 f2
<em class=emdef>make-eliminate-hum </em> (hum-freq 60.0) (hum-harmonics 5) (bandwidth 10)
<em class=emdef>make-peaking-2</em> f1 f2 m
</pre>

<p>More IIR filters.
</p>

<pre class="indented">
(map-channel (make-eliminate-hum))
</pre>

<p>make-peaking (a bandpass filter) returns a function suitable for map-channel (it takes one argument, the current sample,
and returns a sample):
</p>

<pre class="indented">
(<a class=quiet href="extsnd.html#mapchannel">map-channel</a> (make-peaking-2 500 1000 1.0))
</pre>

<p>In this case 'm' is the gain in the pass band.
Use the functions in <a href="#analogfilterdoc">analog-filter.scm</a>, rather than this group.
</p>





<!--  dsp generators  -->
<div class="innerheader" id="dspdocgens">synthesis</div>

<!-- cheby-hka -->
<pre class="indented">
<em class=def id="chebyhka">cheby-hka</em> k a coeffs
</pre>

<p>This returns the amplitude of the kth harmonic (0=DC) in the waveshaping output
given the index 'a', and harmonic coefficients 'coeffs' (the 0th element is DC amplitude).
</p>

<pre class="indented">
(<a class=quiet href="#wsdoc">with-sound</a> ()
  (let ((gen (<a class=quiet href="sndclm.html#make-polyshape">make-polyshape</a> 1000.0 :partials (list 1 .5  2 .25  3 .125  4 .125))))
    (do ((i 0 (+ i 1)))
        ((= i 88200))
      (<a class=quiet href="sndclm.html#outa">outa</a> i (* .5 (<a class=quiet href="sndclm.html#polyshape">polyshape</a> gen 0.25))))))
(<em class=red>cheby-hka</em> 1 0.25 (float-vector 0 .5 .25 .125 .125)) ; returns first partial (fundamental) amplitude
</pre>

<div class="spacer"></div>



<!-- flatten-partials -->
<pre class="indented">
<em class=def id="flattenpartials">flatten-partials</em> partials (tries 32)
</pre>

<p>flatten-partials takes a list or float-vector of partial numbers and amplitudes, as passed to <a href="sndclm.html#make-polywave">make-polywave</a>,
and tries to find an equivalent set of amplitudes that produces a less spikey waveform.  The difference is primarily one of loudness until
you have a lot of partials.
</p>
<div class="spacer"></div>



<!-- fm-parallel-component -->
<pre class="indented">
<em class=def id="fmparallelcomponent">fm-parallel-component</em> freq-we-want wc wms inds ns bs using-sine
<em class=emdef>fm-cascade-component</em> freq-we-want wc wm1 a wm2 b
<em class=emdef>fm-complex-component</em> freq-we-want wc wm a b interp sine ; "sine" arg currently ignored
</pre>

<p>This returns the amplitude of "freq-we-want" in parallel (complex) FM, where
"wc" is the carrier, "wms" is a list of modulator frequencies, "inds" is a list of the
corresponding indices, "ns" and "bs" are null (used internally), and using-sine is #t if
the modulators are set up to produce a spectrum of sines, as opposed to cosines (we
need to know whether to add or subtract the components that foldunder 0.0).
</p>

<pre class="indented">
(fm-parallel-component 200 2000.0 (list 2000.0 200.0) (list 0.5 1.0) () () #t)
</pre>

<p>To get the same information for FM with a complex index, use fm-compex-component:
(fm-compex-component 1200 1000 100 1.0 3.0 0.0 #f).
For cascade FM (two levels only), use fm-cascade-component.
</p>
<div class="spacer"></div>



<!-- ssb-bank -->
<pre class="indented">
<em class=def id="ssbbank">ssb-bank</em> old-freq new-freq pairs-1 (order 40) (bw 50.0) (beg 0) dur snd chn edpos
<em class=def id="ssbbankenv">ssb-bank-env</em> old-freq new-freq freq-env pairs-1 (order 40) (bw 50.0) (beg 0) dur snd chn edpos
<em class=emdef>shift-channel-pitch</em> freq (order 40) (beg 0) dur snd chn edpos
</pre>

<p>The 
ssb-bank functions provide single-sideband amplitude modulation, and pitch/time changes
based on the <a href="sndclm.html#ssb-am">ssb-am</a> generator.  
If you run ssb-am on some input signal, the signal is shifted in pitch by
the 'freq' amount.  The higher the 'order', the better the sideband cancellation
(amplitude modulation creates symmetrical sidebands, one of which is cancelled by the ssb-am
generator).  ssb-bank uses a bank of ssb-am generators, each with its own bandpass filter to
shift a sound's pitch without changing its duration;
the ssb-am generators do the pitch
shift, and the filters pick out successive harmonics,
so each harmonic gets shifted individually (i.e. harmonic relations are maintained despite the pitch shift).
For an oboe at 557 Hz, good values are:
(ssb-bank 557 new-freq 6 40 50).
For a person talking at ca. 150 Hz:
(ssb-bank 150 300 30 100 30) or
(ssb-bank 150 100 40 100 20).
To get a duration change without a pitch change, use this function
followed by sampling rate conversion back to the original pitch:
</p>

<pre class="indented">
(define (stretch-oboe factor)
  (ssb-bank 557 (* factor 557) 7 40 40)
  (<a class=quiet href="extsnd.html#srcsound">src-sound</a> (/ 1.0 factor)))
</pre>

<p>ssb-bank-env is the same as ssb-bank, but includes a frequency envelope:
(ssb-bank-env 557 880 '(0 0 1 100.0) 7).
shift-channel-pitch applies an <a href="sndclm.html#ssb-am">ssb-am</a> generator to a sound's channel (this
is a variant of amplitude modulation).
'freq' and 'order' are the corresponding arguments to <a href="sndclm.html#make-ssb-am">make-ssb-am</a>.
There is a dialog that runs ssb-bank in snd-motif.scm: create-ssb-dialog.
</p>
<div class="spacer"></div>


<!-- any-random -->
<pre class="indented">
<em class=def id="anyrandom">any-random</em> e
<em class=def id="gaussiandistribution">gaussian-distribution</em> s
<em class=emdef>pareto-distribution</em> a
<em class=emdef>gaussian-envelope</em> s
</pre>

<p>any-random provides the same output as <a href="sndclm.html#rand">rand</a> if the latter's
envelope (distribution function) argument is used, but using a slightly different method
to generate the numbers.  
gaussian-envelope makes a gaussian distribution envelope suitable for rand.
Also included is inverse-integrate, a version of
CLM's distribution-to-weighting function.
</p>

<pre class="indented">
(<a class=quiet href="extsnd.html#mapchannel">map-channel</a> (lambda (y) (any-random 1.0 '(0 1 1 1))))          ; uniform distribution
(<a class=quiet href="extsnd.html#mapchannel">map-channel</a> (lambda (y) (any-random 1.0 '(0 0 0.95 0.1 1 1)))) ; mostly toward 1.0
(let ((g (gaussian-distribution 1.0))) (<a class=quiet href="extsnd.html#mapchannel">map-channel</a> (lambda (y) (any-random 1.0 g))))
(let ((g (pareto-distribution 1.0))) (<a class=quiet href="extsnd.html#mapchannel">map-channel</a> (lambda (y) (any-random 1.0 g))))
</pre>

<p>In Ruby:
</p>

<pre class="indented">
map_channel(lambda do |y| any_random(1.0, [0, 1, 1, 1]))            # uniform distribution
map_channel(lambda do |y| any_random(1.0, [0, 0, 0.95, 0.1, 1, 1])) # mostly toward 1.0
let(gaussian-distribution(1.0)) do |g|  map_channel(lambda do |y| any_random(1.0, g)) end
let(pareto-distribution(1.0))   do |g| map_channel(lambda do |y| any_random(1.0, g)) end
</pre>




<!-- INDEX allrandomnumbers:Random Numbers -->

<TABLE class="method">
<tr><td class="methodtitle">Random Numbers in Snd/CLM</td></tr>
<tr><td>
<blockquote id="allrandomnumbers"><small>
generators, arbitrary distributions, fractals, 1/f: <a href="sndclm.html#randdoc">rand and rand-interp</a><br>
dithering: <a href="#ditherchannel">dither-channel</a>, <a href="#dithersound">dither-sound</a><br>
noise-making instrument: <a href="#noisedoc">noise.scm, noise.rb</a><br>
physical modeling of noisy instruments: <a href="#maracadoc">maraca.scm, maraca.rb</a><br>
arbitrary distribution via rejection method: <a href="#anyrandom">any-random</a><br>
s7: random, random-state: random number between 0 and arg<br>
Ruby: kernel_rand (alias for Ruby's rand), srand: random integer between 0 and arg, or float between 0 and 1<br>
<a href="sndclm.html#mus-random">mus-random, mus_random</a>: random float between -arg and arg<br>
mus-rand-seed (settable)<br>
bounded brownian noise: <a href="sndclm.html#green-noise">green-noise</a><br>
brown and pink noise: <a href="sndclm.html#brown-noise">brown-noise</a>
</small></blockquote>
</td></tr></TABLE>



<!--  dsp effects  -->
<div class="innerheader" id="dspdoceffects">effects</div>

<!-- adsat, freqdiv -->
<pre class="indented">
<em class=emdef>adsat</em> size beg dur snd chn
<em class=emdef>freqdiv</em> n snd chn
</pre>

<p>These two functions come from a package of effects developed by sed_sed@my-dejanews.com.
adsat is "adaptive saturation", and freqdiv is "frequency division".
(freqdiv n) repeats each nth sample 'n' times, clobbering the intermediate samples: (freqdiv 8).
It turns your sound into a bunch of square waves.
</p>
<div class="spacer"></div>


<!-- brighten-slightly -->
<pre class="indented">
<em class=emdef>brighten-slightly</em> amount snd chn
</pre>

<p>brighten-slightly is a slight simplification of <a href="sndclm.html#contrast-enhancement">contrast-enhancement</a>.
</p>

<div class="spacer"></div>


<!-- chordalize -->
<pre class="indented">
<em class=def id="chordalize">chordalize</em> 
</pre>

<p>chordalize uses harmonically-related comb-filters to bring out a chord in a sound.
The comb filters are controled by chordalize-amount (the default is .95),
chordalize-base (the default is 100 Hz), and chordalize-chord
(the default is (list 1 3/4 5/4)).  chordalize returns a function suitable
for map-channel:
</p>

<pre class="indented">
 (<a class=quiet href="extsnd.html#mapchannel">map-channel</a> (chordalize))
</pre>

<p>chordalize seems to work best with vocal sounds.
</p>
<div class="spacer"></div>


<!-- chorus -->
<pre class="indented">
<em class=def id="chorus">chorus</em>
</pre>

<p>chorus tries to produce the chorus sound effect, but it needs work.
It is controlled by the following variables:
</p>

<pre class="indented">
chorus-size (5)        ; number of flangers
chorus-time (.05)      ; scales delay line length (flanger)
chorus-amount (20.0)   ; amp of <a href="sndclm.html#rand-interp">rand-interp</a> (flanger)
chorus-speed (10.0)    ; freq of rand-interp (flanger)
</pre>

<div class="spacer"></div>


<!-- harmonicizer -->
<pre class="indented">
<em class=def id="harmonicizer">harmonicizer</em> freq coeffs pairs (order 40) (bw 50.0) (beg 0) dur snd chn edpos
</pre>

<p>harmonicizer splits a sound into separate sinusoids, then splits each resultant harmonic
into a set of harmonics, then reassembles the sound.  The basic idea is very similar to
<a href="#ssbbank">ssb-bank</a>, but harmonicizer splits harmonics, rather than pitch-shifting them.
The result can be a brighter or richer sound.
</p>

<pre class="indented">
(harmonicizer 550.0 (list 1 .5 2 .3 3 .2) 10)
</pre>

<p>'coeffs' is a list of harmonic-number and amplitude pairs, describing the spectrum
produced by each harmonic.  'pairs' controls how many bands are used to split the original sound.
'order' is the bandpass filter's order in each such pair, and 'bw' controls its bandwidth.
</p>
<div class="spacer"></div>


<!-- lpc-coeffs -->
<pre class="indented">
<em class=def id="lpccoeffs">lpc-coeffs</em> data n m
</pre>

<p>lpc-coeffs returns 'm' LPC coeffients (in a vector) given 'n' data points in the float-vector 'data'.
</p>
<div class="spacer"></div>


<!-- lpc-predict -->
<pre class="indented">
<em class=def id="lpcpredict">lpc-predict</em> data n coeffs m nf clipped
</pre>

<p>lpc-predict takes the output of lpc-coeffs ('coeffs') and the length thereof ('m'),
'n' data points 'data', and produces 'nf' new data points (in a float-vector) as its prediction.
If 'clipped' is #t, the new data is assumed to be outside -1.0 to 1.0.
</p>

<pre class="indented">
&gt; (lpc-predict (float-vector 0 1 2 3 4 5 6 7) 8 (lpc-coeffs (float-vector 0 1 2 3 4 5 6 7) 8 4) 4 2)
#(7.906 8.557)
</pre>

<div class="spacer"></div>


<!-- spike -->
<pre class="indented">
<em class=emdef>spike</em> snd chn
</pre>

<p>spike returns a product (rather than the more usual sum) of succesive samples, with the current sample's sign;
this normally produces a more spikey output.
The more successive samples we include in the product, the more we
limit the output to pulses placed at (just after) wave peaks.
In spike's case, just three samples are multiplied.
See also the <a href="#volterrafilter">volterra filter</a>.
</p>
<div class="spacer"></div>


<!-- unclip-channel -->
<pre class="indented">
<em class=def id="unclipchannel">unclip-channel</em> snd chn
</pre>

<p>unclip-channel tries to reconstruct clipped portions of a sound by using LPC to predict (backwards and forwards)
the lost samples. 
</p>
<div class="spacer"></div>


<!-- unclip-sound -->
<pre class="indented">
<em class=emdef>unclip-sound</em> snd
</pre>

<p>unclip-sound calls unclip-channel on each channel in the sound 'snd'.
</p>



<!--  dsp src  -->
<div class="innerheader" id="dspdocsrc">sampling rate conversion</div>

<!-- linear-src-channel -->
<pre class="indented">
<em class=def id="linearsrcchannel">linear-src-channel</em> srinc snd chn
</pre>

<p>linear-src-channel performs sampling rate conversion using linear interpolation;
this can sometimes be a nice effect.
</p>
<div class="spacer"></div>


<!-- src-duration -->
<pre class="indented">
<em class=def id="srcduration">src-duration</em> env
</pre>

<p>src-duration 
takes an envelope representing the
input (src change) to <a href="sndclm.html#src">src</a>, and returns the resultant sound
length.
</p>

<pre class="indented">
(src-duration '(0 1 1 2)) ; -&gt; 0.693147180559945
</pre>

<p>which means that if the original sound was 2 seconds long, and we apply the envelope '(0 1 1 2)
(via <a href="extsnd.html#srcchannel">src-channel</a>, for example) to that sound, the result will be
.693 * 2 seconds long.  To scale an src envelope to return a given duration, see src-fit-envelope below.
</p>
<div class="spacer"></div>


<!-- src-fit-envelope -->
<pre class="indented">
<em class=def id="srcfitenvelope">src-fit-envelope</em> env target-dur
</pre>

<p>src-fit-envelope returns a version of "env" scaled so that its duration as an src envelope is "target-dur".
</p>

<pre class="indented">
&gt; (src-duration (src-fit-envelope '(0 1 1 2) 2.0))
2.0
</pre>





<!--  dsp algebra  -->
<div class="innerheader" id="dspdocalgebra">stats, linear algebra, etc</div>

<!-- JOS -->
<pre class="indented">
<em class=emdef>channel-mean</em> snd chn                            ; &lt;f, 1&gt; / n
<em class=emdef>channel-total-energy</em> snd chn                    ; &lt;f, f&gt;
<em class=emdef>channel-average-power</em> snd chn                   ; &lt;f, f&gt; / n
<em class=emdef>channel-norm</em> snd chn                            ; sqrt(&lt;f, f&gt;)
<em class=def id="channelrms">channel-rms</em> snd chn                             ; sqrt(&lt;f, f&gt; / n)
<em class=emdef>channel-variance</em> snd chn                        ; &lt;f, f&gt; - ((&lt;f, 1&gt; / n) ^ 2) with quibbles
<em class=emdef>channel-lp</em> u-p snd chn              
<em class=emdef>channel-lp-inf</em> snd chn                          ; max abs f
<em class=emdef>channel2-inner-product</em> s1 c1 s2 c2              ; &lt;f, g&gt;
<em class=emdef>channel2-orthogonal?</em> s1 c1 s2 c2                ; &lt;f, g&gt; == 0
<em class=emdef>channel2-angle</em> s1 c1 s2 c2                      ; acos(&lt;f, g&gt; / (sqrt(&lt;f, f&gt;) * sqrt(&lt;g, g&gt;)))
<em class=emdef>channel2-coefficient-of-projection</em> s1 c1 s2 c2  ; &lt;f, g&gt; / &lt;f, f&gt;
<em class=emdef>channel-distance</em> (s1 0) (c1 0) (s2 1) (c2 0)    ; sqrt(&lt;f - g, f - g&gt;)
</pre>

<p>These functions are taken from (or at least inspired by) Julius Smith's "Mathematics of the
DFT".  Many are standard ways of describing a signal in statistics; others treat a signal
as a vector (channel-distance, for example, returns the Euclidean distance between two
sounds).  The 's1' and 's2' parameters refer to sound objects, and the 'c1' and 'c2'
parameters refer to channel numbers.
</p>
<div class="spacer"></div>


<!-- channel-polynomial -->
<pre class="indented">
<em class=def id="channelpolynomial">channel-polynomial</em> coeffs snd chn
<em class=def id="spectralpolynomial">spectral-polynomial</em> coeffs snd chn
<em class=def id="fvpolynomial">float-vector-polynomial</em> v coeffs
</pre>

<p>float-vector-polynomial returns the evaluation of the polynomial (given its coefficients) over an entire
float-vector, each element being treated as "x".  
channel-polynomial performs the same operation over
a sound channel.  
spectral-polynomial is similar, but operates in the frequency domain (each
multiply being a convolution).
</p>

<pre class="indented">
&gt; (float-vector-polynomial (float-vector 0.0 2.0) (float-vector 1.0 2.0)) ; x*2 + 1
#(1.0 5.0)
&gt; (channel-polynomial (float-vector 0.0 1.0 1.0 1.0)) ; x*x*x + x*x + x
</pre>

<p>The "constant" (0-th coefficient) term in spectral polynomial is treated as a dither amount (that is,
it has the given magnitude, but its phase is randomized, rather than being simple DC).
See also <a href="#polydoc">poly.scm</a>.
In channel-poynomial,
if you have an nth-order polynomial, the resultant spectrum is n times as wide as the original,
so aliasing is a possibility, and even powers create energy at 0Hz. 
</p>





<!--  scanned synthesis  -->
<div class="innerheader" id="dspdocscanned">scanned synthesis</div>

<!-- main-index |dspdocscanned:scanned synthesis -->
<!-- scanned synthesis -->
<pre class="indented">
<em class=def id="vibratinguniformcircularstring">vibrating-uniform-circular-string</em> size x0 x1 x2 mass xspring damp
<em class=emdef>vibrating-string</em> size x0 x1 x2 masses xsprings esprings damps haptics
</pre>

<p>These functions implement
scanned synthesis of Bill Verplank and Max Mathews.
To watch the wave, open some sound (so Snd has some place to put the graph), turn off
the time domain display (to give our graph all the window)
then
</p>

<pre class="indented">
(let ((size 128))
  (let ((x0 (make-float-vector size))	   
        (x1 (make-float-vector size))	   
        (x2 (make-float-vector size)))
    (do ((i 0 (+ i 1)))
        ((= i 12))
      (let ((val (sin (/ (* 2 pi i) 12.0))))
        (set! (x1 (- (+ i (/ size 4)) 6)) val)))
    (do ((i 0 (+ i 1)))
        ((= i 1024))
      (<em class=red>vibrating-uniform-circular-string</em> size x0 x1 x2 1.0 0.1 0.0)
      (<a class=quiet href="extsnd.html#graph">graph</a> x0 "string" 0 1.0 -10.0 10.0))))
</pre>




<!--  FILE: env  -->

<div class="header" id="envdoc">env</div>

<p>
env.scm provides a variety envelope functions.
An envelope in Snd/CLM is a list of breakpoint pairs.  In the function names, 
I try to remember to use "envelope" to be a list of breakpoints, and "env" to be the result of <a href="sndclm.html#make-env">make-env</a>,
a CLM env structure passed to the <a href="sndclm.html#env">env</a> generator.
In an envelope,
the x axis extent
is arbitrary, though it's simplest to use 0.0 to 1.0.
(In this file, envelopes are assumed to be flat lists, not float-vectors or lists of lists).
</p>


<div class="spacer"></div>
<!-- add-envelopes -->
<pre class="indented">
<em class=emdef>add-envelopes</em> env1 env2
</pre>
<p>add-envelopes adds two envelopes together:
</p>

<pre class="indented">
&gt; (add-envelopes '(0 0 1 1) '(0 0 1 1 2 0))
(0 0 1/2 3/2 1 1)  ; i.e. (0 0 1 1.5 2 1) in the second env's terms
</pre>

<div class="spacer"></div>


<!-- concatenate-envelopes -->
<pre class="indented">
<em class=def id="concatenateenvelopes">concatenate-envelopes</em> :rest envs
</pre>
<p>concatenate-envelopes concatenates its arguments:
</p>

<pre class="indented">
&gt; (concatenate-envelopes '(0 1 1 0) '(0 0 1 1))
(0.0 1 1.0 0 2.0 1)
</pre>

<div class="spacer"></div>


<!-- envelope-exp -->
<pre class="indented">
<em class=emdef>envelope-exp</em> e (power 1.0) (xgrid 100)
</pre>

<p>envelope-exp interpolates segments into envelope to approximate exponential curves.
</p>

<pre class="indented">
&gt; (<a class=quiet>format</a> #f "~{~,3F ~}" (envelope-exp '(0 0 1 1) 3.0 6))
"0.000 0.000 0.167 0.005 0.333 0.037 0.500 0.125 0.667 0.296 0.833 0.579 1.000 1.000 "
</pre>

<div class="spacer"></div>


<!-- envelope-last-x -->
<pre class="indented">
<em class=emdef>envelope-last-x</em> env
</pre>

<p>envelope-last-x returns the maximum x value:
</p>

<pre class="indented">
&gt; (envelope-last-x '(0 1 1 0 2 0))
2
</pre>

<div class="spacer"></div>


<!-- integrate-envelope -->
<pre class="indented">
<em class=def id="integrateenvelope">integrate-envelope</em> env
</pre>

<p>integrate-envelope returns the area under the envelope.
</p>

<pre class="indented">
&gt; (integrate-envelope '(0 0 1 1))
0.5
&gt; (integrate-envelope '(0 1 1 1))
1.0
&gt; (integrate-envelope '(0 0 1 1 2 .5))
1.25
</pre>

<div class="spacer"></div>


<!-- make-power-env -->
<pre class="indented">
<em class=emdef>make-power-env</em> e (scaler 1.0) (offset 0.0) duration
<em class=def id="powerenv">power-env</em> e
<em class=emdef>power-env-channel</em> pe (beg 0) snd chn edpos (edname "power-env-channel")
<em class=emdef id="powenvchannel">powenv-channel</em> envelope (beg 0) dur snd chn edpos
</pre>

<p>make-power-env and power-env implement an extension of exponential
envelopes; each segment has its own base.  power-env-channel uses the same
mechanism as an extension of env-channel.
</p>

<pre class="indented">
(let ((pe (make-power-env '(0 0 32.0  1 1 0.0312  2 0 1) :duration 1.0)))
  (<a class=quiet href="extsnd.html#mapchannel">map-channel</a> (lambda (y) (* y (power-env pe)))))

(let ((pe1 (make-power-env '(0 0 32.0  1 1 0.0312  2 0 1.0  3 .5 3.0  4 0 0) :duration 1.0)))
  (power-env-channel pe1))
</pre>

<p>powenv-channel is a simplification of power-env-channel; it takes a breakpoint list rather
than a power-env structure: 
</p>

<pre class="indented">
(powenv-channel '(0 0 .325  1 1 32.0 2 0 32.0))
</pre>

<div class="spacer"></div>


<!-- map-envelopes -->
<pre class="indented">
<em class=emdef>map-envelopes</em> func env1 env2
</pre>

<p>map-envelopes applies 'func' to the breakpoints in the two
envelope arguments, returning a new envelope.
</p>

<pre class="indented">
&gt; (map-envelopes + '(0 0 1 1 2 0) '(0 1 2 0))
(0 1 1/2 3/2 1 0)  ; i.e. '(0 1 1 1.5 2 0) in the original x-axis bounds
</pre>

<div class="spacer"></div>


<!-- max-envelope -->
<pre class="indented">
<em class=emdef>min-envelope</em> env
<em class=def id="maxenvelope">max-envelope</em> env
</pre>

<p>max-envelope returns the maximum y value in 'env', and min-envelope returns the minimum y value:
</p>

<pre class="indented">
&gt; (max-envelope '(0 0 1 1 2 3 4 0))
3.0
</pre>

<div class="spacer"></div>


<!-- multiply-envelopes -->
<pre class="indented">
<em class=emdef>multiply-envelopes</em> env1 env2
</pre>

<p>multiply-envelopes uses map-envelopes to multiply two envelopes:
</p>

<pre class="indented">
Scheme:
&gt; (multiply-envelopes '(0 0 1 1) '(0 0 1 1 2 0))
(0 0 0.5 0.5 1 0)

Ruby:
&gt; multiply_envelopes([0, 0, 1, 1], [0, 0, 1, 1, 2, 0])
[0.0, 0.0, 0.5, 0.5, 1.0, 0.0]
 
Forth:
snd&gt; '( 0e 0e 1.0 1.0 ) '( 0e 0e 1.0 1.0 2.0 0.0 ) multiply-envelopes
'( 0.0 0.0 0.5 0.5 1.0 0.0 )
</pre>

<p>The new envelope goes from 0.0 to 1.0 along
the X axis; the multiplied envelopes are stretched or contracted to
fit 0.0 to 1.0, and wherever one has a breakpoint, the corresponding
point in the other envelope is interpolated, if necessary.
</p>
<div class="spacer"></div>


<!-- normalize-envelope -->
<pre class="indented">
<em class=def id="normalizeenvelope">normalize-envelope</em> env (new-max 1.0)
</pre>

<p>normalize-envelope returns a version of 'env' scaled so that its maximum y value is 'new-max'.
</p>

<pre class="indented">
&gt; (normalize-envelope '(0 0 1 1 2 3 4 0) .5)
(0 0.0 1 0.167 2 0.5 4 0.0)
</pre>

<div class="spacer"></div>



<!-- repeat-envelope -->
<pre class="indented">
<em class=emdef>repeat-envelope</em> env repeats reflected normalized
</pre>

<p>repeat-envelope repeats an envelope (concatenates copies of itself).
It's usually easier to use <a href="sndclm.html#mus-reset">mus-reset</a> to restart an envelope over and over (see <a href="sndclm.html#pulsedenv">pulsed-env</a>).
</p>

<pre class="indented">
&gt; (repeat-envelope '(0 0 .1 .9 1 1 1.3 .2 2 0) 2)
(0 0 0.1 0.9 1.0 1 1.3 0.2 2.0 0 2.1 0.9 3.0 1 3.3 0.2 4.0 0)
</pre>

<img class="indented" src="pix/repenv.png" alt="repeated envelope">


<p>If the final y value is different from the first y value (as above), a quick ramp is
inserted between repeats. 'normalized' causes the new envelope's x axis
to have the same extent as the original's. 'reflected' causes every other
repetition to be in reverse.
</p>
<div class="spacer"></div>



<!-- reverse-envelope -->
<pre class="indented">
<em class=def id="reverseenvelope">reverse-envelope</em> env
</pre>

<p>reverse-envelope reverses an envelope.
</p>

<pre class="indented">
&gt; (reverse-envelope '(0 0 1 1 2 1))
(0 1 1 1 2 0)
</pre>

<div class="spacer"></div>



<!-- rms-envelope -->
<pre class="indented">
<em class=def id="rmsenvelope">rms-envelope</em> file (beg 0.0) dur (rfreq 30.0) db
</pre>

<p>rms-envelope returns an rms envelope of a file; it is based on rmsenv.ins in the CLM package.
</p>

<pre class="indented">
&gt; (<a class=quiet>format</a> #f "~{~,3F ~}" (rms-envelope "1a.snd"))
"0.000 0.049 0.033 0.069 0.067 0.049 0.100 0.000 0.133 0.000 0.167 0.000 0.200 0.000 "
</pre>

<div class="spacer"></div>



<!-- scale-envelope -->
<pre class="indented">
<em class=def id="scaleenvelope">scale-envelope</em> env scl (offset 0.0)
</pre>

<p>scale-envelope scales the y values of an envelope by 'scl', and optionally adds 'offset'.
</p>
<div class="spacer"></div>


<!-- stretch-envelope -->
<pre class="indented">
<em class=def id="stretchenvelope">stretch-envelope</em> env old-attack new-attack (old-decay #f) (new-decay #f)
</pre>

<p>stretch-envelope applies attack and optionally decay times
to an envelope, much like divseg in clm-1.
</p>

<pre class="indented">
&gt; (stretch-envelope '(0 0 1 1) .1 .2)
(0 0 0.2 0.1 1.0 1)
&gt; (stretch-envelope '(0 0 1 1 2 0) .1 .2 1.5 1.6)
(0 0 0.2 0.1 1.1 1 1.6 0.5 2.0 0)
</pre>

<div class="spacer"></div>


<!-- window-envelope -->
<pre class="indented">
<em class=emdef>window-envelope</em> beg end env
</pre>

<p>window-envelope returns (as an envelope) the portion of its envelope argument that lies
between the x axis values 'beg' and 'end'.  This is useful when you're treating an
envelope as a phrase-level control, applying successive portions of it to many underlying
notes.
</p>

<pre class="indented">
&gt; (window-envelope 1.0 3.0 '(0.0 0.0 5.0 1.0))
(1.0 0.2 3.0 0.6)
</pre>



<div class="seealso">
see also: &nbsp; <a href="sndclm.html#envdoc">make-env</a> &nbsp; <a href="extsnd.html#envchannel">env-channel</a> &nbsp; <a href="snd.html#editenvelope">Enved</a> &nbsp; <a href="#envexptchannel">env-expt-channel</a>
</div>




<!--  FILE: enved  -->

<div class="header" id="enveddoc">enved, xm-enved</div>

<p>enved.scm implements an independent envelope editor in each channel.  
</p>

<pre class="indented">
<em class=emdef>start-enveloping</em> 
<em class=emdef>stop-enveloping</em> 
<em class=def id="channelenvelope">channel-envelope</em> snd chn
<em class=def id="playwithenvs">play-with-envs</em> snd
</pre>

<p>
(start-enveloping) opens an envelope editor for each subsequently opened sound.
(stop-enveloping) turns this off.
Each envelope can be read or written via (channel-envelope snd chn).
An example use is play-with-envs which
sets the channel's amplitude from its envelope
during playback 
</p>

<img class="indented" src="pix/envs.png" alt="channel enveds">

<div class="spacer"></div>

<p>
Closely related to this is xm-enved.scm which implements a separate envelope editor widget.
</p>

<pre class="indented">
<em class=emdef>xe-create-enved</em> name parent args axis
<em class=emdef>xe-envelope</em> xe-editor
</pre>

<p>
xe-create-enved returns a new envelope editor whose x axis label is 'name', the x and y axis bounds
are in the list 'axis', the editor's parent widget is 'parent',  and the Xt-style
resource argument list is 'args'.  The editor's current envelope is accessible
as 'xe-envelope'.
</p>



<div class="seealso">
see also: &nbsp; <a href="sndclm.html#envdoc">make-env</a> &nbsp; <a href="extsnd.html#envchannel">env-channel</a> &nbsp; <a href="snd.html#editenvelope">Enved</a> &nbsp; <a href="#envdoc">functions</a> &nbsp; <a href="#envexptchannel">env-expt-channel</a>
</div>



<!--  FILE: examp  -->

<div class="header" id="exampdoc">examp</div>

<p>examp.scm has become a bit of a mess; rather than get organized, I just
appended new stuff as it came to mind.  In this documentation, I'll divide the functions into the following non-orthogonal categories:
<a href="#ssffts">ffts</a>,
<a href="#ssfilters">filters</a>,
<a href="#sseffects">sound effects</a>,
<a href="#ssmarks">marks</a>,
<a href="#ssselections">selections</a>,
<a href="#ssgraphics">graphics</a>, and
<a href="#ssmisc">miscellaneous stuff</a>
</p>


<!--  examp FFTS  -->

<div class="innerheader" id="ssffts">FFTs</div>

<!-- display-correlation -->
<pre class="indented">
<em class=def id="displaycorrelation">display-correlation</em> snd chn y0 y1
</pre>

<p>display-correlation graphs the correlation of the 2 channels of the sound 'snd'.
To make this happen automatically as you move the time domain position
slider: (hook-push <a class=quiet href="extsnd.html#graphhook">graph-hook</a> display-correlation).
The last three parameters are unused; they are just for compatibility with graph-hook.
</p>
<div class="spacer"></div>


<!-- fft-cancel -->
<pre class="indented">
<em class=def id="fftcancel">fft-cancel</em> lo-freq hi-freq snd chn
</pre>

<p>fft-cancel ffts an entire channel, zeroes the bins between 'lo-freq' and 'hi-freq' (in Hz), then inverse ffts,
giving a good notch filter.
</p>

<pre class="indented">
(fft-cancel 500 1000)  ; squelch frequencies between 500 and 1000 Hz
</pre>

<div class="spacer"></div>


<!-- fft-edit -->
<pre class="indented">
<em class=def id="fftedit">fft-edit</em> low-freq high-freq snd chn
</pre>

<p>fft-edit takes an fft of the entire sound, removes all energy below 'low-freq' and above 'high-freq' (in Hz),
then inverse fft's.  This is the complement of fft-cancel.
</p>
<div class="spacer"></div>


<!-- fft-env-edit -->
<pre class="indented">
<em class=def id="fftenvedit">fft-env-edit</em> env snd chn
</pre>

<p>fft-env-edit is similar to fft-edit, but applies an envelope to the spectral magnitudes.
</p>

<pre class="indented">
(fft-env-edit '(0 0 .1 1 .2 1 .3 0 .5 1 1.0 0)) ; 1.0 = srate / 2 here
</pre>

<div class="spacer"></div>


<!-- fft-env-interp -->
<pre class="indented">
<em class=def id="fftenvinterp">fft-env-interp</em> env1 env2 interp snd chn
</pre>

<p>fft-env-interp performs fft-env-edit twice (using 'env1' and 'env2'), then mixes the two results following the interpolation
envelope 'interp'.
</p>
<div class="spacer"></div>


<!-- fft-peak -->
<pre class="indented">
<em class=emdef>fft-peak</em> snd chn scale
</pre>

<p>fft-peak is an <a href="extsnd.html#aftertransformhook">after-transform-hook</a> function that reports the peak spectral magnitude in the status area.
</p>

<pre class="indented">
Scheme: (hook-push <a class=quiet href="extsnd.html#aftertransformhook">after-transform-hook</a> fft-peak)

Ruby:   $after_transform_hook.add_hook!(\"fft-peak\") do |snd, chn, scale|
          fft_peak(snd, chn, scale)
        end
</pre>

<p>This can be helpful if you're scanning a sound with the fft graph displayed; since it normalizes
to 1.0 (to keep the graph from jumping around simply because the amplitude is changing), it's nice to know what the current peak
actually represents.  You can, of course, turn off the normalization:
</p>

<pre class="indented">
(set! (<a class=quiet href="extsnd.html#normalizefft">transform-normalization</a>) dont-normalize)
</pre>

<div class="spacer"></div>


<!-- fft-smoother -->
<pre class="indented">
<em class=def id="fftsmoother">fft-smoother</em> cutoff start samps snd chn
</pre>

<p>fft-smoother uses fft filtering to
smooth a portion of a sound, returning a float-vector with the smoothed data.  'cutoff' sets where we starting zeroing out high frequencies.
</p>

<pre class="indented">
Scheme: (float-vector-&gt;channel (fft-smoother .1 (<a class=quiet href="extsnd.html#cursor">cursor</a>) 400 0 0) (<a class=quiet href="extsnd.html#cursor">cursor</a>) 400)
Ruby:   vct2channel(fft_smoother(0.1, cursor, 400, 0, 0), cursor, 400)
</pre>

<div class="spacer"></div>


<!-- fft-squelch -->
<pre class="indented">
<em class=def id="fftsquelch">fft-squelch</em> squelch snd chn
</pre>

<p>fft-squelch is similar to fft-edit; any fft bin whose (normalized) magnitude is below 'squelch' is set to 0.0.
This is sometimes useful for noise-reduction.
</p>
<div class="spacer"></div>


<!-- filter-fft -->
<pre class="indented">
<em class=def id="filterfft">filter-fft</em> func (normalize #t) snd chn
</pre>

<p>
This a sort of generalization of the preceding functions.  It gets the spectrum of all the data in the given channel,
applies the function 'func' to each element of the spectrum, then inverse ffts.  'func' should take one argument, the
current spectrum value.  
</p>

<pre class="indented">
(define brfft
  (let ((+documentation+ "(brfft lofrq hifrq) removes all frequencies between lofrq and hifrq: (brfft 1000.0 2000.0)"))
    (lambda (lofrq hifrq)
      (let* ((fsize (let ((len (<a class=quiet href="extsnd.html#framples">framples</a>)))
                      (expt 2 (ceiling (log len 2)))))
	     (ctr -1)
	     (lo (round (/ (* fsize lofrq) (<a class=quiet href="extsnd.html#srate">srate</a>))))
	     (hi (round (/ (* fsize hifrq) (<a class=quiet href="extsnd.html#srate">srate</a>)))))
        (<em class=red>filter-fft</em> (lambda (y)
		      (set! ctr (+ 1 ctr))
		      (if (&gt;= hi ctr lo)
		          0.0
		          y)))))))
</pre>

<p>Here are some sillier examples...
</p>


<pre class="indented">
(filter-fft (<a class=quiet href="sndclm.html#make-one-zero">make-one-zero</a> .5 .5))
(filter-fft (<a class=quiet href="sndclm.html#make-one-pole">make-one-pole</a> .05 .95))
(filter-fft (lambda (y) (if (&lt; y .1) 0.0 y))) ; like fft-squelch
(let ((rd (<a class=quiet href="extsnd.html#makesampler">make-sampler</a> 0 0 0 1 0))) 
  (<a class=quiet href="extsnd.html#scaleby">scale-by</a> 0) 
  (filter-fft (lambda (y) (rd))))             ; treat sound as spectrum
(filter-fft <a class=quiet href="sndclm.html#contrast-enhancement">contrast-enhancement</a>)
(filter-fft (lambda (y) (* y y y)))           ; extreme low pass
</pre>

<div class="spacer"></div>


<!-- squelch-vowels -->
<pre class="indented">
<em class=def id="squelchvowels">squelch-vowels</em> snd chn
</pre>

<p>squelch-vowels uses fft data to try to distinguish a steady state portion (a vowel in speech) from
noise (a consonant, sometimes), then tries to remove (set to 0.0) the vowel-like portions.
</p>
<div class="spacer"></div>


<!-- superimpose-ffts -->
<pre class="indented">
<em class=def id="superimposeffts">superimpose-ffts</em> snd chn y0 y1
</pre>

<p>superimpose-ffts is a graph-hook function that
superimposes the ffts of multiple (sync'd) sounds.
(hook-push <a class=quiet href="extsnd.html#graphhook">graph-hook</a> superimpose-ffts)
This function needs some work...
</p>
<div class="spacer"></div>


<!-- zoom-spectrum -->
<pre class="indented">
<em class=emdef>zoom-spectrum</em> snd chn y0 y1
</pre>

<p>zoom-spectrum sets the transform size to correspond to the time-domain window size.
(hook-push <a class=quiet href="extsnd.html#graphhook">graph-hook</a> zoom-spectrum).
</p>




<!--  examp FILTERS  -->

<div class="innerheader" id="ssfilters">filters</div>

<!-- comb-filter -->
<pre class="indented">
<em class=emdef>comb-filter</em> scaler size
<em class=emdef>zcomb</em> scaler size pm
</pre>

<p>comb-filter is an example of using the CLM <a href="sndclm.html#comb">comb</a> generator.
</p>

<pre class="indented">
Scheme:  (<a class=quiet href="extsnd.html#mapchannel">map-channel</a> (comb-filter .8 32))
Ruby:    map_channel(comb_filter(0.8, 32))
Forth:   0.8 32 comb-filter-1 map-channel
</pre>

<p>it would be faster to use the comb filter directly:
</p>

<pre class="indented">
(<a class=quiet href="extsnd.html#clmchannel">clm-channel</a> (<a class=quiet href="sndclm.html#make-comb">make-comb</a> .8 32))
</pre>

<p>zcomb is a time-varying comb
filter using the envelope 'pm' (the envelope is applied to the comb filter delay length).
</p>

<pre class="indented">
(<a class=quiet href="extsnd.html#mapchannel">map-channel</a> (zcomb .8 32 '(0 0 1 10)))
</pre>

<div class="spacer"></div>


<!-- comb-chord -->
<pre class="indented">
<em class=emdef>comb-chord</em> scaler size amp
</pre>

<p>comb-chord uses comb filters at harmonically
related sizes to create a chord (see also <a href="#chordalize">chordalize</a> in dsp.scm).
'amp' is an overall amplitude scaler.
</p>

<pre class="indented">
(<a class=quiet href="extsnd.html#mapchannel">map-channel</a> (comb-chord .95 100 .3))
(<a class=quiet href="extsnd.html#mapchannel">map-channel</a> (comb-chord .95 60 .3))
</pre>

<div class="spacer"></div>


<!-- filtered-env -->
<pre class="indented">
<em class=emdef>filtered-env</em> e snd chn
</pre>

<p>filtered-env takes an amplitude envelope 'e' and creates a one-pole
filter, and moves them in parallel over a sound; 
as the sound gets softer, the low-pass filter's cutoff frequency
gets lower, a sort of poor-man's distance effect.  When 'e'
is at 1.0, no filtering takes place.
</p>

<pre class="indented">
(filtered-env '(0 1 1 0)) ; fade out
</pre>

<div class="spacer"></div>


<!-- formant-filter -->
<pre class="indented">
<em class=emdef>formant-filter</em> radius frequency
</pre>

<p>formant-filter applies a formant to its input.
</p>

<pre class="indented">
(<a class=quiet href="extsnd.html#mapchannel">map-channel</a> (formant-filter .99 2400))
</pre>

<p>It's probably faster to use the CLM filter directly:
</p>

<pre class="indented">
(<a class=quiet href="extsnd.html#filtersound">filter-sound</a> (<a class=quiet href="sndclm.html#make-formant">make-formant</a> 2400 .99))
</pre>

<div class="spacer"></div>


<!-- formants -->
<pre class="indented">
<em class=emdef>formants</em> r1 f1 r2 f2 r3 f3
</pre>

<p>formants applies three formants in parallel.
</p>

<pre class="indented">
(<a class=quiet href="extsnd.html#mapchannel">map-channel</a> (formants .99 900 .98 1800 .99 2700))
</pre>

<div class="spacer"></div>


<!-- moving-formant -->
<pre class="indented">
<em class=emdef>moving-formant</em> radius move-envelope
</pre>

<p>moving-formant moves a formant according to an envelope (the envelope y value is in Hz).
</p>

<pre class="indented">
(<a class=quiet href="extsnd.html#mapchannel">map-channel</a> (moving-formant .99 '(0 1200 1 2400)))
</pre>

<div class="spacer"></div>


<!-- notch-filter -->
<pre class="indented">
<em class=emdef>notch-filter</em> scaler size
</pre>

<p>This is an example of calling the CLM <a href="sndclm.html#notch">notch</a> filter.
</p>

<pre class="indented">
(<a class=quiet href="extsnd.html#mapchannel">map-channel</a> (notch-filter .8 32))
</pre>

<div class="spacer"></div>


<!-- osc-formants -->
<pre class="indented">
<em class=emdef>osc-formants</em> radius bases amounts freqs
</pre>

<p>osc-formants sets up any number of independently oscillating formants, then calls map-channel.
</p>

<pre class="indented">
Scheme: (osc-formants .99 (float-vector 400.0 800.0 1200.0) (float-vector 80.0 80.0 120.0) (float-vector 4.0 2.0 3.0))
Ruby:   osc_formants(0.99, vct(400, 800, 1200), vct(80, 80, 120), vct(4, 2, 3))
</pre>

<p>'bases' are the formant center frequencies; 'freqs' are the oscillator frequencies;
'amounts' are "deviations" &mdash; they scale the oscillator outputs which set the runtime
formant frequencies (thereby setting the width of the warbling).
</p>
<div class="spacer"></div>


<!--  examp SOUND EFFECTS  -->

<div class="innerheader" id="sseffects">sound effects</div>

<!-- add-notes -->
<pre class="indented">
<em class=emdef>add-notes</em> notes snd chn
</pre>

<p>add-notes adds (mixes) 'notes' starting at the cursor in the currently selected channel.
'notes' is a list of lists of the form: (list file offset amp).
</p>

<pre class="indented">
Scheme: (add-notes '(("oboe.snd") 
                     ("pistol.snd" 1.0 2.0)))

Ruby:   add_notes([["oboe.snd"], 
                   ["pistol.snd", 1.0, 2.0]])
</pre>

<p>This mixes "oboe.snd" at time 0.0,
then "pistol.snd" at 1.0 (second) scaled by 2.0.
</p>
<div class="spacer"></div>


<!-- am -->
<pre class="indented">
<em class=emdef>am</em> freq
<em class=emdef>ring-mod</em> freq gliss-env
<em class=emdef>ring-modulate-channel</em> freq beg dur snd chn edpos
<em class=emdef>vibro</em> speed depth
</pre>

<p>These functions perform amplitude modulation and ring-modulation. 'freq' is the modulation frequency.
</p>

<pre class="indented">
(<a class=quiet href="extsnd.html#mapchannel">map-channel</a> (am 440))
(<a class=quiet href="extsnd.html#mapchannel">map-channel</a> (ring-mod 10 (list 0 0 1 (<a class=quiet href="sndclm.html#hztoradians">hz-&gt;radians</a> 100))))
(ring-modulate-channel 100.0)
(<a class=quiet href="extsnd.html#mapchannel">map-channel</a> (vibro 440 0.5))
</pre>

<p>am uses the CLM <a href="sndclm.html#amplitude-modulate">amplitude-modulate</a> generator;
the others are little more than <a href="sndclm.html#oscil">oscil</a> and a multiply.
'gliss-env' in ring-mod controls the frequency of the modulation.
See also <a href="sndclm.html#ssb-am">ssb-am</a>.
</p>
<div class="spacer"></div>


<!-- chain-dsps -->
<pre class="indented">
<em class=def id="chaindsps">chain-dsps</em> beg dur :rest dsps
</pre>

<p>chain-dsps creates a patch of chained generators from its arguments.
Someone wanted to set up generator patches in a note list:
</p>

<pre class="indented">
(<a class=quiet href="#wsdoc">with-sound</a> ()
  (chain-dsps 0 1.0 '(0 0 1 .25 2 0) (<a class=quiet href="sndclm.html#make-oscil">make-oscil</a> 440))
  (chain-dsps 1.0 1.0 '(0 0 1 1 2 0) (<a class=quiet href="sndclm.html#make-one-zero">make-one-zero</a> .5) (<a class=quiet href="sndclm.html#make-readin">make-readin</a> "oboe.snd"))
  (chain-dsps 2.0 1.0 '(0 0 1 .125 2 0) (let ((osc1 (<a class=quiet href="sndclm.html#make-oscil">make-oscil</a> 220)) 
	                                      (osc2 (<a class=quiet href="sndclm.html#make-oscil">make-oscil</a> 440))) 
                                          (lambda (val) (+ (osc1 val) 
		                                           (osc2 (* 2 val)))))))
</pre>

<p>The 'dsps' is a sequence of breakpoint lists and generators; the breakpoint lists
are treated as envelopes, and the generators are connected (previous) output to (current) input in the reverse of the order
received.  <a href="sndclm.html#readin">readin</a> is an exception; since its input comes
from a file, it is added to the current output.
So, the first call is an <a href="sndclm.html#oscil">oscil</a> multiplied
by an envelope.  The second filters and envelopes readin input.
The third sets up an additive synthesis patch.
In Ruby, this example is:
</p>

<pre class="indented">
with_sound() do
  chain_dsps(0, 1.0, [0, 0, 1, 1, 2, 0], make_oscil(:frequency, 440))
  chain_dsps(0, 1.0, [0, 0, 1, 1, 2, 0], make_one_pole(0.5), make_readin("oboe.snd"))
  chain_dsps(0, 1.0, [0, 0, 1, 1, 2, 0], 
   let(make_oscil(:frequency, 220),
       make_oscil(:frequency, 440)) 
     do |osc1, osc2|
       lambda do |val| 
         osc1.run(val) + osc2.run(2.0 * val) 
     end
   end)
end
</pre>

<div class="spacer"></div>


<!-- compand -->
<pre class="indented">
<em class=emdef>compand</em> 
</pre>

<p>These functions lookup a table value based on the current sample amplitude; the table is set up
so that soft portions are slightly amplified. 
The companding curve is
taken from Steiglitz "A DSP Primer".
</p>
<div class="spacer"></div>


<!-- cnvtest -->
<pre class="indented">
<em class=emdef>cnvtest</em> snd0 snd1 amp
</pre>

<p>This is an example of using convolution.
It convolves 'snd0' and 'snd1' (using the CLM <a href="sndclm.html#convolve">convolve</a> generator), 
then scales by 'amp'. It returns the new maximum amplitude.
</p>

<pre class="indented">
(cnvtest 0 1 .1)
</pre>

<div class="spacer"></div>


<!-- cross-synthesis -->
<pre class="indented">
<em class=def id="crosssynthesis">cross-synthesis</em> cross-snd amp fftsize radius
</pre>

<p>cross-synthesis performs cross-synthesis between 'cross-snd' (a sound) and the currently 
selected sound.
'cross-snd' is the sound that controls the spectra.
</p>

<pre class="indented">
(<a class=quiet href="extsnd.html#mapchannel">map-channel</a> (cross-synthesis 1 .5 128 6.0))
</pre>

<div class="spacer"></div>


<!-- echo -->
<pre class="indented">
<em class=emdef>echo</em> scaler secs
<em class=emdef>flecho</em> scaler secs
<em class=def id="zecho">zecho</em> scaler secs frq amp
</pre>

<p>These are delay-based sound effects. 
echo returns an echo maker ('secs' is the delay in seconds between echos, 'scaler' is
the amplitude ratio between successive echoes).
zecho is similar, but also modulates the echoes.
flecho is a low-pass filtered echo maker.
See <a href="grfsnd.html#sndwithclm">Snd with CLM</a> for
a discussion.
</p>

<pre class="indented">
Scheme:
(<a class=quiet href="extsnd.html#mapchannel">map-channel</a> (echo .5 .5) 0 44100)
(<a class=quiet href="extsnd.html#mapchannel">map-channel</a> (zecho .5 .75 6 10.0) 0 65000)
(<a class=quiet href="extsnd.html#mapchannel">map-channel</a> (flecho .5 .9) 0 75000)

Ruby:
map_channel(echo(0.5, 0.5), 0 44100)
map_channel(zecho(0.5, 0.75, 6, 10.0), 0, 65000)
map_channel(flecho(0.5, 0.9), 0, 75000)
</pre>

<div class="spacer"></div>


<!-- expsrc -->
<pre class="indented">
<em class=def id="expsrc">expsrc</em> rate snd chn
</pre>

<p>expsrc uses sampling rate conversion (the <a href="sndclm.html#src">src</a> generator) and granular synthesis (the <a href="sndclm.html#granulate">granulate</a> generator)
to change the pitch of a sound without changing its duration.
</p>

<pre class="indented">
(<a class=quiet href="extsnd.html#mapchannel">map-channel</a> (expsrc 2.0)) ; up an octave
</pre>

<p>There are lots of other related examples: see for example <a href="#clmexpsrc">clm-expsrc</a>, expsnd below,
<a href="#ssbbank">ssb-bank</a>, or the <a href="sndclm.html#phase-vocoder">phase-vocoder</a>.
</p>
<div class="spacer"></div>


<!-- expsnd -->
<pre class="indented">
<em class=def id="expsnd">expsnd</em> rate-envelope snd chn
</pre>

<p>expsnd uses the same technique as expsrc, but uses it to change the tempo according to an envelope while
maintaining the original pitch.
expsnd needs dsp.scm (but doesn't check that it is loaded).
</p>

<pre class="indented">
(expsnd '(0 1 2 .4))   ; speed up
(expsnd '(0 .5 2 2.0)) ; start fast, end slow
</pre>

<div class="spacer"></div>


<!-- main-index |fp:Forbidden Planet -->
<!-- fp -->
<pre class="indented">
<em class=def id="fp">fp</em> sr osamp osfrq snd chn
</pre>

<p>fp drives an <a href="sndclm.html#src">src</a> generator with an oscillator, modulating
a sound.  'sr' is the base sampling rate; 'osamp' is the modulation depth; 'osfrq' is
the modulation frequency.  hello-dentist below is a randomized version of this.  The name "fp"
refers to "Forbidden Planet" which used this kind of sound effect a lot.
</p>

<pre class="indented">
(fp 1.0 .3 20)
</pre>

<div class="spacer"></div>


<!-- hello-dentist -->
<pre class="indented">
<em class=def id="hellodentist">hello-dentist</em> frq amp snd chn
</pre>

<p>hello-dentist drives n <a href="sndclm.html#src">src</a> generator with a <a href="sndclm.html#rand-interp">rand-interp</a>
generator, producing a random quavering effect, hence the name.
</p>

<pre class="indented">
(hello-dentist 40.0 .1)
</pre>

<p>'frq' is the random number frequency; 'amp' sets the depth of the modulation.
</p>
<div class="spacer"></div>


<!-- place-sound -->
<pre class="indented">
<em class=def id="placesound">place-sound</em> mono-snd stereo-snd panning-envelope-or-degree
</pre>

<p>place-sound mixes a mono sound ('mono-snd', an index) into a stereo sound ('stereo-snd') 
with panning determined by 'panning-envelope-or-degree'.
If 'panning-envelope-or-degree' is a number (in degrees),
the place-sound function has the same effect as using
CLM's <a href="sndclm.html#locsig">locsig</a> generator; it mixes a mono sound into a stereo sound, splitting 
it into two copies whose amplitudes depend on the desired location.
0 degrees: all in channel 0, 90: all in channel 1.
</p>

<pre class="indented">
(place-sound 0 1 45.0) 
;; 0=sound 0 (mono), 1=sound 1 (stereo), 45 deg, so outa * 0.5 and outb * 0.5
</pre>

<p>If 'panning-envelope-or-degree' is an envelope,
the split depends on the panning envelope (0 = all in chan 0, etc).
</p>

<pre class="indented">
(place-sound 0 1 '(0 0 1 1)) ; mix goes from all in outa to all in outb
</pre>

<p>This function could use at least a start time parameter.
</p>

<table class="method">
<tr><td class="methodtitle">Panning or Sound Placement</td></tr>
<tr><td>
<blockquote><small>
Place sound: <a href="#placesound">place-sound</a> above.<br>
Place mix: <a href="#musfilemix">mus-file-mix</a><br>
CLM placement generator: <a href="sndclm.html#locsig">locsig</a><br>
CLM moving sound generator: <a href="#dlocsigdoc">dlocsig</a><br>
Move sound via flanging: see flanging effect in new-effects.scm<br>
Cross fade in frequency domain: <a href="#fadedoc">fade.scm</a>
</small></blockquote>
</td></tr></table>

<div class="spacer"></div>



<!-- pulse-voice -->
<pre class="indented">
<em class=emdef>pulse-voice</em> cosines (freq 440.0) (amp 1.0) (fftsize 256) (r 2.0) snd chn
</pre>

<p>This function is a form of cross-synthesis which drives the resynthesis with a <a href="sndclm.html#ncos">ncos</a> pulse train.
'freq' is the <a href="sndclm.html#ncos">ncos</a> frequency; 'amp' is an overall amplitude scaler;
'cosines' is the number of cosines in the pulse (the more the spikier);
'fftsize' and 'r' (radius) control the <a href="sndclm.html#formant">formant</a> bank
used to get the current spectrum.
</p>

<pre class="indented">
(pulse-voice 80 20.0 1.0 1024 0.01)
(pulse-voice 80 120.0 1.0 1024 0.2)
(pulse-voice 30 240.0 1.0 1024 0.1)
(pulse-voice 6 1000.0 1.0 512)
</pre>

<p>See also voice-&gt;unvoiced below.
</p>
<div class="spacer"></div>



<!-- ramp -->
<pre class="indented">
<em class=def id="makeramp">make-ramp</em> (size 128)
<em class=emdef>ramp</em> gen up
</pre>

<p>ramp is a generator that produces a ramp of a given length, then sticks at 0.0 or 1.0 until the 'up' argument changes.
The idea here is that we want to ramp in or out a portion of a sound based on some
factor of the sound data; the ramp generator produces a ramp up when 'up' is #t, sticking
at 1.0, and a ramp down when 'up' is #f, sticking at 0.0.
'size' sets the steepness of the ramp.
A similar, less bumpy effect uses the <a href="sndclm.html#moving-average">moving-average</a> generator.
The following produces a very jittery, wandering amplitude envelope (brownian motion):
</p>

<pre class="indented">
(let ((ramper (make-ramp 1000)))  ; ramp via increments of .001
  (<a class=quiet href="extsnd.html#mapchannel">map-channel</a> (lambda (y) 
                 (* y (ramp ramper (&lt; (random 1.0) .5))))))
</pre>

<div class="spacer"></div>


<!-- reverse-by-blocks -->
<pre class="indented">
<em class=def id="reversebyblocks">reverse-by-blocks</em> block-len snd chn
<em class=emdef>reverse-within-blocks</em> block-len snd chn
</pre>

<p>reverse-by-blocks and reverse-within-blocks work best with
speech. reverse-by-blocks divides a sound into blocks, then recombines those blocks in reverse order.
reverse-within-blocks divides a sound into blocks, then recombines them in order, but with each block internally reversed.
'block-len' is the block length in seconds.
</p>

<pre class="indented">
(reverse-by-blocks .1)
(reverse-within-blocks .1) ; .5 is also good
</pre>

<div class="spacer"></div>


<!-- scramble-channels -->
<pre class="indented">
<em class=emdef>scramble-channels</em> :rest new-order
<em class=emdef>scramble-channel</em> silence
</pre>

<p>scramble-channels uses <a href="extsnd.html#swapchannels">swap-channels</a>
to arbitrarily reorder the current sound's channels.  The new channel order
is 'new-order' so
</p>

<pre class="indented">
(scramble-channels 3 2 0 1)
</pre>

<p>replaces chan0 with chan3, chan1 with chan2 and so on.
scramble-channel searches for silences, sets up a list of segments based on
those silences, and randomly re-orders the segments.
'silence' determines the background level that is treated as silence.
</p>

<pre class="indented">
(scramble-channel .01)
</pre>

<p>This function needs cleaner splices between the sections.
</p>
<div class="spacer"></div>


<!-- sound-interp -->
<pre class="indented">
<em class=def id="soundinterp">sound-interp</em> reader loc
<em class=emdef>make-sound-interp</em> start snd chn
<em class=def id="envsoundinterp">env-sound-interp</em> envelope (time-scale 1.0) snd chn
<em class=def id="granulatedsoundinterp">granulated-sound-interp</em> envelope (time-scale 1.0) (grain-length 0.10)
              (grain-envelope '(0 0 1 1 2 1 3 0)) (output-hop 0.05) snd chn
</pre>

<p>make-sound-interp returns an interpolating reader for the given channel.
The interpolating reader reads a channel at an arbitary location,
interpolating between samples if necessary.  The corresponding generator is sound-interp.
Here we use a sine wave to lookup the current sound:
</p>

<pre class="indented">
 (let ((osc (<a class=quiet href="sndclm.html#make-oscil">make-oscil</a> :frequency 0.5 :initial-phase (+ pi (/ pi 2))))
       (reader (make-sound-interp 0 0 0)) 
       (len (- (<a class=quiet href="extsnd.html#framples">framples</a> 0 0) 1)))
   (<a class=quiet href="extsnd.html#mapchannel">map-channel</a> (lambda (val) 
     (sound-interp reader (* len (+ 0.5 (* 0.5 (<a class=quiet href="sndclm.html#oscil">oscil</a> osc))))))))
</pre>

<p>This is effectively phase-modulation with an index of length-of-file-in-samples * 0.5 * hz-&gt;radians(oscil-frequency),
or equivalently duration-in-seconds * frequency-in-Hz * pi.
env-sound-interp reads the given channel (via a sound-interp generator)
according to 'envelope' and 'time-scale',
returning a new version of the data in the specified channel
that follows that envelope; that is, when the envelope is 0.0 we get sample 0, when the
envelope is 1.0 we get the last sample, when it is 0.5 we get the middle sample of the 
sound and so on. 
</p>

<pre class="indented">
Scheme: (env-sound-interp '(0 0 1 1))
Ruby:   env_sound_interp([0, 0, 1, 1])
</pre>
 
<p>returns an unchanged copy of the
current sound. To get the entire sound in reverse:
</p>

<pre class="indented">
Scheme: (env-sound-interp '(0 1 1 0))
Ruby:   env_sound_interp([0, 1, 1, 0])
</pre>

<p>And to go forward then backward, taking twice the original duration:
</p>

<pre class="indented">
Scheme: (env-sound-interp '(0 0 1 1 2 0) 2.0)
Ruby:   env_sound_interp([0, 0, 1, 1, 2, 0], 2.0)
</pre>

<p><a href="extsnd.html#srcsound">src-sound</a> with an
envelope could be used for this effect, but it is much more direct to apply the
envelope to sound sample positions.  A similar function is <a href="#scratch">scratch</a> in clm-ins.scm.
</p>

<p>granulated-sound-interp is similar to env-sound-interp, but uses granular synthesis rather than
sampling rate conversion to recreate the sound, so the effect is one of changing tempo rather
than changing speed (pitch).  Here we dawdle for awhile, then race at the end to get the whole sound in:
</p>

<pre class="indented">
(granulated-sound-interp '(0 0 1 .1 2 1) 1.0 0.2 '(0 0 1 1 2 0))
</pre>

<div class="spacer"></div>



<!-- voiced-&gt;unvoiced -->
<pre class="indented">
<em class=def id="voicedtounvoiced">voiced-&gt;unvoiced</em> amp fftsize r tempo snd chn
</pre>

<p>This function is a form of cross-synthesis which drives the resynthesis with white noise (see also pulse-voice above).
</p>

<pre class="indented">
 (voiced-&gt;unvoiced 1.0 256 2.0 2.0) ; whispered, twice as fast as original
</pre>

<p>'tempo' is the speed of the resynthesis.
</p>




<!--  examp MARKS  -->

<div class="innerheader" id="ssmarks">marks</div>

<!-- first-mark-in-window-at-left -->
<pre class="indented">
<em class=emdef>first-mark-in-window-at-left</em> 
</pre>

<p>first-mark-in-window-at-left moves the (time domain) 
graph so that the leftmost visible mark is at the left edge.
In large sounds it can be pain to get the left edge of the window
aligned with a specific spot in the sound.  In the following example, we assume
the desired left edge has a mark, and the 'l' key (without control)
will move the window left edge to that mark.
</p>

<pre class="indented">
(<a class=quiet href="extsnd.html#bindkey">bind-key</a> #\l 0 first-mark-in-window-at-left)
</pre>

<div class="spacer"></div>



<!-- mark-loops -->
<pre class="indented">
<em class=def id="markloops">mark-loops</em> 
</pre>

<p>mark-loops places marks at any loop points found in the current sound's header.
Only a few headers support loop points which are apparently used in synthesizers
to mark portions of a waveform that can be looped without causing clicks, thereby lengthening
a sound as a key is held down. 
</p>




<!--  examp SELECTIONS  -->

<div class="innerheader" id="ssselections">selections</div>

<!-- region-play-list -->
<pre class="indented">
<em class=def id="regionplaylist">region-play-list</em> data
<em class=emdef>region-play-sequence</em> data
</pre>

<p>region-play-list plays a list of regions.  'data' is list of lists:
(list (list reg time)...); region 'reg' is played at time 'time' (in seconds).
</p>

<pre class="indented">
(region-play-list (list (list reg0 0.0) (list reg1 0.5) (list reg2 1.0) (list reg0 1.0)))
</pre>

<p>which plays region reg0 at time 0.0 and 1.0, region reg1 at 0.5, and region reg2 at 1.0.
Similarly, region-play-sequence plays a sequence of regions, one after the other:
</p>

<pre class="indented">
(region-play-sequence (list reg0 reg1 reg2 reg0)) ; play in same order as before, but one after the other
</pre>

<div class="spacer"></div>


<!-- region-rms -->
<pre class="indented">
<em class=def id="regionrms">region-rms</em> reg
</pre>

<p>region-rms returns the rms value of the region's data (in chan 0).
</p>

<div class="spacer"></div>


<!-- selection-rms -->
<pre class="indented">
<em class=def id="selectionrms">selection-rms</em> 
</pre>

<p>selection-rms returns the rms value of the selection's data (in chan 0).
</p>



<!--  examp GRAPHICS  -->

<div class="innerheader" id="ssgraphics">graphics</div>

<!-- auto-dot -->
<pre class="indented">
<em class=emdef>auto-dot</em> snd chn y0 y1
</pre>

<p>auto-dot sets the dot size (when you're using dots in the time domain) based on 
the current graph size.
</p>

<pre class="indented">
(hook-push <a class=quiet href="extsnd.html#graphhook">graph-hook</a> auto-dot)
</pre>

<div class="spacer"></div>


<!-- display-db -->
<pre class="indented">
<em class=def id="displaydb">display-db</em> snd chn
</pre>

<p>display-db is a <a href="extsnd.html#lispgraphhook">lisp-graph-hook</a> function to display the time domain data in dB.
</p>

<pre class="indented">
(hook-push <a class=quiet href="extsnd.html#lispgraphhook">lisp-graph-hook</a> display-db)
</pre>

<p>I just noticed that its y axis is labelled upside down.
</p>
<div class="spacer"></div>



<!-- display-energy -->
<pre class="indented">
<em class=def id="displayenergy">display-energy</em> snd chn
</pre>

<p>display-energy is a <a href="extsnd.html#lispgraphhook">lisp-graph-hook</a> function to display the time domain data squared.
<a href="extsnd.html#xdisplayenergy">Here</a> is a picture of it in action.
</p>
<div class="spacer"></div>


<!-- flash-selected-data -->
<pre class="indented">
<em class=emdef>flash-selected-data</em> time-interval
</pre>

<p>flash-selected-data causes the selected channel's graph to
flash red and green.  'time-interval' is in milliseconds:
</p>

<pre class="indented">
(flash-selected-data 100)
</pre>

<p>Not sure why anyone would want such a thing...
examp.scm also has (commented out) functions to display colored text
in rxvt:
</p>

<pre class="indented">
(<a class=quiet>format</a> #t "~Athis is red!~Abut this is not" red-text normal-text)
(<a class=quiet>format</a> #t "~A~Ahiho~Ahiho" yellow-bg red-fg normal-text)
</pre>

<p>It's possible to use the same escape sequences in a normal shell script, of course:
</p>

<pre class="indented">
echo '\e[41m This is red! \e[0m'
</pre>




<!--  examp MISCELLANEOUS EXTENSIONS  -->

<div class="innerheader" id="ssmisc">miscellaneous stuff</div>

<!-- all-chans -->
<pre class="indented">
<em class=def id="allchans">all-chans</em> 
</pre>

<p>all-chans returns two parallel lists, the first a list of sound objects, the second of channel numbers.  If we have 
two sounds open (indices 0 and 1 for example), and the second has two channels, (all-chans) returns 
'((#&lt;sound 0&gt; #&lt;sound 1&gt; #&lt;sound 1&gt;) (0 0 1)).  
The interpretation is: '((sound-with-index0 sound-with-index1 sound-with-index1) (chan0 chan0 chan1)),
so if we're mapping some function with the usual snd chn parameters over all the current channels,
we can get the sound and channel values from these lists.  
</p>
<div class="spacer"></div>


<!-- channel-clipped? -->
<pre class="indented">
<em class=emdef>channel-clipped?</em> snd chn
</pre>

<p>channel-clipped? returns #t and a sample number if it finds clipping in the given channel.
examp.scm also has commented out code that places a mark at the start of each clipped
section in a sound, and adds a menu item ("Show Clipping") under the View menu.
</p>
<div class="spacer"></div>



<!-- do-chans -->
<pre class="indented">
<em class=emdef>do-chans</em> func origin
<em class=emdef>do-all-chans</em> func origin
<em class=emdef>do-sound-chans</em> func origin
</pre>

<p>do-chans applies 'func' to all the sync'd channels using 'origin' as the edit history indication.
do-all-chans is the same but applies 'func' to all channels of all sounds.
do-sound-chans applies 'func' to all channels in the currently selected sound.
</p>

<pre class="indented">
(do-all-chans (lambda (val) (* 2.0 val))) ; double all samples
</pre>

<div class="spacer"></div>


<!-- every-sample? -->
<pre class="indented">
<em class=def id="everysample">every-sample?</em> func
</pre>

<p>every-sample? applies 'func' to each sample in the current channel and returns
#t if 'func' is not #f for all samples; otherwise it moves the cursor to the first offending sample.
</p>

<pre class="indented">
&gt; (every-sample? (lambda (y) (&lt; (abs y) .1)))
#f
&gt; (cursor)
4423
&gt; (sample (cursor))
0.101104736328125
</pre>

<div class="spacer"></div>


<!-- explode-sf2 -->
<pre class="indented">
<em class=def id="explodesf2">explode-sf2</em> 
</pre>

<p>explode-sf2 turns a soundfont file (assuming it
is the currently selected sound) into a bunch of files of the form sample-name.aif.
It is based on <a href="extsnd.html#soundfontinfo">soundfont-info</a>; that documentation
includes a function, mark-sf2, that places a named mark at start of each new member of the font
and unnamed marks at the various loop points.
</p>
<div class="spacer"></div>


<!-- find-click -->
<pre class="indented">
<em class=emdef>find-click</em> loc
</pre>

<p>find-click finds the next click, starting its search at 'loc'.
It returns #f if it can't find a click.
</p>
<div class="spacer"></div>


<!-- finfo -->
<pre class="indented">
<em class=def id="finfo">finfo</em> filename
</pre>

<p>finfo returns a description of the file 'filename'.
</p>

<pre class="indented">
&gt; (finfo "oboe.snd")
"oboe.snd: chans: 1, srate: 22050, Sun/Next, big endian short (16 bits), len: 2.305"
</pre>

<div class="spacer"></div>


<!-- locate-zero -->
<pre class="indented">
<em class=emdef>find-pitch</em> pitch
<em class=def id="locatezero">locate-zero</em> limit
<em class=emdef>next-peak</em> 
<em class=def id="searchforclick">search-for-click</em> 
<em class=def id="zeroplus">zero+</em> 
</pre>

<p>locate-zero looks for the next sample where adjacent samples together are less than 'limit'
and moves the cursor to that sample.
The others are
examples of searching procedures (to be used with <a href="snd.html#menufind">C-s</a> and friends):
zero+ finds the next
positive-going zero crossing (if searching forwards).
next-peak finds
the next maximum or minimum in the waveform.
search-for-click looks for a click.
find-pitch finds the next
place where 'pitch' (in Hz) is predominate.
For example, type C-s (in the graph), then in the status area:
(find-pitch 600), and if the function finds some place in the sound
where 600 Hz seems to be the basic pitch, it moves the cursor there and
reports the time in the status area text window.
</p>
<div class="spacer"></div>


<!-- mpg -->
<pre class="indented">
<em class=def id="mpg">mpg</em> mpgfile rawfile
</pre>

<p>mpg uses the "system" function to call mpg123 to translate an MPEG
format sound file to a headerless ("raw") file containing 16-bit samples.
</p>

<pre class="indented">
(mpg "mpeg.mpg" "mpeg.raw")
</pre>

<p>This is now built-in if the Snd configuration process can find mpg123.
</p>
<div class="spacer"></div>


<!-- open-next-file-in-directory -->
<pre class="indented">
<em class=def id="opennextfileindirectory">open-next-file-in-directory</em> 
<em class=emdef>click-middle-button-to-open-next-file-in-directory</em> 
</pre>

<p>click-middle-button-to-open-next-file-in-directory sets up the mouse-click-hook and open-hook so that clicking the middle
mouse button closes the current file and opens the next (alphabetical
by filename) in the current directory.  These are used in edit123.scm.
</p>
<div class="spacer"></div>


<!-- play-ac3 -->
<pre class="indented">
<em class=emdef>play-ac3</em> name
</pre>

<p>play-ac3 tries to play an AC3 encoded sound file by calling a52dec.
</p>
<div class="spacer"></div>


<!-- read-ascii -->
<pre class="indented">
<em class=emdef>read-ascii</em> file (out-filename "test.snd") (out-type mus-next) (out-format mus-bshort) (out-srate 44100)
</pre>

<p>read-ascii tries to turn a text file into a sound file.
Octave or perhaps WaveLab produce these files; each line has one integer (as text), apparently a signed short.
The read-ascii parameters describe the output file.
</p>
<div class="spacer"></div>


<!-- read-flac -->
<pre class="indented">
<em class=emdef>read-flac</em> file
<em class=emdef>write-flac</em> snd
</pre>

<p>read-flac and write-flac deal with FLAC files.  This is now built into Snd if the flac
program can be found at configuration time.
</p>
<div class="spacer"></div>


<!-- read-ogg -->
<pre class="indented">
<em class=emdef>read-ogg</em> file
<em class=emdef>write-ogg</em> snd
</pre>

<p>read-ogg and write-ogg deal with OGG files.  This is now built into Snd if the oggdec and offenc
programs can be found at configuration time.
</p>
<div class="spacer"></div>


<!-- read-speex -->
<pre class="indented">
<em class=emdef>read-speex</em> file
<em class=emdef>write-speex</em> snd
</pre>

<p>read-speex and write-speex deal with SPEEX files.  This is now built into Snd if speexdec and speexenc
can be found at configuration time.
</p>
<div class="spacer"></div>


<!-- remove-clicks -->
<pre class="indented">
<em class=def id="removeclicks">remove-clicks</em> 
</pre>

<p>remove-clicks looks for obvious clicks and uses smooth-sound to remove them.
See also remove-single-sample-clicks and remove-pops in clean.scm.
</p>
<div class="spacer"></div>


<!-- sounds->segment-data -->
<pre class="indented">
<em class=def id="soundstosegmentdata">sounds-&gt;segment-data</em> main-dir (output-file "sounds.data")
</pre>

<p>This function takes a directory name, and runs through all the sounds in the embedded
directories, returning a text file with segment start and end times, and segment maxamps.
</p>

<pre class="indented">
(sounds-&gt;segment-data "/home/bil/test/iowa/sounds/" "iowa.data")
</pre>

<p>It was written to find the note boundaries in the Iowa musical instrument sound library.
</p>
<div class="spacer"></div>



<!-- sort-samples -->
<pre class="indented">
<em class=emdef>sort-samples</em> bins
</pre>

<p>sort-samples provides a histogram of the samples (by amplitude) in 'bins' bins.
</p>

<pre class="indented">
&gt; (sort-samples 20)  ; bins go by 0.05
#(129017 90569 915 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0)
;; so 915 samples were &gt; 0.1 in absolute value
</pre>

<div class="spacer"></div>


<!-- sync-everything -->
<pre class="indented">
<em class=def id="sync-everything">sync-everything</em> 
</pre>

<p>sync-everything sets the sync fields of all currently open sounds to the same unique value.
</p>
<div class="spacer"></div>


<!-- update-graphs -->
<pre class="indented">
<em class=def id="updategraphs">update-graphs</em> 
</pre>

<p>update-graphs updates (redraws) all graphs.
</p>
<div class="spacer"></div>


<!-- window-rms -->
<pre class="indented">
<em class=emdef>window-rms</em> 
</pre>

<p>window-rms returns the rms of the data in currently selected graph window.
</p>
<div class="spacer"></div>


<!-- window-samples -->
<pre class="indented">
<em class=def id="windowsamples">window-samples</em> snd chn
</pre>

<p>window-samples returns (in a float-vector) the samples
displayed in the current window for the given channel.
This is just a trivial wrapper for <a href="extsnd.html#channeltofv">channel-&gt;float-vector</a>.
</p>
<div class="spacer"></div>


<!-- xb-open -->
<pre class="indented">
<em class=def id="xbopen">xb-open</em> snd
<em class=emdef>xb-close</em> snd
<em class=emdef>switch-to-buf</em>
</pre>

<p>These provide Emacs-like C-x b support where only one sound is visible at a time.
To activate it:
</p>

<pre class="indented">
(<a class=quiet href="extsnd.html#bindkey">bind-key</a> #\b 0 switch-to-buf #t)
(hook-push <a class=quiet href="extsnd.html#closehook">close-hook</a> xb-close)
(hook-push <a class=quiet href="extsnd.html#afteropenhook">after-open-hook</a> xb-open)	    
</pre>




<!--  FILE: extensions  -->

<div class="header" id="extensionsdoc">extensions</div>

<p>These were originally scattered around examp.scm; I thought it would be more
convenient if they were in one file.
</p>

<div class="spacer"></div>

<!-- channels-equal? -->
<pre class="indented">
<em class=def id="channelsequal">channels-equal?</em> snd1 chn1 snd2 chn2 (allowable-difference 0.0)
<em class=def id="channelseq">channels=?</em> snd1 chn1 snd2 chn2 (allowable-difference 0.0)
</pre>

<p>channels=? returns #t if the two specified channels are the same within the
given 'allowable-difference'.
The 'allowable-difference' is checked on each sample, so any sample-wise difference
larger than that causes the comparison to return #f.
channels-equal? returns #t if channels=?
and the channels are the same length.  In channels=? one the other hand, the trailing (extra) samples
in one channel are compared with 0.0 (that is, the shorter channel is padded out with zeros).
</p>
<div class="spacer"></div>


<!-- channel-sync -->
<pre class="indented">
<em class=def id="channelsync">channel-sync</em> snd chn
</pre>

<p>channel-sync uses the channel-properties list to implement a channel-local sync field.  (This property is currently
not used anywhere).
</p>
<div class="spacer"></div>


<!-- contrast-channel -->
<pre class="indented">
<em class=def id="contrastchannel">contrast-channel</em> index beg dur snd chn edpos
</pre>

<p>contrast-channel applies the CLM <a href="sndclm.html#contrast-enhancement">contrast-enhancement</a> function to a channel;
this is largely equivalent to the control panel Contrast slider.
</p>
<div class="spacer"></div>


<!-- contrast-sound -->
<pre class="indented">
<em class=def id="contrastsound">contrast-sound</em> index (beg 0) dur snd
</pre>

<p>contrast-sound applies <a href="sndclm.html#contrast-enhancement">contrast-enhancement</a> to every channel of the sound 'snd'.
It is the multichannel version of <a href="#contrastchannel">contrast-channel</a>.
</p>
<div class="spacer"></div>


<!-- dither-channel -->
<pre class="indented">
<em class=def id="ditherchannel">dither-channel</em> (amount .00006) beg dur snd chn edpos	
</pre>

<p>dither-channel adds "dithering" (noise) to a channel; some experts insist this makes everything copacetic.
The noise consists of two white noise generators adding together.
</p>
<div class="spacer"></div>


<!-- dither-sound -->
<pre class="indented">
<em class=def id="dithersound">dither-sound</em> (amount .00006) (beg 0) dur snd
</pre>

<p>dither-sound adds dithering to every channel of the sound 'snd'.
It is the multichannel version of <a href="#ditherchannel">dither-channel</a>.
</p>
<div class="spacer"></div>


<!-- enveloped-mix -->
<pre class="indented">
<em class=def id="envelopedmix">enveloped-mix</em> filename beg env
</pre>

<p>enveloped-mix is like <a href="#mixsound">mix-sound</a>, but includes an
amplitude envelope over the mixed-in data.
</p>

<pre class="indented">
(enveloped-mix "pistol.snd" 0 '(0 0 1 1 2 0))
</pre>

<div class="spacer"></div>


<!-- env-expt-channel -->
<pre class="indented">
<em class=def id="envexptchannel">env-expt-channel</em> env exponent (symmetric #t) beg dur snd chn edpos
<em class=def id="anyenvchannel">any-env-channel</em> env func beg dur snd chn edpos
<em class=emdef>ramp-expt</em> a0 a1 exponent (symmetric #t) beg dur snd chn edpos
<em class=def id="sineenvchannel">sine-env-channel</em> env beg dur snd chn edpos
<em class=def id="sineramp">sine-ramp</em> a0 a1 beg dur snd chn edpos
<em class=def id="blackman4envchannel">blackman4-env-channel</em> env beg dur snd chn edpos
<em class=emdef>blackman4-ramp</em> a0 a1 beg dur snd chn edpos
<em class=def id="envsquaredchannel">env-squared-channel</em> env (symmetric #t) beg dur snd chn edpos
<em class=emdef>ramp-squared</em> a0 a1 (symmetric #t) beg dur snd chn edpos
</pre>

<p>These functions goof around with envelopes in various amusing ways.
any-env-channel takes an envelope and a function to produce the connection between successive
breakpoints, and applies the two to the current channel as an envelope.  This packages up most of
the "boilerplate" associated with applying an envelope to a sound.  It is used by the other
enveloping functions: sine-env-channel, blackman4-env-channel, and env-squared-channel.
sine-ramp and sine-env-channel are the sinusoidal versions of <a href="extsnd.html#rampchannel">ramp-channel</a>
and <a href="extsnd.html#envchannel">env-channel</a>.
</p>

<pre class="indented">
(sine-env-channel '(0 0 1 1 2 -.5 3 1))
</pre>

<p>applies the given envelope to the current channel,
connecting the points with a sinusoidal curve.
Similarly, blackman4-env-channel connects the dots with
a sum of cosines, and env-squared-channel connects the dots with an x^2 curve.  To get any other positive exponent,
use env-expt-channel.  The 'symmetric' argument determines whether the
up and down moving ramps look symmetrical around a break point.
</p>

<table>
<tr><td><img src="pix/exptenvs.png" alt="exponential envelopes"></td><td>

<pre class="indented">
(env-channel '(0 0 1 1 2 -.75 3 0)) 
(env-sound '(0 0 1 1 2 -.75 3 0) 0 100 32.0)  
(env-sound '(0 0 1 1 2 -.75 3 0) 0 100 .032) 
(env-sound '(0 0 1 1 2 -.75 3 0) 0 100 0.0)
(sine-env-channel '(0 0 1 1 2 -.75 3 0))
(env-squared-channel '(0 0 1 1 2 -.75 3 0))
(blackman4-env-channel '(0 0 1 1 2 -.75 3 0))
(env-squared-channel '(0 0 1 1 2 -.75 3 0) #f)
(env-expt-channel '(0 0 1 1 2 -.75 3 0) 3.0)
(env-expt-channel '(0 0 1 1 2 -.75 3 0) 3.0 #f)
(env-expt-channel '(0 0 1 1 2 -.75 3 0) .3)
(env-expt-channel '(0 0 1 1 2 -.75 3 0) .3)
</pre>
</td></tr></table>

<div class="spacer"></div>


<!-- for-each-sound-file -->
<pre class="indented">
<em class=def id="foreachsoundfile">for-each-sound-file</em> func dir
<em class=def id="mapsoundfiles">map-sound-files</em> func dir
<em class=def id="matchsoundfiles">match-sound-files</em> func dir
</pre>

<p>for-each-sound-file and 
map-sound-files apply 'func' to each sound file in 'dir'.
The 'func' is passed one argument, the sound file name.
map-sound-files returns a list of the results, if any, returned from 'func'.
match-sound-files applies 'func' to each sound file in 'dir' and returns a list of files for which func does not return #f.
</p>

<pre class="indented">
(for-each-sound-file
  (lambda (n) 
    (when (&gt; (<a class=quiet href="extsnd.html#mussoundduration">mus-sound-duration</a> n) 10.0) 
      (<a class=quiet href="extsnd.html#sndprint">snd-print</a> (format #f "~%~A" n))))
  ".")
</pre>
<div class="spacer"></div>


<!-- insert-channel -->
<pre class="indented">
<em class=def id="insertchannel">insert-channel</em> filedat beg dur snd chn edpos
</pre>

<p>insert-channel inserts the specified data ('filedat') in the given channel at the given location.
See <a href="#mixchannel">mix-channel</a> for a description of 'filedat'.
</p>
<div class="spacer"></div>


<!-- mix-channel -->
<pre class="indented">
<em class=def id="mixchannel">mix-channel</em> filedat beg dur snd chn edpos
</pre>

<p>mix-channel is a "regularized" version of the file mixing functions (<a class=quiet href="extsnd.html#mix">mix</a> and 
<a href="#mixsound">mix-sound</a>).
Its first argument can be either a filename (a string), a sound, or a list containing the filename (or index), the
start point in the file, and (optionally) the channel of the file to mix:
</p>

<pre class="indented">
(mix-channel "pistol.snd")             ; mixing starts at sample 0, entire sound is mixed
(mix-channel "pistol.snd" 10000)       ; mixing starts at sample 10000 in current sound
(mix-channel (list "pistol.snd" 1000)) ; mixed data starts at sample 1000 in pistol.snd
(mix-channel (list "2.snd" 0 1))       ; mixed data reads channel 1 in 2.snd
</pre>

<div class="spacer"></div>


<!-- mono->stereo -->
<pre class="indented">
<em class=def id="monotostereo">mono-&gt;stereo</em> new-name snd1 chn1 snd2 chn2
<em class=def id="stereotomono">stereo-&gt;mono</em> orig-snd chan1-name chan2-name
<em class=emdef>mono-files-&gt;stereo</em> new-name chan1-file chan2-file
</pre>

<p>mono-&gt;stereo combines two mono sounds (currently open in Snd) into one (new) stereo file. 
mono-files-&gt;stereo
is the same, but the source sounds are files, not necessarily already open in Snd.
stereo-&gt;mono takes a stereo sound and produces two new mono sounds.
(The corresponding stereo-&gt;mono-files can be based on the existing
<a href="extsnd.html#extractchannel">extract-channel</a> function).
</p>
<div class="spacer"></div>


<!-- normalized-mix -->
<pre class="indented">
<em class=def id="normalizedmix">normalized-mix</em> filename beg in-chan snd chn
</pre>

<p>normalized-mix is like <a href="extsnd.html#mix">mix</a> but the mixed result has same peak amplitude as the 
original data. 
</p>
<div class="spacer"></div>


<!-- normalize-sound -->
<pre class="indented">
<em class=def id="normalizesound">normalize-sound</em> amp (beg 0) dur snd
</pre>

<p>normalize-sound scales the sound 'snd' to peak amplitude 'amp'.
It is the multichannel version of <a href="extsnd.html#normalizechannel">normalize-channel</a>.
</p>
<div class="spacer"></div>


<!-- offset-channel -->
<pre class="indented">
<em class=def id="offsetchannel">offset-channel</em> amount beg dur snd chn edpos	
</pre>

<p>offset-channel adds a constant (DC offset) to a channel.
</p>
<div class="spacer"></div>


<!-- offset-sound -->
<pre class="indented">
<em class=def id="offsetsound">offset-sound</em> off (beg 0) dur snd
</pre>

<p>offset-sound adds 'off' to every sample in the sound 'snd'.  
It is the multichannel version of <a href="#offsetchannel">offset-channel</a>.
</p>
<div class="spacer"></div>


<!-- pad-sound -->
<pre class="indented">
<em class=def id="padsound">pad-sound</em> beg dur snd
</pre>

<p>pad-sound places a block of 'dur' zeros in every channel of the sound 'snd' starting at 'beg'.
It is the multichannel version of <a href="extsnd.html#padchannel">pad-channel</a>.
</p>
<div class="spacer"></div>


<!-- redo-channel -->
<pre class="indented">
<em class=emdef>redo-channel</em> (edits 1) snd chn
</pre>

<p>redo-channel is a "regularized" version of <a href="extsnd.html#redo">redo</a>.
</p>
<div class="spacer"></div>


<!-- scale-sound -->
<pre class="indented">
<em class=def id="scalesound">scale-sound</em> scl (beg 0) dur snd
</pre>

<p>scale-sound multiplies every sample in the sound 'snd' by 'scl'.
It is the multichannel version of <a href="extsnd.html#scalechannel">scale-channel</a>.
</p>
<div class="spacer"></div>


<!-- undo-channel -->
<pre class="indented">
<em class=emdef>undo-channel</em> (edits 1) snd chn
</pre>

<p>undo-channel is a "regularized" version of <a href="extsnd.html#undo">undo</a>.
</p>





<!--  FILE: fade  -->

<div class="header" id="fadedoc">fade</div>

<!-- main-index |fadedoc:cross-fade (frequency domain) -->

<p>
The two functions in fade.scm perform frequency-domain cross-fades, that is, the
cross-fade is handled by a bank of bandpass filters (<a class=quiet href="sndclm.html#formant">formant</a> generators).  The effect
is sometimes only slightly different from a normal (time-domain) cross-fade, but
there are some interesting possibilities ("sound evaporation", etc).
</p>

<pre class="indented">
<em class=emdef>cross-fade</em> beg dur amp file1 file2 ramp-beg ramp-dur ramp-type bank-dur fs fwidth
</pre>

<p>
cross-fade stitches 'file1' to 'file2' using filtering to provide the
join (rather than amplitude ramps).  'ramp-type' can be 0: sweep up,
1: sweep down, 2: sweep split from the middle; "sweep up" means that the
low frequencies are filtered out first, etc.  'fs' is how many formants to
set up; 'fwidth' is the formant resonance width control; 'ramp-beg' and
'ramp-dur' set the start point and length of the sweep; 'bank-dur'
controls how much time is spent in the formant bank before starting or after ending
the ramp.
</p>

<pre class="indented">
(<a class=quiet href="#wsdoc">with-sound</a> () (cross-fade 0 2 1.0 "oboe.snd" "trumpet.snd" 0.5 1.0 0 .1 256 2))
(float-vector-&gt;channel (cross-fade 0 1.5 1.0 0 1 0.5 .5 0 1.0 256 2))
</pre>

<p>
These fades seem more successful to me when done relatively quickly (the opposite of the dissolve-fade below
which is best if done as slowly as possible).  With any luck the "sweep up" case can produce a sort of "evaporation" effect.
A similar idea is behind dissolve-fade:
</p>

<div class="spacer"></div>
<pre class="indented">
<em class=def id="dissolvefade">dissolve-fade</em> beg dur amp file1 file2 fsize r lo hi
</pre>

<p>It ramps in and out frequency bands chosen at random.  The original hope was to get something like a graphical dissolve,
but it turns out to be better to let the random changes float along with no overall
direction.  If the current band amplitude is 1.0, we send it toward 0.0 and vice versa.  Given patience
and a suitably noisy original, strange pitches emerge and submerge.  'fsize' is the formant bank size;
'r' is the same as 'fwidth' in cross-fade (resonance width) modulo a factor of 2 (sigh...).
'lo' and 'hi' set the portion of the formant bank that is active during the dissolve.
</p>

<pre class="indented">
(<a class=quiet href="#wsdoc">with-sound</a> () (dissolve-fade 0 1 1.0 "oboe.snd" "trumpet.snd" 256 2 0 128))
(float-vector-&gt;channel (dissolve-fade 0 2 1 0 1 1024 2 2 #f))
</pre>



<!--  FILE: freeverb  -->

<div class="header" id="freeverbdoc">freeverb</div>

<p>freeverb is Jezar Wakefield's reverberator, translated by Michael Scholz from CLM's freeverb.ins (written by Fernando Lopez-Lezcano), and documented
in freeverb.html in the CLM tarball.
</p>

<pre class="indented">
<em class=def id="freeverb">freeverb</em>
    (room-decay 0.5)
    (damping 0.5)
    (global 0.3)
    (predelay 0.03)
    (output-gain 1.0)
    (output-mixer #f)
    (scale-room-decay 0.28)
    (offset-room-decay 0.7)
    (combtuning '(1116 1188 1277 1356 1422 1491 1557 1617))
    (allpasstuning '(556 441 341 225))
    (scale-damping 0.4)
    (stereo-spread 23)
    (verbose #f)
</pre>


<p>Here is a paraphrase of some of Fernando's documentation.
'room-decay'
determines the decay time of the reverberation.
'damping' set the high frequency damping; this parameter can be a number, or an array or a list (with same number of elements as output channels). It is possible to control the damping for each output channel.
'global'
controls how the outputs of all reverbs (one per channel) are mixed into the output stream. Specifying "0" will connect each reverberator directly to each output channel, "1" will mix all reverberated channels equally into all output channels. Intermediate values will allow for an arbitrary balance between local and global reverberation. The overall gain of the mixing matrix is kept constant. 'output-mixer' overrides this parameter.
'predelay' 
sets the predelay that is applied to the input streams. An array or list lets you specify the individual predelays for all chanenels.
'output-gain'
is the overall gain multiplier for the output streams.
'output-mixer'
sets the output mixing matrix directly (rather than through 'global').
</p>

<pre class="indented">
(<a class=quiet href="#wsdoc">with-sound</a> (:reverb freeverb :reverb-data '(:output-gain 3.0)) 
  (fm-violin 0 .1 440 .1 :reverb-amount .1))
</pre>


<div class="seealso">
see also: &nbsp; <a href="#jcrevdoc">jcrev</a> &nbsp; <a href="#nrev">nrev</a> <a href="extsnd.html#convolvewith">convolution</a>
</div>




<!--  FILE: grani  -->

<div class="header" id="granidoc">grani</div>

<p>This is Fernando Lopez-Lezcano's CLM <A HREF="http://ccrma.stanford.edu/~nando/clm/grani/">grani</A> 
granular synthesis instrument translated to Scheme by Mike Scholz.
The Ruby version is in clm-ins.rb.
</p>


<pre class="indented">
<em class=def id="grani">grani</em> start-time duration amplitude file
  (input-channel 0)                       ; input file channel from which samples are read
  (grains 0)                              ; if not 0, total number of grains to be generated
  (amp-envelope '(0 0 0.3 1 0.7 1 1 0))   ; overall amplitude envelope for note
  (grain-envelope '(0 0 0.3 1 0.7 1 1 0)) ; env for each individual grain
  (grain-envelope-end #f)                 ; if not #f, a second grain env
  (grain-envelope-transition '(0 0 1 1))  ; interp 0: use grain-envelope, 1: use grain-envelope-end
  (grain-envelope-array-size 512)         ; <a href="sndclm.html#make-table-lookup">make-table-lookup</a> table size
  (grain-duration 0.1)                    ; number or envelope setting grain duration (in seconds)
  (grain-duration-spread 0.0)             ; random spread around 'grain-duration'
  (grain-duration-limit 0.002)            ; minimum grain duration (in seconds)
  (srate 0.0)                             ; number or envelope setting sampling rate conversion
  (srate-spread 0.0)                      ; random spread of src around 'srate'
  (srate-linear #f)                       ; if #f, srate (envelope) is exponential
  (srate-base (expt 2 (/ 12)))            ; srate env base if exponential
  (srate-error 0.01)                      ; error bound for exponential conversion
  (grain-start '(0 0 1 1))                ; env that sets input file read point of current grain
  (grain-start-spread 0.0)                ; random spread around 'grain-start'
  (grain-start-in-seconds #f)             ; if #f, treat 'grain-start' as a percentage
  (grain-density 10.0)                    ; env on number of grains / second in output
  (grain-density-spread 0.0)              ; random spread around 'grain-density'
  (reverb-amount 0.01)
  (reverse #f)                            ; if #t, input is read backwards
  (where-to 0)                            ; locsig stuff &mdash; see the full documentation
  (where-bins ())
  (grain-distance 1.0)                    ; distance of sound source (<a href="sndclm.html#locsig">locsig</a>)
  (grain-distance-spread 0.0)             ; random spread around 'grain-distance'
  (grain-degree 45.0)
  (grain-degree-spread 0.0)
  (verbose #t)

(<a class=quiet href="#wsdoc">with-sound</a> (:channels 2 :reverb jc-reverb :reverb-channels 1)
  (grani 0 1 .5 "oboe.snd" :grain-envelope '(0 0 0.2 0.2 0.5 1 0.8 0.2 1 0)))
</pre>


<div class="seealso">
see also: &nbsp; <a href="sndclm.html#granulate">granulate</a> &nbsp; <a href="#expsrc">expsrc</a> &nbsp; <a href="extsnd.html#customcontrols">expand</a> 
</div>



<!--  FILE: heart  -->

<div class="header" id="heartdoc">heart</div>

<p>
Snd can be used with non-sound data, and <a href="#wsdoc">with-sound</a> makes it easy to
write such data to a sound file.  An example is heart.scm.  In this code, we search a file for blood pressure
readings (they are scattered around with a bunch of other stuff), then write those numbers to a stereo
sound file (the sphygmometer readings are between 70 and 150), then open that file in Snd with all the sound-related
clipping features turned off.  We also tell Snd to skip the data file in its start-up load process (since it
is an uninterpretable text file) by incrementing script-arg.
</p>
<img class="indented" src="pix/usync.png" alt="heart picture">



<!--  FILE: hooks  -->

<div class="header" id="hooksdoc">hooks</div>

<p>hooks.scm and hooks.rb have various <a href="extsnd.html#sndhooks">hook</a>-related functions.
</p>

<!-- describe-hook -->
<pre class="indented">
<em class=def id="describehook">describe-hook</em> hook
</pre>

<p>describe-hook tries to decipher the functions on the hook list; this is almost identical to hook-functions.
</p>

<div class="spacer"></div>

<!-- hook-member -->
<pre class="indented">
<em class=def id="hookmember">hook-member</em> func hook
</pre>

<p>hook-member returns #t if 'func' is already on the hook list, equivalent to
(member value (hook-functions hook))
</p>


<div class="spacer"></div>

<!-- reset-all-hooks -->
<pre class="indented">
<em class=def id="resetallhooks">reset-all-hooks</em> 
</pre>

<p>reset-all-hooks resets all of Snd's built-in hooks.
</p>

<div class="spacer"></div>

<!-- snd-hooks -->
<pre class="indented">
<em class=def id="sndscmhooks">snd-hooks</em> 
</pre>

<p>snd-hooks returns a list of all Snd built-in non-channel hooks.
</p>

<div class="spacer"></div>

<!-- with-local-hook -->
<pre class="indented">
<em class=def id="withlocalhook">with-local-hook</em> hook local-hook-procs thunk
</pre>

<p>with-local-hook is a kind of "let" for hooks; 
it evaluates 'thunk' with 'hook' set to 'local-hook-procs' (a list which can be nil), then restores 'hook' to its previous state upon exit.
The result returned by 'thunk' is returned by with-local-hook.
</p>




<!--  FILE: index  -->

<div class="header" id="indexdoc">index</div>

<pre class="indented">
<em class=def id="html">html</em> obj
</pre>

<p>index.scm provides a connection between firefox
and the Snd documentation.  The index itself is
built by make-index.scm, then accessed through the function html.
(html arg), where 'arg' can be a string, a symbol, or a procedure sends the html reader to the corresponding url
in the Snd documents.
</p>

<div class="seealso">
see also: &nbsp; <a href="extsnd.html#htmlprogram">html-program</a> &nbsp; <a href="extsnd.html#sndhelp">snd-help</a> &nbsp; <a href="extsnd.html#sndurls">snd-urls</a>
</div>




<!--  FILE: inf-snd.el, DotEmacs  -->

<div class="header" id="dotemacs">inf-snd.el, DotEmacs</div>

<p>These two files provide support for Snd as an Emacs subjob.  inf-snd.el is by Michael Scholz,
and DotEmacs is by Fernando Lopez-Lezcano. Both can be loaded in your ~/.emacs file (or ~/.xemacs/init.el if you're
using xemacs).
</p>
<p>
DotEmacs sets up "dialects" for various versions of Common Lisp and for Snd, then
binds C-x C-l to run ACL.  This is intended for CCRMA'S 220 class, but it might
be of interest to others.  Much fancier is inf-snd.el.  What follows is taken almost
verbatim from Mike Scholz's comments in that file:
</p>

<p>
inf-snd.el defines a snd-in-a-buffer package for Emacs.
It includes a Snd-Ruby mode (snd-ruby-mode), a Snd-Scheme mode
(snd-scheme-mode), and a Snd-Forth mode (snd-forth-mode) for editing source files. 
The commands inf-snd-help and snd-help
access the description which Snd provides for many functions.
Using the prefix key C-u you get the HTML version of Snd's help.
With tab-completion in the status area you can scan all functions at
a glance. 
A menu "Snd/Ruby" is placed in the Emacs menu bar.  Entries in this
menu are disabled if no inferior Snd process exists.
These variables may need to be customized to fit your system:
</p>

<pre class="indented">
inf-snd-ruby-program-name   "snd-ruby"    Snd-Ruby program name
inf-snd-scheme-program-name "snd-s7"      Snd-Scheme program name using s7
inf-snd-forth-program-name  "snd-forth"   Snd-Forth program name
inf-snd-working-directory   "~/"          where Ruby or Scheme scripts reside
inf-snd-index-path          "~/"          path to snd-xref.c
inf-snd-prompt-char         ">"           listener prompt
snd-ruby-mode-hook          nil           to customize snd-ruby-mode
snd-scheme-mode-hook         nil           to customize snd-scheme-mode
snd-forth-mode-hook         nil           to customize inf-snd-forth-mode
</pre>

<p>
You can start inf-snd-ruby-mode either with the prefix-key
(C-u M-x run-snd-ruby) &mdash; you will be asked for program name and
optional arguments &mdash; or directly via (M-x run-snd-ruby).  In the latter
case, the variable inf-snd-ruby-program-name needs to be set correctly.
inf-snd-scheme-mode and inf-snd-forth-mode are handled in the same way.
Here's an example for your ~/.emacs file:
</p>


<pre class="indented">
(autoload 'run-snd-ruby     "inf-snd" "Start inferior Snd-Ruby process" t)
(autoload 'run-snd-scheme    "inf-snd" "Start inferior Snd-Scheme process" t)
(autoload 'run-snd-forth    "inf-snd" "Start inferior Snd-Forth process" t)
(autoload 'snd-ruby-mode    "inf-snd" "Load snd-ruby-mode." t)
(autoload 'snd-scheme-mode   "inf-snd" "Load snd-scheme-mode." t)
(autoload 'snd-forth-mode   "inf-snd" "Load snd-forth-mode." t)

(setq inf-snd-ruby-program-name "snd-ruby -notebook")
(setq inf-snd-scheme-program-name "snd-scheme -separate")
(setq inf-snd-forth-program-name "snd-forth")
(setq inf-snd-working-directory "~/Snd/")
(setq inf-snd-index-path "~/Snd/snd/")
</pre>


<p>
See inf-snd.el for more info and examples of specializing these modes.
You can change the mode while editing a Snd-Ruby, Snd-Scheme, or Snd-Forth source file with
M-x snd-ruby-mode, M-x snd-scheme-mode, or M-x snd-forth-mode.  To have Emacs determine
automatically which mode to set, you can use special
file-extensions.  I use file-extension ".rbs" for Snd-Ruby source
files, ".cms" for Snd-Scheme, and ".fth" for Snd-Forth.
</p>


<pre class="indented">
(set-default 'auto-mode-alist
	     (append '(("\\.rbs$" . snd-ruby-mode)
                    ("\\.cms$" . snd-scheme-mode))
		     auto-mode-alist))
</pre>


<p>
Or you can use the local mode variable in source files, e.g. by
"-*- snd-ruby -*-" or "-*- snd-scheme -*-" in first line.
</p>

<p>
Key bindings for inf-* and snd-*-modes
</p>

<pre class="indented">
\e\TAB        snd-completion    symbol completion at point
C-h m         describe-mode     describe current major mode
</pre>

<p>
Key bindings of inf-snd-ruby|scheme|forth-mode:
</p>

<pre class="indented">
C-c C-s   	 inf-snd-run-snd   (Snd-Ruby|Scheme|Forth from a dead Snd process buffer)
M-C-l		 inf-snd-load      load script in current working directory
C-c C-f   	 inf-snd-file      open view-files-dialog of Snd
M-C-p		 inf-snd-play      play current sound file
C-c C-t 	 inf-snd-stop      stop playing all sound files
C-c C-i   	 inf-snd-help      help on Snd-function (snd-help)
C-u C-c C-i	 inf-snd-help-html help on Snd-function (html)
C-c C-q   	 inf-snd-quit      send exit to Snd process
C-c C-k   	 inf-snd-kill      kill Snd process and buffer
</pre>

<p>
Key bindings of snd-ruby|scheme|forth-mode editing source
files:
</p>

<pre class="indented">
C-c C-s   	 snd-run-snd
M-C-x     	 snd-send-definition
C-x C-e   	 snd-send-last-sexp
C-c M-e   	 snd-send-definition
C-c C-e   	 snd-send-definition-and-go
C-c M-r   	 snd-send-region
C-c C-r   	 snd-send-region-and-go
C-c M-o   	 snd-send-buffer
C-c C-o   	 snd-send-buffer-and-go
C-c M-b   	 snd-send-block          (Ruby only)
C-c C-b   	 snd-send-block-and-go   (Ruby only)
C-c C-z   	 snd-switch-to-snd
C-c C-l   	 snd-load-file
C-u C-c C-l 	 snd-load-file-protected (Ruby only)
C-c C-f   	 snd-file    	   open view-files-dialog of Snd
C-c C-p   	 snd-play    	   play current sound file
C-c C-t   	 snd-stop    	   stop playing all sound files
C-c C-i   	 snd-help    	   help on Snd-function (snd-help)
C-u C-c C-i	 snd-help-html	   help on Snd-function (html)
C-c C-q   	 snd-quit    	   send exit to Snd process
C-c C-k   	 snd-kill    	   kill Snd process and buffer
</pre>


<p>If xemacs complains that comint-snapshot-last-prompt is not defined,
get the latest comint.el; I had to go to the xemacs CVS site since
Fedora Core 5's xemacs (21.4) had an obsolete copy.  Then scrounge
around until you find xemacs-packages/xemacs-base/comint.el.
Don't use the comint.el in the emacs package.  It's not a tragedy
if this variable isn't defined &mdash; you just don't get a prompt in
the Snd Emacs window, but things still work.
If either emacs or
xemacs complains that it can't find gforth.el, you can find that
file in the gforth package or site (or perhaps you can comment out
the line (require 'forth-mode "gforth") in inf-snd.el).  Finally, if temporary-file-directory
is undefined, you can set it alongside the rest of the variables.
So, for example, I (Bill S) have the following in my ~/.xemacs/init.el:
</p>

<pre class="indented">
(setq load-path
      (append (list nil 
		    "/home/bil/cl"
		    "/home/bil/test/gforth-0.6.2" ; gforth.el
		    )
	      load-path))

(autoload 'run-snd-ruby     "inf-snd" "Start inferior Snd-Ruby process" t)
(autoload 'run-snd-scheme   "inf-snd" "Start inferior Snd-Scheme process" t)
(autoload 'run-snd-forth    "inf-snd" "Start inferior Snd-Forth process" t)
(autoload 'snd-ruby-mode    "inf-snd" "Load snd-ruby-mode." t)
(autoload 'snd-scheme-mode  "inf-snd" "Load snd-scheme-mode." t)
(autoload 'snd-forth-mode   "inf-snd" "Load snd-forth-mode." t)

(setq inf-snd-ruby-program-name "~/ruby-snd/snd") ; these are my local Snd's
(setq inf-snd-scheme-program-name "~/cl/snd")
(setq inf-snd-forth-program-name "~/forth-snd/snd")
(setq inf-snd-working-directory "~/cl/")
(setq inf-snd-index-path "~/cl/")
(setq inf-snd-working-directory   "~/cl/")
(setq inf-snd-index-path          "~/cl/")
(setq temporary-file-directory    "~/zap/")
</pre>


<p>If emacs complains about ruby-mode or something similar, you
probably need to get ruby-mode.el and inf-ruby.el from
ftp://ftp.ruby-lang.org/pub/ruby/ruby-*.tar.gz, or gforth.el from 
ftp://ftp.gnu.org/pub/gnu/gforth/gforth-0.[67].*.tar.gz. 
</p>



<!--  FILE: jcrev  -->

<div class="header" id="jcrevdoc">jcrev</div>

<p id="reverbexamples">
jc-reverb is a reverberator developed by John Chowning a long time ago
(I can't actually remember when &mdash; before 1976 probably), based 
on <a href="http://ccrma.stanford.edu/~jos/pasp/Schroeder_Reverberator_called_JCRev.html">ideas</a>
of Manfred Schroeder.
It "colors" the
sound much more than <a href="#clminsdoc">nrev</a>, and has noticeable echoes,
but I liked the effect a lot.  new-effects.scm has a version of jc-reverb
that runs as a normal snd editing function (via <a href="extsnd.html#mapchannel">map-channel</a>), whereas the
jcrev.scm version assumes it is being called within with-sound:
</p>

<pre class="indented">
Scheme:
    (with-sound (:reverb jc-reverb) (fm-violin 0 .1 440 .1 :reverb-amount .1))

Ruby:
    with_sound(:reverb, :jc_reverb) do fm_violin_rb(0, 0.1, 440, 0.1) end

Forth:
    0 1 440 0.2 ' fm-violin :reverb ' jc-reverb with-sound
</pre>

<p>jc-reverb has three parameters:
</p>

<pre class="indented">
<em class=def id="jcreverb">jc-reverb</em> low-pass (volume 1.0) amp-env
</pre>

<p>
if 'low-pass' if #t, a low pass filter is inserted before the output;
'volume' can be used to boost the output;
'amp-env' is an amplitude envelope that can be used to squelch the reverb ringing at the end of a piece.
</p>

<pre class="indented">
(<a class=quiet href="#wsdoc">with-sound</a> (:reverb jc-reverb :reverb-data '(#t 1.5 (0 0 1 1 2 1 3 0))) (fm-violin 0 .1 440 .1))
</pre>


<!-- INDEX reverbexamples:Reverb -->

<TABLE class="method">
<tr><td class="methodtitle">Reverbs in Snd</td></tr>
<tr><td>
<blockquote><small>
freeverb: <a href="#freeverbdoc">freeverb.scm, freeverb.rb</a><br>
jc-reverb: <a href="#jcrevdoc">jcrev.scm</a><br>
jl-reverb: <a href="#clminsdoc">clm-ins.scm</a><br>
nrev: <a href="#clminsdoc">clm-ins.scm</a><br>
control panel reverb: <a href="snd.html#reverb">Reverb</a>, <a href="extsnd.html#reverbdecay">control variables</a><br>
convolution reverb: <a href="extsnd.html#convolvewith">conrev</a><br>
*reverb*: <a href="#wsdoc">with-sound</a>
</small></blockquote>
</td></tr></TABLE>




<!--  FILE: lint  -->

<div class="header" id="lintdoc">lint</div>

<!-- main-index |lintdoc:lint for scheme -->

<p>lint.scm is a lint program for Scheme.  It tries to find errors or infelicities in your code.
To try  it:
</p>

<pre class="indented">
(lint "some-code.scm")
</pre>


<p>lint tries to reduce false positives, so its default is somewhat laconic.  There are several
variables at the start of lint.scm to control additional output:
</p>


<pre class="indented">
*report-unused-parameters*           ; if #t, report unused function/macro parameters
*report-unused-top-level-functions*  ; if #t, report unused functions
*report-undefined-variables*         ; if #t, report undefined identifiers
*report-shadowed-variables*          ; if #t, report function parameters that are shadowed
*report-minor-stuff*                 ; if #t, report all sorts of other stuff
</pre>


<p>lint is not real smart about functions defined outside the current file, so *report-undefined-variables*
sometimes is confused.  *report-minor-stuff* adds output about overly complicated boolean and numerical
expressions, dangerous floating point operations, bad docstrings (this check is easily confused), and
whatever else it finds that it thinks is odd.
</p>




<!--  FILE: maraca  -->

<div class="header" id="maracadoc">maraca</div>

<!-- main-index |maracadoc:maracas -->

<p>The maracas are physical models developed by Perry Cook (CMJ, vol 21 no 3 Fall 97, p 44).
</p>

<pre class="indented">
<em class=emdef>maraca</em> beg dur 
       (amp .1) 
       (sound-decay 0.95) 
       (system-decay 0.999) 
       (probability .0625)
       (shell-freq 3200.0)
       (shell-reso 0.96)

maraca: (<a class=quiet href="#wsdoc">with-sound</a> () (maraca 0 5 .5))
cabasa: (<a class=quiet href="#wsdoc">with-sound</a> () (maraca 0 5 .5 0.95 0.997 0.5 3000.0 0.7))

<em class=emdef>big-maraca</em> beg dur 
           (amp .1) 
           (sound-decay 0.95) 
           (system-decay 0.999) 
           (probability .0625)
           (shell-freqs '(3200.0))
           (shell-resos '(0.96))
           (randiff .01)
           (with-filters #t)

tambourine: 
    (<a class=quiet href="#wsdoc">with-sound</a> () 
      (big-maraca 0 1 .25 0.95 0.9985 .03125 '(2300 5600 8100) '(0.96 0.995 0.995) .01))

sleighbells: 
    (<a class=quiet href="#wsdoc">with-sound</a> () 
      (big-maraca 0 2 .15 0.97 0.9994 0.03125 '(2500 5300 6500 8300 9800) 
        '(0.999 0.999 0.999 0.999 0.999)))

sekere: 
    (<a class=quiet href="#wsdoc">with-sound</a> ()
      (big-maraca 0 2 .5 0.96 0.999 .0625 '(5500) '(0.6)))

windchimes: 
    (<a class=quiet href="#wsdoc">with-sound</a> () 
      (big-maraca 0 4 .5 0.99995 0.95 .001 '(2200 2800 3400) '(0.995 0.995 0.995) .01 #f))
</pre>

<p>
big-maraca is like maraca, but takes a list of resonances and includes low-pass filter (or no filter).
</p>

<div class="seealso">
see also: &nbsp; <a href="#noisedoc">noise</a> &nbsp; <a href="sndclm.html#randdoc">rand</a>
</div>




<!--  FILE: marks  -->

<div class="header" id="marksdoc">marks</div>

<p>marks.scm/rb is a collection of mark-related functions.
</p>


<!-- define-selection-via-marks -->
<pre class="indented">
<em class=def id="defineselectionviamarks">define-selection-via-marks</em> m1 m2
</pre>

<p>define-selection-via-marks selects the portion between the given marks, then returns the selection length.
The marks defining the selection bounds must be in the same channel.
</p>
<div class="spacer"></div>


<!-- describe-mark -->
<pre class="indented">
<em class=def id="describemark">describe-mark</em> mark
</pre>

<p>describe-mark returns a description of the movements of the mark over the channel's edit history:
</p>

<pre class="indented">
&gt; (define m (add-mark 1234))
m
&gt; (describe-mark m)
((#&lt;mark 1&gt; sound: 0 "oboe.snd" channel: 0) 1234 478)
</pre>

<p>Here I placed a mark in oboe.snd at sample 1234, then deleted a few samples
before it, causing it to move to sample 478.
</p>
<div class="spacer"></div>


<!-- fit-selection-between-marks -->
<pre class="indented">
<em class=def id="fitselectionbetweenmarks">fit-selection-between-marks</em> m1 m2
</pre>

<p>fit-selection-between-marks tries to squeeze the current selection between two marks,
using the granulate generator to fix up the selection duration (it currently does a less than perfect job).
</p>
<div class="spacer"></div>


<!-- mark-click-info -->
<pre class="indented">
<em class=def id="markclickinfo">mark-click-info</em> mark
</pre>

<p>mark-click-info is a <a href="extsnd.html#markclickhook">mark-click-hook</a> function that describes a mark and its properties.  It
is used by <a href="#withmarkedsound">with-marked-sound</a> in ws.scm.
</p>
<div class="spacer"></div>


<!-- mark-explode -->
<pre class="indented">
<em class=def id="markexplode">mark-explode</em> (htype mus-next) (dformat mus-bfloat)
</pre>

<p>mark-explode splits a sound into a bunch of separate files based on mark placements.  Each mark becomes the
first sample of a separate sound.
</p>
<div class="spacer"></div>


<!-- mark-name-&gt;id -->
<pre class="indented">
<em class=def id="marknametoid">mark-name-&gt;id</em> name
</pre>

<p>mark-name-&gt;id is like <a href="extsnd.html#findmark">find-mark</a>, but searches all currently accessible channels.
If a such a mark doesn't exist, it returns 'no-such-mark.
</p>
<div class="spacer"></div>


<!-- move-syncd-marks -->
<pre class="indented">
<em class=def id="movesyncdmarks">move-syncd-marks</em> sync samples-to-move
</pre>

<p>move-syncd-marks moves any marks sharing the <a href="extsnd.html#marksync">mark-sync</a> value 'sync' by
'samples-to-move' samples.  
</p>
<div class="spacer"></div>


<!-- pad-marks -->
<pre class="indented">
<em class=def id="padmarks">pad-marks</em> marks secs
</pre>

<p>pad-marks inserts 'secs' seconds of silence before each in a list of marks.
</p>
<div class="spacer"></div>


<!-- play-between-marks -->
<pre class="indented">
<em class=def id="playbetweenmarks">play-between-marks</em> snd m1 m2
</pre>

<p>play-between-marks
plays the portion in the sound 'snd' between the given marks.
</p>
<div class="spacer"></div>


<!-- play-syncd-marks -->
<pre class="indented">
<em class=def id="playsyncdmarks">play-syncd-marks</em> sync
</pre>

<p>play-syncd-marks starts
playing from all the marks sharing its 'sync' argument (see <a href="extsnd.html#marksync">mark-sync</a>).
</p>
<div class="spacer"></div>


<!-- report-mark-names -->
<pre class="indented">
<em class=def id="reportmarknames">report-mark-names</em> 
</pre>

<p>report-mark-names causes a named mark to display its name in the status area when 
its sample happens to be played.
</p>
<div class="spacer"></div>
  

<!-- save-mark-properties -->
<pre class="indented">
<em class=def id="savemarkproperties">save-mark-properties</em> 
</pre>

<p>save-mark-properties sets up an <a href="extsnd.html#aftersavestatehook">after-save-state-hook</a> function to save any mark-properties.
</p>
<div class="spacer"></div>
  

<!-- snap-mark-to-beat -->
<pre class="indented">
<em class=def id="snapmarktobeat">snap-mark-to-beat</em> 
</pre>

<p>snap-mark-to-beat forces a dragged mark to end up on a beat.
</p>
<div class="spacer"></div>


<!-- snap-marks -->
<pre class="indented">
<em class=def id="snapmarks">snap-marks</em> 
</pre>

<p>snap-marks places marks at the start and end of the current selection in all its portions (i.e. in every channel that
has selected data).
It returns a list of all the marks it has added.
</p>

<pre class="indented">
&gt; (selection-position)
360
&gt; (selection-framples)
259
&gt; (snap-marks)
(#&lt;mark 0&gt; #&lt;mark 1&gt;)
&gt; (mark-sample (integer-&gt;mark 0))
360
&gt; (mark-sample (integer-&gt;mark 1))
619
</pre>

<div class="spacer"></div>


<!-- syncup -->
<pre class="indented">
<em class=def id="syncup">syncup</em> marks
</pre>

<p>syncup synchronizes a list of marks (positions them all at the same sample number) by inserting silences as needed.
</p>

<p>marks.scm also has code that tries to make it simpler to sync marks together &mdash;
you just click the marks that should share a <a href="extsnd.html#marksync">mark-sync</a> field,
rather than laboriously setting each one in the listener;
see start-sync and stop-sync.
There is also some code (look for "eval-header" toward the end of the file) that saves mark info in a
sound file header, and reads it when the file is subsequently reopened.
</p>


<div class="seealso">
see also: &nbsp; <a href="#addmarkpane">add-mark-pane</a> &nbsp; <a href="extsnd.html#sndmarks">Marks</a> &nbsp; <a href="#markloops">mark-loops</a> &nbsp; <a href="#menusdoc">marks-menu</a>
</div>



<!--  FILE: maxf  -->

<div class="header" id="maxfdoc">maxf</div>

<p>These files are translations (thanks to Michael Scholz!) of CLM's maxf.ins
(thanks to Juan Reyes!). They implement a variant of the CLM <a href="sndclm.html#formant">formant</a> generator developed
by Max Mathews and Julius Smith (see their online <a href="http://ccrma.stanford.edu/~jos/smac03maxjos/">paper</a>).
For a version of the filter closer to the paper, see the <a href="sndclm.html#firmant">firmant</a> generator.
maxf.scm and maxf.rb provide a kind of demo instrument showing various ways to
use the filter (banks tuned to different sets of frequencies, etc).
</p>

<pre class="indented">
<em class=emdef>maxfilter</em> file beg (att 1.0) (numf 1) (freqfactor 1.0) (amplitude 1.0)
		    (amp-env '(0 1 100 1)) (degree (random 90.0)) (distance 1.0) (reverb-amount 0.2)
</pre>

<pre class="indented">
(<a class=quiet href="#wsdoc">with-sound</a> () (maxfilter "dog.snd" 0))
(<a class=quiet href="#wsdoc">with-sound</a> (:srate 44100) (maxfilter "dog.snd" 0 :numf 12))
(<a class=quiet href="#wsdoc">with-sound</a> (:srate 44100) (maxfilter "dog.snd" 0 :numf 13 :att 0.75))
(<a class=quiet href="#wsdoc">with-sound</a> (:srate 44100) (maxfilter "dog.snd" 0 :numf 2 :att 0.25 :freqfactor 0.5))
</pre>




<!--  FILE: menus  -->

<div class="header" id="menusdoc">menus</div>

<!-- main-index |menusdoc:menus, optional -->

<p>The files described in this section either add new top-level menus to Snd, or
modify existing ones.  Most were written by Dave Phillips.
</p>


<!-- edit-menu -->
<pre class="indented">
<em class=emdef>edit-menu.scm</em>
</pre>

<p>edit-menu.scm adds some useful options to the Edit menu:
</p>

<pre class="indented">
Selection-&gt;new      ; save selection in a new file, open that file
Cut selection-&gt;new  ; save selection in a new file, delete selection, open the file
Append selection    ; append selection to end of selected sound
Make stereofile     ; make a new 2-chan file, copy currently selected sound to it
Trim front          ; find first mark in each sync'd channel and remove all samples before it
Trim back           ; find last mark in each sync'd channel and remove all samples after it
Crop                ; find first and last mark in each sync'd channel and remove all samples outside them
</pre>

<!-- I(trim sound):M(Edit: Trim)(menusdoc) -->
<!-- I(trim sound):A(menusdoc) -->
<div class="separator"></div>



<!-- fft-menu.scm -->
<pre class="indented">
<em class=emdef>fft-menu.scm</em>
</pre>

<p>fft-menu.scm adds an "FFT Edits" top-level menu.  It has entries for:
</p>

<pre class="indented">
FFT notch filter   ; use FFT to notch out a portion of the spectrum
FFT squelch        ; use FFT to squelch low-level noise
Squelch vowels     ; use FFT to squelch vowel-like portions of speech
</pre>

<div class="separator"></div>


<!-- marks-menu.scm -->
<pre class="indented">
<em class=emdef>marks-menu.scm</em>
</pre>

<p>marks-menu.scm adds a "Marks" top-level menu with entries:
</p>

<pre class="indented">
Play between marks         ; play samples between marks
Loop play between marks    ; continuous play looping between marks
Trim before mark           ; remove samples before mark
Trim behind mark           ; remove samples after mark
Crop around marks          ; remove samples outside marks
Fit selection to marks     ; squeeze selection to fit between marks
Define selection by marks  ; define selection based on marks
Mark sync                  ; if on, click mark to sync with other marks
Mark sample loop points    ; place marks at header loop points, if any
Show loop editor           ; edit loop points; this dialog is not really functional yet
Delete all marks           ; delete all marks
Explode marks to files     ; writes a separate file for each set of marks
</pre>

<div class="separator"></div>


<!-- new-effects.scm -->
<pre class="indented">
<em class=emdef id="neweffectsdoc">new-effects.scm, effects-utils.scm, effects.rb, effects.fs</em>
</pre>

<p>new-effects.scm (effects.rb, effects.fs) implements an Effects menu.  
There are a ton of choices, most of them
presented in separate dialogs.  The gain dialog is illustrated below.
Some of the outer menu items are:
</p>

<table><tr><td>
<pre class="indented">
Amplitude effects (gain, normalize)
Delay effects (various echos)
Filter effects (various filters)
Frequency effects (src, expsrc)
Modulation effects (AM)
Reverbs (nrev, jcrev, convolution)
Various (flange, locsig, etc)
Octave down
Remove clicks
Remove DC
Compand
Reverse
</pre>

</td><td>
<img class="indented" src="pix/gain.png" alt="gain effect dialog">
</td></tr></table>

<!-- I(reverse samples):M(Effects: Reverse)(menusdoc) -->
<!-- I(reverberate file):M(Effects: Reverberate)(menusdoc) -->
<!-- I(normalize sound):M(Effects: Normalize)(menusdoc) -->
<!-- I(normalize sound):A(menusdoc) -->
<!-- I(normalize sound):L(scale-to)(scaleto) -->
<!-- I(insert zeros):M(Effects: Add Silence)(menusdoc) -->
<!-- I(change tempo):M(Effects: Expsrc)(menusdoc) -->

<p>Most of these are either simple calls on Snd functions ("invert" is (<a class=quiet href="extsnd.html#scaleby">scale-by</a> -1)),
or use functions in the other scm files.  The actual operations follow the <a class=quiet href="extsnd.html#sync">sync</a> chain of the
currently active channel.  
</p>
<div class="separator"></div>


<!-- special-menu.scm -->
<pre class="indented">
<em class=emdef>special-menu.scm</em>
</pre>

<p>special-menu.scm adds a "Special" menu with entries:
</p>

<pre class="indented">
Append file
MIDI to WAV (using Timidity)
Record input channel 
Envelope new file (see <a href="#enveddoc">start-enveloping</a>)
Play panned 
Save as MP3 (using bladeenc)
Save as Ogg (using oggenc)
Explode SF2 (using the code <a href="#explodesf2">explode-sf2</a> in examp.scm) 
</pre>


<p>
misc.scm loads these menus and interface improvements, adds several sound file extensions,
adds some hook functions for mpeg files,
and
includes a number of options such as show-disk-space.
It then adds these menu items:
</p>

<pre class="indented">
File:Delete                 ; delete the selected file
File:Rename                 ; rename the selected file
Edit:Append selection       ; append selection to end of current sound
Edit:Replace with selection ; put copy of selection at cursor
</pre>


<p>I think Dave expects you to customize this to suit yourself, perhaps even moving the stuff
you want to your initialization file.
</p>

<div class="seealso">
see also: &nbsp; <a href="extsnd.html#addtomainmenu">add-to-main-menu</a>.
</div>



<!--  FILE: mix  -->

<div class="header" id="mixdoc">mix</div>

<!-- main-index |mixdoc:cross-fade (amplitude) -->

<p>mix.scm provides various mix utilities. 
</p>

<!-- check-mix-tags -->
<pre class="indented">
<em class=def id="checkmixtags">check-mix-tags</em> snd chn
</pre>
check-mix-tags looks at the current mix tags in the given channel, and if any are
found that appear to be overlapping, it moves one of them down a ways.
<div class="spacer"></div>


<!-- color-mixes -->
<pre class="indented">
<em class=def id="colormixes">color-mixes</em> mix-list new-color
</pre>
color-mixes sets the color of each mix in 'mix-list' to 'new-color'.
<div class="spacer"></div>


<!-- delay-channel-mixes -->
<pre class="indented">
<em class=def id="delaychannelmixes">delay-channel-mixes</em> beg dur snd chn
</pre>
delay-channel-mixes adds dur (which can be negative) to the
begin time of each mix that starts after beg in the given channel.
<div class="spacer"></div>


<!-- env-mixes -->
<pre class="indented">
<em class=def id="envmixes">env-mixes</em> mix-list envelope
</pre>
env-mixes applies 'envelope' as an overall amplitude envelope to the mixes in 'mix-list'.
<div class="spacer"></div>


<!-- find-mix -->
<pre class="indented">
<em class=def id="findmix">find-mix</em> sample snd chn
</pre>
find-mix returns the identifier of the mix at sample 'sample' (or anywhere in the given channel if 
'sample' is not specified), or #f if no mix is found.
<div class="spacer"></div>


<!-- mix-click-info -->
<pre class="indented">
<em class=def id="mixclickinfo">mix-click-info</em> mix
</pre>
mix-click-info is a <a href="extsnd.html#mixclickhook">mix-click-hook</a> function that posts a description of the
clicked mix in the help dialog.
<div class="spacer"></div>


<!-- mix-click-sets-amp -->
<pre class="indented">
<em class=def id="mixclicksetsamp">mix-click-sets-amp</em> 
</pre>
mix-click-sets-amp adds a <a href="extsnd.html#mixclickhook">mix-click-hook</a> function so that 
if you click a mix, it is removed (its amplitude is set to 0.0);
a subsequent click resets it to its previous value.
This is intended to make it easy to compare renditions with and without a given mix.
<div class="spacer"></div>


<!-- mix-maxamp -->
<pre class="indented">
<em class=def id="mixmaxamp">mix-maxamp</em> mix
</pre>
mix-maxamp returns the maxamp in the given mix.
<div class="spacer"></div>


<!-- mix-name->id -->
<pre class="indented">
<em class=def id="mixnametoid">mix-name-&gt;id</em> name
</pre>
mix-name-&gt;id returns the mix with the given name, or 'no-such-mix if none can be found.
<div class="spacer"></div>


<!-- mix-sound -->
<pre class="indented">
<em class=def id="mixsound">mix-sound</em> file start
</pre>
mix-sound mixes 'file' (all chans) into the currently selected sound at 'start'.
<div class="spacer"></div>


<!-- mix->float-vector -->
<pre class="indented">
<em class=def id="mixtofv">mix-&gt;float-vector</em> mix
</pre>
mix-&gt;float-vector returns a mix's samples in a float-vector.
<div class="spacer"></div>


<!-- mixes-length -->
<pre class="indented">
<em class=emdef>mixes-length</em> mix-list
</pre>
mixes-length returns the number of samples between the start of the first mix in 'mix-list' and
the last end point.
<div class="spacer"></div>


<!-- mixes-maxamp -->
<pre class="indented">
<em class=emdef>mixes-maxamp</em> mix-list
</pre>
mixes-maxamp returns the maxamp of the mixes in 'mix-list'.
<div class="spacer"></div>


<!-- move-mixes -->
<pre class="indented">
<em class=def id="movemixes">move-mixes</em> mix-list samps
</pre>
move-mixes moves each mix in 'mix-list' by 'samps' samples.  To move all sync'd mixes together whenever one of them is dragged:

<pre class="indented">
(hook-push <a class=quiet href="extsnd.html#mixreleasehook">mix-release-hook</a>
	   (lambda (hook)
	     (let* ((id (hook 'id))
	            (samps-moved (hook 'samples))
                    (result (= (<a class=quiet href="extsnd.html#mixsync">mix-sync</a> id) 0)))
	       (if (not result)
		   (<em class=red>move-mixes</em> (<a class=quiet href="#syncdmixes">syncd-mixes</a> (<a class=quiet href="extsnd.html#mixsync">mix-sync</a> id)) samps-moved))
	       (set! (hook 'result) result))))
</pre>

<p>See also <a href="#snapmixtobeat">snap-syncd-mixes-to-beat</a>. </p>



<!-- pan-mix -->
<pre class="indented">
<em class=def id="panmix">pan-mix</em> file beg env snd auto-delete
</pre>
<p>pan-mix
mixes 'file' into the current sound starting at 'beg' using the envelope 'env'
to pan the mixed samples (0: all chan 1, 1: all chan 0).
So, 
</p>

<pre class="indented">
(pan-mix "oboe.snd" 1000 '(0 0 1 1))
</pre>

<p>goes from all chan 0 to all chan 1.
'auto-delete' determines
whether the in-coming file should be treated as a temporary file and deleted when the mix
is no longer accessible.
</p>
<div class="spacer"></div>


<!-- pan-mix-region -->
<pre class="indented">
<em class=emdef>pan-mix-region</em> region beg env snd
</pre>
pan-mix-region is similar to pan-mix above, but mixes a region, rather than a file.
<div class="spacer"></div>


<!-- pan-mix-selection -->
<pre class="indented">
<em class=emdef>pan-mix-selection</em> beg env snd
</pre>
pan-mix-selection is similar to pan-mix above, but mixes the current selection, rather than a file.
<div class="spacer"></div>


<!-- pan-mix-float-vector -->
<pre class="indented">
<em class=def id="panmixfv">pan-mix-float-vector</em> data beg env snd
</pre>
pan-mix-float-vector is similar to pan-mix above, but mixes a float-vector, rather than a file.
The argument 'data' represents one channel of sound.
To sync all the panned mixes together:

<pre class="indented">
(let ((new-sync (+ 1 (<a class=quiet href="extsnd.html#mixsyncmax">mix-sync-max</a>))))
  (for-each
    (lambda (id)
     (set! (<a class=quiet href="extsnd.html#mixsync">mix-sync</a> id) new-sync))
   (<em class=red>pan-mix-float-vector</em> (make-float-vector 10 0.5) 100 '(0 0 1 1))))
</pre>

<div class="spacer"></div>


<!-- play-mixes -->
<pre class="indented">
<em class=def id="playmixes">play-mixes</em> mix-list
</pre>
play-mixes plays the mixes in 'mix-list'.
<div class="spacer"></div>


<!-- scale-mixes -->
<pre class="indented">
<em class=def id="scalemixes">scale-mixes</em> mix-list scl
</pre>
scale-mixes scales the amplitude of each mix in 'mix-list' by 'scl'.
<div class="spacer"></div>


<!-- scale-tempo -->
<pre class="indented">
<em class=def id="scaletempo">scale-tempo</em> mix-list scl
</pre>
scale-tempo changes the positions of the mixes in 'mix-list' to reflect a tempo change of 'scl'.
(scale-tempo (mixes 0 0) 2.0) makes the mixes in snd 0, chan 0 happen twice as slowly.
To reverse the order of the mixes: (scale-tempo (mixes 0 0) -1).
<div class="spacer"></div>


<!-- set-mixes-tag-y -->
<pre class="indented">
<em class=emdef>set-mixes-tag-y</em> mix-list new-y
</pre>
set-mixes-tag-y sets the tag y location of each mix in 'mix-list' to 'new-y'.
<div class="spacer"></div>


<!-- silence-all-mixes -->
<pre class="indented">
<em class=def id="silenceallmixes">silence-all-mixes</em> 
</pre>
This sets all mix amplitudes to 0.0.
<div class="spacer"></div>


<!-- silence-mixes -->
<pre class="indented">
<em class=def id="silencemixes">silence-mixes</em> mix-list
</pre>
silence-mixes sets the amplitude of each mix in 'mix-list' to 0.0.
<div class="spacer"></div>


<!-- snap-mix-to-beat -->
<pre class="indented">
<em class=def id="snapmixtobeat">snap-mix-to-beat</em> 
</pre>
snap-mix-to-beat forces a dragged mix to end up on a beat (see <a href="extsnd.html#xaxisstyle">x-axis-in-beats</a>).
To turn this off, (hook-remove mix-release-hook snap-mix-1).  To snap the dragged mix,
and every other mix syncd to it, use snap-syncd-mixes-to-beat.
<div class="spacer"></div>


<!-- src-mixes -->
<pre class="indented">
<em class=def id="srcmixes">src-mixes</em> mix-list scl
</pre>
src-mixes scales the speed (resampling ratio) of each mix in 'mix-list' by 'scl'.
<div class="spacer"></div>


<!-- sync-all-mixes -->
<pre class="indented">
<em class=emdef>sync-all-mixes</em> (new-sync 1)
</pre>
sync-all-mixes sets the mix-sync field of every active mix to 'new-sync'.
<div class="spacer"></div>


<!-- syncd-mixes -->
<pre class="indented">
<em class=def id="syncdmixes">syncd-mixes</em> sync
</pre>
syncd-mixes returns a list (possibly null) of all mixes whose mix-sync field is set to 'sync'.
Most of the functions in mix.scm take a 'mix-list'; to form that list based on a given
mix-sync value, use syncd-mixes:

<pre class="indented">	
(<a class=quiet href="#scalemixes">scale-mixes</a> (syncd-mixes 2) 2.0)
</pre>

which scales the amplitude by 2.0 of any mix whose mix-sync field is 2.
<div class="spacer"></div>


<!-- transpose-mixes -->
<pre class="indented">
<em class=def id="transposemixes">transpose-mixes</em> mix-list semitones
</pre>
transpose-mixes sets the speed of mix in 'mix-list' to cause a transposition by the given number of semitones.

<div class="spacer"></div>
<div class="seealso">
see also: &nbsp; <a href="extsnd.html#sndmixes">Mixes</a> &nbsp; <a href="snd.html#mixingfiles">View:Mix</a> &nbsp; <a href="#mixchannel">mix-channel</a> &nbsp; <a href="#fadedoc">dissolve-fade</a> &nbsp; <a href="#musfilemix">mus-file-mix</a>
</div>




<!--  FILE: moog  -->

<div class="header" id="moogdoc">moog</div>

<pre class="indented">
<em class=emdef>make-moog-filter</em> frequency Q
<em class=def id="moogfilter">moog-filter</em> gen input
</pre>

<p>moog is a translation of CLM's moog.lisp (written by Fernando Lopez-Lezcano &mdash;
http://ccrma.stanford.edu/~nando/clm/moog),
itself a translation of Tim Stilson's original C code.  The functions provide
a kind of CLM generator view of the filter.  Fernando describes it as a
"Moog style four pole lowpass (24db/Oct) filter clm unit generator,
variable resonance, warm, analog sound ;-)". <!-- ( -->
In make-moog-filter, 'frequency' is the cutoff frequency
in Hz (more or less) and 'Q' controls the resonance: 0.0 = no resonance, whereas
1.0 causes the filter to oscillate at 'frequency'. 
</p>

<pre class="indented">
(define (moog freq Q)
  (let ((gen (<em class=red>make-moog-filter</em> freq Q)))
    (lambda (inval)
      (<em class=red>moog-filter</em> gen inval))))

(<a class=quiet href="extsnd.html#mapchannel">map-channel</a> (moog 1200.0 .7))
</pre>

<p>The Ruby version of this is in examp.rb, and the Forth version is in examp.fs.
</p>



<!--  FILE: musglyphs  -->

<div class="header" id="musglyphs">musglyphs</div>

<p>musglyphs.scm provides Scheme/Snd wrappers to load CMN's cmn-glyphs.lisp (directly!),
thereby defining most of the standard music notation symbols.  Each of the original
functions (e.g. draw-bass-clef) becomes a Snd/Scheme procedure of the form
(name x y size style snd chn context). 
(draw-bass-clef 100 100 50) draws a bass clef in the current graph
at position (100 100) of size 50; since the 'style' argument defaults to
#f, the clef is displayed as a filled polygon; use #t to get an outline of
the clef instead.
</p>
<img class="indented" src="pix/sndcmn.png" alt="Snd with music symbols">

<p>
A fancier <a href="extsnd.html#waltzexample">example</a> is included in musglyphs.scm.  It takes a list of notes, each mixed as a virtual mix,
and displays the note pitches as music notation on two staves at the top of the graph. The two main
drawing functions are draw-staff and draw-a-note.  The staves are drawn via an <a href="extsnd.html#aftergraphhook">after-graph-hook</a>
function, and the notes are displayed via <a href="extsnd.html#drawmixhook">draw-mix-hook</a>.  
<a href="extsnd.html#mixwaveformheight">mix-waveform-height</a> sets the overall size of the music notation.
The note list data is passed into these functions by setting various <a href="extsnd.html#mixproperties">mix-properties</a>:
'frequency and 'instrument (the first to give the pitch, the second the staff).
</p>
<p>There's also an even fancier version of the same thing that treats the note heads as the mix tags, and
changes the mix pitch if you drag the note up or down.
</p>



<!--  FILE: nb  -->

<div class="header" id="nbdoc">nb</div>

<p>nb.scm provides popup help for files in the View:Files dialog.  As you move
the mouse through the file list, the help dialog posts information about the file
underneath the mouse.  This uses a slightly fancier file information procedure
than <a href="#finfo">finfo</a> in examp.scm. 
</p>
<!-- main-index |nbdoc:file database -->

<pre class="indented">
<em class=emdef>nb</em> file note
<em class=emdef>unb</em> file
<em class=emdef>prune-db</em> 
</pre>

<p>nb adds 'note' to the info associated with a file: (nb "test.snd" "test's info").
unb erases any info pertaining to a file: (unb "test.snd").
prune-db removes any info associated with defunct files.
The Ruby version of nb (written by Mike Scholz) has several other features &mdash; see nb.rb
for details.
</p>



<!--  FILE: noise  -->

<div class="header" id="noisedoc">noise</div>

<p>The noise files are translations (thanks to Michael Scholz) of CLM's noise.ins.
noise.ins has a very long pedigree; I think it dates back to about 1978.  It can produce
those all-important whooshing sounds.
</p>

<pre class="indented">
<em class=def id="fmnoise">fm-noise</em> startime dur freq0 amp ampfun ampat ampdc
   freq1 glissfun freqat freqdc rfreq0 rfreq1 rfreqfun rfreqat rfreqdc
   dev0 dev1 devfun devat devdc
   (degree 0.0) (distance 1.0) (reverb-amount 0.005)
</pre>

<p>
This is an old instrument, so one must make allowances.  'ampat' and 'ampdc'
are the amplitude envelope ('ampfun') attack and decay times, and similarly for
the frequency envelope 'glissfun', the random number frequency envelope 'rfreqfun'
and the index envelope 'devfun' (dev = "deviation", and old radio-style name for the
FM index).  Each envelope must go on the x axis from 0 to 100; the attack portion ends
at 25, the decay portion starts at 75 (once upon a time there was
a generator named LINEN; his full name was Line-Segment Envelope, but everyone
just called him LINEN; they had to shout because he was a bit deaf).
'rfreq' is the frequency of the random number generator;
if it is below about 25 Hz, you get automatic composition; above that
you start to get noise.  Well, you get a different kind of noise.
'dev' is the bandwidth of the noise; very narrow 'dev' gives a
whistle, very broad more of a whoosh.  This is simple FM 
where the modulating signal is white noise.
</p>

<pre class="indented">
(<a class=quiet href="#wsdoc">with-sound</a> ()
  (fm-noise 0 2.0 500 0.25 '(0 0 25 1 75 1 100 0) 0.1 0.1 1000 '(0 0 100 1) 0.1 0.1
            10 1000 '(0 0 100 1) 0 0 100 500 '(0 0 100 1) 0 0))
</pre>

<p>
There is also a generator-like version of the instrument:
</p>

<pre class="indented">
<em class=emdef>make-fm-noise</em> len freq (amp 0.25) (ampfun '(0 0 25 1 75 1 100 0)) (ampat 0.1)
              (ampdc 0.1) (freq1 1000) (glissfun '(0 0 100 1)) (freqat 0.1) (freqdc 0.1)
              (rfreq0 10) (rfreq1 1000) (rfreqfun '(0 0 100 1)) (rfreqat 0) (rfreqdc 0)
              (dev0 100) (dev1 500) (devfun '(0 0 100 1)) (devat 0) (devdc 0) 
              (degree (random 90.0)) (distance 1.0) (reverb-amount 0.005)
</pre>


<div class="seealso">
see also: &nbsp; <a href="#maracadoc">maraca</a> &nbsp; <a href="sndclm.html#randdoc">rand</a>
</div>




<!--  FILE: numerics  -->

<div class="header" id="numericsdoc">numerics</div>

<p>This file has a variety of functions oriented toward some experiments that
so far haven't panned out.
</p>

<pre class="indented">
<em class=emdef>factorial</em> n
<em class=emdef>binomial</em> n k
<em class=emdef>n-choose-k</em> n k
<em class=emdef>plgndr</em> l m x
<em class=emdef>legendre-polynomial</em> a x
<em class=emdef>legendre</em> n x
<em class=emdef>gegenbauer</em> n x (alpha 0.0)
<em class=emdef>chebyshev-polynomial</em> a x (kind 1)
<em class=emdef>chebyshev</em> n x (kind 1)
<em class=emdef>hermite-polynomial</em> a x
<em class=emdef>hermite</em> n x
<em class=emdef>laguerre-polynomial</em> a x (alpha 0.0)
<em class=emdef>laguerre</em> n x (alpha 0.0)
<em class=emdef>Si</em> x
<em class=emdef>Ci</em> x
<em class=emdef>sin-m*pi/n</em> m n
<em class=emdef>show-digits-of-pi-starting-at-digit</em> start
</pre>

<p>In this case, "the code is the documentation" &mdash; these functions
are informal, experimental, etc.
One amusing function is sin-m*pi/n.  It
returns an expression giving the exact value of sin(m*pi/n), m and n integer,
if we can handle n.  Currently n can be anything of the form 2^a 3^b 5^c 7^d 11^e 13^f 17^g 257^h,
so (sin-m*pi/n 1 60) returns an exact expression for sin(pi/60).  The expression is not reduced
much.
</p>

<pre class="indented">
&gt; (sin-m*pi/n 1 9)
(/ (- (expt (+ (sqrt 1/4) (* 0+1i (sqrt 3/4))) 1/3) (expt (- (sqrt 1/4) (* 0+1i (sqrt 3/4))) 1/3)) 0+2i)
&gt; (eval (sin-m*pi/n 1 9))
0.34202014332567
&gt; (sin (/ pi 9))
0.34202014332567
&gt; (sin (/ pi (* 257 17)))
0.00071906440440859
&gt; (eval (sin-m*pi/n 1 (* 17 257)))
0.00071906440440875
</pre>

<p>Another amusing function is show-digits-of-pi-starting-at-digit, translated from a C program
written by David Bailey.  It shows 10 (hex) digits of the expansion of pi starting from any
point in that expansion.
</p>



<!--  FILE: peak-phases  -->

<div class="header" id="peakphasesdoc">peak-phases</div>

<p>peak-phases.scm contains the phases that produce a minimum peak amplitude ("low peak-factor") sum of sinusoids,
the unpulse-train, so to speak.  I started with the questions: given a sum of
n equal amplitude harmonically related sinusoids, what set of initial phases minimizes
the peak amplitude?  What is that peak as a function of n?  Can we find any pattern
to the initial phases so that a tiresome search is unnecessary?  For the second question,
there are several simple cases.  If all harmonics are cosines, the peak amplitude is
n (they all are 1 at the start).  If we have 2 harmonics, and vary the initial phase of
the second from 0.0 to 2*pi, graphing the resulting peak amplitude, we get:
</p>

<img class="indented" src="pix/noid2.png" alt="n=2 case">
<img class="indented" src="pix/sum2.png" alt="n=2 case">

<p>The graph on the left is the second harmonic's initial phase vs the peak amplitude.  Since 0.0
appears to be a minimum (we can show that it is via simultaneous non-linear equations; see peak-phases.scm), 
we can solve for the peak at that point using calculus: differentiate
sin(x) + sin(2x) to get cos(x) + 2cos(2x) = 4cos^2(x) + cos(x) -2, a quadratic equation
in cos(x).  Let y=cos(x), solve for y: (sqrt(33)-1)/8.  Plug that back into the original
equation (x=acos(y) = 0.93592945566133), and get 1.7601725930461.  Looking back at the
peak-amplitude graph, it appears that the peak varies as approximately 1.76+0.24*abs(sin(initial-phase)).
If we graph the peak location, we see that it is moving (nearly) linearly with the initial-phase from the
0.9359 business given above to the corresponding peak location when the initial-phase is pi (acos((1-sqrt(33))/8) = 2.20566),
then the two peaks cross, and the other one predominates from pi to 2*pi. So the peak amplitude as
a function of the initial-phase ("phi" below) is (very nearly):
</p>

<pre class="indented">
(let ((a (acos (/ (- (sqrt 33) 1) 8)))
      (b (acos (/ (- 1 (sqrt 33)) 8))))
  (let ((ax (+ b (* (- phi pi) (/ (- a b) pi))))      ; same for peak 2 (the peak when phi is pi..2pi)
        (bx (let ((ap (- (* 2 pi) a))                 ; start location of peak 1 (the peak when phi is 0..pi)
	          (bp (- (* 2 pi) b)))                ; end location of peak 1 
              (+ ap (* phi (/ (- bp ap) pi))))))      ; the 2 peaks move in opposite directions
    (max (abs (+ (sin ax) (sin (+ (* 2 ax) phi))))    ; plug in the 2 locations and
         (abs (+ (sin bx) (sin (+ (* 2 bx) phi))))))) ;   return the max 
</pre>
 
<!--
(with-full-sound (:clipped #f :channels 2 :statistics #t :output "n2a.snd")
  (let ((size 10000))
     (let ((i 0)
	   (incr (/ (* 2 pi) size)))
      (do ((phi1 0.0 (+ phi1 incr))
	   (j 0 (+ j 1)))
	  ((= j size))
	(let ((pk 0.0)
	      (loc 0.0))
	  (do ((x 0.0 (+ x incr))
	       (n 0 (+ n 1)))
	      ((= n size))
	    (let ((val (+ (sin x)
			  (sin (+ (* 2 x) phi1)))))
	      (if (> (abs val) pk)
		  (begin
		    (set! pk (abs val))
		    (set! loc x)))))
	  (outa i pk)
	  (let* ((a 9.359294556613259736065597353788460035329E-1)
		 (b 2.205663197928467264856083647900656880662E0)
		 (ap (- (* 2 pi) a))
		 (bp (- (* 2 pi) b))
		 (ax (+ b (* (- phi1 pi) (/ (- a b) pi))))
		 (bx (+ ap (* phi1 (/ (- bp ap) pi)))))
	    (outb i (max (abs (+ (sin ax) (sin (+ (* 2 ax) phi1))))
			 (abs (+ (sin bx) (sin (+ (* 2 bx) phi1)))))))
	  (set! i (+ i 1)))))))
-->
<p>
We can reduce the peak difference below .00000002 by using:
</p>

<pre class="indented">
  (let ((waver (+ (* .002565 (sin (* 2 phi)))
                   (* .0003645 (sin (* 4 phi)))
                   (* .0001 (sin (* 6 phi)))
                   (* .00004 (sin (* 8 phi)))
                   (* .00002 (sin (* 10 phi)))
                   (* .00001 (sin (* 12 phi)))
                   (* .0000035 (sin (* 14 phi))))))
    (let ((ax (- (+ b (* (- phi pi) (/ (- a b) pi))) waver))
          (bx (- (+ ap (* phi (/ (- bp ap) pi))) waver)))
      ...))
</pre>

<p>
Similarly sin(x)+sin(3x) differentiated is cos(x)+3cos(3x) = 12cos^3(x)-8cos(x).  cos(x)=0
is a minimum of the original, but the other case is acos(sqrt(2/3)) = 0.61547970867039,
and plugging that into the original gives 1.539600717839.  If we vary the sin(3x) term's
initial phase, we get approximately 1.5396 + 0.4604 * sin(initial-phase).
As before, the location of the peak varies nearly linearly with the initial-phase, the end point
now being acos(-(sqrt(2/3))):
</p>

<pre class="indented">
  (let* ((a (acos (sqrt 2/3)))
	 (b (acos (- (sqrt 2/3))))
	 (ax (let ((ap (- (* 2 pi) a))                    ; start loc peak 1
	           (bp (- (* 2 pi) b)))                   ; end loc
               (+ ap (* phi (/ (- bp ap) 2 pi)))))        ; peak 1 
	 (bx (- ax pi)))                                  ; peak 2 (the two interleave)
    (max (abs (+ (sin ax) (sin (+ (* 3 ax) phi))))        ; plug in our 2 peak locations
	 (abs (+ (sin bx) (sin (+ (* 3 bx) phi))))))      ;   and return the max
</pre>


<!--
(with-full-sound (:clipped #f :channels 2 :statistics #t :output "n2b.snd")
  (let ((size 10000))
     (let ((i 0)
	   (incr (/ (* 2 pi) size)))
      (do ((phi1 0.0 (+ phi1 incr))
	   (j 0 (+ j 1)))
	  ((= j size))
	(let ((pk 0.0)
	      (loc 0.0))
	  (do ((x 0.0 (+ x incr))
	       (n 0 (+ n 1)))
	      ((= n size))
	    (let ((val (+ (sin x)
			  (sin (+ (* 3 x) phi1)))))
	      (if (> (abs val) pk)
		  (begin
		    (set! pk (abs val))
		    (set! loc x)))))
	  (outa i pk)
	  (let* ((a 6.154797086703873410674645891239936878517E-1) ; acos(sqrt(2/3))
		 (b 2.526112944919405897395178794155509196341E0)  ; acos(-sqrt(2/3))
		 (ap (- (* 2 pi) a))                              ; start loc peak 1
		 (bp (- (* 2 pi) b))                              ; end loc
		 (ax (+ ap (* phi1 (/ (- bp ap) (* 2 pi)))))      ; peak 1 
		 (bx (- ax pi)))                                  ; peak 2 (the two interleave)
	    (outb i (max (abs (+ (sin ax) (sin (+ (* 3 ax) phi1))))
			 (abs (+ (sin bx) (sin (+ (* 3 bx) phi1)))))))
	  (set! i (+ i 1)))))))
-->
<p>
sin(x)+sin(5x+a) becomes a quadratic in cos^2(x), so we can find the peak location as a function
of the initial-phase:
</p>

<pre class="indented">
  (let* ((a0 (* pi 1/2))
	 (a1 (acos (sqrt (/ (- 25 (sqrt 145)) 40))))
	 (ax (+ a0 (/ (* (- a1 a0) phi) pi)))
	 (bx (+ pi ax))
	 (cx (- a0 (/ (* (- a1 a0) (- (* 2 pi) phi)) pi)))
	 (dx (+ cx pi)))
   (max (abs (+ (sin ax) (sin (+ (* 5 ax) phi))))
	(abs (+ (sin bx) (sin (+ (* 5 bx) phi))))
	(abs (+ (sin cx) (sin (+ (* 5 cx) phi))))
	(abs (+ (sin dx) (sin (+ (* 5 dx) phi))))))
</pre>

<!--
(with-full-sound (:clipped #f :channels 3 :statistics #t :output "n2e.snd")
  (let ((size 10000))
     (let ((i 0)
	   (incr (/ (* 2 pi) size)))
      (do ((phi1 0.0 (+ phi1 incr))
	   (j 0 (+ j 1)))
	  ((= j size))
	(let ((pk 0.0)
	      (loc 0.0))
	  (do ((x 0.0 (+ x incr))
	       (n 0 (+ n 1)))
	      ((= n size))
	    (let ((val (+ (sin x)
			  (sin (+ (* 5 x) phi1)))))
	      (if (> (abs val) pk)
		  (begin
		    (set! pk (abs val))
		    (set! loc x)))))
	  (outa i pk)
	  (let* ((a0 (* pi 1/2))
		 (a1 (acos (sqrt (/ (- 25 (sqrt 145)) 40))))
		 (ax (+ a0 (/ (* (- a1 a0) phi1) pi)))
		 (bx (+ pi ax))
		 (cx (- a0 (/ (* (- a1 a0) (- (* 2 pi) phi1)) pi)))
		 (dx (+ cx pi)))
	    (outb i (max (abs (+ (sin ax) (sin (+ (* 5 ax) phi1))))
			 (abs (+ (sin bx) (sin (+ (* 5 bx) phi1))))
			 (abs (+ (sin cx) (sin (+ (* 5 cx) phi1))))
			 (abs (+ (sin dx) (sin (+ (* 5 dx) phi1)))))))
	  (outc i loc)
	  (set! i (+ i 1)))))))

-->

<p>but now we have four peaks to track.  The minimum peak is at initial-phase of pi,
and is 1.81571610422.  
sin(x)+sin(4x+a) is much messier to handle in this manner when a=0 because it ends up in a quartic equation in cos(x).
A glance at the derivative, cos(x)+4*cos(4x+a), shows there is a 0 at (x=0, a=acos(-1/4)),
(x=pi, a=acos(1/4)), (x=pi/2, a=pi/2) and so on, but these points do not seem to be at maxima of the original.
A brute force search finds that the minimum peak (which is at initial-phase of 0) is at 1.940859829001 and is 1.9282082241513.
We could also use poly-roots in poly.scm:
</p>

<pre class="indented">
  &gt; (map (lambda (y) 
          (+ (sin y) (sin (* 4 y)))) 
        (map acos (poly-roots (float-vector 4 1 -32 0 32)))) ; 4 + cos(x) - 32cos^2(x) + 32cos^4(x)
  (... 1.928208224151313892413267491649096952858E0 ...)
</pre>

<p>
I think in the sin(x)+sin(nx+a) case there's a minimum at a=pi, except when n=4k+3,
and the peak itself (at either pi/2 or 3pi/2) approaches 2 as n increases.
sin-nx-peak in numerics.scm searches for this peak, and for reasonable "n"
it can be compared to the equivalent search using poly-roots in poly.scm:
</p>

<pre class="indented">
  &gt; (sin-nx-peak 6)
  (1.966832009581999989057660894590273760791E0 ...)
  (map (lambda (y) 
         (+ (sin y) (sin (* 6 y)))) 
       (map acos (poly-roots (float-vector -6 1 108 0 -288 0 192)))) ; n*Tn + cos(x)
  (1.966832009581999989057661205729776550611E0 ...)
</pre>

<p>
Another case that is not too hard involves a sum of
n sines all at 0 initial phase.  This can be expressed as:
</p>

<img class="indented" src="pix/sceq1.png" alt="sum of sines">

<p>which is the nsin generator in clm. Since the waveform is a two-sided
pulse with the first local maximum at the peak, we can easily search for that peak as n increases.
We find that it is approaching (3*pi)/(4*n), and if we plug that into the original equation,
we get that the peak amplitude approaches 8*n*(sin^2(3*pi/8))/(3*pi), about 0.7245 * n
(using the right hand expression above, set x to (3*pi)/(4*n), let n be large,
so (n+1)/n approaches 1 and sin(y) is close to y if it is very small).
A sum of n odd harmonics behaves similarly (the peak comes half as far from the zero crossing,
but has the same max).  A sum of n sines of alternating sign also has the same peak amp,
but now the peak is at pi-(3*pi)/(4*n).  
Those are the easy cases.  The next case involves 3 harmonics,
where we vary the second and third harmonic's initial phase, looking for the minimum peak amplitude.
One view of this terrain has the second harmonic's initial phase on the Y axis, the third's on the X axis,
and the color for the height of the corresponding peak:
</p>

<!--
(define (deriv n x)
  (+ (- (/ (* (cos (/ x 2))
	      (sin (/ (* n x) 2))
	      (sin (/ (* (+ n 1) x) 2)))
	   (* 2 (sin (/ x 2)) (sin (/ x 2)))))
     (/ (* n 
	   (cos (/ (* n x) 2))
	   (sin (/ (* (+ n 1) x) 2)))
	(* 2 (sin (/ x 2))))
     (/ (* (+ n 1)
	   (sin (/ (* n x) 2))
	   (cos (/ (* (+ n 1) x) 2)))
	(* 2 (sin (/ x 2))))))

which is hard to nail down; the zero crossing is 3pi/4n, I think, but numerically this is not anywhere near 0!

:(deriv 10000 (- (/ (* 3 pi) 40000) .00001))
2230252.363045
:(deriv 10000 (+ (/ (* 3 pi) 40000) .00001))
-3641295.807378
:(deriv 10000 (+ (/ (* 3 pi) 40000) 0.0))
-742517.21842268
which is also the case in gmp

The curve of the derivative looks very much like the two-sided sine pulse coming from n/2? down, crossing near 3pi/4n

lim n->inf sum k=1 to n kcos(3kpi/4n) = 0
at n = 1e9, the actual peak is at (- x 2.507212094348349975027e-11)
i.e.
 :(let* ((n 1e9) (x (/ (* 3 pi) (* 4 n)))) (deriv n (- x 2.507212094348349975027e-11)))
 3.725127687918788793358833288937859151702E-6
or using 
(define (peak-at n)
  (let* ((x (/ (* 3 pi) (* 4 n)))
	 (range (* x .8))
	 (err 1e-20))
    (do ()
	((< (abs (deriv n x)) err)
	 (list (- x (/ (* 3 pi) (* 4 n)))
	       (deriv n x)))
      (let ((lo (deriv n (- x range)))
	    (hi (deriv n (+ x range))))
	(if (< (abs lo) (abs hi))
	    (set! x (- x (/ range 10)))
	    (set! x (+ x (/ range 10))))
	(set! range (* range .9))))))

or:
2: -2.421677894348464908163819163773325479774E-1  -2.542109530109137315348541607895395692012E-21
3: -1.181070918729755631206093082385937638842E-1  -3.493089933018897636165472895997622659429E-21
4: -7.043276098568086392007563576860101749568E-2  -4.800338790899243746899352912973818251532E-21
5: -4.707669254042527294644510729991788644279E-2  3.462251514314290744891714859502503645785E-21
6: -3.387015497518456023533786854922157878053E-2  -5.550551819638322580161104253852648704675E-21
7: -2.565623507080912890636745657363494539749E-2  5.667521137336683171337058660707235960645E-21
8: -2.018765171370880262166473632066821173556E-2  -2.60075875807278930669457906973394842712E-21
9: -1.635581204680970730391053813339506919918E-2  -2.49691060642061379906356071454917335827E-21
10: -1.356168411128330953565403940042769994662E-2 3.806266181586793878107841906576959486354E-21
11: -1.145811507171758934905894436740180168887E-2 -3.500075183808578156580231318788510376355E-21
12: -9.83243017119212501337362936727640738345E-3  1.01480660438814124456364140502400386379E-22
13: -8.548312956055249881979809501119340017916E-3 -7.239313585107067341837994688198940392904E-21
14: -7.515046477014091277001818997621777552805E-3 -4.077646144271174537876436960403702130689E-21
15: -6.670315400525027347449871935335883744278E-3 -2.405976623505729548206548219351450204594E-22
16: -5.97013703538091639991154748789103345287E-3  -1.045882818863667721861763771430143995709E-21
17: -5.382730445871958442467339348911179502178E-3 3.993689578581470072273709565896866011558E-21
18: -4.88465508788404790507044492948019033614E-3  5.907366932923666851660865434938467677364E-21
19: -4.4583061453239883124546788791877625504E-3   9.452118583104181906394835659535495032207E-21

1e2: -3.666449064510999452172534004805209932E-4  -6.7133569632029478217918235054413664011649197E-21
1e3: -2.623704523377842468822594954231187534E-5  -4.9923846428498028980296129156343442708035258E-21
1e4: -2.518866953580949081116055241339673507E-6  -3.7781433570837640130110185268814176373422622E-21
1e5: -2.508377532616470973577582856419671127E-7   4.5623432062101773657294017611973375042290476E-21
1e6: -2.507328533847142227258073649062622639E-8  -4.6914838629061987833884085483344193742264034E-21
1e7: -2.507223633403447489575620917160615658E-9   5.2291911761872083246687386421454377310046409E-22
1e8: -2.507213143353410364121109699301712442E-10  8.2234860381608642958612200025313809610775802E-21
1e9: -2.507212094348349975025739950520586963E-11 -4.7782070016528057029294375412260845056787478E-21  
1e10: -2.50721198944784336935067073338431120E-12  6.9107383981769940658781617913229048114198940E-21
1e11: -2.50721197895779270311550845619211172E-13  1.6127270311176948101129176357022786397177201E-21
1e12: -2.50721197790878763643531567488505006E-14  -1.455476537343183418317173409749413112473485E-21
-->

<table>
<tr><td>
<table>
<tr><td>
<img class="indented" src="pix/n3a1.png" alt="3 harmonics in 3D">
</td></tr><tr><td class="center">3 harmonics</td></tr></table>
</td><td>
<table>
<tr><td>
<img class="indented" src="pix/n3a2.png" alt="4 harmonics in 3D">
</td></tr><tr><td class="center">4 harmonics</td></tr></table>
</td></tr></table>

<!--
(with-sound (:clipped #f :channels 1 :statistics #t :output "n3.snd")
     (let ((i 0)
	   (incr (/ (* 2 pi) 1000)))
      (do ((phi1 0.0 (+ phi1 incr))
	   (j 0 (+ j 1)))
	  ((= j 1000))
	(do ((phi2 0.0 (+ phi2 incr))
	     (k 0 (+ k 1)))
	    ((= k 1000))
	  (let ((pk 0.0)
		(tpk 0.0))
	    (do ((x 0.0 (+ x incr))
		 (n 0 (+ n 1)))
		((= n 1000))
	      (let ((val (+ (sin x)
			    (sin (+ (* 2 x) phi1))
			    (sin (+ (* 3 x) phi2)))))
		(if (> (abs val) pk)
		    (begin
		      (set! pk (abs val))
		      (set! tpk val)))))
	    (outa i tpk)
	    (set! i (+ i 1)))))))


(with-sound (:clipped #f :channels 8 :statistics #t :output "n4.snd")
  (let* ((size 200)
	 (incr (/ (* 2 pi) size))
	 (i 0))
       (do ((phi1 0.0 (+ phi1 incr))
	    (j 0 (+ j 1)))
	   ((= j size))
	 (do ((phi2 0.0 (+ phi2 incr))
	      (k 0 (+ k 1)))
	     ((= k size))
	   (do ((phi3 0.0 (+ phi3 (/ pi 4))) ; 8 strips through the 3-D landscape
		(m 0 (+ m 1)))
	       ((= m 8))
	     (let ((pk 0.0))
	       (do ((x 0.0 (+ x incr))
		    (n 0 (+ n 1)))
		   ((= n size))
		 (let ((val (+ (sin x)
			       (sin (+ (* 2 x) phi1))
			       (sin (+ (* 3 x) phi2))
			       (sin (+ (* 4 x) phi3)))))
		   (if (> (abs val) pk)
		       (set! pk (abs val)))))
	       (out-any i pk m)))
	   (set! i (+ i 1))))))

(define (gad4)
  (do ((i 0 (+ i 1)))
      ((= i 8))
    (map-channel (lambda (y) (/ (- (abs y) 2) 2)) 0 (framples) 0 i))
  (set! *selected-graph-color* (make-color 1 1 1))
  (set! *wavo-trace* 200)
  (set! *wavo-hop* 1)
  (set! *spectro-x-angle* 0)
  (set! *spectro-y-angle* 0)
  (set! *spectro-z-angle* 0)
  (set! *spectro-x-scale* 0.9)
  (set! *spectro-y-scale* 0.9)
  (set! *spectro-z-scale* 1.0)
  (set! *time-graph-type* graph-as-wavogram))
-->


<p>
I tilted the graph slightly to try to show how the colors match the peaks.  
If we set the second component's phase to (a+pi)/2 where "a" is the third one's initial phase,
we travel along the minimum going diagonally through the middle of the graph (I think the
graph got truncated slightly: the top should match the bottom).
The graph on the right is
an attempt to show the 4-dimensional 4-harmonic case by stacking 3-D slices.
I forgot to "invert" the colors, so red in the n=4 case matches a minimum (blue in the n=3 case);
I should redo these graphs! 
A different way to view these graphs that 
can be applied to any number
of dimensions (until we run out of disk space and patience), is to move through the possibilities
in much the way you'd count to 100; before each 10's digit increments, you'd count diligently
through all the 1's.  Similarly, in the next set of graphs, we go from 0 to 2pi completely
on one component before incrementing the next lower component.  So, we get the second component
moving slowly from 0 to 2pi, and, in the n=3 case, at each step it takes, it waits until the
third component has gone from 0 to 2pi.  This way we get all possible initial phases graphed
in a normal 2D picture.  Here is the n=3 case.  The top level looks a bit like the n=2 case, but
zooming in shows more complexity (each graph on the right is the selected portion of the one
on its left). (The complexity in this case is mostly due to the slice-at-a-time approach).
</p>

<img class="indented" src="pix/noid3.png" alt="n=3 case">

<p>We're trying to pinpoint the minima (there appear to be 4 black areas in the 3D graph,
corresponding (I hope!) to the four minima in the second graph).
A multiprecision search finds these values:
</p>

<pre class="indented">
 1.9798054823226 #(0.0 0.58972511242747172044431636095396243035  0.3166675693251937984129540382127743214) 
 1.9798054823226 #(0.0 1.58972511242745917492413809668505564332  0.3166675693251493894919690319511573761)
 1.9798054823222 #(0.0 0.41027488757208596670267297668033279478  1.68333243067326587816268101960304193198)  
 1.9798054823222 #(0.0 1.41027488757208596670267297668033279478  1.68333243067326587816268101960304193198)
</pre>

<p>which shows that the minima are essentially at (23/39 19/60), (16/39 101/60), (1 + 23/39, 19/60), and (1 + 16/39, 101/60),
all numbers multiplied by pi of course.  (Our labor was mostly wasted; once we find one such point, the symmetries of the
sinusoids hand us the other three for free. See find-other-mins in peak-phases.scm).
</p>

<!--
(set! (srate 2) (round (/ 1000000 (* 2 pi))))
(set! *axis-label-font* "9x15")
(define (window-bounds losamp hisamp snd chn)
  (set! (left-sample snd chn) losamp)
  (set! (x-zoom-slider snd chn) (exact->inexact (/ (- hisamp losamp) (framples snd chn)))))
(window-bounds  283820 310346 1 0)
(set! (x-axis-label 0 0) "2's phase")
(set! (y-zoom-slider 1 0) (y-zoom-slider 0 0))
(set! (y-zoom-slider 2 0) (y-zoom-slider 0 0))
(set! (selection-member? 0 0) #t)
(set! (selection-position 0 0) 283820)
(set! (selection-framples 0 0) (- 310346 283820))
(set! (selection-member? 1 0) #t)
(set! (selection-position 1 0) 294528)
(set! (selection-framples 1 0) (- 297881 294528))
(set! (x-axis-label 1 0) "2's phase")
-->

<p>Here is n=4 graphed in the same way:
</p>

<img class="indented" src="pix/noid4.png" alt="n=4 case">

<!--
(set! (srate 0) (round (/ 1000000 (* 2 pi))))
(set! (y-zoom-slider 1 0) (y-zoom-slider 0 0))
(set! (x-axis-label 0 0) "2's phase")
(window-bounds (- 436349 12000) (+ 436349 12000) 1 0)
(window-bounds (- 436349 500) (+ 436349 500) 2 0)
(set! (selection-member? 0 0) #t)
(set! (selection-position 0 0) (- 436349 12000))
(set! (selection-framples 0 0) 24000)
(set! (selection-member? 1 0) #t)
(set! (selection-position 1 0)(- 436349 500))
(set! (selection-framples 1 0) 1000)
-->

<p>One of those minima might be the one we found near 2.04.
n=5:
</p>

<img class="indented" src="pix/noid5.png" alt="n=5 case">

<!--
899171, 40000 2000
-->

<p>Here is the corresponding 3-D graph of the 5 harmonic case.  It is trying to show 8 4-D slices
through the 5-D landscape, each 4-D case being 8 3-D slices as before (I forgot to invert the colors
here also, so despite appearances, blue is a maximum, and we're looking for the reddest point, the global minimum):
</p>

<img class="indented" src="pix/n5-all.png" alt="all">

<!-- montage -tile 8X1 n51a.png n52a.png n53a.png n54a.png n55a.png n56a.png n57a.png n58a.png n5-all.png -->

<!--
<p>And just for grins, here is the n=6 case:
</p>

<img class="indented" src="pix/n6.png" alt="n=6 case">
-->

<!--
(with-sound (:clipped #f :channels 64 :statistics #t :output "n5a.snd")
     (let* ((i 0)
	    (size 400)
	    (incr (/ (* 2 pi) size))) ; n5=100 here
      (do ((phi1 0.0 (+ phi1 incr))
	   (j 0 (+ j 1)))
	  ((= j size))
	(do ((phi2 0.0 (+ phi2 incr))
	     (k 0 (+ k 1)))
	    ((= k size))
	  (do ((phi3 0.0 (+ phi3 (/ pi 4)))
	       (m 0 (+ m 1)))
	      ((= m 8))
	    (do ((phi4 0.0 (+ phi4 (/ pi 4)))
		 (p 0 (+ p 1)))
		((= p 8))
	      (let ((pk 0.0)
		    (tpk 0.0))
		(do ((x 0.0 (+ x incr))
		     (n 0 (+ n 1)))
		    ((= n 1000))
		  (let ((val (+ (sin x)
				(sin (+ (* 2 x) phi1))
				(sin (+ (* 3 x) phi2))
				(sin (+ (* 4 x) phi3))
				(sin (+ (* 5 x) phi4)))))
		    (if (> (abs val) pk)
			(begin
			  (set! pk (abs val))
			  (set! tpk val)))))
		(out-any i tpk (+ (* 8 m) p)))))
	  (set! i (+ i 1))))))

(define (gad5)
  (do ((i 0 (+ i 1))) ((= i 64)) (map-channel (lambda (y) (/ (- (abs y) 2.3) (- 5.0 2.3))) 0 (framples) 0 i))
  (set! *wavo-trace* 400)
  (set! *wavo-hop* 1)
  (set! *spectro-x-angle* 10)
  (set! *spectro-y-angle* 0)
  (set! *spectro-x-scale* 0.75)
  (set! *spectro-y-scale* 0.9)
  (set! *spectro-z-scale* 0.9)
  (set! *time-graph-type* graph-as-wavogram))

(do ((snd 0 (+ snd 1)))
    ((= snd 8))
  (do ((snd1 0 (+ snd1 1)))
      ((= snd1 8))
    (let* ((outfile (format #f "n6-~D-~D.snd" snd snd1))
	   (size 100)
	   (incr (/ (* 2 pi) size)))
      (with-sound (:clipped #f :channels 8 :statistics #t :output outfile)
	   (let* ((i 0))
	     (do ((phi1 0.0 (+ phi1 incr))
		  (j 0 (+ j 1)))
		 ((= j size))
	       (do ((phi2 0.0 (+ phi2 incr))
		    (k 0 (+ k 1)))
		   ((= k size))
		 (do ((phi3 0.0 (+ phi3 (/ pi 4)))
		      (m 0 (+ m 1)))
		     ((= m 8))
		   (let ((pk 0.0)
			 (phi4 (* snd1 (/ pi 4)))
			 (phi5 (* snd (/ pi 4))))
		     (do ((x 0.0 (+ x incr))
			  (n 0 (+ n 1)))
			 ((= n size))
		       (let ((val (+ (sin x)
				     (sin (+ (* 2 x) phi1))
				     (sin (+ (* 3 x) phi2))
				     (sin (+ (* 4 x) phi3))
				     (sin (+ (* 5 x) phi4))
				     (sin (+ (* 6 x) phi5)))))
			 (if (> (abs val) pk)
			     (set! pk (abs val)))))
		     (out-any i pk m)))
		 (set! i (+ i 1)))))))))


(define (gad6)
  (do ((i 0 (+ i 1))) ((= i 8)) (map-channel (lambda (y) (/ (- (abs y) 2.5) (- 6.0 2.5))) 0 (framples) 0 i))
  (set! *selected-graph-color* (make-color 1 1 1))
  (set! *wavo-trace* 100)
  (set! *wavo-hop* 1)
  (set! *spectro-x-angle* 15) ; was 10
  (set! *spectro-y-angle* 0)
  (set! *spectro-x-scale* 0.9) ; was .75
  (set! *spectro-y-scale* 0.9)
  (set! *spectro-z-scale* 1.0) ; was .9
  (set! *colormap* jet-colormap)
  (set! *color-cutoff* 0.001)
  (set! *color-scale* 1.0) ; 50%
  (set! *time-graph-type* graph-as-wavogram))

-->

<p>n=6 is even more beautiful and complex, but the graph is too large to include here.
</p>


<pre class="indented">
;;; use mix and with-temp-sound to create a draggable mix object for each component.

(load "peak-phases.scm")
(set! *with-mix-tags* #t)     ; drag the tag to change the harmonic's initial phase
(set! *show-mix-waveforms* #f)
(set! *with-inset-graph* #f)

(define (show choice n)                           ; (show :all 14) for example
  (definstrument (sine-wave start dur freq phase) ; make one harmonic
    (let* ((beg (seconds-&gt;samples start))
	   (end (+ beg (seconds-&gt;samples dur)))
	   (osc (make-oscil freq phase)))
     (do ((i beg (+ i 1))) 
	 ((= i end))
       (outa i (oscil osc)))))

  (if (null? (sounds))
      (new-sound))
  (let ((phases (cadr (get-best choice n))))
    (do ((i 0 (+ i 1)))
	((= i n))
      (let* ((freq (case choice
		     ((:all) (+ i 1))
		     ((:even) (max (* 2 i) 1))
		     ((:odd) (+ (* 2 i) 1))
		     ((:prime) (primes i))))
	     (snd (<em class=red>with-temp-sound</em> (:ignore-output #t :clipped #f)
		   (sine-wave 0 2 (* 10 freq) (* pi (phases i))))))
	(let ((mx (car (<em class=red>mix</em> snd 400)))) ; give some space after the axis
	  (set! (mix-tag-y mx) (+ 10 (* 40 i)))))))
  (let ((mx (+ 2.0 (maxamp))))
    (set! (y-bounds) (list (- mx) mx)))
  (set! (x-bounds) (list 0.0 0.2)))

(hook-push mix-drag-hook ; report the current maxamp as we drag a component
  (lambda (hook)
    (let ((beg 0)
	  (end (framples))
	  (mx 0.0))
      (for-each
       (lambda (sine)
	 (set! beg (max beg (mix-position sine)))
	 (set! end (min end (+ (mix-position sine) (mix-length sine)))))
       (caar (mixes)))
      (let ((rd (make-sampler beg)))
	(do ((i beg (+ i 1)))
	    ((&gt; i end))
	  (set! mx (max mx (abs (rd))))))
      (status-report (format #f "maxamp: ~A" mx)))))
</pre>



<p>It's curious that the "min-peak-amplitude versus n" graphs look continuous; what
happens to the minima as we slowly add the next higher harmonic?  In the n=2 case,
each minimum splits in two, then smoothly moves to its next minimum location (where the
third harmonic has amplitude 1.0).  Here's a graph of the moving minima,
showing also the resultant peak amplitude:
</p>

<img class="indented" src="pix/phase-paths.png" alt="moving minima">
<img class="indented" src="pix/peak-path.png" alt="moving minima">

<p>In the first graph, each dot is at the phase location of the minimum peak amplitude as the
third harmonic is increased in amplitude by 0.025.  The turning points are just before the third harmonic
reaches an amplitude of 0.5.  The n=2 minima are at (0, 0), (red and green, with
the green x=2 rather than 0), and (0, 1), (black and blue). Each splits and wanders eventually to
the n=3 global minima at (0.41 1.68), (1.41, 1.68), (1.59, 0.32), and (0.59, 0.32).
Each of the n=2 global minima ends up at 2 of the 4 n=3 global minima!  How lucky can we be?
If this worked in general, we could use it to speed up our search by following a minimum of n harmonics as it meanders to a minimum of n+1 harmonics:
</p>

<pre class="indented">
;; this starts at the current min and marches to an n+1 min
(do ((n 3)
     (phases (vector 0.0 0.0 1.0)))
     (x 0.1 (+ x .1)))
    ((&gt;= x 1.0))
  (let ((p (fpsap x 0 n 1000 0.1 50 #f #t phases))) ; args may change without warning.
    (format () ";~A: ~A~%" x p)
    (do ((k 0 (+ k 1)))
        ((= k n))
      (set! (phases k) (modulo (p k) 2.0)))))
</pre>

<p>
Since we can restrict our search to 0.1 (maybe less) in each direction (rather than 2.0), we
get a reduction of 20^n in the size of the space we are searching.  But, as usual, there's
a problem.  The search works for n=2 -&gt; 3 -&gt; 4 -&gt; 5, but going from 5 to 6, I seem to fall into a
non-optimal path. 
</p>

<p>
The other short-cut that immediately comes to mind is to look for the zeros of
the derivative, then plug those into the original to get the maxima.  But it is just as hard to
find those zeros as to find the peaks of the original.  Or we could minimize the length
of the curve.  In the 57 harmonics case, for example, the cosine version (peak=57.0) has a length of 
485.45, whereas the minimized peak version (peak=7.547) has a length of 909.52.  
But this also doesn't save us any time over the original search.
</p>

<!--
  (let* ((samples 10000)
	 (incr (/ (* 2 pi) samples))
	 (len 0.0)
	 (last-sum 0.0)
	 (sum 0.0)
	 (mx 0.0))
      (do ((i 0 (+ i 1))
	   (x 0.0 (+ x incr)))
	  ((= i samples))
	(set! sum 0.0)
	(do ((k 1 (+ k 1)))
	    ((= k 58))
	  (let ((val (sin (+ (* k x) (* pi (phases (- k 1)))))))
	    (set! sum (+ sum val))))
	  
	;(set! len (+ len (abs (- sum last-sum))))
	(set! len (+ len (sqrt (+ (* (- sum last-sum) (- sum last-sum)) (* incr incr)))))
	(set! last-sum sum)
	(if (< mx (abs sum)) (set! mx (abs sum))))
      (list len mx))
-->


<p>
So we're resigned to a laborious search.  The first thing we need is a fast way to
produce a sum of sinusoids.  Up to n=25 or 30, the Chebyshev polynomials are
just as fast as an inverse FFT, but why stop at 30!  
Since we'll be doing an inverse FFT for every test case, we need to make
the FFT size as small as possible while
still giving a reasonably accurate peak (say 
within 0.001 of the true peak).  
According to N Higham in "Accuracy and Stability of Numerical Algorithms",
the FFT is stable and very accurate.  He has a graph showing accumulated
numerical errors down in the 10^-15 range!   But that is not where the
inverse FFT loses.  We get n points back from an n-point FFT, so
effectively we're sampling the resultant waveform at those n points.
This subsampling can easily miss the peak.
Here are the errors for inverse FFT's of various sizes for the
8 and 128 all harmonics case (all initial phases = 0.0,
multiply "mult" by the number of harmonics to get the FFT size):
</p>
<!--
(let ((phases (make-vector 8 0.0))
      (correct 6.1442))
  (do ((i 2 (* i 2)))
      ((> i 8192))
    (let ((fftval (fft-all 8 i phases)))
      (format () "~D: ~A -> ~A~%" i fftval (abs (- fftval correct))))))
-->

<pre class="indented">
              8 harmonics                     128 harmonics    
                 
mult    reported peak    error           reported peak     error

2        5.02733      1.11686e0           81.48324      11.62779
4        5.57658      5.67621e-1          81.98630      11.12473
8        6.10774      3.64636e-2          93.08931      0.021721
16       6.10774      3.64636e-2          93.08931      0.021721
32       6.14247      1.72736e-3          93.08931      0.021721
64       6.14247      1.72736e-3          93.08931      0.021721
128      6.14391      2.87163e-4          93.10728      0.003753
256      6.14405      1.50636e-4          93.10980      0.001232
512      6.14420      5.36694e-6          93.11143      0.000391
1024     6.14420      5.36694e-6          93.11143      0.000391
2048     6.14420      1.59697e-6          93.11156      0.000525
4096     6.14420      1.44227e-7          93.11156      0.000525
8192     6.14420      3.60112e-8          93.11156      0.000526
</pre>



<p>
128 seems pretty good.  Those are spikey cases.  If we try the
best minimum-peak case, the errors are much smaller.  Here are graphs of both
the 0.0 phase and minimum phase cases for 8 harmonics:
</p>

<table>
<tr><td>
<img src="pix/8.png" alt="8 case">
</td><td></td><td>
<img class="indented" src="pix/88.png" alt="8 case">
</td></tr></table>


<!--
(let ((phases #(0.000000 0.666709 0.807769 1.605408 0.837217 0.044625 0.144433 1.873342))
      (correct 2.7949089))
  (do ((i 2 (* i 2)))
      ((> i 8192))
    (let ((fftval (fft-all 8 i phases)))
      (format () "~D: ~A -> ~A~%" i fftval (abs (- fftval correct))))))

2: 2.7906633022277 -> 0.0042455977723455
4: 2.7906633022277 -> 0.0042455977723455
8: 2.7906633022277 -> 0.0042455977723455
16: 2.7914621378061 -> 0.0034467621938754
32: 2.794721427123 -> 0.00018747287701526
64: 2.794721427123 -> 0.00018747287701526
128: 2.794721427123 -> 0.00018747287701526
256: 2.7948623970663 -> 4.6502933732206e-05
512: 2.7948904456648 -> 1.8454335195095e-05
1024: 2.7949073674377 -> 1.5325622837459e-06
2048: 2.7949073674377 -> 1.5325622837459e-06
4096: 2.7949089386041 -> 3.8604115459862e-08
8192: 2.7949089386041 -> 3.8604115903951e-08

and for 128:

2: 11.600891830857 -> 8.6119827837905e-06
4: 11.600891830857 -> 8.6119827837905e-06
8: 11.600891830857 -> 8.6119827837905e-06
16: 11.600891830857 -> 8.6119827837905e-06
32: 11.600891830857 -> 8.6119827837905e-06
64: 11.600891830857 -> 8.6119827837905e-06
128: 11.600891830857 -> 8.6119827837905e-06
256: 11.600891830857 -> 8.6119827837905e-06
512: 11.600891830857 -> 8.6119827837905e-06
1024: 11.600891830857 -> 8.6119827837905e-06
2048: 11.600894542871 -> 5.8999694552142e-06
4096: 11.600900716528 -> 2.7368773736214e-07
8192: 11.600900716528 -> 2.7368773736214e-07

(I think this happens because the waveform becomes very flat &mdash; there
are lots of peaks that are all about the same size, so we don't need great
accuracy to hit the one peak just right).
Perhaps we could reduce the FFT size once we narrow the search down
to a good candidate, but that seems like asking for trouble.

(let ((dur 2048))

  (let ((old (find-sound "test.snd")))
    (if (sound? old)
	(close-sound old)))
  
(let ((ns (new-sound "test.snd" :channels 5))
      (data (make-float-vector dur)))

  (let ((phases (make-vector 8 0.0))
	(correct 6.1442))

    (set! (y-bounds) (list -6.2 6.2))

    (do ((chan 0 (+ chan 1))
	 (n 4 (* n 4)))
	((> n 512))

      (let* ((size (expt 2 (ceiling (/ (log (* 8 n)) (log 2)))))
	     (fft-rl (make-float-vector size))
	     (fft-im (make-float-vector size))
	     (pi2 (/ pi 2)))
	
	(do ((m 0 (+ m 1)))
	    ((= m 8))
	  (let ((phi (+ (* pi (phases m)) pi2))
		(bin (+ m 1)))
	    (set! (fft-rl bin) (cos phi))
	    (set! (fft-im bin) (sin phi))))
		 
	(mus-fft fft-rl fft-im size -1)

	(do ((i 0 (+ i 1))
	     (k 0)
	     (step (/ dur size))
	     (step-ctr 0 (+ step-ctr 1)))
	    ((= i dur))
	  (set! (data i) (fft-rl k))
	  (if (>= step-ctr step)
	      (begin
		(set! k (+ k 1))
		(set! step-ctr (- step-ctr step)))))

	(float-vector->channel data 0 dur ns chan)))

    (let ((len 8)
	  (incr (/ (* 2 pi) dur)))
      (do ((x 0.0 (+ x incr))
	   (i 0 (+ i 1)))
	  ((>= i dur))
	(let ((val 0.0))
	  (do ((k 0 (+ k 1))
	       (j 1 (+ j 1)))
	      ((= k len))
	    (set! val (+ val (sin (+ (* j x) (* pi (phases k)))))))
	  (set! (data i) val)))
      (float-vector->channel data 0 dur ns 4))

    (set! *selected-graph-color* (make-color 1 1 1))
    (set! *selected-data-color* (make-color 0 0 0))

    (set! (x-axis-label ns 0) "fft size: 32")
    (set! (x-axis-label ns 1) "fft size: 128")
    (set! (x-axis-label ns 2) "fft size: 512")
    (set! (x-axis-label ns 3) "fft size: 2048")

    (set! (x-axis-label ns 4) "sum of sines")

    )))
-->



<p>Ok, we have a fast way to make test cases.  Off we go...
When I started this search more than two years ago, I had no idea what a long and winding
path I was headed down!  My initial guess was that I could find minimum peaks close to
the square root of n.  This was based on nothing more than the breezy idea that the initial phases give you enough
freedom that you're approaching the behavior of a sum of n random signals.
I thought these minima could not be very hard to find; simply use
a brute force grid.  The first such grid used initial phases of 0 and pi, and I
actually ran every possible such case, up to n=45 or so.  Since each harmonic can be
positive or negative, this is 2^44 cases to check, which is starting to be a pain.
The results were discouraging; I did not get close to the square root of n.
I also tried smaller grids (down to pi/32) for small n (say n &lt; 8), without
any success.
</p>

<p>Next great idea: try random initial phases.  This actually works better than it has
any right to, but again the results are disappointing.  You can run random phases until
hell freezes over and only get to n^.6 or slightly less.  And the long term trend of
this process can dampen one's optimism.  Here's a graph where we've taken 100 stabs
at each case of N harmonics, N from 3 to 2000, using randomly chosen initial phases, and tracked the
minimum, maximum, and average peaks.  The graph is logarithmic (that is we show
(log minimum N) and so on):
</p>

<img class="indented" src="pix/averages.png" alt="average peaks from n=3 to 2000">

<!--
(define pi2 (/ pi 2))
(define data-file "test.data")
(set! *print-length* 1000000)

(define (get-fft-size choice n1 mult)
  (let ((n (if (eq? choice :all) n1
	       (if (not (eq? choice :prime)) (* 2 n1)
		   (vector-ref primes n1)))))
    (min (expt 2 21) 
	 (expt 2 (ceiling (/ (log (* n mult)) (log 2)))))))

(define (get-peak choice n cur-phases)
  (let* ((fft-mult 128)
	 (size (get-fft-size choice n fft-mult))
	 (fft-rl (make-float-vector size))
	 (fft-im (make-float-vector size))
	 (nc (if (eq? choice :all) 0
		 (if (eq? choice :odd) 1
		     (if (eq? choice :even) 2 3)))))

    (fill! fft-rl 0.0)
    (fill! fft-im 0.0)
		 
    (do ((m 0 (+ m 1)))
	((= m n))
      (let ((phi (+ (* pi (vector-ref cur-phases m)) pi2))
	    (bin (if (= nc 0) (+ m 1)
		     (if (= nc 1) (+ 1 (* m 2))
			 (if (= nc 2) (max 1 (* m 2))
			     (vector-ref primes m))))))
	(float-vector-set! fft-rl bin (cos phi))
	(float-vector-set! fft-im bin (sin phi))))
    (float-vector-peak (mus-fft fft-rl fft-im size -1))))


(let ((tries 100)
      (file (open-output-file data-file "w")))
  (do ((n 2000 (+ n 1)))
      ((= n 3000))
    (let ((phases (make-vector n 0.0))
	  (sqrt-n (sqrt n)))
      (let ((min-peak n)
	    (max-peak 0.0)
	    (sum 0.0))
	(do ((try 0 (+ try 1)))
	    ((= try tries))
	  (fill! phases 0.0)
	  (do ((k 1 (+ k 1)))
	      ((= k n))
	    (vector-set! phases k (random pi)))
	  (let ((pk (get-peak :all n phases)))

	    (if (> pk n)
		(format () "    ;oops: n: ~D, pk: ~F~%" n pk))
	    (if (< pk sqrt-n)
		(begin
		  (format file "    ;;~D: ~F (~F) from ~A~%" n pk sqrt-n phases)
		  (format () "    ;~D: ~F (~F) from ~A~%" n pk sqrt-n phases)))

	    (set! sum (+ sum pk))
	    (if (< pk min-peak)
		(set! min-peak pk))
	    (if (> pk max-peak)
		(set! max-peak pk))))
	(set! sum (/ sum tries))
	(format file "(~D ~,3F ~,3F ~,3F (~,3F ~,3F ~,3F))~%" n (log min-peak n) (log sum n) (log max-peak n) min-peak sum max-peak)
	(if (zero? (modulo n 10))
	    (format () "~A: ~,3F ~,3F ~,3F (~,3F ~,3F ~,3F)~%" n (log min-peak n) (log sum n) (log max-peak n) min-peak sum max-peak))
	)))
  (close-output-port file))

(if (not (provided? 'snd-ws.scm)) (load "ws.scm"))

(define white (make-color 1 1 1))

;;; turn off clipping 
(set! (mus-clipping) #f)
(set! *clm-clipped* #f)
(set! *with-inset-graph* #f)

;;; these hooks may be drawing the graph in the upper right corner, which we don't want for now
(set! (hook-functions after-graph-hook) ())
(set! (hook-functions mouse-click-hook) ())
(set! (hook-functions update-hook) ())

;;; tell Snd not to try to load the data file
(set! (script-arg) (+ 1 (script-arg)))

(let ((ind (find-sound
	    (with-sound (:channels 3 :sample-type mus-lfloat)
			(let ((samp 0))	    
			  (call-with-input-file 
			      (list-ref (script-args) 1) ; invocation arg = text file of data ("snd graph-averages.scm peaks.data")
			    (lambda (file)
			      (let loop ((data (read file)))
				(if (pair? data)
				    (begin
				      (out-any samp (list-ref data 1) 0) 
				      (out-any samp (list-ref data 2) 1)
				      (out-any samp (list-ref data 3) 2)
				      (set! samp (+ 1 samp))
				      (loop (read file))))))))))))
  
  (set! (channel-style ind) channels-superimposed)
  (set! *selected-graph-color* white)
  (set! *graph-color* white)

  (do ((chan 0 (+ 1 chan)))
      ((= chan 3))
    (set! (x-axis-style ind chan) x-axis-in-samples)
    (set! (x-axis-label ind chan) "N")
    (set! (y-bounds ind chan) (list .5 1.0))))

-->

<p>The trend continues upwards as N goes to 100000; it probably approaches 1 in the limit.
But we can always do better than n^.6 by using phases 0.0938*i*i - 0.35*i
where "i" is the harmonic number counting from 0.
This little formula gives results as low as n^.541 (at n=2076), and it is always below n^.6 if n is large enough.
Lots of such formulas get us down to n^.53 or, as n gets larger, .52:
in the all harmonic case, if n=65536, 
4.5547029e-05*i*i + 0.640075398*i gives a peak of 309.9, and
-4.697190e-05*i*i + 1.357080536*i peaks at 303.6 (n^.515).  If n=131072, 
2.09440276*i*i + 1.4462367*i peaks at 438.7 (n^.516).
</p>

<p>
A good quadratic for each n, in the all harmonics case, 
is (pi/n)*i*i - i*pi/2.  
Except for the pi/n term, the rest just marches through the quadrants in order, so this is the
same as (pi*(((mod(i,4)/2)+(i*i/n)))).
This is similar to the formula suggested by M. Schroeder,
but the addition of the "mod(i,4)/2" term improves its performance.  If N=100, for example, Schroeder's
peak is 13.49, whereas the mod peak is 11.90.  There are better choices of quadrant than mod(i,4);
if N=14, the mod(i,4) formula gives a peak of 4.89 (Schroeder's formula's peak is 5.1), 
but an exhaustive search of all quadrant choices
finds #(0 0 0 1 3 3 0 1 2 3 1 3 2 3) with a peak of 4.28.  
Since the search involves approximately 4^n FFTs,
there's not much hope of going above N=20 or thereabouts.
I can't see any pattern in the lists of ideal quadrants.
</p>

<p>
The corresponding even harmonics version is (-pi/n)*(i+1)*(i+1) - (i+1)*pi/2.
These sorts of formulas do better as n increases, but I don't think they reach n^.5.  If n=4000000,
the peak is at 2408.9 (n^.512). 
A linear equation in "i" here is simply phase offset in the sum of sines formula mentioned
earlier, so given an initial phase of x*i, as x goes from 0 to pi/2, the peak goes from .7245*n to n.
Another good variant is (pi*i*i)/n using cos rather than sin.
</p>


<p>I haven't found any functions that get all the way to the square root. In the next graph,
the y axis is the peak value with n=100, the x axis is the number of tests, and we've
sorted the tests by peak.  Each test is centered around a known excellent minimum
peak, and the separate curves are showing the peaks when the initial phases can vary
around that best value by pi/4, then pi/8 etc.  It's hard to read at first, but
take the black top curve.  This is what you'd get if you randomly sampled a hypercube whose side length is pi/2 centered on that minimum.
Nearly all the values are between 18 (100^.63) and 23 (100^.68).  
Each successive curve divides the space we sample by 2 in all 100 dimensions,
so by the time we get to the bottom curve, we've reduced our search space by
a factor of 2^800 (we're down to .006 on a side), and we still don't see the actual minimum
even once in 50000 tries!  
Imagine trying to set up a grid to catch this point.
</p>

<img class="indented" src="pix/8way.png" alt="histogram of 100 reduced 8 times">

<p>What to do? 
There are a bunch of papers on this subject, but the best I found was:
Horner and Beauchamp, "a genetic algorithm-based method
for synthesis of low peak amplitude signals", J. Acoustic. Soc. Am Vol 99 No 1 Jan 96, online
at ems.music.uiuc.edu/beaucham/papers/JASA.01.96.pdf,
<!--
(In both this paper, and Schroeder's earlier
one, much fuss is made of the RMS value, but that value is independent of the
initial phases, so it is obviously irrelevant).
-->
They report good results using the genetic algorithm, so it tried it.
I started with 2000 randomly chosen initial points and a search radius
of 1.0 (= pi).  These are pretty good choices, but after a few months of searching, I reached a point of almost no
returns.  I tried variants of the basic algorithm and other search methods, but the results were not very good until
I noticed that in the 
graphs of the peaks, the good values are more or less clustered together.  So I tried centering
the genetic search on the best phases I had found to that point, then repeating
the search each time from the new best point, slowly reducing the search radius ("simulated annealing" is the jargon for this).
</p>

<pre class="indented">
(define (iterated-peak choice n)
  (let ((phases (make-vector n 0.0))
	(cur-best n)
	(cur-incr 1.0))
    (do ((i 1 (+ i 1)))
	((= i n))
      (set! (phases i) (random 1.0)))
    (do ()
	((&lt; cur-incr .001))
      (let ((vals (<em class=red>fpsap</em> (case choice ((:all) 0) ((:odd) 1) ((:even) 2) (else 3))
                         n phases 5000 cur-incr)))
	(let ((pk (car vals))
	      (new-phases (cadr vals)))
	  (let ((down (- cur-best pk)))
	    (if (&lt; down (/ cur-best 10))
		(set! cur-incr (* 0.5 cur-incr))))
	  (if (&lt; pk cur-best)
	      (begin
		(set! cur-best pk)
		(set! phases (float-vector-&gt;vector new-phases)))))))
    (list cur-best phases)))
</pre>

<p>The "fpsap" function is the genetic algorithm mentioned earlier, written in C.
Here is the GA code used to find the initial-phase polynomials mentioned above:
</p>

<pre class="indented">
(define (piterate choice n)   ; (piterate :all 4096)
  (let* ((size 1000)
	 (pop (make-vector size))
	 (phases (make-vector n 0.0)))
    ;; initialize our set of choices		   
    (do ((i 0 (+ i 1)))
	((= i size))
      (let ((f1 (random 1.0)) ; or (- 1.0 (random 2.0)) and also below
	    (f2 (random 1.0)))
	(do ((k 0 (+ k 1)))
	    ((= k n))
	  (set! (phases k) (modulo (/ (* k (+ (* f2 k) f1)) pi) 2.0)))
	(set! (pop i) (list (get-peak choice n phases) f1 f2))))
    ;; now do the GA search with annealing
    (do ((try 0 (+ try 1))
	 (increment .3 (* increment .98)))
	((= try 1000))
      (set! pop (sort! pop (lambda (a b) (&lt; (car a) (car b)))))
      (format () "~A ~D ~A ~A~%" choice n (pop 0) (log (car (pop 0)) n))
      (do ((i 0 (+ i 1))
	   (j (/ size 2) (+ j 1)))
	  ((= i (/ size 2)))
      (let ((f1 (+ (list-ref (pop i) 1) (random increment)))
	    (f2 (+ (list-ref (pop i) 2) (random increment))))
	(do ((k 0 (+ k 1)))
	    ((= k n))
	  (set! (phases k) (modulo (/ (* k (+ (* f2 k) f1)) pi) 2.0)))
	(set! (pop j) (list (get-peak choice n phases) f1 f2)))))))
</pre>

<!--
(if (not (provided? 'snd-rgb.scm)) (load "rgb.scm"))

(define (draw-sqrt-label xg yg exponent) ; 20 3 ".59"
  (let* ((snd 0)
	 (chn 0)
	 (axinf (axis-info snd chn))
	 (x (axinf 10))
	 (y (axinf 13))
	 (grf-width (- (axinf 12) x))
	 (grf-height (- (axinf 11) y))

	 (width 278)
	 (height 115)

	 (red (make-color 1 0 0))
	 (blue (make-color 0 0 1))
	 (green (make-color 0 1 0))
	 (black (make-color 0 0 0))
	 (chocolate (make-color 0.82 0.41 0.12))
	 )

    (set! (foreground-color snd chn) black)
    (let ((x1 (+ x xg))
	  (y1 (+ y yg))
	  (yoff 20)
	  (yinit 15)
	  (ytext -7))

      (fill-rectangle x1 y1 width 1 snd chn)
      (fill-rectangle x1 (+ y1 height) width 1 snd chn)
      (fill-rectangle x1 y1 1 height snd chn)
      (fill-rectangle (+ x1 width -1) y1 1 height snd chn)

      (set! (foreground-color snd chn) black)
      (fill-rectangle (+ x1 10) (+ y1 yinit) 30 3 snd chn)
      (set! (foreground-color snd chn) black)
      (draw-string "all harmonics" (+ x1 50) (+ y1 yinit ytext) snd chn)

      (set! (foreground-color snd chn) red)
      (fill-rectangle (+ x1 10) (+ y1 yinit yoff) 30 3 snd chn)
      (set! (foreground-color snd chn) black)
      (draw-string "odd-numbered harmonics" (+ x1 50) (+ y1 yinit yoff ytext) snd chn)

      (set! (foreground-color snd chn) chocolate)
      (fill-rectangle (+ x1 10) (+ y1 yinit (* 2 yoff)) 30 3 snd chn)
      (set! (foreground-color snd chn) black)
      (draw-string "even-numbered harmonics" (+ x1 50) (+ y1 yinit (* 2 yoff) ytext) snd chn)

      (set! (foreground-color snd chn) blue)
      (fill-rectangle (+ x1 10) (+ y1 yinit (* 3 yoff)) 30 3 snd chn)
      (set! (foreground-color snd chn) black)
      (draw-string "prime-numbered harmonics" (+ x1 50) (+ y1 yinit (* 3 yoff) ytext) snd chn)

      (set! (foreground-color snd chn) green)
      (fill-rectangle (+ x1 10) (+ y1 yinit (* 4 yoff)) 30 3 snd chn)
      (set! (foreground-color snd chn) black)
      (draw-string (format #f "n^~A" exponent) (+ x1 50) (+ y1 yinit (* 4 yoff) ytext) snd chn)
      )))


(define* (make-sqrt-png (xp 0.59))
  (set! *with-inset-graph* #f)
  ;; see tmp26...
  (with-sound (:channels 5 :clipped #f)

    (do ((i 1 (1+ i)))
	((> i 128))
      (let ((n-min-val (vector-find-if (lambda (val)
					 (and val
					      (vector? val)
					      (= (val 0) i)
					      (let ((a-val (val 1))
						    (a-len (length val)))
						(do ((k 2 (1+ k)))
						    ((= k a-len))
						  (if (and (number? (val k))
							   (< (val k) a-val))
						      (set! a-val (val k))))
						a-val)))
				       noid-min-peak-phases)))
	
	(let ((odd-min-val (vector-find-if (lambda (val)
					     (and val
						  (vector? val)
						  (= (val 0) i)
						  (let ((a-val (val 1))
							(a-len (length val)))
						    (do ((k 2 (1+ k)))
							((= k a-len))
						      (if (and (number? (val k))
							       (< (val k) a-val))
							  (set! a-val (val k))))
						    a-val)))
					   nodd-min-peak-phases)))
	  
	  (let ((prime-min-val (vector-find-if (lambda (val)
						 (and val
						      (vector? val)
						      (= (val 0) i)
						      (let ((a-val (val 1))
							    (a-len (length val)))
							(do ((k 2 (1+ k)))
							    ((= k a-len))
							  (if (and (number? (val k))
								   (< (val k) a-val))
							      (set! a-val (val k))))
							a-val)))
					       primoid-min-peak-phases)))

	    (let ((even-min-val (vector-find-if (lambda (val)
						  (and val
						       (vector? val)
						       (= (val 0) i)
						       (let ((a-val (val 1))
							     (a-len (length val)))
							 (do ((k 2 (1+ k)))
							     ((= k a-len))
							   (if (and (number? (val k))
								    (< (val k) a-val))
							       (set! a-val (val k))))
							 a-val)))
						neven-min-peak-phases)))
	  
	      (outa i (or n-min-val 0.0))
	      (outb i (or odd-min-val 0.0))
	      (outc i (or prime-min-val 0.0))
	      (outd i (expt (exact->inexact i) xp)) ; or (log pk n)?
	      (out-any i (or even-min-val 0.0) 4)
	      ))))))

  (set! (y-bounds) (list 0 21))
  (set! *channel-style* channels-superimposed)
  (set! *axis-color* (make-color 0 0 0))
  (set! *x-axis-style* x-axis-in-samples)
  (do ((i 0 (1+ i))) 
      ((= i 5)) 
    (set! (x-axis-label 0 i) "n"))
  (set! *selected-graph-color* (make-color 1 1 1))
  (set! *axis-label-font* "9x15")
  )

-->



<p>
Here are the results I have so far.  In each set, the first number is the number
of harmonics, then the minimum peak amplitude, then (log peak n).
</p>

<div class="simple">

<pre class="indented">
=============================================================================================
        all                      odd                      even                    prime
=============================================================================================

20    4.288    0.4860  | 11    3.177   0.4820   | 120  11.314  0.5067   | 24    5.642   0.5444
14    3.612    0.4867  | 9     2.886   0.4824   | 115  11.111  0.5075   | 127   14.038  0.5453
23    4.604    0.4870  | 17    3.926   0.4827   | 88   9.718   0.5079   | 101   12.400  0.5455
11    3.218    0.4874  | 10    3.053   0.4848   | 113  11.042  0.5080   | 102   12.509  0.5463
17    3.980    0.4876  | 19    4.172   0.4851   | 114  11.098  0.5082   | 73    10.425  0.5464
16    3.874    0.4884  | 14    3.598   0.4852   | 111  10.962  0.5084   | 19    4.999   0.5465
24    4.728    0.4888  | 13    3.475   0.4856   | 126  11.703  0.5086   | 106   12.794  0.5466
19    4.218    0.4889  | 18    4.070   0.4856   | 124  11.614  0.5087   | 18    4.855   0.5467
22    4.540    0.4894  | 21    4.399   0.4866   | 122  11.530  0.5089   | 25    5.811   0.5467
21    4.443    0.4898  | 16    3.857   0.4869   | 117  11.296  0.5091   | 110   13.074  0.5469
15    3.768    0.4899  | 20    4.300   0.4869   | 123  11.589  0.5091   | 93    11.931  0.5470
25    4.853    0.4907  | 15    3.738   0.4869   | 128  11.830  0.5092   | 108   12.950  0.5470
13    3.524    0.4911  | 12    3.362   0.4879   | 102  10.539  0.5092   | 109   13.018  0.5470
12    3.389    0.4911  | 22    4.519   0.4880   | 121  11.499  0.5092   | 28    6.191   0.5471
18    4.140    0.4915  | 28    5.089   0.4883   | 127  11.790  0.5093   | 40    7.527   0.5472
10    3.102    0.4917  | 23    4.634   0.4891   | 125  11.697  0.5094   | 95    12.086  0.5472
29    5.241    0.4920  | 25    4.834   0.4895   | 99   10.388  0.5094   | 92    11.878  0.5473
27    5.064    0.4922  | 31    5.419   0.4921   | 100  10.442  0.5094   | 23    5.562   0.5473
28    5.157    0.4923  | 24    4.783   0.4925   | 93   10.066  0.5094   | 126   14.116  0.5474
37    5.918    0.4924  | 33    5.597   0.4925   | 104  10.656  0.5095   | 128   14.240  0.5474
35    5.762    0.4926  | 29    5.257   0.4929   | 94   10.123  0.5095   | 77    10.787  0.5475
26    4.982    0.4929  | 30    5.353   0.4932   | 116  11.278  0.5097   | 22    5.434   0.5476
33    5.608    0.4931  | 27    5.085   0.4935   | 96   10.241  0.5097   | 120   13.757  0.5476
59    7.469    0.4931  | 8     2.791   0.4935   | 105  10.724  0.5098   | 86    11.464  0.5476
32    5.526    0.4932  | 26    4.997   0.4938   | 256  16.896  0.5098   | 17    4.719   0.5476
30    5.361    0.4937  | 37    5.959   0.4943   | 83   9.527   0.5101   | 94    12.040  0.5477
51    6.972    0.4939  | 35    5.801   0.4945   | 103  10.638  0.5101   | 103   12.673  0.5479
31    5.453    0.4939  | 7     2.618   0.4946   | 108  10.902  0.5102   | 122   13.907  0.5479
36    5.872    0.4940  | 32    5.554   0.4947   | 70   8.738   0.5102   | 47    8.247   0.5480
9     2.962    0.4941  | 34    5.726   0.4948   | 109  10.958  0.5103   | 96    12.200  0.5480
8     2.795    0.4942  | 52    7.080   0.4954   | 119  11.463  0.5104   | 30    6.452   0.5481
34    5.715    0.4943  | 50    6.947   0.4955   | 97   10.332  0.5105   | 125   14.110  0.5482
70    8.177    0.4946  | 38    6.071   0.4958   | 106  10.813  0.5105   | 123   13.986  0.5482
39    6.124    0.4946  | 82    8.895   0.4960   | 112  11.128  0.5106   | 115   13.481  0.5482
93    9.413    0.4947  | 48    6.828   0.4962   | 107  10.872  0.5106   | 39    7.452   0.5482
41    6.278    0.4947  | 41    6.322   0.4966   | 118  11.430  0.5107   | 63    9.693   0.5482
82    8.850    0.4948  | 43    6.474   0.4966   | 1024 34.487  0.5108   | 89    11.717  0.5483
81    8.797    0.4948  | 39    6.168   0.4966   | 82   9.497   0.5108   | 119   13.746  0.5484
60    7.589    0.4950  | 72    8.366   0.4967   | 84   9.615   0.5108   | 97    12.294  0.5485
38    6.056    0.4951  | 45    6.625   0.4967   | 85   9.676   0.5109   | 121   13.881  0.5485
69    8.140    0.4952  | 42    6.403   0.4968   | 101  10.574  0.5110   | 87    11.587  0.5486
49    6.872    0.4952  | 74    8.488   0.4969   | 92   10.094  0.5113   | 100   12.508  0.5486
73    8.372    0.4952  | 78    8.715   0.4970   | 110  11.060  0.5113   | 98    12.373  0.5486
58    7.471    0.4953  | 46    6.709   0.4972   | 91   10.043  0.5114   | 113   13.379  0.5486
48    6.804    0.4953  | 105   10.116  0.4972   | 86   9.758   0.5114   | 107   12.988  0.5487
103   9.936    0.4954  | 47    6.785   0.4973   | 95   10.269  0.5115   | 79    11.000  0.5488
64    7.850    0.4955  | 40    6.265   0.4974   | 79   9.357   0.5118   | 51    8.652   0.5488
56    7.349    0.4955  | 89    9.332   0.4976   | 90   10.005  0.5118   | 76    10.773  0.5489
42    6.374    0.4956  | 111   10.417  0.4976   | 87   9.834   0.5118   | 56    9.112   0.5489
63    7.793    0.4956  | 56    7.419   0.4979   | 81   9.484   0.5119   | 114   13.476  0.5492
83    8.935    0.4956  | 36    5.956   0.4979   | 75   9.122   0.5120   | 124   14.115  0.5492
40    6.224    0.4956  | 106   10.198  0.4980   | 71   8.871   0.5121   | 116   13.609  0.5492
85    9.050    0.4958  | 59    7.618   0.4980   | 73   8.999   0.5121   | 104   12.817  0.5492
67    8.044    0.4959  | 57    7.489   0.4980   | 98   10.469  0.5122   | 20    5.183   0.5492
76    8.567    0.4960  | 91    9.457   0.4981   | 77   9.259   0.5124   | 21    5.324   0.5492
92    9.420    0.4960  | 51    7.088   0.4981   | 78   9.328   0.5126   | 117   13.680  0.5493
75    8.512    0.4960  | 80    8.870   0.4981   | 80   9.451   0.5126   | 57    9.217   0.5493
55    7.300    0.4961  | 81    8.926   0.4981   | 61   8.227   0.5126   | 74    10.646  0.5495
53    7.168    0.4961  | 101   9.965   0.4982   | 74   9.090   0.5128   | 111   13.304  0.5495
105   10.064   0.4961  | 119   10.815  0.4982   | 512  24.510  0.5128   | 71    10.407  0.5495
52    7.102    0.4961  | 77    8.707   0.4982   | 72   8.966   0.5129   | 75    10.729  0.5496
104   10.017   0.4962  | 76    8.651   0.4982   | 89   9.997   0.5129   | 29    6.365   0.5496
50    6.966    0.4962  | 62    7.817   0.4982   | 57   7.966   0.5133   | 72    10.497  0.5497
65    7.935    0.4962  | 55    7.364   0.4982   | 68   8.738   0.5137   | 105   12.917  0.5497
71    8.291    0.4962  | 67    8.128   0.4983   | 67   8.681   0.5140   | 80    11.125  0.5498
47    6.757    0.4962  | 110   10.408  0.4984   | 63   8.411   0.5140   | 78    10.979  0.5499
45    6.613    0.4962  | 90    9.422   0.4985   | 76   9.267   0.5141   | 59    9.418   0.5500
100   9.828    0.4962  | 60    7.700   0.4985   | 64   8.488   0.5143   | 38    7.396   0.5501
74    8.468    0.4964  | 86    9.213   0.4985   | 66   8.632   0.5145   | 61    9.597   0.5501
44    6.544    0.4964  | 108   10.325  0.4986   | 65   8.567   0.5146   | 37    7.291   0.5502
57    7.441    0.4964  | 44    6.599   0.4986   | 51   7.569   0.5148   | 33    6.846   0.5502
46    6.691    0.4965  | 88    9.324   0.4986   | 58   8.101   0.5152   | 31    6.616   0.5502
54    7.246    0.4965  | 64    7.957   0.4987   | 69   8.861   0.5153   | 118   13.810  0.5503
84    9.023    0.4965  | 83    9.061   0.4988   | 62   8.387   0.5153   | 41    7.719   0.5503
94    9.544    0.4965  | 68    8.204   0.4988   | 2048 50.887  0.5154   | 27    6.134   0.5503
95    9.595    0.4966  | 71    8.384   0.4988   | 55   7.888   0.5154   | 70    10.362  0.5504
43    6.475    0.4966  | 102   10.046  0.4988   | 53   7.748   0.5157   | 36    7.187   0.5504
87    9.188    0.4966  | 85    9.173   0.4989   | 44   7.039   0.5157   | 16    4.600   0.5504
66    8.012    0.4967  | 114   10.621  0.4989   | 59   8.192   0.5158   | 62    9.697   0.5505
68    8.131    0.4967  | 61    7.775   0.4989   | 56   7.975   0.5158   | 112   13.432  0.5505
88    9.243    0.4967  | 125   11.122  0.4989   | 47   7.290   0.5159   | 66    10.041  0.5506
72    8.368    0.4967  | 70    8.328   0.4989   | 38   6.536   0.5161   | 90    11.912  0.5506
114   10.518   0.4968  | 75    8.621   0.4989   | 54   7.843   0.5163   | 60    9.529   0.5506
77    8.656    0.4969  | 98    9.853   0.4990   | 50   7.547   0.5167   | 54    8.996   0.5507
86    9.145    0.4969  | 63    7.904   0.4990   | 60   8.295   0.5167   | 83    11.400  0.5507
79    8.767    0.4969  | 107   10.296  0.4990   | 48   7.392   0.5168   | 43    7.936   0.5507
91    9.407    0.4969  | 103   10.102  0.4990   | 52   7.705   0.5168   | 88    11.779  0.5508
78    8.713    0.4969  | 118   10.812  0.4990   | 45   7.164   0.5173   | 52    8.817   0.5509
98    9.767    0.4971  | 115   10.674  0.4990   | 40   6.748   0.5176   | 84    11.487  0.5510
80    8.832    0.4971  | 58    7.586   0.4990   | 46   7.274   0.5183   | 91    12.006  0.5510
61    7.718    0.4971  | 128   11.261  0.4990   | 42   6.940   0.5183   | 85    11.571  0.5511
89    9.316    0.4972  | 53    7.253   0.4990   | 39   6.680   0.5184   | 99    12.590  0.5512
101   9.922    0.4972  | 94    9.654   0.4991   | 34   6.223   0.5184   | 45    8.155   0.5513
90    9.369    0.4972  | 69    8.275   0.4991   | 49   7.529   0.5187   | 64    9.905   0.5514
99    9.827    0.4973  | 92    9.553   0.4991   | 43   7.052   0.5193   | 12    3.936   0.5514
97    9.734    0.4974  | 120   10.909  0.4991   | 41   6.880   0.5194   | 34    6.991   0.5515
109   10.316   0.4974  | 113   10.586  0.4991   | 36   6.432   0.5194   | 46    8.260   0.5515
62    7.792    0.4975  | 96    9.759   0.4991   | 37   6.530   0.5197   | 44    8.065   0.5517
112   10.460   0.4975  | 66    8.095   0.4992   | 32   6.061   0.5199   | 42    7.863   0.5517
106   10.180   0.4976  | 73    8.515   0.4992   | 33   6.162   0.5201   | 68    10.262  0.5518
96    9.699    0.4978  | 84    9.133   0.4992   | 29   5.766   0.5203   | 48    8.468   0.5518
102   10.000   0.4979  | 116   10.733  0.4993   | 35   6.362   0.5204   | 32    6.772   0.5519
110   10.385   0.4979  | 100   9.968   0.4993   | 26   5.452   0.5206   | 53    8.948   0.5520
116   10.667   0.4980  | 54    7.328   0.4993   | 31   5.988   0.5212   | 82    11.386  0.5520
115   10.622   0.4980  | 95    9.717   0.4993   | 24   5.253   0.5220   | 81    11.311  0.5520
107   10.251   0.4981  | 121   10.965  0.4993   | 30   5.907   0.5222   | 69    10.358  0.5521
113   10.533   0.4981  | 122   11.011  0.4993   | 23   5.148   0.5226   | 55    9.143   0.5522
128   11.210   0.4981  | 117   10.783  0.4994   | 21   4.920   0.5233   | 50    8.676   0.5523
111   10.443   0.4981  | 65    8.041   0.4994   | 27   5.620   0.5238   | 65    10.031  0.5523
122   10.950   0.4982  | 104   10.169  0.4994   | 28   5.732   0.5240   | 49    8.583   0.5524
127   11.176   0.4983  | 79    8.865   0.4994   | 25   5.403   0.5241   | 58    9.425   0.5525
108   10.313   0.4984  | 109   10.414  0.4995   | 22   5.055   0.5242   | 15    4.466   0.5526
117   10.740   0.4985  | 49    6.986   0.4995   | 18   4.569   0.5257   | 26    6.056   0.5528
126   11.145   0.4985  | 99    9.928   0.4995   | 20   4.839   0.5264   | 35    7.164   0.5538
120   10.878   0.4985  | 97    9.832   0.4996   | 17   4.463   0.5280   | 67    10.266  0.5539
121   10.925   0.4986  | 93    9.629   0.4997   | 16   4.325   0.5282   | 11    3.778   0.5544
118   10.790   0.4986  | 124   11.120  0.4997   | 19   4.741   0.5286   | 9     3.382   0.5546
124   11.060   0.4986  | 87    9.317   0.4998   | 15   4.192   0.5292   | 14    4.324   0.5548
119   10.836   0.4986  | 126   11.217  0.4999   | 14   4.097   0.5344   | 13    4.154   0.5553
123   11.016   0.4986  | 123   11.088  0.4999   | 12   3.787   0.5359   | 10    3.602   0.5565
125   11.105   0.4986  | 127   11.268  0.5000   | 13   3.973   0.5378   | 5     2.477   0.5635
7     2.639    0.4988  | 112   10.582  0.5000   | 11   3.656   0.5406   | 4     2.192   0.5662
256   15.997   0.5000  | 256   16.243  0.5027   | 10   3.559   0.5513   | 8     3.263   0.5687
512   23.194   0.5040  | 3     1.739   0.5035   | 8    3.198   0.5590   | 256   23.955  0.5728
1024  33.039   0.5046  | 512   23.517  0.5062   | 9    3.454   0.5641   | 7     3.062   0.5750
2048  48.913   0.5102  | 1024  33.732  0.5076   | 7    3.047   0.5726   | 6     2.805   0.5757
4     2.039    0.5139  | 2048  48.227  0.5083   | 6    2.837   0.5820   | 512   38.603  0.5856
6     2.549    0.5223  | 4     2.045   0.5161   | 5    2.605   0.5948   | 2048  95.904  0.5985
5     2.343    0.5292  | 6     2.523   0.5164   | 3    2.021   0.6406   | 1024  65.349  0.6030
3     1.980    0.6217  | 5     2.307   0.5195   | 4    2.431   0.6406   | 3     1.980   0.6217
2     1.760    0.8156  | 2     1.539   0.6220   | 2    1.760   0.8157   | 2     1.760   0.8156
</pre>

</div>

<!-- from gad125.scm -->

<p>
Here is a graph of the peaks (as of February, 2015), followed by a graph of
the exponent vs n (n^y = peak amp). 
</p>

<img class="indented" src="pix/sqrt.png" alt="sqrt n">

<img class="indented" src="pix/sqrt1.png" alt="n^y">

<!-- from tmp26.scm -->

<p>The "even" cases are not independent of the "all" cases; each even-harmonics case can be at worst 1.0 above
the corresponding (n-1) all-harmonics case (shift the current "all" choices right to multiply each by 2, then set the new fundamental
phase to 0.0).  If you then search around this set of phases, you'll find very good values.  Using Snd's fpsap (a version
of the genetic algorithm):
</p>


<pre class="indented">
(let ((all (cadr (get-best :all (- n 1)))) ; get the best all-harmonic phases for n - 1
      (new-phases (make-vector n 0.0)))    ; place in new phase vector shifted up
  (do ((k 0 (+ k 1)))
      ((= k (- n 1)))
    (set! (new-phases (+ k 1)) (all k)))
  (set! (new-phases 0) 0.0)
  (fpsap 2 n new-phases))                   ; search that vicinity for a good set (2 = even harmonics)
</pre>



<p>Here is the time domain view of one of the n=5 cases when the minimum peak phases are chosen; the sum of the 5 components is in black.
</p>

<img class="indented" src="pix/sum5.png" alt="n=5 case">

<p>The next graph compares the 100 harmonic minimum peak case in blue with the 
case where all the initial phases are 0.0 in black:
</p>

<img class="indented" src="pix/100twice.png" alt="100 harmonics">

<p>And a few others:
</p>

<table>
<tr>
<td><img class="indented" src="pix/all57.png" alt="57 harmonics"></td>
<td><img class="indented" src="pix/odd57.png" alt="57 odd harmonics"></td>
</tr></table>

<img class="indented" src="pix/all99.png" alt="99 harmonics">

<!-- all57:

(define phases #(0.000000 0.402544 0.873914 0.824224 1.710182 0.183023 0.378574 0.128782 1.816255 1.249608 1.030253 1.030831 0.184699 0.677473 1.528003 1.262679 1.840809 0.082787 1.487290 1.579585 0.150833 0.308197 0.183834 1.435443 0.452047 0.800416 1.697556 1.103318 1.169502 1.438166 1.765331 0.875181 1.049248 1.321068 0.824424 0.599899 1.694664 0.504547 1.583285 1.657047 0.940116 1.788668 1.529808 0.367904 1.371253 0.572088 1.370961 1.371348 0.244247 1.592370 0.135712 0.911345 0.228778 1.543468 1.190091 1.504171 1.491159))

(define (make-all-57)
  (set! *with-inset-graph* #f)
  (let* ((samples 1000)
	 (incr (/ (* 2 pi) samples)))
    (with-sound (:channels 1 :clipped #f)
      (do ((i 0 (+ i 1))
	   (x 0.0 (+ x incr)))
	  ((= i samples))
	(let ((sum 0.0))
	  (do ((k 1 (+ k 1)))
	      ((= k 58))
	    (let ((val (sin (+ (* k x) (* pi (phases (- k 1)))))))
	      (set! sum (+ sum val))))
	  (outa i sum)))))

  (set! (y-bounds) (list -8.0 8.0))
  (set! *channel-style* channels-superimposed)
  (set! *axis-color* (make-color 0 0 0))
  (set! *x-axis-style* x-axis-in-samples)
  (set! *selected-graph-color* (make-color 1 1 1))
  (set! *selected-data-color* (make-color 0 0 0))
  (set! *axis-label-font* "9x15")
  (set! (x-axis-label) "57 harmonics with peak at 7.546")
  )

(define odd-phases #(0.000000 -0.095905 1.360419 0.638244 0.752436 0.060307 1.680434 0.892474 1.556627 1.342822 1.202039 0.989766 0.747386 1.502768 1.484789 1.280575 -0.299617 0.648918 1.386594 0.570314 0.971680 0.602106 1.411224 0.349887 1.776881 0.686211 -0.138570 0.102115 0.187653 1.480790 0.475407 0.080540 0.078971 0.288194 0.529704 0.929207 1.248880 1.402125 0.332857 1.263541 0.757496 0.254501 0.084949 1.308375 0.041441 0.288389 1.222780 0.362725 1.537117 1.518618 0.267187 0.845609 0.722902 0.451852 0.582589 0.839423 1.817054))

(define (make-odd-57)
  (set! *with-inset-graph* #f)
  (let* ((samples 1000)
	 (incr (/ (* 2 pi) samples)))
    (with-sound (:channels 1 :clipped #f)
      (do ((i 0 (+ i 1))
	   (x 0.0 (+ x incr)))
	  ((= i samples))
	(let ((sum 0.0))
	  (do ((k 1 (+ k 1))
	       (j 1 (+ j 2)))
	      ((= k 58))
	    (let ((val (sin (+ (* j x) (* pi (odd-phases (- k 1)))))))
	      (set! sum (+ sum val))))
	  (outa i sum)))))

  (set! (y-bounds) (list -8.0 8.0))
  (set! *channel-style* channels-superimposed)
  (set! *axis-color* (make-color 0 0 0))
  (set! *x-axis-style* x-axis-in-samples)
  (set! *selected-graph-color* (make-color 1 1 1))
  (set! *selected-data-color* (make-color 0 0 0))
  (set! *axis-label-font* "9x15")
  (set! (x-axis-label) "57 odd harmonics with peak at 7.564")
  )

(define all-99 #(0.000000 0.597494 1.146001 -0.056648 1.705293 0.247794 1.067079 1.589758 1.638162 1.207186 0.711609 0.710553 -0.195687 0.350442 0.679684 1.653746 -0.460484 -0.156879 1.629420 1.730071 1.077540 0.075860 0.435827 1.574017 0.450715 1.581154 -0.027175 1.502323 1.501097 0.855975 1.269118 1.563924 1.244477 0.428054 1.250656 0.668151 0.672807 0.481658 1.215020 0.229865 0.052263 -0.265466 0.722697 0.484686 1.525745 -0.088395 1.682325 1.764438 0.384531 0.550629 -0.009864 1.443840 0.844832 1.132436 -0.107693 0.137994 0.009887 1.832991 0.076907 0.020473 0.102198 0.283702 1.246352 0.965046 0.026752 1.471014 0.126851 0.144964 0.731028 -0.335345 0.712331 0.471273 1.705158 0.467571 1.388009 0.875431 0.986268 1.669037 0.667955 0.887678 1.688981 -0.459336 1.461469 1.135012 0.449583 0.176052 1.407825 1.801166 0.208742 1.880027 0.895566 1.761286 1.021896 0.520239 1.466186 0.733284 1.188215 1.584263 1.296521))

(define (make-all-99)
  (set! *with-inset-graph* #f)
  (let* ((samples 1200)
	 (incr (/ (* 2 pi) samples)))
    (with-sound (:channels 1 :clipped #f)
      (do ((i 0 (+ i 1))
	   (x 0.0 (+ x incr)))
	  ((= i samples))
	(let ((sum 0.0))
	  (do ((k 1 (+ k 1)))
	      ((= k 100))
	    (let ((val (sin (+ (* k x) (* pi (all-99 (- k 1)))))))
	      (set! sum (+ sum val))))
	  (outa i sum)))))

  (set! (y-bounds) (list -10.0 10.0))
  (set! *channel-style* channels-superimposed)
  (set! *axis-color* (make-color 0 0 0))
  (set! *x-axis-style* x-axis-in-samples)
  (set! *selected-graph-color* (make-color 1 1 1))
  (set! *selected-data-color* (make-color 0 0 0))
  (set! *axis-label-font* "9x15")
  (set! (x-axis-label) "99 harmonics with peak at 9.9431")
  )
-->


<p>
As N increases, the minimum peak amplitude waveform can approach
white noise (in sound as well as appearance); here is a small portion of one period when n=65536 (the prescaling peak was 704):
</p>


<img class="indented" src="pix/s65536.png" alt="65536 harmonics">


<p>but the waveforms generated from the initial-phase polynomials look more regular (this is with n=64):
</p>

<img class="indented" src="pix/s64pi.png" alt="64 harmonics using pi/n formula">


<!--
(define (try n a b)
  (let ((gens (make-vector n #f))
	(sr (if (< n 1000) 44100 (* n 128))))
    (with-sound (:statistics #t :srate sr)
      (do ((i 0 (+ i 1)))
	  ((= i n))
        (set! (gens i) (make-oscil (+ 1 (* i 1)) 
				   (+ (* a i i) (* b i)))))
       (do ((i 0 (+ i 1)))
	   ((= i sr))
	 (let ((sum 0.0))
	   (do ((k 0 (+ k 1)))
	       ((= k n))
	     (set! sum (+ sum (oscil (gens k)))))
	   (outa i (* 1.0 sum)))))
    (list (log (maxamp) n) (* 1.0 (/ (maxamp-position) sr)))))

    (try 100 (+ pi (/ pi 100)) (/ pi -2.0))
     same settings as above but
     (set! (x-axis-label) "n=64, initial-phase: (pi+pi/64)*i*i - pi*i/2")
-->

<!-- this moves from cosines to the minimum amp phases:

(let ((93-phases  #(0.000000 0.102641 0.679230 0.798388 0.598526 0.445036 1.682481 1.416478 1.010866 0.838753 0.518866 0.185140 -0.260801 1.643327 1.645133 1.587871 1.510095 1.367190 1.252764 1.075109 0.997402 1.226792 1.097666 1.109286 1.266675 1.142806 1.396415 1.366757 1.323435 -0.151657 0.110933 0.254314 0.125232 0.426419 0.874355 1.227943 1.386454 1.437438 0.183960 0.673205 0.896736 1.317085 1.421345 0.557215 0.650544 0.979705 1.599286 -0.027664 0.967924 1.389243 -0.027060 0.800953 1.098758 1.686133 0.493843 1.257456 0.105617 0.800125 0.006765 0.139250 1.353019 -0.059007 1.198209 0.066444 0.431719 1.470864 0.547882 1.294688 0.757592 1.690943 0.714913 1.735237 0.542409 1.804533 0.779629 -0.296056 1.090213 0.178123 1.832019 1.000948 -0.131923 1.161644 0.360890 0.065736 1.232224 0.792139 0.176636 1.688866 1.432871 0.734257 0.042563 1.592538 0.764029)))
  (let ((freq 30.0)
	(dur 3.0)
	(n 93))
    (with-sound ()
      (let ((samps (floor (* dur 44100))))
	(do ((i 0 (+ i 1)))
	    ((= i n))
	  (let ((off (/ (* pi (- 0.5 (93-phases i))) (* dur 44100)))
		(h (hz->radians (* freq (+ i 1)))))
	    (do ((k 0 (+ k 1))
		 (phase (* pi 0.5) (+ phase h off)))
		((= k samps))
	      (outa k (* .01 (sin phase))))))))))

or much faster and using 1024:
  (let ((freq 15.0)
	(dur 5.0)
	(n 1024))
    (with-sound ()
      (let ((samps (floor (* dur 44100)))
	    (1/n (/ 1.0 n))
	    (freqs (make-float-vector n))
	    (phases (make-float-vector n (* pi 0.5))))
	(do ((i 0 (+ i 1)))
	    ((= i n))
	  (let ((off (/ (* pi (- 0.5 (1024-phases i))) (* dur 44100)))
		(h (hz->radians (* freq (+ i 1)))))
	    (set! (freqs i) (+ h off))))
	(let ((ob (make-oscil-bank freqs phases)))
	  (do ((k 0 (+ k 1)))
	      ((= k samps))
	    (outa k (* 1/n (oscil-bank ob))))))))

but that is dominated by the "fm-sweep" effect. 

(let ((98-phases #(0.000000 -0.183194 0.674802 1.163820 -0.147489 1.666302 0.367236 0.494059 0.191339 0.714980 1.719816 0.382307 1.017937 0.548019 0.342322 1.541035 0.966484 0.936993 -0.115147 1.638513 1.644277 0.036575 1.852586 1.211701 1.300475 1.231282 0.026079 0.393108 1.208123 1.645585 -0.152499 0.274978 1.281084 1.674451 1.147440 0.906901 1.137155 1.467770 0.851985 0.437992 0.762219 -0.417594 1.884062 1.725160 -0.230688 0.764342 0.565472 0.612443 0.222826 -0.016453 1.527577 -0.045196 0.585089 0.031829 0.486579 0.557276 -0.040985 1.257633 1.345950 0.061737 0.281650 -0.231535 0.620583 0.504202 0.817304 -0.010580 0.584809 1.234045 0.840674 1.222939 0.685333 1.651765 0.299738 1.890117 0.740013 0.044764 1.547307 0.169892 1.452239 0.352220 0.122254 1.524772 1.183705 0.507801 1.419950 0.851259 0.008092 1.483245 0.608598 0.212267 0.545906 0.255277 1.784889 0.270552 1.164997 -0.083981 0.200818 1.204088)))
  
  (let ((freq 10.0)
	(dur 5.0)
	(n 98))
    (with-sound ()
      (let ((samps (floor (* dur 44100)))
	    (1/n (/ 1.0 n))
	    (freqs (make-float-vector n))
	    (phases (make-float-vector n (* pi 0.5))))
	(do ((i 0 (+ i 1)))
	    ((= i n))
	  (let ((off (/ (* pi (- 0.5 (98-phases i))) (* dur 44100)))
		(h (hz->radians (* freq (+ i 1)))))
	    (set! (freqs i) (+ h off))))
	(let ((ob (make-oscil-bank freqs phases)))
	  (do ((i 0 (+ i 1))) ; get rid of the distracting initial click
	      ((= i 1000))
	    (oscil-bank ob))
	  (do ((k 0 (+ k 1)))
	      ((= k samps))
	    (outa k (* 1/n (oscil-bank ob)))))))))

-->





<!--  FILE: piano  -->

<div class="header" id="pianodoc">piano</div>

<!-- main-index |pianodoc:piano model -->

<p>This instrument is a translation of CLM's piano.ins, a piano physical model by Scott van Duyne; see
Julius O. Smith and Scott A. Van Duyne, "Commuted piano synthesis," in Proc. Int. Computer Music Conf., Banff, Canada, September 1995, pp. 335 - 342.
To paraphrase, the model includes multiple coupled strings, a nonlinear hammer, and an arbitrarily large soundboard and enclosure.
The actual instrument name is 'p':
</p>

<pre class="indented">
(<a class=quiet href="#wsdoc">with-sound</a> ()
  (do ((i 0 (+ i 1))) ((= i 7))
    (p (* i .5) :duration .5                    ; generate a sequence of 1/2 second tones
                :keyNum (+ 24 (* 12 i))         ; jump by octaves
                :strike-velocity .5             ; 0 to 1, 0 is softest played note, 1 is loud note
                :amp .4		                ; overall volume level
                :DryPedalResonanceFactor .25))) ; 0 no open string resonance
				                ; 1.0 is about full resonance of dampers raised
				                ; can be greater than 1.0
</pre>

<p>"p" has lots of parameters, and I really don't know what they do.  The interested reader should
goof around with them.
</p>

<pre class="indented">
<em class=emdef>p</em> (start 
   (duration 1.0)
   (keyNum 60.0)              ; middleC=60: can use fractional part to detune
   (strike-velocity 0.5)      ; corresponding normalized velocities (range: 0.0--1.0)
   (pedal-down #f)	      ; set to t for sustain pedal down...pedal-down-times not yet impl.
   (release-time-margin 0.75) ; extra compute time allowed beyond duration
   (amp .5)                   ; amp scale of noise inputs...
   (detuningFactor 1.0)
   (detuningFactor-table ())
   (stiffnessFactor 1.0)
   (stiffnessFactor-table ())
   (pedalPresenceFactor .3)
   (longitudinalMode 10.5)
   (StrikePositionInvFac -0.9)
   (singleStringDecayRateFactor 1.0)
   
   ;; parameter tables indexed by keyNum
   ;; you can override the loudPole-table by directly setting :loudPole to a value

   loudPole (loudPole-table default-loudPole-table)
   softPole (softPole-table default-softPole-table)
   loudGain (loudGain-table default-loudGain-table)
   softGain (softGain-table default-softGain-table)
   strikePosition (strikePosition-table default-strikePosition-table)
   detuning2 (detuning2-table default-detuning2-table)
   detuning3 (detuning3-table default-detuning3-table)
   stiffnessCoefficient (stiffnessCoefficient-table default-stiffnessCoefficient-table)
   singleStringDecayRate (singleStringDecayRate-table default-singleStringDecayRate-table)
   singleStringZero (singleStringZero-table default-singleStringZero-table)
   singleStringPole (singleStringPole-table default-singleStringPole-table)
   releaseLoopGain (releaseLoopGain-table default-releaseLoopGain-table)
   DryTapFiltCoeft60 (DryTapFiltCoeft60-table default-DryTapFiltCoeft60-table)
   DryTapFiltCoefTarget (DryTapFiltCoefTarget-table default-DryTapFiltCoefTarget-table)
   DryTapFiltCoefCurrent (DryTapFiltCoefCurrent-table default-DryTapFiltCoefCurrent-table)
   DryTapAmpt60 (DryTapAmpt60-table default-DryTapAmpt60-table)
   sustainPedalLevel (sustainPedalLevel-table default-sustainPedalLevel-table)
   pedalResonancePole (pedalResonancePole-table default-pedalResonancePole-table)
   pedalEnvelopet60 (pedalEnvelopet60-table default-pedalEnvelopet60-table)
   soundboardCutofft60 (soundboardCutofft60-table default-soundboardCutofft60-table)
   DryPedalResonanceFactor (DryPedalResonanceFactor-table default-DryPedalResonanceFactor-table)
   unaCordaGain (unaCordaGain-table default-unaCordaGain-table))
</pre>

<p>Here is another example; there are a couple other examples at the end of piano.scm:
</p>

<pre class="indented">
(<a class=quiet href="#wsdoc">with-sound</a> ()
  (do ((i 0 (+ i 1))) ((= i 8))
    (p (* i .5) :duration .5 :keyNum (+ 24 (* 12 i)) :strike-velocity .5 :amp .4 :DryPedalResonanceFactor .25
     :detuningFactor-table '(24 5 36 7.0 48 7.5 60 12.0 72 20 84 30 96 100 108 300)
		    ; scales the above detuning values so 1.0 is nominal detuning, 
                    ;  0.0 is exactly in tune,  &gt; 1.0 is out of tune
     :stiffnessFactor-table '(21 1.5 24 1.5 36 1.5 48 1.5 60 1.4 72 1.3 84 1.2 96 1.0 108 1.0))))
		    ; 0.0 to 1.0 is less stiff, 1.0 to 2.0 is more stiff
</pre>

<p>In Ruby:
</p>

<pre class="indented">
include Piano
with_sound(:clm, false, :channels, 1) do
  7.times do |i|
    p(i * 0.5,
      :duration, 0.5,
      :keyNum, 24 + 12.0 * i,
      :strike_velocity, 0.5,
      :amp, 0.4,
      :dryPedalResonanceFactor, 0.25)
  end
end
</pre>


<div class="seealso">
see also: &nbsp; <a href="#stereoflute">flute</a> &nbsp; <a href="#maracadoc">maraca</a> &nbsp; <a href="#pluck">pluck</a> &nbsp; <a href="#prc95doc">prc95</a> &nbsp; <a href="#singerdoc">singer</a> &nbsp; <a href="#straddoc">strad</a>
</div>




<!--  FILE: play  -->

<div class="header" id="playdoc">play</div>

<p>This file has a variety of "real-time" audio output examples.  It is almost entirely obsolete.
</p>


<!-- play-with-amps -->
<pre class="indented">
<em class=emdef>play-with-amps</em> snd :rest amps
</pre>

<p>play-with-amps plays the sound 'snd' with each channel scaled by the corresponding 
amp: (play-with-amps 0 1.0 0.5) plays sound 0's
channel 1 at full amplitude, and
channel 2 at half amplitude.
</p>
<div class="spacer"></div>


<!-- play-often -->
<pre class="indented">
<em class=def id="playoften">play-often</em> n
<em class=def id="playuntilcg">play-until-c-g</em> 
<em class=def id="playregionforever">play-region-forever</em> reg
</pre>
<p>play-often plays the selected sound 'n' times.
play-until-c-g plays the selected sound until you interrupt it via C-g.
Similarly, play-region-forever plays region 'reg' until you interrupt it with C-g.
</p>

<pre class="indented">
(<a class=quiet href="extsnd.html#bindkey">bind-key</a> #\p 0 
  (lambda (n) 
    "play often" 
    (play-often (max 1 n))))

(<a class=quiet href="extsnd.html#bindkey">bind-key</a> #\r 0 
  (lambda (n) 
    "play region forever" 
    (play-region-forever n)))
</pre>

<p>Now C-u 31 p plays the current sound 31 times; C-u 3 r plays region 3 until we type C-g.
</p>
<div class="spacer"></div>


<!-- play-sines -->
<pre class="indented">
<em class=def id="playsine">play-sine</em> freq amp
<em class=def id="playsines">play-sines</em> freqs-and-amps
</pre>

<p>play-sine plays a one-second sine wave at the given frequency and amplitude: (play-sine 440 .1).
play-sines produces a spectrum given a list of lists of frequency and amplitude:
</p>

<pre class="indented">
(play-sines '((425 .05) (450 .01) (470 .01) (546 .02) (667 .01) (789 .034) (910 .032)))
</pre>

<div class="spacer"></div>


<!-- start-dac -->
<pre class="indented">
<em class=def id="startdac">start-dac</em> 
<em class=emdef>stop-dac</em> 
</pre>

<p>start-dac opens the DAC ready for sound output, and stop-dac closes it.
</p>
<div class="spacer"></div>



<!--  FILE: poly  -->

<div class="header" id="polydoc">poly</div>

<p>This file contains various functions related to the CLM polynomial function.  A polynomial here
is a vector (for complex coefficients) holding the polynomial coefficients from lowest
to highest (i.e. the constant is (v 0), x+2 is (float-vector 2 1), etc).
</p>

<!-- main-index |polydoc:polynomial operations -->

<pre class="indented">
<em class=emdef>poly+</em> p1 p2              ; new poly = p1 + p2
<em class=emdef>poly*</em> p1 p2              ; new poly = p1 * p2
<em class=emdef>poly/</em> p1 p2              ; (list quotient-poly remainder-poly) = p1 / p2
<em class=emdef>poly-derivative</em> p1       ; new poly = Dp1
<em class=emdef>poly-reduce</em> p1           ; new poly = p1 without high zeros
<em class=emdef>poly-gcd</em> p1 p2           ; new poly = gcd(p1, p2)
<em class=emdef>poly-roots</em> p1            ; list of roots of p1
<em class=emdef>poly-resultant</em> p1 p2     ; resultant of p1 and p2
<em class=emdef>poly-discriminant</em> p1     ; discriminant of p1
</pre>

<p>
poly+ adds two polynomials, and poly* multiplies two polynomials.
poly/ divides two polynomials, with a few restrictions, and returns
a list containing the quotient and remainder polynomials.  poly-derivative
returns the derivative of a polynomial.  In all these cases, the resultant
polynomials may have extra high-degree entries whose coefficients are zero.
To remove these pointless coefficients, use poly-reduce.
The last functions are
just for fun.
</p>

<p>You can treat a sound as a set of polynomial coefficients; then, for example,
convolution the infinitely slow way is poly*:
</p>

<pre class="indented">
(float-vector-&gt;channel (poly* (channel-&gt;float-vector 0 (<a class=quiet href="extsnd.html#framples">framples</a>)) (float-vector 2.0))) ; no, this is not serious
</pre>


<div class="seealso">
see also: &nbsp; <a href="sndclm.html#polynomial">polynomial</a> &nbsp; 
</div>




<!--  FILE: prc95  -->

<div class="header" id="prc95doc">prc95</div>

<!-- INDEX prc95doc:Physical Models -->
<p>prc95.scm is a translation to Snd of Perry Cook's (1995) physical modelling toolkit; prc-toolkit95.lisp 
in CLM.  One starting point for physical modelling is Smith, "Music Applications of Digital Waveguides", CCRMA, Stan-M-39, 1987,
or Julius's <A HREF="http://ccrma.stanford.edu/~jos/">home</A> page, or
any of several classic papers also by Julius Smith.  Perry's own version of this code can be
found in <A HREF="http://ccrma.stanford.edu/CCRMA/Software/STK/">STK</A>.
The example instruments are:
</p>

<pre class="indented">
<em class=emdef>plucky</em> beg dur freq amplitude maxa  ; plucked string
<em class=emdef>bow</em> beg dur frq amplitude maxa      ; bowed string
<em class=emdef>brass</em> beg dur freq amplitude maxa   
<em class=emdef>clarinet</em> beg dur freq amplitude maxa 
<em class=emdef>flute</em> beg dur freq amplitude maxa

(<a class=quiet href="#wsdoc">with-sound</a> ()
  (plucky 0 .3 440 .2 1.0)
  (bow .5 .3 220 .2 1.0)
  (brass 1 .3 440 .2 1.0)
  (clarinet 1.5 .3 440 .2 1.0)
  (flute 2 .3 440 .2 1.0))
</pre>


<div class="seealso">
see also: &nbsp;
maraca: <a href="#maracadoc">maraca.scm, maraca.rb</a> &nbsp;
piano: <a href="#pianodoc">piano.scm, piano.rb</a> &nbsp;
singer: <a href="#singerdoc">singer.scm, singer.rb</a> &nbsp;
bowed string: <a href="#straddoc">strad.scm, strad.rb</a> &nbsp;
flute: <a href="#clminsdoc">clm-ins.scm</a> &nbsp;
string: <a href="#vibratinguniformcircularstring">vibrating-string</a> &nbsp;
plucked string: pluck in clm-ins.scm
</div>



<!--  FILE: pvoc  -->

<div class="header" id="pvocdoc">pvoc</div>

<p>
This is the same as the CLM <a href="sndclm.html#phase-vocoder">phase-vocoder</a> generator, but implemented in Scheme.  If you're interested
in how the thing works, I think the Scheme version is easiest to understand; the Common Lisp version 
is in mus.lisp, and the C version is in clm.c.
</p>

<pre class="indented">
<em class=emdef>make-pvocoder</em> fftsize overlap interp analyze edit synthesize
<em class=emdef>pvocoder</em> gen input
<em class=emdef>pvoc</em> (fftsize 512) (overlap 4) (time 1.0) (pitch 1.0) (gate 0.0) (hoffset 0.0) (snd 0) (chn 0)
</pre>

<p>The 'analyze', 'edit', and 'synthesize' arguments to make-pvocoder are
functions that are applied as needed during pvocoder processing; similarly, the 'input'
argument to pvocoder can be a function.
</p>

<pre class="indented">
(begin
  (<a class=quiet href="extsnd.html#opensound">open-sound</a> "oboe.snd")
  (let ((pv (<em class=red>make-pvocoder</em> 256 4 64))
        (rd (<a class=quiet href="extsnd.html#makesampler">make-sampler</a> 0)))
    (<a class=quiet href="extsnd.html#mapchannel">map-channel</a> (lambda (y) (<em class=red>pvocoder</em> pv rd)))))
</pre>

<p>
pvoc.scm also contains a few examples of using the CLM phase-vocoder generator:
</p>

<pre class="indented">
(define test-pv-4
  (lambda (gate)
    (let ((pv (<a class=quiet href="sndclm.html#make-phase-vocoder">make-phase-vocoder</a>
                (let ((reader (<a class=quiet href="extsnd.html#makesampler">make-sampler</a> 0)))
                  (lambda (dir) 
                    (reader)))
		512 4 128 1.0
		#f ;no change to analysis
		(lambda (v)
		  (do ((N (length v))
		       (i 0 (+ i 1)))
		      ((= i N) #t)
		    (if (&lt; ((phase-vocoder-amp-increments v) i) gate)
		        (set! ((phase-vocoder-amp-increments v) i) 0.0))))
	        #f))) ;no change to synthesis
      (<a class=quiet href="extsnd.html#mapchannel">map-channel</a> (lambda (val)
		  (<a class=quiet href="sndclm.html#phase-vocoder">phase-vocoder</a> pv))))))
</pre>

<p>This sets up a phase-vocoder generator whose edit function is squelching soft partials.
In this case, the input function is reading the currently selected channel.
</p>
<p>
pvoc is yet another (unoptimized) phase-vocoder;
it applies the phase-vocoder
to the current sound; 'pitch' specifies the pitch transposition ratio, 
'time' specifies the time dilation ratio,
'gate' specifies a resynthesis gate in dB (partials with amplitudes lower than
the gate value will not be synthesized), 'hoffset' is a pitch offset in Hz.
</p>

<pre class="indented">
(pvoc :time 2.0)
</pre>


<div class="seealso">
see also: &nbsp; <a href="sndclm.html#phase-vocoder">phase-vocoder</a> &nbsp; <a href="#pins">pins</a>
</div>




<!--  FILE: rgb  -->

<div class="header" id="rgbdoc">rgb</div>

<p>rgb.scm (rgb.rb) is a translation of the standard X11 color names into Snd
color objects.
</p>

<pre class="indented">
(define snow (<a class=quiet href="extsnd.html#makecolor">make-color</a> 1.00 0.98 0.98))
</pre>

<p>is taken from the line</p>

<pre class="indented">
255 250 250             snow
</pre>

<p>/usr/lib/X11/rgb.txt.  The choice of a float between 0.0 and 1.0 (rather
than an integer between 0 and 255) mimics PostScript;
as video hardware has improved over the years, there's
less and less need for these elaborate color names, and less
reason (except perhaps psychophysical) to limit these numbers to bytes.
There is one gotcha in this file &mdash; X11 defines a color named "tan"
which is already used by Scheme, so (at the suggestion of Dave Phillips)
this color is named "tawny" in rgb.scm.  rgb.scm exports only *rgb* which
is an environment holding all the color names and values.
</p>



<!--  FILE: rubber  -->

<div class="header" id="rubberdoc">rubber</div>

<pre class="indented">
<em class=def id="rubbersound">rubber-sound</em> stretch-factor snd chn
</pre>

<p>
rubber-sound tries to stretch or contract a sound (in time); it scans the sound
looking for stable (periodic) sections, then either deletes periods or interpolates new ones
to shorten or lengthen the sound.  It still needs a lot of robustification.
The algorithm is 1) remove all frequencies below 16 Hz, 2) resample the file to be
ten times longer (interpolating samples), 3) make a list of upward zero crossings,
4) using autocorrelation decide where the next fundamental zero crossing probably
is and see how much difference there is between the current period and the next,
5) check intermediate crossing weights and if the autocorrelation weight is not
the smallest, throw away this crossing, 6) sort the remaining crossings by least weight,
7) interpolate or delete periods until the sound has been sufficiently lengthened or
shortened.
rubber-sound is incredibly slow, and almost never works.  The idea seems good however...

<!-- ((((((( --><!-- this matches the preceding open parens for make-index.scm's benefit -->
</p>

<div class="seealso">
see also: &nbsp; <a href="#clmexpsrc">clm-expsrc</a> &nbsp; <a href="#expsrc">expsrc</a> &nbsp; <a href="#pvocdoc">pvoc</a> &nbsp; <a href="#ssbbank">ssb-bank</a>
</div>



<!-- FILE: s7test -->

<div class="header" id="s7testdoc">s7test</div>

<p>s7test.scm is a regression test for s7.  Any additional tests are most welcome!
</p>


<!--  FILE: selection  -->

<div class="header" id="selectiondoc">selection</div>


<!-- filter-selection-and-smooth -->
<pre class="indented">
<em class=def id="filterselectionandsmooth">filter-selection-and-smooth</em> ramp-dur flt order
</pre>

<p>filter-selection-and-smooth filters the current selection with flt, then mixes it back into the original using
ramp-dur to set how long the cross-fade ramps are.
</p>

<pre class="indented">
(filter-selection-and-smooth .01 (float-vector .25 .5 .5 .5 .25))
</pre>

<div class="spacer"></div>


<!-- make-selection -->
<pre class="indented">
<em class=def id="makeselection">make-selection</em> beg end snd chn
</pre>

<p>make-selection makes a selection, like <a href="extsnd.html#makeregion">make-region</a> but without creating
a region.  make-selection follows snd's sync field, and applies to all snd's channels if chn is not specified. end defaults
to end of channel, beg defaults to 0, and snd defaults to the currently selected sound.
</p>

<pre class="indented">
(make-selection 1000 2000)
</pre>

<div class="spacer"></div>


<!-- replace-with-selection -->
<pre class="indented">
<em class=def id="replacewithselection">replace-with-selection</em> 
</pre>

<p>replace-with-selection replaces any data at the cursor with the
current selection.
</p>
<div class="spacer"></div>


<!-- selection-members -->
<pre class="indented">
<em class=def id="selectionmembers">selection-members</em> 
</pre>

<p>selection-members returns a list of lists of '(snd chn) indicating the channels participating in the current selection.
It is the selection-oriented version of <a href="#allchans">all-chans</a>.
</p>
<div class="spacer"></div>


<!-- swap-selection-channels -->
<pre class="indented">
<em class=def id="swapselectionchannels">swap-selection-channels</em>
</pre>

<p>swap-selection-channels swaps the current selection's channels.
</p>
<div class="spacer"></div>



<!-- with-temporary-selection -->
<pre class="indented">
<em class=def id="withtemporaryselection">with-temporary-selection</em> thunk beg dur snd chn
</pre>

<p>with-temporary selection saves the current selection placement, makes a new selection
of the data from sample 'beg' to beg + dur in the given channel, calls 'thunk', then
restores the previous selection (if any).  It returns whatever 'thunk' returned.
</p>



<!--  FILE: singer  -->

<div class="header" id="singerdoc">singer</div>

<!-- main-index |singerdoc:singer -->
<!-- main-index |singerdoc:voice physical model -->

<p>singer.scm is an implementation of Perry Cook's
physical model of the vocal tract as described in:
</p>

<pre class="indented">
  Cook, Perry R. "Synthesis of the Singing Voice Using a Physically Parameterized Model of the Human Vocal Tract"
     Published in the Proceedings of the International Computer Music Conference, Ohio 1989 
     and as Stanford University Department of Music Technical Report Stan-M-57, August 1989.
 
 ---- "Identification of Control Parameters in an Articulatory Vocal Tract Model, with Applications 
    to the Synthesis of Singing," Ph.D. Thesis, Stanford University Department of Music Technical Report 
    Stan-M-68, December 1990.

 ----  "SPASM, a Real-time Vocal Tract Physical Model Controller; and Singer, the Companion Software 
    Synthesis System", Computer Music Journal, vol 17 no 1 Spring 1993.
</pre>

<p>
singer.scm is a translation of Perry's singer.c.
I think that Perry's code assumes a sampling rate of 22050; you'll need to fix up lots of
lengths in the code to run at 44100.  
The singer instrument looks deceptively simple:
</p>

<pre class="indented">
<em class=emdef>singer</em> beg amp data
</pre>

<p>
but all the complexity is hidden in the 'data' parameter.  
'data' is a list of lists; each imbedded list has the form: '(dur shape glot pitch glotamp noiseamps vibramt).
The 'shape' and 'glot' entries are themselves lists; I think the 'glot'
list describes the glottal pulse.  I wish I could fully explain all these lists, but 
I translated this code a very long time ago, and can't remember any details.  You'll
have to read the code, or perhaps find something in Perry's publications.
In any case, here's an example:
</p>

<pre class="indented">
(<a class=quiet href="#wsdoc">with-sound</a> () 
  (singer 0 .1 (list (list .4 ehh.shp test.glt 523.0 .8 0.0 .01) 
                     (list .6 oo.shp test.glt 523.0 .7 .1 .01))))
</pre>

<p>
The *.shp and *.glt data is defined at the end of singer.scm.  For example:
</p>

<pre class="indented">
(define test.glt (list 10 .65 .65))
(define ee.shp (list 8 1.02 1.637 1.67 1.558 0.952 0.501 0.681 0.675 0.9 -0.4 1.0 0.0 0.0 0.0 0.0 0.0 0.0))
</pre>

<p>
A more complex example is singer's attempt to say "requiem":
</p>

<pre class="indented">
(<a class=quiet href="#wsdoc">with-sound</a> ()
  (singer 0 .1 (list (list .05 ehh.shp test.glt 523.0 0.8 0.0 .01) 
       (list .15 ehh.shp test.glt 523.0 0.8 0.0 .01) 
       (list .05 kkk.shp test.glt 523.0 0.0 0.0 .01) 
       (list .05 kkk.shp test.glt 523.0 0.0 0.0 .01) 
       (list .02 kk+.shp test.glt 523.0 0.0 1.0 .01) 
       (list .08 kk+.shp test.glt 523.0 0.0 0.2 .01) 
       (list .05 ooo.shp test.glt 523.0 0.8 0.0 .01) 
       (list .15 ooo.shp test.glt 523.0 0.8 0.0 .01) 
       (list .05 eee.shp test.glt 523.0 0.8 0.0 .01) 
       (list .15 eee.shp test.glt 523.0 0.8 0.0 .01) 
       (list .05 ehh.shp test.glt 523.0 0.8 0.0 .01) 
       (list .15 ehh.shp test.glt 523.0 0.8 0.0 .01) 
       (list .05 mmm.shp test.glt 523.0 0.8 0.0 .01) 
       (list .15 mmm.shp test.glt 523.0 0.8 0.0 .01) 			      
       (list .10 mmm.shp test.glt 523.0 0.0 0.0 .01))))
</pre>


<div class="seealso">
see also: &nbsp; <a href="#fofins">fofins</a> &nbsp; <a href="#reson">reson</a> &nbsp; <a href="#pqwvox">pqw-vox</a> &nbsp; <a href="#fmvox">vox</a>
</div>




<!--  FILE: snd15  -->

<div class="header" id="sndolddoc">snd15</div>

<p>This file contains several procedures
that were removed from or renamed in earlier versions of Snd (in Ruby, look in extensions.rb).  
</p>




<!--  FILE: snddiff  -->

<div class="header" id="snddiffdoc">snddiff</div>

<p>The snddiff function tries to detect how one sound differs from another.
</p>

<!-- snddiff -->
<pre class="indented"><a class=def>snddiff</a> snd0 chn0 snd1 chn1
</pre>

<p>This could use about a lifetime's work, but it does find some differences:
</p>

<pre class="indented">
                 ;; start with two identical sounds:
&gt; (map short-file-name (sounds))
("oboe.snd" "oboe.snd")
&gt; (snddiff 0 0 1 0)
no-difference
                 ;; snddiff can find individual sample differences:
&gt; (set! (sample 1000 0 0) 0.5)
0.5
&gt; (snddiff 0 0 1 0)
(differences ((1000 0.5 0.0328369140625)))
                 ;; and scaling changes (we reverted the previous change):
&gt; (scale-channel 2.0)
2.0
&gt; (snddiff 0 0 1 0)
(scale 2.0)
                 ;; and some initial delays:
&gt; (pad-channel 0 200 0 0)
0
&gt; (snddiff 0 0 1 0)
(lag 200 no-difference 0.0 #f #f #f)
</pre>




<!--  FILE: snd-gl  -->

<div class="header" id="sndgldoc">snd-gl</div>

<p>snd-gl.scm has examples of using <A HREF="http://www.mesa3d.org/">OpenGL</A>.  To try out these functions, build Snd
with GL: configure --with-gl.  You can tell if your current Snd has OpenGL loaded by checking the
*features* list for 'gl: (provided? 'gl).
</p>

<!-- complexify -->
<pre class="indented">
<em class=def id="complexify">complexify</em> 
</pre>

<p>complexify displays FFT data in the complex plane; each bin is 
rotated so that they all stack along the x axis, with
a line drawn from the x axis to the current real/imaginary
point (as (z, y)), so as you move (slowly) through a
file, you'll see the phase info as well as the magnitude &mdash;
the vectors whirl around in each slice of the complex 
plane.  Use the View:Orientation dialog to change the
viewing angle.  To move one sample at a time through a sound,
you could bind the arrow keys:
</p>

<pre class="indented">
(<a class=quiet href="extsnd.html#bindkey">bind-key</a> "Left" 0 (lambda () 
                     (set! (<a class=quiet href="extsnd.html#leftsample">left-sample</a>) (max 0 (- (<a class=quiet href="extsnd.html#leftsample">left-sample</a>) 1))) 
                     <a class=quiet>keyboard-no-action</a>))
(<a class=quiet href="extsnd.html#bindkey">bind-key</a> "Right" 0 (lambda () 
                     (set! (<a class=quiet href="extsnd.html#leftsample">left-sample</a>) (min (<a class=quiet href="extsnd.html#framples">framples</a>) (+ 1 (<a class=quiet href="extsnd.html#leftsample">left-sample</a>)))) 
                     <a class=quiet>keyboard-no-action</a>))
</pre>

<div class="spacer"></div>


<!-- gl-dump-state -->
<pre class="indented">
<em class=emdef>gl-dump-state</em>
</pre>

<p>gl-dump-state displays much of the current GL graphics state.
</p>
<div class="spacer"></div>


<!-- gl-info -->
<pre class="indented">
<em class=emdef>gl-info</em> 
</pre>

<p>gl-info prints out information about the current GL system setup.  
</p>
<div class="spacer"></div>


<div class="seealso">
see also: &nbsp; <a href="extsnd.html#glspectrogram">glSpectrogram</a> &nbsp; <a href="grfsnd.html#sndandgl">OpenGL</a>
</div>




<!-- INDEX variabledisplay:Debugging (instruments) -->
<!-- main-index |sndmotifdoc:user interface extensions -->


<!--  FILE: snd-motif, snd-xm  -->

<div class="header" id="sndmotifdoc">snd-motif, snd-xm</div>

<p>snd-motif.scm has a variety of user-interface extensions that rely on the Motif module (xm.c).
In Ruby, see snd-xm.rb.
</p>

<div class="spacer"></div>

<!-- add-amp-controls -->
<pre class="indented">
<em class=def id="addampcontrols">add-amp-controls</em>
</pre>

<p>add-amp-controls adds amplitude sliders to the control panel
for multichannel sounds so that each channel gets its own amplitude control slider.
To make this the default, add (add-amp-controls) to your initialization file.
Here is a 4-channel control panel after adding the channel-specific amp controls.
</p>

<img class="indented" src="pix/addamps.png" alt="added amp controls">

<div class="spacer"></div>


<!-- add-delete-option -->
<pre class="indented">
<em class=def id="adddeleteoption">add-delete-option</em> 
</pre>

<p>add-delete-option adds a "Delete" (file) option to the File menu.
</p>
<div class="spacer"></div>


<!-- add-find-to-listener -->
<pre class="indented">
<em class=emdef>add-find-to-listener</em> 
</pre>

<p>add-find-to-listener causes C-s and C-r in the listener to start a separate "Find" dialog.
</p>
<div class="spacer"></div>


<!-- add-mark-pane -->
<pre class="indented">
<em class=def id="addmarkpane">add-mark-pane</em> 
</pre>

<p>add-mark-pane adds a pane to each channel giving the current mark locations (sample values).
These can be edited to move the mark, or deleted to delete the mark.  (If you add-mark-pane to a channel having marks,
you need to make some change to them to force it to be displayed).
Here's a picture (it also shows <a href="extsnd.html#withsmptelabel">with-smpte-label</a>, 
<a href="extsnd.html#withinsetgraph">with-inset-graph</a>, and <a href="#showdiskspace">show-disk-space</a>).
</p>

<img class="noborder" src="pix/markpane.png" alt="mark pane" usemap="#markpanemap">
<map name="markpanemap">
  <area shape=rect coords="70,30,150,50" alt="SMPTE label" href="extsnd.html#withsmptelabel">
  <area shape=rect coords="240,33,245,120" alt="SMPTE label" href="extsnd.html#addmark">
  <area shape=rect coords="337,33,343,120" alt="SMPTE label" href="extsnd.html#addmark">
  <area shape=rect coords="539,33,545,120" alt="SMPTE label" href="extsnd.html#addmark">
  <area shape=rect coords="570,25,710,45" alt="SMPTE label" href="extsnd.html#withinsetgraph">
  <area shape=rect coords="725,25,800,155" alt="SMPTE label" href="#addmarkpane">
  <area shape=rect coords="590,155,700,170" alt="SMPTE label" href="#showdiskspace">
</map>
<div class="spacer"></div>


<!-- add-rename-option -->
<pre class="indented">
<em class=emdef>add-rename-option</em> 
</pre>

<p>add-rename-option adds a "Rename" (file) option to the File menu.
</p>
<div class="spacer"></div>


<!-- add-text-to-status-area -->
<pre class="indented">
<em class=emdef>add-text-to-status-area</em>
</pre>

<p>add-text-to-status-area puts a text widget in the notebook's status area
(the lower left portion of the main Snd window when using the -notebook invocation switch).
It returns the widget; you can write to it via XmTextFieldSetString.
</p>
<div class="spacer"></div>


<!-- add-tooltip -->
<pre class="indented">
<em class=def id="addtooltip">add-tooltip</em> widget tip
</pre>

<p>add-tooltip adds a tooltip (also known as bubble-help) to a widget.  Once added,
set the variable with-tooltips to #f to turn it off.
</p>

<pre class="indented">
(add-tooltip (cadr (<a class=quiet href="extsnd.html#channelwidgets">channel-widgets</a>)) "show the time domain waveform")
</pre>

<div class="spacer"></div>


<!-- disable-control-panel -->
<pre class="indented">
<em class=def id="disablecontrolpanel">disable-control-panel</em> snd
</pre>

<p>disable-control-panel does away with the control panel.
</p>
<div class="spacer"></div>



<!-- display-widget-tree -->
<pre class="indented">
<em class=emdef>display-widget-tree</em> widget
</pre>

<p>display-widget-tree displays the hierarchy of widgets beneath 'widget'.
</p>
<div class="spacer"></div>


<!-- equalize-panes -->
<pre class="indented">
<em class=emdef>equalize-panes</em> snd
</pre>

<p>This equalizes multichannel sound panes (tries to make them the same size),
It is specific to Motif.
If the 'snd' argument is given, only that sound's panes are affected.
</p>
<div class="spacer"></div>


<!-- for-each-child -->
<pre class="indented">
<em class=def id="foreachchild">for-each-child</em> w func
<em class=emdef>find-child</em> w name
</pre>

<p>for-each-child applies 'func' to the widget 'w' and to each widget in the hierarchy of widgets below it.
'func' takes one argument, the child widget.  for-each-child is used by find-child which searches
for a widget named 'name' belonging to 'w'.
</p>

<pre class="indented">
(for-each-child 
  ((<a class=quiet href="extsnd.html#soundwidgets">sound-widgets</a>) 2) ; control panel
  (lambda (w) 
    (<a class=quiet href="extsnd.html#sndprint">snd-print</a> (<a class=quiet>format</a> #f "~%~A" (XtName w)))))
</pre>

<div class="spacer"></div>


<!-- install-searcher-with-colors -->
<pre class="indented">
<em class=emdef>install-searcher-with-colors</em> proc
</pre>

<p>install-searcher-with-colors places
our own search procedure into the filter mechanism in the File:Open
dialog.  This has been superseded by the <a href="extsnd.html#addfilefilter">file-filter</a> mechanism now built into Snd.
</p>

<pre class="indented">
(install-searcher-with-colors (lambda (file) #t))
</pre>

<div class="spacer"></div>


<!-- keep-file-dialog-open-upon-ok -->
<pre class="indented">
<em class=emdef>keep-file-dialog-open-upon-ok</em>
</pre>

<p>keep-file-dialog-open-upon-ok changes File:Open so that clicking "ok" does not unmanage (dismiss) the dialog.
</p>
<div class="spacer"></div>


<!-- load-font -->
<pre class="indented">
<em class=emdef>load-font</em> font-name
</pre>

<p>
load-font loads a font and returns a handle for it.
</p>

<pre class="indented">
  (define new-font (<em class=red>load-font</em> "-*-helvetica-bold-r-*-*-14-*-*-*-*-*-*-*"))

  (define* (show-greeting (snd 0) (chn 0)) ; works only in motif currently
  ;; show a red "hi!" in the helvetica bold font on a gray background
    (let ((ls (left-sample snd chn))
	  (rs (right-sample snd chn)))
      (if (and (&lt; ls 1000)
	       (&gt; rs 1000))
	  (let ((pos (x-&gt;position (/ 1000.0 (srate))))
		(old-color (foreground-color)))
	    (set! (foreground-color) (make-color .75 .75 .75))
	    (fill-rectangle pos 10 50 20 snd chn time-graph #f #f)
	    (set! (foreground-color) (make-color 1 0 0))
            (if new-font (set! (<em class=red>current-font</em>) new-font))
	    (draw-string "hi!" (+ pos 5) 12 snd chn time-graph #f)
	    (set! (foreground-color) old-color)))))
</pre>

<div class="spacer"></div>


<!-- main-index |makedropsite:drop sites -->
<!-- make-channel-drop-site -->
<pre class="indented">
<em class=def id="makedropsite">make-channel-drop-site</em> snd chn
<em class=emdef>set-channel-drop</em> drop snd chn
</pre>

<p>make-channel-drop-site shows how to add a drop site panel to a channel.  
set-channel-drop changes the channel's graph's drop function to 'drop', a 
function of 3 arguments, the dropped filename (a string) and the current sound and
channel number.
</p>
<div class="spacer"></div>


<!-- make-pixmap -->
<pre class="indented">
<em class=def id="makepixmap">make-pixmap</em> widget strs
</pre>

<p>make-pixmap turns an XPM-style description into pixmap.  Briefly an XPM pixmap description
is an array of strings; the first gives the size in pixels of the pixmap, and the number of colors;
the next set give characters followed by the color desired for that character; then comes the
pixmap itself using those characters.  The following defines a 16 X 12 arrow using 6 colors:
</p>

<pre class="indented">
(define arrow-strs (list
  "16 12 6 1"
  " 	c None s None"
  ".	c gray50"
  "X	c black"
  "o	c white"
  "O	c yellow"
  "-      c ivory2 s basiccolor"
  "--------X---------"
  "---------X--------"
  "----------X-------"
  "-----------X------"
  "------------X-----"
  "XXXXXXXXXXXXXX----"
  "------------X-----"
  "-----------X------"
  "----------X-------"
  "---------X--------"
  "--------X---------"
  "-------X----------"))
</pre>

<p><code>(make-pixmap (cadr (<a class=quiet href="extsnd.html#mainwidgets">main-widgets</a>)) arrow-strs)</code> then creates the actual pixmap.
The 'widget' argument is needed to give us access to the current colormap and so on.
(cadr (main-widgets)) is just Snd's outer shell, which will do the trick in most cases.
</p>

<div class="spacer"></div>


<!-- make-variable-display -->
<pre class="indented">
<em class=def id="makevariabledisplay">make-variable-display</em> page-name variable-name (type 'text) (range (list 0.0 1.0))
<em class=def id="variabledisplay">variable-display</em> val widget
</pre>

<p>make-variable-display sets up a display point (a dialog) for an arbitrary expression which
is updated via variable-display.  The latter returns its argument, so it acts as a sort of
probe, picking out any arbitrary point in an instrument and displaying it as the
instrument is running.  Display points can be organized as pages in a notebook
widget:
</p>

<pre class="indented">
(define wid (make-variable-display "do-loop" "i*2" 'text))
(define wid1 (make-variable-display "do-loop" "i" 'text))
(do ((i 0 (+ i 1)))
    ((= i 10))
  (variable-display (* (variable-display i wid1) 2) wid))
</pre>

<p>The 'type' argument to make-variable-display can be one of 'text
'scale, 'graph, 'spectrum, or 'meter.
It determines the kind of widget(s) used to display that variable.
The 'graph and 'spectrum cases create Snd channel displays,
accessible via a sound (and channel 0); these respond to the
various channel-related functions such as <a href="extsnd.html#showtransformpeaks">show-transform-peaks</a>,
although you have to give the sound explicitly:
</p>

<pre class="indented">
(define wid2 (make-variable-display "do-loop" "x" 'spectrum))
(set! (<a class=quiet href="extsnd.html#showtransformpeaks">show-transform-peaks</a> (car wid2)) #t)
</pre>

<p>Each graph or spectrum display is placed in its own pane (this is a desperate
kludge), whereas all the others are ordered vertically in a single pane.
The 'scale choice has an additional argument that gives the range of the
scale as a list (low high):
</p>

<pre class="indented">
(define wid2 (make-variable-display "do-loop" "i*2" 'scale '(-1.0 1.0)))
</pre>

<p>You can watch a generator's state on a sample-by-sample basis by
putting it in a text display:
</p>

<pre class="indented">
(define wid1 (make-variable-display "simp" "beg" 'text))
(define wid2 (make-variable-display "simp" "oscil" 'text))
(define wid3 (make-variable-display "simp" "outa" 'graph))
(<a class=quiet href="#definstrument">definstrument</a> (simp)
  (let* ((beg 0)
	 (dur 1000)
	 (end (+ beg dur))
	 (osc (<a class=quiet href="sndclm.html#make-oscil">make-oscil</a> 440.0)))
    (do ((i beg (+ i 1)))
	((= i end))
      (variable-display i wid1)
      (variable-display
        (<a class=quiet href="sndclm.html#oscil">oscil</a> (variable-display osc wid2) 0.0)
       wid3))))
(simp)
</pre>

<img class="indented" src="pix/vardpy.png" alt="variable display">

<p>
To clear display state, there's also variable-display-reset.
</p>
<div class="spacer"></div>


<!-- mark-sync-color -->
<pre class="indented">
<em class=def id="marksynccolor">mark-sync-color</em> new-color
</pre>

<p>mark-sync-color uses the <a href="extsnd.html#drawmarkhook">draw-mark-hook</a> to set the color of sync'd marks.
</p>
<div class="spacer"></div>


<!-- menu-option -->
<pre class="indented">
<em class=emdef>menu-option</em> menu-name
</pre>

<p>menu-option returns the widget associated with a given menu item name ("Print" for example).
This is actually a bad idea since the menu names can change without warning.
</p>
<div class="spacer"></div>


<!-- select-file -->
<pre class="indented">
<em class=emdef>select-file</em> func title dir filter help
</pre>
<p>select-file starts a file selection dialog, running 'func' if a file is selected:
</p>

<pre class="indented">
 (<a class=quiet href="extsnd.html#addtomenu">add-to-menu</a> 0 "Insert File" 
   (lambda () 
     (<em class=red>select-file</em>
       <a class=quiet href="extsnd.html#insertsound">insert-sound</a>
       "Insert File" "." "*" "file will be inserted at cursor")))
</pre>

<div class="spacer"></div>


<!-- show-all-atoms -->
<pre class="indented">
<em class=emdef>show-all-atoms</em> 
</pre>

<p>show-all-atoms displays all current X atom names (there are several hundred of these atoms normally).
</p>
<div class="spacer"></div>


<!-- show-disk-space -->
<pre class="indented">
<em class=def id="showdiskspace">show-disk-space</em> 
</pre>

<p>show-disk-space adds a label in the
status area which shows the current amount of disk space available
on the partition of the associated sound.  There's a picture of it in action above (add-mark-pane).
</p>
<div class="spacer"></div>


<!-- show-sounds-in-directory -->
<pre class="indented">
<em class=def id="makesoundbox">make-sound-box</em> name parent select-func peak-func sounds args
<em class=emdef>show-sounds-in-directory</em> (dir ".")
</pre>
<p>make-sound-box makes a container of sound file icons, each icon
containing a little sketch of the waveform, the length of the
file, and the filename.  What happens when an icon is selected
is up to 'select-func'.  However, if you drag (via 
button 2) the icon to the menubar, that sound is opened,
and if you drag it to a channel graph, it is mixed at the
mouse location in that channel.
'select-func' called when sound icon is selected; it is passed the sound file's name.
'peak-func' (if any) tells the soundbox code where to find any associated peak env files.
'sounds' is list of sound file names.
'args' is list of resource settings for each icon.
</p>

<pre class="indented">
(make-sound-box "sounds"
		((<a class=quiet href="extsnd.html#mainwidgets">main-widgets</a>) 3)
                <a class=quiet href="extsnd.html#sndprint">snd-print</a>
		*peak-env-dir*
		(list "oboe.snd" "pistol.snd" "cardinal.snd" "storm.snd")
		())
</pre>

<p>show-sounds-in-directory calls make-sound-box, filling it with
any sounds found in the directory passed as its argument (which defaults to 
the current directory).
</p>

<img class="indented" src="pix/soundbox.png" alt="show-sounds-in-directory">

<div class="spacer"></div>


<!-- snd-clock-icon -->
<pre class="indented">
<em class=emdef>snd-clock-icon</em> snd hour
</pre>

<p>snd-clock-icon replaces Snd's hourglass with a (very primitive) clock.
</p>
<div class="spacer"></div>


<!-- upon-save-yourself -->
<pre class="indented">
<em class=def id="uponsaveyourself">upon-save-yourself</em> thunk
</pre>

<p>upon-save-yourself causes 'thunk' (a function of no arguments) to be called if the window
manager sends a SAVE_YOURSELF message.
</p>
<div class="spacer"></div>


<!-- upon-take-focus -->
<pre class="indented">
<em class=emdef>upon-take-focus</em> thunk
</pre>

<p>upon-take-focus causes 'thunk' (a function of no arguments) to be called
whenever Snd receives focus from the window manager.
</p>
<div class="spacer"></div>


<!-- with-minmax-button -->
<pre class="indented">
<em class=emdef>with-minmax-button</em> 
</pre>
<p>with-minmax-button adds an open/close button to each sound's pane.  To activate it:
</p>

<pre class="indented">
(hook-push <a class=quiet href="extsnd.html#afteropenhook">after-open-hook</a> with-minmax-button)
</pre>

<div class="spacer"></div>


<!-- zync -->
<pre class="indented">
<em class=emdef>unzync</em> 
<em class=emdef>zync</em> 
</pre>

<p>The pair zync and unzync cause the
y-axis zoom sliders of a multichannel file to move together (zync) or separately (unzync, the default).
</p>


<div class="seealso">
see also: &nbsp; <a href="grfsnd.html#sndwithmotif">motif</a> &nbsp; <a href="extsnd.html#snddialogs">dialogs</a> &nbsp; <a href="extsnd.html#graphics">graphics</a> &nbsp; <a href="#menusdoc">menus</a> &nbsp; <a href="#enveddoc">enved</a>
</div>




<!--  FILE: snd-test  -->

<div class="header" id="sndtestdoc">snd-test</div>

<p>
snd-test.scm and snd-test.rb are test suites for Snd. The simplest use is:
</p>

<pre class="indented">
snd -l snd-test
</pre>

<p>
which will run all the tests, assuming you have the various sound files it is expecting to find.
You can run a particular test with:
</p>

<pre class="indented">
snd -l snd-test 23
</pre>

<p>which runs test 23. 
snd-test is primarily useful to non-developers as a source of
a huge number of examples. 
</p>




<!--  FILE: sndwarp  -->

<div class="header" id="sndwarpdoc">sndwarp</div>

<p>
This is a translation from CLM of Bret Battey's sndwarp instrument, itself based on Richard Karpen's sndwarp csound generator. 
It is similar to <a href="#expsrc">expsrc</a>.
</p>

<pre class="indented">
<em class=def id="sndwarp">sndwarp</em> beg dur file 
      (amp 1.0)
      (amp-env '(0 1 100 1))  ; amplitude envelope
      (stretch 1.0)           ; time stretch &mdash; 2.0 -&gt; twice as long
      (srate 1.0)             ; src &mdash; 0.5 -&gt; octave down
      (inputbeg 0.0)          ; source file start point
      (wsize 0.1)             ; size of windows in seconds
      (randw 0.02)            ; randomness of wsize
      (overlaps 15)           ; window overlaps per sec
      (time-ptr #f)           ; #f=stretch mode, #t=time-ptr mode
      (scale-time-ptr #f)     ; #f=absolute, #t=rescale
      (zero-start-time-ptr #f); #t=start at 0
      (window-offset #f)      ; #f=spread windows evenly
      (loc 0.5)               ; stereo loc, 0=left, 1=right
      (rev 0.1)               ; reverb amount
      (srcwidth 5)            ; src interpolation width
</pre>

<p>
Many of the parameters can also be envelopes.  The source has commentary
which I'll slightly paraphrase here for convenience.
'time-ptr' is a flag that determines whether stretching or time-pointer mode
is to be used in interpreting the 'stretch' parameter.
In stretch mode, the value of 'stretch' scales the time 
of the sound. For example, a value of 2 will stretch the sound 
In time-ptr mode, the value(s) of 'stretch' are <a href="sndclm.html#readin">readin</a> pointers
into the soundfile. For example, to read through a file
backwards from 2 seconds at half speed, use a 
stretch envelope such as '(0 2 1 0) with a 4 second note duration.
'scale-time-ptr' is a 
flag that determines whether the time-ptr envelope is
interpreted in absolute seconds or rescaled to fit the 
duration of the input sound file.
'zero-start-time-ptr' is a flag that determines (in time-ptr mode) whether
the first section of the windows start at 
time-ptr = 0.
'window-offset' is a flag that determines how the windows are offset
in time. 
</p>

<pre class="indented">
(<a class=quiet href="#wsdoc">with-sound</a> () (sndwarp 0 1 "oboe.snd"))
(<a class=quiet href="#wsdoc">with-sound</a> () (sndwarp 0 4 "oboe.snd" :stretch 2.0 :srate 0.5))
</pre>


<div class="seealso">
see also: &nbsp; <a href="#clmexpsrc">clm-expsrc</a> &nbsp; <a href="#expsrc">expsrc</a> &nbsp; <a href="#pvocdoc">pvoc</a> &nbsp; <a href="#rubberdoc">rubber</a> &nbsp; <a href="#ssbbank">ssb-bank</a>
</div>




<!--  FILE: spectr  -->

<div class="header" id="spectrdoc">spectr</div>

<p>The spectr files were translated by Michael Scholz from CLM's spectr.clm.  They contain a large 
set of instrument steady-state spectra, gathered many years ago (before 1976) by James A Moorer.
The variable names are taken from the file names used by JAM, but by the time I got around to
rescuing the data from mouldering magtapes, he had long since moved on, so I don't actually
know what instrument some of the labels refer to. The data is in the form of a bunch of lists,
each given a name:
</p>

<pre class="indented">
(define  trp-gs5 '(  1.02 .0114  2.02 .0346  3.02 .0045  4.04 .0013  5.06 .0002))
</pre>

<p>
which (I think) refers to a trumpet playing the note gs5.  The first number is the harmonic,
the second its amplitude, the third the next harmonic, then its amplitude, and so on.
These spectra can be used directly in the instrument <a href="#spectra">spectra</a> in clm-ins.scm.
spectr.scm exports only *spectr* which is an environment that holds the spectral names and values.
</p>

<div class="seealso">
see also: &nbsp; <a href="#twotab">two-tab</a>
</div>



<!--  FILE: stochastic  -->

<div class="header" id="stochasticdoc">stochastic</div>

<p>stochastic is Bill Sack's implementation of Xenakis' Dynamic Stochastic Synthesis as heard in his GENDY3, S.709, Legende d'Eer, etc.
</p>

<pre class="indented">
<em class=emdef>stochastic</em> start dur
           (amp .9)       ; overall amplitude
           (bits 16)      ; resolution of the wave's amplitude dimension
           (xmin 1)       ; minimum number of samples between time breakpoints, must be &gt;= 1
           (xmax 20)      ; maximum number of samples between time breakpoints
           (xwig 0)       ; amplitude applied to random walk function in time dimension
           (xstep 1)      ; quantization of freedom in time dimension, in samples, minimum: 1
           (ywig 0)       ; amplitude applied to random walk function in amplitude dimension, as %amp
           (xfb 0)        ; FIR filter
           (init-array '((10 0) (10 1) (10 0) (10 -.7) (10 0) (10 .5) 
                         (10 0) (10 -.3) (10 0) (10 .2) (10 0) (10 -.1)))
                          ; initial x and y breakpoints for wave,
                          ;    x values must be integers &gt;= 1, y values between -1.0 and 1.0
</pre>

<p>stochastic.ins in the CLM tarball has an elaborate Common Music-based example.
Here is one that is much simpler, but very loud:
</p>

<pre class="indented">
(<a class=quiet href="#wsdoc">with-sound</a> () (stochastic 0 10 :xwig .25 :ywig 10.0))
</pre>





<!--  FILE: strad  -->

<div class="header" id="straddoc">strad</div>

<p>strad.scm is a translation (by Michael Scholz) of CLM's strad.ins (by Juan Reyes).
It implements a physical model of a bowed string with stiffness.
</p>


<!-- FILE: tankrev -->

<div class="header" id="tankrevdoc">tank-rev</div>

<p>
tankrev.scm has Anders Vinjar's implementation of Jon Dattorro's plate reverb.
</p>



<!--  FILE: v and fmv  -->

<div class="header" id="vdoc">v and fmv</div>

<!-- main-index |vdoc:fm-violin -->

<p>The fm violin was my favorite instrument while working in the 70's and 80's,
primarily on the Samson box.  It was developed in Mus10 (ca 1977) based on ideas of John Chowning.
</p>

<pre class="indented">
<em class=emdef id="fmviolin">fm-violin</em> startime dur frequency amplitude
	    (fm-index 1.0)                        ; scales all indices
	    (amp-env '(0 0  25 1  75 1  100 0))   ; amplitude envelope
	    (periodic-vibrato-rate 5.0) 
	    (random-vibrato-rate 16.0)            ; jitter added to vibrato
	    (periodic-vibrato-amplitude 0.0025) 
	    (random-vibrato-amplitude 0.005)
	    (noise-amount 0.0)                    ; noise added to modulation
	    (noise-freq 1000.0)
	    (ind-noise-freq 10.0)                 ; index envelope jitter
	    (ind-noise-amount 0.0)
	    (amp-noise-freq 20.0)                 ; amplitude envelope jitter
	    (amp-noise-amount 0.0)
	    (gliss-env '(0 0  100 0))             ; frequency envelope
	    (glissando-amount 0.0) 
	    (fm1-env '(0 1  25 .4  75 .6  100 0)) ; 1:1 modulator amp (fm index) env
	    (fm2-env '(0 1  25 .4  75 .6  100 0)) ; 3:1 mod env
	    (fm3-env '(0 1  25 .4  75 .6  100 0)) ; 4:1 mod env
	    (fm1-rat 1.0)                         ; 1:1 actual mod:carrier freq ratio
	    (fm2-rat 3.0)	                  ; 3:1 same
	    (fm3-rat 4.0)                         ; 4:1 same
	    (fm1-index #f)                        ; 1:1 mod local index scaler
	    (fm2-index #f)                        ; 3:1 same
	    (fm3-index #f)                        ; 4:1 same
	    (degree 0)
	    (distance 1.0)
	    (reverb-amount 0.01)
	    (base 1.0)                            ; amp env base (1.0 = line segments)
</pre>

<p>Most of these parameters are for special cases; normally you need only:
</p>

<pre class="indented">
Scheme:    (with-sound () (fm-violin 0 1 440 .1))
Ruby:      with_sound() do fm_violin_rb(0, 1, 440, .1, [[:fm_index, 2.0]]) end
</pre>

<p>
fm-violin sets up several parallel modulators of one carrier (see <A HREF="fm.html">fm.html</A>
for details, or (ah nostalgia...) 
Schottstaedt,  "The Simulation of Natural Instrument Tones Using Frequency Modulation with a Complex Modulating Wave", CMJ vol 1 no 4 1977 p46-50). 
The modulators
themselves are modulated (vibrato, noise, etc). The FM indices were chosen to try
to mimic violin or cello sounds over a wide range of frequencies.
The various envelope "jitter" parameters set up slow moving random changes in
the associated envelopes; in some case this can produce a much richer sound.
There's no limit on what this instrument can do; nearly all my compositions in the 80's used
it.  To hear some of the effects, load fmviolin.clm (it is a CLM notelist, but it is
completely compatible with Snd/Scheme).
</p>


<p>fmv.scm (or v.rb in Ruby) implements the fm-violin as a CLM-style generator, making it possible
to call the violin anywhere a generator could be called; since each call on the fm-violin
function produces the next sample of the given violin, this form of the fm-violin is easy
to call in "real-time" situations.  Any other CLM-style instrument could
be rewritten in the same form.
</p>

<pre class="indented">
<em class=emdef>make-fm-violin</em>
    frequency amplitude (fm-index 1.0) (amp-env #f) 
    (periodic-vibrato-rate 5.0) (random-vibrato-rate 16.0)
    (periodic-vibrato-amplitude 0.0025) (random-vibrato-amplitude 0.005) 
    (noise-amount 0.0) (noise-freq 1000.0)
    (ind-noise-freq 10.0) (ind-noise-amount 0.0) 
    (amp-noise-freq 20.0) (amp-noise-amount 0.0) (gliss-env #f)
    (fm1-env #f) (fm2-env #f) (fm3-env #f) 
    (fm1-rat 1.0) (fm2-rat 3.0) (fm3-rat 4.0) 
    (fm1-index #f) (fm2-index #f) (fm3-index #f) (base 1.0)

<em class=emdef>fm-violin</em> gen
<em class=emdef>fm-violin-ins</em> [same args as original violin in v.scm]
</pre>

<p>fm-violin-ins shows how this generator can be fitted into the original fm-violin code.
The plethora of arguments is an historical artifact;
normally only a few of them are used at a time.  There are two examples of calling this generator
in fmv.scm, the simpler one being:
</p>

<pre class="indented">
(define test-v 
  (lambda (beg dur freq amp amp-env)
    (let ((v (<em class=red>make-fm-violin</em>
	      freq amp 
	      :amp-env (let ((e (<a class=quiet href="sndclm.html#make-env">make-env</a> (or amp-env '(0 0 1 1 2 0)) 
					  :scaler amp 
					  :length dur)))
			 (lambda () (<a class=quiet href="sndclm.html#env">env</a> e)))))
	  (data (channel-&gt;float-vector beg dur)))
      (do ((i 0 (+ i 1)))
	  ((= i dur))
	(set! (data i) (+ (data i)
                          (<em class=red>v</em>))))
      (<a class=quiet href="extsnd.html#setsamples">set-samples</a> beg dur data))))
</pre>

<p>Here we are setting up an fm-violin generator (via make-fm-violin), then
calling it 'dur' times, mixing its output into the current data (this could
also use mix-float-vector and so on).  The generator is called via (v).
As can be seen here, each envelope is treated as a function called on each sample
very much like the "as-needed" input in src or granulate; the envelopes could actually be any
arbitrary function you like (see test-v1 in fmv.scm which uses an oscillator as one of
the fm index envelopes).  One complication in some "real-time" situations is that
you don't know in advance how long a note will be; in this case, the envelope
generating functions should have attack and decay ramps, triggered by note-on and
note-off; once the ramp has reached its end point, the end value should be held;
the note itself should be called until it has had time to ramp off.
</p>

<p>
I can't resist including an historical digression.
Here is a Mus10 version of fm-violin (in this code ":=" is used in place of the original SAIL left arrow character,
and so on):
</p>

<pre class="indented">
ARRAY GlissFunc, DecayFunc, AttackFunc, SineWave, AmpFunc(512);
SYNTH(Sinewave); 1,1 999;
SEG(AmpFunc); 0,0 1,25 1,50 0,75 0,100;
SEG(GlissFunc);0,1 1,50, 0,100;
SEG(AttackFunc);0,0 1,100;
SEG(DecayFunc);1,1 .6,5 .3,10 .15,25 .07,50 0,100;
	
INSTRUMENT VN1;
VARIABLE Reset1,Noise,/NewMag,OtherFreq,/Gliss,Distance,Stereo,
	Freq,Amp1,Amp2,Duration,AttackTime,DecayTime,Memory1,
	Index1,Index2,Index3,scFreq,DecayLength,Switch1,Switch2,
	/Mod1,/Mod2,/Mod3,/Env,/Att,/Vibrato,IMult,/Snd,
	/Flutter,VibRate,VibAmp,/Ramp,/Decay,VibSwitch,LogFreq,
	GlissLength,Bowing,DecayCall,VibCall,GlissCall,RampCall;
	
Memory1:=1;
	
I_ONLY BEGIN
  Duration:=P2;
  Freq:=P3;
  Amp1:=P4;
  Amp2:=P5;
  OtherFreq:=P6;
  IF Freq&gt;=C THEN Freq:=Freq+Freq/100;
  IF Freq&lt;C THEN Freq:=Freq-20/Freq;
	
  Switch1:=P14;
  Switch2:=1-Switch1;
  IMult:=P7-(Switch2/4);
  VibSwitch:=P8;
  Bowing:=P9;
	
  Distance:=P10;
  Stereo:=P11;
  Noise:=P12;
  GlissLength:=P13;
  LogFreq:=ALOG(Freq);
  
  DecayCall:=VibCall:=RampCall:=GlissCall:=20;
  IF Amp1=Amp2 THEN RampCall:=SRATE;
  IF Freq=OtherFreq THEN GlissCall:=SRATE;
  IF VibSwitch=0 THEN VibCall:=SRATE;
  IF Switch1=1 THEN DecayCall:=SRATE;
	
  Vibrate:=5.25+RAND*.75;
  VibAmp:=.006+RAND*.001;
	
  IF Bowing=0
    THEN
      IF Memory1&gt;.08
	THEN
	  BEGIN
	  DecayTime:=.7;
	  AttackTime:=.2;
	  END
	ELSE
	  BEGIN
	  DecayTime:=.7;
	  AttackTime:=.05;
	  Noise:=0;
	  END
    ELSE
      IF Memory1&gt;.05
	THEN
	  BEGIN
	  DecayTime:=.05;
	  AttackTime:=.2;
	  END
	ELSE
	  BEGIN
	  DecayTime:=.05;
	  AttackTime:=.05;
	  Noise:=0;
	  END;
	
  Memory1:=DecayTime;
	
  IF AttackTime+DecayTime&gt;=Duration
    THEN
      BEGIN
      AttackTime:=Duration*AttackTime;
      DecayTime:=DecayTime*Duration;
      IF AttackTime&lt;=.05 THEN AttackTime:=Duration-DecayTime-.01;
      END;
	
  ScFreq:=Freq*MAG;
  DecayLength:=1000/Freq;
  IF Switch1=0 THEN Noise:=.1;
  Index1:=7.5*IMult/LogFreq;
  Index2:=5/SQRT(Freq);
  Index3:=IMult*30*(8.5-LogFreq)/Freq;
END;
	
Decay:=Switch1+EXPEN[DecayCall](Switch2,MAG*20/DecayLength,DecayFunc);
ENV:=Switch2+LINEN[20](Switch1,AttackTime/20,DecayTime/20,Duration/20,AmpFunc,Reset1:=0);
Ramp:=Amp1+NOSCIL[RampCall](Amp2-Amp1,20*MAG/Duration,AttackFunc);
Gliss:=Freq+EXPEN[GlissCall](OtherFreq-Freq,20*MAG/GlissLength,GlissFunc);
FLutter:=RANDI[VibCall](1,200*Mag);
Vibrato:=NOSCIL[VibCall](ENV,Vibrate*MAG*20,SineWave);
Att:=1-EXPEN[20](1,MAG*640,AttackFunc);
	
NewMag:=(1+Flutter*.005)*(1+Vibrato*VibAmp)*(1+RANDI(Noise*Att,2000*Mag))*Gliss*Mag;
	
Mod1:=NOSCIL(Decay*ScFreq*(Att+Index1),NewMag,Sinewave);
Mod2:=NOSCIL(Decay*ScFreq*(Att+Index2),4*NewMag,Sinewave);
Mod3:=NOSCIL(Decay*ScFreq*(Att+Index3),3*NewMag,Sinewave);
Snd:=ZOSCIL(Decay*ENV*Ramp,NewMag+Mod1+Mod2+Mod3,Sinewave);
OUTA:=OUTA+Snd*0.5;
END;
</pre>

<table class="method">
<tr><td>
<img src="pix/early.png" alt="at the park, copyright Patte Wood">
</td><td>
<img src="pix/later.png" alt="at home">
</td></tr>
<tr><td class="center">then</td><td class="center">now</td></tr>
</table>

<p>
This instrument required about 60 seconds of computing on a PDP-10
(a $250,000 minicomputer) for 1 second of sound (our normal sampling
rate was 12800).  Since the PDP was massively time-shared, 60 seconds
of computing could involve many minutes of sitting around watching
AI scientists play Space War.
Mus10 was an extension of Music V for the PDP-10 family of computers.
To give a feel for how one worked in those days, here's a brief quote from the Mus10 manual (by Tovar and
Leland Smith, May 1977):
</p>

<pre class="indented">
The following generates  1 second of a  440 Hz sine wave  followed by
1/2 sec. of a  660Hz sine wave. The output goes to a file, MUSIC.MSB,
which is written on DSKM.  

COMMENT Fill array with sine wave;
ARRAY SINETABLE[511];
FOR I:=0 STEP 1 UNTIL 511 DO SINETABLE[I]:=SIN(2*PI/512);

INSTRUMENT SINE;
  COMMENT Generate simple sine wave.  P4 = Amplitude, P3 = frequency;
  OUTA:=OUTA+OSCIL(P4,P3*MAG,SINETABLE);
  END;

COMMENT Now, generate the sound;
PLAY ;
  SIMP 0, 1, 440, 1000;
  SIMP 1, 1/2, 660, 1000;
  FINISH;
</pre>

<p>
The computation involved was considered so burdensome, that the names of
the main users were posted in the AI lab halls, apparently to try to
get us to go away.  I was normally the primary user (in terms of computrons) for the entire lab, and I had no intention
of going away.  
In the Samson box world, this (in its initial "chorus" version) was:
</p>

<pre class="indented">
Instrument(Violin);
RECORD_POINTER(seg) nullfunc;
INTEGER ARRAY gens[1:4],indgens[1:6], GensA[1:4],AmpGens[1:2];
					! synthesizer addresses;
REAL ARRAY ratsA[1:4],Indrats[1:6],ratsB[1:4],AmpRats[1:2];
					! envelope data;
INTEGER ModGens1Sum,i,FuncOffSet,k,GenOutLoc,GenInLoc,ModGens2Sum,x1,x2;

Pars(&lt;(InsName,Beg,Dur,Freq,Amp,Function AmpFunc,Function IndFunc,IndMult,
	SkewMult,Nothing,PcRev,No11,No12,No13,Function SkewFunc)&gt;);
					! the parameters of this instrument;

Dbugit(Pns);				! debugging aid;
GenOutLoc:=CASE (Pn[1] MOD 4) OF (Outma,Outmb,Outmc,Outmd);
					! OUTMA is channel 1, OUTMB channel 2, etc;
if freq&gt;srate/3 then return;		! note too high, so leave it out;
x1:=3;					! modulating frequency checks;
x2:=4;					! (we want them less than srate/2);
If x1*freq&gt;srate/2 Then x1:=1;
If x2*freq&gt;srate/2 then x2:=1;
amp:=Amp/2;				! two carriers, so halve the amplitude;

waiter(Beg);				! wait for the beginning of the note;

indRats[1]:=(x1*Freq*IndMult*((8.5-log(freq))/(3+(freq/1000)))*4/srate) MIN .999;
indRats[2]:=(x2*Freq*IndMult*(1/(freq^.5))*4/srate) MIN .999;
indRats[3]:=(freq*IndMult*(5/log(freq))*4/srate) MIN .999;
indrats[4]:=indrats[1]; indrats[5]:=indrats[2]; indrats[6]:=indrats[3];

ratsA[1]:=x1; ratsA[2]:=x2;     ratsA[3]:=1;     ratsA[4]:=1;	
ratsB[1]:=x1+.002; ratsB[2]:=x2+.003;     ratsB[3]:=1.002;     ratsB[4]:=1;	
					! this is the skewing for the chorus effect;
Gens[1]:=Osc(Pns,ModGens1Sum);		! now set up the oscillators;
Gens[2]:=Osc(Pns,ModGens1Sum);
Gens[3]:=Osc(Pns,ModGens1Sum);
Gens[4]:=Osc(Pns,genInLoc,ModGens1Sum);	! carrier 1;

GensA[1]:=Osc(Pns,ModGens2Sum);
GensA[2]:=Osc(Pns,ModGens2Sum);
GensA[3]:=Osc(Pns,ModGens2Sum);
GensA[4]:=Osc(Pns,genInLoc,ModGens2Sum);! carrier 2;

indgens[1]:=gens[1];   indgens[2]:=gens[2];  indgens[3]:=gens[3];
indgens[4]:=gensA[1];   indgens[5]:=gensA[2];  indgens[6]:=gensA[3];
					! set up envelope addressing;

ModSig(Pns,GenOutLoc,GenInLoc,1-pcRev);	! send signal to DACs;
ModSig(Pns,RevIn,GenInLoc,pcRev);	! and signal to reverberator;

AmpGens[1]:=Gens[4]; AmpGens[2]:=GensA[4]; AmpRats[1]:=1; AmpRats[2]:=1;
					! now add the envelopes;
AddArrEnv(Pns,AmpGens,2,"A",0,Amp/2,AmpFunc,AmpRats);
AddArrEnv(Pns,IndGens,6,"A",0,1,IndFunc,Indrats);
AddArrEnv(Pns,Gens,4,"F",freq,Freq*skewmult,skewfunc,ratsA,
	5,.011,.011,nullfunc,6,.017,.017,nullfunc,0,0);
AddArrEnv(Pns,GensA,4,"F",freq,Freq*skewmult,skewfunc,ratsA,
	6,.010,.010,nullfunc,5,.017,.017,nullfunc,1,0);
End!Instrument(Pns);			! deallocation;
</pre>

<p>
The Sambox version eventually became incredibly complicated, mainly to
try to handle note list problems in the instrument.  The Samson box could
run about 5 or 6 of these in "real-time", similar to a modern-day
500 MHz Pentium running CLM.
The parallel in the Sambox world to the SIMP example above is (this is
taken from SAMBOX.BIL, November 1984):
</p>

<pre class="indented">
    Instrument(Simp);
    Integer Gen1;
    Gen1:=Osc(Pns,OutA,Zero,SineMode,0,0,Pn[3]);
    AddEnv(Pns,Gen1,"A",0,Pn[4],Pf[5]);
    End_Instrument(Pns);
</pre>

<p>The Common Lisp version of this is:</p>

<pre class="indented">
(<a class=quiet href="#definstrument">definstrument</a> simp (start-time duration frequency amplitude
                     &amp;optional (amp-env '(0 0 50 1 100 0)))
  (multiple-value-bind (beg end) (<a class=quiet href="sndclm.html#timestosamples">times-&gt;samples</a> start-time duration)
    (let ((s (<a class=quiet href="sndclm.html#make-oscil">make-oscil</a> frequency))
          (amp (<a class=quiet href="sndclm.html#make-env">make-env</a> amp-env :scaler amplitude :duration duration)))
      (run
       (loop for i from beg below end do
         (<a class=quiet href="sndclm.html#outa">outa</a> i (* (<a class=quiet href="sndclm.html#env">env</a> amp) (<a class=quiet href="sndclm.html#oscil">oscil</a> s))))))))
</pre>

<p>
In Common Lisp, the fm-violin became (fm.html, 1989):
</p>

<pre class="indented">
(<a class=quiet href="#definstrument">definstrument</a> violin (beg end frequency amplitude fm-index)
  (let* ((frq-scl (<a class=quiet href="sndclm.html#hztoradians">hz-&gt;radians</a> frequency))
         (maxdev (* frq-scl fm-index))
         (index1 (* maxdev (/ 5.0 (log frequency))))
         (index2 (* maxdev 3.0 (/ (- 8.5 (log frequency)) (+ 3.0 (/ frequency 1000)))))
         (index3 (* maxdev (/ 4.0 (sqrt frequency))))
         (carrier (<a class=quiet href="sndclm.html#make-oscil">make-oscil</a> frequency))
         (fmosc1 (<a class=quiet href="sndclm.html#make-oscil">make-oscil</a> frequency))
         (fmosc2 (<a class=quiet href="sndclm.html#make-oscil">make-oscil</a> (* 3 frequency)))
         (fmosc3 (<a class=quiet href="sndclm.html#make-oscil">make-oscil</a> (* 4 frequency)))
         (ampf  (<a class=quiet href="sndclm.html#make-env">make-env</a> '(0 0 25 1 75 1 100 0) :scaler amplitude))
         (indf1 (<a class=quiet href="sndclm.html#make-env">make-env</a> '(0 1 25 .4 75 .6 100 0) :scaler index1))
         (indf2 (<a class=quiet href="sndclm.html#make-env">make-env</a> '(0 1 25 .4 75 .6 100 0) :scaler index2))
         (indf3 (<a class=quiet href="sndclm.html#make-env">make-env</a> '(0 1 25 .4 75 .6 100 0) :scaler index3))
         (pervib (<a class=quiet href="sndclm.html#make-triangle-wave">make-triangle-wave</a> :frequency 5 :amplitude (* .0025 frq-scl)))
         (ranvib (make-randi :frequency 16 :amplitude (* .005 frq-scl)))
         (vib 0.0))
    (run
     (loop for i from beg to end do
       (setf vib (+ (<a class=quiet href="sndclm.html#triangle-wave">triangle-wave</a> pervib) (randi ranvib)))
       (<a class=quiet href="sndclm.html#outa">outa</a> i (* (<a class=quiet href="sndclm.html#env">env</a> ampf)
                  (<a class=quiet href="sndclm.html#oscil">oscil</a> carrier
                         (+ vib 
                            (* (<a class=quiet href="sndclm.html#env">env</a> indf1) (<a class=quiet href="sndclm.html#oscil">oscil</a> fmosc1 vib))
                            (* (<a class=quiet href="sndclm.html#env">env</a> indf2) (<a class=quiet href="sndclm.html#oscil">oscil</a> fmosc2 (* 3.0 vib)))
                            (* (<a class=quiet href="sndclm.html#env">env</a> indf3) (<a class=quiet href="sndclm.html#oscil">oscil</a> fmosc3 (* 4.0 vib)))))))))))
</pre>

<p>or in its actual (non-simplified) form:
</p>

<pre class="indented">
(defun bit20 (x)			;Samson box modifier got 20 bit int interpreted as fraction 
  (if (&gt;= x (expt 2 19))                ;(keep fm-violin compatible with old note lists)
      (float (/ (- x (expt 2 20)) (expt 2 19)))
    (float (/ x (expt 2 19)))))

(defun make-frobber-function (beg end frobl)
  (let ((result (list beg))
	(val (bit20 (cadr frobl))))
    (loop for x in frobl by #'cddr and 
              y in (cdr frobl) by #'cddr do
      (when (and (&gt;= x beg)
		 (&lt;= x end))
	(push val result)
	(push x result)
	(setf val (bit20 y))))
    (push val result)
    (push end result)
    (push val result)
    (nreverse result)))

(<a class=quiet href="#definstrument">definstrument</a> fm-violin 
  (startime dur frequency amplitude &amp;key
	    (fm-index 1.0)
	    (amp-env '(0 0  25 1  75 1  100 0))
	    (periodic-vibrato-rate 5.0) 
            (random-vibrato-rate 16.0)
	    (periodic-vibrato-amplitude 0.0025) 
            (random-vibrato-amplitude 0.005)
	    (noise-amount 0.0) (noise-freq 1000.0)
	    (ind-noise-freq 10.0) (ind-noise-amount 0.0)
	    (amp-noise-freq 20.0) (amp-noise-amount 0.0)
	    (gliss-env '(0 0  100 0)) (glissando-amount 0.0) 
	    (fm1-env '(0 1  25 .4  75 .6  100 0)) 
            (fm2-env '(0 1  25 .4  75 .6  100 0)) 
            (fm3-env '(0 1  25 .4  75 .6  100 0))
	    (fm1-rat 1.0) (fm2-rat 3.0)	 (fm3-rat 4.0)                    
	    (fm1-index nil) (fm2-index nil) (fm3-index nil)
	    (base nil) (frobber nil)
	    (reverb-amount 0.01)
	    (index-type :violin)
	    (degree nil) (distance 1.0) (degrees nil)
	    (no-waveshaping nil) (denoise nil)
	    (denoise-dur .1) (denoise-amp .005)
	    &amp;allow-other-keys)
  (if (&gt; (abs amplitude) 1.0) 
      (setf amplitude (clm-cerror ".1?" .1 #'numberp "amplitude = ~A?" amplitude)))
  (if (&lt;= (abs frequency) 1.0) 
      (setf frequency (clm-cerror "440.0?" 440.0 #'numberp "frequency = ~A?" frequency)))
  (let* ((beg (floor (* startime *srate*)))
	 (end (+ beg (floor (* dur *srate*))))
	 (frq-scl (<a class=quiet href="sndclm.html#hztoradians">hz-&gt;radians</a> frequency))
	 (modulate (not (zerop fm-index)))
	 (maxdev (* frq-scl fm-index))
	 (vln (not (eq index-type :cello)))
	 (logfreq (log frequency))
	 (sqrtfreq (sqrt frequency))
	 (index1 (or fm1-index (min pi (* maxdev (/ (if vln 5.0 7.5) logfreq)))))
	 (index2 (or fm2-index (min pi (* maxdev 3.0 (if vln 
							     (/ (- 8.5 logfreq) (+ 3.0 (* frequency .001)))
							   (/ 15.0 sqrtfreq))))))
	 (index3 (or fm3-index (min pi (* maxdev (/ (if vln 4.0 8.0) sqrtfreq)))))

	 (easy-case (and (not no-waveshaping)
			 (zerop noise-amount)
			 (eq fm1-env fm2-env)
			 (eq fm1-env fm3-env)
			 (zerop (- fm1-rat (floor fm1-rat)))
			 (zerop (- fm2-rat (floor fm2-rat)))
			 (zerop (- fm3-rat (floor fm3-rat)))
			 (zerop (nth-value 1 (floor fm2-rat fm1-rat)))
			 (zerop (nth-value 1 (floor fm3-rat fm1-rat)))))
	 (coeffs (and easy-case modulate
	 	      (partials-&gt;polynomial
	 	       (list fm1-rat index1
	 		     (floor fm2-rat fm1-rat) index2
	 		     (floor fm3-rat fm1-rat) index3))))
	 ;; that is, we're doing the polynomial evaluation using fm1osc running at fm1-rat * frequency
	 ;; so everything in the polynomial table should be in terms of harmonics of fm1-rat
	 
	 (norm (or (and easy-case modulate 1.0) index1))
	 
	 (carrier (<a class=quiet href="sndclm.html#make-oscil">make-oscil</a> frequency))
	 (fmosc1  (and modulate (<a class=quiet href="sndclm.html#make-oscil">make-oscil</a> (* fm1-rat frequency))))
	 (fmosc2  (and modulate (or easy-case (<a class=quiet href="sndclm.html#make-oscil">make-oscil</a> (* fm2-rat frequency)))))
	 (fmosc3  (and modulate (or easy-case (<a class=quiet href="sndclm.html#make-oscil">make-oscil</a> (* fm3-rat frequency)))))
	 (ampf  (<a class=quiet href="sndclm.html#make-env">make-env</a> 
                  (if denoise
                       (reduce-amplitude-quantization-noise amp-env dur amplitude denoise-dur denoise-amp) 
                     amp-env)
	          amplitude :base base :duration dur))
	 (indf1 (and modulate (<a class=quiet href="sndclm.html#make-env">make-env</a> fm1-env norm :duration dur)))
	 (indf2 (and modulate (or easy-case (<a class=quiet href="sndclm.html#make-env">make-env</a> fm2-env index2 :duration dur))))
	 (indf3 (and modulate (or easy-case (<a class=quiet href="sndclm.html#make-env">make-env</a> fm3-env index3 :duration dur))))
	 (frqf (<a class=quiet href="sndclm.html#make-env">make-env</a> gliss-env (* glissando-amount frq-scl) :duration dur))
	 (pervib (<a class=quiet href="sndclm.html#make-triangle-wave">make-triangle-wave</a> periodic-vibrato-rate (* periodic-vibrato-amplitude frq-scl)))
	 (ranvib (<a class=quiet href="sndclm.html#make-rand-interp">make-rand-interp</a> random-vibrato-rate (* random-vibrato-amplitude frq-scl)))
	 (fm-noi (if (and (/= 0.0 noise-amount)
			  (null frobber))
		     (<a class=quiet href="sndclm.html#make-rand">make-rand</a> noise-freq (* pi noise-amount))))
	 (ind-noi (if (and (/= 0.0 ind-noise-amount) (/= 0.0 ind-noise-freq))
		      (<a class=quiet href="sndclm.html#make-rand-interp">make-rand-interp</a> ind-noise-freq ind-noise-amount)))
	 (amp-noi (if (and (/= 0.0 amp-noise-amount) (/= 0.0 amp-noise-freq))
		      (<a class=quiet href="sndclm.html#make-rand-interp">make-rand-interp</a> amp-noise-freq amp-noise-amount)))
	 (frb-env (if (and (/= 0.0 noise-amount) frobber)
		      (<a class=quiet href="sndclm.html#make-env">make-env</a> (make-frobber-function startime (+ startime dur) frobber) :duration dur
				:base 0	:scaler (* two-pi noise-amount))))
	 (vib 0.0) 
	 (modulation 0.0)
	 (loc (<a class=quiet href="sndclm.html#make-locsig">make-locsig</a> :degree (or degree degrees (random 90.0)) 
                :reverb reverb-amount :distance distance))
	 (fuzz 0.0)
	 (ind-fuzz 1.0)
	 (amp-fuzz 1.0))
    (run
     (loop for i from beg to end do
       (if (/= 0.0 noise-amount)
	   (if (null frobber)
	       (setf fuzz (<a class=quiet href="sndclm.html#rand">rand</a> fm-noi))
	     (setf fuzz (<a class=quiet href="sndclm.html#env">env</a> frb-env))))
       (setf vib (+ (<a class=quiet href="sndclm.html#env">env</a> frqf) (<a class=quiet href="sndclm.html#triangle-wave">triangle-wave</a> pervib) (<a class=quiet href="sndclm.html#rand-interp">rand_interp</a> ranvib)))
       (if ind-noi (setf ind-fuzz (+ 1.0 (<a class=quiet href="sndclm.html#rand-interp">rand-interp</a> ind-noi))))
       (if amp-noi (setf amp-fuzz (+ 1.0 (<a class=quiet href="sndclm.html#rand-interp">rand-interp</a> amp-noi))))
       (if modulate
	   (if easy-case
	       (setf modulation
		 (* (<a class=quiet href="sndclm.html#env">env</a> indf1) 
		    (<a class=quiet href="sndclm.html#polynomial">polynomial</a> coeffs (<a class=quiet href="sndclm.html#oscil">oscil</a> fmosc1 vib)))) ;(* vib fm1-rat)??
	     (setf modulation
	       (+ (* (<a class=quiet href="sndclm.html#env">env</a> indf1) (<a class=quiet href="sndclm.html#oscil">oscil</a> fmosc1 (+ (* fm1-rat vib) fuzz)))
		  (* (<a class=quiet href="sndclm.html#env">env</a> indf2) (<a class=quiet href="sndclm.html#oscil">oscil</a> fmosc2 (+ (* fm2-rat vib) fuzz)))
		  (* (<a class=quiet href="sndclm.html#env">env</a> indf3) (<a class=quiet href="sndclm.html#oscil">oscil</a> fmosc3 (+ (* fm3-rat vib) fuzz)))))))
       (<a class=quiet href="sndclm.html#locsig">locsig</a> loc i
	     (* (<a class=quiet href="sndclm.html#env">env</a> ampf) amp-fuzz
		(<a class=quiet href="sndclm.html#oscil">oscil</a> carrier (+ vib (* ind-fuzz modulation)))))))))
</pre>

<p>which is very similar to the Scheme version (v.scm).
And I just found this out on the net; I'm no csound expert, so I merely quote what I find:
</p>

<pre class="indented">
;ORC
; edited by R. Pinkston, modified for use with MIDI2CS by R. Borrmann
;
;==========================================================================;
;                Schottstaedt FM String Instrument from Dodge              ;
;                                                                          ;
;p4 = amp p5 = pch p6 = rise p7 = dec p8 = vibdel p9 = vibwth p10 = vibrte ;
;==========================================================================;
;        sr      =       44100
;        kr      =       4410
;        ksmps   =       10
;        nchnls  =       1
;
;                instr   1

par
  p_maxamplitude 32000
  p_cps
endpar

        iamp    =       p4

        irise   = .2    ;p6
        idec    = .2    ;p7
        ivibdel = .75   ;p8
        ivibwth = .03   ;p9
        ivibrte = 5.5   ;p10

        ifc     =       p5
        ifm1    =       ifc
        ifm2    =       ifc*3
        ifm3    =       ifc*4
        indx1   =       7.5/log(ifc)    ;range from ca 2 to 1
        indx2   =       15/sqrt(ifc)    ;range from ca 2.6 to .5
        indx3   =       1.25/sqrt(ifc)  ;range from ca .2 to .038
        kvib    init    0 

                timout  0,ivibdel,transient  ;delays vibrato for p8 seconds
        kvbctl  linen   1,.5,p3-ivibdel,.1   ;vibrato control envelope
        krnd    randi   .0075,15        ;random deviation in vib width 
        kvib    oscili  kvbctl*ivibwth+krnd,ivibrte*kvbctl,1 ;vibrato generator
               
transient:
        timout  .2,p3,continue          ;execute for .2 secs only
        ktrans  linseg  1,.2,0,1,0      ;transient envelope 
        anoise  randi   ktrans,.2*ifc   ;noise... 
        attack  oscil   anoise,2000,1   ;...centered around 2kHz

continue: 
        amod1   oscili  ifm1*(indx1+ktrans),ifm1,1
        amod2   oscili  ifm2*(indx2+ktrans),ifm2,1
        amod3   oscili  ifm3*(indx3+ktrans),ifm3,1
        asig    oscili  iamp,(ifc+amod1+amod2+amod3)*(1+kvib),1
        asig    linen   asig+attack,irise,p3,idec
;                out     asig
; 
;                endin
        aright  = asig
        aleft   = asig
</pre>

<p>There's a C/CLM version of this instrument in <a href="sndlib.html">sndlib.html</a>.  The body of the fm-violin
in C/CLM is:
</p>

<pre class="indented">
      if (noise_amount != 0.0) fuzz = mus_rand(fmnoi,0.0);
      if (frqf) vib = mus_env(frqf); else vib = 0.0;
      vib += mus_triangle_wave(pervib, 0.0) + 
             mus_rand_interp(ranvib, 0.0);
      if (easy_case)
        modulation = mus_env(indf1) * 
                     mus_polynomial(coeffs, mus_oscil(fmosc1, vib, 0.0), npartials);
      else
        modulation = mus_env(indf1) * mus_oscil(fmosc1, (fuzz + fm1_rat * vib), 0.0) +
                     mus_env(indf2) * mus_oscil(fmosc2, (fuzz + fm2_rat * vib), 0.0) +
                     mus_env(indf3) * mus_oscil(fmosc3, (fuzz + fm3_rat * vib), 0.0);
      mus_locsig(loc, i, mus_env(ampf) *
                         mus_oscil(carrier, vib + indfuzz * modulation, 0.0));
</pre>


<p>And here is the Ruby version, written by Michael Scholz (see examp.rb):</p>

<pre class="indented">
#
# fm_violin([start=0.0[, dur=1.0[, freq=440.0[, amp=0.3[, *args]]]]])
#

def fm_violin(start = 0.0, dur = 1.0, freq = 440.0, amp = 0.3, *args)
  include Math;			# PI

  usage = "fm_violin([start=0.0[, dur=1.0[, freq=440.0[, amp=0.3[, *args]]]]])

	[:fm_index, 1.0]
	[:amp_env, [0, 0, 25, 1, 75, 1, 100, 0]]
	[:periodic_vibrato_rate, 5.0]
	[:random_vibrato_rate, 16.0]
	[:periodic_vibrato_amp, 0.0025]
	[:random_vibrato_amp, 0.005]
	[:noise_amount, 0.0]
	[:noise_freq, 1000.0]
	[:ind_noise_freq, 10.0]
	[:ind_noise_amount, 0.0]
	[:amp_noise_freq, 20.0]
	[:amp_noise_amount, 0.0]
	[:gliss_env, [0, 0,  100, 0]]
	[:gliss_amount, 0.0]
	[:fm1_env, [0, 1, 25, 0.4, 75, 0.6, 100, 0]]
	[:fm2_env, [0, 1, 25, 0.4, 75, 0.6, 100, 0]]
	[:fm3_env, [0, 1, 25, 0.4, 75, 0.6, 100, 0]]
	[:fm1_rat, 1.0]
	[:fm2_rat, 3.0]
	[:fm3_rat, 4.0]
	[:fm1_index, false]
	[:fm2_index, false]
	[:fm3_index, false]
	[:base, 1.0]
	[:reverb_amount, 0.01]
	[:index_type, :violin]
	[:degree, false]
	[:distance, 1.0]
	[:degrees, false]

  Ruby: fm_violin(0, 1, 440, .1, [[:fm_index, 2.0]])
 Scheme: (fm-violin 0 1 440 .1 :fm-index 2.0)\n\n";

  fm_index = (args.assoc(:fm_index)[1] rescue 1.0);
  amp_env = (args.assoc(:amp_env)[1] rescue [0, 0, 25, 1, 75, 1, 100, 0]);
  periodic_vibrato_rate = (args.assoc(:periodic_vibrato_rate)[1] rescue 5.0);
  random_vibrato_rate = (args.assoc(:random_vibrato_rate)[1] rescue 16.0);
  periodic_vibrato_amp = (args.assoc(:periodic_vibrato_amp)[1] rescue 0.0025);
  random_vibrato_amp = (args.assoc(:random_vibrato_amp)[1] rescue 0.005);
  noise_amount = (args.assoc(:noise_amount)[1] rescue 0.0);
  noise_freq = (args.assoc(:noise_freq)[1] rescue 1000.0);
  ind_noise_freq = (args.assoc(:ind_noise_freq)[1] rescue 10.0);
  ind_noise_amount = (args.assoc(:ind_noise_amount)[1] rescue 0.0);
  amp_noise_freq = (args.assoc(:amp_noise_freq)[1] rescue 20.0);
  amp_noise_amount = (args.assoc(:amp_noise_amount)[1] rescue 0.0);
  gliss_env = (args.assoc(:gliss_env)[1] rescue [0, 0,  100, 0]);
  gliss_amount = (args.assoc(:gliss_amount)[1] rescue 0.0);
  fm1_env = (args.assoc(:fm1_env)[1] rescue [0, 1, 25, 0.4, 75, 0.6, 100, 0]);
  fm2_env = (args.assoc(:fm2_env)[1] rescue [0, 1, 25, 0.4, 75, 0.6, 100, 0]);
  fm3_env = (args.assoc(:fm3_env)[1] rescue [0, 1, 25, 0.4, 75, 0.6, 100, 0]);
  fm1_rat = (args.assoc(:fm1_rat)[1] rescue 1.0);
  fm2_rat = (args.assoc(:fm2_rat)[1] rescue 3.0);
  fm3_rat = (args.assoc(:fm3_rat)[1] rescue 4.0);
  fm1_index = (args.assoc(:fm1_index)[1] rescue false);
  fm2_index = (args.assoc(:fm2_index)[1] rescue false);
  fm3_index = (args.assoc(:fm3_index)[1] rescue false);
  base = (args.assoc(:base)[1] rescue 1.0);
  reverb_amount = (args.assoc(:reverb_amount)[1] rescue 0.01);
  index_type = (args.assoc(:index_type)[1] rescue :violin);
  degree = (args.assoc(:degree)[1] rescue false);
  distance = (args.assoc(:distance)[1] rescue 1.0);
  degrees = (args.assoc(:degrees)[1] rescue false);

  srate = (srate() rescue $rbm_srate);
  chans = (channels() rescue $rbm_channels);
  beg = (srate * start).round;
  len = (srate * dur).round;
  frq_scl = hz2radians(freq);
  modulate = fm_index.nonzero?;
  maxdev = frq_scl * fm_index;
  vln = (not (index_type == :cello))
  logfreq = log(freq);
  sqrtfreq = sqrt(freq);
  index1 = (fm1_index or [PI, maxdev * (vln ? 5.0 : 7.5) / logfreq].min);
  index2 = (fm2_index or [PI, maxdev * 3.0 * 
	      (vln ? ((8.5 - logfreq) / (3.0 + freq * 0.001)) : (15.0 / sqrtfreq))].min);
  index3 = (fm3_index or [PI, maxdev * (vln ? 4.0 : 8.0) / sqrtfreq].min);
  easy_case = (noise_amount.zero? and
	       (fm1_env == fm2_env) and 
	       (fm1_env == fm3_env) and 
	       (fm1_rat - fm1_rat.floor).zero? and 
	       (fm2_rat - fm2_rat.floor).zero? and 
	       (fm3_rat - fm3_rat.floor).zero?);
  coeffs = (easy_case and modulate and 
	    partials2polynomial([fm1_rat, index1, 
				  (fm2_rat / fm1_rat).floor, index2,
				  (fm3_rat / fm1_rat).floor, index3]));
  norm = ((easy_case and modulate and 1.0) or index1);
  carrier = make_oscil(freq);
  fmosc1 = (modulate and make_oscil(fm1_rat * freq));
  fmosc2 = (modulate and (easy_case or make_oscil(fm2_rat * freq)));
  fmosc3 = (modulate and (easy_case or make_oscil(fm3_rat * freq)));
  ampf = make_env(amp_env, amp, dur, 0.0, base);
  indf1 = (modulate and make_env(fm1_env, norm, dur));
  indf2 = (modulate and (easy_case or make_env(fm2_env, index2, dur)));
  indf3 = (modulate and (easy_case or make_env(fm3_env, index3, dur)));
  frqf = make_env(gliss_env, gliss_amount * frq_scl, dur);
  pervib = make_triangle_wave(periodic_vibrato_rate, periodic_vibrato_amp *  frq_scl);
  ranvib = make_rand_interp(random_vibrato_rate, random_vibrato_amp * frq_scl);
  fm_noi = (noise_amount.nonzero? and make_rand(noise_freq, PI * noise_amount));
  ind_noi = ((ind_noise_amount.nonzero? and ind_noise_freq.nonzero?) and 
	     make_rand_interp(ind_noise_freq, ind_noise_amount));
  amp_noi = ((amp_noise_amount.nonzero? and amp_noise_freq.nonzero?) and
	     make_rand_interp(amp_noise_freq, amp_noise_amount));
  vib = 0.0;
  modulation = 0.0;
  # make_locsig(degree=0.0, distance=1.0, reverb=0.0, output, revout, chans=1, type=Mus_linear)
  # Ruby's rand() is shadowed by CLM's rand(), that's why mus_random().abs.
  loc = make_locsig((degree or degrees or mus_random(90.0).abs), 
		    distance, reverb_amount, false, false, chans);
  fuzz = 0.0;
  ind_fuzz = 1.0;
  amp_fuzz = 1.0;
  out_data = make_vct(len);

  vct_map!(out_data,
	   lambda { | |
	     fuzz = rand(fm_noi) if noise_amount.nonzero?;
	     vib = env(frqf) + triangle_wave(pervib) + rand_interp(ranvib);
	     ind_fuzz = 1.0 + rand_interp(ind_noi) if ind_noi;
	     amp_fuzz = 1.0 + rand_interp(amp_noi) if amp_noi;

	     if(modulate)
	       if(easy_case)
		 modulation = env(indf1) * polynomial(coeffs, oscil(fmosc1, vib));
	       else
		 modulation = env(indf1) * oscil(fmosc1, fm1_rat * vib + fuzz) +
		   env(indf2) * oscil(fmosc2, fm2_rat * vib + fuzz) +
		   env(indf3) * oscil(fmosc3, fm3_rat * vib + fuzz);
	       end
	     end

	     env(ampf) * amp_fuzz * oscil(carrier, vib + ind_fuzz * modulation);
	   });

  if(chans == 2)
    mix_vct(vct_scale!(vct_copy(out_data), locsig_ref(loc, 1)), beg, $rbm_snd, 1, false);
    mix_vct(vct_scale!(out_data, locsig_ref(loc, 0)), beg, $rbm_snd, 0, false);
  else
    mix_vct(out_data, beg, $rbm_snd, 0, false);
  end
rescue
  die(usage + "fm_violin()");
end

</pre>




<!--  FILE: ws  -->

<div class="header" id="wsdoc">ws</div>

<p>
with-sound provides a way to package up a bunch of instrument calls into a new
sound file, and open that file in Snd when the computation is complete. 
To hear (and see) the fm-violin, for example, we first load with-sound and the instrument:
</p>


<table><tr><td>
<div class="scheme">
<pre class="indented">
;; Scheme:
(load "ws.scm")
(load "v.scm")
</pre>
</div>
</td>

<td>
<div class="ruby">
<pre class="indented">
# Ruby:
load("ws.rb")
load("v.rb")
</pre>
</div>
</td>

<td>
<div class="forth">
<pre class="indented">
\ Forth:
"clm.fs" file-eval
"clm-ins.fs" file-eval
</pre>
</div>
</td></tr></table>

<p>Then call with-sound, accepting the default sound file settings, with one fm-violin note at A4 (440 Hz):
</p>

<table><tr><td>

<div class="scheme">
<pre class="indented">
(with-sound ()
  (fm-violin 0 1 440 .1))

</pre>
</div></td>

<td>
<div class="ruby">
<pre class="indented">
with_sound() do 
  fm_violin_rb(0, 1, 440, 0.1) 
end
</pre>
</div></td>

<td>
<div class="forth">
<pre class="indented">
0 1 440 0.1 ' fm-violin with-sound


</pre>
</div>
</td>
</tr></table>

<p>The body of with-sound can hold any number of notes, or any arbitrary code.  For example, say
we want to hear an arpeggio from the fm-violin:
</p>


<pre class="indented">
(with-sound ()
  (do ((i 0 (+ i 1)))
      ((= i 4))                ; 4 notes in all
    (fm-violin (* i 0.25)      ; notes 1/4 secs apart
               0.25            ; each note 1/4 sec long
               (* 220.0 (+ i 1)); go up by 220 Hz on each note
               .1)))           ; all notes .1 amp
</pre>


<p>
with-sound opens an output object, either a sound file, or a vector: (*output*), and
optionally a reverb output object: *reverb*.  Each instrument uses <a href="sndclm.html#out-any">out-any</a> to add its sounds to the
*output* results.  with-sound next sets up a variety of variables describing the current
output, and establishes an environment where various problems can be handled nicely (in Scheme,
a dynamic-wind with various debugging hooks).  Then the with-sound body is evaluated, presumably
producing sound.  Once evaluated, the outputs are closed, and if reverb is requested, the reverberator
is run.  Once complete, with-sound prints out statistics (if :statistics is #t), scales the result (if :scale-to),
and plays it (if :play is #t).  Then, if the output is a sound file (and :to-snd is #t), with-sound opens it in Snd, first closing any previous sound with
the same name (this makes it easier to call with-sound over and over while trying out some patch).
with-sound returns its :output argument.
</p>


<pre class="indented">
  <em class=def id="withsound">with-sound</em>
          (output *clm-file-name*)               ; output file name ("test.snd")
	  (channels *clm-channels*)              ; channels in output (1)
          (srate *clm-srate*)                    ; output sampling rate (44100)
	  (sample-type *clm-sample-type*)        ; output sample data type (mus-bfloat or mus-lshort)
	  (header-type *clm-header-type*)        ; output header type (mus-next or mus-aifc)
	  (comment #f)                           ; any comment to store in the header (a string)
	  (verbose *clm-verbose*)                ; if #t, print out some info
	  (reverb *clm-reverb*)                  ; reverb instrument (jc-reverb)
	  (reverb-data *clm-reverb-data*)        ; arguments passed to the reverb
	  (reverb-channels *clm-reverb-channels*); chans in the reverb intermediate file
          (revfile *clm-reverb-file-name*)       ; reverb intermediate output file name ("test.rev")
	  (continue-old-file #f)                 ; if #t, continue a previous computation
	  (statistics *clm-statistics*)          ; if #t, print info at end of with-sound (compile time, maxamps)
	  (scaled-by #f)                         ; is a number, scale output by that amp
	  (scaled-to #f)                         ; if a number, scale the output to peak at that amp
	  (play *clm-play*)                      ; if #t, play the sound automatically
	  (to-snd *to-snd*)                      ; if #t, open the output file in Snd
</pre>


<p>The with-sound syntax may look sightly odd; we include the arguments in the first list, then
everything after that is evaluated as a note list.
</p>

<pre class="indented">
(with-sound (:srate 44100 :channels 2 :output "test.snd")
  (fm-violin 0 1 440 .1)
  (fm-violin 1 1 660 .1))
</pre>


<p>produces a sound file with two fm-violin notes; the sound file is named "test.snd", is stero, and has a sampling rate of 44100.
</p>


<pre class="indented">
(with-sound (:reverb jc-reverb :statistics #t :play #t) 
  (fm-violin 0 1 440 .1 :reverb-amount .3))
</pre>


<p>produces one fm-violin note, heavily reverberated, and plays it, printing this info:
</p>


<pre class="indented">
&gt; (with-sound (:reverb jc-reverb :statistics #t :play #t) 
    (fm-violin 0 1 440 .1 :reverb-amount .3))
test.snd:
maxamp: 0.3038
rev max: 0.0300
compute time: 0.030
</pre>


<p>It's often hard to predict how loud a set of notes is going to be, so we can use
"scaled-to" to set its final amplitude:
</p>


<pre class="indented">
(with-sound (:scale-to .5) 
  (do ((i 0 (+ i 1))) ((= i 10)) (fm-violin 0 i 440.0 (random 1.0))))
</pre>


<p>Here are examples in Ruby and Forth:
</p>


<pre class="indented">
:with_sound(:channels, 2, :play, false, :statistics, true) do 
  fm_violin_rb(0, 1, 440, 0.1); 
  fm_violin_rb(1, 1, 660, 0.1);
  end
# filename: "test.snd"
#    chans: 2, srate: 22050
#   length: 2.000 (44100 framples)
#   format: big endian short (16 bits) [Sun/Next]
#     real: 2.248  (utime 2.240, stime 0.000)
#    ratio: 1.12  (uratio 1.12)
#  max out: [0.098, 0.024]
#&lt;With_Snd: output: "test.snd", channels: 2, srate: 22050&gt;
</pre>


<p>and in Forth:
</p>

<pre class="indented">
snd&gt; 0.0 1.0 330.0 0.5 ' simp :play #f :channels 2 with-sound
\ filename: test.snd
\    chans: 2, srate: 22050
\   format: little endian float (32 bits) [Sun/Next]
\   length: 1.000  (22050 framples)
\     real: 0.162  (utime 0.267, stime 0.000)
\    ratio: 0.16  (uratio 0.27)
\ maxamp A: 0.500 (near 0.680 secs)
\ maxamp B: 0.000 (near 0.000 secs)
\  comment: Written on Fri Jul 14 07:41:47 PDT 2006 by bil at cat using clm (fth) of 30-Jun-06
</pre>


<p>The default values listed above (*clm-srate* and friends) are set in ws.scm:
</p>


<pre class="indented">
(define *clm-file-name*          "test.snd")
(define *clm-srate*              *default-output-srate*)       ; 44100
(define *clm-channels*           *default-output-chans*)       ; 1
(define *clm-sample-type*        *default-output-sample-type*) ; mus-lfloat
(define *clm-header-type*        *default-output-header-type*) ; mus-next
(define *clm-verbose*            #f)
(define *clm-play*               #f)
(define *clm-statistics*         #f)
(define *clm-reverb*             #f)
(define *clm-reverb-channels*    1)
(define *clm-reverb-data*        ())
(define *clm-reverb-file-name*   "test.rev")
(define *clm-table-size*         512)
(define *clm-file-buffer-size*   65536)
(define *clm-locsig-type*        mus-interp-linear)
(define *clm-clipped*            #t)
(define *clm-array-print-length* *print-length*)  ; 12
(define *clm-player*             #f)
(define *clm-notehook*           #f)
(define *to-snd*                 #t)
(define *reverb*                 #f)
(define *output*                 #f)
(define *clm-delete-reverb*      #f)
</pre>


<p>You can set any of these to permanently change with-sound's defaults
</p>


<pre class="indented">
&gt; (set! *clm-file-name* "test.aif")
#&lt;unspecified&gt;
&gt; (set! *clm-srate* 44100)
#&lt;unspecified&gt;
&gt; (set! *clm-channels* 2)
#&lt;unspecified&gt;
&gt; (set! *clm-header-type* mus-aifc)
#&lt;unspecified&gt;
&gt; (set! *clm-sample-type* mus-bfloat)
#&lt;unspecified&gt;
&gt; (with-sound ()  (fm-violin 0 1 440 .1))test.aif:
"test.aif"
&gt; (srate "test.aif")
44100
&gt; (channels "test.aif")
2
</pre>


<p>
To display the entire sound automatically (independent of <a href="extsnd.html#afteropenhook">after-open-hook</a>),
use with-full-sound:
</p>


<pre class="indented">
(define-macro (with-full-sound args . body)
  `(let ((snd (with-sound-helper (lambda () ,@body) ,@args)))
     (set! (<a class=quiet href="extsnd.html#xbounds">x-bounds</a> *snd-opened-sound*) (list 0.0 (/ (<a class=quiet href="extsnd.html#framples">framples</a> *snd-opened-sound*) (<a class=quiet href="extsnd.html#srate">srate</a> *snd-opened-sound*))))
     snd))
</pre>


<p>Since with-sound returns the new sound's file name, we save that, get the new sound's index (<a href="extsnd.html#sndopenedsound">*snd-opened-sound*</a>),
and set the <a href="extsnd.html#xbounds">x-bounds</a> to display the full sound, then return the file name.  You could obviously customize this any way
you like.
To continue adding notes to an existing file, set 'continue-old-file':
</p>


<pre class="indented">
(with-sound (:continue-old-file #t) (fm-violin 0 1 440 .1))
</pre>


<p>The "notehook" argument is a function called each time an instrument is called:
</p>


<pre class="indented">
&gt; (with-sound (:notehook (lambda (name . args) 
                          (snd-print (<a class=quiet>format</a> #f "~%;~A: ~A" name (caddr args)))))
   (fm-violin 0 1 440 .1) 
   (fm-violin 1 1 660 .1))
;fm-violin: 440
;fm-violin: 660
"test.snd"
</pre>


<p id="definstrument">
The arguments passed to the notehook function are the current instrument name (a string) and all its
arguments.  definstrument implements the notehook feature. 
The "output" argument can be a vector as well as a filename:
</p>

<pre class="indented">
(with-sound (:output (make-float-vector 44100)) (fm-violin 0 1 440 .1))
</pre>


<p>See <a href="#fadedoc">fade.scm</a>, snd-test.scm.
</p>



<div class="innerheader">definstrument</div>

<p>
definstrument
is very much like define*, but with added code to support notehook and (for Common Music) *definstrument-hook*.
It uses old CL-style documentation strings.
An instrument that wants to cooperate fully with with-sound and Common Music has the form:
</p>

<pre class="indented">
(definstrument (ins args)
  (let ...
    (do ((i start (+ i 1)))
        ((= i end))
      (<a class=quiet href="sndclm.html#outa">outa</a> i ...))))
</pre>

<p>definstrument is an extension of define*, so its arguments are handled as optional keyword arguments:
</p>

<pre class="indented">
(definstrument (simp beg dur (frequency 440.0) (amplitude 0.1))
  (let ((os (make-oscil frequency)))
     (do ((i 0 (+ i 1))) ((= i dur))
       (<a class=quiet href="sndclm.html#outa">outa</a> (+ i beg) (* amplitude (<a class=quiet href="sndclm.html#oscil">oscil</a> os))))))

(<a class=quiet href="#wsdoc">with-sound</a> () 
  (simp 0 10000) 
  (simp 10000 10000 550.0 :amplitude 0.1) 
  (simp 20000 10000 :amplitude 0.2))
</pre>

<p>You don't have to use definstrument; in the next example we make a Shepard tone
by calling the oscils and whatnot directly in the with-sound body:
</p>

<pre class="indented">
(define (shepard-tone)
  (let ((x 0.0)
	(incr .000001)               ; sets speed of glissandoes
	(oscs (make-vector 12)))
    (do ((i 0 (+ i 1)))
	((= i 12))
      (set! (oscs i) (<a class=quiet href="sndclm.html#make-oscil">make-oscil</a> :frequency 0.0)))
    (<a class=quiet href="#wsdoc">with-sound</a> (:srate 44100)
     (do ((samp 0 (+ 1 samp))
          (sum 0.0 0.0))
         ((= samp 300000))
       (do ((i 0 (+ i 1)))
           ((= i 12))
         (let ((loc (+ x (/ i 12.0))))  ; location of current oscil in overall trajectory
           (if (&gt; loc 1.0) (set! loc (- loc 1.0)))
           (set! sum (+ sum (* (let ((y (- 4.0 (* 8.0 loc))))
                                 (exp (* -0.5 y y)))  ; Gaussian normal curve as amplitude envelope
                               (<a class=quiet href="sndclm.html#oscil">oscil</a> (oscs i) 
                                      (<a class=quiet href="sndclm.html#hztoradians">hz-&gt;radians</a> (expt 2.0 (+ 2 (* loc 12.0))))))))))
                                      ;; (- 1.0 loc) to go down
       (set! x (+ x incr))
       (<a class=quiet href="sndclm.html#outa">outa</a> samp (* .1 sum))))))
</pre>

<img class="indented" src="pix/shepard.png" alt="shepard tone spectrum" >

<p>There are several other versions of with-sound: with-temp-sound, with-mixed-sound, sound-let, clm-load, and the Common Music
handles, init-with-sound and finish-with-sound.
with-temp-sound and sound-let set up temporary bindings for embedded with-sounds.
</p>



<div class="innerheader">sound-let</div>

<p id="sound-let">sound-let is a form of let* that creates temporary sound files
within with-sound.  Its syntax is a combination of let* and with-sound:
with-sound:</p>

<pre class="indented">
(<em class=red>sound-let</em> ((temp-1 () (fm-violin 0 1 440 .1))
            (temp-2 () (fm-violin 0 2 660 .1)
                       (fm-violin .125 .5 880 .1)))
  (granulate-sound temp-1 0 2 0 2)     ;temp-1's value is the name of the temporary file
  (granulate-sound temp-2 1 1 0 2))
</pre>

<p>This creates two temporary files and passes them along to the subsequent calls
on granulate-sound.  The first list after the sound file identifier (i.e. after
"temp-1" in the example) is the list of <a href="#wsdoc">with-sound</a> options to be passed
along when creating this temporary file.  These default to :output
with a unique name generated internally, and all other variables are taken from
the overall (enclosing) with-sound.  The rest of the list is the body of the
associated <a href="#wsdoc">with-sound</a>.
The difference between sound-let and an embedded with-sound is primarily that
sound-let names and later deletes the temporary files it creates, whereas with-sound leaves
its explicitly named output intact (and tries to open it in Snd, which can be confusing in this context).
Here's another example:
</p>

<pre class="indented">
  (<a class=quiet href="#wsdoc">with-sound</a> ()
    (<em class=red>sound-let</em> ((temp-sound () (fm-violin 0 1 440 .1))) ; create temp-sound with an fm-violin note
       (pins 0.0 2.0 temp-sound 1.0 :time-scaler 2.0))  ; stretch it with the pins instrument (clm-ins.scm)
    (fm-violin 1 1 550 .1))                             ; add another fm-violin note
</pre>




<div class="innerheader">with-temp-sound</div>

<p id="withtempsound">with-temp-sound is like sound-let, but does not delete its output file:
</p>

<pre class="indented">
(<a class=quiet href="#wsdoc">with-sound</a> ()
  (clm-expsrc 0 2 (<em class=red>with-temp-sound</em> () (fm-violin 0 1 440 .1)) 2.0 1.0 1.0))
</pre>


<p>Here are Ruby examples:
</p>

<pre class="indented">
with_sound() do
  clm_mix(with_sound(:output, "hiho.snd") do
            fm_violin_rb(0, 1, 440, 0.1)
          end.output, :scale, 0.5)
end

with_sound() do
  with_mix "s1", %Q{
  sound_let(lambda do fm_violin_rb(0, 1, 440, 0.1) end) do |tmp|
    clm_mix(tmp)
  end
  }
end
</pre>



<div class="innerheader">with-mixed-sound</div>

<p id="withmixedsound">with-mixed-sound is a variant of with-sound that creates a
<a href="extsnd.html#sndmixes">"mix"</a> for each note in the notelist.  If you move the
mixes around, you can write out the new note list via with-mixed-sound-&gt;notelist.
In multichannel files, all the channels associated with a note are sync'd together, so if you drag one,
the others follow.  Also, if you click a mix tag, the corresponding note in the notelist is displayed
in the status area.
</p>


<pre class="indented">
(with-mixed-sound () 
  (fm-violin 0 .1 440 .1) 
  (fm-violin 1 .1 660 .1))

(with-mixed-sound (:channels 2) 
  (fm-violin 0 .1 440 .1 :degree 0) 
  (fm-violin 1 .1 660 .1 :degree 45))
</pre>


<p>There's also a quick sound file mixer named mus-file-mix:
</p>


<pre class="indented">
<em class=def id="musfilemix">mus-file-mix</em> outfile infile (outloc 0) (framples) (inloc 0) mixer envs
</pre>


<p>This function
mixes 'infile' into 'outfile' starting at 'outloc' in 'outfile' and 'inloc' in 'infile',
mixing 'framples' framples into 'outfile'.  'framples' defaults to the length of 'infile'. If 'mixer',
use it to scale the various channels; if 'envs' (an array of envelope generators), use
it in conjunction with mixer to scale and envelope all the various ins and outs.
'outfile' can also be a <a href="sndclm.html#frampletofile">frample-&gt;file</a> generator, and 'infile' can be a 
<a href="sndclm.html#filetoframple">file-&gt;frample</a> generator.
</p>

<pre class="indented">
(<a class=quiet href="#wsdoc">with-sound</a> () 
  (fm-violin 0 .1 440 .1) 
  (<a class=quiet href="#musfilemix">mus-file-mix</a> <a class=quiet>*output*</a> "oboe.snd") 
  (fm-violin .1 .1 660 .1))
</pre>




<div class="innerheader">with-marked-sound</div>

<p id="withmarkedsound">with-marked-sound is yet another version of with-sound that 
adds a mark at the start of each note.  
</p>


<div class="innerheader">clm-load</div>

<p>clm-load provides a slightly different way to load a notelist.  Its first argument is a filename, assumed to
be a text file containing notes (equivalent to the body of with-sound). The rest of the arguments to clm-load are the usual with-sound arguments, if any.
For example, if we have a file named clm-load-test.clm with these contents:
</p>

<pre class="indented">
(fm-violin 0 1 440 .1)
(fm-violin 1 1 660 .1)
</pre>

<p>
then (clm-load "clm-load-test.clm") is the same as (with-sound () (fm-violin 0 1 440 .1) (fm-violin 1 1 660 .1)).
Similarly for, (clm-load "clm-load-test.clm" :srate 44100 :channels 2) and so on.
</p>


<div class="innerheader">init-with-sound</div>

<p>init-with-sound and finish-with-sound
split with-sound into two pieces, primarily for Common Music's benefit.
</p>

<pre class="indented">
(define w (init-with-sound :scaled-to .5))
(fm-violin 0 1 440 .1)
(finish-with-sound w)
</pre>

<p>is equivalent to 
</p>

<pre class="indented">
(<a class=quiet href="#wsdoc">with-sound</a> (:scaled-to .5)
  (fm-violin 0 1 440 .1))
</pre>



<div class="innerheader">other stuff associated with with-sound</div>

<p id="wssavestate">
The *clm-* variables are saved in the save-state
file by ws-save-state, which may not be a good idea &mdash; feedback welcome!
Two more convenience functions are -&gt;frequency and -&gt;sample.
<em class="noem" id="tofrequency">-&gt;frequency</em> takes either a number or a common-music pitch symbol ('c4 is middle C),
and returns either the number or the frequency associated with that pitch:
</p>

<pre class="indented">
&gt; (-&gt;frequency 'cs5)
554.365261953744
</pre>

<p id="tosample">It's optional second argument can be #t to get integer ratios, rather than
the default equal temperment.
-&gt;sample returns a sample number given a time in seconds:
</p>

<pre class="indented">
&gt; (-&gt;sample 1.0)
44100
</pre>


<p>mix-notelists takes any number of notelist arguments,
and returns a new notelist with all the input notes sorted by begin time.
</p>

<pre class="indented">
(mix-notelists '((fm-violin 0 1 440 .1)
		 (fm-violin 1 1 550 .1))
	       '((bird 0 .1 )
		 (bird .2 .1)
		 (bird 1.2 .3)
		 (bird .5 .5)))

((bird 0 0.1) (fm-violin 0 1 440 0.1) (bird 0.2 0.1) (bird 0.5 0.5) (fm-violin 1 1 550 0.1) (bird 1.2 0.3))
</pre>

  



<!--  FILE: zip  -->

<div class="header" id="zipdoc">zip</div>

<pre class="indented">
<em class=emdef>make-zipper</em> ramp-env frame-size frame-env
<em class=def id="zipper">zipper</em> gen in1 in2
<em class=def id="zipsound">zip-sound</em> beg dur file1 file2 ramp size
</pre>

<p>The zipper generator performs a kind of cross fade, but not one that
tries to be smooth!  It marches through the two sounds taking equal short
portions of each, then abutting them while resampling so that as one
takes less overall frame space, the other takes more.  The 'frame-size'
argument is the maximum length of each twosome in seconds (for initial array allocation), the 'frame-env'
argument determines the current such length as new frames are needed, and the
'ramp-env' argument determines which of the files gets more space
in the frame (0: all first, 1: all second).
The following function sets up two sounds,
an upward ramp and a downward ramp, then zips them together:
</p>

<pre class="indented">
(define (ramp-test)
  (let ((data (make-float-vector 10000)))
    (<a class=quiet href="extsnd.html#newsound">new-sound</a> "new-0.snd")
    (do ((i 0 (+ i 1))) ((= i 10000)) 
      (set! (data i) (* i .0001)))
    (float-vector-&gt;channel data 0 10000 0)
    (<a class=quiet href="extsnd.html#newsound">new-sound</a> "new-1.snd")
    (do ((i 0 (+ i 1))) ((= i 10000)) 
      (set! (data i) (- 1.0 (* i .0001))))
    (float-vector-&gt;channel data 0 10000 1)
    (let ((zp (let ((dur (<a class=quiet href="extsnd.html#framples">framples</a>)))
                (<em class=red>make-zipper</em> 
                  (<a class=quiet href="sndclm.html#make-env">make-env</a> '(0 0 1 1) :length dur)
		  0.05
		  (<a class=quiet href="sndclm.html#make-env">make-env</a> (list 0 (* (<a class=quiet href="extsnd.html#srate">srate</a>) 0.05)) :length dur))))
	  (reader0 (<a class=quiet href="extsnd.html#makesampler">make-sampler</a> 0 0 0))
	  (reader1 (<a class=quiet href="extsnd.html#makesampler">make-sampler</a> 0 1 0)))
      (<a class=quiet href="extsnd.html#mapchannel">map-channel</a> (lambda (val) (<em class=red>zipper</em> zp reader0 reader1))))))
</pre>


<img class="indented" src="pix/zramp.png" alt="zipper ramp output">
<p>Needless to say, this is not intended to be a suave, romantic gesture!
</p>

<p>zip-sound applies the zipper to a pair of sounds:
</p>

<pre class="indented">
(zip-sound 0 1 "fyow.snd" "now.snd" '(0 0 1 1) .05)
(zip-sound 0 3 "mb.snd" "fyow.snd" '(0 0 1.0 0 1.5 1.0 3.0 1.0) .025)
</pre>




<div class="related">
related documentation: &nbsp;
<a href="snd.html">snd.html &nbsp;</a>
<a href="extsnd.html">extsnd.html &nbsp;</a>
<a href="grfsnd.html">grfsnd.html &nbsp;</a>
<a href="sndclm.html">sndclm.html &nbsp;</a>
<a href="sndlib.html">sndlib.html &nbsp;</a>
<a href="fm.html">fm.html &nbsp;</a>
<a href="s7.html">s7.html &nbsp;</a>
<a href="s7-ffi.html">s7-ffi.html &nbsp;</a>
<a href="s7-scm.html">s7-scm.html &nbsp;</a>
<a href="index.html">index.html</a>
</div>

</body>
</html>