219 if (!front_.prepare(spec, windowSize))
return;
220 peaks_ = std::move(next);
221 prepared_.store(
true, std::memory_order_release);
237 chromaOut_.fill(T(0));
238 maxFrameTotal_ = 0.0;
241 packed_.store(pack(
Key {}), std::memory_order_relaxed);
255 profile_.store(
static_cast<std::uint8_t
>(p), std::memory_order_relaxed);
261 return static_cast<Profile>(profile_.load(std::memory_order_relaxed));
278 return readsPeaks() ? peaks_.size : front_.getWindowSize();
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)
299 front_.processBlock(buffer.getSubView(off, std::min(hop, n - off)));
303 const T invCh = T(1) /
static_cast<T
>(nCh);
304 for (
int i = 0; i < n; ++i)
307 for (
int ch = 0; ch < nCh; ++ch) m += buffer.getChannel(ch)[i] * invCh;
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)
321 front_.pushSamples(samples.subspan(off, std::min(step, samples.size() - off)));
324 for (
const T x : samples) pushPeak(x);
355 return unpack(packed_.load(std::memory_order_relaxed));
376 [[nodiscard]]
const std::array<T, 12>&
chroma() const noexcept {
return chromaOut_; }
382 return readsPeaks() ? peaks_.framesUsed : framesUsed_;
398 if (dest ==
nullptr || size <= 0)
return 0;
401 if ((key.tonicPitchClass < 0) || (key.tonicPitchClass > 11))
406 const bool sharpMinor =
407 key.isMinor && (key.tonicPitchClass == 1 || key.tonicPitchClass == 8);
408 const std::string_view root =
413 if (len >= size - 1)
break;
416 if (key.isMinor && len < size - 1) dest[len++] =
'm';
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
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
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
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
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
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
508 static constexpr double kFrameGateFraction = 1.0e-3;
511 static constexpr double kFrameEnergyFloor = 1.0e-12;
513 void consumeFrames() noexcept
515 const std::uint64_t fc = front_.getFrameCount();
516 if (fc == lastFrame_)
return;
519 const std::array<T, 12>& frame = front_.getChroma();
521 for (
const T v : frame) total += static_cast<double>(v);
522 if (!(total > kFrameEnergyFloor))
return;
524 if (total > maxFrameTotal_) maxFrameTotal_ = total;
525 if (total < kFrameGateFraction * maxFrameTotal_)
return;
531 std::array<double, 12> magnitude {};
532 double magnitudeTotal = 0.0;
533 for (
int pc = 0; pc < 12; ++pc)
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)];
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;
545 if (!readsPeaks()) estimate();
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;
570 [[nodiscard]]
static int peakWindowFor(
double sampleRate)
noexcept
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);
582 int low = 0, high = 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;
593 void build(
double sampleRate)
596 size = peakWindowFor(sampleRate);
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));
605 time.assign(n, T(0));
606 freq.assign(n + 2, T(0));
607 mag.assign(n / 2 + 1, T(0));
611 void reset() noexcept
613 std::fill(ring.begin(), ring.end(), T(0));
618 for (
auto& s : sums) s.fill(0.0);
623 void pushPeak(T x)
noexcept
625 PeakFront& f = peaks_;
626 if (f.size <= 0)
return;
628 f.ring[f.write] = std::isfinite(x) ? x : T(0);
629 if (++f.write == f.ring.size()) f.write = 0;
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();
635 void peakFrame() noexcept
637 PeakFront& f = peaks_;
638 const auto n =
static_cast<std::size_t
>(f.size);
640 for (std::size_t i = 0; i < n; ++i)
642 std::size_t at = f.write + i;
643 if (at >= n) at -= n;
644 f.time[i] = f.ring[at] * f.window[i];
646 f.fft->forward(f.time.data(), f.freq.data());
648 for (
int k = f.low - 1; k <= f.high + 1; ++k)
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;
657 if (!(top > 0.0))
return;
658 if (top > f.loudest) f.loudest = top;
659 if (!(top > kPeakFrameGate * f.loudest))
return;
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)
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;
687 for (
int s = 0; s < 3; ++s)
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;
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;
698 for (
int s = 0; s < 3; ++s)
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)
704 const int at = midi - kLowMidi;
705 double salience = nt[
static_cast<std::size_t
>(at)];
707 for (
const int offset : kHarmonicOffsets)
709 w *= kHarmonicWeight;
710 if (at + offset >= kNotes)
break;
711 salience += w * nt[
static_cast<std::size_t
>(at + offset)];
713 chroma[
static_cast<std::size_t
>(midi % 12)] += salience;
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)
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;
728 if (readsPeaks()) estimate();
732 [[nodiscard]]
const std::array<double, 12>& peakChroma() const noexcept
734 const auto& t = peaks_.tuning;
736 if (t[0] > t[1] && t[0] >= t[2]) s = 0;
737 if (t[2] > t[1] && t[2] > t[0]) s = 2;
738 return peaks_.sums[
static_cast<std::size_t
>(s)];
741 void estimate() noexcept
743 const bool peaks = readsPeaks();
744 const std::array<double, 12>& evidence = peaks ? peakChroma() : accum_;
746 for (
const double v : evidence) sum += v;
747 if (!(sum > 0.0))
return;
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);
762 std::array<double, 24> scores {};
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)
771 for (
int tonic = 0; tonic < 12; ++tonic)
772 scores[
static_cast<std::size_t
>(mode * 12 + tonic)] = cosineRotated(root, p, tonic);
780 for (
int mode = 0; mode < 2; ++mode)
782 const auto& p = (mode == 0) ? major : minor;
783 for (
int tonic = 0; tonic < 12; ++tonic)
785 const double r = pearsonRotated(accum_, p, tonic);
786 scores[
static_cast<std::size_t
>(mode * 12 + tonic)] = r;
795 std::array<int, 24> order {};
796 for (
int ordinal = 0; ordinal < 24; ++ordinal)
800 && scores[
static_cast<std::size_t
>(ordinal)]
801 > scores[
static_cast<std::size_t
>(order[
static_cast<std::size_t
>(pos - 1)])])
803 order[
static_cast<std::size_t
>(pos)] =
804 order[
static_cast<std::size_t
>(pos - 1)];
807 order[
static_cast<std::size_t
>(pos)] = ordinal;
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;
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)
826 if (order[
static_cast<std::size_t
>(rank)] == relativeOrdinal)
828 relativeRank = rank + 1;
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;
844 key.confidence = (best > 0.0)
845 ?
static_cast<T
>(std::clamp(
846 (best - second) / best, 0.0, 1.0))
848 packed_.store(pack(key), std::memory_order_relaxed);
863 [[nodiscard]]
static double pearsonRotated(
const std::array<double, 12>& x,
864 const std::array<double, 12>& profile,
867 double mx = 0.0, mp = 0.0;
868 for (
int i = 0; i < 12; ++i)
870 mx += x[
static_cast<std::size_t
>(i)];
871 mp += profile[
static_cast<std::size_t
>(i)];
876 double num = 0.0, dx = 0.0, dp = 0.0;
877 for (
int pc = 0; pc < 12; ++pc)
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;
885 const double den = std::sqrt(dx * dp);
886 return (den > 0.0) ? (num / den) : 0.0;
898 [[nodiscard]]
static double cosineRotated(
const std::array<double, 12>& x,
899 const std::array<double, 12>& profile,
902 double num = 0.0, dx = 0.0, dp = 0.0;
903 for (
int pc = 0; pc < 12; ++pc)
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)];
911 const double den = std::sqrt(dx * dp);
912 return (den > 0.0) ? (num / den) : 0.0;
918 [[nodiscard]]
static std::uint64_t pack(
const Key& k)
noexcept
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));
931 | (
static_cast<std::uint64_t
>(k.isMinor ? 1 : 0) << 16)
933 | (
static_cast<std::uint64_t
>(k.runnerUpMinor ? 1 : 0) << 21)
935 | (static_cast<std::uint64_t>(k.relativeAlternativeMinor ? 1 : 0) << 26)
940 [[nodiscard]]
static Key unpack(std::uint64_t v)
noexcept
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);
954 static_assert(std::atomic<std::uint64_t>::is_always_lock_free,
955 "audio-thread stores must not lock");
957 ChordDetector<T> front_;
959 std::atomic<bool> prepared_ {
false };
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;
967 std::atomic<std::uint64_t> packed_ { 0 };
968 std::atomic<std::uint8_t> profile_ {
static_cast<std::uint8_t
>(
Profile::Recorded) };