DSPark 1.9.0
Header-only C++20 DSP for real-time and offline audio
Loading...
Searching...
No Matches
OnsetFeatures.h
1// DSPark - Professional Audio DSP Framework
2// Copyright (c) 2026 Cristian Moresi - MIT License
3
4#pragma once
5
17#include "../../Core/AudioBuffer.h"
18#include "../../Core/DspMath.h"
19#include "../../Core/FFT.h"
20#include "../../Core/WindowFunctions.h"
21#include <algorithm>
22#include <array>
23#include <cmath>
24#include <cstddef>
25#include <memory>
26#include <span>
27#include <vector>
28
29namespace dspark::detail
30{
31
34template <FloatType T> class OnsetPeakPicker final
35{
36 public:
37 struct Windows
38 {
39 std::size_t preMaximum = 0, postMaximum = 0;
40 std::size_t preAverage = 0, postAverage = 0;
41 std::size_t wait = 0;
42 };
49 template <typename Value>
50 [[nodiscard]] bool accept(std::size_t index, std::size_t count, Value value, Windows windows,
51 T delta)
52 {
53 return accept(index, count, value, windows, delta, T(1), [](std::size_t, T) { return true; });
54 }
70 template <typename Value, typename Gate>
71 [[nodiscard]] bool accept(std::size_t index, std::size_t count, Value value, Windows windows,
72 T delta, T meanScale, Gate gate)
73 {
74 if (index >= count || (hasLast_ && (index <= last_ || index - last_ <= windows.wait)))
75 return false;
76 const T current = value(index);
77 const auto fromMax = index - std::min(index, windows.preMaximum);
78 const auto toMax = index + std::min(count - index - 1, windows.postMaximum);
79 for (auto j = fromMax; j <= toMax; ++j)
80 if (value(j) > current)
81 return false;
82 const auto fromAvg = index - std::min(index, windows.preAverage);
83 const auto toAvg = index + std::min(count - index - 1, windows.postAverage);
84 T sum = T(0);
85 for (auto j = fromAvg; j <= toAvg; ++j)
86 sum += value(j);
87 const T mean = sum / static_cast<T>(toAvg - fromAvg + 1);
88 const T threshold = meanScale * mean + delta;
89 if (current < threshold || !gate(index, current - threshold))
90 return false;
91 last_ = index;
92 hasLast_ = true;
93 return true;
94 }
95
96 private:
97 std::size_t last_ = 0;
98 bool hasLast_ = false;
99};
100
102template <FloatType T> class OnsetSpectrum final
103{
104 public:
105 [[nodiscard]] static int defaultFrameSize(double sampleRate) noexcept
106 {
107 int size = 512;
108 const double target = sampleRate * (2048.0 / 48000.0);
109 while (size < 16384 && static_cast<double>(size) < target)
110 size <<= 1;
111 return size;
112 }
115 [[nodiscard]] static std::size_t preparationBytes(int fftSize) noexcept
116 {
117 // Five frontend arrays: 4*N+4 scalars; the FFT reports its own
118 // requests. The 2048-byte allowance covers construction temporaries.
119 return (4 * static_cast<std::size_t>(fftSize) + 4) * sizeof(T) +
120 FFTReal<T>::allocationBytes(static_cast<std::size_t>(fftSize)) + sizeof(FFTReal<T>) +
121 2048;
122 }
125 void prepare(int fftSize)
126 {
127 fft_.reset();
128 phaseValid_ = false;
129 fftSize_ = fftSize;
130 window_.assign(static_cast<size_t>(fftSize_), T(0));
131 WindowFunctions<T>::hann(window_.data(), fftSize_, true);
132 time_.assign(static_cast<size_t>(fftSize_), T(0));
133 spectrum_.assign(static_cast<size_t>(fftSize_) + 2, T(0));
134 magnitude_.assign(static_cast<size_t>(fftSize_ / 2 + 1), T(0));
135 phase_.assign(magnitude_.size(), T(0));
136 fft_ = std::make_unique<FFTReal<T>>(static_cast<size_t>(fftSize_));
137 }
144 void compute(const T *input, bool withPhase = true) noexcept
145 {
146 if (!fft_)
147 return;
148 transform(input);
149 for (size_t k = 0; k < magnitude_.size(); ++k)
150 {
151 const T re = spectrum_[2 * k], im = spectrum_[2 * k + 1];
152 magnitude_[k] = binMagnitude(k);
153 if (withPhase)
154 phase_[k] = std::atan2(im, re);
155 }
156 phaseValid_ = withPhase;
157 }
166 [[nodiscard]] bool computePooled(AudioBufferView<const T> frame) noexcept
167 {
168 phaseValid_ = false;
169 if (!fft_ || frame.getNumSamples() != fftSize_ || frame.getNumChannels() < 1 ||
170 frame.getNumChannels() > 2)
171 return false;
172 for (int c = 0; c < frame.getNumChannels(); ++c)
173 if (!frame.getChannel(c))
174 return false;
175 compute(frame.getChannel(0), false);
176 if (frame.getNumChannels() == 2)
177 {
178 transform(frame.getChannel(1));
179 for (size_t k = 0; k < magnitude_.size(); ++k)
180 {
181 const T other = binMagnitude(k);
182 if (magnitude_[k] != other)
183 magnitude_[k] = std::hypot(magnitude_[k], other) * invSqrt2<T>;
184 }
185 }
186 return true;
187 }
190 [[nodiscard]] std::span<T> magnitudes() noexcept
191 {
192 return magnitude_;
193 }
196 [[nodiscard]] std::span<const T> phases() const noexcept
197 {
198 return phaseValid_ ? std::span<const T>(phase_) : std::span<const T>();
199 }
200
201 private:
202 void transform(const T *input) noexcept
203 {
204 for (int k = 0; k < fftSize_; ++k)
205 time_[static_cast<size_t>(k)] = input[k] * window_[static_cast<size_t>(k)];
206 fft_->forward(time_.data(), spectrum_.data());
207 }
208 [[nodiscard]] T binMagnitude(size_t k) const noexcept
209 {
210 const T re = spectrum_[2 * k], im = spectrum_[2 * k + 1];
211 return std::sqrt(re * re + im * im);
212 }
213 int fftSize_ = 0;
214 bool phaseValid_ = false;
215 std::unique_ptr<FFTReal<T>> fft_;
216 std::vector<T> window_, time_, spectrum_, magnitude_, phase_;
217};
218
221template <FloatType T> class OnsetNovelty final
222{
223 public:
224 enum class Method
225 {
228 SuperFlux,
230 };
231 static constexpr int kNumRegisters = 4;
232 struct Frame
233 {
234 T value = T(0);
235 T spectralFlux = T(0);
238 T pick = T(0);
242 T persist = T(0);
246 T linear = T(0);
247 std::array<T, kNumRegisters> registers{};
248 bool valid = false;
249 };
252 [[nodiscard]] static std::size_t preparationBytes(int fftSize) noexcept
253 {
254 return (3 * static_cast<std::size_t>(fftSize) + 4 + 4 * kBandCapacity) * sizeof(T) +
255 5 * kBandCapacity * sizeof(int);
256 }
285 void prepare(double sampleRate, int fftSize, bool boundedWorkspace = false, int pickLag = 1,
286 int persistLag = 0, int persistSpan = 1, int contentBack = 0, int contentAhead = 0,
287 int contentHold = 0, int contentSpan = 1)
288 {
289 prepared_ = false;
290 sampleRate_ = sampleRate;
291 fftSize_ = fftSize;
292 numBins_ = fftSize / 2 + 1;
293 odfScale_ = static_cast<T>(kOdfRefFrame / static_cast<double>(fftSize_));
294 prevPhase_.assign(static_cast<size_t>(numBins_), T(0));
295 prevPhase2_.assign(static_cast<size_t>(numBins_), T(0));
296 prevMag_.assign(static_cast<size_t>(numBins_), T(0));
297 whitenPeak_.assign(static_cast<size_t>(numBins_), T(0));
298 buildFilterBank(boundedWorkspace);
299 bandCur_.assign(static_cast<size_t>(numBands_), T(0));
300 bandPrev_.assign(static_cast<size_t>(numBands_), T(0));
301 bandMaxPrev_.assign(static_cast<size_t>(numBands_), T(0));
302 pickLag_ = std::max(1, pickLag);
303 persistLag_ = std::max(0, persistLag);
304 persistSpan_ = std::max(1, persistSpan);
305 historyFrames_ = (pickLag_ > 1 || persistLag_ > 0)
306 ? std::max(pickLag_, persistLag_ + persistSpan_ - 1) : 0;
307 maxHistory_.assign(static_cast<size_t>(historyFrames_) * static_cast<size_t>(numBands_), T(0));
308 spanMax_.assign(persistSpan_ > 1 ? static_cast<size_t>(numBands_) : size_t(0), T(0));
309 contentBack_ = std::max(0, contentBack);
310 contentAhead_ = std::max(0, contentAhead);
311 contentHold_ = contentHold > contentAhead_ ? contentHold : 0;
312 contentSpan_ = std::max(1, contentSpan);
313 contentFrames_ = contentHold_ > 0 ? contentHold_ + contentBack_ + contentSpan_ : 0;
314 contentRing_.assign(static_cast<size_t>(contentFrames_) * static_cast<size_t>(numBands_), T(0));
315 bandAmp_.assign(contentHold_ > 0 ? static_cast<size_t>(numBands_) : size_t(0), T(0));
316 contentBefore_.assign(bandAmp_.size(), T(0));
317 reset();
318 prepared_ = true;
319 }
322 void reset() noexcept
323 {
324 std::fill(prevMag_.begin(), prevMag_.end(), T(0));
325 std::fill(prevPhase_.begin(), prevPhase_.end(), T(0));
326 std::fill(prevPhase2_.begin(), prevPhase2_.end(), T(0));
327 std::fill(whitenPeak_.begin(), whitenPeak_.end(), T(0));
328 std::fill(bandPrev_.begin(), bandPrev_.end(), T(0));
329 std::fill(bandMaxPrev_.begin(), bandMaxPrev_.end(), T(0));
330 std::fill(maxHistory_.begin(), maxHistory_.end(), T(0));
331 std::fill(contentRing_.begin(), contentRing_.end(), T(0));
332 historyWrite_ = 0;
333 contentWrite_ = 0;
334 curPick_ = T(0);
335 curPersist_ = T(0);
336 curRegisters_.fill(T(0));
337 phaseHistoryValid_ = true;
338 }
339 [[nodiscard]] int getNumBands() const noexcept
340 {
341 return numBands_;
342 }
359 [[nodiscard]] T contentShare() noexcept
360 {
361 if (contentHold_ <= 0)
362 return T(0);
363 const int frames = contentFrames_;
364 const int newest = (contentWrite_ - 1 + frames) % frames;
365 const size_t nb = static_cast<size_t>(numBands_);
366 const auto frameAt = [&](int back) {
367 return &contentRing_[static_cast<size_t>((newest - back + frames) % frames) * nb];
368 };
369 std::fill(contentBefore_.begin(), contentBefore_.end(), T(0));
370 for (int q = 0; q < contentSpan_; ++q)
371 {
372 const T *f = frameAt(contentHold_ + contentBack_ + q);
373 for (size_t b = 0; b < nb; ++b)
374 {
375 T m = f[b];
376 if (b > 0) m = std::max(m, f[b - 1]);
377 if (b + 1 < nb) m = std::max(m, f[b + 1]);
378 contentBefore_[b] = std::max(contentBefore_[b], m);
379 }
380 }
381 const T *after = frameAt(contentHold_ - contentAhead_);
382 const T *held = frameAt(0);
383 double total = 0.0, grown = 0.0;
384 for (size_t b = 0; b < nb; ++b)
385 {
386 total += static_cast<double>(after[b]);
387 if (after[b] > T(kContentGain) * contentBefore_[b])
388 grown += static_cast<double>(std::min(after[b], held[b]));
389 }
390 return total > 0.0 ? static_cast<T>(grown / total) : T(0);
391 }
394 void setLinearFlux(bool on) noexcept
395 {
396 linearFlux_ = on;
397 }
405 [[nodiscard]] Frame process(std::span<T> mag, std::span<const T> phase, Method method,
406 bool whiten = false) noexcept
407 {
408 Frame result;
409 if (!prepared_ || mag.size() != static_cast<size_t>(numBins_) ||
410 (!phase.empty() && phase.size() != mag.size()) ||
411 (method == Method::ComplexDomain && (phase.empty() || !phaseHistoryValid_)))
412 return result;
413 // The new-content share reads the raw band energies, as the frame
414 // energies of the release test do: whitening rewrites the magnitudes.
415 // Frames of the other functions store silence, so the ring stays
416 // aligned with the frames and reads no growth across them.
417 const bool content = contentHold_ > 0 && (method == Method::SuperFlux || method == Method::BothFlux);
418 if (content && whiten)
419 rawBandAmplitudes(mag);
420 if (whiten)
421 applyWhitening(mag);
422 curRegisters_.fill(T(0));
423 switch (method)
424 {
426 result.value = result.spectralFlux = computeSpectralFlux(mag);
427 break;
429 result.value = computeComplexFlux(mag, phase);
430 break;
431 case Method::BothFlux:
432 result.spectralFlux = computeSpectralFlux(mag);
433 [[fallthrough]];
435 result.value = computeSuperFlux(mag, whiten);
436 result.pick = curPick_;
437 result.persist = curPersist_;
438 if (linearFlux_)
439 result.linear = computeLinearFlux(mag);
440 break;
441 }
442 if (contentHold_ > 0)
443 storeContentFrame(content);
444 if (method != Method::SuperFlux && method != Method::BothFlux)
445 result.pick = result.value;
446 if (!phase.empty())
447 {
448 std::copy(prevPhase_.begin(), prevPhase_.end(), prevPhase2_.begin());
449 std::copy(phase.begin(), phase.end(), prevPhase_.begin());
450 }
451 else
452 phaseHistoryValid_ = false;
453 std::copy(mag.begin(), mag.end(), prevMag_.begin());
454 result.registers = curRegisters_;
455 result.valid = true;
456 return result;
457 }
458
459 private:
460 T computeSpectralFlux(std::span<const T> mag) const noexcept
461 {
462 T odf = T(0);
463 for (int k = 0; k < numBins_; ++k)
464 {
465 const T d = mag[static_cast<size_t>(k)] - prevMag_[static_cast<size_t>(k)];
466 if (d > T(0))
467 odf += d;
468 }
469 odf /= static_cast<T>(numBins_);
470 return odf;
471 }
474 T computeLinearFlux(std::span<const T> mag) const noexcept
475 {
476 T acc[4] = {T(0), T(0), T(0), T(0)};
477 const T *cur = mag.data();
478 const T *prev = prevMag_.data();
479 int k = 0;
480 for (; k + 4 <= numBins_; k += 4)
481 for (int j = 0; j < 4; ++j)
482 acc[j] += std::max(T(0), cur[k + j] - prev[k + j]);
483 for (; k < numBins_; ++k)
484 acc[0] += std::max(T(0), cur[k] - prev[k]);
485 return ((acc[0] + acc[1]) + (acc[2] + acc[3])) / static_cast<T>(numBins_);
486 }
487 T computeComplexFlux(std::span<const T> mag, std::span<const T> phase) const noexcept
488 {
489 T odf = T(0);
490 // Rectified complex-domain deviation (Dixon 2006): phase-predict
491 // each bin, sum |X - Xhat| where magnitude increased.
492 for (int k = 0; k < numBins_; ++k)
493 {
494 const T target = princArg(T(2) * prevPhase_[static_cast<size_t>(k)] -
495 prevPhase2_[static_cast<size_t>(k)]);
496 const T pm = prevMag_[static_cast<size_t>(k)];
497 const T cm = mag[static_cast<size_t>(k)];
498 const T re = cm * std::cos(phase[static_cast<size_t>(k)]) - pm * std::cos(target);
499 const T im = cm * std::sin(phase[static_cast<size_t>(k)]) - pm * std::sin(target);
500 if (cm >= pm)
501 odf += std::sqrt(re * re + im * im);
502 }
503 odf /= static_cast<T>(numBins_);
504 return odf;
505 }
506 T computeSuperFlux(std::span<const T> mag, bool whiten) noexcept
507 {
508 T odf = T(0);
509 // Log-filtered magnitude bands, flux to the mu-th previous
510 // frame after a frequency maximum filter on the reference.
511 // The frame-invariant magnitude scale (kOdfRefFrame/fftSize)
512 // applies to the raw spectrum only: adaptive whitening
513 // already divides each bin by its running peak, which
514 // carries the same linear-in-N growth, so above kWhitenFloor
515 // the whitened spectrum is dimensionless and scaling it
516 // again would INVERT the rate dependence instead of removing
517 // it. Below the floor the divisor is the absolute constant
518 // kWhitenFloor, so those bins keep the linear-in-N growth --
519 // the residual rate dependence documented at prepare().
520 filterLogBands(mag, bandCur_, whiten ? T(1) : odfScale_,
521 contentHold_ > 0 && !whiten ? bandAmp_.data() : nullptr);
522 curRegisters_.fill(T(0));
523 // Branch free (a rise and a fall are equally likely band by band);
524 // adding the zero of a fall leaves both sums exactly as they were.
525 const int registered = std::min(numBands_, static_cast<int>(bandRegister_.size()));
526 for (int b = 0; b < registered; ++b)
527 {
528 const T d = std::max(T(0), bandCur_[static_cast<size_t>(b)] - bandMaxPrev_[static_cast<size_t>(b)]);
529 odf += d;
530 curRegisters_[static_cast<size_t>(bandRegister_[static_cast<size_t>(b)])] += d;
531 }
532 for (int b = registered; b < numBands_; ++b)
533 odf += std::max(T(0), bandCur_[static_cast<size_t>(b)] - bandMaxPrev_[static_cast<size_t>(b)]);
534 odf /= static_cast<T>(numBands_);
535 for (int g = 0; g < kNumRegisters; ++g)
536 if (registerBands_[static_cast<size_t>(g)] > 0)
537 curRegisters_[static_cast<size_t>(g)] /=
538 static_cast<T>(registerBands_[static_cast<size_t>(g)]);
539 curPick_ = pickLag_ > 1 ? fluxTo(pickLag_, 1) : odf;
540 curPersist_ = persistLag_ > 0 ? fluxTo(persistLag_, persistSpan_) : T(0);
541 // Rotate: previous <- current, and rebuild the max-filtered
542 // reference from the (new) previous frame.
543 bandPrev_ = bandCur_;
544 maxFilterFreq(bandPrev_, bandMaxPrev_);
545 if (historyFrames_ > 0)
546 {
547 std::copy(bandMaxPrev_.begin(), bandMaxPrev_.end(),
548 maxHistory_.begin() + static_cast<std::ptrdiff_t>(
549 static_cast<size_t>(historyWrite_) * static_cast<size_t>(numBands_)));
550 historyWrite_ = (historyWrite_ + 1) % historyFrames_;
551 }
552 return odf;
553 }
557 [[nodiscard]] T fluxTo(int lag, int span) noexcept
558 {
559 const auto frameAt = [&](int back) {
560 const int slot = ((historyWrite_ - back) % historyFrames_ + historyFrames_) % historyFrames_;
561 return &maxHistory_[static_cast<size_t>(slot) * static_cast<size_t>(numBands_)];
562 };
563 const T *ref = bandMaxPrev_.data();
564 if (span > 1)
565 {
566 const T *first = frameAt(lag);
567 std::copy(first, first + numBands_, spanMax_.begin());
568 for (int q = 1; q < span; ++q)
569 {
570 const T *f = frameAt(lag + q);
571 for (int b = 0; b < numBands_; ++b)
572 spanMax_[static_cast<size_t>(b)] = std::max(spanMax_[static_cast<size_t>(b)], f[b]);
573 }
574 ref = spanMax_.data();
575 }
576 else if (lag > 1)
577 ref = frameAt(lag);
578 // Branch free: a rise and a fall are equally likely band by band.
579 // Adding the zero of a fall leaves the sum exactly as it was.
580 T sum = T(0);
581 for (int b = 0; b < numBands_; ++b)
582 sum += std::max(T(0), bandCur_[static_cast<size_t>(b)] - ref[b]);
583 return sum / static_cast<T>(numBands_);
584 }
585 void applyWhitening(std::span<T> mag) noexcept
586 {
587 for (int k = 0; k < numBins_; ++k)
588 {
589 T &pk = whitenPeak_[static_cast<size_t>(k)];
590 const T decayed = pk * kWhitenDecay;
591 const T m = mag[static_cast<size_t>(k)];
592 pk = std::max({m, kWhitenFloor, decayed});
593 mag[static_cast<size_t>(k)] = m / pk;
594 }
595 }
596
597 void buildFilterBank(bool boundedWorkspace)
598 {
599 fbStart_.clear();
600 fbWeights_.clear();
601 fbOffset_.clear();
602 bandRegister_.clear();
603 registerBands_.fill(0);
604
605 const double binHz = sampleRate_ / static_cast<double>(fftSize_);
606 const double fMax = std::min(kFMaxHz, sampleRate_ * 0.5 * 0.999);
607
608 // Quarter-tone centre bins, strictly increasing and unique.
609 std::vector<int> centres;
610 if (boundedWorkspace)
611 {
612 // At most 221 quarter-tone centres between 27.5 and 16000 Hz.
613 // Consecutive triangles contain at most N + centres weights.
614 // Reserving these bounds avoids data-dependent vector growth in
615 // worker jobs whose allocation payload is checked before setup.
616 centres.reserve(kBandCapacity);
617 fbStart_.reserve(kBandCapacity);
618 fbOffset_.reserve(kBandCapacity);
619 fbCount_.reserve(kBandCapacity);
620 bandRegister_.reserve(kBandCapacity);
621 fbWeights_.reserve(static_cast<size_t>(fftSize_) + kBandCapacity);
622 }
623 for (int i = 0;; ++i)
624 {
625 const double f = kFMin * std::pow(2.0, static_cast<double>(i) /
626 static_cast<double>(kBandsPerOctave));
627 if (f > fMax)
628 break;
629 int bin = static_cast<int>(std::lround(f / binHz));
630 bin = std::clamp(bin, 0, numBins_ - 1);
631 if (centres.empty() || bin > centres.back())
632 centres.push_back(bin);
633 }
634
635 // Triangular filters over consecutive triples (b[j-1], b[j], b[j+1]).
636 numBands_ = 0;
637 for (size_t j = 1; j + 1 < centres.size(); ++j)
638 {
639 const int lo = centres[j - 1];
640 const int ce = centres[j];
641 const int hi = centres[j + 1];
642 if (!(lo < ce && ce < hi))
643 continue;
644
645 {
646 const double fc = static_cast<double>(ce) * binHz;
647 const int g = fc < 200.0 ? 0 : fc < 800.0 ? 1 : fc < 3200.0 ? 2 : 3;
648 bandRegister_.push_back(g);
649 ++registerBands_[static_cast<size_t>(g)];
650 }
651 fbStart_.push_back(lo);
652 fbOffset_.push_back(static_cast<int>(fbWeights_.size()));
653 for (int k = lo; k <= hi; ++k)
654 {
655 T wv;
656 if (k <= ce)
657 wv = static_cast<T>(static_cast<double>(k - lo) / static_cast<double>(ce - lo));
658 else
659 wv = static_cast<T>(static_cast<double>(hi - k) / static_cast<double>(hi - ce));
660 fbWeights_.push_back(wv);
661 }
662 ++numBands_;
663 }
664 fbCount_.clear();
665 for (int b = 0; b < numBands_; ++b)
666 {
667 const int off = fbOffset_[static_cast<size_t>(b)];
668 const int nextOff = (b + 1 < numBands_) ? fbOffset_[static_cast<size_t>(b + 1)]
669 : static_cast<int>(fbWeights_.size());
670 fbCount_.push_back(nextOff - off);
671 }
672 if (numBands_ < 1)
673 numBands_ = 1; // degenerate guard (tiny fftSize)
674 }
675
678 void filterLogBands(std::span<const T> mag, std::vector<T> &out, T scale, T *raw = nullptr) noexcept
679 {
680 for (int b = 0; b < numBands_ && b < static_cast<int>(fbStart_.size()); ++b)
681 {
682 const T acc = bandAmplitude(mag, b);
683 if (raw)
684 raw[b] = acc;
685 out[static_cast<size_t>(b)] = std::log10(acc * scale + T(1));
686 }
687 }
688
690 [[nodiscard]] T bandAmplitude(std::span<const T> mag, int b) const noexcept
691 {
692 const int start = fbStart_[static_cast<size_t>(b)];
693 const int off = fbOffset_[static_cast<size_t>(b)];
694 const int cnt = fbCount_[static_cast<size_t>(b)];
695 T acc = T(0);
696 for (int i = 0; i < cnt; ++i)
697 {
698 const int k = start + i;
699 if (k >= 0 && k < numBins_)
700 acc += mag[static_cast<size_t>(k)] * fbWeights_[static_cast<size_t>(off + i)];
701 }
702 return acc;
703 }
704
706 void rawBandAmplitudes(std::span<const T> mag) noexcept
707 {
708 for (int b = 0; b < numBands_ && b < static_cast<int>(fbStart_.size()); ++b)
709 bandAmp_[static_cast<size_t>(b)] = bandAmplitude(mag, b);
710 }
711
714 void storeContentFrame(bool bands) noexcept
715 {
716 const size_t nb = static_cast<size_t>(numBands_);
717 T *cur = &contentRing_[static_cast<size_t>(contentWrite_) * nb];
718 for (size_t b = 0; b < nb; ++b)
719 {
720 const T a = bands && b < bandAmp_.size() ? bandAmp_[b] : T(0);
721 cur[b] = a * a;
722 }
723 contentWrite_ = (contentWrite_ + 1) % contentFrames_;
724 }
725
726 void maxFilterFreq(const std::vector<T> &in, std::vector<T> &out) const noexcept
727 {
728 for (int b = 0; b < numBands_; ++b)
729 {
730 T mx = in[static_cast<size_t>(b)];
731 if (b > 0)
732 mx = std::max(mx, in[static_cast<size_t>(b - 1)]);
733 if (b + 1 < numBands_)
734 mx = std::max(mx, in[static_cast<size_t>(b + 1)]);
735 out[static_cast<size_t>(b)] = mx;
736 }
737 }
738
739 static T princArg(T x) noexcept
740 {
741 // Wrap to (-pi, pi].
742 const T twoPiT = twoPi<T>;
743 T y = x - twoPiT * std::floor(x / twoPiT + T(0.5));
744 return y;
745 }
746
747 static constexpr double kOdfRefFrame = 2048.0;
748 static constexpr double kFMin = 27.5;
749 static constexpr double kFMaxHz = 16000.0;
750 static constexpr int kBandsPerOctave = 24;
751 static constexpr std::size_t kBandCapacity = 256;
752 static constexpr T kWhitenDecay = T(0.9995), kWhitenFloor = T(1e-4);
755 static constexpr double kContentGain = 4.0;
756 double sampleRate_ = 44100;
757 int fftSize_ = 0, numBins_ = 0, numBands_ = 1;
758 bool phaseHistoryValid_ = true;
759 bool prepared_ = false;
760 T odfScale_ = T(1);
761 std::vector<T> prevPhase_, prevPhase2_, prevMag_, whitenPeak_;
762 std::vector<int> fbStart_, fbOffset_, fbCount_, bandRegister_;
763 std::vector<T> fbWeights_, bandCur_, bandPrev_, bandMaxPrev_;
764 std::array<T, kNumRegisters> curRegisters_{};
765 std::array<int, kNumRegisters> registerBands_{};
766 int pickLag_ = 1, persistLag_ = 0, persistSpan_ = 1;
767 bool linearFlux_ = false;
768 int historyFrames_ = 0, historyWrite_ = 0;
769 std::vector<T> maxHistory_;
770 std::vector<T> spanMax_;
771 int contentBack_ = 0, contentAhead_ = 0, contentHold_ = 0;
772 int contentFrames_ = 0, contentWrite_ = 0;
773 int contentSpan_ = 1;
774 std::vector<T> contentRing_;
775 std::vector<T> contentBefore_;
776 std::vector<T> bandAmp_;
777 T curPick_ = T(0), curPersist_ = T(0);
778};
779
780} // namespace dspark::detail
Non-owning view over audio channel data.
Definition AudioBuffer.h:53
FFT optimised for real-valued input signals (the common audio case).
Definition FFT.h:1197
Shared whitening, spectral/complex flux and SuperFlux feature history.
static std::size_t preparationBytes(int fftSize) noexcept
Setup payload allowance when prepare() reserves the bounded filterbank.
void setLinearFlux(bool on) noexcept
Computes Frame::linear alongside SuperFlux. Allocation free.
static constexpr int kNumRegisters
T contentShare() noexcept
New-content share of the frame contentHold back from the last processed one (prepare()); zero when no...
void prepare(double sampleRate, int fftSize, bool boundedWorkspace=false, int pickLag=1, int persistLag=0, int persistSpan=1, int contentBack=0, int contentAhead=0, int contentHold=0, int contentSpan=1)
Allocates histories and the canonical quarter-tone filterbank.
Frame process(std::span< T > mag, std::span< const T > phase, Method method, bool whiten=false) noexcept
Advances one frame; optional whitening modifies the supplied magnitudes. Phase-less frames support Sp...
void reset() noexcept
Clears feature history without allocation or changing the filterbank.
int getNumBands() const noexcept
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, T meanScale, Gate gate)
accept() with the moving mean scaled and a final veto. The veto is consulted only for a candidate tha...
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....
Reusable periodic-Hann real spectrum, without feature history.
void prepare(int fftSize)
Allocates a valid power-of-two frame; the caller owns frame timing.
void compute(const T *input, bool withPhase=true) noexcept
Evaluates one contiguous frame, optionally including bin phases. Input is finite and scaled by the ca...
static int defaultFrameSize(double sampleRate) noexcept
static std::size_t preparationBytes(int fftSize) noexcept
Conservative setup payload allowance for a fresh power-of-two instance.
std::span< T > magnitudes() noexcept
Borrowed scratch, valid until the next compute/prepare or destruction.
bool computePooled(AudioBufferView< const T > frame) noexcept
Pools mono/stereo spectral energy without a phase-cancelling downmix. The view must contain exactly o...
std::span< const T > phases() const noexcept
Empty when the last frame did not compute phases. Same scratch lifetime.
static void hann(T *output, int size, bool periodic=true) noexcept
Hann (raised cosine) window.
std::array< T, kNumRegisters > registers
T value
Requested function; SuperFlux when BothFlux is requested.
std::size_t wait
Selected indices must be more than wait frames apart.