Skip to main content

oa/audio/
capture.rs

1//! Real-time device capture into a bounded lock-free FP32 ring.
2
3pub use crate::audio::types::AudioCaptureConfig;
4use std::{
5	sync::{
6		Arc, Mutex, OnceLock,
7		atomic::{AtomicBool, AtomicU64, Ordering},
8	},
9	thread,
10	time::Instant,
11};
12
13use cpal::{
14	Data, FromSample, Sample, SampleFormat, SizedSample, Stream,
15	traits::{DeviceTrait, StreamTrait},
16};
17use rtrb::{Consumer, Producer, PushError, RingBuffer};
18
19use super::player::{cpal_error, ring_capacity};
20use crate::{Engine, Error, Result, runtime::EngineHandle};
21
22static MONOTONIC_EPOCH: OnceLock<Instant> = OnceLock::new();
23
24impl Default for AudioCaptureConfig {
25	fn default() -> Self {
26		Self {
27			sample_rate: 48_000,
28			channel_count: 2,
29			ring_milliseconds: 500,
30		}
31	}
32}
33
34/// One contiguous run of captured interleaved FP32 frames.
35#[derive(Clone, Debug, PartialEq)]
36pub struct AudioCaptureChunk {
37	pub interleaved: Vec<f32>,
38	pub sample_rate: u32,
39	pub channel_count: u32,
40	pub frame_count: u64,
41	pub first_frame_index: u64,
42	/// Process-monotonic presentation timestamp in microseconds.
43	pub presentation_timestamp_us: u64,
44}
45
46/// Stateful default-device audio capture session.
47pub struct AudioCapture {
48	_engine: EngineHandle,
49	service: Option<CaptureService>,
50	shared: Arc<CaptureShared>,
51	consumer: Consumer<CaptureFrame>,
52	pending: Option<CaptureFrame>,
53	config: AudioCaptureConfig,
54}
55
56struct CaptureService {
57	stream: Stream,
58}
59
60struct CaptureShared {
61	accepting: AtomicBool,
62	active_callbacks: AtomicU64,
63	started: AtomicBool,
64	captured_frames: AtomicU64,
65	dropped_frames: AtomicU64,
66	epoch_us: AtomicU64,
67	device_errors: AtomicU64,
68}
69
70#[derive(Clone, Copy, Default)]
71struct CaptureFrame {
72	samples: [f32; 8],
73	index: u64,
74}
75
76impl AudioCapture {
77	/// Open the default input device. The returned session is initially stopped.
78	pub fn open(engine: &Engine, config: AudioCaptureConfig) -> Result<Self> {
79		if config.sample_rate == 0
80			|| !(1..=8).contains(&config.channel_count)
81			|| config.ring_milliseconds < 20
82		{
83			return Err(Error::invalid_argument(
84				"AudioCapture requires a sample rate, 1..8 channels, and at least 20 ms of ring storage",
85			));
86		}
87		let capacity = ring_capacity(config.sample_rate, config.ring_milliseconds, "AudioCapture")?;
88		// Initialize process timing before the real-time callback can run.
89		let _ = MONOTONIC_EPOCH.get_or_init(Instant::now);
90		let (mut producer, consumer) = RingBuffer::<CaptureFrame>::new(capacity);
91		let shared = Arc::new(CaptureShared {
92			accepting: AtomicBool::new(false),
93			active_callbacks: AtomicU64::new(0),
94			started: AtomicBool::new(false),
95			captured_frames: AtomicU64::new(0),
96			dropped_frames: AtomicU64::new(0),
97			epoch_us: AtomicU64::new(0),
98			device_errors: AtomicU64::new(0),
99		});
100
101		let host = cpal::default_host();
102		let (device, stream_config) = super::device::select_device(
103			engine,
104			&host,
105			super::device::Direction::Input,
106			config.sample_rate,
107			config.channel_count,
108		)?;
109		let sample_format = stream_config.sample_format();
110		let callback_shared = Arc::clone(&shared);
111		let error_shared = Arc::clone(&shared);
112		let stream = device
113			.build_input_stream_raw(
114				stream_config.config(),
115				sample_format,
116				move |input, _| {
117					capture_callback(
118						&callback_shared,
119						&mut producer,
120						input,
121						config.sample_rate,
122						config.channel_count,
123					);
124				},
125				move |_| {
126					error_shared.device_errors.fetch_add(1, Ordering::Relaxed);
127				},
128				None,
129			)
130			.map_err(|error| cpal_error("capture stream creation", error))?;
131		Ok(Self {
132			_engine: engine.handle(),
133			service: Some(CaptureService { stream }),
134			shared,
135			consumer,
136			pending: None,
137			config,
138		})
139	}
140
141	/// Start capture and reset frame indices, timestamps, and drop counters.
142	pub fn start(&mut self) -> Result<()> {
143		let service = self
144			.service
145			.as_ref()
146			.ok_or_else(|| Error::failed_precondition("AudioCapture is closed"))?;
147		if self.shared.started.load(Ordering::Acquire) {
148			return Ok(());
149		}
150		while self.consumer.pop().is_ok() {}
151		self.pending = None;
152		self.shared.captured_frames.store(0, Ordering::Relaxed);
153		self.shared.dropped_frames.store(0, Ordering::Relaxed);
154		self.shared.device_errors.store(0, Ordering::Relaxed);
155		self.shared.epoch_us.store(0, Ordering::Release);
156		self.shared.accepting.store(true, Ordering::Release);
157		if let Err(error) = service.stream.play() {
158			self.shared.accepting.store(false, Ordering::Release);
159			return Err(cpal_error("capture stream start", error));
160		}
161		self.shared.started.store(true, Ordering::Release);
162		Ok(())
163	}
164
165	/// Stop callback delivery without releasing the device.
166	///
167	/// On backends without hardware pause, the stream remains active but its
168	/// frames are discarded until restart. Use `close` to release the device.
169	pub fn stop(&mut self) -> Result<()> {
170		self.shared.accepting.store(false, Ordering::SeqCst);
171		if !self.shared.started.swap(false, Ordering::AcqRel) {
172			return Ok(());
173		}
174		let Some(service) = self.service.as_ref() else {
175			return Ok(());
176		};
177		let result = match service.stream.pause() {
178			Ok(()) => Ok(()),
179			// ALSA desktop bridges may not pause. The callback delivery gate is
180			// still authoritative, and play() is idempotent on a running stream.
181			Err(error) if error.kind() == cpal::ErrorKind::UnsupportedOperation => Ok(()),
182			Err(error) => Err(cpal_error("capture stream stop", error)),
183		};
184		// Finish any callback admitted before closing the delivery gate before
185		// start() can reset counters or expose a new capture epoch. SeqCst orders
186		// the gate and callback registration across these two atomics.
187		while self.shared.active_callbacks.load(Ordering::SeqCst) != 0 {
188			thread::yield_now();
189		}
190		result
191	}
192
193	/// Return the next contiguous frame run without blocking.
194	///
195	/// A physical capture gap caused by a full ring ends the current chunk. The
196	/// next call begins at the first frame after that gap.
197	pub fn poll(&mut self, max_frames: u32) -> Option<AudioCaptureChunk> {
198		if self.service.is_none() || max_frames == 0 {
199			return None;
200		}
201		let first = self.pending.take().or_else(|| self.consumer.pop().ok())?;
202		let mut interleaved =
203			Vec::with_capacity(max_frames as usize * self.config.channel_count as usize);
204		interleaved.extend_from_slice(&first.samples[..self.config.channel_count as usize]);
205		let mut expected = first.index.saturating_add(1);
206		let mut frame_count = 1_u64;
207		while frame_count < u64::from(max_frames) {
208			let Ok(frame) = self.consumer.pop() else {
209				break;
210			};
211			if frame.index != expected {
212				self.pending = Some(frame);
213				break;
214			}
215			interleaved.extend_from_slice(&frame.samples[..self.config.channel_count as usize]);
216			expected = expected.saturating_add(1);
217			frame_count += 1;
218		}
219		let epoch = self.shared.epoch_us.load(Ordering::Acquire);
220		Some(AudioCaptureChunk {
221			interleaved,
222			sample_rate: self.config.sample_rate,
223			channel_count: self.config.channel_count,
224			frame_count,
225			first_frame_index: first.index,
226			presentation_timestamp_us: epoch
227				.saturating_add(first.index.saturating_mul(1_000_000) / u64::from(self.config.sample_rate)),
228		})
229	}
230
231	/// Stop capture and release the device at an explicit result-bearing boundary.
232	pub fn close(&mut self) -> Result<()> {
233		let Some(service) = self.service.take() else {
234			return Ok(());
235		};
236		self.shared.accepting.store(false, Ordering::Release);
237		self.shared.started.store(false, Ordering::Release);
238		// As for AudioPlayer, destruction stops and joins the callback worker;
239		// optional hardware pause must not gate explicit close.
240		drop(service);
241		Ok(())
242	}
243
244	pub fn is_open(&self) -> bool {
245		self.service.is_some()
246	}
247
248	pub fn is_started(&self) -> bool {
249		self.is_open() && self.shared.started.load(Ordering::Acquire)
250	}
251
252	pub fn dropped_frame_count(&self) -> u64 {
253		self.shared.dropped_frames.load(Ordering::Relaxed)
254	}
255
256	pub fn device_error_count(&self) -> u64 {
257		self.shared.device_errors.load(Ordering::Relaxed)
258	}
259}
260
261impl Drop for AudioCapture {
262	fn drop(&mut self) {
263		let Some(service) = self.service.take() else {
264			return;
265		};
266		self.shared.accepting.store(false, Ordering::Release);
267		self.shared.started.store(false, Ordering::Release);
268		retire_capture(service);
269	}
270}
271
272fn retire_capture(service: CaptureService) {
273	let retirement = Arc::new(Mutex::new(Some(service)));
274	let worker = Arc::clone(&retirement);
275	let spawned = thread::Builder::new()
276		.name("oa-audio-capture-retirement".into())
277		.spawn(move || {
278			if let Ok(mut slot) = worker.lock()
279				&& let Some(service) = slot.take()
280			{
281				drop(service);
282			}
283		});
284	if spawned.is_err() {
285		// A worker-spawn failure must not turn Drop into an implicit device stop.
286		std::mem::forget(retirement);
287	}
288}
289
290fn capture_callback(
291	shared: &CaptureShared,
292	producer: &mut Producer<CaptureFrame>,
293	input: &Data,
294	sample_rate: u32,
295	channels: u32,
296) {
297	shared.active_callbacks.fetch_add(1, Ordering::SeqCst);
298	if !shared.accepting.load(Ordering::SeqCst) {
299		shared.active_callbacks.fetch_sub(1, Ordering::SeqCst);
300		return;
301	}
302	match input.sample_format() {
303		SampleFormat::I8 => capture_input::<i8>(shared, producer, input, sample_rate, channels),
304		SampleFormat::I16 => capture_input::<i16>(shared, producer, input, sample_rate, channels),
305		SampleFormat::I24 => capture_input::<cpal::I24>(shared, producer, input, sample_rate, channels),
306		SampleFormat::I32 => capture_input::<i32>(shared, producer, input, sample_rate, channels),
307		SampleFormat::I64 => capture_input::<i64>(shared, producer, input, sample_rate, channels),
308		SampleFormat::U8 => capture_input::<u8>(shared, producer, input, sample_rate, channels),
309		SampleFormat::U16 => capture_input::<u16>(shared, producer, input, sample_rate, channels),
310		SampleFormat::U24 => capture_input::<cpal::U24>(shared, producer, input, sample_rate, channels),
311		SampleFormat::U32 => capture_input::<u32>(shared, producer, input, sample_rate, channels),
312		SampleFormat::U64 => capture_input::<u64>(shared, producer, input, sample_rate, channels),
313		SampleFormat::F32 => capture_input::<f32>(shared, producer, input, sample_rate, channels),
314		SampleFormat::F64 => capture_input::<f64>(shared, producer, input, sample_rate, channels),
315		_ => {}
316	}
317	shared.active_callbacks.fetch_sub(1, Ordering::SeqCst);
318}
319
320fn capture_input<T>(
321	shared: &CaptureShared,
322	producer: &mut Producer<CaptureFrame>,
323	input: &Data,
324	sample_rate: u32,
325	channels: u32,
326) where
327	T: SizedSample + Copy,
328	f32: FromSample<T>,
329{
330	let Some(samples) = input.as_slice::<T>() else {
331		return;
332	};
333	let channels = channels as usize;
334	let frame_count = samples.len() / channels;
335	if frame_count == 0 {
336		return;
337	}
338	let first_index = shared
339		.captured_frames
340		.fetch_add(frame_count as u64, Ordering::Relaxed);
341	if shared.epoch_us.load(Ordering::Relaxed) == 0 {
342		let duration = (frame_count as u64).saturating_mul(1_000_000) / u64::from(sample_rate);
343		let epoch = monotonic_microseconds().saturating_sub(duration).max(1);
344		let _ = shared
345			.epoch_us
346			.compare_exchange(0, epoch, Ordering::Release, Ordering::Relaxed);
347	}
348	for frame_offset in 0..frame_count {
349		let mut frame = CaptureFrame {
350			index: first_index.saturating_add(frame_offset as u64),
351			..CaptureFrame::default()
352		};
353		let begin = frame_offset * channels;
354		for channel in 0..channels {
355			frame.samples[channel] = <f32 as Sample>::from_sample(samples[begin + channel]);
356		}
357		if let Err(PushError::Full(_)) = producer.push(frame) {
358			shared
359				.dropped_frames
360				.fetch_add((frame_count - frame_offset) as u64, Ordering::Relaxed);
361			break;
362		}
363	}
364}
365
366fn monotonic_microseconds() -> u64 {
367	let Some(epoch) = MONOTONIC_EPOCH.get() else {
368		return 0;
369	};
370	u64::try_from(epoch.elapsed().as_micros()).unwrap_or(u64::MAX)
371}