RackRenderer.cpp 113 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605
  1. #include "core/RackRenderer.h"
  2. #include "core/Layer.h"
  3. #include "core/FacetEq.h"
  4. #include "core/MidiControls.h"
  5. #include "core/Patcher.h"
  6. #include "core/LoadTrace.h"
  7. #include "core/DynamicsSuite.h"
  8. #include "core/MixSuite.h"
  9. #include "core/VoiceTools.h"
  10. #include "core/WorkerPool.h"
  11. #include "core/Denormals.h"
  12. #include "core/FlKeys.h"
  13. #include "core/DirectWave.h"
  14. #include "core/SoundFont.h"
  15. #include "core/NewtoneFx.h"
  16. #include <algorithm>
  17. #include <chrono>
  18. #include <cstdlib>
  19. #include <ctime>
  20. #include <cmath>
  21. #include <cstring>
  22. #include <limits>
  23. #include <map>
  24. #include <mutex>
  25. namespace lynx
  26. {
  27. namespace
  28. {
  29. // a hosted plugin is created again when its processing options change (fixed blocks, own process)
  30. bool samePluginProcessing (const PluginRef& a, const PluginRef& b) noexcept
  31. {
  32. return a.fixedBuffers == b.fixedBuffers && a.separateProcess == b.separateProcess && a.maxSizeBuffers == b.maxSizeBuffers
  33. && a.hostMaxBuffer == b.hostMaxBuffer;
  34. }
  35. // Silent instrument: plugin channel that could not be loaded.
  36. class SilentInstrument final : public Instrument
  37. {
  38. public:
  39. void prepare (double) noexcept override {}
  40. void noteOn (int, float) noexcept override {}
  41. void noteOff (int) noexcept override {}
  42. void allNotesOff() noexcept override {}
  43. void render (float*, float*, int, float, float) noexcept override {}
  44. };
  45. // FL Keys: the data FL builds from a wavetable's files, shared by every channel that plays the same wavetable
  46. // (Grand Piano holds 40 MB of 16-bit samples)
  47. std::shared_ptr<const flkeys::Wavetable> flKeysWavetable (const ChannelDef& channel, const RackState::SampleProvider& samples)
  48. {
  49. const auto table = flkeys::FlKeysTable::decode (channel.modelParams);
  50. if (! table || ! samples || table->files.size() != channel.zones.size())
  51. return nullptr;
  52. std::string key;
  53. for (const auto& z : channel.zones)
  54. key += z.path + '\n';
  55. for (auto v : channel.modelParams)
  56. key += std::to_string (v) + ' ';
  57. static std::mutex lock;
  58. static std::map<std::string, std::weak_ptr<const flkeys::Wavetable>> cache;
  59. {
  60. std::lock_guard<std::mutex> guard (lock);
  61. if (auto found = cache[key].lock())
  62. return found;
  63. }
  64. std::vector<flkeys::FileSamples> files;
  65. for (std::size_t i = 0; i < channel.zones.size(); ++i)
  66. {
  67. const auto sample = samples (channel.zones[i].path);
  68. if (sample == nullptr || sample->frames() == 0)
  69. return nullptr;
  70. files.push_back (flkeys::toFileSamples (*sample, table->files[i].scale));
  71. }
  72. auto built = flkeys::buildWavetable (*table, files);
  73. std::lock_guard<std::mutex> guard (lock);
  74. cache[key] = built;
  75. return built;
  76. }
  77. // Effect that does nothing: missing plugin slot.
  78. class BypassEffect final : public Effect
  79. {
  80. public:
  81. void prepare (double) noexcept override {}
  82. void reset() noexcept override {}
  83. void process (float*, float*, int, const EffectParams&, double) noexcept override {}
  84. };
  85. } // namespace
  86. std::unique_ptr<const RackState> RackState::build (Song song,
  87. const RackState* previous,
  88. double sampleRate,
  89. const SampleProvider& samples)
  90. {
  91. Factories factories;
  92. factories.samples = samples;
  93. return build (std::move (song), previous, sampleRate, factories);
  94. }
  95. namespace
  96. {
  97. // A channel's instrument, built new (UI thread)
  98. std::shared_ptr<Instrument> buildInstrument (const ChannelDef& channel, double sampleRate, double bpm, const RackState::Factories& factories)
  99. {
  100. const auto& samples = factories.samples;
  101. const auto kind = channel.instrument;
  102. if (kind == InstrumentKind::plugin)
  103. {
  104. std::shared_ptr<Instrument> instrument;
  105. if (factories.pluginInstruments && ! channel.plugin.id.empty())
  106. instrument = factories.pluginInstruments (channel.plugin, sampleRate);
  107. return instrument != nullptr ? instrument : std::make_shared<SilentInstrument>();
  108. }
  109. // FL Keys: its wavetable built from the channel's files
  110. if (kind == InstrumentKind::flkeys)
  111. {
  112. std::shared_ptr<Instrument> instrument = flkeys::makeFlKeysInstrument (flKeysWavetable (channel, samples));
  113. instrument->prepare (sampleRate);
  114. instrument->configure (channel, bpm);
  115. return instrument;
  116. }
  117. // DirectWave (REA_rodada72): the zones' samples as the plugin holds them
  118. if (kind == InstrumentKind::directwave)
  119. {
  120. const auto formats = dw::decodeFormats (channel.modelParams);
  121. std::vector<std::shared_ptr<const dw::ZoneSamples>> zs;
  122. for (std::size_t z = 0; z < channel.zones.size(); ++z)
  123. {
  124. std::shared_ptr<const dw::ZoneSamples> s;
  125. if (samples && ! channel.zones[z].path.empty())
  126. if (const auto data = samples (channel.zones[z].path))
  127. s = dw::zoneSamples (*data, z < formats.size() && formats[z]);
  128. zs.push_back (std::move (s));
  129. }
  130. std::shared_ptr<Instrument> instrument = dw::makeDirectWaveInstrument (std::move (zs));
  131. instrument->prepare (sampleRate);
  132. instrument->configure (channel, bpm);
  133. return instrument;
  134. }
  135. // LYNX Soundfont (REA_rodada158): the font is loaded on a background thread and shared by the channels playing it
  136. if (kind == InstrumentKind::soundfont)
  137. {
  138. std::shared_ptr<Instrument> instrument = sf::makeInstrument (channel.samplePath.empty() ? nullptr : sf::FontLibrary::instance().get (channel.samplePath));
  139. instrument->prepare (sampleRate);
  140. instrument->configure (channel, bpm);
  141. return instrument;
  142. }
  143. // multi-sample sampler: one zone per sample (DirectWave, FPC layers...)
  144. if (kind == InstrumentKind::sampler && ! channel.zones.empty())
  145. {
  146. const loadtrace::Scope timing ("rack_zoned");
  147. std::vector<LoadedZone> zones;
  148. for (const auto& z : channel.zones)
  149. zones.push_back ({ z, samples ? samples (z.path) : nullptr });
  150. std::shared_ptr<Instrument> instrument = makeZonedSampler (std::move (zones));
  151. instrument->prepare (sampleRate);
  152. instrument->configure (channel, bpm);
  153. return instrument;
  154. }
  155. std::shared_ptr<const SampleData> sample;
  156. if ((kind == InstrumentKind::sampler || kind == InstrumentKind::audioClip || kind == InstrumentKind::granulizer) && samples
  157. && ! channel.samplePath.empty())
  158. sample = samples (channel.samplePath);
  159. // pitch-preserving stretch: the sample comes already stretched to the current tempo
  160. if (sample != nullptr && kind != InstrumentKind::granulizer && channel.sampler.keepPitch && channel.sampler.stretchBeats > 0.0f
  161. && factories.stretchedSamples
  162. && sample->frames() > 0)
  163. {
  164. const auto target = channel.sampler.stretchBeats * 60.0 / std::max (1.0, bpm);
  165. const auto ratio = target / ((double) sample->frames() / sample->sampleRate);
  166. if (auto stretched = factories.stretchedSamples (channel.samplePath, ratio, channel.sampler.stretchMethod))
  167. sample = std::move (stretched);
  168. }
  169. const loadtrace::Scope timing ("rack_instruments");
  170. std::shared_ptr<Instrument> instrument = makeInstrument (kind, std::move (sample));
  171. instrument->prepare (sampleRate);
  172. instrument->configure (channel, bpm);
  173. if ((kind == InstrumentKind::sampler || kind == InstrumentKind::audioClip) && channel.sampler.keepPitch)
  174. instrument->prepareKeyShift (sampleRate); // transpositions keep the length (rounds 162, 163)
  175. return instrument;
  176. }
  177. // A slot's effect, built new (UI thread)
  178. std::shared_ptr<Effect> buildEffect (const EffectSlot& slot, double sampleRate, const RackState::Factories& factories)
  179. {
  180. const auto kind = slot.kind;
  181. std::shared_ptr<Effect> effect;
  182. if (kind == EffectKind::plugin)
  183. {
  184. if (factories.pluginEffects && ! slot.plugin.id.empty())
  185. effect = factories.pluginEffects (slot.plugin, sampleRate);
  186. if (effect == nullptr)
  187. effect = std::make_shared<BypassEffect>();
  188. }
  189. else if ((kind == EffectKind::newtone || kind == EffectKind::newtime))
  190. {
  191. // Newtone / Newtime: their source sample (loaded off the audio thread), REA_rodada73
  192. // (Newtone: its note edits rendered by LYNX's engine, REA_rodada95)
  193. effect = newtonefx::make (factories.samples && ! slot.samplePath.empty() ? factories.samples (slot.samplePath) : nullptr,
  194. slot.state);
  195. effect->prepare (sampleRate);
  196. }
  197. else
  198. {
  199. const loadtrace::Scope timing ("rack_builtin_fx"); // (round 112: what the open spends on LYNX's own effects)
  200. effect = makeEffect (slot);
  201. effect->prepare (sampleRate);
  202. }
  203. return effect;
  204. }
  205. // What a Patcher builds its nodes with: the same builders as the rack's channels and slots
  206. patcher::Factories patcherFactories (double sampleRate, double bpm, const RackState::Factories& factories)
  207. {
  208. patcher::Factories f;
  209. f.effect = [sampleRate, bpm, factories] (const EffectSlot& slot) -> std::shared_ptr<Effect> {
  210. if (slot.kind == EffectKind::patcher)
  211. {
  212. std::shared_ptr<Effect> e = patcher::makeEffect (slot, sampleRate, patcherFactories (sampleRate, bpm, factories));
  213. e->prepare (sampleRate);
  214. return e;
  215. }
  216. return buildEffect (slot, sampleRate, factories);
  217. };
  218. f.instrument = [sampleRate, bpm, factories] (const ChannelDef& channel) -> std::shared_ptr<Instrument> {
  219. if (channel.instrument == InstrumentKind::patcher)
  220. {
  221. std::shared_ptr<Instrument> i = patcher::makeInstrument (channel, sampleRate, patcherFactories (sampleRate, bpm, factories));
  222. i->configure (channel, bpm);
  223. return i;
  224. }
  225. return buildInstrument (channel, sampleRate, bpm, factories);
  226. };
  227. return f;
  228. }
  229. } // namespace
  230. std::unique_ptr<const RackState> RackState::build (Song song,
  231. const RackState* previous,
  232. double sampleRate,
  233. const Factories& factories)
  234. {
  235. const auto& samples = factories.samples;
  236. auto state = std::make_unique<RackState>();
  237. state->instruments.reserve (song.channels.size());
  238. for (std::size_t i = 0; i < song.channels.size(); ++i)
  239. {
  240. const auto& channel = song.channels[i];
  241. const auto kind = channel.instrument;
  242. if (previous != nullptr && i < previous->song.channels.size() && i < previous->instruments.size()
  243. && previous->song.channels[i].instrument == kind && kind != InstrumentKind::patcher
  244. && (kind != InstrumentKind::granulizer || previous->song.channels[i].samplePath == channel.samplePath)
  245. && (kind != InstrumentKind::soundfont
  246. || (previous->song.channels[i].samplePath == channel.samplePath && previous->sampleRate == sampleRate))
  247. && (kind != InstrumentKind::directwave
  248. || (previous->song.channels[i].zones == channel.zones && previous->song.channels[i].modelParams == channel.modelParams
  249. && previous->song.channels[i].pluginState == channel.pluginState && previous->sampleRate == sampleRate))
  250. && ((kind != InstrumentKind::sampler && kind != InstrumentKind::audioClip && kind != InstrumentKind::flkeys)
  251. || (previous->song.channels[i].samplePath == channel.samplePath && previous->song.channels[i].zones == channel.zones
  252. && previous->song.channels[i].modelParams == channel.modelParams
  253. && previous->song.channels[i].sampler.keepPitch == channel.sampler.keepPitch
  254. && (! channel.sampler.keepPitch
  255. || (previous->song.channels[i].sampler.stretchBeats == channel.sampler.stretchBeats
  256. && previous->song.channels[i].sampler.stretchMethod == channel.sampler.stretchMethod
  257. && previous->song.bpm == song.bpm))))
  258. && (kind != InstrumentKind::plugin
  259. || (previous->song.channels[i].plugin.id == channel.plugin.id && previous->sampleRate == sampleRate
  260. && samePluginProcessing (previous->song.channels[i].plugin, channel.plugin))))
  261. {
  262. state->instruments.push_back (previous->instruments[i]);
  263. state->instruments.back()->configure (channel, song.bpm);
  264. continue;
  265. }
  266. // FL's Patcher as a generator (REA_rodada141): same structure keeps the running graph (it takes the values)
  267. if (kind == InstrumentKind::patcher)
  268. {
  269. const auto* old = previous != nullptr && i < previous->instruments.size() ? previous->instruments[i].get() : nullptr;
  270. if (old != nullptr && previous->song.channels[i].instrument == kind && previous->sampleRate == sampleRate
  271. && patcher::sameStructure (previous->song.channels[i].patcher, channel.patcher))
  272. {
  273. state->instruments.push_back (previous->instruments[i]);
  274. state->instruments.back()->configure (channel, song.bpm);
  275. continue;
  276. }
  277. state->instruments.push_back (patcher::makeInstrument (channel, sampleRate, patcherFactories (sampleRate, song.bpm, factories), old));
  278. state->instruments.back()->configure (channel, song.bpm);
  279. continue;
  280. }
  281. state->instruments.push_back (buildInstrument (channel, sampleRate, song.bpm, factories));
  282. }
  283. state->effects.resize (song.mixer.size());
  284. for (std::size_t t = 0; t < song.mixer.size(); ++t)
  285. {
  286. const auto& slots = song.mixer[t].effects;
  287. for (std::size_t i = 0; i < slots.size() && i < (std::size_t) maxEffectSlots; ++i)
  288. {
  289. const auto kind = slots[i].kind;
  290. if (previous != nullptr && t < previous->song.mixer.size() && t < previous->effects.size()
  291. && i < previous->song.mixer[t].effects.size() && i < previous->effects[t].size()
  292. && previous->song.mixer[t].effects[i].kind == kind && kind != EffectKind::patcher
  293. && (kind != EffectKind::parallel || sameContainer (previous->song.mixer[t].effects[i], slots[i])) // children are built in
  294. && previous->song.mixer[t].effects[i].samplePath == slots[i].samplePath
  295. // round 144: Facet EQ's buffers are sized by its linear-phase resolution: a new one, a new instance
  296. && (kind != EffectKind::facetEq
  297. || facet::resolution (previous->song.mixer[t].effects[i].params[(std::size_t) facet::resolutionParam])
  298. == facet::resolution (slots[i].params[(std::size_t) facet::resolutionParam]))
  299. && (kind != EffectKind::plugin
  300. || (previous->song.mixer[t].effects[i].plugin.id == slots[i].plugin.id && previous->sampleRate == sampleRate
  301. && samePluginProcessing (previous->song.mixer[t].effects[i].plugin, slots[i].plugin)))
  302. && (previous->song.mixer[t].effects[i].state == slots[i].state
  303. || (previous->sampleRate == sampleRate && previous->effects[t][i] != nullptr && previous->effects[t][i]->acceptState (slots[i].state))))
  304. {
  305. state->effects[t].push_back (previous->effects[t][i]);
  306. continue;
  307. }
  308. // FL's Patcher (REA_rodada141): same structure keeps the running graph (it takes the values)
  309. if (kind == EffectKind::patcher)
  310. {
  311. const auto* old = previous != nullptr && t < previous->effects.size() && i < previous->effects[t].size()
  312. && i < previous->song.mixer[t].effects.size() && previous->song.mixer[t].effects[i].kind == kind
  313. ? previous->effects[t][i].get()
  314. : nullptr;
  315. if (old != nullptr && previous->sampleRate == sampleRate
  316. && patcher::sameStructure (previous->song.mixer[t].effects[i].patcher, slots[i].patcher)
  317. && patcher::acceptValues (previous->effects[t][i].get(), slots[i]))
  318. {
  319. state->effects[t].push_back (previous->effects[t][i]);
  320. continue;
  321. }
  322. std::shared_ptr<Effect> effect = patcher::makeEffect (slots[i], sampleRate, patcherFactories (sampleRate, song.bpm, factories), old);
  323. effect->prepare (sampleRate);
  324. state->effects[t].push_back (std::move (effect));
  325. continue;
  326. }
  327. state->effects[t].push_back (buildEffect (slots[i], sampleRate, factories));
  328. }
  329. }
  330. state->song = std::move (song);
  331. const auto tailStarted = std::chrono::steady_clock::now();
  332. // scheduling: notes sorted by start (order among notes on the same tick is preserved)
  333. for (auto& p : state->song.patterns)
  334. std::stable_sort (p.notes.begin(), p.notes.end(), [] (const Note& a, const Note& b) { return a.start < b.start; });
  335. state->schedule = makeScheduleIndex (state->song);
  336. state->sampleRate = sampleRate;
  337. state->buildMidiRoutes();
  338. state->buildAutomationTables();
  339. {
  340. const loadtrace::Scope timing ("pdc");
  341. state->buildPdc (previous);
  342. }
  343. state->buildMixerGraph();
  344. const auto& channels = state->song.channels;
  345. state->cutTargets.assign (channels.size(), {});
  346. state->arpeggiators.assign (channels.size(), nullptr);
  347. for (std::size_t c = 0; c < channels.size(); ++c)
  348. if (channels[c].arp.enabled())
  349. state->arpeggiators[c] = previous != nullptr && c < previous->arpeggiators.size() && previous->arpeggiators[c] != nullptr
  350. ? previous->arpeggiators[c]
  351. : std::make_shared<Arpeggiator>();
  352. state->echoes.assign (channels.size(), nullptr);
  353. for (std::size_t c = 0; c < channels.size(); ++c)
  354. if (channels[c].misc.echo.enabled())
  355. state->echoes[c] = previous != nullptr && c < previous->echoes.size() && previous->echoes[c] != nullptr
  356. ? previous->echoes[c]
  357. : std::make_shared<channelmisc::NoteEcho>();
  358. for (std::size_t c = 0; c < channels.size(); ++c)
  359. if (channels[c].cutGroup > 0)
  360. for (std::size_t d = 0; d < channels.size(); ++d)
  361. if (channels[d].cutBy == channels[c].cutGroup)
  362. {
  363. state->cutTargets[c].push_back ((int) d);
  364. state->hasCutGroups = true;
  365. }
  366. state->hasLayers = std::any_of (channels.begin(), channels.end(), [] (const ChannelDef& c) {
  367. return c.instrument == InstrumentKind::layer && ! c.layer.children.empty();
  368. });
  369. const auto audible = state->song.soloAudible();
  370. state->mixerAudible.assign (audible.begin(), audible.end());
  371. loadtrace::add ("rack_schedule_graph", loadtrace::msSince (tailStarted));
  372. return state;
  373. }
  374. void RackState::buildMixerGraph()
  375. {
  376. mixerOrder = song.mixerOrder();
  377. const auto audible = song.soloAudible();
  378. mixerAudible.assign (audible.begin(), audible.end());
  379. const auto tracks = std::max<int> (1, (int) song.mixer.size());
  380. mixerInputs.assign ((std::size_t) tracks, {});
  381. sendTaps.clear();
  382. slotTap.assign ((std::size_t) tracks, {});
  383. std::vector<int> depth ((std::size_t) tracks, 0);
  384. // who listens to each track via sidechain (the source goes in an earlier layer)
  385. std::vector<std::vector<int>> sidechainListeners ((std::size_t) tracks);
  386. for (int t = 1; t < tracks; ++t)
  387. for (const auto& fx : song.mixer[(std::size_t) t].effects)
  388. for (const auto source : { fx.sidechain, fx.sidechain2 })
  389. if (source > 0 && source < tracks && source != t)
  390. sidechainListeners[(std::size_t) source].push_back (t);
  391. for (auto t : mixerOrder) // sources before destinations: the depth is already computed
  392. {
  393. const auto& track = song.mixer[(std::size_t) t];
  394. for (const auto listener : sidechainListeners[(std::size_t) t])
  395. depth[(std::size_t) listener] = std::max (depth[(std::size_t) listener], depth[(std::size_t) t] + 1);
  396. if (track.toMaster)
  397. mixerInputs[0].push_back ({ t, 0, track.masterLevel });
  398. for (std::size_t k = 0; k < track.sends.size(); ++k)
  399. {
  400. const auto& send = track.sends[k];
  401. if (send.target > 0 && send.target < tracks && send.target != t && send.level > 0.0f)
  402. {
  403. mixerInputs[(std::size_t) send.target].push_back ({ t, (int) k + 1, send.level });
  404. depth[(std::size_t) send.target] = std::max (depth[(std::size_t) send.target], depth[(std::size_t) t] + 1);
  405. }
  406. }
  407. // Fruity Send slots: their own signal, delay lines after the sends' (PdcPlan::sendDelay)
  408. const auto taps = fruitySendsOf (song, t);
  409. for (std::size_t j = 0; j < taps.size(); ++j)
  410. {
  411. const auto [slot, target] = taps[j];
  412. if ((int) sendTaps.size() >= maxSendTaps)
  413. break;
  414. if ((std::size_t) t >= slotTap.size())
  415. slotTap.resize ((std::size_t) t + 1);
  416. if ((std::size_t) slot >= slotTap[(std::size_t) t].size())
  417. slotTap[(std::size_t) t].resize ((std::size_t) slot + 1, -1);
  418. slotTap[(std::size_t) t][(std::size_t) slot] = (int) sendTaps.size();
  419. mixerInputs[(std::size_t) target].push_back ({ t, (int) (1 + track.sends.size() + j), 1.0f, (int) sendTaps.size() });
  420. sendTaps.push_back ({ t, slot, target });
  421. depth[(std::size_t) target] = std::max (depth[(std::size_t) target], depth[(std::size_t) t] + 1);
  422. }
  423. }
  424. mixerLayers.clear();
  425. for (auto t : mixerOrder)
  426. {
  427. const auto d = (std::size_t) depth[(std::size_t) t];
  428. if (mixerLayers.size() <= d)
  429. mixerLayers.resize (d + 1);
  430. mixerLayers[d].push_back (t);
  431. }
  432. // splitting across threads costs a few microseconds per block; only worth it with plugins or many channels
  433. const auto plugins = std::count_if (song.channels.begin(), song.channels.end(),
  434. [] (const ChannelDef& c) { return c.instrument == InstrumentKind::plugin; });
  435. auto pluginEffects = 0;
  436. for (const auto& t : song.mixer)
  437. pluginEffects += (int) std::count_if (t.effects.begin(), t.effects.end(), [] (const EffectSlot& e) { return e.kind == EffectKind::plugin; });
  438. parallel = plugins + pluginEffects >= 2 || song.channels.size() >= 24;
  439. // plugins whose "Allow threaded processing" is off pin their channel / insert to the audio thread
  440. threadedChannels.clear();
  441. audioThreadChannels.clear();
  442. for (int c = 0; c < (int) song.channels.size(); ++c)
  443. {
  444. const auto& ch = song.channels[(std::size_t) c];
  445. (ch.instrument == InstrumentKind::plugin && ! ch.plugin.threaded ? audioThreadChannels : threadedChannels).push_back (c);
  446. }
  447. threadedLayers.assign (mixerLayers.size(), {});
  448. audioThreadLayers.assign (mixerLayers.size(), {});
  449. for (std::size_t d = 0; d < mixerLayers.size(); ++d)
  450. for (const auto t : mixerLayers[d])
  451. {
  452. const auto& effects = song.mixer[(std::size_t) t].effects;
  453. const auto pinned = ! song.mixer[(std::size_t) t].threaded || std::any_of (effects.begin(), effects.end(),
  454. [] (const EffectSlot& e) { return e.kind == EffectKind::plugin && ! e.plugin.threaded; });
  455. (pinned ? audioThreadLayers : threadedLayers)[d].push_back (t);
  456. }
  457. }
  458. std::vector<int> RackState::currentLatencies() const
  459. {
  460. std::vector<int> out;
  461. // a hosted plugin's latency set by hand in its wrapper settings (round 149) replaces what it reports
  462. auto manual = [this] (const PluginRef& ref, int reported) {
  463. return ref.latencyOverrideMs >= 0.0f ? (int) std::lround (ref.latencyOverrideMs * 0.001 * sampleRate) : reported;
  464. };
  465. for (std::size_t c = 0; c < instruments.size(); ++c)
  466. {
  467. const auto reported = instruments[c]->latencySamples();
  468. out.push_back (c < song.channels.size() && song.channels[c].instrument == InstrumentKind::plugin ? manual (song.channels[c].plugin, reported) : reported);
  469. }
  470. for (std::size_t t = 0; t < effects.size(); ++t)
  471. for (std::size_t s = 0; s < effects[t].size(); ++s)
  472. {
  473. const auto reported = effects[t][s]->latencySamples();
  474. const auto* slot = t < song.mixer.size() && s < song.mixer[t].effects.size() ? &song.mixer[t].effects[s] : nullptr;
  475. out.push_back (slot != nullptr && slot->kind == EffectKind::plugin ? manual (slot->plugin, reported) : reported);
  476. }
  477. return out;
  478. }
  479. void RackState::buildPdc (const RackState* previous)
  480. {
  481. latencies = currentLatencies();
  482. std::vector<int> channelLatency (latencies.begin(), latencies.begin() + (std::ptrdiff_t) instruments.size());
  483. std::vector<std::vector<int>> slotLatency (effects.size());
  484. auto next = latencies.begin() + (std::ptrdiff_t) instruments.size();
  485. for (std::size_t t = 0; t < effects.size(); ++t)
  486. for (std::size_t s = 0; s < effects[t].size(); ++s)
  487. slotLatency[t].push_back (*next++);
  488. pdc = computePdc (song, channelLatency, slotLatency);
  489. // reuses lines of the same length: editing the song must not click the audio
  490. auto line = [] (int length, const std::shared_ptr<DelayLine>* old) -> std::shared_ptr<DelayLine> {
  491. if (length <= 0)
  492. return nullptr;
  493. if (old != nullptr && *old != nullptr && (*old)->length() == length)
  494. return *old;
  495. return std::make_shared<DelayLine> (length);
  496. };
  497. channelDelays.resize (pdc.channelDelay.size());
  498. for (std::size_t c = 0; c < pdc.channelDelay.size(); ++c)
  499. channelDelays[c] = line (pdc.channelDelay[c],
  500. previous != nullptr && c < previous->channelDelays.size() ? &previous->channelDelays[c] : nullptr);
  501. sendDelays.resize (pdc.sendDelay.size());
  502. for (std::size_t t = 0; t < pdc.sendDelay.size(); ++t)
  503. {
  504. sendDelays[t].resize (pdc.sendDelay[t].size());
  505. for (std::size_t k = 0; k < pdc.sendDelay[t].size(); ++k)
  506. {
  507. const std::shared_ptr<DelayLine>* old = nullptr;
  508. if (previous != nullptr && t < previous->sendDelays.size() && k < previous->sendDelays[t].size())
  509. old = &previous->sendDelays[t][k];
  510. sendDelays[t][k] = line (pdc.sendDelay[t][k], old);
  511. }
  512. }
  513. // inserts with a hardware output target: aligned with the Master's output (which waits for the longest path)
  514. hwRoutes.clear();
  515. for (std::size_t t = 1; t < song.mixer.size() && t < (std::size_t) maxMixerTracks; ++t)
  516. {
  517. const auto& track = song.mixer[t];
  518. if (track.outputChannel < 0 || track.outputChannel >= HardwareOutput::maxChannels)
  519. continue;
  520. const auto length = t < pdc.outLat.size() ? std::max (0, pdc.total - pdc.outLat[t]) : 0;
  521. const std::shared_ptr<DelayLine>* old = nullptr;
  522. if (previous != nullptr)
  523. for (const auto& r : previous->hwRoutes)
  524. if (r.track == (int) t)
  525. old = &r.delay;
  526. hwRoutes.push_back ({ (int) t, track.outputChannel, track.outputMode, line (length, old) });
  527. }
  528. }
  529. void RackState::buildMidiRoutes()
  530. {
  531. const auto count = song.channels.size();
  532. midiTargets.assign (count, {});
  533. midiSources.assign (count, {});
  534. midiOutChannel.assign (count, -1);
  535. hasMidiRoutes = false;
  536. midiOutTargets.assign (count, {});
  537. hasMidiOutputs = false;
  538. for (std::size_t c = 0; c < count; ++c)
  539. if (song.channels[c].instrument == InstrumentKind::plugin && song.channels[c].plugin.midiOutPort >= 0)
  540. for (std::size_t t = 0; t < count; ++t)
  541. if (t != c && song.channels[t].instrument == InstrumentKind::plugin
  542. && song.channels[t].plugin.midiInPort == song.channels[c].plugin.midiOutPort)
  543. {
  544. midiOutTargets[c].push_back ((int) t);
  545. hasMidiOutputs = true;
  546. }
  547. midiRoutesOut.assign (count, {});
  548. midiRoutesIn.assign (count, {});
  549. effectMidiRoutes.assign (count, {});
  550. hasEffectMidiRoutes = false;
  551. // the Patchers that take MIDI ports through their "From LYNX" pins (round 162)
  552. std::vector<std::vector<int>> channelPorts (count);
  553. for (std::size_t t = 0; t < count; ++t)
  554. if (song.channels[t].instrument == InstrumentKind::patcher)
  555. channelPorts[t] = patcher::midiInputPorts (song.channels[t].patcher);
  556. struct SlotPorts
  557. {
  558. int track, slot;
  559. std::vector<int> ports;
  560. };
  561. std::vector<SlotPorts> slotPorts;
  562. for (std::size_t t = 0; t < song.mixer.size(); ++t)
  563. for (std::size_t k = 0; k < song.mixer[t].effects.size(); ++k)
  564. if (song.mixer[t].effects[k].kind == EffectKind::patcher)
  565. if (auto ports = patcher::midiInputPorts (song.mixer[t].effects[k].patcher); ! ports.empty())
  566. slotPorts.push_back ({ (int) t, (int) k, std::move (ports) });
  567. // source c sends on `port` with MIDI channel `midiChannel`: the plugins whose input port it is, the Patchers that
  568. // take that port
  569. // (a Patcher that takes the port may pass it on to "To LYNX" MIDI ports: those are sent on too, a few levels deep)
  570. std::function<void (std::size_t, int, int, int)> send = [&] (std::size_t c, int port, int midiChannel, int depth) {
  571. auto passOn = [&] (const PatcherDoc& doc) {
  572. if (depth < 4)
  573. for (const auto& r : patcher::midiOutputsOf (doc, patchMidiPortPin (port)))
  574. if (r.port != port)
  575. send (c, r.port, r.midiChannel >= 0 ? r.midiChannel : midiChannel, depth + 1);
  576. };
  577. if (midiOutChannel[c] < 0)
  578. midiOutChannel[c] = midiChannel;
  579. for (std::size_t t = 0; t < count; ++t)
  580. {
  581. if (t == c)
  582. continue;
  583. const auto plugin = song.channels[t].instrument == InstrumentKind::plugin && song.channels[t].plugin.midiInPort == port;
  584. const auto patch = std::find (channelPorts[t].begin(), channelPorts[t].end(), port) != channelPorts[t].end();
  585. if (! plugin && ! patch)
  586. continue;
  587. if (std::any_of (midiRoutesOut[c].begin(), midiRoutesOut[c].end(), [&] (const MidiRoute& r) {
  588. return r.other == (int) t && r.port == port && r.midiChannel == midiChannel;
  589. }))
  590. continue;
  591. midiRoutesOut[c].push_back ({ (int) t, port, midiChannel });
  592. midiRoutesIn[t].push_back ({ (int) c, port, midiChannel });
  593. if (std::find (midiSources[t].begin(), midiSources[t].end(), (int) c) == midiSources[t].end())
  594. midiSources[t].push_back ((int) c);
  595. if (plugin && std::find (midiTargets[c].begin(), midiTargets[c].end(), (int) t) == midiTargets[c].end())
  596. midiTargets[c].push_back ((int) t); // (controls and program changes: the plugins)
  597. hasMidiRoutes = true;
  598. if (patch)
  599. passOn (song.channels[t].patcher);
  600. }
  601. for (const auto& s : slotPorts)
  602. if (std::find (s.ports.begin(), s.ports.end(), port) != s.ports.end()
  603. && std::none_of (effectMidiRoutes[c].begin(), effectMidiRoutes[c].end(), [&] (const EffectMidiRoute& r) {
  604. return r.track == s.track && r.slot == s.slot && r.port == port && r.midiChannel == midiChannel;
  605. }))
  606. {
  607. effectMidiRoutes[c].push_back ({ s.track, s.slot, port, midiChannel });
  608. hasEffectMidiRoutes = true;
  609. passOn (song.mixer[(std::size_t) s.track].effects[(std::size_t) s.slot].patcher);
  610. }
  611. };
  612. for (std::size_t c = 0; c < count; ++c)
  613. {
  614. // a generator Patcher's "MIDI port N" outputs (REA_rodada141): its notes reach the plugins on those ports, as a
  615. // MIDI Out on MIDI channel 1 would send them (or on the channel of a MIDI Out node on the way, round 162)
  616. if (song.channels[c].instrument == InstrumentKind::patcher)
  617. {
  618. for (const auto& r : patcher::midiOutputsOf (song.channels[c].patcher, 0))
  619. send (c, r.port, std::max (0, r.midiChannel), 0);
  620. continue;
  621. }
  622. if (song.channels[c].instrument != InstrumentKind::midiOut)
  623. continue;
  624. const auto settings = midictl::parseMidiOut (song.channels[c].pluginState);
  625. midiOutChannel[c] = settings.channel;
  626. send (c, settings.port, settings.channel, 0);
  627. }
  628. }
  629. void RackState::buildAutomationTables()
  630. {
  631. const auto& automations = song.automations;
  632. const auto count = std::min<int> ((int) automations.size(), maxAutomations);
  633. automationClips.assign ((std::size_t) count, {});
  634. for (int i = 0; i < (int) song.playlist.size(); ++i)
  635. {
  636. const auto& c = song.playlist[(std::size_t) i];
  637. if (c.kind == ClipKind::automation && c.automation >= 0 && c.automation < count && c.length > 0 && ! c.muted && ! song.isTrackMuted (c.track))
  638. automationClips[(std::size_t) c.automation].push_back (i);
  639. }
  640. for (auto& clips : automationClips)
  641. std::sort (clips.begin(), clips.end(),
  642. [this] (int a, int b) { return song.playlist[(std::size_t) a].start < song.playlist[(std::size_t) b].start; });
  643. liveAutomations.clear();
  644. for (int a = 0; a < count; ++a)
  645. if (automations[(std::size_t) a].isLive())
  646. liveAutomations.push_back (a);
  647. channelVolumeAuto.assign (song.channels.size(), -1);
  648. channelPanAuto.assign (song.channels.size(), -1);
  649. mixerVolumeAuto.assign (song.mixer.size(), -1);
  650. mixerPanAuto.assign (song.mixer.size(), -1);
  651. effectParamAuto.assign (song.mixer.size(), {});
  652. effectMixAuto.assign (song.mixer.size(), {});
  653. for (std::size_t t = 0; t < song.mixer.size(); ++t)
  654. {
  655. std::array<int, maxEffectParams> none;
  656. none.fill (-1);
  657. effectParamAuto[t].assign (song.mixer[t].effects.size(), none);
  658. effectMixAuto[t].assign (song.mixer[t].effects.size(), -1);
  659. }
  660. pluginParams.clear();
  661. hasAutomation = false;
  662. tempoAutomation = -1;
  663. // binds automation slot `a` (an automation, or a pattern event lane after them) to its target
  664. const auto bind = [this] (int a, const AutomationTarget& t) {
  665. const auto channelOk = t.index >= 0 && t.index < (int) song.channels.size();
  666. const auto trackOk = t.index >= 0 && t.index < (int) song.mixer.size();
  667. auto used = true;
  668. switch (t.kind)
  669. {
  670. case AutomationTargetKind::channelVolume: if (channelOk) channelVolumeAuto[(std::size_t) t.index] = a; else used = false; break;
  671. case AutomationTargetKind::channelPan: if (channelOk) channelPanAuto[(std::size_t) t.index] = a; else used = false; break;
  672. case AutomationTargetKind::mixerVolume: if (trackOk) mixerVolumeAuto[(std::size_t) t.index] = a; else used = false; break;
  673. case AutomationTargetKind::mixerPan: if (trackOk) mixerPanAuto[(std::size_t) t.index] = a; else used = false; break;
  674. case AutomationTargetKind::channelParam:
  675. // VST plugins and the exact engines that take FL's parameter automation (FL Slayer: REA_rodada79)
  676. if (channelOk && (song.channels[(std::size_t) t.index].instrument == InstrumentKind::plugin
  677. || song.channels[(std::size_t) t.index].instrument == InstrumentKind::patcher // (its published parameters)
  678. || song.channels[(std::size_t) t.index].instrument == InstrumentKind::slayer
  679. || song.channels[(std::size_t) t.index].instrument == InstrumentKind::soundfont // (LYNX Soundfont's knobs)
  680. || (song.channels[(std::size_t) t.index].instrument == InstrumentKind::midiOut && midictl::isMidiParam (t.param))))
  681. pluginParams.push_back ({ a, t.index, 0, 0, t.param });
  682. else
  683. used = false;
  684. break;
  685. case AutomationTargetKind::effectParam:
  686. {
  687. const auto slotOk = trackOk && t.slot >= 0 && t.slot < (int) song.mixer[(std::size_t) t.index].effects.size();
  688. if (! slotOk)
  689. used = false;
  690. else if (song.mixer[(std::size_t) t.index].effects[(std::size_t) t.slot].kind == EffectKind::plugin
  691. || song.mixer[(std::size_t) t.index].effects[(std::size_t) t.slot].kind == EffectKind::patcher) // (its published parameters)
  692. pluginParams.push_back ({ a, -1, t.index, t.slot, t.param });
  693. else if (song.mixer[(std::size_t) t.index].effects[(std::size_t) t.slot].isSubstitute())
  694. used = false; // the missing plugin's parameters: kept for when it is back, they don't drive the substitute
  695. else if (t.param >= 0 && t.param < maxEffectParams)
  696. effectParamAuto[(std::size_t) t.index][(std::size_t) t.slot][(std::size_t) t.param] = a;
  697. else
  698. used = false;
  699. break;
  700. }
  701. case AutomationTargetKind::effectMix:
  702. if (trackOk && t.slot >= 0 && t.slot < (int) song.mixer[(std::size_t) t.index].effects.size())
  703. effectMixAuto[(std::size_t) t.index][(std::size_t) t.slot] = a;
  704. else
  705. used = false;
  706. break;
  707. case AutomationTargetKind::tempo: tempoAutomation = a; break;
  708. case AutomationTargetKind::none: used = false; break;
  709. }
  710. hasAutomation = hasAutomation || used;
  711. };
  712. // the last automation of the same target wins
  713. for (int a = 0; a < count; ++a)
  714. {
  715. if (automationClips[(std::size_t) a].empty() && ! automations[(std::size_t) a].isLive())
  716. continue;
  717. bind (a, automations[(std::size_t) a].target);
  718. }
  719. // pattern events (event editor): slots after the automations; they win over automation clips of the same
  720. // target. The tempo is not driven by pattern events.
  721. eventLanes.clear();
  722. patternClips.assign (song.patterns.size(), {});
  723. for (int i = 0; i < (int) song.playlist.size(); ++i)
  724. {
  725. const auto& c = song.playlist[(std::size_t) i];
  726. if (c.kind == ClipKind::pattern && c.pattern >= 0 && c.pattern < (int) song.patterns.size() && c.length > 0 && ! c.muted
  727. && ! song.isTrackMuted (c.track))
  728. patternClips[(std::size_t) c.pattern].push_back (i);
  729. }
  730. for (auto& clips : patternClips)
  731. std::sort (clips.begin(), clips.end(),
  732. [this] (int a, int b) { return song.playlist[(std::size_t) a].start < song.playlist[(std::size_t) b].start; });
  733. auto slot = count;
  734. for (int p = 0; p < (int) song.patterns.size(); ++p)
  735. for (int l = 0; l < (int) song.patterns[(std::size_t) p].events.size(); ++l)
  736. {
  737. const auto& lane = song.patterns[(std::size_t) p].events[(std::size_t) l];
  738. if (lane.events.empty() || lane.target.kind == AutomationTargetKind::tempo || slot >= maxAutomations)
  739. continue;
  740. eventLanes.push_back ({ p, l, slot });
  741. bind (slot++, lane.target);
  742. }
  743. }
  744. void RackState::slotsOfTarget (const Song& song, const AutomationTarget& target, std::vector<int>& out)
  745. {
  746. out.clear();
  747. if (target.kind == AutomationTargetKind::none)
  748. return;
  749. const auto count = std::min<int> ((int) song.automations.size(), maxAutomations);
  750. for (int a = 0; a < count; ++a)
  751. if (song.automations[(std::size_t) a].target == target)
  752. out.push_back (a);
  753. auto slot = count;
  754. for (const auto& pattern : song.patterns)
  755. for (const auto& lane : pattern.events)
  756. {
  757. if (lane.events.empty() || lane.target.kind == AutomationTargetKind::tempo || slot >= maxAutomations)
  758. continue;
  759. if (lane.target == target)
  760. out.push_back (slot);
  761. ++slot;
  762. }
  763. }
  764. namespace
  765. {
  766. // Constant-power pan: at center both sides are 1 (0 dB).
  767. void panGains (float pan, float gain, float& left, float& right) noexcept
  768. {
  769. const auto angle = (pan + 1.0f) * 0.25f * 3.14159265f;
  770. left = gain * std::cos (angle) * 1.41421356f;
  771. right = gain * std::sin (angle) * 1.41421356f;
  772. }
  773. // FL's mixer fader and pan: each side's gain moves toward its target by at most 0.001 per sample (a linear glide;
  774. // measured on FL's renders of pattern events on a track's volume and pan, REA_rodada85 §3). Returns the gain reached.
  775. float glideGain (const float* in, float* out, int n, float from, float to) noexcept
  776. {
  777. constexpr float step = 0.001f;
  778. auto g = from;
  779. int i = 0;
  780. for (; i < n && g != to; ++i)
  781. {
  782. g = to > g ? std::min (to, g + step) : std::max (to, g - step);
  783. out[i] = in[i] * g;
  784. }
  785. for (; i < n; ++i)
  786. out[i] = in[i] * g;
  787. return g;
  788. }
  789. float peakOf (const float* data, int n) noexcept
  790. {
  791. float peak = 0.0f;
  792. for (int i = 0; i < n; ++i)
  793. {
  794. const auto a = std::abs (data[i]);
  795. peak = a > peak ? a : peak; // form the compiler vectorizes
  796. }
  797. return peak;
  798. }
  799. // No NaN / inf in the block? (x · 0 is 0 for every finite x: one vectorized pass)
  800. bool finiteBlock (const float* l, const float* r, int n) noexcept
  801. {
  802. float acc = 0.0f;
  803. for (int k = 0; k < n; ++k)
  804. acc += l[k] * 0.0f + r[k] * 0.0f;
  805. return acc == 0.0f;
  806. }
  807. std::atomic<std::uint64_t> nonFiniteBlocks { 0 };
  808. // Any sample above `level`? Stops at the first: with sound (the common case) it costs almost nothing.
  809. bool anyAbove (const float* l, const float* r, int n, float level) noexcept
  810. {
  811. // in blocks of 32: the inner loop vectorizes; silent chunks (the ones that scan everything) stay cheap
  812. int i = 0;
  813. for (; i + 32 <= n; i += 32)
  814. {
  815. float m = 0.0f;
  816. for (int k = i; k < i + 32; ++k)
  817. {
  818. const auto a = std::abs (l[k]), b = std::abs (r[k]);
  819. m = a > m ? a : m;
  820. m = b > m ? b : m;
  821. }
  822. if (m > level)
  823. return true;
  824. }
  825. for (; i < n; ++i)
  826. if (std::abs (l[i]) > level || std::abs (r[i]) > level)
  827. return true;
  828. return false;
  829. }
  830. } // namespace
  831. namespace
  832. {
  833. // A Patcher-style container bakes its children (kinds, states, parameters, routing) in when it is built, so it can be
  834. // reused only if all of that is unchanged. (It used to be rebuilt on every edit: its children's tails and delay lines
  835. // restarted, and a fresh linear-phase child reporting its latency only after the first block made the engine re-plan
  836. // PDC and rebuild it again, over and over — REA round 87.)
  837. bool sameSlotSetup (const EffectSlot& a, const EffectSlot& b);
  838. bool sameBranches (const EffectSlot& a, const EffectSlot& b)
  839. {
  840. if (a.branches.size() != b.branches.size() || a.links.size() != b.links.size())
  841. return false;
  842. for (std::size_t i = 0; i < a.branches.size(); ++i)
  843. {
  844. const auto& x = a.branches[i];
  845. const auto& y = b.branches[i];
  846. if (x.gain != y.gain || x.chain.size() != y.chain.size())
  847. return false;
  848. for (std::size_t k = 0; k < x.chain.size(); ++k)
  849. if (! sameSlotSetup (x.chain[k], y.chain[k]))
  850. return false;
  851. }
  852. for (std::size_t i = 0; i < a.links.size(); ++i)
  853. {
  854. const auto& x = a.links[i];
  855. const auto& y = b.links[i];
  856. if (x.branch != y.branch || x.source != y.source || x.target != y.target || x.param != y.param || x.curve != y.curve)
  857. return false;
  858. }
  859. return true;
  860. }
  861. bool sameSlotSetup (const EffectSlot& a, const EffectSlot& b)
  862. {
  863. return a.kind == b.kind && a.enabled == b.enabled && a.params == b.params && a.mix == b.mix && a.plugin.id == b.plugin.id
  864. && a.sidechain == b.sidechain && a.sidechain2 == b.sidechain2 && a.state == b.state && a.samplePath == b.samplePath
  865. && sameBranches (a, b);
  866. }
  867. } // namespace
  868. bool sameContainer (const EffectSlot& a, const EffectSlot& b) { return sameBranches (a, b); }
  869. namespace
  870. {
  871. std::uint64_t nowNs() noexcept
  872. {
  873. #if defined(__linux__)
  874. // diagnostics on a busy machine: LYNX_PROFILE_CPU=1 measures each unit in its thread's CPU time (renderwav)
  875. static const bool threadCpu = std::getenv ("LYNX_PROFILE_CPU") != nullptr;
  876. if (threadCpu)
  877. {
  878. timespec ts {};
  879. clock_gettime (CLOCK_THREAD_CPUTIME_ID, &ts);
  880. return (std::uint64_t) ts.tv_sec * 1000000000ull + (std::uint64_t) ts.tv_nsec;
  881. }
  882. #endif
  883. return (std::uint64_t) std::chrono::duration_cast<std::chrono::nanoseconds> (std::chrono::steady_clock::now().time_since_epoch()).count();
  884. }
  885. // Adds the time since `start` to `slot` when profiling (start = 0: profiling was off when the unit began)
  886. struct UnitTimer
  887. {
  888. UnitTimer (bool on, std::atomic<std::uint64_t>& s, std::atomic<std::uint64_t>* m = nullptr) noexcept
  889. : slot (s), longest (m), start (on ? nowNs() : 0) {}
  890. ~UnitTimer()
  891. {
  892. if (start == 0)
  893. return;
  894. const auto used = nowNs() - start;
  895. slot.fetch_add (used, std::memory_order_relaxed);
  896. if (longest != nullptr)
  897. {
  898. auto current = longest->load (std::memory_order_relaxed);
  899. while (used > current && ! longest->compare_exchange_weak (current, used, std::memory_order_relaxed))
  900. {
  901. }
  902. }
  903. }
  904. std::atomic<std::uint64_t>& slot;
  905. std::atomic<std::uint64_t>* longest;
  906. std::uint64_t start;
  907. };
  908. } // namespace
  909. void RackRenderer::resetUnitTimes() noexcept
  910. {
  911. for (auto& t : units->channelNs)
  912. t.store (0, std::memory_order_relaxed);
  913. for (auto& t : units->effectNs)
  914. t.store (0, std::memory_order_relaxed);
  915. for (auto& t : units->channelMaxNs)
  916. t.store (0, std::memory_order_relaxed);
  917. for (auto& t : units->effectMaxNs)
  918. t.store (0, std::memory_order_relaxed);
  919. units->processNs.store (0, std::memory_order_relaxed);
  920. units->processedSamples.store (0, std::memory_order_relaxed);
  921. }
  922. void RackRenderer::prepare (double sr, int maxBlockSize)
  923. {
  924. automationValues.fill (std::numeric_limits<float>::quiet_NaN());
  925. lastTrackGain.fill (std::numeric_limits<float>::quiet_NaN());
  926. channelBuffers.assign ((std::size_t) maxChannels * 2 * chunkCapacity, 0.0f);
  927. smartDisable.assign ((std::size_t) maxMixerTracks * maxEffectSlots, {});
  928. trackEqs.assign ((std::size_t) maxMixerTracks, {});
  929. trackScratchBuffers.assign ((std::size_t) maxMixerTracks * 2 * chunkCapacity, 0.0f);
  930. tapBuffers.assign ((std::size_t) RackState::maxSendTaps * 2 * chunkCapacity, 0.0f);
  931. sampleRate = sr;
  932. blockCapacity = std::max (64, maxBlockSize);
  933. mixBuffers.assign ((std::size_t) maxMixerTracks * 2 * (std::size_t) blockCapacity, 0.0f);
  934. hwScratch.assign (2 * (std::size_t) blockCapacity, 0.0f);
  935. layerPick.assign ((std::size_t) maxChannels * 128, (std::int16_t) -1);
  936. if (lastState != nullptr)
  937. {
  938. for (auto& instrument : lastState->instruments)
  939. instrument->prepare (sr);
  940. for (auto& track : lastState->effects)
  941. for (auto& effect : track)
  942. effect->prepare (sr);
  943. }
  944. }
  945. float* RackRenderer::trackBuffer (int track, int channel) noexcept
  946. {
  947. return mixBuffers.data() + ((std::size_t) track * 2 + (std::size_t) channel) * (std::size_t) blockCapacity;
  948. }
  949. float* RackRenderer::tapBuffer (int tap, int side) noexcept
  950. {
  951. return tapBuffers.data() + ((std::size_t) tap * 2 + (std::size_t) side) * chunkCapacity;
  952. }
  953. float RackRenderer::automated (int automation, float base) const noexcept
  954. {
  955. if (automation < 0)
  956. return base;
  957. const auto v = automationValues[(std::size_t) automation];
  958. return std::isnan (v) ? base : v;
  959. }
  960. namespace
  961. {
  962. // Value of an automation at a song position: inside a clip, the curve; between clips,
  963. // the last value of the previous clip; before the first, its initial value. Depends only on
  964. // position, so playing from any point (or exporting) gives the same result.
  965. float automationValueAt (const Song& song, const Automation& automation, const std::vector<int>& clips, double tick) noexcept
  966. {
  967. const Clip* before = nullptr;
  968. for (auto i : clips) // sorted by start
  969. {
  970. const auto& c = song.playlist[(std::size_t) i];
  971. if (tick < (double) c.start)
  972. break;
  973. if (tick < (double) c.end())
  974. return automation.valueAt (tick - (double) c.start + (double) c.offset);
  975. before = &c;
  976. }
  977. if (before != nullptr)
  978. return automation.valueAt ((double) (before->length + before->offset));
  979. const auto& first = song.playlist[(std::size_t) clips.front()];
  980. return automation.valueAt ((double) first.offset);
  981. }
  982. } // namespace
  983. void RackRenderer::setOverriddenSlots (const std::vector<int>& slots) noexcept
  984. {
  985. std::array<std::uint32_t, RackState::maxAutomations / 32> bits {};
  986. for (const auto s : slots)
  987. if (s >= 0 && s < RackState::maxAutomations)
  988. bits[(std::size_t) s / 32] |= 1u << ((unsigned) s % 32);
  989. for (std::size_t i = 0; i < bits.size(); ++i)
  990. overridden[i].store (bits[i], std::memory_order_relaxed);
  991. anyOverridden.store (! slots.empty(), std::memory_order_release);
  992. }
  993. void RackRenderer::clearOverriddenValues() noexcept
  994. {
  995. if (! anyOverridden.load (std::memory_order_acquire))
  996. return;
  997. for (std::size_t w = 0; w < overridden.size(); ++w)
  998. if (auto bits = overridden[w].load (std::memory_order_relaxed); bits != 0)
  999. for (unsigned b = 0; b < 32; ++b)
  1000. if ((bits & (1u << b)) != 0)
  1001. automationValues[w * 32 + b] = std::numeric_limits<float>::quiet_NaN(); // the control's own value
  1002. }
  1003. void RackRenderer::updateAutomation (const RackState& state, double startTick) noexcept
  1004. {
  1005. const auto& song = state.song;
  1006. // controllers (live sources): the effect's output at the end of the previous block, in any mode
  1007. for (const auto a : state.liveAutomations)
  1008. {
  1009. const auto& automation = song.automations[(std::size_t) a];
  1010. const auto& src = automation.source;
  1011. if (src.channel >= 0)
  1012. {
  1013. if (src.channel < (int) state.instruments.size() && state.instruments[(std::size_t) src.channel] != nullptr)
  1014. automationValues[(std::size_t) a] = automation.mapLive (state.instruments[(std::size_t) src.channel]->controlOutput (src.output));
  1015. }
  1016. else if (src.track < (int) state.effects.size() && src.slot >= 0 && src.slot < (int) state.effects[(std::size_t) src.track].size()
  1017. && state.effects[(std::size_t) src.track][(std::size_t) src.slot] != nullptr)
  1018. automationValues[(std::size_t) a] = automation.mapLive (state.effects[(std::size_t) src.track][(std::size_t) src.slot]->controlOutput (src.output));
  1019. }
  1020. // pattern events: in pattern mode the current pattern's (looped); in song mode those of the pattern clip
  1021. // that covers the position. Elsewhere the value holds.
  1022. if (! state.eventLanes.empty())
  1023. {
  1024. if (song.mode != PlayMode::song)
  1025. {
  1026. const auto current = song.currentPattern;
  1027. if (current >= 0 && current < (int) song.patterns.size())
  1028. {
  1029. const auto& pattern = song.patterns[(std::size_t) current];
  1030. const auto length = (double) std::max<std::int64_t> (1, pattern.effectiveLength (song.beatsPerBar));
  1031. const auto t = std::fmod (std::max (0.0, startTick), length);
  1032. for (const auto& lane : state.eventLanes)
  1033. if (lane.pattern == current)
  1034. automationValues[(std::size_t) lane.slot] = pattern.events[(std::size_t) lane.lane].valueAt (t);
  1035. }
  1036. }
  1037. else
  1038. {
  1039. const auto length = (double) std::max<std::int64_t> (1, state.schedule.songLength);
  1040. const auto tick = std::fmod (std::max (0.0, startTick), length);
  1041. // inside a clip of the pattern: its events; after one: the value it ended with; before the first:
  1042. // no value (the target's own). Depends only on the position, like automation clips.
  1043. for (const auto& lane : state.eventLanes)
  1044. {
  1045. const auto& events = song.patterns[(std::size_t) lane.pattern].events[(std::size_t) lane.lane];
  1046. auto value = std::numeric_limits<float>::quiet_NaN();
  1047. for (auto i : state.patternClips[(std::size_t) lane.pattern]) // sorted by start
  1048. {
  1049. const auto& c = song.playlist[(std::size_t) i];
  1050. if (tick < (double) c.start)
  1051. break;
  1052. value = tick < (double) c.end() ? events.valueAt (tick - (double) c.start + (double) c.offset)
  1053. : events.valueAt ((double) (c.offset + c.length) - 1.0);
  1054. }
  1055. automationValues[(std::size_t) lane.slot] = value;
  1056. }
  1057. }
  1058. }
  1059. // in pattern mode the Playlist does not play: values stay as they were
  1060. if (song.mode != PlayMode::song)
  1061. {
  1062. clearOverriddenValues();
  1063. if (! state.eventLanes.empty()) // only the plugin parameters driven by pattern events
  1064. applyPluginParams (state, std::min<int> ((int) song.automations.size(), RackState::maxAutomations));
  1065. return;
  1066. }
  1067. const auto length = (double) std::max<std::int64_t> (1, state.schedule.songLength);
  1068. const auto tick = std::fmod (std::max (0.0, startTick), length);
  1069. for (std::size_t a = 0; a < state.automationClips.size(); ++a)
  1070. if (! state.automationClips[a].empty())
  1071. automationValues[a] = automationValueAt (song, song.automations[a], state.automationClips[a], tick);
  1072. clearOverriddenValues();
  1073. applyPluginParams (state, 0);
  1074. }
  1075. void RackRenderer::applyPluginParams (const RackState& state, int firstSlot) noexcept
  1076. {
  1077. for (const auto& b : state.pluginParams)
  1078. {
  1079. if (b.automation < firstSlot)
  1080. continue;
  1081. const auto v = automationValues[(std::size_t) b.automation];
  1082. if (std::isnan (v))
  1083. continue;
  1084. if (b.channel >= 0)
  1085. {
  1086. if (b.channel < (int) state.instruments.size())
  1087. state.instruments[(std::size_t) b.channel]->setParameter (b.param, v);
  1088. // a MIDI Out's controls reach the plugins on its port
  1089. if ((std::size_t) b.channel < state.midiTargets.size())
  1090. for (const auto t : state.midiTargets[(std::size_t) b.channel])
  1091. if (t < (int) state.instruments.size())
  1092. state.instruments[(std::size_t) t]->setParameter (b.param, v);
  1093. }
  1094. else if (b.track < (int) state.effects.size() && b.slot < (int) state.effects[(std::size_t) b.track].size())
  1095. state.effects[(std::size_t) b.track][(std::size_t) b.slot]->setParameter (b.param, v);
  1096. }
  1097. }
  1098. void RackRenderer::deliverToEffects (const RackState& state, const NoteEvent& e) noexcept
  1099. {
  1100. if (e.channel < 0 || (std::size_t) e.channel >= state.effectMidiRoutes.size()
  1101. || (e.type != NoteEvent::Type::on && e.type != NoteEvent::Type::off))
  1102. return;
  1103. if (e.type == NoteEvent::Type::on && state.song.channels[(std::size_t) e.channel].muted)
  1104. return;
  1105. for (const auto& route : state.effectMidiRoutes[(std::size_t) e.channel])
  1106. {
  1107. if ((std::size_t) route.track >= state.effects.size() || (std::size_t) route.slot >= state.effects[(std::size_t) route.track].size())
  1108. continue;
  1109. if (auto* graph = patcher::graphOf (state.effects[(std::size_t) route.track][(std::size_t) route.slot].get()))
  1110. {
  1111. if (e.type == NoteEvent::Type::on)
  1112. graph->noteOnPort (route.port, e.key, e.velocity, route.midiChannel);
  1113. else
  1114. graph->noteOffPort (route.port, e.key, route.midiChannel);
  1115. }
  1116. }
  1117. }
  1118. float* RackRenderer::channelBuffer (int channel, int side) noexcept
  1119. {
  1120. return channelBuffers.data() + ((std::size_t) channel * 2 + (std::size_t) side) * chunkCapacity;
  1121. }
  1122. float* RackRenderer::trackScratch (int track, int side) noexcept
  1123. {
  1124. return trackScratchBuffers.data() + ((std::size_t) track * 2 + (std::size_t) side) * chunkCapacity;
  1125. }
  1126. // A whole channel over the chunk: notes at the exact sample (only its own events), volume/pan and the
  1127. // PDC delay. Each channel only touches its own instrument and buffer: it can run in parallel.
  1128. void RackRenderer::renderChannel (const RackState& state, int i, int n) noexcept
  1129. {
  1130. const auto& c = state.song.channels[(std::size_t) i];
  1131. const auto automation = state.hasAutomation;
  1132. const auto volume = channelGain (automation ? automated (state.channelVolumeAuto[(std::size_t) i], c.volume) : c.volume);
  1133. const auto pan = automation ? automated (state.channelPanAuto[(std::size_t) i], (c.pan + 1.0f) * 0.5f) * 2.0f - 1.0f : c.pan;
  1134. float gl = 0.0f, gr = 0.0f;
  1135. panGains (pan, volume, gl, gr);
  1136. auto* l = channelBuffer (i, 0);
  1137. auto* r = channelBuffer (i, 1);
  1138. if ((std::size_t) i < state.instruments.size() && state.instruments[(std::size_t) i] != nullptr)
  1139. state.instruments[(std::size_t) i]->setSongPosition (chunkTick);
  1140. auto& instrument = *state.instruments[(std::size_t) i];
  1141. instrument.beginChunk (n); // (extra outputs: a generator Patcher's, REA_rodada141)
  1142. // idle channel, no notes in this chunk and no PDC: nothing to do (neither clear nor sum into the mixer)
  1143. const auto hasDelay = (std::size_t) i < state.channelDelays.size() && state.channelDelays[(std::size_t) i] != nullptr;
  1144. const auto hasArp = ((std::size_t) i < state.arpeggiators.size() && state.arpeggiators[(std::size_t) i] != nullptr)
  1145. || ((std::size_t) i < state.echoes.size() && state.echoes[(std::size_t) i] != nullptr);
  1146. const auto* sources = state.hasMidiRoutes && (std::size_t) i < state.midiSources.size() && ! state.midiSources[(std::size_t) i].empty()
  1147. ? &state.midiSources[(std::size_t) i] : nullptr;
  1148. const auto routed = [sources] (int channel) {
  1149. return sources != nullptr && std::find (sources->begin(), sources->end(), channel) != sources->end();
  1150. };
  1151. if (! hasDelay && ! hasArp && instrument.idle()
  1152. && std::none_of (events.begin(), events.end(), [&] (const NoteEvent& e) { return e.channel == i || routed (e.channel); }))
  1153. {
  1154. channelSilent[(std::size_t) i] = 1;
  1155. return;
  1156. }
  1157. channelSilent[(std::size_t) i] = 0;
  1158. const UnitTimer timer (profiling.load (std::memory_order_relaxed), units->channelNs[(std::size_t) i], &units->channelMaxNs[(std::size_t) i]);
  1159. std::memset (l, 0, sizeof (float) * (std::size_t) n);
  1160. std::memset (r, 0, sizeof (float) * (std::size_t) n);
  1161. int position = 0;
  1162. // arpeggiator: the channel's notes become the arpeggio sequence
  1163. const NoteEvent* list = events.begin();
  1164. int listCount = events.size();
  1165. if ((std::size_t) i < state.arpeggiators.size() && state.arpeggiators[(std::size_t) i] != nullptr)
  1166. {
  1167. auto& arp = *state.arpeggiators[(std::size_t) i];
  1168. int inCount = 0;
  1169. for (const auto& e : events)
  1170. if (e.channel == i && inCount < Arpeggiator::maxEvents)
  1171. arp.input[(std::size_t) inCount++] = e;
  1172. int outCount = 0;
  1173. arp.process (i, arp.input.data(), inCount, chunkStartTick, chunkTps, n, c.arp, arp.output.data(), outCount);
  1174. // FL cuts an arpeggio note at its gate even on a sample that plays out (REA round 146b [EXEC: FL's renders of
  1175. // its Sampler render test]): the arpeggio is one voice, so its "off" stops the channel's sound (not with the
  1176. // echo delay, whose echoes keep ringing)
  1177. if (! c.misc.echo.enabled())
  1178. for (int k = 0; k < outCount; ++k)
  1179. if (arp.output[(std::size_t) k].type == NoteEvent::Type::off)
  1180. arp.output[(std::size_t) k].type = NoteEvent::Type::choke;
  1181. list = arp.output.data();
  1182. listCount = outCount;
  1183. }
  1184. // FL's echo delay (Misc tab): the channel's notes (after the arpeggio) and their echoes
  1185. const float* gains = nullptr;
  1186. if ((std::size_t) i < state.echoes.size() && state.echoes[(std::size_t) i] != nullptr)
  1187. {
  1188. auto& echo = *state.echoes[(std::size_t) i];
  1189. int inCount = 0;
  1190. for (int k = 0; k < listCount; ++k)
  1191. if (list[k].channel == i && inCount < channelmisc::NoteEcho::maxEvents)
  1192. echo.input[(std::size_t) inCount++] = list[k];
  1193. int outCount = 0;
  1194. echo.process (i, echo.input.data(), inCount, chunkStartTick, chunkTps, n, c.misc.echo, echo.output.data(), echo.outputGains.data(), outCount);
  1195. list = echo.output.data();
  1196. listCount = outCount;
  1197. gains = echo.outputGains.data();
  1198. }
  1199. const auto tracking = c.misc.key.pan != 0.0f || c.misc.velocity.pan != 0.0f;
  1200. const auto modTracking = c.misc.key.modX != 0.0f || c.misc.key.modY != 0.0f || c.misc.velocity.modX != 0.0f || c.misc.velocity.modY != 0.0f;
  1201. // FL's Add to key (round 149): the root note moves the notes of instruments that are not samplers
  1202. const auto keyShift = c.misc.addToKey && c.instrument != InstrumentKind::sampler ? 60 - c.misc.rootNote : 0;
  1203. for (int index = 0; index < listCount; ++index)
  1204. {
  1205. auto shifted = list[index];
  1206. if (keyShift != 0 && shifted.channel == i)
  1207. shifted.key = std::clamp (shifted.key + keyShift, 0, 127);
  1208. const auto& e = shifted;
  1209. if (e.channel != i)
  1210. {
  1211. // a note of a MIDI Out channel on this plugin's MIDI input port, with that MIDI Out's MIDI channel
  1212. if (sources == nullptr || ! routed (e.channel) || (e.type != NoteEvent::Type::on && e.type != NoteEvent::Type::off))
  1213. continue;
  1214. if (e.sampleOffset > position)
  1215. {
  1216. instrument.render (l + position, r + position, e.sampleOffset - position, gl, gr);
  1217. position = e.sampleOffset;
  1218. }
  1219. // (each route from that channel: its port and MIDI channel, round 162)
  1220. for (const auto& route : state.midiRoutesIn[(std::size_t) i])
  1221. {
  1222. if (route.other != e.channel)
  1223. continue;
  1224. if (e.type == NoteEvent::Type::on)
  1225. {
  1226. if (! c.muted && ! state.song.channels[(std::size_t) e.channel].muted)
  1227. instrument.noteOnPort (route.port, e.key, e.velocity, route.midiChannel);
  1228. }
  1229. else
  1230. instrument.noteOffPort (route.port, e.key, route.midiChannel);
  1231. }
  1232. continue;
  1233. }
  1234. if (e.sampleOffset > position)
  1235. {
  1236. instrument.render (l + position, r + position, e.sampleOffset - position, gl, gr);
  1237. position = e.sampleOffset;
  1238. }
  1239. auto& held = heldNotes[(std::size_t) i];
  1240. const auto bit = std::uint64_t { 1 } << (e.key & 63);
  1241. if (e.type == NoteEvent::Type::on)
  1242. {
  1243. if (e.key >= 0 && e.key < 128)
  1244. held[(std::size_t) (e.key >> 6)] |= bit;
  1245. // FL's key region (round 164): the channel plays only the notes inside it (audio clips: the key is the clip)
  1246. const auto inRegion = c.instrument == InstrumentKind::audioClip || c.inKeyRegion (list[index].key);
  1247. if (! c.muted && inRegion)
  1248. {
  1249. // Max polyphony: the oldest note is released first
  1250. if (const auto limit = voiceLimitFor (c.maxPolyphony, c.synth.mono); limit > 0)
  1251. if (const auto victim = voiceOrders[(std::size_t) i].noteOn (e.key, limit); victim >= 0)
  1252. instrument.noteOff (victim);
  1253. const auto pan = tracking ? channelmisc::trackedPan (c.misc, e.key, e.velocity, e.pan) : e.pan;
  1254. // (an audio clip follows its fine tune, not the main pitch: LYNX never moved clips with it)
  1255. instrument.setNextNoteExpression (pan, e.cents + c.misc.fineTune
  1256. + (c.misc.mainPitch && c.instrument != InstrumentKind::audioClip ? state.song.masterPitch : 0.0f),
  1257. e.porta);
  1258. {
  1259. const auto [modX, modY] = modTracking ? channelmisc::trackedModulation (c.misc, e.key, e.velocity, e.modX, e.modY)
  1260. : std::pair<float, float> { e.modX, e.modY };
  1261. instrument.setNextNoteModulation (modX, modY);
  1262. }
  1263. if (e.fadeIn > 0.0f || e.fadeOut > 0.0f)
  1264. instrument.setNextClipFades (e.clipElapsed, e.clipRemaining, e.fadeIn, e.fadeOut);
  1265. // an echo's volume: the instrument scales the voice, else (engines without it) the velocity
  1266. auto velocity = e.velocity;
  1267. const auto gain = e.gain * (gains != nullptr ? gains[index] : 1.0f);
  1268. if (gain != 1.0f && ! instrument.setNextNoteGain (gain))
  1269. velocity *= gain;
  1270. instrument.noteOnAt (e.key, velocity, e.startSeconds);
  1271. }
  1272. }
  1273. else if (e.type == NoteEvent::Type::slide)
  1274. {
  1275. instrument.slideTo (e.key, e.cents + c.misc.fineTune + (c.misc.mainPitch ? state.song.masterPitch : 0.0f), e.slideSamples);
  1276. }
  1277. else if (e.type == NoteEvent::Type::choke)
  1278. {
  1279. instrument.allNotesOff(); // short fade, like FL's "cut"
  1280. held = {};
  1281. voiceOrders[(std::size_t) i].clear();
  1282. }
  1283. else
  1284. {
  1285. instrument.setNextNoteRelease (e.release);
  1286. instrument.noteOff (e.key);
  1287. voiceOrders[(std::size_t) i].noteOff (e.key);
  1288. if (e.key >= 0 && e.key < 128)
  1289. held[(std::size_t) (e.key >> 6)] &= ~bit;
  1290. }
  1291. }
  1292. if (position < n)
  1293. instrument.render (l + position, r + position, n - position, gl, gr);
  1294. // PDC: this channel arrives before the track's others; delay until aligned
  1295. if ((std::size_t) i < state.channelDelays.size() && state.channelDelays[(std::size_t) i] != nullptr)
  1296. state.channelDelays[(std::size_t) i]->process (l, r, n);
  1297. }
  1298. void RackRenderer::applyTrackEq (const MixerTrack& track, int t, bool bypassed, float* l, float* r, int n) noexcept
  1299. {
  1300. if ((std::size_t) t >= trackEqs.size())
  1301. return;
  1302. auto& eq = trackEqs[(std::size_t) t];
  1303. if (bypassed || ! track.eq.active()) // clean mixer (round 163): no built-in processing, the samples pass untouched
  1304. {
  1305. if (eq.running)
  1306. eq = {}; // off: reset the filters so they don't come back with a stale tail
  1307. return;
  1308. }
  1309. if (! eq.running || ! (eq.settings == track.eq))
  1310. {
  1311. // new coefficients, keeping the filter state (no click when adjusting)
  1312. const auto& s = track.eq;
  1313. eq.bands[0].shelf (sampleRate, std::min ((double) s.hz[0], sampleRate * 0.45), s.gainDb[0], false, TrackEq::shelfSlope (s.width[0]));
  1314. eq.bands[1].peaking (sampleRate, std::min ((double) s.hz[1], sampleRate * 0.45), TrackEq::peakQ (s.width[1]), s.gainDb[1]);
  1315. eq.bands[2].shelf (sampleRate, std::min ((double) s.hz[2], sampleRate * 0.45), s.gainDb[2], true, TrackEq::shelfSlope (s.width[2]));
  1316. for (std::size_t b = 0; b < 3; ++b)
  1317. if (s.gainDb[b] == 0.0f)
  1318. eq.bands[b].reset();
  1319. eq.settings = s;
  1320. eq.running = true;
  1321. }
  1322. for (std::size_t b = 0; b < 3; ++b)
  1323. {
  1324. if (eq.settings.gainDb[b] == 0.0f)
  1325. continue; // band at 0 dB: not processed (like FL)
  1326. eq.bands[b].processBlock (l, r, n);
  1327. }
  1328. }
  1329. // effects whose controlOutput() an editor shows live
  1330. static bool hasLiveMeters (EffectKind kind) noexcept
  1331. {
  1332. // round 129: the voice tools (Quell's reduction meter was never published) and the basic compressor's meters
  1333. return mixsuite::isSuiteKind (kind) || dyn::isDynKind (kind) || kind == EffectKind::lynxTune || kind == EffectKind::facetEq
  1334. || kind == EffectKind::apexLimiter || voicetools::isVoiceKind (kind) || kind == EffectKind::compressor
  1335. || kind == EffectKind::echoform // round 135w: Echoform's output meter
  1336. || kind == EffectKind::autoPan || kind == EffectKind::voiceShift; // round 135: the pan position, the shifter's notes
  1337. }
  1338. void RackRenderer::setSidechain (const RackState& state, const EffectSlot& slot, Effect& effect, int track) noexcept
  1339. {
  1340. // the source was already processed in this pass (earlier layer); silent = no signal in the detector
  1341. for (const auto second : { false, true })
  1342. {
  1343. const auto source = second ? slot.sidechain2 : slot.sidechain;
  1344. if (source < 0 || source == track || source >= (int) state.song.mixer.size())
  1345. continue;
  1346. const auto active = (std::size_t) source < trackActive.size() && trackActive[(std::size_t) source] != 0;
  1347. const auto* left = active ? trackBuffer (source, 0) : nullptr;
  1348. const auto* right = active ? trackBuffer (source, 1) : nullptr;
  1349. if (second)
  1350. effect.setSidechain2 (left, right);
  1351. else
  1352. effect.setSidechain (left, right);
  1353. }
  1354. }
  1355. void RackRenderer::runEffects (const RackState& state, int track, int n) noexcept
  1356. {
  1357. if (track >= (int) state.effects.size())
  1358. return;
  1359. const auto& slots = state.song.mixer[(std::size_t) track].effects;
  1360. const auto& effects = state.effects[(std::size_t) track];
  1361. auto* l = trackBuffer (track, 0);
  1362. auto* r = trackBuffer (track, 1);
  1363. int audible = -1; // -1 = not measured yet; an effect's output is the next one's input
  1364. const auto timing = times->enabled.load (std::memory_order_relaxed);
  1365. auto timed = [this, timing] (std::size_t key, auto&& run) {
  1366. if (! timing || key >= times->effectNs.size())
  1367. {
  1368. run();
  1369. return;
  1370. }
  1371. const auto before = ProcessTimes::now();
  1372. run();
  1373. times->effectNs[key].fetch_add (ProcessTimes::now() - before, std::memory_order_relaxed);
  1374. };
  1375. for (std::size_t i = 0; i < effects.size() && i < slots.size(); ++i)
  1376. {
  1377. // slot dry/wet (automatable)
  1378. const auto wet = state.hasAutomation && i < state.effectMixAuto[(std::size_t) track].size()
  1379. ? std::clamp (automated (state.effectMixAuto[(std::size_t) track][i], slots[i].mix), 0.0f, 1.0f)
  1380. : slots[i].mix;
  1381. auto clearMeters = [this, track, i] {
  1382. const auto at = ((std::size_t) track * maxEffectSlots + i) * ProcessTimes::meterOutputs;
  1383. if (at + ProcessTimes::meterOutputs <= times->effectMeters.size())
  1384. for (int o = 0; o < ProcessTimes::meterOutputs; ++o)
  1385. times->effectMeters[at + (std::size_t) o].store (0.0f, std::memory_order_relaxed);
  1386. };
  1387. if (! state.song.slotActive (slots[i]) || wet <= 0.0f)
  1388. {
  1389. if (hasLiveMeters (slots[i].kind))
  1390. clearMeters();
  1391. continue;
  1392. }
  1393. // smart disable (like FL): an effect with silent input and output is skipped (plugins
  1394. // after 4 s; built-ins after 1 s, which is well beyond their tail)
  1395. const auto key = (std::size_t) track * maxEffectSlots + i;
  1396. const auto isPlugin = slots[i].kind == EffectKind::plugin;
  1397. const auto hold = (int) (sampleRate * (isPlugin || slots[i].kind == EffectKind::patcher ? 4.0 : 1.0)); // (a Patcher may hold plugins)
  1398. // (not Gross Beat: its buffer must keep recording the silence it may play back later, as in FL)
  1399. // (nor Newtone / Newtime: in slave mode they play their sample whatever the input)
  1400. // (nor a slot whose "Smart disable" is off, or a plugin that does not allow it — FL's per-plugin options, REA round 139)
  1401. if (key < smartDisable.size() && slots[i].smartDisable && ! (isPlugin && ! slots[i].plugin.allowSmartDisable)
  1402. && slots[i].kind != EffectKind::grossBeat && slots[i].kind != EffectKind::newtone
  1403. && slots[i].kind != EffectKind::newtime)
  1404. {
  1405. auto& sd = smartDisable[key];
  1406. if (sd.effect != effects[i].get())
  1407. sd = { effects[i].get(), 0 };
  1408. if (audible < 0)
  1409. audible = anyAbove (l, r, n, silenceLevel) ? 1 : 0;
  1410. if (audible == 1)
  1411. sd.silentSamples = 0;
  1412. else if (sd.silentSamples >= hold)
  1413. {
  1414. if (hasLiveMeters (slots[i].kind))
  1415. clearMeters();
  1416. continue;
  1417. }
  1418. else
  1419. sd.silentSamples += n;
  1420. }
  1421. // the editor's spectrum analyser listens to this slot: its input
  1422. const auto tapped = times->analyzer.key.load (std::memory_order_relaxed) == (int) key;
  1423. if (tapped)
  1424. {
  1425. auto& tap = times->analyzer;
  1426. const auto w = tap.written.load (std::memory_order_relaxed);
  1427. for (int k = 0; k < n; ++k)
  1428. tap.pre[(std::size_t) ((w + (std::uint32_t) k) & (ProcessTimes::AnalyzerTap::size - 1))].store (0.5f * (l[k] + r[k]), std::memory_order_relaxed);
  1429. }
  1430. // dry/wet: keep the dry signal to mix later
  1431. const auto partial = wet < 0.999f;
  1432. if (partial)
  1433. {
  1434. std::memcpy (trackScratch (track, 0), l, sizeof (float) * (std::size_t) n);
  1435. std::memcpy (trackScratch (track, 1), r, sizeof (float) * (std::size_t) n);
  1436. }
  1437. const UnitTimer timer (profiling.load (std::memory_order_relaxed), units->effectNs[std::min (key, units->effectNs.size() - 1)],
  1438. &units->effectMaxNs[std::min (key, units->effectNs.size() - 1)]);
  1439. // Fruity Send: what it sends goes to its own buffer, pulled by the destination insert (processed later)
  1440. if (slots[i].kind == EffectKind::fruitySend || slots[i].kind == EffectKind::patcher)
  1441. {
  1442. const auto tap = (std::size_t) track < state.slotTap.size() && i < state.slotTap[(std::size_t) track].size()
  1443. ? state.slotTap[(std::size_t) track][i]
  1444. : -1;
  1445. if (tap >= 0 && tap < RackState::maxSendTaps)
  1446. {
  1447. std::memset (tapBuffer (tap, 0), 0, sizeof (float) * (std::size_t) n);
  1448. std::memset (tapBuffer (tap, 1), 0, sizeof (float) * (std::size_t) n);
  1449. effects[i]->setSendOutput (tapBuffer (tap, 0), tapBuffer (tap, 1));
  1450. tapActive[(std::size_t) tap] = 1;
  1451. }
  1452. else
  1453. effects[i]->setSendOutput (nullptr, nullptr);
  1454. }
  1455. if (state.hasAutomation && ! isPlugin)
  1456. {
  1457. auto params = slots[i].params; // copy without allocation
  1458. const auto& autos = state.effectParamAuto[(std::size_t) track][i];
  1459. const auto used = std::min (params.size(), effectInfo (slots[i].kind).params.size());
  1460. for (std::size_t p = 0; p < used; ++p)
  1461. params[p] = automated (autos[p], params[p]);
  1462. effects[i]->setSongPosition (chunkTick);
  1463. effects[i]->setPlaying (chunkPlaying);
  1464. effects[i]->setHeldNotes (heldNotes.data(), maxChannels);
  1465. setSidechain (state, slots[i], *effects[i], track);
  1466. timed (key, [&] { effects[i]->process (l, r, n, params, bpm); });
  1467. }
  1468. else
  1469. {
  1470. effects[i]->setSongPosition (chunkTick);
  1471. effects[i]->setPlaying (chunkPlaying);
  1472. effects[i]->setHeldNotes (heldNotes.data(), maxChannels);
  1473. setSidechain (state, slots[i], *effects[i], track);
  1474. timed (key, [&] { effects[i]->process (l, r, n, slots[i].params, bpm); });
  1475. }
  1476. // an effect that output NaN / inf (an unstable setting): this block of it is muted and its state reset, so the
  1477. // broken values never reach the rest of the mix (they would stay in every filter and feedback path after it)
  1478. if (! finiteBlock (l, r, n))
  1479. {
  1480. std::memset (l, 0, sizeof (float) * (std::size_t) n);
  1481. std::memset (r, 0, sizeof (float) * (std::size_t) n);
  1482. effects[i]->reset();
  1483. nonFiniteBlocks.fetch_add (1, std::memory_order_relaxed);
  1484. }
  1485. if (partial)
  1486. {
  1487. const auto* dl = trackScratch (track, 0);
  1488. const auto* dr = trackScratch (track, 1);
  1489. for (int k = 0; k < n; ++k)
  1490. {
  1491. l[k] = dl[k] + (l[k] - dl[k]) * wet;
  1492. r[k] = dr[k] + (r[k] - dr[k]) * wet;
  1493. }
  1494. }
  1495. // ... and its output
  1496. if (tapped)
  1497. {
  1498. auto& tap = times->analyzer;
  1499. const auto w = tap.written.load (std::memory_order_relaxed);
  1500. for (int k = 0; k < n; ++k)
  1501. tap.post[(std::size_t) ((w + (std::uint32_t) k) & (ProcessTimes::AnalyzerTap::size - 1))].store (0.5f * (l[k] + r[k]), std::memory_order_relaxed);
  1502. tap.sampleRate.store (sampleRate, std::memory_order_relaxed);
  1503. tap.written.store (w + (std::uint32_t) n, std::memory_order_release);
  1504. }
  1505. // live meters for the editor (the mixing suite's gain reduction, LYNX Tune's pitch, Facet EQ's dynamic gains)
  1506. if (hasLiveMeters (slots[i].kind) && key < (std::size_t) maxMixerTracks * maxEffectSlots)
  1507. for (int o = 0; o < ProcessTimes::meterOutputs; ++o)
  1508. times->effectMeters[key * ProcessTimes::meterOutputs + (std::size_t) o].store (effects[i]->controlOutput (o), std::memory_order_relaxed);
  1509. // the effect changed the signal: measure again (it is the next slot's input)
  1510. audible = anyAbove (l, r, n, silenceLevel) ? 1 : 0;
  1511. if (audible == 1 && key < smartDisable.size())
  1512. smartDisable[key].silentSamples = 0; // tail (reverb, delay): keep processing
  1513. }
  1514. }
  1515. std::uint64_t RackRenderer::nonFiniteEffectBlocks() noexcept
  1516. {
  1517. return nonFiniteBlocks.load (std::memory_order_relaxed);
  1518. }
  1519. void RackRenderer::process (const RackState* state,
  1520. bool playing,
  1521. double startTick,
  1522. int numSamples,
  1523. float* left,
  1524. float* right,
  1525. LiveEventQueue* live,
  1526. MeterBank* meters,
  1527. LiveEventQueue* moreLive) noexcept
  1528. {
  1529. const ScopedFlushDenormals noDenormals;
  1530. const UnitTimer timer (profiling.load (std::memory_order_relaxed), units->processNs);
  1531. if (profiling.load (std::memory_order_relaxed))
  1532. units->processedSamples.fetch_add ((std::uint64_t) std::max (0, numSamples), std::memory_order_relaxed);
  1533. std::memset (left, 0, sizeof (float) * (std::size_t) numSamples);
  1534. std::memset (right, 0, sizeof (float) * (std::size_t) numSamples);
  1535. events.clear();
  1536. if (state == nullptr || blockCapacity == 0)
  1537. return;
  1538. const auto timing = times->enabled.load (std::memory_order_relaxed);
  1539. const auto wallStart = timing ? ProcessTimes::now() : 0;
  1540. // A snapshot built before the device opened may have another rate. The instruments'
  1541. // prepare() does not allocate, so it can run here.
  1542. if (state != lastState && state->sampleRate != sampleRate)
  1543. {
  1544. for (auto& instrument : state->instruments)
  1545. instrument->prepare (sampleRate);
  1546. for (auto& track : state->effects)
  1547. for (auto& effect : track)
  1548. effect->prepare (sampleRate);
  1549. }
  1550. lastState = state; // so prepare() knows which instruments to reconfigure
  1551. // Stopping, or jumping to another position (seek/rewind), releases held notes:
  1552. // their "off" events will no longer happen.
  1553. const auto jumped = playing && wasPlaying && std::abs (startTick - expectedTick) > 1.0;
  1554. if ((wasPlaying && ! playing) || (playing && ! wasPlaying))
  1555. {
  1556. // the arpeggiators / echoes ran on the live clock while stopped (round 149): they restart on the song's
  1557. liveRoutedCount = 0;
  1558. for (auto& arp : state->arpeggiators)
  1559. if (arp != nullptr)
  1560. arp->reset();
  1561. for (auto& echo : state->echoes)
  1562. if (echo != nullptr)
  1563. echo->reset();
  1564. }
  1565. if ((wasPlaying && ! playing) || jumped)
  1566. {
  1567. for (auto& instrument : state->instruments)
  1568. if (jumped)
  1569. instrument->allNotesOff();
  1570. else
  1571. instrument->transportStopped(); // (a hosted plugin: FL's "Send All Notes Off when playback stops")
  1572. heldNotes.fill ({});
  1573. for (auto& arp : state->arpeggiators)
  1574. if (arp != nullptr)
  1575. arp->reset();
  1576. for (auto& echo : state->echoes)
  1577. if (echo != nullptr)
  1578. echo->reset();
  1579. }
  1580. // FL's MIDI Out sends its bank and program when playback starts (REA_rodada16 §1.3)
  1581. if (playing && ! wasPlaying && state->hasMidiRoutes)
  1582. for (std::size_t c = 0; c < state->midiTargets.size(); ++c)
  1583. {
  1584. if (state->midiTargets[c].empty())
  1585. continue;
  1586. const auto s = midictl::parseMidiOut (state->song.channels[c].pluginState);
  1587. const auto status = (std::uint8_t) (s.channel & 15);
  1588. for (const auto t : state->midiTargets[c])
  1589. {
  1590. auto& target = *state->instruments[(std::size_t) t];
  1591. if (s.bankMsb >= 0)
  1592. {
  1593. const std::uint8_t m[3] { (std::uint8_t) (0xB0 | status), 0, (std::uint8_t) s.bankMsb };
  1594. target.midiMessage (m, 3);
  1595. }
  1596. if (s.bankLsb >= 0)
  1597. {
  1598. const std::uint8_t m[3] { (std::uint8_t) (0xB0 | status), 32, (std::uint8_t) s.bankLsb };
  1599. target.midiMessage (m, 3);
  1600. }
  1601. if (s.program > 0)
  1602. {
  1603. const std::uint8_t m[2] { (std::uint8_t) (0xC0 | status), (std::uint8_t) (s.program - 1) };
  1604. target.midiMessage (m, 2);
  1605. }
  1606. }
  1607. }
  1608. // started playing or jumped: audio clips in progress must start mid-way
  1609. resumeAudio = playing && (! wasPlaying || jumped);
  1610. wasPlaying = playing;
  1611. // tempo automation: the tempo holds for the whole block (evaluated at its start)
  1612. bpm = state->song.bpm;
  1613. if (state->tempoAutomation >= 0 && state->song.mode == PlayMode::song && ! isSlotOverridden (state->tempoAutomation))
  1614. {
  1615. const auto length = (double) std::max<std::int64_t> (1, state->schedule.songLength);
  1616. const auto& clips = state->automationClips[(std::size_t) state->tempoAutomation];
  1617. if (! clips.empty())
  1618. bpm = tempoFromValue (automationValueAt (state->song, state->song.automations[(std::size_t) state->tempoAutomation], clips,
  1619. std::fmod (std::max (0.0, startTick), length)));
  1620. }
  1621. const auto tps = ticksPerSample (bpm, sampleRate);
  1622. expectedTick = startTick + numSamples * tps;
  1623. for (auto* queue : { live, moreLive })
  1624. {
  1625. if (queue == nullptr)
  1626. continue;
  1627. NoteEvent e;
  1628. while (queue->pop (e))
  1629. {
  1630. if (e.type == NoteEvent::Type::choke && e.channel < 0) // panic: every channel stops sounding
  1631. {
  1632. for (auto& instrument : state->instruments)
  1633. if (instrument != nullptr)
  1634. instrument->panic();
  1635. heldNotes.fill ({});
  1636. for (auto& order : voiceOrders)
  1637. order.clear();
  1638. continue;
  1639. }
  1640. if (e.channel < 0 || e.channel >= (int) state->instruments.size())
  1641. continue;
  1642. if (e.type == NoteEvent::Type::control)
  1643. {
  1644. applyLiveControl (*state, e);
  1645. continue;
  1646. }
  1647. auto& instrument = *state->instruments[(std::size_t) e.channel];
  1648. auto& held = heldNotes[(std::size_t) std::min (e.channel, maxChannels - 1)];
  1649. const auto bit = std::uint64_t { 1 } << (e.key & 63);
  1650. const auto inRange = e.key >= 0 && e.key < 128;
  1651. // played on a MIDI Out channel: the plugins on its port get the note with its MIDI channel
  1652. if (state->hasMidiRoutes && (std::size_t) e.channel < state->midiRoutesOut.size())
  1653. for (const auto& route : state->midiRoutesOut[(std::size_t) e.channel])
  1654. if (route.other < (int) state->instruments.size() && state->instruments[(std::size_t) route.other] != nullptr)
  1655. {
  1656. auto& target = *state->instruments[(std::size_t) route.other];
  1657. if (e.type == NoteEvent::Type::on)
  1658. target.noteOnPort (route.port, e.key, e.velocity, route.midiChannel);
  1659. else if (e.type == NoteEvent::Type::off)
  1660. target.noteOffPort (route.port, e.key, route.midiChannel);
  1661. }
  1662. // and the mixer-slot Patchers on its port (round 162)
  1663. // (notes that go through the channel's note path reach them in processChunk)
  1664. if (state->hasEffectMidiRoutes && ! routesLiveNotes (*state, e.channel))
  1665. deliverToEffects (*state, e);
  1666. // the channel's arpeggiator / echo delay / tracking play it (in processChunk's first chunk)
  1667. if ((e.type == NoteEvent::Type::on || e.type == NoteEvent::Type::off) && routesLiveNotes (*state, e.channel))
  1668. {
  1669. if (liveRoutedCount < (int) liveRouted.size())
  1670. {
  1671. e.sampleOffset = 0;
  1672. liveRouted[(std::size_t) liveRoutedCount++] = e;
  1673. }
  1674. continue;
  1675. }
  1676. auto& order = voiceOrders[(std::size_t) std::min (e.channel, maxChannels - 1)];
  1677. if (e.type == NoteEvent::Type::on && (std::size_t) e.channel < state->song.channels.size()
  1678. && ! state->song.channels[(std::size_t) e.channel].inKeyRegion (e.key))
  1679. continue; // outside the channel's key region (round 164)
  1680. if (e.type == NoteEvent::Type::on)
  1681. {
  1682. const auto& def = state->song.channels;
  1683. if ((std::size_t) e.channel < def.size())
  1684. if (const auto limit = voiceLimitFor (def[(std::size_t) e.channel].maxPolyphony, def[(std::size_t) e.channel].synth.mono); limit > 0)
  1685. if (const auto victim = order.noteOn (e.key, limit); victim >= 0)
  1686. instrument.noteOff (victim);
  1687. // a played note is tuned like the song's notes: Misc › Fine tune and the main pitch (round 162, issue
  1688. // #9: the fine tune did nothing to the keys played live)
  1689. if ((std::size_t) e.channel < def.size())
  1690. {
  1691. const auto& misc = def[(std::size_t) e.channel].misc;
  1692. const auto cents = misc.fineTune + (misc.mainPitch ? state->song.masterPitch : 0.0f);
  1693. if (cents != 0.0f)
  1694. instrument.setNextNoteExpression (0.0f, cents, false);
  1695. }
  1696. instrument.noteOn (e.key, e.velocity);
  1697. if (inRange)
  1698. held[(std::size_t) (e.key >> 6)] |= bit;
  1699. }
  1700. else
  1701. {
  1702. order.noteOff (e.key);
  1703. instrument.noteOff (e.key);
  1704. if (inRange)
  1705. held[(std::size_t) (e.key >> 6)] &= ~bit;
  1706. }
  1707. }
  1708. }
  1709. // Blocks larger than the mixer buffers are done in pieces. With automation, small
  1710. // pieces so values move smoothly.
  1711. const auto chunk = std::min (blockCapacity, state->hasAutomation ? 128 : chunkCapacity);
  1712. for (int done = 0; done < numSamples;)
  1713. {
  1714. auto n = std::min (chunk, numSamples - done);
  1715. // pattern events take effect at their own sample, as in FL (REA_rodada85 §3): a chunk ends where one falls
  1716. if (playing && ! state->eventLanes.empty() && tps > 0.0)
  1717. {
  1718. const auto ahead = ticksToNextEvent (*state, startTick + done * tps);
  1719. if (ahead < (double) n * tps)
  1720. n = std::max (1, (int) std::ceil (ahead / tps - 1.0e-9));
  1721. }
  1722. liveInputOffset = done;
  1723. processChunk (*state, playing, startTick + done * tps, n, left + done, right + done, meters);
  1724. resumeAudio = false;
  1725. done += n;
  1726. }
  1727. if (timing)
  1728. {
  1729. times->wallNs.fetch_add (ProcessTimes::now() - wallStart, std::memory_order_relaxed);
  1730. times->audioNs.fetch_add ((std::uint64_t) ((double) numSamples / sampleRate * 1.0e9), std::memory_order_relaxed);
  1731. }
  1732. }
  1733. double RackRenderer::ticksToNextEvent (const RackState& state, double tick) noexcept
  1734. {
  1735. const auto& song = state.song;
  1736. auto best = std::numeric_limits<double>::infinity();
  1737. // first event tick of `events` strictly after `t` (events sorted by tick)
  1738. auto after = [] (const PatternEvents& events, double t) {
  1739. auto it = std::upper_bound (events.events.begin(), events.events.end(), t,
  1740. [] (double x, const PatternEvent& e) { return x < (double) e.tick; });
  1741. return it == events.events.end() ? std::numeric_limits<double>::infinity() : (double) it->tick;
  1742. };
  1743. if (song.mode != PlayMode::song)
  1744. {
  1745. const auto current = song.currentPattern;
  1746. if (current < 0 || current >= (int) song.patterns.size())
  1747. return best;
  1748. const auto& pattern = song.patterns[(std::size_t) current];
  1749. const auto length = (double) std::max<std::int64_t> (1, pattern.effectiveLength (song.beatsPerBar));
  1750. const auto t = std::fmod (std::max (0.0, tick), length);
  1751. for (const auto& lane : state.eventLanes)
  1752. if (lane.pattern == current)
  1753. {
  1754. const auto& events = pattern.events[(std::size_t) lane.lane];
  1755. best = std::min (best, after (events, t) - t);
  1756. if (! events.events.empty()) // the loop restarts at the first event's value
  1757. best = std::min (best, length - t);
  1758. }
  1759. return best;
  1760. }
  1761. const auto length = (double) std::max<std::int64_t> (1, state.schedule.songLength);
  1762. const auto t = std::fmod (std::max (0.0, tick), length);
  1763. for (const auto& lane : state.eventLanes)
  1764. {
  1765. const auto& events = song.patterns[(std::size_t) lane.pattern].events[(std::size_t) lane.lane];
  1766. for (auto i : state.patternClips[(std::size_t) lane.pattern])
  1767. {
  1768. const auto& c = song.playlist[(std::size_t) i];
  1769. if ((double) c.end() <= t)
  1770. continue;
  1771. if ((double) c.start > t)
  1772. {
  1773. best = std::min (best, (double) c.start - t);
  1774. break;
  1775. }
  1776. const auto next = after (events, t - (double) c.start + (double) c.offset) - (double) c.offset + (double) c.start;
  1777. best = std::min (best, std::min (next, (double) c.end()) - t);
  1778. }
  1779. }
  1780. return best;
  1781. }
  1782. void RackRenderer::applyLiveControl (const RackState& state, const NoteEvent& e) noexcept
  1783. {
  1784. // a controller's pitch wheel, mod wheel (CC 1), other CCs and channel pressure played into a channel (round 162,
  1785. // issue #9): hosted plugins (and the SoundFont player) get the MIDI message; LYNX's own instruments bend by the
  1786. // channel's pitch range (FL's Misc › Pitch range, default ±2 semitones) and take the CCs they know
  1787. auto* instrument = state.instruments[(std::size_t) e.channel].get();
  1788. if (instrument == nullptr)
  1789. return;
  1790. std::uint8_t m[3] {};
  1791. auto size = 3;
  1792. const auto value = std::isfinite (e.velocity) ? e.velocity : 0.0f;
  1793. if (e.key == NoteEvent::controlPitchBend)
  1794. {
  1795. const auto v = (int) std::clamp (std::lround ((double) (value + 1.0f) * 8192.0), 0L, 16383L);
  1796. m[0] = 0xE0, m[1] = (std::uint8_t) (v & 127), m[2] = (std::uint8_t) (v >> 7);
  1797. }
  1798. else if (e.key == NoteEvent::controlPressure)
  1799. {
  1800. m[0] = 0xD0, m[1] = (std::uint8_t) std::clamp (std::lround (value * 127.0f), 0L, 127L);
  1801. size = 2;
  1802. }
  1803. else if (e.key >= 0 && e.key < 128)
  1804. m[0] = 0xB0, m[1] = (std::uint8_t) e.key, m[2] = (std::uint8_t) std::clamp (std::lround (value * 127.0f), 0L, 127L);
  1805. else
  1806. return;
  1807. instrument->midiMessage (m, size);
  1808. if (e.key == NoteEvent::controlPitchBend)
  1809. {
  1810. const auto range = (std::size_t) e.channel < state.song.channels.size() ? state.song.channels[(std::size_t) e.channel].misc.pitchRange : 2;
  1811. instrument->pitchBend (std::clamp (value, -1.0f, 1.0f) * (float) std::max (0, range));
  1812. }
  1813. else if (e.key < 128)
  1814. instrument->controlChange (e.key, std::clamp (value, 0.0f, 1.0f));
  1815. // a MIDI Out channel: the plugins on its port get it on its MIDI channel
  1816. if (state.hasMidiRoutes && (std::size_t) e.channel < state.midiTargets.size())
  1817. for (const auto t : state.midiTargets[(std::size_t) e.channel])
  1818. if (t >= 0 && t < (int) state.instruments.size() && state.instruments[(std::size_t) t] != nullptr)
  1819. {
  1820. std::uint8_t routed[3] { (std::uint8_t) ((m[0] & 0xF0) | (state.midiOutChannel[(std::size_t) e.channel] & 15)), m[1], m[2] };
  1821. state.instruments[(std::size_t) t]->midiMessage (routed, size);
  1822. }
  1823. }
  1824. void RackRenderer::expandLayers (const RackState& state) noexcept
  1825. {
  1826. const auto& channels = state.song.channels;
  1827. const auto count = events.size();
  1828. auto added = false;
  1829. for (int i = 0; i < count; ++i)
  1830. {
  1831. const auto e = events[i];
  1832. if (e.channel < 0 || e.channel >= (int) channels.size() || e.channel >= maxChannels)
  1833. continue;
  1834. const auto& l = channels[(std::size_t) e.channel];
  1835. if (l.instrument != InstrumentKind::layer || l.layer.children.empty())
  1836. continue;
  1837. const auto key = std::clamp (e.key, 0, 127);
  1838. auto* picked = layerPick.empty() ? nullptr : &layerPick[(std::size_t) e.channel * 128 + (std::size_t) key];
  1839. auto child = e;
  1840. child.pan = std::clamp (e.pan + l.pan, -1.0f, 1.0f);
  1841. child.cents = e.cents + 100.0f * l.sampler.pitch;
  1842. const auto one = l.layer.random || l.layer.sequential;
  1843. if (e.type == NoteEvent::Type::on)
  1844. {
  1845. if (l.muted)
  1846. continue;
  1847. std::array<layer::Pick, 64> picks;
  1848. const auto n = layer::pick (l, channels, key, layerRandom, layerTurn[(std::size_t) e.channel], picks.data(), (int) picks.size());
  1849. if (one && picked != nullptr)
  1850. *picked = (std::int16_t) (n > 0 ? picks[0].child : -1);
  1851. const auto level = layer::levelGain (l);
  1852. for (int k = 0; k < n; ++k)
  1853. {
  1854. child.channel = picks[(std::size_t) k].child;
  1855. child.gain = e.gain * level * picks[(std::size_t) k].gain;
  1856. events.add (child);
  1857. added = true;
  1858. }
  1859. }
  1860. else if (e.type == NoteEvent::Type::off && one)
  1861. {
  1862. if (picked != nullptr && *picked >= 0)
  1863. {
  1864. child.channel = *picked;
  1865. *picked = -1;
  1866. events.add (child);
  1867. added = true;
  1868. }
  1869. }
  1870. else if (e.type == NoteEvent::Type::off || e.type == NoteEvent::Type::slide || e.type == NoteEvent::Type::choke)
  1871. for (const auto c : l.layer.children)
  1872. if (c >= 0 && c < (int) channels.size() && c != e.channel && channels[(std::size_t) c].instrument != InstrumentKind::layer)
  1873. {
  1874. child.channel = c;
  1875. events.add (child);
  1876. added = true;
  1877. }
  1878. }
  1879. if (added)
  1880. events.sortByOffset();
  1881. }
  1882. bool RackRenderer::routesLiveNotes (const RackState& state, int channel) const noexcept
  1883. {
  1884. const auto c = (std::size_t) channel;
  1885. if (channel < 0 || c >= state.song.channels.size())
  1886. return false;
  1887. if (state.song.channels[c].instrument == InstrumentKind::layer) // (its children play the note: round 164)
  1888. return true;
  1889. const auto& misc = state.song.channels[c].misc;
  1890. return (c < state.arpeggiators.size() && state.arpeggiators[c] != nullptr) || (c < state.echoes.size() && state.echoes[c] != nullptr)
  1891. || misc.key.pan != 0.0f || misc.velocity.pan != 0.0f
  1892. || (misc.addToKey && misc.rootNote != 60 && state.song.channels[c].instrument != InstrumentKind::sampler);
  1893. }
  1894. void RackRenderer::processChunk (const RackState& state, bool playing, double startTick, int numSamples,
  1895. float* left, float* right, MeterBank* meters) noexcept
  1896. {
  1897. chunkTick = startTick;
  1898. chunkPlaying = playing;
  1899. const auto& song = state.song;
  1900. const auto tracks = std::max<int> (1, (int) song.mixer.size());
  1901. if (state.hasAutomation) // (a hair later: a chunk that starts on a pattern event's sample takes its value)
  1902. updateAutomation (state, startTick + 1.0e-6);
  1903. chunkTps = ticksPerSample (bpm, sampleRate);
  1904. chunkStartTick = playing ? startTick : liveTick; // stopped: live notes' arpeggios run on their own clock
  1905. if (! playing)
  1906. liveTick += numSamples * chunkTps;
  1907. // hosted plugins read the transport from here (PluginHost's play head)
  1908. {
  1909. auto& timeline = hostTimeline();
  1910. timeline.tick.store (hostPositionTick (song, startTick, state.schedule.songLength), std::memory_order_relaxed);
  1911. timeline.bpm.store (bpm, std::memory_order_relaxed);
  1912. timeline.sampleRate.store (sampleRate, std::memory_order_relaxed);
  1913. timeline.beatsPerBar.store (std::max (1, song.beatsPerBar), std::memory_order_relaxed);
  1914. timeline.playing.store (playing, std::memory_order_relaxed);
  1915. timeline.looping.store (song.hasLoop(), std::memory_order_relaxed);
  1916. timeline.loopStart.store ((double) song.loopStart, std::memory_order_relaxed);
  1917. timeline.loopEnd.store ((double) song.loopEnd, std::memory_order_relaxed);
  1918. }
  1919. for (int t = 0; t < tracks; ++t)
  1920. {
  1921. std::memset (trackBuffer (t, 0), 0, sizeof (float) * (std::size_t) numSamples);
  1922. std::memset (trackBuffer (t, 1), 0, sizeof (float) * (std::size_t) numSamples);
  1923. }
  1924. events.clear();
  1925. if (playing && song.mode == PlayMode::song)
  1926. {
  1927. scheduleSong (song, startTick, numSamples, ticksPerSample (bpm, sampleRate), events, resumeAudio, &state.schedule,
  1928. liveInput == nullptr || ! liveInput->linearSong.load (std::memory_order_relaxed));
  1929. }
  1930. else if (playing && ! song.patterns.empty())
  1931. {
  1932. const auto patternIndex = std::clamp (song.currentPattern, 0, (int) song.patterns.size() - 1);
  1933. const auto& pattern = song.patterns[(std::size_t) patternIndex];
  1934. schedulePatternLoop (pattern, pattern.effectiveLength (song.beatsPerBar), startTick, numSamples,
  1935. ticksPerSample (bpm, sampleRate), events, song.swing, &song.channels);
  1936. }
  1937. // FL's wrapper "Output port" (round 149): the notes a plugin sent out in the previous chunk play the plugins on
  1938. // that port, at this chunk's start
  1939. if (state.hasMidiOutputs)
  1940. {
  1941. std::array<Instrument::MidiOutNote, 128> notes;
  1942. for (std::size_t c = 0; c < state.midiOutTargets.size() && c < state.instruments.size(); ++c)
  1943. {
  1944. if (state.midiOutTargets[c].empty())
  1945. continue;
  1946. const auto count = state.instruments[c]->takeMidiOutput (notes.data(), (int) notes.size());
  1947. for (int k = 0; k < count; ++k)
  1948. for (const auto t : state.midiOutTargets[c])
  1949. {
  1950. NoteEvent e;
  1951. e.type = notes[(std::size_t) k].velocity > 0.0f ? NoteEvent::Type::on : NoteEvent::Type::off;
  1952. e.channel = t;
  1953. e.key = notes[(std::size_t) k].key;
  1954. e.velocity = notes[(std::size_t) k].velocity;
  1955. e.sampleOffset = 0;
  1956. events.add (e);
  1957. }
  1958. }
  1959. events.sortByOffset();
  1960. }
  1961. // live-played notes routed through their channel's note path (round 149)
  1962. if (liveRoutedCount > 0)
  1963. {
  1964. for (int k = 0; k < liveRoutedCount; ++k)
  1965. events.add (liveRouted[(std::size_t) k]);
  1966. liveRoutedCount = 0;
  1967. events.sortByOffset();
  1968. }
  1969. // Layer channels play their children (round 164)
  1970. if (state.hasLayers)
  1971. expandLayers (state);
  1972. // cut groups: each note of a channel "cuts" the channels linked to it, at the same sample
  1973. if (state.hasCutGroups)
  1974. {
  1975. const auto count = events.size();
  1976. for (int i = 0; i < count; ++i)
  1977. {
  1978. const auto e = events[i];
  1979. if (e.type != NoteEvent::Type::on || e.channel < 0 || e.channel >= (int) state.cutTargets.size())
  1980. continue;
  1981. for (auto target : state.cutTargets[(std::size_t) e.channel])
  1982. {
  1983. NoteEvent choke;
  1984. choke.type = NoteEvent::Type::choke;
  1985. choke.channel = target;
  1986. choke.sampleOffset = e.sampleOffset;
  1987. events.add (choke);
  1988. }
  1989. }
  1990. events.sortByOffset();
  1991. }
  1992. // MIDI to the mixer-slot Patchers that take a MIDI port (round 162): at the chunk's start
  1993. if (state.hasEffectMidiRoutes)
  1994. for (int k = 0; k < events.size(); ++k)
  1995. deliverToEffects (state, events[k]);
  1996. // 1) channels, each with its own notes at the exact sample (in parallel when worth it)
  1997. const auto channels = std::min<int> ({ (int) state.instruments.size(), (int) song.channels.size(), maxChannels });
  1998. auto channel = [this, &state, numSamples] (int c) {
  1999. if (! times->enabled.load (std::memory_order_relaxed) || c >= ProcessTimes::channels)
  2000. {
  2001. renderChannel (state, c, numSamples);
  2002. return;
  2003. }
  2004. const auto before = ProcessTimes::now();
  2005. renderChannel (state, c, numSamples);
  2006. times->channelNs[(std::size_t) c].fetch_add (ProcessTimes::now() - before, std::memory_order_relaxed);
  2007. };
  2008. if (workers != nullptr && state.parallel && state.audioThreadChannels.empty())
  2009. workers->parallelFor (channels, channel);
  2010. else if (workers != nullptr && state.parallel)
  2011. {
  2012. // "Allow threaded processing" off: those channels on this thread, the rest in parallel
  2013. auto threaded = [&state, &channel, channels] (int i) {
  2014. if (const auto c = state.threadedChannels[(std::size_t) i]; c < channels)
  2015. channel (c);
  2016. };
  2017. workers->parallelFor ((int) state.threadedChannels.size(), threaded);
  2018. for (const auto c : state.audioThreadChannels)
  2019. if (c < channels)
  2020. channel (c);
  2021. }
  2022. else
  2023. for (int c = 0; c < channels; ++c)
  2024. channel (c);
  2025. for (int c = 0; c < channels; ++c)
  2026. {
  2027. if (channelSilent[(std::size_t) c])
  2028. continue;
  2029. const auto t = std::clamp (song.channels[(std::size_t) c].mixerTrack, 0, tracks - 1);
  2030. auto* dl = trackBuffer (t, 0);
  2031. auto* dr = trackBuffer (t, 1);
  2032. const auto* sl = channelBuffer (c, 0);
  2033. const auto* sr = channelBuffer (c, 1);
  2034. for (int k = 0; k < numSamples; ++k)
  2035. {
  2036. dl[k] += sl[k];
  2037. dr[k] += sr[k];
  2038. }
  2039. // extra outputs to other inserts (a generator Patcher's, REA_rodada141)
  2040. if ((std::size_t) c < state.instruments.size() && state.instruments[(std::size_t) c] != nullptr)
  2041. {
  2042. const auto& instrument = *state.instruments[(std::size_t) c];
  2043. for (int k = 0; k < instrument.auxOutputCount(); ++k)
  2044. {
  2045. const auto target = instrument.auxOutputTrack (k);
  2046. const auto* al = instrument.auxOutputData (k, 0);
  2047. const auto* ar = instrument.auxOutputData (k, 1);
  2048. if (target < 0 || target >= tracks || al == nullptr || ar == nullptr)
  2049. continue;
  2050. auto* tl = trackBuffer (target, 0);
  2051. auto* tr = trackBuffer (target, 1);
  2052. for (int x = 0; x < numSamples; ++x)
  2053. {
  2054. tl[x] += al[x];
  2055. tr[x] += ar[x];
  2056. }
  2057. }
  2058. }
  2059. }
  2060. if (liveInput != nullptr && liveInput->numChannels > 0)
  2061. mixLiveInput (state, playing, numSamples);
  2062. // 2) inserts by layers: within a layer nothing depends on anything else; each track pulls the
  2063. // outputs of the tracks that send to it (without writing into others' buffers)
  2064. trackActive.fill (0);
  2065. tapActive.fill (0);
  2066. for (std::size_t d = 0; d < state.mixerLayers.size(); ++d)
  2067. {
  2068. const auto split = d < state.audioThreadLayers.size() && ! state.audioThreadLayers[d].empty();
  2069. const auto& layer = split ? state.threadedLayers[d] : state.mixerLayers[d];
  2070. auto track = [this, &state, &layer, numSamples, meters] (int i) { processTrack (state, layer[(std::size_t) i], numSamples, meters); };
  2071. if (workers != nullptr && state.parallel && layer.size() > 1)
  2072. workers->parallelFor ((int) layer.size(), track);
  2073. else
  2074. for (int i = 0; i < (int) layer.size(); ++i)
  2075. track (i);
  2076. if (split) // inserts with a plugin whose "Allow threaded processing" is off
  2077. for (const auto t : state.audioThreadLayers[d])
  2078. processTrack (state, t, numSamples, meters);
  2079. }
  2080. // 3) Master: inputs, effects, fader. Without a configured mixer, it stays at 0 dB.
  2081. pullInputs (state, 0, numSamples);
  2082. runEffects (state, 0, numSamples);
  2083. if (! song.mixer.empty())
  2084. {
  2085. applyTrackEq (song.mixer[0], 0, song.cleanMixer, trackBuffer (0, 0), trackBuffer (0, 1), numSamples);
  2086. applyStereo (song.mixer[0], trackBuffer (0, 0), trackBuffer (0, 1), numSamples);
  2087. }
  2088. float gl = 1.0f, gr = 1.0f;
  2089. if (! song.mixer.empty())
  2090. {
  2091. const auto& master = song.mixer[0];
  2092. const auto volume = state.hasAutomation ? automated (state.mixerVolumeAuto[0], master.volume) : master.volume;
  2093. const auto pan = state.hasAutomation ? automated (state.mixerPanAuto[0], (master.pan + 1.0f) * 0.5f) * 2.0f - 1.0f : master.pan;
  2094. panGains (pan, master.muted ? 0.0f : faderGain (volume), gl, gr);
  2095. }
  2096. auto& lastL = lastTrackGain[0];
  2097. auto& lastR = lastTrackGain[1];
  2098. const auto fromL = std::isnan (lastL) ? gl : lastL;
  2099. const auto fromR = std::isnan (lastR) ? gr : lastR;
  2100. const auto* masterL = trackBuffer (0, 0);
  2101. const auto* masterR = trackBuffer (0, 1);
  2102. lastL = glideGain (masterL, left, numSamples, fromL, gl);
  2103. lastR = glideGain (masterR, right, numSamples, fromR, gr);
  2104. if (meters != nullptr)
  2105. {
  2106. meters->accumulate (0, peakOf (left, numSamples), peakOf (right, numSamples));
  2107. meters->capture.push (0, left, right, numSamples);
  2108. meters->logTap.push (0, left, right, numSamples);
  2109. }
  2110. if (hwOut != nullptr && ! state.hwRoutes.empty() && hwOut->active.load (std::memory_order_relaxed))
  2111. mixHardwareOutputs (state, numSamples);
  2112. }
  2113. // 4) inserts with a hardware output target: their post-fader output (the same signal the Master gets) into the
  2114. // device-channel buses, delayed like the Master's path
  2115. void RackRenderer::mixHardwareOutputs (const RackState& state, int n) noexcept
  2116. {
  2117. auto* sl = hwScratch.data();
  2118. auto* sr = hwScratch.data() + blockCapacity;
  2119. for (const auto& route : state.hwRoutes)
  2120. {
  2121. const auto t = route.track;
  2122. if (t <= 0 || t >= maxMixerTracks)
  2123. continue;
  2124. const float* l = trackActive[(std::size_t) t] ? trackBuffer (t, 0) : nullptr;
  2125. const float* r = trackActive[(std::size_t) t] ? trackBuffer (t, 1) : nullptr;
  2126. if (route.delay != nullptr)
  2127. {
  2128. if (l != nullptr)
  2129. {
  2130. std::copy (l, l + n, sl);
  2131. std::copy (r, r + n, sr);
  2132. }
  2133. else
  2134. {
  2135. std::fill (sl, sl + n, 0.0f);
  2136. std::fill (sr, sr + n, 0.0f);
  2137. }
  2138. route.delay->process (sl, sr, n);
  2139. l = sl;
  2140. r = sr;
  2141. }
  2142. if (l == nullptr)
  2143. continue;
  2144. const auto [first, count] = outputChannelsOf (route.channel, route.mode);
  2145. auto* a = hwOut->bus (first, liveInputOffset, n);
  2146. auto* b = count > 1 ? hwOut->bus (first + 1, liveInputOffset, n) : nullptr;
  2147. addToOutput (l, r, route.mode, a, b, n);
  2148. }
  2149. }
  2150. // Track stereo separation, phase and channel swap (before the fader, like FL).
  2151. // Narrowing uses FL's exponential curve, widening is linear (docs/analise/REA_rodada2.md §2.2).
  2152. void RackRenderer::applyStereo (const MixerTrack& track, float* l, float* r, int n) noexcept
  2153. {
  2154. if (track.stereo != 0.0f)
  2155. {
  2156. const auto s = track.stereo > 0.0f ? (std::pow (5.0f, std::min (track.stereo, 1.0f)) - 1.0f) / 4.0f
  2157. : std::max (track.stereo, -1.0f);
  2158. // s = 1: mono; s = -1: side doubled
  2159. const auto keep = 1.0f - 0.5f * s, cross = 0.5f * s;
  2160. for (int i = 0; i < n; ++i)
  2161. {
  2162. const auto a = l[i], b = r[i];
  2163. l[i] = keep * a + cross * b;
  2164. r[i] = keep * b + cross * a;
  2165. }
  2166. }
  2167. if (track.swapChannels)
  2168. for (int i = 0; i < n; ++i)
  2169. std::swap (l[i], r[i]);
  2170. if (track.invertPhase)
  2171. for (int i = 0; i < n; ++i)
  2172. {
  2173. l[i] = -l[i];
  2174. r[i] = -r[i];
  2175. }
  2176. }
  2177. void RackRenderer::mixLiveInput (const RackState& state, bool playing, int n) noexcept
  2178. {
  2179. const auto& mixer = state.song.mixer;
  2180. const auto recording = liveInput->recording.load (std::memory_order_relaxed);
  2181. // the Master too (FL's slot panel has its audio input selector; REA round 143): it plays whenever its
  2182. // monitoring is not off (it has no record arm)
  2183. for (int t = 0; t < (int) mixer.size() && t < maxMixerTracks; ++t)
  2184. {
  2185. const auto& track = mixer[(std::size_t) t];
  2186. const auto [first, count] = inputChannelsOf (track, liveInput->numChannels);
  2187. if (count == 0)
  2188. continue;
  2189. const auto* a = liveInput->channel (first, liveInputOffset);
  2190. const auto* b = count > 1 ? liveInput->channel (first + 1, liveInputOffset) : a;
  2191. if (a == nullptr || b == nullptr)
  2192. continue;
  2193. liveInput->meters.accumulate (t, peakOf (a, n), peakOf (b, n));
  2194. if (t == 0 ? track.monitor == InputMonitor::off
  2195. : ! inputMonitored (track.monitor, liveInput->armed[(std::size_t) t].load (std::memory_order_relaxed), playing, recording))
  2196. continue;
  2197. auto* dl = trackBuffer (t, 0);
  2198. auto* dr = trackBuffer (t, 1);
  2199. for (int i = 0; i < n; ++i)
  2200. {
  2201. dl[i] += a[i];
  2202. dr[i] += b[i];
  2203. }
  2204. }
  2205. }
  2206. void RackRenderer::pullInputs (const RackState& state, int t, int n) noexcept
  2207. {
  2208. if ((std::size_t) t >= state.mixerInputs.size())
  2209. return;
  2210. auto* dl = trackBuffer (t, 0);
  2211. auto* dr = trackBuffer (t, 1);
  2212. for (const auto& in : state.mixerInputs[(std::size_t) t])
  2213. {
  2214. const auto tap = in.tap >= 0 && in.tap < RackState::maxSendTaps ? in.tap : -1;
  2215. const auto active = tap >= 0 ? tapActive[(std::size_t) tap] : trackActive[(std::size_t) in.source];
  2216. const auto& delays = state.sendDelays[(std::size_t) in.source];
  2217. auto* delay = (std::size_t) in.delay < delays.size() ? delays[(std::size_t) in.delay].get() : nullptr;
  2218. auto* sl = tap >= 0 ? tapBuffer (tap, 0) : trackBuffer (in.source, 0);
  2219. auto* sr = tap >= 0 ? tapBuffer (tap, 1) : trackBuffer (in.source, 1);
  2220. if (delay != nullptr)
  2221. {
  2222. // PDC: this edge is shorter than the slowest one arriving here. A silent source
  2223. // still drains the tail that was in the line.
  2224. delay->mixInto (active ? sl : nullptr, active ? sr : nullptr, in.level, dl, dr, n);
  2225. continue;
  2226. }
  2227. if (! active)
  2228. continue;
  2229. for (int i = 0; i < n; ++i)
  2230. {
  2231. dl[i] += sl[i] * in.level;
  2232. dr[i] += sr[i] * in.level;
  2233. }
  2234. }
  2235. }
  2236. void RackRenderer::processTrack (const RackState& state, int t, int n, MeterBank* meters) noexcept
  2237. {
  2238. const auto& track = state.song.mixer[(std::size_t) t];
  2239. pullInputs (state, t, n);
  2240. const auto silent = track.muted || ! state.mixerAudible[(std::size_t) t];
  2241. // target gain; the ramp from the previous block avoids clicks on mute and fader
  2242. float gl = 0.0f, gr = 0.0f;
  2243. if (! silent)
  2244. {
  2245. const auto volume = state.hasAutomation ? automated (state.mixerVolumeAuto[(std::size_t) t], track.volume) : track.volume;
  2246. const auto pan = state.hasAutomation ? automated (state.mixerPanAuto[(std::size_t) t], (track.pan + 1.0f) * 0.5f) * 2.0f - 1.0f
  2247. : track.pan;
  2248. panGains (pan, faderGain (volume), gl, gr);
  2249. }
  2250. auto& lastL = lastTrackGain[(std::size_t) t * 2];
  2251. auto& lastR = lastTrackGain[(std::size_t) t * 2 + 1];
  2252. const auto fromL = std::isnan (lastL) ? gl : lastL;
  2253. const auto fromR = std::isnan (lastR) ? gr : lastR;
  2254. if (silent && fromL == 0.0f && fromR == 0.0f)
  2255. {
  2256. if (meters != nullptr)
  2257. meters->capture.pushSilence (t, n);
  2258. return; // stays inactive: nobody pulls anything from it
  2259. }
  2260. runEffects (state, t, n);
  2261. auto* l = trackBuffer (t, 0);
  2262. auto* r = trackBuffer (t, 1);
  2263. applyTrackEq (track, t, state.song.cleanMixer, l, r, n);
  2264. applyStereo (track, l, r, n);
  2265. lastL = glideGain (l, l, n, fromL, gl);
  2266. lastR = glideGain (r, r, n, fromR, gr);
  2267. trackActive[(std::size_t) t] = 1;
  2268. if (meters != nullptr)
  2269. {
  2270. meters->accumulate (t, peakOf (l, n), peakOf (r, n));
  2271. meters->capture.push (t, l, r, n);
  2272. }
  2273. }
  2274. } // namespace lynx