33#include "../DspMath.h"
34#include "../SampleZone.h"
35#include "../SimdOps.h"
79 for (
int c = 0; c < ch; ++c)
94 d.
gain = std::pow(10.0, std::clamp(z.
gainDb, -120.0, 24.0) / 20.0);
95 d.
pan = std::clamp(z.
pan, -1.0, 1.0);
97 d.
audio.resize(
static_cast<size_t>(ch) *
static_cast<size_t>(len));
98 for (
int c = 0; c < ch; ++c)
101 T* dst = d.
audio.data() +
static_cast<size_t>(c) *
static_cast<size_t>(len);
102 for (int64_t i = 0; i < len; ++i)
103 dst[i] = std::isfinite(src[i]) ? src[i] : T(0);
117 d.
baked.resize(
static_cast<size_t>(ch) *
static_cast<size_t>(d.
xfade));
118 for (
int c = 0; c < ch; ++c)
120 const T* src = d.
audio.data() +
static_cast<size_t>(c) *
static_cast<size_t>(len);
121 T* dst = d.
baked.data() +
static_cast<size_t>(c) *
static_cast<size_t>(d.
xfade);
122 for (int64_t i = 0; i < d.
xfade; ++i)
126 const double x = (
static_cast<double>(i) + 0.5) /
static_cast<double>(d.
xfade);
129 const double tail =
static_cast<double>(src[d.
loopEnd - d.
xfade + i]);
130 const double lead =
static_cast<double>(src[d.
loopStart - d.
xfade + i]);
131 dst[i] =
static_cast<T
>(fout * tail + fin * lead);
144 double& left,
double& right,
double& mono)
noexcept
151 left = gain * std::cos(0.25 * pi<double> * (1.0 + pan)) * sqrt2<double>;
152 right = gain * std::cos(0.25 * pi<double> * (1.0 - pan)) * sqrt2<double>;
156 left = gain * std::min(1.0, 1.0 - pan);
157 right = gain * std::min(1.0, 1.0 + pan);
166template <FloatType T>
169 return ((lane[0] + lane[4]) + (lane[1] + lane[5])) + ((lane[2] + lane[6]) + (lane[3] + lane[7]));
184template <
int C, FloatType T>
186 int taps, T* out)
noexcept
188 constexpr int W = std::is_same_v<T, float> ? simd::kVecFloatNarrow : simd::kVecDoubleNarrow;
189 using V = simd::Vec<T, W>;
190 using R =
typename V::V;
193 for (
int k = 0; k < K; ++k) acc0[k] = acc1[k] = V::set1(T(0));
194 const R gv = V::set1(g);
196 for (
int k = 0; k < K; ++k)
198 const int o = t + k * W;
199 const R a = V::load(r0 + o);
200 const R w = V::add(a, V::mul(gv, V::sub(V::load(r1 + o), a)));
201 acc0[k] = V::add(acc0[k], V::mul(w, V::load(x0 + o)));
202 if constexpr (C == 2) acc1[k] = V::add(acc1[k], V::mul(w, V::load(x1 + o)));
205 for (
int k = 0; k < K; ++k) V::store(lane + k * W, acc0[k]);
207 if constexpr (C == 2)
209 for (
int k = 0; k < K; ++k) V::store(lane + k * W, acc1[k]);
214#if defined(DSPARK_SIMD_EXACT_AVX2)
215DSPARK_SIMD_EXACT_AVX2_BEGIN
217inline float sampleGatherReduceAvx2(__m256 v)
noexcept
219 const __m128 q = _mm_add_ps(_mm256_castps256_ps128(v), _mm256_extractf128_ps(v, 1));
220 const __m128 pairs = _mm_add_ps(q, _mm_shuffle_ps(q, q, _MM_SHUFFLE(2, 3, 0, 1)));
221 return _mm_cvtss_f32(_mm_add_ss(pairs, _mm_movehl_ps(pairs, pairs)));
225inline double sampleGatherReduceAvx2(__m256d l, __m256d h)
noexcept
227 const __m256d q = _mm256_add_pd(l, h);
228 const __m128d q01 = _mm256_castpd256_pd128(q), q23 = _mm256_extractf128_pd(q, 1);
229 const double s01 = _mm_cvtsd_f64(_mm_add_sd(q01, _mm_unpackhi_pd(q01, q01)));
230 const double s23 = _mm_cvtsd_f64(_mm_add_sd(q23, _mm_unpackhi_pd(q23, q23)));
236inline void sampleGatherAvx2(
const float* r0,
const float* r1,
float g,
const float* x0,
237 const float* x1,
int taps,
float* out)
noexcept
239 __m256 acc0 = _mm256_setzero_ps(), acc1 = _mm256_setzero_ps();
240 const __m256 gv = _mm256_set1_ps(g);
243 const __m256 a = _mm256_loadu_ps(r0 + t);
244 const __m256 w = _mm256_add_ps(a, _mm256_mul_ps(gv, _mm256_sub_ps(_mm256_loadu_ps(r1 + t), a)));
245 acc0 = _mm256_add_ps(acc0, _mm256_mul_ps(w, _mm256_loadu_ps(x0 + t)));
246 if constexpr (C == 2) acc1 = _mm256_add_ps(acc1, _mm256_mul_ps(w, _mm256_loadu_ps(x1 + t)));
248 out[0] = sampleGatherReduceAvx2(acc0);
249 if constexpr (C == 2) out[1] = sampleGatherReduceAvx2(acc1);
254inline void sampleGatherAvx2(
const double* r0,
const double* r1,
double g,
const double* x0,
255 const double* x1,
int taps,
double* out)
noexcept
257 __m256d a00 = _mm256_setzero_pd(), a01 = _mm256_setzero_pd();
258 __m256d a10 = _mm256_setzero_pd(), a11 = _mm256_setzero_pd();
259 const __m256d gv = _mm256_set1_pd(g);
262 const __m256d lo = _mm256_loadu_pd(r0 + t), hi = _mm256_loadu_pd(r0 + t + 4);
263 const __m256d wl = _mm256_add_pd(lo, _mm256_mul_pd(gv, _mm256_sub_pd(_mm256_loadu_pd(r1 + t), lo)));
264 const __m256d wh = _mm256_add_pd(hi, _mm256_mul_pd(gv, _mm256_sub_pd(_mm256_loadu_pd(r1 + t + 4), hi)));
265 a00 = _mm256_add_pd(a00, _mm256_mul_pd(wl, _mm256_loadu_pd(x0 + t)));
266 a01 = _mm256_add_pd(a01, _mm256_mul_pd(wh, _mm256_loadu_pd(x0 + t + 4)));
267 if constexpr (C == 2)
269 a10 = _mm256_add_pd(a10, _mm256_mul_pd(wl, _mm256_loadu_pd(x1 + t)));
270 a11 = _mm256_add_pd(a11, _mm256_mul_pd(wh, _mm256_loadu_pd(x1 + t + 4)));
273 out[0] = sampleGatherReduceAvx2(a00, a01);
274 if constexpr (C == 2) out[1] = sampleGatherReduceAvx2(a10, a11);
276DSPARK_SIMD_EXACT_AVX2_END
283template <FloatType T>
302 static constexpr double kBeta = 10.06;
323 static const std::vector<double> table = [] {
325 auto i0 = [](
double x) {
326 double sum = 1.0, term = 1.0;
327 for (
int k = 1; k < 64; ++k)
329 term *= (x / (2.0 * k)) * (x / (2.0 * k));
331 if (term < sum * 1e-17)
break;
335 const double norm = i0(
kBeta);
336 for (
size_t j = 0; j + 1 < t.size(); ++j)
340 const double arg = pi<double> *
kCutoff * x;
341 const double sinc = (x == 0.0) ? 1.0 : std::sin(arg) / arg;
343 t[j] =
kCutoff * sinc * i0(
kBeta * std::sqrt(std::max(0.0, 1.0 - r * r))) / norm;
359 static const std::vector<T> rows = [] {
361 std::vector<T> r(
static_cast<size_t>((
kPhases + 1) *
kTaps), T(0));
362 for (
int q = 0; q <=
kPhases; ++q)
363 for (
int t = 0; t <
kTaps; ++t)
367 r[
static_cast<size_t>(q *
kTaps + t)] =
368 (
static_cast<size_t>(u) < h.size()) ?
static_cast<T
>(h[
static_cast<size_t>(u)]) : T(0);
378 for (
auto& a : acc_) a.assign(
static_cast<size_t>(
kAccLength), T(0));
389 pos_ =
static_cast<double>(z.start);
390 scatter_ = ratio > 1.0;
392 justWrapped_ =
false;
399 for (
auto& a : acc_) std::fill(a.begin(), a.end(), T(0));
401 releaseLoop_ =
false;
411 [[nodiscard]]
bool scatters() const noexcept {
return scatter_; }
430 Frame next(
double ratio,
int outChannels, T* weights,
double& a0,
double& a1)
noexcept
432 return scatter_ ? scatterFrame(ratio, outChannels, weights, a0, a1)
433 : gatherFrame(ratio, outChannels, weights, a0, a1);
440 [[nodiscard]]
static double dot(
const T* w,
const T* x,
int n)
noexcept
442 T a[8] = { T(0), T(0), T(0), T(0), T(0), T(0), T(0), T(0) };
444 for (; t + 8 <= n; t += 8)
445 for (
int l = 0; l < 8; ++l)
446 a[l] += w[t + l] * x[t + l];
447 T sum = ((a[0] + a[4]) + (a[1] + a[5])) + ((a[2] + a[6]) + (a[3] + a[7]));
448 for (; t < n; ++t) sum += w[t] * x[t];
449 return static_cast<double>(sum);
454 [[nodiscard]]
static double fetch(
const SampleZoneData<T>& z,
const T* chan,
const T* baked,
455 int64_t j,
bool loopEngaged,
bool wrapped =
false) noexcept
457 if (loopEngaged && j >= z.loopEnd)
458 j = z.loopStart + (j - z.loopEnd) % (z.loopEnd - z.loopStart);
459 else if (loopEngaged && wrapped && j < z.loopStart)
460 j = z.loopEnd - 1 - (z.loopStart - 1 - j) % (z.loopEnd - z.loopStart);
461 if (j < 0 || j >= z.length)
return 0.0;
462 if (loopEngaged && baked !=
nullptr && j >= z.loopEnd - z.xfade && j < z.loopEnd)
463 return static_cast<double>(baked[j - (z.loopEnd - z.xfade)]);
464 return static_cast<double>(chan[j]);
469 static int kernelWeights(T* weights,
double frac,
double fc,
int half)
noexcept
474 const double qf = frac *
kPhases;
475 const int q = std::min(
static_cast<int>(qf),
kPhases - 1);
476 const T g =
static_cast<T
>(qf -
static_cast<double>(q));
477 const T* r0 = rows +
static_cast<size_t>(q) *
kTaps;
478 const T* r1 = r0 +
kTaps;
479 for (
int t = 0; t <
kTaps; ++t)
480 weights[t] = r0[t] + g * (r1[t] - r0[t]);
486 double x = (
static_cast<double>(-half + 1) - frac) * step;
487 const size_t last = table.size() - 1;
488 for (
int t = 0; t < 2 * half; ++t, x += step)
490 const double u = std::abs(x);
491 const size_t iu =
static_cast<size_t>(u);
495 const double f = u -
static_cast<double>(iu);
496 w = table[iu] + f * (table[iu + 1] - table[iu]);
498 weights[t] =
static_cast<T
>(w * fc);
504 static const T* unitRows(
double frac, T& g)
noexcept
506 const double qf = frac *
kPhases;
507 const int q = std::min(
static_cast<int>(qf),
kPhases - 1);
508 g =
static_cast<T
>(qf -
static_cast<double>(q));
514 static void gatherRows(
const T* r0, T g,
const T* x0,
const T* x1, T* out)
noexcept
516#if defined(DSPARK_SIMD_EXACT_AVX2) && !defined(DSPARK_SIMD_EXACT_AVX2_DISPATCHED)
517 sampleGatherAvx2<C>(r0, r0 +
kTaps, g, x0, x1,
kTaps, out);
519 #if defined(DSPARK_SIMD_EXACT_AVX2_DISPATCHED)
522 sampleGatherAvx2<C>(r0, r0 +
kTaps, g, x0, x1,
kTaps, out);
526 sampleGatherNarrow<C, T>(r0, r0 +
kTaps, g, x0, x1,
kTaps, out);
536 Frame gatherFrame(
double ratio,
int nCh, T* weights,
double& a0,
double& a1)
noexcept
538 const SampleZoneData<T>& z = *zone_;
539 const double fc = std::min(1.0, 1.0 / ratio);
540 const int half =
static_cast<int>(std::ceil(
kHalfTaps / fc));
541 const double loopLen =
static_cast<double>(z.loopEnd - z.loopStart);
542 const int zc = z.channels;
543 const int used = (nCh == 1) ? zc : std::min(zc, 2);
549 if (releaseLoop_ && (pos_ + half <
static_cast<double>(z.loopEnd - z.xfade) || justWrapped_))
551 loopEngaged_ =
false;
552 releaseLoop_ =
false;
555 justWrapped_ =
false;
556 if (!loopEngaged_ && pos_ >=
static_cast<double>(z.length))
return Frame::Ended;
558 const double fl = std::floor(pos_);
559 const int64_t ip =
static_cast<int64_t
>(fl);
560 const int taps = (fc >= 1.0) ?
kTaps : 2 * half;
562 const int64_t first = ip - half + 1;
563 const bool direct = first >= 0 && first + taps <= z.length
564 && (!loopEngaged_ || (first + taps <= z.loopEnd - z.xfade
565 && (!wrapped_ || first >= z.loopStart)));
566 double acc[2] = { 0.0, 0.0 };
567 if (direct && fc >= 1.0)
571 const T* rows = unitRows(pos_ - fl, g);
572 for (
int c0 = 0; c0 < used; c0 += 2)
574 const int pair = std::min(2, used - c0);
575 const T* x0 = z.audio.data() +
static_cast<size_t>(c0) *
static_cast<size_t>(z.length)
576 +
static_cast<size_t>(first);
577 T sums[2] = { T(0), T(0) };
579 gatherRows<2>(rows, g, x0, x0 +
static_cast<size_t>(z.length), sums);
581 gatherRows<1>(rows, g, x0,
nullptr, sums);
582 for (
int c = 0; c < pair; ++c)
584 const auto sum =
static_cast<double>(sums[c]);
585 if (nCh == 1) acc[0] += sum / zc;
586 else acc[c0 + c] = sum;
591 advanceGather(ratio, half, loopLen);
594 kernelWeights(weights, pos_ - fl, fc, half);
595 for (
int c = 0; c < used; ++c)
597 const T* chan = z.audio.data() +
static_cast<size_t>(c) *
static_cast<size_t>(z.length);
598 const T* baked = z.baked.empty() ? nullptr
599 : z.baked.data() +
static_cast<size_t>(c) *
static_cast<size_t>(z.xfade);
602 sum = dot(weights, chan + first, taps);
604 for (
int t = 0; t < taps; ++t)
605 sum +=
static_cast<double>(weights[t])
606 * fetch(z, chan, baked, first + t, loopEngaged_, wrapped_);
607 if (nCh == 1) acc[0] += sum / zc;
612 advanceGather(ratio, half, loopLen);
617 void advanceGather(
double ratio,
int half,
double loopLen)
noexcept
619 const SampleZoneData<T>& z = *zone_;
621 if (loopEngaged_ && pos_ >=
static_cast<double>(z.loopEnd))
625 justWrapped_ = z.loopEnd - z.xfade - half <= z.loopStart;
641 Frame scatterFrame(
double ratio,
int nCh, T* weights,
double& a0,
double& a1)
noexcept
643 const SampleZoneData<T>& z = *zone_;
644 const double fc = std::min(1.0, ratio);
645 const int half =
static_cast<int>(std::ceil(
kHalfTaps / fc));
646 const double spacing = 1.0 / ratio;
647 const int zc = z.channels;
648 const int used = (nCh == 1) ? zc : std::min(zc, 2);
649 const int rings = (nCh == 1 || zc == 1) ? 1 : 2;
652 while (!inputDone_ && tNext_ <
static_cast<double>(half))
654 if (releaseLoop_ && (jIn_ < z.loopEnd - z.xfade || jIn_ == z.loopStart))
656 loopEngaged_ =
false;
657 releaseLoop_ =
false;
659 double x[2] = { 0.0, 0.0 };
660 for (
int c = 0; c < used; ++c)
662 const T* chan = z.audio.data() +
static_cast<size_t>(c) *
static_cast<size_t>(z.length);
663 const T* baked = z.baked.empty() ? nullptr
664 : z.baked.data() +
static_cast<size_t>(c) *
static_cast<size_t>(z.xfade);
665 const double sample = fetch(z, chan, baked, jIn_, loopEngaged_);
666 if (rings == 1) x[0] += sample / used;
669 const double fl = std::floor(tNext_);
670 const int taps = kernelWeights(weights, tNext_ - fl, fc, half);
671 const int base = accPos_ +
static_cast<int>(fl) - half + 1;
672 for (
int r = 0; r < rings; ++r)
674 const T xs =
static_cast<T
>(x[r] * spacing);
675 T* acc = acc_[
static_cast<size_t>(r)].data();
676 const T* w = weights;
679 for (
int t = std::max(accPos_ - base, 0); t < taps; ++t)
683 if (loopEngaged_ && jIn_ >= z.loopEnd) jIn_ = z.loopStart;
684 if (!loopEngaged_ && jIn_ >= z.length) { inputDone_ =
true; drainLeft_ = 2 * half; }
688 a0 =
static_cast<double>(acc_[0][
static_cast<size_t>(accPos_)]);
689 a1 = (rings == 2) ?
static_cast<double>(acc_[1][
static_cast<size_t>(accPos_)]) : a0;
692 for (
int r = 0; r < rings; ++r) acc_[static_cast<size_t>(r)][
static_cast<size_t>(accPos_)] = T(0);
698 for (
int r = 0; r < rings; ++r)
700 T* acc = acc_[
static_cast<size_t>(r)].data();
701 std::copy(acc + accPos_, acc +
kAccLength, acc);
702 std::fill(acc + keep, acc +
kAccLength, T(0));
706 if (inputDone_ && --drainLeft_ <= 0)
return Frame::Last;
710 const SampleZoneData<T>* zone_ =
nullptr;
712 bool loopEngaged_ =
false;
713 bool releaseLoop_ =
false;
714 bool wrapped_ =
false;
715 bool justWrapped_ =
false;
719 bool scatter_ =
false;
720 bool inputDone_ =
false;
725 std::array<std::vector<T>, 2> acc_;
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.
One voice's position in a zone and its band-limited read.
static constexpr int kTaps
static constexpr int kAccLength
void release() noexcept
The key is released: a Sustain loop plays on past its end.
double minRate() const noexcept
Lowest rate next() accepts for this reader.
static const std::vector< T > & polyphaseTable()
static constexpr int kMaxHalfTaps
static constexpr double kBeta
static constexpr double kMinScatterRate
Lowest rate of the scatter form, whose kernel widens as the rate falls.
static constexpr int kWeightsLength
Scratch weights a caller provides to next().
void allocate()
Allocates the scatter accumulators (setup thread).
Frame next(double ratio, int outChannels, T *weights, double &a0, double &a1) noexcept
One output frame at ratio recording samples per output sample.
Frame
What one call produced.
@ Ended
The zone ended before this sample: nothing produced.
@ Produced
A frame was produced.
@ Last
A frame was produced and it was the last one.
static constexpr double kMinGatherRate
static constexpr int kPhases
Phases of the unit-rate polyphase table (rows interpolated linearly).
static constexpr double kMaxRate
Highest playback rate; the kernel then spans 8 x 64 taps.
const SampleZoneData< T > * zone() const noexcept
The zone being read (null before start()).
bool scatters() const noexcept
True when this reader scatters (it started above the recording's rate).
void start(const SampleZoneData< T > &z, double ratio) noexcept
Starts reading a zone from its start offset. A reader that starts above the recording's rate (ratio >...
static constexpr int kHalfTaps
Zero crossings on each side of the kernel at unit rate: 64 taps.
static constexpr int kTablePerUnit
Table points per zero crossing (linear interpolation between them).
static const std::vector< double > & kernelTable()
static constexpr double kCutoff
bool buildSampleZone(const SampleZoneSpec< T > &z, SampleZoneData< T > &d)
Validates and copies a zone, clamping its loop and baking the loop crossfade. False (and d unspecifie...
constexpr int kSampleGatherLanes
void sampleZonePanGains(double pan, int channels, double gain, double &left, double &right, double &mono) noexcept
Output gains of a zone at gain: a mono zone pans with constant power (unity at centre),...
void sampleGatherNarrow(const T *r0, const T *r1, T g, const T *x0, const T *x1, int taps, T *out) noexcept
Unit-scale gather of C (1 or 2) channels: the weights are the rows r0 and r1 blended by g,...
T sampleGatherReduce(const T *lane) noexcept
The final reduction of the eight partial sums.
bool isRuntimeDispatchActive() noexcept
Whether the AVX2+FMA kernels are selected now (see setRuntimeDispatch()).
SampleLoopMode
How a zone loops.
@ None
Play once to the end of the recording.
@ Sustain
Loop while the key is held, then play on past the loop end.
One zone, as the caller describes it.
int rootKey
MIDI key that plays it untransposed.
double velocityHigh
Highest velocity it answers, 0..1 (inclusive).
int64_t loopEnd
One past the last sample of the loop.
AudioBufferView< const T > audio
The recording (1 or more channels).
int64_t loopCrossfade
Crossfade length in samples (0 = hard loop).
int64_t startOffset
First sample played.
double pan
-1 left .. +1 right (balance for multichannel).
int64_t loopStart
First sample of the loop.
int keyLow
Lowest key it answers (inclusive).
double tuneCents
Fine tuning added to every note.
double sampleRate
Its sample rate.
double velocityLow
Lowest velocity it answers, 0..1 (inclusive).
int keyHigh
Highest key it answers (inclusive).
One validated zone, its audio copied and its loop crossfade baked.
std::vector< T > audio
Channel-major, length per channel.
std::vector< T > baked
Crossfaded copy of [loopEnd - xfade, loopEnd).