DSPark 1.9.0
Header-only C++20 DSP for real-time and offline audio
Loading...
Searching...
No Matches
PitchDetector.h
1// DSPark - Professional Audio DSP Framework
2// Copyright (c) 2026 Cristian Moresi - MIT License
3
4#pragma once
5
93#include "../Core/DspMath.h"
94#include "../Core/FFT.h"
95#include "../Core/SimdOps.h"
96
97#include <algorithm>
98#include <array>
99#include <atomic>
100#include <cmath>
101#include <cstddef>
102#include <limits>
103#include <memory>
104#include <span>
105#include <vector>
106
107namespace dspark {
108
120template <FloatType T>
122{
123public:
169 void prepare(double sampleRate, int windowSize = 0, int hopSize = 0)
170 {
171 if (!std::isfinite(sampleRate) || sampleRate <= 0.0)
172 return;
173
174 fft_.reset(); // gate OFF: pushSamples() is a no-op while rebuilding
175
176 sampleRate_ = sampleRate;
177 if (windowSize <= 0)
178 {
179 // Automatic: hold the analysis TIME SPAN constant across sample
180 // rates (the span 2048 samples cover at 48 kHz). The reachable
181 // register is fs/(windowSize/2 - 1), so a constant span pins the
182 // lowest detectable fundamental instead of letting it climb with
183 // the rate.
184 const double target = sampleRate_ * (kAutoSpanRef / kAutoSpanRate);
185 int n = kAutoMinWindow;
186 while (n < kAutoMaxWindow && static_cast<double>(n) < target) n <<= 1;
187 windowSize_ = n;
188 }
189 else
190 {
191 windowSize_ = std::clamp(windowSize, 64, 1 << 20);
192 }
193 halfWindow_ = windowSize_ / 2;
194 hopSize_ = (hopSize <= 0) ? std::max(1, windowSize_ / 4)
195 : std::clamp(hopSize, 1, windowSize_);
196
197 // Mirrored buffer technique: the last kHistoryWindows windows of
198 // input, written twice, so the analysis window (the newest of them)
199 // and the whole history are both contiguous without modulo
200 // operations. The history is read by the looks a noisy window gets
201 // (the persistence tests and the noise suppression), for periods
202 // whose multiples the window cannot hold.
203 historySize_ = windowSize_ * kHistoryWindows;
204 buffer_.assign(static_cast<size_t>(historySize_) * 2, T(0));
205 clearBuffer_.assign(static_cast<size_t>(historySize_) * 2, T(0));
206 clearPending_ = 0;
207 designRumbleFilter();
208 yinBuffer_.assign(static_cast<size_t>(halfWindow_), T(0));
209 rawDiff_.assign(static_cast<size_t>(halfWindow_), T(0));
210 yinClear_.assign(static_cast<size_t>(halfWindow_), T(0));
211 rawClear_.assign(static_cast<size_t>(halfWindow_), T(0));
212
213 // YIN-FFT resources: the difference function is computed via one
214 // cross-correlation in the frequency domain (3 FFTs) instead of the
215 // O(windowSize^2) direct form - ~20x faster at the default window.
216 // A frame of windowSize is enough: the first half against the whole
217 // window at lags below windowSize/2 reaches at most sample
218 // windowSize - 2, so nothing wraps around.
219 fftSize_ = 1;
220 while (fftSize_ < windowSize_) fftSize_ <<= 1;
221 fftTime_.assign(static_cast<size_t>(fftSize_), T(0));
222 specHalf_.assign(static_cast<size_t>(fftSize_) + 2, T(0));
223 specFull_.assign(static_cast<size_t>(fftSize_) + 2, T(0));
224 corrTime_.assign(static_cast<size_t>(fftSize_), T(0));
225 prefixSq_.assign(static_cast<size_t>(windowSize_) + 1, T(0));
226
227 // Noise floor suppression (setNoiseSuppression()): allocated whether
228 // or not it is on, so switching it is real-time safe.
229 cleanTime_.assign(static_cast<size_t>(windowSize_) * 2, T(0));
230 cleanSpec_.assign(static_cast<size_t>(windowSize_) * 2 + 2, T(0));
231 cleanPower_.assign(static_cast<size_t>(windowSize_) + 1, T(0));
232 cleanFloor_.assign(static_cast<size_t>((windowSize_ + kFloorBins) / kFloorBins), T(0));
233 cleanScratch_.assign(static_cast<size_t>(kFloorBins), T(0));
234 yinClean_.assign(static_cast<size_t>(halfWindow_), T(0));
235 rawClean_.assign(static_cast<size_t>(halfWindow_), T(0));
236 persistSq_.assign(static_cast<size_t>(historySize_) + 1, 0.0);
237 const int multipleReach = static_cast<int>(std::ceil(kMultipleSearch * historySize_)) + 2;
238 multipleScratch_.assign(static_cast<size_t>(2 * multipleReach + 1), 0.0);
239 dipRecords_.assign(static_cast<size_t>(halfWindow_ / 2 + 2), DipRecord {});
240 dipGroups_.assign(dipRecords_.size(), DipGroup {});
241 survivalTable_.assign(static_cast<size_t>(kSurvivalSteps) + 1, 0.0);
242 survivalSlope_.assign(static_cast<size_t>(kSurvivalSteps) + 1, 0.0);
243 cachedThreshold_ = T(-1); // rebuild the prior tables at the first detection
244 recent_.fill(0.0);
245 lastNote_ = 0.0;
246 sinceNote_ = 0;
247 fftClean_ = std::make_unique<FFTReal<T>>(static_cast<size_t>(windowSize_) * 2);
248
249 writePos_ = 0;
250 samplesSinceLastDetect_ = 0;
251
252 frequency_.store(T(0), std::memory_order_relaxed);
253 confidence_.store(T(0), std::memory_order_relaxed);
254
255 fft_ = std::make_unique<FFTReal<T>>(static_cast<size_t>(fftSize_)); // gate ON, last
256 }
257
286 void pushSamples(std::span<const T> samples) noexcept
287 {
288 if (fft_ == nullptr)
289 return;
290
291 for (const T sample : samples)
292 {
293 // Write into mirrored buffer
294 buffer_[static_cast<size_t>(writePos_)] = sample;
295 buffer_[static_cast<size_t>(writePos_ + historySize_)] = sample;
296 // One more sample the rumble-free copy has not seen (the count
297 // saturates once the history no longer holds them all).
298 if (clearPending_ <= historySize_) ++clearPending_;
299
300 writePos_++;
301 if (writePos_ >= historySize_)
302 {
303 writePos_ = 0;
304 }
305
306 samplesSinceLastDetect_++;
307 if (samplesSinceLastDetect_ >= hopSize_)
308 {
309 detect();
310 samplesSinceLastDetect_ = 0;
311 }
312 }
313 }
314
316 [[nodiscard]] T getFrequencyHz() const noexcept
317 {
318 return frequency_.load(std::memory_order_relaxed);
319 }
320
330 [[nodiscard]] T getConfidence() const noexcept
331 {
332 return confidence_.load(std::memory_order_relaxed);
333 }
334
336 [[nodiscard]] int getMidiNote() const noexcept
337 {
338 const T freq = getFrequencyHz();
339 if (freq <= T(0)) return -1;
340 return static_cast<int>(std::round(T(69) + T(12) * std::log2(freq / T(440))));
341 }
342
344 [[nodiscard]] T getCentsOffset() const noexcept
345 {
346 const T freq = getFrequencyHz();
347 if (freq <= T(0)) return T(0);
348 T midiExact = T(69) + T(12) * std::log2(freq / T(440));
349 return (midiExact - std::round(midiExact)) * T(100);
350 }
351
362 void setThreshold(T threshold) noexcept
363 {
364 if (!std::isfinite(threshold)) return;
365 threshold_.store(std::clamp(threshold, T(0.01), T(0.5)), std::memory_order_relaxed);
366 }
367
369 [[nodiscard]] T getThreshold() const noexcept
370 {
371 return threshold_.load(std::memory_order_relaxed);
372 }
373
423 void setNoiseSuppression(bool on) noexcept
424 {
425 noiseSuppression_.store(on, std::memory_order_relaxed);
426 }
427
429 [[nodiscard]] bool getNoiseSuppression() const noexcept
430 {
431 return noiseSuppression_.load(std::memory_order_relaxed);
432 }
433
441 [[nodiscard]] int getWindowSize() const noexcept { return windowSize_; }
442
445 [[nodiscard]] int getHopSize() const noexcept { return hopSize_; }
446
448 void reset() noexcept
449 {
450 std::fill(buffer_.begin(), buffer_.end(), T(0));
451 std::fill(clearBuffer_.begin(), clearBuffer_.end(), T(0));
452 for (RumbleSection& section : rumble_) section.s1 = section.s2 = 0.0;
453 clearPending_ = 0;
454 recent_.fill(0.0);
455 lastNote_ = 0.0;
456 sinceNote_ = 0;
457 writePos_ = 0;
458 samplesSinceLastDetect_ = 0;
459 frequency_.store(T(0), std::memory_order_relaxed);
460 confidence_.store(T(0), std::memory_order_relaxed);
461 }
462
463private:
464 void detect() noexcept
465 {
466 // Obtain a perfectly contiguous block of memory representing the current window.
467 // writePos_ points to the oldest sample of the history in the mirrored
468 // buffer; the window is its newest windowSize_ samples.
469 const T* history = &buffer_[static_cast<size_t>(writePos_)];
470 const T* currentWindow = history + (historySize_ - windowSize_);
471
472 T energy = T(0), e1 = T(0);
473 if (!differenceFunction(currentWindow, yinBuffer_.data(), rawDiff_.data(), energy, e1))
474 {
475 rememberCandidate(0.0);
476 publishUnvoiced();
477 return;
478 }
479
480 // Share of the window's power in the three lowest bins of its
481 // spectrum, which reach up to the lowest note the window can hold.
482 const double lowShare = lowBandPower_ / static_cast<double>(energy);
483 const double subShare = subBandPower_ / static_cast<double>(energy);
484
485 const T threshold = threshold_.load(std::memory_order_relaxed);
486 if (threshold != cachedThreshold_) updatePrior(threshold);
487 WindowReading reading = readWindow(currentWindow, energy, e1, threshold);
488 double secondCandidate = 0.0; // period a look found and could not confirm
489 const bool suppressing = noiseSuppression_.load(std::memory_order_relaxed);
490 // A note a detection reported up to kNoteGaps detections ago goes on:
491 // the window may still hold part of it, or a glide away from it.
492 const bool noteGoesOn = lastNote_ > 0.0 && sinceNote_ <= kNoteGaps;
493 // A dip above the threshold is all a narrow band of noise or slow
494 // wander needs to read as a note: a Q 5 band of noise at 1 kHz read
495 // in 3.9% of its windows, a Q 2 band at 120 Hz in 4.1%, brown noise
496 // in 0.75%. A tone repeats at every multiple of its period, so such
497 // a dip must do so too (periodPersists()). Where the window is mostly
498 // below its lowest note (kSubRumbleShare of its power in the two
499 // lowest bins) the test runs over the whole history, as it always
500 // did; elsewhere over the window itself when it holds two multiples,
501 // and while a note goes on it passes from kGoingOnRatio, since a
502 // glide or a wide vibrato blurs the far multiples.
503 //
504 // The dip also needs a ground (hasGround()): the detections before
505 // it agree, it continues the note, or the input grew. With a note
506 // going on, a period short enough for the window test reads wherever
507 // it lies (a legato change is read at once); a longer one, whose
508 // estimate over two or three periods is coarse, only near the note.
509 // A period refused is this detection's candidate for the next ones.
510 if (reading.voiced && reading.dip >= static_cast<double>(threshold))
511 {
512 historySumsReady_ = false;
513 double contrast = 0.0;
514 const double period = static_cast<double>(parabolicInterp(rawDiff_.data(), reading.tau));
515 const int offset = windowTestOffset(period);
516 const double reach = suppressing ? kLongReachCents : kLongReachOffCents;
517 if (subShare >= kSubRumbleShare)
518 {
519 reading.voiced = periodPersists(history, period, contrast);
520 if (reading.voiced && offset == 0)
521 {
522 reading.voiced = hasGround(history, period, noteGoesOn, reach);
523 if (!reading.voiced) secondCandidate = period;
524 }
525 }
526 else
527 {
528 const bool persists = offset == 0 || periodPersists(history, period, contrast, offset)
529 || (noteGoesOn && persistRatio_ >= kGoingOnRatio);
530 reading.voiced = persists
531 && ((offset > 0 && noteGoesOn) || hasGround(history, period, noteGoesOn, reach));
532 if (!reading.voiced) secondCandidate = period;
533 }
534 }
535
536 // A window that reads unvoiced is looked at once more without what
537 // lies below the lowest note it can hold. Rumble, hum's subharmonics
538 // and the bottom of pink or brown noise carry no period the detector
539 // could report, yet they fill the difference function at the long
540 // lags where low notes dip: 47 to 67 Hz tones in brown noise at 5 dB
541 // SNR read in 57% of their windows, and in 89% without that band.
542 // The look is taken only when the high-pass removes kRumbleShare of
543 // the window's power, and it stands only when it reads a note or dips
544 // deeper than the first (the filter also takes a little of a
545 // fundamental next to its corner): a clean tone or one in white noise
546 // is read as before. When it stands, everything after this point (the
547 // noise suppression included) works on the rumble-free
548 // history. The filter itself is only run when those lowest bins hold
549 // half that share or more, so a window with nothing down there (a
550 // consonant, hiss, a mid tone in white noise) costs nothing extra.
551 if (!reading.voiced && lowShare >= 0.5 * kRumbleShare)
552 {
553 const T* clear = clearHistory();
554 const T* clearWindow = clear + (historySize_ - windowSize_);
555 const double kept = static_cast<double>(simd::sumOfSquaresT(clearWindow, windowSize_));
556 T clearEnergy = T(0), clearFirst = T(0);
557 if (kept < (1.0 - kRumbleShare) * static_cast<double>(energy)
558 && differenceFunction(clearWindow, yinClear_.data(), rawClear_.data(), clearEnergy, clearFirst))
559 {
560 // readWindow() and the code below read yinBuffer_ and rawDiff_.
561 yinBuffer_.swap(yinClear_);
562 rawDiff_.swap(rawClear_);
563 WindowReading second = readWindow(clearWindow, clearEnergy, clearFirst, threshold);
564 // What the filter leaves of brown noise is a band just above
565 // its corner, and a band of noise dips like a low note. A
566 // tone repeats at every multiple of its period and holds it
567 // from one detection to the next; the band does neither. So
568 // a dip above the threshold must pass periodPersists() and
569 // agreesWithRecent() here, and a period that does not is
570 // remembered as this detection's candidate for the next.
571 if (second.voiced && second.dip >= static_cast<double>(threshold))
572 {
573 historySumsReady_ = false;
574 double contrast = 0.0;
575 const double period = static_cast<double>(parabolicInterp(rawDiff_.data(), second.tau));
576 secondCandidate = period;
577 second.voiced = periodPersists(clear, period, contrast) && agreesWithRecent(period);
578 }
579 if (second.voiced || second.dip < reading.dip)
580 {
581 reading = second;
582 history = clear;
583 currentWindow = clearWindow;
584 }
585 else
586 {
587 yinBuffer_.swap(yinClear_);
588 rawDiff_.swap(rawClear_);
589 }
590 }
591 }
592
593 const int tauEstimate = reading.tau;
594 const double dip = reading.dip;
595 const bool steady = reading.steady;
596 if (reading.voiced)
597 {
598 // Sub-sample precision from the raw difference function (see
599 // parabolicInterp()); the CMND only selects the dip.
600 const T period = parabolicInterp(rawDiff_.data(), tauEstimate);
601 rememberCandidate(static_cast<double>(period));
602 publish(period, std::clamp(T(1) - yinBuffer_[static_cast<size_t>(tauEstimate)], T(0), T(1)));
603 return;
604 }
605
606 // Noise floor suppression (on by default): a steady window that reads
607 // unvoiced is read again. Its noise removed, a dip of the cleaned
608 // window below the threshold locates the period, which is then taken
609 // from the input's own difference function next to it (the
610 // subtraction shifts the partials' peaks by a few hertz); when the
611 // cleaning finds none, the input's own dip is the candidate. Either
612 // is refined over its multiples (refineByMultiples()) and kept only
613 // when the input repeats at its multiples (periodPersists()) and the
614 // period agrees with recent detections (agreesWithRecent()). The
615 // confidence is the input's own dip there: a reading taken through
616 // the noise stays a low-confidence one (about 0.5 at 0 dB SNR).
617 //
618 // The suppression assumes a noise floor. A window with most of its
619 // power below its lowest note (kRumbleBound of it in the two lowest
620 // bins) is a slope instead, and what the high-pass leaves of it is a
621 // band just above the corner, which reads like a low note: brown
622 // noise alone read in 0.20% of its windows that way. There the read
623 // only continues a note.
624 double candidate = 0.0;
625 if (suppressing && steady && dip < kFallbackCeiling && (noteGoesOn || subShare <= kRumbleBound))
626 {
627 historySumsReady_ = false;
628 const T* clean = suppressNoise(currentWindow);
629 T cleanEnergy = T(0), cleanFirst = T(0);
630 if (differenceFunction(clean, yinClean_.data(), rawClean_.data(), cleanEnergy, cleanFirst))
631 {
632 int unused[kMaxPartials];
633 int numUnused = 0;
634 const int tau = chooseDip(yinClean_.data(), unused, numUnused);
635 if (tau >= 0 && yinClean_[static_cast<size_t>(tau)] < threshold)
636 {
637 const int lag = inputDipNear(tau);
638 const double period = refineByMultiples(history,
639 static_cast<double>(parabolicInterp(rawDiff_.data(), lag)));
640 double contrast = 0.0;
641 if (periodPersists(history, period, contrast))
642 {
643 candidate = period;
644 if (agreesWithRecent(period))
645 {
646 rememberCandidate(period);
647 publish(static_cast<T>(period),
648 std::clamp(T(1) - yinBuffer_[static_cast<size_t>(lag)], T(0), T(1)));
649 return;
650 }
651 }
652 }
653 }
654 // The input's own dip, where noise keeps the cleaned window from
655 // dipping below the threshold: low notes, whose partials crowd
656 // the floor estimate, and pink noise. Not a dip at the floor that
657 // noise alone reaches (kFallbackCeiling), nor a periodicity as
658 // weak as low-passed noise shows or as strong as a narrow band of
659 // noise makes (kMinFallbackContrast, kMaxFallbackContrast). And
660 // to start a note, a period tested over all kMaxMultiple
661 // multiples must have repeated at them almost as at the first
662 // (kOwnStartRatio): a tone does, while the Q 2 band of noise at
663 // 300 Hz that read in 0.09% of its windows this way stays below.
664 const double own = (tauEstimate >= 0)
665 ? static_cast<double>(parabolicInterp(rawDiff_.data(), tauEstimate)) : 0.0;
666 if (tauEstimate >= 0 && dip < kFallbackCeiling
667 && !(candidate > 0.0 && std::abs(own - candidate) < kSameCandidate * candidate))
668 {
669 const double period = refineByMultiples(history, own);
670 double contrast = 0.0;
671 if (periodPersists(history, period, contrast)
672 && contrast >= kMinFallbackContrast && contrast <= kMaxFallbackContrast)
673 {
674 if (candidate == 0.0) candidate = period;
675 const bool starts = noteGoesOn || persistMultiples_ < kMaxMultiple
676 || persistRatio_ >= kOwnStartRatio;
677 if (starts && agreesWithRecent(period))
678 {
679 rememberCandidate(period);
680 publish(static_cast<T>(period),
681 std::clamp(T(1) - yinBuffer_[static_cast<size_t>(tauEstimate)], T(0), T(1)));
682 return;
683 }
684 }
685 }
686 }
687 // With the suppression off nothing above leaves a candidate for a
688 // window that reads unvoiced, and a note in noise, whose dip hovers
689 // around the voicing ceiling, would find no agreement when it dips
690 // below again. Its own dip is the candidate then: as it is when the
691 // window could test it, and only when it repeats over the history
692 // when it is too long for that.
693 if (!suppressing && secondCandidate == 0.0 && steady && tauEstimate >= 0 && dip < kFallbackCeiling)
694 {
695 historySumsReady_ = false;
696 double contrast = 0.0;
697 const double period = static_cast<double>(parabolicInterp(rawDiff_.data(), tauEstimate));
698 if (windowTestOffset(period) > 0 || periodPersists(history, period, contrast))
699 secondCandidate = period;
700 }
701 rememberCandidate(candidate > 0.0 ? candidate : secondCandidate);
702 publishUnvoiced();
703 }
704
706 struct WindowReading
707 {
708 int tau = -1;
709 double dip = 1.0;
710 bool steady = false;
711 bool voiced = false;
712 };
713
734 [[nodiscard]] WindowReading readWindow(const T* window, T energy, T e1, T threshold) noexcept
735 {
736 int partial[kMaxPartials];
737 int numPartial = 0;
738 WindowReading reading;
739 reading.tau = chooseDip(yinBuffer_.data(), partial, numPartial);
740 reading.dip = (reading.tau < 0) ? 1.0
741 : static_cast<double>(yinBuffer_[static_cast<size_t>(reading.tau)]);
742 const double firstHalf = static_cast<double>(e1);
743 const double secondHalf = static_cast<double>(energy) - firstHalf;
744 reading.steady = std::min(firstHalf, secondHalf)
745 >= kMinHalfEnergyRatio * std::max(firstHalf, secondHalf);
746 reading.voiced = reading.tau >= 0 && reading.dip < voicingCeiling_
747 && (reading.dip < static_cast<double>(threshold)
748 || (reading.steady && !sharesItsPeriod(window, reading.tau, partial, numPartial)));
749 return reading;
750 }
751
765 [[nodiscard]] const T* clearHistory() noexcept
766 {
767 const T* raw = &buffer_[static_cast<size_t>(writePos_)];
768 if (clearPending_ > historySize_)
769 {
770 for (RumbleSection& section : rumble_) section.s1 = section.s2 = 0.0;
771 clearPending_ = historySize_;
772 }
773 const double limit = static_cast<double>(std::numeric_limits<T>::max());
774 for (int k = historySize_ - clearPending_; k < historySize_; ++k)
775 {
776 double v = static_cast<double>(raw[k]);
777 for (RumbleSection& section : rumble_)
778 {
779 const double y = section.b0 * v + section.s1;
780 section.s1 = section.b1 * v - section.a1 * y + section.s2;
781 section.s2 = section.b2 * v - section.a2 * y;
782 v = y;
783 }
784 if (!(std::abs(v) <= limit))
785 {
786 for (RumbleSection& section : rumble_) section.s1 = section.s2 = 0.0;
787 v = 0.0;
788 }
789 int position = writePos_ + k;
790 if (position >= historySize_) position -= historySize_;
791 clearBuffer_[static_cast<size_t>(position)] = static_cast<T>(v);
792 clearBuffer_[static_cast<size_t>(position + historySize_)] = static_cast<T>(v);
793 }
794 clearPending_ = 0;
795 // A state that has decayed to nothing is zero (no subnormal tail).
796 for (RumbleSection& section : rumble_)
797 if (std::abs(section.s1) < 1.0e-30 && std::abs(section.s2) < 1.0e-30)
798 section.s1 = section.s2 = 0.0;
799 return &clearBuffer_[static_cast<size_t>(writePos_)];
800 }
801
803 void designRumbleFilter() noexcept
804 {
805 // The lowest frequency the window reads: a period of halfWindow_ - 1.
806 const double lowest = sampleRate_ / static_cast<double>(std::max(2, halfWindow_ - 1));
807 const double corner = std::min(kRumbleCorner * lowest, 0.4 * sampleRate_);
808 const double w0 = 6.283185307179586 * corner / sampleRate_;
809 const double c = std::cos(w0), s = std::sin(w0);
810 for (int k = 0; k < kRumbleSections; ++k)
811 {
812 // Butterworth: the k-th pole pair of an order 2 * kRumbleSections.
813 const double q = 1.0 / (2.0 * std::cos(3.141592653589793 * (2.0 * k + 1.0)
814 / (4.0 * kRumbleSections)));
815 const double alpha = s / (2.0 * q), a0 = 1.0 + alpha;
816 RumbleSection& section = rumble_[static_cast<size_t>(k)];
817 section.b0 = 0.5 * (1.0 + c) / a0;
818 section.b1 = -2.0 * section.b0;
819 section.b2 = section.b0;
820 section.a1 = -2.0 * c / a0;
821 section.a2 = (1.0 - alpha) / a0;
822 section.s1 = section.s2 = 0.0;
823 }
824 }
825
830 void rememberCandidate(double period) noexcept
831 {
832 for (size_t i = recent_.size() - 1; i > 0; --i) recent_[i] = recent_[i - 1];
833 recent_[0] = period;
834 }
835
849 [[nodiscard]] bool agreesWithRecent(double period) const noexcept
850 {
851 int agree = 0;
852 for (int i = 0; i < kRecentCandidates; ++i)
853 {
854 const double p = recent_[static_cast<size_t>(i)];
855 if (p > 0.0 && std::abs(1200.0 * std::log2(period / p)) <= kAgreementCents * (i + 1)) ++agree;
856 }
857 return agree >= kAgreementsNeeded;
858 }
859
876 [[nodiscard]] bool hasGround(const T* history, double period, bool noteGoesOn, double reachCents) noexcept
877 {
878 if (agreesWithRecent(period)) return true;
879 if (noteGoesOn && std::abs(1200.0 * std::log2(period / lastNote_)) <= reachCents) return true;
880 historyEnergy(history);
881 const double* sq = persistSq_.data();
882 const int split = historySize_ - windowSize_;
883 const double older = sq[split] - sq[0], newer = sq[historySize_] - sq[split];
884 return older < kRiseRatio * newer;
885 }
886
887 void publish(T period, T confidence) noexcept
888 {
889 frequency_.store(static_cast<T>(sampleRate_) / period, std::memory_order_relaxed);
890 confidence_.store(confidence, std::memory_order_relaxed);
891 lastNote_ = static_cast<double>(period);
892 sinceNote_ = 0;
893 }
894
895 void publishUnvoiced() noexcept
896 {
897 frequency_.store(T(0), std::memory_order_relaxed);
898 confidence_.store(T(0), std::memory_order_relaxed);
899 if (sinceNote_ <= kNoteGaps) ++sinceNote_;
900 }
901
914 bool differenceFunction(const T* window, T* yin, T* raw, T& energy, T& e1) noexcept
915 {
916 const int W = halfWindow_;
917
918 // (a) prefix sums of squared samples over the full window
919 prefixSq_[0] = T(0);
920 for (int i = 0; i < windowSize_; ++i)
921 prefixSq_[static_cast<size_t>(i + 1)] =
922 prefixSq_[static_cast<size_t>(i)] + window[i] * window[i];
923
924 // Silence check on the window energy, the last prefix sum. It spans
925 // the whole window, so it doubles as the non-finite gate: with any
926 // NaN/Inf sample present the CMND would be all zeros ((NaN > 0) is
927 // false) and read fs/2 at confidence 1.0 - a fake detection with
928 // maximum confidence. Report unvoiced instead; the bad samples flush
929 // out of the window on their own.
930 energy = prefixSq_[static_cast<size_t>(windowSize_)];
931 if (energy < T(1e-10) || !std::isfinite(energy)) return false;
932 e1 = prefixSq_[static_cast<size_t>(W)];
933
934 // (b) r(tau) via FFT cross-correlation: IFFT(conj(FFT(first half)) * FFT(window))
935 std::copy(window, window + W, fftTime_.begin());
936 std::fill(fftTime_.begin() + W, fftTime_.end(), T(0));
937 fft_->forward(fftTime_.data(), specHalf_.data());
938
939 std::copy(window, window + windowSize_, fftTime_.begin());
940 fft_->forward(fftTime_.data(), specFull_.data()); // tail beyond the window is still zero
941
942 // Power of the window in its three lowest bins (detect() screens
943 // for rumble with it): bin spacing is half the lowest frequency the
944 // window reads, so they reach up to that note at any window size.
945 {
946 double low = 0.0;
947 const int lowBins = std::min(3, fftSize_ / 2 + 1);
948 for (int k = 0; k < lowBins; ++k)
949 {
950 const double re = static_cast<double>(specFull_[static_cast<size_t>(2 * k)]);
951 const double im = static_cast<double>(specFull_[static_cast<size_t>(2 * k + 1)]);
952 low += (k == 0 ? 1.0 : 2.0) * (re * re + im * im);
953 }
954 lowBandPower_ = low / static_cast<double>(fftSize_);
955 // The two lowest alone lie below every note the window reads.
956 double sub = 0.0;
957 for (int k = 0; k < std::min(2, lowBins); ++k)
958 {
959 const double re = static_cast<double>(specFull_[static_cast<size_t>(2 * k)]);
960 const double im = static_cast<double>(specFull_[static_cast<size_t>(2 * k + 1)]);
961 sub += (k == 0 ? 1.0 : 2.0) * (re * re + im * im);
962 }
963 subBandPower_ = sub / static_cast<double>(fftSize_);
964 }
965
966 const int numBins = fftSize_ / 2 + 1;
967 for (int k = 0; k < numBins; ++k)
968 {
969 const T aRe = specHalf_[static_cast<size_t>(2 * k)];
970 const T aIm = specHalf_[static_cast<size_t>(2 * k + 1)];
971 const T bRe = specFull_[static_cast<size_t>(2 * k)];
972 const T bIm = specFull_[static_cast<size_t>(2 * k + 1)];
973 // conj(A) * B
974 specFull_[static_cast<size_t>(2 * k)] = aRe * bRe + aIm * bIm;
975 specFull_[static_cast<size_t>(2 * k + 1)] = aRe * bIm - aIm * bRe;
976 }
977 fft_->inverse(specFull_.data(), corrTime_.data());
978
979 // (c) CMND from the closed-form difference function. While the
980 // running sum is zero the window has no energy at those lags, which
981 // is 0/0 and no evidence of a period, so it is the neutral 1.
982 yin[0] = T(1);
983 T runningSum = T(0);
984 for (int tau = 1; tau < W; ++tau)
985 {
986 const T e2 = prefixSq_[static_cast<size_t>(tau + W)] - prefixSq_[static_cast<size_t>(tau)];
987 T d = e1 + e2 - T(2) * corrTime_[static_cast<size_t>(tau)];
988 if (d < T(0)) d = T(0); // guard tiny negative round-off
989
990 raw[tau] = d;
991 runningSum += d;
992 yin[tau] = (runningSum > T(0)) ? d * static_cast<T>(tau) / runningSum : T(1);
993 }
994 return true;
995 }
996
1047 [[nodiscard]] int chooseDip(const T* c, int* partial, int& numPartial) noexcept
1048 {
1049 const int W = halfWindow_;
1050 DipRecord* rec = dipRecords_.data();
1051 const int capacity = static_cast<int>(dipRecords_.size());
1052 DipGroup* groups = dipGroups_.data();
1053 int numGroups = 0;
1054 double passing = 0.0; // prior mass that passes on to the newest record
1055 int count = 0, leader = -1;
1056 double leaderMass = -1.0, recordValue = 1.0, recordSurvival = 0.0;
1057 T screen = T(1) + kScreenSlack;
1058 T barrier = T(0); // highest CMND sample since the last record
1059 T stopLevel = std::numeric_limits<T>::infinity(); // settled once the barrier reaches it
1060 numPartial = 0;
1061 for (int tau = 2; tau + 1 < W; ++tau)
1062 {
1063 const T c0 = c[tau - 1], c1 = c[tau], c2 = c[tau + 1];
1064 barrier = std::max(barrier, c0);
1065 if (barrier >= stopLevel) break;
1066 if (!((c1 < c0) & (c1 <= c2) & (c1 - std::abs(c0 - c2) * T(0.125) < screen)))
1067 continue;
1068 const double d0 = static_cast<double>(c0), d1 = static_cast<double>(c1),
1069 d2 = static_cast<double>(c2);
1070 const double v = std::max(0.0, d1 - (d0 - d2) * (d0 - d2) / (8.0 * (d0 - 2.0 * d1 + d2)));
1071 if (!(v < recordValue) || count == capacity) continue;
1072 const double s = priorSurvival(v);
1073 DipRecord& r = rec[count];
1074 r.lag = tau;
1075 r.value = v;
1076 r.survival = s;
1077 r.mass = s - recordSurvival; // its own thresholds, (v, previous record]
1078 if (count > 0)
1079 {
1080 // The previous record's barrier is now known: every threshold
1081 // above it that reached that record passes on to this one.
1082 // Thresholds in (rec[i].value, rec[i - 1].value] first meet
1083 // record i and reach this one when they clear every barrier
1084 // from record i on. The records with the same highest such
1085 // barrier form a group on a stack, so each one is merged once
1086 // and the passing mass is a running total.
1087 DipRecord& prev = rec[count - 1];
1088 prev.barrier = static_cast<double>(barrier);
1089 prev.barrierSurvival = priorSurvival(prev.barrier);
1090 int first = count - 1;
1091 while (numGroups > 0 && groups[numGroups - 1].gate <= prev.barrier)
1092 {
1093 --numGroups;
1094 passing -= groups[numGroups].mass;
1095 first = groups[numGroups].first;
1096 }
1097 // Records first..count-1 now share this barrier; those whose
1098 // upper bound (the record before them, 1 for the first) lies
1099 // above it pass the thresholds in between. The bounds fall
1100 // with the index: find the first one at or below it.
1101 int lo = first, hi = count;
1102 while (lo < hi)
1103 {
1104 const int mid = (lo + hi) / 2;
1105 const double upper = (mid == 0) ? 1.0 : rec[mid - 1].value;
1106 if (upper > prev.barrier) lo = mid + 1; else hi = mid;
1107 }
1108 const auto upperSum = [&](int i) noexcept { return (i <= 1) ? 0.0 : rec[i - 1].prefix; };
1109 DipGroup& g = groups[numGroups++];
1110 g.first = first;
1111 g.gate = prev.barrier;
1112 g.mass = static_cast<double>(lo - first) * prev.barrierSurvival
1113 - (upperSum(lo) - upperSum(first));
1114 passing += g.mass;
1115 prev.mass -= passing;
1116 r.mass += passing;
1117 if (prev.mass > leaderMass) { leaderMass = prev.mass; leader = count - 1; }
1118 }
1119 r.prefix = (count == 0) ? 0.0 : rec[count - 1].prefix + rec[count - 1].survival;
1120 ++count;
1121 recordValue = v;
1122 recordSurvival = s;
1123 if (v < kPartialLevel && numPartial < kMaxPartials) partial[numPartial++] = tau;
1124 screen = static_cast<T>(v) + kScreenSlack;
1125 barrier = c1;
1126 stopLevel = settledAbove(r.mass, s, leaderMass);
1127 }
1128 if (count == 0) return -1;
1129 const DipRecord& last = rec[count - 1];
1130 const double lastMass = last.mass + kAbsoluteMinWeight * (1.0 - last.survival);
1131 int chosen = (lastMass > leaderMass) ? count - 1 : leader;
1132 // A choice above the threshold yields to the first separate dip
1133 // about as deep (see above).
1134 const double value = rec[chosen].value;
1135 if (value > static_cast<double>(cachedThreshold_))
1136 {
1137 const double limit = value + kMultipleMargin;
1138 for (int i = 0; i < chosen; ++i)
1139 if (rec[i].value <= limit && rec[i].barrier >= limit + kMultipleBarrier)
1140 {
1141 chosen = i;
1142 break;
1143 }
1144 }
1145 return rec[chosen].lag;
1146 }
1147
1163 [[nodiscard]] T settledAbove(double mass, double survival, double leaderMass) const noexcept
1164 {
1165 const double below = 1.0 - survival;
1166 const double future = (1.0 + kAbsoluteMinWeight) * below;
1167 const bool earlierLeads = leaderMass >= mass + kAbsoluteMinWeight * below;
1168 double target = earlierLeads ? leaderMass - future
1169 : std::min(mass - leaderMass, 0.5 * (mass - future));
1170 target -= kSettleMargin;
1171 if (!(target > 0.0)) return std::numeric_limits<T>::infinity();
1172 if (earlierLeads && mass <= target) return T(-1);
1173 // The first node of the survival table at or below the target (the
1174 // table holds the exact survival at its nodes, and it falls
1175 // monotonically).
1176 int lo = 0, hi = kSurvivalSteps;
1177 while (lo < hi)
1178 {
1179 const int mid = (lo + hi) / 2;
1180 if (survivalTable_[static_cast<size_t>(mid)] > target) lo = mid + 1; else hi = mid;
1181 }
1182 return static_cast<T>(static_cast<double>(lo) / static_cast<double>(kSurvivalSteps));
1183 }
1184
1199 const T* suppressNoise(const T* window) noexcept
1200 {
1201 const int n = windowSize_;
1202 std::copy(window, window + n, cleanTime_.begin());
1203 std::fill(cleanTime_.begin() + n, cleanTime_.end(), T(0));
1204 fftClean_->forward(cleanTime_.data(), cleanSpec_.data());
1205 const int bins = n + 1;
1206 for (int k = 0; k < bins; ++k)
1207 {
1208 const T re = cleanSpec_[static_cast<size_t>(2 * k)], im = cleanSpec_[static_cast<size_t>(2 * k + 1)];
1209 cleanPower_[static_cast<size_t>(k)] = re * re + im * im;
1210 }
1211 const int bands = (bins + kFloorBins - 1) / kFloorBins;
1212 for (int b = 0; b < bands; ++b)
1213 {
1214 const int lo = b * kFloorBins, hi = std::min(bins, lo + kFloorBins);
1215 std::copy(cleanPower_.begin() + lo, cleanPower_.begin() + hi, cleanScratch_.begin());
1216 const auto mid = cleanScratch_.begin() + (hi - lo) / 2;
1217 std::nth_element(cleanScratch_.begin(), mid, cleanScratch_.begin() + (hi - lo));
1218 cleanFloor_[static_cast<size_t>(b)] = *mid * T(1.4426950408889634); // / ln 2
1219 }
1220 for (int k = 0; k < bins; ++k)
1221 {
1222 // The band floors sit at the band centres; linear in between.
1223 const double u = (static_cast<double>(k) + 0.5) / kFloorBins - 0.5;
1224 const int b0 = std::clamp(static_cast<int>(std::floor(u)), 0, bands - 1);
1225 const int b1 = std::min(b0 + 1, bands - 1);
1226 const T frac = static_cast<T>(std::clamp(u - static_cast<double>(b0), 0.0, 1.0));
1227 const T floorK = cleanFloor_[static_cast<size_t>(b0)]
1228 + frac * (cleanFloor_[static_cast<size_t>(b1)] - cleanFloor_[static_cast<size_t>(b0)]);
1229 const T power = cleanPower_[static_cast<size_t>(k)];
1230 const T gain = power > T(0) ? std::max(T(0), T(1) - T(kOverSubtraction) * floorK / power) : T(0);
1231 cleanSpec_[static_cast<size_t>(2 * k)] *= gain;
1232 cleanSpec_[static_cast<size_t>(2 * k + 1)] *= gain;
1233 }
1234 fftClean_->inverse(cleanSpec_.data(), cleanTime_.data());
1235 return cleanTime_.data();
1236 }
1237
1254 [[nodiscard]] bool sharesItsPeriod(const T* x, int tau, const int* partial, int count) const noexcept
1255 {
1256 const int W = halfWindow_;
1257 const int H = W / 2;
1258 for (int r = 0; r < count; ++r)
1259 {
1260 const int lag = partial[r];
1261 if (lag >= tau) break;
1262 const int k = static_cast<int>(std::lround(static_cast<double>(tau) / static_cast<double>(lag)));
1263 if (k < 2 || std::abs(static_cast<double>(tau - k * lag)) > 0.02 * static_cast<double>(k * lag) + 1.0)
1264 continue;
1265 double part[2] = { 0.0, 0.0 };
1266 for (int h = 0; h < 2; ++h)
1267 {
1268 double diff = 0.0, power = 0.0;
1269 for (int j = h * H; j < (h + 1) * H; ++j)
1270 {
1271 const double a = static_cast<double>(x[j]), b = static_cast<double>(x[j + lag]);
1272 diff += (a - b) * (a - b);
1273 power += a * a + b * b;
1274 }
1275 part[h] = power > 0.0 ? diff / power : 1.0;
1276 }
1277 if (std::min(part[0], part[1]) < kStationaryRatio * std::max(part[0], part[1]))
1278 return true;
1279 }
1280 return false;
1281 }
1282
1287 [[nodiscard]] int inputDipNear(int tau) const noexcept
1288 {
1289 const T* raw = rawDiff_.data();
1290 const int lo = std::max(2, static_cast<int>(static_cast<double>(tau) * (1.0 - kRefineSpan)));
1291 const int hi = std::min(halfWindow_ - 2, static_cast<int>(static_cast<double>(tau) * (1.0 + kRefineSpan)) + 1);
1292 int best = std::clamp(tau, lo, hi);
1293 for (int t = lo; t <= hi; ++t)
1294 if (raw[t] < raw[best]) best = t;
1295 return best;
1296 }
1297
1304 void historyEnergy(const T* history) noexcept
1305 {
1306 if (historySumsReady_) return;
1307 historySumsReady_ = true;
1308 // Four samples at a time with one carry, so the running sum is not a
1309 // chain of dependent additions (historySize_ is a multiple of 4).
1310 double* sq = persistSq_.data();
1311 sq[0] = 0.0;
1312 double carry = 0.0;
1313 for (int i = 0; i < historySize_; i += 4)
1314 {
1315 const double a = static_cast<double>(history[i]) * static_cast<double>(history[i]);
1316 const double b = a + static_cast<double>(history[i + 1]) * static_cast<double>(history[i + 1]);
1317 const double c = b + static_cast<double>(history[i + 2]) * static_cast<double>(history[i + 2]);
1318 const double d = c + static_cast<double>(history[i + 3]) * static_cast<double>(history[i + 3]);
1319 sq[i + 1] = carry + a;
1320 sq[i + 2] = carry + b;
1321 sq[i + 3] = carry + c;
1322 sq[i + 4] = carry + d;
1323 carry += d;
1324 }
1325 }
1326
1331 [[nodiscard]] double historyCorrelation(const T* x, int lag, int span, int offset = 0) const noexcept
1332 {
1333 // sq[0] is zero at the start of the history, so with no offset this
1334 // is the sum it always was, to the last bit.
1335 const double* sq = persistSq_.data() + offset;
1336 const double e = sq[span] + sq[lag + span] - sq[lag] - sq[0];
1337 const double r = static_cast<double>(simd::dotProductT(x + offset, x + offset + lag, span));
1338 return e > 0.0 ? 2.0 * r / e : 0.0;
1339 }
1340
1363 [[nodiscard]] double refineByMultiples(const T* x, double period) noexcept
1364 {
1365 if (!(period >= 2.0)) return period;
1366 historyEnergy(x);
1367 const int n = historySize_;
1368 double weighted = period, weight = 1.0, estimate = period;
1369 double* values = multipleScratch_.data();
1370 const int capacity = static_cast<int>(multipleScratch_.size());
1371 for (int k = 2; k <= kRefineMultiples; ++k)
1372 {
1373 const int centre = static_cast<int>(std::lround(static_cast<double>(k) * estimate));
1374 const double search = static_cast<double>(k) * estimate * kMultipleSearch
1375 / static_cast<double>(std::max(1, k - 1));
1376 const int reach = std::max(2, static_cast<int>(std::ceil(search)));
1377 const int span = n - (centre + reach) - 1;
1378 const int count = 2 * reach + 1;
1379 if (span < windowSize_ / 8 || count > capacity) break;
1380 // Every step-th lag first, then every lag within a step of the
1381 // best of them: the peak near k periods is several lags wide.
1382 const int step = std::max(1, reach / kSearchStepDivisor);
1383 int best = -1;
1384 const auto evaluate = [&](int j) noexcept {
1385 values[j] = historyCorrelation(x, centre - reach + j, span);
1386 if (best < 0 || values[j] > values[best]) best = j;
1387 };
1388 for (int j = 0; j < count; j += step) evaluate(j);
1389 if (step > 1)
1390 {
1391 const int coarse = best;
1392 for (int j = std::max(0, coarse - step + 1); j <= std::min(count - 1, coarse + step - 1); ++j)
1393 if (j % step != 0) evaluate(j);
1394 }
1395 double peak = static_cast<double>(centre - reach + best);
1396 if (best > 0 && best + 1 < count)
1397 {
1398 const double a = values[best - 1], b = values[best], c = values[best + 1];
1399 const double curvature = a - 2.0 * b + c;
1400 if (curvature < -1e-30) peak += std::clamp(0.5 * (a - c) / curvature, -0.5, 0.5);
1401 }
1402 const double w = static_cast<double>(k) * static_cast<double>(k);
1403 weighted += w * peak / static_cast<double>(k);
1404 weight += w;
1405 estimate = weighted / weight;
1406 }
1407 return estimate;
1408 }
1409
1441 [[nodiscard]] bool periodPersists(const T* history, double period, double& contrast, int offset = 0) noexcept
1442 {
1443 contrast = 0.0;
1444 persistRatio_ = 0.0;
1445 persistMultiples_ = 0;
1446 historyEnergy(history);
1447 if (!(period >= 2.0)) return false;
1448 const auto reach = [&](int k) noexcept {
1449 return static_cast<int>(std::lround((static_cast<double>(k) + 0.5) * period)) + 2;
1450 };
1451 const int minSpan = windowSize_ / 8;
1452 const int n = historySize_ - offset;
1453 int kmax = kMaxMultiple;
1454 while (kmax >= 2 && n - reach(kmax) < minSpan) --kmax;
1455 if (kmax < 2) return false;
1456 persistMultiples_ = kmax;
1457 const int span = n - reach(kmax);
1458 const auto corr = [&](int lag) noexcept { return historyCorrelation(history, lag, span, offset); };
1459 const auto periodic = [&](int k) noexcept {
1460 const int c = static_cast<int>(std::lround(static_cast<double>(k) * period));
1461 const int h = static_cast<int>(std::lround(0.5 * period));
1462 const double peak = std::max({ corr(c - 1), corr(c), corr(c + 1) });
1463 return peak - 0.5 * (corr(c - h) + corr(c + h));
1464 };
1465 const double first = periodic(1);
1466 contrast = first;
1467 if (!(first > 0.0)) return false;
1468 double sum = 0.0;
1469 for (int k = 2; k <= kmax; ++k) sum += periodic(k);
1470 persistRatio_ = sum / (first * static_cast<double>(kmax - 1));
1471 return sum >= kPersistRatio * first * static_cast<double>(kmax - 1);
1472 }
1473
1480 [[nodiscard]] int windowTestOffset(double period) const noexcept
1481 {
1482 const int reach = static_cast<int>(std::lround(2.5 * period)) + 2;
1483 return (windowSize_ - reach >= windowSize_ / 8) ? historySize_ - windowSize_ : 0;
1484 }
1485
1499 [[nodiscard]] T parabolicInterp(const T* raw, int tau) const noexcept
1500 {
1501 if (tau < 2 || tau >= halfWindow_ - 1)
1502 return static_cast<T>(tau);
1503
1504 // Centre on the raw function's own lowest sample next to the CMND dip.
1505 const int centre = tau;
1506 if (raw[centre - 1] < raw[tau]) tau = centre - 1;
1507 if (raw[centre + 1] < raw[tau]) tau = centre + 1;
1508 if (tau < 2 || tau >= halfWindow_ - 1)
1509 return static_cast<T>(tau);
1510
1511 const double s0 = static_cast<double>(raw[tau - 1]);
1512 const double s1 = static_cast<double>(raw[tau]);
1513 const double s2 = static_cast<double>(raw[tau + 1]);
1514
1515 const double denom = s0 - 2.0 * s1 + s2;
1516
1517 // Flat or inverted curvature (no usable dip on the raw function).
1518 if (!(denom > 1e-30))
1519 return static_cast<T>(tau);
1520
1521 const double vertex = std::clamp((s0 - s2) / (2.0 * denom), -0.5, 0.5);
1522 const double w = 6.283185307179586 / static_cast<double>(tau);
1523 const double offset = std::atan(2.0 * vertex * std::tan(0.5 * w)) / w;
1524 return static_cast<T>(static_cast<double>(tau) + offset);
1525 }
1526
1533 [[nodiscard]] double exactSurvival(double x) const noexcept
1534 {
1535 if (!(x > 0.0)) return 1.0;
1536 if (!(x < 1.0)) return 0.0;
1537 return std::pow(1.0 - x, priorB_) * (1.0 + priorB_ * x);
1538 }
1539
1549 [[nodiscard]] double priorSurvival(double x) const noexcept
1550 {
1551 if (!(x > 0.0)) return 1.0;
1552 if (!(x < 1.0)) return 0.0;
1553 const double u = x * static_cast<double>(kSurvivalSteps);
1554 const int i = std::min(static_cast<int>(u), kSurvivalSteps - 1);
1555 const double t = u - static_cast<double>(i), h = 1.0 / static_cast<double>(kSurvivalSteps);
1556 const double* s = survivalTable_.data();
1557 const double* d = survivalSlope_.data();
1558 const double t2 = t * t, t3 = t2 * t;
1559 return (2.0 * t3 - 3.0 * t2 + 1.0) * s[i] + (t3 - 2.0 * t2 + t) * h * d[i]
1560 + (3.0 * t2 - 2.0 * t3) * s[i + 1] + (t3 - t2) * h * d[i + 1];
1561 }
1562
1569 void updatePrior(T threshold) noexcept
1570 {
1571 cachedThreshold_ = threshold;
1572 const double mean = static_cast<double>(threshold);
1573 priorB_ = 2.0 * (1.0 - mean) / mean;
1574 for (int i = 0; i <= kSurvivalSteps; ++i)
1575 {
1576 const double x = static_cast<double>(i) / static_cast<double>(kSurvivalSteps);
1577 survivalTable_[static_cast<size_t>(i)] = (i == 0) ? 1.0 : exactSurvival(x);
1578 survivalSlope_[static_cast<size_t>(i)] = (i == kSurvivalSteps) ? 0.0
1579 : -priorB_ * (priorB_ + 1.0) * x * std::pow(1.0 - x, priorB_ - 1.0);
1580 }
1581 double lo = 0.0, hi = 1.0; // survival falls monotonically from 1 to 0
1582 for (int i = 0; i < 48; ++i)
1583 {
1584 const double mid = 0.5 * (lo + hi);
1585 if (exactSurvival(mid) > kVoicedSurvival) lo = mid; else hi = mid;
1586 }
1587 voicingCeiling_ = std::min(lo, kMaxVoicingCeiling);
1588 }
1589
1591 static constexpr T kScreenSlack = T(1.0e-4);
1594 static constexpr double kAbsoluteMinWeight = 0.01;
1597 static constexpr double kVoicedSurvival = 1.0e-2;
1600 static constexpr double kMinHalfEnergyRatio = 0.6;
1603 static constexpr double kMaxVoicingCeiling = 0.5;
1606 static constexpr double kPartialLevel = 0.75;
1609 static constexpr double kStationaryRatio = 0.25;
1611 static constexpr int kMaxPartials = 16;
1614 static constexpr double kRefineSpan = 0.06;
1616 static constexpr int kMaxMultiple = 8;
1620 static constexpr double kPersistRatio = 0.6;
1622 static constexpr int kFloorBins = 32;
1624 static constexpr double kOverSubtraction = 2.0;
1626 static constexpr int kHistoryWindows = 2;
1629 static constexpr double kMultipleSearch = 0.03;
1631 static constexpr int kRefineMultiples = 4;
1633 static constexpr int kSearchStepDivisor = 16;
1636 static constexpr double kFallbackCeiling = 0.8;
1639 static constexpr double kSameCandidate = 0.02;
1643 static constexpr double kMinFallbackContrast = 0.35;
1644 static constexpr double kMaxFallbackContrast = 1.3;
1646 static constexpr int kRecentCandidates = 3;
1648 static constexpr int kAgreementsNeeded = 2;
1651 static constexpr double kAgreementCents = 25.0;
1653 static constexpr int kSurvivalSteps = 1024;
1655 static constexpr double kSettleMargin = 1.0e-9;
1660 static constexpr double kMultipleMargin = 0.15;
1661 static constexpr double kMultipleBarrier = 0.25;
1666 static constexpr int kRumbleSections = 3;
1667 static constexpr double kRumbleCorner = 0.9;
1668 static constexpr double kRumbleShare = 0.02;
1672 static constexpr double kSubRumbleShare = 0.10;
1675 static constexpr int kNoteGaps = 6;
1681 static constexpr double kGoingOnRatio = 0.3;
1685 static constexpr double kLongReachCents = 50.0;
1686 static constexpr double kLongReachOffCents = 100.0;
1689 static constexpr double kRiseRatio = 0.5;
1695 static constexpr double kRumbleBound = 0.5;
1699 static constexpr double kOwnStartRatio = 0.9;
1700
1703 static constexpr double kAutoSpanRef = 2048.0;
1704 static constexpr double kAutoSpanRate = 48000.0;
1705 static constexpr int kAutoMinWindow = 512;
1706 static constexpr int kAutoMaxWindow = 16384;
1707
1708 double sampleRate_ = 44100.0;
1709 int windowSize_ = 2048;
1710 int historySize_ = 4096;
1711 int halfWindow_ = 1024;
1712 int hopSize_ = 512;
1713 int writePos_ = 0;
1714 int samplesSinceLastDetect_ = 0;
1715 std::atomic<T> threshold_{ T(0.10) };
1716
1717 // Threshold prior as last built by updatePrior() (audio thread only).
1718 T cachedThreshold_ = T(-1);
1719 double priorB_ = 18.0;
1720 double voicingCeiling_ = 0.0;
1721 std::vector<double> survivalTable_; // Size: kSurvivalSteps + 1 (priorSurvival())
1722 std::vector<double> survivalSlope_; // Its derivative at the same nodes
1723
1724 // Thread-safe outputs
1725 std::atomic<T> frequency_{T(0)};
1726 std::atomic<T> confidence_{T(0)};
1727
1728 // Mirrored buffer keeps every analysis window contiguous
1729 std::vector<T> buffer_; // Size: 2 * historySize_
1730 std::vector<T> yinBuffer_; // Size: halfWindow_
1731 std::vector<T> rawDiff_; // Size: halfWindow_ (difference function d(tau))
1732
1733 // The history without rumble (clearHistory())
1734 struct RumbleSection
1735 {
1736 double b0 = 1.0, b1 = 0.0, b2 = 0.0, a1 = 0.0, a2 = 0.0;
1737 double s1 = 0.0, s2 = 0.0;
1738 };
1739 std::array<RumbleSection, kRumbleSections> rumble_ {};
1740 std::vector<T> clearBuffer_; // Size: 2 * historySize_, mirrored like buffer_
1741 int clearPending_ = 0; // Newest input samples not yet filtered into it
1742 double lowBandPower_ = 0.0; // Power in the three lowest bins of the last window transformed
1743 double subBandPower_ = 0.0; // Power in the two lowest of them
1744 std::vector<T> yinClear_; // Size: halfWindow_ (CMND of the rumble-free window)
1745 std::vector<T> rawClear_; // Size: halfWindow_ (its difference function)
1746
1747 // YIN-FFT resources (cross-correlation difference function)
1748 int fftSize_ = 2048;
1749 std::unique_ptr<FFTReal<T>> fft_; // doubles as the "prepared" gate
1750 std::vector<T> fftTime_; // Size: fftSize_
1751 std::vector<T> specHalf_; // Size: fftSize_ + 2
1752 std::vector<T> specFull_; // Size: fftSize_ + 2
1753 std::vector<T> corrTime_; // Size: fftSize_
1754 std::vector<T> prefixSq_; // Size: windowSize_ + 1
1755
1756 // Noise floor suppression (see suppressNoise())
1757 std::atomic<bool> noiseSuppression_{ true };
1758 std::unique_ptr<FFTReal<T>> fftClean_; // 2 * windowSize_
1759 std::vector<T> cleanTime_; // Size: 2 * windowSize_ (the cleaned window first)
1760 std::vector<T> cleanSpec_; // Size: 2 * windowSize_ + 2
1761 std::vector<T> cleanPower_; // Size: windowSize_ + 1
1762 std::vector<T> cleanFloor_; // One floor per band of kFloorBins bins
1763 std::vector<T> cleanScratch_; // Size: kFloorBins
1764 std::vector<T> yinClean_; // Size: halfWindow_
1765 std::vector<T> rawClean_; // Size: halfWindow_
1766 std::vector<double> persistSq_; // Size: historySize_ + 1 (historyEnergy())
1767 bool historySumsReady_ = false; // persistSq_ holds this detection's sums
1768 std::vector<double> multipleScratch_; // Correlations around one multiple (refineByMultiples())
1769
1771 struct DipRecord
1772 {
1773 int lag = 0;
1774 double value = 0.0, survival = 0.0;
1775 double barrier = 0.0, barrierSurvival = 0.0;
1776 double mass = 0.0;
1777 double prefix = 0.0;
1778 };
1779 std::vector<DipRecord> dipRecords_; // Size: halfWindow_ / 2 + 2 (chooseDip())
1781 struct DipGroup
1782 {
1783 int first = 0;
1784 double gate = 0.0;
1785 double mass = 0.0;
1786 };
1787 std::vector<DipGroup> dipGroups_; // Same size as dipRecords_ (chooseDip())
1788 std::array<double, kRecentCandidates> recent_ {}; // Last detections' periods (agreesWithRecent())
1789 double lastNote_ = 0.0; // Period of the last note a detection reported (0: none yet)
1790 int sinceNote_ = 0; // Detections since then, counted up to kNoteGaps + 1
1791 double persistRatio_ = 0.0; // periodPersists(): mean of the multiples over the first
1792 int persistMultiples_ = 0; // periodPersists(): highest multiple it used
1793};
1794
1795} // namespace dspark
Thread-safe YIN pitch detector with lock-free readout.
T getConfidence() const noexcept
Returns the detection confidence [0.0 - 1.0] safely from any thread.
T getFrequencyHz() const noexcept
Returns the detected frequency in Hz safely from any thread.
int getWindowSize() const noexcept
bool getNoiseSuppression() const noexcept
Whether noise floor suppression is on (setNoiseSuppression()).
void setNoiseSuppression(bool on) noexcept
Reads a tone through broadband noise (on by default).
int getMidiNote() const noexcept
Returns nearest MIDI note (69 = A4), or -1 if unvoiced.
void reset() noexcept
Resets state buffers. Not thread-safe with pushSamples().
void setThreshold(T threshold) noexcept
Sets the sensitivity threshold (clamped to 0.01 - 0.5; default 0.1).
void pushSamples(std::span< const T > samples) noexcept
Pushes audio samples into the analysis buffer.
int getHopSize() const noexcept
void prepare(double sampleRate, int windowSize=0, int hopSize=0)
Prepares the detector and allocates internal structures.
T getCentsOffset() const noexcept
Returns cent offset from the nearest MIDI note [-50, +50].
T getThreshold() const noexcept
Returns the sensitivity threshold.
T dotProductT(const T *DSPARK_RESTRICT a, const T *DSPARK_RESTRICT b, int count) noexcept
Definition SimdOps.h:1426
T sumOfSquaresT(const T *DSPARK_RESTRICT data, int count) noexcept
Definition SimdOps.h:1454
Main namespace for the DSPark framework.