File: compressors.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 (1391 lines) | stat: -rw-r--r-- 66,526 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
//#################################### compressors.lib ###################################
// A library of compressor effects. Its official prefix is `co`.
//
// #### References
// * <https://github.com/grame-cncm/faustlibraries/blob/master/compressors.lib>
//########################################################################################

/************************************************************************
************************************************************************
FAUST library file
Copyright (C) 2003-2016 GRAME, Centre National de Creation Musicale
----------------------------------------------------------------------
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.
************************************************************************
************************************************************************/

ba = library("basics.lib");
si = library("signals.lib");
an = library("analyzers.lib");
ro = library("routes.lib");
ma = library("maths.lib");
it = library("interpolators.lib");

declare name "Faust Compressor Effect Library";
declare version "1.6.0";

//================================Conversion Tools=======================================
// Most compressors have a ratio parameter to define the amount of compression.
// A ratio of 1 means no compression, a ratio of 2 means that for every dB the input 
// goes above the threshold, the output gets turned down half a dB.
// To use a compressor as a brick wall limiter, the ratio needs to be infinity.
// This is hard to express in a Faust UI element, and overcompression can not be expressed at all,
// therefore most compressors in this library use a strength parameter instead, where
// 0 means no compression, 1 means hard limiting and  bigger than 1 means over-compression.
//========================================================================================
//
//--------------------`(co.)ratio2strength `-------------------
//
// This utility converts a ratio to a strength.
//
// #### Usage
//
// ```
// ratio2strength(ratio) : _
// ```
//
// Where:
//
// * `ratio`:  compression ratio, between 1 and infinity (1=no compression, infinity means hard limiting)
//------------------------------------------------------------

declare ratio2strength author "Bart Brouns";
declare ratio2strength license "GPLv3";

ratio2strength(ratio) = 1-(1/ratio);

//--------------------`(co.)strength2ratio `-------------------
//
// This utility converts a strength to a ratio.
//
// #### Usage
//
// ```
// strength2ratio(strength) : _
// ```
//
// Where:
//
// * `strength`: strength of the compression (0 = no compression, 1 means hard limiting, >1 means over-compression)
//------------------------------------------------------------

declare strength2ratio author "Bart Brouns";
declare strength2ratio license "GPLv3";

strength2ratio(strength) = 1/(1-strength);

//=============================Functions Reference========================================
//========================================================================================

//--------------------`(co.)peak_compression_gain_mono_db`-------------------
// Mono dynamic range compressor gain computer with dB output.
// `peak_compression_gain_mono_db` is a standard Faust function.
//
// #### Usage
//
// ```
// _ : peak_compression_gain_mono_db(strength,thresh,att,rel,knee,prePost) : _
// ```
//
// Where:
//
// * `strength`: strength of the compression (0 = no compression, 1 means hard limiting, >1 means over-compression)
// * `thresh`: dB level threshold above which compression kicks in
// * `att`: attack time = time constant (sec) when level & compression going up
// * `rel`: release time = time constant (sec) coming out of compression
// * `knee`: a gradual increase in gain reduction around the threshold:
// below thresh-(knee/2) there is no gain reduction,
// above thresh+(knee/2) there is the same gain reduction as without a knee,
// and in between there is a gradual increase in gain reduction
// * `prePost`: places the level detector either at the input or after the gain computer;
// this turns it from a linear return-to-zero detector into a log domain return-to-threshold detector
//
// It uses a strength parameter instead of the traditional ratio, in order to be able to
// function as a hard limiter.
// For that you'd need a ratio of infinity:1, and you cannot express that in Faust.
//
// Sometimes even bigger ratios are useful:
// for example a group recording where one instrument is recorded with both a close microphone and a room microphone,
// and the instrument is loud enough in the room mic when playing loud, but you want to boost it when it is playing soft.
//
// #### References
//
// * <http://en.wikipedia.org/wiki/Dynamic_range_compression>
// * Digital Dynamic Range Compressor Design,
// A Tutorial and Analysis,
// Dimitrios GIANNOULIS (<Dimitrios.Giannoulis@eecs.qmul.ac.uk>),
// Michael MASSBERG (<michael@massberg.org>),
// and Josuah D.REISS (<josh.reiss@eecs.qmul.ac.uk>)
//------------------------------------------------------------

declare peak_compression_gain_mono_db author "Bart Brouns";
declare peak_compression_gain_mono_db license "GPLv3";

peak_compression_gain_mono_db(strength,thresh,att,rel,knee,prePost) =
  abs : ba.bypass1(prePost,si.onePoleSwitching(att,rel)) : ba.linear2db : gain_computer(strength,thresh,knee) : ba.bypass1((prePost !=1),si.onePoleSwitching(rel,att))
with {
  gain_computer(strength,thresh,knee,level) =
    select3((level>(thresh-(knee/2)))+(level>(thresh+(knee/2))),
            0,
            ((level-thresh+(knee/2)) : pow(2)/(2*max(ma.EPSILON,knee))),
            (level-thresh))
    : max(0)*-strength;
};


//--------------------`(co.)peak_compression_gain_N_chan_db`-------------------
// N channels dynamic range compressor gain computer with dB output.
// `peak_compression_gain_N_chan_db` is a standard Faust function.
//
// #### Usage
//
// ```
// si.bus(N) : peak_compression_gain_N_chan_db(strength,thresh,att,rel,knee,prePost,link,N) : si.bus(N)
// ```
//
// Where:
//
// * `strength`: strength of the compression (0 = no compression, 1 means hard limiting, >1 means over-compression)
// * `thresh`: dB level threshold above which compression kicks in
// * `att`: attack time = time constant (sec) when level & compression going up
// * `rel`: release time = time constant (sec) coming out of compression
// * `knee`: a gradual increase in gain reduction around the threshold:
// below thresh-(knee/2) there is no gain reduction,
// above thresh+(knee/2) there is the same gain reduction as without a knee,
// and in between there is a gradual increase in gain reduction
// * `prePost`: places the level detector either at the input or after the gain computer;
// this turns it from a linear return-to-zero detector into a log  domain return-to-threshold detector
// * `link`: the amount of linkage between the channels: 0 = each channel is independent, 1 = all channels have the same amount of gain reduction
// * `N`: the number of channels of the compressor, known at compile time
//
// It uses a strength parameter instead of the traditional ratio, in order to be able to
// function as a hard limiter.
// For that you'd need a ratio of infinity:1, and you cannot express that in Faust.
//
// Sometimes even bigger ratios are useful:
// for example a group recording where one instrument is recorded with both a close microphone and a room microphone,
// and the instrument is loud enough in the room mic when playing loud, but you want to boost it when it is playing soft.
//
// #### References
//
// * <http://en.wikipedia.org/wiki/Dynamic_range_compression>
// * Digital Dynamic Range Compressor Design,
// A Tutorial and Analysis,
// Dimitrios GIANNOULIS (<Dimitrios.Giannoulis@eecs.qmul.ac.uk>),
// Michael MASSBERG (<michael@massberg.org>),
// and Josuah D.REISS (<josh.reiss@eecs.qmul.ac.uk>)
//------------------------------------------------------------

declare peak_compression_gain_N_chan_db author "Bart Brouns";
declare peak_compression_gain_N_chan_db license "GPLv3";

// generalise compression gains for N channels.
// first we define a mono version:
peak_compression_gain_N_chan_db(strength,thresh,att,rel,knee,prePost,link,1) =
  peak_compression_gain_mono_db(strength,thresh,att,rel,knee,prePost);

// The actual N-channels version:
// Calculate the maximum gain reduction of N channels,
// and then crossfade between that and each channel's own gain reduction,
// to link/unlink channels
peak_compression_gain_N_chan_db(strength,thresh,att,rel,knee,prePost,link,N) =
  par(i, N, peak_compression_gain_mono_db(strength,thresh,att,rel,knee,prePost))
  <: (si.bus(N),(ba.parallelMin(N) <: si.bus(N))) : ro.interleave(N,2) : par(i,N,(it.interpolate_linear(link)));


//--------------------`(co.)FFcompressor_N_chan`-------------------
// Feed forward N channels dynamic range compressor.
// `FFcompressor_N_chan` is a standard Faust function.
//
// #### Usage
//
// ```
// si.bus(N) : FFcompressor_N_chan(strength,thresh,att,rel,knee,prePost,link,meter,N) : si.bus(N)
// ```
//
// Where:
//
// * `strength`: strength of the compression (0 = no compression, 1 means hard limiting, >1 means over-compression)
// * `thresh`: dB level threshold above which compression kicks in
// * `att`: attack time = time constant (sec) when level & compression going up
// * `rel`: release time = time constant (sec) coming out of compression
// * `knee`: a gradual increase in gain reduction around the threshold:
// below thresh-(knee/2) there is no gain reduction,
// above thresh+(knee/2) there is the same gain reduction as without a knee,
// and in between there is a gradual increase in gain reduction
// * `prePost`: places the level detector either at the input or after the gain computer;
// this turns it from a linear return-to-zero detector into a log  domain return-to-threshold detector
// * `link`: the amount of linkage between the channels: 0 = each channel is independent, 1 = all channels have the same amount of gain reduction
// * `meter`: a gain reduction meter. It can be implemented like so:
// `meter = _<:(_, (ba.linear2db:max(maxGR):meter_group((hbargraph("[1][unit:dB][tooltip: gain reduction in dB]", maxGR, 0))))):attach;`
// * `N`: the number of channels of the compressor, known at compile time
//
// It uses a strength parameter instead of the traditional ratio, in order to be able to
// function as a hard limiter.
// For that you'd need a ratio of infinity:1, and you cannot express that in Faust.
//
// Sometimes even bigger ratios are useful:
// for example a group recording where one instrument is recorded with both a close microphone and a room microphone,
// and the instrument is loud enough in the room mic when playing loud, but you want to boost it when it is playing soft.
//
// #### References
//
// * <http://en.wikipedia.org/wiki/Dynamic_range_compression>
// * Digital Dynamic Range Compressor Design,
// A Tutorial and Analysis,
// Dimitrios GIANNOULIS (<Dimitrios.Giannoulis@eecs.qmul.ac.uk>),
// Michael MASSBERG (<michael@massberg.org>),
// and Josuah D.REISS (<josh.reiss@eecs.qmul.ac.uk>)
//------------------------------------------------------------

declare FFcompressor_N_chan author "Bart Brouns";
declare FFcompressor_N_chan license "GPLv3";

// feed forward compressor
FFcompressor_N_chan(strength,thresh,att,rel,knee,prePost,link,meter,N) =
  si.bus(N) <: (peak_compression_gain_N_chan_db(strength,thresh,att,rel,knee,prePost,link,N),si.bus(N)) : ro.interleave(N,2) : par(i,N,(meter: ba.db2linear)*_);


//--------------------`(co.)FBcompressor_N_chan`-------------------
// Feed back N channels dynamic range compressor.
// `FBcompressor_N_chan` is a standard Faust function.
//
// #### Usage
//
// ```
// si.bus(N) : FBcompressor_N_chan(strength,thresh,att,rel,knee,prePost,link,meter,N) : si.bus(N)
// ```
//
// Where:
//
// * `strength`: strength of the compression (0 = no compression, 1 means hard limiting, >1 means over-compression)
// * `thresh`: dB level threshold above which compression kicks in
// * `att`: attack time = time constant (sec) when level & compression going up
// * `rel`: release time = time constant (sec) coming out of compression
// * `knee`: a gradual increase in gain reduction around the threshold:
// below thresh-(knee/2) there is no gain reduction,
// above thresh+(knee/2) there is the same gain reduction as without a knee,
// and in between there is a gradual increase in gain reduction
// * `prePost`: places the level detector either at the input or after the gain computer;
// this turns it from a linear return-to-zero detector into a log  domain return-to-threshold detector
// * `link`: the amount of linkage between the channels. 0 = each channel is independent, 1 = all channels have the same amount of gain reduction
// * `meter`: a gain reduction meter. It can be implemented with:
// `meter = _ <: (_,(ba.linear2db:max(maxGR):meter_group((hbargraph("[1][unit:dB][tooltip: gain reduction in dB]", maxGR, 0))))):attach;`
// or it can be omitted by defining `meter = _;`.
// * `N`: the number of channels of the compressor, known at compile time
//
// It uses a strength parameter instead of the traditional ratio, in order to be able to
// function as a hard limiter.
// For that you'd need a ratio of infinity:1, and you cannot express that in Faust.
//
// Sometimes even bigger ratios are useful:
// for example a group recording where one instrument is recorded with both a close microphone and a room microphone,
// and the instrument is loud enough in the room mic when playing loud, but you want to boost it when it is playing soft.
//
// #### References
//
// * <http://en.wikipedia.org/wiki/Dynamic_range_compression>
// * Digital Dynamic Range Compressor Design,
// A Tutorial and Analysis,
// Dimitrios GIANNOULIS (<Dimitrios.Giannoulis@eecs.qmul.ac.uk>),
// Michael MASSBERG (<michael@massberg.org>),
// and Josuah D.REISS (<josh.reiss@eecs.qmul.ac.uk>)
//------------------------------------------------------------

declare FBcompressor_N_chan author "Bart Brouns";
declare FBcompressor_N_chan license "GPLv3";

FBcompressor_N_chan(strength,thresh,att,rel,knee,prePost,link,meter,N) =
  (peak_compression_gain_N_chan_db(strength,thresh,att,rel,knee,prePost,link,N),si.bus(N) : (ro.interleave(N,2) : par(i,N,(meter : ba.db2linear)*_))) ~ si.bus(N);


//--------------------`(co.)FBFFcompressor_N_chan`-------------------
// Feed forward / feed back N channels dynamic range compressor.
// The feedback part has a much higher strength, so they end up sounding similar.
// `FBFFcompressor_N_chan` is a standard Faust function.
//
// #### Usage
//
// ```
// si.bus(N) : FBFFcompressor_N_chan(strength,thresh,att,rel,knee,prePost,link,FBFF,meter,N) : si.bus(N)
// ```
//
// Where:
//
// * `strength`: strength of the compression (0 = no compression, 1 means hard limiting, >1 means over-compression)
// * `thresh`: dB level threshold above which compression kicks in
// * `att`: attack time = time constant (sec) when level & compression going up
// * `rel`: release time = time constant (sec) coming out of compression
// * `knee`: a gradual increase in gain reduction around the threshold:
// below thresh-(knee/2) there is no gain reduction,
// above thresh+(knee/2) there is the same gain reduction as without a knee,
// and in between there is a gradual increase in gain reduction
// * `prePost`: places the level detector either at the input or after the gain computer;
// this turns it from a linear return-to-zero detector into a log  domain return-to-threshold detector
// * `link`: the amount of linkage between the channels: 0 = each channel is independent, 1 = all channels have the same amount of gain reduction
// * `FBFF`: fade between feed forward (0) and feed back (1) compression
// * `meter`: a gain reduction meter. It can be implemented like so:
// `meter = _<:(_,(max(maxGR):meter_group((hbargraph("[1][unit:dB][tooltip: gain reduction in dB]", maxGR, 0))))):attach;`
// * `N`: the number of channels of the compressor, known at compile time
//
// It uses a strength parameter instead of the traditional ratio, in order to be able to
// function as a hard limiter.
// For that you'd need a ratio of infinity:1, and you cannot express that in Faust.
//
// Sometimes even bigger ratios are useful:
// for example a group recording where one instrument is recorded with both a close microphone and a room microphone,
// and the instrument is loud enough in the room mic when playing loud, but you want to boost it when it is playing soft.
//
// #### References
//
// * <http://en.wikipedia.org/wiki/Dynamic_range_compression>
// * Digital Dynamic Range Compressor Design,
// A Tutorial and Analysis,
// Dimitrios GIANNOULIS (<Dimitrios.Giannoulis@eecs.qmul.ac.uk>),
// Michael MASSBERG (<michael@massberg.org>),
// and Josuah D.REISS (<josh.reiss@eecs.qmul.ac.uk>)
//------------------------------------------------------------

declare FBFFcompressor_N_chan author "Bart Brouns";
declare FBFFcompressor_N_chan license "GPLv3";

FBFFcompressor_N_chan(strength,thresh,att,rel,knee,prePost,link,FBFF,meter,N) =
  si.bus(N) <: si.bus(N*2) :
  (
    ((par(i,2,peak_compression_gain_N_chan_db(strength*(1+((i==0)*2)),thresh,att,rel,knee,prePost,link,N)) : ro.interleave(N,2) : par(i,N,it.interpolate_linear(FBFF))),si.bus(N))
    : (ro.interleave(N,2) : par(i,N,(meter : ba.db2linear)*_))
  )
  ~ si.bus(N);


//--------------------`(co.)RMS_compression_gain_mono_db`-------------------
// Mono RMS dynamic range compressor gain computer with dB output.
// `RMS_compression_gain_mono_db` is a standard Faust function.
//
// #### Usage
//
// ```
// _ : RMS_compression_gain_mono_db(strength,thresh,att,rel,knee,prePost) : _
// ```
//
// Where:
//
// * `strength`: strength of the compression (0 = no compression, 1 means hard limiting, >1 means over-compression)
// * `thresh`: dB level threshold above which compression kicks in
// * `att`: attack time = time constant (sec) when level & compression going up
// * `rel`: release time = time constant (sec) coming out of compression
// * `knee`: a gradual increase in gain reduction around the threshold:
// below thresh-(knee/2) there is no gain reduction,
// above thresh+(knee/2) there is the same gain reduction as without a knee,
// and in between there is a gradual increase in gain reduction
// * `prePost`: places the level detector either at the input or after the gain computer;
// this turns it from a linear return-to-zero detector into a log  domain return-to-threshold detector
//
// It uses a strength parameter instead of the traditional ratio, in order to be able to
// function as a hard limiter.
// For that you'd need a ratio of infinity:1, and you cannot express that in Faust.
//
// Sometimes even bigger ratios are useful:
// for example a group recording where one instrument is recorded with both a close microphone and a room microphone,
// and the instrument is loud enough in the room mic when playing loud, but you want to boost it when it is playing soft.
//
// #### References
//
// * <http://en.wikipedia.org/wiki/Dynamic_range_compression>
// * Digital Dynamic Range Compressor Design,
// A Tutorial and Analysis,
// Dimitrios GIANNOULIS (<Dimitrios.Giannoulis@eecs.qmul.ac.uk>),
// Michael MASSBERG (<michael@massberg.org>),
// and Josuah D.REISS (<josh.reiss@eecs.qmul.ac.uk>)
//------------------------------------------------------------

declare RMS_compression_gain_mono_db author "Bart Brouns";
declare RMS_compression_gain_mono_db license "GPLv3";

RMS_compression_gain_mono_db(strength,thresh,att,rel,knee,prePost) =
  RMS(rel) : ba.bypass1(prePost,si.onePoleSwitching(att,0)) : ba.linear2db : gain_computer(strength,thresh,knee) : ba.bypass1((prePost!=1),si.onePoleSwitching(0,att))  
  with {
    gain_computer(strength,thresh,knee,level) =
      select3((level>(thresh-(knee/2)))+(level>(thresh+(knee/2))),
            0,
            ((level-thresh+(knee/2)) : pow(2)/(2*max(ma.EPSILON,knee))),
            (level-thresh))
      : max(0)*-strength;
    RMS(time) = ba.slidingRMS(s) with {
      s = ba.sec2samp(time):int:max(1);
    };
  };

//--------------------`(co.)RMS_compression_gain_N_chan_db`-------------------
// RMS N channels dynamic range compressor gain computer with dB output.
// `RMS_compression_gain_N_chan_db` is a standard Faust function.
//
// #### Usage
//
// ```
// si.bus(N) : RMS_compression_gain_N_chan_db(strength,thresh,att,rel,knee,prePost,link,N) : si.bus(N)
// ```
//
// Where:
//
// * `strength`: strength of the compression (0 = no compression, 1 means hard limiting, >1 means over-compression)
// * `thresh`: dB level threshold above which compression kicks in
// * `att`: attack time = time constant (sec) when level & compression going up
// * `rel`: release time = time constant (sec) coming out of compression
// * `knee`: a gradual increase in gain reduction around the threshold:
// below thresh-(knee/2) there is no gain reduction,
// above thresh+(knee/2) there is the same gain reduction as without a knee,
// and in between there is a gradual increase in gain reduction
// * `prePost`: places the level detector either at the input or after the gain computer;
// this turns it from a linear return-to-zero detector into a log  domain return-to-threshold detector
// * `link`: the amount of linkage between the channels: 0 = each channel is independent, 1 = all channels have the same amount of gain reduction
// * `N`: the number of channels of the compressor
//
// It uses a strength parameter instead of the traditional ratio, in order to be able to
// function as a hard limiter.
// For that you'd need a ratio of infinity:1, and you cannot express that in Faust.
//
// Sometimes even bigger ratios are useful:
// for example a group recording where one instrument is recorded with both a close microphone and a room microphone,
// and the instrument is loud enough in the room mic when playing loud, but you want to boost it when it is playing soft.
//
// #### References
//
// * <http://en.wikipedia.org/wiki/Dynamic_range_compression>
// * Digital Dynamic Range Compressor Design,
// A Tutorial and Analysis,
// Dimitrios GIANNOULIS (<Dimitrios.Giannoulis@eecs.qmul.ac.uk>),
// Michael MASSBERG (<michael@massberg.org>),
// and Josuah D.REISS (<josh.reiss@eecs.qmul.ac.uk>)
//------------------------------------------------------------

declare RMS_compression_gain_N_chan_db author "Bart Brouns";
declare RMS_compression_gain_N_chan_db license "GPLv3";

RMS_compression_gain_N_chan_db(strength,thresh,att,rel,knee,prePost,link,1) =
  RMS_compression_gain_mono_db(strength,thresh,att,rel,knee,prePost);

RMS_compression_gain_N_chan_db(strength,thresh,att,rel,knee,prePost,link,N) =
  par(i,N,RMS_compression_gain_mono_db(strength,thresh,att,rel,knee,prePost))
  <: (si.bus(N),(ba.parallelMin(N) <: si.bus(N))) : ro.interleave(N,2) : par(i,N,(it.interpolate_linear(link)));


//--------------------`(co.)RMS_FBFFcompressor_N_chan`-------------------
// RMS feed forward / feed back N channels dynamic range compressor.
// The feedback part has a much higher strength, so they end up sounding similar.
// `RMS_FBFFcompressor_N_chan` is a standard Faust function.
//
// #### Usage
//
// ```
// si.bus(N) : RMS_FBFFcompressor_N_chan(strength,thresh,att,rel,knee,prePost,link,FBFF,meter,N) : si.bus(N)
// ```
//
// Where:
//
// * `strength`: strength of the compression (0 = no compression, 1 means hard limiting, >1 means over-compression)
// * `thresh`: dB level threshold above which compression kicks in
// * `att`: attack time = time constant (sec) when level & compression going up
// * `rel`: release time = time constant (sec) coming out of compression
// * `knee`: a gradual increase in gain reduction around the threshold:
// below thresh-(knee/2) there is no gain reduction,
// above thresh+(knee/2) there is the same gain reduction as without a knee,
// and in between there is a gradual increase in gain reduction
// * `prePost`: places the level detector either at the input or after the gain computer;
// this turns it from a linear return-to-zero detector into a log  domain return-to-threshold detector
// * `link`: the amount of linkage between the channels: 0 = each channel is independent, 1 = all channels have the same amount of gain reduction
// * `FBFF`: fade between feed forward (0) and feed back (1) compression.
// * `meter`: a gain reduction meter. It can be implemented with:
// `meter = _<:(_,(max(maxGR):meter_group((hbargraph("[1][unit:dB][tooltip: gain reduction in dB]", maxGR, 0))))):attach;`
// * `N`: the number of channels of the compressor, known at compile time
//
// It uses a strength parameter instead of the traditional ratio, in order to be able to
// function as a hard limiter.
// For that you'd need a ratio of infinity:1, and you cannot express that in Faust.
//
// Sometimes even bigger ratios are useful:
// for example a group recording where one instrument is recorded with both a close microphone and a room microphone,
// and the instrument is loud enough in the room mic when playing loud, but you want to boost it when it is playing soft.
//
// To save CPU we cheat a bit, in a similar way as in the original libs:
// instead of crosfading between two sets of gain calculators as above,
// we take the `abs` of the audio from both the FF and FB, and crossfade between those,
// and feed that into one set of gain calculators
// again the strength is much higher when in FB mode, but implemented differently.
//
// #### References
//
// * <http://en.wikipedia.org/wiki/Dynamic_range_compression>
// * Digital Dynamic Range Compressor Design,
// A Tutorial and Analysis,
// Dimitrios GIANNOULIS (<Dimitrios.Giannoulis@eecs.qmul.ac.uk>),
// Michael MASSBERG (<michael@massberg.org>),
// and Josuah D.REISS (<josh.reiss@eecs.qmul.ac.uk>)
//------------------------------------------------------------

declare RMS_FBFFcompressor_N_chan author "Bart Brouns";
declare RMS_FBFFcompressor_N_chan license "GPLv3";

RMS_FBFFcompressor_N_chan(strength,thresh,att,rel,knee,prePost,link,FBFF,meter,N) =
  si.bus(N) <: si.bus(N*2):
  (
    ((ro.interleave(N,2) : par(i,N*2,abs) :par(i,N,it.interpolate_linear(FBFF)) : RMS_compression_gain_N_chan_db(strength*(1+((FBFF*-1)+1)),thresh,att,rel,knee,prePost,link,N)),si.bus(N))
    : (ro.interleave(N,2) : par(i,N,(meter: ba.db2linear)*_))
  )
  ~ si.bus(N);


//--------------------`(co.)RMS_FBcompressor_peak_limiter_N_chan`-------------------
// N channel RMS feed back compressor into peak limiter feeding back into the FB compressor.
// By combining them this way, they complement each other optimally:
// the RMS compressor doesn't have to deal with the peaks,
// and the peak limiter get's spared from the steady state signal.
// The feedback part has a much higher strength, so they end up sounding similar.
// `RMS_FBcompressor_peak_limiter_N_chan` is a standard Faust function.
//
// #### Usage
//
// ```
// si.bus(N) : RMS_FBcompressor_peak_limiter_N_chan(strength,thresh,threshLim,att,rel,knee,link,meter,meterLim,N) : si.bus(N)
// ```
//
// Where:
//
// * `strength`: strength of the compression (0 = no compression, 1 means hard limiting, >1 means over-compression)
// * `thresh`: dB level threshold above which compression kicks in
// * `threshLim`: dB level threshold above which the brickwall limiter kicks in
// * `att`: attack time = time constant (sec) when level & compression going up
// this is also used as the release time of the limiter
// * `rel`: release time = time constant (sec) coming out of compression
// * `knee`: a gradual increase in gain reduction around the threshold:
// below thresh-(knee/2) there is no gain reduction,
// above thresh+(knee/2) there is the same gain reduction as without a knee,
// and in between there is a gradual increase in gain reduction
// the limiter uses a knee half this size
// * `link`: the amount of linkage between the channels: 0 = each channel is independent, 1 = all channels have the same amount of gain reduction
// * `meter`: compressor gain reduction meter. It can be implemented with:
// `meter = _<:(_,(max(maxGR):meter_group((hbargraph("[1][unit:dB][tooltip: gain reduction in dB]", maxGR, 0))))):attach;`
// * `meterLim`: brickwall limiter gain reduction meter. It can be implemented with:
// `meterLim = _<:(_,(max(maxGR):meter_group((hbargraph("[1][unit:dB][tooltip: gain reduction in dB]", maxGR, 0))))):attach;`
// * `N`: the number of channels of the compressor, known at compile time
//
// It uses a strength parameter instead of the traditional ratio, in order to be able to
// function as a hard limiter.
// For that you'd need a ratio of infinity:1, and you cannot express that in Faust.
//
// Sometimes even bigger ratios are useful:
// for example a group recording where one instrument is recorded with both a close microphone and a room microphone,
// and the instrument is loud enough in the room mic when playing loud, but you want to boost it when it is playing soft.
//
// #### References
//
// * <http://en.wikipedia.org/wiki/Dynamic_range_compression>
// * Digital Dynamic Range Compressor Design,
// A Tutorial and Analysis,
// Dimitrios GIANNOULIS (<Dimitrios.Giannoulis@eecs.qmul.ac.uk>),
// Michael MASSBERG (<michael@massberg.org>),
// and Josuah D.REISS (<josh.reiss@eecs.qmul.ac.uk>)
//------------------------------------------------------------

declare RMS_FBcompressor_peak_limiter_N_chan author "Bart Brouns";
declare RMS_FBcompressor_peak_limiter_N_chan license "GPLv3";

RMS_FBcompressor_peak_limiter_N_chan(strength,thresh,threshLim,att,rel,knee,link,meter,meterLim,N) =
  (((RMS_compression_gain_N_chan_db(strength,thresh,att,rel,knee,0,link,N)),si.bus(N)) : ro.interleave(N,2) : par(i,N,(meter : ba.db2linear)*_) : FFcompressor_N_chan(1,threshLim,0,att:min(rel),knee*0.5,0,link,meterLim,N))
  ~ si.bus(N);


//===========================Linear gain computer section=================================
// The gain computer functions in this section have been replaced by a version that outputs dBs,
// but we retain the linear output version for backward compatibility.
//========================================================================================
//
//--------------------`(co.)peak_compression_gain_mono`-------------------
// Mono dynamic range compressor gain computer with linear output.
// `peak_compression_gain_mono` is a standard Faust function.
//
// #### Usage
//
// ```
// _ : peak_compression_gain_mono(strength,thresh,att,rel,knee,prePost) : _
// ```
//
// Where:
//
// * `strength`: strength of the compression (0 = no compression, 1 means hard limiting, >1 means over-compression)
// * `thresh`: dB level threshold above which compression kicks in
// * `att`: attack time = time constant (sec) when level & compression going up
// * `rel`: release time = time constant (sec) coming out of compression
// * `knee`: a gradual increase in gain reduction around the threshold:
// below thresh-(knee/2) there is no gain reduction,
// above thresh+(knee/2) there is the same gain reduction as without a knee,
// and in between there is a gradual increase in gain reduction
// * `prePost`: places the level detector either at the input or after the gain computer;
// this turns it from a linear return-to-zero detector into a log  domain return-to-threshold detector
//
// It uses a strength parameter instead of the traditional ratio, in order to be able to
// function as a hard limiter.
// For that you'd need a ratio of infinity:1, and you cannot express that in Faust.
//
// Sometimes even bigger ratios are useful:
// for example a group recording where one instrument is recorded with both a close microphone and a room microphone,
// and the instrument is loud enough in the room mic when playing loud, but you want to boost it when it is playing soft.
//
// #### References
//
// * <http://en.wikipedia.org/wiki/Dynamic_range_compression>
// * Digital Dynamic Range Compressor Design,
// A Tutorial and Analysis,
// Dimitrios GIANNOULIS (<Dimitrios.Giannoulis@eecs.qmul.ac.uk>),
// Michael MASSBERG (<michael@massberg.org>),
// and Josuah D.REISS (<josh.reiss@eecs.qmul.ac.uk>)
//------------------------------------------------------------

declare peak_compression_gain_mono author "Bart Brouns";
declare peak_compression_gain_mono license "GPLv3";

peak_compression_gain_mono(strength,thresh,att,rel,knee,prePost) =
  peak_compression_gain_mono_db(strength,thresh,att,rel,knee,prePost):ba.db2linear;


//--------------------`(co.)peak_compression_gain_N_chan`-------------------
// N channels dynamic range compressor gain computer with linear output.
// `peak_compression_gain_N_chan` is a standard Faust function.
//
// #### Usage
//
// ```
// si.bus(N) : peak_compression_gain_N_chan(strength,thresh,att,rel,knee,prePost,link,N) : si.bus(N)
// ```
//
// Where:
//
// * `strength`: strength of the compression (0 = no compression, 1 means hard limiting, >1 means over-compression)
// * `thresh`: dB level threshold above which compression kicks in
// * `att`: attack time = time constant (sec) when level & compression going up
// * `rel`: release time = time constant (sec) coming out of compression
// * `knee`: a gradual increase in gain reduction around the threshold:
// below thresh-(knee/2) there is no gain reduction,
// above thresh+(knee/2) there is the same gain reduction as without a knee,
// and in between there is a gradual increase in gain reduction
// * `prePost`: places the level detector either at the input or after the gain computer;
// this turns it from a linear return-to-zero detector into a log  domain return-to-threshold detector
// * `link`: the amount of linkage between the channels: 0 = each channel is independent, 1 = all channels have the same amount of gain reduction
// * `N`: the number of channels of the compressor, known at compile time
//
// It uses a strength parameter instead of the traditional ratio, in order to be able to
// function as a hard limiter.
// For that you'd need a ratio of infinity:1, and you cannot express that in Faust.
//
// Sometimes even bigger ratios are useful:
// for example a group recording where one instrument is recorded with both a close microphone and a room microphone,
// and the instrument is loud enough in the room mic when playing loud, but you want to boost it when it is playing soft.
//
// #### References
//
// * <http://en.wikipedia.org/wiki/Dynamic_range_compression>
// * Digital Dynamic Range Compressor Design,
// A Tutorial and Analysis,
// Dimitrios GIANNOULIS (<Dimitrios.Giannoulis@eecs.qmul.ac.uk>),
// Michael MASSBERG (<michael@massberg.org>),
// and Josuah D.REISS (<josh.reiss@eecs.qmul.ac.uk>)
//------------------------------------------------------------

declare peak_compression_gain_N_chan author "Bart Brouns";
declare peak_compression_gain_N_chan license "GPLv3";

// generalise compression gains for N channels.
// first we define a mono version:
peak_compression_gain_N_chan(strength,thresh,att,rel,knee,prePost,link,N) =
  peak_compression_gain_N_chan_db(strength,thresh,att,rel,knee,prePost,link,N)
  : par(i, N, ba.db2linear);

//--------------------`(co.)RMS_compression_gain_mono`-------------------
// Mono RMS dynamic range compressor gain computer with linear output.
// `RMS_compression_gain_mono` is a standard Faust function.
//
// #### Usage
//
// ```
// _ : RMS_compression_gain_mono(strength,thresh,att,rel,knee,prePost) : _
// ```
//
// Where:
//
// * `strength`: strength of the compression (0 = no compression, 1 means hard limiting, >1 means over-compression)
// * `thresh`: dB level threshold above which compression kicks in
// * `att`: attack time = time constant (sec) when level & compression going up
// * `rel`: release time = time constant (sec) coming out of compression
// * `knee`: a gradual increase in gain reduction around the threshold:
// below thresh-(knee/2) there is no gain reduction,
// above thresh+(knee/2) there is the same gain reduction as without a knee,
// and in between there is a gradual increase in gain reduction
// * `prePost`: places the level detector either at the input or after the gain computer;
// this turns it from a linear return-to-zero detector into a log  domain return-to-threshold detector
//
// It uses a strength parameter instead of the traditional ratio, in order to be able to
// function as a hard limiter.
// For that you'd need a ratio of infinity:1, and you cannot express that in Faust.
//
// Sometimes even bigger ratios are useful:
// for example a group recording where one instrument is recorded with both a close microphone and a room microphone,
// and the instrument is loud enough in the room mic when playing loud, but you want to boost it when it is playing soft.
//
// #### References
//
// * <http://en.wikipedia.org/wiki/Dynamic_range_compression>
// * Digital Dynamic Range Compressor Design,
// A Tutorial and Analysis,
// Dimitrios GIANNOULIS (<Dimitrios.Giannoulis@eecs.qmul.ac.uk>),
// Michael MASSBERG (<michael@massberg.org>),
// and Josuah D.REISS (<josh.reiss@eecs.qmul.ac.uk>)
//------------------------------------------------------------

declare RMS_compression_gain_mono author "Bart Brouns";
declare RMS_compression_gain_mono license "GPLv3";

RMS_compression_gain_mono(strength,thresh,att,rel,knee,prePost) =
  RMS_compression_gain_mono_db(strength,thresh,att,rel,knee,prePost):ba.db2linear;


//--------------------`(co.)RMS_compression_gain_N_chan`-------------------
// RMS N channels dynamic range compressor gain computer with linear output.
// `RMS_compression_gain_N_chan` is a standard Faust function.
//
// #### Usage
//
// ```
// si.bus(N) : RMS_compression_gain_N_chan(strength,thresh,att,rel,knee,prePost,link,N) : si.bus(N)
// ```
//
// Where:
//
// * `strength`: strength of the compression (0 = no compression, 1 means hard limiting, >1 means over-compression)
// * `thresh`: dB level threshold above which compression kicks in
// * `att`: attack time = time constant (sec) when level & compression going up
// * `rel`: release time = time constant (sec) coming out of compression
// * `knee`: a gradual increase in gain reduction around the threshold:
// below thresh-(knee/2) there is no gain reduction,
// above thresh+(knee/2) there is the same gain reduction as without a knee,
// and in between there is a gradual increase in gain reduction
// * `prePost`: places the level detector either at the input or after the gain computer;
// this turns it from a linear return-to-zero detector into a log  domain return-to-threshold detector
// * `link`: the amount of linkage between the channels: 0 = each channel is independent, 1 = all channels have the same amount of gain reduction
// * `N`: the number of channels of the compressor, known at compile time
//
// It uses a strength parameter instead of the traditional ratio, in order to be able to
// function as a hard limiter.
// For that you'd need a ratio of infinity:1, and you cannot express that in Faust.
//
// Sometimes even bigger ratios are useful:
// for example a group recording where one instrument is recorded with both a close microphone and a room microphone,
// and the instrument is loud enough in the room mic when playing loud, but you want to boost it when it is playing soft.
//
// #### References
//
// * <http://en.wikipedia.org/wiki/Dynamic_range_compression>
// * Digital Dynamic Range Compressor Design,
// A Tutorial and Analysis,
// Dimitrios GIANNOULIS (<Dimitrios.Giannoulis@eecs.qmul.ac.uk>),
// Michael MASSBERG (<michael@massberg.org>),
// and Josuah D.REISS (<josh.reiss@eecs.qmul.ac.uk>)
//------------------------------------------------------------

declare RMS_compression_gain_N_chan author "Bart Brouns";
declare RMS_compression_gain_N_chan license "GPLv3";

RMS_compression_gain_N_chan(strength,thresh,att,rel,knee,prePost,link,N) =
  RMS_compression_gain_N_chan_db(strength,thresh,att,rel,knee,prePost,link,N)
  : par(i, N, ba.db2linear);


//=============================Original versions section=============================
// The functions in this section are largely superseded by the limiters above, but we
// retain them for backward compatibility and for situations in which a more permissive,
// MIT-style license is required.
//========================================================================================

//--------------------`(co.)compressor_lad_mono`-------------------
// Mono dynamic range compressor with lookahead delay.
// `compressor_lad_mono` is a standard Faust function.
//
// #### Usage
//
// ```
// _ : compressor_lad_mono(lad,ratio,thresh,att,rel) : _
// ```
//
// Where:
//
// * `lad`: lookahead delay in seconds (nonnegative) - gets rounded to nearest sample.
//          The effective attack time is a good setting
// * `ratio`: compression ratio (1 = no compression, >1 means compression)
//            Ratios: 4 is moderate compression, 8 is strong compression,
//            12 is mild limiting, and 20 is pretty hard limiting at the threshold
// * `thresh`: dB level threshold above which compression kicks in (0 dB = max level)
// * `att`: attack time = time constant (sec) when level & compression are going up
// * `rel`: release time = time constant (sec) coming out of compression
//
// #### References
//
// * <http://en.wikipedia.org/wiki/Dynamic_range_compression>
// * <https://ccrma.stanford.edu/~jos/filters/Nonlinear_Filter_Example_Dynamic.html>
// * Albert Graef's "faust2pd"/examples/synth/compressor_.dsp
// * More features: <https://github.com/magnetophon/faustCompressors>
//------------------------------------------------------------
declare compressor_lad_mono author "Julius O. Smith III";
declare compressor_lad_mono copyright
        "Copyright (C) 2014-2020 by Julius O. Smith III <jos@ccrma.stanford.edu>";
declare compressor_lad_mono license "MIT-style STK-4.3 license";
compressor_lad_mono(lad,ratio,thresh,att,rel,x)
  = x@max(0,floor(0.5+ma.SR*lad)) * compression_gain_mono(ratio,thresh,att,rel,x);

//--------------------`(co.)compressor_mono`-------------------
// Mono dynamic range compressors.
// `compressor_mono` is a standard Faust function.
//
// #### Usage
//
// ```
// _ : compressor_mono(ratio,thresh,att,rel) : _
// ```
//
// Where:
//
// * `ratio`: compression ratio (1 = no compression, >1 means compression)
//            Ratios: 4 is moderate compression, 8 is strong compression,
//            12 is mild limiting, and 20 is pretty hard limiting at the threshold
// * `thresh`: dB level threshold above which compression kicks in (0 dB = max level)
// * `att`: attack time = time constant (sec) when level & compression are going up
// * `rel`: release time = time constant (sec) coming out of compression
//
// #### References
//
// * <http://en.wikipedia.org/wiki/Dynamic_range_compression>
// * <https://ccrma.stanford.edu/~jos/filters/Nonlinear_Filter_Example_Dynamic.html>
// * Albert Graef's "faust2pd"/examples/synth/compressor_.dsp
// * More features: <https://github.com/magnetophon/faustCompressors>
//------------------------------------------------------------
declare compressor_mono author "Julius O. Smith III";
declare compressor_mono copyright
        "Copyright (C) 2014-2020 by Julius O. Smith III <jos@ccrma.stanford.edu>";
declare compressor_mono license "MIT-style STK-4.3 license";
compressor_mono = compressor_lad_mono(0);

//--------------------`(co.)compressor_stereo`-------------------
// Stereo dynamic range compressors.
//
// #### Usage
//
// ```
// _,_ : compressor_stereo(ratio,thresh,att,rel) : _,_
// ```
//
// Where:
//
// * `ratio`: compression ratio (1 = no compression, >1 means compression)
// * `thresh`: dB level threshold above which compression kicks in (0 dB = max level)
// * `att`: attack time = time constant (sec) when level & compression going up
// * `rel`: release time = time constant (sec) coming out of compression
//
// #### References
//
// * <http://en.wikipedia.org/wiki/Dynamic_range_compression>
// * <https://ccrma.stanford.edu/~jos/filters/Nonlinear_Filter_Example_Dynamic.html>
// * Albert Graef's "faust2pd"/examples/synth/compressor_.dsp
// * More features: <https://github.com/magnetophon/faustCompressors>
//------------------------------------------------------------
declare compressor_stereo author "Julius O. Smith III";
declare compressor_stereo copyright
        "Copyright (C) 2014-2020 by Julius O. Smith III <jos@ccrma.stanford.edu>";
declare compressor_stereo license "MIT-style STK-4.3 license";
compressor_stereo(ratio,thresh,att,rel,x,y) = cgm*x, cgm*y with {
  cgm = compression_gain_mono(ratio,thresh,att,rel,abs(x)+abs(y));
};

//--------------------`(co.)compression_gain_mono`-------------------
// Compression-gain calculation for dynamic range compressors.
//
// #### Usage
//
// ```
// _ : compression_gain_mono(ratio,thresh,att,rel) : _
// ```
//
// Where:
//
// * `ratio`: compression ratio (1 = no compression, >1 means compression)
// * `thresh`: dB level threshold above which compression kicks in (0 dB = max level)
// * `att`: attack time = time constant (sec) when level & compression going up
// * `rel`: release time = time constant (sec) coming out of compression
//
// #### References
//
// * <http://en.wikipedia.org/wiki/Dynamic_range_compression>
// * <https://ccrma.stanford.edu/~jos/filters/Nonlinear_Filter_Example_Dynamic.html>
// * Albert Graef's "faust2pd"/examples/synth/compressor_.dsp
// * More features: <https://github.com/magnetophon/faustCompressors>
//------------------------------------------------------------
declare compression_gain_mono author "Julius O. Smith III";
declare compression_gain_mono copyright
        "Copyright (C) 2014-2020 by Julius O. Smith III <jos@ccrma.stanford.edu>";
declare compression_gain_mono license "MIT-style STK-4.3 license";
compression_gain_mono(ratio,thresh,att,rel) =
  an.amp_follower_ar(att,rel) : ba.linear2db : outminusindb(ratio,thresh) :
  kneesmooth(att) : ba.db2linear
with {
  // kneesmooth(att) installs a "knee" in the dynamic-range compression,
  // where knee smoothness is set equal to half that of the compression-attack.
  // A general 'knee' parameter could be used instead of tying it to att/2:
  kneesmooth(att) = si.smooth(ba.tau2pole(att/2.0));
  // compression gain in dB:
   outminusindb(ratio,thresh,level) = max(level-thresh,0.0) * (1.0/max(ma.EPSILON,float(ratio))-1.0);
  // Note: "float(ratio)" REQUIRED when ratio is an integer > 1!
};

//----------------`(co.)limiter_1176_R4_mono`----------------------
// A limiter guards against hard-clipping.  It can be
// implemented as a compressor having a high threshold (near the
// clipping level), fast attack, and high ratio.  Since
// the compression ratio is so high, some knee smoothing is
// desirable (for softer limiting).  This example is intended
// to get you started using compressors as limiters, so all
// parameters are hardwired here to nominal values.
//
// `ratio`: 4 (moderate compression).
//        See `compressor_mono` comments for a guide to other choices.
//        Mike Shipley likes this (lowest) setting on the 1176.
//        (Grammy award-winning mixer for Queen, Tom Petty, etc.).
//
// `thresh`: -6 dB, meaning 4:1 compression begins at amplitude 1/2.
//
// `att`: 800 MICROseconds (Note: scaled by ratio in the 1176)
//         The 1176 range is said to be 20-800 microseconds.
//         Faster attack gives "more bite" (e.g. on vocals),
//         and makes hard-clipping less likely on fast overloads.
//
// `rel`: 0.5 s (Note: scaled by ratio in the 1176)
//         The 1176 range is said to be 50-1100 ms.
//
// The 1176 also has a "bright, clear eq effect" (use filters.lib if desired).
// `limiter_1176_R4_mono` is a standard Faust function.
//
// #### Usage
//
// ```
//  _ : limiter_1176_R4_mono : _
// ```
//
// #### Reference:
//
// <http://en.wikipedia.org/wiki/1176_Peak_Limiter>
//------------------------------------------------------------
declare limiter_1176_R4_mono author "Julius O. Smith III";
declare limiter_1176_R4_mono copyright
        "Copyright (C) 2014-2020 by Julius O. Smith III <jos@ccrma.stanford.edu>";
declare limiter_1176_R4_mono license "MIT-style STK-4.3 license";
limiter_1176_R4_mono = compressor_mono(4,-6,0.0008,0.5);


//-------------------`(co.)limiter_1176_R4_stereo`---------------------
// A limiter guards against hard-clipping.  It can be
// implemented as a compressor having a high threshold (near the
// clipping level), fast attack and release, and high ratio.  Since
// the ratio is so high, some knee smoothing is
// desirable ("soft limiting").  This example is intended
// to get you started using `compressor_*` as a limiter, so all
// parameters are hardwired to nominal values here.
// 
// `ratio`: 4 (moderate compression), 8 (severe compression),
//          12 (mild limiting), or 20 to 1 (hard limiting).
//
// `att`: 20-800 MICROseconds (Note: scaled by ratio in the 1176).
//
// `rel`: 50-1100 ms (Note: scaled by ratio in the 1176).
//
// Mike Shipley likes 4:1 (Grammy-winning mixer for Queen, Tom Petty, etc.)
// Faster attack gives "more bite" (e.g. on vocals).
// He hears a bright, clear eq effect as well (not implemented here).
//
// #### Usage
//
// ```
//  _,_ : limiter_1176_R4_stereo : _,_
// ```
//
// #### Reference:
//
// <http://en.wikipedia.org/wiki/1176_Peak_Limiter>
//------------------------------------------------------------
declare limiter_1176_R4_stereo author "Julius O. Smith III";
declare limiter_1176_R4_stereo copyright
        "Copyright (C) 2014-2020 by Julius O. Smith III <jos@ccrma.stanford.edu>";
declare limiter_1176_R4_stereo license "MIT-style STK-4.3 license";
limiter_1176_R4_stereo = compressor_stereo(4,-6,0.0008,0.5);


//==================================Expanders=============================================
//========================================================================================

//--------------------`(co.)peak_expansion_gain_N_chan_db`-------------------
// N channels dynamic range expander gain computer.
// `peak_expansion_gain_N_chan_db` is a standard Faust function.
//
// #### Usage
//
// ```
// si.bus(N) : peak_expansion_gain_N_chan_db(strength,thresh,range,att,hold,rel,knee,prePost,link,maxHold,N) : si.bus(N)
// ```
//
// Where:
//
// * `strength`: strength of the expansion (0 = no expansion, 100 means gating, <1 means upward compression)
// * `thresh`: dB level threshold below which expansion kicks in
// * `range`: maximum amount of expansion in dB
// * `att`: attack time = time constant (sec) coming out of expansion
// * `hold` : hold time (sec)
// * `rel`: release time = time constant (sec) going into expansion
// * `knee`: a gradual increase in gain reduction around the threshold:
// above thresh+(knee/2) there is no gain reduction,
// below thresh-(knee/2) there is the same gain reduction as without a knee,
// and in between there is a gradual increase in gain reduction
// * `prePost`: places the level detector either at the input or after the gain computer;
// this turns it from a linear return-to-zero detector into a log  domain return-to-range detector
// * `link`: the amount of linkage between the channels: 0 = each channel is independent, 1 = all channels have the same amount of gain reduction
// * `maxHold`: the maximum hold time in samples, known at compile time
// * `N`: the number of channels of the gain computer, known at compile time
//
//------------------------------------------------------------

declare peak_expansion_gain_N_chan_db author "Bart Brouns";
declare peak_expansion_gain_N_chan_db license "GPLv3";

// generalise expansion gains for N channels.
// first we define a mono version:
peak_expansion_gain_N_chan_db(strength,thresh,range,att,hold,rel,knee,prePost,link,maxHold,1) =
  peak_expansion_gain_mono_db(maxHold,strength,thresh,range,att,hold,rel,knee,prePost);

// The actual N-channels version:
// Calculate the maximum gain reduction of N channels,
// and then crossfade between that and each channel's own gain reduction,
// to link/unlink channels
peak_expansion_gain_N_chan_db(strength,thresh,range,att,hold,rel,knee,prePost,link,maxHold,N) =
  par(i, N, peak_expansion_gain_mono_db(maxHold,strength,thresh,range,att,hold,rel,knee,prePost))

  <: (si.bus(N),(ba.parallelMax(N) <: si.bus(N))) : ro.interleave(N,2) : par(i,N,(it.interpolate_linear(link)));


peak_expansion_gain_mono_db(maxHold,strength,thresh,range,attack,hold,release,knee,prePost) =
  level(hold,maxHold):ba.bypass1(prePost,si.lag_ud(attack,release)) :ba.linear2db : gain_computer(strength,thresh,range,knee) : ba.bypass1((prePost !=1),si.lag_ud(att,rel))
with {
  gain_computer(strength,thresh,range,knee,level) =
    (select3((level>(thresh-(knee/2)))+(level>(thresh+(knee/2)))
             , (level-thresh)
             , ((level-thresh-(knee/2)):pow(2) /(min(ma.EPSILON,knee*-2)))
             , 0
             ) *abs(strength):max(range) * (-1+(2*(strength>0)))
    );
  att = select2((strength>0),release,attack);
  rel = select2((strength>0),attack,release);
  level(hold,maxHold,x) = x : abs : ba.slidingMax(hold*ma.SR,maxHold);
};


//--------------------`(co.)expander_N_chan`-------------------
// Feed forward N channels dynamic range expander.
// `expander_N_chan` is a standard Faust function.
//
// #### Usage
//
// ```
// si.bus(N) : expander_N_chan(strength,thresh,range,att,hold,rel,knee,prePost,link,meter,maxHold,N) : si.bus(N)
// ```
//
// Where:
//
// * `strength`: strength of the expansion (0 = no expansion, 100 means gating, <1 means upward compression)
// * `thresh`: dB level threshold below which expansion kicks in
// * `range`: maximum amount of expansion in dB
// * `att`: attack time = time constant (sec) coming out of expansion
// * `hold` : hold time
// * `rel`: release time = time constant (sec) going into expansion
// * `knee`: a gradual increase in gain reduction around the threshold:
// above thresh+(knee/2) there is no gain reduction,
// below thresh-(knee/2) there is the same gain reduction as without a knee,
// and in between there is a gradual increase in gain reduction
// * `prePost`: places the level detector either at the input or after the gain computer;
// this turns it from a linear return-to-zero detector into a log  domain return-to-range detector
// * `link`: the amount of linkage between the channels: 0 = each channel is independent, 1 = all channels have the same amount of gain reduction
// * `meter`: a gain reduction meter. It can be implemented like so:
// `meter = _<:(_, (ba.linear2db:max(maxGR):meter_group((hbargraph("[1][unit:dB][tooltip: gain reduction in dB]", maxGR, 0))))):attach;`
// * `maxHold`: the maximum hold time in samples, known at compile time
// * `N`: the number of channels of the expander, known at compile time
//
//------------------------------------------------------------

declare expander_N_chan author "Bart Brouns";
declare expander_N_chan license "GPLv3";

// Feed forward expander
expander_N_chan(strength,thresh,range,att,hold,rel,knee,prePost,link,meter,maxHold,N) =
  expanderSC_N_chan(strength,thresh,range,att,hold,rel,knee,prePost,link,meter,maxHold,N,_,0,0);

//--------------------`(co.)expanderSC_N_chan`-------------------
// Feed forward N channels dynamic range expander with sidechain.
// `expanderSC_N_chan` is a standard Faust function.
//
// #### Usage
//
// ```
// si.bus(N) : expanderSC_N_chan(strength,thresh,range,att,hold,rel,knee,prePost,link,meter,maxHold,N,SCfunction,SCswitch,SCsignal) : si.bus(N)
// ```
//
// Where:
//
// * `strength`: strength of the expansion (0 = no expansion, 100 means gating, <1 means upward compression)
// * `thresh`: dB level threshold below which expansion kicks in
// * `range`: maximum amount of expansion in dB
// * `att`: attack time = time constant (sec) coming out of expansion
// * `hold` : hold time
// * `rel`: release time = time constant (sec) going into expansion
// * `knee`: a gradual increase in gain reduction around the threshold:
// above thresh+(knee/2) there is no gain reduction,
// below thresh-(knee/2) there is the same gain reduction as without a knee,
// and in between there is a gradual increase in gain reduction
// * `prePost`: places the level detector either at the input or after the gain computer;
// this turns it from a linear return-to-zero detector into a log  domain return-to-range detector
// * `link`: the amount of linkage between the channels: 0 = each channel is independent, 1 = all channels have the same amount of gain reduction
// * `meter`: a gain reduction meter. It can be implemented like so:
// `meter = _<:(_, (ba.linear2db:max(maxGR):meter_group((hbargraph("[1][unit:dB][tooltip: gain reduction in dB]", maxGR, 0))))):attach;`
// * `maxHold`: the maximum hold time in samples, known at compile time
// * `N`: the number of channels of the expander, known at compile time
// * `SCfunction` : a function that get's placed before the level-detector, needs to have a single input and output
// * `SCswitch` : use either the regular audio input or the SCsignal as the input for the level detector
// * `SCsignal` : an audio signal, to be used as the input for the level detector when SCswitch is 1
//
//------------------------------------------------------------

declare expanderSC_N_chan author "Bart Brouns";
declare expanderSC_N_chan license "GPLv3";

// Feed forward expander with sidechain
expanderSC_N_chan(strength,thresh,range,att,hold,rel,knee,prePost,link,meter,maxHold,N,SCfunction,SCswitch,SCsignal) =
  si.bus(N) <:
  ((par(i, N, select2(SCswitch,_,SCsignal):SCfunction)
    : peak_expansion_gain_N_chan_db(strength,thresh,range,att,hold,rel,knee,prePost,link,maxHold,N))
  ,si.bus(N))
  : ro.interleave(N,2)
  : par(i,N,(meter:ba.db2linear)*_);


//=============================Lookahead Limiters========================================
//========================================================================================

//-----------------------`(co.)limiter_lad_N`---------------------------------
// N-channels lookahead limiter inspired by IOhannes Zmölnig's post, which is 
// in turn based on the thesis by Peter Falkner "Entwicklung eines digitalen
// Stereo-Limiters mit Hilfe des Signalprozessors DSP56001".
// This version of the limiter uses a peak-holder with smoothed
// attack and release based on tau time constant filters.
//
// It is also possible to use a time constant that is `2PI*tau` by dividing 
// the attack and release times by `2PI`. This time constant allows for 
// the amplitude profile to reach `1 - e^(-2PI)` of the final 
// peak after the attack time. The input path can be delayed by the same 
// amount as the attack time to synchronise input and amplitude profile, 
// realising a system that is particularly effective as a colourless
// (ideally) brickwall limiter.
//
// Note that the effectiveness of the ceiling settings are dependent on
// the other parameters, especially the time constant used for the
// smoothing filters and the lookahead delay. 
//
// Similarly, the colourless characteristics are also dependent on attack,
// hold, and release times. Since fluctuations above ~15 Hz are
// perceived as timbral effects, [Vassilakis and Kendall 2010] it is
// reasonable to set the attack time to 1/15 seconds for a smooth amplitude
// modulation. On the other hand, the hold time can be set to the
// peak-to-peak period of the expected lowest frequency in the signal,
// which allows for minimal distortion of the low frequencies. The
// release time can then provide a perceptually linear and gradual gain 
// increase determined by the user for any specific application.
//
// The scaling factor for all the channels is determined by the loudest peak 
// between them all, so that amplitude ratios between the signals are kept.
//
// #### Usage
//
// ```
// si.bus(N) : limiter_lad_N(N, LD, ceiling, attack, hold, release) : si.bus(N)
// ```
//
// Where:
//
// * `N`: is the number of channels, known at compile-time
// * `LD`: is the lookahead delay in seconds, known at compile-time
// * `ceiling`: is the linear amplitude output limit
// * `attack`: is the attack time in seconds
// * `hold`: is the hold time in seconds
// * `release`: is the release time in seconds
//
// Example for a stereo limiter: `limiter_lad_N(2, .01, 1, .01, .1, 1);`
//
// #### Reference:
//
// <http://iem.at/~zmoelnig/publications/limiter>
//------------------------------------------------------------------------------
declare limiter_lad_N author "Dario Sanfilippo";
declare limiter_lad_N copyright "Copyright (C) 2020 Dario Sanfilippo
      <sanfilippo.dario@gmail.com>";
declare limiter_lad_N license "GPLv3 license";
limiter_lad_N(N, LD, ceiling, attack, hold, release) = 
      si.bus(N) <: par(i, N, @(LD * ma.SR)), 
                   (scaling <: si.bus(N)) : ro.interleave(N, 2) : par(i, N, *)
      with {
           scaling = ceiling / max(amp_profile, ma.EPSILON) : min(1);
           amp_profile = par(i, N, abs) : maxN(N) : ba.peakholder(hold * ma.SR) :
               att_smooth(attack) : rel_smooth(release);
           att_smooth(time, in) = si.smooth(ba.tau2pole(time), in);
           rel_smooth(time, in) = an.peak_envelope(time, in);
           maxN(1) = _;
           maxN(2) = max;
           maxN(N) = max(maxN(N - 1));
      };

//-------------`(co.)limiter_lad_mono`----------------------------------------
//
// Specialised case of `limiter_lad_N` mono limiter.
//
// #### Usage
//
// ```
// _ : limiter_lad_mono(LD, ceiling, attack, hold, release) : _
// ```
//
// Where:
//
// * `LD`: is the lookahead delay in seconds, known at compile-time
// * `ceiling`: is the linear amplitude output limit
// * `attack`: is the attack time in seconds
// * `hold`: is the hold time in seconds
// * `release`: is the release time in seconds
//
// #### Reference:
//
// <http://iem.at/~zmoelnig/publications/limiter>
//------------------------------------------------------------------------------
declare limiter_lad_mono author "Dario Sanfilippo";
declare limiter_lad_mono copyright "Copyright (C) 2020 Dario Sanfilippo
      <sanfilippo.dario@gmail.com>";
declare limiter_lad_mono license "GPLv3 license";
limiter_lad_mono(LD) = limiter_lad_N(1, LD);

//-------------`(co.)limiter_lad_stereo`--------------------------------------
//
// Specialised case of `limiter_lad_N` stereo limiter.
//
// #### Usage
//
// ```
// _,_ : limiter_lad_stereo(LD, ceiling, attack, hold, release) : _,_
// ```
//
// Where:
//
// * `LD`: is the lookahead delay in seconds, known at compile-time
// * `ceiling`: is the linear amplitude output limit
// * `attack`: is the attack time in seconds
// * `hold`: is the hold time in seconds
// * `release`: is the release time in seconds
//
// #### Reference:
//
// <http://iem.at/~zmoelnig/publications/limiter>
//------------------------------------------------------------------------------
declare limiter_lad_stereo author "Dario Sanfilippo";
declare limiter_lad_stereo copyright "Copyright (C) 2020 Dario Sanfilippo
      <sanfilippo.dario@gmail.com>";
declare limiter_lad_stereo license "GPLv3 license";
limiter_lad_stereo(LD) = limiter_lad_N(2, LD);

//-------------`(co.)limiter_lad_quad`----------------------------------------
//
// Specialised case of `limiter_lad_N` quadraphonic limiter.
//
// #### Usage
//
// ```
// si.bus(4) : limiter_lad_quad(LD, ceiling, attack, hold, release) : si.bus(4)
// ```
//
// Where:
//
// * `LD`: is the lookahead delay in seconds, known at compile-time
// * `ceiling`: is the linear amplitude output limit
// * `attack`: is the attack time in seconds
// * `hold`: is the hold time in seconds
// * `release`: is the release time in seconds
//
// #### Reference:
//
// <http://iem.at/~zmoelnig/publications/limiter>
//------------------------------------------------------------------------------
declare limiter_lad_quad author "Dario Sanfilippo";
declare limiter_lad_quad copyright "Copyright (C) 2020 Dario Sanfilippo
      <sanfilippo.dario@gmail.com>";
declare limiter_lad_quad license "GPLv3 license";
limiter_lad_quad(LD) = limiter_lad_N(4, LD);

//-------------`(co.)limiter_lad_bw`-----------------------------------------
//
// Specialised case of `limiter_lad_N` and ready-to-use unit-amplitude mono 
// limiting function. This implementation, in particular, uses `2PI*tau`
// time constant filters for attack and release smoothing with
// synchronised input and gain signals. 
//
// This function's best application is to be used as a brickwall limiter with 
// the least colouring artefacts while keeping a not-so-slow release curve. 
// Tests have shown that, given a pop song with 60 dB of amplification
// and a 0-dB-ceiling, the loudest peak recorded was ~0.38 dB.
//
// #### Usage
//
// ```
// _ : limiter_lad_bw : _
// ```
//
// #### Reference:
//
// <http://iem.at/~zmoelnig/publications/limiter>
//------------------------------------------------------------------------------
declare limiter_lad_bw author "Dario Sanfilippo";
declare limiter_lad_bw copyright "Copyright (C) 2020 Dario Sanfilippo
      <sanfilippo.dario@gmail.com>";
declare limiter_lad_bw license "GPLv3 license";
limiter_lad_bw = limiter_lad_mono(.01, 1, 0.01/twopi, .1, 1/twopi)
with {
    twopi = 2 * ma.PI;
};