Add a helper-backed realtime WebRTC session API (#43097)

## What changed

- Add `RealtimeWebrtcSession` and cloneable handles for startup, answer negotiation, audio controls, level meters, and error reporting.
- Open devices after answer negotiation and apply the latest controls before enabling audio. Preserve subsequent control transitions in order and close the session if the command queue fills.
- Cancel pending work on explicit close, external cancellation, or final handle drop, with a shared runtime keeping helper reaping alive.
- Add audio-state polling to consume microphone and speaker peaks and detect helper, device, or connection failures.
- Check packaged helper/runtime availability and initialize build information in the standalone TUI for the helper handshake.

## Testing

Add unit and helper-process integration tests covering startup control ordering, queue overflow, cancellation, helper reaping and loss, package availability, SDP debug redaction, and peak accumulation, clamping, and consumption.

GitOrigin-RevId: 458cd80353697f7411cee785f380d1d53aef8416
This commit is contained in:
Benjamin Carlsson authored and copyberry committed 2026-09-05 20:39:46 +00:00
1 parent 7dc7c7a756
commit 64e9a68987
17 files changed
+962 -3

No files matched your search

+16
View File
@@ -1,8 +1,10 @@
//! Meter reads clear accumulated peaks and surface callback failures.
//! Preallocated callback buffers pack small callbacks into full queue slots without locks.
//! Generation changes, rejected capture buffers and capture gaps discard incomplete frames.
//! Capture/render capacity covers the worker deadline; playback and callback limits stay fixed.
use std::sync::atomic::AtomicBool;
use std::sync::atomic::AtomicU16;
use std::sync::atomic::AtomicU64;
use std::sync::atomic::Ordering;
use std::time::Duration;
@@ -92,9 +94,21 @@ pub(super) struct Buffers {
pub(super) speaker: AtomicU64,
pub(super) serviced: AtomicBool,
pub(super) failed: AtomicBool,
pub(super) microphone_peak: AtomicU16,
pub(super) speaker_peak: AtomicU16,
}
impl Buffers {
pub(super) fn take_state(&self) -> std::io::Result<codex_realtime_webrtc::AudioState> {
if self.failed.load(Ordering::Acquire) {
return Err(std::io::Error::other("audio device failed"));
}
Ok(codex_realtime_webrtc::AudioState {
microphone_peak: self.microphone_peak.swap(/*val*/ 0, Ordering::AcqRel),
speaker_peak: self.speaker_peak.swap(/*val*/ 0, Ordering::AcqRel),
})
}
pub(super) fn new(input_rate: u32, output_rate: u32) -> Self {
// Rates are validated before opening devices. A pending batch can defer
// capture consumption until its freshness deadline plus one in-flight send.
@@ -113,6 +127,8 @@ impl Buffers {
speaker: AtomicU64::new(/*v*/ 1),
serviced: AtomicBool::new(false),
failed: AtomicBool::new(false),
microphone_peak: AtomicU16::new(/*v*/ 0),
speaker_peak: AtomicU16::new(/*v*/ 0),
}
}
+14
View File
@@ -12,6 +12,7 @@ mod processing;
use std::io;
use std::sync::Arc;
use std::sync::atomic::AtomicU16;
use std::sync::atomic::Ordering;
use std::time::Duration;
use std::time::Instant;
@@ -60,6 +61,10 @@ macro_rules! stream {
}
impl Devices {
pub(super) fn take_state(&self) -> io::Result<codex_realtime_webrtc::AudioState> {
self.worker.buffers.take_state()
}
pub(super) fn open() -> io::Result<Self> {
let host = cpal::default_host();
let input = host
@@ -178,6 +183,13 @@ fn bounded_stream_config(
Ok(config)
}
fn record_peak(peak: &AtomicU16, sample: f32) {
peak.fetch_max(
(sample.abs().min(1.0) * f32::from(u16::MAX)) as u16,
Ordering::Relaxed,
);
}
// CPAL reports recoverable underruns/overruns through the same callback as device loss.
fn handle_stream_error(buffers: &Buffers, error: cpal::Error) {
if error.kind() != cpal::ErrorKind::Xrun {
@@ -247,6 +259,7 @@ where
buffers.failed.store(true, Ordering::Release);
return;
}
record_peak(&buffers.microphone_peak, *output);
}
if !capture.push(frame, rate, &buffers.capture) {
buffers.failed.store(true, Ordering::Release);
@@ -320,6 +333,7 @@ fn render_output<T>(
let rendered = T::from_sample(output.playback.next(buffers));
frame.fill(rendered);
*sample = f32::from_sample(rendered);
record_peak(&buffers.speaker_peak, *sample);
}
if !output.reference.push(reference, rate, &buffers.rendered) {
buffers.failed.store(true, Ordering::Release);
+20
View File
@@ -66,6 +66,7 @@ fn startup_output_waits_for_service_but_later_overflow_still_fails() {
&mut state,
);
assert!(buffers.failed.load(Ordering::Acquire));
assert!(buffers.take_state().is_err());
}
#[test]
@@ -257,6 +258,25 @@ fn tiny_output_callbacks_pack_references_without_delaying_rendering() {
);
assert_eq!(output, [0.5; 32]);
}
for sample in [-0.75, 0.25] {
record_peak(&buffers.microphone_peak, sample);
}
assert_eq!(
buffers.take_state().unwrap(),
codex_realtime_webrtc::AudioState {
microphone_peak: 49151,
speaker_peak: 32767,
}
);
assert_eq!(buffers.take_state().unwrap(), Default::default());
record_peak(&buffers.microphone_peak, /*sample*/ 1.5);
assert_eq!(
buffers.take_state().unwrap(),
codex_realtime_webrtc::AudioState {
microphone_peak: u16::MAX,
speaker_peak: 0,
}
);
assert_eq!(buffers.rendered.len(), 7);
assert!(!buffers.failed.load(Ordering::Acquire));
}
@@ -5,6 +5,10 @@ use std::io;
pub(super) struct Devices;
impl Devices {
pub(super) fn take_state(&self) -> io::Result<codex_realtime_webrtc::AudioState> {
Self::open().map(|_| codex_realtime_webrtc::AudioState::default())
}
pub(super) fn open() -> io::Result<Self> {
Err(io::Error::other(
"audio devices unavailable for this helper target",
+13
View File
@@ -119,6 +119,18 @@ fn run(
.map_err(|_| mpsc::RecvTimeoutError::Disconnected)
};
let reply = match message {
Ok(Message::InspectAudio {}) => {
if answered && transport.as_ref().is_none_or(|peer| !*peer.ready.borrow()) {
return Err(io::Error::other("voice connection closed"));
}
Message::AudioState {
state: devices
.as_ref()
.map(devices::Devices::take_state)
.transpose()?
.unwrap_or_default(),
}
}
Ok(Message::OpenDevices {}) if devices.is_none() && runtime.is_some() && answered => {
devices = Some(devices::Devices::open()?);
Message::DevicesOpened {}
@@ -176,6 +188,7 @@ fn run(
| Message::OpenDevices {}
| Message::DevicesOpened {}
| Message::AudioControlsApplied {}
| Message::AudioState { .. }
| Message::Closed {},
) => return Err(io::Error::other("invalid voice control sequence")),
};
+1 -1
View File
@@ -64,7 +64,7 @@ pub(crate) struct Transport {
connection: Arc<dyn PeerConnection>,
gathered: Arc<Notify>,
observer: JoinHandle<()>,
ready: watch::Receiver<bool>,
pub(crate) ready: watch::Receiver<bool>,
}
impl Transport {