110 static_assert(std::atomic<double>::is_always_lock_free,
111 "StudioVocoder requires lock-free std::atomic<double>");
112 static_assert(std::atomic<unsigned>::is_always_lock_free,
113 "StudioVocoder requires lock-free std::atomic<unsigned>");
114 static_assert(std::atomic<bool>::is_always_lock_free,
115 "StudioVocoder requires lock-free std::atomic<bool>");
138 bool prepare(
double sampleRate,
int numChannels,
int fftSize,
bool resampleCompensation)
140 if (!(sampleRate > 0.0) || !std::isfinite(sampleRate) || numChannels < 1
141 || (
fftSize & (
fftSize - 1)) != 0 || fftSize < 256 || fftSize > (1 << 20))
145 sampleRate_ = sampleRate;
146 numChannels_ = numChannels;
150 resample_ = resampleCompensation;
154 while (No_ < 8192 &&
static_cast<double>(No_) * 1.5 < 0.0213 * sampleRate_) No_ <<= 1;
161 delta_ = std::min(16, std::max(1, N_ / 64));
164 while (ring < 2 * N_ + 2 * D_ + No_) ring <<= 1;
166 ringMask_ = ring - 1;
168 accumMask_ = accumSize_ - 1;
170 fft_ = std::make_unique<FFTReal<T>>(
static_cast<size_t>(N_));
171 fftO_ = std::make_unique<FFTReal<T>>(
static_cast<size_t>(No_));
173 window_.resize(
static_cast<size_t>(N_));
174 for (
int k = 0; k < N_; ++k)
175 window_[
static_cast<size_t>(k)] =
static_cast<T
>(std::sqrt(
176 0.5 - 0.5 * std::cos(2.0 * std::numbers::pi * k / N_)));
177 windowO_.resize(
static_cast<size_t>(No_));
178 for (
int k = 0; k < No_; ++k)
179 windowO_[
static_cast<size_t>(k)] =
static_cast<T
>(
180 0.5 - 0.5 * std::cos(2.0 * std::numbers::pi * k / No_));
182 const auto nb =
static_cast<size_t>(bins_);
183 const auto spec =
static_cast<size_t>(N_ + 2);
184 ring_.assign(
static_cast<size_t>(numChannels_), std::vector<T>(
static_cast<size_t>(ringSize_), T(0)));
185 accum_.assign(
static_cast<size_t>(numChannels_), std::vector<T>(
static_cast<size_t>(accumSize_), T(0)));
186 spec_.assign(
static_cast<size_t>(numChannels_), std::vector<T>(spec, T(0)));
187 prevSpec_.assign(
static_cast<size_t>(numChannels_), std::vector<T>(spec, T(0)));
189 frame_.resize(
static_cast<size_t>(N_));
192 crossRe_.resize(nb); crossIm_.resize(nb);
193 dRe_.resize(nb); dIm_.resize(nb);
198 rotRe_.resize(nb); rotIm_.resize(nb);
200 bucketNext_.resize(2 * nb + 2);
201 cepsTime_.resize(
static_cast<size_t>(N_));
202 cepsSpec_.resize(spec);
207 frameO_.resize(
static_cast<size_t>(No_));
208 specO_.resize(
static_cast<size_t>(No_ + 2));
209 powO_.resize(
static_cast<size_t>(No_ / 2 + 1));
210 bandCur_.assign(
static_cast<size_t>(numBands_), T(0));
211 bandPrevMax_.assign(
static_cast<size_t>(numBands_), T(0));
212 bandPrev_.assign(
static_cast<size_t>(numBands_), T(0));
222 if (!prepared_)
return;
223 for (
auto& r : ring_) std::fill(r.begin(), r.end(), T(0));
224 for (
auto& a : accum_) std::fill(a.begin(), a.end(), T(0));
225 for (
auto& s : prevSpec_) std::fill(s.begin(), s.end(), T(0));
226 std::fill(prevMag_.begin(), prevMag_.end(), T(0));
228 std::fill(theta_.begin(), theta_.end(), 0.0);
229 for (
int k = 0; k < bins_; ++k)
230 omPrev_[
static_cast<size_t>(k)] = kTwoPi * k / N_;
232 adoptParamsIfDirty();
233 stActive_ = std::clamp(targetSemitones_, -12.0, 12.0);
234 ratio_ = std::exp2(stActive_ / 12.0);
237 frameStart_ =
static_cast<int64_t
>(accumSize_);
241 aNext_ =
static_cast<double>(Rs_) - 0.5 * N_;
244 cCur_ =
static_cast<double>(frameStart_) + 0.5 * N_ - Rs_;
246 originStream_ =
static_cast<double>(frameStart_) + 0.5 * N_;
247 originRatio_ = ratio_;
248 prevAnalysisStart_ = 0;
251 lockHead_ = lockCount_ = 0;
252 rejoinE_ = 0.0; rejoinC_ = 0.0; rejoinJ_ = 1.0;
253 lastLockS_ = -1e18; lastLockT_ = -1e18;
257 std::fill(bandPrev_.begin(), bandPrev_.end(), T(0));
258 std::fill(bandPrevMax_.begin(), bandPrevMax_.end(), T(0));
259 fluxFill_ = 0; fluxPos_ = 0;
260 fluxPrev_ = 0.0; fluxPrev2_ = 0.0; candPrev_ =
false; candFrame_ = -1;
261 lastOnsetFrame_ = -1000;
262 onsetRing_.fill(-1e18);
271 seq_.fetch_add(1, std::memory_order_acq_rel);
272 std::atomic_thread_fence(std::memory_order_release);
273 stgSemitones_.store(p.targetSemitones, std::memory_order_relaxed);
274 stgTransient_.store(p.transientPreserve, std::memory_order_relaxed);
275 stgFormant_.store(p.formantPreserve, std::memory_order_relaxed);
276 seq_.fetch_add(1, std::memory_order_release);
277 dirty_.store(
true, std::memory_order_release);
286 const int64_t need = analysisStart() + N_ + D_ - inCount_;
287 return static_cast<int>(std::max<int64_t>(0, need));
292 void pushInput(
int ch,
const T* src,
int count)
noexcept
294 auto& r = ring_[
static_cast<size_t>(ch)];
295 int64_t p = inCount_;
296 for (
int k = 0; k < count; ++k, ++p)
297 r[
static_cast<size_t>(p & ringMask_)] = std::isfinite(src[k]) ? src[k] : T(0);
309 runDetector(numActiveChannels);
310 if (inCount_ >= analysisStart() + N_ + D_)
311 processFrame(numActiveChannels);
318 steerValue_ = nominalCentre;
335 [[nodiscard]]
double activeRatio() const noexcept {
return ratio_; }
343 return static_cast<double>(frameStart_) + 0.5 * N_;
349 return originStream_ + originRatio_ * (x - origin_);
352 [[nodiscard]]
const T*
olaData(
int ch)
const noexcept {
return accum_[
static_cast<size_t>(ch)].data(); }
353 [[nodiscard]] int64_t
olaMask() const noexcept {
return static_cast<int64_t
>(accumMask_); }
354 [[nodiscard]]
int olaSize() const noexcept {
return accumSize_; }
356 [[nodiscard]] int64_t
writeHead() const noexcept {
return frameStart_; }
357 [[nodiscard]]
int fftSize() const noexcept {
return prepared_ ? N_ : 0; }
358 [[nodiscard]]
int synthHop() const noexcept {
return Rs_; }
360 [[nodiscard]]
int lookahead() const noexcept {
return D_; }
362 [[nodiscard]] int64_t
inputCount() const noexcept {
return inCount_; }
365 static constexpr double kTwoPi = 2.0 * std::numbers::pi;
366 static constexpr int kSeqlockMaxAttempts = 3;
367 static constexpr int kMaxLocks = 32;
370 static constexpr int kBuckets = 256;
373 static constexpr double kHeapFloorDb = 100.0;
376 static constexpr T kRiseRatio =
static_cast<T
>(1.4142135623730951);
378 static constexpr double kResetCover = 0.375;
380 static constexpr double kFluxDelta = 0.025;
381 static constexpr int kFluxWindow = 12;
383 struct Lock {
double s, target, h; };
385 [[nodiscard]]
static double princArg(
double x)
noexcept
387 return x - kTwoPi * std::round(x / kTwoPi);
390 [[nodiscard]] int64_t analysisStart() const noexcept
392 return static_cast<int64_t
>(std::llround(aNext_)) - N_ / 2;
399 void adoptParamsIfDirty() noexcept
401 if (!dirty_.exchange(
false, std::memory_order_acquire))
return;
402 for (
int attempt = 0; attempt < kSeqlockMaxAttempts; ++attempt)
404 const unsigned s0 = seq_.load(std::memory_order_acquire);
405 if ((s0 & 1u) != 0u)
continue;
406 const double st = stgSemitones_.load(std::memory_order_relaxed);
407 const bool tr = stgTransient_.load(std::memory_order_relaxed);
408 const bool fo = stgFormant_.load(std::memory_order_relaxed);
411 std::atomic_thread_fence(std::memory_order_acquire);
412 if (s0 == seq_.load(std::memory_order_relaxed))
414 targetSemitones_ = st; transientOn_ = tr; formantOn_ = fo;
418 dirty_.store(
true, std::memory_order_release);
423 void analyse(
int ch, int64_t start, T* out)
noexcept
425 const auto& r = ring_[
static_cast<size_t>(ch)];
426 for (
int k = 0; k < N_; ++k)
427 frame_[
static_cast<size_t>(k)] = r[
static_cast<size_t>((start + k) & ringMask_)]
428 * window_[
static_cast<size_t>(k)];
429 fft_->forward(frame_.data(), out);
432 void processFrame(
int nCh)
noexcept
434 nCh = std::clamp(nCh, 1, numChannels_);
435 const int64_t A = analysisStart();
436 const double Ra = firstFrame_ ?
static_cast<double>(Rs_)
437 : static_cast<double>(A - prevAnalysisStart_);
438 const double binW = kTwoPi / N_;
439 const double Rs =
static_cast<double>(Rs_);
442 std::fill(mag_.begin(), mag_.end(), T(0));
443 std::fill(crossRe_.begin(), crossRe_.end(), 0.0);
444 std::fill(crossIm_.begin(), crossIm_.end(), 0.0);
445 std::fill(dRe_.begin(), dRe_.end(), 0.0);
446 std::fill(dIm_.begin(), dIm_.end(), 0.0);
447 for (
int ch = 0; ch < nCh; ++ch)
449 T* X = spec_[
static_cast<size_t>(ch)].data();
450 const T* P = prevSpec_[
static_cast<size_t>(ch)].data();
452 analyse(ch, A + delta_, specD_.data());
453 for (
int k = 0; k < bins_; ++k)
455 const double xr = X[2 * k], xi = X[2 * k + 1];
456 const double pr = P[2 * k],
pi = P[2 * k + 1];
457 const double dr = specD_[
static_cast<size_t>(2 * k)];
458 const double di = specD_[
static_cast<size_t>(2 * k + 1)];
459 mag_[
static_cast<size_t>(k)] +=
static_cast<T
>(xr * xr + xi * xi);
460 crossRe_[
static_cast<size_t>(k)] += xr * pr + xi *
pi;
461 crossIm_[
static_cast<size_t>(k)] += xi * pr - xr *
pi;
462 dRe_[
static_cast<size_t>(k)] += dr * xr + di * xi;
463 dIm_[
static_cast<size_t>(k)] += di * xr - dr * xi;
467 for (
int k = 0; k < bins_; ++k)
469 auto& m = mag_[
static_cast<size_t>(k)];
471 maxMag = std::max(maxMag, m);
475 const double dl =
static_cast<double>(delta_);
476 for (
int k = 0; k < bins_; ++k)
478 const double wk = binW * k;
479 const double omNow = wk + princArg(std::atan2(dIm_[
static_cast<size_t>(k)],
480 dRe_[
static_cast<size_t>(k)]) - wk * dl) / dl;
484 const double dphi = std::atan2(crossIm_[
static_cast<size_t>(k)],
485 crossRe_[
static_cast<size_t>(k)]);
486 const double prior = 0.5 * (omNow + omPrev_[
static_cast<size_t>(k)]);
487 const double om = Ra >= 1.0 ? prior + princArg(dphi - prior * Ra) / Ra : prior;
488 inc = princArg(theta_[
static_cast<size_t>(k)] + Rs * om - dphi);
492 tinc_[
static_cast<size_t>(k)] = std::isfinite(inc) ? inc : 0.0;
493 omPrev_[
static_cast<size_t>(k)] = omNow;
498 std::fill(theta_.begin(), theta_.end(), 0.0);
519 if (transientOn_ && !firstFrame_ && lockCount_ > 0)
521 const Lock& L = locks_[
static_cast<size_t>(lockHead_)];
522 const double c =
static_cast<double>(frameStart_) + 0.5 * N_;
523 bool alone = L.h >= kResetCover * N_;
524 for (
const double o : onsetRing_)
525 if (std::abs(o - L.s) > 1.0 && std::abs(o - L.s) < static_cast<double>(N_))
527 if (alone && c >= L.target - L.h && c <= L.target + L.h)
528 for (
int k = 0; k < bins_; ++k)
529 if (mag_[
static_cast<size_t>(k)] > kRiseRatio * prevMag_[
static_cast<size_t>(k)])
530 theta_[
static_cast<size_t>(k)] = 0.0;
533 theta_[
static_cast<size_t>(bins_ - 1)] = 0.0;
534 for (
int k = 0; k < bins_; ++k)
536 rotRe_[
static_cast<size_t>(k)] =
static_cast<T
>(std::cos(theta_[
static_cast<size_t>(k)]));
537 rotIm_[
static_cast<size_t>(k)] =
static_cast<T
>(std::sin(theta_[
static_cast<size_t>(k)]));
541 const bool formant = resample_ && formantOn_ && std::abs(ratio_ - 1.0) > 1e-6;
542 const bool taper = resample_ && ratio_ > 1.0;
543 if (formant) computeFormantGains();
544 else std::fill(gain_.begin(), gain_.end(), T(1));
547 const int cut =
static_cast<int>(
static_cast<double>(N_ / 2) / ratio_);
548 const int taperStart = std::max(1, cut - 4);
549 for (
int k = taperStart; k < bins_; ++k)
550 gain_[
static_cast<size_t>(k)] *= (k <= cut)
551 ?
static_cast<T
>(cut - k + 1) /
static_cast<T
>(cut - taperStart + 1) : T(0);
555 const T norm =
static_cast<T
>(Rs / (0.5 * N_));
556 for (
int ch = 0; ch < nCh; ++ch)
558 T* X = spec_[
static_cast<size_t>(ch)].data();
559 std::copy(X, X + N_ + 2, prevSpec_[
static_cast<size_t>(ch)].data());
560 for (
int k = 0; k < bins_; ++k)
562 const T re = X[2 * k], im = X[2 * k + 1];
563 const T rr = rotRe_[
static_cast<size_t>(k)] * gain_[
static_cast<size_t>(k)];
564 const T ri = rotIm_[
static_cast<size_t>(k)] * gain_[
static_cast<size_t>(k)];
565 X[2 * k] = re * rr - im * ri;
566 X[2 * k + 1] = re * ri + im * rr;
570 fft_->inverse(X, frame_.data());
571 auto& acc = accum_[
static_cast<size_t>(ch)];
572 for (
int k = N_ - Rs_; k < N_; ++k)
573 acc[
static_cast<size_t>((frameStart_ + k) & accumMask_)] = T(0);
574 for (
int k = 0; k < N_; ++k)
575 acc[
static_cast<size_t>((frameStart_ + k) & accumMask_)]
576 += frame_[
static_cast<size_t>(k)] * window_[
static_cast<size_t>(k)] * norm;
578 for (
int ch = nCh; ch < numChannels_; ++ch)
579 std::fill(prevSpec_[
static_cast<size_t>(ch)].begin(),
580 prevSpec_[
static_cast<size_t>(ch)].end(), T(0));
581 std::copy(mag_.begin(), mag_.end(), prevMag_.begin());
582 prevMaxMag_ = maxMag;
584 prevAnalysisStart_ = A;
587 cCur_ =
static_cast<double>(frameStart_) + 0.5 * N_;
598 void propagate(T maxMag)
noexcept
600 const T tol = maxMag *
static_cast<T
>(std::pow(10.0, -kHeapFloorDb / 20.0));
602 for (
int k = 0; k < bins_; ++k)
604 const bool quiet = mag_[
static_cast<size_t>(k)] < tol;
605 done_[
static_cast<size_t>(k)] = quiet ? 1 : 0;
606 theta_[
static_cast<size_t>(k)] = tinc_[
static_cast<size_t>(k)];
610 queueTop_ = bucketBits(std::max(maxMag, prevMaxMag_));
611 queueCursor_ = kBuckets - 1;
612 bucketHead_.fill(-1);
613 for (
int k = 0; k < bins_; ++k)
614 if (prevMag_[
static_cast<size_t>(k)] > tol)
615 queuePush(prevMag_[
static_cast<size_t>(k)], 2 * k);
621 int best = -1; T bm = T(-1);
622 for (
int k = 0; k < bins_; ++k)
623 if (!done_[
static_cast<size_t>(k)] && mag_[
static_cast<size_t>(k)] > bm)
624 { bm = mag_[
static_cast<size_t>(k)]; best = k; }
628 done_[
static_cast<size_t>(best)] = 1; --todo;
629 queuePush(mag_[
static_cast<size_t>(best)], 2 * best + 1);
632 const int code = queuePop();
633 const int k = code >> 1;
636 if (!done_[
static_cast<size_t>(k)])
638 done_[
static_cast<size_t>(k)] = 1; --todo;
639 queuePush(mag_[
static_cast<size_t>(k)], 2 * k + 1);
644 const double th = theta_[
static_cast<size_t>(k)];
645 if (k + 1 < bins_ && !done_[
static_cast<size_t>(k + 1)])
647 done_[
static_cast<size_t>(k + 1)] = 1; --todo;
648 theta_[
static_cast<size_t>(k + 1)] = th;
649 queuePush(mag_[
static_cast<size_t>(k + 1)], 2 * (k + 1) + 1);
651 if (k > 0 && !done_[
static_cast<size_t>(k - 1)])
653 done_[
static_cast<size_t>(k - 1)] = 1; --todo;
654 theta_[
static_cast<size_t>(k - 1)] = th;
655 queuePush(mag_[
static_cast<size_t>(k - 1)], 2 * (k - 1) + 1);
663 [[nodiscard]]
static int bucketBits(T magnitude)
noexcept
665 return static_cast<int>(std::bit_cast<std::uint32_t>(
static_cast<float>(magnitude)) >> 20);
671 void queuePush(T key,
int code)
noexcept
673 const int b = std::clamp(queueTop_ - bucketBits(key), 0, kBuckets - 1);
674 bucketNext_[
static_cast<size_t>(code)] = bucketHead_[
static_cast<size_t>(b)];
675 bucketHead_[
static_cast<size_t>(b)] = code;
676 queueCursor_ = std::min(queueCursor_, b);
681 int queuePop() noexcept
683 while (bucketHead_[
static_cast<size_t>(queueCursor_)] < 0) ++queueCursor_;
684 const int code = bucketHead_[
static_cast<size_t>(queueCursor_)];
685 bucketHead_[
static_cast<size_t>(queueCursor_)] = bucketNext_[
static_cast<size_t>(code)];
692 void computeFormantGains() noexcept
694 for (
int k = 0; k < bins_; ++k)
695 cepsTime_[
static_cast<size_t>(k)] = std::log(mag_[
static_cast<size_t>(k)] + T(1e-9));
696 for (
int k = bins_; k < N_; ++k)
697 cepsTime_[
static_cast<size_t>(k)] = cepsTime_[
static_cast<size_t>(N_ - k)];
698 fft_->forward(cepsTime_.data(), cepsSpec_.data());
699 const int keep = std::min(std::max(8,
static_cast<int>(0.001 * sampleRate_)), bins_ - 1);
700 for (
int k = keep + 1; k < bins_; ++k)
702 cepsSpec_[
static_cast<size_t>(2 * k)] = T(0);
703 cepsSpec_[
static_cast<size_t>(2 * k + 1)] = T(0);
705 fft_->inverse(cepsSpec_.data(), cepsTime_.data());
706 for (
int k = 0; k < bins_; ++k)
707 envLog_[
static_cast<size_t>(k)] = cepsTime_[
static_cast<size_t>(k)];
708 for (
int k = 0; k < bins_; ++k)
710 const double pos = std::min(
static_cast<double>(k) * ratio_,
static_cast<double>(bins_ - 1));
711 const auto i0 =
static_cast<int>(pos);
712 const auto fr =
static_cast<T
>(pos - i0);
713 const int i1 = std::min(i0 + 1, bins_ - 1);
714 const T target = envLog_[
static_cast<size_t>(i0)]
715 + (envLog_[
static_cast<size_t>(i1)] - envLog_[
static_cast<size_t>(i0)]) * fr;
716 gain_[
static_cast<size_t>(k)] = std::exp(std::clamp(
717 target - envLog_[
static_cast<size_t>(k)], T(-4.6), T(4.6)));
724 void planNext() noexcept
726 adoptParamsIfDirty();
727 const double stTarget = std::clamp(targetSemitones_, -12.0, 12.0);
728 stActive_ += std::clamp(stTarget - stActive_, -0.5, 0.5);
729 ratio_ = std::exp2(stActive_ / 12.0);
730 const double r = ratio_;
732 const double c =
static_cast<double>(frameStart_) + 0.5 * N_;
733 if (steer_) { aNom_ = steerValue_; steer_ =
false; }
734 else aNom_ +=
static_cast<double>(Rs_) / r;
738 while (lockCount_ > 0)
740 const Lock& L = locks_[
static_cast<size_t>(lockHead_)];
741 if (c < L.target + L.h)
break;
742 rejoinC_ = L.target + L.h;
743 rejoinE_ = (L.s + L.h) - (aNom_ + (rejoinC_ - c) / r);
744 rejoinJ_ = std::max(
static_cast<double>(N_), 2.0 * L.h * std::abs(r - 1.0));
745 lockHead_ = (lockHead_ + 1) % kMaxLocks;
752 const Lock& L = locks_[
static_cast<size_t>(lockHead_)];
753 if (c >= L.target - L.h)
754 a = L.s + (c - L.target);
757 const double span = (L.target - L.h) - cCur_;
758 const double f = span > 0.0 ? (c - cCur_) / span : 1.0;
759 a = aCur_ + ((L.s - L.h) - aCur_) * std::clamp(f, 0.0, 1.0);
764 const double f = std::clamp(1.0 - (c - rejoinC_) / rejoinJ_, 0.0, 1.0);
765 a = aNom_ + rejoinE_ * f;
767 aNext_ = std::max(a, aCur_);
771 void addOnset(
double s)
noexcept
773 onsetRing_[
static_cast<size_t>(onsetPos_)] = s;
774 onsetPos_ = (onsetPos_ + 1) % kOnsetRing;
775 if (!transientOn_ || lockCount_ >= kMaxLocks)
return;
776 const double r = ratio_;
777 const double cNext =
static_cast<double>(frameStart_) + 0.5 * N_;
778 const double target = cNext + (s - aNom_) * r;
780 h = std::min(h, s - aCur_ - 1.0);
781 h = std::min(h, target - cNext);
782 if (r < 1.0) h = std::min(h, leadLimit_ / (1.0 / r - 1.0));
783 else if (r > 1.0) h = std::min(h, leadLimit_ / (1.0 - 1.0 / r));
784 double prevS = lastLockS_, prevT = lastLockT_, prevH = 0.0;
787 const Lock& P = locks_[
static_cast<size_t>((lockHead_ + lockCount_ - 1) % kMaxLocks)];
788 prevS = P.s; prevT = P.target; prevH = P.h;
790 h = std::min(h, (s - prevS) - prevH -
static_cast<double>(Rs_));
791 h = std::min(h, (target - prevT) - prevH -
static_cast<double>(Rs_));
792 if (!(h >= 0.5 * Rs_))
return;
793 locks_[
static_cast<size_t>((lockHead_ + lockCount_) % kMaxLocks)] = Lock { s, target, h };
795 lastLockS_ = s; lastLockT_ = target;
797 const double keepNom = aNom_;
798 replanNextFrame(keepNom);
801 void replanNextFrame(
double nom)
noexcept
803 const double c =
static_cast<double>(frameStart_) + 0.5 * N_;
804 const Lock& L = locks_[
static_cast<size_t>(lockHead_)];
806 if (c >= L.target - L.h)
807 a = L.s + (c - L.target);
810 const double span = (L.target - L.h) - cCur_;
811 const double f = span > 0.0 ? (c - cCur_) / span : 1.0;
812 a = aCur_ + ((L.s - L.h) - aCur_) * std::clamp(f, 0.0, 1.0);
817 aNext_ = std::max(a, aCur_);
822 void buildOnsetBank()
824 fbStart_.clear(); fbCount_.clear(); fbOffset_.clear(); fbW_.clear();
825 const double binHz = sampleRate_ / No_;
826 const int nb = No_ / 2 + 1;
827 const double fMax = std::min(16000.0, 0.5 * sampleRate_ * 0.999);
828 std::vector<int> centres;
829 for (
int i = 0; ; ++i)
831 const double f = 27.5 * std::pow(2.0, i / 24.0);
833 const int b = std::clamp(
static_cast<int>(std::lround(f / binHz)), 0, nb - 1);
834 if (centres.empty() || b > centres.back()) centres.push_back(b);
836 for (
size_t j = 1; j + 1 < centres.size(); ++j)
838 const int lo = centres[j - 1], ce = centres[j], hi = centres[j + 1];
839 fbStart_.push_back(lo);
840 fbOffset_.push_back(
static_cast<int>(fbW_.size()));
841 for (
int k = lo; k <= hi; ++k)
842 fbW_.push_back(
static_cast<T
>(k <= ce ?
double(k - lo) / (ce - lo)
843 : double(hi - k) / (hi - ce)));
844 fbCount_.push_back(hi - lo + 1);
846 numBands_ =
static_cast<int>(fbStart_.size());
847 odfScale_ =
static_cast<T
>(2048.0 / No_);
851 void runDetector(
int nCh)
noexcept
853 nCh = std::clamp(nCh, 1, numChannels_);
854 while (nextFrameO_ * hopO_ + No_ <= inCount_)
856 const int64_t start = nextFrameO_ * hopO_;
857 std::fill(powO_.begin(), powO_.end(), T(0));
858 for (
int ch = 0; ch < nCh; ++ch)
860 const auto& r = ring_[
static_cast<size_t>(ch)];
861 for (
int k = 0; k < No_; ++k)
862 frameO_[
static_cast<size_t>(k)] = r[
static_cast<size_t>((start + k) & ringMask_)]
863 * windowO_[
static_cast<size_t>(k)];
864 fftO_->forward(frameO_.data(), specO_.data());
865 for (
int k = 0; k <= No_ / 2; ++k)
867 const T re = specO_[
static_cast<size_t>(2 * k)], im = specO_[
static_cast<size_t>(2 * k + 1)];
868 powO_[
static_cast<size_t>(k)] += re * re + im * im;
871 const T inv = T(1) /
static_cast<T
>(nCh);
873 for (
int b = 0; b < numBands_; ++b)
876 const int s0 = fbStart_[
static_cast<size_t>(b)], off = fbOffset_[
static_cast<size_t>(b)];
877 for (
int i = 0; i < fbCount_[static_cast<size_t>(b)]; ++i)
878 acc += std::sqrt(powO_[
static_cast<size_t>(s0 + i)] * inv) * fbW_[
static_cast<size_t>(off + i)];
879 const T v = std::log10(acc * odfScale_ + T(1));
880 bandCur_[
static_cast<size_t>(b)] = v;
881 const double d =
static_cast<double>(v - bandPrevMax_[
static_cast<size_t>(b)]);
882 if (d > 0.0) flux += d;
884 flux /= std::max(1, numBands_);
885 for (
int b = 0; b < numBands_; ++b)
887 T mx = bandCur_[
static_cast<size_t>(b)];
888 if (b > 0) mx = std::max(mx, bandCur_[
static_cast<size_t>(b - 1)]);
889 if (b + 1 < numBands_) mx = std::max(mx, bandCur_[
static_cast<size_t>(b + 1)]);
890 bandPrevMax_[
static_cast<size_t>(b)] = mx;
892 if (nextFrameO_ == 0) flux = 0.0;
896 if (candPrev_ && fluxPrev_ >= flux && candFrame_ - lastOnsetFrame_ > 4)
898 lastOnsetFrame_ = candFrame_;
899 const double s = locateOnset(candFrame_, nCh);
900 if (s >= 0.0) addOnset(s);
906 const int n = std::min(fluxFill_, kFluxWindow);
907 for (
int i = 0; i < n; ++i) medScratch_[static_cast<size_t>(i)] = fluxHist_[
static_cast<size_t>(i)];
908 std::nth_element(medScratch_.begin(), medScratch_.begin() + n / 2, medScratch_.begin() + n);
909 med = medScratch_[
static_cast<size_t>(n / 2)];
912 const double lo = *std::max_element(medScratch_.begin(), medScratch_.begin() + n / 2);
913 med = 0.5 * (med + lo);
916 candPrev_ = (flux - med > kFluxDelta) && flux >= fluxPrev_;
917 candFrame_ = nextFrameO_;
918 fluxHist_[
static_cast<size_t>(fluxPos_)] = flux;
919 fluxPos_ = (fluxPos_ + 1) % kFluxWindow;
928 [[nodiscard]]
double locateOnset(int64_t i,
int nCh)
const noexcept
930 const int64_t lo = std::max<int64_t>({ 16, i * hopO_ - 2 * hopO_, inCount_ - ringSize_ + 64 });
931 const int64_t hi = std::min<int64_t>(i * hopO_ + (3 * No_) / 4 + hopO_, inCount_ - 16);
932 if (hi - lo < 8)
return -1.0;
933 auto pw = [&](int64_t n) {
935 for (
int ch = 0; ch < nCh; ++ch)
937 const double v = ring_[
static_cast<size_t>(ch)][
static_cast<size_t>(n & ringMask_)];
944 for (int64_t n = lo - 16; n < lo + 16; ++n) run += pw(n);
945 double peak = -1.0; int64_t pk = lo;
949 for (int64_t n = lo; n < hi; ++n)
951 if (rr > peak) { peak = rr; pk = n; }
952 rr += pw(n + 16) - pw(n - 16);
955 if (peak <= 0.0)
return -1.0;
959 for (int64_t n = pk - 16; n < pk + 16; ++n) rr += pw(n);
961 while (j > lo && rr > peak / 16.0)
963 rr += pw(j - 17) - pw(j + 15);
966 return static_cast<double>(j);
970 double sampleRate_ = 48000.0;
971 int numChannels_ = 0;
972 bool prepared_ =
false;
973 bool resample_ =
false;
974 int N_ = 4096, bins_ = 2049, Rs_ = 1024;
975 int D_ = 1536, delta_ = 16;
976 int ringSize_ = 0, ringMask_ = 0, accumSize_ = 0, accumMask_ = 0;
978 std::unique_ptr<FFTReal<T>> fft_, fftO_;
979 std::vector<T> window_, windowO_;
980 std::vector<std::vector<T>> ring_, accum_, spec_, prevSpec_;
981 std::vector<T> specD_, frame_, mag_, prevMag_, rotRe_, rotIm_, gain_;
982 std::vector<double> crossRe_, crossIm_, dRe_, dIm_, theta_, tinc_, omPrev_;
983 std::vector<unsigned char> done_;
984 std::array<int, kBuckets> bucketHead_ {};
985 std::vector<int> bucketNext_;
988 int queueCursor_ = 0;
989 T prevMaxMag_ = T(0);
990 std::vector<T> cepsTime_, cepsSpec_, envLog_;
993 int64_t inCount_ = 0;
994 int64_t frameStart_ = 0;
995 int64_t prevAnalysisStart_ = 0;
996 bool firstFrame_ =
true;
997 double stActive_ = 0.0, ratio_ = 1.0;
998 double aNext_ = 0.0, aNom_ = 0.0, aCur_ = 0.0, cCur_ = 0.0;
999 double origin_ = 0.0, originStream_ = 0.0, originRatio_ = 1.0;
1000 bool steer_ =
false;
1001 double steerValue_ = 0.0;
1002 double leadLimit_ = 1e18;
1005 std::array<Lock, kMaxLocks> locks_ {};
1006 int lockHead_ = 0, lockCount_ = 0;
1007 double rejoinE_ = 0.0, rejoinC_ = 0.0, rejoinJ_ = 1.0;
1008 double lastLockS_ = -1e18, lastLockT_ = -1e18;
1011 int No_ = 1024, hopO_ = 128, numBands_ = 0;
1013 std::vector<int> fbStart_, fbCount_, fbOffset_;
1014 std::vector<T> fbW_, frameO_, specO_, powO_, bandCur_, bandPrev_, bandPrevMax_;
1015 std::array<double, kFluxWindow> fluxHist_ {};
1016 std::array<double, kFluxWindow> medScratch_ {};
1017 int fluxFill_ = 0, fluxPos_ = 0;
1018 int64_t nextFrameO_ = 0, candFrame_ = -1, lastOnsetFrame_ = -1000;
1019 static constexpr int kOnsetRing = 8;
1020 std::array<double, kOnsetRing> onsetRing_ {};
1022 double fluxPrev_ = 0.0, fluxPrev2_ = 0.0;
1023 bool candPrev_ =
false;
1026 double targetSemitones_ = 0.0;
1027 bool transientOn_ =
true, formantOn_ =
false;
1028 std::atomic<double> stgSemitones_ { 0.0 };
1029 std::atomic<bool> stgTransient_ {
true };
1030 std::atomic<bool> stgFormant_ {
false };
1031 std::atomic<unsigned> seq_ { 0 };
1032 std::atomic<bool> dirty_ {
false };