-
Notifications
You must be signed in to change notification settings - Fork 2.2k
/
NoiseReduction.cpp
1770 lines (1509 loc) · 55.1 KB
/
NoiseReduction.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
/**********************************************************************
Audacity: A Digital Audio Editor
NoiseReduction.cpp
Dominic Mazzoni
detailed rewriting by
Paul Licameli
*******************************************************************//**
\class EffectNoiseReduction
\brief A two-pass effect to reduce background noise.
The first pass is done over just noise. For each windowed sample
of the sound, we take a FFT and then statistics are tabulated for
each frequency band.
During the noise reduction phase, we start by setting a gain control
for each frequency band such that if the sound has exceeded the
previously-determined threshold, the gain is set to 0 dB, otherwise
the gain is set lower (e.g. -18 dB), to suppress the noise.
Then time-smoothing is applied so that the gain for each frequency
band moves slowly, and then frequency-smoothing is applied so that a
single frequency is never suppressed or boosted in isolation.
Lookahead is employed; this effect is not designed for real-time
but if it were, there would be a significant delay.
The gain controls are applied to the complex FFT of the signal,
and then the inverse FFT is applied. A Hann window may be
applied (depending on the advanced window types setting), and then
the output signal is then pieced together using overlap/add.
*//****************************************************************//**
*/
#include "NoiseReduction.h"
#include "EffectOutputTracks.h"
#include "LoadEffects.h"
#include "EffectManager.h"
#include "EffectPreview.h"
#include "EffectUI.h"
#include "ShuttleGui.h"
#include "HelpSystem.h"
#include "FFT.h"
#include "Prefs.h"
#include "RealFFTf.h"
#include "../SpectrumTransformer.h"
#include "WaveTrack.h"
#include "AudacityMessageBox.h"
#include "../widgets/valnum.h"
#include <algorithm>
#include <vector>
#include <math.h>
#if defined(__WXMSW__) && !defined(__CYGWIN__)
#include <float.h>
#define finite(x) _finite(x)
#endif
#include <wx/button.h>
#include <wx/choice.h>
#include <wx/radiobut.h>
#include <wx/slider.h>
#include <wx/valtext.h>
#include <wx/textctrl.h>
// SPECTRAL_SELECTION not to affect this effect for now, as there might be no indication that it does.
// [Discussed and agreed for v2.1 by Steve, Paul, Bill].
#undef SPECTRAL_EDIT_NOISE_REDUCTION
typedef std::vector<float> FloatVector;
// Define both of these to make the radio button three-way
#define RESIDUE_CHOICE
//#define ISOLATE_CHOICE
// Define for Attack and release controls.
// #define ATTACK_AND_RELEASE
// Define to expose other advanced, experimental dialog controls
//#define ADVANCED_SETTINGS
// Define to make the old statistical methods an available choice
//#define OLD_METHOD_AVAILABLE
namespace {
enum DiscriminationMethod : size_t {
DM_MEDIAN,
DM_SECOND_GREATEST,
DM_OLD_METHOD,
DM_N_METHODS,
DM_DEFAULT_METHOD = DM_SECOND_GREATEST,
};
const struct DiscriminationMethodInfo {
const TranslatableString name;
} discriminationMethodInfo[DM_N_METHODS] = {
// Experimental only, don't need translations
{ XO("Median") },
{ XO("Second greatest") },
{ XO("Old") },
};
// magic number used only in the old statistics
// and the old discrimination
const float minSignalTime = 0.05f;
enum WindowTypes : unsigned {
WT_RECTANGULAR_HANN = 0, // 2.0.6 behavior, requires 1/2 step
WT_HANN_RECTANGULAR, // requires 1/2 step
WT_HANN_HANN, // requires 1/4 step
WT_BLACKMAN_HANN, // requires 1/4 step
WT_HAMMING_RECTANGULAR, // requires 1/2 step
WT_HAMMING_HANN, // requires 1/4 step
// WT_HAMMING_INV_HAMMING, // requires 1/2 step
WT_N_WINDOW_TYPES,
WT_DEFAULT_WINDOW_TYPES = WT_HANN_HANN
};
const struct WindowTypesInfo {
const TranslatableString name;
unsigned minSteps;
} windowTypesInfo [WT_N_WINDOW_TYPES] = {
// Experimental only, don't need translations
{ Verbatim("none, Hann (2.0.6 behavior)"), 2 },
/* i18n-hint: Hann is a proper name */
{ Verbatim("Hann, none"), 2 },
/* i18n-hint: Hann is a proper name */
{ Verbatim("Hann, Hann (default)"), 4 },
/* i18n-hint: Hann and Blackman are proper names */
{ Verbatim("Blackman, Hann"), 4 },
/* i18n-hint: Hamming is a proper name */
{ Verbatim("Hamming, none"), 2 },
/* i18n-hint: Hamming and Hann area proper names */
{ Verbatim("Hamming, Hann"), 4 },
/* i18n-hint: Hamming is a proper name */
// { XO("Hamming, Reciprocal Hamming"), 2, }, // output window is special
};
enum {
DEFAULT_WINDOW_SIZE_CHOICE = 8, // corresponds to 2048
DEFAULT_STEPS_PER_WINDOW_CHOICE = 1 // corresponds to 4, minimum for WT_HANN_HANN
};
enum NoiseReductionChoice {
NRC_REDUCE_NOISE,
NRC_ISOLATE_NOISE,
NRC_LEAVE_RESIDUE,
};
} // namespace
//----------------------------------------------------------------------------
// EffectNoiseReduction::Statistics
//----------------------------------------------------------------------------
class EffectNoiseReduction::Statistics
{
public:
Statistics(size_t spectrumSize, double rate, int windowTypes)
: mRate{ rate }
, mWindowSize{ (spectrumSize - 1) * 2 }
, mWindowTypes{ windowTypes }
, mTotalWindows{ 0 }
, mTrackWindows{ 0 }
, mSums( spectrumSize )
, mMeans (spectrumSize )
#ifdef OLD_METHOD_AVAILABLE
, mNoiseThreshold( spectrumSize )
#endif
{}
// Noise profile statistics follow
double mRate; // Rate of profile track(s) -- processed tracks must match
size_t mWindowSize;
int mWindowTypes;
unsigned mTotalWindows;
unsigned mTrackWindows;
FloatVector mSums;
FloatVector mMeans;
#ifdef OLD_METHOD_AVAILABLE
// Old statistics:
FloatVector mNoiseThreshold;
#endif
};
//----------------------------------------------------------------------------
// EffectNoiseReduction::Settings
//----------------------------------------------------------------------------
// This object is the memory of the effect between uses
// (other than noise profile statistics)
class EffectNoiseReduction::Settings
{
public:
Settings();
~Settings() {}
int PromptUser(EffectNoiseReduction *effect, EffectSettingsAccess &access,
wxWindow &parent, bool bHasProfile, bool bAllowTwiddleSettings);
bool PrefsIO(bool read);
bool Validate(EffectNoiseReduction *effect) const;
size_t WindowSize() const { return 1u << (3 + mWindowSizeChoice); }
unsigned StepsPerWindow() const { return 1u << (1 + mStepsPerWindowChoice); }
size_t SpectrumSize() const { return 1 + WindowSize() / 2; }
size_t StepSize() const { return WindowSize() / StepsPerWindow(); }
bool mDoProfile;
// Stored in preferences:
// Basic:
double mNewSensitivity; // - log10 of a probability... yeah.
double mFreqSmoothingBands; // really an integer
double mNoiseGain; // in dB, positive
double mAttackTime; // in secs
double mReleaseTime; // in secs
// Advanced:
double mOldSensitivity; // in dB, plus or minus
// Basic:
int mNoiseReductionChoice;
// Advanced:
int mWindowTypes;
int mWindowSizeChoice;
int mStepsPerWindowChoice;
int mMethod;
};
EffectNoiseReduction::Settings::Settings()
: mDoProfile{ true }
{
PrefsIO(true);
}
struct MyTransformer : TrackSpectrumTransformer {
MyTransformer(EffectNoiseReduction::Worker &worker,
WaveChannel *pOutputTrack,
bool needsOutput, eWindowFunctions inWindowType,
eWindowFunctions outWindowType, size_t windowSize,
unsigned stepsPerWindow, bool leadingPadding, bool trailingPadding
) : TrackSpectrumTransformer{ pOutputTrack,
needsOutput, inWindowType, outWindowType,
windowSize, stepsPerWindow, leadingPadding, trailingPadding
}
, mWorker{ worker }
{
}
struct MyWindow : public Window
{
explicit MyWindow(size_t windowSize)
: Window{ windowSize }
, mSpectrums(windowSize / 2 + 1)
, mGains(windowSize / 2 + 1)
{}
~MyWindow() override;
FloatVector mSpectrums;
FloatVector mGains;
};
MyWindow &NthWindow(int nn) { return static_cast<MyWindow&>(Nth(nn)); }
std::unique_ptr<Window> NewWindow(size_t windowSize) override;
bool DoStart() override;
bool DoFinish() override;
EffectNoiseReduction::Worker &mWorker;
};
//----------------------------------------------------------------------------
// EffectNoiseReduction::Worker
//----------------------------------------------------------------------------
// This object holds information needed only during effect calculation
class EffectNoiseReduction::Worker final
{
public:
typedef EffectNoiseReduction::Settings Settings;
typedef EffectNoiseReduction::Statistics Statistics;
Worker(EffectNoiseReduction &effect, const Settings &settings,
Statistics &statistics
#ifdef SPECTRAL_EDIT_NOISE_REDUCTION
, double f0, double f1
#endif
);
~Worker();
bool Process(eWindowFunctions inWindowType, eWindowFunctions outWindowType,
TrackList &tracks, double mT0, double mT1);
static bool Processor(SpectrumTransformer &transformer);
void ApplyFreqSmoothing(FloatVector &gains);
void GatherStatistics(MyTransformer &transformer);
inline bool Classify(
MyTransformer &transformer, unsigned nWindows, int band);
void ReduceNoise(MyTransformer &transformer);
void FinishTrackStatistics();
const bool mDoProfile;
EffectNoiseReduction &mEffect;
const Settings &mSettings;
Statistics &mStatistics;
FloatVector mFreqSmoothingScratch;
const size_t mFreqSmoothingBins;
// When spectral selection limits the affected band:
size_t mBinLow; // inclusive lower bound
size_t mBinHigh; // exclusive upper bound
const int mNoiseReductionChoice;
const int mMethod;
const double mNewSensitivity;
float mOneBlockAttack;
float mOneBlockRelease;
float mNoiseAttenFactor;
float mOldSensitivityFactor;
unsigned mNWindowsToExamine;
unsigned mCenter;
unsigned mHistoryLen;
// Following are for progress indicator only:
unsigned mProgressTrackCount = 0;
sampleCount mLen = 0;
sampleCount mProgressWindowCount = 0;
};
/****************************************************************//**
\class EffectNoiseReduction::Dialog
\brief Dialog used with EffectNoiseReduction
**//*****************************************************************/
//----------------------------------------------------------------------------
// EffectNoiseReduction::Dialog
//----------------------------------------------------------------------------
class EffectNoiseReduction::Dialog final : public EffectDialog
{
public:
// constructors and destructors
Dialog(EffectNoiseReduction *effect, EffectSettingsAccess &access,
Settings *settings,
wxWindow *parent, bool bHasProfile,
bool bAllowTwiddleSettings);
void PopulateOrExchange(ShuttleGui & S) override;
bool TransferDataToWindow() override;
bool TransferDataFromWindow() override;
const Settings &GetTempSettings() const
{ return mTempSettings; }
private:
void DisableControlsIfIsolating();
#ifdef ADVANCED_SETTINGS
void EnableDisableSensitivityControls();
#endif
// handlers
void OnGetProfile( wxCommandEvent &event );
void OnNoiseReductionChoice( wxCommandEvent &event );
#ifdef ADVANCED_SETTINGS
void OnMethodChoice(wxCommandEvent &);
#endif
void OnPreview(wxCommandEvent &event) override;
void OnReduceNoise( wxCommandEvent &event );
void OnCancel( wxCommandEvent &event );
void OnHelp( wxCommandEvent &event );
void OnText(wxCommandEvent &event);
void OnSlider(wxCommandEvent &event);
// data members
EffectNoiseReduction *m_pEffect;
//! This dialog is modal, so mAccess will live long enough for it
EffectSettingsAccess &mAccess;
EffectNoiseReduction::Settings *m_pSettings;
EffectNoiseReduction::Settings mTempSettings;
bool mbHasProfile;
bool mbAllowTwiddleSettings;
wxRadioButton *mKeepSignal;
#ifdef ISOLATE_CHOICE
wxRadioButton *mKeepNoise;
#endif
#ifdef RESIDUE_CHOICE
wxRadioButton *mResidue;
#endif
private:
DECLARE_EVENT_TABLE()
};
const ComponentInterfaceSymbol EffectNoiseReduction::Symbol
{ XO("Noise Reduction") };
namespace{ BuiltinEffectsModule::Registration< EffectNoiseReduction > reg; }
EffectNoiseReduction::EffectNoiseReduction()
: mSettings(std::make_unique<EffectNoiseReduction::Settings>())
{
}
EffectNoiseReduction::~EffectNoiseReduction()
{
}
// ComponentInterface implementation
ComponentInterfaceSymbol EffectNoiseReduction::GetSymbol() const
{
return Symbol;
}
TranslatableString EffectNoiseReduction::GetDescription() const
{
return XO("Removes background noise such as fans, tape noise, or hums");
}
// EffectDefinitionInterface implementation
EffectType EffectNoiseReduction::GetType() const
{
return EffectTypeProcess;
}
//! An override still here for historical reasons, ignoring the factory
//! and the access
/*! We would like to make this effect behave more like others, but it does have
its unusual two-pass nature. First choose and analyze an example of noise,
then apply noise reduction to another selection. That is difficult to fit into
the framework for managing settings of other effects. */
int EffectNoiseReduction::ShowHostInterface(EffectBase &,
wxWindow &parent, const EffectDialogFactory &,
std::shared_ptr<EffectInstance> &pInstance, EffectSettingsAccess &access,
bool forceModal)
{
// Assign the out parameter
pInstance = MakeInstance();
// to do: use forceModal correctly
// Doesn't use the factory but substitutes its own dialog
// We may want to twiddle the levels if we are setting
// from a macro editing dialog
return mSettings->PromptUser(this, access, parent,
bool(mStatistics), IsBatchProcessing());
}
int EffectNoiseReduction::Settings::PromptUser(EffectNoiseReduction *effect,
EffectSettingsAccess &access, wxWindow &parent,
bool bHasProfile, bool bAllowTwiddleSettings)
{
EffectNoiseReduction::Dialog dlog(effect, access,
this, &parent, bHasProfile, bAllowTwiddleSettings);
dlog.CentreOnParent();
dlog.ShowModal();
const auto returnCode = dlog.GetReturnCode();
if (!returnCode)
return 0;
*this = dlog.GetTempSettings();
mDoProfile = (returnCode == 1);
if (!PrefsIO(false))
return 0;
return returnCode;
}
namespace {
template <typename StructureType, typename FieldType>
struct PrefsTableEntry {
typedef FieldType (StructureType::*MemberPointer);
MemberPointer field;
const wxChar *name;
FieldType defaultValue;
};
template <typename StructureType, typename FieldType>
void readPrefs(
StructureType *structure, const wxString &prefix,
const PrefsTableEntry<StructureType, FieldType> *fields, size_t numFields)
{
for (size_t ii = 0; ii < numFields; ++ii) {
const PrefsTableEntry<StructureType, FieldType> &entry = fields[ii];
gPrefs->Read(prefix + entry.name, &(structure->*(entry.field)),
entry.defaultValue);
}
}
template <typename StructureType, typename FieldType>
void writePrefs(
const StructureType *structure, const wxString &prefix,
const PrefsTableEntry<StructureType, FieldType> *fields, size_t numFields)
{
for (size_t ii = 0; ii < numFields; ++ii) {
const PrefsTableEntry<StructureType, FieldType> &entry = fields[ii];
gPrefs->Write(prefix + entry.name, structure->*(entry.field));
}
}
}
bool EffectNoiseReduction::Settings::PrefsIO(bool read)
{
static const double DEFAULT_OLD_SENSITIVITY = 0.0;
static const PrefsTableEntry<Settings, double> doubleTable[] = {
{ &Settings::mNewSensitivity, wxT("Sensitivity"), 6.0 },
{ &Settings::mNoiseGain, wxT("Gain"), 6.0 },
{ &Settings::mAttackTime, wxT("AttackTime"), 0.02 },
{ &Settings::mReleaseTime, wxT("ReleaseTime"), 0.10 },
{ &Settings::mFreqSmoothingBands, wxT("FreqSmoothing"), 6.0 },
// Advanced settings
{ &Settings::mOldSensitivity, wxT("OldSensitivity"), DEFAULT_OLD_SENSITIVITY },
};
static auto doubleTableSize = sizeof(doubleTable) / sizeof(doubleTable[0]);
static const PrefsTableEntry<Settings, int> intTable[] = {
{ &Settings::mNoiseReductionChoice, wxT("ReductionChoice"), NRC_REDUCE_NOISE },
// Advanced settings
{ &Settings::mWindowTypes, wxT("WindowTypes"), WT_DEFAULT_WINDOW_TYPES },
{ &Settings::mWindowSizeChoice, wxT("WindowSize"), DEFAULT_WINDOW_SIZE_CHOICE },
{ &Settings::mStepsPerWindowChoice, wxT("StepsPerWindow"), DEFAULT_STEPS_PER_WINDOW_CHOICE },
{ &Settings::mMethod, wxT("Method"), DM_DEFAULT_METHOD },
};
static auto intTableSize = sizeof(intTable) / sizeof(intTable[0]);
static const wxString prefix(wxT("/Effects/NoiseReduction/"));
if (read) {
readPrefs(this, prefix, doubleTable, doubleTableSize);
readPrefs(this, prefix, intTable, intTableSize);
// Ignore preferences for unavailable options.
#if !(defined(RESIDUE_CHOICE) || defined (ISOLATE_CHOICE))
mNoiseReductionChoice == NRC_REDUCE_NOISE;
#elif !(defined(RESIDUE_CHOICE))
if (mNoiseReductionChoice == NRC_LEAVE_RESIDUE)
mNoiseReductionChoice = NRC_ISOLATE_NOISE;
#elif !(defined(ISOLATE_CHOICE))
if (mNoiseReductionChoice == NRC_ISOLATE_NOISE)
mNoiseReductionChoice = NRC_LEAVE_RESIDUE;
#endif
#ifndef ADVANCED_SETTINGS
// Initialize all hidden advanced settings to defaults.
mWindowTypes = WT_DEFAULT_WINDOW_TYPES;
mWindowSizeChoice = DEFAULT_WINDOW_SIZE_CHOICE;
mStepsPerWindowChoice = DEFAULT_STEPS_PER_WINDOW_CHOICE;
mMethod = DM_DEFAULT_METHOD;
mOldSensitivity = DEFAULT_OLD_SENSITIVITY;
#endif
#ifndef OLD_METHOD_AVAILABLE
if (mMethod == DM_OLD_METHOD)
mMethod = DM_DEFAULT_METHOD;
#endif
return true;
}
else {
writePrefs(this, prefix, doubleTable, doubleTableSize);
writePrefs(this, prefix, intTable, intTableSize);
return gPrefs->Flush();
}
}
bool EffectNoiseReduction::Settings::Validate(EffectNoiseReduction *effect) const
{
if (StepsPerWindow() < windowTypesInfo[mWindowTypes].minSteps) {
EffectUIServices::DoMessageBox(*effect,
XO("Steps per block are too few for the window types.") );
return false;
}
if (StepsPerWindow() > WindowSize()) {
EffectUIServices::DoMessageBox(*effect,
XO("Steps per block cannot exceed the window size.") );
return false;
}
if (mMethod == DM_MEDIAN && StepsPerWindow() > 4) {
EffectUIServices::DoMessageBox(*effect,
XO(
"Median method is not implemented for more than four steps per window.") );
return false;
}
return true;
}
auto MyTransformer::NewWindow(size_t windowSize)
-> std::unique_ptr<Window>
{
return std::make_unique<MyWindow>(windowSize);
}
MyTransformer::MyWindow::~MyWindow()
{
}
bool EffectNoiseReduction::Process(EffectInstance &, EffectSettings &)
{
// This same code will either reduce noise or profile it
EffectOutputTracks outputs { *mTracks, GetType(), { { mT0, mT1 } } };
auto track = *(outputs.Get().Selected<const WaveTrack>()).begin();
if (!track)
return false;
const auto stepsPerWindow = mSettings->StepsPerWindow();
const auto stepSize = mSettings->WindowSize() / stepsPerWindow;
// Initialize statistics if gathering them, or check for mismatched (advanced)
// settings if reducing noise.
if (mSettings->mDoProfile) {
const auto spectrumSize = mSettings->SpectrumSize();
mStatistics = std::make_unique<Statistics>
(spectrumSize, track->GetRate(), mSettings->mWindowTypes);
}
else if (mStatistics->mWindowSize != mSettings->WindowSize()) {
// possible only with advanced settings
EffectUIServices::DoMessageBox(*this,
XO("You must specify the same window size for steps 1 and 2.") );
return false;
}
else if (mStatistics->mWindowTypes != mSettings->mWindowTypes) {
// A warning only
EffectUIServices::DoMessageBox(*this,
XO("Warning: window types are not the same as for profiling.") );
}
eWindowFunctions inWindowType, outWindowType;
switch (mSettings->mWindowTypes) {
case WT_RECTANGULAR_HANN:
inWindowType = eWinFuncRectangular;
outWindowType = eWinFuncHann;
break;
case WT_HANN_RECTANGULAR:
inWindowType = eWinFuncHann;
outWindowType = eWinFuncRectangular;
break;
case WT_BLACKMAN_HANN:
inWindowType = eWinFuncBlackman;
outWindowType = eWinFuncHann;
break;
case WT_HAMMING_RECTANGULAR:
inWindowType = eWinFuncHamming;
outWindowType = eWinFuncRectangular;
break;
case WT_HAMMING_HANN:
inWindowType = eWinFuncHamming;
outWindowType = eWinFuncHann;
break;
default:
wxASSERT(false);
[[fallthrough]] ;
case WT_HANN_HANN:
inWindowType = outWindowType = eWinFuncHann;
break;
}
Worker worker{ *this, *mSettings, *mStatistics
#ifdef SPECTRAL_EDIT_NOISE_REDUCTION
, mF0, mF1
#endif
};
bool bGoodResult = worker.Process(inWindowType, outWindowType,
outputs.Get(), mT0, mT1);
const auto wasProfile = mSettings->mDoProfile;
if (mSettings->mDoProfile) {
if (bGoodResult)
mSettings->mDoProfile = false; // So that "repeat last effect" will reduce noise
else
mStatistics.reset(); // So that profiling must be done again before noise reduction
}
if (bGoodResult && !wasProfile)
outputs.Commit();
return bGoodResult;
}
EffectNoiseReduction::Worker::~Worker()
{
}
bool EffectNoiseReduction::Worker::Process(
eWindowFunctions inWindowType, eWindowFunctions outWindowType,
TrackList &tracks, double inT0, double inT1)
{
mProgressTrackCount = 0;
for (auto track : tracks.Selected<WaveTrack>()) {
mProgressWindowCount = 0;
if (track->GetRate() != mStatistics.mRate) {
if (mDoProfile)
EffectUIServices::DoMessageBox(mEffect,
XO("All noise profile data must have the same sample rate.") );
else
EffectUIServices::DoMessageBox(mEffect,
XO(
"The sample rate of the noise profile must match that of the sound to be processed.") );
return false;
}
double trackStart = track->GetStartTime();
double trackEnd = track->GetEndTime();
double t0 = std::max(trackStart, inT0);
double t1 = std::min(trackEnd, inT1);
if (t1 > t0) {
auto start = track->TimeToLongSamples(t0);
auto end = track->TimeToLongSamples(t1);
const auto len = end - start;
mLen = len;
const auto extra =
(mSettings.StepsPerWindow() - 1) * mSettings.SpectrumSize();
// Adjust denominator for presence or absence of padding,
// which makes the number of windows visited either more or less
// than the number of window steps in the data.
if (mDoProfile)
mLen -= extra;
else
mLen += extra;
auto t0 = track->LongSamplesToTime(start);
auto tLen = track->LongSamplesToTime(len);
std::optional<WaveTrack::Holder> ppTempTrack;
std::optional<ChannelGroup::ChannelIterator<WaveChannel>> pIter;
WaveTrack *pFirstTrack{};
if (!mSettings.mDoProfile) {
ppTempTrack.emplace(track->EmptyCopy());
pFirstTrack = ppTempTrack->get();
pIter.emplace(pFirstTrack->Channels().begin());
}
for (const auto pChannel : track->Channels()) {
auto pOutputTrack = pIter ? *(*pIter)++ : nullptr;
MyTransformer transformer{ *this, pOutputTrack.get(),
!mSettings.mDoProfile, inWindowType, outWindowType,
mSettings.WindowSize(), mSettings.StepsPerWindow(),
!mSettings.mDoProfile, !mSettings.mDoProfile
};
if (!transformer
.Process(Processor, *pChannel, mHistoryLen, start, len))
return false;
++mProgressTrackCount;
}
if (ppTempTrack) {
TrackSpectrumTransformer::PostProcess(*pFirstTrack, len);
constexpr auto preserveSplits = true;
constexpr auto merge = true;
track->ClearAndPaste(
t0, t0 + tLen, **ppTempTrack, preserveSplits, merge);
}
}
}
if (mDoProfile) {
if (mStatistics.mTotalWindows == 0) {
EffectUIServices::DoMessageBox(mEffect,
XO("Selected noise profile is too short."));
return false;
}
}
return true;
}
void EffectNoiseReduction::Worker::ApplyFreqSmoothing(FloatVector &gains)
{
// Given an array of gain mutipliers, average them
// GEOMETRICALLY. Don't multiply and take nth root --
// that may quickly cause underflows. Instead, average the logs.
if (mFreqSmoothingBins == 0)
return;
const auto spectrumSize = mSettings.SpectrumSize();
{
auto pScratch = mFreqSmoothingScratch.data();
std::fill(pScratch, pScratch + spectrumSize, 0.0f);
}
for (size_t ii = 0; ii < spectrumSize; ++ii)
gains[ii] = log(gains[ii]);
// ii must be signed
for (int ii = 0; ii < (int)spectrumSize; ++ii) {
const int j0 = std::max(0, ii - (int)mFreqSmoothingBins);
const int j1 = std::min(spectrumSize - 1, ii + mFreqSmoothingBins);
for(int jj = j0; jj <= j1; ++jj) {
mFreqSmoothingScratch[ii] += gains[jj];
}
mFreqSmoothingScratch[ii] /= (j1 - j0 + 1);
}
for (size_t ii = 0; ii < spectrumSize; ++ii)
gains[ii] = exp(mFreqSmoothingScratch[ii]);
}
EffectNoiseReduction::Worker::Worker(EffectNoiseReduction &effect,
const Settings &settings, Statistics &statistics
#ifdef SPECTRAL_EDIT_NOISE_REDUCTION
, double f0, double f1
#endif
)
: mDoProfile{ settings.mDoProfile }
, mEffect{ effect }
, mSettings{ settings }
, mStatistics{ statistics }
, mFreqSmoothingScratch(mSettings.SpectrumSize())
, mFreqSmoothingBins{ size_t(std::max(0.0, settings.mFreqSmoothingBands)) }
, mBinLow{ 0 }
, mBinHigh{ mSettings.SpectrumSize() }
, mNoiseReductionChoice{ settings.mNoiseReductionChoice }
, mMethod{ settings.mMethod }
// Sensitivity setting is a base 10 log, turn it into a natural log
, mNewSensitivity{ settings.mNewSensitivity * log(10.0) }
{
const auto sampleRate = mStatistics.mRate;
#ifdef SPECTRAL_EDIT_NOISE_REDUCTION
{
// mBinLow is inclusive, mBinHigh is exclusive, of
// the range of frequencies to affect. Include any
// bin that partly overlaps the selected range of frequencies.
const double bin = sampleRate / mWindowSize;
if (f0 >= 0.0 )
mBinLow = floor(f0 / bin);
if (f1 >= 0.0)
mBinHigh = ceil(f1 / bin);
}
#endif
const double noiseGain = -settings.mNoiseGain;
const unsigned nAttackBlocks =
1 + (int)(settings.mAttackTime * sampleRate / mSettings.StepSize());
const unsigned nReleaseBlocks =
1 + (int)(settings.mReleaseTime * sampleRate / mSettings.StepSize());
// Applies to amplitudes, divide by 20:
mNoiseAttenFactor = DB_TO_LINEAR(noiseGain);
// Apply to gain factors which apply to amplitudes, divide by 20:
mOneBlockAttack = DB_TO_LINEAR(noiseGain / nAttackBlocks);
mOneBlockRelease = DB_TO_LINEAR(noiseGain / nReleaseBlocks);
// Applies to power, divide by 10:
mOldSensitivityFactor = pow(10.0, settings.mOldSensitivity / 10.0);
mNWindowsToExamine = (mMethod == DM_OLD_METHOD)
? std::max(2, (int)(minSignalTime * sampleRate / mSettings.StepSize()))
: 1 + mSettings.StepsPerWindow();
mCenter = mNWindowsToExamine / 2;
wxASSERT(mCenter >= 1); // release depends on this assumption
if (mDoProfile)
#ifdef OLD_METHOD_AVAILABLE
mHistoryLen = mNWindowsToExamine;
#else
mHistoryLen = 1;
#endif
else {
// Allow long enough queue for sufficient inspection of the middle
// and for attack processing
// See ReduceNoise()
mHistoryLen = std::max(mNWindowsToExamine, mCenter + nAttackBlocks);
}
}
bool MyTransformer::DoStart()
{
for (size_t ii = 0, nn = TotalQueueSize(); ii < nn; ++ii) {
MyWindow &record = NthWindow(ii);
std::fill(record.mSpectrums.begin(), record.mSpectrums.end(), 0.0);
std::fill(record.mGains.begin(), record.mGains.end(),
mWorker.mNoiseAttenFactor);
}
return TrackSpectrumTransformer::DoStart();
}
bool EffectNoiseReduction::Worker::Processor(SpectrumTransformer &trans)
{
auto &transformer = static_cast<MyTransformer &>(trans);
auto &worker = transformer.mWorker;
// Compute power spectrum in the newest window
{
auto &record = transformer.NthWindow(0);
float *pSpectrum = &record.mSpectrums[0];
const double dc = record.mRealFFTs[0];
*pSpectrum++ = dc * dc;
float *pReal = &record.mRealFFTs[1], *pImag = &record.mImagFFTs[1];
for (size_t nn = worker.mSettings.SpectrumSize() - 2; nn--;) {
const double re = *pReal++, im = *pImag++;
*pSpectrum++ = re * re + im * im;
}
const double nyquist = record.mImagFFTs[0];
*pSpectrum = nyquist * nyquist;
}
if (worker.mDoProfile)
worker.GatherStatistics(transformer);
else
worker.ReduceNoise(transformer);
// Update the Progress meter, let user cancel
return !worker.mEffect.TrackProgress(worker.mProgressTrackCount,
std::min(1.0,
((++worker.mProgressWindowCount).as_double() *
worker.mSettings.StepSize()) / worker.mLen.as_double()));
}
void EffectNoiseReduction::Worker::FinishTrackStatistics()
{
const auto windows = mStatistics.mTrackWindows;
// Combine averages in case of multiple profile tracks.
if (windows) {
const auto multiplier = mStatistics.mTotalWindows;
const auto denom = windows + multiplier;
for (size_t ii = 0, nn = mStatistics.mMeans.size(); ii < nn; ++ii) {
auto &mean = mStatistics.mMeans[ii];
auto &sum = mStatistics.mSums[ii];
mean = (mean * multiplier + sum) / denom;
// Reset for next track
sum = 0;
}
// Reset for next track
mStatistics.mTrackWindows = 0;
mStatistics.mTotalWindows = denom;
}
}
void EffectNoiseReduction::Worker::GatherStatistics(MyTransformer &transformer)
{
++mStatistics.mTrackWindows;
{
// NEW statistics
auto pPower = transformer.NthWindow(0).mSpectrums.data();
auto pSum = mStatistics.mSums.data();
for (size_t jj = 0; jj < mSettings.SpectrumSize(); ++jj) {
*pSum++ += *pPower++;
}
}
#ifdef OLD_METHOD_AVAILABLE
// The noise threshold for each frequency is the maximum
// level achieved at that frequency for a minimum of
// mMinSignalBlocks blocks in a row - the max of a min.
auto finish = mHistoryLen;
{
// old statistics
auto pPower = NthWindow(0).mSpectrums.data();
auto pThreshold = mStatistics.mNoiseThreshold.data();
for (size_t jj = 0; jj < mSpectrumSize; ++jj) {
float min = *pPower++;
for (unsigned ii = 1; ii < finish; ++ii)
min = std::min(min, NthWindow(ii).mSpectrums[jj]);
*pThreshold = std::max(*pThreshold, min);
++pThreshold;
}