-
Notifications
You must be signed in to change notification settings - Fork 513
/
reverb.cpp
1848 lines (1605 loc) · 68.5 KB
/
reverb.cpp
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
/**
* Ambisonic reverb engine for the OpenAL cross platform audio library
* Copyright (C) 2008-2017 by Chris Robinson and Christopher Fitzgerald.
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library 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
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
* Or go to http://www.gnu.org/copyleft/lgpl.html
*/
#include "config.h"
#include <algorithm>
#include <array>
#include <cassert>
#include <cmath>
#include <cstdint>
#include <cstdio>
#include <numeric>
#include <utility>
#include <variant>
#include "alc/effects/base.h"
#include "almalloc.h"
#include "alnumbers.h"
#include "alnumeric.h"
#include "alspan.h"
#include "core/ambidefs.h"
#include "core/bufferline.h"
#include "core/context.h"
#include "core/cubic_tables.h"
#include "core/device.h"
#include "core/effects/base.h"
#include "core/effectslot.h"
#include "core/filters/biquad.h"
#include "core/filters/splitter.h"
#include "core/mixer.h"
#include "core/mixer/defs.h"
#include "intrusive_ptr.h"
#include "opthelpers.h"
#include "vector.h"
struct BufferStorage;
namespace {
using uint = unsigned int;
constexpr float MaxModulationTime{4.0f};
constexpr float DefaultModulationTime{0.25f};
#define MOD_FRACBITS 24
#define MOD_FRACONE (1<<MOD_FRACBITS)
#define MOD_FRACMASK (MOD_FRACONE-1)
/* Max samples per process iteration. Used to limit the size needed for
* temporary buffers. Must be a multiple of 4 for SIMD alignment.
*/
constexpr size_t MAX_UPDATE_SAMPLES{256};
/* The number of spatialized lines or channels to process. Four channels allows
* for a 3D A-Format response. NOTE: This can't be changed without taking care
* of the conversion matrices, and a few places where the length arrays are
* assumed to have 4 elements.
*/
constexpr size_t NUM_LINES{4u};
/* This coefficient is used to define the maximum frequency range controlled by
* the modulation depth. The current value of 0.05 will allow it to swing from
* 0.95x to 1.05x. This value must be below 1. At 1 it will cause the sampler
* to stall on the downswing, and above 1 it will cause it to sample backwards.
* The value 0.05 seems be nearest to Creative hardware behavior.
*/
constexpr float MODULATION_DEPTH_COEFF{0.05f};
/* The B-Format to (W-normalized) A-Format conversion matrix. This produces a
* tetrahedral array of discrete signals (boosted by a factor of sqrt(3), to
* reduce the error introduced in the conversion).
*/
alignas(16) constexpr std::array<std::array<float,NUM_LINES>,NUM_LINES> B2A{{
/* W Y Z X */
{{ 0.5f, 0.5f, 0.5f, 0.5f }}, /* A0 */
{{ 0.5f, -0.5f, -0.5f, 0.5f }}, /* A1 */
{{ 0.5f, 0.5f, -0.5f, -0.5f }}, /* A2 */
{{ 0.5f, -0.5f, 0.5f, -0.5f }} /* A3 */
}};
/* Converts (W-normalized) A-Format to B-Format for early reflections (scaled
* by 1/sqrt(3) to compensate for the boost in the B2A matrix).
*/
alignas(16) constexpr std::array<std::array<float,NUM_LINES>,NUM_LINES> EarlyA2B{{
/* A0 A1 A2 A3 */
{{ 0.5f, 0.5f, 0.5f, 0.5f }}, /* W */
{{ 0.5f, -0.5f, 0.5f, -0.5f }}, /* Y */
{{ 0.5f, -0.5f, -0.5f, 0.5f }}, /* Z */
{{ 0.5f, 0.5f, -0.5f, -0.5f }} /* X */
}};
/* Converts (W-normalized) A-Format to B-Format for late reverb (scaled
* by 1/sqrt(3) to compensate for the boost in the B2A matrix). The response
* is rotated around Z (ambisonic X) so that the front lines are placed
* horizontally in front, and the rear lines are placed vertically in back.
*/
constexpr auto InvSqrt2 = static_cast<float>(1.0/al::numbers::sqrt2);
alignas(16) constexpr std::array<std::array<float,NUM_LINES>,NUM_LINES> LateA2B{{
/* A0 A1 A2 A3 */
{{ 0.5f, 0.5f, 0.5f, 0.5f }}, /* W */
{{ InvSqrt2, -InvSqrt2, 0.0f, 0.0f }}, /* Y */
{{ 0.0f, 0.0f, -InvSqrt2, InvSqrt2 }}, /* Z */
{{ 0.5f, 0.5f, -0.5f, -0.5f }} /* X */
}};
/* The all-pass and delay lines have a variable length dependent on the
* effect's density parameter, which helps alter the perceived environment
* size. The size-to-density conversion is a cubed scale:
*
* density = min(1.0, pow(size, 3.0) / DENSITY_SCALE);
*
* The line lengths scale linearly with room size, so the inverse density
* conversion is needed, taking the cube root of the re-scaled density to
* calculate the line length multiplier:
*
* length_mult = max(5.0, cbrt(density*DENSITY_SCALE));
*
* The density scale below will result in a max line multiplier of 50, for an
* effective size range of 5m to 50m.
*/
constexpr float DENSITY_SCALE{125000.0f};
/* All delay line lengths are specified in seconds.
*
* To approximate early reflections, we break them up into primary (those
* arriving from the same direction as the source) and secondary (those
* arriving from the opposite direction).
*
* The early taps decorrelate the 4-channel signal to approximate an average
* room response for the primary reflections after the initial early delay.
*
* Given an average room dimension (d_a) and the speed of sound (c) we can
* calculate the average reflection delay (r_a) regardless of listener and
* source positions as:
*
* r_a = d_a / c
* c = 343.3
*
* This can extended to finding the average difference (r_d) between the
* maximum (r_1) and minimum (r_0) reflection delays:
*
* r_0 = 2 / 3 r_a
* = r_a - r_d / 2
* = r_d
* r_1 = 4 / 3 r_a
* = r_a + r_d / 2
* = 2 r_d
* r_d = 2 / 3 r_a
* = r_1 - r_0
*
* As can be determined by integrating the 1D model with a source (s) and
* listener (l) positioned across the dimension of length (d_a):
*
* r_d = int_(l=0)^d_a (int_(s=0)^d_a |2 d_a - 2 (l + s)| ds) dl / c
*
* The initial taps (T_(i=0)^N) are then specified by taking a power series
* that ranges between r_0 and half of r_1 less r_0:
*
* R_i = 2^(i / (2 N - 1)) r_d
* = r_0 + (2^(i / (2 N - 1)) - 1) r_d
* = r_0 + T_i
* T_i = R_i - r_0
* = (2^(i / (2 N - 1)) - 1) r_d
*
* Assuming an average of 1m, we get the following taps:
*/
constexpr std::array<float,NUM_LINES> EARLY_TAP_LENGTHS{{
0.0000000e+0f, 2.0213520e-4f, 4.2531060e-4f, 6.7171600e-4f
}};
/* The early all-pass filter lengths are based on the early tap lengths:
*
* A_i = R_i / a
*
* Where a is the approximate maximum all-pass cycle limit (20).
*/
constexpr std::array<float,NUM_LINES> EARLY_ALLPASS_LENGTHS{{
9.7096800e-5f, 1.0720356e-4f, 1.1836234e-4f, 1.3068260e-4f
}};
/* The early delay lines are used to transform the primary reflections into
* the secondary reflections. The A-format is arranged in such a way that
* the channels/lines are spatially opposite:
*
* C_i is opposite C_(N-i-1)
*
* The delays of the two opposing reflections (R_i and O_i) from a source
* anywhere along a particular dimension always sum to twice its full delay:
*
* 2 r_a = R_i + O_i
*
* With that in mind we can determine the delay between the two reflections
* and thus specify our early line lengths (L_(i=0)^N) using:
*
* O_i = 2 r_a - R_(N-i-1)
* L_i = O_i - R_(N-i-1)
* = 2 (r_a - R_(N-i-1))
* = 2 (r_a - T_(N-i-1) - r_0)
* = 2 r_a (1 - (2 / 3) 2^((N - i - 1) / (2 N - 1)))
*
* Using an average dimension of 1m, we get:
*/
constexpr std::array<float,NUM_LINES> EARLY_LINE_LENGTHS{{
0.0000000e+0f, 4.9281100e-4f, 9.3916180e-4f, 1.3434322e-3f
}};
/* The late all-pass filter lengths are based on the late line lengths:
*
* A_i = (5 / 3) L_i / r_1
*/
constexpr std::array<float,NUM_LINES> LATE_ALLPASS_LENGTHS{{
1.6182800e-4f, 2.0389060e-4f, 2.8159360e-4f, 3.2365600e-4f
}};
/* The late lines are used to approximate the decaying cycle of recursive
* late reflections.
*
* Splitting the lines in half, we start with the shortest reflection paths
* (L_(i=0)^(N/2)):
*
* L_i = 2^(i / (N - 1)) r_d
*
* Then for the opposite (longest) reflection paths (L_(i=N/2)^N):
*
* L_i = 2 r_a - L_(i-N/2)
* = 2 r_a - 2^((i - N / 2) / (N - 1)) r_d
*
* For our 1m average room, we get:
*/
constexpr std::array<float,NUM_LINES> LATE_LINE_LENGTHS{{
1.9419362e-3f, 2.4466860e-3f, 3.3791220e-3f, 3.8838720e-3f
}};
using ReverbUpdateLine = std::array<float,MAX_UPDATE_SAMPLES>;
struct DelayLineI {
/* The delay lines use interleaved samples, with the lengths being powers
* of 2 to allow the use of bit-masking instead of a modulus for wrapping.
*/
al::span<float> mLine;
/* Given the allocated sample buffer, this function updates each delay line
* offset.
*/
void realizeLineOffset(al::span<float> sampleBuffer) noexcept
{ mLine = sampleBuffer; }
/* Calculate the length of a delay line and store its mask and offset. */
static
auto calcLineLength(const float length, const float frequency, const uint extra) -> size_t
{
/* All line lengths are powers of 2, calculated from their lengths in
* seconds, rounded up.
*/
uint samples{float2uint(std::ceil(length*frequency))};
samples = NextPowerOf2(samples + extra);
/* Return the sample count for accumulation. */
return samples*NUM_LINES;
}
};
struct DelayLineU {
al::span<float> mLine;
void realizeLineOffset(al::span<float> sampleBuffer) noexcept
{ mLine = sampleBuffer; }
static
auto calcLineLength(const float length, const float frequency, const uint extra) -> size_t
{
uint samples{float2uint(std::ceil(length*frequency))};
samples = NextPowerOf2(samples + extra);
return samples*NUM_LINES;
}
[[nodiscard]]
auto get(size_t chan) const noexcept
{
const size_t stride{mLine.size() / NUM_LINES};
return mLine.subspan(chan*stride, stride);
}
void write(size_t offset, const size_t c, al::span<const float> in) const noexcept
{
const size_t stride{mLine.size() / NUM_LINES};
const auto output = mLine.subspan(c*stride);
while(!in.empty())
{
offset &= stride-1;
const size_t td{std::min(stride - offset, in.size())};
std::copy_n(in.begin(), td, output.begin() + ptrdiff_t(offset));
offset += td;
in = in.subspan(td);
}
}
/* Writes the given input lines to the delay buffer, applying a geometric
* reflection. This effectively applies the matrix
*
* [ +1/2 -1/2 -1/2 -1/2 ]
* [ -1/2 +1/2 -1/2 -1/2 ]
* [ -1/2 -1/2 +1/2 -1/2 ]
* [ -1/2 -1/2 -1/2 +1/2 ]
*
* to the four input lines when writing to the delay buffer. The effect on
* the B-Format signal is negating W, applying a 180-degree phase shift and
* moving each response to its spatially opposite location.
*/
void writeReflected(size_t offset, const al::span<const ReverbUpdateLine,NUM_LINES> in,
const size_t count) const noexcept
{
const size_t stride{mLine.size() / NUM_LINES};
ASSUME(count > 0);
for(size_t i{0u};i < count;)
{
offset &= stride-1;
size_t td{std::min(stride - offset, count - i)};
do {
const std::array src{in[0][i], in[1][i], in[2][i], in[3][i]};
++i;
const std::array f{
(src[0] - src[1] - src[2] - src[3]) * 0.5f,
(src[1] - src[0] - src[2] - src[3]) * 0.5f,
(src[2] - src[0] - src[1] - src[3]) * 0.5f,
(src[3] - src[0] - src[1] - src[2] ) * 0.5f
};
mLine[0*stride + offset] = f[0];
mLine[1*stride + offset] = f[1];
mLine[2*stride + offset] = f[2];
mLine[3*stride + offset] = f[3];
++offset;
} while(--td);
}
}
};
struct VecAllpass {
DelayLineI Delay;
float Coeff{0.0f};
std::array<size_t,NUM_LINES> Offset{};
void process(const al::span<ReverbUpdateLine,NUM_LINES> samples, size_t offset,
const float xCoeff, const float yCoeff, const size_t todo) noexcept;
};
struct Allpass4 {
DelayLineU Delay;
float Coeff{0.0f};
std::array<size_t,NUM_LINES> Offset{};
void process(const al::span<ReverbUpdateLine,NUM_LINES> samples, const size_t offset,
const size_t todo) noexcept;
};
struct T60Filter {
/* Two filters are used to adjust the signal. One to control the low
* frequencies, and one to control the high frequencies.
*/
float MidGain{0.0f};
BiquadFilter HFFilter, LFFilter;
void calcCoeffs(const float length, const float lfDecayTime, const float mfDecayTime,
const float hfDecayTime, const float lf0norm, const float hf0norm);
/* Applies the two T60 damping filter sections. */
void process(const al::span<float> samples)
{ DualBiquad{HFFilter, LFFilter}.process(samples, samples); }
void clear() noexcept { HFFilter.clear(); LFFilter.clear(); }
};
struct EarlyReflections {
Allpass4 VecAp;
/* An echo line is used to complete the second half of the early
* reflections.
*/
DelayLineU Delay;
std::array<size_t,NUM_LINES> Offset{};
std::array<float,NUM_LINES> Coeff{};
/* The gain for each output channel based on 3D panning. */
struct OutGains {
std::array<float,MaxAmbiChannels> Current{};
std::array<float,MaxAmbiChannels> Target{};
};
std::array<OutGains,NUM_LINES> Gains{};
void updateLines(const float density_mult, const float diffusion, const float decayTime,
const float frequency);
};
struct Modulation {
/* The vibrato time is tracked with an index over a (MOD_FRACONE)
* normalized range.
*/
uint Index{}, Step{};
/* The depth of frequency change, in samples. */
float Depth{};
std::array<uint,MAX_UPDATE_SAMPLES> ModDelays{};
void updateModulator(float modTime, float modDepth, float frequency);
void calcDelays(size_t todo);
};
struct LateReverb {
/* A recursive delay line is used fill in the reverb tail. */
DelayLineU Delay;
std::array<size_t,NUM_LINES> Offset{};
/* Attenuation to compensate for the modal density and decay rate of the
* late lines.
*/
float DensityGain{0.0f};
/* T60 decay filters are used to simulate absorption. */
std::array<T60Filter,NUM_LINES> T60;
Modulation Mod;
/* A Gerzon vector all-pass filter is used to simulate diffusion. */
VecAllpass VecAp;
/* The gain for each output channel based on 3D panning. */
struct OutGains {
std::array<float,MaxAmbiChannels> Current{};
std::array<float,MaxAmbiChannels> Target{};
};
std::array<OutGains,NUM_LINES> Gains{};
void updateLines(const float density_mult, const float diffusion, const float lfDecayTime,
const float mfDecayTime, const float hfDecayTime, const float lf0norm,
const float hf0norm, const float frequency);
void clear() noexcept
{
for(auto &filter : T60)
filter.clear();
}
};
struct ReverbPipeline {
/* Master effect filters */
struct FilterPair {
BiquadFilter Lp;
BiquadFilter Hp;
};
std::array<FilterPair,NUM_LINES> mFilter;
/* Late reverb input delay line (early reflections feed this, and late
* reverb taps from it).
*/
DelayLineU mLateDelayIn;
/* Tap points for early reflection input delay. */
std::array<std::array<size_t,2>,NUM_LINES> mEarlyDelayTap{};
std::array<std::array<float,2>,NUM_LINES> mEarlyDelayCoeff{};
/* Tap points for late reverb feed and delay. */
std::array<std::array<size_t,2>,NUM_LINES> mLateDelayTap{};
/* Coefficients for the all-pass and line scattering matrices. */
float mMixX{0.0f};
float mMixY{0.0f};
EarlyReflections mEarly;
LateReverb mLate;
std::array<std::array<BandSplitter,NUM_LINES>,2> mAmbiSplitter;
size_t mFadeSampleCount{1};
void updateDelayLine(const float gain, const float earlyDelay, const float lateDelay,
const float density_mult, const float decayTime, const float frequency);
void update3DPanning(const al::span<const float,3> ReflectionsPan,
const al::span<const float,3> LateReverbPan, const float earlyGain, const float lateGain,
const bool doUpmix, const MixParams *mainMix);
void processEarly(const DelayLineU &main_delay, size_t offset, const size_t samplesToDo,
const al::span<ReverbUpdateLine,NUM_LINES> tempSamples,
const al::span<FloatBufferLine,NUM_LINES> outSamples);
void processLate(size_t offset, const size_t samplesToDo,
const al::span<ReverbUpdateLine,NUM_LINES> tempSamples,
const al::span<FloatBufferLine,NUM_LINES> outSamples);
void clear() noexcept
{
for(auto &filter : mFilter)
{
filter.Lp.clear();
filter.Hp.clear();
}
mLate.clear();
for(auto &filters : mAmbiSplitter)
{
for(auto &filter : filters)
filter.clear();
}
}
};
struct ReverbState final : public EffectState {
/* All delay lines are allocated as a single buffer to reduce memory
* fragmentation and management code.
*/
al::vector<float,16> mSampleBuffer;
struct Params {
/* Calculated parameters which indicate if cross-fading is needed after
* an update.
*/
float Density{1.0f};
float Diffusion{1.0f};
float DecayTime{1.49f};
float HFDecayTime{0.83f * 1.49f};
float LFDecayTime{1.0f * 1.49f};
float ModulationTime{0.25f};
float ModulationDepth{0.0f};
float HFReference{5000.0f};
float LFReference{250.0f};
};
Params mParams;
enum PipelineState : uint8_t {
DeviceClear,
StartFade,
Fading,
Cleanup,
Normal,
};
PipelineState mPipelineState{DeviceClear};
bool mCurrentPipeline{false};
/* Core delay line (early reflections tap from this). */
DelayLineU mMainDelay;
std::array<ReverbPipeline,2> mPipelines;
/* The current write offset for all delay lines. */
size_t mOffset{};
/* Temporary storage used when processing. */
alignas(16) FloatBufferLine mTempLine{};
alignas(16) std::array<ReverbUpdateLine,NUM_LINES> mTempSamples{};
alignas(16) std::array<FloatBufferLine,NUM_LINES> mEarlySamples{};
alignas(16) std::array<FloatBufferLine,NUM_LINES> mLateSamples{};
std::array<float,MaxAmbiOrder+1> mOrderScales{};
bool mUpmixOutput{false};
void MixOutPlain(ReverbPipeline &pipeline, const al::span<FloatBufferLine> samplesOut,
const size_t todo) const
{
ASSUME(todo > 0);
/* When not upsampling, the panning gains convert to B-Format and pan
* at the same time.
*/
auto inBuffer = mEarlySamples.cbegin();
for(auto &gains : pipeline.mEarly.Gains)
{
MixSamples(al::span{*inBuffer++}.first(todo), samplesOut, gains.Current, gains.Target,
todo, 0);
}
inBuffer = mLateSamples.cbegin();
for(auto &gains : pipeline.mLate.Gains)
{
MixSamples(al::span{*inBuffer++}.first(todo), samplesOut, gains.Current, gains.Target,
todo, 0);
}
}
void MixOutAmbiUp(ReverbPipeline &pipeline, const al::span<FloatBufferLine> samplesOut,
const size_t todo)
{
ASSUME(todo > 0);
auto DoMixRow = [](const al::span<float> OutBuffer, const al::span<const float,4> Gains,
const al::span<const FloatBufferLine,4> InSamples)
{
auto inBuffer = InSamples.cbegin();
std::fill(OutBuffer.begin(), OutBuffer.end(), 0.0f);
for(const float gain : Gains)
{
if(std::fabs(gain) > GainSilenceThreshold)
{
auto mix_sample = [gain](const float sample, const float in) noexcept -> float
{ return sample + in*gain; };
std::transform(OutBuffer.begin(), OutBuffer.end(), inBuffer->cbegin(),
OutBuffer.begin(), mix_sample);
}
++inBuffer;
}
};
/* When upsampling, the B-Format conversion needs to be done separately
* so the proper HF scaling can be applied to each B-Format channel.
* The panning gains then pan and upsample the B-Format channels.
*/
const al::span<float> tmpspan{al::assume_aligned<16>(mTempLine.data()), todo};
float hfscale{mOrderScales[0]};
auto splitter = pipeline.mAmbiSplitter[0].begin();
auto a2bcoeffs = EarlyA2B.cbegin();
for(auto &gains : pipeline.mEarly.Gains)
{
DoMixRow(tmpspan, *(a2bcoeffs++), mEarlySamples);
/* Apply scaling to the B-Format's HF response to "upsample" it to
* higher-order output.
*/
(splitter++)->processHfScale(tmpspan, hfscale);
hfscale = mOrderScales[1];
MixSamples(tmpspan, samplesOut, gains.Current, gains.Target, todo, 0);
}
hfscale = mOrderScales[0];
splitter = pipeline.mAmbiSplitter[1].begin();
a2bcoeffs = LateA2B.cbegin();
for(auto &gains : pipeline.mLate.Gains)
{
DoMixRow(tmpspan, *(a2bcoeffs++), mLateSamples);
(splitter++)->processHfScale(tmpspan, hfscale);
hfscale = mOrderScales[1];
MixSamples(tmpspan, samplesOut, gains.Current, gains.Target, todo, 0);
}
}
void mixOut(ReverbPipeline &pipeline, const al::span<FloatBufferLine> samplesOut, const size_t todo)
{
if(mUpmixOutput)
MixOutAmbiUp(pipeline, samplesOut, todo);
else
MixOutPlain(pipeline, samplesOut, todo);
}
void allocLines(const float frequency);
void deviceUpdate(const DeviceBase *device, const BufferStorage *buffer) override;
void update(const ContextBase *context, const EffectSlot *slot, const EffectProps *props,
const EffectTarget target) override;
void process(const size_t samplesToDo, const al::span<const FloatBufferLine> samplesIn,
const al::span<FloatBufferLine> samplesOut) override;
};
/**************************************
* Device Update *
**************************************/
inline float CalcDelayLengthMult(float density)
{ return std::max(5.0f, std::cbrt(density*DENSITY_SCALE)); }
/* Calculates the delay line metrics and allocates the shared sample buffer
* for all lines given the sample rate (frequency).
*/
void ReverbState::allocLines(const float frequency)
{
/* Multiplier for the maximum density value, i.e. density=1, which is
* actually the least density...
*/
const float multiplier{CalcDelayLengthMult(1.0f)};
/* The modulator's line length is calculated from the maximum modulation
* time and depth coefficient, and halfed for the low-to-high frequency
* swing.
*/
static constexpr float max_mod_delay{MaxModulationTime*MODULATION_DEPTH_COEFF / 2.0f};
std::array<size_t,11> linelengths{};
size_t oidx{0};
size_t totalSamples{0u};
/* The main delay length includes the maximum early reflection delay and
* the largest early tap width. It must also be extended by the update size
* (BufferLineSize) for block processing.
*/
float length{ReverbMaxReflectionsDelay + EARLY_TAP_LENGTHS.back()*multiplier};
size_t count{mMainDelay.calcLineLength(length, frequency, BufferLineSize)};
linelengths[oidx++] = count;
totalSamples += count;
for(auto &pipeline : mPipelines)
{
static constexpr float LateDiffAvg{(LATE_LINE_LENGTHS.back()-LATE_LINE_LENGTHS.front()) /
float{NUM_LINES}};
length = ReverbMaxLateReverbDelay + LateDiffAvg*multiplier;
count = pipeline.mLateDelayIn.calcLineLength(length, frequency, BufferLineSize);
linelengths[oidx++] = count;
totalSamples += count;
/* The early vector all-pass line. */
length = EARLY_ALLPASS_LENGTHS.back() * multiplier;
count = pipeline.mEarly.VecAp.Delay.calcLineLength(length, frequency, 0);
linelengths[oidx++] = count;
totalSamples += count;
/* The early reflection line. */
length = EARLY_LINE_LENGTHS.back() * multiplier;
count = pipeline.mEarly.Delay.calcLineLength(length, frequency, MAX_UPDATE_SAMPLES);
linelengths[oidx++] = count;
totalSamples += count;
/* The late vector all-pass line. */
length = LATE_ALLPASS_LENGTHS.back() * multiplier;
count = pipeline.mLate.VecAp.Delay.calcLineLength(length, frequency, 0);
linelengths[oidx++] = count;
totalSamples += count;
/* The late delay lines are calculated from the largest maximum density
* line length, and the maximum modulation delay. Four additional
* samples are needed for resampling the modulator delay.
*/
length = LATE_LINE_LENGTHS.back()*multiplier + max_mod_delay;
count = pipeline.mLate.Delay.calcLineLength(length, frequency, 4);
linelengths[oidx++] = count;
totalSamples += count;
}
assert(oidx == linelengths.size());
if(totalSamples != mSampleBuffer.size())
decltype(mSampleBuffer)(totalSamples).swap(mSampleBuffer);
/* Clear the sample buffer. */
std::fill(mSampleBuffer.begin(), mSampleBuffer.end(), 0.0f);
/* Update all delays to reflect the new sample buffer. */
auto bufferspan = al::span{mSampleBuffer};
oidx = 0;
mMainDelay.realizeLineOffset(bufferspan.first(linelengths[oidx]));
bufferspan = bufferspan.subspan(linelengths[oidx++]);
for(auto &pipeline : mPipelines)
{
pipeline.mLateDelayIn.realizeLineOffset(bufferspan.first(linelengths[oidx]));
bufferspan = bufferspan.subspan(linelengths[oidx++]);
pipeline.mEarly.VecAp.Delay.realizeLineOffset(bufferspan.first(linelengths[oidx]));
bufferspan = bufferspan.subspan(linelengths[oidx++]);
pipeline.mEarly.Delay.realizeLineOffset(bufferspan.first(linelengths[oidx]));
bufferspan = bufferspan.subspan(linelengths[oidx++]);
pipeline.mLate.VecAp.Delay.realizeLineOffset(bufferspan.first(linelengths[oidx]));
bufferspan = bufferspan.subspan(linelengths[oidx++]);
pipeline.mLate.Delay.realizeLineOffset(bufferspan.first(linelengths[oidx]));
bufferspan = bufferspan.subspan(linelengths[oidx++]);
}
assert(oidx == linelengths.size());
}
void ReverbState::deviceUpdate(const DeviceBase *device, const BufferStorage*)
{
const auto frequency = static_cast<float>(device->Frequency);
/* Allocate the delay lines. */
allocLines(frequency);
for(auto &pipeline : mPipelines)
{
/* Clear filters and gain coefficients since the delay lines were all
* just cleared (if not reallocated).
*/
for(auto &filter : pipeline.mFilter)
{
filter.Lp.clear();
filter.Hp.clear();
}
for(auto &coeffs : pipeline.mEarlyDelayCoeff)
coeffs.fill(0.0f);
pipeline.mLate.DensityGain = 0.0f;
for(auto &t60 : pipeline.mLate.T60)
{
t60.MidGain = 0.0f;
t60.HFFilter.clear();
t60.LFFilter.clear();
}
pipeline.mLate.Mod.Index = 0;
pipeline.mLate.Mod.Step = 1;
pipeline.mLate.Mod.Depth = 0.0f;
for(auto &gains : pipeline.mEarly.Gains)
{
gains.Current.fill(0.0f);
gains.Target.fill(0.0f);
}
for(auto &gains : pipeline.mLate.Gains)
{
gains.Current.fill(0.0f);
gains.Target.fill(0.0f);
}
}
mPipelineState = DeviceClear;
/* Reset offset base. */
mOffset = 0;
if(device->mAmbiOrder > 1)
{
mUpmixOutput = true;
mOrderScales = AmbiScale::GetHFOrderScales(1, device->mAmbiOrder, device->m2DMixing);
}
else
{
mUpmixOutput = false;
mOrderScales.fill(1.0f);
}
mPipelines[0].mAmbiSplitter[0][0].init(device->mXOverFreq / frequency);
for(auto &pipeline : mPipelines)
{
std::fill(pipeline.mAmbiSplitter[0].begin(), pipeline.mAmbiSplitter[0].end(),
pipeline.mAmbiSplitter[0][0]);
std::fill(pipeline.mAmbiSplitter[1].begin(), pipeline.mAmbiSplitter[1].end(),
pipeline.mAmbiSplitter[0][0]);
}
}
/**************************************
* Effect Update *
**************************************/
/* Calculate a decay coefficient given the length of each cycle and the time
* until the decay reaches -60 dB.
*/
inline float CalcDecayCoeff(const float length, const float decayTime)
{ return std::pow(ReverbDecayGain, length/decayTime); }
/* Calculate a decay length from a coefficient and the time until the decay
* reaches -60 dB.
*/
inline float CalcDecayLength(const float coeff, const float decayTime)
{
constexpr float log10_decaygain{-3.0f/*std::log10(ReverbDecayGain)*/};
return std::log10(coeff) * decayTime / log10_decaygain;
}
/* Calculate an attenuation to be applied to the input of any echo models to
* compensate for modal density and decay time.
*/
inline float CalcDensityGain(const float a)
{
/* The energy of a signal can be obtained by finding the area under the
* squared signal. This takes the form of Sum(x_n^2), where x is the
* amplitude for the sample n.
*
* Decaying feedback matches exponential decay of the form Sum(a^n),
* where a is the attenuation coefficient, and n is the sample. The area
* under this decay curve can be calculated as: 1 / (1 - a).
*
* Modifying the above equation to find the area under the squared curve
* (for energy) yields: 1 / (1 - a^2). Input attenuation can then be
* calculated by inverting the square root of this approximation,
* yielding: 1 / sqrt(1 / (1 - a^2)), simplified to: sqrt(1 - a^2).
*/
return std::sqrt(1.0f - a*a);
}
/* Calculate the scattering matrix coefficients given a diffusion factor. */
inline void CalcMatrixCoeffs(const float diffusion, float *x, float *y)
{
/* The matrix is of order 4, so n is sqrt(4 - 1). */
constexpr float n{al::numbers::sqrt3_v<float>};
const float t{diffusion * std::atan(n)};
/* Calculate the first mixing matrix coefficient. */
*x = std::cos(t);
/* Calculate the second mixing matrix coefficient. */
*y = std::sin(t) / n;
}
/* Calculate the limited HF ratio for use with the late reverb low-pass
* filters.
*/
float CalcLimitedHfRatio(const float hfRatio, const float airAbsorptionGainHF,
const float decayTime)
{
/* Find the attenuation due to air absorption in dB (converting delay
* time to meters using the speed of sound). Then reversing the decay
* equation, solve for HF ratio. The delay length is cancelled out of
* the equation, so it can be calculated once for all lines.
*/
float limitRatio{1.0f / SpeedOfSoundMetersPerSec /
CalcDecayLength(airAbsorptionGainHF, decayTime)};
/* Using the limit calculated above, apply the upper bound to the HF ratio. */
return std::min(limitRatio, hfRatio);
}
/* Calculates the 3-band T60 damping coefficients for a particular delay line
* of specified length, using a combination of two shelf filter sections given
* decay times for each band split at two reference frequencies.
*/
void T60Filter::calcCoeffs(const float length, const float lfDecayTime,
const float mfDecayTime, const float hfDecayTime, const float lf0norm,
const float hf0norm)
{
const float mfGain{CalcDecayCoeff(length, mfDecayTime)};
const float lfGain{CalcDecayCoeff(length, lfDecayTime) / mfGain};
const float hfGain{CalcDecayCoeff(length, hfDecayTime) / mfGain};
MidGain = mfGain;
LFFilter.setParamsFromSlope(BiquadType::LowShelf, lf0norm, lfGain, 1.0f);
HFFilter.setParamsFromSlope(BiquadType::HighShelf, hf0norm, hfGain, 1.0f);
}
/* Update the early reflection line lengths and gain coefficients. */
void EarlyReflections::updateLines(const float density_mult, const float diffusion,
const float decayTime, const float frequency)
{
/* Calculate the all-pass feed-back/forward coefficient. */
VecAp.Coeff = diffusion*diffusion * InvSqrt2;
for(size_t i{0u};i < NUM_LINES;i++)
{
/* Calculate the delay length of each all-pass line. */
float length{EARLY_ALLPASS_LENGTHS[i] * density_mult};
VecAp.Offset[i] = float2uint(length * frequency);
/* Calculate the delay length of each delay line. */
length = EARLY_LINE_LENGTHS[i] * density_mult;
Offset[i] = float2uint(length * frequency);
/* Calculate the gain (coefficient) for each line. */
Coeff[i] = CalcDecayCoeff(length, decayTime);
}
}
/* Update the EAX modulation step and depth. Keep in mind that this kind of
* vibrato is additive and not multiplicative as one may expect. The downswing
* will sound stronger than the upswing.
*/
void Modulation::updateModulator(float modTime, float modDepth, float frequency)
{
/* Modulation is calculated in two parts.
*
* The modulation time effects the sinus rate, altering the speed of
* frequency changes. An index is incremented for each sample with an
* appropriate step size to generate an LFO, which will vary the feedback
* delay over time.
*/
Step = std::max(fastf2u(MOD_FRACONE / (frequency * modTime)), 1u);
/* The modulation depth effects the amount of frequency change over the
* range of the sinus. It needs to be scaled by the modulation time so that
* a given depth produces a consistent change in frequency over all ranges
* of time. Since the depth is applied to a sinus value, it needs to be
* halved once for the sinus range and again for the sinus swing in time
* (half of it is spent decreasing the frequency, half is spent increasing
* it).
*/
if(modTime >= DefaultModulationTime)
{
/* To cancel the effects of a long period modulation on the late
* reverberation, the amount of pitch should be varied (decreased)
* according to the modulation time. The natural form is varying
* inversely, in fact resulting in an invariant.
*/
Depth = MODULATION_DEPTH_COEFF / 4.0f * DefaultModulationTime * modDepth * frequency;
}
else
Depth = MODULATION_DEPTH_COEFF / 4.0f * modTime * modDepth * frequency;
}
/* Update the late reverb line lengths and T60 coefficients. */
void LateReverb::updateLines(const float density_mult, const float diffusion,
const float lfDecayTime, const float mfDecayTime, const float hfDecayTime,
const float lf0norm, const float hf0norm, const float frequency)
{
/* Scaling factor to convert the normalized reference frequencies from