DSPark 1.9.0
Header-only C++20 DSP for real-time and offline audio
Loading...
Searching...
No Matches
PitchFollower.h
1// DSPark - Professional Audio DSP Framework
2// Copyright (c) 2026 Cristian Moresi - MIT License
3
4#pragma once
5
78#include "../Core/AudioBuffer.h"
79#include "../Core/AudioSpec.h"
80#include "../Core/DspMath.h"
81#include "PitchDetector.h"
82
83#include <algorithm>
84#include <atomic>
85#include <cmath>
86#include <cstddef>
87#include <cstdint>
88#include <limits>
89#include <span>
90#include <vector>
91
92namespace dspark {
93
100template <FloatType T>
102{
103public:
104 // -- Lifecycle -------------------------------------------------------------
105
115 PitchFollower() noexcept { detector_.setNoiseSuppression(false); }
116
140 void prepare(const AudioSpec& spec, int windowSize = 0)
141 {
142 if (!spec.isValid()) return;
143 sampleRate_ = spec.sampleRate;
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));
147 hopPhase_ = 0;
148 prepared_.store(true, std::memory_order_relaxed);
149 reset();
150 }
151
157 void reset() noexcept
158 {
159 hasTarget_ = false;
160 targetSt_ = 0.0;
161 currentSt_ = 0.0;
162 pendingSt_ = 0.0;
163 pendingCount_ = 0;
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);
168 }
169
170 // -- Parameters (thread-safe) ------------------------------------------------
171
177 void setRange(T minHz, T maxHz) noexcept
178 {
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);
184 }
185
195 void setConfidence(T threshold) noexcept
196 {
197 if (!std::isfinite(threshold)) return;
198 confidence_.store(std::clamp(threshold, T(0), T(1)), std::memory_order_relaxed);
199 }
200
206 void setGlide(T msPerOctave) noexcept
207 {
208 if (!std::isfinite(msPerOctave)) return;
209 glideMs_.store(std::max(msPerOctave, T(0)), std::memory_order_relaxed);
210 }
211
213 [[nodiscard]] T getMinHz() const noexcept { return minHz_.load(std::memory_order_relaxed); }
214
216 [[nodiscard]] T getMaxHz() const noexcept { return maxHz_.load(std::memory_order_relaxed); }
217
219 [[nodiscard]] T getConfidenceThreshold() const noexcept { return confidence_.load(std::memory_order_relaxed); }
220
222 [[nodiscard]] T getGlide() const noexcept { return glideMs_.load(std::memory_order_relaxed); }
223
228 [[nodiscard]] int getWindowSize() const noexcept { return detector_.getWindowSize(); }
229
239 void setNoiseSuppression(bool on) noexcept { detector_.setNoiseSuppression(on); }
240
242 [[nodiscard]] bool getNoiseSuppression() const noexcept { return detector_.getNoiseSuppression(); }
243
244 // -- Readout (lock-free, any thread) ------------------------------------------
245
247 [[nodiscard]] T getSmoothedHz() const noexcept
248 {
249 return smoothedHz_.load(std::memory_order_relaxed);
250 }
251
253 [[nodiscard]] T getRawHz() const noexcept { return detector_.getFrequencyHz(); }
254
256 [[nodiscard]] T getConfidence() const noexcept { return detector_.getConfidence(); }
257
259 [[nodiscard]] bool isTracking() const noexcept
260 {
261 return tracking_.load(std::memory_order_relaxed);
262 }
263
269 [[nodiscard]] bool isVoiced() const noexcept
270 {
271 return voiced_.load(std::memory_order_relaxed);
272 }
273
274 // -- Processing ----------------------------------------------------------------
275
281 {
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;
286
287 int i = 0;
288 while (i < nS)
289 {
290 const int chunk = std::min(nS - i, static_cast<int>(monoScratch_.size()));
291 if (nCh == 1)
292 {
293 const T* src = buffer.getChannel(0) + i;
294 std::copy(src, src + chunk, monoScratch_.begin());
295 }
296 else
297 {
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)
301 {
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;
305 }
306 }
307 pushSamples({ monoScratch_.data(), static_cast<size_t>(chunk) });
308 i += chunk;
309 }
310 }
311
316 void pushSamples(std::span<const T> samples) noexcept
317 {
318 if (!prepared_.load(std::memory_order_relaxed) || samples.empty()) return;
319 // Stop at every detection, so each one is judged exactly once: called
320 // per block instead, a small block judged one reading several times
321 // and a large one skipped readings.
322 const int hop = detector_.getHopSize();
323 std::size_t done = 0;
324 while (done < samples.size())
325 {
326 const auto chunk = std::min(samples.size() - done,
327 static_cast<std::size_t>(hop - hopPhase_));
328 detector_.pushSamples(samples.subspan(done, chunk));
329 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);
334 }
335 }
336
337 // -- Offline tracking ------------------------------------------------------------
338
341 {
342 double seconds = 0.0;
343 T frequencyHz = T(0);
344 T confidence = T(0);
345 bool voiced = false;
346 };
347
350 {
351 T minHz = T(60);
352 T maxHz = T(1200);
353 bool noiseSuppression = true;
354 int windowSize = 0;
355 };
356
399 [[nodiscard]] static std::vector<TrackPoint> track(std::span<const T> mono, double sampleRate,
400 const TrackSettings& settings)
401 {
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;
406
407 PitchDetector<T> detector;
408 detector.prepare(sampleRate, settings.windowSize, (settings.windowSize > 0) ? settings.windowSize / 4 : 0);
409 detector.setNoiseSuppression(settings.noiseSuppression);
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;
413
414 // One reading per detection: the detector fires at the end of each hop.
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)
420 {
421 detector.pushSamples(mono.subspan(k * hop, hop));
422 const std::size_t end = (k + 1) * hop;
423 if (end < window) continue; // the window still reaches before the signal
424 const double hz = static_cast<double>(detector.getFrequencyHz());
425 TrackReading reading;
426 TrackPoint point;
427 point.seconds = (static_cast<double>(end) - 0.5 * static_cast<double>(window)) / sampleRate;
428 if (hz >= minHz && hz <= maxHz)
429 {
430 reading.voiced = true;
431 reading.semitones = 12.0 * std::log2(hz / 440.0);
432 reading.confidence = static_cast<double>(detector.getConfidence());
433 point.confidence = detector.getConfidence();
434 }
435 readings.push_back(reading);
436 points.push_back(point);
437 }
438 decodeTrack(readings, 12.0 * std::log2(minHz / 440.0), 12.0 * std::log2(maxHz / 440.0), points);
439 return points;
440 }
441
447 [[nodiscard]] static std::vector<TrackPoint> track(std::span<const T> mono, double sampleRate)
448 {
449 return track(mono, sampleRate, TrackSettings{});
450 }
451
452private:
453 // -- Offline decode (see track()) -------------------------------------------------
454
456 struct TrackReading
457 {
458 double semitones = 0.0;
459 double confidence = 0.0;
460 bool voiced = false;
461 };
462
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;
478
480 struct TrackFrame
481 {
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;
487
488 void add(double st, double c) noexcept
489 {
490 for (int i = 0; i < count; ++i)
491 if (std::abs(semitones[i] - st) < kTrackSame)
492 {
493 cost[i] = std::min(cost[i], c);
494 return;
495 }
496 if (count < kTrackCandidates)
497 {
498 semitones[count] = st;
499 cost[count] = c;
500 ++count;
501 }
502 }
503 };
504
507 static void decodeTrack(const std::vector<TrackReading>& readings, double minSemitones, double maxSemitones,
508 std::vector<TrackPoint>& points)
509 {
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)]; };
513
514 std::vector<TrackFrame> frames(readings.size());
515 for (std::ptrdiff_t k = 0; k < total; ++k)
516 {
517 TrackFrame& frame = frames[static_cast<std::size_t>(k)];
518 const TrackReading& own = at(k);
519 if (own.voiced)
520 {
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;
526 }
527 else if (k + 1 < total && at(k + 1).voiced)
528 {
529 frame.unvoicedCost = kTrackEdge;
530 }
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)
534 {
535 const double distant = borrow + kTrackBorrowStep * static_cast<double>(d - 1);
536 if (k - d >= 0 && at(k - d).voiced)
537 {
538 if (left < 0) left = k - d;
539 frame.add(at(k - d).semitones, distant);
540 }
541 if (k + d < total && at(k + d).voiced)
542 {
543 if (right < 0) right = k + d;
544 // The detection before a first reading takes it at no cost.
545 frame.add(at(k + d).semitones, (!own.voiced && d == 1) ? 0.0 : distant);
546 }
547 }
548 if (left >= 0 && right >= 0 && std::abs(at(left).semitones - at(right).semitones) < kTrackLine)
549 {
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));
553 }
554 }
555
556 // Viterbi over "unvoiced" and each detection's candidates.
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)
561 {
562 const TrackFrame& before = frames[k - 1];
563 TrackFrame& frame = frames[k];
564 {
565 double low = best[0];
566 int from = 0;
567 for (int i = 0; i < before.count; ++i)
568 {
569 const double v = best[i + 1] + kTrackSwitch;
570 if (v < low) { low = v; from = i + 1; }
571 }
572 next[0] = low + frame.unvoicedCost;
573 frame.back[0] = static_cast<std::uint8_t>(from);
574 }
575 for (int j = 0; j < frame.count; ++j)
576 {
577 double low = best[0] + kTrackSwitch;
578 int from = 0;
579 for (int i = 0; i < before.count; ++i)
580 {
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; }
584 }
585 next[j + 1] = low + frame.cost[j];
586 frame.back[j + 1] = static_cast<std::uint8_t>(from);
587 }
588 std::copy(next, next + frame.count + 1, best);
589 }
590
591 // Walk the cheapest path back; unvoiced points keep the pitch of the
592 // nearest voiced one (the earlier one when two are as near).
593 int state = 0;
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;)
597 {
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];
603 }
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)
607 {
608 if (points[k].voiced) voicedAt = k;
609 else if (voicedAt != kNone) points[k].frequencyHz = points[voicedAt].frequencyHz;
610 }
611 voicedAt = kNone;
612 std::size_t earlier = kNone; // the voiced point before the current unvoiced run
613 for (std::size_t k = points.size(); k-- > 0;)
614 {
615 if (points[k].voiced) { voicedAt = k; earlier = kNone; continue; }
616 if (voicedAt == kNone) continue;
617 if (earlier == kNone)
618 {
619 std::size_t j = k;
620 while (j > 0 && !points[j - 1].voiced) --j;
621 earlier = (j > 0) ? j - 1 : kNone - 1; // kNone - 1: no voiced point before the run
622 }
623 const bool none = earlier == kNone - 1;
624 if (none || voicedAt - k < k - earlier) points[k].frequencyHz = points[voicedAt].frequencyHz;
625 }
626 }
627
630 void update(int numSamples, bool freshReading) noexcept
631 {
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);
637
638 if (freshReading) voiced_.store(valid, std::memory_order_relaxed);
639 if (!freshReading)
640 {
641 samplesSinceValid_ += numSamples;
642 }
643 else if (valid)
644 {
645 double st = 12.0 * std::log2(static_cast<double>(raw) / 440.0);
646
647 if (!hasTarget_)
648 {
649 targetSt_ = currentSt_ = st; // first lock: no sweep-in
650 hasTarget_ = true;
651 }
652 else if (std::abs(st - targetSt_) <= 7.0)
653 {
654 targetSt_ = st;
655 pendingCount_ = 0;
656 }
657 else
658 {
659 // A large interval, an octave leap among them, is taken once
660 // kIntervalReadings consecutive readings agree on it; one odd
661 // reading never moves the target. Meanwhile a reading whole
662 // octaves away from the target (the classic 2x / 0.5x
663 // detector error) still updates it, folded back to the
664 // target's octave.
665 if (pendingCount_ > 0 && std::abs(st - pendingSt_) < 1.0)
666 {
667 ++pendingCount_;
668 }
669 else
670 {
671 pendingSt_ = st;
672 pendingCount_ = 1;
673 }
674 if (pendingCount_ >= kIntervalReadings)
675 {
676 targetSt_ = st;
677 pendingCount_ = 0;
678 }
679 else
680 {
681 for (const double oct : { -24.0, -12.0, 12.0, 24.0 })
682 {
683 if (std::abs(st + oct - targetSt_) < 1.5)
684 {
685 targetSt_ = st + oct;
686 break;
687 }
688 }
689 }
690 }
691 samplesSinceValid_ = 0;
692 }
693 else
694 {
695 samplesSinceValid_ += numSamples; // freeze: target stays put
696 }
697
698 if (hasTarget_)
699 {
700 const double glideMs = static_cast<double>(glideMs_.load(std::memory_order_relaxed));
701 if (glideMs < 0.5)
702 {
703 currentSt_ = targetSt_;
704 }
705 else
706 {
707 // Constant musical speed: 12 semitones in glideMs milliseconds.
708 const double maxStep = 12.0 * static_cast<double>(numSamples)
709 / (glideMs * 0.001 * sampleRate_);
710 currentSt_ += std::clamp(targetSt_ - currentSt_, -maxStep, maxStep);
711 }
712 smoothedHz_.store(static_cast<T>(440.0 * std::exp2(currentSt_ / 12.0)),
713 std::memory_order_relaxed);
714 }
715
716 tracking_.store(hasTarget_
717 && samplesSinceValid_ < static_cast<int64_t>(0.25 * sampleRate_),
718 std::memory_order_relaxed);
719 }
720
721 // -- Members --------------------------------------------------------------------
723 static constexpr int kIntervalReadings = 2;
724 double sampleRate_ = 48000.0;
725 std::atomic<bool> prepared_{ false };
726
727 PitchDetector<T> detector_;
728 std::vector<T> monoScratch_;
729
730 bool hasTarget_ = false;
731 double targetSt_ = 0.0;
732 double currentSt_ = 0.0;
733 double pendingSt_ = 0.0;
734 int pendingCount_ = 0;
735 int hopPhase_ = 0;
736 int64_t samplesSinceValid_ = 0;
737
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) };
742
743 std::atomic<T> smoothedHz_ { T(0) };
744 std::atomic<bool> tracking_ { false };
745 std::atomic<bool> voiced_ { false };
746};
747
748} // namespace dspark
Non-owning view over audio channel data.
Definition AudioBuffer.h:53
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
void setNoiseSuppression(bool on) noexcept
Reads a tone through broadband noise (on by default).
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.
Gated, octave-safe, semitone-smoothed pitch tracking source.
void reset() noexcept
Forgets the tracked pitch (parameters are kept). Allocation-free; call from the stream owner (it touc...
PitchFollower() noexcept
Creates a follower with the detector's noise suppression off.
bool getNoiseSuppression() const noexcept
Whether the detector's noise suppression is on.
static std::vector< TrackPoint > track(std::span< const T > mono, double sampleRate)
track() with the default settings (60 to 1200 Hz, noise suppression on, automatic window).
T getGlide() const noexcept
Returns the glide time in milliseconds per octave.
int getWindowSize() const noexcept
T getRawHz() const noexcept
bool isTracking() const noexcept
static std::vector< TrackPoint > track(std::span< const T > mono, double sampleRate, const TrackSettings &settings)
Offline: reads a whole mono signal and decodes its pitch track over the complete sequence of detectio...
T getConfidence() const noexcept
void setConfidence(T threshold) noexcept
Confidence threshold [0, 1] below which readings are ignored (default 0.85).
T getMaxHz() const noexcept
Returns the upper bound of the accepted pitch range in Hz.
void processBlock(AudioBufferView< const T > buffer) noexcept
Feeds a block (any channel count); channels are averaged to mono.
void setNoiseSuppression(bool on) noexcept
Reads tones through broadband noise (opt-in, default off): the wrapped detector's PitchDetector::setN...
void prepare(const AudioSpec &spec, int windowSize=0)
Prepares the follower and the wrapped detector.
void pushSamples(std::span< const T > samples) noexcept
Feeds mono samples directly (alternative to processBlock).
void setGlide(T msPerOctave) noexcept
Glide time in milliseconds per octave (default 60). 0 disables smoothing (the output snaps to each ac...
T getMinHz() const noexcept
Returns the lower bound of the accepted pitch range in Hz.
T getConfidenceThreshold() const noexcept
Returns the confidence gating threshold [0, 1].
void setRange(T minHz, T maxHz) noexcept
Accepted pitch range in Hz (default 60 to 1200). Non-finite values are ignored (the old max() passed ...
T getSmoothedHz() const noexcept
bool isVoiced() const noexcept
void add(float *DSPARK_RESTRICT dst, const float *DSPARK_RESTRICT src, int count) noexcept
Adds source samples into a destination buffer (no scaling).
Definition SimdOps.h:829
Main namespace for the DSPark framework.
Describes the audio environment for a DSP processor.
Definition AudioSpec.h:37
constexpr bool isValid() const noexcept
Checks if the specification contains valid, processable parameters.
Definition AudioSpec.h:71
int maxBlockSize
Maximum number of samples per processing block.
Definition AudioSpec.h:53
double sampleRate
Sample rate in Hz.
Definition AudioSpec.h:45
One detection of an offline pitch track (see track()).
T confidence
The detector's confidence in its own reading there (0: it read nothing).
bool voiced
Whether the point belongs to a note.
double seconds
Centre of the detection's analysis window.
T frequencyHz
Pitch; on an unvoiced point, that of the nearest voiced one (0 if none).
bool noiseSuppression
PitchDetector::setNoiseSuppression().
int windowSize
Analysis window, as prepare(); 0 = automatic.