DSPark 1.9.0
Header-only C++20 DSP for real-time and offline audio
Loading...
Searching...
No Matches
SpectrumAnalyzer.h
1// DSPark - Professional Audio DSP Framework
2// Copyright (c) 2026 Cristian Moresi - MIT License
3
4#pragma once
5
70#include "../Core/AuditoryBands.h"
71#include "../Core/DspMath.h"
72#include "../Core/FFT.h"
73#include "../Core/WindowFunctions.h"
74
75#include <algorithm>
76#include <array>
77#include <atomic>
78#include <cassert>
79#include <cmath>
80#include <cstddef>
81#include <memory>
82#include <type_traits>
83#include <vector>
84
85namespace dspark {
86
100template <FloatType T>
102{
103public:
105 enum class WindowType
106 {
107 Hann,
108 Hamming,
109 Blackman,
111 FlatTop,
114 };
115
168 void prepare(double sampleRate, int fftSize = 0, WindowType windowType = WindowType::Hann)
169 {
170 assert(fftSize <= 0 ||
171 (fftSize >= 256 && fftSize <= 16384 && (fftSize & (fftSize - 1)) == 0));
172
173 if (!std::isfinite(sampleRate) || sampleRate <= 0.0)
174 return;
175
176 if (fftSize <= 0)
177 {
178 // Automatic: hold the analysis TIME SPAN constant across sample
179 // rates (the span 2048 samples cover at 48 kHz). Bin width, main
180 // lobe and frame rate are all fs/fftSize up to a constant, so a
181 // constant span pins the resolution the display shows.
182 const double target = sampleRate * (kAutoSpanRef / kAutoSpanRate);
183 int n = kAutoMinFft;
184 while (n < kAutoMaxFft && static_cast<double>(n) < target) n <<= 1;
185 fftSize = n;
186 }
187
188 // Release-safe size sanitation (the assert only guards debug builds;
189 // an unvalidated size would make FFTReal throw at stream time).
190 fftSize = std::clamp(fftSize, 256, 16384);
191 int pow2 = 256;
192 while (pow2 < fftSize) pow2 <<= 1;
193 fftSize = pow2;
194
195 fft_.reset(); // gate OFF: pushSamples() is a no-op while rebuilding
196 // (and stays OFF if the allocation phase throws below)
197
198 const int numBins = fftSize / 2 + 1;
199 const T floorDb = floorDb_.load(std::memory_order_relaxed);
200
201 // --- Allocation phase. EVERYTHING is built into locals and no
202 // member is written until every allocation has succeeded, so
203 // a bad_alloc from any of them leaves the analyser exactly as it was
204 // (minus the fft_ gate above): sizes, slots and snapshots stay
205 // mutually consistent -- never NEW sizes over OLD storage.
206 std::vector<T> window(static_cast<size_t>(fftSize));
207 const WindowType effectiveWindow = generateWindow(window.data(), fftSize, windowType);
208
209 T windowGain = WindowFunctions<T>::coherentGain(window.data(), fftSize);
210 if (windowGain < T(0.001)) windowGain = T(1);
211 const T invGain = T(2) / (static_cast<T>(fftSize) * windowGain);
212
213 std::vector<T> inputRing(static_cast<size_t>(fftSize), T(0));
214 std::vector<T> fftBuffer(static_cast<size_t>(fftSize));
215 std::vector<T> freqBuffer(static_cast<size_t>(fftSize + 2));
216
217 // Unified DSP State
218 std::vector<T> magnitudesState(static_cast<size_t>(numBins), T(0));
219 std::vector<T> peakState(static_cast<size_t>(numBins), floorDb);
220
221 // Triple buffer for tear-free cross-thread reading (relaxed-atomic
222 // words; ordering comes from the pendingSlot_ RMWs and from each
223 // slot's own seqlock counter, see below).
224 std::array<OutSlot, 3> slots;
225 for (auto& slot : slots)
226 {
227 slot.magnitudesDb = std::make_unique<std::atomic<T>[]>(static_cast<size_t>(numBins));
228 slot.peakDb = std::make_unique<std::atomic<T>[]>(static_cast<size_t>(numBins));
229 slot.seq = std::make_unique<std::atomic<unsigned>>(0u);
230 for (int k = 0; k < numBins; ++k)
231 {
232 slot.magnitudesDb[static_cast<size_t>(k)].store(floorDb, std::memory_order_relaxed);
233 slot.peakDb[static_cast<size_t>(k)].store(floorDb, std::memory_order_relaxed);
234 }
235 }
236 // Reader-private snapshot storage backing the getter return pointers:
237 // TWO alternating numBins-sized halves per getter, so a copy that
238 // fails seqlock validation is discarded without disturbing the
239 // coherent snapshot the reader is still allowed to be holding.
240 std::vector<T> magSnapshot(static_cast<size_t>(2 * numBins), floorDb);
241 std::vector<T> peakSnapshot(static_cast<size_t>(2 * numBins), floorDb);
242
243 auto fft = std::make_unique<FFTReal<T>>(static_cast<size_t>(fftSize));
244
245 // --- Commit phase: moves and scalar stores only, all noexcept, so
246 // every size below matches its storage on every exit path (the
247 // getter/reset() loop bounds trust that invariant). Setup thread
248 // only (documented), so plain stores suffice. The "all noexcept"
249 // half of that claim is compiler-checked rather than asserted in
250 // prose: a throw BETWEEN two commits is the only way back to a
251 // half-committed shape (NEW sizes over OLD storage).
252 static_assert(std::is_nothrow_move_assignable_v<std::vector<T>> &&
253 std::is_nothrow_move_assignable_v<std::array<OutSlot, 3>> &&
254 std::is_nothrow_move_assignable_v<std::unique_ptr<FFTReal<T>>>,
255 "prepare()'s commit phase must be non-throwing");
256
257 sampleRate_ = sampleRate;
258 fftSize_ = fftSize;
259 numBins_ = numBins;
260 hopSize_ = fftSize / 2; // 50% overlap
261 windowType_ = effectiveWindow;
262 window_ = std::move(window);
263 windowGain_ = windowGain;
264 invGain_ = invGain;
265
266 inputRing_ = std::move(inputRing);
267 fftBuffer_ = std::move(fftBuffer);
268 freqBuffer_ = std::move(freqBuffer);
269 magnitudesState_ = std::move(magnitudesState);
270 peakState_ = std::move(peakState);
271
272 outSlots_ = std::move(slots);
273 magSnapshot_ = std::move(magSnapshot);
274 peakSnapshot_ = std::move(peakSnapshot);
275 magSnapshotHalf_ = 0;
276 peakSnapshotHalf_ = 0;
277 staleSnapshots_ = 0;
278 writeSlot_ = 0;
279 readSlot_ = 1;
280 pendingSlot_.store(2, std::memory_order_relaxed);
281
282 ringWritePos_ = 0;
283 ringMask_ = fftSize_ - 1; // power of two guaranteed by the sanitation
284 samplesUntilFFT_ = hopSize_;
285 newDataReady_.store(false, std::memory_order_relaxed);
286
287 fft_ = std::move(fft); // gate ON, last
288 }
289
297 void reset() noexcept
298 {
299 const T floorDb = floorDb_.load(std::memory_order_relaxed);
300 std::fill(inputRing_.begin(), inputRing_.end(), T(0));
301 std::fill(magnitudesState_.begin(), magnitudesState_.end(), T(0));
302 std::fill(peakState_.begin(), peakState_.end(), floorDb);
303
304 for (auto& slot : outSlots_)
305 {
306 // prepare() commits numBins_ and the slot arrays together (and
307 // numBins_ is 0 before the first successful prepare()), so this
308 // loop bound always matches the allocated storage.
309 for (int k = 0; k < numBins_; ++k)
310 {
311 slot.magnitudesDb[static_cast<size_t>(k)].store(floorDb, std::memory_order_relaxed);
312 slot.peakDb[static_cast<size_t>(k)].store(floorDb, std::memory_order_relaxed);
313 }
314 }
315 std::fill(magSnapshot_.begin(), magSnapshot_.end(), floorDb);
316 std::fill(peakSnapshot_.begin(), peakSnapshot_.end(), floorDb);
317
318 ringWritePos_ = 0;
319 samplesUntilFFT_ = hopSize_;
320 newDataReady_.store(false, std::memory_order_relaxed);
321 }
322
329 void setSmoothing(T factor) noexcept
330 {
331 if (!std::isfinite(factor)) return;
332 smoothing_.store(std::clamp(factor, T(0), T(0.99)), std::memory_order_relaxed);
333 }
334
340 void setPeakDecay(T decayDbPerSecond) noexcept
341 {
342 if (!std::isfinite(decayDbPerSecond)) return;
343 peakDecayRate_.store(std::max(T(0), decayDbPerSecond), std::memory_order_relaxed);
344 }
345
347 void setPeakHoldEnabled(bool enabled) noexcept
348 {
349 peakHoldEnabled_.store(enabled, std::memory_order_relaxed);
350 }
351
357 void setFloorDb(T floorDb) noexcept
358 {
359 if (!std::isfinite(floorDb)) return;
360 floorDb_.store(floorDb, std::memory_order_relaxed);
361 }
362
364 [[nodiscard]] T getSmoothing() const noexcept { return smoothing_.load(std::memory_order_relaxed); }
365
367 [[nodiscard]] T getPeakDecay() const noexcept { return peakDecayRate_.load(std::memory_order_relaxed); }
368
370 [[nodiscard]] bool isPeakHoldEnabled() const noexcept { return peakHoldEnabled_.load(std::memory_order_relaxed); }
371
373 [[nodiscard]] T getFloorDb() const noexcept { return floorDb_.load(std::memory_order_relaxed); }
374
376 [[nodiscard]] WindowType getWindowType() const noexcept { return windowType_; }
377
387 void pushSamples(const T* samples, int numSamples) noexcept
388 {
389 if (fft_ == nullptr || samples == nullptr || numSamples <= 0)
390 return;
391
392 for (int i = 0; i < numSamples; ++i)
393 {
394 inputRing_[static_cast<size_t>(ringWritePos_)] = samples[i];
395 ringWritePos_ = (ringWritePos_ + 1) & ringMask_; // pow2 mask, no division
396
397 if (--samplesUntilFFT_ <= 0)
398 {
399 computeSpectrum();
400 samplesUntilFFT_ = hopSize_; // Restart countdown with 50% overlap
401 }
402 }
403 }
404
426 [[nodiscard]] const T* getMagnitudesDb() const noexcept
427 {
428 return snapshotFrame(false);
429 }
430
441 static void toAuditoryBands(const AuditoryBands<double>& bands, const T* magnitudesDb, T* outDb,
442 double* scratch) noexcept
443 {
444 const int bins = bands.getNumBins(), n = bands.getNumBands();
445 if (magnitudesDb == nullptr || outDb == nullptr || scratch == nullptr || bins <= 0) return;
446 for (int k = 0; k < bins; ++k) scratch[k] = std::pow(10.0, static_cast<double>(magnitudesDb[k]) / 10.0);
447 double* p = scratch + bins;
448 bands.bandPowers(scratch, p);
449 for (int b = 0; b < n; ++b) outDb[b] = static_cast<T>(10.0 * std::log10(std::max(p[b], 1e-30)));
450 }
451
462 [[nodiscard]] const T* getPeakHoldDb() const noexcept
463 {
464 return snapshotFrame(true);
465 }
466
478 [[nodiscard]] long long getStaleSnapshotCount() const noexcept { return staleSnapshots_; }
479
481 [[nodiscard]] bool isNewDataReady() noexcept
482 {
483 return newDataReady_.exchange(false, std::memory_order_relaxed);
484 }
485
489 [[nodiscard]] int getNumBins() const noexcept { return numBins_; }
490
492 [[nodiscard]] int getFFTSize() const noexcept { return fftSize_; }
493
496 [[nodiscard]] T binToFrequency(int bin) const noexcept
497 {
498 if (fftSize_ <= 0) return T(0);
499 return static_cast<T>(bin) * static_cast<T>(sampleRate_) / static_cast<T>(fftSize_);
500 }
501
502private:
507 [[nodiscard]] static WindowType generateWindow(T* dst, int size, WindowType type) noexcept
508 {
509 switch (type)
510 {
511 case WindowType::Hamming: WindowFunctions<T>::hamming(dst, size); break;
514 case WindowType::FlatTop: WindowFunctions<T>::flatTop(dst, size); break;
516 case WindowType::AsymmetricHann: WindowFunctions<T>::asymmetricHann(dst, size, std::max(1, size / 8)); break;
517 case WindowType::Hann:
518 default: // wild enum value: fall back to Hann (never a zeroed window)
519 WindowFunctions<T>::hann(dst, size);
520 return WindowType::Hann;
521 }
522 return type;
523 }
524
525 void computeSpectrum() noexcept
526 {
527 // Parameters are published atomically; load once per frame.
528 const T smoothing = smoothing_.load(std::memory_order_relaxed);
529 const T floorDb = floorDb_.load(std::memory_order_relaxed);
530 const T decayRate = peakDecayRate_.load(std::memory_order_relaxed);
531 const bool peakHold = peakHoldEnabled_.load(std::memory_order_relaxed);
532
533 // 1. Copy & Window (pow2 mask instead of division)
534 for (int i = 0; i < fftSize_; ++i)
535 {
536 int ringIdx = (ringWritePos_ + i) & ringMask_;
537 fftBuffer_[static_cast<size_t>(i)] = inputRing_[static_cast<size_t>(ringIdx)] * window_[static_cast<size_t>(i)];
538 }
539
540 // 2. Forward FFT
541 fft_->forward(fftBuffer_.data(), freqBuffer_.data());
542
543 // 3. Magnitude Calculation & Smoothing
544 const T oneMinusSmooth = T(1) - smoothing;
545
546 for (int k = 0; k < numBins_; ++k)
547 {
548 T re = freqBuffer_[static_cast<size_t>(2 * k)];
549 T im = freqBuffer_[static_cast<size_t>(2 * k + 1)];
550 T mag = std::sqrt(re * re + im * im) * invGain_;
551
552 // DC and Nyquist carry no mirrored bin, so the single-sided 2x in
553 // invGain_ must be undone HERE, on the fresh magnitude. (Scaling
554 // the smoothed STATE compounded 0.5x every frame and parked those
555 // bins ~9.5 dB low in steady state.)
556 if (k == 0 || k == numBins_ - 1) mag *= T(0.5);
557
558 magnitudesState_[static_cast<size_t>(k)] =
559 smoothing * magnitudesState_[static_cast<size_t>(k)] + oneMinusSmooth * mag;
560 }
561
562 // 4. Time-Domain Peak Decay Calculation (Using real hopSize_)
563 const T peakDecayDb = decayRate * static_cast<T>(hopSize_) / static_cast<T>(sampleRate_);
564
565 // 5. Write into the writer-owned slot of the triple buffer
566 auto& slot = outSlots_[static_cast<size_t>(writeSlot_)];
567 std::atomic<unsigned>& seq = *slot.seq;
568
569 // Seqlock OPEN, frame-for-frame the same discipline as the reference
570 // implementation in Core/Biquad.h setCoeffs(). An odd counter marks
571 // this slot's frame as mid-write, so a reader copying the slot can
572 // detect that its copy would mix two frames and discard it instead of
573 // returning the mixture. The release fence is MANDATORY
574 // ([atomics.fences]/2; Boehm, MSPC 2012): without it the relaxed bin
575 // stores below may be hoisted above the odd counter, and a copy that
576 // read mid-write words would pass validation. Cost is per analysis
577 // FRAME (two RMWs and one fence per hop), never per sample.
578 seq.fetch_add(1u, std::memory_order_acq_rel); // -> odd
579 std::atomic_thread_fence(std::memory_order_release);
580
581 // 6. DB Conversion and Peak Hold (relaxed atomic stores: the slot is
582 // writer-owned here, ordering is carried by the publication exchange)
583 for (int k = 0; k < numBins_; ++k)
584 {
585 T dB = gainToDecibels(magnitudesState_[static_cast<size_t>(k)], floorDb);
586 slot.magnitudesDb[static_cast<size_t>(k)].store(dB, std::memory_order_relaxed);
587
588 if (peakHold)
589 {
590 // Canonical hold law: decay, but never below the live value.
591 // (The old strict-compare branch decayed a full step whenever
592 // dB == peak, so a stationary tone made the peak FLICKER one
593 // decay step below the signal every other frame.)
594 T& peak = peakState_[static_cast<size_t>(k)];
595 peak = std::max(dB, std::max(floorDb, peak - peakDecayDb));
596 slot.peakDb[static_cast<size_t>(k)].store(peak, std::memory_order_relaxed);
597 }
598 }
599
600 // Seqlock CLOSE: the frame staged in this slot is complete. The
601 // release half publishes every bin store above to any reader that
602 // reads this counter with acquire.
603 seq.fetch_add(1u, std::memory_order_release); // -> even
604
605 // 7. Publish: swap the finished slot into 'pending' (with the fresh
606 // bit) and adopt whatever slot was there as the next write target.
607 // Wait-free; the reader can never observe a slot mid-write.
608 const int old = pendingSlot_.exchange(writeSlot_ | kFreshBit, std::memory_order_acq_rel);
609 writeSlot_ = old & kSlotMask;
610 newDataReady_.store(true, std::memory_order_release);
611 }
612
613 double sampleRate_ = 48000.0;
614 int fftSize_ = 0; // 0 = unprepared (getters report honestly)
615 int numBins_ = 0;
616 int hopSize_ = 1024;
617
618 std::unique_ptr<FFTReal<T>> fft_; // doubles as the "prepared" gate
619 std::vector<T> window_;
620 WindowType windowType_ = WindowType::Hann;
621 T windowGain_ = T(1);
622 T invGain_ = T(1);
623
624 std::vector<T> inputRing_;
625 int ringWritePos_ = 0;
626 int samplesUntilFFT_ = 0;
627
628 std::vector<T> fftBuffer_;
629 std::vector<T> freqBuffer_;
630
631 // Single source of truth for DSP state
632 std::vector<T> magnitudesState_;
633 std::vector<T> peakState_;
634
635 // Tear-free triple buffer: writer owns writeSlot_, the reader owns
636 // readSlot_, and pendingSlot_ (atomic, with a freshness bit) carries the
637 // hand-off. Classic wait-free GUI metering scheme.
638 //
639 // Cross-thread publication derivation. No local race detector can
640 // certify relaxed atomics, so the argument is made here. THREE
641 // obligations, all required: an ownership argument at acquisition time
642 // is not sufficient -- every returned pointer needs a LIFETIME one, and
643 // every multi-word readout needs a FRAME-COHERENCE one that holds for
644 // the whole duration of the copy, not just at its first instruction.
645 //
646 // 1) OWNERSHIP at access time. A slot's words are accessed only by the
647 // thread that currently owns the slot, and ownership moves
648 // exclusively through atomic read-modify-writes on pendingSlot_:
649 // - writer: exchange(writeSlot_ | fresh, acq_rel) -- the release half
650 // publishes every write to the finished slot; the acquire half
651 // synchronizes with the reader's release when adopting the slot the
652 // reader gave up.
653 // - reader: compare_exchange(expected, readSlot_, acq_rel, acquire) --
654 // on success its acquire half reads from the writer's release
655 // exchange ([atomics.order]/2), so all writes to the adopted slot
656 // happen-before the reader's reads; its release half publishes that
657 // the reader is done with the slot it returns.
658 // {writeSlot_, readSlot_, pendingSlot_ & kSlotMask} is a permutation of
659 // {0, 1, 2}: it holds at prepare() (0/1/2) and every RMW swaps one
660 // party's slot with the pending one atomically, so by induction over the
661 // serialized modification order of pendingSlot_ no slot is ever owned by
662 // both threads (the same ownership-transfer discipline as
663 // Core/SpscQueue.h). ABA is harmless: a successful CAS is an RMW and
664 // therefore reads the LATEST value in pendingSlot_'s modification order
665 // -- if the same slot index returns, it does so via a writer
666 // release-exchange that already published that slot's newest contents.
667 //
668 // 2) LIFETIME of returned pointers. Ownership alone does not cover the
669 // pointers the getters return: a pointer into a slot would outlive
670 // the reader's ownership as soon as the NEXT acquisition (by either
671 // getter) handed that slot back to the writer, which would then
672 // overwrite it under the caller's feet. Therefore NO pointer into a
673 // slot ever escapes this class: each getter copies the acquired
674 // slot into reader-private snapshot storage (magSnapshot_ /
675 // peakSnapshot_, touched only by the reader) WHILE it owns the slot,
676 // and returns a pointer to the snapshot. The audio thread cannot
677 // reach the snapshots, so a held pointer can never be written by
678 // another thread, regardless of how long the caller keeps it.
679 //
680 // 3) FRAME COHERENCE across a slow copy. (1) and (2) are arguments
681 // about the OWNERSHIP protocol, and both hold only as long as that
682 // protocol is exactly right: a numBins-word copy is not atomic, so a
683 // reader that took a slow path (page fault, preemption, debugger,
684 // an unoptimised build) would return bins from two different frames
685 // the instant a future edit let the writer reach the slot being
686 // copied. Nothing about the copy itself detected that. Each slot
687 // therefore carries its own seqlock counter (OutSlot::seq): the
688 // writer brackets the bin stores with odd/even RMWs and a release
689 // fence, and the reader validates the counter after the copy behind
690 // an acquire fence ([atomics.fences]/2). A copy that could have
691 // mixed frames FAILS validation and is discarded into the spare
692 // snapshot half rather than published, so the contract holds by
693 // construction and not merely by the correctness of (1). It is the
694 // library's canonical seqlock applied per slot; the reference
695 // implementation is Core/Biquad.h.
696 //
697 // Defence in depth + oracle legibility: the slot words are relaxed
698 // std::atomic<T>. Under (1)+(2) they are never accessed concurrently,
699 // so plain words would be formally correct -- but atomics make any
700 // future lifetime regression read defined (stale) values instead of UB,
701 // and they make the DRD/Helgrind green criterion mechanical: those
702 // oracles model pthread happens-before only and cannot see the RMW
703 // edges, so with plain words they reported the slot arrays as racing
704 // and the verdict rested on a human classification argument (which
705 // an earlier version of this header got wrong). With atomic words
706 // every residual frame machine-classifies as a std::atomic op;
707 // relaxed load/store compiles to plain moves on x86 and ARM. The
708 // C++11-aware oracle for the protocol itself remains ThreadSanitizer
709 // (CI) via the pinned concurrent tests (single-getter tear pin and
710 // paired-getter lifetime pin).
711 static constexpr int kFreshBit = 4;
712 static constexpr int kSlotMask = 3;
713
716 static constexpr double kAutoSpanRef = 2048.0;
717 static constexpr double kAutoSpanRate = 48000.0;
718 static constexpr int kAutoMinFft = 256;
719 static constexpr int kAutoMaxFft = 16384;
720
725 static constexpr int kSnapshotAttempts = 4;
726
727 static_assert(std::atomic<T>::is_always_lock_free,
728 "SpectrumAnalyzer requires lock-free atomic<T> slot words "
729 "(audio-thread stores must not lock)");
730 static_assert(std::atomic<unsigned>::is_always_lock_free,
731 "SpectrumAnalyzer requires a lock-free seqlock counter "
732 "(audio-thread RMWs must not lock)");
733
734 struct OutSlot
735 {
736 std::unique_ptr<std::atomic<T>[]> magnitudesDb;
737 std::unique_ptr<std::atomic<T>[]> peakDb;
738 // Seqlock counter for the frame staged here: odd = mid-write,
739 // even = complete (obligation 3 above). Heap-held so that OutSlot
740 // stays movable and prepare()'s commit phase remains noexcept.
741 std::unique_ptr<std::atomic<unsigned>> seq;
742 };
743 std::array<OutSlot, 3> outSlots_;
744 int writeSlot_ = 0; // writer-thread private
745 mutable int readSlot_ = 1; // reader-thread private
746 mutable std::atomic<int> pendingSlot_{ 2 };
747
748 // Reader-private snapshot storage backing the getter return pointers
749 // (see the lifetime derivation above). Only the reader thread touches
750 // these; contents change only on the reader's own getter calls. Each
751 // vector holds TWO numBins_-sized halves: the getter copies into the
752 // spare half and swaps the published index only once the copy has been
753 // proved frame-coherent, so a discarded copy can never be observed and
754 // a pointer handed out last call is never scribbled on mid-copy.
755 mutable std::vector<T> magSnapshot_;
756 mutable std::vector<T> peakSnapshot_;
757 mutable int magSnapshotHalf_ = 0; // half currently published
758 mutable int peakSnapshotHalf_ = 0;
759 mutable long long staleSnapshots_ = 0; // coherent-copy failures
760
762 void acquireLatestSlot() const noexcept
763 {
764 int expected = pendingSlot_.load(std::memory_order_acquire);
765 while (expected & kFreshBit)
766 {
767 if (pendingSlot_.compare_exchange_weak(expected, readSlot_,
768 std::memory_order_acq_rel,
769 std::memory_order_acquire))
770 {
771 readSlot_ = expected & kSlotMask;
772 return;
773 }
774 }
775 }
776
792 [[nodiscard]] const T* snapshotFrame(bool peakArray) const noexcept
793 {
794 std::vector<T>& store = peakArray ? peakSnapshot_ : magSnapshot_;
795 int& half = peakArray ? peakSnapshotHalf_ : magSnapshotHalf_;
796
797 // Unprepared: no slots, no seq counters, nothing readable. Honest
798 // empty result (the pointer may be null), as documented.
799 if (numBins_ <= 0) return store.data();
800
801 T* const spare = store.data()
802 + static_cast<size_t>(half ^ 1) * static_cast<size_t>(numBins_);
803
804 for (int attempt = 0; attempt < kSnapshotAttempts; ++attempt)
805 {
806 acquireLatestSlot();
807 const OutSlot& slot = outSlots_[static_cast<size_t>(readSlot_)];
808 const std::atomic<T>* const src =
809 (peakArray ? slot.peakDb : slot.magnitudesDb).get();
810 const std::atomic<unsigned>& seq = *slot.seq;
811
812 const unsigned s0 = seq.load(std::memory_order_acquire);
813 if ((s0 & 1u) != 0u) continue; // a frame is mid-write in here
814
815 for (int k = 0; k < numBins_; ++k)
816 spare[static_cast<size_t>(k)] =
817 src[static_cast<size_t>(k)].load(std::memory_order_relaxed);
818
819 std::atomic_thread_fence(std::memory_order_acquire);
820 if (seq.load(std::memory_order_relaxed) == s0)
821 {
822 half ^= 1; // commit the validated copy
823 return spare;
824 }
825 }
826
827 ++staleSnapshots_;
828 return store.data()
829 + static_cast<size_t>(half) * static_cast<size_t>(numBins_);
830 }
831
832 int ringMask_ = 2047;
833
834 std::atomic<T> smoothing_ { T(0.8) };
835 std::atomic<T> peakDecayRate_ { T(10) };
836 std::atomic<T> floorDb_ { T(-100) };
837 std::atomic<bool> peakHoldEnabled_ { false };
838
839 std::atomic<bool> newDataReady_{ false };
840};
841
842} // namespace dspark
Bands uniform in Bark over a power spectrum, with the loudness law.
Real-time FFT spectrum analyser with per-bin smoothing and peak hold.
void setFloorDb(T floorDb) noexcept
Sets the readout floor in decibels.
T getFloorDb() const noexcept
Returns the readout floor in decibels.
int getFFTSize() const noexcept
FFT size in samples; 0 before the first successful prepare().
void setPeakHoldEnabled(bool enabled) noexcept
Enables or disables peak-hold tracking.
WindowType getWindowType() const noexcept
Returns the window type in use (set at prepare time).
int getNumBins() const noexcept
Number of spectrum bins (fftSize/2 + 1); 0 before the first successful prepare(). Always matches the ...
void prepare(double sampleRate, int fftSize=0, WindowType windowType=WindowType::Hann)
Prepares the analyser and allocates all necessary buffers.
static void toAuditoryBands(const AuditoryBands< double > &bands, const T *magnitudesDb, T *outDb, double *scratch) noexcept
A spectrum read in bands of the ear's scale (Bark), the perceptual view of getMagnitudesDb(): each ba...
T getPeakDecay() const noexcept
Returns the peak-hold decay rate in dB per second.
T getSmoothing() const noexcept
Returns the per-frame magnitude smoothing factor.
void pushSamples(const T *samples, int numSamples) noexcept
Pushes audio samples into the analyser's internal ring buffer.
long long getStaleSnapshotCount() const noexcept
Number of getter calls that had to return the previous snapshot because no attempt copied one frame c...
bool isPeakHoldEnabled() const noexcept
Returns true if peak-hold tracking is enabled.
void setPeakDecay(T decayDbPerSecond) noexcept
Sets the peak-hold decay rate.
const T * getPeakHoldDb() const noexcept
Returns the peak-hold spectrum in decibels.
void reset() noexcept
Resets all internal buffers and state to zero/floor values.
void setSmoothing(T factor) noexcept
Sets the per-frame magnitude smoothing factor.
const T * getMagnitudesDb() const noexcept
Returns the current magnitude spectrum in decibels.
T binToFrequency(int bin) const noexcept
Centre frequency of the given bin in Hz (0 before the first successful prepare()).
WindowType
Available window types for the FFT analysis.
@ Hann
Default. Good general-purpose choice.
@ Hamming
Slightly better side lobe rejection.
@ Rectangular
No windowing (transient analysis).
@ BlackmanHarris
Highest side lobe rejection.
@ AsymmetricHann
Low latency: a Hann rise and a fall over the last eighth, so the weight sits on the recent samples (t...
@ FlatTop
Amplitude-accurate measurement.
bool isNewDataReady() noexcept
Consumes and returns the new data flag. True if updated since last call.
Main namespace for the DSPark framework.
T gainToDecibels(T gain, T minusInfinityDb=T(-100)) noexcept
Converts a linear gain value to decibels.
Definition DspMath.h:92
static void hann(T *output, int size, bool periodic=true) noexcept
Hann (raised cosine) window.
static void blackman(T *output, int size, bool periodic=true) noexcept
Blackman window.
static void asymmetricHann(T *output, int size, int fall) noexcept
Asymmetric window for low-latency analysis: the rising half of a Hann window over the first size - fa...
static void blackmanHarris(T *output, int size, bool periodic=true) noexcept
Blackman-Harris window (4-term, -92 dB side lobes).
static void hamming(T *output, int size, bool periodic=true) noexcept
Hamming window.
static T coherentGain(const T *window, int size) noexcept
Computes the coherent gain of a window (mean of its samples).
static void flatTop(T *output, int size, bool periodic=true) noexcept
Flat-top window (amplitude-accurate: scallop loss < 0.01 dB).
static void rectangular(T *output, int size) noexcept
Rectangular window (no windowing – all ones).