feat(qbz-audio): implement Phase 2 - audio backend system
CRITICAL: Copied audio modules from qbz-nix WITHOUT modifying logic. This code handles bit-perfect playback and is IMMUTABLE. Copied modules: - backend.rs: Backend trait and manager - pipewire_backend.rs: PipeWire/PulseAudio backend - alsa_backend.rs: ALSA backend with device enumeration - pulse_backend.rs: PulseAudio fallback - alsa_direct.rs: Direct ALSA hardware access (hw:X,Y) - diagnostic.rs: Audio diagnostic tools - loudness.rs: ReplayGain extraction - loudness_analyzer.rs: EBU R128 analysis - loudness_cache.rs: SQLite cache for loudness data - dynamic_amplify.rs: Dynamic volume amplification - analyzer_tap.rs: Audio analyzer tap Dependencies: - Uses vendored rodio from src-tauri/vendor/rodio - symphonia-all feature for f32 pipeline - ebur128 for loudness analysis - rusqlite for caching Also updated qbz-models to remove incomplete audio types (AudioBackendType, AudioDevice) - these stay in qbz-audio.
This commit is contained in:
1 parent
deafa15205
commit
3c8fc35fcb
16 files changed
+3117
-52
No files matched your search
@@ -15,11 +15,27 @@ async-trait = { workspace = true }
|
||||
# Logging
|
||||
log = { workspace = true }
|
||||
|
||||
# Serialization
|
||||
serde = { workspace = true }
|
||||
|
||||
# Error handling
|
||||
thiserror = { workspace = true }
|
||||
|
||||
# Audio will use vendored rodio/cpal from qbz-player
|
||||
# symphonia = { workspace = true }
|
||||
# Audio - Vendored rodio for bit-perfect playback
|
||||
# This is the same vendored version used by qbz-nix
|
||||
# CRITICAL: Must use symphonia-all feature for f32 pipeline
|
||||
rodio = { path = "../../src-tauri/vendor/rodio", features = ["symphonia-all"] }
|
||||
|
||||
# Audio analysis
|
||||
symphonia = { workspace = true }
|
||||
ebur128 = "0.1"
|
||||
|
||||
# Database for loudness cache
|
||||
rusqlite = { version = "0.31", features = ["bundled"] }
|
||||
|
||||
# System directories
|
||||
dirs = "5"
|
||||
|
||||
[target.'cfg(target_os = "linux")'.dependencies]
|
||||
# ALSA for direct hardware access (bit-perfect)
|
||||
alsa = "0.9"
|
||||
@@ -0,0 +1,705 @@
|
||||
//! ALSA audio backend (direct hardware access)
|
||||
//!
|
||||
//! Provides direct access to ALSA hardware devices for:
|
||||
//! - True exclusive mode (blocks device for other apps)
|
||||
//! - Bit-perfect playback (no resampling)
|
||||
//! - Low-latency audio output
|
||||
//!
|
||||
//! Uses CPAL's ALSA host with specific device selection.
|
||||
//! Device enumeration reads directly from /proc/asound (no alsa-utils dependency).
|
||||
|
||||
use super::backend::{AlsaPlugin, AudioBackend, AudioBackendType, AudioDevice, BackendConfig, BackendResult};
|
||||
use rodio::{
|
||||
cpal::{
|
||||
traits::{DeviceTrait, HostTrait},
|
||||
BufferSize, SampleFormat, SampleRate, StreamConfig, SupportedBufferSize, SupportedStreamConfig,
|
||||
},
|
||||
OutputStream, OutputStreamHandle,
|
||||
};
|
||||
use std::collections::HashMap;
|
||||
use std::fs;
|
||||
|
||||
/// Common audio sample rates to check for device support
|
||||
const COMMON_SAMPLE_RATES: &[u32] = &[
|
||||
44100, // CD quality
|
||||
48000, // DVD/DAT quality
|
||||
88200, // 2x CD
|
||||
96000, // DVD-Audio
|
||||
176400, // 4x CD
|
||||
192000, // High-res audio
|
||||
352800, // DSD64 equivalent
|
||||
384000, // Ultra high-res
|
||||
];
|
||||
|
||||
/// Extract supported sample rates from a CPAL device
|
||||
fn get_supported_sample_rates(device: &rodio::cpal::Device) -> Option<Vec<u32>> {
|
||||
use rodio::cpal::traits::DeviceTrait;
|
||||
|
||||
let configs = device.supported_output_configs().ok()?;
|
||||
let configs_vec: Vec<_> = configs.collect();
|
||||
|
||||
if configs_vec.is_empty() {
|
||||
return None;
|
||||
}
|
||||
|
||||
let mut supported = Vec::new();
|
||||
|
||||
for rate in COMMON_SAMPLE_RATES {
|
||||
let sample_rate = rodio::cpal::SampleRate(*rate);
|
||||
// Check if any config supports this rate
|
||||
let is_supported = configs_vec.iter().any(|config| {
|
||||
sample_rate >= config.min_sample_rate() && sample_rate <= config.max_sample_rate()
|
||||
});
|
||||
if is_supported {
|
||||
supported.push(*rate);
|
||||
}
|
||||
}
|
||||
|
||||
if supported.is_empty() {
|
||||
None
|
||||
} else {
|
||||
Some(supported)
|
||||
}
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// /proc/asound helpers - No aplay dependency
|
||||
// ============================================================================
|
||||
|
||||
/// Information about an ALSA sound card read from /proc/asound
|
||||
#[derive(Debug, Clone)]
|
||||
struct ProcCardInfo {
|
||||
/// Card number (0, 1, 2, ...)
|
||||
number: String,
|
||||
/// Short name used in ALSA device IDs (e.g., "C20", "NVidia", "sofhdadsp")
|
||||
short_name: String,
|
||||
/// Long descriptive name (e.g., "Cambridge Audio USB Audio 2.0")
|
||||
long_name: String,
|
||||
/// PCM playback devices on this card
|
||||
pcm_playback_devices: Vec<ProcPcmInfo>,
|
||||
}
|
||||
|
||||
/// Information about a PCM device
|
||||
#[derive(Debug, Clone)]
|
||||
struct ProcPcmInfo {
|
||||
/// Device number within the card
|
||||
device_num: String,
|
||||
/// Device name (e.g., "USB Audio", "HDMI 0")
|
||||
name: String,
|
||||
}
|
||||
|
||||
/// Read all sound card information from /proc/asound
|
||||
fn read_proc_asound_cards() -> Vec<ProcCardInfo> {
|
||||
let mut cards = Vec::new();
|
||||
|
||||
// Parse /proc/asound/cards for basic card info
|
||||
// Format: " 0 [C20 ]: USB-Audio - Cambridge Audio USB Audio 2.0"
|
||||
let cards_content = match fs::read_to_string("/proc/asound/cards") {
|
||||
Ok(c) => c,
|
||||
Err(e) => {
|
||||
log::warn!("[ALSA] Cannot read /proc/asound/cards: {}", e);
|
||||
return cards;
|
||||
}
|
||||
};
|
||||
|
||||
// Parse cards file - each card has two lines
|
||||
let lines: Vec<&str> = cards_content.lines().collect();
|
||||
let mut i = 0;
|
||||
while i < lines.len() {
|
||||
let line = lines[i].trim();
|
||||
|
||||
// First line format: " 0 [C20 ]: USB-Audio - Cambridge Audio USB Audio 2.0"
|
||||
if let Some(card_info) = parse_proc_card_line(line) {
|
||||
// Read PCM devices for this card
|
||||
let pcm_devices = read_card_pcm_devices(&card_info.0);
|
||||
|
||||
cards.push(ProcCardInfo {
|
||||
number: card_info.0,
|
||||
short_name: card_info.1,
|
||||
long_name: card_info.2,
|
||||
pcm_playback_devices: pcm_devices,
|
||||
});
|
||||
}
|
||||
i += 1;
|
||||
}
|
||||
|
||||
cards
|
||||
}
|
||||
|
||||
/// Parse a line from /proc/asound/cards
|
||||
/// Returns (card_number, short_name, long_name)
|
||||
fn parse_proc_card_line(line: &str) -> Option<(String, String, String)> {
|
||||
// Format: " 0 [C20 ]: USB-Audio - Cambridge Audio USB Audio 2.0"
|
||||
let line = line.trim();
|
||||
|
||||
// Find card number (first number)
|
||||
let parts: Vec<&str> = line.splitn(2, '[').collect();
|
||||
if parts.len() < 2 {
|
||||
return None;
|
||||
}
|
||||
|
||||
let card_num = parts[0].trim().to_string();
|
||||
if card_num.is_empty() || !card_num.chars().all(|c| c.is_ascii_digit()) {
|
||||
return None;
|
||||
}
|
||||
|
||||
// Find short name (inside brackets)
|
||||
let rest = parts[1];
|
||||
let bracket_end = rest.find(']')?;
|
||||
let short_name = rest[..bracket_end].trim().to_string();
|
||||
|
||||
// Find long name (after " - ")
|
||||
let long_name = if let Some(dash_pos) = rest.find(" - ") {
|
||||
rest[dash_pos + 3..].trim().to_string()
|
||||
} else {
|
||||
// Fallback: use everything after ]:
|
||||
rest[bracket_end + 1..]
|
||||
.trim()
|
||||
.trim_start_matches(':')
|
||||
.trim()
|
||||
.split(" - ")
|
||||
.last()
|
||||
.unwrap_or(&short_name)
|
||||
.to_string()
|
||||
};
|
||||
|
||||
Some((card_num, short_name, long_name))
|
||||
}
|
||||
|
||||
/// Read PCM playback devices for a specific card from /proc/asound
|
||||
fn read_card_pcm_devices(card_num: &str) -> Vec<ProcPcmInfo> {
|
||||
let mut devices = Vec::new();
|
||||
let card_path = format!("/proc/asound/card{}", card_num);
|
||||
|
||||
// Read PCM device info files
|
||||
if let Ok(entries) = fs::read_dir(&card_path) {
|
||||
for entry in entries.flatten() {
|
||||
let name = entry.file_name();
|
||||
let name_str = name.to_string_lossy();
|
||||
|
||||
// PCM playback devices are named pcmXp (X = device number, p = playback)
|
||||
if name_str.starts_with("pcm") && name_str.ends_with('p') {
|
||||
let info_path = entry.path().join("info");
|
||||
if let Ok(content) = fs::read_to_string(&info_path) {
|
||||
let mut pcm_name = String::new();
|
||||
let mut device_num = String::new();
|
||||
|
||||
for line in content.lines() {
|
||||
if let Some(val) = line.strip_prefix("name: ") {
|
||||
pcm_name = val.trim().to_string();
|
||||
}
|
||||
if let Some(val) = line.strip_prefix("device: ") {
|
||||
device_num = val.trim().to_string();
|
||||
}
|
||||
}
|
||||
|
||||
if !device_num.is_empty() {
|
||||
devices.push(ProcPcmInfo {
|
||||
device_num,
|
||||
name: if pcm_name.is_empty() { "Unknown".to_string() } else { pcm_name },
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Sort by device number
|
||||
devices.sort_by(|a, b| {
|
||||
a.device_num.parse::<u32>().unwrap_or(0)
|
||||
.cmp(&b.device_num.parse::<u32>().unwrap_or(0))
|
||||
});
|
||||
|
||||
devices
|
||||
}
|
||||
|
||||
/// Build a map of card_number -> (short_name, long_name) from /proc/asound
|
||||
fn build_card_info_map() -> HashMap<String, (String, String)> {
|
||||
let cards = read_proc_asound_cards();
|
||||
let mut map = HashMap::new();
|
||||
|
||||
for card in cards {
|
||||
map.insert(card.number.clone(), (card.short_name, card.long_name));
|
||||
}
|
||||
|
||||
map
|
||||
}
|
||||
|
||||
/// Find card number by short name (e.g., "C20" -> "0")
|
||||
fn find_card_number_by_name(short_name: &str) -> Option<String> {
|
||||
let cards = read_proc_asound_cards();
|
||||
cards.iter()
|
||||
.find(|c| c.short_name == short_name)
|
||||
.map(|c| c.number.clone())
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// ALSA Backend Implementation
|
||||
// ============================================================================
|
||||
|
||||
pub struct AlsaBackend {
|
||||
host: rodio::cpal::Host,
|
||||
}
|
||||
|
||||
impl AlsaBackend {
|
||||
pub fn new() -> BackendResult<Self> {
|
||||
// Try to get ALSA host
|
||||
let available_hosts = rodio::cpal::available_hosts();
|
||||
|
||||
// Check if ALSA is available
|
||||
if !available_hosts.iter().any(|h| h.name() == "ALSA") {
|
||||
return Err("ALSA host not available on this system".to_string());
|
||||
}
|
||||
|
||||
// Get ALSA host
|
||||
let host = rodio::cpal::host_from_id(
|
||||
available_hosts
|
||||
.into_iter()
|
||||
.find(|h| h.name() == "ALSA")
|
||||
.ok_or("ALSA host not found".to_string())?
|
||||
).map_err(|e| format!("Failed to create ALSA host: {}", e))?;
|
||||
|
||||
log::info!("[ALSA Backend] Initialized successfully");
|
||||
|
||||
Ok(Self { host })
|
||||
}
|
||||
|
||||
/// Enumerate ALSA devices using /proc/asound as PRIMARY source
|
||||
///
|
||||
/// This approach ensures consistent device enumeration regardless of playback state.
|
||||
/// CPAL enumeration fails when devices are in exclusive mode, but /proc/asound
|
||||
/// always sees all devices.
|
||||
///
|
||||
/// Architecture:
|
||||
/// 1. /proc/asound = PRIMARY source (always complete)
|
||||
/// 2. CPAL = OPTIONAL enrichment (sample rates only, may fail during playback)
|
||||
fn enumerate_with_proc_descriptions(&self) -> BackendResult<Vec<AudioDevice>> {
|
||||
let mut devices = Vec::new();
|
||||
|
||||
// Read all cards from /proc/asound (PRIMARY SOURCE)
|
||||
let cards = read_proc_asound_cards();
|
||||
|
||||
log::info!("[ALSA Backend] /proc/asound found {} cards", cards.len());
|
||||
for card in &cards {
|
||||
log::debug!(
|
||||
"[ALSA Backend] Card {}: {} = {} ({} PCM devices)",
|
||||
card.number, card.short_name, card.long_name, card.pcm_playback_devices.len()
|
||||
);
|
||||
}
|
||||
|
||||
// Build CPAL device map for sample rate enrichment (OPTIONAL - may be incomplete)
|
||||
let cpal_devices = self.build_cpal_device_map();
|
||||
log::debug!("[ALSA Backend] CPAL found {} devices for enrichment", cpal_devices.len());
|
||||
|
||||
// Add system default device
|
||||
let default_sample_rates = cpal_devices.get("default")
|
||||
.and_then(|d| get_supported_sample_rates(d));
|
||||
let default_max_rate = default_sample_rates.as_ref()
|
||||
.and_then(|rates| rates.iter().max().copied());
|
||||
|
||||
devices.push(AudioDevice {
|
||||
id: "default".to_string(),
|
||||
name: "default".to_string(),
|
||||
description: None, // Frontend shows "System Default"
|
||||
is_default: true,
|
||||
max_sample_rate: default_max_rate.or(Some(384000)),
|
||||
supported_sample_rates: default_sample_rates,
|
||||
device_bus: None,
|
||||
is_hardware: false,
|
||||
});
|
||||
|
||||
// For each card, add relevant devices using STABLE IDs (card NAME, not number)
|
||||
for card in &cards {
|
||||
// Add sysdefault:CARD=name (card default with software mixing)
|
||||
let sysdefault_id = format!("sysdefault:CARD={}", card.short_name);
|
||||
let sysdefault_rates = cpal_devices.get(&sysdefault_id)
|
||||
.and_then(|d| get_supported_sample_rates(d));
|
||||
|
||||
devices.push(AudioDevice {
|
||||
id: sysdefault_id.clone(),
|
||||
name: sysdefault_id.clone(),
|
||||
description: Some(format!("{}, {}", card.long_name, sysdefault_id)),
|
||||
is_default: false,
|
||||
max_sample_rate: sysdefault_rates.as_ref()
|
||||
.and_then(|r| r.iter().max().copied())
|
||||
.or(Some(192000)),
|
||||
supported_sample_rates: sysdefault_rates,
|
||||
device_bus: None,
|
||||
is_hardware: false, // sysdefault uses dmix
|
||||
});
|
||||
|
||||
// Add PCM-specific devices (front:, iec958:, hdmi:)
|
||||
for pcm in &card.pcm_playback_devices {
|
||||
// Determine device type based on PCM name
|
||||
let device_prefix = if pcm.name.to_lowercase().contains("hdmi") {
|
||||
"hdmi"
|
||||
} else if pcm.name.to_lowercase().contains("iec958")
|
||||
|| pcm.name.to_lowercase().contains("spdif")
|
||||
|| pcm.name.to_lowercase().contains("s/pdif") {
|
||||
"iec958"
|
||||
} else {
|
||||
"front" // Default to front: for analog/USB audio
|
||||
};
|
||||
|
||||
let device_id = format!("{}:CARD={},DEV={}", device_prefix, card.short_name, pcm.device_num);
|
||||
|
||||
// Skip if already added (shouldn't happen, but be safe)
|
||||
if devices.iter().any(|d| d.id == device_id) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Try to get sample rates from CPAL (may fail if device is busy)
|
||||
let sample_rates = cpal_devices.get(&device_id)
|
||||
.and_then(|d| get_supported_sample_rates(d));
|
||||
let max_rate = sample_rates.as_ref()
|
||||
.and_then(|r| r.iter().max().copied())
|
||||
.or(Some(384000)); // Assume high capability if CPAL unavailable
|
||||
|
||||
devices.push(AudioDevice {
|
||||
id: device_id.clone(),
|
||||
name: device_id.clone(),
|
||||
description: Some(format!("{}, {}", card.long_name, device_id)),
|
||||
is_default: false,
|
||||
max_sample_rate: max_rate,
|
||||
supported_sample_rates: sample_rates,
|
||||
device_bus: None,
|
||||
is_hardware: true,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
log::info!("[ALSA Backend] Enumerated {} ALSA devices", devices.len());
|
||||
for (idx, dev) in devices.iter().enumerate() {
|
||||
log::info!(
|
||||
" [{}] {} - {} (max_rate: {:?}, rates: {:?})",
|
||||
idx,
|
||||
dev.name,
|
||||
dev.description.as_deref().unwrap_or("(default)"),
|
||||
dev.max_sample_rate,
|
||||
dev.supported_sample_rates
|
||||
);
|
||||
}
|
||||
|
||||
Ok(devices)
|
||||
}
|
||||
|
||||
/// Build a map of device_id -> CPAL Device for sample rate queries
|
||||
/// This is OPTIONAL enrichment - devices may be missing if in exclusive use
|
||||
fn build_cpal_device_map(&self) -> HashMap<String, rodio::cpal::Device> {
|
||||
let mut map = HashMap::new();
|
||||
|
||||
if let Ok(output_devices) = self.host.output_devices() {
|
||||
for device in output_devices {
|
||||
if let Ok(name) = device.name() {
|
||||
map.insert(name, device);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
map
|
||||
}
|
||||
|
||||
/// Try to create direct ALSA stream for hw: devices (bypasses CPAL)
|
||||
/// Returns None if device is not a hw: device (should use CPAL instead)
|
||||
///
|
||||
/// Implements controlled fallback:
|
||||
/// 1. Try direct hw access first
|
||||
/// 2. If format unsupported, try plughw (format conversion only, no resampling)
|
||||
/// 3. Abort on other errors (busy, permissions, etc.)
|
||||
pub fn try_create_direct_stream(
|
||||
&self,
|
||||
config: &BackendConfig,
|
||||
) -> Option<Result<(super::AlsaDirectStream, super::backend::BitPerfectMode), String>> {
|
||||
let device_id = config.device_id.as_ref()?;
|
||||
|
||||
// Only use direct ALSA for hw:/plughw:/front: devices
|
||||
if !super::AlsaDirectStream::is_hw_device(device_id) {
|
||||
log::info!("[ALSA Backend] Device '{}' is not hw:/plughw:/front:, using CPAL", device_id);
|
||||
return None;
|
||||
}
|
||||
|
||||
// Determine the base device path for hw/plughw attempts
|
||||
// front:CARD=X,DEV=Y -> extract card name for hw attempts
|
||||
let (hw_device, plughw_device) = if device_id.starts_with("front:CARD=") {
|
||||
// front:CARD=AMP,DEV=0 -> need to find corresponding hw:X,0
|
||||
// For now, try the front: device directly as it's already hardware-direct
|
||||
(device_id.to_string(), format!("plug:{}", device_id))
|
||||
} else if device_id.starts_with("hw:") {
|
||||
(device_id.to_string(), device_id.replace("hw:", "plughw:"))
|
||||
} else if device_id.starts_with("plughw:") {
|
||||
// Already plughw, try it directly
|
||||
(device_id.replace("plughw:", "hw:"), device_id.to_string())
|
||||
} else {
|
||||
(device_id.to_string(), format!("plug:{}", device_id))
|
||||
};
|
||||
|
||||
// Respect ALSA plugin selection from settings
|
||||
let try_hw_first = match config.alsa_plugin {
|
||||
Some(AlsaPlugin::Hw) => true,
|
||||
Some(AlsaPlugin::PlugHw) => false, // Skip hw, go directly to plughw
|
||||
Some(AlsaPlugin::Pcm) => {
|
||||
log::info!("[ALSA Backend] PCM mode selected, not using direct ALSA");
|
||||
return None; // Use CPAL instead
|
||||
}
|
||||
None => true, // Default: try hw first
|
||||
};
|
||||
|
||||
if try_hw_first {
|
||||
log::info!(
|
||||
"[ALSA Backend] Attempting DIRECT hw stream: {} ({}Hz, {}ch)",
|
||||
hw_device,
|
||||
config.sample_rate,
|
||||
config.channels
|
||||
);
|
||||
|
||||
match super::AlsaDirectStream::new(&hw_device, config.sample_rate, config.channels) {
|
||||
Ok(stream) => {
|
||||
log::info!("[ALSA Backend] ✓ Direct hw stream created successfully");
|
||||
return Some(Ok((stream, super::backend::BitPerfectMode::DirectHardware)));
|
||||
}
|
||||
Err(e) => {
|
||||
let error = super::backend::AlsaDirectError::from_alsa_error(&e);
|
||||
log::warn!("[ALSA Backend] hw attempt failed: {}", error);
|
||||
|
||||
if !error.allows_plughw_fallback() {
|
||||
// Non-recoverable error (busy, permissions, etc.)
|
||||
log::error!("[ALSA Backend] Cannot fallback - error type: {:?}", error);
|
||||
return Some(Err(format!(
|
||||
"ALSA Direct failed: {}. Device may be in use or inaccessible.",
|
||||
error
|
||||
)));
|
||||
}
|
||||
|
||||
log::info!("[ALSA Backend] Format unsupported on hw, trying plughw fallback...");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Try plughw fallback (format conversion only)
|
||||
log::info!(
|
||||
"[ALSA Backend] Attempting plughw stream: {} ({}Hz, {}ch)",
|
||||
plughw_device,
|
||||
config.sample_rate,
|
||||
config.channels
|
||||
);
|
||||
|
||||
match super::AlsaDirectStream::new(&plughw_device, config.sample_rate, config.channels) {
|
||||
Ok(stream) => {
|
||||
log::info!("[ALSA Backend] ✓ plughw stream created (bit-perfect with format conversion)");
|
||||
Some(Ok((stream, super::backend::BitPerfectMode::PluginFallback)))
|
||||
}
|
||||
Err(e) => {
|
||||
log::error!("[ALSA Backend] plughw fallback also failed: {}", e);
|
||||
Some(Err(format!(
|
||||
"Bit-perfect playback could not be established. hw failed, plughw failed: {}",
|
||||
e
|
||||
)))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Convert an unstable hw:X,0 device ID to a stable front:CARD=name,DEV=0 format.
|
||||
/// This survives reboots and USB reconnections since it uses the card name, not the number.
|
||||
///
|
||||
/// Examples:
|
||||
/// - `hw:0,0` with card "C20" -> `front:CARD=C20,DEV=0`
|
||||
/// - `hw:2,0` with card "NVidia" -> `front:CARD=NVidia,DEV=0`
|
||||
/// - `front:CARD=C20,DEV=0` -> unchanged (already stable)
|
||||
/// - `plughw:0,0` -> unchanged (plugin devices don't benefit from this)
|
||||
/// - `default` -> unchanged (not a hardware device)
|
||||
pub fn normalize_device_id_to_stable(device_id: &str) -> String {
|
||||
// Already stable formats - return as-is
|
||||
if device_id.starts_with("front:CARD=")
|
||||
|| device_id.starts_with("plughw:")
|
||||
|| !device_id.starts_with("hw:")
|
||||
{
|
||||
return device_id.to_string();
|
||||
}
|
||||
|
||||
// Parse hw:X,Y format
|
||||
let stripped = device_id.strip_prefix("hw:").unwrap_or(device_id);
|
||||
let parts: Vec<&str> = stripped.split(',').collect();
|
||||
if parts.len() < 2 {
|
||||
log::warn!("[ALSA] Could not parse hw device format: {}", device_id);
|
||||
return device_id.to_string();
|
||||
}
|
||||
|
||||
let card_num = parts[0];
|
||||
let device_num = parts[1];
|
||||
|
||||
// Get card info from /proc/asound
|
||||
let card_map = build_card_info_map();
|
||||
|
||||
if let Some((short_name, _long_name)) = card_map.get(card_num) {
|
||||
let stable_id = format!("front:CARD={},DEV={}", short_name, device_num);
|
||||
log::info!(
|
||||
"[ALSA] Normalized device ID: {} -> {} (stable)",
|
||||
device_id,
|
||||
stable_id
|
||||
);
|
||||
return stable_id;
|
||||
}
|
||||
|
||||
log::warn!(
|
||||
"[ALSA] Could not find card {} in /proc/asound, keeping original ID",
|
||||
card_num
|
||||
);
|
||||
device_id.to_string()
|
||||
}
|
||||
|
||||
/// Get the current card number for a stable device ID.
|
||||
/// Used when we need to resolve front:CARD=X to hw:N,0 for certain operations.
|
||||
///
|
||||
/// Returns None if the card is not currently present.
|
||||
pub fn resolve_stable_to_current_hw(device_id: &str) -> Option<String> {
|
||||
// Only resolve front:CARD= format
|
||||
if !device_id.starts_with("front:CARD=") {
|
||||
return Some(device_id.to_string());
|
||||
}
|
||||
|
||||
// Extract card name: front:CARD=C20,DEV=0 -> C20
|
||||
let stripped = device_id.strip_prefix("front:CARD=")?;
|
||||
let parts: Vec<&str> = stripped.split(',').collect();
|
||||
let card_name = parts.first()?;
|
||||
let dev_part = parts.get(1).and_then(|s| s.strip_prefix("DEV=")).unwrap_or("0");
|
||||
|
||||
// Find current card number for this name using /proc/asound
|
||||
if let Some(card_num) = find_card_number_by_name(card_name) {
|
||||
let hw_id = format!("hw:{},{}", card_num, dev_part);
|
||||
log::debug!("[ALSA] Resolved {} -> {}", device_id, hw_id);
|
||||
return Some(hw_id);
|
||||
}
|
||||
|
||||
log::warn!("[ALSA] Card '{}' not found in current enumeration", card_name);
|
||||
None
|
||||
}
|
||||
|
||||
impl AudioBackend for AlsaBackend {
|
||||
fn backend_type(&self) -> AudioBackendType {
|
||||
AudioBackendType::Alsa
|
||||
}
|
||||
|
||||
fn enumerate_devices(&self) -> BackendResult<Vec<AudioDevice>> {
|
||||
self.enumerate_with_proc_descriptions()
|
||||
}
|
||||
|
||||
fn create_output_stream(
|
||||
&self,
|
||||
config: &BackendConfig,
|
||||
) -> BackendResult<(OutputStream, OutputStreamHandle)> {
|
||||
log::info!(
|
||||
"[ALSA Backend] Creating stream: {}Hz, {} channels, exclusive: {}, plugin: {:?}",
|
||||
config.sample_rate,
|
||||
config.channels,
|
||||
config.exclusive_mode,
|
||||
config.alsa_plugin
|
||||
);
|
||||
|
||||
// Find the device by name/id
|
||||
let device = if let Some(device_id) = &config.device_id {
|
||||
log::info!("[ALSA Backend] Looking for device: {}", device_id);
|
||||
self.host
|
||||
.output_devices()
|
||||
.map_err(|e| format!("Failed to enumerate devices: {}", e))?
|
||||
.find(|d| {
|
||||
d.name()
|
||||
.ok()
|
||||
.map(|n| n == *device_id)
|
||||
.unwrap_or(false)
|
||||
})
|
||||
.ok_or_else(|| format!("Device '{}' not found", device_id))?
|
||||
} else {
|
||||
log::info!("[ALSA Backend] Using default device");
|
||||
self.host
|
||||
.default_output_device()
|
||||
.ok_or("No default ALSA device available")?
|
||||
};
|
||||
|
||||
let device_name = device.name().unwrap_or_else(|_| "unknown".to_string());
|
||||
log::info!("[ALSA Backend] Using device: {}", device_name);
|
||||
|
||||
// Create StreamConfig with requested sample rate
|
||||
let stream_config = StreamConfig {
|
||||
channels: config.channels,
|
||||
sample_rate: SampleRate(config.sample_rate),
|
||||
buffer_size: if config.exclusive_mode {
|
||||
// Smaller buffer for exclusive mode = lower latency
|
||||
BufferSize::Fixed(512)
|
||||
} else {
|
||||
BufferSize::Default
|
||||
},
|
||||
};
|
||||
|
||||
// Check if device supports this configuration
|
||||
let supported_configs = device
|
||||
.supported_output_configs()
|
||||
.map_err(|e| format!("Failed to get supported configs: {}", e))?;
|
||||
|
||||
let mut found_matching = false;
|
||||
for range in supported_configs {
|
||||
if range.channels() == config.channels
|
||||
&& config.sample_rate >= range.min_sample_rate().0
|
||||
&& config.sample_rate <= range.max_sample_rate().0
|
||||
{
|
||||
found_matching = true;
|
||||
log::info!(
|
||||
"[ALSA Backend] Device supports {}Hz (range: {}-{}Hz)",
|
||||
config.sample_rate,
|
||||
range.min_sample_rate().0,
|
||||
range.max_sample_rate().0
|
||||
);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if !found_matching {
|
||||
log::warn!(
|
||||
"[ALSA Backend] Device may not support {}Hz, attempting anyway",
|
||||
config.sample_rate
|
||||
);
|
||||
}
|
||||
|
||||
// Create SupportedStreamConfig
|
||||
let supported_config = SupportedStreamConfig::new(
|
||||
stream_config.channels,
|
||||
stream_config.sample_rate,
|
||||
SupportedBufferSize::Range { min: 64, max: 8192 },
|
||||
SampleFormat::F32,
|
||||
);
|
||||
|
||||
// Create OutputStream with custom config
|
||||
let stream = OutputStream::try_from_device_config(&device, supported_config)
|
||||
.map_err(|e| {
|
||||
if config.exclusive_mode {
|
||||
format!(
|
||||
"Failed to create exclusive ALSA stream at {}Hz: {}. Device may be in use by another application.",
|
||||
config.sample_rate, e
|
||||
)
|
||||
} else {
|
||||
format!("Failed to create ALSA stream at {}Hz: {}", config.sample_rate, e)
|
||||
}
|
||||
})?;
|
||||
|
||||
log::info!(
|
||||
"[ALSA Backend] Output stream created successfully at {}Hz (exclusive: {})",
|
||||
config.sample_rate,
|
||||
config.exclusive_mode
|
||||
);
|
||||
|
||||
Ok(stream)
|
||||
}
|
||||
|
||||
fn is_available(&self) -> bool {
|
||||
// Check if we can enumerate devices (ALSA is working)
|
||||
self.host.output_devices().is_ok()
|
||||
}
|
||||
|
||||
fn description(&self) -> &'static str {
|
||||
"ALSA Direct - Bit-perfect with optional exclusive hardware access"
|
||||
}
|
||||
|
||||
fn as_any(&self) -> &dyn std::any::Any {
|
||||
self
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,553 @@
|
||||
//! Direct ALSA access using alsa-rs
|
||||
//!
|
||||
//! Provides bit-perfect playback for hw:X,Y devices that CPAL cannot open.
|
||||
//! This module bypasses rodio/CPAL completely for direct hardware access.
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
use alsa::pcm::{Access, Format, HwParams, PCM};
|
||||
#[cfg(target_os = "linux")]
|
||||
use alsa::{Direction, ValueOr};
|
||||
use std::sync::atomic::AtomicBool;
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
/// Direct ALSA PCM stream for hw: devices
|
||||
pub struct AlsaDirectStream {
|
||||
pcm: Arc<Mutex<PCM>>,
|
||||
#[allow(dead_code)]
|
||||
is_playing: Arc<AtomicBool>,
|
||||
sample_rate: u32,
|
||||
channels: u16,
|
||||
format: Format,
|
||||
device_id: String,
|
||||
}
|
||||
|
||||
impl AlsaDirectStream {
|
||||
/// Create new ALSA direct stream
|
||||
#[cfg(target_os = "linux")]
|
||||
pub fn new(device_id: &str, sample_rate: u32, channels: u16) -> Result<Self, String> {
|
||||
log::info!(
|
||||
"[ALSA Direct] Opening device: {} ({}Hz, {}ch)",
|
||||
device_id,
|
||||
sample_rate,
|
||||
channels
|
||||
);
|
||||
|
||||
// Open PCM device
|
||||
let pcm = PCM::new(device_id, Direction::Playback, false)
|
||||
.map_err(|e| format!("Failed to open ALSA device '{}': {}", device_id, e))?;
|
||||
|
||||
// Set hardware parameters and auto-detect best format
|
||||
let selected_format = {
|
||||
let hwp = HwParams::any(&pcm)
|
||||
.map_err(|e| format!("Failed to get hardware params: {}", e))?;
|
||||
|
||||
// Set access type (interleaved)
|
||||
hwp.set_access(Access::RWInterleaved)
|
||||
.map_err(|e| format!("Failed to set access: {}", e))?;
|
||||
|
||||
// Try formats in order of preference for bit-perfect playback
|
||||
// S24_3LE first: required by SMSL-class USB DACs (TAS1020B chip)
|
||||
// Then descending bit-depth for quality
|
||||
let format_priority = [
|
||||
(Format::S243LE, "S24_3LE"), // 24-bit packed (SMSL, Topping, Fosi DACs)
|
||||
(Format::S32LE, "S32LE"), // 32-bit
|
||||
(Format::S24LE, "S24LE"), // 24-bit in 32-bit container
|
||||
(Format::S16LE, "S16LE"), // 16-bit
|
||||
(Format::FloatLE, "Float32LE"), // Float (compatibility)
|
||||
];
|
||||
|
||||
let mut selected_format = None;
|
||||
for (format, name) in &format_priority {
|
||||
if hwp.set_format(*format).is_ok() {
|
||||
log::info!("[ALSA Direct] Selected format: {}", name);
|
||||
selected_format = Some(*format);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
let format = selected_format
|
||||
.ok_or_else(|| "No supported audio format found (tried S24_3LE, S32LE, S24LE, S16LE, FloatLE)".to_string())?;
|
||||
|
||||
// Set channels
|
||||
hwp.set_channels(channels as u32)
|
||||
.map_err(|e| format!("Failed to set channels: {}", e))?;
|
||||
|
||||
// Set sample rate (exact match - bit-perfect!)
|
||||
hwp.set_rate(sample_rate, ValueOr::Nearest)
|
||||
.map_err(|e| format!("Failed to set sample rate: {}", e))?;
|
||||
|
||||
// Set buffer size (larger buffer for high-res audio)
|
||||
let buffer_size = if sample_rate >= 192000 {
|
||||
// 500ms buffer for 192kHz+ (like MPD config)
|
||||
(sample_rate / 2) as i64
|
||||
} else if sample_rate >= 96000 {
|
||||
// 250ms buffer for 96kHz
|
||||
(sample_rate / 4) as i64
|
||||
} else {
|
||||
// 125ms buffer for lower rates
|
||||
(sample_rate / 8) as i64
|
||||
};
|
||||
|
||||
hwp.set_buffer_size_near(buffer_size)
|
||||
.map_err(|e| format!("Failed to set buffer size: {}", e))?;
|
||||
|
||||
// Set period size (1/10 of buffer)
|
||||
hwp.set_period_size_near(buffer_size / 10, ValueOr::Nearest)
|
||||
.map_err(|e| format!("Failed to set period size: {}", e))?;
|
||||
|
||||
// Apply hardware parameters
|
||||
pcm.hw_params(&hwp)
|
||||
.map_err(|e| format!("Failed to apply hardware params: {}", e))?;
|
||||
|
||||
log::info!("[ALSA Direct] Hardware configured: {}Hz, {}ch, buffer: {} frames, format: {:?}",
|
||||
sample_rate, channels, buffer_size, format);
|
||||
|
||||
format
|
||||
};
|
||||
|
||||
// Prepare device for playback
|
||||
pcm.prepare()
|
||||
.map_err(|e| format!("Failed to prepare PCM: {}", e))?;
|
||||
|
||||
Ok(Self {
|
||||
pcm: Arc::new(Mutex::new(pcm)),
|
||||
is_playing: Arc::new(AtomicBool::new(false)),
|
||||
sample_rate,
|
||||
channels,
|
||||
format: selected_format,
|
||||
device_id: device_id.to_string(),
|
||||
})
|
||||
}
|
||||
|
||||
/// Write audio samples to ALSA (auto-converts from i16 based on detected format)
|
||||
#[cfg(target_os = "linux")]
|
||||
pub fn write(&self, samples_i16: &[i16]) -> Result<(), String> {
|
||||
let pcm = self.pcm.lock().unwrap();
|
||||
let frames = samples_i16.len() / self.channels as usize;
|
||||
|
||||
match self.format {
|
||||
Format::FloatLE => {
|
||||
// Convert i16 to f32
|
||||
let samples_f32: Vec<f32> = samples_i16
|
||||
.iter()
|
||||
.map(|&s| s as f32 / 32768.0)
|
||||
.collect();
|
||||
|
||||
let io = pcm.io_f32()
|
||||
.map_err(|e| format!("Failed to get PCM I/O: {}", e))?;
|
||||
|
||||
match io.writei(&samples_f32) {
|
||||
Ok(written) => {
|
||||
if written != frames {
|
||||
log::warn!("[ALSA Direct] Partial write: {} / {} frames", written, frames);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
Err(e) => {
|
||||
if let Err(recover_err) = pcm.recover(e.errno() as i32, false) {
|
||||
Err(format!("Failed to recover from error: {}", recover_err))
|
||||
} else {
|
||||
log::warn!("[ALSA Direct] Recovered from PCM error");
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Format::S32LE => {
|
||||
// Convert i16 to i32 (bit-perfect: shift left 16 bits)
|
||||
let samples_i32: Vec<i32> = samples_i16
|
||||
.iter()
|
||||
.map(|&s| (s as i32) << 16)
|
||||
.collect();
|
||||
|
||||
let io = pcm.io_i32()
|
||||
.map_err(|e| format!("Failed to get PCM I/O: {}", e))?;
|
||||
|
||||
match io.writei(&samples_i32) {
|
||||
Ok(written) => {
|
||||
if written != frames {
|
||||
log::warn!("[ALSA Direct] Partial write: {} / {} frames", written, frames);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
Err(e) => {
|
||||
if let Err(recover_err) = pcm.recover(e.errno() as i32, false) {
|
||||
Err(format!("Failed to recover from error: {}", recover_err))
|
||||
} else {
|
||||
log::warn!("[ALSA Direct] Recovered from PCM error");
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Format::S16LE => {
|
||||
// Direct write (no conversion needed)
|
||||
let io = pcm.io_i16()
|
||||
.map_err(|e| format!("Failed to get PCM I/O: {}", e))?;
|
||||
|
||||
match io.writei(samples_i16) {
|
||||
Ok(written) => {
|
||||
if written != frames {
|
||||
log::warn!("[ALSA Direct] Partial write: {} / {} frames", written, frames);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
Err(e) => {
|
||||
if let Err(recover_err) = pcm.recover(e.errno() as i32, false) {
|
||||
Err(format!("Failed to recover from error: {}", recover_err))
|
||||
} else {
|
||||
log::warn!("[ALSA Direct] Recovered from PCM error");
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Format::S243LE => {
|
||||
// S24_3LE: 24-bit packed in 3 bytes, little-endian
|
||||
// Required by SMSL-class USB DACs (TAS1020B chip)
|
||||
// Convert i16 → i24: shift left 8 bits, then pack into 3 bytes
|
||||
let mut bytes: Vec<u8> = Vec::with_capacity(samples_i16.len() * 3);
|
||||
|
||||
for &sample in samples_i16 {
|
||||
// Convert i16 to i24 (lossless: zeros in lower 8 bits)
|
||||
let s24 = (sample as i32) << 8;
|
||||
// Pack as 3 bytes in little-endian order
|
||||
bytes.push((s24 & 0xFF) as u8); // LSB
|
||||
bytes.push(((s24 >> 8) & 0xFF) as u8); // Middle
|
||||
bytes.push(((s24 >> 16) & 0xFF) as u8); // MSB (sign-extended)
|
||||
}
|
||||
|
||||
// Use raw byte I/O for 3-byte packed format
|
||||
let io = pcm.io_bytes();
|
||||
|
||||
match io.writei(&bytes) {
|
||||
Ok(written) => {
|
||||
if written != frames {
|
||||
log::warn!("[ALSA Direct] Partial write: {} / {} frames (S24_3LE)", written, frames);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
Err(e) => {
|
||||
if let Err(recover_err) = pcm.recover(e.errno() as i32, false) {
|
||||
Err(format!("Failed to recover from error: {}", recover_err))
|
||||
} else {
|
||||
log::warn!("[ALSA Direct] Recovered from PCM error (S24_3LE)");
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Format::S24LE => {
|
||||
// S24LE: 24-bit in 32-bit container (padded)
|
||||
// Convert i16 → i32, shift left 16 bits (same as S32LE for i16 source)
|
||||
let samples_i32: Vec<i32> = samples_i16
|
||||
.iter()
|
||||
.map(|&s| (s as i32) << 16)
|
||||
.collect();
|
||||
|
||||
let io = pcm.io_i32()
|
||||
.map_err(|e| format!("Failed to get PCM I/O: {}", e))?;
|
||||
|
||||
match io.writei(&samples_i32) {
|
||||
Ok(written) => {
|
||||
if written != frames {
|
||||
log::warn!("[ALSA Direct] Partial write: {} / {} frames", written, frames);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
Err(e) => {
|
||||
if let Err(recover_err) = pcm.recover(e.errno() as i32, false) {
|
||||
Err(format!("Failed to recover from error: {}", recover_err))
|
||||
} else {
|
||||
log::warn!("[ALSA Direct] Recovered from PCM error");
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
Err(format!("Unsupported format: {:?}", self.format))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Write f32 audio samples to ALSA (converts to hardware format with full precision)
|
||||
///
|
||||
/// f32 has 24 bits of significand, so 24-bit audio is preserved losslessly.
|
||||
/// This is the primary write path for the f32 pipeline.
|
||||
#[cfg(target_os = "linux")]
|
||||
pub fn write_f32(&self, samples_f32: &[f32]) -> Result<(), String> {
|
||||
let pcm = self.pcm.lock().unwrap();
|
||||
let frames = samples_f32.len() / self.channels as usize;
|
||||
|
||||
match self.format {
|
||||
Format::FloatLE => {
|
||||
// Direct write - no conversion needed
|
||||
let io = pcm.io_f32()
|
||||
.map_err(|e| format!("Failed to get PCM I/O: {}", e))?;
|
||||
|
||||
match io.writei(samples_f32) {
|
||||
Ok(written) => {
|
||||
if written != frames {
|
||||
log::warn!("[ALSA Direct] Partial write: {} / {} frames", written, frames);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
Err(e) => {
|
||||
if let Err(recover_err) = pcm.recover(e.errno() as i32, false) {
|
||||
Err(format!("Failed to recover from error: {}", recover_err))
|
||||
} else {
|
||||
log::warn!("[ALSA Direct] Recovered from PCM error");
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Format::S32LE => {
|
||||
// f32 [-1.0, 1.0] -> i32 full range
|
||||
let samples_i32: Vec<i32> = samples_f32
|
||||
.iter()
|
||||
.map(|&s| (s * 2_147_483_647.0) as i32)
|
||||
.collect();
|
||||
|
||||
let io = pcm.io_i32()
|
||||
.map_err(|e| format!("Failed to get PCM I/O: {}", e))?;
|
||||
|
||||
match io.writei(&samples_i32) {
|
||||
Ok(written) => {
|
||||
if written != frames {
|
||||
log::warn!("[ALSA Direct] Partial write: {} / {} frames", written, frames);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
Err(e) => {
|
||||
if let Err(recover_err) = pcm.recover(e.errno() as i32, false) {
|
||||
Err(format!("Failed to recover from error: {}", recover_err))
|
||||
} else {
|
||||
log::warn!("[ALSA Direct] Recovered from PCM error");
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Format::S24LE => {
|
||||
// f32 -> 24-bit in 32-bit container
|
||||
// Clamp to 24-bit range: [-8388608, 8388607]
|
||||
let samples_i32: Vec<i32> = samples_f32
|
||||
.iter()
|
||||
.map(|&s| {
|
||||
let scaled = s * 8_388_607.0;
|
||||
scaled.clamp(-8_388_608.0, 8_388_607.0) as i32
|
||||
})
|
||||
.collect();
|
||||
|
||||
let io = pcm.io_i32()
|
||||
.map_err(|e| format!("Failed to get PCM I/O: {}", e))?;
|
||||
|
||||
match io.writei(&samples_i32) {
|
||||
Ok(written) => {
|
||||
if written != frames {
|
||||
log::warn!("[ALSA Direct] Partial write: {} / {} frames", written, frames);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
Err(e) => {
|
||||
if let Err(recover_err) = pcm.recover(e.errno() as i32, false) {
|
||||
Err(format!("Failed to recover from error: {}", recover_err))
|
||||
} else {
|
||||
log::warn!("[ALSA Direct] Recovered from PCM error");
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Format::S243LE => {
|
||||
// S24_3LE: 24-bit packed in 3 bytes, little-endian
|
||||
// f32 -> 24-bit integer, packed into 3 bytes
|
||||
let mut bytes: Vec<u8> = Vec::with_capacity(samples_f32.len() * 3);
|
||||
|
||||
for &sample in samples_f32 {
|
||||
let scaled = sample * 8_388_607.0;
|
||||
let s24 = scaled.clamp(-8_388_608.0, 8_388_607.0) as i32;
|
||||
// Pack as 3 bytes in little-endian order
|
||||
bytes.push((s24 & 0xFF) as u8); // LSB
|
||||
bytes.push(((s24 >> 8) & 0xFF) as u8); // Middle
|
||||
bytes.push(((s24 >> 16) & 0xFF) as u8); // MSB (sign-extended)
|
||||
}
|
||||
|
||||
let io = pcm.io_bytes();
|
||||
|
||||
match io.writei(&bytes) {
|
||||
Ok(written) => {
|
||||
if written != frames {
|
||||
log::warn!("[ALSA Direct] Partial write: {} / {} frames (S24_3LE)", written, frames);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
Err(e) => {
|
||||
if let Err(recover_err) = pcm.recover(e.errno() as i32, false) {
|
||||
Err(format!("Failed to recover from error: {}", recover_err))
|
||||
} else {
|
||||
log::warn!("[ALSA Direct] Recovered from PCM error (S24_3LE)");
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Format::S16LE => {
|
||||
// f32 -> i16
|
||||
let samples_i16: Vec<i16> = samples_f32
|
||||
.iter()
|
||||
.map(|&s| (s * 32_767.0) as i16)
|
||||
.collect();
|
||||
|
||||
let io = pcm.io_i16()
|
||||
.map_err(|e| format!("Failed to get PCM I/O: {}", e))?;
|
||||
|
||||
match io.writei(&samples_i16) {
|
||||
Ok(written) => {
|
||||
if written != frames {
|
||||
log::warn!("[ALSA Direct] Partial write: {} / {} frames", written, frames);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
Err(e) => {
|
||||
if let Err(recover_err) = pcm.recover(e.errno() as i32, false) {
|
||||
Err(format!("Failed to recover from error: {}", recover_err))
|
||||
} else {
|
||||
log::warn!("[ALSA Direct] Recovered from PCM error");
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
Err(format!("Unsupported format: {:?}", self.format))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Drain and stop playback
|
||||
#[cfg(target_os = "linux")]
|
||||
pub fn drain(&self) -> Result<(), String> {
|
||||
log::info!("[ALSA Direct] Draining PCM");
|
||||
let pcm = self.pcm.lock().unwrap();
|
||||
pcm.drain()
|
||||
.map_err(|e| format!("Failed to drain PCM: {}", e))
|
||||
}
|
||||
|
||||
/// Stop PCM immediately (prepare for next playback)
|
||||
#[cfg(target_os = "linux")]
|
||||
pub fn stop(&self) -> Result<(), String> {
|
||||
log::info!("[ALSA Direct] Stopping PCM");
|
||||
let pcm = self.pcm.lock().unwrap();
|
||||
// PCM::drop() is called automatically when pcm goes out of scope
|
||||
// For now, just prepare for next playback
|
||||
pcm.prepare()
|
||||
.map_err(|e| format!("Failed to prepare PCM after stop: {}", e))
|
||||
}
|
||||
|
||||
/// Get sample rate
|
||||
pub fn sample_rate(&self) -> u32 {
|
||||
self.sample_rate
|
||||
}
|
||||
|
||||
/// Get channels
|
||||
pub fn channels(&self) -> u16 {
|
||||
self.channels
|
||||
}
|
||||
|
||||
/// Get device ID
|
||||
pub fn device_id(&self) -> &str {
|
||||
&self.device_id
|
||||
}
|
||||
|
||||
/// Try to set hardware volume via ALSA mixer
|
||||
///
|
||||
/// Returns error if:
|
||||
/// - DAC doesn't have mixer controls (common for USB DACs)
|
||||
/// - Mixer API fails
|
||||
///
|
||||
/// NOTE: Failure doesn't break playback, just means volume can't be controlled.
|
||||
#[cfg(target_os = "linux")]
|
||||
pub fn set_hardware_volume(&self, volume: f32) -> Result<(), String> {
|
||||
use alsa::mixer::{Mixer, SelemId};
|
||||
use alsa::mixer::SelemChannelId::*;
|
||||
|
||||
// Open mixer for device
|
||||
let mixer = Mixer::new(&self.device_id, false)
|
||||
.map_err(|e| format!("Failed to open mixer for {}: {}", self.device_id, e))?;
|
||||
|
||||
// Try to find a volume control element
|
||||
// Common names: "Master", "PCM", "Speaker", "Headphone"
|
||||
let control_names = ["Master", "PCM", "Speaker", "Headphone", "Digital"];
|
||||
|
||||
for name in &control_names {
|
||||
let selem_id = SelemId::new(name, 0);
|
||||
|
||||
if let Some(selem) = mixer.find_selem(&selem_id) {
|
||||
// Check if this element has playback volume control
|
||||
if selem.has_playback_volume() {
|
||||
let (min, max) = selem.get_playback_volume_range();
|
||||
let target = min + ((max - min) as f32 * volume) as i64;
|
||||
|
||||
log::info!("[ALSA Direct] Setting hardware volume via '{}': {:.0}% (raw: {}/{})",
|
||||
name, volume * 100.0, target, max);
|
||||
|
||||
// Set volume on all channels
|
||||
for channel in &[FrontLeft, FrontRight, FrontCenter, RearLeft, RearRight] {
|
||||
let _ = selem.set_playback_volume(*channel, target);
|
||||
}
|
||||
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Err(format!("No volume control found for {}. DAC may not support hardware mixer.", self.device_id))
|
||||
}
|
||||
|
||||
/// Check if device is a bit-perfect hardware device
|
||||
/// Includes: hw:X,Y, plughw:X,Y, and front:CARD=X,DEV=Y
|
||||
pub fn is_hw_device(device_id: &str) -> bool {
|
||||
device_id.starts_with("hw:")
|
||||
|| device_id.starts_with("plughw:")
|
||||
|| device_id.starts_with("front:CARD=")
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
impl AlsaDirectStream {
|
||||
pub fn new(_device_id: &str, _sample_rate: u32, _channels: u16) -> Result<Self, String> {
|
||||
Err("ALSA Direct is only available on Linux".to_string())
|
||||
}
|
||||
|
||||
pub fn write(&self, _samples: &[i16]) -> Result<(), String> {
|
||||
Err("ALSA Direct is only available on Linux".to_string())
|
||||
}
|
||||
|
||||
pub fn write_f32(&self, _samples: &[f32]) -> Result<(), String> {
|
||||
Err("ALSA Direct is only available on Linux".to_string())
|
||||
}
|
||||
|
||||
pub fn drain(&self) -> Result<(), String> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn stop(&self) -> Result<(), String> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn sample_rate(&self) -> u32 {
|
||||
44100
|
||||
}
|
||||
|
||||
pub fn channels(&self) -> u16 {
|
||||
2
|
||||
}
|
||||
|
||||
/// Check if device is a bit-perfect hardware device (always false on non-Linux)
|
||||
pub fn is_hw_device(_device_id: &str) -> bool {
|
||||
false
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
//! Analyzer tap — captures audio samples for loudness analysis.
|
||||
//!
|
||||
//! Sits in the audio pipeline as a transparent `Source<Item = f32>` wrapper.
|
||||
//! Batches samples and sends them to the loudness analyzer thread via a bounded
|
||||
//! channel. Uses `try_send` so it never blocks the audio thread — if the channel
|
||||
//! is full, the batch is silently dropped (graceful degradation).
|
||||
|
||||
use std::sync::atomic::{AtomicBool, AtomicU32, Ordering};
|
||||
use std::sync::mpsc::SyncSender;
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
use rodio::Source;
|
||||
|
||||
/// Messages sent from the audio pipeline to the loudness analyzer thread.
|
||||
pub enum AnalyzerMessage {
|
||||
/// A batch of interleaved f32 samples.
|
||||
Samples(Vec<f32>),
|
||||
/// A new track has started — reset analyzer state.
|
||||
NewTrack {
|
||||
track_id: u64,
|
||||
sample_rate: u32,
|
||||
channels: u16,
|
||||
target_lufs: f32,
|
||||
/// Shared gain atomic — analyzer writes, DynamicAmplify reads.
|
||||
gain_atomic: Arc<AtomicU32>,
|
||||
},
|
||||
/// Seek occurred — reset accumulated samples but keep current gain.
|
||||
Reset,
|
||||
/// Shut down the analyzer thread.
|
||||
Shutdown,
|
||||
}
|
||||
|
||||
const BATCH_SIZE: usize = 4096;
|
||||
|
||||
pub struct AnalyzerTap<S>
|
||||
where
|
||||
S: Source<Item = f32>,
|
||||
{
|
||||
inner: S,
|
||||
sender: SyncSender<AnalyzerMessage>,
|
||||
enabled: Arc<AtomicBool>,
|
||||
buffer: Vec<f32>,
|
||||
}
|
||||
|
||||
impl<S> AnalyzerTap<S>
|
||||
where
|
||||
S: Source<Item = f32>,
|
||||
{
|
||||
pub fn new(source: S, sender: SyncSender<AnalyzerMessage>, enabled: Arc<AtomicBool>) -> Self {
|
||||
Self {
|
||||
inner: source,
|
||||
sender,
|
||||
enabled,
|
||||
buffer: Vec::with_capacity(BATCH_SIZE),
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn flush_if_full(&mut self) {
|
||||
if self.buffer.len() >= BATCH_SIZE {
|
||||
let batch = std::mem::replace(&mut self.buffer, Vec::with_capacity(BATCH_SIZE));
|
||||
// Non-blocking send — drop batch if channel is full
|
||||
let _ = self.sender.try_send(AnalyzerMessage::Samples(batch));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<S> Iterator for AnalyzerTap<S>
|
||||
where
|
||||
S: Source<Item = f32>,
|
||||
{
|
||||
type Item = f32;
|
||||
|
||||
#[inline]
|
||||
fn next(&mut self) -> Option<Self::Item> {
|
||||
let sample = self.inner.next()?;
|
||||
|
||||
if self.enabled.load(Ordering::Relaxed) {
|
||||
self.buffer.push(sample);
|
||||
self.flush_if_full();
|
||||
}
|
||||
|
||||
Some(sample)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn size_hint(&self) -> (usize, Option<usize>) {
|
||||
self.inner.size_hint()
|
||||
}
|
||||
}
|
||||
|
||||
impl<S> Source for AnalyzerTap<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()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,311 @@
|
||||
//! Audio backend abstraction
|
||||
//!
|
||||
//! Provides a unified interface for different audio backends (PipeWire, ALSA, PulseAudio)
|
||||
//! allowing users to choose their preferred audio stack.
|
||||
|
||||
use rodio::{OutputStream, OutputStreamHandle};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Supported audio backends
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub enum AudioBackendType {
|
||||
/// PipeWire backend (modern, recommended)
|
||||
/// - Supports device selection without changing system default
|
||||
/// - Uses PULSE_SINK environment variable
|
||||
/// - Compatible with PulseAudio apps
|
||||
PipeWire,
|
||||
|
||||
/// ALSA backend (direct hardware access)
|
||||
/// - True exclusive mode (blocks device for other apps)
|
||||
/// - Bit-perfect guaranteed
|
||||
/// - Lowest latency
|
||||
/// - Requires manual device selection (hw:X,Y)
|
||||
Alsa,
|
||||
|
||||
/// PulseAudio backend (legacy compatibility)
|
||||
/// - Similar to PipeWire but older
|
||||
/// - Fallback for systems without PipeWire
|
||||
Pulse,
|
||||
}
|
||||
|
||||
impl Default for AudioBackendType {
|
||||
fn default() -> Self {
|
||||
// PipeWire is the modern default on Linux
|
||||
AudioBackendType::PipeWire
|
||||
}
|
||||
}
|
||||
|
||||
/// ALSA plugin type (only relevant for ALSA backend)
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub enum AlsaPlugin {
|
||||
/// Direct hardware access (hw)
|
||||
/// - Bit-perfect, exclusive
|
||||
/// - No automatic format conversion
|
||||
/// - Blocks device for other apps
|
||||
Hw,
|
||||
|
||||
/// Plug hardware access (plughw)
|
||||
/// - Automatic format conversion
|
||||
/// - Resampling if needed
|
||||
/// - Still relatively direct
|
||||
PlugHw,
|
||||
|
||||
/// PCM device (default)
|
||||
/// - Generic ALSA device
|
||||
/// - Most compatible
|
||||
Pcm,
|
||||
}
|
||||
|
||||
impl Default for AlsaPlugin {
|
||||
fn default() -> Self {
|
||||
// Hw is the audiophile choice
|
||||
AlsaPlugin::Hw
|
||||
}
|
||||
}
|
||||
|
||||
/// Audio device information
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct AudioDevice {
|
||||
/// Internal device identifier (e.g., "hw:4,0" for ALSA, sink name for PipeWire)
|
||||
pub id: String,
|
||||
|
||||
/// User-friendly display name
|
||||
pub name: String,
|
||||
|
||||
/// Detailed description (optional)
|
||||
pub description: Option<String>,
|
||||
|
||||
/// Whether this is the system default device
|
||||
pub is_default: bool,
|
||||
|
||||
/// Maximum supported sample rate (if known)
|
||||
pub max_sample_rate: Option<u32>,
|
||||
|
||||
/// Supported sample rates (common audio rates that the device supports)
|
||||
/// Contains values like 44100, 48000, 88200, 96000, 176400, 192000, etc.
|
||||
pub supported_sample_rates: Option<Vec<u32>>,
|
||||
|
||||
/// Device bus type (for PipeWire): "usb", "pci", "bluetooth", or None
|
||||
pub device_bus: Option<String>,
|
||||
|
||||
/// Whether this is a hardware device (has HARDWARE flag in PipeWire)
|
||||
pub is_hardware: bool,
|
||||
}
|
||||
|
||||
/// Audio backend configuration
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct BackendConfig {
|
||||
/// Backend type
|
||||
pub backend_type: AudioBackendType,
|
||||
|
||||
/// Device ID (backend-specific)
|
||||
pub device_id: Option<String>,
|
||||
|
||||
/// ALSA plugin (only used if backend_type == Alsa)
|
||||
pub alsa_plugin: Option<AlsaPlugin>,
|
||||
|
||||
/// Sample rate (for stream creation)
|
||||
pub sample_rate: u32,
|
||||
|
||||
/// Channels
|
||||
pub channels: u16,
|
||||
|
||||
/// Exclusive mode flag
|
||||
pub exclusive_mode: bool,
|
||||
}
|
||||
|
||||
/// Result type for backend operations
|
||||
pub type BackendResult<T> = Result<T, String>;
|
||||
|
||||
/// ALSA Direct stream error classification
|
||||
/// Used to determine if fallback to plughw is appropriate
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum AlsaDirectError {
|
||||
/// PCM format not supported by hardware (can fallback to plughw)
|
||||
UnsupportedFormat(String),
|
||||
/// Device is busy/in use by another application
|
||||
DeviceBusy(String),
|
||||
/// Permission denied to access device
|
||||
PermissionDenied(String),
|
||||
/// Invalid parameters (channels, sample rate)
|
||||
InvalidParams(String),
|
||||
/// Device not found
|
||||
DeviceNotFound(String),
|
||||
/// Generic/unknown error
|
||||
Other(String),
|
||||
}
|
||||
|
||||
impl std::fmt::Display for AlsaDirectError {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
AlsaDirectError::UnsupportedFormat(msg) => write!(f, "Unsupported format: {}", msg),
|
||||
AlsaDirectError::DeviceBusy(msg) => write!(f, "Device busy: {}", msg),
|
||||
AlsaDirectError::PermissionDenied(msg) => write!(f, "Permission denied: {}", msg),
|
||||
AlsaDirectError::InvalidParams(msg) => write!(f, "Invalid parameters: {}", msg),
|
||||
AlsaDirectError::DeviceNotFound(msg) => write!(f, "Device not found: {}", msg),
|
||||
AlsaDirectError::Other(msg) => write!(f, "{}", msg),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl AlsaDirectError {
|
||||
/// Check if this error allows fallback to plughw
|
||||
pub fn allows_plughw_fallback(&self) -> bool {
|
||||
matches!(self, AlsaDirectError::UnsupportedFormat(_))
|
||||
}
|
||||
|
||||
/// Create from raw ALSA error message
|
||||
pub fn from_alsa_error(msg: &str) -> Self {
|
||||
let msg_lower = msg.to_lowercase();
|
||||
|
||||
if msg_lower.contains("no supported audio format")
|
||||
|| msg_lower.contains("format")
|
||||
|| msg_lower.contains("s24_3le")
|
||||
|| msg_lower.contains("s24le")
|
||||
|| msg_lower.contains("sample format")
|
||||
{
|
||||
AlsaDirectError::UnsupportedFormat(msg.to_string())
|
||||
} else if msg_lower.contains("busy")
|
||||
|| msg_lower.contains("resource temporarily unavailable")
|
||||
|| msg_lower.contains("device or resource busy")
|
||||
{
|
||||
AlsaDirectError::DeviceBusy(msg.to_string())
|
||||
} else if msg_lower.contains("permission")
|
||||
|| msg_lower.contains("access denied")
|
||||
|| msg_lower.contains("operation not permitted")
|
||||
{
|
||||
AlsaDirectError::PermissionDenied(msg.to_string())
|
||||
} else if msg_lower.contains("not found")
|
||||
|| msg_lower.contains("no such")
|
||||
|| msg_lower.contains("doesn't exist")
|
||||
{
|
||||
AlsaDirectError::DeviceNotFound(msg.to_string())
|
||||
} else if msg_lower.contains("invalid")
|
||||
|| msg_lower.contains("channels")
|
||||
|| msg_lower.contains("rate")
|
||||
{
|
||||
AlsaDirectError::InvalidParams(msg.to_string())
|
||||
} else {
|
||||
AlsaDirectError::Other(msg.to_string())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Runtime mode for bit-perfect status tracking
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub enum BitPerfectMode {
|
||||
/// Direct hardware access (hw:), guaranteed bit-perfect
|
||||
DirectHardware,
|
||||
/// Plugin hardware fallback (plughw:), bit-perfect with format conversion only
|
||||
PluginFallback,
|
||||
/// Not using bit-perfect path (pcm, pipewire, pulse)
|
||||
Disabled,
|
||||
}
|
||||
|
||||
/// Audio backend trait
|
||||
///
|
||||
/// All audio backends must implement this trait to provide
|
||||
/// a consistent interface for device enumeration and stream creation.
|
||||
pub trait AudioBackend: Send + Sync {
|
||||
/// Get the backend type
|
||||
fn backend_type(&self) -> AudioBackendType;
|
||||
|
||||
/// Enumerate available audio devices for this backend
|
||||
fn enumerate_devices(&self) -> BackendResult<Vec<AudioDevice>>;
|
||||
|
||||
/// Create an output stream for the given configuration
|
||||
fn create_output_stream(
|
||||
&self,
|
||||
config: &BackendConfig,
|
||||
) -> BackendResult<(OutputStream, OutputStreamHandle)>;
|
||||
|
||||
/// Check if this backend is available on the current system
|
||||
fn is_available(&self) -> bool;
|
||||
|
||||
/// Get a description of this backend for UI display
|
||||
fn description(&self) -> &'static str;
|
||||
|
||||
/// Downcast to concrete type (for ALSA Direct stream creation)
|
||||
fn as_any(&self) -> &dyn std::any::Any;
|
||||
}
|
||||
|
||||
/// Backend manager - factory for creating backends
|
||||
pub struct BackendManager;
|
||||
|
||||
impl BackendManager {
|
||||
/// Get all available backends on this system
|
||||
pub fn available_backends() -> Vec<AudioBackendType> {
|
||||
let mut backends = Vec::new();
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
{
|
||||
// PipeWire (check if running)
|
||||
if Self::is_pipewire_available() {
|
||||
backends.push(AudioBackendType::PipeWire);
|
||||
}
|
||||
|
||||
// ALSA (always available on Linux)
|
||||
backends.push(AudioBackendType::Alsa);
|
||||
|
||||
// PulseAudio (check if running)
|
||||
if Self::is_pulse_available() {
|
||||
backends.push(AudioBackendType::Pulse);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
{
|
||||
// On non-Linux, only PipeWire backend (which uses CPAL default)
|
||||
backends.push(AudioBackendType::PipeWire);
|
||||
}
|
||||
|
||||
backends
|
||||
}
|
||||
|
||||
/// Create a backend instance
|
||||
pub fn create_backend(backend_type: AudioBackendType) -> BackendResult<Box<dyn AudioBackend>> {
|
||||
match backend_type {
|
||||
AudioBackendType::PipeWire => {
|
||||
let backend = crate::pipewire_backend::PipeWireBackend::new()?;
|
||||
Ok(Box::new(backend))
|
||||
}
|
||||
AudioBackendType::Alsa => {
|
||||
#[cfg(target_os = "linux")]
|
||||
{
|
||||
let backend = crate::alsa_backend::AlsaBackend::new()?;
|
||||
Ok(Box::new(backend))
|
||||
}
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
{
|
||||
Err("ALSA backend only available on Linux".to_string())
|
||||
}
|
||||
}
|
||||
AudioBackendType::Pulse => {
|
||||
let backend = crate::pulse_backend::PulseBackend::new()?;
|
||||
Ok(Box::new(backend))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
fn is_pipewire_available() -> bool {
|
||||
// Check if PipeWire/PulseAudio is available using pactl
|
||||
// PipeWire provides PulseAudio compatibility, so pactl works for both
|
||||
// This is more reliable than pw-cli, especially in sandboxed environments (Flatpak)
|
||||
std::process::Command::new("pactl")
|
||||
.arg("info")
|
||||
.output()
|
||||
.map(|o| o.status.success())
|
||||
.unwrap_or(false)
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
fn is_pulse_available() -> bool {
|
||||
// Check if PulseAudio is running
|
||||
std::process::Command::new("pactl")
|
||||
.arg("info")
|
||||
.output()
|
||||
.map(|o| o.status.success())
|
||||
.unwrap_or(false)
|
||||
}
|
||||
}
|
||||
@@ -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()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,137 @@
|
||||
//! Dynamic gain wrapper for real-time volume normalization.
|
||||
//!
|
||||
//! Reads gain from a shared `Arc<AtomicU32>` (f32 stored as bits) and applies
|
||||
//! it to each sample. When the gain value changes, a 50ms linear ramp smooths
|
||||
//! the transition to prevent audible clicks.
|
||||
//!
|
||||
//! When the atomic holds 0.0 (gain not yet computed), the wrapper stays at
|
||||
//! the `initial_gain` provided at construction.
|
||||
|
||||
use std::sync::atomic::{AtomicU32, Ordering};
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
use rodio::Source;
|
||||
|
||||
pub struct DynamicAmplify<S>
|
||||
where
|
||||
S: Source<Item = f32>,
|
||||
{
|
||||
inner: S,
|
||||
gain_atomic: Arc<AtomicU32>,
|
||||
/// Current applied gain (smoothly ramped)
|
||||
current_gain: f32,
|
||||
/// Target gain we're ramping toward
|
||||
target_gain: f32,
|
||||
/// Gain increment per sample during ramp
|
||||
ramp_step: f32,
|
||||
/// Samples remaining in the current ramp
|
||||
ramp_remaining: u32,
|
||||
/// Number of samples in a 50ms ramp at the current sample rate
|
||||
ramp_samples: u32,
|
||||
}
|
||||
|
||||
impl<S> DynamicAmplify<S>
|
||||
where
|
||||
S: Source<Item = f32>,
|
||||
{
|
||||
pub fn new(source: S, gain_atomic: Arc<AtomicU32>, initial_gain: f32) -> Self {
|
||||
let sample_rate = source.sample_rate();
|
||||
let channels = source.channels() as u32;
|
||||
// 50ms ramp in total samples (all channels)
|
||||
let ramp_samples = (sample_rate * channels * 50) / 1000;
|
||||
|
||||
Self {
|
||||
inner: source,
|
||||
gain_atomic,
|
||||
current_gain: initial_gain,
|
||||
target_gain: initial_gain,
|
||||
ramp_step: 0.0,
|
||||
ramp_remaining: 0,
|
||||
ramp_samples,
|
||||
}
|
||||
}
|
||||
|
||||
/// Check for a new gain value and start a ramp if it changed.
|
||||
#[inline]
|
||||
fn poll_gain(&mut self) {
|
||||
let bits = self.gain_atomic.load(Ordering::Relaxed);
|
||||
let new_gain = f32::from_bits(bits);
|
||||
|
||||
// 0.0 means "not yet computed" — stay at current gain
|
||||
if new_gain == 0.0 {
|
||||
return;
|
||||
}
|
||||
|
||||
// Only start a ramp if the target actually changed
|
||||
if (new_gain - self.target_gain).abs() > f32::EPSILON {
|
||||
self.target_gain = new_gain;
|
||||
if self.ramp_samples > 0 {
|
||||
self.ramp_step = (self.target_gain - self.current_gain) / self.ramp_samples as f32;
|
||||
self.ramp_remaining = self.ramp_samples;
|
||||
} else {
|
||||
self.current_gain = self.target_gain;
|
||||
self.ramp_remaining = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<S> Iterator for DynamicAmplify<S>
|
||||
where
|
||||
S: Source<Item = f32>,
|
||||
{
|
||||
type Item = f32;
|
||||
|
||||
#[inline]
|
||||
fn next(&mut self) -> Option<Self::Item> {
|
||||
// Poll for new gain every 1024 samples to avoid atomic contention
|
||||
// (ramp_remaining check is essentially free)
|
||||
if self.ramp_remaining == 0 {
|
||||
self.poll_gain();
|
||||
}
|
||||
|
||||
let sample = self.inner.next()?;
|
||||
|
||||
if self.ramp_remaining > 0 {
|
||||
self.current_gain += self.ramp_step;
|
||||
self.ramp_remaining -= 1;
|
||||
if self.ramp_remaining == 0 {
|
||||
// Snap to target at end of ramp to avoid float drift
|
||||
self.current_gain = self.target_gain;
|
||||
}
|
||||
}
|
||||
|
||||
Some(sample * self.current_gain)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn size_hint(&self) -> (usize, Option<usize>) {
|
||||
self.inner.size_hint()
|
||||
}
|
||||
}
|
||||
|
||||
impl<S> Source for DynamicAmplify<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()
|
||||
}
|
||||
}
|
||||
+56
-21
@@ -1,25 +1,60 @@
|
||||
//! QBZ Audio - Bit-perfect audio backend system
|
||||
//! QBZ Audio - Audio backend system for bit-perfect playback
|
||||
//!
|
||||
//! This crate provides the audio backend abstraction for QBZ:
|
||||
//! - AudioBackend trait
|
||||
//! - PipeWire backend (Linux)
|
||||
//! - ALSA backend (Linux)
|
||||
//! - ALSA Direct backend (Linux, bit-perfect)
|
||||
//! This crate provides the audio backend abstraction layer:
|
||||
//! - Backend trait and implementations (PipeWire, ALSA, PulseAudio)
|
||||
//! - Audio device enumeration and selection
|
||||
//! - Loudness analysis and normalization
|
||||
//! - Diagnostic tools
|
||||
//!
|
||||
//! # CRITICAL
|
||||
//! # CRITICAL: This code is IMMUTABLE
|
||||
//!
|
||||
//! The audio backends in this crate are IMMUTABLE.
|
||||
//! They have been extensively debugged and tested for bit-perfect playback.
|
||||
//! DO NOT modify the logic - only imports may change.
|
||||
//! The audio backend system was carefully designed for bit-perfect playback.
|
||||
//! Do NOT modify the logic in these files without understanding the full
|
||||
//! architecture. See `qbz-nix-docs/AUDIO_BACKENDS.md` for details.
|
||||
//!
|
||||
//! # Architecture
|
||||
//!
|
||||
//! ```text
|
||||
//! ┌─────────────────────────────────────────────────────────────┐
|
||||
//! │ qbz-audio (Tier 1) │
|
||||
//! │ Audio backends, device management, loudness analysis │
|
||||
//! └─────────────────────────────────────────────────────────────┘
|
||||
//! ↑
|
||||
//! ┌───────┴───────┐
|
||||
//! │ qbz-models │
|
||||
//! │ (Tier 0) │
|
||||
//! └───────────────┘
|
||||
//! ```
|
||||
|
||||
// TODO: Phase 2 - Copy audio modules from qbz-nix
|
||||
// pub mod backend;
|
||||
// pub mod pipewire_backend;
|
||||
// pub mod alsa_backend;
|
||||
// pub mod alsa_direct;
|
||||
// pub mod loudness;
|
||||
// pub mod loudness_analyzer;
|
||||
// pub mod loudness_cache;
|
||||
// pub mod dynamic_amplify;
|
||||
// pub mod analyzer_tap;
|
||||
// pub mod diagnostic;
|
||||
pub mod backend;
|
||||
pub mod pipewire_backend;
|
||||
pub mod alsa_backend;
|
||||
pub mod pulse_backend;
|
||||
pub mod alsa_direct;
|
||||
pub mod diagnostic;
|
||||
pub mod loudness;
|
||||
pub mod dynamic_amplify;
|
||||
pub mod analyzer_tap;
|
||||
pub mod loudness_cache;
|
||||
pub mod loudness_analyzer;
|
||||
|
||||
// Re-export commonly used types
|
||||
pub use backend::{
|
||||
AlsaPlugin,
|
||||
AudioBackend,
|
||||
AudioBackendType,
|
||||
AudioDevice,
|
||||
BackendConfig,
|
||||
BackendManager,
|
||||
BackendResult,
|
||||
AlsaDirectError,
|
||||
BitPerfectMode,
|
||||
};
|
||||
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};
|
||||
pub use loudness::{ReplayGainData, extract_replaygain, calculate_gain_factor, db_to_linear};
|
||||
pub use dynamic_amplify::DynamicAmplify;
|
||||
pub use analyzer_tap::{AnalyzerTap, AnalyzerMessage};
|
||||
pub use loudness_cache::LoudnessCache;
|
||||
pub use loudness_analyzer::LoudnessAnalyzer;
|
||||
@@ -0,0 +1,335 @@
|
||||
//! Loudness normalization support
|
||||
//!
|
||||
//! Extracts ReplayGain metadata from audio files and calculates gain factors
|
||||
//! for volume normalization. When normalization is disabled, this module is
|
||||
//! not invoked and the audio pipeline remains bit-perfect.
|
||||
|
||||
use symphonia::core::formats::FormatReader;
|
||||
use symphonia::core::meta::{MetadataOptions, StandardTagKey, Tag, Value};
|
||||
use symphonia::core::formats::FormatOptions;
|
||||
use symphonia::core::io::{MediaSource, MediaSourceStream};
|
||||
use symphonia::core::probe::Hint;
|
||||
use symphonia::default::get_probe;
|
||||
use std::io::{Cursor, Read, Seek, SeekFrom};
|
||||
|
||||
/// Extracted loudness data for a track
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct ReplayGainData {
|
||||
/// Gain adjustment in dB (negative = reduce volume, positive = increase)
|
||||
pub gain_db: f32,
|
||||
/// Peak sample value (0.0-1.0+), used for clipping prevention
|
||||
pub peak: Option<f32>,
|
||||
}
|
||||
|
||||
/// Wrapper to make Cursor<Vec<u8>> implement MediaSource
|
||||
struct CursorMediaSource {
|
||||
inner: Cursor<Vec<u8>>,
|
||||
}
|
||||
|
||||
impl CursorMediaSource {
|
||||
fn new(data: Vec<u8>) -> Self {
|
||||
Self { inner: Cursor::new(data) }
|
||||
}
|
||||
}
|
||||
|
||||
impl Read for CursorMediaSource {
|
||||
fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
|
||||
self.inner.read(buf)
|
||||
}
|
||||
}
|
||||
|
||||
impl Seek for CursorMediaSource {
|
||||
fn seek(&mut self, pos: SeekFrom) -> std::io::Result<u64> {
|
||||
self.inner.seek(pos)
|
||||
}
|
||||
}
|
||||
|
||||
impl MediaSource for CursorMediaSource {
|
||||
fn is_seekable(&self) -> bool { true }
|
||||
fn byte_len(&self) -> Option<u64> {
|
||||
Some(self.inner.get_ref().len() as u64)
|
||||
}
|
||||
}
|
||||
|
||||
/// Extract ReplayGain metadata from raw audio file bytes.
|
||||
///
|
||||
/// Searches for ReplayGain track gain and peak values in:
|
||||
/// - Vorbis comments (FLAC, Ogg): `REPLAYGAIN_TRACK_GAIN`, `REPLAYGAIN_TRACK_PEAK`
|
||||
/// - ID3v2 TXXX frames: `replaygain_track_gain`
|
||||
/// - Standard tag keys mapped by Symphonia
|
||||
///
|
||||
/// Returns `None` if no ReplayGain metadata is found.
|
||||
pub fn extract_replaygain(data: &[u8]) -> Option<ReplayGainData> {
|
||||
let source = Box::new(CursorMediaSource::new(data.to_vec())) as Box<dyn MediaSource>;
|
||||
let mss = MediaSourceStream::new(source, Default::default());
|
||||
|
||||
let mut hint = Hint::new();
|
||||
// Help Symphonia detect isomp4/m4a
|
||||
if data.len() >= 12 && &data[4..8] == b"ftyp" {
|
||||
hint.with_extension("m4a");
|
||||
}
|
||||
|
||||
let format_opts = FormatOptions {
|
||||
enable_gapless: true,
|
||||
..Default::default()
|
||||
};
|
||||
let metadata_opts: MetadataOptions = Default::default();
|
||||
|
||||
let mut probed = match get_probe().format(&hint, mss, &format_opts, &metadata_opts) {
|
||||
Ok(p) => p,
|
||||
Err(e) => {
|
||||
log::debug!("Loudness: probe failed for ReplayGain extraction: {}", e);
|
||||
return None;
|
||||
}
|
||||
};
|
||||
|
||||
// Collect all tags from both the probe metadata and the format reader metadata
|
||||
let mut gain_db: Option<f32> = None;
|
||||
let mut peak: Option<f32> = None;
|
||||
|
||||
// Check probe-level metadata (container-level tags)
|
||||
if let Some(metadata) = probed.metadata.get() {
|
||||
if let Some(rev) = metadata.current() {
|
||||
extract_from_tags(rev.tags(), &mut gain_db, &mut peak);
|
||||
}
|
||||
}
|
||||
|
||||
// Check format-level metadata (in-stream tags, e.g., Vorbis comments in FLAC)
|
||||
if gain_db.is_none() {
|
||||
let fmt_metadata = probed.format.metadata();
|
||||
if let Some(rev) = fmt_metadata.current() {
|
||||
extract_from_tags(rev.tags(), &mut gain_db, &mut peak);
|
||||
}
|
||||
}
|
||||
|
||||
gain_db.map(|db| {
|
||||
log::info!("Loudness: found ReplayGain: {:.2} dB, peak: {:?}", db, peak);
|
||||
ReplayGainData { gain_db: db, peak }
|
||||
})
|
||||
}
|
||||
|
||||
/// Extract ReplayGain data from a Symphonia FormatReader (for streaming sources).
|
||||
///
|
||||
/// This is used when we already have a probed format reader and don't want
|
||||
/// to re-probe the data.
|
||||
pub fn extract_replaygain_from_reader(format: &mut dyn FormatReader) -> Option<ReplayGainData> {
|
||||
let mut gain_db: Option<f32> = None;
|
||||
let mut peak: Option<f32> = None;
|
||||
|
||||
let metadata = format.metadata();
|
||||
if let Some(rev) = metadata.current() {
|
||||
extract_from_tags(rev.tags(), &mut gain_db, &mut peak);
|
||||
}
|
||||
|
||||
gain_db.map(|db| {
|
||||
log::info!("Loudness: found ReplayGain (streaming): {:.2} dB, peak: {:?}", db, peak);
|
||||
ReplayGainData { gain_db: db, peak }
|
||||
})
|
||||
}
|
||||
|
||||
/// Search tags for ReplayGain values.
|
||||
fn extract_from_tags(tags: &[Tag], gain_db: &mut Option<f32>, peak: &mut Option<f32>) {
|
||||
for tag in tags {
|
||||
// Check Symphonia's standard tag key mapping first
|
||||
if let Some(std_key) = tag.std_key {
|
||||
match std_key {
|
||||
StandardTagKey::ReplayGainTrackGain => {
|
||||
if let Some(g) = parse_gain_value(&tag.value) {
|
||||
*gain_db = Some(g);
|
||||
}
|
||||
}
|
||||
StandardTagKey::ReplayGainTrackPeak => {
|
||||
if let Some(p) = parse_peak_value(&tag.value) {
|
||||
*peak = Some(p);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
// Also check raw tag keys (case-insensitive) for formats where
|
||||
// Symphonia might not map to StandardTagKey
|
||||
let key_lower = tag.key.to_lowercase();
|
||||
match key_lower.as_str() {
|
||||
"replaygain_track_gain" => {
|
||||
if gain_db.is_none() {
|
||||
if let Some(g) = parse_gain_value(&tag.value) {
|
||||
*gain_db = Some(g);
|
||||
}
|
||||
}
|
||||
}
|
||||
"replaygain_track_peak" => {
|
||||
if peak.is_none() {
|
||||
if let Some(p) = parse_peak_value(&tag.value) {
|
||||
*peak = Some(p);
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Parse a ReplayGain gain value like "-6.54 dB" or "-6.54"
|
||||
fn parse_gain_value(value: &Value) -> Option<f32> {
|
||||
let s = value_to_string(value)?;
|
||||
// Strip " dB" suffix if present, then parse
|
||||
let trimmed = s.trim().trim_end_matches(" dB").trim_end_matches(" db").trim_end_matches("dB");
|
||||
trimmed.parse::<f32>().ok()
|
||||
}
|
||||
|
||||
/// Parse a ReplayGain peak value like "0.988553" or "1.0"
|
||||
fn parse_peak_value(value: &Value) -> Option<f32> {
|
||||
let s = value_to_string(value)?;
|
||||
s.trim().parse::<f32>().ok()
|
||||
}
|
||||
|
||||
/// Convert a Symphonia Value to a string representation
|
||||
fn value_to_string(value: &Value) -> Option<String> {
|
||||
match value {
|
||||
Value::String(s) => Some(s.clone()),
|
||||
Value::Float(f) => Some(f.to_string()),
|
||||
Value::SignedInt(i) => Some(i.to_string()),
|
||||
Value::UnsignedInt(u) => Some(u.to_string()),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Convert a gain in dB to a linear amplitude factor.
|
||||
///
|
||||
/// gain_db = 0.0 → factor = 1.0 (no change)
|
||||
/// gain_db = -6.0 → factor ≈ 0.501 (half amplitude)
|
||||
/// gain_db = +6.0 → factor ≈ 1.995 (double amplitude)
|
||||
#[inline]
|
||||
pub fn db_to_linear(db: f32) -> f32 {
|
||||
10_f32.powf(db / 20.0)
|
||||
}
|
||||
|
||||
/// Calculate the normalization gain factor for a track.
|
||||
///
|
||||
/// Takes ReplayGain metadata and a target LUFS level, returns the linear
|
||||
/// gain factor to apply to samples. Includes clipping prevention using
|
||||
/// peak data when available.
|
||||
///
|
||||
/// The ReplayGain standard targets -18 LUFS (83 dB SPL). If the user's
|
||||
/// target differs, we adjust accordingly.
|
||||
///
|
||||
/// # Arguments
|
||||
/// * `rg` - ReplayGain metadata extracted from the track
|
||||
/// * `target_lufs` - User's target loudness (e.g., -14.0, -18.0, -23.0)
|
||||
///
|
||||
/// # Returns
|
||||
/// Linear gain factor to multiply samples by
|
||||
pub fn calculate_gain_factor(rg: &ReplayGainData, target_lufs: f32) -> f32 {
|
||||
// ReplayGain reference level is -18 LUFS (EBU R128 / ReplayGain 2.0)
|
||||
const REPLAYGAIN_REFERENCE_LUFS: f32 = -18.0;
|
||||
|
||||
// Adjust gain for the user's target level
|
||||
// If target is -14 LUFS (louder than reference), we need to add +4 dB
|
||||
// If target is -23 LUFS (quieter), we need to subtract -5 dB
|
||||
let target_adjustment = target_lufs - REPLAYGAIN_REFERENCE_LUFS;
|
||||
let adjusted_gain_db = rg.gain_db + target_adjustment;
|
||||
|
||||
let mut gain = db_to_linear(adjusted_gain_db);
|
||||
|
||||
// Clipping prevention: if we have peak data, cap the gain so
|
||||
// the loudest sample doesn't exceed 1.0
|
||||
if let Some(peak) = rg.peak {
|
||||
if peak > 0.0 {
|
||||
let max_safe_gain = 1.0 / peak;
|
||||
if gain > max_safe_gain {
|
||||
log::debug!(
|
||||
"Loudness: capping gain from {:.3} to {:.3} (peak: {:.4})",
|
||||
gain, max_safe_gain, peak
|
||||
);
|
||||
gain = max_safe_gain;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Without peak data, cap at +6 dB maximum (conservative)
|
||||
if rg.peak.is_none() {
|
||||
let max_gain = db_to_linear(6.0);
|
||||
if gain > max_gain {
|
||||
log::debug!("Loudness: capping gain to +6 dB (no peak data)");
|
||||
gain = max_gain;
|
||||
}
|
||||
}
|
||||
|
||||
log::debug!(
|
||||
"Loudness: gain_db={:.2}, target={:.1} LUFS, adjusted={:.2} dB, factor={:.4}",
|
||||
rg.gain_db, target_lufs, adjusted_gain_db, gain
|
||||
);
|
||||
|
||||
gain
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_db_to_linear() {
|
||||
// 0 dB = factor 1.0
|
||||
assert!((db_to_linear(0.0) - 1.0).abs() < 0.001);
|
||||
// -6 dB ≈ 0.501
|
||||
assert!((db_to_linear(-6.0) - 0.501).abs() < 0.01);
|
||||
// +6 dB ≈ 1.995
|
||||
assert!((db_to_linear(6.0) - 1.995).abs() < 0.01);
|
||||
// -20 dB = 0.1
|
||||
assert!((db_to_linear(-20.0) - 0.1).abs() < 0.001);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_calculate_gain_factor_at_reference() {
|
||||
// At -18 LUFS target (ReplayGain reference), gain_db should pass through directly
|
||||
let rg = ReplayGainData { gain_db: -3.0, peak: Some(0.9) };
|
||||
let factor = calculate_gain_factor(&rg, -18.0);
|
||||
// -3 dB → ~0.708
|
||||
assert!((factor - 0.708).abs() < 0.01);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_calculate_gain_factor_with_target_adjustment() {
|
||||
// At -14 LUFS target, we add +4 dB to the RG gain
|
||||
let rg = ReplayGainData { gain_db: -3.0, peak: Some(0.5) };
|
||||
let factor = calculate_gain_factor(&rg, -14.0);
|
||||
// -3 + 4 = +1 dB → ~1.122
|
||||
assert!((factor - 1.122).abs() < 0.01);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_clipping_prevention_with_peak() {
|
||||
// High positive gain but peak close to 1.0 — should be capped
|
||||
let rg = ReplayGainData { gain_db: 10.0, peak: Some(0.95) };
|
||||
let factor = calculate_gain_factor(&rg, -18.0);
|
||||
// max_safe_gain = 1/0.95 ≈ 1.053, which is less than db_to_linear(10) ≈ 3.162
|
||||
assert!((factor - (1.0 / 0.95)).abs() < 0.01);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_clipping_prevention_without_peak() {
|
||||
// High gain without peak data — capped at +6 dB
|
||||
let rg = ReplayGainData { gain_db: 12.0, peak: None };
|
||||
let factor = calculate_gain_factor(&rg, -18.0);
|
||||
assert!((factor - db_to_linear(6.0)).abs() < 0.01);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_parse_gain_value_formats() {
|
||||
// Standard format: "-6.54 dB"
|
||||
assert!((parse_gain_value(&Value::String("-6.54 dB".to_string())).unwrap() - (-6.54)).abs() < 0.001);
|
||||
// Without dB suffix
|
||||
assert!((parse_gain_value(&Value::String("-6.54".to_string())).unwrap() - (-6.54)).abs() < 0.001);
|
||||
// Positive
|
||||
assert!((parse_gain_value(&Value::String("+3.21 dB".to_string())).unwrap() - 3.21).abs() < 0.001);
|
||||
// Float value
|
||||
assert!((parse_gain_value(&Value::Float(-6.54)).unwrap() - (-6.54)).abs() < 0.001);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_parse_peak_value() {
|
||||
assert!((parse_peak_value(&Value::String("0.988553".to_string())).unwrap() - 0.988553).abs() < 0.0001);
|
||||
assert!((parse_peak_value(&Value::Float(0.95)).unwrap() - 0.95).abs() < 0.001);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,231 @@
|
||||
//! Background loudness analyzer thread.
|
||||
//!
|
||||
//! Long-lived thread that receives decoded audio samples from `AnalyzerTap`,
|
||||
//! computes EBU R128 integrated LUFS, and updates a shared `Arc<AtomicU32>`
|
||||
//! gain value that `DynamicAmplify` reads.
|
||||
//!
|
||||
//! - First measurement after ~10s of audio (EBU R128 needs sufficient data)
|
||||
//! - Refinement every ~5s thereafter (gain converges by ~30-60s)
|
||||
//! - Cached results are used immediately on cache hit
|
||||
|
||||
use std::sync::atomic::{AtomicU32, Ordering};
|
||||
use std::sync::mpsc::Receiver;
|
||||
use std::sync::Arc;
|
||||
use std::thread;
|
||||
|
||||
use ebur128::{EbuR128, Mode};
|
||||
|
||||
use super::analyzer_tap::AnalyzerMessage;
|
||||
use super::loudness_cache::LoudnessCache;
|
||||
use super::loudness::db_to_linear;
|
||||
|
||||
/// Maximum gain boost in dB (conservative clipping prevention)
|
||||
const MAX_GAIN_DB: f32 = 6.0;
|
||||
|
||||
|
||||
pub struct LoudnessAnalyzer;
|
||||
|
||||
impl LoudnessAnalyzer {
|
||||
/// Spawn the analyzer thread. Returns the join handle.
|
||||
///
|
||||
/// The thread blocks on `rx.recv()` when idle — zero CPU usage between tracks.
|
||||
pub fn spawn(
|
||||
rx: Receiver<AnalyzerMessage>,
|
||||
cache: Arc<LoudnessCache>,
|
||||
) -> thread::JoinHandle<()> {
|
||||
thread::Builder::new()
|
||||
.name("loudness-analyzer".into())
|
||||
.spawn(move || {
|
||||
log::info!("[LoudnessAnalyzer] Thread started");
|
||||
Self::run(rx, cache);
|
||||
log::info!("[LoudnessAnalyzer] Thread exiting");
|
||||
})
|
||||
.expect("Failed to spawn loudness analyzer thread")
|
||||
}
|
||||
|
||||
fn run(rx: Receiver<AnalyzerMessage>, cache: Arc<LoudnessCache>) {
|
||||
let mut state: Option<AnalyzerState> = None;
|
||||
|
||||
loop {
|
||||
let msg = match rx.recv() {
|
||||
Ok(msg) => msg,
|
||||
Err(_) => {
|
||||
log::info!("[LoudnessAnalyzer] Channel closed, shutting down");
|
||||
break;
|
||||
}
|
||||
};
|
||||
|
||||
match msg {
|
||||
AnalyzerMessage::NewTrack { track_id, sample_rate, channels, target_lufs, gain_atomic } => {
|
||||
log::info!(
|
||||
"[LoudnessAnalyzer] New track {} ({}Hz, {}ch, target {:.1} LUFS)",
|
||||
track_id, sample_rate, channels, target_lufs
|
||||
);
|
||||
|
||||
// Check cache first
|
||||
if let Some(cached) = cache.get(track_id) {
|
||||
let gain = compute_gain_capped(cached.gain_db);
|
||||
log::info!(
|
||||
"[LoudnessAnalyzer] Cache hit for track {}: {:.2} dB (source: {}), gain {:.4}",
|
||||
track_id, cached.gain_db, cached.source, gain
|
||||
);
|
||||
|
||||
// Set gain immediately via the atomic
|
||||
gain_atomic.store(gain.to_bits(), Ordering::Relaxed);
|
||||
|
||||
// Create state marked as cached — still accept samples for refinement
|
||||
let mut s = AnalyzerState::new(track_id, sample_rate, channels, target_lufs);
|
||||
s.gain_atomic = Some(gain_atomic);
|
||||
s.initial_done = true;
|
||||
state = Some(s);
|
||||
continue;
|
||||
}
|
||||
|
||||
// No cache — start fresh analysis
|
||||
let mut s = AnalyzerState::new(track_id, sample_rate, channels, target_lufs);
|
||||
s.gain_atomic = Some(gain_atomic);
|
||||
state = Some(s);
|
||||
}
|
||||
AnalyzerMessage::Samples(samples) => {
|
||||
if let Some(ref mut s) = state {
|
||||
s.feed_samples(&samples, &cache);
|
||||
}
|
||||
}
|
||||
AnalyzerMessage::Reset => {
|
||||
if let Some(ref mut s) = state {
|
||||
log::info!("[LoudnessAnalyzer] Reset (seek) — keeping current gain");
|
||||
s.reset_analyzer();
|
||||
}
|
||||
}
|
||||
AnalyzerMessage::Shutdown => {
|
||||
log::info!("[LoudnessAnalyzer] Shutdown requested");
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct AnalyzerState {
|
||||
track_id: u64,
|
||||
target_lufs: f32,
|
||||
ebur128: EbuR128,
|
||||
channels: u16,
|
||||
sample_rate: u32,
|
||||
/// Shared gain atomic — written by us, read by DynamicAmplify
|
||||
gain_atomic: Option<Arc<AtomicU32>>,
|
||||
/// Total samples fed since last reset
|
||||
samples_fed: u64,
|
||||
/// Total samples fed at last measurement
|
||||
samples_at_last_measure: u64,
|
||||
/// Whether initial measurement has been done
|
||||
initial_done: bool,
|
||||
/// Dynamic thresholds based on actual sample rate and channels
|
||||
initial_threshold: u64,
|
||||
refinement_interval: u64,
|
||||
}
|
||||
|
||||
impl AnalyzerState {
|
||||
fn new(track_id: u64, sample_rate: u32, channels: u16, target_lufs: f32) -> Self {
|
||||
let ebur128 = EbuR128::new(channels as u32, sample_rate, Mode::I)
|
||||
.expect("Failed to create EbuR128 instance");
|
||||
|
||||
// Scale thresholds to actual sample rate and channel count
|
||||
let samples_per_second = sample_rate as u64 * channels as u64;
|
||||
let initial_threshold = samples_per_second * 10; // 10 seconds
|
||||
let refinement_interval = samples_per_second * 5; // 5 seconds
|
||||
|
||||
Self {
|
||||
track_id,
|
||||
target_lufs,
|
||||
ebur128,
|
||||
channels,
|
||||
sample_rate,
|
||||
gain_atomic: None,
|
||||
samples_fed: 0,
|
||||
samples_at_last_measure: 0,
|
||||
initial_done: false,
|
||||
initial_threshold,
|
||||
refinement_interval,
|
||||
}
|
||||
}
|
||||
|
||||
/// Reset the EBU R128 analyzer (e.g., after seek) but keep the gain atomic.
|
||||
fn reset_analyzer(&mut self) {
|
||||
self.ebur128 = EbuR128::new(self.channels as u32, self.sample_rate, Mode::I)
|
||||
.expect("Failed to create EbuR128 instance");
|
||||
self.samples_fed = 0;
|
||||
self.samples_at_last_measure = 0;
|
||||
self.initial_done = false;
|
||||
}
|
||||
|
||||
/// Feed samples to the EBU R128 analyzer and possibly update gain.
|
||||
fn feed_samples(&mut self, samples: &[f32], cache: &LoudnessCache) {
|
||||
// Feed interleaved samples as frames
|
||||
let frame_count = samples.len() / self.channels as usize;
|
||||
if frame_count == 0 {
|
||||
return;
|
||||
}
|
||||
|
||||
if let Err(e) = self.ebur128.add_frames_f32(samples) {
|
||||
log::warn!("[LoudnessAnalyzer] Error feeding samples: {}", e);
|
||||
return;
|
||||
}
|
||||
|
||||
self.samples_fed += samples.len() as u64;
|
||||
|
||||
// Check if it's time to measure
|
||||
let should_measure = if !self.initial_done {
|
||||
self.samples_fed >= self.initial_threshold
|
||||
} else {
|
||||
self.samples_fed - self.samples_at_last_measure >= self.refinement_interval
|
||||
};
|
||||
|
||||
if should_measure {
|
||||
self.measure_and_update(cache);
|
||||
}
|
||||
}
|
||||
|
||||
fn measure_and_update(&mut self, cache: &LoudnessCache) {
|
||||
let loudness = match self.ebur128.loudness_global() {
|
||||
Ok(l) => l,
|
||||
Err(e) => {
|
||||
log::warn!("[LoudnessAnalyzer] Failed to get loudness: {}", e);
|
||||
return;
|
||||
}
|
||||
};
|
||||
|
||||
// -inf means silence — don't adjust
|
||||
if loudness.is_infinite() || loudness.is_nan() {
|
||||
log::debug!("[LoudnessAnalyzer] Track {}: loudness is {:?}, skipping", self.track_id, loudness);
|
||||
return;
|
||||
}
|
||||
|
||||
let measured_lufs = loudness as f32;
|
||||
let adjustment_db = self.target_lufs - measured_lufs;
|
||||
let gain = compute_gain_capped(adjustment_db);
|
||||
|
||||
let phase = if self.initial_done { "refine" } else { "initial" };
|
||||
log::info!(
|
||||
"[LoudnessAnalyzer] Track {} ({}): measured {:.1} LUFS, target {:.1}, adjustment {:.2} dB, gain {:.4}",
|
||||
self.track_id, phase, measured_lufs, self.target_lufs, adjustment_db, gain
|
||||
);
|
||||
|
||||
// Update shared atomic
|
||||
if let Some(ref atomic) = self.gain_atomic {
|
||||
atomic.store(gain.to_bits(), Ordering::Relaxed);
|
||||
}
|
||||
|
||||
self.samples_at_last_measure = self.samples_fed;
|
||||
self.initial_done = true;
|
||||
|
||||
// Cache the result (store the adjustment in dB, not the linear gain)
|
||||
cache.set(self.track_id, adjustment_db, 0.0, "ebur128");
|
||||
}
|
||||
}
|
||||
|
||||
/// Convert a dB adjustment to a capped linear gain factor.
|
||||
fn compute_gain_capped(adjustment_db: f32) -> f32 {
|
||||
let capped_db = adjustment_db.min(MAX_GAIN_DB);
|
||||
db_to_linear(capped_db)
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
//! Loudness cache — persists EBU R128 measurements in SQLite.
|
||||
//!
|
||||
//! Follows the `AudioSettingsStore` pattern: database lives in
|
||||
//! `dirs::data_dir()/qbz/loudness_cache.db`.
|
||||
//!
|
||||
//! Thread-safe via `Mutex<Connection>`.
|
||||
|
||||
use rusqlite::{params, Connection};
|
||||
use std::sync::Mutex;
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct CachedLoudness {
|
||||
pub gain_db: f32,
|
||||
pub peak: f32,
|
||||
/// Source of the measurement: "ebur128" or "replaygain"
|
||||
pub source: String,
|
||||
}
|
||||
|
||||
pub struct LoudnessCache {
|
||||
conn: Mutex<Connection>,
|
||||
}
|
||||
|
||||
impl LoudnessCache {
|
||||
pub fn new() -> Result<Self, String> {
|
||||
let data_dir = dirs::data_dir()
|
||||
.ok_or_else(|| "Could not determine data directory".to_string())?
|
||||
.join("qbz");
|
||||
|
||||
std::fs::create_dir_all(&data_dir)
|
||||
.map_err(|e| format!("Failed to create data directory: {}", e))?;
|
||||
|
||||
let db_path = data_dir.join("loudness_cache.db");
|
||||
let conn = Connection::open(&db_path)
|
||||
.map_err(|e| format!("Failed to open loudness cache database: {}", e))?;
|
||||
|
||||
conn.execute_batch("PRAGMA journal_mode=WAL; PRAGMA synchronous=NORMAL;")
|
||||
.map_err(|e| format!("Failed to enable WAL for loudness cache database: {}", e))?;
|
||||
|
||||
conn.execute_batch(
|
||||
"CREATE TABLE IF NOT EXISTS track_loudness (
|
||||
track_id INTEGER PRIMARY KEY,
|
||||
gain_db REAL NOT NULL,
|
||||
peak REAL NOT NULL DEFAULT 0.0,
|
||||
source TEXT NOT NULL DEFAULT 'ebur128',
|
||||
created_at INTEGER NOT NULL DEFAULT (strftime('%s', 'now'))
|
||||
)",
|
||||
)
|
||||
.map_err(|e| format!("Failed to create loudness table: {}", e))?;
|
||||
|
||||
log::info!("[LoudnessCache] Opened at {}", db_path.display());
|
||||
|
||||
Ok(Self {
|
||||
conn: Mutex::new(conn),
|
||||
})
|
||||
}
|
||||
|
||||
/// Look up cached loudness for a track.
|
||||
pub fn get(&self, track_id: u64) -> Option<CachedLoudness> {
|
||||
let conn = self.conn.lock().ok()?;
|
||||
conn.query_row(
|
||||
"SELECT gain_db, peak, source FROM track_loudness WHERE track_id = ?1",
|
||||
params![track_id as i64],
|
||||
|row| {
|
||||
Ok(CachedLoudness {
|
||||
gain_db: row.get::<_, f64>(0)? as f32,
|
||||
peak: row.get::<_, f64>(1)? as f32,
|
||||
source: row.get(2)?,
|
||||
})
|
||||
},
|
||||
)
|
||||
.ok()
|
||||
}
|
||||
|
||||
/// Store or update loudness data for a track.
|
||||
pub fn set(&self, track_id: u64, gain_db: f32, peak: f32, source: &str) {
|
||||
if let Ok(conn) = self.conn.lock() {
|
||||
let result = conn.execute(
|
||||
"INSERT OR REPLACE INTO track_loudness (track_id, gain_db, peak, source, created_at)
|
||||
VALUES (?1, ?2, ?3, ?4, strftime('%s', 'now'))",
|
||||
params![track_id as i64, gain_db as f64, peak as f64, source],
|
||||
);
|
||||
if let Err(e) = result {
|
||||
log::warn!(
|
||||
"[LoudnessCache] Failed to store loudness for track {}: {}",
|
||||
track_id,
|
||||
e
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,302 @@
|
||||
//! PipeWire audio backend
|
||||
//!
|
||||
//! Uses PipeWire/PulseAudio for audio output with device selection.
|
||||
//! - Enumerates devices using pactl (pretty names)
|
||||
//! - Sets PULSE_SINK environment variable for device routing
|
||||
//! - Creates stream using CPAL "pulse" or "pipewire" device
|
||||
//! - Does NOT change system default (only affects QBZ)
|
||||
|
||||
use super::backend::{AudioBackend, AudioBackendType, AudioDevice, BackendConfig, BackendResult};
|
||||
use rodio::{
|
||||
cpal::{
|
||||
traits::{DeviceTrait, HostTrait},
|
||||
BufferSize, SampleFormat, SampleRate, StreamConfig, SupportedBufferSize, SupportedStreamConfig,
|
||||
},
|
||||
OutputStream, OutputStreamHandle,
|
||||
};
|
||||
use std::process::Command;
|
||||
|
||||
pub struct PipeWireBackend {
|
||||
#[allow(dead_code)]
|
||||
host: rodio::cpal::Host,
|
||||
}
|
||||
|
||||
impl PipeWireBackend {
|
||||
pub fn new() -> BackendResult<Self> {
|
||||
Ok(Self {
|
||||
host: rodio::cpal::default_host(),
|
||||
})
|
||||
}
|
||||
|
||||
/// Parse pactl output to get device list with pretty names
|
||||
fn enumerate_pipewire_sinks(&self) -> BackendResult<Vec<AudioDevice>> {
|
||||
// Get default sink
|
||||
let default_sink = Command::new("pactl")
|
||||
.args(["get-default-sink"])
|
||||
.output()
|
||||
.ok()
|
||||
.and_then(|o| {
|
||||
if o.status.success() {
|
||||
String::from_utf8(o.stdout).ok().map(|s| s.trim().to_string())
|
||||
} else {
|
||||
None
|
||||
}
|
||||
});
|
||||
|
||||
// Get all sinks with details
|
||||
let output = Command::new("pactl")
|
||||
.args(["list", "sinks"])
|
||||
.output()
|
||||
.map_err(|e| format!("Failed to run pactl: {}", e))?;
|
||||
|
||||
if !output.status.success() {
|
||||
return Err("pactl command failed".to_string());
|
||||
}
|
||||
|
||||
let stdout = String::from_utf8_lossy(&output.stdout);
|
||||
let mut devices = Vec::new();
|
||||
|
||||
// Parse pactl output
|
||||
let mut current_name: Option<String> = None;
|
||||
let mut current_description: Option<String> = None;
|
||||
let mut current_max_rate: Option<u32> = None;
|
||||
let mut current_is_hardware: bool = false;
|
||||
let mut current_device_bus: Option<String> = None;
|
||||
|
||||
for line in stdout.lines() {
|
||||
let line = line.trim();
|
||||
|
||||
if line.starts_with("Sink #") {
|
||||
// Save previous device if complete
|
||||
if let (Some(id), Some(name)) = (current_name.take(), current_description.take()) {
|
||||
let is_default = default_sink.as_ref().map(|d| d == &id).unwrap_or(false);
|
||||
devices.push(AudioDevice {
|
||||
id: id.clone(),
|
||||
name,
|
||||
description: None,
|
||||
is_default,
|
||||
max_sample_rate: current_max_rate.take(),
|
||||
supported_sample_rates: None, // PipeWire handles sample rate conversion
|
||||
device_bus: current_device_bus.take(),
|
||||
is_hardware: current_is_hardware,
|
||||
});
|
||||
}
|
||||
current_max_rate = None;
|
||||
current_is_hardware = false;
|
||||
current_device_bus = None;
|
||||
} else if line.starts_with("Name:") {
|
||||
current_name = Some(line.trim_start_matches("Name:").trim().to_string());
|
||||
} else if line.starts_with("Description:") {
|
||||
current_description = Some(line.trim_start_matches("Description:").trim().to_string());
|
||||
} else if line.starts_with("Flags:") {
|
||||
// Check for HARDWARE flag
|
||||
current_is_hardware = line.contains("HARDWARE");
|
||||
} else if line.contains("Sample Specification:") {
|
||||
// Try to parse sample rate from lines like "Sample Specification: s32le 2ch 192000Hz"
|
||||
if let Some(hz_pos) = line.find("Hz") {
|
||||
let before_hz = &line[..hz_pos];
|
||||
if let Some(last_space) = before_hz.rfind(' ') {
|
||||
if let Ok(rate) = before_hz[last_space + 1..].parse::<u32>() {
|
||||
current_max_rate = Some(rate);
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if line.starts_with("device.bus = ") {
|
||||
// Parse device.bus property (e.g., "usb", "pci", "bluetooth")
|
||||
let bus = line.trim_start_matches("device.bus = ").trim_matches('"').to_string();
|
||||
current_device_bus = Some(bus);
|
||||
}
|
||||
}
|
||||
|
||||
// Don't forget the last device
|
||||
if let (Some(id), Some(name)) = (current_name, current_description) {
|
||||
let is_default = default_sink.as_ref().map(|d| d == &id).unwrap_or(false);
|
||||
devices.push(AudioDevice {
|
||||
id,
|
||||
name,
|
||||
description: None,
|
||||
is_default,
|
||||
max_sample_rate: current_max_rate,
|
||||
supported_sample_rates: None, // PipeWire handles sample rate conversion
|
||||
device_bus: current_device_bus,
|
||||
is_hardware: current_is_hardware,
|
||||
});
|
||||
}
|
||||
|
||||
log::info!("[PipeWire Backend] Enumerated {} devices via pactl", devices.len());
|
||||
for (idx, dev) in devices.iter().enumerate() {
|
||||
log::info!(" [{}] {} (id: {}, bus: {:?}, hw: {})",
|
||||
idx, dev.name, dev.id, dev.device_bus, dev.is_hardware);
|
||||
}
|
||||
|
||||
Ok(devices)
|
||||
}
|
||||
}
|
||||
|
||||
impl AudioBackend for PipeWireBackend {
|
||||
fn backend_type(&self) -> AudioBackendType {
|
||||
AudioBackendType::PipeWire
|
||||
}
|
||||
|
||||
fn enumerate_devices(&self) -> BackendResult<Vec<AudioDevice>> {
|
||||
self.enumerate_pipewire_sinks()
|
||||
}
|
||||
|
||||
fn create_output_stream(
|
||||
&self,
|
||||
config: &BackendConfig,
|
||||
) -> BackendResult<(OutputStream, OutputStreamHandle)> {
|
||||
let target_sink = config.device_id.clone();
|
||||
|
||||
// Temporarily set default sink to target (if specified)
|
||||
// We DON'T restore it - let the user's system keep the selected device as default
|
||||
// This is actually the expected behavior: when you select a device, it becomes the default
|
||||
if let Some(sink_name) = &target_sink {
|
||||
log::info!("[PipeWire Backend] Setting default sink to: {}", sink_name);
|
||||
|
||||
let set_result = Command::new("pactl")
|
||||
.args(["set-default-sink", sink_name])
|
||||
.output();
|
||||
|
||||
match set_result {
|
||||
Ok(output) if output.status.success() => {
|
||||
log::info!("[PipeWire Backend] Default sink set to {}", sink_name);
|
||||
}
|
||||
Ok(output) => {
|
||||
let stderr = String::from_utf8_lossy(&output.stderr);
|
||||
log::warn!("[PipeWire Backend] Failed to set default sink: {}", stderr);
|
||||
}
|
||||
Err(e) => {
|
||||
log::warn!("[PipeWire Backend] Error executing pactl set-default-sink: {}", e);
|
||||
}
|
||||
}
|
||||
|
||||
// Wait for PipeWire to process the default sink change
|
||||
std::thread::sleep(std::time::Duration::from_millis(200));
|
||||
}
|
||||
|
||||
// Force PipeWire to use the requested sample rate (for bit-perfect playback)
|
||||
log::info!("[PipeWire Backend] Forcing sample rate to {}Hz via pw-metadata", config.sample_rate);
|
||||
let metadata_result = Command::new("pw-metadata")
|
||||
.args(["-n", "settings", "0", "clock.force-rate", &config.sample_rate.to_string()])
|
||||
.output();
|
||||
|
||||
match metadata_result {
|
||||
Ok(output) if output.status.success() => {
|
||||
log::info!("[PipeWire Backend] Sample rate forced to {}Hz", config.sample_rate);
|
||||
}
|
||||
Ok(output) => {
|
||||
let stderr = String::from_utf8_lossy(&output.stderr);
|
||||
log::warn!("[PipeWire Backend] Failed to force sample rate: {}", stderr);
|
||||
}
|
||||
Err(e) => {
|
||||
log::warn!("[PipeWire Backend] Error executing pw-metadata: {}", e);
|
||||
}
|
||||
}
|
||||
|
||||
// Wait for PipeWire to apply the sample rate change
|
||||
std::thread::sleep(std::time::Duration::from_millis(300));
|
||||
|
||||
// Create a NEW host (will use current default sink)
|
||||
log::info!("[PipeWire Backend] Creating fresh CPAL host...");
|
||||
let fresh_host = rodio::cpal::default_host();
|
||||
|
||||
// Find the "pulse" or "pipewire" CPAL device
|
||||
let device = fresh_host
|
||||
.output_devices()
|
||||
.map_err(|e| format!("Failed to enumerate CPAL devices: {}", e))?
|
||||
.find(|d| {
|
||||
d.name()
|
||||
.ok()
|
||||
.map(|n| n == "pulse" || n == "pipewire")
|
||||
.unwrap_or(false)
|
||||
})
|
||||
.ok_or_else(|| {
|
||||
"Could not find 'pulse' or 'pipewire' CPAL device. Is PulseAudio/PipeWire running?".to_string()
|
||||
})?;
|
||||
|
||||
let device_name = device.name().unwrap_or_else(|_| "unknown".to_string());
|
||||
log::info!("[PipeWire Backend] Using CPAL device: {}", device_name);
|
||||
|
||||
// Create output stream with custom sample rate configuration
|
||||
log::info!(
|
||||
"[PipeWire Backend] Creating stream: {}Hz, {} channels, exclusive: {}",
|
||||
config.sample_rate,
|
||||
config.channels,
|
||||
config.exclusive_mode
|
||||
);
|
||||
|
||||
// Create StreamConfig with desired sample rate
|
||||
let stream_config = StreamConfig {
|
||||
channels: config.channels,
|
||||
sample_rate: SampleRate(config.sample_rate),
|
||||
buffer_size: if config.exclusive_mode {
|
||||
BufferSize::Fixed(512) // Lower latency for exclusive mode
|
||||
} else {
|
||||
BufferSize::Default
|
||||
},
|
||||
};
|
||||
|
||||
// Check if device supports this configuration
|
||||
let supported_configs = device
|
||||
.supported_output_configs()
|
||||
.map_err(|e| format!("Failed to get supported configs: {}", e))?;
|
||||
|
||||
let mut found_matching = false;
|
||||
for range in supported_configs {
|
||||
if range.channels() == config.channels
|
||||
&& config.sample_rate >= range.min_sample_rate().0
|
||||
&& config.sample_rate <= range.max_sample_rate().0
|
||||
{
|
||||
found_matching = true;
|
||||
log::info!(
|
||||
"[PipeWire Backend] Device supports {}Hz (range: {}-{}Hz)",
|
||||
config.sample_rate,
|
||||
range.min_sample_rate().0,
|
||||
range.max_sample_rate().0
|
||||
);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if !found_matching {
|
||||
log::warn!(
|
||||
"[PipeWire Backend] Device may not support {}Hz, attempting anyway",
|
||||
config.sample_rate
|
||||
);
|
||||
}
|
||||
|
||||
// Create SupportedStreamConfig
|
||||
let supported_config = SupportedStreamConfig::new(
|
||||
stream_config.channels,
|
||||
stream_config.sample_rate,
|
||||
SupportedBufferSize::Range { min: 64, max: 8192 },
|
||||
SampleFormat::F32,
|
||||
);
|
||||
|
||||
// Create OutputStream with custom config
|
||||
let stream = OutputStream::try_from_device_config(&device, supported_config)
|
||||
.map_err(|e| format!("Failed to create output stream at {}Hz: {}", config.sample_rate, e))?;
|
||||
|
||||
log::info!("[PipeWire Backend] Output stream created successfully at {}Hz", config.sample_rate);
|
||||
|
||||
Ok(stream)
|
||||
}
|
||||
|
||||
fn is_available(&self) -> bool {
|
||||
// Check if pactl is available (PipeWire/PulseAudio)
|
||||
Command::new("pactl")
|
||||
.arg("info")
|
||||
.output()
|
||||
.map(|o| o.status.success())
|
||||
.unwrap_or(false)
|
||||
}
|
||||
|
||||
fn description(&self) -> &'static str {
|
||||
"PipeWire (Recommended) - Modern audio server with device sharing"
|
||||
}
|
||||
|
||||
fn as_any(&self) -> &dyn std::any::Any {
|
||||
self
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
//! PulseAudio backend (legacy compatibility)
|
||||
//!
|
||||
//! Similar to PipeWire backend but for systems running PulseAudio only.
|
||||
//! Uses same approach: pactl + PULSE_SINK + CPAL "pulse" device.
|
||||
|
||||
use super::backend::{AudioBackend, AudioBackendType, AudioDevice, BackendConfig, BackendResult};
|
||||
use super::pipewire_backend::PipeWireBackend;
|
||||
use rodio::{OutputStream, OutputStreamHandle};
|
||||
|
||||
pub struct PulseBackend {
|
||||
// Reuse PipeWire backend implementation (they're compatible)
|
||||
inner: PipeWireBackend,
|
||||
}
|
||||
|
||||
impl PulseBackend {
|
||||
pub fn new() -> BackendResult<Self> {
|
||||
Ok(Self {
|
||||
inner: PipeWireBackend::new()?,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl AudioBackend for PulseBackend {
|
||||
fn backend_type(&self) -> AudioBackendType {
|
||||
AudioBackendType::Pulse
|
||||
}
|
||||
|
||||
fn enumerate_devices(&self) -> BackendResult<Vec<AudioDevice>> {
|
||||
// Delegate to PipeWire backend (pactl works for both)
|
||||
self.inner.enumerate_devices()
|
||||
}
|
||||
|
||||
fn create_output_stream(
|
||||
&self,
|
||||
config: &BackendConfig,
|
||||
) -> BackendResult<(OutputStream, OutputStreamHandle)> {
|
||||
// Delegate to PipeWire backend (same mechanism)
|
||||
self.inner.create_output_stream(config)
|
||||
}
|
||||
|
||||
fn is_available(&self) -> bool {
|
||||
// Check if PulseAudio is running
|
||||
std::process::Command::new("pactl")
|
||||
.arg("info")
|
||||
.output()
|
||||
.map(|o| o.status.success())
|
||||
.unwrap_or(false)
|
||||
}
|
||||
|
||||
fn description(&self) -> &'static str {
|
||||
"PulseAudio (Legacy) - Older audio server, compatible fallback"
|
||||
}
|
||||
|
||||
fn as_any(&self) -> &dyn std::any::Any {
|
||||
self
|
||||
}
|
||||
}
|
||||
@@ -145,7 +145,8 @@ pub enum CoreEvent {
|
||||
|
||||
/// Audio backend changed
|
||||
AudioBackendChanged {
|
||||
backend: crate::playback::AudioBackendType,
|
||||
/// Backend name: "pipewire", "alsa", "pulse"
|
||||
backend: String,
|
||||
},
|
||||
|
||||
/// Audio system diagnostic info
|
||||
|
||||
@@ -38,10 +38,7 @@ pub mod types;
|
||||
// Re-export commonly used types at crate root
|
||||
pub use error::{QbzError, QbzResult};
|
||||
pub use events::CoreEvent;
|
||||
pub use playback::{
|
||||
AudioBackendType, AudioDevice, PlaybackState, PlaybackStatus, QueueState, QueueTrack,
|
||||
RepeatMode,
|
||||
};
|
||||
pub use playback::{PlaybackState, PlaybackStatus, QueueState, QueueTrack, RepeatMode};
|
||||
pub use traits::{FrontendAdapter, LoggingAdapter, NoOpAdapter};
|
||||
pub use types::{
|
||||
Album, AlbumSummary, Artist, ArtistAlbums, ArtistBiography, Favorites, Genre, GenreInfo,
|
||||
|
||||
@@ -117,27 +117,5 @@ impl Default for PlaybackStatus {
|
||||
}
|
||||
}
|
||||
|
||||
// ============ Audio Backend Types ============
|
||||
|
||||
/// Audio backend type selection
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub enum AudioBackendType {
|
||||
/// PipeWire/PulseAudio via CPAL (default, most compatible)
|
||||
PipeWire,
|
||||
/// Direct ALSA for bit-perfect playback
|
||||
AlsaDirect,
|
||||
}
|
||||
|
||||
impl Default for AudioBackendType {
|
||||
fn default() -> Self {
|
||||
Self::PipeWire
|
||||
}
|
||||
}
|
||||
|
||||
/// Audio device information
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct AudioDevice {
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
pub is_default: bool,
|
||||
}
|
||||
// Note: Audio backend types (AudioBackendType, AudioDevice, etc.) are defined
|
||||
// in qbz-audio crate to keep the audio module self-contained and immutable.
|
||||
Reference in new issue
Block a user