feat: playback of liked tracks with audio engine, queue and player bar

- ym-api: Track/Stream models, liked tracks, signed download URLs (full MP3
  over AAC over previews, highest bitrate) and in-memory fetch
- Audio thread on rodio, driven by commands and reporting through an iced
  subscription; generation ids drop stale events
- Opens the default output with a buffer clamped to the device's range:
  rodio's 2048-frame default fails on Bluetooth headphones that cap at 1024
- Queue with shuffle, repeat off/all/one, back/advance and jump; player
  state machine with prefetch of the next track, replay from memory, and
  skipping unplayable tracks (stops after three in a row)
- Working player bar (seek, volume, mute, quality badge), queue drawer,
  Collection screen with a lazily built liked-tracks list
- audio_probe example lists and test-opens output devices
This commit is contained in:
Yuriy Panov committed 2026-10-15 14:38:33 +06:00
1 parent 43e8f86a5d
commit b73af1f870
20 files changed
+2141 -202

No files matched your search

+57 -3
View File
@@ -1,5 +1,8 @@
use crate::Result;
use std::sync::Arc;
use crate::auth::Credentials;
use crate::models::{Stream, Track, best_variant};
use crate::{Error, Result};
/// The signed-in user as the UI needs them.
#[derive(Debug, Clone, PartialEq, Eq)]
@@ -55,7 +58,7 @@ impl YmClient {
let inner = yamuse::Client::builder().token(&credentials.access_token).build()?;
let status = inner.refresh_account().await?;
let account = Account::from_status(status)
.ok_or_else(|| crate::Error::Unauthorized("account status has no user".into()))?;
.ok_or_else(|| Error::Unauthorized("account status has no user".into()))?;
Ok((Self { inner }, account))
}
@@ -64,11 +67,62 @@ impl YmClient {
Ok(Self { inner: yamuse::Client::anonymous()? })
}
/// The user's liked tracks, newest like first, with full metadata.
pub async fn liked_tracks(&self) -> Result<Vec<Track>> {
let list = self.inner.liked_tracks(None).await?;
let ids: Vec<String> = list
.tracks
.into_iter()
.filter_map(|short| {
let id = match short.id? {
yamuse::models::Id::Number(n) => n.to_string(),
yamuse::models::Id::Text(s) => s,
};
Some(match short.album_id {
Some(album) if !id.contains(':') => format!("{id}:{album}"),
_ => id,
})
})
.collect();
self.tracks(ids).await
}
/// Full metadata for `ids` (`"trackId"` or `"trackId:albumId"`), in the given order.
pub async fn tracks(&self, ids: Vec<String>) -> Result<Vec<Track>> {
if ids.is_empty() {
return Ok(Vec::new());
}
let tracks = self.inner.tracks(&ids).await?;
Ok(tracks.into_iter().filter_map(Track::from_yamuse).collect())
}
/// Resolves a signed, short-lived audio URL for a track.
pub async fn stream(&self, track_id: &str) -> Result<Stream> {
let variants = self.inner.track_download_info(track_id).await?;
let variant = best_variant(&variants)
.ok_or_else(|| Error::Api(format!("no playable variant for track {track_id}")))?;
let url = variant.direct_link(self.inner.transport()).await?;
Ok(Stream {
url,
codec: variant.codec.clone().unwrap_or_default(),
bitrate_kbps: variant.bitrate_in_kbps.unwrap_or(0).max(0) as u32,
preview: variant.preview.unwrap_or(false),
})
}
/// Downloads a whole stream into memory (a 320 kbps track is about 10 MB).
pub async fn fetch(&self, stream: &Stream) -> Result<Arc<[u8]>> {
let bytes = yamuse::download::Downloader::new(self.inner.transport(), [stream.url.clone()])
.to_bytes()
.await?;
Ok(bytes.into())
}
/// Re-reads the account, e.g. after a subscription may have changed.
pub async fn account(&self) -> Result<Account> {
let status = self.inner.refresh_account().await?;
Account::from_status(status)
.ok_or_else(|| crate::Error::Unauthorized("account status has no user".into()))
.ok_or_else(|| Error::Unauthorized("account status has no user".into()))
}
}
+2
View File
@@ -6,6 +6,8 @@
pub mod auth;
mod client;
mod error;
mod models;
pub use client::{Account, YmClient};
pub use models::{AlbumRef, ArtistRef, Stream, Track};
pub use error::{Error, Result};
+204
View File
@@ -0,0 +1,204 @@
//! The app-facing shapes of API objects. Converted from `yamuse` models,
//! keeping only what the UI uses and resolving every `Option` once, here.
use std::time::Duration;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ArtistRef {
pub id: Option<i64>,
pub name: String,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AlbumRef {
pub id: i64,
pub title: String,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Track {
/// Numeric track id as a string; user-uploaded tracks use non-numeric ids.
pub id: String,
pub title: String,
/// "Remastered 2011", "Live" and the like.
pub version: Option<String>,
pub artists: Vec<ArtistRef>,
pub album: Option<AlbumRef>,
pub duration: Duration,
/// `%%`-templated image uri; see [`Track::cover_url`].
cover_uri: Option<String>,
/// False for tracks removed from the catalogue or blocked in the region.
pub available: bool,
pub explicit: bool,
pub lyrics_available: bool,
}
impl Track {
pub(crate) fn from_yamuse(t: yamuse::models::Track) -> Option<Self> {
let id = match t.id? {
yamuse::models::Id::Number(n) => n.to_string(),
yamuse::models::Id::Text(s) if !s.is_empty() => s,
yamuse::models::Id::Text(_) => return None,
};
let album = t.albums.into_iter().find_map(|a| {
Some(AlbumRef { id: a.id?, title: a.title.unwrap_or_default() })
});
Some(Self {
id,
title: t.title.unwrap_or_else(|| "Untitled".into()),
version: t.version.filter(|v| !v.trim().is_empty()),
artists: t
.artists
.into_iter()
.filter_map(|a| {
Some(ArtistRef { id: a.id.and_then(|i| i.as_number()), name: a.name? })
})
.collect(),
album,
duration: Duration::from_millis(t.duration_ms.unwrap_or(0).max(0) as u64),
cover_uri: t.cover_uri.or(t.og_image),
available: t.available.unwrap_or(true),
explicit: t.explicit.unwrap_or(false)
|| t.content_warning.as_deref() == Some("explicit"),
lyrics_available: t.lyrics_available.unwrap_or(false),
})
}
/// Decodes a track from the API's JSON, e.g. a recorded fixture.
pub fn from_json(json: &str) -> crate::Result<Self> {
let raw = serde_json::from_str(json).map_err(|e| crate::Error::Api(e.to_string()))?;
Self::from_yamuse(raw).ok_or_else(|| crate::Error::Api("track has no id".into()))
}
/// "Artist A, Artist B", or "Unknown artist".
pub fn artist_line(&self) -> String {
if self.artists.is_empty() {
return "Unknown artist".into();
}
self.artists.iter().map(|a| a.name.as_str()).collect::<Vec<_>>().join(", ")
}
/// Title with its version: "Song (Live)".
pub fn full_title(&self) -> String {
match &self.version {
Some(v) => format!("{} ({v})", self.title),
None => self.title.clone(),
}
}
/// Absolute cover URL at `size`×`size` pixels.
pub fn cover_url(&self, size: u32) -> Option<String> {
let uri = self.cover_uri.as_deref()?;
Some(yamuse::models::normalize_image_url(uri, &format!("{size}x{size}")))
}
/// Two stable hues for placeholder art, derived from the album (or track) id.
pub fn hues(&self) -> (f32, f32) {
let seed = self.album.as_ref().map_or_else(
|| self.id.bytes().fold(7u64, |h, b| h.wrapping_mul(31).wrapping_add(u64::from(b))),
|a| a.id as u64,
);
((seed.wrapping_mul(47) % 360) as f32, (seed.wrapping_mul(131).wrapping_add(90) % 360) as f32)
}
}
/// Where a track's audio comes from.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Stream {
pub url: String,
/// "mp3" or "aac".
pub codec: String,
pub bitrate_kbps: u32,
/// True when only a 30-second preview is available (no Plus).
pub preview: bool,
}
impl Stream {
/// "MP3 320", shown in the player bar.
pub fn label(&self) -> String {
format!("{} {}", self.codec.to_ascii_uppercase(), self.bitrate_kbps)
}
}
/// Picks the variant to play: full tracks over previews, MP3 over AAC (MP3 seeks
/// reliably), then the highest bitrate.
pub(crate) fn best_variant(
variants: &[yamuse::models::DownloadInfo],
) -> Option<&yamuse::models::DownloadInfo> {
variants
.iter()
.filter(|v| v.download_info_url.is_some())
.filter(|v| matches!(v.codec.as_deref(), Some("mp3" | "aac")))
.max_by_key(|v| {
(
!v.preview.unwrap_or(false),
v.codec.as_deref() == Some("mp3"),
v.bitrate_in_kbps.unwrap_or(0),
)
})
}
#[cfg(test)]
mod tests {
use super::*;
fn track(json: &str) -> Track {
Track::from_yamuse(serde_json::from_str(json).unwrap()).unwrap()
}
#[test]
fn track_converts_with_artists_album_and_cover() {
let t = track(
r#"{"id":"12345","title":"Звезда по имени Солнце","durationMs":225000,
"artists":[{"id":1,"name":"Кино"}],
"albums":[{"id":77,"title":"Звезда по имени Солнце"}],
"coverUri":"avatars.yandex.net/get-music-content/x/%%","lyricsAvailable":true}"#,
);
assert_eq!(t.id, "12345");
assert_eq!(t.artist_line(), "Кино");
assert_eq!(t.album.as_ref().unwrap().id, 77);
assert_eq!(t.duration, Duration::from_secs(225));
assert_eq!(
t.cover_url(200).as_deref(),
Some("https://avatars.yandex.net/get-music-content/x/200x200")
);
assert!(t.available && t.lyrics_available && !t.explicit);
}
#[test]
fn numeric_ids_and_versions() {
let t = track(r#"{"id":42,"title":"Song","version":"Live","artists":[]}"#);
assert_eq!(t.id, "42");
assert_eq!(t.full_title(), "Song (Live)");
assert_eq!(t.artist_line(), "Unknown artist");
assert!(Track::from_yamuse(serde_json::from_str(r#"{"title":"no id"}"#).unwrap()).is_none());
}
#[test]
fn hues_are_stable_and_in_range() {
let a = track(r#"{"id":1,"albums":[{"id":5}]}"#);
let b = track(r#"{"id":2,"albums":[{"id":5}]}"#);
assert_eq!(a.hues(), b.hues(), "same album, same art");
let (h1, h2) = a.hues();
assert!((0.0..360.0).contains(&h1) && (0.0..360.0).contains(&h2));
}
#[test]
fn best_variant_prefers_full_mp3_at_top_bitrate() {
let v: Vec<yamuse::models::DownloadInfo> = serde_json::from_str(
r#"[{"codec":"aac","bitrateInKbps":256,"downloadInfoUrl":"a"},
{"codec":"mp3","bitrateInKbps":192,"downloadInfoUrl":"b"},
{"codec":"mp3","bitrateInKbps":320,"downloadInfoUrl":"c"},
{"codec":"mp3","bitrateInKbps":320,"downloadInfoUrl":"p","preview":true},
{"codec":"flac","bitrateInKbps":900,"downloadInfoUrl":"f"}]"#,
)
.unwrap();
assert_eq!(best_variant(&v).unwrap().download_info_url.as_deref(), Some("c"));
let previews: Vec<yamuse::models::DownloadInfo> = serde_json::from_str(
r#"[{"codec":"mp3","bitrateInKbps":128,"downloadInfoUrl":"p","preview":true}]"#,
)
.unwrap();
assert!(best_variant(&previews).unwrap().preview.unwrap());
assert!(best_variant(&[]).is_none());
}
}