AudioEngine.h 55 KB

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