| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527 |
- #include "core/Patcher.h"
- #include "core/LynxVerbs.h"
- #include "core/Rack.h"
- #include "core/ControlSurface.h"
- #include "core/VfxScript.h"
- #include "core/XyController.h"
- #include <algorithm>
- #include <chrono>
- #include <cctype>
- #include <cmath>
- #include <cstring>
- #include <limits>
- #include <map>
- #include <tuple>
- #include "core/FacetEq.h"
- #include "core/FlSynths.h"
- #include "core/FrequencySplitter.h"
- #include "core/HardwareInsert.h"
- #include "core/Layer.h"
- #include "core/MidiControls.h"
- #include "core/Pdc.h"
- namespace lynx::patcher
- {
- namespace
- {
- class PassEffect final : public Effect
- {
- public:
- void prepare (double) noexcept override {}
- void reset() noexcept override {}
- void process (float*, float*, int, const EffectParams&, double) noexcept override {}
- };
- // what makes a running node reusable: everything but the values the graph hands it every block
- bool sameEffectSetup (const EffectSlot& a, const EffectSlot& b)
- {
- if (a.kind != b.kind || a.plugin.id != b.plugin.id || a.state != b.state || a.samplePath != b.samplePath || ! (a.plugin == b.plugin))
- return false;
- if (a.kind == EffectKind::parallel)
- return a == b; // its children are built in
- if (a.kind == EffectKind::patcher)
- return sameStructure (a.patcher, b.patcher);
- // a Hardware Insert's round trip is its latency, which the graph's delay compensation is built on (round 165c): a new
- // ping result builds the graph again
- if (a.kind == EffectKind::hardwareInsert)
- return a.params[(std::size_t) hwinsert::roundTrip] == b.params[(std::size_t) hwinsert::roundTrip];
- if (a.kind == EffectKind::atrium) // round 190nr: its dense late tank is allocated only where it runs
- return verbs::atriumDense (a.params) == verbs::atriumDense (b.params);
- // effects whose setup depends on parameters at creation (latency, mode) are rebuilt by the rack as well
- return true;
- }
- bool sameInstrumentSetup (const ChannelDef& a, const ChannelDef& b)
- {
- // a VFX node takes new settings while it runs (its held voices end as they started): only its kind is structure
- if (a.instrument == InstrumentKind::vfx || b.instrument == InstrumentKind::vfx)
- return a.instrument == b.instrument && vfx::kindOf (a) == vfx::kindOf (b);
- if (a.instrument != b.instrument)
- return false;
- // (a Layer node's children take notes in their key regions: round 165c)
- if (a.keyLow != b.keyLow || a.keyHigh != b.keyHigh)
- return false;
- // the rack's own rule for a channel (RackState::build): what configure() cannot take means a new instance; the rest
- // reaches the running one (round 164f: an engine edited in its editor inside a Patcher keeps playing, as on a
- // channel, instead of starting again on each knob move)
- switch (a.instrument)
- {
- case InstrumentKind::plugin:
- return a.plugin.id == b.plugin.id && a.plugin == b.plugin && a.pluginState == b.pluginState;
- case InstrumentKind::patcher: return sameStructure (a.patcher, b.patcher);
- case InstrumentKind::midiOut: return a.pluginState == b.pluginState; // (its MIDI channel is in the graph's routes)
- case InstrumentKind::layer: // (its settings are in the graph's note routes: round 165c)
- 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;
- case InstrumentKind::controller: // (a Keyboard Controller has 1 output, an Envelope Controller 8)
- return parseKeyboardController (a.controllerState).has_value() == parseKeyboardController (b.controllerState).has_value();
- case InstrumentKind::sampler:
- case InstrumentKind::audioClip:
- case InstrumentKind::flkeys:
- return a.samplePath == b.samplePath && a.zones == b.zones && a.modelParams == b.modelParams && a.sampler.keepPitch == b.sampler.keepPitch
- && (! a.sampler.keepPitch || (a.sampler.stretchBeats == b.sampler.stretchBeats && a.sampler.stretchMethod == b.sampler.stretchMethod
- && a.sampler.stretchPitch == b.sampler.stretchPitch && a.sampler.warp == b.sampler.warp
- && a.sampler.warpModes == b.sampler.warpModes));
- case InstrumentKind::granulizer:
- case InstrumentKind::wavetraveller:
- case InstrumentKind::soundfont: return a.samplePath == b.samplePath;
- case InstrumentKind::fruityslicer: return a.samplePath == b.samplePath && a.pluginState == b.pluginState;
- case InstrumentKind::slicex: return a.samplePath == b.samplePath && a.zones == b.zones; // (the state is taken live)
- case InstrumentKind::directwave: return a.zones == b.zones && a.modelParams == b.modelParams && a.pluginState == b.pluginState;
- case InstrumentKind::fpc: return a.zones == b.zones && a.pluginState == b.pluginState;
- case InstrumentKind::dashboard: // (its outputs are structure)
- return std::equal (a.patcher.surface.begin(), a.patcher.surface.end(), b.patcher.surface.begin(), b.patcher.surface.end(),
- [] (const SurfaceControl& x, const SurfaceControl& y) { return x.kind == y.kind; });
- default: return true;
- }
- }
- float mapControl (const std::vector<float>& curve, float v) noexcept
- {
- v = std::clamp (v, 0.0f, 1.0f);
- if (curve.size() < 2)
- return v;
- const auto x = v * (float) (curve.size() - 1);
- const auto i = std::min ((std::size_t) x, curve.size() - 2);
- const auto f = x - (float) i;
- return curve[i] + (curve[i + 1] - curve[i]) * f;
- }
- } // namespace
- std::optional<PatchNode::BusHead> busHeadOf (const PatchNode& node, int bus)
- {
- if (bus <= 0 || node.generator)
- return std::nullopt;
- for (const auto& h : node.busHeads)
- if (h.bus == bus)
- return h;
- if (node.effect.kind == EffectKind::frequencySplitter && bus <= 3) // LYNX's own: band sends 1 low, 2 mid, 3 high
- {
- PatchNode::BusHead head;
- head.bus = bus;
- auto slot = node.effect;
- slot.params[(std::size_t) fsplit::outputLow] = bus == 1 ? 1.0f : 0.0f;
- slot.params[(std::size_t) fsplit::outputMid] = bus == 2 ? 1.0f : 0.0f;
- slot.params[(std::size_t) fsplit::outputHigh] = bus == 3 ? 1.0f : 0.0f;
- head.head = slot;
- return head;
- }
- return std::nullopt;
- }
- NodePorts nodePorts (const PatchNode& node)
- {
- NodePorts p;
- if (node.generator)
- {
- p.audioIns = 0;
- p.midiIn = true;
- if (node.channel.instrument == InstrumentKind::controller) // Envelope Controller: 8 outputs; Keyboard Controller: 1
- p.controlOuts = parseKeyboardController (node.channel.controllerState) ? 1 : 8;
- if (node.channel.instrument == InstrumentKind::dashboard) // round 164: one per control (an XY pad: two)
- p.controlOuts = surface::firstOutput (node.channel.patcher.surface, (int) node.channel.patcher.surface.size());
- if (node.channel.instrument == InstrumentKind::controller || node.channel.instrument == InstrumentKind::midiOut
- || node.channel.instrument == InstrumentKind::dashboard || node.channel.instrument == InstrumentKind::layer)
- p.audioOuts = 0; // (no sound of their own)
- // a MIDI Out node; a hosted plugin's notes out (round 164f: an arpeggiator / MIDI effect plugin plays the
- // nodes cabled to it, as FL's Patcher shows a plugin's MIDI output)
- // (a Layer node, round 165c: its Children pin)
- p.midiOut = node.channel.instrument == InstrumentKind::midiOut || node.channel.instrument == InstrumentKind::plugin
- || node.channel.instrument == InstrumentKind::layer;
- p.midiOuts = p.midiOut ? 1 : 0;
- if (const auto kind = vfx::kindOf (node.channel)) // a VFX node: voices in, voices out (round 164b)
- {
- p.audioOuts = 0;
- p.midiOut = true;
- p.midiOuts = vfx::outputCount (*kind);
- if (*kind == vfx::Kind::script) // its output controllers (round 165d)
- if (const auto state = vfx::readState (node.channel.pluginState))
- if (const auto settings = vfx::parseScript (state->fl))
- p.controlOuts = (int) vfx::script::describe (*settings)->outputs.size();
- }
- if (node.channel.instrument == InstrumentKind::patcher)
- p.audioOuts = 1 + (int) node.channel.patcher.outputTracks.size();
- return p;
- }
- p.audioIns = 2; // main + side-chain
- p.midiIn = node.effect.kind == EffectKind::plugin;
- int highest = 0;
- for (const auto& h : node.busHeads)
- highest = std::max (highest, h.bus);
- if (node.effect.kind == EffectKind::frequencySplitter)
- highest = std::max (highest, 3);
- p.audioOuts = 1 + highest;
- if (node.effect.kind == EffectKind::peakController)
- p.controlOuts = 3;
- else if (node.effect.kind == EffectKind::formulaController)
- p.controlOuts = 1;
- else if (xy::isXyController (node.effect.kind)) // round 164: X, Y (, Z)
- p.controlOuts = xy::axesOf (node.effect.kind);
- else if (node.effect.kind == EffectKind::controlSurface) // round 164: one per control (an XY pad: two)
- p.controlOuts = surface::firstOutput (node.effect.patcher.surface, (int) node.effect.patcher.surface.size());
- return p;
- }
- bool sameStructure (const PatcherDoc& a, const PatcherDoc& b)
- {
- if (a.nodes.size() != b.nodes.size() || a.wires.size() != b.wires.size() || a.outputTracks != b.outputTracks || ! (a.published == b.published))
- return false;
- // the Surface's controls: their outputs are structure, their values are not (round 151)
- if (a.surface.size() != b.surface.size())
- return false;
- for (std::size_t i = 0; i < a.surface.size(); ++i)
- if (a.surface[i].kind != b.surface[i].kind)
- return false;
- for (std::size_t i = 0; i < a.nodes.size(); ++i)
- {
- const auto& x = a.nodes[i];
- const auto& y = b.nodes[i];
- if (x.generator != y.generator || x.busHeads.size() != y.busHeads.size())
- return false;
- if (x.generator ? ! sameInstrumentSetup (x.channel, y.channel) : ! sameEffectSetup (x.effect, y.effect))
- return false;
- for (std::size_t h = 0; h < x.busHeads.size(); ++h)
- if (x.busHeads[h].bus != y.busHeads[h].bus || x.busHeads[h].head.has_value() != y.busHeads[h].head.has_value()
- || (x.busHeads[h].head && ! sameEffectSetup (*x.busHeads[h].head, *y.busHeads[h].head)))
- return false;
- }
- for (std::size_t i = 0; i < a.wires.size(); ++i)
- {
- const auto& x = a.wires[i];
- const auto& y = b.wires[i];
- 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
- || (x.kind != PatchWire::Kind::audio && x.enabled != y.enabled) || x.zone != y.zone)
- return false;
- }
- return a.zones == b.zones; // (rack chains' note filters, round 183c)
- }
- // ---------------------------------------------------------------------------------------------------------------
- namespace
- {
- // Round 190ts: a built-in device whose silence LYNX can tell (Graph::setStoppedSleep): not a hosted plugin or a nested
- // Patcher (that one sleeps by itself), nor what the mixer's smart disable leaves out (RackState::planSlot): Gross Beat and
- // Edison record the silence, Newtone / Newtime / the Scratcher play whatever the input, a hardware insert has outboard
- // tails, controllers move whatever the sound, analysers and the tuner follow the signal into silence, Facet EQ playing
- // its comparative target.
- bool sleepableDevice (const EffectSlot& slot) noexcept
- {
- switch (slot.kind)
- {
- case EffectKind::plugin: case EffectKind::patcher: case EffectKind::grossBeat: case EffectKind::newtone:
- case EffectKind::newtime: case EffectKind::scratcher: case EffectKind::edison: case EffectKind::hardwareInsert:
- case EffectKind::formulaController: case EffectKind::xyController: case EffectKind::xyzController:
- case EffectKind::controlSurface: case EffectKind::peakController: case EffectKind::waveCandy:
- case EffectKind::visualizer: case EffectKind::tuner:
- return false;
- default:
- break;
- }
- return ! (slot.kind == EffectKind::facetEq && facet::listensToTarget (slot.params));
- }
- constexpr float sleepLevel = 1.5849e-5f; // -96 dBFS (RackRenderer::silenceLevel)
- bool quietBlock (const float* l, const float* r, int n) noexcept
- {
- float peak = 0.0f;
- for (int k = 0; k < n; ++k)
- peak = std::max (peak, std::max (std::abs (l[k]), std::abs (r[k])));
- return peak < sleepLevel;
- }
- } // namespace
- struct Graph::Node
- {
- bool generator = false;
- EffectSlot setup; // effect nodes
- ChannelDef channel; // generator nodes
- std::shared_ptr<Effect> effect;
- std::shared_ptr<Instrument> instrument;
- bool plugin = false; // values reach it through setParameter (control cables), not the params array
- bool hardware = false; // a Hardware Insert, or a Patcher holding one (round 165c)
- vfx::Processor* vfx = nullptr; // a VFX node's processor (owned by its instrument)
- std::vector<MidiTarget> midiOutTargets; // a plugin node: what its MIDI output pin reaches
- std::vector<std::vector<MidiTarget>> vfxTargets; // [voice output] what it reaches
- std::vector<std::vector<int>> vfxHostPorts; // [voice output] the "To LYNX SHARE" MIDI ports it is cabled to
- struct Head
- {
- int bus = 1;
- std::shared_ptr<Effect> effect; // null = direct
- EffectSlot slot;
- float gain = 1.0f;
- };
- std::vector<Head> heads;
- std::vector<std::array<std::vector<float>, 2>> out; // [0] main output, [1 + h] head h
- bool sidechain = false;
- int inLatency = 0, outLatency = 0;
- std::vector<int> mainInputs, sideInputs; // wire indices
- std::atomic<float> peak { 0.0f }; // round 190ld: main-output peak and process time while watched (Graph::watch)
- std::atomic<std::uint64_t> ns { 0 };
- // round 190ts (Graph::setStoppedSleep): may sleep while stopped (LYNX's own devices / an instrument that says idle);
- // a nested Patcher sleeps by itself (its graph), and counts as asleep when it is
- bool sleeps = false;
- Graph* nested = nullptr;
- int silentSamples = 0; // input and output silent that long (effect nodes)
- bool asleep = false; // not called in the last piece
- };
- struct Graph::AudioWire
- {
- int from = patchFromHost, fromBuffer = 0; // node, and its output buffer (0 main, 1 + h head); host: 0 input, 1 side-chain
- int to = patchToHost, toBus = 0;
- std::shared_ptr<DelayLine> delay;
- int docIndex = 0;
- };
- struct Graph::ControlWire
- {
- int from = 0, output = 0, to = 0, param = 0;
- int fromParam = -1; // a parameter output (round 171b): the source node's parameter, else its control output `output`
- std::vector<float> curve;
- int docIndex = 0;
- float sent = std::numeric_limits<float>::quiet_NaN(); // the value last given to a plugin / instrument target
- };
- struct Graph::VfxQueue
- {
- vfx::EventList in, out; // the voices that reached the node in this piece; what it sends
- };
- struct Graph::NoteOut
- {
- int node = 0, midiChannel = -1;
- vfx::Event event;
- float gain = 1.0f; // a Layer's level for this child (round 165c)
- };
- struct Graph::LayerNode
- {
- std::vector<MidiTarget> children; // the nodes on its Children pin, in node order (no Layers)
- std::vector<ChannelDef> defs; // [node] what layer::pick reads: the Layer's settings, the children's key regions
- std::array<int, 128> picked {}; // Random / Sequential: the child each held key went to (−1: none)
- std::uint32_t random = 0x165c165cu;
- int turn = 0;
- };
- struct Graph::Values
- {
- struct NodeValues
- {
- EffectParams params {};
- bool enabled = true;
- float mix = 1.0f;
- std::vector<EffectParams> heads;
- std::vector<float> headGains;
- };
- std::vector<NodeValues> nodes;
- std::vector<float> gains;
- std::vector<char> on;
- std::vector<float> surface; // the Surface node's control outputs
- };
- Graph::Graph (const PatcherDoc& doc, double sampleRate, const Factories& factories, const Graph* previous) : rate (sampleRate)
- {
- const auto count = (int) doc.nodes.size();
- std::vector<char> taken (previous != nullptr ? previous->nodes.size() : 0, 0);
- for (int i = 0; i < count; ++i)
- {
- const auto& src = doc.nodes[(std::size_t) i];
- auto node = std::make_unique<Node>();
- node->generator = src.generator;
- // a running instance with the same setup (the previous graph's node at the same index first)
- auto reuse = [&] () -> const Node* {
- if (previous == nullptr)
- return nullptr;
- auto matches = [&] (std::size_t k) {
- const auto& p = *previous->nodes[k];
- return ! taken[k] && p.generator == src.generator
- && (src.generator ? p.instrument != nullptr && sameInstrumentSetup (p.channel, src.channel)
- : p.effect != nullptr && sameEffectSetup (p.setup, src.effect));
- };
- if ((std::size_t) i < previous->nodes.size() && matches ((std::size_t) i))
- {
- taken[(std::size_t) i] = 1;
- return previous->nodes[(std::size_t) i].get();
- }
- for (std::size_t k = 0; k < previous->nodes.size(); ++k)
- if (matches (k))
- {
- taken[k] = 1;
- return previous->nodes[k].get();
- }
- return nullptr;
- }();
- if (src.generator)
- {
- node->channel = src.channel;
- node->plugin = src.channel.instrument == InstrumentKind::plugin;
- const auto* nested = reuse != nullptr ? graphOf (reuse->instrument.get()) : nullptr;
- if (nested != nullptr && nested->latencyStale (&src.channel.patcher))
- {
- // a nested generator Patcher whose plan no longer holds (issue #113): built again, keeping its nodes
- node->instrument = makeInstrument (src.channel, sampleRate, factories, reuse->instrument.get());
- node->instrument->configure (src.channel, 140.0);
- }
- else if (reuse != nullptr)
- {
- node->instrument = reuse->instrument;
- node->instrument->configure (src.channel, 140.0);
- }
- else if (factories.instrument)
- node->instrument = factories.instrument (src.channel);
- }
- else
- {
- node->setup = src.effect;
- // (a nested rack takes its macros as published parameters through setParameter, round 183c)
- node->plugin = src.effect.kind == EffectKind::plugin || (src.effect.kind == EffectKind::patcher && src.effect.patcher.isRack());
- const auto* nested = reuse != nullptr ? graphOf (reuse->effect.get()) : nullptr;
- if (nested != nullptr && nested->latencyStale (&src.effect.patcher))
- {
- // a nested Patcher whose plan no longer holds (issue #113): built again too, keeping its running nodes
- node->effect = makeEffect (src.effect, sampleRate, factories, reuse->effect.get());
- node->effect->prepare (sampleRate);
- }
- else if (reuse != nullptr)
- node->effect = reuse->effect;
- else if (factories.effect)
- node->effect = factories.effect (src.effect);
- if (node->effect == nullptr)
- node->effect = std::make_shared<PassEffect>();
- node->hardware = src.effect.kind == EffectKind::hardwareInsert || (src.effect.kind == EffectKind::patcher && usesHardwareIo (src.effect.patcher));
- hardwareNodes = hardwareNodes || node->hardware;
- }
- // extra outputs used by some cable
- for (const auto& w : doc.wires)
- if (w.kind == PatchWire::Kind::audio && w.from == i && w.fromPort > 0
- && std::none_of (node->heads.begin(), node->heads.end(), [&] (const Node::Head& h) { return h.bus == w.fromPort; }))
- if (const auto head = busHeadOf (src, w.fromPort))
- {
- Node::Head h;
- h.bus = head->bus;
- h.gain = head->gain;
- if (head->head)
- {
- h.slot = *head->head;
- const Node::Head* old = nullptr;
- if (reuse != nullptr)
- for (const auto& o : reuse->heads)
- if (o.bus == h.bus && o.effect != nullptr && sameEffectSetup (o.slot, h.slot))
- old = &o;
- h.effect = old != nullptr ? old->effect : (factories.effect ? factories.effect (h.slot) : nullptr);
- if (h.effect == nullptr)
- h.effect = std::make_shared<PassEffect>();
- }
- node->heads.push_back (std::move (h));
- }
- node->out.resize (1 + node->heads.size());
- for (auto& o : node->out)
- for (auto& side : o)
- side.assign ((std::size_t) capacity, 0.0f);
- nodes.push_back (std::move (node));
- }
- // cables
- int highestAux = 0;
- for (std::size_t w = 0; w < doc.wires.size(); ++w)
- {
- const auto& src = doc.wires[w];
- const auto validNode = [count] (int n) { return n >= 0 && n < count; };
- if (src.kind == PatchWire::Kind::audio)
- {
- AudioWire a;
- a.docIndex = (int) w;
- a.from = src.from;
- a.to = src.to;
- a.toBus = std::max (0, src.toPort);
- if (src.from == patchFromHost)
- a.fromBuffer = src.fromPort == 1 ? 1 : 0;
- else if (validNode (src.from))
- {
- if (src.fromPort > 0)
- {
- const auto& heads = nodes[(std::size_t) src.from]->heads;
- const auto h = std::find_if (heads.begin(), heads.end(), [&] (const Node::Head& x) { return x.bus == src.fromPort; });
- if (h == heads.end())
- continue; // an output the node does not have: silence
- a.fromBuffer = 1 + (int) (h - heads.begin());
- }
- }
- else
- continue;
- if (src.to == patchToHost)
- highestAux = std::max (highestAux, a.toBus);
- else if (! validNode (src.to) || nodes[(std::size_t) src.to]->generator || a.toBus > 1)
- continue;
- wires.push_back (std::move (a));
- }
- else if (src.kind == PatchWire::Kind::midi)
- {
- if (src.from == patchFromHost && src.fromPort == 0 && validNode (src.to) && src.enabled
- && std::find (noteTargets.begin(), noteTargets.end(), src.to) == noteTargets.end())
- noteTargets.push_back (src.to);
- }
- else if ((validNode (src.from) || (src.from == patchSurface && std::max (0, src.fromPort) < doc.surfaceOutputs())) && validNode (src.to)
- && src.enabled && src.toPort >= 0
- && (src.from == patchSurface || isPatchParamOutput (src.fromPort) // (a node's parameter output, round 171b)
- || std::max (0, src.fromPort) < nodePorts (doc.nodes[(std::size_t) src.from]).controlOuts)) // (a source with that output)
- {
- ControlWire c;
- c.from = src.from;
- c.output = std::max (0, src.fromPort);
- if (src.from != patchSurface && isPatchParamOutput (src.fromPort))
- {
- c.output = -1;
- c.fromParam = patchOutputParam (src.fromPort);
- if (! nodes[(std::size_t) c.from]->plugin && ! nodes[(std::size_t) c.from]->generator && c.fromParam >= maxEffectParams)
- continue;
- }
- c.to = src.to;
- c.param = src.toPort;
- c.curve = src.curve;
- c.docIndex = (int) w;
- if (! nodes[(std::size_t) c.to]->plugin && ! nodes[(std::size_t) c.to]->generator && c.param >= maxEffectParams)
- continue;
- controls.push_back (std::move (c));
- }
- }
- highestAux = std::max (highestAux, (int) doc.outputTracks.size());
- // MIDI (round 162): what each "From LYNX SHARE" pin reaches, through MIDI Out nodes (they set the MIDI channel); VFX
- // nodes (round 164b) take the voices into their processors and send theirs on from their voice outputs
- zoneStates.resize (doc.zones.size());
- for (std::size_t z = 0; z < doc.zones.size(); ++z)
- zoneStates[z].zone = doc.zones[z];
- pinTargets.assign ((std::size_t) patchMidiPortPin (patchMidiPorts), {});
- for (int pin = 0; pin < (int) pinTargets.size(); ++pin)
- pinTargets[(std::size_t) pin] = midiTargetsOf (doc, patchFromHost, pin);
- vfxQueues.resize ((std::size_t) count);
- for (int i = 0; i < count; ++i)
- {
- auto& node = *nodes[(std::size_t) i];
- if (node.instrument == nullptr || (node.vfx = node.instrument->noteProcessor()) == nullptr)
- continue;
- node.vfx->prepare (rate);
- const auto kind = node.vfx->kind();
- for (int k = 0; k < vfx::outputCount (kind); ++k)
- {
- node.vfxTargets.push_back (midiTargetsOf (doc, i, k));
- std::vector<int> ports;
- for (const auto& w : doc.wires)
- if (w.kind == PatchWire::Kind::midi && w.enabled && w.from == i && w.fromPort == k && w.to == patchToHost && w.toPort >= 0
- && w.toPort < patchMidiPorts && std::find (ports.begin(), ports.end(), w.toPort) == ports.end())
- ports.push_back (w.toPort);
- node.vfxHostPorts.push_back (std::move (ports));
- }
- vfxQueues[(std::size_t) i] = std::make_unique<VfxQueue>();
- hasVfx = true;
- }
- if (hasVfx)
- {
- // sources first (Kahn over the VFX → VFX links); a loop runs in index order (its voices wait a piece)
- std::vector<int> pendingInputs ((std::size_t) count, 0);
- for (int i = 0; i < count; ++i)
- for (const auto& targets : nodes[(std::size_t) i]->vfxTargets)
- for (const auto& t : targets)
- if (t.vfx && t.node != i)
- ++pendingInputs[(std::size_t) t.node];
- std::vector<char> placed ((std::size_t) count, 0);
- for (bool progress = true; progress;)
- {
- progress = false;
- for (int i = 0; i < count; ++i)
- if (! placed[(std::size_t) i] && nodes[(std::size_t) i]->vfx != nullptr && pendingInputs[(std::size_t) i] == 0)
- {
- placed[(std::size_t) i] = 1;
- vfxOrder.push_back (i);
- progress = true;
- for (const auto& targets : nodes[(std::size_t) i]->vfxTargets)
- for (const auto& t : targets)
- if (t.vfx && t.node != i)
- --pendingInputs[(std::size_t) t.node];
- }
- }
- for (int i = 0; i < count; ++i)
- if (! placed[(std::size_t) i] && nodes[(std::size_t) i]->vfx != nullptr)
- vfxOrder.push_back (i);
- }
- // hosted plugin nodes with a cable on their MIDI output (round 164f)
- for (int i = 0; i < count; ++i)
- {
- auto& node = *nodes[(std::size_t) i];
- if (! node.generator || node.instrument == nullptr || node.vfx != nullptr || doc.nodes[(std::size_t) i].channel.instrument != InstrumentKind::plugin)
- continue;
- node.midiOutTargets = midiTargetsOf (doc, i, 0);
- if (! node.midiOutTargets.empty())
- midiSources.push_back (i);
- }
- // Layer nodes (round 165c): their children, and what layer::pick reads
- layers.resize ((std::size_t) count);
- for (int i = 0; i < count; ++i)
- {
- const auto& src = doc.nodes[(std::size_t) i];
- if (! src.generator || src.channel.instrument != InstrumentKind::layer)
- continue;
- auto l = std::make_unique<LayerNode>();
- for (const auto& t : midiTargetsOf (doc, i, 0))
- if (! t.layer && t.node != i)
- l->children.push_back (t);
- std::stable_sort (l->children.begin(), l->children.end(), [] (const MidiTarget& a, const MidiTarget& b) { return a.node < b.node; });
- l->defs.resize ((std::size_t) count);
- for (int k = 0; k < count; ++k)
- {
- auto& d = l->defs[(std::size_t) k];
- d.instrument = doc.nodes[(std::size_t) k].generator ? doc.nodes[(std::size_t) k].channel.instrument : InstrumentKind::synth;
- d.keyLow = doc.nodes[(std::size_t) k].channel.keyLow;
- d.keyHigh = doc.nodes[(std::size_t) k].channel.keyHigh;
- d.misc.addToKey = doc.nodes[(std::size_t) k].channel.misc.addToKey;
- d.misc.rootNote = doc.nodes[(std::size_t) k].channel.misc.rootNote;
- }
- auto& self = l->defs[(std::size_t) i];
- self.layer = src.channel.layer;
- self.layer.children.clear();
- for (const auto& c : l->children)
- self.layer.children.push_back (c.node);
- self.volume = src.channel.volume;
- self.pan = src.channel.pan;
- self.sampler.pitch = src.channel.sampler.pitch;
- self.misc.rootNote = src.channel.misc.rootNote;
- l->picked.fill (-1);
- layers[(std::size_t) i] = std::move (l);
- }
- noteOuts.reserve (vfx::EventList::capacity);
- published = doc.published;
- publishedValues.assign (published.size(), std::numeric_limits<float>::quiet_NaN());
- aux.resize ((std::size_t) highestAux);
- for (auto& a : aux)
- for (auto& side : a)
- side.assign ((std::size_t) capacity, 0.0f);
- // order: nodes once all their audio sources ran (Kahn); what is left (loops) in index order
- std::vector<int> pendingInputs ((std::size_t) count, 0);
- for (const auto& w : wires)
- if (w.from >= 0 && w.to >= 0 && w.from != w.to)
- ++pendingInputs[(std::size_t) w.to];
- std::vector<char> placed ((std::size_t) count, 0);
- for (bool progress = true; progress;)
- {
- progress = false;
- for (int i = 0; i < count; ++i)
- if (! placed[(std::size_t) i] && pendingInputs[(std::size_t) i] == 0)
- {
- placed[(std::size_t) i] = 1;
- order.push_back (i);
- progress = true;
- for (const auto& w : wires)
- if (w.from == i && w.to >= 0 && w.to != i)
- --pendingInputs[(std::size_t) w.to];
- }
- }
- for (int i = 0; i < count; ++i)
- if (! placed[(std::size_t) i])
- order.push_back (i);
- for (std::size_t k = 0; k < wires.size(); ++k)
- if (wires[k].to >= 0)
- {
- auto& node = *nodes[(std::size_t) wires[k].to];
- (wires[k].toBus == 0 ? node.mainInputs : node.sideInputs).push_back ((int) k);
- node.sidechain = node.sidechain || wires[k].toBus == 1;
- }
- // delay compensation (FL: a cable from a source with less latency than the destination's goes through a delay)
- std::vector<int> position ((std::size_t) count, 0);
- for (std::size_t k = 0; k < order.size(); ++k)
- position[(std::size_t) order[k]] = (int) k;
- auto runsBefore = [&] (const AudioWire& w) { return w.from < 0 || w.to < 0 || position[(std::size_t) w.from] < position[(std::size_t) w.to]; };
- auto sourceLatency = [&] (const AudioWire& w) { return w.from >= 0 ? nodes[(std::size_t) w.from]->outLatency : 0; };
- plannedOwn.resize ((std::size_t) count);
- plannedEnabled.resize ((std::size_t) count);
- for (int i = 0; i < count; ++i)
- {
- plannedEnabled[(std::size_t) i] = doc.nodes[(std::size_t) i].generator || doc.nodes[(std::size_t) i].effect.enabled ? 1 : 0;
- plannedOwn[(std::size_t) i] = ownLatency (i, plannedEnabled[(std::size_t) i] != 0);
- }
- {
- std::vector<int> in, out;
- latency = planLatencies (plannedOwn, in, out);
- for (int i = 0; i < count; ++i)
- {
- nodes[(std::size_t) i]->inLatency = in[(std::size_t) i];
- nodes[(std::size_t) i]->outLatency = out[(std::size_t) i];
- }
- }
- for (auto& w : wires)
- {
- if (! runsBefore (w))
- continue;
- const auto target = w.to >= 0 ? nodes[(std::size_t) w.to]->inLatency : latency; // every output aligned to the longest
- const auto difference = target - sourceLatency (w);
- if (difference > 0)
- w.delay = std::make_shared<DelayLine> (difference);
- }
- outputs.resize (aux.size() + 1);
- for (std::size_t k = 0; k < wires.size(); ++k)
- if (wires[k].to == patchToHost && wires[k].toBus < (int) outputs.size())
- outputs[(std::size_t) wires[k].toBus].push_back ((int) k);
- // round 190ts (setStoppedSleep): which nodes may sleep while stopped
- canWholeSleep = ! hardwareNodes;
- for (int i = 0; i < count; ++i)
- {
- auto& node = *nodes[(std::size_t) i];
- const auto& src = doc.nodes[(std::size_t) i];
- if (node.generator)
- {
- // (a hosted generator keeps running: its idle() is FL's smart disable, which the rack asks itself)
- node.nested = graphOf (node.instrument.get());
- node.sleeps = node.instrument != nullptr && node.vfx == nullptr && ! node.plugin && node.nested == nullptr;
- if (node.nested != nullptr)
- nestedGraphs.push_back (node.nested);
- else if (! node.sleeps && node.vfx == nullptr)
- canWholeSleep = false;
- continue;
- }
- node.nested = src.effect.kind == EffectKind::patcher ? graphOf (node.effect.get()) : nullptr;
- if (node.nested != nullptr)
- {
- nestedGraphs.push_back (node.nested);
- if (node.sidechain)
- canWholeSleep = false;
- continue;
- }
- const auto drivesControls = std::any_of (controls.begin(), controls.end(), [i] (const ControlWire& c) { return c.from == i; });
- node.sleeps = node.effect != nullptr && ! node.sidechain && ! node.hardware && ! drivesControls && sleepableDevice (src.effect)
- && std::all_of (node.heads.begin(), node.heads.end(), [] (const Node::Head& h) { return h.effect == nullptr || sleepableDevice (h.slot); });
- canWholeSleep = canWholeSleep && node.sleeps;
- }
- for (auto& s : scratch)
- s.assign ((std::size_t) capacity, 0.0f);
- zeros.assign ((std::size_t) capacity, 0.0f);
- active = std::make_unique<Values>();
- takeValues (doc, 140.0);
- applyPending();
- }
- int Graph::ownLatency (int i, bool enabled) const noexcept
- {
- const auto& node = *nodes[(std::size_t) i];
- if (node.generator)
- return node.instrument != nullptr ? std::max (0, node.instrument->latencySamples()) : 0;
- return enabled && node.effect != nullptr ? std::max (0, node.effect->latencySamples()) : 0;
- }
- int Graph::planLatencies (const std::vector<int>& own, std::vector<int>& in, std::vector<int>& out) const
- {
- const auto count = nodes.size();
- in.assign (count, 0);
- out.assign (count, 0);
- std::vector<int> position (count, 0);
- for (std::size_t k = 0; k < order.size(); ++k)
- position[(std::size_t) order[k]] = (int) k;
- auto runsBefore = [&] (const AudioWire& w) { return w.from < 0 || w.to < 0 || position[(std::size_t) w.from] < position[(std::size_t) w.to]; };
- auto sourceLatency = [&] (const AudioWire& w) { return w.from >= 0 ? out[(std::size_t) w.from] : 0; };
- for (const auto i : order)
- {
- const auto& node = *nodes[(std::size_t) i];
- int latest = 0;
- for (const auto k : node.mainInputs)
- if (runsBefore (wires[(std::size_t) k]))
- latest = std::max (latest, sourceLatency (wires[(std::size_t) k]));
- for (const auto k : node.sideInputs)
- if (runsBefore (wires[(std::size_t) k]))
- latest = std::max (latest, sourceLatency (wires[(std::size_t) k]));
- in[(std::size_t) i] = latest;
- out[(std::size_t) i] = latest + std::max (0, own[(std::size_t) i]);
- }
- int longest = 0;
- for (const auto& w : wires)
- if (w.to == patchToHost && w.toBus <= (int) aux.size())
- longest = std::max (longest, sourceLatency (w));
- return longest;
- }
- bool Graph::latencyStale (const PatcherDoc* doc) const
- {
- for (std::size_t i = 0; i < nodes.size() && i < plannedOwn.size(); ++i)
- {
- const auto* src = doc != nullptr && i < doc->nodes.size() ? &doc->nodes[i] : nullptr;
- const auto enabled = src != nullptr ? (src->generator || src->effect.enabled) : plannedEnabled[i] != 0;
- if (ownLatency ((int) i, enabled) != plannedOwn[i])
- return true;
- // a nested Patcher: a node switched on / off in its own document
- const auto& node = *nodes[i];
- const auto* nested = node.generator ? graphOf (node.instrument.get()) : graphOf (node.effect.get());
- if (nested != nullptr && src != nullptr && src->generator == node.generator
- && nested->latencyStale (node.generator ? &src->channel.patcher : &src->effect.patcher))
- return true;
- }
- return false;
- }
- int Graph::latencySamples() const
- {
- if (! latencyStale())
- return latency;
- // a node's latency moved since the plan (issue #113): report what the graph will have once the rack builds it
- // again, so the mixer sees the change and rebuilds it (the UI thread polls the rack's latencies)
- std::vector<int> own (plannedOwn.size(), 0), in, out;
- for (std::size_t i = 0; i < own.size(); ++i)
- own[i] = ownLatency ((int) i, plannedEnabled[i] != 0);
- return planLatencies (own, in, out);
- }
- Graph::~Graph()
- {
- delete pending.exchange (nullptr);
- delete retired.exchange (nullptr);
- }
- void Graph::takeValues (const PatcherDoc& doc, double bpm)
- {
- auto values = std::make_unique<Values>();
- values->nodes.resize (nodes.size());
- for (std::size_t i = 0; i < nodes.size() && i < doc.nodes.size(); ++i)
- {
- const auto& src = doc.nodes[i];
- auto& v = values->nodes[i];
- if (! src.generator)
- {
- v.params = src.effect.params;
- v.enabled = src.effect.enabled;
- v.mix = src.effect.mix;
- }
- for (const auto& h : nodes[i]->heads)
- {
- const auto head = busHeadOf (src, h.bus);
- v.heads.push_back (head && head->head ? head->head->params : h.slot.params);
- v.headGains.push_back (head ? head->gain : h.gain);
- }
- if (src.generator && nodes[i]->instrument != nullptr)
- nodes[i]->instrument->configure (src.channel, bpm);
- }
- for (const auto& w : wires)
- {
- const auto& src = doc.wires[(std::size_t) w.docIndex];
- values->gains.push_back (std::isfinite (src.gain) ? src.gain : 1.0f);
- values->on.push_back (src.enabled ? 1 : 0);
- }
- for (int k = 0; k < doc.surfaceOutputs(); ++k)
- values->surface.push_back (std::clamp (doc.surfaceOutput (k), 0.0f, 1.0f));
- delete retired.exchange (nullptr);
- delete pending.exchange (values.release());
- }
- void Graph::applyPending() noexcept
- {
- if (auto* incoming = pending.exchange (nullptr))
- {
- auto* old = active.release();
- active.reset (incoming);
- delete retired.exchange (old); // (normally null: the UI frees it on its next call)
- }
- }
- void Graph::prepare (double sampleRate) noexcept
- {
- if (sampleRate == rate)
- return;
- rate = sampleRate;
- for (auto& n : nodes)
- {
- if (n->effect != nullptr)
- n->effect->prepare (sampleRate);
- if (n->instrument != nullptr)
- n->instrument->prepare (sampleRate);
- for (auto& h : n->heads)
- if (h.effect != nullptr)
- h.effect->prepare (sampleRate);
- }
- }
- void Graph::reset() noexcept
- {
- for (auto& n : nodes)
- {
- if (n->effect != nullptr)
- n->effect->reset();
- for (auto& h : n->heads)
- if (h.effect != nullptr)
- h.effect->reset();
- for (auto& o : n->out)
- for (auto& side : o)
- std::fill (side.begin(), side.end(), 0.0f);
- }
- }
- void Graph::setSongPosition (double position) noexcept
- {
- ticks = position;
- playing = hostTimeline().playing.load (std::memory_order_relaxed);
- for (auto& n : nodes)
- {
- if (n->effect != nullptr)
- n->effect->setSongPosition (position);
- if (n->instrument != nullptr)
- n->instrument->setSongPosition (position);
- for (auto& h : n->heads)
- if (h.effect != nullptr)
- h.effect->setSongPosition (position);
- }
- }
- void Graph::setPlaying (bool on) noexcept
- {
- playing = on;
- for (auto& n : nodes)
- if (n->effect != nullptr)
- n->effect->setPlaying (on);
- }
- void Graph::setStoppedSleep (bool on) noexcept
- {
- if (on == sleepOk)
- return;
- sleepOk = on;
- wholeAsleep = allNodesAsleep = false;
- quietSamples = 0;
- for (auto& n : nodes)
- {
- n->silentSamples = 0;
- n->asleep = false;
- }
- for (auto* g : nestedGraphs)
- g->setStoppedSleep (on);
- }
- int Graph::sleepHold (const Node& node) const noexcept
- {
- // (as the mixer's smart disable takes a built-in's declared tail, round 190gp; an undeclared one waits 4 s of silence:
- // the plugins' hold, longer than the mixer's 1 s for built-ins, so a long echo or reverb never stops early)
- const auto fixed = (int) (rate * 4.0);
- if (! declaredTails() || node.effect == nullptr)
- return fixed;
- auto tail = node.effect->tailSamples();
- for (const auto& h : node.heads)
- if (h.effect != nullptr)
- {
- const auto t = h.effect->tailSamples();
- tail = tail < 0 || t < 0 ? -1 : std::max (tail, t);
- }
- return tail < 0 ? fixed : std::clamp (tail, 1, fixed);
- }
- void Graph::setHeldNotes (const NoteMask* channels, int count) noexcept
- {
- for (auto& n : nodes)
- if (n->effect != nullptr)
- n->effect->setHeldNotes (channels, count);
- }
- bool Graph::followsHeldNotes() const noexcept
- {
- for (const auto& n : nodes)
- if (n->effect != nullptr && n->effect->followsHeldNotes())
- return true;
- return false;
- }
- void Graph::noteOn (int key, float velocity) noexcept { deliver (0, true, key, velocity, -1); }
- void Graph::noteOff (int key) noexcept { deliver (0, false, key, 0.0f, -1); }
- void Graph::noteOnMidi (int key, float velocity, int midiChannel) noexcept { deliver (0, true, key, velocity, midiChannel); }
- void Graph::noteOffMidi (int key, int midiChannel) noexcept { deliver (0, false, key, 0.0f, midiChannel); }
- std::vector<Graph::MidiTarget> Graph::midiTargetsOf (const PatcherDoc& doc, int from, int pin) const
- {
- std::vector<MidiTarget> targets;
- const auto count = (int) doc.nodes.size();
- std::vector<char> seen ((std::size_t) count, 0);
- // (source, its pin, the channel set on the way)
- std::vector<std::tuple<int, int, int>> todo { { from, pin, -1 } };
- while (! todo.empty())
- {
- const auto [source, sourcePin, channel] = todo.back();
- todo.pop_back();
- for (const auto& w : doc.wires)
- {
- if (w.kind != PatchWire::Kind::midi || ! w.enabled || w.from != source || w.fromPort != sourcePin || w.to < 0 || w.to >= count
- || seen[(std::size_t) w.to])
- continue;
- seen[(std::size_t) w.to] = 1;
- const auto& target = doc.nodes[(std::size_t) w.to];
- if (! target.generator)
- continue;
- if (target.channel.instrument == InstrumentKind::midiOut)
- todo.emplace_back (w.to, 0, midictl::parseMidiOut (target.channel.pluginState).channel);
- else
- targets.push_back ({ w.to, channel, target.channel.instrument == InstrumentKind::vfx, target.channel.instrument == InstrumentKind::layer,
- source == from && w.zone >= 0 && w.zone < (int) doc.zones.size() ? w.zone : -1 });
- }
- }
- return targets;
- }
- template <typename F>
- void Graph::forLayeredTargets (const std::vector<MidiTarget>& targets, int type, int key, F&& f) noexcept
- {
- for (const auto& t : targets)
- {
- if (! t.layer)
- {
- f (t, key, 1.0f, 0.0f, 0.0f, false);
- continue;
- }
- auto* l = (std::size_t) t.node < layers.size() ? layers[(std::size_t) t.node].get() : nullptr;
- if (l == nullptr || l->children.empty())
- continue;
- const auto& self = l->defs[(std::size_t) t.node];
- const auto pan = self.pan, cents = layer::pitchCents (self);
- auto child = [&t] (MidiTarget c) {
- if (c.midiChannel < 0)
- c.midiChannel = t.midiChannel; // (a MIDI Out node before the Layer sets the channel, one after it wins)
- return c;
- };
- auto childOf = [&] (int node) -> const MidiTarget* {
- for (const auto& c : l->children)
- if (c.node == node)
- return &c;
- return nullptr;
- };
- const auto k = std::clamp (key, 0, 127);
- // a child with Add to key (Split children) sounds its own pitch on its key, as on a channel (the rack's key shift)
- auto keyOf = [&] (int node) {
- const auto& d = l->defs[(std::size_t) node];
- return d.misc.addToKey && d.instrument != InstrumentKind::sampler ? std::clamp (key + 60 - d.misc.rootNote, 0, 127) : key;
- };
- const auto one = self.layer.random || self.layer.sequential;
- if (type == 1)
- {
- std::array<layer::Pick, 64> picks;
- const auto n = layer::pick (self, l->defs, k, l->random, l->turn, picks.data(), (int) picks.size());
- if (one)
- l->picked[(std::size_t) k] = n > 0 ? picks[0].child : -1;
- const auto level = layer::levelGain (self);
- for (int p = 0; p < n; ++p)
- if (const auto* c = childOf (picks[(std::size_t) p].child))
- f (child (*c), keyOf (c->node), level * picks[(std::size_t) p].gain, pan, cents, true);
- }
- else if (type == 0 && one && l->picked[(std::size_t) k] >= 0)
- {
- if (const auto* c = childOf (l->picked[(std::size_t) k]))
- f (child (*c), keyOf (c->node), 1.0f, pan, cents, true);
- l->picked[(std::size_t) k] = -1;
- }
- else // (a note off of every child — also when the Layer was rebuilt while the note was held — or a CC / bend)
- for (const auto& c : l->children)
- f (child (c), keyOf (c.node), 1.0f, pan, cents, true);
- }
- }
- void Graph::choke (int zone) noexcept
- {
- // Live's choke groups (round 190ec): a pad that starts a note stops every other pad of its group (their
- // instruments' cut: the sampler's short declick, as an FL cut group)
- const auto& self = zoneStates[(std::size_t) zone].zone;
- for (std::size_t z = 0; z < zoneStates.size(); ++z)
- {
- const auto& other = zoneStates[z].zone;
- if ((int) z == zone || other.choke != self.choke || other.chokeNode < 0 || other.chokeNode == self.chokeNode
- || other.chokeNode >= (int) nodes.size())
- continue;
- if (auto& i = nodes[(std::size_t) other.chokeNode]->instrument)
- i->cut();
- }
- }
- bool Graph::zoneGate (int zone, bool on, int& key, int midiChannel, float& velocity) noexcept
- {
- if (zone < 0 || zone >= (int) zoneStates.size())
- return true;
- auto& s = zoneStates[(std::size_t) zone];
- const auto k = (std::size_t) std::clamp (key, 0, 127);
- const auto bit = (std::uint16_t) (1u << (midiChannel < 0 ? 0 : (midiChannel & 15)));
- if (! on)
- {
- if ((s.held[k] & bit) == 0)
- return false;
- s.held[k] = (std::uint16_t) (s.held[k] & ~bit);
- if (s.zone.playKey >= 0)
- key = s.zone.playKey;
- return true;
- }
- const auto& surface = active->surface;
- const auto selector = s.zone.selector >= 0 && s.zone.selector < (int) surface.size()
- ? rack::zoneSelector (s.zone, surface[(std::size_t) s.zone.selector])
- : 0.0f;
- const auto v = rack::zoneVelocity (s.zone, (int) k, velocity, selector);
- if (v <= 0.0f)
- return false;
- velocity = v;
- s.held[k] = (std::uint16_t) (s.held[k] | bit);
- if (s.zone.choke > 0)
- choke (zone);
- if (s.zone.playKey >= 0)
- key = s.zone.playKey;
- return true;
- }
- void Graph::deliver (int pin, bool on, int key, float velocityIn, int midiChannel) noexcept
- {
- wholeAsleep = false; // (round 190ts: something comes in: awake, idle() says so at once)
- quietSamples = 0;
- if (pin < 0 || pin >= (int) pinTargets.size())
- return;
- forLayeredTargets (pinTargets[(std::size_t) pin], on ? 1 : 0, key, [&] (const MidiTarget& t, int k, float gain, float pan, float cents, bool viaLayer) {
- auto velocity = velocityIn;
- if (t.zone >= 0 && ! zoneGate (t.zone, on, k, midiChannel, velocity)) // (k: a Drum Rack pad's Play note)
- return;
- if (t.vfx)
- {
- // into the VFX node's processor at the next piece's start, with the note's properties
- if (auto& q = vfxQueues[(std::size_t) t.node])
- {
- vfx::Event e;
- e.type = on ? vfx::Event::Type::on : vfx::Event::Type::off;
- e.voice.key = k;
- e.voice.velocity = on ? std::max (1.0e-6f, velocity * gain) : velocity;
- e.voice.pan = std::clamp (nextVoice.pan + pan, -1.0f, 1.0f);
- e.voice.cents = nextVoice.cents + cents;
- e.voice.modX = nextVoice.modX;
- e.voice.modY = nextVoice.modY;
- e.voice.release = nextVoice.release;
- e.voice.porta = nextVoice.porta;
- const auto channel = t.midiChannel >= 0 ? t.midiChannel : midiChannel;
- e.voice.colour = channel >= 0 ? (channel & 15) : nextVoice.colour;
- e.id = vfx::inputId (k, e.voice.colour);
- q->in.add (e);
- }
- return;
- }
- if (auto& i = nodes[(std::size_t) t.node]->instrument)
- {
- const auto channel = t.midiChannel >= 0 ? t.midiChannel : midiChannel;
- auto v = velocity;
- if (on && viaLayer) // a Layer's child (round 165c): the Layer's pan, pitch and level on top of the note's
- {
- i->setNextNoteExpression (std::clamp (nextVoice.pan + pan, -1.0f, 1.0f), nextVoice.cents + cents, nextVoice.porta);
- if (gain != 1.0f && ! i->setNextNoteGain (gain))
- v = std::max (1.0e-6f, v * gain);
- }
- if (channel < 0)
- on ? i->noteOn (k, v) : i->noteOff (k);
- else
- on ? i->noteOnMidi (k, v, channel) : i->noteOffMidi (k, channel);
- }
- });
- if (! on)
- nextVoice.release = 0.5f;
- else
- nextVoice = {};
- }
- void Graph::noteOnPort (int port, int key, float velocity, int midiChannel) noexcept
- {
- if (port >= 0 && port < patchMidiPorts)
- deliver (patchMidiPortPin (port), true, key, velocity, midiChannel);
- }
- void Graph::noteOffPort (int port, int key, int midiChannel) noexcept
- {
- if (port >= 0 && port < patchMidiPorts)
- deliver (patchMidiPortPin (port), false, key, 0.0f, midiChannel);
- }
- void Graph::queueTimed (int pin, int key, float velocity, int midiChannel, int offset) noexcept
- {
- wholeAsleep = false; // (round 190ts: something comes in: awake, idle() says so at once)
- quietSamples = 0;
- if (pin < 0 || pin >= (int) pinTargets.size() || pinTargets[(std::size_t) pin].empty() || timedCount >= timedCapacity)
- return;
- timed[(std::size_t) timedCount++] = { pin, key, midiChannel, std::max (0, offset), velocity };
- }
- void Graph::queueNoteOnPort (int port, int key, float velocity, int midiChannel, int offset) noexcept
- {
- if (port >= 0 && port < patchMidiPorts)
- queueTimed (patchMidiPortPin (port), key, std::max (velocity, 1.0e-6f), midiChannel, offset);
- }
- void Graph::queueNoteOffPort (int port, int key, int midiChannel, int offset) noexcept
- {
- if (port >= 0 && port < patchMidiPorts)
- queueTimed (patchMidiPortPin (port), key, 0.0f, midiChannel, offset);
- }
- void Graph::routeNote (const std::vector<MidiTarget>& targets, int sourceNode, bool on, int key, float velocityIn, int midiChannel, int offset) noexcept
- {
- forLayeredTargets (targets, on ? 1 : 0, key, [&] (const MidiTarget& t, int k, float gain, float pan, float cents, bool) {
- auto velocity = velocityIn;
- if (t.zone >= 0 && ! zoneGate (t.zone, on, k, midiChannel, velocity))
- return;
- const auto channel = t.midiChannel >= 0 ? t.midiChannel : midiChannel;
- vfx::Event e;
- e.type = on ? vfx::Event::Type::on : vfx::Event::Type::off;
- e.offset = offset;
- e.voice.key = k;
- e.voice.velocity = velocity;
- e.voice.pan = pan;
- e.voice.cents = cents;
- e.voice.colour = channel >= 0 ? (channel & 15) : 0;
- e.id = vfx::inputId (k, e.voice.colour);
- if (sourceNode >= 0)
- e.id += (sourceNode + 1) * (1 << 20); // (ids of different sources never meet)
- if (t.vfx)
- {
- if (auto& q = vfxQueues[(std::size_t) t.node])
- {
- if (on)
- e.voice.velocity = std::max (1.0e-6f, velocity * gain);
- q->in.add (e);
- }
- }
- else if (noteOuts.size() < noteOuts.capacity())
- noteOuts.push_back ({ t.node, channel, e, gain });
- });
- }
- template <typename F>
- void Graph::forNoteTargets (F&& f) noexcept
- {
- if (pinTargets.empty())
- return;
- forLayeredTargets (pinTargets[0], 2, 60, [&] (const MidiTarget& t, int, float, float, float, bool) { // (a Layer's children too)
- if (auto& i = nodes[(std::size_t) t.node]->instrument)
- f (*i);
- });
- }
- void Graph::midiMessage (const std::uint8_t* bytes, int size) noexcept
- {
- wholeAsleep = false; // (round 190ts: something comes in: awake, idle() says so at once)
- quietSamples = 0;
- forNoteTargets ([&] (Instrument& i) { i.midiMessage (bytes, size); });
- }
- void Graph::pitchBend (float semitones) noexcept
- {
- forNoteTargets ([&] (Instrument& i) { i.pitchBend (semitones); });
- }
- void Graph::controlChange (int cc, float value) noexcept
- {
- forNoteTargets ([&] (Instrument& i) { i.controlChange (cc, value); });
- }
- // Issue #271 (round 190qo): a slide note's velocity / pan / Mod X / Y on the channel's own notes ("From LYNX SHARE" pin 0
- // Notes), passed to what those notes reach — FL's Patcher hands its notes' properties on (FL 2026 /R render of its Patcher
- // render test, a 3x Osc inside: the slide fades as 3x Osc's own channel does)
- void Graph::voiceProperty (int key, int prop, float value) noexcept
- {
- if (! voiceProps.load (std::memory_order_relaxed) || pinTargets.empty())
- return;
- forLayeredTargets (pinTargets[0], 2, key, [&] (const MidiTarget& t, int k, float, float, float, bool) {
- if (t.vfx)
- {
- if (auto& q = vfxQueues[(std::size_t) t.node])
- {
- vfx::Event e;
- e.type = vfx::Event::Type::prop;
- e.voice.key = k;
- e.voice.colour = (t.midiChannel >= 0 ? t.midiChannel : 0) & 15;
- e.id = vfx::inputId (k, e.voice.colour);
- e.prop = (vfx::Prop) std::clamp (prop, 0, 4);
- e.value = value;
- q->in.add (e);
- }
- }
- else if (auto& i = nodes[(std::size_t) t.node]->instrument)
- i->voiceProperty (k, prop, value);
- });
- }
- void Graph::voicePropertyPort (int port, int key, int prop, float value, int midiChannel) noexcept
- {
- if (port < 0 || port >= patchMidiPorts)
- return;
- forLayeredTargets (pinTargets[(std::size_t) patchMidiPortPin (port)], 2, key, [&] (const MidiTarget& t, int k, float, float, float, bool) {
- if (t.vfx)
- {
- if (auto& q = vfxQueues[(std::size_t) t.node])
- {
- vfx::Event e;
- e.type = vfx::Event::Type::prop;
- e.voice.key = k;
- e.voice.colour = (t.midiChannel >= 0 ? t.midiChannel : std::max (0, midiChannel)) & 15;
- e.id = vfx::inputId (k, e.voice.colour);
- e.prop = (vfx::Prop) std::clamp (prop, 0, 4);
- e.value = value;
- q->in.add (e);
- }
- }
- else if (auto& i = nodes[(std::size_t) t.node]->instrument)
- i->voiceProperty (k, prop, value);
- });
- }
- int Graph::takeHostEvents (Instrument::PortEvent* out, int max) noexcept
- {
- const auto n = std::min (hostEventCount, std::max (0, max));
- for (int k = 0; k < n; ++k)
- out[k] = hostEvents[(std::size_t) k];
- for (int k = n; k < hostEventCount; ++k)
- hostEvents[(std::size_t) (k - n)] = hostEvents[(std::size_t) k];
- hostEventCount -= n;
- return n;
- }
- bool Graph::takesMidiPort (int port) const noexcept
- {
- return port >= 0 && port < patchMidiPorts && ! pinTargets[(std::size_t) patchMidiPortPin (port)].empty();
- }
- void Graph::allNotesOff() noexcept
- {
- timedCount = 0;
- // the VFX nodes' voices end (their instruments stop below anyway); their queues empty
- for (const auto i : vfxOrder)
- {
- auto& q = *vfxQueues[(std::size_t) i];
- q.in.clear();
- q.out.clear();
- nodes[(std::size_t) i]->vfx->releaseAll (q.out);
- q.out.clear();
- }
- for (auto& n : nodes)
- if (n->instrument != nullptr)
- n->instrument->allNotesOff();
- for (auto& z : zoneStates) // (round 183c: nothing is held through a rack chain's zones any more)
- z.held.fill (0);
- }
- void Graph::cut() noexcept
- {
- for (auto& n : nodes)
- if (n->instrument != nullptr)
- n->instrument->cut();
- }
- void Graph::slideTo (int key, float cents, float samples) noexcept
- {
- for (const auto t : noteTargets)
- {
- if ((std::size_t) t < layers.size() && layers[(std::size_t) t] != nullptr) // (a Layer: its children slide, round 165c)
- for (const auto& c : layers[(std::size_t) t]->children)
- if (auto& i = nodes[(std::size_t) c.node]->instrument)
- i->slideTo (key, cents, samples);
- if (auto& i = nodes[(std::size_t) t]->instrument)
- i->slideTo (key, cents, samples);
- }
- }
- void Graph::setNextNoteModulation (float modX, float modY) noexcept
- {
- nextVoice.modX = modX;
- nextVoice.modY = modY;
- }
- void Graph::setNextNoteRelease (float velocity) noexcept { nextVoice.release = velocity; }
- void Graph::setNextNoteColour (int colour) noexcept { nextVoice.colour = colour & 15; }
- void Graph::setNextNoteExpression (float pan, float cents, bool porta) noexcept
- {
- nextVoice.pan = pan;
- nextVoice.cents = cents;
- nextVoice.porta = porta;
- for (const auto t : noteTargets)
- if (auto& i = nodes[(std::size_t) t]->instrument)
- i->setNextNoteExpression (pan, cents, porta);
- }
- bool Graph::hasInstruments() const noexcept
- {
- return std::any_of (nodes.begin(), nodes.end(), [] (const auto& n) { return n->instrument != nullptr; });
- }
- bool Graph::instrumentsIdle() const noexcept
- {
- // (a VFX node that holds voices or plays on its own — a sequencer — keeps the graph running; so do notes still on
- // their way: queued, waiting at a VFX node for the next piece, or played to the host and not yet taken (round 183c: a
- // MIDI Effect Rack's chains are VFX nodes only, and a note reaches them one piece after it came in))
- if (timedCount > 0 || hostEventCount > 0
- || std::any_of (vfxQueues.begin(), vfxQueues.end(), [] (const auto& q) { return q != nullptr && q->in.size() > 0; }))
- return false;
- return std::all_of (nodes.begin(), nodes.end(), [] (const auto& n) {
- return (n->instrument == nullptr || n->instrument->idle()) && (n->vfx == nullptr || ! n->vfx->busy());
- });
- }
- float Graph::controlOutput (int) const noexcept { return 0.0f; }
- void Graph::setPublished (int k, float v) noexcept
- {
- if (k < 0 || k >= (int) published.size())
- return;
- const auto& p = published[(std::size_t) k];
- if (p.node == patchSurface && p.param >= 0) // a rack's macro / selector (round 183c): the Surface control, at the next block
- {
- publishedValues[(std::size_t) k] = std::clamp (mapControl (p.curve, v), 0.0f, 1.0f);
- return;
- }
- if (p.node < 0 || p.node >= (int) nodes.size() || p.param < 0)
- return;
- const auto value = mapControl (p.curve, v);
- auto& node = *nodes[(std::size_t) p.node];
- if (node.generator)
- {
- if (node.instrument != nullptr)
- node.instrument->setParameter (p.param, value);
- }
- else if (node.plugin)
- node.effect->setParameter (p.param, value);
- else if (p.param < maxEffectParams)
- publishedValues[(std::size_t) k] = value; // (applied at the start of each block, over the UI's values)
- }
- const float* Graph::auxOutput (int index, int side) const noexcept
- {
- return index >= 0 && index < (int) aux.size() ? aux[(std::size_t) index][(std::size_t) (side & 1)].data() : nullptr;
- }
- std::shared_ptr<Effect> Graph::effectAt (int node) const
- {
- return node >= 0 && node < (int) nodes.size() ? nodes[(std::size_t) node]->effect : nullptr;
- }
- std::shared_ptr<Instrument> Graph::instrumentAt (int node) const
- {
- return node >= 0 && node < (int) nodes.size() ? nodes[(std::size_t) node]->instrument : nullptr;
- }
- namespace
- {
- std::uint64_t nowNs() noexcept
- {
- return (std::uint64_t) std::chrono::duration_cast<std::chrono::nanoseconds> (std::chrono::steady_clock::now().time_since_epoch()).count();
- }
- float blockPeak (const float* l, const float* r, int n) noexcept
- {
- float p = 0.0f;
- for (int i = 0; i < n; ++i)
- p = std::max (p, std::max (std::abs (l[i]), std::abs (r[i])));
- return p;
- }
- void raisePeak (std::atomic<float>& a, float p) noexcept
- {
- if (p > a.load (std::memory_order_relaxed))
- a.store (p, std::memory_order_relaxed);
- }
- } // namespace
- float Graph::takeNodePeak (int node) noexcept
- {
- return node >= 0 && node < (int) nodes.size() ? nodes[(std::size_t) node]->peak.exchange (0.0f, std::memory_order_relaxed) : 0.0f;
- }
- std::uint64_t Graph::nodeNanoseconds (int node) const noexcept
- {
- return node >= 0 && node < (int) nodes.size() ? nodes[(std::size_t) node]->ns.load (std::memory_order_relaxed) : 0u;
- }
- void Graph::process (const float* inL, const float* inR, const float* scL, const float* scR, float* outL, float* outR, int n, double bpm) noexcept
- {
- const auto watched = watchLeft.load (std::memory_order_relaxed) > 0; // round 190ld (View › Activity / Performance)
- const auto start = watched ? nowNs() : 0u;
- if (watched)
- raisePeak (inputPeak, blockPeak (inL, inR, n));
- for (int done = 0; done < n; done += capacity)
- {
- const auto piece = std::min (capacity, n - done);
- pieceOffset = hwOffset + done;
- processPiece (inL + done, inR + done, scL != nullptr ? scL + done : nullptr, scR != nullptr ? scR + done : nullptr, outL + done,
- outR + done, piece, bpm);
- }
- if (watched)
- {
- graphNs.fetch_add (nowNs() - start, std::memory_order_relaxed);
- framesWatched.fetch_add ((std::uint64_t) n, std::memory_order_relaxed);
- watchLeft.fetch_sub (n, std::memory_order_relaxed);
- }
- }
- void Graph::processPiece (const float* inL, const float* inR, const float* scL, const float* scR, float* outL, float* outR, int n, double bpm) noexcept
- {
- applyPending();
- auto& values = *active;
- for (std::size_t k = 0; k < publishedValues.size(); ++k)
- if (! std::isnan (publishedValues[k]))
- {
- if (published[k].node == patchSurface) // (round 183c)
- {
- if ((std::size_t) published[k].param < values.surface.size())
- values.surface[(std::size_t) published[k].param] = publishedValues[k];
- }
- else
- values.nodes[(std::size_t) published[k].node].params[(std::size_t) published[k].param] = publishedValues[k];
- }
- // control cables: the source's latest output moves the target's parameter (one block of lag, as the mixer's links)
- for (auto& c : controls)
- {
- auto raw = 0.0f;
- if (c.from == patchSurface) // the Surface tab's control (round 151)
- raw = c.output < (int) values.surface.size() ? values.surface[(std::size_t) c.output] : 0.0f;
- else if (c.fromParam >= 0) // a node's parameter output (round 171b): its current value
- {
- const auto& source = *nodes[(std::size_t) c.from];
- if (source.generator)
- raw = source.instrument != nullptr ? source.instrument->parameterValue (c.fromParam) : -1.0f;
- else if (source.plugin)
- raw = source.effect != nullptr ? source.effect->parameterValue (c.fromParam) : -1.0f;
- else
- raw = values.nodes[(std::size_t) c.from].params[(std::size_t) c.fromParam];
- if (! (raw >= 0.0f)) // (a parameter whose value can't be read: nothing to send)
- continue;
- }
- else
- {
- const auto& source = *nodes[(std::size_t) c.from];
- raw = source.effect != nullptr && ! source.generator ? source.effect->controlOutput (c.output)
- : source.instrument != nullptr ? source.instrument->controlOutput (c.output)
- : 0.0f;
- }
- const auto v = mapControl (c.curve, raw);
- auto& target = *nodes[(std::size_t) c.to];
- // a plugin / instrument target gets the value when it changes (round 171b): a hosted plugin is not called
- // with the same value every block, and a change made in its own window stays until the source moves
- if (target.generator || target.plugin)
- {
- if (v == c.sent)
- continue;
- c.sent = v;
- }
- if (target.generator)
- {
- if (target.instrument != nullptr)
- target.instrument->setParameter (c.param, v);
- }
- else if (target.plugin)
- target.effect->setParameter (c.param, v);
- else
- values.nodes[(std::size_t) c.to].params[(std::size_t) c.param] = v;
- }
- noteOuts.clear();
- // notes queued at their sample (the rack's notes into a mixer-slot Patcher, round 164f): the ones in this piece
- if (timedCount > 0)
- {
- int kept = 0;
- for (int k = 0; k < timedCount; ++k)
- {
- auto t = timed[(std::size_t) k];
- if (t.offset < n)
- routeNote (pinTargets[(std::size_t) t.pin], -1, t.velocity > 0.0f, t.key, t.velocity, t.midiChannel, t.offset);
- else
- {
- t.offset -= n;
- timed[(std::size_t) kept++] = t;
- }
- }
- timedCount = kept;
- }
- // what the hosted plugin nodes sent out in the last piece (round 164f), at this piece's start
- for (const auto i : midiSources)
- {
- std::array<Instrument::MidiOutNote, 128> sent;
- auto& node = *nodes[(std::size_t) i];
- const auto count = node.instrument->takeMidiOutput (sent.data(), (int) sent.size());
- for (int k = 0; k < count; ++k)
- 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);
- }
- if (hasVfx)
- runVfx (n, bpm);
- // round 190ts (setStoppedSleep): every node asleep, nothing coming in and the delays emptied: the graph is skipped
- // (not while an editor watches its nodes: View › Activity / Performance)
- if (sleepOk && watchLeft.load (std::memory_order_relaxed) > 0)
- setStoppedSleep (false);
- if (sleepOk && canWholeSleep)
- {
- const auto quiet = allNodesAsleep && noteOuts.empty() && timedCount == 0 && quietBlock (inL, inR, n)
- && (scL == nullptr || scR == nullptr || quietBlock (scL, scR, n)) && instrumentsIdle();
- quietSamples = quiet ? quietSamples + n : 0;
- wholeAsleep = quiet && quietSamples > latency;
- if (wholeAsleep)
- {
- std::fill (outL, outL + n, 0.0f);
- std::fill (outR, outR + n, 0.0f);
- for (auto& a : aux)
- for (auto& side : a)
- std::fill (side.begin(), side.begin() + n, 0.0f);
- return;
- }
- }
- if (noteOuts.empty())
- {
- renderNodes (inL, inR, scL, scR, outL, outR, 0, n, bpm);
- return;
- }
- // what the VFX nodes, the queued notes and the plugins play lands at its sample: the piece is rendered in parts
- // between those samples
- sortNoteOuts();
- std::size_t next = 0;
- for (int position = 0; position < n;)
- {
- while (next < noteOuts.size() && noteOuts[next].event.offset <= position)
- playNoteOut (noteOuts[next++]);
- const auto end = next < noteOuts.size() ? std::min (n, noteOuts[next].event.offset) : n;
- if (end > position)
- renderNodes (inL + position, inR + position, scL != nullptr ? scL + position : nullptr, scR != nullptr ? scR + position : nullptr,
- outL + position, outR + position, position, end - position, bpm);
- position = end;
- }
- while (next < noteOuts.size())
- playNoteOut (noteOuts[next++]);
- }
- void Graph::runVfx (int n, double bpm) noexcept
- {
- vfx::Transport t;
- t.sampleRate = rate;
- t.bpm = bpm;
- t.ticks = ticks;
- t.playing = playing;
- for (const auto i : vfxOrder)
- {
- auto& q = *vfxQueues[(std::size_t) i];
- q.in.sortByOffset();
- q.out.clear();
- nodes[(std::size_t) i]->vfx->process (&q.in[0], q.in.size(), n, t, q.out);
- q.in.clear();
- for (int k = 0; k < q.out.size(); ++k)
- routeVfxOutput (i, q.out[k]);
- q.out.clear();
- }
- ticks += (double) n * bpm * (double) ppq / (60.0 * rate);
- }
- void Graph::sortNoteOuts() noexcept
- {
- // (stable insertion sort in place: std::stable_sort may allocate on the audio thread)
- for (std::size_t i = 1; i < noteOuts.size(); ++i)
- {
- const auto o = noteOuts[i];
- auto j = i;
- for (; j > 0 && o.event.offset < noteOuts[j - 1].event.offset; --j)
- noteOuts[j] = noteOuts[j - 1];
- noteOuts[j] = o;
- }
- }
- void Graph::routeVfxOutput (int node, const vfx::Event& e) noexcept
- {
- const auto& targets = nodes[(std::size_t) node]->vfxTargets;
- if (e.output < 0 || e.output >= (int) targets.size())
- return;
- // cabled to "To LYNX SHARE" MIDI ports (round 165c): the rack plays it on those ports at the next chunk
- if (e.type != vfx::Event::Type::program)
- for (const auto port : nodes[(std::size_t) node]->vfxHostPorts[(std::size_t) e.output])
- if (hostEventCount < hostEventCapacity)
- {
- auto& h = hostEvents[(std::size_t) hostEventCount++];
- h.port = port;
- h.key = e.voice.key;
- h.channel = e.voice.colour & 15;
- h.prop = e.type == vfx::Event::Type::prop ? (int) e.prop : -1;
- 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;
- h.pan = e.voice.pan;
- h.cents = e.voice.cents;
- h.modX = e.voice.modX;
- h.modY = e.voice.modY;
- h.release = e.voice.release;
- }
- const auto type = e.type == vfx::Event::Type::on ? 1 : e.type == vfx::Event::Type::off ? 0 : 2;
- forLayeredTargets (targets[(std::size_t) e.output], type, e.voice.key, [&] (const MidiTarget& t, int k, float gain, float pan, float cents, bool viaLayer) {
- auto ev = e;
- ev.voice.key = k;
- if (viaLayer) // a Layer's child (round 165c)
- {
- ev.voice.pan = std::clamp (ev.voice.pan + pan, -1.0f, 1.0f);
- ev.voice.cents += cents;
- }
- if (t.vfx)
- {
- if (auto& q = vfxQueues[(std::size_t) t.node])
- {
- auto in = ev;
- if (in.type == vfx::Event::Type::on)
- in.voice.velocity = std::max (1.0e-6f, in.voice.velocity * gain);
- in.output = 0;
- in.id = (node + 1) * (1 << 20) + (e.id & ((1 << 20) - 1)); // (ids of different sources never meet)
- if (t.midiChannel >= 0)
- in.voice.colour = t.midiChannel & 15;
- q->in.add (in);
- }
- }
- else if (noteOuts.size() < noteOuts.capacity())
- noteOuts.push_back ({ t.node, t.midiChannel, ev, gain });
- });
- }
- void Graph::playNoteOut (const NoteOut& o) noexcept
- {
- auto& i = nodes[(std::size_t) o.node]->instrument;
- if (i == nullptr)
- return;
- const auto& e = o.event;
- const auto& v = e.voice;
- const auto channel = o.midiChannel >= 0 ? o.midiChannel : v.colour;
- switch (e.type)
- {
- case vfx::Event::Type::on:
- i->setNextNoteExpression (v.pan, v.cents, v.porta);
- i->setNextNoteModulation (v.modX, v.modY);
- i->setNextNoteColour (v.colour);
- {
- auto velocity = v.velocity;
- if (o.gain != 1.0f && ! i->setNextNoteGain (o.gain)) // (a Layer's level, round 165c)
- velocity = std::max (1.0e-6f, velocity * o.gain);
- if (channel > 0)
- i->noteOnMidi (v.key, velocity, channel);
- else
- i->noteOn (v.key, velocity);
- }
- break;
- case vfx::Event::Type::off:
- i->setNextNoteRelease (v.release);
- if (channel > 0)
- i->noteOffMidi (v.key, channel);
- else
- i->noteOff (v.key);
- break;
- case vfx::Event::Type::prop:
- i->voiceProperty (v.key, (int) e.prop, e.value);
- break;
- case vfx::Event::Type::program: // (a VFX Sequencer passing a program change on, round 165c)
- {
- const std::uint8_t m[2] { (std::uint8_t) (0xC0 | (channel & 15)), (std::uint8_t) std::clamp ((int) e.value, 0, 127) };
- i->midiMessage (m, 2);
- break;
- }
- }
- }
- void Graph::renderNodes (const float* inL, const float* inR, const float* scL, const float* scR, float* outL, float* outR, int start, int n,
- double bpm) noexcept
- {
- // (inL…outR point at this part of the piece; the nodes' buffers are indexed from `start`)
- auto& values = *active;
- auto sourceOf = [&] (const AudioWire& w, int side) -> const float* {
- if (w.from == patchFromHost)
- {
- if (w.fromBuffer == 1)
- return (side == 0 ? scL : scR) != nullptr ? (side == 0 ? scL : scR) : zeros.data() + start;
- return side == 0 ? inL : inR;
- }
- return nodes[(std::size_t) w.from]->out[(std::size_t) w.fromBuffer][(std::size_t) side].data() + start;
- };
- auto gather = [&] (const std::vector<int>& list, float* l, float* r) {
- std::fill (l, l + n, 0.0f);
- std::fill (r, r + n, 0.0f);
- for (const auto k : list)
- {
- const auto& w = wires[(std::size_t) k];
- const auto on = values.on[(std::size_t) k] != 0;
- const auto gain = on ? values.gains[(std::size_t) k] : 0.0f;
- const auto* sl = sourceOf (w, 0);
- const auto* sr = sourceOf (w, 1);
- if (w.delay != nullptr)
- {
- w.delay->mixInto (on ? sl : nullptr, on ? sr : nullptr, gain, l, r, n); // (keeps its line running)
- continue;
- }
- if (! on || gain == 0.0f)
- continue;
- for (int i = 0; i < n; ++i)
- {
- l[i] += sl[i] * gain;
- r[i] += sr[i] * gain;
- }
- }
- };
- auto* inBufL = scratch[0].data();
- auto* inBufR = scratch[1].data();
- auto* scBufL = scratch[2].data();
- auto* scBufR = scratch[3].data();
- const auto watched = watchLeft.load (std::memory_order_relaxed) > 0; // round 190ld: per node (View › Activity / Performance)
- std::uint64_t nodeStart = 0;
- auto measured = [&] (Node& node, const float* l, const float* r) {
- const auto end = nowNs();
- node.ns.fetch_add (end - nodeStart, std::memory_order_relaxed);
- raisePeak (node.peak, blockPeak (l, r, n));
- };
- for (const auto i : order)
- {
- auto& node = *nodes[(std::size_t) i];
- auto& v = values.nodes[(std::size_t) i];
- auto* oL = node.out[0][0].data() + start;
- auto* oR = node.out[0][1].data() + start;
- if (watched)
- nodeStart = nowNs();
- if (node.generator)
- {
- std::fill (oL, oL + n, 0.0f);
- std::fill (oR, oR + n, 0.0f);
- // (round 190ts, stopped: an idle instrument is not rendered, as the rack skips an idle channel)
- node.asleep = sleepOk && (node.nested != nullptr ? node.nested->asleep() || node.instrument->idle()
- : node.sleeps && node.instrument->idle());
- if (node.instrument != nullptr && ! node.asleep)
- node.instrument->render (oL, oR, n, 1.0f, 1.0f);
- if (watched)
- measured (node, oL, oR);
- continue;
- }
- gather (node.mainInputs, inBufL, inBufR);
- std::copy (inBufL, inBufL + n, oL);
- std::copy (inBufR, inBufR + n, oR);
- // round 190ts (setStoppedSleep): stopped, a device whose input and output stayed silent past its tail passes its
- // input through without being called
- auto quietIn = false, skip = false;
- if (sleepOk && node.sleeps)
- {
- quietIn = quietBlock (inBufL, inBufR, n);
- if (! quietIn)
- node.silentSamples = 0;
- else if (node.silentSamples >= sleepHold (node))
- skip = true;
- }
- node.asleep = skip;
- if (v.enabled && v.mix > 0.0f && ! skip)
- {
- if (node.sidechain)
- {
- gather (node.sideInputs, scBufL, scBufR);
- node.effect->setSidechain (scBufL, scBufR);
- }
- if (node.hardware) // a Hardware Insert (or a Patcher holding one): this part's device buses (round 165c)
- node.effect->setHardwareIo (hwIn, hwOut, pieceOffset + start);
- node.effect->process (oL, oR, n, v.params, bpm);
- if (v.mix < 0.999f)
- for (int k = 0; k < n; ++k)
- {
- oL[k] = inBufL[k] + (oL[k] - inBufL[k]) * v.mix;
- oR[k] = inBufR[k] + (oR[k] - inBufR[k]) * v.mix;
- }
- }
- for (std::size_t h = 0; h < node.heads.size(); ++h)
- {
- auto* hL = node.out[1 + h][0].data() + start;
- auto* hR = node.out[1 + h][1].data() + start;
- std::copy (inBufL, inBufL + n, hL);
- std::copy (inBufR, inBufR + n, hR);
- if (node.heads[h].effect != nullptr && ! skip)
- node.heads[h].effect->process (hL, hR, n, v.heads[h], bpm);
- const auto g = v.headGains[h];
- if (g != 1.0f)
- for (int k = 0; k < n; ++k)
- {
- hL[k] *= g;
- hR[k] *= g;
- }
- }
- if (sleepOk && node.sleeps && ! skip)
- {
- // (its tail: silent input and silent outputs count towards the hold)
- auto quietOut = quietIn && quietBlock (oL, oR, n);
- for (std::size_t h = 0; h < node.heads.size() && quietOut; ++h)
- quietOut = quietBlock (node.out[1 + h][0].data() + start, node.out[1 + h][1].data() + start, n);
- node.silentSamples = quietOut ? node.silentSamples + n : 0;
- }
- else if (sleepOk && node.nested != nullptr)
- node.asleep = node.nested->asleep();
- if (watched)
- measured (node, oL, oR);
- }
- if (sleepOk)
- allNodesAsleep = std::all_of (nodes.begin(), nodes.end(), [] (const auto& x) { return x->asleep || x->vfx != nullptr; });
- // "To LYNX SHARE": the main output and the extra ones
- gather (outputs[0], inBufL, inBufR);
- std::copy (inBufL, inBufL + n, outL);
- std::copy (inBufR, inBufR + n, outR);
- for (std::size_t bus = 1; bus < outputs.size(); ++bus)
- gather (outputs[bus], aux[bus - 1][0].data() + start, aux[bus - 1][1].data() + start);
- }
- // ---------------------------------------------------------------------------------------------------------------
- namespace
- {
- class PatcherEffect final : public Effect
- {
- public:
- PatcherEffect (const EffectSlot& slot, double sampleRate, const Factories& factories, const Graph* previous)
- : graph (slot.patcher, sampleRate, factories, previous)
- {
- }
- void prepare (double sampleRate) noexcept override { graph.prepare (sampleRate); }
- void reset() noexcept override { graph.reset(); }
- void setHardwareIo (const LiveInput* in, HardwareOutput* out, int offset) noexcept override
- {
- hwIn = in;
- hwOut = out;
- hwOffset = offset;
- }
- void process (float* l, float* r, int n, const EffectParams&, double bpm) noexcept override
- {
- for (int done = 0; done < n; done += Graph::capacity)
- {
- const auto piece = std::min (Graph::capacity, n - done);
- graph.setHardwareIo (hwIn, hwOut, hwOffset + done);
- graph.process (l + done, r + done, side ? sideL + done : nullptr, side ? sideR + done : nullptr, l + done, r + done, piece, bpm);
- // the first extra output goes to its insert like a Fruity Send (the rack pulls it from there)
- if (sendL != nullptr && sendR != nullptr && graph.auxOutputs() > 0)
- {
- const auto* al = graph.auxOutput (0, 0);
- const auto* ar = graph.auxOutput (0, 1);
- for (int i = 0; i < piece; ++i)
- {
- sendL[done + i] += al[i];
- sendR[done + i] += ar[i];
- }
- }
- }
- side = false;
- }
- void setSendOutput (float* l, float* r) noexcept override
- {
- sendL = l;
- sendR = r;
- }
- void setParameter (int index, float value) noexcept override { graph.setPublished (index, value); }
- void setSongPosition (double ticks) noexcept override { graph.setSongPosition (ticks); }
- void setPlaying (bool playing) noexcept override { graph.setPlaying (playing); }
- void setStoppedSleep (bool on) noexcept override { graph.setStoppedSleep (on); } // (round 190ts)
- void setSidechain (const float* l, const float* r) noexcept override
- {
- sideL = l;
- sideR = r;
- side = l != nullptr && r != nullptr;
- }
- void setHeldNotes (const NoteMask* channels, int count) noexcept override { graph.setHeldNotes (channels, count); }
- bool followsHeldNotes() const noexcept override { return graph.followsHeldNotes(); } // (round 190kz)
- int latencySamples() const noexcept override { return graph.latencySamples(); }
- Graph graph;
- private:
- const float* sideL = nullptr;
- const float* sideR = nullptr;
- bool side = false;
- float* sendL = nullptr;
- float* sendR = nullptr;
- const LiveInput* hwIn = nullptr;
- HardwareOutput* hwOut = nullptr;
- int hwOffset = 0;
- };
- class PatcherInstrument final : public Instrument
- {
- public:
- PatcherInstrument (const ChannelDef& channel, double sampleRate, const Factories& factories, const Graph* previous)
- : graph (channel.patcher, sampleRate, factories, previous)
- {
- for (auto& s : buffer)
- s.assign ((std::size_t) Graph::capacity, 0.0f);
- accumulated.resize ((std::size_t) graph.auxOutputs());
- tracks = std::make_unique<std::atomic<int>[]> ((std::size_t) std::max (1, graph.auxOutputs()));
- for (auto& a : accumulated)
- for (auto& side : a)
- side.assign (auxCapacity, 0.0f);
- configure (channel, 140.0);
- }
- void prepare (double sampleRate) noexcept override { graph.prepare (sampleRate); }
- void noteOn (int key, float velocity) noexcept override { graph.noteOn (key, velocity); }
- void noteOff (int key) noexcept override { graph.noteOff (key); }
- void allNotesOff() noexcept override { graph.allNotesOff(); }
- void cut() noexcept override { graph.cut(); }
- void midiMessage (const std::uint8_t* bytes, int size) noexcept override { graph.midiMessage (bytes, size); }
- void pitchBend (float semitones) noexcept override { graph.pitchBend (semitones); }
- void controlChange (int cc, float value) noexcept override { graph.controlChange (cc, value); }
- void noteOnMidi (int key, float velocity, int midiChannel) noexcept override { graph.noteOnMidi (key, velocity, midiChannel); }
- void noteOffMidi (int key, int midiChannel) noexcept override { graph.noteOffMidi (key, midiChannel); }
- void noteOnPort (int port, int key, float velocity, int midiChannel) noexcept override { graph.noteOnPort (port, key, velocity, midiChannel); }
- void noteOffPort (int port, int key, int midiChannel) noexcept override { graph.noteOffPort (port, key, midiChannel); }
- void voicePropertyPort (int port, int key, int prop, float value, int midiChannel) noexcept override
- {
- graph.voicePropertyPort (port, key, prop, value, midiChannel);
- }
- void voiceProperty (int key, int prop, float value) noexcept override { graph.voiceProperty (key, prop, value); } // (issue #271)
- int takePortEvents (PortEvent* out, int max) noexcept override { return graph.takeHostEvents (out, max); }
- bool followsSlides() const noexcept override { return true; } // (round 168l: a Mono channel's notes)
- void slideTo (int key, float cents, float samples) noexcept override { graph.slideTo (key, cents, samples); }
- void setNextNoteExpression (float pan, float cents, bool porta) noexcept override { graph.setNextNoteExpression (pan, cents, porta); }
- void setNextNoteModulation (float modX, float modY) noexcept override { graph.setNextNoteModulation (modX, modY); }
- void setNextNoteRelease (float velocity) noexcept override { graph.setNextNoteRelease (velocity); }
- void setNextNoteColour (int colour) noexcept override { graph.setNextNoteColour (colour); }
- void setSongPosition (double ticks) noexcept override { graph.setSongPosition (ticks); }
- void setParameter (int index, float value) noexcept override { graph.setPublished (index, value); }
- int latencySamples() const noexcept override { return graph.latencySamples(); }
- // (round 190ts: or its graph sleeps while stopped, Graph::setStoppedSleep)
- bool idle() const noexcept override
- {
- return (idleWhenQuiet.load (std::memory_order_relaxed) && graph.instrumentsIdle()) || graph.asleep();
- }
- void setStoppedSleep (bool on) noexcept override { graph.setStoppedSleep (on); }
- // (UI thread, while the audio thread renders: only atomics change here; the graph swaps its values itself)
- void configure (const ChannelDef& channel, double bpm) noexcept override
- {
- tempo.store (bpm, std::memory_order_relaxed);
- graph.voiceProps.store (channel.engineRev >= 5, std::memory_order_relaxed); // (issue #271)
- graph.takeValues (channel.patcher, bpm);
- if (tracks != nullptr)
- for (int k = 1; k <= graph.auxOutputs(); ++k)
- tracks[(std::size_t) k - 1].store (patcher::auxOutputTrack (channel, k), std::memory_order_relaxed);
- // only instruments (no effects that ring on): silent when its instruments are
- idleWhenQuiet.store (std::all_of (channel.patcher.nodes.begin(), channel.patcher.nodes.end(), [] (const PatchNode& n) { return n.generator; }),
- std::memory_order_relaxed);
- }
- void render (float* left, float* right, int n, float gainLeft, float gainRight) noexcept override
- {
- static const std::vector<float> silence ((std::size_t) Graph::capacity, 0.0f);
- for (int done = 0; done < n; done += Graph::capacity)
- {
- const auto piece = std::min (Graph::capacity, n - done);
- graph.setHardwareIo (hwIn, hwOut, hwOffset + cursor); // (cursor: where this piece starts in the chunk)
- graph.process (silence.data(), silence.data(), nullptr, nullptr, buffer[0].data(), buffer[1].data(), piece,
- tempo.load (std::memory_order_relaxed));
- for (int i = 0; i < piece; ++i)
- {
- left[done + i] += buffer[0][(std::size_t) i] * gainLeft;
- right[done + i] += buffer[1][(std::size_t) i] * gainRight;
- }
- for (int k = 0; k < graph.auxOutputs(); ++k)
- {
- const auto* al = graph.auxOutput (k, 0);
- const auto* ar = graph.auxOutput (k, 1);
- auto& acc = accumulated[(std::size_t) k];
- for (int i = 0; i < piece && cursor + i < (int) auxCapacity; ++i)
- {
- acc[0][(std::size_t) (cursor + i)] += al[i] * gainLeft;
- acc[1][(std::size_t) (cursor + i)] += ar[i] * gainRight;
- }
- }
- cursor += piece;
- }
- }
- void beginChunk (int n) noexcept override
- {
- cursor = 0;
- for (auto& a : accumulated)
- for (auto& side : a)
- std::fill (side.begin(), side.begin() + std::min<std::ptrdiff_t> (n, (std::ptrdiff_t) side.size()), 0.0f);
- }
- void setHardwareIo (const LiveInput* in, HardwareOutput* out, int offset) noexcept override
- {
- hwIn = in;
- hwOut = out;
- hwOffset = offset;
- }
- int auxOutputCount() const noexcept override { return (int) accumulated.size(); }
- int auxOutputTrack (int k) const noexcept override
- {
- return k >= 0 && k < graph.auxOutputs() && tracks != nullptr ? tracks[(std::size_t) k].load (std::memory_order_relaxed) : -1;
- }
- const float* auxOutputData (int k, int side) const noexcept override
- {
- return k >= 0 && k < (int) accumulated.size() ? accumulated[(std::size_t) k][(std::size_t) (side & 1)].data() : nullptr;
- }
- Graph graph;
- private:
- static constexpr std::size_t auxCapacity = 16384;
- std::array<std::vector<float>, 2> buffer;
- std::vector<std::array<std::vector<float>, 2>> accumulated;
- std::unique_ptr<std::atomic<int>[]> tracks; // [extra output] its insert
- int cursor = 0;
- const LiveInput* hwIn = nullptr;
- HardwareOutput* hwOut = nullptr;
- int hwOffset = 0;
- std::atomic<bool> idleWhenQuiet { true };
- std::atomic<double> tempo { 140.0 };
- };
- } // namespace
- std::vector<int> layerChildren (const PatcherDoc& doc, int node)
- {
- std::vector<int> out;
- const auto count = (int) doc.nodes.size();
- if (node < 0 || node >= count)
- return out;
- std::vector<char> seen ((std::size_t) count, 0);
- seen[(std::size_t) node] = 1;
- std::vector<int> todo { node };
- while (! todo.empty())
- {
- const auto source = todo.back();
- todo.pop_back();
- for (const auto& w : doc.wires)
- {
- 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])
- continue;
- seen[(std::size_t) w.to] = 1;
- const auto& target = doc.nodes[(std::size_t) w.to];
- if (! target.generator || target.channel.instrument == InstrumentKind::layer)
- continue;
- if (target.channel.instrument == InstrumentKind::midiOut)
- todo.push_back (w.to);
- else
- out.push_back (w.to);
- }
- }
- std::sort (out.begin(), out.end());
- return out;
- }
- bool usesHardwareIo (const PatcherDoc& doc) noexcept
- {
- for (const auto& n : doc.nodes)
- if (! n.generator && (n.effect.kind == EffectKind::hardwareInsert || (n.effect.kind == EffectKind::patcher && usesHardwareIo (n.effect.patcher))))
- return true;
- return false;
- }
- std::unique_ptr<Effect> makeEffect (const EffectSlot& slot, double sampleRate, const Factories& factories, const Effect* previous)
- {
- const auto* old = dynamic_cast<const PatcherEffect*> (previous);
- return std::make_unique<PatcherEffect> (slot, sampleRate, factories, old != nullptr ? &old->graph : nullptr);
- }
- std::unique_ptr<Instrument> makeInstrument (const ChannelDef& channel, double sampleRate, const Factories& factories, const Instrument* previous)
- {
- const auto* old = dynamic_cast<const PatcherInstrument*> (previous);
- return std::make_unique<PatcherInstrument> (channel, sampleRate, factories, old != nullptr ? &old->graph : nullptr);
- }
- Graph* graphOf (Effect* effect) noexcept
- {
- auto* p = dynamic_cast<PatcherEffect*> (effect);
- return p != nullptr ? &p->graph : nullptr;
- }
- Graph* graphOf (Instrument* instrument) noexcept
- {
- auto* p = dynamic_cast<PatcherInstrument*> (instrument);
- return p != nullptr ? &p->graph : nullptr;
- }
- bool acceptValues (Effect* effect, const EffectSlot& slot)
- {
- if (auto* g = graphOf (effect))
- {
- // a node's latency moved since the graph planned its delay compensation: build it again (issue #113)
- if (g->latencyStale (&slot.patcher))
- return false;
- g->takeValues (slot.patcher);
- return true;
- }
- return false;
- }
- bool acceptValues (Instrument* instrument, const ChannelDef& channel)
- {
- if (auto* g = graphOf (instrument))
- {
- instrument->configure (channel, 140.0); // (the rack configures it again with the song's tempo)
- return true;
- }
- return false;
- }
- int auxOutputTrack (const ChannelDef& channel, int k) noexcept
- {
- if (k <= 0)
- return channel.mixerTrack;
- if (k <= (int) channel.patcher.outputTracks.size() && channel.patcher.outputTracks[(std::size_t) k - 1] >= 0)
- return channel.patcher.outputTracks[(std::size_t) k - 1];
- return std::min (channel.mixerTrack + k, maxMixerTracks - 1);
- }
- Factories builtInFactories (double sampleRate, double bpm)
- {
- Factories f;
- f.effect = [sampleRate] (const EffectSlot& slot) -> std::shared_ptr<Effect> {
- if (slot.kind == EffectKind::plugin)
- return nullptr;
- if (slot.kind == EffectKind::patcher)
- return makeEffect (slot, sampleRate, builtInFactories (sampleRate));
- std::shared_ptr<Effect> e = lynx::makeEffect (slot);
- e->prepare (sampleRate);
- return e;
- };
- f.instrument = [sampleRate, bpm] (const ChannelDef& channel) -> std::shared_ptr<Instrument> {
- if (channel.instrument == InstrumentKind::plugin)
- return nullptr;
- if (channel.instrument == InstrumentKind::patcher)
- return makeInstrument (channel, sampleRate, builtInFactories (sampleRate, bpm));
- std::shared_ptr<Instrument> i = lynx::makeInstrument (channel.instrument);
- i->prepare (sampleRate);
- i->configure (channel, bpm);
- return i;
- };
- return f;
- }
- int addNode (PatcherDoc& doc, PatchNode node)
- {
- doc.nodes.push_back (std::move (node));
- return (int) doc.nodes.size() - 1;
- }
- void removeNode (PatcherDoc& doc, int node)
- {
- if (node < 0 || node >= (int) doc.nodes.size())
- return;
- doc.nodes.erase (doc.nodes.begin() + node);
- std::erase_if (doc.wires, [node] (const PatchWire& w) { return w.from == node || w.to == node; });
- for (auto& w : doc.wires)
- {
- if (w.from > node)
- --w.from;
- if (w.to > node)
- --w.to;
- }
- // its published parameters are freed (their indices stay); the later nodes' move down (round 171b)
- for (auto& p : doc.published)
- {
- if (p.node == node)
- p = PatchParam {};
- else if (p.node > node)
- --p.node;
- }
- }
- namespace
- {
- void insertSorted (std::vector<int>& v, int x)
- {
- if (std::find (v.begin(), v.end(), x) == v.end())
- v.insert (std::upper_bound (v.begin(), v.end(), x), x);
- }
- } // namespace
- std::vector<int> shownParamInputs (const PatcherDoc& doc, int node)
- {
- if (node < 0 || node >= (int) doc.nodes.size())
- return {};
- auto shown = doc.nodes[(std::size_t) node].paramIns;
- for (const auto& w : doc.wires)
- if (w.kind == PatchWire::Kind::control && w.to == node && w.toPort >= 0)
- insertSorted (shown, w.toPort);
- return shown;
- }
- std::vector<int> shownParamOutputs (const PatcherDoc& doc, int node)
- {
- if (node < 0 || node >= (int) doc.nodes.size())
- return {};
- auto shown = doc.nodes[(std::size_t) node].paramOuts;
- for (const auto& w : doc.wires)
- if (w.kind == PatchWire::Kind::control && w.from == node && isPatchParamOutput (w.fromPort))
- insertSorted (shown, patchOutputParam (w.fromPort));
- return shown;
- }
- int publishedIndex (const PatcherDoc& doc, int node, int param)
- {
- for (std::size_t k = 0; k < doc.published.size(); ++k)
- if (doc.published[k].node == node && doc.published[k].param == param)
- return (int) k;
- return -1;
- }
- void setParamInput (PatcherDoc& doc, int node, int param, bool on, const std::string& name)
- {
- if (node < 0 || node >= (int) doc.nodes.size() || param < 0)
- return;
- auto& ins = doc.nodes[(std::size_t) node].paramIns;
- if (on)
- {
- insertSorted (ins, param);
- if (publishedIndex (doc, node, param) < 0)
- {
- PatchParam p;
- p.node = node;
- p.param = param;
- p.name = name.empty() ? nodeName (doc.nodes[(std::size_t) node]) + " " + std::to_string (param + 1) : name;
- doc.published.push_back (std::move (p));
- }
- return;
- }
- std::erase (ins, param);
- std::erase_if (doc.wires, [node, param] (const PatchWire& w) { return w.kind == PatchWire::Kind::control && w.to == node && w.toPort == param; });
- if (const auto k = publishedIndex (doc, node, param); k >= 0)
- doc.published[(std::size_t) k] = PatchParam {};
- while (! doc.published.empty() && doc.published.back().node < 0) // (trailing free indices are dropped)
- doc.published.pop_back();
- }
- void setParamOutput (PatcherDoc& doc, int node, int param, bool on)
- {
- if (node < 0 || node >= (int) doc.nodes.size() || param < 0)
- return;
- auto& outs = doc.nodes[(std::size_t) node].paramOuts;
- if (on)
- {
- insertSorted (outs, param);
- return;
- }
- std::erase (outs, param);
- std::erase_if (doc.wires, [node, param] (const PatchWire& w) {
- return w.kind == PatchWire::Kind::control && w.from == node && w.fromPort == patchParamOutput (param);
- });
- }
- void deactivateUnusedParams (PatcherDoc& doc, int node, bool inputs)
- {
- if (node < 0 || node >= (int) doc.nodes.size())
- return;
- const auto shown = inputs ? shownParamInputs (doc, node) : shownParamOutputs (doc, node);
- for (const auto p : shown)
- {
- const auto used = std::any_of (doc.wires.begin(), doc.wires.end(), [&] (const PatchWire& w) {
- return w.kind == PatchWire::Kind::control && (inputs ? (w.to == node && w.toPort == p) : (w.from == node && w.fromPort == patchParamOutput (p)));
- });
- if (! used)
- inputs ? setParamInput (doc, node, p, false) : setParamOutput (doc, node, p, false);
- }
- }
- bool nodeHasCables (const PatcherDoc& doc, int node)
- {
- return std::any_of (doc.wires.begin(), doc.wires.end(), [node] (const PatchWire& w) { return w.from == node || w.to == node; });
- }
- void disconnectNode (PatcherDoc& doc, int node)
- {
- std::erase_if (doc.wires, [node] (const PatchWire& w) { return w.from == node || w.to == node; });
- }
- int addSurfaceControl (PatcherDoc& doc, SurfaceControl control)
- {
- doc.surface.push_back (std::move (control));
- return (int) doc.surface.size() - 1;
- }
- void removeSurfaceControl (PatcherDoc& doc, int index)
- {
- if (index < 0 || index >= (int) doc.surface.size())
- return;
- int first = 0;
- for (int i = 0; i < index; ++i)
- first += doc.surface[(std::size_t) i].outputs();
- const auto count = doc.surface[(std::size_t) index].outputs();
- doc.surface.erase (doc.surface.begin() + index);
- // its cables go; the later controls' outputs move down
- std::erase_if (doc.wires, [first, count] (const PatchWire& w) { return w.from == patchSurface && w.fromPort >= first && w.fromPort < first + count; });
- for (auto& w : doc.wires)
- if (w.from == patchSurface && w.fromPort >= first + count)
- w.fromPort -= count;
- }
- bool connect (PatcherDoc& doc, const PatchWire& wire)
- {
- const auto count = (int) doc.nodes.size();
- const auto validFrom = wire.from == patchFromHost || (wire.from >= 0 && wire.from < count)
- || (wire.from == patchSurface && wire.kind == PatchWire::Kind::control && wire.fromPort >= 0 && wire.fromPort < doc.surfaceOutputs());
- const auto validTo = wire.to == patchToHost || (wire.to >= 0 && wire.to < count);
- if (! validFrom || ! validTo || (wire.from == wire.to && wire.from >= 0 && wire.kind != PatchWire::Kind::control))
- return false;
- if (wire.kind == PatchWire::Kind::control && ((wire.from < 0 && wire.from != patchSurface) || wire.to < 0))
- return false;
- if (wire.to >= 0 && doc.nodes[(std::size_t) wire.to].generator && wire.kind == PatchWire::Kind::audio)
- return false;
- for (const auto& w : doc.wires)
- if (w.kind == wire.kind && w.from == wire.from && w.fromPort == wire.fromPort && w.to == wire.to && w.toPort == wire.toPort)
- return false;
- doc.wires.push_back (wire);
- return true;
- }
- std::string nodeName (const PatchNode& node)
- {
- auto blank = [] (const std::string& t) { return std::all_of (t.begin(), t.end(), [] (unsigned char c) { return std::isspace (c) != 0; }); };
- if (! blank (node.label))
- return node.label;
- if (node.generator)
- return ! blank (node.channel.plugin.name) ? node.channel.plugin.name : ! blank (node.channel.name) ? node.channel.name : "Instrument";
- if (node.effect.kind == EffectKind::plugin)
- return ! blank (node.effect.plugin.name) ? node.effect.plugin.name : "Plugin";
- return effectInfo (node.effect.kind).name;
- }
- // --- MIDI through the I/O nodes (round 162) ---
- namespace
- {
- void addSorted (std::vector<int>& v, int x)
- {
- if (std::find (v.begin(), v.end(), x) == v.end())
- v.insert (std::upper_bound (v.begin(), v.end(), x), x);
- }
- } // namespace
- std::vector<int> shownFromMidiPorts (const PatcherDoc& doc)
- {
- std::vector<int> ports;
- for (const auto p : doc.fromMidiPorts)
- if (p >= 0 && p < patchMidiPorts)
- addSorted (ports, p);
- for (const auto& w : doc.wires)
- if (w.kind == PatchWire::Kind::midi && w.from == patchFromHost && w.fromPort > 0 && patchPinMidiPort (w.fromPort) < patchMidiPorts)
- addSorted (ports, patchPinMidiPort (w.fromPort));
- return ports;
- }
- std::vector<int> shownToMidiPorts (const PatcherDoc& doc)
- {
- std::vector<int> ports;
- for (const auto p : doc.toMidiPorts)
- if (p >= 0 && p < patchMidiPorts)
- addSorted (ports, p);
- for (const auto& w : doc.wires)
- if (w.kind == PatchWire::Kind::midi && w.to == patchToHost && w.toPort >= 0 && w.toPort < patchMidiPorts)
- addSorted (ports, w.toPort);
- return ports;
- }
- int shownMidiOutputs (const PatcherDoc& doc, int node)
- {
- if (node < 0 || node >= (int) doc.nodes.size())
- return 0;
- const auto ports = nodePorts (doc.nodes[(std::size_t) node]);
- const auto kind = vfx::kindOf (doc.nodes[(std::size_t) node].channel);
- if (! kind)
- return ports.midiOuts;
- int highest = -1;
- for (const auto& w : doc.wires)
- if (w.kind == PatchWire::Kind::midi && w.from == node)
- highest = std::max (highest, w.fromPort);
- return std::clamp (std::max (vfx::outputsShown (*kind), highest + 2), 1, ports.midiOuts);
- }
- bool fromNotesShown (const PatcherDoc& doc, bool generator)
- {
- if (std::any_of (doc.wires.begin(), doc.wires.end(),
- [] (const PatchWire& w) { return w.kind == PatchWire::Kind::midi && w.from == patchFromHost && w.fromPort == 0; }))
- return true;
- return generator && ! doc.fromNotesHidden; // (a mixer slot has no notes of its own)
- }
- std::vector<int> midiInputPorts (const PatcherDoc& doc)
- {
- std::vector<int> ports;
- for (const auto& w : doc.wires)
- if (w.kind == PatchWire::Kind::midi && w.enabled && w.from == patchFromHost && w.fromPort > 0
- && patchPinMidiPort (w.fromPort) < patchMidiPorts)
- addSorted (ports, patchPinMidiPort (w.fromPort));
- return ports;
- }
- std::vector<int> vfxHostPorts (const PatcherDoc& doc)
- {
- std::vector<int> ports;
- for (const auto& w : doc.wires)
- if (w.kind == PatchWire::Kind::midi && w.enabled && w.to == patchToHost && w.toPort >= 0 && w.toPort < patchMidiPorts && w.from >= 0
- && w.from < (int) doc.nodes.size() && doc.nodes[(std::size_t) w.from].generator && vfx::kindOf (doc.nodes[(std::size_t) w.from].channel))
- addSorted (ports, w.toPort);
- return ports;
- }
- std::vector<MidiPortRoute> midiOutputsOf (const PatcherDoc& doc, int fromPin)
- {
- std::vector<MidiPortRoute> out;
- const auto count = (int) doc.nodes.size();
- std::vector<char> seen ((std::size_t) count, 0);
- std::vector<std::tuple<int, int, int>> todo { { patchFromHost, fromPin, -1 } };
- while (! todo.empty())
- {
- const auto [from, pin, channel] = todo.back();
- todo.pop_back();
- for (const auto& w : doc.wires)
- {
- if (w.kind != PatchWire::Kind::midi || ! w.enabled || w.from != from || w.fromPort != pin)
- continue;
- if (w.to == patchToHost)
- {
- const MidiPortRoute r { w.toPort, channel };
- if (w.toPort >= 0 && w.toPort < patchMidiPorts && std::find (out.begin(), out.end(), r) == out.end())
- out.push_back (r);
- }
- else if (w.to >= 0 && w.to < count && ! seen[(std::size_t) w.to])
- {
- const auto& node = doc.nodes[(std::size_t) w.to];
- if (node.generator && node.channel.instrument == InstrumentKind::midiOut)
- {
- seen[(std::size_t) w.to] = 1;
- todo.emplace_back (w.to, 0, midictl::parseMidiOut (node.channel.pluginState).channel);
- }
- }
- }
- }
- return out;
- }
- void deactivateUnusedMidiPins (PatcherDoc& doc, bool fromNode)
- {
- auto used = [&] (int pin) {
- return std::any_of (doc.wires.begin(), doc.wires.end(), [&] (const PatchWire& w) {
- return w.kind == PatchWire::Kind::midi && (fromNode ? w.from == patchFromHost && w.fromPort == pin : w.to == patchToHost && w.toPort == pin);
- });
- };
- if (fromNode)
- {
- std::erase_if (doc.fromMidiPorts, [&] (int p) { return ! used (patchMidiPortPin (p)); });
- doc.fromNotesHidden = ! used (0);
- }
- else
- std::erase_if (doc.toMidiPorts, [&] (int p) { return ! used (p); });
- }
- } // namespace lynx::patcher
|