File: oscillators.lib

package info (click to toggle)
faust 2.79.3%2Bds-2
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 397,496 kB
  • sloc: cpp: 278,433; ansic: 116,164; javascript: 18,529; vhdl: 14,052; sh: 13,884; java: 5,900; objc: 3,852; python: 3,222; makefile: 2,655; cs: 1,672; lisp: 1,146; ruby: 954; yacc: 586; xml: 471; lex: 247; awk: 110; tcl: 26
file content (2093 lines) | stat: -rw-r--r-- 62,381 bytes parent folder | download
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
//############################## oscillators.lib ######################################
// This library contains a collection of sound generators. Its official prefix is `os`.
//
// The oscillators library is organized into 9 sections:
//
// * [Wave-Table-Based Oscillators](#wave-table-based-oscillators)
// * [Low Frequency Oscillators](#low-frequency-oscillators)
// * [Low Frequency Sawtooths](#low-frequency-sawtooths)
// * [Alias-Suppressed Sawtooth](#alias-suppressed-sawtooth)
// * [Alias-Suppressed Pulse, Square, and Impulse Trains](#alias-suppressed-pulse-square-and-impulse-trains)
// * [Filter-Based Oscillators](#filter-based-oscillators)
// * [Waveguide-Resonator-Based Oscillators](#waveguide-resonator-based-oscillators)
// * [Casio CZ Oscillators](#casio-cz-oscillators)
// * [PolyBLEP-Based Oscillators](#polyblep-based-oscillators)
//
// #### References
// * <https://github.com/grame-cncm/faustlibraries/blob/master/oscillators.lib>
//########################################################################################

/************************************************************************
************************************************************************
FAUST library file, GRAME section

Except where noted otherwise, Copyright (C) 2003-2017 by GRAME,
Centre National de Creation Musicale.
----------------------------------------------------------------------
GRAME LICENSE

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as
published by the Free Software Foundation; either version 2.1 of the
License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public
License along with the GNU C Library; if not, write to the Free
Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
02111-1307 USA.

EXCEPTION TO THE LGPL LICENSE : As a special exception, you may create a
larger FAUST program which directly or indirectly imports this library
file and still distribute the compiled code generated by the FAUST
compiler, or a modified version of this compiled code, under your own
copyright and license. This EXCEPTION TO THE LGPL LICENSE explicitly
grants you the right to freely choose the license for the resulting
compiled code. In particular the resulting compiled code has no obligation
to be LGPL or GPL. For example you are free to choose a commercial or
closed source license or any other license if you decide so.
************************************************************************
************************************************************************/

ma = library("maths.lib");
ba = library("basics.lib");
fi = library("filters.lib");
si = library("signals.lib");

declare name "Faust Oscillator Library";
declare version "1.6.0";

// This library contains platform specific constants
pl = library("platform.lib");

//======================Oscillators based on mathematical functions===============
//
// Note that there is a numerical problem with several phasor functions built using the internal
// `phasor_imp`. The reason is that the incremental step is smaller than `ma.EPSILON`, which happens with very small frequencies, 
// so it will have no effect when summed to 1, but it will be enough to make the fractional function wrap 
// around when summed to 0. An example of this problem can be observed when running the following code:
//
// `process = os.phasor(1.0, -.001);`
//
// The output of this program is the sequence 1, 0, 1, 0, 1... This happens because the negative incremental 
// step is greater than `-ma.EPSILON`, which will have no effect when summed to 1, but it will be significant 
// enough to make the fractional function  wrap around when summed to 0.
//
// The incremental step can be clipped to guarantee that the phasor will 
// always run correctly for its full cycle, otherwise, for increments smaller than `ma.EPSILON`, 
// phasor would initially run but it'd eventually get stuck once the output gets big enough.
// 
// All functions using `phasor_imp` are affected by this problem, but a safer
// version is implemented, and can be used alternatively by setting `SAFE=1` in the environment using 
// [explicit sustitution](https://faustdoc.grame.fr/manual/syntax/#explicit-substitution) syntax.
// 
// For example: `process = os[SAFE=1;].phasor(1.0, -.001);` will use the safer implementation of `phasor_imp`.
//=================================================================================

//=========================Wave-Table-Based Oscillators===================================
// Oscillators using tables. The table size is set by the 
// [pl.tablesize](https://github.com/grame-cncm/faustlibraries/blob/master/platform.lib) constant.
//========================================================================================

// Global parameter to use the safer version of `phasor_imp`, but which
// could be used in other functions as well.

SAFE = 0; // 0: use the faster version, 1: use the safer version

//-----------------------`(os.)sinwaveform`------------------------
// Sine waveform ready to use with a `rdtable`.
//
// #### Usage
//
// ```
// sinwaveform(tablesize) : _
// ```
//
// Where:
//
// * `tablesize`: the table size
//------------------------------------------------------------
sinwaveform(tablesize) =
    sin(float(ba.period(tablesize)) * (2.0 * ma.PI) / float(tablesize));


//-----------------------`(os.)coswaveform`------------------------
// Cosine waveform ready to use with a `rdtable`.
//
// #### Usage
//
// ```
// coswaveform(tablesize) : _
// ```
//
// Where:
//
// * `tablesize`: the table size
//------------------------------------------------------------
coswaveform(tablesize) =
    cos(float(ba.period(tablesize)) * (2.0 * ma.PI) / float(tablesize));

// Possibly faster version using integer arithmetic
phasor_env(freq, N) = environment {

    //------- GLOBAL PARAMS
    nbits = 31;
    tablesize = 1<<N;
    accuracy = int(nbits - N);
    mask = (1<<nbits)-1;
    inc(step) = int(tablesize * step * (1<<accuracy));

    //------- LAMBDA DSP CASE 
    lambda(inc_op) = (inc_op : &(mask)) ~ _ : >>(accuracy) : /(tablesize);

    //------- MINIMAL CASE
    hsp(0,0) = lambda(+(inc(freq/ma.SR)'));
    
    //------- GENERAL CASE
    hsp(reset,phase) = lambda(select2(hard_reset,+(inc(freq/ma.SR)),inc(phase)))
    with {
        hard_reset = (1-1')|reset;
    };
};
declare phasor_env author "Pierre Mascarade Relano, Maxime Sirbu, Stéphane Letz";

// Generic phasor with `reset` and `phase` parameters to be specialised in concrete use-cases.
phasor_imp(freq, reset, phase) = (select2(hard_reset, +(incr(SAFE)), phase) : ma.decimal) ~ _
with {
    incr_aux = freq/ma.SR;

    // Faster but less accurate version
    incr(0) = incr_aux;

    // To make sure that the incremental step is greater or equal to EPSILON or 
    // less than or equal to -EPSILON to avoid numerical problems. 
    // A frequency of 0Hz can still be used to freeze the phasor.
    incr(1)= (freq != 0) * ba.if(freq < 0, min(-1.0 * ma.EPSILON, incr_aux), max(ma.EPSILON, incr_aux));

    // To correctly start at `phase` at the first sample
    hard_reset = (1-1')|reset; 
};

// Possibly faster version using integer arithmetic
// phasor_imp(freq, reset, phase) = phasor_env(freq, 16).hsp(reset, phase);

// Version to be used with tables
phasor_table(tablesize, freq, reset, phase) = phasor_imp(freq, reset, phase) : *(float(tablesize));


//-----------------------`(os.)phasor`------------------------
// A simple phasor to be used with a `rdtable`.
// `phasor` is a standard Faust function.
//
// #### Usage
//
// ```
// phasor(tablesize,freq) : _
// ```
//
// Where:
//
// * `tablesize`: the table size
// * `freq`: the frequency in Hz
//
// Note that `tablesize` is just a multiplier for the output of a unit-amp phasor
// so `phasor(1.0, freq)` can be used to generate a phasor output in the range [0, 1[.
//------------------------------------------------------------
phasor(tablesize, freq) = phasor_table(tablesize, freq, 0, 0);


//-----------------------`(os.)hs_phasor`------------------------
// Hardsyncing phasor to be used with a `rdtable`.
//
// #### Usage
//
// ```
// hs_phasor(tablesize,freq,reset) :  _
// ```
//
// Where:
//
// * `tablesize`: the table size
// * `freq`: the frequency in Hz
// * `reset`: a reset signal, reset phase to 0 when equal to 1
//---------------------------------------------------------
declare hs_phasor author "Mike Olsen, revised by Stéphane Letz";

hs_phasor(tablesize, freq, reset) = phasor_table(tablesize, freq, reset, 0);


//-----------------------`(os.)hsp_phasor`------------------------
// Hardsyncing phasor with selectable phase to be used with a `rdtable`.
//
// #### Usage
//
// ```
// hsp_phasor(tablesize,freq,reset,phase)
// ```
//
// Where:
//
// * `tablesize`: the table size
// * `freq`: the frequency in Hz
// * `reset`: reset the oscillator to phase when equal to 1
// * `phase`: phase between 0 and 1
//---------------------------------------------------------
declare hsp_phasor author "Christophe Lebreton, revised by Stéphane Letz";

hsp_phasor(tablesize, freq, reset, phase) = phasor_table(tablesize, freq, reset, phase);


//-----------------------`(os.)oscsin`------------------------
// Sine wave oscillator.
// `oscsin` is a standard Faust function.
//
// #### Usage
//
// ```
// oscsin(freq) : _
// ```
//
// Where:
//
// * `freq`: the frequency in Hz
//------------------------------------------------------------
oscsin(freq) = rdtable(tablesize, sinwaveform(tablesize), int(phasor(tablesize,freq)))
with {
    tablesize = pl.tablesize;
};


//-----------------------`(os.)hs_oscsin`------------------------
// Sin lookup table with hardsyncing phase.
//
// #### Usage
//
// ```
// hs_oscsin(freq,reset) : _
// ```
//
// Where:
//
// * `freq`: the frequency in Hz
// * `reset`: reset the oscillator to 0 when equal to 1
//---------------------------------------------------------
declare hs_oscsin author "Mike Olsen";

hs_oscsin(freq,reset) = rdtable(tablesize, sinwaveform(tablesize), int(hs_phasor(tablesize,freq,reset)))
with {
    tablesize = pl.tablesize;
};


//-----------------------`(os.)osccos`------------------------
// Cosine wave oscillator.
//
// #### Usage
//
// ```
// osccos(freq) : _
// ```
//
// Where:
//
// * `freq`: the frequency in Hz
//------------------------------------------------------------
osccos(freq) = rdtable(tablesize, coswaveform(tablesize), int(phasor(tablesize,freq)))
with {
    tablesize = pl.tablesize;
};


//-----------------------`(os.)hs_osccos`------------------------
// Cos lookup table with hardsyncing phase.
//
// #### Usage
//
// ```
// hs_osccos(freq,reset) : _
// ```
//
// Where:
//
// * `freq`: the frequency in Hz
// * `reset`: reset the oscillator to 0 when equal to 1
//---------------------------------------------------------
declare hs_osccos author "Stéphane Letz";

hs_osccos(freq,reset) = rdtable(tablesize, coswaveform(tablesize), int(hs_phasor(tablesize,freq,reset)))
with {
    tablesize = pl.tablesize;
};


//-----------------------`(os.)oscp`------------------------
// A sine wave generator with controllable phase.
//
// #### Usage
//
// ```
// oscp(freq,phase) : _
// ```
//
// Where:
//
// * `freq`: the frequency in Hz
// * `phase`: the phase in radian
//------------------------------------------------------------
oscp(freq,phase) = oscsin(freq) * cos(phase) + osccos(freq) * sin(phase);


//-----------------------`(os.)osci`------------------------
// Interpolated phase sine wave oscillator.
//
// #### Usage
//
// ```
// osci(freq) : _
// ```
//
// Where:
//
// * `freq`: the frequency in Hz
//------------------------------------------------------------
osci(freq) = s1 + d * (s2 - s1)
with {
    tablesize = pl.tablesize;
    i = int(phasor(tablesize,freq));
    d = ma.decimal(phasor(tablesize,freq));
    s1 = rdtable(tablesize+1,sinwaveform(tablesize),i);
    s2 = rdtable(tablesize+1,sinwaveform(tablesize),i+1);
};


//-----------------------`(os.)osc`------------------------
// Default sine wave oscillator (same as [oscsin](#oscsin)).
// `osc` is a standard Faust function.
//
// #### Usage
//
// ```
// osc(freq) : _
// ```
//
// Where:
//
// * `freq`: the frequency in Hz
//------------------------------------------------------------
osc = oscsin;


//-----------------------`(os.)m_oscsin`------------------------
// Sine wave oscillator based on the `sin` mathematical function.
//
// #### Usage
//
// ```
// m_oscsin(freq) : _
// ```
//
// Where:
//
// * `freq`: the frequency in Hz
//------------------------------------------------------------
m_oscsin(freq) = lf_sawpos(freq) : *(2*ma.PI) : sin;


//-----------------------`(os.)m_osccos`------------------------
// Sine wave oscillator based on the `cos` mathematical function.
//
// #### Usage
//
// ```
// m_osccos(freq) : _
// ```
//
// Where:
//
// * `freq`: the frequency in Hz
//------------------------------------------------------------
m_osccos(freq) = lf_sawpos(freq) : *(2*ma.PI) : cos;


// end GRAME section
//########################################################################################
/************************************************************************
FAUST library file, jos section

Except where noted otherwise, The Faust functions below in this
section are Copyright (C) 2003-2022 by Julius O. Smith III <jos@ccrma.stanford.edu>
([jos](http://ccrma.stanford.edu/~jos/)), and released under the
(MIT-style) [STK-4.3](#stk-4.3-license) license.

The MarkDown comments in this section are Copyright 2016-2017 by Romain
Michon and Julius O. Smith III, and are released under the
[CCA4I](https://creativecommons.org/licenses/by/4.0/) license (TODO: if/when Romain agrees)

************************************************************************/

//===============================Low Frequency Oscillators===============================
// Low Frequency Oscillators (LFOs) have prefix `lf_`
// (no aliasing suppression, since it is inaudible at LF).
// Use `sawN` and its derivatives for audio oscillators with suppressed aliasing.
//==================================================================

//--------`(os.)lf_imptrain`----------
// Unit-amplitude low-frequency impulse train.
// `lf_imptrain` is a standard Faust function.

// #### Usage
//
// ```
// lf_imptrain(freq) : _
// ```

// Where:
//
// * `freq`: frequency in Hz
//------------------------------------------------------------
lf_imptrain(freq) = lf_sawpos(freq)<:-(mem)<0; // definition below


//--------`(os.)lf_pulsetrainpos`----------
// Unit-amplitude nonnegative LF pulse train, duty cycle between 0 and 1.
//
//
// #### Usage
//
// ```
// lf_pulsetrainpos(freq, duty) : _
// ```
//
// Where:
//
// * `freq`: frequency in Hz
// * `duty`: duty cycle between 0 and 1
//------------------------------------------------------------
lf_pulsetrainpos(freq,duty) = float(lf_sawpos(freq) <= duty);

//pulsetrainpos = lf_pulsetrainpos; // for backward compatibility


//--------`(os.)lf_pulsetrain`----------
// Unit-amplitude zero-mean LF pulse train, duty cycle between 0 and 1.
//
// #### Usage
//
// ```
// lf_pulsetrain(freq,duty) : _
// ```
//
// Where:
//
// * `freq`: frequency in Hz
// * `duty`: duty cycle between 0 and 1
//------------------------------------------------------------
lf_pulsetrain(freq,duty) = 2.0*lf_pulsetrainpos(freq,duty) - 1.0;


//--------`(os.)lf_squarewavepos`----------
// Positive LF square wave in [0,1]
//
// #### Usage
//
// ```
// lf_squarewavepos(freq) : _
// ```
//
// Where:
//
// * `freq`: frequency in Hz
//------------------------------------------------------------
lf_squarewavepos(freq) = lf_pulsetrainpos(freq,0.5);
// squarewavepos = lf_squarewavepos; // for backward compatibility


//--------`(os.)lf_squarewave`----------
// Zero-mean unit-amplitude LF square wave.
// `lf_squarewave` is a standard Faust function.
//
// #### Usage
//
// ```
// lf_squarewave(freq) : _
// ```
//
// Where:
//
// * `freq`: frequency in Hz
//------------------------------------------------------------
lf_squarewave(freq) = 2.0*lf_squarewavepos(freq) - 1.0;
// squarewave = lf_squarewave; // for backward compatibility


//--------`(os.)lf_trianglepos`----------
// Positive unit-amplitude LF positive triangle wave.
//
// #### Usage
//
// ```
// lf_trianglepos(freq) : _
// ```
//
// Where:
//
// * `freq`: frequency in Hz
//------------------------------------------------------------
lf_trianglepos(freq) = 1.0-abs(saw1(freq)); // saw1 defined below


//----------`(os.)lf_triangle`----------
// Zero-mean unit-amplitude LF triangle wave.
// `lf_triangle` is a standard Faust function.
//
// #### Usage
//
// ```
// lf_triangle(freq) : _
// ```
//
// Where:
//
// * `freq`: frequency in Hz
//------------------------------------------------------------
declare lf_triangle author "Bart Brouns";
declare lf_triangle licence "STK-4.3";

lf_triangle(freq) = 2.0*lf_trianglepos(freq) - 1.0;


//================== Low Frequency Sawtooths ====================
// Sawtooth waveform oscillators for virtual analog synthesis et al.
// The 'simple' versions (`lf_rawsaw`, `lf_sawpos` and `saw1`), are mere samplings of
// the ideal continuous-time ("analog") waveforms.  While simple, the
// aliasing due to sampling is quite audible.  The differentiated
// polynomial waveform family (`saw2`, `sawN`, and derived functions)
// do some extra processing to suppress aliasing (not audible for
// very low fundamental frequencies).  According to Lehtonen et al.
// (JASA 2012), the aliasing of `saw2` should be inaudible at fundamental
// frequencies below 2 kHz or so, for a 44.1 kHz sampling rate and 60 dB SPL
// presentation level;  fundamentals 415 and below required no aliasing
// suppression (i.e., `saw1` is ok).
//=====================================================================

//-----------------`(os.)lf_rawsaw`--------------------
// Simple sawtooth waveform oscillator between 0 and period in samples.
//
// #### Usage
//
// ```
// lf_rawsaw(periodsamps) : _
// ```
//
// Where:
//
// * `periodsamps`: number of periods per samples
//---------------------------------------------------------
lf_rawsaw(periodsamps) = (_,periodsamps : fmod) ~ +(1.0);


//-----------------`(os.)lf_sawpos`--------------------
// Simple sawtooth waveform oscillator between 0 and 1.
//
// #### Usage
//
// ```
// lf_sawpos(freq) : _
// ```
//
// Where:
//
// * `freq`: frequency in Hz
//
//---------------------------------------------------------
declare lf_sawpos author "Bart Brouns, revised by Stéphane Letz";
declare lf_sawpos licence "STK-4.3";

lf_sawpos(freq) = phasor_imp(freq, 0, 0);


//-----------------`(os.)lf_sawpos_phase`--------------------
// Simple sawtooth waveform oscillator between 0 and 1
// with phase control.
//
// #### Usage
//
// ```
// lf_sawpos_phase(freq, phase) : _
// ```
//
// Where:
//
// * `freq`: frequency in Hz
// * `phase`: phase between 0 and 1
//---------------------------------------------------------
declare lf_sawpos_phase author "Bart Brouns, revised by Stéphane Letz";
declare lf_sawpos_phase licence "STK-4.3";

lf_sawpos_phase(freq,phase) = phasor_imp(freq, 0, phase);


//-----------------`(os.)lf_sawpos_reset`--------------------
// Simple sawtooth waveform oscillator between 0 and 1
// with reset.
//
// #### Usage
//
// ```
// lf_sawpos_reset(freq,reset) : _
// ```
//
// Where:
//
// * `freq`: frequency in Hz
// * `reset`: reset the oscillator to 0 when equal to 1
//
//---------------------------------------------------------
declare lf_sawpos_reset author "Bart Brouns, revised by Stéphane Letz";
declare lf_sawpos_reset licence "STK-4.3";

lf_sawpos_reset(freq,reset) = phasor_imp(freq, reset, 0);


//-----------------`(os.)lf_sawpos_phase_reset`--------------------
// Simple sawtooth waveform oscillator between 0 and 1
// with phase control and reset.
//
// #### Usage
//
// ```
// lf_sawpos_phase_reset(freq,phase,reset) : _
// ```
//
// Where:
//
// * `freq`: frequency in Hz
// * `phase`: phase between 0 and 1
// * `reset`: reset the oscillator to phase when equal to 1
//
//---------------------------------------------------------
declare lf_sawpos_phase_reset author "Bart Brouns, revised by Stéphane Letz";
declare lf_sawpos_phase_reset licence "STK-4.3";

lf_sawpos_phase_reset(freq,phase,reset) = phasor_imp(freq, reset, phase);


//-----------------`(os.)lf_saw`--------------------
// Simple sawtooth waveform oscillator between -1 and 1.
// `lf_saw` is a standard Faust function.
//
// #### Usage
//
// ```
// lf_saw(freq) : _
// ```
//
// Where:
//
// * `freq`: frequency in Hz
//---------------------------------------------------------
declare saw1 author "Bart Brouns";
declare saw1 licence "STK-4.3";

saw1(freq) = 2.0 * lf_sawpos(freq) - 1.0;
lf_saw(freq) = saw1(freq);

//================== Alias-Suppressed Sawtooth ====================
//-----------------`(os.)sawN`--------------------
// Alias-Suppressed Sawtooth Audio-Frequency Oscillator using Nth-order polynomial transitions
// to reduce aliasing.
//
// `sawN(N,freq)`, `sawNp(N,freq,phase)`, `saw2dpw(freq)`, `saw2(freq)`, `saw3(freq)`,
// `saw4(freq)`, `sawtooth(freq)`, `saw2f2(freq)`, `saw2f4(freq)`
//
// #### Usage
//
// ```
// sawN(N,freq) : _        // Nth-order aliasing-suppressed sawtooth using DPW method (see below)
// sawNp(N,freq,phase) : _ // sawN with phase offset feature
// saw2dpw(freq) : _       // saw2 using DPW
// saw2ptr(freq) : _       // saw2 using the faster, stateless PTR method
// saw2(freq) : _          // DPW method, but subject to change if a better method emerges
// saw3(freq) : _          // sawN(3)
// saw4(freq) : _          // sawN(4)
// sawtooth(freq) : _      // saw2
// saw2f2(freq) : _        // saw2dpw with 2nd-order droop-correction filtering
// saw2f4(freq) : _        // saw2dpw with 4th-order droop-correction filtering
// ```
//
// Where:
//
// * `N`: polynomial order, a constant numerical expression between 1 and 4
// * `freq`: frequency in Hz
// * `phase`: phase between 0 and 1
//
// #### Method
// Differentiated Polynomial Wave (DPW).
//
// ##### Reference
// "Alias-Suppressed Oscillators based on Differentiated Polynomial Waveforms",
// Vesa Valimaki, Juhan Nam, Julius Smith, and Jonathan Abel,
// IEEE Tr. Audio, Speech, and Language Processing (IEEE-ASLP),
// Vol. 18, no. 5, pp 786-798, May 2010.
// 10.1109/TASL.2009.2026507.
//
// #### Notes
// The polynomial order `N` is limited to 4 because noise has been
// observed at very low `freq` values.  (LFO sawtooths should of course
// be generated using `lf_sawpos` instead.)
//-----------------------------------------------------------------
declare sawN author "Julius O. Smith III";
declare sawN license "STK-4.3";
// --- sawN for N = 1 to 4 ---
// Orders 5 and 6 have noise at low fundamentals: MAX_SAW_ORDER = 6; MAX_SAW_ORDER_NEXTPOW2 = 8;
MAX_SAW_ORDER = 4;
MAX_SAW_ORDER_NEXTPOW2 = 8; // par cannot handle the case of 0 elements
sawN(N,freq) = saw1l : poly(Nc) : D(Nc-1) : gate(Nc-1)
with {
  Nc = max(1,min(N,MAX_SAW_ORDER));
  clippedFreq = max(20.0,abs(freq)); // use lf_sawpos(freq) for LFOs (freq < 20 Hz)
  saw1l = 2*lf_sawpos(clippedFreq) - 1; // zero-mean, amplitude +/- 1
  poly(1,x) = x;
  poly(2,x) = x*x;
  poly(3,x) = x*x*x - x;
  poly(4,x) = x*x*(x*x - 2.0);
  poly(5,x) = x*(7.0/3 + x*x*(-10.0/3.0 + x*x));
  poly(6,x) = x*x*(7.0 + x*x*(-5.0 + x*x));
  p0n = float(ma.SR)/clippedFreq; // period in samples
  diff1(x) = (x - x')/(2.0/p0n);
  diff(N) = seq(n,N,diff1); // N diff1s in series
  factorial(0) = 1;
  factorial(i) = i * factorial(i-1);
  D(0) = _;
  D(i) = diff(i)/factorial(i+1);
  gate(N) = *(1@(N)); // delayed step for blanking startup glitch
};

//------------------`(os.)sawNp`--------------------------------
// Same as `(os.)sawN` but with a controllable waveform phase.
//
// #### Usage
//
// ```
// sawNp(N,freq,phase) : _
// ```
//
// where
//
// * `N`: waveform interpolation polynomial order 1 to 4 (constant integer expression)
// * `freq`: frequency in Hz
// * `phase`: waveform phase as a fraction of one period (rounded to nearest sample)
//
// #### Implementation Notes
//
// The phase offset is implemented by delaying `sawN(N,freq)` by
// `round(phase*ma.SR/freq)` samples, for up to 8191 samples.
// The minimum sawtooth frequency that can be delayed a whole period
// is therefore `ma.SR/8191`, which is well below audibility for normal
// audio sampling rates.
//
//-----------------------------------------------------------------
declare sawNp author "Julius O. Smith III";
declare sawNp license "STK-4.3";
// --- sawNp for N = 1 to 4 ---
// Phase offset = delay (max 8191 samples is more than one period of audio):
sawNp(N,freq,phase) = sawN(N,freq) : @(max(0,min(8191,int(0.5+phase*ma.SR/freq))));

//------------------`(os.)saw2, (os.)saw3, (os.)saw4`--------------
// Alias-Suppressed Sawtooth Audio-Frequency Oscillators of order 2, 3, 4.
//
// #### Usage
//
// ```
// saw2(freq) : _
// saw3(freq) : _
// saw4(freq) : _
// ```
//
// where
//
// * `freq`: frequency in Hz
//
// ##### References
// See `sawN` above.
//
// #### Implementation Notes
//
// Presently, only `saw2` uses the PTR method, while `saw3` and `saw4` use DPW.
// This is because PTR has been implemented and tested for the 2nd-order case only.
//
//------------------------------------------------------------------
saw2 = saw2ptr; // "faustlibraries choice"
saw3 = sawN(3); // only choice available right now
saw4 = sawN(4); // only choice available right now

//---------------------------`(os.)saw2ptr`---------------------------
// Alias-Suppressed Sawtooth Audio-Frequency Oscillator
// using Polynomial Transition Regions (PTR) for order 2.
//
// #### Usage
//
// ```
// saw2ptr(freq) : _
// ```
//
// where
//
// * `freq`: frequency in Hz
//
// ##### Implementation
//
// Polynomial Transition Regions (PTR) method for aliasing suppression.
//
// ##### References
//
// * Kleimola, J.; Valimaki, V., "Reducing Aliasing from Synthetic Audio
//     Signals Using Polynomial Transition Regions," in Signal Processing
//     Letters, IEEE , vol.19, no.2, pp.67-70, Feb. 2012
// * <https://aaltodoc.aalto.fi/bitstream/handle/123456789/7747/publication6.pdf?sequence=9>
// * <http://research.spa.aalto.fi/publications/papers/spl-ptr/>
//
// ##### Notes
//
// Method PTR may be preferred because it requires less
// computation and is stateless which means that the frequency `freq`
// can be modulated arbitrarily fast over time without filtering
// artifacts.  For this reason, `saw2` is presently defined as `saw2ptr`.
//
//--------------------------------------------------------
declare saw2ptr author "Julius O. Smith III";
declare saw2ptr license "STK-4.3";
// specialized reimplementation:
saw2ptr(freq) = y with { // newer PTR version (stateless - freq can vary at any speed)
  p0 = float(ma.SR)/float(max(ma.EPSILON,abs(freq))); // period in samples
  t0 = 1.0/p0; // phase increment
  p = ((_<:(-(1)<:_,_),_) <: selector1,selector2) ~(+(t0)):!,_;
  selector1 = select2(<(0)); // for feedback
  selector2 = select2(<(0), (_<:_,(*(1-p0):+(1)):+), _); // for output
  y = 2*p-1;
};

//----------------------`(os.)saw2dpw`---------------------
// Alias-Suppressed Sawtooth Audio-Frequency Oscillator
// using the Differentiated Polynomial Waveform (DWP) method.
//
// #### Usage
//
// ```
// saw2dpw(freq) : _
// ```
//
// where
//
// * `freq`: frequency in Hz
//
// This is the original Faust `saw2` function using the DPW method.
// Since `saw2` is now defined as `saw2ptr`, the DPW version
// is now available as `saw2dwp`.
//--------------------------------------------------------
declare saw2dpw author "Julius O. Smith III";
declare saw2dpw license "STK-4.3";
saw2dpw(freq) = saw1(freq) <: * <: -(mem) : *(0.25'*ma.SR/freq);

//------------------`(os.)sawtooth`--------------------------------
// Alias-suppressed aliasing-suppressed sawtooth oscillator, presently defined as `saw2`.
// `sawtooth` is a standard Faust function.
//
// #### Usage
//
// ```
// sawtooth(freq) : _
// ```
//
// with
//
// * `freq`: frequency in Hz
//--------------------------------------------------------
sawtooth = saw2; // default choice for sawtooth signal - see also sawN

//------------------`(os.)saw2f2, (os.)saw2f4`--------------------------------
// Alias-Suppressed Sawtooth Audio-Frequency Oscillator with Order 2 or 4 Droop Correction Filtering.
//
// #### Usage
//
// ```
// saw2f2(freq) : _
// saw2f4(freq) : _
// ```
//
// with
//
// * `freq`: frequency in Hz
//
// In return for aliasing suppression, there is some attenuation near half the sampling rate.
// This can be considered as beneficial, or it can be compensated with a high-frequency boost.
// The boost filter is second-order for `saw2f2` and fourth-order for `saw2f4`, and both are designed
// for the DWP case and therefore use `saw2dpw`.
// See Figure 4(b) in the DPW reference for a plot of the slight droop in the DPW case.
//--------------------------------------------------------
declare saw2f2 author "Julius O. Smith III";
declare saw2f2 license "STK-4.3";
// --- Correction-filtered versions of saw2: saw2f2, saw2f4 -----
saw2f2 = saw2dpw : cf2 with {
  cf2 = fi.tf2(1.155704605878911, 0.745184288225518,0.040305967265900,
        0.823765146386639, 0.117420665547108);
};
declare saw2f4 author "Julius O. Smith III";
declare saw2f4 license "STK-4.3";
saw2f4 = saw2dpw : cf4 with {
  cf4 = fi.iir((1.155727435125014, 2.285861038554662,
        1.430915027294021, 0.290713280893317, 0.008306401748854),
        (2.156834679164532, 1.559532244409321, 0.423036498118354,
        0.032080681130972));
};

//=========Alias-Suppressed Pulse, Square, and Impulse Trains============
// Alias-Suppressed Pulse, Square and Impulse Trains.
//
// `pulsetrainN`, `pulsetrain`, `squareN`, `square`, `imptrainN`, `imptrain`,
// `triangleN`, `triangle`
//
// All are zero-mean and meant to oscillate in the audio frequency range.
// Use simpler sample-rounded `lf_*` versions above for LFOs.
//
// #### Usage
//
// ```
// pulsetrainN(N,freq,duty) : _
// pulsetrain(freq, duty) : _ // = pulsetrainN(2)
//
// squareN(N,freq) : _
// square : _ // = squareN(2)
//
// imptrainN(N,freq) : _
// imptrain : _ // = imptrainN(2)
//
// triangleN(N,freq) : _
// triangle : _ // = triangleN(2)
// ```
//
// Where:
//
// * `N`: polynomial order, a constant numerical expression
// * `freq`: frequency in Hz
//====================================================================


//------------------`(os.)impulse`--------------------------------
// One-time impulse generated when the Faust process is started.
// `impulse` is a standard Faust function.
//
// #### Usage
//
// ```
// impulse : _
// ```
//--------------------------------------------------------
impulse = 1-1';


//------------------`(os.)pulsetrainN`--------------------------------
// Alias-suppressed pulse train oscillator.
//
// #### Usage
//
// ```
// pulsetrainN(N,freq,duty) : _
// ```
//
// Where:
//
// * `N`: order, as a constant numerical expression
// * `freq`: frequency in Hz
// * `duty`: duty cycle between 0 and 1

//--------------------------------------------------------
pulsetrainN(N,freq,duty) = diffdel(sawN(N,freqC),del) with {
 // non-interpolated-delay version: diffdel(x,del) = x - x@int(del+0.5);
 // linearly interpolated delay version (sounds good to me):
    diffdel(x,del) = x-x@int(del)*(1-ma.frac(del))-x@(int(del)+1)*ma.frac(del);
 // Third-order Lagrange interpolated-delay version (see filters.lib):
 // diffdel(x,del) = x - fdelay3(DELPWR2,max(1,min(DELPWR2-2,ddel)));
 DELPWR2 = 2048; // Needs to be a power of 2 when fdelay*() used above.
 delmax = DELPWR2-1; // arbitrary upper limit on diff delay (duty=0.5)
 SRmax = 96000.0; // assumed upper limit on sampling rate
 fmin = SRmax / float(2.0*delmax); // 23.4 Hz (audio freqs only)
 freqC = max(freq,fmin); // clip frequency at lower limit
 period = (float(ma.SR) / freqC); // actual period
 ddel = duty * period; // desired delay
 del = max(0,min(delmax,ddel));
};


//------------------`(os.)pulsetrain`--------------------------------
// Alias-suppressed pulse train oscillator. Based on `pulsetrainN(2)`.
// `pulsetrain` is a standard Faust function.
//
// #### Usage
//
// ```
// pulsetrain(freq,duty) : _
// ```
//
// Where:
//
// * `freq`: frequency in Hz
// * `duty`: duty cycle between 0 and 1
//--------------------------------------------------------
pulsetrain = pulsetrainN(2);


//------------------`(os.)squareN`--------------------------------
// Alias-suppressed square wave oscillator.
//
// #### Usage
//
// ```
// squareN(N,freq) : _
// ```
//
// Where:
//
// * `N`: order, as a constant numerical expression
// * `freq`: frequency in Hz
//--------------------------------------------------------
squareN(N,freq) = pulsetrainN(N,freq,0.5);


//------------------`(os.)square`--------------------------------
// Alias-suppressed square wave oscillator. Based on `squareN(2)`.
// `square` is a standard Faust function.
//
// #### Usage
//
// ```
// square(freq) : _
// ```
//
// Where:
//
// * `freq`: frequency in Hz
//--------------------------------------------------------
square = squareN(2);


//------------------`(os.)imptrainN`--------------------------------
// Alias-suppressed impulse train generator.
//
// #### Usage
//
// ```
// imptrainN(N,freq) : _
// ```
//
// Where:
//
// * `N`: order, as a constant numerical expression
// * `freq`: frequency in Hz
//--------------------------------------------------------
imptrainN(N,freq) = impulse + 0.5*ma.diffn(sawN(N,freq));


//------------------`(os.)imptrain`--------------------------------
// Alias-suppressed impulse train generator. Based on `imptrainN(2)`.
// `imptrain` is a standard Faust function.
//
// #### Usage
//
// ```
// imptrain(freq) : _
// ```
//
// Where:
//
// * `freq`: frequency in Hz
//--------------------------------------------------------
imptrain = imptrainN(2); // default based on saw2


//------------------`(os.)triangleN`--------------------------------
// Alias-suppressed triangle wave oscillator.
//
// #### Usage
//
// ```
// triangleN(N,freq) : _
// ```
//
// Where:
//
// * `N`: order, as a constant numerical expression
// * `freq`: frequency in Hz
//--------------------------------------------------------
triangleN(N,freq) = squareN(N,freq) : fi.pole(p) : *(gain) with {
  gain = 4.0*freq/ma.SR; // for aproximate unit peak amplitude
  p = 0.999;
};


//------------------`(os.)triangle`--------------------------------
// Alias-suppressed triangle wave oscillator. Based on `triangleN(2)`.
// `triangle` is a standard Faust function.
//
// #### Usage
//
// ```
// triangle(freq) : _
// ```
//
// Where:
//
// * `freq`: frequency in Hz
//--------------------------------------------------------
triangle = triangleN(2); // default based on saw2


//===============================Filter-Based Oscillators=================================
// Filter-Based Oscillators.
//
// #### Usage
//
// ```
// osc[b|rq|rs|rc|s](freq), where freq = frequency in Hz.
// ```
//
// #### References
//
// * <http://lac.linuxaudio.org/2012/download/lac12-slides-jos.pdf>
// * <https://ccrma.stanford.edu/~jos/pdf/lac12-paper-jos.pdf>
//========================================================================================

//--------------------------`(os.)oscb`--------------------------------
// Sinusoidal oscillator based on the biquad.
//
// #### Usage
//
// ```
// oscb(freq) : _
// ```
//
// Where:
//
// * `freq`: frequency in Hz
//------------------------------------------------------------
oscb(f) = impulse : fi.tf2(1,0,0,a1,1)
with {
  a1 = -2*cos(2*ma.PI*f/ma.SR);
};


//--------------------------`(os.)oscrq`---------------------------
// Sinusoidal (sine and cosine) oscillator based on 2D vector rotation,
//  = undamped "coupled-form" resonator
//  = lossless 2nd-order normalized ladder filter.
//
// #### Usage
//
// ```
// oscrq(freq) : _,_
// ```
//
// Where:
//
// * `freq`: frequency in Hz
//
// #### Reference
//
// * <https://ccrma.stanford.edu/~jos/pasp/Normalized_Scattering_Junctions.html>
//------------------------------------------------------------
oscrq(f) = impulse : fi.nlf2(f,1); // sine and cosine outputs

//--------------------------`(os.)oscrs`---------------------------
// Sinusoidal (sine) oscillator based on 2D vector rotation,
//  = undamped "coupled-form" resonator
//  = lossless 2nd-order normalized ladder filter.
//
// #### Usage
//
// ```
// oscrs(freq) : _
// ```
//
// Where:
//
// * `freq`: frequency in Hz
//
// #### Reference
//
// * <https://ccrma.stanford.edu/~jos/pasp/Normalized_Scattering_Junctions.html>
//------------------------------------------------------------
oscrs(f) = impulse : fi.nlf2(f,1) : _,!; // sine

//--------------------------`(os.)oscrc`---------------------------
// Sinusoidal (cosine) oscillator based on 2D vector rotation,
//  = undamped "coupled-form" resonator
//  = lossless 2nd-order normalized ladder filter.
//
// #### Usage
//
// ```
// oscrc(freq) : _
// ```
//
// Where:
//
// * `freq`: frequency in Hz
//
// #### Reference
//
// * <https://ccrma.stanford.edu/~jos/pasp/Normalized_Scattering_Junctions.html>
//------------------------------------------------------------
oscrc(f) = impulse : fi.nlf2(f,1) : !,_; // cosine

oscrp(f,p) = oscrq(f) : *(cos(p)), *(sin(p)) : + ; // p=0 for sine, p=PI/2 for cosine, etc.

oscr = oscrs; // default = sine (starts without a pop)

//--------------------------`(os.)oscs`--------------------------------
// Sinusoidal oscillator based on the state variable filter
// = undamped "modified-coupled-form" resonator
// = "magic circle" algorithm used in graphics.
//
// #### Usage
//
// ```
// oscs(freq) : _
// ```
//
// Where:
//
// * `freq`: frequency in Hz
//------------------------------------------------------------
oscs(f) = (*(-1) : sint(wn) : sintp(wn,impulse)) ~ _
with {
  wn = 2*ma.PI*f/ma.SR; // approximate
  // wn = 2*sin(PI*f/SR); // exact
  sint(x) = *(x) : + ~ _ ; // frequency-scaled integrator
  sintp(x,y) = *(x) : +(y): + ~ _; // same + state input
};

//-----------------`(os.)quadosc`--------------------
// Quadrature (cosine and sine) oscillator based on QuadOsc by Martin Vicanek.
//
// #### Usage
//
// ```
// quadosc(freq) : _,_
// ```
//
// where
//
// * `freq`: frequency in Hz
//
// #### Reference
// * <https://vicanek.de/articles/QuadOsc.pdf>
//------------------------------------------------------------
// Authors:
// Dario Sanfilippo <sanfilippo.dario@gmail.com>
// and Oleg Nesterov (JOS ed.)
quadosc(f) = tick ~ (_,_)
with {
    k1 = tan(f * ma.PI / ma.SR);
    k2 = 2 * k1 / (1 + k1 * k1);
    tick(u_0,v_0) = u_1,v_1
    with {
        tmp = u_0 - k1 * v_0;
        v_1 = v_0 + k2 * tmp;
        u_1 = tmp - k1 * v_1 : select2(1',1);
    };
};

//-----------------------------`(os.)sidebands`--------------------------------------
// Adds harmonics to quad oscillator.
//
// #### Usage
//
// ```
//    cos(x),sin(x) : sidebands(vs) : _,_
// ```
//
// Where:
//
// * `vs` : list of amplitudes
//
// #### Example test program
//
// ```
//    cos(x),sin(x) : sidebands((10,20,30))
// ```
//
// outputs:
//
// ```
//    10*cos(x) + 20*cos(2*x) + 30*cos(3*x),
//    10*sin(x) + 20*sin(2*x) + 30*sin(3*x);
// ```
//
// The following:
//
// ```
//    process = os.quadosc(F) : sidebands((10,20,30))
// ```
//
// is (modulo floating point issues) the same as:
//
// ```
//    c = os.quadosc : _,!;
//    s = os.quadosc : !,_;
//    process =
//        10*c(F) + 20*c(2*F) + 30*c(F),
//        10*s(F) + 20*s(2*F) + 30*s(F);
// ```
//
// but much more efficient.
//
// #### Implementation Notes
//
// This is based on the trivial trigonometric identities:
//
// ```
//    cos((n + 1) x) = 2 cos(x) cos(n x) - cos((n - 1) x)
//    sin((n + 1) x) = 2 cos(x) sin(n x) - sin((n - 1) x)
// ```
//
// Note that the calculation of the cosine/sine parts do not depend
// on each other, so if you only need the sine part you can do:
//
// ```
//    process = os.quadosc(F) : sidebands(vs) : !,_;
// ```
//
// and the compiler will discard the half of the calculations.
//-----------------------------------------------------------------------------
sidebands(vs, c0,s0)
	= c0*vn(0),s0*vn(0), 1,c0, 0,s0
	: seq(n, outputs(vs)-1, add(vn(n+1)))
	: _,_, !,!, !,!
with {
	// ba.take(n+1, vs)
	vn(n) = vs : route(outputs(vs),1, n+1,1);

	add(vn, co,so, cn_2,cn_1, sn_2,sn_1) =
		co+cn*vn, so+sn*vn, cn_1,cn, sn_1,sn
	with {
		cn = 2*c0*cn_1 - cn_2;
		sn = 2*c0*sn_1 - sn_2;
	};
};

//-----------------------------`(os.)sidebands_list`--------------------------------------
// Creates the list of complex harmonics from quad oscillator.
//
// Similar to `sidebands` but doesn't sum the harmonics, so it is more
// generic but less convenient for immediate usage.
//
// #### Usage
//
// ```
//    cos(x),sin(x) : sidebands_list(N) : si.bus(2*N)
// ```
//
// Where:
//
// * `N` : number of harmonics, compile time constant > 1
//
// #### Example test program
//
// ```
//    cos(x),sin(x) : sidebands_list(3)
// ```
//
// outputs:
//
// ```
//    cos(x),sin(x), cos(2*x),sin(2*x), cos(3*x),sin(3*x);
// ```
//
// The following:
//
// ```
//    process = os.quadosc(F) : sidebands_list(3)
// ```
//
// is (modulo floating point issues) the same as:
//
// ```
//    process = os.quadosc(F), os.quadosc(2*F), os.quadosc(3*F);
// ```
//
// but much more efficient.
//-----------------------------------------------------------------------------
sidebands_list(N, c0,s0)
	= c0,s0, 1,c0, 0,s0
	: seq(n, N-1, si.bus(2*(n+1)), add)
	: si.bus(2*N), !,!, !,!
with {
	add(cn_2,cn_1, sn_2,sn_1) =
		cn,sn, cn_1,cn, sn_1,sn
	with {
		cn = 2*c0*cn_1 - cn_2;
		sn = 2*c0*sn_1 - sn_2;
	};
};

//------------------------------`(os.)dsf`--------------------------------
// An environment with sine/cosine oscsillators with exponentially decaying
// harmonics based on direct summation formula.
//
// #### Usage
//
// ```
// dsf.xxx(f0, df, a, [n]) : _
// ```
//
// Where:
//
// * `f0`: base frequency
// * `df`: step frequency
// * `a`: decaying factor != 1
// * `n`: total number of harmonics (`osccN/oscsN` only)
//
// #### Variants
//
// - infinite number of harmonics, implies aliasing
// ```
// oscc(f0,df,a) : _;
// oscs(f0,df,a) : _;
// ```
//
// - n harmonics, f0, f0 + df, f0 + 2\*df, ..., f0 + (n-1)\*df
// ```
// osccN(f0,df,a,n) : _;
// oscsN(f0,df,a,n) : _;
// ```
//
// - finite number of harmonics, from f0 to Nyquist
// ```
// osccNq(f0,df,a) : _;
// oscsNq(f0,df,a) : _;
// ```
// 
// #### Example test program
//
// ```
// process = dsf.osccN(F0,DF,A,N),
//           dsf.oscsN(F0,DF,A,N);
// ```
// if `N` is an integer constant, the same (modulo fp issues) as:
// ```
// c = os.quadosc : _,!;
// s = os.quadosc : !,_;
// process = sum(k,N, A^k * c(F0 + k*DF)),
//           sum(k,N, A^k * s(F0 + k*DF));
// ```
// but much more efficient.
//
// #### Reference
//
// * <https://ccrma.stanford.edu/STANM/stanms/stanm5/stanm5.pdf>
//
declare dsf author "Oleg Nesterov";
dsf = environment {
	qo = quadosc;
	co = qo : _,!;
	so = qo : !,_;

	Nq(f0,df) = (ma.SR/2 - f0) / df : int;

	// infinite number of harmonics, implies aliasing
	oscc(f0,df,a) = (co(f0) - a*co(f0-df)) / (1 + a^2 - 2*a*co(df));
	oscs(f0,df,a) = (so(f0) - a*so(f0-df)) / (1 + a^2 - 2*a*co(df));

	// n harmonics, f0, f0 + df, f0 + 2*df, ..., f0 + (n-1)*df
	osccN(f0,df,a,n) = oscc(f0,df,a) - a^n * oscc(f0 + n*df, df,a);
	oscsN(f0,df,a,n) = oscs(f0,df,a) - a^n * oscs(f0 + n*df, df,a);

	// finite number of harmonics, from f0 to Nyquist
	osccNq(f0,df,a) = osccN(f0,df,a, Nq(f0,df));
	oscsNq(f0,df,a) = oscsN(f0,df,a, Nq(f0,df));
};

//================ Waveguide-Resonator-Based Oscillators ================
// Sinusoidal oscillator based on the waveguide resonator `wgr`.
//=======================================================================

//-----------------`(os.)oscwc`--------------------
// Sinusoidal oscillator based on the waveguide resonator `wgr`. Unit-amplitude
// cosine oscillator.
//
// #### Usage
//
// ```
// oscwc(freq) : _
// ```
//
// Where:
//
// * `freq`: frequency in Hz
//
// #### Reference
//
// * <https://ccrma.stanford.edu/~jos/pasp/Digital_Waveguide_Oscillator.html>
//------------------------------------------------------------
oscwc(fr) = impulse : fi.wgr(fr,1) : _,!; // cosine (cheapest at 1 mpy/sample)

//-----------------`(os.)oscws`--------------------
// Sinusoidal oscillator based on the waveguide resonator `wgr`. Unit-amplitude
// sine oscillator.
//
// #### Usage
//
// ```
// oscws(freq) : _
// ```
//
// Where:
//
// * `freq`: frequency in Hz
//
// #### Reference
//
// * <https://ccrma.stanford.edu/~jos/pasp/Digital_Waveguide_Oscillator.html>
//------------------------------------------------------------
oscws(fr) = impulse : fi.wgr(fr,1) : !,_; // sine (needs a 2nd scaling mpy)

//-----------------`(os.)oscq`--------------------
// Sinusoidal oscillator based on the waveguide resonator `wgr`.
// Unit-amplitude cosine and sine (quadrature) oscillator.
//
// #### Usage
//
// ```
// oscq(freq) : _,_
// ```
//
// Where:
//
// * `freq`: frequency in Hz
//
// #### Reference
//
// * <https://ccrma.stanford.edu/~jos/pasp/Digital_Waveguide_Oscillator.html>
//------------------------------------------------------------
oscq(fr) = impulse : fi.wgr(fr,1);       // phase quadrature outputs

//-----------------`(os.)oscw`--------------------
// Sinusoidal oscillator based on the waveguide resonator `wgr`.
// Unit-amplitude cosine oscillator (default).
//
// #### Usage
//
// ```
// oscw(freq) : _
// ```
//
// Where:
//
// * `freq`: frequency in Hz
//
// #### Reference
//
// * <https://ccrma.stanford.edu/~jos/pasp/Digital_Waveguide_Oscillator.html>
//------------------------------------------------------------
oscw = oscwc;

// end jos section
//########################################################################################
/************************************************************************
FAUST library file, further contributions section

All contributions below should indicate both the contributor and terms
of license.  If no such indication is found, "git blame" will say who
last edited each line, and that person can be emailed to inquire about
license disposition, if their license choice is not already indicated
elsewhere among the libraries.  It is expected that all software will be
released under LGPL, STK-4.3, MIT, BSD, or a similar FOSS license.
************************************************************************/

//===================== Casio CZ Oscillators ==========================
// Oscillators that mimic some of the Casio CZ oscillators.
//
// There are two sets:
//
// * a set with an index parameter
//
// * a set with a res parameter
//
// The "index oscillators" outputs a sine wave at index=0 and gets brighter with a higher index.
// There are two versions of the "index oscillators":
//
// * with P appended to the name: is phase aligned with `fund:sin`
//
// * without P appended to the name: has the phase of the original CZ oscillators
//
// The "res oscillators" have a resonant frequency.
// "res" is the frequency of resonance as a factor of the fundamental pitch.
//
// For the `fund` waveform, use a low-frequency oscillator without anti-aliasing such as `os.lf_saw`.
//=====================================================================

//----------`(os.)CZsaw`----------
// Oscillator that mimics the Casio CZ saw oscillator.
// `CZsaw` is a standard Faust function.
//
// #### Usage
//
// ```
// CZsaw(fund,index) : _
// ```
//
// Where:
//
// * `fund`: a saw-tooth waveform between 0 and 1 that the oscillator slaves to
// * `index`: the brightness of the oscillator, 0 to 1. 0 = sine-wave, 1 = saw-wave
//------------------------------------------------------------
declare CZsaw author "Bart Brouns";
declare CZsaw licence "STK-4.3";

// CZ oscillators by Mike Moser-Booth:
// <https://forum.pdpatchrepo.info/topic/5992/casio-cz-oscillators>
// Ported from pd to Faust by Bart Brouns

CZsaw(fund, index) = CZ.sawChooseP(fund, index, 0);

//----------`(os.)CZsawP`----------
// Oscillator that mimics the Casio CZ saw oscillator,
// with it's phase aligned to `fund:sin`.
// `CZsawP` is a standard Faust function.
//
// #### Usage
//
// ```
// CZsawP(fund,index) : _
// ```
//
// Where:
//
// * `fund`: a saw-tooth waveform between 0 and 1 that the oscillator slaves to
// * `index`: the brightness of the oscillator, 0 to 1. 0 = sine-wave, 1 = saw-wave
//------------------------------------------------------------
declare CZsawP author "Bart Brouns";
declare CZsawP licence "STK-4.3";

// CZ oscillators by Mike Moser-Booth:
// <https://forum.pdpatchrepo.info/topic/5992/casio-cz-oscillators>
// Ported from pd to Faust by Bart Brouns

CZsawP(fund, index) = CZ.sawChooseP(fund, index, 1);

//----------`(os.)CZsquare`----------
// Oscillator that mimics the Casio CZ square oscillator
// `CZsquare` is a standard Faust function.
//
// #### Usage
//
// ```
// CZsquare(fund,index) : _
// ```
//
// Where:
//
// * `fund`: a saw-tooth waveform between 0 and 1 that the oscillator slaves to
// * `index`: the brightness of the oscillator, 0 to 1. 0 = sine-wave, 1 = square-wave
//------------------------------------------------------------
declare CZsquare author "Bart Brouns";
declare CZsquare licence "STK-4.3";

// CZ oscillators by Mike Moser-Booth:
// <https://forum.pdpatchrepo.info/topic/5992/casio-cz-oscillators>
// Ported from pd to Faust by Bart Brouns

CZsquare(fund, index) = CZ.squareChooseP(fund, index, 0);

//----------`(os.)CZsquareP`----------
// Oscillator that mimics the Casio CZ square oscillator,
// with it's phase aligned to `fund:sin`.
// `CZsquareP` is a standard Faust function.
//
// #### Usage
//
// ```
// CZsquareP(fund,index) : _
// ```
//
// Where:
//
// * `fund`: a saw-tooth waveform between 0 and 1 that the oscillator slaves to
// * `index`: the brightness of the oscillator, 0 to 1. 0 = sine-wave, 1 = square-wave
//------------------------------------------------------------
declare CZsquareP author "Bart Brouns";
declare CZsquareP licence "STK-4.3";

// CZ oscillators by Mike Moser-Booth:
// <https://forum.pdpatchrepo.info/topic/5992/casio-cz-oscillators>
// Ported from pd to Faust by Bart Brouns

CZsquareP(fund, index) = CZ.squareChooseP(fund, index, 1);

//----------`(os.)CZpulse`----------
// Oscillator that mimics the Casio CZ pulse oscillator.
// `CZpulse` is a standard Faust function.
//
// #### Usage
//
// ```
// CZpulse(fund,index) : _
// ```
//
// Where:
//
// * `fund`: a saw-tooth waveform between 0 and 1 that the oscillator slaves to
// * `index`: the brightness of the oscillator, 0 gives a sine-wave, 1 is closer to a pulse
//------------------------------------------------------------
declare CZpulse author "Bart Brouns";
declare CZpulse licence "STK-4.3";

// CZ oscillators by Mike Moser-Booth:
// <https://forum.pdpatchrepo.info/topic/5992/casio-cz-oscillators>
// Ported from pd to Faust by Bart Brouns

CZpulse(fund, index) = CZ.pulseChooseP(fund, index, 0);

//----------`(os.)CZpulseP`----------
// Oscillator that mimics the Casio CZ pulse oscillator,
// with it's phase aligned to `fund:sin`.
// `CZpulseP` is a standard Faust function.
//
// #### Usage
//
// ```
// CZpulseP(fund,index) : _
// ```
//
// Where:
//
// * `fund`: a saw-tooth waveform between 0 and 1 that the oscillator slaves to
// * `index`: the brightness of the oscillator, 0 gives a sine-wave, 1 is closer to a pulse
//------------------------------------------------------------
declare CZpulseP author "Bart Brouns";
declare CZpulseP licence "STK-4.3";

// CZ oscillators by Mike Moser-Booth:
// <https://forum.pdpatchrepo.info/topic/5992/casio-cz-oscillators>
// Ported from pd to Faust by Bart Brouns

CZpulseP(fund, index) = CZ.pulseChooseP(fund, index, 1);

//----------`(os.)CZsinePulse`----------
// Oscillator that mimics the Casio CZ sine/pulse oscillator.
// `CZsinePulse` is a standard Faust function.
//
// #### Usage
//
// ```
// CZsinePulse(fund,index) : _
// ```
//
// Where:
//
// * `fund`: a saw-tooth waveform between 0 and 1 that the oscillator slaves to
// * `index`: the brightness of the oscillator, 0 gives a sine-wave, 1 is a sine minus a pulse
//------------------------------------------------------------
declare CZsinePulse author "Bart Brouns";
declare CZsinePulse licence "STK-4.3";

// CZ oscillators by Mike Moser-Booth:
// <https://forum.pdpatchrepo.info/topic/5992/casio-cz-oscillators>
// Ported from pd to Faust by Bart Brouns

CZsinePulse(fund, index) = CZ.sinePulseChooseP(fund, index, 0);

//----------`(os.)CZsinePulseP`----------
// Oscillator that mimics the Casio CZ sine/pulse oscillator,
// with it's phase aligned to `fund:sin`.
// `CZsinePulseP` is a standard Faust function.
//
// #### Usage
//
// ```
// CZsinePulseP(fund,index) : _
// ```
//
// Where:
//
// * `fund`: a saw-tooth waveform between 0 and 1 that the oscillator slaves to
// * `index`: the brightness of the oscillator, 0 gives a sine-wave, 1 is a sine minus a pulse
//------------------------------------------------------------
declare CZsinePulseP author "Bart Brouns";
declare CZsinePulseP licence "STK-4.3";

// CZ oscillators by Mike Moser-Booth:
// <https://forum.pdpatchrepo.info/topic/5992/casio-cz-oscillators>
// Ported from pd to Faust by Bart Brouns

CZsinePulseP(fund, index) = CZ.sinePulseChooseP(fund, index, 1);

//----------`(os.)CZhalfSine`----------
// Oscillator that mimics the Casio CZ half sine oscillator.
// `CZhalfSine` is a standard Faust function.
//
// #### Usage
//
// ```
// CZhalfSine(fund,index) : _
// ```
//
// Where:
//
// * `fund`: a saw-tooth waveform between 0 and 1 that the oscillator slaves to
// * `index`: the brightness of the oscillator, 0 gives a sine-wave, 1 is somewhere between a saw and a square
//------------------------------------------------------------
declare CZhalfSine author "Bart Brouns";
declare CZhalfSine licence "STK-4.3";

// CZ oscillators by Mike Moser-Booth:
// <https://forum.pdpatchrepo.info/topic/5992/casio-cz-oscillators>
// Ported from pd to Faust by Bart Brouns

CZhalfSine(fund, index) = CZ.halfSineChooseP(fund, index, 0);

//----------`(os.)CZhalfSineP`----------
// Oscillator that mimics the Casio CZ half sine oscillator,
// with it's phase aligned to `fund:sin`.
// `CZhalfSineP` is a standard Faust function.
//
// #### Usage
//
// ```
// CZhalfSineP(fund,index) : _
// ```
//
// Where:
//
// * `fund`: a saw-tooth waveform between 0 and 1 that the oscillator slaves to
// * `index`: the brightness of the oscillator, 0 gives a sine-wave, 1 is somewhere between a saw and a square
//------------------------------------------------------------
declare CZhalfSineP author "Bart Brouns";
declare CZhalfSineP licence "STK-4.3";

// CZ oscillators by Mike Moser-Booth:
// <https://forum.pdpatchrepo.info/topic/5992/casio-cz-oscillators>
// Ported from pd to Faust by Bart Brouns

CZhalfSineP(fund, index) = CZ.halfSineChooseP(fund, index, 1);

//----------`(os.)CZresSaw`----------
// Oscillator that mimics the Casio CZ resonant sawtooth oscillator.
// `CZresSaw` is a standard Faust function.
//
// #### Usage
//
// ```
// CZresSaw(fund,res) : _
// ```
//
// Where:
//
// * `fund`: a saw-tooth waveform between 0 and 1 that the oscillator slaves to
// * `res`: the frequency of resonance as a factor of the fundamental pitch.
//------------------------------------------------------------
declare CZresSaw author "Bart Brouns";
declare CZresSaw licence "STK-4.3";

// CZ oscillators by Mike Moser-Booth:
// <https://forum.pdpatchrepo.info/topic/5992/casio-cz-oscillators>
// Ported from pd to Faust by Bart Brouns

CZresSaw(fund,res) = CZ.resSaw(fund,res);

//----------`(os.)CZresTriangle`----------
// Oscillator that mimics the Casio CZ resonant triangle oscillator.
// `CZresTriangle` is a standard Faust function.
//
// #### Usage
//
// ```
// CZresTriangle(fund,res) : _
// ```
//
// Where:
//
// * `fund`: a saw-tooth waveform between 0 and 1 that the oscillator slaves to
// * `res`: the frequency of resonance as a factor of the fundamental pitch.
//------------------------------------------------------------
declare CZresTriangle author "Bart Brouns";
declare CZresTriangle licence "STK-4.3";

// CZ oscillators by Mike Moser-Booth:
// <https://forum.pdpatchrepo.info/topic/5992/casio-cz-oscillators>
// Ported from pd to Faust by Bart Brouns

CZresTriangle(fund,res) = CZ.resTriangle(fund,res);

//----------`(os.)CZresTrap`----------
// Oscillator that mimics the Casio CZ resonant trapeze oscillator
// `CZresTrap` is a standard Faust function.
//
// #### Usage
//
// ```
// CZresTrap(fund,res) : _
// ```
//
// Where:
//
// * `fund`: a saw-tooth waveform between 0 and 1 that the oscillator slaves to
// * `res`: the frequency of resonance as a factor of the fundamental pitch.
//------------------------------------------------------------
declare CZresTrap author "Bart Brouns";
declare CZresTrap licence "STK-4.3";

// CZ oscillators by Mike Moser-Booth:
// <https://forum.pdpatchrepo.info/topic/5992/casio-cz-oscillators>
// Ported from pd to Faust by Bart Brouns

CZresTrap(fund, res) = CZ.resTrap(fund, res);

CZ = environment {

    saw(fund, index) = sawChooseP(fund, index, 0);
    sawP(fund, index) = sawChooseP(fund, index, 1);
    sawChooseP(fund, index, p) =
      (((FUND(fund,align,p)*((.5-INDEX)/INDEX)),(-1*FUND(fund,align,p)+1)*((.5-INDEX)/(1-INDEX))):min+FUND(fund,align,p))*2*ma.PI:cos
    with {
      INDEX = (.5-(index*.5)):max(0.01):min(0.5);
      align = si.interpolate(index, 0.75, 0.5);
    };

    square(fund, index) = squareChooseP(fund, index, 0);
    squareP(fund, index) = squareChooseP(fund, index, 1);
    squareChooseP(fund, index, p) = (FUND(fund,align,p)>=0.5), (ma.decimal((FUND(fund,align,p)*2)+1)<:_-min(_,(-1*_+1)*((INDEX)/(1-INDEX)))) :+ *ma.PI:cos
    with {
      INDEX = (index:pow(0.25)):max(0):min(1);
      align = si.interpolate(INDEX, -0.25, 0);
    };

    pulse(fund, index) = pulseChooseP(fund, index, 0);
    pulseP(fund, index) = pulseChooseP(fund, index, 1);
    pulseChooseP(fund, index, p) = ((FUND(fund,align,p)-min(FUND(fund,align,p),((-1*FUND(fund,align,p)+1)*(INDEX/(1-INDEX)))))*2*ma.PI):cos
    with {
      INDEX = index:min(0.99):max(0);
      align = si.interpolate(index, -0.25, 0.0);
    };

    sinePulse(fund, index) = sinePulseChooseP(fund, index, 0);
    sinePulseP(fund, index) = sinePulseChooseP(fund, index, 1);
    sinePulseChooseP(fund, index, p) = (min(FUND(fund,align,p)*((0.5-INDEX)/INDEX),(-1*FUND(fund,align,p)+1)*((.5-INDEX)/(1-INDEX)))+FUND(fund,align,p))*4*ma.PI:cos
    with {
      INDEX = ((index*-0.49)+0.5);
      align = si.interpolate(index, -0.125, -0.25);
    };

    halfSine(fund, index) = halfSineChooseP(fund, index, 0);
    halfSineP(fund, index) = halfSineChooseP(fund, index, 1);
    halfSineChooseP(fund, index, p) = (select2(FUND(fund,align,p)<.5, .5*(FUND(fund,align,p)-.5)/INDEX+.5, FUND(fund,align,p)):min(1))*2*ma.PI:cos
    with {
      INDEX = (.5-(index*0.5)):min(.5):max(.01);
      align = si.interpolate(index:min(0.975), -0.25, -0.5);
    };

    FUND =
      case {
        (fund,align,0) => fund;
        (fund,align,1) => (fund+align) : ma.frac; // align phase with fund
      };
    resSaw(fund,res) = (((-1*(1-fund))*((cos((ma.decimal((max(1,res)*fund)+1))*2*ma.PI)*-.5)+.5))*2)+1;
    resTriangle(fund,res) = select2(fund<.5, 2-(fund*2), fund*2)*INDEX*2-1
    with {
      INDEX = ((fund*(res:max(1)))+1:ma.decimal)*2*ma.PI:cos*.5+.5;
    };
    resTrap(fund, res) = (((1-fund)*2):min(1)*sin(ma.decimal(fund*(res:max(1)))*2*ma.PI));
};

//===============================PolyBLEP-Based Oscillators=================================

//----------`(os.)polyblep`----------
// PolyBLEP residual function, used for smoothing steps in the audio signal.
//
// #### Usage
//
// ```
// polyblep(Q,phase) : _
// ```
//
// Where:
//
// * `Q`: smoothing factor between 0 and 0.5. Determines how far from the ends of the phase interval the quadratic function is used.
// * `phase`: normalised phase (between 0 and 1)
//------------------------------------------------------------
declare polyblep author "Jacek Wieczorek";

polyblep(Q, phase) = (0, L(phase / Q), R((phase - 1) / Q)) : select3(sel)
with {
    sel = (phase < Q) + 2*(phase > 1 - Q);
    L(x) = 2*x - x*x - 1; // Used near the left end of the interval
    R(x) = 2*x + x*x + 1; // Used near the right end of the interval
};

//----------`(os.)polyblep_saw`----------
// Sawtooth oscillator with suppressed aliasing (using `polyblep`).
//
// #### Usage
//
// ```
// polyblep_saw(freq) : _
// ```
//
// Where:
//
// * `freq`: frequency in Hz
//------------------------------------------------------------
declare polyblep_saw author "Jacek Wieczorek";

polyblep_saw(freq) = naive - polyblep(Q , phase)
with {
    phase = phasor(1, freq);
    naive = 2 * phase - 1;
    Q = freq / ma.SR;
};

//----------`(os.)polyblep_square`----------
// Square wave oscillator with suppressed aliasing (using `polyblep`).
//
// #### Usage
//
// ```
// polyblep_square(freq) : _
// ```
//
// Where:
//
// * `freq`: frequency in Hz
//------------------------------------------------------------
declare polyblep_square author "Jacek Wieczorek";

polyblep_square(freq) = naive - polyblep(Q, phase) + polyblep(Q, ma.modulo(phase + 0.5, 1))
with {
    phase = phasor(1, freq);
    naive = 2 * (phase * 2 : int) - 1;
    Q = freq / ma.SR;
};

//----------`(os.)polyblep_triangle`----------
// Triangle wave oscillator with suppressed aliasing (using `polyblep`).
//
// #### Usage
//
// ```
// polyblep_triangle(freq) : _
// ```
//
// Where:
//
// * `freq`: frequency in Hz
//------------------------------------------------------------
declare polyblep_triangle author "Jacek Wieczorek";

polyblep_triangle(freq) = polyblep_square(freq) : fi.pole(0.999) : *(4 * freq / ma.SR);

// end further contributions section
//########################################################################################