forked from grame-cncm/faustlibraries
-
Notifications
You must be signed in to change notification settings - Fork 0
/
analyzers.lib
980 lines (891 loc) · 37 KB
/
analyzers.lib
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
//################################ analyzers.lib ##########################################
// Analyzers library. Its official prefix is `an`.
//
// #### References
// * <https://github.com/grame-cncm/faustlibraries/blob/master/analyzers.lib>
//########################################################################################
ma = library("maths.lib");
ba = library("basics.lib");
ro = library("routes.lib");
si = library("signals.lib");
fi = library("filters.lib");
an = library("analyzers.lib"); // for compatible copy/paste out of this file
declare name "Faust Analyzer Library";
declare version "1.2.0";
/************************************************************************
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 <[email protected]>
([jos](http://ccrma.stanford.edu/~jos/)), and released under the
(MIT-style) [STK-4.3](#stk-4.3-license) license.
All MarkDown comments in this section is Copyright 2016-2017 by Romain
Michon and Julius O. Smith III, and is released under the
[CCA4I](https://creativecommons.org/licenses/by/4.0/) license (TODO: if/when Romain agrees)
************************************************************************/
//==============================Amplitude Tracking========================================
//========================================================================================
//------------------`(an.)abs_envelope_rect`-----------------------------------
// Absolute value average with moving-average algorithm.
//
// #### Usage
//
// ```
// _ : abs_envelope_rect(period) : _
// ```
//
// Where:
//
// * `period`: sets the averaging frame in seconds
//-----------------------------------------------------------------------------
declare abs_envelope_rect author "Dario Sanfilippo and Julius O. Smith III";
declare abs_envelope_rect copyright "Copyright (C) 2020 Dario Sanfilippo
<[email protected]> and
2003-2020 by Julius O. Smith III <[email protected]>";
declare abs_envelope_rect license "MIT-style STK-4.3 license";
abs_envelope_rect(period, x) = abs(x) : fi.avg_rect(period);
//------------------`(an.)abs_envelope_tau`------------------------------------
// Absolute value average with one-pole lowpass and tau response
// (see [filters.lib](https://faustlibraries.grame.fr/libs/filters/)).
//
// #### Usage
//
// ```
// _ : abs_envelope_tau(period) : _
// ```
//
// Where:
//
// * `period`: (time to decay by 1/e) sets the averaging frame in secs
//-----------------------------------------------------------------------------
declare abs_envelope_tau author "Dario Sanfilippo and Julius O. Smith III";
declare abs_envelope_tau copyright "Copyright (C) 2020 Dario Sanfilippo
<[email protected]> and
2003-2020 by Julius O. Smith III <[email protected]>";
declare abs_envelope_tau license "MIT-style STK-4.3 license";
abs_envelope_tau(period, x) = abs(x) : fi.avg_tau(period);
//------------------`(an.)abs_envelope_t60`------------------------------------
// Absolute value average with one-pole lowpass and t60 response
// (see [filters.lib](https://faustlibraries.grame.fr/libs/filters/)).
//
// #### Usage
//
// ```
// _ : abs_envelope_t60(period) : _
// ```
//
// Where:
//
// * `period`: (time to decay by 60 dB) sets the averaging frame in secs
//-----------------------------------------------------------------------------
declare abs_envelope_t60 author "Dario Sanfilippo and Julius O. Smith III";
declare abs_envelope_t60 copyright "Copyright (C) 2020 Dario Sanfilippo
<[email protected]> and
2003-2020 by Julius O. Smith III <[email protected]>";
declare abs_envelope_t60 license "MIT-style STK-4.3 license";
abs_envelope_t60(period, x) = abs(x) : fi.avg_t60(period);
//------------------`(an.)abs_envelope_t19`------------------------------------
// Absolute value average with one-pole lowpass and t19 response
// (see [filters.lib](https://faustlibraries.grame.fr/libs/filters/)).
//
// #### Usage
//
// ```
// _ : abs_envelope_t19(period) : _
// ```
//
// Where:
//
// * `period`: (time to decay by 1/e^2.2) sets the averaging frame in secs
//-----------------------------------------------------------------------------
declare abs_envelope_t19 author "Dario Sanfilippo and Julius O. Smith III";
declare abs_envelope_t19 copyright "Copyright (C) 2020 Dario Sanfilippo
<[email protected]> and
2003-2020 by Julius O. Smith III <[email protected]>";
declare abs_envelope_t19 license "MIT-style STK-4.3 license";
abs_envelope_t19(period, x) = abs(x) : fi.avg_t19(period);
//---------------------------`(an.)amp_follower`---------------------------
// Classic analog audio envelope follower with infinitely fast rise and
// exponential decay. The amplitude envelope instantaneously follows
// the absolute value going up, but then floats down exponentially.
//
// `amp_follower` is a standard Faust function.
//
// #### Usage
//
// ```
// _ : amp_follower(rel) : _
// ```
//
// Where:
//
// * `rel`: release time = amplitude-envelope time-constant (sec) going down
//
// #### References
//
// * Musical Engineer's Handbook, Bernie Hutchins, Ithaca NY
// * 1975 Electronotes Newsletter, Bernie Hutchins
//------------------------------------------------------------
amp_follower(rel) = abs : env with {
p = ba.tau2pole(rel);
env(x) = x * (1.0 - p) : (+ : max(x,_)) ~ *(p);
};
peak_envelope = amp_follower; // Synonym for more standard naming
//---------------------------`(an.)amp_follower_ud`---------------------------
// Envelope follower with different up and down time-constants
// (also called a "peak detector").
//
// #### Usage
//
// ```
// _ : amp_follower_ud(att,rel) : _
// ```
//
// Where:
//
// * `att`: attack time = amplitude-envelope time constant (sec) going up
// * `rel`: release time = amplitude-envelope time constant (sec) going down
//
// #### Note
//
// We assume rel >> att. Otherwise, consider rel ~ max(rel,att).
// For audio, att is normally faster (smaller) than rel (e.g., 0.001 and 0.01).
// Use `amp_follower_ar` below to remove this restriction.
//
// #### Reference
//
// * "Digital Dynamic Range Compressor Design --- A Tutorial and Analysis", by
// Dimitrios Giannoulis, Michael Massberg, and Joshua D. Reiss
// <https://www.eecs.qmul.ac.uk/~josh/documents/2012/GiannoulisMassbergReiss-dynamicrangecompression-JAES2012.pdf>
//------------------------------------------------------------
amp_follower_ud(att,rel) = amp_follower(rel) : si.smooth(ba.tau2pole(att));
//---------------`(an.)amp_follower_ar`----------------
// Envelope follower with independent attack and release times. The
// release can be shorter than the attack (unlike in `amp_follower_ud`
// above).
//
// #### Usage
//
// ```
// _ : amp_follower_ar(att,rel) : _
// ```
//
// Where:
//
// * `att`: attack time = amplitude-envelope time constant (sec) going up
// * `rel`: release time = amplitude-envelope time constant (sec) going down
//
//---------------------------------------------------------
declare amp_follower_ar author "Jonatan Liljedahl, revised by Romain Michon";
amp_follower_ar(att,rel) = abs : si.onePoleSwitching(att,rel);
//------------------`(an.)ms_envelope_rect`------------------------------------
// Mean square with moving-average algorithm.
//
// #### Usage
//
// ```
// _ : ms_envelope_rect(period) : _
// ```
//
// Where:
//
// * `period`: sets the averaging frame in secs
//-----------------------------------------------------------------------------
declare ms_envelope_rect author "Dario Sanfilippo and Julius O. Smith III";
declare ms_envelope_rect copyright "Copyright (C) 2020 Dario Sanfilippo
<[email protected]> and
2003-2020 by Julius O. Smith III <[email protected]>";
declare ms_envelope_rect license "MIT-style STK-4.3 license";
ms_envelope_rect(period, x) = x * x : fi.avg_rect(period);
//------------------`(an.)ms_envelope_tau`-------------------------------------
// Mean square average with one-pole lowpass and tau response
// (see [filters.lib](https://faustlibraries.grame.fr/libs/filters/)).
//
// #### Usage
//
// ```
// _ : ms_envelope_tau(period) : _
// ```
//
// Where:
//
// * `period`: (time to decay by 1/e) sets the averaging frame in secs
//-----------------------------------------------------------------------------
declare ms_envelope_tau author "Dario Sanfilippo and Julius O. Smith III";
declare ms_envelope_tau copyright "Copyright (C) 2020 Dario Sanfilippo
<[email protected]> and
2003-2020 by Julius O. Smith III <[email protected]>";
declare ms_envelope_tau license "MIT-style STK-4.3 license";
ms_envelope_tau(period, x) = x * x : fi.avg_tau(period);
//------------------`(an.)ms_envelope_t60`-------------------------------------
// Mean square with one-pole lowpass and t60 response
// (see [filters.lib](https://faustlibraries.grame.fr/libs/filters/)).
//
// #### Usage
//
// ```
// _ : ms_envelope_t60(period) : _
// ```
//
// Where:
//
// * `period`: (time to decay by 60 dB) sets the averaging frame in secs
//-----------------------------------------------------------------------------
declare ms_envelope_t60 author "Dario Sanfilippo and Julius O. Smith III";
declare ms_envelope_t60 copyright "Copyright (C) 2020 Dario Sanfilippo
<[email protected]> and
2003-2020 by Julius O. Smith III <[email protected]>";
declare ms_envelope_t60 license "MIT-style STK-4.3 license";
ms_envelope_t60(period, x) = x * x : fi.avg_t60(period);
//------------------`(an.)ms_envelope_t19`-------------------------------------
// Mean square with one-pole lowpass and t19 response
// (see [filters.lib](https://faustlibraries.grame.fr/libs/filters/)).
//
// #### Usage
//
// ```
// _ : ms_envelope_t19(period) : _
// ```
//
// Where:
//
// * `period`: (time to decay by 1/e^2.2) sets the averaging frame in secs
//-----------------------------------------------------------------------------
declare ms_envelope_t19 author "Dario Sanfilippo and Julius O. Smith III";
declare ms_envelope_t19 copyright "Copyright (C) 2020 Dario Sanfilippo
<[email protected]> and
2003-2020 by Julius O. Smith III <[email protected]>";
declare ms_envelope_t19 license "MIT-style STK-4.3 license";
ms_envelope_t19(period, x) = x * x : fi.avg_t19(period);
//------------------`(an.)rms_envelope_rect`-----------------------------------
// Root mean square with moving-average algorithm.
//
// #### Usage
//
// ```
// _ : rms_envelope_rect(period) : _
// ```
//
// Where:
//
// * `period`: sets the averaging frame in secs
//-----------------------------------------------------------------------------
declare rms_envelope_rect author "Dario Sanfilippo and Julius O. Smith III";
declare rms_envelope_rect copyright "Copyright (C) 2020 Dario Sanfilippo
<[email protected]> and
2003-2020 by Julius O. Smith III <[email protected]>";
declare rms_envelope_rect license "MIT-style STK-4.3 license";
rms_envelope_rect(period, x) = ms_envelope_rect(period, x) : sqrt;
//------------------`(an.)rms_envelope_tau`------------------------------------
// Root mean square with one-pole lowpass and tau response
// (see [filters.lib](https://faustlibraries.grame.fr/libs/filters/)).
//
// #### Usage
//
// ```
// _ : rms_envelope_tau(period) : _
// ```
//
// Where:
//
// * `period`: (time to decay by 1/e) sets the averaging frame in secs
//-----------------------------------------------------------------------------
declare rms_envelope_tau author "Dario Sanfilippo and Julius O. Smith III";
declare rms_envelope_tau copyright "Copyright (C) 2020 Dario Sanfilippo
<[email protected]> and
2003-2020 by Julius O. Smith III <[email protected]>";
declare rms_envelope_tau license "MIT-style STK-4.3 license";
rms_envelope_tau(period, x) = ms_envelope_tau(period, x) : sqrt;
//------------------`(an.)rms_envelope_t60`------------------------------------
// Root mean square with one-pole lowpass and t60 response
// (see [filters.lib](https://faustlibraries.grame.fr/libs/filters/)).
//
// #### Usage
//
// ```
// _ : rms_envelope_t60(period) : _
// ```
//
// Where:
//
// * `period`: (time to decay by 60 dB) sets the averaging frame in secs
//-----------------------------------------------------------------------------
declare rms_envelope_t60 author "Dario Sanfilippo and Julius O. Smith III";
declare rms_envelope_t60 copyright "Copyright (C) 2020 Dario Sanfilippo
<[email protected]> and
2003-2020 by Julius O. Smith III <[email protected]>";
declare rms_envelope_t60 license "MIT-style STK-4.3 license";
rms_envelope_t60(period, x) = ms_envelope_t60(period, x) : sqrt;
//------------------`(an.)rms_envelope_t19`------------------------------------
// Root mean square with one-pole lowpass and t19 response
// (see [filters.lib](https://faustlibraries.grame.fr/libs/filters/)).
//
// #### Usage
//
// ```
// _ : rms_envelope_t19(period) : _
// ```
//
// Where:
//
// * `period`: (time to decay by 1/e^2.2) sets the averaging frame in secs
//-----------------------------------------------------------------------------
declare rms_envelope_t19 author "Dario Sanfilippo and Julius O. Smith III";
declare rms_envelope_t19 copyright "Copyright (C) 2020 Dario Sanfilippo
<[email protected]> and
2003-2020 by Julius O. Smith III <[email protected]>";
declare rms_envelope_t19 license "MIT-style STK-4.3 license";
rms_envelope_t19(period, x) = ms_envelope_t19(period, x) : sqrt;
//-----------------------`(an.)zcr`--------------------------------------------
// Zero-crossing rate (ZCR) with one-pole lowpass averaging based on the tau
// constant. It outputs an index between 0 and 1 at a desired analysis frame.
// The ZCR of a signal correlates with the noisiness [Gouyon et al. 2000] and
// the spectral centroid [Herrera-Boyer et al. 2006] of a signal.
// For sinusoidal signals, the ZCR can be multiplied by ma.SR/2 and used
// as a frequency detector. For example, it can be deployed as a
// computationally efficient adaptive mechanism for automatic Larsen
// suppression.
//
// #### Usage
//
// ```
// _ : zcr(tau) : _
// ```
//
// Where:
//
// * `tau`: (time to decay by e^-1) sets the averaging frame in seconds.
declare zcr author "Dario Sanfilippo";
declare zcr copyright "Copyright (C) 2020 Dario Sanfilippo
declare zcr license "MIT-style STK-4.3 license";
zcr(period, x) = ma.zc(x) : fi.lptau(period);
//==============================Adaptive Frequency Analysis===============================
//========================================================================================
//--------------------`(an.)pitchTracker`---------------------------------------
//
// This function implements a pitch-tracking algorithm by means of
// zero-crossing rate analysis and adaptive low-pass filtering. The design
// is based on the algorithm described in [this tutorial (section 2.2)](https://pdfslide.net/documents/faust-tutorial2.html).
//
// #### Usage
//
// ```
// _ : pitchTracker(N, tau) : _
// ```
//
// Where:
//
// * `N`: a constant numerical expression, sets the order of the low-pass filter, which
// determines the sensitivity of the algorithm for signals where partials are
// stronger than the fundamental frequency.
// * `tau`: response time in seconds based on exponentially-weighted averaging with tau time-constant. See <https://ccrma.stanford.edu/~jos/st/Exponentials.html>.
declare pitchTracker author "Dario Sanfilippo";
declare pitchTracker copyright "Copyright (C) 2022 Dario Sanfilippo
declare pitchTracker license "MIT License";
pitchTracker(N, t, x) = loop ~ _
with {
xHighpassed = fi.highpass(1, 20.0, x);
loop(y) = an.zcr(t, fi.lowpass(N, max(20.0, y), xHighpassed)) * ma.SR * .5;
};
//--------------------`(an.)spectralCentroid`-----------------------------------
//
// This function implements a time-domain spectral centroid by means of RMS
// measurements and adaptive crossover filtering. The weight difference of the
// upper and lower spectral powers are used to recursively adjust the crossover
// cutoff so that the system (minimally) oscillates around a balancing point.
//
// Unlike block processing techniques such as FFT, this algorithm provides
// continuous measurements and fast response times. Furthermore, when providing
// input signals that are spectrally sparse, the algorithm will output a
// logarithmic measure of the centroid, which is perceptually desirable for
// musical applications. For example, if the input signal is the combination
// of three tones at 1000, 2000, and 4000 Hz, the centroid will be the middle
// octave.
//
// #### Usage
//
// ```
// _ : spectralCentroid(nonlinearity, tau) : _
// ```
//
// Where:
//
// * `nonlinearity`: a boolean to activate or deactivate nonlinear integration. The
// nonlinear function is useful to improve stability with very short response times
// such as .001 <= tau <= .005 , otherwise, the nonlinearity may reduce precision.
// * `tau`: response time in seconds based on exponentially-weighted averaging with tau time-constant. See <https://ccrma.stanford.edu/~jos/st/Exponentials.html>.
//
// #### Reference:
// Sanfilippo, D. (2021). Time-Domain Adaptive Algorithms for Low- and High-Level
// Audio Information Processing. Computer Music Journal, 45(1), 24-38.
//
// #### Example:
//
// `process = os.osc(500) + os.osc(1000) + os.osc(2000) + os.osc(4000) + os.osc(8000) : an.spectralCentroid(1, .001);`
//
declare spectralCentroid author "Dario Sanfilippo";
declare spectralCentroid copyright "Copyright (C) 2022 Dario Sanfilippo
declare spectralCentroid license "MIT License";
spectralCentroid(nonlinearity, t, x) = loop ~ _
with {
loop(fb) = centroid
with {
w(cf) = 2.0 * ma.PI * cf * ma.T;
integrator(t, x) = fi.pole(1.0, x * (1.0 / max(ma.EPSILON, t)) * ma.T);
lowpass(cf, x) = y
letrec {
'y = (x - s) * G + s;
's = 2 * (x - s) * G + s;
}
with {
G = tan(w(cf) / 2.0) / (1.0 + tan(w(cf) / 2.0));
};
highpass(cf, x) = x - lowpass(cf, x);
xRMS = an.rms_envelope_tau(t, x);
xLRMS = an.rms_envelope_tau(t, lowpass(fb, x));
xHRMS = an.rms_envelope_tau(t, highpass(fb, x));
diffRMS = (xHRMS - xLRMS) / max(ma.EPSILON, xRMS);
nonlinearIntegration = ba.if(nonlinearity, pow(diffRMS, 3), diffRMS);
diffInt = max(.0, min(1.0, integrator(t, nonlinearIntegration)));
centroid = max(20.0, diffInt * ma.SR * .5);
};
};
//=============================Spectrum-Analyzers=========================================
// Spectrum-analyzers split the input signal into a bank of parallel signals, one for
// each spectral band. They are related to the Mth-Octave Filter-Banks in `filters.lib`.
// The documentation of this library contains more details about the implementation.
// The parameters are:
//
// * `M`: number of band-slices per octave (>1)
// * `N`: total number of bands (>2)
// * `ftop` = upper bandlimit of the Mth-octave bands (<SR/2)
//
// In addition to the Mth-octave output signals, there is a highpass signal
// containing frequencies from ftop to SR/2, and a "dc band" lowpass signal
// containing frequencies from 0 (dc) up to the start of the Mth-octave bands.
// Thus, the N output signals are:
// ```
// highpass(ftop), MthOctaveBands(M,N-2,ftop), dcBand(ftop*2^(-M*(N-1)))
// ```
//
// A Spectrum-Analyzer is defined here as any band-split whose bands span
// the relevant spectrum, but whose band-signals do not
// necessarily sum to the original signal, either exactly or to within an
// allpass filtering. Spectrum analyzer outputs are normally at least nearly
// "power complementary", i.e., the power spectra of the individual bands
// sum to the original power spectrum (to within some negligible tolerance).
//
// #### Increasing Channel Isolation
//
// Go to higher filter orders - see Regalia et al. or Vaidyanathan (cited
// below) regarding the construction of more aggressive recursive
// filter-banks using elliptic or Chebyshev prototype filters.
//
// #### References
//
// * "Tree-structured complementary filter banks using all-pass sections",
// Regalia et al., IEEE Trans. Circuits & Systems, CAS-34:1470-1484, Dec. 1987
// * "Multirate Systems and Filter Banks", P. Vaidyanathan, Prentice-Hall, 1993
// * Elementary filter theory: <https://ccrma.stanford.edu/~jos/filters/>
//========================================================================================
//-------------------------`(an.)mth_octave_analyzer`----------------------------
// Octave analyzer.
// `mth_octave_analyzer[N]` are standard Faust functions.
//
// #### Usage
// ```
// _ : mth_octave_analyzer(O,M,ftop,N) : par(i,N,_) // Oth-order Butterworth
// _ : mth_octave_analyzer6e(M,ftop,N) : par(i,N,_) // 6th-order elliptic
// ```
//
// Also for convenience:
//
// ```
// _ : mth_octave_analyzer3(M,ftop,N) : par(i,N,_) // 3d-order Butterworth
// _ : mth_octave_analyzer5(M,ftop,N) : par(i,N,_) // 5th-order Butterworth
// mth_octave_analyzer_default = mth_octave_analyzer6e;
// ```
//
// Where:
//
// * `O`: (odd) order of filter used to split each frequency band into two
// * `M`: number of band-slices per octave
// * `ftop`: highest band-split crossover frequency (e.g., 20 kHz)
// * `N`: total number of bands (including dc and Nyquist)
//------------------------------------------------------------
mth_octave_analyzer6e(M,ftop,N) = _ <: bsplit(N-1) with {
fc(n) = ftop * 2^(float(n-N+1)/float(M)); // -3dB crossover frequencies
lp(n) = fi.lowpass6e(fc(n)); // 6th-order elliptic - see other choices above
hp(n) = fi.highpass6e(fc(n)); // (search for lowpass* and highpass*)
bsplit(0) = _;
bsplit(i) = hp(i), (lp(i) <: bsplit(i-1));
};
// Butterworth analyzers may be cascaded with allpass
// delay-equalizers to make (allpass-complementary) filter banks:
mth_octave_analyzer(O,M,ftop,N) = _ <: bsplit(N-1) with {
fc(n) = ftop * 2^(float(n-N+1)/float(M));
lp(n) = fi.lowpass(O,fc(n)); // Order O Butterworth
hp(n) = fi.highpass(O,fc(n));
bsplit(0) = _;
bsplit(i) = hp(i), (lp(i) <: bsplit(i-1));
};
mth_octave_analyzer3(M,ftop,N) = mth_octave_analyzer(3,M,ftop,N);
mth_octave_analyzer5(M,ftop,N) = mth_octave_analyzer(5,M,ftop,N);
mth_octave_analyzer_default = mth_octave_analyzer6e; // default analyzer
//============================Mth-Octave Spectral Level===================================
// Spectral Level: display (in bargraphs) the average signal level in each spectral band.
//========================================================================================
//------------------------`(an.)mth_octave_spectral_level6e`-------------------------
// Spectral level display.
//
// #### Usage:
//
// ```
// _ : mth_octave_spectral_level6e(M,ftop,NBands,tau,dB_offset) : _
// ```
//
// Where:
//
// * `M`: bands per octave
// * `ftop`: lower edge frequency of top band
// * `NBands`: number of passbands (including highpass and dc bands),
// * `tau`: spectral display averaging-time (time constant) in seconds,
// * `dB_offset`: constant dB offset in all band level meters.
//
// Also for convenience:
//
// ```
// mth_octave_spectral_level_default = mth_octave_spectral_level6e;
// spectral_level = mth_octave_spectral_level(2,10000,20);
// ```
//------------------------------------------------------------
mth_octave_spectral_level6e(M,ftop,N,tau,dB_offset) = _<:
_,mth_octave_analyzer6e(M,ftop,N) :
_,(display:>_):attach with {
display = par(i,N,dbmeter(i));
dbmeter(i) = abs : si.smooth(ba.tau2pole(tau)) : max(ma.EPSILON) : ba.linear2db : +(dB_offset) :
meter(N-i-1);
meter(i) = speclevel_group(vbargraph("[%2i] [unit:dB]
[tooltip: Spectral Band Level in dB]", -50, 10));
O = int(((N-2)/M)+0.4999);
speclevel_group(x) = hgroup("[0] CONSTANT-Q SPECTRUM ANALYZER (6E), %N bands spanning
LP, %O octaves below %ftop Hz, HP
[tooltip: See Faust's filters.lib for documentation and references]", x);
};
mth_octave_spectral_level_default = mth_octave_spectral_level6e;
spectral_level = mth_octave_spectral_level(2,10000,20); // simple default
//---------------`(an.)[third|half]_octave_[analyzer|filterbank]`----------------
// A bunch of special cases based on the different analyzer functions described above:
//
// ```
// third_octave_analyzer(N) = mth_octave_analyzer_default(3,10000,N);
// third_octave_filterbank(N) = mth_octave_filterbank_default(3,10000,N);
// half_octave_analyzer(N) = mth_octave_analyzer_default(2,10000,N);
// half_octave_filterbank(N) = mth_octave_filterbank_default(2,10000,N);
// octave_filterbank(N) = mth_octave_filterbank_default(1,10000,N);
// octave_analyzer(N) = mth_octave_analyzer_default(1,10000,N);
// ```
//
// #### Usage
//
// See `mth_octave_spectral_level_demo` in `demos.lib`.
//------------------------------------------------------------
third_octave_analyzer(N) = mth_octave_analyzer_default(3,10000,N);
third_octave_filterbank(N) = mth_octave_filterbank_default(3,10000,N);
// Third-Octave Filter-Banks have been used in audio for over a century.
// See, e.g.,
// Acoustics [the book], by L. L. Beranek
// Amer. Inst. Physics for the Acoustical Soc. America,
// <http://asa.aip.org/publications.html, 1986 (1st ed.1954)>
// Third-octave bands across the audio spectrum are too wide for current
// typical computer screens, so half-octave bands are the default:
half_octave_analyzer(N) = mth_octave_analyzer_default(2,10000,N);
half_octave_filterbank(N) = mth_octave_filterbank_default(2,10000,N);
octave_filterbank(N) = mth_octave_filterbank_default(1,10000,N);
octave_analyzer(N) = mth_octave_analyzer_default(1,10000,N);
//===============Arbritary-Crossover Filter-Banks and Spectrum Analyzers==================
// These are similar to the Mth-octave analyzers above, except that the
// band-split frequencies are passed explicitly as arguments.
//========================================================================================
// ACKNOWLEDGMENT
// Technique for processing a variable number of signal arguments due
// to Yann Orlarey (as is the entire Faust framework!)
//---------------`(an.)analyzer`--------------------------
// Analyzer.
//
// #### Usage
//
// ```
// _ : analyzer(O,freqs) : par(i,N,_) // No delay equalizer
// ```
//
// Where:
//
// * `O`: band-split filter order (ODD integer required for filterbank[i])
// * `freqs`: (fc1,fc2,...,fcNs) [in numerically ascending order], where
// Ns=N-1 is the number of octave band-splits
// (total number of bands N=Ns+1).
//
// If frequencies are listed explicitly as arguments, enclose them in parens:
//
// ```
// _ : analyzer(3,(fc1,fc2)) : _,_,_
// ```
//---------------------------------------------------
analyzer(O,lfreqs) = _ <: bsplit(nb)
with {
nb = ba.count(lfreqs);
fc(n) = ba.take(n, lfreqs);
lp(n) = fi.lowpass(O,fc(n));
hp(n) = fi.highpass(O,fc(n));
bsplit(0) = _;
bsplit(i) = hp(i), (lp(i) <: bsplit(i-1));
};
//================ Fast Fourier Transform (fft) and its Inverse (ifft) ===================
// Sliding FFTs that compute a rectangularly windowed FFT each sample.
//========================================================================================
//---------------`(an.)goertzelOpt` --------------------------
// Optimized Goertzel filter.
//
// #### Usage
//
// ```
// _ : goertzelOpt(freq,n) : _
// ```
//
// Where:
//
// * `freq`: frequency to be analyzed
// * `n`: the Goertzel block size
//
// #### Reference
//
// * <https://en.wikipedia.org/wiki/Goertzel_algorithm>
//---------------------------------------------------
goertzelOpt(freq,n,x) = mg
with {
mg = sqrt(eq^2 + eq'^2-eq*eq'*c) : ba.sAndH(reset0); // magnitude
cnt = ba.time%n; // counter for windowing
reset0 = cnt == (n-1); // reset when end of window
reset1 = 1-(cnt == 0); // reset when beginning of window
k = 0.5 + n*freq/ma.SR;
w = (2*ma.PI/n)*k;
c = 2*cos(w);
eq = s // equation
letrec{
's = c*s*reset1 - s'*reset1*reset1' + x;
};
};
//---------------`(an.)goertzelComp` --------------------------
// Complex Goertzel filter.
//
// #### Usage
//
// ```
// _ : goertzelComp(freq,n) : _
// ```
//
// Where:
//
// * `freq`: frequency to be analyzed
// * `n`: the Goertzel block size
//
// #### Reference
//
// * <https://en.wikipedia.org/wiki/Goertzel_algorithm>
//---------------------------------------------------
goertzelComp(freq,n,x) = mg
with {
mg = sqrt(real^2 + imag^2); // magnitude
cnt = ba.time%n; // counter for windowing
reset0 = cnt == (n-1); // reset when end of window
reset1 = 1-(cnt == 0); // reset when beginning of window
k = 0.5 + n*freq/ma.SR;
w = (2*ma.PI/n)*k;
sine = sin(w);
cosine = cos(w);
c = 2*cosine;
eq = s
letrec{
's = c*s*reset1 - s'*reset1*reset1' + x;
};
real = eq - eq'*cosine;
imag = eq'*sine;
};
//---------------`(an.)goertzel` --------------------------
// Same as [`goertzelOpt`](#goertzelopt).
//
// #### Usage
//
// ```
// _ : goertzel(freq,n) : _
// ```
//
// Where:
//
// * `freq`: frequency to be analyzed
// * `n`: the Goertzel block size
//
// #### Reference
//
// * <https://en.wikipedia.org/wiki/Goertzel_algorithm>
//---------------------------------------------------
goertzel = goertzelOpt;
// Undocumented utility functions used by fft and ifft:
c_magsq(N) = si.cbus(N) : par(i,N,(par(j,2,abs<:_*_):>_)) :> si.bus(N);
c_magdb(N) = si.cbus(N) : an.c_magsq(N) : par(i,N,(max(ma.EPSILON):log10:*(10.0)));
c_select_pos_freqs(2) = (_,_), (_,_); // both dc and SR/2 included with "positive frequencies"
c_select_pos_freqs(N) = si.cbus(N) : par(i,N/2+1,(_,_)),par(i,N/2-1,(!,!)) : si.cbus(N/2+1); // for complex spectra
select_pos_freqs(2) = _,_; // both dc and SR/2 included
select_pos_freqs(N) = si.bus(N) : par(i,N/2+1, _), par(i,N/2-1, !) : si. bus(N/2+1); // real power spectra etc.
rtorv(N,x) = par(i,N,x@i); // convert real scalar signal to length N real vector
rtocv(N,x) = par(i,N,(x@i,0)); // convert real scalar signal to length N complex vector with 0 imag part
rvtocv(N) = si.bus(N), par(i,N,0) : ro.interleave(N,2); // convert real N-vector to complex with 0 imag part
bit_reverse_selector(N,0) = 0;
bit_reverse_selector(N,i) = int(int(N)>>1)*(i&1) + bit_reverse_selector(int(N)>>1,(i>>1));
// decimation in time does this to the input:
bit_reverse_shuffle(N) = si.bus(N) <: par(i,N,bit_reverse_permuter(N,i)) with {
bit_reverse_permuter(N,k) = ba.selector(bit_reverse_selector(N,k),N);
};
c_bit_reverse_shuffle(N) = si.cbus(N) <: par(i,N,c_bit_reverse_permuter(N,i)) with {
c_bit_reverse_permuter(N,k) = ba.cselector(bit_reverse_selector(N,k),N);
};
//---------------`(an.)fft` --------------------------
// Fast Fourier Transform (FFT).
//
// #### Usage
//
// ```
// si.cbus(N) : fft(N) : si.cbus(N)
// ```
//
// Where:
//
// * `si.cbus(N)` is a bus of N complex signals, each specified by real and imaginary parts:
// (r0,i0), (r1,i1), (r2,i2), ...
// * `N` is the FFT size (must be a power of 2: 2,4,8,16,... known at compile time)
// * `fft(N)` performs a length `N` FFT for complex signals (radix 2)
// * The output is a bank of N complex signals containing the complex spectrum over time:
// (R0, I0), (R1,I1), ...
// - The dc component is (R0,I0), where I0=0 for real input signals.
//
// FFTs of Real Signals:
//
// * To perform a sliding FFT over a real input signal, you can say
// ```
// process = signal : an.rtocv(N) : an.fft(N);
// ```
// where `an.rtocv` converts a real (scalar) signal to a complex vector signal having a zero imaginary part.
//
// * See `an.rfft_analyzer_c` (in `analyzers.lib`) and related functions for more detailed usage examples.
//
// * Use `an.rfft_spectral_level(N,tau,dB_offset)` to display the power spectrum of a real signal.
//
// * See `dm.fft_spectral_level_demo(N)` in `demos.lib` for an example GUI driving `an.rfft_spectral_level()`.
//
// #### Reference
//
// * [Decimation-in-time (DIT) Radix-2 FFT](https://cnx.org/contents/zmcmahhR@7/Decimation-in-time-DIT-Radix-2)
//
//---------------------------------------------------
fft(N) = si.cbus(N) : an.c_bit_reverse_shuffle(N) : an.fftb(N); // shuffle off to the butterflies:
fftb(1) = _,_; // each complex number is represented as (real,imag)
fftb(N) = si.cbus(N) : (fftb(No2) <: (si.cbus(No2), si.cbus(No2))), (fftb(No2)
<: (si.cbus(N):twiddleOdd(N))) :> si.cbus(N)
with {
No2 = int(N)>>1;
// Half of these multiplies can go away since w(k) = - w(k+N/2), and others as well (1,j,-j,-1,...)
twiddleOdd(N) = par(k,N,si.cmul(cos(w(k)),0-sin(w(k))))
with {
w(k) = 2.0*ma.PI*float(k)/float(N);
};
};
// `rfft`
// Slow to compile: rfft(N) = si.bus(N) : an.bit_reverse_shuffle(N) : an.rvtocv(N) : an.fftb(N);
// Order of magnitude faster to compile but takes a scalar input, so too different from fft:
// rfft(N) = an.rtocv(N) : an.fft(N);
//---------------`(an.)ifft`--------------------------
// Inverse Fast Fourier Transform (IFFT).
//
// #### Usage
//
// ```
// si.cbus(N) : ifft(N) : si.cbus(N)
// ```
//
// Where:
//
// * N is the IFFT size (power of 2)
// * Input is a complex spectrum represented as interleaved real and imaginary parts:
// (R0, I0), (R1,I1), (R2,I2), ...
// * Output is a bank of N complex signals giving the complex signal in the time domain:
// (r0, i0), (r1,i1), (r2,i2), ...
//---------------------------------------------------
ifft(N) = si.cbus(N) : an.c_bit_reverse_shuffle(N) : an.ifftb(N); // input is shuffled off to the butterflies:
ifftb(1) = _,_;
ifftb(N) = si.cbus(N) : (ifftb(No2) <: (si.cbus(No2), si.cbus(No2))), (ifftb(No2)
<: (si.cbus(N):twiddleOddConj(N))) :> si.cbus(N) : par(i,2*N,/(2.0))
with {
No2 = int(N)>>1;
// Half of these multiplies can go away since w(k) = - w(k+N/2), and others as well (1,j,-j,-1,...)
twiddleOddConj(N) = par(k,N,si.cmul(cos(w(k)),sin(w(k))))
with {
w(k) = 2.0*ma.PI*float(k)/float(N);
};
};
// ========== FFT Analyzers ==========
rfft_analyzer_c(N) = an.rtocv(N) : an.fft(N) : an.c_select_pos_freqs(N); // complex spectral bins 0 to N/2
rfft_analyzer_db(N) = an.rfft_analyzer_c(N) : an.c_magdb(N/2+1); // assumes real input
rfft_analyzer_magsq(N) = an.rfft_analyzer_c(N) : an.c_magsq(N/2+1); // assumes real input
rfft_spectral_level(N,tau,dB_offset) = _<: _, an.rfft_analyzer_db(N) : _,(display:>_):attach with {
display = par(i,N/2+1,dbmeter(i));
dbmeter(i) = si.smooth(ba.tau2pole(tau)) : +(dB_offset) : meter(i);
meter(i) = speclevel_group(vbargraph("[%2i] [unit:dB]
[tooltip: FFT Spectral Band Level in dB]", -50, 10));
speclevel_group(x) = hgroup("[0] FFT SPECTRUM ANALYZER, %N bands
[tooltip: fft_spectral_level in Faust's analyzers.lib]", x);
};
// end jos section
/************************************************************************
************************************************************************
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.
************************************************************************
************************************************************************/
// TODO: Add GRAME functions here
//########################################################################################
/************************************************************************
FAUST library file, further contributions section
All contributions below should indicate both the contributor and terms
of license. If no such indication is found, "git blame" will say who
last edited each line, and that person can be emailed to inquire about
license disposition, if their license choice is not already indicated
elsewhere among the libraries. It is expected that all software will be
released under LGPL, STK-4.3, MIT, BSD, or a similar FOSS license.
************************************************************************/