AudioEngine.cpp 49 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363
  1. #include "engine/AudioEngine.h"
  2. #include "engine/FlStudio.h"
  3. #include <map>
  4. #include "engine/Text.h"
  5. #include "core/FlpImport.h"
  6. #include "core/Instruments.h"
  7. #include "core/Dither.h"
  8. #include "core/SoftClip.h"
  9. #include "engine/ChannelRackProcessor.h"
  10. #include "engine/Metronome.h"
  11. #include "core/NoteTools.h"
  12. #include "engine/PreviewPlayer.h"
  13. #include "flp/Flp.h"
  14. #if JUCE_WINDOWS
  15. #include <windows.h>
  16. #endif
  17. namespace lynx
  18. {
  19. using IONode = juce::AudioProcessorGraph::AudioGraphIOProcessor;
  20. // The FL Studio installation (registry, else the usual folders) to resolve %FLStudio...%.
  21. FlPathRoots findFlStudioRoots()
  22. {
  23. FlPathRoots roots;
  24. const auto fl = findFlStudio();
  25. if (fl.installDir.isDirectory())
  26. {
  27. roots.factoryData = fl.installDir.getFullPathName().toStdString();
  28. roots.data = fl.installDir.getChildFile ("Data").getFullPathName().toStdString();
  29. }
  30. if (fl.userData.isDirectory())
  31. roots.userData = fl.userData.getFullPathName().toStdString();
  32. roots.home = juce::File::getSpecialLocation (juce::File::userHomeDirectory).getFullPathName().toStdString();
  33. return roots;
  34. }
  35. namespace
  36. {
  37. // Audio workers with real-time priority (MMCSS "Pro Audio" on Windows, like the driver).
  38. void raiseAudioThreadPriority()
  39. {
  40. #if JUCE_WINDOWS
  41. using AvSet = void* (__stdcall*) (const wchar_t*, unsigned long*);
  42. static const auto avSet = [] () -> AvSet {
  43. if (auto* avrt = LoadLibraryW (L"avrt.dll"))
  44. return reinterpret_cast<AvSet> (reinterpret_cast<void*> (GetProcAddress (avrt, "AvSetMmThreadCharacteristicsW")));
  45. return nullptr;
  46. }();
  47. unsigned long task = 0;
  48. if (avSet == nullptr || avSet (L"Pro Audio", &task) == nullptr)
  49. SetThreadPriority (GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL);
  50. #endif
  51. }
  52. int workerCount()
  53. {
  54. // diagnostics: LYNX_WORKERS=n fixes the number of extra threads
  55. if (const auto forced = juce::SystemStats::getEnvironmentVariable ("LYNX_WORKERS", {}); forced.isNotEmpty())
  56. return juce::jlimit (0, 31, forced.getIntValue());
  57. // the audio thread works too; leave one core free for the UI
  58. const auto cores = (int) std::thread::hardware_concurrency();
  59. return juce::jlimit (0, 7, cores - 2);
  60. }
  61. juce::File midiSettingsFile() { return PluginHost::settingsFolder().getChildFile ("midi-settings.txt"); }
  62. juce::File audioDeviceFile() { return PluginHost::settingsFolder().getChildFile ("audio-device.xml"); }
  63. } // namespace
  64. // Saves the audio device setup whenever it changes (Settings › Audio, the setup wizard, a driver's own panel), so
  65. // the next start opens the same device.
  66. struct AudioEngine::DeviceStateSaver final : public juce::ChangeListener
  67. {
  68. explicit DeviceStateSaver (AudioEngine& e) : engine (e) { engine.deviceManager.addChangeListener (this); }
  69. ~DeviceStateSaver() override { engine.deviceManager.removeChangeListener (this); }
  70. void changeListenerCallback (juce::ChangeBroadcaster*) override { engine.saveAudioDeviceState(); }
  71. AudioEngine& engine;
  72. };
  73. void AudioEngine::saveAudioDeviceState()
  74. {
  75. if (auto xml = deviceManager.createStateXml())
  76. xml->writeTo (audioDeviceFile());
  77. }
  78. AudioEngine::AudioEngine (bool openAudioDevice)
  79. : workers (std::make_unique<WorkerPool> (workerCount(), raiseAudioThreadPriority)),
  80. song (Song::makeDefault())
  81. {
  82. publishSong();
  83. buildInitialGraph();
  84. if (openAudioDevice)
  85. {
  86. player.setProcessor (&graph);
  87. // 0 inputs, 2 outputs; the device of the last session (Settings › Audio) if it is still there, else the default.
  88. const auto saved = juce::XmlDocument::parse (audioDeviceFile());
  89. if (deviceManager.initialise (0, 2, saved.get(), true).isNotEmpty() && saved != nullptr)
  90. deviceManager.initialise (0, 2, nullptr, true);
  91. deviceManager.addAudioCallback (this);
  92. deviceStateSaver = std::make_unique<DeviceStateSaver> (*this);
  93. midiPrefs = midiPrefsShared = prefs::MidiPrefs::fromText (midiSettingsFile().loadFileAsString().toStdString());
  94. prefetcher = std::make_unique<StreamPrefetcher> (transport);
  95. prefetcher->update (song, samples);
  96. enableAllMidiInputs();
  97. deviceManager.addMidiInputDeviceCallback ({}, this); // {} = all inputs enabled
  98. midiDevicesChanged = juce::MidiDeviceListConnection::make ([this] { enableAllMidiInputs(); });
  99. }
  100. startTimerHz (30); // recording and collection of retired snapshots
  101. }
  102. AudioEngine::~AudioEngine()
  103. {
  104. stopTimer();
  105. {
  106. const juce::SpinLock::ScopedLockType lock (takeLock);
  107. takeWriter = nullptr; // closes the WAV of the take in progress (it stays in the recordings folder)
  108. }
  109. recordThread.stopThread (2000);
  110. prefetcher = nullptr;
  111. midiDevicesChanged = {};
  112. deviceStateSaver = nullptr;
  113. deviceManager.removeMidiInputDeviceCallback ({}, this);
  114. deviceManager.removeAudioCallback (this);
  115. player.setProcessor (nullptr);
  116. graph.clear(); // the nodes reference rackExchange and transport
  117. }
  118. void AudioEngine::buildInitialGraph()
  119. {
  120. // The output node inherits the graph's channel count at the moment it is created.
  121. // Without this the graph still has 0 outputs and JUCE silently rejects the connections.
  122. graph.setPlayConfigDetails (0, 2, transport.sampleRate.load(), 512);
  123. auto output = graph.addNode (std::make_unique<IONode> (IONode::audioOutputNode));
  124. auto rack = graph.addNode (std::make_unique<ChannelRackProcessor> (transport, rackExchange, liveEvents, midiEvents, meters, workers.get()));
  125. rackProcessor = dynamic_cast<ChannelRackProcessor*> (rack->getProcessor());
  126. auto metronome = graph.addNode (std::make_unique<Metronome> (transport));
  127. auto previewOwned = std::make_unique<PreviewPlayer>();
  128. preview = previewOwned.get();
  129. auto previewNode = graph.addNode (std::move (previewOwned));
  130. for (int channel = 0; channel < 2; ++channel)
  131. {
  132. graph.addConnection ({ { rack->nodeID, channel }, { output->nodeID, channel } });
  133. graph.addConnection ({ { metronome->nodeID, channel }, { output->nodeID, channel } });
  134. graph.addConnection ({ { previewNode->nodeID, channel }, { output->nodeID, channel } });
  135. }
  136. jassert (graph.getConnections().size() == 6);
  137. }
  138. float AudioEngine::renderOffline (const RenderOptions& options)
  139. {
  140. const auto seconds = options.seconds;
  141. const auto sampleRate = options.sampleRate;
  142. auto* output = options.output;
  143. const auto& progress = options.progress;
  144. const auto tailSeconds = options.tailSeconds;
  145. const auto trimSamples = options.trimSamples;
  146. std::optional<Dither> dither;
  147. if (options.ditherBits > 0)
  148. dither.emplace (options.ditherBits, options.ditherShaping);
  149. constexpr int blockSize = 512;
  150. constexpr float silence = 3.0e-5f; // ~ -90 dB
  151. setOfflineRendering (true); // instruments with FL render-quality settings use them (Sytrus)
  152. transport.sampleRate.store (sampleRate);
  153. graph.setPlayConfigDetails (0, 2, sampleRate, blockSize);
  154. graph.prepareToPlay (sampleRate, blockSize);
  155. if (rackProcessor != nullptr)
  156. rackProcessor->setMetering (false); // nobody looks at the meters during the render
  157. play();
  158. juce::AudioBuffer<float> buffer (2, blockSize);
  159. juce::MidiBuffer midi;
  160. float peak = 0.0f;
  161. const auto trim = (std::int64_t) juce::jmax (0, trimSamples);
  162. const auto musicSamples = (std::int64_t) (seconds * sampleRate) + trim;
  163. const auto totalSamples = musicSamples + (std::int64_t) (juce::jmax (0.0, tailSeconds) * sampleRate);
  164. std::int64_t quietSamples = 0;
  165. bool cancelled = false;
  166. lastRenderStats = {};
  167. for (std::int64_t done = 0; done < totalSamples; done += blockSize)
  168. {
  169. const auto n = (int) juce::jmin<std::int64_t> (blockSize, totalSamples - done);
  170. juce::AudioBuffer<float> view (buffer.getArrayOfWritePointers(), 2, n);
  171. view.clear();
  172. const auto before = juce::Time::getMillisecondCounterHiRes();
  173. graph.processBlock (view, midi);
  174. const auto afterGraph = juce::Time::getMillisecondCounterHiRes();
  175. lastRenderStats.graphMs += afterGraph - before;
  176. for (int ch = 0; ch < view.getNumChannels(); ++ch)
  177. softClip (view.getWritePointer (ch), n);
  178. const auto blockPeak = view.getMagnitude (0, n);
  179. peak = juce::jmax (peak, blockPeak);
  180. if (dither)
  181. for (int ch = 0; ch < view.getNumChannels(); ++ch)
  182. dither->process (view.getWritePointer (ch), n, ch);
  183. // PDC: the start is the latency's silence; the song's end arrives `trim` samples later
  184. if ((output != nullptr || options.capture) && done + n > trim)
  185. {
  186. const auto skip = (int) juce::jmax<std::int64_t> (0, trim - done);
  187. const auto beforeWrite = juce::Time::getMillisecondCounterHiRes();
  188. if (output != nullptr)
  189. output->writeFromAudioSampleBuffer (view, skip, n - skip);
  190. if (options.capture)
  191. options.capture (view.getReadPointer (0, skip), view.getReadPointer (1, skip), n - skip);
  192. lastRenderStats.writeMs += juce::Time::getMillisecondCounterHiRes() - beforeWrite;
  193. }
  194. transport.positionTicks.store (transport.positionTicks.load() + n * transport.ticksPerSample());
  195. // in the tail: half a second of silence ends it
  196. if (done + n > musicSamples)
  197. {
  198. quietSamples = blockPeak < silence ? quietSamples + n : 0;
  199. if (quietSamples > (std::int64_t) (sampleRate * 0.5))
  200. break;
  201. }
  202. if (progress && (done / blockSize) % 32 == 0 && ! progress ((double) done / (double) juce::jmax<std::int64_t> (1, totalSamples)))
  203. {
  204. cancelled = true;
  205. break;
  206. }
  207. }
  208. stop();
  209. if (rackProcessor != nullptr)
  210. rackProcessor->setMetering (true);
  211. graph.releaseResources();
  212. setOfflineRendering (false);
  213. return cancelled ? -1.0f : peak;
  214. }
  215. ProcessTimes* AudioEngine::getProcessTimes() noexcept
  216. {
  217. return rackProcessor != nullptr ? &rackProcessor->processTimes() : nullptr;
  218. }
  219. void AudioEngine::play() noexcept { transport.playing.store (true); }
  220. void AudioEngine::stop() noexcept
  221. {
  222. waitingForInput.store (false);
  223. transport.countIn.store (0.0);
  224. transport.playing.store (false);
  225. }
  226. void AudioEngine::setRecordOptions (const RecordOptions& options)
  227. {
  228. recordOptions = options;
  229. recordOptions.countInBars = juce::jlimit (0, 4, options.countInBars);
  230. sendChangeMessage();
  231. }
  232. void AudioEngine::startPlayback()
  233. {
  234. if (! transport.recording.load())
  235. {
  236. play();
  237. return;
  238. }
  239. if (recordOptions.waitForInput)
  240. {
  241. waitingForInput.store (true);
  242. sendChangeMessage();
  243. return;
  244. }
  245. if (recordOptions.countInBars > 0)
  246. {
  247. const auto at = (std::int64_t) transport.positionTicks.load();
  248. transport.countIn.store ((double) countInLength (song, recordOptions.countInBars, at));
  249. sendChangeMessage();
  250. return;
  251. }
  252. play();
  253. }
  254. void AudioEngine::startOnInput() noexcept
  255. {
  256. if (waitingForInput.exchange (false))
  257. transport.playing.store (true);
  258. }
  259. void AudioEngine::setInsertArmed (int track, bool armed)
  260. {
  261. const auto it = std::find (armedInserts.begin(), armedInserts.end(), track);
  262. const auto wasArmed = it != armedInserts.end();
  263. if (armed == wasArmed || track <= 0)
  264. return;
  265. if (armed)
  266. armedInserts.push_back (track);
  267. else
  268. armedInserts.erase (it);
  269. if (armed && ! audioArmed)
  270. setAudioRecordingArmed (true);
  271. else if (! armed && armedInserts.empty() && audioArmed)
  272. setAudioRecordingArmed (false);
  273. sendChangeMessage();
  274. }
  275. bool AudioEngine::isInsertArmed (int track) const noexcept
  276. {
  277. return std::find (armedInserts.begin(), armedInserts.end(), track) != armedInserts.end();
  278. }
  279. void AudioEngine::rewind() noexcept { transport.rewindRequested.store (true); }
  280. void AudioEngine::seek (double ticks) noexcept { transport.seekRequest.store (juce::jmax (0.0, ticks)); }
  281. void AudioEngine::copyScope (float* destination, int count) const noexcept
  282. {
  283. count = juce::jmin (count, scopeSize);
  284. auto r = (scopeWrite.load (std::memory_order_acquire) - count + scopeSize) % scopeSize;
  285. for (int i = 0; i < count; ++i)
  286. {
  287. destination[i] = scope[(std::size_t) r].load (std::memory_order_relaxed);
  288. r = (r + 1) % scopeSize;
  289. }
  290. }
  291. void AudioEngine::previewFile (const juce::File& file)
  292. {
  293. if (preview != nullptr)
  294. preview->play (file.existsAsFile() ? samples.load (file.getFullPathName()) : nullptr);
  295. }
  296. void AudioEngine::setInputScale (int scale, int root) noexcept
  297. {
  298. inputScaleRoot.store (root);
  299. inputScale.store (scale);
  300. }
  301. int AudioEngine::snapInputKey (int key) const noexcept
  302. {
  303. const auto scale = inputScale.load();
  304. return scale > 0 ? notetools::snapToScale (key, inputScaleRoot.load(), scale) : key;
  305. }
  306. void AudioEngine::previewSample (std::shared_ptr<const SampleData> sample, bool loop, float gain)
  307. {
  308. if (preview != nullptr)
  309. preview->play (std::move (sample), loop, gain);
  310. }
  311. double AudioEngine::getPreviewPosition() const noexcept
  312. {
  313. return preview != nullptr ? preview->getPlayPosition() : -1.0;
  314. }
  315. void AudioEngine::sendLiveNote (int channel, int key, float velocity, bool on, bool record)
  316. {
  317. if (record) // played notes (the PC keyboard) follow the scale snap; previews don't
  318. {
  319. // the note-off stops the key its note-on started, even if the snap changed in between
  320. const auto requested = key;
  321. if (on)
  322. {
  323. key = snapInputKey (key);
  324. playedKeys.on (channel, requested, key);
  325. startOnInput();
  326. }
  327. else
  328. key = playedKeys.off (channel, requested, snapInputKey (key));
  329. }
  330. NoteEvent e;
  331. e.type = on ? NoteEvent::Type::on : NoteEvent::Type::off;
  332. e.channel = channel;
  333. e.key = key;
  334. e.velocity = velocity;
  335. liveEvents.push (e);
  336. if (record && transport.recording.load() && transport.playing.load())
  337. uiRecorded.push_back ({ estimatedPositionNow(), channel, key, velocity, on });
  338. }
  339. void AudioEngine::panic()
  340. {
  341. NoteEvent e;
  342. e.type = NoteEvent::Type::choke;
  343. e.channel = -1; // every channel
  344. liveEvents.push (e);
  345. }
  346. double AudioEngine::estimatedPositionNow() const noexcept
  347. {
  348. // the position only moves block by block; interpolate by the time since the last block
  349. auto tick = transport.positionTicks.load (std::memory_order_relaxed);
  350. if (transport.playing.load (std::memory_order_relaxed))
  351. {
  352. const auto elapsedMs = juce::jlimit (0.0, 100.0, juce::Time::getMillisecondCounterHiRes() - blockTimeMs.load());
  353. tick += elapsedMs * 0.001 * transport.sampleRate.load() * transport.ticksPerSample();
  354. }
  355. return tick;
  356. }
  357. void AudioEngine::updateAudioRecording()
  358. {
  359. const auto wantTake = audioArmed && transport.recording.load();
  360. // the file is ready before Play: the very first block gets recorded
  361. if (wantTake && takeWriter == nullptr && recordingError.isEmpty())
  362. startAudioTake();
  363. // playback stopped (or recording turned off) with something recorded: close the take
  364. if (takeWriter != nullptr && (! wantTake || ! transport.playing.load()) && takeFrames.load() > 0)
  365. finishAudioTake();
  366. else if (takeWriter != nullptr && ! wantTake)
  367. finishAudioTake();
  368. }
  369. void AudioEngine::startAudioTake()
  370. {
  371. auto* device = deviceManager.getCurrentAudioDevice();
  372. if (device == nullptr)
  373. return;
  374. takeChannels = juce::jlimit (0, 2, device->getActiveInputChannels().countNumberOfSetBits());
  375. if (takeChannels == 0)
  376. {
  377. recordingError = utf8 ("no active audio input");
  378. return;
  379. }
  380. const auto folder = juce::File::getSpecialLocation (juce::File::userMusicDirectory).getChildFile ("LYNX/Recordings");
  381. folder.createDirectory();
  382. takeFile = folder.getNonexistentChildFile ("Take " + juce::Time::getCurrentTime().formatted ("%Y-%m-%d %H-%M-%S"), ".wav");
  383. takeSampleRate = device->getCurrentSampleRate();
  384. takeLatency = device->getInputLatencyInSamples() + device->getOutputLatencyInSamples();
  385. juce::WavAudioFormat wav;
  386. auto stream = takeFile.createOutputStream();
  387. if (stream == nullptr)
  388. {
  389. recordingError = utf8 ("could not create ") + takeFile.getFullPathName();
  390. return;
  391. }
  392. auto* writer = wav.createWriterFor (stream.get(), takeSampleRate, (unsigned int) takeChannels, 24, {}, 0);
  393. if (writer == nullptr)
  394. {
  395. stream.reset();
  396. takeFile.deleteFile();
  397. recordingError = utf8 ("WAV does not accept this sample rate/channel count");
  398. return;
  399. }
  400. stream.release(); // now owned by the writer
  401. takeStartTick.store (-1.0);
  402. takeFrames.store (0);
  403. auto threaded = std::make_unique<juce::AudioFormatWriter::ThreadedWriter> (writer, recordThread, 1 << 18);
  404. const juce::SpinLock::ScopedLockType lock (takeLock);
  405. takeWriter = std::move (threaded);
  406. }
  407. void AudioEngine::finishAudioTake()
  408. {
  409. std::unique_ptr<juce::AudioFormatWriter::ThreadedWriter> done;
  410. {
  411. const juce::SpinLock::ScopedLockType lock (takeLock);
  412. done = std::move (takeWriter);
  413. }
  414. done.reset(); // drains the queue and closes the WAV
  415. const auto frames = takeFrames.exchange (0);
  416. const auto startTick = takeStartTick.exchange (-1.0);
  417. if (frames <= 0 || startTick < 0.0)
  418. {
  419. takeFile.deleteFile();
  420. return;
  421. }
  422. // what came into the interface corresponds to what was heard one latency earlier
  423. const auto ticksPerSample = song.bpm * ppq / (60.0 * takeSampleRate);
  424. auto start = (std::int64_t) std::llround (startTick - takeLatency * ticksPerSample);
  425. std::int64_t offset = 0;
  426. if (start < 0)
  427. {
  428. offset = -start;
  429. start = 0;
  430. }
  431. const auto length = (std::int64_t) std::llround ((double) frames * ticksPerSample) - offset;
  432. if (length <= 0)
  433. return;
  434. const auto path = takeFile.getFullPathName().toStdString();
  435. const auto name = takeFile.getFileNameWithoutExtension().toStdString();
  436. const auto armedTrack = armedInserts.empty() ? 0 : armedInserts.front(); // the take plays through the armed insert
  437. editSong ([=] (Song& s) {
  438. ChannelDef c;
  439. c.name = name;
  440. c.instrument = InstrumentKind::audioClip;
  441. c.samplePath = path;
  442. c.mixerTrack = armedTrack > 0 && armedTrack < (int) s.mixer.size() ? armedTrack : s.nextFreeInsert();
  443. s.channels.push_back (c);
  444. int track = 0;
  445. for (const auto& clip : s.playlist)
  446. track = std::max (track, clip.track + 1);
  447. Clip clip;
  448. clip.kind = ClipKind::audio;
  449. clip.channel = (int) s.channels.size() - 1;
  450. clip.track = track;
  451. clip.start = start;
  452. clip.length = length;
  453. clip.offset = offset;
  454. s.playlist.push_back (clip);
  455. });
  456. }
  457. void AudioEngine::handleIncomingMidiMessage (juce::MidiInput* source, const juce::MidiMessage& m)
  458. {
  459. // MIDI thread: queues and atomics only (and a short copy of the device settings)
  460. prefs::MidiInputPrefs device;
  461. auto velocityCurve = prefs::VelocityCurve::linear;
  462. {
  463. const juce::SpinLock::ScopedLockType lock (midiPrefsLock);
  464. device = midiPrefsShared.input (source != nullptr ? source->getName().toStdString() : std::string());
  465. velocityCurve = midiPrefsShared.velocity;
  466. }
  467. if (! device.enabled || (device.midiChannel != 0 && m.getChannel() != device.midiChannel))
  468. return;
  469. if (m.isController())
  470. {
  471. controllerQueue.push ({ m.getControllerNumber(), m.getChannel() - 1, m.getControllerValue() });
  472. return;
  473. }
  474. if (! m.isNoteOnOrOff())
  475. return;
  476. const auto on = m.isNoteOn();
  477. if (on)
  478. startOnInput();
  479. // a note-off goes to the channels and key its note-on reached (the selection or the scale snap may have
  480. // changed while the key was down); a repeated note-on first stops what the previous one started
  481. InputHeldNotes::Target targets[InputHeldNotes::maxTargets], stale[InputHeldNotes::maxTargets];
  482. auto count = 0;
  483. auto staleCount = 0;
  484. if (on)
  485. {
  486. const auto key = snapInputKey (m.getNoteNumber());
  487. const auto extra = juce::jlimit (0, maxLiveChannels, extraLiveCount.load());
  488. // the primary selected channel, then the other selected ones (or the device's own channel)
  489. if (device.target >= 0)
  490. targets[count++] = { device.target, key };
  491. else
  492. for (int i = -1; i < extra && count < InputHeldNotes::maxTargets; ++i)
  493. targets[count++] = { i < 0 ? liveChannel.load() : extraLiveChannels[(std::size_t) i].load(), key };
  494. staleCount = midiHeld.noteOn (m.getNoteNumber(), targets, count, stale);
  495. }
  496. else
  497. count = midiHeld.noteOff (m.getNoteNumber(), targets);
  498. auto push = [this] (const InputHeldNotes::Target& t, bool noteOn, float velocity) {
  499. NoteEvent e;
  500. e.type = noteOn ? NoteEvent::Type::on : NoteEvent::Type::off;
  501. e.channel = t.channel;
  502. e.key = t.key;
  503. e.velocity = velocity;
  504. midiEvents.push (e);
  505. if (transport.recording.load() && transport.playing.load())
  506. midiRecordQueue.push ({ estimatedPositionNow(), e.channel, e.key, e.velocity, noteOn });
  507. };
  508. for (int i = 0; i < staleCount; ++i)
  509. push (stale[i], false, 0.0f);
  510. for (int i = 0; i < count; ++i)
  511. push (targets[i], on, on ? prefs::mapVelocity (m.getFloatVelocity(), velocityCurve) : 0.0f);
  512. }
  513. void AudioEngine::enableAllMidiInputs()
  514. {
  515. // (a device turned off in the MIDI settings is closed, so other programs can use it)
  516. for (const auto& device : juce::MidiInput::getAvailableDevices())
  517. {
  518. const auto on = midiPrefs.input (device.name.toStdString()).enabled;
  519. if (deviceManager.isMidiInputDeviceEnabled (device.identifier) != on)
  520. deviceManager.setMidiInputDeviceEnabled (device.identifier, on);
  521. }
  522. }
  523. void AudioEngine::setMidiPrefs (const prefs::MidiPrefs& p, bool save)
  524. {
  525. midiPrefs = p;
  526. {
  527. const juce::SpinLock::ScopedLockType lock (midiPrefsLock);
  528. midiPrefsShared = p;
  529. }
  530. if (! p.pickup)
  531. pickups.clear();
  532. if (prefetcher != nullptr) // (only with an audio device: the real app)
  533. enableAllMidiInputs();
  534. if (save)
  535. midiSettingsFile().replaceWithText (juce::String (p.toText()));
  536. sendChangeMessage();
  537. }
  538. void AudioEngine::setUndoLevels (int levels)
  539. {
  540. maxUndoSteps = (std::size_t) prefs::clampUndoLevels (levels);
  541. while (undoStack.size() > maxUndoSteps)
  542. undoStack.pop_front();
  543. }
  544. juce::StringArray AudioEngine::getActiveMidiInputs() const
  545. {
  546. juce::StringArray names;
  547. for (const auto& device : juce::MidiInput::getAvailableDevices())
  548. if (deviceManager.isMidiInputDeviceEnabled (device.identifier))
  549. names.add (device.name);
  550. return names;
  551. }
  552. void AudioEngine::setAudioRecordingArmed (bool armed)
  553. {
  554. audioArmed = armed;
  555. if (armed)
  556. {
  557. recordingError = openAudioInput();
  558. if (! recordThread.isThreadRunning())
  559. recordThread.startThread();
  560. }
  561. sendChangeMessage();
  562. }
  563. juce::String AudioEngine::openAudioInput()
  564. {
  565. // opens the default input (stereo if possible) on the same device/driver type
  566. auto setup = deviceManager.getAudioDeviceSetup();
  567. if (auto* type = deviceManager.getCurrentDeviceTypeObject(); type != nullptr && setup.inputDeviceName.isEmpty())
  568. {
  569. const auto names = type->getDeviceNames (true);
  570. const auto index = type->getDefaultDeviceIndex (true);
  571. if (juce::isPositiveAndBelow (index, names.size()))
  572. setup.inputDeviceName = names[index];
  573. }
  574. setup.useDefaultInputChannels = false;
  575. setup.inputChannels.clear();
  576. setup.inputChannels.setRange (0, 2, true);
  577. return deviceManager.setAudioDeviceSetup (setup, true);
  578. }
  579. void AudioEngine::setRecording (bool shouldRecord)
  580. {
  581. transport.recording.store (shouldRecord);
  582. updateRecording();
  583. sendChangeMessage();
  584. }
  585. void AudioEngine::updateRecording()
  586. {
  587. const auto playing = transport.playing.load();
  588. const auto active = transport.recording.load() && playing;
  589. if (playing)
  590. lastPlayingTick = estimatedPositionNow();
  591. // the take starts when playing with recording on, or at the first recorded event
  592. // (which is only queued in that situation, even if this timer hasn't seen it yet)
  593. auto beginTake = [this] {
  594. if (recorder.isActive())
  595. return;
  596. const auto& pattern = song.patterns[(std::size_t) song.currentPattern];
  597. recorder.begin (pattern.effectiveLength (song.beatsPerBar));
  598. takeHasUndoStep = false;
  599. takeClearedChannels.clear();
  600. takeStartPosition = lastPlayingTick;
  601. };
  602. if (active)
  603. beginTake();
  604. RecordedEvent e;
  605. while (midiRecordQueue.pop (e))
  606. {
  607. beginTake();
  608. recorder.add (song, e);
  609. }
  610. for (const auto& ui : uiRecorded)
  611. {
  612. beginTake();
  613. recorder.add (song, ui);
  614. }
  615. uiRecorded.clear();
  616. updateAudioRecording();
  617. if (! active && recorder.isActive())
  618. recorder.end (song, lastPlayingTick);
  619. auto notes = recorder.takeFinished();
  620. if (notes.empty())
  621. return;
  622. // the whole take is a single undo step: overdub or replace, quantised to the record grid; in song mode a
  623. // clip of the pattern is placed where recording started if none plays there
  624. const auto options = recordOptions;
  625. const auto placeClipAt = (std::int64_t) takeStartPosition;
  626. editSong ([&] (Song& s) {
  627. commitTake (s.patterns[(std::size_t) s.currentPattern], notes, options.mode, options.quantise, takeClearedChannels);
  628. if (options.placeSongClip && s.mode == PlayMode::song && ! takeHasUndoStep)
  629. placePatternClipAt (s, s.currentPattern, placeClipAt);
  630. }, ! takeHasUndoStep);
  631. takeHasUndoStep = true;
  632. }
  633. void AudioEngine::setSong (Song newSong)
  634. {
  635. undoStack.clear();
  636. redoStack.clear();
  637. song = std::move (newSong);
  638. selectedChannel = 0;
  639. selectedChannels = { 0 };
  640. modified = false;
  641. publishSong();
  642. }
  643. void AudioEngine::editSong (const std::function<void (Song&)>& edit, bool undoable)
  644. {
  645. if (undoable)
  646. {
  647. // Dozens of edits arrive during a drag; only the first one of the click saves the state.
  648. bool samePress = false;
  649. if (juce::ModifierKeys::currentModifiers.isAnyMouseButtonDown())
  650. {
  651. const auto press = juce::Desktop::getInstance().getMainMouseSource().getLastMouseDownTime();
  652. samePress = press == lastUndoPress;
  653. lastUndoPress = press;
  654. }
  655. else
  656. {
  657. lastUndoPress = {};
  658. }
  659. if (! samePress)
  660. {
  661. undoStack.push_back (song);
  662. redoStack.clear();
  663. if (undoStack.size() > maxUndoSteps)
  664. undoStack.pop_front();
  665. }
  666. }
  667. if (undoable)
  668. modified = true;
  669. edit (song);
  670. publishSong();
  671. }
  672. void AudioEngine::undo()
  673. {
  674. if (undoStack.empty())
  675. return;
  676. redoStack.push_back (std::move (song));
  677. song = std::move (undoStack.back());
  678. undoStack.pop_back();
  679. modified = true;
  680. lastUndoPress = {};
  681. publishSong();
  682. }
  683. void AudioEngine::redo()
  684. {
  685. if (redoStack.empty())
  686. return;
  687. undoStack.push_back (std::move (song));
  688. song = std::move (redoStack.back());
  689. redoStack.pop_back();
  690. modified = true;
  691. lastUndoPress = {};
  692. publishSong();
  693. }
  694. namespace
  695. {
  696. const Song& historyState (const std::deque<Song>& undo, const Song& current, const std::deque<Song>& redo, int index)
  697. {
  698. if (index < (int) undo.size())
  699. return undo[(std::size_t) index];
  700. if (index == (int) undo.size())
  701. return current;
  702. return redo[redo.size() - 1 - (std::size_t) (index - (int) undo.size() - 1)];
  703. }
  704. } // namespace
  705. ChangeLabel AudioEngine::getHistoryLabel (int index) const
  706. {
  707. if (index <= 0 || index >= getHistorySize())
  708. return { TR_NOOP ("Start"), {} };
  709. return describeChange (historyState (undoStack, song, redoStack, index - 1), historyState (undoStack, song, redoStack, index));
  710. }
  711. void AudioEngine::jumpToHistory (int index)
  712. {
  713. index = juce::jlimit (0, getHistorySize() - 1, index);
  714. if (index == getHistoryPosition())
  715. return;
  716. // move through the stacks, then publish once
  717. while (getHistoryPosition() > index && ! undoStack.empty())
  718. {
  719. redoStack.push_back (std::move (song));
  720. song = std::move (undoStack.back());
  721. undoStack.pop_back();
  722. }
  723. while (getHistoryPosition() < index && ! redoStack.empty())
  724. {
  725. undoStack.push_back (std::move (song));
  726. song = std::move (redoStack.back());
  727. redoStack.pop_back();
  728. }
  729. modified = true;
  730. lastUndoPress = {};
  731. publishSong();
  732. }
  733. void AudioEngine::setSelectedChannel (int channel)
  734. {
  735. channel = juce::jlimit (0, juce::jmax (0, (int) song.channels.size() - 1), channel);
  736. setChannelSelection ({ channel }, channel);
  737. }
  738. void AudioEngine::setChannelSelection (std::vector<int> channels, int primary)
  739. {
  740. const auto count = (int) song.channels.size();
  741. std::sort (channels.begin(), channels.end());
  742. channels.erase (std::unique (channels.begin(), channels.end()), channels.end());
  743. channels.erase (std::remove_if (channels.begin(), channels.end(), [count] (int c) { return c < 0 || c >= count; }), channels.end());
  744. primary = juce::jlimit (0, juce::jmax (0, count - 1), primary);
  745. if (std::find (channels.begin(), channels.end(), primary) == channels.end())
  746. channels.insert (std::lower_bound (channels.begin(), channels.end(), primary), primary);
  747. if (channels == selectedChannels && primary == selectedChannel)
  748. {
  749. publishSelection();
  750. return;
  751. }
  752. selectedChannels = std::move (channels);
  753. selectedChannel = primary;
  754. publishSelection();
  755. sendChangeMessage();
  756. }
  757. void AudioEngine::publishSelection()
  758. {
  759. liveChannel.store (selectedChannel);
  760. int extra = 0;
  761. for (auto c : selectedChannels)
  762. if (c != selectedChannel && extra < maxLiveChannels)
  763. extraLiveChannels[(std::size_t) extra++].store (c);
  764. extraLiveCount.store (extra);
  765. }
  766. bool AudioEngine::importFlpFile (const juce::File& file, juce::String& error, const std::map<std::string, std::string>& relocations, bool asEdit)
  767. {
  768. juce::MemoryBlock data;
  769. if (! file.loadFileAsData (data))
  770. {
  771. error = utf8 ("could not read the file");
  772. return false;
  773. }
  774. try
  775. {
  776. const auto project = flp::parseProject ({ static_cast<const std::uint8_t*> (data.getData()), data.getSize() });
  777. FlpImportOptions options;
  778. options.roots = findFlStudioRoots();
  779. options.projectFolder = file.getParentDirectory().getFullPathName().toStdString();
  780. options.fileExists = [] (const std::string& path) { return juce::File (juce::String::fromUTF8 (path.c_str())).existsAsFile(); };
  781. options.readFile = [] (const std::string& path) {
  782. juce::MemoryBlock data;
  783. juce::File (juce::String::fromUTF8 (path.c_str())).loadFileAsData (data);
  784. const auto* bytes = static_cast<const std::uint8_t*> (data.getData());
  785. return std::vector<std::uint8_t> (bytes, bytes + data.getSize());
  786. };
  787. options.sampleFrames = [this] (const std::string& path) -> std::int64_t {
  788. const auto sample = samples.load (juce::String::fromUTF8 (path.c_str()));
  789. return sample != nullptr ? (std::int64_t) sample->frames() : 0;
  790. };
  791. // WAV that only exists inside the .flp (Slicex): goes to %APPDATA%\LYNX\flp-embedded, keyed by content
  792. options.saveEmbedded = [] (const std::vector<std::uint8_t>& wav, const std::string& name) -> std::string {
  793. const auto folder = PluginHost::settingsFolder().getChildFile ("flp-embedded");
  794. folder.createDirectory();
  795. const auto hash = juce::String::toHexString ((juce::int64) juce::DefaultHashFunctions::generateHash (
  796. juce::String::createStringFromData (wav.data(), (int) juce::jmin<std::size_t> (wav.size(), 65536)) + juce::String ((juce::int64) wav.size()),
  797. 0x7FFFFFFF));
  798. const auto file = folder.getChildFile (juce::File::createLegalFileName (juce::String::fromUTF8 (name.c_str())) + "-" + hash + ".wav");
  799. if (! file.existsAsFile() && ! file.replaceWithData (wav.data(), wav.size()))
  800. return {};
  801. return file.getFullPathName().toStdString();
  802. };
  803. importReport = {};
  804. options.report = &importReport;
  805. options.relocations = relocations;
  806. auto imported = importFlp (project, options);
  807. // the project's third-party plugins, to say which channel/insert used each one that is missing
  808. struct Use
  809. {
  810. std::string name, user;
  811. bool instrument;
  812. };
  813. std::vector<Use> uses;
  814. for (const auto& c : imported.channels)
  815. if (c.plugin.foreign.format != ForeignPlugin::Format::none)
  816. uses.push_back ({ c.plugin.foreign.name, c.name, true });
  817. for (std::size_t t = 0; t < imported.mixer.size(); ++t)
  818. for (const auto& fx : imported.mixer[t].effects)
  819. if (fx.kind == EffectKind::plugin && fx.plugin.foreign.format != ForeignPlugin::Format::none)
  820. uses.push_back ({ fx.plugin.foreign.name, imported.mixer[t].name.empty() ? (t == 0 ? std::string ("Master") : "Insert " + std::to_string (t))
  821. : imported.mixer[t].name,
  822. false });
  823. juce::StringArray missing;
  824. juce::StringArray matched;
  825. plugins.adoptFlPlugins (imported, &missing, &matched);
  826. missingPlugins = missing;
  827. matchedPlugins = matched;
  828. missingPluginDetails.clear();
  829. for (const auto& name : missing)
  830. {
  831. MissingPlugin m;
  832. m.name = name.toStdString();
  833. for (const auto& u : uses)
  834. if (u.name == m.name)
  835. {
  836. if (std::find (m.usedBy.begin(), m.usedBy.end(), u.user) == m.usedBy.end())
  837. m.usedBy.push_back (u.user);
  838. m.replacement = u.instrument ? "Built-in synth (a preset chosen by the channel name)" : "Nothing: the slot was left out of the mixer";
  839. }
  840. missingPluginDetails.push_back (std::move (m));
  841. }
  842. if (asEdit)
  843. {
  844. editSong ([&imported] (Song& s) { s = std::move (imported); });
  845. return true;
  846. }
  847. stop();
  848. rewind();
  849. setSong (std::move (imported));
  850. return true;
  851. }
  852. catch (const flp::Error& e)
  853. {
  854. error = juce::String::fromUTF8 (e.what());
  855. return false;
  856. }
  857. }
  858. void AudioEngine::publishSong()
  859. {
  860. song.currentPattern = juce::jlimit (0, juce::jmax (0, (int) song.patterns.size() - 1), song.currentPattern);
  861. selectedChannel = juce::jlimit (0, juce::jmax (0, (int) song.channels.size() - 1), selectedChannel);
  862. {
  863. const auto count = (int) song.channels.size();
  864. selectedChannels.erase (std::remove_if (selectedChannels.begin(), selectedChannels.end(), [count] (int c) { return c >= count; }),
  865. selectedChannels.end());
  866. if (std::find (selectedChannels.begin(), selectedChannels.end(), selectedChannel) == selectedChannels.end())
  867. selectedChannels.insert (std::lower_bound (selectedChannels.begin(), selectedChannels.end(), selectedChannel), selectedChannel);
  868. }
  869. publishSelection();
  870. transport.bpm.store (song.bpm);
  871. transport.beatsPerBar.store (song.beatsPerBar);
  872. {
  873. // time-signature table for the metronome: the start (beatsPerBar/4) and each signature change
  874. transport.signatureVersion.fetch_add (1, std::memory_order_acq_rel); // odd: writing
  875. int count = 0;
  876. transport.signatureTick[0].store (0, std::memory_order_relaxed);
  877. transport.signatureLength[0].store ((std::int64_t) ppq * juce::jmax (1, song.beatsPerBar), std::memory_order_relaxed);
  878. ++count;
  879. for (const auto& m : song.markers())
  880. if (m.isSignature() && count < Transport::maxSignatures)
  881. {
  882. const auto length = juce::jmax<std::int64_t> (1, (std::int64_t) ppq * 4 * m.numerator / juce::jmax (1, m.denominator));
  883. const auto slot = m.tick <= 0 ? 0 : count++; // at position 0 it replaces the default
  884. transport.signatureTick[(std::size_t) slot].store (juce::jmax<std::int64_t> (0, m.tick), std::memory_order_relaxed);
  885. transport.signatureLength[(std::size_t) slot].store (length, std::memory_order_relaxed);
  886. }
  887. transport.signatureCount.store (count, std::memory_order_relaxed);
  888. transport.signatureVersion.fetch_add (1, std::memory_order_acq_rel); // even: ready
  889. }
  890. transport.songMode.store (song.mode == PlayMode::song);
  891. transport.loopStart.store ((double) song.loopStart);
  892. transport.loopEnd.store ((double) song.loopEnd);
  893. RackState::Factories factories;
  894. factories.samples = [this] (const std::string& path) { return samples.load (juce::String::fromUTF8 (path.c_str())); };
  895. factories.stretchedSamples = [this] (const std::string& path, double ratio) {
  896. return samples.loadStretched (juce::String::fromUTF8 (path.c_str()), ratio);
  897. };
  898. factories.pluginInstruments = [this] (const PluginRef& ref, double sr) { return plugins.makeInstrument (ref, sr); };
  899. factories.pluginEffects = [this] (const PluginRef& ref, double sr) { return plugins.makeEffect (ref, sr); };
  900. auto state = RackState::build (song, &lastPublishedShape, transport.sampleRate.load(), factories);
  901. // what the next build needs to reuse instruments and effects
  902. lastPublishedShape.song.channels = song.channels;
  903. lastPublishedShape.song.mixer = song.mixer;
  904. lastPublishedShape.instruments = state->instruments;
  905. lastPublishedShape.effects = state->effects;
  906. lastPublishedShape.sampleRate = state->sampleRate;
  907. lastPublishedShape.latencies = state->latencies;
  908. lastPublishedShape.pdc = state->pdc;
  909. lastPublishedShape.channelDelays = state->channelDelays;
  910. lastPublishedShape.sendDelays = state->sendDelays;
  911. rackExchange.publish (std::move (state));
  912. if (prefetcher != nullptr)
  913. prefetcher->update (song, samples);
  914. sendChangeMessage();
  915. }
  916. void AudioEngine::learnMidiController (const AutomationTarget& target)
  917. {
  918. learning = target;
  919. sendChangeMessage();
  920. }
  921. void AudioEngine::applyControllers()
  922. {
  923. ControllerEvent e;
  924. std::map<std::pair<int, int>, int> latest; // (cc, channel) -> latest value this frame
  925. while (controllerQueue.pop (e))
  926. {
  927. if (learning.kind != AutomationTargetKind::none)
  928. {
  929. // MIDI learn: replace the old link for the same target with the new one
  930. editSong ([t = learning, e] (Song& s) {
  931. s.midiLinks.erase (std::remove_if (s.midiLinks.begin(), s.midiLinks.end(), [&] (const MidiLink& l) { return l.target == t; }),
  932. s.midiLinks.end());
  933. s.midiLinks.push_back ({ e.cc, e.channel, t });
  934. });
  935. learning = {};
  936. }
  937. latest[{ e.cc, e.channel }] = e.value;
  938. }
  939. if (latest.empty() || song.midiLinks.empty())
  940. return;
  941. // one snapshot per frame, outside the undo history (like turning the knob)
  942. std::vector<std::pair<AutomationTarget, float>> changes;
  943. for (const auto& [key, value] : latest)
  944. for (const auto& link : song.midiLinks)
  945. if (link.cc == key.first && (link.channel < 0 || link.channel == key.second))
  946. {
  947. const auto v = value / 127.0f;
  948. const auto& t = link.target;
  949. // takeover: only parameters the song holds (a plugin's own parameters have no value to compare here)
  950. const auto songHeld = t.kind != AutomationTargetKind::channelParam && t.kind != AutomationTargetKind::effectParam;
  951. if (midiPrefs.pickup && songHeld)
  952. {
  953. auto& state = pickups[{ key.first, key.second, (int) t.kind, t.index, t.slot, t.param }];
  954. if (! prefs::pickupUpdate (state, song.targetValue (t), v))
  955. continue;
  956. }
  957. changes.push_back ({ t, v });
  958. }
  959. std::vector<std::pair<AutomationTarget, float>> pluginChanges;
  960. editSong ([&] (Song& s) {
  961. for (const auto& [target, v] : changes)
  962. if (! s.setTargetValue (target, v))
  963. pluginChanges.push_back ({ target, v });
  964. }, false);
  965. // plugin parameters live in the plugin
  966. for (const auto& [target, v] : pluginChanges)
  967. {
  968. juce::AudioPluginInstance* plugin = nullptr;
  969. if (target.kind == AutomationTargetKind::channelParam)
  970. if (auto* p = dynamic_cast<PluginInstrument*> (getChannelInstrument (target.index).get()))
  971. plugin = &p->getInstance();
  972. if (target.kind == AutomationTargetKind::effectParam)
  973. if (auto* p = dynamic_cast<PluginEffect*> (getEffect (target.index, target.slot).get()))
  974. plugin = &p->getInstance();
  975. if (plugin != nullptr && target.param >= 0 && target.param < plugin->getParameters().size())
  976. plugin->getParameters()[target.param]->setValueNotifyingHost (v);
  977. }
  978. }
  979. void AudioEngine::timerCallback()
  980. {
  981. applyControllers();
  982. updateRecording();
  983. rackExchange.collectGarbage();
  984. // Plugins are prepared at a fixed rate; if the device changed rate, recreate them.
  985. // A plugin whose latency changed (preset change, lookahead) requests a new PDC plan.
  986. if (std::abs (transport.sampleRate.load() - lastPublishedShape.sampleRate) > 0.5
  987. || lastPublishedShape.currentLatencies() != lastPublishedShape.latencies)
  988. publishSong();
  989. }
  990. std::shared_ptr<Instrument> AudioEngine::getChannelInstrument (int channel) const
  991. {
  992. if (channel < 0 || channel >= (int) lastPublishedShape.instruments.size())
  993. return nullptr;
  994. return lastPublishedShape.instruments[(std::size_t) channel];
  995. }
  996. std::shared_ptr<Effect> AudioEngine::getEffect (int track, int slot) const
  997. {
  998. const auto& effects = lastPublishedShape.effects;
  999. if (track < 0 || track >= (int) effects.size() || slot < 0 || slot >= (int) effects[(std::size_t) track].size())
  1000. return nullptr;
  1001. return effects[(std::size_t) track][(std::size_t) slot];
  1002. }
  1003. void AudioEngine::capturePluginStates()
  1004. {
  1005. // Changes only the saved state (recreates nothing and doesn't enter the undo history).
  1006. for (std::size_t i = 0; i < song.channels.size(); ++i)
  1007. if (auto* p = dynamic_cast<PluginInstrument*> (getChannelInstrument ((int) i).get()))
  1008. song.channels[i].plugin.state = capturePluginState (p->getInstance());
  1009. for (std::size_t t = 0; t < song.mixer.size(); ++t)
  1010. for (std::size_t s = 0; s < song.mixer[t].effects.size(); ++s)
  1011. if (auto* p = dynamic_cast<PluginEffect*> (getEffect ((int) t, (int) s).get()))
  1012. song.mixer[t].effects[s].plugin.state = capturePluginState (p->getInstance());
  1013. lastPublishedShape.song.channels = song.channels;
  1014. lastPublishedShape.song.mixer = song.mixer;
  1015. }
  1016. void AudioEngine::audioDeviceIOCallbackWithContext (const float* const* inputChannelData,
  1017. int numInputChannels,
  1018. float* const* outputChannelData,
  1019. int numOutputChannels,
  1020. int numSamples,
  1021. const juce::AudioIODeviceCallbackContext& context)
  1022. {
  1023. if (transport.rewindRequested.exchange (false))
  1024. transport.positionTicks.store (0.0);
  1025. if (const auto target = transport.seekRequest.exchange (-1.0); target >= 0.0)
  1026. transport.positionTicks.store (target);
  1027. // With the loop region on, the block is split at the loop end and the position jumps back to
  1028. // its start (the nodes see a jump and release their notes, as in FL).
  1029. // the audio editor's input recording (nothing happens unless it chose the input)
  1030. meters.capture.push (AudioCapture::input, numInputChannels > 0 ? inputChannelData[0] : nullptr, numInputChannels > 1 ? inputChannelData[1] : nullptr,
  1031. numSamples);
  1032. std::array<const float*, 64> inputs {};
  1033. std::array<float*, 64> outputs {};
  1034. numInputChannels = juce::jmin (numInputChannels, (int) inputs.size());
  1035. numOutputChannels = juce::jmin (numOutputChannels, (int) outputs.size());
  1036. // count-in: the metronome counts the pre-roll down, then playback starts
  1037. if (const auto countIn = transport.countIn.load (std::memory_order_relaxed); countIn > 0.0 && ! transport.playing.load (std::memory_order_relaxed))
  1038. {
  1039. const auto left = countIn - numSamples * transport.ticksPerSample();
  1040. transport.countIn.store (juce::jmax (0.0, left), std::memory_order_relaxed);
  1041. if (left <= 0.0)
  1042. transport.playing.store (true, std::memory_order_relaxed);
  1043. }
  1044. for (int done = 0; done < numSamples;)
  1045. {
  1046. auto n = numSamples - done;
  1047. const auto playing = transport.playing.load (std::memory_order_relaxed);
  1048. const auto tps = transport.ticksPerSample();
  1049. const auto loopStart = transport.loopStart.load (std::memory_order_relaxed);
  1050. const auto loopEnd = transport.loopEnd.load (std::memory_order_relaxed);
  1051. const auto looping = playing && transport.songMode.load (std::memory_order_relaxed) && loopEnd > loopStart && tps > 0.0;
  1052. if (looping)
  1053. {
  1054. // before the loop, play normally until reaching it; past the end, jump back to the start
  1055. auto position = transport.positionTicks.load (std::memory_order_relaxed);
  1056. if (position >= loopEnd)
  1057. {
  1058. position = loopStart;
  1059. transport.positionTicks.store (position, std::memory_order_relaxed);
  1060. }
  1061. n = juce::jlimit (1, n, (int) std::ceil ((loopEnd - position) / tps));
  1062. }
  1063. for (int ch = 0; ch < numInputChannels; ++ch)
  1064. inputs[(std::size_t) ch] = inputChannelData[ch] != nullptr ? inputChannelData[ch] + done : nullptr;
  1065. // audio recording: this block's input goes to disk (without waiting on a lock)
  1066. if (playing && transport.recording.load (std::memory_order_relaxed))
  1067. {
  1068. const juce::SpinLock::ScopedTryLockType lock (takeLock);
  1069. if (lock.isLocked() && takeWriter != nullptr && numInputChannels > 0)
  1070. {
  1071. std::array<const float*, 2> take {};
  1072. for (int ch = 0; ch < takeChannels; ++ch)
  1073. take[(std::size_t) ch] = inputs[(std::size_t) juce::jmin (ch, numInputChannels - 1)];
  1074. if (take[0] != nullptr && (takeChannels < 2 || take[1] != nullptr))
  1075. {
  1076. if (takeStartTick.load (std::memory_order_relaxed) < 0.0)
  1077. takeStartTick.store (transport.positionTicks.load (std::memory_order_relaxed));
  1078. if (takeWriter->write (take.data(), n))
  1079. takeFrames.fetch_add (n, std::memory_order_relaxed);
  1080. }
  1081. }
  1082. }
  1083. for (int ch = 0; ch < numOutputChannels; ++ch)
  1084. outputs[(std::size_t) ch] = outputChannelData[ch] != nullptr ? outputChannelData[ch] + done : nullptr;
  1085. player.audioDeviceIOCallbackWithContext (inputs.data(), numInputChannels, outputs.data(), numOutputChannels, n, context);
  1086. for (int ch = 0; ch < numOutputChannels; ++ch)
  1087. if (outputs[(std::size_t) ch] != nullptr)
  1088. softClip (outputs[(std::size_t) ch], n);
  1089. // oscilloscope: average of both sides into the ring buffer
  1090. if (numOutputChannels > 0 && outputs[0] != nullptr)
  1091. {
  1092. auto w = scopeWrite.load (std::memory_order_relaxed);
  1093. const auto* right = numOutputChannels > 1 && outputs[1] != nullptr ? outputs[1] : outputs[0];
  1094. for (int i = 0; i < n; ++i)
  1095. {
  1096. scope[(std::size_t) w].store (0.5f * (outputs[0][i] + right[i]), std::memory_order_relaxed);
  1097. w = (w + 1) % scopeSize;
  1098. }
  1099. scopeWrite.store (w, std::memory_order_release);
  1100. }
  1101. if (playing)
  1102. {
  1103. auto position = transport.positionTicks.load (std::memory_order_relaxed) + n * tps;
  1104. if (looping && position >= loopEnd - 1e-6)
  1105. position = loopStart;
  1106. transport.positionTicks.store (position, std::memory_order_relaxed);
  1107. }
  1108. done += n;
  1109. }
  1110. blockTimeMs.store (juce::Time::getMillisecondCounterHiRes(), std::memory_order_relaxed);
  1111. }
  1112. void AudioEngine::audioDeviceAboutToStart (juce::AudioIODevice* device)
  1113. {
  1114. transport.sampleRate.store (device->getCurrentSampleRate());
  1115. player.audioDeviceAboutToStart (device);
  1116. }
  1117. void AudioEngine::audioDeviceStopped()
  1118. {
  1119. player.audioDeviceStopped();
  1120. }
  1121. } // namespace lynx