DSPark 1.9.0
Header-only C++20 DSP for real-time and offline audio
Loading...
Searching...
No Matches
OnsetDetector.h
1// DSPark -- Professional Audio DSP Framework
2// Copyright (c) 2026 Cristian Moresi -- MIT License
3
4#pragma once
5
135#include "../Core/DspMath.h"
136#include "detail/OnsetFeatures.h"
137#include "../Core/AudioBuffer.h"
138#include "../Core/AudioSpec.h"
139#include "../Core/SimdOps.h"
140
141#include <algorithm>
142#include <array>
143#include <atomic>
144#include <cmath>
145#include <cstddef>
146#include <cstdint>
147#include <memory>
148#include <span>
149#include <vector>
150
151namespace dspark {
152
164template <FloatType T>
165class OnsetDetector final
166{
167public:
170
178 enum class Picker { Gated, Plain };
179
180 // -- Lifecycle -----------------------------------------------------------
181
264 void prepare(const AudioSpec& spec, int fftSize = 0, int hop = 0)
265 {
266 if (!(spec.sampleRate > 0.0) || !std::isfinite(spec.sampleRate))
267 return;
268
269 prepared_ = false; // gate OFF: the audio path is a no-op while rebuilding
270
271 sampleRate_ = spec.sampleRate;
272
273 if (fftSize <= 0)
274 {
275 // Automatic: hold the analysis TIME SPAN constant across sample
276 // rates (the span 2048 samples cover at 48 kHz). Bin width and the
277 // filterbank's quarter-tone floor are both fs/fftSize, so a
278 // constant span pins them -- and with them the usable low register
279 // -- instead of letting them widen as fs rises.
280 fftSize_ = detail::OnsetSpectrum<T>::defaultFrameSize(sampleRate_);
281 }
282 else
283 {
284 int fs = std::clamp(fftSize, kMinFft, kMaxFft);
285 int pow2 = kMinFft;
286 while (pow2 < fs) pow2 <<= 1;
287 fftSize_ = pow2;
288 }
289
290 if (hop <= 0)
291 hop_ = std::max(1, static_cast<int>(std::lround(sampleRate_ / 200.0)));
292 else
293 hop_ = hop;
294 hop_ = std::clamp(hop_, 1, fftSize_);
295
296 latencySamples_.store(static_cast<int64_t>(fftSize_) + hop_,
297 std::memory_order_relaxed);
298
299 // Analysis-window group-delay compensation: half-wave-rectified spectral
300 // flux peaks on the rising flank of a transient, ~kLocalizationLead*N
301 // before the windowed-energy peak. Adding it back centres the reported
302 // onset on the transient (calibrated on band-limited clicks; softer
303 // onsets localise slightly late but stay within the acceptance window).
304 localizationOffset_ = static_cast<int>(std::lround(kLocalizationLead
305 * static_cast<double>(fftSize_)));
306 // Warm-up: suppress onsets until the analysis ring is fully primed so
307 // the silence->first-input ramp cannot fire a spurious onset.
308 primeFrames_ = fftSize_ / hop_ + 2;
309
310 // Release test spans, in frames, as fractions of the analysis frame
311 // (see setPicker()). The look-ahead always fits inside the
312 // fixed latency L: a candidate is reported at reference + L, which is
313 // 0.84 * fftSize + hop after its frame, and the test needs only
314 // 0.43 * fftSize of it (its new-content rescue, below, at most all).
315 energyBack_ = std::max(1, static_cast<int>(std::lround(kEnergyLookBack
316 * static_cast<double>(fftSize_) / static_cast<double>(hop_))));
317 energyAhead_ = std::max(1, static_cast<int>(std::lround(kEnergyLookAhead
318 * static_cast<double>(fftSize_) / static_cast<double>(hop_))));
319
320 // The gated picker's flux compares with the frame whose Hann window
321 // has fallen to half at the current window's centre, a quarter of the
322 // frame back (Boeck and Widmer, DAFx-13): two hops under the automatic
323 // frame at every rate. The persistence value spans the release test,
324 // against the largest of energyAhead_ frames before it.
325 pickLag_ = std::max(1, static_cast<int>(std::lround(static_cast<double>(fftSize_)
326 / (4.0 * static_cast<double>(hop_)))));
327
328 // The new-content rescue of the release test (setPicker()) reads the
329 // bands twice the release test's look-ahead after the candidate, as
330 // far as the fixed latency allows: the frame that many hops after the
331 // candidate must fire before its reporting sample. When no frame past
332 // the release test's fits, the rescue is off. Its baseline spans two
333 // analysis frames before the release test's.
334 {
335 const int lead = fftSize_ / 2 - localizationOffset_;
336 const int fits = (fftSize_ + hop_ - lead) / hop_;
337 contentHold_ = std::min(2 * energyAhead_, fits);
338 if (contentHold_ <= energyAhead_) contentHold_ = 0;
339 decideAhead_ = std::max(energyAhead_, contentHold_);
340 }
341 const int contentSpan = std::max(1, static_cast<int>(std::lround(kContentSpan
342 * static_cast<double>(fftSize_) / static_cast<double>(hop_))));
343
344 ring_.assign(static_cast<size_t>(fftSize_) * 2, T(0));
345 spectrum_.prepare(fftSize_);
346 novelty_.prepare(sampleRate_, fftSize_, false, pickLag_, energyBack_ + energyAhead_,
347 energyAhead_, energyBack_, energyAhead_, contentHold_, contentSpan);
348
349 // Bin edges of the four registers of OdfFrame::registers, for the
350 // release test's per-register energies.
351 {
352 const double binHz = sampleRate_ / static_cast<double>(fftSize_);
353 const int bins = fftSize_ / 2 + 1;
354 constexpr double edges[kNumRegisters - 1] = { 200.0, 800.0, 3200.0 };
355 registerEdge_[0] = 0;
356 for (int g = 0; g + 1 < kNumRegisters; ++g)
357 registerEdge_[static_cast<size_t>(g) + 1] = std::clamp(
358 static_cast<int>(std::ceil(edges[g] / binHz)), 0, bins);
359 registerEdge_[kNumRegisters] = bins;
360 }
361
362 // Peak-picker windows in frames (derived from the ms defaults above).
363 preMaxFrames_ = msToFrames(30.0);
364 postMaxFrames_ = msToFrames(30.0); // offline; causal uses 1
365 preAvgFrames_ = msToFrames(100.0);
366 postAvgFrames_ = msToFrames(70.0); // offline; causal uses 0
367 waitFrames_ = msToFrames(30.0);
368
369 // Causal ODF history: enough for the pre_avg look-back plus the
370 // single-frame causal confirmation, over the frames a candidate waits.
371 odfHistLen_ = std::max(preAvgFrames_ + decideAhead_, preMaxFrames_) + 4;
372 odfHist_.assign(static_cast<size_t>(odfHistLen_), T(0));
373 pickHist_.assign(static_cast<size_t>(odfHistLen_), T(0));
374
375 energyHistLen_ = decideAhead_ + 4 * energyBack_ + 2;
376 energyHist_.assign(static_cast<size_t>(energyHistLen_), 0.0);
377 registerEnergyHist_.assign(static_cast<size_t>(energyHistLen_), RegisterEnergy {});
378 persistHistLen_ = preAvgFrames_ + decideAhead_ + 4;
379 persistHist_.assign(static_cast<size_t>(persistHistLen_), T(0));
380 candidates_.assign(static_cast<size_t>(decideAhead_ + 2), Candidate{});
381
382 // Pending-onset ring: onsets are held from detection until their
383 // release sample (reference + L). At most ceil(L/hop)+2 can be
384 // in flight; size generously to a power-of-two-ish bound.
385 const int maxPending = (fftSize_ + hop_) / hop_ + 4;
386 pending_.assign(static_cast<size_t>(std::max(8, maxPending)),
387 PendingOnset{});
388 pendingHead_ = 0;
389 pendingCount_ = 0;
390
391 resetState();
392
393 prepared_ = true; // gate ON
394 }
395
397 void setMethod(Method m) noexcept { method_.store(m, std::memory_order_relaxed); }
398
410 void setLinearFlux(bool on) noexcept { linearFlux_.store(on, std::memory_order_relaxed); }
411
413 [[nodiscard]] bool getLinearFlux() const noexcept
414 {
415 return linearFlux_.load(std::memory_order_relaxed);
416 }
417
427 void setThreshold(T deltaAboveMean) noexcept
428 {
429 if (!std::isfinite(deltaAboveMean)) return;
430 threshold_.store(std::max(T(0), deltaAboveMean), std::memory_order_relaxed);
431 }
432
434 void setAdaptiveWhitening(bool on) noexcept
435 {
436 whitening_.store(on, std::memory_order_relaxed);
437 }
438
497 void setPicker(Picker picker) noexcept
498 {
499 picker_.store(picker, std::memory_order_relaxed);
500 }
501
503 [[nodiscard]] Picker getPicker() const noexcept
504 {
505 return picker_.load(std::memory_order_relaxed);
506 }
507
509 [[nodiscard]] Method getMethod() const noexcept
510 {
511 return method_.load(std::memory_order_relaxed);
512 }
513
515 [[nodiscard]] T getThreshold() const noexcept
516 {
517 return threshold_.load(std::memory_order_relaxed);
518 }
519
521 [[nodiscard]] bool getAdaptiveWhitening() const noexcept
522 {
523 return whitening_.load(std::memory_order_relaxed);
524 }
525
528 [[nodiscard]] bool computesBinPhases() const noexcept { return binPhases_; }
529
530 // -- Audio path (causal, RT-safe) ---------------------------------------
531
538 {
539 if (!prepared_ || in.getNumChannels() < 1) return;
540 const T* ch0 = in.getChannel(0);
541 pushSamples(std::span<const T>(ch0, static_cast<size_t>(in.getNumSamples())));
542 }
543
551 void pushSamples(std::span<const T> samples) noexcept
552 {
553 if (!prepared_) return;
554
555 bool firedThisCall = false;
556
557 for (const T s : samples)
558 {
559 const T x = std::isfinite(s) ? s : T(0);
560
561 ring_[static_cast<size_t>(writePos_)] = x;
562 ring_[static_cast<size_t>(writePos_ + fftSize_)] = x;
563 if (++writePos_ >= fftSize_) writePos_ = 0;
564
565 ++totalSamples_;
566
567 // Release any pending onset whose reporting sample has arrived.
568 while (pendingCount_ > 0)
569 {
570 const PendingOnset& p = pending_[static_cast<size_t>(pendingHead_)];
571 if (totalSamples_ - 1 >= p.reportSample)
572 {
573 lastOnsetSample_.store(p.referenceSample, std::memory_order_relaxed);
574 onsetStrength_.store(p.strength, std::memory_order_relaxed);
575 firedThisCall = true;
576 pendingHead_ = (pendingHead_ + 1) % static_cast<int>(pending_.size());
577 --pendingCount_;
578 }
579 else break;
580 }
581
582 if (++hopCounter_ >= hop_)
583 {
584 hopCounter_ = 0;
585 analyzeFrame();
586 }
587 }
588
589 onsetLatched_.store(firedThisCall, std::memory_order_relaxed);
590 }
591
592 // -- Readout (lock-free) -------------------------------------------------
593
595 [[nodiscard]] bool onsetDetected() const noexcept
596 {
597 return onsetLatched_.load(std::memory_order_relaxed);
598 }
599
604 [[nodiscard]] T getOnsetStrength() const noexcept
605 {
606 return onsetStrength_.load(std::memory_order_relaxed);
607 }
608
613 [[nodiscard]] int64_t getLastOnsetSample() const noexcept
614 {
615 return lastOnsetSample_.load(std::memory_order_relaxed);
616 }
617
619 [[nodiscard]] int getLatencySamples() const noexcept
620 {
621 return static_cast<int>(latencySamples_.load(std::memory_order_relaxed));
622 }
623
628 [[nodiscard]] int getFftSize() const noexcept { return fftSize_; }
629
631 [[nodiscard]] int getHopSize() const noexcept { return hop_; }
632
635 [[nodiscard]] int getNumBands() const noexcept { return novelty_.getNumBands(); }
636
637 // -- Onset-strength envelope (stream owner only) -------------------------
638
653
654 struct OdfFrame
655 {
656 T value = T(0);
657 int64_t referenceSample = 0;
658 int64_t frameIndex = 0;
665 std::array<T, kNumRegisters> registers {};
673 T linear = T(0);
674 };
675
698 [[nodiscard]] OdfFrame getLastOdfFrame() const noexcept
699 {
700 return OdfFrame { lastOdfValue_, lastOdfRef_, frameIndex_, lastRegisters_, lastLinear_ };
701 }
702
726 [[nodiscard]] int getWarmupFrames() const noexcept { return primeFrames_; }
727
743 [[nodiscard]] int getEnvelopeLatencySamples() const noexcept
744 {
745 return fftSize_ / 2 - localizationOffset_;
746 }
747
748 // -- Offline -------------------------------------------------------------
749
751 struct Onset
752 {
753 int64_t sample = 0;
754 T strength = T(0);
755 };
756
766 std::vector<int64_t> detectOffline(AudioBufferView<const T> whole)
767 {
768 return positionsOf(detectOfflineOnsets(whole));
769 }
770
773 {
774 if (!prepared_ || whole.getNumChannels() < 1) return {};
775 const int n = std::max(0, whole.getNumSamples());
776 beginOffline(n);
777 pushOffline(std::span<const T>(whole.getChannel(0), static_cast<size_t>(n)));
778 return finishOfflineOnsets();
779 }
780
798 void beginOffline(int64_t expectedSamples = 0)
799 {
800 clearOfflineFrames();
801 offlineOpen_ = false;
802 if (!prepared_) return;
803 if (expectedSamples > 0)
804 {
805 const size_t frames = static_cast<size_t>(expectedSamples / std::max(1, hop_) + 2);
806 offOdf_.reserve(frames);
807 offPick_.reserve(frames);
808 offRef_.reserve(frames);
809 offEnergy_.reserve(frames);
810 offRegisterEnergy_.reserve(frames);
811 offPersist_.reserve(frames);
812 offContent_.reserve(frames);
813 }
814 resetState();
815 offMethod_ = method_.load(std::memory_order_relaxed);
816 offWhiten_ = whitening_.load(std::memory_order_relaxed);
817 offTotal_ = 0;
818 offHop_ = 0;
819 offlineOpen_ = true;
820 }
821
823 void pushOffline(std::span<const T> samples)
824 {
825 if (!offlineOpen_) return;
826 for (const T s : samples)
827 {
828 const T v = std::isfinite(s) ? s : T(0);
829 ring_[static_cast<size_t>(writePos_)] = v;
830 ring_[static_cast<size_t>(writePos_ + fftSize_)] = v;
831 if (++writePos_ >= fftSize_) writePos_ = 0;
832 ++offTotal_;
833 if (++offHop_ >= hop_)
834 {
835 offHop_ = 0;
836 offOdf_.push_back(computeOdf(offMethod_, offWhiten_));
837 offPick_.push_back(curPick_);
838 offRef_.push_back(referenceSample(offTotal_));
839 offEnergy_.push_back(curEnergy_);
840 offRegisterEnergy_.push_back(curRegisterEnergy_);
841 offPersist_.push_back(curPersist_);
842 offContent_.push_back(T(0));
843 storeOfflineContent();
844 }
845 }
846 }
847
850 std::vector<int64_t> finishOffline()
851 {
852 return positionsOf(finishOfflineOnsets());
853 }
854
856 std::vector<Onset> finishOfflineOnsets()
857 {
858 std::vector<Onset> out;
859 if (!offlineOpen_) return out;
860 offlineOpen_ = false;
861
862 // Symmetric peak-pick over the whole envelope.
863 const T delta = threshold_.load(std::memory_order_relaxed);
864 const bool gated = picker_.load(std::memory_order_relaxed) == Picker::Gated;
865 const std::vector<T>& odf = gated ? offPick_ : offOdf_;
867 const typename detail::OnsetPeakPicker<T>::Windows windows {
868 static_cast<size_t>(preMaxFrames_), static_cast<size_t>(postMaxFrames_),
869 static_cast<size_t>(preAvgFrames_), static_cast<size_t>(postAvgFrames_),
870 static_cast<size_t>(waitFrames_)
871 };
872 const int64_t last = static_cast<int64_t>(offEnergy_.size()) - 1;
873 const auto at = [last](int64_t i) { return static_cast<size_t>(std::clamp<int64_t>(i, 0, last)); };
874 const auto energyAt = [&](int64_t i) { return offEnergy_[at(i)]; };
875 const auto registersAt = [&](int64_t i) -> const RegisterEnergy& { return offRegisterEnergy_[at(i)]; };
876 const auto persistAt = [&](int64_t i) { return offPersist_[at(i)]; };
877 const auto contentAt = [&](int64_t i) { return offContent_[at(i)]; };
878 for (size_t f = static_cast<size_t>(primeFrames_); f < odf.size(); ++f)
879 {
880 if (picker.accept(f, odf.size(), [&](size_t i) { return odf[i]; }, windows, delta,
881 gated ? T(kGatedMeanScale) : T(1),
882 [&](size_t i, T margin) {
883 return !gated || keepsGate(static_cast<int64_t>(i), energyAt,
884 registersAt, persistAt, contentAt,
885 margin < T(kWeakMargin),
886 postAvgFrames_);
887 }))
888 out.push_back(Onset { offRef_[f], odf[f] });
889 }
890
891 clearOfflineFrames();
892 resetState();
893 return out;
894 }
895
898 void reset() noexcept
899 {
900 offlineOpen_ = false;
901 resetState();
902 }
903
904private:
906 using RegisterEnergy = std::array<double, detail::OnsetNovelty<T>::kNumRegisters>;
907
908 void clearOfflineFrames() noexcept
909 {
910 offOdf_.clear();
911 offPick_.clear();
912 offRef_.clear();
913 offEnergy_.clear();
914 offRegisterEnergy_.clear();
915 offPersist_.clear();
916 offContent_.clear();
917 }
918
929 void storeOfflineContent() noexcept
930 {
931 if (contentHold_ <= 0 || offMethod_ != Method::SuperFlux) return;
932 const int64_t newest = static_cast<int64_t>(offPick_.size()) - 1;
933 const int64_t c = newest - contentHold_;
934 if (c < 0) return;
935 const T v = offPick_[static_cast<size_t>(c)];
936 const int64_t from = std::max<int64_t>(0, c - preMaxFrames_);
937 const int64_t to = std::min<int64_t>(newest, c + postMaxFrames_);
938 for (int64_t j = from; j <= to; ++j)
939 if (offPick_[static_cast<size_t>(j)] > v) return;
940 offContent_[static_cast<size_t>(c)] = novelty_.contentShare();
941 }
942
943 [[nodiscard]] static std::vector<int64_t> positionsOf(const std::vector<Onset>& onsets)
944 {
945 std::vector<int64_t> out;
946 out.reserve(onsets.size());
947 for (const Onset& o : onsets) out.push_back(o.sample);
948 return out;
949 }
950
951 // -- Constants -----------------------------------------------------------
952 static constexpr int kMinFft = 64;
953 static constexpr int kMaxFft = 1 << 16;
956 static constexpr int64_t kBig = int64_t(1) << 60;
957 static constexpr T kDefaultDelta = T(0.0035);
962 static constexpr double kGatedMeanScale = 2.0;
963 static constexpr double kEnergyLookBack = 0.2;
964 static constexpr double kEnergyLookAhead = 0.43;
965 static constexpr double kReleaseFallDb = -2.0;
969 static constexpr double kWeakMargin = 0.0045;
970 static constexpr double kWeakFallDb = 0.0;
971 static constexpr double kEnergyFloor = 1e-30;
974 static constexpr double kPersistRatio = 2.1;
978 static constexpr double kPersistStrongRatio = 3.0;
979 static constexpr double kWeakRiseDb = 2.0;
980 static constexpr double kPersistFloor = 1e-12;
983 static constexpr double kRescueGain = 2.0;
984 static constexpr double kRescueShare = 0.03;
990 static constexpr double kContentShare = 0.003;
991 static constexpr double kContentSpan = 2.0;
992 static constexpr double kLocalizationLead = 0.34;
993 static constexpr int kPhaseRestartFrames = 3;
994
996 struct Candidate
997 {
998 int64_t frame = 0;
999 int64_t referenceSample = 0;
1000 T strength = T(0);
1001 bool weak = false;
1002 };
1003
1004 struct PendingOnset
1005 {
1006 int64_t referenceSample = 0;
1007 int64_t reportSample = 0;
1008 T strength = T(0);
1009 };
1010
1011 // -- Frame timing --------------------------------------------------------
1012
1015 [[nodiscard]] int64_t referenceSample(int64_t firePos) const noexcept
1016 {
1017 return firePos - static_cast<int64_t>(fftSize_) / 2
1018 + static_cast<int64_t>(localizationOffset_);
1019 }
1020
1021 [[nodiscard]] int msToFrames(double ms) const noexcept
1022 {
1023 return std::max(1, static_cast<int>(std::lround(ms * 0.001 * sampleRate_
1024 / static_cast<double>(hop_))));
1025 }
1026
1027 // -- STFT + ODF ----------------------------------------------------------
1028
1030 T computeOdf(Method method, bool whiten) noexcept
1031 {
1032 // Phases cost more than the FFT, and only ComplexDomain reads them.
1033 // Frames without them leave nothing to predict from, so selecting
1034 // ComplexDomain mid-stream restarts the history, and its first frames
1035 // are held back from the picker: they measure the restart, not audio.
1036 const bool phases = method == Method::ComplexDomain;
1037 if (phases && !binPhases_)
1038 {
1039 novelty_.reset();
1040 lastOnsetFrame_ = frameIndex_ + kPhaseRestartFrames;
1041 }
1042 binPhases_ = phases;
1043 spectrum_.compute(&ring_[static_cast<size_t>(writePos_)], phases);
1044 // Frame energy for the release test, from the raw magnitudes: the
1045 // whitening below rewrites them in place.
1046 const auto mags = spectrum_.magnitudes();
1047 curEnergy_ = 0.0;
1048 for (int g = 0; g < kNumRegisters; ++g)
1049 {
1050 const int from = registerEdge_[static_cast<size_t>(g)];
1051 const int to = registerEdge_[static_cast<size_t>(g) + 1];
1052 const double e = to > from ? static_cast<double>(simd::sumOfSquares(
1053 mags.data() + from, to - from))
1054 : 0.0;
1055 curRegisterEnergy_[static_cast<size_t>(g)] = e;
1056 curEnergy_ += e;
1057 }
1058 using FeatureMethod = typename detail::OnsetNovelty<T>::Method;
1059 const auto selected = method == Method::SpectralFlux ? FeatureMethod::SpectralFlux
1060 : method == Method::ComplexDomain ? FeatureMethod::ComplexDomain
1061 : method == Method::SuperFlux ? FeatureMethod::SuperFlux
1062 : static_cast<FeatureMethod>(-1);
1063 novelty_.setLinearFlux(linearFlux_.load(std::memory_order_relaxed));
1064 const auto result = novelty_.process(spectrum_.magnitudes(), spectrum_.phases(),
1065 selected, whiten);
1066 curRegisters_ = result.registers;
1067 curPick_ = result.pick;
1068 curPersist_ = result.persist;
1069 curLinear_ = method == Method::SpectralFlux ? result.value : result.linear;
1070 return result.value;
1071 }
1072
1074 void analyzeFrame() noexcept
1075 {
1076 const Method m = method_.load(std::memory_order_relaxed);
1077 const bool whiten = whitening_.load(std::memory_order_relaxed);
1078 const T value = computeOdf(m, whiten);
1079
1080 // Push into the causal ODF history rings: the envelope, and the
1081 // function the gated picker reads.
1082 odfHist_[static_cast<size_t>(odfWrite_)] = value;
1083 pickHist_[static_cast<size_t>(odfWrite_)] = curPick_;
1084 odfWrite_ = (odfWrite_ + 1) % odfHistLen_;
1085 ++frameIndex_;
1086 energyHist_[static_cast<size_t>(frameIndex_ % energyHistLen_)] = curEnergy_;
1087 registerEnergyHist_[static_cast<size_t>(frameIndex_ % energyHistLen_)] = curRegisterEnergy_;
1088 persistHist_[static_cast<size_t>(frameIndex_ % persistHistLen_)] = curPersist_;
1089
1090 // Envelope readout for the stream owner (see getLastOdfFrame()). The
1091 // frame fired at totalSamples_, so it localises exactly where an onset
1092 // decided from it would: one definition of frame time, not two.
1093 lastOdfValue_ = value;
1094 lastOdfRef_ = referenceSample(totalSamples_);
1095 lastRegisters_ = curRegisters_;
1096 lastLinear_ = curLinear_;
1097
1098 // Causal peak-pick with a single-frame confirmation: we decide whether
1099 // the PREVIOUS frame was a maximum now that we have the current one.
1100 // This one-hop confirmation is exactly the +hop term of L.
1101 if (frameIndex_ < 2) { lastConfirmOdf_ = value; decideCandidates(); return; }
1102
1103 const bool gated = picker_.load(std::memory_order_relaxed) == Picker::Gated;
1104 const std::vector<T>& hist = gated ? pickHist_ : odfHist_;
1105 const T prev = histAt(hist, 1); // previous frame (candidate)
1106 const T curr = gated ? curPick_ : value; // current frame (confirmation)
1107
1108 // (1) prev is a causal local max over [prev-preMax, prev+1].
1109 bool isMax = (prev >= curr);
1110 if (isMax)
1111 {
1112 for (int j = 2; j <= preMaxFrames_ + 1 && j < frameIndex_; ++j)
1113 {
1114 if (histAt(hist, j) > prev) { isMax = false; break; }
1115 }
1116 }
1117
1118 if (!isMax) { decideCandidates(); return; }
1119 {
1120 // (2) prev exceeds the backward moving mean + delta.
1121 T sum = T(0); int cnt = 0;
1122 for (int j = 1; j <= preAvgFrames_ && j < frameIndex_; ++j)
1123 {
1124 sum += histAt(hist, j); ++cnt;
1125 }
1126 const T mean = (cnt > 0) ? sum / static_cast<T>(cnt) : T(0);
1127 const T delta = threshold_.load(std::memory_order_relaxed);
1128 const T scale = gated ? T(kGatedMeanScale) : T(1);
1129
1130 // (3) combination width since the last onset, and past warm-up.
1131 const int64_t candFrame = frameIndex_ - 1;
1132 if (candFrame >= primeFrames_ && prev >= scale * mean + delta
1133 && candFrame - lastOnsetFrame_ > waitFrames_
1134 && candidateCount_ < static_cast<int>(candidates_.size()))
1135 {
1136 // The candidate is the previous frame; its fire position was
1137 // totalSamples_ - hop (one hop before the current frame's fire).
1138 // It waits for the frames its release test reads; the
1139 // decision still lands well before its reporting sample.
1140 const int64_t candFirePos = totalSamples_ - hop_;
1141 const int tail = (candidateHead_ + candidateCount_)
1142 % static_cast<int>(candidates_.size());
1143 candidates_[static_cast<size_t>(tail)] = Candidate {
1144 candFrame, referenceSample(candFirePos), prev,
1145 prev - (scale * mean + delta) < T(kWeakMargin) };
1146 ++candidateCount_;
1147 }
1148 }
1149 decideCandidates();
1150 }
1151
1154 void decideCandidates() noexcept
1155 {
1156 const bool gated = picker_.load(std::memory_order_relaxed) == Picker::Gated;
1157 const auto clampEnergyFrame = [&](int64_t k) {
1158 const int64_t oldest = std::max<int64_t>(1, frameIndex_ - energyHistLen_ + 1);
1159 return static_cast<size_t>(std::clamp(k, oldest, frameIndex_) % energyHistLen_);
1160 };
1161 const auto energyAt = [&](int64_t k) { return energyHist_[clampEnergyFrame(k)]; };
1162 const auto registersAt = [&](int64_t k) -> const RegisterEnergy& {
1163 return registerEnergyHist_[clampEnergyFrame(k)];
1164 };
1165 const auto persistAt = [&](int64_t k) {
1166 const int64_t oldest = std::max<int64_t>(1, frameIndex_ - persistHistLen_ + 1);
1167 return persistHist_[static_cast<size_t>(std::clamp(k, oldest, frameIndex_) % persistHistLen_)];
1168 };
1169 // A candidate is decided exactly decideAhead_ frames after its own,
1170 // which is contentHold_ when the rescue is on: the frames the content
1171 // share reads are the newest the novelty kernel holds.
1172 const auto contentAt = [&](int64_t k) {
1173 return frameIndex_ - k == contentHold_ ? novelty_.contentShare() : T(0);
1174 };
1175 while (candidateCount_ > 0)
1176 {
1177 Candidate c = candidates_[static_cast<size_t>(candidateHead_)];
1178 if (c.frame + decideAhead_ > frameIndex_) break;
1179 candidateHead_ = (candidateHead_ + 1) % static_cast<int>(candidates_.size());
1180 --candidateCount_;
1181 if (gated)
1182 {
1183 // The frames the release test waited for extend the moving
1184 // mean forward, as the offline mean is centred: the rise of a
1185 // slow attack lies behind its peak, the fluctuations of a bed
1186 // on both sides.
1187 T sum = T(0);
1188 int cnt = 0;
1189 for (int64_t k = std::max<int64_t>(1, c.frame - preAvgFrames_ + 1);
1190 k <= c.frame + energyAhead_; ++k)
1191 {
1192 sum += histAt(pickHist_, static_cast<int>(frameIndex_ - k));
1193 ++cnt;
1194 }
1195 const T mean = cnt > 0 ? sum / static_cast<T>(cnt) : T(0);
1196 const T margin = c.strength
1197 - (T(kGatedMeanScale) * mean + threshold_.load(std::memory_order_relaxed));
1198 if (margin < T(0)) continue;
1199 c.weak = margin < T(kWeakMargin);
1200 }
1201 if (c.frame - lastOnsetFrame_ > waitFrames_
1202 && (!gated || keepsGate(c.frame, energyAt, registersAt, persistAt, contentAt, c.weak, 0)))
1203 {
1204 scheduleOnset(c.referenceSample, c.strength);
1205 lastOnsetFrame_ = c.frame;
1206 }
1207 }
1208 }
1209
1223 template <typename Energy>
1224 [[nodiscard]] bool keepsEnergy(int64_t f, Energy energyAt, bool weak) const noexcept
1225 {
1226 return energyRise(f, energyAt) >= (weak ? kWeakFallDb : kReleaseFallDb);
1227 }
1228
1232 template <typename Energy>
1233 [[nodiscard]] double energyRise(int64_t f, Energy energyAt) const noexcept
1234 {
1235 const auto dB = [](double a, double b) {
1236 return 10.0 * std::log10((a + kEnergyFloor) / (b + kEnergyFloor));
1237 };
1238 const int64_t b = energyBack_, a = energyAhead_;
1239 const double before = dB(energyAt(f - 2 * b), energyAt(f - 4 * b));
1240 return dB(energyAt(f + a), energyAt(f - b))
1241 - static_cast<double>(a + b) / static_cast<double>(2 * b) * std::min(0.0, before);
1242 }
1243
1259 template <typename Energy, typename Registers, typename Persist, typename Content>
1260 [[nodiscard]] bool keepsGate(int64_t f, Energy energyAt, Registers registersAt,
1261 Persist persistAt, Content contentAt, bool weak,
1262 int64_t ahead) const noexcept
1263 {
1264 if (!keepsEnergy(f, energyAt, weak) && !registerRises(f, energyAt, registersAt)
1265 && !(contentHold_ > 0 && static_cast<double>(contentAt(f)) >= kContentShare))
1266 return false;
1267 if (!weak) return true;
1268 const double ratio = persistenceRatio(f, persistAt, ahead);
1269 return ratio >= kPersistRatio
1270 && (ratio >= kPersistStrongRatio || energyRise(f, energyAt) >= kWeakRiseDb);
1271 }
1272
1283 template <typename Energy, typename Registers>
1284 [[nodiscard]] bool registerRises(int64_t f, Energy energyAt, Registers registersAt) const noexcept
1285 {
1286 const RegisterEnergy& before = registersAt(f - energyBack_);
1287 const RegisterEnergy& after = registersAt(f + energyAhead_);
1288 const double total = energyAt(f - energyBack_);
1289 for (int g = 0; g < kNumRegisters; ++g)
1290 {
1291 const double a = after[static_cast<size_t>(g)], b = before[static_cast<size_t>(g)];
1292 if (a >= kRescueGain * b && a - b >= kRescueShare * total && a > kEnergyFloor)
1293 return true;
1294 }
1295 return false;
1296 }
1297
1313 template <typename Persist>
1314 [[nodiscard]] double persistenceRatio(int64_t f, Persist persistAt, int64_t ahead) const noexcept
1315 {
1316 double sum = 0.0;
1317 int n = 0;
1318 for (int64_t j = f - preAvgFrames_; j <= f + ahead; ++j)
1319 {
1320 sum += static_cast<double>(persistAt(j + energyAhead_));
1321 ++n;
1322 }
1323 const double mean = sum / static_cast<double>(std::max(1, n));
1324 return static_cast<double>(persistAt(f + energyAhead_)) / std::max(kPersistFloor, mean);
1325 }
1326
1329 [[nodiscard]] T histAt(const std::vector<T>& hist, int j) const noexcept
1330 {
1331 int idx = odfWrite_ - 1 - j;
1332 idx %= odfHistLen_;
1333 if (idx < 0) idx += odfHistLen_;
1334 return hist[static_cast<size_t>(idx)];
1335 }
1336
1337 void scheduleOnset(int64_t referenceSample, T strength) noexcept
1338 {
1339 if (pendingCount_ >= static_cast<int>(pending_.size())) return; // saturate
1340 const int tail = (pendingHead_ + pendingCount_) % static_cast<int>(pending_.size());
1341 PendingOnset& p = pending_[static_cast<size_t>(tail)];
1342 p.referenceSample = referenceSample;
1343 p.reportSample = referenceSample + latencySamples_.load(std::memory_order_relaxed);
1344 p.strength = strength;
1345 ++pendingCount_;
1346 }
1347
1348 void resetState() noexcept
1349 {
1350 std::fill(ring_.begin(), ring_.end(), T(0));
1351 novelty_.reset();
1352 std::fill(odfHist_.begin(), odfHist_.end(), T(0));
1353 std::fill(pickHist_.begin(), pickHist_.end(), T(0));
1354 std::fill(persistHist_.begin(), persistHist_.end(), T(0));
1355 std::fill(registerEnergyHist_.begin(), registerEnergyHist_.end(), RegisterEnergy {});
1356 curRegisterEnergy_ = RegisterEnergy {};
1357 curPick_ = T(0);
1358 curPersist_ = T(0);
1359 curLinear_ = T(0);
1360 lastLinear_ = T(0);
1361
1362 writePos_ = 0;
1363 hopCounter_ = 0;
1364 totalSamples_ = 0;
1365 frameIndex_ = 0;
1366 odfWrite_ = 0;
1367 lastOdfValue_ = T(0);
1368 lastOdfRef_ = 0;
1369 lastRegisters_.fill(T(0));
1370 curRegisters_.fill(T(0));
1371 lastConfirmOdf_ = T(0);
1372 lastOnsetFrame_ = -kBig;
1373 binPhases_ = true;
1374 pendingHead_ = 0;
1375 pendingCount_ = 0;
1376 candidateHead_ = 0;
1377 candidateCount_ = 0;
1378 curEnergy_ = 0.0;
1379 std::fill(energyHist_.begin(), energyHist_.end(), 0.0);
1380
1381 onsetLatched_.store(false, std::memory_order_relaxed);
1382 onsetStrength_.store(T(0), std::memory_order_relaxed);
1383 lastOnsetSample_.store(-1, std::memory_order_relaxed);
1384 }
1385
1386 // -- Members -------------------------------------------------------------
1387 double sampleRate_ = 44100.0;
1388 int fftSize_ = 2048;
1389 int hop_ = 221;
1390 int localizationOffset_ = 0;
1391 int primeFrames_ = 12;
1392 bool prepared_ = false;
1393 bool binPhases_ = true;
1394 detail::OnsetSpectrum<T> spectrum_;
1395 detail::OnsetNovelty<T> novelty_;
1396 std::vector<T> ring_; // Mirrored chronological input, size 2*fftSize.
1397
1398 // Peak-picker windows (frames).
1399 int preMaxFrames_ = 6, postMaxFrames_ = 6;
1400 int preAvgFrames_ = 20, postAvgFrames_ = 14;
1401 int waitFrames_ = 6;
1402
1403 // Causal ODF history rings: the envelope and the gated picker's function.
1404 std::vector<T> odfHist_;
1405 std::vector<T> pickHist_;
1406 int odfHistLen_ = 32;
1407 int odfWrite_ = 0;
1408 int64_t frameIndex_ = 0;
1409 T lastOdfValue_ = T(0);
1410 int64_t lastOdfRef_ = 0;
1411 std::array<T, kNumRegisters> lastRegisters_ {};
1412 T lastLinear_ = T(0);
1413 T curLinear_ = T(0);
1414 T curPick_ = T(0);
1415 T curPersist_ = T(0);
1416 int pickLag_ = 2;
1417 std::array<T, kNumRegisters> curRegisters_ {};
1418 T lastConfirmOdf_ = T(0);
1419 int64_t lastOnsetFrame_ = -kBig;
1420
1421 // Streaming counters.
1422 int writePos_ = 0;
1423 int hopCounter_ = 0;
1424 int64_t totalSamples_ = 0;
1425
1426 // Pending-onset ring (held from detection to report point).
1427 std::vector<PendingOnset> pending_;
1428 int pendingHead_ = 0;
1429 int pendingCount_ = 0;
1430
1431 // Release test: frame energies and the causal peaks awaiting them.
1432 int energyBack_ = 2, energyAhead_ = 4;
1433 int energyHistLen_ = 12;
1434 std::vector<double> energyHist_;
1435 double curEnergy_ = 0.0;
1436 RegisterEnergy curRegisterEnergy_ {};
1437 std::vector<RegisterEnergy> registerEnergyHist_;
1438 std::array<int, detail::OnsetNovelty<T>::kNumRegisters + 1> registerEdge_ {};
1439 std::vector<T> persistHist_;
1440 int persistHistLen_ = 1;
1441 int contentHold_ = 0;
1442 int decideAhead_ = 4;
1443 std::vector<Candidate> candidates_;
1444 int candidateHead_ = 0;
1445 int candidateCount_ = 0;
1446
1447 // Atomic parameters / readouts.
1448 std::atomic<Method> method_ { Method::SuperFlux };
1449 std::atomic<T> threshold_ { kDefaultDelta };
1450 std::atomic<bool> whitening_ { false };
1451 std::atomic<bool> linearFlux_ { false };
1452 std::atomic<Picker> picker_ { Picker::Gated };
1453 std::atomic<bool> onsetLatched_ { false };
1454 std::atomic<T> onsetStrength_ { T(0) };
1455 std::atomic<int64_t> lastOnsetSample_ { -1 };
1456 std::atomic<int64_t> latencySamples_ { 2269 };
1457
1458 // Offline session (beginOffline() .. finishOffline()).
1459 std::vector<T> offOdf_;
1460 std::vector<T> offPick_;
1461 std::vector<int64_t> offRef_;
1462 std::vector<double> offEnergy_;
1463 std::vector<RegisterEnergy> offRegisterEnergy_;
1464 std::vector<T> offPersist_;
1465 std::vector<T> offContent_;
1466 int64_t offTotal_ = 0;
1467 int offHop_ = 0;
1468 Method offMethod_ = Method::SuperFlux;
1469 bool offWhiten_ = false;
1470 bool offlineOpen_ = false;
1471};
1472
1473} // namespace dspark
Non-owning view over audio channel data.
Definition AudioBuffer.h:53
int getNumSamples() const noexcept
Returns the number of samples per channel.
int getNumChannels() const noexcept
Returns the number of channels in this view.
T * getChannel(int ch) const noexcept
Returns a pointer to the sample data for the given channel.
Causal SuperFlux onset detector with lock-free readout.
void setLinearFlux(bool on) noexcept
Also computes the linear-magnitude spectral flux into OdfFrame::linear under SuperFlux (default off)....
int64_t getLastOnsetSample() const noexcept
Reference sample index (frame centre) of the most recent onset. The latch fires exactly getLatencySam...
void pushSamples(std::span< const T > samples) noexcept
Feeds a mono stream of samples. Lock-free, allocation-free.
std::vector< Onset > detectOfflineOnsets(AudioBufferView< const T > whole)
detectOffline() with each onset's strength alongside its position.
int getEnvelopeLatencySamples() const noexcept
How far behind the newest input sample a frame's reference sample sits, in samples.
void processBlock(AudioBufferView< const T > in) noexcept
Feeds a mono block; reads channel 0 only. Const, never mutated.
Picker getPicker() const noexcept
Peak-picking rule in force.
bool onsetDetected() const noexcept
True if an onset was reported during the most recent call.
void setThreshold(T deltaAboveMean) noexcept
Sets the adaptive peak-pick delta (margin above the moving mean). Non-finite values are ignored; nega...
bool computesBinPhases() const noexcept
True when the last analysis frame computed bin phases. Only ComplexDomain reads them; stream owner,...
bool getAdaptiveWhitening() const noexcept
True when adaptive whitening is on.
void reset() noexcept
Clears all streaming state and abandons an open offline session. Not concurrent with pushSamples().
int getNumBands() const noexcept
Number of log-frequency filterbank bands built for the resolved frame; a direct readout of the analys...
std::vector< int64_t > finishOffline()
Closes the session and returns onset positions, as detectOffline(). Empty when no session is open.
T getOnsetStrength() const noexcept
Onset strength of the most recent reported onset: the value of the function the picker reads (the env...
void beginOffline(int64_t expectedSamples=0)
Opens an incremental offline analysis.
void setAdaptiveWhitening(bool on) noexcept
Enables Stowell-Plumbley adaptive whitening (default off).
void prepare(const AudioSpec &spec, int fftSize=0, int hop=0)
Allocates all state and configures the STFT front-end.
int getWarmupFrames() const noexcept
Frames at the start of a stream whose ODF value is warm-up, not signal.
void setPicker(Picker picker) noexcept
Selects the peak-picking rule. Lock-free.
OdfFrame getLastOdfFrame() const noexcept
The most recent analysis frame's onset-strength value.
Picker
Peak-picking rule. Default Gated.
int getLatencySamples() const noexcept
The single causal reporting latency, L = fftSize + hop (samples).
T getThreshold() const noexcept
Peak-pick delta in force, after setThreshold()'s clamping.
bool getLinearFlux() const noexcept
True when OdfFrame::linear is computed under SuperFlux.
void setMethod(Method m) noexcept
Selects the ODF family. Lock-free.
std::vector< Onset > finishOfflineOnsets()
Closes the session and returns onsets with their strengths.
void pushOffline(std::span< const T > samples)
Feeds the next piece of an offline session. No-op outside one.
Method getMethod() const noexcept
ODF family in force.
std::vector< int64_t > detectOffline(AudioBufferView< const T > whole)
Offline detection over a whole mono buffer (channel 0).
Method
Onset-detection function family. Default SuperFlux.
int getFftSize() const noexcept
Analysis frame in samples actually in effect: the automatic choice when prepare() got fftSize <= 0,...
static constexpr int kNumRegisters
One frame of the onset-strength envelope (the ODF before the peak picker).
int getHopSize() const noexcept
Hop in samples in effect (round(fs/200) unless overridden).
Shared whitening, spectral/complex flux and SuperFlux feature history.
Allocation-free symmetric novelty peak picker with an explicit frame clock.
bool accept(std::size_t index, std::size_t count, Value value, Windows windows, T delta)
Examines increasing indices in an immutable, finite novelty sequence. The accessor returns T....
static int defaultFrameSize(double sampleRate) noexcept
float sumOfSquares(const float *DSPARK_RESTRICT data, int count) noexcept
Returns the sum of squared samples (energy).
Definition SimdOps.h:1213
Main namespace for the DSPark framework.
Describes the audio environment for a DSP processor.
Definition AudioSpec.h:37
double sampleRate
Sample rate in Hz.
Definition AudioSpec.h:45
int64_t referenceSample
Sample index the frame localises to.
T value
ODF value of the most recent frame.
std::array< T, kNumRegisters > registers
One offline onset: where it is and how strong it was.
int64_t sample
Reference sample (frame centre).
T strength
Picked function at the peak, as getOnsetStrength() reports it.