Scheduler.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306
  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
  16. std::stable_sort (events.begin(), events.begin() + count, [] (const NoteEvent& a, const NoteEvent& b) {
  17. if (a.sampleOffset != b.sampleOffset)
  18. return a.sampleOffset < b.sampleOffset;
  19. return a.type != NoteEvent::Type::on && b.type == NoteEvent::Type::on;
  20. });
  21. }
  22. namespace
  23. {
  24. // The sample a tick falls on, as FL's sequencer places it: round(position in samples), ties to even (FLEngine
  25. // FUN_00d0ece0: the k-th tick is at round(Σ samples per tick), cvtsd2si; REA_rodada76 §5). Positions within 10⁻⁶ of a
  26. // half are taken as the exact tie the tick arithmetic rounds off.
  27. double flSampleOf (double samples) noexcept
  28. {
  29. const auto below = std::floor (samples);
  30. if (std::abs (samples - below - 0.5) < 1.0e-6)
  31. return std::fmod (below, 2.0) == 0.0 ? below : below + 1.0;
  32. return std::nearbyint (samples);
  33. }
  34. // Emits an event for each repetition of tick `t` (within the pattern) whose sample (FL's rounding) falls in the block
  35. // [start, end).
  36. void emitOccurrences (double t, std::int64_t loopLength, double start, double end, double tps, int numSamples,
  37. NoteEvent event, EventBuffer& out) noexcept
  38. {
  39. const auto len = (double) loopLength;
  40. const auto first = std::nearbyint (start / tps); // the block's first sample (start is a whole sample)
  41. // first repetition k with t + k*len >= start - one sample
  42. auto k = std::ceil ((start - tps - t) / len);
  43. for (auto tick = t + k * len; tick < end; tick += len)
  44. {
  45. const auto offset = flSampleOf (tick / tps) - first;
  46. if (offset < 0.0 || offset >= (double) numSamples)
  47. continue;
  48. event.sampleOffset = (int) offset;
  49. out.add (event);
  50. }
  51. }
  52. // FL's Misc › Time (REA round 146b [EXEC]): Shift delays a channel's notes (on and off), Gate cuts the long ones to its
  53. // length — not the porta notes when Full porta is on.
  54. struct NoteTiming
  55. {
  56. std::int64_t start = 0, length = 1;
  57. };
  58. NoteTiming noteTiming (const Note& note, float swing, const ChannelDef* c) noexcept
  59. {
  60. NoteTiming t;
  61. t.start = note.start + swingDelay (note.start, swing, c != nullptr ? c->swingMix : 1.0f);
  62. t.length = std::max<std::int64_t> (note.length, 1);
  63. if (c == nullptr)
  64. return t;
  65. if (c->misc.shiftBeats > 0.0f)
  66. t.start += (std::int64_t) std::llround ((double) c->misc.shiftBeats * ppq);
  67. if (c->misc.gateBeats > 0.0f)
  68. {
  69. const auto porta = (c->instrument == InstrumentKind::synth ? c->synth.porta : c->instrument == InstrumentKind::sampler && c->sampler.porta) != note.porta;
  70. if (! (porta && c->misc.fullPorta))
  71. t.length = std::min (t.length, std::max<std::int64_t> (1, (std::int64_t) std::llround ((double) c->misc.gateBeats * ppq)));
  72. }
  73. return t;
  74. }
  75. const ChannelDef* channelOf (const std::vector<ChannelDef>* channels, int channel) noexcept
  76. {
  77. return channels != nullptr && channel >= 0 && channel < (int) channels->size() ? &(*channels)[(std::size_t) channel] : nullptr;
  78. }
  79. } // namespace
  80. std::int64_t maxChannelShift (const std::vector<ChannelDef>& channels) noexcept
  81. {
  82. float beats = 0.0f;
  83. for (const auto& c : channels)
  84. beats = std::max (beats, c.misc.shiftBeats);
  85. return (std::int64_t) std::ceil ((double) beats * ppq);
  86. }
  87. void schedulePatternLoop (const Pattern& pattern,
  88. std::int64_t patternLength,
  89. double startTick,
  90. int numSamples,
  91. double tps,
  92. EventBuffer& out,
  93. float swing,
  94. const std::vector<ChannelDef>* channels) noexcept
  95. {
  96. if (numSamples <= 0 || patternLength <= 0 || tps <= 0.0)
  97. return;
  98. const auto endTick = startTick + numSamples * tps;
  99. for (const auto& note : pattern.notes)
  100. {
  101. if (note.start >= patternLength || note.muted)
  102. continue; // outside the loop / muted note
  103. NoteEvent on;
  104. on.type = NoteEvent::Type::on;
  105. on.channel = note.channel;
  106. on.key = note.key;
  107. on.velocity = note.velocity;
  108. on.pan = note.pan;
  109. on.cents = note.finePitch;
  110. on.porta = note.porta;
  111. const auto timing = noteTiming (note, swing, channelOf (channels, note.channel));
  112. const auto start = timing.start;
  113. if (note.slide)
  114. {
  115. on.type = NoteEvent::Type::slide;
  116. on.slideSamples = (float) ((double) std::max<std::int64_t> (note.length, 1) / tps);
  117. emitOccurrences ((double) start, patternLength, startTick, endTick, tps, numSamples, on, out);
  118. continue; // slide has no "off": the original note continues until its own end
  119. }
  120. emitOccurrences ((double) start, patternLength, startTick, endTick, tps, numSamples, on, out);
  121. NoteEvent off = on;
  122. off.type = NoteEvent::Type::off;
  123. off.velocity = 0.0f;
  124. const auto length = timing.length;
  125. emitOccurrences ((double) (start + length), patternLength, startTick, endTick, tps, numSamples, off, out);
  126. }
  127. out.sortByOffset();
  128. }
  129. ScheduleIndex makeScheduleIndex (const Song& song)
  130. {
  131. ScheduleIndex index;
  132. index.songLength = song.songLength();
  133. index.maxShift = maxChannelShift (song.channels);
  134. index.maxNoteLength.reserve (song.patterns.size());
  135. for (const auto& p : song.patterns)
  136. {
  137. std::int64_t longest = 0;
  138. for (const auto& n : p.notes)
  139. longest = std::max (longest, n.length);
  140. index.maxNoteLength.push_back (longest);
  141. }
  142. return index;
  143. }
  144. PlaybackLoop playbackLoop (bool songMode, double loopStart, double loopEnd, double songLength) noexcept
  145. {
  146. if (! songMode)
  147. return {};
  148. if (loopEnd > loopStart)
  149. return { loopStart, loopEnd };
  150. return { 0.0, std::max (0.0, songLength) };
  151. }
  152. double hostPositionTick (const Song& song, double tick, std::int64_t songLength) noexcept
  153. {
  154. tick = std::max (0.0, tick);
  155. if (song.mode == PlayMode::song)
  156. return song.hasLoop() ? tick : std::fmod (tick, (double) std::max<std::int64_t> (1, songLength));
  157. if (song.patterns.empty())
  158. return tick;
  159. const auto& pattern = song.patterns[(std::size_t) std::clamp (song.currentPattern, 0, (int) song.patterns.size() - 1)];
  160. return std::fmod (tick, (double) std::max<std::int64_t> (1, pattern.effectiveLength (song.beatsPerBar)));
  161. }
  162. void scheduleSong (const Song& song, double startTick, int numSamples, double tps, EventBuffer& out, bool resume,
  163. const ScheduleIndex* index) noexcept
  164. {
  165. if (numSamples <= 0 || tps <= 0.0 || song.playlist.empty())
  166. return;
  167. const auto loop = index != nullptr ? index->songLength : song.songLength();
  168. const auto endTick = startTick + numSamples * tps;
  169. // Block window within the loop; if it crosses the end, it becomes two windows.
  170. const auto loopStart = std::fmod (startTick, (double) loop);
  171. const auto loopEnd = loopStart + (endTick - startTick);
  172. auto overlaps = [&] (double from, double to) {
  173. return (from < loopEnd && to > loopStart) || (loopEnd > (double) loop && from < loopEnd - (double) loop);
  174. };
  175. const auto secondsPerTick = 60.0 / (std::max (song.bpm, 1.0) * ppq);
  176. for (std::size_t clipIndex = 0; clipIndex < song.playlist.size(); ++clipIndex)
  177. {
  178. const auto& clip = song.playlist[clipIndex];
  179. if (clip.muted || song.isTrackMuted (clip.track))
  180. continue;
  181. if (clip.kind == ClipKind::audio)
  182. {
  183. if (clip.channel < 0 || clip.channel >= (int) song.channels.size() || clip.length <= 0)
  184. continue;
  185. NoteEvent e;
  186. e.channel = clip.channel;
  187. e.key = audioClipKey (clipIndex);
  188. e.velocity = clip.gain;
  189. e.fadeIn = (float) ((double) clip.fadeIn / tps);
  190. e.fadeOut = (float) ((double) clip.fadeOut / tps);
  191. if (resume && loopStart > (double) clip.start && loopStart < (double) clip.end())
  192. {
  193. e.type = NoteEvent::Type::on;
  194. e.sampleOffset = 0;
  195. e.startSeconds = ((double) clip.offset + (double) clip.offsetFraction + loopStart - (double) clip.start) * secondsPerTick;
  196. e.clipElapsed = (float) ((loopStart - (double) clip.start) / tps);
  197. e.clipRemaining = (float) (((double) clip.end() - loopStart) / tps);
  198. out.add (e);
  199. }
  200. if (! overlaps ((double) clip.start, (double) clip.end() + 1.0))
  201. continue;
  202. e.type = NoteEvent::Type::on;
  203. e.startSeconds = std::max (0.0, ((double) clip.offset + (double) clip.offsetFraction) * secondsPerTick);
  204. e.clipElapsed = 0.0f;
  205. e.clipRemaining = (float) ((double) clip.length / tps);
  206. emitOccurrences ((double) clip.start, loop, startTick, endTick, tps, numSamples, e, out);
  207. e.type = NoteEvent::Type::off;
  208. e.startSeconds = 0.0;
  209. emitOccurrences ((double) clip.end(), loop, startTick, endTick, tps, numSamples, e, out);
  210. continue;
  211. }
  212. if (clip.kind != ClipKind::pattern || clip.pattern < 0 || clip.pattern >= (int) song.patterns.size() || clip.length <= 0)
  213. continue;
  214. // one tick of slack to catch the "off" that falls exactly at the end of the clip
  215. if (! overlaps ((double) clip.start, (double) clip.end() + 1.0))
  216. continue;
  217. const auto& notes = song.patterns[(std::size_t) clip.pattern].notes;
  218. auto first = notes.begin(), last = notes.end();
  219. // with the index and without the block wrapping around the end of the song: only the notes whose "on" or "off"
  220. // can fall in the block (swing delays by at most half a step)
  221. if (index != nullptr && loopEnd <= (double) loop && (std::size_t) clip.pattern < index->maxNoteLength.size())
  222. {
  223. const auto local = (double) (clip.offset - clip.start);
  224. const auto from = loopStart + local - (double) (ticksPerStep + index->maxNoteLength[(std::size_t) clip.pattern] + index->maxShift) - 1.0;
  225. const auto to = loopEnd + local + 1.0;
  226. first = std::lower_bound (notes.begin(), notes.end(), from, [] (const Note& n, double t) { return (double) n.start < t; });
  227. last = std::upper_bound (first, notes.end(), to, [] (double t, const Note& n) { return t < (double) n.start; });
  228. }
  229. for (auto it = first; it != last; ++it)
  230. {
  231. const auto& note = *it;
  232. if (note.muted || note.start < clip.offset || note.start >= clip.offset + clip.length)
  233. continue;
  234. const auto timing = noteTiming (note, song.swing, channelOf (&song.channels, note.channel));
  235. const auto on = std::min (clip.start + (note.start - clip.offset) + (timing.start - note.start), clip.end() - 1);
  236. const auto off = std::min (on + timing.length, clip.end());
  237. NoteEvent e;
  238. e.type = NoteEvent::Type::on;
  239. e.channel = note.channel;
  240. e.key = note.key;
  241. e.velocity = note.velocity;
  242. e.pan = note.pan;
  243. e.cents = note.finePitch;
  244. e.porta = note.porta;
  245. if (note.slide)
  246. {
  247. e.type = NoteEvent::Type::slide;
  248. e.slideSamples = (float) ((double) (off - on) / tps);
  249. emitOccurrences ((double) on, loop, startTick, endTick, tps, numSamples, e, out);
  250. continue;
  251. }
  252. emitOccurrences ((double) on, loop, startTick, endTick, tps, numSamples, e, out);
  253. e.type = NoteEvent::Type::off;
  254. e.velocity = 0.0f;
  255. emitOccurrences ((double) off, loop, startTick, endTick, tps, numSamples, e, out);
  256. }
  257. }
  258. out.sortByOffset();
  259. }
  260. } // namespace lynx