DSPark 1.9.0
Header-only C++20 DSP for real-time and offline audio
Loading...
Searching...
No Matches
PitchCorrector.h
1// DSPark - Professional Audio DSP Framework
2// Copyright (c) 2026 Cristian Moresi - MIT License
3
4#pragma once
5
290#include "../Analysis/PitchDetector.h"
291#include "../Core/AudioBuffer.h"
292#include "../Core/AudioSpec.h"
293#include "../Core/DenormalGuard.h"
294#include "../Core/DspMath.h"
295#include "../Core/Interpolation.h"
296#include "../Core/StateBlob.h"
297#include "../Music/HarmonyConstants.h"
298#include "PitchShifter.h"
299
300#include <algorithm>
301#include <atomic>
302#include <cmath>
303#include <cstddef>
304#include <cstdint>
305#include <limits>
306#include <span>
307#include <vector>
308
309namespace dspark {
310
318template <FloatType T>
319class PitchCorrector final
320{
321public:
322 // The published words are read on the audio thread every control interval,
323 // and a word that is not lock-free would take a mutex inside the callback.
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");
328
329 // -- Lifecycle -------------------------------------------------------------
330
353 void prepare(const AudioSpec& spec, int fftSize = 0)
354 {
355 if (!std::isfinite(spec.sampleRate) || !spec.isValid()) return;
356
357 prepared_ = false;
358
359 const int frame = fftSize > 0 ? sanitizeFrame(fftSize)
360 : automaticFrame(spec.sampleRate);
361
362 detector_.prepare(spec.sampleRate);
363 // The tracking below was tuned on the detector's first reading alone;
364 // the second one it can take through noise stays off here.
365 detector_.setNoiseSuppression(false);
366 // The corrector keeps the Standard engine: its retune dynamics and the
367 // 2 * frame latency are tuned to it, and it moves the shift on every
368 // control tick, where Studio's strike anchoring buys nothing.
369 shifter_.setQuality(PitchShifter<T>::Quality::Standard);
370 shifter_.prepare(spec, frame);
371
372 sampleRate_ = spec.sampleRate;
373 frameSize_ = frame;
374 spectralLatency_ = shifter_.getLatency();
375 prepareSplice(spec);
376
377 prepared_ = true;
378 reset();
379 }
380
387 void reset() noexcept
388 {
389 if (!prepared_) return;
390
391 detector_.reset();
392 target_ = 0.0;
393 correction_ = 0.0;
394 publishedCorrection_ = 0.0;
395 shifter_.setSemitones(T(0));
396 shifter_.reset();
397 controlPhase_ = 0;
398 smoothingForMs_ = -1.0; // rebuild the glide coefficient on next block
399 warmupRemaining_ = detector_.getWindowSize();
400
401 // The engine is chosen here, so a mode change takes effect as a
402 // restart of the stream (the two latencies differ).
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);
407 resetSplice();
408 }
409
410 // -- Parameters (any thread) -------------------------------------------------
411
422 void setScale(std::uint16_t scaleBitmask, int rootPitchClass) noexcept
423 {
424 const auto mask = static_cast<std::uint32_t>(scaleBitmask & 0x0FFFu);
425 const auto root = static_cast<std::uint32_t>((rootPitchClass % 12 + 12) % 12);
426 const auto absolute = static_cast<std::uint32_t>(harmony::scaleAtRoot(
427 static_cast<harmony::NoteSet>(mask), static_cast<int>(root)));
428 // One packed word: the audio thread must never pair a fresh mask with a
429 // stale root, so the mask, the root and the pre-rotated absolute
430 // pitch-class set travel together.
431 scaleWord_.store(absolute | (root << 12) | (mask << 16),
432 std::memory_order_relaxed);
433 }
434
443 void setRetuneSpeedMs(T ms) noexcept
444 {
445 if (!std::isfinite(ms)) return;
446 retuneSpeedMs_.store(std::clamp(ms, T(0), T(kMaxRetuneMs)),
447 std::memory_order_relaxed);
448 }
449
454 void setFormantPreserve(bool on) noexcept
455 {
456 formantPreserve_.store(on, std::memory_order_relaxed);
457 }
458
470 void setLowLatency(bool on) noexcept
471 {
472 lowLatency_.store(on, std::memory_order_relaxed);
473 }
474
476 [[nodiscard]] bool getLowLatency() const noexcept
477 {
478 return lowLatency_.load(std::memory_order_relaxed);
479 }
480
482 [[nodiscard]] std::uint16_t getScaleMask() const noexcept
483 {
484 return static_cast<std::uint16_t>(
485 (scaleWord_.load(std::memory_order_relaxed) >> 16) & 0x0FFFu);
486 }
487
489 [[nodiscard]] int getRootPitchClass() const noexcept
490 {
491 return static_cast<int>(
492 (scaleWord_.load(std::memory_order_relaxed) >> 12) & 0x0Fu);
493 }
494
496 [[nodiscard]] T getRetuneSpeedMs() const noexcept
497 {
498 return retuneSpeedMs_.load(std::memory_order_relaxed);
499 }
500
502 [[nodiscard]] bool getFormantPreserve() const noexcept
503 {
504 return formantPreserve_.load(std::memory_order_relaxed);
505 }
506
508 [[nodiscard]] std::vector<uint8_t> getState() const
509 {
510 StateWriter w(stateId("PCOR"), 1);
511 w.write("scaleMask", static_cast<int32_t>(getScaleMask()));
512 w.write("root", static_cast<int32_t>(getRootPitchClass()));
513 w.write("retuneMs", static_cast<float>(getRetuneSpeedMs()));
514 w.write("formant", getFormantPreserve());
515 w.write("lowLatency", getLowLatency());
516 return w.blob();
517 }
518
522 bool setState(const uint8_t* data, size_t size)
523 {
524 StateReader r(data, size);
525 if (!r.isValid() || r.processorId() != stateId("PCOR")) return false;
526 setScale(static_cast<std::uint16_t>(r.read("scaleMask", int32_t(0x0FFF)) & 0x0FFF),
527 r.read("root", int32_t(0)));
528 setRetuneSpeedMs(static_cast<T>(r.read("retuneMs", 0.0f)));
529 setFormantPreserve(r.read("formant", false));
530 setLowLatency(r.read("lowLatency", false));
531 return true;
532 }
533
539 [[nodiscard]] int getLatency() const noexcept
540 {
541 return prepared_ ? latency_.load(std::memory_order_relaxed) : 0;
542 }
543
546 [[nodiscard]] int getFrameSize() const noexcept
547 {
548 return prepared_ ? frameSize_ : 0;
549 }
550
551 // -- Processing --------------------------------------------------------------
552
562 void processBlock(AudioBufferView<T> buffer) noexcept
563 {
564 if (!prepared_) return;
565 const int numSamples = buffer.getNumSamples();
566 if (numSamples <= 0) return;
567
568 DenormalGuard guard;
569
570 // A change of engine restarts the stream: the latencies differ, so no
571 // crossfade can join the two.
572 if (lowLatency_.load(std::memory_order_relaxed) != lowActive_) reset();
573 // So does a change of the low-latency engine's formant mode: its grain
574 // engine and the read head keep different state.
575 if (lowActive_ && formantPreserve_.load(std::memory_order_relaxed) != lowFormant_) reset();
576
577 // One load per block for each independent word. The scale word is
578 // internally consistent by packing; the retune speed and the formant
579 // flag stand alone.
580 const std::uint32_t absoluteMask =
581 scaleWord_.load(std::memory_order_relaxed) & 0x0FFFu;
582
583 const double retuneMs = static_cast<double>(
584 retuneSpeedMs_.load(std::memory_order_relaxed));
585 if (retuneMs != smoothingForMs_) rebuildSmoothing(retuneMs);
586
587 const bool formant = formantPreserve_.load(std::memory_order_relaxed);
588 if (formant != publishedFormant_)
589 {
590 // Forwarded by the stream owner, which is the shifter's only
591 // control writer here (see the file documentation).
592 shifter_.setFormantPreserve(formant);
593 publishedFormant_ = formant;
594 }
595
596 const T* const detectionInput =
597 buffer.getNumChannels() > 0 ? buffer.getChannel(0) : nullptr;
598
599 int offset = 0;
600 while (offset < numSamples)
601 {
602 // The grid is absolute (controlPhase_ persists across blocks): the
603 // correction advances once, at the START of each whole interval,
604 // and every sample of that interval is then rendered with it in
605 // force. The shifter's engine adopts a new value at its own
606 // analysis hops, which do not land on this grid once the ratio
607 // leaves unity, so publishing at the start of the interval that
608 // contains a hop - rather than at whichever chunk boundary the
609 // host block size happens to create - is what makes the rendered
610 // output identical however the stream is chopped into blocks.
611 if (controlPhase_ == 0)
612 {
613 // The low-latency engine refines the pitch at its read head
614 // once per fragment, before the correction is taken from it.
615 if (lowActive_ && splicePhase_ == 0) updateLocalPitch();
616 advanceCorrection(absoluteMask);
617 // Splice decisions sit on the same absolute grid and read the
618 // detector BEFORE this interval is pushed, so the host's block
619 // size cannot move them.
620 if (lowActive_ && !lowFormant_ && splicePhase_ == 0) decideSplice();
621 }
622
623 const int chunk =
624 std::min(numSamples - offset, kControlInterval - controlPhase_);
625
626 if (detectionInput != nullptr)
627 detector_.pushSamples(std::span<const T>(
628 detectionInput + offset, static_cast<std::size_t>(chunk)));
629
630 if (warmupRemaining_ > 0)
631 warmupRemaining_ = std::max(0, warmupRemaining_ - chunk);
632
633 if (lowActive_)
634 {
635 if (lowFormant_) grainChunk(buffer, offset, chunk);
636 else spliceChunk(buffer, offset, chunk);
637 }
638 else
639 shifter_.processBlock(buffer.getSubView(offset, chunk));
640
641 controlPhase_ += chunk;
642 if (controlPhase_ >= kControlInterval) controlPhase_ = 0;
643 offset += chunk;
644 }
645 }
646
647private:
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;
656
658 [[nodiscard]] static int automaticFrame(double sampleRate) noexcept
659 {
660 const double target = sampleRate * (kAutoSpanRef / kAutoSpanRate);
661 int frame = kAutoMinFrame;
662 while (frame < kAutoMaxFrame && static_cast<double>(frame) < target)
663 frame <<= 1;
664 return frame;
665 }
666
671 [[nodiscard]] static int sanitizeFrame(int requested) noexcept
672 {
673 constexpr int kMax = 1 << 20;
674 int frame = 256;
675 while (frame < requested && frame < kMax) frame <<= 1;
676 return frame;
677 }
678
682 static constexpr int kControlInterval = 64;
683
687 static constexpr double kLandingSemitones = 0.001;
688
690 static constexpr double kMaxRetuneMs = 10000.0;
691
697 void rebuildSmoothing(double retuneMs) noexcept
698 {
699 smoothingForMs_ = retuneMs;
700 if (retuneMs <= 0.0 || sampleRate_ <= 0.0)
701 {
702 smoothing_ = 1.0; // hard snap
703 return;
704 }
705 const double tauSamples = retuneMs * 0.001 * sampleRate_;
706 smoothing_ = 1.0 - std::exp(-static_cast<double>(kControlInterval) / tauSamples);
707 }
708
713 void advanceCorrection(std::uint32_t absoluteMask) noexcept
714 {
715 if (absoluteMask == 0u)
716 {
717 target_ = 0.0; // no scale to snap to: correction disabled
718 }
719 else if (warmupRemaining_ == 0)
720 {
721 // Two gates before a report may establish a held correction: the
722 // analysis window must be full (a mostly-zero window is too little
723 // evidence for a value that will be held), and the fundamental
724 // must be one this effect could act on - above
725 // a quarter of the sample rate not even its second harmonic fits
726 // below Nyquist. Unvoiced, or refused: keep the previous target.
727 const double frequency = lowActive_
728 ? localHz_ : static_cast<double>(detector_.getFrequencyHz());
729 if (frequency > 0.0 && frequency <= 0.25 * sampleRate_)
730 {
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,
734 -12.0, 12.0);
735 }
736 }
737
738 if (smoothing_ >= 1.0)
739 {
740 correction_ = target_;
741 }
742 else
743 {
744 correction_ += (target_ - correction_) * smoothing_;
745 if (std::abs(target_ - correction_) < kLandingSemitones)
746 correction_ = target_; // exact landing
747 }
748
749 if (correction_ != publishedCorrection_)
750 {
751 if (lowActive_)
752 {
753 spliceRatio_ = std::exp2(correction_ / 12.0);
754 // Rates above 2^(1/8) decimate enough to need the stretched
755 // kernel; below it the full-band sinc folds only content above
756 // 20 kHz back (at 44.1 kHz and up).
757 spliceStep_ = spliceRatio_ > kStretchedFrom
758 ? StretchedSincReader<T>::stepFor(spliceRatio_) : -1;
759 }
760 else
761 {
762 shifter_.setSemitones(static_cast<T>(correction_));
763 }
764 publishedCorrection_ = correction_;
765 }
766 }
767
776 [[nodiscard]] static double nearestInScale(double midi,
777 std::uint32_t absoluteMask) noexcept
778 {
779 const int base = static_cast<int>(std::floor(midi));
780 int bestNote = base;
781 double bestDistance = 1.0e9;
782 for (int note = base - 12; note <= base + 13; ++note)
783 {
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)
788 {
789 bestDistance = distance;
790 bestNote = note;
791 }
792 }
793 return static_cast<double>(bestNote);
794 }
795
796 // -- Low-latency engine (pitch-synchronous splice) ---------------------------
797
799 static constexpr double kStretchedFrom = 1.0905077326652577; // 2^(1/8)
802 static constexpr double kSilence = 1.0e-6;
803
805 static const SincInterpolator<T>& sincTable()
806 {
807 static const SincInterpolator<T> table;
808 return table;
809 }
810 static const StretchedSincReader<T>& stretchedTable()
811 {
812 static const StretchedSincReader<T> table;
813 return table;
814 }
815
817 void prepareSplice(const AudioSpec& spec)
818 {
819 sinc_ = &sincTable();
820 stretched_ = &stretchedTable();
821
822 // The detector's window ends at the write head, so its centre is half
823 // a window back: a read head at that delay plays exactly the audio the
824 // current estimate describes. The delay must also hold a jump of one
825 // full period either way of it, and the detector reports periods up to
826 // half its window, so half a window is both the alignment and the
827 // room the jumps need.
828 const int window = detector_.getWindowSize();
829 spliceDelay_ = window / 2;
830 spliceFragment_ = std::max(kControlInterval, window / 16);
831 // The head never trails by more than the centre, half the longest
832 // jump, two fragments of drift and a kernel's reach: under a window.
833 int size = 1;
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)));
839
840 // Crossfade laws over one fragment, sampled at the midpoints so the
841 // two halves of a fade are mirror images: raised cosine (amplitude
842 // complementary) for period-aligned jumps, whose two reads are the same
843 // waveform, and sine/cosine (power complementary) for jumps through
844 // unvoiced sound, whose two reads are uncorrelated.
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)
850 {
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));
855 }
856 // Closest a read may come to the write head: the widest kernel's reach
857 // (the stretched kernel at the +12 semitone clamp) plus one sample.
858 minReadDelay_ = static_cast<double>(stretched_->reach(
860
861 // Local period search: two windows of at most kLocalSpan around the
862 // longest lag the detector reports, plus the search margin.
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);
866 }
867
869 static constexpr int kLocalSpan = 256;
870
874 [[nodiscard]] static int localMargin(double period) noexcept
875 {
876 return static_cast<int>(std::ceil(0.03 * period)) + 1;
877 }
878
891 [[nodiscard]] double localPeriod(double coarse) noexcept
892 {
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);
897 // Centre on the head, but never so close to the write head that the
898 // later window would need samples not yet written.
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)
913 {
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;
916 }
917
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;
922 const double ab = static_cast<double>(simd::dotProductT(
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;
928 };
929
930 int best = -1;
931 double bestValue = 0.5; // below this there is no clear periodicity
932 for (int lag = lagLo; lag <= lagHi; ++lag)
933 {
934 const double v = ncc(lag);
935 if (v > bestValue) { bestValue = v; best = lag; }
936 }
937 if (best <= lagLo || best >= lagHi) return coarse; // edge: not a peak
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);
942 }
943
945 void updateLocalPitch() noexcept
946 {
947 const double frequency = static_cast<double>(detector_.getFrequencyHz());
948 if (!(frequency > 0.0 && frequency <= 0.25 * sampleRate_) || warmupRemaining_ > 0)
949 {
950 localHz_ = frequency; // unvoiced, refused or warming up: as reported
951 return;
952 }
953 localHz_ = sampleRate_ / localPeriod(sampleRate_ / frequency);
954 }
955
957 void resetSplice() noexcept
958 {
959 for (auto& r : ring_) std::fill(r.begin(), r.end(), T(0));
960 writeCount_ = 0;
961 headInt_ = -static_cast<std::int64_t>(spliceDelay_);
962 headFrac_ = 0.0;
963 nextInt_ = headInt_;
964 nextFrac_ = 0.0;
965 fading_ = false;
966 fadeEqualPower_ = false;
967 holdUnity_ = false;
968 splicePhase_ = 0;
969 spliceRatio_ = 1.0;
970 spliceStep_ = -1;
971 localHz_ = 0.0;
972 lastLoud_ = std::numeric_limits<std::int64_t>::min() / 2;
973 markPrev_ = markNext_ = -static_cast<double>(spliceDelay_);
974 offsetCur_ = offsetNext_ = 0.0;
975 }
976
984 void decideSplice() noexcept
985 {
986 if (fading_)
987 {
988 headInt_ = nextInt_; // the faded-in head is now the only one
989 headFrac_ = nextFrac_;
990 fading_ = false;
991 }
992 holdUnity_ = false;
993
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_);
999
1000 // Everything both heads could read is silence: re-centre for free, and
1001 // read this fragment at unity so the next sound starts exactly at the
1002 // reported latency.
1003 if (lastLoud_ < std::min(headInt_, centreInt) - reach)
1004 {
1005 headInt_ = centreInt;
1006 headFrac_ = 0.0;
1007 holdUnity_ = true;
1008 return;
1009 }
1010
1011 double jump = 0.0;
1012 bool equalPower = false;
1013 const double frequency = localHz_;
1014 const bool voiced = warmupRemaining_ == 0 && frequency > 0.0
1015 && frequency <= 0.25 * sampleRate_;
1016 if (voiced)
1017 {
1018 // A jump of whole periods splices the waveform onto itself; it must
1019 // span at least a fragment, so it outruns the drift of a fragment
1020 // at any rate up to the +12 semitone clamp. The head is kept within
1021 // half a jump of the centre, so the mean delay is the latency.
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; // back: more delay
1025 else if (delay > centre + 0.5 * span) jump = span; // forward
1026 }
1027 else if (std::abs(delay - centre) > static_cast<double>(spliceFragment_))
1028 {
1029 // No period to align on: return to the centre with a
1030 // power-complementary fade.
1031 jump = delay - centre;
1032 equalPower = true;
1033 }
1034
1035 // Safety net for geometry the band rule cannot hold (a fragment
1036 // drifting further than a jump): never let a read reach the write head.
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_)
1039 {
1040 jump = delay - centre;
1041 equalPower = true;
1042 }
1043
1044 if (jump != 0.0)
1045 {
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_);
1049 fading_ = true;
1050 fadeEqualPower_ = equalPower;
1051 }
1052 }
1053
1056 void writeRings(AudioBufferView<T> buffer, int offset, int chunk, int nCh) noexcept
1057 {
1058 for (int ch = 0; ch < spliceChannels_; ++ch)
1059 {
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)
1063 {
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;
1068 }
1069 }
1070 }
1071
1084 void advanceGrain() noexcept
1085 {
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_;
1091 if (!voiced)
1092 {
1093 markNext_ = markPrev_ + static_cast<double>(spliceFragment_);
1094 offsetNext_ = 0.0;
1095 return;
1096 }
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_;
1102 }
1103
1119 void grainChunk(AudioBufferView<T> buffer, int offset, int chunk) noexcept
1120 {
1121 const int nCh = std::min(buffer.getNumChannels(), spliceChannels_);
1122 writeRings(buffer, offset, chunk, nCh);
1123
1124 // Everything a grain could read is silence (offsets stay within half
1125 // a period, under half the delay): re-centre for free.
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; }
1130
1131 std::int64_t pos1[kControlInterval], pos2[kControlInterval];
1132 double frac1[kControlInterval], frac2[kControlInterval];
1133 T fade[kControlInterval];
1134 bool cross = false;
1135 for (int k = 0; k < chunk; ++k)
1136 {
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_;
1147 }
1148 headInt_ = now + chunk - static_cast<std::int64_t>(spliceDelay_)
1149 + static_cast<std::int64_t>(std::lround(offsetCur_));
1150
1151 for (int ch = 0; ch < nCh; ++ch)
1152 {
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)
1156 {
1157 const T a = sinc_->readRing(ring, ringMask_, pos1[k], frac1[k]);
1158 if (!cross || (pos1[k] == pos2[k] && frac1[k] == frac2[k]))
1159 {
1160 out[k] = a;
1161 continue;
1162 }
1163 const T b = sinc_->readRing(ring, ringMask_, pos2[k], frac2[k]);
1164 out[k] = a + (b - a) * fade[k];
1165 }
1166 }
1167
1168 writeCount_ += chunk;
1169 splicePhase_ += chunk;
1170 if (splicePhase_ >= spliceFragment_) splicePhase_ = 0;
1171 }
1172
1174 T readRing(const T* ring, std::int64_t pos, double frac) const noexcept
1175 {
1176 return spliceStep_ < 0
1177 ? sinc_->readRing(ring, ringMask_, pos, frac)
1178 : stretched_->readRing(ring, ringMask_, pos, frac, spliceStep_);
1179 }
1180
1186 void spliceChunk(AudioBufferView<T> buffer, int offset, int chunk) noexcept
1187 {
1188 const int nCh = std::min(buffer.getNumChannels(), spliceChannels_);
1189
1190 // 1. Write the input.
1191 writeRings(buffer, offset, chunk, nCh);
1192
1193 // 2. The head trajectories, shared by every channel (stereo-linked).
1194 const double ratio = holdUnity_ ? 1.0 : spliceRatio_;
1195 std::int64_t pos1[kControlInterval], pos2[kControlInterval];
1196 double frac1[kControlInterval], frac2[kControlInterval];
1197 {
1198 std::int64_t i1 = headInt_, i2 = nextInt_;
1199 double f1 = headFrac_, f2 = nextFrac_;
1200 for (int k = 0; k < chunk; ++k)
1201 {
1202 pos1[k] = i1; frac1[k] = f1;
1203 pos2[k] = i2; frac2[k] = f2;
1204 f1 += ratio;
1205 f2 += ratio;
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;
1210 }
1211 headInt_ = i1; headFrac_ = f1;
1212 if (fading_) { nextInt_ = i2; nextFrac_ = f2; }
1213 }
1214
1215 // 3. Read every channel.
1216 for (int ch = 0; ch < nCh; ++ch)
1217 {
1218 const T* ring = ring_[static_cast<std::size_t>(ch)].data();
1219 T* out = buffer.getChannel(ch) + offset;
1220 if (!fading_)
1221 {
1222 for (int k = 0; k < chunk; ++k) out[k] = readRing(ring, pos1[k], frac1[k]);
1223 continue;
1224 }
1225 const auto at = static_cast<std::size_t>(splicePhase_);
1226 for (int k = 0; k < chunk; ++k)
1227 {
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];
1233 }
1234 }
1235
1236 writeCount_ += chunk;
1237 splicePhase_ += chunk;
1238 if (splicePhase_ >= spliceFragment_) splicePhase_ = 0;
1239 }
1240
1241 // -- Members -----------------------------------------------------------------
1242
1243 PitchDetector<T> detector_;
1244 PitchShifter<T> shifter_;
1245
1246 double sampleRate_ = 48000.0;
1247 int frameSize_ = 0;
1248 int spectralLatency_ = 0;
1249 std::atomic<int> latency_ { 0 };
1250 bool prepared_ = false;
1251
1252 // Low-latency engine (stream owner, sized by prepare()).
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 };
1284
1285 // Stream-owner state (audio thread only).
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;
1294
1297 std::atomic<std::uint32_t> scaleWord_ { 0x0FFF0FFFu };
1298 std::atomic<T> retuneSpeedMs_ { T(0) };
1299 std::atomic<bool> formantPreserve_ { false };
1300};
1301
1302} // namespace dspark
Non-owning view over audio channel data.
Definition AudioBuffer.h:53
RAII scope guard to disable denormalised (subnormal) floating-point numbers.
Scale-aware monophonic retune over the framework's YIN detector and phase-vocoder shifter.
T getRetuneSpeedMs() const noexcept
std::vector< uint8_t > getState() const
Serializes the parameter state (setup/UI threads; allocates).
void setFormantPreserve(bool on) noexcept
Enables formant preservation (default off): the shifter's cepstral envelope pre-warp in the default e...
void setLowLatency(bool on) noexcept
Selects the low-latency engine (default off).
int getFrameSize() const noexcept
The analysis frame in effect, in samples: the automatic choice for this rate, or the rounded explicit...
void processBlock(AudioBufferView< T > buffer) noexcept
Processes audio in-place. Pass-through until prepare() succeeds.
bool getFormantPreserve() const noexcept
int getLatency() const noexcept
Reports the signal latency in samples. Default engine: twice the analysis frame, which is 4096 sample...
bool getLowLatency() const noexcept
void setScale(std::uint16_t scaleBitmask, int rootPitchClass) noexcept
Selects the scale the output snaps to.
bool setState(const uint8_t *data, size_t size)
Restores parameters from a blob (tolerant; rejects foreign ids). A missing field restores its default...
int getRootPitchClass() const noexcept
std::uint16_t getScaleMask() const noexcept
void prepare(const AudioSpec &spec, int fftSize=0)
Allocates the detector and shifter state (setup thread).
void setRetuneSpeedMs(T ms) noexcept
Sets the retune speed: the time constant, in milliseconds, of the glide from the sung pitch to the ta...
void reset() noexcept
Clears all signal state and keeps the parameters (stream owner).
Real-time phase-vocoder pitch shifter (+-12 semitones, stereo-linked).
Tolerant reader: missing keys yield defaults, unknown keys are skipped.
Definition StateBlob.h:171
float read(const char *key, float defaultValue) const
Reads a float, or defaultValue when the key is absent.
Definition StateBlob.h:214
bool isValid() const noexcept
Definition StateBlob.h:209
uint32_t processorId() const noexcept
Definition StateBlob.h:210
Serializes key/value parameters into a versioned blob.
Definition StateBlob.h:53
std::vector< uint8_t > blob() const
Finalizes and returns the blob.
Definition StateBlob.h:112
void write(const char *key, float value)
Writes a float parameter.
Definition StateBlob.h:71
static int stepFor(double rate) noexcept
The table for a read rate: the nearest tabulated rate at or above it. Costs a log2,...
constexpr int delay
Delay of the projected output behind the newest input, in samples.
std::uint16_t NoteSet
A 12-bit bitmask representing the 12 pitch-classes of the chromatic scale.
constexpr NoteSet scaleAtRoot(NoteSet base, int root) noexcept
Circularly rotate a NoteSet so it becomes rooted at a specific key.
T dotProductT(const T *DSPARK_RESTRICT a, const T *DSPARK_RESTRICT b, int count) noexcept
Definition SimdOps.h:1426
Main namespace for the DSPark framework.
T fastCos(T x) noexcept
Fast cosine approximation. See fastSin() for accuracy notes (the pi/2 offset costs float about one ul...
Definition DspMath.h:369
constexpr uint32_t stateId(const char(&tag)[5]) noexcept
Builds a FOURCC processor id, e.g. dspark::stateId("COMP").
Definition StateBlob.h:672
Describes the audio environment for a DSP processor.
Definition AudioSpec.h:37
constexpr bool isValid() const noexcept
Checks if the specification contains valid, processable parameters.
Definition AudioSpec.h:71
double sampleRate
Sample rate in Hz.
Definition AudioSpec.h:45