AudioEngine.cpp 143 KB

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