AudioEngine.cpp 147 KB

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