File: basics.lib

package info (click to toggle)
faust 2.14.4~repack2-1
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 276,136 kB
  • sloc: cpp: 231,578; ansic: 15,403; sh: 10,871; java: 6,917; objc: 4,085; makefile: 3,002; cs: 1,077; ruby: 951; python: 885; xml: 550; yacc: 516; lex: 233; lisp: 201
file content (1386 lines) | stat: -rw-r--r-- 38,595 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
//#################################### basics.lib ########################################
// A library of basic elements. Its official prefix is `ba`.
//########################################################################################
// A library of basic elements for Faust organized in 5 sections:
//
// * Conversion Tools
// * Counters and Time/Tempo Tools
// * Array Processing/Pattern Matching
// * Selectors (Conditions)
// * Other Tools (Misc)

//########################################################################################

/************************************************************************
************************************************************************
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");
ro = library("routes.lib");
ba = library("basics.lib"); // so functions here can be copy/pasted out

declare name "Faust Basic Element Library";
declare version "0.0";

//=============================Conversion Tools===========================================
//========================================================================================


//-------`(ba.)samp2sec`----------
// Converts a number of samples to a duration in seconds.
// `samp2sec` is a standard Faust function.
//
// #### Usage
//
// ```
// samp2sec(n) : _
// ```
//
// Where:
//
// * `n`: number of samples
//----------------------------
samp2sec = /(ma.SR);


//-------`(ba.)sec2samp`----------
// Converts a duration in seconds to a number of samples.
// `samp2sec` is a standard Faust function.
//
// #### Usage
//
// ```
// sec2samp(d) : _
// ```
//
// Where:
//
// * `d`: duration in seconds
//----------------------------
sec2samp = *(ma.SR);


//-------`(ba.)db2linear`----------
// Converts a loudness in dB to a linear gain (0-1).
// `db2linear` is a standard Faust function.
//
// #### Usage
//
// ```
// db2linear(l) : _
// ```
//
// Where:
//
// * `l`: loudness in dB
//-----------------------------
db2linear(n) = pow(10, n/20.0);


//-------`(ba.)linear2db`----------
// Converts a linear gain (0-1) to a loudness in dB.
// `linear2db` is a standard Faust function.
//
// #### Usage
//
// ```
// linear2db(g) : _
// ```
//
// Where:
//
// * `g`: a linear gain
//-----------------------------
linear2db(n) = 20*log10(n);


//----------`(ba.)lin2LogGain`------------------
// Converts a linear gain (0-1) to a log gain (0-1).
//
// #### Usage
//
// ```
// _ : lin2LogGain : _
// ```
//---------------------------------------------
lin2LogGain = _ <: _*_;


//----------`(ba.)log2LinGain`------------------
// Converts a log gain (0-1) to a linear gain (0-1).
//
// #### Usage
//
// ```
// _ : log2LinGain : _
// ```
//---------------------------------------------
log2LinGain = sqrt;

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

Except where noted otherwise, The Faust functions below in this
section are Copyright (C) 2003-2017 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)

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

//-------`(ba.)tau2pole`----------
// Returns a real pole giving exponential decay.
// Note that t60 (time to decay 60 dB) is ~6.91 time constants.
// `tau2pole` is a standard Faust function.
//
// #### Usage
//
// ```
// _ : smooth(tau2pole(tau)) : _
// ```
//
// Where:
//
// * `tau`: time-constant in seconds
//-----------------------------
  tau2pole(tau) = exp(-1.0/(tau*ma.SR));


//-------`(ba.)pole2tau`----------
// Returns the time-constant, in seconds, corresponding to the given real,
// positive pole in (0,1).
// `pole2tau` is a standard Faust function.
//
// #### Usage
//
// ```
// pole2tau(pole) : _
// ```
//
// Where:
//
// * `pole`: the pole
//-----------------------------
  pole2tau(pole) = -1.0/(log(pole)*ma.SR);


//-------`(ba.)midikey2hz`----------
// Converts a MIDI key number to a frequency in Hz (MIDI key 69 = A440).
// `midikey2hz` is a standard Faust function.
//
// #### Usage
//
// ```
// midikey2hz(mk) : _
// ```
//
// Where:
//
// * `mk`: the MIDI key number
//-----------------------------
  midikey2hz(mk)  = 440.0*pow(2.0, (mk-69.0)/12);


//-------`(ba.)hz2midikey`----------
// Converts a frequency in Hz to a MIDI key number (MIDI key 69 = A440).
// `hz2midikey` is a standard Faust function.
//
// #### Usage
//
// ```
// hz2midikey(f) : _
// ```
//
// Where:
//
// * `f`: frequency in Hz
//-----------------------------
  hz2midikey(f) = 12*ma.log2(f/440.0) + 69.0;


//-------`(ba.)pianokey2hz`----------
// Converts a piano key number to a frequency in Hz (piano key 49 = A440).
//
// #### Usage
//
// ```
// pianokey2hz(pk) : _
// ```
//
// Where:
//
// * `pk`: the piano key number
//-----------------------------
  pianokey2hz(pk) = 440.0*pow(2.0, (pk-49.0)/12);


//-------`(ba.)hz2pianokey`----------
// Converts a frequency in Hz to a piano key number (piano key 49 = A440).
//
// #### Usage
//
// ```
// hz2pianokey(f) : _
// ```
//
// Where:
//
// * `f`: frequency in Hz
//-----------------------------
  hz2pianokey(f)  = 12*ma.log2(f/440.0) + 49.0;

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

//==============================Counters and Time/Tempo Tools=============================
//========================================================================================

//----------------------------`(ba.)countdown`------------------------------
// Starts counting down from n included to 0. While trig is 1 the output is n.
// The countdown starts with the transition of trig from 1 to 0. At the end
// of the countdown the output value will remain at 0 until the next trig.
// `countdown` is a standard Faust function.
//
// #### Usage
//
// ```
// countdown(n,trig) : _
// ```
//
// Where:
//
// * `n`: the starting point of the countdown
// * `trig`: the trigger signal (1: start at `n`; 0: decrease until 0)
//-----------------------------------------------------------------------------
countdown(count, trig)	= \(c).(if(trig>0, count, max(0, c-1))) ~_;


//----------------------------`(ba.)countup`--------------------------------
// Starts counting up from 0 to n included. While trig is 1 the output is 0.
// The countup starts with the transition of trig from 1 to 0. At the end
// of the countup the output value will remain at n until the next trig.
// `countup` is a standard Faust function.
//
// #### Usage
//
// ```
// countup(n,trig) : _
// ```
//
// Where:
//
// * `n`: the maximum count value
// * `trig`: the trigger signal (1: start at 0; 0: increase until `n`)
//-----------------------------------------------------------------------------
countup(count, trig)	= \(c).(if(trig>0, 0, min(count, c+1))) ~_;


//--------------------`(ba.)sweep`--------------------------
// Counts from 0 to `period` samples repeatedly, while `run` is 1.
// Outsputs zero while `run` is 0.
//
// #### Usage
//
// ```
// sweep(period,run) : _
// ```
//-----------------------------------------------------------------
// Author: Jonatan Liljedahl, markdown by RM
sweep = %(int(*:max(1)))~+(1);


//-------`(ba.)time`----------
// A simple timer that counts every samples from the beginning of the process.
// `time` is a standard Faust function.
//
// #### Usage
//
// ```
// time : _
// ```
//------------------------
time = (+(1)~_ ) - 1;


//-------`(ba.)tempo`----------
// Converts a tempo in BPM into a number of samples.
//
// #### Usage
//
// ```
// tempo(t) : _
// ```
//
// Where:
//
// * `t`: tempo in BPM
//------------------------
tempo(t) = (60*ma.SR)/t;


//-------`(ba.)period`----------
// Basic sawtooth wave of period `p`.
//
// #### Usage
//
// ```
// period(p) : _
// ```
//
// Where:
//
// * `p`: period as a number of samples
//------------------------
// NOTE: may be this should go in oscillators.lib
period(p) = %(int(p))~+(1');


//-------`(ba.)pulse`----------
// Pulses (10000) generated at period `p`.
//
// #### Usage
//
// ```
// pulse(p) : _
// ```
//
// Where:
//
// * `p`: period as a number of samples
//------------------------
// NOTE: may be this should go in oscillators.lib
pulse(p) = period(p)==0;


//-------`(ba.)pulsen`----------
// Pulses (11110000) of length `n` generated at period `p`.
//
// #### Usage
//
// ```
// pulsen(n,p) : _
// ```
//
// Where:
//
// * `n`: the length of the pulse as a number of samples
// * `p`: period as a number of samples
//------------------------
// NOTE: may be this should go in oscillators.lib
pulsen(n,p) = period(p)<n;


//-----------------------`(ba.)cycle`---------------------------
// Split nonzero input values into `n` cycles.
//
// #### Usage
//
// ```
// _ : cycle(n) <:
// ```
//
// Where:
//
// * `n`: the number of cycles/output signals
//---------------------------------------------------------
// Author: Mike Olsen
cycle(n) = _ <: par(i,n,resetCtr(n,(i+1)));


//-------`(ba.)beat`----------
// Pulses at tempo `t`.
// `beat` is a standard Faust function.
//
// #### Usage
//
// ```
// beat(t) : _
// ```
//
// Where:
//
// * `t`: tempo in BPM
//------------------------
beat(t) = pulse(tempo(t));


//----------------------------`(ba.)pulse_countup`-----------------------------------
// Starts counting up pulses. While trig is 1 the output is
// counting up, while trig is 0 the counter is reset to 0.
//
// #### Usage
//
// ```
// _ : pulse_countup(trig) : _
// ```
//
// Where:
//
// * `trig`: the trigger signal (1: start at next pulse; 0: reset to 0)
//------------------------------------------------------------------------------
//TODO: author "Vince"
pulse_countup(t) =  + ~ _ * t ;


//----------------------------`(ba.)pulse_countdown`---------------------------------
// Starts counting down pulses. While trig is 1 the output is
// counting down, while trig is 0 the counter is reset to 0.
//
// #### Usage
//
// ```
// _ : pulse_countdown(trig) : _
// ```
//
// Where:
//
// * `trig`: the trigger signal (1: start at next pulse; 0: reset to 0)
//------------------------------------------------------------------------------
//TODO: author "Vince"
pulse_countdown(t) =  - ~ _ * t ;


//----------------------------`(ba.)pulse_countup_loop`------------------------------
// Starts counting up pulses from 0 to n included. While trig is 1 the output is
// counting up, while trig is 0 the counter is reset to 0. At the end
// of the countup (n) the output value will be reset to 0.
//
// #### Usage
//
// ```
// _ : pulse_countup_loop(n,trig) : _
// ```
//
// Where:
//
// * `n`: the highest number of the countup (included) before reset to 0.
// * `trig`: the trigger signal (1: start at next pulse; 0: reset to 0)
//------------------------------------------------------------------------------
//TODO: author "Vince"
pulse_countup_loop(n, t) =  + ~ cond(n)*t
with {
  cond(n) =  _ <: _ * (_ <= n) ;
};


//-----------------------`(ba.)resetCtr`------------------------
// Function that lets through the mth impulse out of
// each consecutive group of `n` impulses.
//
// #### Usage
//
// ```
// _ : resetCtr(n,m) : _
// ```
//
// Where:
//
// * `n`: the total number of impulses being split
// * `m`: index of impulse to allow to be output
//---------------------------------------------------------
// Author: Mike Olsen
resetCtr(n,m) = _ <: (_,pulse_countup_loop(n-1,1)) : (_,(_==m)) : *;


//----------------------------`(ba.)pulse_countdown_loop`----------------------------
// Starts counting down pulses from 0 to n included. While trig is 1 the output
// is counting down, while trig is 0 the counter is reset to 0. At the end
// of the countdown (n) the output value will be reset to 0.
//
// #### Usage
//
// ```
// _ : pulse_coundown_loop(n,trig) : _
// ```
//
// Where:
//
// * `n`: the highest number of the countup (included) before reset to 0.
// * `trig`: the trigger signal (1: start at next pulse; 0: reset to 0)
//------------------------------------------------------------------------------
//TODO: author "Vince:
pulse_countdown_loop(n, t) =  - ~ cond(n)*t
with {
  cond(n) =  _ <: _ * (_ >= n) ;
};



//===============================Array Processing/Pattern Matching========================
//========================================================================================

//---------------------------------`(ba.)count`---------------------------------
// Count the number of elements of list l.
// `count` is a standard Faust function.
//
// #### Usage
//
// ```
// count(l)
// count ((10,20,30,40)) -> 4
// ```
//
// Where:
//
// * `l`: list of elements
//-----------------------------------------------------------------------------
count ((xs, xxs)) = 1 + count(xxs);
count (xx) = 1;


//-------------------------------`(ba.)take`-----------------------------------
// Take an element from a list.
// `take` is a standard Faust function.
//
// #### Usage
//
// ```
// take(e,l)
// take(3,(10,20,30,40)) -> 30
// ```
//
// Where:
//
// * `p`: position (starting at 1)
// * `l`: list of elements
//-----------------------------------------------------------------------------
take (1, (xs, xxs)) 	= xs;
take (1, xs) 			= xs;
take (nn, (xs, xxs)) 	= take (nn-1, xxs);


//----------------------------`(ba.)subseq`--------------------------------
// Extract a part of a list.
//
// #### Usage
//
// ```
// subseq(l, p, n)
// subseq((10,20,30,40,50,60), 1, 3) -> (20,30,40)
// subseq((10,20,30,40,50,60), 4, 1) -> 50
// ```
//
// Where:
//
// * `l`: list
// * `p`: start point (0: begin of list)
// * `n`: number of elements
//
// #### Note:
//
// Faust doesn't have proper lists. Lists are simulated with parallel
// compositions and there is no empty list.
//-----------------------------------------------------------------------------
subseq((head, tail), 0, 1)      = head;
subseq((head, tail), 0, n)      = head, subseq(tail, 0, n-1);
subseq((head, tail), p, n)      = subseq(tail, p-1, n);
subseq(head, 0, n)              = head;


//============================Selectors (Conditions)======================================
//========================================================================================

//-----------------------------`(ba.)if`-----------------------------------
// if-then-else implemented with a select2.
//
// #### Usage
//
// *   `if(c, t, e) : _`
//
// Where:
//
// * `c`: condition
// * `t`: signal selected while c is true
// * `e`: signal selected while c is false
//-----------------------------------------------------------------------------
if(cond,thn,els) = select2(cond,els,thn);
// TODO: perhaps it would make more sense to have an if(a,b) and an ifelse(a,b,c)?

//-----------------------------`(ba.)selector`---------------------------------
// Selects the ith input among n at compile time.
//
// #### Usage
//
// ```
// selector(i,n)
// _,_,_,_ : selector(2,4) : _  // selects the 3rd input among 4
// ```
//
// Where:
//
// * `i`: input to select (`int`, numbered from 0, known at compile time)
// * `n`: number of inputs (`int`, known at compile time, `n > i`)
//
// There is also cselector for selecting among complex input signals of the form (real,imag).
//
//-----------------------------------------------------------------------------
selector(i,n) = par(j, n, S(i, j))    with { S(i,i) = _; S(i,j) = !; };
cselector(i,n) = par(j, n, S(i, j))    with { S(i,i) = (_,_); S(i,j) = (!,!); }; // for complex numbers


//-----------------------------`(ba.)selectn`---------------------------------
// Selects the ith input among N at run time.
//
// #### Usage
//
// ```
// selectn(N,i)
// _,_,_,_ : selectn(4,2) : _  // selects the 3rd input among 4
// ```
//
// Where:
//
// * `N`: number of inputs (int, known at compile time, N > 0)
// * `i`: input to select (int, numbered from 0)
//
// #### Example test program
//
// ```
// N=64;
// process = par(n,N, (par(i,N,i) : selectn(N,n)));
// ```
//-----------------------------------------------------------------------------
selectn(N,i) = S(N,0)
    with {
       S(1,offset) = _;
       S(n,offset) = S(left, offset), S(right, offset+left) : select2(i >= offset+left)
            with {
                right = int(n/2);
                left  = n-right;
            };
    };


//--------------------`(ba.)select2stereo`--------------------
// Select between 2 stereo signals.
//
// #### Usage
//
// ```
// _,_,_,_ : select2stereo(bpc) : _,_,_,_
// ```
//
// Where:
//
// * `bpc`: the selector switch (0/1)
//------------------------------------------------------------
  select2stereo(bpc) = ro.cross2 : select2(bpc), select2(bpc) : _,_;
//=====================================Other==============================================
//========================================================================================

//----------------------------`(ba.)latch`--------------------------------
// Latch input on positive-going transition of "clock" ("sample-and-hold").
//
// #### Usage
//
// ```
// _ : latch(clocksig) : _
// ```
//
// Where:
//
// * `clocksig`: hold trigger (0 for hold, 1 for bypass)
//------------------------------------------------------------
  latch(c,x) = x * s : + ~ *(1-s) with { s = ((c'<=0)&(c>0)); };


//--------------------------`(ba.)sAndH`-------------------------------
// Sample And Hold.
// `sAndH` is a standard Faust function.
//
// #### Usage
//
// ```
// _ : sAndH(t) : _
// ```
//
// Where:
//
// * `t`: hold trigger (0 for hold, 1 for bypass)
//----------------------------------------------------------------
// Author: RM
sAndH(t) = select2(t,_,_)~_;


//--------------------------`(ba.)downSample`-------------------------------
// Down sample a signal. WARNING: this function doesn't change the
// rate of a signal, it just holds samples...
// `downSample` is a standard Faust function.
//
// #### Usage
//
// ```
// _ : downSample(freq) : _
// ```
//
// Where:
//
// * `freq`: new rate in Hz
//----------------------------------------------------------------
// Author: RM
downSample(freq) = sAndH(hold)
with{
  hold = time%int(ma.SR/freq) == 0;
};


//------------------`(ba.)peakhold`---------------------------
// Outputs current max value above zero.
//
// #### Usage
//
// ```
// _ : peakhold(mode) : _;
// ```
//
// Where:
//
// `mode` means: 0 - Pass through. A single sample 0 trigger will work as a reset.
//    1 - Track and hold max value.
//----------------------------------------------------------------
// TODO: author Jonatan Liljedahl, revised by RM
peakhold = (*,_:max) ~ _;


//------------------`(ba.)peakholder`---------------------------
// Tracks abs peak and holds peak for 'holdtime' samples.
//
// #### Usage
//
// ```
// _ : peakholder(holdtime) : _;
// ```
//----------------------------------------------------------------
// TODO: author Jonatan Liljedahl
peakholder(holdtime) = peakhold2 ~ reset : (!,_) with {
    reset = ba.sweep(holdtime) > 0;
    // first out is gate that is 1 while holding last peak
    peakhold2 = _,abs <: peakhold,!,_ <: >=,_,!;
};


//--------------------------`(ba.)impulsify`---------------------------
// Turns the signal from a button into an impulse (1,0,0,... when
// button turns on).
// `impulsify` is a standard Faust function.
//
// #### Usage
//
// ```
// button("gate") : impulsify ;
// ```
//----------------------------------------------------------------
impulsify = _ <: _,mem : - <: >(0)*_;


//-----------------------`(ba.)automat`------------------------------
// Record and replay to the values the input signal in a loop.
//
// #### Usage
//
// ```
// hslider(...) : automat(bps, size, init) : _
// ```
//-----------------------------------------------------------------------
automat(bps, size, init, input) = rwtable(size+1, init, windex, input, rindex)
with {
	clock 	= beat(bps);
	rindex 	= int(clock) : (+ : %(size)) ~ _;		// each clock read the next entry of the table
	windex 	= if (timeToRenew, rindex, size);		// we ignore input unless it is time to renew
	timeToRenew 	= int(clock) & (inputHasMoved | (input <= init));
	inputHasMoved 	= abs(input-input') : countfrom(int(clock)') : >(0);
	countfrom(reset) = (+ : if(reset, 0, _)) ~ _;
};


//-----------------`(ba.)bpf`-------------------
// bpf is an environment (a group of related definitions) that can be used to
// create break-point functions. It contains three functions:
//
// * `start(x,y)` to start a break-point function
// * `end(x,y)` to end a break-point function
// * `point(x,y)` to add intermediate points to a break-point function
//
// A minimal break-point function must contain at least a start and an end point :
//
// ```
// f = bpf.start(x0,y0) : bpf.end(x1,y1);
// ```
//
// A more involved break-point function can contains any number of intermediate
// points:
//
// ```
// f = bpf.start(x0,y0) : bpf.point(x1,y1) : bpf.point(x2,y2) : bpf.end(x3,y3);
// ```
//
// In any case the `x_{i}` must be in increasing order (for all `i`, `x_{i} < x_{i+1}`).
// For example the following definition :
//
// ```
// f = bpf.start(x0,y0) : ... : bpf.point(xi,yi) : ... : bpf.end(xn,yn);
// ```
//
// implements a break-point function f such that:
//
// * `f(x) = y_{0}` when `x < x_{0}`
// * `f(x) = y_{n}` when `x > x_{n}`
// * `f(x) = y_{i} + (y_{i+1}-y_{i})*(x-x_{i})/(x_{i+1}-x_{i})` when `x_{i} <= x`
// and `x < x_{i+1}`
//
// `bpf` is a standard Faust function.
//--------------------------------------------------------
bpf = environment
{
  // Start a break-point function
  start(x0,y0) = \(x).(x0,y0,x,y0);
  // Add a break-point
  point(x1,y1) = \(x0,y0,x,y).(x1, y1, x , if (x < x0, y, if (x < x1, y0 + (x-x0)*(y1-y0)/(x1-x0), y1)));
  // End a break-point function
  end  (x1,y1) = \(x0,y0,x,y).(if (x < x0, y, if (x < x1, y0 + (x-x0)*(y1-y0)/(x1-x0), y1)));
};


//-------------------`(ba.)listInterp`-------------------------
// Linearly interpolates between the elements of a list.
//
// #### Usage
//
// ```
// foo = listInterp((800,400,350,450,325),index);
// i = 1.69; // range is 0-4
// process = foo(i);
// ```
//
// Where:
//
// * `index`: the index (float) to interpolate between the different values.
// The range of `index` depends on the size of the list.
//------------------------------------------------------------
// Author: RM
listInterp(v) =
  bpf.start(0,take(1,v)) :
  seq(i,count(v)-2,bpf.point(i+1,take(i+2,v))) :
  bpf.end(count(v)-1,take(count(v),v));


//-------------------`(ba.)bypass1`-------------------------
// Takes a mono input signal, route it to `e` and bypass it if `bpc = 1`.
// `bypass1` is a standard Faust function.
//
// #### Usage
//
// ```
// _ : bypass1(bpc,e) : _
// ```
//
// Where:
//
// * `bpc`: bypass switch (0/1)
// * `e`: a mono effect
//------------------------------------------------------------
// Author: JOS
// License: STK-4.3
bypass1(bpc,e) = _ <: select2(bpc,(inswitch:e),_)
  with {
    inswitch = select2(bpc,_,0);
  };

//-------------------`(ba.)bypass2`-------------------------
// Takes a stereo input signal, route it to `e` and bypass it if `bpc = 1`.
// `bypass2` is a standard Faust function.
//
// #### Usage
//
// ```
// _,_ : bypass2(bpc,e) : _,_
// ```
//
// Where:
//
// * `bpc`: bypass switch (0/1)
// * `e`: a stereo effect
//------------------------------------------------------------
// Author: JOS
// License: STK-4.3
bypass2(bpc,e) = _,_ <: ((inswitch:e),_,_) : select2stereo(bpc)
  with {
    inswitch = _,_ : (select2(bpc,_,0), select2(bpc,_,0)) : _,_;
  };

//-------------------`(ba.)bypass1to2`-------------------------
// Bypass switch for effect `e` having mono input signal and stereo output.
// Effect `e` is bypassed if `bpc = 1`.
// `bypass1to2` is a standard Faust function.
//
// #### Usage
//
// ```
// _ : bypass1(bpc,e) : _,_
// ```
//
// Where:
//
// * `bpc`: bypass switch (0/1)
// * `e`: a mono-to-stereo effect
//------------------------------------------------------------
// Author: JOS
// License: STK-4.3
bypass1to2(bpc,e) = _ <: ((inswitch:e),_,_) : ba.select2stereo(bpc)
  with {
    inswitch = select2(bpc,_,0);
  };

//----------------------------`(ba.)toggle`------------------------------------------
// Triggered by the change of 0 to 1, it toggles the output value
// between 0 and 1.
//
// #### Usage
//
// ```
// _ : toggle : _
// ```
// #### Examples
//
// ```
// button("toggle") : toggle : vbargraph("output", 0, 1)
// (an.amp_follower(0.1) > 0.01) : toggle : vbargraph("output", 0, 1) // takes audio input
// ```
//
//------------------------------------------------------------------------------
// TODO: author "Vince"
toggle = trig : loop
  with {
    trig(x) = (x-x') == 1;
    loop = (_ != _) ~ _ ;
  };


//----------------------------`(ba.)on_and_off`------------------------------------------
// The first channel set the output to 1, the second channel to 0.
//
// #### Usage
//
// ```
// _ , _ : on_and_off : _
// ```
//
// #### Example
//
// ```
// button("on"), button("off") : on_and_off : vbargraph("output", 0, 1)
// ```
//
//------------------------------------------------------------------------------
// TODO: author "Vince"
on_and_off(a, b) = (a : trig) : loop(b)
with {
  trig(x) = (x-x') == 1;
  loop(b) = + ~ (_ >= 1) * ((b : trig) == 0) ;
};


//-----------------------------`(ba.)selectoutn`---------------------------------
// Route input to the output among N at run time.
//
// #### Usage
//
// ```
// _ : selectoutn(n, s) : _,_,...n
// ```
//
// Where:
//
// * `n`: number of outputs (int, known at compile time, N > 0)
// * `s`: output number to route to (int, numbered from 0) (i.e. slider)
//
// #### Example
//
// ```
// process = 1 : selectoutn(3, sel) : par(i,3,bar) ;
// sel = hslider("volume",0,0,2,1) : int;
// bar = vbargraph("v.bargraph", 0, 1);
// ```
//--------------------------------------------------------------------------
// TODO: author "Vince"
selectoutn(n, s) = _ <: par(i,n, _* (s==i) ) ;

//=================================Sliding Reduce=========================================
// Provides various operations on the last N samples using a high order
// `slidingReduce(op,N,maxN,disabledVal,x)`` fold-like function:
//
// * `slidingSumN(n,maxn)`: the sliding sum of the last n input samples
// * `slidingMaxN(n,maxn)`: the sliding max of the last n input samples
// * `slidingMinN(n,maxn)`: the sliding min of the last n input samples
// * `slidingMeanN(n,maxn)`: the sliding mean of the last n input samples
// * `slidingRMSn(n,maxn)`: the sliding RMS of the last n input samples
//
// #### Working Principle
//
// If we want the maximum of the last 8 values, we can do that as:
//
// ```
// simpleMax(x) =
//  (
//    (
//      max(x@0,x@1),
//      max(x@2,x@3)
//    ) :max
//  ),
//  (
//    (
//      max(x@4,x@5),
//      max(x@6,x@7)
//    ) :max
//  )
//  :max;
// ```
//
// `max(x@2,x@3)` is the same as `max(x@0,x@1)@2` but the latter re-uses a
// value we already computed,so is more efficient. Using the same trick for
// values 4 trough 7, we can write:
//
// ```
// efficientMax(x)=
//  (
//    (
//      max(x@0,x@1),
//      max(x@0,x@1)@2
//    ) :max
//  ),
//  (
//    (
//      max(x@0,x@1),
//      max(x@0,x@1)@2
//    ) :max@4
//  )
//  :max;
// ```
//
// We can rewrite it recursively, so it becomes possible to get the maximum at
// have any number of values, as long as it's a power of 2.
//
// ```
// recursiveMax =
//  case {
//    (1,x) => x;
//    (N,x) =>  max(recursiveMax(N/2,x) , recursiveMax(N/2,x)@(N/2));
//  };
// ```
//
// What if we want to look at a number of values that's not a power of 2?
// For each value, we will have to decide whether to use it or not.
// If N is bigger than the index of the value, we use it, otherwise we replace
// it with (`0-(ma.INFINITY)`):
//
// ```
// variableMax(N,x) =
//  max(
//    max(
//      (
//        (x@0 : useVal(0)),
//        (x@1 : useVal(1))
//      ):max,
//      (
//        (x@2 : useVal(2)),
//        (x@3 : useVal(3))
//      ):max
//    ),
//    max(
//      (
//        (x@4 : useVal(4)),
//        (x@5 : useVal(5))
//      ):max,
//      (
//        (x@6 : useVal(6)),
//        (x@7 : useVal(7))
//      ):max
//    )
//  )
//  with{
//  useVal(i) = select2( (N>=i) , (0-(ma.INFINITY)),_);
// };
// ```
//
// Now it becomes impossible to re-use any values. To fix that let's first look
// at how we'd implement it using recursiveMax, but with a fixed N that is not
// a power of 2. For example, this is how you'd do it with `N=3`:
//
// ```
// binaryMaxThree(x) =
//  (
//    recursiveMax(1,x)@0, // the first x
//    recursiveMax(2,x)@1  // the second and third x
//  ):max;
// ```
//
// `N=6`
//
// ```
// binaryMaxSix(x) =
//  (
//    recursiveMax(2,x)@0, // first two
//    recursiveMax(4,x)@2  // third trough sixt
//  ):max;
// ```
//
// Note that `recursiveMax(2,x)` is used at a different delay then in
// `binaryMaxThree`, since it represents 1 and 2, not 2 and 3. Each block is
// delayed the combined size of the previous blocks.
//
// `N=7`
//
// ```
// binaryMaxSeven(x) =
//  (
//    (
//      recursiveMax(1,x)@0, // first x
//      recursiveMax(2,x)@1  // second and third
//    ):max,
//    (
//      recursiveMax(4,x)@3  // fourth trough seventh
//    )
//  ):max;
// ```
//
// To make a variable version, we need to know which powers of two are used,
// and at which delay time.
//
// Then it becomes a matter of:
//
// * lining up all the different block sizes in parallel:  the first `par()`
//  statement
// * delaying each the appropriate amount: `sumOfPrevBlockSizes()`
// * turning it on or off: `useVal()`
// * getting the maximum of all of them: `combine()`
//
// In faust, we can only do that for a fixed maximum number of values: `maxN`
//
// ```
// variableBinaryMaxN(N,maxN,x) =
//  par(i,maxNrBits,recursiveMax(pow2(i),x)@sumOfPrevBlockSizes(N,maxN,i)  : useVal(i)) : combine(maxNrBits) with {
//    // The sum of all the sizes of the previous blocks
//    sumOfPrevBlockSizes(N,maxN,0) = 0;
//    sumOfPrevBlockSizes(N,maxN,i) = (ba.subseq((allBlockSizes(N,maxN)),0,i):>_);
//    allBlockSizes(N,maxN) = par(i, maxNrBits, pow2(i) * isUsed(i) );
//    maxNrBits = int2nrOfBits(maxN);
//    // get the maximum of all blocks
//    combine(2) = max;
//    combine(N) = max(combine(N-1),_);
//    // Decide wether or not to use a certain value, based on N
//    useVal(i) = select2( isUsed(i), (0-(ma.INFINITY)),_);
//    isUsed(i) = ba.take(i+1,(int2bin(N,maxN)));
//  };
// ```
//========================================================================================
// Section contributed by Bart Brouns (bart@magnetophon.nl).
// SPDX-License-Identifier: GPL-3.0
// Copyright (C) 2018 Bart Brouns

//-----------------------------`(ba.)slidingReduce`-----------------------------
// Fold-like high order function. Apply a commutative binary operation `<op>` to
// the last `<n>` consecutive samples of a signal `<x>`. For example :
// `slidingReduce(max,128,128,-(ma.INFINITY))` will compute the maximum of the last
// 128 samples. The output is updated each sample, unlike reduce, where the
// output is constant for the duration of a block.
//
// #### Usage
//
// ```
// _ : slidingReduce(op,N,maxN,disabledVal) : _
// ```
//
// Where:
//
// * `N`: the number of values to process
// * `maxN`: the maximum number of values to process, needs to be a power of 2
// * `op`: the operator. Needs to be a commutative one.
// * `disabledVal`: the value to use when we want to ignore a value.
//
// In other words, `op(x,disabledVal)` should equal to `x`. For example,
// `+(x,0)` equals `x` and `min(x,ma.INFINITY)` equals `x`. So if we want to
// calculate the sum, we need to give 0 as `disabledVal`, and if we want the
// minimum, we need to give `ma.INFINITY` as `disabledVal`.
//------------------------------------------------------------------------------
slidingReduce(op,N,maxN,disabledVal,x) =
  par(i,maxNrBits,fixedDelayOp(pow2(i),x)@sumOfPrevBlockSizes(N,maxN,i)
    : useVal(i)) : combine(maxNrBits)
  with {
    // apply <op> to the last <N> values of <x>, where <N> is fixed
    fixedDelayOp = case {
      (1,x) => x;
      (N,x) =>  op(fixedDelayOp(N/2,x) , fixedDelayOp(N/2,x)@(N/2));
    };
    // The sum of all the sizes of the previous blocks
    sumOfPrevBlockSizes(N,maxN,0) = 0;
    sumOfPrevBlockSizes(N,maxN,i) = (subseq((allBlockSizes(N,maxN)),0,i):>_);
    allBlockSizes(N,maxN) = par(i, maxNrBits, (pow2(i)) * isUsed(i) );
    maxNrBits = int2nrOfBits(maxN);
    // Apply <op> to <N> parallel inputsignals
    combine(2) = op;
    combine(N) = op(combine(N-1),_);
    // Decide wether or not to use a certain value, based on N
    // Basically only the second <select2> is needed,
    // but this version also works for N == 0
    // 'works' in this case means 'does the same as reduce
    useVal(i) =
      _ <: select2(
        (i==0) & (N==0) ,
        select2( isUsed(i) , disabledVal,_),
        _
      );
    // useVal(i) =
    //     select2( isUsed(i) , disabledVal,_);
    isUsed(i) = take(i+1,(int2bin(N,maxN)));
    pow2(i) = 1<<i;
    // same as:
    // pow2(i) = int(pow(2,i));
    // but in the block diagram, it will be displayed as a number, instead of a formula

    // convert N into a list of ones and zeros
    int2bin(N,maxN) = par(j,int2nrOfBits(maxN),int(floor(N/(pow2(j))))%2);
    // calculate how many ones and zeros are needed to represent maxN
    int2nrOfBits(0) = 0;
    int2nrOfBits(maxN) = int(floor(log(maxN)/log(2))+1);
  };


//------------------------------`(ba.)slidingSumN`------------------------------
// The sliding sum of the last n input samples.
//
// #### Usage
//
// ```
// _ : slidingSumN(N,maxN) : _
// ```
//
// Where:
//
// * `N`: the number of values to process
// * `maxN`: the maximum number of values to process, needs to be a power of 2
//------------------------------------------------------------------------------
slidingSumN(n,maxn) = slidingReduce(+,n,maxn,0);


//----------------------------`(ba.)slidingMaxN`--------------------------------
// The sliding maximum of the last n input samples.
//
// #### Usage
//
// ```
// _ : slidingMaxN(N,maxN) : _
// ```
//
// Where:
//
// * `N`: the number of values to process
// * `maxN`: the maximum number of values to process, needs to be a power of 2
//------------------------------------------------------------------------------
slidingMaxN(n,maxn) = slidingReduce(max,n,maxn,-(ma.INFINITY));


//---------------------------`(ba.)slidingSumN`---------------------------------
// The sliding minimum of the last n input samples.
//
// #### Usage
//
// ```
// _ : slidingMinN(N,maxN) : _
// ```
//
// Where:
//
// * `N`: the number of values to process
// * `maxN`: the maximum number of values to process, needs to be a power of 2
//------------------------------------------------------------------------------
slidingMinN(n,maxn) = slidingReduce(min,n,maxn,ma.INFINITY);


//----------------------------`(ba.)slidingMeanN`-------------------------------
// The sliding mean of the last n input samples.
//
// #### Usage
//
// ```
// _ : slidingMeanN(N,maxN) : _
// ```
//
// Where:
//
// * `N`: the number of values to process
// * `maxN`: the maximum number of values to process, needs to be a power of 2
//------------------------------------------------------------------------------
slidingMeanN(n,maxn) = slidingSumN(n,maxn)/n;


//---------------------------`(ba.)slidingRMSn`---------------------------------
// The root mean square of the last n input samples.
//
// #### Usage
//
// ```
// _ : slidingRMSn(N,maxN) : _
// ```
//
// Where:
//
// * `N`: the number of values to process
// * `maxN`: the maximum number of values to process, needs to be a power of 2
//------------------------------------------------------------------------------
slidingRMSn(n,maxn) = pow(2):slidingMeanN(n,maxn) : sqrt;



//////////////////////////////////Deprecated Functions////////////////////////////////////
// This section implements functions that used to be in music.lib but that are now
// considered as "deprecated".
//////////////////////////////////////////////////////////////////////////////////////////

millisec	= ma.SR/1000.0;

time1s 	= hslider("time", 0, 0,  1000, 0.1)*millisec;
time2s 	= hslider("time", 0, 0,  2000, 0.1)*millisec;
time5s 	= hslider("time", 0, 0,  5000, 0.1)*millisec;
time10s = hslider("time", 0, 0, 10000, 0.1)*millisec;
time21s = hslider("time", 0, 0, 21000, 0.1)*millisec;
time43s = hslider("time", 0, 0, 43000, 0.1)*millisec;