Unify desktop audio for voice input

- add a shared desktop audio crate and use device IDs for realtime audio selection
- enable the local voice path across desktop platforms and add targeted voice diagnostics

Co-authored-by: Codex <noreply@openai.com>
This commit is contained in:
Ahmed Ibrahim
2026-03-01 15:03:38 -07:00
co-authored by Codex
parent 6a673e7339
commit 4a62efb637
20 changed files with 912 additions and 1067 deletions
+3 -18
View File
File diff suppressed because one or more lines are too long
+35 -192
View File
@@ -291,28 +291,6 @@ version = "0.2.21"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923"
[[package]]
name = "alsa"
version = "0.9.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ed7572b7ba83a31e20d1b48970ee402d2e3e0537dcfe0a3ff4d6eb7508617d43"
dependencies = [
"alsa-sys",
"bitflags 2.10.0",
"cfg-if",
"libc",
]
[[package]]
name = "alsa-sys"
version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "db8fee663d06c4e303404ef5f40488a53e062f89ba8bfed81f42325aafad1527"
dependencies = [
"libc",
"pkg-config",
]
[[package]]
name = "android_system_properties"
version = "0.1.5"
@@ -937,14 +915,14 @@ dependencies = [
[[package]]
name = "bindgen"
version = "0.72.1"
version = "0.71.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "993776b509cfb49c750f11b8f07a46fa23e0a1386ffc01fb1e7d343efc387895"
checksum = "5f58bf3d7db68cfbac37cfc485a8d711e87e064c3d0fe0435b92f7a407f9d6b3"
dependencies = [
"bitflags 2.10.0",
"cexpr",
"clang-sys",
"itertools 0.13.0",
"itertools 0.10.5",
"proc-macro2",
"quote",
"regex",
@@ -1538,6 +1516,15 @@ dependencies = [
"tokio-util",
]
[[package]]
name = "codex-audio"
version = "0.0.0"
dependencies = [
"om-fork-miniaudio",
"pretty_assertions",
"tracing",
]
[[package]]
name = "codex-backend-client"
version = "0.0.0"
@@ -2382,6 +2369,7 @@ dependencies = [
"codex-ansi-escape",
"codex-app-server-protocol",
"codex-arg0",
"codex-audio",
"codex-backend-client",
"codex-chatgpt",
"codex-cli",
@@ -2407,7 +2395,6 @@ dependencies = [
"codex-utils-string",
"codex-windows-sandbox",
"color-eyre",
"cpal",
"crossterm",
"derive_more 2.1.1",
"diffy",
@@ -2854,49 +2841,6 @@ dependencies = [
"zstd",
]
[[package]]
name = "coreaudio-rs"
version = "0.11.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "321077172d79c662f64f5071a03120748d5bb652f5231570141be24cfcd2bace"
dependencies = [
"bitflags 1.3.2",
"core-foundation-sys",
"coreaudio-sys",
]
[[package]]
name = "coreaudio-sys"
version = "0.2.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ceec7a6067e62d6f931a2baf6f3a751f4a892595bcec1461a3c94ef9949864b6"
dependencies = [
"bindgen",
]
[[package]]
name = "cpal"
version = "0.15.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "873dab07c8f743075e57f524c583985fbaf745602acbe916a01539364369a779"
dependencies = [
"alsa",
"core-foundation-sys",
"coreaudio-rs",
"dasp_sample",
"jni",
"js-sys",
"libc",
"mach2",
"ndk",
"ndk-context",
"oboe",
"wasm-bindgen",
"wasm-bindgen-futures",
"web-sys",
"windows 0.54.0",
]
[[package]]
name = "cpufeatures"
version = "0.2.17"
@@ -3197,12 +3141,6 @@ dependencies = [
"syn 2.0.114",
]
[[package]]
name = "dasp_sample"
version = "0.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0c87e182de0887fd5361989c677c4e8f5000cd9491d6d563161a8f3a5519fc7f"
[[package]]
name = "data-encoding"
version = "2.10.0"
@@ -5515,15 +5453,6 @@ dependencies = [
"pkg-config",
]
[[package]]
name = "mach2"
version = "0.4.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d640282b302c0bb0a2a8e0233ead9035e3bed871f0b7e81fe4a1ec829765db44"
dependencies = [
"libc",
]
[[package]]
name = "maplit"
version = "1.0.2"
@@ -5707,35 +5636,12 @@ dependencies = [
"tempfile",
]
[[package]]
name = "ndk"
version = "0.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2076a31b7010b17a38c01907c45b945e8f11495ee4dd588309718901b1f7a5b7"
dependencies = [
"bitflags 2.10.0",
"jni-sys",
"log",
"ndk-sys",
"num_enum",
"thiserror 1.0.69",
]
[[package]]
name = "ndk-context"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "27b02d87554356db9e9a873add8782d4ea6e3e58ea071a9adb9a2e8ddb884a8b"
[[package]]
name = "ndk-sys"
version = "0.5.0+25.2.9519653"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8c196769dd60fd4f363e11d948139556a344e79d451aeb2fa2fd040738ef7691"
dependencies = [
"jni-sys",
]
[[package]]
name = "new_debug_unreachable"
version = "1.0.6"
@@ -5923,17 +5829,6 @@ version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cf97ec579c3c42f953ef76dbf8d55ac91fb219dde70e49aa4a6b7d74e9919050"
[[package]]
name = "num-derive"
version = "0.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ed3955f1a9c7c0c15e092f9c887db08b1fc683305fdf6eb6684f22555355e202"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.114",
]
[[package]]
name = "num-integer"
version = "0.1.46"
@@ -5985,28 +5880,6 @@ dependencies = [
"libc",
]
[[package]]
name = "num_enum"
version = "0.7.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b1207a7e20ad57b847bbddc6776b968420d38292bbfe2089accff5e19e82454c"
dependencies = [
"num_enum_derive",
"rustversion",
]
[[package]]
name = "num_enum_derive"
version = "0.7.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ff32365de1b6743cb203b710788263c44a03de03802daf96092f2da4fe6ba4d7"
dependencies = [
"proc-macro-crate",
"proc-macro2",
"quote",
"syn 2.0.114",
]
[[package]]
name = "num_threads"
version = "0.1.7"
@@ -6216,29 +6089,6 @@ dependencies = [
"memchr",
]
[[package]]
name = "oboe"
version = "0.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e8b61bebd49e5d43f5f8cc7ee2891c16e0f41ec7954d36bcb6c14c5e0de867fb"
dependencies = [
"jni",
"ndk",
"ndk-context",
"num-derive",
"num-traits",
"oboe-sys",
]
[[package]]
name = "oboe-sys"
version = "0.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6c8bb09a4a2b1d668170cfe0a7d5bc103f8999fb316c98099b6a9939c9f2e79d"
dependencies = [
"cc",
]
[[package]]
name = "oid-registry"
version = "0.8.1"
@@ -6248,6 +6098,28 @@ dependencies = [
"asn1-rs",
]
[[package]]
name = "om-fork-ep-miniaudio-sys"
version = "2.6.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b15275d28e354c1e3665940e8bd668817d6a6bafb6bdcb3860b49acf9358281f"
dependencies = [
"bindgen",
"bitflags 2.10.0",
"cc",
"libc",
]
[[package]]
name = "om-fork-miniaudio"
version = "0.12.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dec79816e1fe9db8c435cb3efac5cf470c4e7bde239ebcac22742412878aaeff"
dependencies = [
"bitflags 2.10.0",
"om-fork-ep-miniaudio-sys",
]
[[package]]
name = "once_cell"
version = "1.21.3"
@@ -10670,16 +10542,6 @@ version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f"
[[package]]
name = "windows"
version = "0.54.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9252e5725dbed82865af151df558e754e4a3c2c30818359eb17465f1346a1b49"
dependencies = [
"windows-core 0.54.0",
"windows-targets 0.52.6",
]
[[package]]
name = "windows"
version = "0.58.0"
@@ -10711,16 +10573,6 @@ dependencies = [
"windows-core 0.62.2",
]
[[package]]
name = "windows-core"
version = "0.54.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "12661b9c89351d684a50a8a643ce5f608e20243b9fb84687800163429f161d65"
dependencies = [
"windows-result 0.1.2",
"windows-targets 0.52.6",
]
[[package]]
name = "windows-core"
version = "0.58.0"
@@ -10829,15 +10681,6 @@ dependencies = [
"windows-strings 0.5.1",
]
[[package]]
name = "windows-result"
version = "0.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5e383302e8ec8515204254685643de10811af0ed97ea37210dc26fb0032647f8"
dependencies = [
"windows-targets 0.52.6",
]
[[package]]
name = "windows-result"
version = "0.2.0"
+3
View File
@@ -1,5 +1,6 @@
[workspace]
members = [
"audio",
"backend-client",
"ansi-escape",
"async-utils",
@@ -78,6 +79,7 @@ license = "Apache-2.0"
[workspace.dependencies]
# Internal
codex-audio = { path = "audio" }
app_test_support = { path = "app-server/tests/common" }
codex-ansi-escape = { path = "ansi-escape" }
codex-api = { path = "codex-api" }
@@ -200,6 +202,7 @@ log = "0.4"
lru = "0.16.3"
maplit = "1.0.2"
mime_guess = "2.0.5"
miniaudio = { package = "om-fork-miniaudio", version = "0.12.2" }
multimap = "0.10.0"
notify = "8.2.0"
nucleo = { git = "https://github.com/helix-editor/nucleo.git", rev = "4253de9faabb4e5c6d81d946a5e35a90f87347ee" }
+15
View File
@@ -0,0 +1,15 @@
[package]
name = "codex-audio"
version.workspace = true
edition.workspace = true
license.workspace = true
[dependencies]
miniaudio = { workspace = true }
tracing = { workspace = true }
[dev-dependencies]
pretty_assertions = { workspace = true }
[lints]
workspace = true
+508
View File
@@ -0,0 +1,508 @@
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;
use std::collections::VecDeque;
use std::mem::MaybeUninit;
use std::sync::Arc;
use std::sync::Mutex;
use std::sync::atomic::AtomicBool;
use std::sync::atomic::AtomicU16;
use std::sync::atomic::Ordering;
use tracing::debug;
use tracing::info;
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;
const MAX_OUTPUT_QUEUE_SAMPLES: usize = (AUDIO_SAMPLE_RATE as usize) * 2;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum AudioDeviceKind {
Input,
Output,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct AudioDeviceInfo {
pub id: String,
pub name: String,
pub backend: String,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct RecordedAudio {
pub data: Vec<i16>,
pub sample_rate: u32,
pub channels: u16,
}
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))
});
debug!(
kind = %audio_device_kind_label(kind),
backend = %backend,
count = devices.len(),
"enumerated audio devices"
);
Ok(devices)
}
pub fn resolve_device_name(
kind: AudioDeviceKind,
device_id: &str,
) -> Result<Option<String>, String> {
let devices = list_audio_devices(kind)?;
let resolved = devices
.into_iter()
.find(|device| device.id == device_id)
.map(|device| device.name);
debug!(
kind = %audio_device_kind_label(kind),
device_id,
resolved = resolved.is_some(),
"resolved persisted audio device"
);
Ok(resolved)
}
pub struct InputCapture {
_device: Device,
data: Arc<Mutex<Vec<i16>>>,
stopped: Arc<AtomicBool>,
last_peak: Arc<AtomicU16>,
}
impl InputCapture {
pub fn start_recording(device_id: Option<&str>) -> Result<Self, String> {
Self::start(device_id, true, None)
}
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)))),
)
}
fn start(
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)?));
}
let data = Arc::new(Mutex::new(Vec::new()));
let stopped = Arc::new(AtomicBool::new(false));
let last_peak = Arc::new(AtomicU16::new(0));
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 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}"))?;
info!(
mode = if collect_audio {
"recording"
} else {
"realtime_streaming"
},
backend = %backend,
device_id = device_id.unwrap_or("system_default"),
sample_rate = AUDIO_SAMPLE_RATE,
channels = AUDIO_CHANNELS,
period_frames = PERIOD_SIZE_IN_FRAMES,
"started input audio stream"
);
Ok(Self {
_device: device,
data,
stopped,
last_peak,
})
}
pub fn stop(self) -> Result<RecordedAudio, String> {
self.stopped.store(true, Ordering::SeqCst);
self._device
.stop()
.map_err(|err| format!("failed to stop input audio stream: {err}"))?;
let data = self
.data
.lock()
.map_err(|_| "failed to lock audio buffer".to_string())?
.clone();
let peak = peak_i16(&data);
let duration_ms = if AUDIO_SAMPLE_RATE > 0 {
(data.len() as u64 * 1_000) / u64::from(AUDIO_SAMPLE_RATE)
} else {
0
};
info!(
sample_count = data.len(),
duration_ms,
peak,
sample_rate = AUDIO_SAMPLE_RATE,
channels = AUDIO_CHANNELS,
"stopped input audio stream"
);
Ok(RecordedAudio {
data,
sample_rate: AUDIO_SAMPLE_RATE,
channels: AUDIO_CHANNELS as u16,
})
}
pub fn data_arc(&self) -> Arc<Mutex<Vec<i16>>> {
Arc::clone(&self.data)
}
pub fn stopped_flag(&self) -> Arc<AtomicBool> {
Arc::clone(&self.stopped)
}
pub fn last_peak_arc(&self) -> Arc<AtomicU16> {
Arc::clone(&self.last_peak)
}
pub fn sample_rate(&self) -> u32 {
AUDIO_SAMPLE_RATE
}
pub fn channels(&self) -> u16 {
AUDIO_CHANNELS as u16
}
}
pub struct OutputPlayback {
_device: Device,
queue: Arc<Mutex<VecDeque<i16>>>,
}
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)?));
}
let queue = Arc::new(Mutex::new(VecDeque::new()));
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}"))?;
info!(
backend = %backend,
device_id = device_id.unwrap_or("system_default"),
sample_rate = AUDIO_SAMPLE_RATE,
channels = AUDIO_CHANNELS,
period_frames = PERIOD_SIZE_IN_FRAMES,
"started output audio stream"
);
Ok(Self {
_device: device,
queue,
})
}
pub fn enqueue_samples(&self, samples: &[i16]) -> Result<(), String> {
if samples.is_empty() {
return Ok(());
}
let mut guard = self
.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));
warn!(
dropped_samples = overflow.min(current_len),
queue_samples_before = current_len,
queue_samples_after = guard.len(),
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();
}
}
}
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(),
});
}
}
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(),
}
}
fn audio_device_kind_label(kind: AudioDeviceKind) -> &'static str {
match kind {
AudioDeviceKind::Input => "input",
AudioDeviceKind::Output => "output",
}
}
fn encode_device_id(device_id: &DeviceId) -> String {
hex_encode(device_id_bytes(device_id))
}
fn decode_device_id(encoded: &str) -> Result<DeviceId, String> {
let bytes = hex_decode(encoded)?;
if bytes.len() != std::mem::size_of::<DeviceId>() {
return Err("invalid persisted audio device id".to_string());
}
let mut device_id = MaybeUninit::<DeviceId>::uninit();
unsafe {
std::ptr::copy_nonoverlapping(
bytes.as_ptr(),
device_id.as_mut_ptr().cast::<u8>(),
bytes.len(),
);
Ok(device_id.assume_init())
}
}
fn device_id_bytes(device_id: &DeviceId) -> &[u8] {
unsafe {
std::slice::from_raw_parts(
(device_id as *const DeviceId).cast::<u8>(),
std::mem::size_of::<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 {
let absolute = (sample as i32).unsigned_abs() as i32;
if absolute > peak {
peak = absolute;
}
}
peak as u16
}
fn hex_encode(bytes: &[u8]) -> String {
const DIGITS: &[u8; 16] = b"0123456789abcdef";
let mut encoded = String::with_capacity(bytes.len() * 2);
for byte in bytes {
encoded.push(DIGITS[(byte >> 4) as usize] as char);
encoded.push(DIGITS[(byte & 0x0f) as usize] as char);
}
encoded
}
fn hex_decode(encoded: &str) -> Result<Vec<u8>, String> {
if !encoded.len().is_multiple_of(2) {
return Err("invalid persisted audio device id".to_string());
}
let mut decoded = Vec::with_capacity(encoded.len() / 2);
let bytes = encoded.as_bytes();
let mut index = 0;
while index < bytes.len() {
let high = decode_hex_nibble(bytes[index])?;
let low = decode_hex_nibble(bytes[index + 1])?;
decoded.push((high << 4) | low);
index += 2;
}
Ok(decoded)
}
fn decode_hex_nibble(byte: u8) -> Result<u8, String> {
match byte {
b'0'..=b'9' => Ok(byte - b'0'),
b'a'..=b'f' => Ok(byte - b'a' + 10),
b'A'..=b'F' => Ok(byte - b'A' + 10),
_ => Err("invalid persisted audio device id".to_string()),
}
}
#[cfg(test)]
mod tests {
use super::hex_decode;
use super::hex_encode;
use pretty_assertions::assert_eq;
#[test]
fn hex_round_trip() {
let bytes = [0x00, 0x10, 0xab, 0xff];
let encoded = hex_encode(&bytes);
assert_eq!(encoded, "0010abff");
assert_eq!(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());
}
}
+2 -2
View File
@@ -1202,10 +1202,10 @@
"RealtimeAudioToml": {
"additionalProperties": false,
"properties": {
"microphone": {
"input_device_id": {
"type": "string"
},
"speaker": {
"output_device_id": {
"type": "string"
}
},
+27 -21
View File
@@ -872,24 +872,24 @@ impl ConfigEditsBuilder {
self
}
pub fn set_realtime_microphone(mut self, microphone: Option<&str>) -> Self {
let segments = vec!["audio".to_string(), "microphone".to_string()];
match microphone {
Some(microphone) => self.edits.push(ConfigEdit::SetPath {
pub fn set_realtime_input_device_id(mut self, input_device_id: Option<&str>) -> Self {
let segments = vec!["audio".to_string(), "input_device_id".to_string()];
match input_device_id {
Some(input_device_id) => self.edits.push(ConfigEdit::SetPath {
segments,
value: value(microphone),
value: value(input_device_id),
}),
None => self.edits.push(ConfigEdit::ClearPath { segments }),
}
self
}
pub fn set_realtime_speaker(mut self, speaker: Option<&str>) -> Self {
let segments = vec!["audio".to_string(), "speaker".to_string()];
match speaker {
Some(speaker) => self.edits.push(ConfigEdit::SetPath {
pub fn set_realtime_output_device_id(mut self, output_device_id: Option<&str>) -> Self {
let segments = vec!["audio".to_string(), "output_device_id".to_string()];
match output_device_id {
Some(output_device_id) => self.edits.push(ConfigEdit::SetPath {
segments,
value: value(speaker),
value: value(output_device_id),
}),
None => self.edits.push(ConfigEdit::ClearPath { segments }),
}
@@ -1893,8 +1893,8 @@ model_reasoning_effort = "high"
let codex_home = tmp.path();
ConfigEditsBuilder::new(codex_home)
.set_realtime_microphone(Some("USB Mic"))
.set_realtime_speaker(Some("Desk Speakers"))
.set_realtime_input_device_id(Some("usb-mic"))
.set_realtime_output_device_id(Some("desk-speakers"))
.apply_blocking()
.expect("persist realtime audio");
@@ -1905,18 +1905,22 @@ model_reasoning_effort = "high"
.and_then(TomlValue::as_table)
.expect("audio table should exist");
assert_eq!(
realtime_audio.get("microphone").and_then(TomlValue::as_str),
Some("USB Mic")
realtime_audio
.get("input_device_id")
.and_then(TomlValue::as_str),
Some("usb-mic")
);
assert_eq!(
realtime_audio.get("speaker").and_then(TomlValue::as_str),
Some("Desk Speakers")
realtime_audio
.get("output_device_id")
.and_then(TomlValue::as_str),
Some("desk-speakers")
);
ConfigEditsBuilder::new(codex_home)
.set_realtime_microphone(None)
.set_realtime_input_device_id(None)
.apply_blocking()
.expect("clear realtime microphone");
.expect("clear realtime input device id");
let raw = std::fs::read_to_string(codex_home.join(CONFIG_TOML_FILE)).expect("read config");
let config: TomlValue = toml::from_str(&raw).expect("parse config");
@@ -1924,10 +1928,12 @@ model_reasoning_effort = "high"
.get("audio")
.and_then(TomlValue::as_table)
.expect("audio table should exist");
assert_eq!(realtime_audio.get("microphone"), None);
assert_eq!(realtime_audio.get("input_device_id"), None);
assert_eq!(
realtime_audio.get("speaker").and_then(TomlValue::as_str),
Some("Desk Speakers")
realtime_audio
.get("output_device_id")
.and_then(TomlValue::as_str),
Some("desk-speakers")
);
}
+19 -13
View File
@@ -1319,15 +1319,15 @@ impl ProjectConfig {
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct RealtimeAudioConfig {
pub microphone: Option<String>,
pub speaker: Option<String>,
pub input_device_id: Option<String>,
pub output_device_id: Option<String>,
}
#[derive(Serialize, Deserialize, Debug, Clone, Default, PartialEq, Eq, JsonSchema)]
#[schemars(deny_unknown_fields)]
pub struct RealtimeAudioToml {
pub microphone: Option<String>,
pub speaker: Option<String>,
pub input_device_id: Option<String>,
pub output_device_id: Option<String>,
}
#[derive(Serialize, Deserialize, Debug, Clone, Default, PartialEq, JsonSchema)]
@@ -2173,8 +2173,8 @@ impl Config {
realtime_audio: cfg
.audio
.map_or_else(RealtimeAudioConfig::default, |audio| RealtimeAudioConfig {
microphone: audio.microphone,
speaker: audio.speaker,
input_device_id: audio.input_device_id,
output_device_id: audio.output_device_id,
}),
experimental_realtime_ws_base_url: cfg.experimental_realtime_ws_base_url,
experimental_realtime_ws_backend_prompt: cfg.experimental_realtime_ws_backend_prompt,
@@ -6132,8 +6132,8 @@ experimental_realtime_ws_backend_prompt = "prompt from config"
let cfg: ConfigToml = toml::from_str(
r#"
[audio]
microphone = "USB Mic"
speaker = "Desk Speakers"
input_device_id = "usb-mic"
output_device_id = "desk-speakers"
"#,
)
.expect("TOML deserialization should succeed");
@@ -6142,8 +6142,11 @@ speaker = "Desk Speakers"
.audio
.as_ref()
.expect("realtime audio config should be present");
assert_eq!(realtime_audio.microphone.as_deref(), Some("USB Mic"));
assert_eq!(realtime_audio.speaker.as_deref(), Some("Desk Speakers"));
assert_eq!(realtime_audio.input_device_id.as_deref(), Some("usb-mic"));
assert_eq!(
realtime_audio.output_device_id.as_deref(),
Some("desk-speakers")
);
let codex_home = TempDir::new()?;
let config = Config::load_from_base_config_with_overrides(
@@ -6152,10 +6155,13 @@ speaker = "Desk Speakers"
codex_home.path().to_path_buf(),
)?;
assert_eq!(config.realtime_audio.microphone.as_deref(), Some("USB Mic"));
assert_eq!(
config.realtime_audio.speaker.as_deref(),
Some("Desk Speakers")
config.realtime_audio.input_device_id.as_deref(),
Some("usb-mic")
);
assert_eq!(
config.realtime_audio.output_device_id.as_deref(),
Some("desk-speakers")
);
Ok(())
}
+3 -5
View File
@@ -18,7 +18,7 @@ default = ["voice-input"]
vt100-tests = []
# Gate verbose debug logging inside the TUI implementation.
debug-logs = []
voice-input = ["dep:cpal", "dep:hound"]
voice-input = ["dep:codex-audio", "dep:hound"]
[lints]
workspace = true
@@ -29,6 +29,7 @@ base64 = { workspace = true }
chrono = { workspace = true, features = ["serde"] }
clap = { workspace = true, features = ["derive"] }
codex-ansi-escape = { workspace = true }
codex-audio = { workspace = true, optional = true }
codex-app-server-protocol = { workspace = true }
codex-arg0 = { workspace = true }
codex-backend-client = { workspace = true }
@@ -103,14 +104,11 @@ unicode-width = { workspace = true }
url = { workspace = true }
webbrowser = { workspace = true }
uuid = { workspace = true }
hound = { version = "3.5", optional = true }
codex-windows-sandbox = { workspace = true }
tokio-util = { workspace = true, features = ["time"] }
[target.'cfg(not(target_os = "linux"))'.dependencies]
cpal = { version = "0.15", optional = true }
hound = { version = "3.5", optional = true }
[target.'cfg(unix)'.dependencies]
libc = { workspace = true }
+19 -10
View File
@@ -2656,15 +2656,15 @@ impl App {
}
}
}
AppEvent::PersistRealtimeAudioDeviceSelection { kind, name } => {
AppEvent::PersistRealtimeAudioDeviceSelection { kind, device_id } => {
let builder = match kind {
RealtimeAudioDeviceKind::Microphone => {
ConfigEditsBuilder::new(&self.config.codex_home)
.set_realtime_microphone(name.as_deref())
.set_realtime_input_device_id(device_id.as_deref())
}
RealtimeAudioDeviceKind::Speaker => {
ConfigEditsBuilder::new(&self.config.codex_home)
.set_realtime_speaker(name.as_deref())
.set_realtime_output_device_id(device_id.as_deref())
}
};
@@ -2672,19 +2672,31 @@ impl App {
Ok(()) => {
match kind {
RealtimeAudioDeviceKind::Microphone => {
self.config.realtime_audio.microphone = name.clone();
self.config.realtime_audio.input_device_id = device_id.clone();
}
RealtimeAudioDeviceKind::Speaker => {
self.config.realtime_audio.speaker = name.clone();
self.config.realtime_audio.output_device_id = device_id.clone();
}
}
self.chat_widget
.set_realtime_audio_device(kind, name.clone());
.set_realtime_audio_device(kind, device_id.clone());
tracing::info!(
kind = kind.noun(),
device_id = device_id.as_deref().unwrap_or("system_default"),
selection = self
.chat_widget
.current_realtime_audio_selection_label(kind)
.unwrap_or_else(|| "System default".to_string()),
"persisted realtime audio device selection"
);
if self.chat_widget.realtime_conversation_is_live() {
self.chat_widget.open_realtime_audio_restart_prompt(kind);
} else {
let selection = name.unwrap_or_else(|| "System default".to_string());
let selection = self
.chat_widget
.current_realtime_audio_selection_label(kind)
.unwrap_or_else(|| "System default".to_string());
self.chat_widget.add_info_message(
format!("Realtime {} set to {selection}", kind.noun()),
None,
@@ -3099,15 +3111,12 @@ impl App {
));
}
},
#[cfg(not(target_os = "linux"))]
AppEvent::TranscriptionComplete { id, text } => {
self.chat_widget.replace_transcription(&id, &text);
}
#[cfg(not(target_os = "linux"))]
AppEvent::TranscriptionFailed { id, error: _ } => {
self.chat_widget.remove_transcription_placeholder(&id);
}
#[cfg(not(target_os = "linux"))]
AppEvent::UpdateRecordingMeter { id, text } => {
// Update in place to preserve the element id for subsequent frames.
let updated = self.chat_widget.update_transcription_in_place(&id, &text);
+2 -8
View File
@@ -203,13 +203,10 @@ pub(crate) enum AppEvent {
},
/// Persist the selected realtime microphone or speaker to top-level config.
#[cfg_attr(
any(target_os = "linux", not(feature = "voice-input")),
allow(dead_code)
)]
#[cfg_attr(not(feature = "voice-input"), allow(dead_code))]
PersistRealtimeAudioDeviceSelection {
kind: RealtimeAudioDeviceKind,
name: Option<String>,
device_id: Option<String>,
},
/// Restart the selected realtime microphone or speaker locally.
@@ -377,21 +374,18 @@ pub(crate) enum AppEvent {
/// Live update for the in-progress voice recording placeholder. Carries
/// the placeholder `id` and the text to display (e.g., an ASCII meter).
#[cfg(not(target_os = "linux"))]
UpdateRecordingMeter {
id: String,
text: String,
},
/// Voice transcription finished for the given placeholder id.
#[cfg(not(target_os = "linux"))]
TranscriptionComplete {
id: String,
text: String,
},
/// Voice transcription failed; remove the placeholder identified by `id`.
#[cfg(not(target_os = "linux"))]
TranscriptionFailed {
id: String,
#[allow(dead_code)]
+14 -164
View File
@@ -1,176 +1,26 @@
use codex_core::config::Config;
use cpal::traits::DeviceTrait;
use cpal::traits::HostTrait;
use tracing::warn;
use codex_audio::AudioDeviceInfo;
use codex_audio::AudioDeviceKind;
use codex_audio::list_audio_devices;
use codex_audio::resolve_device_name;
use crate::app_event::RealtimeAudioDeviceKind;
const PREFERRED_INPUT_SAMPLE_RATE: u32 = 24_000;
const PREFERRED_INPUT_CHANNELS: u16 = 1;
pub(crate) fn list_realtime_audio_device_names(
pub(crate) fn list_realtime_audio_devices(
kind: RealtimeAudioDeviceKind,
) -> Result<Vec<String>, String> {
let host = cpal::default_host();
let mut device_names = Vec::new();
for device in devices(&host, kind)? {
let Ok(name) = device.name() else {
continue;
};
if !device_names.contains(&name) {
device_names.push(name);
}
}
Ok(device_names)
) -> Result<Vec<AudioDeviceInfo>, String> {
list_audio_devices(audio_device_kind(kind))
}
pub(crate) fn select_configured_input_device_and_config(
config: &Config,
) -> Result<(cpal::Device, cpal::SupportedStreamConfig), String> {
select_device_and_config(RealtimeAudioDeviceKind::Microphone, config)
}
pub(crate) fn select_configured_output_device_and_config(
config: &Config,
) -> Result<(cpal::Device, cpal::SupportedStreamConfig), String> {
select_device_and_config(RealtimeAudioDeviceKind::Speaker, config)
}
pub(crate) fn preferred_input_config(
device: &cpal::Device,
) -> Result<cpal::SupportedStreamConfig, String> {
let supported_configs = device
.supported_input_configs()
.map_err(|err| format!("failed to enumerate input audio configs: {err}"))?;
supported_configs
.filter_map(|range| {
let sample_format_rank = match range.sample_format() {
cpal::SampleFormat::I16 => 0u8,
cpal::SampleFormat::U16 => 1u8,
cpal::SampleFormat::F32 => 2u8,
_ => return None,
};
let sample_rate = preferred_input_sample_rate(&range);
let sample_rate_penalty = sample_rate.0.abs_diff(PREFERRED_INPUT_SAMPLE_RATE);
let channel_penalty = range.channels().abs_diff(PREFERRED_INPUT_CHANNELS);
Some((
(sample_rate_penalty, channel_penalty, sample_format_rank),
range.with_sample_rate(sample_rate),
))
})
.min_by_key(|(score, _)| *score)
.map(|(_, config)| config)
.or_else(|| device.default_input_config().ok())
.ok_or_else(|| "failed to get default input config".to_string())
}
fn select_device_and_config(
pub(crate) fn resolve_realtime_audio_device_name(
kind: RealtimeAudioDeviceKind,
config: &Config,
) -> Result<(cpal::Device, cpal::SupportedStreamConfig), String> {
let host = cpal::default_host();
let configured_name = configured_name(kind, config);
let selected = configured_name
.and_then(|name| find_device_by_name(&host, kind, name))
.or_else(|| {
let default_device = default_device(&host, kind);
if let Some(name) = configured_name && default_device.is_some() {
warn!(
"configured {} audio device `{name}` was unavailable; falling back to system default",
kind.noun()
);
}
default_device
})
.ok_or_else(|| missing_device_error(kind, configured_name))?;
let stream_config = match kind {
RealtimeAudioDeviceKind::Microphone => preferred_input_config(&selected)?,
RealtimeAudioDeviceKind::Speaker => default_config(&selected, kind)?,
};
Ok((selected, stream_config))
device_id: &str,
) -> Result<Option<String>, String> {
resolve_device_name(audio_device_kind(kind), device_id)
}
fn configured_name(kind: RealtimeAudioDeviceKind, config: &Config) -> Option<&str> {
fn audio_device_kind(kind: RealtimeAudioDeviceKind) -> AudioDeviceKind {
match kind {
RealtimeAudioDeviceKind::Microphone => config.realtime_audio.microphone.as_deref(),
RealtimeAudioDeviceKind::Speaker => config.realtime_audio.speaker.as_deref(),
}
}
fn find_device_by_name(
host: &cpal::Host,
kind: RealtimeAudioDeviceKind,
name: &str,
) -> Option<cpal::Device> {
let devices = devices(host, kind).ok()?;
devices
.into_iter()
.find(|device| device.name().ok().as_deref() == Some(name))
}
fn devices(host: &cpal::Host, kind: RealtimeAudioDeviceKind) -> Result<Vec<cpal::Device>, String> {
match kind {
RealtimeAudioDeviceKind::Microphone => host
.input_devices()
.map(|devices| devices.collect())
.map_err(|err| format!("failed to enumerate input audio devices: {err}")),
RealtimeAudioDeviceKind::Speaker => host
.output_devices()
.map(|devices| devices.collect())
.map_err(|err| format!("failed to enumerate output audio devices: {err}")),
}
}
fn default_device(host: &cpal::Host, kind: RealtimeAudioDeviceKind) -> Option<cpal::Device> {
match kind {
RealtimeAudioDeviceKind::Microphone => host.default_input_device(),
RealtimeAudioDeviceKind::Speaker => host.default_output_device(),
}
}
fn default_config(
device: &cpal::Device,
kind: RealtimeAudioDeviceKind,
) -> Result<cpal::SupportedStreamConfig, String> {
match kind {
RealtimeAudioDeviceKind::Microphone => device
.default_input_config()
.map_err(|err| format!("failed to get default input config: {err}")),
RealtimeAudioDeviceKind::Speaker => device
.default_output_config()
.map_err(|err| format!("failed to get default output config: {err}")),
}
}
fn preferred_input_sample_rate(range: &cpal::SupportedStreamConfigRange) -> cpal::SampleRate {
let min = range.min_sample_rate().0;
let max = range.max_sample_rate().0;
if (min..=max).contains(&PREFERRED_INPUT_SAMPLE_RATE) {
cpal::SampleRate(PREFERRED_INPUT_SAMPLE_RATE)
} else if PREFERRED_INPUT_SAMPLE_RATE < min {
cpal::SampleRate(min)
} else {
cpal::SampleRate(max)
}
}
fn missing_device_error(kind: RealtimeAudioDeviceKind, configured_name: Option<&str>) -> String {
match (kind, configured_name) {
(RealtimeAudioDeviceKind::Microphone, Some(name)) => {
format!(
"configured microphone `{name}` was unavailable and no default input audio device was found"
)
}
(RealtimeAudioDeviceKind::Speaker, Some(name)) => {
format!(
"configured speaker `{name}` was unavailable and no default output audio device was found"
)
}
(RealtimeAudioDeviceKind::Microphone, None) => {
"no input audio device available".to_string()
}
(RealtimeAudioDeviceKind::Speaker, None) => "no output audio device available".to_string(),
RealtimeAudioDeviceKind::Microphone => AudioDeviceKind::Input,
RealtimeAudioDeviceKind::Speaker => AudioDeviceKind::Output,
}
}
+2 -44
View File
@@ -216,15 +216,12 @@ use std::collections::VecDeque;
use std::ops::Range;
use std::path::PathBuf;
use std::sync::Arc;
#[cfg(not(target_os = "linux"))]
use std::sync::Mutex;
use std::sync::atomic::AtomicBool;
use std::sync::atomic::Ordering;
#[cfg(not(target_os = "linux"))]
use std::thread;
use std::time::Duration;
use std::time::Instant;
#[cfg(not(target_os = "linux"))]
use tokio::runtime::Handle;
/// If the pasted content exceeds this number of characters, replace it with a
/// placeholder in the UI.
@@ -321,13 +318,9 @@ struct VoiceState {
space_hold_trigger: Option<Arc<AtomicBool>>,
key_release_supported: bool,
space_hold_repeat_seen: bool,
#[cfg(not(target_os = "linux"))]
voice: Option<crate::voice::VoiceCapture>,
#[cfg(not(target_os = "linux"))]
recording_placeholder_id: Option<String>,
#[cfg(not(target_os = "linux"))]
space_recording_started_at: Option<Instant>,
#[cfg(not(target_os = "linux"))]
space_recording_last_repeat_at: Option<Instant>,
}
@@ -381,7 +374,6 @@ pub(crate) struct ChatComposer {
footer_flash: Option<FooterFlash>,
context_window_percent: Option<i64>,
// Monotonically increasing identifier for textarea elements we insert.
#[cfg(not(target_os = "linux"))]
next_element_id: u64,
context_window_used_tokens: Option<i64>,
skills: Option<Vec<SkillMetadata>>,
@@ -487,7 +479,6 @@ impl ChatComposer {
selected_remote_image_index: None,
footer_flash: None,
context_window_percent: None,
#[cfg(not(target_os = "linux"))]
next_element_id: 0,
context_window_used_tokens: None,
skills: None,
@@ -511,7 +502,6 @@ impl ChatComposer {
this
}
#[cfg(not(target_os = "linux"))]
fn next_id(&mut self) -> String {
let id = self.next_element_id;
self.next_element_id = self.next_element_id.wrapping_add(1);
@@ -598,9 +588,8 @@ impl ChatComposer {
}
}
#[cfg(not(target_os = "linux"))]
fn voice_transcription_enabled(&self) -> bool {
self.voice_state.transcription_enabled && cfg!(not(target_os = "linux"))
self.voice_state.transcription_enabled
}
/// Centralized feature gating keeps config checks out of call sites.
fn popups_enabled(&self) -> bool {
@@ -671,7 +660,6 @@ impl ChatComposer {
}
// Hide the cursor while recording voice input.
#[cfg(not(target_os = "linux"))]
if self.voice_state.voice.is_some() {
return None;
}
@@ -732,7 +720,6 @@ impl ChatComposer {
/// In all cases, clears any paste-burst Enter suppression state so a real paste cannot affect
/// the next user Enter key, then syncs popup state.
pub fn handle_paste(&mut self, pasted: String) -> bool {
#[cfg(not(target_os = "linux"))]
if self.voice_state.voice.is_some() {
return false;
}
@@ -980,7 +967,6 @@ impl ChatComposer {
local_image_paths: Vec<PathBuf>,
mention_bindings: Vec<MentionBinding>,
) {
#[cfg(not(target_os = "linux"))]
self.stop_all_transcription_spinners();
// Clear any existing content, placeholders, and attachments first.
@@ -2760,15 +2746,6 @@ impl ChatComposer {
}
}
#[cfg(target_os = "linux")]
fn handle_voice_space_key_event(
&mut self,
_key_event: &KeyEvent,
) -> Option<(InputResult, bool)> {
None
}
#[cfg(not(target_os = "linux"))]
fn handle_voice_space_key_event(
&mut self,
key_event: &KeyEvent,
@@ -2843,15 +2820,6 @@ impl ChatComposer {
}
}
#[cfg(target_os = "linux")]
fn handle_key_event_while_recording(
&mut self,
_key_event: KeyEvent,
) -> Option<(InputResult, bool)> {
None
}
#[cfg(not(target_os = "linux"))]
fn handle_key_event_while_recording(
&mut self,
key_event: KeyEvent,
@@ -3624,7 +3592,6 @@ impl ChatComposer {
self.has_focus = has_focus;
}
#[cfg(not(target_os = "linux"))]
pub(crate) fn is_recording(&self) -> bool {
self.voice_state.voice.is_some()
}
@@ -3662,7 +3629,6 @@ impl ChatComposer {
}
}
#[cfg(not(target_os = "linux"))]
fn schedule_space_hold_timer(flag: Arc<AtomicBool>, frame: Option<FrameRequester>) {
const HOLD_DELAY_MILLIS: u64 = 500;
if let Ok(handle) = Handle::try_current() {
@@ -3680,7 +3646,6 @@ impl ChatComposer {
}
}
#[cfg(not(target_os = "linux"))]
fn complete_space_hold_timer(flag: Arc<AtomicBool>, frame: Option<FrameRequester>) {
flag.store(true, Ordering::Relaxed);
if let Some(frame) = frame {
@@ -3705,7 +3670,6 @@ impl ChatComposer {
}
}
#[cfg(not(target_os = "linux"))]
impl ChatComposer {
pub(crate) fn process_space_hold_trigger(&mut self) {
if self.voice_transcription_enabled()
@@ -3810,7 +3774,7 @@ impl ChatComposer {
} else {
0.0
};
const MIN_DURATION_SECONDS: f32 = 1.0;
const MIN_DURATION_SECONDS: f32 = 0.3;
if duration_seconds < MIN_DURATION_SECONDS {
if let Some(id) = self.voice_state.recording_placeholder_id.take() {
let _ = self.textarea.replace_element_by_id(&id, "");
@@ -3973,7 +3937,6 @@ impl ChatComposer {
self.textarea.update_named_element_by_id(id, text)
}
#[cfg(not(target_os = "linux"))]
pub fn insert_transcription_placeholder(&mut self, text: &str) -> String {
let id = self.next_id();
self.textarea.insert_named_element(text, id.clone());
@@ -6461,7 +6424,6 @@ mod tests {
assert!(!composer.voice_state.space_hold_repeat_seen);
}
#[cfg(not(target_os = "linux"))]
#[test]
fn space_hold_timeout_without_release_or_repeat_keeps_typed_space() {
let (tx, _rx) = unbounded_channel::<AppEvent>();
@@ -6493,7 +6455,6 @@ mod tests {
assert!(!composer.voice_state.space_hold_repeat_seen);
}
#[cfg(not(target_os = "linux"))]
#[test]
fn space_hold_timeout_with_repeat_uses_hold_path_without_release() {
let (tx, _rx) = unbounded_channel::<AppEvent>();
@@ -6527,7 +6488,6 @@ mod tests {
}
}
#[cfg(not(target_os = "linux"))]
#[test]
fn space_hold_timeout_with_repeat_does_not_duplicate_existing_space() {
let (tx, _rx) = unbounded_channel::<AppEvent>();
@@ -6561,7 +6521,6 @@ mod tests {
}
}
#[cfg(not(target_os = "linux"))]
#[test]
fn replace_transcription_stops_spinner_for_placeholder() {
let (tx, _rx) = unbounded_channel::<AppEvent>();
@@ -6588,7 +6547,6 @@ mod tests {
assert_eq!(composer.textarea.text(), "transcribed text");
}
#[cfg(not(target_os = "linux"))]
#[test]
fn set_text_content_stops_all_transcription_spinners() {
let (tx, _rx) = unbounded_channel::<AppEvent>();
-3
View File
@@ -346,7 +346,6 @@ impl BottomPane {
pub fn handle_key_event(&mut self, key_event: KeyEvent) -> InputResult {
// Do not globally intercept space; only composer handles hold-to-talk.
// While recording, route all keys to the composer so it can stop on release or next key.
#[cfg(not(target_os = "linux"))]
if self.composer.is_recording() {
let (_ir, needs_redraw) = self.composer.handle_key_event(key_event);
if needs_redraw {
@@ -480,7 +479,6 @@ impl BottomPane {
// Space hold timeout is handled inside ChatComposer via an internal timer.
pub(crate) fn pre_draw_tick(&mut self) {
// Allow composer to process any time-based transitions before drawing
#[cfg(not(target_os = "linux"))]
self.composer.process_space_hold_trigger();
self.composer.sync_popups();
}
@@ -1039,7 +1037,6 @@ impl BottomPane {
}
}
#[cfg(not(target_os = "linux"))]
impl BottomPane {
pub(crate) fn insert_transcription_placeholder(&mut self, text: &str) -> String {
let id = self.composer.insert_transcription_placeholder(text);
+64 -29
View File
@@ -38,8 +38,10 @@ use std::time::Duration;
use std::time::Instant;
use crate::app_event::RealtimeAudioDeviceKind;
#[cfg(all(not(target_os = "linux"), feature = "voice-input"))]
use crate::audio_device::list_realtime_audio_device_names;
#[cfg(feature = "voice-input")]
use crate::audio_device::list_realtime_audio_devices;
#[cfg(feature = "voice-input")]
use crate::audio_device::resolve_realtime_audio_device_name;
use crate::bottom_pane::StatusLineItem;
use crate::bottom_pane::StatusLineSetupView;
use crate::status::RateLimitWindowDisplay;
@@ -49,6 +51,8 @@ use crate::status::rate_limit_snapshot_display_for_limit;
use crate::text_formatting::proper_join;
use crate::version::CODEX_CLI_VERSION;
use codex_app_server_protocol::ConfigLayerSource;
#[cfg(feature = "voice-input")]
use codex_audio::AudioDeviceInfo;
use codex_backend_client::Client as BackendClient;
use codex_chatgpt::connectors;
use codex_core::config::Config;
@@ -155,6 +159,7 @@ use ratatui::widgets::Wrap;
use tokio::sync::mpsc::UnboundedSender;
use tokio::task::JoinHandle;
use tracing::debug;
use tracing::info;
use tracing::warn;
const DEFAULT_MODEL_DISPLAY_NAME: &str = "loading";
@@ -858,7 +863,6 @@ enum ReplayKind {
impl ChatWidget {
fn realtime_conversation_enabled(&self) -> bool {
self.config.features.enabled(Feature::RealtimeConversation)
&& cfg!(not(target_os = "linux"))
}
fn realtime_audio_device_selection_enabled(&self) -> bool {
@@ -5325,6 +5329,7 @@ impl ChatWidget {
let description = Some(format!(
"Current: {}",
self.current_realtime_audio_selection_label(kind)
.unwrap_or_else(|| "System default".to_string())
));
let actions: Vec<SelectionAction> = vec![Box::new(move |tx| {
tx.send(AppEvent::OpenRealtimeAudioDeviceSelection { kind });
@@ -5348,13 +5353,19 @@ impl ChatWidget {
});
}
#[cfg(all(not(target_os = "linux"), feature = "voice-input"))]
#[cfg(feature = "voice-input")]
pub(crate) fn open_realtime_audio_device_selection(&mut self, kind: RealtimeAudioDeviceKind) {
match list_realtime_audio_device_names(kind) {
Ok(device_names) => {
self.open_realtime_audio_device_selection_with_names(kind, device_names);
match list_realtime_audio_devices(kind) {
Ok(devices) => {
info!(
kind = kind.noun(),
count = devices.len(),
"opened realtime audio device picker"
);
self.open_realtime_audio_device_selection_with_names(kind, devices);
}
Err(err) => {
warn!(error = %err, kind = kind.noun(), "failed to enumerate realtime audio devices");
self.add_error_message(format!(
"Failed to load realtime {} devices: {err}",
kind.noun()
@@ -5363,33 +5374,37 @@ impl ChatWidget {
}
}
#[cfg(any(target_os = "linux", not(feature = "voice-input")))]
#[cfg(not(feature = "voice-input"))]
pub(crate) fn open_realtime_audio_device_selection(&mut self, kind: RealtimeAudioDeviceKind) {
let _ = kind;
}
#[cfg(all(not(target_os = "linux"), feature = "voice-input"))]
#[cfg(feature = "voice-input")]
fn open_realtime_audio_device_selection_with_names(
&mut self,
kind: RealtimeAudioDeviceKind,
device_names: Vec<String>,
devices: Vec<AudioDeviceInfo>,
) {
let current_selection = self.current_realtime_audio_device_name(kind);
let current_selection = self.current_realtime_audio_device_id(kind);
let current_available = current_selection
.as_deref()
.is_some_and(|name| device_names.iter().any(|device_name| device_name == name));
.is_some_and(|device_id| devices.iter().any(|device| device.id == device_id));
let mut items = vec![SelectionItem {
name: "System default".to_string(),
description: Some("Use your operating system default device.".to_string()),
is_current: current_selection.is_none(),
actions: vec![Box::new(move |tx| {
tx.send(AppEvent::PersistRealtimeAudioDeviceSelection { kind, name: None });
tx.send(AppEvent::PersistRealtimeAudioDeviceSelection {
kind,
device_id: None,
});
})],
dismiss_on_select: true,
..Default::default()
}];
if let Some(selection) = current_selection.as_deref()
if let Some(selection) = self.current_realtime_audio_selection_label(kind)
&& current_selection.is_some()
&& !current_available
{
items.push(SelectionItem {
@@ -5402,17 +5417,18 @@ impl ChatWidget {
});
}
items.extend(device_names.into_iter().map(|device_name| {
let persisted_name = device_name.clone();
items.extend(devices.into_iter().map(|device| {
let persisted_device_id = device.id.clone();
let actions: Vec<SelectionAction> = vec![Box::new(move |tx| {
tx.send(AppEvent::PersistRealtimeAudioDeviceSelection {
kind,
name: Some(persisted_name.clone()),
device_id: Some(persisted_device_id.clone()),
});
})];
SelectionItem {
is_current: current_selection.as_deref() == Some(device_name.as_str()),
name: device_name,
is_current: current_selection.as_deref() == Some(device.id.as_str()),
name: device.name,
description: Some(device.backend),
actions,
dismiss_on_select: true,
..Default::default()
@@ -6817,11 +6833,15 @@ impl ChatWidget {
pub(crate) fn set_realtime_audio_device(
&mut self,
kind: RealtimeAudioDeviceKind,
name: Option<String>,
device_id: Option<String>,
) {
match kind {
RealtimeAudioDeviceKind::Microphone => self.config.realtime_audio.microphone = name,
RealtimeAudioDeviceKind::Speaker => self.config.realtime_audio.speaker = name,
RealtimeAudioDeviceKind::Microphone => {
self.config.realtime_audio.input_device_id = device_id;
}
RealtimeAudioDeviceKind::Speaker => {
self.config.realtime_audio.output_device_id = device_id;
}
}
}
@@ -6857,16 +6877,32 @@ impl ChatWidget {
self.realtime_conversation.is_active()
}
fn current_realtime_audio_device_name(&self, kind: RealtimeAudioDeviceKind) -> Option<String> {
fn current_realtime_audio_device_id(&self, kind: RealtimeAudioDeviceKind) -> Option<String> {
match kind {
RealtimeAudioDeviceKind::Microphone => self.config.realtime_audio.microphone.clone(),
RealtimeAudioDeviceKind::Speaker => self.config.realtime_audio.speaker.clone(),
RealtimeAudioDeviceKind::Microphone => {
self.config.realtime_audio.input_device_id.clone()
}
RealtimeAudioDeviceKind::Speaker => self.config.realtime_audio.output_device_id.clone(),
}
}
fn current_realtime_audio_selection_label(&self, kind: RealtimeAudioDeviceKind) -> String {
self.current_realtime_audio_device_name(kind)
.unwrap_or_else(|| "System default".to_string())
pub(crate) fn current_realtime_audio_selection_label(
&self,
kind: RealtimeAudioDeviceKind,
) -> Option<String> {
let device_id = self.current_realtime_audio_device_id(kind)?;
#[cfg(feature = "voice-input")]
{
resolve_realtime_audio_device_name(kind, &device_id)
.ok()
.flatten()
.or(Some(format!("Unavailable device ({device_id})")))
}
#[cfg(not(feature = "voice-input"))]
{
let _ = kind;
Some(format!("Unavailable device ({device_id})"))
}
}
fn sync_personality_command_enabled(&mut self) {
@@ -7922,7 +7958,6 @@ impl ChatWidget {
}
}
#[cfg(not(target_os = "linux"))]
impl ChatWidget {
pub(crate) fn replace_transcription(&mut self, id: &str, text: &str) {
self.bottom_pane.replace_transcription(id, text);
+32 -32
View File
@@ -5,6 +5,8 @@ use codex_protocol::protocol::RealtimeConversationClosedEvent;
use codex_protocol::protocol::RealtimeConversationRealtimeEvent;
use codex_protocol::protocol::RealtimeConversationStartedEvent;
use codex_protocol::protocol::RealtimeEvent;
use tracing::info;
use tracing::warn;
const REALTIME_CONVERSATION_PROMPT: &str = "You are in a realtime voice conversation in the Codex TUI. Respond conversationally and concisely.";
@@ -24,11 +26,8 @@ pub(super) struct RealtimeConversationUiState {
session_id: Option<String>,
warned_audio_only_submission: bool,
meter_placeholder_id: Option<String>,
#[cfg(not(target_os = "linux"))]
capture_stop_flag: Option<Arc<AtomicBool>>,
#[cfg(not(target_os = "linux"))]
capture: Option<crate::voice::VoiceCapture>,
#[cfg(not(target_os = "linux"))]
audio_player: Option<crate::voice::RealtimeAudioPlayer>,
}
@@ -119,6 +118,7 @@ impl ChatWidget {
}
pub(super) fn start_realtime_conversation(&mut self) {
info!("starting realtime conversation");
self.realtime_conversation.phase = RealtimeConversationPhase::Starting;
self.realtime_conversation.requested_close = false;
self.realtime_conversation.session_id = None;
@@ -139,6 +139,7 @@ impl ChatWidget {
return;
}
info!("requesting realtime conversation close");
self.realtime_conversation.requested_close = true;
self.realtime_conversation.phase = RealtimeConversationPhase::Stopping;
self.submit_op(Op::RealtimeConversationClose);
@@ -153,6 +154,7 @@ impl ChatWidget {
}
pub(super) fn reset_realtime_conversation_state(&mut self) {
info!("resetting realtime conversation state");
self.stop_realtime_local_audio();
self.set_footer_hint_override(None);
self.realtime_conversation.phase = RealtimeConversationPhase::Inactive;
@@ -170,6 +172,7 @@ impl ChatWidget {
self.reset_realtime_conversation_state();
return;
}
info!(session_id = ?ev.session_id, "realtime conversation started");
self.realtime_conversation.phase = RealtimeConversationPhase::Active;
self.realtime_conversation.session_id = ev.session_id;
self.realtime_conversation.warned_audio_only_submission = false;
@@ -184,12 +187,14 @@ impl ChatWidget {
) {
match ev.payload {
RealtimeEvent::SessionCreated { session_id } => {
info!(%session_id, "realtime session created");
self.realtime_conversation.session_id = Some(session_id);
}
RealtimeEvent::SessionUpdated { .. } => {}
RealtimeEvent::AudioOut(frame) => self.enqueue_realtime_audio_out(&frame),
RealtimeEvent::ConversationItemAdded(_item) => {}
RealtimeEvent::Error(message) => {
warn!(%message, "realtime conversation reported error");
self.add_error_message(format!("Realtime voice error: {message}"));
self.reset_realtime_conversation_state();
}
@@ -199,6 +204,7 @@ impl ChatWidget {
pub(super) fn on_realtime_conversation_closed(&mut self, ev: RealtimeConversationClosedEvent) {
let requested = self.realtime_conversation.requested_close;
let reason = ev.reason;
info!(requested, reason = ?reason, "realtime conversation closed");
self.reset_realtime_conversation_state();
if !requested && let Some(reason) = reason {
self.add_info_message(format!("Realtime voice mode closed: {reason}"), None);
@@ -207,27 +213,21 @@ impl ChatWidget {
}
fn enqueue_realtime_audio_out(&mut self, frame: &RealtimeAudioFrame) {
#[cfg(not(target_os = "linux"))]
{
if self.realtime_conversation.audio_player.is_none() {
self.realtime_conversation.audio_player =
crate::voice::RealtimeAudioPlayer::start(&self.config).ok();
}
if let Some(player) = &self.realtime_conversation.audio_player
&& let Err(err) = player.enqueue_frame(frame)
{
warn!("failed to play realtime audio: {err}");
}
if self.realtime_conversation.audio_player.is_none() {
self.realtime_conversation.audio_player =
crate::voice::RealtimeAudioPlayer::start(&self.config).ok();
}
#[cfg(target_os = "linux")]
if let Some(player) = &self.realtime_conversation.audio_player
&& let Err(err) = player.enqueue_frame(frame)
{
let _ = frame;
warn!("failed to play realtime audio: {err}");
}
}
#[cfg(not(target_os = "linux"))]
fn start_realtime_local_audio(&mut self) {
if self.realtime_conversation.capture_stop_flag.is_some() {
debug_assert!(self.realtime_conversation.capture.is_some());
info!("realtime local microphone already active");
return;
}
@@ -241,6 +241,7 @@ impl ChatWidget {
) {
Ok(capture) => capture,
Err(err) => {
warn!(error = %err, "failed to start realtime microphone capture");
self.remove_transcription_placeholder(&placeholder_id);
self.realtime_conversation.meter_placeholder_id = None;
self.add_error_message(format!("Failed to start microphone capture: {err}"));
@@ -256,8 +257,14 @@ impl ChatWidget {
self.realtime_conversation.capture_stop_flag = Some(stop_flag.clone());
self.realtime_conversation.capture = Some(capture);
if self.realtime_conversation.audio_player.is_none() {
self.realtime_conversation.audio_player =
crate::voice::RealtimeAudioPlayer::start(&self.config).ok();
match crate::voice::RealtimeAudioPlayer::start(&self.config) {
Ok(player) => {
self.realtime_conversation.audio_player = Some(player);
}
Err(err) => {
warn!(error = %err, "failed to start realtime speaker output");
}
}
}
std::thread::spawn(move || {
@@ -279,15 +286,13 @@ impl ChatWidget {
});
}
#[cfg(target_os = "linux")]
fn start_realtime_local_audio(&mut self) {}
#[cfg(all(not(target_os = "linux"), feature = "voice-input"))]
#[cfg(feature = "voice-input")]
pub(crate) fn restart_realtime_audio_device(&mut self, kind: RealtimeAudioDeviceKind) {
if !self.realtime_conversation.is_active() {
return;
}
info!(kind = kind.noun(), "restarting realtime audio device");
match kind {
RealtimeAudioDeviceKind::Microphone => {
self.stop_realtime_microphone();
@@ -300,6 +305,7 @@ impl ChatWidget {
self.realtime_conversation.audio_player = Some(player);
}
Err(err) => {
warn!(error = %err, "failed to restart realtime speaker output");
self.add_error_message(format!("Failed to start speaker output: {err}"));
}
}
@@ -308,24 +314,18 @@ impl ChatWidget {
self.request_redraw();
}
#[cfg(any(target_os = "linux", not(feature = "voice-input")))]
#[cfg(not(feature = "voice-input"))]
pub(crate) fn restart_realtime_audio_device(&mut self, kind: RealtimeAudioDeviceKind) {
let _ = kind;
}
#[cfg(not(target_os = "linux"))]
fn stop_realtime_local_audio(&mut self) {
self.stop_realtime_microphone();
self.stop_realtime_speaker();
}
#[cfg(target_os = "linux")]
fn stop_realtime_local_audio(&mut self) {
self.realtime_conversation.meter_placeholder_id = None;
}
#[cfg(not(target_os = "linux"))]
fn stop_realtime_microphone(&mut self) {
info!("stopping realtime microphone");
if let Some(flag) = self.realtime_conversation.capture_stop_flag.take() {
flag.store(true, Ordering::Relaxed);
}
@@ -337,8 +337,8 @@ impl ChatWidget {
}
}
#[cfg(not(target_os = "linux"))]
fn stop_realtime_speaker(&mut self) {
info!("stopping realtime speaker");
if let Some(player) = self.realtime_conversation.audio_player.take() {
player.clear();
}
@@ -5,14 +5,14 @@ expression: popup
Select Microphone
Saved devices apply to realtime voice only.
1. System default Use your operating system
default device.
› 2. Unavailable: Studio Mic (current) (disabled) Configured device is not
currently available.
(disabled: Reconnect the
device or choose another
one.)
3. Built-in Mic
4. USB Mic
1. System default Use your operating
system default device.
› 2. Unavailable: Unavailable device (studio-mic) (c… (disabled)Configured
device is not currently
available. (disabled:
Reconnect the device or
choose another one.)
3. Built-in Mic CoreAudio
4. USB Mic CoreAudio
Press enter to confirm or esc to go back
+34 -10
View File
@@ -7,7 +7,7 @@
use super::*;
use crate::app_event::AppEvent;
use crate::app_event::ExitMode;
#[cfg(all(not(target_os = "linux"), feature = "voice-input"))]
#[cfg(feature = "voice-input")]
use crate::app_event::RealtimeAudioDeviceKind;
use crate::app_event_sender::AppEventSender;
use crate::bottom_pane::FeedbackAudience;
@@ -17,6 +17,8 @@ use crate::history_cell::UserHistoryCell;
use crate::test_backend::VT100Backend;
use crate::tui::FrameRequester;
use assert_matches::assert_matches;
#[cfg(feature = "voice-input")]
use codex_audio::AudioDeviceInfo;
use codex_core::CodexAuth;
use codex_core::config::Config;
use codex_core::config::ConfigBuilder;
@@ -6011,7 +6013,7 @@ async fn personality_selection_popup_snapshot() {
assert_snapshot!("personality_selection_popup", popup);
}
#[cfg(all(not(target_os = "linux"), feature = "voice-input"))]
#[cfg(feature = "voice-input")]
#[tokio::test]
async fn realtime_audio_selection_popup_snapshot() {
let (mut chat, _rx, _op_rx) = make_chatwidget_manual(Some("gpt-5.2-codex")).await;
@@ -6021,7 +6023,7 @@ async fn realtime_audio_selection_popup_snapshot() {
assert_snapshot!("realtime_audio_selection_popup", popup);
}
#[cfg(all(not(target_os = "linux"), feature = "voice-input"))]
#[cfg(feature = "voice-input")]
#[tokio::test]
async fn realtime_audio_selection_popup_narrow_snapshot() {
let (mut chat, _rx, _op_rx) = make_chatwidget_manual(Some("gpt-5.2-codex")).await;
@@ -6031,27 +6033,49 @@ async fn realtime_audio_selection_popup_narrow_snapshot() {
assert_snapshot!("realtime_audio_selection_popup_narrow", popup);
}
#[cfg(all(not(target_os = "linux"), feature = "voice-input"))]
#[cfg(feature = "voice-input")]
#[tokio::test]
async fn realtime_microphone_picker_popup_snapshot() {
let (mut chat, _rx, _op_rx) = make_chatwidget_manual(Some("gpt-5.2-codex")).await;
chat.config.realtime_audio.microphone = Some("Studio Mic".to_string());
chat.config.realtime_audio.input_device_id = Some("studio-mic".to_string());
chat.open_realtime_audio_device_selection_with_names(
RealtimeAudioDeviceKind::Microphone,
vec!["Built-in Mic".to_string(), "USB Mic".to_string()],
vec![
AudioDeviceInfo {
id: "built-in-mic".to_string(),
name: "Built-in Mic".to_string(),
backend: "CoreAudio".to_string(),
},
AudioDeviceInfo {
id: "usb-mic".to_string(),
name: "USB Mic".to_string(),
backend: "CoreAudio".to_string(),
},
],
);
let popup = render_bottom_popup(&chat, 80);
assert_snapshot!("realtime_microphone_picker_popup", popup);
}
#[cfg(all(not(target_os = "linux"), feature = "voice-input"))]
#[cfg(feature = "voice-input")]
#[tokio::test]
async fn realtime_audio_picker_emits_persist_event() {
let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(Some("gpt-5.2-codex")).await;
chat.open_realtime_audio_device_selection_with_names(
RealtimeAudioDeviceKind::Speaker,
vec!["Desk Speakers".to_string(), "Headphones".to_string()],
vec![
AudioDeviceInfo {
id: "desk-speakers".to_string(),
name: "Desk Speakers".to_string(),
backend: "WASAPI".to_string(),
},
AudioDeviceInfo {
id: "headphones".to_string(),
name: "Headphones".to_string(),
backend: "WASAPI".to_string(),
},
],
);
chat.handle_key_event(KeyEvent::new(KeyCode::Down, KeyModifiers::NONE));
@@ -6062,8 +6086,8 @@ async fn realtime_audio_picker_emits_persist_event() {
rx.try_recv(),
Ok(AppEvent::PersistRealtimeAudioDeviceSelection {
kind: RealtimeAudioDeviceKind::Speaker,
name: Some(name),
}) if name == "Headphones"
device_id: Some(device_id),
}) if device_id == "headphones"
);
}
+3 -3
View File
@@ -63,7 +63,7 @@ mod app_backtrack;
mod app_event;
mod app_event_sender;
mod ascii_animation;
#[cfg(all(not(target_os = "linux"), feature = "voice-input"))]
#[cfg(feature = "voice-input")]
mod audio_device;
mod bottom_pane;
mod chatwidget;
@@ -119,9 +119,9 @@ pub mod update_action;
mod update_prompt;
mod updates;
mod version;
#[cfg(all(not(target_os = "linux"), feature = "voice-input"))]
#[cfg(feature = "voice-input")]
mod voice;
#[cfg(all(not(target_os = "linux"), not(feature = "voice-input")))]
#[cfg(not(feature = "voice-input"))]
mod voice {
use crate::app_event::AppEvent;
use crate::app_event_sender::AppEventSender;
+118 -504
View File
@@ -1,6 +1,10 @@
use crate::app_event::AppEvent;
use crate::app_event_sender::AppEventSender;
use base64::Engine;
use codex_audio::AUDIO_CHANNELS;
use codex_audio::AUDIO_SAMPLE_RATE;
use codex_audio::InputCapture;
use codex_audio::OutputPlayback;
use codex_core::auth::AuthCredentialsStoreMode;
use codex_core::config::Config;
use codex_core::config::find_codex_home;
@@ -10,9 +14,6 @@ use codex_login::CodexAuth;
use codex_protocol::protocol::ConversationAudioParams;
use codex_protocol::protocol::Op;
use codex_protocol::protocol::RealtimeAudioFrame;
use cpal::traits::DeviceTrait;
use cpal::traits::HostTrait;
use cpal::traits::StreamTrait;
use hound::SampleFormat;
use hound::WavSpec;
use hound::WavWriter;
@@ -22,14 +23,15 @@ use std::sync::Arc;
use std::sync::Mutex;
use std::sync::atomic::AtomicBool;
use std::sync::atomic::AtomicU16;
use std::sync::atomic::Ordering;
use tracing::debug;
use tracing::error;
use tracing::info;
use tracing::trace;
use tracing::warn;
const AUDIO_MODEL: &str = "gpt-4o-mini-transcribe";
const MODEL_AUDIO_SAMPLE_RATE: u32 = 24_000;
const MODEL_AUDIO_CHANNELS: u16 = 1;
const MODEL_AUDIO_SAMPLE_RATE: u32 = AUDIO_SAMPLE_RATE;
const MODEL_AUDIO_CHANNELS: u16 = AUDIO_CHANNELS as u16;
struct TranscriptionAuthContext {
mode: AuthMode,
@@ -38,112 +40,54 @@ struct TranscriptionAuthContext {
chatgpt_base_url: String,
}
pub struct RecordedAudio {
pub data: Vec<i16>,
pub sample_rate: u32,
pub channels: u16,
}
pub use codex_audio::RecordedAudio;
pub struct VoiceCapture {
stream: Option<cpal::Stream>,
sample_rate: u32,
channels: u16,
data: Arc<Mutex<Vec<i16>>>,
stopped: Arc<AtomicBool>,
last_peak: Arc<AtomicU16>,
capture: InputCapture,
}
impl VoiceCapture {
pub fn start() -> Result<Self, String> {
let (device, config) = select_default_input_device_and_config()?;
let sample_rate = config.sample_rate().0;
let channels = config.channels();
let data: Arc<Mutex<Vec<i16>>> = Arc::new(Mutex::new(Vec::new()));
let stopped = Arc::new(AtomicBool::new(false));
let last_peak = Arc::new(AtomicU16::new(0));
let stream = build_input_stream(&device, &config, data.clone(), last_peak.clone())?;
stream
.play()
.map_err(|e| format!("failed to start input stream: {e}"))?;
debug!("starting push-to-talk voice capture");
Ok(Self {
stream: Some(stream),
sample_rate,
channels,
data,
stopped,
last_peak,
capture: InputCapture::start_recording(None)?,
})
}
pub fn start_realtime(config: &Config, tx: AppEventSender) -> Result<Self, String> {
let (device, config) = select_realtime_input_device_and_config(config)?;
let sample_rate = config.sample_rate().0;
let channels = config.channels();
let data: Arc<Mutex<Vec<i16>>> = Arc::new(Mutex::new(Vec::new()));
let stopped = Arc::new(AtomicBool::new(false));
let last_peak = Arc::new(AtomicU16::new(0));
let stream = build_realtime_input_stream(
&device,
&config,
sample_rate,
channels,
tx,
last_peak.clone(),
)?;
stream
.play()
.map_err(|e| format!("failed to start input stream: {e}"))?;
Ok(Self {
stream: Some(stream),
sample_rate,
channels,
data,
stopped,
last_peak,
})
let device_id = config.realtime_audio.input_device_id.as_deref();
info!(
device_id = device_id.unwrap_or("system_default"),
"starting realtime microphone capture"
);
let capture = InputCapture::start_streaming(device_id, move |samples| {
send_realtime_audio_chunk(&tx, samples);
})?;
Ok(Self { capture })
}
pub fn stop(mut self) -> Result<RecordedAudio, String> {
// Mark stopped so any metering task can exit cleanly.
self.stopped.store(true, Ordering::SeqCst);
// Dropping the stream stops capture.
self.stream.take();
let data = self
.data
.lock()
.map_err(|_| "failed to lock audio buffer".to_string())?
.clone();
Ok(RecordedAudio {
data,
sample_rate: self.sample_rate,
channels: self.channels,
})
pub fn stop(self) -> Result<RecordedAudio, String> {
self.capture.stop()
}
pub fn data_arc(&self) -> Arc<Mutex<Vec<i16>>> {
self.data.clone()
self.capture.data_arc()
}
pub fn stopped_flag(&self) -> Arc<AtomicBool> {
self.stopped.clone()
self.capture.stopped_flag()
}
pub fn sample_rate(&self) -> u32 {
self.sample_rate
self.capture.sample_rate()
}
pub fn channels(&self) -> u16 {
self.channels
self.capture.channels()
}
pub fn last_peak_arc(&self) -> Arc<AtomicU16> {
self.last_peak.clone()
self.capture.last_peak_arc()
}
}
@@ -213,33 +157,43 @@ pub fn transcribe_async(
tx: AppEventSender,
) {
std::thread::spawn(move || {
// Enforce minimum duration to avoid garbage outputs.
const MIN_DURATION_SECONDS: f32 = 1.0;
const MIN_DURATION_SECONDS: f32 = 0.3;
let duration_seconds = clip_duration_seconds(&audio);
info!(
duration_seconds = duration_seconds,
sample_rate = audio.sample_rate,
channels = audio.channels,
sample_count = audio.data.len(),
has_context = context.as_ref().is_some_and(|value| !value.is_empty()),
"starting voice transcription"
);
if duration_seconds < MIN_DURATION_SECONDS {
let msg = format!(
"recording too short ({duration_seconds:.2}s); minimum is {MIN_DURATION_SECONDS:.2}s"
);
info!("{msg}");
warn!("{msg}");
tx.send(AppEvent::TranscriptionFailed { id, error: msg });
return;
}
// Encode entire clip as normalized WAV.
let wav_bytes = match encode_wav_normalized(&audio) {
Ok(b) => b,
Err(e) => {
error!("failed to encode wav: {e}");
error!(error = %e, "failed to encode transcription wav");
tx.send(AppEvent::TranscriptionFailed { id, error: e });
return;
}
};
debug!(wav_bytes = wav_bytes.len(), "encoded transcription wav");
// Run the HTTP request on a small, dedicated runtime.
let rt = match tokio::runtime::Runtime::new() {
Ok(rt) => rt,
Err(e) => {
error!("failed to create tokio runtime: {e}");
error!(error = %e, "failed to create transcription runtime");
tx.send(AppEvent::TranscriptionFailed {
id,
error: format!("failed to create transcription runtime: {e}"),
});
return;
}
};
@@ -251,163 +205,21 @@ pub fn transcribe_async(
match res {
Ok(text) => {
info!(
transcript_chars = text.chars().count(),
"voice transcription succeeded"
);
tx2.send(AppEvent::TranscriptionComplete { id: id2, text });
info!("voice transcription succeeded");
}
Err(e) => {
error!("voice transcription error: {e}");
error!(error = %e, "voice transcription failed");
tx.send(AppEvent::TranscriptionFailed { id, error: e });
}
}
});
}
// -------------------------
// Voice input helpers
// -------------------------
fn select_default_input_device_and_config()
-> Result<(cpal::Device, cpal::SupportedStreamConfig), String> {
let host = cpal::default_host();
let device = host
.default_input_device()
.ok_or_else(|| "no input audio device available".to_string())?;
let config = crate::audio_device::preferred_input_config(&device)?;
Ok((device, config))
}
fn select_realtime_input_device_and_config(
config: &Config,
) -> Result<(cpal::Device, cpal::SupportedStreamConfig), String> {
crate::audio_device::select_configured_input_device_and_config(config)
}
fn build_input_stream(
device: &cpal::Device,
config: &cpal::SupportedStreamConfig,
data: Arc<Mutex<Vec<i16>>>,
last_peak: Arc<AtomicU16>,
) -> Result<cpal::Stream, String> {
match config.sample_format() {
cpal::SampleFormat::F32 => device
.build_input_stream(
&config.clone().into(),
move |input: &[f32], _| {
let peak = peak_f32(input);
last_peak.store(peak, Ordering::Relaxed);
if let Ok(mut buf) = data.lock() {
for &s in input {
buf.push(f32_to_i16(s));
}
}
},
move |err| error!("audio input error: {err}"),
None,
)
.map_err(|e| format!("failed to build input stream: {e}")),
cpal::SampleFormat::I16 => device
.build_input_stream(
&config.clone().into(),
move |input: &[i16], _| {
let peak = peak_i16(input);
last_peak.store(peak, Ordering::Relaxed);
if let Ok(mut buf) = data.lock() {
buf.extend_from_slice(input);
}
},
move |err| error!("audio input error: {err}"),
None,
)
.map_err(|e| format!("failed to build input stream: {e}")),
cpal::SampleFormat::U16 => device
.build_input_stream(
&config.clone().into(),
move |input: &[u16], _| {
if let Ok(mut buf) = data.lock() {
let peak = convert_u16_to_i16_and_peak(input, &mut buf);
last_peak.store(peak, Ordering::Relaxed);
}
},
move |err| error!("audio input error: {err}"),
None,
)
.map_err(|e| format!("failed to build input stream: {e}")),
_ => Err("unsupported input sample format".to_string()),
}
}
fn build_realtime_input_stream(
device: &cpal::Device,
config: &cpal::SupportedStreamConfig,
sample_rate: u32,
channels: u16,
tx: AppEventSender,
last_peak: Arc<AtomicU16>,
) -> Result<cpal::Stream, String> {
match config.sample_format() {
cpal::SampleFormat::F32 => device
.build_input_stream(
&config.clone().into(),
move |input: &[f32], _| {
let peak = peak_f32(input);
last_peak.store(peak, Ordering::Relaxed);
let samples = input.iter().copied().map(f32_to_i16).collect::<Vec<_>>();
send_realtime_audio_chunk(&tx, samples, sample_rate, channels);
},
move |err| error!("audio input error: {err}"),
None,
)
.map_err(|e| format!("failed to build input stream: {e}")),
cpal::SampleFormat::I16 => device
.build_input_stream(
&config.clone().into(),
move |input: &[i16], _| {
let peak = peak_i16(input);
last_peak.store(peak, Ordering::Relaxed);
send_realtime_audio_chunk(&tx, input.to_vec(), sample_rate, channels);
},
move |err| error!("audio input error: {err}"),
None,
)
.map_err(|e| format!("failed to build input stream: {e}")),
cpal::SampleFormat::U16 => device
.build_input_stream(
&config.clone().into(),
move |input: &[u16], _| {
let mut samples = Vec::with_capacity(input.len());
let peak = convert_u16_to_i16_and_peak(input, &mut samples);
last_peak.store(peak, Ordering::Relaxed);
send_realtime_audio_chunk(&tx, samples, sample_rate, channels);
},
move |err| error!("audio input error: {err}"),
None,
)
.map_err(|e| format!("failed to build input stream: {e}")),
_ => Err("unsupported input sample format".to_string()),
}
}
fn send_realtime_audio_chunk(
tx: &AppEventSender,
samples: Vec<i16>,
sample_rate: u32,
channels: u16,
) {
if samples.is_empty() || sample_rate == 0 || channels == 0 {
return;
}
let samples = if sample_rate == MODEL_AUDIO_SAMPLE_RATE && channels == MODEL_AUDIO_CHANNELS {
samples
} else {
convert_pcm16(
&samples,
sample_rate,
channels,
MODEL_AUDIO_SAMPLE_RATE,
MODEL_AUDIO_CHANNELS,
)
};
fn send_realtime_audio_chunk(tx: &AppEventSender, samples: Vec<i16>) {
if samples.is_empty() {
return;
}
@@ -432,252 +244,61 @@ fn send_realtime_audio_chunk(
)));
}
#[inline]
fn f32_abs_to_u16(x: f32) -> u16 {
let peak_u = (x.abs().min(1.0) * i16::MAX as f32) as i32;
peak_u.max(0) as u16
}
#[inline]
fn f32_to_i16(s: f32) -> i16 {
(s.clamp(-1.0, 1.0) * i16::MAX as f32) as i16
}
fn peak_f32(input: &[f32]) -> u16 {
let mut peak: f32 = 0.0;
for &s in input {
let a = s.abs();
if a > peak {
peak = a;
}
}
f32_abs_to_u16(peak)
}
fn peak_i16(input: &[i16]) -> u16 {
let mut peak: i32 = 0;
for &s in input {
let a = (s as i32).unsigned_abs() as i32;
if a > peak {
peak = a;
}
}
peak as u16
}
fn convert_u16_to_i16_and_peak(input: &[u16], out: &mut Vec<i16>) -> u16 {
let mut peak: i32 = 0;
for &s in input {
let v_i16 = (s as i32 - 32768) as i16;
let a = (v_i16 as i32).unsigned_abs() as i32;
if a > peak {
peak = a;
}
out.push(v_i16);
}
peak as u16
}
// -------------------------
// Realtime audio playback helpers
// -------------------------
pub(crate) struct RealtimeAudioPlayer {
_stream: cpal::Stream,
queue: Arc<Mutex<VecDeque<i16>>>,
output_sample_rate: u32,
output_channels: u16,
playback: OutputPlayback,
}
impl RealtimeAudioPlayer {
pub(crate) fn start(config: &Config) -> Result<Self, String> {
let (device, config) =
crate::audio_device::select_configured_output_device_and_config(config)?;
let output_sample_rate = config.sample_rate().0;
let output_channels = config.channels();
let queue = Arc::new(Mutex::new(VecDeque::new()));
let stream = build_output_stream(&device, &config, Arc::clone(&queue))?;
stream
.play()
.map_err(|e| format!("failed to start output stream: {e}"))?;
info!(
device_id = config
.realtime_audio
.output_device_id
.as_deref()
.unwrap_or("system_default"),
"starting realtime speaker output"
);
Ok(Self {
_stream: stream,
queue,
output_sample_rate,
output_channels,
playback: OutputPlayback::start(config.realtime_audio.output_device_id.as_deref())?,
})
}
pub(crate) fn enqueue_frame(&self, frame: &RealtimeAudioFrame) -> Result<(), String> {
if frame.num_channels == 0 || frame.sample_rate == 0 {
return Err("invalid realtime audio frame format".to_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 converted = convert_pcm16(
&pcm,
frame.sample_rate,
frame.num_channels,
self.output_sample_rate,
self.output_channels,
);
if converted.is_empty() {
return Ok(());
}
let mut guard = self
.queue
.lock()
.map_err(|_| "failed to lock output audio queue".to_string())?;
// TODO(aibrahim): Cap or trim this queue if we observe producer bursts outrunning playback.
guard.extend(converted);
Ok(())
self.playback.enqueue_samples(&pcm)
}
pub(crate) fn clear(&self) {
if let Ok(mut guard) = self.queue.lock() {
guard.clear();
}
self.playback.clear();
}
}
fn build_output_stream(
device: &cpal::Device,
config: &cpal::SupportedStreamConfig,
queue: Arc<Mutex<VecDeque<i16>>>,
) -> Result<cpal::Stream, String> {
let config_any: cpal::StreamConfig = config.clone().into();
match config.sample_format() {
cpal::SampleFormat::F32 => device
.build_output_stream(
&config_any,
move |output: &mut [f32], _| fill_output_f32(output, &queue),
move |err| error!("audio output error: {err}"),
None,
)
.map_err(|e| format!("failed to build f32 output stream: {e}")),
cpal::SampleFormat::I16 => device
.build_output_stream(
&config_any,
move |output: &mut [i16], _| fill_output_i16(output, &queue),
move |err| error!("audio output error: {err}"),
None,
)
.map_err(|e| format!("failed to build i16 output stream: {e}")),
cpal::SampleFormat::U16 => device
.build_output_stream(
&config_any,
move |output: &mut [u16], _| fill_output_u16(output, &queue),
move |err| error!("audio output error: {err}"),
None,
)
.map_err(|e| format!("failed to build u16 output stream: {e}")),
other => Err(format!("unsupported output sample format: {other:?}")),
}
}
fn fill_output_i16(output: &mut [i16], queue: &Arc<Mutex<VecDeque<i16>>>) {
if let Ok(mut guard) = queue.lock() {
for sample in output {
*sample = guard.pop_front().unwrap_or(0);
}
return;
}
output.fill(0);
}
fn fill_output_f32(output: &mut [f32], queue: &Arc<Mutex<VecDeque<i16>>>) {
if let Ok(mut guard) = queue.lock() {
for sample in output {
let v = guard.pop_front().unwrap_or(0);
*sample = (v as f32) / (i16::MAX as f32);
}
return;
}
output.fill(0.0);
}
fn fill_output_u16(output: &mut [u16], queue: &Arc<Mutex<VecDeque<i16>>>) {
if let Ok(mut guard) = queue.lock() {
for sample in output {
let v = guard.pop_front().unwrap_or(0);
*sample = (v as i32 + 32768).clamp(0, u16::MAX as i32) as u16;
}
return;
}
output.fill(32768);
}
fn convert_pcm16(
input: &[i16],
input_sample_rate: u32,
input_channels: u16,
output_sample_rate: u32,
output_channels: u16,
) -> Vec<i16> {
if input.is_empty() || input_channels == 0 || output_channels == 0 {
return Vec::new();
}
let in_channels = input_channels as usize;
let out_channels = output_channels as usize;
let in_frames = input.len() / in_channels;
if in_frames == 0 {
return Vec::new();
}
let out_frames = if input_sample_rate == output_sample_rate {
in_frames
} else {
(((in_frames as u64) * (output_sample_rate as u64)) / (input_sample_rate as u64)).max(1)
as usize
};
let mut out = Vec::with_capacity(out_frames.saturating_mul(out_channels));
for out_frame_idx in 0..out_frames {
let src_frame_idx = if out_frames <= 1 || in_frames <= 1 {
0
} else {
((out_frame_idx as u64) * ((in_frames - 1) as u64) / ((out_frames - 1) as u64)) as usize
};
let src_start = src_frame_idx.saturating_mul(in_channels);
let src = &input[src_start..src_start + in_channels];
match (in_channels, out_channels) {
(1, 1) => out.push(src[0]),
(1, n) => {
for _ in 0..n {
out.push(src[0]);
}
}
(n, 1) if n >= 2 => {
let sum: i32 = src.iter().map(|s| *s as i32).sum();
out.push((sum / (n as i32)) as i16);
}
(n, m) if n == m => out.extend_from_slice(src),
(n, m) if n > m => out.extend_from_slice(&src[..m]),
(n, m) => {
out.extend_from_slice(src);
let last = *src.last().unwrap_or(&0);
for _ in n..m {
out.push(last);
}
}
}
}
out
}
// -------------------------
// Transcription helpers
// -------------------------
fn clip_duration_seconds(audio: &RecordedAudio) -> f32 {
let total_samples = audio.data.len() as f32;
let samples_per_second = (audio.sample_rate as f32) * (audio.channels as f32);
@@ -689,29 +310,17 @@ fn clip_duration_seconds(audio: &RecordedAudio) -> f32 {
}
fn encode_wav_normalized(audio: &RecordedAudio) -> Result<Vec<u8>, String> {
let converted;
let (channels, sample_rate, segment) =
if audio.channels == MODEL_AUDIO_CHANNELS && audio.sample_rate == MODEL_AUDIO_SAMPLE_RATE {
(audio.channels, audio.sample_rate, audio.data.as_slice())
} else {
converted = convert_pcm16(
&audio.data,
audio.sample_rate,
audio.channels,
MODEL_AUDIO_SAMPLE_RATE,
MODEL_AUDIO_CHANNELS,
);
(
MODEL_AUDIO_CHANNELS,
MODEL_AUDIO_SAMPLE_RATE,
converted.as_slice(),
)
};
if audio.channels != MODEL_AUDIO_CHANNELS || audio.sample_rate != MODEL_AUDIO_SAMPLE_RATE {
return Err(format!(
"unexpected recorded audio format: {} Hz / {} channels",
audio.sample_rate, audio.channels
));
}
let mut wav_bytes: Vec<u8> = Vec::new();
let spec = WavSpec {
channels,
sample_rate,
channels: audio.channels,
sample_rate: audio.sample_rate,
bits_per_sample: 16,
sample_format: SampleFormat::Int,
};
@@ -719,28 +328,27 @@ fn encode_wav_normalized(audio: &RecordedAudio) -> Result<Vec<u8>, String> {
let mut writer =
WavWriter::new(&mut cursor, spec).map_err(|_| "failed to create wav writer".to_string())?;
// Simple peak normalization with headroom to improve audibility on quiet inputs.
let mut peak: i16 = 0;
for &s in segment {
let a = s.unsigned_abs();
if a > peak.unsigned_abs() {
peak = s;
for &sample in &audio.data {
let absolute = sample.unsigned_abs();
if absolute > peak.unsigned_abs() {
peak = sample;
}
}
let peak_abs = (peak as i32).unsigned_abs() as i32;
let target = (i16::MAX as f32) * 0.9; // leave some headroom
let gain: f32 = if peak_abs > 0 {
let target = (i16::MAX as f32) * 0.9;
let gain = if peak_abs > 0 {
target / (peak_abs as f32)
} else {
1.0
};
for &s in segment {
let v = ((s as f32) * gain)
for &sample in &audio.data {
let normalized = ((sample as f32) * gain)
.round()
.clamp(i16::MIN as f32, i16::MAX as f32) as i16;
writer
.write_sample(v)
.write_sample(normalized)
.map_err(|_| "failed writing wav sample".to_string())?;
}
writer
@@ -835,21 +443,30 @@ async fn transcribe_bytes(
let audio_kib = audio_bytes as f32 / 1024.0;
let mode = auth.mode;
trace!(
"sending transcription request: mode={mode:?} endpoint={endpoint} duration={duration_seconds:.2}s audio={audio_kib:.1}KiB prompt={prompt_for_log}"
let prompt_chars = prompt_for_log.chars().count();
info!(
?mode,
endpoint,
duration_seconds,
audio_kib,
prompt_chars,
model = AUDIO_MODEL,
"sending transcription request"
);
let resp = request
.send()
.await
.map_err(|e| format!("transcription request failed: {e}"))?;
let status = resp.status();
trace!(%status, "received transcription response");
if !resp.status().is_success() {
let status = resp.status();
if !status.is_success() {
let body = resp
.text()
.await
.unwrap_or_else(|_| "<failed to read body>".to_string());
error!(%status, body, "transcription request returned error");
return Err(format!("transcription failed: {status} {body}"));
}
@@ -864,8 +481,13 @@ async fn transcribe_bytes(
.to_string();
if text.is_empty() {
warn!("transcription response was empty");
Err("empty transcription result".to_string())
} else {
debug!(
transcript_chars = text.chars().count(),
"parsed transcription response"
);
Ok(text)
}
}
@@ -873,24 +495,16 @@ async fn transcribe_bytes(
#[cfg(test)]
mod tests {
use super::RecordedAudio;
use super::convert_pcm16;
use super::encode_wav_normalized;
use pretty_assertions::assert_eq;
use std::io::Cursor;
#[test]
fn convert_pcm16_downmixes_and_resamples_for_model_input() {
let input = vec![100, 300, 200, 400, 500, 700, 600, 800];
let converted = convert_pcm16(&input, 48_000, 2, 24_000, 1);
assert_eq!(converted, vec![200, 700]);
}
#[test]
fn encode_wav_normalized_outputs_24khz_mono_audio() {
let audio = RecordedAudio {
data: vec![100, 300, 200, 400, 500, 700, 600, 800],
sample_rate: 48_000,
channels: 2,
data: vec![100, 300, 200, 400],
sample_rate: 24_000,
channels: 1,
};
let wav = encode_wav_normalized(&audio).expect("wav should encode");
@@ -903,6 +517,6 @@ mod tests {
assert_eq!(spec.channels, 1);
assert_eq!(spec.sample_rate, 24_000);
assert_eq!(samples, vec![8_426, 29_490]);
assert_eq!(samples, vec![7_373, 22_118, 14_745, 29_490]);
}
}