Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

perf(editor): pause the idle editor audio stream on local outputs

Richie McIlroy45b7b0043b58
diff --git a/crates/audio/src/latency.rs b/crates/audio/src/latency.rs
index 7a19f6c90..38058d162 100644
--- a/crates/audio/src/latency.rs
+++ b/crates/audio/src/latency.rs
@@ -452,6 +452,22 @@ pub fn default_output_latency_hint(
}
}
+/// Whether the default output device is local hardware whose stream can be
+/// stopped while idle and restarted within a callback period or two.
+/// Wireless, AirPlay and display outputs are excluded because they can drop
+/// the start of audio or take seconds to wake after their stream stops.
+pub fn default_output_supports_idle_pause() -> bool {
+ #[cfg(target_os = "macos")]
+ {
+ macos::default_output_supports_idle_pause()
+ }
+
+ #[cfg(not(target_os = "macos"))]
+ {
+ false
+ }
+}
+
#[derive(Debug, Clone, Copy)]
pub struct InputLatencyInfo {
pub device_latency_secs: f64,
@@ -571,6 +587,22 @@ mod macos {
compute_latency_hint(&device, sample_rate, fallback_buffer_frames).ok()
}
+ pub(super) fn default_output_supports_idle_pause() -> bool {
+ System::default_output_device()
+ .ok()
+ .and_then(|device| device.transport_type().ok())
+ .is_some_and(|transport| {
+ matches!(
+ transport,
+ DeviceTransportType::BUILT_IN
+ | DeviceTransportType::USB
+ | DeviceTransportType::PCI
+ | DeviceTransportType::FIRE_WIRE
+ | DeviceTransportType::THUNDERBOLT
+ )
+ })
+ }
+
pub(super) fn estimate_input_latency(
sample_rate: u32,
buffer_size_frames: u32,
diff --git a/crates/editor/src/audio_output.rs b/crates/editor/src/audio_output.rs
index de31845a6..0e11ff2aa 100644
--- a/crates/editor/src/audio_output.rs
+++ b/crates/editor/src/audio_output.rs
@@ -6,6 +6,11 @@
//! awake, so audio starts within one callback period of the playback clock
//! rather than after a device wake that could take seconds. The stream is
//! rebuilt only when the default output device changes or the stream errors.
+//!
+//! On local hardware outputs that restart instantly (built-in speakers, USB
+//! and similar), a stream left without a source for [`IDLE_PAUSE_AFTER`] is
+//! paused rather than rendering silence indefinitely, and the next play or
+//! prewarm restarts it in place. Wireless and display outputs keep running.
use std::{
sync::{
@@ -45,6 +50,10 @@ const SOURCE_ACK_TIMEOUT: Duration = Duration::from_secs(5);
const PLAY_REQUEST_TIMEOUT: Duration = Duration::from_secs(15);
/// Bound on waiting for the initial pre-render window (normally a few ms).
const PRERENDER_READY_TIMEOUT: Duration = Duration::from_secs(2);
+/// How long a stream may render silence before it is paused. Long enough to
+/// cover the pauses of an active editing session, so play-pause-play stays on
+/// the already running stream.
+const IDLE_PAUSE_AFTER: Duration = Duration::from_secs(15);
pub struct PlaySpec {
pub segments: Vec<AudioSegment>,
@@ -65,6 +74,8 @@ enum ControlMsg {
Retire(Box<dyn Send>),
Realign(Box<dyn FnOnce() + Send>),
EnsureStream,
+ HoldAwake,
+ ReleaseAwake,
Play {
spec: Box<PlaySpec>,
generation: u64,
@@ -391,12 +402,23 @@ impl AudioOutput {
}
}
- /// Opens the output stream ahead of the first play so even the first
- /// press doesn't wait on the device (Bluetooth wake, etc.). Non-blocking.
+ /// Opens (or restarts an idle-paused) output stream ahead of the first
+ /// play so even the first press doesn't wait on the device (Bluetooth
+ /// wake, etc.). Non-blocking.
pub fn prewarm(&self) {
let _ = self.control_tx.send(ControlMsg::EnsureStream);
}
+ /// Opens the output stream and keeps it running, never idle-paused, until
+ /// the returned hold is dropped. For playback paths that start audio
+ /// without a warmup to hide a stream restart behind.
+ pub(crate) fn hold_awake(&self) -> AudioOutputAwakeHold {
+ let _ = self.control_tx.send(ControlMsg::HoldAwake);
+ AudioOutputAwakeHold {
+ control_tx: self.control_tx.clone(),
+ }
+ }
+
/// Starts playing `spec` on the shared stream. Blocks until the live
/// callback acknowledges that it is consuming the source, so the caller
/// can start the playback clock knowing audio is audible. Returns a
@@ -506,6 +528,16 @@ impl Drop for AudioOutput {
}
}
+pub(crate) struct AudioOutputAwakeHold {
+ control_tx: std_mpsc::Sender<ControlMsg>,
+}
+
+impl Drop for AudioOutputAwakeHold {
+ fn drop(&mut self) {
+ let _ = self.control_tx.send(ControlMsg::ReleaseAwake);
+ }
+}
+
/// Per-playback state owned by the audio callback.
struct ActiveSource<T: FromSampleBytes> {
generation: u64,
@@ -558,7 +590,8 @@ enum SourceCommand<T: FromSampleBytes> {
/// The type-erased face of a running stream. The closures capture the typed
/// channel to the callback, chosen by the device's sample format at build.
struct TypedStreamHandle {
- _stream: cpal::Stream,
+ stream: cpal::Stream,
+ source_active: Arc<AtomicBool>,
#[allow(clippy::type_complexity)]
install: Box<dyn Fn(Box<PlaySpec>, u64, SourceAcknowledgement) -> Result<(), String>>,
install_progressive: Box<InstallProgressiveAudio>,
@@ -568,14 +601,91 @@ struct TypedStreamHandle {
struct StreamState {
device_name: Option<String>,
failed: Arc<AtomicBool>,
+ supports_idle_pause: bool,
+ paused: bool,
handle: TypedStreamHandle,
}
+impl StreamState {
+ fn idle_pausable(&self) -> bool {
+ self.supports_idle_pause && !self.paused
+ }
+}
+
+/// Tracks how long the running stream has gone without a control request or
+/// an active source.
+struct IdleTimer {
+ last_activity: Instant,
+}
+
+impl IdleTimer {
+ fn new(now: Instant) -> Self {
+ Self { last_activity: now }
+ }
+
+ fn touch(&mut self, now: Instant) {
+ self.last_activity = now;
+ }
+
+ fn remaining(&self, now: Instant) -> Duration {
+ IDLE_PAUSE_AFTER.saturating_sub(now.saturating_duration_since(self.last_activity))
+ }
+
+ /// True once the grace period has elapsed with no source playing. An
+ /// active source restarts the grace period.
+ fn should_pause(&mut self, now: Instant, source_active: bool) -> bool {
+ if source_active {
+ self.touch(now);
+ return false;
+ }
+ self.remaining(now).is_zero()
+ }
+}
+
+fn pause_idle_stream(state: &mut Option<StreamState>) {
+ let Some(stream) = state.as_mut() else {
+ return;
+ };
+ match stream.handle.stream.pause() {
+ Ok(()) => {
+ stream.paused = true;
+ info!("Paused idle audio output stream");
+ }
+ Err(error) => {
+ error!(%error, "Failed to pause idle audio output stream; closing it");
+ *state = None;
+ }
+ }
+}
+
fn control_thread(control_rx: std_mpsc::Receiver<ControlMsg>) {
// cpal streams aren't Send; this thread owns the stream for its lifetime.
let mut state: Option<StreamState> = None;
-
- while let Ok(msg) = control_rx.recv() {
+ let mut idle = IdleTimer::new(Instant::now());
+ let mut awake_holds = 0usize;
+
+ loop {
+ let msg = if state.as_ref().is_some_and(StreamState::idle_pausable) {
+ match control_rx.recv_timeout(idle.remaining(Instant::now())) {
+ Ok(msg) => msg,
+ Err(std_mpsc::RecvTimeoutError::Timeout) => {
+ let keep_running = awake_holds > 0
+ || state.as_ref().is_some_and(|stream| {
+ stream.handle.source_active.load(Ordering::Acquire)
+ });
+ if idle.should_pause(Instant::now(), keep_running) {
+ pause_idle_stream(&mut state);
+ }
+ continue;
+ }
+ Err(std_mpsc::RecvTimeoutError::Disconnected) => break,
+ }
+ } else {
+ match control_rx.recv() {
+ Ok(msg) => msg,
+ Err(_) => break,
+ }
+ };
match msg {
ControlMsg::Refresh {
spec,
@@ -596,6 +706,11 @@ fn control_thread(control_rx: std_mpsc::Receiver<ControlMsg>) {
ControlMsg::EnsureStream => {
ensure_stream(&mut state);
}
+ ControlMsg::HoldAwake => {
+ awake_holds += 1;
+ ensure_stream(&mut state);
+ }
+ ControlMsg::ReleaseAwake => awake_holds = awake_holds.saturating_sub(1),
ControlMsg::Play {
spec,
generation,
@@ -663,6 +778,7 @@ fn control_thread(control_rx: std_mpsc::Receiver<ControlMsg>) {
ControlMsg::Realign(realign) => realign(),
ControlMsg::Shutdown => break,
}
+ idle.touch(Instant::now());
}
info!("Audio output thread finished");
@@ -1074,7 +1190,7 @@ fn control_thread_headless(control_rx: std_mpsc::Receiver<ControlMsg>, mut tap:
error!(%error, "Could not update headless audio playback");
}
}
- ControlMsg::EnsureStream => {}
+ ControlMsg::EnsureStream | ControlMsg::HoldAwake | ControlMsg::ReleaseAwake => {}
ControlMsg::Play {
spec,
generation,
@@ -1199,9 +1315,18 @@ fn ensure_stream(state: &mut Option<StreamState>) -> bool {
};
let device_name = device.name().ok();
- if let Some(s) = state.as_ref() {
+ if let Some(s) = state.as_mut() {
if !s.failed.load(Ordering::Acquire) && s.device_name == device_name {
- return true;
+ if !s.paused {
+ return true;
+ }
+ match s.handle.stream.play() {
+ Ok(()) => {
+ s.paused = false;
+ return true;
+ }
+ Err(e) => error!("Failed to resume audio output stream: {e}"),
+ }
}
info!("Rebuilding audio output stream (device changed or stream failed)");
}
@@ -1235,6 +1360,8 @@ fn ensure_stream(state: &mut Option<StreamState>) -> bool {
*state = Some(StreamState {
device_name,
failed,
+ supports_idle_pause: cap_audio::default_output_supports_idle_pause(),
+ paused: false,
handle,
});
true
@@ -1269,13 +1396,16 @@ where
config.channels = output_info.channels as u16;
let (source_tx, source_rx) = std_mpsc::channel::<SourceCommand<T>>();
+ let source_active = Arc::new(AtomicBool::new(false));
let mut active: Option<ActiveSource<T>> = None;
+ let callback_source_active = source_active.clone();
let stream = device
.build_output_stream(
&config,
move |buffer: &mut [T], info| {
drain_source_commands(&mut active, &source_rx);
+ callback_source_active.store(active.is_some(), Ordering::Release);
let Some(source) = active.as_mut() else {
buffer.fill(T::EQUILIBRIUM);
@@ -1334,7 +1464,8 @@ where
});
Ok(TypedStreamHandle {
- _stream: stream,
+ stream,
+ source_active,
install,
install_progressive,
remove,
@@ -1385,6 +1516,37 @@ mod tests {
(*source, playhead_tx)
}
+ #[test]
+ fn idle_timer_pauses_only_after_a_quiet_grace_period() {
+ let start = Instant::now();
+ let mut idle = IdleTimer::new(start);
+
+ assert_eq!(idle.remaining(start), IDLE_PAUSE_AFTER);
+ assert!(!idle.should_pause(start + IDLE_PAUSE_AFTER / 2, false));
+ assert!(idle.should_pause(start + IDLE_PAUSE_AFTER, false));
+
+ idle.touch(start + IDLE_PAUSE_AFTER);
+ assert!(!idle.should_pause(start + IDLE_PAUSE_AFTER * 3 / 2, false));
+ assert_eq!(
+ idle.remaining(start + IDLE_PAUSE_AFTER * 3 / 2),
+ IDLE_PAUSE_AFTER / 2
+ );
+ assert!(idle.should_pause(start + IDLE_PAUSE_AFTER * 2, false));
+ }
+
+ #[test]
+ fn idle_timer_never_pauses_while_a_source_is_playing() {
+ let start = Instant::now();
+ let mut idle = IdleTimer::new(start);
+ let playing_until = start + IDLE_PAUSE_AFTER * 4;
+
+ assert!(!idle.should_pause(start + IDLE_PAUSE_AFTER, true));
+ assert!(!idle.should_pause(playing_until, true));
+ assert_eq!(idle.remaining(playing_until), IDLE_PAUSE_AFTER);
+ assert!(!idle.should_pause(playing_until + IDLE_PAUSE_AFTER / 2, false));
+ assert!(idle.should_pause(playing_until + IDLE_PAUSE_AFTER, false));
+ }
+
#[cfg(target_os = "linux")]
#[test]
fn supported_buffer_maximum_does_not_skip_the_start_of_playback() {
diff --git a/crates/editor/src/playback.rs b/crates/editor/src/playback.rs
index 95696fa68..5a76aad63 100644
--- a/crates/editor/src/playback.rs
+++ b/crates/editor/src/playback.rs
@@ -879,6 +879,11 @@ impl Playback {
elapsed: audio_wait_start.elapsed(),
});
}
+ // Restarts an idle-paused output stream while the video warms up, so
+ // the play request after warmup finds it already running.
+ if adopted.is_none() && has_playback_audio(&audio_segments, !self.music.is_empty()) {
+ self.audio_output.prewarm();
+ }
diagnostic.field(Field::number(
"audio_decode_wait_ms",
diff --git a/crates/editor/src/preparing_playback.rs b/crates/editor/src/preparing_playback.rs
index e163ae186..a74b7f773 100644
--- a/crates/editor/src/preparing_playback.rs
+++ b/crates/editor/src/preparing_playback.rs
@@ -519,14 +519,12 @@ impl PreparingPlaybackRunner {
};
sources.validate()?;
self.audio_sources = Some(sources);
- if self
+ let _audio_awake = self
.required_audio
.iter()
.flatten()
.any(|required| *required)
- {
- self.audio_output.prewarm();
- }
+ .then(|| self.audio_output.hold_awake());
let (frames, received) = flume::bounded(1);
let discard = received.clone();
let preview = crate::PreparingPreview::spawn(