AudioEngine.h 151 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156
  1. #pragma once
  2. #include "engine/DllAsioDevice.h"
  3. #include <array>
  4. #include <optional>
  5. #include <deque>
  6. #include <map>
  7. #include <mutex>
  8. #include <tuple>
  9. #include <utility>
  10. #include <functional>
  11. #include <juce_audio_utils/juce_audio_utils.h>
  12. #include "core/UndoNames.h"
  13. #include "core/StretchDefer.h" // round 190un
  14. #include "core/LinkFormula.h"
  15. #include "core/Multilink.h"
  16. #include "core/RemoteMap.h"
  17. #include "core/AutomationDisplay.h"
  18. #include "core/HeldNotes.h"
  19. #include "core/Mpe.h"
  20. #include "core/RecordLoop.h"
  21. #include "core/StepEdit.h"
  22. #include "core/Preferences.h"
  23. #include "core/LiveEventQueue.h"
  24. #include "core/LiveInput.h"
  25. #include "core/VisualFx.h"
  26. #include "core/HardwareOutput.h"
  27. #include "core/LiveRecordView.h"
  28. #include "core/Recorder.h"
  29. #include "core/CaptureAutomation.h"
  30. #include "core/PedalHold.h"
  31. #include "core/TakeRecording.h"
  32. #include "core/WorkerPool.h"
  33. #include "core/SerialJobs.h"
  34. #include "core/PreviewTempo.h"
  35. #include "engine/MidiSyncIo.h"
  36. #include "engine/AbletonLink.h"
  37. #include "engine/ControllerIo.h"
  38. #include "core/RackRenderer.h"
  39. #include "engine/AraHost.h"
  40. #include "core/RenderAhead.h"
  41. #include "core/RtStats.h"
  42. #include "core/OverloadGuard.h"
  43. #include "core/Dropouts.h"
  44. #include "core/DeviceLoss.h"
  45. #include "core/ScoreLog.h"
  46. #include "core/FlpImport.h"
  47. #include "core/History.h"
  48. #include "core/NativeEngines.h"
  49. #include "core/PluginWarmup.h"
  50. #include "core/SnapshotExchange.h"
  51. #include "core/Song.h"
  52. #include "engine/PluginHost.h"
  53. #include "engine/RenderStream.h"
  54. #include "engine/SampleLibrary.h"
  55. #include "engine/StreamPrefetcher.h"
  56. #include "engine/Transport.h"
  57. namespace lynx
  58. {
  59. class AudioLogger;
  60. // Owns the audio device, the processing graph and the document (Song).
  61. // Sits between the driver and the AudioProcessorPlayer to advance the transport
  62. // after each block, so every node sees the same start position.
  63. //
  64. // The Song is touched only by the UI thread; each edit publishes an immutable
  65. // snapshot (RackState) to the audio thread.
  66. // Folders of the most recent FL Studio installation (empty if none).
  67. FlPathRoots findFlStudioRoots (int waitMs = -1); // (ms to wait for a slow drive; −1 = findFlStudio's own)
  68. // The user's FL installation as the native FL engines read it (round 142): its folders and this PC's file system
  69. const natives::FlAccess& flStudioAccess(); // (found once, and again after refreshFlStudioAccess)
  70. // Settings › Files › FL Studio folder changed: the next flStudioAccess() is the new installation. References taken before
  71. // stay valid (and keep the old one).
  72. void refreshFlStudioAccess();
  73. // Start-up trace hook (round 165i): Main's LYNX_TRACE_STARTUP log receives the engine's own steps (null: off)
  74. inline void (*startupMark) (const char* step) = nullptr;
  75. class AudioEngine final : private juce::AudioIODeviceCallback,
  76. private juce::MidiInputCallback,
  77. public juce::ChangeBroadcaster,
  78. private juce::Timer
  79. {
  80. public:
  81. // workerThreads: extra audio threads (< 0 = by the CPU's cores). An engine that only serves an editor needs none.
  82. // userPluginList = false: the plugin host neither reads nor writes LYNX's plugin list and settings, nor reads FL's
  83. // plugin database in the background (round 180b: an editor inside another host must not, and its close must not
  84. // wait for that reader)
  85. // deferDeviceOpen (round 190go, the app's start): the engine is ready to play but opens no device, MIDI port or
  86. // prefetcher until openAudioDevice() / openMidiDevices() (the main window is built first). Until then it behaves
  87. // like an engine without a device; play pressed meanwhile starts with the device.
  88. explicit AudioEngine (bool openAudioDevice = true, int workerThreads = -1, bool userPluginList = true, bool deferDeviceOpen = false);
  89. // The audio device of the last session (else the default) and the parts that live with it: the device types,
  90. // the audio callback, the saved-setup watcher and the stream prefetcher; then the project's inputs, hardware
  91. // outputs and inserts open on it (what opening a project does). Message thread (JUCE's ASIO type wants one thread
  92. // for a driver's whole life). Does nothing when it is open already or the engine has no device.
  93. void openAudioDevice();
  94. // The MIDI inputs and the MIDI sync outputs (FL's MIDI settings). Message thread; once.
  95. void openMidiDevices();
  96. bool isAudioDeviceOpenPending() const noexcept { return devicePending; }
  97. // Windows (round 190go): the ASIO device of the last session is made and opened on a worker thread now (the
  98. // driver itself on JUCE's ASIO thread, cmake/LynxPatchJuce.cmake fix 29); openAudioDevice() then takes it. Making
  99. // and opening it took ~0.8 s of the start's critical path. Elsewhere, or for another device type: nothing.
  100. static void prewarmAudioDevice();
  101. // Round 190rp (crash reports since 0.1.31.2, group G1: one Windows machine hung at every start inside its ASIO
  102. // driver's open, 6 starts in a row): openAudioDevice notes "opening the audio device <type>: <name>" in the session
  103. // file before the saved device opens and "audio device opened" after. When the last session ended inside that open
  104. // (Main.cpp reads its steps), this start skips the saved device (no prewarm either), opens the default one, saves
  105. // that as the setup and the start-up notice says why. Set before prewarmAudioDevice / openAudioDevice.
  106. static inline bool skipSavedDevice = false;
  107. // the session step written before the saved device opens (Main.cpp looks for it)
  108. static constexpr const char* openingDeviceStep = "opening the audio device ";
  109. // Round 180b (LYNX's plugins in another host): this engine plays nothing, it serves an editor whose audio runs in the
  110. // plugin's own renderer. The editor's displays read that renderer's times and tap, and its running effect.
  111. void setExternalRuntime (ProcessTimes* times, std::function<std::shared_ptr<Effect>()> effect)
  112. {
  113. externalTimes = times;
  114. externalEffect = std::move (effect);
  115. }
  116. ~AudioEngine() override;
  117. juce::AudioDeviceManager& getDeviceManager() noexcept { return deviceManager; }
  118. Transport& getTransport() noexcept { return transport; }
  119. const Transport& getTransport() const noexcept { return transport; }
  120. // The Song-mode playhead for the UI: the position folded into the song (its end goes back to the start), except
  121. // while the song plays on past its end (a Song-mode recording without a loop region, FL [EXEC] round 168k: the
  122. // counter reads 8:08 after recording a 1-bar song from bar 1; a bounce) or with a loop region
  123. double songPlayheadTicks() const noexcept;
  124. // Round 174e: how far the playhead has moved since the last audio block, for screens drawing faster than the blocks
  125. // come (144 Hz against 256-sample blocks, or larger buffers): the time since that block at its tempo, never more
  126. // than one block (so the next block's position is never passed: the playhead only moves forward). 0 when stopped.
  127. double playheadAdvanceTicks() const noexcept;
  128. SampleLibrary& getSampleLibrary() noexcept { return samples; }
  129. // An audio clip's own audio through its channel's instrument (core renderClipAudio), at the engine's sample rate, with
  130. // the samples, stretches and plugins the rack uses (round 189l, Make unique as sample). UI thread.
  131. ClipAudio renderClipAudio (std::size_t clipIndex);
  132. // Round 190ey (live check 190ew PL-3): the Playlist clip menu's Preview as FL plays it — the clip through its own
  133. // channel, so its mixer insert's effects and meter, from the clip's start to its end (core audioClipNote on the live
  134. // note queue). Transport start / stop end it, as does the next preview. False: no audio clip there. UI thread.
  135. bool previewClipThroughChannel (std::size_t clipIndex);
  136. void stopClipPreview() noexcept;
  137. bool isClipPreviewing() const noexcept { return clipPreviewKey >= 0; }
  138. MeterBank& getMeters() noexcept { return meters; }
  139. // Tools > Audio logger (REA round 153): records everything the Master plays to a WAV in the background.
  140. AudioLogger& getAudioLogger();
  141. PluginHost& getPluginHost() noexcept { return plugins; }
  142. // ARA 2 (round 190kx, engine/AraHost.h): the host of the audio clip channels edited in an ARA plugin; nullptr until the
  143. // song first has one (no ARA plugin, no document, no CPU before that). Message thread.
  144. AraHost* getAraHost() noexcept { return araHost.get(); }
  145. // Edits channel `channel` (an audio clip channel) in the ARA plugin `pluginId` (empty: back to its sampler), one undo
  146. // step. False: not an audio clip channel. The plugin's editor opens with AraHost::pluginOf afterwards.
  147. bool setChannelAra (int channel, const std::string& pluginId, const std::string& pluginName);
  148. // The ARA host brought in line with the song again (a channel whose plugin or sample was not ready is tried again)
  149. void refreshAra() { publishSong(); }
  150. // Online Sessions (round 168a): the channels / inserts whose third-party plugin is missing here and that play their
  151. // stand-in render instead (core/StandIns.h), as of the last publish — the Channel Rack and the Mixer badge them.
  152. bool playsStandIn (int channel) const noexcept
  153. {
  154. return std::find (standInChannels.begin(), standInChannels.end(), channel) != standInChannels.end();
  155. }
  156. bool insertPlaysStandIn (int track) const noexcept
  157. {
  158. return std::find (standInInserts.begin(), standInInserts.end(), track) != standInInserts.end();
  159. }
  160. // Freeze (round 190ay, core/StandIns.h lynx::freeze): a frozen channel plays its rendered audio and its instrument is
  161. // not loaded. frozenAudioMissing: its audio is not on disk (as of the last publish), so it plays its instrument
  162. // instead — never silence. freezeOutOfDate: the notes, tempo or arrangement it was rendered from changed since
  163. // (worked out on demand, once per edit of the song). Where the audio goes: next to the project's recordings. UI thread.
  164. bool frozenAudioMissing (int channel) const noexcept
  165. {
  166. return std::find (frozenMissing.begin(), frozenMissing.end(), channel) != frozenMissing.end();
  167. }
  168. bool freezeOutOfDate (int channel);
  169. // Frees now what the engine retired (the racks replaced by an edit, with the instruments and hosted plugin
  170. // instances only they still held) instead of on the next message: for the command-line modes, which run without
  171. // a message loop, before they measure memory or count plugin instances. Message thread.
  172. void freeRetiredRacks()
  173. {
  174. rackExchange.collectGarbage();
  175. rackDisposer.flush();
  176. }
  177. juce::File getFreezeFolder() const { return recordingFolder.getSiblingFile ("Frozen"); }
  178. // Third-party plugins from the last imported .flp that were not found among the scanned ones.
  179. const juce::StringArray& getMissingPlugins() const noexcept { return missingPlugins; }
  180. // "plugin → file (how it was found)" for the plugins of the last imported .flp
  181. const juce::StringArray& getMatchedPlugins() const noexcept { return matchedPlugins; }
  182. // plugins found whose saved settings could not be carried over (VST2 <-> VST3): "name (format)"
  183. const juce::StringArray& getPluginsWithoutState() const noexcept { return pluginsWithoutState; }
  184. // What the last imported .flp converted, approximated or left out.
  185. const FlpImportReport& getImportReport() const noexcept { return importReport; }
  186. // The last imported .flp's plugins that were not found, with what uses them and what LYNX put in their place.
  187. const std::vector<MissingPlugin>& getMissingPluginDetails() const noexcept { return missingPluginDetails; }
  188. // Live instances (to open the plugin window). nullptr if not a plugin.
  189. std::shared_ptr<Instrument> getChannelInstrument (int channel) const;
  190. std::shared_ptr<Effect> getEffect (int track, int slot) const;
  191. // Copies the plugins' current state into the Song (before saving).
  192. // Remote snapshots capture into a copy and do not change working time, history or revision.
  193. Song snapshotForRemoteControl();
  194. juce::String remoteDeviceStateHash();
  195. // Stage and validate a complete edit before one native history step. Playback must be stopped.
  196. bool editSongRemoteTransaction (const std::function<void (Song&)>& stage, const std::function<bool()>& cancelled = {}, bool preserveRuntimeIdentity = false);
  197. void undoRemoteControl (const std::function<bool()>& cancelled = {});
  198. void redoRemoteControl (const std::function<bool()>& cancelled = {});
  199. juce::String getRemoteHistoryError() const { return remoteHistoryError; }
  200. void capturePluginStates(); // (before every save: also adds the working time so far, see stampWorkTime)
  201. // Round 190ua (issue #370): mixer slot `slot` of insert `track` with its running plugin's state as it is now (a hosted
  202. // plugin's chunk, in-process or in a separate process; the plugins inside a Patcher too), as a save would write it;
  203. // the song is not changed. nullopt: no such slot.
  204. std::optional<EffectSlot> liveEffectSlot (int track, int slot);
  205. // Edison slots (round 190cd, core/EdisonFx.h): audio that changed since it was last written goes to a new WAV in
  206. // the recording folder and the slot points at it (not an undo step). Called after a take, when an Edison window
  207. // closes and before every save. UI thread.
  208. void flushEdisonAudio();
  209. // Recordings into Edison slots go on while their windows are closed (as FL's plugin does): this moves what the
  210. // audio thread recorded into the takes (the engine's timer calls it) and flushes a take that ended by itself.
  211. void pumpEdisonRecordings();
  212. // Round 190gk: slots a Gross Beat picked from MIDI notes become its Time slot / Volume slot parameters, as FL's
  213. // click does (not an undo step); the engine's timer calls it.
  214. void pumpGrossBeatPicks();
  215. // Round 190ao (Bitwig's "Reload plug-in"): a hosted plugin of a channel (track < 0) or a mixer slot that is down:
  216. // it crashed inside a call and was switched off, or its separate process died or stopped responding.
  217. struct HostedSlot
  218. {
  219. int channel = -1, track = -1, slot = -1;
  220. bool operator== (const HostedSlot& o) const noexcept { return channel == o.channel && track == o.track && slot == o.slot; }
  221. };
  222. bool hostedPluginDown (HostedSlot where) const;
  223. // The plugins that are down (channels first); `named`: only the ones with that PluginRef name.
  224. std::vector<HostedSlot> downHostedPlugins (const std::string& named = {}) const;
  225. // Starts those plugins again, each from its last captured state (a running plugin's is captured now; one that is
  226. // down keeps what the last save, backup or capture took), without reopening the project. Only ever on request:
  227. // a plugin that goes down again stays down until this is called again. The song and the undo history are not
  228. // changed (close the plugins' windows first: a window keeps the old instance alive). Returns how many run again.
  229. // Plugins inside a Patcher are not covered.
  230. int reloadHostedPlugins (const std::vector<HostedSlot>& which);
  231. // Round 190ao (pain point 13): a short C5 on the channel that hosts `plugin`, a moment from now (a preset was just
  232. // loaded into it; the preset menu's "Play a note when a preset loads"). Only while the song is stopped; a note
  233. // still sounding from the last call ends first. False when nothing will play (an effect, a plugin outside the
  234. // Channel rack, the song playing or recording). auditionState: 0 idle, 1 waiting to start, 2 sounding (tests).
  235. bool auditionPreset (const juce::AudioPluginInstance& plugin);
  236. // Round 190dg (the Simple sound picker's installed plugins): the same short note on channel `channel`, whatever it
  237. // plays (a plugin just loaded there is heard as it is; it can't be rendered aside the way auditionSound does). The
  238. // same conditions: only while the song is stopped and not recording.
  239. bool auditionChannelSound (int channel);
  240. int auditionState() const noexcept { return auditionChannel < 0 ? 0 : auditionSounding ? 2 : 1; }
  241. // Round 190bu (the Simple workflow's sound picker): `channel`'s instrument heard alone through the preview output,
  242. // without touching the song — the notes `keys` in turn (core/RackRenderer.h renderAudition). False when the
  243. // instrument can't be built or makes no sound on this computer. `seconds` (optional) = how long the audition is.
  244. bool auditionSound (const ChannelDef& channel, const std::vector<int>& keys, double* seconds = nullptr);
  245. // FL's Project info working time (REA round 167g): wall-clock time since the project was opened, added to the
  246. // saved total at each save. workSecondsNow() = the saved total + this session so far.
  247. void stampWorkTime();
  248. double workSecondsNow() const;
  249. void resetWorkTime(); // Project info › "Reset working time": created = now, working time 0, the clock restarts
  250. void markCreatedNow(); // a new project: Project info › created = now (when it has no date yet)
  251. // issue #231 (round 190ns): a project without a date takes `file`'s creation date (platform::fileBirthSeconds), when the
  252. // file system keeps one; nothing changes otherwise
  253. void markCreatedFrom (const juce::File& file);
  254. // Offline render mode for the hosted plugins (setNonRealtime), around renderOffline.
  255. void setPluginsRenderMode (bool offline);
  256. // Round 190jb (owner decision: FL-exact; REA_rodada190jb): an export renders with the hosted plugin instances that
  257. // play, as FL does, not with new copies (engine/Exporter.h, LiveExportHold). holdForExport (message thread) stops
  258. // playback, makes the device callback output silence without touching the rack and halts render-ahead; it returns
  259. // true once nothing of this engine runs the plugins any more (false, nothing held: a recording or a real-time
  260. // bounce is running, or the device callback did not come back within `timeoutMs` — the export then makes its own
  261. // instances, as before). releaseAfterExport (message thread) lets the engine play again and publishes the song
  262. // (the units take this song's routes and side inputs back).
  263. bool holdForExport (int timeoutMs = 3000);
  264. void releaseAfterExport();
  265. bool heldForExport() const noexcept { return exportHold.load (std::memory_order_acquire); }
  266. // The export engine's side: its rack builds take the hosted plugins (and the Patchers that host plugins) these return
  267. // instead of making new ones (nullptr: made new). Set before setSong; empty functions = none.
  268. using LiveInstrumentSource = std::function<std::shared_ptr<Instrument> (const ChannelDef&, double sampleRate)>;
  269. using LiveEffectSource = std::function<std::shared_ptr<Effect> (const EffectSlot&, double sampleRate)>;
  270. void setLiveUnits (LiveInstrumentSource instrument, LiveEffectSource effect);
  271. // Every hosted plugin of the song that has not crashed (channels, inserts, inside Patchers); `notifyRender` is the
  272. // plugin's "Notify about rendering mode" option. Message thread or the render thread, while nothing else edits.
  273. void forEachHostedPlugin (const std::function<void (juce::AudioPluginInstance&, bool notifyRender)>& visit) const;
  274. // The render's plugin warm-up (renderOffline, round 155): silent discarded blocks until the hosted plugins settle,
  275. // then a new PDC plan if a latency changed and LYNX's own units reset. Returns blocks == 0 when the song has no
  276. // hosted plugin. `latency` receives the delay compensation's total afterwards.
  277. warmup::Result warmUpPlugins (const warmup::Settings& settings, double sampleRate, int blockSize,
  278. const std::function<bool (double)>& progress, int& latency);
  279. void play() noexcept;
  280. // FL's Stop pressed while already stopped (REA midiout190jl, FLEngine 0x11ca520 → 0x11c9de0): CC 123 on the 16
  281. // channels of every MIDI output with "Send all notes off"
  282. void stopWhileStopped() noexcept { midiSync.requestTransportNotesOff(); }
  283. // --cliplooptest (round 167q): the device callback, driven by hand with a stand-in device
  284. juce::AudioIODeviceCallback& deviceCallback() noexcept { return *this; }
  285. // Performance mode (round 165m, core/Performance.h): launch / release / stop zone clips (message thread). The
  286. // clips start on the next block, quantized by their track's Performance settings; nothing launches while stopped.
  287. void performanceCommand (const perf::Command& command) noexcept { performanceLive->commands.push (command); }
  288. // FL sends the typing keyboard's notes as MIDI channel 1: they launch performance clips when that is the "MIDI
  289. // channel used for playlist live mode" and Performance mode is on (the same test as the MIDI input's)
  290. bool typingNotesLaunchClips() const noexcept
  291. {
  292. return performanceMidiChannel.load (std::memory_order_relaxed) == 1 && performanceMidiOn.load (std::memory_order_relaxed);
  293. }
  294. const perf::Live& performanceState() const noexcept { return *performanceLive; }
  295. // The clip grid (round 181a, core/ClipLauncher.h; message thread). A launch while stopped starts the transport, as the
  296. // first thing a launcher does; a stop while stopped does nothing. Without a grid in the project: nothing at all.
  297. void launcherCommand (const launcher::Command& command);
  298. // What plays per track, or nullptr while no project has had a grid (never with Pattern workflow).
  299. const launcher::Runtime* launcherState() const noexcept { return clipLauncher.get(); }
  300. // --- recording into the clip grid's slots (round 190bv; core/SessionOps.h, docs/analise/REA_rodada190bv.md) ---
  301. // A column of the grid is a Playlist track. Armed, it records what is played on its instrument's channel (a track
  302. // without one: on any channel), or, a track that plays through a mixer insert with an input, that input's audio
  303. // (the insert is armed with it). Arming is not saved. `exclusive`: the other tracks are disarmed.
  304. enum class GridInput : std::uint8_t { midi, audio };
  305. GridInput gridTrackInput (int track) const;
  306. void setGridTrackArmed (int track, bool armed, bool exclusive = true);
  307. bool isGridTrackArmed (int track) const noexcept;
  308. // The record button of an empty slot on an armed track: the recording starts on the next point of the global launch
  309. // quantisation (the transport starts if it was stopped, after the count-in of the record options), stops what the
  310. // track plays there, and runs until endSlotRecording, or for the fixed length. False: the slot has a clip, or the
  311. // track is not armed.
  312. bool recordSlot (int track, int scene);
  313. // Ends the track's recording on the next quantisation point. `thenPlay`: the new clip plays on in a loop from
  314. // there (the recording clip's launch button); otherwise the track stops (a stop button).
  315. void endSlotRecording (int track, bool thenPlay);
  316. // The name the next MIDI clip recorded on a track gets (round 190cy, Live's "<track> <n>"; the grid shows it on the
  317. // recording slot before the clip exists).
  318. std::string slotRecordingName (int track) const;
  319. // The Session Record button. Nothing recording: every armed track records into `scene` where its slot is empty,
  320. // and armed tracks whose MIDI clip is playing take what is played into that clip as it loops (overdub).
  321. // Recording or overdubbing: the recordings go on into loop playback and overdub ends.
  322. void toggleSessionRecord (int scene);
  323. bool isSessionRecording() const noexcept { return ! slotTakes.empty() || sessionOverdub; }
  324. bool isSessionOverdubbing() const noexcept { return sessionOverdub; }
  325. // A fixed recording length in bars (0 = until it is ended). Not saved.
  326. void setSlotRecordBars (int bars) { slotRecordBars = juce::jlimit (0, 32, bars); }
  327. int getSlotRecordBars() const noexcept { return slotRecordBars; }
  328. launcher::Runtime* launcherStateForSnapshot() noexcept { return clipLauncher.get(); } // --gridshot: a sample of what plays
  329. perf::Live& performanceStateForSnapshot() noexcept { return *performanceLive; } // --perfshot: a sample of what plays
  330. void stop() noexcept; // also cancels a count-in or a wait for the first note
  331. // Recording options (docs/WORKFLOW_FL.md P2: recording set). UI thread.
  332. struct RecordOptions
  333. {
  334. int countInBars = 0; // 0 = off
  335. // FL's "Precount duration" (core/CountIn.h, issue #152): the length the count-in keeps while it is off, so
  336. // Ctrl+P turns a 2-bar count-in off and back on at 2 bars. A count-in that is on sets it.
  337. int countInLength = 1;
  338. bool waitForInput = false; // playback starts at the first played note
  339. // FL's Wait for input right-click (manual "Toolbar panels", round 190ld): "Only when recording" (on = LYNX's
  340. // behaviour so far: Play alone never waits) and "Respect recording filter" (only input the recording filter takes
  341. // starts it: notes start it only while the filter records notes)
  342. bool waitOnlyWhenRecording = true;
  343. bool waitRespectFilter = false;
  344. RecordMode mode = RecordMode::replace; // "Blend recorded notes" off, FL's factory default (round 177c)
  345. std::int64_t quantise = 0; // record quantise in ticks (<= 1: as played); follows the global grid
  346. bool placeSongClip = true; // song mode: a take puts a clip of the pattern where recording started
  347. // recording filter (FL's record button right-click, REA_rodada88): what a take records
  348. bool recordNotes = true; // notes played (MIDI and PC keyboard)
  349. bool recordAudio = true; // audio of the armed inserts' inputs
  350. bool askWhatToRecord = true; // the record button asks first ("What would you like to record?")
  351. // FL's record menu "Options" (REA round 134): arming recording also starts playback
  352. bool startsPlayback = false;
  353. // LYNX's own "Disarm the inserts when recording stops" (record menu and Mixer › Disk recording; issue #16): the
  354. // armed inserts are disarmed when a take stops. FL has no such option (round 166e measured: neither its
  355. // "Disarm on stop" nor the mixer's "Auto-unarm" disarms the inserts after a live take).
  356. bool disarmOnStop = false;
  357. // LYNX's "Low latency while recording" (round 190aq, core/LowLatency.h; FL has no such switch): while an insert
  358. // with an audio input is armed or monitored "On", the latency-adding effects on its path to the Master are
  359. // bypassed and the PDC plan is made without them; they return when it is disarmed. What is recorded and the
  360. // saved project never change. Off by default.
  361. bool lowLatencyRecording = false;
  362. // FL's record menu "Disarm on stop" (RecDisableOnStopMenu, round 166e measured): the record switch turns off when
  363. // playback stops after recording
  364. bool recordOffOnStop = false;
  365. // FL's Mixer › Disk recording › "Auto-unarm" (round 166e measured): "Render armed tracks to wave file(s)"
  366. // disarms the tracks it rendered
  367. bool unarmAfterRender = false;
  368. // FL's Mixer › Disk recording › "Auto-create audio clip" (on by default, round 167a [SHOT s28–s37]): the files
  369. // "Render armed tracks to wave file(s)" writes go on the Playlist (mixerops::placeRenderedFiles)
  370. bool autoCreateClip = true;
  371. // FL's Mixer › Disk recording › "Latency compensation" (round 190dx; checked by default in FL's form): off, takes
  372. // are placed with no latency compensation at all (takes::compensation)
  373. bool latencyCompensation = true;
  374. // FL's record menu "Quantize" section (REA round 139); `quantise` is the grid. quantiseStarts = "Note start
  375. // time", noteEnd = "Note end time" (quantize) / "Leave note duration" (keepLength) / neither (keepEnd),
  376. // toStepSequencer = "Record to step sequencer"
  377. bool quantiseStarts = true;
  378. NoteEnd noteEnd = NoteEnd::keepLength;
  379. bool toStepSequencer = false;
  380. // FL's "Enable recording markers": the Playlist's "Start recording" / "Stop recording" markers limit what a
  381. // take keeps in song mode (notes started outside are dropped, audio clips are cut to the ranges)
  382. bool recordingMarkers = false;
  383. // FL's recording filter "Automation" (REA round 143): moved parameters become automation (song mode: automation
  384. // clips; pattern mode: the pattern's events); Quantize › "Automations" puts their points on the snap
  385. bool recordAutomation = true;
  386. // FL's recording filter "Clips" (REA round 146 B5, round 165m): Performance mode's launched clips are written
  387. // into the arrangement where they played
  388. bool recordClips = true;
  389. bool quantiseAutomation = false;
  390. // round 163 (Pro Tools / Nuendo): punch in/out on the Playlist's loop region (instead of loop recording; the
  391. // song plays straight through it), pre-roll before the punch-in (or before the position recording starts at)
  392. // and post-roll after the punch-out (then playback stops). Bars; 0 = off.
  393. bool punchLoopRegion = false;
  394. // round 190lx (DL-61, Live's separate Punch-In / Punch-Out switches, manual 19.3.1): which ends of the loop region
  395. // the punch uses while punchLoopRegion is on. In only: the take starts at the region's start and runs on until
  396. // stopped; out only: it starts where recording starts and ends at the region's end (then the post-roll).
  397. // Both (the default, the other looks' one switch): round 163's punch in/out.
  398. bool punchIn = true, punchOut = true;
  399. int preRollBars = 0;
  400. int postRollBars = 0;
  401. // round 174d (ADR): pre / post-roll in seconds instead of bars while ≥ 0 (the ADR window sets them for its
  402. // record cycle; not saved)
  403. double preRollSeconds = -1.0;
  404. double postRollSeconds = -1.0;
  405. // FL's "Loop record" (toolbar LoopRecordBtn / Options, round 170e3 [DECOMP 0xf1e2a0 toggles a global that
  406. // FUN_011d4800 reads: off while recording, the play end becomes "never", so playback runs on]): on, Song mode
  407. // recording loops the loop region (one take per pass); off, it plays straight through the region and the notes
  408. // and audio stay where they were played. Pattern mode always loops the pattern in LYNX.
  409. bool loopRecord = true;
  410. // LYNX's own option (off = FL's result, REA round 177c): after loop recording only the last pass plays, on top
  411. // of the other passes (muted, newest first, folded). Round 163's behaviour.
  412. bool lastLoopPassPlays = false;
  413. // round 170d (the Busy Works video: the chord on the downbeat after the count-in was lost; Cubase's "MIDI Record
  414. // Catch Range", Logic keeps count-in notes): notes played during the count-in are recorded, and a note-on at most
  415. // this many ticks before the take's start goes onto the start (0 = off: they keep their real time)
  416. std::int64_t catchWindow = ppq / 4;
  417. // round 170d (Pro Tools / Cubase / REAPER): played notes are recorded where they were heard, moved back by the
  418. // output buffer + the driver's output latency
  419. bool compensateOutput = true;
  420. };
  421. // The range this recording keeps (pre-roll or punch), while one is active. UI thread.
  422. std::optional<PunchRange> getActivePunch() const noexcept { return activePunch; }
  423. const RecordOptions& getRecordOptions() const noexcept { return recordOptions; }
  424. void setRecordOptions (const RecordOptions& options);
  425. // Play pressed: with recording on, honours wait-for-input and the count-in; otherwise play().
  426. void startPlayback();
  427. // The song's initial values (FL's initialized controls) back on their targets, in song mode; play() and a
  428. // seek while playing do it (REA round 146). UI thread.
  429. void resetToInitialValues() noexcept;
  430. bool isWaitingForInput() const noexcept { return waitingForInput.load(); }
  431. bool isCountingIn() const noexcept { return transport.countIn.load() > 0.0; }
  432. // Ableton Link (round 190gl): Play was pressed and waits for the session's phase (a Stop cancels it)
  433. bool isLinkWaiting() const noexcept { return transport.linkWaiting.load(); }
  434. // The audio clock the last callback left (core/Recorder.h LiveClock) and where an event played at `eventMs`
  435. // (juce::Time::getMillisecondCounterHiRes) is recorded: sample-accurate against the block, minus the output
  436. // latency when compensateOutput is on (round 170d). Any thread.
  437. LiveClock liveClock() const noexcept;
  438. double recordTickFor (double eventMs) const noexcept;
  439. // The count-in catch of the take being counted in / recorded (round 170d; UI thread).
  440. const CountInCatch& getCountInCatch() const noexcept { return takeCatch; }
  441. // Record › Capture MIDI (round 170d, LYNX's own): the last phrase played without recording into the current pattern
  442. // (core/Recorder.h captureMidi), one undo step. UI thread.
  443. CaptureResult captureMidi();
  444. // Round 190ef / 190em (the Clip-launch layout with the clip grid shown, as Live 12.4.16 captures into its Session
  445. // view, live check 190ei): the same phrase on `track` (the caller passes the armed track), one undo step.
  446. // - `track` plays a MIDI clip while the transport runs: the notes go INTO that clip; its loop content is unrolled up
  447. // to the bars just played and its start / loop move there (session::captureIntoClip). `into` = true.
  448. // - else a new, unnamed clip in the slot session::captureSlot picks from `scene` (the selected scene), launched at
  449. // once (a stopped transport starts). Played while stopped, the song tempo is set from the phrase first
  450. // (session::phraseTempo).
  451. // `placed`: the row written (−1: nothing captured). The notes play on the track's instrument channel.
  452. CaptureResult captureMidiToSlot (int track, int scene, int& placed, bool& into);
  453. // Record › Capture automation (round 190op, research190oe P7; LYNX extra after Live 13's announced Capture Automation):
  454. // the knob / fader / button moves made while playing without recording (core/CaptureAutomation.h, the last two
  455. // minutes) become automation — the last continuous gesture of each moved control, in the layout's form: the Pattern
  456. // layout an automation clip (a lane while lanes are on), Clip-launch the Arrangement lane or, for a control moved
  457. // while a grid clip played on its track, that clip's envelope, Simple a lane; Pattern mode the current pattern's events.
  458. // One undo step; a second capture takes only newer moves. UI thread.
  459. struct AutomationCaptureResult
  460. {
  461. int controls = 0, points = 0;
  462. };
  463. AutomationCaptureResult captureAutomation();
  464. const captureauto::Buffer& getAutomationCapture() const noexcept { return automationCapture; } // (tests)
  465. void addAutomationCaptureSample (const captureauto::Entry& e) { automationCapture.add (e); } // (tests, --selftest)
  466. captureauto::Buffer& automationCaptureForTests() noexcept { return automationCapture; } // (round 190pa: its play passes)
  467. // Per-insert record arm: each armed insert records its own audio input (Mixer › insert › input source) into
  468. // its own take (arming one turns audio recording on; disarming the last one turns it off). Not saved.
  469. void setInsertArmed (int track, bool armed);
  470. bool isInsertArmed (int track) const noexcept;
  471. const std::vector<int>& getArmedInserts() const noexcept { return armedInserts; }
  472. void rewind() noexcept;
  473. void seek (double ticks) noexcept;
  474. // Preview of an audio file (browser). An invalid/empty file stops the preview.
  475. void previewFile (const juce::File& file);
  476. // Round 190iz: the Browser's preview (FL's): from `startFraction` of the file (Shift+Click, a click on the preview
  477. // strip's waveform) for 5 seconds (core/BrowserSend.h browserpreview), or to its end when `full` (Alt+Click, the
  478. // strip's Play button, or the "Full sample preview" option). previewFile (file) plays the whole file from its start.
  479. void previewFile (const juce::File& file, double startFraction, bool full);
  480. void setFullSamplePreview (bool on) noexcept { fullSamplePreview = on; }
  481. bool isFullSamplePreview() const noexcept { return fullSamplePreview; }
  482. // The Browser's "Preview in time" (LYNX extra, round 190aq, core/PreviewTempo.h; off by default): a previewed loop
  483. // plays stretched to the project's tempo and, while the transport plays, starts on the next beat. A file with no
  484. // usable tempo plays as it always did. The stretch is made on a worker thread: previewFile returns at once and the
  485. // sound starts when it is ready. UI thread.
  486. void setPreviewInTime (bool on) noexcept { previewInTime = on; }
  487. bool isPreviewInTime() const noexcept { return previewInTime; }
  488. struct PreviewTiming
  489. {
  490. juce::String path; // the previewed file ("" = none since the last stop)
  491. bool pending = false; // its tempo is being read or its stretch made: nothing sounds yet
  492. bool inTime = false; // it has a tempo: it plays stretched and / or on the beat
  493. double fileBpm = 0.0, projectBpm = 0.0, ratio = 1.0; // ratio: played length / file length (1 = not stretched)
  494. previewtempo::Source source = previewtempo::Source::none;
  495. double prepareMs = 0.0; // from previewFile to the sample handed to the player (tempo + stretch; 0 = cached)
  496. std::size_t frames = 0; // the played sample's length
  497. };
  498. const PreviewTiming& getPreviewTiming() const noexcept { return previewTiming; }
  499. // An in-time preview's progress 0..1 (0 while it is prepared or waits for its beat), −1 when none plays.
  500. double getPreviewInTimeProgress() const noexcept;
  501. // Waits for the preview being prepared and starts it (tests and tools: no message loop needed). UI thread.
  502. void finishPreviewJobs();
  503. // How long the last prepared preview took (tempo detection + stretch), in ms (diagnostics).
  504. double getLastPreviewPrepareMs() const noexcept { return lastPreviewPrepareMs; }
  505. // How many previews started on a beat (diagnostics, tests).
  506. int getPreviewBeatStarts() const noexcept;
  507. // The Browser's preview volume (0..1.25, 1 = default; core/ValueMath.h previewGain). Applies to the preview
  508. // playing now too. UI thread.
  509. void setPreviewVolume (double volume) noexcept;
  510. double getPreviewVolume() const noexcept { return previewVolume; }
  511. // Plays a sound made in memory through the same preview output (the start-up sound). UI thread.
  512. void previewSample (std::shared_ptr<const SampleData> sample, bool loop = false, float gain = 0.8f, bool audioEditor = false,
  513. std::int64_t startFrame = 0);
  514. // Round natives190kj: FL Edison's Scrub button — the audio editor's sample from `startFrame`, its speed then set with
  515. // setPreviewScrubSpeed (× normal, negative = backward, 0 = held). A previewSample (nullptr) ends it. UI thread.
  516. void previewScrub (std::shared_ptr<const SampleData> sample, std::int64_t startFrame);
  517. void setPreviewScrubSpeed (double speed) noexcept;
  518. // The Audio Editor's playback volume (its toolbar knob, round 162): 0..1.25 like the Browser's, 1 = unity.
  519. void setEditorVolume (double volume) noexcept;
  520. double getEditorVolume() const noexcept { return editorVolume; }
  521. // The frame of the previewed sample being played, -1 when the preview is silent.
  522. double getPreviewPosition() const noexcept;
  523. // Note played live (PC keyboard, preview). UI thread.
  524. // `record` = goes into the recording if recording is on (Piano Roll preview doesn't).
  525. void sendLiveNote (int channel, int key, float velocity, bool on, bool record = false);
  526. // GitHub #198 (round 190ks): a note played by clicking an instrument's own pads or keys (FPC's pads, DirectWave's and
  527. // Slicex's keyboards): heard on the channel and recorded while recording, as a played note — FL's host entry for a
  528. // plugin note "as if the user played it" (Dispatcher opcode 0x38 → the MIDI / typing keyboard's record-and-play
  529. // function, REA rea/REA-plugin-midiout-record.md). FL's own FPC / Slicex clicks only play (a LYNX extra here, the
  530. // issue's request). Never moved by the input scale snap (a pad's key is the pad). UI thread.
  531. void sendGuiNote (int channel, int key, float velocity, bool on);
  532. // The keys held right now on MIDI inputs and the typing piano (as played, before the scale snap), ascending; for
  533. // the Piano Roll's chord readout (any thread).
  534. std::vector<int> heldInputKeys() const;
  535. // Round 190ee: the key played last on a MIDI input or the typing piano (C5 = 60 before any): Edison's "Last hit"
  536. int lastPlayedKey() const noexcept { return lastHitKey.load (std::memory_order_relaxed); }
  537. // Round 190ih (FL's hint bar "Note on: C4 / velocity: 100", PLAN R3 DC-9): the last note of the typing keyboard or a
  538. // MIDI input (core/LiveNote.h); 0 = none yet. A note-off carries its note-on's velocity (as FL's hint shows it).
  539. // (unpacked with core/LiveNote.h)
  540. std::uint32_t lastLiveNote() const noexcept { return liveNote.load (std::memory_order_relaxed); }
  541. void markLiveNote (int key, int velocity127, bool on) noexcept;
  542. // The same for one MIDI channel (0-15; the typing keyboard plays on 0), as two 64-bit masks: the chord panel (round
  543. // 181b) counts each channel's keys on its own, as FL does.
  544. std::array<std::uint64_t, 2> heldInputKeyBits (int midiChannel) const noexcept;
  545. // The Audio logger's memory (Tools › Audio logger, round 181b). The audio thread writes it from the Master.
  546. RollingAudioLog& getRollingLog() noexcept;
  547. // The keys sounding on a channel right now (song / pattern notes, keyboard, MIDI): the Piano roll's keyboard lights
  548. // them (issue #14). Any thread.
  549. NoteMask soundingKeys (int channel) const noexcept;
  550. // round 190ih: a counter that moves with every block that struck a note on the channel (the rack's activity light)
  551. std::uint32_t noteStrikes (int channel) const noexcept;
  552. int voicesSounding() const noexcept; // round 190oa (DF-29): the toolbar's polyphony (FL's voices being mixed)
  553. // FL's score logger (REA round 165f): every note played on a MIDI input or the typing keyboard, recording or
  554. // not, for Tools › Dump score log to selected pattern. Any thread (a short spin lock; never the audio thread).
  555. std::vector<scorelog::Entry> scoreLogSnapshot() const;
  556. bool scoreLogEmpty() const;
  557. void clearScoreLog();
  558. // FL's Step edit (round 170e3, core/StepEdit.h): while on, every note played on a MIDI input or the typing keyboard
  559. // is also queued for the UI, which writes it into the pattern when the transport is stopped. Any thread.
  560. void setStepEdit (bool on) noexcept;
  561. bool isStepEdit() const noexcept { return stepEditOn.load (std::memory_order_relaxed); }
  562. std::vector<stepedit::Played> takeStepEditNotes();
  563. // Scale snap for played notes (MIDI input and the PC keyboard): scale index into notetools::scales()
  564. // (0 = off) and its root (0..11). Any thread.
  565. void setInputScale (int scale, int root) noexcept;
  566. int snapInputKey (int key) const noexcept;
  567. // All notes off on every channel (double-click on Stop). UI thread.
  568. void panic();
  569. // FL's Tools › Macros › Stop sound (Ctrl+H, round 170h2; FL64 MacroStopSoundActionExecute → FUN_011c8d10 →
  570. // FUN_011c8a40 (1, 1, 1) → FUN_012b5210): all notes off on every channel and MIDI out, and every effect and
  571. // plugin reset — the tails of delays and reverbs stop too. UI thread.
  572. void stopSound();
  573. // Note recording (MIDI and PC keyboard) into the current pattern while playing. UI thread.
  574. void setRecording (bool shouldRecord);
  575. // FL's Tools › Macros › Cancel recording (MacroCancelRecordingAction, REA round 169k §2.3 [DECOMP 0xf1d7e0]): what this
  576. // recording pass wrote is thrown away (its notes, automation and audio takes; the take files are deleted), recording
  577. // turns off, the armed inserts stay armed and playback goes on. false: not recording. UI thread.
  578. bool cancelRecording();
  579. bool isRecording() const noexcept { return transport.recording.load(); }
  580. // Pattern mode, a take with Loop record off (round 170e5): the transport tick the pattern plays once from, < 0: none
  581. double patternLinearOrigin() const noexcept { return liveInput.patternOrigin.load (std::memory_order_relaxed); }
  582. // Round 177d: the recording in progress as the editors draw it live (core/LiveRecordView.h). UI thread.
  583. struct LiveRecording
  584. {
  585. // the note take: the notes still held (positions in `pattern`, as they would be committed now) and, in Song
  586. // mode, the Playlist range the take covers so far: [from, to) on `track` (from = its clip's start or the origin)
  587. bool notes = false;
  588. int pattern = -1;
  589. std::vector<Note> held;
  590. int track = -1;
  591. std::int64_t from = -1, to = -1;
  592. std::int64_t origin = -1; // the song position of the pattern's start for `held`
  593. // the audio takes: each on the Playlist track it will land on, its current pass and its waveform
  594. struct Audio
  595. {
  596. int track = -1;
  597. liverec::AudioSpan span;
  598. std::shared_ptr<const liverec::LivePeaks> peaks;
  599. juce::String name;
  600. };
  601. std::vector<Audio> audio;
  602. std::optional<PunchRange> punch; // only this range is kept (pre-roll / punch in-out)
  603. bool any() const noexcept { return notes || ! audio.empty(); }
  604. };
  605. // cheap: a take records (notes held or recorded, or audio)
  606. bool isLiveRecording() const noexcept { return recorder.isActive() || takeCount > 0; }
  607. bool isRecordingAudioTakes() const noexcept { return takeCount > 0; } // audio takes are open (issue #152)
  608. LiveRecording liveRecording() const;
  609. // Audio recording from the interface input: with this on, recording (Rec + Play) writes the
  610. // input to a WAV and, on stop, the take becomes a Playlist clip (latency-compensated).
  611. // Enabling it opens the device input (only then does Windows show the mic as in use).
  612. void setAudioRecordingArmed (bool armed);
  613. bool isAudioRecordingArmed() const noexcept { return audioArmed; }
  614. juce::String getLastRecordingError() const { return recordingError; }
  615. // Where takes are written and how they are named (FL's project data folder, REA round 134): `folder` is
  616. // "<project folder>/Audio/Recorded" for a saved project (the global recordings folder otherwise), files are
  617. // "<projectStem>_<yyyy-mm-dd hh-mm-ss>_<insert name>.wav". UI thread.
  618. void setRecordingTarget (const juce::File& folder, const juce::String& projectStem);
  619. juce::File getRecordingFolder() const { return recordingFolder; }
  620. juce::String getRecordingStem() const { return recordingStem; }
  621. // A MIDI message as if a controller had sent it (the --bendrectest of round 167a). Message thread.
  622. void injectMidiInput (const juce::MidiMessage& message) { handleMidiInput (nullptr, {}, message); }
  623. // Round 190pl (--demo midi.input): the same as from an input device with this name ("LYNX demo keyboard"), so the
  624. // device's MIDI settings (on / off, MIDI channel, what it plays) apply as to hardware. Message thread.
  625. void injectMidiInput (const juce::MidiMessage& message, const juce::String& deviceName) { handleMidiInput (nullptr, deviceName.toStdString(), message); }
  626. static juce::File defaultRecordingFolder();
  627. // The take files written since LYNX started (or since forgetRecordings), oldest first. UI thread.
  628. const std::vector<juce::File>& getSessionRecordings() const noexcept { return sessionRecordings; }
  629. void forgetRecordings (const std::vector<juce::File>& files);
  630. // --- hardware recording (round 163, docs/analise/REA_rodada163c.md) ---
  631. // Options › Audio › Recording, saved in <settings>/recording.txt.
  632. struct RecordingSettings
  633. {
  634. takes::SampleFormat format = takes::SampleFormat::pcm24; // 24-bit or 32-bit float WAV; the device's rate
  635. bool trackTakeNames = true; // "<Insert>_Take<N>.wav" (off: FL's "<project>_<date time>_<insert>.wav")
  636. int manualOffset = 0; // samples added to the compensation (negative: earlier)
  637. bool useMeasured = true; // a ping measured for this device setup replaces the driver's figures
  638. std::map<std::string, int> measured; // setupKey -> round trip (samples)
  639. int pingOutput = 0, pingInput = 0; // device channels the ping uses (output pair's first, input)
  640. };
  641. const RecordingSettings& getRecordingSettings() const noexcept { return recordingSettings; }
  642. void setRecordingSettings (const RecordingSettings& settings); // saves
  643. // The current device setup's key (takes::setupKey) and its latency figures (pdc = the Master's PDC now).
  644. std::string currentSetupKey() const;
  645. takes::Latency currentLatency() const;
  646. // The latency ping: clicks on output channel pair `pingOutput` (and the next), listened for on input channel
  647. // `pingInput` through a loopback. Needs the transport stopped and the input open. Returns an error (empty: started).
  648. juce::String startLatencyPing();
  649. bool isPinging() const noexcept { return ping.isRunning(); }
  650. void cancelLatencyPing() noexcept { ping.cancel(); }
  651. // After isPinging() turned false: the result (stored for this setup when ok).
  652. takes::LatencyPing::Result finishLatencyPing();
  653. // Record safe (round 163): a safe insert can't be armed (undoable, saved with the project).
  654. void setInsertRecordSafe (int track, bool safe);
  655. bool isInsertRecordSafe (int track) const noexcept
  656. {
  657. return track > 0 && track < (int) song.mixer.size() && song.mixer[(std::size_t) track].recordSafe;
  658. }
  659. // Frames lost while recording (the disk could not keep up; they became silence, the timing kept) since the
  660. // last take started.
  661. juce::int64 getLostRecordingFrames() const noexcept { return lostFrames; }
  662. // Interrupted takes (crash while recording): repaired WAVs and where they belonged. Scans the journals in the
  663. // given folders (the default recordings folder always). UI thread, at start-up.
  664. std::vector<takes::Journal> recoverInterruptedTakes (const std::vector<juce::File>& folders);
  665. // Puts recovered takes on the Playlist at their recorded positions (undoable). Returns how many were placed.
  666. int placeRecoveredTakes (const std::vector<takes::Journal>& recovered);
  667. // Leaves them as files only (their journals are removed).
  668. void forgetInterruptedTakes (const std::vector<takes::Journal>& recovered);
  669. // --- external audio input through the mixer (REA_rodada88) ---
  670. // Names of the open device's input channels (all of them, open or not); empty without an input device.
  671. std::vector<std::string> getInputChannelNames() const;
  672. // Problems the UI explains to the user (translated there).
  673. enum class InputIssue
  674. {
  675. none,
  676. noDevice, // no audio device open at all
  677. noInputDevice, // the driver has no input device
  678. noInputOpen, // recording with no input open
  679. armedWithoutInput, // armed inserts, none with an input source
  680. insertWithoutInput,// one armed insert (track) has no input source
  681. silentTake, // round 190ir: every take of the pass is digital silence (a muted / wrong input, OS privacy)
  682. lowDisk, // little room left on the recordings drive (detail = minutes)
  683. recordSafe, // the insert (track) is record safe: not armed
  684. framesLost, // the disk could not keep up: frames became silence (detail = how many)
  685. failed // the driver refused (detail = its message) or a file could not be written
  686. };
  687. struct RecordingNotice
  688. {
  689. InputIssue issue = InputIssue::none;
  690. int track = 0;
  691. juce::String detail;
  692. };
  693. // Opens the input of the current driver: `deviceName` (separate-input drivers; empty = the one chosen in
  694. // Settings, else the default), all of its channels. UI thread.
  695. RecordingNotice openAudioInput (const juce::String& deviceName = {});
  696. bool hasAudioInput() const;
  697. // Closes the device input again when nothing needs it (no insert takes an input, no armed recording, no hardware
  698. // insert returning from it): a capture the Audio editor opened for one recording no longer keeps the input — and
  699. // Windows' microphone-in-use icon — on until LYNX quits, as in FL (round 165q). The input device's name is kept
  700. // for the next openAudioInput(). UI thread.
  701. void releaseAudioInputIfUnused();
  702. bool audioInputNeeded() const;
  703. // round 190ub (issue #371): whether the armed inserts' takes use the device input (an input chosen, or "External input
  704. // only"; Settings' "Record input audio" when none is armed). Tapped takes of routed audio don't.
  705. bool armedTakesNeedInput() const;
  706. // Sets an insert's input source (undoable; -1 = none) and opens the device input when needed.
  707. void setInsertInput (int track, int channel, bool stereo);
  708. void setInsertMonitor (int track, InputMonitor mode);
  709. // FL's "Record" position of an insert and LYNX's "also record the dry input" (round 168x, issue #41); undoable
  710. void setInsertRecordSource (int track, RecordSource source);
  711. void setInsertRecordDryToo (int track, bool on);
  712. // --- hardware output targets (REA round 156) ---
  713. // Names of the open device's output channels (all of them, open or not); empty without a device.
  714. std::vector<std::string> getOutputChannelNames() const;
  715. // Whether device output channel `c` is open (gets sound) right now.
  716. bool isOutputChannelOpen (int channel) const;
  717. // Sets a track's hardware output target (undoable; outputNone / outputDefault / a device channel) and opens
  718. // the device's output channels it needs (no trip to Audio settings). The Master's default is its first pair.
  719. void setTrackOutput (int track, int channel, OutputMode mode);
  720. // Opens the device output channels the song's targets need (that the device has). UI thread.
  721. void openTargetedOutputs();
  722. // Round 190nc (DL-110, Live's Solo/Cue, core/SessionMixer.h): the Main strip's Cue Out (outputDefault = as Main Out;
  723. // opens its channels), Solo/Cue Mode switch and Cue Volume (0..1, Live's volume taper; `undoable` false while dragged).
  724. // Undoable edits of the clip grid's SessionCue (made with the grid). UI thread.
  725. void setCueOutput (int channel, OutputMode mode);
  726. void setCueMode (bool cue);
  727. void setCueVolume (float position, bool undoable);
  728. // How many output channels the open device has (0 without one)
  729. int outputChannelCount() const { return outputCountForCheck >= 0 ? outputCountForCheck : (int) getOutputChannelNames().size(); }
  730. // (tests and shots) a device with `count` outputs as far as outputChannelCount is concerned (−1: the real one)
  731. void setOutputChannelCountForCheck (int count) noexcept { outputCountForCheck = count; }
  732. // The hardware inserts' channels (round 164d): opens their outputs and, when one returns from an input, the device
  733. // input. UI thread.
  734. void openHardwareInsertIo();
  735. // Every hardware insert of the song (round 165c): a mixer slot's, or a node inside a Patcher (mixer-slot or generator
  736. // Patcher; `nodes` = the node index at each Patcher level). UI thread.
  737. struct HardwareInsertRef
  738. {
  739. bool channel = false; // a Channel Rack generator Patcher (index = channel), else a mixer slot (index = track)
  740. int index = 0, slot = 0;
  741. std::vector<int> nodes;
  742. bool operator== (const HardwareInsertRef&) const = default;
  743. };
  744. std::vector<HardwareInsertRef> getHardwareInserts() const;
  745. static EffectSlot* locateHardwareInsert (Song& song, const HardwareInsertRef& ref);
  746. std::shared_ptr<Effect> runningHardwareInsert (const HardwareInsertRef& ref) const;
  747. // The routed, active inserts whose round trip was measured for another device setup (device, rate or buffer size)
  748. std::vector<HardwareInsertRef> staleHardwareInserts() const;
  749. // Presses their Ping buttons (the clicks go out on their sends; the results are applied as they come back)
  750. void pingHardwareInserts (const std::vector<HardwareInsertRef>& refs);
  751. // After the device setup changed with stale inserts in the song: those inserts, once (the UI offers "Ping now")
  752. std::vector<HardwareInsertRef> takeHardwareInsertNotice() { return std::exchange (hwNotice, {}); }
  753. // Input level of an insert's source since the last call (0..1, per side). UI thread.
  754. // (the Mixer's strips take it 30 times a second; other views peek at the last value taken)
  755. float takeInputPeak (int track, int side) noexcept
  756. {
  757. const auto v = liveInput.meters.takePeak (track, side);
  758. if (track >= 0 && track < maxMixerTracks && (side == 0 || side == 1))
  759. lastInputPeaks[(std::size_t) (track * 2 + side)] = v;
  760. return v;
  761. }
  762. // Round 190ke: the Simple tuner's input: device input channels [first, first + count) mixed to mono into tunerTap()
  763. // while first >= 0. The tuner sets it only while it shows; −1 (the default) = off, the callback skips it. UI thread.
  764. void setTunerInput (int first, int count) noexcept
  765. {
  766. tunerCount.store (juce::jlimit (0, 2, count), std::memory_order_relaxed);
  767. tunerFirst.store (count > 0 ? first : -1, std::memory_order_release);
  768. }
  769. const visualfx::Tap& tunerTap() const noexcept { return *tunerTapData; }
  770. float peekInputPeak (int track, int side) const noexcept
  771. {
  772. return track >= 0 && track < maxMixerTracks && (side == 0 || side == 1) ? lastInputPeaks[(std::size_t) (track * 2 + side)] : 0.0f;
  773. }
  774. // A message for the user about recording (e.g. an armed insert without an input), once. UI thread.
  775. RecordingNotice takeRecordingNotice() { return std::exchange (recordingNotice, {}); }
  776. // MIDI learn: the next CC received becomes a controller linked to `target`.
  777. void learnMidiController (const AutomationTarget& target);
  778. bool isLearningMidi() const noexcept { return learning.kind != AutomationTargetKind::none; }
  779. // Global links (FL's "Override global link...", REA round 146): links in the MIDI settings that every project
  780. // follows unless it links the same target or controller itself. The next CC received becomes `target`'s.
  781. void learnGlobalLink (const AutomationTarget& target);
  782. // FL's "Multilink to controllers" (Options › Switches, Ctrl+J; round 177b-4, core/Multilink.h): the controls moved
  783. // while it is on link, in that order, to the controllers moved next; it switches itself off when all are linked
  784. void setMultilink (bool on);
  785. bool isMultilinkOn() const noexcept { return multilink.has_value(); }
  786. int multilinkQueued() const noexcept { return multilink ? (int) multilink->targets.size() : 0; }
  787. // the controls queued so far, in the order they were moved (round 190bt: "Link to controllers...")
  788. std::vector<AutomationTarget> multilinkTargets() const { return multilink ? multilink->targets : std::vector<AutomationTarget>(); }
  789. // the switch's menu: "Link to controller" (false) / "Override global links" (true): no more controls are queued,
  790. // the controllers moved next link to the queued ones (as project links / as global links)
  791. void multilinkToControllers (bool global);
  792. void removeGlobalLink (const AutomationTarget& target);
  793. // FL's "Remote control settings" / "Global link settings" windows (round 190bt). setTargetLinks: the control's
  794. // project links become `links` (one undo step; core setTargetLinks). setGlobalLink: the control's global link
  795. // becomes `link` (none: it is removed).
  796. void setTargetLinks (const AutomationTarget& target, std::vector<MidiLink> links, bool removeConflicts);
  797. void setGlobalLink (const AutomationTarget& target, const std::optional<MidiLink>& link);
  798. // The controller message that arrived last (the windows' "Auto detect"); `serial` grows with every message.
  799. struct ControllerSeen
  800. {
  801. int port = -1, channel = 0, cc = -1, value = 0;
  802. std::uint64_t serial = 0;
  803. };
  804. ControllerSeen lastControllerSeen() const noexcept { return controllerSeen; }
  805. // A controller message as if a device had sent it (tests, --snapshot). Message thread.
  806. void injectControllerForTest (int cc, int channel, int value, int port = -1);
  807. void timerCallbackForTests() { timerCallback(); } // (round 190oa: the engine's periodic step, for --details190oashot)
  808. // Round 190em: a played note in the score log (Capture MIDI's source) at a given time (--selftest).
  809. void logPlayedNoteForTest (double ms, int channel, int key, float velocity, bool on, double tick = -1.0);
  810. // Round 190ef, the reference's MIDI Map Mode / Key Map Mode (core/RemoteMap.h). In MIDI Map Mode the controllers and
  811. // keys received pick the control the map overlay selected instead of moving anything (no mapping acts, no key plays);
  812. // takeMapCapture gives the last one (once). Message thread.
  813. void setMapMode (remotemap::Mode mode);
  814. remotemap::Mode getMapMode() const noexcept { return mapMode; }
  815. std::optional<remotemap::MidiControl> takeMapCapture() { return std::exchange (mapCaptured, std::nullopt); }
  816. // A MIDI mapping of a clip slot, a scene, a track's stop button, Stop all clips or a transport switch fired (its
  817. // press or release); the main window acts on it. Message thread (from applyControllers).
  818. std::function<void (const remotemap::Fire&)> onRemoteFire;
  819. // Round 190hp (slice B9): the Mapping Browser's "In every project (LYNX)" — a MIDI mapping moves from the project
  820. // (one undo step) into the settings, or back (core/RemoteMap.h). The app's engine saves the settings. False = nothing
  821. // moved. The global rows' Delete and Min / Max edit the settings (not undoable, as FL's global links).
  822. bool moveMappingScope (const remotemap::Row& row, bool toEveryProject);
  823. bool editGlobalMappingRow (const remotemap::Row& row, const std::function<bool (prefs::MidiPrefs&)>& edit);
  824. // "Omni" links follow the mixer's selected track: the mixer reports it here (-1 = unknown).
  825. std::function<int()> selectedMixerTrackForLinks;
  826. std::optional<MidiLink> globalLinkOf (const AutomationTarget& target) const;
  827. std::vector<MidiLink> getGlobalLinks() const;
  828. // FL's "Last tweaked" (REA round 143: FLEngine keeps the last two moved parameters, Tools › Last tweaked /
  829. // Next to last tweaked, Add › Automation for last tweaked parameter). Every control that can be automated reports
  830. // its moves here (UI thread); `held` = the touch lasts until tweakReleased (a plugin's own editor's gesture),
  831. // otherwise while the control keeps moving. While recording with the "Automation" filter, touched parameters are
  832. // written as automation.
  833. void noteTweaked (const AutomationTarget& target, bool held = false);
  834. // A control on screen was tweaked by the mouse / wheel (knob, fader, slider, switch: ui::onTweak and the editors'
  835. // drag starts). With FL's General › Undo history › "Undo knob tweaks" off (core/FlSettings.h undoKnobTweaks, round
  836. // 190mv, DF-134) the tweak's press (or wheel step) makes no undo step: a step its edit already saved is taken back,
  837. // later edits of the press save none. The project still counts as changed. Online Sessions keep every step.
  838. void controlTweakedForUndo();
  839. // Round 190tv (issue #364; FL 2026 live check 12-02): FL merges the wheel notches of one control that come less than
  840. // 400 ms apart into one undo step (each notch restarts the wait: a spin is one step; a pause makes the next notch a
  841. // new step). A wheel handler names its control (any stable key, e.g. a hash of the control's name) right before its
  842. // edit; the Pattern layout's controls do (ui::onWheelStep, the tempo display). A notch that changes nothing saves
  843. // no step anyway (the caller makes no edit).
  844. void wheelStepForUndo (std::uint64_t control) noexcept;
  845. static constexpr double wheelMergeMs = 400.0;
  846. // FL's Current (C) mixer track (round 190mv, DF-82; core/MixerOps.h currentTrack): the mixer's selected track, whose
  847. // output the Current track's effects process in line during live playback (−1 = none). The Mixer sets it.
  848. // A Current track whose effects add latency moves that latency into the newly selected track's delay compensation
  849. // (round 190my: the rack is published again).
  850. void setCurrentTrackSource (int track);
  851. int getCurrentTrackSource() const noexcept { return currentSource; }
  852. void tweakReleased (const AutomationTarget& target);
  853. // Round 190oa (DL-58, Live 12 manual 25.4 "Re-Enable Automation"): Live's override state in the Clip-launch layout.
  854. // A control moved by hand leaves its automation (the engine's released targets, FL's rule) — in Live until the
  855. // Control Bar's Re-Enable Automation is pressed, not at the next Play. `liveOverride` = the Clip-launch layout's way.
  856. void setLiveAutomationOverride (bool liveOverride) noexcept;
  857. bool automationOverridden() const; // a control with automation is overridden (Live lights Re-Enable Automation)
  858. void reEnableAutomation(); // every overridden control follows its automation again
  859. // 0 = the last tweaked parameter, 1 = the one before it.
  860. std::optional<AutomationTarget> getLastTweaked (int which = 0) const;
  861. // The target's current value 0..1 (a hosted plugin's parameter and MIDI controls included); < 0 when it is gone.
  862. float currentTargetValue (const AutomationTarget& target) const;
  863. // Parameter `param` of a hosted plugin (a channel's instrument or a slot's effect) as an automation target.
  864. std::optional<AutomationTarget> targetOfPlugin (const juce::AudioPluginInstance& plugin, int param) const;
  865. // Number of points recorded as automation since recording started (tests, hint bar).
  866. int getRecordedAutomationPoints() const noexcept { return recordedAutomationPoints; }
  867. // Names a new recorded automation (the UI sets it to its readable target names).
  868. std::function<std::string (const AutomationTarget&)> nameAutomation;
  869. // MIDI inputs: every device is enabled and plays the selected channels unless the MIDI settings say otherwise
  870. // (Settings › MIDI: device off, one MIDI channel only, a fixed Channel Rack channel; velocity curve; pickup).
  871. juce::StringArray getActiveMidiInputs() const;
  872. // Counts the messages received from the enabled MIDI inputs (the toolbar's MIDI activity light).
  873. std::uint32_t getMidiActivity() const noexcept { return midiActivity.load (std::memory_order_relaxed); }
  874. // round 190ld (Simple › Finish, details DS-44): a gain on what the device plays only (never in a render or an
  875. // export), so the "Hear without" A/B is heard at the mastered song's loudness; 1 = off. Faded over one block.
  876. // FL's tempo tapper "now" / "Mute" (round 190my, DF-17; REA 190my R3: FUN_00f12170 → the master volume stage in
  877. // FUN_00d0d4c0): the output drops to 1 % at once and comes back over `ticks` of playback (the song's time, counted
  878. // only while it plays) along FL's curve 0.01 + 0.99 · cos¹⁸(π/2 · left / ticks) — near silent most of the way, back
  879. // in the last part. Stopping ends it. 0 lifts it.
  880. void muteOutputForTicks (double ticks) noexcept
  881. {
  882. muteTicksTotal.store (std::max (0.0, ticks), std::memory_order_relaxed);
  883. muteTicksLeft.store (std::max (0.0, ticks), std::memory_order_relaxed);
  884. }
  885. bool outputMutedForTicks() const noexcept { return muteTicksLeft.load (std::memory_order_relaxed) > 0.0; }
  886. static float tapperMuteGain (double left, double total) noexcept; // (round 190my: FL's curve, 1 when done)
  887. // Round 190oa (DF-10; REA 190oa R4, FL's FUN_011c9ab0): what can start a "Wait for input" — a moved parameter
  888. // (automation), a played note, a tap of the tempo tapper, a launched clip. With "Respect recording filter" on while
  889. // recording, only the kinds the recording filter records (Audio in the filter: any kind; the tapper: always).
  890. enum class WaitInput : std::uint8_t { automation = 1, notes = 2, clips = 8, tapper = 16 };
  891. void inputArrived (WaitInput kind) noexcept { startOnInput (kind); }
  892. void setListenGain (float gain) noexcept { listenGain.store (gain, std::memory_order_relaxed); }
  893. // round 190oa (DF-21): the toolbar's main volume (FL's monitor volume): the song's mainVolume (a fader position) on
  894. // the device output only. Not an undo step, not automatable, never in an export; the project remembers it.
  895. void setMainVolume (float position);
  896. float mainVolumeGainNow() const noexcept { return mainVolumeGain.load (std::memory_order_relaxed); }
  897. float getListenGain() const noexcept { return listenGain.load (std::memory_order_relaxed); }
  898. // round 190ld (FL's Sync indicator colours): messages a project link / mapping and a global link / mapping took
  899. // (message thread, counted in applyControllers)
  900. std::uint32_t getMidiProjectLinked() const noexcept { return midiProjectLinked; }
  901. std::uint32_t getMidiGlobalLinked() const noexcept { return midiGlobalLinked; }
  902. std::uint32_t getMidiPlayed() const noexcept { return midiPlayed.load (std::memory_order_relaxed); }
  903. // Closes and opens again every enabled MIDI input (the MIDI light's click; Settings › MIDI › Refresh).
  904. void reconnectMidiInputs();
  905. // Round 190gh (B8): MIDI device hot-plug. The device lists are compared on the system's notification and every 2 s
  906. // (FL: "MIDI devices have changed... refreshing..."): enabled inputs that appear are opened by name, an input that
  907. // was unplugged while open is closed at once, the sync outputs and the controllers' feedback ports are opened
  908. // again by name, the version below counts up (Settings › MIDI rebuilds its lists) and onMidiDevicesChanged gets
  909. // the names plugged in and out (the hint bar). UI thread.
  910. int getMidiDeviceListVersion() const noexcept { return midiDeviceListVersion; }
  911. std::function<void (const juce::StringArray& added, const juce::StringArray& removed)> onMidiDevicesChanged;
  912. // Round 190rp (0.1.32 Q4, owner decision O-4 (a)): the audio device in use went away (unplugged, its driver or
  913. // PipeWire node removed). A recording stops (the take is kept, as the record button would) and so does playback
  914. // with it; onAudioDeviceLost gets the device's name and whether a recording was stopped (the notice). When the
  915. // device is listed again and nothing else was chosen meanwhile it is opened again with its settings, and
  916. // onAudioDeviceBack gets its name. Checked twice a second from the engine's timer. UI thread.
  917. std::function<void (const juce::String& device, bool recordingStopped)> onAudioDeviceLost;
  918. std::function<void (const juce::String& device)> onAudioDeviceBack;
  919. // Round 190rp (crash group G1, engine/DeviceGuard.h): the saved device's driver did not answer within the time limit
  920. // at start ("<type>: <name>"); the default device is open instead. retryHungAudioDevice: one more bounded attempt
  921. // with the saved setup ("" = it opened; else why not, and the default device is open again). Message thread.
  922. std::function<void (const juce::String& device)> onAudioDeviceHung;
  923. juce::String retryHungAudioDevice();
  924. // --selftest "device_lost" (engine/DeviceChangeTest.cpp): the stand-in device in use unplugged while recording,
  925. // while playing, and while stopped, then plugged in again; and a device chosen while the lost one is away.
  926. // "OK (...)" or "ERROR ..."
  927. static juce::String deviceLostSelfTest();
  928. // --selftest "stab190rp" / --recoverytest (round 190rp, FIX-LIST item 8 = TN2-1, engine/SampleZeroTest.cpp): a burst at
  929. // tick 0 through every effect kind with latency, a linear-phase EQ, a send and side-by-side inserts starts at sample
  930. // 0 of the export, and the delay compensation's total after play from stop and after a relocate. "OK (...)" / "ERROR ..."
  931. static juce::String sampleZeroSelfTest (const std::function<void (const juce::String&)>& log = {});
  932. // --selftest "midi_hotplug" / --midihotplugtest: stand-in device lists in place of the system's (empty = the
  933. // system's), then "OK (...)" or "ERROR ..." (engine/MidiHotplugTest.cpp)
  934. static std::function<juce::Array<juce::MidiDeviceInfo> (bool inputs)>& midiDeviceListOverride();
  935. static juce::String midiHotplugSelfTest();
  936. // Round 190jl (engine/MidiOutPortTest.cpp): MIDI Out channels to the hardware outputs on their port, end to end
  937. static juce::String midiOutPortSelfTest();
  938. // Round 190ks (GitHub #198): a take records what a hosted plugin plays from its window (src/engine/PadRecordTest.cpp,
  939. // `LYNX --padrectest "<LYNX Test Pads.vst3>" report.txt`)
  940. static juce::String padRecordSelfTest (const juce::String& pluginPath);
  941. // Round 190ks: what 8 identical SoundFont / Sampler channels cost in memory (src/engine/ShareMemoryTest.cpp,
  942. // `LYNX --sharetest <folder> sf2-same|sf2-copies|wav-same|wav-copies report.txt`)
  943. static juce::String shareMemorySelfTest (const juce::File& folder, const juce::String& which);
  944. const prefs::MidiPrefs& getMidiPrefs() const noexcept { return midiPrefs; }
  945. // Applies them (and saves them in %APPDATA%\LYNX\midi-settings.txt when `save`).
  946. void setMidiPrefs (const prefs::MidiPrefs& prefs, bool save = true);
  947. // master sync out / external clock in / all notes off (round 165f)
  948. MidiSyncIo& getMidiSync() noexcept { return midiSync; }
  949. // Ableton Link (round 190gl, engine/AbletonLink.h): the session, and its switches (saved with the MIDI settings)
  950. AbletonLink& getLink() noexcept { return abletonLink; }
  951. const AbletonLink& getLink() const noexcept { return abletonLink; }
  952. void setLinkEnabled (bool on);
  953. void setLinkStartStopSync (bool on);
  954. // The tempo the toolbar shows: the Link session's while Link is on, else the project's.
  955. double shownTempo() const noexcept;
  956. // FL's Channel rack "Restretch all" (round 190mp, DE-38; FLEngine FUN_00fe7510): every channel that plays a copy stretched
  957. // ahead of time (pitch kept, a length in beats) is stretched again from its file now. Returns how many channels.
  958. int restretchAll();
  959. // Round 190tg: a sample whose decoded copy on disk failed the check after the open is swapped in anew (it is decoded
  960. // again already) in every channel that plays it: returns how many; `araKept` is set when one of them is an ARA channel,
  961. // whose plugin keeps the audio it read itself. Message thread. Round 190tm: also Channel settings › Reload (FL's: the
  962. // file read from disk again, the channels' settings kept).
  963. int reloadSampleEverywhere (const juce::String& path, bool& araKept);
  964. // FL's tempo menu "Half speed" (round 190mp, DF-16; capture 190mp A4): playback at half the tempo, the tempo shown and
  965. // saved unchanged; a temporary state (not saved, exports play at the normal speed)
  966. void setHalfSpeed (bool on) noexcept { transport.playSpeed.store (on ? 0.5 : 1.0, std::memory_order_relaxed); }
  967. bool isHalfSpeed() const noexcept { return transport.playSpeed.load (std::memory_order_relaxed) != 1.0; }
  968. // MIDI controller profiles (round 190aw, core/ControllerSession.h): the devices that run one, and LYNX as they see
  969. // it (the main window's bridge; null when it closes).
  970. ControllerIo& getControllers() noexcept { return controllerIo; }
  971. const ControllerIo& getControllers() const noexcept { return controllerIo; }
  972. void setControllerSurface (controller::Surface* surface);
  973. // The user's controller profiles (*.lynxctl).
  974. static juce::File controllerProfilesFolder();
  975. // Reads the profiles again (Settings › MIDI "Refresh device list") and moves the devices to them.
  976. void reloadControllerProfiles();
  977. // Values for parameters as a MIDI link sets them: one edit outside the undo history; plugin parameters go to the
  978. // plugin.
  979. void applyTargetValues (const std::vector<std::pair<AutomationTarget, float>>& changes);
  980. // How many undo steps are kept (Settings › General).
  981. void setUndoLevels (int levels);
  982. int getUndoLevels() const noexcept { return (int) maxUndoSteps; }
  983. // round 190rn: the history's memory cap (1 GB; core/SongBytes.h's estimate of each step), another one for checks
  984. void setUndoBytesForTest (std::size_t bytes) { maxUndoBytes = bytes; trimUndoHistory(); }
  985. std::size_t getUndoBytes() const noexcept;
  986. // Document (UI thread)
  987. const Song& getSong() const noexcept { return song; }
  988. // The values automation gives the controls at the playhead while the song plays (issue #12: knobs and faders move
  989. // with their automation, as in FL). Refreshed at most once per UI frame, on the UI thread only; the audio thread
  990. // does no extra work for it. An editor shows `shown (target, its Song value)` and repaints when the generation
  991. // changes.
  992. const AutomationDisplay& getAutomationDisplay();
  993. // the time the last refresh took (ms), for --perf style measurements
  994. double getAutomationDisplayMs() const noexcept { return automationDisplayCostMs; }
  995. void setSong (Song newSong); // new/opened project: clears the history
  996. // Round 190la (QA-10): setSong decodes the song's samples in parallel first (round perfgate190id). An export's own
  997. // engine skips that: the engine it copies the song from holds them decoded already, and what the parallel pass found
  998. // missing there (the full originals of stretched clips, which the racks never keep) was decoded again only to be
  999. // dropped after the rack build: +60-120 MB of peak memory on Windows (Future House, Stroll Up).
  1000. void setParallelSampleDecode (bool on) noexcept { parallelSampleDecode = on; }
  1001. // "Open without third-party plugins" (round 190ap, core/PluginHold.h): the project opens with every hosted plugin
  1002. // switched off (none is created; each slot keeps its saved settings untouched, also through a save). The next
  1003. // project this engine opens the plain way (setSong, an import) ends the mode.
  1004. void setSongWithPluginsOff (Song newSong);
  1005. bool pluginsOff() const; // the mode is on and this engine's project is the one it is for
  1006. std::vector<pluginhold::Use> hostedPluginUses() const; // the song's hosted plugins, each marked off or on
  1007. // Switches the plugin `id` back on ("" = all of them, which ends the mode): its slots are created from the settings
  1008. // in the project. Returns how many slots were built again.
  1009. int switchPluginOn (const std::string& id);
  1010. bool channelPluginOff (int channel) const noexcept { return std::find (channelsOff.begin(), channelsOff.end(), channel) != channelsOff.end(); }
  1011. bool insertPluginOff (int track) const noexcept { return std::find (insertsOff.begin(), insertsOff.end(), track) != insertsOff.end(); }
  1012. // Round 190op (P4, LYNX extra): Deactivate. A deactivated channel / insert (by hand, or one that plays only into a
  1013. // deactivated insert: core/TrackStates.h deactivate::effective) is not loaded and carries silence, as of the last
  1014. // publish. setDeactivated switches the given channels and inserts off or on again, one undo step; switching off first
  1015. // keeps what their running plugins hold (capturePluginStates), so Reactivate loads the same state.
  1016. bool channelDeactivated (int channel) const noexcept
  1017. {
  1018. return channel >= 0 && channel < (int) deactivatedChannels.size() && deactivatedChannels[(std::size_t) channel] != 0;
  1019. }
  1020. bool insertDeactivated (int track) const noexcept
  1021. {
  1022. return track >= 0 && track < (int) deactivatedInserts.size() && deactivatedInserts[(std::size_t) track] != 0;
  1023. }
  1024. void setDeactivated (const std::vector<int>& channels, const std::vector<int>& inserts, bool off);
  1025. // Edits the song and publishes it to audio. `undoable` edits go into the history;
  1026. // all edits made while the same mouse click is held down
  1027. // (dragging a note, turning a knob) become a single step.
  1028. void editSong (const std::function<void (Song&)>& edit, bool undoable = true);
  1029. // Round 190td (QUEUE 0.1.33 item 72): the same, naming the undo step's action (core/UndoNames.h: FL's names in the
  1030. // Pattern layout, Live's in Clip-launch). Without a name the step is named from what changed (core/History.h).
  1031. void editSong (undonames::Action action, const std::function<void (Song&)>& edit, bool undoable = true)
  1032. {
  1033. nameNextStep (action);
  1034. editSong (edit, undoable);
  1035. }
  1036. // Names the undo step of the next undoable edit (or the open gesture's step, while it has no name yet). A gesture
  1037. // keeps the first name it gets. Cleared by the next edit, undoable or not.
  1038. void nameNextStep (undonames::Action action) noexcept { pendingAction = action; }
  1039. // `const AudioEngine::NamedEdit n (engine, undonames::Action::noteTranspose);` around code that edits through helpers
  1040. struct NamedEdit
  1041. {
  1042. NamedEdit (AudioEngine& e, undonames::Action a) noexcept : engine (e), previous (e.scopedAction) { engine.scopedAction = a; }
  1043. ~NamedEdit() { engine.scopedAction = previous; }
  1044. NamedEdit (const NamedEdit&) = delete;
  1045. NamedEdit& operator= (const NamedEdit&) = delete;
  1046. AudioEngine& engine;
  1047. undonames::Action previous;
  1048. };
  1049. // One undo step per mouse gesture (queue item 73, round 190jv): an editor opens a gesture at its mouseDown and closes
  1050. // it when its mouseUp returns (UndoGesture below); every undoable edit in between (each move of a drag, the
  1051. // autoscroll's, the drop at mouseUp) shares the gesture's first undo step. Without an open gesture the engine falls
  1052. // back to the press of the main mouse, which only real mouse presses set: events from another input source (touch,
  1053. // pen, a driven test route) gave one step per move there. A gesture whose mouseUp never came (its component went
  1054. // away) ends by itself at the next edit made with no mouse button down.
  1055. void beginUndoGesture() noexcept;
  1056. void endUndoGesture() noexcept;
  1057. bool isUndoGestureOpen() const noexcept { return gestureOpen; }
  1058. // mouseDown: `const AudioEngine::UndoGesture g (engine, AudioEngine::UndoGesture::begin);`, first line of mouseUp:
  1059. // `const AudioEngine::UndoGesture g (engine, AudioEngine::UndoGesture::end);` (closes when mouseUp returns)
  1060. struct UndoGesture
  1061. {
  1062. enum Kind { begin, end };
  1063. UndoGesture (AudioEngine& e, Kind k) noexcept : engine (e), kind (k)
  1064. {
  1065. if (kind == begin)
  1066. engine.beginUndoGesture();
  1067. else
  1068. engine.gestureEnding = true; // (mouseUp's own edits: the button is already up, still the gesture's)
  1069. }
  1070. ~UndoGesture()
  1071. {
  1072. if (kind == end)
  1073. engine.endUndoGesture();
  1074. }
  1075. UndoGesture (const UndoGesture&) = delete;
  1076. UndoGesture& operator= (const UndoGesture&) = delete;
  1077. AudioEngine& engine;
  1078. Kind kind;
  1079. };
  1080. // FL's General › "Detach all new plugins" (issue #116; a UI setting, off by default as in FL): the plugins an edit
  1081. // adds start Detached (detachNewPlugins in core/Song.h)
  1082. void setDetachNewPlugins (bool on) noexcept { detachNewPluginsOn = on; }
  1083. bool detachesNewPlugins() const noexcept { return detachNewPluginsOn; }
  1084. // For an edit that moves or removes channels, mixer tracks or effect slots (issue #32, PR #37): the live plugin
  1085. // settings are copied into the Song first, so the undo step has them; the moved plugins keep their instances (the
  1086. // rack matches them by instance tag, round 168s).
  1087. void editSongStructural (const std::function<void (Song&)>& edit);
  1088. // An edit that gives the patterns other indices (sort, move): one undo step like editSong, but without
  1089. // followPatternLengths, which compares by index and would resize clips that were sized by hand (round 177d).
  1090. void editSongPatternOrder (const std::function<void (Song&)>& edit);
  1091. // An edit that changes only levels (mixer volume / pan / separation, channel volume / pan), e.g. a fader drag: one
  1092. // undo step per press like editSong, but the playing snapshot takes the values at once without a rebuild (round
  1093. // 171c); the full publish follows when the mouse is released. Anything else falls back to editSong.
  1094. void editLevels (const std::function<void (Song&)>& edit, bool undoable = true);
  1095. // the publish editLevels deferred, now (tests; the timer does it after a drag)
  1096. void flushLevels();
  1097. std::uint64_t getLevelEditCount() const noexcept { return levelEdits; }
  1098. // editLevels notifies this one only (the engine's own change message follows with the full publish after the drag):
  1099. // the ~45 views listening to the engine would otherwise all repaint at every mouse move. The views that show
  1100. // levels (Mixer strips, Channel Rack) listen to it too.
  1101. juce::ChangeBroadcaster& getLevelsBroadcaster() noexcept { return levelsChanged; }
  1102. // + 1 at every full publish (not at a level-only edit): listeners can tell a drag's level change from the rest
  1103. std::uint64_t getPublishCount() const noexcept { return publishCount; }
  1104. // + 1 at every setSong (a project opened, imported or made new; round 190oo, CS O-3: views that set something up once
  1105. // per opened project, e.g. the Clip-launch arrangement's folded automation lanes)
  1106. std::uint64_t getOpenCount() const noexcept { return openCount; }
  1107. // Changes since the last save/open (for the "*" in the title and the "save changes?" prompt).
  1108. bool isModified() const noexcept { return modified; }
  1109. void markSaved() noexcept { modified = false; sendChangeMessage(); }
  1110. void markModified() noexcept { modified = true; sendChangeMessage(); } // e.g. a backup was opened in place of the project
  1111. bool canUndo() const noexcept { return sessionHistory ? ! sessionUndo.empty() : ! undoStack.empty(); }
  1112. bool canRedo() const noexcept { return sessionHistory ? ! sessionRedo.empty() : ! redoStack.empty(); }
  1113. void undo();
  1114. void redo();
  1115. // round 190rw (Q1): an editor's mouse gesture is held down (a clip, a note, a step being dragged). Undo, redo and the
  1116. // history jumps wait for its release: they replaced the song under the drag, whose indices then wrote past the end
  1117. // of the playlist ("double free or corruption", a crash in 0.1.31.2 too)
  1118. bool isEditGestureHeld() const noexcept
  1119. {
  1120. return gestureOpen && gestureRealMouse && juce::ModifierKeys::currentModifiers.isAnyMouseButtonDown();
  1121. }
  1122. // Online Sessions P2 (round 169b): a live session's copy of the song changed by someone else's edit — like setSong,
  1123. // but the history stays, the project stays modified and nothing becomes an undo step.
  1124. void applyRemote (Song remote);
  1125. // Undo per user (ONLINE_SESSIONS.md §1.4): while on, undo / redo bring back only this person's own entities (each one
  1126. // still as his step left it), never other people's edits made since. `onSkipped` names what had to stay.
  1127. void setSessionHistory (bool on);
  1128. bool hasSessionHistory() const noexcept { return sessionHistory; }
  1129. std::function<void (const juce::StringArray& skipped)> onSessionUndoSkipped;
  1130. std::uint64_t getSongStamp() const noexcept { return songStamp; }
  1131. // Round 190rs (G-31): the song stamp an undo, a redo or a history jump published last (0: none yet). An editor that
  1132. // sees it newer than its last look re-finds its selection by content (core/SelectionKeep.h).
  1133. std::uint64_t getHistoryStepStamp() const noexcept { return historyStepStamp; }
  1134. // Undo history as a list of states, oldest first: the undo steps, the current state, then the redo
  1135. // steps. Each entry is named after what changed from the previous one (core/History.h).
  1136. int getHistorySize() const noexcept
  1137. {
  1138. return sessionHistory ? (int) (sessionUndo.size() + 1 + sessionRedo.size()) : (int) (undoStack.size() + 1 + redoStack.size());
  1139. }
  1140. int getHistoryPosition() const noexcept { return sessionHistory ? (int) sessionUndo.size() : (int) undoStack.size(); }
  1141. ChangeLabel getHistoryLabel (int index) const; // index 0 = the oldest state kept
  1142. void jumpToHistory (int index);
  1143. // Channel selected in the Channel Rack (target of the Piano Roll and keyboard). UI thread.
  1144. int getSelectedChannel() const noexcept { return selectedChannel; }
  1145. void setSelectedChannel (int channel); // selects only this channel
  1146. // Multi-selection in the Channel Rack (sorted). The selected channels all receive live MIDI input;
  1147. // `primary` (one of them) is the Piano Roll / keyboard target above.
  1148. const std::vector<int>& getSelectedChannels() const noexcept { return selectedChannels; }
  1149. void setChannelSelection (std::vector<int> channels, int primary);
  1150. // Imports a .flp, locating the FL installation to find the samples.
  1151. // Returns false and fills `error` on failure. `relocations` (saved sample path → file to use) are the samples
  1152. // the user located; with `asEdit` the result replaces the song as one undoable step instead of a new project.
  1153. bool importFlpFile (const juce::File& file, juce::String& error, const std::map<std::string, std::string>& relocations = {},
  1154. bool asEdit = false);
  1155. // Round 190pe (P11, File › Import › Tracks from another project): another project read into a Song of its own, by the
  1156. // importer of its format (.lynx, .flp, .als, .flm, .band, .blx, DAWproject, modules), its plugins found or
  1157. // substituted as an import does. The open song is not touched. `decoded` keeps the decoded samples until the edit
  1158. // that brings the tracks in has built the rack. Message thread.
  1159. struct OtherProject
  1160. {
  1161. Song song;
  1162. FlpImportReport report;
  1163. juce::StringArray missingPlugins;
  1164. std::vector<std::shared_ptr<const SampleData>> decoded;
  1165. };
  1166. bool readOtherProject (const juce::File& file, OtherProject& out, juce::String& error);
  1167. // The same import in steps, so a window can show progress while it runs (round 112): `prepareFlpImport` reads,
  1168. // parses and imports the project and decodes its samples in parallel — no plugin is touched, so it may run on any
  1169. // thread; `preloadPlugins` creates the project's hosted plugins one at a time (message thread; call it until it
  1170. // returns false); `finishFlpImport` adopts the result as the song (message thread). Phase times go to core/LoadTrace.
  1171. struct PreparedFlp
  1172. {
  1173. bool ok = false;
  1174. juce::String error;
  1175. Song song;
  1176. FlpImportReport report;
  1177. std::vector<std::shared_ptr<const SampleData>> decoded; // kept alive until the rack is built
  1178. std::vector<PluginRef> pluginQueue; // hosted plugins to create, in rack order
  1179. std::size_t pluginsDone = 0;
  1180. bool adopted = false;
  1181. juce::StringArray missing, matched, withoutState, substituted;
  1182. struct Use
  1183. {
  1184. std::string name, user;
  1185. bool instrument = false;
  1186. };
  1187. std::vector<Use> uses;
  1188. };
  1189. // Settings › General: a Live set's Session clips go to the clip grid (false, the default) or the Playlist (round 181c)
  1190. static inline std::atomic<bool> alsSessionOnPlaylist { false };
  1191. static void prepareFlpImport (const juce::File& file, const std::map<std::string, std::string>& relocations, SampleLibrary& library,
  1192. PreparedFlp& out);
  1193. // one hosted plugin of the queue (message thread); false when the queue is done
  1194. bool preloadNextPlugin (PreparedFlp& prepared);
  1195. // Before importing the open project again: leaves out of `prepared`'s plugin queue those the song already runs
  1196. // with the same settings (the rack keeps them).
  1197. void keepRunningPlugins (PreparedFlp& prepared);
  1198. bool finishFlpImport (PreparedFlp&& prepared, bool asEdit);
  1199. // --- real-time bounce (round 165c: Export › "Render through the hardware in real time") ---
  1200. // The song plays through the audio device from `startTick` (song mode; past its end and through the loop region,
  1201. // without starting over) while the Master's output is recorded: hardware inserts send to and return from their gear
  1202. // as they do while playing. Message thread; returns an error (empty: started).
  1203. juce::String startRealtimeBounce (double startTick);
  1204. // What the Master played since the last call, from the first sample the song played (one consumer thread).
  1205. int pullRealtimeBounce (std::vector<float>& left, std::vector<float>& right) { return meters.bounceTap.pull (left, right); }
  1206. bool isBouncing() const noexcept { return bouncing; }
  1207. // While bouncing: the transport still plays (false: the user stopped it), the delay compensation's total at the
  1208. // start, the device's dropouts and the frames the tap lost since the start.
  1209. bool bounceStillPlaying() const noexcept { return transport.playing.load(); }
  1210. int bounceLatency() const noexcept { return bounceStartLatency; }
  1211. int bounceDropouts() const;
  1212. // Stops playback and puts the transport back as it was (message thread).
  1213. void finishRealtimeBounce();
  1214. // Renders without an audio device. Writes to `output` if not nullptr.
  1215. // After `seconds`, continues for up to `tailSeconds` while there is still sound.
  1216. // `progress(0..1)` returns false to cancel. Returns the peak (used by the self-test),
  1217. // or -1 if cancelled.
  1218. struct RenderOptions
  1219. {
  1220. double seconds = 10.0;
  1221. double sampleRate = 44100.0;
  1222. juce::AudioFormatWriter* output = nullptr;
  1223. std::function<bool (double)> progress; // 0..1; false cancels
  1224. double tailSeconds = 0.0;
  1225. int trimSamples = 0; // PDC: discards this much from the start and renders the same amount extra at the end
  1226. int ditherBits = 0; // > 0: TPDF dither (with noise shaping unless ditherShaping is false) for this bit depth
  1227. bool ditherShaping = true;
  1228. // FL's "HQ for all plugins": render qualities and HQ switches on (off: the playback quality)
  1229. bool hqAllPlugins = true;
  1230. // receives every rendered block after the PDC trim (left, right, frames), like `output` does
  1231. std::function<void (const float*, const float*, int)> capture;
  1232. // trim the delay compensation's latency as the plugins report it after the warm-up (adds to trimSamples)
  1233. bool trimPdc = false;
  1234. // Export "Plugin warm-up" (round 155, core/PluginWarmup.h): with hosted plugins in the song, silent blocks are
  1235. // processed and thrown away before the render until the plugins have settled
  1236. bool pluginWarmUp = true;
  1237. warmup::Settings warmUp;
  1238. // false: samples above 0 dBFS are clamped to ±1 before the dither / the file (integer formats, Ogg)
  1239. bool keepOvers = false;
  1240. // FL never puts the metronome in an export (round 165z-a2, measured): off, the click is left out even with
  1241. // the metronome on. (The selftest turns it on to measure the click.)
  1242. bool includeMetronome = false;
  1243. // Round 190gj (several files from one render: StemPass, engine/Exporter.h). With `shared`, nothing goes to
  1244. // `output` / `capture` and the render's own end does not apply: after the warm-up shared->start (latency) is
  1245. // called (the latency the plugins report then), each block's size comes from shared->nextBlock (done) (0 = the
  1246. // end) and its output, as the graph made it (before the overs are clamped), goes to shared->block.
  1247. struct Shared
  1248. {
  1249. virtual ~Shared() = default;
  1250. virtual void start (int latency) = 0;
  1251. virtual int nextBlock (std::int64_t done) = 0;
  1252. virtual void block (const juce::AudioBuffer<float>& raw, std::int64_t done, int n) = 0;
  1253. };
  1254. Shared* shared = nullptr;
  1255. // Round 190gh (B7): > 0 renders exactly this many samples after the PDC trim (music, then the tail, without
  1256. // stopping at the tail's silence): the stems of one export all get the mix's length, as FL's split render
  1257. std::int64_t exactSamples = 0;
  1258. // Issue #289 (round 190sw, Export › Channels › "Hardware outputs"): set, the inserts' hardware output targets play
  1259. // during the render, and each block (render sample `done`, `n` samples; the PDC trim is `trim` samples from the
  1260. // start) comes here as the graph made it, before the overs are clamped: the Master's output and the device-channel
  1261. // buses (HardwareOutput::written). Not with `shared`.
  1262. std::function<void (const juce::AudioBuffer<float>& master, const HardwareOutput& buses, std::int64_t done, int n, std::int64_t trim)> hardware;
  1263. };
  1264. static constexpr int renderBlockSize = 512; // renderOffline's blocks
  1265. // What renderOffline does after the graph with these options when the plugins report `latency` (round 190gj: the
  1266. // single-pass stems make each file with the same setup).
  1267. static RenderStream::Setup streamSetup (const RenderOptions& options, int latency);
  1268. float renderOffline (const RenderOptions& options);
  1269. // How many offline renders run now, in any engine (round 168s, issue #32). While one runs, the engine that plays
  1270. // through the audio device stops and outputs silence without processing (FL stops playback while it renders): the
  1271. // project's live plugins never run next to their export copies (plugins that share state between instances cut
  1272. // notes in the file) and no CPU goes to them (the glitches heard until the progress bar ended).
  1273. static std::atomic<int>& offlineRendersRunning() noexcept;
  1274. // timings of the last renderOffline (diagnostics): the audio graph and the file writing
  1275. struct RenderStats
  1276. {
  1277. double graphMs = 0.0, writeMs = 0.0;
  1278. warmup::Result warmUp; // the plugin warm-up before the render (blocks == 0: none ran)
  1279. int trimmedSamples = 0; // the PDC trim used
  1280. double araWaitMs = 0.0; // round 190kx: how long the render waited for ARA plugins to finish their analysis
  1281. };
  1282. RenderStats getLastRenderStats() const noexcept { return lastRenderStats; }
  1283. float renderOffline (double seconds, double sampleRate, juce::AudioFormatWriter* output = nullptr)
  1284. {
  1285. RenderOptions o;
  1286. o.seconds = seconds;
  1287. o.sampleRate = sampleRate;
  1288. o.output = output;
  1289. return renderOffline (o);
  1290. }
  1291. int getNumGraphConnections() const { return (int) graph.getConnections().size(); }
  1292. // Time spent in each instrument and effect (the Plugin performance monitor); nullptr without the rack node.
  1293. ProcessTimes* getProcessTimes() noexcept;
  1294. // Latest output samples (mono), for the oscilloscope. UI thread.
  1295. void copyScope (float* destination, int count) const noexcept;
  1296. // round 190mv (DF-24, FL's output panel › Oscilloscope › Stereo): the same samples' side, (L - R) / 2, so a stereo
  1297. // scope shows L = mid + side and R = mid - side
  1298. void copyScopeSide (float* destination, int count) const noexcept;
  1299. static constexpr int scopeSize = 2048;
  1300. // round 190kn (FL's output panel, DF-23): the peak of the device output's left (0) / right (1) side since the last
  1301. // read, for the toolbar's stereo bars. One reader (the toolbar's output display). UI thread.
  1302. float takeOutputPeak (int channel) noexcept { return outputPeak[(std::size_t) (channel & 1)].exchange (0.0f, std::memory_order_relaxed); }
  1303. // Real-time health of the audio callback (REA round 87): callbacks over their deadline, late device calls, load.
  1304. const RtStats& getRtStats() const noexcept { return rtStats; }
  1305. RtStats& getRtStats() noexcept { return rtStats; }
  1306. const OverloadGuard& getOverloadGuard() const noexcept { return overloadGuard; } // (round 190ok)
  1307. // round 190kb: the renderer's worker pool (its waiting statistics for --uiperf; null without workers)
  1308. const WorkerPool* getWorkerPool() const noexcept { return workers.get(); }
  1309. // What takes the most audio CPU: channels and insert effects, as a share of real time over the last ~2 s of
  1310. // playback, heaviest first. UI thread.
  1311. struct UnitLoad
  1312. {
  1313. juce::String name;
  1314. double load = 0.0; // CPU time / audio time (summed over the worker threads)
  1315. double longestMs = 0.0; // the longest single call in the window
  1316. };
  1317. const std::vector<UnitLoad>& getHeaviestUnits() const noexcept { return heaviestUnits; }
  1318. // Round 190ts: sleep while stopped (RackRenderer::setStoppedSleep; on by default in an engine with a device, unless
  1319. // LYNX_STOPPED_SLEEP=0), and the CPU time a channel / an insert slot took so far (the renderer's unit profile, ns)
  1320. void setStoppedSleep (bool on) noexcept;
  1321. std::uint64_t channelUnitNanoseconds (int channel) const noexcept;
  1322. std::uint64_t effectUnitNanoseconds (int track, int slot) const noexcept;
  1323. // Round 190gg (B5): the dropouts (buffer underruns) since the start, when the last one was and why (core/Dropouts.h):
  1324. // the processing (with the slowest channel / effect of that block) or the driver / system (late while the load was
  1325. // low). Kept by the engine's timer. Message thread.
  1326. struct DropoutInfo
  1327. {
  1328. std::uint64_t count = 0, processing = 0, system = 0;
  1329. long long secondsAgo = -1; // since the last one (−1: none yet)
  1330. dropouts::Cause cause = dropouts::Cause::none;
  1331. juce::String slowest; // "Insert 2 / 1 Serum", a channel's name; empty = not known
  1332. double slowestMs = 0.0, load = 0.0; // that call's length; the highest load around it (1 = the whole deadline)
  1333. double bufferMs = 0.0; // the device's buffer
  1334. };
  1335. DropoutInfo dropoutInfo() const;
  1336. // How regularly the message thread runs the engine's 30 Hz timer (a saturated UI delays it). UI thread.
  1337. struct UiPulse
  1338. {
  1339. int calls = 0;
  1340. double maxGapMs = 0.0;
  1341. };
  1342. UiPulse takeUiPulse() noexcept { return std::exchange (uiPulse, {}); }
  1343. // Writes `state` (a createStateXml() taken earlier; nullptr = none was saved) back as the saved device and stops
  1344. // saving later changes: a test run (--rtstress --type ...) leaves the user's device as it found it.
  1345. void restoreAudioDeviceState (const juce::XmlElement* state);
  1346. // Device, buffer, deadline and the callback statistics in a few lines (CPU meter hint, glitch log, --rtstress).
  1347. juce::String describeRealtime (bool withUnits = true) const;
  1348. // render-ahead's counters (round 190gq, core/RenderAhead.h; nullptr before the graph exists)
  1349. const renderahead::Stats* renderAheadStats() const noexcept;
  1350. // tests: render-ahead whenever it can, whatever the project's load (the app starts it when the load needs it)
  1351. void setRenderAheadAlways (bool always) noexcept;
  1352. // UI: a hosted plugin's editor opened / closed (`key` = its host): its channel (`find`, the PluginRef in the song) or
  1353. // insert (`track` >= 0) is rendered in real time while it is open (render-ahead, round 190gq)
  1354. void setEditorOpen (const void* key, std::function<PluginRef* (Song&)> find, int track, bool open);
  1355. // Settings › Audio "Driver settings…": shows the device's own panel (ASIO) and, when the driver says its settings
  1356. // changed, reopens it with them. The device object is replaced (its driver re-read), so the old pointer is never
  1357. // used after the close (0.1.17 / 0.1.18 called the deleted device: issues #12 and #13), and the buffer size the
  1358. // panel chose is kept (the reopen asks for the driver's preferred size instead of the size LYNX had before, which
  1359. // silently undid an ASIO4ALL / FL ASIO buffer change). Returns true when the device was reopened. Message thread.
  1360. static bool showDriverPanel (juce::AudioDeviceManager& devices);
  1361. // --selftest "driver_panel": showDriverPanel with a fake device whose panel changes its buffer (and one whose panel
  1362. // changes nothing). "OK" or what went wrong.
  1363. static juce::String driverPanelSelfTest();
  1364. // --selftest "device_change" / --devicechangetest (issue #134, engine/DeviceChangeTest.cpp): a playing project while
  1365. // the output device, its sample rate and its buffer size change, on stand-in devices with real callback threads.
  1366. // "OK (...)" or "ERROR ...". `everyUnit`: every instrument and effect LYNX can make here (else a handful);
  1367. // `pluginFiles`: hosted plugins to add; `log` receives a line per change.
  1368. static juce::String deviceChangeSelfTest (int switches, bool everyUnit, const juce::StringArray& pluginFiles = {},
  1369. const std::function<void (const juce::String&)>& log = {});
  1370. // --selftest "export_parity" / --exportparitytest (round 190gh, B7; engine/ExportParityTest.cpp): the export against
  1371. // playback through a stand-in audio device (null below −90 dBFS), stems of every mode starting together with one
  1372. // length and adding up to the mix, group effects and multi-output inserts in "one per mixer insert", the delay
  1373. // compensation's trim on and off. "OK (...)" or "ERROR ...". `log` receives a line per check.
  1374. static juce::String exportParitySelfTest (const std::function<void (const juce::String&)>& log = {});
  1375. // Round 190ub (issue #371): armed inserts record the audio routed into them with no input device, each take equal to its
  1376. // insert's export and placed to the sample (src/engine/InsertRecord190ubTest.cpp; --round190ubtest, --selftest "round190ub")
  1377. static juce::String insertRecord190ubSelfTest (const std::function<void (const juce::String&)>& log = {});
  1378. // Round 190ud (issue #375): the channel's PITCH reaches what already sounds — Sampler notes, audio clips, keep-length
  1379. // notes on their shifter — offline (an automation step) and live (the knobs, on a stand-in device)
  1380. // (src/engine/SamplerPitch190udTest.cpp; --round190udtest, --selftest "round190ud")
  1381. static juce::String samplerPitch190udSelfTest (const std::function<void (const juce::String&)>& log = {});
  1382. // Round 190un (issue #381): a tempo change never blocks the message thread on a long warped clip's stretch — 20 tempo
  1383. // changes in a second, stopped and playing, at 44.1 / 48 kHz, other stretch modes, a Clip-launch clip; the final render
  1384. // matches a fresh one (src/engine/TempoStretch190unTest.cpp; --round190untest, --selftest "round190un"). `seconds`:
  1385. // the long file's length (233 = the reporter's 3:53 song).
  1386. static juce::String tempoStretch190unSelfTest (const std::function<void (const juce::String&)>& log = {}, double seconds = 233.0);
  1387. // Whether every deferred stretch render is done and built into the rack (round 190un; tests)
  1388. bool stretchesSettled() const;
  1389. // How many deferred stretch renders were asked for, started, cancelled, kept (round 190un; tests)
  1390. stretchdefer::Queue::Counts stretchRenderCounts() const;
  1391. // Round 190jb: exports with the live engine's plugin instances (engine/Exporter.h LiveExportHold), on a stand-in device:
  1392. // LYNX's own units render the same with and without the hold; a hosted plugin whose sound depends on its instance
  1393. // (`plugins`: VST3 / CLAP files, e.g. the LYNX Test Synth with LYNX_TEST_SYNTH_SEED=1, Surge XT) exports what
  1394. // playback played; playback after the export plays as before it; the plugins get their state and rate back.
  1395. static juce::String exportLiveSelfTest (const std::function<void (const juce::String&)>& log = {}, const juce::StringArray& plugins = {});
  1396. // Self-tests (round 190hn, engine/ShortExportTest.cpp): an engine made without a device plays through a stand-in one
  1397. // (engine/StandInAudioDevice.h: callbacks of `blockSize` from its own thread, faster than real time). Message thread;
  1398. // empty = opened. `tap` (round 190uc): receives each callback's output on the device thread (what a device would play).
  1399. // `pauseMs`: the pause between callbacks (2: a few times faster than real time).
  1400. juce::String openStandInDevice (double sampleRate, int blockSize, std::function<void (const juce::AudioBuffer<float>&)> tap = {}, int pauseMs = 2);
  1401. void closeStandInDevice();
  1402. // %APPDATA%\LYNX\audio-glitches.log: a line each time callbacks run over their deadline (at most every 2 s).
  1403. static juce::File glitchLogFile();
  1404. // Total latency compensated by PDC (at the Master output), in samples.
  1405. int getLatencySamples() const noexcept { return lastPublishedShape.pdc.total; }
  1406. // Round 190gj (single-pass stems): the latencies the published PDC plan was made from (the channels' instruments,
  1407. // then each insert's slots), for computing the plan of a changed copy of the song.
  1408. void getPublishedLatencies (std::vector<int>& channels, std::vector<std::vector<int>>& slots) const;
  1409. // The render taps of the rack (RackRenderer::RenderTaps; nullptr = none). Set around renderOffline only.
  1410. void setRenderTaps (RackRenderer::RenderTaps* taps) noexcept;
  1411. // The last published PDC plan (per-track latencies: outLat, inAlign). Message thread.
  1412. const PdcPlan& getPdcPlan() const noexcept { return lastPublishedShape.pdc; }
  1413. // "Low latency while recording" (round 190aq): whether slot `slot` of insert `track` is bypassed for it now, the
  1414. // latency it would add (samples, 0 = not bypassed), and how many slots are bypassed in all. Message thread.
  1415. bool isSlotLowLatencyBypassed (int track, int slot) const noexcept { return lowlatency::bypassed (lastPublishedShape.lowLatencySlots, track, slot); }
  1416. int lowLatencyBypassedLatency (int track, int slot) const noexcept;
  1417. int lowLatencyBypassedCount() const noexcept;
  1418. private:
  1419. bool detachNewPluginsOn = false;
  1420. void audioDeviceIOCallbackWithContext (const float* const* inputChannelData,
  1421. int numInputChannels,
  1422. float* const* outputChannelData,
  1423. int numOutputChannels,
  1424. int numSamples,
  1425. const juce::AudioIODeviceCallbackContext& context) override;
  1426. void audioDeviceAboutToStart (juce::AudioIODevice* device) override;
  1427. void audioDeviceStopped() override;
  1428. void timerCallback() override;
  1429. void handleIncomingMidiMessage (juce::MidiInput* source, const juce::MidiMessage& message) override;
  1430. // the input's handling; `deviceName` is the source's name (an injected message: given, or none)
  1431. void handleMidiInput (juce::MidiInput* source, const std::string& deviceName, const juce::MidiMessage& message);
  1432. void enableAllMidiInputs();
  1433. void saveAudioDeviceState();
  1434. void updateRecording();
  1435. void updateAudioRecording();
  1436. void updateAutomationRecording (bool active);
  1437. void startAudioTake();
  1438. void finishAudioTake();
  1439. double estimatedPositionNow() const noexcept;
  1440. AutomationDisplay automationDisplay;
  1441. std::uint64_t historyStepStamp = 0; // round 190rs: see getHistoryStepStamp
  1442. std::uint64_t songStamp = 1; // + 1 at every publishSong (the display's tables follow the Song)
  1443. double automationDisplayAtMs = -1.0e9; // when it was last refreshed
  1444. double automationDisplayCostMs = 0.0;
  1445. void buildInitialGraph();
  1446. void choosePreferredDriver(); // a first start on Linux: PipeWire, then JACK, then ALSA (round 161)
  1447. void chooseSafeBufferSize();
  1448. void updateRealtimeStats(); // timer: unit loads over a window, glitch log
  1449. RtStats rtStats;
  1450. OverloadGuard overloadGuard; // round 190ok: FL's Settings › Audio › "Safe overloads" (core/OverloadGuard.h)
  1451. // Round 190hn (engine/ExportParityTest.cpp): called on the audio thread right after the device callback took the
  1452. // position requests (Rewind, a seek), so the self-test can make the UI's start land exactly there; nullptr otherwise
  1453. std::atomic<void (*) (void*)> afterPositionRequests { nullptr };
  1454. void* afterPositionRequestsContext = nullptr;
  1455. std::vector<UnitLoad> heaviestUnits;
  1456. dropouts::Log dropoutLog;
  1457. juce::String unitDisplayName (std::uint32_t unit) const; // core/Dropouts.h unit → "Kick", "Insert 2 / 1 Serum"
  1458. std::vector<std::uint64_t> lastChannelNs, lastEffectNs;
  1459. std::uint64_t lastProcessedSamples = 0;
  1460. double lastUnitsWindowMs = 0.0, lastUiPulseMs = 0.0;
  1461. UiPulse uiPulse;
  1462. int latencyRepublishes = 0; // PDC re-plans because a unit's latency changed (diagnostics)
  1463. juce::String lastLatencyChange;
  1464. // hardware inserts (round 165c): ping results applied to the slots (whether an editor is open or not), and the device
  1465. // setup they were measured for
  1466. void applyHardwareInsertPings();
  1467. std::map<const void*, int> hwPingSerials; // running insert -> the last ping result seen
  1468. std::string lastSetupKey;
  1469. std::vector<HardwareInsertRef> hwNotice;
  1470. int hwTicks = 0;
  1471. bool bouncing = false;
  1472. int bounceStartLatency = 0, bounceStartXruns = 0;
  1473. double bounceReturnTick = 0.0;
  1474. bool bounceRestoreMode = false;
  1475. bool checkHardwareInserts = false;
  1476. std::uint64_t loggedOver = 0, loggedLate = 0;
  1477. double lastLogMs = 0.0;
  1478. class PreviewPlayer* preview = nullptr; // graph node (owned by the graph)
  1479. int clipPreviewChannel = -1, clipPreviewKey = -1; // the clip previewed through its channel (round 190ey), -1 = none
  1480. std::uint64_t clipPreviewSerial = 0;
  1481. double previewVolume = 1.0;
  1482. // "Preview in time" (round 190aq)
  1483. bool previewInTime = false;
  1484. bool fullSamplePreview = false; // round 190iz: FL's Browser menu "Full sample preview" (off)
  1485. double previewStartFraction = 0.0; // round 190iz: the preview asked for now (previewFile)
  1486. bool previewFull = true;
  1487. void setPreviewRange (const SampleData* sample); // (before each playBrowser of a real sample)
  1488. PreviewTiming previewTiming;
  1489. std::uint64_t previewSerial = 0; // raised by every previewFile: a stale job's result is dropped
  1490. double previewHandedAtMs = 0.0; // when the sample went to the player
  1491. std::shared_ptr<std::atomic<bool>> previewAlive = std::make_shared<std::atomic<bool>> (true);
  1492. std::map<juce::String, previewtempo::Found> previewTempos; // by path (the file's tempo, found once)
  1493. struct PreviewStretch
  1494. {
  1495. juce::String path;
  1496. double ratio = 1.0;
  1497. std::shared_ptr<const SampleData> sample;
  1498. };
  1499. std::vector<PreviewStretch> previewStretches; // the last few stretched previews
  1500. void startPreviewInTime (const juce::String& path, std::shared_ptr<const SampleData> sample, const PreviewTiming& timing);
  1501. struct PreviewResult
  1502. {
  1503. std::uint64_t serial = 0;
  1504. juce::String path;
  1505. std::shared_ptr<const SampleData> sample, out; // the file, and what plays (the same when not stretched)
  1506. PreviewTiming timing;
  1507. previewtempo::Found found;
  1508. bool detected = false; // the tempo was read from the audio now: kept for the next click
  1509. };
  1510. std::mutex previewResultLock;
  1511. std::vector<PreviewResult> previewResults; // worker → message thread
  1512. double lastPreviewPrepareMs = 0.0;
  1513. void takePreviewResults();
  1514. double editorVolume = 1.0;
  1515. void publishSong();
  1516. void applyLinkPrefs(); // (round 190gl) Link on / off and its options as midiPrefs say
  1517. RackState::Factories rackFactories();
  1518. void adoptPrepared (PreparedFlp& prepared); // the plugins of a prepared import found / substituted (message thread)
  1519. std::unique_ptr<WorkerPool> workers; // extra renderer threads (before the graph, which uses them)
  1520. LynxDeviceManager deviceManager; // (JUCE's, taking the prewarmed ASIO device: round 190go)
  1521. juce::AudioProcessorGraph graph;
  1522. juce::AudioProcessorPlayer player;
  1523. Transport transport;
  1524. MidiSyncIo midiSync; // (before the MIDI callbacks and the audio callback use it)
  1525. AbletonLink abletonLink; // (round 190gl; before the audio callback uses it)
  1526. ControllerIo controllerIo; // (before the MIDI callbacks use it)
  1527. SampleLibrary samples;
  1528. LiveEventQueue liveEvents; // UI -> audio
  1529. LiveEventQueue midiEvents; // MIDI thread -> audio
  1530. InputHeldNotes midiHeld; // MIDI thread: what each held MIDI key started
  1531. // issue #108 (MIDI thread): the MPE controller's zone — its member channels' bend / CC 74 / pressure per note
  1532. // (one decoder: two MPE controllers played at once would share it)
  1533. mpe::Input mpeInput;
  1534. mpe::Zone mpeZone; // the zone of the device's settings mpeInput was last set to
  1535. PedalHold pedalHold; // MIDI thread: FL's foot pedal hold per channel (round 187a)
  1536. std::atomic<bool> footPedalNoteOff { true }; // FL's Settings › MIDI "Foot pedal controls note off" (on)
  1537. std::atomic<std::uint64_t> heldKeyBits[16][2] {}; // keys held per MIDI channel on inputs / the typing piano (chord readout)
  1538. std::atomic<std::uint8_t> heldKeyCount[16][128] {};
  1539. void markHeldKey (int midiChannel, int key, bool on) noexcept;
  1540. std::atomic<int> lastHitKey { 60 };
  1541. std::atomic<std::uint32_t> liveNote { 0 }; // (lastLiveNote)
  1542. std::array<std::atomic<std::uint8_t>, 128> liveNoteVelocities {}; // each key's last note-on velocity
  1543. KeyLedger playedKeys; // UI thread: the keys the typing piano started (after the scale snap)
  1544. SpscQueue<RecordedEvent, 4096> midiRecordQueue; // MIDI thread -> UI (recording)
  1545. // a controller's pitch wheel while recording (MIDI thread -> UI): key = its MIDI channel 0…15, velocity = 0..1;
  1546. // written as the channel's pitch bend automation like a moved knob (issue #12: the bend was heard, not recorded)
  1547. SpscQueue<RecordedEvent, 2048> bendRecordQueue;
  1548. std::map<int, float> liveBends; // UI thread: the last recorded bend of each channel (its "current value")
  1549. void takeRecordedBends();
  1550. struct ControllerEvent
  1551. {
  1552. int cc = 0, channel = 0, value = 0;
  1553. int port = -1; // the input device's port number (Settings > MIDI; round 190bt), -1 = none
  1554. // round 190cs: `cc` 256 + n is key n (a note link; value = the velocity, 0 for its release). seenOnly: a key
  1555. // nothing links, offered to Auto detect only
  1556. bool seenOnly = false;
  1557. };
  1558. SpscQueue<ControllerEvent, 1024> controllerQueue; // MIDI thread -> UI (controllers)
  1559. // the CCs a MIDI link (project or global) uses: they move their parameter and are not also played into the
  1560. // selected channel's instrument (round 162); written by applyControllers, read by the MIDI thread
  1561. std::array<std::atomic<std::uint64_t>, 2> linkedCcs {};
  1562. // the keys a link uses (round 190cs: FL's note links, controller number 256 + key): their presses and releases go
  1563. // to the link instead of the instrument. Written by applyControllers, read by the MIDI thread.
  1564. std::array<std::atomic<std::uint64_t>, 2> linkedNotes {};
  1565. AutomationTarget learning;
  1566. ControllerSeen controllerSeen;
  1567. // round 190ef: the map mode, the control it caught, and each controller's last value (a button's press / release)
  1568. remotemap::Mode mapMode = remotemap::Mode::off;
  1569. std::optional<remotemap::MidiControl> mapCaptured;
  1570. std::map<std::tuple<int, int, int>, int> remoteValues; // (number, channel, port) -> value
  1571. public:
  1572. std::atomic<bool> mapCaptureNotes { false }; // (MIDI thread: in MIDI Map Mode every key goes to applyControllers)
  1573. private:
  1574. // round 190bt: a link's compiled mapping formula, and the smoothing filters of the links being moved
  1575. std::map<std::string, linkformula::Formula> linkFormulas;
  1576. struct LinkSmoothing
  1577. {
  1578. MidiLink link;
  1579. float target = 0.0f;
  1580. linkformula::Smoother filter;
  1581. };
  1582. std::vector<LinkSmoothing> linkSmoothing;
  1583. double linkSmoothingClock = 0.0;
  1584. void stepLinkSmoothing (std::vector<std::pair<AutomationTarget, float>>& changes);
  1585. std::optional<MultilinkSession> multilink;
  1586. bool learningGlobal = false;
  1587. bool controllerLearnTick = false; // a MIDI learn was waiting at this tick's applyControllers (round 190aw)
  1588. bool saveGlobalLinks = false; // only the engine with an audio device (the app) writes the settings file
  1589. bool devicePending = false, midiPending = false, midiOpen = false; // (round 190go: see deferDeviceOpen)
  1590. juce::MidiDeviceInfo savedMidiOutput; // the saved setup's default MIDI output, opened by openMidiDevices
  1591. bool followProjectOnDevice(); // true when the song changed (FL's insert inputs placed on the device)
  1592. void applyControllers();
  1593. std::atomic<int> pendingMarkerNote { -1 }; // MIDI thread -> timer: a "Song marker jump" note
  1594. std::vector<RecordedEvent> uiRecorded; // PC keyboard -> recording
  1595. NoteRecorder recorder;
  1596. // last tweaked parameters and automation recording (REA round 143)
  1597. std::array<AutomationTarget, 2> lastTweaked {};
  1598. struct Touch
  1599. {
  1600. AutomationTarget target;
  1601. double lastMs = 0.0;
  1602. bool held = false;
  1603. std::vector<RecordedValue> pending; // sampled, not yet written
  1604. float liveValue = -1.0f; // an internal controller's value to write instead of the control's (round 190cs)
  1605. bool started = false; // round 190pa (P21, Write): the take's start point was written
  1606. };
  1607. double automationTakeStart = -1.0; // round 190pa (P21): where the automation take started (transport position)
  1608. std::vector<Touch> touches;
  1609. int automationCommitCountdown = 0;
  1610. bool automationTakeHasUndoStep = false;
  1611. std::int64_t automationLoopLength = 0;
  1612. int automationPattern = 0;
  1613. int recordedAutomationPoints = 0;
  1614. bool automationOverrideActive = false; // touched targets override their automation in the renderer
  1615. // FL (issue #125): the targets the user moved since playback last started; their automation does not drive them
  1616. // until it starts again (RackRenderer::setReleasedSlots). Not while recording automation (the touch rule above).
  1617. std::vector<AutomationTarget> releasedTargets;
  1618. bool releasedWasPlaying = false;
  1619. bool liveAutomationOverride = false; // (round 190oa, DL-58)
  1620. void publishReleasedTargets();
  1621. // Song mode, no loop region: once a parameter moved while recording, the song plays on past its end (no wrap to
  1622. // the start) until recording stops, and the take's clip grows with the playhead (issue #12: it cut itself)
  1623. bool automationLinear = false;
  1624. // the same for the whole of a take (FL: Song mode plays on while recording; round 168k)
  1625. bool noteTakeLinear = false;
  1626. std::int64_t lastAutomationTick = -1; // the song position of the take's last update (song mode)
  1627. std::vector<AutomationWrite> takeWrites; // per target: where this take writes (its own clip grows)
  1628. bool takeHasUndoStep = false;
  1629. // Cancel recording (round 187a): the undo depth when this recording pass started, and the steps trimmed off the
  1630. // stack's bottom since then (the depth then still counts them)
  1631. bool recordPassActive = false, recordPassMarked = false, discardAudioTakes = false;
  1632. // rollup 0.1.28 (REA 190hb): the PC stays awake while a recording pass runs (engine/PowerHints.h; message thread)
  1633. std::optional<std::uint32_t> awakeForRecording;
  1634. std::size_t recordPassUndoBase = 0, recordPassTrimmed = 0;
  1635. bool perfTakeHasUndoStep = false; // the first clip a performance recording writes is the take's undo step
  1636. void updatePerformanceRecording();
  1637. void updateLauncherRecording();
  1638. // recording into slots (round 190bv): UI thread
  1639. struct SlotTake
  1640. {
  1641. int track = 0, scene = 0;
  1642. bool audio = false;
  1643. int channel = -1; // MIDI: the channel whose notes it takes (−1: any)
  1644. int insert = -1; // audio: the armed insert
  1645. bool known = false; // its end is known: [from, until) on the launcher's clock
  1646. double from = 0.0, until = 0.0;
  1647. bool thenPlay = false, placed = false;
  1648. std::size_t placedEvents = 0;
  1649. std::vector<RecordedEvent> events;
  1650. // round 190mx (GitHub #198): the parameters of the track's devices moved while it records (launcher-clock ticks),
  1651. // written into the new clip's envelopes once it exists
  1652. std::vector<std::pair<AutomationWrite, std::vector<RecordedValue>>> automation;
  1653. };
  1654. std::vector<SlotTake> slotTakes;
  1655. // round 190mx: overdub's moved parameters, per track: into the clip the track plays (its envelopes)
  1656. struct OverdubAutomation
  1657. {
  1658. int track = -1;
  1659. int pattern = -1; // (the clip's pattern the write follows; a new clip starts a new write)
  1660. AutomationWrite write;
  1661. std::vector<RecordedValue> points; // launcher-clock ticks
  1662. };
  1663. std::vector<OverdubAutomation> overdubAutomation;
  1664. bool sessionAutomationPass = false, sessionAutomationHasUndoStep = false;
  1665. // the Session Record take of the track whose devices hold `target` gets the points (none: they are dropped, as Live
  1666. // records automation only into the clips being recorded or overdubbed)
  1667. void routeSessionAutomation (const AutomationTarget& target, std::vector<RecordedValue> points);
  1668. void commitSessionAutomation();
  1669. std::vector<int> gridArmed;
  1670. bool sessionOverdub = false, overdubHasUndoStep = false;
  1671. std::vector<std::pair<int, RecordedEvent>> overdubEvents; // (track, event) not yet written
  1672. int slotRecordBars = 0;
  1673. SpscQueue<RecordedEvent, 1024> slotRecordQueue; // MIDI thread -> UI: notes while a slot records (tick: song position)
  1674. std::vector<RecordedEvent> uiSlotRecorded;
  1675. std::atomic<bool> slotTaking { false }; // a slot records or overdubs MIDI: the played notes are queued
  1676. bool slotAudioWanted = false; // a slot records audio: the armed inserts' takes run
  1677. std::atomic<bool> slotAudioCapture { false }; // (the audio thread's view of it)
  1678. std::atomic<double> takeStartClock { -1.0 }; // the launcher's clock at the take's first sample
  1679. void updateSlotRecording();
  1680. void readSlotTakeMessages();
  1681. struct SlotAudioFile
  1682. {
  1683. juce::File file;
  1684. int insert = -1;
  1685. int latency = 0; // (round 190ub: each take's own, Take::latency)
  1686. };
  1687. bool placeSlotAudio (const std::vector<SlotAudioFile>& files, double ticksPerSample);
  1688. double slotClockNow() const noexcept;
  1689. bool launcherTakeHasUndoStep = false;
  1690. RecordOptions recordOptions;
  1691. std::vector<int> takeClearedChannels; // replace mode: channels already cleared in this take
  1692. std::atomic<bool> waitingForInput { false };
  1693. // MIDI or UI thread: the first input while waiting starts playback (round 190oa: of the kinds FL's wait takes)
  1694. void startOnInput (WaitInput kind = WaitInput::notes) noexcept;
  1695. void preparePlay() noexcept; // play()'s start without the start itself (a Play that waits for input, round 190ld)
  1696. // round 190oa (DF-10; REA 190oa R4): FL's recording filter bits for the wait (1 automation, 2 notes, 4 audio, 8 clips)
  1697. // and whether "Respect recording filter" is on (it acts only while recording)
  1698. std::atomic<int> waitFilter { 15 };
  1699. std::atomic<bool> waitRespects { false };
  1700. std::vector<int> armedInserts;
  1701. // round 190aq: the inserts "Low latency while recording" bypasses latency-adding slots on, as last published
  1702. std::vector<char> publishedLowLatency;
  1703. std::vector<char> lowLatencyTracksNow() const; // what it should be for the song, the armed inserts and the option
  1704. void refreshLowLatency(); // republishes when that changed (an insert armed or disarmed, the option)
  1705. juce::String releasedInputDevice; // the input device releaseAudioInputIfUnused closed (reopened by name)
  1706. double lastPlayingTick = 0.0;
  1707. RecordOffOnStop recordSwitch; // FL's "Disarm on stop"
  1708. std::atomic<int> inputScale { 0 }, inputScaleRoot { 0 };
  1709. std::atomic<int> liveChannel { 0 }; // selected channel, read by the MIDI thread
  1710. static constexpr int maxLiveChannels = 16; // other selected channels that also get MIDI input
  1711. std::array<std::atomic<int>, maxLiveChannels> extraLiveChannels {};
  1712. std::atomic<int> extraLiveCount { 0 };
  1713. void publishSelection();
  1714. void publishRenderAheadTargets();
  1715. struct OpenEditor
  1716. {
  1717. const void* key = nullptr;
  1718. std::function<PluginRef* (Song&)> find; // a channel's plugin (its index is looked up at each publish)
  1719. int track = -1; // or a mixer slot's insert
  1720. };
  1721. std::vector<OpenEditor> openEditors; // (UI thread) hosted plugin editors on screen, for the render-ahead's live part
  1722. renderahead::Targets renderAheadTargets; // (round 190gq) the channels played live, for the render-ahead's partition
  1723. std::atomic<double> blockTimeMs { 0.0 }; // when positionTicks was last updated
  1724. std::atomic<double> blockDurationMs { 0.0 }; // the last block's length (round 174e: playheadAdvanceTicks)
  1725. // round 174e: the device's callback thread (Windows): its priority when first seen and after LYNX raised it to the
  1726. // workers' MMCSS "Pro Audio" class (a driver's own thread at normal priority competed with the UI; LYNX_DEVICE_BOOST=0:
  1727. // left as the driver made it). Shown in the real-time report.
  1728. std::atomic<unsigned long> deviceThreadId { 0 };
  1729. std::atomic<int> deviceThreadPriorityBefore { -100 }, deviceThreadPriorityAfter { -100 };
  1730. bool boostDeviceThread = true;
  1731. // macOS: the device's audio workgroup the render workers join (AudioEngine.cpp, round toolchain190gt)
  1732. struct DeviceWorkgroup;
  1733. std::shared_ptr<DeviceWorkgroup> deviceWorkgroup;
  1734. void joinDeviceWorkgroup (juce::AudioIODevice* device); // message thread (device start / stop)
  1735. bool processFullSpeed = false; // Windows: this engine holds the process out of EcoQoS (platform/PowerThrottling.h)
  1736. // the live clock (round 170d): the musical position of the next block (count-in included), its tempo, and whether
  1737. // it runs; the output latency the played notes are moved back by
  1738. std::atomic<double> clockTick { 0.0 }, clockTicksPerMs { 0.0 }, outputCompensationMs { 0.0 };
  1739. // round 190hq (B13): the PDC plan's latency at the Master output (samples) of the last published rack
  1740. std::atomic<int> masterPdcSamples { 0 };
  1741. // what is heard comes out this long after the rack rendered it: the output buffer + the driver's output latency
  1742. // (outputCompensationMs) + the Master's plugin delay compensation (round 190hq). Any thread.
  1743. double heardLatencyMs() const noexcept;
  1744. std::atomic<bool> clockRunning { false }, compensatePlayed { true };
  1745. CountInCatch takeCatch; // UI thread
  1746. double lastCaptureMs = -1.0; // UI thread: the newest note Capture MIDI took
  1747. captureauto::Buffer automationCapture; // (round 190op) UI thread: the moves made while playing, not recording
  1748. double lastAutomationCaptureMs = -1.0; // UI thread: the newest move Capture automation took
  1749. // round 190op: the grid clip a control's track plays now (its pattern, its own position and end), for the capture
  1750. bool sessionClipOf (const AutomationTarget& target, int& pattern, double& local, std::int64_t& end) const;
  1751. std::array<std::atomic<float>, scopeSize> scope {}; // ring buffer of the output (written by audio)
  1752. std::array<std::atomic<float>, scopeSize> scopeSide {}; // (round 190mv) its side, (L - R) / 2
  1753. std::atomic<int> scopeWrite { 0 };
  1754. std::array<std::atomic<float>, 2> outputPeak {}; // (round 190kn) raised by audio, taken by the toolbar
  1755. juce::MidiDeviceListConnection midiDevicesChanged;
  1756. std::vector<std::string> lastMidiInputIds; // the MIDI inputs available at the last check (UI thread)
  1757. std::vector<prefs::MidiPort> lastMidiPorts; // inputs and outputs at the last check (ids "in:" / "out:"; UI thread)
  1758. bool midiPortsKnown = false; // lastMidiPorts was filled once (no hint for the start-up list)
  1759. int midiDeviceListVersion = 0;
  1760. int midiCheckTicks = 0;
  1761. // round 190rp: the audio device in use going away and coming back (watchAudioDevice, from the timer)
  1762. void watchAudioDevice();
  1763. deviceloss::Watch deviceWatch;
  1764. juce::AudioDeviceManager::AudioDeviceSetup runningDeviceSetup, lostDeviceSetup;
  1765. juce::String hungDeviceSetup; // (round 190rp: the saved setup whose open hung, for retryHungAudioDevice)
  1766. int deviceWatchTicks = 0, deviceReopenTries = 0;
  1767. juce::uint32 deviceReopenMs = 0;
  1768. std::atomic<std::uint32_t> midiActivity { 0 }, midiPlayed { 0 };
  1769. std::uint32_t midiProjectLinked = 0, midiGlobalLinked = 0; // (message thread, round 190ld)
  1770. std::atomic<float> listenGain { 1.0f };
  1771. std::atomic<float> mainVolumeGain { 1.0f }; // (round 190oa: faderGain (song.mainVolume), set by the message thread)
  1772. std::atomic<double> muteTicksLeft { 0.0 }, muteTicksTotal { 0.0 }; // (round 190my: muteOutputForTicks; the audio thread counts down)
  1773. float listenGainNow = 1.0f; // (audio thread: the gain the last block ended at)
  1774. prefs::MidiPrefs midiPrefs; // UI thread
  1775. juce::SpinLock midiPrefsLock; // guards midiPrefsShared (UI writes, MIDI thread reads)
  1776. prefs::MidiPrefs midiPrefsShared;
  1777. // Round 190jl: the MIDI inputs by source number (NoteEvent::source − 1; names only added, so a number stays its
  1778. // device's), under midiPrefsLock; and the hardware MIDI output ports (MidiSyncIo) the rack sends to
  1779. std::vector<std::string> midiSourceNames;
  1780. std::array<std::uint64_t, 4> hardwareMidiPorts {};
  1781. int currentSource = -1; // (round 190mv: setCurrentTrackSource)
  1782. void configureMidiOutputs(); // message thread: MidiSyncIo's devices, the rack's ports
  1783. std::array<RackRenderer::HardwareMidiEvent, RackRenderer::hardwareMidiCapacity> hardwareMidiTaken {}; // audio thread
  1784. // GitHub #198 (round 190ks): the notes hosted plugins play from their own window (pads, keys clicked in it), recorded
  1785. // like played notes. The channels whose plugin window is open (UI thread, at each publish of the editors / song) go
  1786. // to the live rack; its notes come back after each part of the device callback (audio thread) and, while a take or
  1787. // a clip slot records, go to the UI thread through pluginRecordQueue (tick: where the song was heard, as a played
  1788. // note's; `slot` = a clip slot records too).
  1789. struct PluginRecorded
  1790. {
  1791. RecordedEvent event;
  1792. bool take = false, slot = false;
  1793. };
  1794. SpscQueue<PluginRecorded, 1024> pluginRecordQueue; // audio thread -> UI
  1795. std::array<RackRenderer::OwnNoteEvent, RackRenderer::ownNoteCapacity> ownNotesTaken {}; // audio thread
  1796. std::array<std::uint64_t, RackRenderer::ownNoteWords> ownNoteChannels {}; // UI thread (last published)
  1797. void publishOwnNoteChannels();
  1798. void takePluginNotes (int done) noexcept; // audio thread, after a part of the device callback
  1799. public:
  1800. // the plugin notes waiting for the UI thread (updateRecording takes them; tests). UI thread.
  1801. void takeRecordedPluginNotes();
  1802. // GitHub #198: the channels whose plugin notes are recorded now (tests). UI thread.
  1803. const std::array<std::uint64_t, RackRenderer::ownNoteWords>& recordedPluginChannels() const noexcept { return ownNoteChannels; }
  1804. private:
  1805. bool hardwareMidiWasPlaying = false; // audio thread
  1806. // FL's "Receive notes from" (round 165f-rack): the channels locked to a MIDI input device (and MIDI channel, 0 = any),
  1807. // rebuilt from the song on every publish; guarded by midiPrefsLock too
  1808. struct NoteLock
  1809. {
  1810. std::string device;
  1811. int midiChannel = 0;
  1812. int channel = 0;
  1813. };
  1814. std::vector<NoteLock> noteLocks;
  1815. // Round 190ao: each channel's own velocity setting for played notes (a hosted instrument's PluginRef::velocityMode,
  1816. // low byte, and fixedVelocity, high byte; 0 = follow the MIDI settings), rebuilt on every publish; guarded by
  1817. // midiPrefsLock too
  1818. std::vector<std::uint16_t> channelVelocity;
  1819. // round 190ao: the preset audition's note (message thread: auditionPreset and the timer)
  1820. int auditionChannel = -1;
  1821. bool auditionSounding = false;
  1822. double auditionAtMs = 0.0;
  1823. void updateAudition();
  1824. void logPlayedNote (int channel, int key, float velocity, bool on, double tick = -1.0, bool recorded = false);
  1825. mutable juce::SpinLock scoreLogLock; // MIDI thread and UI thread write, the UI reads
  1826. scorelog::Log scoreLog;
  1827. std::atomic<bool> stepEditOn { false };
  1828. std::vector<stepedit::Played> stepEditQueue; // under scoreLogLock
  1829. std::map<std::tuple<int, int, int, int, int, int>, prefs::PickupState> pickups; // (cc, channel, target) -> takeover
  1830. // settings / log files written off the message thread (issue #13's freezes); declared before the saver so it
  1831. // outlives it, and its destructor writes what is still queued
  1832. SerialJobs fileJobs;
  1833. SerialJobs previewJobs; // round 190aq: "Preview in time" reads tempos and stretches here
  1834. struct DeviceStateSaver;
  1835. std::unique_ptr<DeviceStateSaver> deviceStateSaver;
  1836. // audio recording
  1837. bool audioArmed = false;
  1838. juce::String recordingError;
  1839. juce::File recordingFolder = defaultRecordingFolder();
  1840. juce::String recordingStem;
  1841. std::vector<juce::File> sessionRecordings;
  1842. juce::TimeSliceThread recordThread { "LYNX recording" };
  1843. RecordingNotice recordingNotice;
  1844. void notify (InputIssue issue, int track = 0, const juce::String& detail = {});
  1845. // One take being recorded (round 163): the audio thread pushes into `stream`, the recording thread drains it
  1846. // into `writer` (crash-safe WAV). Shared by the UI (start/finish), the audio thread (raw pointer under
  1847. // takeLock) and the recording thread (drainer list under drainLock).
  1848. struct Take
  1849. {
  1850. int track = -1; // the insert that records it (0 = the Master, round 190to; −1 = none: Settings' "Record input audio" without armed inserts)
  1851. int first = 0; // device input channel
  1852. int channels = 0; // 1 or 2
  1853. // round 168x (issue #41): a take tapped inside its insert (FL's "Record" positions after the input) reads
  1854. // liveInput.taps[tap] after the block was rendered (−1 = the device input itself). Its first `skip` frames are
  1855. // dropped (the latency of the insert's effects up to the tap) and as many frames of silence close it, so it
  1856. // lines up with the input to the sample.
  1857. int tap = -1;
  1858. int skip = 0;
  1859. int skipped = 0; // audio thread
  1860. int playThrough = -1; // the insert the take's clip plays through (Master = 0; -1 = a new free insert)
  1861. // round 190ub (issue #371): the samples the take's placement moves it back by. A take of the device input gets the
  1862. // recording latency compensation (round trip + manual + PDC, `takeLatency`); a tapped take holds audio the song
  1863. // made inside LYNX, late only by its insert's input alignment (PdcPlan::inAlign): no round trip, no manual offset
  1864. int latency = 0;
  1865. juce::File file;
  1866. std::unique_ptr<takes::TakeStream> stream;
  1867. takes::WavTakeWriter writer;
  1868. std::atomic<bool> failed { false };
  1869. std::vector<float> scratch;
  1870. std::shared_ptr<liverec::LivePeaks> peaks = std::make_shared<liverec::LivePeaks>(); // the live waveform (round 177d)
  1871. juce::CriticalSection drainMutex; // the recording thread vs the UI's final drain
  1872. // recording thread: writes what arrived; false when the file could not be written
  1873. bool drain();
  1874. };
  1875. static constexpr int maxTakes = 16;
  1876. std::array<Take*, maxTakes> takes {}; // guarded by takeLock (the audio thread's view)
  1877. int takeCount = 0;
  1878. std::vector<std::shared_ptr<Take>> openTakes; // UI thread (owner)
  1879. juce::CriticalSection drainLock; // the recording thread's list
  1880. std::vector<std::shared_ptr<Take>> draining;
  1881. struct Drainer;
  1882. std::unique_ptr<Drainer> drainer;
  1883. juce::SpinLock takeLock; // the audio thread only tries (never waits)
  1884. LiveInput liveInput;
  1885. std::unique_ptr<perf::Live> performanceLive = std::make_unique<perf::Live>(); // Performance mode (round 165m)
  1886. std::unique_ptr<launcher::Runtime> clipLauncher; // made when a project first has a clip grid (round 181a)
  1887. std::atomic<int> performanceMidiChannel { 0 }; // MidiPrefs::performanceChannel (UI writes, MIDI thread reads)
  1888. std::atomic<bool> performanceMidiOn { false }; // Performance mode is on with a zone (UI writes, MIDI thread reads)
  1889. perf::MidiMapping performanceMidi; // MIDI thread only
  1890. HardwareOutput hwOutput; // inserts' hardware outputs (renderer -> callback)
  1891. int outputCountForCheck = -1; // round 190nc: setOutputChannelCountForCheck
  1892. std::array<int, HardwareOutput::maxChannels> outputSlot {}; // device output channel -> callback output index (-1: closed)
  1893. std::atomic<int> masterOutChannel { outputDefault }; // the Master's target (UI -> audio)
  1894. std::atomic<int> masterOutMode { 0 };
  1895. std::vector<float> masterScratch = std::vector<float> (2 * HardwareOutput::capacity, 0.0f);
  1896. void routeOutputs (float* const* outputs, int numOutputs, int n) noexcept; // audio thread
  1897. std::array<float, maxMixerTracks * 2> lastInputPeaks {};
  1898. std::array<int, LiveInput::maxChannels> inputSlot {}; // device input channel -> callback input index (-1: closed)
  1899. // audio thread: its copy of the markers' actions (Transport::readMarkers) and how many marker jumps it made
  1900. MarkerPlan rtMarkers;
  1901. std::uint32_t rtMarkerVersion = 0;
  1902. public:
  1903. // marker jumps / pauses the audio thread made since start (tests, the hint bar); +1 each
  1904. std::atomic<int> markerEvents { 0 };
  1905. // Clicking the ruler / a marker while playing, FL's "Song marker jump": jump to `tick`, while playing at the next
  1906. // "Quantize song jumps" step (FL's Playlist menu: 0 Off, 1 Beats, 2 Bars, 3 2 bars, 4 4 bars, 5 8 bars)
  1907. void jumpTo (double tick) noexcept;
  1908. void jumpToMarker (int index) noexcept; // the index-th marker of the arrangement (by position)
  1909. void jumpToNextMarker (bool forward) noexcept;
  1910. std::atomic<int> quantizeSongJumps { 0 };
  1911. private:
  1912. std::atomic<double> takeStartTick { -1.0 }; // position of the first recorded sample
  1913. std::atomic<juce::int64> takeFrames { 0 };
  1914. std::atomic<double> takeTicks { 0.0 }; // ticks the transport moved while recording (not wrapped)
  1915. std::array<std::atomic<juce::int64>, 256> takeWraps {}; // take frames at which the loop jumped back (loop recording)
  1916. std::atomic<int> takeWrapCount { 0 };
  1917. mutable std::vector<int> liveTakeTracks; // the Playlist tracks the open takes will land on (round 177d)
  1918. double takeSampleRate = 44100.0;
  1919. double takeTicksPerSample = 0.0;
  1920. int takeLatency = 0; // takes::Latency::total() at the take's start, in samples
  1921. std::optional<PunchRange> activePunch; // pre-roll / punch range of the recording in progress (UI thread)
  1922. std::int64_t punchStopAt = -1; // post-roll end: playback stops there (-1: none)
  1923. bool linearRecording() const noexcept
  1924. {
  1925. return recordloop::linear (song.mode, song.loopPlays(), recordOptions.loopRecord, recordOptions.punchLoopRegion);
  1926. }
  1927. // the audio thread's view of the above while takes record (false when none is open)
  1928. void updateLinearSong() noexcept
  1929. {
  1930. const auto on = (takeCount > 0 || automationLinear || noteTakeLinear) && linearRecording();
  1931. liveInput.linearSong.store (on || bouncing);
  1932. liveInput.noLoopRegion.store ((on && song.loopPlays()) || bouncing);
  1933. }
  1934. takes::LatencyPing ping; // audio thread while running (UI starts it, reads the result)
  1935. juce::int64 lostFrames = 0;
  1936. std::array<int, 2> pingOutputs { -1, -1 }; // callback output slots the click goes to
  1937. int pingInput = -1; // callback input slot listened to
  1938. RecordingSettings recordingSettings;
  1939. juce::File journalFor (const juce::File& wav) const { return wav.withFileExtension ("wav.lynxrec"); }
  1940. void writeJournals();
  1941. bool journalsWritten = false;
  1942. MeterBank meters;
  1943. // round 190ke: the Simple tuner's input tap (setTunerInput)
  1944. std::atomic<int> tunerFirst { -1 }, tunerCount { 0 };
  1945. std::unique_ptr<visualfx::Tap> tunerTapData = std::make_unique<visualfx::Tap>();
  1946. std::unique_ptr<AudioLogger> audioLogger; // after `meters` (it reads meters.logTap): destroyed first
  1947. PluginHost plugins;
  1948. std::unique_ptr<AraHost> araHost; // (after `plugins`: its plugin instances go first; round 190kx)
  1949. juce::StringArray missingPlugins, matchedPlugins, pluginsWithoutState;
  1950. FlpImportReport importReport;
  1951. std::vector<MissingPlugin> missingPluginDetails;
  1952. RenderStats lastRenderStats;
  1953. class ChannelRackProcessor* rackProcessor = nullptr; // graph node (owner: the graph)
  1954. Song song;
  1955. int selectedChannel = 0;
  1956. std::vector<int> selectedChannels { 0 };
  1957. bool modified = false;
  1958. double workSince = 0.0; // wall clock (ms since 1970) when the working time was last added
  1959. std::unique_ptr<StreamPrefetcher> prefetcher; // only with an audio device (playing live)
  1960. std::size_t maxUndoSteps = prefs::defaultUndoLevels;
  1961. // round 190rn: the history is also capped by its memory (core/SongBytes.h's estimate of each step's copy): a big
  1962. // project's 100 steps reached 1 GB (Patience, 7.4 MB a step). The oldest steps go first; one step always stays.
  1963. std::size_t maxUndoBytes = std::size_t (1) << 30; // (1 GB; setUndoBytesForTest)
  1964. // `action`: the name its code gave the step from this state to the next (redo: from the one before to this one;
  1965. // round 190td, item 72; none = named from the diff)
  1966. struct HistoryEntry { Song song; bool remote = false; juce::String deviceHash; std::size_t bytes = 0; undonames::Action action = undonames::Action::none; };
  1967. std::deque<HistoryEntry> undoStack, redoStack;
  1968. void trimUndoHistory(); // to maxUndoSteps and maxUndoBytes (the oldest undo steps go)
  1969. // undo per user (round 169b): each local step as (before, after); `sessionAfterOpen` = the last step's "after" is
  1970. // still the song (it is taken when the next step starts, a remote change comes in, or undo is used)
  1971. bool sessionHistory = false, sessionAfterOpen = false;
  1972. struct SessionHistoryEntry { Song first, second; bool remote = false; juce::String deviceHash; undonames::Action action = undonames::Action::none; };
  1973. undonames::Action pendingAction = undonames::Action::none, scopedAction = undonames::Action::none; // (round 190td)
  1974. undonames::Action takeStepName() noexcept
  1975. {
  1976. const auto a = pendingAction != undonames::Action::none ? pendingAction : scopedAction;
  1977. pendingAction = undonames::Action::none;
  1978. return a;
  1979. }
  1980. std::deque<SessionHistoryEntry> sessionUndo, sessionRedo;
  1981. bool nextRemoteHistoryStep = false, remoteHistoryFailed = false, remoteHistoryUncertain = false;
  1982. bool remoteHistoryApiStep = false; // device fences/cancellation apply only to API undo/redo, never native history
  1983. juce::String remoteHistoryError;
  1984. std::string remoteHistoryCode = "changed";
  1985. std::unordered_set<std::uint64_t> remoteFreshInstances;
  1986. std::function<bool()> remoteHistoryCancelled;
  1987. void closeSessionStep();
  1988. void sessionStep (bool redo);
  1989. void historyStep (bool redo);
  1990. juce::Time lastUndoPress; // mouse click that already produced an undo step
  1991. // FL's "Undo knob tweaks" off (round 190mv, DF-134): the press (or, without a button down, the moment) of the last
  1992. // control tweak, and the last undo step pushed (stack size, its press / moment) so a tweak that came after its
  1993. // edit's step can take that step back
  1994. juce::Time tweakPress, lastPushPress;
  1995. double tweakMs = -1.0e9, lastPushMs = -1.0e9;
  1996. std::size_t lastPushSize = 0;
  1997. // round 190tv: the control the next edit's wheel notch belongs to (set just before it), and the last wheel step's
  1998. std::uint64_t pendingWheelControl = 0, lastWheelControl = 0;
  1999. double pendingWheelMs = -1.0e9, lastWheelMs = -1.0e9;
  2000. bool tweakSkipsStep (bool buttonDown, double nowMs) const noexcept;
  2001. // the open mouse gesture (beginUndoGesture): it already saved its undo step; it began with a real button down
  2002. bool gestureOpen = false, gestureSaved = false, gestureRealMouse = false, gestureEnding = false;
  2003. SnapshotExchange<RackState> rackExchange;
  2004. std::shared_ptr<LiveLevels> publishedLevels; // the last snapshot's live levels (editLevels writes them)
  2005. bool levelsPending = false; // editLevels changed the Song since the last publish
  2006. juce::ChangeBroadcaster levelsChanged;
  2007. std::uint64_t levelEdits = 0; // (diagnostics / tests)
  2008. std::uint64_t publishCount = 0;
  2009. std::uint64_t openCount = 0; // (round 190oo: getOpenCount)
  2010. // Issue #134: a publish asked for while one is still building its rack (a plugin being created ran the message
  2011. // loop: the engine's timer, an edit) waits until that one is done; see publishSong
  2012. bool publishing = false, publishAgain = false;
  2013. int nestedPublishes = 0; // (diagnostics / tests)
  2014. // tests: called for every hosted instrument / effect the rack asks for, in place of a plugin that runs the
  2015. // message loop while it is created (DeviceChangeTest)
  2016. std::function<void()> duringPluginCreation;
  2017. void saveUndoStep();
  2018. ProcessTimes* externalTimes = nullptr;
  2019. std::function<std::shared_ptr<Effect>()> externalEffect;
  2020. // round 190jb: an export runs with this engine's plugins (holdForExport); the device callback is inside its block
  2021. std::atomic<bool> exportHold { false }, callbackBusy { false };
  2022. LiveInstrumentSource liveInstrumentSource; // (the export engine's side: setLiveUnits)
  2023. bool parallelSampleDecode = true; // (round 190la: setParallelSampleDecode)
  2024. LiveEffectSource liveEffectSource;
  2025. std::vector<const void*> lentUnits; // the units the sources gave this engine (the export engine; warmUpPlugins)
  2026. void capturePluginStatesInto (Song& target, bool requireAll, int onlyTrack = -1, int onlySlot = -1);
  2027. void syncRemotePluginStates (const Song& before);
  2028. juce::String finishRemoteHistory (const std::optional<Song>& before);
  2029. bool checkRemoteHistory (const juce::String& expected, const Song& current);
  2030. void failRemoteHistory (bool uncertain);
  2031. static juce::String remoteDeviceStateHashOf (const Song&);
  2032. RackState lastPublishedShape; // channels + instruments of the last snapshot, to reuse voices
  2033. bool liveDevice = false; // (round 190qh) an engine made to play on an audio device (the app's); exports have none
  2034. // Round 190un (issue #381, core/StretchDefer.h): the stretches of keep-pitch channels are rendered off the message
  2035. // thread (a new tempo, other warp markers) while the channel's running instrument plays on; the engine's timer builds
  2036. // the rack again when one is ready. On for an engine with an audio device (deferStretches = liveDevice); the tests set it.
  2037. struct StretchWorker;
  2038. std::unique_ptr<StretchWorker> stretchWorker;
  2039. bool deferStretches = false;
  2040. StretchWorker& stretchWorkerNow();
  2041. std::vector<int> standInChannels, standInInserts; // (playsStandIn)
  2042. std::vector<int> frozenMissing; // (frozenAudioMissing)
  2043. struct FreezeCheck
  2044. {
  2045. std::uint64_t stamp = 0;
  2046. bool outOfDate = false;
  2047. };
  2048. std::vector<FreezeCheck> freezeChecks; // [channel] (freezeOutOfDate)
  2049. std::vector<int> channelsOff, insertsOff; // (channelPluginOff / insertPluginOff, round 190ap), as of the last publish
  2050. std::vector<char> deactivatedChannels, deactivatedInserts; // (channelDeactivated / insertDeactivated, round 190op)
  2051. bool rebuildPlugins = false; // switchPluginOn's publish: the slots of rebuildPluginId ("" = all) are created anew
  2052. std::string rebuildPluginId;
  2053. // Issue #36 (u-he Presswerk crashed in its VST3 teardown, freed from the engine's timer callback): the racks the
  2054. // audio thread let go of are freed from a message of their own, not inside the timer callback that collected them.
  2055. // A plugin whose editor is open dies when its window goes (the window closes the editor first). Declared after the
  2056. // rack members: freed first, while the plugin hosts still exist. In the app only (tests have no message loop).
  2057. struct RackDisposer final : private juce::AsyncUpdater
  2058. {
  2059. ~RackDisposer() override
  2060. {
  2061. cancelPendingUpdate();
  2062. flush();
  2063. }
  2064. void add (const RackState* rack)
  2065. {
  2066. {
  2067. const juce::ScopedLock sl (lock);
  2068. items.push_back (rack);
  2069. }
  2070. triggerAsyncUpdate();
  2071. }
  2072. void flush()
  2073. {
  2074. std::vector<const RackState*> now;
  2075. {
  2076. const juce::ScopedLock sl (lock);
  2077. now.swap (items);
  2078. }
  2079. for (const auto* rack : now)
  2080. delete rack;
  2081. }
  2082. private:
  2083. void handleAsyncUpdate() override { flush(); }
  2084. juce::CriticalSection lock;
  2085. std::vector<const RackState*> items;
  2086. } rackDisposer;
  2087. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioEngine)
  2088. };
  2089. } // namespace lynx