Song.cpp 99 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539
  1. #include "core/Song.h"
  2. #include "core/TempoMap.h"
  3. #include "core/ModelParams.h"
  4. #include "core/FlSynths.h"
  5. #include "core/VoltageController.h"
  6. #include "core/MidiOut.h"
  7. #include "core/PatternBlocks.h"
  8. #include "core/MidiControls.h"
  9. #include "core/SessionIds.h"
  10. #include "core/FlCurve.h"
  11. #include "core/SynthParams.h"
  12. #include "core/SoundFont.h"
  13. #include <algorithm>
  14. #include <cstdio>
  15. #include <iterator>
  16. #include <cmath>
  17. #include <functional>
  18. #include <limits>
  19. #include <set>
  20. namespace lynx
  21. {
  22. void Pattern::sortNotes()
  23. {
  24. std::stable_sort (notes.begin(), notes.end(), [] (const Note& a, const Note& b) { return a.start < b.start; });
  25. if (! autoNotes.empty()) // (round 190ow)
  26. std::stable_sort (autoNotes.begin(), autoNotes.end(), [] (const Note& a, const Note& b) { return a.start < b.start; });
  27. }
  28. // round 190ow (DE-123): FL's steps on an automation clip row, the way toggleStep does them for a channel
  29. bool Pattern::hasAutoStep (int automation, int step) const noexcept
  30. {
  31. const auto from = (std::int64_t) step * ticksPerStep, to = from + ticksPerStep;
  32. for (const auto& n : autoNotes)
  33. if (n.channel == automation && n.start >= from && n.start < to && ! n.muted)
  34. return true;
  35. return false;
  36. }
  37. void Pattern::toggleAutoStep (int automation, int step)
  38. {
  39. if (step < 0 || automation < 0)
  40. return;
  41. const auto from = (std::int64_t) step * ticksPerStep, to = from + ticksPerStep;
  42. const auto on = hasAutoStep (automation, step);
  43. autoNotes.erase (std::remove_if (autoNotes.begin(), autoNotes.end(),
  44. [&] (const Note& n) { return n.channel == automation && n.start >= from && n.start < to; }),
  45. autoNotes.end());
  46. if (on)
  47. return;
  48. Note n;
  49. n.start = from;
  50. n.length = 0; // (FL's step of no length, as FL writes a step it sets on an automation clip channel: the clip plays once)
  51. n.channel = automation;
  52. autoNotes.push_back (n);
  53. sortNotes();
  54. }
  55. std::int64_t Pattern::effectiveLength (Meter meter) const noexcept
  56. {
  57. if (lengthTicks > 0)
  58. return lengthTicks;
  59. const std::int64_t bar = meter.bar();
  60. std::int64_t end = 0;
  61. for (auto& n : notes)
  62. end = std::max (end, n.start + std::max<std::int64_t> (n.length, 1));
  63. for (auto& n : autoNotes) // (round 190ow: FL's pattern length counts the automation clip channels' notes too)
  64. end = std::max (end, n.start + std::max<std::int64_t> (n.length, 1));
  65. return std::max<std::int64_t> (bar, (end + bar - 1) / bar * bar);
  66. }
  67. bool Pattern::hasStep (int channel, int step) const noexcept
  68. {
  69. const auto tick = (std::int64_t) step * ticksPerStep;
  70. return std::any_of (notes.begin(), notes.end(),
  71. [&] (const Note& n) { return n.channel == channel && n.start == tick && ! n.muted; });
  72. }
  73. void Pattern::toggleStep (int channel, int step, bool muteRemoved)
  74. {
  75. // FL's SetStep (FLEngine FUN_012d4140, REA round 169f): with "Mute removed steps" on, turning a step off mutes its
  76. // notes and turning it on unmutes them; with the option off, turning it off deletes them (muted ones too) and
  77. // turning it on adds a new note (a muted one there stays as it is).
  78. const auto tick = (std::int64_t) step * ticksPerStep;
  79. const auto onStep = [&] (const Note& n) { return n.channel == channel && n.start == tick; };
  80. if (hasStep (channel, step))
  81. {
  82. if (muteRemoved)
  83. for (auto& n : notes)
  84. n.muted = n.muted || onStep (n);
  85. else
  86. notes.erase (std::remove_if (notes.begin(), notes.end(), onStep), notes.end());
  87. return;
  88. }
  89. if (muteRemoved && std::any_of (notes.begin(), notes.end(), onStep))
  90. {
  91. for (auto& n : notes)
  92. if (onStep (n))
  93. n.muted = false;
  94. return;
  95. }
  96. Note n;
  97. n.start = tick;
  98. n.channel = channel;
  99. notes.push_back (n);
  100. sortNotes();
  101. }
  102. std::int64_t Song::songLength() const noexcept
  103. {
  104. const std::int64_t bar = barTicks();
  105. std::int64_t end = 0;
  106. for (const auto& c : playlist)
  107. end = std::max (end, c.end());
  108. // Pattern Blocks (round 170f) play with the clips
  109. const auto blocksEnd = patternblocks::end (*this);
  110. end = std::max (end, blocksEnd);
  111. // video clips (round 174d): a project with only its picture so far plays to the picture's end, not one bar
  112. std::int64_t videoEndTicks = 0;
  113. if (const auto videoSeconds = videotrack::videoEnd (videoTracks); videoSeconds > 0.0)
  114. videoEndTicks = (std::int64_t) std::ceil (videotrack::ticksForSeconds (*this, videoSeconds) - 1e-6);
  115. end = std::max (end, videoEndTicks);
  116. const bool arranged = ! playlist.empty() || blocksEnd > 0 || videoEndTicks > 0;
  117. // an empty Playlist (e.g. recording the first take in Song mode) loops the current pattern's length, not one bar
  118. if (! arranged && currentPattern >= 0 && currentPattern < (int) patterns.size())
  119. end = patterns[(std::size_t) currentPattern].effectiveLength (meter());
  120. // FL: Song mode loops at the exact end of the last clip (a clip ending at 3:05 loops at 3:05), not at the bar end
  121. if (arranged && end > 0)
  122. return end;
  123. return std::max<std::int64_t> (bar, (end + bar - 1) / bar * bar);
  124. }
  125. std::int64_t Song::performanceZoneEnd() const noexcept
  126. {
  127. if (! performanceMode)
  128. return 0;
  129. for (const auto& m : markers())
  130. if (m.action == Marker::songStart)
  131. return std::max<std::int64_t> (0, m.tick);
  132. return 0;
  133. }
  134. void followPatternLengths (const std::vector<std::int64_t>& before, Song& song)
  135. {
  136. if (before.size() != song.patterns.size())
  137. return; // patterns added, removed or moved: their clips are handled by that edit
  138. for (std::size_t i = 0; i < before.size(); ++i)
  139. {
  140. const auto now = song.patterns[i].effectiveLength (song.meter());
  141. if (now == before[i] || before[i] <= 0)
  142. continue;
  143. song.forEachClipList ([&] (std::vector<Clip>& clips) {
  144. for (auto& c : clips)
  145. if (c.kind == ClipKind::pattern && c.pattern == (int) i && c.offset == 0 && c.length == before[i])
  146. c.length = now;
  147. });
  148. }
  149. }
  150. namespace
  151. {
  152. template <typename Song_, typename Fn>
  153. void forEachHostedPlugin (Song_& song, Fn&& fn)
  154. {
  155. for (auto& c : song.channels)
  156. if (c.instrument == InstrumentKind::plugin && ! c.plugin.id.empty())
  157. fn (c.plugin);
  158. for (auto& track : song.mixer)
  159. for (auto& slot : track.effects)
  160. if (slot.kind == EffectKind::plugin && ! slot.plugin.id.empty())
  161. fn (slot.plugin);
  162. }
  163. } // namespace
  164. namespace
  165. {
  166. // a plugin an edit may have just added: no saved state yet (not loaded with a project, not a clone) and still docked
  167. bool looksJustAdded (const PluginRef& ref) { return ref.state.empty() && ! ref.detached; }
  168. } // namespace
  169. std::map<std::string, int> freshPluginCounts (const Song& song)
  170. {
  171. std::map<std::string, int> counts;
  172. forEachHostedPlugin (song, [&counts] (const PluginRef& ref) {
  173. if (looksJustAdded (ref))
  174. ++counts[ref.id];
  175. });
  176. return counts;
  177. }
  178. int detachNewPlugins (const std::map<std::string, int>& before, Song& song)
  179. {
  180. // only fresh plugins count on both sides, so a clone or a loaded plugin (with a state) that raises the number of
  181. // an id never gets an older fresh plugin of that id (one the user docked again) marked in its place
  182. auto added = freshPluginCounts (song);
  183. for (auto& [id, n] : added)
  184. if (const auto it = before.find (id); it != before.end())
  185. n -= it->second;
  186. // the newest of an id are the last ones: skip the fresh plugins that were already there
  187. std::map<std::string, int> seen;
  188. const auto now = freshPluginCounts (song);
  189. int marked = 0;
  190. forEachHostedPlugin (song, [&] (PluginRef& ref) {
  191. if (! looksJustAdded (ref))
  192. return;
  193. const auto index = seen[ref.id]++;
  194. const auto left = added[ref.id];
  195. if (left > 0 && index >= now.at (ref.id) - left)
  196. {
  197. ref.detached = true;
  198. ++marked;
  199. }
  200. });
  201. return marked;
  202. }
  203. int setAllPluginsDetached (Song& song, bool detached)
  204. {
  205. int changed = 0;
  206. forEachHostedPlugin (song, [&] (PluginRef& ref) {
  207. if (ref.detached != detached)
  208. {
  209. ref.detached = detached;
  210. ++changed;
  211. }
  212. });
  213. return changed;
  214. }
  215. std::vector<std::int64_t> patternLengths (const Song& song)
  216. {
  217. std::vector<std::int64_t> lengths;
  218. lengths.reserve (song.patterns.size());
  219. for (const auto& p : song.patterns)
  220. lengths.push_back (p.effectiveLength (song.meter()));
  221. return lengths;
  222. }
  223. void Song::removePattern (int index)
  224. {
  225. if (index < 0 || index >= (int) patterns.size())
  226. return;
  227. patterns.erase (patterns.begin() + index);
  228. forEachClipList ([index] (std::vector<Clip>& clips) {
  229. clips.erase (std::remove_if (clips.begin(), clips.end(),
  230. [index] (const Clip& c) { return c.kind == ClipKind::pattern && c.pattern == index; }),
  231. clips.end());
  232. for (auto& c : clips)
  233. if (c.kind == ClipKind::pattern && c.pattern > index)
  234. --c.pattern;
  235. });
  236. patternblocks::removePattern (*this, index); // (round 170f)
  237. // Loop Starter channels follow their pattern (round 168b)
  238. for (auto& c : channels)
  239. if (c.loopStarterPattern == index)
  240. c.loopStarterPattern = -1;
  241. else if (c.loopStarterPattern > index)
  242. --c.loopStarterPattern;
  243. if (currentPattern > index)
  244. --currentPattern;
  245. keepOnePattern(); // (the last one: an empty "Pattern 1" stays, as in FL)
  246. }
  247. bool Song::keepOnePattern()
  248. {
  249. bool changed = false;
  250. if (patterns.empty())
  251. {
  252. patterns.emplace_back().name = "Pattern 1";
  253. changed = true;
  254. }
  255. const auto clamped = std::clamp (currentPattern, 0, (int) patterns.size() - 1);
  256. changed = changed || clamped != currentPattern;
  257. currentPattern = clamped;
  258. return changed;
  259. }
  260. const Pattern& Song::activePattern() const noexcept
  261. {
  262. static const Pattern none;
  263. if (patterns.empty())
  264. return none;
  265. return patterns[(std::size_t) std::clamp (currentPattern, 0, (int) patterns.size() - 1)];
  266. }
  267. Pattern& Song::activePattern()
  268. {
  269. keepOnePattern();
  270. return patterns[(std::size_t) currentPattern];
  271. }
  272. std::vector<MixerTrack> Song::defaultMixer (int inserts)
  273. {
  274. std::vector<MixerTrack> mixer ((std::size_t) std::clamp (inserts + 1, 1, maxMixerTracks));
  275. mixer[0].name = "Master";
  276. for (std::size_t i = 1; i < mixer.size(); ++i)
  277. mixer[i].name = "Insert " + std::to_string (i);
  278. return mixer;
  279. }
  280. bool Song::insertInUse (int t) const
  281. {
  282. // free = nothing uses it: no channel plays into it, no insert sends to it, no effects, input or Playlist track
  283. // link, the default name and routing. Round 157b: an FL project's effect buses (a vocal reverb/delay insert fed only
  284. // by sends) have no channel, and a sample added to the rack was routed into one (her beat through the vocal
  285. // H-Delay, reverb and Decapitator: "it sounds terrible").
  286. if (t <= 0 || t >= (int) mixer.size())
  287. return t == 0 && ! mixer.empty();
  288. auto used = [this] (int t) {
  289. const auto& m = mixer[(std::size_t) t];
  290. if (! m.effects.empty() || ! m.toMaster || m.inputChannel >= 0 || ! m.sends.empty()
  291. || (! m.name.empty() && m.name != "Insert " + std::to_string (t)))
  292. return true;
  293. if (std::any_of (channels.begin(), channels.end(), [t] (const ChannelDef& c) { return c.mixerTrack == t; }))
  294. return true;
  295. if (std::any_of (mixer.begin(), mixer.end(), [t] (const MixerTrack& o) {
  296. return std::any_of (o.sends.begin(), o.sends.end(), [t] (const MixerSend& send) { return send.target == t; });
  297. }))
  298. return true;
  299. return std::any_of (playlistTracks.begin(), playlistTracks.end(), [t] (const PlaylistTrack& p) { return p.mixerTrack == t; });
  300. };
  301. if (used (t))
  302. return true;
  303. // round 163 (hiding unused inserts): a fader, pan, mute or colour moved by hand, or automation on it, counts too
  304. const auto& m = mixer[(std::size_t) t];
  305. if (m.volume != unityFader || m.pan != 0.0f || m.muted || m.solo || m.colour != 0 || m.stereo != 0.0f || m.eq.hasBoostOrCut()
  306. || m.outputChannel != outputDefault)
  307. return true;
  308. if (std::any_of (mixer.begin(), mixer.end(), [t] (const MixerTrack& o) {
  309. return std::any_of (o.effects.begin(), o.effects.end(), [t] (const EffectSlot& e) { return e.sidechain == t || e.sidechain2 == t || e.sendTracks[0] == t || e.sendTracks[1] == t; });
  310. }))
  311. return true;
  312. return std::any_of (automations.begin(), automations.end(), [t] (const Automation& a) {
  313. const auto onTrack = a.target.kind == AutomationTargetKind::mixerVolume || a.target.kind == AutomationTargetKind::mixerPan
  314. || a.target.kind == AutomationTargetKind::effectParam || a.target.kind == AutomationTargetKind::effectMix
  315. || a.target.kind == AutomationTargetKind::mixerSend;
  316. return a.source.track == t || (onTrack && a.target.index == t);
  317. });
  318. }
  319. int Song::nextFreeInsert() const
  320. {
  321. // Online Sessions (round 168a): a guest's new channels take the inserts reserved for him first, and nobody's new
  322. // channel takes an insert reserved for another participant
  323. if (const auto* me = session.self(); me != nullptr && me->insertCount > 0)
  324. for (int t = me->insertFirst; t < me->insertFirst + me->insertCount && t < (int) mixer.size(); ++t)
  325. if (t > 0 && ! insertInUse (t))
  326. return t;
  327. for (int t = 1; t < (int) mixer.size(); ++t)
  328. if (! insertInUse (t) && ! session.reservedForOther (true, t))
  329. return t;
  330. return 0; // every insert is in use: Master (FL's default for a new channel)
  331. }
  332. int Song::claimFreeInsert()
  333. {
  334. // a guest's reserved range may lie past the mixer's end: it grows to reach it
  335. if (const auto* me = session.self(); me != nullptr && me->insertCount > 0 && ! mixer.empty())
  336. for (int t = std::max (1, me->insertFirst); t < me->insertFirst + me->insertCount && t < maxMixerTracks; ++t)
  337. {
  338. while ((int) mixer.size() <= t)
  339. mixer.emplace_back().name = "Insert " + std::to_string (mixer.size());
  340. if (! insertInUse (t))
  341. return t;
  342. }
  343. if (const auto t = nextFreeInsert(); t > 0)
  344. return t;
  345. if (mixer.empty() || (int) mixer.size() >= maxMixerTracks)
  346. return 0;
  347. // a new insert past the end, skipping other participants' reserved ones (they are added as plain inserts)
  348. while ((int) mixer.size() < maxMixerTracks)
  349. {
  350. const auto name = "Insert " + std::to_string (mixer.size());
  351. mixer.emplace_back().name = name;
  352. if (! session.reservedForOther (true, (int) mixer.size() - 1))
  353. return (int) mixer.size() - 1;
  354. }
  355. return 0;
  356. }
  357. void Song::removeChannel (int index)
  358. {
  359. if (index < 0 || index >= (int) channels.size())
  360. return;
  361. channels.erase (channels.begin() + index);
  362. for (auto& p : patterns)
  363. {
  364. p.notes.erase (std::remove_if (p.notes.begin(), p.notes.end(), [index] (const Note& n) { return n.channel == index; }),
  365. p.notes.end());
  366. for (auto& n : p.notes)
  367. if (n.channel > index)
  368. --n.channel;
  369. // the Channel Rack's loop points (round 165f-rack)
  370. auto& loops = p.channelLoops;
  371. loops.erase (std::remove_if (loops.begin(), loops.end(), [index] (const ChannelLoop& l) { return l.channel == index; }), loops.end());
  372. for (auto& l : loops)
  373. if (l.channel > index)
  374. --l.channel;
  375. }
  376. forEachClipList ([index] (std::vector<Clip>& clips) {
  377. clips.erase (std::remove_if (clips.begin(), clips.end(),
  378. [index] (const Clip& c) { return c.kind == ClipKind::audio && c.channel == index; }),
  379. clips.end());
  380. for (auto& c : clips)
  381. if (c.kind == ClipKind::audio && c.channel > index)
  382. --c.channel;
  383. });
  384. forEachTarget ([index] (AutomationTarget& t) {
  385. const auto onChannel = t.kind == AutomationTargetKind::channelVolume || t.kind == AutomationTargetKind::channelPan
  386. || t.kind == AutomationTargetKind::channelParam || t.kind == AutomationTargetKind::channelAdjust;
  387. if (onChannel && t.index == index)
  388. t.kind = AutomationTargetKind::none;
  389. else if (onChannel && t.index > index)
  390. --t.index;
  391. });
  392. for (auto& t : playlistTracks) // instrument tracks (REA round 146a)
  393. if (t.channel == index)
  394. {
  395. t.channel = -1;
  396. if (t.mode == PlaylistTrackMode::instrument)
  397. t.mode = PlaylistTrackMode::unassigned, t.mixerTrack = -1;
  398. }
  399. else if (t.channel > index)
  400. --t.channel;
  401. for (auto& automation : automations) // live source on a controller channel
  402. if (automation.source.channel == index)
  403. automation.source.channel = -1, automation.target.kind = AutomationTargetKind::none;
  404. else if (automation.source.channel > index)
  405. --automation.source.channel;
  406. for (auto& automation : automations) // round 190oo (PAT-7): the automation clip rows keep their place in the rack
  407. if (automation.rackSlot > index)
  408. --automation.rackSlot;
  409. for (auto& c : channels) // Layer children (round 164)
  410. {
  411. auto& kids = c.layer.children;
  412. kids.erase (std::remove (kids.begin(), kids.end(), index), kids.end());
  413. for (auto& k : kids)
  414. if (k > index)
  415. --k;
  416. }
  417. removeDeadMidiLinks();
  418. }
  419. void Song::removeDeadMidiLinks()
  420. {
  421. midiLinks.erase (std::remove_if (midiLinks.begin(), midiLinks.end(),
  422. [] (const MidiLink& l) { return l.target.kind == AutomationTargetKind::none; }),
  423. midiLinks.end());
  424. initialValues.erase (std::remove_if (initialValues.begin(), initialValues.end(),
  425. [] (const InitialValue& v) { return v.target.kind == AutomationTargetKind::none; }),
  426. initialValues.end());
  427. remoteMappings.erase (std::remove_if (remoteMappings.begin(), remoteMappings.end(), // (round 190ef)
  428. [] (const RemoteMapping& m) {
  429. return m.action == RemoteAction::parameter && m.target.kind == AutomationTargetKind::none;
  430. }),
  431. remoteMappings.end());
  432. }
  433. std::vector<MidiLink> linksWithGlobal (const std::vector<MidiLink>& project, const std::vector<MidiLink>& global)
  434. {
  435. auto out = project;
  436. for (const auto& g : global)
  437. {
  438. const auto overridden = std::any_of (project.begin(), project.end(), [&] (const MidiLink& p) {
  439. return p.target == g.target || (p.cc == g.cc && p.port == g.port && (p.channel < 0 || g.channel < 0 || p.channel == g.channel));
  440. });
  441. if (! overridden && g.target.kind != AutomationTargetKind::none)
  442. out.push_back (g);
  443. }
  444. return out;
  445. }
  446. bool linkOmniAvailable (AutomationTargetKind kind) noexcept
  447. {
  448. return kind == AutomationTargetKind::channelVolume || kind == AutomationTargetKind::channelPan || kind == AutomationTargetKind::channelParam
  449. || kind == AutomationTargetKind::channelAdjust || kind == AutomationTargetKind::mixerVolume || kind == AutomationTargetKind::mixerPan || kind == AutomationTargetKind::effectParam
  450. || kind == AutomationTargetKind::effectMix;
  451. }
  452. AutomationTarget linkOmniTarget (const MidiLink& link, int selectedChannel, int selectedMixerTrack) noexcept
  453. {
  454. auto t = link.target;
  455. if (! link.omni || ! linkOmniAvailable (t.kind))
  456. return t;
  457. const auto channelControl = t.kind == AutomationTargetKind::channelVolume || t.kind == AutomationTargetKind::channelPan
  458. || t.kind == AutomationTargetKind::channelParam || t.kind == AutomationTargetKind::channelAdjust;
  459. const auto index = channelControl ? selectedChannel : selectedMixerTrack;
  460. if (index >= 0)
  461. t.index = index;
  462. return t;
  463. }
  464. int countLinkConflicts (const std::vector<MidiLink>& links, const MidiLink& link)
  465. {
  466. if (link.cc < 0)
  467. return 0;
  468. return (int) std::count_if (links.begin(), links.end(), [&] (const MidiLink& l) { return ! (l.target == link.target) && sameController (l, link); });
  469. }
  470. int setTargetLinks (std::vector<MidiLink>& links, const AutomationTarget& target, std::vector<MidiLink> edited, bool removeConflicts)
  471. {
  472. edited.erase (std::remove_if (edited.begin(), edited.end(), [] (const MidiLink& l) { return l.cc < 0; }), edited.end());
  473. for (auto& l : edited)
  474. l.target = target;
  475. int removed = 0;
  476. if (removeConflicts)
  477. {
  478. const auto before = links.size();
  479. links.erase (std::remove_if (links.begin(), links.end(),
  480. [&] (const MidiLink& l) {
  481. return ! (l.target == target)
  482. && std::any_of (edited.begin(), edited.end(), [&] (const MidiLink& e) { return sameController (l, e); });
  483. }),
  484. links.end());
  485. removed = (int) (before - links.size());
  486. }
  487. // the control's links keep the place of its first one
  488. const auto first = std::find_if (links.begin(), links.end(), [&] (const MidiLink& l) { return l.target == target; });
  489. const auto at = (std::size_t) (first - links.begin());
  490. std::vector<MidiLink> out;
  491. for (std::size_t i = 0; i < links.size(); ++i)
  492. {
  493. if (i == at)
  494. out.insert (out.end(), edited.begin(), edited.end());
  495. if (! (links[i].target == target))
  496. out.push_back (links[i]);
  497. }
  498. if (at >= links.size())
  499. out.insert (out.end(), edited.begin(), edited.end());
  500. links = std::move (out);
  501. return removed;
  502. }
  503. int Song::findInitialValue (const AutomationTarget& target) const noexcept
  504. {
  505. for (int i = 0; i < (int) initialValues.size(); ++i)
  506. if (initialValues[(std::size_t) i].target == target)
  507. return i;
  508. return -1;
  509. }
  510. void Song::setInitialValue (const AutomationTarget& target, float value)
  511. {
  512. if (target.kind == AutomationTargetKind::none)
  513. return;
  514. value = std::clamp (value, 0.0f, 1.0f);
  515. if (const auto i = findInitialValue (target); i >= 0)
  516. initialValues[(std::size_t) i].value = value;
  517. else
  518. initialValues.push_back ({ target, value });
  519. }
  520. void Song::removeInitialValue (const AutomationTarget& target)
  521. {
  522. initialValues.erase (std::remove_if (initialValues.begin(), initialValues.end(),
  523. [&] (const InitialValue& v) { return v.target == target; }),
  524. initialValues.end());
  525. }
  526. void Song::applyInitialValues (const std::function<void (const AutomationTarget&, float)>& plugin)
  527. {
  528. for (const auto& v : initialValues)
  529. if (! setTargetValue (v.target, v.value) && plugin)
  530. plugin (v.target, v.value);
  531. }
  532. int fruitySendTarget (const EffectSlot& slot) noexcept
  533. {
  534. if (slot.kind == EffectKind::patcher) // a Patcher's first extra output (REA_rodada141)
  535. return ! slot.patcher.outputTracks.empty() && slot.patcher.outputTracks.front() > 0 ? slot.patcher.outputTracks.front() : -1;
  536. if (slot.kind == EffectKind::flTransporter) // FL's Transporter: its loops' send (parameter 24, round 167f)
  537. {
  538. const auto t = (int) std::lround (std::clamp ((double) slot.params[24], 0.0, 1.0) * (maxMixerTracks - 1));
  539. return t > 0 ? t : -1;
  540. }
  541. if (slot.kind != EffectKind::fruitySend)
  542. return -1;
  543. const auto track = (int) std::lround (std::clamp ((double) slot.params[3], 0.0, 1.0) * (maxMixerTracks - 1));
  544. return track > 0 ? track : -1;
  545. }
  546. int slotSendTarget (const EffectSlot& slot, int output) noexcept
  547. {
  548. if (slot.kind == EffectKind::transmitter || (slot.kind == EffectKind::equo && output == 0)) // (EQUO: its band sends, round 173d3)
  549. return output >= 0 && output < (int) slot.sendTracks.size() && slot.sendTracks[(std::size_t) output] > 0 ? slot.sendTracks[(std::size_t) output] : -1;
  550. return output == 0 ? fruitySendTarget (slot) : -1;
  551. }
  552. std::vector<SlotSendTap> fruitySendsOf (const Song& song, int track)
  553. {
  554. std::vector<SlotSendTap> out;
  555. const auto n = (int) song.mixer.size();
  556. if (track <= 0 || track >= n)
  557. return out;
  558. const auto& slots = song.mixer[(std::size_t) track].effects;
  559. for (int s = 0; s < (int) slots.size() && s < maxEffectSlots; ++s)
  560. {
  561. const auto& slot = slots[(std::size_t) s];
  562. if (slot.kind == EffectKind::plugin)
  563. {
  564. // a hosted effect's output pairs that its Connections send elsewhere (round 189j), after its processing
  565. const auto c = slotConnections (song, track, slot);
  566. for (int o = 0; o < maxPluginConnections && c.routed; ++o)
  567. if (const auto target = c.outputs[(std::size_t) o]; target >= 0 && target < n && target != track)
  568. out.push_back ({ s, target, o, true });
  569. continue;
  570. }
  571. for (int o = 0; o < maxSlotSends; ++o)
  572. if (const auto target = slotSendTarget (slot, o); target > 0 && target < n && target != track)
  573. out.push_back ({ s, target, o, slot.kind == EffectKind::transmitter || slot.kind == EffectKind::equo });
  574. }
  575. return out;
  576. }
  577. std::vector<int> insertInputList (const Song& song, int track)
  578. {
  579. std::vector<int> list { track };
  580. for (int from = 1; from < (int) song.mixer.size(); ++from)
  581. if (from != track && song.routes (from, track))
  582. list.push_back (from);
  583. return list;
  584. }
  585. std::vector<int> insertOutputList (const Song& song, int track)
  586. {
  587. std::vector<int> list { track };
  588. if (track <= 0 || track >= (int) song.mixer.size())
  589. return list;
  590. for (int to = 0; to < (int) song.mixer.size(); ++to)
  591. if (to != track && song.routes (track, to))
  592. list.push_back (to);
  593. return list;
  594. }
  595. SlotConnections slotConnections (const Song& song, int track, const EffectSlot& slot)
  596. {
  597. SlotConnections c;
  598. const auto n = (int) song.mixer.size();
  599. const auto& ref = slot.plugin;
  600. if (slot.kind != EffectKind::plugin || track <= 0 || track >= n || (ref.inputs.empty() && ref.outputs.empty()))
  601. return c;
  602. c.routed = true;
  603. // an inactive input / output: silent, unless "Process inactive inputs and outputs" (on by default) [EXEC]
  604. auto on = [&ref] (const PluginOutputRoute& r) { return r.isActive (true) || ref.processInactive; };
  605. const auto at = [] (const std::vector<PluginOutputRoute>& list, std::size_t k) { return k < list.size() ? list[k] : PluginOutputRoute {}; };
  606. // index k = entry k of the inputs list; 0 or past the list = the slot's own input [EXEC e01 e02 e10]
  607. std::vector<int> sources;
  608. auto source = [&] (int k) {
  609. if (k <= 0)
  610. return -1;
  611. if (sources.empty())
  612. sources = insertInputList (song, track);
  613. return k < (int) sources.size() ? sources[(std::size_t) k] : -1;
  614. };
  615. const auto in1 = at (ref.inputs, 0), in2 = at (ref.inputs, 1);
  616. c.mainSource = on (in1) ? source (in1.offset) : -2;
  617. // input 2: the slot's side input source (LYNX's SC picker, or its index, which sets it: core/MixerOps.h), else
  618. // its index; without either the slot's own input [EXEC e00: FL feeds an input at index 0 the insert's audio]
  619. if (! on (in2))
  620. c.sideSource = -2;
  621. else if (slot.sidechain > 0 && slot.sidechain != track && slot.sidechain < n)
  622. c.sideSource = slot.sidechain;
  623. else
  624. c.sideSource = source (in2.offset);
  625. // outputs: index 0 = into the insert; k = entry k of the outputs list, past its end the last one [EXEC e05 e07 e11
  626. // e12 e13 e18 e19]; (a negative index, which FL's wheel never gives, went to the Master past the fader, e17 e23)
  627. std::vector<int> targets;
  628. for (int o = 0; o < maxPluginConnections; ++o)
  629. {
  630. const auto r = ref.outputRoute (o);
  631. if (! on (r))
  632. c.outputs[(std::size_t) o] = -2;
  633. else if (r.offset < 0)
  634. c.outputs[(std::size_t) o] = 0;
  635. else if (r.offset > 0)
  636. {
  637. if (targets.empty())
  638. targets = insertOutputList (song, track);
  639. if (targets.size() > 1)
  640. c.outputs[(std::size_t) o] = targets[(std::size_t) std::min (r.offset, (int) targets.size() - 1)];
  641. }
  642. }
  643. return c;
  644. }
  645. bool Song::routes (int from, int to) const noexcept
  646. {
  647. if (from <= 0 || from >= (int) mixer.size())
  648. return false;
  649. const auto& t = mixer[(std::size_t) from];
  650. if (to == 0)
  651. return t.toMaster;
  652. return std::any_of (t.sends.begin(), t.sends.end(), [to] (const MixerSend& s) { return s.target == to; });
  653. }
  654. float Song::routeLevel (int from, int to) const noexcept
  655. {
  656. if (! routes (from, to))
  657. return 0.0f;
  658. const auto& t = mixer[(std::size_t) from];
  659. if (to == 0)
  660. return t.masterLevel;
  661. for (const auto& s : t.sends)
  662. if (s.target == to)
  663. return s.level;
  664. return 0.0f;
  665. }
  666. void Song::setRouteLevel (int from, int to, float level)
  667. {
  668. if (! routes (from, to))
  669. return;
  670. const auto v = std::clamp (level, 0.0f, maxFaderGain);
  671. auto& t = mixer[(std::size_t) from];
  672. if (to == 0)
  673. t.masterLevel = v;
  674. else
  675. for (auto& s : t.sends)
  676. if (s.target == to)
  677. s.level = v;
  678. }
  679. bool Song::sendPre (int from, int to) const noexcept
  680. {
  681. if (to <= 0 || ! routes (from, to))
  682. return false;
  683. for (const auto& s : mixer[(std::size_t) from].sends)
  684. if (s.target == to)
  685. return s.pre;
  686. return false;
  687. }
  688. void Song::setSendPre (int from, int to, bool pre)
  689. {
  690. if (to <= 0 || ! routes (from, to))
  691. return;
  692. for (auto& s : mixer[(std::size_t) from].sends)
  693. if (s.target == to)
  694. s.pre = pre;
  695. }
  696. bool Song::canRoute (int from, int to) const
  697. {
  698. const auto n = (int) mixer.size();
  699. if (from <= 0 || from >= n || to < 0 || to >= n || from == to)
  700. return false;
  701. if (to == 0)
  702. return true;
  703. // cycle if `from` is already reachable from `to`
  704. std::vector<int> stack { to };
  705. std::vector<bool> seen ((std::size_t) n, false);
  706. while (! stack.empty())
  707. {
  708. const auto t = stack.back();
  709. stack.pop_back();
  710. if (t == from)
  711. return false;
  712. if (seen[(std::size_t) t])
  713. continue;
  714. seen[(std::size_t) t] = true;
  715. for (const auto& s : mixer[(std::size_t) t].sends)
  716. if (s.target > 0 && s.target < n)
  717. stack.push_back (s.target);
  718. for (const auto& fx : mixer[(std::size_t) t].effects)
  719. for (int o = 0; o < maxSlotSends; ++o)
  720. if (const auto target = slotSendTarget (fx, o); target > 0 && target < n)
  721. stack.push_back (target);
  722. }
  723. return true;
  724. }
  725. void Song::setRoute (int from, int to, bool enabled, float level)
  726. {
  727. if (from <= 0 || from >= (int) mixer.size() || to < 0 || to >= (int) mixer.size())
  728. return;
  729. auto& t = mixer[(std::size_t) from];
  730. if (to == 0)
  731. {
  732. t.toMaster = enabled;
  733. return;
  734. }
  735. auto it = std::find_if (t.sends.begin(), t.sends.end(), [to] (const MixerSend& s) { return s.target == to; });
  736. if (! enabled)
  737. {
  738. if (it != t.sends.end())
  739. t.sends.erase (it);
  740. return;
  741. }
  742. if (it != t.sends.end())
  743. it->level = std::clamp (level, 0.0f, maxFaderGain);
  744. else if (canRoute (from, to))
  745. t.sends.push_back ({ to, std::clamp (level, 0.0f, maxFaderGain) });
  746. }
  747. std::vector<int> Song::mixerOrder() const
  748. {
  749. const auto n = (int) mixer.size();
  750. std::vector<int> incoming ((std::size_t) std::max (0, n), 0);
  751. // edges: sends and sidechains (the sidechain source must be processed before whoever listens to it)
  752. std::vector<std::vector<int>> next ((std::size_t) std::max (0, n));
  753. for (int t = 1; t < n; ++t)
  754. {
  755. for (const auto& s : mixer[(std::size_t) t].sends)
  756. if (s.target > 0 && s.target < n)
  757. next[(std::size_t) t].push_back (s.target);
  758. for (const auto& fx : mixer[(std::size_t) t].effects) // Fruity Send / Transmitter slots: the destination comes after
  759. for (int o = 0; o < maxSlotSends; ++o)
  760. if (const auto target = slotSendTarget (fx, o); target > 0 && target < n && target != t)
  761. next[(std::size_t) t].push_back (target);
  762. for (const auto& fx : mixer[(std::size_t) t].effects)
  763. for (const auto source : { fx.sidechain, fx.sidechain2 })
  764. if (source > 0 && source < n && source != t)
  765. next[(std::size_t) source].push_back (t);
  766. }
  767. for (int t = 1; t < n; ++t)
  768. for (const auto target : next[(std::size_t) t])
  769. ++incoming[(std::size_t) target];
  770. // Kahn: start with the tracks nothing feeds (in numeric order)
  771. std::vector<int> order, ready;
  772. for (int t = n - 1; t >= 1; --t)
  773. if (incoming[(std::size_t) t] == 0)
  774. ready.push_back (t);
  775. while (! ready.empty())
  776. {
  777. const auto t = ready.back();
  778. ready.pop_back();
  779. order.push_back (t);
  780. for (const auto target : next[(std::size_t) t])
  781. if (--incoming[(std::size_t) target] == 0)
  782. {
  783. // keep numeric order among those that become ready together
  784. auto pos = std::upper_bound (ready.begin(), ready.end(), target, std::greater<int>());
  785. ready.insert (pos, target);
  786. }
  787. }
  788. // cycle (corrupt file): the leftovers go at the end, without the sends that close the cycle
  789. for (int t = 1; t < n; ++t)
  790. if (std::find (order.begin(), order.end(), t) == order.end())
  791. order.push_back (t);
  792. return order;
  793. }
  794. std::vector<bool> Song::soloAudible() const
  795. {
  796. const auto n = mixer.size();
  797. std::vector<bool> audible (n, true);
  798. std::vector<int> soloed;
  799. for (std::size_t t = 1; t < n; ++t)
  800. if (mixer[t].solo)
  801. soloed.push_back ((int) t);
  802. if (soloed.empty())
  803. return audible;
  804. std::fill (audible.begin(), audible.end(), false);
  805. if (n > 0)
  806. audible[0] = true;
  807. // downstream: the signal path from the soloed tracks to Master; a track with its state locked (FL's Shift+click
  808. // on the mute switch, round 190kn) is not silenced by a solo elsewhere, so its path stays too
  809. std::vector<int> stack = soloed;
  810. for (std::size_t t = 1; t < n; ++t)
  811. if (mixer[t].lockState && ! mixer[t].solo)
  812. stack.push_back ((int) t);
  813. while (! stack.empty())
  814. {
  815. const auto t = stack.back();
  816. stack.pop_back();
  817. if (audible[(std::size_t) t])
  818. continue;
  819. audible[(std::size_t) t] = true;
  820. for (const auto& s : mixer[(std::size_t) t].sends)
  821. if (s.target > 0 && s.target < (int) n)
  822. stack.push_back (s.target);
  823. for (const auto& fx : mixer[(std::size_t) t].effects)
  824. for (int o = 0; o < maxSlotSends; ++o)
  825. if (const auto target = slotSendTarget (fx, o); target > 0 && target < (int) n)
  826. stack.push_back (target);
  827. }
  828. // upstream: whoever feeds the soloed tracks (those soloed with their sources: FL's plain solo leaves them out)
  829. std::vector<bool> feeds (n, false);
  830. stack.clear();
  831. for (auto t : soloed)
  832. if (mixer[(std::size_t) t].soloSources)
  833. stack.push_back (t);
  834. while (! stack.empty())
  835. {
  836. const auto t = stack.back();
  837. stack.pop_back();
  838. for (std::size_t src = 1; src < n; ++src)
  839. if (! feeds[src]
  840. && (routes ((int) src, t)
  841. || std::any_of (mixer[src].effects.begin(), mixer[src].effects.end(),
  842. [t] (const EffectSlot& fx) { return slotSendTarget (fx, 0) == t || slotSendTarget (fx, 1) == t; })))
  843. {
  844. feeds[src] = true;
  845. audible[src] = true;
  846. stack.push_back ((int) src);
  847. }
  848. }
  849. return audible;
  850. }
  851. void Song::uniqueInstances()
  852. {
  853. std::set<std::uint64_t> seen;
  854. const auto unique = [&seen] (InstanceTag& tag) {
  855. if (! seen.insert (tag.id).second)
  856. {
  857. tag.renew();
  858. seen.insert (tag.id);
  859. }
  860. };
  861. for (auto& c : channels)
  862. unique (c.instance);
  863. seen.clear();
  864. for (auto& t : mixer)
  865. for (auto& slot : t.effects)
  866. unique (slot.instance);
  867. }
  868. void Song::swapEffectSlots (int track, int a, int b)
  869. {
  870. if (track < 0 || track >= (int) mixer.size())
  871. return;
  872. auto& fx = mixer[(std::size_t) track].effects;
  873. if (a < 0 || b < 0 || a >= (int) fx.size() || b >= (int) fx.size())
  874. return;
  875. std::swap (fx[(std::size_t) a], fx[(std::size_t) b]);
  876. for (auto& automation : automations)
  877. if (automation.source.track == track)
  878. automation.source.slot = automation.source.slot == a ? b : automation.source.slot == b ? a : automation.source.slot;
  879. forEachTarget ([track, a, b] (AutomationTarget& t) {
  880. if ((t.kind == AutomationTargetKind::effectParam || t.kind == AutomationTargetKind::effectMix) && t.index == track)
  881. t.slot = t.slot == a ? b : t.slot == b ? a : t.slot;
  882. });
  883. }
  884. void Song::removeEffectSlot (int track, int slot)
  885. {
  886. if (track < 0 || track >= (int) mixer.size() || slot < 0 || slot >= (int) mixer[(std::size_t) track].effects.size())
  887. return;
  888. auto& fx = mixer[(std::size_t) track].effects;
  889. fx.erase (fx.begin() + slot);
  890. for (auto& automation : automations)
  891. if (automation.source.track == track)
  892. {
  893. if (automation.source.slot == slot)
  894. automation.source.track = -1, automation.target.kind = AutomationTargetKind::none; // the source is gone
  895. else if (automation.source.slot > slot)
  896. --automation.source.slot;
  897. }
  898. forEachTarget ([track, slot] (AutomationTarget& t) {
  899. if ((t.kind == AutomationTargetKind::effectParam || t.kind == AutomationTargetKind::effectMix) && t.index == track)
  900. {
  901. if (t.slot == slot)
  902. t.kind = AutomationTargetKind::none;
  903. else if (t.slot > slot)
  904. --t.slot;
  905. }
  906. });
  907. removeDeadMidiLinks();
  908. }
  909. void Song::removeAutomation (int index)
  910. {
  911. if (index < 0 || index >= (int) automations.size())
  912. return;
  913. automations.erase (automations.begin() + index);
  914. for (auto& p : patterns) // round 190ow (DE-123): its steps / notes go, the later automations' follow
  915. if (! p.autoNotes.empty())
  916. {
  917. p.autoNotes.erase (std::remove_if (p.autoNotes.begin(), p.autoNotes.end(), [index] (const Note& n) { return n.channel == index; }),
  918. p.autoNotes.end());
  919. for (auto& n : p.autoNotes)
  920. if (n.channel > index)
  921. --n.channel;
  922. }
  923. for (auto& track : playlistTracks) // round 177b: lanes follow the renumbering; the removed one's lane goes
  924. {
  925. track.lanes.erase (std::remove_if (track.lanes.begin(), track.lanes.end(), [index] (const AutomationLane& l) { return l.automation == index; }),
  926. track.lanes.end());
  927. for (auto& l : track.lanes)
  928. if (l.automation > index)
  929. --l.automation;
  930. for (auto& v : track.versions) // round 190pe: the lanes kept by a track's versions too
  931. {
  932. v.lanes.erase (std::remove_if (v.lanes.begin(), v.lanes.end(), [index] (const AutomationLane& l) { return l.automation == index; }),
  933. v.lanes.end());
  934. for (auto& l : v.lanes)
  935. if (l.automation > index)
  936. --l.automation;
  937. }
  938. }
  939. forEachClipList ([index] (std::vector<Clip>& clips) {
  940. clips.erase (std::remove_if (clips.begin(), clips.end(),
  941. [index] (const Clip& c) { return c.kind == ClipKind::automation && c.automation == index; }),
  942. clips.end());
  943. for (auto& c : clips)
  944. if (c.kind == ClipKind::automation && c.automation > index)
  945. --c.automation;
  946. });
  947. }
  948. std::vector<Marker>& Song::markers()
  949. {
  950. if (arrangements.empty())
  951. arrangements.push_back ({ "Arrangement 1", {}, 0, 0, {} });
  952. return arrangements[(std::size_t) std::clamp (currentArrangement, 0, (int) arrangements.size() - 1)].markers;
  953. }
  954. const std::vector<Marker>& Song::markers() const
  955. {
  956. static const std::vector<Marker> none;
  957. return arrangements.empty() ? none : arrangements[(std::size_t) std::clamp (currentArrangement, 0, (int) arrangements.size() - 1)].markers;
  958. }
  959. std::vector<SongSection>& Song::sections()
  960. {
  961. if (arrangements.empty())
  962. arrangements.push_back ({ "Arrangement 1", {}, 0, 0, {} });
  963. return arrangements[(std::size_t) std::clamp (currentArrangement, 0, (int) arrangements.size() - 1)].sections;
  964. }
  965. const std::vector<SongSection>& Song::sections() const
  966. {
  967. static const std::vector<SongSection> none;
  968. return arrangements.empty() ? none : arrangements[(std::size_t) std::clamp (currentArrangement, 0, (int) arrangements.size() - 1)].sections;
  969. }
  970. std::vector<SongChord>& Song::chords()
  971. {
  972. if (arrangements.empty())
  973. arrangements.push_back ({ "Arrangement 1", {}, 0, 0, {} });
  974. return arrangements[(std::size_t) std::clamp (currentArrangement, 0, (int) arrangements.size() - 1)].chords;
  975. }
  976. const std::vector<SongChord>& Song::chords() const
  977. {
  978. static const std::vector<SongChord> none;
  979. return arrangements.empty() ? none : arrangements[(std::size_t) std::clamp (currentArrangement, 0, (int) arrangements.size() - 1)].chords;
  980. }
  981. void Song::addMarker (Marker marker)
  982. {
  983. auto& list = markers();
  984. const auto at = std::upper_bound (list.begin(), list.end(), marker.tick, [] (std::int64_t t, const Marker& m) { return t < m.tick; });
  985. list.insert (at, std::move (marker));
  986. }
  987. std::vector<Bar> Song::barsBetween (std::int64_t from, std::int64_t to) const
  988. {
  989. std::vector<Bar> bars;
  990. auto barLength = [] (int numerator, int denominator) {
  991. return std::max<std::int64_t> (1, (std::int64_t) ppq * 4 * std::max (1, numerator) / std::max (1, denominator));
  992. };
  993. Bar bar { 0, barLength (beatsPerBar, beatUnit), 1 };
  994. const auto& list = markers();
  995. std::size_t next = 0;
  996. while (bar.tick < to)
  997. {
  998. // time signature changes falling at the start of this bar apply to it
  999. while (next < list.size() && (! list[next].isSignature() || list[next].tick <= bar.tick))
  1000. {
  1001. if (list[next].isSignature())
  1002. bar.length = barLength (list[next].numerator, list[next].denominator);
  1003. ++next;
  1004. }
  1005. // the next change cuts this bar short and starts a new one there
  1006. const auto end = next < list.size() ? std::min (bar.tick + bar.length, list[next].tick) : bar.tick + bar.length;
  1007. if (end > from)
  1008. bars.push_back ({ bar.tick, end - bar.tick, bar.number });
  1009. bar = { end, bar.length, bar.number + 1 };
  1010. // no changes ahead: the rest is arithmetic (avoids walking bar by bar up to `from`)
  1011. if (bar.tick < from && next >= list.size())
  1012. {
  1013. const auto skip = (from - bar.tick) / bar.length;
  1014. bar.tick += skip * bar.length;
  1015. bar.number += (int) skip;
  1016. }
  1017. }
  1018. return bars;
  1019. }
  1020. Bar Song::barAt (std::int64_t tick) const
  1021. {
  1022. const auto bars = barsBetween (std::max<std::int64_t> (0, tick), std::max<std::int64_t> (0, tick) + 1);
  1023. return bars.empty() ? Bar { 0, barTicks(), 1 } : bars.front();
  1024. }
  1025. void Song::selectArrangement (int index)
  1026. {
  1027. if (arrangements.empty())
  1028. arrangements.push_back ({ "Arrangement 1", {}, 0, 0, {} });
  1029. currentArrangement = std::clamp (currentArrangement, 0, (int) arrangements.size() - 1);
  1030. index = std::clamp (index, 0, (int) arrangements.size() - 1);
  1031. if (index == currentArrangement)
  1032. return;
  1033. auto& from = arrangements[(std::size_t) currentArrangement];
  1034. from.clips = std::move (playlist);
  1035. from.blocks = std::move (blocks);
  1036. from.loopStart = loopStart;
  1037. from.loopEnd = loopEnd;
  1038. auto& to = arrangements[(std::size_t) index];
  1039. playlist = std::move (to.clips);
  1040. to.clips.clear();
  1041. blocks = std::move (to.blocks);
  1042. to.blocks.clear();
  1043. loopStart = to.loopStart;
  1044. loopEnd = to.loopEnd;
  1045. trackRange = {}; // (round 190pa: a range on tracks belongs to the arrangement it was drawn in)
  1046. currentArrangement = index;
  1047. }
  1048. int Song::addArrangement (const std::string& name, bool copyCurrent)
  1049. {
  1050. Arrangement a;
  1051. a.name = name;
  1052. if (copyCurrent)
  1053. {
  1054. a.clips = playlist;
  1055. a.blocks = blocks;
  1056. a.loopStart = loopStart;
  1057. a.loopEnd = loopEnd;
  1058. a.markers = markers();
  1059. a.sections = sections(); // (round 190ol)
  1060. a.chords = chords(); // (round 190pf)
  1061. }
  1062. arrangements.push_back (std::move (a));
  1063. selectArrangement ((int) arrangements.size() - 1);
  1064. return currentArrangement;
  1065. }
  1066. void Song::removeArrangement (int index)
  1067. {
  1068. if (arrangements.size() <= 1 || index < 0 || index >= (int) arrangements.size())
  1069. return;
  1070. if (index == currentArrangement)
  1071. selectArrangement (index == 0 ? 1 : index - 1);
  1072. arrangements.erase (arrangements.begin() + index);
  1073. if (currentArrangement > index)
  1074. --currentArrangement;
  1075. // round 190pe (track versions): the versions made in the removed arrangement go (each track keeps its active one,
  1076. // which is in no other arrangement); later ones follow the renumbering
  1077. for (auto& t : playlistTracks)
  1078. if (! t.versions.empty())
  1079. {
  1080. if (t.versionArrangement == index)
  1081. {
  1082. t.versions.clear();
  1083. t.activeVersion = 0;
  1084. t.versionArrangement = 0;
  1085. }
  1086. else if (t.versionArrangement > index)
  1087. --t.versionArrangement;
  1088. }
  1089. }
  1090. namespace
  1091. {
  1092. // The value field behind output k of a panel (a Dashboard's: its control's value, an XY pad's X then Y)
  1093. const float* surfaceOutputValue (const std::vector<SurfaceControl>& controls, int k) noexcept
  1094. {
  1095. if (k < 0)
  1096. return nullptr;
  1097. for (const auto& c : controls)
  1098. {
  1099. if (k < c.outputs())
  1100. return k == 0 ? &c.value : &c.valueY;
  1101. k -= c.outputs();
  1102. }
  1103. return nullptr;
  1104. }
  1105. float* surfaceOutputValue (std::vector<SurfaceControl>& controls, int k) noexcept
  1106. {
  1107. return const_cast<float*> (surfaceOutputValue (std::as_const (controls), k));
  1108. }
  1109. } // namespace
  1110. namespace samplerparam
  1111. {
  1112. namespace
  1113. {
  1114. #ifndef TR_NOOP
  1115. #define TR_NOOP(text) text
  1116. #endif
  1117. struct Range
  1118. {
  1119. const char* name;
  1120. float lo, hi, mid; // mid < 0: linear (else the knob's skew from its mid point, like juce::Slider)
  1121. };
  1122. constexpr Range ranges[count] = { { TR_NOOP ("Attack"), 0.0f, 2.0f, 0.2f }, { TR_NOOP ("Decay"), 0.0f, 10.0f, 0.5f },
  1123. { TR_NOOP ("Sustain"), 0.0f, 1.0f, -1.0f }, { TR_NOOP ("Release"), 0.0f, 4.0f, 0.4f },
  1124. { TR_NOOP ("Cutoff"), 20.0f, 20000.0f, 1000.0f }, { TR_NOOP ("Resonance"), 0.0f, 1.0f, -1.0f },
  1125. { TR_NOOP ("Start"), 0.0f, 1.0f, -1.0f }, { TR_NOOP ("End"), 0.0f, 1.0f, -1.0f } };
  1126. double skewOf (const Range& r) noexcept
  1127. {
  1128. return r.mid < 0.0f ? 1.0 : std::log (0.5) / std::log ((double) (r.mid - r.lo) / (double) (r.hi - r.lo));
  1129. }
  1130. } // namespace
  1131. const char* name (int param) noexcept
  1132. {
  1133. return param >= 0 && param < count ? ranges[param].name : "";
  1134. }
  1135. float toValue (int param, float natural) noexcept
  1136. {
  1137. if (param < 0 || param >= count)
  1138. return 0.0f;
  1139. const auto& r = ranges[param];
  1140. const auto p = std::clamp ((double) (natural - r.lo) / (double) (r.hi - r.lo), 0.0, 1.0);
  1141. return (float) std::pow (p, skewOf (r));
  1142. }
  1143. float toNatural (int param, float value) noexcept
  1144. {
  1145. if (param < 0 || param >= count)
  1146. return 0.0f;
  1147. const auto& r = ranges[param];
  1148. const auto v = std::clamp ((double) value, 0.0, 1.0);
  1149. const auto p = v <= 0.0 ? 0.0 : std::exp (std::log (v) / skewOf (r));
  1150. return (float) (r.lo + (r.hi - r.lo) * p);
  1151. }
  1152. float get (const SamplerSettings& s, int param) noexcept
  1153. {
  1154. switch (param)
  1155. {
  1156. case attack: return toValue (param, s.attack);
  1157. case decay: return toValue (param, s.decay);
  1158. case sustain: return toValue (param, s.sustain);
  1159. case release: return toValue (param, s.release);
  1160. case cutoff: return toValue (param, s.cutoff);
  1161. case resonance: return toValue (param, s.resonance);
  1162. case start: return toValue (param, s.regionStart);
  1163. case end: return toValue (param, s.regionEnd);
  1164. default: return 0.0f;
  1165. }
  1166. }
  1167. void set (SamplerSettings& s, int param, float value) noexcept
  1168. {
  1169. const auto x = toNatural (param, value);
  1170. switch (param)
  1171. {
  1172. case attack: s.attack = x; break;
  1173. case decay: s.decay = x; break;
  1174. case sustain: s.sustain = x; break;
  1175. case release: s.release = x; break;
  1176. case cutoff: s.cutoff = x; break;
  1177. case resonance: s.resonance = x; break;
  1178. case start: s.regionStart = x; break;
  1179. case end: s.regionEnd = x; break;
  1180. default: return;
  1181. }
  1182. // like editing the knob by hand: the envelope / filter replace FL's imported voice (REA_rodada69 §3, REA_rodada76)
  1183. if (param <= release)
  1184. {
  1185. s.flVolumeEnvelope.clear();
  1186. s.flmPad.clear();
  1187. }
  1188. if (param <= resonance)
  1189. s.flChannel.clear();
  1190. }
  1191. } // namespace samplerparam
  1192. float channelPitchShift (const ChannelDef& c) noexcept
  1193. {
  1194. return (float) (60 - c.misc.rootNote) + (c.sampler.keepPitch ? (float) c.sampler.flStretchPitch / 100.0f : 0.0f);
  1195. }
  1196. float channelPitchValue (const ChannelDef& c) noexcept
  1197. {
  1198. return std::clamp (((c.sampler.pitch - channelPitchShift (c)) / 48.0f + 1.0f) * 0.5f, 0.0f, 1.0f);
  1199. }
  1200. float channelPitchSemitones (const ChannelDef&, float v) noexcept
  1201. {
  1202. return (std::clamp (v, 0.0f, 1.0f) * 2.0f - 1.0f) * 48.0f; // (the knob's range does not hold it: see Song.h)
  1203. }
  1204. float Song::targetValue (const AutomationTarget& t) const noexcept
  1205. {
  1206. const auto validChannel = t.index >= 0 && t.index < (int) channels.size();
  1207. const auto validTrack = t.index >= 0 && t.index < (int) mixer.size();
  1208. switch (t.kind)
  1209. {
  1210. case AutomationTargetKind::channelVolume: return validChannel ? channels[(std::size_t) t.index].volume : -1.0f;
  1211. case AutomationTargetKind::channelPan: return validChannel ? (channels[(std::size_t) t.index].pan + 1.0f) * 0.5f : -1.0f;
  1212. case AutomationTargetKind::channelAdjust:
  1213. {
  1214. if (! validChannel || ! leveladjust::valid (t.param))
  1215. return -1.0f;
  1216. const auto& l = channels[(std::size_t) t.index].misc.levels;
  1217. return t.param == leveladjust::volume ? l.volume * 0.5f
  1218. : ((t.param == leveladjust::pan ? l.pan : t.param == leveladjust::modX ? l.modX : l.modY) + 1.0f) * 0.5f;
  1219. }
  1220. case AutomationTargetKind::mixerVolume: return validTrack ? mixer[(std::size_t) t.index].volume : -1.0f;
  1221. case AutomationTargetKind::mixerPan: return validTrack ? (mixer[(std::size_t) t.index].pan + 1.0f) * 0.5f : -1.0f;
  1222. case AutomationTargetKind::effectParam:
  1223. if (validTrack && t.slot >= 0 && t.slot < (int) mixer[(std::size_t) t.index].effects.size()
  1224. && mixer[(std::size_t) t.index].effects[(std::size_t) t.slot].kind != EffectKind::plugin && t.param >= 0
  1225. && t.param < maxEffectParams)
  1226. return mixer[(std::size_t) t.index].effects[(std::size_t) t.slot].params[(std::size_t) t.param];
  1227. return validTrack ? 0.5f : -1.0f; // plugin parameter: the value lives in the plugin
  1228. case AutomationTargetKind::channelParam:
  1229. if (validChannel && t.param == channelPitchParam) // (round 190py: the PITCH knob)
  1230. return channelPitchValue (channels[(std::size_t) t.index]);
  1231. if (! validChannel)
  1232. return -1.0f;
  1233. // an Envelope Controller's global Mod X / Y (round 164f): the value lives in its state
  1234. if (channels[(std::size_t) t.index].instrument == InstrumentKind::controller
  1235. && (t.param == envelopeControllerModXParam || t.param == envelopeControllerModYParam))
  1236. if (const auto ec = parseEnvelopeController (channels[(std::size_t) t.index].controllerState))
  1237. return t.param == envelopeControllerModXParam ? ec->modX : ec->modY;
  1238. // a Dashboard's output k (its control's value), the Voltage Controller's offsets / scales (round 165)
  1239. if (channels[(std::size_t) t.index].instrument == InstrumentKind::dashboard)
  1240. if (const auto* v = surfaceOutputValue (channels[(std::size_t) t.index].patcher.surface, t.param))
  1241. return *v;
  1242. if (channels[(std::size_t) t.index].instrument == InstrumentKind::voltage && t.param >= 0 && t.param < voltage::paramCount)
  1243. if (const auto vs = voltage::parse (channels[(std::size_t) t.index].pluginState))
  1244. return voltage::paramValue (*vs, t.param);
  1245. // the Sampler's knobs (issue #12)
  1246. if (channels[(std::size_t) t.index].instrument == InstrumentKind::sampler && t.param >= 0 && t.param < samplerparam::count)
  1247. return samplerparam::get (channels[(std::size_t) t.index].sampler, t.param);
  1248. // LYNX Soundfont's knobs (issue #152, round 190he: a linked controller moved nothing)
  1249. if (channels[(std::size_t) t.index].instrument == InstrumentKind::soundfont && sf::automatable (t.param))
  1250. return sf::normalise (t.param, sf::readParams (channels[(std::size_t) t.index].modelParams)[(std::size_t) t.param]);
  1251. // LYNX Synth's knobs (issue #152, round 190he; core/SynthParams.h)
  1252. if (channels[(std::size_t) t.index].instrument == InstrumentKind::synth && synthparam::valid (t.param))
  1253. return synthparam::get (channels[(std::size_t) t.index].synth, synthparam::indexOf (t.param));
  1254. // a MIDI Out's patch and knobs (round 167i)
  1255. if (channels[(std::size_t) t.index].instrument == InstrumentKind::midiOut && t.param >= 0 && t.param <= midiout::controlCount)
  1256. return midiout::paramValue (midiout::stateOf (channels[(std::size_t) t.index].pluginState), t.param);
  1257. // the knobs of an FL engine kept in the channel's state (round 168n)
  1258. if (const auto v = modelparams::value01 (channels[(std::size_t) t.index], t.param))
  1259. return *v;
  1260. return 0.5f;
  1261. case AutomationTargetKind::mixerSend:
  1262. return validTrack && routes (t.index, t.slot) ? faderPosition (routeLevel (t.index, t.slot)) : -1.0f;
  1263. case AutomationTargetKind::effectMix:
  1264. return validTrack && t.slot >= 0 && t.slot < (int) mixer[(std::size_t) t.index].effects.size()
  1265. ? mixer[(std::size_t) t.index].effects[(std::size_t) t.slot].mix
  1266. : -1.0f;
  1267. case AutomationTargetKind::tempo: return valueFromTempo (bpm);
  1268. case AutomationTargetKind::crossfader: return std::clamp ((crossfader + 1.0f) * 0.5f, 0.0f, 1.0f); // (round 190kc)
  1269. case AutomationTargetKind::modulatorMacro: // (round 190ox: a Macro modulator's knob)
  1270. return t.index >= 0 && t.index < (int) modulators.size() && modulators[(std::size_t) t.index].kind == ModKind::macro
  1271. ? modulators[(std::size_t) t.index].macro
  1272. : -1.0f;
  1273. case AutomationTargetKind::vcaLevel:
  1274. return t.index >= 0 && t.index < (int) vcas.size() ? vcas[(std::size_t) t.index].level : -1.0f;
  1275. case AutomationTargetKind::none: break;
  1276. }
  1277. return -1.0f;
  1278. }
  1279. void Song::removeModulator (int index)
  1280. {
  1281. if (index < 0 || index >= (int) modulators.size())
  1282. return;
  1283. modulators.erase (modulators.begin() + index);
  1284. forEachTarget ([index] (AutomationTarget& t) {
  1285. if (t.kind != AutomationTargetKind::modulatorMacro)
  1286. return;
  1287. if (t.index == index)
  1288. t = AutomationTarget {};
  1289. else if (t.index > index)
  1290. --t.index;
  1291. });
  1292. }
  1293. float Song::modulationBase (const AutomationTarget& t) const noexcept
  1294. {
  1295. if (! soundfontModBaseReal && t.kind == AutomationTargetKind::channelParam && t.index >= 0 && t.index < (int) channels.size()
  1296. && channels[(std::size_t) t.index].instrument == InstrumentKind::soundfont)
  1297. return 0.5f; // (a project saved before round 190he: every Soundfont knob's value read 0.5 then)
  1298. return targetValue (t);
  1299. }
  1300. bool Song::setTargetValue (const AutomationTarget& t, float v) noexcept
  1301. {
  1302. v = std::clamp (v, 0.0f, 1.0f);
  1303. const auto validChannel = t.index >= 0 && t.index < (int) channels.size();
  1304. const auto validTrack = t.index >= 0 && t.index < (int) mixer.size();
  1305. switch (t.kind)
  1306. {
  1307. case AutomationTargetKind::channelVolume: if (! validChannel) return false; channels[(std::size_t) t.index].volume = v; return true;
  1308. case AutomationTargetKind::channelPan: if (! validChannel) return false; channels[(std::size_t) t.index].pan = v * 2.0f - 1.0f; return true;
  1309. case AutomationTargetKind::channelAdjust:
  1310. {
  1311. if (! validChannel || ! leveladjust::valid (t.param))
  1312. return false;
  1313. auto& l = channels[(std::size_t) t.index].misc.levels;
  1314. (t.param == leveladjust::volume ? l.volume : t.param == leveladjust::pan ? l.pan : t.param == leveladjust::modX ? l.modX : l.modY) = v * 2.0f - (t.param == leveladjust::volume ? 0.0f : 1.0f);
  1315. return true;
  1316. }
  1317. case AutomationTargetKind::mixerVolume: if (! validTrack) return false; mixer[(std::size_t) t.index].volume = v; return true;
  1318. case AutomationTargetKind::mixerPan: if (! validTrack) return false; mixer[(std::size_t) t.index].pan = v * 2.0f - 1.0f; return true;
  1319. case AutomationTargetKind::tempo: bpm = tempoFromValue (v); return true;
  1320. case AutomationTargetKind::crossfader: crossfader = v * 2.0f - 1.0f; return true; // (round 190kc)
  1321. case AutomationTargetKind::modulatorMacro: // (round 190ox)
  1322. if (t.index < 0 || t.index >= (int) modulators.size() || modulators[(std::size_t) t.index].kind != ModKind::macro)
  1323. return false;
  1324. modulators[(std::size_t) t.index].macro = v;
  1325. return true;
  1326. case AutomationTargetKind::vcaLevel:
  1327. if (t.index < 0 || t.index >= (int) vcas.size())
  1328. return false;
  1329. vcas[(std::size_t) t.index].level = v;
  1330. return true;
  1331. case AutomationTargetKind::mixerSend:
  1332. if (! validTrack || ! routes (t.index, t.slot))
  1333. return false;
  1334. setRouteLevel (t.index, t.slot, faderGain (v));
  1335. return true;
  1336. case AutomationTargetKind::effectMix:
  1337. if (! validTrack || t.slot < 0 || t.slot >= (int) mixer[(std::size_t) t.index].effects.size())
  1338. return false;
  1339. mixer[(std::size_t) t.index].effects[(std::size_t) t.slot].mix = v;
  1340. return true;
  1341. case AutomationTargetKind::effectParam:
  1342. if (validTrack && t.slot >= 0 && t.slot < (int) mixer[(std::size_t) t.index].effects.size()
  1343. && mixer[(std::size_t) t.index].effects[(std::size_t) t.slot].kind != EffectKind::plugin && t.param >= 0
  1344. && t.param < maxEffectParams)
  1345. {
  1346. mixer[(std::size_t) t.index].effects[(std::size_t) t.slot].params[(std::size_t) t.param] = v;
  1347. return true;
  1348. }
  1349. return false;
  1350. case AutomationTargetKind::channelParam:
  1351. if (validChannel && t.param == channelPitchParam) // (round 190py: the PITCH knob, as FL's song-start value sets it)
  1352. {
  1353. auto& c = channels[(std::size_t) t.index];
  1354. c.sampler.pitch = channelPitchShift (c) + channelPitchSemitones (c, v);
  1355. return true;
  1356. }
  1357. if (validChannel && channels[(std::size_t) t.index].instrument == InstrumentKind::controller
  1358. && (t.param == envelopeControllerModXParam || t.param == envelopeControllerModYParam))
  1359. if (auto ec = parseEnvelopeController (channels[(std::size_t) t.index].controllerState))
  1360. {
  1361. (t.param == envelopeControllerModXParam ? ec->modX : ec->modY) = v;
  1362. channels[(std::size_t) t.index].controllerState = writeEnvelopeController (*ec);
  1363. return true;
  1364. }
  1365. if (validChannel && channels[(std::size_t) t.index].instrument == InstrumentKind::dashboard)
  1366. if (auto* value = surfaceOutputValue (channels[(std::size_t) t.index].patcher.surface, t.param))
  1367. {
  1368. *value = v;
  1369. return true;
  1370. }
  1371. if (validChannel && channels[(std::size_t) t.index].instrument == InstrumentKind::voltage && t.param >= 0 && t.param < voltage::paramCount)
  1372. if (auto vs = voltage::parse (channels[(std::size_t) t.index].pluginState))
  1373. {
  1374. voltage::setParamValue (*vs, t.param, v);
  1375. channels[(std::size_t) t.index].pluginState = voltage::write (*vs);
  1376. return true;
  1377. }
  1378. if (validChannel && channels[(std::size_t) t.index].instrument == InstrumentKind::sampler && t.param >= 0
  1379. && t.param < samplerparam::count)
  1380. {
  1381. samplerparam::set (channels[(std::size_t) t.index].sampler, t.param, v);
  1382. return true;
  1383. }
  1384. if (validChannel && channels[(std::size_t) t.index].instrument == InstrumentKind::soundfont && sf::automatable (t.param))
  1385. {
  1386. auto& c = channels[(std::size_t) t.index]; // (issue #152, round 190he)
  1387. auto params = sf::readParams (c.modelParams);
  1388. params[(std::size_t) t.param] = sf::denormalise (t.param, v);
  1389. c.modelParams.assign (params.begin(), params.end());
  1390. return true;
  1391. }
  1392. if (validChannel && channels[(std::size_t) t.index].instrument == InstrumentKind::synth && synthparam::valid (t.param))
  1393. {
  1394. synthparam::set (channels[(std::size_t) t.index].synth, synthparam::indexOf (t.param), v); // (issue #152, round 190he)
  1395. return true;
  1396. }
  1397. if (validChannel && channels[(std::size_t) t.index].instrument == InstrumentKind::midiOut && t.param >= 0
  1398. && t.param <= midiout::controlCount)
  1399. {
  1400. auto& ch = channels[(std::size_t) t.index];
  1401. try
  1402. {
  1403. auto ms = midiout::stateOf (ch.pluginState);
  1404. midiout::setParamValue (ms, t.param, v);
  1405. ch.pluginState = midiout::write (ms);
  1406. }
  1407. catch (...)
  1408. {
  1409. return false;
  1410. }
  1411. return true;
  1412. }
  1413. // the knobs of an FL engine kept in the channel's state (round 168n)
  1414. if (validChannel && modelparams::find (channels[(std::size_t) t.index].instrument, t.param) != nullptr)
  1415. return modelparams::setValue01 (channels[(std::size_t) t.index], t.param, v);
  1416. return false;
  1417. case AutomationTargetKind::none: break;
  1418. }
  1419. return false;
  1420. }
  1421. float Song::targetValueAt (const AutomationTarget& target, double tick) const
  1422. {
  1423. // the same rule as playback (RackRenderer's automationValueAt, issue #97)
  1424. const Clip* playing = nullptr;
  1425. const Clip* ended = nullptr;
  1426. for (const auto& c : playlist)
  1427. {
  1428. if (c.kind != ClipKind::automation || c.automation < 0 || c.automation >= (int) automations.size() || c.length <= 0 || c.muted
  1429. || isTrackMuted (c.track) || ! (automations[(std::size_t) c.automation].target == target) || tick < (double) c.start)
  1430. continue;
  1431. if (tick < (double) c.end())
  1432. {
  1433. if (playing == nullptr || c.start > playing->start || (c.start == playing->start && c.automation < playing->automation))
  1434. playing = &c;
  1435. }
  1436. else if (ended == nullptr || c.end() > ended->end() || (c.end() == ended->end() && c.start > ended->start))
  1437. ended = &c;
  1438. }
  1439. if (playing != nullptr)
  1440. return automations[(std::size_t) playing->automation].playAt (tick - (double) playing->start + (double) playing->offset, tick);
  1441. if (ended != nullptr)
  1442. return automations[(std::size_t) ended->automation].playAt ((double) (ended->length + ended->offset), (double) ended->end());
  1443. return std::numeric_limits<float>::quiet_NaN();
  1444. }
  1445. double Song::tempoAt (double tick) const
  1446. {
  1447. // tempo automation and FL's pattern Tempo events (issue #86, core/TempoMap.h)
  1448. return tempomap::tempoAt (*this, tick);
  1449. }
  1450. double Song::secondsForTicks (std::int64_t ticks) const
  1451. {
  1452. if (! tempomap::active (*this))
  1453. return (double) ticks * 60.0 / (std::max (1.0, bpm) * ppq);
  1454. // integrate in 1/16 steps (playback changes tempo block by block; the difference is minimal). Round 190ry (Q3): each
  1455. // step's lookup reads the playlist's tempo clips only (tempomap::tempoClips: tempoAtIn over them is tempoAt, the same
  1456. // value): it walked every clip of the song per 16th, 1.6-1.8 s per call on a 1,728-bar project of 17,928 clips, paid
  1457. // by the message thread at every edit while the song played
  1458. double seconds = 0.0;
  1459. constexpr std::int64_t step = ticksPerStep;
  1460. const auto clips = tempomap::tempoClips (*this);
  1461. for (std::int64_t t = 0; t < ticks; t += step)
  1462. {
  1463. const auto n = std::min (step, ticks - t);
  1464. seconds += (double) n * 60.0 / (std::max (1.0, tempomap::tempoAtIn (*this, clips, (double) t)) * ppq);
  1465. }
  1466. return seconds;
  1467. }
  1468. float Automation::mapLive (float v) const noexcept
  1469. {
  1470. v = std::clamp (v, 0.0f, 1.0f);
  1471. if (curve.size() < 2)
  1472. return v;
  1473. const auto x = v * (float) (curve.size() - 1);
  1474. const auto i = std::min ((std::size_t) x, curve.size() - 2);
  1475. const auto f = x - (float) i;
  1476. return std::clamp (curve[i] + (curve[i + 1] - curve[i]) * f, 0.0f, 1.0f);
  1477. }
  1478. float Automation::Link::scaled (float v) const noexcept
  1479. {
  1480. v = std::clamp (v, 0.0f, 1.0f);
  1481. if (scale.size() < 2)
  1482. return v;
  1483. const auto x = v * (float) (scale.size() - 1);
  1484. const auto i = std::min ((std::size_t) x, scale.size() - 2);
  1485. const auto f = x - (float) i;
  1486. return std::clamp (scale[i] + (scale[i + 1] - scale[i]) * f, 0.0f, 1.0f);
  1487. }
  1488. float PatternEvents::valueAt (double tick) const noexcept
  1489. {
  1490. if (events.empty())
  1491. return 0.5f;
  1492. // the last event at or before `tick`
  1493. auto it = std::upper_bound (events.begin(), events.end(), tick, [] (double t, const PatternEvent& e) { return t < (double) e.tick; });
  1494. return it == events.begin() ? events.front().value : std::prev (it)->value;
  1495. }
  1496. float Automation::rerange (float v) const noexcept
  1497. {
  1498. const auto span = pointsMax - pointsMin;
  1499. const auto x = std::abs (span) > 1.0e-9f ? (v - pointsMin) / span : 0.0f;
  1500. return std::clamp (rangeMin + (rangeMax - rangeMin) * x, 0.0f, 1.0f);
  1501. }
  1502. float Automation::valueAt (double tick) const noexcept
  1503. {
  1504. return automationCurveAt (points, tick);
  1505. }
  1506. double automationSegmentShape (const std::vector<AutomationPoint>& points, std::size_t k, double x) noexcept
  1507. {
  1508. if (k + 1 >= points.size())
  1509. return x;
  1510. const auto& a = points[k];
  1511. const auto& b = points[k + 1];
  1512. if (a.mode == AutomationPoint::legacyCurve) // LYNX's law before round 190bw: a power curve
  1513. return a.tension != 0.0f ? std::pow (x, std::pow (2.0, (double) a.tension * 3.0)) : x;
  1514. if (a.mode != flcurve::smooth)
  1515. return flcurve::shape (a.mode, -a.tension, x);
  1516. // Smooth: the slopes come from the neighbouring segments that are Smooth too
  1517. flcurve::SmoothSide before, after;
  1518. if (k > 0 && points[k - 1].mode == flcurve::smooth)
  1519. {
  1520. before.smooth = true;
  1521. before.dx = (double) (a.tick - points[k - 1].tick);
  1522. before.y = (double) points[k - 1].value;
  1523. }
  1524. if (k + 2 < points.size() && b.mode == flcurve::smooth)
  1525. {
  1526. after.smooth = true;
  1527. after.dx = (double) (points[k + 2].tick - b.tick);
  1528. after.y = (double) points[k + 2].value;
  1529. }
  1530. return flcurve::evaluate (flcurve::prepareSmooth (-a.tension, (double) (b.tick - a.tick), (double) a.value, (double) b.value, before, after), x);
  1531. }
  1532. float automationCurveAt (const std::vector<AutomationPoint>& points, double tick) noexcept
  1533. {
  1534. if (points.empty())
  1535. return 0.5f;
  1536. if (tick <= (double) points.front().tick)
  1537. return points.front().value;
  1538. for (std::size_t i = 1; i < points.size(); ++i)
  1539. {
  1540. const auto& a = points[i - 1];
  1541. const auto& b = points[i];
  1542. if (tick < (double) b.tick)
  1543. {
  1544. const auto span = (double) std::max<std::int64_t> (1, b.tick - a.tick);
  1545. const auto x = (tick - (double) a.tick) / span;
  1546. if (a.mode == AutomationPoint::legacyCurve || (a.mode == 0 && a.tension == 0.0f))
  1547. {
  1548. // a straight segment, or an older project's bend: the same float arithmetic as before round 190bw
  1549. auto t = (float) x;
  1550. if (a.tension != 0.0f)
  1551. t = std::pow (t, std::pow (2.0f, a.tension * 3.0f));
  1552. return a.value + (b.value - a.value) * t;
  1553. }
  1554. return (float) ((double) a.value + ((double) b.value - (double) a.value) * automationSegmentShape (points, i - 1, x));
  1555. }
  1556. }
  1557. return points.back().value;
  1558. }
  1559. int automationPointMode (const std::vector<AutomationPoint>& points, int point) noexcept
  1560. {
  1561. if (point < 1 || point >= (int) points.size())
  1562. return -1;
  1563. const auto m = points[(std::size_t) point - 1].mode;
  1564. return m < flcurve::modeCount ? (int) m : -1;
  1565. }
  1566. void setAutomationPointMode (std::vector<AutomationPoint>& points, int point, int mode) noexcept
  1567. {
  1568. if (point < 1 || point >= (int) points.size() || mode < 0 || mode >= flcurve::modeCount)
  1569. return;
  1570. points[(std::size_t) point - 1].mode = (std::uint8_t) mode;
  1571. }
  1572. int insertAutomationPoint (std::vector<AutomationPoint>& points, AutomationPoint p, int mode, float tension)
  1573. {
  1574. const auto at = std::upper_bound (points.begin(), points.end(), p.tick, [] (std::int64_t t, const AutomationPoint& q) { return t < q.tick; });
  1575. const auto index = (int) (at - points.begin());
  1576. const auto m = (std::uint8_t) std::clamp (mode, 0, (int) flcurve::modeCount - 1);
  1577. p.mode = 0;
  1578. p.tension = 0.0f;
  1579. if (index > 0)
  1580. {
  1581. auto& before = points[(std::size_t) index - 1];
  1582. if (index < (int) points.size()) // splitting a segment: its curve stays on the part after the new point
  1583. {
  1584. p.mode = before.mode;
  1585. p.tension = before.tension;
  1586. }
  1587. before.mode = m;
  1588. before.tension = std::clamp (tension, -1.0f, 1.0f);
  1589. }
  1590. points.insert (points.begin() + index, p);
  1591. return index;
  1592. }
  1593. void eraseAutomationPoint (std::vector<AutomationPoint>& points, int point)
  1594. {
  1595. if (point < 0 || point >= (int) points.size())
  1596. return;
  1597. if (point > 0)
  1598. {
  1599. auto& before = points[(std::size_t) point - 1];
  1600. const auto last = point + 1 == (int) points.size();
  1601. before.mode = last ? (std::uint8_t) 0 : points[(std::size_t) point].mode;
  1602. before.tension = last ? 0.0f : points[(std::size_t) point].tension;
  1603. }
  1604. points.erase (points.begin() + point);
  1605. }
  1606. void setAutomationSegmentTension (std::vector<AutomationPoint>& points, int segment, float tension) noexcept
  1607. {
  1608. if (segment < 0 || segment >= (int) points.size())
  1609. return;
  1610. auto& p = points[(std::size_t) segment];
  1611. p.tension = std::clamp (tension, -1.0f, 1.0f);
  1612. if (p.mode == AutomationPoint::legacyCurve)
  1613. p.mode = 0;
  1614. }
  1615. // --- FL's automation clip LFO (REA round 177b; FUN_00ba1700, FUN_00ba0710, FUN_00ba03d0, FUN_00677660/820) ---------
  1616. bool AutomationLfo::isDefault() const noexcept
  1617. {
  1618. return *this == AutomationLfo {};
  1619. }
  1620. double AutomationLfo::cyclesPerBeat (int speed) noexcept
  1621. {
  1622. // rate = (10001^(speed/65536) − 1) · 2^32/625 phase units per beat (FL: 45819 = 1 beat, 40898 = 2, 26257 = 16)
  1623. return (std::pow (10001.0, (double) speed / 65536.0) - 1.0) / 625.0;
  1624. }
  1625. int AutomationLfo::speedForBeats (double beatsPerCycle) noexcept
  1626. {
  1627. if (beatsPerCycle <= 0.0)
  1628. return 65536;
  1629. const auto speed = 65536.0 * std::log (625.0 / beatsPerCycle + 1.0) / std::log (10001.0);
  1630. return (int) std::clamp (std::lround (speed), 512L, 65536L);
  1631. }
  1632. float AutomationLfo::shape (std::uint32_t phase, int tensionKnob, int skewKnob, int pulseWidthKnob, bool unipolar) noexcept
  1633. {
  1634. constexpr double full = 4294967296.0; // 2^32: one cycle
  1635. const auto p = (double) pulseWidthKnob / 128.0;
  1636. const auto s = (double) skewKnob / 256.0;
  1637. const auto s7 = p > 0.0 ? std::round ((1.0 - p) * full - 1.0) : 4294967295.0;
  1638. const auto d = std::clamp (((1.0 - p) * 0.5 - s * (1.0 - std::abs (p))) * full, 1.0, s7 - 1.0);
  1639. const auto s5 = std::round (d);
  1640. const auto s6 = p < 0.0 ? std::max (1.0, std::round (d + p * full)) : s5;
  1641. const auto phi = (double) phase;
  1642. double x;
  1643. if (phi > s7)
  1644. return 1.0f; // the pulse's top (p > 0)
  1645. if (phi < s6)
  1646. x = 1.0 - phi * (2.0 / s6); // falling +1 → −1
  1647. else if (phi < s5)
  1648. return -1.0f; // the pulse's bottom (p < 0)
  1649. else
  1650. x = (phi - s5) * (2.0 / (s7 - s5)) - 1.0; // rising −1 → +1
  1651. // tension (FUN_00ba0250): T = sign(t)·((1e18)^((21^(|t|/128) − 1)·0.05) − 1)
  1652. const auto t = (double) tensionKnob;
  1653. const auto T = t == 0.0 ? 0.0 : (t > 0.0 ? 1.0 : -1.0) * (std::pow (9.99999984e17, (std::pow (21.0, std::abs (t) / 128.0) - 1.0) * 0.05) - 1.0);
  1654. auto curve = [T] (double a) {
  1655. if (T == 0.0)
  1656. return a;
  1657. if (T > 0.0)
  1658. return 1.0 - (std::pow (T + 1.0, 1.0 - a) - 1.0) / T;
  1659. return (std::pow (-T + 1.0, a) - 1.0) / -T;
  1660. };
  1661. const auto y = unipolar ? 2.0 * curve ((x + 1.0) * 0.5) - 1.0 : (x < 0.0 ? -curve (-x) : curve (x));
  1662. return (float) std::clamp (y, -1.0, 1.0);
  1663. }
  1664. float AutomationLfo::output (double clipTick, double songTick) const noexcept
  1665. {
  1666. constexpr double full = 4294967296.0;
  1667. // the amplitude points are bipolar: 0.5 = no swing, 1 = full, 0 = full and inverted (FL's renders, round 177b:
  1668. // a single point at 0.5 plays no LFO; points 0 → 1 swing, pass through nothing at the middle and swing back)
  1669. const auto amplitude = 2.0f * automationCurveAt (amp, clipTick) - 1.0f;
  1670. // the start: the middle of the rising ramp (the LFO starts at 0 going up) plus the phase knob (FUN_00ba06a0)
  1671. const auto p = (double) pulseWidth / 128.0, sk = (double) skew / 256.0;
  1672. const auto s7 = p > 0.0 ? std::round ((1.0 - p) * full - 1.0) : 4294967295.0;
  1673. const auto s5 = std::round (std::clamp (((1.0 - p) * 0.5 - sk * (1.0 - std::abs (p))) * full, 1.0, s7 - 1.0));
  1674. const auto start = std::fmod (s5 + (s7 - s5) * 0.5 + 1.0 + (double) phase, full);
  1675. // frozen: no movement inside the clip; global: the phase runs with the song instead of restarting with the clip
  1676. const auto frozen = (flags & 8) != 0, global = (flags & 2) != 0;
  1677. const auto beats = frozen ? 0.0 : std::max (0.0, global ? songTick : clipTick) / (double) ppq;
  1678. auto cycles = beats * cyclesPerBeat (speed);
  1679. cycles -= std::floor (cycles);
  1680. const auto at = (std::uint32_t) (std::uint64_t) std::fmod (start + cycles * full, full);
  1681. return amplitude * shape (at, tension, skew, pulseWidth, (flags & 4) != 0);
  1682. }
  1683. float AutomationLfo::apply (float value, double clipTick, double songTick) const noexcept
  1684. {
  1685. // TACArticulator.Compute (FUN_00ba1700): add mode out += L·amount; multiply mode out *= 1 + 2·L·amount, with L
  1686. // at half the waveform: FL's own renders (round 177b, lfo/meas: default, level 128, add and shaped clips) match
  1687. // only with the LFO's swing at ±0.5 × its amplitude, in both modes
  1688. const auto amount = (float) level / 128.0f * range;
  1689. const auto l = 0.5f * output (clipTick, songTick);
  1690. const auto out = add ? value + l * amount : value * (1.0f + 2.0f * l * amount);
  1691. return std::clamp (out, 0.0f, 1.0f);
  1692. }
  1693. // --- modulators (round 177b) ------------------------------------------------------------------------------------
  1694. namespace
  1695. {
  1696. float modNoise (std::uint32_t seed, std::int64_t step) noexcept
  1697. {
  1698. // a hash of (seed, step) to -1..1: the same output at the same song position, whatever was played before
  1699. auto x = (std::uint64_t) (std::uint32_t) step * 0x9E3779B97F4A7C15ull ^ ((std::uint64_t) seed << 32 | (std::uint32_t) (step >> 32));
  1700. x ^= x >> 30;
  1701. x *= 0xBF58476D1CE4E5B9ull;
  1702. x ^= x >> 27;
  1703. x *= 0x94D049BB133111EBull;
  1704. x ^= x >> 31;
  1705. return (float) ((double) (x >> 11) / 9007199254740992.0 * 2.0 - 1.0);
  1706. }
  1707. } // namespace
  1708. float Modulator::output (double cycles) const noexcept
  1709. {
  1710. const auto c = cycles + (double) phase;
  1711. const auto whole = std::floor (c);
  1712. const auto f = (float) (c - whole); // 0..1 within the cycle
  1713. float y = 0.0f;
  1714. switch (shape)
  1715. {
  1716. case ModShape::sine: y = std::sin (f * 6.28318530718f); break;
  1717. case ModShape::triangle: y = f < 0.25f ? f * 4.0f : (f < 0.75f ? 2.0f - f * 4.0f : f * 4.0f - 4.0f); break;
  1718. case ModShape::sawUp: y = f * 2.0f - 1.0f; break;
  1719. case ModShape::sawDown: y = 1.0f - f * 2.0f; break;
  1720. case ModShape::square: y = f < 0.5f ? 1.0f : -1.0f; break;
  1721. case ModShape::random: y = modNoise (seed, (std::int64_t) whole); break;
  1722. case ModShape::smoothRandom:
  1723. {
  1724. const auto a = modNoise (seed, (std::int64_t) whole), b = modNoise (seed, (std::int64_t) whole + 1);
  1725. const auto s = f * f * (3.0f - 2.0f * f);
  1726. y = a + (b - a) * s;
  1727. break;
  1728. }
  1729. }
  1730. return unipolar ? (y + 1.0f) * 0.5f : y;
  1731. }
  1732. float Modulator::stepOutput (double stepsIn) const noexcept
  1733. {
  1734. const auto c = stepsIn + (double) phase;
  1735. const auto whole = std::floor (c);
  1736. const auto f = (float) (c - whole); // 0..1 within the step
  1737. float y = 0.0f;
  1738. if (kind == ModKind::steps)
  1739. {
  1740. const auto count = (std::int64_t) steps.size();
  1741. if (count == 0)
  1742. return 0.0f;
  1743. const auto at = [&] (std::int64_t k) { return std::clamp (steps[(std::size_t) (((k % count) + count) % count)], -1.0f, 1.0f); };
  1744. const auto a = at ((std::int64_t) whole);
  1745. y = a;
  1746. // glide: the last `glide` of the step slides to the next value (an S curve, no click at either end)
  1747. if (glide > 0.0f && f > 1.0f - glide)
  1748. {
  1749. const auto u = (f - (1.0f - glide)) / glide;
  1750. const auto s = u * u * (3.0f - 2.0f * u);
  1751. y = a + (at ((std::int64_t) whole + 1) - a) * s;
  1752. }
  1753. }
  1754. else // random: sample and hold, `smooth` of each step spent moving to the next value (1 = a smooth curve)
  1755. {
  1756. const auto a = modNoise (seed, (std::int64_t) whole);
  1757. y = a;
  1758. if (smooth > 0.0f && f > 1.0f - smooth)
  1759. {
  1760. const auto u = (f - (1.0f - smooth)) / smooth;
  1761. const auto s = u * u * (3.0f - 2.0f * u);
  1762. y = a + (modNoise (seed, (std::int64_t) whole + 1) - a) * s;
  1763. }
  1764. }
  1765. return unipolar ? (y + 1.0f) * 0.5f : y;
  1766. }
  1767. bool Modulator::deterministic() const noexcept
  1768. {
  1769. switch (kind)
  1770. {
  1771. case ModKind::lfo: return sync;
  1772. case ModKind::steps:
  1773. case ModKind::random: return sync;
  1774. case ModKind::macro: return true;
  1775. case ModKind::follower:
  1776. case ModKind::envelope:
  1777. case ModKind::keytrack:
  1778. case ModKind::velocity: break;
  1779. }
  1780. return false;
  1781. }
  1782. const char* Modulator::kindName (ModKind kind) noexcept
  1783. {
  1784. switch (kind)
  1785. {
  1786. case ModKind::lfo: return "LFO";
  1787. case ModKind::follower: return "Envelope follower";
  1788. case ModKind::envelope: return "ADSR envelope";
  1789. case ModKind::steps: return "Steps";
  1790. case ModKind::random: return "Random";
  1791. case ModKind::macro: return "Macro";
  1792. case ModKind::keytrack: return "Keytrack";
  1793. case ModKind::velocity: return "Velocity";
  1794. }
  1795. return "LFO";
  1796. }
  1797. Modulator Modulator::make (ModKind kind)
  1798. {
  1799. Modulator m;
  1800. m.kind = kind;
  1801. switch (kind)
  1802. {
  1803. case ModKind::lfo: break;
  1804. case ModKind::follower: m.unipolar = true; break;
  1805. case ModKind::envelope: m.unipolar = true; break;
  1806. case ModKind::steps:
  1807. m.beats = 0.25; // 1/16 per step
  1808. m.steps = { 1.0f, -0.5f, 0.5f, -1.0f, 0.75f, -0.25f, 0.25f, -0.75f };
  1809. break;
  1810. case ModKind::random: m.beats = 0.25; break;
  1811. case ModKind::macro: m.unipolar = true; break;
  1812. case ModKind::keytrack: break;
  1813. case ModKind::velocity: m.unipolar = true; break;
  1814. }
  1815. return m;
  1816. }
  1817. namespace modenv
  1818. {
  1819. namespace
  1820. {
  1821. // a one-pole's share of the way to its target after `seconds` with time constant `ms` (0 ms: all of it)
  1822. float approach (float ms, double seconds) noexcept
  1823. {
  1824. return ms <= 0.05f ? 1.0f : (float) (1.0 - std::exp (-seconds * 1000.0 / (double) ms));
  1825. }
  1826. } // namespace
  1827. void envelope (const Modulator& m, State& s, bool gate, bool trigger, double seconds) noexcept
  1828. {
  1829. if (trigger)
  1830. s.stage = 1;
  1831. else if (! gate && s.stage >= 1 && s.stage <= 3)
  1832. s.stage = 4;
  1833. // linear attack (to 1 in `attack` ms), exponential decay and release (time constants), as the synths' own
  1834. switch (s.stage)
  1835. {
  1836. case 1:
  1837. {
  1838. const auto step = m.attack <= 0.05f ? 1.0f : (float) (seconds * 1000.0 / (double) m.attack);
  1839. s.level = std::min (1.0f, s.level + step);
  1840. if (s.level >= 1.0f)
  1841. s.stage = 2;
  1842. break;
  1843. }
  1844. case 2:
  1845. case 3:
  1846. {
  1847. const auto target = std::clamp (m.sustain, 0.0f, 1.0f);
  1848. s.level += (target - s.level) * approach (m.decay, seconds);
  1849. if (std::abs (s.level - target) < 1.0e-4f)
  1850. s.level = target, s.stage = 3;
  1851. break;
  1852. }
  1853. case 4:
  1854. s.level += (0.0f - s.level) * approach (m.release, seconds);
  1855. if (s.level < 1.0e-5f)
  1856. s.level = 0.0f, s.stage = 0;
  1857. break;
  1858. default: break;
  1859. }
  1860. }
  1861. void follow (const Modulator& m, State& s, float peak, double seconds) noexcept
  1862. {
  1863. const auto in = std::clamp (peak * std::pow (10.0f, m.gain / 20.0f), 0.0f, 1.0f);
  1864. s.level += (in - s.level) * approach (in > s.level ? m.attack : m.release, seconds);
  1865. }
  1866. } // namespace modenv
  1867. bool Modulator::isHostedTarget (const Song& song, const AutomationTarget& t) noexcept
  1868. {
  1869. if (t.kind == AutomationTargetKind::effectParam && t.index >= 0 && t.index < (int) song.mixer.size() && t.slot >= 0
  1870. && t.slot < (int) song.mixer[(std::size_t) t.index].effects.size())
  1871. {
  1872. const auto kind = song.mixer[(std::size_t) t.index].effects[(std::size_t) t.slot].kind;
  1873. return kind == EffectKind::plugin || kind == EffectKind::patcher;
  1874. }
  1875. if (t.kind == AutomationTargetKind::channelParam && t.index >= 0 && t.index < (int) song.channels.size())
  1876. {
  1877. const auto kind = song.channels[(std::size_t) t.index].instrument;
  1878. return kind == InstrumentKind::plugin || kind == InstrumentKind::patcher;
  1879. }
  1880. return false;
  1881. }
  1882. bool Modulator::canModulate (const Song& song, const AutomationTarget& t) noexcept
  1883. {
  1884. // round 190ox: a hosted plugin's parameters too (the base is kept host-side, ModRoute::base); not their MIDI
  1885. // controls (a CC per block), not a missing plugin's stand-in, not a macro (a modulator does not drive another)
  1886. if (t.kind == AutomationTargetKind::modulatorMacro)
  1887. return false;
  1888. if (isHostedTarget (song, t))
  1889. {
  1890. if (t.param < 0 || midictl::isMidiParam (t.param))
  1891. return false;
  1892. if (t.kind == AutomationTargetKind::effectParam && song.mixer[(std::size_t) t.index].effects[(std::size_t) t.slot].isSubstitute())
  1893. return false;
  1894. return true;
  1895. }
  1896. // LYNX's own controls: not the tempo
  1897. if (t.kind == AutomationTargetKind::none || t.kind == AutomationTargetKind::tempo || song.targetValue (t) < 0.0f)
  1898. return false;
  1899. if (t.kind == AutomationTargetKind::effectParam && t.index >= 0 && t.index < (int) song.mixer.size() && t.slot >= 0
  1900. && t.slot < (int) song.mixer[(std::size_t) t.index].effects.size())
  1901. {
  1902. const auto kind = song.mixer[(std::size_t) t.index].effects[(std::size_t) t.slot].kind;
  1903. return kind != EffectKind::plugin && kind != EffectKind::patcher;
  1904. }
  1905. if (t.kind == AutomationTargetKind::channelParam && t.index >= 0 && t.index < (int) song.channels.size())
  1906. {
  1907. const auto kind = song.channels[(std::size_t) t.index].instrument;
  1908. return kind != InstrumentKind::plugin && kind != InstrumentKind::patcher && ! midictl::isMidiParam (t.param);
  1909. }
  1910. return true;
  1911. }
  1912. std::int64_t Automation::length() const noexcept
  1913. {
  1914. return points.empty() ? 1 : std::max<std::int64_t> (1, points.back().tick);
  1915. }
  1916. Clip splitClip (Clip& clip, std::int64_t tick)
  1917. {
  1918. Clip rest = clip;
  1919. const auto head = std::clamp<std::int64_t> (tick - clip.start, 1, std::max<std::int64_t> (1, clip.length - 1));
  1920. clip.length = head;
  1921. rest.start = clip.start + head;
  1922. rest.offset = clip.offset + head;
  1923. rest.length -= head;
  1924. return rest;
  1925. }
  1926. double TrackEq::peakQ (float w) noexcept
  1927. {
  1928. return 0.0999 * (std::pow (1001.0, std::clamp ((double) w, 0.0, 1.0)) - 1.0) + 0.1;
  1929. }
  1930. double TrackEq::shelfSlope (float w) noexcept
  1931. {
  1932. return 1.9 * std::clamp ((double) w, 0.0, 1.0) + 0.1;
  1933. }
  1934. std::int64_t swingDelay (std::int64_t start, float swing, float channelMix) noexcept
  1935. {
  1936. if (swing <= 0.0f || channelMix <= 0.0f)
  1937. return 0;
  1938. constexpr std::int64_t s = ticksPerStep;
  1939. const auto k = (start + s / 2) / s;
  1940. if (k % 2 == 0)
  1941. return 0;
  1942. const auto w = s - 2 * std::abs (start - k * s);
  1943. return (std::int64_t) std::llround ((double) w * std::clamp (swing, 0.0f, 1.0f) * std::clamp (channelMix, 0.0f, 1.0f) * 0.5);
  1944. }
  1945. bool PatcherDoc::operator== (const PatcherDoc& o) const
  1946. {
  1947. return nodes == o.nodes && wires == o.wires && published == o.published && inputX == o.inputX && inputY == o.inputY && outputX == o.outputX && outputY == o.outputY
  1948. && outputTracks == o.outputTracks && surface == o.surface && surfaceX == o.surfaceX && surfaceY == o.surfaceY
  1949. && fromMidiPorts == o.fromMidiPorts && toMidiPorts == o.toMidiPorts && fromNotesHidden == o.fromNotesHidden
  1950. && rack == o.rack && zones == o.zones;
  1951. }
  1952. bool PatchNode::BusHead::operator== (const BusHead& o) const { return bus == o.bus && head == o.head && gain == o.gain; }
  1953. bool PatchNode::operator== (const PatchNode& o) const
  1954. {
  1955. return generator == o.generator && label == o.label && x == o.x && y == o.y && busHeads == o.busHeads
  1956. && paramIns == o.paramIns && paramOuts == o.paramOuts
  1957. && (generator ? channel == o.channel : effect == o.effect);
  1958. }
  1959. bool EffectSlot::operator== (const EffectSlot& o) const
  1960. {
  1961. if (kind != o.kind || enabled != o.enabled || params != o.params || mix != o.mix || ! (plugin == o.plugin) || sidechain != o.sidechain
  1962. || sidechain2 != o.sidechain2 || sendTracks != o.sendTracks || state != o.state || samplePath != o.samplePath || ! (substituteFor == o.substituteFor)
  1963. || presetName != o.presetName || abOther != o.abOther || abShowingB != o.abShowingB || branches.size() != o.branches.size()
  1964. || links.size() != o.links.size() || ! (patcher == o.patcher) || row != o.row || look != o.look || goal != o.goal
  1965. || goalAmount != o.goalAmount || displayView != o.displayView || lockState != o.lockState || ara != o.ara || ! (flOrigin == o.flOrigin) || engineRev != o.engineRev)
  1966. return false;
  1967. for (std::size_t i = 0; i < branches.size(); ++i)
  1968. if (branches[i].gain != o.branches[i].gain || branches[i].chain != o.branches[i].chain)
  1969. return false;
  1970. for (std::size_t i = 0; i < links.size(); ++i)
  1971. {
  1972. const auto& a = links[i];
  1973. const auto& b = o.links[i];
  1974. if (a.branch != b.branch || a.source != b.source || a.target != b.target || a.param != b.param || a.curve != b.curve)
  1975. return false;
  1976. }
  1977. return true;
  1978. }
  1979. float channelGain (float volume) noexcept
  1980. {
  1981. const auto v = std::clamp (volume, 0.0f, 1.0f);
  1982. return (std::pow (11.0f, v) - 1.0f) / 10.0f;
  1983. }
  1984. float levelAdjustGain (float multiplier) noexcept
  1985. {
  1986. const auto x = std::clamp (multiplier, 0.0f, 2.0f);
  1987. return x == 1.0f ? 1.0f : (std::pow (11.0f, x) - 1.0f) / 10.0f;
  1988. }
  1989. std::string levelVolumeText (float multiplier)
  1990. {
  1991. const auto x = std::clamp (multiplier, 0.0f, 2.0f);
  1992. const auto gain = levelAdjustGain (x);
  1993. char text[64];
  1994. if (gain <= 1.0e-6f)
  1995. std::snprintf (text, sizeof (text), "%d%% -INF dB 0.00", (int) std::lround (x * 100.0f));
  1996. else
  1997. std::snprintf (text, sizeof (text), "%d%% %.1fdB %.2f", (int) std::lround (x * 100.0f), 20.0 * std::log10 ((double) gain), (double) gain);
  1998. return text;
  1999. }
  2000. float faderGain (float position) noexcept
  2001. {
  2002. const auto v = std::clamp (position, 0.0f, 1.0f) * 1.25f;
  2003. return (std::pow (11.0f, v) - 1.0f) / 10.0f;
  2004. }
  2005. float faderPosition (float gain) noexcept
  2006. {
  2007. if (! (gain > 0.0f))
  2008. return 0.0f;
  2009. return std::clamp ((float) (std::log (10.0 * (double) gain + 1.0) / std::log (11.0) / 1.25), 0.0f, 1.0f);
  2010. }
  2011. Song makeExportSong (const Song& song, bool wholeSong, std::int64_t tailTicks, std::int64_t& musicLength)
  2012. {
  2013. Song out = song;
  2014. patternblocks::expandSong (out); // Pattern Blocks (round 170f) become clips
  2015. if (out.patterns.empty())
  2016. out.patterns.emplace_back().name = "Pattern 1";
  2017. if (! wholeSong || out.playlist.empty())
  2018. {
  2019. const auto index = std::clamp (out.currentPattern, 0, (int) out.patterns.size() - 1);
  2020. Clip clip;
  2021. clip.pattern = index;
  2022. clip.length = out.patterns[(std::size_t) index].effectiveLength (out.meter());
  2023. out.playlist = { clip };
  2024. musicLength = clip.length;
  2025. }
  2026. else
  2027. {
  2028. musicLength = 0;
  2029. for (const auto& c : out.playlist)
  2030. musicLength = std::max (musicLength, c.end());
  2031. }
  2032. // empty pattern in the tail: extends the song without playing anything. One extra bar of slack
  2033. // because the last rendered block goes slightly past the end and must not wrap to the start.
  2034. if (tailTicks > 0)
  2035. {
  2036. tailTicks += out.barTicks();
  2037. out.patterns.emplace_back().name = "(tail)";
  2038. Clip tail;
  2039. tail.pattern = (int) out.patterns.size() - 1;
  2040. tail.start = musicLength;
  2041. tail.length = tailTicks;
  2042. out.playlist.push_back (tail);
  2043. }
  2044. out.mode = PlayMode::song;
  2045. out.loopStart = out.loopEnd = 0; // export ignores the loop region
  2046. return out;
  2047. }
  2048. Song makeBounceSong (const Song& song, int track)
  2049. {
  2050. Song out = song;
  2051. if (track <= 0 || track >= (int) out.mixer.size())
  2052. return out;
  2053. for (auto& t : out.mixer)
  2054. t.solo = false;
  2055. auto& insert = out.mixer[(std::size_t) track];
  2056. insert.sends.clear();
  2057. insert.toMaster = true;
  2058. insert.masterLevel = 1.0f; // the insert's own output: its route level to Master is the route's (Render to audio keeps the
  2059. // route on the new insert; rendering it too played a route at 50 % at 25 %, round 186b)
  2060. insert.muted = false;
  2061. insert.solo = true; // it and whatever feeds it are audible
  2062. // Round 190gj (owner decision 2026-11-14, FL's split render): what the insert's effects listen to (a side-chain key,
  2063. // a hosted effect's Connections) plays as it does in the mix, unheard — so a ducked bass stays ducked in its stem and
  2064. // the stems add up to the mix. Those inserts (with their own sources and keys) are soloed too, and their routes out
  2065. // of that set are cut, so nothing of them reaches the Master. (Until 0.1.27 they were silenced: no ducking.)
  2066. {
  2067. const auto n = (int) out.mixer.size();
  2068. auto feedersOf = [&out, n] (int u) {
  2069. std::vector<int> f;
  2070. for (int src = 1; src < n; ++src)
  2071. {
  2072. if (src == u)
  2073. continue;
  2074. auto feeds = out.routes (src, u);
  2075. for (const auto& fx : out.mixer[(std::size_t) src].effects)
  2076. for (int o = 0; o < maxSlotSends && ! feeds; ++o)
  2077. feeds = slotSendTarget (fx, o) == u;
  2078. for (const auto& tap : fruitySendsOf (out, src))
  2079. feeds = feeds || tap.target == u;
  2080. if (feeds)
  2081. f.push_back (src);
  2082. }
  2083. return f;
  2084. };
  2085. auto keysOf = [&out, n] (int u) {
  2086. std::vector<int> k;
  2087. for (const auto& fx : out.mixer[(std::size_t) u].effects)
  2088. {
  2089. const auto c = slotConnections (out, u, fx);
  2090. for (const auto source : { fx.sidechain, fx.sidechain2, c.routed ? c.mainSource : -1, c.routed ? c.sideSource : -1 })
  2091. if (source > 0 && source < n && source != u)
  2092. k.push_back (source);
  2093. }
  2094. return k;
  2095. };
  2096. const auto heard = out.soloAudible();
  2097. // the keys of whatever the stem hears that feeds the insert, then everything that reaches those keys
  2098. std::vector<char> inSet ((std::size_t) n, 0);
  2099. std::vector<int> stack;
  2100. for (int u = 1; u < n; ++u)
  2101. if (heard[(std::size_t) u])
  2102. for (const auto k : keysOf (u))
  2103. if (! heard[(std::size_t) k] && ! inSet[(std::size_t) k])
  2104. {
  2105. inSet[(std::size_t) k] = 1;
  2106. stack.push_back (k);
  2107. }
  2108. while (! stack.empty())
  2109. {
  2110. const auto u = stack.back();
  2111. stack.pop_back();
  2112. auto more = feedersOf (u);
  2113. const auto k = keysOf (u);
  2114. more.insert (more.end(), k.begin(), k.end());
  2115. for (const auto src : more)
  2116. if (! inSet[(std::size_t) src] && ! heard[(std::size_t) src])
  2117. {
  2118. inSet[(std::size_t) src] = 1;
  2119. stack.push_back (src);
  2120. }
  2121. }
  2122. if (std::any_of (inSet.begin(), inSet.end(), [] (char c) { return c != 0; }))
  2123. {
  2124. for (int u = 1; u < n; ++u)
  2125. if (inSet[(std::size_t) u])
  2126. {
  2127. auto& m = out.mixer[(std::size_t) u];
  2128. m.solo = true;
  2129. m.soloSources = true;
  2130. }
  2131. // the newly heard inserts send nowhere outside the keys' set (not to the Master, not into the stem's own
  2132. // path: the insert and its sources stay as they were)
  2133. for (int pass = 0; pass < 4; ++pass)
  2134. {
  2135. const auto now = out.soloAudible();
  2136. auto changed = false;
  2137. for (int u = 1; u < n; ++u)
  2138. {
  2139. if (! now[(std::size_t) u] || heard[(std::size_t) u])
  2140. continue;
  2141. auto& m = out.mixer[(std::size_t) u];
  2142. changed = changed || m.toMaster;
  2143. m.toMaster = false;
  2144. const auto before = m.sends.size();
  2145. m.sends.erase (std::remove_if (m.sends.begin(), m.sends.end(),
  2146. [&inSet, n] (const MixerSend& s) { return s.target <= 0 || s.target >= n || ! inSet[(std::size_t) s.target]; }),
  2147. m.sends.end());
  2148. changed = changed || m.sends.size() != before;
  2149. }
  2150. if (! changed)
  2151. break;
  2152. }
  2153. }
  2154. }
  2155. // the Master neutral: the render plays through the song's Master again (Render to audio), so nothing of it may be in
  2156. // the file — effects, fader, pan, separation, phase / swap, EQ and its automation (round 186b, as StandIns' stems)
  2157. auto& master = out.mixer[0];
  2158. master.effects.clear();
  2159. master.volume = unityFader;
  2160. master.pan = 0.0f;
  2161. master.muted = false;
  2162. master.stereo = 0.0f;
  2163. master.invertPhase = master.swapChannels = false;
  2164. master.eq = {};
  2165. auto onMaster = [] (const AutomationTarget& t) { return refs::targetsInsert (t) && t.index == 0; };
  2166. for (auto& a : out.automations)
  2167. if (onMaster (a.target))
  2168. a.target = {};
  2169. for (auto& p : out.patterns)
  2170. p.events.erase (std::remove_if (p.events.begin(), p.events.end(), [&] (const PatternEvents& lane) { return onMaster (lane.target); }),
  2171. p.events.end());
  2172. out.initialValues.erase (std::remove_if (out.initialValues.begin(), out.initialValues.end(),
  2173. [&] (const Song::InitialValue& v) { return onMaster (v.target); }),
  2174. out.initialValues.end());
  2175. out.mode = PlayMode::song;
  2176. return out;
  2177. }
  2178. int applyBounce (Song& song, int track, const std::string& samplePath, std::int64_t length)
  2179. {
  2180. if (track <= 0 || track >= (int) song.mixer.size() || (int) song.mixer.size() >= maxMixerTracks)
  2181. return -1;
  2182. auto& original = song.mixer[(std::size_t) track];
  2183. MixerTrack copy;
  2184. copy.name = original.name + " (audio)";
  2185. copy.toMaster = original.toMaster;
  2186. copy.masterLevel = original.masterLevel;
  2187. copy.sends = original.sends;
  2188. original.muted = true;
  2189. song.mixer.push_back (copy);
  2190. const auto newTrack = (int) song.mixer.size() - 1;
  2191. ChannelDef c;
  2192. c.name = copy.name;
  2193. c.instrument = InstrumentKind::audioClip;
  2194. c.sampler.declickMode = audioClipDeclickMode; // FL's AudioTrack.fst
  2195. c.samplePath = samplePath;
  2196. c.mixerTrack = newTrack;
  2197. c.volume = audioClipUnityVolume; // the render plays at the level of what it replaces (1.0 was +5.18 dB, round 186b)
  2198. song.channels.push_back (c);
  2199. int lane = 0;
  2200. for (const auto& clip : song.playlist)
  2201. lane = std::max (lane, clip.track + 1);
  2202. Clip clip;
  2203. clip.kind = ClipKind::audio;
  2204. clip.channel = (int) song.channels.size() - 1;
  2205. clip.track = lane;
  2206. clip.length = length;
  2207. song.playlist.push_back (clip);
  2208. return newTrack;
  2209. }
  2210. Song Song::makeDefault()
  2211. {
  2212. Song song;
  2213. song.mixer = defaultMixer();
  2214. auto channel = [] (const char* name, InstrumentKind kind, float volume, float pan) {
  2215. ChannelDef c;
  2216. c.name = name;
  2217. c.instrument = kind;
  2218. c.volume = volume;
  2219. c.pan = pan;
  2220. return c;
  2221. };
  2222. song.channels = {
  2223. channel ("Kick", InstrumentKind::kick, 0.9f, 0.0f),
  2224. channel ("Clap", InstrumentKind::clap, 0.8f, 0.0f),
  2225. channel ("Hat", InstrumentKind::hat, 0.7f, 0.1f),
  2226. channel ("Snare", InstrumentKind::snare, 0.8f, 0.0f),
  2227. channel ("Synth", InstrumentKind::synth, 0.78f, 0.0f),
  2228. };
  2229. for (std::size_t i = 0; i < song.channels.size(); ++i)
  2230. song.channels[i].mixerTrack = (int) i + 1;
  2231. // like FL's template: a limiter on Master (transparent up to -0.3 dB)
  2232. EffectSlot limiter;
  2233. limiter.kind = EffectKind::limiter;
  2234. limiter.params = { 11.7f / 12.0f, 0.0f, 0.5f };
  2235. song.mixer[0].effects.push_back (limiter);
  2236. auto& p = song.patterns.emplace_back();
  2237. p.name = "Pattern 1";
  2238. for (int step : { 0, 4, 8, 12 })
  2239. p.toggleStep (0, step);
  2240. for (int step : { 4, 12 })
  2241. p.toggleStep (1, step);
  2242. for (int step : { 2, 6, 10, 14 })
  2243. p.toggleStep (2, step);
  2244. return song;
  2245. }
  2246. int firstChannelWithNotes (const Song& song, int pattern) noexcept
  2247. {
  2248. if (pattern < 0 || pattern >= (int) song.patterns.size())
  2249. return -1;
  2250. int first = -1;
  2251. for (const auto& n : song.patterns[(std::size_t) pattern].notes)
  2252. if (n.channel >= 0 && n.channel < (int) song.channels.size() && (first < 0 || n.channel < first))
  2253. first = n.channel;
  2254. return first;
  2255. }
  2256. } // namespace lynx