DSPark 1.9.0
Header-only C++20 DSP for real-time and offline audio
Loading...
Searching...
No Matches
StudioVocoder.h
1// DSPark - Professional Audio DSP Framework
2// Copyright (c) 2026 Cristian Moresi - MIT License
3
4#pragma once
5
84#include "../../Core/DspMath.h"
85#include "../../Core/FFT.h"
86
87#include <algorithm>
88#include <array>
89#include <atomic>
90#include <bit>
91#include <cmath>
92#include <cstdint>
93#include <memory>
94#include <numbers>
95#include <vector>
96
97namespace dspark {
98namespace detail {
99
106template <FloatType T>
108{
109public:
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>");
116
118 struct Params
119 {
120 double targetSemitones = 0.0;
121 bool transientPreserve = true;
122 bool formantPreserve = false;
123 };
124
125 // -- Lifecycle (setup thread) ---------------------------------------------
126
138 bool prepare(double sampleRate, int numChannels, int fftSize, bool resampleCompensation)
139 {
140 if (!(sampleRate > 0.0) || !std::isfinite(sampleRate) || numChannels < 1
141 || (fftSize & (fftSize - 1)) != 0 || fftSize < 256 || fftSize > (1 << 20))
142 return false;
143
144 prepared_ = false;
145 sampleRate_ = sampleRate;
146 numChannels_ = numChannels;
147 N_ = fftSize;
148 bins_ = N_ / 2 + 1;
149 Rs_ = N_ / 4;
150 resample_ = resampleCompensation;
151
152 // Onset detector: a ~21 ms frame and an eighth-frame hop at every rate.
153 No_ = 256;
154 while (No_ < 8192 && static_cast<double>(No_) * 1.5 < 0.0213 * sampleRate_) No_ <<= 1;
155 hopO_ = No_ / 8;
156 // The detector confirms an onset one hop after its frame and locates
157 // it at most No + 3 hops behind the newest input; the analysis stays
158 // this far behind so that no frame has seen a strike before it is
159 // planned for.
160 D_ = No_ + No_ / 2;
161 delta_ = std::min(16, std::max(1, N_ / 64));
162
163 int ring = 1;
164 while (ring < 2 * N_ + 2 * D_ + No_) ring <<= 1;
165 ringSize_ = ring;
166 ringMask_ = ring - 1;
167 accumSize_ = 4 * N_;
168 accumMask_ = accumSize_ - 1;
169
170 fft_ = std::make_unique<FFTReal<T>>(static_cast<size_t>(N_));
171 fftO_ = std::make_unique<FFTReal<T>>(static_cast<size_t>(No_));
172
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_));
181
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)));
188 specD_.resize(spec);
189 frame_.resize(static_cast<size_t>(N_));
190 mag_.resize(nb);
191 prevMag_.resize(nb);
192 crossRe_.resize(nb); crossIm_.resize(nb);
193 dRe_.resize(nb); dIm_.resize(nb);
194 theta_.resize(nb);
195 tinc_.resize(nb);
196 omPrev_.resize(nb);
197 done_.resize(nb);
198 rotRe_.resize(nb); rotIm_.resize(nb);
199 gain_.resize(nb);
200 bucketNext_.resize(2 * nb + 2);
201 cepsTime_.resize(static_cast<size_t>(N_));
202 cepsSpec_.resize(spec);
203 envLog_.resize(nb);
204
205 // Onset filterbank: quarter-tone triangles, 27.5 Hz to 16 kHz.
206 buildOnsetBank();
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));
213
214 prepared_ = true;
215 return true;
216 }
217
220 void reset() noexcept
221 {
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));
227 prevMaxMag_ = 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_;
231
232 adoptParamsIfDirty();
233 stActive_ = std::clamp(targetSemitones_, -12.0, 12.0);
234 ratio_ = std::exp2(stActive_ / 12.0);
235
236 inCount_ = 0;
237 frameStart_ = static_cast<int64_t>(accumSize_);
238 firstFrame_ = true;
239 // Frame 0 covers input [Rs - N, Rs): it becomes ready after Rs samples
240 // plus the lookahead, like the first hop of a classic vocoder.
241 aNext_ = static_cast<double>(Rs_) - 0.5 * N_;
242 aNom_ = aNext_;
243 aCur_ = aNext_;
244 cCur_ = static_cast<double>(frameStart_) + 0.5 * N_ - Rs_;
245 origin_ = aNext_;
246 originStream_ = static_cast<double>(frameStart_) + 0.5 * N_;
247 originRatio_ = ratio_;
248 prevAnalysisStart_ = 0;
249 steer_ = false;
250
251 lockHead_ = lockCount_ = 0;
252 rejoinE_ = 0.0; rejoinC_ = 0.0; rejoinJ_ = 1.0;
253 lastLockS_ = -1e18; lastLockT_ = -1e18;
254
255 // Detector.
256 nextFrameO_ = 0;
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);
263 onsetPos_ = 0;
264 }
265
266 // -- Parameters (control thread) ------------------------------------------
267
269 void publishParams(const Params& p) noexcept
270 {
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);
278 }
279
280 // -- Streaming (stream owner) -----------------------------------------------
281
284 [[nodiscard]] int samplesToNextHop() const noexcept
285 {
286 const int64_t need = analysisStart() + N_ + D_ - inCount_;
287 return static_cast<int>(std::max<int64_t>(0, need));
288 }
289
292 void pushInput(int ch, const T* src, int count) noexcept
293 {
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);
298 }
299
306 void commitInput(int count, int numActiveChannels) noexcept
307 {
308 inCount_ += count;
309 runDetector(numActiveChannels);
310 if (inCount_ >= analysisStart() + N_ + D_)
311 processFrame(numActiveChannels);
312 }
313
316 void steerTimeline(double nominalCentre) noexcept
317 {
318 steerValue_ = nominalCentre;
319 steer_ = true;
320 }
321
332 void setAnchorLeadLimit(double samples) noexcept { leadLimit_ = std::max(0.0, samples); }
333
335 [[nodiscard]] double activeRatio() const noexcept { return ratio_; }
336
338 [[nodiscard]] double nextNominalCentre() const noexcept { return aNom_; }
339
341 [[nodiscard]] double nextStreamCentre() const noexcept
342 {
343 return static_cast<double>(frameStart_) + 0.5 * N_;
344 }
345
347 [[nodiscard]] double streamPositionOf(double x) const noexcept
348 {
349 return originStream_ + originRatio_ * (x - origin_);
350 }
351
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_; }
363
364private:
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;
382
383 struct Lock { double s, target, h; };
384
385 [[nodiscard]] static double princArg(double x) noexcept
386 {
387 return x - kTwoPi * std::round(x / kTwoPi);
388 }
389
390 [[nodiscard]] int64_t analysisStart() const noexcept
391 {
392 return static_cast<int64_t>(std::llround(aNext_)) - N_ / 2;
393 }
394
399 void adoptParamsIfDirty() noexcept
400 {
401 if (!dirty_.exchange(false, std::memory_order_acquire)) return;
402 for (int attempt = 0; attempt < kSeqlockMaxAttempts; ++attempt)
403 {
404 const unsigned s0 = seq_.load(std::memory_order_acquire);
405 if ((s0 & 1u) != 0u) continue; // writer mid-publish: do not copy
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);
409 // Orders the copy above before the re-read below and pairs with
410 // the writer's release fence ([atomics.fences]/2).
411 std::atomic_thread_fence(std::memory_order_acquire);
412 if (s0 == seq_.load(std::memory_order_relaxed))
413 {
414 targetSemitones_ = st; transientOn_ = tr; formantOn_ = fo;
415 return;
416 }
417 }
418 dirty_.store(true, std::memory_order_release);
419 }
420
421 // -- Frame ------------------------------------------------------------------
422
423 void analyse(int ch, int64_t start, T* out) noexcept
424 {
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);
430 }
431
432 void processFrame(int nCh) noexcept
433 {
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_);
440
441 // --- analysis: magnitudes, time and delta cross-spectra ----------------
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)
448 {
449 T* X = spec_[static_cast<size_t>(ch)].data();
450 const T* P = prevSpec_[static_cast<size_t>(ch)].data();
451 analyse(ch, A, X);
452 analyse(ch, A + delta_, specD_.data());
453 for (int k = 0; k < bins_; ++k)
454 {
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;
464 }
465 }
466 T maxMag = T(0);
467 for (int k = 0; k < bins_; ++k)
468 {
469 auto& m = mag_[static_cast<size_t>(k)];
470 m = std::sqrt(m);
471 maxMag = std::max(maxMag, m);
472 }
473
474 // --- time-direction candidates -------------------------------------------
475 const double dl = static_cast<double>(delta_);
476 for (int k = 0; k < bins_; ++k)
477 {
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;
481 double inc = 0.0;
482 if (!firstFrame_)
483 {
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);
489 }
490 // A spectrum that overflowed must not enter the phase recursion,
491 // which would hold the NaN for the rest of the stream.
492 tinc_[static_cast<size_t>(k)] = std::isfinite(inc) ? inc : 0.0;
493 omPrev_[static_cast<size_t>(k)] = omNow;
494 }
495
496 // --- heap-ordered propagation ----------------------------------------------
497 if (firstFrame_)
498 std::fill(theta_.begin(), theta_.end(), 0.0);
499 else
500 propagate(maxMag);
501
502 // Inside a strike's lock the map has slope 1, so the frame is placed
503 // exactly where a plain delayed copy of the input would put it. The
504 // bins the strike is rising into take no rotation at all: the heap
505 // hands them one rotation, rigid but not zero, and a constant phase
506 // turn of an impulse is cos(phi) times the impulse plus sin(phi)
507 // times its Hilbert transform, whose 1/t tail reaches before the
508 // strike - measured as pre-echo 30 dB down and up to 15 ms long at
509 // ratio 1.25. Zero rotation copies the strike itself; the bins that
510 // are not rising keep their propagated phases, so a partial that
511 // sustains through the strike stays continuous. Two cases are left
512 // to the heap. A lock narrower than the window leaves frames outside
513 // it that still see the strike, and a zero-rotated copy makes their
514 // misplaced copies coherent too (at 960 strikes per minute, 4096
515 // frame and ratio 0.8 the median strike moved from 0.08 to 7.9 ms).
516 // And a strike with another one within a frame of it would share
517 // frames with it, and the copy would carry that one at this lock's
518 // offset rather than at its own place.
519 if (transientOn_ && !firstFrame_ && lockCount_ > 0)
520 {
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_))
526 alone = false;
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;
531 }
532 theta_[0] = 0.0;
533 theta_[static_cast<size_t>(bins_ - 1)] = 0.0;
534 for (int k = 0; k < bins_; ++k)
535 {
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)]));
538 }
539
540 // --- magnitude post-stages for resampling owners --------------------------
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));
545 if (taper)
546 {
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);
552 }
553
554 // --- synthesis ---------------------------------------------------------------
555 const T norm = static_cast<T>(Rs / (0.5 * N_));
556 for (int ch = 0; ch < nCh; ++ch)
557 {
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)
561 {
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;
567 }
568 X[1] = T(0);
569 X[N_ + 1] = T(0);
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;
577 }
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;
583
584 prevAnalysisStart_ = A;
585 firstFrame_ = false;
586 aCur_ = aNext_;
587 cCur_ = static_cast<double>(frameStart_) + 0.5 * N_;
588 frameStart_ += Rs_;
589 planNext();
590 }
591
598 void propagate(T maxMag) noexcept
599 {
600 const T tol = maxMag * static_cast<T>(std::pow(10.0, -kHeapFloorDb / 20.0));
601 int todo = 0;
602 for (int k = 0; k < bins_; ++k)
603 {
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)];
607 if (!quiet) ++todo;
608 }
609 queueSize_ = 0;
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);
616
617 while (todo > 0)
618 {
619 if (queueSize_ == 0)
620 {
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; }
625 // Only NaN magnitudes are left: they cannot be ordered, and
626 // their bins keep the time direction's candidate.
627 if (best < 0) break;
628 done_[static_cast<size_t>(best)] = 1; --todo;
629 queuePush(mag_[static_cast<size_t>(best)], 2 * best + 1);
630 continue;
631 }
632 const int code = queuePop();
633 const int k = code >> 1;
634 if ((code & 1) == 0)
635 {
636 if (!done_[static_cast<size_t>(k)])
637 {
638 done_[static_cast<size_t>(k)] = 1; --todo; // theta = tinc already
639 queuePush(mag_[static_cast<size_t>(k)], 2 * k + 1);
640 }
641 }
642 else
643 {
644 const double th = theta_[static_cast<size_t>(k)];
645 if (k + 1 < bins_ && !done_[static_cast<size_t>(k + 1)])
646 {
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);
650 }
651 if (k > 0 && !done_[static_cast<size_t>(k - 1)])
652 {
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);
656 }
657 }
658 }
659 }
660
663 [[nodiscard]] static int bucketBits(T magnitude) noexcept
664 {
665 return static_cast<int>(std::bit_cast<std::uint32_t>(static_cast<float>(magnitude)) >> 20);
666 }
667
671 void queuePush(T key, int code) noexcept
672 {
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);
677 ++queueSize_;
678 }
679
681 int queuePop() noexcept
682 {
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)];
686 --queueSize_;
687 return code;
688 }
689
692 void computeFormantGains() noexcept
693 {
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)
701 {
702 cepsSpec_[static_cast<size_t>(2 * k)] = T(0);
703 cepsSpec_[static_cast<size_t>(2 * k + 1)] = T(0);
704 }
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)
709 {
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)));
718 }
719 }
720
721 // -- Time map -------------------------------------------------------------
722
724 void planNext() noexcept
725 {
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_;
731
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;
735
736 // Retire locks the stream has passed; the map then rejoins the
737 // nominal line from where the lock left it.
738 while (lockCount_ > 0)
739 {
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;
746 --lockCount_;
747 }
748
749 double a;
750 if (lockCount_ > 0)
751 {
752 const Lock& L = locks_[static_cast<size_t>(lockHead_)];
753 if (c >= L.target - L.h)
754 a = L.s + (c - L.target);
755 else
756 {
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);
760 }
761 }
762 else
763 {
764 const double f = std::clamp(1.0 - (c - rejoinC_) / rejoinJ_, 0.0, 1.0);
765 a = aNom_ + rejoinE_ * f;
766 }
767 aNext_ = std::max(a, aCur_);
768 }
769
771 void addOnset(double s) noexcept
772 {
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;
779 double h = 0.5 * N_;
780 h = std::min(h, s - aCur_ - 1.0); // the map never runs backwards
781 h = std::min(h, target - cNext); // the lock starts at or after the next frame
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;
785 if (lockCount_ > 0)
786 {
787 const Lock& P = locks_[static_cast<size_t>((lockHead_ + lockCount_ - 1) % kMaxLocks)];
788 prevS = P.s; prevT = P.target; prevH = P.h;
789 }
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 };
794 ++lockCount_;
795 lastLockS_ = s; lastLockT_ = target;
796 // Re-plan the next frame now that it may be on the approach.
797 const double keepNom = aNom_;
798 replanNextFrame(keepNom);
799 }
800
801 void replanNextFrame(double nom) noexcept
802 {
803 const double c = static_cast<double>(frameStart_) + 0.5 * N_;
804 const Lock& L = locks_[static_cast<size_t>(lockHead_)];
805 double a;
806 if (c >= L.target - L.h)
807 a = L.s + (c - L.target);
808 else
809 {
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);
813 }
814 (void) nom;
815 // Never ask for input the ring no longer holds or the frame already
816 // passed; never run backwards.
817 aNext_ = std::max(a, aCur_);
818 }
819
820 // -- Onset detector -----------------------------------------------------------
821
822 void buildOnsetBank()
823 {
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)
830 {
831 const double f = 27.5 * std::pow(2.0, i / 24.0);
832 if (f > fMax) break;
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);
835 }
836 for (size_t j = 1; j + 1 < centres.size(); ++j)
837 {
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);
845 }
846 numBands_ = static_cast<int>(fbStart_.size());
847 odfScale_ = static_cast<T>(2048.0 / No_);
848 }
849
851 void runDetector(int nCh) noexcept
852 {
853 nCh = std::clamp(nCh, 1, numChannels_);
854 while (nextFrameO_ * hopO_ + No_ <= inCount_)
855 {
856 const int64_t start = nextFrameO_ * hopO_;
857 std::fill(powO_.begin(), powO_.end(), T(0));
858 for (int ch = 0; ch < nCh; ++ch)
859 {
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)
866 {
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;
869 }
870 }
871 const T inv = T(1) / static_cast<T>(nCh);
872 double flux = 0.0;
873 for (int b = 0; b < numBands_; ++b)
874 {
875 T acc = T(0);
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;
883 }
884 flux /= std::max(1, numBands_);
885 for (int b = 0; b < numBands_; ++b)
886 {
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;
891 }
892 if (nextFrameO_ == 0) flux = 0.0; // no previous frame to rise from
893
894 // The previous frame is an onset if it rose past the median of the
895 // frames before it and is a local maximum of the flux.
896 if (candPrev_ && fluxPrev_ >= flux && candFrame_ - lastOnsetFrame_ > 4)
897 {
898 lastOnsetFrame_ = candFrame_;
899 const double s = locateOnset(candFrame_, nCh);
900 if (s >= 0.0) addOnset(s);
901 }
902
903 double med = 0.0;
904 if (fluxFill_ > 3)
905 {
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)];
910 if ((n & 1) == 0)
911 {
912 const double lo = *std::max_element(medScratch_.begin(), medScratch_.begin() + n / 2);
913 med = 0.5 * (med + lo);
914 }
915 }
916 candPrev_ = (flux - med > kFluxDelta) && flux >= fluxPrev_;
917 candFrame_ = nextFrameO_;
918 fluxHist_[static_cast<size_t>(fluxPos_)] = flux;
919 fluxPos_ = (fluxPos_ + 1) % kFluxWindow;
920 ++fluxFill_;
921 fluxPrev_ = flux;
922 ++nextFrameO_;
923 }
924 }
925
928 [[nodiscard]] double locateOnset(int64_t i, int nCh) const noexcept
929 {
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) {
934 double e = 0.0;
935 for (int ch = 0; ch < nCh; ++ch)
936 {
937 const double v = ring_[static_cast<size_t>(ch)][static_cast<size_t>(n & ringMask_)];
938 e += v * v;
939 }
940 return e;
941 };
942 // Running 32-sample window centred on n: [n - 16, n + 16).
943 double run = 0.0;
944 for (int64_t n = lo - 16; n < lo + 16; ++n) run += pw(n);
945 double peak = -1.0; int64_t pk = lo;
946 // First pass: peak.
947 {
948 double rr = run;
949 for (int64_t n = lo; n < hi; ++n)
950 {
951 if (rr > peak) { peak = rr; pk = n; }
952 rr += pw(n + 16) - pw(n - 16);
953 }
954 }
955 if (peak <= 0.0) return -1.0;
956 // Walk back from the peak to the first sample at or below a quarter
957 // of it in amplitude (1/16 in power).
958 double rr = 0.0;
959 for (int64_t n = pk - 16; n < pk + 16; ++n) rr += pw(n);
960 int64_t j = pk;
961 while (j > lo && rr > peak / 16.0)
962 {
963 rr += pw(j - 17) - pw(j + 15);
964 --j;
965 }
966 return static_cast<double>(j);
967 }
968
969 // -- Members ------------------------------------------------------------------
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;
977
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_;
986 int queueSize_ = 0;
987 int queueTop_ = 0;
988 int queueCursor_ = 0;
989 T prevMaxMag_ = T(0);
990 std::vector<T> cepsTime_, cepsSpec_, envLog_;
991
992 // Stream state.
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;
1003
1004 // Time-map locks.
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;
1009
1010 // Onset detector.
1011 int No_ = 1024, hopO_ = 128, numBands_ = 0;
1012 T odfScale_ = T(2);
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_ {};
1021 int onsetPos_ = 0;
1022 double fluxPrev_ = 0.0, fluxPrev2_ = 0.0;
1023 bool candPrev_ = false;
1024
1025 // Parameters.
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 };
1033};
1034
1035} // namespace detail
1036} // namespace dspark
Streaming phase-gradient vocoder with a strike-anchored time map.
int olaSize() const noexcept
double streamPositionOf(double x) const noexcept
void steerTimeline(double nominalCentre) noexcept
Owner-supplied nominal analysis centre for the NEXT frame (a resampling owner keeps its reader and th...
double activeRatio() const noexcept
const T * olaData(int ch) const noexcept
int lookahead() const noexcept
void pushInput(int ch, const T *src, int count) noexcept
Writes count (<= samplesToNextHop(), or any count when it is 0... see commitInput) samples of channel...
void reset() noexcept
Clears all signal state and adopts the latest parameters (jump, no glide). Stream owner only.
bool prepare(double sampleRate, int numChannels, int fftSize, bool resampleCompensation)
Allocates every buffer the stream will use.
double nextNominalCentre() const noexcept
int synthHop() const noexcept
void commitInput(int count, int numActiveChannels) noexcept
Advances the input head by count and runs at most one frame.
void publishParams(const Params &p) noexcept
Publishes a whole parameter set (one control thread only).
int fftSize() const noexcept
int64_t writeHead() const noexcept
void setAnchorLeadLimit(double samples) noexcept
Caps how far a strike anchor may move the analysis ahead of the nominal timeline, in input samples (o...
int64_t inputCount() const noexcept
int64_t olaMask() const noexcept
double nextStreamCentre() const noexcept
int samplesToNextHop() const noexcept
Main namespace for the DSPark framework.
constexpr T pi
Pi (3.14159...) for the given floating-point type.
Definition DspMath.h:48
The control-published parameter set (adopted as ONE unit).
bool transientPreserve
Anchor the time map on detected strikes.
bool formantPreserve
Cepstral pre-warp (resample owners).
double targetSemitones
Stretch ratio as semitones, clamped +-12.