278#include "../Core/AudioBuffer.h"
279#include "../Core/AudioSpec.h"
280#include "../Core/DenormalGuard.h"
281#include "../Core/DspMath.h"
282#include "../Core/StateBlob.h"
283#include "detail/PhaseVocoderEngine.h"
284#include "detail/StudioVocoder.h"
301template <FloatType T>
307 static_assert(std::atomic<bool>::is_always_lock_free,
308 "audio-thread stores must not lock");
337 std::memory_order_relaxed);
343 return quality_.load(std::memory_order_relaxed);
368 if (fftSize != 0 && ((fftSize & (fftSize - 1)) != 0
369 || fftSize < 256 || fftSize > (1 << 20)))
372 prepared_.store(
false, std::memory_order_relaxed);
378 fftStandard_ = fftSize != 0 ? fftSize : 2048;
379 fftStudio_ = fftSize != 0 ? fftSize : studioDefaultFrame(spec.
sampleRate);
386 const int widest = std::max(fftStandard_, fftStudio_);
389 while (queueSize_ < capacity) queueSize_ <<= 1;
390 queueMask_ = queueSize_ - 1;
397 engine_.prepare(spec.
sampleRate, numChannels_, fftStandard_,
false,
false,
true,
true);
398 studio_.prepare(spec.
sampleRate, numChannels_, fftStudio_,
false);
400 queue_.assign(
static_cast<size_t>(numChannels_), {});
401 for (
int ch = 0; ch < numChannels_; ++ch)
402 queue_[
static_cast<size_t>(ch)].assign(
static_cast<size_t>(queueSize_), T(0));
403 feed_.assign(
static_cast<size_t>(capacity), T(0));
405 publishEngineParams();
406 prepared_.store(
true, std::memory_order_relaxed);
414 if (!prepared_.load(std::memory_order_relaxed))
return;
415 studioActive_ = quality_.load(std::memory_order_relaxed) ==
Quality::Studio;
418 int latency = fftStandard_;
421 fftSize_ = fftStudio_;
424 latency = fftStudio_ + studio_.lookahead();
425 accumMask_ = studio_.olaMask();
429 fftSize_ = fftStandard_;
435 accumMask_ = engine_.olaMask();
437 latency_.store(latency, std::memory_order_relaxed);
438 synthHop_ = fftSize_ / 4;
439 for (
auto& q : queue_) std::fill(q.begin(), q.end(), T(0));
449 readPos_ = eWriteHead() -
static_cast<int64_t
>(latency - fftSize_ + synthHop_);
465 if (!std::isfinite(ratio))
return;
467 std::memory_order_relaxed);
468 publishEngineParams();
481 if (!std::isfinite(pct))
return;
482 const T denom = T(1) + pct / T(100);
492 transientPreserve_.store(on, std::memory_order_relaxed);
493 publishEngineParams();
508 phaseLock_.store(on, std::memory_order_relaxed);
509 publishEngineParams();
515 return timeRatio_.load(std::memory_order_relaxed);
521 return transientPreserve_.load(std::memory_order_relaxed);
527 return phaseLock_.load(std::memory_order_relaxed);
539 return prepared_.load(std::memory_order_relaxed)
540 ? latency_.load(std::memory_order_relaxed)
551 [[nodiscard]]
static int64_t
stretchedLength(int64_t inputSamples,
double ratio)
noexcept
553 return std::llround(
static_cast<double>(inputSamples) * ratio);
571 if (!prepared_.load(std::memory_order_relaxed) || path_ == Path::Adaptor)
573 return queueSize_ - queued_;
585 if (!prepared_.load(std::memory_order_relaxed) || path_ != Path::Pull)
587 return static_cast<int>(std::max<int64_t>(0, eWriteHead() - readPos_));
606 if (!prepared_.load(std::memory_order_relaxed) || !claimPullPath())
return 0;
609 const int nCh = std::min(in.getNumChannels(), numChannels_);
610 const int count = std::min(std::max(0, in.getNumSamples()), queueSize_ - queued_);
611 int wp = queueWrite_;
612 for (
int k = 0; k < count; ++k)
614 for (
int ch = 0; ch < nCh; ++ch)
615 queue_[
static_cast<size_t>(ch)][
static_cast<size_t>(wp)]
616 = in.getChannel(ch)[k];
617 for (
int ch = nCh; ch < numChannels_; ++ch)
618 queue_[
static_cast<size_t>(ch)][
static_cast<size_t>(wp)] = T(0);
619 wp = (wp + 1) & queueMask_;
643 if (!prepared_.load(std::memory_order_relaxed) || !claimPullPath())
return 0;
646 const int nCh = std::min(out.getNumChannels(), numChannels_);
647 const int count = std::min(std::max(0, out.getNumSamples()),
648 static_cast<int>(std::max<int64_t>(0, eWriteHead() - readPos_)));
651 readSynthesis(out, nCh, 0, count);
657 return std::max(0, count);
673 [[nodiscard]] std::vector<uint8_t>
getState()
const
676 w.
write(
"ratio",
static_cast<float>(timeRatio_.load(std::memory_order_relaxed)));
677 w.
write(
"transient", transientPreserve_.load(std::memory_order_relaxed));
678 w.
write(
"phaselock", phaseLock_.load(std::memory_order_relaxed));
679 w.
write(
"quality",
static_cast<int32_t
>(quality_.load(std::memory_order_relaxed)));
715 if (!prepared_.load(std::memory_order_relaxed))
return;
716 if (path_ == Path::Pull)
return;
717 path_ = Path::Adaptor;
720 const int nCh = std::min(buffer.getNumChannels(), numChannels_);
721 const int nS = buffer.getNumSamples();
735 takeInput(buffer, nCh, taken, i);
737 const int64_t avail = eWriteHead() - readPos_;
740 const int take =
static_cast<int>(
741 std::min<int64_t>(avail,
static_cast<int64_t
>(nS - i)));
742 takeInput(buffer, nCh, taken, i + take);
743 readSynthesis(buffer, nCh, i, take);
754 const int need = eSamplesToNextHop();
757 const int silence = std::min(need - queued_, nS - i);
761 takeInput(buffer, nCh, taken, i + silence);
762 for (
int ch = 0; ch < nCh; ++ch)
763 std::fill(buffer.getChannel(ch) + i, buffer.getChannel(ch) + i + silence, T(0));
768 for (
int ch = 0; ch < nCh; ++ch)
770 dequeueInto(ch, need);
771 ePushInput(ch, feed_.data(), need);
773 eCommitInput(need, nCh);
774 queueRead_ = (queueRead_ + need) & queueMask_;
799 if (!prepared_.load(std::memory_order_relaxed) || inLen <= 0 || inCh <= 0)
801 out.
resize(std::max(0, inCh), std::max(0, inLen));
802 for (
int ch = 0; ch < inCh; ++ch)
807 const int nCh = std::min(inCh, numChannels_);
811 const int outLen =
static_cast<int>(offlineStop_ - offlineSkip_);
812 out.
resize(inCh, std::max(0, outLen));
815 std::vector<T*> ptrs(
static_cast<size_t>(nCh));
816 for (
int ch = 0; ch < nCh; ++ch) ptrs[static_cast<size_t>(ch)] = out.
getChannel(ch);
819 offlineOpen_ =
false;
824 for (
int ch = nCh; ch < inCh; ++ch)
828 const int n = std::min(outLen, inLen);
829 std::copy(src, src + n, dst);
830 std::fill(dst + n, dst + outLen, T(0));
852 offlineOpen_ =
false;
853 if (!prepared_.load(std::memory_order_relaxed))
return;
855 path_ = Path::Adaptor;
856 offlineChannels_ = std::clamp(numChannels, 1, numChannels_);
857 offlineRatio_ = studioActive_ ? studio_.activeRatio() : engine_.activeRatio();
861 offlineSkip_ = studioActive_
862 ? std::llround(studio_.streamPositionOf(0.0)) - readPos_
863 : std::llround(0.5 *
static_cast<double>(fftSize_) * (1.0 + offlineRatio_));
864 offlineStreamPos_ = 0;
865 offlineReceived_ = 0;
866 offlineStop_ = offlineSkip_;
867 offlineFinished_ =
false;
868 offlineStaged_.assign(
static_cast<size_t>(offlineChannels_), std::vector<T> {});
869 offlineStagedHead_ = 0;
870 offlineOut_.assign(
static_cast<size_t>(offlineChannels_), std::vector<T> {});
878 if (!offlineOpen_ || offlineFinished_)
return;
881 for (
int ch = 0; ch < offlineChannels_; ++ch)
883 auto& q = offlineStaged_[
static_cast<size_t>(ch)];
887 q.insert(q.end(),
static_cast<size_t>(n), T(0));
889 offlineReceived_ += n;
897 if (!offlineOpen_ || offlineFinished_)
return;
898 offlineFinished_ =
true;
899 offlineStop_ = offlineSkip_ +
stretchedLength(offlineReceived_, offlineRatio_);
906 if (!offlineOpen_ || offlineOut_.empty())
return 0;
907 return static_cast<int>(offlineOut_[0].size() - offlineOutHead_);
918 if (n <= 0)
return 0;
919 for (
int ch = 0; ch < offlineChannels_ && ch < out.
getNumChannels(); ++ch)
921 const T* src = offlineOut_[
static_cast<size_t>(ch)].data() + offlineOutHead_;
924 offlineOutHead_ +=
static_cast<size_t>(n);
925 if (offlineOutHead_ > 65536 && offlineOutHead_ * 2 > offlineOut_[0].size())
927 for (
auto& q : offlineOut_)
928 q.erase(q.begin(), q.begin() +
static_cast<std::ptrdiff_t
>(offlineOutHead_));
947 const int nCh = offlineChannels_;
950 if (offlineFinished_ && offlineStreamPos_ >= offlineStop_)
break;
951 const int64_t avail = eWriteHead() - readPos_;
954 const int need = eSamplesToNextHop();
955 const int64_t staged =
static_cast<int64_t
>(offlineStaged_[0].size() - offlineStagedHead_);
956 if (!offlineFinished_ && staged < need)
break;
958 for (
int ch = 0; ch < nCh; ++ch)
960 const auto& q = offlineStaged_[
static_cast<size_t>(ch)];
961 for (
int k = 0; k < need; ++k)
963 const size_t idx = offlineStagedHead_ +
static_cast<size_t>(k);
964 feed_[
static_cast<size_t>(k)] = (idx < q.size()) ? q[idx] : T(0);
966 ePushInput(ch, feed_.data(), need);
968 eCommitInput(need, nCh);
969 offlineStagedHead_ = std::min(offlineStagedHead_ +
static_cast<size_t>(need),
970 offlineStaged_[0].size());
971 if (offlineStagedHead_ > 65536)
973 for (
auto& q : offlineStaged_)
974 q.erase(q.begin(), q.begin() + static_cast<std::ptrdiff_t>(offlineStagedHead_));
975 offlineStagedHead_ = 0;
980 const int64_t limit = offlineFinished_
983 const int64_t take = std::min(avail, limit - offlineStreamPos_);
984 if (take <= 0)
break;
985 const int64_t from = std::max(offlineStreamPos_, offlineSkip_);
986 const int64_t count = offlineStreamPos_ + take - from;
989 for (
int ch = 0; ch < nCh; ++ch)
991 const T* acc = eOla(ch);
992 auto& q = offlineOut_[
static_cast<size_t>(ch)];
993 const int64_t rp = readPos_ + (from - offlineStreamPos_);
994 for (int64_t k = 0; k < count; ++k)
995 q.push_back(acc[
static_cast<size_t>((rp + k) & accumMask_)]);
999 offlineStreamPos_ += take;
1005 void publishEngineParams() noexcept
1007 typename detail::PhaseVocoderEngine<T>::Params p;
1011 p.targetSemitones = 12.0 * std::log2(
static_cast<double>(
1012 timeRatio_.load(std::memory_order_relaxed)));
1013 p.transientPreserve = transientPreserve_.load(std::memory_order_relaxed);
1014 p.formantPreserve =
false;
1015 p.phaseLock = phaseLock_.load(std::memory_order_relaxed);
1016 p.percussiveSplit =
false;
1017 engine_.publishParams(p);
1019 typename detail::StudioVocoder<T>::Params q;
1020 q.targetSemitones = p.targetSemitones;
1021 q.transientPreserve = p.transientPreserve;
1022 q.formantPreserve =
false;
1023 studio_.publishParams(q);
1047 void openIntake() noexcept
1049 intakeSpan_ = std::max(1, synthHop_);
1050 const double ratio = studioActive_ ? studio_.activeRatio() : engine_.activeRatio();
1055 intakeWant_ = ratio <= 1.0
1056 ? queueSize_ - queued_
1057 : std::clamp(eSamplesToNextHop() - queued_, 0, queueSize_ - queued_);
1063 [[nodiscard]]
bool acceptOffered() noexcept
1065 if (intakeTaken_ >= intakeWant_)
return false;
1066 if (intakeWant_ < intakeSpan_)
1068 intakeErr_ += intakeWant_;
1069 if (intakeErr_ < intakeSpan_)
return false;
1070 intakeErr_ -= intakeSpan_;
1086 void takeInput(AudioBufferView<T> buffer,
int nCh,
int& taken,
int upTo)
noexcept
1088 if (upTo <= taken)
return;
1089 int wp = queueWrite_;
1091 for (
int k = taken; k < upTo; ++k)
1093 if (!acceptOffered()) { ++discarded_;
continue; }
1094 for (
int ch = 0; ch < nCh; ++ch)
1095 queue_[
static_cast<size_t>(ch)][
static_cast<size_t>(wp)]
1096 = buffer.getChannel(ch)[k];
1097 wp = (wp + 1) & queueMask_;
1107 [[nodiscard]]
bool claimPullPath() noexcept
1109 if (path_ == Path::Pull)
return true;
1110 if (path_ != Path::None)
return false;
1116 readPos_ = studioActive_
1117 ?
static_cast<int64_t
>(std::llround(studio_.streamPositionOf(0.0)))
1118 : eWriteHead() - static_cast<int64_t>(synthHop_) + std::llround(
1119 0.5 * static_cast<double>(fftSize_) * (1.0 + engine_.activeRatio()));
1125 void runReadyFrames() noexcept
1129 const int need = eSamplesToNextHop();
1130 if (queued_ < need)
return;
1133 if (eWriteHead() +
static_cast<int64_t
>(fftSize_) - readPos_
1134 >
static_cast<int64_t
>(accumMask_) + 1)
1137 for (
int ch = 0; ch < numChannels_; ++ch)
1139 dequeueInto(ch, need);
1140 ePushInput(ch, feed_.data(), need);
1142 eCommitInput(need, numChannels_);
1143 queueRead_ = (queueRead_ + need) & queueMask_;
1151 void dequeueInto(
int ch,
int count)
noexcept
1153 const auto& q = queue_[
static_cast<size_t>(ch)];
1154 int rp = queueRead_;
1155 for (
int k = 0; k < count; ++k)
1157 feed_[
static_cast<size_t>(k)] = q[
static_cast<size_t>(rp)];
1158 rp = (rp + 1) & queueMask_;
1163 void readSynthesis(AudioBufferView<T> buffer,
int nCh,
int offset,
int count)
noexcept
1165 for (
int ch = 0; ch < nCh; ++ch)
1167 const T* acc = eOla(ch);
1168 T* dst = buffer.getChannel(ch) + offset;
1169 const int64_t rp = readPos_;
1170 for (
int k = 0; k < count; ++k)
1171 dst[k] = acc[
static_cast<size_t>((rp + k) & accumMask_)];
1177 [[nodiscard]] int64_t eWriteHead() const noexcept
1179 return studioActive_ ? studio_.writeHead() : engine_.writeHead();
1181 [[nodiscard]]
int eSamplesToNextHop() const noexcept
1183 return studioActive_ ? studio_.samplesToNextHop() : engine_.samplesToNextHop();
1185 void ePushInput(
int ch,
const T* src,
int count)
noexcept
1187 if (studioActive_) studio_.pushInput(ch, src, count);
1188 else engine_.pushInput(ch, src, count);
1190 void eCommitInput(
int count,
int nCh)
noexcept
1192 if (studioActive_) studio_.commitInput(count, nCh);
1193 else engine_.commitInput(count, nCh);
1195 [[nodiscard]]
const T* eOla(
int ch)
const noexcept
1197 return studioActive_ ? studio_.olaData(ch) : engine_.olaData(ch);
1201 [[nodiscard]]
static int studioDefaultFrame(
double sampleRate)
noexcept
1204 while (n < (1 << 16) &&
static_cast<double>(n) * 1.5 < 0.085 * sampleRate) n <<= 1;
1209 int numChannels_ = 0;
1210 std::atomic<bool> prepared_ {
false };
1212 int fftSize_ = 2048;
1213 int synthHop_ = 512;
1214 std::atomic<int> latency_ { 2048 };
1215 int64_t accumMask_ = 8191;
1217 detail::PhaseVocoderEngine<T> engine_;
1218 detail::StudioVocoder<T> studio_;
1219 bool studioActive_ =
true;
1220 int fftStandard_ = 2048;
1221 int fftStudio_ = 4096;
1223 std::vector<std::vector<T>> queue_;
1224 std::vector<T> feed_;
1227 int queueWrite_ = 0;
1232 enum class Path {
None, Adaptor, Pull };
1233 Path path_ = Path::None;
1235 int64_t discarded_ = 0;
1236 int intakeSpan_ = 0;
1237 int intakeWant_ = 0;
1238 int intakeTaken_ = 0;
1241 int64_t readPos_ = 0;
1244 std::atomic<T> timeRatio_ { T(1) };
1245 std::atomic<bool> transientPreserve_ {
true };
1246 std::atomic<bool> phaseLock_ {
true };
1249 bool offlineOpen_ =
false;
1250 bool offlineFinished_ =
false;
1251 int offlineChannels_ = 0;
1252 double offlineRatio_ = 1.0;
1253 int64_t offlineSkip_ = 0;
1254 int64_t offlineStop_ = 0;
1255 int64_t offlineStreamPos_ = 0;
1256 int64_t offlineReceived_ = 0;
1257 std::vector<std::vector<T>> offlineStaged_;
1258 size_t offlineStagedHead_ = 0;
1259 std::vector<std::vector<T>> offlineOut_;
1260 size_t offlineOutHead_ = 0;
Non-owning view over audio channel data.
int getNumSamples() const noexcept
Returns the number of samples per channel.
int getNumChannels() const noexcept
Returns the number of channels in this view.
T * getChannel(int ch) const noexcept
Returns a pointer to the sample data for the given channel.
AudioBufferView getSubView(int startSample, int length) const noexcept
Returns a zero-copy sub-view starting at an offset.
Owning audio buffer with contiguous, 32-byte aligned storage.
T * getChannel(int ch) noexcept
Returns a pointer to the sample data.
void resize(int numChannels, int numSamples)
Allocates the buffer for the given dimensions.
RAII scope guard to disable denormalised (subnormal) floating-point numbers.
Tolerant reader: missing keys yield defaults, unknown keys are skipped.
float read(const char *key, float defaultValue) const
Reads a float, or defaultValue when the key is absent.
bool isValid() const noexcept
uint32_t processorId() const noexcept
Serializes key/value parameters into a versioned blob.
std::vector< uint8_t > blob() const
Finalizes and returns the blob.
void write(const char *key, float value)
Writes a float parameter.
Real-time and offline time stretching, 0.5x to 2x, pitch unchanged.
static int64_t stretchedLength(int64_t inputSamples, double ratio) noexcept
Length in samples of inputSamples stretched by ratio, which is what process() and an offline session ...
int getInputCapacity() const noexcept
Room for input right now, in samples (stream owner).
void setTimeRatio(T ratio) noexcept
Sets the stretch as an output/input length ratio.
int getAvailableOutput() const noexcept
Stretched output ready right now, in samples (stream owner).
void processBlock(AudioBufferView< T > buffer) noexcept
Fixed-rate playback adaptor: streaming, in-place, real-time safe.
void prepare(const AudioSpec &spec, int fftSize=0)
Allocates every buffer this class will ever use.
T getTimeRatio() const noexcept
void process(AudioBufferView< const T > in, AudioBuffer< T > &out)
Offline whole-signal stretch (setup thread; allocates out).
Quality
The engine that renders the stretch (see the file overview).
std::vector< uint8_t > getState() const
Serializes the parameter state (setup/UI threads; allocates).
int feedInput(AudioBufferView< const T > in) noexcept
Hands input to the stretch; real-time safe (stream owner).
int getQueuedInputSamples() const noexcept
Input samples accepted but not yet consumed by the stretch.
int64_t getDiscardedInput() const noexcept
Input samples the fixed-rate adaptor refused, cumulative since prepare() or reset() (stream owner).
void setTempoChangePercent(T pct) noexcept
Sets the stretch as a tempo change in percent.
void finishOffline()
Ends the input of an offline session; everything left becomes available to pullOffline().
int getLatency() const noexcept
Latency of the fixed-rate processBlock() path in samples for the engine in force: one frame for Stand...
static constexpr T kMinRatio
Smallest and largest stretch this class accepts.
Quality getQuality() const noexcept
int pullOffline(AudioBufferView< T > out)
Writes up to out.getNumSamples() stretched samples of an offline session and returns how many it wrot...
bool getTransientPreserve() const noexcept
bool setState(const uint8_t *data, size_t size)
Restores parameters from a blob (tolerant; rejects foreign ids).
int pullOutput(AudioBufferView< T > out) noexcept
Takes stretched output; real-time safe (stream owner).
int getOfflineAvailable() const noexcept
Stretched samples ready to pull in an offline session.
static constexpr T kMaxRatio
void setQuality(Quality q) noexcept
Selects the engine (applied at the next prepare()/reset()).
void beginOffline(int numChannels)
Opens an offline stretch fed in blocks (setup thread; allocates).
void pushOffline(AudioBufferView< const T > in)
Feeds the next block of an offline session. No-op outside one.
bool getPhaseLock() const noexcept
void setTransientPreserve(bool on) noexcept
Enables phase reset on detected transients (default on). Without it, attacks are stretched along with...
void setPhaseLock(bool on) noexcept
Enables identity phase locking in the Standard engine (default on). Studio has no such switch: its ph...
void reset() noexcept
Clears all signal state and empties the input queue (keeps parameters). Belongs to the owner of the s...
Main namespace for the DSPark framework.
@ None
The curve as drawn: a brief move plays at part of its depth.
constexpr uint32_t stateId(const char(&tag)[5]) noexcept
Builds a FOURCC processor id, e.g. dspark::stateId("COMP").
Describes the audio environment for a DSP processor.
constexpr bool isValid() const noexcept
Checks if the specification contains valid, processable parameters.
int numChannels
Number of audio channels (e.g., 1 = mono, 2 = stereo).
int maxBlockSize
Maximum number of samples per processing block.
double sampleRate
Sample rate in Hz.