AudioEngine.cpp 146 KB

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