chore #14740: capture diagnostics logging

Add diagnostic logging (no behaviour change) to distinguish, from one
instrumented Windows test call, whether an auto-detected call records
nothing because the wrong process tree was targeted, packets arrive but
are flagged silent, or process loopback failed to start and the fallback
hit the wrong device:

- Log one line on every successful WASAPI stream open (initial and
  reopen): endpoint description (process tree pid + exe name for
  loopback, friendly name/id/role for device endpoints), rate and
  channels.
- output_source_with_fallback: Info line when the primary target starts
  OK; the existing fallback Warn line now also names DefaultRender
  explicitly.
- New CaptureStats (crates/audio/src/stats.rs), shared by the Windows
  and Linux capture loops: counts packets, frames, packets flagged
  silent, and the peak absolute sample value, reported every 10 s and
  once more when a stream stops. Plain counters updated inline on the
  audio thread; no locks, no extra threads.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
hauke
2026-11-05 16:27:38 +01:00
co-authored by Claude Sonnet 5
parent c3254c3da0
commit 1420e56e77
6 changed files with 224 additions and 21 deletions
+69 -17
View File
@@ -15,6 +15,7 @@
use std::sync::atomic::{AtomicBool, Ordering};
use std::thread;
use std::time::Instant;
use recorder_core::capture::{
CaptureError, CaptureSource, DataCallback, DeviceInfo, Devices, OutputTarget, StreamFormat,
@@ -25,6 +26,9 @@ use wasapi::{
};
use crate::capture_thread::{CaptureThread, Ready};
use crate::stats::CaptureStats;
use super::sessions;
/// `AUDCLNT_E_DEVICE_INVALIDATED`: the endpoint was removed or disabled.
const AUDCLNT_E_DEVICE_INVALIDATED: i32 = 0x8889_0004_u32 as i32;
@@ -183,28 +187,61 @@ fn device_by_id(enumerator: &DeviceEnumerator, id: &str) -> Result<Device, Captu
.map_err(|_| CaptureError::DeviceNotFound(id.to_owned()))
}
/// Describes the endpoint `open` just opened, for the one-line log on a
/// successful open. For process loopback that is the root pid and the exe
/// name of that process (looked up the same way call detection does);
/// "unknown" if the process cannot be resolved. For a device endpoint it is
/// the friendly name, the device id and whether it was picked as the
/// communications default or by an explicit id.
fn describe_endpoint(endpoint: &Endpoint, device: Option<&Device>, role: &str) -> String {
match endpoint {
Endpoint::Output(OutputTarget::Process { root_pid }) => {
let exe = sessions::image_name(*root_pid).unwrap_or_else(|| "unknown".to_string());
format!("process tree pid {root_pid} ({exe})")
}
_ => {
let device = device.expect("device endpoint always has a Device");
let name = device
.get_friendlyname()
.unwrap_or_else(|_| "unknown".to_string());
let id = device.get_id().unwrap_or_else(|_| "unknown".to_string());
format!("{name} ({id}, {role})")
}
}
}
/// Opens `endpoint` and starts streaming. `format` forces a stream format
/// (used when reopening); otherwise the endpoint's mix format is used, with
/// the samples converted to `f32` by the audio engine.
fn open(endpoint: &Endpoint, format: Option<StreamFormat>) -> Result<Stream, CaptureError> {
let mut client = match endpoint {
let (mut client, description) = match endpoint {
Endpoint::Output(OutputTarget::Process { root_pid }) => {
AudioClient::new_application_loopback_client(*root_pid, true).map_err(backend)?
let client =
AudioClient::new_application_loopback_client(*root_pid, true).map_err(backend)?;
let description = describe_endpoint(endpoint, None, "");
(client, description)
}
_ => {
let enumerator = DeviceEnumerator::new().map_err(backend)?;
let device = match endpoint {
let (device, role) = match endpoint {
Endpoint::Mic(Some(id)) | Endpoint::Output(OutputTarget::Device(id)) => {
device_by_id(&enumerator, id)?
(device_by_id(&enumerator, id)?, "explicit id")
}
Endpoint::Mic(None) => enumerator
.get_default_device_for_role(&Direction::Capture, &Role::Communications)
.map_err(backend)?,
Endpoint::Output(_) => enumerator
.get_default_device_for_role(&Direction::Render, &Role::Communications)
.map_err(backend)?,
Endpoint::Mic(None) => (
enumerator
.get_default_device_for_role(&Direction::Capture, &Role::Communications)
.map_err(backend)?,
"communications default",
),
Endpoint::Output(_) => (
enumerator
.get_default_device_for_role(&Direction::Render, &Role::Communications)
.map_err(backend)?,
"communications default",
),
};
device.get_iaudioclient().map_err(backend)?
let description = describe_endpoint(endpoint, Some(&device), role);
(device.get_iaudioclient().map_err(backend)?, description)
}
};
@@ -239,6 +276,12 @@ fn open(endpoint: &Endpoint, format: Option<StreamFormat>) -> Result<Stream, Cap
let event = client.set_get_eventhandle().map_err(backend)?;
let capture = client.get_audiocaptureclient().map_err(backend)?;
client.start_stream().map_err(backend)?;
log::info!(
"WASAPI capture '{}' opened: {description}, {} Hz, {} ch",
endpoint.label(),
format.rate,
format.channels
);
Ok(Stream {
client,
capture,
@@ -285,16 +328,22 @@ fn capture(
let mut reopened = false;
let mut bytes = Vec::new();
let mut samples = Vec::new();
while !stop.load(Ordering::SeqCst) {
let mut stats = CaptureStats::new(Instant::now());
let result = loop {
if stop.load(Ordering::SeqCst) {
break Ok(());
}
// A timeout is normal (silent loopback); drain regardless, which
// also surfaces an invalidated device.
let _ = stream.event.wait_for_event(WAIT_MS);
let Err(err) = drain(&stream, &mut bytes, &mut samples, &mut on_data) else {
let drained = drain(&stream, &mut bytes, &mut samples, &mut on_data, &mut stats);
stats.maybe_report(label, Instant::now());
let Err(err) = drained else {
continue;
};
if !is_device_invalidated(&err) || reopened {
log::warn!("WASAPI capture '{label}' ended: {err}");
return Err(format!("WASAPI: {err}"));
break Err(format!("WASAPI: {err}"));
}
reopened = true;
log::warn!("WASAPI capture '{label}': device invalidated, reopening the default device");
@@ -303,11 +352,12 @@ fn capture(
Ok(stream) => stream,
Err(err) => {
log::warn!("WASAPI capture '{label}': reopening failed: {err}");
return Err(format!("device lost, reopening failed: {err}"));
break Err(format!("device lost, reopening failed: {err}"));
}
};
}
Ok(())
};
stats.report_final(label);
result
}
/// Delivers every packet currently queued in the capture buffer.
@@ -316,6 +366,7 @@ fn drain(
bytes: &mut Vec<u8>,
samples: &mut Vec<f32>,
on_data: &mut DataCallback,
stats: &mut CaptureStats,
) -> Result<(), WasapiError> {
let block_align = stream.format.channels as usize * std::mem::size_of::<f32>();
loop {
@@ -336,6 +387,7 @@ fn drain(
.map(|raw| f32::from_le_bytes(*raw)),
);
}
stats.record(read as usize, info.flags.silent, samples);
if !samples.is_empty() {
on_data(samples);
}
+3 -2
View File
@@ -101,8 +101,9 @@ fn capture_sessions() -> Vec<(u32, bool)> {
}
/// The file name of `pid`'s executable, or `None` if the process cannot be
/// opened (exited, or protected).
fn image_name(pid: u32) -> Option<String> {
/// opened (exited, or protected). Also used by `windows::capture` to name
/// the process behind a process-loopback endpoint in its diagnostic log.
pub(crate) fn image_name(pid: u32) -> Option<String> {
// SAFETY: plain Win32 calls; the handle is closed below and the buffer
// outlives the call that fills it.
unsafe {