diff --git a/CHANGELOG.md b/CHANGELOG.md index 131dad91..a5656031 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -48,9 +48,11 @@ being released into the GitHub Release notes, so keep one `## ` heading ✅ **Mix > Edit Groups…:** a window with every mix group in one list, where each group can be renamed and its links chosen (Volume, Pan, Mute, Solo). It shows how many tracks each group has, adds groups (up to 64, numbered automatically) and deletes them; the mixer strip's Group popup stays the way to put a track into a group. -✅ **Bounce:** **File > Bounce > Project or Section…** plays the song — or the cycle section, when the cycle is on — through the engine and writes what is heard into a 32-bit float WAV. Every effect (the master bus's included), send, automation lane, audio region and instrument is in the file, because the engine hands over its finished master frames. A bounce runs at playing speed; the transport and the cycle are put back where they were afterwards, and stopping the transport cancels it without writing a file. +✅ **Offline bounce, much faster than real time:** every bounce now renders offline, as Logic's Offline bounce does: **File > Bounce > Project or Section…**, **Export > Track as Audio File…**, **Bounce In Place** (Regions in Place…) and **Bounce and Join**. The song plays through the engine with no sound card, as fast as the processor allows, on a background thread, and writes the same 32-bit float WAV. On the demo song it renders about 4.7 times faster than playback (release build, Apple M1: 24 s of song in about 5 s). Audio regions wait for their disk reads instead of playing silence, and a plug-in in its own process waits for every block, so a busy disk or a slow plug-in cannot drop sound. The bounce works on a copy of the project taken when it starts: the transport, the playhead and the solos are not touched, and editing while it runs does not change the file. Escape cancels it. Two runs give the same file, sample for sample. Not covered: a track that monitors a live input (the I button) is silent in an offline bounce, because there is no input; the real-time bounce stays available with `PROWAVE_BOUNCE_REALTIME=1`. -✅ **Export > Track as Audio File…:** the selected track is bounced alone into a WAV. The other tracks are soloed off while it runs — the track keeps its effects, its sends and the buses they feed — and everyone's solo states are put back when it ends. It is the same real-time bounce as above, so it takes the song's length; a track with no regions is not exported. +✅ **Bounce:** **File > Bounce > Project or Section…** plays the song — or the cycle section, when the cycle is on — through the engine and writes what is heard into a 32-bit float WAV. Every effect (the master bus's included), send, automation lane, audio region and instrument is in the file, because the engine hands over its finished master frames. A bounce renders offline by default (see the entry below); with `PROWAVE_BOUNCE_REALTIME=1` it plays at playing speed instead, puts the transport and the cycle back afterwards, and stopping the transport cancels it without writing a file. + +✅ **Export > Track as Audio File…:** the selected track is bounced alone into a WAV. The other tracks are soloed off while it runs — the track keeps its effects, its sends and the buses they feed — and everyone's solo states are put back when it ends. It is bounced offline like the one above, so it does not take the song's length; a track with no regions is not exported. ✅ **Bounce in place:** **File > Bounce > Regions in Place…** (and **Record > Bounce In Place**) renders the selected MIDI region with its track's instrument, effects and sends, over the region's own span, and replaces the region with the audio where it was. It is one undo step, and the audio lives in the session's media folder until the project is saved, when it travels inside the `.prowave`. @@ -189,7 +191,6 @@ and no MIDI hardware were used. Windows and macOS builds are not tested in this ❌ **Not tested with hardware:** no real MIDI synth, clock source, audio interface or plug-in was used. The MIDI tests use ALSA virtual ports. ❌ **Plug-ins:** CLAP, VST3 and AU hosting does not exist yet. The Plug-in Manager is greyed out. -❌ **Bounce:** Bounce in Place and Bounce and Join need offline rendering, which the engine does not have yet. ❌ **Convert to New Sampler Track:** needs a sampler instrument, which the project does not have yet. ❌ **Chord and Arrangement tracks:** Show Chord Track and Show Arrangement Track need data that does not exist yet. ❌ **Audio settings:** the output device and buffer size cannot be chosen yet. Project Settings > Audio shows them read only. diff --git a/ROADMAP.md b/ROADMAP.md index 5d325d56..acd31580 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -333,7 +333,8 @@ positions (fixed, tested), prefetch size now follows the number of clips. the playhead, the others keep their distances), Quantize (the notes of selected MIDI regions go to the region's Quantize grid, 1/16 when Off; destructive), and Folder (the selected track goes into a track stack, as Track > Create Track Stack; this is our reading of Logic's "Folder"). Not done: - Bounce in Place (needs offline rendering) and Convert to New Sampler Track (needs a sampler track). + Convert to New Sampler Track (needs a sampler track). Bounce in Place came later, with offline + rendering (see "Since 0.2.2"). ✅ Done 2026-11-06: MIDI outputs. The sender (`midi_out.rs`) now works on a `Sink` trait, so its logic is tested with recording ports and a real ALSA virtual port (midir creates it; the notes and the clock arrive). Fixes: a note that was sounding when its track was moved to another port or channel is now released on the port it started on (before, it stayed on). New: each external track sends a Bank Select and a Program Change when it is routed (Inspector: MIDI Program and MIDI Bank, Off at the top of each range); MIDI Clock (Timing Clock 24 per beat, Start, Continue, Stop, Song Position) to the port chosen under Synchronization > Send MIDI Clock, made on the audio clock (`clock.rs`, the engine); Project Settings > MIDI > Send MIDI Panic (All Sound Off and All Notes Off on all 16 channels of every output in use). Saved in `.prowave` (`midi_program`, `midi_bank`, `midi_clock_out`). Not done (the last two were done later, see the next entries): pitch bend, channel aftertouch and SysEx; following MIDI clock from an input; a seek while stopped sends nothing, and a seek while playing sends a Song Position; no test on a real hardware synth. @@ -374,7 +375,7 @@ The items below marked done are in 0.2.2 (see CHANGELOG.md for the full list, an limitations at the end of the section). Still open, in the order the work would take them: - Plug-in hosting: CLAP, VST3 and Audio Unit effects load in the Audio FX slots (`prowave-plugin-host`, done 2026-11-14), with the Plugin Manager and a scan in a separate process. Each plug-in runs in a process of its own on macOS and Linux, shows its own window on macOS, and its parameters can be automated. Not done: instruments, the process of its own on Windows, the plug-ins' own windows on Windows and Linux. -- An offline (faster than real time) bounce: Bounce, Export Track, Bounce in Place and Bounce and Join all work now, but at playing speed. +- Audio output device and I/O buffer size in Project Settings > Audio (needs an engine stream restart). - Convert to New Sampler Track (needs a sampler instrument). - Show Chord Track and Show Arrangement Track (new data models). - Split and Join on audio, Pattern and Drummer regions (audio needs a start offset into the file). @@ -389,7 +390,7 @@ Done and merged into `main` (CHANGELOG.md, section 0.3.0, has the details): Filter envelopes, X-Over with Spread, Output EQ, synthesized IR tab) and three mastering presets. Not done: loading the user's own impulse-response files, tempo-synced Predelay. - **Effects on the Stereo Out (master) strip**, saved with the project. No automation lanes for them yet. -- **Bounce:** Project or Section, Export Track as Audio File, Bounce in Place, Bounce and Join (real time, WAV). +- **Bounce:** Project or Section, Export Track as Audio File, Bounce in Place, Bounce and Join (WAV). Offline by default (faster than real time, on a background thread); the real-time bounce stays with `PROWAVE_BOUNCE_REALTIME=1`. - **Menus that were greyed out and now work:** Record Toggle, Record Enable, Record Project Settings, Record / Record Repeat, Mix > Edit Groups, Show Automation, Delete Automation, Rename Project, Edit > Undo History, Paste Replace, File > Import > Audio File, Show in File Manager, @@ -563,7 +564,7 @@ test of all the features above on Windows and macOS. - [ ] Compile `prowave-engine` to WASM + AudioWorklet (128-sample blocks, SharedArrayBuffer + Atomics) - [ ] `prowave-wasm`: OPFS for project storage, Web UI via `egui_web` (same egui code), Web Remote (like Logic Remote but via browser/WebSocket) - [ ] Collaboration: Project file with Ed25519 signing, simple CRDT for arrangement (optional) -- [ ] Export: Bounce Project/Region/Track in Place (offline/real-time, normalize, dither Apogee UV22HR via `r8brain`), Export All Tracks as Audio, Export MIDI, MusicXML, AAF, ADM BWF (Atmos) +- [ ] Export: Bounce Project/Region/Track in Place (offline rendering done; normalize, dither Apogee UV22HR via `r8brain`, Export All Tracks as Audio), Export MIDI, MusicXML, AAF, ADM BWF (Atmos) - [ ] Performance: SIMD (`wide`, `std::simd`), benchmarks vs Logic/Reaper - **DoD:** Open in Chrome/Firefox, play 16-track project <30ms latency, bounce to WAV diff --git a/crates/prowave-app/locales/de.txt b/crates/prowave-app/locales/de.txt index ea567e35..1a78e12b 100644 --- a/crates/prowave-app/locales/de.txt +++ b/crates/prowave-app/locales/de.txt @@ -916,3 +916,6 @@ Not found = Nicht gefunden In Use = In Verwendung LADSPA scan = LADSPA-Suche Vamp scan = Vamp-Suche +the engine did not take the project in time; no file was written = die Engine hat das Projekt nicht rechtzeitig übernommen; es wurde keine Datei geschrieben +the bounce has not finished = der Bounce ist noch nicht fertig +cannot bounce: there is no audio output = Bounce nicht möglich: keine Audioausgabe diff --git a/crates/prowave-app/locales/es.txt b/crates/prowave-app/locales/es.txt index bcdc43d3..8a3d6698 100644 --- a/crates/prowave-app/locales/es.txt +++ b/crates/prowave-app/locales/es.txt @@ -916,3 +916,6 @@ Not found = No encontrado In Use = En uso LADSPA scan = Búsqueda LADSPA Vamp scan = Búsqueda Vamp +the engine did not take the project in time; no file was written = el motor no aceptó el proyecto a tiempo; no se escribió ningún archivo +the bounce has not finished = el bounce aún no ha terminado +cannot bounce: there is no audio output = no se puede hacer el bounce: no hay salida de audio diff --git a/crates/prowave-app/locales/fi.txt b/crates/prowave-app/locales/fi.txt index c1a938e9..329ec9b7 100644 --- a/crates/prowave-app/locales/fi.txt +++ b/crates/prowave-app/locales/fi.txt @@ -916,3 +916,6 @@ Not found = Ei löytynyt In Use = Käytössä LADSPA scan = LADSPA-haku Vamp scan = Vamp-haku +the engine did not take the project in time; no file was written = äänimoottori ei ottanut projektia vastaan ajoissa; tiedostoa ei kirjoitettu +the bounce has not finished = bounce ei ole vielä valmis +cannot bounce: there is no audio output = bounce ei onnistu: ei äänilähtöä diff --git a/crates/prowave-app/locales/fil.txt b/crates/prowave-app/locales/fil.txt index bdd7af20..99b62fcb 100644 --- a/crates/prowave-app/locales/fil.txt +++ b/crates/prowave-app/locales/fil.txt @@ -916,3 +916,6 @@ Not found = Hindi nahanap In Use = Ginagamit LADSPA scan = LADSPA scan Vamp scan = Vamp scan +the engine did not take the project in time; no file was written = hindi tinanggap ng engine ang proyekto sa tamang oras; walang file na naisulat +the bounce has not finished = hindi pa tapos ang bounce +cannot bounce: there is no audio output = hindi maaaring mag-bounce: walang audio output diff --git a/crates/prowave-app/locales/fr.txt b/crates/prowave-app/locales/fr.txt index 17be9355..bc0dfe4c 100644 --- a/crates/prowave-app/locales/fr.txt +++ b/crates/prowave-app/locales/fr.txt @@ -916,3 +916,6 @@ Not found = Introuvable In Use = Utilisés LADSPA scan = Analyse LADSPA Vamp scan = Analyse Vamp +the engine did not take the project in time; no file was written = le moteur n'a pas pris le projet à temps ; aucun fichier n'a été écrit +the bounce has not finished = le bounce n'est pas terminé +cannot bounce: there is no audio output = impossible de faire le bounce : aucune sortie audio diff --git a/crates/prowave-app/locales/hi.txt b/crates/prowave-app/locales/hi.txt index 88deb033..b1d84cd4 100644 --- a/crates/prowave-app/locales/hi.txt +++ b/crates/prowave-app/locales/hi.txt @@ -916,3 +916,6 @@ Not found = नहीं मिला In Use = उपयोग में LADSPA scan = LADSPA स्कैन Vamp scan = Vamp स्कैन +the engine did not take the project in time; no file was written = इंजन ने प्रोजेक्ट समय पर स्वीकार नहीं किया; कोई फ़ाइल नहीं लिखी गई +the bounce has not finished = बाउंस अभी पूरा नहीं हुआ है +cannot bounce: there is no audio output = बाउंस नहीं हो सकता: कोई ऑडियो आउटपुट नहीं है diff --git a/crates/prowave-app/locales/id.txt b/crates/prowave-app/locales/id.txt index dc54fe11..2c00d977 100644 --- a/crates/prowave-app/locales/id.txt +++ b/crates/prowave-app/locales/id.txt @@ -916,3 +916,6 @@ Not found = Tidak ditemukan In Use = Digunakan LADSPA scan = Pindai LADSPA Vamp scan = Pindai Vamp +the engine did not take the project in time; no file was written = engine tidak menerima proyek tepat waktu; tidak ada berkas yang ditulis +the bounce has not finished = bounce belum selesai +cannot bounce: there is no audio output = tidak dapat bounce: tidak ada output audio diff --git a/crates/prowave-app/locales/ja.txt b/crates/prowave-app/locales/ja.txt index c017bba3..f91061da 100644 --- a/crates/prowave-app/locales/ja.txt +++ b/crates/prowave-app/locales/ja.txt @@ -916,3 +916,6 @@ Not found = 見つかりません In Use = 使用中 LADSPA scan = LADSPAスキャン Vamp scan = Vampスキャン +the engine did not take the project in time; no file was written = エンジンがプロジェクトを時間内に受け取れなかったため、ファイルは書き出されませんでした +the bounce has not finished = バウンスはまだ終わっていません +cannot bounce: there is no audio output = バウンスできません: オーディオ出力がありません diff --git a/crates/prowave-app/locales/lt.txt b/crates/prowave-app/locales/lt.txt index 997f3d94..d675b2a0 100644 --- a/crates/prowave-app/locales/lt.txt +++ b/crates/prowave-app/locales/lt.txt @@ -916,3 +916,6 @@ Not found = Nerasta In Use = Naudojami LADSPA scan = LADSPA paieška Vamp scan = Vamp paieška +the engine did not take the project in time; no file was written = variklis per nustatytą laiką neperėmė projekto; failas neįrašytas +the bounce has not finished = bounce dar nesibaigė +cannot bounce: there is no audio output = negalima atlikti bounce: nėra garso išvesties diff --git a/crates/prowave-app/locales/nb.txt b/crates/prowave-app/locales/nb.txt index e134ed73..1ee483a2 100644 --- a/crates/prowave-app/locales/nb.txt +++ b/crates/prowave-app/locales/nb.txt @@ -916,3 +916,6 @@ Not found = Ikke funnet In Use = I bruk LADSPA scan = LADSPA-skanning Vamp scan = Vamp-skanning +the engine did not take the project in time; no file was written = motoren tok ikke imot prosjektet i tide; ingen fil ble skrevet +the bounce has not finished = bounce er ikke ferdig +cannot bounce: there is no audio output = kan ikke bounce: ingen lydutgang diff --git a/crates/prowave-app/locales/pl.txt b/crates/prowave-app/locales/pl.txt index e67f0c12..b01b8b8e 100644 --- a/crates/prowave-app/locales/pl.txt +++ b/crates/prowave-app/locales/pl.txt @@ -916,3 +916,6 @@ Not found = Nie znaleziono In Use = W użyciu LADSPA scan = Skan LADSPA Vamp scan = Skan Vamp +the engine did not take the project in time; no file was written = silnik nie przyjął projektu na czas; nie zapisano żadnego pliku +the bounce has not finished = bounce nie został zakończony +cannot bounce: there is no audio output = nie można zrobić bounce: brak wyjścia audio diff --git a/crates/prowave-app/locales/pt-BR.txt b/crates/prowave-app/locales/pt-BR.txt index 09150ea3..a2d5b1c6 100644 --- a/crates/prowave-app/locales/pt-BR.txt +++ b/crates/prowave-app/locales/pt-BR.txt @@ -916,3 +916,6 @@ Not found = Não encontrado In Use = Em uso LADSPA scan = Verificação LADSPA Vamp scan = Verificação Vamp +the engine did not take the project in time; no file was written = o motor não recebeu o projeto a tempo; nenhum arquivo foi gravado +the bounce has not finished = o bounce ainda não terminou +cannot bounce: there is no audio output = não é possível fazer o bounce: não há saída de áudio diff --git a/crates/prowave-app/locales/pt-PT.txt b/crates/prowave-app/locales/pt-PT.txt index 8187331d..18cef6a2 100644 --- a/crates/prowave-app/locales/pt-PT.txt +++ b/crates/prowave-app/locales/pt-PT.txt @@ -916,3 +916,6 @@ Not found = Não encontrado In Use = Em utilização LADSPA scan = Análise LADSPA Vamp scan = Análise Vamp +the engine did not take the project in time; no file was written = o motor não recebeu o projeto a tempo; nenhum ficheiro foi gravado +the bounce has not finished = o bounce ainda não terminou +cannot bounce: there is no audio output = não é possível fazer o bounce: não há saída de áudio diff --git a/crates/prowave-app/locales/sv.txt b/crates/prowave-app/locales/sv.txt index c9328a51..6927b716 100644 --- a/crates/prowave-app/locales/sv.txt +++ b/crates/prowave-app/locales/sv.txt @@ -916,3 +916,6 @@ Not found = Hittades inte In Use = I bruk LADSPA scan = LADSPA-sökning Vamp scan = Vamp-sökning +the engine did not take the project in time; no file was written = motorn tog inte emot projektet i tid; ingen fil skrevs +the bounce has not finished = bounce är inte klar +cannot bounce: there is no audio output = kan inte bounca: ingen ljudutgång diff --git a/crates/prowave-app/locales/uk.txt b/crates/prowave-app/locales/uk.txt index 55beaf6a..38fb9036 100644 --- a/crates/prowave-app/locales/uk.txt +++ b/crates/prowave-app/locales/uk.txt @@ -916,3 +916,6 @@ Not found = Не знайдено In Use = Використовуються LADSPA scan = Сканування LADSPA Vamp scan = Сканування Vamp +the engine did not take the project in time; no file was written = рушій не прийняв проєкт вчасно; файл не записано +the bounce has not finished = Боунс ще не завершено +cannot bounce: there is no audio output = неможливо зробити боунс: немає аудіовиходу diff --git a/crates/prowave-app/locales/zh-Hans.txt b/crates/prowave-app/locales/zh-Hans.txt index 845f34d7..65afbc45 100644 --- a/crates/prowave-app/locales/zh-Hans.txt +++ b/crates/prowave-app/locales/zh-Hans.txt @@ -916,3 +916,6 @@ Not found = 未找到 In Use = 使用中 LADSPA scan = LADSPA 扫描 Vamp scan = Vamp 扫描 +the engine did not take the project in time; no file was written = 引擎未能及时接收工程;未写入任何文件 +the bounce has not finished = 导出尚未完成 +cannot bounce: there is no audio output = 无法导出:没有音频输出 diff --git a/crates/prowave-app/src/bounce.rs b/crates/prowave-app/src/bounce.rs index 20a178ba..3d9d4449 100644 --- a/crates/prowave-app/src/bounce.rs +++ b/crates/prowave-app/src/bounce.rs @@ -1,14 +1,20 @@ -//! File > Bounce > Project or Section…, Export > Track as Audio File… and Bounce In Place: plays -//! the song through the engine and writes what is heard into a WAV file. +//! File > Bounce > Project or Section…, Export > Track as Audio File…, Bounce In Place (Regions in +//! Place…) and Bounce and Join: writes what the engine plays into a WAV file. //! -//! The engine hands over its finished master frames (after every effect, send, automation lane -//! and the master fader, see `Command::SetCapture`), so the file is exactly the mix. A bounce -//! runs at playing speed: a four-minute song takes four minutes. +//! By default a bounce is **offline**, like Logic's Offline bounce: a copy of the project is played +//! through an engine that has no sound card (`prowave_engine::Engine::offline`), as fast as the +//! processor allows, on a background thread. The project and its transport are not touched while +//! it runs, and the file is the same mix the real-time path writes. A four-minute song takes a few +//! seconds, not four minutes. //! -//! A bounce of a track or a region is only worth placing if that track or region is still the -//! one that was bounced when it ends. The bounce keeps a copy of what it read, and checks it -//! against the project at the end: a region or track that was edited, moved, deleted or -//! reordered meanwhile is not replaced (or exported) with audio it does not match. +//! `PROWAVE_BOUNCE_REALTIME=1` brings back the real-time bounce: the live engine plays the song at +//! playing speed and hands its finished master frames over (`Command::SetCapture`) to a collector +//! thread, which writes them. It is the only path that needs the sound card. +//! +//! A bounce of a track or a region is only worth placing if that track or region is still the one +//! that was bounced when it ends. The bounce keeps a copy of what it read, and checks it against +//! the project at the end: a region or track that was edited, moved, deleted or reordered meanwhile +//! is not replaced (or exported) with audio it does not match. use prowave_engine::{write_flac, write_wav, CaptureSink, Command, Engine}; use rtrb::{Consumer, RingBuffer}; @@ -16,8 +22,10 @@ use std::path::{Path, PathBuf}; use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; use std::sync::Arc; use std::thread::{self, JoinHandle}; -use std::time::Duration; +use std::time::{Duration, Instant}; +use crate::engine_sync::EngineSync; +use crate::i18n::tr; use crate::model::{Control, Note, Project, Region, RegionParams, Track}; /// The engine's ring holds about 1.4 s at 48 kHz. A collector thread empties it every couple @@ -28,6 +36,15 @@ const RING_FRAMES: usize = 65_536; /// How long the collector sleeps when the ring is empty. const COLLECT_EVERY: Duration = Duration::from_millis(2); +/// Frames an offline bounce renders per call to the engine. +const RENDER_BLOCK: usize = 512; +/// How long an offline bounce waits for the engine to take every change before it gives up. +const SETTLE_LIMIT: Duration = Duration::from_secs(120); +/// How long to wait between two checks while the engine takes its changes. +const SETTLE_STEP: Duration = Duration::from_millis(1); +/// The sample rate of an offline bounce when there is no audio device to take one from. +pub const OFFLINE_RATE: u32 = 48_000; + /// The parts of a region that a bounce of it depends on. #[derive(Clone)] pub struct RegionContent { @@ -147,31 +164,21 @@ pub struct Finished { pub placeable: bool, } -/// A bounce in progress. -pub struct Bounce { - /// Gathers the engine's frames; returns them when stopped. - collector: Option>>, - stop: Arc, - /// Frames the engine's ring had no room for, shared with the engine. - dropped: Arc, - target: Target, - pub start_beat: f64, - pub end_beat: f64, - /// The playhead's place, the cycle, the metronome and the solos before the bounce, put - /// back when it ends. - was_at: f64, - was_cycle: bool, - was_metronome: bool, - /// Each track's name and solo state before a track bounce (empty for a project bounce). - was_solos: Vec<(String, bool)>, - path: PathBuf, - sample_rate: u32, +/// A bounce in progress: offline (the default) or real-time (`PROWAVE_BOUNCE_REALTIME=1`). +pub enum Bounce { + RealTime(RealTime), + Offline(Offline), +} + +/// Whether `PROWAVE_BOUNCE_REALTIME=1` asks for the real-time bounce. +fn realtime_requested() -> bool { + std::env::var_os("PROWAVE_BOUNCE_REALTIME").is_some_and(|v| v == "1") } impl Bounce { - /// Starts bouncing `start_beat` to `end_beat` into `path`, and plays from there. + /// Bounces `start_beat` to `end_beat` (the whole mix) into `path`. pub fn start( - engine: &mut Engine, + engine: Option<&mut Engine>, project: &mut Project, start_beat: f64, end_beat: f64, @@ -191,7 +198,7 @@ impl Bounce { /// Bounces one track: the other tracks are soloed off for the bounce, so only this track — /// with its effects, sends and their returns — reaches the master. pub fn start_track( - engine: &mut Engine, + engine: Option<&mut Engine>, project: &mut Project, track: usize, start_beat: f64, @@ -213,7 +220,7 @@ impl Bounce { /// Bounces `regions` of `track` over their span, soloing the track. The regions are only /// replaced when they are still the ones bounced (see [`Finished::placeable`]). pub fn start_regions( - engine: &mut Engine, + engine: Option<&mut Engine>, project: &mut Project, track: usize, regions: &[usize], @@ -233,6 +240,326 @@ impl Bounce { ) } + /// The offline bounce needs no device: `engine` only gives its sample rate when there is one. + /// The real-time bounce needs the engine. + fn begin( + engine: Option<&mut Engine>, + project: &mut Project, + start_beat: f64, + end_beat: f64, + path: PathBuf, + target: Target, + solo: Option, + ) -> Result { + if realtime_requested() { + let engine = + engine.ok_or_else(|| tr("cannot bounce: there is no audio output").to_string())?; + return RealTime::begin(engine, project, start_beat, end_beat, path, target, solo) + .map(Self::RealTime); + } + let sample_rate = engine.map_or(OFFLINE_RATE, |e| e.sample_rate()); + Offline::begin( + sample_rate, + project, + start_beat, + end_beat, + path, + target, + solo, + ) + .map(Self::Offline) + } + + /// Whether this is the real-time bounce (the song plays through the sound card). + pub fn is_realtime(&self) -> bool { + matches!(self, Self::RealTime(_)) + } + + /// Works the bounce on, once a frame. Returns whether it still runs. + pub fn advance(&mut self, project: &Project) -> bool { + match self { + Self::RealTime(running) => running.poll(project), + Self::Offline(running) => running.advance(project), + } + } + + /// The share of the bounce done, 0 to 1. + pub fn progress(&self, project: &Project) -> f32 { + match self { + Self::RealTime(running) => running.progress(project), + Self::Offline(running) => running.progress(), + } + } + + /// The beat the bounce ends at. + pub fn end_beat(&self) -> f64 { + match self { + Self::RealTime(running) => running.end_beat, + Self::Offline(running) => running.end_beat, + } + } + + /// Stops the bounce early. A real-time bounce stops the transport; an offline one stops + /// rendering at its next block. Either way [`Bounce::finish`] reports it cancelled. + pub fn cancel(&mut self, project: &mut Project) { + match self { + Self::RealTime(_) => project.playing = false, + Self::Offline(running) => running.cancel.store(true, Ordering::Release), + } + } + + /// Ends a bounce that [`Bounce::advance`] reported finished. `Ok(None)`: it was cancelled. + /// `reached_end` is for the real-time bounce (the transport got to the end beat). + pub fn finish( + self, + engine: Option<&mut Engine>, + project: &mut Project, + reached_end: bool, + ) -> Result, String> { + match self { + Self::RealTime(running) => { + let engine = engine + .ok_or_else(|| tr("cannot bounce: there is no audio output").to_string())?; + running.finish(engine, project, reached_end) + } + Self::Offline(running) => running.finish(), + } + } +} + +/// An offline bounce. The project is copied when the bounce starts; a thread plays the copy through +/// an engine with no sound card and returns its frames, then a second thread writes them to `path`. +/// The project's own transport and solos are never touched. +pub struct Offline { + cancel: Arc, + /// Frames rendered so far, for the progress; the bounce is `total` frames long. + rendered: Arc, + total: u64, + target: Target, + pub end_beat: f64, + path: PathBuf, + sample_rate: u32, + placeable: bool, + stage: Stage, +} + +/// Where an offline bounce is: rendering its frames, writing them, or done. +enum Stage { + Rendering(JoinHandle>, String>>), + Writing(JoinHandle>), + Done(Result, String>), +} + +impl Offline { + fn begin( + sample_rate: u32, + project: &Project, + start_beat: f64, + end_beat: f64, + path: PathBuf, + target: Target, + solo: Option, + ) -> Result { + let mut copy = project.clone(); + // The copy plays once through from the start: no cycle, no metronome, no count-in. + copy.cycle = false; + copy.metronome = false; + copy.recording = false; + copy.counting_in = false; + copy.playing = false; + copy.position_beats = start_beat; + if let Some(track) = solo { + solo_only(&mut copy.tracks, track); + } + let total = frames_between(©, start_beat, end_beat, sample_rate); + let cancel = Arc::new(AtomicBool::new(false)); + let rendered = Arc::new(AtomicU64::new(0)); + let thread = { + let cancel = Arc::clone(&cancel); + let rendered = Arc::clone(&rendered); + thread::Builder::new() + .name("prowave-offline-bounce".into()) + .spawn(move || render(copy, sample_rate, total, &rendered, &cancel)) + .map_err(|e| format!("cannot start the bounce: {e}"))? + }; + Ok(Self { + cancel, + rendered, + total, + target, + end_beat, + path, + sample_rate, + placeable: false, + stage: Stage::Rendering(thread), + }) + } + + /// Moves the bounce on: starts the file write when the frames are ready, and checks the + /// target at that moment. Returns whether it still runs. + fn advance(&mut self, project: &Project) -> bool { + let stage = std::mem::replace(&mut self.stage, Stage::Done(Ok(None))); + self.stage = match stage { + Stage::Rendering(thread) if !thread.is_finished() => Stage::Rendering(thread), + Stage::Rendering(thread) => match thread.join() { + Ok(Ok(Some(samples))) => { + self.placeable = self.target.still_there(project); + if matches!(self.target, Target::Track { .. }) && !self.placeable { + Stage::Done(Err( + "the track changed during the bounce, so no file was written; bounce again" + .to_string(), + )) + } else { + let path = self.path.clone(); + let rate = self.sample_rate; + match thread::Builder::new() + .name("prowave-bounce-write".into()) + .spawn(move || write_wav(&path, &samples, rate)) + { + Ok(writer) => Stage::Writing(writer), + Err(e) => Stage::Done(Err(format!("cannot write the bounce: {e}"))), + } + } + } + Ok(Ok(None)) => Stage::Done(Ok(None)), + Ok(Err(e)) => Stage::Done(Err(e)), + Err(_) => Stage::Done(Err("the bounce stopped unexpectedly".to_string())), + }, + Stage::Writing(thread) if !thread.is_finished() => Stage::Writing(thread), + Stage::Writing(thread) => Stage::Done(match thread.join() { + Ok(Ok(())) => Ok(Some(Finished { + path: self.path.clone(), + placeable: self.placeable, + })), + Ok(Err(e)) => Err(format!("{}: {e}", self.path.display())), + Err(_) => Err("the bounce stopped unexpectedly".to_string()), + }), + done @ Stage::Done(_) => done, + }; + matches!(self.stage, Stage::Rendering(_) | Stage::Writing(_)) + } + + fn progress(&self) -> f32 { + match &self.stage { + Stage::Rendering(_) if self.total > 0 => (self.rendered.load(Ordering::Relaxed) as f64 + / self.total as f64) + .clamp(0.0, 1.0) as f32, + Stage::Rendering(_) => 0.0, + Stage::Writing(_) | Stage::Done(_) => 1.0, + } + } + + fn finish(mut self) -> Result, String> { + match std::mem::replace(&mut self.stage, Stage::Done(Ok(None))) { + Stage::Done(result) => result, + _ => Err(tr("the bounce has not finished").to_string()), + } + } +} + +impl Drop for Offline { + /// A bounce dropped while it renders stops at its next block; its thread is not waited for. + fn drop(&mut self) { + self.cancel.store(true, Ordering::Release); + } +} + +/// How many frames the bounce from `start_beat` to `end_beat` is at `sample_rate`, by the tempo map +/// of `project`. +fn frames_between(project: &Project, start_beat: f64, end_beat: f64, sample_rate: u32) -> u64 { + let tempo = project.tempo_map(); + let seconds = tempo.seconds_at(end_beat) - tempo.seconds_at(start_beat); + (seconds * f64::from(sample_rate)).round().max(0.0) as u64 +} + +/// Renders `project` (a bounce's copy, its transport at the start) for `total` frames and returns +/// the interleaved stereo frames, or `None` when `cancel` was set. Runs on the bounce's own thread. +fn render( + mut project: Project, + sample_rate: u32, + total: u64, + rendered: &AtomicU64, + cancel: &AtomicBool, +) -> Result>, String> { + let engine = Engine::offline(sample_rate).map_err(|e| e.to_string())?; + let mut sync = EngineSync::new(engine, &project); + let mut block = vec![0f32; RENDER_BLOCK * 2]; + // Everything the engine needs is applied while the transport stands still. + if !settle(&mut sync, &mut project, &mut block, cancel)? { + return Ok(None); + } + project.playing = true; + if !settle(&mut sync, &mut project, &mut block, cancel)? { + return Ok(None); + } + // Grown as the frames come: reserving the whole bounce up front would cost a long song + // its full size before the first frame. + let mut samples = Vec::new(); + let mut done = 0u64; + while done < total { + if cancel.load(Ordering::Acquire) { + return Ok(None); + } + let frames = RENDER_BLOCK.min((total - done) as usize); + let out = &mut block[..frames * 2]; + sync.engine.render_offline(out).map_err(|e| e.to_string())?; + samples.extend_from_slice(out); + done += frames as u64; + rendered.store(done, Ordering::Relaxed); + } + Ok(Some(samples)) +} + +/// Sends every change of `project` the engine has not taken yet. The engine takes its queue only +/// while it renders, so the blocks made meanwhile are thrown away (the transport is stopped, so no +/// time passes in them). `Ok(false)`: cancelled. +fn settle( + sync: &mut EngineSync, + project: &mut Project, + block: &mut [f32], + cancel: &AtomicBool, +) -> Result { + let limit = Instant::now() + SETTLE_LIMIT; + while !sync.settle(project) { + if cancel.load(Ordering::Acquire) { + return Ok(false); + } + if Instant::now() >= limit { + return Err( + tr("the engine did not take the project in time; no file was written").to_string(), + ); + } + sync.engine + .render_offline(block) + .map_err(|e| e.to_string())?; + thread::sleep(SETTLE_STEP); + } + Ok(true) +} + +/// The real-time bounce: the song plays through the sound card, and the engine hands over what +/// is heard (`Command::SetCapture`). +pub struct RealTime { + /// Gathers the engine's frames; returns them when stopped. + collector: Option>>, + stop: Arc, + /// Frames the engine's ring had no room for, shared with the engine. + dropped: Arc, + target: Target, + pub start_beat: f64, + pub end_beat: f64, + /// The playhead's place, the cycle, the metronome and the solos before the bounce, put + /// back when it ends. + was_at: f64, + was_cycle: bool, + was_metronome: bool, + /// Each track's name and solo state before a track bounce (empty for a project bounce). + was_solos: Vec<(String, bool)>, + path: PathBuf, + sample_rate: u32, +} + +impl RealTime { fn begin( engine: &mut Engine, project: &mut Project, @@ -321,7 +648,7 @@ impl Bounce { /// /// Errors (no file is written): the engine did not take the stop command, the capture ring /// lost frames, or the track being bounced changed while it ran. - pub fn finish( + fn finish( mut self, engine: &mut Engine, project: &mut Project, @@ -367,7 +694,7 @@ impl Bounce { } } -impl Drop for Bounce { +impl Drop for RealTime { /// A bounce that is dropped without `finish` still stops its collector thread. fn drop(&mut self) { self.stop.store(true, Ordering::Release); @@ -450,8 +777,8 @@ mod tests { use crate::model::TrackKind; /// A bounce with no engine behind it: its state maths is what the tests check. - fn bounced(start_beat: f64, end_beat: f64) -> Bounce { - Bounce { + fn bounced(start_beat: f64, end_beat: f64) -> RealTime { + RealTime { collector: None, stop: Arc::new(AtomicBool::new(false)), dropped: Arc::new(AtomicU64::new(0)), @@ -692,4 +1019,137 @@ mod tests { assert_eq!(samples[2 * 19_999], 19_999.0); assert_eq!(samples[2 * 19_999 + 1], -19_999.0); } + + /// Renders `p` from beat 0 to `end_beat` offline, as a bounce does, and returns its frames. + fn render_of(p: &Project, end_beat: f64) -> Vec { + let total = frames_between(p, 0.0, end_beat, OFFLINE_RATE); + let copy = p.clone(); + let cancel = AtomicBool::new(false); + let rendered = AtomicU64::new(0); + render(copy, OFFLINE_RATE, total, &rendered, &cancel) + .expect("the render works") + .expect("it was not cancelled") + } + + /// A project with one region of an A4 note at its start. + fn one_note_project() -> Project { + project_with(vec![region("Lead", 1.0, vec![note(69)])]) + } + + #[test] + fn two_bars_at_the_default_tempo_are_four_seconds_of_frames() { + let p = one_note_project(); + assert_eq!( + frames_between(&p, 0.0, 8.0, 48_000), + 192_000, + "8 beats at 120 BPM" + ); + assert_eq!(frames_between(&p, 4.0, 4.0, 48_000), 0, "an empty span"); + } + + #[test] + fn an_offline_render_plays_the_notes_and_repeats_bit_for_bit() { + let p = one_note_project(); + let a = render_of(&p, 2.0); + let b = render_of(&p, 2.0); + assert_eq!( + a.len(), + frames_between(&p, 0.0, 2.0, OFFLINE_RATE) as usize * 2 + ); + assert!(a.iter().any(|s| s.abs() > 1e-3), "the note is heard"); + assert!( + a.iter().zip(&b).all(|(x, y)| x.to_bits() == y.to_bits()), + "two offline renders are identical" + ); + } + + #[test] + fn a_cancelled_offline_render_gives_no_frames() { + let p = one_note_project(); + let total = frames_between(&p, 0.0, 2.0, OFFLINE_RATE); + let cancel = AtomicBool::new(true); + let rendered = AtomicU64::new(0); + let out = render(p.clone(), OFFLINE_RATE, total, &rendered, &cancel); + assert!(matches!(out, Ok(None)), "cancelled before any frame"); + assert_eq!(rendered.load(Ordering::Relaxed), 0); + } + + #[test] + fn an_offline_bounce_writes_its_span_and_leaves_the_project_alone() { + let mut p = one_note_project(); + p.position_beats = 0.5; + p.cycle = true; + p.metronome = true; + let before = (p.playing, p.position_beats, p.cycle, p.metronome); + let dir = + std::env::temp_dir().join(format!("prowave-offline-bounce-{}", std::process::id())); + std::fs::create_dir_all(&dir).expect("a folder for the test"); + let path = dir.join("bounce.wav"); + + let mut running = Bounce::start(None, &mut p, 0.0, 2.0, path.clone()).expect("it starts"); + assert!(!running.is_realtime(), "offline by default"); + assert_eq!( + (p.playing, p.position_beats, p.cycle, p.metronome), + before, + "the transport is not touched" + ); + let mut polls = 0u32; + while running.advance(&p) { + polls += 1; + assert!(polls < 10_000, "the bounce ends"); + std::thread::sleep(Duration::from_millis(2)); + } + let done = running + .finish(None, &mut p, true) + .expect("it finishes") + .expect("it was not cancelled"); + assert_eq!(done.path, path); + assert!(done.placeable, "the whole project is what was bounced"); + let frames = frames_between(&p, 0.0, 2.0, OFFLINE_RATE); + let len = std::fs::metadata(&path).expect("the file exists").len(); + assert_eq!( + len, + 44 + frames * 8, + "a 32-bit float stereo WAV of the span" + ); + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn an_offline_track_bounce_solos_nothing_in_the_project() { + let mut p = one_note_project(); + p.add_track(TrackKind::Instrument); + p.tracks[1].solo = true; + let dir = std::env::temp_dir().join(format!("prowave-offline-solo-{}", std::process::id())); + std::fs::create_dir_all(&dir).expect("a folder for the test"); + let running = + Bounce::start_track(None, &mut p, 0, 0.0, 2.0, dir.join("solo.wav")).expect("starts"); + let solos: Vec = p.tracks.iter().map(|t| t.solo).collect(); + assert_eq!(solos, [false, true], "the track is soloed only in the copy"); + drop(running); + let _ = std::fs::remove_dir_all(&dir); + } + + /// How much faster than real time an offline bounce of the demo song renders. Run with + /// `cargo test --release -p prowave-app offline_speed -- --ignored --nocapture`. + #[test] + #[ignore] + fn offline_speed() { + let p = Project::demo(); + let end = p + .tracks + .iter() + .flat_map(|t| t.regions.iter()) + .map(|r| p.region_end_beats(r)) + .fold(0.0, f64::max); + let secs = p.tempo_map().seconds_at(end); + let started = Instant::now(); + let frames = render_of(&p, end); + let took = started.elapsed().as_secs_f64(); + println!( + "offline: {secs:.1} s of song in {took:.2} s = {:.1}x real time ({} frames)", + secs / took, + frames.len() / 2 + ); + } } diff --git a/crates/prowave-app/src/engine_sync.rs b/crates/prowave-app/src/engine_sync.rs index 299f9f1d..def3eda4 100644 --- a/crates/prowave-app/src/engine_sync.rs +++ b/crates/prowave-app/src/engine_sync.rs @@ -654,6 +654,14 @@ impl EngineSync { sync } + /// Sends every change of `p` the engine has not accepted yet. Returns `false` while some + /// are still waiting: a full command queue, or a Space Designer response still being made. + /// Offline, the caller renders blocks between calls (which takes the queue) and tries again. + pub fn settle(&mut self, p: &mut Project) -> bool { + self.sync(p); + !self.retry + } + /// Call once per frame: push UI-side changes to the engine, then pull the playhead back. pub fn sync(&mut self, p: &mut Project) { let counted = !self.playing && p.playing && p.recording && p.count_in; diff --git a/crates/prowave-app/src/hosted_plugins.rs b/crates/prowave-app/src/hosted_plugins.rs index 47642881..7eff875f 100644 --- a/crates/prowave-app/src/hosted_plugins.rs +++ b/crates/prowave-app/src/hosted_plugins.rs @@ -180,6 +180,10 @@ impl BlockEffect for Hosted { fn boxed_clone(&self) -> Option> { Some(Box::new(Hosted(self.0.clone()))) } + + fn set_offline(&mut self, offline: bool) { + self.0.set_offline(offline); + } } /// Puts `info` in the rack, with the state a project file had for it, and returns its number diff --git a/crates/prowave-app/src/main.rs b/crates/prowave-app/src/main.rs index d1b710a0..06939193 100644 --- a/crates/prowave-app/src/main.rs +++ b/crates/prowave-app/src/main.rs @@ -683,24 +683,27 @@ impl App { } else { path }; - let Some(sync) = self.sync.as_mut() else { - self.ui.status = Some("cannot bounce: there is no audio output".to_string()); - return; - }; - match bounce::Bounce::start(&mut sync.engine, &mut self.project, start, end, path) { - Ok(running) => { - self.bounce = Some(running); - self.region_bounce = None; - // Send the seek and Play in this same frame, so the engine starts capturing - // exactly when playback starts (no silent lead-in in the file). - if let Some(sync) = self.sync.as_mut() { - sync.sync(&mut self.project); - } - } + let engine = self.sync.as_mut().map(|s| &mut s.engine); + match bounce::Bounce::start(engine, &mut self.project, start, end, path) { + Ok(running) => self.begun_bounce(running, None), Err(e) => self.ui.status = Some(e), } } + /// Keeps a bounce that has just started. A real-time bounce sends its seek and Play in this + /// same frame, so the engine starts capturing exactly when playback starts (no silent lead-in + /// in the file). An offline bounce has nothing to send: it works on a copy of the project. + fn begun_bounce(&mut self, running: bounce::Bounce, placed: Option<(usize, Vec)>) { + let realtime = running.is_realtime(); + self.bounce = Some(running); + self.region_bounce = placed; + if realtime { + if let Some(sync) = self.sync.as_mut() { + sync.sync(&mut self.project); + } + } + } + /// File > Import > Other Projects…: the audio files of a GarageBand bundle become tracks /// (see `garageband`; the arrangement inside the project is not read yet). fn import_band(&mut self, ctx: &egui::Context) { @@ -751,26 +754,9 @@ impl App { else { return; }; - let Some(sync) = self.sync.as_mut() else { - self.ui.status = Some("cannot bounce: there is no audio output".to_string()); - return; - }; - match bounce::Bounce::start_track( - &mut sync.engine, - &mut self.project, - track, - 0.0, - end, - path, - ) { - Ok(running) => { - self.bounce = Some(running); - self.region_bounce = None; - // Seek and Play in this same frame, so the capture starts with the sound. - if let Some(sync) = self.sync.as_mut() { - sync.sync(&mut self.project); - } - } + let engine = self.sync.as_mut().map(|s| &mut s.engine); + match bounce::Bounce::start_track(engine, &mut self.project, track, 0.0, end, path) { + Ok(running) => self.begun_bounce(running, None), Err(e) => self.ui.status = Some(e), } } @@ -819,12 +805,9 @@ impl App { return; } let path = bounce::free_path(&dir, &format!("{} {start:.3}", file_name(&name))); - let Some(sync) = self.sync.as_mut() else { - self.ui.status = Some("cannot bounce: there is no audio output".to_string()); - return; - }; + let engine = self.sync.as_mut().map(|s| &mut s.engine); match bounce::Bounce::start_regions( - &mut sync.engine, + engine, &mut self.project, track, ®ions, @@ -832,14 +815,7 @@ impl App { end, path, ) { - Ok(running) => { - self.bounce = Some(running); - self.region_bounce = Some((track, regions)); - // Seek and Play in this same frame, so the capture starts with the sound. - if let Some(sync) = self.sync.as_mut() { - sync.sync(&mut self.project); - } - } + Ok(running) => self.begun_bounce(running, Some((track, regions))), Err(e) => self.ui.status = Some(e), } } @@ -902,22 +878,23 @@ impl App { return; }; self.ui.bouncing = true; - if running.poll(&self.project) { + if ctx.input(|i| i.key_pressed(egui::Key::Escape)) { + running.cancel(&mut self.project); + } + if running.advance(&self.project) { let percent = (running.progress(&self.project) * 100.0).round(); self.ui.status = Some(i18n::trf("Bouncing {}%", &[&format!("{percent:.0}")])); ctx.request_repaint(); return; } - let reached_end = self.project.playing && self.project.position_beats >= running.end_beat; + let reached_end = self.project.playing && self.project.position_beats >= running.end_beat(); let Some(running) = self.bounce.take() else { self.ui.bouncing = false; return; }; self.ui.bouncing = false; - let result = match self.sync.as_mut() { - Some(sync) => running.finish(&mut sync.engine, &mut self.project, reached_end), - None => Ok(None), - }; + let engine = self.sync.as_mut().map(|s| &mut s.engine); + let result = running.finish(engine, &mut self.project, reached_end); let placed = self.region_bounce.take(); match result { Ok(Some(done)) => { diff --git a/crates/prowave-engine/src/core.rs b/crates/prowave-engine/src/core.rs index 1ab544cc..c4ee0d25 100644 --- a/crates/prowave-engine/src/core.rs +++ b/crates/prowave-engine/src/core.rs @@ -18,6 +18,7 @@ use crate::triple::{triple_buffer, Reader, Writer}; use rtrb::{Consumer, Producer}; use std::sync::atomic::{AtomicU32, AtomicU64, Ordering}; use std::sync::Arc; +use std::time::Duration; /// Tracks the engine mixes (Logic: 1000 tracks per project). pub const MAX_TRACKS: usize = 1024; @@ -170,8 +171,17 @@ pub struct AudioClip { /// Next clip-relative frame to play (negative = before the region starts). pos: i64, underruns: u32, + /// An offline render waited out its whole budget for this clip's disk thread once (the + /// file cannot be read); from then on the clip only counts underruns, without waiting. + gave_up: bool, } +/// How long an offline render waits for the disk thread to deliver one frame of a clip: +/// [`OFFLINE_DISK_STEPS`] sleeps of [`OFFLINE_DISK_STEP`], about half a minute. A live engine +/// never waits; it plays silence instead. +const OFFLINE_DISK_STEPS: u32 = 150_000; +const OFFLINE_DISK_STEP: Duration = Duration::from_micros(200); + /// Non-destructive region edits (Logic Pro: Region Inspector Gain, Fade In/Out, Reverse). #[derive(Clone, Copy, Debug, PartialEq)] pub struct ClipEdit { @@ -251,6 +261,7 @@ impl AudioClip { cur: None, pos: 0, underruns: 0, + gave_up: false, } } @@ -274,13 +285,17 @@ impl AudioClip { } } - fn tick(&mut self) -> Option<(f32, f32)> { + /// The clip's frame at the playhead. When the disk thread has not caught up, a live engine + /// counts an underrun and plays silence; with `wait` (offline rendering, which is not in + /// real time) it waits for the block instead. + fn tick(&mut self, wait: bool) -> Option<(f32, f32)> { let p = self.pos; self.pos += 1; if p < 0 || p as u64 >= self.len_frames { return None; } let p = p as u64; + let mut waited = 0u32; loop { if let Some(b) = &self.cur { if b.gen == self.gen { @@ -298,6 +313,16 @@ impl AudioClip { Ok(b) if b.gen == self.gen => self.cur = Some(b), Ok(_) => {} Err(_) => { + // A producer that is gone (the file did not open) never delivers again. + let may_wait = wait && !self.gave_up && !self.rx.is_abandoned(); + if may_wait { + if waited < OFFLINE_DISK_STEPS { + waited += 1; + std::thread::sleep(OFFLINE_DISK_STEP); + continue; + } + self.gave_up = true; + } self.underruns += 1; return None; } @@ -806,6 +831,9 @@ pub struct EngineCore { input: Option>, /// Where the finished master frames go while a bounce is running. capture: Option, + /// Offline rendering: not in real time, so clips and plug-ins wait for their data (see + /// [`EngineCore::set_offline`]). + offline: bool, monitors: [MonitorTrack; MAX_MONITORS], monitor_count: usize, track_gain_l: Vec, @@ -962,6 +990,7 @@ impl EngineCore { count_step: 1, input: None, capture: None, + offline: false, monitors: [MonitorTrack::default(); MAX_MONITORS], monitor_count: 0, track_gain_l: vec![1.0; MAX_TRACKS], @@ -1017,6 +1046,20 @@ impl EngineCore { } } + /// Offline rendering: the core is driven faster than real time, not by a sound card. A + /// streamed region then waits for its disk thread instead of playing silence, and a plug-in + /// in its own process waits for every block instead of letting a late one pass dry. Set it + /// before the first block; chains installed later get it too. + pub fn set_offline(&mut self, offline: bool) { + self.offline = offline; + if let Some(chain) = self.master_chain.as_mut() { + chain.set_offline(offline); + } + for chain in self.chains.iter_mut().flatten() { + chain.set_offline(offline); + } + } + /// The UI's half of the state this core publishes after every block. There is one; /// it is `None` once taken. pub fn take_state_reader(&mut self) -> Option { @@ -1732,9 +1775,10 @@ impl EngineCore { player.set_piano_params(params); } } - Command::SetInserts { track, chain } => { + Command::SetInserts { mut chain, track } => { let t = track as usize; if t < MAX_TRACKS { + chain.set_offline(self.offline); let old = self.chains[t].replace(chain); if let Some(old) = old { let _ = self.trash.push(Garbage::Chain(old)); @@ -1756,7 +1800,8 @@ impl EngineCore { let _ = self.trash.push(Garbage::Pdc(pdc)); } } - Command::SetMasterInserts(chain) => { + Command::SetMasterInserts(mut chain) => { + chain.set_offline(self.offline); if let Some(old) = self.master_chain.replace(chain) { let _ = self.trash.push(Garbage::Chain(old)); } @@ -2135,7 +2180,7 @@ impl EngineCore { self.send_control(c); } for c in self.song.clips.iter_mut() { - if let Some((cl, cr)) = c.tick() { + if let Some((cl, cr)) = c.tick(self.offline) { let t = (c.track as usize).min(MAX_TRACKS - 1); if self.track_audible[t] { let edit_gain = c.envelope(sample_beat, c.end_beat); diff --git a/crates/prowave-engine/src/fx.rs b/crates/prowave-engine/src/fx.rs index e54ee27a..d4d680d7 100644 --- a/crates/prowave-engine/src/fx.rs +++ b/crates/prowave-engine/src/fx.rs @@ -1255,6 +1255,13 @@ impl Fx { } } + /// Passes offline rendering on to a hosted plug-in (see [`BlockEffect::set_offline`]). + pub fn set_offline(&mut self, offline: bool) { + if let State::Plugin(s) = &mut self.state { + s.set_offline(offline); + } + } + /// Whether this is a [`FxKind::Plugin`] effect with its plug-in loaded. pub fn has_plugin(&self) -> bool { matches!(&self.state, State::Plugin(s) if s.has_plugin()) @@ -1806,6 +1813,13 @@ impl Chain { Self { fx } } + /// Offline rendering on or off for every hosted plug-in in the chain. + pub fn set_offline(&mut self, offline: bool) { + for f in self.fx.iter_mut() { + f.set_offline(offline); + } + } + #[inline] pub fn process(&mut self, mut l: f32, mut r: f32) -> (f32, f32) { for f in self.fx.iter_mut() { diff --git a/crates/prowave-engine/src/output.rs b/crates/prowave-engine/src/output.rs index 9a165524..6f438708 100644 --- a/crates/prowave-engine/src/output.rs +++ b/crates/prowave-engine/src/output.rs @@ -249,6 +249,8 @@ enum Output { /// Windows: our own WASAPI stream with the smallest period the audio engine allows. #[cfg(windows)] Wasapi(#[allow(dead_code)] crate::wasapi::LowLatencyStream), + /// No device: the engine is driven by [`Engine::render_offline`]. + Offline, } /// UI-thread handle. Not `Send` on some platforms (cpal `Stream`); keep it on the UI thread. @@ -267,6 +269,8 @@ pub struct Engine { buffer_frames: Option, _output: Output, disk: DiskThread, + /// The core of an offline engine (see [`Engine::offline`]), which nothing else runs. + offline: Option>, } /// Renders the engine into a device buffer of any sample format and channel count. Lives on @@ -397,6 +401,55 @@ impl Engine { Err(last) } + /// An engine with no sound card, for offline rendering: [`Engine::render_offline`] makes + /// its audio as fast as the processor allows, with the same commands, streams and readers as + /// a device engine. Nothing plays. It can be made on any thread, and needs no device. + pub fn offline(sample_rate: u32) -> Result { + let (tx, rx) = RingBuffer::::new(1024); + let (gtx, grx) = RingBuffer::::new(GARBAGE_CAPACITY); + let shared = Arc::new(Shared::new()); + let mut core = EngineCore::new(sample_rate, rx, gtx, shared.clone()); + core.set_offline(true); + let readers = core.take_readers(); + let state = readers + .state + .ok_or_else(|| EngineError::Backend("no state reader".into()))?; + Ok(Self { + commands: CommandQueue { + tx, + garbage: grx, + credits: GARBAGE_CAPACITY, + }, + shared, + state, + midi_out: readers.midi, + mtc_out: readers.mtc, + clock_out: readers.clock, + sample_rate, + device_name: "offline".to_string(), + device_id: None, + buffer_frames: None, + _output: Output::Offline, + disk: DiskThread::spawn(), + offline: Some(Box::new(core)), + }) + } + + /// Makes the next `out.len() / 2` frames of stereo audio on an [`Engine::offline`] engine + /// (interleaved, left then right), with every command sent so far applied. Not in real time: + /// the frames are as fast as the processor makes them, and a streamed region or a plug-in + /// that runs in its own process waits for its data rather than letting silence through. + /// Errors on an engine that plays on a device. + pub fn render_offline(&mut self, out: &mut [f32]) -> Result<(), EngineError> { + let core = self + .offline + .as_mut() + .ok_or_else(|| EngineError::Backend("this engine plays on a device".into()))?; + core.set_device_info((out.len() / 2) as u32, 0); + assert_no_alloc::assert_no_alloc(|| core.process(out)); + Ok(()) + } + /// Starts on the ASIO host (Windows builds with the `asio` feature only). /// Use this to avoid shared-mode WASAPI buffering when a native ASIO driver is available. #[cfg(all(windows, feature = "asio"))] @@ -448,6 +501,7 @@ impl Engine { buffer_frames: Some(info.period_frames), _output: Output::Wasapi(stream), disk: DiskThread::spawn(), + offline: None, }) } @@ -560,6 +614,7 @@ impl Engine { buffer_frames, _output: Output::Cpal(stream), disk: DiskThread::spawn(), + offline: None, }) } @@ -708,3 +763,249 @@ where ) .map_err(|e| EngineError::Backend(e.to_string())) } + +#[cfg(test)] +mod offline_tests { + use super::*; + use crate::core::{ + AudioClip, CaptureSink, ClipEdit, EngineCore, NoteEvent, Shared, Song, TrackMix, + }; + use crate::fx::{Chain, Fx, FxKind, MAX_FX_PARAMS}; + use crate::plugin::{BlockEffect, PLUGIN_BLOCK}; + use std::path::PathBuf; + use std::sync::atomic::AtomicBool; + + /// Frames of stereo audio rendered per call in these tests. + const BLOCK: usize = 512; + + fn render(engine: &mut Engine, frames: usize) -> Vec { + let mut out = vec![0f32; frames * 2]; + for block in out.chunks_mut(BLOCK * 2) { + engine + .render_offline(block) + .unwrap_or_else(|e| panic!("an offline engine renders: {e}")); + } + out + } + + /// Plays `commands` on a new offline engine at `sample_rate` and renders `frames`. + fn run(sample_rate: u32, commands: Vec, frames: usize) -> (Vec, Engine) { + let mut engine = + Engine::offline(sample_rate).unwrap_or_else(|e| panic!("offline engine: {e}")); + for c in commands { + assert!(engine.send(c), "the command queue takes the commands"); + } + let out = render(&mut engine, frames); + (out, engine) + } + + /// The commands that make a song from `notes` play from the start. + fn song_play(notes: Vec, clips: Vec) -> Vec { + vec![ + Command::SetTempoMap(Box::default()), + Command::SetSong(Box::new( + Song::new(notes, vec![TrackMix::default()]).with_clips(clips), + )), + Command::SetPosition { beat: 0.0 }, + Command::Play, + ] + } + + fn note(start: f64, len: f64, pitch: u8) -> NoteEvent { + NoteEvent { + start_beat: start, + end_beat: start + len, + pitch, + vel: 100, + track: 0, + } + } + + fn temp_wav(name: &str, sample_rate: u32, frames: usize, f: impl Fn(usize) -> f32) -> PathBuf { + let stereo: Vec = (0..frames) + .flat_map(|n| { + let s = f(n); + [s, s] + }) + .collect(); + let path = + std::env::temp_dir().join(format!("prowave-offline-{}-{name}.wav", std::process::id())); + crate::write_wav(&path, &stereo, sample_rate) + .unwrap_or_else(|e| panic!("write the test WAV: {e}")); + path + } + + #[test] + fn an_empty_song_renders_silence() { + let (out, _engine) = run(48_000, song_play(Vec::new(), Vec::new()), 9_600); + assert_eq!(out.len(), 9_600 * 2); + assert!(out.iter().all(|s| *s == 0.0), "nothing plays"); + } + + #[test] + fn a_note_renders_sound() { + let (out, _engine) = run( + 48_000, + song_play(vec![note(0.0, 4.0, 69)], Vec::new()), + 24_000, + ); + let peak = out.iter().fold(0f32, |m, s| m.max(s.abs())); + assert!(peak > 0.01, "an A4 for two beats is heard (peak {peak})"); + assert!(out.iter().all(|s| s.is_finite())); + } + + #[test] + fn the_same_commands_render_the_same_frames() { + let notes = || vec![note(0.0, 2.0, 60), note(1.0, 2.0, 64), note(2.5, 1.0, 67)]; + let (a, _) = run(48_000, song_play(notes(), Vec::new()), 48_000); + let (b, _) = run(48_000, song_play(notes(), Vec::new()), 48_000); + assert!(a.iter().any(|s| *s != 0.0)); + assert!( + a.iter().zip(&b).all(|(x, y)| x.to_bits() == y.to_bits()), + "two offline renders are bit-identical" + ); + } + + #[test] + fn a_streamed_region_comes_out_as_its_file_without_underruns() { + // One second of a 440 Hz sine at the engine's rate, through the disk thread. + let frames = 48_000; + let path = temp_wav("same-rate", 48_000, frames, |n| { + 0.5 * (std::f32::consts::TAU * 440.0 * n as f32 / 48_000.0).sin() + }); + let file = AudioFile::open(&path).unwrap_or_else(|e| panic!("open the test WAV: {e:?}")); + let mut engine = Engine::offline(48_000).unwrap_or_else(|e| panic!("offline engine: {e}")); + let clip = engine.stream_clip_in(&file, 0, 0.0, ClipEdit::default(), 1); + for c in song_play(Vec::new(), vec![clip]) { + assert!(engine.send(c)); + } + let out = render(&mut engine, frames); + let _ = std::fs::remove_file(&path); + + assert_eq!( + engine.shared().underruns.load(Ordering::Relaxed), + 0, + "no gaps" + ); + // The master fader's level is the only gain between the file and the output. + let gain = 0.8f32; + let worst = (0..frames) + .map(|n| { + let source = 0.5 * (std::f32::consts::TAU * 440.0 * n as f32 / 48_000.0).sin(); + (out[2 * n] - gain * source).abs() + }) + .fold(0f32, f32::max); + assert!( + worst < 1e-4, + "every frame is the file's frame (worst error {worst})" + ); + } + + #[test] + fn a_region_from_a_file_at_another_rate_is_resampled_closely() { + let frames = 44_100; + let path = temp_wav("other-rate", 44_100, frames, |n| { + 0.5 * (std::f32::consts::TAU * 440.0 * n as f32 / 44_100.0).sin() + }); + let file = AudioFile::open(&path).unwrap_or_else(|e| panic!("open the test WAV: {e:?}")); + let mut engine = Engine::offline(48_000).unwrap_or_else(|e| panic!("offline engine: {e}")); + let clip = engine.stream_clip_in(&file, 0, 0.0, ClipEdit::default(), 1); + for c in song_play(Vec::new(), vec![clip]) { + assert!(engine.send(c)); + } + let out = render(&mut engine, 44_000); + let _ = std::fs::remove_file(&path); + + assert_eq!(engine.shared().underruns.load(Ordering::Relaxed), 0); + let worst = (0..44_000) + .map(|m| { + let t = m as f32 / 48_000.0; + let want = 0.8 * 0.5 * (std::f32::consts::TAU * 440.0 * t).sin(); + (out[2 * m] - want).abs() + }) + .fold(0f32, f32::max); + assert!( + worst < 5e-3, + "linear resampling stays close (worst error {worst})" + ); + } + + /// A plug-in that only records whether the engine told it about offline rendering. + struct Recorder(Arc); + + impl BlockEffect for Recorder { + fn set_param(&mut self, _index: usize, _norm: f32) {} + fn process( + &mut self, + _in_l: &[f32], + _in_r: &[f32], + _out_l: &mut [f32], + _out_r: &mut [f32], + ) { + } + fn reset(&mut self) {} + fn boxed_clone(&self) -> Option> { + Some(Box::new(Recorder(Arc::clone(&self.0)))) + } + fn set_offline(&mut self, offline: bool) { + self.0.store(offline, Ordering::Relaxed); + } + } + + #[test] + fn a_plug_in_in_a_track_is_told_about_offline_rendering() { + let told = Arc::new(AtomicBool::new(false)); + let mut fx = Fx::new(FxKind::Plugin, [0.0; MAX_FX_PARAMS], false, 48_000.0); + fx.set_plugin(Box::new(Recorder(Arc::clone(&told)))); + let chain = Chain::new(vec![fx]); + let mut commands = song_play(Vec::new(), Vec::new()); + commands.push(Command::SetInserts { + track: 0, + chain: Box::new(chain), + }); + let (_out, _engine) = run(48_000, commands, PLUGIN_BLOCK * 4); + assert!( + told.load(Ordering::Relaxed), + "the plug-in waits for its blocks" + ); + } + + /// The real-time path (a core that is not offline, handing its frames over with + /// `Command::SetCapture`) hears exactly what the offline render makes: offline changes how + /// the core waits for data, not what it plays. + #[test] + fn the_live_capture_is_bit_for_bit_the_offline_render() { + let notes = || vec![note(0.0, 4.0, 60), note(1.0, 2.0, 67), note(2.5, 1.0, 72)]; + let frames = 24_000; + let (offline, _) = run(48_000, song_play(notes(), Vec::new()), frames); + + let (mut tx, rx) = RingBuffer::::new(1024); + let (trash_tx, _trash_rx) = RingBuffer::new(64); + let mut core = EngineCore::new(48_000, rx, trash_tx, Arc::new(Shared::new())); + let (captured_tx, mut captured) = RingBuffer::<[f32; 2]>::new(frames * 2); + let sink = CaptureSink { + frames: captured_tx, + dropped: Arc::new(std::sync::atomic::AtomicU64::new(0)), + }; + assert!(tx.push(Command::SetCapture(Some(sink))).is_ok()); + for c in song_play(notes(), Vec::new()) { + assert!(tx.push(c).is_ok()); + } + let mut out = vec![0f32; frames * 2]; + for block in out.chunks_mut(BLOCK * 2) { + core.process(block); + } + let mut heard = Vec::with_capacity(frames * 2); + while let Ok(frame) = captured.pop() { + heard.extend_from_slice(&frame); + } + assert_eq!(heard.len(), offline.len()); + assert!( + heard + .iter() + .zip(&offline) + .all(|(a, b)| a.to_bits() == b.to_bits()), + "the capture and the offline render are identical" + ); + } +} diff --git a/crates/prowave-engine/src/plugin.rs b/crates/prowave-engine/src/plugin.rs index 2aee2df8..7d669b20 100644 --- a/crates/prowave-engine/src/plugin.rs +++ b/crates/prowave-engine/src/plugin.rs @@ -48,6 +48,11 @@ pub trait BlockEffect: Send { fn boxed_clone(&self) -> Option> { None } + + /// Offline rendering (see `EngineCore::set_offline`) is not in real time: a plug-in that runs + /// in another process must answer every block instead of letting a late answer pass dry. + /// A plug-in that runs on the engine's own thread needs nothing, so the default does nothing. + fn set_offline(&mut self, _offline: bool) {} } /// The audio thread's side of a hosted effect: the plug-in, and the block it is fed with. @@ -103,6 +108,13 @@ impl PluginSlot { } } + /// Offline rendering on or off for the plug-in (see [`BlockEffect::set_offline`]). + pub(crate) fn set_offline(&mut self, offline: bool) { + if let Some(p) = self.plugin.as_mut() { + p.set_offline(offline); + } + } + /// One frame in, one frame out ([`PLUGIN_BLOCK`] frames late). #[inline] pub(crate) fn tick(&mut self, l: f32, r: f32) -> (f32, f32) { diff --git a/crates/prowave-plugin-host/src/lib.rs b/crates/prowave-plugin-host/src/lib.rs index b1df7200..fe245d39 100644 --- a/crates/prowave-plugin-host/src/lib.rs +++ b/crates/prowave-plugin-host/src/lib.rs @@ -580,6 +580,20 @@ impl Processor { ProcessorKind::Remote(p) => p.reset(), } } + + /// Offline rendering (not in real time): a plug-in in its own process is waited for, block + /// by block, instead of its late blocks passing dry. A plug-in in this process runs at the + /// engine's own pace, so nothing changes for it. + pub fn set_offline(&mut self, offline: bool) { + // Only a process-isolated plug-in (Unix) has anything to wait for. + #[cfg(not(unix))] + let _ = offline; + match &mut self.0 { + ProcessorKind::Local(_) => {} + #[cfg(unix)] + ProcessorKind::Remote(p) => p.set_offline(offline), + } + } } /// The folders plug-ins of `format` are installed in on this system (existing or not). diff --git a/crates/prowave-plugin-host/src/sandbox.rs b/crates/prowave-plugin-host/src/sandbox.rs index 19461d20..4d135d0f 100644 --- a/crates/prowave-plugin-host/src/sandbox.rs +++ b/crates/prowave-plugin-host/src/sandbox.rs @@ -32,6 +32,10 @@ use std::time::{Duration, Instant}; pub(crate) const MAX_BLOCK: usize = 1024; /// How long the audio thread waits for a block before it passes dry. const WAIT: Duration = Duration::from_millis(40); +/// How long an offline render waits for one block. Offline nothing is real time, so the wait +/// is as long as the plug-in needs; this cap only stops a plug-in that has hung (without dying) +/// from holding the render forever. A plug-in that died is given up at once. +const OFFLINE_WAIT: Duration = Duration::from_secs(30); /// How long a plug-in may take to load in its process. const START: Duration = Duration::from_secs(30); /// How long a request on the pipes may take. @@ -239,6 +243,9 @@ struct AudioSide { behind: bool, pending: usize, changes: [(u32, f32); MAX_CHANGES], + /// Offline rendering: wait for every answer (see [`OFFLINE_WAIT`]) instead of passing late + /// blocks dry. + offline: bool, } /// A plug-in running in its own process, seen from Pro Wave. @@ -379,6 +386,7 @@ impl Remote { behind: false, pending: 0, changes: [(0, 0.0); MAX_CHANGES], + offline: false, }), })) } @@ -607,14 +615,24 @@ impl RemoteProcessor { remote.wake.post(); // The answer takes about a thread switch: spin, looking at the clock now and then. + // Offline, nothing is real time: the wait yields the processor instead, and only a + // plug-in that has died (or hung for `OFFLINE_WAIT`) is given up. let started = Instant::now(); let mut spins = 0u32; + let offline = audio.offline; while shared.done.load(Ordering::Acquire) != asked { - std::hint::spin_loop(); + if offline { + std::thread::yield_now(); + } else { + std::hint::spin_loop(); + } spins = spins.wrapping_add(1); - if spins.is_multiple_of(256) && (started.elapsed() > WAIT || remote.crashed()) { - audio.behind = true; - return; + if spins.is_multiple_of(256) { + let limit = if offline { OFFLINE_WAIT } else { WAIT }; + if started.elapsed() > limit || remote.crashed() { + audio.behind = true; + return; + } } } for (i, (l, r)) in left @@ -633,6 +651,11 @@ impl RemoteProcessor { } } + /// Offline rendering on or off: see [`AudioSide::offline`]. + pub(crate) fn set_offline(&mut self, offline: bool) { + self.audio().offline = offline; + } + pub(crate) fn set_param_norm(&mut self, index: usize, norm: f32) { if index >= self.0.params.len() || !norm.is_finite() { return;