diff --git a/codex-rs/voice-host/README.md b/codex-rs/voice-host/README.md index cbb5aa656e..5cbaa99db5 100644 --- a/codex-rs/voice-host/README.md +++ b/codex-rs/voice-host/README.md @@ -30,7 +30,8 @@ begins. After unmute, capture waits for a following callback's device timestamp and rejects buffers captured before that cutoff, including buffers crossing it. This can discard speech onset; it relies on backend timestamp estimates and does not establish a precise physical mute boundary. -Both streams request roughly 10 ms callbacks within the device's supported range +On Linux both streams target 80 ms at 48 kHz and 50 ms at other rates. +Other platforms target 10 ms. Both stay within the device's supported range and the 8,192-frame queue budget. Unknown or incompatible ranges are rejected; there is no fallback to an unbounded default. Backends may deliver smaller callbacks than requested, so capture and rendered references pack samples into diff --git a/codex-rs/voice-host/src/audio_sink_tests.rs b/codex-rs/voice-host/src/audio_sink_tests.rs index f9b545e2e1..97b8c7b758 100644 --- a/codex-rs/voice-host/src/audio_sink_tests.rs +++ b/codex-rs/voice-host/src/audio_sink_tests.rs @@ -86,7 +86,7 @@ fn unexpected_flush_cancels_a_blocked_speaker_write() { let sink = Sink::new(port.writer()); sink.set_state(gst::State::Playing).unwrap(); let capacity = if cfg!(target_os = "linux") { - 4_800 + crate::devices::playback::LINUX_48K_LIMIT as usize } else { 1_920 }; diff --git a/codex-rs/voice-host/src/devices.rs b/codex-rs/voice-host/src/devices.rs index d28eba4397..4b32cab091 100644 --- a/codex-rs/voice-host/src/devices.rs +++ b/codex-rs/voice-host/src/devices.rs @@ -116,6 +116,12 @@ fn eligible_devices( }) } +// CPAL reads whole periods from a two-period ALSA ring. With 3840 frames, +// 4096-frame cycles leave at most 3584 unread and 4800-frame cycles leave +// at most 2880. Both fit on the next cycle. Smaller periods lose samples +// on at least one of these steady graphs. One period holds four 20 ms Opus packets. +const LINUX_48K_PERIOD: u32 = 3840; + const MAX_CAPTURE_AGE: Duration = Duration::from_secs(/*secs*/ 1); pub(super) struct Devices { @@ -334,12 +340,13 @@ fn bounded_stream_config( if min > max { return Err(io::Error::other("unsupported audio callback size range")); } - // ALSA allocates two periods. A 20 ms ring can be smaller than one PipeWire - // graph cycle (e.g. 2048 frames at 48 kHz), silently losing capture samples - // every cycle. Give Linux a bounded 100 ms ring instead, while retaining - // 10 ms callbacks elsewhere and rejecting incompatible device ranges below. let periods_per_second = if cfg!(target_os = "linux") { 20 } else { 100 }; - let frames = (config.sample_rate / periods_per_second).clamp(min, max); + let target = if cfg!(target_os = "linux") && config.sample_rate == 48_000 { + LINUX_48K_PERIOD + } else { + config.sample_rate / periods_per_second + }; + let frames = target.clamp(min, max); let callback_duration = Duration::from_secs_f64(f64::from(frames) / f64::from(config.sample_rate)); // Backends may deliver smaller callbacks than requested. Packing makes queue diff --git a/codex-rs/voice-host/src/devices_tests.rs b/codex-rs/voice-host/src/devices_tests.rs index ac1e1c9e47..72d8532331 100644 --- a/codex-rs/voice-host/src/devices_tests.rs +++ b/codex-rs/voice-host/src/devices_tests.rs @@ -80,7 +80,7 @@ fn callback_configuration_fits_supported_range_and_actual_queue() { (384_000, 1, 16, 16, 16), (96_000, 1, 15, 15, 15), (48_000, 1, 128, 128, 128), - (48_000, 2_048, 16_384, 2_048, 2_400), + (48_000, 2_048, 16_384, 2_048, 3_840), (384_000, 6_016, 16_384, 6_016, 8_192), ] { let frames = if cfg!(target_os = "linux") { @@ -146,11 +146,26 @@ fn pipewire_graph_cycles_support_capture_and_playback() { let start = Instant::now(); let mut available = 0; let mut packets = Vec::new(); - // Model measured 2048-frame graph cycles and ALSA's two-period ring. - // Packing and encoding must sustain 20 ms packets despite this cadence. - for cycle in 1..=48 { - available = (available + 2_048).min(2 * period); - let now = start + Duration::from_secs_f64(f64::from(cycle * 2_048) / 48_000.0); + // Include previously working 4800- and 3600-frame cycles, a switch to 4096 + // with samples still unread, and 2048 frames resampled from 44.1 kHz. + let mut elapsed_frames = 0; + let resampled = (2_048_u32 * 48_000).div_ceil(44_100); + let cycles = [ + (4_800, 4), + (2_048, 15), + (512, 5), + (4_096, 15), + (3_600, 16), + (resampled, 12), + ]; + for quantum in cycles + .into_iter() + .flat_map(|(q, n)| std::iter::repeat_n(q, n)) + { + available += quantum; + assert!(available <= 2 * period, "overrun at {quantum} frames"); + elapsed_frames += quantum; + let now = start + Duration::from_secs_f64(f64::from(elapsed_frames) / 48_000.0); while available >= period { let captured = now - Duration::from_secs_f64(f64::from(available) / 48_000.0); packer.discard_capture_gap(captured, /*rate*/ 48_000.0); @@ -171,16 +186,18 @@ fn pipewire_graph_cycles_support_capture_and_playback() { } assert!(packets.len() >= 90, "capture starved Opus"); - // Queue a full output callback without racing the producer. + // Every fifteenth 4096-frame cycle needs two full periods from 20 ms packets. Buffers::set_disabled(&buffers.speaker, /*disabled*/ false).unwrap(); buffers.serviced.store(true, Ordering::Release); let port = PlaybackPort::new(buffers.clone(), /*rate*/ 48_000); let writer = port.writer(); - let bytes = 0.25_f32.to_le_bytes().repeat(period as usize); - for chunk in bytes.chunks(BLOCK * 4) { - assert_eq!(writer.write(chunk).unwrap(), chunk.len()); + let burst = 2 * period as usize; + let packet = 0.25_f32.to_le_bytes().repeat(960); + let mut bytes = 0; + while bytes < burst * 4 { + bytes += writer.write(&packet[bytes % packet.len()..]).unwrap(); } - let mut output = vec![0.0_f32; period as usize]; + let mut output = vec![0.0_f32; burst]; render_output( &mut output, /*channels*/ 1, @@ -189,7 +206,7 @@ fn pipewire_graph_cycles_support_capture_and_playback() { &buffers, &mut OutputState::default(), ); - assert_eq!(output, vec![0.25; period as usize]); + assert_eq!(output, vec![0.25; burst]); } #[test] diff --git a/codex-rs/voice-host/src/playback.rs b/codex-rs/voice-host/src/playback.rs index be796b97c0..6d2e13cfa7 100644 --- a/codex-rs/voice-host/src/playback.rs +++ b/codex-rs/voice-host/src/playback.rs @@ -11,6 +11,10 @@ use std::sync::atomic::Ordering; use std::time::Duration; use std::time::Instant; +// Leave room for the block crossing the two-period boundary. Splitting +// writes as callbacks free individual samples can exhaust queue slots. +pub(super) const LINUX_48K_LIMIT: u32 = 2 * super::LINUX_48K_PERIOD + BLOCK as u32 - 1; + pub(super) struct PlaybackState { pub(super) producer: Mutex<()>, buffers: Arc, @@ -78,13 +82,16 @@ impl PlaybackWriter { .producer .lock() .map_err(|_| "speaker writer failed")?; - let deadline = Instant::now() + Duration::from_millis(/*millis*/ 100); let buffers = &self.state.buffers; - // Linux requests 50 ms callbacks; retain two callbacks of audio so a - // callback can fill without racing the producer. Keep the queue cap. let windows_per_second = if cfg!(target_os = "linux") { 10 } else { 25 }; - let limit = (self.state.rate / windows_per_second) - .min((BLOCK * buffers.playback.capacity()) as u32); + let (budget, wait_ms) = if cfg!(target_os = "linux") && self.state.rate == 48_000 { + // Allow two periods when sub-period cycles delay the next callback. + (LINUX_48K_LIMIT, 2 * u64::from(super::LINUX_48K_PERIOD) / 48) + } else { + (self.state.rate / windows_per_second, 100) + }; + let deadline = Instant::now() + Duration::from_millis(wait_ms); + let limit = budget.min((BLOCK * buffers.playback.capacity()) as u32); loop { if self.epoch % 2 == 1 || buffers.speaker.load(Ordering::Acquire) != self.epoch