AudioEngine.cpp 69 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802
  1. #include "engine/AudioEngine.h"
  2. #include "platform/Paths.h"
  3. #include "engine/FlStudio.h"
  4. #include <map>
  5. #include "engine/Text.h"
  6. #include "ui/I18n.h"
  7. #include "core/FlpImport.h"
  8. #include "core/Instruments.h"
  9. #include "core/Dither.h"
  10. #include "core/SoftClip.h"
  11. #include "engine/ChannelRackProcessor.h"
  12. #include "engine/DllAsioDevice.h"
  13. #include "engine/Metronome.h"
  14. #include "core/NoteTools.h"
  15. #include "engine/PreviewPlayer.h"
  16. #include "flp/Flp.h"
  17. #if JUCE_WINDOWS
  18. #include <windows.h>
  19. #elif JUCE_MAC
  20. #include <pthread.h>
  21. #include <sys/qos.h>
  22. #elif JUCE_LINUX || JUCE_BSD
  23. #include <pthread.h>
  24. #include <sched.h>
  25. #endif
  26. namespace lynx
  27. {
  28. using IONode = juce::AudioProcessorGraph::AudioGraphIOProcessor;
  29. // The FL Studio installation (registry, else the usual folders) to resolve %FLStudio...%.
  30. FlPathRoots findFlStudioRoots()
  31. {
  32. FlPathRoots roots;
  33. const auto fl = findFlStudio();
  34. if (fl.installDir.isDirectory())
  35. {
  36. roots.factoryData = fl.installDir.getFullPathName().toStdString();
  37. roots.data = fl.installDir.getChildFile ("Data").getFullPathName().toStdString();
  38. }
  39. if (fl.userData.isDirectory())
  40. roots.userData = fl.userData.getFullPathName().toStdString();
  41. roots.home = juce::File::getSpecialLocation (juce::File::userHomeDirectory).getFullPathName().toStdString();
  42. return roots;
  43. }
  44. namespace
  45. {
  46. // Audio workers with real-time priority (MMCSS "Pro Audio" on Windows, like the driver; QoS class on macOS; SCHED_FIFO
  47. // on Linux when allowed).
  48. void raiseAudioThreadPriority()
  49. {
  50. #if JUCE_WINDOWS
  51. using AvSet = void* (__stdcall*) (const wchar_t*, unsigned long*);
  52. static const auto avSet = [] () -> AvSet {
  53. if (auto* avrt = LoadLibraryW (L"avrt.dll"))
  54. return reinterpret_cast<AvSet> (reinterpret_cast<void*> (GetProcAddress (avrt, "AvSetMmThreadCharacteristicsW")));
  55. return nullptr;
  56. }();
  57. // FL's audio worker threads also raise their MMCSS priority to "high" (FLEngine_x64.dll, REA round 87)
  58. using AvPriority = int (__stdcall*) (void*, int);
  59. static const auto avPriority = [] () -> AvPriority {
  60. if (auto* avrt = LoadLibraryW (L"avrt.dll"))
  61. return reinterpret_cast<AvPriority> (reinterpret_cast<void*> (GetProcAddress (avrt, "AvSetMmThreadPriority")));
  62. return nullptr;
  63. }();
  64. unsigned long task = 0;
  65. if (auto* handle = avSet != nullptr ? avSet (L"Pro Audio", &task) : nullptr)
  66. {
  67. if (avPriority != nullptr)
  68. avPriority (handle, 1 /* AVRT_PRIORITY_HIGH */);
  69. }
  70. else
  71. SetThreadPriority (GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL);
  72. #elif JUCE_MAC
  73. // the highest quality-of-service class: scheduled like the UI's own interactive work, on the performance cores
  74. pthread_set_qos_class_self_np (QOS_CLASS_USER_INTERACTIVE, 0);
  75. #elif JUCE_LINUX || JUCE_BSD
  76. // real-time FIFO scheduling when the user may have it (audio group / rtkit limits, as JACK and PipeWire set up);
  77. // below the usual JACK/PipeWire audio thread priorities. Without the permission the thread stays as it is.
  78. sched_param param {};
  79. param.sched_priority = juce::jlimit (sched_get_priority_min (SCHED_FIFO), sched_get_priority_max (SCHED_FIFO), 70);
  80. pthread_setschedparam (pthread_self(), SCHED_FIFO, &param);
  81. #endif
  82. }
  83. int workerCount()
  84. {
  85. // diagnostics: LYNX_WORKERS=n fixes the number of extra threads
  86. if (const auto forced = juce::SystemStats::getEnvironmentVariable ("LYNX_WORKERS", {}); forced.isNotEmpty())
  87. return juce::jlimit (0, 31, forced.getIntValue());
  88. // the audio thread works too; leave one core free for the UI
  89. const auto cores = (int) std::thread::hardware_concurrency();
  90. return juce::jlimit (0, 7, cores - 2);
  91. }
  92. juce::File midiSettingsFile() { return PluginHost::settingsFolder().getChildFile ("midi-settings.txt"); }
  93. juce::File audioDeviceFile() { return PluginHost::settingsFolder().getChildFile ("audio-device.xml"); }
  94. } // namespace
  95. // Saves the audio device setup whenever it changes (Settings › Audio, the setup wizard, a driver's own panel), so
  96. // the next start opens the same device.
  97. struct AudioEngine::DeviceStateSaver final : public juce::ChangeListener
  98. {
  99. explicit DeviceStateSaver (AudioEngine& e) : engine (e) { engine.deviceManager.addChangeListener (this); }
  100. ~DeviceStateSaver() override { engine.deviceManager.removeChangeListener (this); }
  101. void changeListenerCallback (juce::ChangeBroadcaster*) override { engine.saveAudioDeviceState(); }
  102. AudioEngine& engine;
  103. };
  104. void AudioEngine::saveAudioDeviceState()
  105. {
  106. if (auto xml = deviceManager.createStateXml())
  107. xml->writeTo (audioDeviceFile());
  108. }
  109. void AudioEngine::restoreAudioDeviceState (const juce::XmlElement* state)
  110. {
  111. deviceStateSaver = nullptr;
  112. if (state != nullptr)
  113. state->writeTo (audioDeviceFile());
  114. else
  115. audioDeviceFile().deleteFile();
  116. }
  117. AudioEngine::AudioEngine (bool openAudioDevice)
  118. : workers (std::make_unique<WorkerPool> (workerCount(), raiseAudioThreadPriority)),
  119. song (Song::makeDefault())
  120. {
  121. inputSlot.fill (-1);
  122. publishSong();
  123. buildInitialGraph();
  124. if (openAudioDevice)
  125. {
  126. player.setProcessor (&graph);
  127. // LYNX ASIO without installation: lynx-asio.dll next to LYNX.exe, when it is not registered (REA round 106)
  128. if (auto lynxAsio = makeBuiltInLynxAsioType())
  129. {
  130. deviceManager.getAvailableDeviceTypes(); // the standard types first
  131. deviceManager.addAudioDeviceType (std::move (lynxAsio));
  132. }
  133. // 0 inputs, 2 outputs; the device of the last session (Settings › Audio) if it is still there, else the default.
  134. const auto saved = juce::XmlDocument::parse (audioDeviceFile());
  135. auto fresh = saved == nullptr;
  136. if (deviceManager.initialise (0, 2, saved.get(), true).isNotEmpty() && saved != nullptr)
  137. {
  138. deviceManager.initialise (0, 2, nullptr, true);
  139. fresh = true;
  140. }
  141. if (fresh)
  142. chooseSafeBufferSize(); // no saved setup: a buffer with room for heavy projects (Settings › Audio changes it)
  143. deviceManager.addAudioCallback (this);
  144. if (rackProcessor != nullptr)
  145. rackProcessor->getRenderer().setProfiling (true); // per-unit CPU for the CPU meter and the glitch log
  146. deviceStateSaver = std::make_unique<DeviceStateSaver> (*this);
  147. midiPrefs = midiPrefsShared = prefs::MidiPrefs::fromText (midiSettingsFile().loadFileAsString().toStdString());
  148. prefetcher = std::make_unique<StreamPrefetcher> (transport);
  149. prefetcher->update (song, samples);
  150. enableAllMidiInputs();
  151. deviceManager.addMidiInputDeviceCallback ({}, this); // {} = all inputs enabled
  152. midiDevicesChanged = juce::MidiDeviceListConnection::make ([this] { enableAllMidiInputs(); });
  153. }
  154. startTimerHz (30); // recording and collection of retired snapshots
  155. }
  156. AudioEngine::~AudioEngine()
  157. {
  158. stopTimer();
  159. {
  160. const juce::SpinLock::ScopedLockType lock (takeLock);
  161. for (auto& take : takes)
  162. take.writer = nullptr; // closes the WAVs of the takes in progress (they stay in the recordings folder)
  163. takeCount = 0;
  164. }
  165. recordThread.stopThread (2000);
  166. prefetcher = nullptr;
  167. midiDevicesChanged = {};
  168. deviceStateSaver = nullptr;
  169. deviceManager.removeMidiInputDeviceCallback ({}, this);
  170. deviceManager.removeAudioCallback (this);
  171. player.setProcessor (nullptr);
  172. graph.clear(); // the nodes reference rackExchange and transport
  173. }
  174. void AudioEngine::buildInitialGraph()
  175. {
  176. // The output node inherits the graph's channel count at the moment it is created.
  177. // Without this the graph still has 0 outputs and JUCE silently rejects the connections.
  178. graph.setPlayConfigDetails (0, 2, transport.sampleRate.load(), 512);
  179. auto output = graph.addNode (std::make_unique<IONode> (IONode::audioOutputNode));
  180. auto rack = graph.addNode (std::make_unique<ChannelRackProcessor> (transport, rackExchange, liveEvents, midiEvents, meters, workers.get()));
  181. rackProcessor = dynamic_cast<ChannelRackProcessor*> (rack->getProcessor());
  182. if (rackProcessor != nullptr)
  183. rackProcessor->setLiveInput (&liveInput);
  184. auto metronome = graph.addNode (std::make_unique<Metronome> (transport));
  185. auto previewOwned = std::make_unique<PreviewPlayer>();
  186. preview = previewOwned.get();
  187. auto previewNode = graph.addNode (std::move (previewOwned));
  188. for (int channel = 0; channel < 2; ++channel)
  189. {
  190. graph.addConnection ({ { rack->nodeID, channel }, { output->nodeID, channel } });
  191. graph.addConnection ({ { metronome->nodeID, channel }, { output->nodeID, channel } });
  192. graph.addConnection ({ { previewNode->nodeID, channel }, { output->nodeID, channel } });
  193. }
  194. jassert (graph.getConnections().size() == 6);
  195. }
  196. float AudioEngine::renderOffline (const RenderOptions& options)
  197. {
  198. const auto seconds = options.seconds;
  199. const auto sampleRate = options.sampleRate;
  200. auto* output = options.output;
  201. const auto& progress = options.progress;
  202. const auto tailSeconds = options.tailSeconds;
  203. const auto trimSamples = options.trimSamples;
  204. std::optional<Dither> dither;
  205. if (options.ditherBits > 0)
  206. dither.emplace (options.ditherBits, options.ditherShaping);
  207. constexpr int blockSize = 512;
  208. constexpr float silence = 3.0e-5f; // ~ -90 dB
  209. setOfflineRendering (true); // instruments with FL render-quality settings use them (Sytrus)
  210. transport.sampleRate.store (sampleRate);
  211. graph.setPlayConfigDetails (0, 2, sampleRate, blockSize);
  212. graph.prepareToPlay (sampleRate, blockSize);
  213. if (rackProcessor != nullptr)
  214. rackProcessor->setMetering (false); // nobody looks at the meters during the render
  215. play();
  216. juce::AudioBuffer<float> buffer (2, blockSize);
  217. juce::MidiBuffer midi;
  218. float peak = 0.0f;
  219. const auto trim = (std::int64_t) juce::jmax (0, trimSamples);
  220. const auto musicSamples = (std::int64_t) (seconds * sampleRate) + trim;
  221. const auto totalSamples = musicSamples + (std::int64_t) (juce::jmax (0.0, tailSeconds) * sampleRate);
  222. std::int64_t quietSamples = 0;
  223. bool cancelled = false;
  224. lastRenderStats = {};
  225. for (std::int64_t done = 0; done < totalSamples; done += blockSize)
  226. {
  227. const auto n = (int) juce::jmin<std::int64_t> (blockSize, totalSamples - done);
  228. juce::AudioBuffer<float> view (buffer.getArrayOfWritePointers(), 2, n);
  229. view.clear();
  230. const auto before = juce::Time::getMillisecondCounterHiRes();
  231. graph.processBlock (view, midi);
  232. const auto afterGraph = juce::Time::getMillisecondCounterHiRes();
  233. lastRenderStats.graphMs += afterGraph - before;
  234. for (int ch = 0; ch < view.getNumChannels(); ++ch)
  235. softClip (view.getWritePointer (ch), n);
  236. const auto blockPeak = view.getMagnitude (0, n);
  237. peak = juce::jmax (peak, blockPeak);
  238. if (dither)
  239. for (int ch = 0; ch < view.getNumChannels(); ++ch)
  240. dither->process (view.getWritePointer (ch), n, ch);
  241. // PDC: the start is the latency's silence; the song's end arrives `trim` samples later
  242. if ((output != nullptr || options.capture) && done + n > trim)
  243. {
  244. const auto skip = (int) juce::jmax<std::int64_t> (0, trim - done);
  245. const auto beforeWrite = juce::Time::getMillisecondCounterHiRes();
  246. if (output != nullptr)
  247. output->writeFromAudioSampleBuffer (view, skip, n - skip);
  248. if (options.capture)
  249. options.capture (view.getReadPointer (0, skip), view.getReadPointer (1, skip), n - skip);
  250. lastRenderStats.writeMs += juce::Time::getMillisecondCounterHiRes() - beforeWrite;
  251. }
  252. transport.positionTicks.store (transport.positionTicks.load() + n * transport.ticksPerSample());
  253. // in the tail: half a second of silence ends it
  254. if (done + n > musicSamples)
  255. {
  256. quietSamples = blockPeak < silence ? quietSamples + n : 0;
  257. if (quietSamples > (std::int64_t) (sampleRate * 0.5))
  258. break;
  259. }
  260. if (progress && (done / blockSize) % 32 == 0 && ! progress ((double) done / (double) juce::jmax<std::int64_t> (1, totalSamples)))
  261. {
  262. cancelled = true;
  263. break;
  264. }
  265. }
  266. stop();
  267. if (rackProcessor != nullptr)
  268. rackProcessor->setMetering (true);
  269. graph.releaseResources();
  270. setOfflineRendering (false);
  271. return cancelled ? -1.0f : peak;
  272. }
  273. ProcessTimes* AudioEngine::getProcessTimes() noexcept
  274. {
  275. return rackProcessor != nullptr ? &rackProcessor->processTimes() : nullptr;
  276. }
  277. void AudioEngine::play() noexcept { transport.playing.store (true); }
  278. void AudioEngine::stop() noexcept
  279. {
  280. waitingForInput.store (false);
  281. transport.countIn.store (0.0);
  282. transport.playing.store (false);
  283. }
  284. void AudioEngine::setRecordOptions (const RecordOptions& options)
  285. {
  286. recordOptions = options;
  287. recordOptions.countInBars = juce::jlimit (0, 4, options.countInBars);
  288. sendChangeMessage();
  289. }
  290. void AudioEngine::startPlayback()
  291. {
  292. if (! transport.recording.load())
  293. {
  294. play();
  295. return;
  296. }
  297. if (recordOptions.waitForInput)
  298. {
  299. waitingForInput.store (true);
  300. sendChangeMessage();
  301. return;
  302. }
  303. if (recordOptions.countInBars > 0)
  304. {
  305. const auto at = (std::int64_t) transport.positionTicks.load();
  306. transport.countIn.store ((double) countInLength (song, recordOptions.countInBars, at));
  307. sendChangeMessage();
  308. return;
  309. }
  310. play();
  311. }
  312. void AudioEngine::startOnInput() noexcept
  313. {
  314. if (waitingForInput.exchange (false))
  315. transport.playing.store (true);
  316. }
  317. void AudioEngine::setInsertArmed (int track, bool armed)
  318. {
  319. const auto it = std::find (armedInserts.begin(), armedInserts.end(), track);
  320. const auto wasArmed = it != armedInserts.end();
  321. if (armed == wasArmed || track <= 0)
  322. return;
  323. if (armed)
  324. armedInserts.push_back (track);
  325. else
  326. armedInserts.erase (it);
  327. if (track < maxMixerTracks)
  328. liveInput.armed[(std::size_t) track].store (armed);
  329. if (armed && ! audioArmed)
  330. setAudioRecordingArmed (true);
  331. else if (! armed && armedInserts.empty() && audioArmed)
  332. setAudioRecordingArmed (false);
  333. sendChangeMessage();
  334. }
  335. bool AudioEngine::isInsertArmed (int track) const noexcept
  336. {
  337. return std::find (armedInserts.begin(), armedInserts.end(), track) != armedInserts.end();
  338. }
  339. void AudioEngine::rewind() noexcept { transport.rewindRequested.store (true); }
  340. void AudioEngine::seek (double ticks) noexcept { transport.seekRequest.store (juce::jmax (0.0, ticks)); }
  341. void AudioEngine::copyScope (float* destination, int count) const noexcept
  342. {
  343. count = juce::jmin (count, scopeSize);
  344. auto r = (scopeWrite.load (std::memory_order_acquire) - count + scopeSize) % scopeSize;
  345. for (int i = 0; i < count; ++i)
  346. {
  347. destination[i] = scope[(std::size_t) r].load (std::memory_order_relaxed);
  348. r = (r + 1) % scopeSize;
  349. }
  350. }
  351. void AudioEngine::previewFile (const juce::File& file)
  352. {
  353. if (preview != nullptr)
  354. preview->play (file.existsAsFile() ? samples.load (file.getFullPathName()) : nullptr);
  355. }
  356. void AudioEngine::setInputScale (int scale, int root) noexcept
  357. {
  358. inputScaleRoot.store (root);
  359. inputScale.store (scale);
  360. }
  361. int AudioEngine::snapInputKey (int key) const noexcept
  362. {
  363. const auto scale = inputScale.load();
  364. return scale > 0 ? notetools::snapToScale (key, inputScaleRoot.load(), scale) : key;
  365. }
  366. void AudioEngine::previewSample (std::shared_ptr<const SampleData> sample, bool loop, float gain)
  367. {
  368. if (preview != nullptr)
  369. preview->play (std::move (sample), loop, gain);
  370. }
  371. double AudioEngine::getPreviewPosition() const noexcept
  372. {
  373. return preview != nullptr ? preview->getPlayPosition() : -1.0;
  374. }
  375. void AudioEngine::sendLiveNote (int channel, int key, float velocity, bool on, bool record)
  376. {
  377. if (record) // played notes (the PC keyboard) follow the scale snap; previews don't
  378. {
  379. // the note-off stops the key its note-on started, even if the snap changed in between
  380. const auto requested = key;
  381. if (on)
  382. {
  383. key = snapInputKey (key);
  384. playedKeys.on (channel, requested, key);
  385. startOnInput();
  386. }
  387. else
  388. key = playedKeys.off (channel, requested, snapInputKey (key));
  389. }
  390. NoteEvent e;
  391. e.type = on ? NoteEvent::Type::on : NoteEvent::Type::off;
  392. e.channel = channel;
  393. e.key = key;
  394. e.velocity = velocity;
  395. liveEvents.push (e);
  396. if (record && transport.recording.load() && transport.playing.load())
  397. uiRecorded.push_back ({ estimatedPositionNow(), channel, key, velocity, on });
  398. }
  399. void AudioEngine::panic()
  400. {
  401. NoteEvent e;
  402. e.type = NoteEvent::Type::choke;
  403. e.channel = -1; // every channel
  404. liveEvents.push (e);
  405. }
  406. double AudioEngine::estimatedPositionNow() const noexcept
  407. {
  408. // the position only moves block by block; interpolate by the time since the last block
  409. auto tick = transport.positionTicks.load (std::memory_order_relaxed);
  410. if (transport.playing.load (std::memory_order_relaxed))
  411. {
  412. const auto elapsedMs = juce::jlimit (0.0, 100.0, juce::Time::getMillisecondCounterHiRes() - blockTimeMs.load());
  413. tick += elapsedMs * 0.001 * transport.sampleRate.load() * transport.ticksPerSample();
  414. }
  415. return tick;
  416. }
  417. void AudioEngine::updateAudioRecording()
  418. {
  419. const auto wantTake = audioArmed && recordOptions.recordAudio && transport.recording.load();
  420. const auto open = takeCount > 0;
  421. // the files are ready before Play: the very first block gets recorded
  422. if (wantTake && ! open && recordingError.isEmpty())
  423. startAudioTake();
  424. // playback stopped (or recording turned off) with something recorded: close the takes
  425. if (open && (! wantTake || (! transport.playing.load() && takeFrames.load() > 0)))
  426. finishAudioTake();
  427. }
  428. void AudioEngine::startAudioTake()
  429. {
  430. auto* device = deviceManager.getCurrentAudioDevice();
  431. if (device == nullptr)
  432. return;
  433. const auto names = getInputChannelNames();
  434. const auto deviceChannels = (int) names.size();
  435. const auto active = device->getActiveInputChannels();
  436. if (deviceChannels == 0 || active.isZero())
  437. {
  438. recordingError = "no audio input is open";
  439. notify (InputIssue::noInputOpen);
  440. return;
  441. }
  442. // one take per armed insert that has an input source; without armed inserts (Settings' "Record input audio"),
  443. // the first two input channels into a new insert
  444. std::vector<Take> wanted;
  445. std::vector<int> withoutInput;
  446. for (const auto t : armedInserts)
  447. {
  448. if (t <= 0 || t >= (int) song.mixer.size() || (int) wanted.size() >= maxTakes)
  449. continue;
  450. const auto [first, count] = inputChannelsOf (song.mixer[(std::size_t) t], deviceChannels);
  451. if (count == 0)
  452. withoutInput.push_back (t);
  453. else
  454. wanted.push_back ({ t, first, count, {}, {} });
  455. }
  456. if (armedInserts.empty())
  457. wanted.push_back ({ 0, 0, juce::jmin (2, deviceChannels), {}, {} });
  458. if (wanted.empty())
  459. {
  460. recordingError = "the armed inserts have no audio input";
  461. notify (InputIssue::armedWithoutInput, withoutInput.empty() ? 0 : withoutInput.front());
  462. return;
  463. }
  464. if (! withoutInput.empty())
  465. notify (InputIssue::insertWithoutInput, withoutInput.front());
  466. const auto folder = juce::File::getSpecialLocation (juce::File::userMusicDirectory).getChildFile ("LYNX/Recordings");
  467. folder.createDirectory();
  468. takeSampleRate = device->getCurrentSampleRate();
  469. takeLatency = device->getInputLatencyInSamples() + device->getOutputLatencyInSamples();
  470. const auto stamp = juce::Time::getCurrentTime().formatted ("%Y-%m-%d %H-%M-%S");
  471. juce::WavAudioFormat wav;
  472. for (auto& take : wanted)
  473. {
  474. auto name = "Take " + stamp;
  475. if (take.track > 0)
  476. name << " - " << (song.mixer[(std::size_t) take.track].name.empty() ? "Insert " + juce::String (take.track)
  477. : juce::String::fromUTF8 (song.mixer[(std::size_t) take.track].name.c_str()));
  478. take.file = folder.getNonexistentChildFile (juce::File::createLegalFileName (name), ".wav");
  479. auto stream = take.file.createOutputStream();
  480. if (stream == nullptr)
  481. {
  482. recordingError = utf8 ("could not create ") + take.file.getFullPathName();
  483. continue;
  484. }
  485. auto* writer = wav.createWriterFor (stream.get(), takeSampleRate, (unsigned int) take.channels, 24, {}, 0);
  486. if (writer == nullptr)
  487. {
  488. stream.reset();
  489. take.file.deleteFile();
  490. recordingError = utf8 ("WAV does not accept this sample rate/channel count");
  491. continue;
  492. }
  493. stream.release(); // now owned by the writer
  494. take.writer = std::make_unique<juce::AudioFormatWriter::ThreadedWriter> (writer, recordThread, 1 << 18);
  495. }
  496. if (recordingError.isNotEmpty())
  497. notify (InputIssue::failed, 0, recordingError);
  498. takeStartTick.store (-1.0);
  499. takeFrames.store (0);
  500. const juce::SpinLock::ScopedLockType lock (takeLock);
  501. takeCount = 0;
  502. for (auto& take : wanted)
  503. if (take.writer != nullptr)
  504. takes[(std::size_t) takeCount++] = std::move (take);
  505. }
  506. void AudioEngine::finishAudioTake()
  507. {
  508. std::vector<Take> done;
  509. {
  510. const juce::SpinLock::ScopedLockType lock (takeLock);
  511. for (int k = 0; k < takeCount; ++k)
  512. done.push_back (std::move (takes[(std::size_t) k]));
  513. takeCount = 0;
  514. }
  515. for (auto& take : done)
  516. take.writer.reset(); // drains the queue and closes the WAV
  517. const auto frames = takeFrames.exchange (0);
  518. const auto startTick = takeStartTick.exchange (-1.0);
  519. if (frames <= 0 || startTick < 0.0)
  520. {
  521. for (auto& take : done)
  522. take.file.deleteFile();
  523. return;
  524. }
  525. // what came into the interface corresponds to what was heard one latency earlier
  526. const auto ticksPerSample = song.bpm * ppq / (60.0 * takeSampleRate);
  527. auto start = (std::int64_t) std::llround (startTick - takeLatency * ticksPerSample);
  528. std::int64_t offset = 0;
  529. if (start < 0)
  530. {
  531. offset = -start;
  532. start = 0;
  533. }
  534. const auto length = (std::int64_t) std::llround ((double) frames * ticksPerSample) - offset;
  535. if (length <= 0)
  536. return;
  537. struct Made
  538. {
  539. std::string path, name;
  540. int track;
  541. };
  542. std::vector<Made> made;
  543. for (const auto& take : done)
  544. made.push_back ({ take.file.getFullPathName().toStdString(), take.file.getFileNameWithoutExtension().toStdString(), take.track });
  545. editSong ([=] (Song& s) {
  546. int playlistTrack = 0;
  547. for (const auto& clip : s.playlist)
  548. playlistTrack = std::max (playlistTrack, clip.track + 1);
  549. for (const auto& m : made) // each take on its own Playlist track, through the insert it was recorded on
  550. {
  551. ChannelDef c;
  552. c.name = m.name;
  553. c.instrument = InstrumentKind::audioClip;
  554. c.samplePath = m.path;
  555. c.mixerTrack = m.track > 0 && m.track < (int) s.mixer.size() ? m.track : s.nextFreeInsert();
  556. s.channels.push_back (c);
  557. Clip clip;
  558. clip.kind = ClipKind::audio;
  559. clip.channel = (int) s.channels.size() - 1;
  560. clip.track = playlistTrack++;
  561. clip.start = start;
  562. clip.length = length;
  563. clip.offset = offset;
  564. s.playlist.push_back (clip);
  565. }
  566. });
  567. }
  568. std::vector<std::string> AudioEngine::getInputChannelNames() const
  569. {
  570. std::vector<std::string> names;
  571. if (auto* device = deviceManager.getCurrentAudioDevice(); device != nullptr && ! device->getActiveInputChannels().isZero())
  572. for (const auto& n : device->getInputChannelNames())
  573. if ((int) names.size() < LiveInput::maxChannels)
  574. names.push_back (n.toStdString());
  575. return names;
  576. }
  577. bool AudioEngine::hasAudioInput() const
  578. {
  579. auto* device = deviceManager.getCurrentAudioDevice();
  580. return device != nullptr && ! device->getActiveInputChannels().isZero();
  581. }
  582. void AudioEngine::notify (InputIssue issue, int track, const juce::String& detail)
  583. {
  584. recordingNotice = { issue, track, detail };
  585. sendChangeMessage();
  586. }
  587. AudioEngine::RecordingNotice AudioEngine::openAudioInput (const juce::String& deviceName)
  588. {
  589. auto* type = deviceManager.getCurrentDeviceTypeObject();
  590. if (type == nullptr || deviceManager.getCurrentAudioDevice() == nullptr)
  591. return { InputIssue::noDevice, 0, {} };
  592. auto setup = deviceManager.getAudioDeviceSetup();
  593. int count = 0;
  594. if (type->hasSeparateInputsAndOutputs())
  595. {
  596. // Windows Audio / DirectSound: the input is a device of its own
  597. const auto inputs = type->getDeviceNames (true);
  598. auto name = deviceName.isNotEmpty() ? deviceName : setup.inputDeviceName;
  599. if (! inputs.contains (name))
  600. {
  601. const auto index = type->getDefaultDeviceIndex (true);
  602. name = juce::isPositiveAndBelow (index, inputs.size()) ? inputs[index] : juce::String();
  603. }
  604. if (name.isEmpty())
  605. return { InputIssue::noInputDevice, 0, {} };
  606. auto* current = deviceManager.getCurrentAudioDevice();
  607. if (name == setup.inputDeviceName && ! current->getActiveInputChannels().isZero())
  608. count = current->getInputChannelNames().size();
  609. else if (std::unique_ptr<juce::AudioIODevice> probe (type->createDevice ({}, name)); probe != nullptr)
  610. count = probe->getInputChannelNames().size();
  611. setup.inputDeviceName = name;
  612. }
  613. else
  614. {
  615. // ASIO: one device does both; its input channels come in pairs in the mixer
  616. count = deviceManager.getCurrentAudioDevice()->getInputChannelNames().size();
  617. setup.inputDeviceName = setup.outputDeviceName;
  618. }
  619. if (count <= 0)
  620. count = 2;
  621. count = juce::jmin (count, (int) LiveInput::maxChannels);
  622. juce::BigInteger wanted;
  623. wanted.setRange (0, count, true);
  624. if (! setup.useDefaultInputChannels && setup.inputChannels == wanted && ! deviceManager.getCurrentAudioDevice()->getActiveInputChannels().isZero())
  625. return {};
  626. setup.useDefaultInputChannels = false;
  627. setup.inputChannels = wanted;
  628. const auto error = deviceManager.setAudioDeviceSetup (setup, true);
  629. sendChangeMessage();
  630. if (error.isNotEmpty())
  631. return { InputIssue::failed, 0, error };
  632. if (! hasAudioInput())
  633. return { InputIssue::noInputDevice, 0, {} };
  634. return {};
  635. }
  636. void AudioEngine::setInsertInput (int track, int channel, bool stereo)
  637. {
  638. if (track <= 0 || track >= (int) song.mixer.size())
  639. return;
  640. editSong ([=] (Song& s) {
  641. s.mixer[(std::size_t) track].inputChannel = channel;
  642. s.mixer[(std::size_t) track].inputStereo = stereo;
  643. });
  644. recordingError = {};
  645. if (channel >= 0 && ! hasAudioInput())
  646. if (const auto result = openAudioInput(); result.issue != InputIssue::none)
  647. notify (result.issue, track, result.detail);
  648. }
  649. void AudioEngine::setInsertMonitor (int track, InputMonitor mode)
  650. {
  651. if (track > 0 && track < (int) song.mixer.size())
  652. editSong ([=] (Song& s) { s.mixer[(std::size_t) track].monitor = mode; });
  653. }
  654. void AudioEngine::handleIncomingMidiMessage (juce::MidiInput* source, const juce::MidiMessage& m)
  655. {
  656. // MIDI thread: queues and atomics only (and a short copy of the device settings)
  657. prefs::MidiInputPrefs device;
  658. auto velocityCurve = prefs::VelocityCurve::linear;
  659. {
  660. const juce::SpinLock::ScopedLockType lock (midiPrefsLock);
  661. device = midiPrefsShared.input (source != nullptr ? source->getName().toStdString() : std::string());
  662. velocityCurve = midiPrefsShared.velocity;
  663. }
  664. if (! device.enabled || (device.midiChannel != 0 && m.getChannel() != device.midiChannel))
  665. return;
  666. if (m.isController())
  667. {
  668. controllerQueue.push ({ m.getControllerNumber(), m.getChannel() - 1, m.getControllerValue() });
  669. return;
  670. }
  671. if (! m.isNoteOnOrOff())
  672. return;
  673. const auto on = m.isNoteOn();
  674. if (on)
  675. startOnInput();
  676. // a note-off goes to the channels and key its note-on reached (the selection or the scale snap may have
  677. // changed while the key was down); a repeated note-on first stops what the previous one started
  678. InputHeldNotes::Target targets[InputHeldNotes::maxTargets], stale[InputHeldNotes::maxTargets];
  679. auto count = 0;
  680. auto staleCount = 0;
  681. if (on)
  682. {
  683. const auto key = snapInputKey (m.getNoteNumber());
  684. const auto extra = juce::jlimit (0, maxLiveChannels, extraLiveCount.load());
  685. // the primary selected channel, then the other selected ones (or the device's own channel)
  686. if (device.target >= 0)
  687. targets[count++] = { device.target, key };
  688. else
  689. for (int i = -1; i < extra && count < InputHeldNotes::maxTargets; ++i)
  690. targets[count++] = { i < 0 ? liveChannel.load() : extraLiveChannels[(std::size_t) i].load(), key };
  691. staleCount = midiHeld.noteOn (m.getNoteNumber(), targets, count, stale);
  692. }
  693. else
  694. count = midiHeld.noteOff (m.getNoteNumber(), targets);
  695. auto push = [this] (const InputHeldNotes::Target& t, bool noteOn, float velocity) {
  696. NoteEvent e;
  697. e.type = noteOn ? NoteEvent::Type::on : NoteEvent::Type::off;
  698. e.channel = t.channel;
  699. e.key = t.key;
  700. e.velocity = velocity;
  701. midiEvents.push (e);
  702. if (transport.recording.load() && transport.playing.load())
  703. midiRecordQueue.push ({ estimatedPositionNow(), e.channel, e.key, e.velocity, noteOn });
  704. };
  705. for (int i = 0; i < staleCount; ++i)
  706. push (stale[i], false, 0.0f);
  707. for (int i = 0; i < count; ++i)
  708. push (targets[i], on, on ? prefs::mapVelocity (m.getFloatVelocity(), velocityCurve) : 0.0f);
  709. }
  710. void AudioEngine::enableAllMidiInputs()
  711. {
  712. // (a device turned off in the MIDI settings is closed, so other programs can use it)
  713. for (const auto& device : juce::MidiInput::getAvailableDevices())
  714. {
  715. const auto on = midiPrefs.input (device.name.toStdString()).enabled;
  716. if (deviceManager.isMidiInputDeviceEnabled (device.identifier) != on)
  717. deviceManager.setMidiInputDeviceEnabled (device.identifier, on);
  718. }
  719. }
  720. void AudioEngine::setMidiPrefs (const prefs::MidiPrefs& p, bool save)
  721. {
  722. midiPrefs = p;
  723. {
  724. const juce::SpinLock::ScopedLockType lock (midiPrefsLock);
  725. midiPrefsShared = p;
  726. }
  727. if (! p.pickup)
  728. pickups.clear();
  729. if (prefetcher != nullptr) // (only with an audio device: the real app)
  730. enableAllMidiInputs();
  731. if (save)
  732. midiSettingsFile().replaceWithText (juce::String (p.toText()));
  733. sendChangeMessage();
  734. }
  735. void AudioEngine::setUndoLevels (int levels)
  736. {
  737. maxUndoSteps = (std::size_t) prefs::clampUndoLevels (levels);
  738. while (undoStack.size() > maxUndoSteps)
  739. undoStack.pop_front();
  740. }
  741. juce::StringArray AudioEngine::getActiveMidiInputs() const
  742. {
  743. juce::StringArray names;
  744. for (const auto& device : juce::MidiInput::getAvailableDevices())
  745. if (deviceManager.isMidiInputDeviceEnabled (device.identifier))
  746. names.add (device.name);
  747. return names;
  748. }
  749. void AudioEngine::setAudioRecordingArmed (bool armed)
  750. {
  751. audioArmed = armed;
  752. recordingError = {};
  753. if (armed)
  754. {
  755. // opens the input of the current driver (every channel, so each insert can pick its own)
  756. if (! hasAudioInput())
  757. if (const auto result = openAudioInput(); result.issue != InputIssue::none)
  758. {
  759. recordingError = "no audio input";
  760. notify (result.issue, 0, result.detail);
  761. }
  762. if (! recordThread.isThreadRunning())
  763. recordThread.startThread();
  764. }
  765. sendChangeMessage();
  766. }
  767. void AudioEngine::setRecording (bool shouldRecord)
  768. {
  769. if (shouldRecord && ! transport.recording.load())
  770. recordingError = {}; // a new attempt
  771. transport.recording.store (shouldRecord);
  772. liveInput.recording.store (shouldRecord);
  773. updateRecording();
  774. sendChangeMessage();
  775. }
  776. void AudioEngine::updateRecording()
  777. {
  778. const auto playing = transport.playing.load();
  779. const auto active = transport.recording.load() && playing;
  780. if (playing)
  781. lastPlayingTick = estimatedPositionNow();
  782. // the take starts when playing with recording on, or at the first recorded event
  783. // (which is only queued in that situation, even if this timer hasn't seen it yet)
  784. auto beginTake = [this] {
  785. if (recorder.isActive())
  786. return;
  787. const auto& pattern = song.patterns[(std::size_t) song.currentPattern];
  788. recorder.begin (pattern.effectiveLength (song.beatsPerBar));
  789. takeHasUndoStep = false;
  790. takeClearedChannels.clear();
  791. takeStartPosition = lastPlayingTick;
  792. };
  793. if (active)
  794. beginTake();
  795. RecordedEvent e;
  796. while (midiRecordQueue.pop (e))
  797. {
  798. if (! recordOptions.recordNotes) // recording filter: notes off
  799. continue;
  800. beginTake();
  801. recorder.add (song, e);
  802. }
  803. for (const auto& ui : uiRecorded)
  804. {
  805. if (! recordOptions.recordNotes)
  806. continue;
  807. beginTake();
  808. recorder.add (song, ui);
  809. }
  810. uiRecorded.clear();
  811. updateAudioRecording();
  812. if (! active && recorder.isActive())
  813. recorder.end (song, lastPlayingTick);
  814. auto notes = recorder.takeFinished();
  815. if (notes.empty())
  816. return;
  817. // the whole take is a single undo step: overdub or replace, quantised to the record grid; in song mode a
  818. // clip of the pattern is placed where recording started if none plays there
  819. const auto options = recordOptions;
  820. const auto placeClipAt = (std::int64_t) takeStartPosition;
  821. editSong ([&] (Song& s) {
  822. commitTake (s.patterns[(std::size_t) s.currentPattern], notes, options.mode, options.quantise, takeClearedChannels);
  823. if (options.placeSongClip && s.mode == PlayMode::song && ! takeHasUndoStep)
  824. placePatternClipAt (s, s.currentPattern, placeClipAt);
  825. }, ! takeHasUndoStep);
  826. takeHasUndoStep = true;
  827. }
  828. void AudioEngine::setSong (Song newSong)
  829. {
  830. undoStack.clear();
  831. redoStack.clear();
  832. song = std::move (newSong);
  833. selectedChannel = 0;
  834. selectedChannels = { 0 };
  835. modified = false;
  836. // arming isn't saved: a new project starts disarmed; its inserts' audio inputs open the device input
  837. for (const auto t : std::vector<int> (armedInserts))
  838. setInsertArmed (t, false);
  839. if (prefetcher != nullptr && ! hasAudioInput()
  840. && std::any_of (song.mixer.begin(), song.mixer.end(), [] (const MixerTrack& t) { return t.inputChannel >= 0; }))
  841. openAudioInput();
  842. publishSong();
  843. }
  844. void AudioEngine::editSong (const std::function<void (Song&)>& edit, bool undoable)
  845. {
  846. if (undoable)
  847. {
  848. // Dozens of edits arrive during a drag; only the first one of the click saves the state.
  849. bool samePress = false;
  850. if (juce::ModifierKeys::currentModifiers.isAnyMouseButtonDown())
  851. {
  852. const auto press = juce::Desktop::getInstance().getMainMouseSource().getLastMouseDownTime();
  853. samePress = press == lastUndoPress;
  854. lastUndoPress = press;
  855. }
  856. else
  857. {
  858. lastUndoPress = {};
  859. }
  860. if (! samePress)
  861. {
  862. undoStack.push_back (song);
  863. redoStack.clear();
  864. if (undoStack.size() > maxUndoSteps)
  865. undoStack.pop_front();
  866. }
  867. }
  868. if (undoable)
  869. modified = true;
  870. edit (song);
  871. publishSong();
  872. }
  873. void AudioEngine::undo()
  874. {
  875. if (undoStack.empty())
  876. return;
  877. redoStack.push_back (std::move (song));
  878. song = std::move (undoStack.back());
  879. undoStack.pop_back();
  880. modified = true;
  881. lastUndoPress = {};
  882. publishSong();
  883. }
  884. void AudioEngine::redo()
  885. {
  886. if (redoStack.empty())
  887. return;
  888. undoStack.push_back (std::move (song));
  889. song = std::move (redoStack.back());
  890. redoStack.pop_back();
  891. modified = true;
  892. lastUndoPress = {};
  893. publishSong();
  894. }
  895. namespace
  896. {
  897. const Song& historyState (const std::deque<Song>& undo, const Song& current, const std::deque<Song>& redo, int index)
  898. {
  899. if (index < (int) undo.size())
  900. return undo[(std::size_t) index];
  901. if (index == (int) undo.size())
  902. return current;
  903. return redo[redo.size() - 1 - (std::size_t) (index - (int) undo.size() - 1)];
  904. }
  905. } // namespace
  906. ChangeLabel AudioEngine::getHistoryLabel (int index) const
  907. {
  908. if (index <= 0 || index >= getHistorySize())
  909. return { TR_NOOP ("Start"), {} };
  910. return describeChange (historyState (undoStack, song, redoStack, index - 1), historyState (undoStack, song, redoStack, index));
  911. }
  912. void AudioEngine::jumpToHistory (int index)
  913. {
  914. index = juce::jlimit (0, getHistorySize() - 1, index);
  915. if (index == getHistoryPosition())
  916. return;
  917. // move through the stacks, then publish once
  918. while (getHistoryPosition() > index && ! undoStack.empty())
  919. {
  920. redoStack.push_back (std::move (song));
  921. song = std::move (undoStack.back());
  922. undoStack.pop_back();
  923. }
  924. while (getHistoryPosition() < index && ! redoStack.empty())
  925. {
  926. undoStack.push_back (std::move (song));
  927. song = std::move (redoStack.back());
  928. redoStack.pop_back();
  929. }
  930. modified = true;
  931. lastUndoPress = {};
  932. publishSong();
  933. }
  934. void AudioEngine::setSelectedChannel (int channel)
  935. {
  936. channel = juce::jlimit (0, juce::jmax (0, (int) song.channels.size() - 1), channel);
  937. setChannelSelection ({ channel }, channel);
  938. }
  939. void AudioEngine::setChannelSelection (std::vector<int> channels, int primary)
  940. {
  941. const auto count = (int) song.channels.size();
  942. std::sort (channels.begin(), channels.end());
  943. channels.erase (std::unique (channels.begin(), channels.end()), channels.end());
  944. channels.erase (std::remove_if (channels.begin(), channels.end(), [count] (int c) { return c < 0 || c >= count; }), channels.end());
  945. primary = juce::jlimit (0, juce::jmax (0, count - 1), primary);
  946. if (std::find (channels.begin(), channels.end(), primary) == channels.end())
  947. channels.insert (std::lower_bound (channels.begin(), channels.end(), primary), primary);
  948. if (channels == selectedChannels && primary == selectedChannel)
  949. {
  950. publishSelection();
  951. return;
  952. }
  953. selectedChannels = std::move (channels);
  954. selectedChannel = primary;
  955. publishSelection();
  956. sendChangeMessage();
  957. }
  958. void AudioEngine::publishSelection()
  959. {
  960. liveChannel.store (selectedChannel);
  961. int extra = 0;
  962. for (auto c : selectedChannels)
  963. if (c != selectedChannel && extra < maxLiveChannels)
  964. extraLiveChannels[(std::size_t) extra++].store (c);
  965. extraLiveCount.store (extra);
  966. }
  967. bool AudioEngine::importFlpFile (const juce::File& file, juce::String& error, const std::map<std::string, std::string>& relocations, bool asEdit)
  968. {
  969. juce::MemoryBlock data;
  970. if (! file.loadFileAsData (data))
  971. {
  972. error = utf8 ("could not read the file");
  973. return false;
  974. }
  975. try
  976. {
  977. const auto project = flp::parseProject ({ static_cast<const std::uint8_t*> (data.getData()), data.getSize() });
  978. FlpImportOptions options;
  979. options.roots = findFlStudioRoots();
  980. options.projectFolder = file.getParentDirectory().getFullPathName().toStdString();
  981. options.fileExists = [] (const std::string& path) { return platform::localFile (path).existsAsFile(); };
  982. options.readFile = [] (const std::string& path) {
  983. juce::MemoryBlock data;
  984. platform::localFile (path).loadFileAsData (data);
  985. const auto* bytes = static_cast<const std::uint8_t*> (data.getData());
  986. return std::vector<std::uint8_t> (bytes, bytes + data.getSize());
  987. };
  988. options.sampleFrames = [this] (const std::string& path) -> std::int64_t {
  989. const auto sample = samples.load (juce::String::fromUTF8 (path.c_str()));
  990. return sample != nullptr ? (std::int64_t) sample->frames() : 0;
  991. };
  992. // WAV that only exists inside the .flp (Slicex): goes to %APPDATA%\LYNX\flp-embedded, keyed by content
  993. options.saveEmbedded = [] (const std::vector<std::uint8_t>& wav, const std::string& name) -> std::string {
  994. const auto folder = PluginHost::settingsFolder().getChildFile ("flp-embedded");
  995. folder.createDirectory();
  996. const auto hash = juce::String::toHexString ((juce::int64) juce::DefaultHashFunctions::generateHash (
  997. juce::String::createStringFromData (wav.data(), (int) juce::jmin<std::size_t> (wav.size(), 65536)) + juce::String ((juce::int64) wav.size()),
  998. 0x7FFFFFFF));
  999. const auto file = folder.getChildFile (juce::File::createLegalFileName (juce::String::fromUTF8 (name.c_str())) + "-" + hash + ".wav");
  1000. if (! file.existsAsFile() && ! file.replaceWithData (wav.data(), wav.size()))
  1001. return {};
  1002. return file.getFullPathName().toStdString();
  1003. };
  1004. importReport = {};
  1005. options.report = &importReport;
  1006. options.relocations = relocations;
  1007. auto imported = importFlp (project, options);
  1008. // the project's third-party plugins, to say which channel/insert used each one that is missing
  1009. struct Use
  1010. {
  1011. std::string name, user;
  1012. bool instrument;
  1013. };
  1014. std::vector<Use> uses;
  1015. for (const auto& c : imported.channels)
  1016. if (c.plugin.foreign.format != ForeignPlugin::Format::none)
  1017. uses.push_back ({ c.plugin.foreign.name, c.name, true });
  1018. for (std::size_t t = 0; t < imported.mixer.size(); ++t)
  1019. for (const auto& fx : imported.mixer[t].effects)
  1020. if (fx.kind == EffectKind::plugin && fx.plugin.foreign.format != ForeignPlugin::Format::none)
  1021. uses.push_back ({ fx.plugin.foreign.name, imported.mixer[t].name.empty() ? (t == 0 ? std::string ("Master") : "Insert " + std::to_string (t))
  1022. : imported.mixer[t].name,
  1023. false });
  1024. juce::StringArray missing;
  1025. juce::StringArray matched;
  1026. juce::StringArray withoutState;
  1027. juce::StringArray substituted;
  1028. plugins.adoptFlPlugins (imported, &missing, &matched, &withoutState, &substituted);
  1029. missingPlugins = missing;
  1030. matchedPlugins = matched;
  1031. pluginsWithoutState = withoutState;
  1032. missingPluginDetails.clear();
  1033. for (const auto& name : missing)
  1034. {
  1035. MissingPlugin m;
  1036. m.name = name.toStdString();
  1037. for (const auto& u : uses)
  1038. if (u.name == m.name)
  1039. {
  1040. if (std::find (m.usedBy.begin(), m.usedBy.end(), u.user) == m.usedBy.end())
  1041. m.usedBy.push_back (u.user);
  1042. m.replacement = u.instrument ? "Built-in synth (a preset chosen by the channel name)" : "Nothing: the slot was left out of the mixer";
  1043. }
  1044. missingPluginDetails.push_back (std::move (m));
  1045. }
  1046. // missing, played by a LYNX substitute that keeps the original for when it is installed
  1047. for (std::size_t t = 0; t < imported.mixer.size(); ++t)
  1048. for (const auto& fx : imported.mixer[t].effects)
  1049. if (fx.isSubstitute())
  1050. {
  1051. const auto name = substituteOriginalName (fx);
  1052. auto it = std::find_if (missingPluginDetails.begin(), missingPluginDetails.end(),
  1053. [&] (const MissingPlugin& m) { return m.name == name && ! m.replacementArg.empty(); });
  1054. if (it == missingPluginDetails.end())
  1055. it = missingPluginDetails.insert (missingPluginDetails.end(),
  1056. MissingPlugin { name, {}, TR_NOOP ("LYNX substitute: {0} (the original plugin is used again once it is installed)"),
  1057. effectInfo (fx.kind).name });
  1058. const auto user = imported.mixer[t].name.empty() ? (t == 0 ? std::string ("Master") : "Insert " + std::to_string (t)) : imported.mixer[t].name;
  1059. if (std::find (it->usedBy.begin(), it->usedBy.end(), user) == it->usedBy.end())
  1060. it->usedBy.push_back (user);
  1061. }
  1062. // found, but the project's settings are in the other format (VST2 <-> VST3): they play their default sound
  1063. for (const auto& line : withoutState)
  1064. missingPluginDetails.push_back ({ line.toStdString(), {}, TR_NOOP ("Its default settings: the project saved them for the other format (VST2/VST3)") });
  1065. plugins.clearLoadFailures();
  1066. if (asEdit)
  1067. editSong ([&imported] (Song& s) { s = std::move (imported); });
  1068. else
  1069. {
  1070. stop();
  1071. rewind();
  1072. setSong (std::move (imported));
  1073. }
  1074. // installed but failed to load (the rack was just built): silence / bypass, said as loudly as a missing one
  1075. for (const auto& line : plugins.getLoadFailures())
  1076. missingPluginDetails.push_back ({ line.toStdString(), {}, TR_NOOP ("Silence: the plugin is installed but did not load") });
  1077. return true;
  1078. }
  1079. catch (const flp::Error& e)
  1080. {
  1081. error = juce::String::fromUTF8 (e.what());
  1082. return false;
  1083. }
  1084. }
  1085. void AudioEngine::publishSong()
  1086. {
  1087. song.currentPattern = juce::jlimit (0, juce::jmax (0, (int) song.patterns.size() - 1), song.currentPattern);
  1088. selectedChannel = juce::jlimit (0, juce::jmax (0, (int) song.channels.size() - 1), selectedChannel);
  1089. {
  1090. const auto count = (int) song.channels.size();
  1091. selectedChannels.erase (std::remove_if (selectedChannels.begin(), selectedChannels.end(), [count] (int c) { return c >= count; }),
  1092. selectedChannels.end());
  1093. if (std::find (selectedChannels.begin(), selectedChannels.end(), selectedChannel) == selectedChannels.end())
  1094. selectedChannels.insert (std::lower_bound (selectedChannels.begin(), selectedChannels.end(), selectedChannel), selectedChannel);
  1095. }
  1096. publishSelection();
  1097. transport.bpm.store (song.bpm);
  1098. transport.beatsPerBar.store (song.beatsPerBar);
  1099. {
  1100. // time-signature table for the metronome: the start (beatsPerBar/4) and each signature change
  1101. transport.signatureVersion.fetch_add (1, std::memory_order_acq_rel); // odd: writing
  1102. int count = 0;
  1103. transport.signatureTick[0].store (0, std::memory_order_relaxed);
  1104. transport.signatureLength[0].store ((std::int64_t) ppq * juce::jmax (1, song.beatsPerBar), std::memory_order_relaxed);
  1105. ++count;
  1106. for (const auto& m : song.markers())
  1107. if (m.isSignature() && count < Transport::maxSignatures)
  1108. {
  1109. const auto length = juce::jmax<std::int64_t> (1, (std::int64_t) ppq * 4 * m.numerator / juce::jmax (1, m.denominator));
  1110. const auto slot = m.tick <= 0 ? 0 : count++; // at position 0 it replaces the default
  1111. transport.signatureTick[(std::size_t) slot].store (juce::jmax<std::int64_t> (0, m.tick), std::memory_order_relaxed);
  1112. transport.signatureLength[(std::size_t) slot].store (length, std::memory_order_relaxed);
  1113. }
  1114. transport.signatureCount.store (count, std::memory_order_relaxed);
  1115. transport.signatureVersion.fetch_add (1, std::memory_order_acq_rel); // even: ready
  1116. }
  1117. transport.songMode.store (song.mode == PlayMode::song);
  1118. transport.loopStart.store ((double) song.loopStart);
  1119. transport.loopEnd.store ((double) song.loopEnd);
  1120. RackState::Factories factories;
  1121. factories.samples = [this] (const std::string& path) { return samples.load (juce::String::fromUTF8 (path.c_str())); };
  1122. factories.stretchedSamples = [this] (const std::string& path, double ratio) {
  1123. return samples.loadStretched (juce::String::fromUTF8 (path.c_str()), ratio);
  1124. };
  1125. factories.pluginInstruments = [this] (const PluginRef& ref, double sr) { return plugins.makeInstrument (ref, sr); };
  1126. factories.pluginEffects = [this] (const PluginRef& ref, double sr) { return plugins.makeEffect (ref, sr); };
  1127. auto state = RackState::build (song, &lastPublishedShape, transport.sampleRate.load(), factories);
  1128. // what the next build needs to reuse instruments and effects
  1129. lastPublishedShape.song.channels = song.channels;
  1130. lastPublishedShape.song.mixer = song.mixer;
  1131. lastPublishedShape.instruments = state->instruments;
  1132. lastPublishedShape.effects = state->effects;
  1133. lastPublishedShape.sampleRate = state->sampleRate;
  1134. lastPublishedShape.latencies = state->latencies;
  1135. lastPublishedShape.pdc = state->pdc;
  1136. lastPublishedShape.channelDelays = state->channelDelays;
  1137. lastPublishedShape.sendDelays = state->sendDelays;
  1138. rackExchange.publish (std::move (state));
  1139. if (prefetcher != nullptr)
  1140. prefetcher->update (song, samples);
  1141. sendChangeMessage();
  1142. }
  1143. void AudioEngine::learnMidiController (const AutomationTarget& target)
  1144. {
  1145. learning = target;
  1146. sendChangeMessage();
  1147. }
  1148. void AudioEngine::applyControllers()
  1149. {
  1150. ControllerEvent e;
  1151. std::map<std::pair<int, int>, int> latest; // (cc, channel) -> latest value this frame
  1152. while (controllerQueue.pop (e))
  1153. {
  1154. if (learning.kind != AutomationTargetKind::none)
  1155. {
  1156. // MIDI learn: replace the old link for the same target with the new one
  1157. editSong ([t = learning, e] (Song& s) {
  1158. s.midiLinks.erase (std::remove_if (s.midiLinks.begin(), s.midiLinks.end(), [&] (const MidiLink& l) { return l.target == t; }),
  1159. s.midiLinks.end());
  1160. s.midiLinks.push_back ({ e.cc, e.channel, t });
  1161. });
  1162. learning = {};
  1163. }
  1164. latest[{ e.cc, e.channel }] = e.value;
  1165. }
  1166. if (latest.empty() || song.midiLinks.empty())
  1167. return;
  1168. // one snapshot per frame, outside the undo history (like turning the knob)
  1169. std::vector<std::pair<AutomationTarget, float>> changes;
  1170. for (const auto& [key, value] : latest)
  1171. for (const auto& link : song.midiLinks)
  1172. if (link.cc == key.first && (link.channel < 0 || link.channel == key.second))
  1173. {
  1174. const auto v = value / 127.0f;
  1175. const auto& t = link.target;
  1176. // takeover: only parameters the song holds (a plugin's own parameters have no value to compare here)
  1177. const auto songHeld = t.kind != AutomationTargetKind::channelParam && t.kind != AutomationTargetKind::effectParam;
  1178. if (midiPrefs.pickup && songHeld)
  1179. {
  1180. auto& state = pickups[{ key.first, key.second, (int) t.kind, t.index, t.slot, t.param }];
  1181. if (! prefs::pickupUpdate (state, song.targetValue (t), v))
  1182. continue;
  1183. }
  1184. changes.push_back ({ t, v });
  1185. }
  1186. std::vector<std::pair<AutomationTarget, float>> pluginChanges;
  1187. editSong ([&] (Song& s) {
  1188. for (const auto& [target, v] : changes)
  1189. if (! s.setTargetValue (target, v))
  1190. pluginChanges.push_back ({ target, v });
  1191. }, false);
  1192. // plugin parameters live in the plugin
  1193. for (const auto& [target, v] : pluginChanges)
  1194. {
  1195. juce::AudioPluginInstance* plugin = nullptr;
  1196. if (target.kind == AutomationTargetKind::channelParam)
  1197. if (auto* p = dynamic_cast<PluginInstrument*> (getChannelInstrument (target.index).get()))
  1198. plugin = &p->getInstance();
  1199. if (target.kind == AutomationTargetKind::effectParam)
  1200. if (auto* p = dynamic_cast<PluginEffect*> (getEffect (target.index, target.slot).get()))
  1201. plugin = &p->getInstance();
  1202. if (plugin != nullptr && target.param >= 0 && target.param < plugin->getParameters().size())
  1203. plugin->getParameters()[target.param]->setValueNotifyingHost (v);
  1204. }
  1205. }
  1206. void AudioEngine::timerCallback()
  1207. {
  1208. updateRealtimeStats();
  1209. applyControllers();
  1210. updateRecording();
  1211. rackExchange.collectGarbage();
  1212. // Plugins are prepared at a fixed rate; if the device changed rate, recreate them.
  1213. // A plugin whose latency changed (preset change, lookahead) requests a new PDC plan.
  1214. const auto rateChanged = std::abs (transport.sampleRate.load() - lastPublishedShape.sampleRate) > 0.5;
  1215. const auto latencies = lastPublishedShape.currentLatencies();
  1216. if (rateChanged || latencies != lastPublishedShape.latencies)
  1217. {
  1218. // (diagnostics: which unit's latency moved)
  1219. if (! rateChanged)
  1220. for (std::size_t i = 0; i < latencies.size() && i < lastPublishedShape.latencies.size(); ++i)
  1221. if (latencies[i] != lastPublishedShape.latencies[i])
  1222. {
  1223. lastLatencyChange = juce::String ((int) i) + ": " + juce::String (lastPublishedShape.latencies[i]) + " -> " + juce::String (latencies[i]);
  1224. break;
  1225. }
  1226. ++latencyRepublishes;
  1227. publishSong();
  1228. }
  1229. }
  1230. void AudioEngine::chooseSafeBufferSize()
  1231. {
  1232. auto* device = deviceManager.getCurrentAudioDevice();
  1233. if (device == nullptr)
  1234. return;
  1235. std::vector<int> sizes;
  1236. for (auto b : device->getAvailableBufferSizes())
  1237. sizes.push_back (b);
  1238. const auto current = device->getCurrentBufferSizeSamples();
  1239. const auto target = prefs::safeBufferSize (sizes, current, device->getCurrentSampleRate());
  1240. if (target > 0 && target != current)
  1241. {
  1242. auto setup = deviceManager.getAudioDeviceSetup();
  1243. setup.bufferSize = target;
  1244. deviceManager.setAudioDeviceSetup (setup, true);
  1245. }
  1246. }
  1247. juce::File AudioEngine::glitchLogFile() { return PluginHost::settingsFolder().getChildFile ("audio-glitches.log"); }
  1248. void AudioEngine::updateRealtimeStats()
  1249. {
  1250. // the message thread's pulse: this 30 Hz timer arriving late means the UI is saturated
  1251. {
  1252. const auto now = juce::Time::getMillisecondCounterHiRes();
  1253. if (lastUiPulseMs > 0.0)
  1254. uiPulse.maxGapMs = juce::jmax (uiPulse.maxGapMs, now - lastUiPulseMs);
  1255. lastUiPulseMs = now;
  1256. ++uiPulse.calls;
  1257. }
  1258. // every ~2 s: the share of real time each channel / insert effect took in that window
  1259. if (rackProcessor != nullptr && juce::Time::getMillisecondCounterHiRes() - lastUnitsWindowMs >= 2000.0)
  1260. {
  1261. lastUnitsWindowMs = juce::Time::getMillisecondCounterHiRes();
  1262. auto& renderer = rackProcessor->getRenderer();
  1263. const auto& units = renderer.unitTimes();
  1264. const auto processed = units.processedSamples.load (std::memory_order_relaxed);
  1265. const auto rate = juce::jmax (1.0, transport.sampleRate.load());
  1266. const auto audioNs = (double) (processed - std::min (processed, lastProcessedSamples)) / rate * 1.0e9;
  1267. lastProcessedSamples = processed;
  1268. lastChannelNs.resize (units.channelNs.size(), 0);
  1269. lastEffectNs.resize (units.effectNs.size(), 0);
  1270. std::vector<UnitLoad> loads;
  1271. auto take = [&] (const std::atomic<std::uint64_t>& total, std::uint64_t& last, std::atomic<std::uint64_t>& longest, auto&& name) {
  1272. const auto now = total.load (std::memory_order_relaxed);
  1273. const auto delta = now - std::min (now, last);
  1274. last = now;
  1275. const auto longestNs = const_cast<std::atomic<std::uint64_t>&> (longest).exchange (0, std::memory_order_relaxed);
  1276. if (delta > 0 && audioNs > 0.0)
  1277. loads.push_back ({ name(), (double) delta / audioNs, (double) longestNs * 1.0e-6 });
  1278. };
  1279. auto& mutableUnits = const_cast<RackRenderer::UnitTimes&> (units);
  1280. for (std::size_t c = 0; c < units.channelNs.size(); ++c)
  1281. take (units.channelNs[c], lastChannelNs[c], mutableUnits.channelMaxNs[c], [&] {
  1282. return c < song.channels.size() ? juce::String::fromUTF8 (song.channels[c].name.c_str()) : "Channel " + juce::String ((int) c + 1);
  1283. });
  1284. for (std::size_t k = 0; k < units.effectNs.size(); ++k)
  1285. take (units.effectNs[k], lastEffectNs[k], mutableUnits.effectMaxNs[k], [&] {
  1286. const auto t = k / (std::size_t) maxEffectSlots, slot = k % (std::size_t) maxEffectSlots;
  1287. juce::String effect;
  1288. if (t < song.mixer.size() && slot < song.mixer[t].effects.size())
  1289. {
  1290. const auto& fx = song.mixer[t].effects[slot];
  1291. effect = juce::String::fromUTF8 (fx.plugin.name.empty() ? effectInfo (fx.kind).name : fx.plugin.name.c_str());
  1292. }
  1293. const auto track = t == 0 ? juce::String ("Master") : (t < song.mixer.size() && ! song.mixer[t].name.empty() ? juce::String::fromUTF8 (song.mixer[t].name.c_str())
  1294. : "Insert " + juce::String ((int) t));
  1295. return track + " / " + juce::String ((int) slot + 1) + " " + effect;
  1296. });
  1297. std::sort (loads.begin(), loads.end(), [] (const UnitLoad& a, const UnitLoad& b) { return a.load > b.load; });
  1298. if (loads.size() > 8)
  1299. loads.resize (8);
  1300. if (audioNs > 0.0)
  1301. heaviestUnits = std::move (loads);
  1302. }
  1303. // a line in the glitch log when callbacks ran over their deadline or the device called late
  1304. const auto stats = rtStats.snapshot();
  1305. if ((stats.overBudget > loggedOver || stats.lateCalls > loggedLate) && juce::Time::getMillisecondCounterHiRes() - lastLogMs > 2000.0)
  1306. {
  1307. const auto file = glitchLogFile();
  1308. if (file.getSize() > 1024 * 1024)
  1309. file.moveFileTo (file.withFileExtension ("old.log"));
  1310. const auto bar = transport.positionTicks.load() / (double) (ppq * juce::jmax (1, song.beatsPerBar)) + 1.0;
  1311. file.appendText (juce::Time::getCurrentTime().formatted ("%Y-%m-%d %H:%M:%S") + " over deadline +" + juce::String ((juce::int64) (stats.overBudget - loggedOver))
  1312. + ", late calls +" + juce::String ((juce::int64) (stats.lateCalls - loggedLate)) + ", at bar " + juce::String (bar, 2)
  1313. + (transport.playing.load() ? "" : " (stopped)") + "\n" + describeRealtime() + "\n",
  1314. false, false, "\r\n");
  1315. loggedOver = stats.overBudget;
  1316. loggedLate = stats.lateCalls;
  1317. lastLogMs = juce::Time::getMillisecondCounterHiRes();
  1318. }
  1319. }
  1320. juce::String AudioEngine::describeRealtime (bool withUnits) const
  1321. {
  1322. juce::String text;
  1323. if (auto* device = const_cast<juce::AudioDeviceManager&> (deviceManager).getCurrentAudioDevice())
  1324. {
  1325. const auto rate = device->getCurrentSampleRate();
  1326. const auto buffer = device->getCurrentBufferSizeSamples();
  1327. text << " device: " << device->getTypeName() << " / " << device->getName() << ", " << (int) rate << " Hz, buffer " << buffer
  1328. << " samples (deadline " << juce::String (prefs::bufferLatencyMs (buffer, rate), 2) << " ms), output latency "
  1329. << device->getOutputLatencyInSamples() << " samples, driver dropouts " << device->getXRunCount() << "\n";
  1330. }
  1331. else
  1332. text << " device: none\n";
  1333. const auto s = rtStats.snapshot();
  1334. text << " callbacks " << (juce::int64) s.callbacks << ": over deadline " << (juce::int64) s.overBudget << ", 80-100% " << (juce::int64) s.nearBudget
  1335. << ", late device calls " << (juce::int64) s.lateCalls << ", average load " << juce::String (s.averageLoad * 100.0, 1) << "%, max "
  1336. << juce::String (s.maxLoad * 100.0, 0) << "%, workers " << (workers != nullptr ? workers->workers() : 0) << "\n";
  1337. if (latencyRepublishes > 0)
  1338. text << " latency changes re-planned PDC " << latencyRepublishes << " times (last: unit " << lastLatencyChange << ")\n";
  1339. if (withUnits && heaviestUnits.empty())
  1340. text << " heaviest: not measured yet\n";
  1341. if (withUnits && ! heaviestUnits.empty())
  1342. {
  1343. text << " heaviest:";
  1344. for (std::size_t i = 0; i < heaviestUnits.size() && i < 5; ++i)
  1345. text << (i > 0 ? ";" : "") << " " << heaviestUnits[i].name << " " << juce::String (heaviestUnits[i].load * 100.0, 1) << "% (peak "
  1346. << juce::String (heaviestUnits[i].longestMs, 1) << " ms)";
  1347. text << "\n";
  1348. }
  1349. return text;
  1350. }
  1351. std::shared_ptr<Instrument> AudioEngine::getChannelInstrument (int channel) const
  1352. {
  1353. if (channel < 0 || channel >= (int) lastPublishedShape.instruments.size())
  1354. return nullptr;
  1355. return lastPublishedShape.instruments[(std::size_t) channel];
  1356. }
  1357. std::shared_ptr<Effect> AudioEngine::getEffect (int track, int slot) const
  1358. {
  1359. const auto& effects = lastPublishedShape.effects;
  1360. if (track < 0 || track >= (int) effects.size() || slot < 0 || slot >= (int) effects[(std::size_t) track].size())
  1361. return nullptr;
  1362. return effects[(std::size_t) track][(std::size_t) slot];
  1363. }
  1364. void AudioEngine::capturePluginStates()
  1365. {
  1366. // Changes only the saved state (recreates nothing and doesn't enter the undo history).
  1367. for (std::size_t i = 0; i < song.channels.size(); ++i)
  1368. if (auto* p = dynamic_cast<PluginInstrument*> (getChannelInstrument ((int) i).get()))
  1369. song.channels[i].plugin.state = capturePluginState (p->getInstance());
  1370. for (std::size_t t = 0; t < song.mixer.size(); ++t)
  1371. for (std::size_t s = 0; s < song.mixer[t].effects.size(); ++s)
  1372. if (auto* p = dynamic_cast<PluginEffect*> (getEffect ((int) t, (int) s).get()))
  1373. song.mixer[t].effects[s].plugin.state = capturePluginState (p->getInstance());
  1374. lastPublishedShape.song.channels = song.channels;
  1375. lastPublishedShape.song.mixer = song.mixer;
  1376. }
  1377. void AudioEngine::audioDeviceIOCallbackWithContext (const float* const* inputChannelData,
  1378. int numInputChannels,
  1379. float* const* outputChannelData,
  1380. int numOutputChannels,
  1381. int numSamples,
  1382. const juce::AudioIODeviceCallbackContext& context)
  1383. {
  1384. // real-time health: how long this callback took against its deadline (the buffer's duration)
  1385. const auto callbackStart = juce::Time::getMillisecondCounterHiRes();
  1386. struct Measure
  1387. {
  1388. ~Measure()
  1389. {
  1390. const auto rate = engine.transport.sampleRate.load (std::memory_order_relaxed);
  1391. if (rate > 0.0)
  1392. engine.rtStats.record (start, juce::Time::getMillisecondCounterHiRes() - start, 1000.0 * samples / rate);
  1393. }
  1394. AudioEngine& engine;
  1395. double start;
  1396. int samples;
  1397. } measure { *this, callbackStart, numSamples };
  1398. if (transport.rewindRequested.exchange (false))
  1399. transport.positionTicks.store (0.0);
  1400. if (const auto target = transport.seekRequest.exchange (-1.0); target >= 0.0)
  1401. transport.positionTicks.store (target);
  1402. // With the loop region on, the block is split at the loop end and the position jumps back to
  1403. // its start (the nodes see a jump and release their notes, as in FL).
  1404. // the audio editor's input recording (nothing happens unless it chose the input)
  1405. meters.capture.push (AudioCapture::input, numInputChannels > 0 ? inputChannelData[0] : nullptr, numInputChannels > 1 ? inputChannelData[1] : nullptr,
  1406. numSamples);
  1407. std::array<const float*, 64> inputs {};
  1408. std::array<float*, 64> outputs {};
  1409. numInputChannels = juce::jmin (numInputChannels, (int) inputs.size());
  1410. numOutputChannels = juce::jmin (numOutputChannels, (int) outputs.size());
  1411. // count-in: the metronome counts the pre-roll down, then playback starts
  1412. if (const auto countIn = transport.countIn.load (std::memory_order_relaxed); countIn > 0.0 && ! transport.playing.load (std::memory_order_relaxed))
  1413. {
  1414. const auto left = countIn - numSamples * transport.ticksPerSample();
  1415. transport.countIn.store (juce::jmax (0.0, left), std::memory_order_relaxed);
  1416. if (left <= 0.0)
  1417. transport.playing.store (true, std::memory_order_relaxed);
  1418. }
  1419. for (int done = 0; done < numSamples;)
  1420. {
  1421. auto n = numSamples - done;
  1422. const auto playing = transport.playing.load (std::memory_order_relaxed);
  1423. const auto tps = transport.ticksPerSample();
  1424. const auto loopStart = transport.loopStart.load (std::memory_order_relaxed);
  1425. const auto loopEnd = transport.loopEnd.load (std::memory_order_relaxed);
  1426. const auto looping = playing && transport.songMode.load (std::memory_order_relaxed) && loopEnd > loopStart && tps > 0.0;
  1427. if (looping)
  1428. {
  1429. // before the loop, play normally until reaching it; past the end, jump back to the start
  1430. auto position = transport.positionTicks.load (std::memory_order_relaxed);
  1431. if (position >= loopEnd)
  1432. {
  1433. position = loopStart;
  1434. transport.positionTicks.store (position, std::memory_order_relaxed);
  1435. }
  1436. n = juce::jlimit (1, n, (int) std::ceil ((loopEnd - position) / tps));
  1437. }
  1438. for (int ch = 0; ch < numInputChannels; ++ch)
  1439. inputs[(std::size_t) ch] = inputChannelData[ch] != nullptr ? inputChannelData[ch] + done : nullptr;
  1440. // the block's input by device channel, for the inserts (monitoring, meters) and the takes
  1441. liveInput.numChannels = 0;
  1442. for (int c = 0; c < LiveInput::maxChannels; ++c)
  1443. {
  1444. const auto slot = inputSlot[(std::size_t) c];
  1445. liveInput.channels[(std::size_t) c] = slot >= 0 && slot < numInputChannels ? inputs[(std::size_t) slot] : nullptr;
  1446. if (liveInput.channels[(std::size_t) c] != nullptr)
  1447. liveInput.numChannels = c + 1;
  1448. }
  1449. // audio recording: this block's input goes to disk (without waiting on a lock)
  1450. if (playing && transport.recording.load (std::memory_order_relaxed))
  1451. {
  1452. const juce::SpinLock::ScopedTryLockType lock (takeLock);
  1453. if (lock.isLocked() && takeCount > 0)
  1454. {
  1455. auto wrote = false;
  1456. for (int k = 0; k < takeCount; ++k)
  1457. {
  1458. auto& take = takes[(std::size_t) k];
  1459. const std::array<const float*, 2> data { liveInput.channel (take.first, 0), liveInput.channel (take.first + take.channels - 1, 0) };
  1460. if (data[0] == nullptr || data[1] == nullptr || take.writer == nullptr)
  1461. continue;
  1462. wrote = take.writer->write (data.data(), n) || wrote;
  1463. }
  1464. if (wrote)
  1465. {
  1466. if (takeStartTick.load (std::memory_order_relaxed) < 0.0)
  1467. takeStartTick.store (transport.positionTicks.load (std::memory_order_relaxed));
  1468. takeFrames.fetch_add (n, std::memory_order_relaxed);
  1469. }
  1470. }
  1471. }
  1472. for (int ch = 0; ch < numOutputChannels; ++ch)
  1473. outputs[(std::size_t) ch] = outputChannelData[ch] != nullptr ? outputChannelData[ch] + done : nullptr;
  1474. player.audioDeviceIOCallbackWithContext (inputs.data(), numInputChannels, outputs.data(), numOutputChannels, n, context);
  1475. for (int ch = 0; ch < numOutputChannels; ++ch)
  1476. if (outputs[(std::size_t) ch] != nullptr)
  1477. softClip (outputs[(std::size_t) ch], n);
  1478. // oscilloscope: average of both sides into the ring buffer
  1479. if (numOutputChannels > 0 && outputs[0] != nullptr)
  1480. {
  1481. auto w = scopeWrite.load (std::memory_order_relaxed);
  1482. const auto* right = numOutputChannels > 1 && outputs[1] != nullptr ? outputs[1] : outputs[0];
  1483. for (int i = 0; i < n; ++i)
  1484. {
  1485. scope[(std::size_t) w].store (0.5f * (outputs[0][i] + right[i]), std::memory_order_relaxed);
  1486. w = (w + 1) % scopeSize;
  1487. }
  1488. scopeWrite.store (w, std::memory_order_release);
  1489. }
  1490. if (playing)
  1491. {
  1492. auto position = transport.positionTicks.load (std::memory_order_relaxed) + n * tps;
  1493. if (looping && position >= loopEnd - 1e-6)
  1494. position = loopStart;
  1495. transport.positionTicks.store (position, std::memory_order_relaxed);
  1496. }
  1497. done += n;
  1498. }
  1499. blockTimeMs.store (juce::Time::getMillisecondCounterHiRes(), std::memory_order_relaxed);
  1500. }
  1501. void AudioEngine::audioDeviceAboutToStart (juce::AudioIODevice* device)
  1502. {
  1503. rtStats.deviceRestarted();
  1504. transport.sampleRate.store (device->getCurrentSampleRate());
  1505. // the callback gets the open input channels only, in order: map device channel -> callback index
  1506. const auto active = device->getActiveInputChannels();
  1507. int slot = 0;
  1508. for (int c = 0; c < LiveInput::maxChannels; ++c)
  1509. inputSlot[(std::size_t) c] = active[c] ? slot++ : -1;
  1510. player.audioDeviceAboutToStart (device);
  1511. }
  1512. void AudioEngine::audioDeviceStopped()
  1513. {
  1514. player.audioDeviceStopped();
  1515. }
  1516. } // namespace lynx