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
+5 -2
View File
@@ -48,14 +48,17 @@ impl CaptureSource for FallbackSource {
let mut source = (self.factory)(self.target.clone());
let format = match source.start(forward(&on_data)) {
Ok(format) => format,
Ok(format) => {
log::info!("output target {:?} started", self.target);
format
}
Err(err) => {
let OutputTarget::Process { root_pid } = self.target else {
return Err(err);
};
log::warn!(
"process loopback for pid {root_pid} failed ({err}), \
recording the default output instead"
falling back to DefaultRender"
);
source = (self.factory)(OutputTarget::DefaultRender);
source.start(forward(&on_data))?
+1
View File
@@ -9,6 +9,7 @@
mod capture_thread;
mod fallback;
mod process_tree;
mod stats;
use recorder_core::capture::{CaptureSource, OutputTarget};
+9
View File
@@ -7,6 +7,7 @@
//! back to that monitor as well.
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::Instant;
use libpulse_binding::def::BufferAttr;
use libpulse_binding::error::{Code, PAErr};
@@ -18,6 +19,7 @@ use recorder_core::capture::{
};
use crate::capture_thread::{CaptureThread, Ready};
use crate::stats::CaptureStats;
const APP_NAME: &str = "Gesprächsrekorder";
const DEFAULT_MONITOR: &str = "@DEFAULT_MONITOR@";
@@ -144,17 +146,24 @@ fn run(
let mut bytes = vec![0u8; CHUNK_BYTES];
let mut samples = vec![0f32; CHUNK_SAMPLES];
let mut stats = CaptureStats::new(Instant::now());
while !stop.load(Ordering::SeqCst) {
if let Err(err) = simple.read(&mut bytes) {
// Source gone (unplugged, server restart): stop delivering and
// report it; the recorder keeps the track aligned with silence.
log::warn!("PulseAudio capture '{stream_name}' ended: {err}");
stats.report_final(stream_name);
return Err(format!("PulseAudio: {err}"));
}
for (sample, raw) in samples.iter_mut().zip(bytes.as_chunks::<4>().0) {
*sample = f32::from_ne_bytes(*raw);
}
// PulseAudio reports no silence flag; every packet counts as not
// silent, which matches the actual samples just decoded above.
stats.record(CHUNK_SAMPLES, false, &samples);
stats.maybe_report(stream_name, Instant::now());
on_data(&samples);
}
stats.report_final(stream_name);
Ok(())
}
+137
View File
@@ -0,0 +1,137 @@
//! Per-stream capture statistics, for diagnosing a silent or flaky stream
//! from the log without ever logging audio content.
//!
//! Plain counters updated inline on the audio thread (no locks, no extra
//! threads): [`CaptureStats::record`] is called once per delivered packet,
//! [`CaptureStats::maybe_report`] once per capture loop iteration. A report
//! logs and resets the counters; [`CaptureStats::report_final`] logs
//! unconditionally, for the one line a capture loop emits when it stops.
use std::time::{Duration, Instant};
/// How often a running stream reports its statistics.
const REPORT_INTERVAL: Duration = Duration::from_secs(10);
#[derive(Debug, Clone, Copy)]
pub(crate) struct CaptureStats {
since: Instant,
packets: u64,
frames: u64,
silent_packets: u64,
/// Peak absolute sample value seen since the last report (0.0 if no
/// samples were delivered, e.g. only silent packets).
peak: f32,
}
impl CaptureStats {
pub(crate) fn new(now: Instant) -> Self {
Self {
since: now,
packets: 0,
frames: 0,
silent_packets: 0,
peak: 0.0,
}
}
/// Records one packet delivered by the backend: its frame count, whether
/// the backend flagged it silent, and the samples it carried (used only
/// for the peak; a silent packet's samples are all zero, so it does not
/// move the peak).
pub(crate) fn record(&mut self, packet_frames: usize, silent: bool, samples: &[f32]) {
self.packets += 1;
self.frames += packet_frames as u64;
if silent {
self.silent_packets += 1;
}
for &sample in samples {
self.peak = self.peak.max(sample.abs());
}
}
/// Logs and resets the counters once at least [`REPORT_INTERVAL`] has
/// passed since the last report (or since `new`). `now` is read once per
/// capture loop iteration by the caller, not here, so this never touches
/// the clock itself.
pub(crate) fn maybe_report(&mut self, label: &str, now: Instant) {
if now.duration_since(self.since) < REPORT_INTERVAL {
return;
}
self.log(label);
*self = Self::new(now);
}
/// Logs the counters accumulated since the last report, regardless of
/// how much time has passed. Call once when a capture loop stops.
pub(crate) fn report_final(&self, label: &str) {
self.log(label);
}
fn log(&self, label: &str) {
log::info!(
"capture '{label}' last 10 s: packets={}, frames={}, silent_packets={}, peak={:.3}",
self.packets,
self.frames,
self.silent_packets,
self.peak
);
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn reports_only_after_ten_seconds_have_passed() {
let t0 = Instant::now();
let mut stats = CaptureStats::new(t0);
stats.record(480, false, &[0.5, -0.25]);
// Not yet due: counters untouched.
stats.maybe_report("test", t0 + Duration::from_secs(9));
assert_eq!(stats.packets, 1);
assert_eq!(stats.frames, 480);
// Due: logs (not asserted here) and resets.
stats.maybe_report("test", t0 + Duration::from_secs(10));
assert_eq!(stats.packets, 0);
assert_eq!(stats.frames, 0);
assert_eq!(stats.silent_packets, 0);
}
#[test]
fn a_report_resets_the_peak() {
let t0 = Instant::now();
let mut stats = CaptureStats::new(t0);
stats.record(100, false, &[0.9]);
assert_eq!(stats.peak, 0.9);
stats.maybe_report("test", t0 + Duration::from_secs(10));
assert_eq!(stats.peak, 0.0, "peak must not survive a report");
stats.record(100, false, &[0.2]);
assert_eq!(stats.peak, 0.2, "only the new packet's peak remains");
}
#[test]
fn a_silent_packet_is_counted_but_does_not_move_the_peak() {
let mut stats = CaptureStats::new(Instant::now());
stats.record(50, false, &[0.4]);
stats.record(50, true, &[0.0, 0.0]);
assert_eq!(stats.packets, 2);
assert_eq!(stats.frames, 100);
assert_eq!(stats.silent_packets, 1);
assert_eq!(stats.peak, 0.4);
}
#[test]
fn report_final_logs_without_requiring_elapsed_time() {
// Mainly a smoke test that it compiles and does not panic or reset;
// report_final must not mutate self (it takes &self).
let mut stats = CaptureStats::new(Instant::now());
stats.record(10, false, &[0.1]);
stats.report_final("test");
assert_eq!(stats.packets, 1, "report_final must not reset the counters");
}
}
+65 -13
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
Endpoint::Mic(None) => (
enumerator
.get_default_device_for_role(&Direction::Capture, &Role::Communications)
.map_err(backend)?,
Endpoint::Output(_) => enumerator
"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 {