AudioEngine.h 48 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814
  1. #pragma once
  2. #include <array>
  3. #include <optional>
  4. #include <deque>
  5. #include <map>
  6. #include <tuple>
  7. #include <utility>
  8. #include <functional>
  9. #include <juce_audio_utils/juce_audio_utils.h>
  10. #include "core/HeldNotes.h"
  11. #include "core/Preferences.h"
  12. #include "core/LiveEventQueue.h"
  13. #include "core/LiveInput.h"
  14. #include "core/HardwareOutput.h"
  15. #include "core/Recorder.h"
  16. #include "core/TakeRecording.h"
  17. #include "core/WorkerPool.h"
  18. #include "engine/MidiSyncIo.h"
  19. #include "core/RackRenderer.h"
  20. #include "core/RtStats.h"
  21. #include "core/ScoreLog.h"
  22. #include "core/FlpImport.h"
  23. #include "core/History.h"
  24. #include "core/NativeEngines.h"
  25. #include "core/PluginWarmup.h"
  26. #include "core/SnapshotExchange.h"
  27. #include "core/Song.h"
  28. #include "engine/PluginHost.h"
  29. #include "engine/SampleLibrary.h"
  30. #include "engine/StreamPrefetcher.h"
  31. #include "engine/Transport.h"
  32. namespace lynx
  33. {
  34. class AudioLogger;
  35. // Owns the audio device, the processing graph and the document (Song).
  36. // Sits between the driver and the AudioProcessorPlayer to advance the transport
  37. // after each block, so every node sees the same start position.
  38. //
  39. // The Song is touched only by the UI thread; each edit publishes an immutable
  40. // snapshot (RackState) to the audio thread.
  41. // Folders of the most recent FL Studio installation (empty if none).
  42. FlPathRoots findFlStudioRoots();
  43. // The user's FL installation as the native FL engines read it (round 142): its folders and this PC's file system
  44. const natives::FlAccess& flStudioAccess(); // (found once per session)
  45. // Start-up trace hook (round 165i): Main's LYNX_TRACE_STARTUP log receives the engine's own steps (null: off)
  46. inline void (*startupMark) (const char* step) = nullptr;
  47. class AudioEngine final : private juce::AudioIODeviceCallback,
  48. private juce::MidiInputCallback,
  49. public juce::ChangeBroadcaster,
  50. private juce::Timer
  51. {
  52. public:
  53. explicit AudioEngine (bool openAudioDevice = true);
  54. ~AudioEngine() override;
  55. juce::AudioDeviceManager& getDeviceManager() noexcept { return deviceManager; }
  56. Transport& getTransport() noexcept { return transport; }
  57. const Transport& getTransport() const noexcept { return transport; }
  58. SampleLibrary& getSampleLibrary() noexcept { return samples; }
  59. MeterBank& getMeters() noexcept { return meters; }
  60. // Tools > Audio logger (REA round 153): records everything the Master plays to a WAV in the background.
  61. AudioLogger& getAudioLogger();
  62. PluginHost& getPluginHost() noexcept { return plugins; }
  63. // Third-party plugins from the last imported .flp that were not found among the scanned ones.
  64. const juce::StringArray& getMissingPlugins() const noexcept { return missingPlugins; }
  65. // "plugin → file (how it was found)" for the plugins of the last imported .flp
  66. const juce::StringArray& getMatchedPlugins() const noexcept { return matchedPlugins; }
  67. // plugins found whose saved settings could not be carried over (VST2 <-> VST3): "name (format)"
  68. const juce::StringArray& getPluginsWithoutState() const noexcept { return pluginsWithoutState; }
  69. // What the last imported .flp converted, approximated or left out.
  70. const FlpImportReport& getImportReport() const noexcept { return importReport; }
  71. // The last imported .flp's plugins that were not found, with what uses them and what LYNX put in their place.
  72. const std::vector<MissingPlugin>& getMissingPluginDetails() const noexcept { return missingPluginDetails; }
  73. // Live instances (to open the plugin window). nullptr if not a plugin.
  74. std::shared_ptr<Instrument> getChannelInstrument (int channel) const;
  75. std::shared_ptr<Effect> getEffect (int track, int slot) const;
  76. // Copies the plugins' current state into the Song (before saving).
  77. void capturePluginStates();
  78. // Offline render mode for the hosted plugins (setNonRealtime), around renderOffline.
  79. void setPluginsRenderMode (bool offline);
  80. // Every hosted plugin of the song that has not crashed (channels, inserts, inside Patchers); `notifyRender` is the
  81. // plugin's "Notify about rendering mode" option. Message thread or the render thread, while nothing else edits.
  82. void forEachHostedPlugin (const std::function<void (juce::AudioPluginInstance&, bool notifyRender)>& visit) const;
  83. // The render's plugin warm-up (renderOffline, round 155): silent discarded blocks until the hosted plugins settle,
  84. // then a new PDC plan if a latency changed and LYNX's own units reset. Returns blocks == 0 when the song has no
  85. // hosted plugin. `latency` receives the delay compensation's total afterwards.
  86. warmup::Result warmUpPlugins (const warmup::Settings& settings, double sampleRate, int blockSize,
  87. const std::function<bool (double)>& progress, int& latency);
  88. void play() noexcept;
  89. // Performance mode (round 165m, core/Performance.h): launch / release / stop zone clips (message thread). The
  90. // clips start on the next block, quantized by their track's Performance settings; nothing launches while stopped.
  91. void performanceCommand (const perf::Command& command) noexcept { performanceLive->commands.push (command); }
  92. const perf::Live& performanceState() const noexcept { return *performanceLive; }
  93. perf::Live& performanceStateForSnapshot() noexcept { return *performanceLive; } // --perfshot: a sample of what plays
  94. void stop() noexcept; // also cancels a count-in or a wait for the first note
  95. // Recording options (docs/WORKFLOW_FL.md P2: recording set). UI thread.
  96. struct RecordOptions
  97. {
  98. int countInBars = 0; // 0 = off
  99. bool waitForInput = false; // playback starts at the first played note
  100. RecordMode mode = RecordMode::overdub;
  101. std::int64_t quantise = 0; // record quantise in ticks (<= 1: as played); follows the global grid
  102. bool placeSongClip = true; // song mode: a take puts a clip of the pattern where recording started
  103. // recording filter (FL's record button right-click, REA_rodada88): what a take records
  104. bool recordNotes = true; // notes played (MIDI and PC keyboard)
  105. bool recordAudio = true; // audio of the armed inserts' inputs
  106. bool askWhatToRecord = true; // the record button asks first ("What would you like to record?")
  107. // FL's record menu "Options" (REA round 134): arming recording also starts playback; the armed inserts are
  108. // disarmed when a take stops
  109. bool startsPlayback = false;
  110. bool disarmOnStop = false;
  111. // FL's record menu "Quantize" section (REA round 139); `quantise` is the grid. quantiseStarts = "Note start
  112. // time", noteEnd = "Note end time" (quantize) / "Leave note duration" (keepLength) / neither (keepEnd),
  113. // toStepSequencer = "Record to step sequencer"
  114. bool quantiseStarts = true;
  115. NoteEnd noteEnd = NoteEnd::keepLength;
  116. bool toStepSequencer = false;
  117. // FL's "Enable recording markers": the Playlist's "Start recording" / "Stop recording" markers limit what a
  118. // take keeps in song mode (notes started outside are dropped, audio clips are cut to the ranges)
  119. bool recordingMarkers = false;
  120. // FL's recording filter "Automation" (REA round 143): moved parameters become automation (song mode: automation
  121. // clips; pattern mode: the pattern's events); Quantize › "Automations" puts their points on the snap
  122. bool recordAutomation = true;
  123. // FL's recording filter "Clips" (REA round 146 B5, round 165m): Performance mode's launched clips are written
  124. // into the arrangement where they played
  125. bool recordClips = true;
  126. bool quantiseAutomation = false;
  127. // round 163 (Pro Tools / Nuendo): punch in/out on the Playlist's loop region (instead of loop recording; the
  128. // song plays straight through it), pre-roll before the punch-in (or before the position recording starts at)
  129. // and post-roll after the punch-out (then playback stops). Bars; 0 = off.
  130. bool punchLoopRegion = false;
  131. int preRollBars = 0;
  132. int postRollBars = 0;
  133. };
  134. // The range this recording keeps (pre-roll or punch), while one is active. UI thread.
  135. std::optional<PunchRange> getActivePunch() const noexcept { return activePunch; }
  136. const RecordOptions& getRecordOptions() const noexcept { return recordOptions; }
  137. void setRecordOptions (const RecordOptions& options);
  138. // Play pressed: with recording on, honours wait-for-input and the count-in; otherwise play().
  139. void startPlayback();
  140. // The song's initial values (FL's initialized controls) back on their targets, in song mode; play() and a
  141. // seek while playing do it (REA round 146). UI thread.
  142. void resetToInitialValues() noexcept;
  143. bool isWaitingForInput() const noexcept { return waitingForInput.load(); }
  144. bool isCountingIn() const noexcept { return transport.countIn.load() > 0.0; }
  145. // Per-insert record arm: each armed insert records its own audio input (Mixer › insert › input source) into
  146. // its own take (arming one turns audio recording on; disarming the last one turns it off). Not saved.
  147. void setInsertArmed (int track, bool armed);
  148. bool isInsertArmed (int track) const noexcept;
  149. const std::vector<int>& getArmedInserts() const noexcept { return armedInserts; }
  150. void rewind() noexcept;
  151. void seek (double ticks) noexcept;
  152. // Preview of an audio file (browser). An invalid/empty file stops the preview.
  153. void previewFile (const juce::File& file);
  154. // The Browser's preview volume (0..1.25, 1 = default; core/ValueMath.h previewGain). Applies to the preview
  155. // playing now too. UI thread.
  156. void setPreviewVolume (double volume) noexcept;
  157. double getPreviewVolume() const noexcept { return previewVolume; }
  158. // Plays a sound made in memory through the same preview output (the start-up sound). UI thread.
  159. void previewSample (std::shared_ptr<const SampleData> sample, bool loop = false, float gain = 0.8f, bool audioEditor = false);
  160. // The Audio Editor's playback volume (its toolbar knob, round 162): 0..1.25 like the Browser's, 1 = unity.
  161. void setEditorVolume (double volume) noexcept;
  162. double getEditorVolume() const noexcept { return editorVolume; }
  163. // The frame of the previewed sample being played, -1 when the preview is silent.
  164. double getPreviewPosition() const noexcept;
  165. // Note played live (PC keyboard, preview). UI thread.
  166. // `record` = goes into the recording if recording is on (Piano Roll preview doesn't).
  167. void sendLiveNote (int channel, int key, float velocity, bool on, bool record = false);
  168. // The keys held right now on MIDI inputs and the typing piano (as played, before the scale snap), ascending; for
  169. // the Piano Roll's chord readout (any thread).
  170. std::vector<int> heldInputKeys() const;
  171. // FL's score logger (REA round 165f): every note played on a MIDI input or the typing keyboard, recording or
  172. // not, for Tools › Dump score log to selected pattern. Any thread (a short spin lock; never the audio thread).
  173. std::vector<scorelog::Entry> scoreLogSnapshot() const;
  174. bool scoreLogEmpty() const;
  175. void clearScoreLog();
  176. // Scale snap for played notes (MIDI input and the PC keyboard): scale index into notetools::scales()
  177. // (0 = off) and its root (0..11). Any thread.
  178. void setInputScale (int scale, int root) noexcept;
  179. int snapInputKey (int key) const noexcept;
  180. // All notes off on every channel (double-click on Stop). UI thread.
  181. void panic();
  182. // Note recording (MIDI and PC keyboard) into the current pattern while playing. UI thread.
  183. void setRecording (bool shouldRecord);
  184. bool isRecording() const noexcept { return transport.recording.load(); }
  185. // Audio recording from the interface input: with this on, recording (Rec + Play) writes the
  186. // input to a WAV and, on stop, the take becomes a Playlist clip (latency-compensated).
  187. // Enabling it opens the device input (only then does Windows show the mic as in use).
  188. void setAudioRecordingArmed (bool armed);
  189. bool isAudioRecordingArmed() const noexcept { return audioArmed; }
  190. juce::String getLastRecordingError() const { return recordingError; }
  191. // Where takes are written and how they are named (FL's project data folder, REA round 134): `folder` is
  192. // "<project folder>/Audio/Recorded" for a saved project (the global recordings folder otherwise), files are
  193. // "<projectStem>_<yyyy-mm-dd hh-mm-ss>_<insert name>.wav". UI thread.
  194. void setRecordingTarget (const juce::File& folder, const juce::String& projectStem);
  195. juce::File getRecordingFolder() const { return recordingFolder; }
  196. static juce::File defaultRecordingFolder();
  197. // The take files written since LYNX started (or since forgetRecordings), oldest first. UI thread.
  198. const std::vector<juce::File>& getSessionRecordings() const noexcept { return sessionRecordings; }
  199. void forgetRecordings (const std::vector<juce::File>& files);
  200. // --- hardware recording (round 163, docs/analise/REA_rodada163c.md) ---
  201. // Options › Audio › Recording, saved in <settings>/recording.txt.
  202. struct RecordingSettings
  203. {
  204. takes::SampleFormat format = takes::SampleFormat::pcm24; // 24-bit or 32-bit float WAV; the device's rate
  205. bool trackTakeNames = true; // "<Insert>_Take<N>.wav" (off: FL's "<project>_<date time>_<insert>.wav")
  206. int manualOffset = 0; // samples added to the compensation (negative: earlier)
  207. bool useMeasured = true; // a ping measured for this device setup replaces the driver's figures
  208. std::map<std::string, int> measured; // setupKey -> round trip (samples)
  209. int pingOutput = 0, pingInput = 0; // device channels the ping uses (output pair's first, input)
  210. };
  211. const RecordingSettings& getRecordingSettings() const noexcept { return recordingSettings; }
  212. void setRecordingSettings (const RecordingSettings& settings); // saves
  213. // The current device setup's key (takes::setupKey) and its latency figures (pdc = the Master's PDC now).
  214. std::string currentSetupKey() const;
  215. takes::Latency currentLatency() const;
  216. // The latency ping: clicks on output channel pair `pingOutput` (and the next), listened for on input channel
  217. // `pingInput` through a loopback. Needs the transport stopped and the input open. Returns an error (empty: started).
  218. juce::String startLatencyPing();
  219. bool isPinging() const noexcept { return ping.isRunning(); }
  220. void cancelLatencyPing() noexcept { ping.cancel(); }
  221. // After isPinging() turned false: the result (stored for this setup when ok).
  222. takes::LatencyPing::Result finishLatencyPing();
  223. // Record safe (round 163): a safe insert can't be armed (undoable, saved with the project).
  224. void setInsertRecordSafe (int track, bool safe);
  225. bool isInsertRecordSafe (int track) const noexcept
  226. {
  227. return track > 0 && track < (int) song.mixer.size() && song.mixer[(std::size_t) track].recordSafe;
  228. }
  229. // Frames lost while recording (the disk could not keep up; they became silence, the timing kept) since the
  230. // last take started.
  231. juce::int64 getLostRecordingFrames() const noexcept { return lostFrames; }
  232. // Interrupted takes (crash while recording): repaired WAVs and where they belonged. Scans the journals in the
  233. // given folders (the default recordings folder always). UI thread, at start-up.
  234. std::vector<takes::Journal> recoverInterruptedTakes (const std::vector<juce::File>& folders);
  235. // Puts recovered takes on the Playlist at their recorded positions (undoable). Returns how many were placed.
  236. int placeRecoveredTakes (const std::vector<takes::Journal>& recovered);
  237. // Leaves them as files only (their journals are removed).
  238. void forgetInterruptedTakes (const std::vector<takes::Journal>& recovered);
  239. // --- external audio input through the mixer (REA_rodada88) ---
  240. // Names of the open device's input channels (all of them, open or not); empty without an input device.
  241. std::vector<std::string> getInputChannelNames() const;
  242. // Problems the UI explains to the user (translated there).
  243. enum class InputIssue
  244. {
  245. none,
  246. noDevice, // no audio device open at all
  247. noInputDevice, // the driver has no input device
  248. noInputOpen, // recording with no input open
  249. armedWithoutInput, // armed inserts, none with an input source
  250. insertWithoutInput,// one armed insert (track) has no input source
  251. lowDisk, // little room left on the recordings drive (detail = minutes)
  252. recordSafe, // the insert (track) is record safe: not armed
  253. framesLost, // the disk could not keep up: frames became silence (detail = how many)
  254. failed // the driver refused (detail = its message) or a file could not be written
  255. };
  256. struct RecordingNotice
  257. {
  258. InputIssue issue = InputIssue::none;
  259. int track = 0;
  260. juce::String detail;
  261. };
  262. // Opens the input of the current driver: `deviceName` (separate-input drivers; empty = the one chosen in
  263. // Settings, else the default), all of its channels. UI thread.
  264. RecordingNotice openAudioInput (const juce::String& deviceName = {});
  265. bool hasAudioInput() const;
  266. // Closes the device input again when nothing needs it (no insert takes an input, no armed recording, no hardware
  267. // insert returning from it): a capture the Audio editor opened for one recording no longer keeps the input — and
  268. // Windows' microphone-in-use icon — on until LYNX quits, as in FL (round 165q). The input device's name is kept
  269. // for the next openAudioInput(). UI thread.
  270. void releaseAudioInputIfUnused();
  271. bool audioInputNeeded() const;
  272. // Sets an insert's input source (undoable; -1 = none) and opens the device input when needed.
  273. void setInsertInput (int track, int channel, bool stereo);
  274. void setInsertMonitor (int track, InputMonitor mode);
  275. // --- hardware output targets (REA round 156) ---
  276. // Names of the open device's output channels (all of them, open or not); empty without a device.
  277. std::vector<std::string> getOutputChannelNames() const;
  278. // Whether device output channel `c` is open (gets sound) right now.
  279. bool isOutputChannelOpen (int channel) const;
  280. // Sets a track's hardware output target (undoable; outputNone / outputDefault / a device channel) and opens
  281. // the device's output channels it needs (no trip to Audio settings). The Master's default is its first pair.
  282. void setTrackOutput (int track, int channel, OutputMode mode);
  283. // Opens the device output channels the song's targets need (that the device has). UI thread.
  284. void openTargetedOutputs();
  285. // The hardware inserts' channels (round 164d): opens their outputs and, when one returns from an input, the device
  286. // input. UI thread.
  287. void openHardwareInsertIo();
  288. // Every hardware insert of the song (round 165c): a mixer slot's, or a node inside a Patcher (mixer-slot or generator
  289. // Patcher; `nodes` = the node index at each Patcher level). UI thread.
  290. struct HardwareInsertRef
  291. {
  292. bool channel = false; // a Channel Rack generator Patcher (index = channel), else a mixer slot (index = track)
  293. int index = 0, slot = 0;
  294. std::vector<int> nodes;
  295. bool operator== (const HardwareInsertRef&) const = default;
  296. };
  297. std::vector<HardwareInsertRef> getHardwareInserts() const;
  298. static EffectSlot* locateHardwareInsert (Song& song, const HardwareInsertRef& ref);
  299. std::shared_ptr<Effect> runningHardwareInsert (const HardwareInsertRef& ref) const;
  300. // The routed, active inserts whose round trip was measured for another device setup (device, rate or buffer size)
  301. std::vector<HardwareInsertRef> staleHardwareInserts() const;
  302. // Presses their Ping buttons (the clicks go out on their sends; the results are applied as they come back)
  303. void pingHardwareInserts (const std::vector<HardwareInsertRef>& refs);
  304. // After the device setup changed with stale inserts in the song: those inserts, once (the UI offers "Ping now")
  305. std::vector<HardwareInsertRef> takeHardwareInsertNotice() { return std::exchange (hwNotice, {}); }
  306. // Input level of an insert's source since the last call (0..1, per side). UI thread.
  307. // (the Mixer's strips take it 30 times a second; other views peek at the last value taken)
  308. float takeInputPeak (int track, int side) noexcept
  309. {
  310. const auto v = liveInput.meters.takePeak (track, side);
  311. if (track >= 0 && track < maxMixerTracks && (side == 0 || side == 1))
  312. lastInputPeaks[(std::size_t) (track * 2 + side)] = v;
  313. return v;
  314. }
  315. float peekInputPeak (int track, int side) const noexcept
  316. {
  317. return track >= 0 && track < maxMixerTracks && (side == 0 || side == 1) ? lastInputPeaks[(std::size_t) (track * 2 + side)] : 0.0f;
  318. }
  319. // A message for the user about recording (e.g. an armed insert without an input), once. UI thread.
  320. RecordingNotice takeRecordingNotice() { return std::exchange (recordingNotice, {}); }
  321. // MIDI learn: the next CC received becomes a controller linked to `target`.
  322. void learnMidiController (const AutomationTarget& target);
  323. bool isLearningMidi() const noexcept { return learning.kind != AutomationTargetKind::none; }
  324. // Global links (FL's "Override global link...", REA round 146): links in the MIDI settings that every project
  325. // follows unless it links the same target or controller itself. The next CC received becomes `target`'s.
  326. void learnGlobalLink (const AutomationTarget& target);
  327. void removeGlobalLink (const AutomationTarget& target);
  328. std::optional<MidiLink> globalLinkOf (const AutomationTarget& target) const;
  329. std::vector<MidiLink> getGlobalLinks() const;
  330. // FL's "Last tweaked" (REA round 143: FLEngine keeps the last two moved parameters, Tools › Last tweaked /
  331. // Next to last tweaked, Add › Automation for last tweaked parameter). Every control that can be automated reports
  332. // its moves here (UI thread); `held` = the touch lasts until tweakReleased (a plugin's own editor's gesture),
  333. // otherwise while the control keeps moving. While recording with the "Automation" filter, touched parameters are
  334. // written as automation.
  335. void noteTweaked (const AutomationTarget& target, bool held = false);
  336. void tweakReleased (const AutomationTarget& target);
  337. // 0 = the last tweaked parameter, 1 = the one before it.
  338. std::optional<AutomationTarget> getLastTweaked (int which = 0) const;
  339. // The target's current value 0..1 (a hosted plugin's parameter and MIDI controls included); < 0 when it is gone.
  340. float currentTargetValue (const AutomationTarget& target) const;
  341. // Parameter `param` of a hosted plugin (a channel's instrument or a slot's effect) as an automation target.
  342. std::optional<AutomationTarget> targetOfPlugin (const juce::AudioPluginInstance& plugin, int param) const;
  343. // Number of points recorded as automation since recording started (tests, hint bar).
  344. int getRecordedAutomationPoints() const noexcept { return recordedAutomationPoints; }
  345. // Names a new recorded automation (the UI sets it to its readable target names).
  346. std::function<std::string (const AutomationTarget&)> nameAutomation;
  347. // MIDI inputs: every device is enabled and plays the selected channels unless the MIDI settings say otherwise
  348. // (Settings › MIDI: device off, one MIDI channel only, a fixed Channel Rack channel; velocity curve; pickup).
  349. juce::StringArray getActiveMidiInputs() const;
  350. // Counts the messages received from the enabled MIDI inputs (the toolbar's MIDI activity light).
  351. std::uint32_t getMidiActivity() const noexcept { return midiActivity.load (std::memory_order_relaxed); }
  352. // Closes and opens again every enabled MIDI input (the MIDI light's click; Settings › MIDI › Refresh).
  353. void reconnectMidiInputs();
  354. const prefs::MidiPrefs& getMidiPrefs() const noexcept { return midiPrefs; }
  355. // Applies them (and saves them in %APPDATA%\LYNX\midi-settings.txt when `save`).
  356. void setMidiPrefs (const prefs::MidiPrefs& prefs, bool save = true);
  357. // master sync out / external clock in / all notes off (round 165f)
  358. MidiSyncIo& getMidiSync() noexcept { return midiSync; }
  359. // How many undo steps are kept (Settings › General).
  360. void setUndoLevels (int levels);
  361. int getUndoLevels() const noexcept { return (int) maxUndoSteps; }
  362. // Document (UI thread)
  363. const Song& getSong() const noexcept { return song; }
  364. void setSong (Song newSong); // new/opened project: clears the history
  365. // Edits the song and publishes it to audio. `undoable` edits go into the history;
  366. // all edits made while the same mouse click is held down
  367. // (dragging a note, turning a knob) become a single step.
  368. void editSong (const std::function<void (Song&)>& edit, bool undoable = true);
  369. // Changes since the last save/open (for the "*" in the title and the "save changes?" prompt).
  370. bool isModified() const noexcept { return modified; }
  371. void markSaved() noexcept { modified = false; sendChangeMessage(); }
  372. void markModified() noexcept { modified = true; sendChangeMessage(); } // e.g. a backup was opened in place of the project
  373. bool canUndo() const noexcept { return ! undoStack.empty(); }
  374. bool canRedo() const noexcept { return ! redoStack.empty(); }
  375. void undo();
  376. void redo();
  377. // Undo history as a list of states, oldest first: the undo steps, the current state, then the redo
  378. // steps. Each entry is named after what changed from the previous one (core/History.h).
  379. int getHistorySize() const noexcept { return (int) (undoStack.size() + 1 + redoStack.size()); }
  380. int getHistoryPosition() const noexcept { return (int) undoStack.size(); }
  381. ChangeLabel getHistoryLabel (int index) const; // index 0 = the oldest state kept
  382. void jumpToHistory (int index);
  383. // Channel selected in the Channel Rack (target of the Piano Roll and keyboard). UI thread.
  384. int getSelectedChannel() const noexcept { return selectedChannel; }
  385. void setSelectedChannel (int channel); // selects only this channel
  386. // Multi-selection in the Channel Rack (sorted). The selected channels all receive live MIDI input;
  387. // `primary` (one of them) is the Piano Roll / keyboard target above.
  388. const std::vector<int>& getSelectedChannels() const noexcept { return selectedChannels; }
  389. void setChannelSelection (std::vector<int> channels, int primary);
  390. // Imports a .flp, locating the FL installation to find the samples.
  391. // Returns false and fills `error` on failure. `relocations` (saved sample path → file to use) are the samples
  392. // the user located; with `asEdit` the result replaces the song as one undoable step instead of a new project.
  393. bool importFlpFile (const juce::File& file, juce::String& error, const std::map<std::string, std::string>& relocations = {},
  394. bool asEdit = false);
  395. // The same import in steps, so a window can show progress while it runs (round 112): `prepareFlpImport` reads,
  396. // parses and imports the project and decodes its samples in parallel — no plugin is touched, so it may run on any
  397. // thread; `preloadPlugins` creates the project's hosted plugins one at a time (message thread; call it until it
  398. // returns false); `finishFlpImport` adopts the result as the song (message thread). Phase times go to core/LoadTrace.
  399. struct PreparedFlp
  400. {
  401. bool ok = false;
  402. juce::String error;
  403. Song song;
  404. FlpImportReport report;
  405. std::vector<std::shared_ptr<const SampleData>> decoded; // kept alive until the rack is built
  406. std::vector<PluginRef> pluginQueue; // hosted plugins to create, in rack order
  407. std::size_t pluginsDone = 0;
  408. bool adopted = false;
  409. juce::StringArray missing, matched, withoutState, substituted;
  410. struct Use
  411. {
  412. std::string name, user;
  413. bool instrument = false;
  414. };
  415. std::vector<Use> uses;
  416. };
  417. static void prepareFlpImport (const juce::File& file, const std::map<std::string, std::string>& relocations, SampleLibrary& library,
  418. PreparedFlp& out);
  419. // one hosted plugin of the queue (message thread); false when the queue is done
  420. bool preloadNextPlugin (PreparedFlp& prepared);
  421. // Before importing the open project again: leaves out of `prepared`'s plugin queue those the song already runs
  422. // with the same settings (the rack keeps them).
  423. void keepRunningPlugins (PreparedFlp& prepared);
  424. bool finishFlpImport (PreparedFlp&& prepared, bool asEdit);
  425. // --- real-time bounce (round 165c: Export › "Render through the hardware in real time") ---
  426. // The song plays through the audio device from `startTick` (song mode; past its end and through the loop region,
  427. // without starting over) while the Master's output is recorded: hardware inserts send to and return from their gear
  428. // as they do while playing. Message thread; returns an error (empty: started).
  429. juce::String startRealtimeBounce (double startTick);
  430. // What the Master played since the last call, from the first sample the song played (one consumer thread).
  431. int pullRealtimeBounce (std::vector<float>& left, std::vector<float>& right) { return meters.bounceTap.pull (left, right); }
  432. bool isBouncing() const noexcept { return bouncing; }
  433. // While bouncing: the transport still plays (false: the user stopped it), the delay compensation's total at the
  434. // start, the device's dropouts and the frames the tap lost since the start.
  435. bool bounceStillPlaying() const noexcept { return transport.playing.load(); }
  436. int bounceLatency() const noexcept { return bounceStartLatency; }
  437. int bounceDropouts() const;
  438. // Stops playback and puts the transport back as it was (message thread).
  439. void finishRealtimeBounce();
  440. // Renders without an audio device. Writes to `output` if not nullptr.
  441. // After `seconds`, continues for up to `tailSeconds` while there is still sound.
  442. // `progress(0..1)` returns false to cancel. Returns the peak (used by the self-test),
  443. // or -1 if cancelled.
  444. struct RenderOptions
  445. {
  446. double seconds = 10.0;
  447. double sampleRate = 44100.0;
  448. juce::AudioFormatWriter* output = nullptr;
  449. std::function<bool (double)> progress; // 0..1; false cancels
  450. double tailSeconds = 0.0;
  451. int trimSamples = 0; // PDC: discards this much from the start and renders the same amount extra at the end
  452. int ditherBits = 0; // > 0: TPDF dither (with noise shaping unless ditherShaping is false) for this bit depth
  453. bool ditherShaping = true;
  454. // FL's "HQ for all plugins": render qualities and HQ switches on (off: the playback quality)
  455. bool hqAllPlugins = true;
  456. // receives every rendered block after the PDC trim (left, right, frames), like `output` does
  457. std::function<void (const float*, const float*, int)> capture;
  458. // trim the delay compensation's latency as the plugins report it after the warm-up (adds to trimSamples)
  459. bool trimPdc = false;
  460. // Export "Plugin warm-up" (round 155, core/PluginWarmup.h): with hosted plugins in the song, silent blocks are
  461. // processed and thrown away before the render until the plugins have settled
  462. bool pluginWarmUp = true;
  463. warmup::Settings warmUp;
  464. // false: samples above 0 dBFS are clamped to ±1 before the dither / the file (integer formats, Ogg)
  465. bool keepOvers = false;
  466. };
  467. float renderOffline (const RenderOptions& options);
  468. // timings of the last renderOffline (diagnostics): the audio graph and the file writing
  469. struct RenderStats
  470. {
  471. double graphMs = 0.0, writeMs = 0.0;
  472. warmup::Result warmUp; // the plugin warm-up before the render (blocks == 0: none ran)
  473. int trimmedSamples = 0; // the PDC trim used
  474. };
  475. RenderStats getLastRenderStats() const noexcept { return lastRenderStats; }
  476. float renderOffline (double seconds, double sampleRate, juce::AudioFormatWriter* output = nullptr)
  477. {
  478. RenderOptions o;
  479. o.seconds = seconds;
  480. o.sampleRate = sampleRate;
  481. o.output = output;
  482. return renderOffline (o);
  483. }
  484. int getNumGraphConnections() const { return (int) graph.getConnections().size(); }
  485. // Time spent in each instrument and effect (the Plugin performance monitor); nullptr without the rack node.
  486. ProcessTimes* getProcessTimes() noexcept;
  487. // Latest output samples (mono), for the oscilloscope. UI thread.
  488. void copyScope (float* destination, int count) const noexcept;
  489. static constexpr int scopeSize = 2048;
  490. // Real-time health of the audio callback (REA round 87): callbacks over their deadline, late device calls, load.
  491. const RtStats& getRtStats() const noexcept { return rtStats; }
  492. RtStats& getRtStats() noexcept { return rtStats; }
  493. // What takes the most audio CPU: channels and insert effects, as a share of real time over the last ~2 s of
  494. // playback, heaviest first. UI thread.
  495. struct UnitLoad
  496. {
  497. juce::String name;
  498. double load = 0.0; // CPU time / audio time (summed over the worker threads)
  499. double longestMs = 0.0; // the longest single call in the window
  500. };
  501. const std::vector<UnitLoad>& getHeaviestUnits() const noexcept { return heaviestUnits; }
  502. // How regularly the message thread runs the engine's 30 Hz timer (a saturated UI delays it). UI thread.
  503. struct UiPulse
  504. {
  505. int calls = 0;
  506. double maxGapMs = 0.0;
  507. };
  508. UiPulse takeUiPulse() noexcept { return std::exchange (uiPulse, {}); }
  509. // Writes `state` (a createStateXml() taken earlier; nullptr = none was saved) back as the saved device and stops
  510. // saving later changes: a test run (--rtstress --type ...) leaves the user's device as it found it.
  511. void restoreAudioDeviceState (const juce::XmlElement* state);
  512. // Device, buffer, deadline and the callback statistics in a few lines (CPU meter hint, glitch log, --rtstress).
  513. juce::String describeRealtime (bool withUnits = true) const;
  514. // %APPDATA%\LYNX\audio-glitches.log: a line each time callbacks run over their deadline (at most every 2 s).
  515. static juce::File glitchLogFile();
  516. // Total latency compensated by PDC (at the Master output), in samples.
  517. int getLatencySamples() const noexcept { return lastPublishedShape.pdc.total; }
  518. // The last published PDC plan (per-track latencies: outLat, inAlign). Message thread.
  519. const PdcPlan& getPdcPlan() const noexcept { return lastPublishedShape.pdc; }
  520. private:
  521. void audioDeviceIOCallbackWithContext (const float* const* inputChannelData,
  522. int numInputChannels,
  523. float* const* outputChannelData,
  524. int numOutputChannels,
  525. int numSamples,
  526. const juce::AudioIODeviceCallbackContext& context) override;
  527. void audioDeviceAboutToStart (juce::AudioIODevice* device) override;
  528. void audioDeviceStopped() override;
  529. void timerCallback() override;
  530. void handleIncomingMidiMessage (juce::MidiInput* source, const juce::MidiMessage& message) override;
  531. void enableAllMidiInputs();
  532. void saveAudioDeviceState();
  533. void updateRecording();
  534. void updateAudioRecording();
  535. void updateAutomationRecording (bool active);
  536. void startAudioTake();
  537. void finishAudioTake();
  538. double estimatedPositionNow() const noexcept;
  539. void buildInitialGraph();
  540. void choosePreferredDriver(); // a first start on Linux: PipeWire, then JACK, then ALSA (round 161)
  541. void chooseSafeBufferSize();
  542. void updateRealtimeStats(); // timer: unit loads over a window, glitch log
  543. RtStats rtStats;
  544. std::vector<UnitLoad> heaviestUnits;
  545. std::vector<std::uint64_t> lastChannelNs, lastEffectNs;
  546. std::uint64_t lastProcessedSamples = 0;
  547. double lastUnitsWindowMs = 0.0, lastUiPulseMs = 0.0;
  548. UiPulse uiPulse;
  549. int latencyRepublishes = 0; // PDC re-plans because a unit's latency changed (diagnostics)
  550. juce::String lastLatencyChange;
  551. // hardware inserts (round 165c): ping results applied to the slots (whether an editor is open or not), and the device
  552. // setup they were measured for
  553. void applyHardwareInsertPings();
  554. std::map<const void*, int> hwPingSerials; // running insert -> the last ping result seen
  555. std::string lastSetupKey;
  556. std::vector<HardwareInsertRef> hwNotice;
  557. int hwTicks = 0;
  558. bool bouncing = false;
  559. int bounceStartLatency = 0, bounceStartXruns = 0;
  560. double bounceReturnTick = 0.0;
  561. bool bounceRestoreMode = false;
  562. bool checkHardwareInserts = false;
  563. std::uint64_t loggedOver = 0, loggedLate = 0;
  564. double lastLogMs = 0.0;
  565. class PreviewPlayer* preview = nullptr; // graph node (owned by the graph)
  566. double previewVolume = 1.0;
  567. double editorVolume = 1.0;
  568. void publishSong();
  569. void adoptPrepared (PreparedFlp& prepared); // the plugins of a prepared import found / substituted (message thread)
  570. std::unique_ptr<WorkerPool> workers; // extra renderer threads (before the graph, which uses them)
  571. juce::AudioDeviceManager deviceManager;
  572. juce::AudioProcessorGraph graph;
  573. juce::AudioProcessorPlayer player;
  574. Transport transport;
  575. MidiSyncIo midiSync; // (before the MIDI callbacks and the audio callback use it)
  576. SampleLibrary samples;
  577. LiveEventQueue liveEvents; // UI -> audio
  578. LiveEventQueue midiEvents; // MIDI thread -> audio
  579. InputHeldNotes midiHeld; // MIDI thread: what each held MIDI key started
  580. std::atomic<std::uint64_t> heldKeyBits[2] {}; // keys held on MIDI inputs / the typing piano (chord readout)
  581. std::atomic<std::uint8_t> heldKeyCount[128] {};
  582. void markHeldKey (int key, bool on) noexcept;
  583. KeyLedger playedKeys; // UI thread: the keys the typing piano started (after the scale snap)
  584. SpscQueue<RecordedEvent, 1024> midiRecordQueue; // MIDI thread -> UI (recording)
  585. // a controller's pitch wheel while recording (MIDI thread -> UI): key = its MIDI channel 0…15, velocity = 0..1;
  586. // written as the channel's pitch bend automation like a moved knob (issue #12: the bend was heard, not recorded)
  587. SpscQueue<RecordedEvent, 2048> bendRecordQueue;
  588. std::map<int, float> liveBends; // UI thread: the last recorded bend of each channel (its "current value")
  589. void takeRecordedBends();
  590. struct ControllerEvent
  591. {
  592. int cc = 0, channel = 0, value = 0;
  593. };
  594. SpscQueue<ControllerEvent, 1024> controllerQueue; // MIDI thread -> UI (controllers)
  595. // the CCs a MIDI link (project or global) uses: they move their parameter and are not also played into the
  596. // selected channel's instrument (round 162); written by applyControllers, read by the MIDI thread
  597. std::array<std::atomic<std::uint64_t>, 2> linkedCcs {};
  598. AutomationTarget learning;
  599. bool learningGlobal = false;
  600. bool saveGlobalLinks = false; // only the engine with an audio device (the app) writes the settings file
  601. void applyControllers();
  602. std::vector<RecordedEvent> uiRecorded; // PC keyboard -> recording
  603. NoteRecorder recorder;
  604. // last tweaked parameters and automation recording (REA round 143)
  605. std::array<AutomationTarget, 2> lastTweaked {};
  606. struct Touch
  607. {
  608. AutomationTarget target;
  609. double lastMs = 0.0;
  610. bool held = false;
  611. std::vector<RecordedValue> pending; // sampled, not yet written
  612. };
  613. std::vector<Touch> touches;
  614. int automationCommitCountdown = 0;
  615. bool automationTakeHasUndoStep = false;
  616. std::int64_t automationLoopLength = 0;
  617. int automationPattern = 0;
  618. int recordedAutomationPoints = 0;
  619. bool automationOverrideActive = false; // touched targets override their automation in the renderer
  620. // Song mode, no loop region: once a parameter moved while recording, the song plays on past its end (no wrap to
  621. // the start) until recording stops, and the take's clip grows with the playhead (issue #12: it cut itself)
  622. bool automationLinear = false;
  623. std::int64_t lastAutomationTick = -1; // the song position of the take's last update (song mode)
  624. std::vector<AutomationWrite> takeWrites; // per target: where this take writes (its own clip grows)
  625. bool takeHasUndoStep = false;
  626. bool perfTakeHasUndoStep = false; // the first clip a performance recording writes is the take's undo step
  627. void updatePerformanceRecording();
  628. RecordOptions recordOptions;
  629. std::vector<int> takeClearedChannels; // replace mode: channels already cleared in this take
  630. double takeStartPosition = 0.0;
  631. std::atomic<bool> waitingForInput { false };
  632. void startOnInput() noexcept; // MIDI or UI thread: the first note while waiting starts playback
  633. std::vector<int> armedInserts;
  634. juce::String releasedInputDevice; // the input device releaseAudioInputIfUnused closed (reopened by name)
  635. double lastPlayingTick = 0.0;
  636. std::atomic<int> inputScale { 0 }, inputScaleRoot { 0 };
  637. std::atomic<int> liveChannel { 0 }; // selected channel, read by the MIDI thread
  638. static constexpr int maxLiveChannels = 16; // other selected channels that also get MIDI input
  639. std::array<std::atomic<int>, maxLiveChannels> extraLiveChannels {};
  640. std::atomic<int> extraLiveCount { 0 };
  641. void publishSelection();
  642. std::atomic<double> blockTimeMs { 0.0 }; // when positionTicks was last updated
  643. std::array<std::atomic<float>, scopeSize> scope {}; // ring buffer of the output (written by audio)
  644. std::atomic<int> scopeWrite { 0 };
  645. juce::MidiDeviceListConnection midiDevicesChanged;
  646. std::vector<std::string> lastMidiInputIds; // the MIDI inputs available at the last check (UI thread)
  647. int midiCheckTicks = 0;
  648. std::atomic<std::uint32_t> midiActivity { 0 };
  649. prefs::MidiPrefs midiPrefs; // UI thread
  650. juce::SpinLock midiPrefsLock; // guards midiPrefsShared (UI writes, MIDI thread reads)
  651. prefs::MidiPrefs midiPrefsShared;
  652. void logPlayedNote (int channel, int key, float velocity, bool on);
  653. mutable juce::SpinLock scoreLogLock; // MIDI thread and UI thread write, the UI reads
  654. scorelog::Log scoreLog;
  655. std::map<std::tuple<int, int, int, int, int, int>, prefs::PickupState> pickups; // (cc, channel, target) -> takeover
  656. struct DeviceStateSaver;
  657. std::unique_ptr<DeviceStateSaver> deviceStateSaver;
  658. // audio recording
  659. bool audioArmed = false;
  660. juce::String recordingError;
  661. juce::File recordingFolder = defaultRecordingFolder();
  662. juce::String recordingStem;
  663. std::vector<juce::File> sessionRecordings;
  664. juce::TimeSliceThread recordThread { "LYNX recording" };
  665. RecordingNotice recordingNotice;
  666. void notify (InputIssue issue, int track = 0, const juce::String& detail = {});
  667. // One take being recorded (round 163): the audio thread pushes into `stream`, the recording thread drains it
  668. // into `writer` (crash-safe WAV). Shared by the UI (start/finish), the audio thread (raw pointer under
  669. // takeLock) and the recording thread (drainer list under drainLock).
  670. struct Take
  671. {
  672. int track = 0; // insert it plays through (0 = a new free insert)
  673. int first = 0; // device input channel
  674. int channels = 0; // 1 or 2
  675. juce::File file;
  676. std::unique_ptr<takes::TakeStream> stream;
  677. takes::WavTakeWriter writer;
  678. std::atomic<bool> failed { false };
  679. std::vector<float> scratch;
  680. juce::CriticalSection drainMutex; // the recording thread vs the UI's final drain
  681. // recording thread: writes what arrived; false when the file could not be written
  682. bool drain();
  683. };
  684. static constexpr int maxTakes = 16;
  685. std::array<Take*, maxTakes> takes {}; // guarded by takeLock (the audio thread's view)
  686. int takeCount = 0;
  687. std::vector<std::shared_ptr<Take>> openTakes; // UI thread (owner)
  688. juce::CriticalSection drainLock; // the recording thread's list
  689. std::vector<std::shared_ptr<Take>> draining;
  690. struct Drainer;
  691. std::unique_ptr<Drainer> drainer;
  692. juce::SpinLock takeLock; // the audio thread only tries (never waits)
  693. LiveInput liveInput;
  694. std::unique_ptr<perf::Live> performanceLive = std::make_unique<perf::Live>(); // Performance mode (round 165m)
  695. std::atomic<int> performanceMidiChannel { 0 }; // MidiPrefs::performanceChannel (UI writes, MIDI thread reads)
  696. std::atomic<bool> performanceMidiOn { false }; // Performance mode is on with a zone (UI writes, MIDI thread reads)
  697. perf::MidiMapping performanceMidi; // MIDI thread only
  698. HardwareOutput hwOutput; // inserts' hardware outputs (renderer -> callback)
  699. std::array<int, HardwareOutput::maxChannels> outputSlot {}; // device output channel -> callback output index (-1: closed)
  700. std::atomic<int> masterOutChannel { outputDefault }; // the Master's target (UI -> audio)
  701. std::atomic<int> masterOutMode { 0 };
  702. std::vector<float> masterScratch = std::vector<float> (2 * HardwareOutput::capacity, 0.0f);
  703. void routeOutputs (float* const* outputs, int numOutputs, int n) noexcept; // audio thread
  704. std::array<float, maxMixerTracks * 2> lastInputPeaks {};
  705. std::array<int, LiveInput::maxChannels> inputSlot {}; // device input channel -> callback input index (-1: closed)
  706. std::atomic<double> takeStartTick { -1.0 }; // position of the first recorded sample
  707. std::atomic<juce::int64> takeFrames { 0 };
  708. std::atomic<double> takeTicks { 0.0 }; // ticks the transport moved while recording (not wrapped)
  709. std::array<std::atomic<juce::int64>, 256> takeWraps {}; // take frames at which the loop jumped back (loop recording)
  710. std::atomic<int> takeWrapCount { 0 };
  711. double takeSampleRate = 44100.0;
  712. double takeTicksPerSample = 0.0;
  713. int takeLatency = 0; // takes::Latency::total() at the take's start, in samples
  714. std::optional<PunchRange> activePunch; // pre-roll / punch range of the recording in progress (UI thread)
  715. std::int64_t punchStopAt = -1; // post-roll end: playback stops there (-1: none)
  716. bool linearRecording() const noexcept
  717. {
  718. return song.mode == PlayMode::song && (! song.hasLoop() || recordOptions.punchLoopRegion);
  719. }
  720. // the audio thread's view of the above while takes record (false when none is open)
  721. void updateLinearSong() noexcept
  722. {
  723. const auto on = (takeCount > 0 || automationLinear) && linearRecording();
  724. liveInput.linearSong.store (on || bouncing);
  725. liveInput.noLoopRegion.store ((on && song.hasLoop()) || bouncing);
  726. }
  727. takes::LatencyPing ping; // audio thread while running (UI starts it, reads the result)
  728. juce::int64 lostFrames = 0;
  729. std::array<int, 2> pingOutputs { -1, -1 }; // callback output slots the click goes to
  730. int pingInput = -1; // callback input slot listened to
  731. RecordingSettings recordingSettings;
  732. juce::File journalFor (const juce::File& wav) const { return wav.withFileExtension ("wav.lynxrec"); }
  733. void writeJournals();
  734. bool journalsWritten = false;
  735. MeterBank meters;
  736. std::unique_ptr<AudioLogger> audioLogger; // after `meters` (it reads meters.logTap): destroyed first
  737. PluginHost plugins;
  738. juce::StringArray missingPlugins, matchedPlugins, pluginsWithoutState;
  739. FlpImportReport importReport;
  740. std::vector<MissingPlugin> missingPluginDetails;
  741. RenderStats lastRenderStats;
  742. class ChannelRackProcessor* rackProcessor = nullptr; // graph node (owner: the graph)
  743. Song song;
  744. int selectedChannel = 0;
  745. std::vector<int> selectedChannels { 0 };
  746. bool modified = false;
  747. std::unique_ptr<StreamPrefetcher> prefetcher; // only with an audio device (playing live)
  748. std::size_t maxUndoSteps = prefs::defaultUndoLevels;
  749. std::deque<Song> undoStack, redoStack;
  750. juce::Time lastUndoPress; // mouse click that already produced an undo step
  751. SnapshotExchange<RackState> rackExchange;
  752. RackState lastPublishedShape; // channels + instruments of the last snapshot, to reuse voices
  753. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioEngine)
  754. };
  755. } // namespace lynx