AudioEngine.h 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624
  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/WorkerPool.h"
  17. #include "core/RackRenderer.h"
  18. #include "core/RtStats.h"
  19. #include "core/FlpImport.h"
  20. #include "core/History.h"
  21. #include "core/NativeEngines.h"
  22. #include "core/PluginWarmup.h"
  23. #include "core/SnapshotExchange.h"
  24. #include "core/Song.h"
  25. #include "engine/PluginHost.h"
  26. #include "engine/SampleLibrary.h"
  27. #include "engine/StreamPrefetcher.h"
  28. #include "engine/Transport.h"
  29. namespace lynx
  30. {
  31. class AudioLogger;
  32. // Owns the audio device, the processing graph and the document (Song).
  33. // Sits between the driver and the AudioProcessorPlayer to advance the transport
  34. // after each block, so every node sees the same start position.
  35. //
  36. // The Song is touched only by the UI thread; each edit publishes an immutable
  37. // snapshot (RackState) to the audio thread.
  38. // Folders of the most recent FL Studio installation (empty if none).
  39. FlPathRoots findFlStudioRoots();
  40. // The user's FL installation as the native FL engines read it (round 142): its folders and this PC's file system
  41. const natives::FlAccess& flStudioAccess(); // (found once per session)
  42. class AudioEngine final : private juce::AudioIODeviceCallback,
  43. private juce::MidiInputCallback,
  44. public juce::ChangeBroadcaster,
  45. private juce::Timer
  46. {
  47. public:
  48. explicit AudioEngine (bool openAudioDevice = true);
  49. ~AudioEngine() override;
  50. juce::AudioDeviceManager& getDeviceManager() noexcept { return deviceManager; }
  51. Transport& getTransport() noexcept { return transport; }
  52. SampleLibrary& getSampleLibrary() noexcept { return samples; }
  53. MeterBank& getMeters() noexcept { return meters; }
  54. // Tools > Audio logger (REA round 153): records everything the Master plays to a WAV in the background.
  55. AudioLogger& getAudioLogger();
  56. PluginHost& getPluginHost() noexcept { return plugins; }
  57. // Third-party plugins from the last imported .flp that were not found among the scanned ones.
  58. const juce::StringArray& getMissingPlugins() const noexcept { return missingPlugins; }
  59. // "plugin → file (how it was found)" for the plugins of the last imported .flp
  60. const juce::StringArray& getMatchedPlugins() const noexcept { return matchedPlugins; }
  61. // plugins found whose saved settings could not be carried over (VST2 <-> VST3): "name (format)"
  62. const juce::StringArray& getPluginsWithoutState() const noexcept { return pluginsWithoutState; }
  63. // What the last imported .flp converted, approximated or left out.
  64. const FlpImportReport& getImportReport() const noexcept { return importReport; }
  65. // The last imported .flp's plugins that were not found, with what uses them and what LYNX put in their place.
  66. const std::vector<MissingPlugin>& getMissingPluginDetails() const noexcept { return missingPluginDetails; }
  67. // Live instances (to open the plugin window). nullptr if not a plugin.
  68. std::shared_ptr<Instrument> getChannelInstrument (int channel) const;
  69. std::shared_ptr<Effect> getEffect (int track, int slot) const;
  70. // Copies the plugins' current state into the Song (before saving).
  71. void capturePluginStates();
  72. // Offline render mode for the hosted plugins (setNonRealtime), around renderOffline.
  73. void setPluginsRenderMode (bool offline);
  74. // Every hosted plugin of the song that has not crashed (channels, inserts, inside Patchers); `notifyRender` is the
  75. // plugin's "Notify about rendering mode" option. Message thread or the render thread, while nothing else edits.
  76. void forEachHostedPlugin (const std::function<void (juce::AudioPluginInstance&, bool notifyRender)>& visit) const;
  77. // The render's plugin warm-up (renderOffline, round 155): silent discarded blocks until the hosted plugins settle,
  78. // then a new PDC plan if a latency changed and LYNX's own units reset. Returns blocks == 0 when the song has no
  79. // hosted plugin. `latency` receives the delay compensation's total afterwards.
  80. warmup::Result warmUpPlugins (const warmup::Settings& settings, double sampleRate, int blockSize,
  81. const std::function<bool (double)>& progress, int& latency);
  82. void play() noexcept;
  83. void stop() noexcept; // also cancels a count-in or a wait for the first note
  84. // Recording options (docs/WORKFLOW_FL.md P2: recording set). UI thread.
  85. struct RecordOptions
  86. {
  87. int countInBars = 0; // 0 = off
  88. bool waitForInput = false; // playback starts at the first played note
  89. RecordMode mode = RecordMode::overdub;
  90. std::int64_t quantise = 0; // record quantise in ticks (<= 1: as played); follows the global grid
  91. bool placeSongClip = true; // song mode: a take puts a clip of the pattern where recording started
  92. // recording filter (FL's record button right-click, REA_rodada88): what a take records
  93. bool recordNotes = true; // notes played (MIDI and PC keyboard)
  94. bool recordAudio = true; // audio of the armed inserts' inputs
  95. bool askWhatToRecord = true; // the record button asks first ("What would you like to record?")
  96. // FL's record menu "Options" (REA round 134): arming recording also starts playback; the armed inserts are
  97. // disarmed when a take stops
  98. bool startsPlayback = false;
  99. bool disarmOnStop = false;
  100. // FL's record menu "Quantize" section (REA round 139); `quantise` is the grid. quantiseStarts = "Note start
  101. // time", noteEnd = "Note end time" (quantize) / "Leave note duration" (keepLength) / neither (keepEnd),
  102. // toStepSequencer = "Record to step sequencer"
  103. bool quantiseStarts = true;
  104. NoteEnd noteEnd = NoteEnd::keepLength;
  105. bool toStepSequencer = false;
  106. // FL's "Enable recording markers": the Playlist's "Start recording" / "Stop recording" markers limit what a
  107. // take keeps in song mode (notes started outside are dropped, audio clips are cut to the ranges)
  108. bool recordingMarkers = false;
  109. // FL's recording filter "Automation" (REA round 143): moved parameters become automation (song mode: automation
  110. // clips; pattern mode: the pattern's events); Quantize › "Automations" puts their points on the snap
  111. bool recordAutomation = true;
  112. bool quantiseAutomation = false;
  113. };
  114. const RecordOptions& getRecordOptions() const noexcept { return recordOptions; }
  115. void setRecordOptions (const RecordOptions& options);
  116. // Play pressed: with recording on, honours wait-for-input and the count-in; otherwise play().
  117. void startPlayback();
  118. // The song's initial values (FL's initialized controls) back on their targets, in song mode; play() and a
  119. // seek while playing do it (REA round 146). UI thread.
  120. void resetToInitialValues() noexcept;
  121. bool isWaitingForInput() const noexcept { return waitingForInput.load(); }
  122. bool isCountingIn() const noexcept { return transport.countIn.load() > 0.0; }
  123. // Per-insert record arm: each armed insert records its own audio input (Mixer › insert › input source) into
  124. // its own take (arming one turns audio recording on; disarming the last one turns it off). Not saved.
  125. void setInsertArmed (int track, bool armed);
  126. bool isInsertArmed (int track) const noexcept;
  127. const std::vector<int>& getArmedInserts() const noexcept { return armedInserts; }
  128. void rewind() noexcept;
  129. void seek (double ticks) noexcept;
  130. // Preview of an audio file (browser). An invalid/empty file stops the preview.
  131. void previewFile (const juce::File& file);
  132. // The Browser's preview volume (0..1.25, 1 = default; core/ValueMath.h previewGain). Applies to the preview
  133. // playing now too. UI thread.
  134. void setPreviewVolume (double volume) noexcept;
  135. double getPreviewVolume() const noexcept { return previewVolume; }
  136. // Plays a sound made in memory through the same preview output (the start-up sound). UI thread.
  137. void previewSample (std::shared_ptr<const SampleData> sample, bool loop = false, float gain = 0.8f, bool audioEditor = false);
  138. // The Audio Editor's playback volume (its toolbar knob, round 162): 0..1.25 like the Browser's, 1 = unity.
  139. void setEditorVolume (double volume) noexcept;
  140. double getEditorVolume() const noexcept { return editorVolume; }
  141. // The frame of the previewed sample being played, -1 when the preview is silent.
  142. double getPreviewPosition() const noexcept;
  143. // Note played live (PC keyboard, preview). UI thread.
  144. // `record` = goes into the recording if recording is on (Piano Roll preview doesn't).
  145. void sendLiveNote (int channel, int key, float velocity, bool on, bool record = false);
  146. // The keys held right now on MIDI inputs and the typing piano (as played, before the scale snap), ascending; for
  147. // the Piano Roll's chord readout (any thread).
  148. std::vector<int> heldInputKeys() const;
  149. // Scale snap for played notes (MIDI input and the PC keyboard): scale index into notetools::scales()
  150. // (0 = off) and its root (0..11). Any thread.
  151. void setInputScale (int scale, int root) noexcept;
  152. int snapInputKey (int key) const noexcept;
  153. // All notes off on every channel (double-click on Stop). UI thread.
  154. void panic();
  155. // Note recording (MIDI and PC keyboard) into the current pattern while playing. UI thread.
  156. void setRecording (bool shouldRecord);
  157. bool isRecording() const noexcept { return transport.recording.load(); }
  158. // Audio recording from the interface input: with this on, recording (Rec + Play) writes the
  159. // input to a WAV and, on stop, the take becomes a Playlist clip (latency-compensated).
  160. // Enabling it opens the device input (only then does Windows show the mic as in use).
  161. void setAudioRecordingArmed (bool armed);
  162. bool isAudioRecordingArmed() const noexcept { return audioArmed; }
  163. juce::String getLastRecordingError() const { return recordingError; }
  164. // Where takes are written and how they are named (FL's project data folder, REA round 134): `folder` is
  165. // "<project folder>/Audio/Recorded" for a saved project (the global recordings folder otherwise), files are
  166. // "<projectStem>_<yyyy-mm-dd hh-mm-ss>_<insert name>.wav". UI thread.
  167. void setRecordingTarget (const juce::File& folder, const juce::String& projectStem);
  168. juce::File getRecordingFolder() const { return recordingFolder; }
  169. static juce::File defaultRecordingFolder();
  170. // The take files written since LYNX started (or since forgetRecordings), oldest first. UI thread.
  171. const std::vector<juce::File>& getSessionRecordings() const noexcept { return sessionRecordings; }
  172. void forgetRecordings (const std::vector<juce::File>& files);
  173. // --- external audio input through the mixer (REA_rodada88) ---
  174. // Names of the open device's input channels (all of them, open or not); empty without an input device.
  175. std::vector<std::string> getInputChannelNames() const;
  176. // Problems the UI explains to the user (translated there).
  177. enum class InputIssue
  178. {
  179. none,
  180. noDevice, // no audio device open at all
  181. noInputDevice, // the driver has no input device
  182. noInputOpen, // recording with no input open
  183. armedWithoutInput, // armed inserts, none with an input source
  184. insertWithoutInput,// one armed insert (track) has no input source
  185. failed // the driver refused (detail = its message) or a file could not be written
  186. };
  187. struct RecordingNotice
  188. {
  189. InputIssue issue = InputIssue::none;
  190. int track = 0;
  191. juce::String detail;
  192. };
  193. // Opens the input of the current driver: `deviceName` (separate-input drivers; empty = the one chosen in
  194. // Settings, else the default), all of its channels. UI thread.
  195. RecordingNotice openAudioInput (const juce::String& deviceName = {});
  196. bool hasAudioInput() const;
  197. // Sets an insert's input source (undoable; -1 = none) and opens the device input when needed.
  198. void setInsertInput (int track, int channel, bool stereo);
  199. void setInsertMonitor (int track, InputMonitor mode);
  200. // --- hardware output targets (REA round 156) ---
  201. // Names of the open device's output channels (all of them, open or not); empty without a device.
  202. std::vector<std::string> getOutputChannelNames() const;
  203. // Whether device output channel `c` is open (gets sound) right now.
  204. bool isOutputChannelOpen (int channel) const;
  205. // Sets a track's hardware output target (undoable; outputNone / outputDefault / a device channel) and opens
  206. // the device's output channels it needs (no trip to Audio settings). The Master's default is its first pair.
  207. void setTrackOutput (int track, int channel, OutputMode mode);
  208. // Opens the device output channels the song's targets need (that the device has). UI thread.
  209. void openTargetedOutputs();
  210. // Input level of an insert's source since the last call (0..1, per side). UI thread.
  211. // (the Mixer's strips take it 30 times a second; other views peek at the last value taken)
  212. float takeInputPeak (int track, int side) noexcept
  213. {
  214. const auto v = liveInput.meters.takePeak (track, side);
  215. if (track >= 0 && track < maxMixerTracks && (side == 0 || side == 1))
  216. lastInputPeaks[(std::size_t) (track * 2 + side)] = v;
  217. return v;
  218. }
  219. float peekInputPeak (int track, int side) const noexcept
  220. {
  221. return track >= 0 && track < maxMixerTracks && (side == 0 || side == 1) ? lastInputPeaks[(std::size_t) (track * 2 + side)] : 0.0f;
  222. }
  223. // A message for the user about recording (e.g. an armed insert without an input), once. UI thread.
  224. RecordingNotice takeRecordingNotice() { return std::exchange (recordingNotice, {}); }
  225. // MIDI learn: the next CC received becomes a controller linked to `target`.
  226. void learnMidiController (const AutomationTarget& target);
  227. bool isLearningMidi() const noexcept { return learning.kind != AutomationTargetKind::none; }
  228. // Global links (FL's "Override global link...", REA round 146): links in the MIDI settings that every project
  229. // follows unless it links the same target or controller itself. The next CC received becomes `target`'s.
  230. void learnGlobalLink (const AutomationTarget& target);
  231. void removeGlobalLink (const AutomationTarget& target);
  232. std::optional<MidiLink> globalLinkOf (const AutomationTarget& target) const;
  233. std::vector<MidiLink> getGlobalLinks() const;
  234. // FL's "Last tweaked" (REA round 143: FLEngine keeps the last two moved parameters, Tools › Last tweaked /
  235. // Next to last tweaked, Add › Automation for last tweaked parameter). Every control that can be automated reports
  236. // its moves here (UI thread); `held` = the touch lasts until tweakReleased (a plugin's own editor's gesture),
  237. // otherwise while the control keeps moving. While recording with the "Automation" filter, touched parameters are
  238. // written as automation.
  239. void noteTweaked (const AutomationTarget& target, bool held = false);
  240. void tweakReleased (const AutomationTarget& target);
  241. // 0 = the last tweaked parameter, 1 = the one before it.
  242. std::optional<AutomationTarget> getLastTweaked (int which = 0) const;
  243. // The target's current value 0..1 (a hosted plugin's parameter and MIDI controls included); < 0 when it is gone.
  244. float currentTargetValue (const AutomationTarget& target) const;
  245. // Parameter `param` of a hosted plugin (a channel's instrument or a slot's effect) as an automation target.
  246. std::optional<AutomationTarget> targetOfPlugin (const juce::AudioPluginInstance& plugin, int param) const;
  247. // Number of points recorded as automation since recording started (tests, hint bar).
  248. int getRecordedAutomationPoints() const noexcept { return recordedAutomationPoints; }
  249. // Names a new recorded automation (the UI sets it to its readable target names).
  250. std::function<std::string (const AutomationTarget&)> nameAutomation;
  251. // MIDI inputs: every device is enabled and plays the selected channels unless the MIDI settings say otherwise
  252. // (Settings › MIDI: device off, one MIDI channel only, a fixed Channel Rack channel; velocity curve; pickup).
  253. juce::StringArray getActiveMidiInputs() const;
  254. // Counts the messages received from the enabled MIDI inputs (the toolbar's MIDI activity light).
  255. std::uint32_t getMidiActivity() const noexcept { return midiActivity.load (std::memory_order_relaxed); }
  256. // Closes and opens again every enabled MIDI input (the MIDI light's click; Settings › MIDI › Refresh).
  257. void reconnectMidiInputs();
  258. const prefs::MidiPrefs& getMidiPrefs() const noexcept { return midiPrefs; }
  259. // Applies them (and saves them in %APPDATA%\LYNX\midi-settings.txt when `save`).
  260. void setMidiPrefs (const prefs::MidiPrefs& prefs, bool save = true);
  261. // How many undo steps are kept (Settings › General).
  262. void setUndoLevels (int levels);
  263. int getUndoLevels() const noexcept { return (int) maxUndoSteps; }
  264. // Document (UI thread)
  265. const Song& getSong() const noexcept { return song; }
  266. void setSong (Song newSong); // new/opened project: clears the history
  267. // Edits the song and publishes it to audio. `undoable` edits go into the history;
  268. // all edits made while the same mouse click is held down
  269. // (dragging a note, turning a knob) become a single step.
  270. void editSong (const std::function<void (Song&)>& edit, bool undoable = true);
  271. // Changes since the last save/open (for the "*" in the title and the "save changes?" prompt).
  272. bool isModified() const noexcept { return modified; }
  273. void markSaved() noexcept { modified = false; sendChangeMessage(); }
  274. void markModified() noexcept { modified = true; sendChangeMessage(); } // e.g. a backup was opened in place of the project
  275. bool canUndo() const noexcept { return ! undoStack.empty(); }
  276. bool canRedo() const noexcept { return ! redoStack.empty(); }
  277. void undo();
  278. void redo();
  279. // Undo history as a list of states, oldest first: the undo steps, the current state, then the redo
  280. // steps. Each entry is named after what changed from the previous one (core/History.h).
  281. int getHistorySize() const noexcept { return (int) (undoStack.size() + 1 + redoStack.size()); }
  282. int getHistoryPosition() const noexcept { return (int) undoStack.size(); }
  283. ChangeLabel getHistoryLabel (int index) const; // index 0 = the oldest state kept
  284. void jumpToHistory (int index);
  285. // Channel selected in the Channel Rack (target of the Piano Roll and keyboard). UI thread.
  286. int getSelectedChannel() const noexcept { return selectedChannel; }
  287. void setSelectedChannel (int channel); // selects only this channel
  288. // Multi-selection in the Channel Rack (sorted). The selected channels all receive live MIDI input;
  289. // `primary` (one of them) is the Piano Roll / keyboard target above.
  290. const std::vector<int>& getSelectedChannels() const noexcept { return selectedChannels; }
  291. void setChannelSelection (std::vector<int> channels, int primary);
  292. // Imports a .flp, locating the FL installation to find the samples.
  293. // Returns false and fills `error` on failure. `relocations` (saved sample path → file to use) are the samples
  294. // the user located; with `asEdit` the result replaces the song as one undoable step instead of a new project.
  295. bool importFlpFile (const juce::File& file, juce::String& error, const std::map<std::string, std::string>& relocations = {},
  296. bool asEdit = false);
  297. // The same import in steps, so a window can show progress while it runs (round 112): `prepareFlpImport` reads,
  298. // parses and imports the project and decodes its samples in parallel — no plugin is touched, so it may run on any
  299. // thread; `preloadPlugins` creates the project's hosted plugins one at a time (message thread; call it until it
  300. // returns false); `finishFlpImport` adopts the result as the song (message thread). Phase times go to core/LoadTrace.
  301. struct PreparedFlp
  302. {
  303. bool ok = false;
  304. juce::String error;
  305. Song song;
  306. FlpImportReport report;
  307. std::vector<std::shared_ptr<const SampleData>> decoded; // kept alive until the rack is built
  308. std::vector<PluginRef> pluginQueue; // hosted plugins to create, in rack order
  309. std::size_t pluginsDone = 0;
  310. bool adopted = false;
  311. juce::StringArray missing, matched, withoutState, substituted;
  312. struct Use
  313. {
  314. std::string name, user;
  315. bool instrument = false;
  316. };
  317. std::vector<Use> uses;
  318. };
  319. static void prepareFlpImport (const juce::File& file, const std::map<std::string, std::string>& relocations, SampleLibrary& library,
  320. PreparedFlp& out);
  321. // one hosted plugin of the queue (message thread); false when the queue is done
  322. bool preloadNextPlugin (PreparedFlp& prepared);
  323. // Before importing the open project again: leaves out of `prepared`'s plugin queue those the song already runs
  324. // with the same settings (the rack keeps them).
  325. void keepRunningPlugins (PreparedFlp& prepared);
  326. bool finishFlpImport (PreparedFlp&& prepared, bool asEdit);
  327. // Renders without an audio device. Writes to `output` if not nullptr.
  328. // After `seconds`, continues for up to `tailSeconds` while there is still sound.
  329. // `progress(0..1)` returns false to cancel. Returns the peak (used by the self-test),
  330. // or -1 if cancelled.
  331. struct RenderOptions
  332. {
  333. double seconds = 10.0;
  334. double sampleRate = 44100.0;
  335. juce::AudioFormatWriter* output = nullptr;
  336. std::function<bool (double)> progress; // 0..1; false cancels
  337. double tailSeconds = 0.0;
  338. int trimSamples = 0; // PDC: discards this much from the start and renders the same amount extra at the end
  339. int ditherBits = 0; // > 0: TPDF dither (with noise shaping unless ditherShaping is false) for this bit depth
  340. bool ditherShaping = true;
  341. // FL's "HQ for all plugins": render qualities and HQ switches on (off: the playback quality)
  342. bool hqAllPlugins = true;
  343. // receives every rendered block after the PDC trim (left, right, frames), like `output` does
  344. std::function<void (const float*, const float*, int)> capture;
  345. // trim the delay compensation's latency as the plugins report it after the warm-up (adds to trimSamples)
  346. bool trimPdc = false;
  347. // Export "Plugin warm-up" (round 155, core/PluginWarmup.h): with hosted plugins in the song, silent blocks are
  348. // processed and thrown away before the render until the plugins have settled
  349. bool pluginWarmUp = true;
  350. warmup::Settings warmUp;
  351. // false: samples above 0 dBFS are clamped to ±1 before the dither / the file (integer formats, Ogg)
  352. bool keepOvers = false;
  353. };
  354. float renderOffline (const RenderOptions& options);
  355. // timings of the last renderOffline (diagnostics): the audio graph and the file writing
  356. struct RenderStats
  357. {
  358. double graphMs = 0.0, writeMs = 0.0;
  359. warmup::Result warmUp; // the plugin warm-up before the render (blocks == 0: none ran)
  360. int trimmedSamples = 0; // the PDC trim used
  361. };
  362. RenderStats getLastRenderStats() const noexcept { return lastRenderStats; }
  363. float renderOffline (double seconds, double sampleRate, juce::AudioFormatWriter* output = nullptr)
  364. {
  365. RenderOptions o;
  366. o.seconds = seconds;
  367. o.sampleRate = sampleRate;
  368. o.output = output;
  369. return renderOffline (o);
  370. }
  371. int getNumGraphConnections() const { return (int) graph.getConnections().size(); }
  372. // Time spent in each instrument and effect (the Plugin performance monitor); nullptr without the rack node.
  373. ProcessTimes* getProcessTimes() noexcept;
  374. // Latest output samples (mono), for the oscilloscope. UI thread.
  375. void copyScope (float* destination, int count) const noexcept;
  376. static constexpr int scopeSize = 2048;
  377. // Real-time health of the audio callback (REA round 87): callbacks over their deadline, late device calls, load.
  378. const RtStats& getRtStats() const noexcept { return rtStats; }
  379. RtStats& getRtStats() noexcept { return rtStats; }
  380. // What takes the most audio CPU: channels and insert effects, as a share of real time over the last ~2 s of
  381. // playback, heaviest first. UI thread.
  382. struct UnitLoad
  383. {
  384. juce::String name;
  385. double load = 0.0; // CPU time / audio time (summed over the worker threads)
  386. double longestMs = 0.0; // the longest single call in the window
  387. };
  388. const std::vector<UnitLoad>& getHeaviestUnits() const noexcept { return heaviestUnits; }
  389. // How regularly the message thread runs the engine's 30 Hz timer (a saturated UI delays it). UI thread.
  390. struct UiPulse
  391. {
  392. int calls = 0;
  393. double maxGapMs = 0.0;
  394. };
  395. UiPulse takeUiPulse() noexcept { return std::exchange (uiPulse, {}); }
  396. // Writes `state` (a createStateXml() taken earlier; nullptr = none was saved) back as the saved device and stops
  397. // saving later changes: a test run (--rtstress --type ...) leaves the user's device as it found it.
  398. void restoreAudioDeviceState (const juce::XmlElement* state);
  399. // Device, buffer, deadline and the callback statistics in a few lines (CPU meter hint, glitch log, --rtstress).
  400. juce::String describeRealtime (bool withUnits = true) const;
  401. // %APPDATA%\LYNX\audio-glitches.log: a line each time callbacks run over their deadline (at most every 2 s).
  402. static juce::File glitchLogFile();
  403. // Total latency compensated by PDC (at the Master output), in samples.
  404. int getLatencySamples() const noexcept { return lastPublishedShape.pdc.total; }
  405. private:
  406. void audioDeviceIOCallbackWithContext (const float* const* inputChannelData,
  407. int numInputChannels,
  408. float* const* outputChannelData,
  409. int numOutputChannels,
  410. int numSamples,
  411. const juce::AudioIODeviceCallbackContext& context) override;
  412. void audioDeviceAboutToStart (juce::AudioIODevice* device) override;
  413. void audioDeviceStopped() override;
  414. void timerCallback() override;
  415. void handleIncomingMidiMessage (juce::MidiInput* source, const juce::MidiMessage& message) override;
  416. void enableAllMidiInputs();
  417. void saveAudioDeviceState();
  418. void updateRecording();
  419. void updateAudioRecording();
  420. void updateAutomationRecording (bool active);
  421. void startAudioTake();
  422. void finishAudioTake();
  423. double estimatedPositionNow() const noexcept;
  424. void buildInitialGraph();
  425. void choosePreferredDriver(); // a first start on Linux: PipeWire, then JACK, then ALSA (round 161)
  426. void chooseSafeBufferSize();
  427. void updateRealtimeStats(); // timer: unit loads over a window, glitch log
  428. RtStats rtStats;
  429. std::vector<UnitLoad> heaviestUnits;
  430. std::vector<std::uint64_t> lastChannelNs, lastEffectNs;
  431. std::uint64_t lastProcessedSamples = 0;
  432. double lastUnitsWindowMs = 0.0, lastUiPulseMs = 0.0;
  433. UiPulse uiPulse;
  434. int latencyRepublishes = 0; // PDC re-plans because a unit's latency changed (diagnostics)
  435. juce::String lastLatencyChange;
  436. std::uint64_t loggedOver = 0, loggedLate = 0;
  437. double lastLogMs = 0.0;
  438. class PreviewPlayer* preview = nullptr; // graph node (owned by the graph)
  439. double previewVolume = 1.0;
  440. double editorVolume = 1.0;
  441. void publishSong();
  442. void adoptPrepared (PreparedFlp& prepared); // the plugins of a prepared import found / substituted (message thread)
  443. std::unique_ptr<WorkerPool> workers; // extra renderer threads (before the graph, which uses them)
  444. juce::AudioDeviceManager deviceManager;
  445. juce::AudioProcessorGraph graph;
  446. juce::AudioProcessorPlayer player;
  447. Transport transport;
  448. SampleLibrary samples;
  449. LiveEventQueue liveEvents; // UI -> audio
  450. LiveEventQueue midiEvents; // MIDI thread -> audio
  451. InputHeldNotes midiHeld; // MIDI thread: what each held MIDI key started
  452. std::atomic<std::uint64_t> heldKeyBits[2] {}; // keys held on MIDI inputs / the typing piano (chord readout)
  453. std::atomic<std::uint8_t> heldKeyCount[128] {};
  454. void markHeldKey (int key, bool on) noexcept;
  455. KeyLedger playedKeys; // UI thread: the keys the typing piano started (after the scale snap)
  456. SpscQueue<RecordedEvent, 1024> midiRecordQueue; // MIDI thread -> UI (recording)
  457. struct ControllerEvent
  458. {
  459. int cc = 0, channel = 0, value = 0;
  460. };
  461. SpscQueue<ControllerEvent, 1024> controllerQueue; // MIDI thread -> UI (controllers)
  462. // the CCs a MIDI link (project or global) uses: they move their parameter and are not also played into the
  463. // selected channel's instrument (round 162); written by applyControllers, read by the MIDI thread
  464. std::array<std::atomic<std::uint64_t>, 2> linkedCcs {};
  465. AutomationTarget learning;
  466. bool learningGlobal = false;
  467. bool saveGlobalLinks = false; // only the engine with an audio device (the app) writes the settings file
  468. void applyControllers();
  469. std::vector<RecordedEvent> uiRecorded; // PC keyboard -> recording
  470. NoteRecorder recorder;
  471. // last tweaked parameters and automation recording (REA round 143)
  472. std::array<AutomationTarget, 2> lastTweaked {};
  473. struct Touch
  474. {
  475. AutomationTarget target;
  476. double lastMs = 0.0;
  477. bool held = false;
  478. std::vector<RecordedValue> pending; // sampled, not yet written
  479. };
  480. std::vector<Touch> touches;
  481. int automationCommitCountdown = 0;
  482. bool automationTakeHasUndoStep = false;
  483. std::int64_t automationLoopLength = 0;
  484. int automationPattern = 0;
  485. int recordedAutomationPoints = 0;
  486. bool automationOverrideActive = false; // touched targets override their automation in the renderer
  487. std::vector<AutomationWrite> takeWrites; // per target: where this take writes (its own clip grows)
  488. bool takeHasUndoStep = false;
  489. RecordOptions recordOptions;
  490. std::vector<int> takeClearedChannels; // replace mode: channels already cleared in this take
  491. double takeStartPosition = 0.0;
  492. std::atomic<bool> waitingForInput { false };
  493. void startOnInput() noexcept; // MIDI or UI thread: the first note while waiting starts playback
  494. std::vector<int> armedInserts;
  495. double lastPlayingTick = 0.0;
  496. std::atomic<int> inputScale { 0 }, inputScaleRoot { 0 };
  497. std::atomic<int> liveChannel { 0 }; // selected channel, read by the MIDI thread
  498. static constexpr int maxLiveChannels = 16; // other selected channels that also get MIDI input
  499. std::array<std::atomic<int>, maxLiveChannels> extraLiveChannels {};
  500. std::atomic<int> extraLiveCount { 0 };
  501. void publishSelection();
  502. std::atomic<double> blockTimeMs { 0.0 }; // when positionTicks was last updated
  503. std::array<std::atomic<float>, scopeSize> scope {}; // ring buffer of the output (written by audio)
  504. std::atomic<int> scopeWrite { 0 };
  505. juce::MidiDeviceListConnection midiDevicesChanged;
  506. std::vector<std::string> lastMidiInputIds; // the MIDI inputs available at the last check (UI thread)
  507. int midiCheckTicks = 0;
  508. std::atomic<std::uint32_t> midiActivity { 0 };
  509. prefs::MidiPrefs midiPrefs; // UI thread
  510. juce::SpinLock midiPrefsLock; // guards midiPrefsShared (UI writes, MIDI thread reads)
  511. prefs::MidiPrefs midiPrefsShared;
  512. std::map<std::tuple<int, int, int, int, int, int>, prefs::PickupState> pickups; // (cc, channel, target) -> takeover
  513. struct DeviceStateSaver;
  514. std::unique_ptr<DeviceStateSaver> deviceStateSaver;
  515. // audio recording
  516. bool audioArmed = false;
  517. juce::String recordingError;
  518. juce::File recordingFolder = defaultRecordingFolder();
  519. juce::String recordingStem;
  520. std::vector<juce::File> sessionRecordings;
  521. juce::TimeSliceThread recordThread { "LYNX recording" };
  522. RecordingNotice recordingNotice;
  523. void notify (InputIssue issue, int track = 0, const juce::String& detail = {});
  524. struct Take
  525. {
  526. int track = 0; // insert it plays through (0 = a new free insert)
  527. int first = 0; // device input channel
  528. int channels = 0; // 1 or 2
  529. juce::File file;
  530. std::unique_ptr<juce::AudioFormatWriter::ThreadedWriter> writer;
  531. };
  532. static constexpr int maxTakes = 16;
  533. std::array<Take, maxTakes> takes; // guarded by takeLock
  534. int takeCount = 0;
  535. juce::SpinLock takeLock; // the audio thread only tries (never waits)
  536. LiveInput liveInput;
  537. HardwareOutput hwOutput; // inserts' hardware outputs (renderer -> callback)
  538. std::array<int, HardwareOutput::maxChannels> outputSlot {}; // device output channel -> callback output index (-1: closed)
  539. std::atomic<int> masterOutChannel { outputDefault }; // the Master's target (UI -> audio)
  540. std::atomic<int> masterOutMode { 0 };
  541. std::vector<float> masterScratch = std::vector<float> (2 * HardwareOutput::capacity, 0.0f);
  542. void routeOutputs (float* const* outputs, int numOutputs, int n) noexcept; // audio thread
  543. std::array<float, maxMixerTracks * 2> lastInputPeaks {};
  544. std::array<int, LiveInput::maxChannels> inputSlot {}; // device input channel -> callback input index (-1: closed)
  545. std::atomic<double> takeStartTick { -1.0 }; // position of the first recorded sample
  546. std::atomic<juce::int64> takeFrames { 0 };
  547. double takeSampleRate = 44100.0;
  548. int takeLatency = 0; // input + output, in samples
  549. MeterBank meters;
  550. std::unique_ptr<AudioLogger> audioLogger; // after `meters` (it reads meters.logTap): destroyed first
  551. PluginHost plugins;
  552. juce::StringArray missingPlugins, matchedPlugins, pluginsWithoutState;
  553. FlpImportReport importReport;
  554. std::vector<MissingPlugin> missingPluginDetails;
  555. RenderStats lastRenderStats;
  556. class ChannelRackProcessor* rackProcessor = nullptr; // graph node (owner: the graph)
  557. Song song;
  558. int selectedChannel = 0;
  559. std::vector<int> selectedChannels { 0 };
  560. bool modified = false;
  561. std::unique_ptr<StreamPrefetcher> prefetcher; // only with an audio device (playing live)
  562. std::size_t maxUndoSteps = prefs::defaultUndoLevels;
  563. std::deque<Song> undoStack, redoStack;
  564. juce::Time lastUndoPress; // mouse click that already produced an undo step
  565. SnapshotExchange<RackState> rackExchange;
  566. RackState lastPublishedShape; // channels + instruments of the last snapshot, to reuse voices
  567. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioEngine)
  568. };
  569. } // namespace lynx