AudioEngine.h 67 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095
  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/AutomationDisplay.h"
  11. #include "core/HeldNotes.h"
  12. #include "core/RecordLoop.h"
  13. #include "core/StepEdit.h"
  14. #include "core/Preferences.h"
  15. #include "core/LiveEventQueue.h"
  16. #include "core/LiveInput.h"
  17. #include "core/HardwareOutput.h"
  18. #include "core/LiveRecordView.h"
  19. #include "core/Recorder.h"
  20. #include "core/TakeRecording.h"
  21. #include "core/WorkerPool.h"
  22. #include "core/SerialJobs.h"
  23. #include "engine/MidiSyncIo.h"
  24. #include "core/RackRenderer.h"
  25. #include "core/RtStats.h"
  26. #include "core/ScoreLog.h"
  27. #include "core/FlpImport.h"
  28. #include "core/History.h"
  29. #include "core/NativeEngines.h"
  30. #include "core/PluginWarmup.h"
  31. #include "core/SnapshotExchange.h"
  32. #include "core/Song.h"
  33. #include "engine/PluginHost.h"
  34. #include "engine/SampleLibrary.h"
  35. #include "engine/StreamPrefetcher.h"
  36. #include "engine/Transport.h"
  37. namespace lynx
  38. {
  39. class AudioLogger;
  40. // Owns the audio device, the processing graph and the document (Song).
  41. // Sits between the driver and the AudioProcessorPlayer to advance the transport
  42. // after each block, so every node sees the same start position.
  43. //
  44. // The Song is touched only by the UI thread; each edit publishes an immutable
  45. // snapshot (RackState) to the audio thread.
  46. // Folders of the most recent FL Studio installation (empty if none).
  47. FlPathRoots findFlStudioRoots();
  48. // The user's FL installation as the native FL engines read it (round 142): its folders and this PC's file system
  49. const natives::FlAccess& flStudioAccess(); // (found once per session)
  50. // Start-up trace hook (round 165i): Main's LYNX_TRACE_STARTUP log receives the engine's own steps (null: off)
  51. inline void (*startupMark) (const char* step) = nullptr;
  52. class AudioEngine final : private juce::AudioIODeviceCallback,
  53. private juce::MidiInputCallback,
  54. public juce::ChangeBroadcaster,
  55. private juce::Timer
  56. {
  57. public:
  58. explicit AudioEngine (bool openAudioDevice = true);
  59. ~AudioEngine() override;
  60. juce::AudioDeviceManager& getDeviceManager() noexcept { return deviceManager; }
  61. Transport& getTransport() noexcept { return transport; }
  62. const Transport& getTransport() const noexcept { return transport; }
  63. // The Song-mode playhead for the UI: the position folded into the song (its end goes back to the start), except
  64. // while the song plays on past its end (a Song-mode recording without a loop region, FL [EXEC] round 168k: the
  65. // counter reads 8:08 after recording a 1-bar song from bar 1; a bounce) or with a loop region
  66. double songPlayheadTicks() const noexcept;
  67. // Round 174e: how far the playhead has moved since the last audio block, for screens drawing faster than the blocks
  68. // come (144 Hz against 256-sample blocks, or larger buffers): the time since that block at its tempo, never more
  69. // than one block (so the next block's position is never passed: the playhead only moves forward). 0 when stopped.
  70. double playheadAdvanceTicks() const noexcept;
  71. SampleLibrary& getSampleLibrary() noexcept { return samples; }
  72. MeterBank& getMeters() noexcept { return meters; }
  73. // Tools > Audio logger (REA round 153): records everything the Master plays to a WAV in the background.
  74. AudioLogger& getAudioLogger();
  75. PluginHost& getPluginHost() noexcept { return plugins; }
  76. // Online Sessions (round 168a): the channels / inserts whose third-party plugin is missing here and that play their
  77. // stand-in render instead (core/StandIns.h), as of the last publish — the Channel Rack and the Mixer badge them.
  78. bool playsStandIn (int channel) const noexcept
  79. {
  80. return std::find (standInChannels.begin(), standInChannels.end(), channel) != standInChannels.end();
  81. }
  82. bool insertPlaysStandIn (int track) const noexcept
  83. {
  84. return std::find (standInInserts.begin(), standInInserts.end(), track) != standInInserts.end();
  85. }
  86. // Third-party plugins from the last imported .flp that were not found among the scanned ones.
  87. const juce::StringArray& getMissingPlugins() const noexcept { return missingPlugins; }
  88. // "plugin → file (how it was found)" for the plugins of the last imported .flp
  89. const juce::StringArray& getMatchedPlugins() const noexcept { return matchedPlugins; }
  90. // plugins found whose saved settings could not be carried over (VST2 <-> VST3): "name (format)"
  91. const juce::StringArray& getPluginsWithoutState() const noexcept { return pluginsWithoutState; }
  92. // What the last imported .flp converted, approximated or left out.
  93. const FlpImportReport& getImportReport() const noexcept { return importReport; }
  94. // The last imported .flp's plugins that were not found, with what uses them and what LYNX put in their place.
  95. const std::vector<MissingPlugin>& getMissingPluginDetails() const noexcept { return missingPluginDetails; }
  96. // Live instances (to open the plugin window). nullptr if not a plugin.
  97. std::shared_ptr<Instrument> getChannelInstrument (int channel) const;
  98. std::shared_ptr<Effect> getEffect (int track, int slot) const;
  99. // Copies the plugins' current state into the Song (before saving).
  100. void capturePluginStates(); // (before every save: also adds the working time so far, see stampWorkTime)
  101. // FL's Project info working time (REA round 167g): wall-clock time since the project was opened, added to the
  102. // saved total at each save. workSecondsNow() = the saved total + this session so far.
  103. void stampWorkTime();
  104. double workSecondsNow() const;
  105. void markCreatedNow(); // a new project: Project info › created = now (when it has no date yet)
  106. // Offline render mode for the hosted plugins (setNonRealtime), around renderOffline.
  107. void setPluginsRenderMode (bool offline);
  108. // Every hosted plugin of the song that has not crashed (channels, inserts, inside Patchers); `notifyRender` is the
  109. // plugin's "Notify about rendering mode" option. Message thread or the render thread, while nothing else edits.
  110. void forEachHostedPlugin (const std::function<void (juce::AudioPluginInstance&, bool notifyRender)>& visit) const;
  111. // The render's plugin warm-up (renderOffline, round 155): silent discarded blocks until the hosted plugins settle,
  112. // then a new PDC plan if a latency changed and LYNX's own units reset. Returns blocks == 0 when the song has no
  113. // hosted plugin. `latency` receives the delay compensation's total afterwards.
  114. warmup::Result warmUpPlugins (const warmup::Settings& settings, double sampleRate, int blockSize,
  115. const std::function<bool (double)>& progress, int& latency);
  116. void play() noexcept;
  117. // --cliplooptest (round 167q): the device callback, driven by hand with a stand-in device
  118. juce::AudioIODeviceCallback& deviceCallback() noexcept { return *this; }
  119. // Performance mode (round 165m, core/Performance.h): launch / release / stop zone clips (message thread). The
  120. // clips start on the next block, quantized by their track's Performance settings; nothing launches while stopped.
  121. void performanceCommand (const perf::Command& command) noexcept { performanceLive->commands.push (command); }
  122. // FL sends the typing keyboard's notes as MIDI channel 1: they launch performance clips when that is the "MIDI
  123. // channel used for playlist live mode" and Performance mode is on (the same test as the MIDI input's)
  124. bool typingNotesLaunchClips() const noexcept
  125. {
  126. return performanceMidiChannel.load (std::memory_order_relaxed) == 1 && performanceMidiOn.load (std::memory_order_relaxed);
  127. }
  128. const perf::Live& performanceState() const noexcept { return *performanceLive; }
  129. perf::Live& performanceStateForSnapshot() noexcept { return *performanceLive; } // --perfshot: a sample of what plays
  130. void stop() noexcept; // also cancels a count-in or a wait for the first note
  131. // Recording options (docs/WORKFLOW_FL.md P2: recording set). UI thread.
  132. struct RecordOptions
  133. {
  134. int countInBars = 0; // 0 = off
  135. bool waitForInput = false; // playback starts at the first played note
  136. RecordMode mode = RecordMode::overdub;
  137. std::int64_t quantise = 0; // record quantise in ticks (<= 1: as played); follows the global grid
  138. bool placeSongClip = true; // song mode: a take puts a clip of the pattern where recording started
  139. // recording filter (FL's record button right-click, REA_rodada88): what a take records
  140. bool recordNotes = true; // notes played (MIDI and PC keyboard)
  141. bool recordAudio = true; // audio of the armed inserts' inputs
  142. bool askWhatToRecord = true; // the record button asks first ("What would you like to record?")
  143. // FL's record menu "Options" (REA round 134): arming recording also starts playback
  144. bool startsPlayback = false;
  145. // LYNX's own "Disarm the inserts when recording stops" (record menu and Mixer › Disk recording; issue #16): the
  146. // armed inserts are disarmed when a take stops. FL has no such option (round 166e measured: neither its
  147. // "Disarm on stop" nor the mixer's "Auto-unarm" disarms the inserts after a live take).
  148. bool disarmOnStop = false;
  149. // FL's record menu "Disarm on stop" (RecDisableOnStopMenu, round 166e measured): the record switch turns off when
  150. // playback stops after recording
  151. bool recordOffOnStop = false;
  152. // FL's Mixer › Disk recording › "Auto-unarm" (round 166e measured): "Render armed tracks to wave file(s)"
  153. // disarms the tracks it rendered
  154. bool unarmAfterRender = false;
  155. // FL's Mixer › Disk recording › "Auto-create audio clip" (on by default, round 167a [SHOT s28–s37]): the files
  156. // "Render armed tracks to wave file(s)" writes go on the Playlist (mixerops::placeRenderedFiles)
  157. bool autoCreateClip = true;
  158. // FL's record menu "Quantize" section (REA round 139); `quantise` is the grid. quantiseStarts = "Note start
  159. // time", noteEnd = "Note end time" (quantize) / "Leave note duration" (keepLength) / neither (keepEnd),
  160. // toStepSequencer = "Record to step sequencer"
  161. bool quantiseStarts = true;
  162. NoteEnd noteEnd = NoteEnd::keepLength;
  163. bool toStepSequencer = false;
  164. // FL's "Enable recording markers": the Playlist's "Start recording" / "Stop recording" markers limit what a
  165. // take keeps in song mode (notes started outside are dropped, audio clips are cut to the ranges)
  166. bool recordingMarkers = false;
  167. // FL's recording filter "Automation" (REA round 143): moved parameters become automation (song mode: automation
  168. // clips; pattern mode: the pattern's events); Quantize › "Automations" puts their points on the snap
  169. bool recordAutomation = true;
  170. // FL's recording filter "Clips" (REA round 146 B5, round 165m): Performance mode's launched clips are written
  171. // into the arrangement where they played
  172. bool recordClips = true;
  173. bool quantiseAutomation = false;
  174. // round 163 (Pro Tools / Nuendo): punch in/out on the Playlist's loop region (instead of loop recording; the
  175. // song plays straight through it), pre-roll before the punch-in (or before the position recording starts at)
  176. // and post-roll after the punch-out (then playback stops). Bars; 0 = off.
  177. bool punchLoopRegion = false;
  178. int preRollBars = 0;
  179. int postRollBars = 0;
  180. // FL's "Loop record" (toolbar LoopRecordBtn / Options, round 170e3 [DECOMP 0xf1e2a0 toggles a global that
  181. // FUN_011d4800 reads: off while recording, the play end becomes "never", so playback runs on]): on, Song mode
  182. // recording loops the loop region (one take per pass); off, it plays straight through the region and the notes
  183. // and audio stay where they were played. Pattern mode always loops the pattern in LYNX.
  184. bool loopRecord = true;
  185. // round 170d (the Busy Works video: the chord on the downbeat after the count-in was lost; Cubase's "MIDI Record
  186. // Catch Range", Logic keeps count-in notes): notes played during the count-in are recorded, and a note-on at most
  187. // this many ticks before the take's start goes onto the start (0 = off: they keep their real time)
  188. std::int64_t catchWindow = ppq / 4;
  189. // round 170d (Pro Tools / Cubase / REAPER): played notes are recorded where they were heard, moved back by the
  190. // output buffer + the driver's output latency
  191. bool compensateOutput = true;
  192. };
  193. // The range this recording keeps (pre-roll or punch), while one is active. UI thread.
  194. std::optional<PunchRange> getActivePunch() const noexcept { return activePunch; }
  195. const RecordOptions& getRecordOptions() const noexcept { return recordOptions; }
  196. void setRecordOptions (const RecordOptions& options);
  197. // Play pressed: with recording on, honours wait-for-input and the count-in; otherwise play().
  198. void startPlayback();
  199. // The song's initial values (FL's initialized controls) back on their targets, in song mode; play() and a
  200. // seek while playing do it (REA round 146). UI thread.
  201. void resetToInitialValues() noexcept;
  202. bool isWaitingForInput() const noexcept { return waitingForInput.load(); }
  203. bool isCountingIn() const noexcept { return transport.countIn.load() > 0.0; }
  204. // The audio clock the last callback left (core/Recorder.h LiveClock) and where an event played at `eventMs`
  205. // (juce::Time::getMillisecondCounterHiRes) is recorded: sample-accurate against the block, minus the output
  206. // latency when compensateOutput is on (round 170d). Any thread.
  207. LiveClock liveClock() const noexcept;
  208. double recordTickFor (double eventMs) const noexcept;
  209. // The count-in catch of the take being counted in / recorded (round 170d; UI thread).
  210. const CountInCatch& getCountInCatch() const noexcept { return takeCatch; }
  211. // Record › Capture MIDI (round 170d, LYNX's own): the last phrase played without recording into the current pattern
  212. // (core/Recorder.h captureMidi), one undo step. UI thread.
  213. CaptureResult captureMidi();
  214. // Per-insert record arm: each armed insert records its own audio input (Mixer › insert › input source) into
  215. // its own take (arming one turns audio recording on; disarming the last one turns it off). Not saved.
  216. void setInsertArmed (int track, bool armed);
  217. bool isInsertArmed (int track) const noexcept;
  218. const std::vector<int>& getArmedInserts() const noexcept { return armedInserts; }
  219. void rewind() noexcept;
  220. void seek (double ticks) noexcept;
  221. // Preview of an audio file (browser). An invalid/empty file stops the preview.
  222. void previewFile (const juce::File& file);
  223. // The Browser's preview volume (0..1.25, 1 = default; core/ValueMath.h previewGain). Applies to the preview
  224. // playing now too. UI thread.
  225. void setPreviewVolume (double volume) noexcept;
  226. double getPreviewVolume() const noexcept { return previewVolume; }
  227. // Plays a sound made in memory through the same preview output (the start-up sound). UI thread.
  228. void previewSample (std::shared_ptr<const SampleData> sample, bool loop = false, float gain = 0.8f, bool audioEditor = false);
  229. // The Audio Editor's playback volume (its toolbar knob, round 162): 0..1.25 like the Browser's, 1 = unity.
  230. void setEditorVolume (double volume) noexcept;
  231. double getEditorVolume() const noexcept { return editorVolume; }
  232. // The frame of the previewed sample being played, -1 when the preview is silent.
  233. double getPreviewPosition() const noexcept;
  234. // Note played live (PC keyboard, preview). UI thread.
  235. // `record` = goes into the recording if recording is on (Piano Roll preview doesn't).
  236. void sendLiveNote (int channel, int key, float velocity, bool on, bool record = false);
  237. // The keys held right now on MIDI inputs and the typing piano (as played, before the scale snap), ascending; for
  238. // the Piano Roll's chord readout (any thread).
  239. std::vector<int> heldInputKeys() const;
  240. // The keys sounding on a channel right now (song / pattern notes, keyboard, MIDI): the Piano roll's keyboard lights
  241. // them (issue #14). Any thread.
  242. NoteMask soundingKeys (int channel) const noexcept;
  243. // FL's score logger (REA round 165f): every note played on a MIDI input or the typing keyboard, recording or
  244. // not, for Tools › Dump score log to selected pattern. Any thread (a short spin lock; never the audio thread).
  245. std::vector<scorelog::Entry> scoreLogSnapshot() const;
  246. bool scoreLogEmpty() const;
  247. void clearScoreLog();
  248. // FL's Step edit (round 170e3, core/StepEdit.h): while on, every note played on a MIDI input or the typing keyboard
  249. // is also queued for the UI, which writes it into the pattern when the transport is stopped. Any thread.
  250. void setStepEdit (bool on) noexcept;
  251. bool isStepEdit() const noexcept { return stepEditOn.load (std::memory_order_relaxed); }
  252. std::vector<stepedit::Played> takeStepEditNotes();
  253. // Scale snap for played notes (MIDI input and the PC keyboard): scale index into notetools::scales()
  254. // (0 = off) and its root (0..11). Any thread.
  255. void setInputScale (int scale, int root) noexcept;
  256. int snapInputKey (int key) const noexcept;
  257. // All notes off on every channel (double-click on Stop). UI thread.
  258. void panic();
  259. // FL's Tools › Macros › Stop sound (Ctrl+H, round 170h2; FL64 MacroStopSoundActionExecute → FUN_011c8d10 →
  260. // FUN_011c8a40 (1, 1, 1) → FUN_012b5210): all notes off on every channel and MIDI out, and every effect and
  261. // plugin reset — the tails of delays and reverbs stop too. UI thread.
  262. void stopSound();
  263. // Note recording (MIDI and PC keyboard) into the current pattern while playing. UI thread.
  264. void setRecording (bool shouldRecord);
  265. bool isRecording() const noexcept { return transport.recording.load(); }
  266. // Pattern mode, a take with Loop record off (round 170e5): the transport tick the pattern plays once from, < 0: none
  267. double patternLinearOrigin() const noexcept { return liveInput.patternOrigin.load (std::memory_order_relaxed); }
  268. // Round 177d: the recording in progress as the editors draw it live (core/LiveRecordView.h). UI thread.
  269. struct LiveRecording
  270. {
  271. // the note take: the notes still held (positions in `pattern`, as they would be committed now) and, in Song
  272. // mode, the Playlist range the take covers so far: [from, to) on `track` (from = its clip's start or the origin)
  273. bool notes = false;
  274. int pattern = -1;
  275. std::vector<Note> held;
  276. int track = -1;
  277. std::int64_t from = -1, to = -1;
  278. std::int64_t origin = -1; // the song position of the pattern's start for `held`
  279. // the audio takes: each on the Playlist track it will land on, its current pass and its waveform
  280. struct Audio
  281. {
  282. int track = -1;
  283. liverec::AudioSpan span;
  284. std::shared_ptr<const liverec::LivePeaks> peaks;
  285. juce::String name;
  286. };
  287. std::vector<Audio> audio;
  288. std::optional<PunchRange> punch; // only this range is kept (pre-roll / punch in-out)
  289. bool any() const noexcept { return notes || ! audio.empty(); }
  290. };
  291. // cheap: a take records (notes held or recorded, or audio)
  292. bool isLiveRecording() const noexcept { return recorder.isActive() || takeCount > 0; }
  293. LiveRecording liveRecording() const;
  294. // Audio recording from the interface input: with this on, recording (Rec + Play) writes the
  295. // input to a WAV and, on stop, the take becomes a Playlist clip (latency-compensated).
  296. // Enabling it opens the device input (only then does Windows show the mic as in use).
  297. void setAudioRecordingArmed (bool armed);
  298. bool isAudioRecordingArmed() const noexcept { return audioArmed; }
  299. juce::String getLastRecordingError() const { return recordingError; }
  300. // Where takes are written and how they are named (FL's project data folder, REA round 134): `folder` is
  301. // "<project folder>/Audio/Recorded" for a saved project (the global recordings folder otherwise), files are
  302. // "<projectStem>_<yyyy-mm-dd hh-mm-ss>_<insert name>.wav". UI thread.
  303. void setRecordingTarget (const juce::File& folder, const juce::String& projectStem);
  304. juce::File getRecordingFolder() const { return recordingFolder; }
  305. juce::String getRecordingStem() const { return recordingStem; }
  306. // A MIDI message as if a controller had sent it (the --bendrectest of round 167a). Message thread.
  307. void injectMidiInput (const juce::MidiMessage& message) { handleIncomingMidiMessage (nullptr, message); }
  308. static juce::File defaultRecordingFolder();
  309. // The take files written since LYNX started (or since forgetRecordings), oldest first. UI thread.
  310. const std::vector<juce::File>& getSessionRecordings() const noexcept { return sessionRecordings; }
  311. void forgetRecordings (const std::vector<juce::File>& files);
  312. // --- hardware recording (round 163, docs/analise/REA_rodada163c.md) ---
  313. // Options › Audio › Recording, saved in <settings>/recording.txt.
  314. struct RecordingSettings
  315. {
  316. takes::SampleFormat format = takes::SampleFormat::pcm24; // 24-bit or 32-bit float WAV; the device's rate
  317. bool trackTakeNames = true; // "<Insert>_Take<N>.wav" (off: FL's "<project>_<date time>_<insert>.wav")
  318. int manualOffset = 0; // samples added to the compensation (negative: earlier)
  319. bool useMeasured = true; // a ping measured for this device setup replaces the driver's figures
  320. std::map<std::string, int> measured; // setupKey -> round trip (samples)
  321. int pingOutput = 0, pingInput = 0; // device channels the ping uses (output pair's first, input)
  322. };
  323. const RecordingSettings& getRecordingSettings() const noexcept { return recordingSettings; }
  324. void setRecordingSettings (const RecordingSettings& settings); // saves
  325. // The current device setup's key (takes::setupKey) and its latency figures (pdc = the Master's PDC now).
  326. std::string currentSetupKey() const;
  327. takes::Latency currentLatency() const;
  328. // The latency ping: clicks on output channel pair `pingOutput` (and the next), listened for on input channel
  329. // `pingInput` through a loopback. Needs the transport stopped and the input open. Returns an error (empty: started).
  330. juce::String startLatencyPing();
  331. bool isPinging() const noexcept { return ping.isRunning(); }
  332. void cancelLatencyPing() noexcept { ping.cancel(); }
  333. // After isPinging() turned false: the result (stored for this setup when ok).
  334. takes::LatencyPing::Result finishLatencyPing();
  335. // Record safe (round 163): a safe insert can't be armed (undoable, saved with the project).
  336. void setInsertRecordSafe (int track, bool safe);
  337. bool isInsertRecordSafe (int track) const noexcept
  338. {
  339. return track > 0 && track < (int) song.mixer.size() && song.mixer[(std::size_t) track].recordSafe;
  340. }
  341. // Frames lost while recording (the disk could not keep up; they became silence, the timing kept) since the
  342. // last take started.
  343. juce::int64 getLostRecordingFrames() const noexcept { return lostFrames; }
  344. // Interrupted takes (crash while recording): repaired WAVs and where they belonged. Scans the journals in the
  345. // given folders (the default recordings folder always). UI thread, at start-up.
  346. std::vector<takes::Journal> recoverInterruptedTakes (const std::vector<juce::File>& folders);
  347. // Puts recovered takes on the Playlist at their recorded positions (undoable). Returns how many were placed.
  348. int placeRecoveredTakes (const std::vector<takes::Journal>& recovered);
  349. // Leaves them as files only (their journals are removed).
  350. void forgetInterruptedTakes (const std::vector<takes::Journal>& recovered);
  351. // --- external audio input through the mixer (REA_rodada88) ---
  352. // Names of the open device's input channels (all of them, open or not); empty without an input device.
  353. std::vector<std::string> getInputChannelNames() const;
  354. // Problems the UI explains to the user (translated there).
  355. enum class InputIssue
  356. {
  357. none,
  358. noDevice, // no audio device open at all
  359. noInputDevice, // the driver has no input device
  360. noInputOpen, // recording with no input open
  361. armedWithoutInput, // armed inserts, none with an input source
  362. insertWithoutInput,// one armed insert (track) has no input source
  363. lowDisk, // little room left on the recordings drive (detail = minutes)
  364. recordSafe, // the insert (track) is record safe: not armed
  365. framesLost, // the disk could not keep up: frames became silence (detail = how many)
  366. failed // the driver refused (detail = its message) or a file could not be written
  367. };
  368. struct RecordingNotice
  369. {
  370. InputIssue issue = InputIssue::none;
  371. int track = 0;
  372. juce::String detail;
  373. };
  374. // Opens the input of the current driver: `deviceName` (separate-input drivers; empty = the one chosen in
  375. // Settings, else the default), all of its channels. UI thread.
  376. RecordingNotice openAudioInput (const juce::String& deviceName = {});
  377. bool hasAudioInput() const;
  378. // Closes the device input again when nothing needs it (no insert takes an input, no armed recording, no hardware
  379. // insert returning from it): a capture the Audio editor opened for one recording no longer keeps the input — and
  380. // Windows' microphone-in-use icon — on until LYNX quits, as in FL (round 165q). The input device's name is kept
  381. // for the next openAudioInput(). UI thread.
  382. void releaseAudioInputIfUnused();
  383. bool audioInputNeeded() const;
  384. // Sets an insert's input source (undoable; -1 = none) and opens the device input when needed.
  385. void setInsertInput (int track, int channel, bool stereo);
  386. void setInsertMonitor (int track, InputMonitor mode);
  387. // FL's "Record" position of an insert and LYNX's "also record the dry input" (round 168x, issue #41); undoable
  388. void setInsertRecordSource (int track, RecordSource source);
  389. void setInsertRecordDryToo (int track, bool on);
  390. // --- hardware output targets (REA round 156) ---
  391. // Names of the open device's output channels (all of them, open or not); empty without a device.
  392. std::vector<std::string> getOutputChannelNames() const;
  393. // Whether device output channel `c` is open (gets sound) right now.
  394. bool isOutputChannelOpen (int channel) const;
  395. // Sets a track's hardware output target (undoable; outputNone / outputDefault / a device channel) and opens
  396. // the device's output channels it needs (no trip to Audio settings). The Master's default is its first pair.
  397. void setTrackOutput (int track, int channel, OutputMode mode);
  398. // Opens the device output channels the song's targets need (that the device has). UI thread.
  399. void openTargetedOutputs();
  400. // The hardware inserts' channels (round 164d): opens their outputs and, when one returns from an input, the device
  401. // input. UI thread.
  402. void openHardwareInsertIo();
  403. // Every hardware insert of the song (round 165c): a mixer slot's, or a node inside a Patcher (mixer-slot or generator
  404. // Patcher; `nodes` = the node index at each Patcher level). UI thread.
  405. struct HardwareInsertRef
  406. {
  407. bool channel = false; // a Channel Rack generator Patcher (index = channel), else a mixer slot (index = track)
  408. int index = 0, slot = 0;
  409. std::vector<int> nodes;
  410. bool operator== (const HardwareInsertRef&) const = default;
  411. };
  412. std::vector<HardwareInsertRef> getHardwareInserts() const;
  413. static EffectSlot* locateHardwareInsert (Song& song, const HardwareInsertRef& ref);
  414. std::shared_ptr<Effect> runningHardwareInsert (const HardwareInsertRef& ref) const;
  415. // The routed, active inserts whose round trip was measured for another device setup (device, rate or buffer size)
  416. std::vector<HardwareInsertRef> staleHardwareInserts() const;
  417. // Presses their Ping buttons (the clicks go out on their sends; the results are applied as they come back)
  418. void pingHardwareInserts (const std::vector<HardwareInsertRef>& refs);
  419. // After the device setup changed with stale inserts in the song: those inserts, once (the UI offers "Ping now")
  420. std::vector<HardwareInsertRef> takeHardwareInsertNotice() { return std::exchange (hwNotice, {}); }
  421. // Input level of an insert's source since the last call (0..1, per side). UI thread.
  422. // (the Mixer's strips take it 30 times a second; other views peek at the last value taken)
  423. float takeInputPeak (int track, int side) noexcept
  424. {
  425. const auto v = liveInput.meters.takePeak (track, side);
  426. if (track >= 0 && track < maxMixerTracks && (side == 0 || side == 1))
  427. lastInputPeaks[(std::size_t) (track * 2 + side)] = v;
  428. return v;
  429. }
  430. float peekInputPeak (int track, int side) const noexcept
  431. {
  432. return track >= 0 && track < maxMixerTracks && (side == 0 || side == 1) ? lastInputPeaks[(std::size_t) (track * 2 + side)] : 0.0f;
  433. }
  434. // A message for the user about recording (e.g. an armed insert without an input), once. UI thread.
  435. RecordingNotice takeRecordingNotice() { return std::exchange (recordingNotice, {}); }
  436. // MIDI learn: the next CC received becomes a controller linked to `target`.
  437. void learnMidiController (const AutomationTarget& target);
  438. bool isLearningMidi() const noexcept { return learning.kind != AutomationTargetKind::none; }
  439. // Global links (FL's "Override global link...", REA round 146): links in the MIDI settings that every project
  440. // follows unless it links the same target or controller itself. The next CC received becomes `target`'s.
  441. void learnGlobalLink (const AutomationTarget& target);
  442. void removeGlobalLink (const AutomationTarget& target);
  443. std::optional<MidiLink> globalLinkOf (const AutomationTarget& target) const;
  444. std::vector<MidiLink> getGlobalLinks() const;
  445. // FL's "Last tweaked" (REA round 143: FLEngine keeps the last two moved parameters, Tools › Last tweaked /
  446. // Next to last tweaked, Add › Automation for last tweaked parameter). Every control that can be automated reports
  447. // its moves here (UI thread); `held` = the touch lasts until tweakReleased (a plugin's own editor's gesture),
  448. // otherwise while the control keeps moving. While recording with the "Automation" filter, touched parameters are
  449. // written as automation.
  450. void noteTweaked (const AutomationTarget& target, bool held = false);
  451. void tweakReleased (const AutomationTarget& target);
  452. // 0 = the last tweaked parameter, 1 = the one before it.
  453. std::optional<AutomationTarget> getLastTweaked (int which = 0) const;
  454. // The target's current value 0..1 (a hosted plugin's parameter and MIDI controls included); < 0 when it is gone.
  455. float currentTargetValue (const AutomationTarget& target) const;
  456. // Parameter `param` of a hosted plugin (a channel's instrument or a slot's effect) as an automation target.
  457. std::optional<AutomationTarget> targetOfPlugin (const juce::AudioPluginInstance& plugin, int param) const;
  458. // Number of points recorded as automation since recording started (tests, hint bar).
  459. int getRecordedAutomationPoints() const noexcept { return recordedAutomationPoints; }
  460. // Names a new recorded automation (the UI sets it to its readable target names).
  461. std::function<std::string (const AutomationTarget&)> nameAutomation;
  462. // MIDI inputs: every device is enabled and plays the selected channels unless the MIDI settings say otherwise
  463. // (Settings › MIDI: device off, one MIDI channel only, a fixed Channel Rack channel; velocity curve; pickup).
  464. juce::StringArray getActiveMidiInputs() const;
  465. // Counts the messages received from the enabled MIDI inputs (the toolbar's MIDI activity light).
  466. std::uint32_t getMidiActivity() const noexcept { return midiActivity.load (std::memory_order_relaxed); }
  467. std::uint32_t getMidiPlayed() const noexcept { return midiPlayed.load (std::memory_order_relaxed); }
  468. // Closes and opens again every enabled MIDI input (the MIDI light's click; Settings › MIDI › Refresh).
  469. void reconnectMidiInputs();
  470. const prefs::MidiPrefs& getMidiPrefs() const noexcept { return midiPrefs; }
  471. // Applies them (and saves them in %APPDATA%\LYNX\midi-settings.txt when `save`).
  472. void setMidiPrefs (const prefs::MidiPrefs& prefs, bool save = true);
  473. // master sync out / external clock in / all notes off (round 165f)
  474. MidiSyncIo& getMidiSync() noexcept { return midiSync; }
  475. // How many undo steps are kept (Settings › General).
  476. void setUndoLevels (int levels);
  477. int getUndoLevels() const noexcept { return (int) maxUndoSteps; }
  478. // Document (UI thread)
  479. const Song& getSong() const noexcept { return song; }
  480. // The values automation gives the controls at the playhead while the song plays (issue #12: knobs and faders move
  481. // with their automation, as in FL). Refreshed at most once per UI frame, on the UI thread only; the audio thread
  482. // does no extra work for it. An editor shows `shown (target, its Song value)` and repaints when the generation
  483. // changes.
  484. const AutomationDisplay& getAutomationDisplay();
  485. // the time the last refresh took (ms), for --perf style measurements
  486. double getAutomationDisplayMs() const noexcept { return automationDisplayCostMs; }
  487. void setSong (Song newSong); // new/opened project: clears the history
  488. // Edits the song and publishes it to audio. `undoable` edits go into the history;
  489. // all edits made while the same mouse click is held down
  490. // (dragging a note, turning a knob) become a single step.
  491. void editSong (const std::function<void (Song&)>& edit, bool undoable = true);
  492. // For an edit that moves or removes channels, mixer tracks or effect slots (issue #32, PR #37): the live plugin
  493. // settings are copied into the Song first, so the undo step has them; the moved plugins keep their instances (the
  494. // rack matches them by instance tag, round 168s).
  495. void editSongStructural (const std::function<void (Song&)>& edit);
  496. // An edit that gives the patterns other indices (sort, move): one undo step like editSong, but without
  497. // followPatternLengths, which compares by index and would resize clips that were sized by hand (round 177d).
  498. void editSongPatternOrder (const std::function<void (Song&)>& edit);
  499. // An edit that changes only levels (mixer volume / pan / separation, channel volume / pan), e.g. a fader drag: one
  500. // undo step per press like editSong, but the playing snapshot takes the values at once without a rebuild (round
  501. // 171c); the full publish follows when the mouse is released. Anything else falls back to editSong.
  502. void editLevels (const std::function<void (Song&)>& edit, bool undoable = true);
  503. // the publish editLevels deferred, now (tests; the timer does it after a drag)
  504. void flushLevels();
  505. std::uint64_t getLevelEditCount() const noexcept { return levelEdits; }
  506. // editLevels notifies this one only (the engine's own change message follows with the full publish after the drag):
  507. // the ~45 views listening to the engine would otherwise all repaint at every mouse move. The views that show
  508. // levels (Mixer strips, Channel Rack) listen to it too.
  509. juce::ChangeBroadcaster& getLevelsBroadcaster() noexcept { return levelsChanged; }
  510. // + 1 at every full publish (not at a level-only edit): listeners can tell a drag's level change from the rest
  511. std::uint64_t getPublishCount() const noexcept { return publishCount; }
  512. // Changes since the last save/open (for the "*" in the title and the "save changes?" prompt).
  513. bool isModified() const noexcept { return modified; }
  514. void markSaved() noexcept { modified = false; sendChangeMessage(); }
  515. void markModified() noexcept { modified = true; sendChangeMessage(); } // e.g. a backup was opened in place of the project
  516. bool canUndo() const noexcept { return sessionHistory ? ! sessionUndo.empty() : ! undoStack.empty(); }
  517. bool canRedo() const noexcept { return sessionHistory ? ! sessionRedo.empty() : ! redoStack.empty(); }
  518. void undo();
  519. void redo();
  520. // Online Sessions P2 (round 169b): a live session's copy of the song changed by someone else's edit — like setSong,
  521. // but the history stays, the project stays modified and nothing becomes an undo step.
  522. void applyRemote (Song remote);
  523. // Undo per user (ONLINE_SESSIONS.md §1.4): while on, undo / redo bring back only this person's own entities (each one
  524. // still as his step left it), never other people's edits made since. `onSkipped` names what had to stay.
  525. void setSessionHistory (bool on);
  526. bool hasSessionHistory() const noexcept { return sessionHistory; }
  527. std::function<void (const juce::StringArray& skipped)> onSessionUndoSkipped;
  528. std::uint64_t getSongStamp() const noexcept { return songStamp; }
  529. // Undo history as a list of states, oldest first: the undo steps, the current state, then the redo
  530. // steps. Each entry is named after what changed from the previous one (core/History.h).
  531. int getHistorySize() const noexcept
  532. {
  533. return sessionHistory ? (int) (sessionUndo.size() + 1 + sessionRedo.size()) : (int) (undoStack.size() + 1 + redoStack.size());
  534. }
  535. int getHistoryPosition() const noexcept { return sessionHistory ? (int) sessionUndo.size() : (int) undoStack.size(); }
  536. ChangeLabel getHistoryLabel (int index) const; // index 0 = the oldest state kept
  537. void jumpToHistory (int index);
  538. // Channel selected in the Channel Rack (target of the Piano Roll and keyboard). UI thread.
  539. int getSelectedChannel() const noexcept { return selectedChannel; }
  540. void setSelectedChannel (int channel); // selects only this channel
  541. // Multi-selection in the Channel Rack (sorted). The selected channels all receive live MIDI input;
  542. // `primary` (one of them) is the Piano Roll / keyboard target above.
  543. const std::vector<int>& getSelectedChannels() const noexcept { return selectedChannels; }
  544. void setChannelSelection (std::vector<int> channels, int primary);
  545. // Imports a .flp, locating the FL installation to find the samples.
  546. // Returns false and fills `error` on failure. `relocations` (saved sample path → file to use) are the samples
  547. // the user located; with `asEdit` the result replaces the song as one undoable step instead of a new project.
  548. bool importFlpFile (const juce::File& file, juce::String& error, const std::map<std::string, std::string>& relocations = {},
  549. bool asEdit = false);
  550. // The same import in steps, so a window can show progress while it runs (round 112): `prepareFlpImport` reads,
  551. // parses and imports the project and decodes its samples in parallel — no plugin is touched, so it may run on any
  552. // thread; `preloadPlugins` creates the project's hosted plugins one at a time (message thread; call it until it
  553. // returns false); `finishFlpImport` adopts the result as the song (message thread). Phase times go to core/LoadTrace.
  554. struct PreparedFlp
  555. {
  556. bool ok = false;
  557. juce::String error;
  558. Song song;
  559. FlpImportReport report;
  560. std::vector<std::shared_ptr<const SampleData>> decoded; // kept alive until the rack is built
  561. std::vector<PluginRef> pluginQueue; // hosted plugins to create, in rack order
  562. std::size_t pluginsDone = 0;
  563. bool adopted = false;
  564. juce::StringArray missing, matched, withoutState, substituted;
  565. struct Use
  566. {
  567. std::string name, user;
  568. bool instrument = false;
  569. };
  570. std::vector<Use> uses;
  571. };
  572. static void prepareFlpImport (const juce::File& file, const std::map<std::string, std::string>& relocations, SampleLibrary& library,
  573. PreparedFlp& out);
  574. // one hosted plugin of the queue (message thread); false when the queue is done
  575. bool preloadNextPlugin (PreparedFlp& prepared);
  576. // Before importing the open project again: leaves out of `prepared`'s plugin queue those the song already runs
  577. // with the same settings (the rack keeps them).
  578. void keepRunningPlugins (PreparedFlp& prepared);
  579. bool finishFlpImport (PreparedFlp&& prepared, bool asEdit);
  580. // --- real-time bounce (round 165c: Export › "Render through the hardware in real time") ---
  581. // The song plays through the audio device from `startTick` (song mode; past its end and through the loop region,
  582. // without starting over) while the Master's output is recorded: hardware inserts send to and return from their gear
  583. // as they do while playing. Message thread; returns an error (empty: started).
  584. juce::String startRealtimeBounce (double startTick);
  585. // What the Master played since the last call, from the first sample the song played (one consumer thread).
  586. int pullRealtimeBounce (std::vector<float>& left, std::vector<float>& right) { return meters.bounceTap.pull (left, right); }
  587. bool isBouncing() const noexcept { return bouncing; }
  588. // While bouncing: the transport still plays (false: the user stopped it), the delay compensation's total at the
  589. // start, the device's dropouts and the frames the tap lost since the start.
  590. bool bounceStillPlaying() const noexcept { return transport.playing.load(); }
  591. int bounceLatency() const noexcept { return bounceStartLatency; }
  592. int bounceDropouts() const;
  593. // Stops playback and puts the transport back as it was (message thread).
  594. void finishRealtimeBounce();
  595. // Renders without an audio device. Writes to `output` if not nullptr.
  596. // After `seconds`, continues for up to `tailSeconds` while there is still sound.
  597. // `progress(0..1)` returns false to cancel. Returns the peak (used by the self-test),
  598. // or -1 if cancelled.
  599. struct RenderOptions
  600. {
  601. double seconds = 10.0;
  602. double sampleRate = 44100.0;
  603. juce::AudioFormatWriter* output = nullptr;
  604. std::function<bool (double)> progress; // 0..1; false cancels
  605. double tailSeconds = 0.0;
  606. int trimSamples = 0; // PDC: discards this much from the start and renders the same amount extra at the end
  607. int ditherBits = 0; // > 0: TPDF dither (with noise shaping unless ditherShaping is false) for this bit depth
  608. bool ditherShaping = true;
  609. // FL's "HQ for all plugins": render qualities and HQ switches on (off: the playback quality)
  610. bool hqAllPlugins = true;
  611. // receives every rendered block after the PDC trim (left, right, frames), like `output` does
  612. std::function<void (const float*, const float*, int)> capture;
  613. // trim the delay compensation's latency as the plugins report it after the warm-up (adds to trimSamples)
  614. bool trimPdc = false;
  615. // Export "Plugin warm-up" (round 155, core/PluginWarmup.h): with hosted plugins in the song, silent blocks are
  616. // processed and thrown away before the render until the plugins have settled
  617. bool pluginWarmUp = true;
  618. warmup::Settings warmUp;
  619. // false: samples above 0 dBFS are clamped to ±1 before the dither / the file (integer formats, Ogg)
  620. bool keepOvers = false;
  621. // FL never puts the metronome in an export (round 165z-a2, measured): off, the click is left out even with
  622. // the metronome on. (The selftest turns it on to measure the click.)
  623. bool includeMetronome = false;
  624. };
  625. float renderOffline (const RenderOptions& options);
  626. // How many offline renders run now, in any engine (round 168s, issue #32). While one runs, the engine that plays
  627. // through the audio device stops and outputs silence without processing (FL stops playback while it renders): the
  628. // project's live plugins never run next to their export copies (plugins that share state between instances cut
  629. // notes in the file) and no CPU goes to them (the glitches heard until the progress bar ended).
  630. static std::atomic<int>& offlineRendersRunning() noexcept;
  631. // timings of the last renderOffline (diagnostics): the audio graph and the file writing
  632. struct RenderStats
  633. {
  634. double graphMs = 0.0, writeMs = 0.0;
  635. warmup::Result warmUp; // the plugin warm-up before the render (blocks == 0: none ran)
  636. int trimmedSamples = 0; // the PDC trim used
  637. };
  638. RenderStats getLastRenderStats() const noexcept { return lastRenderStats; }
  639. float renderOffline (double seconds, double sampleRate, juce::AudioFormatWriter* output = nullptr)
  640. {
  641. RenderOptions o;
  642. o.seconds = seconds;
  643. o.sampleRate = sampleRate;
  644. o.output = output;
  645. return renderOffline (o);
  646. }
  647. int getNumGraphConnections() const { return (int) graph.getConnections().size(); }
  648. // Time spent in each instrument and effect (the Plugin performance monitor); nullptr without the rack node.
  649. ProcessTimes* getProcessTimes() noexcept;
  650. // Latest output samples (mono), for the oscilloscope. UI thread.
  651. void copyScope (float* destination, int count) const noexcept;
  652. static constexpr int scopeSize = 2048;
  653. // Real-time health of the audio callback (REA round 87): callbacks over their deadline, late device calls, load.
  654. const RtStats& getRtStats() const noexcept { return rtStats; }
  655. RtStats& getRtStats() noexcept { return rtStats; }
  656. // What takes the most audio CPU: channels and insert effects, as a share of real time over the last ~2 s of
  657. // playback, heaviest first. UI thread.
  658. struct UnitLoad
  659. {
  660. juce::String name;
  661. double load = 0.0; // CPU time / audio time (summed over the worker threads)
  662. double longestMs = 0.0; // the longest single call in the window
  663. };
  664. const std::vector<UnitLoad>& getHeaviestUnits() const noexcept { return heaviestUnits; }
  665. // How regularly the message thread runs the engine's 30 Hz timer (a saturated UI delays it). UI thread.
  666. struct UiPulse
  667. {
  668. int calls = 0;
  669. double maxGapMs = 0.0;
  670. };
  671. UiPulse takeUiPulse() noexcept { return std::exchange (uiPulse, {}); }
  672. // Writes `state` (a createStateXml() taken earlier; nullptr = none was saved) back as the saved device and stops
  673. // saving later changes: a test run (--rtstress --type ...) leaves the user's device as it found it.
  674. void restoreAudioDeviceState (const juce::XmlElement* state);
  675. // Device, buffer, deadline and the callback statistics in a few lines (CPU meter hint, glitch log, --rtstress).
  676. juce::String describeRealtime (bool withUnits = true) const;
  677. // Settings › Audio "Driver settings…": shows the device's own panel (ASIO) and, when the driver says its settings
  678. // changed, reopens it with them. The device object is replaced (its driver re-read), so the old pointer is never
  679. // used after the close (0.1.17 / 0.1.18 called the deleted device: issues #12 and #13), and the buffer size the
  680. // panel chose is kept (the reopen asks for the driver's preferred size instead of the size LYNX had before, which
  681. // silently undid an ASIO4ALL / FL ASIO buffer change). Returns true when the device was reopened. Message thread.
  682. static bool showDriverPanel (juce::AudioDeviceManager& devices);
  683. // --selftest "driver_panel": showDriverPanel with a fake device whose panel changes its buffer (and one whose panel
  684. // changes nothing). "OK" or what went wrong.
  685. static juce::String driverPanelSelfTest();
  686. // %APPDATA%\LYNX\audio-glitches.log: a line each time callbacks run over their deadline (at most every 2 s).
  687. static juce::File glitchLogFile();
  688. // Total latency compensated by PDC (at the Master output), in samples.
  689. int getLatencySamples() const noexcept { return lastPublishedShape.pdc.total; }
  690. // The last published PDC plan (per-track latencies: outLat, inAlign). Message thread.
  691. const PdcPlan& getPdcPlan() const noexcept { return lastPublishedShape.pdc; }
  692. private:
  693. void audioDeviceIOCallbackWithContext (const float* const* inputChannelData,
  694. int numInputChannels,
  695. float* const* outputChannelData,
  696. int numOutputChannels,
  697. int numSamples,
  698. const juce::AudioIODeviceCallbackContext& context) override;
  699. void audioDeviceAboutToStart (juce::AudioIODevice* device) override;
  700. void audioDeviceStopped() override;
  701. void timerCallback() override;
  702. void handleIncomingMidiMessage (juce::MidiInput* source, const juce::MidiMessage& message) override;
  703. void enableAllMidiInputs();
  704. void saveAudioDeviceState();
  705. void updateRecording();
  706. void updateAudioRecording();
  707. void updateAutomationRecording (bool active);
  708. void startAudioTake();
  709. void finishAudioTake();
  710. double estimatedPositionNow() const noexcept;
  711. AutomationDisplay automationDisplay;
  712. std::uint64_t songStamp = 1; // + 1 at every publishSong (the display's tables follow the Song)
  713. double automationDisplayAtMs = -1.0e9; // when it was last refreshed
  714. double automationDisplayCostMs = 0.0;
  715. void buildInitialGraph();
  716. void choosePreferredDriver(); // a first start on Linux: PipeWire, then JACK, then ALSA (round 161)
  717. void chooseSafeBufferSize();
  718. void updateRealtimeStats(); // timer: unit loads over a window, glitch log
  719. RtStats rtStats;
  720. std::vector<UnitLoad> heaviestUnits;
  721. std::vector<std::uint64_t> lastChannelNs, lastEffectNs;
  722. std::uint64_t lastProcessedSamples = 0;
  723. double lastUnitsWindowMs = 0.0, lastUiPulseMs = 0.0;
  724. UiPulse uiPulse;
  725. int latencyRepublishes = 0; // PDC re-plans because a unit's latency changed (diagnostics)
  726. juce::String lastLatencyChange;
  727. // hardware inserts (round 165c): ping results applied to the slots (whether an editor is open or not), and the device
  728. // setup they were measured for
  729. void applyHardwareInsertPings();
  730. std::map<const void*, int> hwPingSerials; // running insert -> the last ping result seen
  731. std::string lastSetupKey;
  732. std::vector<HardwareInsertRef> hwNotice;
  733. int hwTicks = 0;
  734. bool bouncing = false;
  735. int bounceStartLatency = 0, bounceStartXruns = 0;
  736. double bounceReturnTick = 0.0;
  737. bool bounceRestoreMode = false;
  738. bool checkHardwareInserts = false;
  739. std::uint64_t loggedOver = 0, loggedLate = 0;
  740. double lastLogMs = 0.0;
  741. class PreviewPlayer* preview = nullptr; // graph node (owned by the graph)
  742. double previewVolume = 1.0;
  743. double editorVolume = 1.0;
  744. void publishSong();
  745. void adoptPrepared (PreparedFlp& prepared); // the plugins of a prepared import found / substituted (message thread)
  746. std::unique_ptr<WorkerPool> workers; // extra renderer threads (before the graph, which uses them)
  747. juce::AudioDeviceManager deviceManager;
  748. juce::AudioProcessorGraph graph;
  749. juce::AudioProcessorPlayer player;
  750. Transport transport;
  751. MidiSyncIo midiSync; // (before the MIDI callbacks and the audio callback use it)
  752. SampleLibrary samples;
  753. LiveEventQueue liveEvents; // UI -> audio
  754. LiveEventQueue midiEvents; // MIDI thread -> audio
  755. InputHeldNotes midiHeld; // MIDI thread: what each held MIDI key started
  756. std::atomic<std::uint64_t> heldKeyBits[2] {}; // keys held on MIDI inputs / the typing piano (chord readout)
  757. std::atomic<std::uint8_t> heldKeyCount[128] {};
  758. void markHeldKey (int key, bool on) noexcept;
  759. KeyLedger playedKeys; // UI thread: the keys the typing piano started (after the scale snap)
  760. SpscQueue<RecordedEvent, 1024> midiRecordQueue; // MIDI thread -> UI (recording)
  761. // a controller's pitch wheel while recording (MIDI thread -> UI): key = its MIDI channel 0…15, velocity = 0..1;
  762. // written as the channel's pitch bend automation like a moved knob (issue #12: the bend was heard, not recorded)
  763. SpscQueue<RecordedEvent, 2048> bendRecordQueue;
  764. std::map<int, float> liveBends; // UI thread: the last recorded bend of each channel (its "current value")
  765. void takeRecordedBends();
  766. struct ControllerEvent
  767. {
  768. int cc = 0, channel = 0, value = 0;
  769. };
  770. SpscQueue<ControllerEvent, 1024> controllerQueue; // MIDI thread -> UI (controllers)
  771. // the CCs a MIDI link (project or global) uses: they move their parameter and are not also played into the
  772. // selected channel's instrument (round 162); written by applyControllers, read by the MIDI thread
  773. std::array<std::atomic<std::uint64_t>, 2> linkedCcs {};
  774. AutomationTarget learning;
  775. bool learningGlobal = false;
  776. bool saveGlobalLinks = false; // only the engine with an audio device (the app) writes the settings file
  777. void applyControllers();
  778. std::atomic<int> pendingMarkerNote { -1 }; // MIDI thread -> timer: a "Song marker jump" note
  779. std::vector<RecordedEvent> uiRecorded; // PC keyboard -> recording
  780. NoteRecorder recorder;
  781. // last tweaked parameters and automation recording (REA round 143)
  782. std::array<AutomationTarget, 2> lastTweaked {};
  783. struct Touch
  784. {
  785. AutomationTarget target;
  786. double lastMs = 0.0;
  787. bool held = false;
  788. std::vector<RecordedValue> pending; // sampled, not yet written
  789. };
  790. std::vector<Touch> touches;
  791. int automationCommitCountdown = 0;
  792. bool automationTakeHasUndoStep = false;
  793. std::int64_t automationLoopLength = 0;
  794. int automationPattern = 0;
  795. int recordedAutomationPoints = 0;
  796. bool automationOverrideActive = false; // touched targets override their automation in the renderer
  797. // Song mode, no loop region: once a parameter moved while recording, the song plays on past its end (no wrap to
  798. // the start) until recording stops, and the take's clip grows with the playhead (issue #12: it cut itself)
  799. bool automationLinear = false;
  800. // the same for the whole of a take (FL: Song mode plays on while recording; round 168k)
  801. bool noteTakeLinear = false;
  802. std::int64_t lastAutomationTick = -1; // the song position of the take's last update (song mode)
  803. std::vector<AutomationWrite> takeWrites; // per target: where this take writes (its own clip grows)
  804. bool takeHasUndoStep = false;
  805. bool perfTakeHasUndoStep = false; // the first clip a performance recording writes is the take's undo step
  806. void updatePerformanceRecording();
  807. RecordOptions recordOptions;
  808. std::vector<int> takeClearedChannels; // replace mode: channels already cleared in this take
  809. std::atomic<bool> waitingForInput { false };
  810. void startOnInput() noexcept; // MIDI or UI thread: the first note while waiting starts playback
  811. std::vector<int> armedInserts;
  812. juce::String releasedInputDevice; // the input device releaseAudioInputIfUnused closed (reopened by name)
  813. double lastPlayingTick = 0.0;
  814. RecordOffOnStop recordSwitch; // FL's "Disarm on stop"
  815. std::atomic<int> inputScale { 0 }, inputScaleRoot { 0 };
  816. std::atomic<int> liveChannel { 0 }; // selected channel, read by the MIDI thread
  817. static constexpr int maxLiveChannels = 16; // other selected channels that also get MIDI input
  818. std::array<std::atomic<int>, maxLiveChannels> extraLiveChannels {};
  819. std::atomic<int> extraLiveCount { 0 };
  820. void publishSelection();
  821. std::atomic<double> blockTimeMs { 0.0 }; // when positionTicks was last updated
  822. std::atomic<double> blockDurationMs { 0.0 }; // the last block's length (round 174e: playheadAdvanceTicks)
  823. // round 174e: the device's callback thread (Windows): its priority when first seen and after LYNX raised it to the
  824. // workers' MMCSS "Pro Audio" class (a driver's own thread at normal priority competed with the UI; LYNX_DEVICE_BOOST=0:
  825. // left as the driver made it). Shown in the real-time report.
  826. std::atomic<unsigned long> deviceThreadId { 0 };
  827. std::atomic<int> deviceThreadPriorityBefore { -100 }, deviceThreadPriorityAfter { -100 };
  828. bool boostDeviceThread = true;
  829. // the live clock (round 170d): the musical position of the next block (count-in included), its tempo, and whether
  830. // it runs; the output latency the played notes are moved back by
  831. std::atomic<double> clockTick { 0.0 }, clockTicksPerMs { 0.0 }, outputCompensationMs { 0.0 };
  832. std::atomic<bool> clockRunning { false }, compensatePlayed { true };
  833. CountInCatch takeCatch; // UI thread
  834. double lastCaptureMs = -1.0; // UI thread: the newest note Capture MIDI took
  835. std::array<std::atomic<float>, scopeSize> scope {}; // ring buffer of the output (written by audio)
  836. std::atomic<int> scopeWrite { 0 };
  837. juce::MidiDeviceListConnection midiDevicesChanged;
  838. std::vector<std::string> lastMidiInputIds; // the MIDI inputs available at the last check (UI thread)
  839. int midiCheckTicks = 0;
  840. std::atomic<std::uint32_t> midiActivity { 0 }, midiPlayed { 0 };
  841. prefs::MidiPrefs midiPrefs; // UI thread
  842. juce::SpinLock midiPrefsLock; // guards midiPrefsShared (UI writes, MIDI thread reads)
  843. prefs::MidiPrefs midiPrefsShared;
  844. // FL's "Receive notes from" (round 165f-rack): the channels locked to a MIDI input device (and MIDI channel, 0 = any),
  845. // rebuilt from the song on every publish; guarded by midiPrefsLock too
  846. struct NoteLock
  847. {
  848. std::string device;
  849. int midiChannel = 0;
  850. int channel = 0;
  851. };
  852. std::vector<NoteLock> noteLocks;
  853. void logPlayedNote (int channel, int key, float velocity, bool on, double tick = -1.0, bool recorded = false);
  854. mutable juce::SpinLock scoreLogLock; // MIDI thread and UI thread write, the UI reads
  855. scorelog::Log scoreLog;
  856. std::atomic<bool> stepEditOn { false };
  857. std::vector<stepedit::Played> stepEditQueue; // under scoreLogLock
  858. std::map<std::tuple<int, int, int, int, int, int>, prefs::PickupState> pickups; // (cc, channel, target) -> takeover
  859. // settings / log files written off the message thread (issue #13's freezes); declared before the saver so it
  860. // outlives it, and its destructor writes what is still queued
  861. SerialJobs fileJobs;
  862. struct DeviceStateSaver;
  863. std::unique_ptr<DeviceStateSaver> deviceStateSaver;
  864. // audio recording
  865. bool audioArmed = false;
  866. juce::String recordingError;
  867. juce::File recordingFolder = defaultRecordingFolder();
  868. juce::String recordingStem;
  869. std::vector<juce::File> sessionRecordings;
  870. juce::TimeSliceThread recordThread { "LYNX recording" };
  871. RecordingNotice recordingNotice;
  872. void notify (InputIssue issue, int track = 0, const juce::String& detail = {});
  873. // One take being recorded (round 163): the audio thread pushes into `stream`, the recording thread drains it
  874. // into `writer` (crash-safe WAV). Shared by the UI (start/finish), the audio thread (raw pointer under
  875. // takeLock) and the recording thread (drainer list under drainLock).
  876. struct Take
  877. {
  878. int track = 0; // insert it plays through (0 = a new free insert)
  879. int first = 0; // device input channel
  880. int channels = 0; // 1 or 2
  881. // round 168x (issue #41): a take tapped inside its insert (FL's "Record" positions after the input) reads
  882. // liveInput.taps[tap] after the block was rendered (−1 = the device input itself). Its first `skip` frames are
  883. // dropped (the latency of the insert's effects up to the tap) and as many frames of silence close it, so it
  884. // lines up with the input to the sample.
  885. int tap = -1;
  886. int skip = 0;
  887. int skipped = 0; // audio thread
  888. int playThrough = 0; // the insert the take's clip plays through (0 = a new free insert)
  889. juce::File file;
  890. std::unique_ptr<takes::TakeStream> stream;
  891. takes::WavTakeWriter writer;
  892. std::atomic<bool> failed { false };
  893. std::vector<float> scratch;
  894. std::shared_ptr<liverec::LivePeaks> peaks = std::make_shared<liverec::LivePeaks>(); // the live waveform (round 177d)
  895. juce::CriticalSection drainMutex; // the recording thread vs the UI's final drain
  896. // recording thread: writes what arrived; false when the file could not be written
  897. bool drain();
  898. };
  899. static constexpr int maxTakes = 16;
  900. std::array<Take*, maxTakes> takes {}; // guarded by takeLock (the audio thread's view)
  901. int takeCount = 0;
  902. std::vector<std::shared_ptr<Take>> openTakes; // UI thread (owner)
  903. juce::CriticalSection drainLock; // the recording thread's list
  904. std::vector<std::shared_ptr<Take>> draining;
  905. struct Drainer;
  906. std::unique_ptr<Drainer> drainer;
  907. juce::SpinLock takeLock; // the audio thread only tries (never waits)
  908. LiveInput liveInput;
  909. std::unique_ptr<perf::Live> performanceLive = std::make_unique<perf::Live>(); // Performance mode (round 165m)
  910. std::atomic<int> performanceMidiChannel { 0 }; // MidiPrefs::performanceChannel (UI writes, MIDI thread reads)
  911. std::atomic<bool> performanceMidiOn { false }; // Performance mode is on with a zone (UI writes, MIDI thread reads)
  912. perf::MidiMapping performanceMidi; // MIDI thread only
  913. HardwareOutput hwOutput; // inserts' hardware outputs (renderer -> callback)
  914. std::array<int, HardwareOutput::maxChannels> outputSlot {}; // device output channel -> callback output index (-1: closed)
  915. std::atomic<int> masterOutChannel { outputDefault }; // the Master's target (UI -> audio)
  916. std::atomic<int> masterOutMode { 0 };
  917. std::vector<float> masterScratch = std::vector<float> (2 * HardwareOutput::capacity, 0.0f);
  918. void routeOutputs (float* const* outputs, int numOutputs, int n) noexcept; // audio thread
  919. std::array<float, maxMixerTracks * 2> lastInputPeaks {};
  920. std::array<int, LiveInput::maxChannels> inputSlot {}; // device input channel -> callback input index (-1: closed)
  921. // audio thread: its copy of the markers' actions (Transport::readMarkers) and how many marker jumps it made
  922. MarkerPlan rtMarkers;
  923. std::uint32_t rtMarkerVersion = 0;
  924. public:
  925. // marker jumps / pauses the audio thread made since start (tests, the hint bar); +1 each
  926. std::atomic<int> markerEvents { 0 };
  927. // Clicking the ruler / a marker while playing, FL's "Song marker jump": jump to `tick`, while playing at the next
  928. // "Quantize song jumps" step (FL's Playlist menu: 0 Off, 1 Beats, 2 Bars, 3 2 bars, 4 4 bars, 5 8 bars)
  929. void jumpTo (double tick) noexcept;
  930. void jumpToMarker (int index) noexcept; // the index-th marker of the arrangement (by position)
  931. void jumpToNextMarker (bool forward) noexcept;
  932. std::atomic<int> quantizeSongJumps { 0 };
  933. private:
  934. std::atomic<double> takeStartTick { -1.0 }; // position of the first recorded sample
  935. std::atomic<juce::int64> takeFrames { 0 };
  936. std::atomic<double> takeTicks { 0.0 }; // ticks the transport moved while recording (not wrapped)
  937. std::array<std::atomic<juce::int64>, 256> takeWraps {}; // take frames at which the loop jumped back (loop recording)
  938. std::atomic<int> takeWrapCount { 0 };
  939. mutable std::vector<int> liveTakeTracks; // the Playlist tracks the open takes will land on (round 177d)
  940. double takeSampleRate = 44100.0;
  941. double takeTicksPerSample = 0.0;
  942. int takeLatency = 0; // takes::Latency::total() at the take's start, in samples
  943. std::optional<PunchRange> activePunch; // pre-roll / punch range of the recording in progress (UI thread)
  944. std::int64_t punchStopAt = -1; // post-roll end: playback stops there (-1: none)
  945. bool linearRecording() const noexcept
  946. {
  947. return recordloop::linear (song.mode, song.hasLoop(), recordOptions.loopRecord, recordOptions.punchLoopRegion);
  948. }
  949. // the audio thread's view of the above while takes record (false when none is open)
  950. void updateLinearSong() noexcept
  951. {
  952. const auto on = (takeCount > 0 || automationLinear || noteTakeLinear) && linearRecording();
  953. liveInput.linearSong.store (on || bouncing);
  954. liveInput.noLoopRegion.store ((on && song.hasLoop()) || bouncing);
  955. }
  956. takes::LatencyPing ping; // audio thread while running (UI starts it, reads the result)
  957. juce::int64 lostFrames = 0;
  958. std::array<int, 2> pingOutputs { -1, -1 }; // callback output slots the click goes to
  959. int pingInput = -1; // callback input slot listened to
  960. RecordingSettings recordingSettings;
  961. juce::File journalFor (const juce::File& wav) const { return wav.withFileExtension ("wav.lynxrec"); }
  962. void writeJournals();
  963. bool journalsWritten = false;
  964. MeterBank meters;
  965. std::unique_ptr<AudioLogger> audioLogger; // after `meters` (it reads meters.logTap): destroyed first
  966. PluginHost plugins;
  967. juce::StringArray missingPlugins, matchedPlugins, pluginsWithoutState;
  968. FlpImportReport importReport;
  969. std::vector<MissingPlugin> missingPluginDetails;
  970. RenderStats lastRenderStats;
  971. class ChannelRackProcessor* rackProcessor = nullptr; // graph node (owner: the graph)
  972. Song song;
  973. int selectedChannel = 0;
  974. std::vector<int> selectedChannels { 0 };
  975. bool modified = false;
  976. double workSince = 0.0; // wall clock (ms since 1970) when the working time was last added
  977. std::unique_ptr<StreamPrefetcher> prefetcher; // only with an audio device (playing live)
  978. std::size_t maxUndoSteps = prefs::defaultUndoLevels;
  979. std::deque<Song> undoStack, redoStack;
  980. // undo per user (round 169b): each local step as (before, after); `sessionAfterOpen` = the last step's "after" is
  981. // still the song (it is taken when the next step starts, a remote change comes in, or undo is used)
  982. bool sessionHistory = false, sessionAfterOpen = false;
  983. std::deque<std::pair<Song, Song>> sessionUndo, sessionRedo;
  984. void closeSessionStep();
  985. void sessionStep (bool redo);
  986. juce::Time lastUndoPress; // mouse click that already produced an undo step
  987. SnapshotExchange<RackState> rackExchange;
  988. std::shared_ptr<LiveLevels> publishedLevels; // the last snapshot's live levels (editLevels writes them)
  989. bool levelsPending = false; // editLevels changed the Song since the last publish
  990. juce::ChangeBroadcaster levelsChanged;
  991. std::uint64_t levelEdits = 0; // (diagnostics / tests)
  992. std::uint64_t publishCount = 0;
  993. void saveUndoStep();
  994. RackState lastPublishedShape; // channels + instruments of the last snapshot, to reuse voices
  995. std::vector<int> standInChannels, standInInserts; // (playsStandIn)
  996. // Issue #36 (u-he Presswerk crashed in its VST3 teardown, freed from the engine's timer callback): the racks the
  997. // audio thread let go of are freed from a message of their own, not inside the timer callback that collected them.
  998. // A plugin whose editor is open dies when its window goes (the window closes the editor first). Declared after the
  999. // rack members: freed first, while the plugin hosts still exist. In the app only (tests have no message loop).
  1000. struct RackDisposer final : private juce::AsyncUpdater
  1001. {
  1002. ~RackDisposer() override
  1003. {
  1004. cancelPendingUpdate();
  1005. flush();
  1006. }
  1007. void add (const RackState* rack)
  1008. {
  1009. {
  1010. const juce::ScopedLock sl (lock);
  1011. items.push_back (rack);
  1012. }
  1013. triggerAsyncUpdate();
  1014. }
  1015. void flush()
  1016. {
  1017. std::vector<const RackState*> now;
  1018. {
  1019. const juce::ScopedLock sl (lock);
  1020. now.swap (items);
  1021. }
  1022. for (const auto* rack : now)
  1023. delete rack;
  1024. }
  1025. private:
  1026. void handleAsyncUpdate() override { flush(); }
  1027. juce::CriticalSection lock;
  1028. std::vector<const RackState*> items;
  1029. } rackDisposer;
  1030. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioEngine)
  1031. };
  1032. } // namespace lynx