AudioEngine.cpp 125 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044
  1. #include "engine/AudioEngine.h"
  2. #include "engine/AudioLogger.h"
  3. #include "core/Patcher.h"
  4. #include "core/ValueMath.h"
  5. #include "platform/Paths.h"
  6. #include "engine/FlStudio.h"
  7. #include <map>
  8. #include <thread>
  9. #include "engine/Text.h"
  10. #include "ui/I18n.h"
  11. #include "core/FlpImport.h"
  12. #include "core/LoadTrace.h"
  13. #include "core/Instruments.h"
  14. #include "core/Denormals.h"
  15. #include "core/Dither.h"
  16. #include "core/ProjectSafety.h"
  17. #include "core/SoftClip.h"
  18. #include "core/Scheduler.h"
  19. #include "engine/ChannelRackProcessor.h"
  20. #include "engine/DllAsioDevice.h"
  21. #include "engine/PipeWireDevice.h"
  22. #include "platform/LinuxRealtime.h"
  23. #include "engine/Metronome.h"
  24. #include "core/NoteTools.h"
  25. #include "engine/PreviewPlayer.h"
  26. #include "flp/Flp.h"
  27. #if JUCE_WINDOWS
  28. #include <windows.h>
  29. #elif JUCE_MAC
  30. #include <pthread.h>
  31. #include <sys/qos.h>
  32. #elif JUCE_LINUX || JUCE_BSD
  33. #include <pthread.h>
  34. #include <sched.h>
  35. #endif
  36. namespace lynx
  37. {
  38. using IONode = juce::AudioProcessorGraph::AudioGraphIOProcessor;
  39. // The FL Studio installation (registry, else the usual folders) to resolve %FLStudio...%.
  40. FlPathRoots findFlStudioRoots()
  41. {
  42. FlPathRoots roots;
  43. const auto fl = findFlStudio();
  44. if (fl.installDir.isDirectory())
  45. {
  46. roots.factoryData = fl.installDir.getFullPathName().toStdString();
  47. roots.data = fl.installDir.getChildFile ("Data").getFullPathName().toStdString();
  48. }
  49. if (fl.userData.isDirectory())
  50. roots.userData = fl.userData.getFullPathName().toStdString();
  51. roots.home = juce::File::getSpecialLocation (juce::File::userHomeDirectory).getFullPathName().toStdString();
  52. return roots;
  53. }
  54. const natives::FlAccess& flStudioAccess()
  55. {
  56. static const natives::FlAccess cached = [] {
  57. natives::FlAccess access;
  58. access.roots = findFlStudioRoots();
  59. access.fileExists = [] (const std::string& path) { return platform::localFile (path).existsAsFile(); };
  60. access.readFile = [] (const std::string& path) {
  61. juce::MemoryBlock data;
  62. platform::localFile (path).loadFileAsData (data);
  63. const auto* bytes = static_cast<const std::uint8_t*> (data.getData());
  64. return std::vector<std::uint8_t> (bytes, bytes + data.getSize());
  65. };
  66. access.listPresets = [] (const std::string& folder) {
  67. std::vector<std::string> out;
  68. auto files = platform::localFile (folder).findChildFiles (juce::File::findFiles, true, "*.fst;*.tbio;*.gmsynth;*.mrp");
  69. std::sort (files.begin(), files.end(), [] (const juce::File& a, const juce::File& b) {
  70. return a.getFullPathName().compareNatural (b.getFullPathName()) < 0;
  71. });
  72. for (const auto& f : files)
  73. out.push_back (f.getFullPathName().toStdString());
  74. return out;
  75. };
  76. // (FL Keys' raw wavetables become WAV files of LYNX's settings folder, like an .flp's embedded samples)
  77. access.saveEmbedded = [] (const std::vector<std::uint8_t>& wav, const std::string& name) -> std::string {
  78. const auto folder = PluginHost::settingsFolder().getChildFile ("flp-embedded");
  79. folder.createDirectory();
  80. const auto hash = juce::String::toHexString ((juce::int64) juce::DefaultHashFunctions::generateHash (
  81. juce::String::createStringFromData (wav.data(), (int) juce::jmin<std::size_t> (wav.size(), 65536)) + juce::String ((juce::int64) wav.size()),
  82. 0x7FFFFFFF));
  83. const auto file = folder.getChildFile (juce::File::createLegalFileName (juce::String::fromUTF8 (name.c_str())) + "-" + hash + ".wav");
  84. if (! file.existsAsFile() && ! file.replaceWithData (wav.data(), wav.size()))
  85. return {};
  86. return file.getFullPathName().toStdString();
  87. };
  88. return access;
  89. }();
  90. return cached;
  91. }
  92. namespace
  93. {
  94. // Audio workers with real-time priority (MMCSS "Pro Audio" on Windows, like the driver; QoS class on macOS; SCHED_FIFO
  95. // on Linux when allowed).
  96. void raiseAudioThreadPriority()
  97. {
  98. #if JUCE_WINDOWS
  99. using AvSet = void* (__stdcall*) (const wchar_t*, unsigned long*);
  100. static const auto avSet = [] () -> AvSet {
  101. if (auto* avrt = LoadLibraryW (L"avrt.dll"))
  102. return reinterpret_cast<AvSet> (reinterpret_cast<void*> (GetProcAddress (avrt, "AvSetMmThreadCharacteristicsW")));
  103. return nullptr;
  104. }();
  105. // FL's audio worker threads also raise their MMCSS priority to "high" (FLEngine_x64.dll, REA round 87)
  106. using AvPriority = int (__stdcall*) (void*, int);
  107. static const auto avPriority = [] () -> AvPriority {
  108. if (auto* avrt = LoadLibraryW (L"avrt.dll"))
  109. return reinterpret_cast<AvPriority> (reinterpret_cast<void*> (GetProcAddress (avrt, "AvSetMmThreadPriority")));
  110. return nullptr;
  111. }();
  112. unsigned long task = 0;
  113. if (auto* handle = avSet != nullptr ? avSet (L"Pro Audio", &task) : nullptr)
  114. {
  115. if (avPriority != nullptr)
  116. avPriority (handle, 1 /* AVRT_PRIORITY_HIGH */);
  117. }
  118. else
  119. SetThreadPriority (GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL);
  120. #elif JUCE_MAC
  121. // the highest quality-of-service class: scheduled like the UI's own interactive work, on the performance cores
  122. pthread_set_qos_class_self_np (QOS_CLASS_USER_INTERACTIVE, 0);
  123. #elif JUCE_LINUX || JUCE_BSD
  124. // real-time FIFO scheduling when the user may have it (audio group / rtkit limits, as JACK and PipeWire set up);
  125. // below the usual JACK/PipeWire audio thread priorities. Without the permission the thread stays as it is.
  126. sched_param param {};
  127. param.sched_priority = juce::jlimit (sched_get_priority_min (SCHED_FIFO), sched_get_priority_max (SCHED_FIFO), 70);
  128. if (pthread_setschedparam (pthread_self(), SCHED_FIFO, &param) != 0)
  129. rt::noteAudioThread (false); // RealtimeKit / the portal may grant it (round 161)
  130. #endif
  131. }
  132. int workerCount()
  133. {
  134. // diagnostics: LYNX_WORKERS=n fixes the number of extra threads
  135. if (const auto forced = juce::SystemStats::getEnvironmentVariable ("LYNX_WORKERS", {}); forced.isNotEmpty())
  136. return juce::jlimit (0, 31, forced.getIntValue());
  137. // the audio thread works too; leave one core free for the UI
  138. const auto cores = (int) std::thread::hardware_concurrency();
  139. return juce::jlimit (0, 7, cores - 2);
  140. }
  141. juce::File midiSettingsFile() { return PluginHost::settingsFolder().getChildFile ("midi-settings.txt"); }
  142. juce::File audioDeviceFile() { return PluginHost::settingsFolder().getChildFile ("audio-device.xml"); }
  143. } // namespace
  144. // Saves the audio device setup whenever it changes (Settings › Audio, the setup wizard, a driver's own panel), so
  145. // the next start opens the same device.
  146. struct AudioEngine::DeviceStateSaver final : public juce::ChangeListener
  147. {
  148. explicit DeviceStateSaver (AudioEngine& e) : engine (e) { engine.deviceManager.addChangeListener (this); }
  149. ~DeviceStateSaver() override { engine.deviceManager.removeChangeListener (this); }
  150. void changeListenerCallback (juce::ChangeBroadcaster*) override { engine.saveAudioDeviceState(); }
  151. AudioEngine& engine;
  152. };
  153. void AudioEngine::saveAudioDeviceState()
  154. {
  155. if (auto xml = deviceManager.createStateXml())
  156. xml->writeTo (audioDeviceFile());
  157. }
  158. void AudioEngine::restoreAudioDeviceState (const juce::XmlElement* state)
  159. {
  160. deviceStateSaver = nullptr;
  161. if (state != nullptr)
  162. state->writeTo (audioDeviceFile());
  163. else
  164. audioDeviceFile().deleteFile();
  165. }
  166. AudioEngine::AudioEngine (bool openAudioDevice)
  167. : workers (std::make_unique<WorkerPool> (workerCount(), raiseAudioThreadPriority)),
  168. song (Song::makeDefault())
  169. {
  170. inputSlot.fill (-1);
  171. outputSlot.fill (-1);
  172. publishSong();
  173. buildInitialGraph();
  174. if (openAudioDevice)
  175. {
  176. player.setProcessor (&graph);
  177. // LYNX ASIO without installation: lynx-asio.dll next to LYNX.exe, when it is not registered (REA round 106)
  178. if (auto lynxAsio = makeBuiltInLynxAsioType())
  179. {
  180. deviceManager.getAvailableDeviceTypes(); // the standard types first
  181. deviceManager.addAudioDeviceType (std::move (lynxAsio));
  182. }
  183. // LYNX's own PipeWire client on Linux (round 161), listed when a PipeWire daemon answers
  184. if (auto pipeWire = makePipeWireDeviceType())
  185. {
  186. deviceManager.getAvailableDeviceTypes();
  187. deviceManager.addAudioDeviceType (std::move (pipeWire));
  188. }
  189. // 0 inputs, 2 outputs; the device of the last session (Settings › Audio) if it is still there, else the default.
  190. const auto saved = juce::XmlDocument::parse (audioDeviceFile());
  191. auto fresh = saved == nullptr;
  192. if (deviceManager.initialise (0, 2, saved.get(), true).isNotEmpty() && saved != nullptr)
  193. {
  194. deviceManager.initialise (0, 2, nullptr, true);
  195. fresh = true;
  196. }
  197. if (fresh)
  198. {
  199. choosePreferredDriver(); // Linux: PipeWire, then JACK, then ALSA
  200. chooseSafeBufferSize(); // no saved setup: a buffer with room for heavy projects (Settings › Audio changes it)
  201. }
  202. deviceManager.addAudioCallback (this);
  203. if (rackProcessor != nullptr)
  204. rackProcessor->getRenderer().setProfiling (true); // per-unit CPU for the CPU meter and the glitch log
  205. deviceStateSaver = std::make_unique<DeviceStateSaver> (*this);
  206. midiPrefs = midiPrefsShared = prefs::MidiPrefs::fromText (midiSettingsFile().loadFileAsString().toStdString());
  207. saveGlobalLinks = true;
  208. prefetcher = std::make_unique<StreamPrefetcher> (transport);
  209. prefetcher->update (song, samples);
  210. enableAllMidiInputs();
  211. deviceManager.addMidiInputDeviceCallback ({}, this); // {} = all inputs enabled
  212. midiDevicesChanged = juce::MidiDeviceListConnection::make ([this] { enableAllMidiInputs(); });
  213. }
  214. startTimerHz (30); // recording and collection of retired snapshots
  215. }
  216. AudioLogger& AudioEngine::getAudioLogger()
  217. {
  218. if (audioLogger == nullptr)
  219. audioLogger = std::make_unique<AudioLogger> (meters.logTap);
  220. return *audioLogger;
  221. }
  222. AudioEngine::~AudioEngine()
  223. {
  224. stopTimer();
  225. audioLogger.reset(); // closes the log file
  226. {
  227. const juce::SpinLock::ScopedLockType lock (takeLock);
  228. for (auto& take : takes)
  229. take.writer = nullptr; // closes the WAVs of the takes in progress (they stay in the recordings folder)
  230. takeCount = 0;
  231. }
  232. recordThread.stopThread (2000);
  233. prefetcher = nullptr;
  234. midiDevicesChanged = {};
  235. deviceStateSaver = nullptr;
  236. deviceManager.removeMidiInputDeviceCallback ({}, this);
  237. deviceManager.removeAudioCallback (this);
  238. player.setProcessor (nullptr);
  239. graph.clear(); // the nodes reference rackExchange and transport
  240. }
  241. void AudioEngine::buildInitialGraph()
  242. {
  243. // The output node inherits the graph's channel count at the moment it is created.
  244. // Without this the graph still has 0 outputs and JUCE silently rejects the connections.
  245. graph.setPlayConfigDetails (0, 2, transport.sampleRate.load(), 512);
  246. auto output = graph.addNode (std::make_unique<IONode> (IONode::audioOutputNode));
  247. auto rack = graph.addNode (std::make_unique<ChannelRackProcessor> (transport, rackExchange, liveEvents, midiEvents, meters, workers.get()));
  248. rackProcessor = dynamic_cast<ChannelRackProcessor*> (rack->getProcessor());
  249. if (rackProcessor != nullptr)
  250. {
  251. rackProcessor->setLiveInput (&liveInput);
  252. rackProcessor->setHardwareOutput (&hwOutput);
  253. }
  254. auto metronome = graph.addNode (std::make_unique<Metronome> (transport));
  255. auto previewOwned = std::make_unique<PreviewPlayer>();
  256. preview = previewOwned.get();
  257. preview->setVolume (controls::previewGain (previewVolume));
  258. preview->setEditorVolume (controls::previewGain (editorVolume));
  259. auto previewNode = graph.addNode (std::move (previewOwned));
  260. for (int channel = 0; channel < 2; ++channel)
  261. {
  262. graph.addConnection ({ { rack->nodeID, channel }, { output->nodeID, channel } });
  263. graph.addConnection ({ { metronome->nodeID, channel }, { output->nodeID, channel } });
  264. graph.addConnection ({ { previewNode->nodeID, channel }, { output->nodeID, channel } });
  265. }
  266. jassert (graph.getConnections().size() == 6);
  267. }
  268. float AudioEngine::renderOffline (const RenderOptions& options)
  269. {
  270. const auto seconds = options.seconds;
  271. const auto sampleRate = options.sampleRate;
  272. auto* output = options.output;
  273. const auto& progress = options.progress;
  274. const auto tailSeconds = options.tailSeconds;
  275. const auto trimSamples = options.trimSamples;
  276. std::optional<Dither> dither;
  277. if (options.ditherBits > 0)
  278. dither.emplace (options.ditherBits, options.ditherShaping);
  279. constexpr int blockSize = 512;
  280. constexpr float silence = 3.0e-5f; // ~ -90 dB
  281. // "HQ for all plugins" (REA round 134): engines with FL render-quality settings use them (Sytrus) and HQ switches
  282. // are forced on; without it the export keeps the playback quality
  283. setOfflineRendering (options.hqAllPlugins);
  284. setHqForAllPlugins (options.hqAllPlugins);
  285. setPluginsRenderMode (true); // and hosted plugins are told an export is running (FL: "notify about rendering mode")
  286. transport.sampleRate.store (sampleRate);
  287. graph.setPlayConfigDetails (0, 2, sampleRate, blockSize);
  288. graph.prepareToPlay (sampleRate, blockSize);
  289. if (rackProcessor != nullptr)
  290. rackProcessor->setMetering (false); // nobody looks at the meters during the render
  291. lastRenderStats = {};
  292. // FL's init list first (play() would do it at the first block), so the plugins settle on those values too
  293. resetToInitialValues();
  294. int latency = getLatencySamples();
  295. if (options.pluginWarmUp)
  296. lastRenderStats.warmUp = warmUpPlugins (options.warmUp, sampleRate, blockSize, progress, latency);
  297. play();
  298. juce::AudioBuffer<float> buffer (2, blockSize);
  299. juce::MidiBuffer midi;
  300. float peak = 0.0f;
  301. // PDC trim with the latency the plugins report once they have settled
  302. const auto trim = (std::int64_t) juce::jmax (0, trimSamples + (options.trimPdc ? latency : 0));
  303. lastRenderStats.trimmedSamples = (int) trim;
  304. const auto musicSamples = (std::int64_t) (seconds * sampleRate) + trim;
  305. const auto totalSamples = musicSamples + (std::int64_t) (juce::jmax (0.0, tailSeconds) * sampleRate);
  306. std::int64_t quietSamples = 0;
  307. bool cancelled = lastRenderStats.warmUp.cancelled;
  308. for (std::int64_t done = 0; done < totalSamples && ! cancelled; done += blockSize)
  309. {
  310. const auto n = (int) juce::jmin<std::int64_t> (blockSize, totalSamples - done);
  311. juce::AudioBuffer<float> view (buffer.getArrayOfWritePointers(), 2, n);
  312. view.clear();
  313. const auto before = juce::Time::getMillisecondCounterHiRes();
  314. graph.processBlock (view, midi);
  315. const auto afterGraph = juce::Time::getMillisecondCounterHiRes();
  316. lastRenderStats.graphMs += afterGraph - before;
  317. if (! options.keepOvers) // float WAV and the buffered export (normalize) keep what goes above 0 dBFS, like FL
  318. for (int ch = 0; ch < view.getNumChannels(); ++ch)
  319. clipOvers (view.getWritePointer (ch), n);
  320. const auto blockPeak = view.getMagnitude (0, n);
  321. peak = juce::jmax (peak, blockPeak);
  322. if (dither)
  323. for (int ch = 0; ch < view.getNumChannels(); ++ch)
  324. dither->process (view.getWritePointer (ch), n, ch);
  325. // PDC: the start is the latency's silence; the song's end arrives `trim` samples later
  326. if ((output != nullptr || options.capture) && done + n > trim)
  327. {
  328. const auto skip = (int) juce::jmax<std::int64_t> (0, trim - done);
  329. const auto beforeWrite = juce::Time::getMillisecondCounterHiRes();
  330. if (output != nullptr)
  331. output->writeFromAudioSampleBuffer (view, skip, n - skip);
  332. if (options.capture)
  333. options.capture (view.getReadPointer (0, skip), view.getReadPointer (1, skip), n - skip);
  334. lastRenderStats.writeMs += juce::Time::getMillisecondCounterHiRes() - beforeWrite;
  335. }
  336. transport.positionTicks.store (transport.positionTicks.load() + n * transport.ticksPerSample());
  337. // in the tail: half a second of silence ends it
  338. if (done + n > musicSamples)
  339. {
  340. quietSamples = blockPeak < silence ? quietSamples + n : 0;
  341. if (quietSamples > (std::int64_t) (sampleRate * 0.5))
  342. break;
  343. }
  344. if (progress && (done / blockSize) % 32 == 0 && ! progress ((double) done / (double) juce::jmax<std::int64_t> (1, totalSamples)))
  345. {
  346. cancelled = true;
  347. break;
  348. }
  349. }
  350. stop();
  351. if (rackProcessor != nullptr)
  352. rackProcessor->setMetering (true);
  353. graph.releaseResources();
  354. setPluginsRenderMode (false);
  355. setOfflineRendering (false);
  356. setHqForAllPlugins (false);
  357. return cancelled ? -1.0f : peak;
  358. }
  359. warmup::Result AudioEngine::warmUpPlugins (const warmup::Settings& settings, double sampleRate, int blockSize,
  360. const std::function<bool (double)>& progress, int& latency)
  361. {
  362. // the hosted plugins, collected once: the timer may republish the song meanwhile (the instances stay the same)
  363. std::vector<juce::AudioPluginInstance*> hosted;
  364. forEachHostedPlugin ([&hosted] (juce::AudioPluginInstance& p, bool) { hosted.push_back (&p); });
  365. if (hosted.empty())
  366. return {}; // LYNX's own engines are ready as soon as they are created: nothing to wait for
  367. // keeps the units alive whatever the timer publishes during the warm-up
  368. std::vector<std::shared_ptr<Instrument>> keepInstruments;
  369. std::vector<std::shared_ptr<Effect>> keepEffects;
  370. for (std::size_t i = 0; i < song.channels.size(); ++i)
  371. keepInstruments.push_back (getChannelInstrument ((int) i));
  372. for (std::size_t t = 0; t < song.mixer.size(); ++t)
  373. for (std::size_t s = 0; s < song.mixer[t].effects.size(); ++s)
  374. keepEffects.push_back (getEffect ((int) t, (int) s));
  375. juce::AudioBuffer<float> buffer (2, blockSize);
  376. juce::MidiBuffer midi;
  377. int blocks = 0;
  378. // transport stopped at the start position: no note plays, and the automation / pattern events at that position
  379. // reach the plugins (the rack evaluates them every block), so they settle on the values the song starts with
  380. const auto result = warmup::run (
  381. settings, sampleRate,
  382. [&]() -> int {
  383. if (progress && ++blocks % 32 == 0 && ! progress (0.0))
  384. return -1;
  385. buffer.clear();
  386. midi.clear();
  387. graph.processBlock (buffer, midi);
  388. return blockSize;
  389. },
  390. [&hosted] {
  391. warmup::Hash h;
  392. for (auto* p : hosted)
  393. {
  394. h.add ((std::uint64_t) (std::int64_t) p->getLatencySamples());
  395. for (auto* param : p->getParameters())
  396. h.addValue (param->getValue());
  397. }
  398. return h.value;
  399. },
  400. [] { return juce::Time::getMillisecondCounterHiRes() * 0.001; },
  401. [] (double s) { juce::Thread::sleep (juce::jlimit (1, 20, (int) std::lround (s * 1000.0))); });
  402. // a latency that changed (reported late) gets its PDC plan before the render, on the message thread as the
  403. // timer does it (renders from the Export window run on a thread of their own)
  404. auto republish = [this] {
  405. if (lastPublishedShape.currentLatencies() != lastPublishedShape.latencies)
  406. {
  407. ++latencyRepublishes;
  408. publishSong();
  409. }
  410. return getLatencySamples();
  411. };
  412. auto* mm = juce::MessageManager::getInstanceWithoutCreating();
  413. if (mm == nullptr || mm->isThisTheMessageThread())
  414. latency = republish();
  415. else
  416. {
  417. struct Reply
  418. {
  419. juce::WaitableEvent done;
  420. std::atomic<int> latency { 0 };
  421. };
  422. auto reply = std::make_shared<Reply>();
  423. reply->latency = getLatencySamples();
  424. juce::MessageManager::callAsync ([this, reply, republish] {
  425. reply->latency = republish();
  426. reply->done.signal();
  427. });
  428. reply->done.wait (3000);
  429. latency = reply->latency.load();
  430. }
  431. // LYNX's own units start the render from a clean state, as without the warm-up (free-running LFOs, the delay
  432. // compensation's lines); the hosted plugins are not reset: they keep what they settled on (a reset re-activates
  433. // them, which is what they had to settle from)
  434. if (rackProcessor != nullptr)
  435. rackProcessor->prepareToPlay (sampleRate, blockSize);
  436. return result;
  437. }
  438. void AudioEngine::forEachHostedPlugin (const std::function<void (juce::AudioPluginInstance&, bool notifyRender)>& visit) const
  439. {
  440. for (std::size_t i = 0; i < song.channels.size(); ++i)
  441. if (auto* p = dynamic_cast<PluginInstrument*> (getChannelInstrument ((int) i).get()); p != nullptr && ! p->hasCrashed())
  442. visit (p->getInstance(), song.channels[i].plugin.notifyRender);
  443. for (std::size_t t = 0; t < song.mixer.size(); ++t)
  444. for (std::size_t s = 0; s < song.mixer[t].effects.size(); ++s)
  445. if (auto* p = dynamic_cast<PluginEffect*> (getEffect ((int) t, (int) s).get()); p != nullptr && ! p->hasCrashed())
  446. visit (p->getInstance(), song.mixer[t].effects[s].plugin.notifyRender);
  447. std::function<void (patcher::Graph*)> inGraph = [&] (patcher::Graph* graph) {
  448. if (graph == nullptr)
  449. return;
  450. for (int n = 0; n < graph->nodeCount(); ++n)
  451. {
  452. auto effect = graph->effectAt (n);
  453. auto instrument = graph->instrumentAt (n);
  454. if (auto* p = dynamic_cast<PluginEffect*> (effect.get()); p != nullptr && ! p->hasCrashed())
  455. visit (p->getInstance(), true);
  456. if (auto* p = dynamic_cast<PluginInstrument*> (instrument.get()); p != nullptr && ! p->hasCrashed())
  457. visit (p->getInstance(), true);
  458. inGraph (patcher::graphOf (effect.get()));
  459. inGraph (patcher::graphOf (instrument.get()));
  460. }
  461. };
  462. for (std::size_t i = 0; i < song.channels.size(); ++i)
  463. inGraph (patcher::graphOf (getChannelInstrument ((int) i).get()));
  464. for (std::size_t t = 0; t < song.mixer.size(); ++t)
  465. for (std::size_t s = 0; s < song.mixer[t].effects.size(); ++s)
  466. inGraph (patcher::graphOf (getEffect ((int) t, (int) s).get()));
  467. }
  468. ProcessTimes* AudioEngine::getProcessTimes() noexcept
  469. {
  470. return rackProcessor != nullptr ? &rackProcessor->processTimes() : nullptr;
  471. }
  472. void AudioEngine::play() noexcept
  473. {
  474. if (! transport.playing.load())
  475. resetToInitialValues();
  476. transport.playing.store (true);
  477. }
  478. // FL resets its "initialized controls" whenever the song position is set in song mode (playing starts, a jump):
  479. // FUN_011e7470 plays the song's init list (PTR_DAT_015dfc48) before the pattern events (REA round 146).
  480. void AudioEngine::resetToInitialValues() noexcept
  481. {
  482. if (song.initialValues.empty() || song.mode != PlayMode::song)
  483. return;
  484. try
  485. {
  486. auto differs = false;
  487. for (const auto& v : song.initialValues)
  488. {
  489. const auto now = currentTargetValue (v.target);
  490. differs = differs || (now >= 0.0f && std::abs (now - v.value) > 1.0e-6f);
  491. }
  492. if (! differs)
  493. return;
  494. std::vector<Song::InitialValue> plugins;
  495. editSong ([&plugins] (Song& s) { s.applyInitialValues ([&plugins] (const AutomationTarget& t, float v) { plugins.push_back ({ t, v }); }); },
  496. false);
  497. for (const auto& v : plugins)
  498. {
  499. if (v.target.kind == AutomationTargetKind::channelParam)
  500. if (auto* p = dynamic_cast<PluginInstrument*> (getChannelInstrument (v.target.index).get()))
  501. p->setParameterFromUi (v.target.param, v.value);
  502. if (v.target.kind == AutomationTargetKind::effectParam)
  503. if (auto* p = dynamic_cast<PluginEffect*> (getEffect (v.target.index, v.target.slot).get()))
  504. p->setParameterFromUi (v.target.param, v.value);
  505. }
  506. }
  507. catch (...)
  508. {
  509. }
  510. }
  511. void AudioEngine::stop() noexcept
  512. {
  513. waitingForInput.store (false);
  514. transport.countIn.store (0.0);
  515. transport.playing.store (false);
  516. }
  517. void AudioEngine::setRecordOptions (const RecordOptions& options)
  518. {
  519. recordOptions = options;
  520. recordOptions.countInBars = juce::jlimit (0, 4, options.countInBars);
  521. sendChangeMessage();
  522. }
  523. void AudioEngine::startPlayback()
  524. {
  525. if (! transport.recording.load())
  526. {
  527. play();
  528. return;
  529. }
  530. if (recordOptions.waitForInput)
  531. {
  532. waitingForInput.store (true);
  533. sendChangeMessage();
  534. return;
  535. }
  536. if (recordOptions.countInBars > 0)
  537. {
  538. const auto at = (std::int64_t) transport.positionTicks.load();
  539. transport.countIn.store ((double) countInLength (song, recordOptions.countInBars, at));
  540. sendChangeMessage();
  541. return;
  542. }
  543. play();
  544. }
  545. void AudioEngine::startOnInput() noexcept
  546. {
  547. if (waitingForInput.exchange (false))
  548. transport.playing.store (true);
  549. }
  550. void AudioEngine::setInsertArmed (int track, bool armed)
  551. {
  552. const auto it = std::find (armedInserts.begin(), armedInserts.end(), track);
  553. const auto wasArmed = it != armedInserts.end();
  554. if (armed == wasArmed || track <= 0)
  555. return;
  556. if (armed)
  557. armedInserts.push_back (track);
  558. else
  559. armedInserts.erase (it);
  560. if (track < maxMixerTracks)
  561. liveInput.armed[(std::size_t) track].store (armed);
  562. if (armed && ! audioArmed)
  563. setAudioRecordingArmed (true);
  564. else if (! armed && armedInserts.empty() && audioArmed)
  565. setAudioRecordingArmed (false);
  566. sendChangeMessage();
  567. }
  568. bool AudioEngine::isInsertArmed (int track) const noexcept
  569. {
  570. return std::find (armedInserts.begin(), armedInserts.end(), track) != armedInserts.end();
  571. }
  572. void AudioEngine::rewind() noexcept { transport.rewindRequested.store (true); }
  573. void AudioEngine::seek (double ticks) noexcept
  574. {
  575. if (transport.playing.load())
  576. resetToInitialValues(); // a jump while the song plays (FL sets the position the same way)
  577. transport.seekRequest.store (juce::jmax (0.0, ticks));
  578. }
  579. void AudioEngine::copyScope (float* destination, int count) const noexcept
  580. {
  581. count = juce::jmin (count, scopeSize);
  582. auto r = (scopeWrite.load (std::memory_order_acquire) - count + scopeSize) % scopeSize;
  583. for (int i = 0; i < count; ++i)
  584. {
  585. destination[i] = scope[(std::size_t) r].load (std::memory_order_relaxed);
  586. r = (r + 1) % scopeSize;
  587. }
  588. }
  589. void AudioEngine::previewFile (const juce::File& file)
  590. {
  591. if (preview != nullptr)
  592. preview->playBrowser (file.existsAsFile() ? samples.load (file.getFullPathName()) : nullptr);
  593. }
  594. void AudioEngine::setInputScale (int scale, int root) noexcept
  595. {
  596. inputScaleRoot.store (root);
  597. inputScale.store (scale);
  598. }
  599. int AudioEngine::snapInputKey (int key) const noexcept
  600. {
  601. const auto scale = inputScale.load();
  602. return scale > 0 ? notetools::snapToScale (key, inputScaleRoot.load(), scale) : key;
  603. }
  604. void AudioEngine::previewSample (std::shared_ptr<const SampleData> sample, bool loop, float gain, bool audioEditor)
  605. {
  606. if (preview != nullptr)
  607. preview->play (std::move (sample), loop, gain, audioEditor);
  608. }
  609. void AudioEngine::setEditorVolume (double volume) noexcept
  610. {
  611. editorVolume = controls::clampUtilityVolume (volume);
  612. if (preview != nullptr)
  613. preview->setEditorVolume (controls::previewGain (editorVolume));
  614. }
  615. void AudioEngine::setPreviewVolume (double volume) noexcept
  616. {
  617. previewVolume = controls::clampUtilityVolume (volume);
  618. if (preview != nullptr)
  619. preview->setVolume (controls::previewGain (previewVolume));
  620. }
  621. double AudioEngine::getPreviewPosition() const noexcept
  622. {
  623. return preview != nullptr ? preview->getPlayPosition() : -1.0;
  624. }
  625. void AudioEngine::markHeldKey (int key, bool on) noexcept
  626. {
  627. if (key < 0 || key > 127)
  628. return;
  629. auto& count = heldKeyCount[(std::size_t) key];
  630. auto before = count.load();
  631. std::uint8_t after = 0;
  632. do
  633. after = on ? (std::uint8_t) std::min (255, before + 1) : (std::uint8_t) (before > 0 ? before - 1 : 0);
  634. while (! count.compare_exchange_weak (before, after));
  635. const auto bit = std::uint64_t { 1 } << (key & 63);
  636. if (after > 0)
  637. heldKeyBits[key >> 6].fetch_or (bit);
  638. else
  639. heldKeyBits[key >> 6].fetch_and (~bit);
  640. }
  641. std::vector<int> AudioEngine::heldInputKeys() const
  642. {
  643. std::vector<int> keys;
  644. for (int word = 0; word < 2; ++word)
  645. {
  646. const auto bits = heldKeyBits[word].load();
  647. for (int b = 0; b < 64; ++b)
  648. if ((bits >> b & 1u) != 0)
  649. keys.push_back (word * 64 + b);
  650. }
  651. return keys;
  652. }
  653. void AudioEngine::sendLiveNote (int channel, int key, float velocity, bool on, bool record)
  654. {
  655. if (record) // played notes (the PC keyboard) follow the scale snap; previews don't
  656. {
  657. markHeldKey (key, on);
  658. // the note-off stops the key its note-on started, even if the snap changed in between
  659. const auto requested = key;
  660. if (on)
  661. {
  662. key = snapInputKey (key);
  663. playedKeys.on (channel, requested, key);
  664. startOnInput();
  665. }
  666. else
  667. key = playedKeys.off (channel, requested, snapInputKey (key));
  668. }
  669. NoteEvent e;
  670. e.type = on ? NoteEvent::Type::on : NoteEvent::Type::off;
  671. e.channel = channel;
  672. e.key = key;
  673. e.velocity = velocity;
  674. liveEvents.push (e);
  675. if (record && transport.recording.load() && transport.playing.load())
  676. uiRecorded.push_back ({ estimatedPositionNow(), channel, key, velocity, on });
  677. }
  678. void AudioEngine::panic()
  679. {
  680. NoteEvent e;
  681. e.type = NoteEvent::Type::choke;
  682. e.channel = -1; // every channel
  683. liveEvents.push (e);
  684. for (auto& c : heldKeyCount)
  685. c.store (0);
  686. for (auto& w : heldKeyBits)
  687. w.store (0);
  688. }
  689. double AudioEngine::estimatedPositionNow() const noexcept
  690. {
  691. // the position only moves block by block; interpolate by the time since the last block
  692. auto tick = transport.positionTicks.load (std::memory_order_relaxed);
  693. if (transport.playing.load (std::memory_order_relaxed))
  694. {
  695. const auto elapsedMs = juce::jlimit (0.0, 100.0, juce::Time::getMillisecondCounterHiRes() - blockTimeMs.load());
  696. tick += elapsedMs * 0.001 * transport.sampleRate.load() * transport.ticksPerSample();
  697. }
  698. return tick;
  699. }
  700. void AudioEngine::updateAudioRecording()
  701. {
  702. const auto wantTake = audioArmed && recordOptions.recordAudio && transport.recording.load();
  703. const auto open = takeCount > 0;
  704. // the files are ready before Play: the very first block gets recorded
  705. if (wantTake && ! open && recordingError.isEmpty())
  706. startAudioTake();
  707. // playback stopped (or recording turned off) with something recorded: close the takes
  708. if (open && (! wantTake || (! transport.playing.load() && takeFrames.load() > 0)))
  709. finishAudioTake();
  710. }
  711. void AudioEngine::startAudioTake()
  712. {
  713. auto* device = deviceManager.getCurrentAudioDevice();
  714. if (device == nullptr)
  715. return;
  716. const auto names = getInputChannelNames();
  717. const auto deviceChannels = (int) names.size();
  718. const auto active = device->getActiveInputChannels();
  719. if (deviceChannels == 0 || active.isZero())
  720. {
  721. recordingError = "no audio input is open";
  722. notify (InputIssue::noInputOpen);
  723. return;
  724. }
  725. // one take per armed insert that has an input source; without armed inserts (Settings' "Record input audio"),
  726. // the first two input channels into a new insert
  727. std::vector<Take> wanted;
  728. std::vector<int> withoutInput;
  729. for (const auto t : armedInserts)
  730. {
  731. if (t <= 0 || t >= (int) song.mixer.size() || (int) wanted.size() >= maxTakes)
  732. continue;
  733. const auto [first, count] = inputChannelsOf (song.mixer[(std::size_t) t], deviceChannels);
  734. if (count == 0)
  735. withoutInput.push_back (t);
  736. else
  737. wanted.push_back ({ t, first, count, {}, {} });
  738. }
  739. if (armedInserts.empty())
  740. wanted.push_back ({ 0, 0, juce::jmin (2, deviceChannels), {}, {} });
  741. if (wanted.empty())
  742. {
  743. recordingError = "the armed inserts have no audio input";
  744. notify (InputIssue::armedWithoutInput, withoutInput.empty() ? 0 : withoutInput.front());
  745. return;
  746. }
  747. if (! withoutInput.empty())
  748. notify (InputIssue::insertWithoutInput, withoutInput.front());
  749. auto folder = recordingFolder;
  750. if (! folder.createDirectory()) // e.g. a read-only project folder: the global recordings folder
  751. folder = defaultRecordingFolder(), folder.createDirectory();
  752. takeSampleRate = device->getCurrentSampleRate();
  753. takeLatency = device->getInputLatencyInSamples() + device->getOutputLatencyInSamples();
  754. const auto now = juce::Time::getCurrentTime();
  755. juce::WavAudioFormat wav;
  756. for (auto& take : wanted)
  757. {
  758. // FL's name (REA round 134): "<project>_<yyyy-mm-dd hh-mm-ss>_<insert name>", "_2", "_3"... when taken
  759. juce::String insert;
  760. if (take.track > 0)
  761. insert = song.mixer[(std::size_t) take.track].name.empty() ? "Insert " + juce::String (take.track)
  762. : juce::String::fromUTF8 (song.mixer[(std::size_t) take.track].name.c_str());
  763. const auto name = juce::File::createLegalFileName (juce::String::fromUTF8 (
  764. safety::recordingName (recordingStem.toStdString(), now.getYear(), now.getMonth() + 1, now.getDayOfMonth(), now.getHours(),
  765. now.getMinutes(), now.getSeconds(), insert.toStdString()).c_str()));
  766. const auto unique = safety::uniqueName (name.toStdString(), [&folder] (const std::string& n) {
  767. return folder.getChildFile (juce::String::fromUTF8 (n.c_str()) + ".wav").exists();
  768. });
  769. take.file = folder.getChildFile (juce::String::fromUTF8 (unique.c_str()) + ".wav");
  770. auto stream = take.file.createOutputStream();
  771. if (stream == nullptr)
  772. {
  773. recordingError = utf8 ("could not create ") + take.file.getFullPathName();
  774. continue;
  775. }
  776. auto* writer = wav.createWriterFor (stream.get(), takeSampleRate, (unsigned int) take.channels, 24, {}, 0);
  777. if (writer == nullptr)
  778. {
  779. stream.reset();
  780. take.file.deleteFile();
  781. recordingError = utf8 ("WAV does not accept this sample rate/channel count");
  782. continue;
  783. }
  784. stream.release(); // now owned by the writer
  785. take.writer = std::make_unique<juce::AudioFormatWriter::ThreadedWriter> (writer, recordThread, 1 << 18);
  786. }
  787. if (recordingError.isNotEmpty())
  788. notify (InputIssue::failed, 0, recordingError);
  789. takeStartTick.store (-1.0);
  790. takeFrames.store (0);
  791. const juce::SpinLock::ScopedLockType lock (takeLock);
  792. takeCount = 0;
  793. for (auto& take : wanted)
  794. if (take.writer != nullptr)
  795. takes[(std::size_t) takeCount++] = std::move (take);
  796. }
  797. void AudioEngine::finishAudioTake()
  798. {
  799. std::vector<Take> done;
  800. {
  801. const juce::SpinLock::ScopedLockType lock (takeLock);
  802. for (int k = 0; k < takeCount; ++k)
  803. done.push_back (std::move (takes[(std::size_t) k]));
  804. takeCount = 0;
  805. }
  806. for (auto& take : done)
  807. {
  808. take.writer.reset(); // drains the queue and closes the WAV
  809. if (take.file.existsAsFile())
  810. sessionRecordings.push_back (take.file);
  811. }
  812. if (recordOptions.disarmOnStop) // FL's "Disarm on stop"
  813. for (const auto t : std::vector<int> (armedInserts))
  814. setInsertArmed (t, false);
  815. const auto frames = takeFrames.exchange (0);
  816. const auto startTick = takeStartTick.exchange (-1.0);
  817. if (frames <= 0 || startTick < 0.0)
  818. {
  819. for (auto& take : done)
  820. take.file.deleteFile();
  821. return;
  822. }
  823. // what came into the interface corresponds to what was heard one latency earlier
  824. const auto ticksPerSample = song.bpm * ppq / (60.0 * takeSampleRate);
  825. auto start = (std::int64_t) std::llround (startTick - takeLatency * ticksPerSample);
  826. std::int64_t offset = 0;
  827. if (song.mode == PlayMode::song && ! song.hasLoop() && start >= song.songLength()) // (the position loops over the song)
  828. start %= std::max<std::int64_t> (1, song.songLength());
  829. if (start < 0)
  830. {
  831. offset = -start;
  832. start = 0;
  833. }
  834. const auto length = (std::int64_t) std::llround ((double) frames * ticksPerSample) - offset;
  835. if (length <= 0)
  836. return;
  837. // FL's "Enable recording markers": only the parts inside the Start / Stop recording ranges become clips
  838. const auto parts = recordOptions.recordingMarkers && song.mode == PlayMode::song ? punchParts (punchRanges (song.markers()), start, length, offset)
  839. : std::vector<ClipPart> { { start, length, offset } };
  840. if (parts.empty()) // the whole take was outside the ranges
  841. {
  842. for (auto& take : done)
  843. take.file.deleteFile();
  844. return;
  845. }
  846. struct Made
  847. {
  848. std::string path, name;
  849. int track;
  850. };
  851. std::vector<Made> made;
  852. for (const auto& take : done)
  853. made.push_back ({ take.file.getFullPathName().toStdString(), take.file.getFileNameWithoutExtension().toStdString(), take.track });
  854. editSong ([=] (Song& s) {
  855. int playlistTrack = 0;
  856. for (const auto& clip : s.playlist)
  857. playlistTrack = std::max (playlistTrack, clip.track + 1);
  858. for (const auto& m : made) // each take on its own Playlist track, through the insert it was recorded on
  859. {
  860. ChannelDef c;
  861. c.name = m.name;
  862. c.instrument = InstrumentKind::audioClip;
  863. c.samplePath = m.path;
  864. c.mixerTrack = m.track > 0 && m.track < (int) s.mixer.size() ? m.track : s.claimFreeInsert();
  865. s.channels.push_back (c);
  866. for (const auto& part : parts)
  867. {
  868. Clip clip;
  869. clip.kind = ClipKind::audio;
  870. clip.channel = (int) s.channels.size() - 1;
  871. clip.track = playlistTrack;
  872. clip.start = part.start;
  873. clip.length = part.length;
  874. clip.offset = part.offset;
  875. s.playlist.push_back (clip);
  876. }
  877. ++playlistTrack;
  878. }
  879. });
  880. }
  881. juce::File AudioEngine::defaultRecordingFolder()
  882. {
  883. return juce::File::getSpecialLocation (juce::File::userMusicDirectory).getChildFile ("LYNX/Recordings");
  884. }
  885. void AudioEngine::setRecordingTarget (const juce::File& folder, const juce::String& projectStem)
  886. {
  887. recordingFolder = folder == juce::File() ? defaultRecordingFolder() : folder;
  888. recordingStem = projectStem;
  889. }
  890. void AudioEngine::forgetRecordings (const std::vector<juce::File>& files)
  891. {
  892. sessionRecordings.erase (std::remove_if (sessionRecordings.begin(), sessionRecordings.end(),
  893. [&files] (const juce::File& f) { return std::find (files.begin(), files.end(), f) != files.end(); }),
  894. sessionRecordings.end());
  895. }
  896. std::vector<std::string> AudioEngine::getInputChannelNames() const
  897. {
  898. std::vector<std::string> names;
  899. if (auto* device = deviceManager.getCurrentAudioDevice(); device != nullptr && ! device->getActiveInputChannels().isZero())
  900. for (const auto& n : device->getInputChannelNames())
  901. if ((int) names.size() < LiveInput::maxChannels)
  902. names.push_back (n.toStdString());
  903. return names;
  904. }
  905. bool AudioEngine::hasAudioInput() const
  906. {
  907. auto* device = deviceManager.getCurrentAudioDevice();
  908. return device != nullptr && ! device->getActiveInputChannels().isZero();
  909. }
  910. void AudioEngine::notify (InputIssue issue, int track, const juce::String& detail)
  911. {
  912. recordingNotice = { issue, track, detail };
  913. sendChangeMessage();
  914. }
  915. AudioEngine::RecordingNotice AudioEngine::openAudioInput (const juce::String& deviceName)
  916. {
  917. auto* type = deviceManager.getCurrentDeviceTypeObject();
  918. if (type == nullptr || deviceManager.getCurrentAudioDevice() == nullptr)
  919. return { InputIssue::noDevice, 0, {} };
  920. auto setup = deviceManager.getAudioDeviceSetup();
  921. int count = 0;
  922. if (type->hasSeparateInputsAndOutputs())
  923. {
  924. // Windows Audio / DirectSound: the input is a device of its own
  925. const auto inputs = type->getDeviceNames (true);
  926. auto name = deviceName.isNotEmpty() ? deviceName : setup.inputDeviceName;
  927. if (! inputs.contains (name))
  928. {
  929. const auto index = type->getDefaultDeviceIndex (true);
  930. name = juce::isPositiveAndBelow (index, inputs.size()) ? inputs[index] : juce::String();
  931. }
  932. if (name.isEmpty())
  933. return { InputIssue::noInputDevice, 0, {} };
  934. auto* current = deviceManager.getCurrentAudioDevice();
  935. if (name == setup.inputDeviceName && ! current->getActiveInputChannels().isZero())
  936. count = current->getInputChannelNames().size();
  937. else if (std::unique_ptr<juce::AudioIODevice> probe (type->createDevice ({}, name)); probe != nullptr)
  938. count = probe->getInputChannelNames().size();
  939. setup.inputDeviceName = name;
  940. }
  941. else
  942. {
  943. // ASIO: one device does both; its input channels come in pairs in the mixer
  944. count = deviceManager.getCurrentAudioDevice()->getInputChannelNames().size();
  945. setup.inputDeviceName = setup.outputDeviceName;
  946. }
  947. if (count <= 0)
  948. count = 2;
  949. count = juce::jmin (count, (int) LiveInput::maxChannels);
  950. juce::BigInteger wanted;
  951. wanted.setRange (0, count, true);
  952. if (! setup.useDefaultInputChannels && setup.inputChannels == wanted && ! deviceManager.getCurrentAudioDevice()->getActiveInputChannels().isZero())
  953. return {};
  954. setup.useDefaultInputChannels = false;
  955. setup.inputChannels = wanted;
  956. const auto error = deviceManager.setAudioDeviceSetup (setup, true);
  957. sendChangeMessage();
  958. if (error.isNotEmpty())
  959. return { InputIssue::failed, 0, error };
  960. if (! hasAudioInput())
  961. return { InputIssue::noInputDevice, 0, {} };
  962. return {};
  963. }
  964. void AudioEngine::setInsertInput (int track, int channel, bool stereo)
  965. {
  966. if (track < 0 || track >= (int) song.mixer.size()) // (the Master too: REA round 143)
  967. return;
  968. editSong ([=] (Song& s) {
  969. s.mixer[(std::size_t) track].inputChannel = channel;
  970. s.mixer[(std::size_t) track].inputStereo = stereo;
  971. });
  972. recordingError = {};
  973. if (channel >= 0 && ! hasAudioInput())
  974. if (const auto result = openAudioInput(); result.issue != InputIssue::none)
  975. notify (result.issue, track, result.detail);
  976. }
  977. void AudioEngine::setInsertMonitor (int track, InputMonitor mode)
  978. {
  979. if (track >= 0 && track < (int) song.mixer.size())
  980. editSong ([=] (Song& s) { s.mixer[(std::size_t) track].monitor = mode; });
  981. }
  982. void AudioEngine::handleIncomingMidiMessage (juce::MidiInput* source, const juce::MidiMessage& m)
  983. {
  984. // MIDI thread: queues and atomics only (and a short copy of the device settings)
  985. prefs::MidiInputPrefs device;
  986. auto velocityCurve = prefs::VelocityCurve::linear;
  987. {
  988. const juce::SpinLock::ScopedLockType lock (midiPrefsLock);
  989. device = midiPrefsShared.input (source != nullptr ? source->getName().toStdString() : std::string());
  990. velocityCurve = midiPrefsShared.velocity;
  991. }
  992. if (! device.enabled)
  993. return;
  994. midiActivity.fetch_add (1, std::memory_order_relaxed); // the toolbar's MIDI input light
  995. if (device.midiChannel != 0 && m.getChannel() != device.midiChannel)
  996. return;
  997. // the pitch wheel, the mod wheel and the other controllers play into the channels the notes go to (round 162,
  998. // issue #9: they did nothing unless linked): hosted plugins get the MIDI message, LYNX's instruments bend by the
  999. // channel's pitch range. A CC with a MIDI link only moves its parameter.
  1000. auto playControl = [this, &device] (int control, float value) {
  1001. NoteEvent e;
  1002. e.type = NoteEvent::Type::control;
  1003. e.key = control;
  1004. e.velocity = value;
  1005. const auto extra = juce::jlimit (0, maxLiveChannels, extraLiveCount.load());
  1006. if (device.target >= 0)
  1007. {
  1008. e.channel = device.target;
  1009. midiEvents.push (e);
  1010. return;
  1011. }
  1012. for (int i = -1; i < extra; ++i)
  1013. {
  1014. e.channel = i < 0 ? liveChannel.load() : extraLiveChannels[(std::size_t) i].load();
  1015. if (e.channel >= 0)
  1016. midiEvents.push (e);
  1017. }
  1018. };
  1019. if (m.isController())
  1020. {
  1021. const auto cc = m.getControllerNumber();
  1022. controllerQueue.push ({ cc, m.getChannel() - 1, m.getControllerValue() });
  1023. // (120…127 are channel mode messages: All Sound / Notes Off, reset…)
  1024. if (cc >= 0 && cc < 120 && (linkedCcs[(std::size_t) (cc >> 6)].load (std::memory_order_relaxed) >> (cc & 63) & 1u) == 0)
  1025. playControl (cc, (float) m.getControllerValue() / 127.0f);
  1026. return;
  1027. }
  1028. if (m.isPitchWheel())
  1029. {
  1030. playControl (NoteEvent::controlPitchBend, juce::jlimit (-1.0f, 1.0f, (float) (m.getPitchWheelValue() - 8192) / 8192.0f));
  1031. return;
  1032. }
  1033. if (m.isChannelPressure())
  1034. {
  1035. playControl (NoteEvent::controlPressure, (float) m.getChannelPressureValue() / 127.0f);
  1036. return;
  1037. }
  1038. if (! m.isNoteOnOrOff())
  1039. return;
  1040. const auto on = m.isNoteOn();
  1041. markHeldKey (m.getNoteNumber(), on);
  1042. if (on)
  1043. startOnInput();
  1044. // a note-off goes to the channels and key its note-on reached (the selection or the scale snap may have
  1045. // changed while the key was down); a repeated note-on first stops what the previous one started
  1046. InputHeldNotes::Target targets[InputHeldNotes::maxTargets], stale[InputHeldNotes::maxTargets];
  1047. auto count = 0;
  1048. auto staleCount = 0;
  1049. if (on)
  1050. {
  1051. const auto key = snapInputKey (m.getNoteNumber());
  1052. const auto extra = juce::jlimit (0, maxLiveChannels, extraLiveCount.load());
  1053. // the primary selected channel, then the other selected ones (or the device's own channel)
  1054. if (device.target >= 0)
  1055. targets[count++] = { device.target, key };
  1056. else
  1057. for (int i = -1; i < extra && count < InputHeldNotes::maxTargets; ++i)
  1058. targets[count++] = { i < 0 ? liveChannel.load() : extraLiveChannels[(std::size_t) i].load(), key };
  1059. staleCount = midiHeld.noteOn (m.getNoteNumber(), targets, count, stale);
  1060. }
  1061. else
  1062. count = midiHeld.noteOff (m.getNoteNumber(), targets);
  1063. auto push = [this] (const InputHeldNotes::Target& t, bool noteOn, float velocity) {
  1064. NoteEvent e;
  1065. e.type = noteOn ? NoteEvent::Type::on : NoteEvent::Type::off;
  1066. e.channel = t.channel;
  1067. e.key = t.key;
  1068. e.velocity = velocity;
  1069. midiEvents.push (e);
  1070. if (transport.recording.load() && transport.playing.load())
  1071. midiRecordQueue.push ({ estimatedPositionNow(), e.channel, e.key, e.velocity, noteOn });
  1072. };
  1073. for (int i = 0; i < staleCount; ++i)
  1074. push (stale[i], false, 0.0f);
  1075. for (int i = 0; i < count; ++i)
  1076. push (targets[i], on, on ? prefs::mapVelocity (m.getFloatVelocity(), velocityCurve) : 0.0f);
  1077. }
  1078. void AudioEngine::enableAllMidiInputs()
  1079. {
  1080. // (a device turned off in the MIDI settings is closed, so other programs can use it)
  1081. std::vector<prefs::MidiPort> available;
  1082. std::vector<std::string> open;
  1083. for (const auto& device : juce::MidiInput::getAvailableDevices())
  1084. {
  1085. available.push_back ({ device.identifier.toStdString(), device.name.toStdString() });
  1086. if (deviceManager.isMidiInputDeviceEnabled (device.identifier))
  1087. open.push_back (device.identifier.toStdString());
  1088. }
  1089. const auto plan = prefs::planMidiInputs (midiPrefs, available, lastMidiInputIds, open);
  1090. for (const auto& id : plan.close)
  1091. deviceManager.setMidiInputDeviceEnabled (juce::String (id), false);
  1092. for (const auto& id : plan.reopen) // it went away and came back: the old handle may be dead
  1093. deviceManager.setMidiInputDeviceEnabled (juce::String (id), false);
  1094. for (const auto* list : { &plan.reopen, &plan.open })
  1095. for (const auto& id : *list)
  1096. deviceManager.setMidiInputDeviceEnabled (juce::String (id), true);
  1097. lastMidiInputIds.clear();
  1098. for (const auto& port : available)
  1099. lastMidiInputIds.push_back (port.id);
  1100. }
  1101. void AudioEngine::reconnectMidiInputs()
  1102. {
  1103. if (prefetcher == nullptr) // (only with an audio device: the real app)
  1104. return;
  1105. for (const auto& device : juce::MidiInput::getAvailableDevices())
  1106. if (deviceManager.isMidiInputDeviceEnabled (device.identifier))
  1107. deviceManager.setMidiInputDeviceEnabled (device.identifier, false);
  1108. enableAllMidiInputs();
  1109. }
  1110. void AudioEngine::setMidiPrefs (const prefs::MidiPrefs& p, bool save)
  1111. {
  1112. midiPrefs = p;
  1113. {
  1114. const juce::SpinLock::ScopedLockType lock (midiPrefsLock);
  1115. midiPrefsShared = p;
  1116. }
  1117. if (! p.pickup)
  1118. pickups.clear();
  1119. if (prefetcher != nullptr) // (only with an audio device: the real app)
  1120. enableAllMidiInputs();
  1121. if (save)
  1122. midiSettingsFile().replaceWithText (juce::String (p.toText()));
  1123. sendChangeMessage();
  1124. }
  1125. void AudioEngine::setUndoLevels (int levels)
  1126. {
  1127. maxUndoSteps = (std::size_t) prefs::clampUndoLevels (levels);
  1128. while (undoStack.size() > maxUndoSteps)
  1129. undoStack.pop_front();
  1130. }
  1131. juce::StringArray AudioEngine::getActiveMidiInputs() const
  1132. {
  1133. juce::StringArray names;
  1134. for (const auto& device : juce::MidiInput::getAvailableDevices())
  1135. if (deviceManager.isMidiInputDeviceEnabled (device.identifier))
  1136. names.add (device.name);
  1137. return names;
  1138. }
  1139. void AudioEngine::setAudioRecordingArmed (bool armed)
  1140. {
  1141. audioArmed = armed;
  1142. recordingError = {};
  1143. if (armed)
  1144. {
  1145. // opens the input of the current driver (every channel, so each insert can pick its own)
  1146. if (! hasAudioInput())
  1147. if (const auto result = openAudioInput(); result.issue != InputIssue::none)
  1148. {
  1149. recordingError = "no audio input";
  1150. notify (result.issue, 0, result.detail);
  1151. }
  1152. if (! recordThread.isThreadRunning())
  1153. recordThread.startThread();
  1154. }
  1155. sendChangeMessage();
  1156. }
  1157. void AudioEngine::setRecording (bool shouldRecord)
  1158. {
  1159. if (shouldRecord && ! transport.recording.load())
  1160. recordingError = {}; // a new attempt
  1161. transport.recording.store (shouldRecord);
  1162. liveInput.recording.store (shouldRecord);
  1163. updateRecording();
  1164. sendChangeMessage();
  1165. }
  1166. void AudioEngine::updateRecording()
  1167. {
  1168. const auto playing = transport.playing.load();
  1169. const auto active = transport.recording.load() && playing;
  1170. if (playing)
  1171. lastPlayingTick = estimatedPositionNow();
  1172. // the take starts when playing with recording on, or at the first recorded event
  1173. // (which is only queued in that situation, even if this timer hasn't seen it yet)
  1174. auto beginTake = [this] {
  1175. if (recorder.isActive())
  1176. return;
  1177. const auto& pattern = song.patterns[(std::size_t) song.currentPattern];
  1178. recorder.begin (pattern.effectiveLength (song.beatsPerBar));
  1179. takeHasUndoStep = false;
  1180. takeClearedChannels.clear();
  1181. takeStartPosition = lastPlayingTick;
  1182. };
  1183. if (active)
  1184. beginTake();
  1185. RecordedEvent e;
  1186. // FL's "Enable recording markers" (song mode): a note that starts outside the Start / Stop recording ranges is
  1187. // not recorded (its release finds no held note and is ignored too)
  1188. const auto punch = recordOptions.recordingMarkers && song.mode == PlayMode::song ? punchRanges (song.markers()) : std::vector<PunchRange> {};
  1189. auto outsidePunch = [this, &punch] (const RecordedEvent& ev) {
  1190. if (punch.empty() || ! ev.on)
  1191. return false;
  1192. auto tick = ev.tick;
  1193. if (! song.hasLoop())
  1194. tick = std::fmod (std::max (0.0, tick), (double) std::max<std::int64_t> (1, song.songLength()));
  1195. return ! inPunchRanges (punch, tick);
  1196. };
  1197. while (midiRecordQueue.pop (e))
  1198. {
  1199. if (! recordOptions.recordNotes || outsidePunch (e)) // recording filter: notes off
  1200. continue;
  1201. beginTake();
  1202. recorder.add (song, e);
  1203. }
  1204. for (const auto& ui : uiRecorded)
  1205. {
  1206. if (! recordOptions.recordNotes || outsidePunch (ui))
  1207. continue;
  1208. beginTake();
  1209. recorder.add (song, ui);
  1210. }
  1211. uiRecorded.clear();
  1212. updateAudioRecording();
  1213. updateAutomationRecording (active);
  1214. if (! active && recorder.isActive())
  1215. recorder.end (song, lastPlayingTick);
  1216. auto notes = recorder.takeFinished();
  1217. if (notes.empty())
  1218. return;
  1219. // the whole take is a single undo step: overdub or replace, quantised to the record grid; in song mode a
  1220. // clip of the pattern is placed where recording started if none plays there
  1221. const auto options = recordOptions;
  1222. auto placeClipAt = (std::int64_t) takeStartPosition;
  1223. if (song.mode == PlayMode::song && ! song.hasLoop()) // (the position loops over the song)
  1224. placeClipAt %= std::max<std::int64_t> (1, song.songLength());
  1225. editSong ([&] (Song& s) {
  1226. TakeQuantize q;
  1227. q.grid = options.quantise;
  1228. q.starts = options.quantiseStarts;
  1229. q.end = options.noteEnd;
  1230. q.stepSequencer = options.toStepSequencer;
  1231. commitTake (s.patterns[(std::size_t) s.currentPattern], notes, options.mode, q, takeClearedChannels);
  1232. if (options.placeSongClip && s.mode == PlayMode::song && ! takeHasUndoStep)
  1233. placePatternClipAt (s, s.currentPattern, placeClipAt);
  1234. }, ! takeHasUndoStep);
  1235. takeHasUndoStep = true;
  1236. }
  1237. void AudioEngine::setSong (Song newSong)
  1238. {
  1239. undoStack.clear();
  1240. redoStack.clear();
  1241. song = std::move (newSong);
  1242. selectedChannel = 0;
  1243. selectedChannels = { 0 };
  1244. modified = false;
  1245. // arming isn't saved: a new project starts disarmed; its inserts' audio inputs open the device input
  1246. for (const auto t : std::vector<int> (armedInserts))
  1247. setInsertArmed (t, false);
  1248. if (prefetcher != nullptr && ! hasAudioInput()
  1249. && std::any_of (song.mixer.begin(), song.mixer.end(), [] (const MixerTrack& t) { return t.inputChannel >= 0 || t.flInput >= 0; }))
  1250. openAudioInput();
  1251. // an FL project's insert inputs (REA round 157c): FL's list index on the device open now
  1252. if (prefetcher != nullptr && hasAudioInput())
  1253. {
  1254. auto* device = deviceManager.getCurrentAudioDevice();
  1255. const auto channels = device != nullptr ? device->getInputChannelNames().size() : 0;
  1256. for (auto& t : song.mixer)
  1257. {
  1258. if (t.flInput >= 0 && t.inputChannel < 0)
  1259. {
  1260. const auto source = flInputSource (t.flInput, channels);
  1261. t.inputChannel = source.channel;
  1262. t.inputStereo = source.stereo;
  1263. }
  1264. t.flInput = -1;
  1265. }
  1266. }
  1267. // hardware output targets: their channels open with the project (the ones the device has)
  1268. if (prefetcher != nullptr)
  1269. openTargetedOutputs();
  1270. publishSong();
  1271. }
  1272. void AudioEngine::editSong (const std::function<void (Song&)>& edit, bool undoable)
  1273. {
  1274. if (undoable)
  1275. {
  1276. // Dozens of edits arrive during a drag; only the first one of the click saves the state.
  1277. bool samePress = false;
  1278. if (juce::ModifierKeys::currentModifiers.isAnyMouseButtonDown())
  1279. {
  1280. const auto press = juce::Desktop::getInstance().getMainMouseSource().getLastMouseDownTime();
  1281. samePress = press == lastUndoPress;
  1282. lastUndoPress = press;
  1283. }
  1284. else
  1285. {
  1286. lastUndoPress = {};
  1287. }
  1288. if (! samePress)
  1289. {
  1290. undoStack.push_back (song);
  1291. redoStack.clear();
  1292. if (undoStack.size() > maxUndoSteps)
  1293. undoStack.pop_front();
  1294. }
  1295. }
  1296. if (undoable)
  1297. modified = true;
  1298. const auto lengthsBefore = patternLengths (song);
  1299. edit (song);
  1300. followPatternLengths (lengthsBefore, song);
  1301. publishSong();
  1302. }
  1303. void AudioEngine::undo()
  1304. {
  1305. if (undoStack.empty())
  1306. return;
  1307. redoStack.push_back (std::move (song));
  1308. song = std::move (undoStack.back());
  1309. undoStack.pop_back();
  1310. modified = true;
  1311. lastUndoPress = {};
  1312. publishSong();
  1313. }
  1314. void AudioEngine::redo()
  1315. {
  1316. if (redoStack.empty())
  1317. return;
  1318. undoStack.push_back (std::move (song));
  1319. song = std::move (redoStack.back());
  1320. redoStack.pop_back();
  1321. modified = true;
  1322. lastUndoPress = {};
  1323. publishSong();
  1324. }
  1325. namespace
  1326. {
  1327. const Song& historyState (const std::deque<Song>& undo, const Song& current, const std::deque<Song>& redo, int index)
  1328. {
  1329. if (index < (int) undo.size())
  1330. return undo[(std::size_t) index];
  1331. if (index == (int) undo.size())
  1332. return current;
  1333. return redo[redo.size() - 1 - (std::size_t) (index - (int) undo.size() - 1)];
  1334. }
  1335. } // namespace
  1336. ChangeLabel AudioEngine::getHistoryLabel (int index) const
  1337. {
  1338. if (index <= 0 || index >= getHistorySize())
  1339. return { TR_NOOP ("Start"), {} };
  1340. return describeChange (historyState (undoStack, song, redoStack, index - 1), historyState (undoStack, song, redoStack, index));
  1341. }
  1342. void AudioEngine::jumpToHistory (int index)
  1343. {
  1344. index = juce::jlimit (0, getHistorySize() - 1, index);
  1345. if (index == getHistoryPosition())
  1346. return;
  1347. // move through the stacks, then publish once
  1348. while (getHistoryPosition() > index && ! undoStack.empty())
  1349. {
  1350. redoStack.push_back (std::move (song));
  1351. song = std::move (undoStack.back());
  1352. undoStack.pop_back();
  1353. }
  1354. while (getHistoryPosition() < index && ! redoStack.empty())
  1355. {
  1356. undoStack.push_back (std::move (song));
  1357. song = std::move (redoStack.back());
  1358. redoStack.pop_back();
  1359. }
  1360. modified = true;
  1361. lastUndoPress = {};
  1362. publishSong();
  1363. }
  1364. void AudioEngine::setSelectedChannel (int channel)
  1365. {
  1366. channel = juce::jlimit (0, juce::jmax (0, (int) song.channels.size() - 1), channel);
  1367. setChannelSelection ({ channel }, channel);
  1368. }
  1369. void AudioEngine::setChannelSelection (std::vector<int> channels, int primary)
  1370. {
  1371. const auto count = (int) song.channels.size();
  1372. std::sort (channels.begin(), channels.end());
  1373. channels.erase (std::unique (channels.begin(), channels.end()), channels.end());
  1374. channels.erase (std::remove_if (channels.begin(), channels.end(), [count] (int c) { return c < 0 || c >= count; }), channels.end());
  1375. primary = juce::jlimit (0, juce::jmax (0, count - 1), primary);
  1376. if (std::find (channels.begin(), channels.end(), primary) == channels.end())
  1377. channels.insert (std::lower_bound (channels.begin(), channels.end(), primary), primary);
  1378. if (channels == selectedChannels && primary == selectedChannel)
  1379. {
  1380. publishSelection();
  1381. return;
  1382. }
  1383. selectedChannels = std::move (channels);
  1384. selectedChannel = primary;
  1385. publishSelection();
  1386. sendChangeMessage();
  1387. }
  1388. void AudioEngine::publishSelection()
  1389. {
  1390. liveChannel.store (selectedChannel);
  1391. int extra = 0;
  1392. for (auto c : selectedChannels)
  1393. if (c != selectedChannel && extra < maxLiveChannels)
  1394. extraLiveChannels[(std::size_t) extra++].store (c);
  1395. extraLiveCount.store (extra);
  1396. }
  1397. namespace
  1398. {
  1399. // Whether a drive / network share is there, within a time limit: a disconnected network drive can block a file
  1400. // query for half a minute, and an open probes many paths under the same root (round 112). One probe per root per open.
  1401. bool rootReachable (const std::string& root)
  1402. {
  1403. auto result = std::make_shared<std::atomic<int>> (-1);
  1404. std::thread ([result, root] {
  1405. result->store (platform::localFile (root).isDirectory() ? 1 : 0); // FL's "C:\" spelling on macOS/Linux too
  1406. }).detach();
  1407. const auto started = juce::Time::getMillisecondCounter();
  1408. while (result->load() < 0 && juce::Time::getMillisecondCounter() - started < 2000)
  1409. juce::Thread::sleep (2);
  1410. return result->load() == 1; // still unknown after 2 s: treated as missing (the probe thread finishes on its own)
  1411. }
  1412. std::string userOf (const Song& song, std::size_t track)
  1413. {
  1414. return song.mixer[track].name.empty() ? (track == 0 ? std::string ("Master") : "Insert " + std::to_string (track)) : song.mixer[track].name;
  1415. }
  1416. } // namespace
  1417. void AudioEngine::prepareFlpImport (const juce::File& file, const std::map<std::string, std::string>& relocations, SampleLibrary& library,
  1418. PreparedFlp& out)
  1419. {
  1420. juce::MemoryBlock data;
  1421. {
  1422. const loadtrace::Scope timing ("read_project");
  1423. if (! file.loadFileAsData (data))
  1424. {
  1425. out.error = utf8 ("could not read the file");
  1426. return;
  1427. }
  1428. }
  1429. try
  1430. {
  1431. loadtrace::stage (0.20, 0.30, TR_NOOP ("Reading the project..."));
  1432. const auto started = std::chrono::steady_clock::now();
  1433. const auto project = flp::parseProject ({ static_cast<const std::uint8_t*> (data.getData()), data.getSize() });
  1434. loadtrace::add ("parse", loadtrace::msSince (started));
  1435. FlpImportOptions options;
  1436. options.roots = findFlStudioRoots();
  1437. options.projectFolder = file.getParentDirectory().getFullPathName().toStdString();
  1438. // samples on a drive that is not there (unplugged external drive, dead network share): one probe per root
  1439. auto roots = std::make_shared<loadtrace::RootProbe> ([] (const std::string& root) {
  1440. const auto t = std::chrono::steady_clock::now();
  1441. const auto ok = rootReachable (root);
  1442. loadtrace::add ("probe_root", loadtrace::msSince (t));
  1443. return ok;
  1444. });
  1445. options.fileExists = [roots] (const std::string& path) {
  1446. if (! roots->rootAvailable (path))
  1447. return false;
  1448. const auto t = std::chrono::steady_clock::now();
  1449. const auto exists = platform::localFile (path).existsAsFile();
  1450. loadtrace::add ("probe_file", loadtrace::msSince (t));
  1451. return exists;
  1452. };
  1453. options.readFile = [roots] (const std::string& path) {
  1454. if (! roots->rootAvailable (path))
  1455. return std::vector<std::uint8_t> {};
  1456. const auto t = std::chrono::steady_clock::now();
  1457. juce::MemoryBlock data;
  1458. platform::localFile (path).loadFileAsData (data);
  1459. const auto* bytes = static_cast<const std::uint8_t*> (data.getData());
  1460. loadtrace::add ("read_aux_file", loadtrace::msSince (t));
  1461. return std::vector<std::uint8_t> (bytes, bytes + data.getSize());
  1462. };
  1463. auto decoded = std::make_shared<std::vector<std::shared_ptr<const SampleData>>>();
  1464. options.sampleFrames = [&library, decoded] (const std::string& path) -> std::int64_t {
  1465. const auto sample = library.load (juce::String::fromUTF8 (path.c_str()));
  1466. if (sample != nullptr)
  1467. decoded->push_back (sample); // kept: the rack uses it next (it was decoded twice before)
  1468. return sample != nullptr ? (std::int64_t) sample->frames() : 0;
  1469. };
  1470. // WAV that only exists inside the .flp (Slicex): goes to %APPDATA%\LYNX\flp-embedded, keyed by content
  1471. options.saveEmbedded = [] (const std::vector<std::uint8_t>& wav, const std::string& name) -> std::string {
  1472. const auto folder = PluginHost::settingsFolder().getChildFile ("flp-embedded");
  1473. folder.createDirectory();
  1474. const auto hash = juce::String::toHexString ((juce::int64) juce::DefaultHashFunctions::generateHash (
  1475. juce::String::createStringFromData (wav.data(), (int) juce::jmin<std::size_t> (wav.size(), 65536)) + juce::String ((juce::int64) wav.size()),
  1476. 0x7FFFFFFF));
  1477. const auto file = folder.getChildFile (juce::File::createLegalFileName (juce::String::fromUTF8 (name.c_str())) + "-" + hash + ".wav");
  1478. if (! file.existsAsFile() && ! file.replaceWithData (wav.data(), wav.size()))
  1479. return {};
  1480. return file.getFullPathName().toStdString();
  1481. };
  1482. out.report = {};
  1483. options.report = &out.report;
  1484. options.relocations = relocations;
  1485. {
  1486. const auto t = std::chrono::steady_clock::now();
  1487. out.song = importFlp (project, options);
  1488. loadtrace::add ("import", loadtrace::msSince (t));
  1489. }
  1490. loadtrace::add ("missing_roots", 0.0, (int) roots->missingRoots().size());
  1491. loadtrace::add ("probe_skipped", 0.0, roots->skipped());
  1492. // the project's third-party plugins, to say which channel/insert used each one that is missing
  1493. for (const auto& c : out.song.channels)
  1494. if (c.plugin.foreign.format != ForeignPlugin::Format::none)
  1495. out.uses.push_back ({ c.plugin.foreign.name, c.name, true });
  1496. for (std::size_t t = 0; t < out.song.mixer.size(); ++t)
  1497. for (const auto& fx : out.song.mixer[t].effects)
  1498. if (fx.kind == EffectKind::plugin && fx.plugin.foreign.format != ForeignPlugin::Format::none)
  1499. out.uses.push_back ({ fx.plugin.foreign.name, userOf (out.song, t), false });
  1500. // (and the ones inside Patchers, REA_rodada141)
  1501. std::function<void (const PatcherDoc&, const std::string&)> patcherUses = [&] (const PatcherDoc& doc, const std::string& user) {
  1502. for (const auto& n : doc.nodes)
  1503. {
  1504. const auto& ref = n.generator ? n.channel.plugin : n.effect.plugin;
  1505. if (ref.foreign.format != ForeignPlugin::Format::none)
  1506. out.uses.push_back ({ ref.foreign.name, user + " (Patcher)", n.generator });
  1507. if (n.generator && n.channel.instrument == InstrumentKind::patcher)
  1508. patcherUses (n.channel.patcher, user);
  1509. if (! n.generator && n.effect.kind == EffectKind::patcher)
  1510. patcherUses (n.effect.patcher, user);
  1511. }
  1512. };
  1513. for (const auto& c : out.song.channels)
  1514. if (c.instrument == InstrumentKind::patcher)
  1515. patcherUses (c.patcher, c.name);
  1516. for (std::size_t t = 0; t < out.song.mixer.size(); ++t)
  1517. for (const auto& fx : out.song.mixer[t].effects)
  1518. if (fx.kind == EffectKind::patcher)
  1519. patcherUses (fx.patcher, userOf (out.song, t));
  1520. // the samples, decoded now (in parallel, off the message thread) so building the rack only finds them ready
  1521. std::vector<std::string> paths;
  1522. auto addPath = [&paths] (const std::string& p) {
  1523. if (! p.empty() && std::find (paths.begin(), paths.end(), p) == paths.end())
  1524. paths.push_back (p);
  1525. };
  1526. for (const auto& c : out.song.channels)
  1527. {
  1528. if (c.instrument == InstrumentKind::sampler || c.instrument == InstrumentKind::audioClip || c.instrument == InstrumentKind::granulizer
  1529. || c.instrument == InstrumentKind::flkeys || c.instrument == InstrumentKind::directwave)
  1530. addPath (c.samplePath);
  1531. for (const auto& z : c.zones)
  1532. addPath (z.path);
  1533. }
  1534. for (const auto& track : out.song.mixer)
  1535. for (const auto& fx : track.effects)
  1536. addPath (fx.samplePath);
  1537. loadtrace::stage (0.30, 0.55, TR_NOOP ("Reading the samples..."), TR_NOOP ("Reading {0}... {1}/{2}"));
  1538. const auto decodeStarted = std::chrono::steady_clock::now();
  1539. std::atomic<std::size_t> next { 0 }, done { 0 };
  1540. std::mutex keep;
  1541. auto worker = [&] {
  1542. for (auto i = next++; i < paths.size(); i = next++)
  1543. {
  1544. const auto t = std::chrono::steady_clock::now();
  1545. auto sample = library.load (juce::String::fromUTF8 (paths[i].c_str()));
  1546. loadtrace::add ("sample_decode", loadtrace::msSince (t));
  1547. {
  1548. const std::scoped_lock l (keep);
  1549. if (sample != nullptr)
  1550. out.decoded.push_back (std::move (sample));
  1551. }
  1552. const auto n = ++done;
  1553. loadtrace::step ((int) n, (int) paths.size(),
  1554. juce::File::createFileWithoutCheckingPath (juce::String::fromUTF8 (paths[i].c_str())).getFileName().toStdString());
  1555. }
  1556. };
  1557. const auto threads = (std::size_t) juce::jlimit (1, 6, juce::SystemStats::getNumCpus() - 1);
  1558. std::vector<std::thread> pool;
  1559. for (std::size_t i = 1; i < juce::jmin (threads, paths.size()); ++i)
  1560. pool.emplace_back (worker);
  1561. worker();
  1562. for (auto& t : pool)
  1563. t.join();
  1564. for (auto& d : *decoded)
  1565. out.decoded.push_back (std::move (d));
  1566. // pitch-preserving stretch (audio clips that follow the tempo): the stretched copy too, in parallel, with the
  1567. // same ratio the rack asks for (RackState::build) — it was computed on the message thread while building
  1568. struct Stretch
  1569. {
  1570. std::string path;
  1571. double ratio;
  1572. StretchMethod method;
  1573. };
  1574. std::vector<Stretch> stretches;
  1575. for (const auto& c : out.song.channels)
  1576. if ((c.instrument == InstrumentKind::sampler || c.instrument == InstrumentKind::audioClip) && c.zones.empty() && ! c.samplePath.empty()
  1577. && c.sampler.keepPitch && c.sampler.stretchBeats > 0.0f)
  1578. if (const auto data = library.load (juce::String::fromUTF8 (c.samplePath.c_str())); data != nullptr && data->frames() > 0)
  1579. {
  1580. const auto target = c.sampler.stretchBeats * 60.0 / std::max (1.0, out.song.bpm);
  1581. const auto ratio = target / ((double) data->frames() / data->sampleRate);
  1582. const auto method = c.sampler.stretchMethod;
  1583. if (std::none_of (stretches.begin(), stretches.end(), [&] (const Stretch& x) { return x.path == c.samplePath && x.ratio == ratio && x.method == method; }))
  1584. stretches.push_back ({ c.samplePath, ratio, method });
  1585. }
  1586. if (! stretches.empty())
  1587. {
  1588. const auto stretchStarted = std::chrono::steady_clock::now();
  1589. std::atomic<std::size_t> nextStretch { 0 };
  1590. auto stretchWorker = [&] {
  1591. for (auto i = nextStretch++; i < stretches.size(); i = nextStretch++)
  1592. library.loadStretched (juce::String::fromUTF8 (stretches[i].path.c_str()), stretches[i].ratio, stretches[i].method);
  1593. };
  1594. std::vector<std::thread> helpers;
  1595. for (std::size_t i = 1; i < juce::jmin (threads, stretches.size()); ++i)
  1596. helpers.emplace_back (stretchWorker);
  1597. stretchWorker();
  1598. for (auto& t : helpers)
  1599. t.join();
  1600. loadtrace::add ("stretch_wall", loadtrace::msSince (stretchStarted), (int) stretches.size());
  1601. }
  1602. loadtrace::add ("samples_wall", loadtrace::msSince (decodeStarted), (int) paths.size());
  1603. out.ok = true;
  1604. }
  1605. catch (const flp::Error& e)
  1606. {
  1607. out.error = juce::String::fromUTF8 (e.what());
  1608. }
  1609. }
  1610. void AudioEngine::adoptPrepared (PreparedFlp& prepared)
  1611. {
  1612. if (prepared.adopted)
  1613. return;
  1614. prepared.adopted = true;
  1615. const auto t = std::chrono::steady_clock::now();
  1616. plugins.clearPreloaded();
  1617. plugins.setPreloadRate (transport.sampleRate.load());
  1618. plugins.adoptFlPlugins (prepared.song, &prepared.missing, &prepared.matched, &prepared.withoutState, &prepared.substituted);
  1619. loadtrace::add ("adopt_plugins", loadtrace::msSince (t));
  1620. // the hosted plugins the rack will create, in its order (channels, then inserts)
  1621. for (const auto& c : prepared.song.channels)
  1622. if (c.instrument == InstrumentKind::plugin && ! c.plugin.id.empty())
  1623. prepared.pluginQueue.push_back (c.plugin);
  1624. for (const auto& track : prepared.song.mixer)
  1625. for (std::size_t i = 0; i < track.effects.size() && i < (std::size_t) maxEffectSlots; ++i)
  1626. if (track.effects[i].kind == EffectKind::plugin && ! track.effects[i].plugin.id.empty())
  1627. prepared.pluginQueue.push_back (track.effects[i].plugin);
  1628. }
  1629. bool AudioEngine::preloadNextPlugin (PreparedFlp& prepared)
  1630. {
  1631. adoptPrepared (prepared);
  1632. if (prepared.pluginsDone >= prepared.pluginQueue.size())
  1633. return false;
  1634. const auto total = (int) prepared.pluginQueue.size();
  1635. const auto& ref = prepared.pluginQueue[prepared.pluginsDone];
  1636. auto wanted = 0;
  1637. for (std::size_t i = 0; i <= prepared.pluginsDone; ++i)
  1638. wanted += prepared.pluginQueue[i].id == ref.id && prepared.pluginQueue[i].state == ref.state ? 1 : 0;
  1639. plugins.preload (ref, wanted);
  1640. ++prepared.pluginsDone;
  1641. loadtrace::step ((int) prepared.pluginsDone, total, {});
  1642. return prepared.pluginsDone < prepared.pluginQueue.size();
  1643. }
  1644. bool AudioEngine::finishFlpImport (PreparedFlp&& prepared, bool asEdit)
  1645. {
  1646. if (! prepared.ok)
  1647. return false;
  1648. adoptPrepared (prepared);
  1649. auto& imported = prepared.song;
  1650. importReport = std::move (prepared.report);
  1651. const auto& uses = prepared.uses;
  1652. missingPlugins = prepared.missing;
  1653. matchedPlugins = prepared.matched;
  1654. pluginsWithoutState = prepared.withoutState;
  1655. missingPluginDetails.clear();
  1656. for (const auto& name : prepared.missing)
  1657. {
  1658. MissingPlugin m;
  1659. m.name = name.toStdString();
  1660. for (const auto& u : uses)
  1661. if (u.name == m.name)
  1662. {
  1663. if (std::find (m.usedBy.begin(), m.usedBy.end(), u.user) == m.usedBy.end())
  1664. m.usedBy.push_back (u.user);
  1665. m.replacement = u.instrument ? "Built-in synth (a preset chosen by the channel name)" : "Nothing: the slot was left out of the mixer";
  1666. }
  1667. missingPluginDetails.push_back (std::move (m));
  1668. }
  1669. // missing, played by a LYNX substitute that keeps the original for when it is installed
  1670. for (std::size_t t = 0; t < imported.mixer.size(); ++t)
  1671. for (const auto& fx : imported.mixer[t].effects)
  1672. if (fx.isSubstitute())
  1673. {
  1674. const auto name = substituteOriginalName (fx);
  1675. auto it = std::find_if (missingPluginDetails.begin(), missingPluginDetails.end(),
  1676. [&] (const MissingPlugin& m) { return m.name == name && ! m.replacementArg.empty(); });
  1677. if (it == missingPluginDetails.end())
  1678. it = missingPluginDetails.insert (missingPluginDetails.end(),
  1679. MissingPlugin { name, {}, TR_NOOP ("LYNX substitute: {0} (the original plugin is used again once it is installed). FL Studio plays a missing plugin's slot unprocessed: a substitute slot's menu › Bypass all LYNX substitutes of this project does the same"),
  1680. effectInfo (fx.kind).name });
  1681. const auto user = userOf (imported, t);
  1682. if (std::find (it->usedBy.begin(), it->usedBy.end(), user) == it->usedBy.end())
  1683. it->usedBy.push_back (user);
  1684. }
  1685. // found, but the project's settings are in the other format (VST2 <-> VST3): they play their default sound
  1686. for (const auto& line : prepared.withoutState)
  1687. missingPluginDetails.push_back ({ line.toStdString(), {}, TR_NOOP ("Its default settings: the project saved them for the other format (VST2/VST3)") });
  1688. plugins.clearLoadFailures();
  1689. loadtrace::stage (0.90, 0.99, TR_NOOP ("Building the mixer..."));
  1690. {
  1691. const loadtrace::Scope timing ("set_song");
  1692. if (asEdit)
  1693. editSong ([&imported] (Song& s) { s = std::move (imported); });
  1694. else
  1695. {
  1696. stop();
  1697. rewind();
  1698. setSong (std::move (imported));
  1699. }
  1700. }
  1701. plugins.clearPreloaded(); // (any left over: a slot the rack reused, nothing to keep)
  1702. prepared.decoded.clear();
  1703. // installed but failed to load (the rack was just built): silence / bypass, said as loudly as a missing one
  1704. for (const auto& line : plugins.getLoadFailures())
  1705. missingPluginDetails.push_back ({ line.toStdString(), {}, TR_NOOP ("Silence: the plugin is installed but did not load") });
  1706. return true;
  1707. }
  1708. bool AudioEngine::importFlpFile (const juce::File& file, juce::String& error, const std::map<std::string, std::string>& relocations, bool asEdit)
  1709. {
  1710. // a slow plugin module (a Waves shell) starts on its own thread while the samples decode (round 121)
  1711. if (juce::MemoryBlock data; file.loadFileAsData (data))
  1712. try
  1713. {
  1714. PluginHost::newOpen();
  1715. plugins.startModulesFor (flpForeignPlugins (flp::parseProject ({ static_cast<const std::uint8_t*> (data.getData()), data.getSize() })));
  1716. }
  1717. catch (const flp::Error&)
  1718. {
  1719. }
  1720. PreparedFlp prepared;
  1721. prepareFlpImport (file, relocations, samples, prepared);
  1722. if (! prepared.ok)
  1723. {
  1724. error = prepared.error;
  1725. return false;
  1726. }
  1727. if (asEdit)
  1728. keepRunningPlugins (prepared);
  1729. loadtrace::stage (0.55, 0.90, TR_NOOP ("Loading plugins..."), TR_NOOP ("Loading {0}... {1}/{2}"));
  1730. while (preloadNextPlugin (prepared))
  1731. {
  1732. }
  1733. return finishFlpImport (std::move (prepared), asEdit);
  1734. }
  1735. void AudioEngine::keepRunningPlugins (PreparedFlp& prepared)
  1736. {
  1737. // The open project imported again (Missing files › Apply): its plugins are already running with these settings,
  1738. // and the rack keeps a slot whose plugin did not change. Creating them all again first (round 151: 71 plugins,
  1739. // 25 s with the window frozen, then a crash inside a plugin as the second copies replaced the first) is skipped
  1740. // for every plugin the song already has with the same settings.
  1741. adoptPrepared (prepared);
  1742. std::vector<const PluginRef*> running;
  1743. for (const auto& c : song.channels)
  1744. if (c.instrument == InstrumentKind::plugin && ! c.plugin.id.empty())
  1745. running.push_back (&c.plugin);
  1746. for (const auto& track : song.mixer)
  1747. for (const auto& fx : track.effects)
  1748. if (fx.kind == EffectKind::plugin && ! fx.plugin.id.empty())
  1749. running.push_back (&fx.plugin);
  1750. auto& queue = prepared.pluginQueue;
  1751. queue.erase (std::remove_if (queue.begin(), queue.end(),
  1752. [&running] (const PluginRef& ref) {
  1753. const auto it = std::find_if (running.begin(), running.end(), [&ref] (const PluginRef* r) { return r != nullptr && *r == ref; });
  1754. if (it == running.end())
  1755. return false;
  1756. *it = nullptr; // each running plugin stands for one queued copy
  1757. return true;
  1758. }),
  1759. queue.end());
  1760. }
  1761. void AudioEngine::publishSong()
  1762. {
  1763. // diagnostics (round 149): with LYNX_TRACE_EDITS set, each publish's time goes to %APPDATA%\LYNX\edits.log
  1764. static const bool traceEdits = std::getenv ("LYNX_TRACE_EDITS") != nullptr;
  1765. const auto publishStart = juce::Time::getMillisecondCounterHiRes();
  1766. const juce::ScopeGuard traceEnd { [&] {
  1767. if (traceEdits)
  1768. platform::settingsFile ("edits.log").appendText (juce::String (juce::Time::getMillisecondCounterHiRes() - publishStart, 1) + " ms publish\n");
  1769. } };
  1770. // the Master's hardware output target, read by the device callback
  1771. masterOutChannel.store (song.mixer.empty() ? outputDefault : song.mixer[0].outputChannel, std::memory_order_relaxed);
  1772. masterOutMode.store (song.mixer.empty() ? 0 : (int) song.mixer[0].outputMode, std::memory_order_relaxed);
  1773. song.currentPattern = juce::jlimit (0, juce::jmax (0, (int) song.patterns.size() - 1), song.currentPattern);
  1774. selectedChannel = juce::jlimit (0, juce::jmax (0, (int) song.channels.size() - 1), selectedChannel);
  1775. {
  1776. const auto count = (int) song.channels.size();
  1777. selectedChannels.erase (std::remove_if (selectedChannels.begin(), selectedChannels.end(), [count] (int c) { return c >= count; }),
  1778. selectedChannels.end());
  1779. if (std::find (selectedChannels.begin(), selectedChannels.end(), selectedChannel) == selectedChannels.end())
  1780. selectedChannels.insert (std::lower_bound (selectedChannels.begin(), selectedChannels.end(), selectedChannel), selectedChannel);
  1781. }
  1782. publishSelection();
  1783. transport.bpm.store (song.bpm);
  1784. transport.beatsPerBar.store (song.beatsPerBar);
  1785. {
  1786. // time-signature table for the metronome: the start (beatsPerBar/4) and each signature change
  1787. transport.signatureVersion.fetch_add (1, std::memory_order_acq_rel); // odd: writing
  1788. int count = 0;
  1789. transport.signatureTick[0].store (0, std::memory_order_relaxed);
  1790. transport.signatureLength[0].store ((std::int64_t) ppq * juce::jmax (1, song.beatsPerBar), std::memory_order_relaxed);
  1791. ++count;
  1792. for (const auto& m : song.markers())
  1793. if (m.isSignature() && count < Transport::maxSignatures)
  1794. {
  1795. const auto length = juce::jmax<std::int64_t> (1, (std::int64_t) ppq * 4 * m.numerator / juce::jmax (1, m.denominator));
  1796. const auto slot = m.tick <= 0 ? 0 : count++; // at position 0 it replaces the default
  1797. transport.signatureTick[(std::size_t) slot].store (juce::jmax<std::int64_t> (0, m.tick), std::memory_order_relaxed);
  1798. transport.signatureLength[(std::size_t) slot].store (length, std::memory_order_relaxed);
  1799. }
  1800. transport.signatureCount.store (count, std::memory_order_relaxed);
  1801. transport.signatureVersion.fetch_add (1, std::memory_order_acq_rel); // even: ready
  1802. }
  1803. transport.songMode.store (song.mode == PlayMode::song);
  1804. transport.loopStart.store ((double) song.loopStart);
  1805. transport.loopEnd.store ((double) song.loopEnd);
  1806. transport.songEnd.store ((double) song.songLength());
  1807. const loadtrace::Scope buildTiming ("rack_build");
  1808. RackState::Factories factories;
  1809. factories.samples = [this] (const std::string& path) {
  1810. const loadtrace::Scope timing ("rack_samples");
  1811. return samples.load (juce::String::fromUTF8 (path.c_str()));
  1812. };
  1813. factories.stretchedSamples = [this] (const std::string& path, double ratio, StretchMethod method) {
  1814. const loadtrace::Scope timing ("rack_stretch");
  1815. return samples.loadStretched (juce::String::fromUTF8 (path.c_str()), ratio, method);
  1816. };
  1817. factories.pluginInstruments = [this] (const PluginRef& ref, double sr) { return plugins.makeInstrument (ref, sr); };
  1818. factories.pluginEffects = [this] (const PluginRef& ref, double sr) { return plugins.makeEffect (ref, sr); };
  1819. const auto buildStart = juce::Time::getMillisecondCounterHiRes();
  1820. const auto tracePhases = traceEdits && ! loadtrace::active(); // the build's phases (an open traces its own)
  1821. if (tracePhases)
  1822. loadtrace::begin ("edit");
  1823. auto state = RackState::build (song, &lastPublishedShape, transport.sampleRate.load(), factories);
  1824. if (traceEdits)
  1825. platform::settingsFile ("edits.log").appendText (juce::String (juce::Time::getMillisecondCounterHiRes() - buildStart, 1) + " ms rack build\n"
  1826. + (tracePhases ? juce::String (loadtrace::reportLines()) : juce::String()));
  1827. if (tracePhases)
  1828. loadtrace::end();
  1829. // what the next build needs to reuse instruments and effects
  1830. lastPublishedShape.song.channels = song.channels;
  1831. lastPublishedShape.song.mixer = song.mixer;
  1832. // the tempo too (round 149): a channel that plays a time-stretched copy is kept when its stretch and the tempo
  1833. // did not change; without it every edit rebuilt them (sample reloaded and stretch looked up, ~0.5 s on Thief)
  1834. lastPublishedShape.song.bpm = song.bpm;
  1835. lastPublishedShape.instruments = state->instruments;
  1836. lastPublishedShape.effects = state->effects;
  1837. lastPublishedShape.sampleRate = state->sampleRate;
  1838. lastPublishedShape.latencies = state->latencies;
  1839. lastPublishedShape.pdc = state->pdc;
  1840. lastPublishedShape.channelDelays = state->channelDelays;
  1841. lastPublishedShape.sendDelays = state->sendDelays;
  1842. const auto mark = [&] (const char* what) {
  1843. if (traceEdits)
  1844. platform::settingsFile ("edits.log").appendText (juce::String (juce::Time::getMillisecondCounterHiRes() - publishStart, 1) + " ms " + what + "\n");
  1845. };
  1846. mark ("built");
  1847. rackExchange.publish (std::move (state));
  1848. mark ("exchanged");
  1849. if (prefetcher != nullptr)
  1850. prefetcher->update (song, samples);
  1851. mark ("prefetch updated");
  1852. sendChangeMessage();
  1853. }
  1854. std::vector<MidiLink> AudioEngine::getGlobalLinks() const
  1855. {
  1856. std::vector<MidiLink> out;
  1857. for (const auto& l : midiPrefs.globalLinks)
  1858. out.push_back ({ l.cc, l.channel, { (AutomationTargetKind) l.kind, l.index, l.slot, l.param } });
  1859. return out;
  1860. }
  1861. std::optional<MidiLink> AudioEngine::globalLinkOf (const AutomationTarget& target) const
  1862. {
  1863. for (const auto& l : getGlobalLinks())
  1864. if (l.target == target)
  1865. return l;
  1866. return std::nullopt;
  1867. }
  1868. void AudioEngine::learnGlobalLink (const AutomationTarget& target)
  1869. {
  1870. learning = target;
  1871. learningGlobal = true;
  1872. sendChangeMessage();
  1873. }
  1874. void AudioEngine::removeGlobalLink (const AutomationTarget& target)
  1875. {
  1876. auto p = midiPrefs;
  1877. p.globalLinks.erase (std::remove_if (p.globalLinks.begin(), p.globalLinks.end(),
  1878. [&] (const prefs::GlobalLink& l) {
  1879. return l.kind == (int) target.kind && l.index == target.index && l.slot == target.slot
  1880. && l.param == target.param;
  1881. }),
  1882. p.globalLinks.end());
  1883. setMidiPrefs (p, saveGlobalLinks);
  1884. }
  1885. void AudioEngine::learnMidiController (const AutomationTarget& target)
  1886. {
  1887. learning = target;
  1888. learningGlobal = false;
  1889. sendChangeMessage();
  1890. }
  1891. // --- last tweaked parameters and automation recording (REA round 143) --------------------------------------
  1892. void AudioEngine::noteTweaked (const AutomationTarget& target, bool held)
  1893. {
  1894. if (target.kind == AutomationTargetKind::none)
  1895. return;
  1896. if (! (lastTweaked[0] == target))
  1897. {
  1898. lastTweaked[1] = lastTweaked[0];
  1899. lastTweaked[0] = target;
  1900. }
  1901. const auto now = juce::Time::getMillisecondCounterHiRes();
  1902. auto it = std::find_if (touches.begin(), touches.end(), [&] (const Touch& t) { return t.target == target; });
  1903. if (it == touches.end())
  1904. {
  1905. touches.push_back ({ target, now, held, {} });
  1906. return;
  1907. }
  1908. it->lastMs = now;
  1909. it->held = it->held || held;
  1910. }
  1911. void AudioEngine::tweakReleased (const AutomationTarget& target)
  1912. {
  1913. for (auto& t : touches)
  1914. if (t.target == target)
  1915. {
  1916. t.held = false;
  1917. t.lastMs = juce::Time::getMillisecondCounterHiRes();
  1918. }
  1919. }
  1920. std::optional<AutomationTarget> AudioEngine::getLastTweaked (int which) const
  1921. {
  1922. if (which < 0 || which > 1 || lastTweaked[(std::size_t) which].kind == AutomationTargetKind::none
  1923. || currentTargetValue (lastTweaked[(std::size_t) which]) < 0.0f)
  1924. return std::nullopt;
  1925. return lastTweaked[(std::size_t) which];
  1926. }
  1927. float AudioEngine::currentTargetValue (const AutomationTarget& t) const
  1928. {
  1929. const auto base = song.targetValue (t);
  1930. if (base < 0.0f || (t.kind != AutomationTargetKind::channelParam && t.kind != AutomationTargetKind::effectParam))
  1931. return base;
  1932. juce::AudioPluginInstance* plugin = nullptr;
  1933. float midiValue = -1.0f;
  1934. if (t.kind == AutomationTargetKind::channelParam)
  1935. if (auto* p = dynamic_cast<PluginInstrument*> (getChannelInstrument (t.index).get()))
  1936. {
  1937. plugin = &p->getInstance();
  1938. midiValue = midictl::isMidiParam (t.param) ? p->midiControlValue (t.param) : -1.0f;
  1939. }
  1940. if (t.kind == AutomationTargetKind::effectParam)
  1941. if (auto* p = dynamic_cast<PluginEffect*> (getEffect (t.index, t.slot).get()))
  1942. {
  1943. plugin = &p->getInstance();
  1944. midiValue = midictl::isMidiParam (t.param) ? p->midiControlValue (t.param) : -1.0f;
  1945. }
  1946. if (midiValue >= 0.0f)
  1947. return midiValue;
  1948. if (plugin != nullptr && t.param >= 0 && t.param < plugin->getParameters().size())
  1949. return plugin->getParameters()[t.param]->getValue();
  1950. return base;
  1951. }
  1952. std::optional<AutomationTarget> AudioEngine::targetOfPlugin (const juce::AudioPluginInstance& plugin, int param) const
  1953. {
  1954. for (int c = 0; c < (int) song.channels.size(); ++c)
  1955. if (auto* p = dynamic_cast<PluginInstrument*> (getChannelInstrument (c).get()); p != nullptr && &p->getInstance() == &plugin)
  1956. return AutomationTarget { AutomationTargetKind::channelParam, c, 0, param };
  1957. for (int t = 0; t < (int) song.mixer.size(); ++t)
  1958. for (int s = 0; s < (int) song.mixer[(std::size_t) t].effects.size(); ++s)
  1959. if (auto* p = dynamic_cast<PluginEffect*> (getEffect (t, s).get()); p != nullptr && &p->getInstance() == &plugin)
  1960. return AutomationTarget { AutomationTargetKind::effectParam, t, s, param };
  1961. return std::nullopt;
  1962. }
  1963. void AudioEngine::updateAutomationRecording (bool active)
  1964. {
  1965. const auto now = juce::Time::getMillisecondCounterHiRes();
  1966. const auto recording = active && recordOptions.recordAutomation;
  1967. const auto grid = recordOptions.quantiseAutomation ? recordOptions.quantise : std::int64_t { 0 };
  1968. auto writeFor = [this] (const AutomationTarget& target) -> AutomationWrite& {
  1969. auto it = std::find_if (takeWrites.begin(), takeWrites.end(), [&] (const AutomationWrite& w) { return w.target == target; });
  1970. if (it != takeWrites.end())
  1971. return *it;
  1972. AutomationWrite w;
  1973. w.target = target;
  1974. w.name = nameAutomation ? nameAutomation (target) : std::string ("Automation");
  1975. takeWrites.push_back (w);
  1976. return takeWrites.back();
  1977. };
  1978. // writes what was sampled (one undo step for the whole take); `ended` = the gestures that are over
  1979. auto commit = [&] (const std::vector<AutomationTarget>& ended) {
  1980. if (std::none_of (touches.begin(), touches.end(), [] (const Touch& t) { return ! t.pending.empty(); }))
  1981. return;
  1982. const auto songMode = song.mode == PlayMode::song;
  1983. editSong ([&] (Song& s) {
  1984. for (auto& t : touches)
  1985. if (! t.pending.empty())
  1986. {
  1987. auto& w = writeFor (t.target);
  1988. recordedAutomationPoints += (int) t.pending.size();
  1989. if (songMode)
  1990. commitAutomationPoints (s, w, std::move (t.pending), grid);
  1991. else
  1992. commitEventPoints (s, automationPattern, w, std::move (t.pending), automationLoopLength, grid);
  1993. t.pending.clear();
  1994. }
  1995. }, ! automationTakeHasUndoStep);
  1996. automationTakeHasUndoStep = true;
  1997. for (const auto& target : ended)
  1998. writeFor (target).lastLocal = -1; // the next gesture on it starts a new stretch
  1999. };
  2000. // FL: while recording, the moved control wins over its playing automation at once (REA round 146); the
  2001. // automation of a touched target does not drive it until the gesture ends and its points are written.
  2002. auto overrideTouched = [this] {
  2003. if (rackProcessor == nullptr)
  2004. return;
  2005. std::vector<int> slots, one;
  2006. for (const auto& t : touches)
  2007. {
  2008. RackState::slotsOfTarget (song, t.target, one);
  2009. slots.insert (slots.end(), one.begin(), one.end());
  2010. }
  2011. if (slots.empty() && ! automationOverrideActive)
  2012. return;
  2013. rackProcessor->getRenderer().setOverriddenSlots (slots);
  2014. automationOverrideActive = ! slots.empty();
  2015. };
  2016. if (! recording)
  2017. {
  2018. commit ({});
  2019. touches.clear();
  2020. overrideTouched();
  2021. if (! active)
  2022. {
  2023. takeWrites.clear();
  2024. automationTakeHasUndoStep = false;
  2025. automationLoopLength = 0;
  2026. }
  2027. return;
  2028. }
  2029. if (automationLoopLength <= 0)
  2030. {
  2031. automationPattern = song.currentPattern;
  2032. automationLoopLength = song.patterns.empty() ? ppq * 4
  2033. : song.patterns[(std::size_t) juce::jlimit (0, (int) song.patterns.size() - 1, song.currentPattern)]
  2034. .effectiveLength (song.beatsPerBar);
  2035. }
  2036. const auto tick = estimatedPositionNow();
  2037. std::vector<AutomationTarget> ended;
  2038. for (auto& t : touches)
  2039. {
  2040. const auto alive = t.held || now - t.lastMs < 350.0;
  2041. const auto value = currentTargetValue (t.target);
  2042. if (value < 0.0f)
  2043. {
  2044. ended.push_back (t.target);
  2045. continue;
  2046. }
  2047. if (alive)
  2048. t.pending.push_back ({ tick, value });
  2049. else
  2050. ended.push_back (t.target);
  2051. }
  2052. if (! ended.empty() || --automationCommitCountdown <= 0)
  2053. {
  2054. commit (ended);
  2055. automationCommitCountdown = 6; // about 5 writes per second while a control keeps moving
  2056. }
  2057. touches.erase (std::remove_if (touches.begin(), touches.end(),
  2058. [&] (const Touch& t) { return std::find (ended.begin(), ended.end(), t.target) != ended.end(); }),
  2059. touches.end());
  2060. overrideTouched();
  2061. }
  2062. void AudioEngine::applyControllers()
  2063. {
  2064. ControllerEvent e;
  2065. std::map<std::pair<int, int>, int> latest; // (cc, channel) -> latest value this frame
  2066. while (controllerQueue.pop (e))
  2067. {
  2068. if (learning.kind != AutomationTargetKind::none && learningGlobal)
  2069. {
  2070. // "Override global link...": the link goes to the settings, for every project (REA round 146)
  2071. auto p = midiPrefs;
  2072. const prefs::GlobalLink g { e.cc, e.channel, (int) learning.kind, learning.index, learning.slot, learning.param };
  2073. p.globalLinks.erase (std::remove_if (p.globalLinks.begin(), p.globalLinks.end(),
  2074. [&] (const prefs::GlobalLink& l) {
  2075. return l.kind == g.kind && l.index == g.index && l.slot == g.slot && l.param == g.param;
  2076. }),
  2077. p.globalLinks.end());
  2078. p.globalLinks.push_back (g);
  2079. learning = {};
  2080. learningGlobal = false;
  2081. setMidiPrefs (p, saveGlobalLinks);
  2082. }
  2083. else if (learning.kind != AutomationTargetKind::none)
  2084. {
  2085. // MIDI learn: replace the old link for the same target with the new one
  2086. editSong ([t = learning, e] (Song& s) {
  2087. s.midiLinks.erase (std::remove_if (s.midiLinks.begin(), s.midiLinks.end(), [&] (const MidiLink& l) { return l.target == t; }),
  2088. s.midiLinks.end());
  2089. s.midiLinks.push_back ({ e.cc, e.channel, t });
  2090. });
  2091. learning = {};
  2092. }
  2093. latest[{ e.cc, e.channel }] = e.value;
  2094. }
  2095. const auto links = linksWithGlobal (song.midiLinks, getGlobalLinks());
  2096. {
  2097. std::uint64_t bits[2] {};
  2098. for (const auto& link : links)
  2099. if (link.cc >= 0 && link.cc < 128)
  2100. bits[link.cc >> 6] |= std::uint64_t { 1 } << (link.cc & 63);
  2101. for (int w = 0; w < 2; ++w)
  2102. linkedCcs[(std::size_t) w].store (bits[w], std::memory_order_relaxed);
  2103. }
  2104. if (latest.empty() || links.empty())
  2105. return;
  2106. // one snapshot per frame, outside the undo history (like turning the knob)
  2107. std::vector<std::pair<AutomationTarget, float>> changes;
  2108. for (const auto& [key, value] : latest)
  2109. for (const auto& link : links)
  2110. if (link.cc == key.first && (link.channel < 0 || link.channel == key.second))
  2111. {
  2112. const auto v = value / 127.0f;
  2113. const auto& t = link.target;
  2114. // takeover: only parameters the song holds (a plugin's own parameters have no value to compare here)
  2115. const auto songHeld = t.kind != AutomationTargetKind::channelParam && t.kind != AutomationTargetKind::effectParam;
  2116. if (midiPrefs.pickup && songHeld)
  2117. {
  2118. auto& state = pickups[{ key.first, key.second, (int) t.kind, t.index, t.slot, t.param }];
  2119. if (! prefs::pickupUpdate (state, song.targetValue (t), v))
  2120. continue;
  2121. }
  2122. changes.push_back ({ t, v });
  2123. noteTweaked (t); // a linked controller's move is a tweak (Last tweaked, automation recording)
  2124. }
  2125. std::vector<std::pair<AutomationTarget, float>> pluginChanges;
  2126. editSong ([&] (Song& s) {
  2127. for (const auto& [target, v] : changes)
  2128. if (! s.setTargetValue (target, v))
  2129. pluginChanges.push_back ({ target, v });
  2130. }, false);
  2131. // plugin parameters live in the plugin
  2132. for (const auto& [target, v] : pluginChanges)
  2133. {
  2134. if (target.kind == AutomationTargetKind::channelParam)
  2135. {
  2136. if (auto* p = dynamic_cast<PluginInstrument*> (getChannelInstrument (target.index).get()))
  2137. p->setParameterFromUi (target.param, v);
  2138. // a MIDI Out's controls: the plugins on its port (REA_rodada133 §4)
  2139. if (target.index >= 0 && target.index < (int) song.channels.size()
  2140. && song.channels[(std::size_t) target.index].instrument == InstrumentKind::midiOut)
  2141. {
  2142. const auto port = midictl::parseMidiOut (song.channels[(std::size_t) target.index].pluginState).port;
  2143. for (int c = 0; c < (int) song.channels.size(); ++c)
  2144. if (song.channels[(std::size_t) c].instrument == InstrumentKind::plugin && song.channels[(std::size_t) c].plugin.midiInPort == port)
  2145. if (auto* p = dynamic_cast<PluginInstrument*> (getChannelInstrument (c).get()))
  2146. p->setParameterFromUi (target.param, v);
  2147. }
  2148. }
  2149. if (target.kind == AutomationTargetKind::effectParam)
  2150. if (auto* p = dynamic_cast<PluginEffect*> (getEffect (target.index, target.slot).get()))
  2151. p->setParameterFromUi (target.param, v);
  2152. }
  2153. }
  2154. void AudioEngine::timerCallback()
  2155. {
  2156. // MIDI inputs: open the enabled devices that appeared (or were not ready) and reopen the ones that came back
  2157. if (prefetcher != nullptr && ++midiCheckTicks >= 60) // every 2 s
  2158. {
  2159. midiCheckTicks = 0;
  2160. enableAllMidiInputs();
  2161. }
  2162. updateRealtimeStats();
  2163. rt::promotePending(); // Linux: real-time priority for the audio threads seen since the last tick (round 161)
  2164. applyControllers();
  2165. updateRecording();
  2166. rackExchange.collectGarbage();
  2167. // Plugins are prepared at a fixed rate; if the device changed rate, recreate them.
  2168. // A plugin whose latency changed (preset change, lookahead) requests a new PDC plan.
  2169. const auto rateChanged = std::abs (transport.sampleRate.load() - lastPublishedShape.sampleRate) > 0.5;
  2170. const auto latencies = lastPublishedShape.currentLatencies();
  2171. if (rateChanged || latencies != lastPublishedShape.latencies)
  2172. {
  2173. // (diagnostics: which unit's latency moved)
  2174. if (! rateChanged)
  2175. for (std::size_t i = 0; i < latencies.size() && i < lastPublishedShape.latencies.size(); ++i)
  2176. if (latencies[i] != lastPublishedShape.latencies[i])
  2177. {
  2178. lastLatencyChange = juce::String ((int) i) + ": " + juce::String (lastPublishedShape.latencies[i]) + " -> " + juce::String (latencies[i]);
  2179. break;
  2180. }
  2181. ++latencyRepublishes;
  2182. publishSong();
  2183. }
  2184. }
  2185. void AudioEngine::choosePreferredDriver()
  2186. {
  2187. #if JUCE_LINUX || JUCE_BSD
  2188. std::vector<std::pair<std::string, bool>> types;
  2189. for (auto* type : deviceManager.getAvailableDeviceTypes())
  2190. {
  2191. type->scanForDevices();
  2192. types.emplace_back (type->getTypeName().toStdString(), ! type->getDeviceNames (false).isEmpty());
  2193. }
  2194. const auto best = juce::String (prefs::preferredLinuxDriver (types));
  2195. if (best.isNotEmpty() && best != deviceManager.getCurrentAudioDeviceType())
  2196. {
  2197. deviceManager.setCurrentAudioDeviceType (best, true);
  2198. if (deviceManager.getCurrentAudioDevice() == nullptr) // it would not open: back to what worked
  2199. deviceManager.initialise (0, 2, nullptr, true);
  2200. }
  2201. #endif
  2202. }
  2203. void AudioEngine::chooseSafeBufferSize()
  2204. {
  2205. auto* device = deviceManager.getCurrentAudioDevice();
  2206. if (device == nullptr)
  2207. return;
  2208. std::vector<int> sizes;
  2209. for (auto b : device->getAvailableBufferSizes())
  2210. sizes.push_back (b);
  2211. const auto current = device->getCurrentBufferSizeSamples();
  2212. const auto target = prefs::safeBufferSize (sizes, current, device->getCurrentSampleRate());
  2213. if (target > 0 && target != current)
  2214. {
  2215. auto setup = deviceManager.getAudioDeviceSetup();
  2216. setup.bufferSize = target;
  2217. deviceManager.setAudioDeviceSetup (setup, true);
  2218. }
  2219. }
  2220. juce::File AudioEngine::glitchLogFile() { return PluginHost::settingsFolder().getChildFile ("audio-glitches.log"); }
  2221. void AudioEngine::updateRealtimeStats()
  2222. {
  2223. // the message thread's pulse: this 30 Hz timer arriving late means the UI is saturated
  2224. {
  2225. const auto now = juce::Time::getMillisecondCounterHiRes();
  2226. if (lastUiPulseMs > 0.0)
  2227. uiPulse.maxGapMs = juce::jmax (uiPulse.maxGapMs, now - lastUiPulseMs);
  2228. lastUiPulseMs = now;
  2229. ++uiPulse.calls;
  2230. }
  2231. // every ~2 s: the share of real time each channel / insert effect took in that window
  2232. if (rackProcessor != nullptr && juce::Time::getMillisecondCounterHiRes() - lastUnitsWindowMs >= 2000.0)
  2233. {
  2234. lastUnitsWindowMs = juce::Time::getMillisecondCounterHiRes();
  2235. auto& renderer = rackProcessor->getRenderer();
  2236. const auto& units = renderer.unitTimes();
  2237. const auto processed = units.processedSamples.load (std::memory_order_relaxed);
  2238. const auto rate = juce::jmax (1.0, transport.sampleRate.load());
  2239. const auto audioNs = (double) (processed - std::min (processed, lastProcessedSamples)) / rate * 1.0e9;
  2240. lastProcessedSamples = processed;
  2241. lastChannelNs.resize (units.channelNs.size(), 0);
  2242. lastEffectNs.resize (units.effectNs.size(), 0);
  2243. std::vector<UnitLoad> loads;
  2244. auto take = [&] (const std::atomic<std::uint64_t>& total, std::uint64_t& last, std::atomic<std::uint64_t>& longest, auto&& name) {
  2245. const auto now = total.load (std::memory_order_relaxed);
  2246. const auto delta = now - std::min (now, last);
  2247. last = now;
  2248. const auto longestNs = const_cast<std::atomic<std::uint64_t>&> (longest).exchange (0, std::memory_order_relaxed);
  2249. if (delta > 0 && audioNs > 0.0)
  2250. loads.push_back ({ name(), (double) delta / audioNs, (double) longestNs * 1.0e-6 });
  2251. };
  2252. auto& mutableUnits = const_cast<RackRenderer::UnitTimes&> (units);
  2253. for (std::size_t c = 0; c < units.channelNs.size(); ++c)
  2254. take (units.channelNs[c], lastChannelNs[c], mutableUnits.channelMaxNs[c], [&] {
  2255. return c < song.channels.size() ? juce::String::fromUTF8 (song.channels[c].name.c_str()) : "Channel " + juce::String ((int) c + 1);
  2256. });
  2257. for (std::size_t k = 0; k < units.effectNs.size(); ++k)
  2258. take (units.effectNs[k], lastEffectNs[k], mutableUnits.effectMaxNs[k], [&] {
  2259. const auto t = k / (std::size_t) maxEffectSlots, slot = k % (std::size_t) maxEffectSlots;
  2260. juce::String effect;
  2261. if (t < song.mixer.size() && slot < song.mixer[t].effects.size())
  2262. {
  2263. const auto& fx = song.mixer[t].effects[slot];
  2264. effect = juce::String::fromUTF8 (fx.plugin.name.empty() ? effectInfo (fx.kind).name : fx.plugin.name.c_str());
  2265. }
  2266. 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())
  2267. : "Insert " + juce::String ((int) t));
  2268. return track + " / " + juce::String ((int) slot + 1) + " " + effect;
  2269. });
  2270. std::sort (loads.begin(), loads.end(), [] (const UnitLoad& a, const UnitLoad& b) { return a.load > b.load; });
  2271. if (loads.size() > 8)
  2272. loads.resize (8);
  2273. if (audioNs > 0.0)
  2274. heaviestUnits = std::move (loads);
  2275. }
  2276. // a line in the glitch log when callbacks ran over their deadline or the device called late
  2277. const auto stats = rtStats.snapshot();
  2278. if ((stats.overBudget > loggedOver || stats.lateCalls > loggedLate) && juce::Time::getMillisecondCounterHiRes() - lastLogMs > 2000.0)
  2279. {
  2280. const auto file = glitchLogFile();
  2281. if (file.getSize() > 1024 * 1024)
  2282. file.moveFileTo (file.withFileExtension ("old.log"));
  2283. const auto bar = transport.positionTicks.load() / (double) (ppq * juce::jmax (1, song.beatsPerBar)) + 1.0;
  2284. file.appendText (juce::Time::getCurrentTime().formatted ("%Y-%m-%d %H:%M:%S") + " over deadline +" + juce::String ((juce::int64) (stats.overBudget - loggedOver))
  2285. + ", late calls +" + juce::String ((juce::int64) (stats.lateCalls - loggedLate)) + ", at bar " + juce::String (bar, 2)
  2286. + (transport.playing.load() ? "" : " (stopped)") + "\n" + describeRealtime() + "\n",
  2287. false, false, "\r\n");
  2288. loggedOver = stats.overBudget;
  2289. loggedLate = stats.lateCalls;
  2290. lastLogMs = juce::Time::getMillisecondCounterHiRes();
  2291. }
  2292. }
  2293. juce::String AudioEngine::describeRealtime (bool withUnits) const
  2294. {
  2295. juce::String text;
  2296. if (auto* device = const_cast<juce::AudioDeviceManager&> (deviceManager).getCurrentAudioDevice())
  2297. {
  2298. const auto rate = device->getCurrentSampleRate();
  2299. const auto buffer = device->getCurrentBufferSizeSamples();
  2300. text << " device: " << device->getTypeName() << " / " << device->getName() << ", " << (int) rate << " Hz, buffer " << buffer
  2301. << " samples (deadline " << juce::String (prefs::bufferLatencyMs (buffer, rate), 2) << " ms), output latency "
  2302. << device->getOutputLatencyInSamples() << " samples, driver dropouts " << device->getXRunCount() << "\n";
  2303. #if JUCE_LINUX
  2304. text << " audio thread: " << (rt::status() == rt::Status::unknown ? juce::String ("not seen yet") : rt::describe()) << "\n";
  2305. #endif
  2306. }
  2307. else
  2308. text << " device: none\n";
  2309. const auto s = rtStats.snapshot();
  2310. text << " callbacks " << (juce::int64) s.callbacks << ": over deadline " << (juce::int64) s.overBudget << ", 80-100% " << (juce::int64) s.nearBudget
  2311. << ", late device calls " << (juce::int64) s.lateCalls << ", average load " << juce::String (s.averageLoad * 100.0, 1) << "%, max "
  2312. << juce::String (s.maxLoad * 100.0, 0) << "%, workers " << (workers != nullptr ? workers->workers() : 0) << "\n";
  2313. if (latencyRepublishes > 0)
  2314. text << " latency changes re-planned PDC " << latencyRepublishes << " times (last: unit " << lastLatencyChange << ")\n";
  2315. if (withUnits && heaviestUnits.empty())
  2316. text << " heaviest: not measured yet\n";
  2317. if (withUnits && ! heaviestUnits.empty())
  2318. {
  2319. text << " heaviest:";
  2320. for (std::size_t i = 0; i < heaviestUnits.size() && i < 5; ++i)
  2321. text << (i > 0 ? ";" : "") << " " << heaviestUnits[i].name << " " << juce::String (heaviestUnits[i].load * 100.0, 1) << "% (peak "
  2322. << juce::String (heaviestUnits[i].longestMs, 1) << " ms)";
  2323. text << "\n";
  2324. }
  2325. return text;
  2326. }
  2327. std::shared_ptr<Instrument> AudioEngine::getChannelInstrument (int channel) const
  2328. {
  2329. if (channel < 0 || channel >= (int) lastPublishedShape.instruments.size())
  2330. return nullptr;
  2331. return lastPublishedShape.instruments[(std::size_t) channel];
  2332. }
  2333. std::shared_ptr<Effect> AudioEngine::getEffect (int track, int slot) const
  2334. {
  2335. const auto& effects = lastPublishedShape.effects;
  2336. if (track < 0 || track >= (int) effects.size() || slot < 0 || slot >= (int) effects[(std::size_t) track].size())
  2337. return nullptr;
  2338. return effects[(std::size_t) track][(std::size_t) slot];
  2339. }
  2340. void AudioEngine::setPluginsRenderMode (bool offline)
  2341. {
  2342. // FL's "Notify about rendering mode" off: that plugin is not told (round 149); "Reset plugin when FL Studio
  2343. // resets": reset as the export starts (round 151)
  2344. for (std::size_t i = 0; i < song.channels.size(); ++i)
  2345. if (auto* p = dynamic_cast<PluginInstrument*> (getChannelInstrument ((int) i).get()))
  2346. {
  2347. if (song.channels[i].plugin.notifyRender)
  2348. p->setRenderMode (offline);
  2349. if (offline)
  2350. p->resetForExport();
  2351. }
  2352. for (std::size_t t = 0; t < song.mixer.size(); ++t)
  2353. for (std::size_t s = 0; s < song.mixer[t].effects.size(); ++s)
  2354. if (auto* p = dynamic_cast<PluginEffect*> (getEffect ((int) t, (int) s).get()))
  2355. {
  2356. if (song.mixer[t].effects[s].plugin.notifyRender)
  2357. p->setRenderMode (offline);
  2358. if (offline)
  2359. p->resetForExport();
  2360. }
  2361. // the plugins inside Patchers (REA_rodada141)
  2362. std::function<void (patcher::Graph*)> graphMode = [&] (patcher::Graph* graph) {
  2363. if (graph == nullptr)
  2364. return;
  2365. for (int n = 0; n < graph->nodeCount(); ++n)
  2366. {
  2367. auto effect = graph->effectAt (n);
  2368. auto instrument = graph->instrumentAt (n);
  2369. if (auto* p = dynamic_cast<PluginEffect*> (effect.get()))
  2370. p->setRenderMode (offline);
  2371. if (auto* p = dynamic_cast<PluginInstrument*> (instrument.get()))
  2372. p->setRenderMode (offline);
  2373. graphMode (patcher::graphOf (effect.get()));
  2374. graphMode (patcher::graphOf (instrument.get()));
  2375. }
  2376. };
  2377. for (std::size_t i = 0; i < song.channels.size(); ++i)
  2378. graphMode (patcher::graphOf (getChannelInstrument ((int) i).get()));
  2379. for (std::size_t t = 0; t < song.mixer.size(); ++t)
  2380. for (std::size_t s = 0; s < song.mixer[t].effects.size(); ++s)
  2381. graphMode (patcher::graphOf (getEffect ((int) t, (int) s).get()));
  2382. }
  2383. void AudioEngine::capturePluginStates()
  2384. {
  2385. // Changes only the saved state (recreates nothing and doesn't enter the undo history).
  2386. for (std::size_t i = 0; i < song.channels.size(); ++i)
  2387. if (auto* p = dynamic_cast<PluginInstrument*> (getChannelInstrument ((int) i).get()))
  2388. if (auto state = p->captureState()) // (a plugin that crashed keeps the state saved before)
  2389. song.channels[i].plugin.state = std::move (*state);
  2390. for (std::size_t t = 0; t < song.mixer.size(); ++t)
  2391. for (std::size_t s = 0; s < song.mixer[t].effects.size(); ++s)
  2392. if (auto* p = dynamic_cast<PluginEffect*> (getEffect ((int) t, (int) s).get()))
  2393. if (auto state = p->captureState())
  2394. song.mixer[t].effects[s].plugin.state = std::move (*state);
  2395. // the plugins inside Patchers (REA_rodada141), nested ones too
  2396. std::function<void (PatcherDoc&, patcher::Graph*)> captureGraph = [&] (PatcherDoc& doc, patcher::Graph* graph) {
  2397. if (graph == nullptr)
  2398. return;
  2399. for (int n = 0; n < (int) doc.nodes.size() && n < graph->nodeCount(); ++n)
  2400. {
  2401. auto& node = doc.nodes[(std::size_t) n];
  2402. if (node.generator)
  2403. {
  2404. auto instrument = graph->instrumentAt (n);
  2405. if (auto* p = dynamic_cast<PluginInstrument*> (instrument.get()))
  2406. if (auto state = p->captureState())
  2407. node.channel.plugin.state = std::move (*state);
  2408. if (node.channel.instrument == InstrumentKind::patcher)
  2409. captureGraph (node.channel.patcher, patcher::graphOf (instrument.get()));
  2410. }
  2411. else
  2412. {
  2413. auto effect = graph->effectAt (n);
  2414. if (auto* p = dynamic_cast<PluginEffect*> (effect.get()))
  2415. if (auto state = p->captureState())
  2416. node.effect.plugin.state = std::move (*state);
  2417. if (node.effect.kind == EffectKind::patcher)
  2418. captureGraph (node.effect.patcher, patcher::graphOf (effect.get()));
  2419. }
  2420. }
  2421. };
  2422. for (std::size_t i = 0; i < song.channels.size(); ++i)
  2423. if (song.channels[i].instrument == InstrumentKind::patcher)
  2424. captureGraph (song.channels[i].patcher, patcher::graphOf (getChannelInstrument ((int) i).get()));
  2425. for (std::size_t t = 0; t < song.mixer.size(); ++t)
  2426. for (std::size_t s = 0; s < song.mixer[t].effects.size(); ++s)
  2427. if (song.mixer[t].effects[s].kind == EffectKind::patcher)
  2428. captureGraph (song.mixer[t].effects[s].patcher, patcher::graphOf (getEffect ((int) t, (int) s).get()));
  2429. lastPublishedShape.song.channels = song.channels;
  2430. lastPublishedShape.song.mixer = song.mixer;
  2431. }
  2432. void AudioEngine::audioDeviceIOCallbackWithContext (const float* const* inputChannelData,
  2433. int numInputChannels,
  2434. float* const* outputChannelData,
  2435. int numOutputChannels,
  2436. int numSamples,
  2437. const juce::AudioIODeviceCallbackContext& context)
  2438. {
  2439. // FTZ/DAZ for the whole callback (round 160): the rack had it, but the metronome, the preview player and the
  2440. // hosted plugins' graph nodes around it ran without
  2441. const ScopedFlushDenormals noDenormals;
  2442. rt::noteAudioThread(); // Linux: the message thread asks for real-time priority for this thread once
  2443. // real-time health: how long this callback took against its deadline (the buffer's duration)
  2444. const auto callbackStart = juce::Time::getMillisecondCounterHiRes();
  2445. struct Measure
  2446. {
  2447. ~Measure()
  2448. {
  2449. const auto rate = engine.transport.sampleRate.load (std::memory_order_relaxed);
  2450. if (rate > 0.0)
  2451. engine.rtStats.record (start, juce::Time::getMillisecondCounterHiRes() - start, 1000.0 * samples / rate);
  2452. }
  2453. AudioEngine& engine;
  2454. double start;
  2455. int samples;
  2456. } measure { *this, callbackStart, numSamples };
  2457. if (transport.rewindRequested.exchange (false))
  2458. transport.positionTicks.store (0.0);
  2459. if (const auto target = transport.seekRequest.exchange (-1.0); target >= 0.0)
  2460. transport.positionTicks.store (target);
  2461. // With the loop region on, the block is split at the loop end and the position jumps back to
  2462. // its start (the nodes see a jump and release their notes, as in FL).
  2463. // the audio editor's input recording (nothing happens unless it chose the input)
  2464. meters.capture.push (AudioCapture::input, numInputChannels > 0 ? inputChannelData[0] : nullptr, numInputChannels > 1 ? inputChannelData[1] : nullptr,
  2465. numSamples);
  2466. std::array<const float*, 64> inputs {};
  2467. std::array<float*, 64> outputs {};
  2468. numInputChannels = juce::jmin (numInputChannels, (int) inputs.size());
  2469. numOutputChannels = juce::jmin (numOutputChannels, (int) outputs.size());
  2470. // count-in: the metronome counts the pre-roll down, then playback starts
  2471. if (const auto countIn = transport.countIn.load (std::memory_order_relaxed); countIn > 0.0 && ! transport.playing.load (std::memory_order_relaxed))
  2472. {
  2473. const auto left = countIn - numSamples * transport.ticksPerSample();
  2474. transport.countIn.store (juce::jmax (0.0, left), std::memory_order_relaxed);
  2475. if (left <= 0.0)
  2476. transport.playing.store (true, std::memory_order_relaxed);
  2477. }
  2478. for (int done = 0; done < numSamples;)
  2479. {
  2480. auto n = numSamples - done;
  2481. const auto playing = transport.playing.load (std::memory_order_relaxed);
  2482. const auto tps = transport.ticksPerSample();
  2483. // Song mode: the loop region, or else the whole song (back to the start at its end, like FL)
  2484. const auto loop = playbackLoop (transport.songMode.load (std::memory_order_relaxed), transport.loopStart.load (std::memory_order_relaxed),
  2485. transport.loopEnd.load (std::memory_order_relaxed), transport.songEnd.load (std::memory_order_relaxed));
  2486. const auto loopStart = loop.start, loopEnd = loop.end;
  2487. const auto looping = playing && loop.active() && tps > 0.0;
  2488. if (looping)
  2489. {
  2490. // before the loop, play normally until reaching it; past the end, jump back to the start
  2491. auto position = transport.positionTicks.load (std::memory_order_relaxed);
  2492. if (position >= loopEnd)
  2493. {
  2494. position = loopStart;
  2495. transport.positionTicks.store (position, std::memory_order_relaxed);
  2496. }
  2497. n = juce::jlimit (1, n, (int) std::ceil ((loopEnd - position) / tps));
  2498. }
  2499. for (int ch = 0; ch < numInputChannels; ++ch)
  2500. inputs[(std::size_t) ch] = inputChannelData[ch] != nullptr ? inputChannelData[ch] + done : nullptr;
  2501. // the block's input by device channel, for the inserts (monitoring, meters) and the takes
  2502. liveInput.numChannels = 0;
  2503. for (int c = 0; c < LiveInput::maxChannels; ++c)
  2504. {
  2505. const auto slot = inputSlot[(std::size_t) c];
  2506. liveInput.channels[(std::size_t) c] = slot >= 0 && slot < numInputChannels ? inputs[(std::size_t) slot] : nullptr;
  2507. if (liveInput.channels[(std::size_t) c] != nullptr)
  2508. liveInput.numChannels = c + 1;
  2509. }
  2510. // audio recording: this block's input goes to disk (without waiting on a lock)
  2511. if (playing && transport.recording.load (std::memory_order_relaxed))
  2512. {
  2513. const juce::SpinLock::ScopedTryLockType lock (takeLock);
  2514. if (lock.isLocked() && takeCount > 0)
  2515. {
  2516. auto wrote = false;
  2517. for (int k = 0; k < takeCount; ++k)
  2518. {
  2519. auto& take = takes[(std::size_t) k];
  2520. const std::array<const float*, 2> data { liveInput.channel (take.first, 0), liveInput.channel (take.first + take.channels - 1, 0) };
  2521. if (data[0] == nullptr || data[1] == nullptr || take.writer == nullptr)
  2522. continue;
  2523. wrote = take.writer->write (data.data(), n) || wrote;
  2524. }
  2525. if (wrote)
  2526. {
  2527. if (takeStartTick.load (std::memory_order_relaxed) < 0.0)
  2528. takeStartTick.store (transport.positionTicks.load (std::memory_order_relaxed));
  2529. takeFrames.fetch_add (n, std::memory_order_relaxed);
  2530. }
  2531. }
  2532. }
  2533. for (int ch = 0; ch < numOutputChannels; ++ch)
  2534. outputs[(std::size_t) ch] = outputChannelData[ch] != nullptr ? outputChannelData[ch] + done : nullptr;
  2535. player.audioDeviceIOCallbackWithContext (inputs.data(), numInputChannels, outputs.data(), numOutputChannels, n, context);
  2536. routeOutputs (outputs.data(), numOutputChannels, n);
  2537. for (int ch = 0; ch < numOutputChannels; ++ch)
  2538. if (outputs[(std::size_t) ch] != nullptr)
  2539. clipOvers (outputs[(std::size_t) ch], n);
  2540. // oscilloscope: average of both sides into the ring buffer
  2541. if (numOutputChannels > 0 && outputs[0] != nullptr)
  2542. {
  2543. auto w = scopeWrite.load (std::memory_order_relaxed);
  2544. const auto* right = numOutputChannels > 1 && outputs[1] != nullptr ? outputs[1] : outputs[0];
  2545. for (int i = 0; i < n; ++i)
  2546. {
  2547. scope[(std::size_t) w].store (0.5f * (outputs[0][i] + right[i]), std::memory_order_relaxed);
  2548. w = (w + 1) % scopeSize;
  2549. }
  2550. scopeWrite.store (w, std::memory_order_release);
  2551. }
  2552. if (playing)
  2553. {
  2554. auto position = transport.positionTicks.load (std::memory_order_relaxed) + n * tps;
  2555. if (looping && position >= loopEnd - 1e-6)
  2556. position = loopStart;
  2557. transport.positionTicks.store (position, std::memory_order_relaxed);
  2558. }
  2559. done += n;
  2560. }
  2561. // the block is done: the workers sleep until the next one instead of spinning (REA round 116)
  2562. if (workers != nullptr)
  2563. workers->park();
  2564. blockTimeMs.store (juce::Time::getMillisecondCounterHiRes(), std::memory_order_relaxed);
  2565. }
  2566. void AudioEngine::audioDeviceAboutToStart (juce::AudioIODevice* device)
  2567. {
  2568. rtStats.deviceRestarted();
  2569. rt::resetForNewDevice();
  2570. transport.sampleRate.store (device->getCurrentSampleRate());
  2571. // FL's fixed size buffers: 2 ms, or the device buffer with "Process maximum size buffers" (REA round 134)
  2572. setFixedPluginBlock (device->getCurrentBufferSizeSamples(), device->getCurrentSampleRate());
  2573. // the callback gets the open input channels only, in order: map device channel -> callback index
  2574. const auto active = device->getActiveInputChannels();
  2575. int slot = 0;
  2576. for (int c = 0; c < LiveInput::maxChannels; ++c)
  2577. inputSlot[(std::size_t) c] = active[c] ? slot++ : -1;
  2578. // the same for the outputs (hardware output targets, REA round 156)
  2579. const auto activeOut = device->getActiveOutputChannels();
  2580. slot = 0;
  2581. for (int c = 0; c < HardwareOutput::maxChannels; ++c)
  2582. outputSlot[(std::size_t) c] = activeOut[c] ? slot++ : -1;
  2583. hwOutput.clear();
  2584. hwOutput.active.store (true);
  2585. player.audioDeviceAboutToStart (device);
  2586. }
  2587. void AudioEngine::audioDeviceStopped()
  2588. {
  2589. hwOutput.active.store (false);
  2590. player.audioDeviceStopped();
  2591. }
  2592. // The Master's own target (its default: the graph's output as it is, on the first open pair) and the inserts'
  2593. // hardware outputs, added into the device channels they chose. A channel that is not open drops its sound.
  2594. void AudioEngine::routeOutputs (float* const* outputs, int numOutputs, int n) noexcept
  2595. {
  2596. const auto slotOf = [this] (int c) { return c >= 0 && c < HardwareOutput::maxChannels ? outputSlot[(std::size_t) c] : -1; };
  2597. if (const auto channel = masterOutChannel.load (std::memory_order_relaxed); channel != outputDefault && numOutputs > 0 && n <= HardwareOutput::capacity)
  2598. {
  2599. auto* l = masterScratch.data();
  2600. auto* r = masterScratch.data() + HardwareOutput::capacity;
  2601. const auto* srcR = numOutputs > 1 && outputs[1] != nullptr ? outputs[1] : outputs[0];
  2602. if (outputs[0] == nullptr)
  2603. return;
  2604. std::copy (outputs[0], outputs[0] + n, l);
  2605. std::copy (srcR, srcR + n, r);
  2606. for (int k = 0; k < std::min (numOutputs, 2); ++k)
  2607. if (outputs[k] != nullptr)
  2608. std::fill (outputs[k], outputs[k] + n, 0.0f);
  2609. const auto mode = (OutputMode) masterOutMode.load (std::memory_order_relaxed);
  2610. const auto [first, count] = outputChannelsOf (channel, mode);
  2611. if (count > 0)
  2612. {
  2613. const auto a = slotOf (first), b = count > 1 ? slotOf (first + 1) : -1;
  2614. if (a >= 0 && a < numOutputs)
  2615. addToOutput (l, r, mode, outputs[a], b >= 0 && b < numOutputs ? outputs[b] : nullptr, n);
  2616. }
  2617. }
  2618. hwOutput.drainInto (outputs, numOutputs, slotOf, n);
  2619. }
  2620. std::vector<std::string> AudioEngine::getOutputChannelNames() const
  2621. {
  2622. std::vector<std::string> names;
  2623. if (auto* device = deviceManager.getCurrentAudioDevice(); device != nullptr)
  2624. for (const auto& n : device->getOutputChannelNames())
  2625. if ((int) names.size() < HardwareOutput::maxChannels)
  2626. names.push_back (n.toStdString());
  2627. return names;
  2628. }
  2629. bool AudioEngine::isOutputChannelOpen (int channel) const
  2630. {
  2631. auto* device = deviceManager.getCurrentAudioDevice();
  2632. return device != nullptr && channel >= 0 && device->getActiveOutputChannels()[channel];
  2633. }
  2634. void AudioEngine::setTrackOutput (int track, int channel, OutputMode mode)
  2635. {
  2636. if (track < 0 || track >= (int) song.mixer.size())
  2637. return;
  2638. if (track > 0 && channel < 0) // an insert without a target: the default (the Master only), nothing saved
  2639. channel = outputDefault;
  2640. editSong ([=] (Song& s) {
  2641. s.mixer[(std::size_t) track].outputChannel = channel;
  2642. s.mixer[(std::size_t) track].outputMode = mode;
  2643. });
  2644. openTargetedOutputs();
  2645. }
  2646. void AudioEngine::openTargetedOutputs()
  2647. {
  2648. auto* device = deviceManager.getCurrentAudioDevice();
  2649. if (device == nullptr)
  2650. return;
  2651. const auto available = juce::jmin ((int) HardwareOutput::maxChannels, device->getOutputChannelNames().size());
  2652. auto setup = deviceManager.getAudioDeviceSetup();
  2653. auto wanted = device->getActiveOutputChannels();
  2654. const auto before = wanted;
  2655. for (const auto& t : song.mixer)
  2656. {
  2657. const auto [first, count] = outputChannelsOf (t.outputChannel, t.outputMode);
  2658. for (int c = first; c < first + count; ++c)
  2659. if (c < available)
  2660. wanted.setBit (c);
  2661. }
  2662. if (wanted == before)
  2663. return;
  2664. setup.useDefaultOutputChannels = false;
  2665. setup.outputChannels = wanted;
  2666. deviceManager.setAudioDeviceSetup (setup, true);
  2667. sendChangeMessage();
  2668. }
  2669. } // namespace lynx