mirror of
https://github.com/storytold/soundcraft.git
synced 2026-11-28 14:08:07 -08:00
Playback: strips render on the audio thread itself; count underruns and late callbacks (#1074)
* Playback: strips render on the audio thread itself The realtime callback handed strips to rayon's global pool whenever a session had four or more, then waited for them. The pool's workers run at normal priority, so under CPU load the callback waited for starved workers (priority inversion) and blocked, which the callback must never do. On the audio thread strips now render one after the other on the thread itself; offline renders (bounces) keep the parallelism. `as_audio_thread`, which marked pool workers while they rendered for the audio thread, is no longer needed. A headless stress test (opt-in: `cargo test -p soundcraft-playback -- --ignored`) plays a 16-track session with an EQ and a compressor per track, one callback per 512-frame period, while all cores but one spin. Before: 23 and 30 of 1500 callbacks missed their deadline; after: none in two runs. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Playback: count underruns and late callbacks; audio.health control method cpal reports underruns as `ErrorKind::Xrun`; they were only logged. The player now counts them, callbacks that overran their buffer period, and the worst callback load (relaxed atomics and one `Instant::now()` per callback, nothing on wasm32). `Player::health()` reads them; `Player::take_health()` reads and counts afresh without losing an event in between. The control channel reports them as `audio.health` (with the device's rate and buffer), and `soundcraft-cli app` knows it as a method. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * style: rustfmt the audio.health port cargo fmt --check failed on import grouping and a one-line if in the playback tests. * fix: cpal 0.18 sample_rate is a u32, and drop an unused import The output callback health timer used the old SampleRate newtype field, and note_stream_error removed the only use of Ordering in stream.rs. --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: FredApps <153173854+FredApps@users.noreply.github.com>
This commit is contained in:
10 files changed
+143
-18
No files matched your search
@@ -27,6 +27,7 @@ fn is_control_method(method: &str) -> bool {
|
||||
| "ui.key"
|
||||
| "ui.text"
|
||||
| "ui.screenshot"
|
||||
| "audio.health"
|
||||
| "app.quit"
|
||||
)
|
||||
}
|
||||
@@ -67,7 +68,7 @@ mod tests {
|
||||
assert_eq!(m, "engine.execute");
|
||||
let (m, _) = app_request("track.new", json!({}));
|
||||
assert_eq!(m, "engine.execute");
|
||||
for method in ["session.inspect", "engine.commands", "engine.parity", "ui.screenshot", "app.quit"] {
|
||||
for method in ["session.inspect", "engine.commands", "engine.parity", "ui.screenshot", "audio.health", "app.quit"] {
|
||||
assert_eq!(app_request(method, json!({})).0, method);
|
||||
}
|
||||
for (method, params) in [
|
||||
|
||||
@@ -22,8 +22,8 @@
|
||||
//! callback must never do. Code that runs on the audio thread logs anyway (the cpal error callback,
|
||||
//! the synth's full event queue, a hosted plugin's failed `process`, a CLAP plugin calling the
|
||||
//! host's `log` from its audio thread, the panic hook). So the cpal callbacks mark their thread
|
||||
//! (`soundcraft_playback::mark_audio_thread`; the mix engine carries the mark into the worker
|
||||
//! threads that render strips for it), and a record from a marked thread is not written
|
||||
//! (`soundcraft_playback::mark_audio_thread`; the mix engine renders every strip on the marked
|
||||
//! thread itself), and a record from a marked thread is not written
|
||||
//! there: the first one is kept in a fixed buffer (`try_lock`, no allocation, never waits) and the
|
||||
//! rest are only counted (an atomic). Another thread writes them out: the UI thread every frame
|
||||
//! ([`AppLogger::report_audio_thread`]) and any other thread before its own next record.
|
||||
|
||||
@@ -389,7 +389,7 @@ impl MixEngine {
|
||||
self.begin_block(s, pos, frames);
|
||||
let blk = Block { pos, frames, any_solo: any_solo(s) };
|
||||
let order = std::mem::take(&mut self.order);
|
||||
// Phase 1: independent strips (audio, instrument, MIDI) in parallel.
|
||||
// Phase 1: independent strips (audio, instrument, MIDI), in parallel except on the audio thread.
|
||||
let mut work = std::mem::take(&mut self.work);
|
||||
work.clear();
|
||||
for &i in &order {
|
||||
|
||||
@@ -1,16 +1,15 @@
|
||||
use super::AUDIO_THREAD;
|
||||
|
||||
/// Mark the calling thread as the realtime audio thread (`soundcraft_playback`'s cpal callbacks
|
||||
/// do, every call: one thread-local store). Strips [`MixEngine::render`] hands to worker threads
|
||||
/// count as the audio thread while they render for it. Code that might run there asks
|
||||
/// do, every call: one thread-local store). [`MixEngine::render`] renders every strip on that
|
||||
/// thread itself instead of handing strips to worker threads. Code that might run there asks
|
||||
/// [`on_audio_thread`] before doing anything that blocks; the desktop app's logger does, so a
|
||||
/// `log::` record from the audio thread never takes a lock or touches a file.
|
||||
pub fn mark_audio_thread() {
|
||||
AUDIO_THREAD.set(true);
|
||||
}
|
||||
|
||||
/// True on the thread [`mark_audio_thread`] marked, and on a worker while it renders strips for
|
||||
/// it. Lock-free and allocation-free.
|
||||
/// True on the thread [`mark_audio_thread`] marked. Lock-free and allocation-free.
|
||||
pub fn on_audio_thread() -> bool {
|
||||
AUDIO_THREAD.get()
|
||||
}
|
||||
@@ -29,7 +28,11 @@ fn as_audio_thread(audio: bool, f: impl FnOnce()) {
|
||||
f();
|
||||
}
|
||||
|
||||
/// Process strips, in parallel on native targets when there are enough of them.
|
||||
/// Process strips: in parallel on native targets when there are enough of them, except on the
|
||||
/// realtime audio thread. There they render one after the other on the thread itself: the pool's
|
||||
/// workers run at normal priority, so under load the callback would wait for starved workers
|
||||
/// (priority inversion) and miss its deadline, and waiting on them blocks, which the callback
|
||||
/// never may. Offline renders (bounces) keep the parallelism.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(crate) fn run_strips<T: Send>(work: &mut [T], f: impl Fn(&mut T) + Sync + Send) {
|
||||
use rayon::prelude::*;
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use super::{
|
||||
Arc, AtomicBool, BLOCK, BTreeMap, Cmd, HashMap, HashSet, MAX_CHANNELS, MeterSnapshot, MixEngine, OLD_SESSIONS, Ordering, OutputTrouble, Plugin,
|
||||
PluginEditor, PluginStateReader, PluginStates, PreparedInstance, Range, Receiver, Samples, Sender, Session, Shared, SyncSender, TrackId,
|
||||
itu_stereo_fold, main_channels, midi, record, sync_channel,
|
||||
Arc, AtomicBool, AtomicU32, BLOCK, BTreeMap, Cmd, HashMap, HashSet, MAX_CHANNELS, MeterSnapshot, MixEngine, OLD_SESSIONS, Ordering,
|
||||
OutputTrouble, Plugin, PluginEditor, PluginStateReader, PluginStates, PreparedInstance, Range, Receiver, Samples, Sender, Session, Shared,
|
||||
SyncSender, TrackId, devices, itu_stereo_fold, main_channels, midi, record, sync_channel,
|
||||
};
|
||||
use soundcraft_mix::{LiveMidi, midi_port_bit, midi_thru};
|
||||
use soundcraft_model::TrackKind;
|
||||
@@ -17,6 +17,29 @@ pub(crate) struct Fault {
|
||||
pub(crate) beats: std::sync::atomic::AtomicU64,
|
||||
/// The UI has been told.
|
||||
reported: AtomicBool,
|
||||
/// Underruns the device reported, callbacks that overran their buffer period, and the worst
|
||||
/// callback's share of its buffer time (‰), since the stream opened or the last
|
||||
/// [`Player::take_health`], and the device callbacks in that time.
|
||||
xruns: std::sync::atomic::AtomicU64,
|
||||
late_callbacks: std::sync::atomic::AtomicU64,
|
||||
worst_load: AtomicU32,
|
||||
callbacks: std::sync::atomic::AtomicU64,
|
||||
}
|
||||
|
||||
/// How the realtime audio path keeps up, for the UI and for stress tests: since the output
|
||||
/// opened, or since the last [`Player::take_health`].
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, serde::Serialize)]
|
||||
pub struct AudioHealth {
|
||||
/// Device callbacks (none for the silent clock).
|
||||
pub callbacks: u64,
|
||||
/// Underruns (dropouts) the device reported.
|
||||
pub xruns: u64,
|
||||
/// Callbacks that overran their buffer period. Not every one is an audible gap, and the
|
||||
/// device may report the same overrun as an xrun too (CoreAudio does).
|
||||
pub late_callbacks: u64,
|
||||
/// The slowest callback's render time as a share of its buffer period, to 0.001 (1.0 = it
|
||||
/// overran).
|
||||
pub worst_load: f64,
|
||||
}
|
||||
|
||||
impl Fault {
|
||||
@@ -33,6 +56,50 @@ impl Fault {
|
||||
};
|
||||
(!self.reported.swap(true, Ordering::Relaxed)).then_some(trouble)
|
||||
}
|
||||
|
||||
/// A device callback rendered `frames` at `rate` in `took`. Lock-free and allocation-free.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(crate) fn note_callback(&self, took: std::time::Duration, frames: usize, rate: f64) {
|
||||
self.callbacks.fetch_add(1, Ordering::Relaxed);
|
||||
if frames == 0 || rate <= 0.0 {
|
||||
return;
|
||||
}
|
||||
let load = took.as_secs_f64() * rate / frames as f64;
|
||||
if load > 1.0 {
|
||||
self.late_callbacks.fetch_add(1, Ordering::Relaxed);
|
||||
}
|
||||
self.worst_load.fetch_max((load * 1000.0).min(f64::from(u32::MAX)) as u32, Ordering::Relaxed);
|
||||
}
|
||||
|
||||
/// The stream reported an error (on the audio thread or another). A lost stream is recorded
|
||||
/// as gone; a transient xrun is counted and the stream keeps playing.
|
||||
pub(crate) fn note_stream_error(&self, e: &cpal::Error) {
|
||||
if devices::stream_lost(e) {
|
||||
self.gone.store(true, Ordering::Relaxed);
|
||||
} else if e.kind() == cpal::ErrorKind::Xrun {
|
||||
self.xruns.fetch_add(1, Ordering::Relaxed);
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn health(&self) -> AudioHealth {
|
||||
AudioHealth {
|
||||
callbacks: self.callbacks.load(Ordering::Relaxed),
|
||||
xruns: self.xruns.load(Ordering::Relaxed),
|
||||
late_callbacks: self.late_callbacks.load(Ordering::Relaxed),
|
||||
worst_load: f64::from(self.worst_load.load(Ordering::Relaxed)) / 1000.0,
|
||||
}
|
||||
}
|
||||
|
||||
/// The health so far, counting afresh from here: each counter is swapped for zero, so an
|
||||
/// event the callback records meanwhile lands in this reading or the next, never in neither.
|
||||
pub(crate) fn take_health(&self) -> AudioHealth {
|
||||
AudioHealth {
|
||||
callbacks: self.callbacks.swap(0, Ordering::Relaxed),
|
||||
xruns: self.xruns.swap(0, Ordering::Relaxed),
|
||||
late_callbacks: self.late_callbacks.swap(0, Ordering::Relaxed),
|
||||
worst_load: f64::from(self.worst_load.swap(0, Ordering::Relaxed)) / 1000.0,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// How long a playing output may go without a block before it counts as stalled.
|
||||
|
||||
@@ -48,8 +48,9 @@ const BLOCK: usize = 512;
|
||||
/// Room for replaced snapshots on their way back; `update_session` empties it before each send.
|
||||
const OLD_SESSIONS: usize = 16;
|
||||
|
||||
/// The realtime audio thread marker lives in the mix engine, which carries it into the strips it
|
||||
/// renders on worker threads; the cpal callbacks here set it.
|
||||
pub use callback::AudioHealth;
|
||||
/// The realtime audio thread marker lives in the mix engine, which renders every strip on the
|
||||
/// marked thread itself; the cpal callbacks here set it.
|
||||
pub use soundcraft_mix::{mark_audio_thread, on_audio_thread};
|
||||
|
||||
mod callback;
|
||||
@@ -221,6 +222,19 @@ impl Player {
|
||||
self.fault.trouble(stalled)
|
||||
}
|
||||
|
||||
/// How the realtime path has kept up since the output opened or the last
|
||||
/// [`Player::take_health`]: callbacks, device-reported underruns, late callbacks and the
|
||||
/// worst callback load.
|
||||
pub fn health(&self) -> AudioHealth {
|
||||
self.fault.health()
|
||||
}
|
||||
|
||||
/// [`Player::health`] so far, then count afresh (a stress run measures from a take). No
|
||||
/// event is lost between the reading and the restart.
|
||||
pub fn take_health(&self) -> AudioHealth {
|
||||
self.fault.take_health()
|
||||
}
|
||||
|
||||
fn side(&self) -> std::sync::MutexGuard<'_, Side> {
|
||||
self.side.lock().unwrap_or_else(PoisonError::into_inner)
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
use super::callback::{AudioState, Fault, guarded_block};
|
||||
use super::{Arc, AudioConfig, Cmd, Ordering, Plugin, Receiver, Sender, Shared, devices, mark_audio_thread};
|
||||
use super::{Arc, AudioConfig, Cmd, Plugin, Receiver, Sender, Shared, devices, mark_audio_thread};
|
||||
|
||||
/// Start a freshly built output stream. `false` when the device refuses to start it, so the caller
|
||||
/// treats it like a stream that failed to build and tries the next configuration.
|
||||
@@ -63,10 +63,14 @@ where
|
||||
let mut scratch = vec![0.0f32; 8192 * frame];
|
||||
let chunk = scratch.len();
|
||||
let (failed, guard, gone) = (Arc::clone(fault), Arc::clone(shared), Arc::clone(fault));
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
let rate = f64::from(config.sample_rate);
|
||||
device.build_output_stream(
|
||||
config,
|
||||
move |data: &mut [T], _: &cpal::OutputCallbackInfo| {
|
||||
mark_audio_thread();
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
let started = std::time::Instant::now();
|
||||
for out in data.chunks_mut(chunk) {
|
||||
let Some(s) = scratch.get_mut(..out.len()) else { return };
|
||||
guarded_block(&failed, &guard, s, |d| state.fill(d, channels));
|
||||
@@ -74,6 +78,8 @@ where
|
||||
*o = T::from_sample(*x);
|
||||
}
|
||||
}
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
failed.note_callback(started.elapsed(), data.len() / frame, rate);
|
||||
},
|
||||
// cpal may call this on the audio thread (on ALSA in a loop while the device stays
|
||||
// broken): marked, so the logger hands the record off instead of writing it.
|
||||
@@ -83,9 +89,7 @@ where
|
||||
// stream that must be rebuilt (`StreamInvalidated`), stops playback until the user
|
||||
// reconnects; a rerouted default device (`DeviceChanged`) keeps playing on the new
|
||||
// route, and an xrun is transient, so neither counts as losing the stream.
|
||||
if devices::stream_lost(&e) {
|
||||
gone.gone.store(true, Ordering::Relaxed);
|
||||
}
|
||||
gone.note_stream_error(&e);
|
||||
log::warn!("audio stream error: {e}");
|
||||
},
|
||||
None,
|
||||
|
||||
@@ -289,6 +289,28 @@ fn a_lost_or_stalled_device_is_reported_once() {
|
||||
assert_eq!((fault.trouble(false), fault.trouble(true)), (Some(OutputTrouble::Gone), None));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn underruns_and_late_callbacks_are_counted_until_taken() {
|
||||
use std::time::Duration;
|
||||
let f = Fault::default();
|
||||
let error = |kind| cpal::Error::with_message(kind, "test");
|
||||
f.note_stream_error(&error(cpal::ErrorKind::Xrun));
|
||||
f.note_stream_error(&error(cpal::ErrorKind::Xrun));
|
||||
// 512 frames at 48 kHz last 10.67 ms.
|
||||
f.note_callback(Duration::from_millis(4), 512, 48_000.0);
|
||||
f.note_callback(Duration::from_millis(16), 512, 48_000.0);
|
||||
f.note_callback(Duration::from_millis(2), 512, 48_000.0);
|
||||
let h = f.health();
|
||||
assert_eq!(h, AudioHealth { callbacks: 3, xruns: 2, late_callbacks: 1, worst_load: 1.5 });
|
||||
assert!(!f.gone.load(Ordering::Relaxed), "an underrun is not a lost device");
|
||||
assert_eq!(f.take_health(), h);
|
||||
assert_eq!(f.health(), AudioHealth::default());
|
||||
f.note_callback(Duration::from_millis(2), 512, 48_000.0);
|
||||
assert_eq!(f.health().callbacks, 1);
|
||||
f.note_stream_error(&error(cpal::ErrorKind::DeviceNotAvailable));
|
||||
assert!(f.gone.load(Ordering::Relaxed));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn audio_state_plays_and_stops_at_end() {
|
||||
let s = Arc::new(soundcraft_model::Session::default());
|
||||
|
||||
@@ -488,6 +488,19 @@ fn handle(app: &mut SoundApp, ctx: &egui::Context, req: &ControlRequest) -> Opti
|
||||
"session.inspect" | "document.inspect" => {
|
||||
ok(soundcraft_engine::inspect::session(&app.engine, p.get("detail").and_then(Value::as_str) == Some("full")))
|
||||
}
|
||||
"audio.health" => match &app.player {
|
||||
Some(player) => {
|
||||
let h = if p.get("reset").and_then(Value::as_bool) == Some(true) { player.take_health() } else { player.health() };
|
||||
ok(json!({
|
||||
"device": player.device_name,
|
||||
"silent": player.silent,
|
||||
"sample_rate": player.device_rate,
|
||||
"buffer_frames": player.device_buffer,
|
||||
"health": h,
|
||||
}))
|
||||
}
|
||||
None => err("no audio output"),
|
||||
},
|
||||
"ui.inspect" => {
|
||||
let mut v = app.inspect(ctx);
|
||||
v["edit_layout"] = json!(app.edit_layout);
|
||||
|
||||
@@ -44,6 +44,7 @@ Errors: `{"id": 1, "ok": false, "error": "bad parameters for `mix.volume`: no tr
|
||||
| `engine.parity` | `{}` | Parity report against the incumbent's menu catalog. |
|
||||
| `session.inspect` | `{detail?: "summary"|"full"}` | The document: tracks, clips (with times), inserts (+params when full), sends, routing, automation, markers, groups, busses, sources (`loaded` true when decoded audio is in the pool), selection, zoom (`samples_per_px`, `scroll`), transport, undo label. |
|
||||
| `ui.inspect` | `{}` | UI state (`window`, panels, dialogs), window size, playing/position, audio device, MIDI inputs (`midi_inputs`: name, enabled, open; `midi_events`: messages received so far; `midi_events_dropped`: messages a full input queue dropped), and `edit_layout` (timeline rect and every track row's rect, for clicking). |
|
||||
| `audio.health` | `{reset?: bool}` | How the realtime audio path keeps up since the output opened (or the last reset): `health` holds `callbacks`, `xruns` (underruns the device reported), `late_callbacks` (callbacks that overran their buffer period; not every one is audible, and the device may report the same overrun as an xrun) and `worst_load` (slowest callback as a share of its buffer period, to 0.001; 1.0 = it overran). Also `device`, `silent`, `sample_rate` and `buffer_frames` (`null`: the device default). The first blocks create plugins and may read late, so a stress run resets once playback is under way. `reset: true` returns the reading and counts afresh from it; no event falls between the two. |
|
||||
| `ui.set` | any `UiState` fields | e.g. `{"window": "Mix", "narrow_mix": true}`. |
|
||||
| `ui.menu.list` | `{}` | Every catalog menu path and the command that implements it (or null). |
|
||||
| `ui.menu.invoke` | `{path}` or `{id}` | Like clicking the menu item: may open its dialog (e.g. `"Track > New..."`). |
|
||||
|
||||
Reference in new issue
Block a user