Debian Codegraph @

src/tracks/playabletrack/wavetrack/ui/SpectrumCache.cpp

raw
1 /**********************************************************************
2
3 Audacity: A Digital Audio Editor
4
5 @file SpectrumCache.cpp
6
7 Paul Licameli split from WaveClip.cpp
8
9 **********************************************************************/
10
11 #include "SpectrumCache.h"
12
13 #include "SpectrogramSettings.h"
14 #include "RealFFTf.h"
15 #include "Sequence.h"
16 #include "Spectrum.h"
17 #include "WaveClipUIUtilities.h"
18 #include "WaveTrack.h"
19 #include "WideSampleSequence.h"
20 #include <cmath>
21
22 namespace {
23
24 static void ComputeSpectrumUsingRealFFTf
25 (float * __restrict buffer, const FFTParam *hFFT,
26 const float * __restrict window, size_t len, float * __restrict out)
27 {
28 size_t i;
29 if(len > hFFT->Points * 2)
30 len = hFFT->Points * 2;
31 for(i = 0; i < len; i++)
32 buffer[i] *= window[i];
33 for( ; i < (hFFT->Points * 2); i++)
34 buffer[i] = 0; // zero pad as needed
35 RealFFTf(buffer, hFFT);
36 // Handle the (real-only) DC
37 float power = buffer[0] * buffer[0];
38 if(power <= 0)
39 out[0] = -160.0;
40 else
41 out[0] = 10.0 * log10f(power);
42 for(i = 1; i < hFFT->Points; i++) {
43 const int index = hFFT->BitReversed[i];
44 const float re = buffer[index], im = buffer[index + 1];
45 power = re * re + im * im;
46 if(power <= 0)
47 out[i] = -160.0;
48 else
49 out[i] = 10.0*log10f(power);
50 }
51 }
52
53 void ComputeSpectrogramGainFactors
54 (size_t fftLen, double rate, int frequencyGain, std::vector<float> &gainFactors)
55 {
56 if (frequencyGain > 0) {
57 // Compute a frequency-dependent gain factor
58 // scaled such that 1000 Hz gets a gain of 0dB
59
60 // This is the reciprocal of the bin number of 1000 Hz:
61 const double factor = ((double)rate / (double)fftLen) / 1000.0;
62
63 auto half = fftLen / 2;
64 gainFactors.reserve(half);
65 // Don't take logarithm of zero! Let bin 0 replicate the gain factor for bin 1.
66 gainFactors.push_back(frequencyGain*log10(factor));
67 for (decltype(half) x = 1; x < half; x++) {
68 gainFactors.push_back(frequencyGain*log10(factor * x));
69 }
70 }
71 }
72
73 }
74
75 bool SpecCache::isWaveletAnalysis(const SpectrogramSettings& settings) const
76 {
77 return settings.algorithm == SpectrogramSettings::algWavelet;
78 }
79
80 bool SpecCache::Matches(
81 int dirty_, double samplesPerPixel,
82 const SpectrogramSettings& settings) const
83 {
84 // Make a tolerant comparison of the spp values in this wise:
85 // accumulated difference of times over the number of pixels is less than
86 // a sample period.
87 const bool sppMatch = (fabs(samplesPerPixel - spp) * len < 1.0);
88
89 if (isWaveletAnalysis(settings))
90 {
91 return
92 sppMatch &&
93 dirty == dirty_ &&
94 frequencyGain == settings.frequencyGain &&
95 algorithm == settings.algorithm &&
96 windowSize == settings.WindowSize();
97 }
98 return
99 sppMatch &&
100 dirty == dirty_ &&
101 windowType == settings.windowType &&
102 windowSize == settings.WindowSize() &&
103 zeroPaddingFactor == settings.ZeroPaddingFactor() &&
104 frequencyGain == settings.frequencyGain &&
105 algorithm == settings.algorithm;
106 }
107
108 bool SpecCache::CalculateOneSpectrum(
109 const SpectrogramSettings& settings, const WaveChannelInterval& clip,
110 const int xx, double pixelsPerSecond, int lowerBoundX, int upperBoundX,
111 const std::vector<float>& gainFactors, float* __restrict scratch,
112 float* __restrict out) const
113 {
114 bool result = false;
115 const bool reassignment =
116 (settings.algorithm == SpectrogramSettings::algReassignment);
117 const size_t windowSizeSetting = settings.WindowSize();
118
119 sampleCount from;
120
121 const auto numSamples = clip.GetSequence().GetNumSamples();
122 const auto sampleRate = clip.GetRate();
123 const auto stretchRatio = clip.GetStretchRatio();
124 const auto samplesPerPixel = sampleRate / pixelsPerSecond / stretchRatio;
125 // xx may be for a column that is out of the visible bounds, but only
126 // when we are calculating reassignment contributions that may cross into
127 // the visible area.
128
129 if (xx < 0)
130 from = sampleCount(where[0].as_double() + xx * samplesPerPixel);
131 else if (xx > (int)len)
132 from = sampleCount(where[len].as_double() + (xx - len) * samplesPerPixel);
133 else
134 from = where[xx];
135
136 const bool autocorrelation =
137 settings.algorithm == SpectrogramSettings::algPitchEAC;
138 const size_t zeroPaddingFactorSetting = settings.ZeroPaddingFactor();
139 const size_t padding = (windowSizeSetting * (zeroPaddingFactorSetting - 1)) / 2;
140 const size_t fftLen = windowSizeSetting * zeroPaddingFactorSetting;
141 auto nBins = settings.NBins();
142
143 if (from < 0 || from >= numSamples) {
144 if (xx >= 0 && xx < (int)len) {
145 // Pixel column is out of bounds of the clip! Should not happen.
146 float *const results = &out[nBins * xx];
147 std::fill(results, results + nBins, 0.0f);
148 }
149 }
150 else {
151
152
153 // We can avoid copying memory when ComputeSpectrum is used below
154 bool copy = !autocorrelation || (padding > 0) || reassignment;
155 std::vector<float> floats;
156 float* useBuffer = 0;
157 float *adj = scratch + padding;
158
159 {
160 auto myLen = windowSizeSetting;
161 // Take a window of the track centered at this sample.
162 from -= windowSizeSetting >> 1;
163 if (from < 0) {
164 // Near the start of the clip, pad left with zeroes as needed.
165 // from is at least -windowSize / 2
166 for (auto ii = from; ii < 0; ++ii)
167 *adj++ = 0;
168 myLen += from.as_long_long(); // add a negative
169 from = 0;
170 copy = true;
171 }
172
173 if (from + myLen >= numSamples) {
174 // Near the end of the clip, pad right with zeroes as needed.
175 // newlen is bounded by myLen:
176 auto newlen = ( numSamples - from ).as_size_t();
177 for (decltype(myLen) ii = newlen; ii < myLen; ++ii)
178 adj[ii] = 0;
179 myLen = newlen;
180 copy = true;
181 }
182
183 if (myLen > 0) {
184 constexpr auto iChannel = 0u;
185 constexpr auto mayThrow = false; // Don't throw just for display
186 mSampleCacheHolder.emplace(
187 clip.GetSampleView(from, myLen, mayThrow));
188 floats.resize(myLen);
189 mSampleCacheHolder->Copy(floats.data(), myLen);
190 useBuffer = floats.data();
191 if (copy) {
192 if (useBuffer)
193 memcpy(adj, useBuffer, myLen * sizeof(float));
194 else
195 memset(adj, 0, myLen * sizeof(float));
196 }
197 }
198 }
199
200 if (copy || !useBuffer)
201 useBuffer = scratch;
202
203 if (autocorrelation) {
204 // not reassignment, xx is surely within bounds.
205 wxASSERT(xx >= 0);
206 float *const results = &out[nBins * xx];
207 // This function does not mutate useBuffer
208 ComputeSpectrum(
209 useBuffer, windowSizeSetting, windowSizeSetting, results,
210 autocorrelation, settings.windowType);
211 }
212 else if (reassignment) {
213 static const double epsilon = 1e-16;
214 const auto hFFT = settings.hFFT.get();
215
216 float *const scratch2 = scratch + fftLen;
217 std::copy(scratch, scratch2, scratch2);
218
219 float *const scratch3 = scratch + 2 * fftLen;
220 std::copy(scratch, scratch2, scratch3);
221
222 {
223 const float *const window = settings.window.get();
224 for (size_t ii = 0; ii < fftLen; ++ii)
225 scratch[ii] *= window[ii];
226 RealFFTf(scratch, hFFT);
227 }
228
229 {
230 const float *const dWindow = settings.dWindow.get();
231 for (size_t ii = 0; ii < fftLen; ++ii)
232 scratch2[ii] *= dWindow[ii];
233 RealFFTf(scratch2, hFFT);
234 }
235
236 {
237 const float *const tWindow = settings.tWindow.get();
238 for (size_t ii = 0; ii < fftLen; ++ii)
239 scratch3[ii] *= tWindow[ii];
240 RealFFTf(scratch3, hFFT);
241 }
242
243 for (size_t ii = 0; ii < hFFT->Points; ++ii) {
244 const int index = hFFT->BitReversed[ii];
245 const float
246 denomRe = scratch[index],
247 denomIm = ii == 0 ? 0 : scratch[index + 1];
248 const double power = denomRe * denomRe + denomIm * denomIm;
249 if (power < epsilon)
250 // Avoid dividing by near-zero below
251 continue;
252
253 double freqCorrection;
254 {
255 const double multiplier = -(fftLen / (2.0f * M_PI));
256 const float
257 numRe = scratch2[index],
258 numIm = ii == 0 ? 0 : scratch2[index + 1];
259 // Find complex quotient --
260 // Which means, multiply numerator by conjugate of denominator,
261 // then divide by norm squared of denominator --
262 // Then just take its imaginary part.
263 const double
264 quotIm = (-numRe * denomIm + numIm * denomRe) / power;
265 // With appropriate multiplier, that becomes the correction of
266 // the frequency bin.
267 freqCorrection = multiplier * quotIm;
268 }
269
270 const int bin = (int)((int)ii + freqCorrection + 0.5f);
271 // Must check if correction takes bin out of bounds, above or below!
272 // bin is signed!
273 if (bin >= 0 && bin < (int)hFFT->Points) {
274 double timeCorrection;
275 {
276 const float
277 numRe = scratch3[index],
278 numIm = ii == 0 ? 0 : scratch3[index + 1];
279 // Find another complex quotient --
280 // Then just take its real part.
281 // The result has sample interval as unit.
282 timeCorrection =
283 (numRe * denomRe + numIm * denomIm) / power;
284 }
285
286 // PRL: timeCorrection is scaled to the clip's raw sample rate,
287 // without the stretching ratio correction for real time. We want
288 // to find the correct X coordinate for that.
289 int correctedX = (floor(
290 0.5 + xx + timeCorrection * pixelsPerSecond / sampleRate));
291 if (correctedX >= lowerBoundX && correctedX < upperBoundX)
292 {
293 result = true;
294
295 // This is non-negative, because bin and correctedX are
296 auto ind = (int)nBins * correctedX + bin;
297 #ifdef _OPENMP
298 // This assignment can race if index reaches into another thread's bins.
299 // The probability of a race very low, so this carries little overhead,
300 // about 5% slower vs allowing it to race.
301 #pragma omp atomic update
302 #endif
303 out[ind] += power;
304 }
305 }
306 }
307 }
308 else {
309 // not reassignment, xx is surely within bounds.
310 wxASSERT(xx >= 0);
311 float *const results = &out[nBins * xx];
312
313 // Do the FFT. Note that useBuffer is multiplied by the window,
314 // and the window is initialized with leading and trailing zeroes
315 // when there is padding. Therefore we did not need to reinitialize
316 // the part of useBuffer in the padding zones.
317
318 // This function mutates useBuffer
319 ComputeSpectrumUsingRealFFTf
320 (useBuffer, settings.hFFT.get(), settings.window.get(), fftLen, results);
321 if (!gainFactors.empty()) {
322 // Apply a frequency-dependent gain factor
323 for (size_t ii = 0; ii < nBins; ++ii)
324 results[ii] += gainFactors[ii];
325 }
326 }
327 }
328
329 return result;
330 }
331
332 bool SpecCache::CalculateOneWaveletSpectrum(
333 const SpectrogramSettings& settings, const WaveChannelInterval& clip,
334 const int xx, double pixelsPerSecond, int lowerBoundX, int upperBoundX,
335 const std::vector<float>& gainFactors,
336 float* __restrict out) const
337 {
338 bool result = false;
339 sampleCount from;
340
341 const auto numSamples = clip.GetSequence().GetNumSamples();
342 const auto sampleRate = clip.GetRate();
343 const auto stretchRatio = clip.GetStretchRatio();
344 const auto samplesPerPixel = sampleRate / pixelsPerSecond / stretchRatio;
345 const size_t nBins = settings.NBins();
346 float *const results = &out[nBins * xx];
347
348 // not reassignment, xx is surely within bounds.
349 wxASSERT(xx >= 0);
350 if (xx > (int)len)
351 from = sampleCount(where[len].as_double() + (xx - len) * samplesPerPixel);
352 else
353 from = where[xx];
354
355 if (from < 0 || from >= numSamples) {
356 if (xx >= 0 && xx < (int)len) {
357 // Pixel column is out of bounds of the clip! Should not happen.
358 std::fill(results, results + nBins, 0.0f);
359 }
360 }
361 else
362 {
363 // Iterate frequencies in turn
364 // Note that as opposed to Fourier Transform, using wavelets implies a window length that varies with frequency
365 // We extract samples corresponding to max wavelet length (the first)
366
367 // Locate longest wavelet (first one)
368 const auto longestWaveletLen = settings.waveletMaxLength;
369 wxASSERT(longestWaveletLen);
370
371 auto myLen = 2 * longestWaveletLen - 1;
372 std::vector<float> scratch(myLen);
373
374 // Take a window of the track centered at this sample.
375 from -= longestWaveletLen;
376 float * adj = &scratch[0];
377 if (from < 0) {
378 // Near the start of the clip, pad left with zeroes as needed.
379 for (auto ii = from; ii < 0; ++ii)
380 *adj++ = 0;
381 myLen += from.as_long_long(); // add a negative
382 from = 0;
383 }
384 if (from + myLen >= numSamples) {
385 // Near the end of the clip, pad right with zeroes as needed.
386 // newlen is bounded by myLen:
387 auto newlen = ( numSamples - from ).as_size_t();
388 for (decltype(myLen) ii = newlen; ii < myLen; ++ii)
389 adj[ii] = 0;
390 myLen = newlen;
391 }
392 std::vector<float> floats;
393 if (myLen > 0) {
394 constexpr auto iChannel = 0u;
395 constexpr auto mayThrow = false; // Don't throw just for display
396 mSampleCacheHolder.emplace(
397 clip.GetSampleView(from, myLen, mayThrow));
398 floats.resize(myLen);
399 mSampleCacheHolder->Copy(floats.data(), myLen);
400 float *useBuffer = floats.data();
401 memcpy(adj, useBuffer, myLen * sizeof(float));
402 }
403
404 // Done preparing samples. Now onward with calculations
405 const float * middleSample = &scratch[longestWaveletLen - 1];
406 for (size_t iBin = 0; iBin < nBins; iBin++)
407 {
408 if (settings.waveletSizes[iBin] == 0)
409 {
410 results[iBin] = -160.0;
411 continue;
412 }
413
414 const float *right = middleSample;
415 const float *left = middleSample;
416 // Do the inner product
417 const float * wRe = &settings.waveletsRe[iBin][0];
418 const float * wIm = &settings.waveletsIm[iBin][0];
419 double sumRe = *middleSample * *wRe;
420 double sumIm = 0.0;
421 wRe++, wIm++, right++, left--;
422 const auto halfLen = settings.waveletSizes[iBin];
423 for (auto ii = 1; ii < halfLen; ii++)
424 {
425 sumRe += (*right + *left) * *wRe;
426 sumIm += (*left - *right) * *wIm;
427 wRe++, wIm++, right++, left--;
428 }
429
430 // Calculate magnitude
431 float power = sumRe * sumRe + sumIm * sumIm;
432
433
434 // Do the log thing
435 if (power <= 0)
436 power = -160.0;
437 else
438 power = 10.0*log10f(power);
439
440 results[iBin] = power;
441 }
442
443
444 if (!gainFactors.empty()) {
445 // Apply a frequency-dependent gain factor
446 for (size_t ii = 0; ii < nBins; ++ii)
447 results[ii] += gainFactors[ii];
448 }
449 result = true;
450 }
451
452 return result;
453 }
454
455 void SpecCache::Grow(
456 size_t len_, SpectrogramSettings& settings, double samplesPerPixel,
457 double start_)
458 {
459 settings.CacheWindows();
460
461 // len columns, and so many rows, column-major.
462 // Don't take column literally -- this isn't pixel data yet, it's the
463 // raw data to be mapped onto the display.
464 freq.resize(len_ * settings.NBins());
465
466 // Sample counts corresponding to the columns, and to one past the end.
467 where.resize(len_ + 1);
468
469 len = len_;
470 algorithm = settings.algorithm;
471 spp = samplesPerPixel;
472 start = start_;
473 windowType = settings.windowType;
474 windowSize = settings.WindowSize();
475 zeroPaddingFactor = settings.ZeroPaddingFactor();
476 frequencyGain = settings.frequencyGain;
477 }
478
479 void SpecCache::Populate(
480 const SpectrogramSettings& settings, const WaveChannelInterval& clip,
481 int copyBegin, int copyEnd, size_t numPixels, double pixelsPerSecond)
482 {
483 const auto sampleRate = clip.GetRate();
484 const int &frequencyGainSetting = settings.frequencyGain;
485 const size_t windowSizeSetting = settings.WindowSize();
486 const bool autocorrelation =
487 settings.algorithm == SpectrogramSettings::algPitchEAC;
488 const bool reassignment =
489 settings.algorithm == SpectrogramSettings::algReassignment;
490 const size_t zeroPaddingFactorSetting = settings.ZeroPaddingFactor();
491
492 // FFT length may be longer than the window of samples that affect results
493 // because of zero padding done for increased frequency resolution
494 const size_t fftLen = windowSizeSetting * zeroPaddingFactorSetting;
495 const auto nBins = settings.NBins();
496
497 const size_t bufferSize = fftLen;
498 const size_t scratchSize = reassignment ? 3 * bufferSize : bufferSize;
499 std::vector<float> scratch(scratchSize);
500
501 std::vector<float> gainFactors;
502 if (!autocorrelation)
503 ComputeSpectrogramGainFactors(
504 fftLen, sampleRate, frequencyGainSetting, gainFactors);
505
506 // Loop over the ranges before and after the copied portion and compute anew.
507 // One of the ranges may be empty.
508 for (int jj = 0; jj < 2; ++jj) {
509 const int lowerBoundX = jj == 0 ? 0 : copyEnd;
510 const int upperBoundX = jj == 0 ? copyBegin : numPixels;
511
512 // todo(mhodgkinson): I don't find an option to define _OPENMP anywhere. Is this
513 // still of interest?
514 #ifdef _OPENMP
515 // Storage for mutable per-thread data.
516 // private clause ensures one copy per thread
517 struct ThreadLocalStorage {
518 ThreadLocalStorage() { }
519 ~ThreadLocalStorage() { }
520
521 void init(SampleTrackCache &waveTrackCache, size_t scratchSize) {
522 if (!cache) {
523 cache = std::make_unique<SampleTrackCache>(waveTrackCache.GetTrack());
524 scratch.resize(scratchSize);
525 }
526 }
527 std::unique_ptr<SampleTrackCache> cache;
528 std::vector<float> scratch;
529 } tls;
530
531 #pragma omp parallel for private(tls)
532 #endif
533 for (auto xx = lowerBoundX; xx < upperBoundX; ++xx)
534 {
535 if (isWaveletAnalysis(settings))
536 {
537 CalculateOneWaveletSpectrum(settings, clip, xx, pixelsPerSecond, lowerBoundX, upperBoundX,
538 gainFactors, &freq[0]);
539 }
540 else
541 {
542 #ifdef _OPENMP
543 tls.init(waveTrackCache, scratchSize);
544 SampleTrackCache& cache = *tls.cache;
545 float* buffer = &tls.scratch[0];
546 #else
547 float* buffer = &scratch[0];
548 #endif
549 CalculateOneSpectrum(
550 settings, clip, xx, pixelsPerSecond, lowerBoundX, upperBoundX,
551 gainFactors, buffer, &freq[0]);
552 }
553 }
554
555 if (reassignment) {
556 // Need to look beyond the edges of the range to accumulate more
557 // time reassignments.
558 // I'm not sure what's a good stopping criterion?
559 auto xx = lowerBoundX;
560 const double pixelsPerSample =
561 pixelsPerSecond * clip.GetStretchRatio() / sampleRate;
562 const int limit = std::min((int)(0.5 + fftLen * pixelsPerSample), 100);
563 for (int ii = 0; ii < limit; ++ii)
564 {
565 const bool result = CalculateOneSpectrum(
566 settings, clip, --xx, pixelsPerSecond, lowerBoundX, upperBoundX,
567 gainFactors, &scratch[0], &freq[0]);
568 if (!result)
569 break;
570 }
571
572 xx = upperBoundX;
573 for (int ii = 0; ii < limit; ++ii)
574 {
575 const bool result = CalculateOneSpectrum(
576 settings, clip, xx++, pixelsPerSecond, lowerBoundX, upperBoundX,
577 gainFactors, &scratch[0], &freq[0]);
578 if (!result)
579 break;
580 }
581
582 // Now Convert to dB terms. Do this only after accumulating
583 // power values, which may cross columns with the time correction.
584 #ifdef _OPENMP
585 #pragma omp parallel for
586 #endif
587 for (xx = lowerBoundX; xx < upperBoundX; ++xx) {
588 float *const results = &freq[nBins * xx];
589 for (size_t ii = 0; ii < nBins; ++ii) {
590 float &power = results[ii];
591 if (power <= 0)
592 power = -160.0;
593 else
594 power = 10.0*log10f(power);
595 }
596 if (!gainFactors.empty()) {
597 // Apply a frequency-dependent gain factor
598 for (size_t ii = 0; ii < nBins; ++ii)
599 results[ii] += gainFactors[ii];
600 }
601 }
602 }
603 }
604 }
605
606 bool WaveClipSpectrumCache::GetSpectrogram(
607 const WaveChannelInterval &clip,
608 const float*& spectrogram, SpectrogramSettings& settings,
609 const sampleCount*& where, size_t numPixels, double t0,
610 double pixelsPerSecond)
611
612 {
613 auto &mSpecCache = mSpecCaches[clip.GetChannelIndex()];
614
615 const auto sampleRate = clip.GetRate();
616 const auto stretchRatio = clip.GetStretchRatio();
617 const auto samplesPerPixel = sampleRate / pixelsPerSecond / stretchRatio;
618
619 //Trim offset comparison failure forces spectrogram cache rebuild
620 //and skip copying "unchanged" data after clip border was trimmed.
621 bool match = mSpecCache && mSpecCache->leftTrim == clip.GetTrimLeft() &&
622 mSpecCache->rightTrim == clip.GetTrimRight() &&
623 mSpecCache->len > 0 &&
624 mSpecCache->Matches(mDirty, samplesPerPixel, settings);
625
626 if (match && mSpecCache->start == t0 && mSpecCache->len >= numPixels)
627 {
628 spectrogram = &mSpecCache->freq[0];
629 where = &mSpecCache->where[0];
630
631 return false; //hit cache completely
632 }
633
634 // Caching is not implemented for reassignment, unless for
635 // a complete hit, because of the complications of time reassignment
636 if (settings.algorithm == SpectrogramSettings::algReassignment)
637 match = false;
638
639 // Free the cache when it won't cause a major stutter.
640 // If the window size changed, we know there is nothing to be copied
641 // If we zoomed out, or resized, we can give up memory. But not too much -
642 // up to 2x extra is needed at the end of the clip to prevent stutter.
643 if (mSpecCache->freq.capacity() > 2.1 * mSpecCache->freq.size() ||
644 mSpecCache->windowSize*mSpecCache->zeroPaddingFactor <
645 settings.WindowSize()*settings.ZeroPaddingFactor())
646 {
647 match = false;
648 mSpecCache = std::make_unique<SpecCache>();
649 }
650
651 int oldX0 = 0;
652 double correction = 0.0;
653
654 int copyBegin = 0, copyEnd = 0;
655 if (match) {
656 WaveClipUIUtilities::findCorrection(
657 mSpecCache->where, mSpecCache->len, numPixels, t0, sampleRate,
658 stretchRatio, samplesPerPixel, oldX0, correction);
659 // Remember our first pixel maps to oldX0 in the old cache,
660 // possibly out of bounds.
661 // For what range of pixels can data be copied?
662 int oldLen = mSpecCache->len;
663 copyBegin = std::min(oldLen, std::max(0, -oldX0));
664 copyEnd = std::min(oldLen, std::max(0, oldLen - oldX0));
665 }
666
667 mSpecCache->leftTrim = clip.GetTrimLeft();
668 mSpecCache->rightTrim = clip.GetTrimRight();
669 auto nBins = settings.NBins();
670
671 // Optimization: if the old cache is good and overlaps
672 // with the current one, re-use as much of the cache as
673 // possible
674 if (copyEnd > copyBegin)
675 {
676 // memmove is required since dst/src overlap
677 memmove(&mSpecCache->freq[nBins * copyBegin],
678 &mSpecCache->freq[nBins * (copyBegin + oldX0)],
679 nBins * (copyEnd - copyBegin) * sizeof(float));
680 }
681
682 // Resize the cache, keep the contents unchanged.
683 mSpecCache->Grow(numPixels, settings, samplesPerPixel, t0);
684
685 // Reassignment accumulates, so it needs a zeroed buffer
686 if (settings.algorithm == SpectrogramSettings::algReassignment)
687 {
688 // The cache could theoretically copy from the middle, resulting
689 // in two regions to update. This won't happen in zoom, since
690 // old cache doesn't match. It won't happen in resize, since the
691 // spectrum view is pinned to left side of window.
692 wxASSERT(
693 (copyBegin >= 0 && copyEnd == (int)numPixels) || // copied the end
694 (copyBegin == 0 && copyEnd <= (int)numPixels) // copied the beginning
695 );
696
697 int zeroBegin = copyBegin > 0 ? 0 : copyEnd-copyBegin;
698 int zeroEnd = copyBegin > 0 ? copyBegin : numPixels;
699
700 memset(&mSpecCache->freq[nBins*zeroBegin], 0, nBins*(zeroEnd-zeroBegin)*sizeof(float));
701 }
702
703 // purposely offset the display 1/2 sample to the left (as compared
704 // to waveform display) to properly center response of the FFT
705 constexpr auto addBias = true;
706 WaveClipUIUtilities::fillWhere(
707 mSpecCache->where, numPixels, addBias, correction, t0, sampleRate,
708 stretchRatio, samplesPerPixel);
709
710 mSpecCache->Populate(settings, clip, copyBegin, copyEnd, numPixels, pixelsPerSecond);
711 mSpecCache->dirty = mDirty;
712 spectrogram = &mSpecCache->freq[0];
713 where = &mSpecCache->where[0];
714
715 return true;
716 }
717
718 WaveClipSpectrumCache::WaveClipSpectrumCache(size_t nChannels)
719 : mSpecCaches(nChannels)
720 , mSpecPxCaches(nChannels)
721 {
722 for (auto &pCache : mSpecCaches)
723 pCache = std::make_unique<SpecCache>();
724 }
725
726 WaveClipSpectrumCache::~WaveClipSpectrumCache()
727 {
728 }
729
730 std::unique_ptr<WaveClipListener> WaveClipSpectrumCache::Clone() const
731 {
732 // Don't need to copy contents
733 return std::make_unique<WaveClipSpectrumCache>(mSpecCaches.size());
734 }
735
736 static WaveClip::Attachments::RegisteredFactory sKeyS{ [](WaveClip &clip){
737 return std::make_unique<WaveClipSpectrumCache>(clip.NChannels());
738 } };
739
740 WaveClipSpectrumCache &
741 WaveClipSpectrumCache::Get(const WaveChannelInterval &clip)
742 {
743 return const_cast<WaveClip&>(clip.GetClip()) // Consider it mutable data
744 .Attachments::Get< WaveClipSpectrumCache >( sKeyS );
745 }
746
747 void WaveClipSpectrumCache::MarkChanged() noexcept
748 {
749 ++mDirty;
750 }
751
752 void WaveClipSpectrumCache::Invalidate()
753 {
754 // Invalidate the spectrum display cache
755 for (auto &pCache : mSpecCaches)
756 pCache = std::make_unique<SpecCache>();
757 }
758
759 void WaveClipSpectrumCache::MakeStereo(WaveClipListener &&other, bool)
760 {
761 auto pOther = dynamic_cast<WaveClipSpectrumCache *>(&other);
762 assert(pOther); // precondition
763 mSpecCaches.push_back(move(pOther->mSpecCaches[0]));
764 mSpecPxCaches.push_back(move(pOther->mSpecPxCaches[0]));
765 }
766
767 void WaveClipSpectrumCache::SwapChannels()
768 {
769 mSpecCaches.resize(2);
770 std::swap(mSpecCaches[0], mSpecCaches[1]);
771 mSpecPxCaches.resize(2);
772 std::swap(mSpecPxCaches[0], mSpecPxCaches[1]);
773 }
774
775 void WaveClipSpectrumCache::Erase(size_t index)
776 {
777 if (index < mSpecCaches.size())
778 mSpecCaches.erase(mSpecCaches.begin() + index);
779 if (index < mSpecPxCaches.size())
780 mSpecPxCaches.erase(mSpecPxCaches.begin() + index);
781 }