| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208 |
- #include "core/RackRenderer.h"
- #include "core/WorkerPool.h"
- #include "core/Denormals.h"
- #include <algorithm>
- #include <cmath>
- #include <cstring>
- #include <limits>
- namespace lynx
- {
- namespace
- {
- // Silent instrument: plugin channel that could not be loaded.
- class SilentInstrument final : public Instrument
- {
- public:
- void prepare (double) noexcept override {}
- void noteOn (int, float) noexcept override {}
- void noteOff (int) noexcept override {}
- void allNotesOff() noexcept override {}
- void render (float*, float*, int, float, float) noexcept override {}
- };
- // Effect that does nothing: missing plugin slot.
- class BypassEffect final : public Effect
- {
- public:
- void prepare (double) noexcept override {}
- void reset() noexcept override {}
- void process (float*, float*, int, const EffectParams&, double) noexcept override {}
- };
- } // namespace
- std::unique_ptr<const RackState> RackState::build (Song song,
- const RackState* previous,
- double sampleRate,
- const SampleProvider& samples)
- {
- Factories factories;
- factories.samples = samples;
- return build (std::move (song), previous, sampleRate, factories);
- }
- std::unique_ptr<const RackState> RackState::build (Song song,
- const RackState* previous,
- double sampleRate,
- const Factories& factories)
- {
- const auto& samples = factories.samples;
- auto state = std::make_unique<RackState>();
- state->instruments.reserve (song.channels.size());
- for (std::size_t i = 0; i < song.channels.size(); ++i)
- {
- const auto& channel = song.channels[i];
- const auto kind = channel.instrument;
- if (previous != nullptr && i < previous->song.channels.size() && i < previous->instruments.size()
- && previous->song.channels[i].instrument == kind
- && ((kind != InstrumentKind::sampler && kind != InstrumentKind::audioClip)
- || (previous->song.channels[i].samplePath == channel.samplePath && previous->song.channels[i].zones == channel.zones
- && previous->song.channels[i].sampler.keepPitch == channel.sampler.keepPitch
- && (! channel.sampler.keepPitch
- || (previous->song.channels[i].sampler.stretchBeats == channel.sampler.stretchBeats
- && previous->song.bpm == song.bpm))))
- && (kind != InstrumentKind::plugin
- || (previous->song.channels[i].plugin.id == channel.plugin.id && previous->sampleRate == sampleRate)))
- {
- state->instruments.push_back (previous->instruments[i]);
- state->instruments.back()->configure (channel, song.bpm);
- continue;
- }
- if (kind == InstrumentKind::plugin)
- {
- std::shared_ptr<Instrument> instrument;
- if (factories.pluginInstruments && ! channel.plugin.id.empty())
- instrument = factories.pluginInstruments (channel.plugin, sampleRate);
- state->instruments.push_back (instrument != nullptr ? instrument : std::make_shared<SilentInstrument>());
- continue;
- }
- // multi-sample sampler: one zone per sample (DirectWave, FPC layers...)
- if (kind == InstrumentKind::sampler && ! channel.zones.empty())
- {
- std::vector<LoadedZone> zones;
- for (const auto& z : channel.zones)
- zones.push_back ({ z, samples ? samples (z.path) : nullptr });
- std::shared_ptr<Instrument> instrument = makeZonedSampler (std::move (zones));
- instrument->prepare (sampleRate);
- instrument->configure (channel, song.bpm);
- state->instruments.push_back (std::move (instrument));
- continue;
- }
- std::shared_ptr<const SampleData> sample;
- if ((kind == InstrumentKind::sampler || kind == InstrumentKind::audioClip) && samples && ! channel.samplePath.empty())
- sample = samples (channel.samplePath);
- // pitch-preserving stretch: the sample comes already stretched to the current tempo
- if (sample != nullptr && channel.sampler.keepPitch && channel.sampler.stretchBeats > 0.0f && factories.stretchedSamples
- && sample->frames() > 0)
- {
- const auto target = channel.sampler.stretchBeats * 60.0 / std::max (1.0, song.bpm);
- const auto ratio = target / ((double) sample->frames() / sample->sampleRate);
- if (auto stretched = factories.stretchedSamples (channel.samplePath, ratio))
- sample = std::move (stretched);
- }
- std::shared_ptr<Instrument> instrument = makeInstrument (kind, std::move (sample));
- instrument->prepare (sampleRate);
- instrument->configure (channel, song.bpm);
- state->instruments.push_back (std::move (instrument));
- }
- state->effects.resize (song.mixer.size());
- for (std::size_t t = 0; t < song.mixer.size(); ++t)
- {
- const auto& slots = song.mixer[t].effects;
- for (std::size_t i = 0; i < slots.size() && i < (std::size_t) maxEffectSlots; ++i)
- {
- const auto kind = slots[i].kind;
- if (previous != nullptr && t < previous->song.mixer.size() && t < previous->effects.size()
- && i < previous->song.mixer[t].effects.size() && i < previous->effects[t].size()
- && previous->song.mixer[t].effects[i].kind == kind && kind != EffectKind::parallel // the container is rebuilt
- && previous->song.mixer[t].effects[i].state == slots[i].state
- && (kind != EffectKind::plugin
- || (previous->song.mixer[t].effects[i].plugin.id == slots[i].plugin.id && previous->sampleRate == sampleRate)))
- {
- state->effects[t].push_back (previous->effects[t][i]);
- continue;
- }
- std::shared_ptr<Effect> effect;
- if (kind == EffectKind::plugin)
- {
- if (factories.pluginEffects && ! slots[i].plugin.id.empty())
- effect = factories.pluginEffects (slots[i].plugin, sampleRate);
- if (effect == nullptr)
- effect = std::make_shared<BypassEffect>();
- }
- else
- {
- effect = makeEffect (slots[i]);
- effect->prepare (sampleRate);
- }
- state->effects[t].push_back (std::move (effect));
- }
- }
- state->song = std::move (song);
- // scheduling: notes sorted by start (order among notes on the same tick is preserved)
- for (auto& p : state->song.patterns)
- std::stable_sort (p.notes.begin(), p.notes.end(), [] (const Note& a, const Note& b) { return a.start < b.start; });
- state->schedule = makeScheduleIndex (state->song);
- state->sampleRate = sampleRate;
- state->buildAutomationTables();
- state->buildPdc (previous);
- state->buildMixerGraph();
- const auto& channels = state->song.channels;
- state->cutTargets.assign (channels.size(), {});
- state->arpeggiators.assign (channels.size(), nullptr);
- for (std::size_t c = 0; c < channels.size(); ++c)
- if (channels[c].arp.enabled())
- state->arpeggiators[c] = previous != nullptr && c < previous->arpeggiators.size() && previous->arpeggiators[c] != nullptr
- ? previous->arpeggiators[c]
- : std::make_shared<Arpeggiator>();
- for (std::size_t c = 0; c < channels.size(); ++c)
- if (channels[c].cutGroup > 0)
- for (std::size_t d = 0; d < channels.size(); ++d)
- if (channels[d].cutBy == channels[c].cutGroup)
- {
- state->cutTargets[c].push_back ((int) d);
- state->hasCutGroups = true;
- }
- const auto audible = state->song.soloAudible();
- state->mixerAudible.assign (audible.begin(), audible.end());
- return state;
- }
- void RackState::buildMixerGraph()
- {
- mixerOrder = song.mixerOrder();
- const auto audible = song.soloAudible();
- mixerAudible.assign (audible.begin(), audible.end());
- const auto tracks = std::max<int> (1, (int) song.mixer.size());
- mixerInputs.assign ((std::size_t) tracks, {});
- std::vector<int> depth ((std::size_t) tracks, 0);
- // who listens to each track via sidechain (the source goes in an earlier layer)
- std::vector<std::vector<int>> sidechainListeners ((std::size_t) tracks);
- for (int t = 1; t < tracks; ++t)
- for (const auto& fx : song.mixer[(std::size_t) t].effects)
- for (const auto source : { fx.sidechain, fx.sidechain2 })
- if (source > 0 && source < tracks && source != t)
- sidechainListeners[(std::size_t) source].push_back (t);
- for (auto t : mixerOrder) // sources before destinations: the depth is already computed
- {
- const auto& track = song.mixer[(std::size_t) t];
- for (const auto listener : sidechainListeners[(std::size_t) t])
- depth[(std::size_t) listener] = std::max (depth[(std::size_t) listener], depth[(std::size_t) t] + 1);
- if (track.toMaster)
- mixerInputs[0].push_back ({ t, 0, 1.0f });
- for (std::size_t k = 0; k < track.sends.size(); ++k)
- {
- const auto& send = track.sends[k];
- if (send.target > 0 && send.target < tracks && send.target != t && send.level > 0.0f)
- {
- mixerInputs[(std::size_t) send.target].push_back ({ t, (int) k + 1, send.level });
- depth[(std::size_t) send.target] = std::max (depth[(std::size_t) send.target], depth[(std::size_t) t] + 1);
- }
- }
- }
- mixerLayers.clear();
- for (auto t : mixerOrder)
- {
- const auto d = (std::size_t) depth[(std::size_t) t];
- if (mixerLayers.size() <= d)
- mixerLayers.resize (d + 1);
- mixerLayers[d].push_back (t);
- }
- // splitting across threads costs a few microseconds per block; only worth it with plugins or many channels
- const auto plugins = std::count_if (song.channels.begin(), song.channels.end(),
- [] (const ChannelDef& c) { return c.instrument == InstrumentKind::plugin; });
- auto pluginEffects = 0;
- for (const auto& t : song.mixer)
- pluginEffects += (int) std::count_if (t.effects.begin(), t.effects.end(), [] (const EffectSlot& e) { return e.kind == EffectKind::plugin; });
- parallel = plugins + pluginEffects >= 2 || song.channels.size() >= 24;
- }
- std::vector<int> RackState::currentLatencies() const
- {
- std::vector<int> out;
- for (const auto& i : instruments)
- out.push_back (i->latencySamples());
- for (const auto& track : effects)
- for (const auto& e : track)
- out.push_back (e->latencySamples());
- return out;
- }
- void RackState::buildPdc (const RackState* previous)
- {
- latencies = currentLatencies();
- std::vector<int> channelLatency (latencies.begin(), latencies.begin() + (std::ptrdiff_t) instruments.size());
- std::vector<std::vector<int>> slotLatency (effects.size());
- auto next = latencies.begin() + (std::ptrdiff_t) instruments.size();
- for (std::size_t t = 0; t < effects.size(); ++t)
- for (std::size_t s = 0; s < effects[t].size(); ++s)
- slotLatency[t].push_back (*next++);
- pdc = computePdc (song, channelLatency, slotLatency);
- // reuses lines of the same length: editing the song must not click the audio
- auto line = [] (int length, const std::shared_ptr<DelayLine>* old) -> std::shared_ptr<DelayLine> {
- if (length <= 0)
- return nullptr;
- if (old != nullptr && *old != nullptr && (*old)->length() == length)
- return *old;
- return std::make_shared<DelayLine> (length);
- };
- channelDelays.resize (pdc.channelDelay.size());
- for (std::size_t c = 0; c < pdc.channelDelay.size(); ++c)
- channelDelays[c] = line (pdc.channelDelay[c],
- previous != nullptr && c < previous->channelDelays.size() ? &previous->channelDelays[c] : nullptr);
- sendDelays.resize (pdc.sendDelay.size());
- for (std::size_t t = 0; t < pdc.sendDelay.size(); ++t)
- {
- sendDelays[t].resize (pdc.sendDelay[t].size());
- for (std::size_t k = 0; k < pdc.sendDelay[t].size(); ++k)
- {
- const std::shared_ptr<DelayLine>* old = nullptr;
- if (previous != nullptr && t < previous->sendDelays.size() && k < previous->sendDelays[t].size())
- old = &previous->sendDelays[t][k];
- sendDelays[t][k] = line (pdc.sendDelay[t][k], old);
- }
- }
- }
- void RackState::buildAutomationTables()
- {
- const auto& automations = song.automations;
- const auto count = std::min<int> ((int) automations.size(), maxAutomations);
- automationClips.assign ((std::size_t) count, {});
- for (int i = 0; i < (int) song.playlist.size(); ++i)
- {
- const auto& c = song.playlist[(std::size_t) i];
- if (c.kind == ClipKind::automation && c.automation >= 0 && c.automation < count && c.length > 0 && ! c.muted && ! song.isTrackMuted (c.track))
- automationClips[(std::size_t) c.automation].push_back (i);
- }
- for (auto& clips : automationClips)
- std::sort (clips.begin(), clips.end(),
- [this] (int a, int b) { return song.playlist[(std::size_t) a].start < song.playlist[(std::size_t) b].start; });
- liveAutomations.clear();
- for (int a = 0; a < count; ++a)
- if (automations[(std::size_t) a].isLive())
- liveAutomations.push_back (a);
- channelVolumeAuto.assign (song.channels.size(), -1);
- channelPanAuto.assign (song.channels.size(), -1);
- mixerVolumeAuto.assign (song.mixer.size(), -1);
- mixerPanAuto.assign (song.mixer.size(), -1);
- effectParamAuto.assign (song.mixer.size(), {});
- effectMixAuto.assign (song.mixer.size(), {});
- for (std::size_t t = 0; t < song.mixer.size(); ++t)
- {
- std::array<int, maxEffectParams> none;
- none.fill (-1);
- effectParamAuto[t].assign (song.mixer[t].effects.size(), none);
- effectMixAuto[t].assign (song.mixer[t].effects.size(), -1);
- }
- pluginParams.clear();
- hasAutomation = false;
- tempoAutomation = -1;
- // the last automation of the same target wins
- for (int a = 0; a < count; ++a)
- {
- if (automationClips[(std::size_t) a].empty() && ! automations[(std::size_t) a].isLive())
- continue;
- const auto& t = automations[(std::size_t) a].target;
- const auto channelOk = t.index >= 0 && t.index < (int) song.channels.size();
- const auto trackOk = t.index >= 0 && t.index < (int) song.mixer.size();
- auto used = true;
- switch (t.kind)
- {
- case AutomationTargetKind::channelVolume: if (channelOk) channelVolumeAuto[(std::size_t) t.index] = a; else used = false; break;
- case AutomationTargetKind::channelPan: if (channelOk) channelPanAuto[(std::size_t) t.index] = a; else used = false; break;
- case AutomationTargetKind::mixerVolume: if (trackOk) mixerVolumeAuto[(std::size_t) t.index] = a; else used = false; break;
- case AutomationTargetKind::mixerPan: if (trackOk) mixerPanAuto[(std::size_t) t.index] = a; else used = false; break;
- case AutomationTargetKind::channelParam:
- if (channelOk && song.channels[(std::size_t) t.index].instrument == InstrumentKind::plugin)
- pluginParams.push_back ({ a, t.index, 0, 0, t.param });
- else
- used = false;
- break;
- case AutomationTargetKind::effectParam:
- {
- const auto slotOk = trackOk && t.slot >= 0 && t.slot < (int) song.mixer[(std::size_t) t.index].effects.size();
- if (! slotOk)
- used = false;
- else if (song.mixer[(std::size_t) t.index].effects[(std::size_t) t.slot].kind == EffectKind::plugin)
- pluginParams.push_back ({ a, -1, t.index, t.slot, t.param });
- else if (t.param >= 0 && t.param < maxEffectParams)
- effectParamAuto[(std::size_t) t.index][(std::size_t) t.slot][(std::size_t) t.param] = a;
- else
- used = false;
- break;
- }
- case AutomationTargetKind::effectMix:
- if (trackOk && t.slot >= 0 && t.slot < (int) song.mixer[(std::size_t) t.index].effects.size())
- effectMixAuto[(std::size_t) t.index][(std::size_t) t.slot] = a;
- else
- used = false;
- break;
- case AutomationTargetKind::tempo: tempoAutomation = a; break;
- case AutomationTargetKind::none: used = false; break;
- }
- hasAutomation = hasAutomation || used;
- }
- }
- namespace
- {
- // Constant-power pan: at center both sides are 1 (0 dB).
- void panGains (float pan, float gain, float& left, float& right) noexcept
- {
- const auto angle = (pan + 1.0f) * 0.25f * 3.14159265f;
- left = gain * std::cos (angle) * 1.41421356f;
- right = gain * std::sin (angle) * 1.41421356f;
- }
- float peakOf (const float* data, int n) noexcept
- {
- float peak = 0.0f;
- for (int i = 0; i < n; ++i)
- {
- const auto a = std::abs (data[i]);
- peak = a > peak ? a : peak; // form the compiler vectorizes
- }
- return peak;
- }
- // Any sample above `level`? Stops at the first: with sound (the common case) it costs almost nothing.
- bool anyAbove (const float* l, const float* r, int n, float level) noexcept
- {
- // in blocks of 32: the inner loop vectorizes; silent chunks (the ones that scan everything) stay cheap
- int i = 0;
- for (; i + 32 <= n; i += 32)
- {
- float m = 0.0f;
- for (int k = i; k < i + 32; ++k)
- {
- const auto a = std::abs (l[k]), b = std::abs (r[k]);
- m = a > m ? a : m;
- m = b > m ? b : m;
- }
- if (m > level)
- return true;
- }
- for (; i < n; ++i)
- if (std::abs (l[i]) > level || std::abs (r[i]) > level)
- return true;
- return false;
- }
- } // namespace
- void RackRenderer::prepare (double sr, int maxBlockSize)
- {
- automationValues.fill (std::numeric_limits<float>::quiet_NaN());
- lastTrackGain.fill (std::numeric_limits<float>::quiet_NaN());
- channelBuffers.assign ((std::size_t) maxChannels * 2 * chunkCapacity, 0.0f);
- smartDisable.assign ((std::size_t) maxMixerTracks * maxEffectSlots, {});
- trackEqs.assign ((std::size_t) maxMixerTracks, {});
- trackScratchBuffers.assign ((std::size_t) maxMixerTracks * 2 * chunkCapacity, 0.0f);
- sampleRate = sr;
- blockCapacity = std::max (64, maxBlockSize);
- mixBuffers.assign ((std::size_t) maxMixerTracks * 2 * (std::size_t) blockCapacity, 0.0f);
- if (lastState != nullptr)
- {
- for (auto& instrument : lastState->instruments)
- instrument->prepare (sr);
- for (auto& track : lastState->effects)
- for (auto& effect : track)
- effect->prepare (sr);
- }
- }
- float* RackRenderer::trackBuffer (int track, int channel) noexcept
- {
- return mixBuffers.data() + ((std::size_t) track * 2 + (std::size_t) channel) * (std::size_t) blockCapacity;
- }
- float RackRenderer::automated (int automation, float base) const noexcept
- {
- if (automation < 0)
- return base;
- const auto v = automationValues[(std::size_t) automation];
- return std::isnan (v) ? base : v;
- }
- namespace
- {
- // Value of an automation at a song position: inside a clip, the curve; between clips,
- // the last value of the previous clip; before the first, its initial value. Depends only on
- // position, so playing from any point (or exporting) gives the same result.
- float automationValueAt (const Song& song, const Automation& automation, const std::vector<int>& clips, double tick) noexcept
- {
- const Clip* before = nullptr;
- for (auto i : clips) // sorted by start
- {
- const auto& c = song.playlist[(std::size_t) i];
- if (tick < (double) c.start)
- break;
- if (tick < (double) c.end())
- return automation.valueAt (tick - (double) c.start + (double) c.offset);
- before = &c;
- }
- if (before != nullptr)
- return automation.valueAt ((double) (before->length + before->offset));
- const auto& first = song.playlist[(std::size_t) clips.front()];
- return automation.valueAt ((double) first.offset);
- }
- } // namespace
- void RackRenderer::updateAutomation (const RackState& state, double startTick) noexcept
- {
- const auto& song = state.song;
- // controllers (live sources): the effect's output at the end of the previous block, in any mode
- for (const auto a : state.liveAutomations)
- {
- const auto& automation = song.automations[(std::size_t) a];
- const auto& src = automation.source;
- if (src.channel >= 0)
- {
- if (src.channel < (int) state.instruments.size() && state.instruments[(std::size_t) src.channel] != nullptr)
- automationValues[(std::size_t) a] = automation.mapLive (state.instruments[(std::size_t) src.channel]->controlOutput (src.output));
- }
- else if (src.track < (int) state.effects.size() && src.slot >= 0 && src.slot < (int) state.effects[(std::size_t) src.track].size()
- && state.effects[(std::size_t) src.track][(std::size_t) src.slot] != nullptr)
- automationValues[(std::size_t) a] = automation.mapLive (state.effects[(std::size_t) src.track][(std::size_t) src.slot]->controlOutput (src.output));
- }
- // in pattern mode the Playlist does not play: values stay as they were
- if (song.mode != PlayMode::song)
- return;
- const auto length = (double) std::max<std::int64_t> (1, state.schedule.songLength);
- const auto tick = std::fmod (std::max (0.0, startTick), length);
- for (std::size_t a = 0; a < state.automationClips.size(); ++a)
- if (! state.automationClips[a].empty())
- automationValues[a] = automationValueAt (song, song.automations[a], state.automationClips[a], tick);
- for (const auto& b : state.pluginParams)
- {
- const auto v = automationValues[(std::size_t) b.automation];
- if (std::isnan (v))
- continue;
- if (b.channel >= 0)
- {
- if (b.channel < (int) state.instruments.size())
- state.instruments[(std::size_t) b.channel]->setParameter (b.param, v);
- }
- else if (b.track < (int) state.effects.size() && b.slot < (int) state.effects[(std::size_t) b.track].size())
- state.effects[(std::size_t) b.track][(std::size_t) b.slot]->setParameter (b.param, v);
- }
- }
- float* RackRenderer::channelBuffer (int channel, int side) noexcept
- {
- return channelBuffers.data() + ((std::size_t) channel * 2 + (std::size_t) side) * chunkCapacity;
- }
- float* RackRenderer::trackScratch (int track, int side) noexcept
- {
- return trackScratchBuffers.data() + ((std::size_t) track * 2 + (std::size_t) side) * chunkCapacity;
- }
- // A whole channel over the chunk: notes at the exact sample (only its own events), volume/pan and the
- // PDC delay. Each channel only touches its own instrument and buffer: it can run in parallel.
- void RackRenderer::renderChannel (const RackState& state, int i, int n) noexcept
- {
- const auto& c = state.song.channels[(std::size_t) i];
- const auto automation = state.hasAutomation;
- const auto volume = channelGain (automation ? automated (state.channelVolumeAuto[(std::size_t) i], c.volume) : c.volume);
- const auto pan = automation ? automated (state.channelPanAuto[(std::size_t) i], (c.pan + 1.0f) * 0.5f) * 2.0f - 1.0f : c.pan;
- float gl = 0.0f, gr = 0.0f;
- panGains (pan, volume, gl, gr);
- auto* l = channelBuffer (i, 0);
- auto* r = channelBuffer (i, 1);
- if ((std::size_t) i < state.instruments.size() && state.instruments[(std::size_t) i] != nullptr)
- state.instruments[(std::size_t) i]->setSongPosition (chunkTick);
- auto& instrument = *state.instruments[(std::size_t) i];
- // idle channel, no notes in this chunk and no PDC: nothing to do (neither clear nor sum into the mixer)
- const auto hasDelay = (std::size_t) i < state.channelDelays.size() && state.channelDelays[(std::size_t) i] != nullptr;
- const auto hasArp = (std::size_t) i < state.arpeggiators.size() && state.arpeggiators[(std::size_t) i] != nullptr;
- if (! hasDelay && ! hasArp && instrument.idle()
- && std::none_of (events.begin(), events.end(), [i] (const NoteEvent& e) { return e.channel == i; }))
- {
- channelSilent[(std::size_t) i] = 1;
- return;
- }
- channelSilent[(std::size_t) i] = 0;
- std::memset (l, 0, sizeof (float) * (std::size_t) n);
- std::memset (r, 0, sizeof (float) * (std::size_t) n);
- int position = 0;
- // arpeggiator: the channel's notes become the arpeggio sequence
- const NoteEvent* list = events.begin();
- int listCount = events.size();
- if ((std::size_t) i < state.arpeggiators.size() && state.arpeggiators[(std::size_t) i] != nullptr)
- {
- auto& arp = *state.arpeggiators[(std::size_t) i];
- int inCount = 0;
- for (const auto& e : events)
- if (e.channel == i && inCount < Arpeggiator::maxEvents)
- arp.input[(std::size_t) inCount++] = e;
- int outCount = 0;
- arp.process (i, arp.input.data(), inCount, chunkStartTick, chunkTps, n, c.arp, arp.output.data(), outCount);
- list = arp.output.data();
- listCount = outCount;
- }
- for (int index = 0; index < listCount; ++index)
- {
- const auto& e = list[index];
- if (e.channel != i)
- continue;
- if (e.sampleOffset > position)
- {
- instrument.render (l + position, r + position, e.sampleOffset - position, gl, gr);
- position = e.sampleOffset;
- }
- if (e.type == NoteEvent::Type::on)
- {
- if (! c.muted)
- {
- instrument.setNextNoteExpression (e.pan, e.cents + state.song.masterPitch, e.porta);
- if (e.fadeIn > 0.0f || e.fadeOut > 0.0f)
- instrument.setNextClipFades (e.clipElapsed, e.clipRemaining, e.fadeIn, e.fadeOut);
- instrument.noteOnAt (e.key, e.velocity, e.startSeconds);
- }
- }
- else if (e.type == NoteEvent::Type::slide)
- {
- instrument.slideTo (e.key, e.cents + state.song.masterPitch, e.slideSamples);
- }
- else if (e.type == NoteEvent::Type::choke)
- {
- instrument.allNotesOff(); // short fade, like FL's "cut"
- }
- else
- instrument.noteOff (e.key);
- }
- if (position < n)
- instrument.render (l + position, r + position, n - position, gl, gr);
- // PDC: this channel arrives before the track's others; delay until aligned
- if ((std::size_t) i < state.channelDelays.size() && state.channelDelays[(std::size_t) i] != nullptr)
- state.channelDelays[(std::size_t) i]->process (l, r, n);
- }
- void RackRenderer::applyTrackEq (const MixerTrack& track, int t, float* l, float* r, int n) noexcept
- {
- if ((std::size_t) t >= trackEqs.size())
- return;
- auto& eq = trackEqs[(std::size_t) t];
- if (! track.eq.active())
- {
- if (eq.running)
- eq = {}; // off: reset the filters so they don't come back with a stale tail
- return;
- }
- if (! eq.running || ! (eq.settings == track.eq))
- {
- // new coefficients, keeping the filter state (no click when adjusting)
- const auto& s = track.eq;
- eq.bands[0].shelf (sampleRate, std::min ((double) s.hz[0], sampleRate * 0.45), s.gainDb[0], false, TrackEq::shelfSlope (s.width[0]));
- eq.bands[1].peaking (sampleRate, std::min ((double) s.hz[1], sampleRate * 0.45), TrackEq::peakQ (s.width[1]), s.gainDb[1]);
- eq.bands[2].shelf (sampleRate, std::min ((double) s.hz[2], sampleRate * 0.45), s.gainDb[2], true, TrackEq::shelfSlope (s.width[2]));
- for (std::size_t b = 0; b < 3; ++b)
- if (s.gainDb[b] == 0.0f)
- eq.bands[b].reset();
- eq.settings = s;
- eq.running = true;
- }
- for (std::size_t b = 0; b < 3; ++b)
- {
- if (eq.settings.gainDb[b] == 0.0f)
- continue; // band at 0 dB: not processed (like FL)
- eq.bands[b].processBlock (l, r, n);
- }
- }
- void RackRenderer::setSidechain (const RackState& state, const EffectSlot& slot, Effect& effect, int track) noexcept
- {
- // the source was already processed in this pass (earlier layer); silent = no signal in the detector
- for (const auto second : { false, true })
- {
- const auto source = second ? slot.sidechain2 : slot.sidechain;
- if (source < 0 || source == track || source >= (int) state.song.mixer.size())
- continue;
- const auto active = (std::size_t) source < trackActive.size() && trackActive[(std::size_t) source] != 0;
- const auto* left = active ? trackBuffer (source, 0) : nullptr;
- const auto* right = active ? trackBuffer (source, 1) : nullptr;
- if (second)
- effect.setSidechain2 (left, right);
- else
- effect.setSidechain (left, right);
- }
- }
- void RackRenderer::runEffects (const RackState& state, int track, int n) noexcept
- {
- if (track >= (int) state.effects.size())
- return;
- const auto& slots = state.song.mixer[(std::size_t) track].effects;
- const auto& effects = state.effects[(std::size_t) track];
- auto* l = trackBuffer (track, 0);
- auto* r = trackBuffer (track, 1);
- int audible = -1; // -1 = not measured yet; an effect's output is the next one's input
- for (std::size_t i = 0; i < effects.size() && i < slots.size(); ++i)
- {
- // slot dry/wet (automatable)
- const auto wet = state.hasAutomation && i < state.effectMixAuto[(std::size_t) track].size()
- ? std::clamp (automated (state.effectMixAuto[(std::size_t) track][i], slots[i].mix), 0.0f, 1.0f)
- : slots[i].mix;
- if (! slots[i].enabled || wet <= 0.0f)
- continue;
- // smart disable (like FL): an effect with silent input and output is skipped (plugins
- // after 4 s; built-ins after 1 s, which is well beyond their tail)
- const auto key = (std::size_t) track * maxEffectSlots + i;
- const auto isPlugin = slots[i].kind == EffectKind::plugin;
- const auto hold = (int) (sampleRate * (isPlugin ? 4.0 : 1.0));
- if (key < smartDisable.size())
- {
- auto& sd = smartDisable[key];
- if (sd.effect != effects[i].get())
- sd = { effects[i].get(), 0 };
- if (audible < 0)
- audible = anyAbove (l, r, n, silenceLevel) ? 1 : 0;
- if (audible == 1)
- sd.silentSamples = 0;
- else if (sd.silentSamples >= hold)
- continue;
- else
- sd.silentSamples += n;
- }
- // dry/wet: keep the dry signal to mix later
- const auto partial = wet < 0.999f;
- if (partial)
- {
- std::memcpy (trackScratch (track, 0), l, sizeof (float) * (std::size_t) n);
- std::memcpy (trackScratch (track, 1), r, sizeof (float) * (std::size_t) n);
- }
- if (state.hasAutomation && ! isPlugin)
- {
- auto params = slots[i].params; // copy without allocation
- const auto& autos = state.effectParamAuto[(std::size_t) track][i];
- const auto used = std::min (params.size(), effectInfo (slots[i].kind).params.size());
- for (std::size_t p = 0; p < used; ++p)
- params[p] = automated (autos[p], params[p]);
- effects[i]->setSongPosition (chunkTick);
- setSidechain (state, slots[i], *effects[i], track);
- effects[i]->process (l, r, n, params, bpm);
- }
- else
- {
- effects[i]->setSongPosition (chunkTick);
- setSidechain (state, slots[i], *effects[i], track);
- effects[i]->process (l, r, n, slots[i].params, bpm);
- }
- if (partial)
- {
- const auto* dl = trackScratch (track, 0);
- const auto* dr = trackScratch (track, 1);
- for (int k = 0; k < n; ++k)
- {
- l[k] = dl[k] + (l[k] - dl[k]) * wet;
- r[k] = dr[k] + (r[k] - dr[k]) * wet;
- }
- }
- // the effect changed the signal: measure again (it is the next slot's input)
- audible = anyAbove (l, r, n, silenceLevel) ? 1 : 0;
- if (audible == 1 && key < smartDisable.size())
- smartDisable[key].silentSamples = 0; // tail (reverb, delay): keep processing
- }
- }
- void RackRenderer::process (const RackState* state,
- bool playing,
- double startTick,
- int numSamples,
- float* left,
- float* right,
- LiveEventQueue* live,
- MeterBank* meters,
- LiveEventQueue* moreLive) noexcept
- {
- const ScopedFlushDenormals noDenormals;
- std::memset (left, 0, sizeof (float) * (std::size_t) numSamples);
- std::memset (right, 0, sizeof (float) * (std::size_t) numSamples);
- events.clear();
- if (state == nullptr || blockCapacity == 0)
- return;
- // A snapshot built before the device opened may have another rate. The instruments'
- // prepare() does not allocate, so it can run here.
- if (state != lastState && state->sampleRate != sampleRate)
- {
- for (auto& instrument : state->instruments)
- instrument->prepare (sampleRate);
- for (auto& track : state->effects)
- for (auto& effect : track)
- effect->prepare (sampleRate);
- }
- lastState = state; // so prepare() knows which instruments to reconfigure
- // Stopping, or jumping to another position (seek/rewind), releases held notes:
- // their "off" events will no longer happen.
- const auto jumped = playing && wasPlaying && std::abs (startTick - expectedTick) > 1.0;
- if ((wasPlaying && ! playing) || jumped)
- {
- for (auto& instrument : state->instruments)
- instrument->allNotesOff();
- for (auto& arp : state->arpeggiators)
- if (arp != nullptr)
- arp->reset();
- }
- // started playing or jumped: audio clips in progress must start mid-way
- resumeAudio = playing && (! wasPlaying || jumped);
- wasPlaying = playing;
- // tempo automation: the tempo holds for the whole block (evaluated at its start)
- bpm = state->song.bpm;
- if (state->tempoAutomation >= 0 && state->song.mode == PlayMode::song)
- {
- const auto length = (double) std::max<std::int64_t> (1, state->schedule.songLength);
- const auto& clips = state->automationClips[(std::size_t) state->tempoAutomation];
- if (! clips.empty())
- bpm = tempoFromValue (automationValueAt (state->song, state->song.automations[(std::size_t) state->tempoAutomation], clips,
- std::fmod (std::max (0.0, startTick), length)));
- }
- const auto tps = ticksPerSample (bpm, sampleRate);
- expectedTick = startTick + numSamples * tps;
- for (auto* queue : { live, moreLive })
- {
- if (queue == nullptr)
- continue;
- NoteEvent e;
- while (queue->pop (e))
- {
- if (e.type == NoteEvent::Type::choke && e.channel < 0) // panic: every channel stops sounding
- {
- for (auto& instrument : state->instruments)
- if (instrument != nullptr)
- instrument->allNotesOff();
- continue;
- }
- if (e.channel < 0 || e.channel >= (int) state->instruments.size())
- continue;
- auto& instrument = *state->instruments[(std::size_t) e.channel];
- if (e.type == NoteEvent::Type::on)
- instrument.noteOn (e.key, e.velocity);
- else
- instrument.noteOff (e.key);
- }
- }
- // Blocks larger than the mixer buffers are done in pieces. With automation, small
- // pieces so values move smoothly.
- const auto chunk = std::min (blockCapacity, state->hasAutomation ? 128 : chunkCapacity);
- for (int done = 0; done < numSamples; done += chunk)
- {
- const auto n = std::min (chunk, numSamples - done);
- processChunk (*state, playing, startTick + done * tps, n, left + done, right + done, meters);
- resumeAudio = false;
- }
- }
- void RackRenderer::processChunk (const RackState& state, bool playing, double startTick, int numSamples,
- float* left, float* right, MeterBank* meters) noexcept
- {
- chunkTick = startTick;
- const auto& song = state.song;
- const auto tracks = std::max<int> (1, (int) song.mixer.size());
- if (state.hasAutomation)
- updateAutomation (state, startTick);
- chunkStartTick = startTick;
- chunkTps = ticksPerSample (bpm, sampleRate);
- for (int t = 0; t < tracks; ++t)
- {
- std::memset (trackBuffer (t, 0), 0, sizeof (float) * (std::size_t) numSamples);
- std::memset (trackBuffer (t, 1), 0, sizeof (float) * (std::size_t) numSamples);
- }
- events.clear();
- if (playing && song.mode == PlayMode::song)
- {
- scheduleSong (song, startTick, numSamples, ticksPerSample (bpm, sampleRate), events, resumeAudio, &state.schedule);
- }
- else if (playing && ! song.patterns.empty())
- {
- const auto patternIndex = std::clamp (song.currentPattern, 0, (int) song.patterns.size() - 1);
- const auto& pattern = song.patterns[(std::size_t) patternIndex];
- schedulePatternLoop (pattern, pattern.effectiveLength (song.beatsPerBar), startTick, numSamples,
- ticksPerSample (bpm, sampleRate), events, song.swing, &song.channels);
- }
- // cut groups: each note of a channel "cuts" the channels linked to it, at the same sample
- if (state.hasCutGroups)
- {
- const auto count = events.size();
- for (int i = 0; i < count; ++i)
- {
- const auto e = events[i];
- if (e.type != NoteEvent::Type::on || e.channel < 0 || e.channel >= (int) state.cutTargets.size())
- continue;
- for (auto target : state.cutTargets[(std::size_t) e.channel])
- {
- NoteEvent choke;
- choke.type = NoteEvent::Type::choke;
- choke.channel = target;
- choke.sampleOffset = e.sampleOffset;
- events.add (choke);
- }
- }
- events.sortByOffset();
- }
- // 1) channels, each with its own notes at the exact sample (in parallel when worth it)
- const auto channels = std::min<int> ({ (int) state.instruments.size(), (int) song.channels.size(), maxChannels });
- auto channel = [this, &state, numSamples] (int c) { renderChannel (state, c, numSamples); };
- if (workers != nullptr && state.parallel)
- workers->parallelFor (channels, channel);
- else
- for (int c = 0; c < channels; ++c)
- channel (c);
- for (int c = 0; c < channels; ++c)
- {
- if (channelSilent[(std::size_t) c])
- continue;
- const auto t = std::clamp (song.channels[(std::size_t) c].mixerTrack, 0, tracks - 1);
- auto* dl = trackBuffer (t, 0);
- auto* dr = trackBuffer (t, 1);
- const auto* sl = channelBuffer (c, 0);
- const auto* sr = channelBuffer (c, 1);
- for (int k = 0; k < numSamples; ++k)
- {
- dl[k] += sl[k];
- dr[k] += sr[k];
- }
- }
- // 2) inserts by layers: within a layer nothing depends on anything else; each track pulls the
- // outputs of the tracks that send to it (without writing into others' buffers)
- trackActive.fill (0);
- for (const auto& layer : state.mixerLayers)
- {
- auto track = [this, &state, &layer, numSamples, meters] (int i) { processTrack (state, layer[(std::size_t) i], numSamples, meters); };
- if (workers != nullptr && state.parallel && layer.size() > 1)
- workers->parallelFor ((int) layer.size(), track);
- else
- for (int i = 0; i < (int) layer.size(); ++i)
- track (i);
- }
- // 3) Master: inputs, effects, fader. Without a configured mixer, it stays at 0 dB.
- pullInputs (state, 0, numSamples);
- runEffects (state, 0, numSamples);
- if (! song.mixer.empty())
- {
- applyTrackEq (song.mixer[0], 0, trackBuffer (0, 0), trackBuffer (0, 1), numSamples);
- applyStereo (song.mixer[0], trackBuffer (0, 0), trackBuffer (0, 1), numSamples);
- }
- float gl = 1.0f, gr = 1.0f;
- if (! song.mixer.empty())
- {
- const auto& master = song.mixer[0];
- const auto volume = state.hasAutomation ? automated (state.mixerVolumeAuto[0], master.volume) : master.volume;
- const auto pan = state.hasAutomation ? automated (state.mixerPanAuto[0], (master.pan + 1.0f) * 0.5f) * 2.0f - 1.0f : master.pan;
- panGains (pan, master.muted ? 0.0f : faderGain (volume), gl, gr);
- }
- auto& lastL = lastTrackGain[0];
- auto& lastR = lastTrackGain[1];
- const auto fromL = std::isnan (lastL) ? gl : lastL;
- const auto fromR = std::isnan (lastR) ? gr : lastR;
- lastL = gl;
- lastR = gr;
- const auto stepL = (gl - fromL) / (float) numSamples, stepR = (gr - fromR) / (float) numSamples;
- const auto* masterL = trackBuffer (0, 0);
- const auto* masterR = trackBuffer (0, 1);
- for (int i = 0; i < numSamples; ++i)
- {
- left[i] = masterL[i] * (fromL + stepL * (float) (i + 1));
- right[i] = masterR[i] * (fromR + stepR * (float) (i + 1));
- }
- if (meters != nullptr)
- meters->accumulate (0, peakOf (left, numSamples), peakOf (right, numSamples));
- }
- // Track stereo separation, phase and channel swap (before the fader, like FL).
- // Narrowing uses FL's exponential curve, widening is linear (docs/analise/REA_rodada2.md §2.2).
- void RackRenderer::applyStereo (const MixerTrack& track, float* l, float* r, int n) noexcept
- {
- if (track.stereo != 0.0f)
- {
- const auto s = track.stereo > 0.0f ? (std::pow (5.0f, std::min (track.stereo, 1.0f)) - 1.0f) / 4.0f
- : std::max (track.stereo, -1.0f);
- // s = 1: mono; s = -1: side doubled
- const auto keep = 1.0f - 0.5f * s, cross = 0.5f * s;
- for (int i = 0; i < n; ++i)
- {
- const auto a = l[i], b = r[i];
- l[i] = keep * a + cross * b;
- r[i] = keep * b + cross * a;
- }
- }
- if (track.swapChannels)
- for (int i = 0; i < n; ++i)
- std::swap (l[i], r[i]);
- if (track.invertPhase)
- for (int i = 0; i < n; ++i)
- {
- l[i] = -l[i];
- r[i] = -r[i];
- }
- }
- void RackRenderer::pullInputs (const RackState& state, int t, int n) noexcept
- {
- if ((std::size_t) t >= state.mixerInputs.size())
- return;
- auto* dl = trackBuffer (t, 0);
- auto* dr = trackBuffer (t, 1);
- for (const auto& in : state.mixerInputs[(std::size_t) t])
- {
- const auto active = trackActive[(std::size_t) in.source];
- const auto& delays = state.sendDelays[(std::size_t) in.source];
- auto* delay = (std::size_t) in.delay < delays.size() ? delays[(std::size_t) in.delay].get() : nullptr;
- if (delay != nullptr)
- {
- // PDC: this edge is shorter than the slowest one arriving here. A silent source
- // still drains the tail that was in the line.
- delay->mixInto (active ? trackBuffer (in.source, 0) : nullptr, active ? trackBuffer (in.source, 1) : nullptr,
- in.level, dl, dr, n);
- continue;
- }
- if (! active)
- continue;
- const auto* sl = trackBuffer (in.source, 0);
- const auto* sr = trackBuffer (in.source, 1);
- for (int i = 0; i < n; ++i)
- {
- dl[i] += sl[i] * in.level;
- dr[i] += sr[i] * in.level;
- }
- }
- }
- void RackRenderer::processTrack (const RackState& state, int t, int n, MeterBank* meters) noexcept
- {
- const auto& track = state.song.mixer[(std::size_t) t];
- pullInputs (state, t, n);
- const auto silent = track.muted || ! state.mixerAudible[(std::size_t) t];
- // target gain; the ramp from the previous block avoids clicks on mute and fader
- float gl = 0.0f, gr = 0.0f;
- if (! silent)
- {
- const auto volume = state.hasAutomation ? automated (state.mixerVolumeAuto[(std::size_t) t], track.volume) : track.volume;
- const auto pan = state.hasAutomation ? automated (state.mixerPanAuto[(std::size_t) t], (track.pan + 1.0f) * 0.5f) * 2.0f - 1.0f
- : track.pan;
- panGains (pan, faderGain (volume), gl, gr);
- }
- auto& lastL = lastTrackGain[(std::size_t) t * 2];
- auto& lastR = lastTrackGain[(std::size_t) t * 2 + 1];
- const auto fromL = std::isnan (lastL) ? gl : lastL;
- const auto fromR = std::isnan (lastR) ? gr : lastR;
- lastL = gl;
- lastR = gr;
- if (silent && fromL == 0.0f && fromR == 0.0f)
- return; // stays inactive: nobody pulls anything from it
- runEffects (state, t, n);
- auto* l = trackBuffer (t, 0);
- auto* r = trackBuffer (t, 1);
- applyTrackEq (track, t, l, r, n);
- applyStereo (track, l, r, n);
- const auto stepL = (gl - fromL) / (float) n, stepR = (gr - fromR) / (float) n;
- for (int i = 0; i < n; ++i)
- {
- l[i] *= fromL + stepL * (float) (i + 1);
- r[i] *= fromR + stepR * (float) (i + 1);
- }
- trackActive[(std::size_t) t] = 1;
- if (meters != nullptr)
- meters->accumulate (t, peakOf (l, n), peakOf (r, n));
- }
- } // namespace lynx
|