mirror of
https://github.com/openai/codex.git
synced 2026-11-23 23:10:47 +00:00
Add voice test helpers and smoke tests
Co-authored-by: Codex <noreply@openai.com>
This commit is contained in:
Generated
+1
@@ -1522,6 +1522,7 @@ version = "0.0.0"
|
||||
dependencies = [
|
||||
"om-fork-miniaudio",
|
||||
"pretty_assertions",
|
||||
"serial_test",
|
||||
"tracing",
|
||||
]
|
||||
|
||||
|
||||
@@ -10,6 +10,7 @@ tracing = { workspace = true }
|
||||
|
||||
[dev-dependencies]
|
||||
pretty_assertions = { workspace = true }
|
||||
serial_test = { workspace = true }
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
use crate::AudioDeviceInfo;
|
||||
use crate::AudioDeviceKind;
|
||||
use std::sync::Arc;
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub(crate) struct InputOpenRequest {
|
||||
pub(crate) device_id: Option<String>,
|
||||
pub(crate) sample_rate: u32,
|
||||
pub(crate) channels: u32,
|
||||
pub(crate) period_frames: u32,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub(crate) struct OutputOpenRequest {
|
||||
pub(crate) device_id: Option<String>,
|
||||
pub(crate) sample_rate: u32,
|
||||
pub(crate) channels: u32,
|
||||
pub(crate) period_frames: u32,
|
||||
}
|
||||
|
||||
pub(crate) type InputDataCallback = Arc<dyn Fn(&[i16]) + Send + Sync>;
|
||||
pub(crate) type OutputDataCallback = Arc<dyn Fn(&mut [i16]) + Send + Sync>;
|
||||
|
||||
pub(crate) trait InputStreamHandle: Send {
|
||||
fn stop(&mut self) -> Result<(), String>;
|
||||
}
|
||||
|
||||
pub(crate) trait OutputStreamHandle: Send {
|
||||
fn stop(&mut self) -> Result<(), String>;
|
||||
}
|
||||
|
||||
pub(crate) trait AudioBackend: Send + Sync {
|
||||
fn backend_name(&self) -> String;
|
||||
fn list_devices(&self, kind: AudioDeviceKind) -> Result<Vec<AudioDeviceInfo>, String>;
|
||||
fn open_input(
|
||||
&self,
|
||||
request: &InputOpenRequest,
|
||||
callback: InputDataCallback,
|
||||
) -> Result<Box<dyn InputStreamHandle>, String>;
|
||||
fn open_output(
|
||||
&self,
|
||||
request: &OutputOpenRequest,
|
||||
callback: OutputDataCallback,
|
||||
) -> Result<Box<dyn OutputStreamHandle>, String>;
|
||||
}
|
||||
+497
-208
@@ -1,14 +1,12 @@
|
||||
use miniaudio::Backend;
|
||||
use miniaudio::Context;
|
||||
use miniaudio::Device;
|
||||
use miniaudio::DeviceConfig;
|
||||
use miniaudio::DeviceId;
|
||||
use miniaudio::DeviceIdAndName;
|
||||
use miniaudio::DeviceType;
|
||||
use miniaudio::Format;
|
||||
use miniaudio::Frames;
|
||||
use miniaudio::FramesMut;
|
||||
use miniaudio::ResampleAlgorithm;
|
||||
mod backend;
|
||||
mod miniaudio_backend;
|
||||
|
||||
use crate::backend::AudioBackend;
|
||||
use crate::backend::InputOpenRequest;
|
||||
use crate::backend::InputStreamHandle;
|
||||
use crate::backend::OutputOpenRequest;
|
||||
use crate::backend::OutputStreamHandle;
|
||||
use crate::miniaudio_backend::MiniaudioBackend;
|
||||
use std::collections::VecDeque;
|
||||
use std::mem::MaybeUninit;
|
||||
use std::sync::Arc;
|
||||
@@ -23,7 +21,7 @@ use tracing::warn;
|
||||
pub const AUDIO_SAMPLE_RATE: u32 = 24_000;
|
||||
pub const AUDIO_CHANNELS: u32 = 1;
|
||||
const PERIOD_SIZE_IN_FRAMES: u32 = 240;
|
||||
const SPEEX_RESAMPLE_QUALITY: u32 = 5;
|
||||
pub(crate) const SPEEX_RESAMPLE_QUALITY: u32 = 5;
|
||||
const MAX_OUTPUT_QUEUE_SAMPLES: usize = (AUDIO_SAMPLE_RATE as usize) * 2;
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
@@ -49,35 +47,12 @@ pub struct RecordedAudio {
|
||||
type ChunkCallback = Arc<Mutex<Box<dyn FnMut(Vec<i16>) + Send>>>;
|
||||
|
||||
pub fn list_audio_devices(kind: AudioDeviceKind) -> Result<Vec<AudioDeviceInfo>, String> {
|
||||
let context = create_context()?;
|
||||
let backend = backend_label(context.backend());
|
||||
let mut devices = Vec::new();
|
||||
|
||||
match kind {
|
||||
AudioDeviceKind::Input => {
|
||||
context
|
||||
.with_capture_devices(|infos| {
|
||||
extend_device_infos(&mut devices, infos, backend.as_str());
|
||||
})
|
||||
.map_err(|err| format!("failed to enumerate input audio devices: {err}"))?;
|
||||
}
|
||||
AudioDeviceKind::Output => {
|
||||
context
|
||||
.with_playback_devices(|infos| {
|
||||
extend_device_infos(&mut devices, infos, backend.as_str());
|
||||
})
|
||||
.map_err(|err| format!("failed to enumerate output audio devices: {err}"))?;
|
||||
}
|
||||
}
|
||||
|
||||
devices.sort_by(|left, right| {
|
||||
left.name
|
||||
.cmp(&right.name)
|
||||
.then_with(|| left.id.cmp(&right.id))
|
||||
});
|
||||
let backend = MiniaudioBackend;
|
||||
let backend_name = backend.backend_name();
|
||||
let devices = backend.list_devices(kind)?;
|
||||
debug!(
|
||||
kind = %audio_device_kind_label(kind),
|
||||
backend = %backend,
|
||||
backend = %backend_name,
|
||||
count = devices.len(),
|
||||
"enumerated audio devices"
|
||||
);
|
||||
@@ -103,7 +78,7 @@ pub fn resolve_device_name(
|
||||
}
|
||||
|
||||
pub struct InputCapture {
|
||||
_device: Device,
|
||||
stream: Box<dyn InputStreamHandle>,
|
||||
data: Arc<Mutex<Vec<i16>>>,
|
||||
stopped: Arc<AtomicBool>,
|
||||
last_peak: Arc<AtomicU16>,
|
||||
@@ -111,72 +86,63 @@ pub struct InputCapture {
|
||||
|
||||
impl InputCapture {
|
||||
pub fn start_recording(device_id: Option<&str>) -> Result<Self, String> {
|
||||
Self::start(device_id, true, None)
|
||||
Self::start_with_backend(&MiniaudioBackend, device_id, true, None::<fn(Vec<i16>)>)
|
||||
}
|
||||
|
||||
pub fn start_streaming<F>(device_id: Option<&str>, callback: F) -> Result<Self, String>
|
||||
where
|
||||
F: FnMut(Vec<i16>) + Send + 'static,
|
||||
{
|
||||
Self::start(
|
||||
device_id,
|
||||
false,
|
||||
Some(Arc::new(Mutex::new(Box::new(callback)))),
|
||||
)
|
||||
Self::start_with_backend(&MiniaudioBackend, device_id, false, Some(callback))
|
||||
}
|
||||
|
||||
fn start(
|
||||
fn start_with_backend<F>(
|
||||
backend: &dyn AudioBackend,
|
||||
device_id: Option<&str>,
|
||||
collect_audio: bool,
|
||||
callback: Option<ChunkCallback>,
|
||||
) -> Result<Self, String> {
|
||||
let context = create_context()?;
|
||||
let backend = backend_label(context.backend());
|
||||
let mut config = DeviceConfig::new(DeviceType::Capture);
|
||||
config.set_sample_rate(AUDIO_SAMPLE_RATE);
|
||||
config.set_period_size_in_frames(PERIOD_SIZE_IN_FRAMES);
|
||||
config.set_resampling(ResampleAlgorithm::Speex {
|
||||
quality: SPEEX_RESAMPLE_QUALITY,
|
||||
});
|
||||
config.capture_mut().set_format(Format::S16);
|
||||
config.capture_mut().set_channels(AUDIO_CHANNELS);
|
||||
if let Some(device_id) = device_id {
|
||||
config
|
||||
.capture_mut()
|
||||
.set_device_id(Some(decode_device_id(device_id)?));
|
||||
}
|
||||
|
||||
callback: Option<F>,
|
||||
) -> Result<Self, String>
|
||||
where
|
||||
F: FnMut(Vec<i16>) + Send + 'static,
|
||||
{
|
||||
let data = Arc::new(Mutex::new(Vec::new()));
|
||||
let stopped = Arc::new(AtomicBool::new(false));
|
||||
let last_peak = Arc::new(AtomicU16::new(0));
|
||||
let request = InputOpenRequest {
|
||||
device_id: device_id.map(ToString::to_string),
|
||||
sample_rate: AUDIO_SAMPLE_RATE,
|
||||
channels: AUDIO_CHANNELS,
|
||||
period_frames: PERIOD_SIZE_IN_FRAMES,
|
||||
};
|
||||
|
||||
let data_for_callback = Arc::clone(&data);
|
||||
let callback_for_callback = callback.clone();
|
||||
let last_peak_for_callback = Arc::clone(&last_peak);
|
||||
config.set_data_callback(move |_device, _output: &mut FramesMut, input: &Frames| {
|
||||
let samples = input.as_samples::<i16>();
|
||||
if samples.is_empty() {
|
||||
return;
|
||||
}
|
||||
|
||||
last_peak_for_callback.store(peak_i16(samples), Ordering::Relaxed);
|
||||
|
||||
if collect_audio && let Ok(mut guard) = data_for_callback.lock() {
|
||||
guard.extend_from_slice(samples);
|
||||
}
|
||||
|
||||
if let Some(callback) = callback_for_callback.as_ref()
|
||||
&& let Ok(mut callback) = callback.lock()
|
||||
{
|
||||
callback(samples.to_vec());
|
||||
}
|
||||
let callback: Option<ChunkCallback> = callback.map(|callback| {
|
||||
Arc::new(Mutex::new(
|
||||
Box::new(callback) as Box<dyn FnMut(Vec<i16>) + Send>
|
||||
))
|
||||
});
|
||||
let data_for_callback = Arc::clone(&data);
|
||||
let last_peak_for_callback = Arc::clone(&last_peak);
|
||||
let chunk_callback = callback.clone();
|
||||
let stream = backend.open_input(
|
||||
&request,
|
||||
Arc::new(move |samples: &[i16]| {
|
||||
if samples.is_empty() {
|
||||
return;
|
||||
}
|
||||
|
||||
let device = Device::new(Some(context), &config)
|
||||
.map_err(|err| format!("failed to open input audio device: {err}"))?;
|
||||
device
|
||||
.start()
|
||||
.map_err(|err| format!("failed to start input audio stream: {err}"))?;
|
||||
last_peak_for_callback.store(peak_i16(samples), Ordering::Relaxed);
|
||||
|
||||
if collect_audio && let Ok(mut guard) = data_for_callback.lock() {
|
||||
guard.extend_from_slice(samples);
|
||||
}
|
||||
|
||||
if let Some(callback) = chunk_callback.as_ref()
|
||||
&& let Ok(mut callback) = callback.lock()
|
||||
{
|
||||
callback(samples.to_vec());
|
||||
}
|
||||
}),
|
||||
)?;
|
||||
|
||||
info!(
|
||||
mode = if collect_audio {
|
||||
@@ -184,7 +150,7 @@ impl InputCapture {
|
||||
} else {
|
||||
"realtime_streaming"
|
||||
},
|
||||
backend = %backend,
|
||||
backend = %backend.backend_name(),
|
||||
device_id = device_id.unwrap_or("system_default"),
|
||||
sample_rate = AUDIO_SAMPLE_RATE,
|
||||
channels = AUDIO_CHANNELS,
|
||||
@@ -193,18 +159,16 @@ impl InputCapture {
|
||||
);
|
||||
|
||||
Ok(Self {
|
||||
_device: device,
|
||||
stream,
|
||||
data,
|
||||
stopped,
|
||||
last_peak,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn stop(self) -> Result<RecordedAudio, String> {
|
||||
pub fn stop(mut self) -> Result<RecordedAudio, String> {
|
||||
self.stopped.store(true, Ordering::SeqCst);
|
||||
self._device
|
||||
.stop()
|
||||
.map_err(|err| format!("failed to stop input audio stream: {err}"))?;
|
||||
self.stream.stop()?;
|
||||
let data = self
|
||||
.data
|
||||
.lock()
|
||||
@@ -252,43 +216,47 @@ impl InputCapture {
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for InputCapture {
|
||||
fn drop(&mut self) {
|
||||
let _ = self.stream.stop();
|
||||
}
|
||||
}
|
||||
|
||||
pub struct OutputPlayback {
|
||||
_device: Device,
|
||||
queue: Arc<Mutex<VecDeque<i16>>>,
|
||||
stream: Box<dyn OutputStreamHandle>,
|
||||
queue: Arc<Mutex<OutputSampleQueue>>,
|
||||
}
|
||||
|
||||
impl OutputPlayback {
|
||||
pub fn start(device_id: Option<&str>) -> Result<Self, String> {
|
||||
let context = create_context()?;
|
||||
let backend = backend_label(context.backend());
|
||||
let mut config = DeviceConfig::new(DeviceType::Playback);
|
||||
config.set_sample_rate(AUDIO_SAMPLE_RATE);
|
||||
config.set_period_size_in_frames(PERIOD_SIZE_IN_FRAMES);
|
||||
config.set_resampling(ResampleAlgorithm::Speex {
|
||||
quality: SPEEX_RESAMPLE_QUALITY,
|
||||
});
|
||||
config.playback_mut().set_format(Format::S16);
|
||||
config.playback_mut().set_channels(AUDIO_CHANNELS);
|
||||
if let Some(device_id) = device_id {
|
||||
config
|
||||
.playback_mut()
|
||||
.set_device_id(Some(decode_device_id(device_id)?));
|
||||
}
|
||||
Self::start_with_backend(&MiniaudioBackend, device_id)
|
||||
}
|
||||
|
||||
let queue = Arc::new(Mutex::new(VecDeque::new()));
|
||||
fn start_with_backend(
|
||||
backend: &dyn AudioBackend,
|
||||
device_id: Option<&str>,
|
||||
) -> Result<Self, String> {
|
||||
let request = OutputOpenRequest {
|
||||
device_id: device_id.map(ToString::to_string),
|
||||
sample_rate: AUDIO_SAMPLE_RATE,
|
||||
channels: AUDIO_CHANNELS,
|
||||
period_frames: PERIOD_SIZE_IN_FRAMES,
|
||||
};
|
||||
let queue = Arc::new(Mutex::new(OutputSampleQueue::new(MAX_OUTPUT_QUEUE_SAMPLES)));
|
||||
let queue_for_callback = Arc::clone(&queue);
|
||||
config.set_data_callback(move |_device, output: &mut FramesMut, _input: &Frames| {
|
||||
fill_output_samples(output, &queue_for_callback);
|
||||
});
|
||||
|
||||
let device = Device::new(Some(context), &config)
|
||||
.map_err(|err| format!("failed to open output audio device: {err}"))?;
|
||||
device
|
||||
.start()
|
||||
.map_err(|err| format!("failed to start output audio stream: {err}"))?;
|
||||
let stream = backend.open_output(
|
||||
&request,
|
||||
Arc::new(move |output: &mut [i16]| {
|
||||
if let Ok(mut guard) = queue_for_callback.lock() {
|
||||
guard.drain_into(output);
|
||||
return;
|
||||
}
|
||||
output.fill(0);
|
||||
}),
|
||||
)?;
|
||||
|
||||
info!(
|
||||
backend = %backend,
|
||||
backend = %backend.backend_name(),
|
||||
device_id = device_id.unwrap_or("system_default"),
|
||||
sample_rate = AUDIO_SAMPLE_RATE,
|
||||
channels = AUDIO_CHANNELS,
|
||||
@@ -296,10 +264,7 @@ impl OutputPlayback {
|
||||
"started output audio stream"
|
||||
);
|
||||
|
||||
Ok(Self {
|
||||
_device: device,
|
||||
queue,
|
||||
})
|
||||
Ok(Self { stream, queue })
|
||||
}
|
||||
|
||||
pub fn enqueue_samples(&self, samples: &[i16]) -> Result<(), String> {
|
||||
@@ -311,83 +276,87 @@ impl OutputPlayback {
|
||||
.queue
|
||||
.lock()
|
||||
.map_err(|_| "failed to lock output audio queue".to_string())?;
|
||||
let overflow = guard
|
||||
.len()
|
||||
.saturating_add(samples.len())
|
||||
.saturating_sub(MAX_OUTPUT_QUEUE_SAMPLES);
|
||||
if overflow > 0 {
|
||||
let current_len = guard.len();
|
||||
guard.drain(..overflow.min(current_len));
|
||||
let queue_len_before = guard.len();
|
||||
let result = guard.enqueue(samples);
|
||||
if result.dropped_samples > 0 {
|
||||
warn!(
|
||||
dropped_samples = overflow.min(current_len),
|
||||
queue_samples_before = current_len,
|
||||
queue_samples_after = guard.len(),
|
||||
dropped_samples = result.dropped_samples,
|
||||
queue_samples_before = queue_len_before,
|
||||
queue_samples_after = result.queue_len_after,
|
||||
max_queue_samples = MAX_OUTPUT_QUEUE_SAMPLES,
|
||||
"trimmed output audio queue due to backlog"
|
||||
);
|
||||
}
|
||||
guard.extend(samples.iter().copied());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn clear(&self) {
|
||||
if let Ok(mut guard) = self.queue.lock() {
|
||||
debug!(cleared_samples = guard.len(), "cleared output audio queue");
|
||||
guard.clear();
|
||||
debug!(
|
||||
cleared_samples = guard.clear(),
|
||||
"cleared output audio queue"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn extend_device_infos(
|
||||
devices: &mut Vec<AudioDeviceInfo>,
|
||||
infos: &[DeviceIdAndName],
|
||||
backend: &str,
|
||||
) {
|
||||
for info in infos {
|
||||
devices.push(AudioDeviceInfo {
|
||||
id: encode_device_id(info.id()),
|
||||
name: info.name().to_string(),
|
||||
backend: backend.to_string(),
|
||||
});
|
||||
impl Drop for OutputPlayback {
|
||||
fn drop(&mut self) {
|
||||
let _ = self.stream.stop();
|
||||
}
|
||||
}
|
||||
|
||||
fn create_context() -> Result<Context, String> {
|
||||
Context::new(preferred_backends(), None)
|
||||
.map_err(|err| format!("failed to initialize audio backend: {err}"))
|
||||
#[derive(Debug)]
|
||||
struct OutputSampleQueue {
|
||||
samples: VecDeque<i16>,
|
||||
max_samples: usize,
|
||||
}
|
||||
|
||||
fn preferred_backends() -> &'static [Backend] {
|
||||
#[cfg(target_os = "linux")]
|
||||
{
|
||||
&[Backend::PulseAudio, Backend::Alsa, Backend::Jack]
|
||||
}
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
&[Backend::CoreAudio]
|
||||
}
|
||||
#[cfg(target_os = "windows")]
|
||||
{
|
||||
&[Backend::Wasapi, Backend::DSound, Backend::WinMM]
|
||||
}
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
struct QueueEnqueueResult {
|
||||
dropped_samples: usize,
|
||||
queue_len_after: usize,
|
||||
}
|
||||
|
||||
fn backend_label(backend: Backend) -> String {
|
||||
match backend {
|
||||
Backend::PulseAudio => "PulseAudio".to_string(),
|
||||
Backend::Alsa => "ALSA".to_string(),
|
||||
Backend::Jack => "JACK".to_string(),
|
||||
Backend::CoreAudio => "CoreAudio".to_string(),
|
||||
Backend::Wasapi => "WASAPI".to_string(),
|
||||
Backend::DSound => "DirectSound".to_string(),
|
||||
Backend::WinMM => "WinMM".to_string(),
|
||||
Backend::SNDIO => "sndio".to_string(),
|
||||
Backend::Audio4 => "audio4".to_string(),
|
||||
Backend::OSS => "OSS".to_string(),
|
||||
Backend::AAudio => "AAudio".to_string(),
|
||||
Backend::OpenSL => "OpenSL".to_string(),
|
||||
Backend::WebAudio => "WebAudio".to_string(),
|
||||
Backend::Null => "Null".to_string(),
|
||||
impl OutputSampleQueue {
|
||||
fn new(max_samples: usize) -> Self {
|
||||
Self {
|
||||
samples: VecDeque::new(),
|
||||
max_samples,
|
||||
}
|
||||
}
|
||||
|
||||
fn enqueue(&mut self, samples: &[i16]) -> QueueEnqueueResult {
|
||||
let dropped_samples = self
|
||||
.samples
|
||||
.len()
|
||||
.saturating_add(samples.len())
|
||||
.saturating_sub(self.max_samples)
|
||||
.min(self.samples.len());
|
||||
if dropped_samples > 0 {
|
||||
self.samples.drain(..dropped_samples);
|
||||
}
|
||||
self.samples.extend(samples.iter().copied());
|
||||
QueueEnqueueResult {
|
||||
dropped_samples,
|
||||
queue_len_after: self.samples.len(),
|
||||
}
|
||||
}
|
||||
|
||||
fn drain_into(&mut self, output: &mut [i16]) {
|
||||
for sample in output {
|
||||
*sample = self.samples.pop_front().unwrap_or(0);
|
||||
}
|
||||
}
|
||||
|
||||
fn clear(&mut self) -> usize {
|
||||
let cleared = self.samples.len();
|
||||
self.samples.clear();
|
||||
cleared
|
||||
}
|
||||
|
||||
fn len(&self) -> usize {
|
||||
self.samples.len()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -398,17 +367,17 @@ fn audio_device_kind_label(kind: AudioDeviceKind) -> &'static str {
|
||||
}
|
||||
}
|
||||
|
||||
fn encode_device_id(device_id: &DeviceId) -> String {
|
||||
fn encode_device_id(device_id: &miniaudio::DeviceId) -> String {
|
||||
hex_encode(device_id_bytes(device_id))
|
||||
}
|
||||
|
||||
fn decode_device_id(encoded: &str) -> Result<DeviceId, String> {
|
||||
fn decode_device_id(encoded: &str) -> Result<miniaudio::DeviceId, String> {
|
||||
let bytes = hex_decode(encoded)?;
|
||||
if bytes.len() != std::mem::size_of::<DeviceId>() {
|
||||
if bytes.len() != std::mem::size_of::<miniaudio::DeviceId>() {
|
||||
return Err("invalid persisted audio device id".to_string());
|
||||
}
|
||||
|
||||
let mut device_id = MaybeUninit::<DeviceId>::uninit();
|
||||
let mut device_id = MaybeUninit::<miniaudio::DeviceId>::uninit();
|
||||
unsafe {
|
||||
std::ptr::copy_nonoverlapping(
|
||||
bytes.as_ptr(),
|
||||
@@ -419,26 +388,15 @@ fn decode_device_id(encoded: &str) -> Result<DeviceId, String> {
|
||||
}
|
||||
}
|
||||
|
||||
fn device_id_bytes(device_id: &DeviceId) -> &[u8] {
|
||||
fn device_id_bytes(device_id: &miniaudio::DeviceId) -> &[u8] {
|
||||
unsafe {
|
||||
std::slice::from_raw_parts(
|
||||
(device_id as *const DeviceId).cast::<u8>(),
|
||||
std::mem::size_of::<DeviceId>(),
|
||||
(device_id as *const miniaudio::DeviceId).cast::<u8>(),
|
||||
std::mem::size_of::<miniaudio::DeviceId>(),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
fn fill_output_samples(output: &mut FramesMut, queue: &Arc<Mutex<VecDeque<i16>>>) {
|
||||
let output_samples = output.as_samples_mut::<i16>();
|
||||
if let Ok(mut guard) = queue.lock() {
|
||||
for sample in output_samples {
|
||||
*sample = guard.pop_front().unwrap_or(0);
|
||||
}
|
||||
return;
|
||||
}
|
||||
output_samples.fill(0);
|
||||
}
|
||||
|
||||
fn peak_i16(samples: &[i16]) -> u16 {
|
||||
let mut peak: i32 = 0;
|
||||
for &sample in samples {
|
||||
@@ -488,21 +446,352 @@ fn decode_hex_nibble(byte: u8) -> Result<u8, String> {
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::hex_decode;
|
||||
use super::hex_encode;
|
||||
use super::AUDIO_CHANNELS;
|
||||
use super::AUDIO_SAMPLE_RATE;
|
||||
use super::AudioDeviceInfo;
|
||||
use super::AudioDeviceKind;
|
||||
use super::InputCapture;
|
||||
use super::OutputPlayback;
|
||||
use super::OutputSampleQueue;
|
||||
use super::PERIOD_SIZE_IN_FRAMES;
|
||||
use super::QueueEnqueueResult;
|
||||
use super::RecordedAudio;
|
||||
use super::backend::AudioBackend;
|
||||
use super::backend::InputDataCallback;
|
||||
use super::backend::InputOpenRequest;
|
||||
use super::backend::InputStreamHandle;
|
||||
use super::backend::OutputDataCallback;
|
||||
use super::backend::OutputOpenRequest;
|
||||
use super::backend::OutputStreamHandle;
|
||||
use pretty_assertions::assert_eq;
|
||||
use std::sync::Arc;
|
||||
use std::sync::Mutex;
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
struct FakeOpenRequest {
|
||||
device_id: Option<String>,
|
||||
sample_rate: u32,
|
||||
channels: u32,
|
||||
period_frames: u32,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct FakeAudioBackend {
|
||||
state: Mutex<FakeAudioBackendState>,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct FakeAudioBackendState {
|
||||
input_devices: Vec<AudioDeviceInfo>,
|
||||
output_devices: Vec<AudioDeviceInfo>,
|
||||
input_open_requests: Vec<FakeOpenRequest>,
|
||||
output_open_requests: Vec<FakeOpenRequest>,
|
||||
next_input_error: Option<String>,
|
||||
next_output_error: Option<String>,
|
||||
input_callbacks: Vec<InputDataCallback>,
|
||||
output_callbacks: Vec<OutputDataCallback>,
|
||||
}
|
||||
|
||||
impl FakeAudioBackend {
|
||||
fn with_devices(
|
||||
input_devices: Vec<AudioDeviceInfo>,
|
||||
output_devices: Vec<AudioDeviceInfo>,
|
||||
) -> Self {
|
||||
Self {
|
||||
state: Mutex::new(FakeAudioBackendState {
|
||||
input_devices,
|
||||
output_devices,
|
||||
..FakeAudioBackendState::default()
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
fn push_capture_samples(&self, samples: &[i16]) {
|
||||
let callbacks = self
|
||||
.state
|
||||
.lock()
|
||||
.expect("backend state")
|
||||
.input_callbacks
|
||||
.clone();
|
||||
for callback in callbacks {
|
||||
callback(samples);
|
||||
}
|
||||
}
|
||||
|
||||
fn drain_playback(&self, len: usize) -> Vec<i16> {
|
||||
let callbacks = self
|
||||
.state
|
||||
.lock()
|
||||
.expect("backend state")
|
||||
.output_callbacks
|
||||
.clone();
|
||||
let mut output = vec![0; len];
|
||||
for callback in callbacks {
|
||||
callback(&mut output);
|
||||
}
|
||||
output
|
||||
}
|
||||
|
||||
fn fail_next_input_open(&self, error: &str) {
|
||||
self.state.lock().expect("backend state").next_input_error = Some(error.to_string());
|
||||
}
|
||||
|
||||
fn input_open_requests(&self) -> Vec<FakeOpenRequest> {
|
||||
self.state
|
||||
.lock()
|
||||
.expect("backend state")
|
||||
.input_open_requests
|
||||
.clone()
|
||||
}
|
||||
|
||||
fn output_open_requests(&self) -> Vec<FakeOpenRequest> {
|
||||
self.state
|
||||
.lock()
|
||||
.expect("backend state")
|
||||
.output_open_requests
|
||||
.clone()
|
||||
}
|
||||
}
|
||||
|
||||
impl AudioBackend for FakeAudioBackend {
|
||||
fn backend_name(&self) -> String {
|
||||
"FakeAudio".to_string()
|
||||
}
|
||||
|
||||
fn list_devices(&self, kind: AudioDeviceKind) -> Result<Vec<AudioDeviceInfo>, String> {
|
||||
let state = self.state.lock().expect("backend state");
|
||||
Ok(match kind {
|
||||
AudioDeviceKind::Input => state.input_devices.clone(),
|
||||
AudioDeviceKind::Output => state.output_devices.clone(),
|
||||
})
|
||||
}
|
||||
|
||||
fn open_input(
|
||||
&self,
|
||||
request: &InputOpenRequest,
|
||||
callback: InputDataCallback,
|
||||
) -> Result<Box<dyn InputStreamHandle>, String> {
|
||||
let mut state = self.state.lock().expect("backend state");
|
||||
if let Some(error) = state.next_input_error.take() {
|
||||
return Err(error);
|
||||
}
|
||||
state.input_open_requests.push(FakeOpenRequest {
|
||||
device_id: request.device_id.clone(),
|
||||
sample_rate: request.sample_rate,
|
||||
channels: request.channels,
|
||||
period_frames: request.period_frames,
|
||||
});
|
||||
state.input_callbacks.push(callback);
|
||||
Ok(Box::new(FakeInputStream))
|
||||
}
|
||||
|
||||
fn open_output(
|
||||
&self,
|
||||
request: &OutputOpenRequest,
|
||||
callback: OutputDataCallback,
|
||||
) -> Result<Box<dyn OutputStreamHandle>, String> {
|
||||
let mut state = self.state.lock().expect("backend state");
|
||||
if let Some(error) = state.next_output_error.take() {
|
||||
return Err(error);
|
||||
}
|
||||
state.output_open_requests.push(FakeOpenRequest {
|
||||
device_id: request.device_id.clone(),
|
||||
sample_rate: request.sample_rate,
|
||||
channels: request.channels,
|
||||
period_frames: request.period_frames,
|
||||
});
|
||||
state.output_callbacks.push(callback);
|
||||
Ok(Box::new(FakeOutputStream {
|
||||
state: Arc::new(Mutex::new(())),
|
||||
}))
|
||||
}
|
||||
}
|
||||
|
||||
struct FakeInputStream;
|
||||
|
||||
impl InputStreamHandle for FakeInputStream {
|
||||
fn stop(&mut self) -> Result<(), String> {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
struct FakeOutputStream {
|
||||
state: Arc<Mutex<()>>,
|
||||
}
|
||||
|
||||
impl OutputStreamHandle for FakeOutputStream {
|
||||
fn stop(&mut self) -> Result<(), String> {
|
||||
let _guard = self.state.lock().expect("output stream state");
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hex_round_trip() {
|
||||
let bytes = [0x00, 0x10, 0xab, 0xff];
|
||||
let encoded = hex_encode(&bytes);
|
||||
let encoded = super::hex_encode(&bytes);
|
||||
assert_eq!(encoded, "0010abff");
|
||||
assert_eq!(hex_decode(&encoded).expect("hex decode"), bytes);
|
||||
assert_eq!(super::hex_decode(&encoded).expect("hex decode"), bytes);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hex_decode_rejects_invalid_input() {
|
||||
assert!(hex_decode("abc").is_err());
|
||||
assert!(hex_decode("zz").is_err());
|
||||
assert!(super::hex_decode("abc").is_err());
|
||||
assert!(super::hex_decode("zz").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn output_sample_queue_trims_oldest_samples() {
|
||||
let mut queue = OutputSampleQueue::new(4);
|
||||
let initial = queue.enqueue(&[1, 2, 3]);
|
||||
let overflow = queue.enqueue(&[4, 5, 6]);
|
||||
|
||||
assert_eq!(
|
||||
initial,
|
||||
QueueEnqueueResult {
|
||||
dropped_samples: 0,
|
||||
queue_len_after: 3,
|
||||
}
|
||||
);
|
||||
assert_eq!(
|
||||
overflow,
|
||||
QueueEnqueueResult {
|
||||
dropped_samples: 2,
|
||||
queue_len_after: 4,
|
||||
}
|
||||
);
|
||||
|
||||
let mut output = [0; 4];
|
||||
queue.drain_into(&mut output);
|
||||
assert_eq!(output, [3, 4, 5, 6]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn output_sample_queue_zero_fills_on_underrun() {
|
||||
let mut queue = OutputSampleQueue::new(8);
|
||||
queue.enqueue(&[11, 22]);
|
||||
|
||||
let mut output = [0; 4];
|
||||
queue.drain_into(&mut output);
|
||||
|
||||
assert_eq!(output, [11, 22, 0, 0]);
|
||||
assert_eq!(queue.len(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn output_sample_queue_clear_returns_cleared_count() {
|
||||
let mut queue = OutputSampleQueue::new(8);
|
||||
queue.enqueue(&[1, 2, 3, 4]);
|
||||
|
||||
assert_eq!(queue.clear(), 4);
|
||||
assert_eq!(queue.len(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn peak_i16_handles_negative_samples() {
|
||||
assert_eq!(super::peak_i16(&[-7, 3, -200, 1]), 200);
|
||||
assert_eq!(super::peak_i16(&[i16::MIN]), i16::MAX as u16 + 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fake_backend_records_input_request_and_collects_audio() {
|
||||
let backend = FakeAudioBackend::with_devices(
|
||||
vec![AudioDeviceInfo {
|
||||
id: "usb-mic".to_string(),
|
||||
name: "USB Mic".to_string(),
|
||||
backend: "FakeAudio".to_string(),
|
||||
}],
|
||||
Vec::new(),
|
||||
);
|
||||
let capture =
|
||||
InputCapture::start_with_backend(&backend, Some("usb-mic"), true, None::<fn(Vec<i16>)>)
|
||||
.expect("capture should start");
|
||||
|
||||
backend.push_capture_samples(&[1, -2, 3, -4]);
|
||||
let recorded = capture.stop().expect("capture should stop");
|
||||
|
||||
assert_eq!(
|
||||
backend.input_open_requests(),
|
||||
vec![FakeOpenRequest {
|
||||
device_id: Some("usb-mic".to_string()),
|
||||
sample_rate: AUDIO_SAMPLE_RATE,
|
||||
channels: AUDIO_CHANNELS,
|
||||
period_frames: PERIOD_SIZE_IN_FRAMES,
|
||||
}]
|
||||
);
|
||||
assert_eq!(
|
||||
recorded,
|
||||
RecordedAudio {
|
||||
data: vec![1, -2, 3, -4],
|
||||
sample_rate: AUDIO_SAMPLE_RATE,
|
||||
channels: AUDIO_CHANNELS as u16,
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fake_backend_streaming_callback_receives_samples() {
|
||||
let backend = FakeAudioBackend::default();
|
||||
let streamed = Arc::new(Mutex::new(Vec::new()));
|
||||
let streamed_for_callback = Arc::clone(&streamed);
|
||||
let capture = InputCapture::start_with_backend(
|
||||
&backend,
|
||||
None,
|
||||
false,
|
||||
Some(move |samples| {
|
||||
streamed_for_callback
|
||||
.lock()
|
||||
.expect("streamed samples")
|
||||
.extend(samples);
|
||||
}),
|
||||
)
|
||||
.expect("streaming capture should start");
|
||||
|
||||
backend.push_capture_samples(&[10, 20, 30]);
|
||||
let _ = capture.stop().expect("capture should stop");
|
||||
|
||||
assert_eq!(
|
||||
streamed.lock().expect("streamed samples").as_slice(),
|
||||
[10, 20, 30]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fake_backend_input_open_failure_surfaces() {
|
||||
let backend = FakeAudioBackend::default();
|
||||
backend.fail_next_input_open("input failed");
|
||||
|
||||
let err = InputCapture::start_with_backend(&backend, None, true, None::<fn(Vec<i16>)>);
|
||||
|
||||
assert_eq!(err.err().as_deref(), Some("input failed"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fake_backend_records_output_request_and_drains_playback() {
|
||||
let backend = FakeAudioBackend::with_devices(
|
||||
Vec::new(),
|
||||
vec![AudioDeviceInfo {
|
||||
id: "desk-speakers".to_string(),
|
||||
name: "Desk Speakers".to_string(),
|
||||
backend: "FakeAudio".to_string(),
|
||||
}],
|
||||
);
|
||||
let playback = OutputPlayback::start_with_backend(&backend, Some("desk-speakers"))
|
||||
.expect("playback should start");
|
||||
|
||||
playback
|
||||
.enqueue_samples(&[7, 8, 9])
|
||||
.expect("enqueue should succeed");
|
||||
|
||||
assert_eq!(
|
||||
backend.output_open_requests(),
|
||||
vec![FakeOpenRequest {
|
||||
device_id: Some("desk-speakers".to_string()),
|
||||
sample_rate: AUDIO_SAMPLE_RATE,
|
||||
channels: AUDIO_CHANNELS,
|
||||
period_frames: PERIOD_SIZE_IN_FRAMES,
|
||||
}]
|
||||
);
|
||||
assert_eq!(backend.drain_playback(4), vec![7, 8, 9, 0]);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,208 @@
|
||||
use crate::AudioDeviceInfo;
|
||||
use crate::AudioDeviceKind;
|
||||
use crate::backend::AudioBackend;
|
||||
use crate::backend::InputDataCallback;
|
||||
use crate::backend::InputOpenRequest;
|
||||
use crate::backend::InputStreamHandle;
|
||||
use crate::backend::OutputDataCallback;
|
||||
use crate::backend::OutputOpenRequest;
|
||||
use crate::backend::OutputStreamHandle;
|
||||
use crate::decode_device_id;
|
||||
use miniaudio::Backend;
|
||||
use miniaudio::Context;
|
||||
use miniaudio::Device;
|
||||
use miniaudio::DeviceConfig;
|
||||
use miniaudio::DeviceIdAndName;
|
||||
use miniaudio::DeviceType;
|
||||
use miniaudio::Format;
|
||||
use miniaudio::Frames;
|
||||
use miniaudio::FramesMut;
|
||||
use miniaudio::ResampleAlgorithm;
|
||||
|
||||
pub(crate) struct MiniaudioBackend;
|
||||
|
||||
impl AudioBackend for MiniaudioBackend {
|
||||
fn backend_name(&self) -> String {
|
||||
match create_context() {
|
||||
Ok(context) => backend_label(context.backend()),
|
||||
Err(_) => "Unknown".to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
fn list_devices(&self, kind: AudioDeviceKind) -> Result<Vec<AudioDeviceInfo>, String> {
|
||||
let context = create_context()?;
|
||||
let backend = backend_label(context.backend());
|
||||
let mut devices = Vec::new();
|
||||
|
||||
match kind {
|
||||
AudioDeviceKind::Input => {
|
||||
context
|
||||
.with_capture_devices(|infos| {
|
||||
extend_device_infos(&mut devices, infos, backend.as_str());
|
||||
})
|
||||
.map_err(|err| format!("failed to enumerate input audio devices: {err}"))?;
|
||||
}
|
||||
AudioDeviceKind::Output => {
|
||||
context
|
||||
.with_playback_devices(|infos| {
|
||||
extend_device_infos(&mut devices, infos, backend.as_str());
|
||||
})
|
||||
.map_err(|err| format!("failed to enumerate output audio devices: {err}"))?;
|
||||
}
|
||||
}
|
||||
|
||||
devices.sort_by(|left, right| {
|
||||
left.name
|
||||
.cmp(&right.name)
|
||||
.then_with(|| left.id.cmp(&right.id))
|
||||
});
|
||||
Ok(devices)
|
||||
}
|
||||
|
||||
fn open_input(
|
||||
&self,
|
||||
request: &InputOpenRequest,
|
||||
callback: InputDataCallback,
|
||||
) -> Result<Box<dyn InputStreamHandle>, String> {
|
||||
let context = create_context()?;
|
||||
let mut config = DeviceConfig::new(DeviceType::Capture);
|
||||
config.set_sample_rate(request.sample_rate);
|
||||
config.set_period_size_in_frames(request.period_frames);
|
||||
config.set_resampling(ResampleAlgorithm::Speex {
|
||||
quality: crate::SPEEX_RESAMPLE_QUALITY,
|
||||
});
|
||||
config.capture_mut().set_format(Format::S16);
|
||||
config.capture_mut().set_channels(request.channels);
|
||||
if let Some(device_id) = request.device_id.as_deref() {
|
||||
config
|
||||
.capture_mut()
|
||||
.set_device_id(Some(decode_device_id(device_id)?));
|
||||
}
|
||||
|
||||
let data_callback = callback.clone();
|
||||
config.set_data_callback(move |_device, _output: &mut FramesMut, input: &Frames| {
|
||||
let samples = input.as_samples::<i16>();
|
||||
if samples.is_empty() {
|
||||
return;
|
||||
}
|
||||
data_callback(samples);
|
||||
});
|
||||
|
||||
let device = Device::new(Some(context), &config)
|
||||
.map_err(|err| format!("failed to open input audio device: {err}"))?;
|
||||
device
|
||||
.start()
|
||||
.map_err(|err| format!("failed to start input audio stream: {err}"))?;
|
||||
Ok(Box::new(MiniaudioInputStream { device }))
|
||||
}
|
||||
|
||||
fn open_output(
|
||||
&self,
|
||||
request: &OutputOpenRequest,
|
||||
callback: OutputDataCallback,
|
||||
) -> Result<Box<dyn OutputStreamHandle>, String> {
|
||||
let context = create_context()?;
|
||||
let mut config = DeviceConfig::new(DeviceType::Playback);
|
||||
config.set_sample_rate(request.sample_rate);
|
||||
config.set_period_size_in_frames(request.period_frames);
|
||||
config.set_resampling(ResampleAlgorithm::Speex {
|
||||
quality: crate::SPEEX_RESAMPLE_QUALITY,
|
||||
});
|
||||
config.playback_mut().set_format(Format::S16);
|
||||
config.playback_mut().set_channels(request.channels);
|
||||
if let Some(device_id) = request.device_id.as_deref() {
|
||||
config
|
||||
.playback_mut()
|
||||
.set_device_id(Some(decode_device_id(device_id)?));
|
||||
}
|
||||
|
||||
let data_callback = callback.clone();
|
||||
config.set_data_callback(move |_device, output: &mut FramesMut, _input: &Frames| {
|
||||
data_callback(output.as_samples_mut::<i16>());
|
||||
});
|
||||
|
||||
let device = Device::new(Some(context), &config)
|
||||
.map_err(|err| format!("failed to open output audio device: {err}"))?;
|
||||
device
|
||||
.start()
|
||||
.map_err(|err| format!("failed to start output audio stream: {err}"))?;
|
||||
Ok(Box::new(MiniaudioOutputStream { device }))
|
||||
}
|
||||
}
|
||||
|
||||
struct MiniaudioInputStream {
|
||||
device: Device,
|
||||
}
|
||||
|
||||
impl InputStreamHandle for MiniaudioInputStream {
|
||||
fn stop(&mut self) -> Result<(), String> {
|
||||
self.device
|
||||
.stop()
|
||||
.map_err(|err| format!("failed to stop input audio stream: {err}"))
|
||||
}
|
||||
}
|
||||
|
||||
struct MiniaudioOutputStream {
|
||||
device: Device,
|
||||
}
|
||||
|
||||
impl OutputStreamHandle for MiniaudioOutputStream {
|
||||
fn stop(&mut self) -> Result<(), String> {
|
||||
self.device
|
||||
.stop()
|
||||
.map_err(|err| format!("failed to stop output audio stream: {err}"))
|
||||
}
|
||||
}
|
||||
|
||||
fn extend_device_infos(
|
||||
devices: &mut Vec<AudioDeviceInfo>,
|
||||
infos: &[DeviceIdAndName],
|
||||
backend: &str,
|
||||
) {
|
||||
for info in infos {
|
||||
devices.push(AudioDeviceInfo {
|
||||
id: crate::encode_device_id(info.id()),
|
||||
name: info.name().to_string(),
|
||||
backend: backend.to_string(),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
fn create_context() -> Result<Context, String> {
|
||||
Context::new(preferred_backends(), None)
|
||||
.map_err(|err| format!("failed to initialize audio backend: {err}"))
|
||||
}
|
||||
|
||||
fn preferred_backends() -> &'static [Backend] {
|
||||
#[cfg(target_os = "linux")]
|
||||
{
|
||||
&[Backend::PulseAudio, Backend::Alsa, Backend::Jack]
|
||||
}
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
&[Backend::CoreAudio]
|
||||
}
|
||||
#[cfg(target_os = "windows")]
|
||||
{
|
||||
&[Backend::Wasapi, Backend::DSound, Backend::WinMM]
|
||||
}
|
||||
}
|
||||
|
||||
fn backend_label(backend: Backend) -> String {
|
||||
match backend {
|
||||
Backend::PulseAudio => "PulseAudio".to_string(),
|
||||
Backend::Alsa => "ALSA".to_string(),
|
||||
Backend::Jack => "JACK".to_string(),
|
||||
Backend::CoreAudio => "CoreAudio".to_string(),
|
||||
Backend::Wasapi => "WASAPI".to_string(),
|
||||
Backend::DSound => "DirectSound".to_string(),
|
||||
Backend::WinMM => "WinMM".to_string(),
|
||||
Backend::SNDIO => "sndio".to_string(),
|
||||
Backend::Audio4 => "audio4".to_string(),
|
||||
Backend::OSS => "OSS".to_string(),
|
||||
Backend::AAudio => "AAudio".to_string(),
|
||||
Backend::OpenSL => "OpenSL".to_string(),
|
||||
Backend::WebAudio => "WebAudio".to_string(),
|
||||
Backend::Null => "Null".to_string(),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
mod support;
|
||||
|
||||
use codex_audio::AudioDeviceKind;
|
||||
use codex_audio::InputCapture;
|
||||
use codex_audio::OutputPlayback;
|
||||
use codex_audio::list_audio_devices;
|
||||
use pretty_assertions::assert_eq;
|
||||
use serial_test::serial;
|
||||
|
||||
#[test]
|
||||
#[serial]
|
||||
fn enumerates_input_devices_without_error() {
|
||||
if let Err(error) = list_audio_devices(AudioDeviceKind::Input) {
|
||||
support::skip_without_backend(AudioDeviceKind::Input, &error);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[serial]
|
||||
fn enumerates_output_devices_without_error() {
|
||||
if let Err(error) = list_audio_devices(AudioDeviceKind::Output) {
|
||||
support::skip_without_backend(AudioDeviceKind::Output, &error);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[serial]
|
||||
fn opens_explicit_input_device_when_available() {
|
||||
let Some(device_id) = support::first_device_id(AudioDeviceKind::Input) else {
|
||||
support::skip_without_device(AudioDeviceKind::Input);
|
||||
return;
|
||||
};
|
||||
|
||||
let capture =
|
||||
InputCapture::start_recording(Some(&device_id)).expect("explicit input device should open");
|
||||
let recorded = capture.stop().expect("explicit input device should stop");
|
||||
|
||||
assert_eq!(recorded.sample_rate, codex_audio::AUDIO_SAMPLE_RATE);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[serial]
|
||||
fn opens_explicit_output_device_when_available() {
|
||||
let Some(device_id) = support::first_device_id(AudioDeviceKind::Output) else {
|
||||
support::skip_without_device(AudioDeviceKind::Output);
|
||||
return;
|
||||
};
|
||||
|
||||
let playback =
|
||||
OutputPlayback::start(Some(&device_id)).expect("explicit output device should open");
|
||||
playback
|
||||
.enqueue_samples(&[1, 2, 3, 4])
|
||||
.expect("enqueue should succeed");
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
use codex_audio::AudioDeviceKind;
|
||||
use codex_audio::list_audio_devices;
|
||||
|
||||
pub(crate) fn first_device_id(kind: AudioDeviceKind) -> Option<String> {
|
||||
match list_audio_devices(kind) {
|
||||
Ok(devices) => devices.into_iter().next().map(|device| device.id),
|
||||
Err(_) => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn skip_without_device(kind: AudioDeviceKind) {
|
||||
let label = match kind {
|
||||
AudioDeviceKind::Input => "input",
|
||||
AudioDeviceKind::Output => "output",
|
||||
};
|
||||
eprintln!("skipping host audio smoke test: no {label} device available");
|
||||
}
|
||||
|
||||
pub(crate) fn skip_without_backend(kind: AudioDeviceKind, error: &str) {
|
||||
let label = match kind {
|
||||
AudioDeviceKind::Input => "input",
|
||||
AudioDeviceKind::Output => "output",
|
||||
};
|
||||
eprintln!("skipping host audio smoke test: could not enumerate {label} devices: {error}");
|
||||
}
|
||||
@@ -6091,6 +6091,32 @@ async fn realtime_audio_picker_emits_persist_event() {
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(feature = "voice-input")]
|
||||
#[tokio::test]
|
||||
async fn realtime_audio_picker_can_reset_to_system_default() {
|
||||
let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(Some("gpt-5.2-codex")).await;
|
||||
chat.config.realtime_audio.output_device_id = Some("desk-speakers".to_string());
|
||||
chat.open_realtime_audio_device_selection_with_names(
|
||||
RealtimeAudioDeviceKind::Speaker,
|
||||
vec![AudioDeviceInfo {
|
||||
id: "desk-speakers".to_string(),
|
||||
name: "Desk Speakers".to_string(),
|
||||
backend: "WASAPI".to_string(),
|
||||
}],
|
||||
);
|
||||
|
||||
chat.handle_key_event(KeyEvent::new(KeyCode::Up, KeyModifiers::NONE));
|
||||
chat.handle_key_event(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE));
|
||||
|
||||
assert_matches!(
|
||||
rx.try_recv(),
|
||||
Ok(AppEvent::PersistRealtimeAudioDeviceSelection {
|
||||
kind: RealtimeAudioDeviceKind::Speaker,
|
||||
device_id: None,
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn model_picker_hides_show_in_picker_false_models_from_cache() {
|
||||
let (mut chat, _rx, _op_rx) = make_chatwidget_manual(Some("test-visible-model")).await;
|
||||
|
||||
+176
-45
@@ -224,24 +224,7 @@ fn send_realtime_audio_chunk(tx: &AppEventSender, samples: Vec<i16>) {
|
||||
return;
|
||||
}
|
||||
|
||||
let mut bytes = Vec::with_capacity(samples.len() * 2);
|
||||
for sample in &samples {
|
||||
bytes.extend_from_slice(&sample.to_le_bytes());
|
||||
}
|
||||
|
||||
let encoded = base64::engine::general_purpose::STANDARD.encode(bytes);
|
||||
let samples_per_channel = (samples.len() / usize::from(MODEL_AUDIO_CHANNELS)) as u32;
|
||||
|
||||
tx.send(AppEvent::CodexOp(Op::RealtimeConversationAudio(
|
||||
ConversationAudioParams {
|
||||
frame: RealtimeAudioFrame {
|
||||
data: encoded,
|
||||
sample_rate: MODEL_AUDIO_SAMPLE_RATE,
|
||||
num_channels: MODEL_AUDIO_CHANNELS,
|
||||
samples_per_channel: Some(samples_per_channel),
|
||||
},
|
||||
},
|
||||
)));
|
||||
tx.send(AppEvent::CodexOp(build_realtime_audio_op(&samples)));
|
||||
}
|
||||
|
||||
pub(crate) struct RealtimeAudioPlayer {
|
||||
@@ -264,33 +247,7 @@ impl RealtimeAudioPlayer {
|
||||
}
|
||||
|
||||
pub(crate) fn enqueue_frame(&self, frame: &RealtimeAudioFrame) -> Result<(), String> {
|
||||
if frame.num_channels != MODEL_AUDIO_CHANNELS
|
||||
|| frame.sample_rate != MODEL_AUDIO_SAMPLE_RATE
|
||||
{
|
||||
warn!(
|
||||
sample_rate = frame.sample_rate,
|
||||
num_channels = frame.num_channels,
|
||||
expected_sample_rate = MODEL_AUDIO_SAMPLE_RATE,
|
||||
expected_channels = MODEL_AUDIO_CHANNELS,
|
||||
"received unexpected realtime audio format"
|
||||
);
|
||||
return Err(format!(
|
||||
"unexpected realtime audio format: {} Hz / {} channels",
|
||||
frame.sample_rate, frame.num_channels
|
||||
));
|
||||
}
|
||||
|
||||
let raw_bytes = base64::engine::general_purpose::STANDARD
|
||||
.decode(&frame.data)
|
||||
.map_err(|e| format!("failed to decode realtime audio: {e}"))?;
|
||||
if raw_bytes.len() % 2 != 0 {
|
||||
return Err("realtime audio frame had odd byte length".to_string());
|
||||
}
|
||||
|
||||
let mut pcm = Vec::with_capacity(raw_bytes.len() / 2);
|
||||
for pair in raw_bytes.chunks_exact(2) {
|
||||
pcm.push(i16::from_le_bytes([pair[0], pair[1]]));
|
||||
}
|
||||
let pcm = decode_realtime_audio_frame(frame)?;
|
||||
self.playback.enqueue_samples(&pcm)
|
||||
}
|
||||
|
||||
@@ -309,6 +266,54 @@ fn clip_duration_seconds(audio: &RecordedAudio) -> f32 {
|
||||
}
|
||||
}
|
||||
|
||||
fn build_realtime_audio_op(samples: &[i16]) -> Op {
|
||||
let mut bytes = Vec::with_capacity(samples.len() * 2);
|
||||
for sample in samples {
|
||||
bytes.extend_from_slice(&sample.to_le_bytes());
|
||||
}
|
||||
|
||||
let encoded = base64::engine::general_purpose::STANDARD.encode(bytes);
|
||||
let samples_per_channel = (samples.len() / usize::from(MODEL_AUDIO_CHANNELS)) as u32;
|
||||
|
||||
Op::RealtimeConversationAudio(ConversationAudioParams {
|
||||
frame: RealtimeAudioFrame {
|
||||
data: encoded,
|
||||
sample_rate: MODEL_AUDIO_SAMPLE_RATE,
|
||||
num_channels: MODEL_AUDIO_CHANNELS,
|
||||
samples_per_channel: Some(samples_per_channel),
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
fn decode_realtime_audio_frame(frame: &RealtimeAudioFrame) -> Result<Vec<i16>, String> {
|
||||
if frame.num_channels != MODEL_AUDIO_CHANNELS || frame.sample_rate != MODEL_AUDIO_SAMPLE_RATE {
|
||||
warn!(
|
||||
sample_rate = frame.sample_rate,
|
||||
num_channels = frame.num_channels,
|
||||
expected_sample_rate = MODEL_AUDIO_SAMPLE_RATE,
|
||||
expected_channels = MODEL_AUDIO_CHANNELS,
|
||||
"received unexpected realtime audio format"
|
||||
);
|
||||
return Err(format!(
|
||||
"unexpected realtime audio format: {} Hz / {} channels",
|
||||
frame.sample_rate, frame.num_channels
|
||||
));
|
||||
}
|
||||
|
||||
let raw_bytes = base64::engine::general_purpose::STANDARD
|
||||
.decode(&frame.data)
|
||||
.map_err(|e| format!("failed to decode realtime audio: {e}"))?;
|
||||
if raw_bytes.len() % 2 != 0 {
|
||||
return Err("realtime audio frame had odd byte length".to_string());
|
||||
}
|
||||
|
||||
let mut pcm = Vec::with_capacity(raw_bytes.len() / 2);
|
||||
for pair in raw_bytes.chunks_exact(2) {
|
||||
pcm.push(i16::from_le_bytes([pair[0], pair[1]]));
|
||||
}
|
||||
Ok(pcm)
|
||||
}
|
||||
|
||||
fn encode_wav_normalized(audio: &RecordedAudio) -> Result<Vec<u8>, String> {
|
||||
if audio.channels != MODEL_AUDIO_CHANNELS || audio.sample_rate != MODEL_AUDIO_SAMPLE_RATE {
|
||||
return Err(format!(
|
||||
@@ -495,9 +500,20 @@ async fn transcribe_bytes(
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::RecordedAudio;
|
||||
use super::build_realtime_audio_op;
|
||||
use super::decode_realtime_audio_frame;
|
||||
use super::encode_wav_normalized;
|
||||
use super::transcribe_async;
|
||||
use crate::app_event::AppEvent;
|
||||
use crate::app_event_sender::AppEventSender;
|
||||
use assert_matches::assert_matches;
|
||||
use base64::Engine;
|
||||
use codex_protocol::protocol::ConversationAudioParams;
|
||||
use codex_protocol::protocol::Op;
|
||||
use codex_protocol::protocol::RealtimeAudioFrame;
|
||||
use pretty_assertions::assert_eq;
|
||||
use std::io::Cursor;
|
||||
use tokio::sync::mpsc::unbounded_channel;
|
||||
|
||||
#[test]
|
||||
fn encode_wav_normalized_outputs_24khz_mono_audio() {
|
||||
@@ -519,4 +535,119 @@ mod tests {
|
||||
assert_eq!(spec.sample_rate, 24_000);
|
||||
assert_eq!(samples, vec![7_373, 22_118, 14_745, 29_490]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn encode_wav_normalized_rejects_wrong_format() {
|
||||
let audio = RecordedAudio {
|
||||
data: vec![1, 2, 3, 4],
|
||||
sample_rate: 44_100,
|
||||
channels: 2,
|
||||
};
|
||||
|
||||
let err = encode_wav_normalized(&audio).expect_err("wrong format should fail");
|
||||
assert_eq!(
|
||||
err,
|
||||
"unexpected recorded audio format: 44100 Hz / 2 channels"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn build_realtime_audio_op_encodes_pcm16_frame() {
|
||||
let op = build_realtime_audio_op(&[1, -2, 3, -4]);
|
||||
|
||||
let Op::RealtimeConversationAudio(ConversationAudioParams { frame }) = op else {
|
||||
panic!("expected realtime audio op");
|
||||
};
|
||||
|
||||
assert_eq!(frame.sample_rate, 24_000);
|
||||
assert_eq!(frame.num_channels, 1);
|
||||
assert_eq!(frame.samples_per_channel, Some(4));
|
||||
assert_eq!(frame.data, "AQD+/wMA/P8=");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decode_realtime_audio_frame_decodes_pcm16() {
|
||||
let frame = RealtimeAudioFrame {
|
||||
data: base64::engine::general_purpose::STANDARD.encode([1, 0, 254, 255]),
|
||||
sample_rate: 24_000,
|
||||
num_channels: 1,
|
||||
samples_per_channel: Some(2),
|
||||
};
|
||||
|
||||
let pcm = decode_realtime_audio_frame(&frame).expect("frame should decode");
|
||||
assert_eq!(pcm, vec![1, -2]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decode_realtime_audio_frame_rejects_invalid_shape() {
|
||||
let wrong_rate = RealtimeAudioFrame {
|
||||
data: String::new(),
|
||||
sample_rate: 16_000,
|
||||
num_channels: 1,
|
||||
samples_per_channel: Some(0),
|
||||
};
|
||||
let wrong_channels = RealtimeAudioFrame {
|
||||
data: String::new(),
|
||||
sample_rate: 24_000,
|
||||
num_channels: 2,
|
||||
samples_per_channel: Some(0),
|
||||
};
|
||||
|
||||
assert_eq!(
|
||||
decode_realtime_audio_frame(&wrong_rate).expect_err("wrong rate should fail"),
|
||||
"unexpected realtime audio format: 16000 Hz / 1 channels"
|
||||
);
|
||||
assert_eq!(
|
||||
decode_realtime_audio_frame(&wrong_channels)
|
||||
.expect_err("wrong channel count should fail"),
|
||||
"unexpected realtime audio format: 24000 Hz / 2 channels"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decode_realtime_audio_frame_rejects_invalid_payloads() {
|
||||
let invalid_base64 = RealtimeAudioFrame {
|
||||
data: "not-base64!".to_string(),
|
||||
sample_rate: 24_000,
|
||||
num_channels: 1,
|
||||
samples_per_channel: Some(0),
|
||||
};
|
||||
let odd_bytes = RealtimeAudioFrame {
|
||||
data: base64::engine::general_purpose::STANDARD.encode([1, 2, 3]),
|
||||
sample_rate: 24_000,
|
||||
num_channels: 1,
|
||||
samples_per_channel: Some(0),
|
||||
};
|
||||
|
||||
assert!(
|
||||
decode_realtime_audio_frame(&invalid_base64)
|
||||
.expect_err("invalid base64 should fail")
|
||||
.starts_with("failed to decode realtime audio:")
|
||||
);
|
||||
assert_eq!(
|
||||
decode_realtime_audio_frame(&odd_bytes).expect_err("odd byte length should fail"),
|
||||
"realtime audio frame had odd byte length"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn transcribe_async_rejects_short_clip() {
|
||||
let (tx, mut rx) = unbounded_channel();
|
||||
let sender = AppEventSender::new(tx);
|
||||
let audio = RecordedAudio {
|
||||
data: vec![0; 100],
|
||||
sample_rate: 24_000,
|
||||
channels: 1,
|
||||
};
|
||||
|
||||
transcribe_async("test-id".to_string(), audio, None, sender);
|
||||
|
||||
let event = rx.blocking_recv().expect("transcription result");
|
||||
assert_matches!(
|
||||
event,
|
||||
AppEvent::TranscriptionFailed { id, error }
|
||||
if id == "test-id"
|
||||
&& error == "recording too short (0.00s); minimum is 0.30s"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user