feat(audio): add internal bit-depth diagnostic capture

Lock-free OR-mask analysis of f32 samples converted to i32,
bypassing PipeWire processing entirely. DiagnosticSource wraps
the audio source at decode level for both rodio and ALSA Direct
paths. Tauri commands: start_bitdepth_capture / stop_bitdepth_capture.

cc
This commit is contained in:
vicrodh committed 2026-02-07 15:58:26 -06:00
1 parent 3253e05263
commit af624d4642
5 files changed
+255 -8

No files matched your search

+200
View File
@@ -0,0 +1,200 @@
//! Audio bit-depth diagnostic
//!
//! Lock-free capture that accumulates an OR-mask of all sample values
//! converted to i32. The trailing zeros in the mask reveal the effective
//! bit depth of the source data — no sample storage needed.
//!
//! Works for both rodio (PipeWire/ALSA via CPAL) and ALSA Direct paths
//! via a transparent Source wrapper.
use std::sync::atomic::{AtomicBool, AtomicU32, AtomicU64, Ordering};
use std::sync::Arc;
use std::time::Duration;
use rodio::Source;
use serde::Serialize;
// ---------------------------------------------------------------------------
// Shared diagnostic state (atomics — safe to clone across threads)
// ---------------------------------------------------------------------------
#[derive(Clone)]
pub struct AudioDiagnostic {
capturing: Arc<AtomicBool>,
or_mask: Arc<AtomicU32>,
sample_count: Arc<AtomicU64>,
sample_rate: Arc<AtomicU32>,
channels: Arc<AtomicU32>,
}
impl AudioDiagnostic {
pub fn new() -> Self {
Self {
capturing: Arc::new(AtomicBool::new(false)),
or_mask: Arc::new(AtomicU32::new(0)),
sample_count: Arc::new(AtomicU64::new(0)),
sample_rate: Arc::new(AtomicU32::new(0)),
channels: Arc::new(AtomicU32::new(0)),
}
}
/// Begin capturing. Resets previous state.
pub fn start_capture(&self, sample_rate: u32, channels: u32) {
self.or_mask.store(0, Ordering::SeqCst);
self.sample_count.store(0, Ordering::SeqCst);
self.sample_rate.store(sample_rate, Ordering::SeqCst);
self.channels.store(channels, Ordering::SeqCst);
self.capturing.store(true, Ordering::SeqCst);
log::info!(
"[Diagnostic] Bit-depth capture started ({}Hz, {}ch)",
sample_rate,
channels
);
}
#[inline]
pub fn is_capturing(&self) -> bool {
self.capturing.load(Ordering::Relaxed)
}
/// Push a single sample (called per-sample in the Source wrapper).
#[inline]
pub fn push_sample(&self, sample: f32) {
if !self.is_capturing() {
return;
}
let clamped = sample.clamp(-1.0, 1.0);
let s32 = (clamped * 2_147_483_647.0) as i32;
self.or_mask.fetch_or(s32.unsigned_abs(), Ordering::Relaxed);
self.sample_count.fetch_add(1, Ordering::Relaxed);
}
/// Stop capturing and return the analysis.
pub fn stop_and_analyze(&self) -> BitDepthResult {
self.capturing.store(false, Ordering::SeqCst);
let or_mask = self.or_mask.load(Ordering::SeqCst);
let sample_count = self.sample_count.load(Ordering::SeqCst);
let sample_rate = self.sample_rate.load(Ordering::SeqCst);
let channels = self.channels.load(Ordering::SeqCst);
let trailing_zeros = if or_mask == 0 { 32 } else { or_mask.trailing_zeros() };
let effective_bits = 32 - trailing_zeros;
let frames = if channels > 0 {
sample_count / channels as u64
} else {
sample_count
};
let duration_secs = if sample_rate > 0 {
frames as f64 / sample_rate as f64
} else {
0.0
};
log::info!(
"[Diagnostic] Capture stopped: {} samples, {:.1}s, or_mask=0x{:08X}, trailing_zeros={}, effective_bits={}",
sample_count, duration_secs, or_mask, trailing_zeros, effective_bits
);
BitDepthResult {
sample_count,
sample_rate,
channels,
duration_secs,
or_mask: format!("0x{:08X}", or_mask),
trailing_zeros,
effective_bits,
}
}
}
impl Default for AudioDiagnostic {
fn default() -> Self {
Self::new()
}
}
// ---------------------------------------------------------------------------
// Result returned to the frontend
// ---------------------------------------------------------------------------
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BitDepthResult {
pub sample_count: u64,
pub sample_rate: u32,
pub channels: u32,
pub duration_secs: f64,
pub or_mask: String,
pub trailing_zeros: u32,
pub effective_bits: u32,
}
// ---------------------------------------------------------------------------
// Source wrapper — transparent tap for bit-depth capture
// ---------------------------------------------------------------------------
pub struct DiagnosticSource<S>
where
S: Source<Item = f32>,
{
inner: S,
diagnostic: AudioDiagnostic,
}
impl<S> DiagnosticSource<S>
where
S: Source<Item = f32>,
{
pub fn new(source: S, diagnostic: AudioDiagnostic) -> Self {
Self {
inner: source,
diagnostic,
}
}
}
impl<S> Iterator for DiagnosticSource<S>
where
S: Source<Item = f32>,
{
type Item = f32;
#[inline]
fn next(&mut self) -> Option<Self::Item> {
let sample = self.inner.next()?;
self.diagnostic.push_sample(sample);
Some(sample)
}
#[inline]
fn size_hint(&self) -> (usize, Option<usize>) {
self.inner.size_hint()
}
}
impl<S> Source for DiagnosticSource<S>
where
S: Source<Item = f32>,
{
#[inline]
fn current_frame_len(&self) -> Option<usize> {
self.inner.current_frame_len()
}
#[inline]
fn channels(&self) -> u16 {
self.inner.channels()
}
#[inline]
fn sample_rate(&self) -> u32 {
self.inner.sample_rate()
}
#[inline]
fn total_duration(&self) -> Option<Duration> {
self.inner.total_duration()
}
}
+2
View File
@@ -8,6 +8,7 @@ pub mod pipewire_backend;
pub mod alsa_backend;
pub mod pulse_backend;
pub mod alsa_direct;
pub mod diagnostic;
// Re-export commonly used types
pub use backend::{
@@ -21,3 +22,4 @@ pub use backend::{
};
pub use alsa_direct::AlsaDirectStream;
pub use alsa_backend::{normalize_device_id_to_stable, resolve_stable_to_current_hw};
pub use diagnostic::{AudioDiagnostic, DiagnosticSource, BitDepthResult};
@@ -1,7 +1,12 @@
//! Audio diagnostics commands for detecting actual hardware sample rate
//! and verifying effective bit depth of the audio pipeline.
use std::fs;
use tauri::Manager;
use crate::AppState;
use crate::audio::BitDepthResult;
/// Hardware audio status
#[derive(Debug, Clone, serde::Serialize)]
pub struct HardwareAudioStatus {
@@ -71,3 +76,34 @@ pub fn get_hardware_audio_status() -> Result<HardwareAudioStatus, String> {
is_active: false,
})
}
/// Start bit-depth diagnostic capture on the currently playing audio.
/// Samples are analyzed on-the-fly with zero allocation (OR-mask of i32 values).
/// Call `stop_bitdepth_capture` after a few seconds to get the result.
#[tauri::command]
pub fn start_bitdepth_capture(
app: tauri::AppHandle,
) -> Result<String, String> {
let state = app.state::<AppState>();
let sample_rate = state.player.state.get_sample_rate();
if sample_rate == 0 {
return Err("No audio playing — cannot start capture".to_string());
}
// Default to 2 channels (stereo) — SharedState doesn't track channels
state.player.diagnostic.start_capture(sample_rate, 2);
Ok(format!("Capture started at {}Hz", sample_rate))
}
/// Stop bit-depth capture and return analysis.
///
/// The `effective_bits` field is the key result:
/// - 24 → source data has 24-bit precision (f32 pipeline working)
/// - 16 → source data truncated to 16-bit (bug)
/// - Other values → intermediate precision or pipeline issue
#[tauri::command]
pub fn stop_bitdepth_capture(
app: tauri::AppHandle,
) -> Result<BitDepthResult, String> {
let state = app.state::<AppState>();
Ok(state.player.diagnostic.stop_and_analyze())
}
+3 -1
View File
@@ -100,7 +100,7 @@ impl AppState {
Self {
client: Arc::new(Mutex::new(QobuzClient::default())),
player: Player::new(device_name, audio_settings, Some(viz_tap)),
player: Player::new(device_name, audio_settings, Some(viz_tap), audio::AudioDiagnostic::new()),
queue: QueueManager::new(),
context: ContextManager::new(),
media_controls: MediaControlsManager::new(),
@@ -458,6 +458,8 @@ pub fn run() {
commands::set_pipewire_default_sink,
commands::reinit_audio_device,
commands::get_hardware_audio_status,
commands::start_bitdepth_capture,
commands::stop_bitdepth_capture,
// Queue commands
commands::add_to_queue,
commands::add_to_queue_next,
+14 -7
View File
@@ -37,7 +37,7 @@ use symphonia::core::probe::Hint;
use symphonia::default::{get_codecs, get_probe};
use crate::api::{client::QobuzClient, models::Quality};
use crate::audio::{AudioBackendType, BackendConfig, BackendManager};
use crate::audio::{AudioBackendType, AudioDiagnostic, BackendConfig, BackendManager, DiagnosticSource};
use crate::config::audio_settings::AudioSettings;
use crate::visualizer::{VisualizerTap, TappedSource};
use playback_engine::PlaybackEngine;
@@ -651,11 +651,13 @@ pub struct Player {
/// Visualizer tap for audio sample capture (optional)
#[allow(dead_code)]
visualizer_tap: Option<VisualizerTap>,
/// Bit-depth diagnostic capture (always available, zero-cost when idle)
pub diagnostic: AudioDiagnostic,
}
impl Default for Player {
fn default() -> Self {
Self::new(None, AudioSettings::default(), None)
Self::new(None, AudioSettings::default(), None, AudioDiagnostic::new())
}
}
@@ -663,7 +665,7 @@ impl Player {
/// Create a new player with an optional specific output device and audio settings
/// If device_name is None, uses the system default device
/// visualizer_tap is optional - if provided, audio samples are captured for visualization
pub fn new(device_name: Option<String>, audio_settings: AudioSettings, visualizer_tap: Option<VisualizerTap>) -> Self {
pub fn new(device_name: Option<String>, audio_settings: AudioSettings, visualizer_tap: Option<VisualizerTap>, diagnostic: AudioDiagnostic) -> Self {
let (tx, rx) = mpsc::channel::<AudioCommand>();
let state = SharedState::new();
let thread_state = state.clone();
@@ -672,16 +674,21 @@ impl Player {
let settings = Arc::new(Mutex::new(audio_settings.clone()));
let thread_settings = settings.clone();
// Clone visualizer tap for audio thread
// Clone visualizer tap and diagnostic for audio thread
let thread_viz_tap = visualizer_tap.clone();
let thread_diagnostic = diagnostic.clone();
// Spawn dedicated audio thread
thread::spawn(move || {
log::info!("Audio thread starting...");
// Helper to wrap source with visualizer tap (if enabled)
// This captures audio samples for visualization without affecting playback
// Helper to wrap source with visualizer tap and diagnostic capture
let wrap_source = |source: Box<dyn Source<Item = f32> + Send>| -> Box<dyn Source<Item = f32> + Send> {
// Diagnostic tap (innermost — captures raw decoded samples)
let source: Box<dyn Source<Item = f32> + Send> =
Box::new(DiagnosticSource::new(source, thread_diagnostic.clone()));
// Visualizer tap (outermost)
if let Some(ref tap) = thread_viz_tap {
Box::new(TappedSource::new(source, tap.ring_buffer.clone(), tap.enabled.clone()))
} else {
@@ -1725,7 +1732,7 @@ impl Player {
}
});
Self { tx, state, audio_settings: settings, visualizer_tap }
Self { tx, state, audio_settings: settings, visualizer_tap, diagnostic }
}
/// Play a track by ID (downloads audio)