feat #14740: two-track capture and recorder
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,154 @@
|
||||
//! PulseAudio (and PipeWire via pipewire-pulse) capture with libpulse-simple.
|
||||
//!
|
||||
//! Streams are opened directly as 16 kHz mono `f32`, so the server does the
|
||||
//! resampling and downmix and the recorder's conditioner passes them through.
|
||||
//! The call output is recorded from the default sink's monitor source;
|
||||
//! per-process capture does not exist here, so `OutputTarget::Process` falls
|
||||
//! back to that monitor as well.
|
||||
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
|
||||
use libpulse_binding::def::BufferAttr;
|
||||
use libpulse_binding::error::{Code, PAErr};
|
||||
use libpulse_binding::sample::{Format, Spec};
|
||||
use libpulse_binding::stream::Direction;
|
||||
use libpulse_simple_binding::Simple;
|
||||
use recorder_core::capture::{
|
||||
CaptureError, CaptureSource, DataCallback, Devices, OutputTarget, StreamFormat,
|
||||
};
|
||||
|
||||
use crate::capture_thread::{CaptureThread, Ready};
|
||||
|
||||
const APP_NAME: &str = "Gesprächsrekorder";
|
||||
const DEFAULT_MONITOR: &str = "@DEFAULT_MONITOR@";
|
||||
const FORMAT: StreamFormat = StreamFormat {
|
||||
rate: 16_000,
|
||||
channels: 1,
|
||||
};
|
||||
/// Samples per blocking read (20 ms). Also bounds how long `stop` waits.
|
||||
const CHUNK_SAMPLES: usize = 320;
|
||||
const CHUNK_BYTES: usize = CHUNK_SAMPLES * std::mem::size_of::<f32>();
|
||||
|
||||
/// A PulseAudio record stream on one source (microphone or monitor).
|
||||
pub struct PulseSource {
|
||||
/// Source name; `None` for the server's default source.
|
||||
device: Option<String>,
|
||||
stream_name: &'static str,
|
||||
thread: Option<CaptureThread>,
|
||||
}
|
||||
|
||||
pub fn mic_source(device: Option<&str>) -> Box<dyn CaptureSource> {
|
||||
Box::new(PulseSource {
|
||||
device: device.map(str::to_owned),
|
||||
stream_name: "Mikrofon",
|
||||
thread: None,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn output_source(target: OutputTarget) -> Box<dyn CaptureSource> {
|
||||
let device = match target {
|
||||
OutputTarget::Process { .. } | OutputTarget::DefaultRender => DEFAULT_MONITOR.to_owned(),
|
||||
OutputTarget::Device(name) => name,
|
||||
};
|
||||
Box::new(PulseSource {
|
||||
device: Some(device),
|
||||
stream_name: "Gesprächsaudio",
|
||||
thread: None,
|
||||
})
|
||||
}
|
||||
|
||||
/// Device enumeration is not offered on Linux; recordings use the defaults.
|
||||
pub fn list_devices() -> Devices {
|
||||
Devices::default()
|
||||
}
|
||||
|
||||
impl CaptureSource for PulseSource {
|
||||
fn start(&mut self, on_data: DataCallback) -> Result<StreamFormat, CaptureError> {
|
||||
self.stop();
|
||||
let device = self.device.clone();
|
||||
let stream_name = self.stream_name;
|
||||
let (thread, format) =
|
||||
CaptureThread::spawn(&format!("pulse {stream_name}"), move |stop, ready| {
|
||||
run(device.as_deref(), stream_name, stop, ready, on_data)
|
||||
})?;
|
||||
self.thread = Some(thread);
|
||||
Ok(format)
|
||||
}
|
||||
|
||||
fn stop(&mut self) {
|
||||
if let Some(thread) = self.thread.take() {
|
||||
thread.stop();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for PulseSource {
|
||||
fn drop(&mut self) {
|
||||
self.stop();
|
||||
}
|
||||
}
|
||||
|
||||
fn open(device: Option<&str>, stream_name: &str) -> Result<Simple, CaptureError> {
|
||||
let spec = Spec {
|
||||
format: Format::FLOAT32NE,
|
||||
rate: FORMAT.rate,
|
||||
channels: FORMAT.channels as u8,
|
||||
};
|
||||
let attr = BufferAttr {
|
||||
maxlength: u32::MAX,
|
||||
tlength: u32::MAX,
|
||||
prebuf: u32::MAX,
|
||||
minreq: u32::MAX,
|
||||
fragsize: CHUNK_BYTES as u32,
|
||||
};
|
||||
Simple::new(
|
||||
None,
|
||||
APP_NAME,
|
||||
Direction::Record,
|
||||
device,
|
||||
stream_name,
|
||||
&spec,
|
||||
None,
|
||||
Some(&attr),
|
||||
)
|
||||
.map_err(|err| to_capture_error(err, device))
|
||||
}
|
||||
|
||||
fn to_capture_error(err: PAErr, device: Option<&str>) -> CaptureError {
|
||||
match (Code::try_from(err), device) {
|
||||
(Ok(Code::NoEntity), Some(device)) => CaptureError::DeviceNotFound(device.to_owned()),
|
||||
_ => CaptureError::Backend(format!("PulseAudio: {err}")),
|
||||
}
|
||||
}
|
||||
|
||||
fn run(
|
||||
device: Option<&str>,
|
||||
stream_name: &str,
|
||||
stop: &AtomicBool,
|
||||
ready: Ready,
|
||||
mut on_data: DataCallback,
|
||||
) {
|
||||
let simple = match open(device, stream_name) {
|
||||
Ok(simple) => simple,
|
||||
Err(err) => {
|
||||
let _ = ready.send(Err(err));
|
||||
return;
|
||||
}
|
||||
};
|
||||
let _ = ready.send(Ok(FORMAT));
|
||||
|
||||
let mut bytes = vec![0u8; CHUNK_BYTES];
|
||||
let mut samples = vec![0f32; CHUNK_SAMPLES];
|
||||
while !stop.load(Ordering::SeqCst) {
|
||||
if let Err(err) = simple.read(&mut bytes) {
|
||||
// Source gone (unplugged, server restart): stop delivering; the
|
||||
// recorder keeps the track aligned with silence.
|
||||
log::warn!("PulseAudio capture '{stream_name}' ended: {err}");
|
||||
return;
|
||||
}
|
||||
for (sample, raw) in samples.iter_mut().zip(bytes.as_chunks::<4>().0) {
|
||||
*sample = f32::from_ne_bytes(*raw);
|
||||
}
|
||||
on_data(&samples);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user