merge: integrate backend reliability round
cx
This commit is contained in:
52 files changed
+2165
-222
No files matched your search
@@ -384,6 +384,10 @@ streamer.
|
||||
- HiFi wizard with copyable audio-stack config blocks (clipboard works over SSH)
|
||||
- MPRIS out of the box, live JSON events (`qbzd watch`), service files for
|
||||
systemd/OpenRC/runit
|
||||
- Event hooks: `qbzd settings set hooks.script /path/to/script` runs your script
|
||||
on playback/session events with `QBZ_*` environment variables — push
|
||||
integration for audio-box distros (moOde, Volumio, DIY setups), no polling
|
||||
required
|
||||
|
||||
Full manual:
|
||||
**[Headless Daemon (qbzd) — Wiki](https://github.com/vicrodh/qbz/wiki/Headless-Daemon)**
|
||||
|
||||
@@ -209,7 +209,8 @@ pub fn plan_tick(
|
||||
// next track pre-queued and none is armed; arm the first playable upcoming
|
||||
// exactly once per current track, suppressed when the current track is
|
||||
// stop-after-marked (so it ends naturally and the marker can fire).
|
||||
if ev.gapless_ready
|
||||
if ev.is_playing
|
||||
&& ev.gapless_ready
|
||||
&& ev.gapless_next_track_id == 0
|
||||
&& ev.track_id != 0
|
||||
&& state.gapless_requested_for != ev.track_id
|
||||
@@ -382,6 +383,70 @@ pub struct DriverDeps {
|
||||
pub on_tick: Arc<dyn Fn() + Send + Sync>,
|
||||
}
|
||||
|
||||
/// Result of a gapless byte fetch that ran outside the 450 ms control loop.
|
||||
/// Keeping the predecessor alongside the successor lets the loop reject a
|
||||
/// late download after a manual track/queue change instead of appending it to
|
||||
/// whichever engine happens to be current by then.
|
||||
struct GaplessFetchResult {
|
||||
predecessor_id: u64,
|
||||
successor_id: u64,
|
||||
bytes: Option<Vec<u8>>,
|
||||
}
|
||||
|
||||
/// A completed gapless fetch is usable only while both playback and the queue
|
||||
/// still describe the edge it was started for. `is_playing` is deliberately
|
||||
/// not required: `PlayNext` can safely land just after natural end and revive
|
||||
/// the now-empty engine, closing the final download-vs-end race.
|
||||
fn gapless_fetch_is_current(
|
||||
result: &GaplessFetchResult,
|
||||
event: &PlaybackEvent,
|
||||
queue: &QueueSnapshot,
|
||||
) -> bool {
|
||||
event.track_id == result.predecessor_id
|
||||
&& event.gapless_next_track_id == 0
|
||||
&& queue.current == result.predecessor_id
|
||||
&& queue.stop_after != Some(result.predecessor_id)
|
||||
&& queue.upcoming.first().copied() == Some((result.successor_id, true))
|
||||
}
|
||||
|
||||
async fn finish_gapless_fetch<A: FrontendAdapter + Send + Sync + 'static>(
|
||||
runtime: &Arc<AppRuntime<A>>,
|
||||
result: GaplessFetchResult,
|
||||
) {
|
||||
if result.bytes.is_none() {
|
||||
log::warn!(
|
||||
"[qbzd] driver: gapless fetch for track {} failed",
|
||||
result.successor_id
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
let core = runtime.core();
|
||||
let queue = queue_snapshot(core).await;
|
||||
let player = core.player();
|
||||
let event = player.get_playback_event();
|
||||
if !player.state.has_loaded_audio() || !gapless_fetch_is_current(&result, &event, &queue) {
|
||||
log::info!(
|
||||
"[qbzd] driver: discarding stale gapless track {} (predecessor was {})",
|
||||
result.successor_id,
|
||||
result.predecessor_id
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
let bytes = result.bytes.expect("gapless bytes checked above");
|
||||
match player.play_next(bytes, result.successor_id) {
|
||||
Ok(()) => log::info!(
|
||||
"[qbzd] driver: queued track {} for gapless playback",
|
||||
result.successor_id
|
||||
),
|
||||
Err(error) => log::warn!(
|
||||
"[qbzd] driver: gapless play_next for track {} failed: {error}",
|
||||
result.successor_id
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
/// The 450 ms IO shell. Each tick: read the player event, drain the stream-error
|
||||
/// latch, project the queue, `plan_tick`, execute the actions, then
|
||||
/// `advance_state`. Breaks when `shutdown` flips to `true`; the loop is thin by
|
||||
@@ -395,16 +460,35 @@ pub async fn run_driver<A: FrontendAdapter + Send + Sync + 'static>(
|
||||
let mut state = DriverState::default();
|
||||
let mut ticker = tokio::time::interval(Duration::from_millis(TICK_MS));
|
||||
ticker.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
|
||||
// Gapless downloads may outlive the fixed ten-second arm window, but they
|
||||
// must never block the loop that detects natural end and advances the
|
||||
// queue. JoinSet keeps those tasks owned by the driver so shutdown can
|
||||
// abort and drain them before AppRuntime is dropped (#521 ordering).
|
||||
let mut gapless_fetches = tokio::task::JoinSet::new();
|
||||
|
||||
loop {
|
||||
tokio::select! {
|
||||
_ = ticker.tick() => {}
|
||||
_ = shutdown.changed() => {
|
||||
if *shutdown.borrow() {
|
||||
biased;
|
||||
changed = shutdown.changed() => {
|
||||
if changed.is_err() || *shutdown.borrow() {
|
||||
break;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
completed = gapless_fetches.join_next(), if !gapless_fetches.is_empty() => {
|
||||
match completed {
|
||||
Some(Ok(result)) => finish_gapless_fetch(&runtime, result).await,
|
||||
Some(Err(error)) if error.is_cancelled() => {
|
||||
log::debug!("[qbzd] driver: stale gapless fetch cancelled");
|
||||
}
|
||||
Some(Err(error)) => {
|
||||
log::warn!("[qbzd] driver: gapless fetch task failed: {error}");
|
||||
}
|
||||
None => {}
|
||||
}
|
||||
continue;
|
||||
}
|
||||
_ = ticker.tick() => {}
|
||||
}
|
||||
|
||||
let core = runtime.core();
|
||||
@@ -416,6 +500,21 @@ pub async fn run_driver<A: FrontendAdapter + Send + Sync + 'static>(
|
||||
|
||||
let actions = plan_tick(&state, &ev, &queue, stream_error.as_deref());
|
||||
|
||||
// Once the engine/queue edge has moved, an outstanding fetch belongs
|
||||
// to the old predecessor. Drop its network future immediately so it
|
||||
// cannot contend with the normal next-track start.
|
||||
if actions.iter().any(|action| {
|
||||
matches!(
|
||||
action,
|
||||
DriverAction::SyncCursorTo(_)
|
||||
| DriverAction::AdvanceAndPlay
|
||||
| DriverAction::PauseStopAfter
|
||||
| DriverAction::QueueFinished
|
||||
)
|
||||
}) {
|
||||
gapless_fetches.abort_all();
|
||||
}
|
||||
|
||||
for action in &actions {
|
||||
match action {
|
||||
DriverAction::SyncCursorTo(id) => {
|
||||
@@ -423,13 +522,23 @@ pub async fn run_driver<A: FrontendAdapter + Send + Sync + 'static>(
|
||||
}
|
||||
DriverAction::ArmGapless(id) => {
|
||||
let quality = (deps.quality)();
|
||||
if let Some(bytes) =
|
||||
core.fetch_for_gapless_resolved(*id, quality, None, None).await
|
||||
{
|
||||
if let Err(e) = player.play_next(bytes, *id) {
|
||||
log::warn!("[qbzd] driver: gapless play_next failed: {e}");
|
||||
let predecessor_id = ev.track_id;
|
||||
let successor_id = *id;
|
||||
let task_runtime = Arc::clone(&runtime);
|
||||
log::info!(
|
||||
"[qbzd] driver: fetching gapless track {successor_id} after {predecessor_id}"
|
||||
);
|
||||
gapless_fetches.spawn(async move {
|
||||
let bytes = task_runtime
|
||||
.core()
|
||||
.fetch_for_gapless_resolved(successor_id, quality, None, None)
|
||||
.await;
|
||||
GaplessFetchResult {
|
||||
predecessor_id,
|
||||
successor_id,
|
||||
bytes,
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
DriverAction::PauseStopAfter => {
|
||||
// The ended track is the queue's current track (playback.rs:4708).
|
||||
@@ -479,6 +588,14 @@ pub async fn run_driver<A: FrontendAdapter + Send + Sync + 'static>(
|
||||
state = advance_state(&state, &ev, &actions);
|
||||
(deps.on_tick)();
|
||||
}
|
||||
gapless_fetches.abort_all();
|
||||
while let Some(result) = gapless_fetches.join_next().await {
|
||||
if let Err(error) = result {
|
||||
if !error.is_cancelled() {
|
||||
log::warn!("[qbzd] driver: gapless fetch failed during shutdown: {error}");
|
||||
}
|
||||
}
|
||||
}
|
||||
log::info!("[qbzd] driver: shutting down");
|
||||
}
|
||||
|
||||
@@ -864,6 +981,83 @@ mod tests {
|
||||
assert!(!a2.iter().any(|x| matches!(x, DriverAction::ArmGapless(_))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stopped_track_never_starts_a_gapless_fetch() {
|
||||
let mut current = ev(1, false, 581, 581);
|
||||
current.gapless_ready = true;
|
||||
let previous = DriverState::after(&ev(1, true, 580, 581));
|
||||
let actions = plan_tick(
|
||||
&previous,
|
||||
¤t,
|
||||
&q(1, &[(2, true)], "off", None),
|
||||
None,
|
||||
);
|
||||
assert!(!actions
|
||||
.iter()
|
||||
.any(|action| matches!(action, DriverAction::ArmGapless(_))));
|
||||
assert!(actions.contains(&DriverAction::AdvanceAndPlay));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn completed_gapless_fetch_requires_the_original_queue_edge() {
|
||||
let result = GaplessFetchResult {
|
||||
predecessor_id: 1,
|
||||
successor_id: 2,
|
||||
bytes: None,
|
||||
};
|
||||
let mut current = ev(1, true, 575, 581);
|
||||
current.gapless_ready = true;
|
||||
assert!(gapless_fetch_is_current(
|
||||
&result,
|
||||
¤t,
|
||||
&q(1, &[(2, true)], "off", None)
|
||||
));
|
||||
|
||||
// Natural end still accepts a just-finished download: PlayNext's
|
||||
// late-arrival path revives the empty engine without replaying track 1.
|
||||
current.is_playing = false;
|
||||
assert!(gapless_fetch_is_current(
|
||||
&result,
|
||||
¤t,
|
||||
&q(1, &[(2, true)], "off", None)
|
||||
));
|
||||
|
||||
current.track_id = 2;
|
||||
assert!(!gapless_fetch_is_current(
|
||||
&result,
|
||||
¤t,
|
||||
&q(2, &[(3, true)], "off", None)
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn completed_gapless_fetch_rejects_changed_successor_and_stop_after() {
|
||||
let result = GaplessFetchResult {
|
||||
predecessor_id: 1,
|
||||
successor_id: 2,
|
||||
bytes: None,
|
||||
};
|
||||
let mut current = ev(1, true, 575, 581);
|
||||
current.gapless_ready = true;
|
||||
assert!(!gapless_fetch_is_current(
|
||||
&result,
|
||||
¤t,
|
||||
&q(1, &[(3, true)], "off", None)
|
||||
));
|
||||
assert!(!gapless_fetch_is_current(
|
||||
&result,
|
||||
¤t,
|
||||
&q(1, &[(2, true)], "off", Some(1))
|
||||
));
|
||||
|
||||
current.gapless_next_track_id = 9;
|
||||
assert!(!gapless_fetch_is_current(
|
||||
&result,
|
||||
¤t,
|
||||
&q(1, &[(2, true)], "off", None)
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn repeat_one_advances_instead_of_finishing() {
|
||||
let s = DriverState::after(&ev(1, true, 580, 581));
|
||||
|
||||
@@ -16,6 +16,12 @@ pub struct DaemonPrefs {
|
||||
/// (CONSOLE ext). Default ON; the `QBZD_MPRIS` env var overrides it when
|
||||
/// set. Toggling this needs a daemon restart (the service spawns at boot).
|
||||
pub mpris_enabled: bool,
|
||||
/// Absolute path of an executable the daemon runs on playback/session
|
||||
/// events (CONSOLE ext), with the event in `QBZ_*` environment variables.
|
||||
/// Empty = hooks off (the default). The `QBZD_HOOK` env var overrides it
|
||||
/// when set. Changing it needs a daemon restart (the dispatcher spawns at
|
||||
/// boot). Machine-local by design — NEVER part of the settings bundle.
|
||||
pub hook_script: String,
|
||||
}
|
||||
impl Default for DaemonPrefs {
|
||||
fn default() -> Self {
|
||||
@@ -23,6 +29,7 @@ impl Default for DaemonPrefs {
|
||||
streaming_quality: "hires_plus".into(),
|
||||
volume: 0.5,
|
||||
mpris_enabled: true,
|
||||
hook_script: String::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -35,7 +42,11 @@ pub fn load_at(data_root: &Path) -> DaemonPrefs {
|
||||
// forward-compatible: unknown fields ignored WITH a warning (01 §10.3)
|
||||
if let Some(obj) = v.as_object() {
|
||||
for k in obj.keys() {
|
||||
if k != "streaming_quality" && k != "volume" && k != "mpris_enabled" {
|
||||
if k != "streaming_quality"
|
||||
&& k != "volume"
|
||||
&& k != "mpris_enabled"
|
||||
&& k != "hook_script"
|
||||
{
|
||||
log::warn!("[daemon_prefs] unknown field ignored: {k}");
|
||||
}
|
||||
}
|
||||
@@ -92,6 +103,8 @@ mod tests {
|
||||
// Non-default (default is true) so the roundtrip actually exercises
|
||||
// the field, not just its presence.
|
||||
mpris_enabled: false,
|
||||
// Non-default (default is empty) for the same reason.
|
||||
hook_script: "/usr/local/bin/qbz-hook.sh".into(),
|
||||
};
|
||||
|
||||
save_at(&prefs, &dir).expect("save daemon prefs");
|
||||
@@ -100,6 +113,7 @@ mod tests {
|
||||
assert_eq!(loaded.streaming_quality, "cd");
|
||||
assert_eq!(loaded.volume, 0.72);
|
||||
assert!(!loaded.mpris_enabled);
|
||||
assert_eq!(loaded.hook_script, "/usr/local/bin/qbz-hook.sh");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
|
||||
@@ -69,17 +69,77 @@ fn suspend_default_sink_for_exclusive() {
|
||||
/// fix). No-op if QBZ did not suspend one — so it is safe to call on every
|
||||
/// stop/teardown. Call it once the exclusive device has actually been released
|
||||
/// so the rest of the system can use the sink again.
|
||||
pub fn resume_suspended_sink() {
|
||||
pub fn resume_suspended_sink() -> Result<(), String> {
|
||||
let target = match SUSPENDED_SINK.lock() {
|
||||
Ok(mut guard) => guard.take(),
|
||||
Ok(guard) => guard.clone(),
|
||||
Err(_) => None,
|
||||
};
|
||||
if let Some(sink) = target {
|
||||
let _ = std::process::Command::new("pactl")
|
||||
.args(["suspend-sink", &sink, "0"])
|
||||
.output();
|
||||
log::info!("[ALSA Backend] Resumed PipeWire sink '{}'", sink);
|
||||
let Some(sink) = target else {
|
||||
return Ok(());
|
||||
};
|
||||
|
||||
// The PCM and reservation have already been dropped by every caller, but
|
||||
// PipeWire may need a short moment to recreate the parked sink. Retry the
|
||||
// exact recorded name, then the default alias as a compatibility fallback.
|
||||
// Keep SUSPENDED_SINK populated until one command actually succeeds: the
|
||||
// old take-before-command implementation permanently lost the recovery
|
||||
// target on one transient `pactl` failure while logging success anyway.
|
||||
let mut last_error = String::new();
|
||||
for delay_ms in [0u64, 25, 75, 150] {
|
||||
if delay_ms > 0 {
|
||||
std::thread::sleep(std::time::Duration::from_millis(delay_ms));
|
||||
}
|
||||
let mut targets = vec![sink.as_str()];
|
||||
if sink != "@DEFAULT_SINK@" {
|
||||
targets.push("@DEFAULT_SINK@");
|
||||
}
|
||||
for target in targets {
|
||||
match std::process::Command::new("pactl")
|
||||
.args(["suspend-sink", target, "0"])
|
||||
.output()
|
||||
{
|
||||
Ok(output) if output.status.success() => {
|
||||
if let Ok(mut guard) = SUSPENDED_SINK.lock() {
|
||||
if guard.as_deref() == Some(sink.as_str()) {
|
||||
*guard = None;
|
||||
}
|
||||
}
|
||||
log::info!(
|
||||
"[ALSA Backend] Resumed PipeWire sink '{}' via '{}'",
|
||||
sink,
|
||||
target
|
||||
);
|
||||
return Ok(());
|
||||
}
|
||||
Ok(output) => {
|
||||
last_error = String::from_utf8_lossy(&output.stderr).trim().to_string();
|
||||
}
|
||||
Err(error) => {
|
||||
last_error = error.to_string();
|
||||
if error.kind() == std::io::ErrorKind::NotFound {
|
||||
let message = format!(
|
||||
"cannot resume PipeWire sink '{}': pactl is unavailable ({error})",
|
||||
sink
|
||||
);
|
||||
log::warn!("[ALSA Backend] {message}");
|
||||
return Err(message);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let message = format!(
|
||||
"cannot resume PipeWire sink '{}' after releasing ALSA: {}",
|
||||
sink,
|
||||
if last_error.is_empty() {
|
||||
"pactl failed without a diagnostic"
|
||||
} else {
|
||||
last_error.as_str()
|
||||
}
|
||||
);
|
||||
log::warn!("[ALSA Backend] {message}");
|
||||
Err(message)
|
||||
}
|
||||
|
||||
/// Common audio sample rates to check for device support
|
||||
|
||||
@@ -113,6 +113,18 @@ pub struct AlsaDirectStream {
|
||||
device_id: String,
|
||||
}
|
||||
|
||||
/// A writable ALSA mixer element and its current normalized level.
|
||||
///
|
||||
/// The probe is deliberately read-only. Callers use the sampled level to seed
|
||||
/// QBZ's volume state *before* enabling hardware volume, so changing the
|
||||
/// setting cannot copy the direct path's fixed 100% UI value into the
|
||||
/// physical mixer.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct HardwareVolumeInfo {
|
||||
pub control_name: String,
|
||||
pub volume: f32,
|
||||
}
|
||||
|
||||
/// Defensive settle delay between reservation acquisition and PCM open.
|
||||
///
|
||||
/// Only applied when the reservation actually transitioned ownership (i.e.
|
||||
@@ -886,7 +898,7 @@ impl AlsaDirectStream {
|
||||
&self.device_id
|
||||
}
|
||||
|
||||
/// Try to set hardware volume via ALSA mixer
|
||||
/// Try to set hardware volume via ALSA mixer.
|
||||
///
|
||||
/// Returns error if:
|
||||
/// - DAC doesn't have mixer controls (common for USB DACs)
|
||||
@@ -894,57 +906,29 @@ impl AlsaDirectStream {
|
||||
///
|
||||
/// NOTE: Failure doesn't break playback, just means volume can't be controlled.
|
||||
pub fn set_hardware_volume(&self, volume: f32) -> Result<(), String> {
|
||||
use alsa::mixer::SelemChannelId::*;
|
||||
use alsa::mixer::{Mixer, SelemId};
|
||||
let mixer = open_hardware_mixer(&self.device_id)?;
|
||||
let (selem, name) = find_hardware_volume_control(&mixer, &self.device_id)?;
|
||||
let (min, max) = usable_volume_range(&selem, &self.device_id, &name)?;
|
||||
let volume = volume.clamp(0.0, 1.0);
|
||||
let target = min + (((max - min) as f32 * volume).round() as i64);
|
||||
|
||||
// Mixer controls live on the CARD ctl device, not on the PCM alias the
|
||||
// stream opened: `iec958:CARD=x,DEV=0` (HiFiBerry Digi, #331/#659),
|
||||
// `hdmi:`, `front:`… are PCM plugin ids the mixer can't attach to, and
|
||||
// a `DEV`-qualified `hw:` id isn't a valid ctl name either. Open the
|
||||
// mixer on the derived `hw:CARD=<name>` instead.
|
||||
let ctl_name = mixer_ctl_name(&self.device_id);
|
||||
let mixer = Mixer::new(&ctl_name, false).map_err(|e| {
|
||||
log::info!(
|
||||
"[ALSA Direct] Setting hardware volume via '{}': {:.0}% (raw: {}/{})",
|
||||
name,
|
||||
volume * 100.0,
|
||||
target,
|
||||
max
|
||||
);
|
||||
|
||||
// The ALSA helper addresses every playback channel the element owns
|
||||
// and, unlike the old hand-written five-channel loop, propagates a
|
||||
// write failure instead of reporting success after ignoring it.
|
||||
selem.set_playback_volume_all(target).map_err(|error| {
|
||||
format!(
|
||||
"Failed to open mixer for {} (ctl {}): {}",
|
||||
self.device_id, ctl_name, e
|
||||
"Failed to set ALSA hardware volume via '{}' for {}: {}",
|
||||
name, self.device_id, error
|
||||
)
|
||||
})?;
|
||||
|
||||
// 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
|
||||
@@ -956,6 +940,158 @@ impl AlsaDirectStream {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
fn open_hardware_mixer(device_id: &str) -> Result<alsa::mixer::Mixer, String> {
|
||||
use alsa::mixer::Mixer;
|
||||
|
||||
// Mixer controls live on the CARD ctl device, not on the PCM alias the
|
||||
// stream opened: `iec958:CARD=x,DEV=0` (HiFiBerry Digi, #331/#659),
|
||||
// `hdmi:`, `front:`… are PCM plugin ids the mixer can't attach to, and a
|
||||
// `DEV`-qualified `hw:` id isn't a valid ctl name either.
|
||||
let ctl_name = mixer_ctl_name(device_id);
|
||||
Mixer::new(&ctl_name, false).map_err(|error| {
|
||||
format!(
|
||||
"Failed to open mixer for {} (ctl {}): {}",
|
||||
device_id, ctl_name, error
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
/// Rank playback elements conservatively. ALSA devices are inconsistent:
|
||||
/// many expose `DAC` or `Line Out` instead of the five names the old code
|
||||
/// hard-coded. Capture/sidetone elements are never acceptable fallbacks.
|
||||
fn hardware_volume_rank(name: &str) -> u8 {
|
||||
let lower = name.to_ascii_lowercase();
|
||||
if ["capture", "mic", "boost", "sidetone", "loopback"]
|
||||
.iter()
|
||||
.any(|token| lower.contains(token))
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
[
|
||||
("master", 100),
|
||||
("pcm", 90),
|
||||
("speaker", 80),
|
||||
("headphone", 70),
|
||||
("digital", 60),
|
||||
("dac", 50),
|
||||
("line out", 40),
|
||||
("playback", 30),
|
||||
]
|
||||
.into_iter()
|
||||
.find_map(|(token, score)| lower.contains(token).then_some(score))
|
||||
.unwrap_or(1)
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
fn find_hardware_volume_control<'a>(
|
||||
mixer: &'a alsa::mixer::Mixer,
|
||||
device_id: &str,
|
||||
) -> Result<(alsa::mixer::Selem<'a>, String), String> {
|
||||
use alsa::mixer::Selem;
|
||||
|
||||
let mut candidates = mixer
|
||||
.iter()
|
||||
.filter_map(Selem::new)
|
||||
.filter(|selem| selem.has_playback_volume())
|
||||
.filter_map(|selem| {
|
||||
let name = selem.get_id().get_name().ok()?.to_string();
|
||||
let rank = hardware_volume_rank(&name);
|
||||
(rank > 0).then_some((rank, name, selem))
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
candidates.sort_by(|left, right| right.0.cmp(&left.0).then_with(|| left.1.cmp(&right.1)));
|
||||
|
||||
let Some((top_rank, _, _)) = candidates.first() else {
|
||||
return Err(format!(
|
||||
"No writable playback-volume control found for {}",
|
||||
device_id
|
||||
));
|
||||
};
|
||||
if candidates.get(1).is_some_and(|next| next.0 == *top_rank) {
|
||||
let names = candidates
|
||||
.iter()
|
||||
.filter(|candidate| candidate.0 == *top_rank)
|
||||
.map(|candidate| candidate.1.as_str())
|
||||
.collect::<Vec<_>>()
|
||||
.join(", ");
|
||||
return Err(format!(
|
||||
"Ambiguous playback-volume controls for {}: {}",
|
||||
device_id, names
|
||||
));
|
||||
}
|
||||
|
||||
let (_, name, selem) = candidates.remove(0);
|
||||
Ok((selem, name))
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
fn usable_volume_range(
|
||||
selem: &alsa::mixer::Selem<'_>,
|
||||
device_id: &str,
|
||||
control_name: &str,
|
||||
) -> Result<(i64, i64), String> {
|
||||
let (min, max) = selem.get_playback_volume_range();
|
||||
(max > min).then_some((min, max)).ok_or_else(|| {
|
||||
format!(
|
||||
"ALSA playback-volume control '{}' for {} has no usable range ({min}..{max})",
|
||||
control_name, device_id
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
/// Read-only capability probe used before the UI enables hardware volume.
|
||||
#[cfg(target_os = "linux")]
|
||||
pub fn probe_hardware_volume(device_id: &str) -> Result<HardwareVolumeInfo, String> {
|
||||
use alsa::mixer::SelemChannelId;
|
||||
|
||||
let mixer = open_hardware_mixer(device_id)?;
|
||||
let (selem, name) = find_hardware_volume_control(&mixer, device_id)?;
|
||||
let (min, max) = usable_volume_range(&selem, device_id, &name)?;
|
||||
let channel = SelemChannelId::all()
|
||||
.iter()
|
||||
.copied()
|
||||
.find(|channel| selem.has_playback_channel(*channel))
|
||||
.ok_or_else(|| {
|
||||
format!(
|
||||
"ALSA playback-volume control '{}' for {} has no playback channel",
|
||||
name, device_id
|
||||
)
|
||||
})?;
|
||||
let raw = selem.get_playback_volume(channel).map_err(|error| {
|
||||
format!(
|
||||
"Failed to read ALSA hardware volume via '{}' for {}: {}",
|
||||
name, device_id, error
|
||||
)
|
||||
})?;
|
||||
let volume = ((raw - min) as f32 / (max - min) as f32).clamp(0.0, 1.0);
|
||||
|
||||
Ok(HardwareVolumeInfo {
|
||||
control_name: name,
|
||||
volume,
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
pub fn probe_hardware_volume(_device_id: &str) -> Result<HardwareVolumeInfo, String> {
|
||||
Err("ALSA hardware volume is only available on Linux".to_string())
|
||||
}
|
||||
|
||||
/// Mirrors the exact route predicate used by the player: ALSA plus a direct
|
||||
/// device id and either the `hw` or `plughw` engine. ALSA's default/sysdefault
|
||||
/// and `Pcm` routes use CPAL/Rodio and retain software volume.
|
||||
pub fn uses_alsa_direct_route(audio: &crate::settings::AudioSettings) -> bool {
|
||||
audio.backend_type == Some(crate::backend::AudioBackendType::Alsa)
|
||||
&& audio.alsa_plugin.unwrap_or(crate::backend::AlsaPlugin::Hw)
|
||||
!= crate::backend::AlsaPlugin::Pcm
|
||||
&& audio
|
||||
.output_device
|
||||
.as_deref()
|
||||
.is_some_and(AlsaDirectStream::is_hw_device)
|
||||
}
|
||||
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
impl AlsaDirectStream {
|
||||
pub fn new(_device_id: &str, _sample_rate: u32, _channels: u16) -> Result<Self, String> {
|
||||
@@ -1027,7 +1163,9 @@ pub(crate) fn mixer_ctl_name(device_id: &str) -> String {
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::mixer_ctl_name;
|
||||
use super::{hardware_volume_rank, mixer_ctl_name, uses_alsa_direct_route};
|
||||
use crate::backend::{AlsaPlugin, AudioBackendType};
|
||||
use crate::settings::AudioSettings;
|
||||
|
||||
#[test]
|
||||
fn mixer_ctl_name_maps_card_forms() {
|
||||
@@ -1055,4 +1193,37 @@ mod tests {
|
||||
assert_eq!(mixer_ctl_name("default"), "default");
|
||||
assert_eq!(mixer_ctl_name("pulse"), "pulse");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hardware_volume_ranking_prefers_output_controls_and_rejects_capture_paths() {
|
||||
assert!(hardware_volume_rank("Master") > hardware_volume_rank("PCM"));
|
||||
assert!(hardware_volume_rank("PCM") > hardware_volume_rank("USB DAC"));
|
||||
assert!(hardware_volume_rank("Speaker Playback") > 1);
|
||||
assert_eq!(hardware_volume_rank("Mic Playback Volume"), 0);
|
||||
assert_eq!(hardware_volume_rank("Capture"), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn direct_route_requires_alsa_direct_device_and_non_pcm_plugin() {
|
||||
let mut audio = AudioSettings::default();
|
||||
assert!(!uses_alsa_direct_route(&audio));
|
||||
|
||||
audio.backend_type = Some(AudioBackendType::Alsa);
|
||||
audio.output_device = Some("front:CARD=USB,DEV=0".to_string());
|
||||
audio.alsa_plugin = Some(AlsaPlugin::Hw);
|
||||
assert!(uses_alsa_direct_route(&audio));
|
||||
|
||||
audio.alsa_plugin = Some(AlsaPlugin::PlugHw);
|
||||
assert!(uses_alsa_direct_route(&audio));
|
||||
|
||||
audio.alsa_plugin = Some(AlsaPlugin::Pcm);
|
||||
assert!(!uses_alsa_direct_route(&audio));
|
||||
|
||||
audio.alsa_plugin = Some(AlsaPlugin::Hw);
|
||||
audio.output_device = Some("sysdefault:CARD=USB".to_string());
|
||||
assert!(!uses_alsa_direct_route(&audio));
|
||||
|
||||
audio.output_device = None;
|
||||
assert!(!uses_alsa_direct_route(&audio));
|
||||
}
|
||||
}
|
||||
@@ -2077,8 +2077,14 @@ msgstr "Wie ALSA das Gerät öffnet – hw ist bit-perfect, plughw konvertiert."
|
||||
msgid "Hardware volume control"
|
||||
msgstr "Hardware-Lautstärkeregelung"
|
||||
|
||||
msgid "Use the ALSA mixer for volume instead of software gain."
|
||||
msgstr "Verwendet den ALSA-Mixer für die Lautstärke anstelle von Software-Gain."
|
||||
msgid "Control volume through a mixer exposed by the selected ALSA device. If unavailable, direct playback stays fixed at 100%."
|
||||
msgstr "Steuert die Lautstärke über einen Mixer, den das ausgewählte ALSA-Gerät bereitstellt. Ist keiner verfügbar, bleibt die direkte Wiedergabe fest auf 100 %."
|
||||
|
||||
msgid "This ALSA device has no compatible hardware volume control. Direct playback remains fixed at 100%."
|
||||
msgstr "Dieses ALSA-Gerät hat keine kompatible Hardware-Lautstärkeregelung. Die direkte Wiedergabe bleibt fest auf 100 %."
|
||||
|
||||
msgid "QBZ could not fully release the previous audio device. See the audio log for details."
|
||||
msgstr "QBZ konnte das vorherige Audiogerät nicht vollständig freigeben. Details stehen im Audioprotokoll."
|
||||
|
||||
msgid "BIT-PERFECT"
|
||||
msgstr "BIT-PERFECT"
|
||||
|
||||
@@ -1641,3 +1641,12 @@ msgstr "This album has no tracks."
|
||||
|
||||
msgid "Reactive Rings"
|
||||
msgstr "Reactive Rings"
|
||||
|
||||
msgid "Control volume through a mixer exposed by the selected ALSA device. If unavailable, direct playback stays fixed at 100%."
|
||||
msgstr "Control volume through a mixer exposed by the selected ALSA device. If unavailable, direct playback stays fixed at 100%."
|
||||
|
||||
msgid "This ALSA device has no compatible hardware volume control. Direct playback remains fixed at 100%."
|
||||
msgstr "This ALSA device has no compatible hardware volume control. Direct playback remains fixed at 100%."
|
||||
|
||||
msgid "QBZ could not fully release the previous audio device. See the audio log for details."
|
||||
msgstr "QBZ could not fully release the previous audio device. See the audio log for details."
|
||||
@@ -2077,8 +2077,14 @@ msgstr "Cómo ALSA abre el dispositivo: hw es bit-perfect, plughw convierte."
|
||||
msgid "Hardware volume control"
|
||||
msgstr "Control de volumen por hardware"
|
||||
|
||||
msgid "Use the ALSA mixer for volume instead of software gain."
|
||||
msgstr "Usa el mezclador de ALSA para el volumen en lugar de la ganancia por software."
|
||||
msgid "Control volume through a mixer exposed by the selected ALSA device. If unavailable, direct playback stays fixed at 100%."
|
||||
msgstr "Controla el volumen mediante un mezclador expuesto por el dispositivo ALSA seleccionado. Si no está disponible, la reproducción directa se mantiene fija al 100 %."
|
||||
|
||||
msgid "This ALSA device has no compatible hardware volume control. Direct playback remains fixed at 100%."
|
||||
msgstr "Este dispositivo ALSA no tiene un control de volumen por hardware compatible. La reproducción directa se mantiene fija al 100 %."
|
||||
|
||||
msgid "QBZ could not fully release the previous audio device. See the audio log for details."
|
||||
msgstr "QBZ no pudo liberar por completo el dispositivo de audio anterior. Consulta el registro de audio para ver los detalles."
|
||||
|
||||
msgid "BIT-PERFECT"
|
||||
msgstr "BIT-PERFECT"
|
||||
|
||||
@@ -2077,8 +2077,14 @@ msgstr "Comment ALSA ouvre le périphérique — hw est bit-perfect, plughw conv
|
||||
msgid "Hardware volume control"
|
||||
msgstr "Contrôle du volume matériel"
|
||||
|
||||
msgid "Use the ALSA mixer for volume instead of software gain."
|
||||
msgstr "Utilise le mixeur ALSA pour le volume au lieu du gain logiciel."
|
||||
msgid "Control volume through a mixer exposed by the selected ALSA device. If unavailable, direct playback stays fixed at 100%."
|
||||
msgstr "Contrôle le volume via un mixeur exposé par le périphérique ALSA sélectionné. S’il n’est pas disponible, la lecture directe reste fixée à 100 %."
|
||||
|
||||
msgid "This ALSA device has no compatible hardware volume control. Direct playback remains fixed at 100%."
|
||||
msgstr "Ce périphérique ALSA ne possède aucun contrôle matériel du volume compatible. La lecture directe reste fixée à 100 %."
|
||||
|
||||
msgid "QBZ could not fully release the previous audio device. See the audio log for details."
|
||||
msgstr "QBZ n’a pas pu libérer complètement le périphérique audio précédent. Consultez le journal audio pour plus de détails."
|
||||
|
||||
msgid "BIT-PERFECT"
|
||||
msgstr "BIT-PERFECT"
|
||||
|
||||
@@ -2010,8 +2010,14 @@ msgstr "ALSAがデバイスを開く方法 — hwはビットパーフェクト
|
||||
msgid "Hardware volume control"
|
||||
msgstr "ハードウェア音量コントロール"
|
||||
|
||||
msgid "Use the ALSA mixer for volume instead of software gain."
|
||||
msgstr "ソフトウェアゲインの代わりにALSAミキサーで音量を調整します。"
|
||||
msgid "Control volume through a mixer exposed by the selected ALSA device. If unavailable, direct playback stays fixed at 100%."
|
||||
msgstr "選択したALSAデバイスが提供するミキサーで音量を調整します。利用できない場合、ダイレクト再生の音量は100%に固定されます。"
|
||||
|
||||
msgid "This ALSA device has no compatible hardware volume control. Direct playback remains fixed at 100%."
|
||||
msgstr "このALSAデバイスには互換性のあるハードウェア音量コントロールがありません。ダイレクト再生の音量は100%に固定されます。"
|
||||
|
||||
msgid "QBZ could not fully release the previous audio device. See the audio log for details."
|
||||
msgstr "QBZは以前のオーディオデバイスを完全に解放できませんでした。詳細はオーディオログを確認してください。"
|
||||
|
||||
msgid "BIT-PERFECT"
|
||||
msgstr "ビットパーフェクト"
|
||||
|
||||
@@ -2073,8 +2073,14 @@ msgstr "Hoe ALSA het apparaat opent — hw is bit-perfect, plughw converteert."
|
||||
msgid "Hardware volume control"
|
||||
msgstr "Hardware-volumeregeling"
|
||||
|
||||
msgid "Use the ALSA mixer for volume instead of software gain."
|
||||
msgstr "Gebruik de ALSA-mixer voor volume in plaats van software-versterking."
|
||||
msgid "Control volume through a mixer exposed by the selected ALSA device. If unavailable, direct playback stays fixed at 100%."
|
||||
msgstr "Regel het volume via een mixer die door het geselecteerde ALSA-apparaat wordt aangeboden. Als die niet beschikbaar is, blijft directe weergave vast op 100%."
|
||||
|
||||
msgid "This ALSA device has no compatible hardware volume control. Direct playback remains fixed at 100%."
|
||||
msgstr "Dit ALSA-apparaat heeft geen compatibele hardwarevolumeregeling. Directe weergave blijft vast op 100%."
|
||||
|
||||
msgid "QBZ could not fully release the previous audio device. See the audio log for details."
|
||||
msgstr "QBZ kon het vorige audioapparaat niet volledig vrijgeven. Bekijk het audiologboek voor details."
|
||||
|
||||
msgid "BIT-PERFECT"
|
||||
msgstr "BIT-PERFECT"
|
||||
|
||||
@@ -2077,8 +2077,14 @@ msgstr "Como o ALSA abre o dispositivo — hw é bit-perfect, plughw converte."
|
||||
msgid "Hardware volume control"
|
||||
msgstr "Controlo de volume por hardware"
|
||||
|
||||
msgid "Use the ALSA mixer for volume instead of software gain."
|
||||
msgstr "Usa o mixer do ALSA para o volume em vez do ganho por software."
|
||||
msgid "Control volume through a mixer exposed by the selected ALSA device. If unavailable, direct playback stays fixed at 100%."
|
||||
msgstr "Controla o volume por meio de um mixer disponibilizado pelo dispositivo ALSA selecionado. Se não estiver disponível, a reprodução direta permanece fixa em 100%."
|
||||
|
||||
msgid "This ALSA device has no compatible hardware volume control. Direct playback remains fixed at 100%."
|
||||
msgstr "Este dispositivo ALSA não possui um controle de volume por hardware compatível. A reprodução direta permanece fixa em 100%."
|
||||
|
||||
msgid "QBZ could not fully release the previous audio device. See the audio log for details."
|
||||
msgstr "O QBZ não conseguiu liberar completamente o dispositivo de áudio anterior. Consulte o log de áudio para obter detalhes."
|
||||
|
||||
msgid "BIT-PERFECT"
|
||||
msgstr "BIT-PERFECT"
|
||||
|
||||
@@ -2014,8 +2014,14 @@ msgstr "Как ALSA открывает устройство — hw обеспе
|
||||
msgid "Hardware volume control"
|
||||
msgstr "Аппаратное управление громкостью"
|
||||
|
||||
msgid "Use the ALSA mixer for volume instead of software gain."
|
||||
msgstr "Использовать микшер ALSA для громкости вместо программного усиления."
|
||||
msgid "Control volume through a mixer exposed by the selected ALSA device. If unavailable, direct playback stays fixed at 100%."
|
||||
msgstr "Управляет громкостью через микшер выбранного устройства ALSA. Если он недоступен, громкость прямого воспроизведения остаётся на уровне 100 %."
|
||||
|
||||
msgid "This ALSA device has no compatible hardware volume control. Direct playback remains fixed at 100%."
|
||||
msgstr "У этого устройства ALSA нет совместимого аппаратного регулятора громкости. Громкость прямого воспроизведения остаётся на уровне 100 %."
|
||||
|
||||
msgid "QBZ could not fully release the previous audio device. See the audio log for details."
|
||||
msgstr "QBZ не удалось полностью освободить предыдущее аудиоустройство. Подробности смотрите в журнале аудио."
|
||||
|
||||
msgid "BIT-PERFECT"
|
||||
msgstr "БИТ-ПЕРФЕКТ"
|
||||
|
||||
@@ -16,7 +16,7 @@ mod types;
|
||||
pub use types::{xesam_url_for, MediaEvent, MediaIntegration, PlaybackStatus, TrackMeta};
|
||||
|
||||
pub mod notify;
|
||||
pub use notify::{show_track_notification, NotificationMeta};
|
||||
pub use notify::{show_track_notification, withdraw_track_notification, NotificationMeta};
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
mod inhibit;
|
||||
|
||||
@@ -20,6 +20,19 @@
|
||||
|
||||
use std::path::PathBuf;
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
const PORTAL_NOTIFICATION_ID: &str = "track-now-playing";
|
||||
|
||||
/// Serializes portal mutations and invalidates slow, stale artwork jobs. A
|
||||
/// track-A notification can spend seconds downloading its cover while track B
|
||||
/// starts (or playback stops); without this generation check A may overwrite B
|
||||
/// or resurrect the notification after it was withdrawn.
|
||||
#[cfg(target_os = "linux")]
|
||||
static PORTAL_NOTIFICATION_GENERATION: std::sync::atomic::AtomicU64 =
|
||||
std::sync::atomic::AtomicU64::new(0);
|
||||
#[cfg(target_os = "linux")]
|
||||
static PORTAL_NOTIFICATION_GATE: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());
|
||||
|
||||
/// Everything needed to render a track-change notification. The crate formats
|
||||
/// the body + quality line itself so the output matches the Tauri notification
|
||||
/// exactly, regardless of frontend.
|
||||
@@ -249,11 +262,25 @@ pub async fn show_track_notification(meta: NotificationMeta, offline: bool) {
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
{
|
||||
use ashpd::desktop::notification::{Notification as PortalNotification, NotificationProxy};
|
||||
use ashpd::desktop::notification::{
|
||||
DisplayHint, Notification as PortalNotification, NotificationProxy,
|
||||
};
|
||||
use ashpd::desktop::Icon;
|
||||
use std::sync::atomic::Ordering;
|
||||
|
||||
let mut notification =
|
||||
PortalNotification::new(&meta.title).body(Some(body.as_str()));
|
||||
let generation = PORTAL_NOTIFICATION_GENERATION
|
||||
.fetch_add(1, Ordering::AcqRel)
|
||||
.wrapping_add(1);
|
||||
|
||||
// One stable id intentionally replaces the previous track toast. The
|
||||
// portal normally treats that as an in-place update, which Plasma does
|
||||
// not animate as a new banner after the first track. `show-as-new` is
|
||||
// the portal's explicit contract for a replacement that must be
|
||||
// presented again. It must not be combined with `transient`; stop,
|
||||
// opt-out and shutdown withdraw the replaceable notification below.
|
||||
let mut notification = PortalNotification::new(&meta.title)
|
||||
.body(Some(body.as_str()))
|
||||
.display_hint([DisplayHint::ShowAsNew]);
|
||||
|
||||
if let Some(url) = meta.art_url.clone() {
|
||||
let prepared = tokio::task::spawn_blocking(move || -> Result<Vec<u8>, String> {
|
||||
@@ -273,11 +300,17 @@ pub async fn show_track_notification(meta: NotificationMeta, offline: bool) {
|
||||
|
||||
match NotificationProxy::new().await {
|
||||
Ok(proxy) => {
|
||||
if let Err(e) = proxy
|
||||
.add_notification("track-now-playing", notification)
|
||||
let _guard = PORTAL_NOTIFICATION_GATE.lock().await;
|
||||
if PORTAL_NOTIFICATION_GENERATION.load(Ordering::Acquire) != generation {
|
||||
log::debug!("[notify] stale track notification discarded");
|
||||
return;
|
||||
}
|
||||
match proxy
|
||||
.add_notification(PORTAL_NOTIFICATION_ID, notification)
|
||||
.await
|
||||
{
|
||||
log::warn!("[notify] XDG portal add_notification failed: {e}");
|
||||
Ok(()) => log::debug!("[notify] XDG portal notification published"),
|
||||
Err(e) => log::warn!("[notify] XDG portal add_notification failed: {e}"),
|
||||
}
|
||||
}
|
||||
Err(e) => log::warn!("[notify] XDG notification portal unavailable: {e}"),
|
||||
@@ -314,3 +347,33 @@ pub async fn show_track_notification(meta: NotificationMeta, offline: bool) {
|
||||
log::info!("[notify] desktop notifications not implemented on this platform");
|
||||
}
|
||||
}
|
||||
|
||||
/// Withdraw the active Linux portal notification, if any. This also
|
||||
/// invalidates an in-flight artwork preparation so it cannot publish after a
|
||||
/// stop or process shutdown. Other platforms currently have no replaceable
|
||||
/// notification handle, so this is a deliberate no-op there.
|
||||
pub async fn withdraw_track_notification() {
|
||||
#[cfg(target_os = "linux")]
|
||||
{
|
||||
use ashpd::desktop::notification::NotificationProxy;
|
||||
use std::sync::atomic::Ordering;
|
||||
|
||||
let generation = PORTAL_NOTIFICATION_GENERATION
|
||||
.fetch_add(1, Ordering::AcqRel)
|
||||
.wrapping_add(1);
|
||||
let proxy = match NotificationProxy::new().await {
|
||||
Ok(proxy) => proxy,
|
||||
Err(e) => {
|
||||
log::debug!("[notify] XDG notification portal unavailable during withdrawal: {e}");
|
||||
return;
|
||||
}
|
||||
};
|
||||
let _guard = PORTAL_NOTIFICATION_GATE.lock().await;
|
||||
if PORTAL_NOTIFICATION_GENERATION.load(Ordering::Acquire) != generation {
|
||||
return;
|
||||
}
|
||||
if let Err(e) = proxy.remove_notification(PORTAL_NOTIFICATION_ID).await {
|
||||
log::debug!("[notify] XDG portal remove_notification failed: {e}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -47,6 +47,17 @@ pub enum CoreEvent {
|
||||
/// Repeat mode changed
|
||||
RepeatModeChanged { mode: crate::playback::RepeatMode },
|
||||
|
||||
// ============ Qobuz Connect Events ============
|
||||
/// Qobuz Connect session lifecycle changed (headless renderer)
|
||||
QconnectSessionChanged {
|
||||
/// "off" | "connecting" | "connected" | "retrying" | "exhausted"
|
||||
state: String,
|
||||
/// The advertised renderer name, when one is set
|
||||
device_name: Option<String>,
|
||||
/// True only while a session is established ("connected")
|
||||
session_active: bool,
|
||||
},
|
||||
|
||||
// ============ Authentication Events ============
|
||||
/// User logged in successfully
|
||||
LoggedIn { session: UserSession },
|
||||
|
||||
@@ -102,7 +102,9 @@ enum AudioCommand {
|
||||
/// stream (freeing an exclusive ALSA `hw:` grab + its D-Bus reservation)
|
||||
/// and un-suspends / un-forces anything QBZ parked, so PipeWire can
|
||||
/// reclaim a device QBZ was holding. User-triggered from settings.
|
||||
ReleaseDevice,
|
||||
ReleaseDevice {
|
||||
completed: SyncSender<Result<(), String>>,
|
||||
},
|
||||
/// Append next track to current engine for gapless playback (Rodio only)
|
||||
PlayNext {
|
||||
data: Vec<u8>,
|
||||
@@ -438,6 +440,7 @@ fn create_output_stream_with_config(
|
||||
sample_rate: u32,
|
||||
channels: u16,
|
||||
exclusive_mode: bool,
|
||||
state: SharedState,
|
||||
) -> Result<MixerDeviceSink, String> {
|
||||
log::info!(
|
||||
"Creating MixerDeviceSink: {}Hz, {} channels, exclusive: {}",
|
||||
@@ -508,9 +511,25 @@ fn create_output_stream_with_config(
|
||||
// Create MixerDeviceSink with custom config
|
||||
match DeviceSinkBuilder::from_device(device) {
|
||||
Ok(builder) => {
|
||||
// rodio's default error callback only eprintln!s a live stream
|
||||
// error (e.g. an ALSA buffer underrun mid-playback), so playback
|
||||
// dies without the driver ever seeing a message to latch. Record
|
||||
// it on the shared state instead so it drains to the event bus as
|
||||
// a PlaybackError. Rate-limited: ALSA can repeat EPIPE every
|
||||
// period on a wedged device, and each recorded message is one
|
||||
// bus event (and one forked hook script) after the drain.
|
||||
let mut last_reported: Option<std::time::Instant> = None;
|
||||
match builder
|
||||
.with_supported_config(&supported_config)
|
||||
.with_buffer_size(cpal_buffer_size)
|
||||
.with_error_callback(move |err| {
|
||||
log::error!("Audio stream error: {err}");
|
||||
let now = std::time::Instant::now();
|
||||
if last_reported.map_or(true, |t| now.duration_since(t).as_secs() >= 5) {
|
||||
last_reported = Some(now);
|
||||
state.record_stream_error(format!("Audio stream error: {err}"));
|
||||
}
|
||||
})
|
||||
.open_stream()
|
||||
{
|
||||
Ok(mixer_sink) => {
|
||||
@@ -1994,6 +2013,7 @@ impl Player {
|
||||
sample_rate,
|
||||
channels,
|
||||
dac_passthrough,
|
||||
thread_state.clone(),
|
||||
)
|
||||
.map(StreamType::rodio)
|
||||
};
|
||||
@@ -2085,6 +2105,7 @@ impl Player {
|
||||
sample_rate,
|
||||
channels,
|
||||
dac_passthrough,
|
||||
thread_state.clone(),
|
||||
)
|
||||
.map(StreamType::rodio)
|
||||
};
|
||||
@@ -2513,6 +2534,7 @@ impl Player {
|
||||
sample_rate,
|
||||
channels,
|
||||
dac_passthrough,
|
||||
thread_state.clone(),
|
||||
)
|
||||
.map(StreamType::rodio)
|
||||
};
|
||||
@@ -2587,6 +2609,7 @@ impl Player {
|
||||
sample_rate,
|
||||
channels,
|
||||
dac_passthrough,
|
||||
thread_state.clone(),
|
||||
)
|
||||
.map(StreamType::rodio)
|
||||
};
|
||||
@@ -3785,6 +3808,35 @@ impl Player {
|
||||
drop(stream_opt.take());
|
||||
log::info!("Audio thread: previous stream dropped, device released");
|
||||
|
||||
// ReloadSettings updates `thread_settings` before
|
||||
// this command is queued. When the NEW route is no
|
||||
// longer ALSA Direct, finish the teardown the same
|
||||
// way ReleaseDevice does: dropping the PCM alone
|
||||
// releases the fd/reservation but leaves the
|
||||
// PipeWire sink QBZ suspended. Keep it suspended
|
||||
// for direct->direct reinitialization so PipeWire
|
||||
// cannot race the immediate exclusive reopen.
|
||||
#[cfg(target_os = "linux")]
|
||||
{
|
||||
let next_is_alsa_direct = thread_settings
|
||||
.lock()
|
||||
.ok()
|
||||
.map(|settings| {
|
||||
qbz_audio::alsa_direct::uses_alsa_direct_route(&settings)
|
||||
})
|
||||
.unwrap_or(false);
|
||||
if !next_is_alsa_direct {
|
||||
if let Err(error) =
|
||||
qbz_audio::alsa_backend::resume_suspended_sink()
|
||||
{
|
||||
log::warn!(
|
||||
"Audio thread: release during reinit was incomplete: {error}"
|
||||
);
|
||||
}
|
||||
}
|
||||
qbz_audio::pipewire_backend::PipeWireBackend::reset_pipewire_clock();
|
||||
}
|
||||
|
||||
std::thread::sleep(Duration::from_millis(100));
|
||||
|
||||
*current_device_name = new_device;
|
||||
@@ -3809,7 +3861,7 @@ impl Player {
|
||||
// Keep current_audio_data and current_streaming_source
|
||||
// intact so Resume can recreate the engine and seek.
|
||||
}
|
||||
AudioCommand::ReleaseDevice => {
|
||||
AudioCommand::ReleaseDevice { completed } => {
|
||||
log::info!("Audio thread: releasing output device (user-requested)");
|
||||
// Cancel any deferred drop and tear the stream down NOW so
|
||||
// the device is freed immediately (no warm-stream lingering).
|
||||
@@ -3823,15 +3875,19 @@ impl Player {
|
||||
// apps after bit-perfect ALSA Direct held it exclusively).
|
||||
// Both calls are self-gating no-ops if QBZ didn't set them.
|
||||
#[cfg(target_os = "linux")]
|
||||
{
|
||||
qbz_audio::alsa_backend::resume_suspended_sink();
|
||||
let release_result = {
|
||||
let result = qbz_audio::alsa_backend::resume_suspended_sink();
|
||||
qbz_audio::pipewire_backend::PipeWireBackend::reset_pipewire_clock();
|
||||
}
|
||||
result
|
||||
};
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
let release_result = Ok(());
|
||||
thread_state.pause_playback_timer();
|
||||
thread_state.is_playing.store(false, Ordering::SeqCst);
|
||||
// Keep current_audio_data / current_streaming_source intact
|
||||
// so a later Play / Resume reopens and continues.
|
||||
log::info!("Audio thread: output device released");
|
||||
let _ = completed.send(release_result);
|
||||
}
|
||||
AudioCommand::PlayNext {
|
||||
data,
|
||||
@@ -4480,7 +4536,7 @@ impl Player {
|
||||
// above), so resume any PipeWire sink we suspended for
|
||||
// exclusive access — self-gating no-op otherwise (#263).
|
||||
#[cfg(target_os = "linux")]
|
||||
qbz_audio::alsa_backend::resume_suspended_sink();
|
||||
let _ = qbz_audio::alsa_backend::resume_suspended_sink();
|
||||
log::info!("Audio thread: suspended stream after pause");
|
||||
continue;
|
||||
}
|
||||
@@ -6079,6 +6135,19 @@ impl Player {
|
||||
.map_err(|e| format!("Failed to send volume command: {}", e))
|
||||
}
|
||||
|
||||
/// Seed the volume state for an imminent engine rebuild without touching
|
||||
/// the currently open output. Settings uses this when enabling ALSA
|
||||
/// hardware volume: it samples the physical mixer first, stores that level
|
||||
/// here, then reinitializes the direct engine. Sending `SetVolume` instead
|
||||
/// would write the new device's sampled level through the *old* device's
|
||||
/// still-live hardware mixer before the reinit command reached the audio
|
||||
/// thread.
|
||||
pub fn seed_volume_state(&self, volume: f32) {
|
||||
self.state
|
||||
.volume
|
||||
.store(volume.clamp(0.0, 1.0).to_bits(), Ordering::SeqCst);
|
||||
}
|
||||
|
||||
/// Seek to position in seconds
|
||||
pub fn seek(&self, position: u64) -> Result<(), String> {
|
||||
// Clamp to duration if known
|
||||
@@ -6110,9 +6179,15 @@ impl Player {
|
||||
/// with a device re-enumeration in the UI to surface a freed or
|
||||
/// hot-plugged DAC without restarting the app.
|
||||
pub fn release_device(&self) -> Result<(), String> {
|
||||
let (completed_tx, completed_rx) = mpsc::sync_channel(1);
|
||||
self.tx
|
||||
.send(AudioCommand::ReleaseDevice)
|
||||
.map_err(|e| format!("Failed to send release command: {}", e))
|
||||
.send(AudioCommand::ReleaseDevice {
|
||||
completed: completed_tx,
|
||||
})
|
||||
.map_err(|e| format!("Failed to send release command: {}", e))?;
|
||||
completed_rx
|
||||
.recv_timeout(Duration::from_secs(5))
|
||||
.map_err(|error| format!("Timed out waiting for audio-device release: {error}"))?
|
||||
}
|
||||
|
||||
/// Reload audio settings from fresh config (e.g., after database update)
|
||||
|
||||
@@ -1775,6 +1775,38 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn repeat_all_wraps_a_local_album_for_renderer_advance() {
|
||||
let queue = QueueManager::new();
|
||||
for id in 1..=3 {
|
||||
let mut track = create_test_track(id);
|
||||
track.is_local = true;
|
||||
track.source = Some("local".to_string());
|
||||
queue.add_track(track);
|
||||
}
|
||||
queue.play_index(2);
|
||||
queue.set_repeat(RepeatMode::All);
|
||||
|
||||
let wrapped = queue.next().expect("repeat-all must wrap the album");
|
||||
assert_eq!(wrapped.id, 1);
|
||||
assert_eq!(queue.current_track().map(|track| track.id), Some(1));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn repeat_one_returns_the_same_local_track_for_renderer_advance() {
|
||||
let queue = QueueManager::new();
|
||||
let mut track = create_test_track(7);
|
||||
track.is_local = true;
|
||||
track.source = Some("local".to_string());
|
||||
queue.add_track(track);
|
||||
queue.play_index(0);
|
||||
queue.set_repeat(RepeatMode::One);
|
||||
|
||||
let repeated = queue.next().expect("repeat-one must replay the current row");
|
||||
assert_eq!(repeated.id, 7);
|
||||
assert_eq!(queue.current_track().map(|track| track.id), Some(7));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_clear_without_current_track() {
|
||||
let queue = QueueManager::new();
|
||||
@@ -2189,6 +2221,44 @@ mod tests {
|
||||
assert_eq!(track.id, 4);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn idle_queue_promotes_first_row_for_transport_play() {
|
||||
let queue = QueueManager::new();
|
||||
queue.set_queue(vec![create_test_track(99)], Some(0));
|
||||
queue.clear(false);
|
||||
|
||||
// All three enqueue actions keep an idle list cursor-less. "Later"
|
||||
// and "Next" form the manual block ahead of a plain queued row.
|
||||
queue.add_track(create_test_track(1));
|
||||
queue.add_track_later(create_test_track(2));
|
||||
queue.add_track_next(create_test_track(3));
|
||||
|
||||
let idle = queue.get_state_full();
|
||||
assert!(idle.current_track.is_none());
|
||||
assert_eq!(
|
||||
idle.upcoming.iter().map(|track| track.id).collect::<Vec<_>>(),
|
||||
vec![3, 2, 1]
|
||||
);
|
||||
|
||||
let promoted = queue
|
||||
.play_upcoming_at_preserving_timeline(0, 3)
|
||||
.expect("first idle row");
|
||||
assert_eq!(promoted.id, 3);
|
||||
|
||||
let playing = queue.get_state_full();
|
||||
assert_eq!(playing.current_track.expect("current").id, 3);
|
||||
assert_eq!(
|
||||
playing
|
||||
.upcoming
|
||||
.iter()
|
||||
.map(|track| track.id)
|
||||
.collect::<Vec<_>>(),
|
||||
vec![2, 1]
|
||||
);
|
||||
assert!(playing.history.is_empty());
|
||||
assert_eq!(playing.manual_next_count, 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn peek_previous_matches_previous_without_consuming_history() {
|
||||
let queue = QueueManager::new();
|
||||
|
||||
@@ -317,8 +317,8 @@ fn build_rhi_items() {
|
||||
let moc = qtbuild.moc(&header, qt_build_utils::MocArguments::default());
|
||||
cc.file(source).file(&moc.cpp);
|
||||
}
|
||||
// Plain helper, no QObject/moc: registers one script-specific bundled
|
||||
// font through QFontDatabase before Main.qml constructs any text.
|
||||
// Plain helper, no QObject/moc: registers script-specific bundled font
|
||||
// fallbacks through QFontDatabase before Main.qml constructs any text.
|
||||
println!("cargo:rerun-if-changed=cxx/font_fallback.cpp");
|
||||
cc.file("cxx/font_fallback.cpp");
|
||||
// Plain helper, no QObject/moc: enumerates the exact QVulkanInstance that
|
||||
|
||||
@@ -73,3 +73,27 @@ extern "C" bool qbz_register_devanagari_fallback()
|
||||
installFontMessageFilter();
|
||||
return true;
|
||||
}
|
||||
|
||||
extern "C" bool qbz_register_japanese_fallback()
|
||||
{
|
||||
// LINE Seed JP is already bundled as a selectable UI/lyrics face. Make
|
||||
// it Qt's deterministic fallback for the three scripts used by Japanese
|
||||
// text as well. Without this, a Latin-only choice such as Source Sans 3
|
||||
// delegates to the host's first fontconfig match; a user-installed
|
||||
// MS Gothic can therefore receive synthetic Medium/Bold and render much
|
||||
// heavier than the surrounding UI.
|
||||
const auto id = QFontDatabase::addApplicationFont(QStringLiteral(
|
||||
":/qt/qml/com/blitzfc/qbz/qml/assets/fonts/"
|
||||
"LINESeedJP-Regular.ttf"));
|
||||
if (id < 0)
|
||||
return false;
|
||||
|
||||
const auto families = QFontDatabase::applicationFontFamilies(id);
|
||||
if (families.isEmpty())
|
||||
return false;
|
||||
const auto &family = families.constFirst();
|
||||
QFontDatabase::addApplicationFallbackFontFamily(QChar::Script_Han, family);
|
||||
QFontDatabase::addApplicationFallbackFontFamily(QChar::Script_Hiragana, family);
|
||||
QFontDatabase::addApplicationFallbackFontFamily(QChar::Script_Katakana, family);
|
||||
return true;
|
||||
}
|
||||
@@ -20,8 +20,8 @@
|
||||
// Hence this document: `QQmlApplicationEngine::load` returns with its
|
||||
// FontLoader already in the font database (verified: the family is present
|
||||
// the instant load() returns), so main.rs can set the application font in the
|
||||
// gap between this document and Main.qml. "System" maps to an empty source:
|
||||
// no UI family is loaded and Qt keeps the operating-system default.
|
||||
// gap between this document and Main.qml. "System" leaves the Loader inactive:
|
||||
// no empty URL is assigned and Qt keeps the operating-system default.
|
||||
//
|
||||
// It is deliberately NON-VISUAL — a QtObject, not a Window — so loading it
|
||||
// adds a root object and nothing else.
|
||||
@@ -46,7 +46,11 @@ QtObject {
|
||||
return "assets/fonts/SourceSans3-VariableFont_wght.ttf"
|
||||
return ""
|
||||
}
|
||||
readonly property FontLoader selected: FontLoader {
|
||||
source: root.selectedSource
|
||||
readonly property Component selectedComponent: Component {
|
||||
FontLoader { source: root.selectedSource }
|
||||
}
|
||||
readonly property Loader selected: Loader {
|
||||
active: root.selectedSource !== ""
|
||||
sourceComponent: root.selectedComponent
|
||||
}
|
||||
}
|
||||
@@ -58,17 +58,26 @@ Item {
|
||||
Math.min(root.width * 0.026, 48)))
|
||||
|
||||
readonly property string fontDir: "qrc:/qt/qml/com/blitzfc/qbz/qml/assets/fonts/"
|
||||
FontLoader { id: fLineSeed; source: QbzLyrics.fontIndex === 1 ? root.fontDir + "LINESeedJP-Regular.ttf" : "" }
|
||||
FontLoader { id: fMontserrat; source: QbzLyrics.fontIndex === 2 ? root.fontDir + "Montserrat-VariableFont_wght.ttf" : "" }
|
||||
FontLoader { id: fNoto; source: QbzLyrics.fontIndex === 3 ? root.fontDir + "NotoSans-VariableFont_wdth,wght.ttf" : "" }
|
||||
FontLoader { id: fSource; source: QbzLyrics.fontIndex === 4 ? root.fontDir + "SourceSans3-VariableFont_wght.ttf" : "" }
|
||||
readonly property string fontFamily: {
|
||||
if (QbzLyrics.fontIndex === 1) return fLineSeed.status === FontLoader.Ready ? fLineSeed.name : ""
|
||||
if (QbzLyrics.fontIndex === 2) return fMontserrat.status === FontLoader.Ready ? fMontserrat.name : ""
|
||||
if (QbzLyrics.fontIndex === 3) return fNoto.status === FontLoader.Ready ? fNoto.name : ""
|
||||
if (QbzLyrics.fontIndex === 4) return fSource.status === FontLoader.Ready ? fSource.name : ""
|
||||
readonly property string fontSource: {
|
||||
if (QbzLyrics.fontIndex === 1) return root.fontDir + "LINESeedJP-Regular.ttf"
|
||||
if (QbzLyrics.fontIndex === 2) return root.fontDir + "Montserrat-VariableFont_wght.ttf"
|
||||
if (QbzLyrics.fontIndex === 3) return root.fontDir + "NotoSans-VariableFont_wdth,wght.ttf"
|
||||
if (QbzLyrics.fontIndex === 4) return root.fontDir + "SourceSans3-VariableFont_wght.ttf"
|
||||
return ""
|
||||
}
|
||||
Component {
|
||||
id: fontLoaderComponent
|
||||
FontLoader { source: root.fontSource }
|
||||
}
|
||||
Loader {
|
||||
id: selectedFontLoader
|
||||
active: root.fontSource !== ""
|
||||
sourceComponent: fontLoaderComponent
|
||||
}
|
||||
readonly property string fontFamily:
|
||||
selectedFontLoader.item
|
||||
&& selectedFontLoader.item.status === FontLoader.Ready
|
||||
? selectedFontLoader.item.name : ""
|
||||
|
||||
// --- Entry-animation retrigger (:57-74) --------------------------------
|
||||
readonly property int watchedIndex: root.activeIndex
|
||||
|
||||
@@ -86,17 +86,26 @@ Item {
|
||||
1.0 - root.ambientPrimary.b, 1.0), 1.18)
|
||||
|
||||
readonly property string fontDir: "qrc:/qt/qml/com/blitzfc/qbz/qml/assets/fonts/"
|
||||
FontLoader { id: fLineSeed; source: QbzLyrics.fontIndex === 1 ? root.fontDir + "LINESeedJP-Regular.ttf" : "" }
|
||||
FontLoader { id: fMontserrat; source: QbzLyrics.fontIndex === 2 ? root.fontDir + "Montserrat-VariableFont_wght.ttf" : "" }
|
||||
FontLoader { id: fNoto; source: QbzLyrics.fontIndex === 3 ? root.fontDir + "NotoSans-VariableFont_wdth,wght.ttf" : "" }
|
||||
FontLoader { id: fSource; source: QbzLyrics.fontIndex === 4 ? root.fontDir + "SourceSans3-VariableFont_wght.ttf" : "" }
|
||||
readonly property string lyricFontFamily: {
|
||||
if (QbzLyrics.fontIndex === 1) return fLineSeed.status === FontLoader.Ready ? fLineSeed.name : ""
|
||||
if (QbzLyrics.fontIndex === 2) return fMontserrat.status === FontLoader.Ready ? fMontserrat.name : ""
|
||||
if (QbzLyrics.fontIndex === 3) return fNoto.status === FontLoader.Ready ? fNoto.name : ""
|
||||
if (QbzLyrics.fontIndex === 4) return fSource.status === FontLoader.Ready ? fSource.name : ""
|
||||
readonly property string fontSource: {
|
||||
if (QbzLyrics.fontIndex === 1) return root.fontDir + "LINESeedJP-Regular.ttf"
|
||||
if (QbzLyrics.fontIndex === 2) return root.fontDir + "Montserrat-VariableFont_wght.ttf"
|
||||
if (QbzLyrics.fontIndex === 3) return root.fontDir + "NotoSans-VariableFont_wdth,wght.ttf"
|
||||
if (QbzLyrics.fontIndex === 4) return root.fontDir + "SourceSans3-VariableFont_wght.ttf"
|
||||
return ""
|
||||
}
|
||||
Component {
|
||||
id: fontLoaderComponent
|
||||
FontLoader { source: root.fontSource }
|
||||
}
|
||||
Loader {
|
||||
id: selectedFontLoader
|
||||
active: root.fontSource !== ""
|
||||
sourceComponent: fontLoaderComponent
|
||||
}
|
||||
readonly property string lyricFontFamily:
|
||||
selectedFontLoader.item
|
||||
&& selectedFontLoader.item.status === FontLoader.Ready
|
||||
? selectedFontLoader.item.name : ""
|
||||
|
||||
function fmt(sec) {
|
||||
sec = Math.max(0, Math.floor(sec))
|
||||
|
||||
@@ -70,6 +70,7 @@ Rectangle {
|
||||
readonly property int timeFont: root.compactMode ? 10 : 11
|
||||
|
||||
readonly property bool hasTrack: QbzPlayer.npHasTrack
|
||||
readonly property bool canPlay: root.hasTrack || QbzQueue.hasPlayTarget
|
||||
|
||||
// --- The pending-seek machine (:214-249) -------------------------------
|
||||
// All three constants are load-bearing: the -1.0 SENTINEL (every test is
|
||||
@@ -273,6 +274,7 @@ Rectangle {
|
||||
icSkip: root.icSkip
|
||||
icPlay: root.icPlay
|
||||
btnEnabled: root.hasTrack
|
||||
playEnabled: root.canPlay
|
||||
}
|
||||
|
||||
// The capsule (:322-327): right-aligned, vertically centred
|
||||
@@ -394,6 +396,7 @@ Rectangle {
|
||||
icSkip: 9
|
||||
icPlay: 9
|
||||
btnEnabled: root.hasTrack
|
||||
playEnabled: root.canPlay
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -28,6 +28,9 @@ Row {
|
||||
property int gap: 18
|
||||
/// Gated on `NowPlayingState.has-track` by the footer (:315).
|
||||
property bool btnEnabled: true
|
||||
/// Play additionally accepts an idle, populated queue. The other four
|
||||
/// controls remain tied to a real current track.
|
||||
property bool playEnabled: root.btnEnabled
|
||||
|
||||
spacing: root.gap
|
||||
|
||||
@@ -50,7 +53,7 @@ Row {
|
||||
name: QbzPlayer.npPlaying ? "pause" : "play-fill"
|
||||
iconSize: root.icPlay
|
||||
btn: root.btn
|
||||
btnEnabled: root.btnEnabled
|
||||
btnEnabled: root.playEnabled
|
||||
onClicked: QbzPlayer.togglePlay()
|
||||
}
|
||||
TBtn {
|
||||
|
||||
@@ -141,9 +141,9 @@ Column {
|
||||
}
|
||||
}
|
||||
SettingRow {
|
||||
visible: root.doc.backendIsAlsa === true && root.doc.alsaPluginIsHw === true
|
||||
visible: root.doc.backendIsAlsa === true && root.doc.alsaDirectSelected === true
|
||||
label: QbzSession.tr("Hardware volume control", QbzSession.trRev)
|
||||
description: QbzSession.tr("Use the ALSA mixer for volume instead of software gain.", QbzSession.trRev)
|
||||
description: QbzSession.tr("Control volume through a mixer exposed by the selected ALSA device. If unavailable, direct playback stays fixed at 100%.", QbzSession.trRev)
|
||||
QbzToggle {
|
||||
checked: root.doc.alsaHardwareVolume === true
|
||||
onToggled: function (v) { QbzBridge.settingsBool("alsa-hardware-volume", v) }
|
||||
|
||||
@@ -577,7 +577,7 @@ Rectangle {
|
||||
// (kiosk_nav_qt.rs:222-225).
|
||||
if (QbzKioskNav.zone === "player") {
|
||||
QbzKioskNav.markActive()
|
||||
if (QbzPlayer.npHasTrack)
|
||||
if (QbzPlayer.npHasTrack || QbzQueue.hasPlayTarget)
|
||||
QbzPlayer.togglePlay()
|
||||
} else if (QbzKioskNav.zone === "rail") {
|
||||
QbzKioskNav.markActive()
|
||||
|
||||
@@ -16,8 +16,8 @@
|
||||
// moves of <= 2 lines, INSTANT for bigger jumps and the initial sync,
|
||||
// 1:1 with Slint. The animation drives `contentY` only on the auto-follow
|
||||
// path, so user wheel input is never animated.
|
||||
// - the four embedded lyric font families (lazy: a FontLoader only gets a
|
||||
// source once its option is selected).
|
||||
// - the embedded lyric font families (lazy: one FontLoader exists only while
|
||||
// a non-System option is selected).
|
||||
//
|
||||
// Unsynced/plain documents render as a static top-aligned list: no spacers,
|
||||
// no active line, no scroll-follow.
|
||||
@@ -60,23 +60,32 @@ Item {
|
||||
|
||||
readonly property real contentWidth: Math.max(0, width - 2 * sidePadding)
|
||||
|
||||
// ---- embedded lyric fonts (lazy) -------------------------------------
|
||||
// ---- embedded lyric font (lazy) --------------------------------------
|
||||
readonly property string fontDir: "qrc:/qt/qml/com/blitzfc/qbz/qml/assets/fonts/"
|
||||
FontLoader { id: fLineSeed; source: view.fontIndex === 1 ? view.fontDir + "LINESeedJP-Regular.ttf" : "" }
|
||||
FontLoader { id: fMontserrat; source: view.fontIndex === 2 ? view.fontDir + "Montserrat-VariableFont_wght.ttf" : "" }
|
||||
FontLoader { id: fNoto; source: view.fontIndex === 3 ? view.fontDir + "NotoSans-VariableFont_wdth,wght.ttf" : "" }
|
||||
FontLoader { id: fSource; source: view.fontIndex === 4 ? view.fontDir + "SourceSans3-VariableFont_wght.ttf" : "" }
|
||||
readonly property string fontSource: {
|
||||
if (view.fontIndex === 1) return view.fontDir + "LINESeedJP-Regular.ttf"
|
||||
if (view.fontIndex === 2) return view.fontDir + "Montserrat-VariableFont_wght.ttf"
|
||||
if (view.fontIndex === 3) return view.fontDir + "NotoSans-VariableFont_wdth,wght.ttf"
|
||||
if (view.fontIndex === 4) return view.fontDir + "SourceSans3-VariableFont_wght.ttf"
|
||||
return ""
|
||||
}
|
||||
Component {
|
||||
id: fontLoaderComponent
|
||||
FontLoader { source: view.fontSource }
|
||||
}
|
||||
Loader {
|
||||
id: selectedFontLoader
|
||||
active: view.fontSource !== ""
|
||||
sourceComponent: fontLoaderComponent
|
||||
}
|
||||
|
||||
// "" = the real Qt/system default = Slint's "System" option. A family
|
||||
// that has not finished loading falls back to the default rather than
|
||||
// rendering in a wrong face.
|
||||
readonly property string fontFamily: {
|
||||
if (view.fontIndex === 1) return fLineSeed.status === FontLoader.Ready ? fLineSeed.name : ""
|
||||
if (view.fontIndex === 2) return fMontserrat.status === FontLoader.Ready ? fMontserrat.name : ""
|
||||
if (view.fontIndex === 3) return fNoto.status === FontLoader.Ready ? fNoto.name : ""
|
||||
if (view.fontIndex === 4) return fSource.status === FontLoader.Ready ? fSource.name : ""
|
||||
return ""
|
||||
}
|
||||
readonly property string fontFamily:
|
||||
selectedFontLoader.item
|
||||
&& selectedFontLoader.item.status === FontLoader.Ready
|
||||
? selectedFontLoader.item.name : ""
|
||||
|
||||
// ---- auto-center scroll ----------------------------------------------
|
||||
// Last index centered on; -1 = nothing yet -> the next center is INSTANT.
|
||||
|
||||
@@ -73,6 +73,10 @@ Row {
|
||||
// play. Not gated on `npHasTrack`: the first play of a session has no
|
||||
// track yet, and that is exactly the case that felt dead.
|
||||
readonly property bool loading: QbzPlayer.npLoading
|
||||
// Clear-while-paused removes the NPB cursor by design. Rows added
|
||||
// afterwards still make Play actionable: the backend promotes the first
|
||||
// one without resurrecting the cleared paused stream.
|
||||
readonly property bool playEnabled: QbzPlayer.npHasTrack || QbzQueue.hasPlayTarget
|
||||
// Spin phase, advanced on the shared shell pulse (QbzShell.pulseMs).
|
||||
property real spinPhase: 0
|
||||
Connections {
|
||||
@@ -94,10 +98,10 @@ Row {
|
||||
height: tc.playCircle ? 38 : 34
|
||||
radius: tc.playCircle ? width / 2 : theme.radiusSm
|
||||
anchors.verticalCenter: parent.verticalCenter
|
||||
opacity: QbzPlayer.npHasTrack ? 1.0 : 0.3
|
||||
opacity: tc.playEnabled ? 1.0 : 0.3
|
||||
color: tc.playCircle
|
||||
? (playArea.containsMouse && QbzPlayer.npHasTrack ? theme.accentHover : theme.accent)
|
||||
: ((playArea.containsMouse && QbzPlayer.npHasTrack) ? theme.surfaceHover : "transparent")
|
||||
? (playArea.containsMouse && tc.playEnabled ? theme.accentHover : theme.accent)
|
||||
: ((playArea.containsMouse && tc.playEnabled) ? theme.surfaceHover : "transparent")
|
||||
QbzIcon {
|
||||
// Hidden while loading — the ring below stands in for it, so the
|
||||
// button never shows a play glyph for a track that is still being
|
||||
@@ -145,8 +149,8 @@ Row {
|
||||
id: playArea
|
||||
anchors.fill: parent
|
||||
hoverEnabled: true
|
||||
cursorShape: QbzPlayer.npHasTrack ? Qt.PointingHandCursor : Qt.ArrowCursor
|
||||
onClicked: if (QbzPlayer.npHasTrack) QbzPlayer.togglePlay()
|
||||
cursorShape: tc.playEnabled ? Qt.PointingHandCursor : Qt.ArrowCursor
|
||||
onClicked: if (tc.playEnabled) QbzPlayer.togglePlay()
|
||||
}
|
||||
}
|
||||
QbzIconButton {
|
||||
|
||||
@@ -1,17 +1,24 @@
|
||||
//! Script-specific application font fallbacks.
|
||||
//!
|
||||
//! The UI's "System" choice remains Qt's real system font. This module only
|
||||
//! gives Qt a deterministic face when a selected UI font lacks Devanagari,
|
||||
//! avoiding its noisy scan through unrelated installed families.
|
||||
//! The UI's "System" choice remains Qt's real system font for covered glyphs.
|
||||
//! This module only gives Qt deterministic bundled faces when that font (or a
|
||||
//! selected UI/lyrics font) lacks Japanese or Devanagari, avoiding arbitrary
|
||||
//! and sometimes visually incompatible host fallbacks.
|
||||
|
||||
unsafe extern "C" {
|
||||
fn qbz_register_devanagari_fallback() -> bool;
|
||||
fn qbz_register_japanese_fallback() -> bool;
|
||||
}
|
||||
|
||||
pub(crate) fn register_devanagari_fallback() {
|
||||
// SAFETY: the C++ function has no arguments, is called once on the GUI
|
||||
// thread after QGuiApplication exists, and only mutates QFontDatabase's
|
||||
pub(crate) fn register_script_fallbacks() {
|
||||
// SAFETY: these C++ functions have no arguments, are called once on the
|
||||
// GUI thread after QGuiApplication exists, and only mutate QFontDatabase's
|
||||
// documented process-global application-font registry.
|
||||
if unsafe { qbz_register_japanese_fallback() } {
|
||||
log::info!("[qbz-qt] font fallback -> LINE Seed JP (Han/Hiragana/Katakana)");
|
||||
} else {
|
||||
log::warn!("[qbz-qt] bundled LINE Seed JP fallback failed to load");
|
||||
}
|
||||
if unsafe { qbz_register_devanagari_fallback() } {
|
||||
log::info!("[qbz-qt] font fallback -> Noto Sans Devanagari");
|
||||
} else {
|
||||
|
||||
@@ -24,7 +24,7 @@ use cxx_qt_lib::QString;
|
||||
|
||||
use crate::local_bridge_ops::{
|
||||
emit_artwork, emit_artwork_one, invalidate_artists, load_tab_impl, load_tracks,
|
||||
publish_plex_state, publish_tree, reload_browse, run_sync,
|
||||
publish_availability, publish_plex_state, publish_tree, reload_browse, run_sync,
|
||||
};
|
||||
use crate::local_library_qt as lib;
|
||||
use crate::local_plex as plex;
|
||||
@@ -929,21 +929,16 @@ impl qbz_local::QbzLocal {
|
||||
let sort = lib::tracks_sort();
|
||||
let group = lib::tracks_group();
|
||||
let tracks_filter = lib::tracks_filter();
|
||||
crate::spawn(async move {
|
||||
let available = tokio::task::spawn_blocking(lib::has_library)
|
||||
.await
|
||||
.unwrap_or(false);
|
||||
ui(move |mut b| {
|
||||
b.as_mut().set_local_available(available);
|
||||
b.as_mut()
|
||||
.set_local_album_mode(QString::from(mode.as_str()));
|
||||
b.as_mut()
|
||||
.set_local_tracks_sort(QString::from(sort.as_str()));
|
||||
b.as_mut()
|
||||
.set_local_tracks_group(QString::from(group.as_str()));
|
||||
b.as_mut()
|
||||
.set_local_tracks_filter(QString::from(tracks_filter.as_str()));
|
||||
});
|
||||
publish_availability();
|
||||
ui(move |mut b| {
|
||||
b.as_mut()
|
||||
.set_local_album_mode(QString::from(mode.as_str()));
|
||||
b.as_mut()
|
||||
.set_local_tracks_sort(QString::from(sort.as_str()));
|
||||
b.as_mut()
|
||||
.set_local_tracks_group(QString::from(group.as_str()));
|
||||
b.as_mut()
|
||||
.set_local_tracks_filter(QString::from(tracks_filter.as_str()));
|
||||
});
|
||||
publish_plex_state();
|
||||
crate::local_album_actions::publish_track_artwork();
|
||||
|
||||
@@ -11,13 +11,15 @@
|
||||
//! Every loader publishes its own tab's document + the shared badges; the
|
||||
//! Plex helpers publish the gates and drive the manual sync.
|
||||
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
|
||||
use cxx_qt_lib::QString;
|
||||
|
||||
use crate::local_bridge::ui;
|
||||
use crate::local_library_qt as lib;
|
||||
use crate::local_plex as plex;
|
||||
|
||||
/// Republish the tab badges + availability after any load.
|
||||
/// Republish the tab badges after any load.
|
||||
pub(crate) fn publish_counts() {
|
||||
let counts = lib::to_json(&lib::counts());
|
||||
ui(move |mut b| {
|
||||
@@ -26,6 +28,34 @@ pub(crate) fn publish_counts() {
|
||||
});
|
||||
}
|
||||
|
||||
/// Republish whether any browse source currently makes Local Library usable.
|
||||
///
|
||||
/// `localAvailable` gates the entire Local Library surface, but it used to be
|
||||
/// seeded only once during bridge boot. Adding the first folder (or removing
|
||||
/// the last one) then refreshed every document behind the gate without ever
|
||||
/// changing the gate itself. Keep this asynchronous because `has_library`
|
||||
/// opens the per-user SQLite database.
|
||||
///
|
||||
/// A generation prevents a slower, older database read from overwriting the
|
||||
/// answer from a newer source mutation.
|
||||
static AVAILABILITY_GENERATION: AtomicU64 = AtomicU64::new(0);
|
||||
|
||||
pub(crate) fn publish_availability() {
|
||||
let generation = AVAILABILITY_GENERATION
|
||||
.fetch_add(1, Ordering::AcqRel)
|
||||
.wrapping_add(1);
|
||||
crate::spawn(async move {
|
||||
let available = tokio::task::spawn_blocking(lib::has_library)
|
||||
.await
|
||||
.unwrap_or(false);
|
||||
if AVAILABILITY_GENERATION.load(Ordering::Acquire) != generation {
|
||||
log::debug!("[qbz-qt] discarded stale local availability generation {generation}");
|
||||
return;
|
||||
}
|
||||
ui(move |mut b| b.as_mut().set_local_available(available));
|
||||
});
|
||||
}
|
||||
|
||||
pub(crate) fn publish_tree(nodes_json: String) {
|
||||
ui(move |mut b| {
|
||||
b.as_mut()
|
||||
@@ -144,6 +174,9 @@ fn pruned_albums_filter(has_jellyfin: bool, has_subsonic: bool) -> String {
|
||||
|
||||
pub(crate) fn reload_browse() {
|
||||
publish_media_gates();
|
||||
// This is the shared mutation chokepoint for folders and remote sources.
|
||||
// Republish the gate as well as the documents it controls (#723).
|
||||
publish_availability();
|
||||
// The cortinilla's instant-paint cache embeds LOCAL rows and their artwork
|
||||
// paths, so anything that reaches here has just made those rows possibly
|
||||
// wrong. This is the single chokepoint for local-library mutations, which
|
||||
|
||||
@@ -802,12 +802,19 @@ fn on_session_entered() {
|
||||
qconnect_service.spawn_offline_force_disconnect(&tokio_handle);
|
||||
}
|
||||
}
|
||||
// Seed the saved level, then enforce unity gain for ALSA-direct `hw`.
|
||||
// Sequencing both writes in one task prevents the asynchronous restore
|
||||
// from landing after the bit-perfect correction.
|
||||
// Revalidate hardware volume first. When a compatible ALSA mixer exists,
|
||||
// the probe samples its physical level and seeds SharedState without a
|
||||
// write; restoring the persisted slider afterward would otherwise move
|
||||
// that mixer at launch. Without hardware volume, restore the saved level
|
||||
// and then enforce unity for the protected ALSA-direct path. Sequencing
|
||||
// these decisions in one task prevents an asynchronous restore from
|
||||
// landing after the bit-perfect correction.
|
||||
let rt = app();
|
||||
spawn(async move {
|
||||
playback_qt::set_volume(&rt, restored).await;
|
||||
let hardware_level = settings_qt::reconcile_alsa_hardware_volume(&rt).await;
|
||||
if hardware_level.is_none() {
|
||||
playback_qt::set_volume(&rt, restored).await;
|
||||
}
|
||||
settings_qt::maybe_force_bitperfect_volume(&rt).await;
|
||||
});
|
||||
// 3. Startup auto-connect — gated on NOT offline: the offline shell entry
|
||||
@@ -3422,7 +3429,7 @@ fn main() {
|
||||
"qrc:/qt/qml/com/blitzfc/qbz/qml/FontPreload.qml",
|
||||
));
|
||||
}
|
||||
font_qt::register_devanagari_fallback();
|
||||
font_qt::register_script_fallbacks();
|
||||
let app_font_family = settings_qt::app_font_family();
|
||||
if !app_font_family.is_empty() {
|
||||
if let Some(app) = app.as_mut() {
|
||||
@@ -3481,6 +3488,23 @@ fn main() {
|
||||
// playing for two seconds longer is a far smaller failure than an app
|
||||
// that cannot be closed, so the timeout wins the tie.
|
||||
if let Some(rt) = TOKIO.get() {
|
||||
// Construct the timer *inside* the runtime. Building
|
||||
// `tokio::time::timeout` as the argument to `block_on` happens
|
||||
// before the runtime is entered and panics with "no reactor
|
||||
// running" during every normal quit.
|
||||
let notification_withdrawn = rt.block_on(async {
|
||||
tokio::time::timeout(
|
||||
std::time::Duration::from_secs(1),
|
||||
qbz_media_controls::withdraw_track_notification(),
|
||||
)
|
||||
.await
|
||||
});
|
||||
let notification_withdrawn = notification_withdrawn.is_ok();
|
||||
if !notification_withdrawn {
|
||||
log::warn!(
|
||||
"[qbz-qt] notification withdrawal did not finish within 1s; exiting anyway"
|
||||
);
|
||||
}
|
||||
let stopped = rt.block_on(async {
|
||||
tokio::time::timeout(
|
||||
std::time::Duration::from_secs(2),
|
||||
|
||||
@@ -209,6 +209,7 @@ pub(crate) fn clear_now_playing() {
|
||||
// (`crates/qbz/src/playback.rs:1911`, same `u64::MAX` sentinel — a real
|
||||
// track id can never collide with it).
|
||||
NOTIFY_LAST_TRACK.store(u64::MAX, std::sync::atomic::Ordering::Relaxed);
|
||||
crate::spawn(qbz_media_controls::withdraw_track_notification());
|
||||
if let Some(mc) = handle() {
|
||||
mc.set_playback(qbz_media_controls::PlaybackStatus::Stopped, None);
|
||||
}
|
||||
|
||||
@@ -105,17 +105,14 @@ pub fn output_labels(audio: &AudioSettings) -> OutputLabels {
|
||||
/// (`qbz-player/src/player/playback_engine.rs`) is a documented NO-OP on the
|
||||
/// `AlsaDirect` arm unless `alsa_hardware_volume` is on, in which case it
|
||||
/// drives the DAC's own mixer instead (still bit-perfect, so the slider stays
|
||||
/// live). The ALSA backend builds an `AlsaDirectStream` for BOTH the `hw`
|
||||
/// (bit-perfect direct) and the `plughw` fallback plugin; only `Pcm` opts out
|
||||
/// of the direct engine entirely and lands on CPAL/rodio, where software
|
||||
/// volume works. Hence: ALSA backend, plugin != Pcm, hardware volume off.
|
||||
/// live). The route predicate also includes the selected device id: ALSA's
|
||||
/// system-default/sysdefault rows land on CPAL/Rodio and keep software volume,
|
||||
/// even if the plugin preference says `hw`.
|
||||
///
|
||||
/// READ-ONLY derivation from the persisted `AudioSettings` — no audio
|
||||
/// behaviour is changed anywhere by this, the UI just stops lying about it.
|
||||
pub fn volume_locked(audio: &AudioSettings) -> bool {
|
||||
matches!(audio.backend_type, Some(AudioBackendType::Alsa))
|
||||
&& !matches!(audio.alsa_plugin, Some(AlsaPlugin::Pcm))
|
||||
&& !audio.alsa_hardware_volume
|
||||
qbz_audio::alsa_direct::uses_alsa_direct_route(audio) && !audio.alsa_hardware_volume
|
||||
}
|
||||
|
||||
/// Derive + push the four LED values (and the volume-lock flag) onto the
|
||||
@@ -219,6 +216,7 @@ mod tests {
|
||||
assert!(!volume_locked(&settings(b)), "{b:?} must keep the slider");
|
||||
}
|
||||
let mut s = settings(Some(AudioBackendType::Alsa));
|
||||
s.output_device = Some("front:CARD=USB,DEV=0".to_string());
|
||||
// hw = the bit-perfect direct path: engine set_volume is a no-op.
|
||||
s.alsa_plugin = Some(AlsaPlugin::Hw);
|
||||
s.alsa_hardware_volume = false;
|
||||
@@ -233,6 +231,12 @@ mod tests {
|
||||
// Pcm opts out of the direct engine (CPAL/rodio) -> software volume.
|
||||
s.alsa_plugin = Some(AlsaPlugin::Pcm);
|
||||
assert!(!volume_locked(&s));
|
||||
// ALSA default/sysdefault use CPAL/Rodio rather than AlsaDirect.
|
||||
s.alsa_plugin = Some(AlsaPlugin::Hw);
|
||||
s.output_device = None;
|
||||
assert!(!volume_locked(&s));
|
||||
s.output_device = Some("sysdefault:CARD=USB".to_string());
|
||||
assert!(!volume_locked(&s));
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -213,6 +213,55 @@ fn should_stream_gapless_successor(
|
||||
streaming_only && !player_cached && !offline_cached && throttle_cap > 0
|
||||
}
|
||||
|
||||
/// The queue/engine edge a completed gapless fetch still belongs to.
|
||||
///
|
||||
/// Full-track materialization can outlive the predecessor. Checking only the
|
||||
/// requested successor lets a late result append that successor behind itself
|
||||
/// after the normal end-edge already started it. Queue edits and a late
|
||||
/// stop-after mark are equally stale. Keep the policy pure so all of those
|
||||
/// races have deterministic coverage.
|
||||
fn gapless_edge_matches(
|
||||
predecessor_id: u64,
|
||||
successor_id: u64,
|
||||
engine_track_id: u64,
|
||||
engine_queued_id: u64,
|
||||
stop_after_id: Option<u64>,
|
||||
queue_successor_id: Option<u64>,
|
||||
) -> bool {
|
||||
predecessor_id != 0
|
||||
&& successor_id != 0
|
||||
&& predecessor_id != successor_id
|
||||
&& engine_track_id == predecessor_id
|
||||
&& engine_queued_id == 0
|
||||
&& stop_after_id != Some(predecessor_id)
|
||||
&& queue_successor_id == Some(successor_id)
|
||||
}
|
||||
|
||||
async fn gapless_edge_is_current(
|
||||
runtime: &Arc<AppRuntime<LoggingAdapter>>,
|
||||
predecessor_id: u64,
|
||||
successor_id: u64,
|
||||
) -> bool {
|
||||
let player = runtime.core().player();
|
||||
let engine_track_id = player.state.current_track_id();
|
||||
let engine_queued_id = player.state.get_gapless_next_track_id();
|
||||
let stop_after_id = runtime.core().get_stop_after().await;
|
||||
let queue_successor_id = runtime
|
||||
.core()
|
||||
.peek_upcoming(1)
|
||||
.await
|
||||
.first()
|
||||
.map(|track| track.id);
|
||||
gapless_edge_matches(
|
||||
predecessor_id,
|
||||
successor_id,
|
||||
engine_track_id,
|
||||
engine_queued_id,
|
||||
stop_after_id,
|
||||
queue_successor_id,
|
||||
)
|
||||
}
|
||||
|
||||
/// Warm the next two queue rows in the player's shared L1/L2 cache. This only
|
||||
/// performs cheap policy/queue work inline; every full download is spawned in
|
||||
/// the background and goes through `Player::prefetch_into_cache`, which owns
|
||||
@@ -2244,9 +2293,51 @@ pub async fn toggle_play(runtime: &Arc<AppRuntime<LoggingAdapter>>) {
|
||||
return;
|
||||
}
|
||||
|
||||
if !was_playing && !runtime.core().player().has_loaded_audio() {
|
||||
match runtime.core().current_track().await {
|
||||
Some(track) => {
|
||||
if !was_playing {
|
||||
let current = runtime.core().current_track().await;
|
||||
|
||||
// IDLE LIST: Clear while paused intentionally removes the cursor and
|
||||
// NPB, but Add to queue / Play next / Play later deliberately do not
|
||||
// create a new current row. The paused engine can still hold the old
|
||||
// decoded stream here, so checking `has_loaded_audio()` first would
|
||||
// resume the track the user just cleared. Promote the first live queue
|
||||
// occurrence before considering resume, with the expected id checked
|
||||
// under the queue lock so a concurrent mutation cannot start a
|
||||
// different row.
|
||||
if current.is_none() {
|
||||
let state = runtime.core().get_queue_state_full().await;
|
||||
let Some(candidate) = state.upcoming.first().cloned() else {
|
||||
log::info!("[qbz-qt] toggle-play ignored: empty queue");
|
||||
return;
|
||||
};
|
||||
if crate::local_playback::preflight_queue_track(&candidate)
|
||||
.await
|
||||
.is_err()
|
||||
{
|
||||
return;
|
||||
}
|
||||
let Some(track) = runtime
|
||||
.core()
|
||||
.play_upcoming_at_preserving_timeline(0, candidate.id)
|
||||
.await
|
||||
else {
|
||||
log::warn!("[qbz-qt] toggle-play: idle queue changed before activation");
|
||||
return;
|
||||
};
|
||||
log::info!(
|
||||
"[qbz-qt] toggle-play: idle queue -> starting first track {}",
|
||||
track.id
|
||||
);
|
||||
PENDING_PLAY_ID.store(track.id, Ordering::Relaxed);
|
||||
play_queue_track(runtime, track.id, 0).await;
|
||||
PENDING_PLAY_ID
|
||||
.compare_exchange(track.id, 0, Ordering::Relaxed, Ordering::Relaxed)
|
||||
.ok();
|
||||
return;
|
||||
}
|
||||
|
||||
if !runtime.core().player().has_loaded_audio() {
|
||||
if let Some(track) = current {
|
||||
log::info!(
|
||||
"[qbz-qt] toggle-play: no loaded audio -> cold-starting current track {}",
|
||||
track.id
|
||||
@@ -2266,11 +2357,8 @@ pub async fn toggle_play(runtime: &Arc<AppRuntime<LoggingAdapter>>) {
|
||||
.compare_exchange(track.id, 0, Ordering::Relaxed, Ordering::Relaxed)
|
||||
.ok();
|
||||
}
|
||||
None => {
|
||||
log::info!("[qbz-qt] toggle-play ignored: no loaded audio and an empty queue");
|
||||
}
|
||||
return;
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
let result = if was_playing {
|
||||
@@ -3469,6 +3557,12 @@ pub fn start_poll_loop(runtime: Arc<AppRuntime<LoggingAdapter>>) {
|
||||
)
|
||||
.await
|
||||
{
|
||||
if !gapless_edge_is_current(&runtime, track_id, next_id).await {
|
||||
log::info!(
|
||||
"[qbz-qt] [GAPLESS] discarded stale track {next_id} after predecessor {track_id} moved or its queue edge changed"
|
||||
);
|
||||
return;
|
||||
}
|
||||
let player = runtime.core().player();
|
||||
match player.play_next(data, next_id) {
|
||||
Ok(()) => log::info!(
|
||||
@@ -3677,9 +3771,9 @@ pub fn start_poll_loop(runtime: Arc<AppRuntime<LoggingAdapter>>) {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{
|
||||
filter_queue_with, prefetch_track_ids, quality_badge_from, reconcile_device_cap,
|
||||
should_stream_gapless_successor, stream_error_text, xorshift_shuffle_seeded,
|
||||
PrefetchCandidate, PrefetchTrackEdge,
|
||||
filter_queue_with, gapless_edge_matches, prefetch_track_ids, quality_badge_from,
|
||||
reconcile_device_cap, should_stream_gapless_successor, stream_error_text,
|
||||
xorshift_shuffle_seeded, PrefetchCandidate, PrefetchTrackEdge,
|
||||
};
|
||||
use qbz_models::{Quality, QualityLimit, QueueTrack};
|
||||
use qbz_source::QualityHint;
|
||||
@@ -3832,6 +3926,16 @@ mod tests {
|
||||
assert!(!should_stream_gapless_successor(true, false, false, 0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn completed_gapless_fetch_only_matches_its_live_queue_edge() {
|
||||
assert!(gapless_edge_matches(1, 2, 1, 0, None, Some(2)));
|
||||
assert!(!gapless_edge_matches(1, 2, 2, 0, None, Some(2)));
|
||||
assert!(!gapless_edge_matches(1, 2, 1, 9, None, Some(2)));
|
||||
assert!(!gapless_edge_matches(1, 2, 1, 0, Some(1), Some(2)));
|
||||
assert!(!gapless_edge_matches(1, 2, 1, 0, None, Some(3)));
|
||||
assert!(!gapless_edge_matches(1, 1, 1, 0, None, Some(1)));
|
||||
}
|
||||
|
||||
// --- #638 fix 3: the request tier reconciles preference against the
|
||||
// detected local device cap. -------------------------------------------
|
||||
|
||||
|
||||
@@ -36,6 +36,11 @@ pub mod qbz_queue {
|
||||
// One JSON document (queue_qt.rs QueueDoc: current/upcoming/history
|
||||
// + pagination + #442 section markers). Supersedes `queueModel`.
|
||||
#[qproperty(QString, queue_json)]
|
||||
// True whenever the core still has at least one queue row, including
|
||||
// the idle state produced by Clear -> Add/Next/Later. Unlike
|
||||
// `QbzPlayer.npHasTrack`, this deliberately does not require a current
|
||||
// cursor: it is the transport's answer to "can Play start anything?".
|
||||
#[qproperty(bool, has_play_target)]
|
||||
// Full chronological queue projection used only by QueueView. It is
|
||||
// opt-in so ordinary sidebar publishes stay paged and cheap.
|
||||
#[qproperty(QString, extended_queue_json)]
|
||||
@@ -166,6 +171,7 @@ type QListQVariant = QList<QVariant>;
|
||||
pub struct QbzQueueRust {
|
||||
queue_model: QListQVariant,
|
||||
queue_json: QString,
|
||||
has_play_target: bool,
|
||||
extended_queue_json: QString,
|
||||
coverflow_json: QString,
|
||||
drop_play_prompt: bool,
|
||||
@@ -178,6 +184,7 @@ impl Default for QbzQueueRust {
|
||||
Self {
|
||||
queue_model: QListQVariant::default(),
|
||||
queue_json: QString::from("{}"),
|
||||
has_play_target: false,
|
||||
extended_queue_json: QString::from(
|
||||
r#"{"rows":[],"currentIndex":-1,"historyCount":0,"upcomingCount":0,"stopAfterId":"","infinitePlay":false,"searchQuery":""}"#,
|
||||
),
|
||||
|
||||
@@ -615,6 +615,7 @@ static LOCAL_ROW_IDS: std::sync::LazyLock<Mutex<HashSet<u64>>> =
|
||||
pub async fn publish(runtime: &Arc<AppRuntime<LoggingAdapter>>) {
|
||||
let t_build = std::time::Instant::now();
|
||||
let state = runtime.core().get_queue_state_full().await;
|
||||
let has_play_target = state.total_tracks > 0;
|
||||
let (search, requested_page) = {
|
||||
let view = VIEW.lock().unwrap();
|
||||
(view.search.clone(), view.page)
|
||||
@@ -745,6 +746,7 @@ pub async fn publish(runtime: &Arc<AppRuntime<LoggingAdapter>>) {
|
||||
t_build.elapsed()
|
||||
);
|
||||
crate::queue_bridge::ui(move |mut b| {
|
||||
b.as_mut().set_has_play_target(has_play_target);
|
||||
b.as_mut().set_queue_json(QString::from(json.as_str()));
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1618,6 +1618,8 @@ pub struct SettingsDoc {
|
||||
pub alsa_plugin_index: i32,
|
||||
#[serde(rename = "alsaPluginIsHw")]
|
||||
pub alsa_plugin_is_hw: bool,
|
||||
#[serde(rename = "alsaDirectSelected")]
|
||||
pub alsa_direct_selected: bool,
|
||||
#[serde(rename = "alsaHardwareVolume")]
|
||||
pub alsa_hardware_volume: bool,
|
||||
#[serde(rename = "dsdModes")]
|
||||
@@ -2105,6 +2107,7 @@ pub async fn publish_snapshot() {
|
||||
alsa_plugins: ALSA_PLUGIN_LABELS.iter().map(|l| qbz_i18n::t(l)).collect(),
|
||||
alsa_plugin_index: alsa_plugin_index as i32,
|
||||
alsa_plugin_is_hw: alsa_plugin == AlsaPlugin::Hw,
|
||||
alsa_direct_selected: qbz_audio::alsa_direct::uses_alsa_direct_route(&audio_settings),
|
||||
alsa_hardware_volume: audio_settings.alsa_hardware_volume,
|
||||
dsd_modes: DSD_MODE_LABELS.iter().map(|l| qbz_i18n::t(l)).collect(),
|
||||
dsd_mode_index: DSD_MODE_VALUES
|
||||
@@ -2317,6 +2320,64 @@ enum Apply {
|
||||
Reinit,
|
||||
}
|
||||
|
||||
async fn probe_selected_hardware_volume(
|
||||
audio: &qbz_audio::settings::AudioSettings,
|
||||
) -> Result<qbz_audio::alsa_direct::HardwareVolumeInfo, String> {
|
||||
if !qbz_audio::alsa_direct::uses_alsa_direct_route(audio) {
|
||||
return Err(
|
||||
"hardware volume requires an explicitly selected ALSA Direct device".to_string(),
|
||||
);
|
||||
}
|
||||
let device_id = audio
|
||||
.output_device
|
||||
.clone()
|
||||
.ok_or_else(|| "ALSA Direct device is missing".to_string())?;
|
||||
tokio::task::spawn_blocking(move || qbz_audio::alsa_direct::probe_hardware_volume(&device_id))
|
||||
.await
|
||||
.map_err(|error| format!("ALSA hardware-volume probe task failed: {error}"))?
|
||||
}
|
||||
|
||||
fn seed_hardware_volume(
|
||||
runtime: &Arc<AppRuntime<LoggingAdapter>>,
|
||||
info: &qbz_audio::alsa_direct::HardwareVolumeInfo,
|
||||
) {
|
||||
// Update SharedState without touching the old output. The new direct
|
||||
// engine reads this after Reinit and writes back the same level the probe
|
||||
// sampled, instead of copying the locked path's synthetic 100% into the
|
||||
// physical mixer (or writing the new device's level through the old one).
|
||||
runtime.core().player().seed_volume_state(info.volume);
|
||||
save_pref("volume", serde_json::json!(info.volume));
|
||||
crate::now_playing::set_volume(info.volume);
|
||||
log::info!(
|
||||
"[qbz-qt] ALSA hardware volume: '{}' available at {:.0}%",
|
||||
info.control_name,
|
||||
info.volume * 100.0
|
||||
);
|
||||
}
|
||||
|
||||
async fn set_alsa_hardware_volume(
|
||||
runtime: &Arc<AppRuntime<LoggingAdapter>>,
|
||||
enabled: bool,
|
||||
) -> Result<Apply, String> {
|
||||
if !enabled {
|
||||
return with_audio(|store| store.set_alsa_hardware_volume(false)).map(|_| Apply::Reinit);
|
||||
}
|
||||
|
||||
let audio = with_audio(|store| store.get_settings())?;
|
||||
let info = match probe_selected_hardware_volume(&audio).await {
|
||||
Ok(info) => info,
|
||||
Err(error) => {
|
||||
// An old build or an external settings edit may already have left
|
||||
// this true. Fail closed so the UI cannot advertise an enabled,
|
||||
// inert slider after the probe rejects the device.
|
||||
let _ = with_audio(|store| store.set_alsa_hardware_volume(false));
|
||||
return Err(error);
|
||||
}
|
||||
};
|
||||
seed_hardware_volume(runtime, &info);
|
||||
with_audio(|store| store.set_alsa_hardware_volume(true)).map(|_| Apply::Reinit)
|
||||
}
|
||||
|
||||
fn apply_audio(runtime: &Arc<AppRuntime<LoggingAdapter>>, apply: Apply) {
|
||||
let reinit = match apply {
|
||||
Apply::None => return,
|
||||
@@ -2348,18 +2409,33 @@ fn apply_audio(runtime: &Arc<AppRuntime<LoggingAdapter>>, apply: Apply) {
|
||||
crate::publish_settings();
|
||||
}
|
||||
|
||||
fn uses_alsa_direct_hw(audio: &qbz_audio::settings::AudioSettings) -> bool {
|
||||
audio.backend_type.unwrap_or_default() == AudioBackendType::Alsa
|
||||
&& audio.alsa_plugin.unwrap_or(AlsaPlugin::Hw) == AlsaPlugin::Hw
|
||||
/// Release the live output and wait for the audio thread to confirm that the
|
||||
/// PCM/reservation is gone and any PipeWire sink QBZ suspended is awake.
|
||||
/// `Player::release_device` is intentionally blocking because the ack is the
|
||||
/// ordering guarantee; keep that wait off Tokio's worker threads.
|
||||
async fn release_output_device(runtime: &Arc<AppRuntime<LoggingAdapter>>) -> Result<(), String> {
|
||||
let player = runtime.core().player();
|
||||
tokio::task::spawn_blocking(move || player.release_device())
|
||||
.await
|
||||
.map_err(|error| format!("audio-device release task failed: {error}"))?
|
||||
}
|
||||
|
||||
/// Keep software gain at unity for ALSA-direct `hw` output. The public core
|
||||
fn report_release_failure(error: &str) {
|
||||
log::error!("[qbz-qt] output-device release failed: {error}");
|
||||
crate::toast_qt::error(qbz_i18n::t(
|
||||
"QBZ could not fully release the previous audio device. See the audio log for details.",
|
||||
));
|
||||
}
|
||||
|
||||
fn requires_alsa_direct_unity(audio: &qbz_audio::settings::AudioSettings) -> bool {
|
||||
qbz_audio::alsa_direct::uses_alsa_direct_route(audio) && !audio.alsa_hardware_volume
|
||||
}
|
||||
|
||||
/// Keep software gain at unity for ALSA-direct output. The public core
|
||||
/// volume seam does not reconfigure the protected device/backend; the DAC owns
|
||||
/// level in this mode. A QConnect peer is deliberately exempt because its
|
||||
/// remote volume is the active control.
|
||||
pub(crate) async fn maybe_force_bitperfect_volume(
|
||||
runtime: &Arc<AppRuntime<LoggingAdapter>>,
|
||||
) {
|
||||
pub(crate) async fn maybe_force_bitperfect_volume(runtime: &Arc<AppRuntime<LoggingAdapter>>) {
|
||||
let audio = match with_audio(|store| store.get_settings()) {
|
||||
Ok(audio) => audio,
|
||||
Err(error) => {
|
||||
@@ -2367,7 +2443,7 @@ pub(crate) async fn maybe_force_bitperfect_volume(
|
||||
return;
|
||||
}
|
||||
};
|
||||
if !uses_alsa_direct_hw(&audio) {
|
||||
if !requires_alsa_direct_unity(&audio) {
|
||||
return;
|
||||
}
|
||||
let controlling_peer = match crate::qconnect_qt::service() {
|
||||
@@ -2385,6 +2461,46 @@ pub(crate) async fn maybe_force_bitperfect_volume(
|
||||
crate::now_playing::set_volume(1.0);
|
||||
}
|
||||
|
||||
/// Revalidate a persisted hardware-volume preference after startup or a route
|
||||
/// change. A successful probe synchronizes QBZ to the physical mixer before
|
||||
/// any stream reinitialization. A failed probe disables the preference and
|
||||
/// reloads the player, leaving the protected direct path locked at unity.
|
||||
pub(crate) async fn reconcile_alsa_hardware_volume(
|
||||
runtime: &Arc<AppRuntime<LoggingAdapter>>,
|
||||
) -> Option<f32> {
|
||||
let audio = match with_audio(|store| store.get_settings()) {
|
||||
Ok(audio) => audio,
|
||||
Err(error) => {
|
||||
log::error!("[qbz-qt] re-read audio for hardware-volume probe failed: {error}");
|
||||
return None;
|
||||
}
|
||||
};
|
||||
if !audio.alsa_hardware_volume || !qbz_audio::alsa_direct::uses_alsa_direct_route(&audio) {
|
||||
return None;
|
||||
}
|
||||
|
||||
match probe_selected_hardware_volume(&audio).await {
|
||||
Ok(info) => {
|
||||
seed_hardware_volume(runtime, &info);
|
||||
Some(info.volume)
|
||||
}
|
||||
Err(error) => {
|
||||
log::warn!("[qbz-qt] ALSA hardware volume unavailable; disabling the setting: {error}");
|
||||
if let Err(persist_error) = with_audio(|store| store.set_alsa_hardware_volume(false)) {
|
||||
log::error!(
|
||||
"[qbz-qt] failed to disable unavailable hardware volume: {persist_error}"
|
||||
);
|
||||
return None;
|
||||
}
|
||||
apply_audio(runtime, Apply::Reinit);
|
||||
crate::toast_qt::error(qbz_i18n::t(
|
||||
"This ALSA device has no compatible hardware volume control. Direct playback remains fixed at 100%.",
|
||||
));
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Handlers (settings.rs handle_bool / handle_select / handle_slider /
|
||||
// handle_string, including the cascades)
|
||||
@@ -2416,9 +2532,7 @@ pub async fn settings_bool(runtime: &Arc<AppRuntime<LoggingAdapter>>, key: &str,
|
||||
"limit-quality-to-device" => {
|
||||
with_audio(|s| s.set_limit_quality_to_device(value)).map(|_| Apply::Reload)
|
||||
}
|
||||
"alsa-hardware-volume" => {
|
||||
with_audio(|s| s.set_alsa_hardware_volume(value)).map(|_| Apply::Reinit)
|
||||
}
|
||||
"alsa-hardware-volume" => set_alsa_hardware_volume(runtime, value).await,
|
||||
"exclusive-mode" => with_audio(|s| s.set_exclusive_mode(value)).map(|_| Apply::Reinit),
|
||||
"reserve-dac" => {
|
||||
with_audio(|s| s.set_reserve_dac_while_running(value)).map(|_| Apply::Reload)
|
||||
@@ -2541,6 +2655,9 @@ pub async fn settings_bool(runtime: &Arc<AppRuntime<LoggingAdapter>>, key: &str,
|
||||
}
|
||||
"system-notifications" => {
|
||||
save_pref("system_notifications", serde_json::json!(value));
|
||||
if !value {
|
||||
crate::spawn(qbz_media_controls::withdraw_track_notification());
|
||||
}
|
||||
Ok(Apply::None)
|
||||
}
|
||||
"window-title-show" => {
|
||||
@@ -2712,9 +2829,24 @@ pub async fn settings_bool(runtime: &Arc<AppRuntime<LoggingAdapter>>, key: &str,
|
||||
refresh_device_cap(runtime).await;
|
||||
}
|
||||
apply_audio(runtime, apply);
|
||||
if key == "alsa-hardware-volume" {
|
||||
maybe_force_bitperfect_volume(runtime).await;
|
||||
}
|
||||
publish_snapshot().await;
|
||||
}
|
||||
Err(e) => log::error!("[qbz-qt] settings persist failed ({key}): {e}"),
|
||||
Err(e) => {
|
||||
log::error!("[qbz-qt] settings persist failed ({key}): {e}");
|
||||
if key == "alsa-hardware-volume" {
|
||||
// The failed enable path persisted `false`; push that state to
|
||||
// the player/document and explain why the toggle bounced back.
|
||||
apply_audio(runtime, Apply::Reinit);
|
||||
maybe_force_bitperfect_volume(runtime).await;
|
||||
publish_snapshot().await;
|
||||
crate::toast_qt::error(qbz_i18n::t(
|
||||
"This ALSA device has no compatible hardware volume control. Direct playback remains fixed at 100%.",
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2749,6 +2881,16 @@ pub async fn settings_select(runtime: &Arc<AppRuntime<LoggingAdapter>>, key: &st
|
||||
None => return,
|
||||
}
|
||||
};
|
||||
let previous_backend = audio_settings().backend_type.unwrap_or_default();
|
||||
if previous_backend == AudioBackendType::Alsa && backend != AudioBackendType::Alsa {
|
||||
// This must complete BEFORE the new backend is persisted and
|
||||
// initialized. Reinit used to drop the ALSA PCM but omitted
|
||||
// the suspended-sink cleanup, while Refresh merely queued a
|
||||
// release and raced its own re-enumeration.
|
||||
if let Err(error) = release_output_device(runtime).await {
|
||||
report_release_failure(&error);
|
||||
}
|
||||
}
|
||||
if let Err(e) = with_audio(|s| s.set_backend_type(Some(backend))) {
|
||||
log::error!("[qbz-qt] persist backend failed: {e}");
|
||||
return;
|
||||
@@ -2818,6 +2960,7 @@ pub async fn settings_select(runtime: &Arc<AppRuntime<LoggingAdapter>>, key: &st
|
||||
}
|
||||
// #638 fix 3, trigger 4 — a different DAC has a different ceiling.
|
||||
refresh_device_cap(runtime).await;
|
||||
reconcile_alsa_hardware_volume(runtime).await;
|
||||
apply_audio(runtime, Apply::Reinit);
|
||||
}
|
||||
"dsd-mode" => {
|
||||
@@ -2838,6 +2981,7 @@ pub async fn settings_select(runtime: &Arc<AppRuntime<LoggingAdapter>>, key: &st
|
||||
log::error!("[qbz-qt] persist alsa plugin failed: {e}");
|
||||
return;
|
||||
}
|
||||
reconcile_alsa_hardware_volume(runtime).await;
|
||||
apply_audio(runtime, Apply::Reinit);
|
||||
maybe_force_bitperfect_volume(runtime).await;
|
||||
}
|
||||
@@ -3225,9 +3369,8 @@ pub async fn settings_reset(runtime: &Arc<AppRuntime<LoggingAdapter>>) {
|
||||
pub async fn refresh_devices(runtime: &Arc<AppRuntime<LoggingAdapter>>) {
|
||||
// Release whatever the player holds, then re-enumerate from scratch (the
|
||||
// whole point of the button is a device that was not in the last list).
|
||||
let player = runtime.core().player();
|
||||
if let Err(e) = player.release_device() {
|
||||
log::warn!("[qbz-qt] release device failed: {e}");
|
||||
if let Err(error) = release_output_device(runtime).await {
|
||||
report_release_failure(&error);
|
||||
}
|
||||
invalidate_device_cache();
|
||||
// #638 fix 3, trigger 6 — Qt-only, and the easiest of the six to miss.
|
||||
@@ -3237,6 +3380,7 @@ pub async fn refresh_devices(runtime: &Arc<AppRuntime<LoggingAdapter>>) {
|
||||
// default". Placed after the re-enumeration so the probe reads the new
|
||||
// device list, and before the publish so the row lands settled.
|
||||
refresh_device_cap(runtime).await;
|
||||
reconcile_alsa_hardware_volume(runtime).await;
|
||||
publish_snapshot().await;
|
||||
}
|
||||
|
||||
@@ -3296,18 +3440,29 @@ mod local_tab_order_tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_alsa_hw_requires_unity_software_volume() {
|
||||
fn only_alsa_direct_without_a_hardware_mixer_requires_unity_volume() {
|
||||
let mut audio = qbz_audio::settings::AudioSettings::default();
|
||||
assert!(!uses_alsa_direct_hw(&audio));
|
||||
assert!(!requires_alsa_direct_unity(&audio));
|
||||
|
||||
audio.backend_type = Some(AudioBackendType::Alsa);
|
||||
audio.output_device = Some("front:CARD=USB,DEV=0".to_string());
|
||||
audio.alsa_plugin = Some(AlsaPlugin::Hw);
|
||||
assert!(uses_alsa_direct_hw(&audio));
|
||||
assert!(requires_alsa_direct_unity(&audio));
|
||||
|
||||
audio.alsa_hardware_volume = true;
|
||||
assert!(!requires_alsa_direct_unity(&audio));
|
||||
audio.alsa_hardware_volume = false;
|
||||
|
||||
audio.alsa_plugin = Some(AlsaPlugin::PlugHw);
|
||||
assert!(!uses_alsa_direct_hw(&audio));
|
||||
audio.backend_type = Some(AudioBackendType::PipeWire);
|
||||
assert!(requires_alsa_direct_unity(&audio));
|
||||
audio.alsa_plugin = Some(AlsaPlugin::Pcm);
|
||||
assert!(!requires_alsa_direct_unity(&audio));
|
||||
|
||||
audio.alsa_plugin = Some(AlsaPlugin::Hw);
|
||||
assert!(!uses_alsa_direct_hw(&audio));
|
||||
audio.output_device = None;
|
||||
assert!(!requires_alsa_direct_unity(&audio));
|
||||
audio.backend_type = Some(AudioBackendType::PipeWire);
|
||||
audio.output_device = Some("front:CARD=USB,DEV=0".to_string());
|
||||
assert!(!requires_alsa_direct_unity(&audio));
|
||||
}
|
||||
}
|
||||
@@ -56,7 +56,8 @@ pub enum ApplyClass {
|
||||
/// lists exactly these, in this order; `settings set` accepts exactly these
|
||||
/// keys and nothing else. Domains: `audio.*` (`AudioSettingsStore`),
|
||||
/// `playback.*` (daemon_prefs.streaming_quality + `PlaybackPreferencesStore`),
|
||||
/// `qconnect.*` (the daemon-root `qconnect_settings.db` KV, T9).
|
||||
/// `qconnect.*` (the daemon-root `qconnect_settings.db` KV, T9),
|
||||
/// `hooks.*` (daemon_prefs, CONSOLE ext).
|
||||
const KEY_TABLE: &[(&str, ApplyClass)] = &[
|
||||
// --- audio (Reinit — 03-setup-tui.md §4.3's 9-field list) -------------
|
||||
("audio.backend", ApplyClass::Reinit),
|
||||
@@ -92,6 +93,8 @@ const KEY_TABLE: &[(&str, ApplyClass)] = &[
|
||||
("qconnect.device_name", ApplyClass::None),
|
||||
("qconnect.startup_mode", ApplyClass::None),
|
||||
("qconnect.volume_mode", ApplyClass::None),
|
||||
// --- hooks (daemon_prefs, CONSOLE ext) ----------------------------------
|
||||
("hooks.script", ApplyClass::None),
|
||||
];
|
||||
|
||||
fn classify(key: &str) -> Option<ApplyClass> {
|
||||
@@ -192,6 +195,24 @@ fn render_opt_string(v: &Option<String>) -> String {
|
||||
v.clone().unwrap_or_else(|| "system".to_string())
|
||||
}
|
||||
|
||||
/// `hooks.script`: empty clears (hooks off, the default); anything else must
|
||||
/// be an absolute path — the daemon spawns it verbatim with no PATH lookup or
|
||||
/// shell, so a relative value would silently depend on the daemon's cwd. Not
|
||||
/// checked for existence here (a headless `settings set` must work before the
|
||||
/// script is installed); the daemon warns at spawn time instead.
|
||||
fn parse_hook_script(v: &str) -> Result<String, String> {
|
||||
let trimmed = v.trim();
|
||||
if trimmed.is_empty() {
|
||||
return Ok(String::new());
|
||||
}
|
||||
if !std::path::Path::new(trimmed).is_absolute() {
|
||||
return Err(format!(
|
||||
"invalid hook script '{trimmed}' — expected an absolute path (or empty to disable)"
|
||||
));
|
||||
}
|
||||
Ok(trimmed.to_string())
|
||||
}
|
||||
|
||||
/// `audio.device_max_sample_rate`: "none"/"" clears the limit (Hz, matching
|
||||
/// the stored unit directly — e.g. `192000`, not `192` kHz).
|
||||
fn parse_opt_u32(v: &str) -> Result<Option<u32>, String> {
|
||||
@@ -332,6 +353,7 @@ fn read_all(roots: &ProfileRoots) -> Result<Vec<(&'static str, String)>, String>
|
||||
"qconnect.volume_mode" => {
|
||||
qconnect_kv::load_volume_mode_at(&db).unwrap_or_else(|| "software".to_string())
|
||||
}
|
||||
"hooks.script" => prefs.hook_script.clone(),
|
||||
other => unreachable!("KEY_TABLE/read_all drifted apart on key: {other}"),
|
||||
};
|
||||
out.push((*key, value));
|
||||
@@ -557,6 +579,12 @@ pub(crate) fn write_one(roots: &ProfileRoots, key: &str, raw: &str) -> Result<Ap
|
||||
let v = parse_volume_mode(raw).map_err(SetError::Usage)?;
|
||||
qconnect_kv::save_volume_mode_at(&qconnect_db(roots), &v)
|
||||
}
|
||||
"hooks.script" => {
|
||||
let v = parse_hook_script(raw).map_err(SetError::Usage)?;
|
||||
let mut prefs = daemon_prefs::load_at(&roots.data);
|
||||
prefs.hook_script = v;
|
||||
daemon_prefs::save_at(&prefs, &roots.data).map_err(SetError::Io)?;
|
||||
}
|
||||
other => unreachable!("KEY_TABLE/write_one drifted apart on key: {other}"),
|
||||
}
|
||||
Ok(class)
|
||||
@@ -1215,6 +1243,30 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hook_script_accepts_absolute_or_empty_and_rejects_relative() {
|
||||
// Empty clears (hooks off, the default — and what `show`'s value must
|
||||
// round-trip through `set`); absolute paths pass verbatim; a relative
|
||||
// path is a USAGE mistake (the daemon spawns with no PATH lookup).
|
||||
assert_eq!(parse_hook_script(""), Ok(String::new()));
|
||||
assert_eq!(parse_hook_script(" "), Ok(String::new()));
|
||||
assert_eq!(
|
||||
parse_hook_script("/usr/local/bin/qbz-hook.sh"),
|
||||
Ok("/usr/local/bin/qbz-hook.sh".to_string())
|
||||
);
|
||||
assert!(parse_hook_script("qbz-hook.sh").is_err());
|
||||
assert!(parse_hook_script("./hook.sh").is_err());
|
||||
|
||||
let roots = scratch_roots("hook-script");
|
||||
let err = write_one(&roots, "hooks.script", "relative.sh").unwrap_err();
|
||||
assert!(matches!(err, SetError::Usage(_)), "{err:?}");
|
||||
write_one(&roots, "hooks.script", "/opt/hook.sh").expect("absolute path writes");
|
||||
assert_eq!(daemon_prefs::load_at(&roots.data).hook_script, "/opt/hook.sh");
|
||||
write_one(&roots, "hooks.script", "").expect("empty clears");
|
||||
assert_eq!(daemon_prefs::load_at(&roots.data).hook_script, "");
|
||||
cleanup(&roots);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn show_json_round_trips_into_set_for_every_canonical_key() {
|
||||
// The brief's Step 1 property: `settings show --json` includes every
|
||||
|
||||
@@ -96,6 +96,12 @@ pub async fn run(roots: ProfileRoots, cfg: QbzdConfig, warns: Vec<String>) -> Re
|
||||
// ordering — aborted alongside the scrobbler for a clean shutdown.
|
||||
let memwatch = qbz_app::memory_watchdog::spawn(booted.runtime.core().player());
|
||||
|
||||
// Attach the CoreEvent bus to the shared state so the qconnect lifecycle
|
||||
// latches can publish `QconnectSessionChanged` (SSE + the event hook).
|
||||
if let Ok(mut s) = booted.shared.lock() {
|
||||
s.bus = Some(booted.bus.clone());
|
||||
}
|
||||
|
||||
// 10. playback driver (T4). Spawn the 450 ms headless orchestrator on the
|
||||
// booted runtime + shared state. It runs safely regardless of auth: with
|
||||
// no session the queue is empty and each tick is a near-no-op. The
|
||||
@@ -117,7 +123,16 @@ pub async fn run(roots: ProfileRoots, cfg: QbzdConfig, warns: Vec<String>) -> Re
|
||||
// QConnect report scheduler (step 12) waits on it. Created BEFORE the driver
|
||||
// so `on_edge` can capture it, and shared with `qconnect::start`.
|
||||
let report_notify = Arc::new(tokio::sync::Notify::new());
|
||||
let deps = build_driver_deps(quality_cell.clone(), booted.shared.clone(), report_notify.clone());
|
||||
// The same edge, pulsed onto a SECOND Notify for the events bridge (10e):
|
||||
// two subscribers on one Notify would race for the single stored permit.
|
||||
let edge_notify = Arc::new(tokio::sync::Notify::new());
|
||||
let deps = build_driver_deps(
|
||||
quality_cell.clone(),
|
||||
booted.shared.clone(),
|
||||
report_notify.clone(),
|
||||
edge_notify.clone(),
|
||||
booted.bus.clone(),
|
||||
);
|
||||
let driver = tokio::spawn(playback_driver::run_driver(
|
||||
booted.runtime.clone(),
|
||||
deps,
|
||||
@@ -139,6 +154,27 @@ pub async fn run(roots: ProfileRoots, cfg: QbzdConfig, warns: Vec<String>) -> Re
|
||||
// outside the #521/§8.2 ordering — aborted for a clean shutdown below.
|
||||
let scrobbler = crate::scrobble_engine::spawn(roots.clone(), booted.bus.subscribe());
|
||||
|
||||
// 10c½. Events bridge: translate the driver's transition edges into the
|
||||
// playback CoreEvents the bus consumers above (and SSE, and the event
|
||||
// hook below) are written for — TrackStarted / PlaybackStateChanged /
|
||||
// PositionUpdated / VolumeChanged. Holds only a Weak<AppRuntime>
|
||||
// upgraded per wake, but is still aborted+joined ahead of
|
||||
// `drop(booted)` so a mid-wake strong Arc can't outlive the ordering.
|
||||
let events_bridge =
|
||||
crate::events_bridge::spawn(&booted.runtime, booted.bus.clone(), edge_notify);
|
||||
|
||||
// 10c¾. Event hook (CONSOLE): fork `hooks.script` (or `QBZD_HOOK`) once per
|
||||
// forwarded bus event with QBZ_* variables in its environment — push
|
||||
// integration for headless boxes (moOde-style renderer coordination).
|
||||
// Holds no Arc<AppRuntime>; aborted for a clean shutdown.
|
||||
let hooks = match crate::hooks::script(&roots) {
|
||||
Some(path) => {
|
||||
log::info!("[hooks] running {} on daemon events (hooks.script)", path.display());
|
||||
Some(crate::hooks::spawn(path, booted.bus.subscribe()))
|
||||
}
|
||||
None => None,
|
||||
};
|
||||
|
||||
// 10d. MPRIS media controls (CONSOLE): publish org.mpris.MediaPlayer2 so a
|
||||
// KDE/GNOME media widget, a plasmoid, or hardware media keys drive the
|
||||
// daemon with no custom client. The inbound callback holds a
|
||||
@@ -198,6 +234,7 @@ pub async fn run(roots: ProfileRoots, cfg: QbzdConfig, warns: Vec<String>) -> Re
|
||||
booted.runtime.clone(),
|
||||
booted.shared.clone(),
|
||||
&roots,
|
||||
quality_cell.clone(),
|
||||
report_notify,
|
||||
booted.bus.subscribe(),
|
||||
);
|
||||
@@ -236,6 +273,15 @@ pub async fn run(roots: ProfileRoots, cfg: QbzdConfig, warns: Vec<String>) -> Re
|
||||
// device — the same ordering constraint as the driver (§8.2).
|
||||
memwatch.abort();
|
||||
let _ = memwatch.await;
|
||||
// Stop the events bridge BEFORE `drop(booted)`: it upgrades its Weak to a
|
||||
// strong Arc<AppRuntime> for the span of each wake (#521 ordering).
|
||||
events_bridge.abort();
|
||||
let _ = events_bridge.await;
|
||||
// Stop the event-hook dispatcher (holds no Arc<AppRuntime>; order-free).
|
||||
if let Some(hooks) = hooks {
|
||||
hooks.abort();
|
||||
let _ = hooks.await;
|
||||
}
|
||||
// Tear down MPRIS: abort its updater and drop the D-Bus handle. Its inbound
|
||||
// callback held only a Weak<AppRuntime>, so this is order-free too.
|
||||
if let Some(mpris) = mpris {
|
||||
@@ -270,7 +316,7 @@ pub async fn run(roots: ProfileRoots, cfg: QbzdConfig, warns: Vec<String>) -> Re
|
||||
// Both calls self-gate to no-ops when QBZ forced nothing.
|
||||
#[cfg(target_os = "linux")]
|
||||
{
|
||||
qbz_audio::alsa_backend::resume_suspended_sink();
|
||||
let _ = qbz_audio::alsa_backend::resume_suspended_sink();
|
||||
qbz_audio::pipewire_backend::PipeWireBackend::reset_pipewire_clock();
|
||||
}
|
||||
|
||||
@@ -384,11 +430,14 @@ async fn boot(roots: &ProfileRoots, cfg: &QbzdConfig, warn_count: usize) -> Resu
|
||||
/// Assemble the driver's host side channels: the streaming-quality resolver and
|
||||
/// the daemon-shared latching / tick-timestamping hooks. T10: `on_edge` now
|
||||
/// pulses the QConnect report `Notify` so the report scheduler reports on the
|
||||
/// same transition/periodic edges the driver detects (§7.2).
|
||||
/// same transition/periodic edges the driver detects (§7.2) — and, on a second
|
||||
/// `Notify`, the events bridge (10c½) that publishes those edges to the bus.
|
||||
fn build_driver_deps(
|
||||
quality_cell: Arc<std::sync::Mutex<qbz_models::Quality>>,
|
||||
shared: Arc<Mutex<DaemonShared>>,
|
||||
report_notify: Arc<tokio::sync::Notify>,
|
||||
edge_notify: Arc<tokio::sync::Notify>,
|
||||
bus: tokio::sync::broadcast::Sender<qbz_models::CoreEvent>,
|
||||
) -> DriverDeps {
|
||||
let latch_shared = shared.clone();
|
||||
let tick_shared = shared;
|
||||
@@ -402,16 +451,28 @@ fn build_driver_deps(
|
||||
// T10: signal the report scheduler on every ReportEdge. `notify_one`
|
||||
// stores a single permit if the scheduler is mid-report, so no edge is
|
||||
// lost and rapid edges coalesce into one report.
|
||||
on_edge: Arc::new(move || report_notify.notify_one()),
|
||||
on_edge: Arc::new(move || {
|
||||
report_notify.notify_one();
|
||||
edge_notify.notify_one();
|
||||
}),
|
||||
on_latch: Arc::new(move |category, message| {
|
||||
if let Ok(mut s) = latch_shared.lock() {
|
||||
match category {
|
||||
"stream" => s.last_errors.stream = Some(message),
|
||||
"transport" => s.last_errors.transport = Some(message),
|
||||
"auth" => s.last_errors.auth = Some(message),
|
||||
"stream" => s.last_errors.stream = Some(message.clone()),
|
||||
"transport" => s.last_errors.transport = Some(message.clone()),
|
||||
"auth" => s.last_errors.auth = Some(message.clone()),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
// Surface stream failures on the bus too, so `/api/events` and the
|
||||
// event hook see them live (e.g. a busy ALSA device at play time)
|
||||
// instead of only the polled /api/status error latch.
|
||||
if category == "stream" {
|
||||
let _ = bus.send(qbz_models::CoreEvent::PlaybackError {
|
||||
track_id: 0,
|
||||
message,
|
||||
});
|
||||
}
|
||||
}),
|
||||
on_tick: Arc::new(move || {
|
||||
if let Ok(mut s) = tick_shared.lock() {
|
||||
@@ -517,6 +578,8 @@ fn new_shared(cfg: &QbzdConfig) -> Arc<Mutex<DaemonShared>> {
|
||||
qconnect: QconnectStatus::default(),
|
||||
credential_fingerprint: None,
|
||||
network_online: std::sync::atomic::AtomicBool::new(true),
|
||||
// Attached by daemon::run right after boot (the bus outlives boot).
|
||||
bus: None,
|
||||
}))
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,107 @@
|
||||
// crates/qbzd/src/events_bridge.rs — bridge playback-driver edges onto the
|
||||
// CoreEvent bus.
|
||||
//
|
||||
// The 450 ms playback driver detects track/play-state transitions
|
||||
// (`DriverAction::ReportEdge` -> `deps.on_edge`), but nothing translated those
|
||||
// edges into the playback CoreEvent variants the bus consumers were written
|
||||
// for: mpris.rs and scrobble_engine.rs both carry TrackStarted /
|
||||
// PlaybackStateChanged / PositionUpdated / VolumeChanged arms that never
|
||||
// fired, and `/api/events` (SSE) / `qbzd watch` carried no playback traffic at
|
||||
// all. This task closes that gap: it wakes on the same edge Notify pulse the
|
||||
// QConnect report scheduler uses (with a 2 s poll fallback, because
|
||||
// `plan_tick` only reports edges while a track id is present — a stop that
|
||||
// clears the track id would otherwise go unseen), reads the live player state,
|
||||
// dedups against what it last published, and sends the delta to the bus.
|
||||
//
|
||||
// Holds only a Weak<AppRuntime> (upgraded per wake, dropped before the next
|
||||
// wait), so it sits outside the #521 audio-release ordering — the caller
|
||||
// aborts it for a clean shutdown, same as the queue-persist subscriber.
|
||||
use std::sync::{Arc, Weak};
|
||||
use std::time::Duration;
|
||||
|
||||
use qbz_app::shell::AppRuntime;
|
||||
use qbz_models::{CoreEvent, PlaybackState};
|
||||
use tokio::sync::{broadcast, Notify};
|
||||
use tokio::task::JoinHandle;
|
||||
|
||||
use crate::adapter::DaemonAdapter;
|
||||
|
||||
type Runtime = Arc<AppRuntime<DaemonAdapter>>;
|
||||
|
||||
/// The poll fallback cadence: only exercised when no edge pulse arrives (e.g.
|
||||
/// a stop cleared the track id, which suppresses `ReportEdge`).
|
||||
const FALLBACK_POLL: Duration = Duration::from_secs(2);
|
||||
|
||||
/// Spawn the bridge task. Emits, deduped against the last published values:
|
||||
/// * `TrackStarted` on a track-id change while playing (with the queue's
|
||||
/// current-track metadata),
|
||||
/// * `PlaybackStateChanged` on a playing/paused/stopped change,
|
||||
/// * `PositionUpdated` on every wake while playing (~2 s cadence, the
|
||||
/// scrobbler's timing source and the MPRIS progress feed),
|
||||
/// * `VolumeChanged` on a volume change.
|
||||
pub fn spawn(runtime: &Runtime, bus: broadcast::Sender<CoreEvent>, edge: Arc<Notify>) -> JoinHandle<()> {
|
||||
let weak: Weak<AppRuntime<DaemonAdapter>> = Arc::downgrade(runtime);
|
||||
tokio::spawn(async move {
|
||||
let mut last_track_id: u64 = 0;
|
||||
let mut last_state: Option<PlaybackState> = None;
|
||||
let mut last_volume: Option<f32> = None;
|
||||
loop {
|
||||
// Wake on a driver edge, or fall back to a slow poll so a
|
||||
// track-id-clearing stop still surfaces as a transition.
|
||||
let _ = tokio::time::timeout(FALLBACK_POLL, edge.notified()).await;
|
||||
|
||||
let Some(rt) = weak.upgrade() else { return };
|
||||
let core = rt.core();
|
||||
let player = core.player();
|
||||
let ev = player.get_playback_event();
|
||||
let has_audio = player.has_loaded_audio();
|
||||
|
||||
if ev.track_id != 0 && ev.track_id != last_track_id && ev.is_playing {
|
||||
// The queue's current track carries the metadata (title/artist/
|
||||
// artwork). Skip when the cursor hasn't caught up yet — the next
|
||||
// wake retries because last_track_id only advances on a send.
|
||||
let queue = core.get_queue_state().await;
|
||||
if let Some(track) = queue.current_track.as_ref().filter(|t| t.id == ev.track_id) {
|
||||
let _ = bus.send(CoreEvent::TrackStarted {
|
||||
track: track.clone(),
|
||||
position_secs: ev.position,
|
||||
});
|
||||
last_track_id = ev.track_id;
|
||||
}
|
||||
}
|
||||
|
||||
// Same three-way mapping as the MPRIS seed: loaded-but-not-playing
|
||||
// audio is Paused, nothing loaded is Stopped. Dedup on the MAPPED
|
||||
// state, not `is_playing` — paused and stopped are both
|
||||
// not-playing, and a pause -> stop transition must still emit.
|
||||
let state = if ev.is_playing {
|
||||
PlaybackState::Playing
|
||||
} else if has_audio {
|
||||
PlaybackState::Paused
|
||||
} else {
|
||||
PlaybackState::Stopped
|
||||
};
|
||||
if last_state != Some(state) {
|
||||
let _ = bus.send(CoreEvent::PlaybackStateChanged { state });
|
||||
last_state = Some(state);
|
||||
// A stop ends the "current track": forget it so replaying the
|
||||
// same track emits a fresh TrackStarted (scrobbling, hooks).
|
||||
if state == PlaybackState::Stopped {
|
||||
last_track_id = 0;
|
||||
}
|
||||
}
|
||||
|
||||
if ev.is_playing {
|
||||
let _ = bus.send(CoreEvent::PositionUpdated {
|
||||
position_secs: ev.position,
|
||||
duration_secs: ev.duration,
|
||||
});
|
||||
}
|
||||
|
||||
if last_volume.is_none_or(|v| (v - ev.volume).abs() > 0.001) {
|
||||
let _ = bus.send(CoreEvent::VolumeChanged { volume: ev.volume });
|
||||
last_volume = Some(ev.volume);
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,331 @@
|
||||
// crates/qbzd/src/hooks.rs — run a user script on daemon events (CONSOLE ext).
|
||||
//
|
||||
// Headless integrators (moOde, Volumio, home-grown setups) need PUSH
|
||||
// notifications to coordinate the daemon with the rest of an audio box — stop
|
||||
// the local player when a Qobuz Connect session starts playing, restore the
|
||||
// volume when it ends — without keeping a poller or an SSE client alive.
|
||||
// `hooks.script` names an executable the daemon forks once per bus event with
|
||||
// the event described in `QBZ_*` environment variables, the same integration
|
||||
// contract pleezer (`--hook`) and shairport-sync (`run_this_...`) established.
|
||||
//
|
||||
// Enablement: the `QBZD_HOOK` env var wins when set (empty disables);
|
||||
// otherwise the persisted `daemon_prefs.hook_script` path, written by `qbzd
|
||||
// settings set hooks.script`. Changing it needs a daemon restart (the
|
||||
// dispatcher spawns at boot, like MPRIS).
|
||||
//
|
||||
// The dispatcher never waits for one script before receiving another event.
|
||||
// It does, however, cap concurrent children so a stuck integration cannot
|
||||
// turn a burst of events into an unbounded process storm. Scripts may overlap;
|
||||
// an integrator needing strict ordering can flock inside the script.
|
||||
use std::path::PathBuf;
|
||||
|
||||
use qbz_models::{CoreEvent, PlaybackState};
|
||||
use tokio::sync::broadcast;
|
||||
use tokio::task::{JoinHandle, JoinSet};
|
||||
|
||||
use crate::paths::ProfileRoots;
|
||||
|
||||
/// Hooks are an integration escape hatch, not a job runner. Four concurrent
|
||||
/// children leave room for short event bursts while putting a hard ceiling on
|
||||
/// a broken or hung script.
|
||||
const MAX_CONCURRENT_HOOKS: usize = 4;
|
||||
|
||||
fn parse_script(raw: &str) -> Option<PathBuf> {
|
||||
let trimmed = raw.trim();
|
||||
if trimmed.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let path = PathBuf::from(trimmed);
|
||||
if !path.is_absolute() {
|
||||
log::warn!(
|
||||
"[hooks] ignoring non-absolute script path '{}'; use an absolute path",
|
||||
path.display()
|
||||
);
|
||||
return None;
|
||||
}
|
||||
Some(path)
|
||||
}
|
||||
|
||||
/// Resolve the configured hook script: `QBZD_HOOK` when set (empty string
|
||||
/// disables), else the persisted `hooks.script` setting; None = hooks off.
|
||||
pub fn script(roots: &ProfileRoots) -> Option<PathBuf> {
|
||||
let raw = match std::env::var("QBZD_HOOK") {
|
||||
Ok(v) => v,
|
||||
Err(_) => qbz_app::settings::daemon_prefs::load_at(&roots.data).hook_script,
|
||||
};
|
||||
parse_script(&raw)
|
||||
}
|
||||
|
||||
/// Spawn the hook dispatcher. Holds no `Arc<AppRuntime>` (only the script path
|
||||
/// and the bus receiver), so it sits outside the §8.2 audio-release ordering —
|
||||
/// the caller aborts it for a clean shutdown, like the scrobbler.
|
||||
pub fn spawn(script: PathBuf, mut rx: broadcast::Receiver<CoreEvent>) -> JoinHandle<()> {
|
||||
use broadcast::error::RecvError;
|
||||
tokio::spawn(async move {
|
||||
let mut children = JoinSet::new();
|
||||
loop {
|
||||
let ev = tokio::select! {
|
||||
received = rx.recv() => match received {
|
||||
Ok(ev) => ev,
|
||||
Err(RecvError::Lagged(skipped)) => {
|
||||
log::warn!("[hooks] event receiver lagged; skipped {skipped} event(s)");
|
||||
continue;
|
||||
}
|
||||
Err(RecvError::Closed) => return,
|
||||
},
|
||||
finished = children.join_next(), if !children.is_empty() => {
|
||||
if let Some(Err(e)) = finished {
|
||||
log::debug!("[hooks] reaper task ended unexpectedly: {e}");
|
||||
}
|
||||
continue;
|
||||
}
|
||||
};
|
||||
let Some(vars) = hook_env(&ev) else { continue };
|
||||
if children.len() >= MAX_CONCURRENT_HOOKS {
|
||||
log::warn!(
|
||||
"[hooks] dropping event while {MAX_CONCURRENT_HOOKS} hook scripts are still running"
|
||||
);
|
||||
continue;
|
||||
}
|
||||
let mut cmd = tokio::process::Command::new(&script);
|
||||
cmd.envs(vars)
|
||||
.stdin(std::process::Stdio::null())
|
||||
.kill_on_drop(true);
|
||||
match cmd.spawn() {
|
||||
Ok(mut child) => {
|
||||
// JoinSet owns every reaper. Dropping the dispatcher aborts
|
||||
// them, and kill_on_drop then terminates their children.
|
||||
children.spawn(async move {
|
||||
let _ = child.wait().await;
|
||||
});
|
||||
}
|
||||
Err(e) => log::warn!("[hooks] could not run {}: {e}", script.display()),
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn state_label(state: PlaybackState) -> &'static str {
|
||||
match state {
|
||||
PlaybackState::Playing => "playing",
|
||||
PlaybackState::Paused => "paused",
|
||||
PlaybackState::Stopped => "stopped",
|
||||
PlaybackState::Loading => "loading",
|
||||
}
|
||||
}
|
||||
|
||||
/// Map one bus event onto the script's `QBZ_*` environment, or None for
|
||||
/// events the hook does not forward. Deliberately excluded: `PositionUpdated`
|
||||
/// (a fork every ~2 s), `QueueUpdated` (bulky, and queue state is one
|
||||
/// `GET /api/status` away), and everything on the SSE suppress list. The
|
||||
/// `LoggedIn` session payload (auth token) is NEVER forwarded — the event
|
||||
/// name alone is.
|
||||
fn hook_env(ev: &CoreEvent) -> Option<Vec<(String, String)>> {
|
||||
use CoreEvent::*;
|
||||
let mut vars: Vec<(String, String)> = Vec::new();
|
||||
let mut push = |k: &str, v: String| vars.push((format!("QBZ_{k}"), v));
|
||||
match ev {
|
||||
TrackStarted {
|
||||
track,
|
||||
position_secs,
|
||||
} => {
|
||||
push("EVENT", "TrackStarted".into());
|
||||
push("TRACK_ID", track.id.to_string());
|
||||
push("TITLE", track.title.clone());
|
||||
push("ARTIST", track.artist.clone());
|
||||
push("ALBUM", track.album.clone());
|
||||
push("DURATION", track.duration_secs.to_string());
|
||||
push("POSITION", position_secs.to_string());
|
||||
if let Some(url) = &track.artwork_url {
|
||||
push("COVER_URL", url.clone());
|
||||
}
|
||||
if let Some(bits) = track.bit_depth {
|
||||
push("BIT_DEPTH", bits.to_string());
|
||||
}
|
||||
if let Some(rate) = track.sample_rate {
|
||||
push("SAMPLE_RATE", rate.to_string());
|
||||
}
|
||||
}
|
||||
PlaybackStateChanged { state } => {
|
||||
push("EVENT", "PlaybackStateChanged".into());
|
||||
push("STATE", state_label(*state).into());
|
||||
}
|
||||
TrackEnded { track_id } => {
|
||||
push("EVENT", "TrackEnded".into());
|
||||
push("TRACK_ID", track_id.to_string());
|
||||
}
|
||||
VolumeChanged { volume } => {
|
||||
push("EVENT", "VolumeChanged".into());
|
||||
// 0-100, the same scale the `qbzd volume` verb speaks.
|
||||
push(
|
||||
"VOLUME",
|
||||
(((*volume).clamp(0.0, 1.0) * 100.0).round() as u32).to_string(),
|
||||
);
|
||||
}
|
||||
QconnectSessionChanged {
|
||||
state,
|
||||
device_name,
|
||||
session_active,
|
||||
} => {
|
||||
push("EVENT", "QconnectSessionChanged".into());
|
||||
push("STATE", state.clone());
|
||||
push("SESSION_ACTIVE", session_active.to_string());
|
||||
if let Some(name) = device_name {
|
||||
push("DEVICE_NAME", name.clone());
|
||||
}
|
||||
}
|
||||
LoggedIn { .. } => push("EVENT", "LoggedIn".into()),
|
||||
LoggedOut => push("EVENT", "LoggedOut".into()),
|
||||
SessionExpired => push("EVENT", "SessionExpired".into()),
|
||||
Error {
|
||||
code,
|
||||
message,
|
||||
recoverable,
|
||||
} => {
|
||||
push("EVENT", "Error".into());
|
||||
push("CODE", code.clone());
|
||||
push("MESSAGE", message.clone());
|
||||
push("RECOVERABLE", recoverable.to_string());
|
||||
}
|
||||
PlaybackError { track_id, message } => {
|
||||
push("EVENT", "PlaybackError".into());
|
||||
push("TRACK_ID", track_id.to_string());
|
||||
push("MESSAGE", message.clone());
|
||||
}
|
||||
AudioDeviceChanged { device_name } => {
|
||||
push("EVENT", "AudioDeviceChanged".into());
|
||||
push("DEVICE_NAME", device_name.clone());
|
||||
}
|
||||
_ => return None,
|
||||
}
|
||||
// The full tagged JSON for scripts that prefer jq over positional vars —
|
||||
// except LoggedIn, whose session payload stays out of child environments.
|
||||
if !matches!(ev, LoggedIn { .. }) {
|
||||
if let Ok(json) = serde_json::to_string(ev) {
|
||||
vars.push(("QBZ_EVENT_JSON".to_string(), json));
|
||||
}
|
||||
}
|
||||
Some(vars)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn get<'a>(vars: &'a [(String, String)], key: &str) -> Option<&'a str> {
|
||||
vars.iter().find(|(k, _)| k == key).map(|(_, v)| v.as_str())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hook_path_must_be_absolute() {
|
||||
assert_eq!(parse_script(" "), None);
|
||||
assert_eq!(parse_script("relative/hook.sh"), None);
|
||||
assert_eq!(
|
||||
parse_script(" /opt/qbz/hook.sh "),
|
||||
Some(PathBuf::from("/opt/qbz/hook.sh"))
|
||||
);
|
||||
}
|
||||
|
||||
/// A minimal QueueTrack via its serde defaults (the struct has no Default
|
||||
/// impl, and adding one to the shared models is not this feature's call).
|
||||
fn test_track() -> qbz_models::QueueTrack {
|
||||
serde_json::from_value(serde_json::json!({
|
||||
"id": 42,
|
||||
"title": "Red Beans",
|
||||
"artist": "Jon Batiste",
|
||||
"album": "Monk Movements",
|
||||
"duration_secs": 163,
|
||||
"artwork_url": "https://example.com/cover.jpg",
|
||||
"bit_depth": 24,
|
||||
"sample_rate": 48.0,
|
||||
"album_id": null,
|
||||
"artist_id": null,
|
||||
}))
|
||||
.expect("QueueTrack from JSON")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn track_started_carries_metadata_and_json() {
|
||||
let track = test_track();
|
||||
let vars = hook_env(&CoreEvent::TrackStarted {
|
||||
track,
|
||||
position_secs: 7,
|
||||
})
|
||||
.expect("TrackStarted is forwarded");
|
||||
assert_eq!(get(&vars, "QBZ_EVENT"), Some("TrackStarted"));
|
||||
assert_eq!(get(&vars, "QBZ_TITLE"), Some("Red Beans"));
|
||||
assert_eq!(get(&vars, "QBZ_ARTIST"), Some("Jon Batiste"));
|
||||
assert_eq!(get(&vars, "QBZ_DURATION"), Some("163"));
|
||||
assert_eq!(get(&vars, "QBZ_POSITION"), Some("7"));
|
||||
assert_eq!(get(&vars, "QBZ_BIT_DEPTH"), Some("24"));
|
||||
let json = get(&vars, "QBZ_EVENT_JSON").expect("JSON payload present");
|
||||
assert!(json.contains("\"type\":\"TrackStarted\""));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn playback_state_uses_lowercase_labels() {
|
||||
for (state, label) in [
|
||||
(PlaybackState::Playing, "playing"),
|
||||
(PlaybackState::Paused, "paused"),
|
||||
(PlaybackState::Stopped, "stopped"),
|
||||
(PlaybackState::Loading, "loading"),
|
||||
] {
|
||||
let vars = hook_env(&CoreEvent::PlaybackStateChanged { state }).unwrap();
|
||||
assert_eq!(get(&vars, "QBZ_STATE"), Some(label));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qconnect_session_changed_is_forwarded() {
|
||||
let vars = hook_env(&CoreEvent::QconnectSessionChanged {
|
||||
state: "connected".into(),
|
||||
device_name: Some("Moode Qobuz".into()),
|
||||
session_active: true,
|
||||
})
|
||||
.unwrap();
|
||||
assert_eq!(get(&vars, "QBZ_EVENT"), Some("QconnectSessionChanged"));
|
||||
assert_eq!(get(&vars, "QBZ_STATE"), Some("connected"));
|
||||
assert_eq!(get(&vars, "QBZ_SESSION_ACTIVE"), Some("true"));
|
||||
assert_eq!(get(&vars, "QBZ_DEVICE_NAME"), Some("Moode Qobuz"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn logged_in_forwards_the_event_name_but_never_the_session() {
|
||||
let session: qbz_models::UserSession = serde_json::from_value(serde_json::json!({
|
||||
"user_auth_token": "SECRET-TOKEN",
|
||||
"user_id": 1,
|
||||
"email": "user@example.com",
|
||||
"display_name": "User",
|
||||
"subscription_label": "Studio",
|
||||
}))
|
||||
.expect("UserSession from JSON");
|
||||
let vars = hook_env(&CoreEvent::LoggedIn { session }).unwrap();
|
||||
assert_eq!(get(&vars, "QBZ_EVENT"), Some("LoggedIn"));
|
||||
// Redaction: no JSON payload, no token, exactly one variable.
|
||||
assert_eq!(vars.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn chatty_and_bulky_events_are_not_forwarded() {
|
||||
assert!(
|
||||
hook_env(&CoreEvent::PositionUpdated {
|
||||
position_secs: 1,
|
||||
duration_secs: 2
|
||||
})
|
||||
.is_none()
|
||||
);
|
||||
assert!(hook_env(&CoreEvent::ShuffleChanged { enabled: true }).is_none());
|
||||
assert!(
|
||||
hook_env(&CoreEvent::LoadingStarted {
|
||||
operation: "x".into()
|
||||
})
|
||||
.is_none()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn volume_is_forwarded_on_the_cli_percent_scale() {
|
||||
let vars = hook_env(&CoreEvent::VolumeChanged { volume: 0.45 }).unwrap();
|
||||
assert_eq!(get(&vars, "QBZ_VOLUME"), Some("45"));
|
||||
}
|
||||
}
|
||||
@@ -5,6 +5,8 @@ mod api;
|
||||
mod cli;
|
||||
mod config;
|
||||
mod daemon;
|
||||
mod events_bridge;
|
||||
mod hooks;
|
||||
mod lock;
|
||||
mod login;
|
||||
mod mpris;
|
||||
|
||||
@@ -84,13 +84,22 @@ pub struct DaemonRendererEngine {
|
||||
runtime: Arc<AppRuntime<DaemonAdapter>>,
|
||||
/// T10 (OD4): resolved volume policy for this session (from the KV at connect).
|
||||
volume_mode: VolumeMode,
|
||||
/// Live daemon `playback.quality` preference. The settings reload route
|
||||
/// updates this same cell, so an active QConnect session honors changes
|
||||
/// without reconnecting (#693).
|
||||
quality_cap: Arc<std::sync::Mutex<Quality>>,
|
||||
}
|
||||
|
||||
impl DaemonRendererEngine {
|
||||
pub fn new(runtime: Arc<AppRuntime<DaemonAdapter>>, volume_mode: VolumeMode) -> Self {
|
||||
pub fn new(
|
||||
runtime: Arc<AppRuntime<DaemonAdapter>>,
|
||||
volume_mode: VolumeMode,
|
||||
quality_cap: Arc<std::sync::Mutex<Quality>>,
|
||||
) -> Self {
|
||||
Self {
|
||||
runtime,
|
||||
volume_mode,
|
||||
quality_cap,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -98,6 +107,15 @@ impl DaemonRendererEngine {
|
||||
self.runtime.core()
|
||||
}
|
||||
|
||||
fn effective_quality(&self, requested: Quality) -> Quality {
|
||||
let cap = self
|
||||
.quality_cap
|
||||
.lock()
|
||||
.map(|quality| *quality)
|
||||
.unwrap_or_else(|poisoned| *poisoned.into_inner());
|
||||
clamp_quality(requested, cap)
|
||||
}
|
||||
|
||||
/// Last-resort load for tracks the raw-URL path cannot fetch (the CDN
|
||||
/// header flood defeats every reqwest attempt — see
|
||||
/// `remote_stream::is_header_flood_error`): the CMAF path is unaffected by
|
||||
@@ -209,10 +227,18 @@ impl QconnectRendererEngine for DaemonRendererEngine {
|
||||
async fn start_track_stream(
|
||||
&self,
|
||||
track_id: u64,
|
||||
quality: Quality,
|
||||
requested_quality: Quality,
|
||||
duration_secs: u64,
|
||||
start_position_secs: u64,
|
||||
) -> Result<(), String> {
|
||||
let quality = self.effective_quality(requested_quality);
|
||||
if quality != requested_quality {
|
||||
log::info!(
|
||||
"[QConnect] playback.quality capped track {track_id}: controller requested {:?}, using {:?}",
|
||||
requested_quality,
|
||||
quality
|
||||
);
|
||||
}
|
||||
let stream_url = self
|
||||
.core()
|
||||
.get_stream_url(track_id, quality)
|
||||
@@ -280,6 +306,9 @@ impl QconnectRendererEngine for DaemonRendererEngine {
|
||||
}
|
||||
}
|
||||
|
||||
fn clamp_quality(requested: Quality, cap: Quality) -> Quality {
|
||||
Quality::min_tier(requested, cap)
|
||||
}
|
||||
|
||||
async fn download_remote_audio(url: &str) -> Result<Vec<u8>, String> {
|
||||
let response = reqwest::Client::new()
|
||||
@@ -349,4 +378,22 @@ mod tests {
|
||||
// Whitespace around the real value is tolerated.
|
||||
assert_eq!(VolumeMode::from_kv(Some(" locked ")), VolumeMode::Locked);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qconnect_quality_never_exceeds_daemon_preference() {
|
||||
let tiers = [
|
||||
Quality::Mp3,
|
||||
Quality::Lossless,
|
||||
Quality::HiRes,
|
||||
Quality::UltraHiRes,
|
||||
];
|
||||
for requested in tiers {
|
||||
for cap in tiers {
|
||||
let effective = clamp_quality(requested, cap);
|
||||
assert!(effective <= requested);
|
||||
assert!(effective <= cap);
|
||||
assert_eq!(effective, requested.min(cap));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -103,6 +103,9 @@ fn latch_lifecycle_into_shared(shared: &SharedState, state: QconnectLifecycleSta
|
||||
if matches!(state, QconnectLifecycleState::Connected) {
|
||||
s.set_network_online(true);
|
||||
}
|
||||
// Surface the transition on the CoreEvent bus (SSE, `qbzd watch`,
|
||||
// the event hook) alongside the /api/status latch.
|
||||
s.emit_qconnect_session_changed();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -144,6 +147,10 @@ pub struct DaemonQconnectService {
|
||||
#[allow(dead_code)] // T11 (settings reload) re-reads the KV through this path.
|
||||
settings_db: PathBuf,
|
||||
custom_device_name: Arc<tokio::sync::RwLock<Option<String>>>,
|
||||
/// Shared with the playback driver and settings reload route; the engine
|
||||
/// reads it for every remote stream start so QConnect cannot bypass the
|
||||
/// daemon's configured maximum quality (#693).
|
||||
quality_cap: Arc<std::sync::Mutex<qbz_models::Quality>>,
|
||||
}
|
||||
|
||||
impl DaemonQconnectService {
|
||||
@@ -194,7 +201,11 @@ impl DaemonQconnectService {
|
||||
// next connect. Unset/unknown -> Software (the OD4 default).
|
||||
let volume_mode =
|
||||
engine::VolumeMode::from_kv(transport::load_volume_mode_at(&self.settings_db).as_deref());
|
||||
let engine = DaemonRendererEngine::new(Arc::clone(&self.runtime), volume_mode);
|
||||
let engine = DaemonRendererEngine::new(
|
||||
Arc::clone(&self.runtime),
|
||||
volume_mode,
|
||||
Arc::clone(&self.quality_cap),
|
||||
);
|
||||
let sink = Arc::new(DaemonEventSink::new(engine, Arc::clone(&sync_state)));
|
||||
let app = Arc::new(QconnectApp::new(
|
||||
Arc::clone(&transport),
|
||||
@@ -309,6 +320,7 @@ impl DaemonQconnectService {
|
||||
if let Ok(mut s) = self.shared.lock() {
|
||||
s.qconnect.state = "off".to_string();
|
||||
s.qconnect.session_active = false;
|
||||
s.emit_qconnect_session_changed();
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -462,6 +474,7 @@ pub fn start(
|
||||
runtime: Runtime,
|
||||
shared: SharedState,
|
||||
roots: &ProfileRoots,
|
||||
quality_cap: Arc<std::sync::Mutex<qbz_models::Quality>>,
|
||||
report_notify: Arc<tokio::sync::Notify>,
|
||||
core_events: broadcast::Receiver<CoreEvent>,
|
||||
) -> QconnectHandle {
|
||||
@@ -492,6 +505,7 @@ pub fn start(
|
||||
shared,
|
||||
settings_db,
|
||||
custom_device_name: Arc::new(tokio::sync::RwLock::new(custom_name)),
|
||||
quality_cap,
|
||||
});
|
||||
|
||||
let watcher = if should_auto_connect {
|
||||
|
||||
@@ -129,6 +129,7 @@ impl SessionLoopHost for DaemonSessionLoopHost {
|
||||
// latch `network.online` false (the success side latches true in
|
||||
// `latch_lifecycle_into_shared` on the next `Connected` transition).
|
||||
s.set_network_online(false);
|
||||
s.emit_qconnect_session_changed();
|
||||
}
|
||||
log::warn!("[QConnect] Reconnect exhausted ({attempts}): {last_reason}");
|
||||
// Daemon has no offline MODE, so the desktop's idle-retry offline park is
|
||||
|
||||
@@ -45,6 +45,10 @@ pub struct DaemonShared {
|
||||
/// funnels through) or a successful QConnect (re)connect. Defaults true
|
||||
/// (optimistic) until the first outcome latches it.
|
||||
pub network_online: std::sync::atomic::AtomicBool,
|
||||
/// CoreEvent bus handle so state mutations here can publish matching bus
|
||||
/// events (`emit_qconnect_session_changed`). None until `daemon::run`
|
||||
/// attaches it right after boot; tests leave it None.
|
||||
pub bus: Option<tokio::sync::broadcast::Sender<qbz_models::CoreEvent>>,
|
||||
}
|
||||
|
||||
impl DaemonShared {
|
||||
@@ -62,6 +66,21 @@ impl DaemonShared {
|
||||
self.network_online
|
||||
.store(online, std::sync::atomic::Ordering::Relaxed);
|
||||
}
|
||||
|
||||
/// Publish the CURRENT `qconnect` block as a `QconnectSessionChanged` bus
|
||||
/// event (SSE `/api/events`, `qbzd watch`, the event hook). Call AFTER
|
||||
/// mutating `self.qconnect`; a best-effort no-op before the bus attaches
|
||||
/// or when no receiver is subscribed.
|
||||
pub fn emit_qconnect_session_changed(&self) {
|
||||
if let Some(bus) = &self.bus {
|
||||
let _ = bus.send(qbz_models::CoreEvent::QconnectSessionChanged {
|
||||
state: self.qconnect.state.clone(),
|
||||
device_name: (!self.qconnect.device_name.is_empty())
|
||||
.then(|| self.qconnect.device_name.clone()),
|
||||
session_active: self.qconnect.session_active,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A non-reversible-in-practice fingerprint of a credential token (SipHash via
|
||||
@@ -141,6 +160,7 @@ mod tests {
|
||||
qconnect: QconnectStatus::default(),
|
||||
credential_fingerprint: None,
|
||||
network_online: std::sync::atomic::AtomicBool::new(true),
|
||||
bus: None,
|
||||
};
|
||||
assert_eq!(shared.auth, AuthState::LoggedIn);
|
||||
assert_eq!(shared.user_id, Some(1234567));
|
||||
@@ -164,6 +184,7 @@ mod tests {
|
||||
qconnect: QconnectStatus::default(),
|
||||
credential_fingerprint: None,
|
||||
network_online: std::sync::atomic::AtomicBool::new(true),
|
||||
bus: None,
|
||||
};
|
||||
assert!(shared.network_online(), "defaults true (optimistic)");
|
||||
|
||||
|
||||
@@ -439,7 +439,43 @@ pub async fn apply_renderer_command(
|
||||
if let Some(value) = resolved_playing_state {
|
||||
match value {
|
||||
PLAYING_STATE_PLAYING => {
|
||||
engine.resume()?;
|
||||
// A state-only resume (current_track = null, e.g. a
|
||||
// mid-track handoff from a peer renderer after the
|
||||
// engine restarted) can land on an engine whose queue
|
||||
// cursor is set but which holds NO loaded audio — the
|
||||
// session store restores the queue paused and
|
||||
// unloaded. A bare resume() then dies in the audio
|
||||
// thread ("cannot resume - no audio data available")
|
||||
// while the cloud keeps reporting paused 0:00 to the
|
||||
// controller forever. Cold-load the cloud's current
|
||||
// track at its position first, exactly like the
|
||||
// SetActive takeback path; the has_loaded_audio gate
|
||||
// keeps echoes and live playback on the plain resume.
|
||||
let cold_engine = !engine.has_loaded_audio();
|
||||
let cold_track = projection_renderer_state.current_track.as_ref();
|
||||
if cold_engine && cold_track.is_some() {
|
||||
let track_id = cold_track.map(|t| t.track_id).unwrap_or(0);
|
||||
let start_position_secs = renderer_state
|
||||
.current_position_ms
|
||||
.or(*current_position_ms)
|
||||
.map(|ms| ms / 1000)
|
||||
.unwrap_or(0);
|
||||
if let Err(err) = force_remote_track_stream(
|
||||
engine,
|
||||
sync_state,
|
||||
track_id,
|
||||
projection_renderer_state.max_audio_quality,
|
||||
start_position_secs,
|
||||
)
|
||||
.await
|
||||
{
|
||||
log::warn!(
|
||||
"[QConnect] Cold-start load of remote track {track_id} failed: {err}"
|
||||
);
|
||||
}
|
||||
} else {
|
||||
engine.resume()?;
|
||||
}
|
||||
}
|
||||
PLAYING_STATE_PAUSED => {
|
||||
engine.pause()?;
|
||||
@@ -1244,6 +1280,88 @@ mod tests {
|
||||
assert_eq!(engine.calls().seeks, vec![40]);
|
||||
}
|
||||
|
||||
/// A state-only resume (current_track = null) on a COLD engine — queue
|
||||
/// cursor restored but no audio loaded, as after a daemon restart — must
|
||||
/// cold-load the cloud's current track at the handed-off position instead
|
||||
/// of issuing a bare resume that dies in the audio thread ("cannot resume
|
||||
/// - no audio data available") and wedges the controller at paused 0:00.
|
||||
#[tokio::test]
|
||||
async fn apply_renderer_command_cold_resume_loads_current_track() {
|
||||
let mut engine = MockEngine::new();
|
||||
// Cursor reports the restored track, but nothing is loaded: the plain
|
||||
// track-id guard would skip, which is why the force path is used.
|
||||
engine.playback = PlaybackState {
|
||||
track_id: 7,
|
||||
..Default::default()
|
||||
};
|
||||
engine.queue_tracks = vec![mock_queue_track(7)];
|
||||
engine.queue_index = Some(0);
|
||||
engine.loaded_audio = false;
|
||||
let sync = sync();
|
||||
let cmd = RendererCommand::SetState {
|
||||
playing_state: Some(PLAYING_STATE_PLAYING),
|
||||
current_position_ms: None,
|
||||
current_track: None,
|
||||
next_track: None,
|
||||
};
|
||||
// The cloud's view carries the session's current track + position.
|
||||
let renderer_state = QConnectRendererState {
|
||||
current_track: Some(qi(7, 2)),
|
||||
current_position_ms: Some(242_491),
|
||||
..Default::default()
|
||||
};
|
||||
apply_renderer_command(&engine, &sync, &cmd, &renderer_state)
|
||||
.await
|
||||
.unwrap();
|
||||
let calls = engine.calls();
|
||||
assert_eq!(
|
||||
calls.start_track_streams,
|
||||
vec![7],
|
||||
"cold resume must load the session's current track"
|
||||
);
|
||||
assert_eq!(
|
||||
calls.start_positions,
|
||||
vec![242],
|
||||
"load must resume at the handed-off position"
|
||||
);
|
||||
assert_eq!(calls.resumes, 0, "no bare resume on a cold engine");
|
||||
}
|
||||
|
||||
/// The cold-start load never fires while audio is loaded: a resume during
|
||||
/// live playback (or a cloud echo) stays a plain resume, no re-stream.
|
||||
#[tokio::test]
|
||||
async fn apply_renderer_command_warm_resume_stays_plain() {
|
||||
let mut engine = MockEngine::new();
|
||||
engine.playback = PlaybackState {
|
||||
track_id: 7,
|
||||
position: 30,
|
||||
..Default::default()
|
||||
};
|
||||
engine.queue_tracks = vec![mock_queue_track(7)];
|
||||
engine.queue_index = Some(0);
|
||||
engine.loaded_audio = true;
|
||||
let sync = sync();
|
||||
let cmd = RendererCommand::SetState {
|
||||
playing_state: Some(PLAYING_STATE_PLAYING),
|
||||
current_position_ms: None,
|
||||
current_track: None,
|
||||
next_track: None,
|
||||
};
|
||||
let renderer_state = QConnectRendererState {
|
||||
current_track: Some(qi(7, 2)),
|
||||
..Default::default()
|
||||
};
|
||||
apply_renderer_command(&engine, &sync, &cmd, &renderer_state)
|
||||
.await
|
||||
.unwrap();
|
||||
let calls = engine.calls();
|
||||
assert!(
|
||||
calls.start_track_streams.is_empty(),
|
||||
"no re-stream while audio is loaded"
|
||||
);
|
||||
assert_eq!(calls.resumes, 1, "plain resume on a warm engine");
|
||||
}
|
||||
|
||||
/// #4 — WS-authoritative shuffle: a standalone SetShuffleMode must flip the
|
||||
/// flag ONLY (set_shuffle_flag), NEVER generate a local order. It must not
|
||||
/// call the order-generating set_shuffle, and must not apply any queue order
|
||||
|
||||
@@ -62,6 +62,72 @@ systemctl --user enable --now qbzd
|
||||
systemctl --user status qbzd
|
||||
```
|
||||
|
||||
## System service (appliances and HiFiBerryOS)
|
||||
|
||||
`qbzd` can also emit a **system-scoped** unit. This is the form an appliance
|
||||
manager can control with ordinary `systemctl` even when no user is logged in:
|
||||
|
||||
```bash
|
||||
qbzd service systemd --system --user "$USER" --bin /usr/bin/qbzd \
|
||||
| sudo tee /etc/systemd/system/qbzd.service >/dev/null
|
||||
sudo systemctl daemon-reload
|
||||
sudo systemctl enable --now qbzd
|
||||
sudo systemctl status qbzd
|
||||
```
|
||||
|
||||
`--system` changes who owns and manages the unit; it deliberately does **not**
|
||||
run the audio player as root. The generated unit contains `User=`, `HOME=` and
|
||||
`XDG_RUNTIME_DIR=` for the selected account. Keep that account in the `audio`
|
||||
group when using ALSA Direct, and enable linger when its PipeWire/Pulse socket
|
||||
lives under `/run/user/<uid>`:
|
||||
|
||||
```bash
|
||||
sudo usermod -aG audio "$USER"
|
||||
sudo loginctl enable-linger "$USER"
|
||||
```
|
||||
|
||||
HiFiBerryOS Next Generation can register an external player through drop-in
|
||||
files. Point its `systemd_service` field at `qbzd`; the upstream
|
||||
[Add your own player](https://github.com/hifiberry/hifiberry-os/blob/main/docs/add-your-own-player.md)
|
||||
guide documents the player descriptor, AudioControl registration and
|
||||
config-server permission files. A native HiFiBerry package can therefore own
|
||||
the unit and expose its on/off switch without making `qbzd` a root process.
|
||||
|
||||
## Read-only root filesystems
|
||||
|
||||
All default profile paths follow the standard XDG variables. Redirect them to
|
||||
writable mounts before running `qbzd setup`, then use the same environment in
|
||||
the service. This example keeps configuration and databases on persistent
|
||||
storage while putting disposable cache data in RAM (replace `/data` and the
|
||||
`qbz` account with paths/usernames from the appliance):
|
||||
|
||||
```bash
|
||||
sudo install -d -o qbz -g qbz /data/qbzd-config /data/qbzd-data
|
||||
sudo -u qbz env \
|
||||
XDG_CONFIG_HOME=/data/qbzd-config \
|
||||
XDG_DATA_HOME=/data/qbzd-data \
|
||||
XDG_CACHE_HOME=/run/qbzd-cache \
|
||||
/usr/bin/qbzd setup
|
||||
```
|
||||
|
||||
Add the same paths to the system unit with `sudo systemctl edit qbzd`:
|
||||
|
||||
```ini
|
||||
[Service]
|
||||
Environment=XDG_CONFIG_HOME=/data/qbzd-config
|
||||
Environment=XDG_DATA_HOME=/data/qbzd-data
|
||||
Environment=XDG_CACHE_HOME=/run/qbzd-cache
|
||||
RuntimeDirectory=qbzd-cache
|
||||
RuntimeDirectoryMode=0700
|
||||
```
|
||||
|
||||
After `sudo systemctl daemon-reload && sudo systemctl restart qbzd`, the roots
|
||||
reported by `qbzd status` should all be writable. As a simpler container-style
|
||||
alternative, set `data_root = "/writable/qbzd-state"` in `qbzd.toml`; this
|
||||
moves both application data and its cache below that directory. The XDG config
|
||||
root still holds `qbzd.toml` and the login credential, so it must remain
|
||||
readable (and writable whenever login/settings are changed).
|
||||
|
||||
## Why glibc 2.35
|
||||
|
||||
This binary is built on ubuntu-22.04 (glibc 2.35) specifically so it runs on
|
||||
|
||||
@@ -100,6 +100,11 @@ parts:
|
||||
- libasound2t64
|
||||
- libasound2-plugins
|
||||
- libpipewire-0.3-0
|
||||
# Keep the runtime tools used by PipeWireBackend in both architectures.
|
||||
# They expose host sinks (including Bluetooth) and permit explicit sink
|
||||
# routing inside the connected strict Snap sandbox (#703).
|
||||
- pipewire-bin
|
||||
- pulseaudio-utils
|
||||
- libjack-jackd2-0
|
||||
# TLS / HTTP
|
||||
- libssl3t64
|
||||
|
||||
@@ -100,6 +100,12 @@ parts:
|
||||
- libasound2t64
|
||||
- libasound2-plugins
|
||||
- libpipewire-0.3-0
|
||||
# The backend invokes these at runtime: pw-dump discovers the host sinks
|
||||
# (including Bluetooth) and pw-metadata/pactl select and inspect them.
|
||||
# Without the binaries the strict Snap sees only the generic CPAL bridge
|
||||
# even when the pipewire plug is connected (#703).
|
||||
- pipewire-bin
|
||||
- pulseaudio-utils
|
||||
- libjack-jackd2-0
|
||||
# TLS / HTTP
|
||||
- libssl3t64
|
||||
|
||||
Reference in new issue
Block a user