RenderAhead.cpp 69 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480
  1. #include "core/RenderAhead.h"
  2. #include "core/OverloadGuard.h"
  3. #include <algorithm>
  4. #include <cmath>
  5. #include <cstring>
  6. #include <utility>
  7. #include "core/Denormals.h"
  8. #include "core/Patcher.h"
  9. #include "core/Rack.h"
  10. #include "core/WorkerPool.h"
  11. namespace lynx
  12. {
  13. std::atomic<bool>& renderAheadOption() noexcept
  14. {
  15. static std::atomic<bool> on { true }; // O22: on by default
  16. return on;
  17. }
  18. namespace renderahead
  19. {
  20. void Targets::publish (const int* channels, int channelCount, const int* tracks, int trackCount) noexcept
  21. {
  22. channelCount = std::clamp (channelCount, 0, maxChannels);
  23. trackCount = std::clamp (trackCount, 0, maxTracks);
  24. versionCounter.fetch_add (1, std::memory_order_acq_rel); // odd: writing
  25. for (int i = 0; i < channelCount; ++i)
  26. channelList[(std::size_t) i].store (channels[i], std::memory_order_relaxed);
  27. for (int i = 0; i < trackCount; ++i)
  28. trackList[(std::size_t) i].store (tracks[i], std::memory_order_relaxed);
  29. channelTotal.store (channelCount, std::memory_order_relaxed);
  30. trackTotal.store (trackCount, std::memory_order_relaxed);
  31. versionCounter.fetch_add (1, std::memory_order_acq_rel); // even: ready
  32. }
  33. bool Targets::read (std::array<int, maxChannels>& channels, int& channelCount, std::array<int, maxTracks>& tracks, int& trackCount,
  34. std::uint32_t& version) const noexcept
  35. {
  36. const auto before = versionCounter.load (std::memory_order_acquire);
  37. if ((before & 1u) != 0 || before == version)
  38. return false;
  39. const auto nc = std::clamp (channelTotal.load (std::memory_order_relaxed), 0, maxChannels);
  40. const auto nt = std::clamp (trackTotal.load (std::memory_order_relaxed), 0, maxTracks);
  41. std::array<int, maxChannels> c {};
  42. std::array<int, maxTracks> t {};
  43. for (int i = 0; i < nc; ++i)
  44. c[(std::size_t) i] = channelList[(std::size_t) i].load (std::memory_order_relaxed);
  45. for (int i = 0; i < nt; ++i)
  46. t[(std::size_t) i] = trackList[(std::size_t) i].load (std::memory_order_relaxed);
  47. if (versionCounter.load (std::memory_order_acquire) != before)
  48. return false; // written meanwhile: next block
  49. channels = c;
  50. tracks = t;
  51. channelCount = nc;
  52. trackCount = nt;
  53. version = before;
  54. return true;
  55. }
  56. bool TransportModel::operator== (const TransportModel& o) const noexcept
  57. {
  58. // (offset is where the current sub-block starts: it moves every sub-block and changes no prediction)
  59. return sampleRate == o.sampleRate && deviceBlock == o.deviceBlock && songMode == o.songMode && loopStart == o.loopStart && loopEnd == o.loopEnd
  60. && songEnd == o.songEnd && songStart == o.songStart && linear == o.linear && throughRegion == o.throughRegion
  61. && pendingAt == o.pendingAt && predictable == o.predictable
  62. && (markers == nullptr) == (o.markers == nullptr)
  63. && (markers == nullptr || (markers->count == o.markers->count && markers->wrapTo == o.markers->wrapTo && markers->start == o.markers->start
  64. && std::equal (markers->jumps.begin(), markers->jumps.begin() + std::clamp (markers->count, 0, MarkerPlan::maxJumps),
  65. o.markers->jumps.begin(),
  66. [] (const MarkerJump& a, const MarkerJump& b) { return a.at == b.at && a.to == b.to && a.kind == b.kind; })));
  67. }
  68. SubBlock planSubBlock (const TransportModel& m, double position, int done, double tps) noexcept
  69. {
  70. // AudioEngine::audioDeviceIOCallbackWithContext, one turn of its loop while playing (not counting in): the same
  71. // values in the same order, so the positions come out bit for bit as the callback's
  72. SubBlock s;
  73. auto n = m.deviceBlock - done;
  74. const auto loop = playbackLoop (m.songMode, m.throughRegion ? 0.0 : m.loopStart, m.throughRegion ? 0.0 : m.loopEnd, m.linear ? 0.0 : m.songEnd,
  75. m.songStart);
  76. const auto looping = loop.active() && tps > 0.0;
  77. const auto regionOn = ! m.throughRegion && m.loopEnd > m.loopStart;
  78. const auto wrapTo = m.markers != nullptr ? (double) m.markers->wrapTo : 0.0;
  79. const auto songWrap = regionOn ? loop.start : std::clamp (wrapTo, loop.start, std::max (loop.start, loop.end - 1.0));
  80. if (looping)
  81. {
  82. if (transportReached (position, loop.end))
  83. position = songWrap;
  84. n = transportSamplesUntil (position, loop.end, tps, n);
  85. }
  86. const MarkerJump* jump = nullptr;
  87. auto userJump = false;
  88. if (tps > 0.0 && m.songMode && m.markers != nullptr)
  89. {
  90. const auto step = markerStep (*m.markers, position, n, tps, m.pendingAt);
  91. n = step.samples;
  92. jump = step.jump;
  93. userJump = step.userJump;
  94. }
  95. s.start = position;
  96. s.samples = n;
  97. auto after = position + n * tps;
  98. if (userJump && transportReached (after, m.pendingAt))
  99. s.last = true; // the user's quantized jump: the callback moves the position
  100. else if (jump != nullptr && transportReached (after, (double) jump->at))
  101. s.last = true; // a marker jump / pause
  102. else if (looping && transportReached (after, loop.end))
  103. after = songWrap;
  104. s.next = after;
  105. return s;
  106. }
  107. } // namespace renderahead
  108. using namespace renderahead;
  109. namespace
  110. {
  111. constexpr int maxEntries = 64;
  112. constexpr int poolSamples = 4096; // per boundary slot and side, for all the ring's entries
  113. constexpr int tweakHoldMs = 250;
  114. constexpr int editorPollSamples = 2048; // how often the open editors' live meters are looked at
  115. } // namespace
  116. struct RenderAhead::Entry
  117. {
  118. RackRenderer::SplitBlock block;
  119. double start = 0.0;
  120. int samples = 0;
  121. bool playing = false;
  122. std::array<float, 2 * maxMixerTracks> peaks {}; // [i * 2 + side]: the i-th insert of the part rendered ahead
  123. // round 190lr (DL-108): the blocks' sums of squares and their frames, kept only while the Session mixer's RMS bars show
  124. std::array<float, 2 * maxMixerTracks> power {};
  125. std::array<int, maxMixerTracks> powerFrames {};
  126. // round 190qh (D2-MX3): the blocks' L·R, L², R² sums, kept only while the Mixer's correlation bars show
  127. std::array<float, 3 * maxMixerTracks> correlation {};
  128. };
  129. struct RenderAhead::Partition
  130. {
  131. RackRenderer::Split liveSplit, aheadSplit;
  132. std::array<char, RackRenderer::maxChannels> aheadChannel {};
  133. std::array<char, maxMixerTracks> aheadTrack {};
  134. std::array<std::int16_t, maxMixerTracks> aheadTrackList {};
  135. int aheadTrackCount = 0, aheadChannelCount = 0;
  136. // the automations driven by a unit of the part rendered ahead (controllers): their value moves with that part
  137. std::array<int, RackState::maxAutomations> aheadAutomations {};
  138. int aheadAutomationCount = 0;
  139. // scratch of the closure
  140. static constexpr int nodes = RackRenderer::maxChannels + maxMixerTracks;
  141. std::array<std::int16_t, nodes> parent {};
  142. std::array<char, nodes> live {}, groupLive {};
  143. std::uint32_t editorHash = 0;
  144. bool sameUnits (const Partition& o) const noexcept
  145. {
  146. return aheadChannel == o.aheadChannel && aheadTrack == o.aheadTrack && liveSplit.slots == o.liveSplit.slots
  147. && std::equal (liveSplit.slotKind.begin(), liveSplit.slotKind.begin() + liveSplit.slots, o.liveSplit.slotKind.begin())
  148. && std::equal (liveSplit.slotUnit.begin(), liveSplit.slotUnit.begin() + liveSplit.slots, o.liveSplit.slotUnit.begin());
  149. }
  150. };
  151. RenderAhead::RenderAhead (RackRenderer& liveRenderer)
  152. : live (liveRenderer),
  153. ahead (std::make_unique<RackRenderer>()),
  154. aheadInput (std::make_unique<LiveInput>()),
  155. aheadMeters (std::make_unique<MeterBank>()),
  156. aheadTimeline (std::make_unique<HostTimeline>()),
  157. current (std::make_unique<Partition>()),
  158. next (std::make_unique<Partition>()),
  159. wake (std::make_unique<OsSemaphore>()),
  160. forward (std::make_unique<LiveEventQueue>()),
  161. localEvents (std::make_unique<LiveEventQueue>())
  162. {
  163. ahead->shareTimesWith (live);
  164. ahead->setLiveInput (aheadInput.get());
  165. ahead->setHostTimeline (aheadTimeline.get());
  166. live.setPropsMirror (ahead.get()); // (round 190ql: the live renderer's per-channel note blocks, made here too)
  167. for (int e = 0; e < maxEntries; ++e)
  168. entries.push_back (std::make_unique<Entry>());
  169. }
  170. RenderAhead::~RenderAhead()
  171. {
  172. quit.store (true, std::memory_order_seq_cst);
  173. wake->release();
  174. if (worker.joinable())
  175. worker.join();
  176. live.setPropsMirror (nullptr);
  177. }
  178. void RenderAhead::setWorkerPool (WorkerPool* p, std::function<void()> onThreadStart)
  179. {
  180. pool = p;
  181. if (! worker.joinable())
  182. worker = std::thread ([this, onThreadStart] { threadLoop (onThreadStart); });
  183. }
  184. void RenderAhead::prepare (double rate, int maxBlockSize)
  185. {
  186. // (no audio callback runs the rack now: a device (re)start or an offline render getting ready)
  187. running.store (false, std::memory_order_seq_cst);
  188. while (owner.load (std::memory_order_acquire) == 1)
  189. std::this_thread::yield();
  190. if (engagedNow.load (std::memory_order_relaxed))
  191. disengage (liveState, writeIndex.load() != readIndex.load());
  192. sampleRate = rate;
  193. maxBlock = std::max (64, maxBlockSize);
  194. halted.store (false, std::memory_order_seq_cst);
  195. if (windowSamples <= 0)
  196. windowSamples = (int) std::lround (0.0232 * rate); // about 23 ms: 1024 samples at 44.1 kHz
  197. ahead->forgetState();
  198. ahead->prepare (rate, maxBlockSize);
  199. audioPool.assign ((std::size_t) RackRenderer::Split::maxSlots * 2 * poolSamples, 0.0f);
  200. flagPool.assign ((std::size_t) maxEntries * RackRenderer::SplitBlock::maxChunks * RackRenderer::Split::maxSlots, 0);
  201. scratchL.assign ((std::size_t) maxBlock, 0.0f);
  202. scratchR.assign ((std::size_t) maxBlock, 0.0f);
  203. entryCount.store (0, std::memory_order_relaxed);
  204. readIndex.store (0);
  205. writeIndex.store (0);
  206. }
  207. void RenderAhead::halt() noexcept
  208. {
  209. halted.store (true, std::memory_order_seq_cst);
  210. running.store (false, std::memory_order_seq_cst);
  211. while (owner.load (std::memory_order_acquire) == 1)
  212. std::this_thread::yield();
  213. }
  214. void RenderAhead::setOverriddenSlots (const std::vector<int>& slots) noexcept
  215. {
  216. live.setOverriddenSlots (slots);
  217. ahead->setOverriddenSlots (slots);
  218. }
  219. void RenderAhead::setKeepReleasedOnPlay (bool keep) noexcept
  220. {
  221. live.setKeepReleasedOnPlay (keep);
  222. ahead->setKeepReleasedOnPlay (keep);
  223. }
  224. void RenderAhead::setReleasedSlots (const std::vector<int>& slots) noexcept
  225. {
  226. live.setReleasedSlots (slots);
  227. ahead->setReleasedSlots (slots);
  228. }
  229. void RenderAhead::setProfiling (bool on) noexcept
  230. {
  231. live.setProfiling (on);
  232. ahead->setProfiling (on);
  233. }
  234. void RenderAhead::setStoppedSleep (bool on) noexcept
  235. {
  236. live.setStoppedSleep (on);
  237. ahead->setStoppedSleep (on);
  238. }
  239. const RackRenderer& RenderAhead::rendererOf (int channel) const noexcept
  240. {
  241. if (engagedNow.load (std::memory_order_relaxed) && channel >= 0 && channel < RackRenderer::maxChannels
  242. && current->aheadChannel[(std::size_t) channel] != 0)
  243. return *ahead;
  244. return live;
  245. }
  246. // ---- the partition -------------------------------------------------------------------------------------------------
  247. bool RenderAhead::computePartition (const RackState& state, const Block& block, Partition& p) noexcept
  248. {
  249. const auto& song = state.song;
  250. const auto C = std::min<int> ({ (int) song.channels.size(), (int) state.instruments.size(), RackRenderer::maxChannels });
  251. const auto T = std::clamp ((int) song.mixer.size(), 1, maxMixerTracks);
  252. const auto N = C + T;
  253. auto track = [C] (int t) { return C + t; };
  254. auto okChannel = [C] (int c) { return c >= 0 && c < C; };
  255. auto okTrack = [T] (int t) { return t >= 0 && t < T; };
  256. for (int i = 0; i < N; ++i)
  257. {
  258. p.parent[(std::size_t) i] = (std::int16_t) i;
  259. p.live[(std::size_t) i] = 0;
  260. p.groupLive[(std::size_t) i] = 0;
  261. }
  262. auto find = [&p] (int x) {
  263. while (p.parent[(std::size_t) x] != x)
  264. {
  265. p.parent[(std::size_t) x] = p.parent[(std::size_t) p.parent[(std::size_t) x]];
  266. x = p.parent[(std::size_t) x];
  267. }
  268. return x;
  269. };
  270. auto unite = [&] (int a, int b) {
  271. a = find (a);
  272. b = find (b);
  273. if (a != b)
  274. p.parent[(std::size_t) a] = (std::int16_t) b;
  275. };
  276. auto unitOf = [&] (const AutomationTarget& t, int* out) -> int {
  277. switch (t.kind)
  278. {
  279. case AutomationTargetKind::channelVolume:
  280. case AutomationTargetKind::channelPan:
  281. case AutomationTargetKind::channelParam:
  282. case AutomationTargetKind::channelAdjust:
  283. if (okChannel (t.index))
  284. {
  285. out[0] = t.index;
  286. return 1;
  287. }
  288. return 0;
  289. case AutomationTargetKind::mixerVolume:
  290. case AutomationTargetKind::mixerPan:
  291. case AutomationTargetKind::effectParam:
  292. case AutomationTargetKind::effectMix:
  293. if (okTrack (t.index))
  294. {
  295. out[0] = track (t.index);
  296. return 1;
  297. }
  298. return 0;
  299. case AutomationTargetKind::mixerSend: // (the destination pulls the route at its level)
  300. {
  301. auto n = 0;
  302. if (okTrack (t.index))
  303. out[n++] = track (t.index);
  304. if (okTrack (t.slot))
  305. out[n++] = track (t.slot);
  306. return n;
  307. }
  308. default:
  309. return 0;
  310. }
  311. };
  312. // a controller driving the tempo: the positions depend on a unit's output, nothing can be foreseen
  313. if (state.tempoAutomation >= 0 && (std::size_t) state.tempoAutomation < song.automations.size()
  314. && song.automations[(std::size_t) state.tempoAutomation].isLive())
  315. return false;
  316. // --- the live seeds
  317. p.live[(std::size_t) track (0)] = 1; // the Master: its effects, its captures, the device
  318. for (int t = 1; t < T; ++t)
  319. {
  320. const auto& m = song.mixer[(std::size_t) t];
  321. if (m.inputChannel >= 0)
  322. p.live[(std::size_t) track (t)] = 1;
  323. if (liveInput != nullptr && (liveInput->armed[(std::size_t) t].load (std::memory_order_relaxed) || liveInput->tappedPoints (t) != 0))
  324. p.live[(std::size_t) track (t)] = 1;
  325. }
  326. for (const auto& route : state.hwRoutes)
  327. if (okTrack (route.track))
  328. p.live[(std::size_t) track (route.track)] = 1;
  329. for (const auto t : { block.metronomeTrack, block.sideTrack, block.captureTrack })
  330. if (okTrack (t))
  331. p.live[(std::size_t) track (t)] = 1;
  332. for (const auto c : state.audioThreadChannels) // ("Allow threaded processing" off, hardware I/O): the audio thread only
  333. if (okChannel (c))
  334. p.live[(std::size_t) c] = 1;
  335. for (const auto& layer : state.audioThreadLayers)
  336. for (const auto t : layer)
  337. if (okTrack (t))
  338. p.live[(std::size_t) track (t)] = 1;
  339. for (int i = 0; i < targetChannelCount; ++i)
  340. if (okChannel (targetChannels[(std::size_t) i]))
  341. p.live[(std::size_t) targetChannels[(std::size_t) i]] = 1;
  342. for (int i = 0; i < promotedCount; ++i)
  343. if (okChannel (promotedChannels[(std::size_t) i]))
  344. p.live[(std::size_t) promotedChannels[(std::size_t) i]] = 1;
  345. for (int i = 0; i < targetTrackCount; ++i)
  346. if (okTrack (targetTracks[(std::size_t) i]))
  347. p.live[(std::size_t) track (targetTracks[(std::size_t) i])] = 1;
  348. // an editor showing a slot's live level meters (levelWanted), its effect meters (190gp's metersWanted: gain reduction,
  349. // band levels...) or its spectrum: that insert stays in time with its pictures
  350. {
  351. auto& times = live.processTimes();
  352. std::uint32_t hash = 2166136261u;
  353. for (int t = 0; t < T; ++t)
  354. for (int s = 0; s < maxEffectSlots; ++s)
  355. if (times.levelWanted[(std::size_t) (t * maxEffectSlots + s)].load (std::memory_order_relaxed) > 0
  356. || times.metersWanted[(std::size_t) (t * maxEffectSlots + s)].load (std::memory_order_relaxed) > 0) // (rollup 0.1.28: 190gp's live meters too)
  357. {
  358. p.live[(std::size_t) track (t)] = 1;
  359. hash = (hash ^ (std::uint32_t) (t * maxEffectSlots + s)) * 16777619u;
  360. }
  361. if (const auto key = times.analyzer.key.load (std::memory_order_relaxed); key >= 0 && okTrack (key / maxEffectSlots))
  362. {
  363. p.live[(std::size_t) track (key / maxEffectSlots)] = 1;
  364. hash = (hash ^ (std::uint32_t) (key + 0x10000)) * 16777619u;
  365. }
  366. p.editorHash = hash;
  367. }
  368. // --- units tied together by notes and controls: one side only
  369. for (int c = 0; c < C; ++c)
  370. {
  371. const auto& ch = song.channels[(std::size_t) c];
  372. if ((std::size_t) c < state.midiRoutesOut.size())
  373. for (const auto& route : state.midiRoutesOut[(std::size_t) c])
  374. if (okChannel (route.other))
  375. unite (c, route.other);
  376. if ((std::size_t) c < state.midiOutTargets.size())
  377. for (const auto t : state.midiOutTargets[(std::size_t) c])
  378. if (okChannel (t))
  379. unite (c, t);
  380. if ((std::size_t) c < state.midiTargets.size())
  381. for (const auto t : state.midiTargets[(std::size_t) c])
  382. if (okChannel (t))
  383. unite (c, t);
  384. if ((std::size_t) c < state.cutTargets.size())
  385. for (const auto t : state.cutTargets[(std::size_t) c])
  386. if (okChannel (t))
  387. unite (c, t);
  388. if (ch.instrument == InstrumentKind::layer)
  389. for (const auto child : ch.layer.children)
  390. if (okChannel (child))
  391. unite (c, child);
  392. if ((std::size_t) c < state.effectMidiRoutes.size())
  393. for (const auto& route : state.effectMidiRoutes[(std::size_t) c])
  394. if (okTrack (route.track))
  395. unite (c, track (route.track));
  396. if (const auto* rk = rack::rackOf (ch.patcher); rk != nullptr)
  397. for (const auto child : rk->children)
  398. if (okChannel (child))
  399. unite (c, child);
  400. // a generator's extra outputs (a generator Patcher's) go to inserts it names while it plays
  401. if (const auto* instrument = state.instruments[(std::size_t) c].get(); instrument != nullptr)
  402. for (int k = 0; k < instrument->auxOutputCount(); ++k)
  403. if (okTrack (instrument->auxOutputTrack (k)))
  404. unite (c, track (instrument->auxOutputTrack (k)));
  405. }
  406. // controllers (Peak / Formula / XY controllers, a plugin's output, a generator's): their source and what they drive
  407. p.aheadAutomationCount = 0;
  408. for (const auto a : state.liveAutomations)
  409. {
  410. if (a < 0 || (std::size_t) a >= song.automations.size())
  411. continue;
  412. const auto& automation = song.automations[(std::size_t) a];
  413. const auto& src = automation.source;
  414. const auto source = src.channel >= 0 ? (okChannel (src.channel) ? src.channel : -1) : (okTrack (src.track) ? track (src.track) : -1);
  415. if (source < 0)
  416. continue;
  417. int units[2] {};
  418. for (int k = 0, n = unitOf (automation.target, units); k < n; ++k)
  419. unite (source, units[k]);
  420. for (const auto& route : state.modRoutes) // (a modulator riding on that controller's value)
  421. if (route.source == a && route.slot >= 0 && (std::size_t) route.slot < song.automations.size())
  422. for (int k = 0, n = unitOf (song.automations[(std::size_t) route.slot].target, units); k < n; ++k)
  423. unite (source, units[k]);
  424. }
  425. // round 190ox: a follower's insert / an envelope's channel and what the modulator drives stay on one side (the state
  426. // lives in the renderer that runs the source)
  427. for (const auto& route : state.modRoutes)
  428. {
  429. if ((std::size_t) route.modulator >= state.modFeeds.size() || (std::size_t) route.modulator >= song.modulators.size())
  430. continue;
  431. const auto& feed = state.modFeeds[(std::size_t) route.modulator];
  432. const auto source = feed.track >= 0 ? (okTrack (feed.track) ? track (feed.track) : -1) : (feed.channel >= 0 && okChannel (feed.channel) ? feed.channel : -1);
  433. if (source < 0)
  434. continue;
  435. int units[2] {};
  436. const auto& mod = song.modulators[(std::size_t) route.modulator];
  437. for (const auto& r : mod.routes)
  438. for (int k = 0, n = unitOf (r.target, units); k < n; ++k)
  439. unite (source, units[k]);
  440. }
  441. // --- the closure: a group with a live member is live; whatever a live unit feeds is live
  442. for (auto changed = true; changed;)
  443. {
  444. changed = false;
  445. for (int i = 0; i < N; ++i)
  446. if (p.live[(std::size_t) i] != 0)
  447. p.groupLive[(std::size_t) find (i)] = 1;
  448. for (int i = 0; i < N; ++i)
  449. if (p.live[(std::size_t) i] == 0 && p.groupLive[(std::size_t) find (i)] != 0)
  450. {
  451. p.live[(std::size_t) i] = 1;
  452. changed = true;
  453. }
  454. for (int t = 1; t < T; ++t)
  455. {
  456. if (p.live[(std::size_t) track (t)] != 0)
  457. continue;
  458. auto feeds = false;
  459. if ((std::size_t) t < state.trackChannels.size())
  460. for (const auto c : state.trackChannels[(std::size_t) t])
  461. feeds = feeds || (okChannel (c) && p.live[(std::size_t) c] != 0);
  462. if ((std::size_t) t < state.mixerInputs.size())
  463. for (const auto& in : state.mixerInputs[(std::size_t) t])
  464. feeds = feeds || (okTrack (in.source) && p.live[(std::size_t) track (in.source)] != 0);
  465. const auto& effects = song.mixer[(std::size_t) t].effects;
  466. const auto* connections = (std::size_t) t < state.slotConnections.size() ? &state.slotConnections[(std::size_t) t] : nullptr;
  467. for (std::size_t i = 0; i < effects.size(); ++i)
  468. for (const auto source : { effects[i].sidechain, effects[i].sidechain2,
  469. connections != nullptr && i < connections->size() ? (*connections)[i].mainSource : -1,
  470. connections != nullptr && i < connections->size() ? (*connections)[i].sideSource : -1 })
  471. feeds = feeds || (okTrack (source) && source != t && p.live[(std::size_t) track (source)] != 0);
  472. if (feeds)
  473. {
  474. p.live[(std::size_t) track (t)] = 1;
  475. changed = true;
  476. }
  477. }
  478. }
  479. // --- the two renderers' views and the boundary
  480. auto& L = p.liveSplit;
  481. auto& A = p.aheadSplit;
  482. L.clear();
  483. A.clear();
  484. p.aheadChannel.fill (0);
  485. p.aheadTrack.fill (0);
  486. p.aheadChannelCount = p.aheadTrackCount = 0;
  487. for (int c = 0; c < RackRenderer::maxChannels; ++c)
  488. {
  489. const auto ahead = c < C && p.live[(std::size_t) c] == 0;
  490. p.aheadChannel[(std::size_t) c] = ahead ? 1 : 0;
  491. L.foreignChannel[(std::size_t) c] = ahead ? 1 : 0;
  492. A.foreignChannel[(std::size_t) c] = ahead ? 0 : 1;
  493. p.aheadChannelCount += ahead ? 1 : 0;
  494. }
  495. for (int t = 0; t < maxMixerTracks; ++t)
  496. {
  497. const auto ahead = t < T && p.live[(std::size_t) track (t)] == 0;
  498. p.aheadTrack[(std::size_t) t] = ahead ? 1 : 0;
  499. L.foreignTrack[(std::size_t) t] = ahead ? 1 : 0;
  500. A.foreignTrack[(std::size_t) t] = ahead ? 0 : 1;
  501. if (ahead)
  502. p.aheadTrackList[(std::size_t) p.aheadTrackCount++] = (std::int16_t) t;
  503. }
  504. // (nothing worth it: no channel and no insert with effects to render ahead)
  505. auto aheadWork = p.aheadChannelCount > 0;
  506. for (int i = 0; i < p.aheadTrackCount && ! aheadWork; ++i)
  507. aheadWork = ! song.mixer[(std::size_t) p.aheadTrackList[(std::size_t) i]].effects.empty();
  508. if (! aheadWork)
  509. return false;
  510. auto overflow = false;
  511. auto addSlot = [&] (RackRenderer::Split::Kind kind, int unit) {
  512. auto* slot = kind == RackRenderer::Split::Kind::channel ? &L.channelSlot[(std::size_t) unit]
  513. : kind == RackRenderer::Split::Kind::track ? &L.trackSlot[(std::size_t) unit]
  514. : &L.tapSlot[(std::size_t) unit];
  515. if (*slot >= 0)
  516. return;
  517. if (L.slots >= RackRenderer::Split::maxSlots)
  518. {
  519. overflow = true;
  520. return;
  521. }
  522. *slot = (std::int16_t) L.slots;
  523. L.slotKind[(std::size_t) L.slots] = kind;
  524. L.slotUnit[(std::size_t) L.slots] = (std::int16_t) unit;
  525. ++L.slots;
  526. };
  527. for (int t = 0; t < T; ++t)
  528. {
  529. if (p.live[(std::size_t) track (t)] == 0)
  530. continue;
  531. if ((std::size_t) t < state.trackChannels.size())
  532. for (const auto c : state.trackChannels[(std::size_t) t])
  533. if (okChannel (c) && p.live[(std::size_t) c] == 0)
  534. addSlot (RackRenderer::Split::Kind::channel, c);
  535. if ((std::size_t) t < state.mixerInputs.size())
  536. for (const auto& in : state.mixerInputs[(std::size_t) t])
  537. if (okTrack (in.source) && p.live[(std::size_t) track (in.source)] == 0)
  538. {
  539. if (in.tap >= 0 && in.tap < RackState::maxSendTaps)
  540. addSlot (RackRenderer::Split::Kind::tap, in.tap);
  541. else
  542. addSlot (RackRenderer::Split::Kind::track, in.source);
  543. }
  544. const auto& effects = song.mixer[(std::size_t) t].effects;
  545. const auto* connections = (std::size_t) t < state.slotConnections.size() ? &state.slotConnections[(std::size_t) t] : nullptr;
  546. for (std::size_t i = 0; i < effects.size(); ++i)
  547. for (const auto source : { effects[i].sidechain, effects[i].sidechain2,
  548. connections != nullptr && i < connections->size() ? (*connections)[i].mainSource : -1,
  549. connections != nullptr && i < connections->size() ? (*connections)[i].sideSource : -1 })
  550. if (okTrack (source) && source != t && p.live[(std::size_t) track (source)] == 0)
  551. addSlot (RackRenderer::Split::Kind::track, source);
  552. }
  553. if (overflow)
  554. return false;
  555. A.channelSlot = L.channelSlot;
  556. A.trackSlot = L.trackSlot;
  557. A.tapSlot = L.tapSlot;
  558. A.slotKind = L.slotKind;
  559. A.slotUnit = L.slotUnit;
  560. A.slots = L.slots;
  561. A.exports = true;
  562. L.exports = false;
  563. for (const auto a : state.liveAutomations)
  564. {
  565. if (a < 0 || (std::size_t) a >= song.automations.size() || p.aheadAutomationCount >= RackState::maxAutomations)
  566. continue;
  567. const auto& src = song.automations[(std::size_t) a].source;
  568. const auto aheadSource = src.channel >= 0 ? okChannel (src.channel) && p.live[(std::size_t) src.channel] == 0
  569. : okTrack (src.track) && p.live[(std::size_t) track (src.track)] == 0;
  570. if (aheadSource)
  571. p.aheadAutomations[(std::size_t) p.aheadAutomationCount++] = a;
  572. }
  573. return true;
  574. }
  575. bool RenderAhead::partitionOf (const RackState& state, const int* liveChannels, int liveChannelCount, const int* liveTracks, int liveTrackCount,
  576. const LiveInput* input, std::vector<char>& aheadChannels, std::vector<char>& aheadTracks, int& boundary,
  577. const ProcessTimes* editors)
  578. {
  579. RackRenderer scratch;
  580. if (editors != nullptr)
  581. {
  582. auto& times = scratch.processTimes();
  583. for (std::size_t k = 0; k < times.levelWanted.size(); ++k)
  584. {
  585. times.levelWanted[k].store (editors->levelWanted[k].load (std::memory_order_relaxed), std::memory_order_relaxed);
  586. times.metersWanted[k].store (editors->metersWanted[k].load (std::memory_order_relaxed), std::memory_order_relaxed);
  587. }
  588. times.analyzer.key.store (editors->analyzer.key.load (std::memory_order_relaxed), std::memory_order_relaxed);
  589. }
  590. RenderAhead r (scratch);
  591. r.liveInput = const_cast<LiveInput*> (input);
  592. r.targetChannelCount = std::clamp (liveChannelCount, 0, Targets::maxChannels);
  593. for (int i = 0; i < r.targetChannelCount; ++i)
  594. r.targetChannels[(std::size_t) i] = liveChannels[i];
  595. r.targetTrackCount = std::clamp (liveTrackCount, 0, Targets::maxTracks);
  596. for (int i = 0; i < r.targetTrackCount; ++i)
  597. r.targetTracks[(std::size_t) i] = liveTracks[i];
  598. Block block;
  599. const auto ok = r.computePartition (state, block, *r.next);
  600. aheadChannels.assign (r.next->aheadChannel.begin(), r.next->aheadChannel.begin() + (std::ptrdiff_t) std::min<std::size_t> (state.song.channels.size(), RackRenderer::maxChannels));
  601. aheadTracks.assign (r.next->aheadTrack.begin(), r.next->aheadTrack.begin() + (std::ptrdiff_t) std::min<std::size_t> (state.song.mixer.size(), maxMixerTracks));
  602. boundary = r.next->liveSplit.slots;
  603. return ok;
  604. }
  605. // ---- engaging, syncing, dropping ------------------------------------------------------------------------------------
  606. bool RenderAhead::engage (const RackState& state, const Block& b) noexcept
  607. {
  608. if (! computePartition (state, b, *next))
  609. return false;
  610. stride = b.model->deviceBlock;
  611. const auto rings = std::min (maxEntries, poolSamples / std::max (1, stride));
  612. entryCount.store (rings, std::memory_order_relaxed);
  613. if (rings < 2 || stride > maxBlock)
  614. return false;
  615. targetFill.store (std::clamp ((windowSamples + stride - 1) / stride, 1, rings - 1), std::memory_order_relaxed);
  616. for (int e = 0; e < rings; ++e)
  617. {
  618. auto& block = entries[(std::size_t) e]->block;
  619. block.audio = audioPool.data() + (std::size_t) e * RackRenderer::Split::maxSlots * 2 * (std::size_t) stride;
  620. block.stride = stride;
  621. block.flags = flagPool.data() + (std::size_t) e * RackRenderer::SplitBlock::maxChunks * RackRenderer::Split::maxSlots;
  622. block.chunks = 0;
  623. }
  624. readIndex.store (0, std::memory_order_relaxed);
  625. writeIndex.store (0, std::memory_order_relaxed);
  626. std::swap (current, next);
  627. // (the back-off rules start counting afresh; the thread is idle)
  628. serialLoad = 0.0;
  629. serialLoadSeen.store (0.0f, std::memory_order_relaxed);
  630. jobsSinceSerial = 0;
  631. heavyFor = windowSeconds = 0.0;
  632. windowBlocks = windowWaits = 0;
  633. // the part rendered ahead starts where the live renderer is: its transport, its started notes, the units' state
  634. ahead->adoptGlobals (live);
  635. ahead->adoptUnits (live, current->aheadChannel.data(), current->aheadTrack.data());
  636. ahead->adoptAutomationValues (live, current->aheadAutomations.data(), current->aheadAutomationCount);
  637. live.setSplit (&current->liveSplit);
  638. ahead->setSplit (&current->aheadSplit);
  639. live.setWorkerPool (nullptr); // (the workers are the ahead part's now; the live part is small)
  640. liveState = aheadState = &state;
  641. aheadNext.store (&state, std::memory_order_release);
  642. aheadAck.store (&state, std::memory_order_release);
  643. jobBlock = b;
  644. jobRecording = liveInput != nullptr && liveInput->recording.load (std::memory_order_relaxed);
  645. jobLinear = liveInput != nullptr && liveInput->linearSong.load (std::memory_order_relaxed);
  646. jobPatternOrigin = liveInput != nullptr ? liveInput->patternOrigin.load (std::memory_order_relaxed) : -1.0;
  647. model = *b.model;
  648. if (b.model->markers != nullptr)
  649. {
  650. modelMarkers = *b.model->markers;
  651. model.markers = &modelMarkers;
  652. }
  653. lastModel = model;
  654. modelStop.store (true, std::memory_order_release); // (until the first block is rendered here and the thread knows where the next one starts)
  655. partitionTargets = targetVersion;
  656. drain.store (false, std::memory_order_relaxed);
  657. running.store (false, std::memory_order_relaxed);
  658. engagedNow.store (true, std::memory_order_release);
  659. counters.engaged.store (true, std::memory_order_relaxed);
  660. counters.engagements.fetch_add (1, std::memory_order_relaxed);
  661. counters.aheadChannels.store (current->aheadChannelCount, std::memory_order_relaxed);
  662. counters.aheadTracks.store (current->aheadTrackCount, std::memory_order_relaxed);
  663. counters.boundary.store (current->liveSplit.slots, std::memory_order_relaxed);
  664. counters.window.store (targetFill.load (std::memory_order_relaxed) * stride, std::memory_order_relaxed);
  665. return true;
  666. }
  667. void RenderAhead::disengage (const RackState* state, bool dropped) noexcept
  668. {
  669. // (the thread is idle: the callback holds the renderer, or nothing runs)
  670. if (! engagedNow.load (std::memory_order_relaxed))
  671. return;
  672. running.store (false, std::memory_order_seq_cst);
  673. readIndex.store (writeIndex.load (std::memory_order_relaxed), std::memory_order_relaxed);
  674. live.adoptUnits (*ahead, current->aheadChannel.data(), current->aheadTrack.data());
  675. live.adoptAutomationValues (*ahead, current->aheadAutomations.data(), current->aheadAutomationCount);
  676. live.setSplit (nullptr);
  677. if (dropped && state != nullptr) // what the ahead part played past the dropped blocks never sounded: its notes end
  678. live.silenceChannels (*state, current->aheadChannel.data());
  679. live.setSplitBlock (nullptr);
  680. live.setWorkerPool (pool);
  681. ahead->setSplit (nullptr);
  682. ahead->setSplitBlock (nullptr);
  683. ahead->forgetState();
  684. // live notes still waiting for the part rendered ahead: the live renderer plays them now
  685. NoteEvent e;
  686. while (forward->pop (e))
  687. {
  688. localEvents->push (e);
  689. localPending = true;
  690. }
  691. aheadState = nullptr;
  692. aheadNext.store (nullptr, std::memory_order_release);
  693. aheadAck.store (nullptr, std::memory_order_release);
  694. pinned.store (0.0, std::memory_order_relaxed);
  695. drain.store (false, std::memory_order_relaxed);
  696. engagedNow.store (false, std::memory_order_release);
  697. counters.engaged.store (false, std::memory_order_relaxed);
  698. }
  699. void RenderAhead::dropRing (const RackState& state) noexcept
  700. {
  701. // (the callback holds the renderer) the ring's blocks are not the ones the callback plays: dropped. The ahead part
  702. // goes on from the live renderer's transport (in step again), its own notes ended (they were played past here).
  703. readIndex.store (writeIndex.load (std::memory_order_relaxed), std::memory_order_relaxed);
  704. ahead->adoptGlobals (live);
  705. ahead->adoptAutomationValues (live, nullptr, 0);
  706. ahead->silenceChannels (state, current->aheadChannel.data());
  707. modelStop.store (true, std::memory_order_release);
  708. counters.flushes.fetch_add (1, std::memory_order_relaxed);
  709. }
  710. void RenderAhead::retireHeld (SnapshotExchange<RackState>& exchange) noexcept
  711. {
  712. if (held == nullptr)
  713. return;
  714. if (engagedNow.load (std::memory_order_relaxed) && aheadAck.load (std::memory_order_acquire) == held)
  715. return; // still in use by the ahead renderer
  716. if (held == liveState)
  717. return;
  718. if (exchange.retire (held))
  719. held = nullptr;
  720. }
  721. // ---- the render-ahead thread ----------------------------------------------------------------------------------------
  722. bool RenderAhead::producing() const noexcept
  723. {
  724. if (! running.load (std::memory_order_acquire) || drain.load (std::memory_order_acquire) || modelStop.load (std::memory_order_acquire)
  725. || halted.load (std::memory_order_acquire))
  726. return false;
  727. const auto fill = writeIndex.load (std::memory_order_relaxed) - readIndex.load (std::memory_order_acquire);
  728. const auto target = tweakHoldSamples.load (std::memory_order_relaxed) > 0 ? 1 : targetFill.load (std::memory_order_relaxed);
  729. return fill < target && fill < entryCount.load (std::memory_order_relaxed) - 1;
  730. }
  731. void RenderAhead::wakeThread() noexcept
  732. {
  733. if (sleeping.exchange (false, std::memory_order_seq_cst))
  734. wake->release();
  735. }
  736. void RenderAhead::threadLoop (std::function<void()> onStart)
  737. {
  738. const ScopedFlushDenormals noDenormals;
  739. WorkerPool::nameCurrentThread ("LYNX render-ahead"); // (round 190kb)
  740. if (onStart)
  741. onStart();
  742. while (! quit.load (std::memory_order_acquire))
  743. {
  744. auto expected = 0;
  745. if (! producing() || ! owner.compare_exchange_strong (expected, 1, std::memory_order_acq_rel))
  746. {
  747. sleeping.store (true, std::memory_order_seq_cst);
  748. if (quit.load (std::memory_order_seq_cst) || (producing() && owner.load (std::memory_order_seq_cst) == 0))
  749. {
  750. sleeping.store (false, std::memory_order_seq_cst);
  751. continue;
  752. }
  753. wake->acquire();
  754. sleeping.store (false, std::memory_order_seq_cst);
  755. continue;
  756. }
  757. if (! producing() || aheadState == nullptr) // (the callback asked for a drain meanwhile)
  758. {
  759. owner.store (0, std::memory_order_release);
  760. continue;
  761. }
  762. if (const auto* s = aheadNext.load (std::memory_order_acquire); s != nullptr && s != aheadState)
  763. {
  764. aheadState = s;
  765. aheadAck.store (s, std::memory_order_release);
  766. }
  767. const auto w = writeIndex.load (std::memory_order_relaxed);
  768. const auto fill = w - readIndex.load (std::memory_order_acquire);
  769. auto& entry = *entries[(std::size_t) (w % entryCount.load (std::memory_order_relaxed))];
  770. const auto sb = planSubBlock (model, nextPosition, nextDone, transportTps (ahead->currentBpm(), model.sampleRate));
  771. // (serial while the window is comfortable: no hand-off cost; the workers when it runs thin)
  772. // (macOS: the workers may sit in the device's Audio Workgroup, round 190gt; render-ahead is not deadline work and
  773. // stays on its own thread there)
  774. #if defined(__APPLE__)
  775. const auto useWorkers = false;
  776. (void) fill;
  777. #else
  778. // (the workers when the window runs thin, or for good while one thread can't keep up — a serial block now and
  779. // then, with the window comfortable, measures that again)
  780. const auto heavy = serialLoad >= serialLimit && ! (jobsSinceSerial >= 256 && fill >= targetFill.load (std::memory_order_relaxed) / 2);
  781. // round 190px: while the UI starves ("Safe overloads"), the workers only when the ring is about to run dry
  782. const auto starving = uiGuard != nullptr && uiClock != nullptr && uiGuard->uiStarving (uiClock());
  783. const auto useWorkers = pool != nullptr && (starving ? fill < 2 : (fill < std::max (1, targetFill.load (std::memory_order_relaxed) / 3) || heavy));
  784. #endif
  785. const auto jobStart = ProcessTimes::now();
  786. const auto jobCpu = WorkerPool::threadCpuNs();
  787. renderJob (entry, *aheadState, sb.start, sb.samples, true, useWorkers);
  788. const auto jobNs = ProcessTimes::now() - jobStart;
  789. aheadCpuNs.fetch_add (WorkerPool::threadCpuNs() - jobCpu, std::memory_order_relaxed);
  790. aheadBusyNs.fetch_add (jobNs, std::memory_order_relaxed);
  791. counters.aheadNs.fetch_add (jobNs, std::memory_order_relaxed); // (round 190of: the split CPU meter)
  792. if (useWorkers)
  793. ++jobsSinceSerial;
  794. else if (sb.samples > 0 && model.sampleRate > 0.0)
  795. {
  796. const auto load = (double) jobNs * 1.0e-9 * model.sampleRate / sb.samples;
  797. serialLoad += 0.1 * (load - serialLoad);
  798. serialLoadSeen.store ((float) serialLoad, std::memory_order_relaxed);
  799. jobsSinceSerial = 0;
  800. }
  801. nextPosition = sb.next;
  802. nextDone = nextDone + sb.samples >= model.deviceBlock ? 0 : nextDone + sb.samples;
  803. modelStop.store (sb.last, std::memory_order_release);
  804. if (useWorkers && (fill + 1 >= targetFill.load (std::memory_order_relaxed) || sb.last))
  805. pool->park(); // (the window is full: the workers sleep instead of spinning)
  806. writeIndex.store (w + 1, std::memory_order_release);
  807. owner.store (0, std::memory_order_release);
  808. #if ! defined(__APPLE__)
  809. // round 190px (perf 7, fluidity): the UI starving while two or more blocks wait in the ring — the callbacks are
  810. // served — the thread gives the screen as long as the block took (0.5 … 4 ms), so a window refilled after an
  811. // overload no longer keeps both CPUs of a small PC busy (the samples rendered are the same; only when)
  812. if (starving && fill + 1 >= 2 && ! sb.last)
  813. {
  814. const auto ms = std::clamp ((double) jobNs * 1.0e-6, 0.5, 4.0);
  815. if (useWorkers)
  816. pool->park();
  817. OverloadGuard::sleepFor (ms);
  818. uiGuard->notePaced (ms);
  819. }
  820. #endif
  821. }
  822. }
  823. void RenderAhead::renderJob (Entry& entry, const RackState& state, double startTick, int samples, bool playing, bool useWorkers) noexcept
  824. {
  825. ahead->setWorkerPool (useWorkers ? pool : nullptr);
  826. aheadInput->recording.store (jobRecording, std::memory_order_relaxed);
  827. aheadInput->linearSong.store (jobLinear, std::memory_order_relaxed);
  828. aheadInput->patternOrigin.store (jobPatternOrigin, std::memory_order_relaxed);
  829. ahead->setTransportOptions (jobBlock.playTruncated, jobBlock.resetPlugins, jobBlock.userJumps);
  830. ahead->setTempoOverride (0.0);
  831. entry.block.chunks = 0;
  832. ahead->setSplitBlock (&entry.block);
  833. ahead->process (&state, playing, startTick, samples, scratchL.data(), scratchR.data(), forward.get(), aheadMeters.get(), nullptr);
  834. harvestMeters (entry);
  835. entry.start = startTick;
  836. entry.samples = samples;
  837. entry.playing = playing;
  838. }
  839. void RenderAhead::harvestMeters (Entry& entry) noexcept
  840. {
  841. auto& m = *aheadMeters;
  842. for (int i = 0; i < current->aheadTrackCount; ++i)
  843. {
  844. const auto t = current->aheadTrackList[(std::size_t) i];
  845. for (int side = 0; side < 2; ++side)
  846. {
  847. const auto a = m.takePeak (t, side), v = m.takeViewPeak (t, side), s = m.takeSessionPeak (t, side);
  848. entry.peaks[(std::size_t) (i * 2 + side)] = std::max ({ a, v, s });
  849. }
  850. float pl = 0.0f, pr = 0.0f;
  851. int frames = 0;
  852. m.takePowerSums (t, pl, pr, frames); // (round 190lr: zeros while nobody wants them)
  853. entry.power[(std::size_t) (i * 2)] = pl;
  854. entry.power[(std::size_t) (i * 2 + 1)] = pr;
  855. entry.powerFrames[(std::size_t) i] = frames;
  856. m.takeCorrelationSums (t, entry.correlation[(std::size_t) (i * 3)], entry.correlation[(std::size_t) (i * 3 + 1)],
  857. entry.correlation[(std::size_t) (i * 3 + 2)]); // (zeros while nobody wants them)
  858. }
  859. }
  860. void RenderAhead::replayMeters (const Entry& entry, MeterBank* meters) noexcept
  861. {
  862. if (meters == nullptr)
  863. return;
  864. const auto power = meters->powerWanted.load (std::memory_order_relaxed);
  865. aheadMeters->powerWanted.store (power, std::memory_order_relaxed); // (round 190lr: the part rendered ahead sums them too)
  866. const auto correlation = meters->correlationWanted.load (std::memory_order_relaxed);
  867. aheadMeters->correlationWanted.store (correlation, std::memory_order_relaxed); // (round 190qh: and these)
  868. for (int i = 0; i < current->aheadTrackCount; ++i)
  869. {
  870. const auto l = entry.peaks[(std::size_t) (i * 2)], r = entry.peaks[(std::size_t) (i * 2 + 1)];
  871. if (l > 0.0f || r > 0.0f)
  872. meters->accumulate (current->aheadTrackList[(std::size_t) i], l, r);
  873. if (power && entry.powerFrames[(std::size_t) i] > 0)
  874. meters->accumulatePower (current->aheadTrackList[(std::size_t) i], entry.power[(std::size_t) (i * 2)], entry.power[(std::size_t) (i * 2 + 1)],
  875. entry.powerFrames[(std::size_t) i]);
  876. if (correlation)
  877. meters->accumulateCorrelation (current->aheadTrackList[(std::size_t) i], entry.correlation[(std::size_t) (i * 3)],
  878. entry.correlation[(std::size_t) (i * 3 + 1)], entry.correlation[(std::size_t) (i * 3 + 2)]);
  879. }
  880. }
  881. void RenderAhead::noteLoad (double ns, int samples, bool playing) noexcept
  882. {
  883. if (samples <= 0 || sampleRate <= 0.0)
  884. return;
  885. const auto seconds = samples / sampleRate;
  886. const auto load = ns * 1.0e-9 / seconds;
  887. const auto a = std::min (1.0, seconds / 0.5); // (about half a second's average)
  888. loadAverage += a * (load - loadAverage);
  889. // one heavy block arms it until the average has had a second to settle (decays with it)
  890. spiked = playing && (load >= engageSpike || (spiked && loadAverage >= engageLoad * 0.5));
  891. idleFor = engagedNow.load (std::memory_order_relaxed) && loadAverage < idleLoad ? idleFor + seconds : 0.0;
  892. }
  893. bool RenderAhead::claimForCallback() noexcept
  894. {
  895. for (int spins = 0;; ++spins)
  896. {
  897. auto expected = 0;
  898. if (owner.compare_exchange_strong (expected, 2, std::memory_order_acq_rel))
  899. return true;
  900. WorkerPool::relax(); // the thread is finishing a block
  901. if ((spins & 1023) == 1023)
  902. std::this_thread::yield(); // (as WorkerPool's wait: never starve the thread of its core)
  903. }
  904. }
  905. void RenderAhead::releaseClaim() noexcept
  906. {
  907. owner.store (0, std::memory_order_release);
  908. }
  909. void RenderAhead::routeLiveEvents (LiveEventQueue* queue) noexcept
  910. {
  911. if (queue == nullptr)
  912. return;
  913. NoteEvent e;
  914. while (queue->pop (e))
  915. {
  916. if (e.channel < 0) // panic, Stop sound: both parts
  917. {
  918. localEvents->push (e);
  919. forward->push (e);
  920. continue;
  921. }
  922. if (e.channel < RackRenderer::maxChannels && current->aheadChannel[(std::size_t) e.channel] != 0)
  923. {
  924. forward->push (e); // played there at the next block it renders (a window late)...
  925. auto known = false;
  926. for (int i = 0; i < promotedCount; ++i)
  927. known = known || promotedChannels[(std::size_t) i] == e.channel;
  928. if (! known && promotedCount < (int) promotedChannels.size())
  929. {
  930. promotedChannels[(std::size_t) promotedCount++] = e.channel; // ... and the channel joins the live part
  931. promotionPending = true;
  932. counters.promoted.fetch_add (1, std::memory_order_relaxed);
  933. }
  934. continue;
  935. }
  936. localEvents->push (e);
  937. }
  938. }
  939. void RenderAhead::renderLive (const RackState& state, const Block& b, Entry& entry, float* left, float* right, MeterBank* meters) noexcept
  940. {
  941. live.setSplitBlock (&entry.block);
  942. live.process (&state, b.playing, b.startTick, b.samples, left, right, localEvents.get(), meters, nullptr);
  943. live.setSplitBlock (nullptr);
  944. replayMeters (entry, meters);
  945. counters.splitMismatches.store (live.splitMismatchCount(), std::memory_order_relaxed);
  946. }
  947. // ---- the callback --------------------------------------------------------------------------------------------------
  948. void RenderAhead::process (SnapshotExchange<RackState>& exchange, const Block& b, float* left, float* right, LiveEventQueue* liveQueue,
  949. MeterBank* meters, LiveEventQueue* moreLive) noexcept
  950. {
  951. const auto wall0 = ProcessTimes::now();
  952. const auto cpu0 = WorkerPool::threadCpuNs();
  953. processBlock (exchange, b, left, right, liveQueue, meters, moreLive);
  954. const auto cpu = (double) (WorkerPool::threadCpuNs() - cpu0);
  955. account ((double) (ProcessTimes::now() - wall0), cpu, b.samples, b.playing, liveState);
  956. // round 190of (P24): the live part's share (the callback's own time here) for the split CPU meter
  957. if (b.model != nullptr && b.samples > 0 && sampleRate > 0.0)
  958. {
  959. counters.liveNs.fetch_add (ProcessTimes::now() - wall0, std::memory_order_relaxed);
  960. counters.audioNs.fetch_add ((std::uint64_t) ((double) b.samples / sampleRate * 1.0e9), std::memory_order_relaxed);
  961. }
  962. }
  963. bool RenderAhead::renderAheadAllowed() const noexcept
  964. {
  965. return alwaysEngage || probe == Probe::on || probe == Probe::decidedOn;
  966. }
  967. RenderAhead::ProbeVerdict RenderAhead::probeVerdict (double cpuShareOff, double cpuShareOn, double overRateOff, double overRateOn) noexcept
  968. {
  969. ProbeVerdict v;
  970. const auto fewerOverruns = overRateOn <= overRateOff * probeOverrunGain && overRateOff > 0.0;
  971. const auto muchFewer = overRateOn <= overRateOff * probeMuchFewer && overRateOff > 0.0;
  972. const auto lessCpu = cpuShareOn <= cpuShareOff * probeCpuGain;
  973. // kept for a CPU win beyond the probe's measuring error (about ten points in render-ahead's favour against whole
  974. // runs) with no more overruns. Since the owner's 0.1.28 decision (`favourFewerOverruns`) also for clearly fewer
  975. // overruns at no more than probeCpuMargin more CPU (synth100, Exoplanet: 5-20x fewer), and since 0.1.30 for at
  976. // least 4x fewer at no more than probeCpuMarginMuchFewer.
  977. const auto cpuWin = lessCpu && overRateOn <= overRateOff;
  978. const auto forOverruns = favourFewerOverruns
  979. && ((fewerOverruns && cpuShareOn <= cpuShareOff * probeCpuMargin)
  980. || (muchFewer && cpuShareOn <= cpuShareOff * probeCpuMarginMuchFewer));
  981. v.keep = cpuWin || forOverruns;
  982. v.forOverruns = v.keep && ! cpuWin;
  983. return v;
  984. }
  985. void RenderAhead::account (double wallNs, double cpuNs, int samples, bool playing, const RackState* state) noexcept
  986. {
  987. if (alwaysEngage || samples <= 0 || sampleRate <= 0.0)
  988. return;
  989. const auto seconds = samples / sampleRate;
  990. const auto over = wallNs * 1.0e-9 > seconds;
  991. // the rack's CPU in this block: the callback's here, the workers' and the thread's since the last block
  992. const auto workers = pool != nullptr ? pool->cpuNs() : 0, aheadNs = aheadCpuNs.load (std::memory_order_relaxed);
  993. const auto rackNs = cpuNs + (double) (workers - lastWorkersCpu) + (double) (aheadNs - lastAheadCpu);
  994. lastWorkersCpu = workers;
  995. lastAheadCpu = aheadNs;
  996. if (! playing)
  997. return;
  998. recentOverruns += std::min (1.0, seconds / 2.0) * ((over ? 1.0 / seconds : 0.0) - recentOverruns);
  999. if (! engagedNow.load (std::memory_order_relaxed))
  1000. workShare += std::min (1.0, seconds / 2.0) * (live.lastWorkShare() - workShare);
  1001. const auto engaged = engagedNow.load (std::memory_order_relaxed);
  1002. const auto changed = state != nullptr && state->serial != decidedState;
  1003. switch (probe)
  1004. {
  1005. case Probe::none:
  1006. if (! engaged && (recentOverruns >= probeTriggerOverruns || loadAverage >= probeTriggerLoad) && workShare <= probeMaxWork)
  1007. {
  1008. probe = Probe::off;
  1009. probeLeft = probeSeconds;
  1010. probeRound = 0;
  1011. cpuOff = cpuOn = secondsOff = secondsOn = 0.0;
  1012. overOff = overOn = 0;
  1013. counters.probes.fetch_add (1, std::memory_order_relaxed);
  1014. }
  1015. break;
  1016. case Probe::off:
  1017. if (engaged) // (still draining from the last "on" window)
  1018. break;
  1019. cpuOff += rackNs;
  1020. secondsOff += seconds;
  1021. overOff += over ? 1 : 0;
  1022. if ((probeLeft -= seconds) <= 0.0)
  1023. {
  1024. probe = Probe::on;
  1025. probeLeft = probeSeconds;
  1026. warmupLeft = probeWarmup;
  1027. }
  1028. break;
  1029. case Probe::on:
  1030. if (! engaged)
  1031. {
  1032. // it could not start (nothing to render ahead, backed off): off it is
  1033. if ((warmupLeft -= seconds) < -1.0)
  1034. {
  1035. probe = Probe::decidedOff;
  1036. decidedLeft = decidedSeconds;
  1037. decidedState = state != nullptr ? state->serial : 0;
  1038. counters.keptOff.fetch_add (1, std::memory_order_relaxed);
  1039. }
  1040. break;
  1041. }
  1042. if ((warmupLeft -= seconds) > 0.0) // (its first blocks fill the window)
  1043. break;
  1044. cpuOn += rackNs;
  1045. secondsOn += seconds;
  1046. overOn += over ? 1 : 0;
  1047. if ((probeLeft -= seconds) <= 0.0)
  1048. {
  1049. if (++probeRound < probeRounds)
  1050. {
  1051. probe = Probe::off;
  1052. probeLeft = probeSeconds;
  1053. drain.store (true, std::memory_order_release); // (off again, cleanly)
  1054. break;
  1055. }
  1056. const auto cpuShareOff = secondsOff > 0.0 ? cpuOff * 1.0e-9 / secondsOff : 0.0;
  1057. const auto cpuShareOn = secondsOn > 0.0 ? cpuOn * 1.0e-9 / secondsOn : 0.0;
  1058. const auto overRateOff = secondsOff > 0.0 ? overOff / secondsOff : 0.0, overRateOn = secondsOn > 0.0 ? overOn / secondsOn : 0.0;
  1059. counters.probeCpuOff.store ((float) (100.0 * cpuShareOff), std::memory_order_relaxed);
  1060. counters.probeCpuOn.store ((float) (100.0 * cpuShareOn), std::memory_order_relaxed);
  1061. counters.probeOverOff.store ((float) (60.0 * overRateOff), std::memory_order_relaxed);
  1062. counters.probeOverOn.store ((float) (60.0 * overRateOn), std::memory_order_relaxed);
  1063. const auto verdict = probeVerdict (cpuShareOff, cpuShareOn, overRateOff, overRateOn);
  1064. const auto keep = verdict.keep;
  1065. probe = keep ? Probe::decidedOn : Probe::decidedOff;
  1066. // (a project that keeps losing is probed less and less often: the probe's own "on" windows cost)
  1067. decidedLeft = keep ? decidedSeconds : offHold;
  1068. offHold = keep ? decidedSeconds : std::min (600.0, offHold * 2.0);
  1069. decidedState = state != nullptr ? state->serial : 0;
  1070. (keep ? counters.keptOn : counters.keptOff).fetch_add (1, std::memory_order_relaxed);
  1071. if (verdict.forOverruns)
  1072. counters.keptForOverruns.fetch_add (1, std::memory_order_relaxed);
  1073. if (! keep)
  1074. drain.store (true, std::memory_order_release);
  1075. }
  1076. break;
  1077. case Probe::decidedOn:
  1078. case Probe::decidedOff:
  1079. if ((decidedLeft -= seconds) <= 0.0 || changed)
  1080. {
  1081. probe = Probe::none; // (measured again when the load asks)
  1082. if (engaged)
  1083. drain.store (true, std::memory_order_release);
  1084. }
  1085. break;
  1086. }
  1087. }
  1088. void RenderAhead::processBlock (SnapshotExchange<RackState>& exchange, const Block& b, float* left, float* right, LiveEventQueue* liveQueue,
  1089. MeterBank* meters, LiveEventQueue* moreLive) noexcept
  1090. {
  1091. counters.blocks.fetch_add (1, std::memory_order_relaxed);
  1092. if (targets != nullptr)
  1093. targets->read (targetChannels, targetChannelCount, targetTracks, targetTrackCount, targetVersion);
  1094. // the tweak hold (round 190gq): while edits keep coming the window holds at one block
  1095. if (targets != nullptr && targets->tweakCount() != lastTweaks)
  1096. {
  1097. lastTweaks = targets->tweakCount();
  1098. tweakHoldSamples.store ((int) (sampleRate * tweakHoldMs / 1000), std::memory_order_relaxed);
  1099. }
  1100. else if (const auto hold = tweakHoldSamples.load (std::memory_order_relaxed); hold > 0)
  1101. tweakHoldSamples.store (std::max (0, hold - b.samples), std::memory_order_relaxed);
  1102. const auto* m = b.model;
  1103. if (m != nullptr && m->deviceBlock != lastBlockSize)
  1104. {
  1105. lastBlockSize = m->deviceBlock;
  1106. stableSamples = 0;
  1107. }
  1108. else if (m != nullptr)
  1109. stableSamples = std::min (stableSamples + b.samples, 1 << 30);
  1110. const auto want = renderAheadOption().load (std::memory_order_relaxed) && m != nullptr && m->predictable && b.metering && b.tempoOverride <= 0.0
  1111. && b.playing && b.samples > 0 && m->deviceBlock > 0 && m->deviceBlock <= maxBlock && ! audioPool.empty();
  1112. // (a device that changes its block size now and then: render-ahead starts again once it has held for half a second)
  1113. const auto steady = stableSamples >= (int) (sampleRate * 0.5) || counters.engagements.load (std::memory_order_relaxed) == 0;
  1114. if (! engagedNow.load (std::memory_order_relaxed))
  1115. {
  1116. const auto* state = exchange.acquire();
  1117. retireHeld (exchange);
  1118. if (! b.playing)
  1119. {
  1120. promotedCount = 0; // (the channels played live join the live part until playback stops)
  1121. stickyOn = false;
  1122. }
  1123. auto engaged = false;
  1124. // (light projects: no deadline to ease, render-ahead would only add its thread)
  1125. // (backed off: not again until the time is up or the project changes)
  1126. if (backoffLeft > 0.0 && b.playing)
  1127. backoffLeft = state != nullptr && state->serial != backoffState ? 0.0 : std::max (0.0, backoffLeft - b.samples / sampleRate);
  1128. // (the probe's "on" window or its verdict; tests: whenever it can)
  1129. const auto needed = renderAheadAllowed() && (alwaysEngage || backoffLeft <= 0.0);
  1130. if (want && steady && needed && state != nullptr && ! state->launchers && held == nullptr)
  1131. {
  1132. // (a state with nothing to render ahead is not looked at again until it, or the live targets, change)
  1133. const auto blocked = engageBlocked && blockedSerial == state->serial && blockedTargets == targetVersion && blockedLiveSeed == promotedCount;
  1134. if (! blocked)
  1135. {
  1136. engaged = engage (*state, b);
  1137. stickyOn = stickyOn || engaged;
  1138. engageBlocked = ! engaged;
  1139. blockedSerial = state->serial;
  1140. blockedTargets = targetVersion;
  1141. blockedLiveSeed = promotedCount;
  1142. }
  1143. }
  1144. if (! engaged)
  1145. {
  1146. const auto start = ProcessTimes::now();
  1147. if (localPending) // (live notes a disengage handed back: they play first, then the queues' own)
  1148. {
  1149. localPending = false;
  1150. for (auto* q : { liveQueue, moreLive })
  1151. if (q != nullptr)
  1152. for (NoteEvent e; q->pop (e);)
  1153. localEvents->push (e);
  1154. live.process (state, b.playing, b.startTick, b.samples, left, right, localEvents.get(), meters, nullptr);
  1155. }
  1156. else
  1157. live.process (state, b.playing, b.startTick, b.samples, left, right, liveQueue, meters, moreLive);
  1158. liveState = state;
  1159. noteLoad ((double) (ProcessTimes::now() - start), b.samples, b.playing);
  1160. return;
  1161. }
  1162. }
  1163. // --- engaged
  1164. routeLiveEvents (liveQueue);
  1165. routeLiveEvents (moreLive);
  1166. const auto hardStop = ! b.playing || m == nullptr || ! m->predictable || ! b.metering || b.tempoOverride > 0.0 || b.samples <= 0
  1167. || m->deviceBlock != stride || audioPool.empty();
  1168. if (hardStop)
  1169. {
  1170. // Stop, an export, an external clock, a device change: what was rendered ahead is dropped and the live renderer
  1171. // renders everything again
  1172. claimForCallback();
  1173. const auto dropped = writeIndex.load (std::memory_order_relaxed) != readIndex.load (std::memory_order_relaxed);
  1174. disengage (liveState, dropped);
  1175. releaseClaim();
  1176. if (! b.playing)
  1177. promotedCount = 0;
  1178. const auto* state = exchange.acquire();
  1179. retireHeld (exchange);
  1180. localPending = false;
  1181. live.process (state, b.playing, b.startTick, b.samples, left, right, localEvents.get(), meters, nullptr);
  1182. liveState = state;
  1183. return;
  1184. }
  1185. if (! want || ! renderAheadAllowed()) // the option switched off while playing, the probe's "off": drained, then off
  1186. drain.store (true, std::memory_order_release);
  1187. // a new snapshot: the live part takes it now when the part rendered ahead can go on as it is (same units, same
  1188. // timeline); else both take it together once the ring has drained
  1189. if (held == nullptr && ! pendingSync && exchange.hasIncoming())
  1190. {
  1191. tweakHoldSamples.store ((int) (sampleRate * tweakHoldMs / 1000), std::memory_order_relaxed);
  1192. const RackState* previous = nullptr;
  1193. const auto* s2 = exchange.acquireHolding (previous);
  1194. if (s2 != liveState && previous != nullptr)
  1195. {
  1196. held = previous;
  1197. const auto& s1 = *liveState;
  1198. auto compatible = s2->song.channels.size() == s1.song.channels.size() && s2->song.mixer.size() == s1.song.mixer.size()
  1199. && ! s2->channelsMoved && s2->sampleRate == s1.sampleRate && ! s2->launchers && s2->song.bpm == s1.song.bpm
  1200. && s2->song.mode == s1.song.mode && s2->song.currentPattern == s1.song.currentPattern && s2->tempoMap == s1.tempoMap
  1201. && s2->tempoAutomation == s1.tempoAutomation && s2->song.beatsPerBar == s1.song.beatsPerBar
  1202. && s2->schedule.songLength == s1.schedule.songLength;
  1203. if (compatible)
  1204. compatible = computePartition (*s2, b, *next) && next->sameUnits (*current);
  1205. if (compatible)
  1206. {
  1207. liveState = s2;
  1208. aheadNext.store (s2, std::memory_order_release);
  1209. wakeThread(); // (it takes the new state at its next block, even with the ring full)
  1210. counters.statesSwapped.fetch_add (1, std::memory_order_relaxed);
  1211. }
  1212. else
  1213. {
  1214. pendingSync = true;
  1215. drain.store (true, std::memory_order_release);
  1216. }
  1217. }
  1218. }
  1219. retireHeld (exchange);
  1220. // the live targets, a channel played live, an editor's live meters: a new partition at the next sync
  1221. {
  1222. static_assert (editorPollSamples > 0);
  1223. auto partitionChanged = false;
  1224. if (promotionPending || targetVersion != partitionTargets)
  1225. {
  1226. promotionPending = false;
  1227. partitionTargets = targetVersion;
  1228. partitionChanged = true;
  1229. }
  1230. editorPoll += b.samples;
  1231. if (editorPoll >= editorPollSamples)
  1232. {
  1233. editorPoll = 0;
  1234. partitionChanged = true;
  1235. }
  1236. if (partitionChanged && ! drain.load (std::memory_order_relaxed))
  1237. {
  1238. const auto ok = computePartition (*liveState, b, *next);
  1239. if (! ok || ! next->sameUnits (*current) || next->editorHash != current->editorHash)
  1240. {
  1241. if (! ok || ! next->sameUnits (*current))
  1242. {
  1243. drain.store (true, std::memory_order_release);
  1244. counters.partitionChanges.fetch_add (1, std::memory_order_relaxed);
  1245. }
  1246. else
  1247. current->editorHash = next->editorHash;
  1248. }
  1249. }
  1250. }
  1251. // the transport options and the input's flags the ahead part renders with: a change waits for a sync
  1252. {
  1253. const auto recording = liveInput != nullptr && liveInput->recording.load (std::memory_order_relaxed);
  1254. const auto linear = liveInput != nullptr && liveInput->linearSong.load (std::memory_order_relaxed);
  1255. const auto origin = liveInput != nullptr ? liveInput->patternOrigin.load (std::memory_order_relaxed) : -1.0;
  1256. if (recording != jobRecording || linear != jobLinear || origin != jobPatternOrigin || b.playTruncated != jobBlock.playTruncated
  1257. || b.resetPlugins != jobBlock.resetPlugins || (m != nullptr && ! (*m == lastModel)))
  1258. drain.store (true, std::memory_order_release);
  1259. }
  1260. // --- this block's part rendered ahead: from the ring, from the thread finishing it, or rendered here
  1261. Entry* entry = nullptr;
  1262. auto fromRing = false;
  1263. auto claimed = false;
  1264. for (;;)
  1265. {
  1266. const auto r = readIndex.load (std::memory_order_relaxed);
  1267. const auto w = writeIndex.load (std::memory_order_acquire);
  1268. if (r != w)
  1269. {
  1270. auto& front = *entries[(std::size_t) (r % entryCount.load (std::memory_order_relaxed))];
  1271. if (front.playing == b.playing && front.start == b.startTick && front.samples == b.samples)
  1272. {
  1273. entry = &front;
  1274. fromRing = true;
  1275. break;
  1276. }
  1277. // not the block the callback plays (a jump, Stop, a change of the loop...): dropped
  1278. claimForCallback();
  1279. claimed = true;
  1280. dropRing (*liveState);
  1281. break;
  1282. }
  1283. if (owner.load (std::memory_order_acquire) == 1)
  1284. {
  1285. // the thread is rendering it: wait for it (the renderer can't do two blocks at once)
  1286. counters.waited.fetch_add (1, std::memory_order_relaxed);
  1287. if (tweakHoldSamples.load (std::memory_order_relaxed) == 0) // (a drag holds the window at one block: waits are expected)
  1288. ++windowWaits;
  1289. for (int spins = 0; owner.load (std::memory_order_acquire) == 1; ++spins)
  1290. {
  1291. WorkerPool::relax();
  1292. if ((spins & 1023) == 1023)
  1293. std::this_thread::yield();
  1294. }
  1295. continue;
  1296. }
  1297. claimForCallback();
  1298. claimed = true;
  1299. if (readIndex.load (std::memory_order_relaxed) != writeIndex.load (std::memory_order_acquire))
  1300. {
  1301. releaseClaim(); // (it published one meanwhile)
  1302. claimed = false;
  1303. continue;
  1304. }
  1305. break;
  1306. }
  1307. if (entry == nullptr)
  1308. {
  1309. // the ring is empty and the callback holds the ahead renderer: a sync point
  1310. if (drain.load (std::memory_order_acquire))
  1311. {
  1312. counters.drains.fetch_add (1, std::memory_order_relaxed);
  1313. // both parts stop here together; the live renderer renders this block alone, and render-ahead starts again
  1314. // at the next block with the new snapshot / partition / options
  1315. disengage (liveState, false);
  1316. releaseClaim();
  1317. pendingSync = false;
  1318. engageBlocked = false;
  1319. const auto* state = exchange.acquire();
  1320. retireHeld (exchange);
  1321. if (std::exchange (backoffPending, false) && state != nullptr)
  1322. {
  1323. backoffLeft = backoffSeconds; // (backed off: off for a while, or until the project changes)
  1324. backoffState = state->serial;
  1325. }
  1326. localPending = false;
  1327. live.process (state, b.playing, b.startTick, b.samples, left, right, localEvents.get(), meters, nullptr);
  1328. liveState = state;
  1329. return;
  1330. }
  1331. // render the part rendered ahead here, now (the start, after a drop, or the thread fell behind)
  1332. if (const auto* s = aheadNext.load (std::memory_order_acquire); s != nullptr && s != aheadState)
  1333. {
  1334. aheadState = s;
  1335. aheadAck.store (s, std::memory_order_release);
  1336. }
  1337. auto& slot = *entries[(std::size_t) (writeIndex.load (std::memory_order_relaxed) % entryCount.load (std::memory_order_relaxed))];
  1338. jobBlock = b; // (the transport options as they are now: a user's jump chases in both parts)
  1339. renderJob (slot, *aheadState, b.startTick, b.samples, b.playing, pool != nullptr);
  1340. entry = &slot;
  1341. counters.inline_.fetch_add (1, std::memory_order_relaxed);
  1342. if (tweakHoldSamples.load (std::memory_order_relaxed) == 0)
  1343. ++windowWaits;
  1344. // the thread goes on after this block: where the callback will put the position
  1345. const auto sb = planSubBlock (*m, b.startTick, m->offset, b.tps);
  1346. if (sb.start == b.startTick && sb.samples == b.samples)
  1347. {
  1348. nextPosition = sb.next;
  1349. nextDone = m->offset + b.samples >= m->deviceBlock ? 0 : m->offset + b.samples;
  1350. modelStop.store (sb.last, std::memory_order_release);
  1351. }
  1352. else
  1353. modelStop.store (true, std::memory_order_release); // (the transport moved as the model does not: inline until a sync)
  1354. }
  1355. else
  1356. counters.fromRing.fetch_add (1, std::memory_order_relaxed);
  1357. const auto liveStart = ProcessTimes::now();
  1358. renderLive (*liveState, b, *entry, left, right, meters);
  1359. pinned.store (live.currentBpm(), std::memory_order_relaxed);
  1360. // the whole rack's load while on (the live part + what the thread rendered since the last block): a long quiet
  1361. // stretch hands everything back to the callback
  1362. noteLoad ((double) (ProcessTimes::now() - liveStart + aheadBusyNs.exchange (0, std::memory_order_relaxed)), b.samples, true);
  1363. if (! alwaysEngage && idleFor >= idleSeconds && ! drain.load (std::memory_order_relaxed))
  1364. {
  1365. idleFor = 0.0;
  1366. stickyOn = false;
  1367. drain.store (true, std::memory_order_release); // (disengaged cleanly at the next sync)
  1368. engageBlocked = false;
  1369. }
  1370. // the back-off rules
  1371. {
  1372. const auto seconds = b.samples / sampleRate;
  1373. heavyFor = serialLoadSeen.load (std::memory_order_relaxed) >= serialLimit ? heavyFor + seconds : 0.0;
  1374. ++windowBlocks;
  1375. windowSeconds += seconds;
  1376. // (only once the probe has kept it on: the probe itself measures the "on" window)
  1377. auto backOff = false;
  1378. if (windowSeconds >= backoffWindowSeconds)
  1379. {
  1380. backOff = windowWaits > backoffWaitShare * windowBlocks;
  1381. windowBlocks = windowWaits = 0;
  1382. windowSeconds = 0.0;
  1383. }
  1384. if (backOff && probe == Probe::decidedOn && ! alwaysEngage && ! drain.load (std::memory_order_relaxed))
  1385. {
  1386. heavyFor = 0.0;
  1387. stickyOn = false;
  1388. backoffPending = true;
  1389. drain.store (true, std::memory_order_release);
  1390. engageBlocked = false;
  1391. counters.backoffs.fetch_add (1, std::memory_order_relaxed);
  1392. probe = Probe::none; // (the window stopped absorbing anything: measured again)
  1393. }
  1394. }
  1395. if (fromRing)
  1396. readIndex.store (readIndex.load (std::memory_order_relaxed) + 1, std::memory_order_release);
  1397. if (claimed)
  1398. {
  1399. if (pool != nullptr && (drain.load (std::memory_order_relaxed) || modelStop.load (std::memory_order_relaxed)))
  1400. pool->park();
  1401. releaseClaim();
  1402. }
  1403. if (! drain.load (std::memory_order_relaxed))
  1404. running.store (true, std::memory_order_release);
  1405. // the thread refills the ring from half the window: at small buffers one wake-up every few blocks, not one per block
  1406. const auto fill = writeIndex.load (std::memory_order_relaxed) - readIndex.load (std::memory_order_relaxed);
  1407. const auto target = tweakHoldSamples.load (std::memory_order_relaxed) > 0 ? 1 : targetFill.load (std::memory_order_relaxed);
  1408. if (claimed || fill <= target / 2)
  1409. wakeThread();
  1410. }
  1411. } // namespace lynx