fix: restore playback buffering and mpris controls

This commit is contained in:
vicrodh committed 2026-01-13 15:06:49 -06:00
1 parent 3e3cc4746d
commit a86dc5bcba
12 files changed
+477 -38

No files matched your search

+3
View File
@@ -43,3 +43,6 @@ vite.config.ts.timestamp-*
flatpak-build/ flatpak-build/
flatpak-repo/ flatpak-repo/
.flatpak-builder/ .flatpak-builder/
# Local build temp
/.tmp/
+53 -6
View File
@@ -12,11 +12,11 @@
# QBZ # QBZ
QBZ is a free and open source (FOSS) Qobuz client for Linux with native, high-fidelity playback. It is a real desktop application, not a web wrapper, so it can use DAC passthrough, preserve hi-res sample rates end-to-end, and deliver bit-perfect audio. QBZ is a free and open source (FOSS) Qobuz client for Linux with native, high-fidelity playback. It is a real desktop application, not a web wrapper, so it can use DAC passthrough, switch sample rates per track, and deliver bit-perfect audio.
## Why QBZ ## Why QBZ
Browsers cap audio output around 48 kHz, while Qobuz streams up to 192 kHz. QBZ uses a native playback pipeline with direct device control so your system and DAC receive the original resolution, with caching and system integrations that wrappers cannot provide. Browsers cap audio output around 48 kHz, while Qobuz streams up to 192 kHz. QBZ uses a native playback pipeline with direct device control, exclusive mode, and no forced resampling so your system and DAC receive the original resolution, with caching and system integrations that wrappers cannot provide.
## Installation ## Installation
@@ -37,11 +37,32 @@ paru -S qbz-bin
flatpak install ./QBZ.flatpak flatpak install ./QBZ.flatpak
``` ```
### AppImage / Tarball ### AppImage
Download the latest release from the [Releases](https://github.com/vicrodh/qbz/releases) page. Download the latest release from the [Releases](https://github.com/vicrodh/qbz/releases) page.
> **Note:** Pre-built binaries include all API integrations (Last.fm, Discogs, Spotify, Tidal) ready to use. If you build from source, you'll need to provide your own API keys. ```bash
chmod +x QBZ.AppImage
./QBZ.AppImage
```
### DEB (Debian/Ubuntu/Mint/Pop!_OS/Zorin)
Download the `.deb` from [Releases](https://github.com/vicrodh/qbz/releases).
```bash
sudo apt install ./qbz_*.deb
```
### RPM (Fedora/openSUSE/RHEL-based)
Download the `.rpm` from [Releases](https://github.com/vicrodh/qbz/releases).
```bash
sudo dnf install ./qbz-*.rpm
```
> **Note:** Pre-built binaries include all API integrations (Last.fm, Discogs, Spotify, Apple Music, Tidal, Deezer) ready to use. If you build from source, you'll need to provide your own API keys.
## Screenshots ## Screenshots
@@ -54,7 +75,8 @@ Coming soon.
- Native decoding for FLAC, MP3, AAC, and ALAC with real-time playback state updates. - Native decoding for FLAC, MP3, AAC, and ALAC with real-time playback state updates.
- Quality selection with automatic fallback across Qobuz tiers. - Quality selection with automatic fallback across Qobuz tiers.
- Audio device enumeration and per-device output selection. - Audio device enumeration and per-device output selection.
- DAC passthrough mode for bit-perfect playback. - Exclusive mode and DAC passthrough for bit-perfect playback.
- Preserve original sample rates end-to-end where supported.
- Gapless-ready playback pipeline with precise position tracking. - Gapless-ready playback pipeline with precise position tracking.
### Queue and Library ### Queue and Library
@@ -62,9 +84,12 @@ Coming soon.
- In-memory audio cache with LRU eviction and next-track prefetching. - In-memory audio cache with LRU eviction and next-track prefetching.
- Favorites and playlists from your Qobuz account. - Favorites and playlists from your Qobuz account.
- Local library backend: directory scanning, metadata extraction, CUE sheet parsing, and SQLite indexing. - Local library backend: directory scanning, metadata extraction, CUE sheet parsing, and SQLite indexing.
- Grid and list views with search, A-Z index, and grouping by artist or album.
- Multi-disc album grouping with disc headers in album views.
- Local artwork detection (folder and embedded) with Discogs fallback.
### Playlist Import ### Playlist Import
- Import playlists from Spotify and Tidal into your Qobuz library. - Import public playlists from Spotify, Apple Music, Tidal, and Deezer into your Qobuz library.
- Automatic track matching with fuzzy search. - Automatic track matching with fuzzy search.
- Batch import with progress tracking. - Batch import with progress tracking.
@@ -93,6 +118,9 @@ Coming soon.
- API keys configuration for self-hosted builds. - API keys configuration for self-hosted builds.
- Theme and appearance options. - Theme and appearance options.
### Performance
- Low CPU usage in idle and playback with adaptive audio thread scheduling.
## Open Source ## Open Source
QBZ is MIT-licensed and fully open source. No telemetry, no lock-in, and no hidden services. Just a clean, transparent player built for Linux audio fans. QBZ is MIT-licensed and fully open source. No telemetry, no lock-in, and no hidden services. Just a clean, transparent player built for Linux audio fans.
@@ -139,6 +167,11 @@ npm run tauri build
### Environment Variables ### Environment Variables
API keys are only required when you build QBZ yourself. The app runs without them, but the corresponding features will be disabled.
<details>
<summary>API keys and integrations (optional)</summary>
When building from source, you need to provide your own API keys. Copy the example environment file: When building from source, you need to provide your own API keys. Copy the example environment file:
```bash ```bash
@@ -190,6 +223,7 @@ TIDAL_API_CLIENT_SECRET=your_client_secret
``` ```
> **Note:** All integrations are optional. The application will work without them, but the corresponding features will be disabled. > **Note:** All integrations are optional. The application will work without them, but the corresponding features will be disabled.
</details>
## Project Structure ## Project Structure
@@ -220,6 +254,19 @@ qbz/
Contributions are welcome! Please feel free to submit issues and pull requests. Contributions are welcome! Please feel free to submit issues and pull requests.
## macOS (Experimental)
QBZ is built for Linux first, but the codebase can compile on macOS in many cases. Expect missing integrations and bugs, especially around audio devices, exclusive mode, MPRIS, and platform-specific packaging.
If you want to try it:
```bash
npm install
npm run tauri dev
```
Please treat macOS support as best-effort and report issues with clear logs.
## License ## License
MIT MIT
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "qbz-nix", "name": "qbz-nix",
"version": "1.1.0", "version": "1.1.1",
"description": "Native Qobuz client for Linux with Hi-Fi audio support", "description": "Native Qobuz client for Linux with Hi-Fi audio support",
"type": "module", "type": "module",
"scripts": { "scripts": {
+1 -1
View File
@@ -1,6 +1,6 @@
[package] [package]
name = "qbz-nix" name = "qbz-nix"
version = "1.1.0" version = "1.1.1"
description = "Native Qobuz client for Linux with Hi-Fi audio support" description = "Native Qobuz client for Linux with Hi-Fi audio support"
authors = ["blitzkriegfc"] authors = ["blitzkriegfc"]
edition = "2021" edition = "2021"
+57 -1
View File
@@ -106,6 +106,62 @@ pub async fn play_track(
Ok(()) Ok(())
} }
/// Prefetch a track into the in-memory cache without starting playback
#[tauri::command]
pub async fn prefetch_track(
track_id: u64,
state: State<'_, AppState>,
download_cache: State<'_, DownloadCacheState>,
) -> Result<(), String> {
log::info!("Command: prefetch_track {}", track_id);
let cache = state.audio_cache.clone();
if cache.contains(track_id) {
log::info!("Track {} already in memory cache", track_id);
return Ok(());
}
if cache.is_fetching(track_id) {
log::info!("Track {} already being fetched", track_id);
return Ok(());
}
cache.mark_fetching(track_id);
let result = async {
// Check persistent download cache first
{
let db = download_cache.db.lock().await;
if let Ok(Some(file_path)) = db.get_file_path(track_id) {
let path = std::path::Path::new(&file_path);
if path.exists() {
log::info!("Prefetching track {} from download cache", track_id);
drop(db);
let audio_data = std::fs::read(path)
.map_err(|e| format!("Failed to read cached file: {}", e))?;
cache.insert(track_id, audio_data);
return Ok(());
}
}
}
let client = state.client.lock().await;
let stream_url = client
.get_stream_url_with_fallback(track_id, Quality::HiRes)
.await
.map_err(|e| format!("Failed to get stream URL: {}", e))?;
drop(client);
let audio_data = download_audio(&stream_url.url).await?;
cache.insert(track_id, audio_data);
Ok(())
}
.await;
cache.unmark_fetching(track_id);
result
}
/// Download audio from URL /// Download audio from URL
async fn download_audio(url: &str) -> Result<Vec<u8>, String> { async fn download_audio(url: &str) -> Result<Vec<u8>, String> {
use std::time::Duration; use std::time::Duration;
@@ -251,7 +307,7 @@ pub fn set_media_metadata(
duration_secs, duration_secs,
cover_url, cover_url,
); );
state.media_controls.set_playback(true); state.media_controls.set_playback_with_progress(true, 0);
Ok(()) Ok(())
} }
+17 -1
View File
@@ -163,6 +163,11 @@ pub fn run() {
log::error!("Failed to initialize tray icon: {}", e); log::error!("Failed to initialize tray icon: {}", e);
} }
// Initialize media controls (MPRIS) now that we have an AppHandle
app.state::<AppState>()
.media_controls
.init(app.handle().clone());
// Start background task to emit playback events // Start background task to emit playback events
let app_handle = app.handle().clone(); let app_handle = app.handle().clone();
let player_state = app.state::<AppState>().player.state.clone(); let player_state = app.state::<AppState>().player.state.clone();
@@ -204,6 +209,8 @@ pub fn run() {
|| (is_playing && position != last_position) || (is_playing && position != last_position)
); );
let should_update_mpris = should_emit || (track_id == 0 && last_track_id != 0);
if should_emit { if should_emit {
let event = player::PlaybackEvent { let event = player::PlaybackEvent {
is_playing, is_playing,
@@ -213,11 +220,19 @@ pub fn run() {
volume, volume,
}; };
let _ = app_handle.emit("playback:state", &event); let _ = app_handle.emit("playback:state", &event);
last_position = position; last_position = position;
last_is_playing = is_playing; last_is_playing = is_playing;
last_track_id = track_id; last_track_id = track_id;
} }
if should_update_mpris {
let media_controls = &app_handle.state::<AppState>().media_controls;
if track_id == 0 {
media_controls.set_stopped();
} else {
media_controls.set_playback_with_progress(is_playing, position);
}
}
} }
}); });
@@ -259,6 +274,7 @@ pub fn run() {
commands::get_similar_artists, commands::get_similar_artists,
// Playback commands // Playback commands
commands::play_track, commands::play_track,
commands::prefetch_track,
commands::pause_playback, commands::pause_playback,
commands::resume_playback, commands::resume_playback,
commands::stop_playback, commands::stop_playback,
+103 -11
View File
@@ -5,9 +5,14 @@
//! - Media key support //! - Media key support
//! - Now playing notifications //! - Now playing notifications
use souvlaki::{MediaControlEvent, MediaControls, MediaMetadata, MediaPlayback, PlatformConfig}; use souvlaki::{MediaControlEvent, MediaControls, MediaMetadata, MediaPlayback, PlatformConfig, SeekDirection};
use std::sync::{Arc, Mutex}; use std::sync::{
atomic::{AtomicBool, Ordering},
Arc, Mutex,
};
use std::thread; use std::thread;
use tauri::{AppHandle, Emitter, Manager};
use serde::Serialize;
/// Track metadata for media controls /// Track metadata for media controls
#[derive(Debug, Clone, Default)] #[derive(Debug, Clone, Default)]
@@ -22,13 +27,26 @@ pub struct TrackInfo {
/// Media controls manager /// Media controls manager
pub struct MediaControlsManager { pub struct MediaControlsManager {
controls: Arc<Mutex<Option<MediaControls>>>, controls: Arc<Mutex<Option<MediaControls>>>,
initialized: Arc<AtomicBool>,
} }
impl MediaControlsManager { impl MediaControlsManager {
/// Create a new media controls manager /// Create a new media controls manager
pub fn new() -> Self { pub fn new() -> Self {
let controls = Arc::new(Mutex::new(None)); let controls = Arc::new(Mutex::new(None));
let controls_clone = controls.clone(); Self {
controls,
initialized: Arc::new(AtomicBool::new(false)),
}
}
pub fn init(&self, app: AppHandle) {
if self.initialized.swap(true, Ordering::SeqCst) {
return;
}
let controls_clone = self.controls.clone();
let app_handle = app.clone();
// Initialize media controls in a separate thread // Initialize media controls in a separate thread
// (souvlaki requires a window handle on some platforms) // (souvlaki requires a window handle on some platforms)
@@ -41,11 +59,11 @@ impl MediaControlsManager {
match MediaControls::new(config) { match MediaControls::new(config) {
Ok(mut mc) => { Ok(mut mc) => {
// Set up event handler for media key presses
// For now, just log events - we'll wire them up later
if let Err(e) = mc.attach(move |event: MediaControlEvent| { if let Err(e) = mc.attach(move |event: MediaControlEvent| {
log::info!("Media control event: {:?}", event); log::info!("Media control event: {:?}", event);
// TODO: Wire these to player commands via Tauri events let payload = MediaControlPayload::from(event);
let _ = app_handle.emit("media:control", &payload);
}) { }) {
log::error!("Failed to attach media controls handler: {}", e); log::error!("Failed to attach media controls handler: {}", e);
return; return;
@@ -53,7 +71,6 @@ impl MediaControlsManager {
log::info!("Media controls initialized successfully (MPRIS)"); log::info!("Media controls initialized successfully (MPRIS)");
// Store the controls
if let Ok(mut guard) = controls_clone.lock() { if let Ok(mut guard) = controls_clone.lock() {
*guard = Some(mc); *guard = Some(mc);
} }
@@ -63,10 +80,6 @@ impl MediaControlsManager {
} }
} }
}); });
Self {
controls,
}
} }
/// Update the currently playing track metadata /// Update the currently playing track metadata
@@ -135,6 +148,85 @@ impl MediaControlsManager {
} }
} }
#[derive(Debug, Serialize)]
struct MediaControlPayload {
action: String,
direction: Option<String>,
offset_secs: Option<i64>,
position_secs: Option<u64>,
volume: Option<f64>,
}
impl From<MediaControlEvent> for MediaControlPayload {
fn from(event: MediaControlEvent) -> Self {
match event {
MediaControlEvent::Play => Self::action_only("play"),
MediaControlEvent::Pause => Self::action_only("pause"),
MediaControlEvent::Toggle => Self::action_only("toggle"),
MediaControlEvent::Next => Self::action_only("next"),
MediaControlEvent::Previous => Self::action_only("previous"),
MediaControlEvent::Stop => Self::action_only("stop"),
MediaControlEvent::Seek(direction) => Self {
action: "seek".to_string(),
direction: Some(direction_to_string(direction)),
offset_secs: None,
position_secs: None,
volume: None,
},
MediaControlEvent::SeekBy(direction, duration) => {
let offset = duration.as_secs() as i64;
let signed_offset = match direction {
SeekDirection::Forward => offset,
SeekDirection::Backward => -offset,
};
Self {
action: "seek_by".to_string(),
direction: Some(direction_to_string(direction)),
offset_secs: Some(signed_offset),
position_secs: None,
volume: None,
}
}
MediaControlEvent::SetPosition(position) => Self {
action: "set_position".to_string(),
direction: None,
offset_secs: None,
position_secs: Some(position.0.as_secs()),
volume: None,
},
MediaControlEvent::SetVolume(volume) => Self {
action: "set_volume".to_string(),
direction: None,
offset_secs: None,
position_secs: None,
volume: Some(volume),
},
MediaControlEvent::OpenUri(_) => Self::action_only("open_uri"),
MediaControlEvent::Raise => Self::action_only("raise"),
MediaControlEvent::Quit => Self::action_only("quit"),
}
}
}
impl MediaControlPayload {
fn action_only(action: &str) -> Self {
Self {
action: action.to_string(),
direction: None,
offset_secs: None,
position_secs: None,
volume: None,
}
}
}
fn direction_to_string(direction: SeekDirection) -> String {
match direction {
SeekDirection::Forward => "forward".to_string(),
SeekDirection::Backward => "backward".to_string(),
}
}
impl Default for MediaControlsManager { impl Default for MediaControlsManager {
fn default() -> Self { fn default() -> Self {
Self::new() Self::new()
+1 -1
View File
@@ -1,7 +1,7 @@
{ {
"$schema": "https://schema.tauri.app/config/2", "$schema": "https://schema.tauri.app/config/2",
"productName": "QBZ", "productName": "QBZ",
"version": "1.1.0", "version": "1.1.1",
"identifier": "com.blitzkriegfc.qbz", "identifier": "com.blitzkriegfc.qbz",
"build": { "build": {
"beforeDevCommand": "npm run dev", "beforeDevCommand": "npm run dev",
+27 -4
View File
@@ -14,6 +14,8 @@ import {
setCurrentTrack, setCurrentTrack,
setIsPlaying, setIsPlaying,
setIsFavorite, setIsFavorite,
getCurrentTrack,
waitForPlaybackStart,
type PlayingTrack type PlayingTrack
} from '$lib/stores/playerStore'; } from '$lib/stores/playerStore';
import { syncQueueState } from '$lib/stores/queueStore'; import { syncQueueState } from '$lib/stores/queueStore';
@@ -31,6 +33,7 @@ import {
export interface PlayTrackOptions { export interface PlayTrackOptions {
isLocal?: boolean; isLocal?: boolean;
showLoadingToast?: boolean; showLoadingToast?: boolean;
showSuccessToast?: boolean;
} }
export interface MediaMetadata { export interface MediaMetadata {
@@ -63,7 +66,9 @@ export async function playTrack(
track: PlayingTrack, track: PlayingTrack,
options: PlayTrackOptions = {} options: PlayTrackOptions = {}
): Promise<boolean> { ): Promise<boolean> {
const { isLocal = false, showLoadingToast = true } = options; const { isLocal = false, showLoadingToast = true, showSuccessToast = true } = options;
const shouldAwaitPlayback = showLoadingToast && !isCasting();
const playbackStartTimeoutMs = 25000;
// Set current track in store // Set current track in store
setCurrentTrack(track); setCurrentTrack(track);
@@ -92,10 +97,28 @@ export async function playTrack(
} }
} }
// Dismiss buffering toast and show success
dismissBuffering();
setIsPlaying(true); setIsPlaying(true);
showToast(`Playing: ${track.title}`, 'success');
if (shouldAwaitPlayback) {
try {
await waitForPlaybackStart(track.id, playbackStartTimeoutMs);
} catch (waitErr) {
if (getCurrentTrack()?.id !== track.id) {
return true;
}
dismissBuffering();
setIsPlaying(false);
showToast('Audio output recovery failed. Please restart QBZ or check your audio device.', 'error');
return false;
}
}
if (getCurrentTrack()?.id === track.id) {
dismissBuffering();
if (showSuccessToast) {
showToast(`Playing: ${track.title}`, 'success');
}
}
// Log play event for recommendations (fire-and-forget) // Log play event for recommendations (fire-and-forget)
if (!isLocal) { if (!isLocal) {
+90 -2
View File
@@ -15,6 +15,7 @@ import {
castSetVolume, castSetVolume,
castStop castStop
} from '$lib/stores/castStore'; } from '$lib/stores/castStore';
import { showToast, dismissBuffering } from '$lib/stores/toastStore';
// ============ Types ============ // ============ Types ============
@@ -59,12 +60,19 @@ let currentTime = 0;
let duration = 0; let duration = 0;
let volume = 75; let volume = 75;
let isFavorite = false; let isFavorite = false;
let loadedTrackId: number | null = null;
// Event listener state (replaces polling) // Event listener state (replaces polling)
let eventUnlisten: UnlistenFn | null = null; let eventUnlisten: UnlistenFn | null = null;
let isAdvancingTrack = false; let isAdvancingTrack = false;
let isSkipping = false; let isSkipping = false;
let queueEnded = false; let queueEnded = false;
type PlaybackStartWaiter = {
resolve: () => void;
reject: (err: Error) => void;
timeout: ReturnType<typeof setTimeout>;
};
const playbackStartWaiters = new Map<number, PlaybackStartWaiter>();
// Callbacks for track advancement (set by consumer) // Callbacks for track advancement (set by consumer)
let onTrackEnded: (() => Promise<void>) | null = null; let onTrackEnded: (() => Promise<void>) | null = null;
@@ -151,6 +159,7 @@ export function getPlayerState(): PlayerState {
*/ */
export function setCurrentTrack(track: PlayingTrack | null): void { export function setCurrentTrack(track: PlayingTrack | null): void {
currentTrack = track; currentTrack = track;
loadedTrackId = null;
if (track) { if (track) {
duration = track.duration; duration = track.duration;
currentTime = 0; currentTime = 0;
@@ -235,9 +244,12 @@ export async function togglePlay(): Promise<void> {
console.log('[Player] Loading restored track:', pendingSessionRestore.trackId); console.log('[Player] Loading restored track:', pendingSessionRestore.trackId);
const savedPosition = pendingSessionRestore.position; const savedPosition = pendingSessionRestore.position;
pendingSessionRestore = null; // Clear before loading pendingSessionRestore = null; // Clear before loading
const trackId = currentTrack.id;
showToast(currentTrack.title, 'buffering');
// Load the track from Qobuz // Load the track from Qobuz
await invoke('play_track', { trackId: currentTrack.id }); await invoke('play_track', { trackId });
// Seek to saved position after a short delay to let audio load // Seek to saved position after a short delay to let audio load
if (savedPosition > 0) { if (savedPosition > 0) {
@@ -250,8 +262,49 @@ export async function togglePlay(): Promise<void> {
} }
}, 500); }, 500);
} }
try {
await waitForPlaybackStart(trackId, 25000);
if (currentTrack?.id !== trackId) {
return;
}
dismissBuffering();
showToast(`Playing: ${currentTrack.title}`, 'success');
} catch (waitErr) {
if (currentTrack?.id !== trackId) {
return;
}
dismissBuffering();
isPlaying = false;
notifyListeners();
showToast('Audio output recovery failed. Please restart QBZ or check your audio device.', 'error');
return;
}
} else { } else {
await invoke('resume_playback'); if (!loadedTrackId || loadedTrackId !== currentTrack.id) {
const trackId = currentTrack.id;
showToast(currentTrack.title, 'buffering');
await invoke('play_track', { trackId });
try {
await waitForPlaybackStart(trackId, 25000);
if (currentTrack?.id !== trackId) {
return;
}
dismissBuffering();
showToast(`Playing: ${currentTrack.title}`, 'success');
} catch (waitErr) {
if (currentTrack?.id !== trackId) {
return;
}
dismissBuffering();
isPlaying = false;
notifyListeners();
showToast('Audio output recovery failed. Please restart QBZ or check your audio device.', 'error');
return;
}
} else {
await invoke('resume_playback');
}
} }
} else { } else {
await invoke('pause_playback'); await invoke('pause_playback');
@@ -326,6 +379,7 @@ export async function stop(): Promise<void> {
currentTrack = null; currentTrack = null;
currentTime = 0; currentTime = 0;
duration = 0; duration = 0;
loadedTrackId = null;
notifyListeners(); notifyListeners();
} catch (err) { } catch (err) {
console.error('Failed to stop playback:', err); console.error('Failed to stop playback:', err);
@@ -351,8 +405,20 @@ async function handlePlaybackEvent(event: PlaybackEvent): Promise<void> {
if (event.track_id === currentTrack.id) { if (event.track_id === currentTrack.id) {
currentTime = event.position; currentTime = event.position;
isPlaying = event.is_playing; isPlaying = event.is_playing;
if (event.is_playing) {
loadedTrackId = event.track_id;
}
notifyListeners(); notifyListeners();
if (event.is_playing) {
const waiter = playbackStartWaiters.get(event.track_id);
if (waiter) {
clearTimeout(waiter.timeout);
playbackStartWaiters.delete(event.track_id);
waiter.resolve();
}
}
// Check if track ended - auto-advance to next // Check if track ended - auto-advance to next
if ( if (
event.duration > 0 && event.duration > 0 &&
@@ -376,6 +442,28 @@ async function handlePlaybackEvent(event: PlaybackEvent): Promise<void> {
} }
} }
export function waitForPlaybackStart(trackId: number, timeoutMs: number): Promise<void> {
return new Promise((resolve, reject) => {
if (trackId <= 0) {
resolve();
return;
}
const existing = playbackStartWaiters.get(trackId);
if (existing) {
clearTimeout(existing.timeout);
playbackStartWaiters.delete(trackId);
}
const timeout = setTimeout(() => {
playbackStartWaiters.delete(trackId);
reject(new Error('playback_start_timeout'));
}, timeoutMs);
playbackStartWaiters.set(trackId, { resolve, reject, timeout });
});
}
/** /**
* Start listening for playback events from backend * Start listening for playback events from backend
*/ */
+110 -8
View File
@@ -118,6 +118,16 @@
type RepeatMode type RepeatMode
} from '$lib/stores/queueStore'; } from '$lib/stores/queueStore';
type MediaControlPayload = {
action: string;
direction?: 'forward' | 'backward';
offset_secs?: number;
position_secs?: number;
volume?: number;
};
const MEDIA_SEEK_FALLBACK_SECS = 10;
// Types // Types
import type { import type {
QobuzTrack, QobuzTrack,
@@ -995,9 +1005,10 @@
// If there was a track playing, restore it (paused) // If there was a track playing, restore it (paused)
if (session.current_index !== null && tracks[session.current_index]) { if (session.current_index !== null && tracks[session.current_index]) {
const track = tracks[session.current_index]; const track = tracks[session.current_index];
showToast(`Restored: ${track.title}`, 'info'); showToast(`Restoring: ${track.title}`, 'buffering');
// Fetch full track info from Qobuz to get albumId, artistId, and quality // Fetch full track info from Qobuz to get albumId, artistId, and quality
let restoredTrack: PlayingTrack | null = null;
try { try {
const fullTrack = await invoke<QobuzTrack>('get_track', { trackId: track.id }); const fullTrack = await invoke<QobuzTrack>('get_track', { trackId: track.id });
const artwork = fullTrack.album?.image?.large || fullTrack.album?.image?.thumbnail || track.artwork_url || ''; const artwork = fullTrack.album?.image?.large || fullTrack.album?.image?.thumbnail || track.artwork_url || '';
@@ -1005,7 +1016,7 @@
? `${fullTrack.maximum_bit_depth ?? 24}/${fullTrack.maximum_sampling_rate ?? 96}` ? `${fullTrack.maximum_bit_depth ?? 24}/${fullTrack.maximum_sampling_rate ?? 96}`
: 'CD'; : 'CD';
setCurrentTrack({ restoredTrack = {
id: track.id, id: track.id,
title: fullTrack.title || track.title, title: fullTrack.title || track.title,
artist: fullTrack.performer?.name || track.artist, artist: fullTrack.performer?.name || track.artist,
@@ -1017,14 +1028,14 @@
samplingRate: fullTrack.maximum_sampling_rate, samplingRate: fullTrack.maximum_sampling_rate,
albumId: fullTrack.album?.id, albumId: fullTrack.album?.id,
artistId: fullTrack.performer?.id, artistId: fullTrack.performer?.id,
}); };
} catch (fetchErr) { } catch (fetchErr) {
console.warn('[Session] Failed to fetch track details, using cached data:', fetchErr); console.warn('[Session] Failed to fetch track details, using cached data:', fetchErr);
// Fallback to cached data without albumId/artistId // Fallback to cached data without albumId/artistId
const quality = track.hires const quality = track.hires
? `${track.bit_depth ?? 24}/${track.sample_rate ? track.sample_rate / 1000 : 96}` ? `${track.bit_depth ?? 24}/${track.sample_rate ? track.sample_rate / 1000 : 96}`
: 'CD'; : 'CD';
setCurrentTrack({ restoredTrack = {
id: track.id, id: track.id,
title: track.title, title: track.title,
artist: track.artist, artist: track.artist,
@@ -1034,12 +1045,42 @@
quality, quality,
bitDepth: track.bit_depth ?? undefined, bitDepth: track.bit_depth ?? undefined,
samplingRate: track.sample_rate ?? undefined, samplingRate: track.sample_rate ?? undefined,
}); };
} }
// Mark that this track needs to be loaded when user presses play if (restoredTrack) {
setPendingSessionRestore(track.id, session.current_position_secs); setCurrentTrack(restoredTrack);
console.log(`[Session] Track ${track.id} pending load, will resume at ${session.current_position_secs}s`); }
const restoreTimeoutMs = 20000;
try {
await Promise.race([
invoke('prefetch_track', { trackId: track.id }),
new Promise((_, reject) => setTimeout(() => reject(new Error('restore_timeout')), restoreTimeoutMs))
]);
dismissBuffering();
showToast(`Restored: ${track.title}`, 'info');
if (session.was_playing && restoredTrack) {
await playTrack(restoredTrack, { showLoadingToast: false, showSuccessToast: false });
if (session.current_position_secs > 0) {
setTimeout(async () => {
try {
await invoke('seek', { position: session.current_position_secs });
} catch (seekErr) {
console.error('[Session] Failed to seek on restore:', seekErr);
}
}, 500);
}
} else {
setPendingSessionRestore(track.id, session.current_position_secs);
console.log(`[Session] Track ${track.id} pending load, will resume at ${session.current_position_secs}s`);
}
} catch (restoreErr) {
dismissBuffering();
showToast('Restore failed. Please restart QBZ or check your audio device.', 'error');
setPendingSessionRestore(track.id, session.current_position_secs);
}
} }
console.log('[Session] Session restored successfully'); console.log('[Session] Session restored successfully');
@@ -1352,6 +1393,7 @@
let unlistenTrayPlayPause: UnlistenFn | null = null; let unlistenTrayPlayPause: UnlistenFn | null = null;
let unlistenTrayNext: UnlistenFn | null = null; let unlistenTrayNext: UnlistenFn | null = null;
let unlistenTrayPrevious: UnlistenFn | null = null; let unlistenTrayPrevious: UnlistenFn | null = null;
let unlistenMediaControls: UnlistenFn | null = null;
(async () => { (async () => {
unlistenTrayPlayPause = await listen('tray:play_pause', () => { unlistenTrayPlayPause = await listen('tray:play_pause', () => {
@@ -1366,6 +1408,65 @@
console.log('[Tray] Previous'); console.log('[Tray] Previous');
await handleSkipBack(); await handleSkipBack();
}); });
unlistenMediaControls = await listen('media:control', async (event) => {
const payload = event.payload as MediaControlPayload;
if (!payload?.action) return;
const playerState = getPlayerState();
switch (payload.action) {
case 'play':
if (!playerState.isPlaying) {
await togglePlay();
}
break;
case 'pause':
if (playerState.isPlaying) {
await togglePlay();
}
break;
case 'toggle':
await togglePlay();
break;
case 'next':
await handleSkipForward();
break;
case 'previous':
await handleSkipBack();
break;
case 'stop':
await stopPlayback();
break;
case 'seek': {
const direction = payload.direction === 'backward' ? -1 : 1;
const target = playerState.currentTime + direction * MEDIA_SEEK_FALLBACK_SECS;
await playerSeek(target);
break;
}
case 'seek_by': {
if (typeof payload.offset_secs === 'number') {
await playerSeek(playerState.currentTime + payload.offset_secs);
}
break;
}
case 'set_position': {
if (typeof payload.position_secs === 'number') {
await playerSeek(payload.position_secs);
}
break;
}
case 'set_volume': {
if (typeof payload.volume === 'number') {
const normalized = Math.max(0, Math.min(1, payload.volume));
await playerSetVolume(Math.round(normalized * 100));
}
break;
}
default:
break;
}
});
})(); })();
return () => { return () => {
@@ -1373,6 +1474,7 @@
unlistenTrayPlayPause?.(); unlistenTrayPlayPause?.();
unlistenTrayNext?.(); unlistenTrayNext?.();
unlistenTrayPrevious?.(); unlistenTrayPrevious?.();
unlistenMediaControls?.();
// Save session before cleanup // Save session before cleanup
saveSessionBeforeClose(); saveSessionBeforeClose();
cleanupBootstrap(); cleanupBootstrap();
+14 -2
View File
@@ -171,6 +171,10 @@
await exitMiniplayerMode(); await exitMiniplayerMode();
} }
function handleRestoreMouseDown(e: MouseEvent): void {
e.stopPropagation();
}
async function startDrag(): Promise<void> { async function startDrag(): Promise<void> {
try { try {
isDragging = true; isDragging = true;
@@ -183,6 +187,14 @@
} }
} }
function handleTopMouseDown(e: MouseEvent): void {
const target = e.target as HTMLElement | null;
if (target?.closest('button')) {
return;
}
void startDrag();
}
function handleOpenQueue(e: MouseEvent): void { function handleOpenQueue(e: MouseEvent): void {
e.stopPropagation(); e.stopPropagation();
console.log('[MiniPlayer] Queue button clicked, tracks:', queueCount); console.log('[MiniPlayer] Queue button clicked, tracks:', queueCount);
@@ -202,7 +214,7 @@
aria-label="MiniPlayer" aria-label="MiniPlayer"
> >
<!-- Top Section: Artwork + Info + Restore --> <!-- Top Section: Artwork + Info + Restore -->
<div class="top-section" onmousedown={startDrag}> <div class="top-section" onmousedown={handleTopMouseDown}>
<!-- Album Art (clickable for view modes) --> <!-- Album Art (clickable for view modes) -->
<button class="artwork-section" onclick={handleArtworkClick}> <button class="artwork-section" onclick={handleArtworkClick}>
{#if playerState.currentTrack?.artwork} {#if playerState.currentTrack?.artwork}
@@ -214,7 +226,7 @@
<!-- Track Info + Restore Button --> <!-- Track Info + Restore Button -->
<div class="info-section"> <div class="info-section">
<button class="restore-btn" onclick={handleRestore} title="Restore"> <button class="restore-btn" onclick={handleRestore} onmousedown={handleRestoreMouseDown} title="Restore">
<Maximize2 size={14} /> <Maximize2 size={14} />
</button> </button>
<div class="track-info"> <div class="track-info">