AudioEngine.h 146 KB

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