Song.cpp 37 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126
  1. #include "core/Song.h"
  2. #include <algorithm>
  3. #include <iterator>
  4. #include <cmath>
  5. #include <functional>
  6. #include <limits>
  7. namespace lynx
  8. {
  9. void Pattern::sortNotes()
  10. {
  11. std::stable_sort (notes.begin(), notes.end(), [] (const Note& a, const Note& b) { return a.start < b.start; });
  12. }
  13. std::int64_t Pattern::effectiveLength (int beatsPerBar) const noexcept
  14. {
  15. if (lengthTicks > 0)
  16. return lengthTicks;
  17. const std::int64_t bar = (std::int64_t) ppq * std::max (1, beatsPerBar);
  18. std::int64_t end = 0;
  19. for (auto& n : notes)
  20. end = std::max (end, n.start + std::max<std::int64_t> (n.length, 1));
  21. return std::max<std::int64_t> (bar, (end + bar - 1) / bar * bar);
  22. }
  23. bool Pattern::hasStep (int channel, int step) const noexcept
  24. {
  25. const auto tick = (std::int64_t) step * ticksPerStep;
  26. return std::any_of (notes.begin(), notes.end(),
  27. [&] (const Note& n) { return n.channel == channel && n.start == tick; });
  28. }
  29. void Pattern::toggleStep (int channel, int step)
  30. {
  31. const auto tick = (std::int64_t) step * ticksPerStep;
  32. const auto it = std::find_if (notes.begin(), notes.end(),
  33. [&] (const Note& n) { return n.channel == channel && n.start == tick; });
  34. if (it != notes.end())
  35. {
  36. notes.erase (it);
  37. return;
  38. }
  39. Note n;
  40. n.start = tick;
  41. n.channel = channel;
  42. notes.push_back (n);
  43. sortNotes();
  44. }
  45. std::int64_t Song::songLength() const noexcept
  46. {
  47. const std::int64_t bar = (std::int64_t) ppq * std::max (1, beatsPerBar);
  48. std::int64_t end = 0;
  49. for (const auto& c : playlist)
  50. end = std::max (end, c.end());
  51. // an empty Playlist (e.g. recording the first take in Song mode) loops the current pattern's length, not one bar
  52. if (playlist.empty() && currentPattern >= 0 && currentPattern < (int) patterns.size())
  53. end = patterns[(std::size_t) currentPattern].effectiveLength (beatsPerBar);
  54. return std::max<std::int64_t> (bar, (end + bar - 1) / bar * bar);
  55. }
  56. void followPatternLengths (const std::vector<std::int64_t>& before, Song& song)
  57. {
  58. if (before.size() != song.patterns.size())
  59. return; // patterns added, removed or moved: their clips are handled by that edit
  60. for (std::size_t i = 0; i < before.size(); ++i)
  61. {
  62. const auto now = song.patterns[i].effectiveLength (song.beatsPerBar);
  63. if (now == before[i] || before[i] <= 0)
  64. continue;
  65. song.forEachClipList ([&] (std::vector<Clip>& clips) {
  66. for (auto& c : clips)
  67. if (c.kind == ClipKind::pattern && c.pattern == (int) i && c.offset == 0 && c.length == before[i])
  68. c.length = now;
  69. });
  70. }
  71. }
  72. std::vector<std::int64_t> patternLengths (const Song& song)
  73. {
  74. std::vector<std::int64_t> lengths;
  75. lengths.reserve (song.patterns.size());
  76. for (const auto& p : song.patterns)
  77. lengths.push_back (p.effectiveLength (song.beatsPerBar));
  78. return lengths;
  79. }
  80. void Song::removePattern (int index)
  81. {
  82. if (index < 0 || index >= (int) patterns.size())
  83. return;
  84. patterns.erase (patterns.begin() + index);
  85. forEachClipList ([index] (std::vector<Clip>& clips) {
  86. clips.erase (std::remove_if (clips.begin(), clips.end(),
  87. [index] (const Clip& c) { return c.kind == ClipKind::pattern && c.pattern == index; }),
  88. clips.end());
  89. for (auto& c : clips)
  90. if (c.kind == ClipKind::pattern && c.pattern > index)
  91. --c.pattern;
  92. });
  93. if (patterns.empty())
  94. patterns.emplace_back().name = "Pattern 1";
  95. currentPattern = std::clamp (currentPattern > index ? currentPattern - 1 : currentPattern, 0, (int) patterns.size() - 1);
  96. }
  97. std::vector<MixerTrack> Song::defaultMixer (int inserts)
  98. {
  99. std::vector<MixerTrack> mixer ((std::size_t) std::clamp (inserts + 1, 1, maxMixerTracks));
  100. mixer[0].name = "Master";
  101. for (std::size_t i = 1; i < mixer.size(); ++i)
  102. mixer[i].name = "Insert " + std::to_string (i);
  103. return mixer;
  104. }
  105. int Song::nextFreeInsert() const
  106. {
  107. for (int t = 1; t < (int) mixer.size(); ++t)
  108. if (std::none_of (channels.begin(), channels.end(), [t] (const ChannelDef& c) { return c.mixerTrack == t; }))
  109. return t;
  110. return std::max (0, (int) mixer.size() - 1);
  111. }
  112. void Song::removeChannel (int index)
  113. {
  114. if (index < 0 || index >= (int) channels.size())
  115. return;
  116. channels.erase (channels.begin() + index);
  117. for (auto& p : patterns)
  118. {
  119. p.notes.erase (std::remove_if (p.notes.begin(), p.notes.end(), [index] (const Note& n) { return n.channel == index; }),
  120. p.notes.end());
  121. for (auto& n : p.notes)
  122. if (n.channel > index)
  123. --n.channel;
  124. }
  125. forEachClipList ([index] (std::vector<Clip>& clips) {
  126. clips.erase (std::remove_if (clips.begin(), clips.end(),
  127. [index] (const Clip& c) { return c.kind == ClipKind::audio && c.channel == index; }),
  128. clips.end());
  129. for (auto& c : clips)
  130. if (c.kind == ClipKind::audio && c.channel > index)
  131. --c.channel;
  132. });
  133. forEachTarget ([index] (AutomationTarget& t) {
  134. const auto onChannel = t.kind == AutomationTargetKind::channelVolume || t.kind == AutomationTargetKind::channelPan
  135. || t.kind == AutomationTargetKind::channelParam;
  136. if (onChannel && t.index == index)
  137. t.kind = AutomationTargetKind::none;
  138. else if (onChannel && t.index > index)
  139. --t.index;
  140. });
  141. for (auto& t : playlistTracks) // instrument tracks (REA round 146a)
  142. if (t.channel == index)
  143. {
  144. t.channel = -1;
  145. if (t.mode == PlaylistTrackMode::instrument)
  146. t.mode = PlaylistTrackMode::unassigned, t.mixerTrack = -1;
  147. }
  148. else if (t.channel > index)
  149. --t.channel;
  150. for (auto& automation : automations) // live source on a controller channel
  151. if (automation.source.channel == index)
  152. automation.source.channel = -1, automation.target.kind = AutomationTargetKind::none;
  153. else if (automation.source.channel > index)
  154. --automation.source.channel;
  155. removeDeadMidiLinks();
  156. }
  157. void Song::removeDeadMidiLinks()
  158. {
  159. midiLinks.erase (std::remove_if (midiLinks.begin(), midiLinks.end(),
  160. [] (const MidiLink& l) { return l.target.kind == AutomationTargetKind::none; }),
  161. midiLinks.end());
  162. initialValues.erase (std::remove_if (initialValues.begin(), initialValues.end(),
  163. [] (const InitialValue& v) { return v.target.kind == AutomationTargetKind::none; }),
  164. initialValues.end());
  165. }
  166. std::vector<MidiLink> linksWithGlobal (const std::vector<MidiLink>& project, const std::vector<MidiLink>& global)
  167. {
  168. auto out = project;
  169. for (const auto& g : global)
  170. {
  171. const auto overridden = std::any_of (project.begin(), project.end(), [&] (const MidiLink& p) {
  172. return p.target == g.target || (p.cc == g.cc && (p.channel < 0 || g.channel < 0 || p.channel == g.channel));
  173. });
  174. if (! overridden && g.target.kind != AutomationTargetKind::none)
  175. out.push_back (g);
  176. }
  177. return out;
  178. }
  179. int Song::findInitialValue (const AutomationTarget& target) const noexcept
  180. {
  181. for (int i = 0; i < (int) initialValues.size(); ++i)
  182. if (initialValues[(std::size_t) i].target == target)
  183. return i;
  184. return -1;
  185. }
  186. void Song::setInitialValue (const AutomationTarget& target, float value)
  187. {
  188. if (target.kind == AutomationTargetKind::none)
  189. return;
  190. value = std::clamp (value, 0.0f, 1.0f);
  191. if (const auto i = findInitialValue (target); i >= 0)
  192. initialValues[(std::size_t) i].value = value;
  193. else
  194. initialValues.push_back ({ target, value });
  195. }
  196. void Song::removeInitialValue (const AutomationTarget& target)
  197. {
  198. initialValues.erase (std::remove_if (initialValues.begin(), initialValues.end(),
  199. [&] (const InitialValue& v) { return v.target == target; }),
  200. initialValues.end());
  201. }
  202. void Song::applyInitialValues (const std::function<void (const AutomationTarget&, float)>& plugin)
  203. {
  204. for (const auto& v : initialValues)
  205. if (! setTargetValue (v.target, v.value) && plugin)
  206. plugin (v.target, v.value);
  207. }
  208. int fruitySendTarget (const EffectSlot& slot) noexcept
  209. {
  210. if (slot.kind == EffectKind::patcher) // a Patcher's first extra output (REA_rodada141)
  211. return ! slot.patcher.outputTracks.empty() && slot.patcher.outputTracks.front() > 0 ? slot.patcher.outputTracks.front() : -1;
  212. if (slot.kind != EffectKind::fruitySend)
  213. return -1;
  214. const auto track = (int) std::lround (std::clamp ((double) slot.params[3], 0.0, 1.0) * (maxMixerTracks - 1));
  215. return track > 0 ? track : -1;
  216. }
  217. std::vector<std::pair<int, int>> fruitySendsOf (const Song& song, int track)
  218. {
  219. std::vector<std::pair<int, int>> out;
  220. const auto n = (int) song.mixer.size();
  221. if (track <= 0 || track >= n)
  222. return out;
  223. const auto& slots = song.mixer[(std::size_t) track].effects;
  224. for (int s = 0; s < (int) slots.size() && s < maxEffectSlots; ++s)
  225. if (const auto target = fruitySendTarget (slots[(std::size_t) s]); target > 0 && target < n && target != track)
  226. out.emplace_back (s, target);
  227. return out;
  228. }
  229. bool Song::routes (int from, int to) const noexcept
  230. {
  231. if (from <= 0 || from >= (int) mixer.size())
  232. return false;
  233. const auto& t = mixer[(std::size_t) from];
  234. if (to == 0)
  235. return t.toMaster;
  236. return std::any_of (t.sends.begin(), t.sends.end(), [to] (const MixerSend& s) { return s.target == to; });
  237. }
  238. float Song::routeLevel (int from, int to) const noexcept
  239. {
  240. if (! routes (from, to))
  241. return 0.0f;
  242. const auto& t = mixer[(std::size_t) from];
  243. if (to == 0)
  244. return t.masterLevel;
  245. for (const auto& s : t.sends)
  246. if (s.target == to)
  247. return s.level;
  248. return 0.0f;
  249. }
  250. void Song::setRouteLevel (int from, int to, float level)
  251. {
  252. if (! routes (from, to))
  253. return;
  254. const auto v = std::clamp (level, 0.0f, maxFaderGain);
  255. auto& t = mixer[(std::size_t) from];
  256. if (to == 0)
  257. t.masterLevel = v;
  258. else
  259. for (auto& s : t.sends)
  260. if (s.target == to)
  261. s.level = v;
  262. }
  263. bool Song::canRoute (int from, int to) const
  264. {
  265. const auto n = (int) mixer.size();
  266. if (from <= 0 || from >= n || to < 0 || to >= n || from == to)
  267. return false;
  268. if (to == 0)
  269. return true;
  270. // cycle if `from` is already reachable from `to`
  271. std::vector<int> stack { to };
  272. std::vector<bool> seen ((std::size_t) n, false);
  273. while (! stack.empty())
  274. {
  275. const auto t = stack.back();
  276. stack.pop_back();
  277. if (t == from)
  278. return false;
  279. if (seen[(std::size_t) t])
  280. continue;
  281. seen[(std::size_t) t] = true;
  282. for (const auto& s : mixer[(std::size_t) t].sends)
  283. if (s.target > 0 && s.target < n)
  284. stack.push_back (s.target);
  285. for (const auto& fx : mixer[(std::size_t) t].effects)
  286. if (const auto target = fruitySendTarget (fx); target > 0 && target < n)
  287. stack.push_back (target);
  288. }
  289. return true;
  290. }
  291. void Song::setRoute (int from, int to, bool enabled, float level)
  292. {
  293. if (from <= 0 || from >= (int) mixer.size() || to < 0 || to >= (int) mixer.size())
  294. return;
  295. auto& t = mixer[(std::size_t) from];
  296. if (to == 0)
  297. {
  298. t.toMaster = enabled;
  299. return;
  300. }
  301. auto it = std::find_if (t.sends.begin(), t.sends.end(), [to] (const MixerSend& s) { return s.target == to; });
  302. if (! enabled)
  303. {
  304. if (it != t.sends.end())
  305. t.sends.erase (it);
  306. return;
  307. }
  308. if (it != t.sends.end())
  309. it->level = std::clamp (level, 0.0f, maxFaderGain);
  310. else if (canRoute (from, to))
  311. t.sends.push_back ({ to, std::clamp (level, 0.0f, maxFaderGain) });
  312. }
  313. std::vector<int> Song::mixerOrder() const
  314. {
  315. const auto n = (int) mixer.size();
  316. std::vector<int> incoming ((std::size_t) std::max (0, n), 0);
  317. // edges: sends and sidechains (the sidechain source must be processed before whoever listens to it)
  318. std::vector<std::vector<int>> next ((std::size_t) std::max (0, n));
  319. for (int t = 1; t < n; ++t)
  320. {
  321. for (const auto& s : mixer[(std::size_t) t].sends)
  322. if (s.target > 0 && s.target < n)
  323. next[(std::size_t) t].push_back (s.target);
  324. for (const auto& fx : mixer[(std::size_t) t].effects) // Fruity Send slots: the destination comes after
  325. if (const auto target = fruitySendTarget (fx); target > 0 && target < n && target != t)
  326. next[(std::size_t) t].push_back (target);
  327. for (const auto& fx : mixer[(std::size_t) t].effects)
  328. for (const auto source : { fx.sidechain, fx.sidechain2 })
  329. if (source > 0 && source < n && source != t)
  330. next[(std::size_t) source].push_back (t);
  331. }
  332. for (int t = 1; t < n; ++t)
  333. for (const auto target : next[(std::size_t) t])
  334. ++incoming[(std::size_t) target];
  335. // Kahn: start with the tracks nothing feeds (in numeric order)
  336. std::vector<int> order, ready;
  337. for (int t = n - 1; t >= 1; --t)
  338. if (incoming[(std::size_t) t] == 0)
  339. ready.push_back (t);
  340. while (! ready.empty())
  341. {
  342. const auto t = ready.back();
  343. ready.pop_back();
  344. order.push_back (t);
  345. for (const auto target : next[(std::size_t) t])
  346. if (--incoming[(std::size_t) target] == 0)
  347. {
  348. // keep numeric order among those that become ready together
  349. auto pos = std::upper_bound (ready.begin(), ready.end(), target, std::greater<int>());
  350. ready.insert (pos, target);
  351. }
  352. }
  353. // cycle (corrupt file): the leftovers go at the end, without the sends that close the cycle
  354. for (int t = 1; t < n; ++t)
  355. if (std::find (order.begin(), order.end(), t) == order.end())
  356. order.push_back (t);
  357. return order;
  358. }
  359. std::vector<bool> Song::soloAudible() const
  360. {
  361. const auto n = mixer.size();
  362. std::vector<bool> audible (n, true);
  363. std::vector<int> soloed;
  364. for (std::size_t t = 1; t < n; ++t)
  365. if (mixer[t].solo)
  366. soloed.push_back ((int) t);
  367. if (soloed.empty())
  368. return audible;
  369. std::fill (audible.begin(), audible.end(), false);
  370. if (n > 0)
  371. audible[0] = true;
  372. // downstream: the signal path from the soloed tracks to Master
  373. std::vector<int> stack = soloed;
  374. while (! stack.empty())
  375. {
  376. const auto t = stack.back();
  377. stack.pop_back();
  378. if (audible[(std::size_t) t])
  379. continue;
  380. audible[(std::size_t) t] = true;
  381. for (const auto& s : mixer[(std::size_t) t].sends)
  382. if (s.target > 0 && s.target < (int) n)
  383. stack.push_back (s.target);
  384. for (const auto& fx : mixer[(std::size_t) t].effects)
  385. if (const auto target = fruitySendTarget (fx); target > 0 && target < (int) n)
  386. stack.push_back (target);
  387. }
  388. // upstream: whoever feeds the soloed tracks
  389. std::vector<bool> feeds (n, false);
  390. stack = soloed;
  391. while (! stack.empty())
  392. {
  393. const auto t = stack.back();
  394. stack.pop_back();
  395. for (std::size_t src = 1; src < n; ++src)
  396. if (! feeds[src]
  397. && (routes ((int) src, t)
  398. || std::any_of (mixer[src].effects.begin(), mixer[src].effects.end(),
  399. [t] (const EffectSlot& fx) { return fruitySendTarget (fx) == t; })))
  400. {
  401. feeds[src] = true;
  402. audible[src] = true;
  403. stack.push_back ((int) src);
  404. }
  405. }
  406. return audible;
  407. }
  408. void Song::swapEffectSlots (int track, int a, int b)
  409. {
  410. if (track < 0 || track >= (int) mixer.size())
  411. return;
  412. auto& fx = mixer[(std::size_t) track].effects;
  413. if (a < 0 || b < 0 || a >= (int) fx.size() || b >= (int) fx.size())
  414. return;
  415. std::swap (fx[(std::size_t) a], fx[(std::size_t) b]);
  416. for (auto& automation : automations)
  417. if (automation.source.track == track)
  418. automation.source.slot = automation.source.slot == a ? b : automation.source.slot == b ? a : automation.source.slot;
  419. forEachTarget ([track, a, b] (AutomationTarget& t) {
  420. if ((t.kind == AutomationTargetKind::effectParam || t.kind == AutomationTargetKind::effectMix) && t.index == track)
  421. t.slot = t.slot == a ? b : t.slot == b ? a : t.slot;
  422. });
  423. }
  424. void Song::removeEffectSlot (int track, int slot)
  425. {
  426. if (track < 0 || track >= (int) mixer.size() || slot < 0 || slot >= (int) mixer[(std::size_t) track].effects.size())
  427. return;
  428. auto& fx = mixer[(std::size_t) track].effects;
  429. fx.erase (fx.begin() + slot);
  430. for (auto& automation : automations)
  431. if (automation.source.track == track)
  432. {
  433. if (automation.source.slot == slot)
  434. automation.source.track = -1, automation.target.kind = AutomationTargetKind::none; // the source is gone
  435. else if (automation.source.slot > slot)
  436. --automation.source.slot;
  437. }
  438. forEachTarget ([track, slot] (AutomationTarget& t) {
  439. if ((t.kind == AutomationTargetKind::effectParam || t.kind == AutomationTargetKind::effectMix) && t.index == track)
  440. {
  441. if (t.slot == slot)
  442. t.kind = AutomationTargetKind::none;
  443. else if (t.slot > slot)
  444. --t.slot;
  445. }
  446. });
  447. removeDeadMidiLinks();
  448. }
  449. void Song::removeAutomation (int index)
  450. {
  451. if (index < 0 || index >= (int) automations.size())
  452. return;
  453. automations.erase (automations.begin() + index);
  454. forEachClipList ([index] (std::vector<Clip>& clips) {
  455. clips.erase (std::remove_if (clips.begin(), clips.end(),
  456. [index] (const Clip& c) { return c.kind == ClipKind::automation && c.automation == index; }),
  457. clips.end());
  458. for (auto& c : clips)
  459. if (c.kind == ClipKind::automation && c.automation > index)
  460. --c.automation;
  461. });
  462. }
  463. std::vector<Marker>& Song::markers()
  464. {
  465. if (arrangements.empty())
  466. arrangements.push_back ({ "Arrangement 1", {}, 0, 0, {} });
  467. return arrangements[(std::size_t) std::clamp (currentArrangement, 0, (int) arrangements.size() - 1)].markers;
  468. }
  469. const std::vector<Marker>& Song::markers() const
  470. {
  471. static const std::vector<Marker> none;
  472. return arrangements.empty() ? none : arrangements[(std::size_t) std::clamp (currentArrangement, 0, (int) arrangements.size() - 1)].markers;
  473. }
  474. void Song::addMarker (Marker marker)
  475. {
  476. auto& list = markers();
  477. const auto at = std::upper_bound (list.begin(), list.end(), marker.tick, [] (std::int64_t t, const Marker& m) { return t < m.tick; });
  478. list.insert (at, std::move (marker));
  479. }
  480. std::vector<Bar> Song::barsBetween (std::int64_t from, std::int64_t to) const
  481. {
  482. std::vector<Bar> bars;
  483. auto barLength = [] (int numerator, int denominator) {
  484. return std::max<std::int64_t> (1, (std::int64_t) ppq * 4 * std::max (1, numerator) / std::max (1, denominator));
  485. };
  486. Bar bar { 0, barLength (beatsPerBar, 4), 1 };
  487. const auto& list = markers();
  488. std::size_t next = 0;
  489. while (bar.tick < to)
  490. {
  491. // time signature changes falling at the start of this bar apply to it
  492. while (next < list.size() && (! list[next].isSignature() || list[next].tick <= bar.tick))
  493. {
  494. if (list[next].isSignature())
  495. bar.length = barLength (list[next].numerator, list[next].denominator);
  496. ++next;
  497. }
  498. // the next change cuts this bar short and starts a new one there
  499. const auto end = next < list.size() ? std::min (bar.tick + bar.length, list[next].tick) : bar.tick + bar.length;
  500. if (end > from)
  501. bars.push_back ({ bar.tick, end - bar.tick, bar.number });
  502. bar = { end, bar.length, bar.number + 1 };
  503. // no changes ahead: the rest is arithmetic (avoids walking bar by bar up to `from`)
  504. if (bar.tick < from && next >= list.size())
  505. {
  506. const auto skip = (from - bar.tick) / bar.length;
  507. bar.tick += skip * bar.length;
  508. bar.number += (int) skip;
  509. }
  510. }
  511. return bars;
  512. }
  513. Bar Song::barAt (std::int64_t tick) const
  514. {
  515. const auto bars = barsBetween (std::max<std::int64_t> (0, tick), std::max<std::int64_t> (0, tick) + 1);
  516. return bars.empty() ? Bar { 0, (std::int64_t) ppq * std::max (1, beatsPerBar), 1 } : bars.front();
  517. }
  518. void Song::selectArrangement (int index)
  519. {
  520. if (arrangements.empty())
  521. arrangements.push_back ({ "Arrangement 1", {}, 0, 0, {} });
  522. currentArrangement = std::clamp (currentArrangement, 0, (int) arrangements.size() - 1);
  523. index = std::clamp (index, 0, (int) arrangements.size() - 1);
  524. if (index == currentArrangement)
  525. return;
  526. auto& from = arrangements[(std::size_t) currentArrangement];
  527. from.clips = std::move (playlist);
  528. from.loopStart = loopStart;
  529. from.loopEnd = loopEnd;
  530. auto& to = arrangements[(std::size_t) index];
  531. playlist = std::move (to.clips);
  532. to.clips.clear();
  533. loopStart = to.loopStart;
  534. loopEnd = to.loopEnd;
  535. currentArrangement = index;
  536. }
  537. int Song::addArrangement (const std::string& name, bool copyCurrent)
  538. {
  539. Arrangement a;
  540. a.name = name;
  541. if (copyCurrent)
  542. {
  543. a.clips = playlist;
  544. a.loopStart = loopStart;
  545. a.loopEnd = loopEnd;
  546. a.markers = markers();
  547. }
  548. arrangements.push_back (std::move (a));
  549. selectArrangement ((int) arrangements.size() - 1);
  550. return currentArrangement;
  551. }
  552. void Song::removeArrangement (int index)
  553. {
  554. if (arrangements.size() <= 1 || index < 0 || index >= (int) arrangements.size())
  555. return;
  556. if (index == currentArrangement)
  557. selectArrangement (index == 0 ? 1 : index - 1);
  558. arrangements.erase (arrangements.begin() + index);
  559. if (currentArrangement > index)
  560. --currentArrangement;
  561. }
  562. float Song::targetValue (const AutomationTarget& t) const noexcept
  563. {
  564. const auto validChannel = t.index >= 0 && t.index < (int) channels.size();
  565. const auto validTrack = t.index >= 0 && t.index < (int) mixer.size();
  566. switch (t.kind)
  567. {
  568. case AutomationTargetKind::channelVolume: return validChannel ? channels[(std::size_t) t.index].volume : -1.0f;
  569. case AutomationTargetKind::channelPan: return validChannel ? (channels[(std::size_t) t.index].pan + 1.0f) * 0.5f : -1.0f;
  570. case AutomationTargetKind::mixerVolume: return validTrack ? mixer[(std::size_t) t.index].volume : -1.0f;
  571. case AutomationTargetKind::mixerPan: return validTrack ? (mixer[(std::size_t) t.index].pan + 1.0f) * 0.5f : -1.0f;
  572. case AutomationTargetKind::effectParam:
  573. if (validTrack && t.slot >= 0 && t.slot < (int) mixer[(std::size_t) t.index].effects.size()
  574. && mixer[(std::size_t) t.index].effects[(std::size_t) t.slot].kind != EffectKind::plugin && t.param >= 0
  575. && t.param < maxEffectParams)
  576. return mixer[(std::size_t) t.index].effects[(std::size_t) t.slot].params[(std::size_t) t.param];
  577. return validTrack ? 0.5f : -1.0f; // plugin parameter: the value lives in the plugin
  578. case AutomationTargetKind::channelParam: return validChannel ? 0.5f : -1.0f;
  579. case AutomationTargetKind::effectMix:
  580. return validTrack && t.slot >= 0 && t.slot < (int) mixer[(std::size_t) t.index].effects.size()
  581. ? mixer[(std::size_t) t.index].effects[(std::size_t) t.slot].mix
  582. : -1.0f;
  583. case AutomationTargetKind::tempo: return valueFromTempo (bpm);
  584. case AutomationTargetKind::none: break;
  585. }
  586. return -1.0f;
  587. }
  588. bool Song::setTargetValue (const AutomationTarget& t, float v) noexcept
  589. {
  590. v = std::clamp (v, 0.0f, 1.0f);
  591. const auto validChannel = t.index >= 0 && t.index < (int) channels.size();
  592. const auto validTrack = t.index >= 0 && t.index < (int) mixer.size();
  593. switch (t.kind)
  594. {
  595. case AutomationTargetKind::channelVolume: if (! validChannel) return false; channels[(std::size_t) t.index].volume = v; return true;
  596. case AutomationTargetKind::channelPan: if (! validChannel) return false; channels[(std::size_t) t.index].pan = v * 2.0f - 1.0f; return true;
  597. case AutomationTargetKind::mixerVolume: if (! validTrack) return false; mixer[(std::size_t) t.index].volume = v; return true;
  598. case AutomationTargetKind::mixerPan: if (! validTrack) return false; mixer[(std::size_t) t.index].pan = v * 2.0f - 1.0f; return true;
  599. case AutomationTargetKind::tempo: bpm = tempoFromValue (v); return true;
  600. case AutomationTargetKind::effectMix:
  601. if (! validTrack || t.slot < 0 || t.slot >= (int) mixer[(std::size_t) t.index].effects.size())
  602. return false;
  603. mixer[(std::size_t) t.index].effects[(std::size_t) t.slot].mix = v;
  604. return true;
  605. case AutomationTargetKind::effectParam:
  606. if (validTrack && t.slot >= 0 && t.slot < (int) mixer[(std::size_t) t.index].effects.size()
  607. && mixer[(std::size_t) t.index].effects[(std::size_t) t.slot].kind != EffectKind::plugin && t.param >= 0
  608. && t.param < maxEffectParams)
  609. {
  610. mixer[(std::size_t) t.index].effects[(std::size_t) t.slot].params[(std::size_t) t.param] = v;
  611. return true;
  612. }
  613. return false;
  614. case AutomationTargetKind::channelParam:
  615. case AutomationTargetKind::none: break;
  616. }
  617. return false;
  618. }
  619. float Song::automationValueAt (int index, double tick) const
  620. {
  621. if (index < 0 || index >= (int) automations.size())
  622. return std::numeric_limits<float>::quiet_NaN();
  623. std::vector<const Clip*> clips;
  624. for (const auto& c : playlist)
  625. if (c.kind == ClipKind::automation && c.automation == index && c.length > 0 && ! c.muted && ! isTrackMuted (c.track))
  626. clips.push_back (&c);
  627. if (clips.empty())
  628. return std::numeric_limits<float>::quiet_NaN();
  629. std::stable_sort (clips.begin(), clips.end(), [] (const Clip* a, const Clip* b) { return a->start < b->start; });
  630. const auto& automation = automations[(std::size_t) index];
  631. const Clip* before = nullptr;
  632. // same rule as playback: inside a clip the curve; between clips the last value; before, the first
  633. for (const auto* c : clips)
  634. {
  635. if (tick < (double) c->start)
  636. break;
  637. if (tick < (double) c->end())
  638. return automation.valueAt (tick - (double) c->start + (double) c->offset);
  639. before = c;
  640. }
  641. if (before != nullptr)
  642. return automation.valueAt ((double) (before->length + before->offset));
  643. return automation.valueAt ((double) clips.front()->offset);
  644. }
  645. double Song::tempoAt (double tick) const
  646. {
  647. if (mode != PlayMode::song)
  648. return bpm;
  649. for (int i = (int) automations.size() - 1; i >= 0; --i) // the last tempo automation wins
  650. if (automations[(std::size_t) i].target.kind == AutomationTargetKind::tempo)
  651. if (const auto v = automationValueAt (i, tick); ! std::isnan (v))
  652. return tempoFromValue (v);
  653. return bpm;
  654. }
  655. double Song::secondsForTicks (std::int64_t ticks) const
  656. {
  657. const auto hasTempo = mode == PlayMode::song
  658. && std::any_of (automations.begin(), automations.end(),
  659. [] (const Automation& a) { return a.target.kind == AutomationTargetKind::tempo; });
  660. if (! hasTempo)
  661. return (double) ticks * 60.0 / (std::max (1.0, bpm) * ppq);
  662. // integrate in 1/16 steps (playback changes tempo block by block; the difference is minimal)
  663. double seconds = 0.0;
  664. constexpr std::int64_t step = ticksPerStep;
  665. for (std::int64_t t = 0; t < ticks; t += step)
  666. {
  667. const auto n = std::min (step, ticks - t);
  668. seconds += (double) n * 60.0 / (std::max (1.0, tempoAt ((double) t)) * ppq);
  669. }
  670. return seconds;
  671. }
  672. float Automation::mapLive (float v) const noexcept
  673. {
  674. v = std::clamp (v, 0.0f, 1.0f);
  675. if (curve.size() < 2)
  676. return v;
  677. const auto x = v * (float) (curve.size() - 1);
  678. const auto i = std::min ((std::size_t) x, curve.size() - 2);
  679. const auto f = x - (float) i;
  680. return std::clamp (curve[i] + (curve[i + 1] - curve[i]) * f, 0.0f, 1.0f);
  681. }
  682. float PatternEvents::valueAt (double tick) const noexcept
  683. {
  684. if (events.empty())
  685. return 0.5f;
  686. // the last event at or before `tick`
  687. auto it = std::upper_bound (events.begin(), events.end(), tick, [] (double t, const PatternEvent& e) { return t < (double) e.tick; });
  688. return it == events.begin() ? events.front().value : std::prev (it)->value;
  689. }
  690. float Automation::valueAt (double tick) const noexcept
  691. {
  692. if (points.empty())
  693. return 0.5f;
  694. if (tick <= (double) points.front().tick)
  695. return points.front().value;
  696. for (std::size_t i = 1; i < points.size(); ++i)
  697. {
  698. const auto& a = points[i - 1];
  699. const auto& b = points[i];
  700. if (tick < (double) b.tick)
  701. {
  702. const auto span = (double) std::max<std::int64_t> (1, b.tick - a.tick);
  703. auto t = (float) ((tick - (double) a.tick) / span);
  704. // tension: curve exponent (positive = rises slowly then accelerates)
  705. if (a.tension != 0.0f)
  706. t = std::pow (t, std::pow (2.0f, a.tension * 3.0f));
  707. return a.value + (b.value - a.value) * t;
  708. }
  709. }
  710. return points.back().value;
  711. }
  712. std::int64_t Automation::length() const noexcept
  713. {
  714. return points.empty() ? 1 : std::max<std::int64_t> (1, points.back().tick);
  715. }
  716. Clip splitClip (Clip& clip, std::int64_t tick)
  717. {
  718. Clip rest = clip;
  719. const auto head = std::clamp<std::int64_t> (tick - clip.start, 1, std::max<std::int64_t> (1, clip.length - 1));
  720. clip.length = head;
  721. rest.start = clip.start + head;
  722. rest.offset = clip.offset + head;
  723. rest.length -= head;
  724. return rest;
  725. }
  726. double TrackEq::peakQ (float w) noexcept
  727. {
  728. return 0.0999 * (std::pow (1001.0, std::clamp ((double) w, 0.0, 1.0)) - 1.0) + 0.1;
  729. }
  730. double TrackEq::shelfSlope (float w) noexcept
  731. {
  732. return 1.9 * std::clamp ((double) w, 0.0, 1.0) + 0.1;
  733. }
  734. std::int64_t swingDelay (std::int64_t start, float swing, float channelMix) noexcept
  735. {
  736. if (swing <= 0.0f || channelMix <= 0.0f)
  737. return 0;
  738. constexpr std::int64_t s = ticksPerStep;
  739. const auto k = (start + s / 2) / s;
  740. if (k % 2 == 0)
  741. return 0;
  742. const auto w = s - 2 * std::abs (start - k * s);
  743. return (std::int64_t) std::llround ((double) w * std::clamp (swing, 0.0f, 1.0f) * std::clamp (channelMix, 0.0f, 1.0f) * 0.5);
  744. }
  745. bool PatcherDoc::operator== (const PatcherDoc& o) const
  746. {
  747. return nodes == o.nodes && wires == o.wires && published == o.published && inputX == o.inputX && inputY == o.inputY && outputX == o.outputX && outputY == o.outputY
  748. && outputTracks == o.outputTracks;
  749. }
  750. bool PatchNode::BusHead::operator== (const BusHead& o) const { return bus == o.bus && head == o.head && gain == o.gain; }
  751. bool PatchNode::operator== (const PatchNode& o) const
  752. {
  753. return generator == o.generator && label == o.label && x == o.x && y == o.y && busHeads == o.busHeads
  754. && (generator ? channel == o.channel : effect == o.effect);
  755. }
  756. bool EffectSlot::operator== (const EffectSlot& o) const
  757. {
  758. if (kind != o.kind || enabled != o.enabled || params != o.params || mix != o.mix || ! (plugin == o.plugin) || sidechain != o.sidechain
  759. || sidechain2 != o.sidechain2 || state != o.state || samplePath != o.samplePath || ! (substituteFor == o.substituteFor)
  760. || presetName != o.presetName || abOther != o.abOther || abShowingB != o.abShowingB || branches.size() != o.branches.size()
  761. || links.size() != o.links.size() || ! (patcher == o.patcher))
  762. return false;
  763. for (std::size_t i = 0; i < branches.size(); ++i)
  764. if (branches[i].gain != o.branches[i].gain || branches[i].chain != o.branches[i].chain)
  765. return false;
  766. for (std::size_t i = 0; i < links.size(); ++i)
  767. {
  768. const auto& a = links[i];
  769. const auto& b = o.links[i];
  770. if (a.branch != b.branch || a.source != b.source || a.target != b.target || a.param != b.param || a.curve != b.curve)
  771. return false;
  772. }
  773. return true;
  774. }
  775. float channelGain (float volume) noexcept
  776. {
  777. const auto v = std::clamp (volume, 0.0f, 1.0f);
  778. return (std::pow (11.0f, v) - 1.0f) / 10.0f;
  779. }
  780. float faderGain (float position) noexcept
  781. {
  782. const auto v = std::clamp (position, 0.0f, 1.0f) * 1.25f;
  783. return (std::pow (11.0f, v) - 1.0f) / 10.0f;
  784. }
  785. float faderPosition (float gain) noexcept
  786. {
  787. if (! (gain > 0.0f))
  788. return 0.0f;
  789. return std::clamp ((float) (std::log (10.0 * (double) gain + 1.0) / std::log (11.0) / 1.25), 0.0f, 1.0f);
  790. }
  791. Song makeExportSong (const Song& song, bool wholeSong, std::int64_t tailTicks, std::int64_t& musicLength)
  792. {
  793. Song out = song;
  794. if (out.patterns.empty())
  795. out.patterns.emplace_back().name = "Pattern 1";
  796. if (! wholeSong || out.playlist.empty())
  797. {
  798. const auto index = std::clamp (out.currentPattern, 0, (int) out.patterns.size() - 1);
  799. Clip clip;
  800. clip.pattern = index;
  801. clip.length = out.patterns[(std::size_t) index].effectiveLength (out.beatsPerBar);
  802. out.playlist = { clip };
  803. musicLength = clip.length;
  804. }
  805. else
  806. {
  807. musicLength = 0;
  808. for (const auto& c : out.playlist)
  809. musicLength = std::max (musicLength, c.end());
  810. }
  811. // empty pattern in the tail: extends the song without playing anything. One extra bar of slack
  812. // because the last rendered block goes slightly past the end and must not wrap to the start.
  813. if (tailTicks > 0)
  814. {
  815. tailTicks += (std::int64_t) ppq * std::max (1, out.beatsPerBar);
  816. out.patterns.emplace_back().name = "(tail)";
  817. Clip tail;
  818. tail.pattern = (int) out.patterns.size() - 1;
  819. tail.start = musicLength;
  820. tail.length = tailTicks;
  821. out.playlist.push_back (tail);
  822. }
  823. out.mode = PlayMode::song;
  824. out.loopStart = out.loopEnd = 0; // export ignores the loop region
  825. return out;
  826. }
  827. Song makeBounceSong (const Song& song, int track)
  828. {
  829. Song out = song;
  830. if (track <= 0 || track >= (int) out.mixer.size())
  831. return out;
  832. for (auto& t : out.mixer)
  833. t.solo = false;
  834. auto& insert = out.mixer[(std::size_t) track];
  835. insert.sends.clear();
  836. insert.toMaster = true;
  837. insert.muted = false;
  838. insert.solo = true; // it and whatever feeds it are audible
  839. auto& master = out.mixer[0];
  840. master.effects.clear();
  841. master.volume = unityFader;
  842. master.pan = 0.0f;
  843. master.muted = false;
  844. out.mode = PlayMode::song;
  845. return out;
  846. }
  847. int applyBounce (Song& song, int track, const std::string& samplePath, std::int64_t length)
  848. {
  849. if (track <= 0 || track >= (int) song.mixer.size() || (int) song.mixer.size() >= maxMixerTracks)
  850. return -1;
  851. auto& original = song.mixer[(std::size_t) track];
  852. MixerTrack copy;
  853. copy.name = original.name + " (audio)";
  854. copy.toMaster = original.toMaster;
  855. copy.masterLevel = original.masterLevel;
  856. copy.sends = original.sends;
  857. original.muted = true;
  858. song.mixer.push_back (copy);
  859. const auto newTrack = (int) song.mixer.size() - 1;
  860. ChannelDef c;
  861. c.name = copy.name;
  862. c.instrument = InstrumentKind::audioClip;
  863. c.samplePath = samplePath;
  864. c.mixerTrack = newTrack;
  865. c.volume = 1.0f;
  866. song.channels.push_back (c);
  867. int lane = 0;
  868. for (const auto& clip : song.playlist)
  869. lane = std::max (lane, clip.track + 1);
  870. Clip clip;
  871. clip.kind = ClipKind::audio;
  872. clip.channel = (int) song.channels.size() - 1;
  873. clip.track = lane;
  874. clip.length = length;
  875. song.playlist.push_back (clip);
  876. return newTrack;
  877. }
  878. Song Song::makeDefault()
  879. {
  880. Song song;
  881. song.mixer = defaultMixer();
  882. auto channel = [] (const char* name, InstrumentKind kind, float volume, float pan) {
  883. ChannelDef c;
  884. c.name = name;
  885. c.instrument = kind;
  886. c.volume = volume;
  887. c.pan = pan;
  888. return c;
  889. };
  890. song.channels = {
  891. channel ("Kick", InstrumentKind::kick, 0.9f, 0.0f),
  892. channel ("Clap", InstrumentKind::clap, 0.8f, 0.0f),
  893. channel ("Hat", InstrumentKind::hat, 0.7f, 0.1f),
  894. channel ("Snare", InstrumentKind::snare, 0.8f, 0.0f),
  895. channel ("Synth", InstrumentKind::synth, 0.78f, 0.0f),
  896. };
  897. for (std::size_t i = 0; i < song.channels.size(); ++i)
  898. song.channels[i].mixerTrack = (int) i + 1;
  899. // like FL's template: a limiter on Master (transparent up to -0.3 dB)
  900. EffectSlot limiter;
  901. limiter.kind = EffectKind::limiter;
  902. limiter.params = { 11.7f / 12.0f, 0.0f, 0.5f };
  903. song.mixer[0].effects.push_back (limiter);
  904. auto& p = song.patterns.emplace_back();
  905. p.name = "Pattern 1";
  906. for (int step : { 0, 4, 8, 12 })
  907. p.toggleStep (0, step);
  908. for (int step : { 4, 12 })
  909. p.toggleStep (1, step);
  910. for (int step : { 2, 6, 10, 14 })
  911. p.toggleStep (2, step);
  912. return song;
  913. }
  914. } // namespace lynx