diff --git a/GLOSSARY.md b/GLOSSARY.md index 5e0e697..5023bff 100644 --- a/GLOSSARY.md +++ b/GLOSSARY.md @@ -37,7 +37,7 @@ Sending Plays straight to the Scrobbling account instead of to Navidrome, which _Avoid_: Last.fm only **Device config**: -A named output setup: one output device (or the system default), and whether Reverb matches each Song's sample rate and takes the device exclusively. Or instead an HQPlayer, on this computer or another, that Reverb hands playback to: HQPlayer then fetches and plays the Songs itself, while the Queue, transport and Plays stay in Reverb. One is active at a time; with none active, Reverb plays on the system default, shared, at the device's own rate — which is also where playback goes when the active one's device is unplugged. The config keeps its device, so picking it again once the device is back is all it takes. Switching configs carries the playing Song across, from where it was. +A named output setup: one output device (or the system default), and whether Reverb matches each Song's sample rate and takes the device exclusively. Or instead an HQPlayer, on this computer or another, that Reverb hands playback to: HQPlayer then fetches and plays the Songs itself, while the Queue, transport and Plays stay in Reverb. One is active at a time; with none active, Reverb plays on the system default, shared, at the device's own rate — which is also where playback goes when the active one's device is unplugged. The config keeps its device, so picking it again once the device is back is all it takes. A config locked to its device never moves playback elsewhere: while the device is away, playback pauses and the config stays active, ready again the moment the device is back. Switching configs carries the playing Song across, from where it was. _Avoid_: Output profile, audio preset, zone ### Stats diff --git a/crates/reverb-core/examples/play_url.rs b/crates/reverb-core/examples/play_url.rs index b2e4018..ab15cd4 100644 --- a/crates/reverb-core/examples/play_url.rs +++ b/crates/reverb-core/examples/play_url.rs @@ -12,6 +12,8 @@ //! (direct ALSA cards, rate switching) can be exercised without the app: //! `REVERB_DEVICE` is a device id from `--devices`, and `REVERB_AUTO_RATE` / //! `REVERB_EXCLUSIVE` turn on rate matching and exclusive access. +//! `REVERB_LOCKED` locks the output to `REVERB_DEVICE`: give it an id that is +//! not plugged in and nothing plays, rather than the system default. use std::time::{Duration, Instant}; @@ -55,6 +57,7 @@ fn main() { device, auto_rate: std::env::var("REVERB_AUTO_RATE").is_ok(), exclusive: std::env::var("REVERB_EXCLUSIVE").is_ok(), + locked: std::env::var("REVERB_LOCKED").is_ok(), }, false, ); diff --git a/crates/reverb-core/src/audio/engine.rs b/crates/reverb-core/src/audio/engine.rs index dc5e05c..5422363 100644 --- a/crates/reverb-core/src/audio/engine.rs +++ b/crates/reverb-core/src/audio/engine.rs @@ -15,7 +15,7 @@ use crossbeam_channel::{unbounded, Receiver, Sender}; use super::decoder::TrackDecoder; use super::eq::{EqCoeffSet, EqState}; use super::events::{EngineEvent, PlaybackState, SignalPathInfo, TrackChangeReason}; -use super::output::{is_direct_device, open_output, AudioOutput, ExclusiveAccess}; +use super::output::{device_present, is_direct_device, open_output, AudioOutput, ExclusiveAccess}; use super::resampler::StereoResampler; use super::ring::{volume_taper, SharedAudioState, RING_CAPACITY_SECS}; use super::source::{open_stream_source, stream_http_client}; @@ -135,9 +135,9 @@ pub enum EngineCommand { } /// Where and how the engine plays: the output device, whether the device is -/// re-clocked to each track's native rate, and whether it is held -/// exclusively. The default is the system default device, shared, at its own -/// rate. +/// re-clocked to each track's native rate, whether it is held exclusively, and +/// whether playback may leave it. The default is the system default device, +/// shared, at its own rate. #[derive(Debug, Clone, Default, PartialEq, Eq)] pub struct OutputSettings { /// Device id (see `OutputDevice::id`); `None` = system default. @@ -147,6 +147,11 @@ pub struct OutputSettings { /// Hold the device exclusively: hog mode on macOS, WASAPI exclusive mode /// on Windows, the raw `hw:` alias of a direct device on Linux. pub exclusive: bool, + /// Play on `device` or nowhere. When it is not plugged in, open nothing + /// and wait for it, paused, instead of moving to the system default and + /// forgetting it; when it will not open exclusively, share it rather than + /// play elsewhere. Means nothing for the system default. + pub locked: bool, } #[derive(Clone)] @@ -173,6 +178,7 @@ pub fn spawn_engine( let shared_for_thread = shared.clone(); let event_tx_for_err = event_tx.clone(); let initial_device = output.device.clone(); + let locked = output.locked; std::thread::Builder::new() .name("reverb-audio-engine".into()) @@ -181,6 +187,7 @@ pub fn spawn_engine( event_tx, shared_for_thread, initial_device, + locked, standby, ) { Ok(mut engine) => { @@ -307,6 +314,11 @@ struct Engine { /// Switch the output device to each track's native rate (bit-perfect). auto_rate: bool, exclusive_output: bool, + /// Play on `preferred_device` or nowhere (see `OutputSettings::locked`). + locked: bool, + /// The locked device that is not there, while nothing is open waiting + /// for it (see `wait_for_device`). + waiting_for: Option, /// Holds hog-mode access when `exclusive_output` is on (macOS). exclusive_access: ExclusiveAccess, /// Rate-limits the "we have no output at all" recovery attempts. @@ -342,6 +354,7 @@ impl Engine { event_tx: Sender, shared: Arc, initial_device: Option, + locked: bool, standby: bool, ) -> Result { let (output_error_tx, output_error_rx) = unbounded(); @@ -354,6 +367,12 @@ impl Engine { let (mut eq_input, eq_output) = triple_buffer::triple_buffer(&EqCoeffSet::IDENTITY); + // Locked to a device that is not plugged in: open nothing — not the + // system default in its place, not the device's card — and wait. + let locked_missing = locked + && !standby + && initial_device.as_deref().is_some_and(|device| !device_present(device)); + // A saved direct device needs the card freed before it can be opened, // exactly as on a later switch — otherwise the app starts with no // audio at all whenever the sound server happens to hold it. Resolved @@ -362,14 +381,14 @@ impl Engine { #[cfg(target_os = "linux")] let mut card_claim = initial_device .as_deref() - .filter(|device| is_direct_device(device) && !standby) + .filter(|device| is_direct_device(device) && !standby && !locked_missing) .and_then(super::reserve::CardClaim::acquire); let exclusive_access = ExclusiveAccess::inactive(); // In standby the device stays untouched until the engine is woken — // which also means a device that would not open (another player // holding it exclusively) cannot fail the start. - let output = if standby { + let mut output = if standby || locked_missing { AudioOutput::closed(probe_rate) } else { match open_output( @@ -382,6 +401,16 @@ impl Engine { false, ) { Ok(output) => output, + // Locked: no other device will do. The recovery loop in `run` + // keeps trying this one. + Err(e) if locked && initial_device.is_some() => { + log::warn!("{e}; waiting for the locked device"); + #[cfg(target_os = "linux")] + { + card_claim = None; + } + AudioOutput::closed(probe_rate) + } // Starting on the wrong device beats starting mute: the frontend // pushes the real preferences moments later anyway. Err(e) if initial_device.is_some() => { @@ -412,6 +441,23 @@ impl Engine { } }; + // A locked device that is not there is waited for. Also when it left + // between looking and opening: `open_output` then put the system + // default in its place, which a locked output does not take. + let mut waiting_for = None; + if locked && (locked_missing || output.device_missing) { + output = AudioOutput::closed(probe_rate); + #[cfg(target_os = "linux")] + { + card_claim = None; + } + if let Some(device) = initial_device.clone() { + log::warn!("locked output device {device} is not connected; waiting for it"); + let _ = event_tx.send(EngineEvent::LockedDeviceMissing { device: device.clone() }); + waiting_for = Some(device); + } + } + // A saved device that is not plugged in at all: `open_output` opened the // system default, so the preference follows it rather than sitting there // inert — nothing here re-attaches a device that comes back, and the @@ -462,6 +508,8 @@ impl Engine { replay_gain: ReplayGainSettings::default(), scrobble_percent: 80, preferred_device: initial_device, + locked, + waiting_for, #[cfg(target_os = "linux")] card_claim, standby, @@ -487,6 +535,11 @@ impl Engine { } log::warn!("audio stream error: {err}; reopening output device"); if let Err(rebuild_err) = self.rebuild_output(self.auto_rate_target()) { + // A locked device that left is not a failure to stop + // over: it is reported as missing, and waited for. + if self.waiting_for.is_some() { + continue; + } self.emit(EngineEvent::Error { code: "audio-stream".into(), message: format!("{err}; reopen failed: {rebuild_err}"), @@ -561,7 +614,10 @@ impl Engine { } } EngineCommand::Resume => { - if self.state == PlaybackState::Paused { + // Nothing to play into until the locked device is back. + if self.state == PlaybackState::Paused && self.waiting_for.is_some() { + self.report_device_missing(); + } else if self.state == PlaybackState::Paused { self.shared.paused.store(false, Ordering::Relaxed); self.set_state(PlaybackState::Playing); // Navidrome's now-playing entry likely expired while paused. @@ -679,7 +735,14 @@ impl Engine { duration_ms, }); self.last_now_playing = Instant::now(); - self.set_state(PlaybackState::Playing); + if self.waiting_for.is_some() { + // Loaded, with nothing to play it into: it waits, paused, + // for the locked device to come back. + self.pause_for_device(); + self.report_device_missing(); + } else { + self.set_state(PlaybackState::Playing); + } self.emit_position(); self.emit_signal_path(); } @@ -835,7 +898,11 @@ impl Engine { /// Switch device and output mode together, reopening the stream once — /// and not at all when nothing changed. fn set_output(&mut self, settings: OutputSettings) { - let OutputSettings { device, auto_rate, exclusive } = settings; + let OutputSettings { device, auto_rate, exclusive, locked } = settings; + // Locking changes nothing about a stream that is open; it decides what + // the next open does when the device is not there. Unlocked while + // waiting, the recovery loop's next try falls back as usual. + self.locked = locked; if self.preferred_device == device && self.auto_rate == auto_rate && self.exclusive_output == exclusive @@ -852,6 +919,9 @@ impl Engine { // Re-open at the current track's rate (or the device default when // auto-rate is off). if let Err(e) = self.rebuild_output(self.auto_rate_target()) { + if self.waiting_for.is_some() { + return; // reported as missing + } self.emit(EngineEvent::Error { code: "audio-device".into(), message: format!("could not switch output: {e}"), @@ -871,6 +941,9 @@ impl Engine { // Stop while the stream is still there to acknowledge the flush. self.stop(); self.standby = true; + // Nothing is waited for in standby; waking on a device still + // missing reports it afresh. + self.waiting_for = None; self.output.close(); self.exclusive_access = ExclusiveAccess::inactive(); #[cfg(target_os = "linux")] @@ -881,6 +954,9 @@ impl Engine { self.standby = false; if let Err(e) = self.rebuild_output(self.auto_rate_target()) { // The recovery loop in `run` keeps trying from here. + if self.waiting_for.is_some() { + return; // reported as missing + } self.emit(EngineEvent::Error { code: "audio-device".into(), message: format!("could not reopen output: {e}"), @@ -904,6 +980,45 @@ impl Engine { } } + /// Whether the output is locked to a device that is not plugged in. + fn locked_device_missing(&self) -> bool { + self.locked + && self.preferred_device.as_deref().is_some_and(|device| !device_present(device)) + } + + /// The device the output is locked to is not there. Let go of everything + /// — the stream, hog mode, the card — pause, and keep the device: the + /// recovery loop in `run` opens it again once it is back. + fn wait_for_device(&mut self) { + self.output.close(); + self.exclusive_access = ExclusiveAccess::inactive(); + #[cfg(target_os = "linux")] + self.claim_card(None); + self.pause_for_device(); + if self.waiting_for != self.preferred_device { + self.waiting_for = self.preferred_device.clone(); + if let Some(device) = &self.waiting_for { + log::warn!("locked output device {device} is not connected; waiting for it"); + } + self.report_device_missing(); + } + } + + /// Nothing can be heard while the locked device is away, so nothing + /// pretends to play. + fn pause_for_device(&mut self) { + if matches!(self.state, PlaybackState::Playing | PlaybackState::Buffering) { + self.shared.paused.store(true, Ordering::Relaxed); + self.set_state(PlaybackState::Paused); + } + } + + fn report_device_missing(&self) { + if let Some(device) = self.waiting_for.clone() { + self.emit(EngineEvent::LockedDeviceMissing { device }); + } + } + /// The rate the output should run at right now under auto-rate (None = /// device default, or auto-rate off). fn auto_rate_target(&self) -> Option { @@ -939,6 +1054,14 @@ impl Engine { /// unplugged), a device change, or to run at a track's native rate. /// Playback resumes from the current position. fn rebuild_output(&mut self, target_rate: Option) -> Result<(), String> { + // Locked to a device that is not plugged in: open nothing — no other + // device in its place, and no card or hog mode to take for it — and + // wait. The recovery loop in `run` looks again every second. + if self.locked_device_missing() { + self.wait_for_device(); + return Err("the output is locked to a device that is not connected".into()); + } + // Size the ring for the highest rate it might carry. let ring_rate = f64::from(target_rate.unwrap_or(48_000).max(48_000)); let ring_capacity = @@ -1012,9 +1135,16 @@ impl Engine { } } // Nothing is playing once the device was let go, so rather than leave - // the user in silence, come back on the shared default and say why. + // the user in silence, come back on the shared default and say why — + // or, locked, share the device itself, as no other one will do. let mut fallback_error = None; let result = match result { + Err(e) if (was_exclusive || target_direct) && self.locked && device.is_some() => { + log::warn!("exclusive output unavailable ({e}); sharing the locked device"); + fallback_error = Some(e.to_string()); + attempt(device.as_deref(), false) + .map_err(|open_err| format!("{e} (shared mode also failed: {open_err})")) + } Err(e) if was_exclusive || target_direct => { log::warn!("exclusive output unavailable ({e}); using the default device"); fallback_error = Some(e.to_string()); @@ -1034,8 +1164,24 @@ impl Engine { // rebuild after this one stops chasing hardware that has left; nothing // here re-attaches a device that comes back. if output.device_missing { + if self.locked { + // Gone between looking and opening: `open_output` put the + // system default in its place, which a locked output does + // not take. + drop(output); + self.wait_for_device(); + return Err("the output is locked to a device that is not connected".into()); + } self.drop_lost_device(); } + if let Some(device) = self.waiting_for.take() { + // Opened, so not waiting any more — but only the device waited + // for is news; a switch to another one meanwhile is not. + if self.preferred_device.as_deref() == Some(device.as_str()) { + log::info!("locked output device {device} is back"); + self.emit(EngineEvent::LockedDeviceReturned { device }); + } + } if let Some(message) = fallback_error { self.emit(EngineEvent::Error { code: "audio-device".into(), @@ -1088,14 +1234,18 @@ impl Engine { /// Request the callback to drain the ring, wait for the ack, and resync /// the producer-side frame counter. fn flush_ring(&mut self) { - let generation = self.shared.request_flush(); - let deadline = Instant::now() + Duration::from_millis(250); - while !self.shared.flush_complete(generation) { - if Instant::now() > deadline { - log::warn!("ring flush timed out (audio stream stalled?)"); - break; + // With no stream there is no callback to drain the ring, and no need + // for one: the next stream comes with a fresh ring (`rebuild_output`). + if !self.output.is_closed() { + let generation = self.shared.request_flush(); + let deadline = Instant::now() + Duration::from_millis(250); + while !self.shared.flush_complete(generation) { + if Instant::now() > deadline { + log::warn!("ring flush timed out (audio stream stalled?)"); + break; + } + std::thread::sleep(Duration::from_millis(1)); } - std::thread::sleep(Duration::from_millis(1)); } self.frames_pushed = self.shared.frames_played.load(Ordering::Relaxed); // Any starvation the callback flagged before the flush is stale now. @@ -1110,6 +1260,13 @@ impl Engine { if self.state == PlaybackState::Stopped { return false; } + // No stream: the ring goes when the output reopens, so whatever were + // decoded into it now would never be heard — a song loaded while the + // locked device is away would lose its opening. Decode once there is + // somewhere to play it. + if self.output.is_closed() { + return false; + } if self.rate_switch.is_some() { return self.try_complete_rate_switch(); } @@ -1559,6 +1716,11 @@ impl Engine { /// Publish the current audio chain (source → DSP → output). fn emit_signal_path(&self) { let Some(current) = self.current.as_ref() else { return }; + // No stream, no path to show: the last one stays up until the output + // reopens, which publishes it again (`rebuild_output`). + if self.output.is_closed() { + return; + } let ext = current.src.ext_hint.as_deref().unwrap_or("").to_lowercase(); let lossless_source = matches!(ext.as_str(), "flac" | "wav" | "alac" | "aiff" | "aif" | "ape"); let source_rate = current.decoder.sample_rate(); diff --git a/crates/reverb-core/src/audio/events.rs b/crates/reverb-core/src/audio/events.rs index 358ece3..d638662 100644 --- a/crates/reverb-core/src/audio/events.rs +++ b/crates/reverb-core/src/audio/events.rs @@ -78,6 +78,19 @@ pub enum EngineEvent { OutputDeviceLost { device: String, }, + /// The output is locked to a device that is not there (see + /// `OutputSettings::locked`). Nothing is open and playback is paused; the + /// engine keeps the device and opens it again the moment it is back. + /// Sent when the device goes, and again whenever playing is asked for + /// while it is still gone. + LockedDeviceMissing { + device: String, + }, + /// The device `LockedDeviceMissing` waited for is open again. Playback + /// stays paused until asked to resume. + LockedDeviceReturned { + device: String, + }, /// The current audio chain, source to output (the signal path). SignalPath(SignalPathInfo), /// The output's own volume moved — HQPlayer's, turned there or read on diff --git a/crates/reverb-core/src/audio/output.rs b/crates/reverb-core/src/audio/output.rs index c39f5cb..1f38d37 100644 --- a/crates/reverb-core/src/audio/output.rs +++ b/crates/reverb-core/src/audio/output.rs @@ -381,6 +381,13 @@ fn find_device(host: &cpal::Host, wanted: &str, exclusive: bool) -> Option bool { + find_device(&cpal::default_host(), id, false).is_some() +} + pub fn open_output( shared: Arc, consumer: rtrb::Consumer, diff --git a/src-tauri/src/events.rs b/src-tauri/src/events.rs index 22a019c..c8791e0 100644 --- a/src-tauri/src/events.rs +++ b/src-tauri/src/events.rs @@ -177,8 +177,9 @@ struct VolumePayload { #[derive(Clone, Serialize)] #[serde(rename_all = "camelCase")] struct DeviceLostPayload { - /// The device id that was given up. Its label is unknowable — the device is - /// gone from the enumeration the label would have come from. + /// The device id that was given up, or is waited for. Its label is + /// unknowable — the device is gone from the enumeration the label would + /// have come from. device: String, } @@ -372,6 +373,14 @@ fn forward( } let _ = app.emit("player:device-lost", DeviceLostPayload { device }); } + // A locked config's device: the engine waits for it, paused, and the + // config stays the active one — nothing to save. + EngineEvent::LockedDeviceMissing { device } => { + let _ = app.emit("player:device-missing", DeviceLostPayload { device }); + } + EngineEvent::LockedDeviceReturned { device } => { + let _ = app.emit("player:device-returned", DeviceLostPayload { device }); + } EngineEvent::SignalPath(info) => { let _ = app.emit("player:signal-path", info); } diff --git a/src-tauri/src/persistence/settings.rs b/src-tauri/src/persistence/settings.rs index 6b615d1..18c0835 100644 --- a/src-tauri/src/persistence/settings.rs +++ b/src-tauri/src/persistence/settings.rs @@ -46,8 +46,12 @@ pub struct DeviceConfig { pub match_source_rate: bool, /// Take the output device exclusively (macOS hog mode / WASAPI exclusive). pub exclusive_output: bool, + /// Play on `device` or nowhere: when it is not plugged in, pause and wait + /// for it, with this config staying the active one, instead of moving to + /// the system default. Means nothing without a device. + pub lock_device: bool, /// Play through this HQPlayer instead of a device here. When set, the - /// three fields above mean nothing: HQPlayer has its own output setup. + /// fields above mean nothing: HQPlayer has its own output setup. pub hqplayer: Option, } @@ -214,6 +218,7 @@ impl Preferences { device: config.device.clone(), auto_rate: config.match_source_rate, exclusive: config.exclusive_output, + locked: config.lock_device, }, ) } @@ -296,6 +301,7 @@ impl Settings { device: audio_device, match_source_rate, exclusive_output, + lock_device: false, hqplayer: None, }); self.prefs.active_device_config = Some(id); @@ -537,6 +543,7 @@ mod tests { device: Some("coreaudio:BTR17-uid".into()), auto_rate: true, exclusive: true, + locked: false, }, "playback starts where it left off" ); @@ -564,7 +571,7 @@ mod tests { assert_eq!(s.prefs.device_configs[0].name, "System default"); assert_eq!( s.prefs.output(), - OutputSettings { device: None, auto_rate: true, exclusive: false } + OutputSettings { device: None, auto_rate: true, exclusive: false, locked: false } ); } @@ -600,6 +607,7 @@ mod tests { device: Some("coreaudio:dac".into()), match_source_rate: true, exclusive_output: false, + lock_device: false, hqplayer: None, }, DeviceConfig { @@ -608,6 +616,7 @@ mod tests { device: None, match_source_rate: false, exclusive_output: true, + lock_device: false, hqplayer: None, }, ], @@ -616,7 +625,10 @@ mod tests { assert_eq!(prefs.output(), OutputSettings::default(), "none active: system default"); prefs.active_device_config = Some("speakers".into()); - assert_eq!(prefs.output(), OutputSettings { device: None, auto_rate: false, exclusive: true }); + assert_eq!( + prefs.output(), + OutputSettings { device: None, auto_rate: false, exclusive: true, locked: false } + ); prefs.active_device_config = Some("desk".into()); assert_eq!(prefs.output().device.as_deref(), Some("coreaudio:dac")); @@ -653,6 +665,7 @@ mod tests { device: Some("coreaudio:dac".into()), auto_rate: false, exclusive: true, + locked: false, }) ); @@ -662,6 +675,37 @@ mod tests { assert_eq!(back["deviceConfigs"][0]["hqplayer"], serde_json::Value::Null); } + #[test] + fn a_locked_config_locks_the_output_to_its_device() { + let raw = r#"{ + "deviceConfigs": [ + {"id": "desk", "name": "Desk DAC", "device": "coreaudio:dac", "lockDevice": true}, + {"id": "old", "name": "Speakers", "device": "coreaudio:spk"} + ], + "activeDeviceConfig": "desk" + }"#; + let mut prefs: Preferences = serde_json::from_str(raw).unwrap(); + assert_eq!( + prefs.output(), + OutputSettings { + device: Some("coreaudio:dac".into()), + auto_rate: false, + exclusive: false, + locked: true, + } + ); + + // A config from before locking is not locked. + prefs.active_device_config = Some("old".into()); + assert!(!prefs.device_configs[1].lock_device); + assert!(!prefs.output().locked); + + // And the field round-trips under its name. + let back = serde_json::to_value(&prefs).unwrap(); + assert_eq!(back["deviceConfigs"][0]["lockDevice"], serde_json::json!(true)); + assert_eq!(back["deviceConfigs"][1]["lockDevice"], serde_json::json!(false)); + } + #[test] fn old_settings_files_parse_with_pref_defaults() { // A settings.json written before the preferences existed. diff --git a/src/lib/deviceConfigs.test.ts b/src/lib/deviceConfigs.test.ts index 7e7c7ae..0c8ab63 100644 --- a/src/lib/deviceConfigs.test.ts +++ b/src/lib/deviceConfigs.test.ts @@ -18,6 +18,7 @@ const desk: DeviceConfig = { device: "coreaudio:dac", matchSourceRate: true, exclusiveOutput: true, + lockDevice: false, hqplayer: null, }; const speakers: DeviceConfig = { @@ -26,6 +27,7 @@ const speakers: DeviceConfig = { device: null, matchSourceRate: false, exclusiveOutput: false, + lockDevice: false, hqplayer: null, }; const prefs = { deviceConfigs: [desk, speakers], activeDeviceConfig: "desk" }; diff --git a/src/lib/i18n/messages/de.ts b/src/lib/i18n/messages/de.ts index 75f5f9a..baa2bd6 100644 --- a/src/lib/i18n/messages/de.ts +++ b/src/lib/i18n/messages/de.ts @@ -299,6 +299,8 @@ export const de: Messages = { "{n, plural, one {Bibliotheksscan abgeschlossen — # Eintrag} other {Bibliotheksscan abgeschlossen — # Einträge}}", "toast.scanFailed": "Scan fehlgeschlagen", "toast.outputDeviceLost": "Ausgabegerät getrennt — zurück auf die Systemvorgabe", + "toast.outputDeviceMissing": "Ausgabegerät nicht verbunden — die Wiedergabe pausiert, bis es wieder da ist", + "toast.outputDeviceReturned": "Ausgabegerät wieder verbunden", "toast.connected": "{service} verbunden", "toast.imported": "{n, plural, one {# neuer Scrobble von {service} importiert} other {# neue Scrobbles von {service} importiert}}", @@ -471,6 +473,7 @@ export const de: Messages = { "settings.configShared": "Geteilt", "settings.configExclusive": "Exklusiv", "settings.configMatchRate": "Übernimmt die Abtastrate der Quelle", + "settings.configLocked": "Gebunden", "settings.deviceNotConnected": "Gerät nicht verbunden", "settings.savedDeviceMissing": "Gespeichertes Gerät (nicht verbunden)", "settings.outputDevice": "Ausgabegerät", @@ -494,6 +497,11 @@ export const de: Messages = { "Keine andere App kann über das Gerät abspielen, solange Reverb es hält — Hog Mode unter macOS, WASAPI-Exklusivmodus unter Windows. Unter Linux oben ein (direkt)-Ausgabegerät wählen; es wird dann strikt angesprochen, ohne ALSA-Umwandlung.", "settings.exclusiveUnavailable": "Benötigt ein direktes Ausgabegerät — über einen Soundserver gibt es keine Karte zu belegen. Oben eines auswählen.", + "settings.lockDevice": "An dieses Gerät binden", + "settings.lockDeviceHint": + "Wird das Gerät getrennt oder ausgeschaltet, pausiert die Wiedergabe und wartet darauf, statt auf die Systemvorgabe zu wechseln. Diese Konfiguration bleibt ausgewählt und ist wieder bereit, sobald das Gerät zurück ist.", + "settings.lockDeviceUnavailable": + "Oben ein Ausgabegerät wählen, an das gebunden werden soll — die Systemvorgabe ist kein festes Gerät.", "settings.playsOn": "Spielt auf", "settings.playsOnThisComputer": "Diesem Computer", "settings.configHqplayer": "HQPlayer auf {address}", diff --git a/src/lib/i18n/messages/en.ts b/src/lib/i18n/messages/en.ts index f1fb95c..201d1f4 100644 --- a/src/lib/i18n/messages/en.ts +++ b/src/lib/i18n/messages/en.ts @@ -326,6 +326,8 @@ export const en = { "{n, plural, one {Library scan finished — # entry} other {Library scan finished — # entries}}", "toast.scanFailed": "Scan failed", "toast.outputDeviceLost": "Output device disconnected — switched to the system default", + "toast.outputDeviceMissing": "Output device not connected — playback is paused until it is back", + "toast.outputDeviceReturned": "Output device reconnected", "toast.connected": "{service} connected", "toast.imported": "{n, plural, one {Imported # new scrobble from {service}} other {Imported # new scrobbles from {service}}}", @@ -496,6 +498,7 @@ export const en = { "settings.configShared": "Shared", "settings.configExclusive": "Exclusive", "settings.configMatchRate": "Matches source rate", + "settings.configLocked": "Locked", "settings.deviceNotConnected": "Device not connected", "settings.savedDeviceMissing": "Saved device (not connected)", "settings.outputDevice": "Output device", @@ -519,6 +522,11 @@ export const en = { "No other app can play through the device while Reverb holds it — hog mode on macOS, WASAPI exclusive mode on Windows. On Linux, pick a (direct) output device above; this then addresses it strictly, with no ALSA conversion.", "settings.exclusiveUnavailable": "Needs a direct output device — a sound-server route has no card to claim. Pick one above.", + "settings.lockDevice": "Lock to this device", + "settings.lockDeviceHint": + "If the device is unplugged or switched off, playback pauses and waits for it instead of moving to the system default. This config stays selected, ready again once the device is back.", + "settings.lockDeviceUnavailable": + "Pick an output device above to lock to — the system default is not one fixed device.", "settings.playsOn": "Plays on", "settings.playsOnThisComputer": "This computer", "settings.configHqplayer": "HQPlayer at {address}", diff --git a/src/lib/i18n/messages/es.ts b/src/lib/i18n/messages/es.ts index 7aa6f40..84a5557 100644 --- a/src/lib/i18n/messages/es.ts +++ b/src/lib/i18n/messages/es.ts @@ -299,6 +299,8 @@ export const es: Messages = { "{n, plural, one {Análisis terminado — # entrada} other {Análisis terminado — # entradas}}", "toast.scanFailed": "Error en el análisis", "toast.outputDeviceLost": "Dispositivo de salida desconectado: se ha vuelto al predeterminado del sistema", + "toast.outputDeviceMissing": "Dispositivo de salida no conectado: la reproducción queda en pausa hasta que vuelva", + "toast.outputDeviceReturned": "Dispositivo de salida reconectado", "toast.connected": "{service} conectado", "toast.imported": "{n, plural, one {# scrobble nuevo importado de {service}} other {# scrobbles nuevos importados de {service}}}", @@ -471,6 +473,7 @@ export const es: Messages = { "settings.configShared": "Compartido", "settings.configExclusive": "Exclusivo", "settings.configMatchRate": "Sigue la frecuencia de la fuente", + "settings.configLocked": "Fijado", "settings.deviceNotConnected": "Dispositivo no conectado", "settings.savedDeviceMissing": "Dispositivo guardado (no conectado)", "settings.outputDevice": "Dispositivo de salida", @@ -494,6 +497,11 @@ export const es: Messages = { "Ninguna otra aplicación puede reproducir a través del dispositivo mientras Reverb lo retiene: hog mode en macOS, modo exclusivo de WASAPI en Windows. En Linux, elige arriba un dispositivo (directo); entonces se direcciona de forma estricta, sin conversión de ALSA.", "settings.exclusiveUnavailable": "Requiere un dispositivo de salida directo: una ruta a través del servidor de sonido no tiene tarjeta que reclamar. Elige uno arriba.", + "settings.lockDevice": "Fijar a este dispositivo", + "settings.lockDeviceHint": + "Si el dispositivo se desconecta o se apaga, la reproducción se pausa y lo espera en lugar de pasar al predeterminado del sistema. Esta configuración sigue seleccionada y vuelve a estar lista en cuanto vuelva el dispositivo.", + "settings.lockDeviceUnavailable": + "Elige arriba un dispositivo de salida al que fijarla: el predeterminado del sistema no es un dispositivo concreto.", "settings.playsOn": "Suena en", "settings.playsOnThisComputer": "Este ordenador", "settings.configHqplayer": "HQPlayer en {address}", diff --git a/src/lib/i18n/messages/fr.ts b/src/lib/i18n/messages/fr.ts index 6efa335..5cfea46 100644 --- a/src/lib/i18n/messages/fr.ts +++ b/src/lib/i18n/messages/fr.ts @@ -300,6 +300,8 @@ export const fr: Messages = { "{n, plural, one {Analyse terminée — # entrée} other {Analyse terminée — # entrées}}", "toast.scanFailed": "Échec de l'analyse", "toast.outputDeviceLost": "Périphérique de sortie déconnecté — retour à la valeur par défaut du système", + "toast.outputDeviceMissing": "Périphérique de sortie non connecté — lecture en pause jusqu’à son retour", + "toast.outputDeviceReturned": "Périphérique de sortie reconnecté", "toast.connected": "{service} connecté", "toast.imported": "{n, plural, one {# nouveau scrobble importé depuis {service}} other {# nouveaux scrobbles importés depuis {service}}}", @@ -472,6 +474,7 @@ export const fr: Messages = { "settings.configShared": "Partagé", "settings.configExclusive": "Exclusif", "settings.configMatchRate": "Suit la fréquence de la source", + "settings.configLocked": "Verrouillé", "settings.deviceNotConnected": "Périphérique non connecté", "settings.savedDeviceMissing": "Périphérique enregistré (non connecté)", "settings.outputDevice": "Périphérique de sortie", @@ -495,6 +498,11 @@ export const fr: Messages = { "Aucune autre application ne peut jouer sur le périphérique tant que Reverb le détient — hog mode sur macOS, mode exclusif WASAPI sur Windows. Sous Linux, choisissez un périphérique (direct) ci-dessus ; il est alors adressé strictement, sans conversion ALSA.", "settings.exclusiveUnavailable": "Nécessite un périphérique de sortie direct — une route via le serveur audio n’a aucune carte à réserver. Choisissez-en un ci-dessus.", + "settings.lockDevice": "Verrouiller sur ce périphérique", + "settings.lockDeviceHint": + "Si le périphérique est débranché ou éteint, la lecture se met en pause et l’attend au lieu de passer à la valeur par défaut du système. Cette configuration reste sélectionnée, prête dès que le périphérique revient.", + "settings.lockDeviceUnavailable": + "Choisissez ci-dessus un périphérique de sortie sur lequel verrouiller — la valeur par défaut du système n’est pas un périphérique fixe.", "settings.playsOn": "Joue sur", "settings.playsOnThisComputer": "Cet ordinateur", "settings.configHqplayer": "HQPlayer sur {address}", diff --git a/src/lib/ipc/events.ts b/src/lib/ipc/events.ts index a870d6d..7b04eef 100644 --- a/src/lib/ipc/events.ts +++ b/src/lib/ipc/events.ts @@ -38,6 +38,13 @@ export interface EventMap { "player:format": { sampleRate: number }; /** The configured output device vanished; the backend is on the system default. */ "player:device-lost": { device: string }; + /** + * The active config is locked to this device and it is not there: playback + * is paused, waiting for it. Sent again when playing is asked for meanwhile. + */ + "player:device-missing": { device: string }; + /** The device `player:device-missing` waited for is back; playback stays paused. */ + "player:device-returned": { device: string }; /** HQPlayer's own volume moved (or was read on connecting); 0–1, like the slider. */ "player:volume": { volume: number }; "eq:state": import("../subsonic/types").EqState; diff --git a/src/lib/playback/engineBridge.ts b/src/lib/playback/engineBridge.ts index fec599e..1d08309 100644 --- a/src/lib/playback/engineBridge.ts +++ b/src/lib/playback/engineBridge.ts @@ -76,6 +76,19 @@ export function initEngineBridge() { useUiStore.getState().showToast(getT()("toast.outputDeviceLost")); }); + // The active config is locked to its device: the engine paused to wait for + // it, and the config stays the active one, so there is nothing to mirror — + // only the news, and a device list that changed. + void on("player:device-missing", () => { + void queryClient.invalidateQueries({ queryKey: ["audio-devices"] }); + useUiStore.getState().showToast(getT()("toast.outputDeviceMissing")); + }); + + void on("player:device-returned", () => { + void queryClient.invalidateQueries({ queryKey: ["audio-devices"] }); + useUiStore.getState().showToast(getT()("toast.outputDeviceReturned")); + }); + // HQPlayer's volume, turned in HQPlayer or read on connecting. Only mirrored: // setting it through the store would send it straight back. void on("player:volume", ({ volume }) => { diff --git a/src/lib/subsonic/types.ts b/src/lib/subsonic/types.ts index bd47291..df01c4e 100644 --- a/src/lib/subsonic/types.ts +++ b/src/lib/subsonic/types.ts @@ -487,9 +487,15 @@ export interface DeviceConfig { matchSourceRate: boolean; /** Take the output device exclusively (macOS hog mode / WASAPI exclusive). */ exclusiveOutput: boolean; + /** + * Play on `device` or nowhere: when it is not plugged in, playback pauses + * and waits for it, with this config staying the active one, instead of + * moving to the system default. Means nothing without a device. + */ + lockDevice: boolean; /** * Play through this HQPlayer instead of a device here; `null` for a device - * config. When set, the three fields above mean nothing. + * config. When set, the fields above mean nothing. */ hqplayer: HqPlayerEndpoint | null; } diff --git a/src/views/settings/SettingsView.tsx b/src/views/settings/SettingsView.tsx index b36f287..4ccffe8 100644 --- a/src/views/settings/SettingsView.tsx +++ b/src/views/settings/SettingsView.tsx @@ -385,6 +385,7 @@ function blankDeviceConfig(): DeviceConfig { device: null, matchSourceRate: false, exclusiveOutput: false, + lockDevice: false, hqplayer: null, }; } @@ -422,6 +423,7 @@ function AudioSection() { config.exclusiveOutput ? t("settings.configExclusive") : t("settings.configShared"), ]; if (config.matchSourceRate) parts.push(t("settings.configMatchRate")); + if (config.lockDevice) parts.push(t("settings.configLocked")); return { text: parts.join(" · "), missing }; } @@ -655,14 +657,16 @@ function DeviceConfigDialog({ device: null, matchSourceRate: false, exclusiveOutput: false, + lockDevice: false, hqplayer: endpoint, }); } else { onSave({ ...draft, name, - // Keep the summary truthful: the switch cannot be on where it means nothing. + // Keep the summary truthful: the switches cannot be on where they mean nothing. exclusiveOutput: draft.exclusiveOutput && exclusiveOk, + lockDevice: draft.lockDevice && device != null, hqplayer: null, }); } @@ -784,6 +788,20 @@ function DeviceConfigDialog({ onChange={(exclusiveOutput) => update({ exclusiveOutput })} /> + + update({ lockDevice })} + /> + )}