324 static_assert(std::atomic<T>::is_always_lock_free,
325 "audio-thread stores must not lock");
326 static_assert(std::atomic<std::uint32_t>::is_always_lock_free,
327 "audio-thread stores must not lock");
359 const int frame = fftSize > 0 ? sanitizeFrame(fftSize)
365 detector_.setNoiseSuppression(
false);
370 shifter_.prepare(spec, frame);
374 spectralLatency_ = shifter_.getLatency();
389 if (!prepared_)
return;
394 publishedCorrection_ = 0.0;
395 shifter_.setSemitones(T(0));
398 smoothingForMs_ = -1.0;
399 warmupRemaining_ = detector_.getWindowSize();
403 lowActive_ = lowLatency_.load(std::memory_order_relaxed);
404 lowFormant_ = lowActive_ && formantPreserve_.load(std::memory_order_relaxed);
405 latency_.store(lowActive_ ? spliceDelay_ : spectralLatency_,
406 std::memory_order_relaxed);
422 void setScale(std::uint16_t scaleBitmask,
int rootPitchClass)
noexcept
424 const auto mask =
static_cast<std::uint32_t
>(scaleBitmask & 0x0FFFu);
425 const auto root =
static_cast<std::uint32_t
>((rootPitchClass % 12 + 12) % 12);
431 scaleWord_.store(absolute | (root << 12) | (mask << 16),
432 std::memory_order_relaxed);
445 if (!std::isfinite(ms))
return;
446 retuneSpeedMs_.store(std::clamp(ms, T(0), T(kMaxRetuneMs)),
447 std::memory_order_relaxed);
456 formantPreserve_.store(on, std::memory_order_relaxed);
472 lowLatency_.store(on, std::memory_order_relaxed);
478 return lowLatency_.load(std::memory_order_relaxed);
484 return static_cast<std::uint16_t
>(
485 (scaleWord_.load(std::memory_order_relaxed) >> 16) & 0x0FFFu);
491 return static_cast<int>(
492 (scaleWord_.load(std::memory_order_relaxed) >> 12) & 0x0Fu);
498 return retuneSpeedMs_.load(std::memory_order_relaxed);
504 return formantPreserve_.load(std::memory_order_relaxed);
508 [[nodiscard]] std::vector<uint8_t>
getState()
const
526 setScale(
static_cast<std::uint16_t
>(r.
read(
"scaleMask", int32_t(0x0FFF)) & 0x0FFF),
527 r.
read(
"root", int32_t(0)));
541 return prepared_ ? latency_.load(std::memory_order_relaxed) : 0;
548 return prepared_ ? frameSize_ : 0;
564 if (!prepared_)
return;
565 const int numSamples = buffer.getNumSamples();
566 if (numSamples <= 0)
return;
572 if (lowLatency_.load(std::memory_order_relaxed) != lowActive_)
reset();
575 if (lowActive_ && formantPreserve_.load(std::memory_order_relaxed) != lowFormant_)
reset();
580 const std::uint32_t absoluteMask =
581 scaleWord_.load(std::memory_order_relaxed) & 0x0FFFu;
583 const double retuneMs =
static_cast<double>(
584 retuneSpeedMs_.load(std::memory_order_relaxed));
585 if (retuneMs != smoothingForMs_) rebuildSmoothing(retuneMs);
587 const bool formant = formantPreserve_.load(std::memory_order_relaxed);
588 if (formant != publishedFormant_)
592 shifter_.setFormantPreserve(formant);
593 publishedFormant_ = formant;
596 const T*
const detectionInput =
597 buffer.getNumChannels() > 0 ? buffer.getChannel(0) :
nullptr;
600 while (offset < numSamples)
611 if (controlPhase_ == 0)
615 if (lowActive_ && splicePhase_ == 0) updateLocalPitch();
616 advanceCorrection(absoluteMask);
620 if (lowActive_ && !lowFormant_ && splicePhase_ == 0) decideSplice();
624 std::min(numSamples - offset, kControlInterval - controlPhase_);
626 if (detectionInput !=
nullptr)
627 detector_.pushSamples(std::span<const T>(
628 detectionInput + offset,
static_cast<std::size_t
>(chunk)));
630 if (warmupRemaining_ > 0)
631 warmupRemaining_ = std::max(0, warmupRemaining_ - chunk);
635 if (lowFormant_) grainChunk(buffer, offset, chunk);
636 else spliceChunk(buffer, offset, chunk);
639 shifter_.processBlock(buffer.getSubView(offset, chunk));
641 controlPhase_ += chunk;
642 if (controlPhase_ >= kControlInterval) controlPhase_ = 0;
652 static constexpr double kAutoSpanRef = 2048.0;
653 static constexpr double kAutoSpanRate = 48000.0;
654 static constexpr int kAutoMinFrame = 512;
655 static constexpr int kAutoMaxFrame = 32768;
658 [[nodiscard]]
static int automaticFrame(
double sampleRate)
noexcept
660 const double target = sampleRate * (kAutoSpanRef / kAutoSpanRate);
661 int frame = kAutoMinFrame;
662 while (frame < kAutoMaxFrame &&
static_cast<double>(frame) < target)
671 [[nodiscard]]
static int sanitizeFrame(
int requested)
noexcept
673 constexpr int kMax = 1 << 20;
675 while (frame < requested && frame < kMax) frame <<= 1;
682 static constexpr int kControlInterval = 64;
687 static constexpr double kLandingSemitones = 0.001;
690 static constexpr double kMaxRetuneMs = 10000.0;
697 void rebuildSmoothing(
double retuneMs)
noexcept
699 smoothingForMs_ = retuneMs;
700 if (retuneMs <= 0.0 || sampleRate_ <= 0.0)
705 const double tauSamples = retuneMs * 0.001 * sampleRate_;
706 smoothing_ = 1.0 - std::exp(-
static_cast<double>(kControlInterval) / tauSamples);
713 void advanceCorrection(std::uint32_t absoluteMask)
noexcept
715 if (absoluteMask == 0u)
719 else if (warmupRemaining_ == 0)
727 const double frequency = lowActive_
728 ? localHz_ :
static_cast<double>(detector_.getFrequencyHz());
729 if (frequency > 0.0 && frequency <= 0.25 * sampleRate_)
731 const double midi = 69.0 + 12.0 * std::log2(frequency / 440.0);
732 if (std::isfinite(midi))
733 target_ = std::clamp(nearestInScale(midi, absoluteMask) - midi,
738 if (smoothing_ >= 1.0)
740 correction_ = target_;
744 correction_ += (target_ - correction_) * smoothing_;
745 if (std::abs(target_ - correction_) < kLandingSemitones)
746 correction_ = target_;
749 if (correction_ != publishedCorrection_)
753 spliceRatio_ = std::exp2(correction_ / 12.0);
757 spliceStep_ = spliceRatio_ > kStretchedFrom
762 shifter_.setSemitones(
static_cast<T
>(correction_));
764 publishedCorrection_ = correction_;
776 [[nodiscard]]
static double nearestInScale(
double midi,
777 std::uint32_t absoluteMask)
noexcept
779 const int base =
static_cast<int>(std::floor(midi));
781 double bestDistance = 1.0e9;
782 for (
int note = base - 12; note <= base + 13; ++note)
784 const int pitchClass = ((note % 12) + 12) % 12;
785 if ((absoluteMask & (1u << pitchClass)) == 0u)
continue;
786 const double distance = std::abs(
static_cast<double>(note) - midi);
787 if (distance < bestDistance)
789 bestDistance = distance;
793 return static_cast<double>(bestNote);
799 static constexpr double kStretchedFrom = 1.0905077326652577;
802 static constexpr double kSilence = 1.0e-6;
805 static const SincInterpolator<T>& sincTable()
807 static const SincInterpolator<T> table;
810 static const StretchedSincReader<T>& stretchedTable()
812 static const StretchedSincReader<T> table;
817 void prepareSplice(
const AudioSpec& spec)
819 sinc_ = &sincTable();
820 stretched_ = &stretchedTable();
828 const int window = detector_.getWindowSize();
829 spliceDelay_ = window / 2;
830 spliceFragment_ = std::max(kControlInterval, window / 16);
834 while (size < 2 * window) size <<= 1;
835 ringMask_ =
static_cast<std::int64_t
>(size - 1);
836 spliceChannels_ = std::max(1, spec.numChannels);
837 ring_.assign(
static_cast<std::size_t
>(spliceChannels_),
838 std::vector<T>(
static_cast<std::size_t
>(size), T(0)));
845 const auto f =
static_cast<std::size_t
>(spliceFragment_);
846 fadeAmp_.assign(f, T(0));
847 fadeOldPow_.assign(f, T(0));
848 fadeNewPow_.assign(f, T(0));
849 for (std::size_t k = 0; k < f; ++k)
851 const double x = (
static_cast<double>(k) + 0.5) /
static_cast<double>(f);
852 fadeAmp_[k] =
static_cast<T
>(0.5 - 0.5 * std::cos(pi<double> * x));
853 fadeOldPow_[k] =
static_cast<T
>(std::cos(0.5 * pi<double> * x));
854 fadeNewPow_[k] =
static_cast<T
>(std::sin(0.5 * pi<double> * x));
858 minReadDelay_ =
static_cast<double>(stretched_->reach(
863 const int longest = window / 2 + localMargin(
static_cast<double>(window / 2)) + 2;
864 localScratch_.assign(
static_cast<std::size_t
>(2 * longest + kLocalSpan + 8), T(0));
865 localEnergy_.assign(localScratch_.size() + 1, 0.0);
869 static constexpr int kLocalSpan = 256;
874 [[nodiscard]]
static int localMargin(
double period)
noexcept
876 return static_cast<int>(std::ceil(0.03 * period)) + 1;
891 [[nodiscard]]
double localPeriod(
double coarse)
noexcept
893 const int margin = localMargin(coarse);
894 const int lagLo = std::max(2,
static_cast<int>(std::floor(coarse)) - margin);
895 const int lagHi =
static_cast<int>(std::ceil(coarse)) + margin;
896 const int span = std::clamp(
static_cast<int>(coarse), 64, kLocalSpan);
899 std::int64_t centre = headInt_;
900 const std::int64_t newest = writeCount_ - 1;
901 const std::int64_t reachAhead = lagHi / 2 + span / 2 + 2;
902 if (centre + reachAhead > newest) centre = newest - reachAhead;
903 const std::int64_t first = centre - lagHi / 2 - span / 2 - 1;
904 const int count =
static_cast<int>(std::min<std::int64_t>(
905 { newest - first + 1,
static_cast<std::int64_t
>(lagHi + span + 4),
906 static_cast<std::int64_t
>(localScratch_.size()) }));
907 const T* ring = ring_.front().data();
908 for (
int i = 0; i < count; ++i)
909 localScratch_[
static_cast<std::size_t
>(i)] =
910 ring[
static_cast<std::size_t
>((first + i) & ringMask_)];
911 localEnergy_[0] = 0.0;
912 for (
int i = 0; i < count; ++i)
914 const double v =
static_cast<double>(localScratch_[
static_cast<std::size_t
>(i)]);
915 localEnergy_[
static_cast<std::size_t
>(i) + 1] = localEnergy_[
static_cast<std::size_t
>(i)] + v * v;
918 auto ncc = [&](
int lag)
noexcept {
919 const std::int64_t a = centre - (lag + 1) / 2 - span / 2 - first;
920 const std::int64_t b = a + lag;
921 if (a < 0 || b + span > count)
return -2.0;
923 localScratch_.data() + a, localScratch_.data() + b, span));
924 const double ea = localEnergy_[
static_cast<std::size_t
>(a + span)] - localEnergy_[
static_cast<std::size_t
>(a)];
925 const double eb = localEnergy_[
static_cast<std::size_t
>(b + span)] - localEnergy_[
static_cast<std::size_t
>(b)];
926 const double den = std::sqrt(ea * eb);
927 return den > 1e-20 ? ab / den : -2.0;
931 double bestValue = 0.5;
932 for (
int lag = lagLo; lag <= lagHi; ++lag)
934 const double v = ncc(lag);
935 if (v > bestValue) { bestValue = v; best = lag; }
937 if (best <= lagLo || best >= lagHi)
return coarse;
938 const double ym = ncc(best - 1), yp = ncc(best + 1);
939 const double den = ym - 2.0 * bestValue + yp;
940 const double shift = den < 0.0 ? 0.5 * (ym - yp) / den : 0.0;
941 return static_cast<double>(best) + std::clamp(shift, -0.5, 0.5);
945 void updateLocalPitch() noexcept
947 const double frequency =
static_cast<double>(detector_.getFrequencyHz());
948 if (!(frequency > 0.0 && frequency <= 0.25 * sampleRate_) || warmupRemaining_ > 0)
950 localHz_ = frequency;
953 localHz_ = sampleRate_ / localPeriod(sampleRate_ / frequency);
957 void resetSplice() noexcept
959 for (
auto& r : ring_) std::fill(r.begin(), r.end(), T(0));
961 headInt_ = -
static_cast<std::int64_t
>(spliceDelay_);
966 fadeEqualPower_ =
false;
972 lastLoud_ = std::numeric_limits<std::int64_t>::min() / 2;
973 markPrev_ = markNext_ = -
static_cast<double>(spliceDelay_);
974 offsetCur_ = offsetNext_ = 0.0;
984 void decideSplice() noexcept
989 headFrac_ = nextFrac_;
994 const auto now = writeCount_;
995 const double delay =
static_cast<double>(now - headInt_) - headFrac_;
996 const double centre =
static_cast<double>(spliceDelay_);
997 const auto centreInt = now -
static_cast<std::int64_t
>(spliceDelay_);
998 const auto reach =
static_cast<std::int64_t
>(minReadDelay_);
1003 if (lastLoud_ < std::min(headInt_, centreInt) - reach)
1005 headInt_ = centreInt;
1012 bool equalPower =
false;
1013 const double frequency = localHz_;
1014 const bool voiced = warmupRemaining_ == 0 && frequency > 0.0
1015 && frequency <= 0.25 * sampleRate_;
1022 const double period = sampleRate_ / frequency;
1023 const double span = period * std::ceil(
static_cast<double>(spliceFragment_) / period);
1024 if (delay < centre - 0.5 * span) jump = -span;
1025 else if (delay > centre + 0.5 * span) jump = span;
1027 else if (std::abs(delay - centre) >
static_cast<double>(spliceFragment_))
1031 jump =
delay - centre;
1037 const double drift =
static_cast<double>(spliceFragment_) * std::max(0.0, spliceRatio_ - 1.0);
1038 if (jump == 0.0 && delay - 2.0 * drift < minReadDelay_)
1040 jump =
delay - centre;
1046 const double target =
static_cast<double>(headInt_) + headFrac_ + jump;
1047 nextInt_ =
static_cast<std::int64_t
>(std::floor(target));
1048 nextFrac_ = target -
static_cast<double>(nextInt_);
1050 fadeEqualPower_ = equalPower;
1056 void writeRings(AudioBufferView<T> buffer,
int offset,
int chunk,
int nCh)
noexcept
1058 for (
int ch = 0; ch < spliceChannels_; ++ch)
1060 T* ring = ring_[
static_cast<std::size_t
>(ch)].data();
1061 const T* in = ch < nCh ? buffer.getChannel(ch) + offset :
nullptr;
1062 for (
int k = 0; k < chunk; ++k)
1064 T x = in !=
nullptr ? in[k] : T(0);
1065 if (!std::isfinite(x)) x = T(0);
1066 ring[
static_cast<std::size_t
>((writeCount_ + k) & ringMask_)] = x;
1067 if (std::abs(
static_cast<double>(x)) > kSilence) lastLoud_ = writeCount_ + k;
1084 void advanceGrain() noexcept
1086 markPrev_ = markNext_;
1087 offsetCur_ = offsetNext_;
1088 const double frequency = localHz_;
1089 const bool voiced = !holdUnity_ && warmupRemaining_ == 0 && frequency > 0.0
1090 && frequency <= 0.25 * sampleRate_;
1093 markNext_ = markPrev_ +
static_cast<double>(spliceFragment_);
1097 const double period = sampleRate_ / frequency;
1098 markNext_ = markPrev_ + period / spliceRatio_;
1099 const double source = markPrev_ + offsetCur_;
1100 const double periods = std::round((markNext_ - source) / period);
1101 offsetNext_ = source + periods * period - markNext_;
1119 void grainChunk(AudioBufferView<T> buffer,
int offset,
int chunk)
noexcept
1121 const int nCh = std::min(buffer.getNumChannels(), spliceChannels_);
1122 writeRings(buffer, offset, chunk, nCh);
1126 const auto now = writeCount_;
1127 holdUnity_ = lastLoud_ < now -
static_cast<std::int64_t
>(spliceDelay_ + spliceDelay_ / 2)
1128 -
static_cast<std::int64_t
>(minReadDelay_);
1129 if (holdUnity_) { offsetCur_ = 0.0; offsetNext_ = 0.0; }
1131 std::int64_t pos1[kControlInterval], pos2[kControlInterval];
1132 double frac1[kControlInterval], frac2[kControlInterval];
1133 T fade[kControlInterval];
1135 for (
int k = 0; k < chunk; ++k)
1137 const double t =
static_cast<double>(now + k - spliceDelay_);
1138 while (t >= markNext_) advanceGrain();
1139 const double span = markNext_ - markPrev_;
1140 const double u = span > 0.0 ? std::clamp((t - markPrev_) / span, 0.0, 1.0) : 1.0;
1141 fade[k] =
static_cast<T
>(0.5 - 0.5 *
fastCos(pi<double> * u));
1142 const double p1 = t + offsetCur_, p2 = t + offsetNext_;
1143 const double f1 = std::floor(p1), f2 = std::floor(p2);
1144 pos1[k] =
static_cast<std::int64_t
>(f1); frac1[k] = p1 - f1;
1145 pos2[k] =
static_cast<std::int64_t
>(f2); frac2[k] = p2 - f2;
1146 cross = cross || offsetCur_ != offsetNext_;
1148 headInt_ = now + chunk -
static_cast<std::int64_t
>(spliceDelay_)
1149 +
static_cast<std::int64_t
>(std::lround(offsetCur_));
1151 for (
int ch = 0; ch < nCh; ++ch)
1153 const T* ring = ring_[
static_cast<std::size_t
>(ch)].data();
1154 T* out = buffer.getChannel(ch) + offset;
1155 for (
int k = 0; k < chunk; ++k)
1157 const T a = sinc_->readRing(ring, ringMask_, pos1[k], frac1[k]);
1158 if (!cross || (pos1[k] == pos2[k] && frac1[k] == frac2[k]))
1163 const T b = sinc_->readRing(ring, ringMask_, pos2[k], frac2[k]);
1164 out[k] = a + (b - a) * fade[k];
1168 writeCount_ += chunk;
1169 splicePhase_ += chunk;
1170 if (splicePhase_ >= spliceFragment_) splicePhase_ = 0;
1174 T readRing(
const T* ring, std::int64_t pos,
double frac)
const noexcept
1176 return spliceStep_ < 0
1177 ? sinc_->readRing(ring, ringMask_, pos, frac)
1178 : stretched_->readRing(ring, ringMask_, pos, frac, spliceStep_);
1186 void spliceChunk(AudioBufferView<T> buffer,
int offset,
int chunk)
noexcept
1188 const int nCh = std::min(buffer.getNumChannels(), spliceChannels_);
1191 writeRings(buffer, offset, chunk, nCh);
1194 const double ratio = holdUnity_ ? 1.0 : spliceRatio_;
1195 std::int64_t pos1[kControlInterval], pos2[kControlInterval];
1196 double frac1[kControlInterval], frac2[kControlInterval];
1198 std::int64_t i1 = headInt_, i2 = nextInt_;
1199 double f1 = headFrac_, f2 = nextFrac_;
1200 for (
int k = 0; k < chunk; ++k)
1202 pos1[k] = i1; frac1[k] = f1;
1203 pos2[k] = i2; frac2[k] = f2;
1206 const double c1 = std::floor(f1);
1207 const double c2 = std::floor(f2);
1208 i1 +=
static_cast<std::int64_t
>(c1); f1 -= c1;
1209 i2 +=
static_cast<std::int64_t
>(c2); f2 -= c2;
1211 headInt_ = i1; headFrac_ = f1;
1212 if (fading_) { nextInt_ = i2; nextFrac_ = f2; }
1216 for (
int ch = 0; ch < nCh; ++ch)
1218 const T* ring = ring_[
static_cast<std::size_t
>(ch)].data();
1219 T* out = buffer.getChannel(ch) + offset;
1222 for (
int k = 0; k < chunk; ++k) out[k] = readRing(ring, pos1[k], frac1[k]);
1225 const auto at =
static_cast<std::size_t
>(splicePhase_);
1226 for (
int k = 0; k < chunk; ++k)
1228 const T a = readRing(ring, pos1[k], frac1[k]);
1229 const T b = readRing(ring, pos2[k], frac2[k]);
1230 const std::size_t j = at +
static_cast<std::size_t
>(k);
1231 out[k] = fadeEqualPower_ ? a * fadeOldPow_[j] + b * fadeNewPow_[j]
1232 : a + (b - a) * fadeAmp_[j];
1236 writeCount_ += chunk;
1237 splicePhase_ += chunk;
1238 if (splicePhase_ >= spliceFragment_) splicePhase_ = 0;
1243 PitchDetector<T> detector_;
1244 PitchShifter<T> shifter_;
1246 double sampleRate_ = 48000.0;
1248 int spectralLatency_ = 0;
1249 std::atomic<int> latency_ { 0 };
1250 bool prepared_ =
false;
1253 const SincInterpolator<T>* sinc_ =
nullptr;
1254 const StretchedSincReader<T>* stretched_ =
nullptr;
1255 std::vector<std::vector<T>> ring_;
1256 std::vector<T> fadeAmp_, fadeOldPow_, fadeNewPow_;
1257 std::int64_t ringMask_ = 0;
1258 int spliceChannels_ = 1;
1259 int spliceDelay_ = 0;
1260 int spliceFragment_ = 64;
1261 double minReadDelay_ = 34.0;
1262 std::int64_t writeCount_ = 0;
1263 std::int64_t headInt_ = 0;
1264 double headFrac_ = 0.0;
1265 std::int64_t nextInt_ = 0;
1266 double nextFrac_ = 0.0;
1267 std::int64_t lastLoud_ = 0;
1268 std::vector<T> localScratch_;
1269 std::vector<double> localEnergy_;
1270 double localHz_ = 0.0;
1271 double spliceRatio_ = 1.0;
1272 int spliceStep_ = -1;
1273 int splicePhase_ = 0;
1274 bool fading_ =
false;
1275 bool fadeEqualPower_ =
false;
1276 bool holdUnity_ =
false;
1277 bool lowActive_ =
false;
1278 bool lowFormant_ =
false;
1279 double markPrev_ = 0.0;
1280 double markNext_ = 0.0;
1281 double offsetCur_ = 0.0;
1282 double offsetNext_ = 0.0;
1283 std::atomic<bool> lowLatency_ {
false };
1286 double target_ = 0.0;
1287 double correction_ = 0.0;
1288 double publishedCorrection_ = 0.0;
1289 double smoothing_ = 1.0;
1290 double smoothingForMs_ = -1.0;
1291 bool publishedFormant_ =
false;
1292 int controlPhase_ = 0;
1293 int warmupRemaining_ = 0;
1297 std::atomic<std::uint32_t> scaleWord_ { 0x0FFF0FFFu };
1298 std::atomic<T> retuneSpeedMs_ { T(0) };
1299 std::atomic<bool> formantPreserve_ {
false };