563 values_[
static_cast<size_t>(i)].store(info(i).
defValue, std::memory_order_relaxed);
564 params_[
static_cast<size_t>(i)] = info(i).
defValue;
570 delete pending_.exchange(
nullptr, std::memory_order_acq_rel);
571 delete retired_.exchange(
nullptr, std::memory_order_acq_rel);
597 voices_ = std::vector<Voice>(
static_cast<size_t>(2 * maxVoices_ + 2));
598 for (
auto& v : voices_)
599 for (
auto& u : v.uni) u.reader.allocate();
601 for (
auto& b : mix_) b.assign(
static_cast<size_t>(maxBlock_), T(0));
602 const AudioSpec osSpec { baseRate_, maxBlock_, 2 };
611 snapshotParameters(
true);
612 configureRate(oversamplingFactor());
621 for (
auto& v : voices_) v.active =
false;
623 sustainPedal_ =
false;
634 haveLastPitch_ =
false;
635 for (
int k = 0; k < 2; ++k)
637 freeLfo_[
static_cast<size_t>(k)].anchorCycles = p(lfoParam(k, 6));
638 freeLfo_[
static_cast<size_t>(k)].anchorTime = 0;
640 masterGain_ =
decibelsToGain(
static_cast<double>(p(Param::MasterVolume)), -200.0);
643 activeVoices_.store(0, std::memory_order_relaxed);
647 [[nodiscard]]
int getLatency() const noexcept {
return latency_.load(std::memory_order_relaxed); }
652 return activeVoices_.load(std::memory_order_relaxed);
664 const int i =
static_cast<int>(param);
665 if (i < 0 || i >=
kNumParams || value != value)
return;
668 if (pinfo.
steps > 0) v = std::round(v);
669 values_[
static_cast<size_t>(i)].store(v, std::memory_order_relaxed);
676 if (i < 0)
return false;
684 const int i = std::clamp(
static_cast<int>(param), 0,
kNumParams - 1);
685 return values_[
static_cast<size_t>(i)].load(std::memory_order_relaxed);
691 if (!(bpm >= 1.0) || !(bpm <= 999.0))
return;
692 tempo_.store(
static_cast<float>(bpm), std::memory_order_relaxed);
709 auto built = std::make_shared<std::vector<ZoneData>>();
710 built->reserve(zones.size());
711 for (
const auto& z : zones)
715 built->push_back(std::move(d));
717 controlZones_ = std::move(built);
735 controlZones_.reset();
746 auto bank = std::make_shared<WavetableBank>();
747 if (!bank->loadFrames(frames, frameSize, numFrames))
return false;
748 controlWavetable_ = std::move(bank);
757 void noteOn(
int key, T velocity,
int offset = 0) noexcept
770 void noteOnTuned(
int key, T velocity, T tuningCents,
int offset = 0) noexcept
772 if (!std::isfinite(velocity) || !std::isfinite(tuningCents))
return;
773 if (velocity <= T(0)) {
noteOff(key, T(0), offset);
return; }
774 push({ EventType::NoteOn, std::clamp(key, 0, 127),
775 std::clamp(
static_cast<double>(velocity), 0.0, 1.0), offset,
776 std::clamp(
static_cast<double>(tuningCents), -100.0, 100.0) });
780 void noteOff(
int key, T releaseVelocity = T(0),
int offset = 0) noexcept
782 const double rv = std::isfinite(releaseVelocity) ?
static_cast<double>(releaseVelocity) : 0.0;
783 push({ EventType::NoteOff, std::clamp(key, 0, 127), std::clamp(rv, 0.0, 1.0), offset });
789 if (!std::isfinite(bend))
return;
790 push({ EventType::Bend, 0, std::clamp(
static_cast<double>(bend), -1.0, 1.0), offset });
794 void setModWheel(T value,
int offset = 0) noexcept { pushController(EventType::ModWheel, 0, value, offset); }
797 void setChannelPressure(T value,
int offset = 0) noexcept { pushController(EventType::Pressure, 0, value, offset); }
802 pushController(EventType::PolyPressure, std::clamp(key, 0, 127), value, offset);
808 push({ EventType::Pedal, 0, down ? 1.0 : 0.0, offset });
822 case 2: pushController(EventType::Breath, 0, value, offset);
break;
823 case 11: pushController(EventType::Expression, 0, value, offset);
break;
824 case 64:
if (std::isfinite(value))
setSustainPedal(value >= T(0.5), offset);
break;
832 void allNotesOff(
int offset = 0) noexcept { push({ EventType::AllOff, 0, 0.0, offset }); }
844 const int n = out.getNumSamples();
845 const int nCh = out.getNumChannels();
846 for (
int c = 0; c < nCh; ++c)
847 std::fill_n(out.getChannel(c), n, T(0));
848 if (!prepared_) { eventCount_ = 0;
return; }
852 snapshotParameters(
false);
855 for (
int start = 0; start < n; start += maxBlock_)
857 const int len = std::min(maxBlock_, n - start);
858 renderPiece(out, start, len, e, start + len >= n);
862 retireFadedContent();
864 for (
const auto& v : voices_) count += v.active ? 1 : 0;
865 activeVoices_.store(count, std::memory_order_relaxed);
872 [[nodiscard]] std::vector<uint8_t>
getState()
const
876 w.
write(info(i).
id, values_[
static_cast<size_t>(i)].load(std::memory_order_relaxed));
899 [[nodiscard]]
static constexpr const ParamInfo& info(
int i)
noexcept
907 std::shared_ptr<const std::vector<ZoneData>> zones;
908 std::shared_ptr<const WavetableBank> wavetable;
916 double start = 0.0, step = 0.0, target = 0.0;
917 [[nodiscard]]
double at(
int pos)
const noexcept {
return start + step *
static_cast<double>(pos); }
918 void to(
double next,
double invPeriod)
noexcept
922 step = (next - start) * invPeriod;
924 void snap(
double value)
noexcept { start = target = value; step = 0.0; }
925 [[nodiscard]]
bool live() const noexcept {
return start > 0.0 || target > 0.0; }
930 std::array<Oscillator<T>, 3> osc;
931 std::array<bool, 3> oscOn {};
932 std::array<Ramp, 3> freq;
933 std::array<Ramp, 3> master;
934 std::array<double, 2> wtPhase {};
935 std::array<WavetableBank::Mip, 2> mip {};
936 std::array<double, 4> opPhase {};
937 std::array<Ramp, 4> opFreq;
938 double fb1 = 0.0, fb2 = 0.0;
940 bool readerOn =
false;
942 double gainL = 1.0, gainR = 1.0;
944 std::array<double, 3> spread {};
945 double driftCents = 0.0;
946 AnalogRandom::Generator<double> drift { 1 };
952 kOsc1Level, kOsc2Level, kOsc3Level, kSubLevel, kNoiseLevel, kSampleLevel,
953 kPw1, kPw2, kPw3, kWt1Pos, kWt2Pos, kWt1Level, kWt2Level,
954 kOp1Level, kOp2Level, kOp3Level, kOp4Level, kFeedback,
955 kCutoff, kResonance, kDrive, kPan, kNumSmoothed
962 bool sustained =
false;
963 bool firstTick =
true;
970 Engine engine = Engine::Analog;
974 double velocity = 1.0;
975 double tuningCents = 0.0;
976 double releaseVelocity = 0.0;
977 double polyPressure = 0.0;
979 double velGain = 1.0;
981 double glideFrom = 60.0;
982 double glideLeft = 0.0;
983 double glideTotal = 0.0;
985 const Content* content =
nullptr;
986 const ZoneData* zone =
nullptr;
987 double zoneGainL = 1.0, zoneGainR = 1.0;
989 ADSREnvelope<double> amp;
990 ADSREnvelope<double> env2, env3;
991 std::array<ADSREnvelope<double>, 4> opEnv;
992 std::array<Lfo<double>, 2> lfo;
993 std::array<double, 2> lfoValue {};
994 std::array<double, kNumSmoothed> smooth {};
995 std::array<Ramp, 3> oscLevel;
996 Ramp subLevel, noiseLevel, sampleLevel;
997 std::array<Ramp, 3> pulseWidth;
998 std::array<Ramp, 2> wtPosition, wtLevel;
999 std::array<Ramp, 4> opLevel;
1000 Ramp feedback, g, resonance, svfK, drive, ampGain, panL, panR, subFreq;
1001 std::array<std::array<T, 4>, 2> ladder {};
1002 std::array<detail::TptSvfState<T>, 2> svf {};
1004 AnalogRandom::Generator<double> cutoffDrift { 1 };
1005 std::array<UnisonVoice, kMaxUnison> uni;
1009 static constexpr int kChunk = 128;
1012 Voice* voice =
nullptr;
1015 std::array<double, kChunk> l {}, r {}, gain {}, panL {}, panR {};
1016 std::array<T, kChunk> g {}, q {}, drive {};
1020 struct Event { EventType type;
int key;
double value;
int offset;
double tuningCents = 0.0; };
1024 double anchorCycles = 0.0;
1025 int64_t anchorTime = 0;
1026 double increment = 0.0;
1033 [[nodiscard]]
float p(
Param param)
const noexcept {
return params_[
static_cast<size_t>(
param)]; }
1034 [[nodiscard]]
int ip(
Param param)
const noexcept {
return static_cast<int>(params_[
static_cast<size_t>(
param)]); }
1035 [[nodiscard]]
static Param at(
Param first,
int offset)
noexcept
1037 return static_cast<Param>(
static_cast<int>(first) + offset);
1040 [[nodiscard]]
static Param oscParam(
int k,
int field)
noexcept {
return at(Param::Osc1Wave, 7 * k + field); }
1041 [[nodiscard]]
static Param opParam(
int k,
int field)
noexcept {
return at(Param::Op1Ratio, 11 * k + field); }
1042 [[nodiscard]]
static Param wtParam(
int k,
int field)
noexcept {
return at(Param::Wt1Bank, 6 * k + field); }
1043 [[nodiscard]]
static Param envParam(
int k,
int field)
noexcept {
return at(Param::Env1Attack, 5 * k + field); }
1044 [[nodiscard]]
static Param lfoParam(
int k,
int field)
noexcept {
return at(Param::Lfo1Shape, 8 * k + field); }
1045 [[nodiscard]]
static Param modParam(
int k,
int field)
noexcept {
return at(Param::Mod1Source, 4 * k + field); }
1048 return static_cast<ModDest>(
static_cast<int>(first) + k);
1051 [[nodiscard]]
int oversamplingFactor() const noexcept
1053 const int choice = ip(Param::Oversampling);
1058 void snapshotParameters(
bool force)
noexcept
1060 std::array<float, kNumParams> next {};
1062 next[
static_cast<size_t>(i)] = values_[
static_cast<size_t>(i)].load(std::memory_order_relaxed);
1063 const float tempo = tempo_.load(std::memory_order_relaxed);
1064 const bool tempoChanged = tempo != tempoApplied_;
1066 auto changed = [&](
Param a,
Param b)
noexcept {
1067 if (force)
return true;
1068 for (
int i =
static_cast<int>(a); i <= static_cast<int>(b); ++i)
1069 if (next[
static_cast<size_t>(i)] != params_[
static_cast<size_t>(i)])
return true;
1072 const bool envs = changed(Param::Env1Attack, Param::Env3Curve);
1073 const bool ops = changed(Param::Op1Ratio, Param::Op4Release);
1074 const bool lfos = changed(Param::Lfo1Shape, Param::Lfo2Mode) || tempoChanged;
1075 const bool rate = !force && next[
static_cast<size_t>(Param::Oversampling)]
1076 != params_[
static_cast<size_t>(Param::Oversampling)];
1080 std::array<double, 2> cyclesNow {};
1081 for (
int k = 0; k < 2; ++k) cyclesNow[static_cast<size_t>(k)] = freeCycles(k, timeHi_);
1083 tempoApplied_ = tempo;
1085 if (rate && prepared_) configureRate(oversamplingFactor());
1087 for (
auto& v : voices_) applyEnvelopes(v);
1089 for (
auto& v : voices_) applyOperatorEnvelopes(v);
1092 for (
int k = 0; k < 2; ++k)
1094 auto& f = freeLfo_[
static_cast<size_t>(k)];
1095 f.anchorCycles = cyclesNow[
static_cast<size_t>(k)];
1096 f.anchorTime = timeHi_;
1097 f.increment = lfoRateHz(k) / internalRate_;
1099 for (
auto& v : voices_)
1100 for (int k = 0; k < 2; ++k) applyLfo(v, k);
1108 void configureRate(
int factor)
noexcept
1111 internalRate_ = baseRate_ * factor_;
1113 invPeriod_ = 1.0 /
static_cast<double>(periodHi_);
1124 const int over =
delay % factor_;
1125 const int latency =
delay / factor_ + (over != 0 ? 1 : 0);
1126 shift_ = (over != 0) ? factor_ - over : 0;
1127 latency_.store(latency, std::memory_order_relaxed);
1128 smoothAlpha_ = 1.0 - std::exp(-
static_cast<double>(
kControlPeriod) / (0.010 * baseRate_));
1129 stealFade_ = std::max(1,
static_cast<int>(std::lround(0.003 * internalRate_)));
1130 noiseScale_ = std::sqrt(
static_cast<double>(factor_));
1132 for (
auto& v : voices_)
1135 v.amp.prepare(internalRate_);
1136 v.env2.prepare(controlRate);
1137 v.env3.prepare(controlRate);
1138 for (
auto& e : v.opEnv) e.
prepare(internalRate_);
1139 for (
auto& l : v.lfo) l.
prepare(internalRate_);
1140 v.sub.prepare(internalRate_);
1142 v.cutoffDrift.setRange(-1.0, 1.0);
1143 v.cutoffDrift.setRateHz(1.5);
1144 v.cutoffDrift.setSmoothing(
true, 150.0);
1145 v.cutoffDrift.prepare(controlRate);
1146 for (
auto& u : v.uni)
1148 for (
auto& o : u.osc) o.
prepare(internalRate_);
1150 u.drift.setRange(-1.0, 1.0);
1151 u.drift.setRateHz(2.0);
1152 u.drift.setSmoothing(
true, 150.0);
1153 u.drift.prepare(controlRate);
1156 applyOperatorEnvelopes(v);
1157 for (
int k = 0; k < 2; ++k) applyLfo(v, k);
1161 for (
int k = 0; k < 2; ++k)
1162 freeLfo_[
static_cast<size_t>(k)].increment = lfoRateHz(k) / internalRate_;
1170 void publishContent()
1172 delete retired_.exchange(
nullptr, std::memory_order_acq_rel);
1173 auto* content =
new Content { controlZones_, controlWavetable_ };
1174 delete pending_.exchange(content, std::memory_order_acq_rel);
1177 void adoptPending() noexcept
1179 if (fading_ !=
nullptr)
return;
1180 Content* next = pending_.exchange(
nullptr, std::memory_order_acq_rel);
1181 if (next ==
nullptr)
return;
1186 void retireFadedContent() noexcept
1188 if (fading_ ==
nullptr)
return;
1189 for (
const auto& v : voices_)
1190 if (v.active && v.content == fading_) return;
1191 if (retired_.load(std::memory_order_acquire) !=
nullptr)
return;
1192 retired_.store(fading_, std::memory_order_release);
1200 void push(
const Event& e)
noexcept
1202 if (!prepared_ || eventCount_ >=
kMaxEvents)
return;
1204 int i = eventCount_++;
1205 while (i > 0 && events_[
static_cast<size_t>(i - 1)].offset > e.offset)
1207 events_[
static_cast<size_t>(i)] = events_[
static_cast<size_t>(i - 1)];
1210 events_[
static_cast<size_t>(i)] = e;
1213 void pushController(EventType type,
int key, T value,
int offset)
noexcept
1215 if (!std::isfinite(value))
return;
1216 push({ type, key, std::clamp(
static_cast<double>(value), 0.0, 1.0), offset });
1219 void apply(
const Event& e)
noexcept
1223 case EventType::NoteOn: noteOnNow(e.key, e.value, e.tuningCents);
break;
1224 case EventType::NoteOff: noteOffNow(e.key, e.value);
break;
1225 case EventType::Bend: bend_ = e.value;
break;
1226 case EventType::ModWheel: modWheel_ = e.value;
break;
1227 case EventType::Pressure: pressure_ = e.value;
break;
1228 case EventType::Expression: expression_ = e.value;
break;
1229 case EventType::Breath: breath_ = e.value;
break;
1230 case EventType::PolyPressure:
1231 for (
auto& v : voices_)
1232 if (v.active && v.key == e.key && v.stealLeft < 0) v.polyPressure = e.value;
1234 case EventType::Pedal:
1235 sustainPedal_ = e.value > 0.5;
1237 for (
auto& v : voices_)
1238 if (v.active && v.sustained && !v.held) release(v);
1240 case EventType::AllOff:
1241 sustainPedal_ =
false;
1243 for (
auto& v : voices_)
1244 if (v.active && v.stealLeft < 0) release(v);
1249 [[nodiscard]]
bool monophonic() const noexcept
1251 return static_cast<VoiceMode>(ip(Param::VoiceMode)) != VoiceMode::Poly;
1254 void noteOnNow(
int key,
double velocity,
double tuningCents)
noexcept
1256 const bool anyHeldBefore = heldCount_ > 0;
1258 heldTuning_[
static_cast<size_t>(key)] = tuningCents;
1261 for (
auto& v : voices_)
1262 if (v.active && v.stealLeft < 0)
1264 const bool legato = anyHeldBefore && v.held;
1265 const bool retrigger = !(legato &&
static_cast<VoiceMode>(ip(Param::VoiceMode)) == VoiceMode::Legato);
1266 if (moveRestartsSample(v, key, velocity, retrigger))
1268 v.stealLeft = stealFade_;
1271 moveMonoVoice(v, key, velocity, tuningCents, retrigger, legato);
1278 for (
auto& v : voices_)
1279 if (v.active && v.key == key && v.stealLeft < 0 && (v.held || v.sustained))
1282 if (Voice* v = freeVoice()) startVoice(*v, key, velocity, tuningCents, anyHeldBefore);
1285 void noteOffNow(
int key,
double releaseVelocity)
noexcept
1288 for (
auto& v : voices_)
1290 if (!v.active || !v.held || v.key != key || v.stealLeft >= 0)
continue;
1291 if (monophonic() && heldCount_ > 0)
1294 const int nextKey = held_[
static_cast<size_t>(heldCount_ - 1)];
1295 const double nextTuning = heldTuning_[
static_cast<size_t>(nextKey)];
1296 if (moveRestartsSample(v, nextKey, v.velocity,
false))
1298 v.stealLeft = stealFade_;
1299 if (Voice* next = freeVoice()) startVoice(*next, nextKey, v.velocity, nextTuning,
true);
1302 moveMonoVoice(v, nextKey, v.velocity, nextTuning,
false,
true);
1305 v.releaseVelocity = releaseVelocity;
1306 if (sustainPedal_) { v.held =
false; v.sustained =
true; }
1312 [[nodiscard]]
const ZoneData* zoneFor(
int key,
double velocity)
const noexcept
1314 if (active_ !=
nullptr && active_->zones !=
nullptr)
1315 for (
const auto& z : *active_->zones)
1316 if (key >= z.keyLow && key <= z.keyHigh && velocity >= z.velLow && velocity <= z.velHigh)
1322 [[nodiscard]]
bool sampleSourceInUse() const noexcept
1324 if (p(Param::SampleLevel) > 0.0f)
return true;
1326 if (
static_cast<ModDest>(ip(modParam(s, 2))) == ModDest::SampleLevel)
return true;
1333 [[nodiscard]]
bool moveRestartsSample(
const Voice& v,
int key,
double velocity,
bool retrigger)
const noexcept
1335 if (!sampleSourceInUse())
return false;
1336 const ZoneData* next = zoneFor(key, velocity);
1337 return next != v.zone || (retrigger && next !=
nullptr);
1340 void pushHeld(
int key)
noexcept
1343 if (heldCount_ < 128) held_[
static_cast<size_t>(heldCount_++)] = key;
1346 void removeHeld(
int key)
noexcept
1349 for (
int i = 0; i < heldCount_; ++i)
1350 if (held_[
static_cast<size_t>(i)] != key) held_[
static_cast<size_t>(w++)] = held_[
static_cast<size_t>(i)];
1354 void release(Voice& v)
noexcept
1357 v.sustained =
false;
1361 for (
auto& e : v.opEnv) e.
noteOff();
1362 for (
int u = 0; u < v.unison; ++u) v.uni[
static_cast<size_t>(u)].reader.release();
1366 void moveMonoVoice(Voice& v,
int key,
double velocity,
double tuningCents,
bool retrigger,
bool legato)
noexcept
1368 const double glideMs =
static_cast<double>(p(Param::Glide));
1369 const bool glide = glideMs > 0.0
1370 && (
static_cast<GlideMode>(ip(Param::GlideMode)) == GlideMode::Always || legato);
1371 const double tunedPitch =
static_cast<double>(key) + tuningCents / 100.0;
1372 v.glideFrom = glide ? v.pitch : tunedPitch;
1373 v.glideTotal = glide ? glideMs * 0.001 * internalRate_ : 0.0;
1374 v.glideLeft = v.glideTotal;
1376 v.tuningCents = tuningCents;
1378 v.sustained =
false;
1379 lastPitch_ = tunedPitch;
1380 haveLastPitch_ =
true;
1381 if (!retrigger)
return;
1382 v.velocity = velocity;
1383 v.releaseVelocity = 0.0;
1384 v.velGain = velocityGain(velocity);
1388 for (
auto& e : v.opEnv) e.
noteOn();
1389 for (
int k = 0; k < 2; ++k)
1390 if (
static_cast<LfoMode>(ip(lfoParam(k, 7))) == LfoMode::Retrigger)
1391 v.lfo[
static_cast<size_t>(k)].
reset();
1394 [[nodiscard]]
double velocityGain(
double velocity)
const noexcept
1396 return std::pow(10.0,
static_cast<double>(p(Param::AmpVelocity)) * (velocity - 1.0) / 20.0);
1401 Voice* freeVoice() noexcept
1403 const int polyphony = monophonic() ? 1 : std::min(ip(Param::Polyphony), maxVoices_);
1405 Voice* idle =
nullptr;
1406 for (
auto& v : voices_)
1408 if (!v.active) {
if (idle ==
nullptr) idle = &v; }
1409 else if (v.stealLeft < 0) ++sounding;
1411 if (sounding < polyphony && idle !=
nullptr)
return idle;
1414 Voice* victim =
nullptr;
1415 for (
auto& v : voices_)
1417 if (!v.active || v.stealLeft >= 0)
continue;
1418 if (victim ==
nullptr) { victim = &v;
continue; }
1419 const bool vr = !v.held && !v.sustained, cr = !victim->held && !victim->sustained;
1420 if (vr != cr) {
if (vr) victim = &v;
continue; }
1421 const double va = v.amp.getCurrentValue(), ca = victim->amp.getCurrentValue();
1422 if (va < ca - 1e-9 || (std::abs(va - ca) <= 1e-9 && v.age < victim->age)) victim = &v;
1424 if (victim !=
nullptr) victim->stealLeft = stealFade_;
1425 if (idle !=
nullptr)
return idle;
1427 Voice* oldest =
nullptr;
1428 for (
auto& v : voices_)
1429 if (v.active && v.stealLeft >= 0 && (oldest == nullptr || v.age < oldest->age)) oldest = &v;
1430 if (oldest !=
nullptr) oldest->active =
false;
1438 [[nodiscard]]
static uint64_t mix64(uint64_t x)
noexcept
1440 x += 0x9E3779B97F4A7C15ull;
1441 x = (x ^ (x >> 30)) * 0xBF58476D1CE4E5B9ull;
1442 x = (x ^ (x >> 27)) * 0x94D049BB133111EBull;
1443 return x ^ (x >> 31);
1447 [[nodiscard]]
static double voiceRandom(uint64_t seed,
int stream)
noexcept
1452 void startVoice(Voice& v,
int key,
double velocity,
double tuningCents,
bool anyHeldBefore)
noexcept
1456 v.sustained =
false;
1460 v.tuningCents = tuningCents;
1461 v.velocity = velocity;
1462 v.releaseVelocity = 0.0;
1463 v.polyPressure = 0.0;
1464 v.velGain = velocityGain(velocity);
1466 v.seed = mix64(
static_cast<uint64_t
>(ip(Param::Seed)) * 0x100000001B3ull + noteCounter_++);
1467 v.random = voiceRandom(v.seed, 0);
1468 v.engine =
static_cast<Engine>(ip(Param::Engine));
1469 v.unison = std::clamp(ip(Param::Unison), 1,
kMaxUnison);
1470 v.content = active_;
1472 v.noise =
static_cast<uint32_t
>(mix64(v.seed ^ 0x6E6F697365ull)) | 1u;
1475 const double glideMs =
static_cast<double>(p(Param::Glide));
1476 const bool glide = glideMs > 0.0 && haveLastPitch_
1477 && (
static_cast<GlideMode>(ip(Param::GlideMode)) == GlideMode::Always || anyHeldBefore);
1478 const double tunedPitch =
static_cast<double>(key) + tuningCents / 100.0;
1479 v.glideFrom = glide ? lastPitch_ : tunedPitch;
1480 v.glideTotal = glide ? glideMs * 0.001 * internalRate_ : 0.0;
1481 v.glideLeft = v.glideTotal;
1482 v.pitch = v.glideFrom;
1483 lastPitch_ = tunedPitch;
1484 haveLastPitch_ =
true;
1487 v.zone = zoneFor(key, velocity);
1488 if (v.zone !=
nullptr)
1492 v.zoneGainL, v.zoneGainR, mono);
1497 const int U = v.unison;
1498 const double spread =
static_cast<double>(p(Param::UnisonSpread));
1499 const double detuneCents =
static_cast<double>(p(Param::UnisonDetune));
1500 const double drift =
static_cast<double>(p(Param::Drift));
1501 const double norm = 1.0 / std::sqrt(
static_cast<double>(U));
1504 v.stereo = (U > 1 && spread > 0.0)
1505 || (v.zone !=
nullptr && (v.zone->channels > 1 || v.zone->pan != 0.0));
1506 for (
int u = 0; u < U; ++u)
1508 auto& uv = v.uni[
static_cast<size_t>(u)];
1509 const double x = (U > 1) ? 2.0 *
static_cast<double>(u) /
static_cast<double>(U - 1) - 1.0 : 0.0;
1510 uv.detune = std::exp2(0.5 * x * detuneCents / 1200.0);
1513 uv.gainL = norm * std::cos(0.25 * pi<double> * (1.0 + x * spread)) * sqrt2<double>;
1514 uv.gainR = norm * std::cos(0.25 * pi<double> * (1.0 - x * spread)) * sqrt2<double>;
1515 for (
int k = 0; k < 3; ++k)
1516 uv.spread[
static_cast<size_t>(k)] =
1517 std::exp2(drift * 3.0 * voiceRandom(v.seed, 10 + 3 * u + k) / 1200.0);
1518 uv.driftCents = 0.0;
1519 uv.drift.reseed(mix64(v.seed + 101u +
static_cast<uint64_t
>(u)) | 1u);
1520 uv.fb1 = uv.fb2 = 0.0;
1521 uv.readerOn =
false;
1524 v.cutoffDrift.reseed(mix64(v.seed + 77u) | 1u);
1528 applyOperatorEnvelopes(v);
1535 for (
auto& e : v.opEnv) { e.reset(); e.noteOn(); }
1536 for (
int k = 0; k < 2; ++k)
1539 auto& l = v.lfo[
static_cast<size_t>(k)];
1540 l.setSeed(mix64(v.seed + 200u +
static_cast<uint64_t
>(k)));
1542 v.lfoValue[
static_cast<size_t>(k)] = 0.0;
1550 const bool randomPhase =
static_cast<PhaseMode>(ip(Param::PhaseMode)) == PhaseMode::Random;
1551 for (
int u = 0; u < U; ++u)
1553 auto& uv = v.uni[
static_cast<size_t>(u)];
1554 for (
int k = 0; k < 3; ++k)
1556 const double ph = randomPhase ? 0.5 + 0.5 * voiceRandom(v.seed, 40 + 3 * u + k) : 0.0;
1557 uv.osc[
static_cast<size_t>(k)].setPhase(
static_cast<T
>(ph));
1559 for (
int k = 0; k < 2; ++k)
1560 uv.wtPhase[
static_cast<size_t>(k)] = randomPhase ? 0.5 + 0.5 * voiceRandom(v.seed, 70 + 2 * u + k) : 0.0;
1561 for (
int k = 0; k < 4; ++k)
1562 uv.opPhase[
static_cast<size_t>(k)] = randomPhase ? 0.5 + 0.5 * voiceRandom(v.seed, 90 + 4 * u + k) : 0.0;
1563 if (v.zone !=
nullptr)
1565 uv.reader.start(*v.zone, uv.sampleRatio.target);
1570 v.tickLeft = periodHi_;
1574 void applyEnvelopes(Voice& v)
noexcept
1576 auto set = [&](ADSREnvelope<double>& e,
int k)
noexcept {
1577 e.setParameters(p(envParam(k, 0)), p(envParam(k, 1)), p(envParam(k, 2)), p(envParam(k, 3)));
1578 e.setCurvature(p(envParam(k, 4)));
1585 void applyOperatorEnvelopes(Voice& v)
noexcept
1587 for (
int k = 0; k < 4; ++k)
1588 v.opEnv[
static_cast<size_t>(k)].setParameters(p(opParam(k, 7)), p(opParam(k, 8)),
1589 p(opParam(k, 9)), p(opParam(k, 10)));
1592 [[nodiscard]]
double lfoRateHz(
int k)
const noexcept
1594 if (ip(lfoParam(k, 2)) != 0)
1599 return static_cast<double>(p(lfoParam(k, 1)));
1602 void applyLfo(Voice& v,
int k)
noexcept
1604 auto& l = v.lfo[
static_cast<size_t>(k)];
1606 l.setRateHz(
static_cast<double>(p(lfoParam(k, 1))));
1607 l.setTempo(
static_cast<double>(tempoApplied_));
1609 l.setTempoSync(ip(lfoParam(k, 2)) != 0);
1610 l.setDelayMs(
static_cast<double>(p(lfoParam(k, 4))));
1611 l.setFadeInMs(
static_cast<double>(p(lfoParam(k, 5))));
1612 l.setStartPhase(
static_cast<double>(p(lfoParam(k, 6))));
1615 [[nodiscard]]
double freeCycles(
int k, int64_t t)
const noexcept
1617 const auto& f = freeLfo_[
static_cast<size_t>(k)];
1618 return f.anchorCycles + f.increment *
static_cast<double>(t - f.anchorTime);
1625 [[nodiscard]]
static double noteHz(
double semitones)
noexcept
1627 return 440.0 * std::exp2((semitones - 69.0) / 12.0);
1630 void controlTick(Voice& v)
noexcept
1632 const bool first = v.firstTick;
1633 v.firstTick =
false;
1635 const int64_t now = timeHi_ + offsetHi_;
1638 const double keyPitch =
static_cast<double>(v.key);
1639 const double tunedPitch = keyPitch + v.tuningCents / 100.0;
1640 if (v.glideLeft > 0.0)
1642 v.pitch = tunedPitch + (v.glideFrom - tunedPitch) * (v.glideLeft / std::max(v.glideTotal, 1.0));
1643 v.glideLeft = std::max(0.0, v.glideLeft -
static_cast<double>(periodHi_));
1647 v.pitch = tunedPitch;
1651 std::array<double, synthesizer::kNumModSources> src {};
1652 auto source = [&](
ModSource s)
noexcept ->
double& {
return src[
static_cast<size_t>(s)]; };
1653 source(ModSource::Velocity) = v.velocity;
1654 source(ModSource::ReleaseVelocity) = v.releaseVelocity;
1655 source(ModSource::Key) = (keyPitch - 60.0) / 60.0;
1656 source(ModSource::ModWheel) = modWheel_;
1657 source(ModSource::Pressure) = std::max(pressure_, v.polyPressure);
1658 source(ModSource::PitchBend) = bend_;
1659 source(ModSource::Expression) = expression_;
1660 source(ModSource::Breath) = breath_;
1661 source(ModSource::Env1) = v.amp.getCurrentValue();
1662 source(ModSource::Env2) = v.env2.getNextValue();
1663 source(ModSource::Env3) = v.env3.getNextValue();
1664 source(ModSource::Random) = v.random;
1665 source(ModSource::Lfo1) = v.lfoValue[0];
1666 source(ModSource::Lfo2) = v.lfoValue[1];
1671 std::array<double, synthesizer::kNumModDests> dst {};
1672 auto runMatrix = [&](
bool rateOnly)
noexcept {
1675 const auto d =
static_cast<ModDest>(ip(modParam(s, 2)));
1676 const auto a =
static_cast<ModSource>(ip(modParam(s, 0)));
1677 const double amount =
static_cast<double>(p(modParam(s, 3)));
1678 if (d == ModDest::None || a == ModSource::None || amount == 0.0)
continue;
1679 const bool isRate = d == ModDest::Lfo1Rate || d == ModDest::Lfo2Rate;
1680 if (isRate != rateOnly)
continue;
1681 const auto via =
static_cast<ModSource>(ip(modParam(s, 1)));
1682 const double scale = (via == ModSource::None) ? 1.0 : src[static_cast<size_t>(via)];
1683 dst[
static_cast<size_t>(d)] += src[
static_cast<size_t>(a)] * scale * amount;
1686 auto mod = [&](
ModDest d)
noexcept {
return dst[
static_cast<size_t>(d)]; };
1688 for (
int k = 0; k < 2; ++k)
1690 auto& l = v.lfo[
static_cast<size_t>(k)];
1692 if (
static_cast<LfoMode>(ip(lfoParam(k, 7))) == LfoMode::Retrigger)
1694 value = l.advanceScaled(periodHi_, std::exp2(mod(k == 0 ? ModDest::Lfo1Rate :
ModDest::
Lfo2Rate)));
1699 const uint64_t seed = mix64(
static_cast<uint64_t
>(ip(Param::Seed)) + 300u +
static_cast<uint64_t
>(k));
1703 v.lfoValue[
static_cast<size_t>(k)] = value;
1708 std::array<double, kNumSmoothed> base {};
1709 for (
int k = 0; k < 3; ++k)
1711 base[
static_cast<size_t>(kOsc1Level + k)] = p(oscParam(k, 1));
1712 base[
static_cast<size_t>(kPw1 + k)] = p(oscParam(k, 5));
1714 base[kSubLevel] = p(Param::SubLevel);
1715 base[kNoiseLevel] = p(Param::NoiseLevel);
1716 base[kSampleLevel] = p(Param::SampleLevel);
1717 base[kWt1Pos] = p(wtParam(0, 1));
1718 base[kWt2Pos] = p(wtParam(1, 1));
1719 base[kWt1Level] = p(wtParam(0, 2));
1720 base[kWt2Level] = p(wtParam(1, 2));
1721 for (
int k = 0; k < 4; ++k) base[static_cast<size_t>(kOp1Level + k)] = p(opParam(k, 4));
1722 base[kFeedback] = p(Param::FmFeedback);
1723 base[kCutoff] = std::log2(
static_cast<double>(p(Param::FilterCutoff)));
1724 base[kResonance] = p(Param::FilterResonance);
1725 base[kDrive] = p(Param::FilterDrive);
1726 base[kPan] = p(Param::AmpPan);
1727 for (
int i = 0; i < kNumSmoothed; ++i)
1729 double& s = v.smooth[
static_cast<size_t>(i)];
1730 s = first ? base[
static_cast<size_t>(i)] : s + (base[static_cast<size_t>(i)] - s) * smoothAlpha_;
1732 auto sm = [&](
int i)
noexcept {
return v.smooth[
static_cast<size_t>(i)]; };
1733 auto setRamp = [&](Ramp& r,
double value)
noexcept {
1734 if (first) r.snap(value);
1735 else r.to(value, invPeriod_);
1737 auto unit = [](
double x)
noexcept {
return std::clamp(x, 0.0, 1.0); };
1740 const double bendSt = bend_ *
static_cast<double>(p(Param::BendRange));
1741 const double notePitch = v.pitch + bendSt +
static_cast<double>(p(Param::MasterTune)) / 100.0
1742 + mod(ModDest::Pitch);
1743 const double baseHz = noteHz(notePitch);
1744 const double limitHz = 0.499 * internalRate_;
1745 auto clampHz = [&](
double hz)
noexcept {
return std::clamp(hz, 0.0, limitHz); };
1748 std::array<double, 3> oscRatio {};
1749 if (v.engine == Engine::Analog)
1750 for (
int k = 0; k < 3; ++k)
1751 oscRatio[
static_cast<size_t>(k)] = std::exp2((12.0 * p(oscParam(k, 2)) + p(oscParam(k, 3))
1752 + p(oscParam(k, 4)) / 100.0 + mod(dest(ModDest::Osc1Pitch, k))) / 12.0);
1753 std::array<double, 2> wtRatio {};
1754 if (v.engine == Engine::Wavetable)
1755 for (
int k = 0; k < 2; ++k)
1756 wtRatio[
static_cast<size_t>(k)] = std::exp2((12.0 * p(wtParam(k, 3)) + p(wtParam(k, 4))
1757 + p(wtParam(k, 5)) / 100.0 + mod(dest(ModDest::Osc1Pitch, k))) / 12.0);
1758 std::array<double, 4> opHz {};
1759 std::array<bool, 4> opFixed {};
1760 if (v.engine == Engine::Fm)
1761 for (
int k = 0; k < 4; ++k)
1763 opFixed[
static_cast<size_t>(k)] = ip(opParam(k, 2)) != 0;
1764 opHz[
static_cast<size_t>(k)] = opFixed[
static_cast<size_t>(k)]
1765 ?
static_cast<double>(p(opParam(k, 3)))
1766 : static_cast<double>(p(opParam(k, 0))) * std::exp2(static_cast<double>(p(opParam(k, 1))) / 1200.0);
1769 const double driftAmount =
static_cast<double>(p(Param::Drift));
1770 constexpr double centRatio = std::numbers::ln2 / 1200.0;
1771 for (
int u = 0; u < v.unison; ++u)
1773 auto& uv = v.uni[
static_cast<size_t>(u)];
1774 uv.driftCents = driftAmount > 0.0 ? 6.0 * driftAmount * uv.drift.getNextSample() : 0.0;
1775 const double unisonHz = baseHz * uv.detune * (1.0 + uv.driftCents * centRatio);
1778 case Engine::Analog:
1779 for (
int k = 0; k < 3; ++k)
1781 const double masterHz = unisonHz * uv.spread[
static_cast<size_t>(k)];
1782 setRamp(uv.freq[
static_cast<size_t>(k)], clampHz(masterHz * oscRatio[
static_cast<size_t>(k)]));
1783 setRamp(uv.master[
static_cast<size_t>(k)], clampHz(masterHz));
1786 case Engine::Wavetable:
1787 for (
int k = 0; k < 2; ++k)
1788 setRamp(uv.freq[
static_cast<size_t>(k)],
1789 clampHz(unisonHz * uv.spread[
static_cast<size_t>(k)] * wtRatio[
static_cast<size_t>(k)]));
1792 for (
int k = 0; k < 4; ++k)
1793 setRamp(uv.opFreq[
static_cast<size_t>(k)],
1794 clampHz(opFixed[
static_cast<size_t>(k)] ? opHz[
static_cast<size_t>(k)]
1795 : unisonHz * opHz[static_cast<size_t>(k)]));
1798 if (v.zone !=
nullptr)
1800 const auto& z = *v.zone;
1801 const double offset = 12.0 * p(Param::SampleOctave) + p(Param::SampleSemitone)
1802 + p(Param::SampleFine) / 100.0;
1803 const double played = (ip(Param::SampleKeyTrack) != 0)
1804 ? notePitch : static_cast<double>(z.rootKey) + bendSt + mod(
ModDest::
Pitch);
1805 const double st = played + offset -
static_cast<double>(z.rootKey) + z.tuneCents / 100.0;
1806 const double ratio = z.sampleRate / internalRate_ * std::exp2(st / 12.0) * uv.detune
1807 * (1.0 + uv.driftCents * centRatio);
1808 const bool scatters = first ? ratio > 1.0 : uv.reader.scatters();
1813 setRamp(v.subFreq, clampHz(baseHz * (ip(Param::SubOctave) == 1 ? 0.25 : 0.5)));
1816 for (
int k = 0; k < 3; ++k)
1818 setRamp(v.oscLevel[
static_cast<size_t>(k)], unit(sm(kOsc1Level + k) + mod(dest(ModDest::Osc1Level, k))));
1819 setRamp(v.pulseWidth[
static_cast<size_t>(k)], std::clamp(sm(kPw1 + k) + mod(ModDest::PulseWidth), 0.01, 0.99));
1821 setRamp(v.subLevel, unit(sm(kSubLevel) + mod(ModDest::SubLevel)));
1822 setRamp(v.noiseLevel, unit(sm(kNoiseLevel) + mod(ModDest::NoiseLevel)));
1823 setRamp(v.sampleLevel, unit(sm(kSampleLevel) + mod(ModDest::SampleLevel)));
1824 for (
int k = 0; k < 2; ++k)
1826 setRamp(v.wtPosition[
static_cast<size_t>(k)],
1827 unit(sm(kWt1Pos + k) + mod(ModDest::WtPosition) + mod(dest(ModDest::Wt1Position, k))));
1828 setRamp(v.wtLevel[
static_cast<size_t>(k)], unit(sm(kWt1Level + k) + mod(dest(ModDest::Osc1Level, k))));
1830 const double keyOctaves = (keyPitch - 60.0) / 12.0;
1831 if (v.engine == Engine::Fm)
1832 for (
int k = 0; k < 4; ++k)
1834 const double velSens =
static_cast<double>(p(opParam(k, 5)));
1835 const double keyDb = 6.0 *
static_cast<double>(p(opParam(k, 6))) * keyOctaves;
1836 const double level = unit(sm(kOp1Level + k) + mod(dest(ModDest::Op1Level, k)))
1837 * (1.0 - velSens * (1.0 - v.velocity)) * std::pow(10.0, keyDb / 20.0);
1838 setRamp(v.opLevel[
static_cast<size_t>(k)], level);
1840 setRamp(v.feedback, unit(sm(kFeedback) + mod(ModDest::FmFeedback)));
1843 if (v.engine == Engine::Wavetable)
1844 for (
int u = 0; u < v.unison; ++u)
1845 for (
int k = 0; k < 2; ++k)
1847 auto& uv = v.uni[
static_cast<size_t>(u)];
1848 const auto& r = uv.freq[
static_cast<size_t>(k)];
1849 uv.mip[
static_cast<size_t>(k)] = bankFor(v, k).
selectMip(std::max(r.start, r.target), internalRate_);
1853 const double cutDrift = driftAmount > 0.0 ? 0.15 * driftAmount * v.cutoffDrift.getNextSample() : 0.0;
1854 const double envScale = 1.0 -
static_cast<double>(p(Param::FilterVelocity)) * (1.0 - v.velocity);
1855 const double octaves = sm(kCutoff)
1856 +
static_cast<double>(p(Param::FilterKeyTrack)) * keyOctaves
1857 +
static_cast<double>(p(Param::FilterEnvAmount)) * envScale * source(ModSource::Env2)
1858 + mod(ModDest::Cutoff) + cutDrift;
1859 const auto filterType =
static_cast<FilterType>(ip(Param::FilterType));
1860 if (filterType != FilterType::Off || first)
1862 const double cutoff = std::clamp(std::exp2(octaves), 10.0, std::min(0.49 * internalRate_, 40000.0));
1863 setRamp(v.g, std::tan(pi<double> * cutoff / internalRate_));
1865 const double resonance = unit(sm(kResonance) + mod(ModDest::Resonance));
1866 setRamp(v.resonance, resonance);
1867 if (filterType >= FilterType::SvfLp || first)
1868 setRamp(v.svfK, 2.0 / std::pow(100.0, resonance));
1869 setRamp(v.drive, std::max(sm(kDrive), 1.01));
1872 setRamp(v.ampGain, v.velGain * std::max(0.0, 1.0 + mod(ModDest::Amp)) * expression_);
1873 const double pan = std::clamp(sm(kPan) + mod(ModDest::Pan), -1.0, 1.0);
1876 setRamp(v.panL, std::min(1.0, 1.0 - pan));
1877 setRamp(v.panR, std::min(1.0, 1.0 + pan));
1882 setRamp(v.panL, std::cos(0.25 * pi<double> * (1.0 + pan)) * sqrt2<double>);
1883 setRamp(v.panR, std::cos(0.25 * pi<double> * (1.0 - pan)) * sqrt2<double>);
1887 if (v.engine == Engine::Analog)
1888 for (
int u = 0; u < v.unison; ++u)
1889 for (
int k = 0; k < 3; ++k)
1891 auto& uv = v.uni[
static_cast<size_t>(u)];
1892 auto& o = uv.osc[
static_cast<size_t>(k)];
1893 const bool on = v.oscLevel[
static_cast<size_t>(k)].live();
1894 o.setWaveform(waveOf(
static_cast<OscWave>(ip(oscParam(k, 0)))));
1895 o.setPulseWidth(
static_cast<T
>(v.pulseWidth[
static_cast<size_t>(k)].start));
1896 if (ip(oscParam(k, 6)) != 0)
1898 const double m = uv.master[
static_cast<size_t>(k)].start;
1899 o.setFrequency(
static_cast<T
>(m));
1900 o.setSyncRatio(
static_cast<T
>(m > 0.0 ? uv.freq[
static_cast<size_t>(k)].start / m : 0.0));
1904 o.setSyncRatio(T(0));
1905 o.setFrequency(
static_cast<T
>(uv.freq[
static_cast<size_t>(k)].start));
1907 if (on && !uv.oscOn[
static_cast<size_t>(k)] && !first)
1908 o.setPhase(o.getPhase());
1909 uv.oscOn[
static_cast<size_t>(k)] = on;
1911 v.sub.setWaveform(subWaveOf(
static_cast<SubWave>(ip(Param::SubWave))));
1912 v.sub.setFrequency(
static_cast<T
>(v.subFreq.start));
1920 case OscWave::Sine:
return W::Sine;
1921 case OscWave::Triangle:
return W::Triangle;
1922 case OscWave::Saw:
return W::Saw;
1923 case OscWave::Pulse:
return W::Square;
1933 case SubWave::Square:
return W::Square;
1934 case SubWave::Triangle:
return W::Triangle;
1935 case SubWave::Sine:
return W::Sine;
1940 [[nodiscard]]
const WavetableBank& bankFor(
const Voice& v,
int k)
const noexcept
1942 const int b = ip(wtParam(k, 0));
1945 if (v.content !=
nullptr && v.content->wavetable !=
nullptr)
return *v.content->wavetable;
1955 void renderPiece(AudioBufferView<T> out,
int start,
int len,
int& e,
bool lastPiece)
noexcept
1957 const int lenHi = len * factor_;
1958 T* hiL = mix_[0].data();
1959 T* hiR = mix_[1].data();
1963 hiL = hi.getChannel(0);
1964 hiR = hi.getChannel(1);
1966 std::fill_n(hiL, lenHi, T(0));
1967 std::fill_n(hiR, lenHi, T(0));
1970 while (e < eventCount_)
1972 const Event& ev = events_[
static_cast<size_t>(e)];
1973 const int offset = std::max(ev.offset, 0);
1974 if (!lastPiece && offset >= start + len)
break;
1975 const int local = std::clamp(offset - start, 0, len);
1976 const int atHi = (local >= len) ? lenHi : local * factor_ + shift_;
1977 if (atHi > cursor) { renderVoices(hiL, hiR, cursor, atHi); cursor = atHi; }
1982 if (cursor < lenHi) renderVoices(hiL, hiR, cursor, lenHi);
1986 T* baseL = mix_[0].data();
1987 T* baseR = mix_[1].data();
1990 T* ch[2] = { baseL, baseR };
1991 const AudioBufferView<T> base(ch, 2, len);
1996 const double targetGain =
decibelsToGain(
static_cast<double>(p(Param::MasterVolume)), -200.0);
1997 const double a = 1.0 - std::exp(-1.0 / (0.010 * baseRate_));
1998 const int nCh = out.getNumChannels();
1999 T* outL = nCh > 0 ? out.getChannel(0) :
nullptr;
2000 T* outR = nCh > 1 ? out.getChannel(1) :
nullptr;
2001 for (
int i = 0; i < len; ++i)
2003 masterGain_ += (targetGain - masterGain_) * a;
2004 const auto g =
static_cast<T
>(masterGain_);
2005 if (outR !=
nullptr)
2007 outL[start + i] = baseL[i] * g;
2008 outR[start + i] = baseR[i] * g;
2010 else if (outL !=
nullptr)
2012 outL[start + i] = T(0.5) * (baseL[i] + baseR[i]) * g;
2027 void renderVoices(T* hiL, T* hiR,
int from,
int to)
noexcept
2029 const auto type =
static_cast<FilterType>(ip(Param::FilterType));
2030 if (type == FilterType::Off)
2032 for (
auto& v : voices_)
2033 if (v.active) gather(v, lanes_[0], from, to, type, hiL, hiR);
2036 for (
int c0 = from; c0 < to; c0 += kChunk)
2038 const int c1 = std::min(to, c0 + kChunk);
2039 bool pending =
false;
2040 for (
auto& v : voices_)
2042 if (!v.active)
continue;
2043 gather(v, lanes_[pending ? 1 : 0], c0, c1, type, hiL, hiR);
2044 if (pending) mixLanes(type, hiL, hiR,
true);
2047 if (pending) mixLanes(type, hiL, hiR,
false);
2054 void gather(Voice& v, Lane& lane,
int from,
int to,
FilterType type, T* outL, T* outR)
noexcept
2056 const bool filtered = type != FilterType::Off;
2057 const bool ladder = type == FilterType::LadderLp24 || type == FilterType::LadderLp12
2058 || type == FilterType::LadderBp12 || type == FilterType::LadderHp24;
2064 if (v.tickLeft == 0)
2068 v.tickLeft = periodHi_;
2070 const int m = std::min(to - i, v.tickLeft);
2071 const int at = filtered ? i - from : 0;
2072 double* L = lane.l.data() + at;
2073 double* R = lane.r.data() + at;
2074 std::fill_n(L, m, 0.0);
2075 std::fill_n(R, m, 0.0);
2076 renderSources(v, L, R, m);
2078 const int pos0 = v.tickPos;
2079 for (
int j = 0; j < m; ++j)
2081 const int pos = pos0 + j;
2082 const auto s =
static_cast<size_t>(at + j);
2085 lane.g[s] =
static_cast<T
>(v.g.at(pos));
2086 lane.q[s] =
static_cast<T
>(ladder ? v.resonance.at(pos) : v.svfK.at(pos));
2087 if (ladder) lane.drive[s] =
static_cast<T
>(v.drive.at(pos));
2089 double gain = v.amp.getNextValue() * v.ampGain.at(pos);
2090 if (v.stealLeft >= 0)
2092 gain *=
static_cast<double>(v.stealLeft) /
static_cast<double>(stealFade_);
2093 if (--v.stealLeft < 0)
2095 lane.count = at + j;
2102 lane.gain[s] = gain;
2103 lane.panL[s] = v.panL.at(pos);
2104 lane.panR[s] = v.panR.at(pos);
2108 const double l = L[j];
2109 const double r = v.stereo ? R[j] : l;
2110 outL[i + j] +=
static_cast<T
>(l * gain * v.panL.at(pos));
2111 outR[i + j] +=
static_cast<T
>(r * gain * v.panR.at(pos));
2113 if (!v.amp.isActive())
2115 lane.count = at + j + 1;
2125 lane.count = to - from;
2128 void mixLanes(
FilterType type, T* outL, T* outR,
bool pair)
noexcept
2133 case FilterType::LadderLp24: mixWith<LadderKernel<LadderTap::LP24>>(outL, outR, pair);
break;
2134 case FilterType::LadderLp12: mixWith<LadderKernel<LadderTap::LP12>>(outL, outR, pair);
break;
2135 case FilterType::LadderBp12: mixWith<LadderKernel<LadderTap::BP12>>(outL, outR, pair);
break;
2136 case FilterType::LadderHp24: mixWith<LadderKernel<LadderTap::HP24>>(outL, outR, pair);
break;
2137 case FilterType::SvfHp: mixWith<SvfKernel<FilterType::SvfHp>>(outL, outR, pair);
break;
2138 case FilterType::SvfBp: mixWith<SvfKernel<FilterType::SvfBp>>(outL, outR, pair);
break;
2139 case FilterType::SvfNotch: mixWith<SvfKernel<FilterType::SvfNotch>>(outL, outR, pair);
break;
2140 default: mixWith<SvfKernel<FilterType::SvfLp>>(outL, outR, pair);
break;
2146 template <
class Kernel>
2147 void mixWith(T* outL, T* outR,
bool pair)
noexcept
2149 Lane& a = lanes_[0];
2150 Lane& b = lanes_[1];
2151 const int both = pair ? std::min(a.count, b.count) : 0;
2152 for (
int j = 0; j < both; ++j)
2154 mixSample<Kernel>(a, j, outL, outR);
2155 mixSample<Kernel>(b, j, outL, outR);
2157 for (
int j = both; j < a.count; ++j) mixSample<Kernel>(a, j, outL, outR);
2159 for (
int j = both; j < b.count; ++j) mixSample<Kernel>(b, j, outL, outR);
2162 template <
class Kernel>
2163 static void mixSample(Lane& lane,
int j, T* outL, T* outR)
noexcept
2165 const auto s =
static_cast<size_t>(j);
2166 Voice& v = *lane.voice;
2167 double l = lane.l[s];
2168 double r = v.stereo ? lane.r[s] : l;
2169 Kernel::run(v, lane, s, l, r);
2170 outL[lane.start + j] +=
static_cast<T
>(l * lane.gain[s] * lane.panL[s]);
2171 outR[lane.start + j] +=
static_cast<T
>(r * lane.gain[s] * lane.panR[s]);
2174 template <detail::LadderTap Tap>
struct LadderKernel
2176 static void run(Voice& v,
const Lane& lane,
size_t s,
double& l,
double& r)
noexcept
2179 const T drive = lane.drive[s];
2180 l =
static_cast<double>(detail::ladderStep<Tap>(
static_cast<T
>(l), v.ladder[0], c, drive));
2181 r = v.stereo ?
static_cast<double>(detail::ladderStep<Tap>(
static_cast<T
>(r), v.ladder[1], c, drive)) : l;
2185 template <FilterType Type>
struct SvfKernel
2187 static T highpass(T x, T k, T bandpass, T lowpass)
noexcept {
return x - k * bandpass - lowpass; }
2189 static double step(T x, detail::TptSvfState<T>& state, T a1, T a2, T a3, T k)
noexcept
2192 if constexpr (Type == FilterType::SvfHp)
2193 return static_cast<double>(highpass(x, k, o.bandpass, o.lowpass));
2194 else if constexpr (Type == FilterType::SvfBp)
2195 return static_cast<double>(k * o.bandpass);
2196 else if constexpr (Type == FilterType::SvfNotch)
2197 return static_cast<double>(o.lowpass + highpass(x, k, o.bandpass, o.lowpass));
2199 return static_cast<double>(o.lowpass);
2202 static void run(Voice& v,
const Lane& lane,
size_t s,
double& l,
double& r)
noexcept
2204 const T g = lane.g[s];
2205 const T k = lane.q[s];
2206 const T a1 = T(1) / (T(1) + g * (g + k));
2207 const T a2 = g * a1;
2208 const T a3 = g * a2;
2209 l = step(
static_cast<T
>(l), v.svf[0], a1, a2, a3, k);
2210 r = v.stereo ? step(
static_cast<T
>(r), v.svf[1], a1, a2, a3, k) : l;
2214 void renderSources(Voice& v,
double* L,
double* R,
int m)
noexcept
2216 const int pos0 = v.tickPos;
2219 case Engine::Analog: renderAnalog(v, L, R, m, pos0);
break;
2220 case Engine::Wavetable: renderWavetable(v, L, R, m, pos0);
break;
2221 case Engine::Fm: renderFm(v, L, R, m, pos0);
break;
2226 if (v.zone !=
nullptr)
2228 const bool audible = v.sampleLevel.live();
2229 const bool zoneStereo = v.zone->channels > 1;
2230 for (
int u = 0; u < v.unison; ++u)
2232 auto& uv = v.uni[
static_cast<size_t>(u)];
2233 for (
int j = 0; j < m && uv.readerOn; ++j)
2235 double a0 = 0.0, a1 = 0.0;
2236 const auto frame = uv.reader.next(uv.sampleRatio.at(pos0 + j), 2, weights_.data(), a0, a1);
2240 const double level = v.sampleLevel.at(pos0 + j);
2241 L[j] += a0 * v.zoneGainL * level * uv.gainL;
2242 R[j] += (zoneStereo ? a1 : a0) * v.zoneGainR * level * uv.gainR;
2250 if (v.subLevel.live())
2251 for (
int j = 0; j < m; ++j)
2253 if (v.subFreq.step != 0.0) v.sub.setFrequency(
static_cast<T
>(v.subFreq.at(pos0 + j)));
2254 const double s =
static_cast<double>(v.sub.getNextSample()) * v.subLevel.at(pos0 + j);
2258 if (v.noiseLevel.live())
2259 for (
int j = 0; j < m; ++j)
2261 uint32_t x = v.noise;
2266 const double s = (
static_cast<double>(x) * (2.0 / 4294967296.0) - 1.0)
2267 * noiseScale_ * v.noiseLevel.at(pos0 + j);
2273 void renderAnalog(Voice& v,
double* L,
double* R,
int m,
int pos0)
noexcept
2275 for (
int k = 0; k < 3; ++k)
2277 const auto& lv = v.oscLevel[
static_cast<size_t>(k)];
2278 if (!lv.live())
continue;
2279 const auto& pw = v.pulseWidth[
static_cast<size_t>(k)];
2280 const bool sync = ip(oscParam(k, 6)) != 0;
2281 const bool pulse =
static_cast<OscWave>(ip(oscParam(k, 0))) == OscWave::Pulse;
2282 for (
int u = 0; u < v.unison; ++u)
2284 auto& uv = v.uni[
static_cast<size_t>(u)];
2285 auto& o = uv.osc[
static_cast<size_t>(k)];
2286 const auto& fr = uv.freq[
static_cast<size_t>(k)];
2287 const auto& ms = uv.master[
static_cast<size_t>(k)];
2288 const bool moving = fr.step != 0.0 || ms.step != 0.0;
2289 for (
int j = 0; j < m; ++j)
2291 const int pos = pos0 + j;
2296 const double mh = ms.at(pos);
2297 o.setFrequency(
static_cast<T
>(mh));
2298 o.setSyncRatio(
static_cast<T
>(mh > 0.0 ? fr.at(pos) / mh : 0.0));
2302 o.setFrequency(
static_cast<T
>(fr.at(pos)));
2305 if (pulse && pw.step != 0.0) o.setPulseWidth(
static_cast<T
>(pw.at(pos)));
2306 const double s =
static_cast<double>(o.getNextSample()) * lv.at(pos);
2307 L[j] += s * uv.gainL;
2308 R[j] += s * uv.gainR;
2314 void renderWavetable(Voice& v,
double* L,
double* R,
int m,
int pos0)
noexcept
2316 for (
int k = 0; k < 2; ++k)
2318 const auto& lv = v.wtLevel[
static_cast<size_t>(k)];
2319 if (!lv.live())
continue;
2320 const WavetableBank& bank = bankFor(v, k);
2321 const double frames =
static_cast<double>(std::max(bank.getNumFrames() - 1, 0));
2322 const auto& wp = v.wtPosition[
static_cast<size_t>(k)];
2327 for (
int c0 = 0; c0 < m; c0 += kWaveChunk)
2329 const int mc = std::min(kWaveChunk, m - c0);
2330 const bool morphing = wp.step != 0.0;
2331 std::array<double, kWaveChunk> positions;
2333 for (
int j = 0; j < mc; ++j)
2334 positions[
static_cast<size_t>(j)] = wp.at(pos0 + c0 + j) * frames;
2335 const double still = wp.at(pos0 + c0) * frames;
2336 for (
int u = 0; u < v.unison; ++u)
2338 auto& uv = v.uni[
static_cast<size_t>(u)];
2339 const auto& fr = uv.freq[
static_cast<size_t>(k)];
2340 double& phase = uv.wtPhase[
static_cast<size_t>(k)];
2341 const auto mip = uv.mip[
static_cast<size_t>(k)];
2342 std::array<double, kWaveChunk> phases;
2343 std::array<T, kWaveChunk> wave;
2344 for (
int j = 0; j < mc; ++j)
2346 phases[
static_cast<size_t>(j)] = phase;
2347 phase += fr.at(pos0 + c0 + j) / internalRate_;
2348 if (phase >= 1.0) phase -= 1.0;
2351 bank.readBlock<T>(phases.data(), positions.data(), mip, wave.data(), mc);
2353 bank.readBlock<T>(phases.data(), still, mip, wave.data(), mc);
2354 for (
int j = 0; j < mc; ++j)
2356 const double s =
static_cast<double>(wave[
static_cast<size_t>(j)]) * lv.at(pos0 + c0 + j);
2357 L[c0 + j] += s * uv.gainL;
2358 R[c0 + j] += s * uv.gainR;
2365 void renderFm(Voice& v,
double* L,
double* R,
int m,
int pos0)
noexcept
2369 constexpr double kIndex = 4.0 * pi<double>;
2371 const int algorithm = std::clamp(ip(Param::FmAlgorithm), 0, 7);
2375 std::array<std::array<double, kMax>, 4> amp;
2376 std::array<bool, 4> live {};
2377 for (
int k = 0; k < 4; ++k) live[static_cast<size_t>(k)] = v.opLevel[
static_cast<size_t>(k)].live();
2378 for (
int j = 0; j < m; ++j)
2379 for (
int k = 0; k < 4; ++k)
2380 amp[
static_cast<size_t>(k)][
static_cast<size_t>(j)] =
2381 v.opLevel[
static_cast<size_t>(k)].at(pos0 + j) * v.opEnv[
static_cast<size_t>(k)].getNextValue();
2383 for (
int u = 0; u < v.unison; ++u)
2385 auto& uv = v.uni[
static_cast<size_t>(u)];
2386 for (
int j = 0; j < m; ++j)
2388 const int pos = pos0 + j;
2389 auto op = [&](
int k,
double pm)
noexcept {
2390 return live[
static_cast<size_t>(k)]
2391 ? amp[
static_cast<size_t>(k)][
static_cast<size_t>(j)]
2392 *
fastSin(twoPi<double> * uv.opPhase[
static_cast<size_t>(k)] + pm)
2396 const double o4 = op(3, v.feedback.at(pos) * pi<double> * 0.5 * (uv.fb1 + uv.fb2));
2402 case 0: {
const double o3 = op(2, kIndex * o4);
const double o2 = op(1, kIndex * o3);
2403 out = op(0, kIndex * o2);
break; }
2404 case 1: {
const double o3 = op(2, 0.0);
const double o2 = op(1, kIndex * (o3 + o4));
2405 out = op(0, kIndex * o2);
break; }
2406 case 2: {
const double o3 = op(2, 0.0);
const double o2 = op(1, kIndex * o3);
2407 out = op(0, kIndex * (o2 + o4));
break; }
2408 case 3: {
const double o3 = op(2, kIndex * o4);
const double o2 = op(1, 0.0);
2409 out = op(0, kIndex * (o2 + o3));
break; }
2410 case 4: {
const double o3 = op(2, kIndex * o4);
const double o2 = op(1, 0.0);
2411 out = 0.5 * (op(0, kIndex * o2) + o3);
break; }
2412 case 5: out = (op(0, kIndex * o4) + op(1, kIndex * o4) + op(2, kIndex * o4)) / 3.0;
break;
2413 case 6: out = (op(0, 0.0) + op(1, 0.0) + op(2, kIndex * o4)) / 3.0;
break;
2414 default: out = 0.25 * (op(0, 0.0) + op(1, 0.0) + op(2, 0.0) + o4);
break;
2416 for (
int k = 0; k < 4; ++k)
2418 double& ph = uv.opPhase[
static_cast<size_t>(k)];
2419 ph += uv.opFreq[
static_cast<size_t>(k)].at(pos) / internalRate_;
2420 if (ph >= 1.0) ph -= 1.0;
2422 L[j] += out * uv.gainL;
2423 R[j] += out * uv.gainR;
2433 std::array<std::atomic<float>,
kNumParams> values_ {};
2434 std::array<float, kNumParams> params_ {};
2435 std::atomic<float> tempo_ { 120.0f };
2436 float tempoApplied_ = 120.0f;
2438 double baseRate_ = 48000.0;
2439 double internalRate_ = 48000.0;
2440 int maxBlock_ = 512;
2441 int maxVoices_ = 16;
2446 int stealFade_ = 144;
2447 double noiseScale_ = 1.0;
2448 double smoothAlpha_ = 0.03;
2449 bool prepared_ =
false;
2451 std::vector<Voice> voices_;
2452 std::vector<T> weights_;
2453 std::array<std::vector<T>, 2> mix_;
2454 std::array<Lane, 2> lanes_ {};
2455 Oversampling<T, 2> os2_ { 2, Oversampling<T, 2>::Quality::Maximum };
2456 Oversampling<T, 2> os4_ { 4, Oversampling<T, 2>::Quality::Maximum };
2458 std::array<Event, kMaxEvents> events_ {};
2459 int eventCount_ = 0;
2460 std::array<int, 128> held_ {};
2461 std::array<double, 128> heldTuning_ {};
2463 bool sustainPedal_ =
false;
2465 double modWheel_ = 0.0;
2466 double pressure_ = 0.0;
2467 double expression_ = 1.0;
2468 double breath_ = 0.0;
2469 double lastPitch_ = -1.0;
2470 bool haveLastPitch_ =
false;
2471 double masterGain_ = 0.5;
2472 uint64_t noteCounter_ = 0;
2473 uint64_t clock_ = 0;
2474 int64_t timeHi_ = 0;
2476 std::array<FreeLfo, 2> freeLfo_ {};
2479 std::shared_ptr<const std::vector<ZoneData>> controlZones_;
2480 std::shared_ptr<const WavetableBank> controlWavetable_;
2482 Content* active_ =
nullptr;
2483 Content* fading_ =
nullptr;
2484 std::atomic<Content*> pending_ {
nullptr };
2485 std::atomic<Content*> retired_ {
nullptr };
2487 std::atomic<int> latency_ { 0 };
2488 std::atomic<int> activeVoices_ { 0 };