-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathWaveformHelper.h
1606 lines (1370 loc) · 54.3 KB
/
WaveformHelper.h
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
//
// WaveformHelper.h
// 8Beat
//
// Created by Rasmus Anthin on 2024-02-10.
//
#pragma once
#include "Waveform.h"
#include "Spectrum.h"
#include "ADSR.h"
#include <TrainOfThought/ann_cnn.h>
#include <Core/Math.h>
#include <Core/StlOperators.h>
#include <complex>
#include <iostream>
namespace audio
{
using namespace std::complex_literals;
enum class FilterType { NONE, Butterworth, ChebyshevTypeI, ChebyshevTypeII };
enum class FilterOpType { NONE, LowPass, HighPass, BandPass, BandStop };
enum class GraphType { PLOT_THIN, PLOT_THICK0, PLOT_THICK1, PLOT_THICK2, PLOT_THICK3, FILLED_BOTTOM_UP, FILLED_FROM_T_AXIS };
enum class Complex2Real { ABS, REAL, IMAG };
enum class WindowType { HAMMING, HANNING };
struct FilterArgs
{
FilterType filter_type = FilterType::NONE;
FilterOpType filter_op_type = FilterOpType::NONE;
int filter_order = 1;
float cutoff_freq_multiplier = 2.5f;
std::optional<float> bandwidth_freq_multiplier = std::nullopt;
float ripple = 0.1f;
bool normalize_filtered_wave = false;
};
struct Filter
{
std::vector<float> a;
std::vector<float> b;
};
struct FilterS
{
std::vector<std::complex<double>> zeroes, poles;
double gain = 1.f;
};
class WaveformHelper
{
public:
static Waveform subset(const Waveform& wave, size_t start_idx, size_t length = static_cast<size_t>(-1))
{
auto N = wave.buffer.size();
if (N == 0)
return {};
Waveform output;
output.copy_properties(wave);
if (start_idx < N)
{
if (length == static_cast<size_t>(-1))
length = N;
size_t N_new = length;
if (start_idx + length > N)
N_new = N - start_idx;
output.buffer.resize(N_new);
std::memcpy(output.buffer.data(), wave.buffer.data() + start_idx, N_new * sizeof(wave.buffer[0]));
}
output.update_duration();
return output;
}
static Waveform mix(const std::vector<std::pair<float, Waveform>>& weighted_waves)
{
const size_t Nw = weighted_waves.size();
size_t Nmin = static_cast<size_t>(-1);
std::vector<std::pair<float, Waveform>> res_weighted_waves(weighted_waves.size());
int common_sample_rate = 0;
float frequency = 0.f;
float weight_sum = 0.f;
for (const auto& ww : weighted_waves)
{
const auto weight = ww.first;
const auto& wave = ww.second;
math::maximize(common_sample_rate, wave.sample_rate);
frequency += wave.frequency;
math::minimize(Nmin, wave.buffer.size());
weight_sum += weight;
}
frequency /= Nw;
for (size_t w_idx = 0; w_idx < Nw; ++w_idx)
{
const auto& ww_i = weighted_waves[w_idx];
const auto& wave_i = ww_i.second;
auto& ww_o = res_weighted_waves[w_idx];
ww_o.first = ww_i.first;
ww_o.second = resample(wave_i, common_sample_rate, FilterType::Butterworth);
}
Waveform weighted_sum(Nmin, 0.f);
weighted_sum.sample_rate = common_sample_rate;
weighted_sum.frequency = frequency;
for (size_t i = 0; i < Nmin; ++i)
{
weighted_sum.buffer[i] = 0.f;
for (const auto& ww : weighted_waves)
weighted_sum.buffer[i] += ww.first * ww.second.buffer[i];
weighted_sum.buffer[i] /= weight_sum;
}
weighted_sum.update_duration();
return weighted_sum;
}
static Waveform mix(float t, const Waveform& wave_A, const Waveform& wave_B)
{
// Resample both signals to a common sample rate
int common_sample_rate = std::max(wave_A.sample_rate, wave_B.sample_rate);
Waveform res_A = resample(wave_A, common_sample_rate, FilterType::Butterworth);
Waveform res_B = resample(wave_B, common_sample_rate, FilterType::Butterworth);
const auto Nmin = std::min(res_A.buffer.size(), res_A.buffer.size());
Waveform sum(Nmin, 0.f);
sum.sample_rate = common_sample_rate;
sum.frequency = (res_A.frequency + res_B.frequency)*0.5f;
for (size_t i = 0; i < Nmin; ++i)
sum.buffer[i] = math::lerp(t, res_A.buffer[i], res_B.buffer[i]);
return sum;
}
static Waveform ring_modulation(const Waveform& wave_A, const Waveform& wave_B)
{
// Resample both signals to a common sample rate
int common_sample_rate = std::max(wave_A.sample_rate, wave_B.sample_rate);
Waveform res_A = resample(wave_A, common_sample_rate, FilterType::Butterworth);
Waveform res_B = resample(wave_B, common_sample_rate, FilterType::Butterworth);
Waveform prod;
prod.sample_rate = common_sample_rate;
prod.frequency = calc_fundamental_frequency(res_A.frequency, res_B.frequency);
int Nmin = static_cast<int>(std::min(res_A.buffer.size(), res_B.buffer.size()));
prod.buffer.resize(Nmin);
for (int i = 0; i < Nmin; ++i)
{
float a = res_A.buffer[i];
float b = res_B.buffer[i];
prod.buffer[i] = a * b;
}
prod.duration = calc_duration(prod);
return prod;
}
// wave: the waveform to produce a reverb effect for.
// kernel: a dirac-like pulse sample in the environment to make a reverb effect from.
static Waveform reverb(const Waveform& wave, const Waveform& kernel)
{
// Resample both signals to a common sample rate.
int common_sample_rate = std::max(wave.sample_rate, kernel.sample_rate);
Waveform res_wave = resample(wave, common_sample_rate, FilterType::Butterworth);
Waveform res_kernel = resample(kernel, common_sample_rate, FilterType::Butterworth);
Waveform conv;
conv.sample_rate = common_sample_rate;
conv.frequency = calc_fundamental_frequency(res_wave.frequency, res_kernel.frequency);
conv.buffer = ml::ann::conv_1d(res_wave.buffer, res_kernel.buffer, 0.f,
ml::ann::ConvRange::Full, ml::ann::ConvType::Convolution);
normalize_over(conv);
//auto [minval, maxval] = WaveformHelper::find_min_max(conv, true);
//std::cout << "minval = " << minval << std::endl;
//std::cout << "maxval = " << maxval << std::endl;
conv.update_duration();
return conv;
}
static Waveform reverb_fast(const Waveform& wave, const Waveform& kernel)
{
// Resample both signals to a common sample rate.
int common_sample_rate = std::max(wave.sample_rate, kernel.sample_rate);
Waveform res_wave = resample(wave, common_sample_rate, FilterType::Butterworth);
Waveform res_kernel = resample(kernel, common_sample_rate, FilterType::Butterworth);
// Apply windowing.
//apply_window(res_wave, WindowType::HAMMING);
//apply_window(res_kernel, WindowType::HAMMING);
// Padding to common length.
auto Nw = static_cast<int>(res_wave.buffer.size());
auto Nk = static_cast<int>(res_kernel.buffer.size());
auto N = static_cast<int>(std::max(Nw, Nk));
for (int i = 0; i < N - Nw; ++i)
res_wave.buffer.emplace_back(0.f);
for (int i = 0; i < N - Nk; ++i)
res_kernel.buffer.emplace_back(0.f);
auto spec_res_wave = fft(res_wave);
auto spec_res_kernel = fft(res_kernel);
int Ns = static_cast<int>(spec_res_wave.buffer.size());
Spectrum prod;
prod.buffer.resize(Ns);
for (int i = 0; i < Ns; ++i)
prod.buffer[i] = spec_res_wave.buffer[i] * spec_res_kernel.buffer[i];
prod.copy_properties(spec_res_wave);
auto reverb = ifft(prod);
auto conv_full_size = Nw + Nk - 1;
//reverb.buffer.resize(std::min(reverb.buffer.size(), res_kernel.buffer.size()));
//reverb.buffer.resize(std::min(reverb.buffer.size(), res_wave.buffer.size()));
reverb.buffer.resize(conv_full_size);
reverb.sample_rate = common_sample_rate;
reverb.frequency = calc_fundamental_frequency(res_wave.frequency, res_kernel.frequency);
reverb.update_duration();
// Normalize to amplitude max 1 if amplitude > 1.
normalize_over(reverb);
//auto [minval, maxval] = WaveformHelper::find_min_max(reverb, true);
//std::cout << "minval = " << minval << std::endl;
//std::cout << "maxval = " << maxval << std::endl;
//apply_window(reverb, WindowType::HANNING);
return reverb;
}
static float complex2real(const std::complex<float>& input, Complex2Real filter)
{
switch (filter)
{
case Complex2Real::ABS: return std::abs(input);
case Complex2Real::REAL: return std::real(input);
case Complex2Real::IMAG: return std::imag(input);
}
}
static std::vector<float> complex2real(const std::vector<std::complex<float>>& input,
Complex2Real filter)
{
size_t N = input.size();
std::vector<float> output(N);
switch (filter)
{
case Complex2Real::ABS:
for (size_t i = 0; i < N; ++i)
output[i] = std::abs(input[i]);
break;
case Complex2Real::REAL:
for (size_t i = 0; i < N; ++i)
output[i] = std::real(input[i]);
break;
case Complex2Real::IMAG:
for (size_t i = 0; i < N; ++i)
output[i] = std::imag(input[i]);
break;
}
return output;
}
static Spectrum fft(const Waveform& wave)
{
auto sz = static_cast<int>(wave.buffer.size());
auto N = static_cast<int>(std::pow<int>(2, std::ceil(std::log(sz)/std::log(2))));
std::vector<std::complex<float>> input(std::begin(wave.buffer), std::end(wave.buffer));
// Padding.
for (int i = 0; i < N - sz; ++i)
input.emplace_back(0.f);
auto output = fft_rec(input);
Spectrum result;
result.buffer = output;
// Calculate frequency axis.
result.freq_start = -wave.sample_rate / 2.f;
result.freq_end = wave.sample_rate / 2.f;
return result;
}
static Waveform ifft(const Spectrum& spectrum, Complex2Real c2r_filter = Complex2Real::REAL)
{
auto sz = static_cast<int>(spectrum.buffer.size());
auto N = static_cast<int>(std::pow<int>(2, std::ceil(std::log(sz)/std::log(2))));
std::vector<std::complex<float>> input(std::begin(spectrum.buffer), std::end(spectrum.buffer));
// Padding.
for (int i = 0; i < N - sz; ++i)
input.emplace_back(0.f);
auto output = ifft_rec(input);
// Normalize the output.
for (auto& s : output)
s /= static_cast<float>(N);
Waveform result;
result.buffer = complex2real(output, c2r_filter);
// Calculate frequency axis.
result.sample_rate = static_cast<int>(spectrum.freq_end * 2.f);
return result;
}
static std::tuple<float, float> find_min_max(const Waveform& wd, bool abs = false)
{
float min_val = 0.f;
float max_val = 0.f;
if (abs)
{
min_val = +std::numeric_limits<float>::infinity();
max_val = 0.f;
for (const auto& s : wd.buffer)
{
math::minimize(min_val, std::abs(s));
math::maximize(max_val, std::abs(s));
}
}
else
{
min_val = +std::numeric_limits<float>::infinity();
max_val = -std::numeric_limits<float>::infinity();
for (const auto& s : wd.buffer)
{
math::minimize(min_val, s);
math::maximize(max_val, s);
}
}
return { min_val, max_val };
}
// Normalize only over a certain amplitude limit.
// if max(abs(waveform)) > amplitude_limit
// waveform scaled so that max amplitude = amplitude_limit
// else
// unchanged
static void normalize_over(Waveform& wd, float amplitude_limit = 1.f)
{
auto [_, max_val] = find_min_max(wd, true);
if (max_val > amplitude_limit)
{
for (auto& s : wd.buffer)
s *= amplitude_limit / max_val;
}
}
// Compresses all samples above a certain threshold.
// /\ /\ |* |
// /..\......../..\.v.. /^^\ /^^\ |
// /____\______/____\ => /____\____/____\ |
// \ / \ / |
// ......\../.......... vv |
// -- |
// * : squeezed interval by factor upper_scale * (abs(sample) - upper_limit)
// for sample > upper_limit. Analogously for negative samples values.
// upper_limit <= 1 and upper_scale <= (normally).
static void compress_over(Waveform& wd, float upper_limit, float upper_scale)
{
for (auto& s : wd.buffer)
{
auto s_abs = std::abs(s);
if (s_abs >= upper_limit)
{
auto sgn = math::sgn(s);
s = sgn * (upper_limit + (s - upper_limit * upper_scale));
}
}
}
// Normalize so that max amplitude = 1
static void normalize(Waveform& wd, bool two_sided = false)
{
auto [min_val, max_val] = find_min_max(wd, !two_sided);
if (two_sided)
{
auto neg_max_val = std::abs(min_val);
auto pos_max_val = std::abs(max_val);
for (auto& s : wd.buffer)
if (math::sgn(s) == +1)
s /= pos_max_val;
else
s /= neg_max_val;
}
else
for (auto& s : wd.buffer)
s /= max_val;
}
// Scale so that max_amplitude = scale.
static void normalize_scale(Waveform& wd, float scale = 1.f)
{
auto [_, max_val] = find_min_max(wd, true);
for (auto& s : wd.buffer)
s *= scale / max_val;
}
static void scale(Waveform& wd, float scale = 1.f)
{
for (auto& s : wd.buffer)
s *= scale;
}
static void clamp(Waveform& wd, float min = -1.f, float max = +1.f)
{
for (auto& s : wd.buffer)
if (s > max)
s = max;
else if (s < min)
s = min;
}
// Upwards compression function
static void compress(Waveform& wd, float upper_threshold, float upper_scale, float boost_gain)
{
// normalize_scale(wd, 1.2f); // Boost signal by 20%.
// compress_over(wd, 0.6f, 0.5f); // Compresses abs(sample) values over 0.6f by half => 0.6 + 0.4*0.5 = = 0.8.
// // 1.2 * 0.8 = 0.96. Amplitude effectlively lowered by factor 0.96.
// normalize(wd); // Normalizing the waveform back to an amplitude of 1.
normalize_scale(wd, boost_gain);
compress_over(wd, upper_threshold, upper_scale);
normalize(wd, true);
}
static Waveform fir_moving_average(const Waveform& wave, int window_size, bool preserve_amplitude)
{
auto N = static_cast<int>(wave.buffer.size());
if (window_size > N)
window_size = N;
int Navg = N - window_size + 1;
Waveform output(Navg, 0.f);
output.copy_properties(wave);
auto [_, max_val] = find_min_max(wave, true);
for (int i = 0; i < Navg; ++i)
{
for (int j = 0; j < window_size; ++j)
output.buffer[i] += wave.buffer[i + j];
output.buffer[i] /= static_cast<float>(window_size);
}
if (preserve_amplitude)
scale(output, max_val);
output.update_duration();
return output;
}
static Waveform fir_sinc_window_low_pass(const Waveform& wave)
{
auto N = static_cast<int>(wave.buffer.size());
Waveform output(N, 0.f);
// #FIXME: Implement me.
output.update_duration();
return output;
}
static Waveform flanger(const Waveform& wave, float delay_time, float rate, float feedback)
{
Waveform output = wave;
output.buffer = flanger(wave.buffer, delay_time, rate, feedback, wave.sample_rate);
return output;
}
// #FIXME: Why you not work!?!?
static Waveform fir_chorus(const Waveform& wave, float modulation_freq = 1.f, float modulation_depth = 5e-3f, const std::vector<float> coeffs = { 1.f, .5f, -.2f, .1f })
{
auto N = wave.buffer.size();
auto Nc = coeffs.size();
Waveform output(N, 0.f);
output.copy_properties(wave);
float delay = modulation_depth * std::sin(math::c_2pi * modulation_freq / wave.sample_rate);
// FIR filter.
for (size_t i = 0; i < N; ++i)
for (size_t j = 0; j < Nc; ++j)
{
auto delayed_index = static_cast<int>(i - delay * wave.sample_rate * j);
if (delayed_index >= 0 && delayed_index < static_cast<int>(wave.buffer.size()))
output.buffer[i] += coeffs[j] * wave.buffer[delayed_index];
}
output.update_duration();
return output;
}
// Emulates string instrument sounds.
static Waveform karplus_strong(float duration_s, float frequency,
int sample_rate = 44100)
{
auto Ns = static_cast<int>(calc_num_samples(duration_s, sample_rate));
Waveform wave(Ns, 0.f);
wave.duration = duration_s;
wave.frequency = frequency;
auto Nb = std::min(Ns, static_cast<int>(std::round(sample_rate / frequency)));
std::vector<float> noise(Nb);
for (int s_idx = 0; s_idx < Nb; ++s_idx)
noise[s_idx] = rnd::rand_float(-1.f, +1.f);
// y(n) = x(n) + (y(n-N) + y(n-N+1))/2
for (int s_idx = 0; s_idx < Ns; ++s_idx)
{
size_t idx_offs = s_idx < Nb ? s_idx : s_idx - Nb;
float avg = 0.5f * (wave.buffer[idx_offs % Ns] + wave.buffer[idx_offs % Ns]);
wave.buffer[s_idx] = avg + noise[s_idx % Nb];
// Low-pass filter
//wave.buffer[s_idx] = 0.5f * (wave.buffer[s_idx] + wave.buffer[s_idx - 1]);
}
return wave;
}
static Waveform envelope_adsr(const Waveform& wave, const ADSR& adsr)
{
auto N = wave.buffer.size();
Waveform output = wave;
// Ex0:
// t_a t_ad t_ds t_sr t_r
// |----- T_a_s ----->|----- T_d_s ----->|----- T_s_max_s ----->|----- T_r_s ----->|
// |-------------------------------- T_dur_s ----------------------------------------------------->|
//
// T_a_s = .10, T_d_s = .10, (T_s_s = *), T_r_s = .10
// t_a = 0, t_ad = .10, t_ds = .20, t_sr = .35, t_r = .45
// T_dur_s = .60
// t_ad = T_a_s = .10
// t_ds = T_a_s + T_d_s = 0.10 + 0.10 = 0.20
// t_sr = T_a_s + T_d_s + T_s_max_s = 0.10 + 0.10 + 0.15 = 0.35
// t_r = T_a_s + T_d_s + T_s_max_s + T_r_s = .10 + .10 + .15 + .10 = .45
// Ex1:
// t_a t_ad t_ds t_sr t_r
// |----- T_a_s ----->|----- T_d_s ----->|----- T_s_s ----->|----- T_r_s ----->|
// |-------------------------------- T_dur_s --------------------------------->|
//
// T_a_s = .10, T_d_s = .10, (T_s_s = *), T_r_s = .10
// t_a = 0, t_ad = .10, t_ds = .20, t_sr = .30, t_r = .40
// T_dur_s = .40
// T_ads_s = max(T_dur_s - T_r_s, 0) = max(.40 - .10, 0) = 0.30
// t_ad = min(T_ads_s, T_a_s) = min(0.30, 0.10) = 0.10 = T_a_s (original)
// t_ds = min(T_ads_s, T_a_s + T_d_s) = min(0.30, 0.10 + 0.10) = 0.20 = T_a_s + T_d_s (original)
// t_sr = max(t_ds, T_ads_s) = max(0.20, 0.30) = 0.30
// t_r = T_dur_s = 0.40
// Ex2:
// |----- T_a_s ----->|----- T_d_s ----->|- T_s_s ->|----- T_r_s ----->|
// |---------------------------- T_dur_s ----------------------------->|
// Ex3:
// |----- T_a_s ----->|----- T_d_s ----->|----- T_r_s ----->|
// |------------------------ T_dur_s ---------------------->|
//
// T_a_s = .10, T_d_s = .10, (T_s_s = *), T_r_s = .10
// Ex4:
// t_a t_ad t_ds/t_sr t_r
// |----- T_a_s ----->|- T_d_s ->|----- T_r_s ----->|
// |-------------------- T_dur_s ------------------>|
//
// T_a_s = .10, T_d_s = .10, (T_s_s = *), T_r_s = .10
// t_a = 0, t_ad = .10, t_ds = .15, t_sr = .15, t_r = .25
// T_dur_s = .25
// T_ads_s = max(T_dur_s - T_r_s, 0) = max(.25 - .10, 0) = 0.15
// t_ad = min(T_ads_s, T_a_s) = min(0.15, 0.10) = 0.10 = T_a_s (original)
// t_ds = min(T_ads_s, T_a_s + T_d_s) = min(0.15, 0.10 + 0.10) = 0.15 < 0.20 = T_a_s + T_d_s
// t_sr = max(t_ds, T_ads_s) = max(0.15, 0.15) = 0.15
// t_r = T_dur_s = 0.25
// Ex5:
// t_a t_ad/t_ds/t_sr t_r
// |----- T_a_s ----->|----- T_r_s ----->|
// |-------------- T_dur_s ------------->|
//
// T_a_s = .10, T_d_s = .10, (T_s_s = *), T_r_s = .10
// t_a = 0, t_ad = .10, t_ds = .10, t_sr = .10, t_r = .20
// T_dur_s = .20
// T_ads_s = max(T_dur_s - T_r_s, 0) = max(.20 - .10, 0) = 0.10
// t_ad = min(T_ads_s, T_a_s) = min(0.10, 0.10) = 0.10 = T_a_s (original)
// t_ds = min(T_ads_s, T_a_s + T_d_s) = min(0.10, 0.10 + 0.10) = 0.10 < 0.20 = T_a_s + T_d_s
// t_sr = max(t_ds, T_ads_s) = max(0.10, 0.10) = 0.10
// t_r = T_dur_s = 0.20
// Ex6:
// t_a t_ad/t_ds/t_sr t_r
// |- T_a_s ->|----- T_r_s ----->|
// |---------- T_dur_s --------->|
//
// T_a_s = .10, T_d_s = .10, (T_s_s = *), T_r_s = .10
// t_a = 0, t_ad = .05, t_ds = .05, t_sr = .05, t_r = .15
// T_dur_s = .15
// T_ads_s = max(T_dur_s - T_r_s, 0) = max(.15 - .10, 0) = 0.05
// t_ad = min(T_ads_s, T_a_s) = min(0.05, 0.10) = 0.05 < 0.10 = T_a_s
// t_ds = min(T_ads_s, T_a_s + T_d_s) = min(0.05, 0.10 + 0.10) = 0.05 < 0.20 = T_a_s + T_d_s
// t_sr = max(t_ds, T_ads_s) = max(0.05, 0.05) = 0.05
// t_r = T_dur_s = 0.15
// Ex7:
// t_a/t_ad/t_ds/t_sr t_r
// |----- T_r_s ----->|
// |----- T_dur_s --->|
//
// T_a_s = .10, T_d_s = .10, (T_s_s = *), T_r_s = .10
// t_a = 0, t_ad = 0, t_ds = 0, t_sr = 0, t_r = .10
// T_dur_s = .10
// T_ads_s = max(T_dur_s - T_r_s, 0) = max(.10 - .10, 0) = 0
// t_ad = min(T_ads_s, T_a_s) = min(0, 0.10) = 0 < 0.10 = T_a_s
// t_ds = min(T_ads_s, T_a_s + T_d_s) = min(0, 0.10 + 0.10) = 0 < 0.20 = T_a_s + T_d_s
// t_sr = max(t_ds, T_ads_s) = max(0, 0) = 0
// t_r = T_dur_s = 0.10
// Ex8:
// t_a/t_ad/t_ds/t_sr t_r
// |- T_r_s ->|
// |--------->| T_dur_s
//
// T_a_s = .10, T_d_s = .10, (T_s_s = *), T_r_s = .10
// t_a = 0, t_ad = 0, t_ds = 0, t_sr = 0, t_r = .05
// T_dur_s = .05
// T_ads_s = max(T_dur_s - T_r_s, 0) = max(.05 - .10, 0) = 0
// t_ad = min(T_ads_s, T_a_s) = min(0, 0.10) = 0 < 0.10 = T_a_s
// t_ds = min(T_ads_s, T_a_s + T_d_s) = min(0, 0.10 + 0.10) = 0 < 0.20 = T_a_s + T_d_s
// t_sr = max(t_ds, T_ads_s) = max(0, 0) = 0
// t_r = T_dur_s = 0.05
// Ex9:
// t_a/t_ad/t_ds/t_sr/t_r
// |
// | T_dur_s
//
// T_a_s = .10, T_d_s = .10, (T_s_s = *), T_r_s = .10
// t_a = 0, t_ad = 0, t_ds = 0, t_sr = 0, t_r = 0
// T_dur_s = 0
// T_ads_s = max(T_dur_s - T_r_s, 0) = max(0 - .10, 0) = 0
// t_ad = min(T_ads_s, T_a_s) = min(0, 0.10) = 0 < 0.10 = T_a_s
// t_ds = min(T_ads_s, T_a_s + T_d_s) = min(0, 0.10 + 0.10) = 0 < 0.20 = T_a_s + T_d_s
// t_sr = max(t_ds, T_ads_s) = max(0, 0) = 0
// t_r = T_dur_s = 0
using namespace stloperators;
// T_dur_s = T_a_s + T_d_s + T_s + T_r_s.
const float T_dur_s = output.duration;
const float T_a_s = adsr.get_time_A_ms() * 1e-3f;
const float T_d_s = adsr.get_time_D_ms() * 1e-3f;
const std::optional<float> T_s_max_s = adsr.get_max_time_S_ms() * 1e-3f;
const float T_r_s = adsr.get_time_R_ms() * 1e-3f;
const float t_a = 0.f;
const float T_ads_s = std::max(T_dur_s - T_r_s, 0.f);
float t_ad = std::min(T_ads_s, T_a_s);
float t_ds = std::min(T_ads_s, T_a_s + T_d_s);
float t_sr = std::max(t_ds, T_ads_s); // T_dur_s - T_a_s - T_d_s - T_r_s;
float t_r = T_dur_s;
if (T_s_max_s.has_value())
{
auto T_adsr_s = T_a_s + T_d_s + T_s_max_s.value() + T_r_s;
if (T_adsr_s < T_dur_s)
{
t_ad = T_a_s;
t_ds = t_ad + T_d_s;
t_sr = t_ds + T_s_max_s.value();
t_r = t_sr + T_r_s;
}
}
float dt = calc_dt(wave);
float t = 0.f;
for (size_t i = 0; i < N; ++i)
{
t = i * dt;
//std::cout << t << '\n';
auto& s = output.buffer[i];
float env = 0.f;
float p = 0.f; // Param.
float pl = 0.f; // Linear Param.
if (math::in_range<float>(t, t_a, t_ad, Range::Closed))
{
//std::cout << "A";
pl = math::value_to_param(t, t_a, t_ad);
switch (adsr.get_shape_A())
{
case ADSRMode::LIN:
p = pl;
//env = math::linmap(t, t_a, t_ad, 0.f, 1.f);
break;
case ADSRMode::EXP:
p = std::exp(pl * math::c_ln2) - 1;
//env = std::exp(math::c_ln2 * (t - t_a)/attack_s) - 1;
break;
case ADSRMode::LOG:
p = std::log(pl * (math::c_e - 1) + 1);
//env = std::log((t - t_a)/attack_s*(math::c_e - 1) + 1);
break;
}
env = math::lerp(p, adsr.get_level_A0(), adsr.get_level_A1());
}
else if (math::in_range<float>(t, t_ad, t_ds, Range::OpenClosed))
{
//std::cout << "D";
pl = math::value_to_param(t, t_ad, t_ds);
switch (adsr.get_shape_D())
{
case ADSRMode::LIN:
p = pl;
//env = math::linmap(t, t_ad, t_ds, 1.f, sustain_lvl);
break;
case ADSRMode::EXP:
p = 2 - 2*std::exp(-pl * math::c_ln2);
//env = (2 - 2.f*sustain_lvl)*std::exp(-math::c_ln2*(t - t_ad)/decay_s) - (1 - 2.f*sustain_lvl);
break;
case ADSRMode::LOG:
p = -std::log(1 - pl*(1 - math::c_1_e));
//env = std::log(1-(t - t_ad)/decay_s*(1.f-std::exp(sustain_lvl - 1))) + 1;
break;
}
env = math::lerp(p, adsr.get_level_D0(), adsr.get_level_D1());
}
else if (math::in_range<float>(t, t_ds, t_sr, Range::OpenClosed))
{
//std::cout << "S";
env = adsr.get_level_S();
}
else if (math::in_range<float>(t, t_sr, t_r, Range::OpenClosed))
{
//std::cout << "R";
pl = math::value_to_param(t, t_sr, t_r);
switch (adsr.get_shape_R())
{
case ADSRMode::LIN:
p = pl;
//env = math::linmap(t, t_sr, t_r, sustain_lvl, 0.f);
break;
case ADSRMode::EXP:
p = 2 - 2*std::exp(-pl * math::c_ln2);
//env = 2.f*sustain_lvl*std::exp(-static_cast<float>(M_LN2)*(t - t_sr)/release_s) - sustain_lvl;
break;
case ADSRMode::LOG:
p = -std::log(1 - pl*(1 - math::c_1_e));
//env = sustain_lvl*(static_cast<float>(std::log(1-(t - t_sr))/release_s*(1-1./static_cast<float>(M_E))) + 1);
break;
}
env = math::lerp(p, adsr.get_level_R0(), adsr.get_level_R1());
}
//std::cout << env << ", ";
s *= env;
}
output.update_duration();
return output;
}
static Waveform envelope_adsr(const Waveform& wave,
const Attack& attack, const Decay& decay, const Sustain& sustain, const Release& release)
{
ADSR adsr(attack, decay, sustain, release);
return envelope_adsr(wave, adsr);
}
static Waveform resample(const Waveform& wave, int new_sample_rate = 44100,
FilterType filter_type = FilterType::Butterworth,
int filter_order = 1, float cutoff_freq_multiplier = 2.5f, float ripple = 0.1f)
{
if (wave.sample_rate == new_sample_rate)
return wave;
Waveform resampled_wave;
resampled_wave.copy_properties(wave);
resampled_wave.sample_rate = new_sample_rate;
// Calculate the resampling factor
float resampling_factor = static_cast<float>(wave.sample_rate) / new_sample_rate;
//resampled_wave.duration = wave.duration * resampling_factor;
// Calculate the new size of the buffer
size_t new_size = static_cast<size_t>(wave.buffer.size() / resampling_factor);
// Resize the buffer in the resampled_wave struct
resampled_wave.buffer.resize(new_size);
// Perform linear interpolation to fill the new buffer
for (size_t i = 0; i < new_size; ++i)
{
float index_f = i * resampling_factor;
size_t index = static_cast<size_t>(index_f);
float fraction = index_f - index;
// Linear interpolation
resampled_wave.buffer[i] = (1.0f - fraction) * wave.buffer[index]
+ fraction * wave.buffer[index + 1];
}
auto filtered_wave = filter(resampled_wave, filter_type, FilterOpType::LowPass,
filter_order, cutoff_freq_multiplier * wave.frequency, ripple, true);
filtered_wave.update_duration();
return filtered_wave;
}
static Waveform filter(const Waveform& wave, const FilterArgs& args)
{
std::optional<float> bandwidth;
if (args.bandwidth_freq_multiplier.has_value())
bandwidth = args.bandwidth_freq_multiplier.value() * wave.frequency;
return filter(wave,
args.filter_type,
args.filter_op_type,
args.filter_order,
args.cutoff_freq_multiplier * wave.frequency,
bandwidth,
args.ripple,
args.normalize_filtered_wave);
}
static Waveform filter(const Waveform& wave,
FilterType type,
FilterOpType op_type,
int filter_order,
float freq_cutoff_hz, std::optional<float> freq_bandwidth_hz,
float ripple = 0.1f, // ripple: For Chebychev filters.
bool normalize_filtered_wave = false)
{
auto filtered_wave = wave;
Filter flt;
switch (type)
{
case FilterType::Butterworth:
flt = create_Butterworth_filter(filter_order, op_type, freq_cutoff_hz, freq_bandwidth_hz, wave.sample_rate);
break;
case FilterType::ChebyshevTypeI:
flt = create_ChebyshevI_filter(filter_order, op_type, freq_cutoff_hz, freq_bandwidth_hz, ripple, wave.sample_rate);
break;
case FilterType::ChebyshevTypeII:
flt = create_ChebyshevII_filter(filter_order, op_type, freq_cutoff_hz, freq_bandwidth_hz, ripple, wave.sample_rate);
break;
default:
return wave;
}
filtered_wave.buffer = filter(wave.buffer, flt);
clamp(filtered_wave);
if (normalize_filtered_wave)
normalize(filtered_wave, true);
return filtered_wave;
}
static Waveform filter(const Waveform& wave,
const Filter& filter)
{
Waveform ret = wave;
ret.buffer = WaveformHelper::filter(wave.buffer, filter);
return ret;
}
static std::vector<float> filter(const std::vector<float>& x,
const Filter& filter)
{
size_t Ns = x.size();
size_t Na = filter.a.size();
size_t Nb = filter.b.size();
std::vector<float> y(Ns, 0);
// Apply the filter (Direct Form I)
for (size_t n = 0; n < Ns; ++n)
{
y[n] = 0;
// Summing the b terms
for (size_t i = 0; i < Nb; i++)
{
if (n >= i)
y[n] += filter.b[i] * x[n - i];
}
// Subtracting the a terms
for (size_t i = 1; i < Na; i++)
{
if (n >= i)
y[n] -= filter.a[i] * y[n - i];
}
y[n] /= filter.a[0]; // Normalize output
}
return y;
}
static Filter create_Butterworth_filter(int order,
FilterOpType type,
float freq_cutoff, std::optional<float> freq_bandwidth,
int sample_rate = 44100)
{
Filter flt;
if (type == FilterOpType::NONE)
return flt;
if (order <= 0)
{
std::cerr << "The order of the Butterworth filter must be at least 1!" << std::endl;
return flt;
}
if ((type == FilterOpType::BandPass || type == FilterOpType::BandStop) && !freq_bandwidth.has_value())
{
std::cerr << "freq_bandwidth must be specified when creating a BandPass or BandStop filter!" << std::endl;
return flt;
}
std::vector<double> W_cutoff;
if (freq_bandwidth.has_value())
{
// 2*(Fc - BW/2)/Fs
// 2*(Fc + BW/2)/Fs
W_cutoff.reserve(2);
W_cutoff.emplace_back(std::max(0.f, (2 * freq_cutoff - freq_bandwidth.value()) / sample_rate));
W_cutoff.emplace_back((2 * freq_cutoff + freq_bandwidth.value()) / sample_rate);
}
else
{
W_cutoff.reserve(1);
W_cutoff.emplace_back(2 * freq_cutoff / sample_rate);
}
double fs2 = 2.;
for (auto& wc : W_cutoff)
wc = 2. / fs2 * std::tan(math::c_pi * wc / fs2);
FilterS s;
s.poles.reserve(order);
auto v = static_cast<double>(order + 1);
for (int i = 1; i <= order; ++i)
{
s.poles.emplace_back(std::exp(1i * M_PI * (0.5 * v / order)));
v += 2.;
}
// It is supposed to be -1 here. Makes sure the value is clean.
if (order % 2 == 1)
s.poles[(order - 1)/2] = -1.;
s.gain = 1.;
s = filter_edge_adjustment(s, type, W_cutoff[0], W_cutoff.size() == 2 ? W_cutoff[1] : 0.f);
bilinear(s, fs2);
flt.b = stlutils::static_cast_vector<float>(stlutils::mult_scalar(poly(s.zeroes), s.gain));
flt.a = stlutils::static_cast_vector<float>(poly(s.poles));
return flt;
}
static Filter create_ChebyshevI_filter(int order,
FilterOpType type,
float freq_cutoff, std::optional<float> freq_bandwidth,
float ripple,
int sample_rate = 44100)
{
Filter flt;
if (type == FilterOpType::NONE)
return flt;