From a604fe8e3eb2aa8eea654474943f82aadf8a710a Mon Sep 17 00:00:00 2001 From: Zan <69921455+InZan17@users.noreply.github.com> Date: Thu, 9 Jan 2025 19:25:19 +0100 Subject: [PATCH 1/2] Reduce latency on Alsa --- src/alsa_snd.rs | 23 ++++++++++++----------- 1 file changed, 12 insertions(+), 11 deletions(-) diff --git a/src/alsa_snd.rs b/src/alsa_snd.rs index 8bd403c..c2b1d11 100644 --- a/src/alsa_snd.rs +++ b/src/alsa_snd.rs @@ -109,23 +109,24 @@ unsafe fn audio_thread(mut mixer: crate::mixer::Mixer) { panic!("PCM device is not ready"); } - // // find out how much space is available for playback data + // find out how much space is available for playback data // teoretically it should reduce latency - we will fill a minimum amount of // frames just to keep alsa busy and will be able to mix some fresh sounds - // it does, but also randmly panics sometimes - // let frames_to_deliver = sys::snd_pcm_avail_update(pcm_handle); - // println!("{}", frames_to_deliver); - // let frames_to_deliver = if frames_to_deliver > consts::PCM_BUFFER_SIZE as _ { - // consts::PCM_BUFFER_SIZE as i64 - // } else { - // frames_to_deliver - // }; + let frames_to_deliver = sys::snd_pcm_avail_update(pcm_handle); + let frames_to_deliver = if frames_to_deliver > consts::PCM_BUFFER_SIZE as _ { + consts::PCM_BUFFER_SIZE as i64 + } else { + frames_to_deliver + }; - let frames_to_deliver = consts::PCM_BUFFER_SIZE as i64; + let buffer = std::slice::from_raw_parts_mut( + buffer.as_mut_ptr(), + frames_to_deliver as usize * consts::CHANNELS as usize, + ); // ask mixer to fill the buffer - mixer.fill_audio_buffer(&mut buffer, frames_to_deliver as usize); + mixer.fill_audio_buffer(buffer, frames_to_deliver as usize); // send filled buffer back to alsa let frames_writen = sys::snd_pcm_writei( From 07d0060b9edce4cfba8af73254c46bd526c40d79 Mon Sep 17 00:00:00 2001 From: Zan <69921455+InZan17@users.noreply.github.com> Date: Thu, 9 Jan 2025 20:13:09 +0100 Subject: [PATCH 2/2] cargo fmt --- src/mixer.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/mixer.rs b/src/mixer.rs index 98f8895..e650142 100644 --- a/src/mixer.rs +++ b/src/mixer.rs @@ -2,8 +2,8 @@ use crate::{AudioContext, PlaySoundParams}; use std::cell::Cell; use std::collections::HashMap; -use std::sync::Arc; use std::sync::mpsc; +use std::sync::Arc; enum AudioMessage { AddSound(u32, Vec),