RackRenderer.cpp 165 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598
  1. #include "core/RackRenderer.h"
  2. #include "core/ModelParams.h"
  3. #include "core/SamplePrecompute.h"
  4. #include "core/MetronomeVoice.h"
  5. #include "core/ChannelLoops.h"
  6. #include "core/ControlSurface.h"
  7. #include "core/VoltageController.h"
  8. #include "core/FlSynths.h"
  9. #include "core/HardwareInsert.h"
  10. #include "core/Layer.h"
  11. #include "core/RackOps.h"
  12. #include "core/HostSlide.h"
  13. #include "core/Vfx.h"
  14. #include "core/FacetEq.h"
  15. #include "core/MidiControls.h"
  16. #include "core/MidiOut.h"
  17. #include "core/Patcher.h"
  18. #include "core/LoadTrace.h"
  19. #include "core/DynamicsSuite.h"
  20. #include "core/MixSuite.h"
  21. #include "core/VoiceTools.h"
  22. #include "core/WorkerPool.h"
  23. #include "core/Denormals.h"
  24. #include "core/FlKeys.h"
  25. #include "core/FlVoiceProcessor.h"
  26. #include "core/DirectWave.h"
  27. #include "core/SoundFont.h"
  28. #include "core/NewtoneFx.h"
  29. #include "core/Dvs.h"
  30. #include "core/Scratcher.h"
  31. #include <algorithm>
  32. #include <atomic>
  33. #include <chrono>
  34. #include <cstdlib>
  35. #include <ctime>
  36. #include <cmath>
  37. #include <cstring>
  38. #include <limits>
  39. #include <map>
  40. #include <mutex>
  41. #include <thread>
  42. namespace lynx
  43. {
  44. namespace
  45. {
  46. // a hosted plugin is created again when its processing options change (fixed blocks, own process)
  47. bool samePluginProcessing (const PluginRef& a, const PluginRef& b) noexcept
  48. {
  49. return a.fixedBuffers == b.fixedBuffers && a.separateProcess == b.separateProcess && a.maxSizeBuffers == b.maxSizeBuffers
  50. && a.hostMaxBuffer == b.hostMaxBuffer;
  51. }
  52. // Silent instrument: plugin channel that could not be loaded.
  53. class SilentInstrument final : public Instrument
  54. {
  55. public:
  56. void prepare (double) noexcept override {}
  57. void noteOn (int, float) noexcept override {}
  58. void noteOff (int) noexcept override {}
  59. void allNotesOff() noexcept override {}
  60. void render (float*, float*, int, float, float) noexcept override {}
  61. };
  62. // FL Keys: the data FL builds from a wavetable's files, shared by every channel that plays the same wavetable
  63. // (Grand Piano holds 40 MB of 16-bit samples)
  64. std::shared_ptr<const flkeys::Wavetable> flKeysWavetable (const ChannelDef& channel, const RackState::SampleProvider& samples)
  65. {
  66. const auto table = flkeys::FlKeysTable::decode (channel.modelParams);
  67. if (! table || ! samples || table->files.size() != channel.zones.size())
  68. return nullptr;
  69. std::string key;
  70. for (const auto& z : channel.zones)
  71. key += z.path + '\n';
  72. for (auto v : channel.modelParams)
  73. key += std::to_string (v) + ' ';
  74. static std::mutex lock;
  75. static std::map<std::string, std::weak_ptr<const flkeys::Wavetable>> cache;
  76. {
  77. std::lock_guard<std::mutex> guard (lock);
  78. if (auto found = cache[key].lock())
  79. return found;
  80. }
  81. std::vector<flkeys::FileSamples> files;
  82. for (std::size_t i = 0; i < channel.zones.size(); ++i)
  83. {
  84. const auto sample = samples (channel.zones[i].path);
  85. if (sample == nullptr || sample->frames() == 0)
  86. return nullptr;
  87. files.push_back (flkeys::toFileSamples (*sample, table->files[i].scale));
  88. }
  89. auto built = flkeys::buildWavetable (*table, files);
  90. std::lock_guard<std::mutex> guard (lock);
  91. cache[key] = built;
  92. return built;
  93. }
  94. // Effect that does nothing: missing plugin slot.
  95. class BypassEffect final : public Effect
  96. {
  97. public:
  98. void prepare (double) noexcept override {}
  99. void reset() noexcept override {}
  100. void process (float*, float*, int, const EffectParams&, double) noexcept override {}
  101. };
  102. } // namespace
  103. std::unique_ptr<const RackState> RackState::build (Song song,
  104. const RackState* previous,
  105. double sampleRate,
  106. const SampleProvider& samples)
  107. {
  108. Factories factories;
  109. factories.samples = samples;
  110. return build (std::move (song), previous, sampleRate, factories);
  111. }
  112. namespace
  113. {
  114. // A channel's instrument, built new (UI thread)
  115. // deferKeyShift (round 165i): the pitch shifters of a keep-pitch sampler are made later by the caller, all channels at
  116. // once in parallel (Thief: 29 such channels × 8 shifters took most of the 860 ms of rack_instruments, one by one)
  117. std::shared_ptr<Instrument> buildInstrument (const ChannelDef& channel, double sampleRate, double bpm, const RackState::Factories& factories,
  118. std::vector<Instrument*>* deferKeyShift = nullptr)
  119. {
  120. const auto& samples = factories.samples;
  121. const auto kind = channel.instrument;
  122. if (kind == InstrumentKind::plugin)
  123. {
  124. std::shared_ptr<Instrument> instrument;
  125. if (factories.pluginInstruments && ! channel.plugin.id.empty())
  126. instrument = factories.pluginInstruments (channel.plugin, sampleRate);
  127. return instrument != nullptr ? instrument : std::make_shared<SilentInstrument>();
  128. }
  129. // FL Keys: its wavetable built from the channel's files
  130. if (kind == InstrumentKind::flkeys)
  131. {
  132. std::shared_ptr<Instrument> instrument = flkeys::makeFlKeysInstrument (flKeysWavetable (channel, samples));
  133. instrument->prepare (sampleRate);
  134. instrument->configure (channel, bpm);
  135. return instrument;
  136. }
  137. // DirectWave (REA_rodada72): the zones' samples as the plugin holds them
  138. if (kind == InstrumentKind::directwave)
  139. {
  140. const auto formats = dw::decodeFormats (channel.modelParams);
  141. std::vector<std::shared_ptr<const dw::ZoneSamples>> zs;
  142. for (std::size_t z = 0; z < channel.zones.size(); ++z)
  143. {
  144. std::shared_ptr<const dw::ZoneSamples> s;
  145. if (samples && ! channel.zones[z].path.empty())
  146. if (const auto data = samples (channel.zones[z].path))
  147. s = dw::zoneSamples (*data, z < formats.size() && formats[z]);
  148. zs.push_back (std::move (s));
  149. }
  150. std::shared_ptr<Instrument> instrument = dw::makeDirectWaveInstrument (std::move (zs));
  151. instrument->prepare (sampleRate);
  152. instrument->configure (channel, bpm);
  153. return instrument;
  154. }
  155. // LYNX Soundfont (REA_rodada158): the font is loaded on a background thread and shared by the channels playing it
  156. if (kind == InstrumentKind::soundfont)
  157. {
  158. std::shared_ptr<Instrument> instrument = sf::makeInstrument (channel.samplePath.empty() ? nullptr : sf::FontLibrary::instance().get (channel.samplePath));
  159. instrument->prepare (sampleRate);
  160. instrument->configure (channel, bpm);
  161. return instrument;
  162. }
  163. // multi-sample sampler: one zone per sample (DirectWave, FPC layers...)
  164. if (kind == InstrumentKind::sampler && ! channel.zones.empty())
  165. {
  166. const loadtrace::Scope timing ("rack_zoned");
  167. std::vector<LoadedZone> zones;
  168. for (const auto& z : channel.zones)
  169. zones.push_back ({ z, samples ? samples (z.path) : nullptr });
  170. std::shared_ptr<Instrument> instrument = makeZonedSampler (std::move (zones));
  171. instrument->prepare (sampleRate);
  172. instrument->configure (channel, bpm);
  173. return instrument;
  174. }
  175. std::shared_ptr<const SampleData> sample;
  176. if ((kind == InstrumentKind::sampler || kind == InstrumentKind::audioClip || kind == InstrumentKind::granulizer
  177. || kind == InstrumentKind::wavetraveller) && samples
  178. && ! channel.samplePath.empty())
  179. sample = samples (channel.samplePath);
  180. // pitch-preserving stretch: the sample comes already stretched to the current tempo
  181. if (sample != nullptr && kind != InstrumentKind::granulizer && kind != InstrumentKind::wavetraveller && channel.sampler.keepPitch && channel.sampler.stretchBeats > 0.0f
  182. && factories.stretchedSamples
  183. && sample->frames() > 0)
  184. {
  185. const auto target = channel.sampler.stretchBeats * 60.0 / std::max (1.0, bpm);
  186. const auto ratio = target / ((double) sample->frames() / sample->sampleRate);
  187. if (auto stretched = factories.stretchedSamples (channel.samplePath, ratio, channel.sampler.stretchMethod))
  188. sample = std::move (stretched);
  189. }
  190. // FL's Sampler › Precomputed effects (REA_rodada167h §2): the played region, processed once
  191. // Audio clips too (round 167k, FL render r167k/fl/clip/p_*: an audio clip channel's Normalize, Reverse polarity,
  192. // Fade in / out play in FL); a clip plays the whole file, so the region stays whole there
  193. if (sample != nullptr && kind == InstrumentKind::sampler && precompute::needed (channel.sampler))
  194. {
  195. if (auto processed = precompute::apply (*sample, channel.sampler))
  196. sample = std::move (processed);
  197. }
  198. else if (sample != nullptr && kind == InstrumentKind::audioClip && channel.sampler.precompute.any())
  199. {
  200. auto whole = channel.sampler;
  201. whole.regionStart = 0.0f;
  202. whole.regionEnd = 1.0f;
  203. if (auto processed = precompute::apply (*sample, whole))
  204. sample = std::move (processed);
  205. }
  206. const loadtrace::Scope timing ("rack_instruments");
  207. std::shared_ptr<Instrument> instrument = makeInstrument (kind, std::move (sample));
  208. instrument->prepare (sampleRate);
  209. instrument->configure (channel, bpm);
  210. instrument->settleNew();
  211. if ((kind == InstrumentKind::sampler || kind == InstrumentKind::audioClip) && channel.sampler.keepPitch)
  212. {
  213. if (deferKeyShift != nullptr)
  214. deferKeyShift->push_back (instrument.get());
  215. else
  216. instrument->prepareKeyShift (sampleRate); // transpositions keep the length (rounds 162, 163)
  217. }
  218. return instrument;
  219. }
  220. // A slot's effect, built new (UI thread)
  221. std::shared_ptr<Effect> buildEffect (const EffectSlot& slot, double sampleRate, const RackState::Factories& factories)
  222. {
  223. const auto kind = slot.kind;
  224. std::shared_ptr<Effect> effect;
  225. if (kind == EffectKind::plugin)
  226. {
  227. if (factories.pluginEffects && ! slot.plugin.id.empty())
  228. effect = factories.pluginEffects (slot.plugin, sampleRate);
  229. if (effect == nullptr)
  230. effect = std::make_shared<BypassEffect>();
  231. }
  232. else if ((kind == EffectKind::newtone || kind == EffectKind::newtime))
  233. {
  234. // Newtone / Newtime: their source sample (loaded off the audio thread), REA_rodada73
  235. // (Newtone: its note edits rendered by LYNX's engine, REA_rodada95)
  236. effect = newtonefx::make (factories.samples && ! slot.samplePath.empty() ? factories.samples (slot.samplePath) : nullptr,
  237. slot.state);
  238. effect->prepare (sampleRate);
  239. }
  240. else if (kind == EffectKind::scratcher)
  241. {
  242. // Fruity Scratcher: its turntable's sample, loaded off the audio thread (REA_rodada165g-flscratch165)
  243. effect = scratcher::make (factories.samples && ! slot.samplePath.empty() ? factories.samples (slot.samplePath) : nullptr);
  244. effect->prepare (sampleRate);
  245. // its DVS position table (REA_rodada167c §1), built here so the audio thread finds it ready
  246. dvs::warm (scratcher::timecodeOf (slot.params[scratcher::timecodeType]), true);
  247. }
  248. else
  249. {
  250. const loadtrace::Scope timing ("rack_builtin_fx"); // (round 112: what the open spends on LYNX's own effects)
  251. effect = makeEffect (slot);
  252. effect->prepare (sampleRate);
  253. }
  254. return effect;
  255. }
  256. // What a Patcher builds its nodes with: the same builders as the rack's channels and slots
  257. patcher::Factories patcherFactories (double sampleRate, double bpm, const RackState::Factories& factories)
  258. {
  259. patcher::Factories f;
  260. f.effect = [sampleRate, bpm, factories] (const EffectSlot& slot) -> std::shared_ptr<Effect> {
  261. if (slot.kind == EffectKind::patcher)
  262. {
  263. std::shared_ptr<Effect> e = patcher::makeEffect (slot, sampleRate, patcherFactories (sampleRate, bpm, factories));
  264. e->prepare (sampleRate);
  265. return e;
  266. }
  267. return buildEffect (slot, sampleRate, factories);
  268. };
  269. f.instrument = [sampleRate, bpm, factories] (const ChannelDef& channel) -> std::shared_ptr<Instrument> {
  270. if (channel.instrument == InstrumentKind::patcher)
  271. {
  272. std::shared_ptr<Instrument> i = patcher::makeInstrument (channel, sampleRate, patcherFactories (sampleRate, bpm, factories));
  273. i->configure (channel, bpm);
  274. return i;
  275. }
  276. return buildInstrument (channel, sampleRate, bpm, factories);
  277. };
  278. return f;
  279. }
  280. // an audio clip channel that resamples but has a clip of its own pitch (FL 2026's keys 7/8): it needs the shifters
  281. bool clipShiftWanted (const Song& song, std::size_t channel)
  282. {
  283. if (channel >= song.channels.size() || song.channels[channel].instrument != InstrumentKind::audioClip
  284. || song.channels[channel].sampler.keepPitch)
  285. return false;
  286. for (const auto& c : song.playlist)
  287. if (c.kind == ClipKind::audio && c.channel == (int) channel && c.pitch != 0.0f)
  288. return true;
  289. return false;
  290. }
  291. // The keep-pitch samplers' shifters, in parallel: each instrument only touches its own pool, and each shifter's
  292. // set-up is deterministic (a fixed seed and a silent priming run), so the result is the same as one by one
  293. void prepareKeyShifts (const std::vector<Instrument*>& list, double sampleRate)
  294. {
  295. if (list.empty())
  296. return;
  297. const loadtrace::Scope timing ("rack_keyshift");
  298. const auto threads = (std::size_t) std::clamp ((int) std::thread::hardware_concurrency() - 1, 1, 6);
  299. const char* off = std::getenv ("LYNX_PARALLEL_KEYSHIFT"); // "0": one by one (A/B and the null test)
  300. if (list.size() < 2 || threads < 2 || (off != nullptr && off[0] == '0'))
  301. {
  302. for (auto* i : list)
  303. i->prepareKeyShift (sampleRate);
  304. return;
  305. }
  306. std::atomic<std::size_t> next { 0 };
  307. const auto mode = FloatMode::current(); // the helpers round and flush like this thread
  308. auto work = [&] {
  309. mode.applyHere();
  310. for (auto k = next.fetch_add (1); k < list.size(); k = next.fetch_add (1))
  311. list[k]->prepareKeyShift (sampleRate);
  312. };
  313. std::vector<std::thread> helpers;
  314. for (std::size_t t = 1; t < std::min (threads, list.size()); ++t)
  315. {
  316. try
  317. {
  318. helpers.emplace_back (work);
  319. }
  320. catch (...) // no thread: the others (and this one) do the rest
  321. {
  322. break;
  323. }
  324. }
  325. work();
  326. for (auto& h : helpers)
  327. h.join();
  328. }
  329. } // namespace
  330. std::unique_ptr<const RackState> RackState::build (Song song,
  331. const RackState* previous,
  332. double sampleRate,
  333. const Factories& factories)
  334. {
  335. const auto& samples = factories.samples;
  336. auto state = std::make_unique<RackState>();
  337. state->instruments.reserve (song.channels.size());
  338. std::vector<Instrument*> keyShiftLater; // new instruments only: none is visible to the audio thread yet
  339. for (std::size_t i = 0; i < song.channels.size(); ++i)
  340. {
  341. const auto& channel = song.channels[i];
  342. const auto kind = channel.instrument;
  343. if (previous != nullptr && i < previous->song.channels.size() && i < previous->instruments.size()
  344. && previous->song.channels[i].instrument == kind && kind != InstrumentKind::patcher
  345. && ((kind != InstrumentKind::granulizer && kind != InstrumentKind::wavetraveller)
  346. || previous->song.channels[i].samplePath == channel.samplePath)
  347. && (kind != InstrumentKind::soundfont
  348. || (previous->song.channels[i].samplePath == channel.samplePath && previous->sampleRate == sampleRate))
  349. && (kind != InstrumentKind::directwave
  350. || (previous->song.channels[i].zones == channel.zones && previous->song.channels[i].modelParams == channel.modelParams
  351. && previous->song.channels[i].pluginState == channel.pluginState && previous->sampleRate == sampleRate))
  352. && ((kind != InstrumentKind::sampler && kind != InstrumentKind::audioClip && kind != InstrumentKind::flkeys)
  353. || (previous->song.channels[i].samplePath == channel.samplePath && previous->song.channels[i].zones == channel.zones
  354. && previous->song.channels[i].modelParams == channel.modelParams
  355. && previous->song.channels[i].sampler.keepPitch == channel.sampler.keepPitch
  356. && clipShiftWanted (previous->song, i) == clipShiftWanted (song, i)
  357. // FL's precomputed effects (round 167h): the sample is processed when the channel is built
  358. && previous->song.channels[i].sampler.precompute == channel.sampler.precompute
  359. && previous->song.channels[i].sampler.useLoopPoints == channel.sampler.useLoopPoints
  360. && (! precompute::needed (channel.sampler)
  361. || (previous->song.channels[i].sampler.regionStart == channel.sampler.regionStart
  362. && previous->song.channels[i].sampler.regionEnd == channel.sampler.regionEnd
  363. && previous->song.channels[i].sampler.reverse == channel.sampler.reverse
  364. && precompute::needed (previous->song.channels[i].sampler)))
  365. && (! channel.sampler.keepPitch
  366. || (previous->song.channels[i].sampler.stretchBeats == channel.sampler.stretchBeats
  367. && previous->song.channels[i].sampler.stretchMethod == channel.sampler.stretchMethod
  368. && previous->song.bpm == song.bpm))))
  369. && (kind != InstrumentKind::plugin
  370. || (previous->song.channels[i].plugin.id == channel.plugin.id && previous->sampleRate == sampleRate
  371. && samePluginProcessing (previous->song.channels[i].plugin, channel.plugin))))
  372. {
  373. state->instruments.push_back (previous->instruments[i]);
  374. state->instruments.back()->configure (channel, song.bpm);
  375. continue;
  376. }
  377. // FL's Patcher as a generator (REA_rodada141): same structure keeps the running graph (it takes the values)
  378. if (kind == InstrumentKind::patcher)
  379. {
  380. const auto* old = previous != nullptr && i < previous->instruments.size() ? previous->instruments[i].get() : nullptr;
  381. if (old != nullptr && previous->song.channels[i].instrument == kind && previous->sampleRate == sampleRate
  382. && patcher::sameStructure (previous->song.channels[i].patcher, channel.patcher))
  383. {
  384. state->instruments.push_back (previous->instruments[i]);
  385. state->instruments.back()->configure (channel, song.bpm);
  386. continue;
  387. }
  388. state->instruments.push_back (patcher::makeInstrument (channel, sampleRate, patcherFactories (sampleRate, song.bpm, factories), old));
  389. state->instruments.back()->configure (channel, song.bpm);
  390. continue;
  391. }
  392. state->instruments.push_back (buildInstrument (channel, sampleRate, song.bpm, factories, &keyShiftLater));
  393. // FL 2026's clip pitch (round 167k): a channel with a pitched clip gets its pitch shifters even when it resamples
  394. if (clipShiftWanted (song, i) && state->instruments.back() != nullptr)
  395. {
  396. state->instruments.back()->setClipShift (true);
  397. keyShiftLater.push_back (state->instruments.back().get());
  398. }
  399. }
  400. // Options › Project › "Fast declick for cut groups" (REA round 167h §3)
  401. for (auto& instrument : state->instruments)
  402. if (instrument != nullptr)
  403. {
  404. instrument->setFastDeclick (song.fastDeclick);
  405. instrument->setPanTriangular (song.panTriangular);
  406. }
  407. prepareKeyShifts (keyShiftLater, sampleRate);
  408. state->effects.resize (song.mixer.size());
  409. for (std::size_t t = 0; t < song.mixer.size(); ++t)
  410. {
  411. const auto& slots = song.mixer[t].effects;
  412. for (std::size_t i = 0; i < slots.size() && i < (std::size_t) maxEffectSlots; ++i)
  413. {
  414. const auto kind = slots[i].kind;
  415. if (previous != nullptr && t < previous->song.mixer.size() && t < previous->effects.size()
  416. && i < previous->song.mixer[t].effects.size() && i < previous->effects[t].size()
  417. && previous->song.mixer[t].effects[i].kind == kind && kind != EffectKind::patcher
  418. && (kind != EffectKind::parallel || sameContainer (previous->song.mixer[t].effects[i], slots[i])) // children are built in
  419. && previous->song.mixer[t].effects[i].samplePath == slots[i].samplePath
  420. // round 144: Facet EQ's buffers are sized by its linear-phase resolution: a new one, a new instance
  421. && (kind != EffectKind::facetEq
  422. || facet::resolution (previous->song.mixer[t].effects[i].params[(std::size_t) facet::resolutionParam])
  423. == facet::resolution (slots[i].params[(std::size_t) facet::resolutionParam]))
  424. && (kind != EffectKind::plugin
  425. || (previous->song.mixer[t].effects[i].plugin.id == slots[i].plugin.id && previous->sampleRate == sampleRate
  426. && samePluginProcessing (previous->song.mixer[t].effects[i].plugin, slots[i].plugin)))
  427. && (previous->song.mixer[t].effects[i].state == slots[i].state
  428. || (previous->sampleRate == sampleRate && previous->effects[t][i] != nullptr && previous->effects[t][i]->acceptState (slots[i].state))))
  429. {
  430. state->effects[t].push_back (previous->effects[t][i]);
  431. continue;
  432. }
  433. // FL's Patcher (REA_rodada141): same structure keeps the running graph (it takes the values)
  434. if (kind == EffectKind::patcher)
  435. {
  436. const auto* old = previous != nullptr && t < previous->effects.size() && i < previous->effects[t].size()
  437. && i < previous->song.mixer[t].effects.size() && previous->song.mixer[t].effects[i].kind == kind
  438. ? previous->effects[t][i].get()
  439. : nullptr;
  440. if (old != nullptr && previous->sampleRate == sampleRate
  441. && patcher::sameStructure (previous->song.mixer[t].effects[i].patcher, slots[i].patcher)
  442. && patcher::acceptValues (previous->effects[t][i].get(), slots[i]))
  443. {
  444. state->effects[t].push_back (previous->effects[t][i]);
  445. continue;
  446. }
  447. std::shared_ptr<Effect> effect = patcher::makeEffect (slots[i], sampleRate, patcherFactories (sampleRate, song.bpm, factories), old);
  448. effect->prepare (sampleRate);
  449. state->effects[t].push_back (std::move (effect));
  450. continue;
  451. }
  452. state->effects[t].push_back (buildEffect (slots[i], sampleRate, factories));
  453. }
  454. }
  455. // FL's Channel Rack looping (round 165f-rack): the looping channels' repeats are written out as notes here, so
  456. // playback, the Playlist's pattern clips and export all play them without any cost on the audio thread
  457. channelloops::expandSong (song);
  458. state->song = std::move (song);
  459. const auto tailStarted = std::chrono::steady_clock::now();
  460. // scheduling: notes sorted by start (order among notes on the same tick is preserved)
  461. for (auto& p : state->song.patterns)
  462. std::stable_sort (p.notes.begin(), p.notes.end(), [] (const Note& a, const Note& b) { return a.start < b.start; });
  463. state->schedule = makeScheduleIndex (state->song);
  464. state->performanceZone = perf::zoneClips (state->song);
  465. state->sampleRate = sampleRate;
  466. state->buildMidiRoutes();
  467. state->buildAutomationTables();
  468. {
  469. const loadtrace::Scope timing ("pdc");
  470. state->buildPdc (previous);
  471. }
  472. state->buildMixerGraph();
  473. const auto& channels = state->song.channels;
  474. state->cutTargets.assign (channels.size(), {});
  475. state->arpeggiators.assign (channels.size(), nullptr);
  476. for (std::size_t c = 0; c < channels.size(); ++c)
  477. if (channels[c].arp.enabled())
  478. state->arpeggiators[c] = previous != nullptr && c < previous->arpeggiators.size() && previous->arpeggiators[c] != nullptr
  479. ? previous->arpeggiators[c]
  480. : std::make_shared<Arpeggiator>();
  481. state->echoes.assign (channels.size(), nullptr);
  482. for (std::size_t c = 0; c < channels.size(); ++c)
  483. if (channels[c].misc.echo.enabled())
  484. state->echoes[c] = previous != nullptr && c < previous->echoes.size() && previous->echoes[c] != nullptr
  485. ? previous->echoes[c]
  486. : std::make_shared<channelmisc::NoteEcho>();
  487. // (FL's Kepler keeps sounding when its cut group cuts it: FL's renders with and without "cut itself" are the same
  488. // and both null against the engine fed every note to its end, REA_rodada165g-flbeta165k §3)
  489. for (std::size_t c = 0; c < channels.size(); ++c)
  490. if (channels[c].cutGroup > 0)
  491. for (std::size_t d = 0; d < channels.size(); ++d)
  492. if (channels[d].cutBy == channels[c].cutGroup && channels[d].instrument != InstrumentKind::kepler)
  493. {
  494. state->cutTargets[c].push_back ((int) d);
  495. state->hasCutGroups = true;
  496. }
  497. state->hasLayers = std::any_of (channels.begin(), channels.end(), [] (const ChannelDef& c) {
  498. return c.instrument == InstrumentKind::layer && ! c.layer.children.empty();
  499. });
  500. const auto audible = state->song.soloAudible();
  501. state->mixerAudible.assign (audible.begin(), audible.end());
  502. loadtrace::add ("rack_schedule_graph", loadtrace::msSince (tailStarted));
  503. return state;
  504. }
  505. void RackState::buildMixerGraph()
  506. {
  507. mixerOrder = song.mixerOrder();
  508. const auto audible = song.soloAudible();
  509. mixerAudible.assign (audible.begin(), audible.end());
  510. const auto tracks = std::max<int> (1, (int) song.mixer.size());
  511. mixerInputs.assign ((std::size_t) tracks, {});
  512. sendTaps.clear();
  513. slotTap.assign ((std::size_t) tracks, {});
  514. std::vector<int> depth ((std::size_t) tracks, 0);
  515. // who listens to each track via sidechain (the source goes in an earlier layer)
  516. std::vector<std::vector<int>> sidechainListeners ((std::size_t) tracks);
  517. for (int t = 1; t < tracks; ++t)
  518. for (const auto& fx : song.mixer[(std::size_t) t].effects)
  519. for (const auto source : { fx.sidechain, fx.sidechain2 })
  520. if (source > 0 && source < tracks && source != t)
  521. sidechainListeners[(std::size_t) source].push_back (t);
  522. for (auto t : mixerOrder) // sources before destinations: the depth is already computed
  523. {
  524. const auto& track = song.mixer[(std::size_t) t];
  525. for (const auto listener : sidechainListeners[(std::size_t) t])
  526. depth[(std::size_t) listener] = std::max (depth[(std::size_t) listener], depth[(std::size_t) t] + 1);
  527. // a route whose level knob is automated (issue #12)
  528. auto routeAuto = [this, t] (int to) {
  529. for (const auto& r : routeAutos)
  530. if (r.from == t && r.to == to)
  531. return r.slot;
  532. return -1;
  533. };
  534. if (track.toMaster)
  535. mixerInputs[0].push_back ({ t, 0, track.masterLevel, -1, routeAuto (0) });
  536. for (std::size_t k = 0; k < track.sends.size(); ++k)
  537. {
  538. const auto& send = track.sends[k];
  539. const auto automation = send.target > 0 ? routeAuto (send.target) : -1;
  540. // (a send at 0 is left out, unless an automation brings it up)
  541. if (send.target > 0 && send.target < tracks && send.target != t && (send.level > 0.0f || automation >= 0))
  542. {
  543. mixerInputs[(std::size_t) send.target].push_back ({ t, (int) k + 1, send.level, -1, automation });
  544. depth[(std::size_t) send.target] = std::max (depth[(std::size_t) send.target], depth[(std::size_t) t] + 1);
  545. }
  546. }
  547. // Fruity Send slots: their own signal, delay lines after the sends' (PdcPlan::sendDelay)
  548. const auto taps = fruitySendsOf (song, t);
  549. for (std::size_t j = 0; j < taps.size(); ++j)
  550. {
  551. const auto slot = taps[j].slot, target = taps[j].target;
  552. if ((int) sendTaps.size() >= maxSendTaps)
  553. break;
  554. if ((std::size_t) t >= slotTap.size())
  555. slotTap.resize ((std::size_t) t + 1);
  556. // (two entries per slot: its outputs 0 and 1, the Transmitter's transient / sustain sends)
  557. const auto key = (std::size_t) slot * maxSlotSends + (std::size_t) taps[j].output;
  558. if (key >= slotTap[(std::size_t) t].size())
  559. slotTap[(std::size_t) t].resize (key + 1, -1);
  560. slotTap[(std::size_t) t][key] = (int) sendTaps.size();
  561. mixerInputs[(std::size_t) target].push_back ({ t, (int) (1 + track.sends.size() + j), 1.0f, (int) sendTaps.size() });
  562. sendTaps.push_back ({ t, slot, target });
  563. depth[(std::size_t) target] = std::max (depth[(std::size_t) target], depth[(std::size_t) t] + 1);
  564. }
  565. }
  566. mixerLayers.clear();
  567. for (auto t : mixerOrder)
  568. {
  569. const auto d = (std::size_t) depth[(std::size_t) t];
  570. if (mixerLayers.size() <= d)
  571. mixerLayers.resize (d + 1);
  572. mixerLayers[d].push_back (t);
  573. }
  574. // splitting across threads costs a few microseconds per block; only worth it with plugins or many channels
  575. const auto plugins = std::count_if (song.channels.begin(), song.channels.end(),
  576. [] (const ChannelDef& c) { return c.instrument == InstrumentKind::plugin; });
  577. auto pluginEffects = 0;
  578. for (const auto& t : song.mixer)
  579. pluginEffects += (int) std::count_if (t.effects.begin(), t.effects.end(), [] (const EffectSlot& e) { return e.kind == EffectKind::plugin; });
  580. parallel = plugins + pluginEffects >= 2 || song.channels.size() >= 24;
  581. // plugins whose "Allow threaded processing" is off pin their channel / insert to the audio thread
  582. threadedChannels.clear();
  583. audioThreadChannels.clear();
  584. for (int c = 0; c < (int) song.channels.size(); ++c)
  585. {
  586. const auto& ch = song.channels[(std::size_t) c];
  587. // (and a generator Patcher holding a Hardware Insert, round 165c: the device-output buses are not shared between threads)
  588. const auto pinned = (ch.instrument == InstrumentKind::plugin && ! ch.plugin.threaded)
  589. || (ch.instrument == InstrumentKind::patcher && patcher::usesHardwareIo (ch.patcher));
  590. (pinned ? audioThreadChannels : threadedChannels).push_back (c);
  591. }
  592. threadedLayers.assign (mixerLayers.size(), {});
  593. audioThreadLayers.assign (mixerLayers.size(), {});
  594. for (std::size_t d = 0; d < mixerLayers.size(); ++d)
  595. for (const auto t : mixerLayers[d])
  596. {
  597. const auto& effects = song.mixer[(std::size_t) t].effects;
  598. // (and the hardware inserts, round 164d: the device-output buses they write are not shared between threads)
  599. const auto pinned = ! song.mixer[(std::size_t) t].threaded || std::any_of (effects.begin(), effects.end(),
  600. [] (const EffectSlot& e) {
  601. return (e.kind == EffectKind::plugin && ! e.plugin.threaded) || e.kind == EffectKind::hardwareInsert
  602. || (e.kind == EffectKind::patcher && patcher::usesHardwareIo (e.patcher)); // (round 165c)
  603. });
  604. (pinned ? audioThreadLayers : threadedLayers)[d].push_back (t);
  605. }
  606. buildTaskGraph (depth);
  607. }
  608. void RackState::buildTaskGraph (const std::vector<int>& depth)
  609. {
  610. const auto tracks = std::max<int> (1, (int) song.mixer.size());
  611. graphChannels = std::min<int> ((int) song.channels.size(), RackRenderer::maxChannels);
  612. trackChannels.assign ((std::size_t) tracks, {});
  613. for (int c = 0; c < graphChannels; ++c)
  614. trackChannels[(std::size_t) std::clamp (song.channels[(std::size_t) c].mixerTrack, 0, tracks - 1)].push_back (c);
  615. graphOk = false;
  616. graphIndegree.clear();
  617. graphNextStart.clear();
  618. graphNext.clear();
  619. graphRoots.clear();
  620. const auto pinned = ! audioThreadChannels.empty()
  621. || std::any_of (audioThreadLayers.begin(), audioThreadLayers.end(), [] (const std::vector<int>& l) { return ! l.empty(); });
  622. if (pinned)
  623. return;
  624. const auto tasks = graphChannels + tracks - 1;
  625. const auto trackTask = [this] (int t) { return graphChannels + t - 1; };
  626. std::vector<std::vector<int>> next ((std::size_t) tasks);
  627. auto ok = true;
  628. auto edge = [&] (int from, int to) {
  629. // the layers run a source in an earlier layer than its destination; a cycle breaks that (the layered path
  630. // then reads the source before it ran): keep the layers for such a mixer
  631. if (depth[(std::size_t) to] <= depth[(std::size_t) from])
  632. ok = false;
  633. next[(std::size_t) trackTask (from)].push_back (trackTask (to));
  634. };
  635. for (int c = 0; c < graphChannels; ++c)
  636. if (const auto t = std::clamp (song.channels[(std::size_t) c].mixerTrack, 0, tracks - 1); t > 0)
  637. next[(std::size_t) c].push_back (trackTask (t));
  638. for (int t = 1; t < tracks; ++t)
  639. {
  640. for (const auto& in : mixerInputs[(std::size_t) t])
  641. if (in.source > 0 && in.source < tracks && in.source != t)
  642. edge (in.source, t);
  643. for (const auto& fx : song.mixer[(std::size_t) t].effects)
  644. for (const auto source : { fx.sidechain, fx.sidechain2 })
  645. if (source > 0 && source < tracks && source != t)
  646. edge (source, t);
  647. }
  648. if (! ok)
  649. return;
  650. graphIndegree.assign ((std::size_t) tasks, 0);
  651. graphNextStart.assign ((std::size_t) tasks + 1, 0);
  652. for (int i = 0; i < tasks; ++i)
  653. {
  654. auto& n = next[(std::size_t) i];
  655. std::sort (n.begin(), n.end());
  656. n.erase (std::unique (n.begin(), n.end()), n.end());
  657. graphNextStart[(std::size_t) i + 1] = graphNextStart[(std::size_t) i] + (int) n.size();
  658. for (const auto j : n)
  659. {
  660. graphNext.push_back (j);
  661. ++graphIndegree[(std::size_t) j];
  662. }
  663. }
  664. // the channels first (they are most of the work and every insert waits for some of them), then the inserts
  665. // nothing feeds
  666. for (int i = 0; i < tasks; ++i)
  667. if (graphIndegree[(std::size_t) i] == 0)
  668. graphRoots.push_back (i);
  669. graphOk = true;
  670. }
  671. std::vector<int> RackState::currentLatencies() const
  672. {
  673. std::vector<int> out;
  674. // a hosted plugin's latency set by hand in its wrapper settings (round 149) replaces what it reports
  675. auto manual = [this] (const PluginRef& ref, int reported) {
  676. return ref.latencyOverrideMs >= 0.0f ? (int) std::lround (ref.latencyOverrideMs * 0.001 * sampleRate) : reported;
  677. };
  678. for (std::size_t c = 0; c < instruments.size(); ++c)
  679. {
  680. const auto reported = instruments[c]->latencySamples();
  681. out.push_back (c < song.channels.size() && song.channels[c].instrument == InstrumentKind::plugin ? manual (song.channels[c].plugin, reported) : reported);
  682. }
  683. for (std::size_t t = 0; t < effects.size(); ++t)
  684. for (std::size_t s = 0; s < effects[t].size(); ++s)
  685. {
  686. const auto reported = effects[t][s]->latencySamples();
  687. const auto* slot = t < song.mixer.size() && s < song.mixer[t].effects.size() ? &song.mixer[t].effects[s] : nullptr;
  688. out.push_back (slot != nullptr && slot->kind == EffectKind::plugin ? manual (slot->plugin, reported) : reported);
  689. }
  690. return out;
  691. }
  692. void RackState::buildPdc (const RackState* previous)
  693. {
  694. latencies = currentLatencies();
  695. std::vector<int> channelLatency (latencies.begin(), latencies.begin() + (std::ptrdiff_t) instruments.size());
  696. std::vector<std::vector<int>> slotLatency (effects.size());
  697. auto next = latencies.begin() + (std::ptrdiff_t) instruments.size();
  698. for (std::size_t t = 0; t < effects.size(); ++t)
  699. for (std::size_t s = 0; s < effects[t].size(); ++s)
  700. slotLatency[t].push_back (*next++);
  701. pdc = computePdc (song, channelLatency, slotLatency, sampleRate);
  702. // reuses lines of the same length: editing the song must not click the audio
  703. auto line = [] (int length, const std::shared_ptr<DelayLine>* old) -> std::shared_ptr<DelayLine> {
  704. if (length <= 0)
  705. return nullptr;
  706. if (old != nullptr && *old != nullptr && (*old)->length() == length)
  707. return *old;
  708. return std::make_shared<DelayLine> (length);
  709. };
  710. channelDelays.resize (pdc.channelDelay.size());
  711. for (std::size_t c = 0; c < pdc.channelDelay.size(); ++c)
  712. channelDelays[c] = line (pdc.channelDelay[c],
  713. previous != nullptr && c < previous->channelDelays.size() ? &previous->channelDelays[c] : nullptr);
  714. sendDelays.resize (pdc.sendDelay.size());
  715. for (std::size_t t = 0; t < pdc.sendDelay.size(); ++t)
  716. {
  717. sendDelays[t].resize (pdc.sendDelay[t].size());
  718. for (std::size_t k = 0; k < pdc.sendDelay[t].size(); ++k)
  719. {
  720. const std::shared_ptr<DelayLine>* old = nullptr;
  721. if (previous != nullptr && t < previous->sendDelays.size() && k < previous->sendDelays[t].size())
  722. old = &previous->sendDelays[t][k];
  723. sendDelays[t][k] = line (pdc.sendDelay[t][k], old);
  724. }
  725. }
  726. // inserts with a hardware output target: aligned with the Master's output (which waits for the longest path)
  727. hwRoutes.clear();
  728. for (std::size_t t = 1; t < song.mixer.size() && t < (std::size_t) maxMixerTracks; ++t)
  729. {
  730. const auto& track = song.mixer[t];
  731. if (track.outputChannel < 0 || track.outputChannel >= HardwareOutput::maxChannels)
  732. continue;
  733. // FL (FUN_010ffca0): only with "Compensate for master latency" on and the track not bypassed
  734. const auto compensated = track.compensateMasterLatency && track.latencyBypass != LatencyBypass::always;
  735. const auto length = compensated && t < pdc.outLat.size() ? std::max (0, pdc.total - pdc.outLat[t]) : 0;
  736. const std::shared_ptr<DelayLine>* old = nullptr;
  737. if (previous != nullptr)
  738. for (const auto& r : previous->hwRoutes)
  739. if (r.track == (int) t)
  740. old = &r.delay;
  741. hwRoutes.push_back ({ (int) t, track.outputChannel, track.outputMode, line (length, old) });
  742. }
  743. bypassWhenIdle.assign (song.mixer.size(), 0);
  744. anyBypassWhenIdle = false;
  745. for (std::size_t t = 1; t < song.mixer.size(); ++t)
  746. if (song.mixer[t].latencyBypass == LatencyBypass::whenRecordingOrStopped)
  747. anyBypassWhenIdle = bypassWhenIdle[t] = 1;
  748. }
  749. void RackState::buildMidiRoutes()
  750. {
  751. const auto count = song.channels.size();
  752. midiTargets.assign (count, {});
  753. midiSources.assign (count, {});
  754. midiOutChannel.assign (count, -1);
  755. vfxChannels.clear();
  756. portEventChannels.clear();
  757. dashboardChannels.clear();
  758. mapNoteColour.assign (count, 0);
  759. vfxPort.assign (count, -1);
  760. hasMidiRoutes = false;
  761. midiOutTargets.assign (count, {});
  762. hasMidiOutputs = false;
  763. for (std::size_t c = 0; c < count; ++c)
  764. if (song.channels[c].instrument == InstrumentKind::plugin && song.channels[c].plugin.midiOutPort >= 0)
  765. for (std::size_t t = 0; t < count; ++t)
  766. if (t != c && song.channels[t].instrument == InstrumentKind::plugin
  767. && song.channels[t].plugin.midiInPort == song.channels[c].plugin.midiOutPort)
  768. {
  769. midiOutTargets[c].push_back ((int) t);
  770. hasMidiOutputs = true;
  771. }
  772. midiRoutesOut.assign (count, {});
  773. midiRoutesIn.assign (count, {});
  774. effectMidiRoutes.assign (count, {});
  775. hasEffectMidiRoutes = false;
  776. // the Patchers that take MIDI ports through their "From LYNX" pins (round 162)
  777. std::vector<std::vector<int>> channelPorts (count);
  778. for (std::size_t t = 0; t < count; ++t)
  779. if (song.channels[t].instrument == InstrumentKind::patcher)
  780. channelPorts[t] = patcher::midiInputPorts (song.channels[t].patcher);
  781. struct SlotPorts
  782. {
  783. int track, slot;
  784. std::vector<int> ports;
  785. };
  786. std::vector<SlotPorts> slotPorts;
  787. for (std::size_t t = 0; t < song.mixer.size(); ++t)
  788. for (std::size_t k = 0; k < song.mixer[t].effects.size(); ++k)
  789. if (song.mixer[t].effects[k].kind == EffectKind::patcher)
  790. if (auto ports = patcher::midiInputPorts (song.mixer[t].effects[k].patcher); ! ports.empty())
  791. slotPorts.push_back ({ (int) t, (int) k, std::move (ports) });
  792. // source c sends on `port` with MIDI channel `midiChannel`: the plugins whose input port it is, the Patchers that
  793. // take that port
  794. // (a Patcher that takes the port may pass it on to "To LYNX" MIDI ports: those are sent on too, a few levels deep)
  795. bool portOnly = false; // (the routes sent next carry only what goes out on the port: a Patcher's VFX outputs)
  796. std::function<void (std::size_t, int, int, int)> send = [&] (std::size_t c, int port, int midiChannel, int depth) {
  797. auto passOn = [&] (const PatcherDoc& doc) {
  798. if (depth < 4)
  799. for (const auto& r : patcher::midiOutputsOf (doc, patchMidiPortPin (port)))
  800. if (r.port != port)
  801. send (c, r.port, r.midiChannel >= 0 ? r.midiChannel : midiChannel, depth + 1);
  802. };
  803. if (midiOutChannel[c] < 0)
  804. midiOutChannel[c] = midiChannel;
  805. for (std::size_t t = 0; t < count; ++t)
  806. {
  807. if (t == c)
  808. continue;
  809. const auto plugin = song.channels[t].instrument == InstrumentKind::plugin && song.channels[t].plugin.midiInPort == port;
  810. const auto patch = std::find (channelPorts[t].begin(), channelPorts[t].end(), port) != channelPorts[t].end();
  811. if (! plugin && ! patch)
  812. continue;
  813. if (std::any_of (midiRoutesOut[c].begin(), midiRoutesOut[c].end(), [&] (const MidiRoute& r) {
  814. return r.other == (int) t && r.port == port && r.midiChannel == midiChannel;
  815. }))
  816. continue;
  817. midiRoutesOut[c].push_back ({ (int) t, port, midiChannel, portOnly });
  818. midiRoutesIn[t].push_back ({ (int) c, port, midiChannel, portOnly });
  819. if (std::find (midiSources[t].begin(), midiSources[t].end(), (int) c) == midiSources[t].end())
  820. midiSources[t].push_back ((int) c);
  821. if (plugin && ! portOnly && std::find (midiTargets[c].begin(), midiTargets[c].end(), (int) t) == midiTargets[c].end())
  822. midiTargets[c].push_back ((int) t); // (controls and program changes: the plugins)
  823. hasMidiRoutes = true;
  824. if (patch)
  825. passOn (song.channels[t].patcher);
  826. }
  827. for (const auto& s : slotPorts)
  828. if (std::find (s.ports.begin(), s.ports.end(), port) != s.ports.end()
  829. && std::none_of (effectMidiRoutes[c].begin(), effectMidiRoutes[c].end(), [&] (const EffectMidiRoute& r) {
  830. return r.track == s.track && r.slot == s.slot && r.port == port && r.midiChannel == midiChannel;
  831. }))
  832. {
  833. effectMidiRoutes[c].push_back ({ s.track, s.slot, port, midiChannel, portOnly });
  834. hasEffectMidiRoutes = true;
  835. passOn (song.mixer[(std::size_t) s.track].effects[(std::size_t) s.slot].patcher);
  836. }
  837. };
  838. for (std::size_t c = 0; c < count; ++c)
  839. {
  840. // a generator Patcher's "MIDI port N" outputs (REA_rodada141): its notes reach the plugins on those ports, as a
  841. // MIDI Out on MIDI channel 1 would send them (or on the channel of a MIDI Out node on the way, round 162)
  842. if (song.channels[c].instrument == InstrumentKind::patcher)
  843. {
  844. for (const auto& r : patcher::midiOutputsOf (song.channels[c].patcher, 0))
  845. send (c, r.port, std::max (0, r.midiChannel), 0);
  846. // its VFX nodes' outputs cabled to "To LYNX" MIDI ports (round 165c): what they play goes out there
  847. if (const auto ports = patcher::vfxHostPorts (song.channels[c].patcher); ! ports.empty())
  848. {
  849. portEventChannels.push_back ((int) c);
  850. portOnly = true;
  851. for (const auto port : ports)
  852. send (c, port, 0, 0);
  853. portOnly = false;
  854. }
  855. continue;
  856. }
  857. if (song.channels[c].instrument == InstrumentKind::vfx) // a VFX channel: output k on port + k (round 164b)
  858. {
  859. if (const auto vs = vfx::readState (song.channels[c].pluginState))
  860. {
  861. vfxChannels.push_back ((int) c);
  862. vfxPort[c] = vs->port;
  863. for (int k = 0; k < vfx::outputCount (vs->kind) && vs->port + k < patchMidiPorts; ++k)
  864. send (c, vs->port + k, 0, 0);
  865. }
  866. continue;
  867. }
  868. if (song.channels[c].instrument == InstrumentKind::dashboard) // its notes and controls' MIDI (round 165)
  869. {
  870. const auto settings = surface::dashboardMidi (song.channels[c].pluginState);
  871. midiOutChannel[c] = settings.channel;
  872. dashboardChannels.push_back ((int) c);
  873. send (c, settings.port, settings.channel, 0);
  874. continue;
  875. }
  876. if (song.channels[c].instrument != InstrumentKind::midiOut)
  877. continue;
  878. // its knobs' MIDI (round 167i) goes out like a Dashboard's
  879. const auto settings = midiout::stateOf (song.channels[c].pluginState);
  880. midiOutChannel[c] = settings.channel;
  881. mapNoteColour[c] = settings.mapNoteColour ? 1 : 0;
  882. dashboardChannels.push_back ((int) c);
  883. send (c, settings.port, settings.channel, 0);
  884. }
  885. }
  886. void RackState::buildAutomationTables()
  887. {
  888. const auto& automations = song.automations;
  889. const auto count = std::min<int> ((int) automations.size(), maxAutomations);
  890. automationClips.assign ((std::size_t) count, {});
  891. zoneAutomations.assign ((std::size_t) count, 0);
  892. const auto zoneEnd = song.performanceZoneEnd();
  893. for (int i = 0; i < (int) song.playlist.size(); ++i)
  894. {
  895. const auto& c = song.playlist[(std::size_t) i];
  896. if (c.kind == ClipKind::automation && c.automation >= 0 && c.automation < count && c.length > 0 && ! c.muted && ! song.isTrackMuted (c.track))
  897. {
  898. if (c.start < zoneEnd) // Performance mode: plays only when launched
  899. zoneAutomations[(std::size_t) c.automation] = 1;
  900. else
  901. automationClips[(std::size_t) c.automation].push_back (i);
  902. }
  903. }
  904. for (auto& clips : automationClips)
  905. std::sort (clips.begin(), clips.end(),
  906. [this] (int a, int b) { return song.playlist[(std::size_t) a].start < song.playlist[(std::size_t) b].start; });
  907. liveAutomations.clear();
  908. for (int a = 0; a < count; ++a)
  909. if (automations[(std::size_t) a].isLive())
  910. liveAutomations.push_back (a);
  911. channelVolumeAuto.assign (song.channels.size(), -1);
  912. channelPanAuto.assign (song.channels.size(), -1);
  913. mixerVolumeAuto.assign (song.mixer.size(), -1);
  914. mixerPanAuto.assign (song.mixer.size(), -1);
  915. effectParamAuto.assign (song.mixer.size(), {});
  916. effectMixAuto.assign (song.mixer.size(), {});
  917. for (std::size_t t = 0; t < song.mixer.size(); ++t)
  918. {
  919. std::array<int, maxEffectParams> none;
  920. none.fill (-1);
  921. effectParamAuto[t].assign (song.mixer[t].effects.size(), none);
  922. effectMixAuto[t].assign (song.mixer[t].effects.size(), -1);
  923. }
  924. pluginParams.clear();
  925. routeAutos.clear();
  926. hasAutomation = false;
  927. tempoAutomation = -1;
  928. // binds automation slot `a` (an automation, or a pattern event lane after them) to its target
  929. const auto bind = [this] (int a, const AutomationTarget& t) {
  930. const auto channelOk = t.index >= 0 && t.index < (int) song.channels.size();
  931. const auto trackOk = t.index >= 0 && t.index < (int) song.mixer.size();
  932. auto used = true;
  933. switch (t.kind)
  934. {
  935. case AutomationTargetKind::channelVolume: if (channelOk) channelVolumeAuto[(std::size_t) t.index] = a; else used = false; break;
  936. case AutomationTargetKind::channelPan: if (channelOk) channelPanAuto[(std::size_t) t.index] = a; else used = false; break;
  937. case AutomationTargetKind::mixerVolume: if (trackOk) mixerVolumeAuto[(std::size_t) t.index] = a; else used = false; break;
  938. case AutomationTargetKind::mixerPan: if (trackOk) mixerPanAuto[(std::size_t) t.index] = a; else used = false; break;
  939. case AutomationTargetKind::channelParam:
  940. // VST plugins and the exact engines that take FL's parameter automation (FL Slayer: REA_rodada79)
  941. if (channelOk && (song.channels[(std::size_t) t.index].instrument == InstrumentKind::plugin
  942. || song.channels[(std::size_t) t.index].instrument == InstrumentKind::patcher // (its published parameters)
  943. || song.channels[(std::size_t) t.index].instrument == InstrumentKind::slayer
  944. || song.channels[(std::size_t) t.index].instrument == InstrumentKind::soundfont // (LYNX Soundfont's knobs)
  945. || (song.channels[(std::size_t) t.index].instrument == InstrumentKind::midiOut
  946. && (midictl::isMidiParam (t.param) || (t.param >= 0 && t.param <= midiout::controlCount)))
  947. // a recorded / drawn pitch bend plays on any instrument (issue #12)
  948. || midictl::isPitchBend (t.param)
  949. // an Envelope Controller's global Mod X / Y (round 164f)
  950. || (song.channels[(std::size_t) t.index].instrument == InstrumentKind::controller
  951. && (t.param == envelopeControllerModXParam || t.param == envelopeControllerModYParam))
  952. // a Dashboard's outputs, the Voltage Controller's offsets / scales (round 165)
  953. || (song.channels[(std::size_t) t.index].instrument == InstrumentKind::dashboard && t.param >= 0
  954. && t.param < surface::maxOutputs)
  955. || (song.channels[(std::size_t) t.index].instrument == InstrumentKind::voltage && t.param >= 0
  956. && t.param < voltage::paramCount)
  957. // the Sampler's knobs (issue #12)
  958. || (song.channels[(std::size_t) t.index].instrument == InstrumentKind::sampler && t.param >= 0
  959. && t.param < samplerparam::count)
  960. // the knobs of an FL engine kept in the channel's state (round 168n)
  961. || modelparams::find (song.channels[(std::size_t) t.index].instrument, t.param) != nullptr))
  962. pluginParams.push_back ({ a, t.index, 0, 0, t.param });
  963. else
  964. used = false;
  965. break;
  966. case AutomationTargetKind::effectParam:
  967. {
  968. const auto slotOk = trackOk && t.slot >= 0 && t.slot < (int) song.mixer[(std::size_t) t.index].effects.size();
  969. if (! slotOk)
  970. used = false;
  971. else if (song.mixer[(std::size_t) t.index].effects[(std::size_t) t.slot].kind == EffectKind::plugin
  972. || song.mixer[(std::size_t) t.index].effects[(std::size_t) t.slot].kind == EffectKind::patcher) // (its published parameters)
  973. pluginParams.push_back ({ a, -1, t.index, t.slot, t.param });
  974. else if (song.mixer[(std::size_t) t.index].effects[(std::size_t) t.slot].isSubstitute())
  975. used = false; // the missing plugin's parameters: kept for when it is back, they don't drive the substitute
  976. else if (t.param >= 0 && t.param < maxEffectParams)
  977. effectParamAuto[(std::size_t) t.index][(std::size_t) t.slot][(std::size_t) t.param] = a;
  978. else
  979. used = false;
  980. break;
  981. }
  982. case AutomationTargetKind::effectMix:
  983. if (trackOk && t.slot >= 0 && t.slot < (int) song.mixer[(std::size_t) t.index].effects.size())
  984. effectMixAuto[(std::size_t) t.index][(std::size_t) t.slot] = a;
  985. else
  986. used = false;
  987. break;
  988. case AutomationTargetKind::tempo: tempoAutomation = a; break;
  989. case AutomationTargetKind::mixerSend:
  990. if (trackOk && song.routes (t.index, t.slot))
  991. {
  992. // the last one of the same route wins (as the loop's order makes it for the other targets)
  993. auto it = std::find_if (routeAutos.begin(), routeAutos.end(), [&t] (const RouteAuto& r) { return r.from == t.index && r.to == t.slot; });
  994. if (it == routeAutos.end())
  995. routeAutos.push_back ({ t.index, t.slot, a });
  996. else
  997. it->slot = a;
  998. }
  999. else
  1000. used = false;
  1001. break;
  1002. case AutomationTargetKind::none: used = false; break;
  1003. }
  1004. hasAutomation = hasAutomation || used;
  1005. };
  1006. // the last automation of the same target wins
  1007. for (int a = 0; a < count; ++a)
  1008. {
  1009. if (automationClips[(std::size_t) a].empty() && ! automations[(std::size_t) a].isLive() && zoneAutomations[(std::size_t) a] == 0)
  1010. continue;
  1011. bind (a, automations[(std::size_t) a].target);
  1012. }
  1013. // pattern events (event editor): slots after the automations; they win over automation clips of the same
  1014. // target. The tempo is not driven by pattern events.
  1015. eventLanes.clear();
  1016. patternClips.assign (song.patterns.size(), {});
  1017. for (int i = 0; i < (int) song.playlist.size(); ++i)
  1018. {
  1019. const auto& c = song.playlist[(std::size_t) i];
  1020. if (c.kind == ClipKind::pattern && c.pattern >= 0 && c.pattern < (int) song.patterns.size() && c.length > 0 && ! c.muted
  1021. && ! song.isTrackMuted (c.track))
  1022. patternClips[(std::size_t) c.pattern].push_back (i);
  1023. }
  1024. for (auto& clips : patternClips)
  1025. std::sort (clips.begin(), clips.end(),
  1026. [this] (int a, int b) { return song.playlist[(std::size_t) a].start < song.playlist[(std::size_t) b].start; });
  1027. auto slot = count;
  1028. for (int p = 0; p < (int) song.patterns.size(); ++p)
  1029. for (int l = 0; l < (int) song.patterns[(std::size_t) p].events.size(); ++l)
  1030. {
  1031. const auto& lane = song.patterns[(std::size_t) p].events[(std::size_t) l];
  1032. if (lane.events.empty() || lane.target.kind == AutomationTargetKind::tempo || slot >= maxAutomations)
  1033. continue;
  1034. eventLanes.push_back ({ p, l, slot });
  1035. bind (slot++, lane.target);
  1036. }
  1037. }
  1038. void RackState::slotsOfTarget (const Song& song, const AutomationTarget& target, std::vector<int>& out)
  1039. {
  1040. out.clear();
  1041. if (target.kind == AutomationTargetKind::none)
  1042. return;
  1043. const auto count = std::min<int> ((int) song.automations.size(), maxAutomations);
  1044. for (int a = 0; a < count; ++a)
  1045. if (song.automations[(std::size_t) a].target == target)
  1046. out.push_back (a);
  1047. auto slot = count;
  1048. for (const auto& pattern : song.patterns)
  1049. for (const auto& lane : pattern.events)
  1050. {
  1051. if (lane.events.empty() || lane.target.kind == AutomationTargetKind::tempo || slot >= maxAutomations)
  1052. continue;
  1053. if (lane.target == target)
  1054. out.push_back (slot);
  1055. ++slot;
  1056. }
  1057. }
  1058. MixerMatrix mixerMatrix (const MixerTrack& track, float volume, float pan, bool triangular) noexcept
  1059. {
  1060. // FL keeps the fader as an int (12800 = 0 dB), the pan ±6400 and the separation ±64; LYNX keeps them /16000,
  1061. // /6400 and /64. Float arithmetic as FL's, the circular kernel in x87 extended precision (flvp::panLaw).
  1062. const auto x = std::clamp (volume, 0.0f, 1.0f) * 1.25f;
  1063. const auto p = std::clamp (pan, -1.0f, 1.0f);
  1064. const auto sep = std::clamp (track.stereo, -1.0f, 1.0f);
  1065. MixerMatrix m;
  1066. if (x == 1.0f && p == 0.0f && sep == 0.0f) // FL's fast path: exactly unity
  1067. {
  1068. m.ll = m.rr = track.invertPhase ? -1.0f : 1.0f;
  1069. m.rl = m.lr = 0.0f;
  1070. }
  1071. else if (x == 0.0f)
  1072. m = { 0.0f, 0.0f, 0.0f, 0.0f };
  1073. else
  1074. {
  1075. constexpr float ln11 = 2.3978953f, sqrt2 = 1.4142135f, sin45 = 0.70710677f;
  1076. auto g = x == 1.0f ? 1.0f : (float) ((std::exp ((double) (x * ln11)) - 1.0) * (double) 0.1f);
  1077. if (track.invertPhase)
  1078. g = -g;
  1079. float gl, gr;
  1080. if (triangular) // FUN_006a39c0: the louder side keeps the level
  1081. {
  1082. const auto v = g * sqrt2 * sin45;
  1083. if (std::signbit (p))
  1084. gl = v, gr = (p + 1.0f) * v;
  1085. else
  1086. gr = v, gl = (1.0f - p) * v;
  1087. }
  1088. else
  1089. flvp::panLaw (p, g * sqrt2, gl, gr);
  1090. float fl = 0.0f, fr = 0.0f; // the share of each side that folds into the other
  1091. if (p != 0.0f)
  1092. {
  1093. if (p < 0.0f)
  1094. fl = 1.0f - gr / g;
  1095. else
  1096. fr = 1.0f - gl / g;
  1097. }
  1098. if (sep != 0.0f)
  1099. {
  1100. // narrowing (5^s − 1)/4 (up to mono), widening linear (−1: side ×2)
  1101. const auto s = sep < 0.0f ? sep : (float) (std::exp ((double) sep * std::log (5.0)) - 1.0) * 0.25f;
  1102. fl = std::min (fl + s, 1.0f);
  1103. fr = std::min (fr + s, 1.0f);
  1104. }
  1105. m.rl = gl * fl * 0.5f;
  1106. m.ll = gl * (1.0f - fl * 0.5f);
  1107. m.lr = gr * fr * 0.5f;
  1108. m.rr = gr * (1.0f - fr * 0.5f);
  1109. }
  1110. if (track.swapChannels) // the outputs trade places
  1111. m = { m.lr, m.rr, m.ll, m.rl };
  1112. return m;
  1113. }
  1114. namespace
  1115. {
  1116. // The matrix over a block, each coefficient gliding toward its target by at most 0.001 per sample (FL's fader / pan
  1117. // glide, REA_rodada85 §3; the folded terms glide the same way). `from` = the previous block's matrix (NaN: none).
  1118. // The output may be the input. Returns the matrix reached.
  1119. MixerMatrix applyMatrix (const float* inL, const float* inR, float* outL, float* outR, int n, MixerMatrix from,
  1120. const MixerMatrix& to) noexcept
  1121. {
  1122. if (std::isnan (from.ll))
  1123. from = to;
  1124. constexpr float step = 0.001f;
  1125. auto toward = [] (float g, float target) { return target > g ? std::min (target, g + step) : std::max (target, g - step); };
  1126. auto m = from;
  1127. int i = 0;
  1128. for (; i < n && ! (m == to); ++i)
  1129. {
  1130. m = { toward (m.ll, to.ll), toward (m.rl, to.rl), toward (m.lr, to.lr), toward (m.rr, to.rr) };
  1131. const auto a = inL[i], b = inR[i];
  1132. outL[i] = m.ll * a + m.rl * b;
  1133. outR[i] = m.rr * b + m.lr * a;
  1134. }
  1135. if (i < n)
  1136. {
  1137. if (m.rl == 0.0f && m.lr == 0.0f) // no fold: two gains (the common case)
  1138. for (int k = i; k < n; ++k)
  1139. {
  1140. outL[k] = inL[k] * m.ll;
  1141. outR[k] = inR[k] * m.rr;
  1142. }
  1143. else
  1144. for (int k = i; k < n; ++k)
  1145. {
  1146. const auto a = inL[k], b = inR[k];
  1147. outL[k] = m.ll * a + m.rl * b;
  1148. outR[k] = m.rr * b + m.lr * a;
  1149. }
  1150. }
  1151. return m;
  1152. }
  1153. } // namespace
  1154. namespace
  1155. {
  1156. // Constant-power pan: at center both sides are 1 (0 dB).
  1157. void panGains (float pan, float gain, float& left, float& right) noexcept
  1158. {
  1159. const auto angle = (pan + 1.0f) * 0.25f * 3.14159265f;
  1160. left = gain * std::cos (angle) * 1.41421356f;
  1161. right = gain * std::sin (angle) * 1.41421356f;
  1162. }
  1163. float peakOf (const float* data, int n) noexcept
  1164. {
  1165. float peak = 0.0f;
  1166. for (int i = 0; i < n; ++i)
  1167. {
  1168. const auto a = std::abs (data[i]);
  1169. peak = a > peak ? a : peak; // form the compiler vectorizes
  1170. }
  1171. return peak;
  1172. }
  1173. // No NaN / inf in the block? (x · 0 is 0 for every finite x: one vectorized pass)
  1174. bool finiteBlock (const float* l, const float* r, int n) noexcept
  1175. {
  1176. float acc = 0.0f;
  1177. for (int k = 0; k < n; ++k)
  1178. acc += l[k] * 0.0f + r[k] * 0.0f;
  1179. return acc == 0.0f;
  1180. }
  1181. std::atomic<std::uint64_t> nonFiniteBlocks { 0 };
  1182. // Any sample above `level`? Stops at the first: with sound (the common case) it costs almost nothing.
  1183. bool anyAbove (const float* l, const float* r, int n, float level) noexcept
  1184. {
  1185. // in blocks of 32: the inner loop vectorizes; silent chunks (the ones that scan everything) stay cheap
  1186. int i = 0;
  1187. for (; i + 32 <= n; i += 32)
  1188. {
  1189. float m = 0.0f;
  1190. for (int k = i; k < i + 32; ++k)
  1191. {
  1192. const auto a = std::abs (l[k]), b = std::abs (r[k]);
  1193. m = a > m ? a : m;
  1194. m = b > m ? b : m;
  1195. }
  1196. if (m > level)
  1197. return true;
  1198. }
  1199. for (; i < n; ++i)
  1200. if (std::abs (l[i]) > level || std::abs (r[i]) > level)
  1201. return true;
  1202. return false;
  1203. }
  1204. } // namespace
  1205. namespace
  1206. {
  1207. // A Patcher-style container bakes its children (kinds, states, parameters, routing) in when it is built, so it can be
  1208. // reused only if all of that is unchanged. (It used to be rebuilt on every edit: its children's tails and delay lines
  1209. // restarted, and a fresh linear-phase child reporting its latency only after the first block made the engine re-plan
  1210. // PDC and rebuild it again, over and over — REA round 87.)
  1211. bool sameSlotSetup (const EffectSlot& a, const EffectSlot& b);
  1212. bool sameBranches (const EffectSlot& a, const EffectSlot& b)
  1213. {
  1214. if (a.branches.size() != b.branches.size() || a.links.size() != b.links.size())
  1215. return false;
  1216. for (std::size_t i = 0; i < a.branches.size(); ++i)
  1217. {
  1218. const auto& x = a.branches[i];
  1219. const auto& y = b.branches[i];
  1220. if (x.gain != y.gain || x.chain.size() != y.chain.size())
  1221. return false;
  1222. for (std::size_t k = 0; k < x.chain.size(); ++k)
  1223. if (! sameSlotSetup (x.chain[k], y.chain[k]))
  1224. return false;
  1225. }
  1226. for (std::size_t i = 0; i < a.links.size(); ++i)
  1227. {
  1228. const auto& x = a.links[i];
  1229. const auto& y = b.links[i];
  1230. if (x.branch != y.branch || x.source != y.source || x.target != y.target || x.param != y.param || x.curve != y.curve)
  1231. return false;
  1232. }
  1233. return true;
  1234. }
  1235. bool sameSlotSetup (const EffectSlot& a, const EffectSlot& b)
  1236. {
  1237. return a.kind == b.kind && a.enabled == b.enabled && a.params == b.params && a.mix == b.mix && a.plugin.id == b.plugin.id
  1238. && a.sidechain == b.sidechain && a.sidechain2 == b.sidechain2 && a.sendTracks == b.sendTracks && a.state == b.state && a.samplePath == b.samplePath
  1239. && sameBranches (a, b);
  1240. }
  1241. } // namespace
  1242. bool sameContainer (const EffectSlot& a, const EffectSlot& b) { return sameBranches (a, b); }
  1243. namespace
  1244. {
  1245. std::uint64_t nowNs() noexcept
  1246. {
  1247. #if defined(__linux__)
  1248. // diagnostics on a busy machine: LYNX_PROFILE_CPU=1 measures each unit in its thread's CPU time (renderwav)
  1249. static const bool threadCpu = std::getenv ("LYNX_PROFILE_CPU") != nullptr;
  1250. if (threadCpu)
  1251. {
  1252. timespec ts {};
  1253. clock_gettime (CLOCK_THREAD_CPUTIME_ID, &ts);
  1254. return (std::uint64_t) ts.tv_sec * 1000000000ull + (std::uint64_t) ts.tv_nsec;
  1255. }
  1256. #endif
  1257. return (std::uint64_t) std::chrono::duration_cast<std::chrono::nanoseconds> (std::chrono::steady_clock::now().time_since_epoch()).count();
  1258. }
  1259. // Adds the time since `start` to `slot` when profiling (start = 0: profiling was off when the unit began)
  1260. struct UnitTimer
  1261. {
  1262. UnitTimer (bool on, std::atomic<std::uint64_t>& s, std::atomic<std::uint64_t>* m = nullptr) noexcept
  1263. : slot (s), longest (m), start (on ? nowNs() : 0) {}
  1264. ~UnitTimer()
  1265. {
  1266. if (start == 0)
  1267. return;
  1268. const auto used = nowNs() - start;
  1269. slot.fetch_add (used, std::memory_order_relaxed);
  1270. if (longest != nullptr)
  1271. {
  1272. auto current = longest->load (std::memory_order_relaxed);
  1273. while (used > current && ! longest->compare_exchange_weak (current, used, std::memory_order_relaxed))
  1274. {
  1275. }
  1276. }
  1277. }
  1278. std::atomic<std::uint64_t>& slot;
  1279. std::atomic<std::uint64_t>* longest;
  1280. std::uint64_t start;
  1281. };
  1282. } // namespace
  1283. void RackRenderer::resetUnitTimes() noexcept
  1284. {
  1285. for (auto& t : units->channelNs)
  1286. t.store (0, std::memory_order_relaxed);
  1287. for (auto& t : units->effectNs)
  1288. t.store (0, std::memory_order_relaxed);
  1289. for (auto& t : units->channelMaxNs)
  1290. t.store (0, std::memory_order_relaxed);
  1291. for (auto& t : units->effectMaxNs)
  1292. t.store (0, std::memory_order_relaxed);
  1293. units->processNs.store (0, std::memory_order_relaxed);
  1294. units->processedSamples.store (0, std::memory_order_relaxed);
  1295. }
  1296. void RackRenderer::prepare (double sr, int maxBlockSize)
  1297. {
  1298. automationValues.fill (std::numeric_limits<float>::quiet_NaN());
  1299. lastTrackGain.fill ({ std::numeric_limits<float>::quiet_NaN(), 0.0f, 0.0f, 0.0f });
  1300. lastTapGain.fill ({ std::numeric_limits<float>::quiet_NaN(), 0.0f, 0.0f, 0.0f });
  1301. channelBuffers.assign ((std::size_t) maxChannels * 2 * chunkCapacity, 0.0f);
  1302. smartDisable.assign ((std::size_t) maxMixerTracks * maxEffectSlots, {});
  1303. trackEqs.assign ((std::size_t) maxMixerTracks, {});
  1304. trackScratchBuffers.assign ((std::size_t) maxMixerTracks * 2 * chunkCapacity, 0.0f);
  1305. tapBuffers.assign ((std::size_t) RackState::maxSendTaps * 2 * chunkCapacity, 0.0f);
  1306. sampleRate = sr;
  1307. blockCapacity = std::max (64, maxBlockSize);
  1308. mixBuffers.assign ((std::size_t) maxMixerTracks * 2 * (std::size_t) blockCapacity, 0.0f);
  1309. hwScratch.assign (2 * (std::size_t) blockCapacity, 0.0f);
  1310. layerPick.assign ((std::size_t) maxChannels * 128, (std::int16_t) -1);
  1311. polyLayers.assign ((std::size_t) maxChannels, {});
  1312. if (lastState != nullptr)
  1313. {
  1314. for (auto& instrument : lastState->instruments)
  1315. instrument->prepare (sr);
  1316. for (auto& track : lastState->effects)
  1317. for (auto& effect : track)
  1318. effect->prepare (sr);
  1319. }
  1320. }
  1321. float* RackRenderer::trackBuffer (int track, int channel) noexcept
  1322. {
  1323. return mixBuffers.data() + ((std::size_t) track * 2 + (std::size_t) channel) * (std::size_t) blockCapacity;
  1324. }
  1325. float* RackRenderer::tapBuffer (int tap, int side) noexcept
  1326. {
  1327. return tapBuffers.data() + ((std::size_t) tap * 2 + (std::size_t) side) * chunkCapacity;
  1328. }
  1329. float RackRenderer::automated (int automation, float base) const noexcept
  1330. {
  1331. if (automation < 0)
  1332. return base;
  1333. const auto v = automationValues[(std::size_t) automation];
  1334. return std::isnan (v) ? base : v;
  1335. }
  1336. namespace
  1337. {
  1338. // Value of an automation at a song position: inside a clip, the curve; between clips,
  1339. // the last value of the previous clip; before the first, its initial value. Depends only on
  1340. // position, so playing from any point (or exporting) gives the same result.
  1341. float automationValueAt (const Song& song, const Automation& automation, const std::vector<int>& clips, double tick) noexcept
  1342. {
  1343. const Clip* before = nullptr;
  1344. for (auto i : clips) // sorted by start
  1345. {
  1346. const auto& c = song.playlist[(std::size_t) i];
  1347. if (tick < (double) c.start)
  1348. break;
  1349. if (tick < (double) c.end())
  1350. return automation.valueAt (tick - (double) c.start + (double) c.offset);
  1351. before = &c;
  1352. }
  1353. if (before != nullptr)
  1354. return automation.valueAt ((double) (before->length + before->offset));
  1355. const auto& first = song.playlist[(std::size_t) clips.front()];
  1356. return automation.valueAt ((double) first.offset);
  1357. }
  1358. } // namespace
  1359. void RackRenderer::setOverriddenSlots (const std::vector<int>& slots) noexcept
  1360. {
  1361. std::array<std::uint32_t, RackState::maxAutomations / 32> bits {};
  1362. for (const auto s : slots)
  1363. if (s >= 0 && s < RackState::maxAutomations)
  1364. bits[(std::size_t) s / 32] |= 1u << ((unsigned) s % 32);
  1365. for (std::size_t i = 0; i < bits.size(); ++i)
  1366. overridden[i].store (bits[i], std::memory_order_relaxed);
  1367. anyOverridden.store (! slots.empty(), std::memory_order_release);
  1368. }
  1369. void RackRenderer::clearOverriddenValues() noexcept
  1370. {
  1371. if (! anyOverridden.load (std::memory_order_acquire))
  1372. return;
  1373. for (std::size_t w = 0; w < overridden.size(); ++w)
  1374. if (auto bits = overridden[w].load (std::memory_order_relaxed); bits != 0)
  1375. for (unsigned b = 0; b < 32; ++b)
  1376. if ((bits & (1u << b)) != 0)
  1377. automationValues[w * 32 + b] = std::numeric_limits<float>::quiet_NaN(); // the control's own value
  1378. }
  1379. void RackRenderer::updateAutomation (const RackState& state, double startTick) noexcept
  1380. {
  1381. const auto& song = state.song;
  1382. // controllers (live sources): the effect's output at the end of the previous block, in any mode
  1383. for (const auto a : state.liveAutomations)
  1384. {
  1385. const auto& automation = song.automations[(std::size_t) a];
  1386. const auto& src = automation.source;
  1387. if (src.channel >= 0)
  1388. {
  1389. if (src.channel < (int) state.instruments.size() && state.instruments[(std::size_t) src.channel] != nullptr)
  1390. automationValues[(std::size_t) a] = automation.mapLive (state.instruments[(std::size_t) src.channel]->controlOutput (src.output));
  1391. }
  1392. else if (src.track < (int) state.effects.size() && src.slot >= 0 && src.slot < (int) state.effects[(std::size_t) src.track].size()
  1393. && state.effects[(std::size_t) src.track][(std::size_t) src.slot] != nullptr)
  1394. automationValues[(std::size_t) a] = automation.mapLive (state.effects[(std::size_t) src.track][(std::size_t) src.slot]->controlOutput (src.output));
  1395. }
  1396. // pattern events: in pattern mode the current pattern's (looped); in song mode those of the pattern clip
  1397. // that covers the position. Elsewhere the value holds.
  1398. if (! state.eventLanes.empty())
  1399. {
  1400. if (song.mode != PlayMode::song)
  1401. {
  1402. const auto current = song.currentPattern;
  1403. if (current >= 0 && current < (int) song.patterns.size())
  1404. {
  1405. const auto& pattern = song.patterns[(std::size_t) current];
  1406. const auto length = (double) std::max<std::int64_t> (1, pattern.effectiveLength (song.beatsPerBar));
  1407. const auto t = std::fmod (std::max (0.0, startTick), length);
  1408. for (const auto& lane : state.eventLanes)
  1409. if (lane.pattern == current)
  1410. automationValues[(std::size_t) lane.slot] = pattern.events[(std::size_t) lane.lane].valueAt (t);
  1411. }
  1412. }
  1413. else
  1414. {
  1415. const auto length = (double) std::max<std::int64_t> (1, state.schedule.songLength);
  1416. const auto tick = std::fmod (std::max (0.0, startTick), length);
  1417. // inside a clip of the pattern: its events; after one: the value it ended with; before the first:
  1418. // no value (the target's own). Depends only on the position, like automation clips.
  1419. for (const auto& lane : state.eventLanes)
  1420. {
  1421. const auto& events = song.patterns[(std::size_t) lane.pattern].events[(std::size_t) lane.lane];
  1422. auto value = std::numeric_limits<float>::quiet_NaN();
  1423. for (auto i : state.patternClips[(std::size_t) lane.pattern]) // sorted by start
  1424. {
  1425. const auto& c = song.playlist[(std::size_t) i];
  1426. if (tick < (double) c.start)
  1427. break;
  1428. // a stretched clip loops its pattern (LYNX extra stretchedClipsLoop, issue #25), its events too
  1429. const auto period = (std::size_t) lane.pattern < state.schedule.patternLength.size() ? state.schedule.patternLength[(std::size_t) lane.pattern] : 0;
  1430. value = events.valueAt (patternTickInClip (c, tick < (double) c.end() ? tick : (double) c.end() - 1.0, period));
  1431. }
  1432. automationValues[(std::size_t) lane.slot] = value;
  1433. }
  1434. }
  1435. }
  1436. // in pattern mode the Playlist does not play: values stay as they were
  1437. if (song.mode != PlayMode::song)
  1438. {
  1439. clearOverriddenValues();
  1440. // only the plugin parameters driven by pattern events and by live controllers (links: FL's work in any mode,
  1441. // round 165)
  1442. if (! state.eventLanes.empty() || ! state.liveAutomations.empty())
  1443. applyPluginParams (state, std::min<int> ((int) song.automations.size(), RackState::maxAutomations), true);
  1444. return;
  1445. }
  1446. const auto length = (double) std::max<std::int64_t> (1, state.schedule.songLength);
  1447. const auto tick = std::fmod (std::max (0.0, startTick), length);
  1448. for (std::size_t a = 0; a < state.automationClips.size(); ++a)
  1449. if (! state.automationClips[a].empty())
  1450. automationValues[a] = automationValueAt (song, song.automations[a], state.automationClips[a], tick);
  1451. // Performance mode: the launched automation clips (the last block's passes) drive their automation
  1452. if (perfRunning)
  1453. for (int i = 0; i < perfPlayer.virtualCount(); ++i)
  1454. {
  1455. const auto& v = perfPlayer.virtualClip (i).clip;
  1456. if (v.kind != ClipKind::automation || v.automation < 0 || v.automation >= (int) song.automations.size()
  1457. || v.automation >= RackState::maxAutomations)
  1458. continue;
  1459. const auto local = std::clamp (perfClock - (double) v.start, 0.0, (double) v.length);
  1460. automationValues[(std::size_t) v.automation] = song.automations[(std::size_t) v.automation].valueAt (local + (double) v.offset);
  1461. }
  1462. clearOverriddenValues();
  1463. applyPluginParams (state, 0);
  1464. }
  1465. void RackRenderer::applyPluginParams (const RackState& state, int firstSlot, bool andLive) noexcept
  1466. {
  1467. for (const auto& b : state.pluginParams)
  1468. {
  1469. if (b.automation < firstSlot
  1470. && ! (andLive && (std::size_t) b.automation < state.song.automations.size() && state.song.automations[(std::size_t) b.automation].isLive()))
  1471. continue;
  1472. const auto v = automationValues[(std::size_t) b.automation];
  1473. if (std::isnan (v))
  1474. continue;
  1475. if (b.channel >= 0)
  1476. {
  1477. const auto kind = (std::size_t) b.channel < state.song.channels.size() ? state.song.channels[(std::size_t) b.channel].instrument
  1478. : InstrumentKind::plugin;
  1479. if (midictl::isPitchBend (b.param) && kind != InstrumentKind::plugin && kind != InstrumentKind::midiOut
  1480. && b.channel < (int) state.instruments.size() && b.channel < maxChannels)
  1481. {
  1482. // LYNX's own instruments: the bend as the controller's wheel plays it (applyLiveControl), when it changes
  1483. if (! automatedBendReset)
  1484. {
  1485. automatedBend.fill (std::numeric_limits<float>::quiet_NaN());
  1486. automatedBendReset = true;
  1487. }
  1488. auto& last = automatedBend[(std::size_t) b.channel];
  1489. if (! (last == v) && state.instruments[(std::size_t) b.channel] != nullptr)
  1490. {
  1491. last = v;
  1492. NoteEvent e;
  1493. e.type = NoteEvent::Type::control;
  1494. e.channel = b.channel;
  1495. e.key = NoteEvent::controlPitchBend;
  1496. e.velocity = std::clamp (v, 0.0f, 1.0f) * 2.0f - 1.0f;
  1497. applyLiveControl (state, e);
  1498. }
  1499. continue;
  1500. }
  1501. if (b.channel < (int) state.instruments.size())
  1502. state.instruments[(std::size_t) b.channel]->setParameter (b.param, v);
  1503. // a MIDI Out's controls reach the plugins on its port
  1504. if ((std::size_t) b.channel < state.midiTargets.size() && midictl::isMidiParam (b.param)) // (a Dashboard's outputs stay its own)
  1505. for (const auto t : state.midiTargets[(std::size_t) b.channel])
  1506. if (t < (int) state.instruments.size())
  1507. state.instruments[(std::size_t) t]->setParameter (b.param, v);
  1508. }
  1509. else if (b.track < (int) state.effects.size() && b.slot < (int) state.effects[(std::size_t) b.track].size())
  1510. state.effects[(std::size_t) b.track][(std::size_t) b.slot]->setParameter (b.param, v);
  1511. }
  1512. }
  1513. void RackRenderer::deliverToEffects (const RackState& state, const NoteEvent& e) noexcept
  1514. {
  1515. if (e.channel < 0 || (std::size_t) e.channel >= state.effectMidiRoutes.size()
  1516. || (e.type != NoteEvent::Type::on && e.type != NoteEvent::Type::off && e.type != NoteEvent::Type::voiceProp) || e.port == -2)
  1517. return;
  1518. if (e.type == NoteEvent::Type::on && state.song.channels[(std::size_t) e.channel].muted)
  1519. return;
  1520. for (const auto& route : state.effectMidiRoutes[(std::size_t) e.channel])
  1521. {
  1522. if ((std::size_t) route.track >= state.effects.size() || (std::size_t) route.slot >= state.effects[(std::size_t) route.track].size())
  1523. continue;
  1524. if ((e.port >= 0 && route.port != e.port) || (e.port < 0 && route.portOnly))
  1525. continue;
  1526. if (auto* graph = patcher::graphOf (state.effects[(std::size_t) route.track][(std::size_t) route.slot].get()))
  1527. {
  1528. if (e.type == NoteEvent::Type::voiceProp) // (a VFX channel's voice property, round 165c: at once)
  1529. {
  1530. graph->voicePropertyPort (route.port, e.key, e.prop, e.velocity, e.port >= 0 ? (int) e.colour : route.midiChannel);
  1531. continue;
  1532. }
  1533. // at the note's sample in the chunk the slot renders next (round 164f; it was the chunk's start); a slot
  1534. // that is off renders nothing and gets nothing
  1535. const auto& slot = state.song.mixer[(std::size_t) route.track].effects[(std::size_t) route.slot];
  1536. if (! state.song.slotActive (slot))
  1537. continue;
  1538. if (e.type == NoteEvent::Type::on)
  1539. {
  1540. graph->queueNoteOnPort (route.port, e.key, e.velocity, route.midiChannel, e.sampleOffset);
  1541. // a note wakes a smart-disabled slot: the instruments inside play it (a silent insert is their usual place)
  1542. if (const auto key = (std::size_t) route.track * maxEffectSlots + (std::size_t) route.slot; key < smartDisable.size())
  1543. smartDisable[key].silentSamples = 0;
  1544. }
  1545. else
  1546. graph->queueNoteOffPort (route.port, e.key, route.midiChannel, e.sampleOffset);
  1547. }
  1548. }
  1549. }
  1550. float* RackRenderer::channelBuffer (int channel, int side) noexcept
  1551. {
  1552. return channelBuffers.data() + ((std::size_t) channel * 2 + (std::size_t) side) * chunkCapacity;
  1553. }
  1554. float* RackRenderer::trackScratch (int track, int side) noexcept
  1555. {
  1556. return trackScratchBuffers.data() + ((std::size_t) track * 2 + (std::size_t) side) * chunkCapacity;
  1557. }
  1558. // A whole channel over the chunk: notes at the exact sample (only its own events), volume/pan and the
  1559. // PDC delay. Each channel only touches its own instrument and buffer: it can run in parallel.
  1560. channelpoly::Mode RackRenderer::polyMode (const ChannelDef& c, const Instrument& instrument) const noexcept
  1561. {
  1562. channelpoly::Mode m;
  1563. // (the LYNX Synth plays its own Mono / Porta, the Sampler its own Porta: the layer leaves those to them)
  1564. m.mono = c.instrument != InstrumentKind::synth && channelMono (c);
  1565. m.porta = channelPortamento (c);
  1566. m.portaBeats = channelPortamentoBeats (c);
  1567. m.arpeggiator = c.arp.direction != 0;
  1568. m.echo = c.misc.echo.feedback > 0.0f;
  1569. m.slides = instrument.followsSlides();
  1570. m.glidesIn = instrument.followsChannelPorta();
  1571. return m;
  1572. }
  1573. void RackRenderer::clearPolyLayers() noexcept
  1574. {
  1575. for (auto& layer : polyLayers)
  1576. layer.clear();
  1577. }
  1578. void RackRenderer::renderChannel (const RackState& state, int i, int n) noexcept
  1579. {
  1580. const auto& c = state.song.channels[(std::size_t) i];
  1581. const auto automation = state.hasAutomation;
  1582. const auto volume = channelGain (automation ? automated (state.channelVolumeAuto[(std::size_t) i], c.volume) : c.volume);
  1583. const auto pan = automation ? automated (state.channelPanAuto[(std::size_t) i], (c.pan + 1.0f) * 0.5f) * 2.0f - 1.0f : c.pan;
  1584. float gl = 0.0f, gr = 0.0f;
  1585. panGains (pan, volume, gl, gr);
  1586. auto* l = channelBuffer (i, 0);
  1587. auto* r = channelBuffer (i, 1);
  1588. if ((std::size_t) i < state.instruments.size() && state.instruments[(std::size_t) i] != nullptr)
  1589. state.instruments[(std::size_t) i]->setSongPosition (chunkTick);
  1590. auto& instrument = *state.instruments[(std::size_t) i];
  1591. instrument.beginChunk (n); // (extra outputs: a generator Patcher's, REA_rodada141)
  1592. // issue #14: the channel's pitch as it is now (a hosted plugin bends to it; native engines took it at note on)
  1593. // (round 167a: the native generators move their sounding notes with it, as FL's do)
  1594. instrument.setChannelPitchNow (c.sampler.pitch * 100.0f, c.misc.fineTune + (c.misc.mainPitch ? state.song.masterPitch : 0.0f));
  1595. if (c.instrument == InstrumentKind::patcher) // its Hardware Insert nodes: this chunk's device buses (round 165c)
  1596. instrument.setHardwareIo (liveInput, hwOut != nullptr && hwOut->active.load (std::memory_order_relaxed) ? hwOut : nullptr, liveInputOffset);
  1597. // idle channel, no notes in this chunk and no PDC: nothing to do (neither clear nor sum into the mixer)
  1598. const auto hasDelay = (std::size_t) i < state.channelDelays.size() && state.channelDelays[(std::size_t) i] != nullptr;
  1599. const auto hasArp = ((std::size_t) i < state.arpeggiators.size() && state.arpeggiators[(std::size_t) i] != nullptr)
  1600. || ((std::size_t) i < state.echoes.size() && state.echoes[(std::size_t) i] != nullptr);
  1601. const auto* sources = state.hasMidiRoutes && (std::size_t) i < state.midiSources.size() && ! state.midiSources[(std::size_t) i].empty()
  1602. ? &state.midiSources[(std::size_t) i] : nullptr;
  1603. const auto routed = [sources] (int channel) {
  1604. return sources != nullptr && std::find (sources->begin(), sources->end(), channel) != sources->end();
  1605. };
  1606. if (! hasDelay && ! hasArp && instrument.idle()
  1607. && std::none_of (events.begin(), events.end(), [&] (const NoteEvent& e) { return e.channel == i || routed (e.channel); }))
  1608. {
  1609. channelSilent[(std::size_t) i] = 1;
  1610. return;
  1611. }
  1612. channelSilent[(std::size_t) i] = 0;
  1613. const UnitTimer timer (profiling.load (std::memory_order_relaxed), units->channelNs[(std::size_t) i], &units->channelMaxNs[(std::size_t) i]);
  1614. std::memset (l, 0, sizeof (float) * (std::size_t) n);
  1615. std::memset (r, 0, sizeof (float) * (std::size_t) n);
  1616. int position = 0;
  1617. // arpeggiator: the channel's notes become the arpeggio sequence
  1618. const NoteEvent* list = events.begin();
  1619. int listCount = events.size();
  1620. if ((std::size_t) i < state.arpeggiators.size() && state.arpeggiators[(std::size_t) i] != nullptr)
  1621. {
  1622. auto& arp = *state.arpeggiators[(std::size_t) i];
  1623. int inCount = 0;
  1624. for (const auto& e : events)
  1625. if (e.channel == i && inCount < Arpeggiator::maxEvents)
  1626. arp.input[(std::size_t) inCount++] = e;
  1627. int outCount = 0;
  1628. arp.process (i, arp.input.data(), inCount, chunkStartTick, chunkTps, n, c.arp, arp.output.data(), outCount);
  1629. // FL cuts an arpeggio note at its gate even on a sample that plays out (REA round 146b [EXEC: FL's renders of
  1630. // its Sampler render test]): the arpeggio is one voice, so its "off" stops the channel's sound (not with the
  1631. // echo delay, whose echoes keep ringing)
  1632. if (! c.misc.echo.enabled())
  1633. for (int k = 0; k < outCount; ++k)
  1634. if (arp.output[(std::size_t) k].type == NoteEvent::Type::off)
  1635. arp.output[(std::size_t) k].type = NoteEvent::Type::choke;
  1636. list = arp.output.data();
  1637. listCount = outCount;
  1638. }
  1639. // FL's echo delay (Misc tab): the channel's notes (after the arpeggio) and their echoes
  1640. const float* gains = nullptr;
  1641. if ((std::size_t) i < state.echoes.size() && state.echoes[(std::size_t) i] != nullptr)
  1642. {
  1643. auto& echo = *state.echoes[(std::size_t) i];
  1644. int inCount = 0;
  1645. for (int k = 0; k < listCount; ++k)
  1646. if (list[k].channel == i && inCount < channelmisc::NoteEcho::maxEvents)
  1647. echo.input[(std::size_t) inCount++] = list[k];
  1648. int outCount = 0;
  1649. echo.process (i, echo.input.data(), inCount, chunkStartTick, chunkTps, n, c.misc.echo, echo.output.data(), echo.outputGains.data(), outCount);
  1650. list = echo.output.data();
  1651. listCount = outCount;
  1652. gains = echo.outputGains.data();
  1653. }
  1654. const auto tracking = c.misc.key.pan != 0.0f || c.misc.velocity.pan != 0.0f;
  1655. 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;
  1656. // FL's Add to key (round 149): the root note moves the notes of instruments that are not samplers
  1657. const auto keyShift = c.misc.addToKey && c.instrument != InstrumentKind::sampler ? 60 - c.misc.rootNote : 0;
  1658. for (int index = 0; index < listCount; ++index)
  1659. {
  1660. auto shifted = list[index];
  1661. if (keyShift != 0 && shifted.channel == i)
  1662. shifted.key = std::clamp (shifted.key + keyShift, 0, 127);
  1663. const auto& e = shifted;
  1664. if (e.channel != i)
  1665. {
  1666. // a note of a MIDI Out channel on this plugin's MIDI input port, with that MIDI Out's MIDI channel
  1667. if (sources == nullptr || ! routed (e.channel)
  1668. || (e.type != NoteEvent::Type::on && e.type != NoteEvent::Type::off && e.type != NoteEvent::Type::voiceProp))
  1669. continue;
  1670. if (e.port == -2) // (a VFX channel's own note: its processor's output goes out instead)
  1671. continue;
  1672. if (e.sampleOffset > position)
  1673. {
  1674. instrument.render (l + position, r + position, e.sampleOffset - position, gl, gr);
  1675. position = e.sampleOffset;
  1676. }
  1677. // (each route from that channel: its port and MIDI channel, round 162)
  1678. for (const auto& route : state.midiRoutesIn[(std::size_t) i])
  1679. {
  1680. if (route.other != e.channel || (e.port >= 0 && route.port != e.port) || (e.port < 0 && route.portOnly))
  1681. continue;
  1682. // (a VFX channel's voice keeps its colour as the MIDI channel; so does a MIDI Out's note with "Map note
  1683. // color to MIDI channel", round 167i)
  1684. const auto midiChannel = e.port >= 0 || ((std::size_t) e.channel < state.mapNoteColour.size() && state.mapNoteColour[(std::size_t) e.channel] != 0)
  1685. ? (int) (e.colour & 15)
  1686. : route.midiChannel;
  1687. if (e.type == NoteEvent::Type::voiceProp) // (round 165c: outside a Patcher too)
  1688. instrument.voicePropertyPort (route.port, e.key, e.prop, e.velocity, midiChannel);
  1689. else if (e.type == NoteEvent::Type::on)
  1690. {
  1691. if (! c.muted && ! state.song.channels[(std::size_t) e.channel].muted)
  1692. {
  1693. if (e.port >= 0)
  1694. {
  1695. instrument.setNextNoteExpression (e.pan, e.cents, e.porta);
  1696. instrument.setNextNoteModulation (e.modX, e.modY);
  1697. instrument.setNextNoteColour (e.colour);
  1698. }
  1699. instrument.noteOnPort (route.port, e.key, e.velocity, midiChannel);
  1700. }
  1701. }
  1702. else
  1703. {
  1704. if (e.port >= 0)
  1705. instrument.setNextNoteRelease (e.release);
  1706. instrument.noteOffPort (route.port, e.key, midiChannel);
  1707. }
  1708. }
  1709. continue;
  1710. }
  1711. if (e.port >= 0 || e.type == NoteEvent::Type::voiceProp) // (what this channel sends out on a port is for the others)
  1712. continue;
  1713. if (e.sampleOffset > position)
  1714. {
  1715. instrument.render (l + position, r + position, e.sampleOffset - position, gl, gr);
  1716. position = e.sampleOffset;
  1717. }
  1718. auto& held = heldNotes[(std::size_t) i];
  1719. const auto bit = std::uint64_t { 1 } << (e.key & 63);
  1720. if (e.type == NoteEvent::Type::on)
  1721. {
  1722. if (e.key >= 0 && e.key < 128)
  1723. {
  1724. held[(std::size_t) (e.key >> 6)] |= bit;
  1725. struckNotes[(std::size_t) i][(std::size_t) (e.key >> 6)] |= bit;
  1726. }
  1727. // FL's key region (round 164): the channel plays only the notes inside it (audio clips: the key is the clip)
  1728. const auto inRegion = c.instrument == InstrumentKind::audioClip || c.inKeyRegion (list[index].key);
  1729. if (! c.muted && inRegion)
  1730. {
  1731. // (an audio clip follows its fine tune, not the main pitch: LYNX never moved clips with it)
  1732. const auto noteCents = e.cents + c.misc.fineTune
  1733. + (c.misc.mainPitch && c.instrument != InstrumentKind::audioClip ? state.song.masterPitch : 0.0f);
  1734. // FL's channel Mono / Porta (round 168l): a Mono note over a held one moves the sounding voice instead
  1735. const auto mode = polyMode (c, instrument);
  1736. const auto glideSamples = (float) (channelpoly::glideBeats (mode.portaBeats) * ppq / std::max (1.0e-9, chunkTps));
  1737. auto& poly = polyLayers[(std::size_t) i];
  1738. // (an echo delay's repeats are FL's generated voices: they don't enter the Mono list)
  1739. const auto on = e.echo ? channelpoly::On {} : poly.noteOn (mode, e.key, noteCents, e.porta, e.colour);
  1740. if (on.release >= 0)
  1741. {
  1742. instrument.noteOff (on.release);
  1743. voiceOrders[(std::size_t) i].noteOff (on.release);
  1744. }
  1745. if (! on.start)
  1746. {
  1747. if (on.slide)
  1748. instrument.slideTo (e.key, noteCents, glideSamples);
  1749. continue;
  1750. }
  1751. // Max polyphony: the oldest note is released first
  1752. if (const auto limit = voiceLimitFor (c.maxPolyphony, channelMono (c)); limit > 0)
  1753. if (const auto victim = voiceOrders[(std::size_t) i].noteOn (e.key, limit); victim >= 0)
  1754. instrument.noteOff (victim);
  1755. const auto pan = tracking ? channelmisc::trackedPan (c.misc, e.key, e.velocity, e.pan) : e.pan;
  1756. // (porta: the voice starts at the group's last note and glides to its own pitch, HostSlide::anchor)
  1757. instrument.setNextNoteExpression (pan, noteCents + (on.glide ? on.glideFrom : 0.0f), e.porta);
  1758. HostSlide::pendingGlide() = { on.glide ? on.glideFrom : 0.0f, on.glide ? glideSamples : 0.0f, false };
  1759. {
  1760. const auto [modX, modY] = modTracking ? channelmisc::trackedModulation (c.misc, e.key, e.velocity, e.modX, e.modY)
  1761. : std::pair<float, float> { e.modX, e.modY };
  1762. instrument.setNextNoteModulation (modX, modY);
  1763. }
  1764. instrument.setNextNoteColour (e.colour);
  1765. if (e.clipPitch != 0.0f)
  1766. instrument.setNextClipPitch (e.clipPitch);
  1767. if (e.clipStretch != 1.0f)
  1768. instrument.setNextClipStretch (e.clipStretch);
  1769. if (e.fadeIn > 0.0f || e.fadeOut > 0.0f || e.fadeShape != 0)
  1770. instrument.setNextClipFades (e.clipElapsed, e.clipRemaining, e.fadeIn, e.fadeOut, e.fadeShape);
  1771. // an echo's volume: the instrument scales the voice, else (engines without it) the velocity
  1772. auto velocity = e.velocity;
  1773. const auto gain = e.gain * (gains != nullptr ? gains[index] : 1.0f);
  1774. if (gain != 1.0f && ! instrument.setNextNoteGain (gain))
  1775. velocity *= gain;
  1776. instrument.noteOnAt (e.key, velocity, e.startSeconds);
  1777. HostSlide::pendingGlide() = {};
  1778. }
  1779. }
  1780. else if (e.type == NoteEvent::Type::slide)
  1781. {
  1782. instrument.slideTo (e.key, e.cents + c.misc.fineTune + (c.misc.mainPitch ? state.song.masterPitch : 0.0f), e.slideSamples);
  1783. }
  1784. else if (e.type == NoteEvent::Type::choke)
  1785. {
  1786. instrument.cut(); // short fade, like FL's "cut"
  1787. held = {};
  1788. voiceOrders[(std::size_t) i].clear();
  1789. polyLayers[(std::size_t) i].clear();
  1790. }
  1791. else
  1792. {
  1793. instrument.setNextNoteRelease (e.release);
  1794. // a Mono channel (round 168l): the voice ends with the last held note, else it glides back to the newest
  1795. const auto mode = polyMode (c, instrument);
  1796. const auto off = e.echo ? channelpoly::Off { e.key } : polyLayers[(std::size_t) i].noteOff (mode, e.key, e.colour);
  1797. if (off.slide)
  1798. instrument.slideTo (off.key, off.cents,
  1799. (float) (channelpoly::glideBeats (mode.portaBeats) * ppq / std::max (1.0e-9, chunkTps)));
  1800. if (off.release >= 0)
  1801. {
  1802. instrument.noteOff (off.release);
  1803. voiceOrders[(std::size_t) i].noteOff (off.release);
  1804. }
  1805. if (e.key >= 0 && e.key < 128)
  1806. held[(std::size_t) (e.key >> 6)] &= ~bit;
  1807. }
  1808. }
  1809. if (position < n)
  1810. instrument.render (l + position, r + position, n - position, gl, gr);
  1811. // PDC: this channel arrives before the track's others; delay until aligned
  1812. if ((std::size_t) i < state.channelDelays.size() && state.channelDelays[(std::size_t) i] != nullptr)
  1813. state.channelDelays[(std::size_t) i]->process (l, r, n);
  1814. }
  1815. void RackRenderer::applyTrackEq (const MixerTrack& track, int t, bool bypassed, float* l, float* r, int n) noexcept
  1816. {
  1817. if ((std::size_t) t >= trackEqs.size())
  1818. return;
  1819. auto& eq = trackEqs[(std::size_t) t];
  1820. if (bypassed || ! track.eq.active()) // clean mixer (round 163): no built-in processing, the samples pass untouched
  1821. {
  1822. if (eq.running)
  1823. eq = {}; // off: reset the filters so they don't come back with a stale tail
  1824. return;
  1825. }
  1826. if (! eq.running || ! (eq.settings == track.eq))
  1827. {
  1828. // new coefficients, keeping the filter state (no click when adjusting)
  1829. const auto& s = track.eq;
  1830. eq.bands[0].shelf (sampleRate, std::min ((double) s.hz[0], sampleRate * 0.45), s.gainDb[0], false, TrackEq::shelfSlope (s.width[0]));
  1831. eq.bands[1].peaking (sampleRate, std::min ((double) s.hz[1], sampleRate * 0.45), TrackEq::peakQ (s.width[1]), s.gainDb[1]);
  1832. eq.bands[2].shelf (sampleRate, std::min ((double) s.hz[2], sampleRate * 0.45), s.gainDb[2], true, TrackEq::shelfSlope (s.width[2]));
  1833. for (std::size_t b = 0; b < 3; ++b)
  1834. if (s.gainDb[b] == 0.0f)
  1835. eq.bands[b].reset();
  1836. eq.settings = s;
  1837. eq.running = true;
  1838. }
  1839. for (std::size_t b = 0; b < 3; ++b)
  1840. {
  1841. if (eq.settings.gainDb[b] == 0.0f)
  1842. continue; // band at 0 dB: not processed (like FL)
  1843. eq.bands[b].processBlock (l, r, n);
  1844. }
  1845. }
  1846. // effects whose controlOutput() an editor shows live
  1847. static bool hasLiveMeters (EffectKind kind) noexcept
  1848. {
  1849. // round 129: the voice tools (Quell's reduction meter was never published) and the basic compressor's meters
  1850. return mixsuite::isSuiteKind (kind) || dyn::isDynKind (kind) || kind == EffectKind::lynxTune || kind == EffectKind::facetEq
  1851. || kind == EffectKind::apexLimiter || voicetools::isVoiceKind (kind) || kind == EffectKind::compressor
  1852. || kind == EffectKind::echoform // round 135w: Echoform's output meter
  1853. || kind == EffectKind::autoPan || kind == EffectKind::voiceShift // round 135: the pan position, the shifter's notes
  1854. || kind == EffectKind::hardwareInsert // round 164d: send / return levels, the ping
  1855. || kind == EffectKind::xyController || kind == EffectKind::xyzController; // round 164: the pad's target and outputs
  1856. }
  1857. void RackRenderer::setSidechain (const RackState& state, const EffectSlot& slot, Effect& effect, int track) noexcept
  1858. {
  1859. // the source was already processed in this pass (earlier layer); silent = no signal in the detector
  1860. for (const auto second : { false, true })
  1861. {
  1862. const auto source = second ? slot.sidechain2 : slot.sidechain;
  1863. if (source < 0 || source == track || source >= (int) state.song.mixer.size())
  1864. continue;
  1865. const auto active = (std::size_t) source < trackActive.size() && trackActive[(std::size_t) source] != 0;
  1866. const auto* left = active ? trackBuffer (source, 0) : nullptr;
  1867. const auto* right = active ? trackBuffer (source, 1) : nullptr;
  1868. if (second)
  1869. effect.setSidechain2 (left, right);
  1870. else
  1871. effect.setSidechain (left, right);
  1872. }
  1873. }
  1874. void RackRenderer::runEffects (const RackState& state, int track, int n) noexcept
  1875. {
  1876. if (track >= (int) state.effects.size())
  1877. return;
  1878. const auto& slots = state.song.mixer[(std::size_t) track].effects;
  1879. const auto& effects = state.effects[(std::size_t) track];
  1880. auto* l = trackBuffer (track, 0);
  1881. auto* r = trackBuffer (track, 1);
  1882. int audible = -1; // -1 = not measured yet; an effect's output is the next one's input
  1883. const auto timing = times->enabled.load (std::memory_order_relaxed);
  1884. auto timed = [this, timing] (std::size_t key, auto&& run) {
  1885. if (! timing || key >= times->effectNs.size())
  1886. {
  1887. run();
  1888. return;
  1889. }
  1890. const auto before = ProcessTimes::now();
  1891. run();
  1892. times->effectNs[key].fetch_add (ProcessTimes::now() - before, std::memory_order_relaxed);
  1893. };
  1894. for (std::size_t i = 0; i < effects.size() && i < slots.size(); ++i)
  1895. {
  1896. // slot dry/wet (automatable)
  1897. const auto wet = state.hasAutomation && i < state.effectMixAuto[(std::size_t) track].size()
  1898. ? std::clamp (automated (state.effectMixAuto[(std::size_t) track][i], slots[i].mix), 0.0f, 1.0f)
  1899. : slots[i].mix;
  1900. auto clearMeters = [this, track, i] {
  1901. const auto at = ((std::size_t) track * maxEffectSlots + i) * ProcessTimes::meterOutputs;
  1902. if (at + ProcessTimes::meterOutputs <= times->effectMeters.size())
  1903. for (int o = 0; o < ProcessTimes::meterOutputs; ++o)
  1904. times->effectMeters[at + (std::size_t) o].store (0.0f, std::memory_order_relaxed);
  1905. };
  1906. if (! state.song.slotActive (slots[i]) || wet <= 0.0f)
  1907. {
  1908. if (hasLiveMeters (slots[i].kind))
  1909. clearMeters();
  1910. continue;
  1911. }
  1912. // smart disable (like FL): an effect with silent input and output is skipped (plugins
  1913. // after 4 s; built-ins after 1 s, which is well beyond their tail)
  1914. const auto key = (std::size_t) track * maxEffectSlots + i;
  1915. const auto isPlugin = slots[i].kind == EffectKind::plugin;
  1916. const auto hold = (int) (sampleRate * (isPlugin || slots[i].kind == EffectKind::patcher ? 4.0 : 1.0)); // (a Patcher may hold plugins)
  1917. // (not Gross Beat: its buffer must keep recording the silence it may play back later, as in FL)
  1918. // (nor Newtone / Newtime: in slave mode they play their sample whatever the input)
  1919. // (nor a slot whose "Smart disable" is off, or a plugin that does not allow it — FL's per-plugin options, REA round 139)
  1920. if (key < smartDisable.size() && slots[i].smartDisable && ! (isPlugin && ! slots[i].plugin.allowSmartDisable)
  1921. && slots[i].kind != EffectKind::grossBeat && slots[i].kind != EffectKind::newtone
  1922. && slots[i].kind != EffectKind::newtime
  1923. && slots[i].kind != EffectKind::scratcher // (nor the Scratcher: its turntable plays whatever the input)
  1924. && slots[i].kind != EffectKind::hardwareInsert // (nor the hardware insert: outboard gear has its own tails and noise)
  1925. && ! (slots[i].kind == EffectKind::patcher && patcher::usesHardwareIo (slots[i].patcher)) // (nor a Patcher holding one, round 165c)
  1926. // (nor a controller: its outputs move whatever the sound — a silent insert is their usual place; round 164)
  1927. && slots[i].kind != EffectKind::formulaController
  1928. && slots[i].kind != EffectKind::xyController && slots[i].kind != EffectKind::xyzController
  1929. && slots[i].kind != EffectKind::controlSurface
  1930. // round 164c: a visual plugin keeps recording silence (its display falls, the video export stays in time)
  1931. && slots[i].kind != EffectKind::waveCandy && slots[i].kind != EffectKind::visualizer
  1932. && slots[i].kind != EffectKind::tuner // (round 165g: the tuner's display follows the signal into silence)
  1933. // (round 166f: nor Facet EQ playing its comparative target — the sidechain plays while this track is silent)
  1934. && ! (slots[i].kind == EffectKind::facetEq && facet::listensToTarget (slots[i].params)))
  1935. {
  1936. auto& sd = smartDisable[key];
  1937. if (sd.effect != effects[i].get())
  1938. sd = { effects[i].get(), 0 };
  1939. if (audible < 0)
  1940. audible = anyAbove (l, r, n, silenceLevel) ? 1 : 0;
  1941. if (audible == 1)
  1942. sd.silentSamples = 0;
  1943. else if (sd.silentSamples >= hold)
  1944. {
  1945. if (hasLiveMeters (slots[i].kind))
  1946. clearMeters();
  1947. continue;
  1948. }
  1949. else
  1950. sd.silentSamples += n;
  1951. }
  1952. // the editor's spectrum analyser listens to this slot: its input
  1953. const auto tapped = times->analyzer.key.load (std::memory_order_relaxed) == (int) key;
  1954. if (tapped)
  1955. {
  1956. auto& tap = times->analyzer;
  1957. const auto w = tap.written.load (std::memory_order_relaxed);
  1958. for (int k = 0; k < n; ++k)
  1959. 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);
  1960. // round 166f: and its sidechain (Facet EQ draws its comparative target)
  1961. const auto source = slots[i].sidechain;
  1962. const bool side = source >= 0 && source != track && source < (int) state.song.mixer.size();
  1963. const bool sounding = side && (std::size_t) source < trackActive.size() && trackActive[(std::size_t) source] != 0;
  1964. const auto* sl = sounding ? trackBuffer (source, 0) : nullptr;
  1965. const auto* sr = sounding ? trackBuffer (source, 1) : nullptr;
  1966. for (int k = 0; k < n; ++k)
  1967. tap.side[(std::size_t) ((w + (std::uint32_t) k) & (ProcessTimes::AnalyzerTap::size - 1))].store (sl != nullptr ? 0.5f * (sl[k] + sr[k]) : 0.0f, std::memory_order_relaxed);
  1968. tap.sideOn.store (side, std::memory_order_relaxed);
  1969. }
  1970. // dry/wet: keep the dry signal to mix later
  1971. // (not the hardware insert: its dry path is delayed by its round trip inside it, so the slot's mix scales its own
  1972. // dry/wet instead — round 164d)
  1973. const auto partial = wet < 0.999f && slots[i].kind != EffectKind::hardwareInsert;
  1974. if (partial)
  1975. {
  1976. std::memcpy (trackScratch (track, 0), l, sizeof (float) * (std::size_t) n);
  1977. std::memcpy (trackScratch (track, 1), r, sizeof (float) * (std::size_t) n);
  1978. }
  1979. const UnitTimer timer (profiling.load (std::memory_order_relaxed), units->effectNs[std::min (key, units->effectNs.size() - 1)],
  1980. &units->effectMaxNs[std::min (key, units->effectNs.size() - 1)]);
  1981. // the hardware insert (round 164d): this piece's device input and output buses (none during an export)
  1982. if (slots[i].kind == EffectKind::hardwareInsert || slots[i].kind == EffectKind::patcher) // (a Patcher hands them to its nodes, round 165c)
  1983. effects[i]->setHardwareIo (liveInput, hwOut != nullptr && hwOut->active.load (std::memory_order_relaxed) ? hwOut : nullptr, liveInputOffset);
  1984. // Fruity Send / Patcher / Transmitter / Transporter: what it sends goes to its own buffer, pulled by the destination insert
  1985. // (processed later)
  1986. if (slots[i].kind == EffectKind::fruitySend || slots[i].kind == EffectKind::patcher || slots[i].kind == EffectKind::transmitter
  1987. || slots[i].kind == EffectKind::flTransporter)
  1988. {
  1989. for (int o = 0; o < maxSlotSends; ++o)
  1990. {
  1991. const auto key = i * (std::size_t) maxSlotSends + (std::size_t) o;
  1992. const auto tap = (std::size_t) track < state.slotTap.size() && key < state.slotTap[(std::size_t) track].size()
  1993. ? state.slotTap[(std::size_t) track][key]
  1994. : -1;
  1995. if (tap >= 0 && tap < RackState::maxSendTaps)
  1996. {
  1997. std::memset (tapBuffer (tap, 0), 0, sizeof (float) * (std::size_t) n);
  1998. std::memset (tapBuffer (tap, 1), 0, sizeof (float) * (std::size_t) n);
  1999. effects[i]->setExtraOutput (o, tapBuffer (tap, 0), tapBuffer (tap, 1));
  2000. tapActive[(std::size_t) tap] = 1;
  2001. }
  2002. else
  2003. effects[i]->setExtraOutput (o, nullptr, nullptr);
  2004. }
  2005. }
  2006. if (slots[i].kind == EffectKind::hardwareInsert && wet < 0.999f)
  2007. {
  2008. auto params = slots[i].params; // copy without allocation
  2009. if (state.hasAutomation)
  2010. {
  2011. const auto& autos = state.effectParamAuto[(std::size_t) track][i];
  2012. const auto used = std::min (params.size(), effectInfo (slots[i].kind).params.size());
  2013. for (std::size_t p = 0; p < used; ++p)
  2014. params[p] = automated (autos[p], params[p]);
  2015. }
  2016. params[(std::size_t) hwinsert::dryWet] *= wet;
  2017. timed (key, [&] { effects[i]->process (l, r, n, params, bpm); });
  2018. }
  2019. else if (state.hasAutomation && ! isPlugin)
  2020. {
  2021. auto params = slots[i].params; // copy without allocation
  2022. const auto& autos = state.effectParamAuto[(std::size_t) track][i];
  2023. const auto used = std::min (params.size(), effectInfo (slots[i].kind).params.size());
  2024. for (std::size_t p = 0; p < used; ++p)
  2025. params[p] = automated (autos[p], params[p]);
  2026. effects[i]->setSongPosition (chunkTick);
  2027. effects[i]->setPlaying (chunkPlaying);
  2028. effects[i]->setHeldNotes (heldNotes.data(), maxChannels);
  2029. setSidechain (state, slots[i], *effects[i], track);
  2030. timed (key, [&] { effects[i]->process (l, r, n, params, bpm); });
  2031. }
  2032. else
  2033. {
  2034. effects[i]->setSongPosition (chunkTick);
  2035. effects[i]->setPlaying (chunkPlaying);
  2036. effects[i]->setHeldNotes (heldNotes.data(), maxChannels);
  2037. setSidechain (state, slots[i], *effects[i], track);
  2038. timed (key, [&] { effects[i]->process (l, r, n, slots[i].params, bpm); });
  2039. }
  2040. // an effect that output NaN / inf (an unstable setting): this block of it is muted and its state reset, so the
  2041. // broken values never reach the rest of the mix (they would stay in every filter and feedback path after it)
  2042. if (! finiteBlock (l, r, n))
  2043. {
  2044. std::memset (l, 0, sizeof (float) * (std::size_t) n);
  2045. std::memset (r, 0, sizeof (float) * (std::size_t) n);
  2046. effects[i]->reset();
  2047. nonFiniteBlocks.fetch_add (1, std::memory_order_relaxed);
  2048. }
  2049. if (partial)
  2050. {
  2051. const auto* dl = trackScratch (track, 0);
  2052. const auto* dr = trackScratch (track, 1);
  2053. for (int k = 0; k < n; ++k)
  2054. {
  2055. l[k] = dl[k] + (l[k] - dl[k]) * wet;
  2056. r[k] = dr[k] + (r[k] - dr[k]) * wet;
  2057. }
  2058. }
  2059. // ... and its output
  2060. if (tapped)
  2061. {
  2062. auto& tap = times->analyzer;
  2063. const auto w = tap.written.load (std::memory_order_relaxed);
  2064. for (int k = 0; k < n; ++k)
  2065. 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);
  2066. tap.sampleRate.store (sampleRate, std::memory_order_relaxed);
  2067. tap.written.store (w + (std::uint32_t) n, std::memory_order_release);
  2068. }
  2069. // live meters for the editor (the mixing suite's gain reduction, LYNX Tune's pitch, Facet EQ's dynamic gains)
  2070. if (hasLiveMeters (slots[i].kind) && key < (std::size_t) maxMixerTracks * maxEffectSlots)
  2071. for (int o = 0; o < ProcessTimes::meterOutputs; ++o)
  2072. times->effectMeters[key * ProcessTimes::meterOutputs + (std::size_t) o].store (effects[i]->controlOutput (o), std::memory_order_relaxed);
  2073. // the effect changed the signal: measure again (it is the next slot's input)
  2074. audible = anyAbove (l, r, n, silenceLevel) ? 1 : 0;
  2075. if (audible == 1 && key < smartDisable.size())
  2076. smartDisable[key].silentSamples = 0; // tail (reverb, delay): keep processing
  2077. }
  2078. }
  2079. std::uint64_t RackRenderer::nonFiniteEffectBlocks() noexcept
  2080. {
  2081. return nonFiniteBlocks.load (std::memory_order_relaxed);
  2082. }
  2083. void RackRenderer::process (const RackState* state,
  2084. bool playing,
  2085. double startTick,
  2086. int numSamples,
  2087. float* left,
  2088. float* right,
  2089. LiveEventQueue* live,
  2090. MeterBank* meters,
  2091. LiveEventQueue* moreLive) noexcept
  2092. {
  2093. const ScopedFlushDenormals noDenormals;
  2094. const UnitTimer timer (profiling.load (std::memory_order_relaxed), units->processNs);
  2095. if (profiling.load (std::memory_order_relaxed))
  2096. units->processedSamples.fetch_add ((std::uint64_t) std::max (0, numSamples), std::memory_order_relaxed);
  2097. std::memset (left, 0, sizeof (float) * (std::size_t) numSamples);
  2098. std::memset (right, 0, sizeof (float) * (std::size_t) numSamples);
  2099. events.clear();
  2100. if (state == nullptr || blockCapacity == 0)
  2101. return;
  2102. const auto timing = times->enabled.load (std::memory_order_relaxed);
  2103. const auto wallStart = timing ? ProcessTimes::now() : 0;
  2104. // A snapshot built before the device opened may have another rate. The instruments'
  2105. // prepare() does not allocate, so it can run here.
  2106. if (state != lastState && state->sampleRate != sampleRate)
  2107. {
  2108. for (auto& instrument : state->instruments)
  2109. instrument->prepare (sampleRate);
  2110. for (auto& track : state->effects)
  2111. for (auto& effect : track)
  2112. effect->prepare (sampleRate);
  2113. }
  2114. lastState = state; // so prepare() knows which instruments to reconfigure
  2115. // Stopping, or jumping to another position (seek/rewind), releases held notes:
  2116. // their "off" events will no longer happen.
  2117. const auto jumped = playing && wasPlaying && std::abs (startTick - expectedTick) > 1.0;
  2118. if ((wasPlaying && ! playing) || (playing && ! wasPlaying))
  2119. {
  2120. // the arpeggiators / echoes ran on the live clock while stopped (round 149): they restart on the song's
  2121. liveRoutedCount = 0;
  2122. for (auto& arp : state->arpeggiators)
  2123. if (arp != nullptr)
  2124. arp->reset();
  2125. for (auto& echo : state->echoes)
  2126. if (echo != nullptr)
  2127. echo->reset();
  2128. }
  2129. if ((wasPlaying && ! playing) || jumped)
  2130. {
  2131. for (auto& instrument : state->instruments)
  2132. if (jumped)
  2133. instrument->allNotesOff();
  2134. else
  2135. instrument->transportStopped(); // (a hosted plugin: FL's "Send All Notes Off when playback stops")
  2136. heldNotes.fill ({});
  2137. clearPolyLayers();
  2138. for (auto& arp : state->arpeggiators)
  2139. if (arp != nullptr)
  2140. arp->reset();
  2141. for (auto& echo : state->echoes)
  2142. if (echo != nullptr)
  2143. echo->reset();
  2144. }
  2145. // FL resets its generators when playback starts: a MIDI Out sends its bank, patch and controls again
  2146. // (REA_rodada167i §1.4)
  2147. if (playing && ! wasPlaying)
  2148. for (std::size_t c = 0; c < state->song.channels.size() && c < state->instruments.size(); ++c)
  2149. if (state->song.channels[c].instrument == InstrumentKind::midiOut && state->instruments[c] != nullptr)
  2150. state->instruments[c]->transportStarted();
  2151. // started playing or jumped: audio clips in progress must start mid-way
  2152. resumeAudio = playing && (! wasPlaying || jumped);
  2153. // FL's "Play truncated notes on transport": at the start of playback, and after the user moves the position while
  2154. // playing (FL's set-position FUN_011e7a10 → FUN_011e78a0 → FUN_011e7470 with its catch-up flag set, round 167k),
  2155. // the notes already sounding there play. The loop's wrap is not a set-position and chases nothing.
  2156. const auto userJump = jumped && userJumpSerial != seenUserJumpSerial;
  2157. seenUserJumpSerial = userJumpSerial;
  2158. chaseNotes = playing && (! wasPlaying || userJump) && playTruncatedOnTransport;
  2159. // FL's "Reset plugins on transport" (FUN_011e7a10 → FUN_011c8a40 mode 2 → FUN_012b5210, every registered plugin's
  2160. // reset, generators included): the effects' tails and buffers are cleared and the plugin generators stop when
  2161. // playback starts or jumps (round 167k: instruments too, hosted plugins with their wrapper's reset option)
  2162. if (resetPluginsOnTransport && playing && (! wasPlaying || jumped))
  2163. {
  2164. for (auto& slots : state->effects)
  2165. for (auto& effect : slots)
  2166. if (effect != nullptr)
  2167. effect->transportReset();
  2168. for (auto& instrument : state->instruments)
  2169. if (instrument != nullptr)
  2170. instrument->transportReset();
  2171. }
  2172. wasPlaying = playing;
  2173. // tempo automation: the tempo holds for the whole block (evaluated at its start)
  2174. bpm = tempoOverride > 0.0 ? tempoOverride : state->song.bpm;
  2175. if (tempoOverride <= 0.0 && state->tempoAutomation >= 0 && state->song.mode == PlayMode::song && ! isSlotOverridden (state->tempoAutomation))
  2176. {
  2177. const auto length = (double) std::max<std::int64_t> (1, state->schedule.songLength);
  2178. const auto& clips = state->automationClips[(std::size_t) state->tempoAutomation];
  2179. if (! clips.empty())
  2180. bpm = tempoFromValue (automationValueAt (state->song, state->song.automations[(std::size_t) state->tempoAutomation], clips,
  2181. std::fmod (std::max (0.0, startTick), length)));
  2182. }
  2183. const auto tps = ticksPerSample (bpm, sampleRate);
  2184. expectedTick = startTick + numSamples * tps;
  2185. for (auto* queue : { live, moreLive })
  2186. {
  2187. if (queue == nullptr)
  2188. continue;
  2189. NoteEvent e;
  2190. while (queue->pop (e))
  2191. {
  2192. if (e.type == NoteEvent::Type::choke && e.channel < 0) // panic: every channel stops sounding
  2193. {
  2194. for (auto& instrument : state->instruments)
  2195. if (instrument != nullptr)
  2196. instrument->panic();
  2197. heldNotes.fill ({});
  2198. for (auto& order : voiceOrders)
  2199. order.clear();
  2200. clearPolyLayers();
  2201. continue;
  2202. }
  2203. if (e.channel < 0 || e.channel >= (int) state->instruments.size())
  2204. continue;
  2205. if (e.type == NoteEvent::Type::control)
  2206. {
  2207. applyLiveControl (*state, e);
  2208. continue;
  2209. }
  2210. auto& instrument = *state->instruments[(std::size_t) e.channel];
  2211. auto& held = heldNotes[(std::size_t) std::min (e.channel, maxChannels - 1)];
  2212. const auto bit = std::uint64_t { 1 } << (e.key & 63);
  2213. const auto inRange = e.key >= 0 && e.key < 128;
  2214. // played on a MIDI Out channel: the plugins on its port get the note with its MIDI channel
  2215. if (state->hasMidiRoutes && (std::size_t) e.channel < state->midiRoutesOut.size()
  2216. && ((std::size_t) e.channel >= state->vfxPort.size() || state->vfxPort[(std::size_t) e.channel] < 0))
  2217. for (const auto& route : state->midiRoutesOut[(std::size_t) e.channel])
  2218. if (! route.portOnly && route.other < (int) state->instruments.size() && state->instruments[(std::size_t) route.other] != nullptr)
  2219. {
  2220. auto& target = *state->instruments[(std::size_t) route.other];
  2221. const auto midiChannel = state->mapNoteColour[(std::size_t) e.channel] != 0 ? (int) (e.colour & 15) : route.midiChannel;
  2222. if (e.type == NoteEvent::Type::on)
  2223. target.noteOnPort (route.port, e.key, e.velocity, midiChannel);
  2224. else if (e.type == NoteEvent::Type::off)
  2225. target.noteOffPort (route.port, e.key, midiChannel);
  2226. }
  2227. // and the mixer-slot Patchers on its port (round 162)
  2228. // (notes that go through the channel's note path reach them in processChunk)
  2229. if (state->hasEffectMidiRoutes && ! routesLiveNotes (*state, e.channel))
  2230. deliverToEffects (*state, e);
  2231. // the channel's arpeggiator / echo delay / tracking play it (in processChunk's first chunk)
  2232. if ((e.type == NoteEvent::Type::on || e.type == NoteEvent::Type::off) && routesLiveNotes (*state, e.channel))
  2233. {
  2234. if (liveRoutedCount < (int) liveRouted.size())
  2235. {
  2236. e.sampleOffset = 0;
  2237. liveRouted[(std::size_t) liveRoutedCount++] = e;
  2238. }
  2239. continue;
  2240. }
  2241. auto& order = voiceOrders[(std::size_t) std::min (e.channel, maxChannels - 1)];
  2242. if (e.type == NoteEvent::Type::on && (std::size_t) e.channel < state->song.channels.size()
  2243. && ! state->song.channels[(std::size_t) e.channel].inKeyRegion (e.key))
  2244. continue; // outside the channel's key region (round 164)
  2245. const auto& def = state->song.channels;
  2246. auto& poly = polyLayers[(std::size_t) std::min (e.channel, maxChannels - 1)];
  2247. if (e.type == NoteEvent::Type::on)
  2248. {
  2249. if (inRange)
  2250. {
  2251. held[(std::size_t) (e.key >> 6)] |= bit;
  2252. struckNotes[(std::size_t) std::min (e.channel, maxChannels - 1)][(std::size_t) (e.key >> 6)] |= bit;
  2253. }
  2254. if ((std::size_t) e.channel >= def.size())
  2255. {
  2256. instrument.noteOn (e.key, e.velocity);
  2257. continue;
  2258. }
  2259. const auto& c = def[(std::size_t) e.channel];
  2260. // a played note is tuned like the song's notes: Misc › Fine tune and the main pitch (round 162, issue
  2261. // #9: the fine tune did nothing to the keys played live)
  2262. const auto cents = c.misc.fineTune + (c.misc.mainPitch ? state->song.masterPitch : 0.0f);
  2263. // FL's channel Mono / Porta (round 168l), as for the song's notes
  2264. const auto mode = polyMode (c, instrument);
  2265. const auto glideSamples = (float) (channelpoly::glideBeats (mode.portaBeats) * ppq / std::max (1.0e-9, tps));
  2266. const auto on = poly.noteOn (mode, e.key, cents, false, e.colour);
  2267. if (on.release >= 0)
  2268. {
  2269. order.noteOff (on.release);
  2270. instrument.noteOff (on.release);
  2271. }
  2272. if (! on.start)
  2273. {
  2274. if (on.slide)
  2275. instrument.slideTo (e.key, cents, glideSamples);
  2276. continue;
  2277. }
  2278. if (const auto limit = voiceLimitFor (c.maxPolyphony, channelMono (c)); limit > 0)
  2279. if (const auto victim = order.noteOn (e.key, limit); victim >= 0)
  2280. instrument.noteOff (victim);
  2281. if (const auto from = on.glide ? on.glideFrom : 0.0f; cents != 0.0f || from != 0.0f)
  2282. instrument.setNextNoteExpression (0.0f, cents + from, false);
  2283. HostSlide::pendingGlide() = { on.glide ? on.glideFrom : 0.0f, on.glide ? glideSamples : 0.0f, false };
  2284. instrument.noteOn (e.key, e.velocity);
  2285. HostSlide::pendingGlide() = {};
  2286. }
  2287. else
  2288. {
  2289. if (inRange)
  2290. held[(std::size_t) (e.key >> 6)] &= ~bit;
  2291. if ((std::size_t) e.channel >= def.size())
  2292. {
  2293. order.noteOff (e.key);
  2294. instrument.noteOff (e.key);
  2295. continue;
  2296. }
  2297. const auto mode = polyMode (def[(std::size_t) e.channel], instrument);
  2298. const auto off = poly.noteOff (mode, e.key, e.colour);
  2299. if (off.slide)
  2300. instrument.slideTo (off.key, off.cents, (float) (channelpoly::glideBeats (mode.portaBeats) * ppq / std::max (1.0e-9, tps)));
  2301. if (off.release >= 0)
  2302. {
  2303. order.noteOff (off.release);
  2304. instrument.noteOff (off.release);
  2305. }
  2306. }
  2307. }
  2308. }
  2309. // Blocks larger than the mixer buffers are done in pieces. With automation, small
  2310. // pieces so values move smoothly.
  2311. const auto chunk = std::min (blockCapacity, state->hasAutomation ? 128 : chunkCapacity);
  2312. for (int done = 0; done < numSamples;)
  2313. {
  2314. auto n = std::min (chunk, numSamples - done);
  2315. // pattern events take effect at their own sample, as in FL (REA_rodada85 §3): a chunk ends where one falls
  2316. if (playing && ! state->eventLanes.empty() && tps > 0.0)
  2317. {
  2318. const auto ahead = ticksToNextEvent (*state, startTick + done * tps);
  2319. if (ahead < (double) n * tps)
  2320. n = std::max (1, (int) std::ceil (ahead / tps - 1.0e-9));
  2321. }
  2322. liveInputOffset = done;
  2323. processChunk (*state, playing, startTick + done * tps, n, left + done, right + done, meters);
  2324. resumeAudio = false;
  2325. chaseNotes = false;
  2326. done += n;
  2327. }
  2328. publishSoundingKeys ((int) state->song.channels.size());
  2329. if (timing)
  2330. {
  2331. times->wallNs.fetch_add (ProcessTimes::now() - wallStart, std::memory_order_relaxed);
  2332. times->audioNs.fetch_add ((std::uint64_t) ((double) numSamples / sampleRate * 1.0e9), std::memory_order_relaxed);
  2333. }
  2334. }
  2335. void RackRenderer::publishSoundingKeys (int channels) noexcept
  2336. {
  2337. channels = std::clamp (channels, 0, maxChannels);
  2338. const auto top = std::max (channels, publishedTop);
  2339. publishedTop = 0;
  2340. for (int i = 0; i < top; ++i)
  2341. {
  2342. auto& was = publishedNotes[(std::size_t) i];
  2343. NoteMask now {};
  2344. if (i < channels)
  2345. {
  2346. const auto& held = heldNotes[(std::size_t) i];
  2347. auto& struck = struckNotes[(std::size_t) i];
  2348. now = { held[0] | struck[0], held[1] | struck[1] };
  2349. struck = {};
  2350. }
  2351. if (now[0] != 0 || now[1] != 0)
  2352. publishedTop = i + 1;
  2353. if (now == was)
  2354. continue;
  2355. was = now;
  2356. sounding[(std::size_t) i][0].store (now[0], std::memory_order_relaxed);
  2357. sounding[(std::size_t) i][1].store (now[1], std::memory_order_relaxed);
  2358. }
  2359. }
  2360. double RackRenderer::ticksToNextEvent (const RackState& state, double tick) noexcept
  2361. {
  2362. const auto& song = state.song;
  2363. auto best = std::numeric_limits<double>::infinity();
  2364. // first event tick of `events` strictly after `t` (events sorted by tick)
  2365. auto after = [] (const PatternEvents& events, double t) {
  2366. auto it = std::upper_bound (events.events.begin(), events.events.end(), t,
  2367. [] (double x, const PatternEvent& e) { return x < (double) e.tick; });
  2368. return it == events.events.end() ? std::numeric_limits<double>::infinity() : (double) it->tick;
  2369. };
  2370. if (song.mode != PlayMode::song)
  2371. {
  2372. const auto current = song.currentPattern;
  2373. if (current < 0 || current >= (int) song.patterns.size())
  2374. return best;
  2375. const auto& pattern = song.patterns[(std::size_t) current];
  2376. const auto length = (double) std::max<std::int64_t> (1, pattern.effectiveLength (song.beatsPerBar));
  2377. const auto t = std::fmod (std::max (0.0, tick), length);
  2378. for (const auto& lane : state.eventLanes)
  2379. if (lane.pattern == current)
  2380. {
  2381. const auto& events = pattern.events[(std::size_t) lane.lane];
  2382. best = std::min (best, after (events, t) - t);
  2383. if (! events.events.empty()) // the loop restarts at the first event's value
  2384. best = std::min (best, length - t);
  2385. }
  2386. return best;
  2387. }
  2388. const auto length = (double) std::max<std::int64_t> (1, state.schedule.songLength);
  2389. const auto t = std::fmod (std::max (0.0, tick), length);
  2390. for (const auto& lane : state.eventLanes)
  2391. {
  2392. const auto& events = song.patterns[(std::size_t) lane.pattern].events[(std::size_t) lane.lane];
  2393. for (auto i : state.patternClips[(std::size_t) lane.pattern])
  2394. {
  2395. const auto& c = song.playlist[(std::size_t) i];
  2396. if ((double) c.end() <= t)
  2397. continue;
  2398. if ((double) c.start > t)
  2399. {
  2400. best = std::min (best, (double) c.start - t);
  2401. break;
  2402. }
  2403. const auto period = (std::size_t) lane.pattern < state.schedule.patternLength.size() ? state.schedule.patternLength[(std::size_t) lane.pattern] : 0;
  2404. const auto local = patternTickInClip (c, t, period);
  2405. auto ahead = after (events, local) - local;
  2406. if (stretchedClipsLoop() && period > 0 && c.offset + c.length > period) // the next pass restarts at the first event's value
  2407. ahead = std::min (ahead, (double) period - local);
  2408. best = std::min (best, std::min (t + ahead, (double) c.end()) - t);
  2409. }
  2410. }
  2411. return best;
  2412. }
  2413. void RackRenderer::applyLiveControl (const RackState& state, const NoteEvent& e) noexcept
  2414. {
  2415. // a controller's pitch wheel, mod wheel (CC 1), other CCs and channel pressure played into a channel (round 162,
  2416. // issue #9): hosted plugins (and the SoundFont player) get the MIDI message; LYNX's own instruments bend by the
  2417. // channel's pitch range (FL's Misc › Pitch range, default ±2 semitones) and take the CCs they know
  2418. auto* instrument = state.instruments[(std::size_t) e.channel].get();
  2419. if (instrument == nullptr)
  2420. return;
  2421. std::uint8_t m[3] {};
  2422. auto size = 3;
  2423. const auto value = std::isfinite (e.velocity) ? e.velocity : 0.0f;
  2424. if (e.key == NoteEvent::controlPitchBend)
  2425. {
  2426. const auto v = (int) std::clamp (std::lround ((double) (value + 1.0f) * 8192.0), 0L, 16383L);
  2427. m[0] = 0xE0, m[1] = (std::uint8_t) (v & 127), m[2] = (std::uint8_t) (v >> 7);
  2428. }
  2429. else if (e.key == NoteEvent::controlPressure)
  2430. {
  2431. m[0] = 0xD0, m[1] = (std::uint8_t) std::clamp (std::lround (value * 127.0f), 0L, 127L);
  2432. size = 2;
  2433. }
  2434. else if (e.key == NoteEvent::controlProgram) // (round 165c: a VFX Sequencer selects its sequence, plugins their preset)
  2435. {
  2436. m[0] = 0xC0, m[1] = (std::uint8_t) std::clamp (std::lround (value * 127.0f), 0L, 127L);
  2437. size = 2;
  2438. }
  2439. else if (e.key >= 0 && e.key < 128)
  2440. m[0] = 0xB0, m[1] = (std::uint8_t) e.key, m[2] = (std::uint8_t) std::clamp (std::lround (value * 127.0f), 0L, 127L);
  2441. else
  2442. return;
  2443. instrument->midiMessage (m, size);
  2444. if (e.key == NoteEvent::controlPitchBend)
  2445. {
  2446. const auto range = (std::size_t) e.channel < state.song.channels.size() ? state.song.channels[(std::size_t) e.channel].misc.pitchRange : 2;
  2447. instrument->pitchBend (std::clamp (value, -1.0f, 1.0f) * (float) std::max (0, range));
  2448. }
  2449. else if (e.key < 128)
  2450. instrument->controlChange (e.key, std::clamp (value, 0.0f, 1.0f));
  2451. // a MIDI Out channel: the plugins on its port get it on its MIDI channel
  2452. if (state.hasMidiRoutes && (std::size_t) e.channel < state.midiTargets.size())
  2453. for (const auto t : state.midiTargets[(std::size_t) e.channel])
  2454. if (t >= 0 && t < (int) state.instruments.size() && state.instruments[(std::size_t) t] != nullptr)
  2455. {
  2456. std::uint8_t routed[3] { (std::uint8_t) ((m[0] & 0xF0) | (state.midiOutChannel[(std::size_t) e.channel] & 15)), m[1], m[2] };
  2457. state.instruments[(std::size_t) t]->midiMessage (routed, size);
  2458. }
  2459. }
  2460. void RackRenderer::expandLayers (const RackState& state) noexcept
  2461. {
  2462. const auto& channels = state.song.channels;
  2463. const auto count = events.size();
  2464. auto added = false;
  2465. for (int i = 0; i < count; ++i)
  2466. {
  2467. const auto e = events[i];
  2468. if (e.channel < 0 || e.channel >= (int) channels.size() || e.channel >= maxChannels)
  2469. continue;
  2470. const auto& l = channels[(std::size_t) e.channel];
  2471. if (l.instrument != InstrumentKind::layer || l.layer.children.empty())
  2472. continue;
  2473. const auto key = std::clamp (e.key, 0, 127);
  2474. auto* picked = layerPick.empty() ? nullptr : &layerPick[(std::size_t) e.channel * 128 + (std::size_t) key];
  2475. auto child = e;
  2476. child.pan = std::clamp (e.pan + l.pan, -1.0f, 1.0f);
  2477. child.cents = e.cents + layer::pitchCents (l);
  2478. const auto one = l.layer.random || l.layer.sequential;
  2479. if (e.type == NoteEvent::Type::on)
  2480. {
  2481. if (l.muted)
  2482. continue;
  2483. std::array<layer::Pick, 64> picks;
  2484. const auto n = layer::pick (l, channels, key, layerRandom, layerTurn[(std::size_t) e.channel], picks.data(), (int) picks.size());
  2485. if (one && picked != nullptr)
  2486. *picked = (std::int16_t) (n > 0 ? picks[0].child : -1);
  2487. const auto level = layer::levelGain (l);
  2488. for (int k = 0; k < n; ++k)
  2489. {
  2490. child.channel = picks[(std::size_t) k].child;
  2491. child.gain = e.gain * level * picks[(std::size_t) k].gain;
  2492. events.add (child);
  2493. added = true;
  2494. }
  2495. }
  2496. else if (e.type == NoteEvent::Type::off && one)
  2497. {
  2498. if (picked != nullptr && *picked >= 0)
  2499. {
  2500. child.channel = *picked;
  2501. *picked = -1;
  2502. events.add (child);
  2503. added = true;
  2504. }
  2505. }
  2506. else if (e.type == NoteEvent::Type::off || e.type == NoteEvent::Type::slide || e.type == NoteEvent::Type::choke)
  2507. for (const auto c : l.layer.children)
  2508. if (c >= 0 && c < (int) channels.size() && c != e.channel && channels[(std::size_t) c].instrument != InstrumentKind::layer)
  2509. {
  2510. child.channel = c;
  2511. events.add (child);
  2512. added = true;
  2513. }
  2514. }
  2515. if (added)
  2516. events.sortByOffset();
  2517. }
  2518. bool RackRenderer::routesLiveNotes (const RackState& state, int channel) const noexcept
  2519. {
  2520. const auto c = (std::size_t) channel;
  2521. if (channel < 0 || c >= state.song.channels.size())
  2522. return false;
  2523. if (state.song.channels[c].instrument == InstrumentKind::layer) // (its children play the note: round 164)
  2524. return true;
  2525. const auto& misc = state.song.channels[c].misc;
  2526. return (c < state.arpeggiators.size() && state.arpeggiators[c] != nullptr) || (c < state.echoes.size() && state.echoes[c] != nullptr)
  2527. || misc.key.pan != 0.0f || misc.velocity.pan != 0.0f
  2528. || (misc.addToKey && misc.rootNote != 60 && state.song.channels[c].instrument != InstrumentKind::sampler)
  2529. || (c < state.vfxPort.size() && state.vfxPort[c] >= 0); // (a VFX channel's processor takes them in the chunk)
  2530. }
  2531. void RackRenderer::runVfxChannels (const RackState& state, bool playing, int numSamples) noexcept
  2532. {
  2533. vfx::Transport transport;
  2534. transport.sampleRate = sampleRate;
  2535. transport.bpm = chunkTps * sampleRate * 60.0 / (double) ppq; // (the tempo at this chunk)
  2536. transport.ticks = chunkStartTick; // (stopped: the live clock, as the arpeggiator)
  2537. transport.playing = playing;
  2538. for (const auto c : state.vfxChannels)
  2539. {
  2540. if ((std::size_t) c >= state.instruments.size() || state.instruments[(std::size_t) c] == nullptr)
  2541. continue;
  2542. auto* processor = state.instruments[(std::size_t) c]->noteProcessor();
  2543. if (processor == nullptr)
  2544. continue;
  2545. vfxIn->clear();
  2546. vfxOut->clear();
  2547. const auto count = events.size();
  2548. for (int k = 0; k < count; ++k)
  2549. {
  2550. auto& e = events.at (k);
  2551. if (e.channel != c || e.port != -1)
  2552. continue;
  2553. if (e.type == NoteEvent::Type::on || e.type == NoteEvent::Type::off)
  2554. {
  2555. vfx::Event in;
  2556. in.type = e.type == NoteEvent::Type::on ? vfx::Event::Type::on : vfx::Event::Type::off;
  2557. in.offset = e.sampleOffset;
  2558. in.voice.key = e.key;
  2559. in.voice.velocity = e.velocity;
  2560. in.voice.pan = e.pan;
  2561. in.voice.cents = e.cents;
  2562. in.voice.modX = e.modX;
  2563. in.voice.modY = e.modY;
  2564. in.voice.release = e.release;
  2565. in.voice.colour = e.colour & 15;
  2566. in.voice.porta = e.porta;
  2567. in.id = vfx::inputId (e.key, in.voice.colour);
  2568. vfxIn->add (in);
  2569. }
  2570. e.port = -2; // (taken by the processor)
  2571. }
  2572. processor->process (vfxIn->size() > 0 ? &(*vfxIn)[0] : nullptr, vfxIn->size(), numSamples, transport, *vfxOut);
  2573. const auto port = state.vfxPort[(std::size_t) c];
  2574. for (int k = 0; k < vfxOut->size(); ++k)
  2575. {
  2576. const auto& o = (*vfxOut)[k];
  2577. if (o.type == vfx::Event::Type::program) // (a VFX Sequencer passing a program change on: the plugins on its port)
  2578. {
  2579. if ((std::size_t) c < state.midiTargets.size())
  2580. for (const auto t : state.midiTargets[(std::size_t) c])
  2581. if (t >= 0 && t < (int) state.instruments.size() && state.instruments[(std::size_t) t] != nullptr)
  2582. {
  2583. const std::uint8_t m[2] { 0xC0, (std::uint8_t) std::clamp ((int) o.value, 0, 127) };
  2584. state.instruments[(std::size_t) t]->midiMessage (m, 2);
  2585. }
  2586. continue;
  2587. }
  2588. if (port + o.output >= patchMidiPorts)
  2589. continue;
  2590. NoteEvent e;
  2591. e.type = o.type == vfx::Event::Type::on ? NoteEvent::Type::on : o.type == vfx::Event::Type::off ? NoteEvent::Type::off : NoteEvent::Type::voiceProp;
  2592. e.prop = (std::uint8_t) o.prop;
  2593. if (e.type == NoteEvent::Type::voiceProp) // (round 165c: the voice's property over time, on its port too)
  2594. {
  2595. e.velocity = o.value;
  2596. e.channel = c;
  2597. e.sampleOffset = std::clamp (o.offset, 0, std::max (0, numSamples - 1));
  2598. e.key = o.voice.key;
  2599. e.colour = (std::int8_t) (o.voice.colour & 15);
  2600. e.port = (std::int16_t) (port + o.output);
  2601. events.add (e);
  2602. continue;
  2603. }
  2604. e.channel = c;
  2605. e.sampleOffset = std::clamp (o.offset, 0, std::max (0, numSamples - 1));
  2606. e.key = o.voice.key;
  2607. e.velocity = o.voice.velocity;
  2608. e.pan = o.voice.pan;
  2609. e.cents = o.voice.cents;
  2610. e.modX = o.voice.modX;
  2611. e.modY = o.voice.modY;
  2612. e.release = o.voice.release;
  2613. e.colour = (std::int8_t) (o.voice.colour & 15);
  2614. e.porta = o.voice.porta;
  2615. e.port = (std::int16_t) (port + o.output);
  2616. events.add (e);
  2617. }
  2618. }
  2619. events.sortByOffset();
  2620. }
  2621. void RackRenderer::processChunk (const RackState& state, bool playing, double startTick, int numSamples,
  2622. float* left, float* right, MeterBank* meters) noexcept
  2623. {
  2624. chunkTick = startTick;
  2625. chunkPlaying = playing;
  2626. updatePdcBypass (state, playing);
  2627. const auto& song = state.song;
  2628. const auto tracks = std::max<int> (1, (int) song.mixer.size());
  2629. if (state.hasAutomation) // (a hair later: a chunk that starts on a pattern event's sample takes its value)
  2630. updateAutomation (state, startTick + 1.0e-6);
  2631. chunkTps = ticksPerSample (bpm, sampleRate);
  2632. chunkStartTick = playing ? startTick : liveTick; // stopped: live notes' arpeggios run on their own clock
  2633. if (! playing)
  2634. liveTick += numSamples * chunkTps;
  2635. // hosted plugins read the transport from here (PluginHost's play head)
  2636. {
  2637. auto& timeline = hostTimeline();
  2638. timeline.tick.store (hostPositionTick (song, startTick, state.schedule.songLength), std::memory_order_relaxed);
  2639. timeline.bpm.store (bpm, std::memory_order_relaxed);
  2640. timeline.sampleRate.store (sampleRate, std::memory_order_relaxed);
  2641. timeline.beatsPerBar.store (std::max (1, song.beatsPerBar), std::memory_order_relaxed);
  2642. timeline.playing.store (playing, std::memory_order_relaxed);
  2643. timeline.looping.store (song.hasLoop(), std::memory_order_relaxed);
  2644. timeline.loopStart.store ((double) song.loopStart, std::memory_order_relaxed);
  2645. timeline.loopEnd.store ((double) song.loopEnd, std::memory_order_relaxed);
  2646. }
  2647. for (int t = 0; t < tracks; ++t)
  2648. {
  2649. std::memset (trackBuffer (t, 0), 0, sizeof (float) * (std::size_t) numSamples);
  2650. std::memset (trackBuffer (t, 1), 0, sizeof (float) * (std::size_t) numSamples);
  2651. }
  2652. events.clear();
  2653. const auto songPlaying = playing && song.mode == PlayMode::song;
  2654. if (songPlaying)
  2655. {
  2656. scheduleSong (song, startTick, numSamples, ticksPerSample (bpm, sampleRate), events, resumeAudio, &state.schedule,
  2657. liveInput == nullptr || ! liveInput->linearSong.load (std::memory_order_relaxed), chaseNotes);
  2658. }
  2659. // Performance mode (round 165m): the launched clips, on the Player's steady clock (the transport's ticks from
  2660. // where playback started, never wrapping with the song loop)
  2661. if (songPlaying && (! state.performanceZone.empty() || perfRunning))
  2662. {
  2663. if (! perfRunning)
  2664. perfClock = startTick;
  2665. perfRunning = true;
  2666. const auto tps = ticksPerSample (bpm, sampleRate);
  2667. perfPlayer.process (song, state.performanceZone, perfLive, perfClock, startTick, numSamples * tps, true);
  2668. schedulePerformance (song, perfPlayer, perfClock, numSamples, tps, events, &state.schedule);
  2669. perfClock += numSamples * tps;
  2670. }
  2671. else if (perfRunning || (perfLive != nullptr && perfLive->anyPlaying.load (std::memory_order_relaxed)))
  2672. {
  2673. perfPlayer.process (song, state.performanceZone, perfLive, perfClock, startTick, 0.0, false);
  2674. perfRunning = false;
  2675. }
  2676. else if (perfLive != nullptr)
  2677. {
  2678. perf::Command c;
  2679. while (perfLive->commands.pop (c)) {} // nothing launches while stopped or in Pattern mode
  2680. }
  2681. if (! songPlaying && playing && ! song.patterns.empty())
  2682. {
  2683. const auto patternIndex = std::clamp (song.currentPattern, 0, (int) song.patterns.size() - 1);
  2684. const auto& pattern = song.patterns[(std::size_t) patternIndex];
  2685. schedulePatternLoop (pattern, pattern.effectiveLength (song.beatsPerBar), startTick, numSamples,
  2686. ticksPerSample (bpm, sampleRate), events, song.swing, &song.channels, chaseNotes);
  2687. }
  2688. // FL's wrapper "Output port" (round 149): the notes a plugin sent out in the previous chunk play the plugins on
  2689. // that port, at this chunk's start
  2690. if (state.hasMidiOutputs)
  2691. {
  2692. std::array<Instrument::MidiOutNote, 128> notes;
  2693. for (std::size_t c = 0; c < state.midiOutTargets.size() && c < state.instruments.size(); ++c)
  2694. {
  2695. if (state.midiOutTargets[c].empty())
  2696. continue;
  2697. const auto count = state.instruments[c]->takeMidiOutput (notes.data(), (int) notes.size());
  2698. for (int k = 0; k < count; ++k)
  2699. for (const auto t : state.midiOutTargets[c])
  2700. {
  2701. NoteEvent e;
  2702. e.type = notes[(std::size_t) k].velocity > 0.0f ? NoteEvent::Type::on : NoteEvent::Type::off;
  2703. e.channel = t;
  2704. e.key = notes[(std::size_t) k].key;
  2705. e.velocity = notes[(std::size_t) k].velocity;
  2706. e.sampleOffset = 0;
  2707. events.add (e);
  2708. }
  2709. }
  2710. events.sortByOffset();
  2711. }
  2712. // generator Patchers' VFX nodes cabled to "To LYNX" MIDI ports (round 165c): what they played in the previous
  2713. // chunk goes out on those ports at this chunk's start (as a VFX channel's outputs do)
  2714. if (! state.portEventChannels.empty())
  2715. {
  2716. std::array<Instrument::PortEvent, 128> sent;
  2717. auto added = false;
  2718. for (const auto c : state.portEventChannels)
  2719. {
  2720. if ((std::size_t) c >= state.instruments.size() || state.instruments[(std::size_t) c] == nullptr)
  2721. continue;
  2722. const auto count = state.instruments[(std::size_t) c]->takePortEvents (sent.data(), (int) sent.size());
  2723. for (int k = 0; k < count; ++k)
  2724. {
  2725. const auto& p = sent[(std::size_t) k];
  2726. NoteEvent e;
  2727. e.type = p.prop >= 0 ? NoteEvent::Type::voiceProp : p.value > 0.0f ? NoteEvent::Type::on : NoteEvent::Type::off;
  2728. e.channel = c;
  2729. e.key = p.key;
  2730. e.velocity = p.value;
  2731. e.prop = (std::uint8_t) std::max (0, p.prop);
  2732. e.pan = p.pan;
  2733. e.cents = p.cents;
  2734. e.modX = p.modX;
  2735. e.modY = p.modY;
  2736. e.release = p.release;
  2737. e.colour = (std::int8_t) (p.channel & 15);
  2738. e.port = (std::int16_t) p.port;
  2739. events.add (e);
  2740. added = true;
  2741. }
  2742. }
  2743. if (added)
  2744. events.sortByOffset();
  2745. }
  2746. // Dashboards (round 165, FL's Dashboard): the MIDI their controls and patch send reaches the plugins on their port
  2747. for (const auto c : state.dashboardChannels)
  2748. {
  2749. if ((std::size_t) c >= state.instruments.size() || state.instruments[(std::size_t) c] == nullptr)
  2750. continue;
  2751. std::array<std::uint32_t, midiout::maxResetMessages + 8> sent; // (a MIDI Out's reset: every active control at once)
  2752. const auto count = state.instruments[(std::size_t) c]->takeMidiMessages (sent.data(), (int) sent.size());
  2753. if (count <= 0 || (std::size_t) c >= state.midiTargets.size())
  2754. continue;
  2755. for (int k = 0; k < count; ++k)
  2756. {
  2757. const auto m = sent[(std::size_t) k];
  2758. const std::uint8_t bytes[3] { (std::uint8_t) (m & 0xff), (std::uint8_t) ((m >> 8) & 127), (std::uint8_t) ((m >> 16) & 127) };
  2759. const auto size = (bytes[0] & 0xE0) == 0xC0 ? 2 : 3; // (program change, channel pressure: one data byte)
  2760. for (const auto t : state.midiTargets[(std::size_t) c])
  2761. if (t >= 0 && t < (int) state.instruments.size() && state.instruments[(std::size_t) t] != nullptr)
  2762. state.instruments[(std::size_t) t]->midiMessage (bytes, size);
  2763. }
  2764. }
  2765. // live-played notes routed through their channel's note path (round 149)
  2766. if (liveRoutedCount > 0)
  2767. {
  2768. for (int k = 0; k < liveRoutedCount; ++k)
  2769. events.add (liveRouted[(std::size_t) k]);
  2770. liveRoutedCount = 0;
  2771. events.sortByOffset();
  2772. }
  2773. // Layer channels play their children (round 164)
  2774. if (state.hasLayers)
  2775. expandLayers (state);
  2776. // VFX channels (round 164b): their processors turn their notes into what they send on their ports
  2777. if (! state.vfxChannels.empty())
  2778. runVfxChannels (state, playing, numSamples);
  2779. // cut groups: each note of a channel "cuts" the channels linked to it, at the same sample
  2780. if (state.hasCutGroups)
  2781. {
  2782. const auto count = events.size();
  2783. for (int i = 0; i < count; ++i)
  2784. {
  2785. const auto e = events[i];
  2786. if (e.type != NoteEvent::Type::on || e.channel < 0 || e.channel >= (int) state.cutTargets.size())
  2787. continue;
  2788. for (auto target : state.cutTargets[(std::size_t) e.channel])
  2789. {
  2790. NoteEvent choke;
  2791. choke.type = NoteEvent::Type::choke;
  2792. choke.channel = target;
  2793. choke.sampleOffset = e.sampleOffset;
  2794. events.add (choke);
  2795. }
  2796. }
  2797. events.sortByOffset();
  2798. }
  2799. // MIDI to the mixer-slot Patchers that take a MIDI port (round 162): at its sample (round 164f)
  2800. if (state.hasEffectMidiRoutes)
  2801. for (int k = 0; k < events.size(); ++k)
  2802. deliverToEffects (state, events[k]);
  2803. // 1) channels, each with its own notes at the exact sample (in parallel when worth it)
  2804. const auto channels = std::min<int> ({ (int) state.instruments.size(), (int) song.channels.size(), maxChannels });
  2805. auto channel = [this, &state, numSamples] (int c) {
  2806. if (! times->enabled.load (std::memory_order_relaxed) || c >= ProcessTimes::channels)
  2807. {
  2808. renderChannel (state, c, numSamples);
  2809. return;
  2810. }
  2811. const auto before = ProcessTimes::now();
  2812. renderChannel (state, c, numSamples);
  2813. times->channelNs[(std::size_t) c].fetch_add (ProcessTimes::now() - before, std::memory_order_relaxed);
  2814. };
  2815. // the task graph (round 165i): channels and inserts by readiness; else the channel pass, then the inserts by layers
  2816. if (! runTaskGraph (state, playing, channels, numSamples, meters))
  2817. {
  2818. if (workers != nullptr && state.parallel && state.audioThreadChannels.empty())
  2819. workers->parallelFor (channels, channel);
  2820. else if (workers != nullptr && state.parallel)
  2821. {
  2822. // "Allow threaded processing" off: those channels on this thread, the rest in parallel
  2823. auto threaded = [&state, &channel, channels] (int i) {
  2824. if (const auto c = state.threadedChannels[(std::size_t) i]; c < channels)
  2825. channel (c);
  2826. };
  2827. workers->parallelFor ((int) state.threadedChannels.size(), threaded);
  2828. for (const auto c : state.audioThreadChannels)
  2829. if (c < channels)
  2830. channel (c);
  2831. }
  2832. else
  2833. for (int c = 0; c < channels; ++c)
  2834. channel (c);
  2835. for (int c = 0; c < channels; ++c)
  2836. {
  2837. if (channelSilent[(std::size_t) c])
  2838. continue;
  2839. const auto t = std::clamp (song.channels[(std::size_t) c].mixerTrack, 0, tracks - 1);
  2840. auto* dl = trackBuffer (t, 0);
  2841. auto* dr = trackBuffer (t, 1);
  2842. const auto* sl = channelBuffer (c, 0);
  2843. const auto* sr = channelBuffer (c, 1);
  2844. for (int k = 0; k < numSamples; ++k)
  2845. {
  2846. dl[k] += sl[k];
  2847. dr[k] += sr[k];
  2848. }
  2849. // extra outputs to other inserts (a generator Patcher's, REA_rodada141)
  2850. if ((std::size_t) c < state.instruments.size() && state.instruments[(std::size_t) c] != nullptr)
  2851. {
  2852. const auto& instrument = *state.instruments[(std::size_t) c];
  2853. for (int k = 0; k < instrument.auxOutputCount(); ++k)
  2854. {
  2855. const auto target = instrument.auxOutputTrack (k);
  2856. const auto* al = instrument.auxOutputData (k, 0);
  2857. const auto* ar = instrument.auxOutputData (k, 1);
  2858. if (target < 0 || target >= tracks || al == nullptr || ar == nullptr)
  2859. continue;
  2860. auto* tl = trackBuffer (target, 0);
  2861. auto* tr = trackBuffer (target, 1);
  2862. for (int x = 0; x < numSamples; ++x)
  2863. {
  2864. tl[x] += al[x];
  2865. tr[x] += ar[x];
  2866. }
  2867. }
  2868. }
  2869. }
  2870. if (liveInput != nullptr && liveInput->numChannels > 0)
  2871. mixLiveInput (state, playing, numSamples);
  2872. mixMetronome (state, metronomeTarget (state), numSamples);
  2873. // 2) inserts by layers: within a layer nothing depends on anything else; each track pulls the
  2874. // outputs of the tracks that send to it (without writing into others' buffers)
  2875. trackActive.fill (0);
  2876. tapActive.fill (0);
  2877. for (std::size_t d = 0; d < state.mixerLayers.size(); ++d)
  2878. {
  2879. const auto split = d < state.audioThreadLayers.size() && ! state.audioThreadLayers[d].empty();
  2880. const auto& layer = split ? state.threadedLayers[d] : state.mixerLayers[d];
  2881. auto track = [this, &state, &layer, numSamples, meters] (int i) { processTrack (state, layer[(std::size_t) i], numSamples, meters); };
  2882. if (workers != nullptr && state.parallel && layer.size() > 1)
  2883. workers->parallelFor ((int) layer.size(), track);
  2884. else
  2885. for (int i = 0; i < (int) layer.size(); ++i)
  2886. track (i);
  2887. if (split) // inserts with a plugin whose "Allow threaded processing" is off
  2888. for (const auto t : state.audioThreadLayers[d])
  2889. processTrack (state, t, numSamples, meters);
  2890. }
  2891. }
  2892. // 3) Master: inputs, effects, fader. Without a configured mixer, it stays at 0 dB.
  2893. pullInputs (state, 0, numSamples);
  2894. runEffects (state, 0, numSamples);
  2895. if (! song.mixer.empty())
  2896. {
  2897. applyTrackEq (song.mixer[0], 0, song.cleanMixer, trackBuffer (0, 0), trackBuffer (0, 1), numSamples);
  2898. }
  2899. MixerMatrix target; // without a mixer: unity
  2900. if (! song.mixer.empty())
  2901. {
  2902. const auto& master = song.mixer[0];
  2903. const auto volume = state.hasAutomation ? automated (state.mixerVolumeAuto[0], master.volume) : master.volume;
  2904. const auto pan = state.hasAutomation ? automated (state.mixerPanAuto[0], (master.pan + 1.0f) * 0.5f) * 2.0f - 1.0f : master.pan;
  2905. target = master.muted ? MixerMatrix { 0.0f, 0.0f, 0.0f, 0.0f } : mixerMatrix (master, volume, pan, song.panTriangular);
  2906. }
  2907. lastTrackGain[0] = applyMatrix (trackBuffer (0, 0), trackBuffer (0, 1), left, right, numSamples, lastTrackGain[0], target);
  2908. if (meters != nullptr)
  2909. {
  2910. meters->accumulate (0, peakOf (left, numSamples), peakOf (right, numSamples));
  2911. meters->capture.push (0, left, right, numSamples);
  2912. meters->logTap.push (0, left, right, numSamples);
  2913. if (chunkPlaying)
  2914. meters->bounceTap.push (0, left, right, numSamples);
  2915. }
  2916. if (hwOut != nullptr && ! state.hwRoutes.empty() && hwOut->active.load (std::memory_order_relaxed))
  2917. mixHardwareOutputs (state, numSamples);
  2918. }
  2919. // 4) inserts with a hardware output target: their post-fader output (the same signal the Master gets) into the
  2920. // device-channel buses, delayed like the Master's path
  2921. void RackRenderer::mixHardwareOutputs (const RackState& state, int n) noexcept
  2922. {
  2923. auto* sl = hwScratch.data();
  2924. auto* sr = hwScratch.data() + blockCapacity;
  2925. for (const auto& route : state.hwRoutes)
  2926. {
  2927. const auto t = route.track;
  2928. if (t <= 0 || t >= maxMixerTracks)
  2929. continue;
  2930. const float* l = trackActive[(std::size_t) t] ? trackBuffer (t, 0) : nullptr;
  2931. const float* r = trackActive[(std::size_t) t] ? trackBuffer (t, 1) : nullptr;
  2932. const auto bypassed = pdcBypassNow && (std::size_t) t < state.bypassWhenIdle.size() && state.bypassWhenIdle[(std::size_t) t] != 0;
  2933. if (route.delay != nullptr && ! bypassed)
  2934. {
  2935. if (l != nullptr)
  2936. {
  2937. std::copy (l, l + n, sl);
  2938. std::copy (r, r + n, sr);
  2939. }
  2940. else
  2941. {
  2942. std::fill (sl, sl + n, 0.0f);
  2943. std::fill (sr, sr + n, 0.0f);
  2944. }
  2945. route.delay->process (sl, sr, n);
  2946. l = sl;
  2947. r = sr;
  2948. }
  2949. if (l == nullptr)
  2950. continue;
  2951. const auto [first, count] = outputChannelsOf (route.channel, route.mode);
  2952. auto* a = hwOut->bus (first, liveInputOffset, n);
  2953. auto* b = count > 1 ? hwOut->bus (first + 1, liveInputOffset, n) : nullptr;
  2954. addToOutput (l, r, route.mode, a, b, n);
  2955. }
  2956. }
  2957. void RackRenderer::mixLiveInput (const RackState& state, bool playing, int n) noexcept
  2958. {
  2959. const auto recording = liveInput->recording.load (std::memory_order_relaxed);
  2960. // the Master too (FL's slot panel has its audio input selector; REA round 143): it plays whenever its
  2961. // monitoring is not off (it has no record arm)
  2962. for (int t = 0; t < (int) state.song.mixer.size() && t < maxMixerTracks; ++t)
  2963. mixLiveInputTrack (state, t, recording, playing, n);
  2964. }
  2965. void RackRenderer::mixLiveInputTrack (const RackState& state, int t, bool recording, bool playing, int n) noexcept
  2966. {
  2967. if (t >= (int) state.song.mixer.size() || t >= maxMixerTracks)
  2968. return;
  2969. const auto& track = state.song.mixer[(std::size_t) t];
  2970. const auto [first, count] = inputChannelsOf (track, liveInput->numChannels);
  2971. if (count == 0)
  2972. return;
  2973. const auto* a = liveInput->channel (first, liveInputOffset);
  2974. const auto* b = count > 1 ? liveInput->channel (first + 1, liveInputOffset) : a;
  2975. if (a == nullptr || b == nullptr)
  2976. return;
  2977. liveInput->meters.accumulate (t, peakOf (a, n), peakOf (b, n));
  2978. if (t == 0 ? track.monitor == InputMonitor::off
  2979. : ! inputMonitored (track.monitor, liveInput->armed[(std::size_t) t].load (std::memory_order_relaxed), playing, recording))
  2980. return;
  2981. auto* dl = trackBuffer (t, 0);
  2982. auto* dr = trackBuffer (t, 1);
  2983. for (int i = 0; i < n; ++i)
  2984. {
  2985. dl[i] += a[i];
  2986. dr[i] += b[i];
  2987. }
  2988. }
  2989. void RackRenderer::sumChannelsInto (const RackState& state, int t, int channels, int n) noexcept
  2990. {
  2991. if ((std::size_t) t >= state.trackChannels.size())
  2992. return;
  2993. auto* dl = trackBuffer (t, 0);
  2994. auto* dr = trackBuffer (t, 1);
  2995. for (const auto c : state.trackChannels[(std::size_t) t])
  2996. {
  2997. if (c >= channels || channelSilent[(std::size_t) c])
  2998. continue;
  2999. const auto* sl = channelBuffer (c, 0);
  3000. const auto* sr = channelBuffer (c, 1);
  3001. for (int k = 0; k < n; ++k)
  3002. {
  3003. dl[k] += sl[k];
  3004. dr[k] += sr[k];
  3005. }
  3006. }
  3007. }
  3008. // FL's FUN_012c19f0: "When recording or not playing" bypasses while the transport is stopped or recording. Back to
  3009. // compensated, those tracks' lines are emptied: they start from silence instead of replaying what they held.
  3010. void RackRenderer::updatePdcBypass (const RackState& state, bool playing) noexcept
  3011. {
  3012. const auto recording = liveInput != nullptr && liveInput->recording.load (std::memory_order_relaxed);
  3013. pdcBypassNow = state.anyBypassWhenIdle && (! playing || recording);
  3014. if (pdcBypassBefore && ! pdcBypassNow)
  3015. {
  3016. for (std::size_t t = 0; t < state.bypassWhenIdle.size() && t < state.sendDelays.size(); ++t)
  3017. if (state.bypassWhenIdle[t] != 0)
  3018. {
  3019. const auto plain = std::min (state.sendDelays[t].size(), 1 + state.song.mixer[t].sends.size()); // not the Fruity Send taps
  3020. for (std::size_t k = 0; k < plain; ++k)
  3021. if (state.sendDelays[t][k] != nullptr)
  3022. state.sendDelays[t][k]->clear();
  3023. }
  3024. for (const auto& route : state.hwRoutes)
  3025. if (route.delay != nullptr && (std::size_t) route.track < state.bypassWhenIdle.size() && state.bypassWhenIdle[(std::size_t) route.track] != 0)
  3026. route.delay->clear();
  3027. }
  3028. pdcBypassBefore = pdcBypassNow;
  3029. }
  3030. bool RackRenderer::runTaskGraph (const RackState& state, bool playing, int channels, int n, MeterBank* meters) noexcept
  3031. {
  3032. // LYNX_TASKGRAPH=0: the layers only (A/B measurements)
  3033. static const bool enabled = [] { const char* e = std::getenv ("LYNX_TASKGRAPH"); return e == nullptr || std::atoi (e) != 0; }();
  3034. if (! enabled || ! state.graphOk || workers == nullptr || ! state.parallel || state.graphChannels != channels)
  3035. return false;
  3036. const auto tracks = std::max<int> (1, (int) state.song.mixer.size());
  3037. const auto tasks = channels + tracks - 1;
  3038. if (tasks <= 0 || tasks > graphCapacity || (int) state.graphIndegree.size() != tasks)
  3039. return false;
  3040. // extra outputs of an instrument (a generator Patcher's) go to inserts known only now: the layers then
  3041. for (int c = 0; c < channels; ++c)
  3042. if (state.instruments[(std::size_t) c] != nullptr && state.instruments[(std::size_t) c]->auxOutputCount() > 0)
  3043. return false;
  3044. trackActive.fill (0);
  3045. tapActive.fill (0);
  3046. const auto live = liveInput != nullptr && liveInput->numChannels > 0;
  3047. const auto recording = live && liveInput->recording.load (std::memory_order_relaxed);
  3048. for (int i = 0; i < tasks; ++i)
  3049. {
  3050. graphPending[(std::size_t) i].store (state.graphIndegree[(std::size_t) i], std::memory_order_relaxed);
  3051. graphSlots[(std::size_t) i].store (0, std::memory_order_relaxed);
  3052. }
  3053. auto pushed = 0;
  3054. for (const auto r : state.graphRoots)
  3055. graphSlots[(std::size_t) pushed++].store (r + 1, std::memory_order_relaxed);
  3056. graphPushed.store (pushed, std::memory_order_release); // (the pool publishes its work after this: seq_cst)
  3057. const auto timing = times->enabled.load (std::memory_order_relaxed);
  3058. auto task = [&] (int position) {
  3059. int id;
  3060. for (int spins = 0; (id = graphSlots[(std::size_t) position].load (std::memory_order_acquire)) == 0; ++spins)
  3061. {
  3062. WorkerPool::relax();
  3063. if ((spins & 1023) == 1023)
  3064. std::this_thread::yield();
  3065. }
  3066. --id;
  3067. if (id < channels)
  3068. {
  3069. if (! timing || id >= ProcessTimes::channels)
  3070. renderChannel (state, id, n);
  3071. else
  3072. {
  3073. const auto before = ProcessTimes::now();
  3074. renderChannel (state, id, n);
  3075. times->channelNs[(std::size_t) id].fetch_add (ProcessTimes::now() - before, std::memory_order_relaxed);
  3076. }
  3077. }
  3078. else
  3079. {
  3080. const auto t = id - channels + 1;
  3081. sumChannelsInto (state, t, channels, n);
  3082. if (live)
  3083. mixLiveInputTrack (state, t, recording, playing, n);
  3084. mixMetronome (state, t, n);
  3085. processTrack (state, t, n, meters);
  3086. }
  3087. for (auto k = state.graphNextStart[(std::size_t) id]; k < state.graphNextStart[(std::size_t) id + 1]; ++k)
  3088. {
  3089. const auto j = state.graphNext[(std::size_t) k];
  3090. if (graphPending[(std::size_t) j].fetch_sub (1, std::memory_order_acq_rel) == 1)
  3091. graphSlots[(std::size_t) graphPushed.fetch_add (1, std::memory_order_acq_rel)].store (j + 1, std::memory_order_release);
  3092. }
  3093. };
  3094. workers->parallelFor (tasks, task);
  3095. // the Master's own channels and input (its effects run after, as before)
  3096. sumChannelsInto (state, 0, channels, n);
  3097. if (live)
  3098. mixLiveInputTrack (state, 0, recording, playing, n);
  3099. mixMetronome (state, 0, n);
  3100. return true;
  3101. }
  3102. int RackRenderer::metronomeTarget (const RackState& state) const noexcept
  3103. {
  3104. return metronome::targetTrack (clickTrack, std::min ((int) state.song.mixer.size(), maxMixerTracks));
  3105. }
  3106. // the metronome's click into its track's input (round 165z-a2); `track` is the one being filled, the click goes in
  3107. // only when it is the metronome's
  3108. void RackRenderer::mixMetronome (const RackState& state, int track, int n) noexcept
  3109. {
  3110. if (clickLeft == nullptr || state.song.mixer.empty() || track != metronomeTarget (state))
  3111. return;
  3112. auto* dl = trackBuffer (track, 0);
  3113. auto* dr = trackBuffer (track, 1);
  3114. const auto* a = clickLeft + liveInputOffset;
  3115. const auto* b = clickRight + liveInputOffset;
  3116. for (int i = 0; i < n; ++i)
  3117. {
  3118. dl[i] += a[i];
  3119. dr[i] += b[i];
  3120. }
  3121. }
  3122. void RackRenderer::pullInputs (const RackState& state, int t, int n) noexcept
  3123. {
  3124. if ((std::size_t) t >= state.mixerInputs.size())
  3125. return;
  3126. auto* dl = trackBuffer (t, 0);
  3127. auto* dr = trackBuffer (t, 1);
  3128. for (const auto& in : state.mixerInputs[(std::size_t) t])
  3129. {
  3130. const auto tap = in.tap >= 0 && in.tap < RackState::maxSendTaps ? in.tap : -1;
  3131. // an automated route level (fader curve, like the knob)
  3132. const auto automatedLevel = in.automation >= 0 ? automationValues[(std::size_t) in.automation] : std::numeric_limits<float>::quiet_NaN();
  3133. const auto level = std::isnan (automatedLevel) ? in.level : faderGain (automatedLevel);
  3134. const auto active = tap >= 0 ? tapActive[(std::size_t) tap] : trackActive[(std::size_t) in.source];
  3135. const auto& delays = state.sendDelays[(std::size_t) in.source];
  3136. auto* delay = (std::size_t) in.delay < delays.size() ? delays[(std::size_t) in.delay].get() : nullptr;
  3137. if (pdcBypassNow && tap < 0 && state.bypassWhenIdle[(std::size_t) in.source] != 0)
  3138. delay = nullptr; // FL's "When recording or not playing": no compensation now
  3139. auto* sl = tap >= 0 ? tapBuffer (tap, 0) : trackBuffer (in.source, 0);
  3140. auto* sr = tap >= 0 ? tapBuffer (tap, 1) : trackBuffer (in.source, 1);
  3141. if (delay != nullptr)
  3142. {
  3143. // PDC: this edge is shorter than the slowest one arriving here. A silent source
  3144. // still drains the tail that was in the line.
  3145. delay->mixInto (active ? sl : nullptr, active ? sr : nullptr, level, dl, dr, n);
  3146. continue;
  3147. }
  3148. if (! active)
  3149. continue;
  3150. for (int i = 0; i < n; ++i)
  3151. {
  3152. dl[i] += sl[i] * level;
  3153. dr[i] += sr[i] * level;
  3154. }
  3155. }
  3156. }
  3157. namespace
  3158. {
  3159. bool isSilentBlock (const float* l, const float* r, int n) noexcept
  3160. {
  3161. for (int i = 0; i < n; ++i)
  3162. if (l[i] != 0.0f || r[i] != 0.0f)
  3163. return false;
  3164. return true;
  3165. }
  3166. } // namespace
  3167. void RackRenderer::processTrack (const RackState& state, int t, int n, MeterBank* meters) noexcept
  3168. {
  3169. const auto& track = state.song.mixer[(std::size_t) t];
  3170. pullInputs (state, t, n);
  3171. // recording taps on this insert (round 168x, issue #41): FL's "Record" positions after the input
  3172. const auto taps = liveInput != nullptr && t > 0 ? liveInput->tappedPoints (t) : 0u;
  3173. auto tap = [&] (RecordSource point, const float* l, const float* r) {
  3174. if ((taps & (1u << (unsigned) point)) != 0)
  3175. liveInput->tap (t, point, l, r, liveInputOffset, n);
  3176. };
  3177. const auto silent = track.muted || ! state.mixerAudible[(std::size_t) t];
  3178. // target matrix; the ramp from the previous block avoids clicks on mute and fader
  3179. MixerMatrix target { 0.0f, 0.0f, 0.0f, 0.0f };
  3180. MixerMatrix level { 0.0f, 0.0f, 0.0f, 0.0f }; // the same without the mute (the "Post level and panning" tap)
  3181. if (! silent || (taps & (1u << (unsigned) RecordSource::postLevel)) != 0)
  3182. {
  3183. const auto volume = state.hasAutomation ? automated (state.mixerVolumeAuto[(std::size_t) t], track.volume) : track.volume;
  3184. const auto pan = state.hasAutomation ? automated (state.mixerPanAuto[(std::size_t) t], (track.pan + 1.0f) * 0.5f) * 2.0f - 1.0f
  3185. : track.pan;
  3186. level = mixerMatrix (track, volume, pan, state.song.panTriangular);
  3187. if (! silent)
  3188. target = level;
  3189. }
  3190. auto& last = lastTrackGain[(std::size_t) t];
  3191. const auto from = std::isnan (last.ll) ? target : last;
  3192. constexpr MixerMatrix zero { 0.0f, 0.0f, 0.0f, 0.0f };
  3193. auto* l = trackBuffer (t, 0);
  3194. auto* r = trackBuffer (t, 1);
  3195. if (silent && from == zero && taps == 0) // (a muted insert being recorded still runs its effects for the take)
  3196. {
  3197. if (meters != nullptr)
  3198. meters->capture.pushSilence (t, n);
  3199. return; // stays inactive: nobody pulls anything from it
  3200. }
  3201. tap (RecordSource::externalAndMixer, l, r);
  3202. // an idle insert (round 166d, up to 500 of them): no effects, no built-in EQ and nothing came in this block. Its
  3203. // output is silence whatever the fader does, so it stays inactive and the tracks it feeds skip it (the same
  3204. // samples: adding zeros changes nothing; a tap stays silent too)
  3205. if (track.effects.empty() && (state.song.cleanMixer || ! track.eq.active()) && isSilentBlock (l, r, n))
  3206. {
  3207. if (t < (int) trackEqs.size() && trackEqs[(std::size_t) t].running)
  3208. trackEqs[(std::size_t) t] = {};
  3209. last = target;
  3210. if (meters != nullptr)
  3211. meters->capture.pushSilence (t, n);
  3212. return;
  3213. }
  3214. runEffects (state, t, n);
  3215. tap (RecordSource::postEffects, l, r);
  3216. applyTrackEq (track, t, state.song.cleanMixer, l, r, n);
  3217. tap (RecordSource::postEq, l, r);
  3218. if ((taps & (1u << (unsigned) RecordSource::postLevel)) != 0)
  3219. if (const auto dest = liveInput->tapDestination (t, RecordSource::postLevel, liveInputOffset, n); dest.first != nullptr)
  3220. {
  3221. // the fader, pan and separation without the mute, with their own ramp
  3222. auto& lastLevel = lastTapGain[(std::size_t) t];
  3223. const auto fromLevel = std::isnan (lastLevel.ll) ? level : lastLevel;
  3224. lastLevel = applyMatrix (l, r, dest.first, dest.second, n, fromLevel, level);
  3225. }
  3226. last = applyMatrix (l, r, l, r, n, from, target);
  3227. tap (RecordSource::postTrack, l, r);
  3228. trackActive[(std::size_t) t] = 1;
  3229. if (meters != nullptr)
  3230. {
  3231. meters->accumulate (t, peakOf (l, n), peakOf (r, n));
  3232. meters->capture.push (t, l, r, n);
  3233. }
  3234. }
  3235. } // namespace lynx