144 detector_.prepare(spec.
sampleRate, windowSize,
145 (windowSize > 0) ? windowSize / 4 : 0);
146 monoScratch_.assign(
static_cast<size_t>(std::max(spec.
maxBlockSize, 1)), T(0));
148 prepared_.store(
true, std::memory_order_relaxed);
164 samplesSinceValid_ = std::numeric_limits<int64_t>::max() / 2;
165 smoothedHz_.store(T(0), std::memory_order_relaxed);
166 tracking_.store(
false, std::memory_order_relaxed);
167 voiced_.store(
false, std::memory_order_relaxed);
179 if (!std::isfinite(minHz) || !std::isfinite(maxHz))
return;
180 minHz = std::max(minHz, T(10));
181 maxHz = std::max(maxHz, minHz);
182 minHz_.store(minHz, std::memory_order_relaxed);
183 maxHz_.store(maxHz, std::memory_order_relaxed);
197 if (!std::isfinite(threshold))
return;
198 confidence_.store(std::clamp(threshold, T(0), T(1)), std::memory_order_relaxed);
208 if (!std::isfinite(msPerOctave))
return;
209 glideMs_.store(std::max(msPerOctave, T(0)), std::memory_order_relaxed);
213 [[nodiscard]] T
getMinHz() const noexcept {
return minHz_.load(std::memory_order_relaxed); }
216 [[nodiscard]] T
getMaxHz() const noexcept {
return maxHz_.load(std::memory_order_relaxed); }
222 [[nodiscard]] T
getGlide() const noexcept {
return glideMs_.load(std::memory_order_relaxed); }
228 [[nodiscard]]
int getWindowSize() const noexcept {
return detector_.getWindowSize(); }
249 return smoothedHz_.load(std::memory_order_relaxed);
253 [[nodiscard]] T
getRawHz() const noexcept {
return detector_.getFrequencyHz(); }
256 [[nodiscard]] T
getConfidence() const noexcept {
return detector_.getConfidence(); }
261 return tracking_.load(std::memory_order_relaxed);
271 return voiced_.load(std::memory_order_relaxed);
282 if (!prepared_.load(std::memory_order_relaxed))
return;
283 const int nCh = buffer.getNumChannels();
284 const int nS = buffer.getNumSamples();
285 if (nCh <= 0 || nS <= 0)
return;
290 const int chunk = std::min(nS - i,
static_cast<int>(monoScratch_.size()));
293 const T* src = buffer.getChannel(0) + i;
294 std::copy(src, src + chunk, monoScratch_.begin());
298 const T invCh = T(1) /
static_cast<T
>(nCh);
299 std::fill(monoScratch_.begin(), monoScratch_.begin() + chunk, T(0));
300 for (
int ch = 0; ch < nCh; ++ch)
302 const T* src = buffer.getChannel(ch) + i;
303 for (
int k = 0; k < chunk; ++k)
304 monoScratch_[
static_cast<size_t>(k)] += src[k] * invCh;
307 pushSamples({ monoScratch_.data(),
static_cast<size_t>(chunk) });
318 if (!prepared_.load(std::memory_order_relaxed) || samples.empty())
return;
322 const int hop = detector_.getHopSize();
323 std::size_t done = 0;
324 while (done < samples.size())
326 const auto chunk = std::min(samples.size() - done,
327 static_cast<std::size_t
>(hop - hopPhase_));
328 detector_.pushSamples(samples.subspan(done, chunk));
330 hopPhase_ +=
static_cast<int>(chunk);
331 const bool freshReading = hopPhase_ >= hop;
332 if (freshReading) hopPhase_ = 0;
333 update(
static_cast<int>(chunk), freshReading);
399 [[nodiscard]]
static std::vector<TrackPoint>
track(std::span<const T> mono,
double sampleRate,
402 std::vector<TrackPoint> points;
403 if (!std::isfinite(sampleRate) || sampleRate <= 0.0)
return points;
404 const double minHz =
static_cast<double>(settings.
minHz), maxHz =
static_cast<double>(settings.
maxHz);
405 if (!(std::isfinite(minHz) && std::isfinite(maxHz) && minHz > 0.0 && maxHz >= minHz))
return points;
410 const std::size_t window =
static_cast<std::size_t
>(std::max(detector.
getWindowSize(), 1));
411 const std::size_t hop =
static_cast<std::size_t
>(std::max(detector.
getHopSize(), 1));
412 if (mono.size() < window)
return points;
415 const std::size_t hops = mono.size() / hop;
416 std::vector<TrackReading> readings;
417 readings.reserve(hops);
418 points.reserve(hops);
419 for (std::size_t k = 0; k < hops; ++k)
422 const std::size_t end = (k + 1) * hop;
423 if (end < window)
continue;
425 TrackReading reading;
427 point.
seconds = (
static_cast<double>(end) - 0.5 *
static_cast<double>(window)) / sampleRate;
428 if (hz >= minHz && hz <= maxHz)
430 reading.voiced =
true;
431 reading.semitones = 12.0 * std::log2(hz / 440.0);
432 reading.confidence =
static_cast<double>(detector.
getConfidence());
435 readings.push_back(reading);
436 points.push_back(point);
438 decodeTrack(readings, 12.0 * std::log2(minHz / 440.0), 12.0 * std::log2(maxHz / 440.0), points);
447 [[nodiscard]]
static std::vector<TrackPoint>
track(std::span<const T> mono,
double sampleRate)
458 double semitones = 0.0;
459 double confidence = 0.0;
463 static constexpr int kTrackReach = 3;
464 static constexpr int kTrackCandidates = 4 + 2 * kTrackReach;
465 static constexpr double kTrackOwn = 4.0;
466 static constexpr double kTrackOctave = 1.0;
467 static constexpr double kTrackBorrowVoiced = 3.0;
468 static constexpr double kTrackBorrowSilent = 0.5;
469 static constexpr double kTrackBorrowStep = 0.5;
470 static constexpr double kTrackUnvoicedBase = 1.0;
471 static constexpr double kTrackUnvoicedConf = 4.0;
472 static constexpr double kTrackEdge = 0.5;
473 static constexpr double kTrackSwitch = 4.0;
474 static constexpr double kTrackPerSemitone = 1.0;
475 static constexpr double kTrackJumpCap = 6.0;
476 static constexpr double kTrackSame = 0.25;
477 static constexpr double kTrackLine = 2.0;
482 double semitones[kTrackCandidates] = {};
483 double cost[kTrackCandidates] = {};
484 std::uint8_t back[kTrackCandidates + 1] = {};
485 std::uint8_t count = 0;
486 double unvoicedCost = 0.0;
488 void add(
double st,
double c)
noexcept
490 for (
int i = 0; i < count; ++i)
491 if (std::abs(semitones[i] - st) < kTrackSame)
493 cost[i] = std::min(cost[i], c);
496 if (count < kTrackCandidates)
498 semitones[count] = st;
507 static void decodeTrack(
const std::vector<TrackReading>& readings,
double minSemitones,
double maxSemitones,
508 std::vector<TrackPoint>& points)
510 const std::ptrdiff_t total =
static_cast<std::ptrdiff_t
>(readings.size());
511 if (total == 0)
return;
512 const auto at = [&](std::ptrdiff_t k) ->
const TrackReading& {
return readings[
static_cast<std::size_t
>(k)]; };
514 std::vector<TrackFrame> frames(readings.size());
515 for (std::ptrdiff_t k = 0; k < total; ++k)
517 TrackFrame& frame = frames[
static_cast<std::size_t
>(k)];
518 const TrackReading& own = at(k);
521 const double cost = kTrackOwn * (1.0 - own.confidence);
522 frame.add(own.semitones, cost);
523 if (own.semitones - 12.0 >= minSemitones) frame.add(own.semitones - 12.0, cost + kTrackOctave);
524 if (own.semitones + 12.0 <= maxSemitones) frame.add(own.semitones + 12.0, cost + kTrackOctave);
525 frame.unvoicedCost = kTrackUnvoicedBase + kTrackUnvoicedConf * own.confidence;
527 else if (k + 1 < total && at(k + 1).voiced)
529 frame.unvoicedCost = kTrackEdge;
531 const double borrow = own.voiced ? kTrackBorrowVoiced : kTrackBorrowSilent;
532 std::ptrdiff_t left = -1, right = -1;
533 for (std::ptrdiff_t d = 1; d <= kTrackReach; ++d)
535 const double distant = borrow + kTrackBorrowStep *
static_cast<double>(d - 1);
536 if (k - d >= 0 && at(k - d).voiced)
538 if (left < 0) left = k - d;
539 frame.add(at(k - d).semitones, distant);
541 if (k + d < total && at(k + d).voiced)
543 if (right < 0) right = k + d;
545 frame.add(at(k + d).semitones, (!own.voiced && d == 1) ? 0.0 : distant);
548 if (left >= 0 && right >= 0 && std::abs(at(left).semitones - at(right).semitones) < kTrackLine)
550 const double w =
static_cast<double>(k - left) /
static_cast<double>(right - left);
551 frame.add(at(left).semitones + (at(right).semitones - at(left).semitones) * w,
552 borrow + kTrackBorrowStep *
static_cast<double>(std::min(k - left, right - k) - 1));
557 double best[kTrackCandidates + 1] = {}, next[kTrackCandidates + 1] = {};
558 best[0] = frames[0].unvoicedCost;
559 for (
int i = 0; i < frames[0].count; ++i) best[i + 1] = frames[0].cost[i];
560 for (std::size_t k = 1; k < frames.size(); ++k)
562 const TrackFrame& before = frames[k - 1];
563 TrackFrame& frame = frames[k];
565 double low = best[0];
567 for (
int i = 0; i < before.count; ++i)
569 const double v = best[i + 1] + kTrackSwitch;
570 if (v < low) { low = v; from = i + 1; }
572 next[0] = low + frame.unvoicedCost;
573 frame.back[0] =
static_cast<std::uint8_t
>(from);
575 for (
int j = 0; j < frame.count; ++j)
577 double low = best[0] + kTrackSwitch;
579 for (
int i = 0; i < before.count; ++i)
581 const double v = best[i + 1]
582 + kTrackPerSemitone * std::min(std::abs(frame.semitones[j] - before.semitones[i]), kTrackJumpCap);
583 if (v < low) { low = v; from = i + 1; }
585 next[j + 1] = low + frame.cost[j];
586 frame.back[j + 1] =
static_cast<std::uint8_t
>(from);
588 std::copy(next, next + frame.count + 1, best);
594 for (
int i = 1; i <= frames.back().count; ++i)
595 if (best[i] < best[state]) state = i;
596 for (std::size_t k = frames.size(); k-- > 0;)
598 TrackPoint& point = points[k];
599 point.voiced = state > 0;
600 point.frequencyHz = state > 0
601 ?
static_cast<T
>(440.0 * std::pow(2.0, frames[k].semitones[state - 1] / 12.0)) : T(0);
602 state = frames[k].back[state];
604 constexpr std::size_t kNone = std::numeric_limits<std::size_t>::max();
605 std::size_t voicedAt = kNone;
606 for (std::size_t k = 0; k < points.size(); ++k)
608 if (points[k].voiced) voicedAt = k;
609 else if (voicedAt != kNone) points[k].frequencyHz = points[voicedAt].frequencyHz;
612 std::size_t earlier = kNone;
613 for (std::size_t k = points.size(); k-- > 0;)
615 if (points[k].voiced) { voicedAt = k; earlier = kNone;
continue; }
616 if (voicedAt == kNone)
continue;
617 if (earlier == kNone)
620 while (j > 0 && !points[j - 1].voiced) --j;
621 earlier = (j > 0) ? j - 1 : kNone - 1;
623 const bool none = earlier == kNone - 1;
624 if (none || voicedAt - k < k - earlier) points[k].frequencyHz = points[voicedAt].frequencyHz;
630 void update(
int numSamples,
bool freshReading)
noexcept
632 const T raw = detector_.getFrequencyHz();
633 const T conf = detector_.getConfidence();
634 const bool valid = conf >= confidence_.load(std::memory_order_relaxed)
635 && raw >= minHz_.load(std::memory_order_relaxed)
636 && raw <= maxHz_.load(std::memory_order_relaxed);
638 if (freshReading) voiced_.store(valid, std::memory_order_relaxed);
641 samplesSinceValid_ += numSamples;
645 double st = 12.0 * std::log2(
static_cast<double>(raw) / 440.0);
649 targetSt_ = currentSt_ = st;
652 else if (std::abs(st - targetSt_) <= 7.0)
665 if (pendingCount_ > 0 && std::abs(st - pendingSt_) < 1.0)
674 if (pendingCount_ >= kIntervalReadings)
681 for (
const double oct : { -24.0, -12.0, 12.0, 24.0 })
683 if (std::abs(st + oct - targetSt_) < 1.5)
685 targetSt_ = st + oct;
691 samplesSinceValid_ = 0;
695 samplesSinceValid_ += numSamples;
700 const double glideMs =
static_cast<double>(glideMs_.load(std::memory_order_relaxed));
703 currentSt_ = targetSt_;
708 const double maxStep = 12.0 *
static_cast<double>(numSamples)
709 / (glideMs * 0.001 * sampleRate_);
710 currentSt_ += std::clamp(targetSt_ - currentSt_, -maxStep, maxStep);
712 smoothedHz_.store(
static_cast<T
>(440.0 * std::exp2(currentSt_ / 12.0)),
713 std::memory_order_relaxed);
716 tracking_.store(hasTarget_
717 && samplesSinceValid_ <
static_cast<int64_t
>(0.25 * sampleRate_),
718 std::memory_order_relaxed);
723 static constexpr int kIntervalReadings = 2;
724 double sampleRate_ = 48000.0;
725 std::atomic<bool> prepared_{
false };
727 PitchDetector<T> detector_;
728 std::vector<T> monoScratch_;
730 bool hasTarget_ =
false;
731 double targetSt_ = 0.0;
732 double currentSt_ = 0.0;
733 double pendingSt_ = 0.0;
734 int pendingCount_ = 0;
736 int64_t samplesSinceValid_ = 0;
738 std::atomic<T> minHz_ { T(60) };
739 std::atomic<T> maxHz_ { T(1200) };
740 std::atomic<T> confidence_ { T(0.85) };
741 std::atomic<T> glideMs_ { T(60) };
743 std::atomic<T> smoothedHz_ { T(0) };
744 std::atomic<bool> tracking_ {
false };
745 std::atomic<bool> voiced_ {
false };