Scheduler.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380
  1. #include "core/Scheduler.h"
  2. #include <algorithm>
  3. #include <cmath>
  4. namespace lynx
  5. {
  6. void EventBuffer::add (const NoteEvent& e) noexcept
  7. {
  8. if (count < capacity)
  9. events[(std::size_t) count++] = e;
  10. else
  11. ++dropped;
  12. }
  13. void EventBuffer::sortByOffset() noexcept
  14. {
  15. // "off" before "on" on the same sample, so a repeated note isn't cut. A stable insertion sort in place: this runs
  16. // on the audio thread for every block with events, and std::stable_sort allocates a temporary buffer (round 160);
  17. // the events arrive nearly in order, so it is close to linear.
  18. const auto before = [] (const NoteEvent& a, const NoteEvent& b) {
  19. if (a.sampleOffset != b.sampleOffset)
  20. return a.sampleOffset < b.sampleOffset;
  21. return a.type != NoteEvent::Type::on && b.type == NoteEvent::Type::on;
  22. };
  23. for (int i = 1; i < count; ++i)
  24. {
  25. const auto e = events[(std::size_t) i];
  26. auto j = i;
  27. while (j > 0 && before (e, events[(std::size_t) j - 1]))
  28. {
  29. events[(std::size_t) j] = events[(std::size_t) j - 1];
  30. --j;
  31. }
  32. events[(std::size_t) j] = e;
  33. }
  34. }
  35. namespace
  36. {
  37. // The sample a tick falls on, as FL's sequencer places it: round(position in samples), ties to even (FLEngine
  38. // FUN_00d0ece0: the k-th tick is at round(Σ samples per tick), cvtsd2si; REA_rodada76 §5). Positions within 10⁻⁶ of a
  39. // half are taken as the exact tie the tick arithmetic rounds off.
  40. double flSampleOf (double samples) noexcept
  41. {
  42. const auto below = std::floor (samples);
  43. if (std::abs (samples - below - 0.5) < 1.0e-6)
  44. return std::fmod (below, 2.0) == 0.0 ? below : below + 1.0;
  45. return std::nearbyint (samples);
  46. }
  47. // Emits an event for each repetition of tick `t` (within the pattern) whose sample (FL's rounding) falls in the block
  48. // [start, end).
  49. void emitOccurrences (double t, std::int64_t loopLength, double start, double end, double tps, int numSamples,
  50. NoteEvent event, EventBuffer& out) noexcept
  51. {
  52. const auto len = (double) loopLength;
  53. const auto first = std::nearbyint (start / tps); // the block's first sample (start is a whole sample)
  54. // first repetition k with t + k*len >= start - one sample
  55. auto k = std::ceil ((start - tps - t) / len);
  56. for (auto tick = t + k * len; tick < end; tick += len)
  57. {
  58. const auto offset = flSampleOf (tick / tps) - first;
  59. if (offset < 0.0 || offset >= (double) numSamples)
  60. continue;
  61. event.sampleOffset = (int) offset;
  62. out.add (event);
  63. }
  64. }
  65. using NoteTiming = PlayedTiming;
  66. NoteTiming noteTiming (const Note& note, float swing, const ChannelDef* c) noexcept { return playedTiming (note, swing, c); }
  67. const ChannelDef* channelOf (const std::vector<ChannelDef>* channels, int channel) noexcept
  68. {
  69. return channels != nullptr && channel >= 0 && channel < (int) channels->size() ? &(*channels)[(std::size_t) channel] : nullptr;
  70. }
  71. } // namespace
  72. // FL's Misc › Time (REA round 146b [EXEC]): Shift delays a channel's notes (on and off), Gate cuts the long ones to its
  73. // length — not the porta notes when Full porta is on.
  74. PlayedTiming playedTiming (const Note& note, float swing, const ChannelDef* c) noexcept
  75. {
  76. PlayedTiming t;
  77. t.start = note.start + swingDelay (note.start, swing, c != nullptr ? c->swingMix : 1.0f);
  78. t.length = std::max<std::int64_t> (note.length, 1);
  79. if (c == nullptr)
  80. return t;
  81. if (c->misc.shiftBeats > 0.0f)
  82. t.start += (std::int64_t) std::llround ((double) c->misc.shiftBeats * ppq);
  83. if (c->misc.gateBeats > 0.0f)
  84. {
  85. const auto porta = (c->instrument == InstrumentKind::synth ? c->synth.porta : c->instrument == InstrumentKind::sampler && c->sampler.porta) != note.porta;
  86. if (! (porta && c->misc.fullPorta))
  87. t.length = std::min (t.length, std::max<std::int64_t> (1, (std::int64_t) std::llround ((double) c->misc.gateBeats * ppq)));
  88. }
  89. return t;
  90. }
  91. std::int64_t maxChannelShift (const std::vector<ChannelDef>& channels) noexcept
  92. {
  93. float beats = 0.0f;
  94. for (const auto& c : channels)
  95. beats = std::max (beats, c.misc.shiftBeats);
  96. return (std::int64_t) std::ceil ((double) beats * ppq);
  97. }
  98. void schedulePatternLoop (const Pattern& pattern,
  99. std::int64_t patternLength,
  100. double startTick,
  101. int numSamples,
  102. double tps,
  103. EventBuffer& out,
  104. float swing,
  105. const std::vector<ChannelDef>* channels,
  106. bool chase) noexcept
  107. {
  108. if (numSamples <= 0 || patternLength <= 0 || tps <= 0.0)
  109. return;
  110. const auto endTick = startTick + numSamples * tps;
  111. const auto position = std::fmod (startTick, (double) patternLength);
  112. for (const auto& note : pattern.notes)
  113. {
  114. if (note.start >= patternLength || note.muted)
  115. continue; // outside the loop / muted note
  116. NoteEvent on;
  117. on.type = NoteEvent::Type::on;
  118. on.channel = note.channel;
  119. on.key = note.key;
  120. on.velocity = note.velocity;
  121. on.pan = note.pan;
  122. on.cents = note.finePitch;
  123. on.porta = note.porta;
  124. on.modX = note.modX;
  125. on.modY = note.modY;
  126. on.release = note.release;
  127. on.colour = (std::int8_t) (note.colour & 15);
  128. const auto timing = noteTiming (note, swing, channelOf (channels, note.channel));
  129. const auto start = timing.start;
  130. if (note.slide)
  131. {
  132. on.type = NoteEvent::Type::slide;
  133. on.slideSamples = (float) ((double) std::max<std::int64_t> (note.length, 1) / tps);
  134. emitOccurrences ((double) start, patternLength, startTick, endTick, tps, numSamples, on, out);
  135. continue; // slide has no "off": the original note continues until its own end
  136. }
  137. emitOccurrences ((double) start, patternLength, startTick, endTick, tps, numSamples, on, out);
  138. if (chase && (double) start + tps <= position && (double) (start + timing.length) > position)
  139. {
  140. on.sampleOffset = 0; // a note crossing the start position ("Play truncated notes on transport")
  141. out.add (on);
  142. }
  143. NoteEvent off = on;
  144. off.type = NoteEvent::Type::off;
  145. off.velocity = 0.0f;
  146. const auto length = timing.length;
  147. emitOccurrences ((double) (start + length), patternLength, startTick, endTick, tps, numSamples, off, out);
  148. }
  149. out.sortByOffset();
  150. }
  151. ScheduleIndex makeScheduleIndex (const Song& song)
  152. {
  153. ScheduleIndex index;
  154. index.songLength = song.songLength();
  155. index.maxShift = maxChannelShift (song.channels);
  156. index.maxNoteLength.reserve (song.patterns.size());
  157. for (const auto& p : song.patterns)
  158. {
  159. std::int64_t longest = 0;
  160. for (const auto& n : p.notes)
  161. longest = std::max (longest, n.length);
  162. index.maxNoteLength.push_back (longest);
  163. }
  164. return index;
  165. }
  166. PlaybackLoop playbackLoop (bool songMode, double loopStart, double loopEnd, double songLength, double songStart) noexcept
  167. {
  168. if (! songMode)
  169. return {};
  170. if (loopEnd > loopStart)
  171. return { loopStart, loopEnd };
  172. if (songStart > 0.0 && songStart < songLength)
  173. return { songStart, songLength };
  174. return { 0.0, std::max (0.0, songLength) };
  175. }
  176. double hostPositionTick (const Song& song, double tick, std::int64_t songLength) noexcept
  177. {
  178. tick = std::max (0.0, tick);
  179. if (song.mode == PlayMode::song)
  180. return song.hasLoop() ? tick : std::fmod (tick, (double) std::max<std::int64_t> (1, songLength));
  181. if (song.patterns.empty())
  182. return tick;
  183. const auto& pattern = song.patterns[(std::size_t) std::clamp (song.currentPattern, 0, (int) song.patterns.size() - 1)];
  184. return std::fmod (tick, (double) std::max<std::int64_t> (1, pattern.effectiveLength (song.beatsPerBar)));
  185. }
  186. namespace
  187. {
  188. // One clip of the Playlist (or a performance-mode launch, played as a clip of its own), its events in the block.
  189. // [loopStart, loopEnd) = the block within the song loop of length `loop`.
  190. void scheduleClip (const Song& song, const Clip& clip, std::size_t clipIndex, double startTick, double endTick, int numSamples,
  191. double tps, std::int64_t loop, double loopStart, double loopEnd, bool resume, const ScheduleIndex* index,
  192. EventBuffer& out, bool chase = false) noexcept
  193. {
  194. auto overlaps = [&] (double from, double to) {
  195. return (from < loopEnd && to > loopStart) || (loopEnd > (double) loop && from < loopEnd - (double) loop);
  196. };
  197. const auto secondsPerTick = 60.0 / (std::max (song.bpm, 1.0) * ppq);
  198. if (clip.kind == ClipKind::audio)
  199. {
  200. if (clip.channel < 0 || clip.channel >= (int) song.channels.size() || clip.length <= 0)
  201. return;
  202. NoteEvent e;
  203. e.channel = clip.channel;
  204. e.key = audioClipKey (clipIndex);
  205. e.velocity = clip.gain;
  206. e.pan = clip.pan;
  207. e.fadeIn = (float) ((double) clip.effectiveFadeIn() / tps);
  208. e.fadeOut = (float) ((double) clip.effectiveFadeOut() / tps);
  209. e.fadeShape = (std::uint8_t) ((clip.crossfadeIn > 0 ? 1 : 0) | (clip.crossfadeOut > 0 ? 2 : 0));
  210. if (resume && loopStart > (double) clip.start && loopStart < (double) clip.end())
  211. {
  212. e.type = NoteEvent::Type::on;
  213. e.sampleOffset = 0;
  214. e.startSeconds = ((double) clip.offset + (double) clip.offsetFraction + loopStart - (double) clip.start) * secondsPerTick;
  215. e.clipElapsed = (float) ((loopStart - (double) clip.start) / tps);
  216. e.clipRemaining = (float) (((double) clip.end() - loopStart) / tps);
  217. out.add (e);
  218. }
  219. if (! overlaps ((double) clip.start, (double) clip.end() + 1.0))
  220. return;
  221. e.type = NoteEvent::Type::on;
  222. e.startSeconds = std::max (0.0, ((double) clip.offset + (double) clip.offsetFraction) * secondsPerTick);
  223. e.clipElapsed = 0.0f;
  224. e.clipRemaining = (float) ((double) clip.length / tps);
  225. emitOccurrences ((double) clip.start, loop, startTick, endTick, tps, numSamples, e, out);
  226. e.type = NoteEvent::Type::off;
  227. e.startSeconds = 0.0;
  228. emitOccurrences ((double) clip.end(), loop, startTick, endTick, tps, numSamples, e, out);
  229. return;
  230. }
  231. if (clip.kind != ClipKind::pattern || clip.pattern < 0 || clip.pattern >= (int) song.patterns.size() || clip.length <= 0)
  232. return;
  233. // one tick of slack to catch the "off" that falls exactly at the end of the clip
  234. if (! overlaps ((double) clip.start, (double) clip.end() + 1.0))
  235. return;
  236. const auto& notes = song.patterns[(std::size_t) clip.pattern].notes;
  237. auto first = notes.begin(), last = notes.end();
  238. // with the index and without the block wrapping around the end of the song: only the notes whose "on" or "off"
  239. // can fall in the block (swing delays by at most half a step)
  240. if (index != nullptr && loopEnd <= (double) loop && (std::size_t) clip.pattern < index->maxNoteLength.size())
  241. {
  242. const auto local = (double) (clip.offset - clip.start);
  243. const auto from = loopStart + local - (double) (ticksPerStep + index->maxNoteLength[(std::size_t) clip.pattern] + index->maxShift) - 1.0;
  244. const auto to = loopEnd + local + 1.0;
  245. first = std::lower_bound (notes.begin(), notes.end(), from, [] (const Note& n, double t) { return (double) n.start < t; });
  246. last = std::upper_bound (first, notes.end(), to, [] (double t, const Note& n) { return t < (double) n.start; });
  247. }
  248. for (auto it = first; it != last; ++it)
  249. {
  250. const auto& note = *it;
  251. if (note.muted || note.start >= clip.offset + clip.length)
  252. continue;
  253. const auto timing = noteTiming (note, song.swing, channelOf (&song.channels, note.channel));
  254. auto on = std::min (clip.start + (note.start - clip.offset) + (timing.start - note.start), clip.end() - 1);
  255. auto off = std::min (on + timing.length, clip.end());
  256. // FL's "Play truncated notes in clips" (FUN_010608a0): a note starting before the clip's offset keeps what is
  257. // left of it from the clip's start (dropped when nothing is left); off: dropped
  258. if (note.start < clip.offset)
  259. {
  260. const auto left = note.start + timing.length - clip.offset;
  261. if (! song.playTruncatedNotes || left < 1)
  262. continue;
  263. on = clip.start;
  264. off = std::min (clip.start + left, clip.end());
  265. }
  266. NoteEvent e;
  267. e.type = NoteEvent::Type::on;
  268. e.channel = note.channel;
  269. e.key = note.key;
  270. e.velocity = note.velocity;
  271. e.pan = note.pan;
  272. e.cents = note.finePitch;
  273. e.porta = note.porta;
  274. e.modX = note.modX;
  275. e.modY = note.modY;
  276. e.release = note.release;
  277. e.colour = (std::int8_t) (note.colour & 15);
  278. if (note.slide)
  279. {
  280. e.type = NoteEvent::Type::slide;
  281. e.slideSamples = (float) ((double) (off - on) / tps);
  282. emitOccurrences ((double) on, loop, startTick, endTick, tps, numSamples, e, out);
  283. continue;
  284. }
  285. emitOccurrences ((double) on, loop, startTick, endTick, tps, numSamples, e, out);
  286. if (chase && (double) on + tps <= loopStart && (double) off > loopStart)
  287. {
  288. e.sampleOffset = 0; // a note crossing the start position ("Play truncated notes on transport")
  289. out.add (e);
  290. }
  291. e.type = NoteEvent::Type::off;
  292. e.velocity = 0.0f;
  293. emitOccurrences ((double) off, loop, startTick, endTick, tps, numSamples, e, out);
  294. }
  295. }
  296. } // namespace
  297. void scheduleSingleClip (const Song& song, const Clip& clip, std::size_t clipIndex, double startTick, int numSamples, double tps,
  298. EventBuffer& out, const ScheduleIndex* index) noexcept
  299. {
  300. if (numSamples <= 0 || tps <= 0.0)
  301. return;
  302. const auto endTick = startTick + numSamples * tps;
  303. // a "loop" longer than anything played: the clip plays once, where it is
  304. const auto loop = (std::max<std::int64_t> ((std::int64_t) std::ceil (endTick), clip.end()) + 1) * 2;
  305. scheduleClip (song, clip, clipIndex, startTick, endTick, numSamples, tps, loop, startTick, endTick, false, index, out);
  306. }
  307. void scheduleSong (const Song& song, double startTick, int numSamples, double tps, EventBuffer& out, bool resume,
  308. const ScheduleIndex* index, bool wrap, bool chase) noexcept
  309. {
  310. if (numSamples <= 0 || tps <= 0.0 || song.playlist.empty())
  311. return;
  312. const auto endTick = startTick + numSamples * tps;
  313. auto loop = index != nullptr ? index->songLength : song.songLength();
  314. if (! wrap) // a "loop" longer than anything played: nothing starts over
  315. loop = std::max<std::int64_t> (loop, (std::int64_t) std::ceil (endTick) + 1) * 2;
  316. // Block window within the loop; if it crosses the end, it becomes two windows.
  317. const auto loopStart = std::fmod (startTick, (double) loop);
  318. const auto loopEnd = loopStart + (endTick - startTick);
  319. const auto zoneEnd = song.performanceZoneEnd();
  320. for (std::size_t clipIndex = 0; clipIndex < song.playlist.size(); ++clipIndex)
  321. {
  322. const auto& clip = song.playlist[clipIndex];
  323. if (clip.muted || song.isTrackMuted (clip.track))
  324. continue;
  325. if (clip.start < zoneEnd) // Performance mode: the zone's clips play only when launched (schedulePerformance)
  326. continue;
  327. scheduleClip (song, clip, clipIndex, startTick, endTick, numSamples, tps, loop, loopStart, loopEnd, resume, index, out, chase);
  328. }
  329. out.sortByOffset();
  330. }
  331. } // namespace lynx