DSPark 1.9.0
Header-only C++20 DSP for real-time and offline audio
Loading...
Searching...
No Matches
KeyDetector.h
1// DSPark - Professional Audio DSP Framework
2// Copyright (c) 2026 Cristian Moresi - MIT License
3
4#pragma once
5
91#include "../Core/AudioBuffer.h"
92#include "../Core/AudioSpec.h"
93#include "../Core/DspMath.h"
94#include "../Core/FFT.h"
95#include "../Core/WindowFunctions.h"
96#include "ChordDetector.h"
97#include "HarmonyConstants.h"
98
99#include <algorithm>
100#include <array>
101#include <atomic>
102#include <cmath>
103#include <cstddef>
104#include <cstdint>
105#include <memory>
106#include <span>
107#include <string_view>
108#include <utility>
109#include <vector>
110
111namespace dspark {
112
125template <FloatType T>
126class KeyDetector final
127{
128public:
164 enum class Profile : std::uint8_t
165 {
166 KrumhanslKessler = 0,
167 Temperley,
168 Recorded
169 };
170
172 struct Key
173 {
175 bool isMinor = false;
176 T confidence = T(0);
178 bool runnerUpMinor = false;
182 };
183
184 // -- Lifecycle ---------------------------------------------------------------
185
208 void prepare(const AudioSpec& spec, int windowSize = 0)
209 {
210 // The peak front end is built aside first: an allocation that throws
211 // leaves the detector exactly as it was. A specification the shared
212 // front end would reject is turned away before anything is built.
213 if (!spec.isValid() || !std::isfinite(spec.sampleRate)) return;
214 PeakFront next;
215 next.build(spec.sampleRate);
216 // The shared front end validates the complete specification and its
217 // strict Nyquist bound before changing any state. Only commit wrapper
218 // state after it reports that the same request was accepted.
219 if (!front_.prepare(spec, windowSize)) return;
220 peaks_ = std::move(next);
221 prepared_.store(true, std::memory_order_release);
222 reset();
223 }
224
232 void reset() noexcept
233 {
234 front_.reset();
235 peaks_.reset();
236 accum_.fill(0.0);
237 chromaOut_.fill(T(0));
238 maxFrameTotal_ = 0.0;
239 lastFrame_ = 0;
240 framesUsed_ = 0;
241 packed_.store(pack(Key {}), std::memory_order_relaxed);
242 }
243
253 void setProfile(Profile p) noexcept
254 {
255 profile_.store(static_cast<std::uint8_t>(p), std::memory_order_relaxed);
256 }
257
259 [[nodiscard]] Profile getProfile() const noexcept
260 {
261 return static_cast<Profile>(profile_.load(std::memory_order_relaxed));
262 }
263
276 [[nodiscard]] int getWindowSize() const noexcept
277 {
278 return readsPeaks() ? peaks_.size : front_.getWindowSize();
279 }
280
281 // -- Processing -------------------------------------------------------------------
282
291 {
292 if (!prepared_.load(std::memory_order_acquire)) return;
293 const int hop = front_.getHopSize();
294 const int n = buffer.getNumSamples();
295 const int nCh = buffer.getNumChannels();
296 if (hop <= 0 || n <= 0 || nCh <= 0) return;
297 for (int off = 0; off < n; off += hop)
298 {
299 front_.processBlock(buffer.getSubView(off, std::min(hop, n - off)));
300 consumeFrames();
301 }
302 // The same mono mix the note front end takes, sample by sample.
303 const T invCh = T(1) / static_cast<T>(nCh);
304 for (int i = 0; i < n; ++i)
305 {
306 T m = T(0);
307 for (int ch = 0; ch < nCh; ++ch) m += buffer.getChannel(ch)[i] * invCh;
308 pushPeak(m);
309 }
310 }
311
313 void pushSamples(std::span<const T> samples) noexcept
314 {
315 if (!prepared_.load(std::memory_order_acquire)) return;
316 const int hop = front_.getHopSize();
317 if (hop <= 0) return;
318 const auto step = static_cast<std::size_t>(hop);
319 for (std::size_t off = 0; off < samples.size(); off += step)
320 {
321 front_.pushSamples(samples.subspan(off, std::min(step, samples.size() - off)));
322 consumeFrames();
323 }
324 for (const T x : samples) pushPeak(x);
325 }
326
327 // -- Readout ----------------------------------------------------------------------
328
353 [[nodiscard]] Key getKey() const noexcept
354 {
355 return unpack(packed_.load(std::memory_order_relaxed));
356 }
357
376 [[nodiscard]] const std::array<T, 12>& chroma() const noexcept { return chromaOut_; }
377
380 [[nodiscard]] std::uint64_t getFrameCount() const noexcept
381 {
382 return readsPeaks() ? peaks_.framesUsed : framesUsed_;
383 }
384
396 static int getKeyName(const Key& key, char* dest, int size) noexcept
397 {
398 if (dest == nullptr || size <= 0) return 0;
399 // Parenthesised on purpose: inside a class template MSVC can read a
400 // bare `a.b < ... || a.b > ...` chain as a template argument list.
401 if ((key.tonicPitchClass < 0) || (key.tonicPitchClass > 11))
402 {
403 dest[0] = '\0';
404 return 0;
405 }
406 const bool sharpMinor =
407 key.isMinor && (key.tonicPitchClass == 1 || key.tonicPitchClass == 8);
408 const std::string_view root =
409 harmony::noteName(key.tonicPitchClass, sharpMinor ? 0 : key.tonicPitchClass);
410 int len = 0;
411 for (char c : root)
412 {
413 if (len >= size - 1) break;
414 dest[len++] = c;
415 }
416 if (key.isMinor && len < size - 1) dest[len++] = 'm';
417 dest[len] = '\0';
418 return len;
419 }
420
421 // -- Published key profiles -------------------------------------------------------
422
431 static constexpr std::array<double, 12> kKrumhanslKesslerMajor {
432 6.35, 2.23, 3.48, 2.33, 4.38, 4.09, 2.52, 5.19, 2.39, 3.66, 2.29, 2.88
433 };
434
443 static constexpr std::array<double, 12> kKrumhanslKesslerMinor {
444 6.33, 2.68, 3.52, 5.38, 2.60, 3.53, 2.54, 4.75, 3.98, 2.69, 3.34, 3.17
445 };
446
455 static constexpr std::array<double, 12> kTemperleyMajor {
456 5.0, 2.0, 3.5, 2.0, 4.5, 4.0, 2.0, 4.5, 2.0, 3.5, 1.5, 4.0
457 };
458
467 static constexpr std::array<double, 12> kTemperleyMinor {
468 5.0, 2.0, 3.5, 4.5, 2.0, 4.0, 2.0, 4.5, 3.5, 2.0, 1.5, 4.0
469 };
470
482 static constexpr std::array<double, 12> kRecordedMajor {
483 1.0, 0.04, 0.3, 0.04, 0.55, 0.3, 0.04, 0.85, 0.04, 0.3, 0.04, 0.35
484 };
485
493 static constexpr std::array<double, 12> kRecordedMinor {
494 1.0, 0.04, 0.3, 0.45, 0.04, 0.3, 0.04, 0.85, 0.3, 0.05, 0.25, 0.2
495 };
496
497private:
508 static constexpr double kFrameGateFraction = 1.0e-3;
509
511 static constexpr double kFrameEnergyFloor = 1.0e-12;
512
513 void consumeFrames() noexcept
514 {
515 const std::uint64_t fc = front_.getFrameCount();
516 if (fc == lastFrame_) return;
517 lastFrame_ = fc;
518
519 const std::array<T, 12>& frame = front_.getChroma();
520 double total = 0.0;
521 for (const T v : frame) total += static_cast<double>(v);
522 if (!(total > kFrameEnergyFloor)) return;
523
524 if (total > maxFrameTotal_) maxFrameTotal_ = total;
525 if (total < kFrameGateFraction * maxFrameTotal_) return;
526
527 // Equal weight per frame: the input to the method is how LONG each
528 // pitch class sounds, so a frame's own level must not scale its vote.
529 // Magnitudes, not energies: squared, one loud bass note outvotes the
530 // whole chord above it.
531 std::array<double, 12> magnitude {};
532 double magnitudeTotal = 0.0;
533 for (int pc = 0; pc < 12; ++pc)
534 {
535 magnitude[static_cast<std::size_t>(pc)] =
536 std::sqrt(static_cast<double>(frame[static_cast<std::size_t>(pc)]));
537 magnitudeTotal += magnitude[static_cast<std::size_t>(pc)];
538 }
539 const double inv = 1.0 / magnitudeTotal;
540 for (int pc = 0; pc < 12; ++pc)
541 accum_[static_cast<std::size_t>(pc)] +=
542 magnitude[static_cast<std::size_t>(pc)] * inv;
543 ++framesUsed_;
544
545 if (!readsPeaks()) estimate();
546 }
547
548 [[nodiscard]] bool readsPeaks() const noexcept { return getProfile() == Profile::Recorded; }
549
550 // -- The spectral-peak front end of Profile::Recorded -----------------------------
551
552 static constexpr int kLowMidi = 21;
553 static constexpr int kNotes = 88;
554 static constexpr int kThirds = 3 * kNotes;
555 static constexpr int kChromaLowMidi = 36;
556 static constexpr int kChromaHighMidi = 83;
557 static constexpr double kPeakReferenceSize = 8192.0;
558 static constexpr double kPeakReferenceRate = 44100.0;
559 static constexpr int kPeakMinSize = 1024;
560 static constexpr int kPeakMaxSize = 65536;
561 static constexpr double kPeakLowHz = 26.0;
562 static constexpr double kPeakHighHz = 5000.0;
563 static constexpr double kPeakFloor = 1.0e-3;
564 static constexpr double kPeakFrameGate = 1.0e-3;
565 static constexpr double kHarmonicWeight = 0.6;
566 static constexpr std::array<int, 5> kHarmonicOffsets { 12, 19, 24, 28, 31 };
567 static constexpr double kClassFloor = 0.3;
568
570 [[nodiscard]] static int peakWindowFor(double sampleRate) noexcept
571 {
572 const double want = kPeakReferenceSize * sampleRate / kPeakReferenceRate;
573 const double e = std::round(std::log2(std::max(want, 1.0)));
574 const double size = std::exp2(std::clamp(e, 10.0, 16.0));
575 return std::clamp(static_cast<int>(size), kPeakMinSize, kPeakMaxSize);
576 }
577
578 struct PeakFront
579 {
580 int size = 0;
581 int hop = 0;
582 int low = 0, high = 0;
583 double rate = 0.0;
584 std::unique_ptr<FFTReal<T>> fft;
585 std::vector<T> ring, window, time, freq, mag;
586 std::size_t write = 0;
587 std::uint64_t seen = 0;
588 double loudest = 0.0;
589 std::array<double, 3> tuning {};
590 std::array<std::array<double, 12>, 3> sums {};
591 std::uint64_t framesUsed = 0;
592
593 void build(double sampleRate)
594 {
595 rate = sampleRate;
596 size = peakWindowFor(sampleRate);
597 hop = size / 4;
598 low = std::max(2, static_cast<int>(std::floor(kPeakLowHz * size / rate)));
599 high = std::min(size / 2 - 1, static_cast<int>(std::ceil(kPeakHighHz * size / rate)));
600 const auto n = static_cast<std::size_t>(size);
601 fft = std::make_unique<FFTReal<T>>(n);
602 ring.assign(n, T(0));
603 window.assign(n, T(0));
604 WindowFunctions<T>::hann(window.data(), size, true);
605 time.assign(n, T(0));
606 freq.assign(n + 2, T(0));
607 mag.assign(n / 2 + 1, T(0));
608 reset();
609 }
610
611 void reset() noexcept
612 {
613 std::fill(ring.begin(), ring.end(), T(0));
614 write = 0;
615 seen = 0;
616 loudest = 0.0;
617 tuning.fill(0.0);
618 for (auto& s : sums) s.fill(0.0);
619 framesUsed = 0;
620 }
621 };
622
623 void pushPeak(T x) noexcept
624 {
625 PeakFront& f = peaks_;
626 if (f.size <= 0) return;
627 // A non-finite sample would make every bin of its frames non-finite.
628 f.ring[f.write] = std::isfinite(x) ? x : T(0);
629 if (++f.write == f.ring.size()) f.write = 0;
630 ++f.seen;
631 const auto n = static_cast<std::uint64_t>(f.size);
632 if (f.seen >= n && (f.seen - n) % static_cast<std::uint64_t>(f.hop) == 0) peakFrame();
633 }
634
635 void peakFrame() noexcept
636 {
637 PeakFront& f = peaks_;
638 const auto n = static_cast<std::size_t>(f.size);
639 // Oldest sample first: the ring's next write position.
640 for (std::size_t i = 0; i < n; ++i)
641 {
642 std::size_t at = f.write + i;
643 if (at >= n) at -= n;
644 f.time[i] = f.ring[at] * f.window[i];
645 }
646 f.fft->forward(f.time.data(), f.freq.data());
647 double top = 0.0;
648 for (int k = f.low - 1; k <= f.high + 1; ++k)
649 {
650 const auto ks = static_cast<std::size_t>(k);
651 const double re = static_cast<double>(f.freq[2 * ks]);
652 const double im = static_cast<double>(f.freq[2 * ks + 1]);
653 const double m = std::sqrt(re * re + im * im);
654 f.mag[ks] = static_cast<T>(m);
655 if (k >= f.low && k <= f.high && m > top) top = m;
656 }
657 if (!(top > 0.0)) return;
658 if (top > f.loudest) f.loudest = top;
659 if (!(top > kPeakFrameGate * f.loudest)) return;
660
661 // The peaks, each at its third of a semitone, and the notes they make
662 // at the three tunings (the third the programme sits on is decided
663 // from the whole programme when the key is read).
664 std::array<std::array<double, kNotes>, 3> note {};
665 std::array<double, 3> frameThird {};
666 double frameTotal = 0.0;
667 const double floor = kPeakFloor * top;
668 for (int k = f.low; k <= f.high; ++k)
669 {
670 const auto ks = static_cast<std::size_t>(k);
671 const double b = static_cast<double>(f.mag[ks]);
672 const double before = static_cast<double>(f.mag[ks - 1]);
673 const double after = static_cast<double>(f.mag[ks + 1]);
674 if (!(b > floor) || !(b > before) || !(b >= after)) continue;
675 const double la = std::log(std::max(before, 1.0e-20));
676 const double lb = std::log(b);
677 const double lc = std::log(std::max(after, 1.0e-20));
678 const double curve = la - 2.0 * lb + lc;
679 const double p = (curve < 0.0) ? std::clamp(0.5 * (la - lc) / curve, -0.5, 0.5) : 0.0;
680 const double hz = (static_cast<double>(k) + p) * f.rate / static_cast<double>(f.size);
681 const double amp = std::exp(lb - 0.25 * (la - lc) * p);
682 const double midi = 69.0 + 12.0 * std::log2(hz / 440.0);
683 const long third = std::lround(3.0 * (midi - kLowMidi)) + 1;
684 if (third < 0 || third >= kThirds) continue;
685 frameThird[static_cast<std::size_t>(third % 3)] += amp;
686 frameTotal += amp;
687 for (int s = 0; s < 3; ++s)
688 {
689 const long at = third - (s - 1);
690 if (at >= 0 && at < kThirds)
691 note[static_cast<std::size_t>(s)][static_cast<std::size_t>(at / 3)] += amp;
692 }
693 }
694 if (!(frameTotal > 0.0)) return;
695 for (int i = 0; i < 3; ++i)
696 f.tuning[static_cast<std::size_t>(i)] += frameThird[static_cast<std::size_t>(i)] / frameTotal;
697
698 for (int s = 0; s < 3; ++s)
699 {
700 const auto& nt = note[static_cast<std::size_t>(s)];
701 std::array<double, 12> chroma {};
702 for (int midi = kChromaLowMidi; midi <= kChromaHighMidi; ++midi)
703 {
704 const int at = midi - kLowMidi;
705 double salience = nt[static_cast<std::size_t>(at)];
706 double w = 1.0;
707 for (const int offset : kHarmonicOffsets)
708 {
709 w *= kHarmonicWeight;
710 if (at + offset >= kNotes) break;
711 salience += w * nt[static_cast<std::size_t>(at + offset)];
712 }
713 chroma[static_cast<std::size_t>(midi % 12)] += salience;
714 }
715 double strongest = 0.0;
716 for (const double c : chroma) strongest = std::max(strongest, c);
717 if (!(strongest > 0.0)) continue;
718 const double classFloor = kClassFloor * strongest;
719 auto& sum = f.sums[static_cast<std::size_t>(s)];
720 for (int pc = 0; pc < 12; ++pc)
721 {
722 const double c = chroma[static_cast<std::size_t>(pc)];
723 if (c >= classFloor && c > 0.0) sum[static_cast<std::size_t>(pc)] += c / strongest;
724 }
725 }
726 ++f.framesUsed;
727
728 if (readsPeaks()) estimate();
729 }
730
732 [[nodiscard]] const std::array<double, 12>& peakChroma() const noexcept
733 {
734 const auto& t = peaks_.tuning;
735 int s = 1; // in tune: the middle third
736 if (t[0] > t[1] && t[0] >= t[2]) s = 0; // flat: the lower third
737 if (t[2] > t[1] && t[2] > t[0]) s = 2; // sharp: the upper third
738 return peaks_.sums[static_cast<std::size_t>(s)];
739 }
740
741 void estimate() noexcept
742 {
743 const bool peaks = readsPeaks();
744 const std::array<double, 12>& evidence = peaks ? peakChroma() : accum_;
745 double sum = 0.0;
746 for (const double v : evidence) sum += v;
747 if (!(sum > 0.0)) return;
748
749 // The score reads the ACCUMULATOR, not the normalized readout built
750 // below. Pearson subtracts each argument's mean and divides by its
751 // spread, and a cosine divides by the length, so multiplying the
752 // chroma by any positive constant divides straight back out:
753 // normalizing first cannot move an argmax, a top score or a
754 // confidence, only their last bits. The normalization exists for the
755 // readout alone, for the reason stated at chroma(), and is
756 // deliberately not in the path of the estimate.
757 const double inv = 1.0 / sum;
758 for (int pc = 0; pc < 12; ++pc)
759 chromaOut_[static_cast<std::size_t>(pc)] =
760 static_cast<T>(evidence[static_cast<std::size_t>(pc)] * inv);
761
762 std::array<double, 24> scores {};
763 if (peaks)
764 {
765 std::array<double, 12> root {};
766 for (int pc = 0; pc < 12; ++pc)
767 root[static_cast<std::size_t>(pc)] = std::cbrt(evidence[static_cast<std::size_t>(pc)]);
768 for (int mode = 0; mode < 2; ++mode)
769 {
770 const auto& p = (mode == 0) ? kRecordedMajor : kRecordedMinor;
771 for (int tonic = 0; tonic < 12; ++tonic)
772 scores[static_cast<std::size_t>(mode * 12 + tonic)] = cosineRotated(root, p, tonic);
773 }
774 }
775 else
776 {
777 const bool temperley = (getProfile() == Profile::Temperley);
778 const auto& major = temperley ? kTemperleyMajor : kKrumhanslKesslerMajor;
779 const auto& minor = temperley ? kTemperleyMinor : kKrumhanslKesslerMinor;
780 for (int mode = 0; mode < 2; ++mode)
781 {
782 const auto& p = (mode == 0) ? major : minor;
783 for (int tonic = 0; tonic < 12; ++tonic)
784 {
785 const double r = pearsonRotated(accum_, p, tonic);
786 scores[static_cast<std::size_t>(mode * 12 + tonic)] = r;
787 }
788 }
789 }
790
791 // Fixed-size stable insertion sort: score descending, exact ties in
792 // candidate ordinal order. Retaining the complete order makes both the
793 // numerical runner-up and the relative candidate's real rank explicit
794 // without allocating on the processing path.
795 std::array<int, 24> order {};
796 for (int ordinal = 0; ordinal < 24; ++ordinal)
797 {
798 int pos = ordinal;
799 while (pos > 0
800 && scores[static_cast<std::size_t>(ordinal)]
801 > scores[static_cast<std::size_t>(order[static_cast<std::size_t>(pos - 1)])])
802 {
803 order[static_cast<std::size_t>(pos)] =
804 order[static_cast<std::size_t>(pos - 1)];
805 --pos;
806 }
807 order[static_cast<std::size_t>(pos)] = ordinal;
808 }
809
810 const int bestOrdinal = order[0];
811 const int secondOrdinal = order[1];
812 const double best = scores[static_cast<std::size_t>(bestOrdinal)];
813 const double second = scores[static_cast<std::size_t>(secondOrdinal)];
814 const int bestPc = bestOrdinal % 12;
815 const bool bestMinor = bestOrdinal >= 12;
816
817 // A major key's relative minor is nine semitones above it; a minor
818 // key's relative major is three above. It is a named policy candidate,
819 // never a replacement for the numerical runner-up.
820 const int relativePc = (bestPc + (bestMinor ? 3 : 9)) % 12;
821 const bool relativeMinor = !bestMinor;
822 const int relativeOrdinal = (relativeMinor ? 12 : 0) + relativePc;
823 int relativeRank = 0;
824 for (int rank = 0; rank < 24; ++rank)
825 {
826 if (order[static_cast<std::size_t>(rank)] == relativeOrdinal)
827 {
828 relativeRank = rank + 1;
829 break;
830 }
831 }
832
833 Key key;
834 key.tonicPitchClass = bestPc;
835 key.isMinor = bestMinor;
836 key.runnerUpPitchClass = secondOrdinal % 12;
837 key.runnerUpMinor = secondOrdinal >= 12;
838 key.relativeAlternativePitchClass = relativePc;
839 key.relativeAlternativeMinor = relativeMinor;
840 key.relativeAlternativeRank = relativeRank;
841 // Undefined where the winner is not itself a positive correlation:
842 // dividing by a zero or negative top would turn "no tonal structure"
843 // into a large number of the wrong sign.
844 key.confidence = (best > 0.0)
845 ? static_cast<T>(std::clamp(
846 (best - second) / best, 0.0, 1.0))
847 : T(0);
848 packed_.store(pack(key), std::memory_order_relaxed);
849 }
850
863 [[nodiscard]] static double pearsonRotated(const std::array<double, 12>& x,
864 const std::array<double, 12>& profile,
865 int tonic) noexcept
866 {
867 double mx = 0.0, mp = 0.0;
868 for (int i = 0; i < 12; ++i)
869 {
870 mx += x[static_cast<std::size_t>(i)];
871 mp += profile[static_cast<std::size_t>(i)];
872 }
873 mx /= 12.0;
874 mp /= 12.0;
875
876 double num = 0.0, dx = 0.0, dp = 0.0;
877 for (int pc = 0; pc < 12; ++pc)
878 {
879 const double a = x[static_cast<std::size_t>(pc)] - mx;
880 const double b = profile[static_cast<std::size_t>((pc - tonic + 12) % 12)] - mp;
881 num += a * b;
882 dx += a * a;
883 dp += b * b;
884 }
885 const double den = std::sqrt(dx * dp);
886 return (den > 0.0) ? (num / den) : 0.0;
887 }
888
898 [[nodiscard]] static double cosineRotated(const std::array<double, 12>& x,
899 const std::array<double, 12>& profile,
900 int tonic) noexcept
901 {
902 double num = 0.0, dx = 0.0, dp = 0.0;
903 for (int pc = 0; pc < 12; ++pc)
904 {
905 const double a = x[static_cast<std::size_t>(pc)];
906 const double b = profile[static_cast<std::size_t>((pc - tonic + 12) % 12)];
907 num += a * b;
908 dx += a * a;
909 dp += b * b;
910 }
911 const double den = std::sqrt(dx * dp);
912 return (den > 0.0) ? (num / den) : 0.0;
913 }
914
915 // One packed word so a reader never sees fields from different estimates:
916 // bits 0-15 confidence; 16/17-20 winner mode/tonic+1; 21/22-25 numerical
917 // runner-up mode/tonic+1; 26/27-30 relative mode/tonic+1; 31-35 rank.
918 [[nodiscard]] static std::uint64_t pack(const Key& k) noexcept
919 {
920 const auto q = static_cast<std::uint64_t>(
921 std::clamp(static_cast<double>(k.confidence), 0.0, 1.0) * 65535.0 + 0.5);
922 const auto t = static_cast<std::uint64_t>(
923 std::clamp(k.tonicPitchClass, -1, 11) + 1);
924 const auto ru = static_cast<std::uint64_t>(
925 std::clamp(k.runnerUpPitchClass, -1, 11) + 1);
926 const auto rel = static_cast<std::uint64_t>(
927 std::clamp(k.relativeAlternativePitchClass, -1, 11) + 1);
928 const auto rank = static_cast<std::uint64_t>(
929 std::clamp(k.relativeAlternativeRank, 0, 24));
930 return q
931 | (static_cast<std::uint64_t>(k.isMinor ? 1 : 0) << 16)
932 | (t << 17)
933 | (static_cast<std::uint64_t>(k.runnerUpMinor ? 1 : 0) << 21)
934 | (ru << 22)
935 | (static_cast<std::uint64_t>(k.relativeAlternativeMinor ? 1 : 0) << 26)
936 | (rel << 27)
937 | (rank << 31);
938 }
939
940 [[nodiscard]] static Key unpack(std::uint64_t v) noexcept
941 {
942 Key k;
943 k.confidence = static_cast<T>(static_cast<double>(v & 0xFFFFu) / 65535.0);
944 k.isMinor = ((v >> 16) & 1u) != 0u;
945 k.tonicPitchClass = static_cast<int>((v >> 17) & 0xFu) - 1;
946 k.runnerUpMinor = ((v >> 21) & 1u) != 0u;
947 k.runnerUpPitchClass = static_cast<int>((v >> 22) & 0xFu) - 1;
948 k.relativeAlternativeMinor = ((v >> 26) & 1u) != 0u;
949 k.relativeAlternativePitchClass = static_cast<int>((v >> 27) & 0xFu) - 1;
950 k.relativeAlternativeRank = static_cast<int>((v >> 31) & 0x1Fu);
951 return k;
952 }
953
954 static_assert(std::atomic<std::uint64_t>::is_always_lock_free,
955 "audio-thread stores must not lock");
956
957 ChordDetector<T> front_;
958 PeakFront peaks_;
959 std::atomic<bool> prepared_ { false };
960
961 std::array<double, 12> accum_ {};
962 std::array<T, 12> chromaOut_ {};
963 double maxFrameTotal_ = 0.0;
964 std::uint64_t lastFrame_ = 0;
965 std::uint64_t framesUsed_ = 0;
966
967 std::atomic<std::uint64_t> packed_ { 0 };
968 std::atomic<std::uint8_t> profile_ { static_cast<std::uint8_t>(Profile::Recorded) };
969};
970
971} // namespace dspark
Non-owning view over audio channel data.
Definition AudioBuffer.h:53
Key estimation by profile correlation over an accumulated chroma.
static constexpr std::array< double, 12 > kKrumhanslKesslerMinor
Krumhansl & Kessler (1982) probe-tone ratings, minor.
void pushSamples(std::span< const T > samples) noexcept
Feeds mono samples directly. Allocation-free.
void prepare(const AudioSpec &spec, int windowSize=0)
Prepares the analysis pipeline.
static constexpr std::array< double, 12 > kKrumhanslKesslerMajor
Krumhansl & Kessler (1982) probe-tone ratings, major.
static constexpr std::array< double, 12 > kRecordedMinor
Profile::Recorded degree weights, minor.
static constexpr std::array< double, 12 > kRecordedMajor
Profile::Recorded degree weights, major.
static int getKeyName(const Key &key, char *dest, int size) noexcept
Writes a key name ("C", "F#m", "Bbm") into dest.
static constexpr std::array< double, 12 > kTemperleyMajor
Temperley (1999) revised profiles, major.
Profile
Which analysis names the key: the default for recorded music, or one of the two published profiles.
@ KrumhanslKessler
Krumhansl & Kessler 1982 probe-tone ratings.
@ Recorded
Spectral-peak chroma and measured degree weights (default).
@ Temperley
Temperley 1999 revised profiles.
void processBlock(AudioBufferView< const T > buffer) noexcept
Feeds a block (channels averaged to mono). Allocation-free.
std::uint64_t getFrameCount() const noexcept
static constexpr std::array< double, 12 > kTemperleyMinor
Temperley (1999) revised profiles, minor.
Key getKey() const noexcept
void setProfile(Profile p) noexcept
Selects the analysis (default Recorded).
Profile getProfile() const noexcept
const std::array< T, 12 > & chroma() const noexcept
The accumulated chroma the estimate was formed from.
void reset() noexcept
Clears the accumulated chroma and forgets the estimate.
int getWindowSize() const noexcept
constexpr std::string_view noteName(int midi, int root=0) noexcept
Returns a human-readable note name for the given MIDI note (0..127).
Main namespace for the DSPark framework.
Describes the audio environment for a DSP processor.
Definition AudioSpec.h:37
constexpr bool isValid() const noexcept
Checks if the specification contains valid, processable parameters.
Definition AudioSpec.h:71
double sampleRate
Sample rate in Hz.
Definition AudioSpec.h:45
One key estimate.
bool relativeAlternativeMinor
Mode of the relative key.
int runnerUpPitchClass
Numerical rank 2; -1 = nothing yet.
bool isMinor
Mode of the numerical winner.
int tonicPitchClass
Numerical rank 1; -1 = nothing yet.
int relativeAlternativeRank
Its actual 1-based numerical rank.
int relativeAlternativePitchClass
Winner's relative key.
bool runnerUpMinor
Mode of the numerical runner-up.
T confidence
Numerical rank-1/rank-2 margin.
static void hann(T *output, int size, bool periodic=true) noexcept
Hann (raised cosine) window.