Patcher.cpp 106 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527
  1. #include "core/Patcher.h"
  2. #include "core/LynxVerbs.h"
  3. #include "core/Rack.h"
  4. #include "core/ControlSurface.h"
  5. #include "core/VfxScript.h"
  6. #include "core/XyController.h"
  7. #include <algorithm>
  8. #include <chrono>
  9. #include <cctype>
  10. #include <cmath>
  11. #include <cstring>
  12. #include <limits>
  13. #include <map>
  14. #include <tuple>
  15. #include "core/FacetEq.h"
  16. #include "core/FlSynths.h"
  17. #include "core/FrequencySplitter.h"
  18. #include "core/HardwareInsert.h"
  19. #include "core/Layer.h"
  20. #include "core/MidiControls.h"
  21. #include "core/Pdc.h"
  22. namespace lynx::patcher
  23. {
  24. namespace
  25. {
  26. class PassEffect final : public Effect
  27. {
  28. public:
  29. void prepare (double) noexcept override {}
  30. void reset() noexcept override {}
  31. void process (float*, float*, int, const EffectParams&, double) noexcept override {}
  32. };
  33. // what makes a running node reusable: everything but the values the graph hands it every block
  34. bool sameEffectSetup (const EffectSlot& a, const EffectSlot& b)
  35. {
  36. if (a.kind != b.kind || a.plugin.id != b.plugin.id || a.state != b.state || a.samplePath != b.samplePath || ! (a.plugin == b.plugin))
  37. return false;
  38. if (a.kind == EffectKind::parallel)
  39. return a == b; // its children are built in
  40. if (a.kind == EffectKind::patcher)
  41. return sameStructure (a.patcher, b.patcher);
  42. // a Hardware Insert's round trip is its latency, which the graph's delay compensation is built on (round 165c): a new
  43. // ping result builds the graph again
  44. if (a.kind == EffectKind::hardwareInsert)
  45. return a.params[(std::size_t) hwinsert::roundTrip] == b.params[(std::size_t) hwinsert::roundTrip];
  46. if (a.kind == EffectKind::atrium) // round 190nr: its dense late tank is allocated only where it runs
  47. return verbs::atriumDense (a.params) == verbs::atriumDense (b.params);
  48. // effects whose setup depends on parameters at creation (latency, mode) are rebuilt by the rack as well
  49. return true;
  50. }
  51. bool sameInstrumentSetup (const ChannelDef& a, const ChannelDef& b)
  52. {
  53. // a VFX node takes new settings while it runs (its held voices end as they started): only its kind is structure
  54. if (a.instrument == InstrumentKind::vfx || b.instrument == InstrumentKind::vfx)
  55. return a.instrument == b.instrument && vfx::kindOf (a) == vfx::kindOf (b);
  56. if (a.instrument != b.instrument)
  57. return false;
  58. // (a Layer node's children take notes in their key regions: round 165c)
  59. if (a.keyLow != b.keyLow || a.keyHigh != b.keyHigh)
  60. return false;
  61. // the rack's own rule for a channel (RackState::build): what configure() cannot take means a new instance; the rest
  62. // reaches the running one (round 164f: an engine edited in its editor inside a Patcher keeps playing, as on a
  63. // channel, instead of starting again on each knob move)
  64. switch (a.instrument)
  65. {
  66. case InstrumentKind::plugin:
  67. return a.plugin.id == b.plugin.id && a.plugin == b.plugin && a.pluginState == b.pluginState;
  68. case InstrumentKind::patcher: return sameStructure (a.patcher, b.patcher);
  69. case InstrumentKind::midiOut: return a.pluginState == b.pluginState; // (its MIDI channel is in the graph's routes)
  70. case InstrumentKind::layer: // (its settings are in the graph's note routes: round 165c)
  71. return a.layer == b.layer && a.volume == b.volume && a.pan == b.pan && a.sampler.pitch == b.sampler.pitch && a.misc.rootNote == b.misc.rootNote;
  72. case InstrumentKind::controller: // (a Keyboard Controller has 1 output, an Envelope Controller 8)
  73. return parseKeyboardController (a.controllerState).has_value() == parseKeyboardController (b.controllerState).has_value();
  74. case InstrumentKind::sampler:
  75. case InstrumentKind::audioClip:
  76. case InstrumentKind::flkeys:
  77. return a.samplePath == b.samplePath && a.zones == b.zones && a.modelParams == b.modelParams && a.sampler.keepPitch == b.sampler.keepPitch
  78. && (! a.sampler.keepPitch || (a.sampler.stretchBeats == b.sampler.stretchBeats && a.sampler.stretchMethod == b.sampler.stretchMethod
  79. && a.sampler.stretchPitch == b.sampler.stretchPitch && a.sampler.warp == b.sampler.warp
  80. && a.sampler.warpModes == b.sampler.warpModes));
  81. case InstrumentKind::granulizer:
  82. case InstrumentKind::wavetraveller:
  83. case InstrumentKind::soundfont: return a.samplePath == b.samplePath;
  84. case InstrumentKind::fruityslicer: return a.samplePath == b.samplePath && a.pluginState == b.pluginState;
  85. case InstrumentKind::slicex: return a.samplePath == b.samplePath && a.zones == b.zones; // (the state is taken live)
  86. case InstrumentKind::directwave: return a.zones == b.zones && a.modelParams == b.modelParams && a.pluginState == b.pluginState;
  87. case InstrumentKind::fpc: return a.zones == b.zones && a.pluginState == b.pluginState;
  88. case InstrumentKind::dashboard: // (its outputs are structure)
  89. return std::equal (a.patcher.surface.begin(), a.patcher.surface.end(), b.patcher.surface.begin(), b.patcher.surface.end(),
  90. [] (const SurfaceControl& x, const SurfaceControl& y) { return x.kind == y.kind; });
  91. default: return true;
  92. }
  93. }
  94. float mapControl (const std::vector<float>& curve, float v) noexcept
  95. {
  96. v = std::clamp (v, 0.0f, 1.0f);
  97. if (curve.size() < 2)
  98. return v;
  99. const auto x = v * (float) (curve.size() - 1);
  100. const auto i = std::min ((std::size_t) x, curve.size() - 2);
  101. const auto f = x - (float) i;
  102. return curve[i] + (curve[i + 1] - curve[i]) * f;
  103. }
  104. } // namespace
  105. std::optional<PatchNode::BusHead> busHeadOf (const PatchNode& node, int bus)
  106. {
  107. if (bus <= 0 || node.generator)
  108. return std::nullopt;
  109. for (const auto& h : node.busHeads)
  110. if (h.bus == bus)
  111. return h;
  112. if (node.effect.kind == EffectKind::frequencySplitter && bus <= 3) // LYNX's own: band sends 1 low, 2 mid, 3 high
  113. {
  114. PatchNode::BusHead head;
  115. head.bus = bus;
  116. auto slot = node.effect;
  117. slot.params[(std::size_t) fsplit::outputLow] = bus == 1 ? 1.0f : 0.0f;
  118. slot.params[(std::size_t) fsplit::outputMid] = bus == 2 ? 1.0f : 0.0f;
  119. slot.params[(std::size_t) fsplit::outputHigh] = bus == 3 ? 1.0f : 0.0f;
  120. head.head = slot;
  121. return head;
  122. }
  123. return std::nullopt;
  124. }
  125. NodePorts nodePorts (const PatchNode& node)
  126. {
  127. NodePorts p;
  128. if (node.generator)
  129. {
  130. p.audioIns = 0;
  131. p.midiIn = true;
  132. if (node.channel.instrument == InstrumentKind::controller) // Envelope Controller: 8 outputs; Keyboard Controller: 1
  133. p.controlOuts = parseKeyboardController (node.channel.controllerState) ? 1 : 8;
  134. if (node.channel.instrument == InstrumentKind::dashboard) // round 164: one per control (an XY pad: two)
  135. p.controlOuts = surface::firstOutput (node.channel.patcher.surface, (int) node.channel.patcher.surface.size());
  136. if (node.channel.instrument == InstrumentKind::controller || node.channel.instrument == InstrumentKind::midiOut
  137. || node.channel.instrument == InstrumentKind::dashboard || node.channel.instrument == InstrumentKind::layer)
  138. p.audioOuts = 0; // (no sound of their own)
  139. // a MIDI Out node; a hosted plugin's notes out (round 164f: an arpeggiator / MIDI effect plugin plays the
  140. // nodes cabled to it, as FL's Patcher shows a plugin's MIDI output)
  141. // (a Layer node, round 165c: its Children pin)
  142. p.midiOut = node.channel.instrument == InstrumentKind::midiOut || node.channel.instrument == InstrumentKind::plugin
  143. || node.channel.instrument == InstrumentKind::layer;
  144. p.midiOuts = p.midiOut ? 1 : 0;
  145. if (const auto kind = vfx::kindOf (node.channel)) // a VFX node: voices in, voices out (round 164b)
  146. {
  147. p.audioOuts = 0;
  148. p.midiOut = true;
  149. p.midiOuts = vfx::outputCount (*kind);
  150. if (*kind == vfx::Kind::script) // its output controllers (round 165d)
  151. if (const auto state = vfx::readState (node.channel.pluginState))
  152. if (const auto settings = vfx::parseScript (state->fl))
  153. p.controlOuts = (int) vfx::script::describe (*settings)->outputs.size();
  154. }
  155. if (node.channel.instrument == InstrumentKind::patcher)
  156. p.audioOuts = 1 + (int) node.channel.patcher.outputTracks.size();
  157. return p;
  158. }
  159. p.audioIns = 2; // main + side-chain
  160. p.midiIn = node.effect.kind == EffectKind::plugin;
  161. int highest = 0;
  162. for (const auto& h : node.busHeads)
  163. highest = std::max (highest, h.bus);
  164. if (node.effect.kind == EffectKind::frequencySplitter)
  165. highest = std::max (highest, 3);
  166. p.audioOuts = 1 + highest;
  167. if (node.effect.kind == EffectKind::peakController)
  168. p.controlOuts = 3;
  169. else if (node.effect.kind == EffectKind::formulaController)
  170. p.controlOuts = 1;
  171. else if (xy::isXyController (node.effect.kind)) // round 164: X, Y (, Z)
  172. p.controlOuts = xy::axesOf (node.effect.kind);
  173. else if (node.effect.kind == EffectKind::controlSurface) // round 164: one per control (an XY pad: two)
  174. p.controlOuts = surface::firstOutput (node.effect.patcher.surface, (int) node.effect.patcher.surface.size());
  175. return p;
  176. }
  177. bool sameStructure (const PatcherDoc& a, const PatcherDoc& b)
  178. {
  179. if (a.nodes.size() != b.nodes.size() || a.wires.size() != b.wires.size() || a.outputTracks != b.outputTracks || ! (a.published == b.published))
  180. return false;
  181. // the Surface's controls: their outputs are structure, their values are not (round 151)
  182. if (a.surface.size() != b.surface.size())
  183. return false;
  184. for (std::size_t i = 0; i < a.surface.size(); ++i)
  185. if (a.surface[i].kind != b.surface[i].kind)
  186. return false;
  187. for (std::size_t i = 0; i < a.nodes.size(); ++i)
  188. {
  189. const auto& x = a.nodes[i];
  190. const auto& y = b.nodes[i];
  191. if (x.generator != y.generator || x.busHeads.size() != y.busHeads.size())
  192. return false;
  193. if (x.generator ? ! sameInstrumentSetup (x.channel, y.channel) : ! sameEffectSetup (x.effect, y.effect))
  194. return false;
  195. for (std::size_t h = 0; h < x.busHeads.size(); ++h)
  196. if (x.busHeads[h].bus != y.busHeads[h].bus || x.busHeads[h].head.has_value() != y.busHeads[h].head.has_value()
  197. || (x.busHeads[h].head && ! sameEffectSetup (*x.busHeads[h].head, *y.busHeads[h].head)))
  198. return false;
  199. }
  200. for (std::size_t i = 0; i < a.wires.size(); ++i)
  201. {
  202. const auto& x = a.wires[i];
  203. const auto& y = b.wires[i];
  204. if (x.kind != y.kind || x.from != y.from || x.fromPort != y.fromPort || x.to != y.to || x.toPort != y.toPort || x.curve != y.curve
  205. || (x.kind != PatchWire::Kind::audio && x.enabled != y.enabled) || x.zone != y.zone)
  206. return false;
  207. }
  208. return a.zones == b.zones; // (rack chains' note filters, round 183c)
  209. }
  210. // ---------------------------------------------------------------------------------------------------------------
  211. namespace
  212. {
  213. // Round 190ts: a built-in device whose silence LYNX can tell (Graph::setStoppedSleep): not a hosted plugin or a nested
  214. // Patcher (that one sleeps by itself), nor what the mixer's smart disable leaves out (RackState::planSlot): Gross Beat and
  215. // Edison record the silence, Newtone / Newtime / the Scratcher play whatever the input, a hardware insert has outboard
  216. // tails, controllers move whatever the sound, analysers and the tuner follow the signal into silence, Facet EQ playing
  217. // its comparative target.
  218. bool sleepableDevice (const EffectSlot& slot) noexcept
  219. {
  220. switch (slot.kind)
  221. {
  222. case EffectKind::plugin: case EffectKind::patcher: case EffectKind::grossBeat: case EffectKind::newtone:
  223. case EffectKind::newtime: case EffectKind::scratcher: case EffectKind::edison: case EffectKind::hardwareInsert:
  224. case EffectKind::formulaController: case EffectKind::xyController: case EffectKind::xyzController:
  225. case EffectKind::controlSurface: case EffectKind::peakController: case EffectKind::waveCandy:
  226. case EffectKind::visualizer: case EffectKind::tuner:
  227. return false;
  228. default:
  229. break;
  230. }
  231. return ! (slot.kind == EffectKind::facetEq && facet::listensToTarget (slot.params));
  232. }
  233. constexpr float sleepLevel = 1.5849e-5f; // -96 dBFS (RackRenderer::silenceLevel)
  234. bool quietBlock (const float* l, const float* r, int n) noexcept
  235. {
  236. float peak = 0.0f;
  237. for (int k = 0; k < n; ++k)
  238. peak = std::max (peak, std::max (std::abs (l[k]), std::abs (r[k])));
  239. return peak < sleepLevel;
  240. }
  241. } // namespace
  242. struct Graph::Node
  243. {
  244. bool generator = false;
  245. EffectSlot setup; // effect nodes
  246. ChannelDef channel; // generator nodes
  247. std::shared_ptr<Effect> effect;
  248. std::shared_ptr<Instrument> instrument;
  249. bool plugin = false; // values reach it through setParameter (control cables), not the params array
  250. bool hardware = false; // a Hardware Insert, or a Patcher holding one (round 165c)
  251. vfx::Processor* vfx = nullptr; // a VFX node's processor (owned by its instrument)
  252. std::vector<MidiTarget> midiOutTargets; // a plugin node: what its MIDI output pin reaches
  253. std::vector<std::vector<MidiTarget>> vfxTargets; // [voice output] what it reaches
  254. std::vector<std::vector<int>> vfxHostPorts; // [voice output] the "To LYNX SHARE" MIDI ports it is cabled to
  255. struct Head
  256. {
  257. int bus = 1;
  258. std::shared_ptr<Effect> effect; // null = direct
  259. EffectSlot slot;
  260. float gain = 1.0f;
  261. };
  262. std::vector<Head> heads;
  263. std::vector<std::array<std::vector<float>, 2>> out; // [0] main output, [1 + h] head h
  264. bool sidechain = false;
  265. int inLatency = 0, outLatency = 0;
  266. std::vector<int> mainInputs, sideInputs; // wire indices
  267. std::atomic<float> peak { 0.0f }; // round 190ld: main-output peak and process time while watched (Graph::watch)
  268. std::atomic<std::uint64_t> ns { 0 };
  269. // round 190ts (Graph::setStoppedSleep): may sleep while stopped (LYNX's own devices / an instrument that says idle);
  270. // a nested Patcher sleeps by itself (its graph), and counts as asleep when it is
  271. bool sleeps = false;
  272. Graph* nested = nullptr;
  273. int silentSamples = 0; // input and output silent that long (effect nodes)
  274. bool asleep = false; // not called in the last piece
  275. };
  276. struct Graph::AudioWire
  277. {
  278. int from = patchFromHost, fromBuffer = 0; // node, and its output buffer (0 main, 1 + h head); host: 0 input, 1 side-chain
  279. int to = patchToHost, toBus = 0;
  280. std::shared_ptr<DelayLine> delay;
  281. int docIndex = 0;
  282. };
  283. struct Graph::ControlWire
  284. {
  285. int from = 0, output = 0, to = 0, param = 0;
  286. int fromParam = -1; // a parameter output (round 171b): the source node's parameter, else its control output `output`
  287. std::vector<float> curve;
  288. int docIndex = 0;
  289. float sent = std::numeric_limits<float>::quiet_NaN(); // the value last given to a plugin / instrument target
  290. };
  291. struct Graph::VfxQueue
  292. {
  293. vfx::EventList in, out; // the voices that reached the node in this piece; what it sends
  294. };
  295. struct Graph::NoteOut
  296. {
  297. int node = 0, midiChannel = -1;
  298. vfx::Event event;
  299. float gain = 1.0f; // a Layer's level for this child (round 165c)
  300. };
  301. struct Graph::LayerNode
  302. {
  303. std::vector<MidiTarget> children; // the nodes on its Children pin, in node order (no Layers)
  304. std::vector<ChannelDef> defs; // [node] what layer::pick reads: the Layer's settings, the children's key regions
  305. std::array<int, 128> picked {}; // Random / Sequential: the child each held key went to (−1: none)
  306. std::uint32_t random = 0x165c165cu;
  307. int turn = 0;
  308. };
  309. struct Graph::Values
  310. {
  311. struct NodeValues
  312. {
  313. EffectParams params {};
  314. bool enabled = true;
  315. float mix = 1.0f;
  316. std::vector<EffectParams> heads;
  317. std::vector<float> headGains;
  318. };
  319. std::vector<NodeValues> nodes;
  320. std::vector<float> gains;
  321. std::vector<char> on;
  322. std::vector<float> surface; // the Surface node's control outputs
  323. };
  324. Graph::Graph (const PatcherDoc& doc, double sampleRate, const Factories& factories, const Graph* previous) : rate (sampleRate)
  325. {
  326. const auto count = (int) doc.nodes.size();
  327. std::vector<char> taken (previous != nullptr ? previous->nodes.size() : 0, 0);
  328. for (int i = 0; i < count; ++i)
  329. {
  330. const auto& src = doc.nodes[(std::size_t) i];
  331. auto node = std::make_unique<Node>();
  332. node->generator = src.generator;
  333. // a running instance with the same setup (the previous graph's node at the same index first)
  334. auto reuse = [&] () -> const Node* {
  335. if (previous == nullptr)
  336. return nullptr;
  337. auto matches = [&] (std::size_t k) {
  338. const auto& p = *previous->nodes[k];
  339. return ! taken[k] && p.generator == src.generator
  340. && (src.generator ? p.instrument != nullptr && sameInstrumentSetup (p.channel, src.channel)
  341. : p.effect != nullptr && sameEffectSetup (p.setup, src.effect));
  342. };
  343. if ((std::size_t) i < previous->nodes.size() && matches ((std::size_t) i))
  344. {
  345. taken[(std::size_t) i] = 1;
  346. return previous->nodes[(std::size_t) i].get();
  347. }
  348. for (std::size_t k = 0; k < previous->nodes.size(); ++k)
  349. if (matches (k))
  350. {
  351. taken[k] = 1;
  352. return previous->nodes[k].get();
  353. }
  354. return nullptr;
  355. }();
  356. if (src.generator)
  357. {
  358. node->channel = src.channel;
  359. node->plugin = src.channel.instrument == InstrumentKind::plugin;
  360. const auto* nested = reuse != nullptr ? graphOf (reuse->instrument.get()) : nullptr;
  361. if (nested != nullptr && nested->latencyStale (&src.channel.patcher))
  362. {
  363. // a nested generator Patcher whose plan no longer holds (issue #113): built again, keeping its nodes
  364. node->instrument = makeInstrument (src.channel, sampleRate, factories, reuse->instrument.get());
  365. node->instrument->configure (src.channel, 140.0);
  366. }
  367. else if (reuse != nullptr)
  368. {
  369. node->instrument = reuse->instrument;
  370. node->instrument->configure (src.channel, 140.0);
  371. }
  372. else if (factories.instrument)
  373. node->instrument = factories.instrument (src.channel);
  374. }
  375. else
  376. {
  377. node->setup = src.effect;
  378. // (a nested rack takes its macros as published parameters through setParameter, round 183c)
  379. node->plugin = src.effect.kind == EffectKind::plugin || (src.effect.kind == EffectKind::patcher && src.effect.patcher.isRack());
  380. const auto* nested = reuse != nullptr ? graphOf (reuse->effect.get()) : nullptr;
  381. if (nested != nullptr && nested->latencyStale (&src.effect.patcher))
  382. {
  383. // a nested Patcher whose plan no longer holds (issue #113): built again too, keeping its running nodes
  384. node->effect = makeEffect (src.effect, sampleRate, factories, reuse->effect.get());
  385. node->effect->prepare (sampleRate);
  386. }
  387. else if (reuse != nullptr)
  388. node->effect = reuse->effect;
  389. else if (factories.effect)
  390. node->effect = factories.effect (src.effect);
  391. if (node->effect == nullptr)
  392. node->effect = std::make_shared<PassEffect>();
  393. node->hardware = src.effect.kind == EffectKind::hardwareInsert || (src.effect.kind == EffectKind::patcher && usesHardwareIo (src.effect.patcher));
  394. hardwareNodes = hardwareNodes || node->hardware;
  395. }
  396. // extra outputs used by some cable
  397. for (const auto& w : doc.wires)
  398. if (w.kind == PatchWire::Kind::audio && w.from == i && w.fromPort > 0
  399. && std::none_of (node->heads.begin(), node->heads.end(), [&] (const Node::Head& h) { return h.bus == w.fromPort; }))
  400. if (const auto head = busHeadOf (src, w.fromPort))
  401. {
  402. Node::Head h;
  403. h.bus = head->bus;
  404. h.gain = head->gain;
  405. if (head->head)
  406. {
  407. h.slot = *head->head;
  408. const Node::Head* old = nullptr;
  409. if (reuse != nullptr)
  410. for (const auto& o : reuse->heads)
  411. if (o.bus == h.bus && o.effect != nullptr && sameEffectSetup (o.slot, h.slot))
  412. old = &o;
  413. h.effect = old != nullptr ? old->effect : (factories.effect ? factories.effect (h.slot) : nullptr);
  414. if (h.effect == nullptr)
  415. h.effect = std::make_shared<PassEffect>();
  416. }
  417. node->heads.push_back (std::move (h));
  418. }
  419. node->out.resize (1 + node->heads.size());
  420. for (auto& o : node->out)
  421. for (auto& side : o)
  422. side.assign ((std::size_t) capacity, 0.0f);
  423. nodes.push_back (std::move (node));
  424. }
  425. // cables
  426. int highestAux = 0;
  427. for (std::size_t w = 0; w < doc.wires.size(); ++w)
  428. {
  429. const auto& src = doc.wires[w];
  430. const auto validNode = [count] (int n) { return n >= 0 && n < count; };
  431. if (src.kind == PatchWire::Kind::audio)
  432. {
  433. AudioWire a;
  434. a.docIndex = (int) w;
  435. a.from = src.from;
  436. a.to = src.to;
  437. a.toBus = std::max (0, src.toPort);
  438. if (src.from == patchFromHost)
  439. a.fromBuffer = src.fromPort == 1 ? 1 : 0;
  440. else if (validNode (src.from))
  441. {
  442. if (src.fromPort > 0)
  443. {
  444. const auto& heads = nodes[(std::size_t) src.from]->heads;
  445. const auto h = std::find_if (heads.begin(), heads.end(), [&] (const Node::Head& x) { return x.bus == src.fromPort; });
  446. if (h == heads.end())
  447. continue; // an output the node does not have: silence
  448. a.fromBuffer = 1 + (int) (h - heads.begin());
  449. }
  450. }
  451. else
  452. continue;
  453. if (src.to == patchToHost)
  454. highestAux = std::max (highestAux, a.toBus);
  455. else if (! validNode (src.to) || nodes[(std::size_t) src.to]->generator || a.toBus > 1)
  456. continue;
  457. wires.push_back (std::move (a));
  458. }
  459. else if (src.kind == PatchWire::Kind::midi)
  460. {
  461. if (src.from == patchFromHost && src.fromPort == 0 && validNode (src.to) && src.enabled
  462. && std::find (noteTargets.begin(), noteTargets.end(), src.to) == noteTargets.end())
  463. noteTargets.push_back (src.to);
  464. }
  465. else if ((validNode (src.from) || (src.from == patchSurface && std::max (0, src.fromPort) < doc.surfaceOutputs())) && validNode (src.to)
  466. && src.enabled && src.toPort >= 0
  467. && (src.from == patchSurface || isPatchParamOutput (src.fromPort) // (a node's parameter output, round 171b)
  468. || std::max (0, src.fromPort) < nodePorts (doc.nodes[(std::size_t) src.from]).controlOuts)) // (a source with that output)
  469. {
  470. ControlWire c;
  471. c.from = src.from;
  472. c.output = std::max (0, src.fromPort);
  473. if (src.from != patchSurface && isPatchParamOutput (src.fromPort))
  474. {
  475. c.output = -1;
  476. c.fromParam = patchOutputParam (src.fromPort);
  477. if (! nodes[(std::size_t) c.from]->plugin && ! nodes[(std::size_t) c.from]->generator && c.fromParam >= maxEffectParams)
  478. continue;
  479. }
  480. c.to = src.to;
  481. c.param = src.toPort;
  482. c.curve = src.curve;
  483. c.docIndex = (int) w;
  484. if (! nodes[(std::size_t) c.to]->plugin && ! nodes[(std::size_t) c.to]->generator && c.param >= maxEffectParams)
  485. continue;
  486. controls.push_back (std::move (c));
  487. }
  488. }
  489. highestAux = std::max (highestAux, (int) doc.outputTracks.size());
  490. // MIDI (round 162): what each "From LYNX SHARE" pin reaches, through MIDI Out nodes (they set the MIDI channel); VFX
  491. // nodes (round 164b) take the voices into their processors and send theirs on from their voice outputs
  492. zoneStates.resize (doc.zones.size());
  493. for (std::size_t z = 0; z < doc.zones.size(); ++z)
  494. zoneStates[z].zone = doc.zones[z];
  495. pinTargets.assign ((std::size_t) patchMidiPortPin (patchMidiPorts), {});
  496. for (int pin = 0; pin < (int) pinTargets.size(); ++pin)
  497. pinTargets[(std::size_t) pin] = midiTargetsOf (doc, patchFromHost, pin);
  498. vfxQueues.resize ((std::size_t) count);
  499. for (int i = 0; i < count; ++i)
  500. {
  501. auto& node = *nodes[(std::size_t) i];
  502. if (node.instrument == nullptr || (node.vfx = node.instrument->noteProcessor()) == nullptr)
  503. continue;
  504. node.vfx->prepare (rate);
  505. const auto kind = node.vfx->kind();
  506. for (int k = 0; k < vfx::outputCount (kind); ++k)
  507. {
  508. node.vfxTargets.push_back (midiTargetsOf (doc, i, k));
  509. std::vector<int> ports;
  510. for (const auto& w : doc.wires)
  511. if (w.kind == PatchWire::Kind::midi && w.enabled && w.from == i && w.fromPort == k && w.to == patchToHost && w.toPort >= 0
  512. && w.toPort < patchMidiPorts && std::find (ports.begin(), ports.end(), w.toPort) == ports.end())
  513. ports.push_back (w.toPort);
  514. node.vfxHostPorts.push_back (std::move (ports));
  515. }
  516. vfxQueues[(std::size_t) i] = std::make_unique<VfxQueue>();
  517. hasVfx = true;
  518. }
  519. if (hasVfx)
  520. {
  521. // sources first (Kahn over the VFX → VFX links); a loop runs in index order (its voices wait a piece)
  522. std::vector<int> pendingInputs ((std::size_t) count, 0);
  523. for (int i = 0; i < count; ++i)
  524. for (const auto& targets : nodes[(std::size_t) i]->vfxTargets)
  525. for (const auto& t : targets)
  526. if (t.vfx && t.node != i)
  527. ++pendingInputs[(std::size_t) t.node];
  528. std::vector<char> placed ((std::size_t) count, 0);
  529. for (bool progress = true; progress;)
  530. {
  531. progress = false;
  532. for (int i = 0; i < count; ++i)
  533. if (! placed[(std::size_t) i] && nodes[(std::size_t) i]->vfx != nullptr && pendingInputs[(std::size_t) i] == 0)
  534. {
  535. placed[(std::size_t) i] = 1;
  536. vfxOrder.push_back (i);
  537. progress = true;
  538. for (const auto& targets : nodes[(std::size_t) i]->vfxTargets)
  539. for (const auto& t : targets)
  540. if (t.vfx && t.node != i)
  541. --pendingInputs[(std::size_t) t.node];
  542. }
  543. }
  544. for (int i = 0; i < count; ++i)
  545. if (! placed[(std::size_t) i] && nodes[(std::size_t) i]->vfx != nullptr)
  546. vfxOrder.push_back (i);
  547. }
  548. // hosted plugin nodes with a cable on their MIDI output (round 164f)
  549. for (int i = 0; i < count; ++i)
  550. {
  551. auto& node = *nodes[(std::size_t) i];
  552. if (! node.generator || node.instrument == nullptr || node.vfx != nullptr || doc.nodes[(std::size_t) i].channel.instrument != InstrumentKind::plugin)
  553. continue;
  554. node.midiOutTargets = midiTargetsOf (doc, i, 0);
  555. if (! node.midiOutTargets.empty())
  556. midiSources.push_back (i);
  557. }
  558. // Layer nodes (round 165c): their children, and what layer::pick reads
  559. layers.resize ((std::size_t) count);
  560. for (int i = 0; i < count; ++i)
  561. {
  562. const auto& src = doc.nodes[(std::size_t) i];
  563. if (! src.generator || src.channel.instrument != InstrumentKind::layer)
  564. continue;
  565. auto l = std::make_unique<LayerNode>();
  566. for (const auto& t : midiTargetsOf (doc, i, 0))
  567. if (! t.layer && t.node != i)
  568. l->children.push_back (t);
  569. std::stable_sort (l->children.begin(), l->children.end(), [] (const MidiTarget& a, const MidiTarget& b) { return a.node < b.node; });
  570. l->defs.resize ((std::size_t) count);
  571. for (int k = 0; k < count; ++k)
  572. {
  573. auto& d = l->defs[(std::size_t) k];
  574. d.instrument = doc.nodes[(std::size_t) k].generator ? doc.nodes[(std::size_t) k].channel.instrument : InstrumentKind::synth;
  575. d.keyLow = doc.nodes[(std::size_t) k].channel.keyLow;
  576. d.keyHigh = doc.nodes[(std::size_t) k].channel.keyHigh;
  577. d.misc.addToKey = doc.nodes[(std::size_t) k].channel.misc.addToKey;
  578. d.misc.rootNote = doc.nodes[(std::size_t) k].channel.misc.rootNote;
  579. }
  580. auto& self = l->defs[(std::size_t) i];
  581. self.layer = src.channel.layer;
  582. self.layer.children.clear();
  583. for (const auto& c : l->children)
  584. self.layer.children.push_back (c.node);
  585. self.volume = src.channel.volume;
  586. self.pan = src.channel.pan;
  587. self.sampler.pitch = src.channel.sampler.pitch;
  588. self.misc.rootNote = src.channel.misc.rootNote;
  589. l->picked.fill (-1);
  590. layers[(std::size_t) i] = std::move (l);
  591. }
  592. noteOuts.reserve (vfx::EventList::capacity);
  593. published = doc.published;
  594. publishedValues.assign (published.size(), std::numeric_limits<float>::quiet_NaN());
  595. aux.resize ((std::size_t) highestAux);
  596. for (auto& a : aux)
  597. for (auto& side : a)
  598. side.assign ((std::size_t) capacity, 0.0f);
  599. // order: nodes once all their audio sources ran (Kahn); what is left (loops) in index order
  600. std::vector<int> pendingInputs ((std::size_t) count, 0);
  601. for (const auto& w : wires)
  602. if (w.from >= 0 && w.to >= 0 && w.from != w.to)
  603. ++pendingInputs[(std::size_t) w.to];
  604. std::vector<char> placed ((std::size_t) count, 0);
  605. for (bool progress = true; progress;)
  606. {
  607. progress = false;
  608. for (int i = 0; i < count; ++i)
  609. if (! placed[(std::size_t) i] && pendingInputs[(std::size_t) i] == 0)
  610. {
  611. placed[(std::size_t) i] = 1;
  612. order.push_back (i);
  613. progress = true;
  614. for (const auto& w : wires)
  615. if (w.from == i && w.to >= 0 && w.to != i)
  616. --pendingInputs[(std::size_t) w.to];
  617. }
  618. }
  619. for (int i = 0; i < count; ++i)
  620. if (! placed[(std::size_t) i])
  621. order.push_back (i);
  622. for (std::size_t k = 0; k < wires.size(); ++k)
  623. if (wires[k].to >= 0)
  624. {
  625. auto& node = *nodes[(std::size_t) wires[k].to];
  626. (wires[k].toBus == 0 ? node.mainInputs : node.sideInputs).push_back ((int) k);
  627. node.sidechain = node.sidechain || wires[k].toBus == 1;
  628. }
  629. // delay compensation (FL: a cable from a source with less latency than the destination's goes through a delay)
  630. std::vector<int> position ((std::size_t) count, 0);
  631. for (std::size_t k = 0; k < order.size(); ++k)
  632. position[(std::size_t) order[k]] = (int) k;
  633. auto runsBefore = [&] (const AudioWire& w) { return w.from < 0 || w.to < 0 || position[(std::size_t) w.from] < position[(std::size_t) w.to]; };
  634. auto sourceLatency = [&] (const AudioWire& w) { return w.from >= 0 ? nodes[(std::size_t) w.from]->outLatency : 0; };
  635. plannedOwn.resize ((std::size_t) count);
  636. plannedEnabled.resize ((std::size_t) count);
  637. for (int i = 0; i < count; ++i)
  638. {
  639. plannedEnabled[(std::size_t) i] = doc.nodes[(std::size_t) i].generator || doc.nodes[(std::size_t) i].effect.enabled ? 1 : 0;
  640. plannedOwn[(std::size_t) i] = ownLatency (i, plannedEnabled[(std::size_t) i] != 0);
  641. }
  642. {
  643. std::vector<int> in, out;
  644. latency = planLatencies (plannedOwn, in, out);
  645. for (int i = 0; i < count; ++i)
  646. {
  647. nodes[(std::size_t) i]->inLatency = in[(std::size_t) i];
  648. nodes[(std::size_t) i]->outLatency = out[(std::size_t) i];
  649. }
  650. }
  651. for (auto& w : wires)
  652. {
  653. if (! runsBefore (w))
  654. continue;
  655. const auto target = w.to >= 0 ? nodes[(std::size_t) w.to]->inLatency : latency; // every output aligned to the longest
  656. const auto difference = target - sourceLatency (w);
  657. if (difference > 0)
  658. w.delay = std::make_shared<DelayLine> (difference);
  659. }
  660. outputs.resize (aux.size() + 1);
  661. for (std::size_t k = 0; k < wires.size(); ++k)
  662. if (wires[k].to == patchToHost && wires[k].toBus < (int) outputs.size())
  663. outputs[(std::size_t) wires[k].toBus].push_back ((int) k);
  664. // round 190ts (setStoppedSleep): which nodes may sleep while stopped
  665. canWholeSleep = ! hardwareNodes;
  666. for (int i = 0; i < count; ++i)
  667. {
  668. auto& node = *nodes[(std::size_t) i];
  669. const auto& src = doc.nodes[(std::size_t) i];
  670. if (node.generator)
  671. {
  672. // (a hosted generator keeps running: its idle() is FL's smart disable, which the rack asks itself)
  673. node.nested = graphOf (node.instrument.get());
  674. node.sleeps = node.instrument != nullptr && node.vfx == nullptr && ! node.plugin && node.nested == nullptr;
  675. if (node.nested != nullptr)
  676. nestedGraphs.push_back (node.nested);
  677. else if (! node.sleeps && node.vfx == nullptr)
  678. canWholeSleep = false;
  679. continue;
  680. }
  681. node.nested = src.effect.kind == EffectKind::patcher ? graphOf (node.effect.get()) : nullptr;
  682. if (node.nested != nullptr)
  683. {
  684. nestedGraphs.push_back (node.nested);
  685. if (node.sidechain)
  686. canWholeSleep = false;
  687. continue;
  688. }
  689. const auto drivesControls = std::any_of (controls.begin(), controls.end(), [i] (const ControlWire& c) { return c.from == i; });
  690. node.sleeps = node.effect != nullptr && ! node.sidechain && ! node.hardware && ! drivesControls && sleepableDevice (src.effect)
  691. && std::all_of (node.heads.begin(), node.heads.end(), [] (const Node::Head& h) { return h.effect == nullptr || sleepableDevice (h.slot); });
  692. canWholeSleep = canWholeSleep && node.sleeps;
  693. }
  694. for (auto& s : scratch)
  695. s.assign ((std::size_t) capacity, 0.0f);
  696. zeros.assign ((std::size_t) capacity, 0.0f);
  697. active = std::make_unique<Values>();
  698. takeValues (doc, 140.0);
  699. applyPending();
  700. }
  701. int Graph::ownLatency (int i, bool enabled) const noexcept
  702. {
  703. const auto& node = *nodes[(std::size_t) i];
  704. if (node.generator)
  705. return node.instrument != nullptr ? std::max (0, node.instrument->latencySamples()) : 0;
  706. return enabled && node.effect != nullptr ? std::max (0, node.effect->latencySamples()) : 0;
  707. }
  708. int Graph::planLatencies (const std::vector<int>& own, std::vector<int>& in, std::vector<int>& out) const
  709. {
  710. const auto count = nodes.size();
  711. in.assign (count, 0);
  712. out.assign (count, 0);
  713. std::vector<int> position (count, 0);
  714. for (std::size_t k = 0; k < order.size(); ++k)
  715. position[(std::size_t) order[k]] = (int) k;
  716. auto runsBefore = [&] (const AudioWire& w) { return w.from < 0 || w.to < 0 || position[(std::size_t) w.from] < position[(std::size_t) w.to]; };
  717. auto sourceLatency = [&] (const AudioWire& w) { return w.from >= 0 ? out[(std::size_t) w.from] : 0; };
  718. for (const auto i : order)
  719. {
  720. const auto& node = *nodes[(std::size_t) i];
  721. int latest = 0;
  722. for (const auto k : node.mainInputs)
  723. if (runsBefore (wires[(std::size_t) k]))
  724. latest = std::max (latest, sourceLatency (wires[(std::size_t) k]));
  725. for (const auto k : node.sideInputs)
  726. if (runsBefore (wires[(std::size_t) k]))
  727. latest = std::max (latest, sourceLatency (wires[(std::size_t) k]));
  728. in[(std::size_t) i] = latest;
  729. out[(std::size_t) i] = latest + std::max (0, own[(std::size_t) i]);
  730. }
  731. int longest = 0;
  732. for (const auto& w : wires)
  733. if (w.to == patchToHost && w.toBus <= (int) aux.size())
  734. longest = std::max (longest, sourceLatency (w));
  735. return longest;
  736. }
  737. bool Graph::latencyStale (const PatcherDoc* doc) const
  738. {
  739. for (std::size_t i = 0; i < nodes.size() && i < plannedOwn.size(); ++i)
  740. {
  741. const auto* src = doc != nullptr && i < doc->nodes.size() ? &doc->nodes[i] : nullptr;
  742. const auto enabled = src != nullptr ? (src->generator || src->effect.enabled) : plannedEnabled[i] != 0;
  743. if (ownLatency ((int) i, enabled) != plannedOwn[i])
  744. return true;
  745. // a nested Patcher: a node switched on / off in its own document
  746. const auto& node = *nodes[i];
  747. const auto* nested = node.generator ? graphOf (node.instrument.get()) : graphOf (node.effect.get());
  748. if (nested != nullptr && src != nullptr && src->generator == node.generator
  749. && nested->latencyStale (node.generator ? &src->channel.patcher : &src->effect.patcher))
  750. return true;
  751. }
  752. return false;
  753. }
  754. int Graph::latencySamples() const
  755. {
  756. if (! latencyStale())
  757. return latency;
  758. // a node's latency moved since the plan (issue #113): report what the graph will have once the rack builds it
  759. // again, so the mixer sees the change and rebuilds it (the UI thread polls the rack's latencies)
  760. std::vector<int> own (plannedOwn.size(), 0), in, out;
  761. for (std::size_t i = 0; i < own.size(); ++i)
  762. own[i] = ownLatency ((int) i, plannedEnabled[i] != 0);
  763. return planLatencies (own, in, out);
  764. }
  765. Graph::~Graph()
  766. {
  767. delete pending.exchange (nullptr);
  768. delete retired.exchange (nullptr);
  769. }
  770. void Graph::takeValues (const PatcherDoc& doc, double bpm)
  771. {
  772. auto values = std::make_unique<Values>();
  773. values->nodes.resize (nodes.size());
  774. for (std::size_t i = 0; i < nodes.size() && i < doc.nodes.size(); ++i)
  775. {
  776. const auto& src = doc.nodes[i];
  777. auto& v = values->nodes[i];
  778. if (! src.generator)
  779. {
  780. v.params = src.effect.params;
  781. v.enabled = src.effect.enabled;
  782. v.mix = src.effect.mix;
  783. }
  784. for (const auto& h : nodes[i]->heads)
  785. {
  786. const auto head = busHeadOf (src, h.bus);
  787. v.heads.push_back (head && head->head ? head->head->params : h.slot.params);
  788. v.headGains.push_back (head ? head->gain : h.gain);
  789. }
  790. if (src.generator && nodes[i]->instrument != nullptr)
  791. nodes[i]->instrument->configure (src.channel, bpm);
  792. }
  793. for (const auto& w : wires)
  794. {
  795. const auto& src = doc.wires[(std::size_t) w.docIndex];
  796. values->gains.push_back (std::isfinite (src.gain) ? src.gain : 1.0f);
  797. values->on.push_back (src.enabled ? 1 : 0);
  798. }
  799. for (int k = 0; k < doc.surfaceOutputs(); ++k)
  800. values->surface.push_back (std::clamp (doc.surfaceOutput (k), 0.0f, 1.0f));
  801. delete retired.exchange (nullptr);
  802. delete pending.exchange (values.release());
  803. }
  804. void Graph::applyPending() noexcept
  805. {
  806. if (auto* incoming = pending.exchange (nullptr))
  807. {
  808. auto* old = active.release();
  809. active.reset (incoming);
  810. delete retired.exchange (old); // (normally null: the UI frees it on its next call)
  811. }
  812. }
  813. void Graph::prepare (double sampleRate) noexcept
  814. {
  815. if (sampleRate == rate)
  816. return;
  817. rate = sampleRate;
  818. for (auto& n : nodes)
  819. {
  820. if (n->effect != nullptr)
  821. n->effect->prepare (sampleRate);
  822. if (n->instrument != nullptr)
  823. n->instrument->prepare (sampleRate);
  824. for (auto& h : n->heads)
  825. if (h.effect != nullptr)
  826. h.effect->prepare (sampleRate);
  827. }
  828. }
  829. void Graph::reset() noexcept
  830. {
  831. for (auto& n : nodes)
  832. {
  833. if (n->effect != nullptr)
  834. n->effect->reset();
  835. for (auto& h : n->heads)
  836. if (h.effect != nullptr)
  837. h.effect->reset();
  838. for (auto& o : n->out)
  839. for (auto& side : o)
  840. std::fill (side.begin(), side.end(), 0.0f);
  841. }
  842. }
  843. void Graph::setSongPosition (double position) noexcept
  844. {
  845. ticks = position;
  846. playing = hostTimeline().playing.load (std::memory_order_relaxed);
  847. for (auto& n : nodes)
  848. {
  849. if (n->effect != nullptr)
  850. n->effect->setSongPosition (position);
  851. if (n->instrument != nullptr)
  852. n->instrument->setSongPosition (position);
  853. for (auto& h : n->heads)
  854. if (h.effect != nullptr)
  855. h.effect->setSongPosition (position);
  856. }
  857. }
  858. void Graph::setPlaying (bool on) noexcept
  859. {
  860. playing = on;
  861. for (auto& n : nodes)
  862. if (n->effect != nullptr)
  863. n->effect->setPlaying (on);
  864. }
  865. void Graph::setStoppedSleep (bool on) noexcept
  866. {
  867. if (on == sleepOk)
  868. return;
  869. sleepOk = on;
  870. wholeAsleep = allNodesAsleep = false;
  871. quietSamples = 0;
  872. for (auto& n : nodes)
  873. {
  874. n->silentSamples = 0;
  875. n->asleep = false;
  876. }
  877. for (auto* g : nestedGraphs)
  878. g->setStoppedSleep (on);
  879. }
  880. int Graph::sleepHold (const Node& node) const noexcept
  881. {
  882. // (as the mixer's smart disable takes a built-in's declared tail, round 190gp; an undeclared one waits 4 s of silence:
  883. // the plugins' hold, longer than the mixer's 1 s for built-ins, so a long echo or reverb never stops early)
  884. const auto fixed = (int) (rate * 4.0);
  885. if (! declaredTails() || node.effect == nullptr)
  886. return fixed;
  887. auto tail = node.effect->tailSamples();
  888. for (const auto& h : node.heads)
  889. if (h.effect != nullptr)
  890. {
  891. const auto t = h.effect->tailSamples();
  892. tail = tail < 0 || t < 0 ? -1 : std::max (tail, t);
  893. }
  894. return tail < 0 ? fixed : std::clamp (tail, 1, fixed);
  895. }
  896. void Graph::setHeldNotes (const NoteMask* channels, int count) noexcept
  897. {
  898. for (auto& n : nodes)
  899. if (n->effect != nullptr)
  900. n->effect->setHeldNotes (channels, count);
  901. }
  902. bool Graph::followsHeldNotes() const noexcept
  903. {
  904. for (const auto& n : nodes)
  905. if (n->effect != nullptr && n->effect->followsHeldNotes())
  906. return true;
  907. return false;
  908. }
  909. void Graph::noteOn (int key, float velocity) noexcept { deliver (0, true, key, velocity, -1); }
  910. void Graph::noteOff (int key) noexcept { deliver (0, false, key, 0.0f, -1); }
  911. void Graph::noteOnMidi (int key, float velocity, int midiChannel) noexcept { deliver (0, true, key, velocity, midiChannel); }
  912. void Graph::noteOffMidi (int key, int midiChannel) noexcept { deliver (0, false, key, 0.0f, midiChannel); }
  913. std::vector<Graph::MidiTarget> Graph::midiTargetsOf (const PatcherDoc& doc, int from, int pin) const
  914. {
  915. std::vector<MidiTarget> targets;
  916. const auto count = (int) doc.nodes.size();
  917. std::vector<char> seen ((std::size_t) count, 0);
  918. // (source, its pin, the channel set on the way)
  919. std::vector<std::tuple<int, int, int>> todo { { from, pin, -1 } };
  920. while (! todo.empty())
  921. {
  922. const auto [source, sourcePin, channel] = todo.back();
  923. todo.pop_back();
  924. for (const auto& w : doc.wires)
  925. {
  926. if (w.kind != PatchWire::Kind::midi || ! w.enabled || w.from != source || w.fromPort != sourcePin || w.to < 0 || w.to >= count
  927. || seen[(std::size_t) w.to])
  928. continue;
  929. seen[(std::size_t) w.to] = 1;
  930. const auto& target = doc.nodes[(std::size_t) w.to];
  931. if (! target.generator)
  932. continue;
  933. if (target.channel.instrument == InstrumentKind::midiOut)
  934. todo.emplace_back (w.to, 0, midictl::parseMidiOut (target.channel.pluginState).channel);
  935. else
  936. targets.push_back ({ w.to, channel, target.channel.instrument == InstrumentKind::vfx, target.channel.instrument == InstrumentKind::layer,
  937. source == from && w.zone >= 0 && w.zone < (int) doc.zones.size() ? w.zone : -1 });
  938. }
  939. }
  940. return targets;
  941. }
  942. template <typename F>
  943. void Graph::forLayeredTargets (const std::vector<MidiTarget>& targets, int type, int key, F&& f) noexcept
  944. {
  945. for (const auto& t : targets)
  946. {
  947. if (! t.layer)
  948. {
  949. f (t, key, 1.0f, 0.0f, 0.0f, false);
  950. continue;
  951. }
  952. auto* l = (std::size_t) t.node < layers.size() ? layers[(std::size_t) t.node].get() : nullptr;
  953. if (l == nullptr || l->children.empty())
  954. continue;
  955. const auto& self = l->defs[(std::size_t) t.node];
  956. const auto pan = self.pan, cents = layer::pitchCents (self);
  957. auto child = [&t] (MidiTarget c) {
  958. if (c.midiChannel < 0)
  959. c.midiChannel = t.midiChannel; // (a MIDI Out node before the Layer sets the channel, one after it wins)
  960. return c;
  961. };
  962. auto childOf = [&] (int node) -> const MidiTarget* {
  963. for (const auto& c : l->children)
  964. if (c.node == node)
  965. return &c;
  966. return nullptr;
  967. };
  968. const auto k = std::clamp (key, 0, 127);
  969. // a child with Add to key (Split children) sounds its own pitch on its key, as on a channel (the rack's key shift)
  970. auto keyOf = [&] (int node) {
  971. const auto& d = l->defs[(std::size_t) node];
  972. return d.misc.addToKey && d.instrument != InstrumentKind::sampler ? std::clamp (key + 60 - d.misc.rootNote, 0, 127) : key;
  973. };
  974. const auto one = self.layer.random || self.layer.sequential;
  975. if (type == 1)
  976. {
  977. std::array<layer::Pick, 64> picks;
  978. const auto n = layer::pick (self, l->defs, k, l->random, l->turn, picks.data(), (int) picks.size());
  979. if (one)
  980. l->picked[(std::size_t) k] = n > 0 ? picks[0].child : -1;
  981. const auto level = layer::levelGain (self);
  982. for (int p = 0; p < n; ++p)
  983. if (const auto* c = childOf (picks[(std::size_t) p].child))
  984. f (child (*c), keyOf (c->node), level * picks[(std::size_t) p].gain, pan, cents, true);
  985. }
  986. else if (type == 0 && one && l->picked[(std::size_t) k] >= 0)
  987. {
  988. if (const auto* c = childOf (l->picked[(std::size_t) k]))
  989. f (child (*c), keyOf (c->node), 1.0f, pan, cents, true);
  990. l->picked[(std::size_t) k] = -1;
  991. }
  992. else // (a note off of every child — also when the Layer was rebuilt while the note was held — or a CC / bend)
  993. for (const auto& c : l->children)
  994. f (child (c), keyOf (c.node), 1.0f, pan, cents, true);
  995. }
  996. }
  997. void Graph::choke (int zone) noexcept
  998. {
  999. // Live's choke groups (round 190ec): a pad that starts a note stops every other pad of its group (their
  1000. // instruments' cut: the sampler's short declick, as an FL cut group)
  1001. const auto& self = zoneStates[(std::size_t) zone].zone;
  1002. for (std::size_t z = 0; z < zoneStates.size(); ++z)
  1003. {
  1004. const auto& other = zoneStates[z].zone;
  1005. if ((int) z == zone || other.choke != self.choke || other.chokeNode < 0 || other.chokeNode == self.chokeNode
  1006. || other.chokeNode >= (int) nodes.size())
  1007. continue;
  1008. if (auto& i = nodes[(std::size_t) other.chokeNode]->instrument)
  1009. i->cut();
  1010. }
  1011. }
  1012. bool Graph::zoneGate (int zone, bool on, int& key, int midiChannel, float& velocity) noexcept
  1013. {
  1014. if (zone < 0 || zone >= (int) zoneStates.size())
  1015. return true;
  1016. auto& s = zoneStates[(std::size_t) zone];
  1017. const auto k = (std::size_t) std::clamp (key, 0, 127);
  1018. const auto bit = (std::uint16_t) (1u << (midiChannel < 0 ? 0 : (midiChannel & 15)));
  1019. if (! on)
  1020. {
  1021. if ((s.held[k] & bit) == 0)
  1022. return false;
  1023. s.held[k] = (std::uint16_t) (s.held[k] & ~bit);
  1024. if (s.zone.playKey >= 0)
  1025. key = s.zone.playKey;
  1026. return true;
  1027. }
  1028. const auto& surface = active->surface;
  1029. const auto selector = s.zone.selector >= 0 && s.zone.selector < (int) surface.size()
  1030. ? rack::zoneSelector (s.zone, surface[(std::size_t) s.zone.selector])
  1031. : 0.0f;
  1032. const auto v = rack::zoneVelocity (s.zone, (int) k, velocity, selector);
  1033. if (v <= 0.0f)
  1034. return false;
  1035. velocity = v;
  1036. s.held[k] = (std::uint16_t) (s.held[k] | bit);
  1037. if (s.zone.choke > 0)
  1038. choke (zone);
  1039. if (s.zone.playKey >= 0)
  1040. key = s.zone.playKey;
  1041. return true;
  1042. }
  1043. void Graph::deliver (int pin, bool on, int key, float velocityIn, int midiChannel) noexcept
  1044. {
  1045. wholeAsleep = false; // (round 190ts: something comes in: awake, idle() says so at once)
  1046. quietSamples = 0;
  1047. if (pin < 0 || pin >= (int) pinTargets.size())
  1048. return;
  1049. forLayeredTargets (pinTargets[(std::size_t) pin], on ? 1 : 0, key, [&] (const MidiTarget& t, int k, float gain, float pan, float cents, bool viaLayer) {
  1050. auto velocity = velocityIn;
  1051. if (t.zone >= 0 && ! zoneGate (t.zone, on, k, midiChannel, velocity)) // (k: a Drum Rack pad's Play note)
  1052. return;
  1053. if (t.vfx)
  1054. {
  1055. // into the VFX node's processor at the next piece's start, with the note's properties
  1056. if (auto& q = vfxQueues[(std::size_t) t.node])
  1057. {
  1058. vfx::Event e;
  1059. e.type = on ? vfx::Event::Type::on : vfx::Event::Type::off;
  1060. e.voice.key = k;
  1061. e.voice.velocity = on ? std::max (1.0e-6f, velocity * gain) : velocity;
  1062. e.voice.pan = std::clamp (nextVoice.pan + pan, -1.0f, 1.0f);
  1063. e.voice.cents = nextVoice.cents + cents;
  1064. e.voice.modX = nextVoice.modX;
  1065. e.voice.modY = nextVoice.modY;
  1066. e.voice.release = nextVoice.release;
  1067. e.voice.porta = nextVoice.porta;
  1068. const auto channel = t.midiChannel >= 0 ? t.midiChannel : midiChannel;
  1069. e.voice.colour = channel >= 0 ? (channel & 15) : nextVoice.colour;
  1070. e.id = vfx::inputId (k, e.voice.colour);
  1071. q->in.add (e);
  1072. }
  1073. return;
  1074. }
  1075. if (auto& i = nodes[(std::size_t) t.node]->instrument)
  1076. {
  1077. const auto channel = t.midiChannel >= 0 ? t.midiChannel : midiChannel;
  1078. auto v = velocity;
  1079. if (on && viaLayer) // a Layer's child (round 165c): the Layer's pan, pitch and level on top of the note's
  1080. {
  1081. i->setNextNoteExpression (std::clamp (nextVoice.pan + pan, -1.0f, 1.0f), nextVoice.cents + cents, nextVoice.porta);
  1082. if (gain != 1.0f && ! i->setNextNoteGain (gain))
  1083. v = std::max (1.0e-6f, v * gain);
  1084. }
  1085. if (channel < 0)
  1086. on ? i->noteOn (k, v) : i->noteOff (k);
  1087. else
  1088. on ? i->noteOnMidi (k, v, channel) : i->noteOffMidi (k, channel);
  1089. }
  1090. });
  1091. if (! on)
  1092. nextVoice.release = 0.5f;
  1093. else
  1094. nextVoice = {};
  1095. }
  1096. void Graph::noteOnPort (int port, int key, float velocity, int midiChannel) noexcept
  1097. {
  1098. if (port >= 0 && port < patchMidiPorts)
  1099. deliver (patchMidiPortPin (port), true, key, velocity, midiChannel);
  1100. }
  1101. void Graph::noteOffPort (int port, int key, int midiChannel) noexcept
  1102. {
  1103. if (port >= 0 && port < patchMidiPorts)
  1104. deliver (patchMidiPortPin (port), false, key, 0.0f, midiChannel);
  1105. }
  1106. void Graph::queueTimed (int pin, int key, float velocity, int midiChannel, int offset) noexcept
  1107. {
  1108. wholeAsleep = false; // (round 190ts: something comes in: awake, idle() says so at once)
  1109. quietSamples = 0;
  1110. if (pin < 0 || pin >= (int) pinTargets.size() || pinTargets[(std::size_t) pin].empty() || timedCount >= timedCapacity)
  1111. return;
  1112. timed[(std::size_t) timedCount++] = { pin, key, midiChannel, std::max (0, offset), velocity };
  1113. }
  1114. void Graph::queueNoteOnPort (int port, int key, float velocity, int midiChannel, int offset) noexcept
  1115. {
  1116. if (port >= 0 && port < patchMidiPorts)
  1117. queueTimed (patchMidiPortPin (port), key, std::max (velocity, 1.0e-6f), midiChannel, offset);
  1118. }
  1119. void Graph::queueNoteOffPort (int port, int key, int midiChannel, int offset) noexcept
  1120. {
  1121. if (port >= 0 && port < patchMidiPorts)
  1122. queueTimed (patchMidiPortPin (port), key, 0.0f, midiChannel, offset);
  1123. }
  1124. void Graph::routeNote (const std::vector<MidiTarget>& targets, int sourceNode, bool on, int key, float velocityIn, int midiChannel, int offset) noexcept
  1125. {
  1126. forLayeredTargets (targets, on ? 1 : 0, key, [&] (const MidiTarget& t, int k, float gain, float pan, float cents, bool) {
  1127. auto velocity = velocityIn;
  1128. if (t.zone >= 0 && ! zoneGate (t.zone, on, k, midiChannel, velocity))
  1129. return;
  1130. const auto channel = t.midiChannel >= 0 ? t.midiChannel : midiChannel;
  1131. vfx::Event e;
  1132. e.type = on ? vfx::Event::Type::on : vfx::Event::Type::off;
  1133. e.offset = offset;
  1134. e.voice.key = k;
  1135. e.voice.velocity = velocity;
  1136. e.voice.pan = pan;
  1137. e.voice.cents = cents;
  1138. e.voice.colour = channel >= 0 ? (channel & 15) : 0;
  1139. e.id = vfx::inputId (k, e.voice.colour);
  1140. if (sourceNode >= 0)
  1141. e.id += (sourceNode + 1) * (1 << 20); // (ids of different sources never meet)
  1142. if (t.vfx)
  1143. {
  1144. if (auto& q = vfxQueues[(std::size_t) t.node])
  1145. {
  1146. if (on)
  1147. e.voice.velocity = std::max (1.0e-6f, velocity * gain);
  1148. q->in.add (e);
  1149. }
  1150. }
  1151. else if (noteOuts.size() < noteOuts.capacity())
  1152. noteOuts.push_back ({ t.node, channel, e, gain });
  1153. });
  1154. }
  1155. template <typename F>
  1156. void Graph::forNoteTargets (F&& f) noexcept
  1157. {
  1158. if (pinTargets.empty())
  1159. return;
  1160. forLayeredTargets (pinTargets[0], 2, 60, [&] (const MidiTarget& t, int, float, float, float, bool) { // (a Layer's children too)
  1161. if (auto& i = nodes[(std::size_t) t.node]->instrument)
  1162. f (*i);
  1163. });
  1164. }
  1165. void Graph::midiMessage (const std::uint8_t* bytes, int size) noexcept
  1166. {
  1167. wholeAsleep = false; // (round 190ts: something comes in: awake, idle() says so at once)
  1168. quietSamples = 0;
  1169. forNoteTargets ([&] (Instrument& i) { i.midiMessage (bytes, size); });
  1170. }
  1171. void Graph::pitchBend (float semitones) noexcept
  1172. {
  1173. forNoteTargets ([&] (Instrument& i) { i.pitchBend (semitones); });
  1174. }
  1175. void Graph::controlChange (int cc, float value) noexcept
  1176. {
  1177. forNoteTargets ([&] (Instrument& i) { i.controlChange (cc, value); });
  1178. }
  1179. // Issue #271 (round 190qo): a slide note's velocity / pan / Mod X / Y on the channel's own notes ("From LYNX SHARE" pin 0
  1180. // Notes), passed to what those notes reach — FL's Patcher hands its notes' properties on (FL 2026 /R render of its Patcher
  1181. // render test, a 3x Osc inside: the slide fades as 3x Osc's own channel does)
  1182. void Graph::voiceProperty (int key, int prop, float value) noexcept
  1183. {
  1184. if (! voiceProps.load (std::memory_order_relaxed) || pinTargets.empty())
  1185. return;
  1186. forLayeredTargets (pinTargets[0], 2, key, [&] (const MidiTarget& t, int k, float, float, float, bool) {
  1187. if (t.vfx)
  1188. {
  1189. if (auto& q = vfxQueues[(std::size_t) t.node])
  1190. {
  1191. vfx::Event e;
  1192. e.type = vfx::Event::Type::prop;
  1193. e.voice.key = k;
  1194. e.voice.colour = (t.midiChannel >= 0 ? t.midiChannel : 0) & 15;
  1195. e.id = vfx::inputId (k, e.voice.colour);
  1196. e.prop = (vfx::Prop) std::clamp (prop, 0, 4);
  1197. e.value = value;
  1198. q->in.add (e);
  1199. }
  1200. }
  1201. else if (auto& i = nodes[(std::size_t) t.node]->instrument)
  1202. i->voiceProperty (k, prop, value);
  1203. });
  1204. }
  1205. void Graph::voicePropertyPort (int port, int key, int prop, float value, int midiChannel) noexcept
  1206. {
  1207. if (port < 0 || port >= patchMidiPorts)
  1208. return;
  1209. forLayeredTargets (pinTargets[(std::size_t) patchMidiPortPin (port)], 2, key, [&] (const MidiTarget& t, int k, float, float, float, bool) {
  1210. if (t.vfx)
  1211. {
  1212. if (auto& q = vfxQueues[(std::size_t) t.node])
  1213. {
  1214. vfx::Event e;
  1215. e.type = vfx::Event::Type::prop;
  1216. e.voice.key = k;
  1217. e.voice.colour = (t.midiChannel >= 0 ? t.midiChannel : std::max (0, midiChannel)) & 15;
  1218. e.id = vfx::inputId (k, e.voice.colour);
  1219. e.prop = (vfx::Prop) std::clamp (prop, 0, 4);
  1220. e.value = value;
  1221. q->in.add (e);
  1222. }
  1223. }
  1224. else if (auto& i = nodes[(std::size_t) t.node]->instrument)
  1225. i->voiceProperty (k, prop, value);
  1226. });
  1227. }
  1228. int Graph::takeHostEvents (Instrument::PortEvent* out, int max) noexcept
  1229. {
  1230. const auto n = std::min (hostEventCount, std::max (0, max));
  1231. for (int k = 0; k < n; ++k)
  1232. out[k] = hostEvents[(std::size_t) k];
  1233. for (int k = n; k < hostEventCount; ++k)
  1234. hostEvents[(std::size_t) (k - n)] = hostEvents[(std::size_t) k];
  1235. hostEventCount -= n;
  1236. return n;
  1237. }
  1238. bool Graph::takesMidiPort (int port) const noexcept
  1239. {
  1240. return port >= 0 && port < patchMidiPorts && ! pinTargets[(std::size_t) patchMidiPortPin (port)].empty();
  1241. }
  1242. void Graph::allNotesOff() noexcept
  1243. {
  1244. timedCount = 0;
  1245. // the VFX nodes' voices end (their instruments stop below anyway); their queues empty
  1246. for (const auto i : vfxOrder)
  1247. {
  1248. auto& q = *vfxQueues[(std::size_t) i];
  1249. q.in.clear();
  1250. q.out.clear();
  1251. nodes[(std::size_t) i]->vfx->releaseAll (q.out);
  1252. q.out.clear();
  1253. }
  1254. for (auto& n : nodes)
  1255. if (n->instrument != nullptr)
  1256. n->instrument->allNotesOff();
  1257. for (auto& z : zoneStates) // (round 183c: nothing is held through a rack chain's zones any more)
  1258. z.held.fill (0);
  1259. }
  1260. void Graph::cut() noexcept
  1261. {
  1262. for (auto& n : nodes)
  1263. if (n->instrument != nullptr)
  1264. n->instrument->cut();
  1265. }
  1266. void Graph::slideTo (int key, float cents, float samples) noexcept
  1267. {
  1268. for (const auto t : noteTargets)
  1269. {
  1270. if ((std::size_t) t < layers.size() && layers[(std::size_t) t] != nullptr) // (a Layer: its children slide, round 165c)
  1271. for (const auto& c : layers[(std::size_t) t]->children)
  1272. if (auto& i = nodes[(std::size_t) c.node]->instrument)
  1273. i->slideTo (key, cents, samples);
  1274. if (auto& i = nodes[(std::size_t) t]->instrument)
  1275. i->slideTo (key, cents, samples);
  1276. }
  1277. }
  1278. void Graph::setNextNoteModulation (float modX, float modY) noexcept
  1279. {
  1280. nextVoice.modX = modX;
  1281. nextVoice.modY = modY;
  1282. }
  1283. void Graph::setNextNoteRelease (float velocity) noexcept { nextVoice.release = velocity; }
  1284. void Graph::setNextNoteColour (int colour) noexcept { nextVoice.colour = colour & 15; }
  1285. void Graph::setNextNoteExpression (float pan, float cents, bool porta) noexcept
  1286. {
  1287. nextVoice.pan = pan;
  1288. nextVoice.cents = cents;
  1289. nextVoice.porta = porta;
  1290. for (const auto t : noteTargets)
  1291. if (auto& i = nodes[(std::size_t) t]->instrument)
  1292. i->setNextNoteExpression (pan, cents, porta);
  1293. }
  1294. bool Graph::hasInstruments() const noexcept
  1295. {
  1296. return std::any_of (nodes.begin(), nodes.end(), [] (const auto& n) { return n->instrument != nullptr; });
  1297. }
  1298. bool Graph::instrumentsIdle() const noexcept
  1299. {
  1300. // (a VFX node that holds voices or plays on its own — a sequencer — keeps the graph running; so do notes still on
  1301. // their way: queued, waiting at a VFX node for the next piece, or played to the host and not yet taken (round 183c: a
  1302. // MIDI Effect Rack's chains are VFX nodes only, and a note reaches them one piece after it came in))
  1303. if (timedCount > 0 || hostEventCount > 0
  1304. || std::any_of (vfxQueues.begin(), vfxQueues.end(), [] (const auto& q) { return q != nullptr && q->in.size() > 0; }))
  1305. return false;
  1306. return std::all_of (nodes.begin(), nodes.end(), [] (const auto& n) {
  1307. return (n->instrument == nullptr || n->instrument->idle()) && (n->vfx == nullptr || ! n->vfx->busy());
  1308. });
  1309. }
  1310. float Graph::controlOutput (int) const noexcept { return 0.0f; }
  1311. void Graph::setPublished (int k, float v) noexcept
  1312. {
  1313. if (k < 0 || k >= (int) published.size())
  1314. return;
  1315. const auto& p = published[(std::size_t) k];
  1316. if (p.node == patchSurface && p.param >= 0) // a rack's macro / selector (round 183c): the Surface control, at the next block
  1317. {
  1318. publishedValues[(std::size_t) k] = std::clamp (mapControl (p.curve, v), 0.0f, 1.0f);
  1319. return;
  1320. }
  1321. if (p.node < 0 || p.node >= (int) nodes.size() || p.param < 0)
  1322. return;
  1323. const auto value = mapControl (p.curve, v);
  1324. auto& node = *nodes[(std::size_t) p.node];
  1325. if (node.generator)
  1326. {
  1327. if (node.instrument != nullptr)
  1328. node.instrument->setParameter (p.param, value);
  1329. }
  1330. else if (node.plugin)
  1331. node.effect->setParameter (p.param, value);
  1332. else if (p.param < maxEffectParams)
  1333. publishedValues[(std::size_t) k] = value; // (applied at the start of each block, over the UI's values)
  1334. }
  1335. const float* Graph::auxOutput (int index, int side) const noexcept
  1336. {
  1337. return index >= 0 && index < (int) aux.size() ? aux[(std::size_t) index][(std::size_t) (side & 1)].data() : nullptr;
  1338. }
  1339. std::shared_ptr<Effect> Graph::effectAt (int node) const
  1340. {
  1341. return node >= 0 && node < (int) nodes.size() ? nodes[(std::size_t) node]->effect : nullptr;
  1342. }
  1343. std::shared_ptr<Instrument> Graph::instrumentAt (int node) const
  1344. {
  1345. return node >= 0 && node < (int) nodes.size() ? nodes[(std::size_t) node]->instrument : nullptr;
  1346. }
  1347. namespace
  1348. {
  1349. std::uint64_t nowNs() noexcept
  1350. {
  1351. return (std::uint64_t) std::chrono::duration_cast<std::chrono::nanoseconds> (std::chrono::steady_clock::now().time_since_epoch()).count();
  1352. }
  1353. float blockPeak (const float* l, const float* r, int n) noexcept
  1354. {
  1355. float p = 0.0f;
  1356. for (int i = 0; i < n; ++i)
  1357. p = std::max (p, std::max (std::abs (l[i]), std::abs (r[i])));
  1358. return p;
  1359. }
  1360. void raisePeak (std::atomic<float>& a, float p) noexcept
  1361. {
  1362. if (p > a.load (std::memory_order_relaxed))
  1363. a.store (p, std::memory_order_relaxed);
  1364. }
  1365. } // namespace
  1366. float Graph::takeNodePeak (int node) noexcept
  1367. {
  1368. return node >= 0 && node < (int) nodes.size() ? nodes[(std::size_t) node]->peak.exchange (0.0f, std::memory_order_relaxed) : 0.0f;
  1369. }
  1370. std::uint64_t Graph::nodeNanoseconds (int node) const noexcept
  1371. {
  1372. return node >= 0 && node < (int) nodes.size() ? nodes[(std::size_t) node]->ns.load (std::memory_order_relaxed) : 0u;
  1373. }
  1374. void Graph::process (const float* inL, const float* inR, const float* scL, const float* scR, float* outL, float* outR, int n, double bpm) noexcept
  1375. {
  1376. const auto watched = watchLeft.load (std::memory_order_relaxed) > 0; // round 190ld (View › Activity / Performance)
  1377. const auto start = watched ? nowNs() : 0u;
  1378. if (watched)
  1379. raisePeak (inputPeak, blockPeak (inL, inR, n));
  1380. for (int done = 0; done < n; done += capacity)
  1381. {
  1382. const auto piece = std::min (capacity, n - done);
  1383. pieceOffset = hwOffset + done;
  1384. processPiece (inL + done, inR + done, scL != nullptr ? scL + done : nullptr, scR != nullptr ? scR + done : nullptr, outL + done,
  1385. outR + done, piece, bpm);
  1386. }
  1387. if (watched)
  1388. {
  1389. graphNs.fetch_add (nowNs() - start, std::memory_order_relaxed);
  1390. framesWatched.fetch_add ((std::uint64_t) n, std::memory_order_relaxed);
  1391. watchLeft.fetch_sub (n, std::memory_order_relaxed);
  1392. }
  1393. }
  1394. void Graph::processPiece (const float* inL, const float* inR, const float* scL, const float* scR, float* outL, float* outR, int n, double bpm) noexcept
  1395. {
  1396. applyPending();
  1397. auto& values = *active;
  1398. for (std::size_t k = 0; k < publishedValues.size(); ++k)
  1399. if (! std::isnan (publishedValues[k]))
  1400. {
  1401. if (published[k].node == patchSurface) // (round 183c)
  1402. {
  1403. if ((std::size_t) published[k].param < values.surface.size())
  1404. values.surface[(std::size_t) published[k].param] = publishedValues[k];
  1405. }
  1406. else
  1407. values.nodes[(std::size_t) published[k].node].params[(std::size_t) published[k].param] = publishedValues[k];
  1408. }
  1409. // control cables: the source's latest output moves the target's parameter (one block of lag, as the mixer's links)
  1410. for (auto& c : controls)
  1411. {
  1412. auto raw = 0.0f;
  1413. if (c.from == patchSurface) // the Surface tab's control (round 151)
  1414. raw = c.output < (int) values.surface.size() ? values.surface[(std::size_t) c.output] : 0.0f;
  1415. else if (c.fromParam >= 0) // a node's parameter output (round 171b): its current value
  1416. {
  1417. const auto& source = *nodes[(std::size_t) c.from];
  1418. if (source.generator)
  1419. raw = source.instrument != nullptr ? source.instrument->parameterValue (c.fromParam) : -1.0f;
  1420. else if (source.plugin)
  1421. raw = source.effect != nullptr ? source.effect->parameterValue (c.fromParam) : -1.0f;
  1422. else
  1423. raw = values.nodes[(std::size_t) c.from].params[(std::size_t) c.fromParam];
  1424. if (! (raw >= 0.0f)) // (a parameter whose value can't be read: nothing to send)
  1425. continue;
  1426. }
  1427. else
  1428. {
  1429. const auto& source = *nodes[(std::size_t) c.from];
  1430. raw = source.effect != nullptr && ! source.generator ? source.effect->controlOutput (c.output)
  1431. : source.instrument != nullptr ? source.instrument->controlOutput (c.output)
  1432. : 0.0f;
  1433. }
  1434. const auto v = mapControl (c.curve, raw);
  1435. auto& target = *nodes[(std::size_t) c.to];
  1436. // a plugin / instrument target gets the value when it changes (round 171b): a hosted plugin is not called
  1437. // with the same value every block, and a change made in its own window stays until the source moves
  1438. if (target.generator || target.plugin)
  1439. {
  1440. if (v == c.sent)
  1441. continue;
  1442. c.sent = v;
  1443. }
  1444. if (target.generator)
  1445. {
  1446. if (target.instrument != nullptr)
  1447. target.instrument->setParameter (c.param, v);
  1448. }
  1449. else if (target.plugin)
  1450. target.effect->setParameter (c.param, v);
  1451. else
  1452. values.nodes[(std::size_t) c.to].params[(std::size_t) c.param] = v;
  1453. }
  1454. noteOuts.clear();
  1455. // notes queued at their sample (the rack's notes into a mixer-slot Patcher, round 164f): the ones in this piece
  1456. if (timedCount > 0)
  1457. {
  1458. int kept = 0;
  1459. for (int k = 0; k < timedCount; ++k)
  1460. {
  1461. auto t = timed[(std::size_t) k];
  1462. if (t.offset < n)
  1463. routeNote (pinTargets[(std::size_t) t.pin], -1, t.velocity > 0.0f, t.key, t.velocity, t.midiChannel, t.offset);
  1464. else
  1465. {
  1466. t.offset -= n;
  1467. timed[(std::size_t) kept++] = t;
  1468. }
  1469. }
  1470. timedCount = kept;
  1471. }
  1472. // what the hosted plugin nodes sent out in the last piece (round 164f), at this piece's start
  1473. for (const auto i : midiSources)
  1474. {
  1475. std::array<Instrument::MidiOutNote, 128> sent;
  1476. auto& node = *nodes[(std::size_t) i];
  1477. const auto count = node.instrument->takeMidiOutput (sent.data(), (int) sent.size());
  1478. for (int k = 0; k < count; ++k)
  1479. routeNote (node.midiOutTargets, i, sent[(std::size_t) k].velocity > 0.0f, sent[(std::size_t) k].key, sent[(std::size_t) k].velocity, -1, 0);
  1480. }
  1481. if (hasVfx)
  1482. runVfx (n, bpm);
  1483. // round 190ts (setStoppedSleep): every node asleep, nothing coming in and the delays emptied: the graph is skipped
  1484. // (not while an editor watches its nodes: View › Activity / Performance)
  1485. if (sleepOk && watchLeft.load (std::memory_order_relaxed) > 0)
  1486. setStoppedSleep (false);
  1487. if (sleepOk && canWholeSleep)
  1488. {
  1489. const auto quiet = allNodesAsleep && noteOuts.empty() && timedCount == 0 && quietBlock (inL, inR, n)
  1490. && (scL == nullptr || scR == nullptr || quietBlock (scL, scR, n)) && instrumentsIdle();
  1491. quietSamples = quiet ? quietSamples + n : 0;
  1492. wholeAsleep = quiet && quietSamples > latency;
  1493. if (wholeAsleep)
  1494. {
  1495. std::fill (outL, outL + n, 0.0f);
  1496. std::fill (outR, outR + n, 0.0f);
  1497. for (auto& a : aux)
  1498. for (auto& side : a)
  1499. std::fill (side.begin(), side.begin() + n, 0.0f);
  1500. return;
  1501. }
  1502. }
  1503. if (noteOuts.empty())
  1504. {
  1505. renderNodes (inL, inR, scL, scR, outL, outR, 0, n, bpm);
  1506. return;
  1507. }
  1508. // what the VFX nodes, the queued notes and the plugins play lands at its sample: the piece is rendered in parts
  1509. // between those samples
  1510. sortNoteOuts();
  1511. std::size_t next = 0;
  1512. for (int position = 0; position < n;)
  1513. {
  1514. while (next < noteOuts.size() && noteOuts[next].event.offset <= position)
  1515. playNoteOut (noteOuts[next++]);
  1516. const auto end = next < noteOuts.size() ? std::min (n, noteOuts[next].event.offset) : n;
  1517. if (end > position)
  1518. renderNodes (inL + position, inR + position, scL != nullptr ? scL + position : nullptr, scR != nullptr ? scR + position : nullptr,
  1519. outL + position, outR + position, position, end - position, bpm);
  1520. position = end;
  1521. }
  1522. while (next < noteOuts.size())
  1523. playNoteOut (noteOuts[next++]);
  1524. }
  1525. void Graph::runVfx (int n, double bpm) noexcept
  1526. {
  1527. vfx::Transport t;
  1528. t.sampleRate = rate;
  1529. t.bpm = bpm;
  1530. t.ticks = ticks;
  1531. t.playing = playing;
  1532. for (const auto i : vfxOrder)
  1533. {
  1534. auto& q = *vfxQueues[(std::size_t) i];
  1535. q.in.sortByOffset();
  1536. q.out.clear();
  1537. nodes[(std::size_t) i]->vfx->process (&q.in[0], q.in.size(), n, t, q.out);
  1538. q.in.clear();
  1539. for (int k = 0; k < q.out.size(); ++k)
  1540. routeVfxOutput (i, q.out[k]);
  1541. q.out.clear();
  1542. }
  1543. ticks += (double) n * bpm * (double) ppq / (60.0 * rate);
  1544. }
  1545. void Graph::sortNoteOuts() noexcept
  1546. {
  1547. // (stable insertion sort in place: std::stable_sort may allocate on the audio thread)
  1548. for (std::size_t i = 1; i < noteOuts.size(); ++i)
  1549. {
  1550. const auto o = noteOuts[i];
  1551. auto j = i;
  1552. for (; j > 0 && o.event.offset < noteOuts[j - 1].event.offset; --j)
  1553. noteOuts[j] = noteOuts[j - 1];
  1554. noteOuts[j] = o;
  1555. }
  1556. }
  1557. void Graph::routeVfxOutput (int node, const vfx::Event& e) noexcept
  1558. {
  1559. const auto& targets = nodes[(std::size_t) node]->vfxTargets;
  1560. if (e.output < 0 || e.output >= (int) targets.size())
  1561. return;
  1562. // cabled to "To LYNX SHARE" MIDI ports (round 165c): the rack plays it on those ports at the next chunk
  1563. if (e.type != vfx::Event::Type::program)
  1564. for (const auto port : nodes[(std::size_t) node]->vfxHostPorts[(std::size_t) e.output])
  1565. if (hostEventCount < hostEventCapacity)
  1566. {
  1567. auto& h = hostEvents[(std::size_t) hostEventCount++];
  1568. h.port = port;
  1569. h.key = e.voice.key;
  1570. h.channel = e.voice.colour & 15;
  1571. h.prop = e.type == vfx::Event::Type::prop ? (int) e.prop : -1;
  1572. h.value = e.type == vfx::Event::Type::prop ? e.value : e.type == vfx::Event::Type::on ? std::max (1.0e-6f, e.voice.velocity) : 0.0f;
  1573. h.pan = e.voice.pan;
  1574. h.cents = e.voice.cents;
  1575. h.modX = e.voice.modX;
  1576. h.modY = e.voice.modY;
  1577. h.release = e.voice.release;
  1578. }
  1579. const auto type = e.type == vfx::Event::Type::on ? 1 : e.type == vfx::Event::Type::off ? 0 : 2;
  1580. forLayeredTargets (targets[(std::size_t) e.output], type, e.voice.key, [&] (const MidiTarget& t, int k, float gain, float pan, float cents, bool viaLayer) {
  1581. auto ev = e;
  1582. ev.voice.key = k;
  1583. if (viaLayer) // a Layer's child (round 165c)
  1584. {
  1585. ev.voice.pan = std::clamp (ev.voice.pan + pan, -1.0f, 1.0f);
  1586. ev.voice.cents += cents;
  1587. }
  1588. if (t.vfx)
  1589. {
  1590. if (auto& q = vfxQueues[(std::size_t) t.node])
  1591. {
  1592. auto in = ev;
  1593. if (in.type == vfx::Event::Type::on)
  1594. in.voice.velocity = std::max (1.0e-6f, in.voice.velocity * gain);
  1595. in.output = 0;
  1596. in.id = (node + 1) * (1 << 20) + (e.id & ((1 << 20) - 1)); // (ids of different sources never meet)
  1597. if (t.midiChannel >= 0)
  1598. in.voice.colour = t.midiChannel & 15;
  1599. q->in.add (in);
  1600. }
  1601. }
  1602. else if (noteOuts.size() < noteOuts.capacity())
  1603. noteOuts.push_back ({ t.node, t.midiChannel, ev, gain });
  1604. });
  1605. }
  1606. void Graph::playNoteOut (const NoteOut& o) noexcept
  1607. {
  1608. auto& i = nodes[(std::size_t) o.node]->instrument;
  1609. if (i == nullptr)
  1610. return;
  1611. const auto& e = o.event;
  1612. const auto& v = e.voice;
  1613. const auto channel = o.midiChannel >= 0 ? o.midiChannel : v.colour;
  1614. switch (e.type)
  1615. {
  1616. case vfx::Event::Type::on:
  1617. i->setNextNoteExpression (v.pan, v.cents, v.porta);
  1618. i->setNextNoteModulation (v.modX, v.modY);
  1619. i->setNextNoteColour (v.colour);
  1620. {
  1621. auto velocity = v.velocity;
  1622. if (o.gain != 1.0f && ! i->setNextNoteGain (o.gain)) // (a Layer's level, round 165c)
  1623. velocity = std::max (1.0e-6f, velocity * o.gain);
  1624. if (channel > 0)
  1625. i->noteOnMidi (v.key, velocity, channel);
  1626. else
  1627. i->noteOn (v.key, velocity);
  1628. }
  1629. break;
  1630. case vfx::Event::Type::off:
  1631. i->setNextNoteRelease (v.release);
  1632. if (channel > 0)
  1633. i->noteOffMidi (v.key, channel);
  1634. else
  1635. i->noteOff (v.key);
  1636. break;
  1637. case vfx::Event::Type::prop:
  1638. i->voiceProperty (v.key, (int) e.prop, e.value);
  1639. break;
  1640. case vfx::Event::Type::program: // (a VFX Sequencer passing a program change on, round 165c)
  1641. {
  1642. const std::uint8_t m[2] { (std::uint8_t) (0xC0 | (channel & 15)), (std::uint8_t) std::clamp ((int) e.value, 0, 127) };
  1643. i->midiMessage (m, 2);
  1644. break;
  1645. }
  1646. }
  1647. }
  1648. void Graph::renderNodes (const float* inL, const float* inR, const float* scL, const float* scR, float* outL, float* outR, int start, int n,
  1649. double bpm) noexcept
  1650. {
  1651. // (inL…outR point at this part of the piece; the nodes' buffers are indexed from `start`)
  1652. auto& values = *active;
  1653. auto sourceOf = [&] (const AudioWire& w, int side) -> const float* {
  1654. if (w.from == patchFromHost)
  1655. {
  1656. if (w.fromBuffer == 1)
  1657. return (side == 0 ? scL : scR) != nullptr ? (side == 0 ? scL : scR) : zeros.data() + start;
  1658. return side == 0 ? inL : inR;
  1659. }
  1660. return nodes[(std::size_t) w.from]->out[(std::size_t) w.fromBuffer][(std::size_t) side].data() + start;
  1661. };
  1662. auto gather = [&] (const std::vector<int>& list, float* l, float* r) {
  1663. std::fill (l, l + n, 0.0f);
  1664. std::fill (r, r + n, 0.0f);
  1665. for (const auto k : list)
  1666. {
  1667. const auto& w = wires[(std::size_t) k];
  1668. const auto on = values.on[(std::size_t) k] != 0;
  1669. const auto gain = on ? values.gains[(std::size_t) k] : 0.0f;
  1670. const auto* sl = sourceOf (w, 0);
  1671. const auto* sr = sourceOf (w, 1);
  1672. if (w.delay != nullptr)
  1673. {
  1674. w.delay->mixInto (on ? sl : nullptr, on ? sr : nullptr, gain, l, r, n); // (keeps its line running)
  1675. continue;
  1676. }
  1677. if (! on || gain == 0.0f)
  1678. continue;
  1679. for (int i = 0; i < n; ++i)
  1680. {
  1681. l[i] += sl[i] * gain;
  1682. r[i] += sr[i] * gain;
  1683. }
  1684. }
  1685. };
  1686. auto* inBufL = scratch[0].data();
  1687. auto* inBufR = scratch[1].data();
  1688. auto* scBufL = scratch[2].data();
  1689. auto* scBufR = scratch[3].data();
  1690. const auto watched = watchLeft.load (std::memory_order_relaxed) > 0; // round 190ld: per node (View › Activity / Performance)
  1691. std::uint64_t nodeStart = 0;
  1692. auto measured = [&] (Node& node, const float* l, const float* r) {
  1693. const auto end = nowNs();
  1694. node.ns.fetch_add (end - nodeStart, std::memory_order_relaxed);
  1695. raisePeak (node.peak, blockPeak (l, r, n));
  1696. };
  1697. for (const auto i : order)
  1698. {
  1699. auto& node = *nodes[(std::size_t) i];
  1700. auto& v = values.nodes[(std::size_t) i];
  1701. auto* oL = node.out[0][0].data() + start;
  1702. auto* oR = node.out[0][1].data() + start;
  1703. if (watched)
  1704. nodeStart = nowNs();
  1705. if (node.generator)
  1706. {
  1707. std::fill (oL, oL + n, 0.0f);
  1708. std::fill (oR, oR + n, 0.0f);
  1709. // (round 190ts, stopped: an idle instrument is not rendered, as the rack skips an idle channel)
  1710. node.asleep = sleepOk && (node.nested != nullptr ? node.nested->asleep() || node.instrument->idle()
  1711. : node.sleeps && node.instrument->idle());
  1712. if (node.instrument != nullptr && ! node.asleep)
  1713. node.instrument->render (oL, oR, n, 1.0f, 1.0f);
  1714. if (watched)
  1715. measured (node, oL, oR);
  1716. continue;
  1717. }
  1718. gather (node.mainInputs, inBufL, inBufR);
  1719. std::copy (inBufL, inBufL + n, oL);
  1720. std::copy (inBufR, inBufR + n, oR);
  1721. // round 190ts (setStoppedSleep): stopped, a device whose input and output stayed silent past its tail passes its
  1722. // input through without being called
  1723. auto quietIn = false, skip = false;
  1724. if (sleepOk && node.sleeps)
  1725. {
  1726. quietIn = quietBlock (inBufL, inBufR, n);
  1727. if (! quietIn)
  1728. node.silentSamples = 0;
  1729. else if (node.silentSamples >= sleepHold (node))
  1730. skip = true;
  1731. }
  1732. node.asleep = skip;
  1733. if (v.enabled && v.mix > 0.0f && ! skip)
  1734. {
  1735. if (node.sidechain)
  1736. {
  1737. gather (node.sideInputs, scBufL, scBufR);
  1738. node.effect->setSidechain (scBufL, scBufR);
  1739. }
  1740. if (node.hardware) // a Hardware Insert (or a Patcher holding one): this part's device buses (round 165c)
  1741. node.effect->setHardwareIo (hwIn, hwOut, pieceOffset + start);
  1742. node.effect->process (oL, oR, n, v.params, bpm);
  1743. if (v.mix < 0.999f)
  1744. for (int k = 0; k < n; ++k)
  1745. {
  1746. oL[k] = inBufL[k] + (oL[k] - inBufL[k]) * v.mix;
  1747. oR[k] = inBufR[k] + (oR[k] - inBufR[k]) * v.mix;
  1748. }
  1749. }
  1750. for (std::size_t h = 0; h < node.heads.size(); ++h)
  1751. {
  1752. auto* hL = node.out[1 + h][0].data() + start;
  1753. auto* hR = node.out[1 + h][1].data() + start;
  1754. std::copy (inBufL, inBufL + n, hL);
  1755. std::copy (inBufR, inBufR + n, hR);
  1756. if (node.heads[h].effect != nullptr && ! skip)
  1757. node.heads[h].effect->process (hL, hR, n, v.heads[h], bpm);
  1758. const auto g = v.headGains[h];
  1759. if (g != 1.0f)
  1760. for (int k = 0; k < n; ++k)
  1761. {
  1762. hL[k] *= g;
  1763. hR[k] *= g;
  1764. }
  1765. }
  1766. if (sleepOk && node.sleeps && ! skip)
  1767. {
  1768. // (its tail: silent input and silent outputs count towards the hold)
  1769. auto quietOut = quietIn && quietBlock (oL, oR, n);
  1770. for (std::size_t h = 0; h < node.heads.size() && quietOut; ++h)
  1771. quietOut = quietBlock (node.out[1 + h][0].data() + start, node.out[1 + h][1].data() + start, n);
  1772. node.silentSamples = quietOut ? node.silentSamples + n : 0;
  1773. }
  1774. else if (sleepOk && node.nested != nullptr)
  1775. node.asleep = node.nested->asleep();
  1776. if (watched)
  1777. measured (node, oL, oR);
  1778. }
  1779. if (sleepOk)
  1780. allNodesAsleep = std::all_of (nodes.begin(), nodes.end(), [] (const auto& x) { return x->asleep || x->vfx != nullptr; });
  1781. // "To LYNX SHARE": the main output and the extra ones
  1782. gather (outputs[0], inBufL, inBufR);
  1783. std::copy (inBufL, inBufL + n, outL);
  1784. std::copy (inBufR, inBufR + n, outR);
  1785. for (std::size_t bus = 1; bus < outputs.size(); ++bus)
  1786. gather (outputs[bus], aux[bus - 1][0].data() + start, aux[bus - 1][1].data() + start);
  1787. }
  1788. // ---------------------------------------------------------------------------------------------------------------
  1789. namespace
  1790. {
  1791. class PatcherEffect final : public Effect
  1792. {
  1793. public:
  1794. PatcherEffect (const EffectSlot& slot, double sampleRate, const Factories& factories, const Graph* previous)
  1795. : graph (slot.patcher, sampleRate, factories, previous)
  1796. {
  1797. }
  1798. void prepare (double sampleRate) noexcept override { graph.prepare (sampleRate); }
  1799. void reset() noexcept override { graph.reset(); }
  1800. void setHardwareIo (const LiveInput* in, HardwareOutput* out, int offset) noexcept override
  1801. {
  1802. hwIn = in;
  1803. hwOut = out;
  1804. hwOffset = offset;
  1805. }
  1806. void process (float* l, float* r, int n, const EffectParams&, double bpm) noexcept override
  1807. {
  1808. for (int done = 0; done < n; done += Graph::capacity)
  1809. {
  1810. const auto piece = std::min (Graph::capacity, n - done);
  1811. graph.setHardwareIo (hwIn, hwOut, hwOffset + done);
  1812. graph.process (l + done, r + done, side ? sideL + done : nullptr, side ? sideR + done : nullptr, l + done, r + done, piece, bpm);
  1813. // the first extra output goes to its insert like a Fruity Send (the rack pulls it from there)
  1814. if (sendL != nullptr && sendR != nullptr && graph.auxOutputs() > 0)
  1815. {
  1816. const auto* al = graph.auxOutput (0, 0);
  1817. const auto* ar = graph.auxOutput (0, 1);
  1818. for (int i = 0; i < piece; ++i)
  1819. {
  1820. sendL[done + i] += al[i];
  1821. sendR[done + i] += ar[i];
  1822. }
  1823. }
  1824. }
  1825. side = false;
  1826. }
  1827. void setSendOutput (float* l, float* r) noexcept override
  1828. {
  1829. sendL = l;
  1830. sendR = r;
  1831. }
  1832. void setParameter (int index, float value) noexcept override { graph.setPublished (index, value); }
  1833. void setSongPosition (double ticks) noexcept override { graph.setSongPosition (ticks); }
  1834. void setPlaying (bool playing) noexcept override { graph.setPlaying (playing); }
  1835. void setStoppedSleep (bool on) noexcept override { graph.setStoppedSleep (on); } // (round 190ts)
  1836. void setSidechain (const float* l, const float* r) noexcept override
  1837. {
  1838. sideL = l;
  1839. sideR = r;
  1840. side = l != nullptr && r != nullptr;
  1841. }
  1842. void setHeldNotes (const NoteMask* channels, int count) noexcept override { graph.setHeldNotes (channels, count); }
  1843. bool followsHeldNotes() const noexcept override { return graph.followsHeldNotes(); } // (round 190kz)
  1844. int latencySamples() const noexcept override { return graph.latencySamples(); }
  1845. Graph graph;
  1846. private:
  1847. const float* sideL = nullptr;
  1848. const float* sideR = nullptr;
  1849. bool side = false;
  1850. float* sendL = nullptr;
  1851. float* sendR = nullptr;
  1852. const LiveInput* hwIn = nullptr;
  1853. HardwareOutput* hwOut = nullptr;
  1854. int hwOffset = 0;
  1855. };
  1856. class PatcherInstrument final : public Instrument
  1857. {
  1858. public:
  1859. PatcherInstrument (const ChannelDef& channel, double sampleRate, const Factories& factories, const Graph* previous)
  1860. : graph (channel.patcher, sampleRate, factories, previous)
  1861. {
  1862. for (auto& s : buffer)
  1863. s.assign ((std::size_t) Graph::capacity, 0.0f);
  1864. accumulated.resize ((std::size_t) graph.auxOutputs());
  1865. tracks = std::make_unique<std::atomic<int>[]> ((std::size_t) std::max (1, graph.auxOutputs()));
  1866. for (auto& a : accumulated)
  1867. for (auto& side : a)
  1868. side.assign (auxCapacity, 0.0f);
  1869. configure (channel, 140.0);
  1870. }
  1871. void prepare (double sampleRate) noexcept override { graph.prepare (sampleRate); }
  1872. void noteOn (int key, float velocity) noexcept override { graph.noteOn (key, velocity); }
  1873. void noteOff (int key) noexcept override { graph.noteOff (key); }
  1874. void allNotesOff() noexcept override { graph.allNotesOff(); }
  1875. void cut() noexcept override { graph.cut(); }
  1876. void midiMessage (const std::uint8_t* bytes, int size) noexcept override { graph.midiMessage (bytes, size); }
  1877. void pitchBend (float semitones) noexcept override { graph.pitchBend (semitones); }
  1878. void controlChange (int cc, float value) noexcept override { graph.controlChange (cc, value); }
  1879. void noteOnMidi (int key, float velocity, int midiChannel) noexcept override { graph.noteOnMidi (key, velocity, midiChannel); }
  1880. void noteOffMidi (int key, int midiChannel) noexcept override { graph.noteOffMidi (key, midiChannel); }
  1881. void noteOnPort (int port, int key, float velocity, int midiChannel) noexcept override { graph.noteOnPort (port, key, velocity, midiChannel); }
  1882. void noteOffPort (int port, int key, int midiChannel) noexcept override { graph.noteOffPort (port, key, midiChannel); }
  1883. void voicePropertyPort (int port, int key, int prop, float value, int midiChannel) noexcept override
  1884. {
  1885. graph.voicePropertyPort (port, key, prop, value, midiChannel);
  1886. }
  1887. void voiceProperty (int key, int prop, float value) noexcept override { graph.voiceProperty (key, prop, value); } // (issue #271)
  1888. int takePortEvents (PortEvent* out, int max) noexcept override { return graph.takeHostEvents (out, max); }
  1889. bool followsSlides() const noexcept override { return true; } // (round 168l: a Mono channel's notes)
  1890. void slideTo (int key, float cents, float samples) noexcept override { graph.slideTo (key, cents, samples); }
  1891. void setNextNoteExpression (float pan, float cents, bool porta) noexcept override { graph.setNextNoteExpression (pan, cents, porta); }
  1892. void setNextNoteModulation (float modX, float modY) noexcept override { graph.setNextNoteModulation (modX, modY); }
  1893. void setNextNoteRelease (float velocity) noexcept override { graph.setNextNoteRelease (velocity); }
  1894. void setNextNoteColour (int colour) noexcept override { graph.setNextNoteColour (colour); }
  1895. void setSongPosition (double ticks) noexcept override { graph.setSongPosition (ticks); }
  1896. void setParameter (int index, float value) noexcept override { graph.setPublished (index, value); }
  1897. int latencySamples() const noexcept override { return graph.latencySamples(); }
  1898. // (round 190ts: or its graph sleeps while stopped, Graph::setStoppedSleep)
  1899. bool idle() const noexcept override
  1900. {
  1901. return (idleWhenQuiet.load (std::memory_order_relaxed) && graph.instrumentsIdle()) || graph.asleep();
  1902. }
  1903. void setStoppedSleep (bool on) noexcept override { graph.setStoppedSleep (on); }
  1904. // (UI thread, while the audio thread renders: only atomics change here; the graph swaps its values itself)
  1905. void configure (const ChannelDef& channel, double bpm) noexcept override
  1906. {
  1907. tempo.store (bpm, std::memory_order_relaxed);
  1908. graph.voiceProps.store (channel.engineRev >= 5, std::memory_order_relaxed); // (issue #271)
  1909. graph.takeValues (channel.patcher, bpm);
  1910. if (tracks != nullptr)
  1911. for (int k = 1; k <= graph.auxOutputs(); ++k)
  1912. tracks[(std::size_t) k - 1].store (patcher::auxOutputTrack (channel, k), std::memory_order_relaxed);
  1913. // only instruments (no effects that ring on): silent when its instruments are
  1914. idleWhenQuiet.store (std::all_of (channel.patcher.nodes.begin(), channel.patcher.nodes.end(), [] (const PatchNode& n) { return n.generator; }),
  1915. std::memory_order_relaxed);
  1916. }
  1917. void render (float* left, float* right, int n, float gainLeft, float gainRight) noexcept override
  1918. {
  1919. static const std::vector<float> silence ((std::size_t) Graph::capacity, 0.0f);
  1920. for (int done = 0; done < n; done += Graph::capacity)
  1921. {
  1922. const auto piece = std::min (Graph::capacity, n - done);
  1923. graph.setHardwareIo (hwIn, hwOut, hwOffset + cursor); // (cursor: where this piece starts in the chunk)
  1924. graph.process (silence.data(), silence.data(), nullptr, nullptr, buffer[0].data(), buffer[1].data(), piece,
  1925. tempo.load (std::memory_order_relaxed));
  1926. for (int i = 0; i < piece; ++i)
  1927. {
  1928. left[done + i] += buffer[0][(std::size_t) i] * gainLeft;
  1929. right[done + i] += buffer[1][(std::size_t) i] * gainRight;
  1930. }
  1931. for (int k = 0; k < graph.auxOutputs(); ++k)
  1932. {
  1933. const auto* al = graph.auxOutput (k, 0);
  1934. const auto* ar = graph.auxOutput (k, 1);
  1935. auto& acc = accumulated[(std::size_t) k];
  1936. for (int i = 0; i < piece && cursor + i < (int) auxCapacity; ++i)
  1937. {
  1938. acc[0][(std::size_t) (cursor + i)] += al[i] * gainLeft;
  1939. acc[1][(std::size_t) (cursor + i)] += ar[i] * gainRight;
  1940. }
  1941. }
  1942. cursor += piece;
  1943. }
  1944. }
  1945. void beginChunk (int n) noexcept override
  1946. {
  1947. cursor = 0;
  1948. for (auto& a : accumulated)
  1949. for (auto& side : a)
  1950. std::fill (side.begin(), side.begin() + std::min<std::ptrdiff_t> (n, (std::ptrdiff_t) side.size()), 0.0f);
  1951. }
  1952. void setHardwareIo (const LiveInput* in, HardwareOutput* out, int offset) noexcept override
  1953. {
  1954. hwIn = in;
  1955. hwOut = out;
  1956. hwOffset = offset;
  1957. }
  1958. int auxOutputCount() const noexcept override { return (int) accumulated.size(); }
  1959. int auxOutputTrack (int k) const noexcept override
  1960. {
  1961. return k >= 0 && k < graph.auxOutputs() && tracks != nullptr ? tracks[(std::size_t) k].load (std::memory_order_relaxed) : -1;
  1962. }
  1963. const float* auxOutputData (int k, int side) const noexcept override
  1964. {
  1965. return k >= 0 && k < (int) accumulated.size() ? accumulated[(std::size_t) k][(std::size_t) (side & 1)].data() : nullptr;
  1966. }
  1967. Graph graph;
  1968. private:
  1969. static constexpr std::size_t auxCapacity = 16384;
  1970. std::array<std::vector<float>, 2> buffer;
  1971. std::vector<std::array<std::vector<float>, 2>> accumulated;
  1972. std::unique_ptr<std::atomic<int>[]> tracks; // [extra output] its insert
  1973. int cursor = 0;
  1974. const LiveInput* hwIn = nullptr;
  1975. HardwareOutput* hwOut = nullptr;
  1976. int hwOffset = 0;
  1977. std::atomic<bool> idleWhenQuiet { true };
  1978. std::atomic<double> tempo { 140.0 };
  1979. };
  1980. } // namespace
  1981. std::vector<int> layerChildren (const PatcherDoc& doc, int node)
  1982. {
  1983. std::vector<int> out;
  1984. const auto count = (int) doc.nodes.size();
  1985. if (node < 0 || node >= count)
  1986. return out;
  1987. std::vector<char> seen ((std::size_t) count, 0);
  1988. seen[(std::size_t) node] = 1;
  1989. std::vector<int> todo { node };
  1990. while (! todo.empty())
  1991. {
  1992. const auto source = todo.back();
  1993. todo.pop_back();
  1994. for (const auto& w : doc.wires)
  1995. {
  1996. if (w.kind != PatchWire::Kind::midi || ! w.enabled || w.from != source || w.fromPort != 0 || w.to < 0 || w.to >= count || seen[(std::size_t) w.to])
  1997. continue;
  1998. seen[(std::size_t) w.to] = 1;
  1999. const auto& target = doc.nodes[(std::size_t) w.to];
  2000. if (! target.generator || target.channel.instrument == InstrumentKind::layer)
  2001. continue;
  2002. if (target.channel.instrument == InstrumentKind::midiOut)
  2003. todo.push_back (w.to);
  2004. else
  2005. out.push_back (w.to);
  2006. }
  2007. }
  2008. std::sort (out.begin(), out.end());
  2009. return out;
  2010. }
  2011. bool usesHardwareIo (const PatcherDoc& doc) noexcept
  2012. {
  2013. for (const auto& n : doc.nodes)
  2014. if (! n.generator && (n.effect.kind == EffectKind::hardwareInsert || (n.effect.kind == EffectKind::patcher && usesHardwareIo (n.effect.patcher))))
  2015. return true;
  2016. return false;
  2017. }
  2018. std::unique_ptr<Effect> makeEffect (const EffectSlot& slot, double sampleRate, const Factories& factories, const Effect* previous)
  2019. {
  2020. const auto* old = dynamic_cast<const PatcherEffect*> (previous);
  2021. return std::make_unique<PatcherEffect> (slot, sampleRate, factories, old != nullptr ? &old->graph : nullptr);
  2022. }
  2023. std::unique_ptr<Instrument> makeInstrument (const ChannelDef& channel, double sampleRate, const Factories& factories, const Instrument* previous)
  2024. {
  2025. const auto* old = dynamic_cast<const PatcherInstrument*> (previous);
  2026. return std::make_unique<PatcherInstrument> (channel, sampleRate, factories, old != nullptr ? &old->graph : nullptr);
  2027. }
  2028. Graph* graphOf (Effect* effect) noexcept
  2029. {
  2030. auto* p = dynamic_cast<PatcherEffect*> (effect);
  2031. return p != nullptr ? &p->graph : nullptr;
  2032. }
  2033. Graph* graphOf (Instrument* instrument) noexcept
  2034. {
  2035. auto* p = dynamic_cast<PatcherInstrument*> (instrument);
  2036. return p != nullptr ? &p->graph : nullptr;
  2037. }
  2038. bool acceptValues (Effect* effect, const EffectSlot& slot)
  2039. {
  2040. if (auto* g = graphOf (effect))
  2041. {
  2042. // a node's latency moved since the graph planned its delay compensation: build it again (issue #113)
  2043. if (g->latencyStale (&slot.patcher))
  2044. return false;
  2045. g->takeValues (slot.patcher);
  2046. return true;
  2047. }
  2048. return false;
  2049. }
  2050. bool acceptValues (Instrument* instrument, const ChannelDef& channel)
  2051. {
  2052. if (auto* g = graphOf (instrument))
  2053. {
  2054. instrument->configure (channel, 140.0); // (the rack configures it again with the song's tempo)
  2055. return true;
  2056. }
  2057. return false;
  2058. }
  2059. int auxOutputTrack (const ChannelDef& channel, int k) noexcept
  2060. {
  2061. if (k <= 0)
  2062. return channel.mixerTrack;
  2063. if (k <= (int) channel.patcher.outputTracks.size() && channel.patcher.outputTracks[(std::size_t) k - 1] >= 0)
  2064. return channel.patcher.outputTracks[(std::size_t) k - 1];
  2065. return std::min (channel.mixerTrack + k, maxMixerTracks - 1);
  2066. }
  2067. Factories builtInFactories (double sampleRate, double bpm)
  2068. {
  2069. Factories f;
  2070. f.effect = [sampleRate] (const EffectSlot& slot) -> std::shared_ptr<Effect> {
  2071. if (slot.kind == EffectKind::plugin)
  2072. return nullptr;
  2073. if (slot.kind == EffectKind::patcher)
  2074. return makeEffect (slot, sampleRate, builtInFactories (sampleRate));
  2075. std::shared_ptr<Effect> e = lynx::makeEffect (slot);
  2076. e->prepare (sampleRate);
  2077. return e;
  2078. };
  2079. f.instrument = [sampleRate, bpm] (const ChannelDef& channel) -> std::shared_ptr<Instrument> {
  2080. if (channel.instrument == InstrumentKind::plugin)
  2081. return nullptr;
  2082. if (channel.instrument == InstrumentKind::patcher)
  2083. return makeInstrument (channel, sampleRate, builtInFactories (sampleRate, bpm));
  2084. std::shared_ptr<Instrument> i = lynx::makeInstrument (channel.instrument);
  2085. i->prepare (sampleRate);
  2086. i->configure (channel, bpm);
  2087. return i;
  2088. };
  2089. return f;
  2090. }
  2091. int addNode (PatcherDoc& doc, PatchNode node)
  2092. {
  2093. doc.nodes.push_back (std::move (node));
  2094. return (int) doc.nodes.size() - 1;
  2095. }
  2096. void removeNode (PatcherDoc& doc, int node)
  2097. {
  2098. if (node < 0 || node >= (int) doc.nodes.size())
  2099. return;
  2100. doc.nodes.erase (doc.nodes.begin() + node);
  2101. std::erase_if (doc.wires, [node] (const PatchWire& w) { return w.from == node || w.to == node; });
  2102. for (auto& w : doc.wires)
  2103. {
  2104. if (w.from > node)
  2105. --w.from;
  2106. if (w.to > node)
  2107. --w.to;
  2108. }
  2109. // its published parameters are freed (their indices stay); the later nodes' move down (round 171b)
  2110. for (auto& p : doc.published)
  2111. {
  2112. if (p.node == node)
  2113. p = PatchParam {};
  2114. else if (p.node > node)
  2115. --p.node;
  2116. }
  2117. }
  2118. namespace
  2119. {
  2120. void insertSorted (std::vector<int>& v, int x)
  2121. {
  2122. if (std::find (v.begin(), v.end(), x) == v.end())
  2123. v.insert (std::upper_bound (v.begin(), v.end(), x), x);
  2124. }
  2125. } // namespace
  2126. std::vector<int> shownParamInputs (const PatcherDoc& doc, int node)
  2127. {
  2128. if (node < 0 || node >= (int) doc.nodes.size())
  2129. return {};
  2130. auto shown = doc.nodes[(std::size_t) node].paramIns;
  2131. for (const auto& w : doc.wires)
  2132. if (w.kind == PatchWire::Kind::control && w.to == node && w.toPort >= 0)
  2133. insertSorted (shown, w.toPort);
  2134. return shown;
  2135. }
  2136. std::vector<int> shownParamOutputs (const PatcherDoc& doc, int node)
  2137. {
  2138. if (node < 0 || node >= (int) doc.nodes.size())
  2139. return {};
  2140. auto shown = doc.nodes[(std::size_t) node].paramOuts;
  2141. for (const auto& w : doc.wires)
  2142. if (w.kind == PatchWire::Kind::control && w.from == node && isPatchParamOutput (w.fromPort))
  2143. insertSorted (shown, patchOutputParam (w.fromPort));
  2144. return shown;
  2145. }
  2146. int publishedIndex (const PatcherDoc& doc, int node, int param)
  2147. {
  2148. for (std::size_t k = 0; k < doc.published.size(); ++k)
  2149. if (doc.published[k].node == node && doc.published[k].param == param)
  2150. return (int) k;
  2151. return -1;
  2152. }
  2153. void setParamInput (PatcherDoc& doc, int node, int param, bool on, const std::string& name)
  2154. {
  2155. if (node < 0 || node >= (int) doc.nodes.size() || param < 0)
  2156. return;
  2157. auto& ins = doc.nodes[(std::size_t) node].paramIns;
  2158. if (on)
  2159. {
  2160. insertSorted (ins, param);
  2161. if (publishedIndex (doc, node, param) < 0)
  2162. {
  2163. PatchParam p;
  2164. p.node = node;
  2165. p.param = param;
  2166. p.name = name.empty() ? nodeName (doc.nodes[(std::size_t) node]) + " " + std::to_string (param + 1) : name;
  2167. doc.published.push_back (std::move (p));
  2168. }
  2169. return;
  2170. }
  2171. std::erase (ins, param);
  2172. std::erase_if (doc.wires, [node, param] (const PatchWire& w) { return w.kind == PatchWire::Kind::control && w.to == node && w.toPort == param; });
  2173. if (const auto k = publishedIndex (doc, node, param); k >= 0)
  2174. doc.published[(std::size_t) k] = PatchParam {};
  2175. while (! doc.published.empty() && doc.published.back().node < 0) // (trailing free indices are dropped)
  2176. doc.published.pop_back();
  2177. }
  2178. void setParamOutput (PatcherDoc& doc, int node, int param, bool on)
  2179. {
  2180. if (node < 0 || node >= (int) doc.nodes.size() || param < 0)
  2181. return;
  2182. auto& outs = doc.nodes[(std::size_t) node].paramOuts;
  2183. if (on)
  2184. {
  2185. insertSorted (outs, param);
  2186. return;
  2187. }
  2188. std::erase (outs, param);
  2189. std::erase_if (doc.wires, [node, param] (const PatchWire& w) {
  2190. return w.kind == PatchWire::Kind::control && w.from == node && w.fromPort == patchParamOutput (param);
  2191. });
  2192. }
  2193. void deactivateUnusedParams (PatcherDoc& doc, int node, bool inputs)
  2194. {
  2195. if (node < 0 || node >= (int) doc.nodes.size())
  2196. return;
  2197. const auto shown = inputs ? shownParamInputs (doc, node) : shownParamOutputs (doc, node);
  2198. for (const auto p : shown)
  2199. {
  2200. const auto used = std::any_of (doc.wires.begin(), doc.wires.end(), [&] (const PatchWire& w) {
  2201. return w.kind == PatchWire::Kind::control && (inputs ? (w.to == node && w.toPort == p) : (w.from == node && w.fromPort == patchParamOutput (p)));
  2202. });
  2203. if (! used)
  2204. inputs ? setParamInput (doc, node, p, false) : setParamOutput (doc, node, p, false);
  2205. }
  2206. }
  2207. bool nodeHasCables (const PatcherDoc& doc, int node)
  2208. {
  2209. return std::any_of (doc.wires.begin(), doc.wires.end(), [node] (const PatchWire& w) { return w.from == node || w.to == node; });
  2210. }
  2211. void disconnectNode (PatcherDoc& doc, int node)
  2212. {
  2213. std::erase_if (doc.wires, [node] (const PatchWire& w) { return w.from == node || w.to == node; });
  2214. }
  2215. int addSurfaceControl (PatcherDoc& doc, SurfaceControl control)
  2216. {
  2217. doc.surface.push_back (std::move (control));
  2218. return (int) doc.surface.size() - 1;
  2219. }
  2220. void removeSurfaceControl (PatcherDoc& doc, int index)
  2221. {
  2222. if (index < 0 || index >= (int) doc.surface.size())
  2223. return;
  2224. int first = 0;
  2225. for (int i = 0; i < index; ++i)
  2226. first += doc.surface[(std::size_t) i].outputs();
  2227. const auto count = doc.surface[(std::size_t) index].outputs();
  2228. doc.surface.erase (doc.surface.begin() + index);
  2229. // its cables go; the later controls' outputs move down
  2230. std::erase_if (doc.wires, [first, count] (const PatchWire& w) { return w.from == patchSurface && w.fromPort >= first && w.fromPort < first + count; });
  2231. for (auto& w : doc.wires)
  2232. if (w.from == patchSurface && w.fromPort >= first + count)
  2233. w.fromPort -= count;
  2234. }
  2235. bool connect (PatcherDoc& doc, const PatchWire& wire)
  2236. {
  2237. const auto count = (int) doc.nodes.size();
  2238. const auto validFrom = wire.from == patchFromHost || (wire.from >= 0 && wire.from < count)
  2239. || (wire.from == patchSurface && wire.kind == PatchWire::Kind::control && wire.fromPort >= 0 && wire.fromPort < doc.surfaceOutputs());
  2240. const auto validTo = wire.to == patchToHost || (wire.to >= 0 && wire.to < count);
  2241. if (! validFrom || ! validTo || (wire.from == wire.to && wire.from >= 0 && wire.kind != PatchWire::Kind::control))
  2242. return false;
  2243. if (wire.kind == PatchWire::Kind::control && ((wire.from < 0 && wire.from != patchSurface) || wire.to < 0))
  2244. return false;
  2245. if (wire.to >= 0 && doc.nodes[(std::size_t) wire.to].generator && wire.kind == PatchWire::Kind::audio)
  2246. return false;
  2247. for (const auto& w : doc.wires)
  2248. if (w.kind == wire.kind && w.from == wire.from && w.fromPort == wire.fromPort && w.to == wire.to && w.toPort == wire.toPort)
  2249. return false;
  2250. doc.wires.push_back (wire);
  2251. return true;
  2252. }
  2253. std::string nodeName (const PatchNode& node)
  2254. {
  2255. auto blank = [] (const std::string& t) { return std::all_of (t.begin(), t.end(), [] (unsigned char c) { return std::isspace (c) != 0; }); };
  2256. if (! blank (node.label))
  2257. return node.label;
  2258. if (node.generator)
  2259. return ! blank (node.channel.plugin.name) ? node.channel.plugin.name : ! blank (node.channel.name) ? node.channel.name : "Instrument";
  2260. if (node.effect.kind == EffectKind::plugin)
  2261. return ! blank (node.effect.plugin.name) ? node.effect.plugin.name : "Plugin";
  2262. return effectInfo (node.effect.kind).name;
  2263. }
  2264. // --- MIDI through the I/O nodes (round 162) ---
  2265. namespace
  2266. {
  2267. void addSorted (std::vector<int>& v, int x)
  2268. {
  2269. if (std::find (v.begin(), v.end(), x) == v.end())
  2270. v.insert (std::upper_bound (v.begin(), v.end(), x), x);
  2271. }
  2272. } // namespace
  2273. std::vector<int> shownFromMidiPorts (const PatcherDoc& doc)
  2274. {
  2275. std::vector<int> ports;
  2276. for (const auto p : doc.fromMidiPorts)
  2277. if (p >= 0 && p < patchMidiPorts)
  2278. addSorted (ports, p);
  2279. for (const auto& w : doc.wires)
  2280. if (w.kind == PatchWire::Kind::midi && w.from == patchFromHost && w.fromPort > 0 && patchPinMidiPort (w.fromPort) < patchMidiPorts)
  2281. addSorted (ports, patchPinMidiPort (w.fromPort));
  2282. return ports;
  2283. }
  2284. std::vector<int> shownToMidiPorts (const PatcherDoc& doc)
  2285. {
  2286. std::vector<int> ports;
  2287. for (const auto p : doc.toMidiPorts)
  2288. if (p >= 0 && p < patchMidiPorts)
  2289. addSorted (ports, p);
  2290. for (const auto& w : doc.wires)
  2291. if (w.kind == PatchWire::Kind::midi && w.to == patchToHost && w.toPort >= 0 && w.toPort < patchMidiPorts)
  2292. addSorted (ports, w.toPort);
  2293. return ports;
  2294. }
  2295. int shownMidiOutputs (const PatcherDoc& doc, int node)
  2296. {
  2297. if (node < 0 || node >= (int) doc.nodes.size())
  2298. return 0;
  2299. const auto ports = nodePorts (doc.nodes[(std::size_t) node]);
  2300. const auto kind = vfx::kindOf (doc.nodes[(std::size_t) node].channel);
  2301. if (! kind)
  2302. return ports.midiOuts;
  2303. int highest = -1;
  2304. for (const auto& w : doc.wires)
  2305. if (w.kind == PatchWire::Kind::midi && w.from == node)
  2306. highest = std::max (highest, w.fromPort);
  2307. return std::clamp (std::max (vfx::outputsShown (*kind), highest + 2), 1, ports.midiOuts);
  2308. }
  2309. bool fromNotesShown (const PatcherDoc& doc, bool generator)
  2310. {
  2311. if (std::any_of (doc.wires.begin(), doc.wires.end(),
  2312. [] (const PatchWire& w) { return w.kind == PatchWire::Kind::midi && w.from == patchFromHost && w.fromPort == 0; }))
  2313. return true;
  2314. return generator && ! doc.fromNotesHidden; // (a mixer slot has no notes of its own)
  2315. }
  2316. std::vector<int> midiInputPorts (const PatcherDoc& doc)
  2317. {
  2318. std::vector<int> ports;
  2319. for (const auto& w : doc.wires)
  2320. if (w.kind == PatchWire::Kind::midi && w.enabled && w.from == patchFromHost && w.fromPort > 0
  2321. && patchPinMidiPort (w.fromPort) < patchMidiPorts)
  2322. addSorted (ports, patchPinMidiPort (w.fromPort));
  2323. return ports;
  2324. }
  2325. std::vector<int> vfxHostPorts (const PatcherDoc& doc)
  2326. {
  2327. std::vector<int> ports;
  2328. for (const auto& w : doc.wires)
  2329. if (w.kind == PatchWire::Kind::midi && w.enabled && w.to == patchToHost && w.toPort >= 0 && w.toPort < patchMidiPorts && w.from >= 0
  2330. && w.from < (int) doc.nodes.size() && doc.nodes[(std::size_t) w.from].generator && vfx::kindOf (doc.nodes[(std::size_t) w.from].channel))
  2331. addSorted (ports, w.toPort);
  2332. return ports;
  2333. }
  2334. std::vector<MidiPortRoute> midiOutputsOf (const PatcherDoc& doc, int fromPin)
  2335. {
  2336. std::vector<MidiPortRoute> out;
  2337. const auto count = (int) doc.nodes.size();
  2338. std::vector<char> seen ((std::size_t) count, 0);
  2339. std::vector<std::tuple<int, int, int>> todo { { patchFromHost, fromPin, -1 } };
  2340. while (! todo.empty())
  2341. {
  2342. const auto [from, pin, channel] = todo.back();
  2343. todo.pop_back();
  2344. for (const auto& w : doc.wires)
  2345. {
  2346. if (w.kind != PatchWire::Kind::midi || ! w.enabled || w.from != from || w.fromPort != pin)
  2347. continue;
  2348. if (w.to == patchToHost)
  2349. {
  2350. const MidiPortRoute r { w.toPort, channel };
  2351. if (w.toPort >= 0 && w.toPort < patchMidiPorts && std::find (out.begin(), out.end(), r) == out.end())
  2352. out.push_back (r);
  2353. }
  2354. else if (w.to >= 0 && w.to < count && ! seen[(std::size_t) w.to])
  2355. {
  2356. const auto& node = doc.nodes[(std::size_t) w.to];
  2357. if (node.generator && node.channel.instrument == InstrumentKind::midiOut)
  2358. {
  2359. seen[(std::size_t) w.to] = 1;
  2360. todo.emplace_back (w.to, 0, midictl::parseMidiOut (node.channel.pluginState).channel);
  2361. }
  2362. }
  2363. }
  2364. }
  2365. return out;
  2366. }
  2367. void deactivateUnusedMidiPins (PatcherDoc& doc, bool fromNode)
  2368. {
  2369. auto used = [&] (int pin) {
  2370. return std::any_of (doc.wires.begin(), doc.wires.end(), [&] (const PatchWire& w) {
  2371. return w.kind == PatchWire::Kind::midi && (fromNode ? w.from == patchFromHost && w.fromPort == pin : w.to == patchToHost && w.toPort == pin);
  2372. });
  2373. };
  2374. if (fromNode)
  2375. {
  2376. std::erase_if (doc.fromMidiPorts, [&] (int p) { return ! used (patchMidiPortPin (p)); });
  2377. doc.fromNotesHidden = ! used (0);
  2378. }
  2379. else
  2380. std::erase_if (doc.toMidiPorts, [&] (int p) { return ! used (p); });
  2381. }
  2382. } // namespace lynx::patcher