fix: restore playback buffering and mpris controls
This commit is contained in:
1 parent
3e3cc4746d
commit
a86dc5bcba
12 files changed
+473
-34
No files matched your search
@@ -43,3 +43,6 @@ vite.config.ts.timestamp-*
|
||||
flatpak-build/
|
||||
flatpak-repo/
|
||||
.flatpak-builder/
|
||||
|
||||
# Local build temp
|
||||
/.tmp/
|
||||
@@ -12,11 +12,11 @@
|
||||
|
||||
# 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
|
||||
|
||||
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
|
||||
|
||||
@@ -37,11 +37,32 @@ paru -S qbz-bin
|
||||
flatpak install ./QBZ.flatpak
|
||||
```
|
||||
|
||||
### AppImage / Tarball
|
||||
### AppImage
|
||||
|
||||
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
|
||||
|
||||
@@ -54,7 +75,8 @@ Coming soon.
|
||||
- Native decoding for FLAC, MP3, AAC, and ALAC with real-time playback state updates.
|
||||
- Quality selection with automatic fallback across Qobuz tiers.
|
||||
- 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.
|
||||
|
||||
### Queue and Library
|
||||
@@ -62,9 +84,12 @@ Coming soon.
|
||||
- In-memory audio cache with LRU eviction and next-track prefetching.
|
||||
- Favorites and playlists from your Qobuz account.
|
||||
- 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
|
||||
- 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.
|
||||
- Batch import with progress tracking.
|
||||
|
||||
@@ -93,6 +118,9 @@ Coming soon.
|
||||
- API keys configuration for self-hosted builds.
|
||||
- Theme and appearance options.
|
||||
|
||||
### Performance
|
||||
- Low CPU usage in idle and playback with adaptive audio thread scheduling.
|
||||
|
||||
## 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.
|
||||
@@ -139,6 +167,11 @@ npm run tauri build
|
||||
|
||||
### 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:
|
||||
|
||||
```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.
|
||||
</details>
|
||||
|
||||
## Project Structure
|
||||
|
||||
@@ -220,6 +254,19 @@ qbz/
|
||||
|
||||
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
|
||||
|
||||
MIT
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "qbz-nix",
|
||||
"version": "1.1.0",
|
||||
"version": "1.1.1",
|
||||
"description": "Native Qobuz client for Linux with Hi-Fi audio support",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "qbz-nix"
|
||||
version = "1.1.0"
|
||||
version = "1.1.1"
|
||||
description = "Native Qobuz client for Linux with Hi-Fi audio support"
|
||||
authors = ["blitzkriegfc"]
|
||||
edition = "2021"
|
||||
|
||||
@@ -106,6 +106,62 @@ pub async fn play_track(
|
||||
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
|
||||
async fn download_audio(url: &str) -> Result<Vec<u8>, String> {
|
||||
use std::time::Duration;
|
||||
@@ -251,7 +307,7 @@ pub fn set_media_metadata(
|
||||
duration_secs,
|
||||
cover_url,
|
||||
);
|
||||
state.media_controls.set_playback(true);
|
||||
state.media_controls.set_playback_with_progress(true, 0);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
|
||||
+17
-1
@@ -163,6 +163,11 @@ pub fn run() {
|
||||
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
|
||||
let app_handle = app.handle().clone();
|
||||
let player_state = app.state::<AppState>().player.state.clone();
|
||||
@@ -204,6 +209,8 @@ pub fn run() {
|
||||
|| (is_playing && position != last_position)
|
||||
);
|
||||
|
||||
let should_update_mpris = should_emit || (track_id == 0 && last_track_id != 0);
|
||||
|
||||
if should_emit {
|
||||
let event = player::PlaybackEvent {
|
||||
is_playing,
|
||||
@@ -213,11 +220,19 @@ pub fn run() {
|
||||
volume,
|
||||
};
|
||||
let _ = app_handle.emit("playback:state", &event);
|
||||
|
||||
last_position = position;
|
||||
last_is_playing = is_playing;
|
||||
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,
|
||||
// Playback commands
|
||||
commands::play_track,
|
||||
commands::prefetch_track,
|
||||
commands::pause_playback,
|
||||
commands::resume_playback,
|
||||
commands::stop_playback,
|
||||
|
||||
@@ -5,9 +5,14 @@
|
||||
//! - Media key support
|
||||
//! - Now playing notifications
|
||||
|
||||
use souvlaki::{MediaControlEvent, MediaControls, MediaMetadata, MediaPlayback, PlatformConfig};
|
||||
use std::sync::{Arc, Mutex};
|
||||
use souvlaki::{MediaControlEvent, MediaControls, MediaMetadata, MediaPlayback, PlatformConfig, SeekDirection};
|
||||
use std::sync::{
|
||||
atomic::{AtomicBool, Ordering},
|
||||
Arc, Mutex,
|
||||
};
|
||||
use std::thread;
|
||||
use tauri::{AppHandle, Emitter, Manager};
|
||||
use serde::Serialize;
|
||||
|
||||
/// Track metadata for media controls
|
||||
#[derive(Debug, Clone, Default)]
|
||||
@@ -22,13 +27,26 @@ pub struct TrackInfo {
|
||||
/// Media controls manager
|
||||
pub struct MediaControlsManager {
|
||||
controls: Arc<Mutex<Option<MediaControls>>>,
|
||||
initialized: Arc<AtomicBool>,
|
||||
}
|
||||
|
||||
impl MediaControlsManager {
|
||||
/// Create a new media controls manager
|
||||
pub fn new() -> Self {
|
||||
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
|
||||
// (souvlaki requires a window handle on some platforms)
|
||||
@@ -41,11 +59,11 @@ impl MediaControlsManager {
|
||||
|
||||
match MediaControls::new(config) {
|
||||
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| {
|
||||
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);
|
||||
return;
|
||||
@@ -53,7 +71,6 @@ impl MediaControlsManager {
|
||||
|
||||
log::info!("Media controls initialized successfully (MPRIS)");
|
||||
|
||||
// Store the controls
|
||||
if let Ok(mut guard) = controls_clone.lock() {
|
||||
*guard = Some(mc);
|
||||
}
|
||||
@@ -63,10 +80,6 @@ impl MediaControlsManager {
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
Self {
|
||||
controls,
|
||||
}
|
||||
}
|
||||
|
||||
/// 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 {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"$schema": "https://schema.tauri.app/config/2",
|
||||
"productName": "QBZ",
|
||||
"version": "1.1.0",
|
||||
"version": "1.1.1",
|
||||
"identifier": "com.blitzkriegfc.qbz",
|
||||
"build": {
|
||||
"beforeDevCommand": "npm run dev",
|
||||
|
||||
@@ -14,6 +14,8 @@ import {
|
||||
setCurrentTrack,
|
||||
setIsPlaying,
|
||||
setIsFavorite,
|
||||
getCurrentTrack,
|
||||
waitForPlaybackStart,
|
||||
type PlayingTrack
|
||||
} from '$lib/stores/playerStore';
|
||||
import { syncQueueState } from '$lib/stores/queueStore';
|
||||
@@ -31,6 +33,7 @@ import {
|
||||
export interface PlayTrackOptions {
|
||||
isLocal?: boolean;
|
||||
showLoadingToast?: boolean;
|
||||
showSuccessToast?: boolean;
|
||||
}
|
||||
|
||||
export interface MediaMetadata {
|
||||
@@ -63,7 +66,9 @@ export async function playTrack(
|
||||
track: PlayingTrack,
|
||||
options: PlayTrackOptions = {}
|
||||
): 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
|
||||
setCurrentTrack(track);
|
||||
@@ -92,10 +97,28 @@ export async function playTrack(
|
||||
}
|
||||
}
|
||||
|
||||
// Dismiss buffering toast and show success
|
||||
dismissBuffering();
|
||||
setIsPlaying(true);
|
||||
|
||||
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)
|
||||
if (!isLocal) {
|
||||
|
||||
@@ -15,6 +15,7 @@ import {
|
||||
castSetVolume,
|
||||
castStop
|
||||
} from '$lib/stores/castStore';
|
||||
import { showToast, dismissBuffering } from '$lib/stores/toastStore';
|
||||
|
||||
// ============ Types ============
|
||||
|
||||
@@ -59,12 +60,19 @@ let currentTime = 0;
|
||||
let duration = 0;
|
||||
let volume = 75;
|
||||
let isFavorite = false;
|
||||
let loadedTrackId: number | null = null;
|
||||
|
||||
// Event listener state (replaces polling)
|
||||
let eventUnlisten: UnlistenFn | null = null;
|
||||
let isAdvancingTrack = false;
|
||||
let isSkipping = 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)
|
||||
let onTrackEnded: (() => Promise<void>) | null = null;
|
||||
@@ -151,6 +159,7 @@ export function getPlayerState(): PlayerState {
|
||||
*/
|
||||
export function setCurrentTrack(track: PlayingTrack | null): void {
|
||||
currentTrack = track;
|
||||
loadedTrackId = null;
|
||||
if (track) {
|
||||
duration = track.duration;
|
||||
currentTime = 0;
|
||||
@@ -235,9 +244,12 @@ export async function togglePlay(): Promise<void> {
|
||||
console.log('[Player] Loading restored track:', pendingSessionRestore.trackId);
|
||||
const savedPosition = pendingSessionRestore.position;
|
||||
pendingSessionRestore = null; // Clear before loading
|
||||
const trackId = currentTrack.id;
|
||||
|
||||
showToast(currentTrack.title, 'buffering');
|
||||
|
||||
// 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
|
||||
if (savedPosition > 0) {
|
||||
@@ -250,9 +262,50 @@ export async function togglePlay(): Promise<void> {
|
||||
}
|
||||
}, 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 {
|
||||
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 {
|
||||
await invoke('pause_playback');
|
||||
}
|
||||
@@ -326,6 +379,7 @@ export async function stop(): Promise<void> {
|
||||
currentTrack = null;
|
||||
currentTime = 0;
|
||||
duration = 0;
|
||||
loadedTrackId = null;
|
||||
notifyListeners();
|
||||
} catch (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) {
|
||||
currentTime = event.position;
|
||||
isPlaying = event.is_playing;
|
||||
if (event.is_playing) {
|
||||
loadedTrackId = event.track_id;
|
||||
}
|
||||
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
|
||||
if (
|
||||
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
|
||||
*/
|
||||
|
||||
+108
-6
@@ -118,6 +118,16 @@
|
||||
type RepeatMode
|
||||
} 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
|
||||
import type {
|
||||
QobuzTrack,
|
||||
@@ -995,9 +1005,10 @@
|
||||
// If there was a track playing, restore it (paused)
|
||||
if (session.current_index !== null && 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
|
||||
let restoredTrack: PlayingTrack | null = null;
|
||||
try {
|
||||
const fullTrack = await invoke<QobuzTrack>('get_track', { trackId: track.id });
|
||||
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}`
|
||||
: 'CD';
|
||||
|
||||
setCurrentTrack({
|
||||
restoredTrack = {
|
||||
id: track.id,
|
||||
title: fullTrack.title || track.title,
|
||||
artist: fullTrack.performer?.name || track.artist,
|
||||
@@ -1017,14 +1028,14 @@
|
||||
samplingRate: fullTrack.maximum_sampling_rate,
|
||||
albumId: fullTrack.album?.id,
|
||||
artistId: fullTrack.performer?.id,
|
||||
});
|
||||
};
|
||||
} catch (fetchErr) {
|
||||
console.warn('[Session] Failed to fetch track details, using cached data:', fetchErr);
|
||||
// Fallback to cached data without albumId/artistId
|
||||
const quality = track.hires
|
||||
? `${track.bit_depth ?? 24}/${track.sample_rate ? track.sample_rate / 1000 : 96}`
|
||||
: 'CD';
|
||||
setCurrentTrack({
|
||||
restoredTrack = {
|
||||
id: track.id,
|
||||
title: track.title,
|
||||
artist: track.artist,
|
||||
@@ -1034,13 +1045,43 @@
|
||||
quality,
|
||||
bitDepth: track.bit_depth ?? undefined,
|
||||
samplingRate: track.sample_rate ?? undefined,
|
||||
});
|
||||
};
|
||||
}
|
||||
|
||||
// Mark that this track needs to be loaded when user presses play
|
||||
if (restoredTrack) {
|
||||
setCurrentTrack(restoredTrack);
|
||||
}
|
||||
|
||||
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');
|
||||
}
|
||||
@@ -1352,6 +1393,7 @@
|
||||
let unlistenTrayPlayPause: UnlistenFn | null = null;
|
||||
let unlistenTrayNext: UnlistenFn | null = null;
|
||||
let unlistenTrayPrevious: UnlistenFn | null = null;
|
||||
let unlistenMediaControls: UnlistenFn | null = null;
|
||||
|
||||
(async () => {
|
||||
unlistenTrayPlayPause = await listen('tray:play_pause', () => {
|
||||
@@ -1366,6 +1408,65 @@
|
||||
console.log('[Tray] Previous');
|
||||
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 () => {
|
||||
@@ -1373,6 +1474,7 @@
|
||||
unlistenTrayPlayPause?.();
|
||||
unlistenTrayNext?.();
|
||||
unlistenTrayPrevious?.();
|
||||
unlistenMediaControls?.();
|
||||
// Save session before cleanup
|
||||
saveSessionBeforeClose();
|
||||
cleanupBootstrap();
|
||||
|
||||
@@ -171,6 +171,10 @@
|
||||
await exitMiniplayerMode();
|
||||
}
|
||||
|
||||
function handleRestoreMouseDown(e: MouseEvent): void {
|
||||
e.stopPropagation();
|
||||
}
|
||||
|
||||
async function startDrag(): Promise<void> {
|
||||
try {
|
||||
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 {
|
||||
e.stopPropagation();
|
||||
console.log('[MiniPlayer] Queue button clicked, tracks:', queueCount);
|
||||
@@ -202,7 +214,7 @@
|
||||
aria-label="MiniPlayer"
|
||||
>
|
||||
<!-- Top Section: Artwork + Info + Restore -->
|
||||
<div class="top-section" onmousedown={startDrag}>
|
||||
<div class="top-section" onmousedown={handleTopMouseDown}>
|
||||
<!-- Album Art (clickable for view modes) -->
|
||||
<button class="artwork-section" onclick={handleArtworkClick}>
|
||||
{#if playerState.currentTrack?.artwork}
|
||||
@@ -214,7 +226,7 @@
|
||||
|
||||
<!-- Track Info + Restore Button -->
|
||||
<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} />
|
||||
</button>
|
||||
<div class="track-info">
|
||||
|
||||
Reference in new issue
Block a user