File: SpectrogramSettings.cpp

package info (click to toggle)
audacity 3.7.7%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 134,800 kB
  • sloc: cpp: 366,277; ansic: 198,323; lisp: 7,761; sh: 3,414; python: 1,501; xml: 1,385; perl: 854; makefile: 125
file content (858 lines) | stat: -rw-r--r-- 24,621 bytes parent folder | download
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
/**********************************************************************

Audacity: A Digital Audio Editor

SpectrogramSettings.cpp

Paul Licameli

*******************************************************************//**

\class SpectrogramSettings
\brief Spectrogram settings, either for one track or as defaults.

*//*******************************************************************/


#include "SpectrogramSettings.h"

#include "NumberScale.h"

#include <algorithm>

#include "FFT.h"
#include "Prefs.h"
#include "WaveTrack.h"

#include <cmath>

#include "BasicUI.h"

IntSetting SpectrumMaxFreq{
   L"/Spectrum/MaxFreq", 20000 };

namespace {
// Other settings not yet used outside of this file

// To do: migrate these to ChoiceSetting preferences, which will store an
// Identifier instead of a number in the preference file.
IntSetting SpectrumAlgorithm{
   L"/Spectrum/Algorithm", 0 }; // Default to Frequencies
IntSetting SpectrumScale{
   L"/Spectrum/ScaleType", 2 }; // Default to Mel
IntSetting SpectrumWindowFunction{
   L"/Spectrum/WindowType", eWinFuncHann };

BoolSetting SpectrumEnableSelection{
   L"/Spectrum/EnableSpectralSelection", true };
IntSetting SpectrumFFTSize{
   L"/Spectrum/FFTSize", 2048 };
IntSetting SpectrumFrequencyGain{
   L"/Spectrum/FrequencyGain", 0 };
IntSetting SpectrumGain{
   L"/Spectrum/Gain", 20 };
BoolSetting SpectrumGrayscale{
   L"/Spectrum/Grayscale", false };
IntSetting SpectrumMinFreq{
   L"/Spectrum/MinFreq", 0 };
IntSetting SpectrumRange{
   L"/Spectrum/Range", 80 };
IntSetting SpectrumZeroPaddingFactor{
   L"/Spectrum/ZeroPaddingFactor", 2 };

#ifdef EXPERIMENTAL_FIND_NOTES
BoolSetting SpectrumFindNotes{
   L"/Spectrum/FFTFindNotes", false };
DoubleSetting SpectrumFindNotesMinA{
   L"/Spectrum/FindNotesMinA", -30.0 };
IntSetting SpectrumFindNotesN{
   L"/Spectrum/FindNotesN", 5 };
BoolSetting SpectrumFindNotesQuantize{
   L"/Spectrum/FindNotesQuantize", false };
#endif //EXPERIMENTAL_FIND_NOTES

#ifdef EXPERIMENTAL_FFT_Y_GRID
BoolSetting SpectrumYGrid{
   L"/Spectrum/FFTYGrid", false};
#endif
}

SpectrogramSettings::Globals::Globals()
{
   LoadPrefs();
}

void SpectrogramSettings::Globals::SavePrefs()
{
#ifdef SPECTRAL_SELECTION_GLOBAL_SWITCH
   SpectrumEnableSelection.Write(spectralSelection);
#endif
}

void SpectrogramSettings::Globals::LoadPrefs()
{
#ifdef SPECTRAL_SELECTION_GLOBAL_SWITCH
   spectralSelection = SpectrumEnableSelection.Read();
#endif
}

SpectrogramSettings::Globals
&SpectrogramSettings::Globals::Get()
{
   static Globals instance;
   return instance;
}

static const ChannelGroup::Attachments::RegisteredFactory
key1{ [](auto &) { return nullptr; } };

SpectrogramSettings &SpectrogramSettings::Get(const WaveTrack &track)
{
   auto &mutTrack = const_cast<WaveTrack&>(track);
   auto pSettings = mutTrack.Attachments::Find<SpectrogramSettings>(key1);
   if (pSettings)
      return *pSettings;
   else
      return SpectrogramSettings::defaults();
}

SpectrogramSettings &SpectrogramSettings::Get(const WaveChannel &channel)
{
   return Get(channel.GetTrack());
}

SpectrogramSettings &SpectrogramSettings::Own(WaveChannel &wc)
{
   auto &track = wc.GetTrack();
   auto pSettings = track.Attachments::Find<SpectrogramSettings>(key1);
   if (!pSettings) {
      auto uSettings = std::make_unique<SpectrogramSettings>();
      pSettings = uSettings.get();
      track.Attachments::Assign(key1, std::move(uSettings));
   }
   return *pSettings;
}

void SpectrogramSettings::Reset(WaveChannel &wc)
{
   wc.GetTrack().Attachments::Assign(key1, nullptr);
}

SpectrogramSettings::SpectrogramSettings()
{
   LoadPrefs();
}

SpectrogramSettings::SpectrogramSettings(const SpectrogramSettings &other)
   : minFreq(other.minFreq)
   , maxFreq(other.maxFreq)
   , range(other.range)
   , gain(other.gain)
   , frequencyGain(other.frequencyGain)
   , windowType(other.windowType)
   , windowSize(other.windowSize)
   , zeroPaddingFactor(other.zeroPaddingFactor)
   , colorScheme(other.colorScheme)
   , scaleType(other.scaleType)
#ifndef SPECTRAL_SELECTION_GLOBAL_SWITCH
   , spectralSelection(other.spectralSelection)
#endif
   , algorithm(other.algorithm)
#ifdef EXPERIMENTAL_FFT_Y_GRID
   , fftYGrid(other.fftYGrid)
#endif
#ifdef EXPERIMENTAL_FIND_NOTES
   , fftFindNotes(other.fftFindNotes)
   , findNotesMinA(other.findNotesMinA)
   , numberOfMaxima(other.numberOfMaxima)
   , findNotesQuantize(other.findNotesQuantize)
#endif

   // Do not copy these!
   , hFFT{}
   , window{}
   , waveletsRe{}
   , waveletsIm{}
   , waveletSizes{}
   , waveletMaxLength(0)
   , tWindow{}
   , dWindow{}
{
}

SpectrogramSettings &SpectrogramSettings::operator= (const SpectrogramSettings &other)
{
   if (this != &other) {
      minFreq = other.minFreq;
      maxFreq = other.maxFreq;
      range = other.range;
      gain = other.gain;
      frequencyGain = other.frequencyGain;
      windowType = other.windowType;
      windowSize = other.windowSize;
      zeroPaddingFactor = other.zeroPaddingFactor;
      colorScheme = other.colorScheme;
      scaleType = other.scaleType;
#ifndef SPECTRAL_SELECTION_GLOBAL_SWITCH
      spectralSelection = other.spectralSelection;
#endif
      algorithm = other.algorithm;
#ifdef EXPERIMENTAL_FFT_Y_GRID
      fftYGrid = other.fftYGrid;
#endif
#ifdef EXPERIMENTAL_FIND_NOTES
      fftFindNotes = other.fftFindNotes;
      findNotesMinA = other.findNotesMinA;
      numberOfMaxima = other.numberOfMaxima;
      findNotesQuantize = other.findNotesQuantize;
#endif

      // Invalidate the caches
      DestroyWindows();
   }
   return *this;
}

SpectrogramSettings& SpectrogramSettings::defaults()
{
   static SpectrogramSettings instance;
   return instance;
}

//static
const EnumValueSymbols &SpectrogramSettings::GetScaleNames()
{
   static const EnumValueSymbols result{
      // Keep in correspondence with enum SpectrogramSettings::ScaleType:
      XO("Linear") ,
      XO("Logarithmic") ,
      /* i18n-hint: The name of a frequency scale in psychoacoustics */
      XO("Mel") ,
      /* i18n-hint: The name of a frequency scale in psychoacoustics, named for Heinrich Barkhausen */
      XO("Bark") ,
      /* i18n-hint: The name of a frequency scale in psychoacoustics, abbreviates Equivalent Rectangular Bandwidth */
      XO("ERB") ,
      /* i18n-hint: Time units, that is Period = 1 / Frequency */
      XO("Period") ,
   };
   return result;
}

//static
const EnumValueSymbols &SpectrogramSettings::GetColorSchemeNames()
{
   static const EnumValueSymbols result{
      // Keep in correspondence with enum SpectrogramSettings::ColorScheme:
      /* i18n-hint: New color scheme for spectrograms, Roseus is proper name of the color scheme */
      { wxT("SpecColorNew"),     XC("Color (Roseus)",    "spectrum prefs") },
      /* i18n-hint: Classic color scheme(from theme) for spectrograms */
      { wxT("SpecColorTheme"),   XC("Color (classic)",   "spectrum prefs") },
      /* i18n-hint: Grayscale color scheme for spectrograms */
      { wxT("SpecGrayscale"),    XC("Grayscale",         "spectrum prefs") },
      /* i18n-hint: Inverse grayscale color scheme for spectrograms */
      { wxT("SpecInvGrayscale"), XC("Inverse grayscale", "spectrum prefs") },
   };

   wxASSERT(csNumColorScheme == result.size());

   return result;
}


void SpectrogramSettings::ColorSchemeEnumSetting::Migrate(wxString &value)
{
   // Migrate old grayscale option to Color scheme choice
   bool isGrayscale = SpectrumGrayscale.Read();
   if (isGrayscale && !gPrefs->Read(wxT("/Spectrum/ColorScheme"), &value)) {
      value = GetColorSchemeNames().at(csGrayscale).Internal();
      Write(value);
      gPrefs->Flush();
   }
}

SpectrogramSettings::ColorSchemeEnumSetting SpectrogramSettings::colorSchemeSetting{
   wxT("/Spectrum/ColorScheme"),
   GetColorSchemeNames(),
   csColorNew, // default to Color(New)
   { csColorNew, csColorTheme, csGrayscale, csInvGrayscale },
};


//static
const TranslatableStrings &SpectrogramSettings::GetAlgorithmNames()
{
   static const TranslatableStrings results{
      // Keep in correspondence with enum SpectrogramSettings::Algorithm:
      XO("Frequencies") ,
      /* i18n-hint: the Reassignment algorithm for spectrograms */
      XO("Reassignment") ,
      /* i18n-hint: EAC abbreviates "Enhanced Autocorrelation" */
      XO("Pitch (EAC)") ,
#ifdef WAVELET
      XO("Wavelet (1/6 Octave Hann)") ,
#endif
   };
   return results;
}

bool SpectrogramSettings::Validate(bool quiet)
{
   if (!quiet &&
      maxFreq < 100) {
      BasicUI::ShowMessageBox( XO("Maximum frequency must be 100 Hz or above") );
      return false;
   }
   else
      maxFreq = std::max(100, maxFreq);

   if (!quiet &&
      minFreq < 0) {
      BasicUI::ShowMessageBox( XO("Minimum frequency must be at least 0 Hz") );
      return false;
   }
   else
      minFreq = std::max(0, minFreq);

   if (!quiet &&
      maxFreq <= minFreq) {
      BasicUI::ShowMessageBox( XO(
"Minimum frequency must be less than maximum frequency") );
      return false;
   }
   else
      maxFreq = std::max(1 + minFreq, maxFreq);

   if (!quiet &&
      range <= 0) {
      BasicUI::ShowMessageBox( XO("The range must be at least 1 dB") );
      return false;
   }
   else
      range = std::max(1, range);

   if (!quiet &&
      frequencyGain < 0) {
      BasicUI::ShowMessageBox( XO("The frequency gain cannot be negative") );
      return false;
   }
   else if (!quiet &&
      frequencyGain > 60) {
      BasicUI::ShowMessageBox( XO(
"The frequency gain must be no more than 60 dB/dec") );
      return false;
   }
   else
      frequencyGain =
         std::max(0, std::min(60, frequencyGain));

   // The rest are controlled by drop-down menus so they can't go wrong
   // in the Preferences dialog, but we also come here after reading fom saved
   // preference files, which could be or from future versions.  Validate quietly.
   windowType =
      std::max(0, std::min(NumWindowFuncs() - 1, windowType));
   scaleType =
      ScaleType(std::max(0,
         std::min((int)(SpectrogramSettings::stNumScaleTypes) - 1,
            (int)(scaleType))));
   colorScheme = ColorScheme(
      std::max(0, std::min<int>(csNumColorScheme-1, colorScheme))
   );
   algorithm = Algorithm(
      std::max(0, std::min((int)(algNumAlgorithms) - 1, (int)(algorithm)))
   );
   ConvertToEnumeratedWindowSizes();
   ConvertToActualWindowSizes();

   return true;
}

void SpectrogramSettings::LoadPrefs()
{
   minFreq = SpectrumMinFreq.Read();

   maxFreq = SpectrumMaxFreq.Read();

   range = SpectrumRange.Read();
   gain = SpectrumGain.Read();
   frequencyGain = SpectrumFrequencyGain.Read();

   windowSize = SpectrumFFTSize.Read();

   zeroPaddingFactor = SpectrumZeroPaddingFactor.Read();

   windowType = SpectrumWindowFunction.Read();

   colorScheme = colorSchemeSetting.ReadEnum();

   scaleType = static_cast<ScaleType>(SpectrumScale.Read());

#ifndef SPECTRAL_SELECTION_GLOBAL_SWITCH
   spectralSelection = SpectrumEnableSelection.Read();
#endif

   algorithm = static_cast<Algorithm>(SpectrumAlgorithm.Read());

#ifdef EXPERIMENTAL_FFT_Y_GRID
   fftYGrid = SpectrumYGrid.Read();
#endif //EXPERIMENTAL_FFT_Y_GRID

#ifdef EXPERIMENTAL_FIND_NOTES
   fftFindNotes = SpectrumFindNotes.Read();
   findNotesMinA = SpectrumFindNotesMinA.Read();
   numberOfMaxima = SpectrumFindNotesN.Read();
   findNotesQuantize = SpectrumFindNotesQuantize.Read();
#endif //EXPERIMENTAL_FIND_NOTES

   // Enforce legal values
   Validate(true);

   InvalidateCaches();
}

void SpectrogramSettings::SavePrefs()
{
   SpectrumMinFreq.Write(minFreq);
   SpectrumMaxFreq.Write(maxFreq);

   // Nothing wrote these.  They only varied from the linear scale bounds in-session. -- PRL
   // gPrefs->Write(wxT("/SpectrumLog/MaxFreq"), logMinFreq);
   // gPrefs->Write(wxT("/SpectrumLog/MinFreq"), logMaxFreq);

   SpectrumRange.Write(range);
   SpectrumGain.Write(gain);
   SpectrumFrequencyGain.Write(frequencyGain);

   SpectrumFFTSize.Write(windowSize);

   SpectrumZeroPaddingFactor.Write(zeroPaddingFactor);

   SpectrumWindowFunction.Write(windowType);

   colorSchemeSetting.WriteEnum(colorScheme);

   SpectrumScale.Write(static_cast<int>(scaleType));

#ifndef SPECTRAL_SELECTION_GLOBAL_SWITCH
   SpectrumEnableSelection.Write(spectralSelection);
#endif

   SpectrumAlgorithm.Write(static_cast<int>(algorithm));

#ifdef EXPERIMENTAL_FFT_Y_GRID
   SpectrumYGrid.Write(fftYGrid);
#endif //EXPERIMENTAL_FFT_Y_GRID

#ifdef EXPERIMENTAL_FIND_NOTES
   SpectrumFindNotes.Write(fftFindNotes);
   SpectrumFindNotesMinA.Write(findNotesMinA);
   SpectrumFindNotesN.Write(numberOfMaxima);
   SpectrumFindNotesQuantize.Write(findNotesQuantize);
#endif //EXPERIMENTAL_FIND_NOTES
}

// This is a temporary hack until SpectrogramSettings gets fully integrated
void SpectrogramSettings::UpdatePrefs()
{
   if (minFreq == defaults().minFreq)
      minFreq = SpectrumMinFreq.Read();

   if (maxFreq == defaults().maxFreq)
      maxFreq = SpectrumMaxFreq.Read();

   if (range == defaults().range)
      range = SpectrumRange.Read();

   if (gain == defaults().gain)
      gain = SpectrumGain.Read();

   if (frequencyGain == defaults().frequencyGain)
      frequencyGain = SpectrumFrequencyGain.Read();

   if (windowSize == defaults().windowSize)
      windowSize = SpectrumFFTSize.Read();

   if (zeroPaddingFactor == defaults().zeroPaddingFactor)
      zeroPaddingFactor = SpectrumZeroPaddingFactor.Read();

   if (windowType == defaults().windowType)
      windowType = SpectrumWindowFunction.Read();

   if (colorScheme == defaults().colorScheme) {
      colorScheme = colorSchemeSetting.ReadEnum();
   }

   if (scaleType == defaults().scaleType)
      scaleType = static_cast<ScaleType>(SpectrumScale.Read());

#ifndef SPECTRAL_SELECTION_GLOBAL_SWITCH
   if (spectralSelection == defaults().spectralSelection)
      spectralSelection = SpectrumEnableSelection.Read();
#endif

   if (algorithm == defaults().algorithm)
      algorithm = static_cast<Algorithm>(SpectrumAlgorithm.Read());

#ifdef EXPERIMENTAL_FFT_Y_GRID
   if (fftYGrid == defaults().fftYGrid)
      fftYGrid = SpectrumYGrid.Read();
#endif //EXPERIMENTAL_FFT_Y_GRID

#ifdef EXPERIMENTAL_FIND_NOTES
   if (fftFindNotes == defaults().fftFindNotes)
      fftFindNotes = SpectrumFindNotes.Read();

   if (findNotesMinA == defaults().findNotesMinA)
      findNotesMinA = SpectrumFindNotesMinA.Read();

   if (numberOfMaxima == defaults().numberOfMaxima)
      numberOfMaxima = SpectrumFindNotesN.Read();

   if (findNotesQuantize == defaults().findNotesQuantize)
      findNotesQuantize = SpectrumFindNotesQuantize.Read();
#endif //EXPERIMENTAL_FIND_NOTES

   // Enforce legal values
   Validate(true);
}

void SpectrogramSettings::InvalidateCaches()
{
   DestroyWindows();
}

SpectrogramSettings::~SpectrogramSettings()
{
   DestroyWindows();
}

auto SpectrogramSettings::Clone() const -> PointerType
{
   return std::make_unique<SpectrogramSettings>(*this);
}

void SpectrogramSettings::DestroyWindows()
{
   hFFT.reset();
   window.reset();
   waveletsRe.reset();
   waveletsIm.reset();
   waveletSizes.reset();
   waveletMaxLength = 0;
   dWindow.reset();
   tWindow.reset();
}


namespace
{
   enum { WINDOW, TWINDOW, DWINDOW };
   void RecreateWindow(
      Floats &window, int which, size_t fftLen,
      size_t padding, int windowType, size_t windowSize, double &scale)
   {
      // Create the requested window function
      window = Floats{ fftLen };
      size_t ii;

      const bool extra = padding > 0;
      wxASSERT(windowSize % 2 == 0);
      if (extra)
         // For windows that do not go to 0 at the edges, this improves symmetry
         ++windowSize;
      const size_t endOfWindow = padding + windowSize;
      // Left and right padding
      for (ii = 0; ii < padding; ++ii) {
         window[ii] = 0.0;
         window[fftLen - ii - 1] = 0.0;
      }
      // Default rectangular window in the middle
      for (; ii < endOfWindow; ++ii)
         window[ii] = 1.0;
      // Overwrite middle as needed
      switch (which) {
      case WINDOW:
         NewWindowFunc(windowType, windowSize, extra, window.get() + padding);
         break;
      case TWINDOW:
         NewWindowFunc(windowType, windowSize, extra, window.get() + padding);
         {
            for (int jj = padding, multiplier = -(int)windowSize / 2; jj < (int)endOfWindow; ++jj, ++multiplier)
               window[jj] *= multiplier;
         }
         break;
      case DWINDOW:
         DerivativeOfWindowFunc(windowType, windowSize, extra, window.get() + padding);
         break;
      default:
         wxASSERT(false);
      }
      // Scale the window function to give 0dB spectrum for 0dB sine tone
      if (which == WINDOW) {
         scale = 0.0;
         for (ii = padding; ii < endOfWindow; ++ii)
            scale += window[ii];
         if (scale > 0)
            scale = 2.0 / scale;
      }
      for (ii = padding; ii < endOfWindow; ++ii)
         window[ii] *= scale;
}

void RecreateWavelet(size_t &size, Floats &waveletRe, Floats &waveletIm, double frequency, size_t bins)
{
    assert(frequency >= 0);
    assert(frequency <= 0.5);
    if (frequency == 0)
    {
        size = 0;
        waveletRe = Floats{};
        waveletIm = Floats{};
        return;
    }
    
    // We will then create a modulated Hann window at the given nominal frequency
    // Window length must be chosen such that spectral power bandwidth is 1/6th of an octave
    // This bandwidth constraint then in return governs the duration of the hann window
    // The RMS Bandwidth of Hann window is 2* 1/T * sqrt(1/3)
    // Formula to obtain duration is thus
    // RMSBW = 2 * sqrt(1/3) / T
    // T = 2 * sqrt(1/3) / RMSBW
    // RMSBW = 1/6th octave, ie factor 2^0.16667 = 1.122 between bands
    // T = 2 * sqrt(1/3) / (sqrt(1.122) * Fc - Fc / sqrt(1.122)) = 2 * sqrt(1/3) / (sqrt(1.122) - 1/sqrt(1.122) / Fc = 10,02 / Fc
    const double BandsPerOctave = 6.0;
    const double bwFactor = pow(2, 1.0/BandsPerOctave);
    const double durationFactor = 2 * sqrt(1.0/3.0) / (sqrt(bwFactor) - sqrt(1/bwFactor));
    const double PI = 4.0 * atan(1);
    const double omega = 2 * PI * frequency;

    double waveletDurationHalf = 0.5 * durationFactor / frequency; // float number of samples for half-length. Hann enveloped filter will be zero outside range [-waveletDurationHalf; waveletDurationHalf]
    size = (int) (waveletDurationHalf); // truncate to integer number of samples. "size" will hold the half-length of the wavelet filter (conjugate symmetry)
    if (size > bins)
    {
        // There is no point in using wavelets that exceed resolution in our frequency array (under sampling, really)
        size = 0;
        waveletRe = Floats{};
        waveletIm = Floats{};
        return;
    }


    waveletRe = Floats{size};
    waveletIm = Floats{size};
    
    for (int i = 0; i < size; i++)
    {
        double relative_dt = i / waveletDurationHalf;
        double envelope = (1 + cos(relative_dt * PI)) / (waveletDurationHalf * 2.0); // Normalize for zero gain when doing convolution
        waveletRe[i] = envelope * cos(omega * i);
        waveletIm[i] = envelope * sin(omega * i);
    }
    
    return;
}
}

void SpectrogramSettings::CacheWindows()
{
   if (algorithm == algWavelet)
   {
       if (waveletsRe == NULL || waveletsIm == NULL)
       {
           size_t num = NBins();
           waveletsRe = FloatBuffers {num};
           waveletsIm = FloatBuffers {num};
           waveletSizes = ArrayOf<size_t> {num};
           waveletMaxLength = 0;
           double delta = 0.5 / num;
           for (int i = 0; i < num; i++)
           {
               RecreateWavelet(waveletSizes[i], waveletsRe[i], waveletsIm[i], i * delta, num);
               if (waveletSizes[i] > waveletMaxLength)
               {
                   waveletMaxLength = waveletSizes[i];
               }
           }
       }
   }
   else
   {
       if (hFFT == NULL || window == NULL) {
           
           double scale;
           auto factor = ZeroPaddingFactor();
           const auto fftLen = WindowSize() * factor;
           const auto padding = (WindowSize() * (factor - 1)) / 2;
           
           hFFT = GetFFT(fftLen);
           RecreateWindow(window, WINDOW, fftLen, padding, windowType, windowSize, scale);
           if (algorithm == algReassignment) {
               RecreateWindow(tWindow, TWINDOW, fftLen, padding, windowType, windowSize, scale);
               RecreateWindow(dWindow, DWINDOW, fftLen, padding, windowType, windowSize, scale);
           }
       }
   }
}

void SpectrogramSettings::ConvertToEnumeratedWindowSizes()
{
   unsigned size;
   int logarithm;

   logarithm = -LogMinWindowSize;
   size = unsigned(windowSize);
   while (size > 1)
      size >>= 1, ++logarithm;
   windowSize = std::max(0, std::min(NumWindowSizes - 1, logarithm));

   // Choices for zero padding begin at 1
   logarithm = 0;
   size = unsigned(zeroPaddingFactor);
   while (zeroPaddingFactor > 1)
      zeroPaddingFactor >>= 1, ++logarithm;
   zeroPaddingFactor = std::max(0,
      std::min(LogMaxWindowSize - (windowSize + LogMinWindowSize),
         logarithm
   ));
}

void SpectrogramSettings::ConvertToActualWindowSizes()
{
   windowSize = 1 << (windowSize + LogMinWindowSize);
   zeroPaddingFactor = 1 << zeroPaddingFactor;
}

float SpectrogramSettings::findBin( float frequency, float binUnit ) const
{
   float linearBin = frequency / binUnit;
   if (linearBin < 0)
      return -1;
   else
      return linearBin;
}

size_t SpectrogramSettings::GetFFTLength() const
{
//#ifndef EXPERIMENTAL_ZERO_PADDED_SPECTROGRAMS
  // return windowSize;
//#else
   return windowSize * ((algorithm != algPitchEAC && algorithm != algWavelet) ? zeroPaddingFactor : 1);
//#endif
}

size_t SpectrogramSettings::NBins() const
{
   // Omit the Nyquist frequency bin
   return GetFFTLength() / 2;
}

NumberScale SpectrogramSettings::GetScale( float minFreqIn, float maxFreqIn ) const
{
   NumberScaleType type = nstLinear;

   // Don't assume the correspondence of the enums will remain direct in the future.
   // Do this switch.
   switch (scaleType) {
   default:
      wxASSERT(false);
   case stLinear:
      type = nstLinear; break;
   case stLogarithmic:
      type = nstLogarithmic; break;
   case stMel:
      type = nstMel; break;
   case stBark:
      type = nstBark; break;
   case stErb:
      type = nstErb; break;
   case stPeriod:
      type = nstPeriod; break;
   }

   return NumberScale(type, minFreqIn, maxFreqIn);
}

bool SpectrogramSettings::SpectralSelectionEnabled() const
{
#ifdef SPECTRAL_SELECTION_GLOBAL_SWITCH
   return Globals::Get().spectralSelection;
#else
   return spectralSelection;
#endif
}

static const ChannelGroup::Attachments::RegisteredFactory
key2{ [](auto &) { return std::make_unique<SpectrogramBounds>(); } };

SpectrogramBounds &SpectrogramBounds::Get( WaveTrack &track )
{
   return track.Attachments::Get<SpectrogramBounds>(key2);
}

const SpectrogramBounds &SpectrogramBounds::Get(
   const WaveTrack &track )
{
   return Get(const_cast<WaveTrack&>(track));
}

SpectrogramBounds &SpectrogramBounds::Get(WaveChannel &channel)
{
   return Get(channel.GetTrack());
}

const SpectrogramBounds &SpectrogramBounds::Get(const WaveChannel &channel)
{
   return Get(const_cast<WaveChannel&>(channel));
}

SpectrogramBounds::~SpectrogramBounds() = default;

auto SpectrogramBounds::Clone() const -> PointerType
{
   return std::make_unique<SpectrogramBounds>(*this);
}

void SpectrogramBounds::GetBounds(
   const WaveChannel &wc, float &min, float &max) const
{
   auto &wt = wc.GetTrack();
   const double rate = wt.GetRate();

   const auto &settings = SpectrogramSettings::Get(wt);
   const auto type = settings.scaleType;

   const float top = (rate / 2.);

   float bottom;
   if (type == SpectrogramSettings::stLinear)
      bottom = 0.0f;
   else if (type == SpectrogramSettings::stPeriod) {
      // special case
      const auto half = settings.GetFFTLength() / 2;
      // EAC returns no data for below this frequency:
      const float bin2 = rate / half;
      bottom = bin2;
   }
   else
      // logarithmic, etc.
      bottom = 1.0f;

   {
      float spectrumMax = mSpectrumMax;
      if (spectrumMax < 0)
         spectrumMax = settings.maxFreq;
      if (spectrumMax < 0)
         max = top;
      else
         max = std::clamp(spectrumMax, bottom, top);
   }

   {
      float spectrumMin = mSpectrumMin;
      if (spectrumMin < 0)
         spectrumMin = settings.minFreq;
      if (spectrumMin < 0)
         min = std::max(bottom, top / 1000.0f);
      else
         min = std::clamp(spectrumMin, bottom, top);
   }
}