RackRenderer.cpp 45 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208
  1. #include "core/RackRenderer.h"
  2. #include "core/WorkerPool.h"
  3. #include "core/Denormals.h"
  4. #include <algorithm>
  5. #include <cmath>
  6. #include <cstring>
  7. #include <limits>
  8. namespace lynx
  9. {
  10. namespace
  11. {
  12. // Silent instrument: plugin channel that could not be loaded.
  13. class SilentInstrument final : public Instrument
  14. {
  15. public:
  16. void prepare (double) noexcept override {}
  17. void noteOn (int, float) noexcept override {}
  18. void noteOff (int) noexcept override {}
  19. void allNotesOff() noexcept override {}
  20. void render (float*, float*, int, float, float) noexcept override {}
  21. };
  22. // Effect that does nothing: missing plugin slot.
  23. class BypassEffect final : public Effect
  24. {
  25. public:
  26. void prepare (double) noexcept override {}
  27. void reset() noexcept override {}
  28. void process (float*, float*, int, const EffectParams&, double) noexcept override {}
  29. };
  30. } // namespace
  31. std::unique_ptr<const RackState> RackState::build (Song song,
  32. const RackState* previous,
  33. double sampleRate,
  34. const SampleProvider& samples)
  35. {
  36. Factories factories;
  37. factories.samples = samples;
  38. return build (std::move (song), previous, sampleRate, factories);
  39. }
  40. std::unique_ptr<const RackState> RackState::build (Song song,
  41. const RackState* previous,
  42. double sampleRate,
  43. const Factories& factories)
  44. {
  45. const auto& samples = factories.samples;
  46. auto state = std::make_unique<RackState>();
  47. state->instruments.reserve (song.channels.size());
  48. for (std::size_t i = 0; i < song.channels.size(); ++i)
  49. {
  50. const auto& channel = song.channels[i];
  51. const auto kind = channel.instrument;
  52. if (previous != nullptr && i < previous->song.channels.size() && i < previous->instruments.size()
  53. && previous->song.channels[i].instrument == kind
  54. && ((kind != InstrumentKind::sampler && kind != InstrumentKind::audioClip)
  55. || (previous->song.channels[i].samplePath == channel.samplePath && previous->song.channels[i].zones == channel.zones
  56. && previous->song.channels[i].sampler.keepPitch == channel.sampler.keepPitch
  57. && (! channel.sampler.keepPitch
  58. || (previous->song.channels[i].sampler.stretchBeats == channel.sampler.stretchBeats
  59. && previous->song.bpm == song.bpm))))
  60. && (kind != InstrumentKind::plugin
  61. || (previous->song.channels[i].plugin.id == channel.plugin.id && previous->sampleRate == sampleRate)))
  62. {
  63. state->instruments.push_back (previous->instruments[i]);
  64. state->instruments.back()->configure (channel, song.bpm);
  65. continue;
  66. }
  67. if (kind == InstrumentKind::plugin)
  68. {
  69. std::shared_ptr<Instrument> instrument;
  70. if (factories.pluginInstruments && ! channel.plugin.id.empty())
  71. instrument = factories.pluginInstruments (channel.plugin, sampleRate);
  72. state->instruments.push_back (instrument != nullptr ? instrument : std::make_shared<SilentInstrument>());
  73. continue;
  74. }
  75. // multi-sample sampler: one zone per sample (DirectWave, FPC layers...)
  76. if (kind == InstrumentKind::sampler && ! channel.zones.empty())
  77. {
  78. std::vector<LoadedZone> zones;
  79. for (const auto& z : channel.zones)
  80. zones.push_back ({ z, samples ? samples (z.path) : nullptr });
  81. std::shared_ptr<Instrument> instrument = makeZonedSampler (std::move (zones));
  82. instrument->prepare (sampleRate);
  83. instrument->configure (channel, song.bpm);
  84. state->instruments.push_back (std::move (instrument));
  85. continue;
  86. }
  87. std::shared_ptr<const SampleData> sample;
  88. if ((kind == InstrumentKind::sampler || kind == InstrumentKind::audioClip) && samples && ! channel.samplePath.empty())
  89. sample = samples (channel.samplePath);
  90. // pitch-preserving stretch: the sample comes already stretched to the current tempo
  91. if (sample != nullptr && channel.sampler.keepPitch && channel.sampler.stretchBeats > 0.0f && factories.stretchedSamples
  92. && sample->frames() > 0)
  93. {
  94. const auto target = channel.sampler.stretchBeats * 60.0 / std::max (1.0, song.bpm);
  95. const auto ratio = target / ((double) sample->frames() / sample->sampleRate);
  96. if (auto stretched = factories.stretchedSamples (channel.samplePath, ratio))
  97. sample = std::move (stretched);
  98. }
  99. std::shared_ptr<Instrument> instrument = makeInstrument (kind, std::move (sample));
  100. instrument->prepare (sampleRate);
  101. instrument->configure (channel, song.bpm);
  102. state->instruments.push_back (std::move (instrument));
  103. }
  104. state->effects.resize (song.mixer.size());
  105. for (std::size_t t = 0; t < song.mixer.size(); ++t)
  106. {
  107. const auto& slots = song.mixer[t].effects;
  108. for (std::size_t i = 0; i < slots.size() && i < (std::size_t) maxEffectSlots; ++i)
  109. {
  110. const auto kind = slots[i].kind;
  111. if (previous != nullptr && t < previous->song.mixer.size() && t < previous->effects.size()
  112. && i < previous->song.mixer[t].effects.size() && i < previous->effects[t].size()
  113. && previous->song.mixer[t].effects[i].kind == kind && kind != EffectKind::parallel // the container is rebuilt
  114. && previous->song.mixer[t].effects[i].state == slots[i].state
  115. && (kind != EffectKind::plugin
  116. || (previous->song.mixer[t].effects[i].plugin.id == slots[i].plugin.id && previous->sampleRate == sampleRate)))
  117. {
  118. state->effects[t].push_back (previous->effects[t][i]);
  119. continue;
  120. }
  121. std::shared_ptr<Effect> effect;
  122. if (kind == EffectKind::plugin)
  123. {
  124. if (factories.pluginEffects && ! slots[i].plugin.id.empty())
  125. effect = factories.pluginEffects (slots[i].plugin, sampleRate);
  126. if (effect == nullptr)
  127. effect = std::make_shared<BypassEffect>();
  128. }
  129. else
  130. {
  131. effect = makeEffect (slots[i]);
  132. effect->prepare (sampleRate);
  133. }
  134. state->effects[t].push_back (std::move (effect));
  135. }
  136. }
  137. state->song = std::move (song);
  138. // scheduling: notes sorted by start (order among notes on the same tick is preserved)
  139. for (auto& p : state->song.patterns)
  140. std::stable_sort (p.notes.begin(), p.notes.end(), [] (const Note& a, const Note& b) { return a.start < b.start; });
  141. state->schedule = makeScheduleIndex (state->song);
  142. state->sampleRate = sampleRate;
  143. state->buildAutomationTables();
  144. state->buildPdc (previous);
  145. state->buildMixerGraph();
  146. const auto& channels = state->song.channels;
  147. state->cutTargets.assign (channels.size(), {});
  148. state->arpeggiators.assign (channels.size(), nullptr);
  149. for (std::size_t c = 0; c < channels.size(); ++c)
  150. if (channels[c].arp.enabled())
  151. state->arpeggiators[c] = previous != nullptr && c < previous->arpeggiators.size() && previous->arpeggiators[c] != nullptr
  152. ? previous->arpeggiators[c]
  153. : std::make_shared<Arpeggiator>();
  154. for (std::size_t c = 0; c < channels.size(); ++c)
  155. if (channels[c].cutGroup > 0)
  156. for (std::size_t d = 0; d < channels.size(); ++d)
  157. if (channels[d].cutBy == channels[c].cutGroup)
  158. {
  159. state->cutTargets[c].push_back ((int) d);
  160. state->hasCutGroups = true;
  161. }
  162. const auto audible = state->song.soloAudible();
  163. state->mixerAudible.assign (audible.begin(), audible.end());
  164. return state;
  165. }
  166. void RackState::buildMixerGraph()
  167. {
  168. mixerOrder = song.mixerOrder();
  169. const auto audible = song.soloAudible();
  170. mixerAudible.assign (audible.begin(), audible.end());
  171. const auto tracks = std::max<int> (1, (int) song.mixer.size());
  172. mixerInputs.assign ((std::size_t) tracks, {});
  173. std::vector<int> depth ((std::size_t) tracks, 0);
  174. // who listens to each track via sidechain (the source goes in an earlier layer)
  175. std::vector<std::vector<int>> sidechainListeners ((std::size_t) tracks);
  176. for (int t = 1; t < tracks; ++t)
  177. for (const auto& fx : song.mixer[(std::size_t) t].effects)
  178. for (const auto source : { fx.sidechain, fx.sidechain2 })
  179. if (source > 0 && source < tracks && source != t)
  180. sidechainListeners[(std::size_t) source].push_back (t);
  181. for (auto t : mixerOrder) // sources before destinations: the depth is already computed
  182. {
  183. const auto& track = song.mixer[(std::size_t) t];
  184. for (const auto listener : sidechainListeners[(std::size_t) t])
  185. depth[(std::size_t) listener] = std::max (depth[(std::size_t) listener], depth[(std::size_t) t] + 1);
  186. if (track.toMaster)
  187. mixerInputs[0].push_back ({ t, 0, 1.0f });
  188. for (std::size_t k = 0; k < track.sends.size(); ++k)
  189. {
  190. const auto& send = track.sends[k];
  191. if (send.target > 0 && send.target < tracks && send.target != t && send.level > 0.0f)
  192. {
  193. mixerInputs[(std::size_t) send.target].push_back ({ t, (int) k + 1, send.level });
  194. depth[(std::size_t) send.target] = std::max (depth[(std::size_t) send.target], depth[(std::size_t) t] + 1);
  195. }
  196. }
  197. }
  198. mixerLayers.clear();
  199. for (auto t : mixerOrder)
  200. {
  201. const auto d = (std::size_t) depth[(std::size_t) t];
  202. if (mixerLayers.size() <= d)
  203. mixerLayers.resize (d + 1);
  204. mixerLayers[d].push_back (t);
  205. }
  206. // splitting across threads costs a few microseconds per block; only worth it with plugins or many channels
  207. const auto plugins = std::count_if (song.channels.begin(), song.channels.end(),
  208. [] (const ChannelDef& c) { return c.instrument == InstrumentKind::plugin; });
  209. auto pluginEffects = 0;
  210. for (const auto& t : song.mixer)
  211. pluginEffects += (int) std::count_if (t.effects.begin(), t.effects.end(), [] (const EffectSlot& e) { return e.kind == EffectKind::plugin; });
  212. parallel = plugins + pluginEffects >= 2 || song.channels.size() >= 24;
  213. }
  214. std::vector<int> RackState::currentLatencies() const
  215. {
  216. std::vector<int> out;
  217. for (const auto& i : instruments)
  218. out.push_back (i->latencySamples());
  219. for (const auto& track : effects)
  220. for (const auto& e : track)
  221. out.push_back (e->latencySamples());
  222. return out;
  223. }
  224. void RackState::buildPdc (const RackState* previous)
  225. {
  226. latencies = currentLatencies();
  227. std::vector<int> channelLatency (latencies.begin(), latencies.begin() + (std::ptrdiff_t) instruments.size());
  228. std::vector<std::vector<int>> slotLatency (effects.size());
  229. auto next = latencies.begin() + (std::ptrdiff_t) instruments.size();
  230. for (std::size_t t = 0; t < effects.size(); ++t)
  231. for (std::size_t s = 0; s < effects[t].size(); ++s)
  232. slotLatency[t].push_back (*next++);
  233. pdc = computePdc (song, channelLatency, slotLatency);
  234. // reuses lines of the same length: editing the song must not click the audio
  235. auto line = [] (int length, const std::shared_ptr<DelayLine>* old) -> std::shared_ptr<DelayLine> {
  236. if (length <= 0)
  237. return nullptr;
  238. if (old != nullptr && *old != nullptr && (*old)->length() == length)
  239. return *old;
  240. return std::make_shared<DelayLine> (length);
  241. };
  242. channelDelays.resize (pdc.channelDelay.size());
  243. for (std::size_t c = 0; c < pdc.channelDelay.size(); ++c)
  244. channelDelays[c] = line (pdc.channelDelay[c],
  245. previous != nullptr && c < previous->channelDelays.size() ? &previous->channelDelays[c] : nullptr);
  246. sendDelays.resize (pdc.sendDelay.size());
  247. for (std::size_t t = 0; t < pdc.sendDelay.size(); ++t)
  248. {
  249. sendDelays[t].resize (pdc.sendDelay[t].size());
  250. for (std::size_t k = 0; k < pdc.sendDelay[t].size(); ++k)
  251. {
  252. const std::shared_ptr<DelayLine>* old = nullptr;
  253. if (previous != nullptr && t < previous->sendDelays.size() && k < previous->sendDelays[t].size())
  254. old = &previous->sendDelays[t][k];
  255. sendDelays[t][k] = line (pdc.sendDelay[t][k], old);
  256. }
  257. }
  258. }
  259. void RackState::buildAutomationTables()
  260. {
  261. const auto& automations = song.automations;
  262. const auto count = std::min<int> ((int) automations.size(), maxAutomations);
  263. automationClips.assign ((std::size_t) count, {});
  264. for (int i = 0; i < (int) song.playlist.size(); ++i)
  265. {
  266. const auto& c = song.playlist[(std::size_t) i];
  267. if (c.kind == ClipKind::automation && c.automation >= 0 && c.automation < count && c.length > 0 && ! c.muted && ! song.isTrackMuted (c.track))
  268. automationClips[(std::size_t) c.automation].push_back (i);
  269. }
  270. for (auto& clips : automationClips)
  271. std::sort (clips.begin(), clips.end(),
  272. [this] (int a, int b) { return song.playlist[(std::size_t) a].start < song.playlist[(std::size_t) b].start; });
  273. liveAutomations.clear();
  274. for (int a = 0; a < count; ++a)
  275. if (automations[(std::size_t) a].isLive())
  276. liveAutomations.push_back (a);
  277. channelVolumeAuto.assign (song.channels.size(), -1);
  278. channelPanAuto.assign (song.channels.size(), -1);
  279. mixerVolumeAuto.assign (song.mixer.size(), -1);
  280. mixerPanAuto.assign (song.mixer.size(), -1);
  281. effectParamAuto.assign (song.mixer.size(), {});
  282. effectMixAuto.assign (song.mixer.size(), {});
  283. for (std::size_t t = 0; t < song.mixer.size(); ++t)
  284. {
  285. std::array<int, maxEffectParams> none;
  286. none.fill (-1);
  287. effectParamAuto[t].assign (song.mixer[t].effects.size(), none);
  288. effectMixAuto[t].assign (song.mixer[t].effects.size(), -1);
  289. }
  290. pluginParams.clear();
  291. hasAutomation = false;
  292. tempoAutomation = -1;
  293. // the last automation of the same target wins
  294. for (int a = 0; a < count; ++a)
  295. {
  296. if (automationClips[(std::size_t) a].empty() && ! automations[(std::size_t) a].isLive())
  297. continue;
  298. const auto& t = automations[(std::size_t) a].target;
  299. const auto channelOk = t.index >= 0 && t.index < (int) song.channels.size();
  300. const auto trackOk = t.index >= 0 && t.index < (int) song.mixer.size();
  301. auto used = true;
  302. switch (t.kind)
  303. {
  304. case AutomationTargetKind::channelVolume: if (channelOk) channelVolumeAuto[(std::size_t) t.index] = a; else used = false; break;
  305. case AutomationTargetKind::channelPan: if (channelOk) channelPanAuto[(std::size_t) t.index] = a; else used = false; break;
  306. case AutomationTargetKind::mixerVolume: if (trackOk) mixerVolumeAuto[(std::size_t) t.index] = a; else used = false; break;
  307. case AutomationTargetKind::mixerPan: if (trackOk) mixerPanAuto[(std::size_t) t.index] = a; else used = false; break;
  308. case AutomationTargetKind::channelParam:
  309. if (channelOk && song.channels[(std::size_t) t.index].instrument == InstrumentKind::plugin)
  310. pluginParams.push_back ({ a, t.index, 0, 0, t.param });
  311. else
  312. used = false;
  313. break;
  314. case AutomationTargetKind::effectParam:
  315. {
  316. const auto slotOk = trackOk && t.slot >= 0 && t.slot < (int) song.mixer[(std::size_t) t.index].effects.size();
  317. if (! slotOk)
  318. used = false;
  319. else if (song.mixer[(std::size_t) t.index].effects[(std::size_t) t.slot].kind == EffectKind::plugin)
  320. pluginParams.push_back ({ a, -1, t.index, t.slot, t.param });
  321. else if (t.param >= 0 && t.param < maxEffectParams)
  322. effectParamAuto[(std::size_t) t.index][(std::size_t) t.slot][(std::size_t) t.param] = a;
  323. else
  324. used = false;
  325. break;
  326. }
  327. case AutomationTargetKind::effectMix:
  328. if (trackOk && t.slot >= 0 && t.slot < (int) song.mixer[(std::size_t) t.index].effects.size())
  329. effectMixAuto[(std::size_t) t.index][(std::size_t) t.slot] = a;
  330. else
  331. used = false;
  332. break;
  333. case AutomationTargetKind::tempo: tempoAutomation = a; break;
  334. case AutomationTargetKind::none: used = false; break;
  335. }
  336. hasAutomation = hasAutomation || used;
  337. }
  338. }
  339. namespace
  340. {
  341. // Constant-power pan: at center both sides are 1 (0 dB).
  342. void panGains (float pan, float gain, float& left, float& right) noexcept
  343. {
  344. const auto angle = (pan + 1.0f) * 0.25f * 3.14159265f;
  345. left = gain * std::cos (angle) * 1.41421356f;
  346. right = gain * std::sin (angle) * 1.41421356f;
  347. }
  348. float peakOf (const float* data, int n) noexcept
  349. {
  350. float peak = 0.0f;
  351. for (int i = 0; i < n; ++i)
  352. {
  353. const auto a = std::abs (data[i]);
  354. peak = a > peak ? a : peak; // form the compiler vectorizes
  355. }
  356. return peak;
  357. }
  358. // Any sample above `level`? Stops at the first: with sound (the common case) it costs almost nothing.
  359. bool anyAbove (const float* l, const float* r, int n, float level) noexcept
  360. {
  361. // in blocks of 32: the inner loop vectorizes; silent chunks (the ones that scan everything) stay cheap
  362. int i = 0;
  363. for (; i + 32 <= n; i += 32)
  364. {
  365. float m = 0.0f;
  366. for (int k = i; k < i + 32; ++k)
  367. {
  368. const auto a = std::abs (l[k]), b = std::abs (r[k]);
  369. m = a > m ? a : m;
  370. m = b > m ? b : m;
  371. }
  372. if (m > level)
  373. return true;
  374. }
  375. for (; i < n; ++i)
  376. if (std::abs (l[i]) > level || std::abs (r[i]) > level)
  377. return true;
  378. return false;
  379. }
  380. } // namespace
  381. void RackRenderer::prepare (double sr, int maxBlockSize)
  382. {
  383. automationValues.fill (std::numeric_limits<float>::quiet_NaN());
  384. lastTrackGain.fill (std::numeric_limits<float>::quiet_NaN());
  385. channelBuffers.assign ((std::size_t) maxChannels * 2 * chunkCapacity, 0.0f);
  386. smartDisable.assign ((std::size_t) maxMixerTracks * maxEffectSlots, {});
  387. trackEqs.assign ((std::size_t) maxMixerTracks, {});
  388. trackScratchBuffers.assign ((std::size_t) maxMixerTracks * 2 * chunkCapacity, 0.0f);
  389. sampleRate = sr;
  390. blockCapacity = std::max (64, maxBlockSize);
  391. mixBuffers.assign ((std::size_t) maxMixerTracks * 2 * (std::size_t) blockCapacity, 0.0f);
  392. if (lastState != nullptr)
  393. {
  394. for (auto& instrument : lastState->instruments)
  395. instrument->prepare (sr);
  396. for (auto& track : lastState->effects)
  397. for (auto& effect : track)
  398. effect->prepare (sr);
  399. }
  400. }
  401. float* RackRenderer::trackBuffer (int track, int channel) noexcept
  402. {
  403. return mixBuffers.data() + ((std::size_t) track * 2 + (std::size_t) channel) * (std::size_t) blockCapacity;
  404. }
  405. float RackRenderer::automated (int automation, float base) const noexcept
  406. {
  407. if (automation < 0)
  408. return base;
  409. const auto v = automationValues[(std::size_t) automation];
  410. return std::isnan (v) ? base : v;
  411. }
  412. namespace
  413. {
  414. // Value of an automation at a song position: inside a clip, the curve; between clips,
  415. // the last value of the previous clip; before the first, its initial value. Depends only on
  416. // position, so playing from any point (or exporting) gives the same result.
  417. float automationValueAt (const Song& song, const Automation& automation, const std::vector<int>& clips, double tick) noexcept
  418. {
  419. const Clip* before = nullptr;
  420. for (auto i : clips) // sorted by start
  421. {
  422. const auto& c = song.playlist[(std::size_t) i];
  423. if (tick < (double) c.start)
  424. break;
  425. if (tick < (double) c.end())
  426. return automation.valueAt (tick - (double) c.start + (double) c.offset);
  427. before = &c;
  428. }
  429. if (before != nullptr)
  430. return automation.valueAt ((double) (before->length + before->offset));
  431. const auto& first = song.playlist[(std::size_t) clips.front()];
  432. return automation.valueAt ((double) first.offset);
  433. }
  434. } // namespace
  435. void RackRenderer::updateAutomation (const RackState& state, double startTick) noexcept
  436. {
  437. const auto& song = state.song;
  438. // controllers (live sources): the effect's output at the end of the previous block, in any mode
  439. for (const auto a : state.liveAutomations)
  440. {
  441. const auto& automation = song.automations[(std::size_t) a];
  442. const auto& src = automation.source;
  443. if (src.channel >= 0)
  444. {
  445. if (src.channel < (int) state.instruments.size() && state.instruments[(std::size_t) src.channel] != nullptr)
  446. automationValues[(std::size_t) a] = automation.mapLive (state.instruments[(std::size_t) src.channel]->controlOutput (src.output));
  447. }
  448. else if (src.track < (int) state.effects.size() && src.slot >= 0 && src.slot < (int) state.effects[(std::size_t) src.track].size()
  449. && state.effects[(std::size_t) src.track][(std::size_t) src.slot] != nullptr)
  450. automationValues[(std::size_t) a] = automation.mapLive (state.effects[(std::size_t) src.track][(std::size_t) src.slot]->controlOutput (src.output));
  451. }
  452. // in pattern mode the Playlist does not play: values stay as they were
  453. if (song.mode != PlayMode::song)
  454. return;
  455. const auto length = (double) std::max<std::int64_t> (1, state.schedule.songLength);
  456. const auto tick = std::fmod (std::max (0.0, startTick), length);
  457. for (std::size_t a = 0; a < state.automationClips.size(); ++a)
  458. if (! state.automationClips[a].empty())
  459. automationValues[a] = automationValueAt (song, song.automations[a], state.automationClips[a], tick);
  460. for (const auto& b : state.pluginParams)
  461. {
  462. const auto v = automationValues[(std::size_t) b.automation];
  463. if (std::isnan (v))
  464. continue;
  465. if (b.channel >= 0)
  466. {
  467. if (b.channel < (int) state.instruments.size())
  468. state.instruments[(std::size_t) b.channel]->setParameter (b.param, v);
  469. }
  470. else if (b.track < (int) state.effects.size() && b.slot < (int) state.effects[(std::size_t) b.track].size())
  471. state.effects[(std::size_t) b.track][(std::size_t) b.slot]->setParameter (b.param, v);
  472. }
  473. }
  474. float* RackRenderer::channelBuffer (int channel, int side) noexcept
  475. {
  476. return channelBuffers.data() + ((std::size_t) channel * 2 + (std::size_t) side) * chunkCapacity;
  477. }
  478. float* RackRenderer::trackScratch (int track, int side) noexcept
  479. {
  480. return trackScratchBuffers.data() + ((std::size_t) track * 2 + (std::size_t) side) * chunkCapacity;
  481. }
  482. // A whole channel over the chunk: notes at the exact sample (only its own events), volume/pan and the
  483. // PDC delay. Each channel only touches its own instrument and buffer: it can run in parallel.
  484. void RackRenderer::renderChannel (const RackState& state, int i, int n) noexcept
  485. {
  486. const auto& c = state.song.channels[(std::size_t) i];
  487. const auto automation = state.hasAutomation;
  488. const auto volume = channelGain (automation ? automated (state.channelVolumeAuto[(std::size_t) i], c.volume) : c.volume);
  489. const auto pan = automation ? automated (state.channelPanAuto[(std::size_t) i], (c.pan + 1.0f) * 0.5f) * 2.0f - 1.0f : c.pan;
  490. float gl = 0.0f, gr = 0.0f;
  491. panGains (pan, volume, gl, gr);
  492. auto* l = channelBuffer (i, 0);
  493. auto* r = channelBuffer (i, 1);
  494. if ((std::size_t) i < state.instruments.size() && state.instruments[(std::size_t) i] != nullptr)
  495. state.instruments[(std::size_t) i]->setSongPosition (chunkTick);
  496. auto& instrument = *state.instruments[(std::size_t) i];
  497. // idle channel, no notes in this chunk and no PDC: nothing to do (neither clear nor sum into the mixer)
  498. const auto hasDelay = (std::size_t) i < state.channelDelays.size() && state.channelDelays[(std::size_t) i] != nullptr;
  499. const auto hasArp = (std::size_t) i < state.arpeggiators.size() && state.arpeggiators[(std::size_t) i] != nullptr;
  500. if (! hasDelay && ! hasArp && instrument.idle()
  501. && std::none_of (events.begin(), events.end(), [i] (const NoteEvent& e) { return e.channel == i; }))
  502. {
  503. channelSilent[(std::size_t) i] = 1;
  504. return;
  505. }
  506. channelSilent[(std::size_t) i] = 0;
  507. std::memset (l, 0, sizeof (float) * (std::size_t) n);
  508. std::memset (r, 0, sizeof (float) * (std::size_t) n);
  509. int position = 0;
  510. // arpeggiator: the channel's notes become the arpeggio sequence
  511. const NoteEvent* list = events.begin();
  512. int listCount = events.size();
  513. if ((std::size_t) i < state.arpeggiators.size() && state.arpeggiators[(std::size_t) i] != nullptr)
  514. {
  515. auto& arp = *state.arpeggiators[(std::size_t) i];
  516. int inCount = 0;
  517. for (const auto& e : events)
  518. if (e.channel == i && inCount < Arpeggiator::maxEvents)
  519. arp.input[(std::size_t) inCount++] = e;
  520. int outCount = 0;
  521. arp.process (i, arp.input.data(), inCount, chunkStartTick, chunkTps, n, c.arp, arp.output.data(), outCount);
  522. list = arp.output.data();
  523. listCount = outCount;
  524. }
  525. for (int index = 0; index < listCount; ++index)
  526. {
  527. const auto& e = list[index];
  528. if (e.channel != i)
  529. continue;
  530. if (e.sampleOffset > position)
  531. {
  532. instrument.render (l + position, r + position, e.sampleOffset - position, gl, gr);
  533. position = e.sampleOffset;
  534. }
  535. if (e.type == NoteEvent::Type::on)
  536. {
  537. if (! c.muted)
  538. {
  539. instrument.setNextNoteExpression (e.pan, e.cents + state.song.masterPitch, e.porta);
  540. if (e.fadeIn > 0.0f || e.fadeOut > 0.0f)
  541. instrument.setNextClipFades (e.clipElapsed, e.clipRemaining, e.fadeIn, e.fadeOut);
  542. instrument.noteOnAt (e.key, e.velocity, e.startSeconds);
  543. }
  544. }
  545. else if (e.type == NoteEvent::Type::slide)
  546. {
  547. instrument.slideTo (e.key, e.cents + state.song.masterPitch, e.slideSamples);
  548. }
  549. else if (e.type == NoteEvent::Type::choke)
  550. {
  551. instrument.allNotesOff(); // short fade, like FL's "cut"
  552. }
  553. else
  554. instrument.noteOff (e.key);
  555. }
  556. if (position < n)
  557. instrument.render (l + position, r + position, n - position, gl, gr);
  558. // PDC: this channel arrives before the track's others; delay until aligned
  559. if ((std::size_t) i < state.channelDelays.size() && state.channelDelays[(std::size_t) i] != nullptr)
  560. state.channelDelays[(std::size_t) i]->process (l, r, n);
  561. }
  562. void RackRenderer::applyTrackEq (const MixerTrack& track, int t, float* l, float* r, int n) noexcept
  563. {
  564. if ((std::size_t) t >= trackEqs.size())
  565. return;
  566. auto& eq = trackEqs[(std::size_t) t];
  567. if (! track.eq.active())
  568. {
  569. if (eq.running)
  570. eq = {}; // off: reset the filters so they don't come back with a stale tail
  571. return;
  572. }
  573. if (! eq.running || ! (eq.settings == track.eq))
  574. {
  575. // new coefficients, keeping the filter state (no click when adjusting)
  576. const auto& s = track.eq;
  577. eq.bands[0].shelf (sampleRate, std::min ((double) s.hz[0], sampleRate * 0.45), s.gainDb[0], false, TrackEq::shelfSlope (s.width[0]));
  578. eq.bands[1].peaking (sampleRate, std::min ((double) s.hz[1], sampleRate * 0.45), TrackEq::peakQ (s.width[1]), s.gainDb[1]);
  579. eq.bands[2].shelf (sampleRate, std::min ((double) s.hz[2], sampleRate * 0.45), s.gainDb[2], true, TrackEq::shelfSlope (s.width[2]));
  580. for (std::size_t b = 0; b < 3; ++b)
  581. if (s.gainDb[b] == 0.0f)
  582. eq.bands[b].reset();
  583. eq.settings = s;
  584. eq.running = true;
  585. }
  586. for (std::size_t b = 0; b < 3; ++b)
  587. {
  588. if (eq.settings.gainDb[b] == 0.0f)
  589. continue; // band at 0 dB: not processed (like FL)
  590. eq.bands[b].processBlock (l, r, n);
  591. }
  592. }
  593. void RackRenderer::setSidechain (const RackState& state, const EffectSlot& slot, Effect& effect, int track) noexcept
  594. {
  595. // the source was already processed in this pass (earlier layer); silent = no signal in the detector
  596. for (const auto second : { false, true })
  597. {
  598. const auto source = second ? slot.sidechain2 : slot.sidechain;
  599. if (source < 0 || source == track || source >= (int) state.song.mixer.size())
  600. continue;
  601. const auto active = (std::size_t) source < trackActive.size() && trackActive[(std::size_t) source] != 0;
  602. const auto* left = active ? trackBuffer (source, 0) : nullptr;
  603. const auto* right = active ? trackBuffer (source, 1) : nullptr;
  604. if (second)
  605. effect.setSidechain2 (left, right);
  606. else
  607. effect.setSidechain (left, right);
  608. }
  609. }
  610. void RackRenderer::runEffects (const RackState& state, int track, int n) noexcept
  611. {
  612. if (track >= (int) state.effects.size())
  613. return;
  614. const auto& slots = state.song.mixer[(std::size_t) track].effects;
  615. const auto& effects = state.effects[(std::size_t) track];
  616. auto* l = trackBuffer (track, 0);
  617. auto* r = trackBuffer (track, 1);
  618. int audible = -1; // -1 = not measured yet; an effect's output is the next one's input
  619. for (std::size_t i = 0; i < effects.size() && i < slots.size(); ++i)
  620. {
  621. // slot dry/wet (automatable)
  622. const auto wet = state.hasAutomation && i < state.effectMixAuto[(std::size_t) track].size()
  623. ? std::clamp (automated (state.effectMixAuto[(std::size_t) track][i], slots[i].mix), 0.0f, 1.0f)
  624. : slots[i].mix;
  625. if (! slots[i].enabled || wet <= 0.0f)
  626. continue;
  627. // smart disable (like FL): an effect with silent input and output is skipped (plugins
  628. // after 4 s; built-ins after 1 s, which is well beyond their tail)
  629. const auto key = (std::size_t) track * maxEffectSlots + i;
  630. const auto isPlugin = slots[i].kind == EffectKind::plugin;
  631. const auto hold = (int) (sampleRate * (isPlugin ? 4.0 : 1.0));
  632. if (key < smartDisable.size())
  633. {
  634. auto& sd = smartDisable[key];
  635. if (sd.effect != effects[i].get())
  636. sd = { effects[i].get(), 0 };
  637. if (audible < 0)
  638. audible = anyAbove (l, r, n, silenceLevel) ? 1 : 0;
  639. if (audible == 1)
  640. sd.silentSamples = 0;
  641. else if (sd.silentSamples >= hold)
  642. continue;
  643. else
  644. sd.silentSamples += n;
  645. }
  646. // dry/wet: keep the dry signal to mix later
  647. const auto partial = wet < 0.999f;
  648. if (partial)
  649. {
  650. std::memcpy (trackScratch (track, 0), l, sizeof (float) * (std::size_t) n);
  651. std::memcpy (trackScratch (track, 1), r, sizeof (float) * (std::size_t) n);
  652. }
  653. if (state.hasAutomation && ! isPlugin)
  654. {
  655. auto params = slots[i].params; // copy without allocation
  656. const auto& autos = state.effectParamAuto[(std::size_t) track][i];
  657. const auto used = std::min (params.size(), effectInfo (slots[i].kind).params.size());
  658. for (std::size_t p = 0; p < used; ++p)
  659. params[p] = automated (autos[p], params[p]);
  660. effects[i]->setSongPosition (chunkTick);
  661. setSidechain (state, slots[i], *effects[i], track);
  662. effects[i]->process (l, r, n, params, bpm);
  663. }
  664. else
  665. {
  666. effects[i]->setSongPosition (chunkTick);
  667. setSidechain (state, slots[i], *effects[i], track);
  668. effects[i]->process (l, r, n, slots[i].params, bpm);
  669. }
  670. if (partial)
  671. {
  672. const auto* dl = trackScratch (track, 0);
  673. const auto* dr = trackScratch (track, 1);
  674. for (int k = 0; k < n; ++k)
  675. {
  676. l[k] = dl[k] + (l[k] - dl[k]) * wet;
  677. r[k] = dr[k] + (r[k] - dr[k]) * wet;
  678. }
  679. }
  680. // the effect changed the signal: measure again (it is the next slot's input)
  681. audible = anyAbove (l, r, n, silenceLevel) ? 1 : 0;
  682. if (audible == 1 && key < smartDisable.size())
  683. smartDisable[key].silentSamples = 0; // tail (reverb, delay): keep processing
  684. }
  685. }
  686. void RackRenderer::process (const RackState* state,
  687. bool playing,
  688. double startTick,
  689. int numSamples,
  690. float* left,
  691. float* right,
  692. LiveEventQueue* live,
  693. MeterBank* meters,
  694. LiveEventQueue* moreLive) noexcept
  695. {
  696. const ScopedFlushDenormals noDenormals;
  697. std::memset (left, 0, sizeof (float) * (std::size_t) numSamples);
  698. std::memset (right, 0, sizeof (float) * (std::size_t) numSamples);
  699. events.clear();
  700. if (state == nullptr || blockCapacity == 0)
  701. return;
  702. // A snapshot built before the device opened may have another rate. The instruments'
  703. // prepare() does not allocate, so it can run here.
  704. if (state != lastState && state->sampleRate != sampleRate)
  705. {
  706. for (auto& instrument : state->instruments)
  707. instrument->prepare (sampleRate);
  708. for (auto& track : state->effects)
  709. for (auto& effect : track)
  710. effect->prepare (sampleRate);
  711. }
  712. lastState = state; // so prepare() knows which instruments to reconfigure
  713. // Stopping, or jumping to another position (seek/rewind), releases held notes:
  714. // their "off" events will no longer happen.
  715. const auto jumped = playing && wasPlaying && std::abs (startTick - expectedTick) > 1.0;
  716. if ((wasPlaying && ! playing) || jumped)
  717. {
  718. for (auto& instrument : state->instruments)
  719. instrument->allNotesOff();
  720. for (auto& arp : state->arpeggiators)
  721. if (arp != nullptr)
  722. arp->reset();
  723. }
  724. // started playing or jumped: audio clips in progress must start mid-way
  725. resumeAudio = playing && (! wasPlaying || jumped);
  726. wasPlaying = playing;
  727. // tempo automation: the tempo holds for the whole block (evaluated at its start)
  728. bpm = state->song.bpm;
  729. if (state->tempoAutomation >= 0 && state->song.mode == PlayMode::song)
  730. {
  731. const auto length = (double) std::max<std::int64_t> (1, state->schedule.songLength);
  732. const auto& clips = state->automationClips[(std::size_t) state->tempoAutomation];
  733. if (! clips.empty())
  734. bpm = tempoFromValue (automationValueAt (state->song, state->song.automations[(std::size_t) state->tempoAutomation], clips,
  735. std::fmod (std::max (0.0, startTick), length)));
  736. }
  737. const auto tps = ticksPerSample (bpm, sampleRate);
  738. expectedTick = startTick + numSamples * tps;
  739. for (auto* queue : { live, moreLive })
  740. {
  741. if (queue == nullptr)
  742. continue;
  743. NoteEvent e;
  744. while (queue->pop (e))
  745. {
  746. if (e.type == NoteEvent::Type::choke && e.channel < 0) // panic: every channel stops sounding
  747. {
  748. for (auto& instrument : state->instruments)
  749. if (instrument != nullptr)
  750. instrument->allNotesOff();
  751. continue;
  752. }
  753. if (e.channel < 0 || e.channel >= (int) state->instruments.size())
  754. continue;
  755. auto& instrument = *state->instruments[(std::size_t) e.channel];
  756. if (e.type == NoteEvent::Type::on)
  757. instrument.noteOn (e.key, e.velocity);
  758. else
  759. instrument.noteOff (e.key);
  760. }
  761. }
  762. // Blocks larger than the mixer buffers are done in pieces. With automation, small
  763. // pieces so values move smoothly.
  764. const auto chunk = std::min (blockCapacity, state->hasAutomation ? 128 : chunkCapacity);
  765. for (int done = 0; done < numSamples; done += chunk)
  766. {
  767. const auto n = std::min (chunk, numSamples - done);
  768. processChunk (*state, playing, startTick + done * tps, n, left + done, right + done, meters);
  769. resumeAudio = false;
  770. }
  771. }
  772. void RackRenderer::processChunk (const RackState& state, bool playing, double startTick, int numSamples,
  773. float* left, float* right, MeterBank* meters) noexcept
  774. {
  775. chunkTick = startTick;
  776. const auto& song = state.song;
  777. const auto tracks = std::max<int> (1, (int) song.mixer.size());
  778. if (state.hasAutomation)
  779. updateAutomation (state, startTick);
  780. chunkStartTick = startTick;
  781. chunkTps = ticksPerSample (bpm, sampleRate);
  782. for (int t = 0; t < tracks; ++t)
  783. {
  784. std::memset (trackBuffer (t, 0), 0, sizeof (float) * (std::size_t) numSamples);
  785. std::memset (trackBuffer (t, 1), 0, sizeof (float) * (std::size_t) numSamples);
  786. }
  787. events.clear();
  788. if (playing && song.mode == PlayMode::song)
  789. {
  790. scheduleSong (song, startTick, numSamples, ticksPerSample (bpm, sampleRate), events, resumeAudio, &state.schedule);
  791. }
  792. else if (playing && ! song.patterns.empty())
  793. {
  794. const auto patternIndex = std::clamp (song.currentPattern, 0, (int) song.patterns.size() - 1);
  795. const auto& pattern = song.patterns[(std::size_t) patternIndex];
  796. schedulePatternLoop (pattern, pattern.effectiveLength (song.beatsPerBar), startTick, numSamples,
  797. ticksPerSample (bpm, sampleRate), events, song.swing, &song.channels);
  798. }
  799. // cut groups: each note of a channel "cuts" the channels linked to it, at the same sample
  800. if (state.hasCutGroups)
  801. {
  802. const auto count = events.size();
  803. for (int i = 0; i < count; ++i)
  804. {
  805. const auto e = events[i];
  806. if (e.type != NoteEvent::Type::on || e.channel < 0 || e.channel >= (int) state.cutTargets.size())
  807. continue;
  808. for (auto target : state.cutTargets[(std::size_t) e.channel])
  809. {
  810. NoteEvent choke;
  811. choke.type = NoteEvent::Type::choke;
  812. choke.channel = target;
  813. choke.sampleOffset = e.sampleOffset;
  814. events.add (choke);
  815. }
  816. }
  817. events.sortByOffset();
  818. }
  819. // 1) channels, each with its own notes at the exact sample (in parallel when worth it)
  820. const auto channels = std::min<int> ({ (int) state.instruments.size(), (int) song.channels.size(), maxChannels });
  821. auto channel = [this, &state, numSamples] (int c) { renderChannel (state, c, numSamples); };
  822. if (workers != nullptr && state.parallel)
  823. workers->parallelFor (channels, channel);
  824. else
  825. for (int c = 0; c < channels; ++c)
  826. channel (c);
  827. for (int c = 0; c < channels; ++c)
  828. {
  829. if (channelSilent[(std::size_t) c])
  830. continue;
  831. const auto t = std::clamp (song.channels[(std::size_t) c].mixerTrack, 0, tracks - 1);
  832. auto* dl = trackBuffer (t, 0);
  833. auto* dr = trackBuffer (t, 1);
  834. const auto* sl = channelBuffer (c, 0);
  835. const auto* sr = channelBuffer (c, 1);
  836. for (int k = 0; k < numSamples; ++k)
  837. {
  838. dl[k] += sl[k];
  839. dr[k] += sr[k];
  840. }
  841. }
  842. // 2) inserts by layers: within a layer nothing depends on anything else; each track pulls the
  843. // outputs of the tracks that send to it (without writing into others' buffers)
  844. trackActive.fill (0);
  845. for (const auto& layer : state.mixerLayers)
  846. {
  847. auto track = [this, &state, &layer, numSamples, meters] (int i) { processTrack (state, layer[(std::size_t) i], numSamples, meters); };
  848. if (workers != nullptr && state.parallel && layer.size() > 1)
  849. workers->parallelFor ((int) layer.size(), track);
  850. else
  851. for (int i = 0; i < (int) layer.size(); ++i)
  852. track (i);
  853. }
  854. // 3) Master: inputs, effects, fader. Without a configured mixer, it stays at 0 dB.
  855. pullInputs (state, 0, numSamples);
  856. runEffects (state, 0, numSamples);
  857. if (! song.mixer.empty())
  858. {
  859. applyTrackEq (song.mixer[0], 0, trackBuffer (0, 0), trackBuffer (0, 1), numSamples);
  860. applyStereo (song.mixer[0], trackBuffer (0, 0), trackBuffer (0, 1), numSamples);
  861. }
  862. float gl = 1.0f, gr = 1.0f;
  863. if (! song.mixer.empty())
  864. {
  865. const auto& master = song.mixer[0];
  866. const auto volume = state.hasAutomation ? automated (state.mixerVolumeAuto[0], master.volume) : master.volume;
  867. const auto pan = state.hasAutomation ? automated (state.mixerPanAuto[0], (master.pan + 1.0f) * 0.5f) * 2.0f - 1.0f : master.pan;
  868. panGains (pan, master.muted ? 0.0f : faderGain (volume), gl, gr);
  869. }
  870. auto& lastL = lastTrackGain[0];
  871. auto& lastR = lastTrackGain[1];
  872. const auto fromL = std::isnan (lastL) ? gl : lastL;
  873. const auto fromR = std::isnan (lastR) ? gr : lastR;
  874. lastL = gl;
  875. lastR = gr;
  876. const auto stepL = (gl - fromL) / (float) numSamples, stepR = (gr - fromR) / (float) numSamples;
  877. const auto* masterL = trackBuffer (0, 0);
  878. const auto* masterR = trackBuffer (0, 1);
  879. for (int i = 0; i < numSamples; ++i)
  880. {
  881. left[i] = masterL[i] * (fromL + stepL * (float) (i + 1));
  882. right[i] = masterR[i] * (fromR + stepR * (float) (i + 1));
  883. }
  884. if (meters != nullptr)
  885. meters->accumulate (0, peakOf (left, numSamples), peakOf (right, numSamples));
  886. }
  887. // Track stereo separation, phase and channel swap (before the fader, like FL).
  888. // Narrowing uses FL's exponential curve, widening is linear (docs/analise/REA_rodada2.md §2.2).
  889. void RackRenderer::applyStereo (const MixerTrack& track, float* l, float* r, int n) noexcept
  890. {
  891. if (track.stereo != 0.0f)
  892. {
  893. const auto s = track.stereo > 0.0f ? (std::pow (5.0f, std::min (track.stereo, 1.0f)) - 1.0f) / 4.0f
  894. : std::max (track.stereo, -1.0f);
  895. // s = 1: mono; s = -1: side doubled
  896. const auto keep = 1.0f - 0.5f * s, cross = 0.5f * s;
  897. for (int i = 0; i < n; ++i)
  898. {
  899. const auto a = l[i], b = r[i];
  900. l[i] = keep * a + cross * b;
  901. r[i] = keep * b + cross * a;
  902. }
  903. }
  904. if (track.swapChannels)
  905. for (int i = 0; i < n; ++i)
  906. std::swap (l[i], r[i]);
  907. if (track.invertPhase)
  908. for (int i = 0; i < n; ++i)
  909. {
  910. l[i] = -l[i];
  911. r[i] = -r[i];
  912. }
  913. }
  914. void RackRenderer::pullInputs (const RackState& state, int t, int n) noexcept
  915. {
  916. if ((std::size_t) t >= state.mixerInputs.size())
  917. return;
  918. auto* dl = trackBuffer (t, 0);
  919. auto* dr = trackBuffer (t, 1);
  920. for (const auto& in : state.mixerInputs[(std::size_t) t])
  921. {
  922. const auto active = trackActive[(std::size_t) in.source];
  923. const auto& delays = state.sendDelays[(std::size_t) in.source];
  924. auto* delay = (std::size_t) in.delay < delays.size() ? delays[(std::size_t) in.delay].get() : nullptr;
  925. if (delay != nullptr)
  926. {
  927. // PDC: this edge is shorter than the slowest one arriving here. A silent source
  928. // still drains the tail that was in the line.
  929. delay->mixInto (active ? trackBuffer (in.source, 0) : nullptr, active ? trackBuffer (in.source, 1) : nullptr,
  930. in.level, dl, dr, n);
  931. continue;
  932. }
  933. if (! active)
  934. continue;
  935. const auto* sl = trackBuffer (in.source, 0);
  936. const auto* sr = trackBuffer (in.source, 1);
  937. for (int i = 0; i < n; ++i)
  938. {
  939. dl[i] += sl[i] * in.level;
  940. dr[i] += sr[i] * in.level;
  941. }
  942. }
  943. }
  944. void RackRenderer::processTrack (const RackState& state, int t, int n, MeterBank* meters) noexcept
  945. {
  946. const auto& track = state.song.mixer[(std::size_t) t];
  947. pullInputs (state, t, n);
  948. const auto silent = track.muted || ! state.mixerAudible[(std::size_t) t];
  949. // target gain; the ramp from the previous block avoids clicks on mute and fader
  950. float gl = 0.0f, gr = 0.0f;
  951. if (! silent)
  952. {
  953. const auto volume = state.hasAutomation ? automated (state.mixerVolumeAuto[(std::size_t) t], track.volume) : track.volume;
  954. const auto pan = state.hasAutomation ? automated (state.mixerPanAuto[(std::size_t) t], (track.pan + 1.0f) * 0.5f) * 2.0f - 1.0f
  955. : track.pan;
  956. panGains (pan, faderGain (volume), gl, gr);
  957. }
  958. auto& lastL = lastTrackGain[(std::size_t) t * 2];
  959. auto& lastR = lastTrackGain[(std::size_t) t * 2 + 1];
  960. const auto fromL = std::isnan (lastL) ? gl : lastL;
  961. const auto fromR = std::isnan (lastR) ? gr : lastR;
  962. lastL = gl;
  963. lastR = gr;
  964. if (silent && fromL == 0.0f && fromR == 0.0f)
  965. return; // stays inactive: nobody pulls anything from it
  966. runEffects (state, t, n);
  967. auto* l = trackBuffer (t, 0);
  968. auto* r = trackBuffer (t, 1);
  969. applyTrackEq (track, t, l, r, n);
  970. applyStereo (track, l, r, n);
  971. const auto stepL = (gl - fromL) / (float) n, stepR = (gr - fromR) / (float) n;
  972. for (int i = 0; i < n; ++i)
  973. {
  974. l[i] *= fromL + stepL * (float) (i + 1);
  975. r[i] *= fromR + stepR * (float) (i + 1);
  976. }
  977. trackActive[(std::size_t) t] = 1;
  978. if (meters != nullptr)
  979. meters->accumulate (t, peakOf (l, n), peakOf (r, n));
  980. }
  981. } // namespace lynx