169 void prepare(
double sampleRate,
int windowSize = 0,
int hopSize = 0)
171 if (!std::isfinite(sampleRate) || sampleRate <= 0.0)
176 sampleRate_ = sampleRate;
184 const double target = sampleRate_ * (kAutoSpanRef / kAutoSpanRate);
185 int n = kAutoMinWindow;
186 while (n < kAutoMaxWindow &&
static_cast<double>(n) < target) n <<= 1;
191 windowSize_ = std::clamp(windowSize, 64, 1 << 20);
193 halfWindow_ = windowSize_ / 2;
194 hopSize_ = (hopSize <= 0) ? std::max(1, windowSize_ / 4)
195 : std::clamp(hopSize, 1, windowSize_);
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));
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));
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));
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);
247 fftClean_ = std::make_unique<FFTReal<T>>(
static_cast<size_t>(windowSize_) * 2);
250 samplesSinceLastDetect_ = 0;
252 frequency_.store(T(0), std::memory_order_relaxed);
253 confidence_.store(T(0), std::memory_order_relaxed);
255 fft_ = std::make_unique<FFTReal<T>>(
static_cast<size_t>(fftSize_));
291 for (
const T sample : samples)
294 buffer_[
static_cast<size_t>(writePos_)] = sample;
295 buffer_[
static_cast<size_t>(writePos_ + historySize_)] = sample;
298 if (clearPending_ <= historySize_) ++clearPending_;
301 if (writePos_ >= historySize_)
306 samplesSinceLastDetect_++;
307 if (samplesSinceLastDetect_ >= hopSize_)
310 samplesSinceLastDetect_ = 0;
318 return frequency_.load(std::memory_order_relaxed);
332 return confidence_.load(std::memory_order_relaxed);
339 if (freq <= T(0))
return -1;
340 return static_cast<int>(std::round(T(69) + T(12) * std::log2(freq / T(440))));
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);
364 if (!std::isfinite(threshold))
return;
365 threshold_.store(std::clamp(threshold, T(0.01), T(0.5)), std::memory_order_relaxed);
371 return threshold_.load(std::memory_order_relaxed);
425 noiseSuppression_.store(on, std::memory_order_relaxed);
431 return noiseSuppression_.load(std::memory_order_relaxed);
445 [[nodiscard]]
int getHopSize() const noexcept {
return hopSize_; }
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;
458 samplesSinceLastDetect_ = 0;
459 frequency_.store(T(0), std::memory_order_relaxed);
460 confidence_.store(T(0), std::memory_order_relaxed);
464 void detect() noexcept
469 const T* history = &buffer_[
static_cast<size_t>(writePos_)];
470 const T* currentWindow = history + (historySize_ - windowSize_);
472 T energy = T(0), e1 = T(0);
473 if (!differenceFunction(currentWindow, yinBuffer_.data(), rawDiff_.data(), energy, e1))
475 rememberCandidate(0.0);
482 const double lowShare = lowBandPower_ /
static_cast<double>(energy);
483 const double subShare = subBandPower_ /
static_cast<double>(energy);
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;
489 const bool suppressing = noiseSuppression_.load(std::memory_order_relaxed);
492 const bool noteGoesOn = lastNote_ > 0.0 && sinceNote_ <= kNoteGaps;
510 if (reading.voiced && reading.dip >=
static_cast<double>(threshold))
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)
519 reading.voiced = periodPersists(history, period, contrast);
520 if (reading.voiced && offset == 0)
522 reading.voiced = hasGround(history, period, noteGoesOn, reach);
523 if (!reading.voiced) secondCandidate = period;
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;
551 if (!reading.voiced && lowShare >= 0.5 * kRumbleShare)
553 const T* clear = clearHistory();
554 const T* clearWindow = clear + (historySize_ - 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))
561 yinBuffer_.swap(yinClear_);
562 rawDiff_.swap(rawClear_);
563 WindowReading second = readWindow(clearWindow, clearEnergy, clearFirst, threshold);
571 if (second.voiced && second.dip >=
static_cast<double>(threshold))
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);
579 if (second.voiced || second.dip < reading.dip)
583 currentWindow = clearWindow;
587 yinBuffer_.swap(yinClear_);
588 rawDiff_.swap(rawClear_);
593 const int tauEstimate = reading.tau;
594 const double dip = reading.dip;
595 const bool steady = reading.steady;
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)));
624 double candidate = 0.0;
625 if (suppressing && steady && dip < kFallbackCeiling && (noteGoesOn || subShare <= kRumbleBound))
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))
632 int unused[kMaxPartials];
634 const int tau = chooseDip(yinClean_.data(), unused, numUnused);
635 if (tau >= 0 && yinClean_[
static_cast<size_t>(tau)] < threshold)
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))
644 if (agreesWithRecent(period))
646 rememberCandidate(period);
647 publish(
static_cast<T
>(period),
648 std::clamp(T(1) - yinBuffer_[
static_cast<size_t>(lag)], T(0), T(1)));
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))
669 const double period = refineByMultiples(history, own);
670 double contrast = 0.0;
671 if (periodPersists(history, period, contrast)
672 && contrast >= kMinFallbackContrast && contrast <= kMaxFallbackContrast)
674 if (candidate == 0.0) candidate = period;
675 const bool starts = noteGoesOn || persistMultiples_ < kMaxMultiple
676 || persistRatio_ >= kOwnStartRatio;
677 if (starts && agreesWithRecent(period))
679 rememberCandidate(period);
680 publish(
static_cast<T
>(period),
681 std::clamp(T(1) - yinBuffer_[
static_cast<size_t>(tauEstimate)], T(0), T(1)));
693 if (!suppressing && secondCandidate == 0.0 && steady && tauEstimate >= 0 && dip < kFallbackCeiling)
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;
701 rememberCandidate(candidate > 0.0 ? candidate : secondCandidate);
734 [[nodiscard]] WindowReading readWindow(
const T* window, T energy, T e1, T threshold)
noexcept
736 int partial[kMaxPartials];
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)));
765 [[nodiscard]]
const T* clearHistory() noexcept
767 const T* raw = &buffer_[
static_cast<size_t>(writePos_)];
768 if (clearPending_ > historySize_)
770 for (RumbleSection& section : rumble_) section.s1 = section.s2 = 0.0;
771 clearPending_ = historySize_;
773 const double limit =
static_cast<double>(std::numeric_limits<T>::max());
774 for (
int k = historySize_ - clearPending_; k < historySize_; ++k)
776 double v =
static_cast<double>(raw[k]);
777 for (RumbleSection& section : rumble_)
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;
784 if (!(std::abs(v) <= limit))
786 for (RumbleSection& section : rumble_) section.s1 = section.s2 = 0.0;
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);
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_)];
803 void designRumbleFilter() noexcept
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)
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;
830 void rememberCandidate(
double period)
noexcept
832 for (
size_t i = recent_.size() - 1; i > 0; --i) recent_[i] = recent_[i - 1];
849 [[nodiscard]]
bool agreesWithRecent(
double period)
const noexcept
852 for (
int i = 0; i < kRecentCandidates; ++i)
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;
857 return agree >= kAgreementsNeeded;
876 [[nodiscard]]
bool hasGround(
const T* history,
double period,
bool noteGoesOn,
double reachCents)
noexcept
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;
887 void publish(T period, T confidence)
noexcept
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);
895 void publishUnvoiced() noexcept
897 frequency_.store(T(0), std::memory_order_relaxed);
898 confidence_.store(T(0), std::memory_order_relaxed);
899 if (sinceNote_ <= kNoteGaps) ++sinceNote_;
914 bool differenceFunction(
const T* window, T* yin, T* raw, T& energy, T& e1)
noexcept
916 const int W = halfWindow_;
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];
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)];
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());
939 std::copy(window, window + windowSize_, fftTime_.begin());
940 fft_->forward(fftTime_.data(), specFull_.data());
947 const int lowBins = std::min(3, fftSize_ / 2 + 1);
948 for (
int k = 0; k < lowBins; ++k)
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);
954 lowBandPower_ = low /
static_cast<double>(fftSize_);
957 for (
int k = 0; k < std::min(2, lowBins); ++k)
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);
963 subBandPower_ = sub /
static_cast<double>(fftSize_);
966 const int numBins = fftSize_ / 2 + 1;
967 for (
int k = 0; k < numBins; ++k)
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)];
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;
977 fft_->inverse(specFull_.data(), corrTime_.data());
984 for (
int tau = 1; tau < W; ++tau)
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);
992 yin[tau] = (runningSum > T(0)) ? d *
static_cast<T
>(tau) / runningSum : T(1);
1047 [[nodiscard]]
int chooseDip(
const T* c,
int* partial,
int& numPartial)
noexcept
1049 const int W = halfWindow_;
1050 DipRecord* rec = dipRecords_.data();
1051 const int capacity =
static_cast<int>(dipRecords_.size());
1052 DipGroup* groups = dipGroups_.data();
1054 double passing = 0.0;
1055 int count = 0, leader = -1;
1056 double leaderMass = -1.0, recordValue = 1.0, recordSurvival = 0.0;
1057 T screen = T(1) + kScreenSlack;
1059 T stopLevel = std::numeric_limits<T>::infinity();
1061 for (
int tau = 2; tau + 1 < W; ++tau)
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)))
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];
1077 r.mass = s - recordSurvival;
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)
1094 passing -= groups[numGroups].mass;
1095 first = groups[numGroups].first;
1101 int lo = first, hi = count;
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;
1108 const auto upperSum = [&](
int i)
noexcept {
return (i <= 1) ? 0.0 : rec[i - 1].prefix; };
1109 DipGroup& g = groups[numGroups++];
1111 g.gate = prev.barrier;
1112 g.mass =
static_cast<double>(lo - first) * prev.barrierSurvival
1113 - (upperSum(lo) - upperSum(first));
1115 prev.mass -= passing;
1117 if (prev.mass > leaderMass) { leaderMass = prev.mass; leader = count - 1; }
1119 r.prefix = (count == 0) ? 0.0 : rec[count - 1].prefix + rec[count - 1].survival;
1123 if (v < kPartialLevel && numPartial < kMaxPartials) partial[numPartial++] = tau;
1124 screen =
static_cast<T
>(v) + kScreenSlack;
1126 stopLevel = settledAbove(r.mass, s, leaderMass);
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;
1134 const double value = rec[chosen].value;
1135 if (value >
static_cast<double>(cachedThreshold_))
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)
1145 return rec[chosen].lag;
1163 [[nodiscard]] T settledAbove(
double mass,
double survival,
double leaderMass)
const noexcept
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);
1176 int lo = 0, hi = kSurvivalSteps;
1179 const int mid = (lo + hi) / 2;
1180 if (survivalTable_[
static_cast<size_t>(mid)] > target) lo = mid + 1;
else hi = mid;
1182 return static_cast<T
>(
static_cast<double>(lo) /
static_cast<double>(kSurvivalSteps));
1199 const T* suppressNoise(
const T* window)
noexcept
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)
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;
1211 const int bands = (bins + kFloorBins - 1) / kFloorBins;
1212 for (
int b = 0; b < bands; ++b)
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);
1220 for (
int k = 0; k < bins; ++k)
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;
1234 fftClean_->inverse(cleanSpec_.data(), cleanTime_.data());
1235 return cleanTime_.data();
1254 [[nodiscard]]
bool sharesItsPeriod(
const T* x,
int tau,
const int* partial,
int count)
const noexcept
1256 const int W = halfWindow_;
1257 const int H = W / 2;
1258 for (
int r = 0; r < count; ++r)
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)
1265 double part[2] = { 0.0, 0.0 };
1266 for (
int h = 0; h < 2; ++h)
1268 double diff = 0.0, power = 0.0;
1269 for (
int j = h * H; j < (h + 1) * H; ++j)
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;
1275 part[h] = power > 0.0 ? diff / power : 1.0;
1277 if (std::min(part[0], part[1]) < kStationaryRatio * std::max(part[0], part[1]))
1287 [[nodiscard]]
int inputDipNear(
int tau)
const noexcept
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;
1304 void historyEnergy(
const T* history)
noexcept
1306 if (historySumsReady_)
return;
1307 historySumsReady_ =
true;
1310 double* sq = persistSq_.data();
1313 for (
int i = 0; i < historySize_; i += 4)
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;
1331 [[nodiscard]]
double historyCorrelation(
const T* x,
int lag,
int span,
int offset = 0) const noexcept
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;
1363 [[nodiscard]]
double refineByMultiples(
const T* x,
double period)
noexcept
1365 if (!(period >= 2.0))
return period;
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)
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;
1382 const int step = std::max(1, reach / kSearchStepDivisor);
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;
1388 for (
int j = 0; j < count; j += step) evaluate(j);
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);
1395 double peak =
static_cast<double>(centre - reach + best);
1396 if (best > 0 && best + 1 < count)
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);
1402 const double w =
static_cast<double>(k) *
static_cast<double>(k);
1403 weighted += w * peak /
static_cast<double>(k);
1405 estimate = weighted / weight;
1441 [[nodiscard]]
bool periodPersists(
const T* history,
double period,
double& contrast,
int offset = 0) noexcept
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;
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));
1465 const double first = periodic(1);
1467 if (!(first > 0.0))
return false;
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);
1480 [[nodiscard]]
int windowTestOffset(
double period)
const noexcept
1482 const int reach =
static_cast<int>(std::lround(2.5 * period)) + 2;
1483 return (windowSize_ - reach >= windowSize_ / 8) ? historySize_ - windowSize_ : 0;
1499 [[nodiscard]] T parabolicInterp(
const T* raw,
int tau)
const noexcept
1501 if (tau < 2 || tau >= halfWindow_ - 1)
1502 return static_cast<T
>(tau);
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);
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]);
1515 const double denom = s0 - 2.0 * s1 + s2;
1518 if (!(denom > 1e-30))
1519 return static_cast<T
>(tau);
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);
1533 [[nodiscard]]
double exactSurvival(
double x)
const noexcept
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);
1549 [[nodiscard]]
double priorSurvival(
double x)
const noexcept
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];
1569 void updatePrior(T threshold)
noexcept
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)
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);
1581 double lo = 0.0, hi = 1.0;
1582 for (
int i = 0; i < 48; ++i)
1584 const double mid = 0.5 * (lo + hi);
1585 if (exactSurvival(mid) > kVoicedSurvival) lo = mid;
else hi = mid;
1587 voicingCeiling_ = std::min(lo, kMaxVoicingCeiling);
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;
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;
1708 double sampleRate_ = 44100.0;
1709 int windowSize_ = 2048;
1710 int historySize_ = 4096;
1711 int halfWindow_ = 1024;
1714 int samplesSinceLastDetect_ = 0;
1715 std::atomic<T> threshold_{ T(0.10) };
1718 T cachedThreshold_ = T(-1);
1719 double priorB_ = 18.0;
1720 double voicingCeiling_ = 0.0;
1721 std::vector<double> survivalTable_;
1722 std::vector<double> survivalSlope_;
1725 std::atomic<T> frequency_{T(0)};
1726 std::atomic<T> confidence_{T(0)};
1729 std::vector<T> buffer_;
1730 std::vector<T> yinBuffer_;
1731 std::vector<T> rawDiff_;
1734 struct RumbleSection
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;
1739 std::array<RumbleSection, kRumbleSections> rumble_ {};
1740 std::vector<T> clearBuffer_;
1741 int clearPending_ = 0;
1742 double lowBandPower_ = 0.0;
1743 double subBandPower_ = 0.0;
1744 std::vector<T> yinClear_;
1745 std::vector<T> rawClear_;
1748 int fftSize_ = 2048;
1749 std::unique_ptr<FFTReal<T>> fft_;
1750 std::vector<T> fftTime_;
1751 std::vector<T> specHalf_;
1752 std::vector<T> specFull_;
1753 std::vector<T> corrTime_;
1754 std::vector<T> prefixSq_;
1757 std::atomic<bool> noiseSuppression_{
true };
1758 std::unique_ptr<FFTReal<T>> fftClean_;
1759 std::vector<T> cleanTime_;
1760 std::vector<T> cleanSpec_;
1761 std::vector<T> cleanPower_;
1762 std::vector<T> cleanFloor_;
1763 std::vector<T> cleanScratch_;
1764 std::vector<T> yinClean_;
1765 std::vector<T> rawClean_;
1766 std::vector<double> persistSq_;
1767 bool historySumsReady_ =
false;
1768 std::vector<double> multipleScratch_;
1774 double value = 0.0, survival = 0.0;
1775 double barrier = 0.0, barrierSurvival = 0.0;
1777 double prefix = 0.0;
1779 std::vector<DipRecord> dipRecords_;
1787 std::vector<DipGroup> dipGroups_;
1788 std::array<double, kRecentCandidates> recent_ {};
1789 double lastNote_ = 0.0;
1791 double persistRatio_ = 0.0;
1792 int persistMultiples_ = 0;