From 35b94bdc9467f312dac0e2244f8b5806f98132e7 Mon Sep 17 00:00:00 2001 From: JasonLG1979 Date: Wed, 21 Jun 2023 19:17:23 -0500 Subject: [PATCH] Add the ability to get backend latency --- playback/src/audio_backend/alsa.rs | 17 +++++++++++++++++ playback/src/audio_backend/mod.rs | 3 +++ playback/src/audio_backend/pulseaudio.rs | 11 +++++++++++ 3 files changed, 31 insertions(+) diff --git a/playback/src/audio_backend/alsa.rs b/playback/src/audio_backend/alsa.rs index fada2580..b647b1e4 100644 --- a/playback/src/audio_backend/alsa.rs +++ b/playback/src/audio_backend/alsa.rs @@ -456,6 +456,23 @@ impl Sink for AlsaSink { Ok(()) } + fn get_latency_pcm(&mut self) -> u64 { + let buffer_len = self.period_buffer.len(); + + self.pcm + .as_mut() + .and_then(|pcm| { + pcm.status().ok().map(|status| { + let delay_frames = status.get_delay(); + + let frames_in_buffer = pcm.bytes_to_frames(buffer_len as isize); + + (delay_frames + frames_in_buffer) as u64 + }) + }) + .unwrap_or(0) + } + sink_as_bytes!(); } diff --git a/playback/src/audio_backend/mod.rs b/playback/src/audio_backend/mod.rs index 05822395..05916fa6 100644 --- a/playback/src/audio_backend/mod.rs +++ b/playback/src/audio_backend/mod.rs @@ -30,6 +30,9 @@ pub trait Sink { fn stop(&mut self) -> SinkResult<()> { Ok(()) } + fn get_latency_pcm(&mut self) -> u64 { + 0 + } fn write(&mut self, packet: AudioPacket, converter: &mut Converter) -> SinkResult<()>; } diff --git a/playback/src/audio_backend/pulseaudio.rs b/playback/src/audio_backend/pulseaudio.rs index 43d7ec07..b1b93822 100644 --- a/playback/src/audio_backend/pulseaudio.rs +++ b/playback/src/audio_backend/pulseaudio.rs @@ -131,6 +131,17 @@ impl Sink for PulseAudioSink { Ok(()) } + fn get_latency_pcm(&mut self) -> u64 { + self.sink + .as_mut() + .and_then(|sink| { + sink.get_latency() + .ok() + .map(|micro_sec| (micro_sec.as_secs_f64() * SAMPLE_RATE as f64).round() as u64) + }) + .unwrap_or(0) + } + sink_as_bytes!(); }