191 const double highestNote = noteHz(kFirstMidi + kNumNotes - 1);
192 if (!(spec.
sampleRate > highestNote * 2.0))
return false;
202 const double target = sampleRate_ * (4096.0 / 48000.0);
204 while (n < 16384 &&
static_cast<double>(n) < target) n *= 2;
209 windowSize_ = std::clamp(windowSize, 1024, 16384);
211 hopSize_ = windowSize_ / 2;
215 prepared_.store(
true, std::memory_order_release);
229 std::fill(input_.begin(), input_.end(), T(0));
231 for (
auto& s : stages_)
233 std::fill(s.even.begin(), s.even.end(), T(0));
234 std::fill(s.odd.begin(), s.odd.end(), T(0));
236 for (
auto& o : octaves_) std::fill(o.history.begin(), o.history.end(), T(0));
237 chromaFrame_.fill(T(0));
239 packed_.store(pack(
Result {}), std::memory_order_relaxed);
251 if (!std::isfinite(threshold))
return;
252 threshold_.store(std::clamp(threshold, 0.0f, 1.0f), std::memory_order_relaxed);
258 return threshold_.load(std::memory_order_relaxed);
278 [[nodiscard]]
int getHopSize() const noexcept {
return hopSize_; }
302 [[nodiscard]] std::uint64_t
getFrameCount() const noexcept {
return frameCount_; }
326 [[nodiscard]]
const std::array<T, 12>&
getChroma() const noexcept {
return chromaFrame_; }
333 if (!prepared_.load(std::memory_order_acquire))
return;
334 const int nCh = buffer.getNumChannels();
335 const int nS = buffer.getNumSamples();
336 if (nCh <= 0)
return;
338 const T invCh = T(1) /
static_cast<T
>(nCh);
342 const int take = std::min(nS - done, hopSize_ - inputFill_);
343 T* dst = input_.data() + inputFill_;
344 for (
int i = 0; i < take; ++i)
347 for (
int ch = 0; ch < nCh; ++ch)
348 m += buffer.getChannel(ch)[done + i] * invCh;
359 if (!prepared_.load(std::memory_order_acquire))
return;
361 while (done < samples.size())
363 const size_t take = std::min(samples.size() - done,
364 static_cast<size_t>(hopSize_ - inputFill_));
365 std::memcpy(input_.data() + inputFill_, samples.data() + done, take *
sizeof(T));
367 advance(
static_cast<int>(take));
376 return unpack(packed_.load(std::memory_order_relaxed));
388 if (size <= 0)
return 0;
394 static constexpr const char* kSuffix[11] = {
395 "",
"",
"m",
"dim",
"aug",
"sus2",
"sus4",
"7",
"maj7",
"m7",
"m7b5"
398 for (
const char c :
harmony::noteName(result.rootPitchClass, result.rootPitchClass))
399 if (len < size - 1) dest[len++] = c;
400 for (
const char* p = kSuffix[
static_cast<int>(result.type)]; *p && len < size - 1; ++p)
407 static constexpr int kFirstMidi = 36;
408 static constexpr int kNumNotes = 48;
409 static constexpr int kNumOctaves = kNumNotes / 12;
410 static constexpr int kNumTemplates = 10;
415 static constexpr double kMarginBins = 8.0;
419 static constexpr double kRateSeparation = 2.5;
421 static constexpr double kStopbandDb = 80.0;
423 static constexpr int kMinOctaveWindow = 32;
425 static constexpr int kMaxLevels = 9;
434 static constexpr std::array<Template, kNumTemplates> kTemplates { {
462 std::vector<T> kernel;
463 std::vector<T> even, odd;
464 [[nodiscard]]
int historyHalf() const noexcept {
return 2 * pairs - 1; }
465 [[nodiscard]]
int delay() const noexcept {
return 2 * pairs - 1; }
474 std::vector<T> history;
478 [[nodiscard]]
static double noteHz(
int midi)
noexcept
480 return 440.0 * std::exp2((midi - 69) / 12.0);
483 [[nodiscard]]
static double besselI0(
double x)
noexcept
485 double sum = 1.0, term = 1.0;
486 for (
int k = 1; k < 64; ++k)
488 term *= (0.5 * x) /
static_cast<double>(k);
490 if (term * term < 1e-17 * sum)
break;
497 static void designStage(Stage& s,
double passHz,
double rate)
499 const double width = std::max(0.02, (0.5 * rate - 2.0 * passHz) / rate);
500 const double beta = 0.1102 * (kStopbandDb - 8.7);
501 const double length = (kStopbandDb - 8.0) / (2.285 * twoPi<double> * width) + 1.0;
502 const int k = std::clamp(
static_cast<int>(std::ceil((length - 3.0) / 4.0)), 0, 64);
504 const double half =
static_cast<double>(2 * k + 1);
505 std::vector<double> h(
static_cast<size_t>(s.pairs));
507 for (
int j = 0; j < s.pairs; ++j)
509 const int n = 2 * j + 1;
510 const double r =
static_cast<double>(n) / half;
511 const double w = besselI0(beta * std::sqrt(std::max(0.0, 1.0 - r * r)))
513 const double sinc = ((j & 1) ? -1.0 : 1.0) / (
pi<double> * static_cast<double>(n));
514 h[
static_cast<size_t>(j)] = sinc * w;
515 sum += 2.0 * h[
static_cast<size_t>(j)];
517 s.taps.resize(
static_cast<size_t>(s.pairs));
518 for (
int j = 0; j < s.pairs; ++j)
519 s.taps[
static_cast<size_t>(j)] =
static_cast<T
>(h[
static_cast<size_t>(j)] / sum);
520 s.centre =
static_cast<T
>(0.5 / sum);
521 s.kernel.resize(
static_cast<size_t>(2 * s.pairs));
522 for (
int j = 0; j < s.pairs; ++j)
524 s.kernel[
static_cast<size_t>(s.pairs - 1 - j)] = s.taps[
static_cast<size_t>(j)];
525 s.kernel[
static_cast<size_t>(s.pairs + j)] = s.taps[
static_cast<size_t>(j)];
530 [[nodiscard]]
static double stageGain(
const Stage& s,
double hz,
double rate)
noexcept
532 double a =
static_cast<double>(s.centre);
533 for (
int j = 0; j < s.pairs; ++j)
534 a += 2.0 *
static_cast<double>(s.taps[
static_cast<size_t>(j)])
535 * std::cos(twoPi<double> * hz / rate *
static_cast<double>(2 * j + 1));
541 const double fs = sampleRate_;
542 const double bin = fs /
static_cast<double>(windowSize_);
543 std::array<double, kNumOctaves> pass {};
545 for (
int o = 0; o < kNumOctaves; ++o)
547 pass[
static_cast<size_t>(o)] = noteHz(kFirstMidi + 12 * o + 11) + kMarginBins * bin;
549 while (d < kMaxLevels
550 && fs / std::exp2(d + 1) >= kRateSeparation * pass[
static_cast<size_t>(o)]
551 && (windowSize_ >> (d + 1)) >= kMinOctaveWindow)
553 octaves_[
static_cast<size_t>(o)].level = d;
554 levels_ = std::max(levels_, d);
557 stages_.assign(
static_cast<size_t>(levels_), Stage {});
558 for (
int k = 0; k < levels_; ++k)
561 for (
int o = 0; o < kNumOctaves; ++o)
562 if (octaves_[
static_cast<size_t>(o)].level > k)
563 p = std::max(p, pass[
static_cast<size_t>(o)]);
564 Stage& s = stages_[
static_cast<size_t>(k)];
565 designStage(s, p, fs / std::exp2(k));
566 const size_t phase =
static_cast<size_t>(s.historyHalf() + (hopSize_ >> (k + 1)));
567 s.even.assign(phase, T(0));
568 s.odd.assign(phase, T(0));
575 auto levelDelay = [&](
int d) {
577 for (
int s = 0; s < d; ++s) g += stages_[static_cast<size_t>(s)].delay() << s;
578 return g - ((1 << d) - 1);
581 for (
const Octave& o : octaves_) target = std::max(target, levelDelay(o.level));
582 analysisDelay_ = target;
584 for (
int o = 0; o < kNumOctaves; ++o)
586 Octave& oc = octaves_[
static_cast<size_t>(o)];
587 const int d = oc.level;
588 oc.length = windowSize_ >> d;
589 const double step = std::exp2(d);
590 oc.offset = std::max(0,
static_cast<int>(std::lround(
591 static_cast<double>(target - levelDelay(d)) / step)));
592 oc.history.assign(
static_cast<size_t>(oc.length + oc.offset), T(0));
594 const double rate = fs / step;
595 const double norm = 2.0 /
static_cast<double>(oc.length);
596 oc.rows.assign(
static_cast<size_t>(24 * oc.length), T(0));
597 for (
int k = 0; k < 12; ++k)
599 const double hz = noteHz(kFirstMidi + 12 * o + k);
601 for (
int s = 0; s < d; ++s)
602 gain *= stageGain(stages_[
static_cast<size_t>(s)], hz, fs / std::exp2(s));
603 const double scale = norm / std::max(gain, 1e-6);
604 const double w = twoPi<double> * hz / rate;
605 T* cosRow = oc.rows.data() +
static_cast<size_t>(k) *
static_cast<size_t>(oc.length);
606 T* sinRow = oc.rows.data() +
static_cast<size_t>(12 + k) *
static_cast<size_t>(oc.length);
607 for (
int i = 0; i < oc.length; ++i)
609 const double hann = 0.5 - 0.5 * std::cos(twoPi<double> *
static_cast<double>(i)
610 /
static_cast<double>(oc.length));
611 const double a = w *
static_cast<double>(i);
612 cosRow[i] =
static_cast<T
>(scale * hann * std::cos(a));
613 sinRow[i] =
static_cast<T
>(scale * hann * std::sin(a));
618 input_.assign(
static_cast<size_t>(hopSize_), T(0));
619 for (
int d = 1; d <= levels_; ++d)
620 levelBlock_[
static_cast<size_t>(d)].assign(
static_cast<size_t>(hopSize_ >> d), T(0));
624 void advance(
int count)
noexcept
627 if (inputFill_ >= hopSize_)
635 static void runStage(Stage& s,
const T* x,
int n, T* DSPARK_RESTRICT y)
noexcept
637 constexpr int W = simd::kVecWidth<T>;
638 using O = simd::Vec<T, W>;
639 const int hist = s.historyHalf();
640 T* e = s.even.data();
642 const int outN = n / 2;
644 for (; m + W <= outN; m += W)
646 typename O::V ev, od;
647 O::loadDeinterleave(x + 2 * m, ev, od);
648 O::store(e + hist + m, ev);
649 O::store(o + hist + m, od);
651 for (; m < outN; ++m)
653 e[hist + m] = x[2 * m];
654 o[hist + m] = x[2 * m + 1];
659 const T* centre = e + s.pairs;
660 const auto c = O::set1(s.centre);
662 for (; k + W <= outN; k += W)
663 O::store(y + k, O::madd(c, O::load(centre + k), O::load(y + k)));
664 for (; k < outN; ++k)
668 O::store(lanes, O::madd(c, O::set1(centre[k]), O::set1(y[k])));
671 std::memmove(e, e + outN,
static_cast<size_t>(hist) *
sizeof(T));
672 std::memmove(o, o + outN,
static_cast<size_t>(hist) *
sizeof(T));
675 void analyze() noexcept
678 const T* source = input_.data();
680 for (
int d = 0; d < levels_; ++d)
682 T* out = levelBlock_[
static_cast<size_t>(d + 1)].data();
683 runStage(stages_[
static_cast<size_t>(d)], source, n, out);
691 std::array<double, 12> chroma {};
692 std::array<double, static_cast<std::size_t>(kNumNotes)> noteE {};
693 double total = 0.0, maxNote = 0.0;
694 for (
int o = 0; o < kNumOctaves; ++o)
696 Octave& oc = octaves_[
static_cast<size_t>(o)];
697 const int fresh = hopSize_ >> oc.level;
698 const int keep = oc.length + oc.offset - fresh;
699 T* h = oc.history.data();
700 std::memmove(h, h + fresh,
static_cast<size_t>(keep) *
sizeof(T));
701 std::memcpy(h + keep, oc.level == 0 ? input_.data()
702 : levelBlock_[static_cast<size_t>(oc.level)].data(),
703 static_cast<size_t>(fresh) * sizeof(T));
705 for (
int k = 0; k < 12; ++k)
707 const T* cosRow = oc.rows.data() +
static_cast<size_t>(k) *
static_cast<size_t>(oc.length);
708 const T* sinRow = oc.rows.data() +
static_cast<size_t>(12 + k) *
static_cast<size_t>(oc.length);
709 const double re =
static_cast<double>(
simd::dotProduct(cosRow, window, oc.length));
710 const double im =
static_cast<double>(
simd::dotProduct(sinRow, window, oc.length));
711 const double e = re * re + im * im;
712 const int n12 = 12 * o + k;
713 noteE[
static_cast<std::size_t
>(n12)] = e;
714 chroma[
static_cast<std::size_t
>((kFirstMidi + n12) % 12)] += e;
716 maxNote = std::max(maxNote, e);
723 for (
int pc = 0; pc < 12; ++pc)
724 chromaFrame_[
static_cast<std::size_t
>(pc)] =
725 static_cast<T
>(chroma[
static_cast<std::size_t
>(pc)]);
731 for (
int n12 = 0; n12 < kNumNotes; ++n12)
733 const double e = noteE[
static_cast<std::size_t
>(n12)];
734 const double prev = (n12 > 0) ? noteE[
static_cast<std::size_t
>(n12 - 1)] : 0.0;
735 const double next = (n12 + 1 < kNumNotes) ? noteE[
static_cast<std::size_t
>(n12 + 1)] : 0.0;
736 if (e > 0.15 * maxNote && e >= prev && e >= next)
738 bassPc = (kFirstMidi + n12) % 12;
745 if (!(total >= 1e-12) || !std::isfinite(total))
748 Result held = unpack(packed_.load(std::memory_order_relaxed));
749 held.confidence = 0.0f;
750 packed_.store(pack(held), std::memory_order_relaxed);
755 for (
const double c : chroma) norm += c * c;
756 norm = std::sqrt(norm);
759 double best = 0.0, second = 0.0;
762 for (
int root = 0; root < 12; ++root)
764 for (
const auto& tpl : kTemplates)
767 for (
int iv = 0; iv < 12; ++iv)
768 if (tpl.mask & (1u << iv))
769 inSum += chroma[
static_cast<std::size_t
>((root + iv) % 12)];
770 double score = inSum / (norm * std::sqrt(
static_cast<double>(tpl.count)));
780 else if (score > second)
788 const double margin = (best > 1e-9) ? std::clamp((best - second) / best * 4.0, 0.0, 1.0)
790 const auto confidence =
static_cast<float>(std::clamp(best, 0.0, 1.0) * (0.5 + 0.5 * margin));
793 if (confidence >= threshold_.load(std::memory_order_relaxed))
795 out.rootPitchClass = bestRoot;
797 out.confidence = confidence;
801 out = unpack(packed_.load(std::memory_order_relaxed));
802 out.confidence = confidence;
804 packed_.store(pack(out), std::memory_order_relaxed);
808 [[nodiscard]]
static std::uint64_t pack(
const Result& r)
noexcept
810 const auto conf =
static_cast<std::uint32_t
>(std::clamp(r.confidence, 0.0f, 1.0f) * 65535.0f);
811 return (
static_cast<std::uint64_t
>(
static_cast<std::uint8_t
>(r.rootPitchClass + 1)) << 24)
812 | (
static_cast<std::uint64_t
>(
static_cast<std::uint8_t
>(r.type)) << 16)
816 [[nodiscard]]
static Result unpack(std::uint64_t v)
noexcept
819 r.rootPitchClass =
static_cast<int>((v >> 24) & 0xFF) - 1;
820 r.type =
static_cast<ChordType>((v >> 16) & 0xFF);
821 r.confidence =
static_cast<float>(v & 0xFFFF) / 65535.0f;
826 double sampleRate_ = 48000.0;
827 int windowSize_ = 4096;
830 int analysisDelay_ = 0;
831 std::atomic<bool> prepared_ {
false };
833 std::vector<T> input_;
835 std::vector<Stage> stages_;
836 std::array<std::vector<T>,
static_cast<std::size_t
>(kMaxLevels + 1)> levelBlock_;
837 std::array<Octave, static_cast<std::size_t>(kNumOctaves)> octaves_;
840 std::array<T, 12> chromaFrame_ {};
841 std::uint64_t frameCount_ = 0;
843 std::atomic<std::uint64_t> packed_ { 0 };
844 std::atomic<float> threshold_ { 0.55f };