feat(audio): add PipeWire force bit-perfect mode

Add experimental toggle to force PipeWire clock.force-quantum alongside
clock.force-rate for true bit-perfect playback. Quantum is matched to
sample rate (1024 for <=48kHz, 2048 for <=96kHz, etc). Both values
reset to 0 on stop and pause-suspend to avoid affecting other apps.

Requires DAC Passthrough to be enabled, PipeWire backend only.
This commit is contained in:
vicrodh committed 2026-02-19 18:01:42 -06:00
1 parent 98ffd3dff2
commit cbc2ff0b26
13 files changed
+181 -5

No files matched your search

+3
View File
@@ -112,6 +112,9 @@ pub struct BackendConfig {
/// Exclusive mode flag
pub exclusive_mode: bool,
/// When true, force PipeWire clock.force-quantum for bit-perfect playback
pub pw_force_bitperfect: bool,
}
/// Result type for backend operations
+45
View File
@@ -21,6 +21,17 @@ pub struct PipeWireBackend {
host: rodio::cpal::Host,
}
/// Calculate the optimal PipeWire quantum for a given sample rate.
/// Returns a power-of-2 value matching common audio interface expectations.
fn quantum_for_sample_rate(sample_rate: u32) -> u32 {
match sample_rate {
r if r <= 48000 => 1024,
r if r <= 96000 => 2048,
r if r <= 192000 => 4096,
_ => 8192,
}
}
impl PipeWireBackend {
pub fn new() -> BackendResult<Self> {
Ok(Self {
@@ -28,6 +39,18 @@ impl PipeWireBackend {
})
}
/// Reset PipeWire clock.force-rate and clock.force-quantum to 0.
/// Call this when playback stops so other apps aren't stuck at a forced rate.
pub fn reset_pipewire_clock() {
log::info!("[PipeWire Backend] Resetting clock.force-rate and clock.force-quantum to 0");
let _ = Command::new("pw-metadata")
.args(["-n", "settings", "0", "clock.force-rate", "0"])
.output();
let _ = Command::new("pw-metadata")
.args(["-n", "settings", "0", "clock.force-quantum", "0"])
.output();
}
/// Parse pactl output to get device list with pretty names
fn enumerate_pipewire_sinks(&self) -> BackendResult<Vec<AudioDevice>> {
// Get default sink
@@ -194,6 +217,28 @@ impl AudioBackend for PipeWireBackend {
}
}
// Force quantum if bit-perfect mode is enabled
if config.pw_force_bitperfect {
let quantum = quantum_for_sample_rate(config.sample_rate);
log::info!("[PipeWire Backend] Forcing quantum to {} via pw-metadata (bit-perfect)", quantum);
let quantum_result = Command::new("pw-metadata")
.args(["-n", "settings", "0", "clock.force-quantum", &quantum.to_string()])
.output();
match quantum_result {
Ok(output) if output.status.success() => {
log::info!("[PipeWire Backend] Quantum forced to {}", quantum);
}
Ok(output) => {
let stderr = String::from_utf8_lossy(&output.stderr);
log::warn!("[PipeWire Backend] Failed to force quantum: {}", stderr);
}
Err(e) => {
log::warn!("[PipeWire Backend] Error executing pw-metadata for quantum: {}", e);
}
}
}
// Wait for PipeWire to apply the sample rate change
std::thread::sleep(std::time::Duration::from_millis(300));
+23 -2
View File
@@ -47,6 +47,9 @@ pub struct AudioSettings {
/// When true, tracks with the same format are cross-faded seamlessly via Rodio Sink queueing.
/// Only works with cached tracks on Rodio backend (not ALSA Direct or streaming).
pub gapless_enabled: bool,
/// When true, force PipeWire clock.force-quantum alongside clock.force-rate for bit-perfect.
/// Reset both to 0 on stop. PipeWire-only, requires dac_passthrough.
pub pw_force_bitperfect: bool,
}
impl Default for AudioSettings {
@@ -68,6 +71,7 @@ impl Default for AudioSettings {
normalization_enabled: false, // Off by default — preserves bit-perfect pipeline
normalization_target_lufs: -14.0, // Spotify/YouTube standard
gapless_enabled: false, // Off by default — user opts in
pw_force_bitperfect: false, // Off by default — experimental PipeWire feature
}
}
}
@@ -152,6 +156,10 @@ impl AudioSettingsStore {
"ALTER TABLE audio_settings ADD COLUMN device_sample_rate_limits TEXT",
[],
);
let _ = conn.execute(
"ALTER TABLE audio_settings ADD COLUMN pw_force_bitperfect INTEGER DEFAULT 0",
[],
);
Ok(Self { conn })
}
@@ -170,7 +178,7 @@ impl AudioSettingsStore {
pub fn get_settings(&self) -> Result<AudioSettings, String> {
self.conn
.query_row(
"SELECT output_device, exclusive_mode, dac_passthrough, preferred_sample_rate, backend_type, alsa_plugin, alsa_hardware_volume, stream_first_track, stream_buffer_seconds, streaming_only, limit_quality_to_device, device_max_sample_rate, normalization_enabled, normalization_target_lufs, gapless_enabled, device_sample_rate_limits FROM audio_settings WHERE id = 1",
"SELECT output_device, exclusive_mode, dac_passthrough, preferred_sample_rate, backend_type, alsa_plugin, alsa_hardware_volume, stream_first_track, stream_buffer_seconds, streaming_only, limit_quality_to_device, device_max_sample_rate, normalization_enabled, normalization_target_lufs, gapless_enabled, device_sample_rate_limits, pw_force_bitperfect FROM audio_settings WHERE id = 1",
[],
|row| {
// Parse backend_type from JSON string
@@ -206,6 +214,7 @@ impl AudioSettingsStore {
normalization_enabled: row.get::<_, Option<i64>>(12)?.unwrap_or(0) != 0,
normalization_target_lufs: row.get::<_, Option<f64>>(13)?.unwrap_or(-14.0) as f32,
gapless_enabled: row.get::<_, Option<i64>>(14)?.unwrap_or(0) != 0,
pw_force_bitperfect: row.get::<_, Option<i64>>(16)?.unwrap_or(0) != 0,
})
},
)
@@ -422,6 +431,16 @@ impl AudioSettingsStore {
Ok(())
}
pub fn set_pw_force_bitperfect(&self, enabled: bool) -> Result<(), String> {
self.conn
.execute(
"UPDATE audio_settings SET pw_force_bitperfect = ?1 WHERE id = 1",
params![enabled as i64],
)
.map_err(|e| format!("Failed to set pw_force_bitperfect: {}", e))?;
Ok(())
}
pub fn set_normalization_target_lufs(&self, target: f32) -> Result<(), String> {
self.conn
.execute(
@@ -468,7 +487,8 @@ impl AudioSettingsStore {
normalization_enabled = ?13,
normalization_target_lufs = ?14,
gapless_enabled = ?15,
device_sample_rate_limits = ?16
device_sample_rate_limits = ?16,
pw_force_bitperfect = ?17
WHERE id = 1",
params![
defaults.output_device,
@@ -487,6 +507,7 @@ impl AudioSettingsStore {
defaults.normalization_target_lufs as f64,
defaults.gapless_enabled as i64,
limits_json,
defaults.pw_force_bitperfect as i64,
],
)
.map_err(|e| format!("Failed to reset audio settings: {}", e))?;
+9
View File
@@ -460,6 +460,7 @@ fn try_init_stream_with_backend(
channels,
exclusive_mode: audio_settings.exclusive_mode,
alsa_plugin: audio_settings.alsa_plugin,
pw_force_bitperfect: audio_settings.pw_force_bitperfect,
};
// For ALSA backend with hw: devices, try direct ALSA first (Linux only)
@@ -1720,6 +1721,10 @@ impl Player {
// Drop the stream to release the device and stop background CPU use.
drop(stream_opt.take());
*pause_suspend_deadline = None;
// Reset PipeWire clock if bit-perfect was active
if thread_settings.lock().ok().map(|s| s.pw_force_bitperfect).unwrap_or(false) {
qbz_audio::pipewire_backend::PipeWireBackend::reset_pipewire_clock();
}
log::info!("Audio thread: stopped");
}
AudioCommand::SetVolume(volume) => {
@@ -2088,6 +2093,10 @@ impl Player {
}
drop(stream_opt.take());
pause_suspend_deadline = None;
// Reset PipeWire clock if bit-perfect was active
if thread_settings.lock().ok().map(|s| s.pw_force_bitperfect).unwrap_or(false) {
qbz_audio::pipewire_backend::PipeWireBackend::reset_pipewire_clock();
}
log::info!("Audio thread: suspended stream after pause");
continue;
}
+16
View File
@@ -4966,6 +4966,7 @@ pub async fn v2_reinit_audio_device(
normalization_enabled: fresh_settings.normalization_enabled,
normalization_target_lufs: fresh_settings.normalization_target_lufs,
gapless_enabled: fresh_settings.gapless_enabled,
pw_force_bitperfect: fresh_settings.pw_force_bitperfect,
};
let _ = player.reload_settings(qbz_settings);
}
@@ -5235,6 +5236,21 @@ pub fn v2_set_audio_dac_passthrough(
store.set_dac_passthrough(enabled).map_err(RuntimeError::Internal)
}
/// Set PipeWire force bit-perfect mode (V2)
#[tauri::command]
pub fn v2_set_audio_pw_force_bitperfect(
enabled: bool,
state: State<'_, AudioSettingsState>,
) -> Result<(), RuntimeError> {
log::info!("[V2] set_audio_pw_force_bitperfect: {}", enabled);
let guard = state
.store
.lock()
.map_err(|e| RuntimeError::Internal(format!("Lock error: {}", e)))?;
let store = guard.as_ref().ok_or(RuntimeError::UserSessionNotActivated)?;
store.set_pw_force_bitperfect(enabled).map_err(RuntimeError::Internal)
}
/// Set preferred sample rate (V2)
#[tauri::command]
pub fn v2_set_audio_sample_rate(
+23 -2
View File
@@ -44,6 +44,9 @@ pub struct AudioSettings {
/// When true, tracks with the same format are cross-faded seamlessly via Rodio Sink queueing.
/// Only works with cached tracks on Rodio backend (not ALSA Direct or streaming).
pub gapless_enabled: bool,
/// When true, force PipeWire clock.force-quantum alongside clock.force-rate for bit-perfect.
/// Reset both to 0 on stop. PipeWire-only, requires dac_passthrough.
pub pw_force_bitperfect: bool,
}
impl Default for AudioSettings {
@@ -65,6 +68,7 @@ impl Default for AudioSettings {
normalization_enabled: false, // Off by default — preserves bit-perfect pipeline
normalization_target_lufs: -14.0, // Spotify/YouTube standard
gapless_enabled: false, // Off by default — user opts in
pw_force_bitperfect: false, // Off by default — experimental PipeWire feature
}
}
}
@@ -149,6 +153,10 @@ impl AudioSettingsStore {
"ALTER TABLE audio_settings ADD COLUMN device_sample_rate_limits TEXT",
[],
);
let _ = conn.execute(
"ALTER TABLE audio_settings ADD COLUMN pw_force_bitperfect INTEGER DEFAULT 0",
[],
);
Ok(Self { conn })
}
@@ -167,7 +175,7 @@ impl AudioSettingsStore {
pub fn get_settings(&self) -> Result<AudioSettings, String> {
self.conn
.query_row(
"SELECT output_device, exclusive_mode, dac_passthrough, preferred_sample_rate, backend_type, alsa_plugin, alsa_hardware_volume, stream_first_track, stream_buffer_seconds, streaming_only, limit_quality_to_device, device_max_sample_rate, normalization_enabled, normalization_target_lufs, gapless_enabled, device_sample_rate_limits FROM audio_settings WHERE id = 1",
"SELECT output_device, exclusive_mode, dac_passthrough, preferred_sample_rate, backend_type, alsa_plugin, alsa_hardware_volume, stream_first_track, stream_buffer_seconds, streaming_only, limit_quality_to_device, device_max_sample_rate, normalization_enabled, normalization_target_lufs, gapless_enabled, device_sample_rate_limits, pw_force_bitperfect FROM audio_settings WHERE id = 1",
[],
|row| {
// Parse backend_type from JSON string
@@ -203,6 +211,7 @@ impl AudioSettingsStore {
normalization_enabled: row.get::<_, Option<i64>>(12)?.unwrap_or(0) != 0,
normalization_target_lufs: row.get::<_, Option<f64>>(13)?.unwrap_or(-14.0) as f32,
gapless_enabled: row.get::<_, Option<i64>>(14)?.unwrap_or(0) != 0,
pw_force_bitperfect: row.get::<_, Option<i64>>(16)?.unwrap_or(0) != 0,
})
},
)
@@ -419,6 +428,16 @@ impl AudioSettingsStore {
Ok(())
}
pub fn set_pw_force_bitperfect(&self, enabled: bool) -> Result<(), String> {
self.conn
.execute(
"UPDATE audio_settings SET pw_force_bitperfect = ?1 WHERE id = 1",
params![enabled as i64],
)
.map_err(|e| format!("Failed to set pw_force_bitperfect: {}", e))?;
Ok(())
}
pub fn set_normalization_target_lufs(&self, target: f32) -> Result<(), String> {
self.conn
.execute(
@@ -465,7 +484,8 @@ impl AudioSettingsStore {
normalization_enabled = ?13,
normalization_target_lufs = ?14,
gapless_enabled = ?15,
device_sample_rate_limits = ?16
device_sample_rate_limits = ?16,
pw_force_bitperfect = ?17
WHERE id = 1",
params![
defaults.output_device,
@@ -484,6 +504,7 @@ impl AudioSettingsStore {
defaults.normalization_target_lufs as f64,
defaults.gapless_enabled as i64,
limits_json,
defaults.pw_force_bitperfect as i64,
],
)
.map_err(|e| format!("Failed to reset audio settings: {}", e))?;
+1
View File
@@ -946,6 +946,7 @@ pub fn run() {
commands_v2::v2_set_audio_output_device,
commands_v2::v2_set_audio_exclusive_mode,
commands_v2::v2_set_audio_dac_passthrough,
commands_v2::v2_set_audio_pw_force_bitperfect,
commands_v2::v2_set_audio_sample_rate,
commands_v2::v2_set_audio_backend_type,
commands_v2::v2_set_audio_alsa_plugin,
+1
View File
@@ -479,6 +479,7 @@ fn try_init_stream_with_backend(
channels,
exclusive_mode: audio_settings.exclusive_mode,
alsa_plugin: audio_settings.alsa_plugin,
pw_force_bitperfect: audio_settings.pw_force_bitperfect,
};
// For ALSA backend with hw: devices, try direct ALSA first (Linux only)
+48 -1
View File
@@ -553,6 +553,7 @@
let outputDevice = $state('System Default');
let exclusiveMode = $state(false);
let dacPassthrough = $state(false);
let pwForceBitperfect = $state(false);
let selectedBackend = $state<string>('Auto');
let selectedAlsaPlugin = $state<string>('hw (Direct Hardware)');
let alsaHardwareVolume = $state(false);
@@ -2023,6 +2024,7 @@
limit_quality_to_device: boolean;
device_max_sample_rate: number | null;
gapless_enabled: boolean;
pw_force_bitperfect: boolean;
}
interface BackendInfo {
@@ -2167,6 +2169,7 @@
}
exclusiveMode = settings.exclusive_mode;
dacPassthrough = settings.dac_passthrough;
pwForceBitperfect = settings.pw_force_bitperfect;
// Load backend and plugin settings
if (settings.backend_type) {
@@ -2285,6 +2288,13 @@
console.log('[Audio] Disabled gapless playback (not compatible with DAC Passthrough)');
}
// Disabling DAC Passthrough also disables PW force bit-perfect
if (!enabled && pwForceBitperfect) {
pwForceBitperfect = false;
await invoke('v2_set_audio_pw_force_bitperfect', { enabled: false });
console.log('[Audio] Disabled PW force bit-perfect (requires DAC Passthrough)');
}
try {
await invoke('v2_set_audio_dac_passthrough', { enabled });
@@ -2297,6 +2307,25 @@
}
}
async function handlePwForceBitperfectChange(enabled: boolean) {
pwForceBitperfect = enabled;
// Auto-enable DAC Passthrough when turning on bit-perfect
if (enabled && !dacPassthrough) {
await handleDacPassthroughChange(true);
}
try {
await invoke('v2_set_audio_pw_force_bitperfect', { enabled });
const deviceName = getCurrentDeviceSinkName();
await reinitAndResume(deviceName);
console.log('[Audio] PW force bit-perfect changed:', enabled);
} catch (err) {
console.error('[Audio] Failed to change PW force bit-perfect:', err);
}
}
async function handleBackendChange(backendName: string) {
selectedBackend = backendName;
@@ -2305,8 +2334,13 @@
const backendType = backendName === 'Auto' ? null : backend?.backend_type ?? null;
// Auto-disable incompatible features
// DAC Passthrough only works with PipeWire
// DAC Passthrough and PW force bit-perfect only work with PipeWire
if (backendName !== 'PipeWire') {
if (pwForceBitperfect) {
pwForceBitperfect = false;
await invoke('v2_set_audio_pw_force_bitperfect', { enabled: false });
console.log('[Audio] Disabled PW force bit-perfect (only compatible with PipeWire)');
}
if (dacPassthrough) {
dacPassthrough = false;
await invoke('v2_set_audio_dac_passthrough', { enabled: false });
@@ -2851,6 +2885,7 @@
outputDevice = 'System Default';
exclusiveMode = false;
dacPassthrough = false;
pwForceBitperfect = false;
selectedBackend = 'Auto';
selectedAlsaPlugin = 'hw (Direct Hardware)';
alsaHardwareVolume = false;
@@ -3311,6 +3346,18 @@
</div>
</div>
{/if}
{#if dacPassthrough && selectedBackend === 'PipeWire'}
<div class="setting-row">
<div class="setting-info">
<span class="setting-label">{$t('settings.audio.pwForceBitperfect')}</span>
<span class="setting-desc">{$t('settings.audio.pwForceBitperfectDesc')}</span>
</div>
<Toggle enabled={pwForceBitperfect} onchange={handlePwForceBitperfectChange} />
</div>
{#if pwForceBitperfect}
<small class="setting-note">{$t('settings.audio.pwForceBitperfectNote')}</small>
{/if}
{/if}
<div class="setting-row">
<span class="setting-label">{$t('settings.audio.currentSampleRate')}</span>
<span class="setting-value" class:muted={!hardwareStatus?.is_active}>
+3
View File
@@ -544,6 +544,9 @@
"dacPassthroughNote": "Bezieht sich auf den dekodierten Audio-Inhalt. DAC-Anzeigen zeigen möglicherweise das Transportformat, nicht die Inhaltsauflösung.",
"dacPassthroughDisabledDesc": "DAC-Passthrough verwendet pw-metadata, um PipeWire-Abtastraten zu erzwingen. Es ist nur mit dem PipeWire-Backend kompatibel.",
"dacPassthroughExtendedDesc": "Wenn aktiviert, überschreibt es die obige Qualitätseinstellung, wenn Ihr Audiogerät die gewählte Abtastrate nicht unterstützt. Verhindert Resampling, um eine bitperfekte Wiedergabe zu gewährleisten.",
"pwForceBitperfect": "Bit-Perfect erzwingen (Experimentell)",
"pwForceBitperfectDesc": "Erzwingt PipeWire-Quantum und Abtastrate passend zum Track, Zurücksetzen beim Stoppen. Erfordert DAC-Passthrough.",
"pwForceBitperfectNote": "Experimentell. Kann auf einigen Systemen Audio-Artefakte verursachen. Betrifft nur das PipeWire-Backend.",
"audioBackend": "Audio-Backend",
"audioBackendDesc": "Wähle Audiosystem: Auto (empfohlen), PipeWire (modern), ALSA Direct (bitperfekt, exklusiv) oder PulseAudio (veraltet).",
"currentSampleRate": "Aktuelle Abtastrate",
+3
View File
@@ -561,6 +561,9 @@
"dacPassthroughNote": "Refers to decoded audio content. DAC displays may show transport format, not content resolution.",
"dacPassthroughDisabledDesc": "DAC Passthrough uses pw-metadata to force PipeWire sample rates. It is only compatible with the PipeWire backend.",
"dacPassthroughExtendedDesc": "When enabled, overrides the quality setting above if your audio device doesn't support the selected sample rate. Prevents resampling to guarantee bit-perfect playback.",
"pwForceBitperfect": "Force Bit-Perfect (Experimental)",
"pwForceBitperfectDesc": "Forces PipeWire quantum and sample rate to match the track, resetting on stop. Requires DAC Passthrough.",
"pwForceBitperfectNote": "Experimental. May cause audio glitches on some systems. Only affects PipeWire backend.",
"audioBackend": "Audio Backend",
"audioBackendDesc": "Choose audio system: Auto (recommended), PipeWire (modern), ALSA Direct (bit-perfect, exclusive), or PulseAudio (legacy).",
"currentSampleRate": "Current Sample Rate",
+3
View File
@@ -561,6 +561,9 @@
"dacPassthroughNote": "Se refiere al contenido de audio decodificado. Las pantallas del DAC pueden mostrar el formato de transporte, no la resolución del contenido.",
"dacPassthroughDisabledDesc": "DAC Passthrough usa pw-metadata para forzar las tasas de muestreo de PipeWire. Solo es compatible con el backend PipeWire.",
"dacPassthroughExtendedDesc": "Cuando está habilitado, anula la configuración de calidad anterior si tu dispositivo de audio no soporta la tasa de muestreo seleccionada. Previene el remuestreo para garantizar reproducción bit-perfect.",
"pwForceBitperfect": "Forzar Bit-Perfect (Experimental)",
"pwForceBitperfectDesc": "Fuerza el quantum y la tasa de muestreo de PipeWire para coincidir con la pista, restableciendo al detener. Requiere Passthrough DAC.",
"pwForceBitperfectNote": "Experimental. Puede causar artefactos de audio en algunos sistemas. Solo afecta al backend PipeWire.",
"audioBackend": "Backend de Audio",
"audioBackendDesc": "Elige el sistema de audio: Auto (recomendado), PipeWire (moderno), ALSA Direct (bit-perfect, exclusivo), o PulseAudio (legacy).",
"currentSampleRate": "Tasa de Muestreo Actual",
+3
View File
@@ -544,6 +544,9 @@
"dacPassthroughNote": "Concerne le contenu audio décodé. Les affichages du DAC peuvent montrer le format de transport, pas la résolution du contenu.",
"dacPassthroughDisabledDesc": "Le Passthrough DAC utilise pw-metadata pour forcer les taux d'échantillonnage PipeWire. Il n'est compatible qu'avec le backend PipeWire.",
"dacPassthroughExtendedDesc": "Lorsqu'il est activé, remplace le paramètre de qualité ci-dessus si votre périphérique audio ne prend pas en charge la fréquence d'échantillonnage sélectionnée. Empêche le rééchantillonnage pour garantir une lecture bit-perfect.",
"pwForceBitperfect": "Forcer Bit-Perfect (Expérimental)",
"pwForceBitperfectDesc": "Force le quantum et le taux d'échantillonnage PipeWire pour correspondre à la piste, réinitialisation à l'arrêt. Nécessite le Passthrough DAC.",
"pwForceBitperfectNote": "Expérimental. Peut causer des artefacts audio sur certains systèmes. N'affecte que le backend PipeWire.",
"audioBackend": "Backend audio",
"audioBackendDesc": "Choisissez le système audio : Auto (recommandé), PipeWire (moderne), ALSA Direct (bit-perfect, exclusif) ou PulseAudio (ancien).",
"currentSampleRate": "Taux d'échantillonnage actuel",